@hamur/i18n 0.0.0-stage → 0.0.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/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 +20 -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 +155 -4
- package/src/adapters/angular.ts +58 -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,85 @@
|
|
|
1
|
+
import { MessageSyntaxError } from "./parse.ts"
|
|
2
|
+
|
|
3
|
+
export interface Skeleton {
|
|
4
|
+
options: Record<string, unknown>
|
|
5
|
+
/** The value is multiplied by this before formatting. */
|
|
6
|
+
scale?: number
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
const WIDTHS: Record<string, string> = { short: "short", narrow: "narrow", "full-name": "long" }
|
|
10
|
+
|
|
11
|
+
function supportedUnit(unit: string): boolean {
|
|
12
|
+
try {
|
|
13
|
+
new Intl.NumberFormat("en", { style: "unit", unit })
|
|
14
|
+
return true
|
|
15
|
+
} catch {
|
|
16
|
+
return false
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/** The tokens after `::` as `Intl.NumberFormat` options; `offset` is where `source` starts in the message. */
|
|
21
|
+
export function parseSkeleton(source: string, offset: number): Skeleton {
|
|
22
|
+
const options: Record<string, unknown> = {}
|
|
23
|
+
let scale: number | undefined
|
|
24
|
+
let percent = false
|
|
25
|
+
let unit: string | undefined
|
|
26
|
+
let currency: string | undefined
|
|
27
|
+
let width: { token: string; value: string; at: number } | undefined
|
|
28
|
+
const fail = (at: number, reason: string): never => {
|
|
29
|
+
throw new MessageSyntaxError(at, reason)
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
for (const match of source.matchAll(/\S+/g)) {
|
|
33
|
+
const token = match[0]
|
|
34
|
+
const at = offset + match.index
|
|
35
|
+
const stem = () => fail(at, 'number skeleton stem "' + token.split("/")[0] + '" is not supported')
|
|
36
|
+
let found: RegExpExecArray | null
|
|
37
|
+
if (token === "percent") {
|
|
38
|
+
options.style = "percent"
|
|
39
|
+
percent = true
|
|
40
|
+
} else if (token === "compact-short" || token === "compact-long") {
|
|
41
|
+
options.notation = "compact"
|
|
42
|
+
options.compactDisplay = token === "compact-short" ? "short" : "long"
|
|
43
|
+
} else if (token.startsWith("unit/")) {
|
|
44
|
+
unit = token.slice(5)
|
|
45
|
+
if (!unit || !supportedUnit(unit)) fail(at, 'number skeleton unit "' + unit + '" is not supported')
|
|
46
|
+
} else if (token.startsWith("currency/")) {
|
|
47
|
+
currency = token.slice(9)
|
|
48
|
+
if (!/^[A-Za-z]{3}$/.test(currency))
|
|
49
|
+
fail(at, 'number skeleton currency "' + currency + '" is not a three-letter code')
|
|
50
|
+
currency = currency.toUpperCase()
|
|
51
|
+
} else if (token.startsWith("scale/")) {
|
|
52
|
+
scale = Number(token.slice(6))
|
|
53
|
+
if (token.length === 6 || !Number.isFinite(scale))
|
|
54
|
+
fail(at, 'number skeleton scale "' + token.slice(6) + '" is not a number')
|
|
55
|
+
} else if (token.startsWith("unit-width-")) {
|
|
56
|
+
const value = token.slice(11)
|
|
57
|
+
if (!Object.hasOwn(WIDTHS, value)) stem()
|
|
58
|
+
width = { token, value, at }
|
|
59
|
+
} else if ((found = /^\.(0*)(#*)$/.exec(token)) && token.length > 1) {
|
|
60
|
+
options.minimumFractionDigits = found[1]!.length
|
|
61
|
+
options.maximumFractionDigits = found[1]!.length + found[2]!.length
|
|
62
|
+
} else if (token === "sign-always") options.signDisplay = "always"
|
|
63
|
+
else if (token === "group-off") options.useGrouping = false
|
|
64
|
+
else if (token === "integer") options.maximumFractionDigits = 0
|
|
65
|
+
else stem()
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
if (unit !== undefined && currency !== undefined)
|
|
69
|
+
fail(offset, "number skeleton cannot hold both unit/<unit> and currency/<code>")
|
|
70
|
+
if (unit !== undefined) {
|
|
71
|
+
options.style = "unit"
|
|
72
|
+
options.unit = unit
|
|
73
|
+
if (width) options.unitDisplay = WIDTHS[width.value]
|
|
74
|
+
} else if (currency !== undefined) {
|
|
75
|
+
options.style = "currency"
|
|
76
|
+
options.currency = currency
|
|
77
|
+
if (width) {
|
|
78
|
+
if (width.value !== "narrow") fail(width.at, 'number skeleton stem "' + width.token + '" is not supported')
|
|
79
|
+
options.currencyDisplay = "narrowSymbol"
|
|
80
|
+
}
|
|
81
|
+
} else if (width) fail(width.at, 'number skeleton "' + width.token + '" needs a unit/<unit> or currency/<code> stem')
|
|
82
|
+
|
|
83
|
+
if (percent && scale === 100) scale = undefined
|
|
84
|
+
return scale === undefined ? { options } : { options, scale }
|
|
85
|
+
}
|
package/src/env.d.ts
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
declare module "#hamur/i18n/routes" {
|
|
2
|
+
export const copies: string[]
|
|
3
|
+
export const routes: Record<string, Record<string, string>>
|
|
4
|
+
export const aliases: Record<string, Record<string, string>>
|
|
5
|
+
/** Base route name → the codes whose copy is `false`; their paths are in `routes`. */
|
|
6
|
+
export const missing: Record<string, string[]>
|
|
7
|
+
export const domains: Record<string, string> | undefined
|
|
8
|
+
/** The server route patterns, which the link resolver leaves as written. */
|
|
9
|
+
export const server: string[]
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
declare module "#hamur/i18n/options" {
|
|
13
|
+
export const locales: import("./types.ts").LocaleInfo[]
|
|
14
|
+
export const defaultLocale: string
|
|
15
|
+
export const strategy: "prefix_except_default" | "prefix" | "prefix_and_default" | "no_prefix"
|
|
16
|
+
export const redirectToDefaultLocale: boolean
|
|
17
|
+
export const cookie: string | false
|
|
18
|
+
export const baseURL: string
|
|
19
|
+
export const timeZone: string
|
|
20
|
+
export const fallback: "default" | false | Record<string, string[]>
|
|
21
|
+
export const missingPage: "404" | "redirect" | "rewrite"
|
|
22
|
+
export const localizeLinks: boolean
|
|
23
|
+
/** What run-time catalogs parse as. */
|
|
24
|
+
export const syntax: "mf1" | "mf2"
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
declare module "#hamur/i18n/loaders" {
|
|
28
|
+
const loaders: import("./runtime/messages.ts").MessageLoaders
|
|
29
|
+
export default loaders
|
|
30
|
+
/** The client's per-route chunk loaders under `split: "route"`; empty on the server and without it. */
|
|
31
|
+
export const routes: import("./runtime/messages.ts").RouteMessageLoaders
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
declare module "#hamur/i18n/chunks" {
|
|
35
|
+
const chunks: import("./runtime/messages.ts").MessageChunks
|
|
36
|
+
export default chunks
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
declare module "#hamur/i18n/catalog" {
|
|
40
|
+
/** The browser's run-time catalog loader when `i18n.catalog` is set; the server's is `#hamur/i18n/catalog-server`. */
|
|
41
|
+
const catalog: import("./runtime/catalog-loader.ts").CatalogLoader | undefined
|
|
42
|
+
export default catalog
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
declare module "#hamur/i18n/catalog-server" {
|
|
46
|
+
/** The server's run-time catalog loader when `i18n.catalog` is set. */
|
|
47
|
+
const catalog: import("./runtime/catalog-loader.ts").CatalogLoader | undefined
|
|
48
|
+
export default catalog
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
declare module "#hamur/i18n/catalog-source" {
|
|
52
|
+
/** The file `i18n.catalog` names, imported on the first request that needs it. */
|
|
53
|
+
const source: (() => Promise<{ default: unknown }>) | undefined
|
|
54
|
+
export default source
|
|
55
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
export { default } from "./module.ts"
|
|
2
|
+
export type {
|
|
3
|
+
CurrentLocale,
|
|
4
|
+
I18nArgsObject,
|
|
5
|
+
I18nArgsTuple,
|
|
6
|
+
I18nKey,
|
|
7
|
+
I18nOptions,
|
|
8
|
+
I18nRich,
|
|
9
|
+
I18nRouteLocation,
|
|
10
|
+
I18nRuntime,
|
|
11
|
+
I18nSetup,
|
|
12
|
+
LocaleInfo,
|
|
13
|
+
LocaleInput,
|
|
14
|
+
ResolvedI18nOptions,
|
|
15
|
+
HamurI18nLocales,
|
|
16
|
+
HamurI18nMessages,
|
|
17
|
+
HamurI18nTags,
|
|
18
|
+
HamurLocale,
|
|
19
|
+
RichHandlers,
|
|
20
|
+
RichJoin,
|
|
21
|
+
RichNode,
|
|
22
|
+
RichParts,
|
|
23
|
+
Translator,
|
|
24
|
+
} from "./types.ts"
|
package/src/load.ts
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import type { LoadContext } from "hamur/app"
|
|
2
|
+
import type { ServerTranslation } from "./server/context.ts"
|
|
3
|
+
import type { Translator } from "./types.ts"
|
|
4
|
+
import { serverCatalog } from "./runtime/catalog-loader.ts"
|
|
5
|
+
import {
|
|
6
|
+
configOf,
|
|
7
|
+
contextLocale,
|
|
8
|
+
loadRuntime,
|
|
9
|
+
readsRequestLocale,
|
|
10
|
+
routeBaseName,
|
|
11
|
+
routeLoadOf,
|
|
12
|
+
} from "./runtime/locale.ts"
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* The translator of the locale a `load` renders in, on both sides. On the server `ctx.event.context.locale`, as
|
|
16
|
+
* `useTranslation(event)` of `@hamur/i18n/server`; in the browser the app's locale, its messages loaded first.
|
|
17
|
+
*/
|
|
18
|
+
export async function useTranslation(ctx: LoadContext): Promise<ServerTranslation> {
|
|
19
|
+
const i18n = loadRuntime.current
|
|
20
|
+
if (!i18n) throw new Error('useTranslation(ctx) needs the "@hamur/i18n" module: its app plugin has not run')
|
|
21
|
+
const { event, route } = ctx
|
|
22
|
+
const { code } =
|
|
23
|
+
contextLocale(i18n, event?.context) ?? (readsRequestLocale(i18n) ? i18n.locale : i18n.localeOf(route.path))
|
|
24
|
+
const loadRoute = routeLoadOf(i18n)
|
|
25
|
+
const catalog = event ? serverCatalog() : undefined
|
|
26
|
+
await Promise.all([
|
|
27
|
+
loadRoute ? loadRoute(code, route.name ? routeBaseName(route.name) : undefined) : i18n.load(code),
|
|
28
|
+
catalog?.(code, { event, baseURL: configOf(i18n).baseURL ?? "/" }),
|
|
29
|
+
])
|
|
30
|
+
const { locale, t, n, d, dynamic } = i18n.translator(code)
|
|
31
|
+
return {
|
|
32
|
+
locale,
|
|
33
|
+
t: Object.assign(
|
|
34
|
+
((key: string, ...args: unknown[]) =>
|
|
35
|
+
(t as (key: string, ...args: unknown[]) => string)(key, ...args)) as Translator["t"],
|
|
36
|
+
{ dynamic },
|
|
37
|
+
),
|
|
38
|
+
n,
|
|
39
|
+
d,
|
|
40
|
+
}
|
|
41
|
+
}
|
package/src/module.ts
ADDED
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
import { DiagnosticError, defineModule, type HamurContext } from "hamur/kit"
|
|
2
|
+
import { setupCatalog } from "./build/catalog.ts"
|
|
3
|
+
import { setupHead } from "./build/head.ts"
|
|
4
|
+
import { setupMessages } from "./build/messages.ts"
|
|
5
|
+
import { isStaticPreset, setupPrerender } from "./build/prerender.ts"
|
|
6
|
+
import { setupRoutes } from "./build/routes.ts"
|
|
7
|
+
import { setupTypes } from "./build/types.ts"
|
|
8
|
+
import { resolveOptions } from "./options.ts"
|
|
9
|
+
import { setupServer } from "./server/setup.ts"
|
|
10
|
+
import type { I18nOptions, ResolvedI18nOptions } from "./types.ts"
|
|
11
|
+
|
|
12
|
+
/** The options each context's setup resolved, for `runI18nCommand`. */
|
|
13
|
+
export const resolvedOptions = new WeakMap<HamurContext, ResolvedI18nOptions>()
|
|
14
|
+
|
|
15
|
+
/** One static host serves one domain. */
|
|
16
|
+
export const DOMAIN_STATIC = "i18n: locales[].domain needs a server preset (static serves one host)"
|
|
17
|
+
|
|
18
|
+
/** A static host has no server to call `load` or answer `_hamur/i18n/<code>`. */
|
|
19
|
+
export const CATALOG_STATIC = "i18n.catalog needs a server preset (static has no server to load the catalog)"
|
|
20
|
+
|
|
21
|
+
/** `getRequestURL` answers the public origin's host for every request, so no other domain is ever seen. */
|
|
22
|
+
export const DOMAIN_ORIGIN = "i18n: locales[].domain cannot be used with app.origin, which gives every request one host"
|
|
23
|
+
|
|
24
|
+
/** The presets whose CDN keeps an `isr` answer by path, not host. */
|
|
25
|
+
export const PATH_KEYED_ISR = new Set(["vercel", "netlify"])
|
|
26
|
+
|
|
27
|
+
export const domainIsrError = (preset: string, pattern: string): string =>
|
|
28
|
+
"i18n: locales[].domain cannot be used with an isr route rule on the " +
|
|
29
|
+
preset +
|
|
30
|
+
" preset (" +
|
|
31
|
+
JSON.stringify(pattern) +
|
|
32
|
+
"); its ISR cache keys on the path, not the host"
|
|
33
|
+
|
|
34
|
+
const isIsr = (rule: unknown): boolean => {
|
|
35
|
+
const isr = (rule as { isr?: unknown } | undefined)?.isr
|
|
36
|
+
return isr === true || (typeof isr === "number" && isr > 0)
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
function checkDomainHosting(hamur: HamurContext): void {
|
|
40
|
+
const { preset, app, routeRules } = hamur.options
|
|
41
|
+
if (isStaticPreset(preset)) throw new DiagnosticError("HAMUR_E5802", DOMAIN_STATIC)
|
|
42
|
+
if (app.origin !== undefined) throw new DiagnosticError("HAMUR_E5803", DOMAIN_ORIGIN)
|
|
43
|
+
if (!PATH_KEYED_ISR.has(preset)) return
|
|
44
|
+
for (const [pattern, rule] of Object.entries(routeRules)) {
|
|
45
|
+
if ((Array.isArray(rule) ? rule : [rule]).some(isIsr))
|
|
46
|
+
throw new DiagnosticError("HAMUR_E5804", domainIsrError(preset, pattern))
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
export default defineModule<I18nOptions>({
|
|
51
|
+
meta: { name: "i18n", configKey: "i18n" },
|
|
52
|
+
async setup(input, hamur) {
|
|
53
|
+
const options = resolveOptions(input)
|
|
54
|
+
if (options.domains) checkDomainHosting(hamur)
|
|
55
|
+
if (options.catalog !== undefined && isStaticPreset(hamur.options.preset))
|
|
56
|
+
throw new DiagnosticError("HAMUR_E5805", CATALOG_STATIC)
|
|
57
|
+
await setupRoutes(options, hamur)
|
|
58
|
+
await setupMessages(options, hamur)
|
|
59
|
+
await setupCatalog(options, hamur)
|
|
60
|
+
await setupServer(options, hamur)
|
|
61
|
+
await setupHead(options, hamur)
|
|
62
|
+
await setupPrerender(options, hamur)
|
|
63
|
+
await setupTypes(options, hamur)
|
|
64
|
+
resolvedOptions.set(hamur, options)
|
|
65
|
+
},
|
|
66
|
+
})
|
package/src/options.ts
ADDED
|
@@ -0,0 +1,198 @@
|
|
|
1
|
+
import type { HamurLocale, I18nOptions, LocaleInfo, LocaleInput, ResolvedI18nOptions } from "./types.ts"
|
|
2
|
+
import { DiagnosticError } from "hamur/kit"
|
|
3
|
+
|
|
4
|
+
export const CODE = /^[a-z]{2,3}(-[a-z0-9]{2,8})*$/
|
|
5
|
+
const COOKIE_NAME = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/
|
|
6
|
+
const STRATEGIES = new Set(["prefix_except_default", "prefix", "prefix_and_default", "no_prefix"])
|
|
7
|
+
|
|
8
|
+
/** `i18n.catalog` naming no file. */
|
|
9
|
+
export const catalogMissing = (catalog: unknown): string =>
|
|
10
|
+
"i18n.catalog " + JSON.stringify(catalog) + " does not exist"
|
|
11
|
+
|
|
12
|
+
export const BASE_URL_REMOVED = "i18n.baseUrl was removed: set site.url (HAMUR_SITE_URL at run time)"
|
|
13
|
+
|
|
14
|
+
function fail(message: string): never {
|
|
15
|
+
throw new DiagnosticError("HAMUR_E5806", message)
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
function resolveLocale(entry: string | LocaleInput, index: number): LocaleInfo {
|
|
19
|
+
const input = typeof entry === "string" ? { code: entry } : entry
|
|
20
|
+
const { code } = input
|
|
21
|
+
if (typeof code !== "string" || !CODE.test(code)) {
|
|
22
|
+
fail(
|
|
23
|
+
`i18n.locales[${index}].code ${JSON.stringify(code)} must be lower-case letters, digits and "-" (like "fr" or "pt-br")`,
|
|
24
|
+
)
|
|
25
|
+
}
|
|
26
|
+
const language = input.language ?? code
|
|
27
|
+
try {
|
|
28
|
+
Intl.getCanonicalLocales(language)
|
|
29
|
+
} catch {
|
|
30
|
+
fail(`i18n.locales[${index}].language ${JSON.stringify(language)} is not a BCP 47 language tag`)
|
|
31
|
+
}
|
|
32
|
+
const dir =
|
|
33
|
+
input.dir ??
|
|
34
|
+
((new Intl.Locale(language) as Intl.Locale & { getTextInfo(): { direction?: string } }).getTextInfo().direction ===
|
|
35
|
+
"rtl"
|
|
36
|
+
? "rtl"
|
|
37
|
+
: "ltr")
|
|
38
|
+
const name = input.name ?? new Intl.DisplayNames([language], { type: "language" }).of(language) ?? language
|
|
39
|
+
return { code: code as HamurLocale, language, dir, name }
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
function originOf(value: unknown): string | undefined {
|
|
43
|
+
if (typeof value !== "string") return undefined
|
|
44
|
+
let url: URL
|
|
45
|
+
try {
|
|
46
|
+
url = new URL(value)
|
|
47
|
+
} catch {
|
|
48
|
+
return undefined
|
|
49
|
+
}
|
|
50
|
+
if (url.protocol !== "http:" && url.protocol !== "https:") return undefined
|
|
51
|
+
if (url.username || url.password || url.pathname !== "/" || url.search || url.hash || /[?#]/.test(value))
|
|
52
|
+
return undefined
|
|
53
|
+
return url.origin
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
function originExample(value: unknown): string {
|
|
57
|
+
const host =
|
|
58
|
+
typeof value === "string"
|
|
59
|
+
? value
|
|
60
|
+
.replace(/^[A-Za-z][A-Za-z0-9+.-]*:\/*/, "")
|
|
61
|
+
.replace(/^[^@/?#]*@/, "")
|
|
62
|
+
.split(/[/?#]/)[0]
|
|
63
|
+
: ""
|
|
64
|
+
try {
|
|
65
|
+
if (host) return new URL("https://" + host).origin
|
|
66
|
+
} catch {
|
|
67
|
+
return "https://example.com"
|
|
68
|
+
}
|
|
69
|
+
return "https://example.com"
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/** Locale code → origin when every locale sets `domain`, `undefined` when none does. */
|
|
73
|
+
function resolveDomains(
|
|
74
|
+
entries: (string | LocaleInput)[],
|
|
75
|
+
locales: LocaleInfo[],
|
|
76
|
+
strategySet: boolean,
|
|
77
|
+
): Record<string, string> | undefined {
|
|
78
|
+
const given = entries.map((entry) => (typeof entry === "string" ? undefined : entry.domain))
|
|
79
|
+
if (given.every((domain) => domain === undefined)) return undefined
|
|
80
|
+
const domains: Record<string, string> = {}
|
|
81
|
+
const byHost = new Map<string, string>()
|
|
82
|
+
given.forEach((domain, index) => {
|
|
83
|
+
if (domain === undefined) return
|
|
84
|
+
const origin = originOf(domain)
|
|
85
|
+
if (!origin)
|
|
86
|
+
fail(
|
|
87
|
+
`i18n.locales[${index}].domain ${JSON.stringify(domain)} must be an origin such as ${JSON.stringify(originExample(domain))}`,
|
|
88
|
+
)
|
|
89
|
+
const { code } = locales[index]!
|
|
90
|
+
const host = new URL(origin).host
|
|
91
|
+
const other = byHost.get(host)
|
|
92
|
+
if (other !== undefined)
|
|
93
|
+
fail(
|
|
94
|
+
`i18n.locales: ${JSON.stringify(other)} and ${JSON.stringify(code)} share the domain ${JSON.stringify(domains[other])}`,
|
|
95
|
+
)
|
|
96
|
+
byHost.set(host, code)
|
|
97
|
+
domains[code] = origin
|
|
98
|
+
})
|
|
99
|
+
const missing = given.indexOf(undefined)
|
|
100
|
+
if (missing !== -1) fail(`i18n.locales[${missing}] has no domain; set domain on every locale or none`)
|
|
101
|
+
if (strategySet)
|
|
102
|
+
fail("i18n.strategy cannot be set with locales[].domain; each domain serves one locale without a prefix")
|
|
103
|
+
return domains
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/** The options with their defaults, or the build error of the first value that is wrong. */
|
|
107
|
+
export function resolveOptions(input: Partial<I18nOptions> | undefined): ResolvedI18nOptions {
|
|
108
|
+
const options = input ?? {}
|
|
109
|
+
if (!Array.isArray(options.locales) || options.locales.length === 0)
|
|
110
|
+
fail("i18n.locales must list at least one locale")
|
|
111
|
+
const locales = options.locales.map(resolveLocale)
|
|
112
|
+
const codes = new Set<string>()
|
|
113
|
+
for (const { code } of locales) {
|
|
114
|
+
if (codes.has(code)) fail(`i18n.locales: ${JSON.stringify(code)} is listed twice`)
|
|
115
|
+
codes.add(code)
|
|
116
|
+
}
|
|
117
|
+
const defaultLocale = options.defaultLocale as string
|
|
118
|
+
if (!codes.has(defaultLocale))
|
|
119
|
+
fail(`i18n.defaultLocale ${JSON.stringify(defaultLocale)} is not in i18n.locales (${[...codes].join(", ")})`)
|
|
120
|
+
const strategy = options.strategy ?? "prefix_except_default"
|
|
121
|
+
if (!STRATEGIES.has(strategy))
|
|
122
|
+
fail(
|
|
123
|
+
`i18n.strategy ${JSON.stringify(strategy)} is not supported; use "prefix_except_default", "prefix", "prefix_and_default" or "no_prefix"`,
|
|
124
|
+
)
|
|
125
|
+
const redirectToDefaultLocale = options.redirectToDefaultLocale ?? false
|
|
126
|
+
if (redirectToDefaultLocale && strategy !== "prefix") fail('i18n.redirectToDefaultLocale needs strategy "prefix"')
|
|
127
|
+
if (strategy === "no_prefix" && Object.keys(options.pages ?? {}).length > 0)
|
|
128
|
+
fail("i18n.pages needs a prefix strategy; no_prefix keeps one path per page")
|
|
129
|
+
if (Object.hasOwn(options, "baseUrl")) fail(BASE_URL_REMOVED)
|
|
130
|
+
const timeZone = options.timeZone ?? "UTC"
|
|
131
|
+
try {
|
|
132
|
+
new Intl.DateTimeFormat("en", { timeZone })
|
|
133
|
+
} catch {
|
|
134
|
+
fail(`i18n.timeZone ${JSON.stringify(timeZone)} is not a time zone this runtime knows`)
|
|
135
|
+
}
|
|
136
|
+
const cookie = options.detect?.cookie ?? "hamur_locale"
|
|
137
|
+
if (cookie !== false && (typeof cookie !== "string" || !COOKIE_NAME.test(cookie)))
|
|
138
|
+
fail(`i18n.detect.cookie ${JSON.stringify(cookie)} is not a valid cookie name`)
|
|
139
|
+
const { redirect } = options.detect ?? {}
|
|
140
|
+
if (redirect !== undefined && redirect !== "root" && redirect !== "all" && redirect !== false)
|
|
141
|
+
fail(`i18n.detect.redirect ${JSON.stringify(redirect)} is not supported; use "root", "all" or false`)
|
|
142
|
+
const fallback = options.fallback ?? "default"
|
|
143
|
+
if (fallback !== "default" && fallback !== false) {
|
|
144
|
+
if (typeof fallback !== "object" || fallback === null || Array.isArray(fallback))
|
|
145
|
+
fail(`i18n.fallback must be "default", false or an object of locale chains (got ${JSON.stringify(fallback)})`)
|
|
146
|
+
for (const [key, chain] of Object.entries(fallback)) {
|
|
147
|
+
if (!codes.has(key)) fail(`i18n.fallback: ${JSON.stringify(key)} is not in i18n.locales`)
|
|
148
|
+
if (!Array.isArray(chain)) fail(`i18n.fallback[${JSON.stringify(key)}] must be an array of locale codes`)
|
|
149
|
+
for (const entry of chain) {
|
|
150
|
+
if (!codes.has(entry))
|
|
151
|
+
fail(`i18n.fallback[${JSON.stringify(key)}]: ${JSON.stringify(entry)} is not in i18n.locales`)
|
|
152
|
+
if (entry === key) fail(`i18n.fallback[${JSON.stringify(key)}] lists ${JSON.stringify(key)} itself`)
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
for (const [name, paths] of Object.entries(options.pages ?? {})) {
|
|
157
|
+
if (paths?.[defaultLocale] === false)
|
|
158
|
+
fail(`i18n.pages.${name}.${defaultLocale}: the default locale always has its page`)
|
|
159
|
+
}
|
|
160
|
+
const missingPage = options.missingPage ?? "404"
|
|
161
|
+
if (missingPage !== "404" && missingPage !== "redirect" && missingPage !== "rewrite")
|
|
162
|
+
fail(`i18n.missingPage must be "404", "redirect" or "rewrite" (got ${JSON.stringify(missingPage)})`)
|
|
163
|
+
const domains = resolveDomains(options.locales, locales, options.strategy !== undefined)
|
|
164
|
+
const localizeLinks = options.localizeLinks ?? true
|
|
165
|
+
if (typeof localizeLinks !== "boolean")
|
|
166
|
+
fail(`i18n.localizeLinks must be a boolean (got ${JSON.stringify(localizeLinks)})`)
|
|
167
|
+
const split = options.split ?? false
|
|
168
|
+
if (split !== false && split !== "route")
|
|
169
|
+
fail(`i18n.split ${JSON.stringify(split)} is not supported; use false or "route"`)
|
|
170
|
+
const dropUnusedKeys = options.dropUnusedKeys ?? false
|
|
171
|
+
if (typeof dropUnusedKeys !== "boolean")
|
|
172
|
+
fail(`i18n.dropUnusedKeys must be a boolean (got ${JSON.stringify(dropUnusedKeys)})`)
|
|
173
|
+
const keepKeys = options.keepKeys ?? []
|
|
174
|
+
if (!Array.isArray(keepKeys) || keepKeys.some((glob) => typeof glob !== "string" || glob === ""))
|
|
175
|
+
fail('i18n.keepKeys must be an array of key globs such as "status.*"')
|
|
176
|
+
const syntax = options.syntax ?? "mf1"
|
|
177
|
+
if (syntax !== "mf1" && syntax !== "mf2") fail(`i18n.syntax must be "mf1" or "mf2" (got ${JSON.stringify(syntax)})`)
|
|
178
|
+
const { catalog } = options
|
|
179
|
+
if (catalog !== undefined && (typeof catalog !== "string" || catalog === "")) fail(catalogMissing(catalog))
|
|
180
|
+
return {
|
|
181
|
+
locales,
|
|
182
|
+
defaultLocale,
|
|
183
|
+
strategy,
|
|
184
|
+
redirectToDefaultLocale,
|
|
185
|
+
detect: { cookie, redirect: options.detect?.redirect ?? (domains ? false : "root") },
|
|
186
|
+
pages: options.pages ?? {},
|
|
187
|
+
timeZone,
|
|
188
|
+
missingPage,
|
|
189
|
+
fallback,
|
|
190
|
+
localizeLinks,
|
|
191
|
+
split,
|
|
192
|
+
dropUnusedKeys,
|
|
193
|
+
keepKeys,
|
|
194
|
+
syntax,
|
|
195
|
+
...(catalog === undefined ? {} : { catalog }),
|
|
196
|
+
...(domains ? { domains } : {}),
|
|
197
|
+
}
|
|
198
|
+
}
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
/// <reference path="../env.d.ts" />
|
|
2
|
+
import { syntax } from "#hamur/i18n/options"
|
|
3
|
+
import { catalogURL, type CatalogFrom } from "./catalog-loader.ts"
|
|
4
|
+
import { interpretCatalog, parseCatalog } from "./interpret.ts"
|
|
5
|
+
import { messageStore } from "./messages.ts"
|
|
6
|
+
|
|
7
|
+
const loading = new Map<string, Promise<undefined>>()
|
|
8
|
+
|
|
9
|
+
async function fetchCatalog(code: string, from: CatalogFrom): Promise<undefined> {
|
|
10
|
+
try {
|
|
11
|
+
const response = await fetch(catalogURL(from.baseURL, code, from.version))
|
|
12
|
+
if (!response.ok) throw new Error(String(response.status))
|
|
13
|
+
messageStore.setRemote(code, interpretCatalog(parseCatalog(await response.json(), syntax).parsed, syntax))
|
|
14
|
+
} catch {
|
|
15
|
+
loading.delete(code)
|
|
16
|
+
}
|
|
17
|
+
return undefined
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/** `GET <baseURL>_hamur/i18n/<code>` once per document and code (the head preloads it), in `messageStore` before the render. */
|
|
21
|
+
export function loadCatalog(code: string, from: CatalogFrom): Promise<undefined> {
|
|
22
|
+
let pending = loading.get(code)
|
|
23
|
+
if (!pending) {
|
|
24
|
+
pending = fetchCatalog(code, from)
|
|
25
|
+
loading.set(code, pending)
|
|
26
|
+
}
|
|
27
|
+
return pending
|
|
28
|
+
}
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import type { HamurEvent } from "hamur/server"
|
|
2
|
+
|
|
3
|
+
/** What `loadCatalog` of the server or the client module needs: the request on the server, `app.baseURL` in the browser. */
|
|
4
|
+
export interface CatalogFrom {
|
|
5
|
+
event?: HamurEvent | undefined
|
|
6
|
+
baseURL: string
|
|
7
|
+
/** In the browser, the version the server rendered with (`app.modulePayload.i18nCatalog`). */
|
|
8
|
+
version?: string | undefined
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
/** Loads the run-time catalog of `code` into `messageStore`; the server's answers the version it holds. */
|
|
12
|
+
export type CatalogLoader = (code: string, from: CatalogFrom) => Promise<string | undefined>
|
|
13
|
+
|
|
14
|
+
/** The preload and fetch URL; `?v=` names the catalog the server rendered with, so the browser never reuses another. */
|
|
15
|
+
export const catalogURL = (baseURL: string, code: string, version: string | undefined): string =>
|
|
16
|
+
baseURL +
|
|
17
|
+
"_hamur/i18n/" +
|
|
18
|
+
encodeURIComponent(code) +
|
|
19
|
+
(version === undefined ? "" : "?v=" + encodeURIComponent(version))
|
|
20
|
+
|
|
21
|
+
let serverLoader: CatalogLoader | undefined
|
|
22
|
+
|
|
23
|
+
/** The server's loader, which the module's door installs on its first request when `i18n.catalog` is set. */
|
|
24
|
+
export const serverCatalog = (): CatalogLoader | undefined => serverLoader
|
|
25
|
+
|
|
26
|
+
export function installServerCatalog(loader: CatalogLoader): void {
|
|
27
|
+
serverLoader = loader
|
|
28
|
+
}
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
/// <reference path="../env.d.ts" />
|
|
2
|
+
import source from "#hamur/i18n/catalog-source"
|
|
3
|
+
import { locales, syntax } from "#hamur/i18n/options"
|
|
4
|
+
import { useStorage, type HamurEvent } from "hamur/server"
|
|
5
|
+
import { answerCatalog, createCatalogCache, type CatalogDefinition, type CatalogStorage } from "./catalog.ts"
|
|
6
|
+
import type { CatalogFrom } from "./catalog-loader.ts"
|
|
7
|
+
import { messageStore } from "./messages.ts"
|
|
8
|
+
|
|
9
|
+
async function definition(): Promise<CatalogDefinition> {
|
|
10
|
+
const loaded = source ? (await source()).default : undefined
|
|
11
|
+
if (typeof (loaded as CatalogDefinition | undefined)?.load !== "function")
|
|
12
|
+
throw new TypeError("the file of i18n.catalog must export default defineCatalog({ … })")
|
|
13
|
+
return loaded as CatalogDefinition
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
const storage = (): CatalogStorage => {
|
|
17
|
+
const kept = useStorage("cache")
|
|
18
|
+
return { getItem: (key) => kept.getItem(key), setItem: (key, value, options) => kept.setItem(key, value, options) }
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
const cache = createCatalogCache({
|
|
22
|
+
definition,
|
|
23
|
+
syntax,
|
|
24
|
+
codes: locales.map((locale) => locale.code),
|
|
25
|
+
store: messageStore,
|
|
26
|
+
storage,
|
|
27
|
+
warn: (line) => console.warn(line),
|
|
28
|
+
})
|
|
29
|
+
|
|
30
|
+
/** The run-time catalog of `code`, in `messageStore` for the render of `from.event`. */
|
|
31
|
+
export async function loadCatalog(code: string, from: CatalogFrom): Promise<string | undefined> {
|
|
32
|
+
const entry = await cache.ensure(code, from.event)
|
|
33
|
+
return entry && !entry.failed ? entry.version : undefined
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export const catalogAnswer = (event: HamurEvent): Promise<Response> => answerCatalog(event.request, cache, event)
|