Selaa lähdekoodia

feat: implement kleur instead of raw ansi codes

Sv443 5 kuukautta sitten
vanhempi
commit
80389719c9

+ 2 - 0
package.json

@@ -20,6 +20,7 @@
     "build-prod-gf": "pnpm run build-prod-base --config-host greasyfork --config-suffix _gf",
     "build-prod-oujs": "pnpm run build-prod-base --config-host openuserjs --config-suffix _oujs",
     "post-build": "pnpm run node-ts ./src/tools/post-build.ts",
+    "tr-changed": "pnpm run node-ts ./src/tools/tr-changed.ts",
     "tr-progress": "pnpm run node-ts ./src/tools/tr-progress.ts",
     "tr-format": "pnpm run node-ts ./src/tools/tr-format.ts",
     "tr-prep": "pnpm run tr-format -p",
@@ -98,6 +99,7 @@
     "eslint-plugin-storybook": "^0.11.0",
     "express": "^4.19.2",
     "globals": "^15.6.0",
+    "kleur": "^4.1.5",
     "knip": "^5.22.2",
     "nanoevents": "^9.0.0",
     "nodemon": "^3.1.4",

+ 9 - 0
pnpm-lock.yaml

@@ -105,6 +105,9 @@ importers:
       globals:
         specifier: ^15.6.0
         version: 15.6.0
+      kleur:
+        specifier: ^4.1.5
+        version: 4.1.5
       knip:
         specifier: ^5.22.2
         version: 5.22.2(@types/[email protected])([email protected])
@@ -3413,6 +3416,10 @@ packages:
     resolution: {integrity: sha512-eTIzlVOSUR+JxdDFepEYcBMtZ9Qqdef+rnzWdRZuMbOywu5tO2w2N7rqjoANZ5k9vywhL6Br1VRjUIgTQx4E8w==}
     engines: {node: '>=6'}
 
+  [email protected]:
+    resolution: {integrity: sha512-o+NO+8WrRiQEE4/7nwRJhN1HWpVmJm511pBHUxPLtp0BUISzlBplORYSmTclCnJvQq2tKu/sgl3xVpkc7ZWuQQ==}
+    engines: {node: '>=6'}
+
   [email protected]:
     resolution: {integrity: sha512-eMEnuLOkLN5wn1Os9v0cujZQAhcZ8dYZ23ZsVizfWaaeIx9/s8PaaW4HlbnePQ+ci463X61/+CboGSkmmB8OZA==}
     engines: {node: '>=18.6.0'}
@@ -8639,6 +8646,8 @@ snapshots:
 
   [email protected]: {}
 
+  [email protected]: {}
+
   [email protected](@types/[email protected])([email protected]):
     dependencies:
       '@ericcornelissen/bash-parser': 0.5.3

+ 2 - 2
rollup.config.mjs

@@ -4,7 +4,7 @@ import pluginJson from "@rollup/plugin-json";
 import pluginCss from "rollup-plugin-import-css";
 import pluginExecute from "rollup-plugin-execute";
 import typescript from "typescript";
-
+import k from "kleur";
 import "dotenv/config";
 import requireJson from "./assets/require.json" with { type: "json" };
 
@@ -68,7 +68,7 @@ export default (/**@type {import("./src/types.js").RollupArgs}*/ args) => (async
       // ignore circular dependency warnings
       if(warning.code !== "CIRCULAR_DEPENDENCY") {
         const { message, ...rest } = warning;
-        console.error(`\x1b[33m(!)\x1b[0m ${message}\n`, rest);
+        console.error(`${k.yellow("(!)")} ${message}\n`, rest);
       }
     },
     external: externalPkgs,

+ 2 - 1
src/tools/gen-readme.ts

@@ -1,6 +1,7 @@
 import { readFile, writeFile } from "node:fs/promises";
 import { join } from "node:path";
 import { fileURLToPath } from "node:url";
+import k from "kleur";
 import type { PluginDef } from "../types.js";
 import locales from "../../assets/locales.json" with { type: "json" };
 import pluginsJson from "../../assets/plugins.json" with { type: "json" };
@@ -46,7 +47,7 @@ async function run() {
     await writeFile(path, result);
   }
 
-  console.log("\n\x1b[32mReadme files generated successfully\x1b[0m\n");
+  console.log(k.green("\nReadme files generated successfully\n"));
 
   setImmediate(() => process.exit(0));
 }

+ 14 - 12
src/tools/post-build.ts

@@ -2,6 +2,7 @@ import { access, readFile, writeFile, constants as fsconst } from "node:fs/promi
 import { dirname, join, relative, resolve } from "node:path";
 import { fileURLToPath } from "node:url";
 import { exec } from "node:child_process";
+import k from "kleur";
 import "dotenv/config";
 import { outputDir as rollupCfgOutputDir, outputFile as rollupCfgOutputFile } from "../../rollup.config.mjs";
 import locales from "../../assets/locales.json" with { type: "json" };
@@ -157,7 +158,7 @@ I welcome every contribution on GitHub!
     await writeFile(scriptPath, finalUserscript);
     ringBell && stdout.write("\u0007");
 
-    const envText = `${mode === "production" ? "\x1b[32m" : "\x1b[33m"}${mode}`;
+    const envText = (mode === "production" ? k.magenta : k.blue)(mode);
     const sizeKiB = Number((Buffer.byteLength(finalUserscript, "utf8") / 1024).toFixed(2));
 
     let buildStats: Partial<BuildStats>[] = [];
@@ -177,15 +178,18 @@ I welcome every contribution on GitHub!
     if(prevBuildStats?.sizeKiB) {
       const sizeDiff = sizeKiB - prevBuildStats.sizeKiB;
       const sizeDiffTrunc = parseFloat(sizeDiff.toFixed(2));
-      if(sizeDiffTrunc !== 0)
-        sizeIndicator = " \x1b[2m(\x1b[0m\x1b[1m" + (sizeDiff > 0 ? "\x1b[33m+" : (sizeDiff !== 0 ? "\x1b[32m-" : "\x1b[32m")) + Math.abs(sizeDiffTrunc) + "\x1b[0m\x1b[2m)\x1b[0m";
+      if(sizeDiffTrunc !== 0) {
+        const sizeDiffCol = (sizeDiff > 0 ? k.yellow : k.green)().bold;
+        const sizeDiffNum = `${(sizeDiff > 0 ? "+" : (sizeDiff !== 0 ? "-" : ""))}${Math.abs(sizeDiffTrunc)}`;
+        sizeIndicator = ` ${k.gray("(")}${sizeDiffCol(sizeDiffNum)}${k.gray(")")}`;
+      }
     }
 
     console.info([
       "",
-      `Successfully built for ${envText}\x1b[0m - build number (last commit SHA): ${buildNbr}`,
-      `Outputted file '${relative("./", scriptPath)}' with a size of \x1b[32m${sizeKiB} KiB\x1b[0m${sizeIndicator}`,
-      `Userscript URL: \x1b[34m\x1b[4m${devServerUserscriptUrl}\x1b[0m`,
+      `Successfully built for ${envText} - build number (last commit SHA): ${buildNbr}`,
+      `Outputted file '${relative("./", scriptPath)}' with a size of ${k.green(`${sizeKiB} KiB`)}${sizeIndicator}`,
+      `Userscript URL: ${k.blue().underline(devServerUserscriptUrl)}`,
       "",
     ].join("\n"));
 
@@ -205,9 +209,7 @@ I welcome every contribution on GitHub!
     schedExit(0);
   }
   catch(err) {
-    console.error("\x1b[31mError while adding userscript header:\x1b[0m");
-    console.error(err);
-
+    console.error(k.red("Error while adding userscript header:\n"), err);
     schedExit(1);
   }
 })();
@@ -233,7 +235,7 @@ function getLastCommitSha() {
   return new Promise<string>((res, rej) => {
     exec("git rev-parse --short HEAD", (err, stdout, stderr) => {
       if(err) {
-        console.error("\x1b[31mError while checking for last Git commit. Do you have Git installed?\x1b[0m\n", stderr);
+        console.error(k.red("Error while checking for last Git commit. Do you have Git installed?\n"), stderr);
         return rej(err);
       }
       return res(String(stdout).replace(/\r?\n/gm, "").trim());
@@ -295,7 +297,7 @@ async function getResourceDirectives(ref: string) {
         resourcesHashed[name] = { path: getResourceUrl(path, ref), ref, hash: await getFileHashSha256(path) };
       }
       catch(err) {
-        console.error(`\x1b[31mCouldn't add hashed resource '${name}':\x1b[0m`, err);
+        console.warn(k.yellow(`Couldn't add hashed resource '${name}':`), err);
       }
     };
 
@@ -380,7 +382,7 @@ function getLocalizedDescriptions() {
     return descriptions.join("\n") + "\n";
   }
   catch(err) {
-    console.warn("\x1b[33mNo localized descriptions found:\x1b[0m", err);
+    console.warn(k.yellow("No localized descriptions found:"), err);
   }
 }
 

+ 3 - 2
src/tools/run-invisible.mjs

@@ -1,12 +1,13 @@
 import { exec } from "node:child_process";
+import k from "kleur";
 
 (() => {
   const command = process.argv.slice(2).join(" ");
   const child = exec(command, (error, _stdout, _stderr) => {
     if(error)
-      console.error("\x1b[31m[run-invisible error]\x1b[0m", error);
+      console.error(k.red("[run-invisible error]:"), error);
     // #DEBUG
-    // console.log("[run-invisible debug] out:", _stdout ?? "undefined", "err:", _stderr ?? "undefined");
+    // console.log(k.cyan("[run-invisible debug]:"), "out:", _stdout ?? "undefined", "err:", _stderr ?? "undefined");
   });
   child.on("exit", (code, signal) => {
     if(code !== null)

+ 5 - 4
src/tools/serve.ts

@@ -1,9 +1,10 @@
 import { resolve } from "node:path";
 import { fileURLToPath } from "node:url";
+import type { Server } from "node:http";
 import express, { NextFunction, Request, Response } from "express";
+import k from "kleur";
 import "dotenv/config";
 import { outputDir } from "../../rollup.config.mjs";
-import type { Server } from "node:http";
 
 const { argv, env, exit, stdout } = process;
 
@@ -28,7 +29,7 @@ enableLogging && app.use((_req, _res, next) => {
 
 app.use((err: unknown, _req: Request, _res: Response, _next: NextFunction) => {
   if(typeof err === "string" || err instanceof Error)
-    console.error("\x1b[31mError in dev server:\x1b[0m\n", err);
+    console.error(k.red("Error in dev server:\n"), err);
 });
 
 app.use("/", express.static(
@@ -58,7 +59,7 @@ try {
     if(enableLogging)
       stdout.write("\nRequests: ");
     else
-      console.log("\x1b[2m(request logging is disabled)\x1b[0m");
+      console.log(k.gray("(request logging is disabled)"));
     console.log();
 
     if(autoExitTime) {
@@ -68,6 +69,6 @@ try {
   });
 }
 catch(err) {
-  console.error("\x1b[31mError starting dev server:\x1b[0m", err);
+  console.error(k.red("Error starting dev server:"), err);
   closeAndExit(1);
 }

+ 2 - 1
src/tools/tr-format.ts

@@ -1,4 +1,5 @@
 import { readFile, writeFile } from "node:fs/promises";
+import k from "kleur";
 import type { TrLocale } from "../utils/index.js";
 import locales from "../../assets/locales.json" with { type: "json" };
 
@@ -77,7 +78,7 @@ async function run() {
 
     reformattedAmt++;
   }
-  console.log(`\nDone reformatting \x1b[32m${reformattedAmt}\x1b[0m translation file${reformattedAmt === 1 ? "" : "s"}!\n`);
+  console.log(`\nDone reformatting ${k.green(reformattedAmt)} translation file${reformattedAmt === 1 ? "" : "s"}!\n`);
 }
 
 /** Escapes various characters for use as a JSON value */

+ 3 - 2
src/tools/tr-progress.ts

@@ -1,6 +1,7 @@
 import { readFile, writeFile } from "node:fs/promises";
 import { join, relative, resolve } from "node:path";
 import { fileURLToPath } from "node:url";
+import k from "kleur";
 import type { TrLocale } from "../utils/index.js";
 import locales from "../../assets/locales.json" with { type: "json" };
 
@@ -15,7 +16,7 @@ interface TrFile {
 }
 
 async function run() {
-  console.log("\n\x1b[34mUpdating translation progress...\x1b[0m\n");
+  console.log(k.blue("\nUpdating translation progress...\n"));
 
   //#region parse
 
@@ -119,7 +120,7 @@ ${lines.join("\n")}\n
     .replace(/<!--#{{TR_MISSING_KEYS}}-->/m, missingKeys.length > 0 ? missingKeys.join("\n") : "No missing keys");
   await writeFile(join(trDir, "README.md"), readmeCont);
 
-  console.log(`\n\x1b[32mFinished updating translation progress\x1b[0m - updated file at '${relative(rootDir, join(trDir, "README.md"))}'\n`);
+  console.log(`\n${k.green("Finished updating translation progress")} - updated file at '${relative(rootDir, join(trDir, "README.md"))}'\n`);
 
   setImmediate(() => exit(0));
 }