post-build-global.mts 1.7 KB

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