@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,504 @@
1
+ import { FUNCTIONS, parseMf2, type Expression, type Message as Mf2Message, type Part } from "../compiler/mf2-parse.ts"
2
+ import { MessageSyntaxError, parseMessage, type MessageNode } from "../compiler/parse.ts"
3
+ import type { RichNode, RichParts } from "../types.ts"
4
+ import type { Formatters } from "./format.ts"
5
+ import type { Catalog, Message } from "./messages.ts"
6
+
7
+ /** A run-time message, parsed: MF1 nodes, or an MF2 message under `syntax: "mf2"`. */
8
+ export type ParsedMessage = MessageNode[] | Mf2Message
9
+ export type ParsedCatalog = Record<string, ParsedMessage>
10
+
11
+ export interface ParsedRun {
12
+ /** The messages that parsed, as given. */
13
+ messages: Record<string, string>
14
+ parsed: ParsedCatalog
15
+ /** A message that is not a string or does not parse: its key and the reason, with the column. */
16
+ skipped: { key: string; reason: string }[]
17
+ }
18
+
19
+ type Out = string | RichParts
20
+ type Args = Record<string, unknown>
21
+
22
+ const isRecord = (value: unknown): value is Record<string, unknown> =>
23
+ value !== null && typeof value === "object" && !Array.isArray(value)
24
+
25
+ /** Each message of `messages` parsed once; one that fails is skipped with its reason. */
26
+ export function parseCatalog(messages: unknown, syntax: "mf1" | "mf2"): ParsedRun {
27
+ const run: ParsedRun = {
28
+ messages: Object.create(null) as Record<string, string>,
29
+ parsed: Object.create(null) as ParsedCatalog,
30
+ skipped: [],
31
+ }
32
+ if (!isRecord(messages)) return run
33
+ for (const [key, source] of Object.entries(messages)) {
34
+ if (typeof source !== "string") {
35
+ run.skipped.push({ key, reason: "a message must be a string" })
36
+ continue
37
+ }
38
+ try {
39
+ run.parsed[key] = syntax === "mf2" ? parseMf2(source) : parseMessage(source)
40
+ run.messages[key] = source
41
+ } catch (error) {
42
+ if (!(error instanceof MessageSyntaxError)) throw error
43
+ run.skipped.push({ key, reason: error.message })
44
+ }
45
+ }
46
+ return run
47
+ }
48
+
49
+ /** The catalog of `parsed` in the compiled modules' shape, each message rendered by walking its nodes. */
50
+ export function interpretCatalog(parsed: ParsedCatalog, syntax: "mf1" | "mf2"): Catalog {
51
+ const catalog = Object.create(null) as Catalog
52
+ for (const [key, message] of Object.entries(parsed))
53
+ catalog[key] = syntax === "mf2" ? mf2Message(message as Mf2Message) : mf1Message(message as MessageNode[])
54
+ return catalog
55
+ }
56
+
57
+ function hasTag(nodes: MessageNode[]): boolean {
58
+ return nodes.some(
59
+ (node) =>
60
+ node.type === "tag" ||
61
+ ((node.type === "plural" || node.type === "select") && node.cases.some(({ body }) => hasTag(body))),
62
+ )
63
+ }
64
+
65
+ /** `in` first: the dev translator's Proxy reports a missing argument from its `has` trap. */
66
+ const argOf = (a: Args, name: string): unknown =>
67
+ name in a && Object.hasOwn(a, name) && a[name] !== undefined ? a[name] : "{" + name + "}"
68
+
69
+ const plain = (value: unknown, f: Formatters): string =>
70
+ typeof value === "number" || typeof value === "bigint"
71
+ ? f.n(value)
72
+ : value instanceof Date
73
+ ? f.d(value)
74
+ : String(value)
75
+
76
+ const scaled = (value: unknown, scale: number): unknown =>
77
+ typeof value === "number" || typeof value === "bigint" ? Number(value) * scale : value
78
+
79
+ function numberOptions(node: Extract<MessageNode, { type: "number" }>): Intl.NumberFormatOptions {
80
+ if (node.style === "integer") return { maximumFractionDigits: 0 }
81
+ if (node.style === "percent") return { style: "percent" }
82
+ if (node.style === "currency") return { style: "currency", currency: node.currency }
83
+ if (node.style === "skeleton") return (node.options ?? {}) as Intl.NumberFormatOptions
84
+ return {}
85
+ }
86
+
87
+ function mf1Node(node: MessageNode, a: Args, f: Formatters, pound: string | undefined): Out {
88
+ switch (node.type) {
89
+ case "text":
90
+ return node.value
91
+ case "pound":
92
+ return pound ?? "#"
93
+ case "arg":
94
+ return plain(argOf(a, node.name), f)
95
+ case "number": {
96
+ const value = argOf(a, node.name)
97
+ return f.n(node.scale === undefined ? value : scaled(value, node.scale), numberOptions(node))
98
+ }
99
+ case "date":
100
+ return f.d(argOf(a, node.name), node.kind === "date" ? { dateStyle: node.style } : { timeStyle: node.style })
101
+ case "tag":
102
+ return [{ tag: node.name, children: mf1Parts(node.children, a, f, pound) } as RichNode]
103
+ case "select": {
104
+ const cases = Object.create(null) as Record<string, Out | (() => Out)>
105
+ for (const { key, body } of node.cases) cases[key] = allText(body) ?? (() => mf1Render(body, a, f, pound))
106
+ return f.s(argOf(a, node.name), cases)
107
+ }
108
+ case "plural": {
109
+ const cases = Object.create(null) as Record<string, Out | ((count: string) => Out)>
110
+ for (const { key, body } of node.cases)
111
+ cases[key] = allText(body) ?? ((count: string) => mf1Render(body, a, f, count))
112
+ return f.p(argOf(a, node.name), node.offset, cases, node.ordinal)
113
+ }
114
+ default:
115
+ return ""
116
+ }
117
+ }
118
+
119
+ function mf1Parts(nodes: MessageNode[], a: Args, f: Formatters, pound: string | undefined): RichParts {
120
+ return nodes.map((node) => mf1Node(node, a, f, pound)).flat()
121
+ }
122
+
123
+ function mf1Render(nodes: MessageNode[], a: Args, f: Formatters, pound: string | undefined): Out {
124
+ if (hasTag(nodes)) return mf1Parts(nodes, a, f, pound)
125
+ let text = ""
126
+ for (const node of nodes) text += mf1Node(node, a, f, pound) as string
127
+ return text
128
+ }
129
+
130
+ const allText = (nodes: MessageNode[]): string | undefined =>
131
+ nodes.every((node) => node.type === "text")
132
+ ? nodes.map((node) => (node as { value: string }).value).join("")
133
+ : undefined
134
+
135
+ function mf1Message(nodes: MessageNode[]): Message {
136
+ return allText(nodes) ?? ((a, f) => mf1Render(nodes, a, f, undefined))
137
+ }
138
+
139
+ /** An MF2 resolved value: `x` marks a fallback, `t` is its fallback text, `k` the function, `r` the resolved and `i` the `Intl` options. */
140
+ interface Value {
141
+ x?: 1
142
+ t: string
143
+ v?: unknown
144
+ k?: string
145
+ r?: Record<string, unknown>
146
+ i?: Record<string, unknown>
147
+ n?: number
148
+ d?: number
149
+ om?: number | undefined
150
+ fl?: 1 | undefined
151
+ }
152
+
153
+ type OptionValue = string | [unknown]
154
+
155
+ const literalFallback = (value: string) => "{|" + value.replace(/[\\|]/g, "\\$&") + "|}"
156
+
157
+ function argument(a: Args, name: string): Value {
158
+ let value = Object.hasOwn(a, name) ? a[name] : undefined
159
+ if (value === undefined) for (const given of Object.keys(a)) if (given.normalize("NFC") === name) value = a[given]
160
+ return value === undefined ? { x: 1, t: "{$" + name + "}" } : { v: value, t: "{$" + name + "}" }
161
+ }
162
+
163
+ const optionValue = (value: Value): unknown => (value.x ? undefined : value.v)
164
+
165
+ function text(value: Value, f: Formatters): string {
166
+ if (value.x) return value.t
167
+ try {
168
+ const v = value.v
169
+ if (value.k === "number" || value.k === "integer") return f.n(v, value.i as Intl.NumberFormatOptions)
170
+ if (value.k === "datetime" || value.k === "date" || value.k === "time")
171
+ return f.d(value.d, value.i as Intl.DateTimeFormatOptions)
172
+ if (value.k === "string") return v as string
173
+ return plain(v, f)
174
+ } catch {
175
+ return value.t
176
+ }
177
+ }
178
+
179
+ const among =
180
+ (list: string[]) =>
181
+ (value: unknown): string | undefined =>
182
+ list.includes(String(value)) ? String(value) : undefined
183
+
184
+ function digits(value: unknown, low: number, high: number): number | undefined {
185
+ const given = String(value)
186
+ if (!/^(0|[1-9][0-9]?)$/.test(given)) return undefined
187
+ const number = Number(given)
188
+ return number >= low && number <= high ? number : undefined
189
+ }
190
+
191
+ const NUMBER_LITERAL = /^-?(0|[1-9][0-9]*)(\.[0-9]+)?([eE][+-]?[0-9]+)?$/
192
+ const NUMBER_OPTIONS: Record<string, (value: unknown) => unknown> = {
193
+ select: among(["plural", "ordinal", "exact"]),
194
+ signDisplay: among(["auto", "always", "exceptZero", "negative", "never"]),
195
+ useGrouping: among(["auto", "always", "never", "min2"]),
196
+ minimumIntegerDigits: (value) => digits(value, 1, 21),
197
+ minimumFractionDigits: (value) => digits(value, 0, 99),
198
+ maximumFractionDigits: (value) => digits(value, 0, 99),
199
+ minimumSignificantDigits: (value) => digits(value, 1, 21),
200
+ maximumSignificantDigits: (value) => digits(value, 1, 21),
201
+ trailingZeroDisplay: among(["auto", "stripIfInteger"]),
202
+ roundingPriority: among(["auto", "morePrecision", "lessPrecision"]),
203
+ roundingIncrement: (value) =>
204
+ [1, 2, 5, 10, 20, 25, 50, 100, 200, 250, 500, 1000, 2000, 2500, 5000].includes(Number(value))
205
+ ? Number(value)
206
+ : undefined,
207
+ roundingMode: among([
208
+ "ceil",
209
+ "floor",
210
+ "expand",
211
+ "trunc",
212
+ "halfCeil",
213
+ "halfFloor",
214
+ "halfExpand",
215
+ "halfTrunc",
216
+ "halfEven",
217
+ ]),
218
+ }
219
+ const INTEGER_KEYS = ["select", "signDisplay", "useGrouping", "minimumIntegerDigits", "maximumSignificantDigits"]
220
+
221
+ function numberValue(fn: string, x: Value | undefined, options: Record<string, OptionValue>, t: string): Value {
222
+ const bad: Value = { x: 1, t }
223
+ if (x === undefined || x.x || x.k === "datetime" || x.k === "date" || x.k === "time") return bad
224
+ let v = x.v
225
+ if (typeof v === "string" && NUMBER_LITERAL.test(v)) v = Number(v)
226
+ if (typeof v !== "number" && typeof v !== "bigint") return bad
227
+ const keys = fn === "integer" ? INTEGER_KEYS : Object.keys(NUMBER_OPTIONS)
228
+ const resolved: Record<string, unknown> = {}
229
+ let noSelect = x.n || 0
230
+ if (x.r) {
231
+ for (const key of keys) if (key !== "select" && x.r[key] !== undefined) resolved[key] = x.r[key]
232
+ if (x.r.select !== undefined) noSelect = 1
233
+ }
234
+ for (const key of keys) {
235
+ if (!Object.hasOwn(options, key)) continue
236
+ const raw = options[key]!
237
+ if (key === "select") {
238
+ if (Array.isArray(raw)) noSelect = 1
239
+ else if (NUMBER_OPTIONS.select!(raw) !== undefined) {
240
+ resolved.select = NUMBER_OPTIONS.select!(raw)
241
+ noSelect = 0
242
+ }
243
+ continue
244
+ }
245
+ const value = NUMBER_OPTIONS[key]!(Array.isArray(raw) ? raw[0] : raw)
246
+ if (value !== undefined) resolved[key] = value
247
+ }
248
+ if (fn === "integer") v = typeof v === "bigint" ? v : Math.trunc(v as number) || 0
249
+ const intl: Record<string, unknown> = {}
250
+ for (const key in resolved)
251
+ if (key !== "select") intl[key] = key === "useGrouping" && resolved[key] === "never" ? false : resolved[key]
252
+ if (fn === "integer") intl.maximumFractionDigits = 0
253
+ return { k: fn, v, r: resolved, i: intl, n: noSelect, t }
254
+ }
255
+
256
+ const DATE_LITERAL =
257
+ /^(?!0000)[0-9]{4}-(0[1-9]|1[0-2])-(0[1-9]|[12][0-9]|3[01])(T([01][0-9]|2[0-3]):[0-5][0-9]:[0-5][0-9](\.[0-9]{1,3})?(Z|[+-]((0[0-9]|1[0-3]):[0-5][0-9]|14:00))?)?$/
258
+
259
+ function dateOf(value: unknown): { ms: number; om?: number; fl?: 1 } | undefined {
260
+ if (value instanceof Date) return isNaN(value.getTime()) ? undefined : { ms: value.getTime() }
261
+ if (typeof value === "number") return isFinite(value) ? { ms: value } : undefined
262
+ if (typeof value !== "string" || !DATE_LITERAL.test(value)) return undefined
263
+ const at = value.indexOf("T")
264
+ const date = at < 0 ? value : value.slice(0, at)
265
+ let time = at < 0 ? "00:00:00" : value.slice(at + 1)
266
+ let offset: number | undefined
267
+ const zone = /(Z|[+-][0-9]{2}:[0-9]{2})$/.exec(time)
268
+ if (zone) {
269
+ time = time.slice(0, -zone[1]!.length)
270
+ offset =
271
+ zone[1] === "Z"
272
+ ? 0
273
+ : (zone[1]![0] === "-" ? -1 : 1) * (Number(zone[1]!.slice(1, 3)) * 60 + Number(zone[1]!.slice(4)))
274
+ }
275
+ const ms = Date.parse(date + "T" + time + "Z")
276
+ if (isNaN(ms)) return undefined
277
+ return offset === undefined ? { ms, fl: 1 } : { ms: ms - offset * 60000, om: offset }
278
+ }
279
+
280
+ function knownTo(make: (value: string) => unknown): (value: unknown) => string | undefined {
281
+ return (value) => {
282
+ const given = String(value)
283
+ try {
284
+ make(given)
285
+ return given
286
+ } catch {
287
+ return undefined
288
+ }
289
+ }
290
+ }
291
+
292
+ const DATE_OPTIONS: Record<string, (value: unknown) => unknown> = {
293
+ fields: among([
294
+ "weekday",
295
+ "day-weekday",
296
+ "month-day",
297
+ "month-day-weekday",
298
+ "year-month-day",
299
+ "year-month-day-weekday",
300
+ ]),
301
+ length: among(["long", "medium", "short"]),
302
+ precision: among(["hour", "minute", "second"]),
303
+ timeZoneStyle: among(["long", "short"]),
304
+ timeZone: (value) =>
305
+ String(value) === "input" || String(value) === "UTC"
306
+ ? String(value)
307
+ : knownTo((zone) => new Intl.DateTimeFormat("en", { timeZone: zone }))(value),
308
+ hour12: among(["true", "false"]),
309
+ calendar: knownTo((calendar) => new Intl.DateTimeFormat("en", { calendar })),
310
+ }
311
+ const DATE_ALIASES: Record<string, string> = { dateFields: "fields", dateLength: "length", timePrecision: "precision" }
312
+
313
+ function dateValue(fn: string, x: Value | undefined, options: Record<string, OptionValue>, t: string): Value {
314
+ const bad: Value = { x: 1, t }
315
+ if (x === undefined || x.x || x.k === "number" || x.k === "integer") return bad
316
+ const d =
317
+ x.k === "datetime" || x.k === "date" || x.k === "time" ? { ms: x.v as number, om: x.om, fl: x.fl } : dateOf(x.v)
318
+ if (!d) return bad
319
+ const r: Record<string, unknown> = {}
320
+ if (x.r) for (const key of ["timeZone", "hour12", "calendar"]) if (x.r[key] !== undefined) r[key] = x.r[key]
321
+ for (const name of Object.keys(options)) {
322
+ const key = DATE_ALIASES[name] ?? name
323
+ const raw = options[name]!
324
+ const over = key === "timeZone" || key === "hour12" || key === "calendar"
325
+ if (Array.isArray(raw) && !over) continue
326
+ const read = DATE_OPTIONS[key]
327
+ const value = read ? read(Array.isArray(raw) ? raw[0] : raw) : undefined
328
+ if (value !== undefined) r[key] = value
329
+ }
330
+ const i: Record<string, unknown> = {}
331
+ if (fn !== "time") {
332
+ const parts = String(r.fields ?? "year-month-day").split("-")
333
+ const length = r.length ?? "medium"
334
+ if (parts.includes("year")) i.year = length === "short" ? "2-digit" : "numeric"
335
+ if (parts.includes("month")) i.month = length === "long" ? "long" : length === "medium" ? "short" : "numeric"
336
+ if (parts.includes("day")) i.day = "numeric"
337
+ if (parts.includes("weekday")) i.weekday = length === "long" ? "long" : "short"
338
+ }
339
+ if (fn !== "date") {
340
+ const precision = r.precision ?? "minute"
341
+ i.hour = "numeric"
342
+ if (precision !== "hour") i.minute = "2-digit"
343
+ if (precision === "second") i.second = "2-digit"
344
+ }
345
+ if (r.timeZoneStyle) i.timeZoneName = r.timeZoneStyle
346
+ if (r.hour12 !== undefined) i.hour12 = r.hour12 === "true"
347
+ if (r.calendar) i.calendar = r.calendar
348
+ let shown = d.ms
349
+ if (r.timeZone === "UTC") i.timeZone = "UTC"
350
+ else if (r.timeZone === "input") {
351
+ if (d.om !== undefined) {
352
+ i.timeZone = "UTC"
353
+ shown += d.om * 60000
354
+ } else if (d.fl) i.timeZone = "UTC"
355
+ } else if (r.timeZone) i.timeZone = r.timeZone
356
+ else if (d.fl) i.timeZone = "UTC"
357
+ return { k: fn, v: d.ms, om: d.om, fl: d.fl, r, i, d: shown, t }
358
+ }
359
+
360
+ const CATEGORIES: Record<string, Out> = {
361
+ zero: "zero",
362
+ one: "one",
363
+ two: "two",
364
+ few: "few",
365
+ many: "many",
366
+ other: "other",
367
+ }
368
+
369
+ function selectKeys(x: Value, f: Formatters): string[] {
370
+ if (x.x) return []
371
+ if (x.k === "string") return [String(x.v).normalize("NFC")]
372
+ if ((x.k !== "number" && x.k !== "integer") || x.n) return []
373
+ const n = typeof x.v === "bigint" ? Number(x.v) : (x.v as number)
374
+ const select = x.r?.select ?? "plural"
375
+ const keys = [String(n)]
376
+ if (select !== "exact") keys.push(f.p(n, 0, CATEGORIES, select === "ordinal") as string)
377
+ return keys
378
+ }
379
+
380
+ function pick(selectors: string[][], variants: [(string | null)[], () => Out][]): Out {
381
+ let best: (() => Out) | undefined
382
+ let rank: number[] | undefined
383
+ for (const [keys, body] of variants) {
384
+ const ranks: number[] = []
385
+ for (let i = 0; i < selectors.length; i++) {
386
+ const at = keys[i] === null ? selectors[i]!.length : selectors[i]!.indexOf(keys[i]!)
387
+ if (at < 0) break
388
+ ranks.push(at)
389
+ }
390
+ if (ranks.length < selectors.length) continue
391
+ let better = rank === undefined
392
+ for (let i = 0; !better && i < ranks.length && ranks[i]! <= rank![i]!; i++) better = ranks[i]! < rank![i]!
393
+ if (better) {
394
+ rank = ranks
395
+ best = body
396
+ }
397
+ }
398
+ return best ? best() : ""
399
+ }
400
+
401
+ function staticMf2(message: Mf2Message): boolean {
402
+ if (message.declarations.length > 0 || message.matcher) return false
403
+ return message.parts.every(
404
+ (part) =>
405
+ part.type === "text" ||
406
+ (part.type === "expression" && !part.expression.call && part.expression.operand?.kind === "literal"),
407
+ )
408
+ }
409
+
410
+ function mf2Message(message: Mf2Message): Message {
411
+ if (staticMf2(message)) {
412
+ let out = ""
413
+ for (const part of message.parts)
414
+ out +=
415
+ part.type === "text"
416
+ ? part.value
417
+ : part.type === "expression"
418
+ ? (part.expression.operand as { value: string }).value
419
+ : ""
420
+ return out
421
+ }
422
+ return (a, f) => {
423
+ const scope = new Map<string, Value>()
424
+ const ref = (name: string): Value => scope.get(name) ?? argument(a, name)
425
+ const evaluate = ({ operand, call }: Expression): Value | undefined => {
426
+ let x: Value | undefined
427
+ let t = "{:" + (call?.name ?? "") + "}"
428
+ if (operand?.kind === "literal") {
429
+ t = literalFallback(operand.value)
430
+ x = { v: operand.value, t }
431
+ } else if (operand) {
432
+ t = "{$" + operand.name + "}"
433
+ x = ref(operand.name)
434
+ }
435
+ if (!call) return x
436
+ const known = Object.hasOwn(FUNCTIONS, call.name) ? FUNCTIONS[call.name]! : []
437
+ const options = Object.create(null) as Record<string, OptionValue>
438
+ for (const option of call.options) {
439
+ if (known.includes(option.name))
440
+ options[option.name] =
441
+ option.value.kind === "literal" ? option.value.value : [optionValue(ref(option.value.name))]
442
+ }
443
+ if (call.name === "string") return x === undefined || x.x ? { x: 1, t } : { k: "string", v: String(x.v), t }
444
+ if (call.name === "number" || call.name === "integer") return numberValue(call.name, x, options, t)
445
+ if (call.name === "datetime" || call.name === "date" || call.name === "time")
446
+ return dateValue(call.name, x, options, t)
447
+ return { x: 1, t }
448
+ }
449
+ const pattern = (parts: Part[]): Out => {
450
+ const rich = parts.some((part) => part.type === "markup")
451
+ let pieces: (string | RichNode)[] = []
452
+ let literal: string | undefined
453
+ const open: { name: string; pieces: (string | RichNode)[] }[] = []
454
+ const flush = () => {
455
+ if (literal !== undefined) pieces.push(literal)
456
+ literal = undefined
457
+ }
458
+ const closeTop = () => {
459
+ const frame = open.pop()!
460
+ const children = pieces
461
+ pieces = frame.pieces
462
+ pieces.push({ tag: frame.name, children })
463
+ }
464
+ for (const part of parts) {
465
+ if (part.type === "markup") {
466
+ flush()
467
+ if (part.kind === "open") {
468
+ open.push({ name: part.name, pieces })
469
+ pieces = []
470
+ } else if (part.kind === "standalone") pieces.push({ tag: part.name, children: [] })
471
+ else if (open.some((frame) => frame.name === part.name)) {
472
+ while (open[open.length - 1]!.name !== part.name) closeTop()
473
+ closeTop()
474
+ }
475
+ } else if (part.type === "text") literal = (literal ?? "") + part.value
476
+ else {
477
+ const { operand, call } = part.expression
478
+ if (!call && operand?.kind === "literal") literal = (literal ?? "") + operand.value
479
+ else {
480
+ flush()
481
+ pieces.push(text(evaluate(part.expression) ?? { x: 1, t: "{:}" }, f))
482
+ }
483
+ }
484
+ }
485
+ flush()
486
+ while (open.length) closeTop()
487
+ return rich ? pieces : (pieces as string[]).join("")
488
+ }
489
+ for (const declaration of message.declarations) {
490
+ const value = evaluate(declaration.expression) ?? { x: 1 as const, t: "{:}" }
491
+ scope.set(declaration.name, { ...value, t: "{$" + declaration.name + "}" })
492
+ }
493
+ const { matcher } = message
494
+ if (!matcher) return pattern(message.parts)
495
+ const selectors = matcher.selectors.map((selector) => selectKeys(scope.get(selector.name) ?? { x: 1, t: "" }, f))
496
+ return pick(
497
+ selectors,
498
+ matcher.variants.map((variant): [(string | null)[], () => Out] => [
499
+ variant.keys.map((key) => (key === null ? null : key.normalize("NFC"))),
500
+ () => pattern(variant.parts),
501
+ ]),
502
+ )
503
+ }
504
+ }
@@ -0,0 +1,36 @@
1
+ import type { LinkResolver } from "hamur/app"
2
+ import type { I18nRuntime } from "../types.ts"
3
+ import { createMatcher } from "./match.ts"
4
+
5
+ const UNLOCALIZED = /^\/(?:api|_hamur)(?:[/?#]|$)/
6
+ const FILE = /\.[A-Za-z0-9]+$/
7
+
8
+ /** A path whose first segment is a prefixed locale's code is already localized, as `switchLocalePath` writes one. */
9
+ function namesLocale(i18n: I18nRuntime, to: string): boolean {
10
+ const segment = /^\/([^/?#]*)/.exec(to)![1]!
11
+ return i18n.localeOf(to).code === segment
12
+ }
13
+
14
+ /**
15
+ * The link resolver of `localizeLinks`: `to` in the `locale` prop's locale, the page's by default; `locale={false}`
16
+ * or `""` keeps it. A file (a last segment with an extension), a server route of `server` (its patterns), `/api` and
17
+ * `/_hamur` are left as written, since a catch-all page would match them.
18
+ */
19
+ export function i18nLinkResolver(i18n: I18nRuntime, server: readonly string[] = []): LinkResolver {
20
+ const routes = createMatcher({
21
+ copies: [],
22
+ routes: Object.fromEntries(server.map((pattern, index) => [String(index), { "": pattern }])),
23
+ })
24
+ return {
25
+ props: ["locale"],
26
+ resolve(to, { locale }) {
27
+ const path = /^[^?#]*/.exec(to)![0]
28
+ if (locale === false || UNLOCALIZED.test(path) || FILE.test(path) || routes.matchPath(path)) return to
29
+ const code = typeof locale === "string" && locale !== "" ? locale : undefined
30
+ if (code === undefined && namesLocale(i18n, to)) return to
31
+ const target = code === undefined ? i18n.locale : i18n.locales.find((info) => info.code === code)
32
+ if (!target) throw new Error(`i18n: "${code}" is not in i18n.locales`)
33
+ return i18n.localePath(to, target.code)
34
+ },
35
+ }
36
+ }