|
| 1 | +// The translation slices in the client build (script/i18n-slices.ts works out what goes in each): |
| 2 | +// |
| 3 | +// - each locale gets a table module (virtual:i18n/<locale>) holding the shell's strings and where each |
| 4 | +// other slice is, each slice a module of its own (virtual:i18n/<locale>/<slice>), and |
| 5 | +// src/i18n/tables.ts becomes the 18 tables; |
| 6 | +// - src/i18n/english.ts keeps only the English the browser reads in every language; |
| 7 | +// - every import() of a lazy boundary (a page route, a module only ever loaded with import()) |
| 8 | +// loads the boundary's slice alongside it and resolves once both have arrived, so the boundary's |
| 9 | +// code never runs before its strings (a top-level await in the boundary would do the same, but |
| 10 | +// makes Rolldown split the shared chunks differently); |
| 11 | +// - the server reads where the files went (virtual:i18n-preload) to preload a page's own |
| 12 | +// (src/i18n/preload.ts), so no string costs a round trip before hydration. |
| 13 | +// |
| 14 | +// The development server and the Worker keep the source files whole. |
| 15 | +import path from "node:path" |
| 16 | +import { fileURLToPath } from "node:url" |
| 17 | +import { spawnSync } from "node:child_process" |
| 18 | +import type { Plugin } from "vite" |
| 19 | +import type { result as Result } from "./i18n-slices" |
| 20 | + |
| 21 | +type Slices = typeof Result |
| 22 | + |
| 23 | +// Vite ids use forward slashes on every platform. |
| 24 | +const slashes = (file: string) => file.replaceAll("\\", "/") |
| 25 | +const root = slashes(fileURLToPath(new URL("..", import.meta.url))) |
| 26 | +const runtime = path.posix.join(root, "src/i18n/index.ts") |
| 27 | +const tablesFile = path.posix.join(root, "src/i18n/tables.ts") |
| 28 | +const englishFile = path.posix.join(root, "src/i18n/english.ts") |
| 29 | +// An import() of a module, with any spaces or comments (such as /* @vite-ignore */) inside. |
| 30 | +const dynamicImport = /\bimport\(\s*(?:\/\*[\s\S]*?\*\/\s*)*(["'])([^"'`]+)\1\s*\)/g |
| 31 | + |
| 32 | +export function i18nSlices(): Plugin { |
| 33 | + let build = false |
| 34 | + let slices: Slices | undefined |
| 35 | + // Output file of each virtual module in the client build, by its id. |
| 36 | + const files = new Map<string, string>() |
| 37 | + const client = (environment: { name: string }) => build && environment.name === "client" |
| 38 | + const analyze = () => { |
| 39 | + if (slices) return slices |
| 40 | + const run = spawnSync("bun", ["script/i18n-slices.ts", "--json"], { cwd: root, maxBuffer: 256 * 1024 * 1024 }) |
| 41 | + if (run.status !== 0) throw new Error(`i18n-slices failed:\n${run.stderr}`) |
| 42 | + slices = JSON.parse(run.stdout.toString()) as Slices |
| 43 | + return slices |
| 44 | + } |
| 45 | + const boundary = (id: string) => analyze().boundaries[slashes(id).split("?")[0]] |
| 46 | + const routes = () => Object.keys(analyze().boundaries).filter((file) => file.startsWith(`${root}src/routes/`)) |
| 47 | + // The page routes whose import() in SolidStart's route list loads their slice (checked in generateBundle). |
| 48 | + const routed = new Set<string>() |
| 49 | + |
| 50 | + return { |
| 51 | + name: "i18n-slices", |
| 52 | + enforce: "post", |
| 53 | + configResolved(config) { |
| 54 | + build = config.command === "build" |
| 55 | + }, |
| 56 | + resolveId(id) { |
| 57 | + if (id.startsWith("virtual:i18n")) return `\0${id}` |
| 58 | + }, |
| 59 | + load(id) { |
| 60 | + // Read by the server only; the browser's copy is empty. |
| 61 | + if (id === "\0virtual:i18n-preload") |
| 62 | + return `export default ${JSON.stringify(build && this.environment.name !== "client" ? preloads() : null)}` |
| 63 | + if (!client(this.environment)) return |
| 64 | + const data = analyze() |
| 65 | + if (id === englishFile) return `export const english = ${json(data.english)}` |
| 66 | + if (id === tablesFile) |
| 67 | + return `export const tables = {\n${Object.keys(data.locales) |
| 68 | + .map((locale) => ` ${JSON.stringify(locale)}: () => import("virtual:i18n/${locale}").then((module) => module.default),`) |
| 69 | + .join("\n")}\n}` |
| 70 | + const match = id.match(/^\0virtual:i18n\/(\w+)(?:\/([\w-]+))?$/) |
| 71 | + if (!match) return |
| 72 | + const locale = data.locales[match[1] as keyof Slices["locales"]] |
| 73 | + if (match[2] === "all") return `export default ${json(locale.full)}` |
| 74 | + if (match[2]) return `export default ${json(locale.slices[match[2]])}` |
| 75 | + // The shell's strings are in the table itself, which every page loads anyway; an empty slice |
| 76 | + // has no entry. |
| 77 | + const entries = Object.keys(data.shared).flatMap((slice) => { |
| 78 | + const payload = locale.slices[data.shared[slice]] |
| 79 | + if (slice === "shell") return [` shell: ${json(payload)},`] |
| 80 | + if (!Object.keys(payload.dict).length && !Object.keys(payload.content).length) return [] |
| 81 | + return [` ${JSON.stringify(slice)}: () => import("virtual:i18n/${match[1]}/${data.shared[slice]}"),`] |
| 82 | + }) |
| 83 | + return `export default {\n slices: {\n${entries.join("\n")}\n },\n all: () => import("virtual:i18n/${match[1]}/all"),\n}` |
| 84 | + }, |
| 85 | + async transform(code, id) { |
| 86 | + if (!client(this.environment) || id.startsWith("\0") || slashes(id).includes("/src/i18n/")) return |
| 87 | + const slices = new Map<string, string>() |
| 88 | + for (const match of code.matchAll(dynamicImport)) { |
| 89 | + const target = await this.resolve(match[2], id) |
| 90 | + const slice = target && boundary(target.id) |
| 91 | + if (!target || !slice) continue |
| 92 | + slices.set(match[0], slice) |
| 93 | + if (id === "solid-start:routes") routed.add(slashes(target.id).split("?")[0]) |
| 94 | + } |
| 95 | + if (!slices.size) return |
| 96 | + return { |
| 97 | + code: [ |
| 98 | + `import { loadSlice as __i18nSlice } from ${JSON.stringify(runtime)};`, |
| 99 | + "const __i18nWith = (module, slice) => Promise.all([module, __i18nSlice(slice).catch(() => {})]).then((loaded) => loaded[0]);", |
| 100 | + code.replace(dynamicImport, (text) => (slices.has(text) ? `__i18nWith(${text}, ${JSON.stringify(slices.get(text))})` : text)), |
| 101 | + ].join("\n"), |
| 102 | + map: null, |
| 103 | + } |
| 104 | + }, |
| 105 | + generateBundle(_, bundle) { |
| 106 | + if (!client(this.environment)) return |
| 107 | + // A page route whose import() wasn't rewritten would run before its strings arrive: fail the |
| 108 | + // build instead (a change in how SolidStart writes its route list, for example). |
| 109 | + const missed = routes().filter((file) => !routed.has(file)) |
| 110 | + if (missed.length) |
| 111 | + throw new Error(`i18n-slices: SolidStart's route list doesn't load the strings of ${missed.join(", ")}`) |
| 112 | + for (const chunk of Object.values(bundle)) |
| 113 | + if (chunk.type === "chunk" && chunk.facadeModuleId?.startsWith("\0virtual:i18n/")) |
| 114 | + files.set(chunk.facadeModuleId.slice(1), `/${chunk.fileName}`) |
| 115 | + }, |
| 116 | + } |
| 117 | + |
| 118 | + /** For each locale, the files a page in it loads before hydration: its table (with the shell's strings) and its route's slice. */ |
| 119 | + function preloads() { |
| 120 | + const data = analyze() |
| 121 | + const src = `${root}src/` |
| 122 | + return Object.fromEntries( |
| 123 | + Object.keys(data.locales).map((locale) => [ |
| 124 | + locale, |
| 125 | + { |
| 126 | + table: files.get(`virtual:i18n/${locale}`), |
| 127 | + routes: Object.fromEntries( |
| 128 | + Object.entries(data.boundaries) |
| 129 | + .filter(([file]) => file.startsWith(`${src}routes/`)) |
| 130 | + .map(([file, slice]) => [ |
| 131 | + file.slice(src.length), |
| 132 | + files.get(`virtual:i18n/${locale}/${data.shared[slice]}`) ?? null, |
| 133 | + ]), |
| 134 | + ), |
| 135 | + }, |
| 136 | + ]), |
| 137 | + ) |
| 138 | + } |
| 139 | +} |
| 140 | + |
| 141 | +/** Strings as one JSON.parse call: compact whether or not the build minifies, and quick to parse. */ |
| 142 | +function json(value: unknown) { |
| 143 | + return `JSON.parse('${JSON.stringify(value).replace(/\\/g, "\\\\").replace(/'/g, "\\'")}')` |
| 144 | +} |
0 commit comments