@prunellejs/i18n 0.0.0-stage → 0.5.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/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.2",
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.2"
25
+ }
26
+ }
package/src/index.ts ADDED
@@ -0,0 +1,253 @@
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 INTERNAL_HREF_RE = /<a\b([^>]*?)\bhref="(\/[^"]*)"([^>]*)>/gi
29
+
30
+ function collapseLeadingSlashes(p: string): string {
31
+ if (!p)
32
+ return '/'
33
+ const collapsed = p.replace(/^\/+/, '/')
34
+ return collapsed.startsWith('/') ? collapsed : `/${collapsed}`
35
+ }
36
+
37
+ export function stripLocalePrefix(pathname: string, locales: readonly string[]): { locale: string | undefined, path: string } {
38
+ const normalized = collapseLeadingSlashes(pathname)
39
+ const parts = normalized.split('/')
40
+ const first = parts[1]
41
+ if (first !== undefined && locales.includes(first)) {
42
+ const rest = collapseLeadingSlashes(`/${parts.slice(2).join('/')}`)
43
+ return { locale: first, path: rest === '/' ? '/' : rest.replace(/\/+$/, '') || '/' }
44
+ }
45
+ return { locale: undefined, path: normalized }
46
+ }
47
+
48
+ export function localizePath(
49
+ pathname: string,
50
+ targetLocale: string,
51
+ defaultLocale: string,
52
+ locales: readonly string[],
53
+ prefixDefault = false,
54
+ ): string {
55
+ const { path } = stripLocalePrefix(pathname, locales)
56
+ const safePath = collapseLeadingSlashes(path)
57
+ if (targetLocale === defaultLocale && !prefixDefault)
58
+ return safePath
59
+ return safePath === '/' ? `/${targetLocale}` : `/${targetLocale}${safePath}`
60
+ }
61
+
62
+ export function alternateLinks(
63
+ pathname: string,
64
+ options: { site?: string | undefined, locales: readonly string[], defaultLocale: string, prefixDefault?: boolean | undefined },
65
+ ): Array<{ locale: string, href: string }> {
66
+ const origin = options.site ? options.site.replace(/\/$/, '') : ''
67
+ return options.locales.map(loc => ({
68
+ locale: loc,
69
+ href: `${origin}${localizePath(pathname, loc, options.defaultLocale, options.locales, options.prefixDefault)}`,
70
+ }))
71
+ }
72
+
73
+ export function formatDate(
74
+ value: Date | string | number,
75
+ locale: string,
76
+ options: Intl.DateTimeFormatOptions = { dateStyle: 'long' },
77
+ ): string {
78
+ const d = value instanceof Date ? value : new Date(value)
79
+ return new Intl.DateTimeFormat(locale, options).format(d)
80
+ }
81
+
82
+ export function formatNumber(
83
+ value: number,
84
+ locale: string,
85
+ options?: Intl.NumberFormatOptions,
86
+ ): string {
87
+ return new Intl.NumberFormat(locale, options).format(value)
88
+ }
89
+
90
+ export function i18n(options: I18nOptions): PrunellePlugin {
91
+ const { locales, defaultLocale, messages = {}, prefixDefault = false } = options
92
+ let activeSite = options.site?.replace(/\/$/, '')
93
+ let activeAssetPrefix = '/_pru'
94
+ const localeSet = new Set(locales)
95
+ const sharedConfig: ActiveI18nConfig = { locales, defaultLocale, prefixDefault }
96
+
97
+ function translate(locale: string, key: string): string {
98
+ return messages[locale]?.[key] ?? messages[defaultLocale]?.[key] ?? key
99
+ }
100
+
101
+ function* missingKeys(): Generator<{ locale: string, key: string }> {
102
+ const baseKeys = Object.keys(messages[defaultLocale] ?? {})
103
+ for (const locale of locales) {
104
+ if (locale === defaultLocale)
105
+ continue
106
+ const dict = messages[locale] ?? {}
107
+ for (const key of baseKeys) {
108
+ if (!(key in dict))
109
+ yield { locale, key }
110
+ }
111
+ }
112
+ }
113
+
114
+ return definePlugin({
115
+ name: '@prunellejs/i18n',
116
+ enforce: 'pre',
117
+ providesLocals: ['locale', 't', 'localize', 'alternates'],
118
+
119
+ build(ctx) {
120
+ if (options.site === undefined && ctx.site !== undefined)
121
+ activeSite = ctx.site.replace(/\/$/, '')
122
+ if (ctx.assetPrefix)
123
+ activeAssetPrefix = ctx.assetPrefix.replace(/\/+$/, '') || '/_pru'
124
+ ctx.provide(I18N_CONFIG_SERVICE, sharedConfig)
125
+ },
126
+
127
+ server(api) {
128
+ if (options.site === undefined && api.site !== undefined)
129
+ activeSite = api.site.replace(/\/$/, '')
130
+ if (api.assetPrefix)
131
+ activeAssetPrefix = api.assetPrefix.replace(/\/+$/, '') || '/_pru'
132
+ const assetPrefixSlash = `${activeAssetPrefix}/`
133
+ const actionPrefix = `${assetPrefixSlash}action/`
134
+ const trustedOrigins = api.trustedOrigins.length > 0 ? new Set(api.trustedOrigins) : undefined
135
+ api.provide(I18N_CONFIG_SERVICE, sharedConfig)
136
+
137
+ // Rewrite /fr/about -> /about and attach locale + helpers onto ctx.locals
138
+ api.rewrite((pathname, ctx) => {
139
+ const stripped = stripLocalePrefix(pathname, locales)
140
+ let matched = stripped.locale
141
+ let path = stripped.path
142
+ // Server action URLs live under <assetPrefix>/action/<id> without a locale prefix; recover locale from trusted Referer.
143
+ if (matched === undefined && pathname.startsWith(actionPrefix)) {
144
+ const referer = ctx.request.headers.get('referer')
145
+ if (referer !== null && URL.canParse(referer)) {
146
+ const refUrl = new URL(referer)
147
+ if (isTrustedOrigin(refUrl.origin, ctx.request, trustedOrigins, api.trustProxy, ctx.url)) {
148
+ const fromRef = stripLocalePrefix(refUrl.pathname, locales)
149
+ matched = fromRef.locale
150
+ path = fromRef.path
151
+ }
152
+ }
153
+ }
154
+ const active = matched ?? defaultLocale
155
+ ctx.locals.locale = active
156
+ ctx.locals.t = (key: string) => translate(active, key)
157
+ ctx.locals.localize = (p: string, target = active) => localizePath(p, target, defaultLocale, locales, prefixDefault)
158
+ ctx.locals.alternates = () => alternateLinks(path, { site: activeSite, locales, defaultLocale, prefixDefault })
159
+ return stripped.locale !== undefined ? stripped.path : undefined
160
+ })
161
+
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
+ }
185
+
186
+ api.route('GET', '/_i18n/locales', ctx =>
187
+ ctx.json({ locales, defaultLocale, current: ctx.locals.locale ?? defaultLocale }))
188
+ },
189
+
190
+ prerenderPaths(paths) {
191
+ const out = new Set<string>()
192
+ for (const raw of paths) {
193
+ if (stripLocalePrefix(raw, locales).locale !== undefined) {
194
+ out.add(raw)
195
+ continue
196
+ }
197
+ for (const loc of locales)
198
+ out.add(localizePath(raw, loc, defaultLocale, locales, prefixDefault))
199
+ }
200
+ return [...out]
201
+ },
202
+
203
+ head(head, ctx) {
204
+ const locale = ctx.locals.locale ?? defaultLocale
205
+ head.lang = locale
206
+
207
+ if (activeSite) {
208
+ const { path } = stripLocalePrefix(ctx.url.pathname, locales)
209
+ const links = alternateLinks(path, { site: activeSite, locales, defaultLocale, prefixDefault })
210
+ for (const l of links)
211
+ head.add(`<link rel="alternate" hreflang="${escAttr(l.locale)}" href="${escAttr(l.href)}">`)
212
+ }
213
+ },
214
+
215
+ transformHtml(html, ctx) {
216
+ const locale = ctx.locals.locale ?? defaultLocale
217
+ // Prefix internal <a href="/..."> links for non-default locales only
218
+ if (locale === defaultLocale && !prefixDefault)
219
+ 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
+ })
234
+ },
235
+
236
+ check(ctx) {
237
+ for (const { locale, key } of missingKeys())
238
+ ctx.error(`[i18n] ${locale}: missing translation key "${key}"`)
239
+ },
240
+
241
+ commands: {
242
+ 'i18n-check': () => {
243
+ let missing = 0
244
+ for (const { locale, key } of missingKeys()) {
245
+ console.log(`[i18n] ${locale}: missing "${key}"`)
246
+ missing++
247
+ }
248
+ if (missing === 0)
249
+ console.log('[i18n] all locales complete')
250
+ },
251
+ },
252
+ })
253
+ }
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.