patch-wasm.ts 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. #!/usr/bin/env bun
  2. import fs from "fs"
  3. import path from "path"
  4. /**
  5. * Rewrite tree-sitter wasm references inside a JS file to absolute paths.
  6. * argv: [node, script, file, mainWasm, ...wasmPaths]
  7. */
  8. const [, , file, mainWasm, ...wasmPaths] = process.argv
  9. if (!file || !mainWasm) {
  10. console.error("usage: patch-wasm <file> <mainWasm> [wasmPaths...]")
  11. process.exit(1)
  12. }
  13. const content = fs.readFileSync(file, "utf8")
  14. const byName = new Map<string, string>()
  15. for (const wasm of wasmPaths) {
  16. const name = path.basename(wasm)
  17. byName.set(name, wasm)
  18. }
  19. let next = content
  20. for (const [name, wasmPath] of byName) {
  21. next = next.replaceAll(name, wasmPath)
  22. }
  23. next = next.replaceAll("tree-sitter.wasm", mainWasm).replaceAll("web-tree-sitter/tree-sitter.wasm", mainWasm)
  24. // Collapse any relative prefixes before absolute store paths (e.g., "../../../..//nix/store/...")
  25. const nixStorePrefix = process.env.NIX_STORE || "/nix/store"
  26. next = next.replace(/(\.\/)+/g, "./")
  27. next = next.replace(
  28. new RegExp(`(\\.\\.\\/)+\\/{1,2}(${nixStorePrefix.replace(/^\//, "").replace(/\//g, "\\/")}[^"']+)`, "g"),
  29. "/$2",
  30. )
  31. next = next.replace(new RegExp(`(["'])\\/{2,}(\\/${nixStorePrefix.replace(/\//g, "\\/")}[^"']+)(["'])`, "g"), "$1$2$3")
  32. next = next.replace(new RegExp(`(["'])\\/\\/(${nixStorePrefix.replace(/\//g, "\\/")}[^"']+)(["'])`, "g"), "$1$2$3")
  33. if (next !== content) fs.writeFileSync(file, next)