wad-finder.ts 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. import { existsSync, writeFileSync } from "node:fs";
  2. import { dirname, join, resolve } from "node:path";
  3. import { fileURLToPath } from "node:url";
  4. // Get the bundled WAD path (relative to this module)
  5. const __dirname = dirname(fileURLToPath(import.meta.url));
  6. const BUNDLED_WAD = join(__dirname, "doom1.wad");
  7. const WAD_URL = "https://distro.ibiblio.org/slitaz/sources/packages/d/doom1.wad";
  8. const DEFAULT_WAD_PATHS = ["./doom1.wad", "./DOOM1.WAD", "~/doom1.wad", "~/.doom/doom1.wad"];
  9. export function findWadFile(customPath?: string): string | null {
  10. if (customPath) {
  11. const resolved = resolve(customPath.replace(/^~/, process.env.HOME || ""));
  12. if (existsSync(resolved)) return resolved;
  13. return null;
  14. }
  15. // Check bundled WAD first
  16. if (existsSync(BUNDLED_WAD)) {
  17. return BUNDLED_WAD;
  18. }
  19. // Fall back to default paths
  20. for (const p of DEFAULT_WAD_PATHS) {
  21. const resolved = resolve(p.replace(/^~/, process.env.HOME || ""));
  22. if (existsSync(resolved)) return resolved;
  23. }
  24. return null;
  25. }
  26. /** Download the shareware WAD if not present. Returns path or null on failure. */
  27. export async function ensureWadFile(): Promise<string | null> {
  28. // Check if already exists
  29. const existing = findWadFile();
  30. if (existing) return existing;
  31. // Download to bundled location
  32. try {
  33. const response = await fetch(WAD_URL);
  34. if (!response.ok) {
  35. throw new Error(`HTTP ${response.status}`);
  36. }
  37. const buffer = await response.arrayBuffer();
  38. writeFileSync(BUNDLED_WAD, Buffer.from(buffer));
  39. return BUNDLED_WAD;
  40. } catch {
  41. return null;
  42. }
  43. }