1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183 |
x2
x2
x2
x2
x2
x2
x2
x2
x39
x39
x39
x39
x2
x39
x39
x39
x2
x2
x11
x11
x2
x10
x10
x10
x10
x10
x2
x4
x4
x4
x4
x3
x3
x4
x4
x4
x4
x1
x1
x4
x2
x11
x13
x13
x13
x13
x1
x1
x11
x2
x2
x2
x2
x2
x4
x4
x4
x4
x4
x4
x4
x4
x2
x17
x17
x13
x13
x17
x17
x17
x17
x9
x9
x9
x9
x9
x17
x17
x17
x2
x3
x3
x3
x2
x34
x34
x34
x34
x2
x2 |
I
|
import { acceptsLanguages } from "@std/http/negotiation"
import * as YAML from "@std/yaml/parse"
import { pluralize } from "@libs/toolbox/pluralize"
import { timezone as tz } from "@libs/toolbox/timezone"
import { evaluate, EvaluationReturn } from "@libs/toolbox/evaluate"
import { getLogger, type Logger } from "@logtape/logtape"
export class I18n {
constructor({ language = globalThis.navigator?.language, timezone = tz }: { language?: string; timezone?: string } = {}) {
this.language = language ?? I18n.fallback
this.timezone = timezone
this.#log = getLogger(["i18n", this.language])
}
readonly #log: Logger
static readonly #storage = new Map<string, Map<string, string>>()
static fallback = "en"
readonly language: string
readonly timezone: string
get(key: string, context?: Record<string, unknown>): string {
return this.#translate(key, context)
}
set(key: string, value: string): this {
const translations = I18n.#storage.getOrInsert(this.language, new Map())
translations.set(key, value)
this.#log.trace(`registered translation "${key}":\n${value}`)
return this
}
async load(source: string | URL): Promise<this> {
this.#log.debug(`loading translations from: ${source}`)
const response = await fetch(source)
if (!response.ok)
throw new Error(`Failed to load translations from "${source}" (HTTP ${response.status})`)
const content = await response.text()
const parsed = YAML.parse(content) as Record<string, unknown>
if ((!parsed) || (typeof parsed !== "object") || (Array.isArray(parsed)))
throw new Error(`Failed to parse translations from "${source}" (not a valid YAML object)`)
for (const [key, value] of Object.entries(parsed))
this.set(key, `${value}`)
this.#log.info(`loaded ${Object.keys(parsed).length} translations from: ${source}`)
return this
}
#translate(key: string, context: Record<string, unknown> = {}, { language = this.language } = {}): string {
for (const lang of new Set([language, this.language, I18n.fallback].filter(Boolean))) {
const value = I18n.#storage.get(lang)?.get(key)
if (value !== undefined)
return evaluate(value, context, { sync: true, return: EvaluationReturn.String })
}
this.#log.warn(`missing translation for key "${key}" (${language})`)
return key
}
time(time: string): string {
const intl = new Intl.DateTimeFormat(this.language, { timeZone: this.timezone, hour: "2-digit", minute: "2-digit", second: "2-digit", hourCycle: "h23" })
return intl.format(new Date(time))
}
date(date: string, options: Intl.DateTimeFormatOptions = {}): string {
const intl = new Intl.DateTimeFormat(this.language, {
timeZone: this.timezone,
day: "day" in options ? options.day : "numeric",
month: "month" in options ? options.month : "short",
year: "year" in options ? options.year : "numeric",
})
return intl.format(new Date(date))
}
number(text: string, number: number, options?: Intl.NumberFormatOptions & { format?: "bytes" }): string
number(number: number, options?: Intl.NumberFormatOptions & { format?: "bytes" }): string
number(): string {
let [text, number, options] = arguments as unknown as [string, number, (Intl.NumberFormatOptions & { format?: "bytes" })?]
if (typeof text === "number") {
;[text, number, options] = ["", text, number as unknown as typeof options]
}
const { format, ...overrides } = options ?? {}
let value = number
let defaults: Intl.NumberFormatOptions = { notation: "compact", compactDisplay: "short", maximumFractionDigits: 1 }
if (format === "bytes") {
const units = ["byte", "kilobyte", "megabyte", "gigabyte", "terabyte", "petabyte"] as const
const scale = Math.max(0, Math.min(units.length - 1, Math.floor(Math.log10(Math.abs(value) || 1) / 3)))
value /= 1000 ** scale
defaults = { style: "unit", unit: units[scale], unitDisplay: "narrow", maximumFractionDigits: 1 }
}
const intl = new Intl.NumberFormat(this.language, { ...defaults, ...overrides })
return `${intl.format(value).replace(/(\d)\s/, "$1")} ${number === 1 ? text : pluralize(text)}`.trim()
}
percentage(value: number, digits = 2): string {
const intl = Intl.NumberFormat(this.language, { style: "percent", minimumFractionDigits: 0, maximumFractionDigits: digits })
return intl.format(value).replaceAll(/\s/g, "")
}
for(language: string | Request, { timezone }: { timezone?: string } = {}): I18n {
if (language instanceof Request)
language = acceptsLanguages(language, ...I18n.#storage.keys()) ?? I18n.fallback
return new I18n({ language: language as string, timezone: timezone ?? this.timezone })
}
}
export const i18n = new I18n() as I18n
|