@prunellejs/seo 0.1.1 → 0.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/llms.txt +12 -3
- package/package.json +2 -2
- package/src/check.ts +599 -0
- package/src/index.ts +170 -27
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Kaynooo
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/llms.txt
CHANGED
|
@@ -8,15 +8,15 @@
|
|
|
8
8
|
|
|
9
9
|
## Plugin Setup (`seo(options?)`)
|
|
10
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.
|
|
11
|
+
- `site`: public origin (`https://example.com`, inherits `PrunelleConfig.site`). Required for canonical links (the path, plus `?page=N` for a list page past the first; any other query is left out), absolute `og:image`, and `sitemap.xml`; a production start refuses without it.
|
|
12
12
|
- `name`: site name (`og:site_name` and fallback `<title>`).
|
|
13
13
|
- `titleTemplate`: e.g. `'%s | My App'` (skips wrapping if `<title>` already contains `name`).
|
|
14
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
15
|
- `image`, `imageAlt`: default `og:image`, `twitter:card` (`summary_large_image`), and `og:image:alt`.
|
|
16
16
|
- `locale`: default `og:locale`.
|
|
17
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`).
|
|
18
|
+
- `sitemap`: `boolean` (default `true`, emitted in `afterPrerender` as `/sitemap.xml` with `xhtml:link` alternates when `@prunellejs/i18n` is active; past 50,000 URLs it becomes a sitemap index over `sitemap-1.xml`, `sitemap-2.xml`, ...). `sitemapExclude`: `string[]`. `extraUrls`: `() => string[]`.
|
|
19
|
+
- `redirects`: `Record<fromPath, string | { to: string, status?: 301 | 302 | 307 | 308 }>` (mounted as `GET` routes, default `301`; a `--static` export writes them to `dist/_redirects` instead, and `prunelle build --static` adds the exact-path ones to its Caddy and nginx snippets).
|
|
20
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
21
|
- `manifest`: `{ name?, shortName?, description?, themeColor?, backgroundColor?, display?, startUrl? }` (emits `/manifest.webmanifest`).
|
|
22
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">`).
|
|
@@ -25,6 +25,15 @@
|
|
|
25
25
|
|
|
26
26
|
- `jsonLd(schema)` returns a branded `Html` value for `<Head>`: `<Head>{jsonLd({ '@type': 'Article', headline: title })}</Head>`.
|
|
27
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">`, and with `[seo/missing-image-file]` when a `seo({ image })` path names no file in `publicDir`.
|
|
36
|
+
|
|
28
37
|
## Snippet
|
|
29
38
|
|
|
30
39
|
```ts
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@prunellejs/seo",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.7.0",
|
|
4
4
|
"description": "SEO meta, JSON-LD, sitemap, redirects, and self-hosted fonts plugin for Prunelle",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"type": "module",
|
|
@@ -21,6 +21,6 @@
|
|
|
21
21
|
"directory": "packages/plugin-seo"
|
|
22
22
|
},
|
|
23
23
|
"peerDependencies": {
|
|
24
|
-
"prunelle": "^0.
|
|
24
|
+
"prunelle": "^0.7.0"
|
|
25
25
|
}
|
|
26
26
|
}
|
package/src/check.ts
ADDED
|
@@ -0,0 +1,599 @@
|
|
|
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
|
+
const REMOTE_URL_RE = /^(?:[a-z][a-z0-9+.-]*:|\/\/)/i
|
|
373
|
+
|
|
374
|
+
// A share image served by the app itself has to be a file of its public folder, or every preview of every page shows a broken image.
|
|
375
|
+
function checkImageFile(ctx: CheckPluginContext, image: string | undefined): void {
|
|
376
|
+
const path = image?.trim().split(/[?#]/)[0]
|
|
377
|
+
if (path === undefined || path === '' || ctx.publicDir === undefined || REMOTE_URL_RE.test(path))
|
|
378
|
+
return
|
|
379
|
+
const file = join(ctx.publicDir, decodeURIComponent(path.replace(/^\/+/, '')))
|
|
380
|
+
if (!existsSync(file))
|
|
381
|
+
ctx.warn(formatWarn('prunelle.config.ts', undefined, 0, 'missing-image-file', `seo({ image }) is "${image}", but ${relative(ctx.root, file)} does not exist, so share previews show no image`, `add the image to ${relative(ctx.root, ctx.publicDir) || '.'}/, or point \`image\` at a file there or at an absolute URL`))
|
|
382
|
+
}
|
|
383
|
+
|
|
384
|
+
function lastOwned(entries: readonly TextEntry[], file: string, code: string, fromLayout: boolean): OwnedEntry | undefined {
|
|
385
|
+
const last = entries[entries.length - 1]
|
|
386
|
+
return last === undefined ? undefined : { value: last.value, file, code, offset: last.offset, fromLayout }
|
|
387
|
+
}
|
|
388
|
+
|
|
389
|
+
function resolveEffectiveHead(
|
|
390
|
+
file: string,
|
|
391
|
+
code: string,
|
|
392
|
+
pageInfo: RouteHeadInfo,
|
|
393
|
+
layouts: readonly string[],
|
|
394
|
+
cache: Map<string, { code: string, info: RouteHeadInfo }>,
|
|
395
|
+
): { title: OwnedEntry | undefined, description: OwnedEntry | undefined, hasOgImage: boolean, noindex: { file: string, offset: number } | undefined } {
|
|
396
|
+
let title: OwnedEntry | undefined
|
|
397
|
+
let description: OwnedEntry | undefined
|
|
398
|
+
let hasOgImage = pageInfo.hasOgImage
|
|
399
|
+
let noindex: { file: string, offset: number } | undefined
|
|
400
|
+
|
|
401
|
+
for (const lf of layouts) {
|
|
402
|
+
let c = cache.get(lf)
|
|
403
|
+
if (c === undefined) {
|
|
404
|
+
const lCode = readFileSync(lf, 'utf8')
|
|
405
|
+
c = { code: lCode, info: extractRouteHead(stripCommentsPreserveOffsets(lCode)) }
|
|
406
|
+
cache.set(lf, c)
|
|
407
|
+
}
|
|
408
|
+
title = lastOwned(c.info.titles, lf, c.code, true) ?? title
|
|
409
|
+
description = lastOwned(c.info.descriptions, lf, c.code, true) ?? description
|
|
410
|
+
if (c.info.hasOgImage) hasOgImage = true
|
|
411
|
+
if (c.info.noindexOffset !== undefined) noindex = { file: lf, offset: c.info.noindexOffset }
|
|
412
|
+
}
|
|
413
|
+
title = lastOwned(pageInfo.titles, file, code, false) ?? title
|
|
414
|
+
description = lastOwned(pageInfo.descriptions, file, code, false) ?? description
|
|
415
|
+
if (pageInfo.noindexOffset !== undefined) noindex = { file, offset: pageInfo.noindexOffset }
|
|
416
|
+
return { title, description, hasOgImage, noindex }
|
|
417
|
+
}
|
|
418
|
+
|
|
419
|
+
function checkRouteTitle(ctx: CheckPluginContext, options: SeoPluginOptions, state: StaticState, relFile: string, routePath: string, code: string, pageInfo: RouteHeadInfo, title: OwnedEntry | undefined): void {
|
|
420
|
+
if (title === undefined) {
|
|
421
|
+
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`))
|
|
422
|
+
return
|
|
423
|
+
}
|
|
424
|
+
if (title.value === undefined) return
|
|
425
|
+
const rendered = applyTitleTemplate(title.value, options)
|
|
426
|
+
if (rendered.length > MAX_TITLE) {
|
|
427
|
+
const ownerRel = relPosix(ctx.root, title.file)
|
|
428
|
+
const key = `title:${ownerRel}:${title.offset}`
|
|
429
|
+
if (!title.fromLayout || !state.warnedLayouts.has(key)) {
|
|
430
|
+
state.warnedLayouts.add(key)
|
|
431
|
+
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`))
|
|
432
|
+
}
|
|
433
|
+
state.longTitleUrls.add(routePath)
|
|
434
|
+
}
|
|
435
|
+
const prev = state.seenTitles.get(rendered)
|
|
436
|
+
if (prev !== undefined) {
|
|
437
|
+
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>'))
|
|
438
|
+
state.dupTitles.add(rendered)
|
|
439
|
+
}
|
|
440
|
+
else {
|
|
441
|
+
state.seenTitles.set(rendered, { relFile, routePath })
|
|
442
|
+
}
|
|
443
|
+
}
|
|
444
|
+
|
|
445
|
+
function checkRouteDescription(ctx: CheckPluginContext, state: StaticState, fallbackDesc: boolean, relFile: string, routePath: string, code: string, pageInfo: RouteHeadInfo, description: OwnedEntry | undefined): void {
|
|
446
|
+
if (description === undefined) {
|
|
447
|
+
if (!fallbackDesc)
|
|
448
|
+
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()`'))
|
|
449
|
+
return
|
|
450
|
+
}
|
|
451
|
+
if (description.value === undefined) return
|
|
452
|
+
const desc = description.value
|
|
453
|
+
if (desc.length > MAX_DESC) {
|
|
454
|
+
const ownerRel = relPosix(ctx.root, description.file)
|
|
455
|
+
const key = `desc:${ownerRel}:${description.offset}`
|
|
456
|
+
if (!description.fromLayout || !state.warnedLayouts.has(key)) {
|
|
457
|
+
state.warnedLayouts.add(key)
|
|
458
|
+
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`))
|
|
459
|
+
}
|
|
460
|
+
state.longDescUrls.add(routePath)
|
|
461
|
+
}
|
|
462
|
+
const prev = state.seenDescs.get(desc)
|
|
463
|
+
if (prev !== undefined) {
|
|
464
|
+
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'))
|
|
465
|
+
state.dupDescs.add(desc)
|
|
466
|
+
}
|
|
467
|
+
else {
|
|
468
|
+
state.seenDescs.set(desc, { relFile, routePath })
|
|
469
|
+
}
|
|
470
|
+
}
|
|
471
|
+
|
|
472
|
+
function checkStaticRoutes(ctx: CheckPluginContext, options: SeoPluginOptions, siteConfigured: boolean, excluded: ReadonlySet<string>): StaticState {
|
|
473
|
+
const state: StaticState = {
|
|
474
|
+
longTitleUrls: new Set(), longDescUrls: new Set(), noindexUrls: new Set(),
|
|
475
|
+
dupTitles: new Set(), dupDescs: new Set(), warnedLayouts: new Set(),
|
|
476
|
+
seenTitles: new Map(), seenDescs: new Map(),
|
|
477
|
+
}
|
|
478
|
+
const layoutCache = new Map<string, { code: string, info: RouteHeadInfo }>()
|
|
479
|
+
const descOpt = options.description
|
|
480
|
+
const fallbackDesc = typeof descOpt === 'string' ? descOpt.trim().length > 0 : descOpt !== undefined && Object.values(descOpt).some(v => v.trim().length > 0)
|
|
481
|
+
const hasDefaultImage = Boolean(options.image?.trim())
|
|
482
|
+
|
|
483
|
+
for (const file of walkRouteFiles(ctx.routesDir)) {
|
|
484
|
+
if (basename(file).startsWith('_')) continue
|
|
485
|
+
const code = readFileSync(file, 'utf8')
|
|
486
|
+
const exports = scanExports(file, code)
|
|
487
|
+
if (exports === undefined || !exports.includes('default') || exports.includes('GET')) continue
|
|
488
|
+
const routePath = fileToRoutePath(ctx.routesDir, file)
|
|
489
|
+
if (isSkippedPath(routePath)) continue
|
|
490
|
+
|
|
491
|
+
const relFile = relPosix(ctx.root, file)
|
|
492
|
+
const stripped = stripCommentsPreserveOffsets(code)
|
|
493
|
+
const pageInfo = extractRouteHead(stripped)
|
|
494
|
+
const effective = resolveEffectiveHead(file, code, pageInfo, ancestorLayouts(ctx.routesDir, file), layoutCache)
|
|
495
|
+
|
|
496
|
+
checkRouteTitle(ctx, options, state, relFile, routePath, code, pageInfo, effective.title)
|
|
497
|
+
checkRouteDescription(ctx, state, fallbackDesc, relFile, routePath, code, pageInfo, effective.description)
|
|
498
|
+
|
|
499
|
+
const isDynamic = routePath.includes(':') || routePath.includes('*')
|
|
500
|
+
const hasPrerender = exports.includes('prerender') && PRERENDER_TRUE_RE.test(stripped)
|
|
501
|
+
if (effective.noindex !== undefined && options.sitemap !== false && (!isDynamic || hasPrerender) && !excluded.has(routePath)) {
|
|
502
|
+
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\``))
|
|
503
|
+
state.noindexUrls.add(routePath)
|
|
504
|
+
}
|
|
505
|
+
if (siteConfigured && !hasDefaultImage && !effective.hasOgImage)
|
|
506
|
+
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>'))
|
|
507
|
+
}
|
|
508
|
+
return state
|
|
509
|
+
}
|
|
510
|
+
|
|
511
|
+
function collectHtmlFiles(dir: string, skipTopDirs: boolean): string[] {
|
|
512
|
+
const out: string[] = []
|
|
513
|
+
const walk = (cur: string, top: boolean): void => {
|
|
514
|
+
for (const e of readdirSync(cur, { withFileTypes: true })) {
|
|
515
|
+
if (e.isDirectory() && !e.name.startsWith('.') && !(top && skipTopDirs && SKIP_PRERENDER_DIRS.has(e.name)))
|
|
516
|
+
walk(join(cur, e.name), false)
|
|
517
|
+
else if (e.isFile() && e.name.endsWith('.html'))
|
|
518
|
+
out.push(join(cur, e.name))
|
|
519
|
+
}
|
|
520
|
+
}
|
|
521
|
+
if (existsSync(dir)) walk(dir, true)
|
|
522
|
+
return out.sort()
|
|
523
|
+
}
|
|
524
|
+
|
|
525
|
+
function htmlFileToUrl(htmlRoot: string, file: string): string {
|
|
526
|
+
const rel = relPosix(htmlRoot, file)
|
|
527
|
+
if (rel === 'index.html') return '/'
|
|
528
|
+
if (rel.endsWith('/index.html')) return `/${rel.slice(0, -11)}`
|
|
529
|
+
return rel === '404.html' || rel === '500.html' ? `/${rel.slice(0, -5)}` : `/${rel}`
|
|
530
|
+
}
|
|
531
|
+
|
|
532
|
+
function parsePrerenderedHead(html: string): { title: string | undefined, description: string | undefined, noindex: boolean } {
|
|
533
|
+
const head = HTML_HEAD_RE.exec(html)?.[1] ?? html
|
|
534
|
+
const rawTitle = HTML_TITLE_RE.exec(head)?.[1]
|
|
535
|
+
const title = rawTitle !== undefined ? decodeEntities(rawTitle).replace(/\s+/g, ' ').trim() || undefined : undefined
|
|
536
|
+
let description: string | undefined
|
|
537
|
+
let noindex = false
|
|
538
|
+
HTML_META_RE.lastIndex = 0
|
|
539
|
+
for (let m = HTML_META_RE.exec(head); m !== null; m = HTML_META_RE.exec(head)) {
|
|
540
|
+
const attrs = new Map<string, string>()
|
|
541
|
+
HTML_ATTR_RE.lastIndex = 0
|
|
542
|
+
for (let am = HTML_ATTR_RE.exec(m[0]); am !== null; am = HTML_ATTR_RE.exec(m[0]))
|
|
543
|
+
attrs.set(am[1]!.toLowerCase(), decodeEntities(am[2] ?? am[3] ?? am[4] ?? ''))
|
|
544
|
+
const name = attrs.get('name')?.trim().toLowerCase()
|
|
545
|
+
const content = attrs.get('content')?.trim()
|
|
546
|
+
if (name === 'description' && content) description = content
|
|
547
|
+
else if (name === 'robots' && content && NOINDEX_RE.test(content)) noindex = true
|
|
548
|
+
}
|
|
549
|
+
return { title, description, noindex }
|
|
550
|
+
}
|
|
551
|
+
|
|
552
|
+
function checkPrerenderedHtml(ctx: CheckPluginContext, options: SeoPluginOptions, excluded: ReadonlySet<string>, state: StaticState): void {
|
|
553
|
+
const outDir = getAppContext()?.outDir ?? join(ctx.root, 'dist')
|
|
554
|
+
const prerenderDir = join(outDir, 'prerendered')
|
|
555
|
+
const htmlRoot = existsSync(prerenderDir) ? prerenderDir : (existsSync(join(outDir, '.prunelle-output')) || existsSync(join(outDir, 'index.html'))) ? outDir : undefined
|
|
556
|
+
if (htmlRoot === undefined) return
|
|
557
|
+
|
|
558
|
+
const seenTitles = new Map<string, string>()
|
|
559
|
+
const seenDescs = new Map<string, string>()
|
|
560
|
+
const publicDir = ctx.publicDir ?? join(ctx.root, 'public')
|
|
561
|
+
for (const file of collectHtmlFiles(htmlRoot, htmlRoot === outDir)) {
|
|
562
|
+
const url = htmlFileToUrl(htmlRoot, file)
|
|
563
|
+
if (isSkippedPath(url)) continue
|
|
564
|
+
const html = readFileSync(file)
|
|
565
|
+
// A static export copies public/ beside its pages: a file that is still byte for byte the app's own is no page of the app (#72).
|
|
566
|
+
const shipped = join(publicDir, relative(htmlRoot, file))
|
|
567
|
+
if (htmlRoot === outDir && existsSync(shipped) && readFileSync(shipped).equals(html)) continue
|
|
568
|
+
const relFile = relPosix(ctx.root, file)
|
|
569
|
+
const { title, description, noindex } = parsePrerenderedHead(html.toString('utf8'))
|
|
570
|
+
|
|
571
|
+
if (title !== undefined) {
|
|
572
|
+
if (title.length > MAX_TITLE && !state.longTitleUrls.has(url))
|
|
573
|
+
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`))
|
|
574
|
+
const prev = seenTitles.get(title)
|
|
575
|
+
if (prev !== undefined && !state.dupTitles.has(title))
|
|
576
|
+
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>'))
|
|
577
|
+
else if (prev === undefined) seenTitles.set(title, url)
|
|
578
|
+
}
|
|
579
|
+
if (description !== undefined) {
|
|
580
|
+
if (description.length > MAX_DESC && !state.longDescUrls.has(url))
|
|
581
|
+
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`))
|
|
582
|
+
const prev = seenDescs.get(description)
|
|
583
|
+
if (prev !== undefined && !state.dupDescs.has(description))
|
|
584
|
+
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'))
|
|
585
|
+
else if (prev === undefined) seenDescs.set(description, url)
|
|
586
|
+
}
|
|
587
|
+
if (noindex && options.sitemap !== false && !excluded.has(url) && !state.noindexUrls.has(url))
|
|
588
|
+
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\``))
|
|
589
|
+
}
|
|
590
|
+
}
|
|
591
|
+
|
|
592
|
+
export function checkSeo(ctx: CheckPluginContext, options: SeoPluginOptions, activeSite: string | undefined): void {
|
|
593
|
+
const siteConfigured = hasConfiguredSite(ctx.root, options, activeSite)
|
|
594
|
+
const excluded = new Set((options.sitemapExclude ?? []).map(normalizePath))
|
|
595
|
+
checkConfigOptions(options, siteConfigured, ctx.warn)
|
|
596
|
+
checkImageFile(ctx, options.image)
|
|
597
|
+
const state = checkStaticRoutes(ctx, options, siteConfigured, excluded)
|
|
598
|
+
checkPrerenderedHtml(ctx, options, excluded, state)
|
|
599
|
+
}
|
package/src/index.ts
CHANGED
|
@@ -2,12 +2,13 @@
|
|
|
2
2
|
// Built strictly on the public PrunellePlugin API (server, build, transformHtml).
|
|
3
3
|
|
|
4
4
|
import type { Html } from 'prunelle'
|
|
5
|
-
import type { ActiveI18nConfig, BuildPluginContext, DocumentHeadContext, FinalizeBuildContext, PrunellePlugin, ServerPluginAPI } from 'prunelle/config'
|
|
5
|
+
import type { ActiveI18nConfig, BuildPluginContext, DocumentHeadContext, FinalizeBuildContext, PrunellePlugin, ServerPluginAPI, WebManifestIcon, WebManifestInfo } from 'prunelle/config'
|
|
6
6
|
import type { RequestContext } from 'prunelle/server'
|
|
7
7
|
import { existsSync, readFileSync } from 'node:fs'
|
|
8
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'
|
|
9
|
+
import { definePlugin, I18N_CONFIG_SERVICE, WEB_MANIFEST_SERVICE } from 'prunelle/config'
|
|
10
|
+
import { escAttr, escJson, escXml, raw } from 'prunelle/server'
|
|
11
|
+
import { checkSeo } from './check'
|
|
11
12
|
|
|
12
13
|
export interface FontEntry {
|
|
13
14
|
family: string
|
|
@@ -27,6 +28,7 @@ export interface ManifestOptions {
|
|
|
27
28
|
backgroundColor?: string | undefined
|
|
28
29
|
display?: 'standalone' | 'minimal-ui' | 'fullscreen' | 'browser' | undefined
|
|
29
30
|
startUrl?: string | undefined
|
|
31
|
+
icons?: WebManifestIcon[] | undefined
|
|
30
32
|
}
|
|
31
33
|
|
|
32
34
|
export type RedirectTarget = string | { to: string, status?: 301 | 302 | 307 | 308 | undefined }
|
|
@@ -51,7 +53,61 @@ export interface SeoPluginOptions {
|
|
|
51
53
|
|
|
52
54
|
const JS_SCANNER = new Bun.Transpiler({ loader: 'js' })
|
|
53
55
|
const CANONICAL_LINK_RE = /<link rel="canonical" href="[^"]*">/
|
|
56
|
+
// A list page past the first, the one query parameter a canonical link keeps: page 1 is the bare URL.
|
|
57
|
+
const LIST_PAGE_RE = /^(?:[2-9]|[1-9]\d+)$/
|
|
54
58
|
const ABSOLUTE_URL_RE = /^(?:https?:)?\/\//i
|
|
59
|
+
const META_TAG_RE = /<meta\b[^>]*>/gi
|
|
60
|
+
const ROBOTS_NAME_RE = /\bname\s*=\s*(?:"robots"|'robots'|robots(?:\s|>|\/|$))/i
|
|
61
|
+
const CONTENT_ATTR_RE = /\bcontent\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s>]+))/i
|
|
62
|
+
const NOINDEX_TOKEN_RE = /(?:^|[\s,])noindex(?:$|[\s,])/i
|
|
63
|
+
const HTML_ENTITY_RE = /&(?:amp|lt|gt|quot|apos|#39|#x27|#34|#38|#60|#62);/gi
|
|
64
|
+
const HTML_ENTITY_MAP: Record<string, string> = {
|
|
65
|
+
'&': '&',
|
|
66
|
+
'<': '<',
|
|
67
|
+
'>': '>',
|
|
68
|
+
'"': '"',
|
|
69
|
+
''': '\'',
|
|
70
|
+
''': '\'',
|
|
71
|
+
''': '\'',
|
|
72
|
+
'"': '"',
|
|
73
|
+
'&': '&',
|
|
74
|
+
'<': '<',
|
|
75
|
+
'>': '>',
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
function decodeBasicHtmlEntities(text: string): string {
|
|
79
|
+
return text.includes('&') ? text.replace(HTML_ENTITY_RE, m => HTML_ENTITY_MAP[m.toLowerCase()] ?? m) : text
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
function hasNoindexMeta(html: string): boolean {
|
|
83
|
+
const headEnd = html.toLowerCase().indexOf('</head>')
|
|
84
|
+
const slice = headEnd === -1 ? html : html.slice(0, headEnd)
|
|
85
|
+
META_TAG_RE.lastIndex = 0
|
|
86
|
+
let match = META_TAG_RE.exec(slice)
|
|
87
|
+
while (match !== null) {
|
|
88
|
+
const tag = match[0]
|
|
89
|
+
if (ROBOTS_NAME_RE.test(tag)) {
|
|
90
|
+
const contentMatch = CONTENT_ATTR_RE.exec(tag)
|
|
91
|
+
const content = contentMatch?.[1] ?? contentMatch?.[2] ?? contentMatch?.[3]
|
|
92
|
+
if (content !== undefined && NOINDEX_TOKEN_RE.test(content))
|
|
93
|
+
return true
|
|
94
|
+
}
|
|
95
|
+
match = META_TAG_RE.exec(slice)
|
|
96
|
+
}
|
|
97
|
+
return false
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
function isPrerenderedNoindex(baseDir: string, relHtml: string): boolean {
|
|
101
|
+
const abs = join(baseDir, relHtml)
|
|
102
|
+
if (!existsSync(abs))
|
|
103
|
+
return false
|
|
104
|
+
try {
|
|
105
|
+
return hasNoindexMeta(readFileSync(abs, 'utf8'))
|
|
106
|
+
}
|
|
107
|
+
catch {
|
|
108
|
+
return false
|
|
109
|
+
}
|
|
110
|
+
}
|
|
55
111
|
|
|
56
112
|
function serializeJsonLd(schema: Record<string, unknown>): string {
|
|
57
113
|
const payload = '@context' in schema ? schema : { '@context': 'https://schema.org', ...schema }
|
|
@@ -144,7 +200,7 @@ function readPngSize(bytes: Uint8Array): { width: number, height: number } | und
|
|
|
144
200
|
return width > 0 && height > 0 ? { width, height } : undefined
|
|
145
201
|
}
|
|
146
202
|
|
|
147
|
-
function emitFavicons(ctx: BuildPluginContext, favicon: string | string[]):
|
|
203
|
+
function emitFavicons(ctx: BuildPluginContext, favicon: string | string[]): WebManifestIcon[] {
|
|
148
204
|
const favicons = Array.isArray(favicon) ? favicon : [favicon]
|
|
149
205
|
const resolved: Array<{ abs: string, ext: string, bytes: Uint8Array }> = []
|
|
150
206
|
const extCounts = new Map<string, number>()
|
|
@@ -159,6 +215,7 @@ function emitFavicons(ctx: BuildPluginContext, favicon: string | string[]): void
|
|
|
159
215
|
}
|
|
160
216
|
|
|
161
217
|
const usedNames = new Set<string>()
|
|
218
|
+
const manifestIcons: WebManifestIcon[] = []
|
|
162
219
|
for (const item of resolved) {
|
|
163
220
|
const size = item.ext === '.png' ? readPngSize(item.bytes) : undefined
|
|
164
221
|
let outName: string
|
|
@@ -183,29 +240,74 @@ function emitFavicons(ctx: BuildPluginContext, favicon: string | string[]): void
|
|
|
183
240
|
const type = item.ext === '.svg' ? 'image/svg+xml' : item.ext === '.png' ? 'image/png' : 'image/x-icon'
|
|
184
241
|
const sizesAttr = size !== undefined ? ` sizes="${size.width}x${size.height}"` : ''
|
|
185
242
|
ctx.addHead(`<link rel="icon" href="${escAttr(href)}" type="${type}"${sizesAttr}>`)
|
|
243
|
+
if (item.ext === '.svg')
|
|
244
|
+
manifestIcons.push({ src: href, sizes: 'any', type })
|
|
245
|
+
else if (size !== undefined)
|
|
246
|
+
manifestIcons.push({ src: href, sizes: `${size.width}x${size.height}`, type })
|
|
247
|
+
}
|
|
248
|
+
return manifestIcons
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
function deriveFaviconIconsForCheck(root: string, favicon: string | string[] | undefined): WebManifestIcon[] {
|
|
252
|
+
if (favicon === undefined)
|
|
253
|
+
return []
|
|
254
|
+
const favicons = Array.isArray(favicon) ? favicon : [favicon]
|
|
255
|
+
const icons: WebManifestIcon[] = []
|
|
256
|
+
for (const fav of favicons) {
|
|
257
|
+
const abs = resolveFileOrPkg(root, fav)
|
|
258
|
+
if (abs === undefined)
|
|
259
|
+
continue
|
|
260
|
+
const ext = extname(abs).toLowerCase()
|
|
261
|
+
if (ext === '.svg') {
|
|
262
|
+
icons.push({ src: `/${basename(abs)}`, sizes: 'any', type: 'image/svg+xml' })
|
|
263
|
+
}
|
|
264
|
+
else if (ext === '.png') {
|
|
265
|
+
const size = readPngSize(new Uint8Array(readFileSync(abs)))
|
|
266
|
+
if (size !== undefined)
|
|
267
|
+
icons.push({ src: `/${basename(abs)}`, sizes: `${size.width}x${size.height}`, type: 'image/png' })
|
|
268
|
+
}
|
|
186
269
|
}
|
|
270
|
+
return icons
|
|
187
271
|
}
|
|
188
272
|
|
|
189
|
-
function
|
|
273
|
+
function buildManifestInfo(options: SeoPluginOptions, derivedIcons: readonly WebManifestIcon[]): WebManifestInfo | undefined {
|
|
274
|
+
const m = options.manifest
|
|
275
|
+
if (m === undefined)
|
|
276
|
+
return undefined
|
|
277
|
+
const icons = m.icons ?? (derivedIcons.length > 0 ? derivedIcons : undefined)
|
|
278
|
+
return {
|
|
279
|
+
name: m.name ?? options.name ?? '',
|
|
280
|
+
shortName: m.shortName ?? m.name ?? options.name ?? '',
|
|
281
|
+
startUrl: m.startUrl ?? '/',
|
|
282
|
+
display: m.display ?? 'standalone',
|
|
283
|
+
...(icons !== undefined ? { icons } : {}),
|
|
284
|
+
source: '@prunellejs/seo',
|
|
285
|
+
}
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
function emitManifest(ctx: BuildPluginContext, options: SeoPluginOptions, faviconIcons: readonly WebManifestIcon[]): void {
|
|
190
289
|
const m = options.manifest
|
|
191
290
|
if (m === undefined)
|
|
192
291
|
return
|
|
292
|
+
const info = buildManifestInfo(options, faviconIcons)!
|
|
193
293
|
const defaultDesc = typeof options.description === 'string'
|
|
194
294
|
? options.description
|
|
195
295
|
: (options.description ? Object.values(options.description)[0] : undefined)
|
|
196
296
|
const body = JSON.stringify({
|
|
197
|
-
name:
|
|
198
|
-
short_name:
|
|
297
|
+
name: info.name,
|
|
298
|
+
short_name: info.shortName,
|
|
199
299
|
description: m.description ?? defaultDesc,
|
|
200
|
-
start_url:
|
|
201
|
-
display:
|
|
300
|
+
start_url: info.startUrl,
|
|
301
|
+
display: info.display,
|
|
202
302
|
theme_color: m.themeColor,
|
|
203
303
|
background_color: m.backgroundColor,
|
|
304
|
+
...(info.icons !== undefined && info.icons.length > 0 ? { icons: info.icons } : {}),
|
|
204
305
|
}, null, 2)
|
|
205
306
|
const href = ctx.emitPublic('manifest.webmanifest', body)
|
|
206
307
|
ctx.addHead(`<link rel="manifest" href="${escAttr(href)}">`)
|
|
207
308
|
if (m.themeColor)
|
|
208
309
|
ctx.addHead(`<meta name="theme-color" content="${escAttr(m.themeColor)}">`)
|
|
310
|
+
ctx.provide(WEB_MANIFEST_SERVICE, info)
|
|
209
311
|
}
|
|
210
312
|
|
|
211
313
|
function emitFonts(ctx: BuildPluginContext, fonts: FontEntry[]): void {
|
|
@@ -242,13 +344,14 @@ function emitSitemap(
|
|
|
242
344
|
i18nCfg: ActiveI18nConfig | undefined,
|
|
243
345
|
): void {
|
|
244
346
|
const excluded = new Set(options.sitemapExclude ?? [])
|
|
347
|
+
const prerenderBaseDir = ctx.prerenderDir ?? ctx.outDir
|
|
245
348
|
const urls = new Set<string>()
|
|
246
349
|
for (const r of ctx.routes) {
|
|
247
350
|
if (isApiPath(r.path) || isErrorLikePath(r.path, i18nCfg) || isApiRouteFile(ctx.outDir, r.file))
|
|
248
351
|
continue
|
|
249
352
|
if (r.prerendered) {
|
|
250
|
-
for (const u of Object.
|
|
251
|
-
if (!excluded.has(u) && !isApiPath(u) && !isErrorLikePath(u, i18nCfg))
|
|
353
|
+
for (const [u, relHtml] of Object.entries(r.prerendered)) {
|
|
354
|
+
if (!excluded.has(u) && !isApiPath(u) && !isErrorLikePath(u, i18nCfg) && !isPrerenderedNoindex(prerenderBaseDir, relHtml))
|
|
252
355
|
urls.add(u)
|
|
253
356
|
}
|
|
254
357
|
}
|
|
@@ -292,20 +395,37 @@ function emitSitemap(
|
|
|
292
395
|
const { basePath } = stripLocaleFromPath(u, i18nCfg)
|
|
293
396
|
const group = byBase.get(basePath) ?? []
|
|
294
397
|
const alts = group
|
|
295
|
-
.map(a => `<xhtml:link rel="alternate" hreflang="${
|
|
398
|
+
.map(a => `<xhtml:link rel="alternate" hreflang="${escXml(a.locale)}" href="${escXml(`${site}${a.path === '/' ? '/' : a.path}`)}"/>`)
|
|
296
399
|
.join('')
|
|
297
|
-
return ` <url><loc>${
|
|
298
|
-
})
|
|
299
|
-
|
|
300
|
-
ctx.emitPublic('sitemap.xml', xml)
|
|
400
|
+
return ` <url><loc>${escXml(`${site}${u === '/' ? '/' : u}`)}</loc>${alts}</url>`
|
|
401
|
+
})
|
|
402
|
+
writeSitemaps(ctx, site, entries, ' xmlns:xhtml="http://www.w3.org/1999/xhtml"')
|
|
301
403
|
}
|
|
302
404
|
else {
|
|
303
|
-
|
|
304
|
-
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`
|
|
305
|
-
ctx.emitPublic('sitemap.xml', xml)
|
|
405
|
+
writeSitemaps(ctx, site, sortedUrls.map(u => ` <url><loc>${escXml(`${site}${u === '/' ? '/' : u}`)}</loc></url>`), '')
|
|
306
406
|
}
|
|
307
407
|
}
|
|
308
408
|
|
|
409
|
+
// The most URLs one sitemap file may hold (sitemaps.org).
|
|
410
|
+
const SITEMAP_MAX_URLS = 50_000
|
|
411
|
+
|
|
412
|
+
// One `sitemap.xml`, or past SITEMAP_MAX_URLS, numbered files under a `sitemap.xml` index so robots.txt keeps its link.
|
|
413
|
+
function writeSitemaps(ctx: FinalizeBuildContext, site: string, entries: readonly string[], namespaces: string): void {
|
|
414
|
+
const urlset = (part: readonly string[]): string =>
|
|
415
|
+
`<?xml version="1.0" encoding="UTF-8"?>\n<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"${namespaces}>\n${part.join('\n')}\n</urlset>\n`
|
|
416
|
+
if (entries.length <= SITEMAP_MAX_URLS) {
|
|
417
|
+
ctx.emitPublic('sitemap.xml', urlset(entries))
|
|
418
|
+
return
|
|
419
|
+
}
|
|
420
|
+
const index: string[] = []
|
|
421
|
+
for (let start = 0; start < entries.length; start += SITEMAP_MAX_URLS) {
|
|
422
|
+
const file = `sitemap-${index.length + 1}.xml`
|
|
423
|
+
ctx.emitPublic(file, urlset(entries.slice(start, start + SITEMAP_MAX_URLS)))
|
|
424
|
+
index.push(` <sitemap><loc>${escXml(`${site}/${file}`)}</loc></sitemap>`)
|
|
425
|
+
}
|
|
426
|
+
ctx.emitPublic('sitemap.xml', `<?xml version="1.0" encoding="UTF-8"?>\n<sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">\n${index.join('\n')}\n</sitemapindex>\n`)
|
|
427
|
+
}
|
|
428
|
+
|
|
309
429
|
function registerRedirects(
|
|
310
430
|
api: ServerPluginAPI,
|
|
311
431
|
redirects: Record<string, RedirectTarget>,
|
|
@@ -319,21 +439,32 @@ function registerRedirects(
|
|
|
319
439
|
const source = normalizePathname(from)
|
|
320
440
|
api.use((ctx, next) => {
|
|
321
441
|
const read = ctx.request.method === 'GET' || ctx.request.method === 'HEAD'
|
|
322
|
-
return read && normalizePathname(ctx.url.pathname) === source ? ctx.redirect(to, status) : next()
|
|
442
|
+
return read && normalizePathname(ctx.url.pathname) === source ? ctx.redirect(to, status, { external: true }) : next()
|
|
323
443
|
}, { scope: source })
|
|
324
444
|
continue
|
|
325
445
|
}
|
|
326
446
|
api.route('GET', from, (ctx) => {
|
|
327
447
|
if (i18nCfg === undefined)
|
|
328
|
-
return ctx.redirect(to, status)
|
|
448
|
+
return ctx.redirect(to, status, { external: true })
|
|
329
449
|
const locale = 'locale' in ctx.locals && typeof ctx.locals.locale === 'string'
|
|
330
450
|
? ctx.locals.locale
|
|
331
451
|
: i18nCfg.defaultLocale
|
|
332
|
-
return ctx.redirect(localizeRedirectTarget(to, locale, i18nCfg), status)
|
|
452
|
+
return ctx.redirect(localizeRedirectTarget(to, locale, i18nCfg), status, { external: true })
|
|
333
453
|
})
|
|
334
454
|
}
|
|
335
455
|
}
|
|
336
456
|
|
|
457
|
+
// A static export has no server to run the redirect routes, so `prunelle build --static` reads them from `_redirects` (Netlify and Cloudflare Pages read it too) and states them in its Caddy and nginx snippets. A source holding a pattern is left out, and one under i18n answers with the default locale.
|
|
458
|
+
function emitRedirectsFile(ctx: FinalizeBuildContext, redirects: Record<string, RedirectTarget>, i18nCfg: ActiveI18nConfig | undefined): void {
|
|
459
|
+
const lines = Object.entries(redirects).map(([from, target]) => {
|
|
460
|
+
const to = typeof target === 'string' ? target : target.to
|
|
461
|
+
const status = typeof target === 'string' ? 301 : (target.status ?? 301)
|
|
462
|
+
return `${from} ${i18nCfg === undefined ? to : localizeRedirectTarget(to, i18nCfg.defaultLocale, i18nCfg)} ${status}`
|
|
463
|
+
})
|
|
464
|
+
if (lines.length > 0)
|
|
465
|
+
ctx.emitPublic('_redirects', `${lines.join('\n')}\n`)
|
|
466
|
+
}
|
|
467
|
+
|
|
337
468
|
function resolveFallbackDescription(
|
|
338
469
|
description: SeoPluginOptions['description'],
|
|
339
470
|
ctx: RequestContext,
|
|
@@ -359,7 +490,9 @@ function applySeoHead(
|
|
|
359
490
|
): void {
|
|
360
491
|
if (options.titleTemplate || options.name) {
|
|
361
492
|
if (head.title !== undefined) {
|
|
362
|
-
|
|
493
|
+
const hasBrand = options.name !== undefined
|
|
494
|
+
&& (head.title.includes(options.name) || decodeBasicHtmlEntities(head.title).includes(options.name))
|
|
495
|
+
if (options.titleTemplate && !hasBrand) {
|
|
363
496
|
const safeTemplate = escAttr(options.titleTemplate)
|
|
364
497
|
head.title = safeTemplate.replace('%s', () => head.title!)
|
|
365
498
|
}
|
|
@@ -389,7 +522,9 @@ function applySeoHead(
|
|
|
389
522
|
}
|
|
390
523
|
|
|
391
524
|
if (activeSite && !head.headHtml.includes('rel="canonical"') && !errorRequests.has(ctx.request) && !isErrorLikePath(ctx.url.pathname, activeI18n)) {
|
|
392
|
-
const
|
|
525
|
+
const page = ctx.url.searchParams.get('page')
|
|
526
|
+
const pageQuery = page !== null && LIST_PAGE_RE.test(page) ? `?page=${page}` : ''
|
|
527
|
+
const canonical = escAttr(`${activeSite}${normalizePathname(ctx.url.pathname)}${pageQuery}`)
|
|
393
528
|
head.add(`<link rel="canonical" href="${canonical}">`)
|
|
394
529
|
seoCanonicalRequests.add(ctx.request)
|
|
395
530
|
}
|
|
@@ -415,6 +550,13 @@ export function seo(options: SeoPluginOptions = {}): PrunellePlugin {
|
|
|
415
550
|
: []
|
|
416
551
|
},
|
|
417
552
|
|
|
553
|
+
check(ctx) {
|
|
554
|
+
checkSeo(ctx, options, activeSite)
|
|
555
|
+
const manifestInfo = buildManifestInfo(options, options.manifest?.icons ? [] : deriveFaviconIconsForCheck(ctx.root, options.favicon))
|
|
556
|
+
if (manifestInfo !== undefined)
|
|
557
|
+
ctx.provide?.(WEB_MANIFEST_SERVICE, manifestInfo)
|
|
558
|
+
},
|
|
559
|
+
|
|
418
560
|
onError({ request }) {
|
|
419
561
|
errorRequests.add(request)
|
|
420
562
|
},
|
|
@@ -453,9 +595,8 @@ export function seo(options: SeoPluginOptions = {}): PrunellePlugin {
|
|
|
453
595
|
for (const schema of options.jsonLd)
|
|
454
596
|
ctx.addHead(serializeJsonLd(schema))
|
|
455
597
|
}
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
emitManifest(ctx, options)
|
|
598
|
+
const faviconIcons = options.favicon ? emitFavicons(ctx, options.favicon) : []
|
|
599
|
+
emitManifest(ctx, options, faviconIcons)
|
|
459
600
|
if (options.fonts && options.fonts.length > 0)
|
|
460
601
|
emitFonts(ctx, options.fonts)
|
|
461
602
|
},
|
|
@@ -465,6 +606,8 @@ export function seo(options: SeoPluginOptions = {}): PrunellePlugin {
|
|
|
465
606
|
const i18nCfg = ctx.inject<ActiveI18nConfig>(I18N_CONFIG_SERVICE) ?? activeI18n
|
|
466
607
|
if (site && options.sitemap !== false)
|
|
467
608
|
emitSitemap(ctx, site, options, i18nCfg)
|
|
609
|
+
if (ctx.isStatic && options.redirects !== undefined)
|
|
610
|
+
emitRedirectsFile(ctx, options.redirects, i18nCfg)
|
|
468
611
|
},
|
|
469
612
|
|
|
470
613
|
head(head, ctx) {
|