@prunellejs/seo 0.1.1 → 0.5.3
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 +9 -0
- package/package.json +2 -2
- package/src/check.ts +581 -0
- package/src/index.ts +64 -4
package/llms.txt
CHANGED
|
@@ -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">`.
|
|
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.5.3",
|
|
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.5.3"
|
|
25
25
|
}
|
|
26
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
CHANGED
|
@@ -8,6 +8,7 @@ import { existsSync, readFileSync } from 'node:fs'
|
|
|
8
8
|
import { basename, extname, join, resolve } from 'node:path'
|
|
9
9
|
import { definePlugin, I18N_CONFIG_SERVICE } from 'prunelle/config'
|
|
10
10
|
import { escAttr, escJson, raw } from 'prunelle/server'
|
|
11
|
+
import { checkSeo } from './check'
|
|
11
12
|
|
|
12
13
|
export interface FontEntry {
|
|
13
14
|
family: string
|
|
@@ -52,6 +53,58 @@ export interface SeoPluginOptions {
|
|
|
52
53
|
const JS_SCANNER = new Bun.Transpiler({ loader: 'js' })
|
|
53
54
|
const CANONICAL_LINK_RE = /<link rel="canonical" href="[^"]*">/
|
|
54
55
|
const ABSOLUTE_URL_RE = /^(?:https?:)?\/\//i
|
|
56
|
+
const META_TAG_RE = /<meta\b[^>]*>/gi
|
|
57
|
+
const ROBOTS_NAME_RE = /\bname\s*=\s*(?:"robots"|'robots'|robots(?:\s|>|\/|$))/i
|
|
58
|
+
const CONTENT_ATTR_RE = /\bcontent\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s>]+))/i
|
|
59
|
+
const NOINDEX_TOKEN_RE = /(?:^|[\s,])noindex(?:$|[\s,])/i
|
|
60
|
+
const HTML_ENTITY_RE = /&(?:amp|lt|gt|quot|apos|#39|#x27|#34|#38|#60|#62);/gi
|
|
61
|
+
const HTML_ENTITY_MAP: Record<string, string> = {
|
|
62
|
+
'&': '&',
|
|
63
|
+
'<': '<',
|
|
64
|
+
'>': '>',
|
|
65
|
+
'"': '"',
|
|
66
|
+
''': '\'',
|
|
67
|
+
''': '\'',
|
|
68
|
+
''': '\'',
|
|
69
|
+
'"': '"',
|
|
70
|
+
'&': '&',
|
|
71
|
+
'<': '<',
|
|
72
|
+
'>': '>',
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
function decodeBasicHtmlEntities(text: string): string {
|
|
76
|
+
return text.includes('&') ? text.replace(HTML_ENTITY_RE, m => HTML_ENTITY_MAP[m.toLowerCase()] ?? m) : text
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
function hasNoindexMeta(html: string): boolean {
|
|
80
|
+
const headEnd = html.toLowerCase().indexOf('</head>')
|
|
81
|
+
const slice = headEnd === -1 ? html : html.slice(0, headEnd)
|
|
82
|
+
META_TAG_RE.lastIndex = 0
|
|
83
|
+
let match = META_TAG_RE.exec(slice)
|
|
84
|
+
while (match !== null) {
|
|
85
|
+
const tag = match[0]
|
|
86
|
+
if (ROBOTS_NAME_RE.test(tag)) {
|
|
87
|
+
const contentMatch = CONTENT_ATTR_RE.exec(tag)
|
|
88
|
+
const content = contentMatch?.[1] ?? contentMatch?.[2] ?? contentMatch?.[3]
|
|
89
|
+
if (content !== undefined && NOINDEX_TOKEN_RE.test(content))
|
|
90
|
+
return true
|
|
91
|
+
}
|
|
92
|
+
match = META_TAG_RE.exec(slice)
|
|
93
|
+
}
|
|
94
|
+
return false
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
function isPrerenderedNoindex(baseDir: string, relHtml: string): boolean {
|
|
98
|
+
const abs = join(baseDir, relHtml)
|
|
99
|
+
if (!existsSync(abs))
|
|
100
|
+
return false
|
|
101
|
+
try {
|
|
102
|
+
return hasNoindexMeta(readFileSync(abs, 'utf8'))
|
|
103
|
+
}
|
|
104
|
+
catch {
|
|
105
|
+
return false
|
|
106
|
+
}
|
|
107
|
+
}
|
|
55
108
|
|
|
56
109
|
function serializeJsonLd(schema: Record<string, unknown>): string {
|
|
57
110
|
const payload = '@context' in schema ? schema : { '@context': 'https://schema.org', ...schema }
|
|
@@ -242,13 +295,14 @@ function emitSitemap(
|
|
|
242
295
|
i18nCfg: ActiveI18nConfig | undefined,
|
|
243
296
|
): void {
|
|
244
297
|
const excluded = new Set(options.sitemapExclude ?? [])
|
|
298
|
+
const prerenderBaseDir = ctx.prerenderDir ?? ctx.outDir
|
|
245
299
|
const urls = new Set<string>()
|
|
246
300
|
for (const r of ctx.routes) {
|
|
247
301
|
if (isApiPath(r.path) || isErrorLikePath(r.path, i18nCfg) || isApiRouteFile(ctx.outDir, r.file))
|
|
248
302
|
continue
|
|
249
303
|
if (r.prerendered) {
|
|
250
|
-
for (const u of Object.
|
|
251
|
-
if (!excluded.has(u) && !isApiPath(u) && !isErrorLikePath(u, i18nCfg))
|
|
304
|
+
for (const [u, relHtml] of Object.entries(r.prerendered)) {
|
|
305
|
+
if (!excluded.has(u) && !isApiPath(u) && !isErrorLikePath(u, i18nCfg) && !isPrerenderedNoindex(prerenderBaseDir, relHtml))
|
|
252
306
|
urls.add(u)
|
|
253
307
|
}
|
|
254
308
|
}
|
|
@@ -359,7 +413,9 @@ function applySeoHead(
|
|
|
359
413
|
): void {
|
|
360
414
|
if (options.titleTemplate || options.name) {
|
|
361
415
|
if (head.title !== undefined) {
|
|
362
|
-
|
|
416
|
+
const hasBrand = options.name !== undefined
|
|
417
|
+
&& (head.title.includes(options.name) || decodeBasicHtmlEntities(head.title).includes(options.name))
|
|
418
|
+
if (options.titleTemplate && !hasBrand) {
|
|
363
419
|
const safeTemplate = escAttr(options.titleTemplate)
|
|
364
420
|
head.title = safeTemplate.replace('%s', () => head.title!)
|
|
365
421
|
}
|
|
@@ -389,7 +445,7 @@ function applySeoHead(
|
|
|
389
445
|
}
|
|
390
446
|
|
|
391
447
|
if (activeSite && !head.headHtml.includes('rel="canonical"') && !errorRequests.has(ctx.request) && !isErrorLikePath(ctx.url.pathname, activeI18n)) {
|
|
392
|
-
const canonical = escAttr(`${activeSite}${ctx.url.pathname}`)
|
|
448
|
+
const canonical = escAttr(`${activeSite}${normalizePathname(ctx.url.pathname)}`)
|
|
393
449
|
head.add(`<link rel="canonical" href="${canonical}">`)
|
|
394
450
|
seoCanonicalRequests.add(ctx.request)
|
|
395
451
|
}
|
|
@@ -415,6 +471,10 @@ export function seo(options: SeoPluginOptions = {}): PrunellePlugin {
|
|
|
415
471
|
: []
|
|
416
472
|
},
|
|
417
473
|
|
|
474
|
+
check(ctx) {
|
|
475
|
+
checkSeo(ctx, options, activeSite)
|
|
476
|
+
},
|
|
477
|
+
|
|
418
478
|
onError({ request }) {
|
|
419
479
|
errorRequests.add(request)
|
|
420
480
|
},
|