@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.
Files changed (155) hide show
  1. package/LICENSE +22 -0
  2. package/README.md +38 -2
  3. package/dist/chunks/bun-index-1ve1hj66.js +744 -0
  4. package/dist/chunks/bun-index-8bw4xpv8.js +93 -0
  5. package/dist/chunks/bun-index-ej6vjnjs.js +297 -0
  6. package/dist/chunks/bun-index-pdepkyy1.js +474 -0
  7. package/dist/src/adapters/angular.js +67 -0
  8. package/dist/src/adapters/html.js +34 -0
  9. package/dist/src/adapters/preact.js +23 -0
  10. package/dist/src/adapters/react.js +23 -0
  11. package/dist/src/adapters/solid.js +48 -0
  12. package/dist/src/adapters/svelte.js +74 -0
  13. package/dist/src/adapters/vue.js +48 -0
  14. package/dist/src/cli.js +1898 -0
  15. package/dist/src/index.js +2755 -0
  16. package/dist/src/load.js +35 -0
  17. package/dist/src/server/index.js +395 -0
  18. package/dist/types/src/adapters/angular.d.ts +20 -0
  19. package/dist/types/src/adapters/bind.d.ts +44 -0
  20. package/dist/types/src/adapters/html.d.ts +5 -0
  21. package/dist/types/src/adapters/preact.d.ts +6 -0
  22. package/dist/types/src/adapters/react.d.ts +6 -0
  23. package/dist/types/src/adapters/solid.d.ts +9 -0
  24. package/dist/types/src/adapters/svelte.d.ts +12 -0
  25. package/dist/types/src/adapters/vue.d.ts +8 -0
  26. package/dist/types/src/build/catalog.d.ts +5 -0
  27. package/dist/types/src/build/drop.d.ts +12 -0
  28. package/dist/types/src/build/extract.d.ts +11 -0
  29. package/dist/types/src/build/head.d.ts +4 -0
  30. package/dist/types/src/build/messages.d.ts +27 -0
  31. package/dist/types/src/build/prerender.d.ts +10 -0
  32. package/dist/types/src/build/routes.d.ts +14 -0
  33. package/dist/types/src/build/split.d.ts +37 -0
  34. package/dist/types/src/build/types.d.ts +15 -0
  35. package/dist/types/src/cli.d.ts +12 -0
  36. package/dist/types/src/compiler/compile.d.ts +17 -0
  37. package/dist/types/src/compiler/mf2-parse.d.ts +62 -0
  38. package/dist/types/src/compiler/mf2.d.ts +3 -0
  39. package/dist/types/src/compiler/parse.d.ts +58 -0
  40. package/dist/types/src/compiler/skeleton.d.ts +7 -0
  41. package/dist/types/src/index.d.ts +2 -0
  42. package/dist/types/src/load.d.ts +7 -0
  43. package/dist/types/src/module.d.ts +15 -0
  44. package/dist/types/src/options.d.ts +7 -0
  45. package/dist/types/src/runtime/catalog-client.d.ts +3 -0
  46. package/dist/types/src/runtime/catalog-loader.d.ts +15 -0
  47. package/dist/types/src/runtime/catalog-server.d.ts +5 -0
  48. package/dist/types/src/runtime/catalog.d.ts +60 -0
  49. package/dist/types/src/runtime/chain.d.ts +3 -0
  50. package/dist/types/src/runtime/format.d.ts +27 -0
  51. package/dist/types/src/runtime/head.d.ts +9 -0
  52. package/dist/types/src/runtime/interpret.d.ts +20 -0
  53. package/dist/types/src/runtime/link.d.ts +8 -0
  54. package/dist/types/src/runtime/locale.d.ts +73 -0
  55. package/dist/types/src/runtime/match.d.ts +54 -0
  56. package/dist/types/src/runtime/messages.d.ts +42 -0
  57. package/dist/types/src/runtime/middleware.d.ts +2 -0
  58. package/dist/types/src/runtime/negotiate.d.ts +9 -0
  59. package/dist/types/src/runtime/plugin.d.ts +4 -0
  60. package/dist/types/src/runtime/redirect.d.ts +32 -0
  61. package/dist/types/src/runtime/rich.d.ts +5 -0
  62. package/dist/types/src/runtime/translate.d.ts +21 -0
  63. package/dist/types/src/server/catalog.d.ts +2 -0
  64. package/dist/types/src/server/context.d.ts +48 -0
  65. package/dist/types/src/server/door-all-catalog.d.ts +3 -0
  66. package/dist/types/src/server/door-all.d.ts +2 -0
  67. package/dist/types/src/server/door-catalog.d.ts +3 -0
  68. package/dist/types/src/server/door-root-catalog.d.ts +3 -0
  69. package/dist/types/src/server/door-root.d.ts +2 -0
  70. package/dist/types/src/server/door.d.ts +2 -0
  71. package/dist/types/src/server/index.d.ts +7 -0
  72. package/dist/types/src/server/preferred.d.ts +6 -0
  73. package/dist/types/src/server/redirect.d.ts +3 -0
  74. package/dist/types/src/server/setup.d.ts +2 -0
  75. package/dist/types/src/types.d.ts +163 -0
  76. package/package.json +155 -4
  77. package/src/adapters/angular.ts +58 -0
  78. package/src/adapters/bind.ts +144 -0
  79. package/src/adapters/html.ts +35 -0
  80. package/src/adapters/preact.ts +18 -0
  81. package/src/adapters/react.ts +18 -0
  82. package/src/adapters/solid.ts +44 -0
  83. package/src/adapters/svelte.ts +75 -0
  84. package/src/adapters/test/SveltePage.svelte +18 -0
  85. package/src/adapters/test/SvelteReporting.svelte +20 -0
  86. package/src/adapters/test/SvelteRich.svelte +11 -0
  87. package/src/adapters/test/SvelteRichPlain.svelte +11 -0
  88. package/src/adapters/test/peer.ts +7 -0
  89. package/src/adapters/test/preact-client.ts +43 -0
  90. package/src/adapters/test/preact-page.ts +34 -0
  91. package/src/adapters/test/preact-rich.ts +9 -0
  92. package/src/adapters/test/react-client.ts +49 -0
  93. package/src/adapters/test/react-page.ts +34 -0
  94. package/src/adapters/test/react-rich.ts +15 -0
  95. package/src/adapters/test/runtime.ts +104 -0
  96. package/src/adapters/test/solid-client.ts +33 -0
  97. package/src/adapters/test/solid-page.ts +30 -0
  98. package/src/adapters/test/solid-rich.ts +5 -0
  99. package/src/adapters/test/svelte-client.ts +51 -0
  100. package/src/adapters/test/svelte-log.ts +2 -0
  101. package/src/adapters/test/svelte-plugin.ts +20 -0
  102. package/src/adapters/test/vue-page.ts +26 -0
  103. package/src/adapters/test/vue-rich.ts +16 -0
  104. package/src/adapters/vue.ts +44 -0
  105. package/src/build/catalog.ts +44 -0
  106. package/src/build/drop.ts +36 -0
  107. package/src/build/extract.ts +207 -0
  108. package/src/build/head.ts +10 -0
  109. package/src/build/messages.ts +347 -0
  110. package/src/build/prerender.ts +48 -0
  111. package/src/build/routes.ts +269 -0
  112. package/src/build/split.ts +240 -0
  113. package/src/build/types.ts +156 -0
  114. package/src/cli.ts +25 -0
  115. package/src/compiler/compile.ts +190 -0
  116. package/src/compiler/mf2-parse.ts +469 -0
  117. package/src/compiler/mf2.ts +393 -0
  118. package/src/compiler/parse.ts +265 -0
  119. package/src/compiler/skeleton.ts +85 -0
  120. package/src/env.d.ts +55 -0
  121. package/src/index.ts +24 -0
  122. package/src/load.ts +41 -0
  123. package/src/module.ts +66 -0
  124. package/src/options.ts +198 -0
  125. package/src/runtime/catalog-client.ts +28 -0
  126. package/src/runtime/catalog-loader.ts +28 -0
  127. package/src/runtime/catalog-server.ts +36 -0
  128. package/src/runtime/catalog.ts +190 -0
  129. package/src/runtime/chain.ts +9 -0
  130. package/src/runtime/format.ts +102 -0
  131. package/src/runtime/head.ts +57 -0
  132. package/src/runtime/interpret.ts +504 -0
  133. package/src/runtime/link.ts +36 -0
  134. package/src/runtime/locale.ts +392 -0
  135. package/src/runtime/match.ts +334 -0
  136. package/src/runtime/messages.ts +129 -0
  137. package/src/runtime/middleware.ts +32 -0
  138. package/src/runtime/negotiate.ts +61 -0
  139. package/src/runtime/plugin.ts +69 -0
  140. package/src/runtime/redirect.ts +191 -0
  141. package/src/runtime/rich.ts +21 -0
  142. package/src/runtime/translate.ts +131 -0
  143. package/src/server/catalog.ts +11 -0
  144. package/src/server/context.ts +191 -0
  145. package/src/server/door-all-catalog.ts +7 -0
  146. package/src/server/door-all.ts +5 -0
  147. package/src/server/door-catalog.ts +6 -0
  148. package/src/server/door-root-catalog.ts +7 -0
  149. package/src/server/door-root.ts +5 -0
  150. package/src/server/door.ts +4 -0
  151. package/src/server/index.ts +11 -0
  152. package/src/server/preferred.ts +12 -0
  153. package/src/server/redirect.ts +26 -0
  154. package/src/server/setup.ts +14 -0
  155. package/src/types.ts +182 -0
@@ -0,0 +1,392 @@
1
+ import { siteConfigOf, type AppContext } from "hamur/app"
2
+ import type {
3
+ I18nRouteLocation,
4
+ I18nRuntime,
5
+ LocaleInfo,
6
+ ResolvedI18nOptions,
7
+ HamurLocale,
8
+ Translator,
9
+ } from "../types.ts"
10
+ import type { FormattedTexts, FormatterTexts } from "./format.ts"
11
+ import type { Fallback } from "./chain.ts"
12
+ import { createMatcher, type Matcher, type RouteTable } from "./match.ts"
13
+ import { negotiateAll } from "./negotiate.ts"
14
+ import { loadMessages, loadRouteMessages, messageStore } from "./messages.ts"
15
+ import { createTranslators, type TextScope } from "./translate.ts"
16
+
17
+ /** What the runtime reads from `#hamur/i18n/options` and `#hamur/i18n/routes`. */
18
+ export interface I18nConfig extends RouteTable {
19
+ locales: LocaleInfo[]
20
+ defaultLocale: string
21
+ strategy: ResolvedI18nOptions["strategy"]
22
+ cookie: string | false
23
+ /** `app.baseURL` with its trailing `/`, the fallback of `app.config.runtimeApp`. */
24
+ baseURL?: string
25
+ /** `Intl` time zone of `d()` and date arguments; `"UTC"` when absent. */
26
+ timeZone?: string
27
+ /** `"default"` when absent. */
28
+ fallback?: Fallback
29
+ }
30
+
31
+ /** The prefix of the `cacheVariant` the server door sets under `no_prefix`, `locale:<code>`. */
32
+ export const LOCALE_VARIANT = "locale:"
33
+
34
+ const YEAR = 31536000
35
+
36
+ const configs = new WeakMap<I18nRuntime, I18nConfig>()
37
+ const matchers = new WeakMap<I18nRuntime, Matcher>()
38
+ const routeLoads = new WeakMap<I18nRuntime, (code: string, base: string | undefined) => Promise<void>>()
39
+ const scopedTranslators = new WeakMap<I18nRuntime, (code: HamurLocale, scope: TextScope) => Translator>()
40
+
41
+ export function configOf(runtime: I18nRuntime): I18nConfig {
42
+ const config = configs.get(runtime)
43
+ if (!config) throw new Error("i18n: not an I18nRuntime of @hamur/i18n")
44
+ return config
45
+ }
46
+
47
+ /** Loads `code` for route `base` through an app's runtime (the route middleware); `undefined` for a runtime that is not bound to an app. */
48
+ export const routeLoadOf = (
49
+ runtime: I18nRuntime,
50
+ ): ((code: string, base: string | undefined) => Promise<void>) | undefined => routeLoads.get(runtime)
51
+
52
+ /** The locale a request's context names: `locale`, else the `cacheVariant` a cache fork keeps. */
53
+ export function contextLocale(
54
+ runtime: I18nRuntime,
55
+ context: { locale?: unknown; cacheVariant?: unknown } | undefined,
56
+ ): LocaleInfo | undefined {
57
+ if (!context) return undefined
58
+ const byCode = (code: unknown) => runtime.locales.find((locale) => locale.code === code)
59
+ const variant = context.cacheVariant
60
+ return (
61
+ byCode(context.locale) ??
62
+ (typeof variant === "string" && variant.startsWith(LOCALE_VARIANT)
63
+ ? byCode(variant.slice(LOCALE_VARIANT.length))
64
+ : undefined)
65
+ )
66
+ }
67
+
68
+ /** The locale cookie, for a year, on `app.baseURL`. */
69
+ export function writeLocaleCookie(app: AppContext, cookie: string, code: string): void {
70
+ const path = app.config.runtimeApp?.baseURL ?? "/"
71
+ const secure = typeof location !== "undefined" && location.protocol === "https:" ? "; Secure" : ""
72
+ document.cookie =
73
+ cookie + "=" + encodeURIComponent(code) + "; Path=" + path + "; Max-Age=" + YEAR + "; SameSite=Lax" + secure
74
+ }
75
+
76
+ /** True when a page's locale comes from the request (`no_prefix`, or the host under `locales[].domain`), not from its path. */
77
+ export function readsRequestLocale(runtime: I18nRuntime): boolean {
78
+ const config = configs.get(runtime)
79
+ return config?.strategy === "no_prefix" || config?.domains !== undefined
80
+ }
81
+
82
+ /**
83
+ * What a page route answers on a host of `code`: `true` renders it, a string is the app path (query kept) of the
84
+ * host locale's localized copy that an original answers `301` with, and `false` is another locale's copy, a 404.
85
+ */
86
+ export function domainRoute(
87
+ runtime: I18nRuntime,
88
+ route: { name?: string | null; params: Record<string, string | string[]>; query: Record<string, string | string[]> },
89
+ code: HamurLocale,
90
+ ): boolean | string {
91
+ const config = configOf(runtime)
92
+ if (!config.domains || !route.name) return true
93
+ const base = routeBaseName(route.name)
94
+ const own = route.name === base ? config.defaultLocale : route.name.slice(base.length + 3)
95
+ const patterns = config.routes[base]
96
+ if (!patterns || patterns[code] === patterns[own]) return true
97
+ if (own !== config.defaultLocale) return false
98
+ return runtime.localePath({ name: base, params: route.params, query: route.query }, code)
99
+ }
100
+
101
+ /** The page `path` (below `app.baseURL`) names when that locale's copy is `false`: the base route name, the code and the params. */
102
+ export function missingCopyOf(
103
+ runtime: I18nRuntime,
104
+ path: string,
105
+ ): { name: string; code: string; params: Record<string, string | string[]> } | undefined {
106
+ const { missing } = configOf(runtime)
107
+ if (!missing || Object.keys(missing).length === 0) return undefined
108
+ const match = matchers.get(runtime)?.matchPath(path)
109
+ return match && missing[match.name]?.includes(match.code) ? match : undefined
110
+ }
111
+
112
+ /** Whether the copy of route `name` in `code` is `false`, so it has a path but no page. */
113
+ export const copyMissing = (runtime: I18nRuntime, name: string, code: string): boolean =>
114
+ configOf(runtime).missing?.[name]?.includes(code) === true
115
+
116
+ type Query = Record<string, string | string[]>
117
+
118
+ function queryString(query: Query | undefined): string {
119
+ const search = new URLSearchParams()
120
+ for (const [key, value] of Object.entries(query ?? {}))
121
+ for (const item of Array.isArray(value) ? value : [value]) search.append(key, item)
122
+ const text = search.toString()
123
+ return text ? `?${text}` : ""
124
+ }
125
+
126
+ const hashOf = (hash: string | undefined) => (!hash ? "" : hash.startsWith("#") ? hash : `#${hash}`)
127
+
128
+ function splitHref(href: string): { path: string; rest: string } {
129
+ const index = href.search(/[?#]/)
130
+ return index === -1 ? { path: href, rest: "" } : { path: href.slice(0, index), rest: href.slice(index) }
131
+ }
132
+
133
+ export const routeBaseName = (name: string): string => {
134
+ const index = name.indexOf("___")
135
+ return index === -1 ? name : name.slice(0, index)
136
+ }
137
+
138
+ /** The runtime `useTranslation(ctx)` of `@hamur/i18n/load` reads, which the app plugin holds: the process's on the server, the app's in the browser. */
139
+ export const loadRuntime: { current?: I18nRuntime } = {}
140
+
141
+ /** `app.i18n` over the route table and the resolved locales. */
142
+ export function createI18nRuntime(config: I18nConfig): I18nRuntime {
143
+ const matcher = createMatcher(config)
144
+ const byCode = new Map<string, LocaleInfo>(config.locales.map((locale) => [locale.code, locale]))
145
+ const defaultLocale = byCode.get(config.defaultLocale)!
146
+ const copies = new Set(config.copies)
147
+ const single = config.strategy === "no_prefix"
148
+ const prefixes = (code: string) =>
149
+ copies.has(code) && !(config.strategy === "prefix_and_default" && code === config.defaultLocale)
150
+ const translatorOf = createTranslators({
151
+ defaultLocale,
152
+ fallback: config.fallback ?? "default",
153
+ locales: config.locales,
154
+ timeZone: config.timeZone ?? "UTC",
155
+ dev: (import.meta as { dev?: boolean }).dev === true,
156
+ store: messageStore,
157
+ })
158
+ const localeFor = (code: string): LocaleInfo => {
159
+ const locale = byCode.get(code)
160
+ if (!locale) throw new Error(`i18n: "${code}" is not in i18n.locales`)
161
+ return locale
162
+ }
163
+ const firstSegment = (path: string) => /^\/?([^/?#]*)/.exec(path)![1]!
164
+ const runtime: I18nRuntime = {
165
+ locales: config.locales,
166
+ defaultLocale,
167
+ timeZone: config.timeZone ?? "UTC",
168
+ locale: defaultLocale,
169
+ async setLocale(code) {
170
+ localeFor(code)
171
+ throw new Error("i18n: setLocale needs the app's i18n (useApp().i18n)")
172
+ },
173
+ localeOf(path) {
174
+ const segment = firstSegment(path)
175
+ return copies.has(segment) ? byCode.get(segment)! : defaultLocale
176
+ },
177
+ load: (code) => loadMessages(localeFor(code).code),
178
+ translator: (code) => translatorOf(localeFor(code)),
179
+ localePath(to, code) {
180
+ localeFor(code)
181
+ if (typeof to === "string") {
182
+ if (single) return to
183
+ const { path, rest } = splitHref(to)
184
+ const match = matcher.matchPath(path)
185
+ return match ? matcher.buildPath(match.name, code, match.params) + rest : to
186
+ }
187
+ const location = to as I18nRouteLocation
188
+ const name = routeBaseName(location.name)
189
+ if (!config.routes[name]) throw new Error(`i18n: no route named "${location.name}"`)
190
+ return (
191
+ matcher.buildPath(name, single ? config.defaultLocale : code, location.params) +
192
+ queryString(location.query) +
193
+ hashOf(location.hash)
194
+ )
195
+ },
196
+ switchLocalePath(route, code) {
197
+ localeFor(code)
198
+ const rest = queryString(route.query) + hashOf(route.hash)
199
+ if (single) return route.path + rest
200
+ const name = route.name ? routeBaseName(route.name) : undefined
201
+ if (name && config.routes[name]) return matcher.buildPath(name, code, route.params) + rest
202
+ const segments = route.path.split("/").filter(Boolean)
203
+ if (copies.has(segments[0]!)) segments.shift()
204
+ if (prefixes(code)) segments.unshift(code)
205
+ return `/${segments.join("/")}${rest}`
206
+ },
207
+ absoluteLocalePath() {
208
+ throw new Error("i18n: absoluteLocalePath needs the app's i18n (useApp().i18n)")
209
+ },
210
+ allLocalePaths() {
211
+ throw new Error("i18n: allLocalePaths needs the app's i18n (useApp().i18n)")
212
+ },
213
+ routeBaseName,
214
+ preferredLocaleList: () => negotiateAll((globalThis.navigator?.languages ?? []).join(","), config.locales),
215
+ }
216
+ configs.set(runtime, config)
217
+ matchers.set(runtime, matcher)
218
+ scopedTranslators.set(runtime, (code, scope) => translatorOf(localeFor(code), scope))
219
+ return runtime
220
+ }
221
+
222
+ type LocaleRoute = Parameters<I18nRuntime["switchLocalePath"]>[0]
223
+
224
+ /** `app.modulePayload.i18n`: the table of formatted texts and, when the locale comes from the request, the locale the server rendered. */
225
+ interface I18nPayload {
226
+ texts?: FormattedTexts
227
+ locale?: string
228
+ }
229
+
230
+ export interface AppLocaleOptions {
231
+ /** On the client, the app path the document was loaded at. */
232
+ path?: string
233
+ /** On the client, the document's `?locale` value: under `no_prefix` the cookie keeps the locale it chose. */
234
+ queryLocale?: string
235
+ /** `navigateTo` of `hamur/app`. */
236
+ navigate?: (to: string) => Promise<void>
237
+ /** The navigator's `refresh()`: `refreshData()` of `hamur/app`. */
238
+ refresh?: () => Promise<void>
239
+ /** Loads the run-time catalog of a locale beside its chunks, when `i18n.catalog` is set. */
240
+ catalog?: (code: string) => Promise<void>
241
+ }
242
+
243
+ /**
244
+ * `i18n` with translators bound to `app`. On the server they record what `n`, `d` and plurals print in
245
+ * `app.modulePayload.i18n.texts` from the page render's `page:start`, and an error page starts a table of its own at `page:error`;
246
+ * on the client they read it until the first navigation after `app:mounted`. `locale` and `setLocale` of this app.
247
+ */
248
+ export function forApp(
249
+ i18n: I18nRuntime,
250
+ app: AppContext,
251
+ server = import.meta.server === true,
252
+ options: AppLocaleOptions = {},
253
+ ): I18nRuntime {
254
+ const translatorOf = scopedTranslators.get(i18n)
255
+ if (!translatorOf) throw new Error("i18n: not an I18nRuntime of @hamur/i18n")
256
+ const config = configOf(i18n)
257
+ const single = config.strategy === "no_prefix"
258
+ const { domains } = config
259
+ const fromRequest = single || domains !== undefined
260
+ const known = (code: unknown) => i18n.locales.find((locale) => locale.code === code)
261
+ let recording = false
262
+ const payload = () => app.modulePayload.i18n as I18nPayload | undefined
263
+ const entry = (): I18nPayload => {
264
+ const found = payload()
265
+ if (found) return found
266
+ const made: I18nPayload = {}
267
+ app.modulePayload.i18n = made
268
+ return made
269
+ }
270
+ const dropTexts = () => {
271
+ const found = payload()
272
+ if (!found) return
273
+ delete found.texts
274
+ if (found.locale === undefined) delete app.modulePayload.i18n
275
+ }
276
+ const read = () => payload()?.texts
277
+ const texts: FormatterTexts = server
278
+ ? {
279
+ read,
280
+ get write() {
281
+ return recording
282
+ },
283
+ create: () => (entry().texts = {}),
284
+ }
285
+ : { read, write: false }
286
+ const scope: TextScope = { owner: app, texts }
287
+ const loadRoute = (code: string, base: string | undefined): Promise<void> => {
288
+ const files = loadRouteMessages(code, base)
289
+ return options.catalog ? Promise.all([files, options.catalog(code)]).then(() => undefined) : files
290
+ }
291
+ let route: LocaleRoute | undefined
292
+ let chosen = fromRequest && !server ? known(payload()?.locale) : undefined
293
+ const startPath = options.path ?? "/"
294
+ if (single && chosen && config.cookie && options.queryLocale === chosen.code)
295
+ writeLocaleCookie(app, config.cookie, chosen.code)
296
+ const requested = () => (server ? contextLocale(i18n, app.event?.context) : undefined)
297
+ const current = (): LocaleInfo => {
298
+ if (fromRequest) return chosen ?? requested() ?? i18n.defaultLocale
299
+ if (route) return i18n.localeOf(route.path)
300
+ return requested() ?? i18n.localeOf(startPath)
301
+ }
302
+ const onDomain = (code: string, path: string): string => {
303
+ if (!domains || code === current().code || !path.startsWith("/")) return path
304
+ return domains[code] + (app.config.runtimeApp?.baseURL ?? config.baseURL ?? "/").replace(/\/$/, "") + path
305
+ }
306
+ const originOf = (code: string, name: string): string => {
307
+ const origin = domains?.[code] ?? siteConfigOf(app).url
308
+ if (origin === undefined) throw new Error("i18n: " + name + " needs site.url or locales[].domain")
309
+ return origin.replace(/\/$/, "")
310
+ }
311
+ const absolute = (to: string | I18nRouteLocation, code: HamurLocale, name: string): string => {
312
+ const path = i18n.localePath(to, code)
313
+ if (!path.startsWith("/")) return path
314
+ return originOf(code, name) + (app.config.runtimeApp?.baseURL ?? config.baseURL ?? "/").replace(/\/$/, "") + path
315
+ }
316
+ const baseOf = (to: string | I18nRouteLocation): string | undefined =>
317
+ typeof to === "string" ? matchers.get(i18n)?.matchPath(splitHref(to).path)?.name : routeBaseName(to.name)
318
+ const runtime: I18nRuntime = {
319
+ ...i18n,
320
+ translator: (code) => translatorOf(code, scope),
321
+ absoluteLocalePath: (to, code) => absolute(to, code ?? current().code, "absoluteLocalePath"),
322
+ allLocalePaths(to) {
323
+ const base = baseOf(to)
324
+ return i18n.locales
325
+ .filter((locale) => base === undefined || !copyMissing(i18n, base, locale.code))
326
+ .map(({ code, language }) => ({ code, language, url: absolute(to, code, "allLocalePaths") }))
327
+ },
328
+ preferredLocaleList: () =>
329
+ server
330
+ ? negotiateAll(app.event?.request.headers.get("accept-language"), config.locales)
331
+ : i18n.preferredLocaleList(),
332
+ localePath: (to, code) => onDomain(code, i18n.localePath(to, code)),
333
+ switchLocalePath: (to, code) => onDomain(code, i18n.switchLocalePath(to, code)),
334
+ get locale() {
335
+ return current()
336
+ },
337
+ load(code) {
338
+ const locale = known(code)
339
+ if (!locale) return Promise.reject(new Error(`i18n: "${code}" is not in i18n.locales`))
340
+ return loadRoute(
341
+ locale.code,
342
+ route?.name ? routeBaseName(route.name) : matchers.get(i18n)?.matchPath(startPath)?.name,
343
+ )
344
+ },
345
+ async setLocale(code) {
346
+ const locale = known(code)
347
+ if (!locale) throw new Error(`i18n: "${code}" is not in i18n.locales`)
348
+ if (!single) {
349
+ if (!options.navigate) throw new Error("i18n: setLocale needs the app plugin's navigator")
350
+ return options.navigate(
351
+ runtime.switchLocalePath(route ?? { path: startPath, params: {}, query: {}, hash: "" }, code),
352
+ )
353
+ }
354
+ await runtime.load(code)
355
+ chosen = locale
356
+ if (server) {
357
+ if (app.event)
358
+ Object.assign(app.event.context, { locale: locale.code, cacheVariant: LOCALE_VARIANT + locale.code })
359
+ entry().locale = locale.code
360
+ return
361
+ }
362
+ if (config.cookie) writeLocaleCookie(app, config.cookie, locale.code)
363
+ await options.refresh?.()
364
+ },
365
+ }
366
+ configs.set(runtime, config)
367
+ routeLoads.set(runtime, loadRoute)
368
+ scopedTranslators.set(runtime, translatorOf)
369
+ app.hooks.hook("page:start", (to) => {
370
+ if (typeof to?.path === "string")
371
+ route = { path: to.path, name: to.name, params: to.params ?? {}, query: to.query ?? {}, hash: to.hash ?? "" }
372
+ })
373
+ if (server) {
374
+ app.hooks.hook("page:start", () => {
375
+ recording = true
376
+ if (fromRequest) entry().locale = current().code
377
+ })
378
+ app.hooks.hook("page:error", () => {
379
+ dropTexts()
380
+ recording = true
381
+ })
382
+ } else {
383
+ let mounted = false
384
+ app.hooks.hook("app:mounted", () => {
385
+ mounted = true
386
+ })
387
+ app.hooks.hook("page:start", (_route, info) => {
388
+ if (mounted && !info?.refresh) dropTexts()
389
+ })
390
+ }
391
+ return runtime
392
+ }