post-build-global.mts 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. import { access, constants as fsconstants, readFile, writeFile } from "node:fs/promises";
  2. import { resolve } from "node:path";
  3. import pkg from "../package.json" with { type: "json" };
  4. const { exit } = process;
  5. /** Path to the global / IIFE bundle built by tsup */
  6. const iifeBundlePath = resolve("dist/index.global.js");
  7. async function run() {
  8. if(!await exists(iifeBundlePath)) {
  9. console.error(`No global script found at path '${iifeBundlePath}'`);
  10. setImmediate(() => exit(1));
  11. return;
  12. }
  13. const libHeader = `\
  14. // ==UserScript==
  15. // @namespace ${pkg.homepage}
  16. // @exclude *
  17. // @author ${pkg.author.name}
  18. // @supportURL ${pkg.bugs.url}
  19. // @homepageURL ${pkg.homepage}
  20. // ==UserLibrary==
  21. // @name ${pkg.libName}
  22. // @description ${pkg.description}
  23. // @version ${pkg.version}
  24. // @license ${pkg.license}
  25. // @copyright ${pkg.author.name} (${pkg.author.url})
  26. // ==/UserScript==
  27. // ==/UserLibrary==
  28. // ==OpenUserJS==
  29. // @author Sv443
  30. // ==/OpenUserJS==
  31. `;
  32. const initialBundle = await readFile(iifeBundlePath, "utf8");
  33. const finalBundle = `${libHeader}\nvar UserUtils = ${initialBundle}`
  34. .replace(/^\s*'use strict';\s*(\r?\n){1,2}/gm, "");
  35. await writeFile(iifeBundlePath, finalBundle, "utf8");
  36. console.log(`\x1b[32mGlobal bundle at path \x1b[0m'${iifeBundlePath}'\x1b[32m has been updated\x1b[0m`);
  37. setImmediate(() => exit(0));
  38. }
  39. /** Checks if a path exists / is readable and writable (by default) */
  40. async function exists(path: string, mode = fsconstants.R_OK | fsconstants.W_OK) {
  41. try {
  42. await access(path, mode);
  43. return true;
  44. }
  45. catch(err) {
  46. return false;
  47. }
  48. }
  49. run();