@prunellejs/i18n 0.7.0 → 0.7.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/package.json +2 -2
  2. package/src/index.ts +64 -30
  3. package/src/routes.ts +172 -0
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@prunellejs/i18n",
3
- "version": "0.7.0",
3
+ "version": "0.7.1",
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.7.0"
24
+ "prunelle": "^0.7.1"
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 {
@@ -191,6 +194,54 @@ function isHtmlPage(res: Response): boolean {
191
194
  return res.status >= 200 && res.status < 300 && (res.headers.get('content-type') ?? '').startsWith('text/html')
192
195
  }
193
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
+
194
245
  export function i18n(options: I18nOptions): PrunellePlugin {
195
246
  validateOptions(options)
196
247
  const { locales, defaultLocale, messages = {}, prefixDefault = false } = options
@@ -229,6 +280,10 @@ export function i18n(options: I18nOptions): PrunellePlugin {
229
280
  ctx.provide(I18N_CONFIG_SERVICE, sharedConfig)
230
281
  },
231
282
 
283
+ afterPrerender(ctx) {
284
+ ctx.setData({ ...collectI18nBuildData(ctx.routes) })
285
+ },
286
+
232
287
  server(api) {
233
288
  if (options.site === undefined && api.site !== undefined)
234
289
  activeSite = api.site.replace(/\/$/, '')
@@ -237,6 +292,7 @@ export function i18n(options: I18nOptions): PrunellePlugin {
237
292
  const assetPrefixSlash = `${activeAssetPrefix}/`
238
293
  const actionPrefix = `${assetPrefixSlash}action/`
239
294
  const trustedOrigins = api.trustedOrigins.length > 0 ? new Set(api.trustedOrigins) : undefined
295
+ const canonicalRoutes = buildCanonicalRouteIndex(api.getBuildData<I18nBuildData>())
240
296
  api.provide(I18N_CONFIG_SERVICE, sharedConfig)
241
297
 
242
298
  // Rewrite /fr/about -> /about and attach locale + helpers onto ctx.locals
@@ -264,36 +320,14 @@ export function i18n(options: I18nOptions): PrunellePlugin {
264
320
  return stripped.locale !== undefined ? stripped.path : undefined
265
321
  })
266
322
 
267
- // One URL per page: the default locale is prefixed (301 away) only with prefixDefault, and unprefixed (302 to the prefix) only without it.
268
- // The redirect waits for the chain, so plugin and API routes and missing pages answer as they are.
269
- // Prerendered paths never need it (`prerenderPaths`), so prerendered pages skip it.
270
- api.use(async (ctx, next) => {
271
- const method = ctx.request.method
272
- if (method !== 'GET' && method !== 'HEAD')
273
- return next()
274
- const rawPath = ctx.url.pathname
275
- const { locale, path } = stripLocalePrefix(rawPath, locales)
276
- let target: string
277
- let status: 301 | 302
278
- if (locale === undefined && prefixDefault) {
279
- if (isSkippedI18nPath(rawPath, activeAssetPrefix, assetPrefixSlash))
280
- return next()
281
- target = localizePath(rawPath, defaultLocale, defaultLocale, locales, true)
282
- status = 302
283
- }
284
- else if (locale === defaultLocale && !prefixDefault) {
285
- target = path
286
- status = 301
287
- }
288
- else {
289
- return next()
290
- }
291
- const res = await next()
292
- if (!isHtmlPage(res))
293
- return res
294
- void res.body?.cancel()
295
- return ctx.redirect(`${target}${ctx.url.search}`, status)
296
- }, { scope: 'rendered' })
323
+ api.use(createCanonicalRedirectMiddleware({
324
+ locales,
325
+ defaultLocale,
326
+ prefixDefault,
327
+ assetPrefix: activeAssetPrefix,
328
+ assetPrefixSlash,
329
+ canonicalRoutes,
330
+ }), { scope: 'rendered' })
297
331
 
298
332
  api.route('GET', '/_i18n/locales', ctx =>
299
333
  ctx.json({ locales, defaultLocale, current: ctx.locals.locale ?? defaultLocale }))
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
+ }