@prunellejs/i18n 0.0.0-stage → 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 ADDED
@@ -0,0 +1,63 @@
1
+ # @prunellejs/i18n Reference
2
+
3
+ > Locale URL rewriting, dictionary translation, `<html lang>`, automatic internal link prefixing, `hreflang` alternates, localized prerendering, `Intl` formatters, and missing-key checks.
4
+
5
+ ## Imports
6
+
7
+ - `@prunellejs/i18n`: `i18n`, `stripLocalePrefix`, `localizePath`, `alternateLinks`, `formatDate`, `formatNumber`; type `I18nOptions`.
8
+
9
+ ## Plugin Setup (`i18n(options)`)
10
+
11
+ - `locales`: `string[]` (e.g. `['en', 'fr']`).
12
+ - `defaultLocale`: `string` (e.g. `'en'`).
13
+ - `messages`: `Record<locale, Record<key, string>>` (optional; falls back to `defaultLocale`, then returns `key`).
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>`.
16
+
17
+ ## Mounted Routes, Rewriting & `ctx.locals`
18
+
19
+ - Request rewrite: strips `/<locale>` prefix (e.g. `/fr/about` → `/about`) before routing and populates `ctx.locals`:
20
+ - `ctx.locals.locale`: active locale string
21
+ - `ctx.locals.t(key)`: translate string for active locale
22
+ - `ctx.locals.localize(path, targetLocale?)`: build localized path
23
+ - `ctx.locals.alternates()`: `Array<{ locale, href }>` for the current page
24
+ - Mounted route: `GET /_i18n/locales` → `{ locales, defaultLocale, current }`.
25
+ - HTML & build integration:
26
+ - Sets `<html lang={locale}>` and `hreflang` links in `head()`.
27
+ - 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
+ - Expands `prerenderPaths` across all configured locales and shares `I18N_CONFIG_SERVICE` with `@prunellejs/seo` for multilingual `sitemap.xml`.
29
+ - Checks & CLI: `prunelle check` fails on translation keys missing vs `defaultLocale`; `prunelle i18n-check` prints missing keys.
30
+
31
+ ## Helpers
32
+
33
+ - `localizePath(pathname, targetLocale, defaultLocale, locales, prefixDefault?)`
34
+ - `stripLocalePrefix(pathname, locales)` → `{ locale, path }`
35
+ - `alternateLinks(pathname, { site?, locales, defaultLocale, prefixDefault? })`
36
+ - `formatDate(value, locale, options?)`, `formatNumber(value, locale, options?)`
37
+
38
+ ## Snippets
39
+
40
+ ```ts
41
+ // prunelle.config.ts
42
+ import { i18n } from '@prunellejs/i18n'
43
+ import { defineConfig } from 'prunelle/config'
44
+
45
+ export default defineConfig({
46
+ site: 'https://example.com',
47
+ plugins: [i18n({ locales: ['en', 'fr'], defaultLocale: 'en', messages: { en: { hello: 'Hello' }, fr: { hello: 'Bonjour' } } })],
48
+ })
49
+ ```
50
+
51
+ ```tsx
52
+ // src/routes/index.tsx
53
+ import type { PageProps } from 'prunelle'
54
+
55
+ export default function Home({ locals }: PageProps) {
56
+ return (
57
+ <main>
58
+ <h1>{locals.t?.('hello')}</h1>
59
+ <a href={locals.localize?.('/', 'fr')} data-no-localize>Français</a>
60
+ </main>
61
+ )
62
+ }
63
+ ```
package/package.json CHANGED
@@ -1,6 +1,26 @@
1
1
  {
2
2
  "name": "@prunellejs/i18n",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.5.3",
4
+ "description": "Locale URL rewriting and dictionary internationalization plugin for Prunelle",
5
+ "license": "MIT",
6
+ "type": "module",
7
+ "sideEffects": false,
8
+ "files": [
9
+ "src",
10
+ "llms.txt"
11
+ ],
12
+ "exports": {
13
+ ".": "./src/index.ts"
14
+ },
15
+ "engines": {
16
+ "bun": ">=1.4.0"
17
+ },
18
+ "repository": {
19
+ "type": "git",
20
+ "url": "https://github.com/Kayno0o/prunelle",
21
+ "directory": "packages/plugin-i18n"
22
+ },
23
+ "peerDependencies": {
24
+ "prunelle": "^0.5.3"
25
+ }
26
+ }
package/src/index.ts ADDED
@@ -0,0 +1,300 @@
1
+ // @prunellejs/i18n — opt-in locale routing, <html lang> & link rewriting, localized prerendering,
2
+ // hreflang alternates, Intl formatters, and CLI missing-key check.
3
+ // Implemented 100% through PrunellePlugin public hooks — zero i18n logic in @prunellejs/core.
4
+
5
+ import type { ActiveI18nConfig, PrunellePlugin } from 'prunelle/config'
6
+ import { definePlugin, I18N_CONFIG_SERVICE } from 'prunelle/config'
7
+ import { escAttr, isTrustedOrigin } from 'prunelle/server'
8
+
9
+ declare module 'prunelle/server' {
10
+ interface PrunelleLocals {
11
+ locale?: string | undefined
12
+ t?: ((key: string) => string) | undefined
13
+ localize?: ((path: string, targetLocale?: string) => string) | undefined
14
+ alternates?: (() => Array<{ locale: string, href: string }>) | undefined
15
+ }
16
+ }
17
+
18
+ export interface I18nOptions {
19
+ locales: string[]
20
+ defaultLocale: string
21
+ messages?: Record<string, Record<string, string>> | undefined
22
+ /** Prefix URLs for default locale too (default: false). */
23
+ prefixDefault?: boolean | undefined
24
+ /** Optional site origin (e.g. 'https://example.com') to auto-inject <link rel="alternate" hreflang="..."> tags. */
25
+ site?: string | undefined
26
+ }
27
+
28
+ const HTML_TOKEN_RE = /<(\/?)(pre|code|textarea)(?=[\s>/])[^>]*>|<a\b([^>]*?)\bhref="(\/[^"]*)"([^>]*)>/gi
29
+ 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
30
+
31
+ function isSkippedI18nPath(pathname: string, assetPrefix: string, assetPrefixSlash: string): boolean {
32
+ return pathname === assetPrefix
33
+ || pathname.startsWith(assetPrefixSlash)
34
+ || pathname === '/_i18n'
35
+ || pathname.startsWith('/_i18n/')
36
+ || pathname === '/api'
37
+ || pathname.startsWith('/api/')
38
+ || pathname === '/auth'
39
+ || pathname.startsWith('/auth/')
40
+ || NON_HTML_EXT_RE.test(pathname)
41
+ }
42
+
43
+ function localizeHtmlLinks(
44
+ html: string,
45
+ locale: string,
46
+ localeSet: ReadonlySet<string>,
47
+ assetPrefix: string,
48
+ ): string {
49
+ const assetPrefixSlash = `${assetPrefix}/`
50
+ const escapedLocale = escAttr(locale)
51
+ let inTextarea = false
52
+ let codePreDepth = 0
53
+ HTML_TOKEN_RE.lastIndex = 0
54
+ return html.replace(
55
+ HTML_TOKEN_RE,
56
+ (match, slash: string | undefined, skipTag: string | undefined, before: string | undefined, href: string | undefined, after: string | undefined) => {
57
+ if (skipTag !== undefined) {
58
+ const tag = skipTag.toLowerCase()
59
+ const isClosing = slash === '/'
60
+ const isSelfClosing = !isClosing && match.endsWith('/>')
61
+ if (inTextarea) {
62
+ if (isClosing && tag === 'textarea')
63
+ inTextarea = false
64
+ }
65
+ else if (tag === 'textarea') {
66
+ if (!isClosing && !isSelfClosing)
67
+ inTextarea = true
68
+ }
69
+ else if (isClosing) {
70
+ if (codePreDepth > 0)
71
+ codePreDepth--
72
+ }
73
+ else if (!isSelfClosing) {
74
+ codePreDepth++
75
+ }
76
+ return match
77
+ }
78
+ if (inTextarea || codePreDepth > 0 || href === undefined)
79
+ return match
80
+ const pre = before ?? ''
81
+ const post = after ?? ''
82
+ if (pre.includes('data-no-localize') || post.includes('data-no-localize') || href.startsWith('//'))
83
+ return match
84
+ const cut = href.search(/[?#]/)
85
+ const pathOnly = cut === -1 ? href : href.slice(0, cut)
86
+ if (isSkippedI18nPath(pathOnly, assetPrefix, assetPrefixSlash))
87
+ return match
88
+ const seg = pathOnly.slice(1).split('/', 1)[0]
89
+ if (seg !== undefined && localeSet.has(seg))
90
+ return match
91
+ // `href` is already extracted from a double-quoted HTML attribute; only escape the prepended locale segment to avoid double-escaping `&amp;`.
92
+ const prefixed = href === '/' ? `/${escapedLocale}` : `/${escapedLocale}${href}`
93
+ return `<a${pre}href="${prefixed}"${post}>`
94
+ },
95
+ )
96
+ }
97
+
98
+ function collapseLeadingSlashes(p: string): string {
99
+ if (!p)
100
+ return '/'
101
+ const collapsed = p.replace(/^\/+/, '/')
102
+ return collapsed.startsWith('/') ? collapsed : `/${collapsed}`
103
+ }
104
+
105
+ export function stripLocalePrefix(pathname: string, locales: readonly string[]): { locale: string | undefined, path: string } {
106
+ const normalized = collapseLeadingSlashes(pathname)
107
+ const parts = normalized.split('/')
108
+ const first = parts[1]
109
+ if (first !== undefined && locales.includes(first)) {
110
+ const rest = collapseLeadingSlashes(`/${parts.slice(2).join('/')}`)
111
+ return { locale: first, path: rest === '/' ? '/' : rest.replace(/\/+$/, '') || '/' }
112
+ }
113
+ return { locale: undefined, path: normalized }
114
+ }
115
+
116
+ export function localizePath(
117
+ pathname: string,
118
+ targetLocale: string,
119
+ defaultLocale: string,
120
+ locales: readonly string[],
121
+ prefixDefault = false,
122
+ ): string {
123
+ const { path } = stripLocalePrefix(pathname, locales)
124
+ const safePath = collapseLeadingSlashes(path)
125
+ if (targetLocale === defaultLocale && !prefixDefault)
126
+ return safePath
127
+ return safePath === '/' ? `/${targetLocale}` : `/${targetLocale}${safePath}`
128
+ }
129
+
130
+ export function alternateLinks(
131
+ pathname: string,
132
+ options: { site?: string | undefined, locales: readonly string[], defaultLocale: string, prefixDefault?: boolean | undefined },
133
+ ): Array<{ locale: string, href: string }> {
134
+ const origin = options.site ? options.site.replace(/\/$/, '') : ''
135
+ return options.locales.map(loc => ({
136
+ locale: loc,
137
+ href: `${origin}${localizePath(pathname, loc, options.defaultLocale, options.locales, options.prefixDefault)}`,
138
+ }))
139
+ }
140
+
141
+ export function formatDate(
142
+ value: Date | string | number,
143
+ locale: string,
144
+ options: Intl.DateTimeFormatOptions = { dateStyle: 'long' },
145
+ ): string {
146
+ const d = value instanceof Date ? value : new Date(value)
147
+ return new Intl.DateTimeFormat(locale, options).format(d)
148
+ }
149
+
150
+ export function formatNumber(
151
+ value: number,
152
+ locale: string,
153
+ options?: Intl.NumberFormatOptions,
154
+ ): string {
155
+ return new Intl.NumberFormat(locale, options).format(value)
156
+ }
157
+
158
+ export function i18n(options: I18nOptions): PrunellePlugin {
159
+ const { locales, defaultLocale, messages = {}, prefixDefault = false } = options
160
+ let activeSite = options.site?.replace(/\/$/, '')
161
+ let activeAssetPrefix = '/_pru'
162
+ const localeSet = new Set(locales)
163
+ const sharedConfig: ActiveI18nConfig = { locales, defaultLocale, prefixDefault }
164
+
165
+ function translate(locale: string, key: string): string {
166
+ return messages[locale]?.[key] ?? messages[defaultLocale]?.[key] ?? key
167
+ }
168
+
169
+ function* missingKeys(): Generator<{ locale: string, key: string }> {
170
+ const baseKeys = Object.keys(messages[defaultLocale] ?? {})
171
+ for (const locale of locales) {
172
+ if (locale === defaultLocale)
173
+ continue
174
+ const dict = messages[locale] ?? {}
175
+ for (const key of baseKeys) {
176
+ if (!(key in dict))
177
+ yield { locale, key }
178
+ }
179
+ }
180
+ }
181
+
182
+ return definePlugin({
183
+ name: '@prunellejs/i18n',
184
+ enforce: 'pre',
185
+ providesLocals: ['locale', 't', 'localize', 'alternates'],
186
+
187
+ build(ctx) {
188
+ if (options.site === undefined && ctx.site !== undefined)
189
+ activeSite = ctx.site.replace(/\/$/, '')
190
+ if (ctx.assetPrefix)
191
+ activeAssetPrefix = ctx.assetPrefix.replace(/\/+$/, '') || '/_pru'
192
+ ctx.provide(I18N_CONFIG_SERVICE, sharedConfig)
193
+ },
194
+
195
+ server(api) {
196
+ if (options.site === undefined && api.site !== undefined)
197
+ activeSite = api.site.replace(/\/$/, '')
198
+ if (api.assetPrefix)
199
+ activeAssetPrefix = api.assetPrefix.replace(/\/+$/, '') || '/_pru'
200
+ const assetPrefixSlash = `${activeAssetPrefix}/`
201
+ const actionPrefix = `${assetPrefixSlash}action/`
202
+ const trustedOrigins = api.trustedOrigins.length > 0 ? new Set(api.trustedOrigins) : undefined
203
+ api.provide(I18N_CONFIG_SERVICE, sharedConfig)
204
+
205
+ // Rewrite /fr/about -> /about and attach locale + helpers onto ctx.locals
206
+ api.rewrite((pathname, ctx) => {
207
+ const stripped = stripLocalePrefix(pathname, locales)
208
+ let matched = stripped.locale
209
+ let path = stripped.path
210
+ // Server action URLs live under <assetPrefix>/action/<id> without a locale prefix; recover locale from trusted Referer.
211
+ if (matched === undefined && pathname.startsWith(actionPrefix)) {
212
+ const referer = ctx.request.headers.get('referer')
213
+ if (referer !== null && URL.canParse(referer)) {
214
+ const refUrl = new URL(referer)
215
+ if (isTrustedOrigin(refUrl.origin, ctx.request, trustedOrigins, api.trustProxy, ctx.url)) {
216
+ const fromRef = stripLocalePrefix(refUrl.pathname, locales)
217
+ matched = fromRef.locale
218
+ path = fromRef.path
219
+ }
220
+ }
221
+ }
222
+ const active = matched ?? defaultLocale
223
+ ctx.locals.locale = active
224
+ ctx.locals.t = (key: string) => translate(active, key)
225
+ ctx.locals.localize = (p: string, target = active) => localizePath(p, target, defaultLocale, locales, prefixDefault)
226
+ ctx.locals.alternates = () => alternateLinks(path, { site: activeSite, locales, defaultLocale, prefixDefault })
227
+ return stripped.locale !== undefined ? stripped.path : undefined
228
+ })
229
+
230
+ if (prefixDefault) {
231
+ // Every prerendered path carries a locale prefix (`prerenderPaths`), so prerendered pages skip this redirect.
232
+ api.use((ctx, next) => {
233
+ const method = ctx.request.method
234
+ if (method !== 'GET' && method !== 'HEAD')
235
+ return next()
236
+ const rawPath = ctx.url.pathname
237
+ if (isSkippedI18nPath(rawPath, activeAssetPrefix, assetPrefixSlash))
238
+ return next()
239
+ if (stripLocalePrefix(rawPath, locales).locale !== undefined)
240
+ return next()
241
+ const target = localizePath(rawPath, defaultLocale, defaultLocale, locales, true)
242
+ return ctx.redirect(`${target}${ctx.url.search}`, 302)
243
+ }, { scope: 'rendered' })
244
+ }
245
+
246
+ api.route('GET', '/_i18n/locales', ctx =>
247
+ ctx.json({ locales, defaultLocale, current: ctx.locals.locale ?? defaultLocale }))
248
+ },
249
+
250
+ prerenderPaths(paths) {
251
+ const out = new Set<string>()
252
+ for (const raw of paths) {
253
+ if (stripLocalePrefix(raw, locales).locale !== undefined) {
254
+ out.add(raw)
255
+ continue
256
+ }
257
+ for (const loc of locales)
258
+ out.add(localizePath(raw, loc, defaultLocale, locales, prefixDefault))
259
+ }
260
+ return [...out]
261
+ },
262
+
263
+ head(head, ctx) {
264
+ const locale = ctx.locals.locale ?? defaultLocale
265
+ head.lang = locale
266
+
267
+ if (activeSite) {
268
+ const { path } = stripLocalePrefix(ctx.url.pathname, locales)
269
+ const links = alternateLinks(path, { site: activeSite, locales, defaultLocale, prefixDefault })
270
+ for (const l of links)
271
+ head.add(`<link rel="alternate" hreflang="${escAttr(l.locale)}" href="${escAttr(l.href)}">`)
272
+ }
273
+ },
274
+
275
+ transformHtml(html, ctx) {
276
+ const locale = ctx.locals.locale ?? defaultLocale
277
+ // Prefix internal <a href="/..."> links for non-default locales only
278
+ if (locale === defaultLocale && !prefixDefault)
279
+ return html
280
+ return localizeHtmlLinks(html, locale, localeSet, activeAssetPrefix)
281
+ },
282
+
283
+ check(ctx) {
284
+ for (const { locale, key } of missingKeys())
285
+ ctx.error(`[i18n] ${locale}: missing translation key "${key}"`)
286
+ },
287
+
288
+ commands: {
289
+ 'i18n-check': () => {
290
+ let missing = 0
291
+ for (const { locale, key } of missingKeys()) {
292
+ console.log(`[i18n] ${locale}: missing "${key}"`)
293
+ missing++
294
+ }
295
+ if (missing === 0)
296
+ console.log('[i18n] all locales complete')
297
+ },
298
+ },
299
+ })
300
+ }
package/README.md DELETED
@@ -1,3 +0,0 @@
1
- # Temporary Holding Version
2
-
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.