This commit is contained in:
thororen1234 2024-09-04 19:20:15 -04:00
parent fd4159a1a6
commit e3832b35ee
12 changed files with 377 additions and 638 deletions

View file

@ -14,9 +14,9 @@
"license": "GPL-3.0-or-later",
"author": "Equicord",
"scripts": {
"build": "tsx scripts/build/build.mts",
"build": "node --require=./scripts/suppressExperimentalWarnings.js scripts/build/build.mjs",
"buildStandalone": "pnpm build --standalone",
"buildWeb": "tsx scripts/build/buildWeb.mts",
"buildWeb": "node --require=./scripts/suppressExperimentalWarnings.js scripts/build/buildWeb.mjs",
"buildWebStandalone": "pnpm buildWeb --standalone",
"buildReporter": "pnpm buildWebStandalone --reporter --skip-extension",
"buildReporterDesktop": "pnpm build --reporter",
@ -63,7 +63,7 @@
"@types/yazl": "^2.4.5",
"diff": "^5.2.0",
"discord-types": "^1.3.26",
"esbuild": "^0.23.0",
"esbuild": "^0.15.18",
"eslint": "^9.8.0",
"eslint-import-resolver-alias": "^1.1.2",
"eslint-plugin-simple-header": "^1.1.1",
@ -78,7 +78,7 @@
"stylelint-config-standard": "^36.0.1",
"ts-patch": "^3.2.1",
"ts-pattern": "^5.3.1",
"tsx": "^4.16.5",
"tsx": "^3.12.7",
"type-fest": "^4.23.0",
"typed-emitter": "^2.1.0",
"typescript": "^5.5.4",
@ -114,7 +114,7 @@
"sourceDir": "./dist/firefox-unpacked"
},
"engines": {
"node": ">=20",
"node": ">=18",
"pnpm": ">=9"
}
}

File diff suppressed because it is too large Load diff

View file

@ -17,13 +17,13 @@
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
import esbuild from "esbuild";
import { createPackage } from "@electron/asar";
import { BuildOptions, Plugin } from "esbuild";
import { existsSync, readdirSync } from "fs";
import { readdir, rm, writeFile } from "fs/promises";
import { join } from "path";
import { readdir, writeFile } from "fs/promises";
import { dirname, join } from "path";
import { fileURLToPath } from "url";
import { addBuild, BUILD_TIMESTAMP, buildOrWatchAll, commonOpts, exists, globPlugins, IS_DEV, IS_REPORTER, IS_STANDALONE, IS_UPDATER_DISABLED, resolvePluginName, VERSION, watch } from "./common.mjs";
import { BUILD_TIMESTAMP, commonOpts, exists, globPlugins, IS_DEV, IS_REPORTER, IS_STANDALONE, IS_UPDATER_DISABLED, resolvePluginName, VERSION, watch } from "./common.mjs";
const defines = {
IS_STANDALONE: String(IS_STANDALONE),
@ -41,6 +41,9 @@ if (defines.IS_STANDALONE === "false")
// for the specific platform we're on
defines["process.platform"] = JSON.stringify(process.platform);
/**
* @type {esbuild.BuildOptions}
*/
const nodeCommonOpts = {
...commonOpts,
format: "cjs",
@ -48,12 +51,15 @@ const nodeCommonOpts = {
target: ["esnext"],
external: ["electron", "original-fs", "~pluginNatives", ...commonOpts.external],
define: defines
} satisfies BuildOptions;
};
const sourceMapFooter = (s: string) => watch ? "" : `//# sourceMappingURL=vencord://${s}.js.map`;
const sourceMapFooter = s => watch ? "" : `//# sourceMappingURL=vencord://${s}.js.map`;
const sourcemap = watch ? "inline" : "external";
const globNativesPlugin: Plugin = {
/**
* @type {import("esbuild").Plugin}
*/
const globNativesPlugin = {
name: "glob-natives-plugin",
setup: build => {
const filter = /^~pluginNatives$/;
@ -100,9 +106,9 @@ const globNativesPlugin: Plugin = {
await Promise.all([
// Discord Desktop main & renderer & preload
addBuild({
esbuild.build({
...nodeCommonOpts,
entryPoints: ["src/main/index.ts"],
entryPoints: [join(dirname(fileURLToPath(import.meta.url)), "../../src/main/index.ts")],
outfile: "dist/desktop/patcher.js",
footer: { js: "//# sourceURL=VencordPatcher\n" + sourceMapFooter("patcher") },
sourcemap,
@ -117,9 +123,9 @@ await Promise.all([
globNativesPlugin
]
}),
addBuild({
esbuild.build({
...commonOpts,
entryPoints: ["src/Vencord.ts"],
entryPoints: [join(dirname(fileURLToPath(import.meta.url)), "../../src/Vencord.ts")],
outfile: "dist/desktop/renderer.js",
format: "iife",
target: ["esnext"],
@ -137,9 +143,9 @@ await Promise.all([
IS_EQUIBOP: "false"
}
}),
addBuild({
esbuild.build({
...nodeCommonOpts,
entryPoints: ["src/preload.ts"],
entryPoints: [join(dirname(fileURLToPath(import.meta.url)), "../../src/preload.ts")],
outfile: "dist/desktop/preload.js",
footer: { js: "//# sourceURL=VencordPreload\n" + sourceMapFooter("preload") },
sourcemap,
@ -152,9 +158,9 @@ await Promise.all([
}),
// Vencord Desktop main & renderer & preload
addBuild({
esbuild.build({
...nodeCommonOpts,
entryPoints: ["src/main/index.ts"],
entryPoints: [join(dirname(fileURLToPath(import.meta.url)), "../../src/main/index.ts")],
outfile: "dist/vesktop/main.js",
footer: { js: "//# sourceURL=VencordMain\n" + sourceMapFooter("main") },
sourcemap,
@ -169,10 +175,10 @@ await Promise.all([
globNativesPlugin
]
}),
addBuild({
esbuild.build({
...commonOpts,
entryPoints: ["src/Vencord.ts"],
outfile: "dist/vesktop/renderer.js",
entryPoints: [join(dirname(fileURLToPath(import.meta.url)), "../../src/Vencord.ts")],
outfile: "dist/vencordDesktopRenderer.js",
format: "iife",
target: ["esnext"],
footer: { js: "//# sourceURL=VencordRenderer\n" + sourceMapFooter("renderer") },
@ -189,9 +195,9 @@ await Promise.all([
IS_EQUIBOP: "false"
}
}),
addBuild({
esbuild.build({
...nodeCommonOpts,
entryPoints: ["src/preload.ts"],
entryPoints: [join(dirname(fileURLToPath(import.meta.url)), "../../src/preload.ts")],
outfile: "dist/vesktop/preload.js",
footer: { js: "//# sourceURL=VencordPreload\n" + sourceMapFooter("preload") },
sourcemap,
@ -204,9 +210,9 @@ await Promise.all([
}),
// Equicord Desktop main & renderer & preload
addBuild({
esbuild.build({
...nodeCommonOpts,
entryPoints: ["src/main/index.ts"],
entryPoints: [join(dirname(fileURLToPath(import.meta.url)), "../../src/main/index.ts")],
outfile: "dist/equibop/main.js",
footer: { js: "//# sourceURL=EquicordMain\n" + sourceMapFooter("main") },
sourcemap,
@ -221,9 +227,9 @@ await Promise.all([
globNativesPlugin
]
}),
addBuild({
esbuild.build({
...commonOpts,
entryPoints: ["src/Vencord.ts"],
entryPoints: [join(dirname(fileURLToPath(import.meta.url)), "../../src/Vencord.ts")],
outfile: "dist/equibop/renderer.js",
format: "iife",
target: ["esnext"],
@ -241,9 +247,9 @@ await Promise.all([
IS_EQUIBOP: "true"
}
}),
addBuild({
esbuild.build({
...nodeCommonOpts,
entryPoints: ["src/preload.ts"],
entryPoints: [join(dirname(fileURLToPath(import.meta.url)), "../../src/preload.ts")],
outfile: "dist/equibop/preload.js",
footer: { js: "//# sourceURL=EquicordPreload\n" + sourceMapFooter("preload") },
sourcemap,
@ -254,9 +260,13 @@ await Promise.all([
IS_EQUIBOP: "true"
}
}),
]);
await buildOrWatchAll();
]).catch(err => {
console.error("Build failed");
console.error(err.message);
// make ci fail
if (!commonOpts.watch)
process.exitCode = 1;
});
await Promise.all([
writeFile("dist/desktop/package.json", JSON.stringify({
@ -278,24 +288,3 @@ await Promise.all([
createPackage("dist/equibop", "dist/equibop.asar"),
createPackage("dist/vesktop", "dist/vesktop.asar")
]);
if (existsSync("dist/renderer.js")) {
console.warn("Legacy dist folder. Cleaning up and adding shims.");
await Promise.all(
readdirSync("dist")
.filter(f =>
f.endsWith(".map") ||
f.endsWith(".LEGAL.txt") ||
["patcher", "preload", "renderer"].some(name => f.startsWith(name))
)
.map(file => rm(join("dist", file)))
);
await Promise.all([
writeFile("dist/patcher.js", 'require("./desktop")'),
writeFile("dist/equicordDesktopMain.js", 'require("./equibop")'),
writeFile("dist/vencordDesktopMain.js", 'require("./vesktop")')
]);
}

View file

@ -23,12 +23,12 @@ import { appendFile, mkdir, readdir, readFile, rm, writeFile } from "fs/promises
import { join } from "path";
import Zip from "zip-local";
import { addBuild, BUILD_TIMESTAMP, buildOrWatchAll, commonOpts, globPlugins, IS_DEV, IS_REPORTER, VERSION } from "./common.mjs";
import { BUILD_TIMESTAMP, commonOpts, globPlugins, IS_DEV, IS_REPORTER, VERSION } from "./common.mjs";
/**
* @type {esbuild.BuildOptions}
*/
const commonOptions: esbuild.BuildOptions = {
const commonOptions = {
...commonOpts,
entryPoints: ["browser/Vencord.ts"],
globalName: "Vencord",
@ -68,7 +68,7 @@ const RnNoiseFiles = [
await Promise.all(
[
addBuild({
esbuild.build({
entryPoints: MonacoWorkerEntryPoints.map(entry => `node_modules/monaco-editor/esm/${entry}`),
bundle: true,
minify: true,
@ -76,7 +76,7 @@ await Promise.all(
outbase: "node_modules/monaco-editor/esm/",
outdir: "dist/browser/monaco"
}),
addBuild({
esbuild.build({
entryPoints: ["browser/monaco.ts"],
bundle: true,
minify: true,
@ -86,12 +86,12 @@ await Promise.all(
".ttf": "file"
}
}),
addBuild({
esbuild.build({
...commonOptions,
outfile: "dist/browser/browser.js",
footer: { js: "//# sourceURL=VencordWeb" }
}),
addBuild({
esbuild.build({
...commonOptions,
outfile: "dist/browser/extension.js",
define: {
@ -100,7 +100,7 @@ await Promise.all(
},
footer: { js: "//# sourceURL=VencordWeb" }
}),
addBuild({
esbuild.build({
...commonOptions,
inject: ["browser/GMPolyfill.js", ...(commonOptions?.inject || [])],
define: {
@ -119,10 +119,11 @@ await Promise.all(
]
);
await buildOrWatchAll();
async function globDir(dir: string): Promise<string[]> {
const files = [] as string[];
/**
* @type {(dir: string) => Promise<string[]>}
*/
async function globDir(dir) {
const files = [];
for (const child of await readdir(dir, { withFileTypes: true })) {
const p = join(dir, child.name);
@ -135,23 +136,34 @@ async function globDir(dir: string): Promise<string[]> {
return files;
}
async function loadDir(dir: string, basePath = "") {
/**
* @type {(dir: string, basePath?: string) => Promise<Record<string, string>>}
*/
async function loadDir(dir, basePath = "") {
const files = await globDir(dir);
return Object.fromEntries(await Promise.all(files.map(async f =>
[f.slice(basePath.length), await readFile(f)] as const
)));
return Object.fromEntries(
await Promise.all(
files.map(
async f =>
[f.slice(basePath.length), await readFile(f)]
)
)
);
}
async function buildExtension(target: string, files: string[]): Promise<void> {
const entries: Record<string, Buffer> = {
/**
* @type {(target: string, files: string[]) => Promise<void>}
*/
async function buildExtension(target, files) {
const entries = {
"dist/Vencord.js": await readFile("dist/browser/extension.js"),
"dist/Vencord.css": await readFile("dist/browser/extension.css"),
...await loadDir("dist/browser/monaco"),
...Object.fromEntries(await Promise.all(RnNoiseFiles.map(async file =>
[`third-party/rnnoise/${file.replace(/^dist\//, "")}`, await readFile(`node_modules/@sapphi-red/web-noise-suppressor/${file}`)] as const
[`third-party/rnnoise/${file.replace(/^dist\//, "")}`, await readFile(`node_modules/@sapphi-red/web-noise-suppressor/${file}`)]
))),
...Object.fromEntries(await Promise.all(files.map(async f => {
let content: Uint8Array | Buffer = await readFile(join("browser", f));
let content = await readFile(join("browser", f));
if (f.startsWith("manifest")) {
const json = JSON.parse(content.toString("utf-8"));
json.version = VERSION;
@ -161,7 +173,7 @@ async function buildExtension(target: string, files: string[]): Promise<void> {
return [
f.startsWith("manifest") ? "manifest.json" : f,
content
] as const;
];
})))
};

View file

@ -20,16 +20,17 @@ import "../suppressExperimentalWarnings.js";
import "../checkNodeVersion.js";
import { exec, execSync } from "child_process";
import esbuild, { build, BuildOptions, context, Plugin } from "esbuild";
import esbuild from "esbuild";
import { constants as FsConstants, readFileSync } from "fs";
import { access, readdir, readFile } from "fs/promises";
import { minify as minifyHtml } from "html-minifier-terser";
import { join, relative } from "path";
import { dirname, join, relative } from "path";
import { fileURLToPath } from "url";
import { promisify } from "util";
import { getPluginTarget } from "../utils.mjs";
const PackageJSON: typeof import("../../package.json") = JSON.parse(readFileSync("package.json", "utf-8"));
const PackageJSON = JSON.parse(readFileSync(join(dirname(fileURLToPath(import.meta.url)), "../../package.json")));
export const VERSION = PackageJSON.version;
// https://reproducible-builds.org/docs/source-date-epoch/
@ -53,8 +54,11 @@ export const banner = {
};
const PluginDefinitionNameMatcher = /definePlugin\(\{\s*(["'])?name\1:\s*(["'`])(.+?)\2/;
export async function resolvePluginName(base: string, dirent: import("fs").Dirent) {
/**
* @param {string} base
* @param {import("fs").Dirent} dirent
*/
export async function resolvePluginName(base, dirent) {
const fullPath = join(base, dirent.name);
const content = dirent.isFile()
? await readFile(fullPath, "utf-8")
@ -75,13 +79,28 @@ export async function resolvePluginName(base: string, dirent: import("fs").Diren
})();
}
export async function exists(path: string) {
export async function exists(path) {
return await access(path, FsConstants.F_OK)
.then(() => true)
.catch(() => false);
}
export const globPlugins: (kind: "web" | "discordDesktop" | "vencordDesktop" | "equicordDesktop") => Plugin = kind => ({
// https://github.com/evanw/esbuild/issues/619#issuecomment-751995294
/**
* @type {import("esbuild").Plugin}
*/
export const makeAllPackagesExternalPlugin = {
name: "make-all-packages-external",
setup(build) {
const filter = /^[^./]|^\.[^./]|^\.\.[^/]/; // Must not start with "/" or "./" or "../"
build.onResolve({ filter }, args => ({ path: args.path, external: true }));
}
};
/**
* @type {(kind: "web" | "discordDesktop" | "vencordDesktop" | "equicordDesktop") => import("esbuild").Plugin}
*/
export const globPlugins = kind => ({
name: "glob-plugins",
setup: build => {
const filter = /^~plugins$/;
@ -146,7 +165,10 @@ export const globPlugins: (kind: "web" | "discordDesktop" | "vencordDesktop" | "
}
});
export const gitHashPlugin: Plugin = {
/**
* @type {import("esbuild").Plugin}
*/
export const gitHashPlugin = {
name: "git-hash-plugin",
setup: build => {
const filter = /^~git-hash$/;
@ -159,7 +181,10 @@ export const gitHashPlugin: Plugin = {
}
};
export const gitRemotePlugin: Plugin = {
/**
* @type {import("esbuild").Plugin}
*/
export const gitRemotePlugin = {
name: "git-remote-plugin",
setup: build => {
const filter = /^~git-remote$/;
@ -181,7 +206,10 @@ export const gitRemotePlugin: Plugin = {
}
};
export const fileUrlPlugin: Plugin = {
/**
* @type {import("esbuild").Plugin}
*/
export const fileUrlPlugin = {
name: "file-uri-plugin",
setup: build => {
const filter = /^file:\/\/.+$/;
@ -201,7 +229,7 @@ export const fileUrlPlugin: Plugin = {
const encoding = base64 ? "base64" : "utf-8";
let content: string;
let content;
if (!minify) {
content = await readFile(path, encoding);
if (!noTrim) content = content.trimEnd();
@ -240,8 +268,12 @@ export const fileUrlPlugin: Plugin = {
}
};
const styleModule = readFileSync("./scripts/build/module/style.js", "utf-8");
export const stylePlugin: Plugin = {
const styleModule = readFileSync(join(dirname(fileURLToPath(import.meta.url)), "module/style.js"), "utf-8");
/**
* @type {import("esbuild").Plugin}
*/
export const stylePlugin = {
name: "style-plugin",
setup: ({ onResolve, onLoad }) => {
onResolve({ filter: /\.css\?managed$/, namespace: "file" }, ({ path, resolveDir }) => ({
@ -262,43 +294,23 @@ export const stylePlugin: Plugin = {
}
};
/**
* @type {import("esbuild").BuildOptions}
*/
export const commonOpts = {
logLevel: "info",
bundle: true,
watch,
minify: !watch,
sourcemap: watch ? "inline" : "external",
sourcemap: watch ? "inline" : "",
legalComments: "linked",
banner,
plugins: [fileUrlPlugin, gitHashPlugin, gitRemotePlugin, stylePlugin],
external: ["~plugins", "~git-hash", "~git-remote", "/assets/*"],
inject: ["./scripts/build/inject/react.mjs"],
inject: [join(dirname(fileURLToPath(import.meta.url)), "inject/react.mjs")],
jsxFactory: "VencordCreateElement",
jsxFragment: "VencordFragment",
jsx: "transform"
} satisfies BuildOptions;
const builds = [] as BuildOptions[];
export function addBuild(options: BuildOptions) {
builds.push(options);
}
export async function buildOrWatchAll() {
if (watch) {
const contexts = await Promise.all(builds.map(context));
await Promise.all(contexts.map(ctx => ctx.watch()));
} else {
try {
await Promise.all(builds.map(build));
} catch (err) {
const reason = err instanceof Error
? err.message
: err;
console.error("Build failed");
console.error(reason);
// make ci fail
process.exitCode = 1;
}
}
}
jsx: "transform",
// Work around https://github.com/evanw/esbuild/issues/2460
tsconfig: join(dirname(fileURLToPath(import.meta.url)), "tsconfig.esbuild.json")
};

View file

@ -0,0 +1,7 @@
// Work around https://github.com/evanw/esbuild/issues/2460
{
"extends": "../../tsconfig.json",
"compilerOptions": {
"jsx": "react"
}
}

View file

@ -16,11 +16,15 @@
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
export function getPluginTarget(filePath: string) {
/**
* @param {string} filePath
* @returns {string | null}
*/
export function getPluginTarget(filePath) {
const pathParts = filePath.split(/[/\\]/);
if (/^index\.tsx?$/.test(pathParts.at(-1)!)) pathParts.pop();
if (/^index\.tsx?$/.test(pathParts.at(-1))) pathParts.pop();
const identifier = pathParts.at(-1)!.replace(/\.tsx?$/, "");
const identifier = pathParts.at(-1).replace(/\.tsx?$/, "");
const identiferBits = identifier.split(".");
return identiferBits.length === 1 ? null : identiferBits.at(-1);
}

View file

@ -138,6 +138,8 @@ export function registerCommand<C extends Command>(command: C, plugin: string) {
throw new Error(`Command '${command.name}' already exists.`);
command.isVencordCommand = true;
command.untranslatedName ??= command.name;
command.untranslatedDescription ??= command.description;
command.id ??= `-${BUILT_IN.length + 1}`;
command.applicationId ??= "-1"; // BUILT_IN;
command.type ??= ApplicationCommandType.CHAT_INPUT;

View file

@ -93,8 +93,10 @@ export interface Command {
isVencordCommand?: boolean;
name: string;
untranslatedName?: string;
displayName?: string;
description: string;
untranslatedDescription?: string;
displayDescription?: string;
options?: Option[];

View file

@ -103,7 +103,6 @@ export default definePlugin({
description: "Add call timer to all users in a server voice channel.",
authors: [EquicordDevs.MaxHerbold, Devs.D3SOX],
settings,
patches: [
{
find: "renderPrioritySpeaker",

View file

@ -76,7 +76,6 @@ function ToolBarHeader() {
}
async function openCompleteQuestUI() {
// check if user is sharing screen and there is someone that is watching the stream
const ApplicationStreamingStore = findByProps("getStreamerActiveStreamMetadata");
const RunningGameStore = findByProps("getRunningGames");
const ExperimentStore = findByProps("getGuildExperiments");

View file

@ -25,6 +25,7 @@ import { promisify } from "util";
import { serializeErrors } from "./common";
const VENCORD_SRC_DIR = join(__dirname, "..");
const EQUICORD_DIR = join(__dirname, "../../");
const execFile = promisify(cpExecFile);
@ -72,14 +73,16 @@ async function pull() {
}
async function build() {
const opts = { cwd: VENCORD_SRC_DIR };
const opts = { cwd: EQUICORD_DIR };
const command = isFlatpak ? "flatpak-spawn" : "node";
const args = isFlatpak ? ["--host", "node", "../scripts/build/build.mts"] : ["../scripts/build/build.mts"];
const args = isFlatpak ? ["--host", "node", "scripts/build/build.mjs"] : ["scripts/build/build.mjs"];
if (IS_DEV) args.push("--dev");
const res = await execFile(command, args, opts);
console.log(res);
console.log(`\n\n\n\n\n${res.stderr}`);
return !res.stderr.includes("Build failed");
}