|
| 1 | +import { Plugin } from "vite"; |
| 2 | +import { loadEnv } from "vite"; |
| 3 | +import path from "node:path"; |
| 4 | +import fs from "node:fs/promises"; |
| 5 | +import { isReadable } from "./isReadable"; |
| 6 | + |
| 7 | +export function mud(opts: { worldsFile: string }): Plugin { |
| 8 | + const rootDir = process.cwd(); |
| 9 | + const worldsFile = path.resolve(rootDir, opts.worldsFile); |
| 10 | + |
| 11 | + return { |
| 12 | + name: "vite-plugin-mud", |
| 13 | + async config(config, { mode }) { |
| 14 | + const env = Object.assign({}, process.env, loadEnv(mode, rootDir)); |
| 15 | + const chainId = Number(env.VITE_CHAIN_ID) || 31337; |
| 16 | + |
| 17 | + config.define ??= {}; |
| 18 | + config.define["import.meta.env.CHAIN_ID"] = chainId; |
| 19 | + |
| 20 | + if (!(await isReadable(worldsFile))) { |
| 21 | + console.log("no worlds file"); |
| 22 | + return; |
| 23 | + } |
| 24 | + |
| 25 | + const worlds = JSON.parse(await fs.readFile(worldsFile, "utf-8")) as Partial< |
| 26 | + Record<string, { address: `0x${string}`; blockNumber?: number }> |
| 27 | + >; |
| 28 | + |
| 29 | + const world = worlds[chainId]; |
| 30 | + if (world) { |
| 31 | + config.define["import.meta.env.WORLD_ADDRESS"] = JSON.stringify(world.address); |
| 32 | + config.define["import.meta.env.START_BLOCK"] = world.blockNumber != null ? `${world.blockNumber}n` : undefined; |
| 33 | + } else { |
| 34 | + console.log("no world deploy for chain ID", chainId); |
| 35 | + } |
| 36 | + }, |
| 37 | + configureServer(server) { |
| 38 | + server.watcher.add(worldsFile); |
| 39 | + |
| 40 | + server.watcher.on("add", handleFileChange); |
| 41 | + server.watcher.on("change", handleFileChange); |
| 42 | + server.watcher.on("unlink", handleFileChange); |
| 43 | + |
| 44 | + // Wrap server restart in a delay to "debounce" so we |
| 45 | + // only restart once after all file change emissions complete. |
| 46 | + let timer: ReturnType<typeof setTimeout> | undefined; |
| 47 | + function restart() { |
| 48 | + clearTimeout(timer); |
| 49 | + timer = setTimeout(() => server.restart(), 500); |
| 50 | + } |
| 51 | + |
| 52 | + function handleFileChange(filename: string) { |
| 53 | + // TODO: check if this works on windows, as paths may have different separators |
| 54 | + if (filename === worldsFile) { |
| 55 | + restart(); |
| 56 | + } |
| 57 | + } |
| 58 | + }, |
| 59 | + }; |
| 60 | +} |
0 commit comments