Explorar o código

feat: added jsdelivr as new default asset source

Sv443 hai 3 meses
pai
achega
43c1e10d53
Modificáronse 7 ficheiros con 59 adicións e 34 borrados
  1. 2 6
      assets/resources.json
  2. 3 3
      contributing.md
  3. 1 1
      rollup.config.mjs
  4. 20 10
      src/constants.ts
  5. 11 3
      src/tools/post-build.ts
  6. 1 1
      src/types.ts
  7. 21 10
      src/utils/misc.ts

+ 2 - 6
assets/resources.json

@@ -12,14 +12,10 @@
     "css-hide_themesong_logo": "style/hideThemeSongLogo.css",
     "css-show_votes": "style/showVotes.css",
     "css-vol_slider_size": "style/volSliderSize.css",
-    "doc-changelog": {
-      "path": "/changelog.md",
-      "ref": "main",
-      "integrity": false
-    },
     "doc-license": {
       "path": "/LICENSE.txt",
-      "ref": "$BRANCH"
+      "ref": "$BRANCH",
+      "integrity": false
     },
     "font-cousine_ttf": "fonts/Cousine/Cousine-Regular.ttf",
     "font-cousine_woff": "fonts/Cousine/Cousine-Regular.woff",

+ 3 - 3
contributing.md

@@ -118,14 +118,14 @@ To edit an existing translation, please follow these steps:
   - `--config-mode=<value>` - The mode to build in. Can be either `production` or `development` (default)
   - `--config-branch=<value>` - The GitHub branch to target. Can be any branch name, but should be `main` for production and `develop` for development (default)
   - `--config-host=<value>` - The host to build for. Can be either `github` (default), `greasyfork` or `openuserjs`
-  - `--config-assetSource=<value>` - Where to get the resource files from. Can be either `local` or `github` (default)
+  - `--config-assetSource=<value>` - Where to get the resource files from. Can be either `local`, `jsdelivr` (default) or `github`
   - `--config-suffix=<value>` - Suffix to add just before the `.user.js` extension. Defaults to an empty string
     
   Shorthand commands:
   - `pnpm run build-prod-base` - Used for building for production, targets the main branch and the public asset source.  
-    Sets `--config-mode=production` and `--config-branch=main` and `--config-assetSource=github`
+    Sets `--config-mode=production` and `--config-branch=main` and `--config-assetSource=jsdelivr`
   - `pnpm run build-dev` - Builds a preview version, targeting the develop branch and the public asset source so no local dev environment is needed.  
-    Sets `--config-mode=development`, `--config-branch=develop` and `--config-assetSource=github`
+    Sets `--config-mode=development`, `--config-branch=develop` and `--config-assetSource=jsdelivr`
   - `pnpm run preview` - Same as `pnpm run build-prod`, but sets `--config-host=github` and `--config-assetSource=local`, then starts the dev server for a few seconds so the extension that's waiting for file changes can update the script and assets
 - **`pnpm run lint`**  
   Builds the userscript with the TypeScript compiler and lints it with ESLint. Doesn't verify the functionality of the script, only checks for syntax and TypeScript errors!

+ 1 - 1
rollup.config.mjs

@@ -28,7 +28,7 @@ export default (/**@type {import("./src/types.js").RollupArgs}*/ args) => (async
     mode: args["config-mode"] ?? (process.env.NODE_ENV === "production" ? "production" : "development"),
     branch: args["config-branch"] ?? "develop",
     host: args["config-host"] ?? "github",
-    assetSource: args["config-assetSource"] ?? "github",
+    assetSource: args["config-assetSource"] ?? "jsdelivr",
     suffix: args["config-suffix"] ?? "",
   };
   const passCliArgsStr = Object.entries(passCliArgs).map(([key, value]) => `--${key}=${value}`).join(" ");

+ 20 - 10
src/constants.ts

@@ -1,27 +1,37 @@
 import { randomId } from "@sv443-network/userutils";
 import { LogLevel } from "./types.js";
 
-// these variables will have their values replaced by the build script:
+// these strings will have their values replaced by the post-build script:
 const modeRaw = "#{{MODE}}";
 const branchRaw = "#{{BRANCH}}";
 const hostRaw = "#{{HOST}}";
 const buildNumberRaw  = "#{{BUILD_NUMBER}}";
+const assetSourceRaw  = "#{{ASSET_SOURCE}}";
+const devServerPortRaw  = "#{{DEV_SERVER_PORT}}";
+
+const getRawVal = <T extends string | number>(rawVal: string, defaultVal: T) =>
+  (rawVal.match(/^#{{.+}}$/) ? defaultVal : rawVal) as T;
 
-/** The mode in which the script was built (production or development) */
-export const mode = (modeRaw.match(/^#{{.+}}$/) ? "production" : modeRaw) as "production" | "development";
-/** The branch to use in various URLs that point to the GitHub repo */
-export const branch = (branchRaw.match(/^#{{.+}}$/) ? "main" : branchRaw) as "main" | "develop";
 /** Path to the GitHub repo */
 export const repo = "Sv443/BetterYTM";
+/** The mode in which the script was built (production or development) */
+export const mode = getRawVal<"production" | "development">(modeRaw, "production");
+/** The branch to use in various URLs that point to the GitHub repo */
+export const branch = getRawVal<"main" | "develop">(branchRaw, "main");
 /** Which host the userscript was installed from */
-export const host = (hostRaw.match(/^#{{.+}}$/) ? "github" : hostRaw) as "github" | "greasyfork" | "openuserjs";
+export const host = getRawVal<"github" | "greasyfork" | "openuserjs">(hostRaw, "github");
 /** The build number of the userscript */
-export const buildNumber = (buildNumberRaw.match(/^#{{.+}}$/) ? "BUILD_ERROR!" : buildNumberRaw) as string; // asserted as generic string instead of literal
+export const buildNumber = getRawVal<string>(buildNumberRaw, "BUILD_ERROR!");
+/** The source of the assets - github, jsdelivr or local */
+export const assetSource = getRawVal<"github" | "jsdelivr" | "local">(assetSourceRaw, "jsdelivr");
+/** The port of the dev server */
+export const devServerPort = Number(getRawVal<number>(devServerPortRaw, 8710));
 
-export const changelogUrl = `https://raw.githubusercontent.com/${repo}/${branch}/changelog.md`;
+/** URL to the changelog file */
+export const changelogUrl = `https://raw.githubusercontent.com/${repo}/${buildNumber??branch}/changelog.md`;
 
 /** The URL search parameters at the earliest possible time */
-export const initialParams = new URL(location.href).searchParams;
+export const initialParams = Object.assign({}, new URL(location.href).searchParams);
 
 /** Names of platforms by key of {@linkcode host} */
 export const platformNames = {
@@ -38,7 +48,7 @@ export const sessionStorageAvailable =
   typeof sessionStorage?.setItem === "function"
   && (() => {
     try {
-      const key = `_bytm_test_${randomId(6, 36)}`;
+      const key = `_bytm_test_${randomId(6, 36, false, true)}`;
       sessionStorage.setItem(key, "test");
       sessionStorage.removeItem(key);
       return true;

+ 11 - 3
src/tools/post-build.ts

@@ -43,7 +43,7 @@ type CliArg<TName extends keyof Required<RollupArgs>> = Required<RollupArgs>[TNa
 const mode = getCliArg<CliArg<"config-mode">>("mode", "development");
 const branch = getCliArg<CliArg<"config-branch">>("branch", (mode === "production" ? "main" : "develop"));
 const host = getCliArg<CliArg<"config-host">>("host", "github");
-const assetSource = getCliArg<CliArg<"config-assetSource">>("assetSource", "github");
+const assetSource = getCliArg<CliArg<"config-assetSource">>("assetSource", "jsdelivr");
 const suffix = getCliArg<CliArg<"config-suffix">>("suffix", "");
 
 const envPort = Number(env.DEV_SERVER_PORT);
@@ -145,6 +145,8 @@ I welcome every contribution on GitHub!
         BRANCH: branch,
         HOST: host,
         BUILD_NUMBER: buildNbr,
+        ASSET_SOURCE: assetSource,
+        DEV_SERVER_PORT: devServerPort,
       },
     );
 
@@ -411,9 +413,15 @@ function getResourceUrl(path: string, ghRef?: string) {
   let assetPath = "/assets/";
   if(path.startsWith("/"))
     assetPath = "";
+  assetPath += path;
+  const finalPath = `${ghRef ?? `v${pkg.version}`}${assetPath}`;
   return assetSource === "local"
-    ? `http://localhost:${devServerPort}${assetPath}${path}?b=${buildUid}`
-    : `https://raw.githubusercontent.com/${repo}/${ghRef ?? `v${pkg.version}`}${assetPath}${path}`;
+    ? `http://localhost:${devServerPort}${assetPath}?b=${buildUid}`
+    : (
+      assetSource === "github"
+        ? `https://raw.githubusercontent.com/${repo}/${finalPath}`
+        : `https://cdn.jsdelivr.net/gh/${repo}@${finalPath}`
+    );
 }
 
 /**

+ 1 - 1
src/types.ts

@@ -19,7 +19,7 @@ export type RollupArgs = Partial<{
   "config-mode": "development" | "production";
   "config-branch": "main" | "develop";
   "config-host": "greasyfork" | "github" | "openuserjs";
-  "config-assetSource": "local" | "github";
+  "config-assetSource": "local" | "github" | "jsdelivr";
   "config-suffix": string;
 }>;
 

+ 21 - 10
src/utils/misc.ts

@@ -1,6 +1,6 @@
 import { compress, decompress, fetchAdvanced, getUnsafeWindow, openInNewTab, pauseFor, randomId, randRange, type Prettify } from "@sv443-network/userutils";
 import { marked } from "marked";
-import { buildNumber, changelogUrl, compressionFormat, repo, sessionStorageAvailable } from "../constants.js";
+import { assetSource, buildNumber, changelogUrl, compressionFormat, devServerPort, repo, sessionStorageAvailable } from "../constants.js";
 import { type Domain, type NumberLengthFormat, type ResourceKey } from "../types.js";
 import { error, type TrLocale, warn, sendRequest, getLocale, log, getVideoElement, getVideoTime } from "./index.js";
 import { enableDiscardBeforeUnload } from "../features/behavior.js";
@@ -257,15 +257,26 @@ export async function getResourceUrl(name: ResourceKey | "_", uncached = false)
     const resObjOrStr = resourcesJson.resources?.[name as keyof typeof resourcesJson.resources];
 
     if(typeof resObjOrStr === "object" || typeof resObjOrStr === "string") {
-      const pathName = typeof resObjOrStr === "object" && "path" in resObjOrStr ? resObjOrStr.path : resObjOrStr;
-      const ghRef = typeof resObjOrStr === "object" && "ref" in resObjOrStr ? resObjOrStr.ref : buildNumber;
-
-      if((pathName?.startsWith("/") && pathName.length > 1))
-        return `https://raw.githubusercontent.com/${repo}/${ghRef}${pathName}`;
-      else if(pathName && pathName.startsWith("http"))
-        return pathName;
-      else if(pathName && pathName.length > 0)
-        return `https://raw.githubusercontent.com/${repo}/${ghRef}/assets/${pathName}`;
+      const pathName = typeof resObjOrStr === "object" && "path" in resObjOrStr ? resObjOrStr?.path : resObjOrStr;
+      const ghRef = typeof resObjOrStr === "object" && "ref" in resObjOrStr ? resObjOrStr?.ref : buildNumber;
+
+      if(pathName) {
+        return pathName.startsWith("http")
+          ? pathName
+          : (() => {
+            let path = pathName;
+            if(path.startsWith("/"))
+              path = path.slice(1);
+            switch(assetSource) {
+            case "jsdelivr":
+              return `https://cdn.jsdelivr.net/gh/${repo}@${ghRef}/assets/${path}`;
+            case "github":
+              return `https://raw.githubusercontent.com/${repo}/${ghRef}/assets/${path}`;
+            case "local":
+              return `http://localhost:${devServerPort}/assets/${path}`;
+            }
+          })();
+      }
     }
 
     warn(`Couldn't get blob URL nor external URL for @resource '${name}', attempting to use base64-encoded fallback`);