@prunellejs/i18n 0.1.1 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (4) hide show
  1. package/LICENSE +21 -0
  2. package/llms.txt +4 -1
  3. package/package.json +2 -2
  4. package/src/index.ts +143 -39
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.0",
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.0"
25
25
  }
26
26
  }
package/src/index.ts CHANGED
@@ -25,7 +25,86 @@ export interface I18nOptions {
25
25
  site?: string | undefined
26
26
  }
27
27
 
28
- const INTERNAL_HREF_RE = /<a\b([^>]*?)\bhref="(\/[^"]*)"([^>]*)>/gi
28
+ const HTML_TOKEN_RE = /<(\/?)(pre|code|textarea)(?=[\s>/])[^>]*>|<a(?=[\s>/])((?:[^>"']|"[^"]*"|'[^']*')*)>/gi
29
+ // One attribute of a start tag: its leading space, its name, and the value when it is quoted.
30
+ const ATTR_RE = /(\s)([^\s"'<>/=]+)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'))?/g
31
+ const NO_LOCALIZE_RE = /\sdata-no-localize(?=[\s=/]|$)/i
32
+ 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
33
+
34
+ function isSkippedI18nPath(pathname: string, assetPrefix: string, assetPrefixSlash: string): boolean {
35
+ return pathname === assetPrefix
36
+ || pathname.startsWith(assetPrefixSlash)
37
+ || pathname === '/_i18n'
38
+ || pathname.startsWith('/_i18n/')
39
+ || pathname === '/api'
40
+ || pathname.startsWith('/api/')
41
+ || pathname === '/auth'
42
+ || pathname.startsWith('/auth/')
43
+ || NON_HTML_EXT_RE.test(pathname)
44
+ }
45
+
46
+ function localizeHtmlLinks(
47
+ html: string,
48
+ locale: string,
49
+ localeSet: ReadonlySet<string>,
50
+ assetPrefix: string,
51
+ ): string {
52
+ const assetPrefixSlash = `${assetPrefix}/`
53
+ const escapedLocale = escAttr(locale)
54
+ let inTextarea = false
55
+ let codePreDepth = 0
56
+ HTML_TOKEN_RE.lastIndex = 0
57
+ const localizeHref = (href: string): string | undefined => {
58
+ if (!href.startsWith('/') || href.startsWith('//'))
59
+ return undefined
60
+ const cut = href.search(/[?#]/)
61
+ const pathOnly = cut === -1 ? href : href.slice(0, cut)
62
+ if (isSkippedI18nPath(pathOnly, assetPrefix, assetPrefixSlash))
63
+ return undefined
64
+ const seg = pathOnly.slice(1).split('/', 1)[0]
65
+ if (seg !== undefined && localeSet.has(seg))
66
+ return undefined
67
+ // `href` is already extracted from a quoted HTML attribute; only escape the prepended locale segment to avoid double-escaping `&amp;`.
68
+ return href === '/' ? `/${escapedLocale}` : `/${escapedLocale}${href}`
69
+ }
70
+ return html.replace(
71
+ HTML_TOKEN_RE,
72
+ (match, slash: string | undefined, skipTag: string | undefined, attrs: string | undefined) => {
73
+ if (skipTag !== undefined) {
74
+ const tag = skipTag.toLowerCase()
75
+ const isClosing = slash === '/'
76
+ const isSelfClosing = !isClosing && match.endsWith('/>')
77
+ if (inTextarea) {
78
+ if (isClosing && tag === 'textarea')
79
+ inTextarea = false
80
+ }
81
+ else if (tag === 'textarea') {
82
+ if (!isClosing && !isSelfClosing)
83
+ inTextarea = true
84
+ }
85
+ else if (isClosing) {
86
+ if (codePreDepth > 0)
87
+ codePreDepth--
88
+ }
89
+ else if (!isSelfClosing) {
90
+ codePreDepth++
91
+ }
92
+ return match
93
+ }
94
+ if (inTextarea || codePreDepth > 0 || attrs === undefined || NO_LOCALIZE_RE.test(attrs))
95
+ return match
96
+ const rewritten = attrs.replace(ATTR_RE, (attr, space: string, name: string, double: string | undefined, single: string | undefined) => {
97
+ const value = double ?? single
98
+ const next = name.toLowerCase() === 'href' && value !== undefined ? localizeHref(value) : undefined
99
+ if (next === undefined)
100
+ return attr
101
+ const quote = double !== undefined ? '"' : "'"
102
+ return `${space}${name}=${quote}${next}${quote}`
103
+ })
104
+ return `<a${rewritten}>`
105
+ },
106
+ )
107
+ }
29
108
 
30
109
  function collapseLeadingSlashes(p: string): string {
31
110
  if (!p)
@@ -87,7 +166,33 @@ export function formatNumber(
87
166
  return new Intl.NumberFormat(locale, options).format(value)
88
167
  }
89
168
 
169
+ const LOCALE_TAG_RE = /^[a-z]{2,3}(?:-[a-z0-9]{2,8})*$/i
170
+
171
+ function validateOptions({ locales, defaultLocale }: I18nOptions): void {
172
+ const fail = (what: string, fix: string): never => {
173
+ throw new Error(`@prunellejs/i18n: ${what}: ${fix}.`)
174
+ }
175
+ if (locales.length === 0)
176
+ fail('locales is empty', "list at least one locale tag, for example locales: ['en']")
177
+ const seen = new Set<string>()
178
+ for (const loc of locales) {
179
+ if (!LOCALE_TAG_RE.test(loc))
180
+ fail(`"${loc}" is not a valid locale tag`, "use a BCP 47 tag such as 'en' or 'fr-CA'")
181
+ if (seen.has(loc))
182
+ fail(`locale "${loc}" is listed twice`, 'remove the duplicate from locales')
183
+ seen.add(loc)
184
+ }
185
+ if (!seen.has(defaultLocale))
186
+ fail(`defaultLocale "${defaultLocale}" is not in locales`, 'add it to locales or pick one of them')
187
+ }
188
+
189
+ /** A successful HTML page, as opposed to a plugin or API route answering JSON, XML or a stream, or a 404. */
190
+ function isHtmlPage(res: Response): boolean {
191
+ return res.status >= 200 && res.status < 300 && (res.headers.get('content-type') ?? '').startsWith('text/html')
192
+ }
193
+
90
194
  export function i18n(options: I18nOptions): PrunellePlugin {
195
+ validateOptions(options)
91
196
  const { locales, defaultLocale, messages = {}, prefixDefault = false } = options
92
197
  let activeSite = options.site?.replace(/\/$/, '')
93
198
  let activeAssetPrefix = '/_pru'
@@ -159,29 +264,36 @@ export function i18n(options: I18nOptions): PrunellePlugin {
159
264
  return stripped.locale !== undefined ? stripped.path : undefined
160
265
  })
161
266
 
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')
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))
167
280
  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
- }
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' })
185
297
 
186
298
  api.route('GET', '/_i18n/locales', ctx =>
187
299
  ctx.json({ locales, defaultLocale, current: ctx.locals.locale ?? defaultLocale }))
@@ -190,8 +302,10 @@ export function i18n(options: I18nOptions): PrunellePlugin {
190
302
  prerenderPaths(paths) {
191
303
  const out = new Set<string>()
192
304
  for (const raw of paths) {
193
- if (stripLocalePrefix(raw, locales).locale !== undefined) {
194
- out.add(raw)
305
+ const { locale } = stripLocalePrefix(raw, locales)
306
+ if (locale !== undefined) {
307
+ // The default locale is only ever served unprefixed when prefixDefault is off: `/en/x` is a redirect, never a page.
308
+ out.add(locale === defaultLocale && !prefixDefault ? localizePath(raw, locale, defaultLocale, locales, false) : raw)
195
309
  continue
196
310
  }
197
311
  for (const loc of locales)
@@ -209,6 +323,9 @@ export function i18n(options: I18nOptions): PrunellePlugin {
209
323
  const links = alternateLinks(path, { site: activeSite, locales, defaultLocale, prefixDefault })
210
324
  for (const l of links)
211
325
  head.add(`<link rel="alternate" hreflang="${escAttr(l.locale)}" href="${escAttr(l.href)}">`)
326
+ const base = links.find(l => l.locale === defaultLocale)
327
+ if (base !== undefined)
328
+ head.add(`<link rel="alternate" hreflang="x-default" href="${escAttr(base.href)}">`)
212
329
  }
213
330
  },
214
331
 
@@ -217,20 +334,7 @@ export function i18n(options: I18nOptions): PrunellePlugin {
217
334
  // Prefix internal <a href="/..."> links for non-default locales only
218
335
  if (locale === defaultLocale && !prefixDefault)
219
336
  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
- })
337
+ return localizeHtmlLinks(html, locale, localeSet, activeAssetPrefix)
234
338
  },
235
339
 
236
340
  check(ctx) {