@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.
- package/LICENSE +22 -0
- package/README.md +38 -2
- package/dist/chunks/bun-index-1ve1hj66.js +744 -0
- package/dist/chunks/bun-index-8bw4xpv8.js +93 -0
- package/dist/chunks/bun-index-ej6vjnjs.js +297 -0
- package/dist/chunks/bun-index-pdepkyy1.js +474 -0
- package/dist/src/adapters/angular.js +67 -0
- package/dist/src/adapters/html.js +34 -0
- package/dist/src/adapters/preact.js +23 -0
- package/dist/src/adapters/react.js +23 -0
- package/dist/src/adapters/solid.js +48 -0
- package/dist/src/adapters/svelte.js +74 -0
- package/dist/src/adapters/vue.js +48 -0
- package/dist/src/cli.js +1898 -0
- package/dist/src/index.js +2755 -0
- package/dist/src/load.js +35 -0
- package/dist/src/server/index.js +395 -0
- package/dist/types/src/adapters/angular.d.ts +17 -0
- package/dist/types/src/adapters/bind.d.ts +44 -0
- package/dist/types/src/adapters/html.d.ts +5 -0
- package/dist/types/src/adapters/preact.d.ts +6 -0
- package/dist/types/src/adapters/react.d.ts +6 -0
- package/dist/types/src/adapters/solid.d.ts +9 -0
- package/dist/types/src/adapters/svelte.d.ts +12 -0
- package/dist/types/src/adapters/vue.d.ts +8 -0
- package/dist/types/src/build/catalog.d.ts +5 -0
- package/dist/types/src/build/drop.d.ts +12 -0
- package/dist/types/src/build/extract.d.ts +11 -0
- package/dist/types/src/build/head.d.ts +4 -0
- package/dist/types/src/build/messages.d.ts +27 -0
- package/dist/types/src/build/prerender.d.ts +10 -0
- package/dist/types/src/build/routes.d.ts +14 -0
- package/dist/types/src/build/split.d.ts +37 -0
- package/dist/types/src/build/types.d.ts +15 -0
- package/dist/types/src/cli.d.ts +12 -0
- package/dist/types/src/compiler/compile.d.ts +17 -0
- package/dist/types/src/compiler/mf2-parse.d.ts +62 -0
- package/dist/types/src/compiler/mf2.d.ts +3 -0
- package/dist/types/src/compiler/parse.d.ts +58 -0
- package/dist/types/src/compiler/skeleton.d.ts +7 -0
- package/dist/types/src/index.d.ts +2 -0
- package/dist/types/src/load.d.ts +7 -0
- package/dist/types/src/module.d.ts +15 -0
- package/dist/types/src/options.d.ts +7 -0
- package/dist/types/src/runtime/catalog-client.d.ts +3 -0
- package/dist/types/src/runtime/catalog-loader.d.ts +15 -0
- package/dist/types/src/runtime/catalog-server.d.ts +5 -0
- package/dist/types/src/runtime/catalog.d.ts +60 -0
- package/dist/types/src/runtime/chain.d.ts +3 -0
- package/dist/types/src/runtime/format.d.ts +27 -0
- package/dist/types/src/runtime/head.d.ts +9 -0
- package/dist/types/src/runtime/interpret.d.ts +20 -0
- package/dist/types/src/runtime/link.d.ts +8 -0
- package/dist/types/src/runtime/locale.d.ts +73 -0
- package/dist/types/src/runtime/match.d.ts +54 -0
- package/dist/types/src/runtime/messages.d.ts +42 -0
- package/dist/types/src/runtime/middleware.d.ts +2 -0
- package/dist/types/src/runtime/negotiate.d.ts +9 -0
- package/dist/types/src/runtime/plugin.d.ts +4 -0
- package/dist/types/src/runtime/redirect.d.ts +32 -0
- package/dist/types/src/runtime/rich.d.ts +5 -0
- package/dist/types/src/runtime/translate.d.ts +21 -0
- package/dist/types/src/server/catalog.d.ts +2 -0
- package/dist/types/src/server/context.d.ts +48 -0
- package/dist/types/src/server/door-all-catalog.d.ts +3 -0
- package/dist/types/src/server/door-all.d.ts +2 -0
- package/dist/types/src/server/door-catalog.d.ts +3 -0
- package/dist/types/src/server/door-root-catalog.d.ts +3 -0
- package/dist/types/src/server/door-root.d.ts +2 -0
- package/dist/types/src/server/door.d.ts +2 -0
- package/dist/types/src/server/index.d.ts +7 -0
- package/dist/types/src/server/preferred.d.ts +6 -0
- package/dist/types/src/server/redirect.d.ts +3 -0
- package/dist/types/src/server/setup.d.ts +2 -0
- package/dist/types/src/types.d.ts +163 -0
- package/package.json +122 -4
- package/src/adapters/angular.ts +65 -0
- package/src/adapters/bind.ts +144 -0
- package/src/adapters/html.ts +35 -0
- package/src/adapters/preact.ts +18 -0
- package/src/adapters/react.ts +18 -0
- package/src/adapters/solid.ts +44 -0
- package/src/adapters/svelte.ts +75 -0
- package/src/adapters/test/SveltePage.svelte +18 -0
- package/src/adapters/test/SvelteReporting.svelte +20 -0
- package/src/adapters/test/SvelteRich.svelte +11 -0
- package/src/adapters/test/SvelteRichPlain.svelte +11 -0
- package/src/adapters/test/peer.ts +7 -0
- package/src/adapters/test/preact-client.ts +43 -0
- package/src/adapters/test/preact-page.ts +34 -0
- package/src/adapters/test/preact-rich.ts +9 -0
- package/src/adapters/test/react-client.ts +49 -0
- package/src/adapters/test/react-page.ts +34 -0
- package/src/adapters/test/react-rich.ts +15 -0
- package/src/adapters/test/runtime.ts +104 -0
- package/src/adapters/test/solid-client.ts +33 -0
- package/src/adapters/test/solid-page.ts +30 -0
- package/src/adapters/test/solid-rich.ts +5 -0
- package/src/adapters/test/svelte-client.ts +51 -0
- package/src/adapters/test/svelte-log.ts +2 -0
- package/src/adapters/test/svelte-plugin.ts +20 -0
- package/src/adapters/test/vue-page.ts +26 -0
- package/src/adapters/test/vue-rich.ts +16 -0
- package/src/adapters/vue.ts +44 -0
- package/src/build/catalog.ts +44 -0
- package/src/build/drop.ts +36 -0
- package/src/build/extract.ts +207 -0
- package/src/build/head.ts +10 -0
- package/src/build/messages.ts +347 -0
- package/src/build/prerender.ts +48 -0
- package/src/build/routes.ts +269 -0
- package/src/build/split.ts +240 -0
- package/src/build/types.ts +156 -0
- package/src/cli.ts +25 -0
- package/src/compiler/compile.ts +190 -0
- package/src/compiler/mf2-parse.ts +469 -0
- package/src/compiler/mf2.ts +393 -0
- package/src/compiler/parse.ts +265 -0
- package/src/compiler/skeleton.ts +85 -0
- package/src/env.d.ts +55 -0
- package/src/index.ts +24 -0
- package/src/load.ts +41 -0
- package/src/module.ts +66 -0
- package/src/options.ts +198 -0
- package/src/runtime/catalog-client.ts +28 -0
- package/src/runtime/catalog-loader.ts +28 -0
- package/src/runtime/catalog-server.ts +36 -0
- package/src/runtime/catalog.ts +190 -0
- package/src/runtime/chain.ts +9 -0
- package/src/runtime/format.ts +102 -0
- package/src/runtime/head.ts +57 -0
- package/src/runtime/interpret.ts +504 -0
- package/src/runtime/link.ts +36 -0
- package/src/runtime/locale.ts +392 -0
- package/src/runtime/match.ts +334 -0
- package/src/runtime/messages.ts +129 -0
- package/src/runtime/middleware.ts +32 -0
- package/src/runtime/negotiate.ts +61 -0
- package/src/runtime/plugin.ts +69 -0
- package/src/runtime/redirect.ts +191 -0
- package/src/runtime/rich.ts +21 -0
- package/src/runtime/translate.ts +131 -0
- package/src/server/catalog.ts +11 -0
- package/src/server/context.ts +191 -0
- package/src/server/door-all-catalog.ts +7 -0
- package/src/server/door-all.ts +5 -0
- package/src/server/door-catalog.ts +6 -0
- package/src/server/door-root-catalog.ts +7 -0
- package/src/server/door-root.ts +5 -0
- package/src/server/door.ts +4 -0
- package/src/server/index.ts +11 -0
- package/src/server/preferred.ts +12 -0
- package/src/server/redirect.ts +26 -0
- package/src/server/setup.ts +14 -0
- package/src/types.ts +182 -0
|
@@ -0,0 +1,240 @@
|
|
|
1
|
+
import { existsSync } from "node:fs"
|
|
2
|
+
import { readFile } from "node:fs/promises"
|
|
3
|
+
import { dirname, join, sep } from "node:path"
|
|
4
|
+
import type { HamurContext, RouteRecord } from "hamur/kit"
|
|
5
|
+
|
|
6
|
+
const SCRIPT_LOADERS: Record<string, Bun.JavaScriptLoader> = {
|
|
7
|
+
".ts": "ts",
|
|
8
|
+
".mts": "ts",
|
|
9
|
+
".cts": "ts",
|
|
10
|
+
".tsx": "tsx",
|
|
11
|
+
".js": "js",
|
|
12
|
+
".mjs": "js",
|
|
13
|
+
".cjs": "js",
|
|
14
|
+
".jsx": "jsx",
|
|
15
|
+
}
|
|
16
|
+
export const SOURCE = /\.(?:[cm]?[jt]sx?|vue|svelte|md|mdx|html)$/
|
|
17
|
+
const IMPORT_TEXT = /\b(?:import|export)\s+(?:[^'"`;]*?\bfrom\s*)?(["'])([^"'\n]+)\1/g
|
|
18
|
+
const INLINE_OBJECT = "useTranslation\\s*\\([^()]*\\)\\s*\\)?\\s*\\.\\s*t\\s*"
|
|
19
|
+
const BINDING =
|
|
20
|
+
/\b(?:const|let|var)\s+(\{[^}]*\}|[A-Za-z_$][\w$]*)\s*=\s*(?:await\s+)?[\w$.]*?(?:useI18n|useTranslation|translator)\s*\(/g
|
|
21
|
+
const baseOf = (name: string): string => name.split("___")[0]!
|
|
22
|
+
const escape = (text: string) => text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")
|
|
23
|
+
|
|
24
|
+
const transpilers = new Map<Bun.Loader, Bun.Transpiler>()
|
|
25
|
+
|
|
26
|
+
/** What one file asks of the catalog: the literal keys of its `t` calls, and whether any call has a key that is not a literal. */
|
|
27
|
+
export interface KeyRead {
|
|
28
|
+
keys: Set<string>
|
|
29
|
+
dynamic: boolean
|
|
30
|
+
/** Offset of the first call whose key is not a literal. */
|
|
31
|
+
at?: number
|
|
32
|
+
/** Key to the offset of its first call. */
|
|
33
|
+
positions: Map<string, number>
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/** The names a `useI18n()`, `useTranslation(event)` or `translator(code)` result is bound to: the `t` aliases and the whole-result names. */
|
|
37
|
+
function boundNames(source: string): { functions: Set<string>; objects: Set<string> } {
|
|
38
|
+
const functions = new Set<string>()
|
|
39
|
+
const objects = new Set<string>()
|
|
40
|
+
for (const found of source.matchAll(BINDING)) {
|
|
41
|
+
const target = found[1]!
|
|
42
|
+
if (!target.startsWith("{")) {
|
|
43
|
+
objects.add(target)
|
|
44
|
+
continue
|
|
45
|
+
}
|
|
46
|
+
for (const member of target.slice(1, -1).split(",")) {
|
|
47
|
+
const named = /^\s*t\s*(?::\s*([A-Za-z_$][\w$]*))?\s*(?:=.*)?$/s.exec(member)
|
|
48
|
+
if (named) functions.add(named[1] ?? "t")
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
return { functions, objects }
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/** The literal first argument of the call whose `(` ends at `at`: its text, `null` when the argument is not a literal, `undefined` for `t()`. */
|
|
55
|
+
function firstArgument(source: string, at: number): string | null | undefined {
|
|
56
|
+
let i = at
|
|
57
|
+
while (/\s/.test(source[i] ?? "")) i++
|
|
58
|
+
const quote = source[i]
|
|
59
|
+
if (quote === ")") return undefined
|
|
60
|
+
if (quote !== '"' && quote !== "'" && quote !== "`") return null
|
|
61
|
+
let end = i + 1
|
|
62
|
+
while (end < source.length && source[end] !== quote) {
|
|
63
|
+
if (source[end] === "\\" || (quote === "`" && source[end] === "$" && source[end + 1] === "{")) return null
|
|
64
|
+
end++
|
|
65
|
+
}
|
|
66
|
+
if (end >= source.length) return null
|
|
67
|
+
let after = end + 1
|
|
68
|
+
while (/\s/.test(source[after] ?? "")) after++
|
|
69
|
+
return source[after] === "," || source[after] === ")" ? source.slice(i + 1, end) : null
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/**
|
|
73
|
+
* The `t("<literal>")`, `t.rich("<literal>")` and `` t(`<no ${}>`) `` calls of one file, under the names a `useI18n()` result was bound to.
|
|
74
|
+
* With `withDynamic`, `t.dynamic("<literal>")` is a key and `t.dynamic(x)` a dynamic call too.
|
|
75
|
+
*/
|
|
76
|
+
export function readKeys(source: string, withDynamic = true): KeyRead {
|
|
77
|
+
const keys = new Set<string>()
|
|
78
|
+
const positions = new Map<string, number>()
|
|
79
|
+
let dynamic = false
|
|
80
|
+
let at: number | undefined
|
|
81
|
+
const { functions, objects } = boundNames(source)
|
|
82
|
+
const member = withDynamic ? "(?:\\.\\s*(?:rich|dynamic)\\s*)?\\(" : "(?:\\.\\s*rich\\s*)?\\("
|
|
83
|
+
const patterns = [
|
|
84
|
+
new RegExp(INLINE_OBJECT + member, "g"),
|
|
85
|
+
...[...functions].map((name) => new RegExp("(?<![\\w$.])" + escape(name) + "\\s*" + member, "g")),
|
|
86
|
+
...[...objects].map((name) => new RegExp("(?<![\\w$.])" + escape(name) + "\\s*\\.\\s*t\\s*" + member, "g")),
|
|
87
|
+
]
|
|
88
|
+
for (const pattern of patterns) {
|
|
89
|
+
for (const found of source.matchAll(pattern)) {
|
|
90
|
+
const argument = firstArgument(source, found.index + found[0].length)
|
|
91
|
+
if (argument === undefined) continue
|
|
92
|
+
if (argument === null) {
|
|
93
|
+
dynamic = true
|
|
94
|
+
at = at === undefined ? found.index : Math.min(at, found.index)
|
|
95
|
+
} else {
|
|
96
|
+
keys.add(argument)
|
|
97
|
+
positions.set(argument, Math.min(positions.get(argument) ?? found.index, found.index))
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
return { keys, dynamic, positions, ...(at === undefined ? {} : { at }) }
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
function importsOf(source: string, file: string): string[] {
|
|
105
|
+
const loader = SCRIPT_LOADERS[file.slice(file.lastIndexOf("."))]
|
|
106
|
+
if (loader) {
|
|
107
|
+
let transpiler = transpilers.get(loader)
|
|
108
|
+
if (!transpiler) transpilers.set(loader, (transpiler = new Bun.Transpiler({ loader })))
|
|
109
|
+
try {
|
|
110
|
+
return transpiler
|
|
111
|
+
.scan(source)
|
|
112
|
+
.imports.filter((entry) => entry.kind === "import-statement")
|
|
113
|
+
.map((entry) => entry.path)
|
|
114
|
+
} catch {
|
|
115
|
+
// A file the scanner cannot parse is read by its import lines instead.
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
return [...source.matchAll(IMPORT_TEXT)].map((found) => found[2]!)
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
export interface SplitReader {
|
|
122
|
+
/** The keys of `entries` and of the files they import statically, and the files among them with a key that is not a literal. */
|
|
123
|
+
read(entries: string[]): Promise<{ keys: Set<string>; dynamic: string[] }>
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
/** Reads each file once; only files under `roots` (the app and its layers, not `node_modules`) are followed. */
|
|
127
|
+
export function createSplitReader(roots: string[]): SplitReader {
|
|
128
|
+
const files = new Map<string, Promise<{ read: KeyRead; imports: string[] } | undefined>>()
|
|
129
|
+
const inside = (file: string) =>
|
|
130
|
+
!file.includes(sep + "node_modules" + sep) && roots.some((root) => file.startsWith(root + sep)) && SOURCE.test(file)
|
|
131
|
+
const resolve = (specifier: string, from: string): string | undefined => {
|
|
132
|
+
if (!/^[./#]/.test(specifier)) return undefined
|
|
133
|
+
try {
|
|
134
|
+
return Bun.resolveSync(specifier, dirname(from))
|
|
135
|
+
} catch {
|
|
136
|
+
return undefined
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
const load = (file: string) => {
|
|
140
|
+
let held = files.get(file)
|
|
141
|
+
if (!held) {
|
|
142
|
+
held = readFile(file, "utf8").then(
|
|
143
|
+
(source) => ({
|
|
144
|
+
read: readKeys(source),
|
|
145
|
+
imports: importsOf(source, file).flatMap((specifier) => resolve(specifier, file) ?? []),
|
|
146
|
+
}),
|
|
147
|
+
() => undefined,
|
|
148
|
+
)
|
|
149
|
+
files.set(file, held)
|
|
150
|
+
}
|
|
151
|
+
return held
|
|
152
|
+
}
|
|
153
|
+
return {
|
|
154
|
+
async read(entries) {
|
|
155
|
+
const keys = new Set<string>()
|
|
156
|
+
const dynamic: string[] = []
|
|
157
|
+
const seen = new Set<string>()
|
|
158
|
+
const queue = [...entries]
|
|
159
|
+
for (let file = queue.shift(); file !== undefined; file = queue.shift()) {
|
|
160
|
+
if (seen.has(file)) continue
|
|
161
|
+
seen.add(file)
|
|
162
|
+
const loaded = await load(file)
|
|
163
|
+
if (!loaded) continue
|
|
164
|
+
for (const key of loaded.read.keys) keys.add(key)
|
|
165
|
+
if (loaded.read.dynamic) dynamic.push(file)
|
|
166
|
+
queue.push(...loaded.imports.filter((next) => !seen.has(next) && inside(next)))
|
|
167
|
+
}
|
|
168
|
+
return { keys, dynamic }
|
|
169
|
+
},
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
export interface SplitKeys {
|
|
174
|
+
keys: Set<string>
|
|
175
|
+
/** The files whose route ships the whole catalog. */
|
|
176
|
+
dynamic: string[]
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
export interface SplitPlan {
|
|
180
|
+
shared: SplitKeys
|
|
181
|
+
/** Route base name → keys of its page chain and boundaries, those of `shared` left out. */
|
|
182
|
+
routes: Map<string, SplitKeys>
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
function flatten(
|
|
186
|
+
records: RouteRecord[],
|
|
187
|
+
ancestors: RouteRecord[] = [],
|
|
188
|
+
): Array<{ record: RouteRecord; chain: RouteRecord[] }> {
|
|
189
|
+
return records.flatMap((record) => [
|
|
190
|
+
{ record, chain: [...ancestors, record] },
|
|
191
|
+
...flatten(record.children, [...ancestors, record]),
|
|
192
|
+
])
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
const slotFiles = (record: RouteRecord): string[] =>
|
|
196
|
+
Object.values(record.slots ?? {}).flatMap((slot) => [
|
|
197
|
+
...(slot.default ? [slot.default] : []),
|
|
198
|
+
...flatten(slot.routes).map((entry) => entry.record.file),
|
|
199
|
+
])
|
|
200
|
+
|
|
201
|
+
const filesOf = (chain: RouteRecord[]): string[] =>
|
|
202
|
+
chain.flatMap((record) => [
|
|
203
|
+
record.file,
|
|
204
|
+
...[record.error, record.template, record.notFound, record.outletNotFound, record.pending].filter(
|
|
205
|
+
(file): file is string => file !== undefined,
|
|
206
|
+
),
|
|
207
|
+
...slotFiles(record),
|
|
208
|
+
])
|
|
209
|
+
|
|
210
|
+
/** The `app/error.<ext>` of the app or the first layer that has one. */
|
|
211
|
+
function errorFile(hamur: HamurContext): string | undefined {
|
|
212
|
+
for (const { srcDir } of [hamur.options, ...hamur.options.layers]) {
|
|
213
|
+
for (const extension of hamur.adapter.extensions)
|
|
214
|
+
if (existsSync(join(srcDir, "error" + extension))) return join(srcDir, "error" + extension)
|
|
215
|
+
}
|
|
216
|
+
return undefined
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
/** What each route, and the layouts, `app/app.*` and `app/error.*`, read from the catalogs. */
|
|
220
|
+
export async function planSplit(hamur: HamurContext): Promise<SplitPlan> {
|
|
221
|
+
const { options } = hamur
|
|
222
|
+
const roots = [options.rootDir, ...options.layers.map((layer) => layer.rootDir)]
|
|
223
|
+
const reader = createSplitReader(roots)
|
|
224
|
+
const error = errorFile(hamur)
|
|
225
|
+
const sharedFiles = [
|
|
226
|
+
...hamur.layouts.map((layout) => layout.file),
|
|
227
|
+
...(hamur.appRoot ? [hamur.appRoot] : []),
|
|
228
|
+
...(hamur.notFound ? [hamur.notFound] : []),
|
|
229
|
+
...(error ? [error] : []),
|
|
230
|
+
]
|
|
231
|
+
const shared = await reader.read(sharedFiles)
|
|
232
|
+
const routes = new Map<string, SplitKeys>()
|
|
233
|
+
for (const { record, chain } of flatten(hamur.routes)) {
|
|
234
|
+
const base = baseOf(record.name)
|
|
235
|
+
if (routes.has(base)) continue
|
|
236
|
+
const own = await reader.read(filesOf(chain))
|
|
237
|
+
routes.set(base, { keys: new Set([...own.keys].filter((key) => !shared.keys.has(key))), dynamic: own.dynamic })
|
|
238
|
+
}
|
|
239
|
+
return { shared, routes }
|
|
240
|
+
}
|
|
@@ -0,0 +1,156 @@
|
|
|
1
|
+
import { DiagnosticError, addTypeTemplate, diagnostic, useLogger, type HamurContext } from "hamur/kit"
|
|
2
|
+
import { compileCatalog, type ArgKind } from "../compiler/compile.ts"
|
|
3
|
+
import { parseMessage, type MessageNode } from "../compiler/parse.ts"
|
|
4
|
+
import type { I18nSetup, ResolvedI18nOptions } from "../types.ts"
|
|
5
|
+
import { mergeLocaleFiles, scanLocaleFiles } from "./messages.ts"
|
|
6
|
+
|
|
7
|
+
export interface LocaleAnalysis {
|
|
8
|
+
/** Key to argument name to its TypeScript type, from the default locale. */
|
|
9
|
+
messages: Record<string, Record<string, string>>
|
|
10
|
+
/** Key to the tag names of its message, from the default locale; only keys with tags. */
|
|
11
|
+
tags: Record<string, string[]>
|
|
12
|
+
warnings: string[]
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
function selectCases(nodes: MessageNode[], into: Map<string, Set<string>>): void {
|
|
16
|
+
for (const node of nodes) {
|
|
17
|
+
if (node.type === "select") {
|
|
18
|
+
const set = into.get(node.name) ?? new Set<string>()
|
|
19
|
+
for (const { key } of node.cases) if (key !== "other") set.add(key)
|
|
20
|
+
into.set(node.name, set)
|
|
21
|
+
}
|
|
22
|
+
if (node.type === "select" || node.type === "plural") for (const { body } of node.cases) selectCases(body, into)
|
|
23
|
+
if (node.type === "tag") selectCases(node.children, into)
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
function typeOf(kind: ArgKind, cases: Set<string> | undefined): string {
|
|
28
|
+
switch (kind) {
|
|
29
|
+
case "text":
|
|
30
|
+
return "string | number"
|
|
31
|
+
case "number":
|
|
32
|
+
return "number"
|
|
33
|
+
case "date":
|
|
34
|
+
return "Date | number"
|
|
35
|
+
case "select":
|
|
36
|
+
return [...[...(cases ?? [])].map((name) => JSON.stringify(name)), "(string & {})"].join(" | ")
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** The argument types of the default locale and the cross-locale checks; an argument a translation adds or retypes throws. */
|
|
41
|
+
export async function analyzeLocales(
|
|
42
|
+
options: ResolvedI18nOptions,
|
|
43
|
+
roots: string[],
|
|
44
|
+
rootDir: string,
|
|
45
|
+
): Promise<LocaleAnalysis> {
|
|
46
|
+
const { byCode } = await scanLocaleFiles(
|
|
47
|
+
roots,
|
|
48
|
+
options.locales.map((locale) => locale.code),
|
|
49
|
+
)
|
|
50
|
+
const load = async (code: string) => {
|
|
51
|
+
const merged = await mergeLocaleFiles(byCode.get(code) ?? [], rootDir)
|
|
52
|
+
const language = options.locales.find((locale) => locale.code === code)!.language
|
|
53
|
+
const { args, tags } = compileCatalog(merged.messages, language, {
|
|
54
|
+
file: (key) => merged.origin[key] ?? `locales/${code}.json`,
|
|
55
|
+
syntax: options.syntax,
|
|
56
|
+
})
|
|
57
|
+
return { ...merged, args, tags }
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
const base = await load(options.defaultLocale)
|
|
61
|
+
const baseKeys = Object.keys(base.messages)
|
|
62
|
+
const messages: LocaleAnalysis["messages"] = {}
|
|
63
|
+
for (const key of baseKeys) {
|
|
64
|
+
const cases = new Map<string, Set<string>>()
|
|
65
|
+
if (options.syntax === "mf1") selectCases(parseMessage(base.messages[key]!), cases)
|
|
66
|
+
messages[key] = Object.fromEntries(
|
|
67
|
+
Object.entries(base.args[key]!).map(([name, kind]) => [name, typeOf(kind, cases.get(name))]),
|
|
68
|
+
)
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
const warnings: string[] = []
|
|
72
|
+
const tags = base.tags
|
|
73
|
+
if (baseKeys.length === 0) return { messages, tags, warnings }
|
|
74
|
+
for (const { code } of options.locales) {
|
|
75
|
+
if (code === options.defaultLocale || !byCode.has(code)) continue
|
|
76
|
+
const own = await load(code)
|
|
77
|
+
const file = `locales/${code}.json`
|
|
78
|
+
const missing = baseKeys.filter((key) => !Object.hasOwn(own.messages, key))
|
|
79
|
+
if (missing.length)
|
|
80
|
+
warnings.push(
|
|
81
|
+
`${file} lacks ${missing.length} key${missing.length === 1 ? "" : "s"} of the default locale: ${missing.join(", ")}`,
|
|
82
|
+
)
|
|
83
|
+
const extra = Object.keys(own.messages).filter((key) => !Object.hasOwn(base.messages, key))
|
|
84
|
+
if (extra.length)
|
|
85
|
+
warnings.push(
|
|
86
|
+
`${file} has ${extra.length} key${extra.length === 1 ? "" : "s"} the default locale lacks: ${extra.join(", ")}`,
|
|
87
|
+
)
|
|
88
|
+
for (const [key, args] of Object.entries(own.args)) {
|
|
89
|
+
const expected = base.args[key]
|
|
90
|
+
if (!expected) continue
|
|
91
|
+
const where = own.origin[key] ?? file
|
|
92
|
+
for (const tag of own.tags[key] ?? []) {
|
|
93
|
+
if (!base.tags[key]?.includes(tag))
|
|
94
|
+
throw new DiagnosticError(
|
|
95
|
+
"HAMUR_E5827",
|
|
96
|
+
`${where} ${JSON.stringify(key)}: tag <${tag}> is not in the default locale's message`,
|
|
97
|
+
)
|
|
98
|
+
}
|
|
99
|
+
for (const [name, kind] of Object.entries(args)) {
|
|
100
|
+
if (!Object.hasOwn(expected, name))
|
|
101
|
+
throw new DiagnosticError(
|
|
102
|
+
"HAMUR_E5828",
|
|
103
|
+
`${where} ${JSON.stringify(key)}: argument ${JSON.stringify(name)} is not in the default locale's message`,
|
|
104
|
+
)
|
|
105
|
+
if (expected[name] !== kind)
|
|
106
|
+
throw new DiagnosticError(
|
|
107
|
+
"HAMUR_E5829",
|
|
108
|
+
`${where} ${JSON.stringify(key)}: argument ${JSON.stringify(name)} is ${kind}, the default locale's message has ${expected[name]}`,
|
|
109
|
+
)
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
return { messages, tags, warnings }
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
export function typesTemplate(options: ResolvedI18nOptions, analysis: LocaleAnalysis): string {
|
|
117
|
+
const messages = Object.entries(analysis.messages).map(([key, args]) => {
|
|
118
|
+
const fields = Object.entries(args).map(([name, type]) => `${JSON.stringify(name)}: ${type}`)
|
|
119
|
+
return ` ${JSON.stringify(key)}: ${fields.length ? `{ ${fields.join("; ")} }` : "{}"};`
|
|
120
|
+
})
|
|
121
|
+
const locales = options.locales.map(({ code }) => ` ${JSON.stringify(code)}: true;`)
|
|
122
|
+
const tagged = Object.entries(analysis.tags).map(
|
|
123
|
+
([key, names]) => ` ${JSON.stringify(key)}: ${names.map((name) => JSON.stringify(name)).join(" | ")};`,
|
|
124
|
+
)
|
|
125
|
+
const tags = tagged.length ? ` interface HamurI18nTags {\n${tagged.join("\n")}\n }\n` : ""
|
|
126
|
+
return `declare module "@hamur/i18n" {
|
|
127
|
+
interface HamurI18nMessages {
|
|
128
|
+
${messages.join("\n")}
|
|
129
|
+
}
|
|
130
|
+
${tags} interface HamurI18nLocales {
|
|
131
|
+
${locales.join("\n")}
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
export {};
|
|
135
|
+
`
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
/** Under `prefix` no page is `/`, but the root redirect answers it, so a `Link` to `/` type-checks. */
|
|
139
|
+
export function rootPathTypes(options: ResolvedI18nOptions, hamur: HamurContext): string {
|
|
140
|
+
if (!hamur.options.typescript.typedPaths || options.strategy !== "prefix" || options.detect.redirect === false)
|
|
141
|
+
return ""
|
|
142
|
+
return `declare module "hamur/app" {\n interface HamurRoutePaths {\n "i18n /": "/";\n }\n}\n`
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
export const setupTypes: I18nSetup = async (options: ResolvedI18nOptions, hamur: HamurContext) => {
|
|
146
|
+
const { rootDir, layers } = hamur.options
|
|
147
|
+
const roots = [rootDir, ...layers.map((layer) => layer.rootDir)]
|
|
148
|
+
const log = useLogger("hamur")
|
|
149
|
+
const analysis = await analyzeLocales(options, roots, rootDir)
|
|
150
|
+
for (const text of analysis.warnings) log.warn(diagnostic("HAMUR_W5830", `i18n: ${text}`))
|
|
151
|
+
addTypeTemplate({
|
|
152
|
+
filename: "i18n.d.ts",
|
|
153
|
+
getContents: async () =>
|
|
154
|
+
typesTemplate(options, await analyzeLocales(options, roots, rootDir)) + rootPathTypes(options, hamur),
|
|
155
|
+
})
|
|
156
|
+
}
|
package/src/cli.ts
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import type { HamurContext } from "hamur/kit"
|
|
2
|
+
import { extract } from "./build/extract.ts"
|
|
3
|
+
import { resolvedOptions } from "./module.ts"
|
|
4
|
+
import { DiagnosticError } from "hamur/kit"
|
|
5
|
+
|
|
6
|
+
export interface I18nCommand {
|
|
7
|
+
command: "extract"
|
|
8
|
+
check?: boolean
|
|
9
|
+
prune?: boolean
|
|
10
|
+
out(line: string): void
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* The body of `hamur i18n`, on a context `createContext` made with the dev config.
|
|
15
|
+
* Resolves to the exit code; a failure rejects with the message the CLI prints.
|
|
16
|
+
*/
|
|
17
|
+
export async function runI18nCommand(args: I18nCommand, hamur: HamurContext): Promise<number> {
|
|
18
|
+
const options = resolvedOptions.get(hamur)
|
|
19
|
+
if (!options)
|
|
20
|
+
throw new DiagnosticError(
|
|
21
|
+
"HAMUR_E5801",
|
|
22
|
+
"hamur i18n needs @hamur/i18n (bun add @hamur/i18n, then add it to modules)",
|
|
23
|
+
)
|
|
24
|
+
return extract(hamur, options, { check: args.check === true, prune: args.prune === true }, args.out)
|
|
25
|
+
}
|
|
@@ -0,0 +1,190 @@
|
|
|
1
|
+
import { compileMf2Catalog } from "./mf2.ts"
|
|
2
|
+
import { MessageSyntaxError, parseMessage, type MessageNode } from "./parse.ts"
|
|
3
|
+
import { DiagnosticError } from "hamur/kit"
|
|
4
|
+
|
|
5
|
+
export type ArgKind = "text" | "number" | "date" | "select"
|
|
6
|
+
|
|
7
|
+
export interface CompileOptions {
|
|
8
|
+
/** The file a key came from, for error and warning text. */
|
|
9
|
+
file?: string | ((key: string) => string)
|
|
10
|
+
/** Gets each warning; the default drops them. */
|
|
11
|
+
warn?: (text: string) => void
|
|
12
|
+
/** The message syntax; default `"mf1"`. */
|
|
13
|
+
syntax?: "mf1" | "mf2"
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
export interface CompiledCatalog {
|
|
17
|
+
code: string
|
|
18
|
+
args: Record<string, Record<string, ArgKind>>
|
|
19
|
+
/** The tag names of each message that has tags, in order of first use. */
|
|
20
|
+
tags: Record<string, string[]>
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
interface Scope {
|
|
24
|
+
pound: string | undefined
|
|
25
|
+
state: { used: boolean }
|
|
26
|
+
depth: number
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
const q = JSON.stringify
|
|
30
|
+
|
|
31
|
+
function hasTag(nodes: MessageNode[]): boolean {
|
|
32
|
+
return nodes.some(
|
|
33
|
+
(node) =>
|
|
34
|
+
node.type === "tag" ||
|
|
35
|
+
((node.type === "plural" || node.type === "select") && node.cases.some(({ body }) => hasTag(body))),
|
|
36
|
+
)
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
function collectTags(nodes: MessageNode[], into: Set<string>): void {
|
|
40
|
+
for (const node of nodes) {
|
|
41
|
+
if (node.type === "tag") {
|
|
42
|
+
into.add(node.name)
|
|
43
|
+
collectTags(node.children, into)
|
|
44
|
+
} else if (node.type === "plural" || node.type === "select")
|
|
45
|
+
for (const { body } of node.cases) collectTags(body, into)
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
function categoriesOf(language: string, type: "cardinal" | "ordinal"): Set<string> {
|
|
50
|
+
return new Set(new Intl.PluralRules(language, { type }).resolvedOptions().pluralCategories)
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** The module text of one locale (`export default { key: string | (a, f) => string }`, no import) and the argument kinds of each message. */
|
|
54
|
+
export function compileCatalog(
|
|
55
|
+
messages: Record<string, string>,
|
|
56
|
+
language: string,
|
|
57
|
+
options: CompileOptions = {},
|
|
58
|
+
): CompiledCatalog {
|
|
59
|
+
if (options.syntax === "mf2") return compileMf2Catalog(messages, language, options)
|
|
60
|
+
const entries: string[] = []
|
|
61
|
+
const args: Record<string, Record<string, ArgKind>> = {}
|
|
62
|
+
const tags: Record<string, string[]> = {}
|
|
63
|
+
const helpers = { g: false, v: false, j: false, m: false }
|
|
64
|
+
const where = (key: string) => {
|
|
65
|
+
const file = typeof options.file === "function" ? options.file(key) : (options.file ?? `locales/${language}.json`)
|
|
66
|
+
return `${file} ${q(key)}`
|
|
67
|
+
}
|
|
68
|
+
const cardinal = categoriesOf(language, "cardinal")
|
|
69
|
+
const ordinal = categoriesOf(language, "ordinal")
|
|
70
|
+
|
|
71
|
+
for (const [key, source] of Object.entries(messages)) {
|
|
72
|
+
let nodes: MessageNode[]
|
|
73
|
+
try {
|
|
74
|
+
nodes = parseMessage(source)
|
|
75
|
+
} catch (error) {
|
|
76
|
+
if (error instanceof MessageSyntaxError)
|
|
77
|
+
throw new DiagnosticError("HAMUR_E5807", error.message, { at: where(key) })
|
|
78
|
+
throw error
|
|
79
|
+
}
|
|
80
|
+
const kinds: Record<string, ArgKind> = {}
|
|
81
|
+
const use = (name: string, kind: ArgKind) => {
|
|
82
|
+
const known = kinds[name]
|
|
83
|
+
if (known === undefined || known === "text") kinds[name] = kind
|
|
84
|
+
else if (kind !== "text" && known !== kind)
|
|
85
|
+
throw new DiagnosticError("HAMUR_E5808", `argument ${q(name)} is used as both ${known} and ${kind}`, {
|
|
86
|
+
at: where(key),
|
|
87
|
+
})
|
|
88
|
+
}
|
|
89
|
+
const ref = (name: string) => {
|
|
90
|
+
helpers.g = true
|
|
91
|
+
return `g(a, ${q(name)})`
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
const emit = (list: MessageNode[], scope: Scope): string[] =>
|
|
95
|
+
list.map((node): string => {
|
|
96
|
+
switch (node.type) {
|
|
97
|
+
case "text":
|
|
98
|
+
return q(node.value)
|
|
99
|
+
case "pound":
|
|
100
|
+
scope.state.used = true
|
|
101
|
+
return scope.pound!
|
|
102
|
+
case "arg":
|
|
103
|
+
use(node.name, "text")
|
|
104
|
+
helpers.v = true
|
|
105
|
+
return `v(${ref(node.name)}, f)`
|
|
106
|
+
case "number": {
|
|
107
|
+
use(node.name, "number")
|
|
108
|
+
const opts = {
|
|
109
|
+
decimal: "{}",
|
|
110
|
+
integer: "{ maximumFractionDigits: 0 }",
|
|
111
|
+
percent: '{ style: "percent" }',
|
|
112
|
+
currency: `{ style: "currency", currency: ${q(node.currency)} }`,
|
|
113
|
+
skeleton: q(node.options),
|
|
114
|
+
}[node.style]
|
|
115
|
+
if (node.scale === undefined) return `f.n(${ref(node.name)}, ${opts})`
|
|
116
|
+
helpers.m = true
|
|
117
|
+
return `f.n(m(${ref(node.name)}, ${node.scale}), ${opts})`
|
|
118
|
+
}
|
|
119
|
+
case "tag":
|
|
120
|
+
return `{ tag: ${q(node.name)}, children: ${join(node.children, scope)} }`
|
|
121
|
+
case "date":
|
|
122
|
+
use(node.name, "date")
|
|
123
|
+
return `f.d(${ref(node.name)}, { ${node.kind === "date" ? "dateStyle" : "timeStyle"}: ${q(node.style)} })`
|
|
124
|
+
case "select": {
|
|
125
|
+
use(node.name, "select")
|
|
126
|
+
const cases = node.cases.map(
|
|
127
|
+
({ key: label, body }) =>
|
|
128
|
+
`${q(label)}: ${caseBody(body, { pound: scope.pound, state: scope.state, depth: scope.depth }, false)}`,
|
|
129
|
+
)
|
|
130
|
+
return `f.s(${ref(node.name)}, { ${cases.join(", ")} })`
|
|
131
|
+
}
|
|
132
|
+
case "plural": {
|
|
133
|
+
use(node.name, "number")
|
|
134
|
+
const known = node.ordinal ? ordinal : cardinal
|
|
135
|
+
for (const { key: label } of node.cases) {
|
|
136
|
+
if (label.startsWith("=") || label === "other" || known.has(label)) continue
|
|
137
|
+
options.warn?.(`${where(key)}: plural case ${q(label)} never applies to ${language}`)
|
|
138
|
+
}
|
|
139
|
+
const cases = node.cases.map(({ key: label, body }) => {
|
|
140
|
+
const own: Scope = { pound: `c${scope.depth}`, state: { used: false }, depth: scope.depth + 1 }
|
|
141
|
+
return `${q(label)}: ${caseBody(body, own, true)}`
|
|
142
|
+
})
|
|
143
|
+
return `f.p(${ref(node.name)}, ${node.offset}, { ${cases.join(", ")} }, ${node.ordinal})`
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
})
|
|
147
|
+
|
|
148
|
+
const join = (list: MessageNode[], scope: Scope): string => {
|
|
149
|
+
helpers.j = true
|
|
150
|
+
return `J(${emit(list, scope).join(", ")})`
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
const caseBody = (body: MessageNode[], scope: Scope, takesCount: boolean): string => {
|
|
154
|
+
const parts = emit(body, scope)
|
|
155
|
+
let text = parts.length === 0 ? '""' : parts.join(" + ")
|
|
156
|
+
if (hasTag(body)) {
|
|
157
|
+
helpers.j = true
|
|
158
|
+
text = `J(${parts.join(", ")})`
|
|
159
|
+
}
|
|
160
|
+
if (body.every((node) => node.type === "text")) return text
|
|
161
|
+
return takesCount && scope.state.used ? `(${scope.pound}) => ${text}` : `() => ${text}`
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
const top: Scope = { pound: undefined, state: { used: false }, depth: 0 }
|
|
165
|
+
const rich = hasTag(nodes)
|
|
166
|
+
const parts = emit(nodes, top)
|
|
167
|
+
args[key] = kinds
|
|
168
|
+
if (rich) {
|
|
169
|
+
const names = new Set<string>()
|
|
170
|
+
collectTags(nodes, names)
|
|
171
|
+
tags[key] = [...names]
|
|
172
|
+
helpers.j = true
|
|
173
|
+
}
|
|
174
|
+
const dynamic = nodes.some((node) => node.type !== "text")
|
|
175
|
+
const body = rich ? `J(${parts.join(", ")})` : parts.length ? parts.join(" + ") : '""'
|
|
176
|
+
entries.push(` ${q(key)}: ${dynamic ? `(a, f) => ${body}` : body},`)
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
const lines: string[] = []
|
|
180
|
+
if (helpers.g)
|
|
181
|
+
lines.push('const g = (a, k) => (k in a && Object.hasOwn(a, k) && a[k] !== undefined ? a[k] : "{" + k + "}");')
|
|
182
|
+
if (helpers.v)
|
|
183
|
+
lines.push(
|
|
184
|
+
'const v = (x, f) => (typeof x === "number" || typeof x === "bigint" ? f.n(x) : x instanceof Date ? f.d(x) : String(x));',
|
|
185
|
+
)
|
|
186
|
+
if (helpers.j) lines.push("const J = (...p) => p.flat();")
|
|
187
|
+
if (helpers.m) lines.push('const m = (x, s) => (typeof x === "number" || typeof x === "bigint" ? Number(x) * s : x);')
|
|
188
|
+
lines.push(entries.length ? `export default {\n${entries.join("\n")}\n};` : "export default {};")
|
|
189
|
+
return { code: `${lines.join("\n")}\n`, args, tags }
|
|
190
|
+
}
|