|
| 1 | +import { Plugin } from "vite"; |
| 2 | +import { readdirSync, readFileSync } from "fs"; |
| 3 | +import { TextEncoder } from "util"; |
| 4 | +import { createHash } from "crypto"; |
| 5 | + |
| 6 | +const virtualModuleId = "virtual:language-hashes"; |
| 7 | +const resolvedVirtualModuleId = "\0" + virtualModuleId; |
| 8 | +let skip = false; |
| 9 | + |
| 10 | +export function languageHashes(): Plugin { |
| 11 | + return { |
| 12 | + name: "virtual-language-hashes", |
| 13 | + resolveId(id) { |
| 14 | + if (id === virtualModuleId) return resolvedVirtualModuleId; |
| 15 | + return; |
| 16 | + }, |
| 17 | + load(id) { |
| 18 | + if (id === resolvedVirtualModuleId) { |
| 19 | + const hashes: Record<string, string> = skip ? {} : getHashes(); |
| 20 | + return ` |
| 21 | + export const languageHashes = ${JSON.stringify(hashes)}; |
| 22 | + `; |
| 23 | + } |
| 24 | + return; |
| 25 | + }, |
| 26 | + configResolved(resolvedConfig) { |
| 27 | + if (resolvedConfig?.define?.["IS_DEVELOPMENT"] === "true") { |
| 28 | + skip = true; |
| 29 | + console.log("Skipping language hashing in dev environment."); |
| 30 | + } |
| 31 | + }, |
| 32 | + }; |
| 33 | +} |
| 34 | + |
| 35 | +function getHashes(): Record<string, string> { |
| 36 | + const start = performance.now(); |
| 37 | + |
| 38 | + console.log("\nHashing languages..."); |
| 39 | + |
| 40 | + const hashes = Object.fromEntries( |
| 41 | + readdirSync("./static/languages").map((file) => { |
| 42 | + return [file.slice(0, -5), calcHash(file)]; |
| 43 | + }) |
| 44 | + ); |
| 45 | + |
| 46 | + const end = performance.now(); |
| 47 | + |
| 48 | + console.log(`Creating language hashes took ${Math.round(end - start)} ms`); |
| 49 | + |
| 50 | + return hashes; |
| 51 | +} |
| 52 | + |
| 53 | +function calcHash(file: string): string { |
| 54 | + const currentLanguage = JSON.stringify( |
| 55 | + JSON.parse(readFileSync("./static/languages/" + file).toString()), |
| 56 | + null, |
| 57 | + 0 |
| 58 | + ); |
| 59 | + const encoder = new TextEncoder(); |
| 60 | + const data = encoder.encode(currentLanguage); |
| 61 | + return createHash("sha256").update(data).digest("hex"); |
| 62 | +} |
| 63 | + |
| 64 | +if (import.meta.url.endsWith(process.argv[1] as string)) { |
| 65 | + console.log(JSON.stringify(getHashes(), null, 4)); |
| 66 | +} |
0 commit comments