@prunellejs/i18n 0.1.1 → 0.7.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/LICENSE +21 -0
- package/llms.txt +4 -1
- package/package.json +2 -2
- package/src/index.ts +200 -40
- package/src/routes.ts +172 -0
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
|
@@ -12,7 +12,8 @@
|
|
|
12
12
|
- `defaultLocale`: `string` (e.g. `'en'`).
|
|
13
13
|
- `messages`: `Record<locale, Record<key, string>>` (optional; falls back to `defaultLocale`, then returns `key`).
|
|
14
14
|
- `prefixDefault`: `boolean` (default `false`; when `true`, default locale is also prefixed as `/en/...`).
|
|
15
|
-
- `
|
|
15
|
+
- Options are checked when `i18n()` runs: an empty `locales`, a duplicate, a malformed tag (`en US`, `fr/ca`) or a `defaultLocale` outside `locales` throws `@prunellejs/i18n: ...` with the fix.
|
|
16
|
+
- `site`: optional public origin (inherits `PrunelleConfig.site`); when set, injects `<link rel="alternate" hreflang="...">` tags into `<head>`, plus `hreflang="x-default"` pointing at the default locale URL.
|
|
16
17
|
|
|
17
18
|
## Mounted Routes, Rewriting & `ctx.locals`
|
|
18
19
|
|
|
@@ -21,8 +22,10 @@
|
|
|
21
22
|
- `ctx.locals.t(key)`: translate string for active locale
|
|
22
23
|
- `ctx.locals.localize(path, targetLocale?)`: build localized path
|
|
23
24
|
- `ctx.locals.alternates()`: `Array<{ locale, href }>` for the current page
|
|
25
|
+
- One URL per page: with `prefixDefault: false`, `/en/about` (the default locale prefixed) answers 301 to `/about`; with `true`, an unprefixed page answers 302 to `/en/about`. Both keep the query, apply to GET and HEAD, and only to pages: plugin and API routes and 404s answer as they are.
|
|
24
26
|
- Mounted route: `GET /_i18n/locales` → `{ locales, defaultLocale, current }`.
|
|
25
27
|
- HTML & build integration:
|
|
28
|
+
- The link rewrite reads attributes: only `href` (single or double quotes) on an `<a>` is changed, never `data-href`, and a `>` inside another attribute value does not hide it.
|
|
26
29
|
- Sets `<html lang={locale}>` and `hreflang` links in `head()`.
|
|
27
30
|
- Prefixes internal `<a href="/...">` for non-default locales (`data-no-localize` opts a link out, e.g. language switchers; skips `/_pru/`, `/_i18n/`, already-prefixed paths).
|
|
28
31
|
- Expands `prerenderPaths` across all configured locales and shares `I18N_CONFIG_SERVICE` with `@prunellejs/seo` for multilingual `sitemap.xml`.
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@prunellejs/i18n",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.7.3",
|
|
4
4
|
"description": "Locale URL rewriting and dictionary internationalization plugin for Prunelle",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"type": "module",
|
|
@@ -21,6 +21,6 @@
|
|
|
21
21
|
"directory": "packages/plugin-i18n"
|
|
22
22
|
},
|
|
23
23
|
"peerDependencies": {
|
|
24
|
-
"prunelle": "^0.
|
|
24
|
+
"prunelle": "^0.7.3"
|
|
25
25
|
}
|
|
26
26
|
}
|
package/src/index.ts
CHANGED
|
@@ -3,8 +3,11 @@
|
|
|
3
3
|
// Implemented 100% through PrunellePlugin public hooks — zero i18n logic in @prunellejs/core.
|
|
4
4
|
|
|
5
5
|
import type { ActiveI18nConfig, PrunellePlugin } from 'prunelle/config'
|
|
6
|
+
import type { Middleware } from 'prunelle/server'
|
|
7
|
+
import type { CanonicalRouteIndex, I18nBuildData } from './routes'
|
|
6
8
|
import { definePlugin, I18N_CONFIG_SERVICE } from 'prunelle/config'
|
|
7
9
|
import { escAttr, isTrustedOrigin } from 'prunelle/server'
|
|
10
|
+
import { buildCanonicalRouteIndex, collectI18nBuildData, isCanonicalHtmlTarget, normalizePathname } from './routes'
|
|
8
11
|
|
|
9
12
|
declare module 'prunelle/server' {
|
|
10
13
|
interface PrunelleLocals {
|
|
@@ -25,7 +28,108 @@ export interface I18nOptions {
|
|
|
25
28
|
site?: string | undefined
|
|
26
29
|
}
|
|
27
30
|
|
|
28
|
-
const
|
|
31
|
+
const HTML_TOKEN_RE = /<(\/?)(pre|code|textarea)(?=[\s>/])[^<>]*>|<a(?=[\s>/])((?:[^<>"']|"[^"]*"|'[^']*')*)>/gi
|
|
32
|
+
// One attribute of a start tag: optional leading separator, name, and optional `= value` (quoted or unquoted).
|
|
33
|
+
const ATTR_RE = /([\s/]*)([^\s"'<>/=]+)(?:(\s*=\s*)(?:"([^"]*)"|'([^']*)'|([^\s<>]+)))?/g
|
|
34
|
+
const NON_HTML_EXT_RE = /\.(?:xml|json|txt|pdf|ico|png|jpe?g|gif|svg|webp|avif|webmanifest|zip|tar|gz|bz2|xz|7z|css|m?js|cjs|wasm|map|woff2?|ttf|otf|eot|mp3|mp4|webm|ogg|wav|csv|tsv|rss|atom|ics|vcf|epub|docx?|xlsx?|pptx?)$/i
|
|
35
|
+
|
|
36
|
+
function rewriteAnchorAttrs(attrs: string, localizeHref: (href: string) => string | undefined): string {
|
|
37
|
+
ATTR_RE.lastIndex = 0
|
|
38
|
+
let seenHref = false
|
|
39
|
+
let hrefReplacement: { start: number, end: number, text: string } | undefined
|
|
40
|
+
let match: RegExpExecArray | null
|
|
41
|
+
while ((match = ATTR_RE.exec(attrs)) !== null) {
|
|
42
|
+
const name = match[2]!.toLowerCase()
|
|
43
|
+
if (name === 'data-no-localize')
|
|
44
|
+
return attrs
|
|
45
|
+
if (name === 'href' && !seenHref) {
|
|
46
|
+
seenHref = true
|
|
47
|
+
const double = match[4]
|
|
48
|
+
const single = match[5]
|
|
49
|
+
const value = double ?? single
|
|
50
|
+
const next = value !== undefined ? localizeHref(value) : undefined
|
|
51
|
+
if (next !== undefined) {
|
|
52
|
+
const quote = double !== undefined ? '"' : '\''
|
|
53
|
+
hrefReplacement = {
|
|
54
|
+
start: match.index,
|
|
55
|
+
end: match.index + match[0].length,
|
|
56
|
+
text: `${match[1]}${match[2]}${match[3]}${quote}${next}${quote}`,
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
if (hrefReplacement === undefined)
|
|
62
|
+
return attrs
|
|
63
|
+
return `${attrs.slice(0, hrefReplacement.start)}${hrefReplacement.text}${attrs.slice(hrefReplacement.end)}`
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
function isSkippedI18nPath(pathname: string, assetPrefix: string, assetPrefixSlash: string): boolean {
|
|
67
|
+
return pathname === assetPrefix
|
|
68
|
+
|| pathname.startsWith(assetPrefixSlash)
|
|
69
|
+
|| pathname === '/_i18n'
|
|
70
|
+
|| pathname.startsWith('/_i18n/')
|
|
71
|
+
|| pathname === '/api'
|
|
72
|
+
|| pathname.startsWith('/api/')
|
|
73
|
+
|| pathname === '/auth'
|
|
74
|
+
|| pathname.startsWith('/auth/')
|
|
75
|
+
|| NON_HTML_EXT_RE.test(pathname)
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
function localizeHtmlLinks(
|
|
79
|
+
html: string,
|
|
80
|
+
locale: string,
|
|
81
|
+
localeSet: ReadonlySet<string>,
|
|
82
|
+
assetPrefix: string,
|
|
83
|
+
): string {
|
|
84
|
+
const assetPrefixSlash = `${assetPrefix}/`
|
|
85
|
+
const escapedLocale = escAttr(locale)
|
|
86
|
+
let inTextarea = false
|
|
87
|
+
let codePreDepth = 0
|
|
88
|
+
HTML_TOKEN_RE.lastIndex = 0
|
|
89
|
+
const localizeHref = (href: string): string | undefined => {
|
|
90
|
+
if (!href.startsWith('/') || href.startsWith('//'))
|
|
91
|
+
return undefined
|
|
92
|
+
const cut = href.search(/[?#]/)
|
|
93
|
+
const pathOnly = cut === -1 ? href : href.slice(0, cut)
|
|
94
|
+
if (isSkippedI18nPath(pathOnly, assetPrefix, assetPrefixSlash))
|
|
95
|
+
return undefined
|
|
96
|
+
const seg = pathOnly.slice(1).split('/', 1)[0]
|
|
97
|
+
if (seg !== undefined && localeSet.has(seg))
|
|
98
|
+
return undefined
|
|
99
|
+
// `href` is already extracted from a quoted HTML attribute; only escape the prepended locale segment to avoid double-escaping `&`.
|
|
100
|
+
return href === '/' ? `/${escapedLocale}` : `/${escapedLocale}${href}`
|
|
101
|
+
}
|
|
102
|
+
return html.replace(
|
|
103
|
+
HTML_TOKEN_RE,
|
|
104
|
+
(match, slash: string | undefined, skipTag: string | undefined, attrs: string | undefined) => {
|
|
105
|
+
if (skipTag !== undefined) {
|
|
106
|
+
const tag = skipTag.toLowerCase()
|
|
107
|
+
const isClosing = slash === '/'
|
|
108
|
+
const isSelfClosing = !isClosing && match.endsWith('/>')
|
|
109
|
+
if (inTextarea) {
|
|
110
|
+
if (isClosing && tag === 'textarea')
|
|
111
|
+
inTextarea = false
|
|
112
|
+
}
|
|
113
|
+
else if (tag === 'textarea') {
|
|
114
|
+
if (!isClosing && !isSelfClosing)
|
|
115
|
+
inTextarea = true
|
|
116
|
+
}
|
|
117
|
+
else if (isClosing) {
|
|
118
|
+
if (codePreDepth > 0)
|
|
119
|
+
codePreDepth--
|
|
120
|
+
}
|
|
121
|
+
else if (!isSelfClosing) {
|
|
122
|
+
codePreDepth++
|
|
123
|
+
}
|
|
124
|
+
return match
|
|
125
|
+
}
|
|
126
|
+
if (inTextarea || codePreDepth > 0 || attrs === undefined)
|
|
127
|
+
return match
|
|
128
|
+
const rewritten = rewriteAnchorAttrs(attrs, localizeHref)
|
|
129
|
+
return rewritten === attrs ? match : `<a${rewritten}>`
|
|
130
|
+
},
|
|
131
|
+
)
|
|
132
|
+
}
|
|
29
133
|
|
|
30
134
|
function collapseLeadingSlashes(p: string): string {
|
|
31
135
|
if (!p)
|
|
@@ -87,7 +191,81 @@ export function formatNumber(
|
|
|
87
191
|
return new Intl.NumberFormat(locale, options).format(value)
|
|
88
192
|
}
|
|
89
193
|
|
|
194
|
+
const LOCALE_TAG_RE = /^[a-z]{2,3}(?:-[a-z0-9]{2,8})*$/i
|
|
195
|
+
|
|
196
|
+
function validateOptions({ locales, defaultLocale }: I18nOptions): void {
|
|
197
|
+
const fail = (what: string, fix: string): never => {
|
|
198
|
+
throw new Error(`@prunellejs/i18n: ${what}: ${fix}.`)
|
|
199
|
+
}
|
|
200
|
+
if (locales.length === 0)
|
|
201
|
+
fail('locales is empty', "list at least one locale tag, for example locales: ['en']")
|
|
202
|
+
const seen = new Set<string>()
|
|
203
|
+
for (const loc of locales) {
|
|
204
|
+
if (!LOCALE_TAG_RE.test(loc))
|
|
205
|
+
fail(`"${loc}" is not a valid locale tag`, "use a BCP 47 tag such as 'en' or 'fr-CA'")
|
|
206
|
+
if (seen.has(loc))
|
|
207
|
+
fail(`locale "${loc}" is listed twice`, 'remove the duplicate from locales')
|
|
208
|
+
seen.add(loc)
|
|
209
|
+
}
|
|
210
|
+
if (!seen.has(defaultLocale))
|
|
211
|
+
fail(`defaultLocale "${defaultLocale}" is not in locales`, 'add it to locales or pick one of them')
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
/** A successful HTML page, as opposed to a plugin or API route answering JSON, XML or a stream, or a 404. */
|
|
215
|
+
function isHtmlPage(res: Response): boolean {
|
|
216
|
+
return res.status >= 200 && res.status < 300 && (res.headers.get('content-type') ?? '').startsWith('text/html')
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
interface CanonicalRedirectOptions {
|
|
220
|
+
readonly locales: readonly string[]
|
|
221
|
+
readonly defaultLocale: string
|
|
222
|
+
readonly prefixDefault: boolean
|
|
223
|
+
readonly assetPrefix: string
|
|
224
|
+
readonly assetPrefixSlash: string
|
|
225
|
+
readonly canonicalRoutes: CanonicalRouteIndex | undefined
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
// One URL per page: the default locale is prefixed (301 away) only with prefixDefault, and unprefixed (302 to the prefix) only without it.
|
|
229
|
+
// Matching against the build's prerendered HTML URLs and SSR HTML page routes lets us redirect before load() / downstream middleware
|
|
230
|
+
// and avoids 404s on dynamic prerendered routes, while leaving plugin routes, API routes and missing pages alone.
|
|
231
|
+
function createCanonicalRedirectMiddleware(opts: CanonicalRedirectOptions): Middleware {
|
|
232
|
+
const { locales, defaultLocale, prefixDefault, assetPrefix, assetPrefixSlash, canonicalRoutes } = opts
|
|
233
|
+
return async (ctx, next) => {
|
|
234
|
+
const method = ctx.request.method
|
|
235
|
+
if (method !== 'GET' && method !== 'HEAD')
|
|
236
|
+
return next()
|
|
237
|
+
const rawPath = ctx.url.pathname
|
|
238
|
+
const { locale, path } = stripLocalePrefix(rawPath, locales)
|
|
239
|
+
let target: string
|
|
240
|
+
let status: 301 | 302
|
|
241
|
+
if (locale === undefined && prefixDefault) {
|
|
242
|
+
if (isSkippedI18nPath(rawPath, assetPrefix, assetPrefixSlash))
|
|
243
|
+
return next()
|
|
244
|
+
target = normalizePathname(localizePath(rawPath, defaultLocale, defaultLocale, locales, true))
|
|
245
|
+
status = 302
|
|
246
|
+
}
|
|
247
|
+
else if (locale === defaultLocale && !prefixDefault) {
|
|
248
|
+
target = path
|
|
249
|
+
status = 301
|
|
250
|
+
}
|
|
251
|
+
else {
|
|
252
|
+
return next()
|
|
253
|
+
}
|
|
254
|
+
if (canonicalRoutes !== undefined) {
|
|
255
|
+
if (isCanonicalHtmlTarget(canonicalRoutes, target, path, ctx.params))
|
|
256
|
+
return ctx.redirect(`${target}${ctx.url.search}`, status)
|
|
257
|
+
return next()
|
|
258
|
+
}
|
|
259
|
+
const res = await next()
|
|
260
|
+
if (!isHtmlPage(res))
|
|
261
|
+
return res
|
|
262
|
+
void res.body?.cancel()
|
|
263
|
+
return ctx.redirect(`${target}${ctx.url.search}`, status)
|
|
264
|
+
}
|
|
265
|
+
}
|
|
266
|
+
|
|
90
267
|
export function i18n(options: I18nOptions): PrunellePlugin {
|
|
268
|
+
validateOptions(options)
|
|
91
269
|
const { locales, defaultLocale, messages = {}, prefixDefault = false } = options
|
|
92
270
|
let activeSite = options.site?.replace(/\/$/, '')
|
|
93
271
|
let activeAssetPrefix = '/_pru'
|
|
@@ -124,6 +302,10 @@ export function i18n(options: I18nOptions): PrunellePlugin {
|
|
|
124
302
|
ctx.provide(I18N_CONFIG_SERVICE, sharedConfig)
|
|
125
303
|
},
|
|
126
304
|
|
|
305
|
+
afterPrerender(ctx) {
|
|
306
|
+
ctx.setData({ ...collectI18nBuildData(ctx.routes) })
|
|
307
|
+
},
|
|
308
|
+
|
|
127
309
|
server(api) {
|
|
128
310
|
if (options.site === undefined && api.site !== undefined)
|
|
129
311
|
activeSite = api.site.replace(/\/$/, '')
|
|
@@ -132,6 +314,7 @@ export function i18n(options: I18nOptions): PrunellePlugin {
|
|
|
132
314
|
const assetPrefixSlash = `${activeAssetPrefix}/`
|
|
133
315
|
const actionPrefix = `${assetPrefixSlash}action/`
|
|
134
316
|
const trustedOrigins = api.trustedOrigins.length > 0 ? new Set(api.trustedOrigins) : undefined
|
|
317
|
+
const canonicalRoutes = buildCanonicalRouteIndex(api.getBuildData<I18nBuildData>())
|
|
135
318
|
api.provide(I18N_CONFIG_SERVICE, sharedConfig)
|
|
136
319
|
|
|
137
320
|
// Rewrite /fr/about -> /about and attach locale + helpers onto ctx.locals
|
|
@@ -159,29 +342,14 @@ export function i18n(options: I18nOptions): PrunellePlugin {
|
|
|
159
342
|
return stripped.locale !== undefined ? stripped.path : undefined
|
|
160
343
|
})
|
|
161
344
|
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
rawPath === activeAssetPrefix
|
|
171
|
-
|| rawPath.startsWith(assetPrefixSlash)
|
|
172
|
-
|| rawPath === '/_i18n'
|
|
173
|
-
|| rawPath.startsWith('/_i18n/')
|
|
174
|
-
|| rawPath === '/api'
|
|
175
|
-
|| rawPath.startsWith('/api/')
|
|
176
|
-
) {
|
|
177
|
-
return next()
|
|
178
|
-
}
|
|
179
|
-
if (stripLocalePrefix(rawPath, locales).locale !== undefined)
|
|
180
|
-
return next()
|
|
181
|
-
const target = localizePath(rawPath, defaultLocale, defaultLocale, locales, true)
|
|
182
|
-
return ctx.redirect(`${target}${ctx.url.search}`, 302)
|
|
183
|
-
}, { scope: 'rendered' })
|
|
184
|
-
}
|
|
345
|
+
api.use(createCanonicalRedirectMiddleware({
|
|
346
|
+
locales,
|
|
347
|
+
defaultLocale,
|
|
348
|
+
prefixDefault,
|
|
349
|
+
assetPrefix: activeAssetPrefix,
|
|
350
|
+
assetPrefixSlash,
|
|
351
|
+
canonicalRoutes,
|
|
352
|
+
}), { scope: 'rendered' })
|
|
185
353
|
|
|
186
354
|
api.route('GET', '/_i18n/locales', ctx =>
|
|
187
355
|
ctx.json({ locales, defaultLocale, current: ctx.locals.locale ?? defaultLocale }))
|
|
@@ -190,8 +358,10 @@ export function i18n(options: I18nOptions): PrunellePlugin {
|
|
|
190
358
|
prerenderPaths(paths) {
|
|
191
359
|
const out = new Set<string>()
|
|
192
360
|
for (const raw of paths) {
|
|
193
|
-
|
|
194
|
-
|
|
361
|
+
const { locale } = stripLocalePrefix(raw, locales)
|
|
362
|
+
if (locale !== undefined) {
|
|
363
|
+
// The default locale is only ever served unprefixed when prefixDefault is off: `/en/x` is a redirect, never a page.
|
|
364
|
+
out.add(locale === defaultLocale && !prefixDefault ? localizePath(raw, locale, defaultLocale, locales, false) : raw)
|
|
195
365
|
continue
|
|
196
366
|
}
|
|
197
367
|
for (const loc of locales)
|
|
@@ -209,6 +379,9 @@ export function i18n(options: I18nOptions): PrunellePlugin {
|
|
|
209
379
|
const links = alternateLinks(path, { site: activeSite, locales, defaultLocale, prefixDefault })
|
|
210
380
|
for (const l of links)
|
|
211
381
|
head.add(`<link rel="alternate" hreflang="${escAttr(l.locale)}" href="${escAttr(l.href)}">`)
|
|
382
|
+
const base = links.find(l => l.locale === defaultLocale)
|
|
383
|
+
if (base !== undefined)
|
|
384
|
+
head.add(`<link rel="alternate" hreflang="x-default" href="${escAttr(base.href)}">`)
|
|
212
385
|
}
|
|
213
386
|
},
|
|
214
387
|
|
|
@@ -217,20 +390,7 @@ export function i18n(options: I18nOptions): PrunellePlugin {
|
|
|
217
390
|
// Prefix internal <a href="/..."> links for non-default locales only
|
|
218
391
|
if (locale === defaultLocale && !prefixDefault)
|
|
219
392
|
return html
|
|
220
|
-
|
|
221
|
-
const escapedLocale = escAttr(locale)
|
|
222
|
-
return html.replace(INTERNAL_HREF_RE, (match, before: string, href: string, after: string) => {
|
|
223
|
-
if (before.includes('data-no-localize') || after.includes('data-no-localize'))
|
|
224
|
-
return match
|
|
225
|
-
if (href.startsWith('//') || href === activeAssetPrefix || href.startsWith(assetPrefixSlash) || href.startsWith('/_i18n/'))
|
|
226
|
-
return match
|
|
227
|
-
const seg = href.slice(1).split(/[/?#]/, 1)[0]
|
|
228
|
-
if (seg !== undefined && localeSet.has(seg))
|
|
229
|
-
return match
|
|
230
|
-
// `href` is already extracted from a double-quoted HTML attribute; only escape the prepended locale segment to avoid double-escaping `&`.
|
|
231
|
-
const prefixed = href === '/' ? `/${escapedLocale}` : `/${escapedLocale}${href}`
|
|
232
|
-
return `<a${before}href="${prefixed}"${after}>`
|
|
233
|
-
})
|
|
393
|
+
return localizeHtmlLinks(html, locale, localeSet, activeAssetPrefix)
|
|
234
394
|
},
|
|
235
395
|
|
|
236
396
|
check(ctx) {
|
package/src/routes.ts
ADDED
|
@@ -0,0 +1,172 @@
|
|
|
1
|
+
// Build-time route index for @prunellejs/i18n canonical-URL redirects: avoids 404s on dynamic prerendered routes
|
|
2
|
+
// and avoids invoking load() or downstream middleware before redirecting SSR HTML routes.
|
|
3
|
+
|
|
4
|
+
import type { FinalizeBuildContext } from 'prunelle/config'
|
|
5
|
+
|
|
6
|
+
type RouteEntry = FinalizeBuildContext['routes'][number]
|
|
7
|
+
|
|
8
|
+
export interface I18nBuildData {
|
|
9
|
+
/** Canonical prerendered HTML URLs (normalized, no trailing slash except '/'). */
|
|
10
|
+
prerenderedHtml: string[]
|
|
11
|
+
/** Static SSR HTML page paths (e.g. '/', '/about'). */
|
|
12
|
+
staticPages: string[]
|
|
13
|
+
/** Dynamic SSR HTML page route patterns (e.g. '/blog/:slug', '/docs/*path'). */
|
|
14
|
+
dynamicPages: string[]
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
interface CompiledSegment {
|
|
18
|
+
readonly kind: 'static' | 'param' | 'optional' | 'catchall'
|
|
19
|
+
readonly value: string
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export interface CanonicalRouteIndex {
|
|
23
|
+
readonly prerenderedHtml: ReadonlySet<string>
|
|
24
|
+
readonly staticPages: ReadonlySet<string>
|
|
25
|
+
readonly dynamicPages: readonly (readonly CompiledSegment[])[]
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export function normalizePathname(pathname: string): string {
|
|
29
|
+
return pathname.length > 1 ? pathname.replace(/\/+$/, '') || '/' : pathname
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
function decodeSegments(pathname: string): string[] | undefined {
|
|
33
|
+
const norm = normalizePathname(pathname)
|
|
34
|
+
if (norm === '/')
|
|
35
|
+
return []
|
|
36
|
+
const raw = norm.slice(1).split('/')
|
|
37
|
+
const out: string[] = []
|
|
38
|
+
for (const seg of raw) {
|
|
39
|
+
let decoded: string
|
|
40
|
+
try {
|
|
41
|
+
decoded = decodeURIComponent(seg)
|
|
42
|
+
}
|
|
43
|
+
catch {
|
|
44
|
+
return undefined
|
|
45
|
+
}
|
|
46
|
+
if (decoded.includes('/') || decoded.includes('\\') || decoded.includes('\0'))
|
|
47
|
+
return undefined
|
|
48
|
+
out.push(decoded)
|
|
49
|
+
}
|
|
50
|
+
return out
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
function decodePathname(pathname: string): string | undefined {
|
|
54
|
+
const segs = decodeSegments(pathname)
|
|
55
|
+
if (segs === undefined)
|
|
56
|
+
return undefined
|
|
57
|
+
return segs.length === 0 ? '/' : `/${segs.join('/')}`
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
function isHtmlOutput(relOut: string): boolean {
|
|
61
|
+
return relOut.endsWith('.html') || relOut.endsWith('.htm')
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
function parseSegment(seg: string): CompiledSegment {
|
|
65
|
+
if (seg.startsWith('*')) {
|
|
66
|
+
const body = seg.slice(1)
|
|
67
|
+
const eq = body.indexOf('=')
|
|
68
|
+
return { kind: 'catchall', value: (eq === -1 ? body : body.slice(0, eq)) || 'rest' }
|
|
69
|
+
}
|
|
70
|
+
if (seg.startsWith(':')) {
|
|
71
|
+
const body = seg.slice(1)
|
|
72
|
+
const optional = body.endsWith('?')
|
|
73
|
+
const spec = optional ? body.slice(0, -1) : body
|
|
74
|
+
const eq = spec.indexOf('=')
|
|
75
|
+
return { kind: optional ? 'optional' : 'param', value: eq === -1 ? spec : spec.slice(0, eq) }
|
|
76
|
+
}
|
|
77
|
+
return { kind: 'static', value: seg }
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/** Collects prerendered HTML URLs and SSR HTML page routes for persistence in `manifest.pluginData`. */
|
|
81
|
+
export function collectI18nBuildData(routes: readonly RouteEntry[]): I18nBuildData {
|
|
82
|
+
const prerenderedHtml = new Set<string>()
|
|
83
|
+
const staticPages = new Set<string>()
|
|
84
|
+
const dynamicPages = new Set<string>()
|
|
85
|
+
for (const route of routes) {
|
|
86
|
+
if (route.prerendered !== undefined) {
|
|
87
|
+
for (const [url, relOut] of Object.entries(route.prerendered)) {
|
|
88
|
+
if (isHtmlOutput(relOut))
|
|
89
|
+
prerenderedHtml.add(normalizePathname(url))
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
if (typeof route.isIsland !== 'boolean')
|
|
93
|
+
continue
|
|
94
|
+
const isDynamic = route.path.includes(':') || route.path.includes('*')
|
|
95
|
+
if (isDynamic) {
|
|
96
|
+
if (!(route.prerender === true && route.prerendered !== undefined))
|
|
97
|
+
dynamicPages.add(route.path)
|
|
98
|
+
}
|
|
99
|
+
else if (route.prerendered === undefined || Object.keys(route.prerendered).length === 0) {
|
|
100
|
+
staticPages.add(normalizePathname(route.path))
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
return {
|
|
104
|
+
prerenderedHtml: [...prerenderedHtml],
|
|
105
|
+
staticPages: [...staticPages],
|
|
106
|
+
dynamicPages: [...dynamicPages],
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
export function buildCanonicalRouteIndex(data: I18nBuildData | undefined): CanonicalRouteIndex | undefined {
|
|
111
|
+
if (data === undefined)
|
|
112
|
+
return undefined
|
|
113
|
+
const dynamicPages = data.dynamicPages.map((pattern) => {
|
|
114
|
+
const norm = normalizePathname(pattern)
|
|
115
|
+
return norm === '/' ? [] : norm.slice(1).split('/').map(parseSegment)
|
|
116
|
+
})
|
|
117
|
+
return {
|
|
118
|
+
prerenderedHtml: new Set(data.prerenderedHtml),
|
|
119
|
+
staticPages: new Set(data.staticPages),
|
|
120
|
+
dynamicPages,
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
function matchPattern(
|
|
125
|
+
pattern: readonly CompiledSegment[],
|
|
126
|
+
parts: readonly string[],
|
|
127
|
+
params: Readonly<Record<string, string>>,
|
|
128
|
+
pi = 0,
|
|
129
|
+
si = 0,
|
|
130
|
+
): boolean {
|
|
131
|
+
if (pi === pattern.length)
|
|
132
|
+
return si === parts.length
|
|
133
|
+
const seg = pattern[pi]!
|
|
134
|
+
if (seg.kind === 'catchall')
|
|
135
|
+
return params[seg.value] === parts.slice(si).join('/')
|
|
136
|
+
if (seg.kind === 'optional') {
|
|
137
|
+
if (si < parts.length && params[seg.value] === parts[si] && matchPattern(pattern, parts, params, pi + 1, si + 1))
|
|
138
|
+
return true
|
|
139
|
+
return !Object.hasOwn(params, seg.value) && matchPattern(pattern, parts, params, pi + 1, si)
|
|
140
|
+
}
|
|
141
|
+
if (si >= parts.length)
|
|
142
|
+
return false
|
|
143
|
+
if (seg.kind === 'static')
|
|
144
|
+
return seg.value === parts[si] && matchPattern(pattern, parts, params, pi + 1, si + 1)
|
|
145
|
+
return params[seg.value] === parts[si] && matchPattern(pattern, parts, params, pi + 1, si + 1)
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
/** True when `target` is a known prerendered HTML page or `strippedPath` matches an SSR HTML page route. */
|
|
149
|
+
export function isCanonicalHtmlTarget(
|
|
150
|
+
index: CanonicalRouteIndex,
|
|
151
|
+
target: string,
|
|
152
|
+
strippedPath: string,
|
|
153
|
+
params: Readonly<Record<string, string>>,
|
|
154
|
+
): boolean {
|
|
155
|
+
const normTarget = normalizePathname(target)
|
|
156
|
+
if (index.prerenderedHtml.has(normTarget))
|
|
157
|
+
return true
|
|
158
|
+
if (normTarget.includes('%')) {
|
|
159
|
+
const decodedTarget = decodePathname(normTarget)
|
|
160
|
+
if (decodedTarget !== undefined && index.prerenderedHtml.has(decodedTarget))
|
|
161
|
+
return true
|
|
162
|
+
}
|
|
163
|
+
const decodedPath = decodePathname(strippedPath)
|
|
164
|
+
if (decodedPath === undefined)
|
|
165
|
+
return false
|
|
166
|
+
if (index.staticPages.has(decodedPath))
|
|
167
|
+
return true
|
|
168
|
+
if (index.dynamicPages.length === 0)
|
|
169
|
+
return false
|
|
170
|
+
const parts = decodedPath === '/' ? [] : decodedPath.slice(1).split('/')
|
|
171
|
+
return index.dynamicPages.some(pattern => matchPattern(pattern, parts, params))
|
|
172
|
+
}
|