@prunellejs/i18n 0.1.1 → 0.7.2

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 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
- - `site`: optional public origin (inherits `PrunelleConfig.site`); when set, injects `<link rel="alternate" hreflang="...">` tags into `<head>`.
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.1.1",
3
+ "version": "0.7.2",
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.1.1"
24
+ "prunelle": "^0.7.2"
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,86 @@ export interface I18nOptions {
25
28
  site?: string | undefined
26
29
  }
27
30
 
28
- const INTERNAL_HREF_RE = /<a\b([^>]*?)\bhref="(\/[^"]*)"([^>]*)>/gi
31
+ const HTML_TOKEN_RE = /<(\/?)(pre|code|textarea)(?=[\s>/])[^>]*>|<a(?=[\s>/])((?:[^>"']|"[^"]*"|'[^']*')*)>/gi
32
+ // One attribute of a start tag: its leading space, its name, and the value when it is quoted.
33
+ const ATTR_RE = /(\s)([^\s"'<>/=]+)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'))?/g
34
+ const NO_LOCALIZE_RE = /\sdata-no-localize(?=[\s=/]|$)/i
35
+ 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
36
+
37
+ function isSkippedI18nPath(pathname: string, assetPrefix: string, assetPrefixSlash: string): boolean {
38
+ return pathname === assetPrefix
39
+ || pathname.startsWith(assetPrefixSlash)
40
+ || pathname === '/_i18n'
41
+ || pathname.startsWith('/_i18n/')
42
+ || pathname === '/api'
43
+ || pathname.startsWith('/api/')
44
+ || pathname === '/auth'
45
+ || pathname.startsWith('/auth/')
46
+ || NON_HTML_EXT_RE.test(pathname)
47
+ }
48
+
49
+ function localizeHtmlLinks(
50
+ html: string,
51
+ locale: string,
52
+ localeSet: ReadonlySet<string>,
53
+ assetPrefix: string,
54
+ ): string {
55
+ const assetPrefixSlash = `${assetPrefix}/`
56
+ const escapedLocale = escAttr(locale)
57
+ let inTextarea = false
58
+ let codePreDepth = 0
59
+ HTML_TOKEN_RE.lastIndex = 0
60
+ const localizeHref = (href: string): string | undefined => {
61
+ if (!href.startsWith('/') || href.startsWith('//'))
62
+ return undefined
63
+ const cut = href.search(/[?#]/)
64
+ const pathOnly = cut === -1 ? href : href.slice(0, cut)
65
+ if (isSkippedI18nPath(pathOnly, assetPrefix, assetPrefixSlash))
66
+ return undefined
67
+ const seg = pathOnly.slice(1).split('/', 1)[0]
68
+ if (seg !== undefined && localeSet.has(seg))
69
+ return undefined
70
+ // `href` is already extracted from a quoted HTML attribute; only escape the prepended locale segment to avoid double-escaping `&amp;`.
71
+ return href === '/' ? `/${escapedLocale}` : `/${escapedLocale}${href}`
72
+ }
73
+ return html.replace(
74
+ HTML_TOKEN_RE,
75
+ (match, slash: string | undefined, skipTag: string | undefined, attrs: string | undefined) => {
76
+ if (skipTag !== undefined) {
77
+ const tag = skipTag.toLowerCase()
78
+ const isClosing = slash === '/'
79
+ const isSelfClosing = !isClosing && match.endsWith('/>')
80
+ if (inTextarea) {
81
+ if (isClosing && tag === 'textarea')
82
+ inTextarea = false
83
+ }
84
+ else if (tag === 'textarea') {
85
+ if (!isClosing && !isSelfClosing)
86
+ inTextarea = true
87
+ }
88
+ else if (isClosing) {
89
+ if (codePreDepth > 0)
90
+ codePreDepth--
91
+ }
92
+ else if (!isSelfClosing) {
93
+ codePreDepth++
94
+ }
95
+ return match
96
+ }
97
+ if (inTextarea || codePreDepth > 0 || attrs === undefined || NO_LOCALIZE_RE.test(attrs))
98
+ return match
99
+ const rewritten = attrs.replace(ATTR_RE, (attr, space: string, name: string, double: string | undefined, single: string | undefined) => {
100
+ const value = double ?? single
101
+ const next = name.toLowerCase() === 'href' && value !== undefined ? localizeHref(value) : undefined
102
+ if (next === undefined)
103
+ return attr
104
+ const quote = double !== undefined ? '"' : "'"
105
+ return `${space}${name}=${quote}${next}${quote}`
106
+ })
107
+ return `<a${rewritten}>`
108
+ },
109
+ )
110
+ }
29
111
 
30
112
  function collapseLeadingSlashes(p: string): string {
31
113
  if (!p)
@@ -87,7 +169,81 @@ export function formatNumber(
87
169
  return new Intl.NumberFormat(locale, options).format(value)
88
170
  }
89
171
 
172
+ const LOCALE_TAG_RE = /^[a-z]{2,3}(?:-[a-z0-9]{2,8})*$/i
173
+
174
+ function validateOptions({ locales, defaultLocale }: I18nOptions): void {
175
+ const fail = (what: string, fix: string): never => {
176
+ throw new Error(`@prunellejs/i18n: ${what}: ${fix}.`)
177
+ }
178
+ if (locales.length === 0)
179
+ fail('locales is empty', "list at least one locale tag, for example locales: ['en']")
180
+ const seen = new Set<string>()
181
+ for (const loc of locales) {
182
+ if (!LOCALE_TAG_RE.test(loc))
183
+ fail(`"${loc}" is not a valid locale tag`, "use a BCP 47 tag such as 'en' or 'fr-CA'")
184
+ if (seen.has(loc))
185
+ fail(`locale "${loc}" is listed twice`, 'remove the duplicate from locales')
186
+ seen.add(loc)
187
+ }
188
+ if (!seen.has(defaultLocale))
189
+ fail(`defaultLocale "${defaultLocale}" is not in locales`, 'add it to locales or pick one of them')
190
+ }
191
+
192
+ /** A successful HTML page, as opposed to a plugin or API route answering JSON, XML or a stream, or a 404. */
193
+ function isHtmlPage(res: Response): boolean {
194
+ return res.status >= 200 && res.status < 300 && (res.headers.get('content-type') ?? '').startsWith('text/html')
195
+ }
196
+
197
+ interface CanonicalRedirectOptions {
198
+ readonly locales: readonly string[]
199
+ readonly defaultLocale: string
200
+ readonly prefixDefault: boolean
201
+ readonly assetPrefix: string
202
+ readonly assetPrefixSlash: string
203
+ readonly canonicalRoutes: CanonicalRouteIndex | undefined
204
+ }
205
+
206
+ // One URL per page: the default locale is prefixed (301 away) only with prefixDefault, and unprefixed (302 to the prefix) only without it.
207
+ // Matching against the build's prerendered HTML URLs and SSR HTML page routes lets us redirect before load() / downstream middleware
208
+ // and avoids 404s on dynamic prerendered routes, while leaving plugin routes, API routes and missing pages alone.
209
+ function createCanonicalRedirectMiddleware(opts: CanonicalRedirectOptions): Middleware {
210
+ const { locales, defaultLocale, prefixDefault, assetPrefix, assetPrefixSlash, canonicalRoutes } = opts
211
+ return async (ctx, next) => {
212
+ const method = ctx.request.method
213
+ if (method !== 'GET' && method !== 'HEAD')
214
+ return next()
215
+ const rawPath = ctx.url.pathname
216
+ const { locale, path } = stripLocalePrefix(rawPath, locales)
217
+ let target: string
218
+ let status: 301 | 302
219
+ if (locale === undefined && prefixDefault) {
220
+ if (isSkippedI18nPath(rawPath, assetPrefix, assetPrefixSlash))
221
+ return next()
222
+ target = normalizePathname(localizePath(rawPath, defaultLocale, defaultLocale, locales, true))
223
+ status = 302
224
+ }
225
+ else if (locale === defaultLocale && !prefixDefault) {
226
+ target = path
227
+ status = 301
228
+ }
229
+ else {
230
+ return next()
231
+ }
232
+ if (canonicalRoutes !== undefined) {
233
+ if (isCanonicalHtmlTarget(canonicalRoutes, target, path, ctx.params))
234
+ return ctx.redirect(`${target}${ctx.url.search}`, status)
235
+ return next()
236
+ }
237
+ const res = await next()
238
+ if (!isHtmlPage(res))
239
+ return res
240
+ void res.body?.cancel()
241
+ return ctx.redirect(`${target}${ctx.url.search}`, status)
242
+ }
243
+ }
244
+
90
245
  export function i18n(options: I18nOptions): PrunellePlugin {
246
+ validateOptions(options)
91
247
  const { locales, defaultLocale, messages = {}, prefixDefault = false } = options
92
248
  let activeSite = options.site?.replace(/\/$/, '')
93
249
  let activeAssetPrefix = '/_pru'
@@ -124,6 +280,10 @@ export function i18n(options: I18nOptions): PrunellePlugin {
124
280
  ctx.provide(I18N_CONFIG_SERVICE, sharedConfig)
125
281
  },
126
282
 
283
+ afterPrerender(ctx) {
284
+ ctx.setData({ ...collectI18nBuildData(ctx.routes) })
285
+ },
286
+
127
287
  server(api) {
128
288
  if (options.site === undefined && api.site !== undefined)
129
289
  activeSite = api.site.replace(/\/$/, '')
@@ -132,6 +292,7 @@ export function i18n(options: I18nOptions): PrunellePlugin {
132
292
  const assetPrefixSlash = `${activeAssetPrefix}/`
133
293
  const actionPrefix = `${assetPrefixSlash}action/`
134
294
  const trustedOrigins = api.trustedOrigins.length > 0 ? new Set(api.trustedOrigins) : undefined
295
+ const canonicalRoutes = buildCanonicalRouteIndex(api.getBuildData<I18nBuildData>())
135
296
  api.provide(I18N_CONFIG_SERVICE, sharedConfig)
136
297
 
137
298
  // Rewrite /fr/about -> /about and attach locale + helpers onto ctx.locals
@@ -159,29 +320,14 @@ export function i18n(options: I18nOptions): PrunellePlugin {
159
320
  return stripped.locale !== undefined ? stripped.path : undefined
160
321
  })
161
322
 
162
- if (prefixDefault) {
163
- // Every prerendered path carries a locale prefix (`prerenderPaths`), so prerendered pages skip this redirect.
164
- api.use((ctx, next) => {
165
- const method = ctx.request.method
166
- if (method !== 'GET' && method !== 'HEAD')
167
- return next()
168
- const rawPath = ctx.url.pathname
169
- if (
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
- }
323
+ api.use(createCanonicalRedirectMiddleware({
324
+ locales,
325
+ defaultLocale,
326
+ prefixDefault,
327
+ assetPrefix: activeAssetPrefix,
328
+ assetPrefixSlash,
329
+ canonicalRoutes,
330
+ }), { scope: 'rendered' })
185
331
 
186
332
  api.route('GET', '/_i18n/locales', ctx =>
187
333
  ctx.json({ locales, defaultLocale, current: ctx.locals.locale ?? defaultLocale }))
@@ -190,8 +336,10 @@ export function i18n(options: I18nOptions): PrunellePlugin {
190
336
  prerenderPaths(paths) {
191
337
  const out = new Set<string>()
192
338
  for (const raw of paths) {
193
- if (stripLocalePrefix(raw, locales).locale !== undefined) {
194
- out.add(raw)
339
+ const { locale } = stripLocalePrefix(raw, locales)
340
+ if (locale !== undefined) {
341
+ // The default locale is only ever served unprefixed when prefixDefault is off: `/en/x` is a redirect, never a page.
342
+ out.add(locale === defaultLocale && !prefixDefault ? localizePath(raw, locale, defaultLocale, locales, false) : raw)
195
343
  continue
196
344
  }
197
345
  for (const loc of locales)
@@ -209,6 +357,9 @@ export function i18n(options: I18nOptions): PrunellePlugin {
209
357
  const links = alternateLinks(path, { site: activeSite, locales, defaultLocale, prefixDefault })
210
358
  for (const l of links)
211
359
  head.add(`<link rel="alternate" hreflang="${escAttr(l.locale)}" href="${escAttr(l.href)}">`)
360
+ const base = links.find(l => l.locale === defaultLocale)
361
+ if (base !== undefined)
362
+ head.add(`<link rel="alternate" hreflang="x-default" href="${escAttr(base.href)}">`)
212
363
  }
213
364
  },
214
365
 
@@ -217,20 +368,7 @@ export function i18n(options: I18nOptions): PrunellePlugin {
217
368
  // Prefix internal <a href="/..."> links for non-default locales only
218
369
  if (locale === defaultLocale && !prefixDefault)
219
370
  return html
220
- const assetPrefixSlash = `${activeAssetPrefix}/`
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 `&amp;`.
231
- const prefixed = href === '/' ? `/${escapedLocale}` : `/${escapedLocale}${href}`
232
- return `<a${before}href="${prefixed}"${after}>`
233
- })
371
+ return localizeHtmlLinks(html, locale, localeSet, activeAssetPrefix)
234
372
  },
235
373
 
236
374
  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
+ }