@hamur/i18n 0.0.0-stage → 0.0.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.
- package/LICENSE +22 -0
- package/README.md +38 -2
- package/dist/chunks/bun-index-1ve1hj66.js +744 -0
- package/dist/chunks/bun-index-8bw4xpv8.js +93 -0
- package/dist/chunks/bun-index-ej6vjnjs.js +297 -0
- package/dist/chunks/bun-index-pdepkyy1.js +474 -0
- package/dist/src/adapters/angular.js +67 -0
- package/dist/src/adapters/html.js +34 -0
- package/dist/src/adapters/preact.js +23 -0
- package/dist/src/adapters/react.js +23 -0
- package/dist/src/adapters/solid.js +48 -0
- package/dist/src/adapters/svelte.js +74 -0
- package/dist/src/adapters/vue.js +48 -0
- package/dist/src/cli.js +1898 -0
- package/dist/src/index.js +2755 -0
- package/dist/src/load.js +35 -0
- package/dist/src/server/index.js +395 -0
- package/dist/types/src/adapters/angular.d.ts +17 -0
- package/dist/types/src/adapters/bind.d.ts +44 -0
- package/dist/types/src/adapters/html.d.ts +5 -0
- package/dist/types/src/adapters/preact.d.ts +6 -0
- package/dist/types/src/adapters/react.d.ts +6 -0
- package/dist/types/src/adapters/solid.d.ts +9 -0
- package/dist/types/src/adapters/svelte.d.ts +12 -0
- package/dist/types/src/adapters/vue.d.ts +8 -0
- package/dist/types/src/build/catalog.d.ts +5 -0
- package/dist/types/src/build/drop.d.ts +12 -0
- package/dist/types/src/build/extract.d.ts +11 -0
- package/dist/types/src/build/head.d.ts +4 -0
- package/dist/types/src/build/messages.d.ts +27 -0
- package/dist/types/src/build/prerender.d.ts +10 -0
- package/dist/types/src/build/routes.d.ts +14 -0
- package/dist/types/src/build/split.d.ts +37 -0
- package/dist/types/src/build/types.d.ts +15 -0
- package/dist/types/src/cli.d.ts +12 -0
- package/dist/types/src/compiler/compile.d.ts +17 -0
- package/dist/types/src/compiler/mf2-parse.d.ts +62 -0
- package/dist/types/src/compiler/mf2.d.ts +3 -0
- package/dist/types/src/compiler/parse.d.ts +58 -0
- package/dist/types/src/compiler/skeleton.d.ts +7 -0
- package/dist/types/src/index.d.ts +2 -0
- package/dist/types/src/load.d.ts +7 -0
- package/dist/types/src/module.d.ts +15 -0
- package/dist/types/src/options.d.ts +7 -0
- package/dist/types/src/runtime/catalog-client.d.ts +3 -0
- package/dist/types/src/runtime/catalog-loader.d.ts +15 -0
- package/dist/types/src/runtime/catalog-server.d.ts +5 -0
- package/dist/types/src/runtime/catalog.d.ts +60 -0
- package/dist/types/src/runtime/chain.d.ts +3 -0
- package/dist/types/src/runtime/format.d.ts +27 -0
- package/dist/types/src/runtime/head.d.ts +9 -0
- package/dist/types/src/runtime/interpret.d.ts +20 -0
- package/dist/types/src/runtime/link.d.ts +8 -0
- package/dist/types/src/runtime/locale.d.ts +73 -0
- package/dist/types/src/runtime/match.d.ts +54 -0
- package/dist/types/src/runtime/messages.d.ts +42 -0
- package/dist/types/src/runtime/middleware.d.ts +2 -0
- package/dist/types/src/runtime/negotiate.d.ts +9 -0
- package/dist/types/src/runtime/plugin.d.ts +4 -0
- package/dist/types/src/runtime/redirect.d.ts +32 -0
- package/dist/types/src/runtime/rich.d.ts +5 -0
- package/dist/types/src/runtime/translate.d.ts +21 -0
- package/dist/types/src/server/catalog.d.ts +2 -0
- package/dist/types/src/server/context.d.ts +48 -0
- package/dist/types/src/server/door-all-catalog.d.ts +3 -0
- package/dist/types/src/server/door-all.d.ts +2 -0
- package/dist/types/src/server/door-catalog.d.ts +3 -0
- package/dist/types/src/server/door-root-catalog.d.ts +3 -0
- package/dist/types/src/server/door-root.d.ts +2 -0
- package/dist/types/src/server/door.d.ts +2 -0
- package/dist/types/src/server/index.d.ts +7 -0
- package/dist/types/src/server/preferred.d.ts +6 -0
- package/dist/types/src/server/redirect.d.ts +3 -0
- package/dist/types/src/server/setup.d.ts +2 -0
- package/dist/types/src/types.d.ts +163 -0
- package/package.json +122 -4
- package/src/adapters/angular.ts +65 -0
- package/src/adapters/bind.ts +144 -0
- package/src/adapters/html.ts +35 -0
- package/src/adapters/preact.ts +18 -0
- package/src/adapters/react.ts +18 -0
- package/src/adapters/solid.ts +44 -0
- package/src/adapters/svelte.ts +75 -0
- package/src/adapters/test/SveltePage.svelte +18 -0
- package/src/adapters/test/SvelteReporting.svelte +20 -0
- package/src/adapters/test/SvelteRich.svelte +11 -0
- package/src/adapters/test/SvelteRichPlain.svelte +11 -0
- package/src/adapters/test/peer.ts +7 -0
- package/src/adapters/test/preact-client.ts +43 -0
- package/src/adapters/test/preact-page.ts +34 -0
- package/src/adapters/test/preact-rich.ts +9 -0
- package/src/adapters/test/react-client.ts +49 -0
- package/src/adapters/test/react-page.ts +34 -0
- package/src/adapters/test/react-rich.ts +15 -0
- package/src/adapters/test/runtime.ts +104 -0
- package/src/adapters/test/solid-client.ts +33 -0
- package/src/adapters/test/solid-page.ts +30 -0
- package/src/adapters/test/solid-rich.ts +5 -0
- package/src/adapters/test/svelte-client.ts +51 -0
- package/src/adapters/test/svelte-log.ts +2 -0
- package/src/adapters/test/svelte-plugin.ts +20 -0
- package/src/adapters/test/vue-page.ts +26 -0
- package/src/adapters/test/vue-rich.ts +16 -0
- package/src/adapters/vue.ts +44 -0
- package/src/build/catalog.ts +44 -0
- package/src/build/drop.ts +36 -0
- package/src/build/extract.ts +207 -0
- package/src/build/head.ts +10 -0
- package/src/build/messages.ts +347 -0
- package/src/build/prerender.ts +48 -0
- package/src/build/routes.ts +269 -0
- package/src/build/split.ts +240 -0
- package/src/build/types.ts +156 -0
- package/src/cli.ts +25 -0
- package/src/compiler/compile.ts +190 -0
- package/src/compiler/mf2-parse.ts +469 -0
- package/src/compiler/mf2.ts +393 -0
- package/src/compiler/parse.ts +265 -0
- package/src/compiler/skeleton.ts +85 -0
- package/src/env.d.ts +55 -0
- package/src/index.ts +24 -0
- package/src/load.ts +41 -0
- package/src/module.ts +66 -0
- package/src/options.ts +198 -0
- package/src/runtime/catalog-client.ts +28 -0
- package/src/runtime/catalog-loader.ts +28 -0
- package/src/runtime/catalog-server.ts +36 -0
- package/src/runtime/catalog.ts +190 -0
- package/src/runtime/chain.ts +9 -0
- package/src/runtime/format.ts +102 -0
- package/src/runtime/head.ts +57 -0
- package/src/runtime/interpret.ts +504 -0
- package/src/runtime/link.ts +36 -0
- package/src/runtime/locale.ts +392 -0
- package/src/runtime/match.ts +334 -0
- package/src/runtime/messages.ts +129 -0
- package/src/runtime/middleware.ts +32 -0
- package/src/runtime/negotiate.ts +61 -0
- package/src/runtime/plugin.ts +69 -0
- package/src/runtime/redirect.ts +191 -0
- package/src/runtime/rich.ts +21 -0
- package/src/runtime/translate.ts +131 -0
- package/src/server/catalog.ts +11 -0
- package/src/server/context.ts +191 -0
- package/src/server/door-all-catalog.ts +7 -0
- package/src/server/door-all.ts +5 -0
- package/src/server/door-catalog.ts +6 -0
- package/src/server/door-root-catalog.ts +7 -0
- package/src/server/door-root.ts +5 -0
- package/src/server/door.ts +4 -0
- package/src/server/index.ts +11 -0
- package/src/server/preferred.ts +12 -0
- package/src/server/redirect.ts +26 -0
- package/src/server/setup.ts +14 -0
- package/src/types.ts +182 -0
|
@@ -0,0 +1,191 @@
|
|
|
1
|
+
/// <reference path="../env.d.ts" />
|
|
2
|
+
import { defineMiddleware, getCookie, useSiteConfig, type HamurEvent } from "hamur/server"
|
|
3
|
+
import type { LocaleInfo, ResolvedI18nOptions } from "../types.ts"
|
|
4
|
+
import { createMatcher, type Matcher } from "./match.ts"
|
|
5
|
+
import { negotiate } from "./negotiate.ts"
|
|
6
|
+
|
|
7
|
+
export interface RootRedirectConfig {
|
|
8
|
+
locales: LocaleInfo[]
|
|
9
|
+
defaultLocale: string
|
|
10
|
+
strategy: ResolvedI18nOptions["strategy"]
|
|
11
|
+
redirectToDefaultLocale?: boolean
|
|
12
|
+
cookie: string | false
|
|
13
|
+
/** `app.baseURL`, with its trailing `/`. */
|
|
14
|
+
baseURL: string
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
const escapeHtml = (text: string) => text.replace(/[&<>"']/g, (c) => `&#${c.charCodeAt(0)};`)
|
|
18
|
+
const scriptJson = (value: unknown) => JSON.stringify(value).replace(/</g, "\\u003c")
|
|
19
|
+
|
|
20
|
+
/** The same order as `pickLocale` (negotiate.ts), over `navigator.languages`, inlined in the locale root page. */
|
|
21
|
+
const PICK_SCRIPT = `(function(c){var s=function(t){try{return new Intl.Locale(t).language}catch(e){return""}};var l=c.locales,p=null,i,j,k;if(c.cookie){var a=document.cookie.split(";");for(i=0;i<a.length;i++){var e=a[i].indexOf("=");if(e>0&&a[i].slice(0,e).trim()===c.cookie){var v=a[i].slice(e+1).trim();try{v=decodeURIComponent(v)}catch(x){}for(j=0;j<l.length;j++)if(l[j].code===v)p=l[j].code;break}}}var n=navigator.languages||[navigator.language];for(i=0;!p&&i<n.length;i++){var r=String(n[i]).toLowerCase();for(j=0;j<l.length;j++)if(l[j].language.toLowerCase()===r||l[j].code===r){p=l[j].code;break}if(!p){k=s(r);for(j=0;k&&j<l.length;j++)if(s(l[j].language)===k){p=l[j].code;break}}}location.replace(c.base+(p||c.fallback))})`
|
|
22
|
+
|
|
23
|
+
/** The locale root page: the 200 answer of `/` under `prefix` when no locale was found. */
|
|
24
|
+
/** `origin` is `site.url`; a caller that already holds it passes it. */
|
|
25
|
+
export function localeRootPage(
|
|
26
|
+
event: HamurEvent,
|
|
27
|
+
config: RootRedirectConfig,
|
|
28
|
+
origin: string | undefined = useSiteConfig(event).url,
|
|
29
|
+
): string {
|
|
30
|
+
const { baseURL, locales } = config
|
|
31
|
+
const fallback = locales.find((locale) => locale.code === config.defaultLocale)!
|
|
32
|
+
const target = `${baseURL}${fallback.code}`
|
|
33
|
+
const nonce = typeof event.context.nonce === "string" ? ` nonce="${escapeHtml(event.context.nonce)}"` : ""
|
|
34
|
+
const data = {
|
|
35
|
+
locales: locales.map(({ code, language }) => ({ code, language })),
|
|
36
|
+
cookie: config.cookie,
|
|
37
|
+
base: baseURL,
|
|
38
|
+
fallback: fallback.code,
|
|
39
|
+
}
|
|
40
|
+
return [
|
|
41
|
+
"<!DOCTYPE html>",
|
|
42
|
+
`<html lang="${escapeHtml(fallback.language)}">`,
|
|
43
|
+
"<head>",
|
|
44
|
+
'<meta charset="utf-8">',
|
|
45
|
+
`<meta http-equiv="refresh" content="0; url=${escapeHtml(target)}">`,
|
|
46
|
+
...(origin ? [`<link rel="canonical" href="${escapeHtml(origin + target)}">`] : []),
|
|
47
|
+
`<script${nonce}>${PICK_SCRIPT}(${scriptJson(data)})</script>`,
|
|
48
|
+
"</head>",
|
|
49
|
+
"<body>",
|
|
50
|
+
"<ul>",
|
|
51
|
+
...locales.map(
|
|
52
|
+
(locale) =>
|
|
53
|
+
`<li><a href="${escapeHtml(baseURL + locale.code)}" hreflang="${escapeHtml(locale.language)}" lang="${escapeHtml(locale.language)}">${escapeHtml(locale.name)}</a></li>`,
|
|
54
|
+
),
|
|
55
|
+
"</ul>",
|
|
56
|
+
"</body>",
|
|
57
|
+
"</html>",
|
|
58
|
+
"",
|
|
59
|
+
].join("\n")
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
function targetOf(event: HamurEvent, config: RootRedirectConfig): LocaleInfo | undefined {
|
|
63
|
+
const fromCookie = config.cookie ? getCookie(event, config.cookie) : undefined
|
|
64
|
+
return (
|
|
65
|
+
config.locales.find((locale) => locale.code === fromCookie) ??
|
|
66
|
+
negotiate(event.request.headers.get("accept-language"), config.locales)
|
|
67
|
+
)
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
function privateAnswer(event: HamurEvent): Headers {
|
|
71
|
+
const headers = event.response.headers
|
|
72
|
+
headers.append("vary", "Cookie, Accept-Language")
|
|
73
|
+
headers.set("cache-control", "private, no-store")
|
|
74
|
+
return headers
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/** The answer of `GET /`, or `undefined` to let the page `/` render. */
|
|
78
|
+
export function rootRedirect(event: HamurEvent, config: RootRedirectConfig, origin?: string): Response | undefined {
|
|
79
|
+
if (config.strategy === "no_prefix") return undefined
|
|
80
|
+
const headers = privateAnswer(event)
|
|
81
|
+
const target = targetOf(event, config)
|
|
82
|
+
const redirect = (code: string) => {
|
|
83
|
+
const answer = new Headers(headers)
|
|
84
|
+
answer.set("location", `${config.baseURL}${code}${event.url.search}`)
|
|
85
|
+
return new Response(null, { status: 302, headers: answer })
|
|
86
|
+
}
|
|
87
|
+
if (config.strategy === "prefix_except_default" || config.strategy === "prefix_and_default")
|
|
88
|
+
return target && target.code !== config.defaultLocale ? redirect(target.code) : undefined
|
|
89
|
+
if (target) return redirect(target.code)
|
|
90
|
+
if (config.redirectToDefaultLocale) return redirect(config.defaultLocale)
|
|
91
|
+
const answer = new Headers(headers)
|
|
92
|
+
answer.set("content-type", "text/html; charset=utf-8")
|
|
93
|
+
return new Response(event.method === "HEAD" ? null : localeRootPage(event, config, origin), {
|
|
94
|
+
status: 200,
|
|
95
|
+
headers: answer,
|
|
96
|
+
})
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
export interface AllRedirectConfig extends RootRedirectConfig {
|
|
100
|
+
copies: string[]
|
|
101
|
+
matcher: Matcher
|
|
102
|
+
/** Base route name → the codes whose copy is `false`; `"all"` does not send a visitor to one. */
|
|
103
|
+
missing?: Record<string, string[]>
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
const UNTOUCHED = /^\/(?:api|_hamur)(?:\/|$)/
|
|
107
|
+
const FILE = /\.[A-Za-z0-9]+$/
|
|
108
|
+
|
|
109
|
+
const namesHtml = (accept: string | null): boolean =>
|
|
110
|
+
(accept ?? "").split(",").some((entry) => entry.split(";")[0]!.trim().toLowerCase() === "text/html")
|
|
111
|
+
|
|
112
|
+
/**
|
|
113
|
+
* The answer of `detect.redirect: "all"` for a `GET` or `HEAD` of any path: `/` as `rootRedirect`, an unprefixed
|
|
114
|
+
* page path (under `prefix`, any path a locale's copy answers) as a `302` to the target locale's copy, else `undefined`.
|
|
115
|
+
*/
|
|
116
|
+
export function allRedirect(event: HamurEvent, config: AllRedirectConfig, origin?: string): Response | undefined {
|
|
117
|
+
if (config.strategy === "no_prefix") return undefined
|
|
118
|
+
const base = config.baseURL.replace(/\/$/, "")
|
|
119
|
+
let path = event.url.pathname
|
|
120
|
+
if (base) {
|
|
121
|
+
if (path !== base && !path.startsWith(base + "/")) return undefined
|
|
122
|
+
path = path.slice(base.length) || "/"
|
|
123
|
+
}
|
|
124
|
+
if (path === "/") return rootRedirect(event, config, origin)
|
|
125
|
+
if (!namesHtml(event.request.headers.get("accept")) || UNTOUCHED.test(path) || FILE.test(path)) return undefined
|
|
126
|
+
if (config.copies.includes(path.split("/")[1]!)) return undefined
|
|
127
|
+
const prefix = config.strategy === "prefix"
|
|
128
|
+
const ordered = [
|
|
129
|
+
config.defaultLocale,
|
|
130
|
+
...config.locales.map((locale) => locale.code).filter((code) => code !== config.defaultLocale),
|
|
131
|
+
]
|
|
132
|
+
const match = prefix
|
|
133
|
+
? ordered.map((code) => config.matcher.matchPath("/" + code + path)).find((found) => found !== undefined)
|
|
134
|
+
: config.matcher.matchPath(path)
|
|
135
|
+
if (!match || (!prefix && match.code !== config.defaultLocale)) return undefined
|
|
136
|
+
const headers = privateAnswer(event)
|
|
137
|
+
const target = targetOf(event, config)
|
|
138
|
+
const code = target?.code ?? (prefix ? config.defaultLocale : undefined)
|
|
139
|
+
if (code === undefined || (!prefix && code === config.defaultLocale)) return undefined
|
|
140
|
+
let copy: string
|
|
141
|
+
try {
|
|
142
|
+
copy = config.matcher.buildPath(match.name, code, match.params)
|
|
143
|
+
} catch {
|
|
144
|
+
return undefined
|
|
145
|
+
}
|
|
146
|
+
if (config.missing?.[match.name]?.includes(code)) return undefined
|
|
147
|
+
const answer = new Headers(headers)
|
|
148
|
+
answer.set("location", base + copy + event.url.search)
|
|
149
|
+
return new Response(null, { status: 302, headers: answer })
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
let config: Promise<RootRedirectConfig> | undefined
|
|
153
|
+
let allConfig: Promise<AllRedirectConfig> | undefined
|
|
154
|
+
|
|
155
|
+
async function loadConfig(): Promise<RootRedirectConfig> {
|
|
156
|
+
const options = await import("#hamur/i18n/options")
|
|
157
|
+
return {
|
|
158
|
+
locales: options.locales,
|
|
159
|
+
defaultLocale: options.defaultLocale,
|
|
160
|
+
strategy: options.strategy,
|
|
161
|
+
redirectToDefaultLocale: options.redirectToDefaultLocale,
|
|
162
|
+
cookie: options.cookie,
|
|
163
|
+
baseURL: options.baseURL,
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
async function loadAllConfig(): Promise<AllRedirectConfig> {
|
|
168
|
+
const [base, table] = await Promise.all([loadConfig(), import("#hamur/i18n/routes")])
|
|
169
|
+
return {
|
|
170
|
+
...base,
|
|
171
|
+
copies: table.copies,
|
|
172
|
+
matcher: createMatcher({ copies: table.copies, routes: table.routes, aliases: table.aliases }),
|
|
173
|
+
missing: table.missing,
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
/** The door's answer for a `GET` or `HEAD`: `allRedirect` over a config that holds the route matcher, else `rootRedirect`. */
|
|
178
|
+
export function redirectAnswer(
|
|
179
|
+
event: HamurEvent,
|
|
180
|
+
config: RootRedirectConfig | AllRedirectConfig,
|
|
181
|
+
origin?: string,
|
|
182
|
+
): Response | undefined {
|
|
183
|
+
if (event.request.method !== "GET" && event.request.method !== "HEAD") return undefined
|
|
184
|
+
return "matcher" in config ? allRedirect(event, config, origin) : rootRedirect(event, config, origin)
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
export const rootStep = defineMiddleware(async ({ event }) => redirectAnswer(event, await (config ??= loadConfig())))
|
|
188
|
+
|
|
189
|
+
export const allStep = defineMiddleware(async ({ event }) =>
|
|
190
|
+
redirectAnswer(event, await (allConfig ??= loadAllConfig())),
|
|
191
|
+
)
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import type { RichJoin, RichNode, RichParts } from "../types.ts"
|
|
2
|
+
|
|
3
|
+
/** The text of a rich message with its tags removed. */
|
|
4
|
+
export function richText(parts: RichParts): string {
|
|
5
|
+
let text = ""
|
|
6
|
+
for (const part of parts) text += typeof part === "string" ? part : richText(part.children)
|
|
7
|
+
return text
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
/** Walks the parts of a rich message; a tag with a handler becomes `handler(chunks)`, one without becomes its chunks. */
|
|
11
|
+
export function renderRich<N>(parts: RichParts, handlers: object, join: RichJoin<N>): N {
|
|
12
|
+
const out = parts.map((part: string | RichNode) => {
|
|
13
|
+
if (typeof part === "string") return part
|
|
14
|
+
const chunks = renderRich(part.children, handlers, join)
|
|
15
|
+
const handler = Object.hasOwn(handlers, part.tag)
|
|
16
|
+
? (handlers as Record<string, ((chunks: N) => N) | undefined>)[part.tag]
|
|
17
|
+
: undefined
|
|
18
|
+
return { node: handler ? handler(chunks) : chunks }
|
|
19
|
+
})
|
|
20
|
+
return join(out)
|
|
21
|
+
}
|
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
import type { LocaleInfo, RichParts, Translator } from "../types.ts"
|
|
2
|
+
import { fallbackChain, type Fallback } from "./chain.ts"
|
|
3
|
+
import { createFormatters, type FormatterTexts, type Formatters } from "./format.ts"
|
|
4
|
+
import type { Catalog, Message, MessageStore } from "./messages.ts"
|
|
5
|
+
import { renderRich, richText } from "./rich.ts"
|
|
6
|
+
|
|
7
|
+
export interface TranslatorSettings {
|
|
8
|
+
defaultLocale: LocaleInfo
|
|
9
|
+
fallback: Fallback
|
|
10
|
+
/** Every configured locale, to format a message taken from a locale of the chain; the default locale alone when absent. */
|
|
11
|
+
locales?: readonly LocaleInfo[]
|
|
12
|
+
timeZone: string
|
|
13
|
+
/** Missing keys and arguments are logged once each. */
|
|
14
|
+
dev: boolean
|
|
15
|
+
store: MessageStore
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
/** The formatted-text table of one app context; `translatorOf(locale, scope)` keeps one translator set per scope. */
|
|
19
|
+
export interface TextScope {
|
|
20
|
+
owner: object
|
|
21
|
+
texts: FormatterTexts
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
interface Translators {
|
|
25
|
+
formatters: Map<string, Formatters>
|
|
26
|
+
translators: Map<string, Translator>
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/** `t.dynamic` takes any key, so `constructor` must not reach `Object.prototype`. */
|
|
30
|
+
const messageOf = (catalog: Catalog | undefined, key: string): Message | undefined =>
|
|
31
|
+
catalog && Object.hasOwn(catalog, key) ? catalog[key] : undefined
|
|
32
|
+
|
|
33
|
+
/** `translator(locale)`; throws `i18n: locale "fr" is not loaded` until its catalog is in the store. */
|
|
34
|
+
export function createTranslators(settings: TranslatorSettings): (locale: LocaleInfo, scope?: TextScope) => Translator {
|
|
35
|
+
const { defaultLocale, fallback, timeZone, dev, store } = settings
|
|
36
|
+
const byCode = new Map<string, LocaleInfo>((settings.locales ?? [defaultLocale]).map((info) => [info.code, info]))
|
|
37
|
+
const shared: Translators = { formatters: new Map(), translators: new Map() }
|
|
38
|
+
const scoped = new WeakMap<object, Translators>()
|
|
39
|
+
const reported = new Set<string>()
|
|
40
|
+
const report = (text: string, ...parts: string[]) => {
|
|
41
|
+
if (!dev || reported.has(parts.join("\0"))) return
|
|
42
|
+
reported.add(parts.join("\0"))
|
|
43
|
+
console.warn(`[hamur] i18n: ${text}`)
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
return (locale, scope) => {
|
|
47
|
+
if (!store.get(locale.code)) throw new Error(`i18n: locale "${locale.code}" is not loaded`)
|
|
48
|
+
let set = scope ? scoped.get(scope.owner) : shared
|
|
49
|
+
if (!set) scoped.set(scope!.owner, (set = { formatters: new Map(), translators: new Map() }))
|
|
50
|
+
const { formatters, translators } = set
|
|
51
|
+
const formattersOf = (info: LocaleInfo): Formatters => {
|
|
52
|
+
let f = formatters.get(info.language)
|
|
53
|
+
if (!f) formatters.set(info.language, (f = createFormatters(info.language, timeZone, scope?.texts)))
|
|
54
|
+
return f
|
|
55
|
+
}
|
|
56
|
+
const known = translators.get(locale.code)
|
|
57
|
+
if (known) return known
|
|
58
|
+
const own = formattersOf(locale)
|
|
59
|
+
const chain = fallbackChain(fallback, defaultLocale.code, locale.code)
|
|
60
|
+
const render = (key: string, message: Message, f: Formatters, rest: unknown[]): string | RichParts => {
|
|
61
|
+
if (typeof message === "string") return message
|
|
62
|
+
const given = (rest[0] ?? {}) as Record<string, unknown>
|
|
63
|
+
const args = dev
|
|
64
|
+
? new Proxy(given, {
|
|
65
|
+
has(target, name) {
|
|
66
|
+
const present = Reflect.has(target, name) && target[name as string] !== undefined
|
|
67
|
+
if (!present)
|
|
68
|
+
report(
|
|
69
|
+
`${JSON.stringify(key)} in ${locale.code} needs the argument ${JSON.stringify(name)}`,
|
|
70
|
+
"arg",
|
|
71
|
+
key,
|
|
72
|
+
locale.code,
|
|
73
|
+
String(name),
|
|
74
|
+
)
|
|
75
|
+
return present
|
|
76
|
+
},
|
|
77
|
+
})
|
|
78
|
+
: given
|
|
79
|
+
return message(args, f)
|
|
80
|
+
}
|
|
81
|
+
const fromRemote = (code: string, key: string, f: Formatters, rest: unknown[]): string | RichParts | undefined => {
|
|
82
|
+
const message = messageOf(store.remote(code), key)
|
|
83
|
+
if (message === undefined) return undefined
|
|
84
|
+
try {
|
|
85
|
+
return render(key, message, f, rest)
|
|
86
|
+
} catch {
|
|
87
|
+
return undefined
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
const lookup = (key: string, rest: unknown[]): string | RichParts => {
|
|
91
|
+
const remote = fromRemote(locale.code, key, own, rest)
|
|
92
|
+
if (remote !== undefined) return remote
|
|
93
|
+
const message = messageOf(store.get(locale.code), key)
|
|
94
|
+
if (message !== undefined) {
|
|
95
|
+
if (store.filled(locale.code)?.has(key))
|
|
96
|
+
report(`missing ${JSON.stringify(key)} in ${locale.code}`, "key", key, locale.code)
|
|
97
|
+
return render(key, message, own, rest)
|
|
98
|
+
}
|
|
99
|
+
report(`missing ${JSON.stringify(key)} in ${locale.code}`, "key", key, locale.code)
|
|
100
|
+
for (const code of chain) {
|
|
101
|
+
const info = byCode.get(code)
|
|
102
|
+
if (!info) continue
|
|
103
|
+
const f = formattersOf(info)
|
|
104
|
+
const fallbackRemote = fromRemote(code, key, f, rest)
|
|
105
|
+
if (fallbackRemote !== undefined) return fallbackRemote
|
|
106
|
+
const fallbackMessage = messageOf(store.get(code), key)
|
|
107
|
+
if (fallbackMessage !== undefined) return render(key, fallbackMessage, f, rest)
|
|
108
|
+
}
|
|
109
|
+
return key
|
|
110
|
+
}
|
|
111
|
+
const translator: Translator = {
|
|
112
|
+
locale,
|
|
113
|
+
t(key: string, ...rest: unknown[]) {
|
|
114
|
+
const out = lookup(key, rest)
|
|
115
|
+
return typeof out === "string" ? out : richText(out)
|
|
116
|
+
},
|
|
117
|
+
dynamic(key, args) {
|
|
118
|
+
const out = lookup(key, [args])
|
|
119
|
+
return typeof out === "string" ? out : richText(out)
|
|
120
|
+
},
|
|
121
|
+
rich(key, args, handlers, join) {
|
|
122
|
+
const out = lookup(key as string, [args])
|
|
123
|
+
return renderRich(typeof out === "string" ? [out] : out, handlers, join)
|
|
124
|
+
},
|
|
125
|
+
n: (value, options) => own.n(value, options),
|
|
126
|
+
d: (value, options) => own.d(value, options),
|
|
127
|
+
}
|
|
128
|
+
translators.set(locale.code, translator)
|
|
129
|
+
return translator
|
|
130
|
+
}
|
|
131
|
+
}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import { defineHandler } from "hamur/server"
|
|
2
|
+
import { catalogAnswer } from "../runtime/catalog-server.ts"
|
|
3
|
+
|
|
4
|
+
/** `GET <baseURL>_hamur/i18n/<code>`, the run-time messages of a locale for the browser. */
|
|
5
|
+
export const i18nCatalog = defineHandler({
|
|
6
|
+
route: "/_hamur/i18n/:code",
|
|
7
|
+
method: "*",
|
|
8
|
+
raw: true,
|
|
9
|
+
meta: { hidden: true },
|
|
10
|
+
handler: (_, { event }) => catalogAnswer(event),
|
|
11
|
+
})
|
|
@@ -0,0 +1,191 @@
|
|
|
1
|
+
/// <reference path="../env.d.ts" />
|
|
2
|
+
import { rewrite, type HamurRewrite } from "hamur/app"
|
|
3
|
+
import { defineMiddleware, getCookie, getRequestURL, type HamurEvent } from "hamur/server"
|
|
4
|
+
import { installServerCatalog, serverCatalog } from "../runtime/catalog-loader.ts"
|
|
5
|
+
import { fallbackChain } from "../runtime/chain.ts"
|
|
6
|
+
import {
|
|
7
|
+
contextLocale,
|
|
8
|
+
copyMissing,
|
|
9
|
+
createI18nRuntime,
|
|
10
|
+
LOCALE_VARIANT,
|
|
11
|
+
missingCopyOf,
|
|
12
|
+
type I18nConfig,
|
|
13
|
+
} from "../runtime/locale.ts"
|
|
14
|
+
import { messageStore } from "../runtime/messages.ts"
|
|
15
|
+
import { negotiate } from "../runtime/negotiate.ts"
|
|
16
|
+
import type { I18nRuntime, LocaleInfo, HamurLocale, Translator } from "../types.ts"
|
|
17
|
+
|
|
18
|
+
declare module "hamur/server" {
|
|
19
|
+
interface HamurEventContext {
|
|
20
|
+
locale?: HamurLocale
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export interface ServerConfig extends I18nConfig {
|
|
25
|
+
/** `app.baseURL`, with its trailing `/`. */
|
|
26
|
+
baseURL: string
|
|
27
|
+
/** The answer at the URL of a copy that is `false`; `"404"` when absent. */
|
|
28
|
+
missingPage?: "404" | "redirect" | "rewrite"
|
|
29
|
+
/** `hamur dev`: a host no domain names falls to the order of `resolve` instead of the default locale. */
|
|
30
|
+
dev?: boolean
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export interface ServerI18n {
|
|
34
|
+
runtime: I18nRuntime
|
|
35
|
+
/** `app.baseURL`, with its trailing `/`. */
|
|
36
|
+
baseURL: string
|
|
37
|
+
/**
|
|
38
|
+
* Path prefix, `?locale`, cookie, `Accept-Language`, the default; the first that names a locale wins. Under `no_prefix`
|
|
39
|
+
* and with domains a cache fork's `cacheVariant` comes first; with domains the host of `getRequestURL` then decides, and a
|
|
40
|
+
* host no domain names gets the default locale, or the order above in `hamur dev`.
|
|
41
|
+
*/
|
|
42
|
+
resolve(event: HamurEvent): LocaleInfo
|
|
43
|
+
/**
|
|
44
|
+
* The door's step: `event.context.locale`, and under `no_prefix` and with domains `cacheVariant`, which a cache fork keeps; `Vary:
|
|
45
|
+
* Cookie, Accept-Language` under `no_prefix` and when no host decided.
|
|
46
|
+
*/
|
|
47
|
+
enter(event: HamurEvent): void
|
|
48
|
+
/** The `302` or the `rewrite()` for the URL of a copy that is `false` under `missingPage` `"redirect"` or `"rewrite"`; `undefined` for any other request. */
|
|
49
|
+
missing(event: HamurEvent): Response | HamurRewrite | undefined
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
function firstSegment(pathname: string, baseURL: string): string | undefined {
|
|
53
|
+
const base = baseURL.replace(/\/$/, "")
|
|
54
|
+
let path = pathname
|
|
55
|
+
if (base && (path === base || path.startsWith(`${base}/`))) path = path.slice(base.length)
|
|
56
|
+
return /^\/([^/]*)/.exec(path)?.[1]
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
export function createServerI18n(config: ServerConfig): ServerI18n {
|
|
60
|
+
const runtime = createI18nRuntime(config)
|
|
61
|
+
const byCode = new Map<string, LocaleInfo>(config.locales.map((locale) => [locale.code, locale]))
|
|
62
|
+
const copies = new Set(config.copies)
|
|
63
|
+
const single = config.strategy === "no_prefix"
|
|
64
|
+
const hosts = config.domains
|
|
65
|
+
? new Map(Object.entries(config.domains).map(([code, origin]) => [new URL(origin).host, byCode.get(code)!]))
|
|
66
|
+
: undefined
|
|
67
|
+
const byRequest = (event: HamurEvent): { locale: LocaleInfo; byHost: boolean } => {
|
|
68
|
+
if (single || hosts) {
|
|
69
|
+
const fromVariant = contextLocale(runtime, { cacheVariant: event.context.cacheVariant })
|
|
70
|
+
if (fromVariant) return { locale: fromVariant, byHost: false }
|
|
71
|
+
}
|
|
72
|
+
if (hosts) {
|
|
73
|
+
const url = getRequestURL(event)
|
|
74
|
+
// TLS termination without trustProxy can leave the other scheme's default port on the URL: http://example.fr:443
|
|
75
|
+
const fromHost =
|
|
76
|
+
hosts.get(url.host) ?? (url.port === "80" || url.port === "443" ? hosts.get(url.hostname) : undefined)
|
|
77
|
+
if (fromHost) return { locale: fromHost, byHost: true }
|
|
78
|
+
if (!config.dev) return { locale: runtime.defaultLocale, byHost: true }
|
|
79
|
+
}
|
|
80
|
+
return { locale: ordered(event), byHost: false }
|
|
81
|
+
}
|
|
82
|
+
const ordered = (event: HamurEvent): LocaleInfo => {
|
|
83
|
+
const segment = firstSegment(event.url.pathname, config.baseURL)
|
|
84
|
+
if (segment !== undefined && copies.has(segment)) return byCode.get(segment)!
|
|
85
|
+
const query = event.url.searchParams.get("locale")
|
|
86
|
+
const fromQuery = query === null ? undefined : byCode.get(query)
|
|
87
|
+
if (fromQuery) return fromQuery
|
|
88
|
+
const cookie = config.cookie ? getCookie(event, config.cookie) : undefined
|
|
89
|
+
const fromCookie = cookie === undefined ? undefined : byCode.get(cookie)
|
|
90
|
+
if (fromCookie) return fromCookie
|
|
91
|
+
return negotiate(event.request.headers.get("accept-language"), config.locales) ?? runtime.defaultLocale
|
|
92
|
+
}
|
|
93
|
+
return {
|
|
94
|
+
runtime,
|
|
95
|
+
baseURL: config.baseURL,
|
|
96
|
+
resolve: (event) => byRequest(event).locale,
|
|
97
|
+
enter(event) {
|
|
98
|
+
const { locale, byHost } = byRequest(event)
|
|
99
|
+
const { code } = locale
|
|
100
|
+
event.context.locale = code
|
|
101
|
+
if (!single && !hosts) return
|
|
102
|
+
event.context.cacheVariant = LOCALE_VARIANT + code
|
|
103
|
+
if (!byHost) event.response.headers.append("vary", "Cookie, Accept-Language")
|
|
104
|
+
},
|
|
105
|
+
missing(event) {
|
|
106
|
+
const mode = config.missingPage ?? "404"
|
|
107
|
+
if (mode === "404" || (event.method !== "GET" && event.method !== "HEAD")) return undefined
|
|
108
|
+
const base = config.baseURL.replace(/\/$/, "")
|
|
109
|
+
const { pathname } = event.url
|
|
110
|
+
if (base && pathname !== base && !pathname.startsWith(base + "/")) return undefined
|
|
111
|
+
const match = missingCopyOf(runtime, pathname.slice(base.length) || "/")
|
|
112
|
+
if (!match) return undefined
|
|
113
|
+
const holder = byCode.get(
|
|
114
|
+
fallbackChain(config.fallback, config.defaultLocale, match.code).find(
|
|
115
|
+
(code) => !copyMissing(runtime, match.name, code),
|
|
116
|
+
) ?? config.defaultLocale,
|
|
117
|
+
)!
|
|
118
|
+
const target = runtime.localePath({ name: match.name, params: match.params }, holder.code)
|
|
119
|
+
if (mode === "rewrite") return rewrite(target)
|
|
120
|
+
const headers = new Headers(event.response.headers)
|
|
121
|
+
headers.set("location", base + target + event.url.search)
|
|
122
|
+
return new Response(null, { status: 302, headers })
|
|
123
|
+
},
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
export interface ServerTranslation {
|
|
128
|
+
locale: LocaleInfo
|
|
129
|
+
/** `t.dynamic(key, args?)` reads a run-time key. */
|
|
130
|
+
t: Translator["t"] & { dynamic: Translator["dynamic"] }
|
|
131
|
+
n: Translator["n"]
|
|
132
|
+
d: Translator["d"]
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
export async function translationOf(server: ServerI18n, event: HamurEvent): Promise<ServerTranslation> {
|
|
136
|
+
const { runtime } = server
|
|
137
|
+
const known = runtime.locales.find((locale) => locale.code === event.context.locale)
|
|
138
|
+
const { code } = known ?? server.resolve(event)
|
|
139
|
+
const catalog = serverCatalog()
|
|
140
|
+
await Promise.all([runtime.load(code), catalog?.(code, { event, baseURL: server.baseURL })])
|
|
141
|
+
const { locale, t, n, d, dynamic } = runtime.translator(code)
|
|
142
|
+
return {
|
|
143
|
+
locale,
|
|
144
|
+
t: Object.assign(
|
|
145
|
+
((key: string, ...args: unknown[]) =>
|
|
146
|
+
(t as (key: string, ...args: unknown[]) => string)(key, ...args)) as Translator["t"],
|
|
147
|
+
{ dynamic },
|
|
148
|
+
),
|
|
149
|
+
n,
|
|
150
|
+
d,
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
let server: Promise<ServerI18n> | undefined
|
|
155
|
+
|
|
156
|
+
async function loadServer(): Promise<ServerI18n> {
|
|
157
|
+
const [options, table, loaders, chunks, catalog] = await Promise.all([
|
|
158
|
+
import("#hamur/i18n/options"),
|
|
159
|
+
import("#hamur/i18n/routes"),
|
|
160
|
+
import("#hamur/i18n/loaders"),
|
|
161
|
+
import("#hamur/i18n/chunks"),
|
|
162
|
+
import("#hamur/i18n/catalog-server"),
|
|
163
|
+
])
|
|
164
|
+
messageStore.install(loaders.default, chunks.default)
|
|
165
|
+
const loader = catalog.default
|
|
166
|
+
if (loader) installServerCatalog(loader)
|
|
167
|
+
return createServerI18n({
|
|
168
|
+
locales: options.locales,
|
|
169
|
+
defaultLocale: options.defaultLocale,
|
|
170
|
+
strategy: options.strategy,
|
|
171
|
+
cookie: options.cookie,
|
|
172
|
+
timeZone: options.timeZone,
|
|
173
|
+
fallback: options.fallback,
|
|
174
|
+
missingPage: options.missingPage,
|
|
175
|
+
baseURL: options.baseURL,
|
|
176
|
+
copies: table.copies,
|
|
177
|
+
routes: table.routes,
|
|
178
|
+
aliases: table.aliases,
|
|
179
|
+
missing: table.missing,
|
|
180
|
+
...(table.domains ? { domains: table.domains } : {}),
|
|
181
|
+
dev: (import.meta as { dev?: boolean }).dev === true,
|
|
182
|
+
})
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
export const serverI18n = (): Promise<ServerI18n> => (server ??= loadServer())
|
|
186
|
+
|
|
187
|
+
export const localeStep = defineMiddleware(async ({ event }) => {
|
|
188
|
+
const i18n = await serverI18n()
|
|
189
|
+
i18n.enter(event)
|
|
190
|
+
return i18n.missing(event)
|
|
191
|
+
})
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import { defineServer } from "hamur/server"
|
|
2
|
+
import { rootStep } from "../runtime/redirect.ts"
|
|
3
|
+
import { localeStep } from "./context.ts"
|
|
4
|
+
|
|
5
|
+
export { i18nCatalog } from "./catalog.ts"
|
|
6
|
+
|
|
7
|
+
export default defineServer({ middleware: [{ route: "/", handler: rootStep }, localeStep] })
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import type { HamurEvent } from "hamur/server"
|
|
2
|
+
import { serverI18n, translationOf, type ServerTranslation } from "./context.ts"
|
|
3
|
+
|
|
4
|
+
export { preferredLocale, preferredLocaleList } from "./preferred.ts"
|
|
5
|
+
export { i18nRedirect } from "./redirect.ts"
|
|
6
|
+
export { defineCatalog, type CatalogDefinition } from "../runtime/catalog.ts"
|
|
7
|
+
|
|
8
|
+
/** The translator of `event.context.locale`, or of the locale the middleware would have set. */
|
|
9
|
+
export async function useTranslation(event: HamurEvent): Promise<ServerTranslation> {
|
|
10
|
+
return translationOf(await serverI18n(), event)
|
|
11
|
+
}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
/// <reference path="../env.d.ts" />
|
|
2
|
+
import type { HamurEvent } from "hamur/server"
|
|
3
|
+
import { locales } from "#hamur/i18n/options"
|
|
4
|
+
import { negotiateAll } from "../runtime/negotiate.ts"
|
|
5
|
+
import type { LocaleInfo } from "../types.ts"
|
|
6
|
+
|
|
7
|
+
/** Every configured locale the request's `Accept-Language` matches, best first. */
|
|
8
|
+
export const preferredLocaleList = (event: HamurEvent): LocaleInfo[] =>
|
|
9
|
+
negotiateAll(event.request.headers.get("accept-language"), locales)
|
|
10
|
+
|
|
11
|
+
/** The first of `preferredLocaleList(event)`. */
|
|
12
|
+
export const preferredLocale = (event: HamurEvent): LocaleInfo | undefined => preferredLocaleList(event)[0]
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
/// <reference path="../env.d.ts" />
|
|
2
|
+
import type { HamurEvent } from "hamur/server"
|
|
3
|
+
import * as options from "#hamur/i18n/options"
|
|
4
|
+
import { aliases, copies, missing, routes } from "#hamur/i18n/routes"
|
|
5
|
+
import { createMatcher } from "../runtime/match.ts"
|
|
6
|
+
import { redirectAnswer, type AllRedirectConfig, type RootRedirectConfig } from "../runtime/redirect.ts"
|
|
7
|
+
|
|
8
|
+
let root: RootRedirectConfig | undefined
|
|
9
|
+
let all: AllRedirectConfig | undefined
|
|
10
|
+
|
|
11
|
+
const rootConfig = (): RootRedirectConfig =>
|
|
12
|
+
(root ??= {
|
|
13
|
+
locales: options.locales,
|
|
14
|
+
defaultLocale: options.defaultLocale,
|
|
15
|
+
strategy: options.strategy,
|
|
16
|
+
redirectToDefaultLocale: options.redirectToDefaultLocale,
|
|
17
|
+
cookie: options.cookie,
|
|
18
|
+
baseURL: options.baseURL,
|
|
19
|
+
})
|
|
20
|
+
|
|
21
|
+
const allConfig = (): AllRedirectConfig =>
|
|
22
|
+
(all ??= { ...rootConfig(), copies, matcher: createMatcher({ copies, routes, aliases }), missing })
|
|
23
|
+
|
|
24
|
+
/** The redirect step of the built-in door as a function, for an app that sets `detect.redirect: false` and lists its own middleware. */
|
|
25
|
+
export const i18nRedirect = (event: HamurEvent, mode: "root" | "all" = "root"): Response | undefined =>
|
|
26
|
+
redirectAnswer(event, mode === "all" ? allConfig() : rootConfig())
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import { addServer, createResolver } from "hamur/kit"
|
|
2
|
+
import type { I18nSetup } from "../types.ts"
|
|
3
|
+
|
|
4
|
+
export const setupServer: I18nSetup = (options) => {
|
|
5
|
+
const mode = options.domains
|
|
6
|
+
? ""
|
|
7
|
+
: options.detect.redirect === "root"
|
|
8
|
+
? "-root"
|
|
9
|
+
: options.detect.redirect === "all" && options.strategy !== "no_prefix"
|
|
10
|
+
? "-all"
|
|
11
|
+
: ""
|
|
12
|
+
const door = "./door" + mode + (options.catalog === undefined ? "" : "-catalog") + ".ts"
|
|
13
|
+
addServer(createResolver(import.meta.url).resolve(door))
|
|
14
|
+
}
|