@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,334 @@
1
+ export type MixedPart = string | { param: string; optional?: true }
2
+
3
+ export type Segment =
4
+ | { kind: "static"; text: string }
5
+ | { kind: "mixed"; parts: MixedPart[] }
6
+ | { kind: "param"; name: string }
7
+ | { kind: "optional"; name: string }
8
+ | { kind: "catchAll"; name: string }
9
+ | { kind: "optionalCatchAll"; name: string }
10
+
11
+ /** `#hamur/i18n/routes`: each base route name's pattern per locale code, and the codes that have a URL prefix. */
12
+ export interface RouteTable {
13
+ copies: string[]
14
+ routes: Record<string, Record<string, string>>
15
+ /** Paths that match like `routes` but are never built: the default locale's prefixed copies under `prefix_and_default`. */
16
+ aliases?: Record<string, Record<string, string>>
17
+ /** Base route name → the codes whose copy is `false` (`i18n.pages`); the path such a copy would have had is in `routes`, but no page answers it. */
18
+ missing?: Record<string, string[]>
19
+ /** Locale code → origin; every code then has a path in `routes`, and `copies` is empty. */
20
+ domains?: Record<string, string>
21
+ }
22
+
23
+ export interface PathMatch {
24
+ name: string
25
+ code: string
26
+ params: Record<string, string | string[]>
27
+ }
28
+
29
+ const NAME = /^[A-Za-z_][A-Za-z0-9_]*/
30
+
31
+ function splitPath(path: string): string[] {
32
+ const start = path.startsWith("/") ? 1 : 0
33
+ const end = path.length > start && path.endsWith("/") ? path.length - 1 : path.length
34
+ return end <= start ? [] : path.slice(start, end).split("/")
35
+ }
36
+
37
+ const SEPARATORS = "-_.~"
38
+
39
+ /** The run of `-_.~` that leaves with the optional param at `index` of a mixed segment: after it, or before it when it ends the segment. */
40
+ export function optionalRun(parts: MixedPart[], index: number): { side: "before" | "after"; run: string } {
41
+ const next = parts[index + 1]
42
+ if (typeof next === "string") {
43
+ let run = 0
44
+ while (run < next.length && SEPARATORS.includes(next[run]!)) run++
45
+ return { side: "after", run: next.slice(0, run) }
46
+ }
47
+ const previous = parts[index - 1] as string
48
+ let run = previous.length
49
+ while (run > 0 && SEPARATORS.includes(previous[run - 1]!)) run--
50
+ return { side: "before", run: previous.slice(run) }
51
+ }
52
+
53
+ function parseSegment(text: string): Segment {
54
+ if (text.startsWith("**:")) {
55
+ const optional = text.endsWith("?")
56
+ const name = text.slice(3, optional ? -1 : undefined)
57
+ if (NAME.exec(name)?.[0] !== name) throw new Error(`bad catch-all name in "${text}"`)
58
+ return { kind: optional ? "optionalCatchAll" : "catchAll", name }
59
+ }
60
+ if (!text.includes(":") && !text.includes("\\")) return { kind: "static", text }
61
+ const parts: MixedPart[] = []
62
+ let literal = ""
63
+ let stray = false
64
+ let i = 0
65
+ while (i < text.length) {
66
+ if (text[i] === "\\") {
67
+ if (i === text.length - 1) throw new Error(`trailing "\\" in "${text}"`)
68
+ literal += text[i + 1]
69
+ i += 2
70
+ continue
71
+ }
72
+ if (text[i] !== ":") {
73
+ if (text[i] === "?") stray = true
74
+ literal += text[i++]
75
+ continue
76
+ }
77
+ const name = NAME.exec(text.slice(i + 1))?.[0]
78
+ if (!name) throw new Error(`missing param name in "${text}"`)
79
+ if (literal) parts.push(literal)
80
+ else if (parts.length > 0) throw new Error(`params in "${text}" need text between them`)
81
+ literal = ""
82
+ i += 1 + name.length
83
+ const optional = text[i] === "?"
84
+ if (optional) i++
85
+ if (optional && parts.length === 0 && i === text.length) return { kind: "optional", name }
86
+ parts.push(optional ? { param: name, optional: true } : { param: name })
87
+ }
88
+ if (parts.length === 0) return { kind: "static", text: literal }
89
+ if (literal) parts.push(literal)
90
+ if (stray) throw new Error(`unexpected "?" in "${text}"`)
91
+ const params = parts.filter((part) => typeof part !== "string")
92
+ if (params.length > 1 && params.some((part) => part.optional))
93
+ throw new Error(`an optional param in "${text}" cannot share the segment with another param`)
94
+ const [only] = parts
95
+ return parts.length === 1 && typeof only !== "string"
96
+ ? { kind: "param", name: only!.param }
97
+ : { kind: "mixed", parts }
98
+ }
99
+
100
+ /** The segments of a route pattern; throws when it is not one. */
101
+ export function parsePattern(pattern: string): Segment[] {
102
+ if (!pattern.startsWith("/")) throw new Error('must start with "/"')
103
+ const segments = splitPath(pattern).map((text) => {
104
+ if (text === "") throw new Error("empty segment")
105
+ return parseSegment(text)
106
+ })
107
+ const names = new Set<string>()
108
+ segments.forEach((segment, index) => {
109
+ for (const name of paramsOf(segment)) {
110
+ if (names.has(name)) throw new Error(`duplicate param "${name}"`)
111
+ names.add(name)
112
+ }
113
+ if (
114
+ (segment.kind === "optional" || segment.kind === "catchAll" || segment.kind === "optionalCatchAll") &&
115
+ index !== segments.length - 1
116
+ ) {
117
+ throw new Error(`"${segment.kind}" segment must be last`)
118
+ }
119
+ })
120
+ return segments
121
+ }
122
+
123
+ function paramsOf(segment: Segment): string[] {
124
+ if (segment.kind === "static") return []
125
+ if (segment.kind === "mixed") return segment.parts.flatMap((part) => (typeof part === "string" ? [] : [part.param]))
126
+ return [segment.name]
127
+ }
128
+
129
+ interface Leaf {
130
+ data: { name: string; code: string }
131
+ names: string[]
132
+ catchAll?: string
133
+ }
134
+
135
+ interface Node {
136
+ statics?: Map<string, Node>
137
+ mixed?: { key: string; regex: RegExp; literal: number; optional: boolean; node: Node }[]
138
+ param?: Node
139
+ route?: Leaf
140
+ optional?: Leaf
141
+ catchAll?: Leaf
142
+ optionalCatchAll?: Leaf
143
+ }
144
+
145
+ const escapeRegex = (text: string) => text.replace(/[.*+?^${}()|[\]\\/-]/g, "\\$&")
146
+
147
+ function mixedRegex(parts: MixedPart[]): RegExp {
148
+ const at = parts.findIndex((part) => typeof part !== "string" && part.optional)
149
+ const { side, run }: ReturnType<typeof optionalRun> = at === -1 ? { side: "after", run: "" } : optionalRun(parts, at)
150
+ const source = parts
151
+ .map((part, index) => {
152
+ if (typeof part === "string") {
153
+ if (at === -1 || index !== at + (side === "after" ? 1 : -1)) return escapeRegex(part)
154
+ return escapeRegex(side === "after" ? part.slice(run.length) : part.slice(0, part.length - run.length))
155
+ }
156
+ if (!part.optional) return "(.+?)"
157
+ return side === "after" ? `(?:(.+?)${escapeRegex(run)})?` : `(?:${escapeRegex(run)}(.+?))?`
158
+ })
159
+ .join("")
160
+ return new RegExp(`^${source}$`)
161
+ }
162
+
163
+ function insert(root: Node, segments: Segment[], data: Leaf["data"]): void {
164
+ const names: string[] = []
165
+ let node = root
166
+ let slot: "route" | "optional" | "catchAll" | "optionalCatchAll" = "route"
167
+ let catchAll: string | undefined
168
+ for (const segment of segments) {
169
+ if (segment.kind === "static") {
170
+ node.statics ??= new Map()
171
+ let next = node.statics.get(segment.text)
172
+ if (!next) node.statics.set(segment.text, (next = {}))
173
+ node = next
174
+ } else if (segment.kind === "mixed") {
175
+ const key = segment.parts
176
+ .map((part) => (typeof part === "string" ? part : part.optional ? "\0?\0" : "\0"))
177
+ .join("")
178
+ names.push(...paramsOf(segment))
179
+ node.mixed ??= []
180
+ let child = node.mixed.find((entry) => entry.key === key)
181
+ if (!child) {
182
+ const regex = mixedRegex(segment.parts)
183
+ const literal = segment.parts.reduce((sum, part) => sum + (typeof part === "string" ? part.length : 0), 0)
184
+ node.mixed.push(
185
+ (child = {
186
+ key,
187
+ regex,
188
+ literal,
189
+ optional: segment.parts.some((part) => typeof part !== "string" && part.optional === true),
190
+ node: {},
191
+ }),
192
+ )
193
+ node.mixed.sort((a, b) => Number(a.optional) - Number(b.optional) || b.literal - a.literal)
194
+ }
195
+ node = child.node
196
+ } else if (segment.kind === "param") {
197
+ names.push(segment.name)
198
+ node = node.param ??= {}
199
+ } else if (segment.kind === "optional") {
200
+ names.push(segment.name)
201
+ slot = "optional"
202
+ } else {
203
+ catchAll = segment.name
204
+ slot = segment.kind
205
+ }
206
+ }
207
+ node[slot] ??= { data, names, ...(catchAll !== undefined ? { catchAll } : {}) }
208
+ }
209
+
210
+ function leafMatch(leaf: Leaf, captured: Array<string | undefined>, rest: string[]): PathMatch {
211
+ const params: Record<string, string | string[]> = {}
212
+ leaf.names.forEach((name, index) => {
213
+ if (captured[index] !== undefined) params[name] = captured[index]!
214
+ })
215
+ if (leaf.catchAll !== undefined) params[leaf.catchAll] = rest
216
+ return { ...leaf.data, params }
217
+ }
218
+
219
+ function walk(
220
+ node: Node,
221
+ segments: string[],
222
+ index: number,
223
+ captured: Array<string | undefined>,
224
+ ): PathMatch | undefined {
225
+ if (index === segments.length) {
226
+ const leaf = node.route ?? node.optional ?? node.optionalCatchAll
227
+ return leaf && leafMatch(leaf, captured, [])
228
+ }
229
+ const segment = segments[index]!
230
+ const next = node.statics?.get(segment)
231
+ const viaStatic = next && walk(next, segments, index + 1, captured)
232
+ if (viaStatic) return viaStatic
233
+ if (segment !== "") {
234
+ for (const child of node.mixed ?? []) {
235
+ const found = child.regex.exec(segment)
236
+ if (!found) continue
237
+ const depth = captured.length
238
+ captured.push(...found.slice(1))
239
+ const match = walk(child.node, segments, index + 1, captured)
240
+ if (match) return match
241
+ captured.length = depth
242
+ }
243
+ if (node.param) {
244
+ captured.push(segment)
245
+ const match = walk(node.param, segments, index + 1, captured)
246
+ if (match) return match
247
+ captured.pop()
248
+ }
249
+ if (index === segments.length - 1 && node.optional) return leafMatch(node.optional, [...captured, segment], [])
250
+ }
251
+ const all = node.catchAll ?? node.optionalCatchAll
252
+ return all && leafMatch(all, captured, segments.slice(index))
253
+ }
254
+
255
+ function encodeParam(value: string): string {
256
+ return encodeURIComponent(value)
257
+ }
258
+
259
+ export interface Matcher {
260
+ /** The base route name, locale code and params of an app path; one trailing `/` is ignored and segments are percent-decoded. */
261
+ matchPath(path: string): PathMatch | undefined
262
+ /** The app path of a base route name in a locale, its params filled in. */
263
+ buildPath(name: string, code: string, params?: Record<string, string | string[]>): string
264
+ }
265
+
266
+ /** The matcher over `#hamur/i18n/routes`, ranking as the core router does. */
267
+ export function createMatcher(table: RouteTable): Matcher {
268
+ const root: Node = {}
269
+ const parsed = new Map<string, Segment[]>()
270
+ for (const [name, patterns] of Object.entries(table.routes)) {
271
+ for (const [code, pattern] of Object.entries(patterns)) {
272
+ const segments = parsePattern(pattern)
273
+ parsed.set(`${name}\0${code}`, segments)
274
+ insert(root, segments, { name, code })
275
+ }
276
+ }
277
+ for (const [name, patterns] of Object.entries(table.aliases ?? {})) {
278
+ for (const [code, pattern] of Object.entries(patterns)) insert(root, parsePattern(pattern), { name, code })
279
+ }
280
+ return {
281
+ matchPath(path) {
282
+ const segments = splitPath(path)
283
+ try {
284
+ for (let i = 0; i < segments.length; i++)
285
+ if (segments[i]!.includes("%")) segments[i] = decodeURIComponent(segments[i]!)
286
+ } catch {
287
+ return undefined
288
+ }
289
+ return walk(root, segments, 0, [])
290
+ },
291
+ buildPath(name, code, params = {}) {
292
+ const segments = parsed.get(`${name}\0${code}`)
293
+ if (!segments) {
294
+ if (!table.routes[name]) throw new Error(`i18n: no route named "${name}"`)
295
+ throw new Error(`i18n: route "${name}" has no path in "${code}"`)
296
+ }
297
+ const value = (param: string): string | string[] | undefined => params[param]
298
+ const required = (param: string): string => {
299
+ const given = value(param)
300
+ const text = Array.isArray(given) ? given.join("/") : given
301
+ if (text === undefined || text === "") throw new Error(`i18n: route "${name}" needs the param "${param}"`)
302
+ return text
303
+ }
304
+ const out: string[] = []
305
+ for (const segment of segments) {
306
+ if (segment.kind === "static") out.push(segment.text)
307
+ else if (segment.kind === "mixed") {
308
+ const optional = segment.parts.find((part) => typeof part !== "string" && part.optional) as
309
+ { param: string } | undefined
310
+ const absent = optional !== undefined && (value(optional.param) === undefined || value(optional.param) === "")
311
+ const at = segment.parts.findIndex((part) => part === optional)
312
+ const { side, run } = absent ? optionalRun(segment.parts, at) : { side: "after" as const, run: "" }
313
+ out.push(
314
+ segment.parts
315
+ .flatMap((part, index) => {
316
+ if (typeof part !== "string")
317
+ return absent && part === optional ? [] : [encodeParam(required(part.param))]
318
+ if (!absent || index !== at + (side === "after" ? 1 : -1)) return [part]
319
+ return [side === "after" ? part.slice(run.length) : part.slice(0, part.length - run.length)]
320
+ })
321
+ .join(""),
322
+ )
323
+ } else if (segment.kind === "param") out.push(encodeParam(required(segment.name)))
324
+ else {
325
+ const given = value(segment.name)
326
+ const list = given === undefined ? [] : Array.isArray(given) ? given : [given]
327
+ if (segment.kind === "catchAll" && list.length === 0) required(segment.name)
328
+ out.push(...list.filter((part) => part !== "").map(encodeParam))
329
+ }
330
+ }
331
+ return `/${out.join("/")}`
332
+ },
333
+ }
334
+ }
@@ -0,0 +1,129 @@
1
+ import type { AppContext } from "hamur/app"
2
+ import type { RichParts } from "../types.ts"
3
+ import { catalogURL } from "./catalog-loader.ts"
4
+ import type { Formatters } from "./format.ts"
5
+
6
+ /** A message with tags returns its parts; any other returns a string. */
7
+ export type Message = string | ((args: Record<string, unknown>, f: Formatters) => string | RichParts)
8
+ export type Catalog = Record<string, Message>
9
+ export type MessageLoaders = Record<string, () => Promise<{ default: Catalog; fallbacks?: string[] }>>
10
+ /** Locale code → `_shared` and route base name → its chunk, under `split: "route"` on the client. */
11
+ export type RouteMessageLoaders = Record<string, Record<string, () => Promise<{ default: Catalog }>>>
12
+ /** `#hamur/i18n/chunks`: a locale's chunk URL, or under `split: "route"` its `_shared` and route chunk URLs. */
13
+ export type MessageChunks = Record<string, string | Record<string, string>>
14
+
15
+ export interface MessageStore {
16
+ load(code: string): Promise<void>
17
+ loadAll(): Promise<void>
18
+ get(code: string): Catalog | undefined
19
+ /** Keys the build filled from the default locale (dev builds only). */
20
+ filled(code: string): ReadonlySet<string> | undefined
21
+ /** The `_shared` chunk and the route's chunk of `code` once each; the whole catalog when the build did not split. */
22
+ loadRoute(code: string, base: string | undefined): Promise<void>
23
+ install(loaders: MessageLoaders, chunks?: MessageChunks, routes?: RouteMessageLoaders): void
24
+ /** The chunk URLs the page of route `base` needs in `code`. */
25
+ chunksOf(code: string, base: string | undefined): string[]
26
+ /** The run-time catalog of `code`, whose messages win over the file catalog's key by key. */
27
+ remote(code: string): Catalog | undefined
28
+ /** `undefined` drops it, so the file catalog answers. */
29
+ setRemote(code: string, catalog: Catalog | undefined): void
30
+ }
31
+
32
+ /** The compiled catalogs of the locales loaded so far; a locale loads once. */
33
+ export function createMessageStore(): MessageStore {
34
+ let loaders: MessageLoaders = {}
35
+ let chunks: MessageChunks = {}
36
+ let routes: RouteMessageLoaders = {}
37
+ const parts = new Map<string, Set<string>>()
38
+ const catalogs = new Map<string, Catalog>()
39
+ const fills = new Map<string, Set<string>>()
40
+ const pending = new Map<string, Promise<void>>()
41
+ const remotes = new Map<string, Catalog>()
42
+ const store: MessageStore = {
43
+ load(code) {
44
+ if (catalogs.has(code)) return Promise.resolve()
45
+ let promise = pending.get(code)
46
+ if (!promise) {
47
+ const loader = loaders[code]
48
+ if (!loader) return Promise.reject(new Error(`i18n: no messages for locale "${code}"`))
49
+ promise = loader().then(
50
+ (module) => {
51
+ catalogs.set(code, module.default)
52
+ if (module.fallbacks?.length) fills.set(code, new Set(module.fallbacks))
53
+ pending.delete(code)
54
+ },
55
+ (error) => {
56
+ pending.delete(code)
57
+ throw error
58
+ },
59
+ )
60
+ pending.set(code, promise)
61
+ }
62
+ return promise
63
+ },
64
+ async loadRoute(code, base) {
65
+ const own = routes[code]
66
+ if (!own) return store.load(code)
67
+ const names = ["_shared", ...(base !== undefined && own[base] ? [base] : [])]
68
+ const held = parts.get(code) ?? new Set<string>()
69
+ parts.set(code, held)
70
+ const wanted = names.filter((name) => !held.has(name))
71
+ if (wanted.length === 0 && catalogs.has(code)) return
72
+ const loaded = await Promise.all(
73
+ wanted.map((name) => own[name]!().then((module) => [name, module.default] as const)),
74
+ )
75
+ const catalog = catalogs.get(code) ?? {}
76
+ for (const [name, messages] of loaded) {
77
+ held.add(name)
78
+ Object.assign(catalog, messages)
79
+ }
80
+ catalogs.set(code, catalog)
81
+ },
82
+ async loadAll() {
83
+ await Promise.all(Object.keys(loaders).map((code) => store.load(code)))
84
+ },
85
+ get: (code) => catalogs.get(code),
86
+ filled: (code) => fills.get(code),
87
+ install(next, urls = {}, split = {}) {
88
+ loaders = next
89
+ chunks = urls
90
+ routes = split
91
+ },
92
+ chunksOf(code, base) {
93
+ const own = chunks[code]
94
+ if (own === undefined) return []
95
+ if (typeof own === "string") return [own]
96
+ return [own._shared, base === undefined ? undefined : own[base]].filter(
97
+ (href): href is string => href !== undefined,
98
+ )
99
+ },
100
+ remote: (code) => remotes.get(code),
101
+ setRemote(code, catalog) {
102
+ if (catalog) remotes.set(code, catalog)
103
+ else remotes.delete(code)
104
+ },
105
+ }
106
+ return store
107
+ }
108
+
109
+ export const messageStore = createMessageStore()
110
+
111
+ export const loadMessages = (code: string): Promise<void> => messageStore.load(code)
112
+
113
+ export const loadAllMessages = (): Promise<void> => messageStore.loadAll()
114
+
115
+ export const loadRouteMessages = (code: string, base: string | undefined): Promise<void> =>
116
+ messageStore.loadRoute(code, base)
117
+
118
+ /** On the server, `modulepreload` links in the head for the client chunks of `code` and, under `split: "route"`, of route `base`. */
119
+ export function preloadMessages(app: AppContext, code: string, base?: string): void {
120
+ if (!import.meta.server) return
121
+ const links = messageStore.chunksOf(code, base).map((href) => ({ rel: "modulepreload", href }))
122
+ if (links.length) app.head.push({ link: links })
123
+ }
124
+
125
+ /** On the server, the `preload` link of the run-time catalog of `code`, which the browser fetches before it hydrates. */
126
+ export function preloadCatalog(app: AppContext, baseURL: string, code: string, version: string | undefined): void {
127
+ if (!import.meta.server) return
128
+ app.head.push({ link: [{ rel: "preload", as: "fetch", crossorigin: "", href: catalogURL(baseURL, code, version) }] })
129
+ }
@@ -0,0 +1,32 @@
1
+ import { defineRouteMiddleware, notFound, redirect } from "hamur/app"
2
+ import type { I18nRuntime } from "../types.ts"
3
+ import {
4
+ configOf,
5
+ contextLocale,
6
+ domainRoute,
7
+ readsRequestLocale,
8
+ routeBaseName,
9
+ routeLoadOf,
10
+ writeLocaleCookie,
11
+ } from "./locale.ts"
12
+
13
+ export default defineRouteMiddleware(async (to, from, { app, event }) => {
14
+ const { i18n } = app as typeof app & { i18n: I18nRuntime }
15
+ const { cookie } = configOf(i18n)
16
+ const fromRequest = readsRequestLocale(i18n)
17
+ const code = fromRequest
18
+ ? (event ? (contextLocale(i18n, event.context) ?? i18n.defaultLocale) : i18n.locale).code
19
+ : i18n.localeOf(to.path).code
20
+ const answer = domainRoute(i18n, to, code)
21
+ if (answer === false) notFound("Page Not Found: " + to.path)
22
+ if (typeof answer === "string")
23
+ return redirect(answer, !event || event.method === "GET" || event.method === "HEAD" ? 301 : 308)
24
+ const loadRoute = routeLoadOf(i18n)
25
+ await (loadRoute ? loadRoute(code, to.name ? routeBaseName(to.name) : undefined) : i18n.load(code))
26
+ if (event) {
27
+ event.context.locale = code
28
+ return
29
+ }
30
+ if (fromRequest || !cookie || !from || i18n.localeOf(from.path).code === code) return
31
+ writeLocaleCookie(app, cookie, code)
32
+ })
@@ -0,0 +1,61 @@
1
+ import type { LocaleInfo } from "../types.ts"
2
+
3
+ const RANGE = /^[A-Za-z]{1,8}(-[A-Za-z0-9]{1,8})*$/
4
+ const QUALITY = /^q=(0(\.\d{0,3})?|1(\.0{0,3})?)$/i
5
+ const MAX_ENTRIES = 32
6
+
7
+ function subtag(tag: string): string | undefined {
8
+ try {
9
+ return new Intl.Locale(tag).language
10
+ } catch {
11
+ return undefined
12
+ }
13
+ }
14
+
15
+ /** The first locale a range picks: one whose `language` or `code` equals it, else the first whose language subtag does. */
16
+ export function pickLocale(ranges: readonly string[], locales: readonly LocaleInfo[]): LocaleInfo | undefined {
17
+ for (const range of ranges) {
18
+ const lower = range.toLowerCase()
19
+ const exact = locales.find((locale) => locale.language.toLowerCase() === lower || locale.code === lower)
20
+ if (exact) return exact
21
+ const language = subtag(range)
22
+ const near = language && locales.find((locale) => subtag(locale.language) === language)
23
+ if (near) return near
24
+ }
25
+ return undefined
26
+ }
27
+
28
+ /** The ranges of an `Accept-Language` header in `q` order (ties keep header order), without `*`, `q=0` and malformed entries. */
29
+ export function acceptedRanges(header: string | null | undefined): string[] {
30
+ if (!header) return []
31
+ const entries: { range: string; q: number; index: number }[] = []
32
+ header
33
+ .split(",")
34
+ .slice(0, MAX_ENTRIES)
35
+ .forEach((entry, index) => {
36
+ const [range = "", ...params] = entry.split(";").map((part) => part.trim())
37
+ if (!RANGE.test(range)) return
38
+ let q = 1
39
+ for (const param of params) {
40
+ if (!QUALITY.test(param)) return
41
+ q = Number(param.slice(2))
42
+ }
43
+ if (q > 0) entries.push({ range, q, index })
44
+ })
45
+ return entries.sort((a, b) => b.q - a.q || a.index - b.index).map((entry) => entry.range)
46
+ }
47
+
48
+ /** Every configured locale an `Accept-Language` header matches, best first, each once. */
49
+ export function negotiateAll(header: string | null | undefined, locales: readonly LocaleInfo[]): LocaleInfo[] {
50
+ const found: LocaleInfo[] = []
51
+ for (const range of acceptedRanges(header)) {
52
+ const locale = pickLocale([range], locales)
53
+ if (locale && !found.includes(locale)) found.push(locale)
54
+ }
55
+ return found
56
+ }
57
+
58
+ /** The locale an `Accept-Language` header asks for, if any. */
59
+ export function negotiate(header: string | null | undefined, locales: readonly LocaleInfo[]): LocaleInfo | undefined {
60
+ return negotiateAll(header, locales)[0]
61
+ }
@@ -0,0 +1,69 @@
1
+ /// <reference path="../env.d.ts" />
2
+ import { addLinkResolver, definePlugin, navigateTo, refreshData, withoutBase } from "hamur/app"
3
+ import * as options from "#hamur/i18n/options"
4
+ import catalog from "#hamur/i18n/catalog"
5
+ import chunks from "#hamur/i18n/chunks"
6
+ import loaders, { routes as routeLoaders } from "#hamur/i18n/loaders"
7
+ import { aliases, copies, domains, missing, routes, server as serverRoutes } from "#hamur/i18n/routes"
8
+ import { serverCatalog } from "./catalog-loader.ts"
9
+ import { applyLocaleHead, commitLocaleHead } from "./head.ts"
10
+ import { i18nLinkResolver } from "./link.ts"
11
+ import { createI18nRuntime, forApp, loadRuntime, readsRequestLocale, routeBaseName } from "./locale.ts"
12
+ import { loadAllMessages, messageStore, preloadCatalog, preloadMessages } from "./messages.ts"
13
+
14
+ const i18n = createI18nRuntime({
15
+ locales: options.locales,
16
+ defaultLocale: options.defaultLocale,
17
+ strategy: options.strategy,
18
+ cookie: options.cookie,
19
+ baseURL: options.baseURL,
20
+ timeZone: options.timeZone,
21
+ fallback: options.fallback,
22
+ copies,
23
+ routes,
24
+ aliases,
25
+ missing,
26
+ ...(domains ? { domains } : {}),
27
+ })
28
+ messageStore.install(loaders, chunks, routeLoaders)
29
+
30
+ export default definePlugin(async (app) => {
31
+ const server = import.meta.server === true
32
+ const path = server ? undefined : withoutBase(location.pathname, app.config.runtimeApp?.baseURL ?? options.baseURL)
33
+ const queryLocale = server ? null : new URLSearchParams(location.search).get("locale")
34
+ const baseURL = app.config.runtimeApp?.baseURL ?? options.baseURL
35
+ const remote = catalog && (server ? serverCatalog() : catalog)
36
+ const versions = () => app.modulePayload.i18nCatalog as Record<string, string> | undefined
37
+ const loadCatalog = remote
38
+ ? async (code: string) => {
39
+ const version = await remote(code, {
40
+ event: app.event,
41
+ baseURL,
42
+ version: server ? undefined : versions()?.[code],
43
+ })
44
+ if (server && version !== undefined) app.modulePayload.i18nCatalog = { ...versions(), [code]: version }
45
+ }
46
+ : undefined
47
+ const runtime = forApp(i18n, app, server, {
48
+ ...(path === undefined ? {} : { path }),
49
+ ...(queryLocale === null ? {} : { queryLocale }),
50
+ navigate: (to) => (/^https?:\/\//.test(to) ? navigateTo(to, { external: true }) : navigateTo(to)),
51
+ refresh: () => refreshData(),
52
+ ...(loadCatalog ? { catalog: loadCatalog } : {}),
53
+ })
54
+ loadRuntime.current = server ? i18n : runtime
55
+ if (server) await loadAllMessages()
56
+ else await runtime.load(runtime.locale.code)
57
+ app.hooks.hook("page:start", async (route) => {
58
+ const { code } = readsRequestLocale(i18n) ? runtime.locale : i18n.localeOf(route.path)
59
+ preloadMessages(app, code, route.name ? routeBaseName(route.name) : undefined)
60
+ if (server && loadCatalog) {
61
+ await loadCatalog(code)
62
+ preloadCatalog(app, baseURL, code, versions()?.[code])
63
+ }
64
+ applyLocaleHead(app, route)
65
+ })
66
+ app.hooks.hook("page:finish", () => commitLocaleHead(app))
67
+ if (options.localizeLinks) addLinkResolver(app, i18nLinkResolver(runtime, serverRoutes))
68
+ return { provide: { i18n: runtime } }
69
+ })