Merge branch 'immediate-finds' into immediate-finds-modules-proxy

This commit is contained in:
Nuckyz 2024-05-28 17:45:36 -03:00
commit a1309ea897
No known key found for this signature in database
GPG key ID: 440BF8296E1C4AD9
6 changed files with 226 additions and 142 deletions

View file

@ -8,7 +8,7 @@ import { definePluginSettings } from "@api/Settings";
import { classNameFactory } from "@api/Styles"; import { classNameFactory } from "@api/Styles";
import { Devs } from "@utils/constants"; import { Devs } from "@utils/constants";
import { Logger } from "@utils/Logger"; import { Logger } from "@utils/Logger";
import { proxyInnerValue } from "@utils/proxyInner"; import { SYM_PROXY_INNER_VALUE } from "@utils/proxyInner";
import { NoopComponent } from "@utils/react"; import { NoopComponent } from "@utils/react";
import definePlugin, { OptionType } from "@utils/types"; import definePlugin, { OptionType } from "@utils/types";
import { findByProps } from "@webpack"; import { findByProps } from "@webpack";
@ -133,7 +133,7 @@ export default definePlugin({
// try catch will only catch errors in the Layer function (hence why it's called as a plain function rather than a component), but // try catch will only catch errors in the Layer function (hence why it's called as a plain function rather than a component), but
// not in children // not in children
Layer(props: LayerProps) { Layer(props: LayerProps) {
if (FocusLock === NoopComponent || ComponentDispatch[proxyInnerValue] == null || Classes[proxyInnerValue] == null) { if (FocusLock === NoopComponent || ComponentDispatch[SYM_PROXY_INNER_VALUE] == null || Classes[SYM_PROXY_INNER_VALUE] == null) {
new Logger("BetterSettings").error("Failed to find some components"); new Logger("BetterSettings").error("Failed to find some components");
return props.children; return props.children;
} }

View file

@ -17,24 +17,34 @@
*/ */
import { Devs } from "@utils/constants"; import { Devs } from "@utils/constants";
import { getCurrentChannel, getCurrentGuild } from "@utils/discord";
import { SYM_LAZY_CACHED, SYM_LAZY_GET } from "@utils/lazy";
import { relaunch } from "@utils/native"; import { relaunch } from "@utils/native";
import { canonicalizeMatch, canonicalizeReplace, canonicalizeReplacement } from "@utils/patches"; import { canonicalizeMatch, canonicalizeReplace, canonicalizeReplacement } from "@utils/patches";
import definePlugin, { StartAt } from "@utils/types"; import { SYM_PROXY_INNER_GET, SYM_PROXY_INNER_VALUE } from "@utils/proxyInner";
import definePlugin, { PluginNative, StartAt } from "@utils/types";
import * as Webpack from "@webpack"; import * as Webpack from "@webpack";
import { cacheFindAll, extract, filters, findModuleId, search } from "@webpack"; import { cacheFindAll, extract, filters, findModuleId, search } from "@webpack";
import * as Common from "@webpack/common"; import * as Common from "@webpack/common";
import type { ComponentType } from "react"; import type { ComponentType } from "react";
const WEB_ONLY = (f: string) => () => { const DESKTOP_ONLY = (f: string) => () => {
throw new Error(`'${f}' is Discord Desktop only.`); throw new Error(`'${f}' is Discord Desktop only.`);
}; };
export default definePlugin({ const define: typeof Object.defineProperty =
name: "ConsoleShortcuts", (obj, prop, desc) => {
description: "Adds shorter Aliases for many things on the window. Run `shortcutList` for a list.", if (Object.hasOwn(desc, "value"))
authors: [Devs.Ven], desc.writable = true;
getShortcuts(): Record<PropertyKey, any> { return Object.defineProperty(obj, prop, {
configurable: true,
enumerable: true,
...desc
});
};
function makeShortcuts() {
function newFindWrapper(filterFactory: (...props: any[]) => Webpack.FilterFn) { function newFindWrapper(filterFactory: (...props: any[]) => Webpack.FilterFn) {
const cache = new Map<string, unknown>(); const cache = new Map<string, unknown>();
@ -87,14 +97,17 @@ export default definePlugin({
plugins: { getter: () => Vencord.Plugins.plugins }, plugins: { getter: () => Vencord.Plugins.plugins },
Settings: { getter: () => Vencord.Settings }, Settings: { getter: () => Vencord.Settings },
Api: { getter: () => Vencord.Api }, Api: { getter: () => Vencord.Api },
Util: { getter: () => Vencord.Util },
reload: () => location.reload(), reload: () => location.reload(),
restart: IS_WEB ? WEB_ONLY("restart") : relaunch, restart: IS_WEB ? DESKTOP_ONLY("restart") : relaunch,
canonicalizeMatch, canonicalizeMatch,
canonicalizeReplace, canonicalizeReplace,
canonicalizeReplacement, canonicalizeReplacement,
fakeRender: (component: ComponentType, props: any) => { fakeRender: (component: ComponentType, props: any) => {
const prevWin = fakeRenderWin?.deref(); const prevWin = fakeRenderWin?.deref();
const win = prevWin?.closed === false ? prevWin : window.open("about:blank", "Fake Render", "popup,width=500,height=500")!; const win = prevWin?.closed === false
? prevWin
: window.open("about:blank", "Fake Render", "popup,width=500,height=500")!;
fakeRenderWin = new WeakRef(win); fakeRenderWin = new WeakRef(win);
win.focus(); win.focus();
@ -117,38 +130,91 @@ export default definePlugin({
} }
Common.ReactDOM.render(Common.React.createElement(component, props), doc.body.appendChild(document.createElement("div"))); Common.ReactDOM.render(Common.React.createElement(component, props), doc.body.appendChild(document.createElement("div")));
}
};
}, },
preEnable: (plugin: string) => (Vencord.Settings.plugins[plugin] ??= { enabled: true }).enabled = true,
channel: { getter: () => getCurrentChannel(), preload: false },
channelId: { getter: () => Common.SelectedChannelStore.getChannelId(), preload: false },
guild: { getter: () => getCurrentGuild(), preload: false },
guildId: { getter: () => Common.SelectedGuildStore.getGuildId(), preload: false },
me: { getter: () => Common.UserStore.getCurrentUser(), preload: false },
meId: { getter: () => Common.UserStore.getCurrentUser().id, preload: false },
messages: { getter: () => Common.MessageStore.getMessages(Common.SelectedChannelStore.getChannelId()), preload: false }
};
}
function loadAndCacheShortcut(key: string, val: any, forceLoad: boolean) {
const currentVal = val.getter();
if (!currentVal || val.preload === false) return currentVal;
let value: any;
if (currentVal[SYM_LAZY_GET]) {
value = forceLoad ? currentVal[SYM_LAZY_GET]() : currentVal[SYM_LAZY_CACHED];
} else if (currentVal[SYM_PROXY_INNER_GET]) {
value = forceLoad ? currentVal[SYM_PROXY_INNER_GET]() : currentVal[SYM_PROXY_INNER_VALUE];
} else {
value = currentVal;
}
if (value) define(window.shortcutList, key, { value });
return value;
}
export default definePlugin({
name: "ConsoleShortcuts",
description: "Adds shorter Aliases for many things on the window. Run `shortcutList` for a list.",
authors: [Devs.Ven],
startAt: StartAt.Init, startAt: StartAt.Init,
start() { start() {
const shortcuts = this.getShortcuts(); const shortcuts = makeShortcuts();
window.shortcutList = {}; window.shortcutList = {};
for (const [key, val] of Object.entries(shortcuts)) { for (const [key, val] of Object.entries(shortcuts)) {
if (val.getter != null) { if ("getter" in val) {
Object.defineProperty(window.shortcutList, key, { define(window.shortcutList, key, {
get: val.getter, get: () => loadAndCacheShortcut(key, val, true)
configurable: true,
enumerable: true
}); });
Object.defineProperty(window, key, { define(window, key, {
get: () => window.shortcutList[key], get: () => window.shortcutList[key]
configurable: true,
enumerable: true
}); });
} else { } else {
window.shortcutList[key] = val; window.shortcutList[key] = val;
window[key] = val; window[key] = val;
} }
} }
// unproxy loaded modules
Webpack.onceReady.then(() => {
setTimeout(() => this.eagerLoad(false), 1000);
if (!IS_WEB) {
const Native = VencordNative.pluginHelpers.ConsoleShortcuts as PluginNative<typeof import("./native")>;
Native.initDevtoolsOpenEagerLoad();
}
});
},
async eagerLoad(forceLoad: boolean) {
await Webpack.onceReady;
const shortcuts = makeShortcuts();
for (const [key, val] of Object.entries(shortcuts)) {
if (!Object.hasOwn(val, "getter") || (val as any).preload === false) continue;
try {
loadAndCacheShortcut(key, val, forceLoad);
} catch { } // swallow not found errors in DEV
}
}, },
stop() { stop() {
delete window.shortcutList; delete window.shortcutList;
for (const key in this.getShortcuts()) { for (const key in makeShortcuts()) {
delete window[key]; delete window[key];
} }
} }

View file

@ -0,0 +1,16 @@
/*
* Vencord, a Discord client mod
* Copyright (c) 2024 Vendicated and contributors
* SPDX-License-Identifier: GPL-3.0-or-later
*/
import { IpcMainInvokeEvent } from "electron";
export function initDevtoolsOpenEagerLoad(e: IpcMainInvokeEvent) {
const handleDevtoolsOpened = () => e.sender.executeJavaScript("Vencord.Plugins.plugins.ConsoleShortcuts.eagerLoad(true)");
if (e.sender.isDevToolsOpened())
handleDevtoolsOpened();
else
e.sender.once("devtools-opened", () => handleDevtoolsOpened());
}

View file

@ -8,12 +8,12 @@ import { UNCONFIGURABLE_PROPERTIES } from "./misc";
import { AnyObject } from "./types"; import { AnyObject } from "./types";
export type ProxyLazy<T = AnyObject> = T & { export type ProxyLazy<T = AnyObject> = T & {
[proxyLazyGet]: () => T; [SYM_LAZY_GET]: () => T;
[proxyLazyCache]: T | undefined; [SYM_LAZY_CACHED]: T | undefined;
}; };
export const proxyLazyGet = Symbol.for("vencord.lazy.get"); export const SYM_LAZY_GET = Symbol.for("vencord.lazy.get");
export const proxyLazyCache = Symbol.for("vencord.lazy.cached"); export const SYM_LAZY_CACHED = Symbol.for("vencord.lazy.cached");
export type LazyFunction<T> = (() => T) & { export type LazyFunction<T> = (() => T) & {
$$vencordLazyFailed: () => boolean; $$vencordLazyFailed: () => boolean;
@ -42,14 +42,14 @@ export function makeLazy<T>(factory: () => T, attempts = 5, { isIndirect = false
const handler: ProxyHandler<any> = { const handler: ProxyHandler<any> = {
...Object.fromEntries(Object.getOwnPropertyNames(Reflect).map(propName => ...Object.fromEntries(Object.getOwnPropertyNames(Reflect).map(propName =>
[propName, (target: any, ...args: any[]) => Reflect[propName](target[proxyLazyGet](), ...args)] [propName, (target: any, ...args: any[]) => Reflect[propName](target[SYM_LAZY_GET](), ...args)]
)), )),
set: (target, p, newValue) => { set: (target, p, newValue) => {
const lazyTarget = target[proxyLazyGet](); const lazyTarget = target[SYM_LAZY_GET]();
return Reflect.set(lazyTarget, p, newValue, lazyTarget); return Reflect.set(lazyTarget, p, newValue, lazyTarget);
}, },
ownKeys: target => { ownKeys: target => {
const keys = Reflect.ownKeys(target[proxyLazyGet]()); const keys = Reflect.ownKeys(target[SYM_LAZY_GET]());
for (const key of UNCONFIGURABLE_PROPERTIES) { for (const key of UNCONFIGURABLE_PROPERTIES) {
if (!keys.includes(key)) keys.push(key); if (!keys.includes(key)) keys.push(key);
} }
@ -59,7 +59,7 @@ const handler: ProxyHandler<any> = {
if (typeof p === "string" && UNCONFIGURABLE_PROPERTIES.includes(p)) if (typeof p === "string" && UNCONFIGURABLE_PROPERTIES.includes(p))
return Reflect.getOwnPropertyDescriptor(target, p); return Reflect.getOwnPropertyDescriptor(target, p);
const descriptor = Reflect.getOwnPropertyDescriptor(target[proxyLazyGet](), p); const descriptor = Reflect.getOwnPropertyDescriptor(target[SYM_LAZY_GET](), p);
if (descriptor) Object.defineProperty(target, p, descriptor); if (descriptor) Object.defineProperty(target, p, descriptor);
return descriptor; return descriptor;
} }
@ -81,31 +81,32 @@ export function proxyLazy<T = AnyObject>(factory: () => T, attempts = 5, isChild
// Define the function in an object to preserve the name after minification // Define the function in an object to preserve the name after minification
const proxyDummy = ({ ProxyDummy() { } }).ProxyDummy; const proxyDummy = ({ ProxyDummy() { } }).ProxyDummy;
Object.assign(proxyDummy, { Object.assign(proxyDummy, {
[proxyLazyGet]() { [SYM_LAZY_GET]() {
if (!proxyDummy[proxyLazyCache]) { if (!proxyDummy[SYM_LAZY_CACHED]) {
if (!get.$$vencordLazyFailed()) { if (!get.$$vencordLazyFailed()) {
proxyDummy[proxyLazyCache] = get(); proxyDummy[SYM_LAZY_CACHED] = get();
} }
if (!proxyDummy[proxyLazyCache]) { if (!proxyDummy[SYM_LAZY_CACHED]) {
throw new Error(`proxyLazy factory failed:\n\n${factory}`); throw new Error(`proxyLazy factory failed:\n\n${factory}`);
} else { } else {
if (typeof proxyDummy[proxyLazyCache] === "function") { if (typeof proxyDummy[SYM_LAZY_CACHED] === "function") {
proxy.toString = proxyDummy[proxyLazyCache].toString.bind(proxyDummy[proxyLazyCache]); proxy.toString = proxyDummy[SYM_LAZY_CACHED].toString.bind(proxyDummy[SYM_LAZY_CACHED]);
} }
} }
} }
return proxyDummy[proxyLazyCache]; return proxyDummy[SYM_LAZY_CACHED];
}, },
[proxyLazyCache]: void 0 as T | undefined [SYM_LAZY_CACHED]: void 0 as T | undefined
}); });
const proxy = new Proxy(proxyDummy, { const proxy = new Proxy(proxyDummy, {
...handler, ...handler,
get(target, p) { get(target, p, receiver) {
if (p === proxyLazyGet) return target[proxyLazyGet]; if (p === SYM_LAZY_GET || p === SYM_LAZY_CACHED) {
if (p === proxyLazyCache) return target[proxyLazyCache]; return Reflect.get(target, p, receiver);
}
// If we're still in the same tick, it means the lazy was immediately used. // If we're still in the same tick, it means the lazy was immediately used.
// thus, we lazy proxy the get access to make things like destructuring work as expected // thus, we lazy proxy the get access to make things like destructuring work as expected
@ -114,7 +115,7 @@ export function proxyLazy<T = AnyObject>(factory: () => T, attempts = 5, isChild
if (!isChild && isSameTick) { if (!isChild && isSameTick) {
return proxyLazy( return proxyLazy(
() => { () => {
const lazyTarget = target[proxyLazyGet](); const lazyTarget = target[SYM_LAZY_GET]();
return Reflect.get(lazyTarget, p, lazyTarget); return Reflect.get(lazyTarget, p, lazyTarget);
}, },
attempts, attempts,
@ -122,7 +123,7 @@ export function proxyLazy<T = AnyObject>(factory: () => T, attempts = 5, isChild
); );
} }
const lazyTarget = target[proxyLazyGet](); const lazyTarget = target[SYM_LAZY_GET]();
if (typeof lazyTarget === "object" || typeof lazyTarget === "function") { if (typeof lazyTarget === "object" || typeof lazyTarget === "function") {
return Reflect.get(lazyTarget, p, lazyTarget); return Reflect.get(lazyTarget, p, lazyTarget);
} }

View file

@ -8,23 +8,23 @@ import { UNCONFIGURABLE_PROPERTIES } from "./misc";
import { AnyObject } from "./types"; import { AnyObject } from "./types";
export type ProxyInner<T = AnyObject> = T & { export type ProxyInner<T = AnyObject> = T & {
[proxyInnerGet]?: () => T; [SYM_PROXY_INNER_GET]?: () => T;
[proxyInnerValue]?: T | undefined; [SYM_PROXY_INNER_VALUE]?: T | undefined;
}; };
export const proxyInnerGet = Symbol.for("vencord.proxyInner.get"); export const SYM_PROXY_INNER_GET = Symbol.for("vencord.proxyInner.get");
export const proxyInnerValue = Symbol.for("vencord.proxyInner.innerValue"); export const SYM_PROXY_INNER_VALUE = Symbol.for("vencord.proxyInner.innerValue");
const handler: ProxyHandler<any> = { const handler: ProxyHandler<any> = {
...Object.fromEntries(Object.getOwnPropertyNames(Reflect).map(propName => ...Object.fromEntries(Object.getOwnPropertyNames(Reflect).map(propName =>
[propName, (target: any, ...args: any[]) => Reflect[propName](target[proxyInnerGet](), ...args)] [propName, (target: any, ...args: any[]) => Reflect[propName](target[SYM_PROXY_INNER_GET](), ...args)]
)), )),
set: (target, p, value) => { set: (target, p, value) => {
const innerTarget = target[proxyInnerGet](); const innerTarget = target[SYM_PROXY_INNER_GET]();
return Reflect.set(innerTarget, p, value, innerTarget); return Reflect.set(innerTarget, p, value, innerTarget);
}, },
ownKeys: target => { ownKeys: target => {
const keys = Reflect.ownKeys(target[proxyInnerGet]()); const keys = Reflect.ownKeys(target[SYM_PROXY_INNER_GET]());
for (const key of UNCONFIGURABLE_PROPERTIES) { for (const key of UNCONFIGURABLE_PROPERTIES) {
if (!keys.includes(key)) keys.push(key); if (!keys.includes(key)) keys.push(key);
} }
@ -34,7 +34,7 @@ const handler: ProxyHandler<any> = {
if (typeof p === "string" && UNCONFIGURABLE_PROPERTIES.includes(p)) if (typeof p === "string" && UNCONFIGURABLE_PROPERTIES.includes(p))
return Reflect.getOwnPropertyDescriptor(target, p); return Reflect.getOwnPropertyDescriptor(target, p);
const descriptor = Reflect.getOwnPropertyDescriptor(target[proxyInnerGet](), p); const descriptor = Reflect.getOwnPropertyDescriptor(target[SYM_PROXY_INNER_GET](), p);
if (descriptor) Object.defineProperty(target, p, descriptor); if (descriptor) Object.defineProperty(target, p, descriptor);
return descriptor; return descriptor;
} }
@ -58,21 +58,22 @@ export function proxyInner<T = AnyObject>(
// Define the function in an object to preserve the name after minification // Define the function in an object to preserve the name after minification
const proxyDummy = ({ ProxyDummy() { } }).ProxyDummy; const proxyDummy = ({ ProxyDummy() { } }).ProxyDummy;
Object.assign(proxyDummy, { Object.assign(proxyDummy, {
[proxyInnerGet]: function () { [SYM_PROXY_INNER_GET]: function () {
if (proxyDummy[proxyInnerValue] == null) { if (proxyDummy[SYM_PROXY_INNER_VALUE] == null) {
throw new Error(errMsg); throw new Error(errMsg);
} }
return proxyDummy[proxyInnerValue]; return proxyDummy[SYM_PROXY_INNER_VALUE];
}, },
[proxyInnerValue]: void 0 as T | undefined [SYM_PROXY_INNER_VALUE]: void 0 as T | undefined
}); });
const proxy = new Proxy(proxyDummy, { const proxy = new Proxy(proxyDummy, {
...handler, ...handler,
get(target, p) { get(target, p, receiver) {
if (p === proxyInnerValue) return target[proxyInnerValue]; if (p === SYM_PROXY_INNER_GET || p === SYM_PROXY_INNER_VALUE) {
if (p === proxyInnerGet) return target[proxyInnerGet]; return Reflect.get(target, p, receiver);
}
// If we're still in the same tick, it means the proxy was immediately used. // If we're still in the same tick, it means the proxy was immediately used.
// thus, we proxy the get access to make things like destructuring work as expected // thus, we proxy the get access to make things like destructuring work as expected
@ -89,7 +90,7 @@ export function proxyInner<T = AnyObject>(
return recursiveProxy; return recursiveProxy;
} }
const innerTarget = target[proxyInnerGet](); const innerTarget = target[SYM_PROXY_INNER_GET]();
if (typeof innerTarget === "object" || typeof innerTarget === "function") { if (typeof innerTarget === "object" || typeof innerTarget === "function") {
return Reflect.get(innerTarget, p, innerTarget); return Reflect.get(innerTarget, p, innerTarget);
} }
@ -104,7 +105,7 @@ export function proxyInner<T = AnyObject>(
// Once we set the parent inner value, we will call the setInnerValue functions of the destructured values, // Once we set the parent inner value, we will call the setInnerValue functions of the destructured values,
// for them to get the proper value from the parent and use as their inner instead // for them to get the proper value from the parent and use as their inner instead
function setInnerValue(innerValue: T) { function setInnerValue(innerValue: T) {
proxyDummy[proxyInnerValue] = innerValue; proxyDummy[SYM_PROXY_INNER_VALUE] = innerValue;
recursiveSetInnerValues.forEach(setInnerValue => setInnerValue(innerValue)); recursiveSetInnerValues.forEach(setInnerValue => setInnerValue(innerValue));
if (typeof innerValue === "function") { if (typeof innerValue === "function") {

View file

@ -8,7 +8,7 @@ import { makeLazy, proxyLazy } from "@utils/lazy";
import { LazyComponent } from "@utils/lazyReact"; import { LazyComponent } from "@utils/lazyReact";
import { Logger } from "@utils/Logger"; import { Logger } from "@utils/Logger";
import { canonicalizeMatch } from "@utils/patches"; import { canonicalizeMatch } from "@utils/patches";
import { ProxyInner, proxyInner, proxyInnerValue } from "@utils/proxyInner"; import { ProxyInner, proxyInner, SYM_PROXY_INNER_VALUE } from "@utils/proxyInner";
import { AnyObject } from "@utils/types"; import { AnyObject } from "@utils/types";
import { traceFunction } from "../debug/Tracer"; import { traceFunction } from "../debug/Tracer";
@ -190,7 +190,7 @@ export function find<T = AnyObject>(filter: FilterFn, callback: (module: ModuleE
webpackSearchHistory.push(["find", [proxy, filter]]); webpackSearchHistory.push(["find", [proxy, filter]]);
} }
if (proxy[proxyInnerValue] != null) return proxy[proxyInnerValue] as ProxyInner<T>; if (proxy[SYM_PROXY_INNER_VALUE] != null) return proxy[SYM_PROXY_INNER_VALUE] as ProxyInner<T>;
return proxy; return proxy;
} }