@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.
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 +17 -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 +122 -4
  77. package/src/adapters/angular.ts +65 -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,190 @@
1
+ import type { HamurEvent } from "hamur/server"
2
+ import type { HamurLocale } from "../types.ts"
3
+ import { interpretCatalog, parseCatalog } from "./interpret.ts"
4
+ import type { MessageStore } from "./messages.ts"
5
+
6
+ /** The default export of the file `i18n.catalog` names. */
7
+ export interface CatalogDefinition {
8
+ /** The messages of `code`, source strings in the app's `syntax`; called once per code and `ttl`. */
9
+ load(code: HamurLocale, event: HamurEvent): Promise<Record<string, string>> | Record<string, string>
10
+ /** Seconds the parsed catalog is kept; default 300. */
11
+ ttl?: number
12
+ }
13
+
14
+ export const DEFAULT_TTL = 300
15
+
16
+ /** The run-time catalog of `i18n.catalog`; checks `load` and `ttl` and returns the definition. */
17
+ export function defineCatalog(definition: CatalogDefinition): CatalogDefinition {
18
+ if (typeof definition?.load !== "function") throw new TypeError("defineCatalog needs load(code, event)")
19
+ const { ttl } = definition
20
+ if (ttl !== undefined && (typeof ttl !== "number" || !(ttl > 0) || !Number.isFinite(ttl)))
21
+ throw new TypeError("defineCatalog: ttl must be a positive number of seconds (got " + String(ttl) + ")")
22
+ return definition
23
+ }
24
+
25
+ /** The value kept in `useStorage("cache")` under `i18n:catalog:<code>`: source strings, parsed again by each process, so no build's parse tree outlives it. */
26
+ export interface StoredCatalog {
27
+ syntax: "mf1" | "mf2"
28
+ /** Milliseconds since the epoch. */
29
+ expires: number
30
+ messages: Record<string, string>
31
+ }
32
+
33
+ export interface CatalogStorage {
34
+ getItem(key: string): Promise<unknown>
35
+ setItem(key: string, value: StoredCatalog, options: { ttl: number }): Promise<void>
36
+ }
37
+
38
+ export interface CatalogEntry {
39
+ /** The messages that parsed; `{}` after a failed load. */
40
+ messages: Record<string, string>
41
+ expires: number
42
+ ttl: number
43
+ failed: boolean
44
+ /** The `?v=` of the preload and the client's fetch: the catalog this entry holds. */
45
+ version: string
46
+ }
47
+
48
+ /** A `load` that has not answered after this many milliseconds fails. */
49
+ export const LOAD_TIMEOUT = 10_000
50
+
51
+ export interface CatalogCacheOptions {
52
+ definition: () => Promise<CatalogDefinition>
53
+ syntax: "mf1" | "mf2"
54
+ codes: readonly HamurLocale[]
55
+ store: MessageStore
56
+ storage?: () => CatalogStorage
57
+ warn: (line: string) => void
58
+ now?: () => number
59
+ /** Milliseconds; default `LOAD_TIMEOUT`. */
60
+ timeout?: number
61
+ }
62
+
63
+ export interface CatalogCache {
64
+ /**
65
+ * The entry of `code`, loaded at most once per `ttl`; concurrent calls share one load. Once `ttl` passes the stale entry
66
+ * answers while one load refreshes it in the background. `undefined` for a code not configured.
67
+ */
68
+ ensure(code: string, event: HamurEvent | undefined): Promise<CatalogEntry | undefined>
69
+ }
70
+
71
+ export const catalogKey = (code: string): string => "i18n:catalog:" + code
72
+
73
+ const isRecord = (value: unknown): value is Record<string, unknown> =>
74
+ value !== null && typeof value === "object" && !Array.isArray(value)
75
+
76
+ function isStored(value: unknown, syntax: "mf1" | "mf2"): value is StoredCatalog {
77
+ return isRecord(value) && value.syntax === syntax && typeof value.expires === "number" && isRecord(value.messages)
78
+ }
79
+
80
+ const reasonOf = (error: unknown): string => (error instanceof Error ? error.message : String(error))
81
+
82
+ const kindOf = (value: unknown): string => (value === null ? "null" : Array.isArray(value) ? "an array" : typeof value)
83
+
84
+ async function withTimeout(work: unknown, ms: number): Promise<unknown> {
85
+ let timer: ReturnType<typeof setTimeout> | undefined
86
+ const late = new Promise<never>((_, reject) => {
87
+ timer = setTimeout(() => reject(new Error("load did not answer within " + ms / 1000 + " s")), ms)
88
+ })
89
+ try {
90
+ return await Promise.race([work, late])
91
+ } finally {
92
+ clearTimeout(timer)
93
+ }
94
+ }
95
+
96
+ /** The server's run-time catalogs: parsed once per code and `ttl`, kept in storage, installed in `store`; a failure logs once per `ttl`. */
97
+ export function createCatalogCache(options: CatalogCacheOptions): CatalogCache {
98
+ const { syntax, codes, store, warn } = options
99
+ const now = options.now ?? Date.now
100
+ const timeout = options.timeout ?? LOAD_TIMEOUT
101
+ const entries = new Map<string, CatalogEntry>()
102
+ const loading = new Map<string, Promise<CatalogEntry>>()
103
+
104
+ const failed = (code: string, ttl: number, error: unknown): CatalogEntry => {
105
+ warn(
106
+ "[hamur] i18n: catalog load(" +
107
+ JSON.stringify(code) +
108
+ ") failed: " +
109
+ reasonOf(error) +
110
+ "; the file catalogs answer",
111
+ )
112
+ const expires = now() + ttl * 1000
113
+ const entry: CatalogEntry = { messages: {}, expires, ttl, failed: true, version: String(expires) }
114
+ entries.set(code, entry)
115
+ store.setRemote(code, undefined)
116
+ return entry
117
+ }
118
+
119
+ async function refresh(code: HamurLocale, event: HamurEvent | undefined): Promise<CatalogEntry> {
120
+ let ttl = DEFAULT_TTL
121
+ try {
122
+ const definition = await options.definition()
123
+ ttl = definition.ttl ?? DEFAULT_TTL
124
+ const storage = options.storage?.()
125
+ const found = storage ? await storage.getItem(catalogKey(code)).catch(() => undefined) : undefined
126
+ const kept = isStored(found, syntax) && found.expires > now() ? found : undefined
127
+ let source: unknown = kept?.messages
128
+ const expires = kept?.expires ?? now() + ttl * 1000
129
+ if (!kept) {
130
+ source = await withTimeout(definition.load(code, event as HamurEvent), timeout)
131
+ if (!isRecord(source))
132
+ throw new TypeError("load must return an object of message strings (got " + kindOf(source) + ")")
133
+ }
134
+ const run = parseCatalog(source, syntax)
135
+ for (const { key, reason } of run.skipped)
136
+ warn("[hamur] i18n: catalog " + code + " " + JSON.stringify(key) + ": " + reason)
137
+ const catalog = interpretCatalog(run.parsed, syntax)
138
+ if (storage && !kept)
139
+ await storage
140
+ .setItem(catalogKey(code), { syntax, expires, messages: run.messages }, { ttl })
141
+ .catch(() => undefined)
142
+ const entry: CatalogEntry = { messages: run.messages, expires, ttl, failed: false, version: String(expires) }
143
+ store.setRemote(code, catalog)
144
+ entries.set(code, entry)
145
+ return entry
146
+ } catch (error) {
147
+ return failed(code, ttl, error)
148
+ }
149
+ }
150
+
151
+ return {
152
+ ensure(code, event) {
153
+ const known = codes.find((own) => own === code)
154
+ if (known === undefined) return Promise.resolve(undefined)
155
+ const held = entries.get(code)
156
+ if (held && now() < held.expires) return Promise.resolve(held)
157
+ let pending = loading.get(code)
158
+ if (!pending) {
159
+ pending = refresh(known, event).finally(() => loading.delete(code))
160
+ loading.set(code, pending)
161
+ if (held) event?.waitUntil(pending)
162
+ }
163
+ return held ? Promise.resolve(held) : pending
164
+ },
165
+ }
166
+ }
167
+
168
+ /** `GET <baseURL>_hamur/i18n/<code>`: the run-time messages as JSON, 404 for a code not configured, 405 for another method. */
169
+ export async function answerCatalog(
170
+ request: Request,
171
+ cache: CatalogCache,
172
+ event: HamurEvent | undefined,
173
+ ): Promise<Response> {
174
+ const { method } = request
175
+ if (method !== "GET" && method !== "HEAD") return new Response(null, { status: 405, headers: { allow: "GET, HEAD" } })
176
+ const segment = /\/_hamur\/i18n\/([^/]+)$/.exec(new URL(request.url).pathname)?.[1]
177
+ let code: string | undefined
178
+ try {
179
+ code = segment === undefined ? undefined : decodeURIComponent(segment)
180
+ } catch {
181
+ code = undefined
182
+ }
183
+ const entry = code === undefined ? undefined : await cache.ensure(code, event)
184
+ if (!entry) return new Response(null, { status: 404 })
185
+ const headers = {
186
+ "content-type": "application/json; charset=utf-8",
187
+ "cache-control": entry.failed ? "no-store" : "public, max-age=" + entry.ttl,
188
+ }
189
+ return new Response(method === "HEAD" ? null : JSON.stringify(entry.messages), { status: 200, headers })
190
+ }
@@ -0,0 +1,9 @@
1
+ export type Fallback = "default" | false | Record<string, string[]>
2
+
3
+ /** The locales a missing key of `code` is looked up in, in order; the default locale ends every chain but its own. */
4
+ export function fallbackChain(fallback: Fallback | undefined, defaultLocale: string, code: string): string[] {
5
+ if (code === defaultLocale || fallback === false) return []
6
+ if (fallback === undefined || fallback === "default") return [defaultLocale]
7
+ const own = (fallback[code] ?? []).filter((entry) => entry !== code && entry !== defaultLocale)
8
+ return [...new Set(own), defaultLocale]
9
+ }
@@ -0,0 +1,102 @@
1
+ import type { RichParts } from "../types.ts"
2
+
3
+ const MAX_ENTRIES = 256
4
+
5
+ type Out = string | RichParts
6
+ export type PluralCase = Out | ((count: string) => Out)
7
+
8
+ /** The formatter set `f` the compiled messages receive, bound to one locale. */
9
+ export interface Formatters {
10
+ n(value: number | bigint | unknown, options?: Intl.NumberFormatOptions): string
11
+ d(value: Date | number | unknown, options?: Intl.DateTimeFormatOptions): string
12
+ p(value: unknown, offset: number, cases: Record<string, PluralCase>, ordinal: boolean): Out
13
+ s(value: unknown, cases: Record<string, Out | (() => Out)>): Out
14
+ }
15
+
16
+ function cached<T>(cache: Map<string, T>, key: string, make: () => T): T {
17
+ let value = cache.get(key)
18
+ if (value === undefined) {
19
+ if (cache.size >= MAX_ENTRIES) cache.clear()
20
+ value = make()
21
+ cache.set(key, value)
22
+ }
23
+ return value
24
+ }
25
+
26
+ const numberFormats = new Map<string, Intl.NumberFormat>()
27
+ const dateFormats = new Map<string, Intl.DateTimeFormat>()
28
+ const pluralRules = new Map<string, Intl.PluralRules>()
29
+
30
+ export const numberFormat = (language: string, options: Intl.NumberFormatOptions = {}): Intl.NumberFormat =>
31
+ cached(numberFormats, `${language}\n${JSON.stringify(options)}`, () => new Intl.NumberFormat(language, options))
32
+
33
+ export const dateFormat = (language: string, options: Intl.DateTimeFormatOptions): Intl.DateTimeFormat =>
34
+ cached(dateFormats, `${language}\n${JSON.stringify(options)}`, () => new Intl.DateTimeFormat(language, options))
35
+
36
+ export const pluralRule = (language: string, type: Intl.PluralRulesOptions["type"]): Intl.PluralRules =>
37
+ cached(pluralRules, `${language}\n${type}`, () => new Intl.PluralRules(language, { type }))
38
+
39
+ /** The server's formatted text by `<kind>|<language>|<options>`, then by the value's key (a `Date` by its time, `-0` apart from `0`). */
40
+ export type FormattedTexts = Record<string, Record<string, string>>
41
+
42
+ export interface FormatterTexts {
43
+ read(): FormattedTexts | undefined
44
+ write: boolean
45
+ /** Called on the first write when `read()` has no table yet. */
46
+ create?(): FormattedTexts
47
+ }
48
+
49
+ const keyOf = (value: number | bigint) => (Object.is(value, -0) ? "-0" : String(value))
50
+
51
+ function recorded(texts: FormatterTexts | undefined, table: string, value: string, make: () => string): string {
52
+ if (!texts) return make()
53
+ const known = texts.read()?.[table]?.[value]
54
+ if (known !== undefined) return known
55
+ const text = make()
56
+ if (texts.write) {
57
+ const all = texts.read() ?? texts.create?.()
58
+ if (all) (all[table] ??= {})[value] = text
59
+ }
60
+ return text
61
+ }
62
+
63
+ const run = <A extends unknown[]>(value: Out | ((...args: A) => Out), ...args: A): Out =>
64
+ typeof value === "function" ? value(...args) : value
65
+
66
+ /**
67
+ * `Intl` formatters are cached per language and options; `timeZone` is the config's unless a call's options set one.
68
+ * With `texts`, `n`, `d` and the plural category read the server's text first.
69
+ */
70
+ export function createFormatters(language: string, timeZone: string, texts?: FormatterTexts): Formatters {
71
+ const f: Formatters = {
72
+ n(value, options) {
73
+ if (typeof value !== "number" && typeof value !== "bigint") return String(value)
74
+ return recorded(texts, `n|${language}|${JSON.stringify(options ?? {})}`, keyOf(value), () =>
75
+ numberFormat(language, options).format(value),
76
+ )
77
+ },
78
+ d(value, options) {
79
+ if (!(value instanceof Date) && typeof value !== "number") return String(value)
80
+ const resolved = { timeZone, ...options }
81
+ const at = value instanceof Date ? value.getTime() : value
82
+ return recorded(texts, `d|${language}|${JSON.stringify(resolved)}`, String(at), () =>
83
+ dateFormat(language, resolved).format(value),
84
+ )
85
+ },
86
+ p(value, offset, cases, ordinal) {
87
+ const count = typeof value === "bigint" ? Number(value) : value
88
+ if (typeof count !== "number" || Number.isNaN(count)) return run(cases.other!, String(value))
89
+ const exact = cases[`=${count}`]
90
+ const shifted = count - offset
91
+ const type = ordinal ? "ordinal" : "cardinal"
92
+ const category =
93
+ exact === undefined
94
+ ? recorded(texts, `p|${language}|${type}`, keyOf(shifted), () => pluralRule(language, type).select(shifted))
95
+ : undefined
96
+ const chosen = exact ?? cases[category!] ?? cases.other!
97
+ return typeof chosen === "function" ? chosen(f.n(shifted)) : chosen
98
+ },
99
+ s: (value, cases) => run(Object.hasOwn(cases, String(value)) ? cases[String(value)]! : cases.other!),
100
+ }
101
+ return f
102
+ }
@@ -0,0 +1,57 @@
1
+ import type { ResolvedRoute } from "hamur/adapter"
2
+ import { siteConfigOf, type AppContext, type HeadEntry, type HeadInput } from "hamur/app"
3
+ import type { I18nRuntime, HamurLocale } from "../types.ts"
4
+ import { configOf, copyMissing, readsRequestLocale, routeBaseName } from "./locale.ts"
5
+
6
+ const entries = new WeakMap<object, HeadEntry>()
7
+
8
+ /**
9
+ * The one i18n head entry of `app`, written on the first call and patched after; under `no_prefix` the locale is
10
+ * `i18n.locale` and no alternate is written; with domains the locale is `i18n.locale` and each link's origin is its locale's domain.
11
+ */
12
+ export function applyLocaleHead(app: AppContext, route: ResolvedRoute): void {
13
+ const i18n = (app as AppContext & { i18n: I18nRuntime }).i18n
14
+ const config = configOf(i18n)
15
+ const single = config.strategy === "no_prefix"
16
+ const { domains } = config
17
+ const locale = readsRequestLocale(i18n) ? i18n.locale : i18n.localeOf(route.path)
18
+ const base = route.name ? routeBaseName(route.name) : undefined
19
+ const present = i18n.locales.filter((other) => base === undefined || !copyMissing(i18n, base, other.code))
20
+ const alternates = single ? [] : present.filter((other) => other.code !== locale.code)
21
+ const head: HeadInput = {
22
+ htmlAttrs: { lang: locale.language, dir: locale.dir },
23
+ meta: [
24
+ { property: "og:locale", content: locale.language.replaceAll("-", "_") },
25
+ ...alternates.map((other) => ({ property: "og:locale:alternate", content: other.language.replaceAll("-", "_") })),
26
+ ],
27
+ }
28
+ const origin = siteConfigOf(app).url
29
+ if (origin !== undefined || domains) {
30
+ const prefix = (app.config.runtimeApp?.baseURL ?? config.baseURL ?? "/").replace(/\/$/, "")
31
+ const bare = { ...route, query: {}, hash: "" }
32
+ const href = (code: HamurLocale) => {
33
+ const path = i18n.switchLocalePath(bare, code)
34
+ return path.startsWith("/") ? (domains?.[code] ?? origin) + prefix + path : path
35
+ }
36
+ const hreflang = single
37
+ ? []
38
+ : [
39
+ ...present.map((other) => ({
40
+ key: `hreflang:${other.language}`,
41
+ rel: "alternate",
42
+ hreflang: other.language,
43
+ href: href(other.code),
44
+ })),
45
+ { key: "hreflang:x-default", rel: "alternate", hreflang: "x-default", href: href(i18n.defaultLocale.code) },
46
+ ]
47
+ head.link = [...hreflang, { rel: "canonical", href: href(locale.code) }]
48
+ }
49
+ const entry = entries.get(app)
50
+ if (entry) entry.patch(head)
51
+ else entries.set(app, app.head.push(head))
52
+ }
53
+
54
+ /** Browser only: writes the stacked entries to the document once the new page has rendered; the adapters apply only from `useHead`. */
55
+ export function commitLocaleHead(app: AppContext): void {
56
+ if (typeof document !== "undefined") app.head.apply()
57
+ }