this repo has no description

Use LunAST, moonmap, mappings in separate repos

+1 -1
.prettierignore
···
-
pnpm-lock.yml
+
pnpm-lock.yaml
+2 -1
packages/core/package.json
···
},
"dependencies": {
"@moonlight-mod/types": "workspace:*",
-
"@moonlight-mod/lunast": "workspace:*"
+
"@moonlight-mod/lunast": "git+https://github.com/moonlight-mod/lunast.git",
+
"@moonlight-mod/moonmap": "git+https://github.com/moonlight-mod/moonmap.git"
}
}
+16 -12
packages/core/src/patch.ts
···
for (const [id, func] of Object.entries(entry)) {
if (!Object.hasOwn(moduleCache, id) && func.__moonlight !== true) {
moduleCache[id] = func.toString().replace(/\n/g, "");
+
moonlight.moonmap.parseScript(id, moduleCache[id]);
}
}
···
const parsed = moonlight.lunast.parseScript(id, moduleString);
if (parsed != null) {
for (const [parsedId, parsedScript] of Object.entries(parsed)) {
-
// parseScript adds an extra ; for some reason
-
const fixedScript = parsedScript
-
.trimEnd()
-
.substring(0, parsedScript.lastIndexOf(";"));
-
-
if (patchModule(parsedId, "lunast", fixedScript)) {
-
moduleCache[parsedId] = fixedScript;
+
if (patchModule(parsedId, "lunast", parsedScript)) {
+
moduleCache[parsedId] = parsedScript;
}
}
}
···
const entrypoints: string[] = [];
let inject = false;
+
for (const [name, func] of Object.entries(
+
moonlight.moonmap.getWebpackModules("window.moonlight.moonmap")
+
)) {
+
modules[name] = func;
+
inject = true;
+
}
+
for (const [_modId, mod] of Object.entries(entry)) {
const modStr = mod.toString();
for (const wpModule of webpackModules) {
···
interface Window {
webpackChunkdiscord_app: WebpackJsonp;
}
+
}
+
+
function moduleSourceGetter(id: string) {
+
return moduleCache[id] ?? null;
}
/*
···
export async function installWebpackPatcher() {
await handleModuleDependencies();
-
moonlight.lunast.setModuleSourceGetter((id) => {
-
return moduleCache[id] ?? null;
-
});
+
moonlight.lunast.setModuleSourceGetter(moduleSourceGetter);
+
moonlight.moonmap.setModuleSourceGetter(moduleSourceGetter);
let realWebpackJsonp: WebpackJsonp | null = null;
Object.defineProperty(window, "webpackChunkdiscord_app", {
···
window.webpackChunkdiscord_app = [];
injectModules(modules);
}
-
-
moonlight.lunast.setDefaultRequire(this);
Object.defineProperty(this, "m", {
value: modules,
-131
packages/lunast/README.md
···
-
# LunAST
-
-
LunAST is an experimental in-development [AST](https://en.wikipedia.org/wiki/Abstract_syntax_tree)-based remapper and patcher for Webpack modules.
-
-
## Introduction
-
-
Modern Webpack patching functions off of matching existing minified code (using a string or regular expression) and then replacing it. While this is an easy to use and powerful way of patching Webpack modules, there are many downsides:
-
-
- Even the smallest change can break patches, which can require lots of maintenance, especially on large Discord bundler changes.
-
- Fetching exports from a Webpack module will sometimes result in minified export names. These exports must be manually remapped to human readable names by a library extension.
-
- Making complicated patches is extremely difficult and means your patch has more points of failure.
-
-
To solve this, LunAST generates [the ESTree format](https://github.com/estree/estree) with a handful of libraries ([meriyah](https://github.com/meriyah/meriyah), [estree-toolkit](https://github.com/sarsamurmu/estree-toolkit), [astring](https://github.com/davidbonnet/astring)) on each Webpack module. This makes large-scale manipulation and mapping feasible, by allowing you to write code to detect what modules you want to find.
-
-
## Usage
-
-
### Embedding into your own code
-
-
LunAST is not ready to be used in other projects just yet. In the future, LunAST will be a standalone library.
-
-
### Registering a processor
-
-
LunAST functions off of "processors". Processors have a unique ID, an optional filter (string or regex) on what to parse, and a process function which receives the AST.
-
-
The process function returns a boolean, which when true will unregister the processor. Once you have found what you're looking for, you can return true to skip parsing any other subsequent module, speeding up load times.
-
-
LunAST includes some core processors, and extensions can register their own processors (citation needed).
-
-
```ts
-
register({
-
name: "UniqueIDForTheProcessorSystem",
-
find: "some string or regex to search for", // optional
-
priority: 0, // optional
-
process({ id, ast, lunast }) {
-
// do some stuff with the ast
-
return false; // return true to unregister
-
}
-
});
-
```
-
-
### Mapping with LunAST
-
-
LunAST can use proxies to remap minified export names to more human readable ones. Let's say that you determined the module ID and export name of a component you want in a module.
-
-
First, you must define the type. A type contains a unique name and a list of fields. These fields contain the minified name and the human-readable name that can be used in code.
-
-
Then, register the module, with the ID passed to you in the process function. Specify its type so the remapper knows what fields to remap. It is suggested to name the module and type with the same name.
-
-
```ts
-
process({ id, ast, lunast }) {
-
let exportName: string | null = null;
-
-
// some code to discover the export name...
-
-
if (exportName != null) {
-
lunast.addType({
-
name: "SomeModule",
-
fields: [
-
{
-
name: "SomeComponent",
-
unmapped: exportName
-
}
-
]
-
});
-
lunast.addModule({
-
name: "SomeModule",
-
id,
-
type: "SomeModule"
-
});
-
return true;
-
}
-
-
return false;
-
}
-
```
-
-
Then, you need to specify the type of the module in `types.ts`. Using the `import` statement in Webpack modules is not supported yet. Hopefully this step is automated in the future.
-
-
After all this, fetch the remapped module and its remapped field:
-
-
```ts
-
moonlight.lunast.remap("SomeModule").SomeComponent
-
```
-
-
### Patching with LunAST
-
-
LunAST also enables you to modify the AST and then rebuild a module string from the modified AST. It is suggested you read the [estree-toolkit](https://estree-toolkit.netlify.app/welcome) documentation.
-
-
You can use the `magicAST` function to turn some JavaScript code into another AST node, and then merge/replace the original AST.
-
-
**After you modify the AST, call the markDirty function.** LunAST will not know to replace the module otherwise.
-
-
```ts
-
process({ ast, markDirty }) {
-
const node = /* do something with the AST */;
-
if (node != null) {
-
const replacement = magicAST("return 1 + 1");
-
node.replaceWith(replacement);
-
markDirty();
-
return true;
-
}
-
-
return false;
-
}
-
```
-
-
## FAQ
-
-
### How do you fetch the scripts to parse?
-
-
Fetching the content of the `<script>` tags is impossible, and making a `fetch` request would result in different headers to what the client would normally send. We use `Function.prototype.toString()` and wrap the function in parentheses to ensure the anonymous function is valid JavaScript.
-
-
### Isn't this slow?
-
-
Not really. LunAST runs in roughly ~10ms on [my](https://github.com/NotNite) machine, with filtering for what modules to parse. Parsing every module takes only a second. There are future plans to cache and parallelize the process, so that load times are only slow once.
-
-
You can measure how long LunAST took to process with the `moonlight.lunast.elapsed` variable.
-
-
### Does this mean patches are dead?
-
-
No. Patches will continue to serve their purpose and be supported in moonlight, no matter what. LunAST should also work with patches, but patches may conflict or not match.
-
-
[astring](https://github.com/davidbonnet/astring) may need to be forked in the future to output code without whitespace, in the event patches fail to match on AST-patched code.
-
-
### This API surface seems kind of bad
-
-
This is still in heavy development and all suggestions on how to improve it are welcome. :3
-
-
### Can I help?
-
-
Discussion takes place in the [moonlight Discord server](https://discord.gg/FdZBTFCP6F) and its `#lunast-devel` channel.
-22
packages/lunast/TODO.md
···
-
# LunAST TODO
-
-
- [ ] Experiment more! We need to know what's bad with this
-
- [ ] Write utility functions for imports, exports, etc.
-
- [ ] Imports
-
- [x] Exports
-
- [ ] Constant bindings for an object
-
- [ ] Map Z/ZP to default
-
- [x] Steal Webpack require and use it in our LunAST instance
-
- [ ] Map `import` statements to LunAST
-
- [x] Support patching in the AST
-
- Let user modify the AST, have a function to flag it as modified, if it's modified we serialize it back into a string and put it back into Webpack
-
- We already have a `priority` system for this
-
- [ ] Run in parallel with service workers
-
- This is gonna require making Webpack entrypoint async and us doing kickoff ourselves
-
- [ ] Support lazy loaded chunks
-
- Works right now, but will break when caching is implemented
-
- [ ] Split into a new repo on GitHub, publish to NPM maybe
-
- [ ] Implement caching based off of the client build and LunAST commit
-
- Means you only have to have a long client start once per client build
-
- [ ] Process in CI to use if available on startup
-
- Should mean, if you're lucky, client starts only take the extra time to make the request
-14
packages/lunast/package.json
···
-
{
-
"name": "@moonlight-mod/lunast",
-
"version": "1.0.0",
-
"main": "./src/index.ts",
-
"types": "./src/index.ts",
-
"exports": {
-
".": "./src/index.ts"
-
},
-
"dependencies": {
-
"astring": "^1.9.0",
-
"estree-toolkit": "^1.7.8",
-
"meriyah": "^6.0.1"
-
}
-
}
-196
packages/lunast/src/index.ts
···
-
import { RemapField, RemapModule, RemapType } from "./types";
-
import { Remapped } from "./modules";
-
import { getProcessors, parseFixed } from "./utils";
-
import { Processor, ProcessorState } from "./remap";
-
import { generate } from "astring";
-
-
export default class LunAST {
-
private modules: Record<string, RemapModule>;
-
private types: Record<string, RemapType>;
-
private successful: Set<string>;
-
-
private typeCache: Record<string, RemapType | null>;
-
private fieldCache: Record<
-
string,
-
Record<string | symbol, RemapField | null>
-
>;
-
private processors: Processor[];
-
private defaultRequire?: (id: string) => any;
-
private getModuleSource?: (id: string) => string;
-
-
elapsed: number;
-
-
constructor() {
-
this.modules = {};
-
this.types = {};
-
this.successful = new Set();
-
-
this.typeCache = {};
-
this.fieldCache = {};
-
this.processors = getProcessors();
-
-
this.elapsed = 0;
-
}
-
-
public static getVersion() {
-
// TODO: embed version in build when we move this to a new repo
-
// this is here for caching based off of the lunast commit ID
-
return "dev";
-
}
-
-
public parseScript(id: string, code: string): Record<string, string> {
-
const start = performance.now();
-
-
const available = [...this.processors]
-
.sort((a, b) => (a.priority ?? 0) - (b.priority ?? 0))
-
.filter((x) => {
-
if (x.find == null) return true;
-
const finds = Array.isArray(x.find) ? x.find : [x.find];
-
return finds.every((find) =>
-
typeof find === "string" ? code.indexOf(find) !== -1 : find.test(code)
-
);
-
})
-
.filter((x) => x.manual !== true);
-
-
const ret = this.parseScriptInternal(id, code, available);
-
-
const end = performance.now();
-
this.elapsed += end - start;
-
-
return ret;
-
}
-
-
// This is like this so processors can trigger other processors while they're parsing
-
private parseScriptInternal(
-
id: string,
-
code: string,
-
processors: Processor[]
-
) {
-
const ret: Record<string, string> = {};
-
if (processors.length === 0) return ret;
-
-
// Wrap so the anonymous function is valid JS
-
const module = parseFixed(`(\n${code}\n)`);
-
let dirty = false;
-
const state: ProcessorState = {
-
id,
-
ast: module,
-
lunast: this,
-
markDirty: () => {
-
dirty = true;
-
},
-
trigger: (id, tag) => {
-
const source = this.getModuleSourceById(id);
-
if (source == null) return;
-
if (this.successful.has(tag)) return;
-
const processor = this.processors.find((x) => x.name === tag);
-
if (processor == null) return;
-
const theirRet = this.parseScriptInternal(id, source, [processor]);
-
Object.assign(ret, theirRet);
-
}
-
};
-
-
for (const processor of processors) {
-
if (processor.process(state)) {
-
this.processors.splice(this.processors.indexOf(processor), 1);
-
this.successful.add(processor.name);
-
}
-
}
-
-
const str = dirty ? generate(module) : null;
-
if (str != null) ret[id] = str;
-
-
return ret;
-
}
-
-
public getType(name: string) {
-
return (
-
this.typeCache[name] ?? (this.typeCache[name] = this.types[name] ?? null)
-
);
-
}
-
-
public getIdForModule(name: string) {
-
return Object.values(this.modules).find((x) => x.name === name)?.id ?? null;
-
}
-
-
public addModule(module: RemapModule) {
-
if (!this.modules[module.name]) {
-
this.modules[module.name] = module;
-
} else {
-
throw new Error(
-
`Module ${module.name} already registered (${
-
this.modules[module.name].id
-
})`
-
);
-
}
-
}
-
-
public addType(type: RemapType) {
-
if (!this.types[type.name]) {
-
this.types[type.name] = type;
-
} else {
-
throw new Error(`Type ${type.name} already registered`);
-
}
-
}
-
-
public proxy(obj: any, type: RemapType): any {
-
const fields =
-
this.fieldCache[type.name] ?? (this.fieldCache[type.name] = {});
-
-
return new Proxy(obj, {
-
get: (target, prop) => {
-
const field =
-
fields[prop] ??
-
(fields[prop] = type.fields.find((x) => x.name === prop) ?? null);
-
if (field) {
-
const fieldType =
-
field.type != null ? this.getType(field.type) : null;
-
const name = field.unmapped ?? field.name;
-
if (fieldType != null) {
-
return this.proxy(target[name], fieldType);
-
} else {
-
return target[name];
-
}
-
} else {
-
return target[prop];
-
}
-
}
-
});
-
}
-
-
// TODO: call this with require we obtain from the webpack entrypoint
-
public setDefaultRequire(require: (id: string) => any) {
-
this.defaultRequire = require;
-
}
-
-
public setModuleSourceGetter(getSource: (id: string) => string) {
-
this.getModuleSource = getSource;
-
}
-
-
public getModuleSourceById(id: string) {
-
return this.getModuleSource?.(id) ?? null;
-
}
-
-
public remap<Id extends keyof Remapped>(
-
id: Id,
-
require?: (id: string) => any
-
): Remapped[Id] | null {
-
const mappedModule = this.modules[id];
-
if (!mappedModule) return null;
-
-
const realRequire = require ?? this.defaultRequire;
-
if (!realRequire) return null;
-
-
const module = realRequire(mappedModule.id);
-
if (module == null) return null;
-
-
const type = this.getType(mappedModule.type);
-
if (type != null) {
-
return this.proxy(module, type);
-
} else {
-
return module;
-
}
-
}
-
}
-
-
export { Remapped } from "./modules";
-4
packages/lunast/src/modules.ts
···
-
// This kinda sucks, TODO figure out a better way to do this dynamically
-
import "./modules/test";
-
-
export type Remapped = Record<string, never>;
-170
packages/lunast/src/modules/test.ts
···
-
import { traverse, is } from "estree-toolkit";
-
import { getPropertyGetters, register, magicAST, getImports } from "../utils";
-
import { BlockStatement } from "estree-toolkit/dist/generated/types";
-
-
// These aren't actual modules yet, I'm just using this as a testbed for stuff
-
-
// Exports example
-
/*register({
-
name: "ApplicationStoreDirectoryStore",
-
find: '"displayName","ApplicationStoreDirectoryStore"',
-
process({ ast }) {
-
const exports = getExports(ast);
-
return Object.keys(exports).length > 0;
-
}
-
});
-
-
register({
-
name: "FluxDispatcher",
-
find: "addBreadcrumb:",
-
process({ id, ast, lunast }) {
-
const exports = getExports(ast);
-
for (const [name, data] of Object.entries(exports)) {
-
if (!is.identifier(data.argument)) continue;
-
const binding = data.scope.getOwnBinding(data.argument.name);
-
console.log(name, binding);
-
}
-
return false;
-
}
-
});*/
-
-
// Patching example
-
register({
-
name: "ImagePreview",
-
find: ".Messages.OPEN_IN_BROWSER",
-
process({ id, ast, lunast, markDirty }) {
-
const getters = getPropertyGetters(ast);
-
const replacement = magicAST(`return require("common_react").createElement(
-
"div",
-
{
-
style: {
-
color: "white",
-
},
-
},
-
"balls"
-
)`)!;
-
for (const data of Object.values(getters)) {
-
if (!is.identifier(data.expression)) continue;
-
-
const node = data.scope.getOwnBinding(data.expression.name);
-
if (!node) continue;
-
-
const body = node.path.get<BlockStatement>("body");
-
body.replaceWith(replacement);
-
}
-
markDirty();
-
-
return true;
-
}
-
});
-
-
// Remapping example
-
register({
-
name: "ClipboardUtils",
-
find: 'document.queryCommandEnabled("copy")',
-
process({ id, ast, lunast }) {
-
const getters = getPropertyGetters(ast);
-
const fields = [];
-
-
for (const [name, data] of Object.entries(getters)) {
-
if (!is.identifier(data.expression)) continue;
-
const node = data.scope.getOwnBinding(data.expression.name);
-
if (!node) continue;
-
-
let isSupportsCopy = false;
-
traverse(node.path.node!, {
-
MemberExpression(path) {
-
if (
-
is.identifier(path.node?.property) &&
-
path.node?.property.name === "queryCommandEnabled"
-
) {
-
isSupportsCopy = true;
-
this.stop();
-
}
-
}
-
});
-
-
if (isSupportsCopy) {
-
fields.push({
-
name: "SUPPORTS_COPY",
-
unmapped: name
-
});
-
} else {
-
fields.push({
-
name: "copy",
-
unmapped: name
-
});
-
}
-
}
-
-
if (fields.length > 0) {
-
lunast.addType({
-
name: "ClipboardUtils",
-
fields
-
});
-
lunast.addModule({
-
name: "ClipboardUtils",
-
id,
-
type: "ClipboardUtils"
-
});
-
return true;
-
}
-
-
return false;
-
}
-
});
-
-
// Parse all modules to demonstrate speed loss
-
/*register({
-
name: "AllModules",
-
process({ id, ast, lunast }) {
-
return false;
-
}
-
});*/
-
-
// Triggering a processor from another processor
-
register({
-
name: "FluxDispatcherParent",
-
find: ["isDispatching", "dispatch", "googlebot"],
-
process({ id, ast, lunast, trigger }) {
-
const imports = getImports(ast);
-
// This is so stupid lol
-
const usages = Object.entries(imports)
-
.map(([name, data]): [string, number] => {
-
if (!is.identifier(data.expression)) return [name, 0];
-
const binding = data.scope.getOwnBinding(data.expression.name);
-
if (!binding) return [name, 0];
-
return [name, binding.references.length];
-
})
-
.sort(([, a], [, b]) => b! - a!)
-
.map(([name]) => name);
-
-
const dispatcher = usages[1].toString();
-
trigger(dispatcher, "FluxDispatcher");
-
return true;
-
}
-
});
-
-
register({
-
name: "FluxDispatcher",
-
manual: true,
-
process({ id, ast, lunast }) {
-
lunast.addModule({
-
name: "FluxDispatcher",
-
id,
-
type: "FluxDispatcher"
-
});
-
-
lunast.addType({
-
name: "FluxDispatcher",
-
fields: [
-
{
-
name: "default",
-
unmapped: "Z"
-
}
-
]
-
});
-
-
return true;
-
}
-
});
-17
packages/lunast/src/remap.ts
···
-
import type LunAST from ".";
-
import type { Program } from "estree-toolkit/dist/generated/types";
-
-
export type Processor = {
-
name: string;
-
find?: (string | RegExp)[] | (string | RegExp);
-
priority?: number;
-
manual?: boolean;
-
process: (state: ProcessorState) => boolean;
-
};
-
export type ProcessorState = {
-
id: string;
-
ast: Program;
-
lunast: LunAST;
-
markDirty: () => void;
-
trigger: (id: string, tag: string) => void;
-
};
-16
packages/lunast/src/types.ts
···
-
export type RemapModule = {
-
name: string; // the name you require it by in your code
-
id: string; // the resolved webpack module ID (usually a number)
-
type: string;
-
};
-
-
export type RemapType = {
-
name: string;
-
fields: RemapField[];
-
};
-
-
export type RemapField = {
-
name: string; // the name of the field in the proxy (human readable)
-
unmapped?: string; // the name of the field in discord source (minified)
-
type?: string;
-
};
-211
packages/lunast/src/utils.ts
···
-
import type { Processor } from "./remap";
-
import { traverse, is, Scope, Binding, NodePath } from "estree-toolkit";
-
// FIXME something's fishy with these types
-
import type {
-
Expression,
-
ExpressionStatement,
-
ObjectExpression,
-
Program,
-
ReturnStatement
-
} from "estree-toolkit/dist/generated/types";
-
import { parse } from "meriyah";
-
-
export const processors: Processor[] = [];
-
-
export function register(processor: Processor) {
-
processors.push(processor);
-
}
-
-
export function getProcessors() {
-
// Clone the array to prevent mutation
-
return [...processors];
-
}
-
-
export type ExpressionWithScope = {
-
expression: Expression;
-
scope: Scope;
-
};
-
-
function getParent(path: NodePath) {
-
let parent = path.parentPath;
-
while (!is.program(parent)) {
-
parent = parent?.parentPath ?? null;
-
if (
-
parent == null ||
-
parent.node == null ||
-
![
-
"FunctionExpression",
-
"ExpressionStatement",
-
"CallExpression",
-
"Program"
-
].includes(parent.node.type)
-
) {
-
return null;
-
}
-
}
-
-
if (!is.functionExpression(path.parent)) return null;
-
return path.parent;
-
}
-
-
export function getExports(ast: Program) {
-
const ret: Record<string, ExpressionWithScope> = {};
-
-
traverse(ast, {
-
$: { scope: true },
-
BlockStatement(path) {
-
if (path.scope == null) return;
-
const parent = getParent(path);
-
if (parent == null) return;
-
-
for (let i = 0; i < parent.params.length; i++) {
-
const param = parent.params[i];
-
if (!is.identifier(param)) continue;
-
const binding: Binding | undefined = path.scope!.getBinding(param.name);
-
if (!binding) continue;
-
-
// module
-
if (i === 0) {
-
for (const reference of binding.references) {
-
if (!is.identifier(reference.node)) continue;
-
if (!is.assignmentExpression(reference.parentPath?.parentPath))
-
continue;
-
-
const exportsNode = reference.parentPath?.parentPath.node;
-
if (!is.memberExpression(exportsNode?.left)) continue;
-
if (!is.identifier(exportsNode.left.property)) continue;
-
if (exportsNode.left.property.name !== "exports") continue;
-
-
const exports = exportsNode?.right;
-
if (!is.objectExpression(exports)) continue;
-
-
for (const property of exports.properties) {
-
if (!is.property(property)) continue;
-
if (!is.identifier(property.key)) continue;
-
if (!is.expression(property.value)) continue;
-
ret[property.key.name] = {
-
expression: property.value,
-
scope: path.scope
-
};
-
}
-
}
-
}
-
// TODO: exports
-
else if (i === 1) {
-
for (const reference of binding.references) {
-
if (!is.identifier(reference.node)) continue;
-
if (reference.parentPath == null) continue;
-
if (!is.memberExpression(reference.parentPath.node)) continue;
-
if (!is.identifier(reference.parentPath.node.property)) continue;
-
-
const assignmentExpression = reference.parentPath.parentPath?.node;
-
if (!is.assignmentExpression(assignmentExpression)) continue;
-
-
ret[reference.parentPath.node.property.name] = {
-
expression: assignmentExpression.right,
-
scope: path.scope
-
};
-
}
-
}
-
}
-
}
-
});
-
-
return ret;
-
}
-
-
// TODO: util function to resolve the value of an expression
-
export function getPropertyGetters(ast: Program) {
-
const ret: Record<string, ExpressionWithScope> = {};
-
-
traverse(ast, {
-
$: { scope: true },
-
CallExpression(path) {
-
if (path.scope == null) return;
-
if (!is.callExpression(path.node)) return;
-
if (!is.memberExpression(path.node.callee)) return;
-
if (!is.identifier(path.node?.callee?.property)) return;
-
if (path.node.callee.property.name !== "d") return;
-
-
const arg = path.node.arguments.find((node): node is ObjectExpression =>
-
is.objectExpression(node)
-
);
-
if (!arg) return;
-
-
for (const property of arg.properties) {
-
if (!is.property(property)) continue;
-
if (!is.identifier(property.key)) continue;
-
if (!is.functionExpression(property.value)) continue;
-
if (!is.blockStatement(property.value.body)) continue;
-
-
const returnStatement = property.value.body.body.find(
-
(node): node is ReturnStatement => is.returnStatement(node)
-
);
-
if (!returnStatement || !returnStatement.argument) continue;
-
ret[property.key.name] = {
-
expression: returnStatement.argument,
-
scope: path.scope
-
};
-
}
-
-
this.stop();
-
}
-
});
-
-
return ret;
-
}
-
-
// The ESTree types are mismatched with estree-toolkit, but ESTree is a standard so this is fine
-
export function parseFixed(code: string): Program {
-
return parse(code) as any as Program;
-
}
-
-
export function magicAST(code: string) {
-
// Wraps code in an IIFE so you can type `return` and all that goodies
-
// Might not work for some other syntax issues but oh well
-
const tree = parse("(()=>{" + code + "})()");
-
-
const expressionStatement = tree.body[0] as ExpressionStatement;
-
if (!is.expressionStatement(expressionStatement)) return null;
-
if (!is.callExpression(expressionStatement.expression)) return null;
-
if (!is.arrowFunctionExpression(expressionStatement.expression.callee))
-
return null;
-
if (!is.blockStatement(expressionStatement.expression.callee.body))
-
return null;
-
return expressionStatement.expression.callee.body;
-
}
-
-
export function getImports(ast: Program) {
-
const ret: Record<string, ExpressionWithScope> = {};
-
-
traverse(ast, {
-
$: { scope: true },
-
BlockStatement(path) {
-
if (path.scope == null) return;
-
const parent = getParent(path);
-
if (parent == null) return;
-
-
const require = parent.params[2];
-
if (!is.identifier(require)) return;
-
const references = path.scope.getOwnBinding(require.name)?.references;
-
if (references == null) return;
-
for (const reference of references) {
-
if (!is.callExpression(reference.parentPath)) continue;
-
if (reference.parentPath.node?.arguments.length !== 1) continue;
-
if (!is.variableDeclarator(reference.parentPath.parentPath)) continue;
-
if (!is.identifier(reference.parentPath.parentPath.node?.id)) continue;
-
-
const moduleId = reference.parentPath.node.arguments[0];
-
if (!is.literal(moduleId)) continue;
-
if (moduleId.value == null) continue;
-
-
ret[moduleId.value.toString()] = {
-
expression: reference.parentPath.parentPath.node.id,
-
scope: path.scope
-
};
-
}
-
}
-
});
-
-
return ret;
-
}
-3
packages/lunast/tsconfig.json
···
-
{
-
"extends": "../../tsconfig.json"
-
}
+2 -1
packages/types/package.json
···
"./*": "./src/*.ts"
},
"dependencies": {
-
"@moonlight-mod/lunast": "workspace:*",
+
"@moonlight-mod/lunast": "git+https://github.com/moonlight-mod/lunast.git",
+
"@moonlight-mod/moonmap": "git+https://github.com/moonlight-mod/moonmap.git",
"@types/flux": "^3.1.12",
"@types/react": "^18.2.22",
"csstype": "^3.1.2",
+2
packages/types/src/globals.ts
···
} from "./extension";
import type EventEmitter from "events";
import type LunAST from "@moonlight-mod/lunast";
+
import type Moonmap from "@moonlight-mod/moonmap";
export type MoonlightHost = {
asarPath: string;
···
getNatives: (ext: string) => any | undefined;
getLogger: (id: string) => Logger;
lunast: LunAST;
+
moonmap: Moonmap;
};
export enum MoonlightEnv {
+3
packages/types/src/index.ts
···
export * from "./logger";
export * as constants from "./constants";
+
export type { AST } from "@moonlight-mod/lunast";
+
export { ModuleExport, ModuleExportType } from "@moonlight-mod/moonmap";
+
declare global {
const MOONLIGHT_ENV: MoonlightEnv;
const MOONLIGHT_PROD: boolean;
+3 -1
packages/web-preload/package.json
···
"private": true,
"dependencies": {
"@moonlight-mod/core": "workspace:*",
-
"@moonlight-mod/lunast": "workspace:*"
+
"@moonlight-mod/lunast": "git+https://github.com/moonlight-mod/lunast.git",
+
"@moonlight-mod/moonmap": "git+https://github.com/moonlight-mod/moonmap.git",
+
"@moonlight-mod/mappings": "git+https://github.com/moonlight-mod/mappings.git"
}
}
+5 -1
packages/web-preload/src/index.ts
···
import { installStyles } from "@moonlight-mod/core/styles";
import Logger from "@moonlight-mod/core/util/logger";
import LunAST from "@moonlight-mod/lunast";
+
import Moonmap from "@moonlight-mod/moonmap";
+
import loadMappings from "@moonlight-mod/mappings";
(async () => {
const logger = new Logger("web-preload");
···
getLogger(id) {
return new Logger(id);
},
-
lunast: new LunAST()
+
lunast: new LunAST(),
+
moonmap: new Moonmap()
};
try {
+
loadMappings(window.moonlight.moonmap, window.moonlight.lunast);
await loadProcessedExtensions(moonlightNode.processedExtensions);
await installWebpackPatcher();
} catch (e) {
+46 -18
pnpm-lock.yaml
···
packages/core:
dependencies:
'@moonlight-mod/lunast':
-
specifier: workspace:*
-
version: link:../lunast
+
specifier: git+https://github.com/moonlight-mod/lunast.git
+
version: https://codeload.github.com/moonlight-mod/lunast/tar.gz/af98b963bf8b6d00301229b094811a55f96eca0a
+
'@moonlight-mod/moonmap':
+
specifier: git+https://github.com/moonlight-mod/moonmap.git
+
version: https://codeload.github.com/moonlight-mod/moonmap/tar.gz/79cfb0f84f62c910ff6eb3cf314e045110b9d319
'@moonlight-mod/types':
specifier: workspace:*
version: link:../types
···
specifier: workspace:*
version: link:../types
-
packages/lunast:
-
dependencies:
-
astring:
-
specifier: ^1.9.0
-
version: 1.9.0
-
estree-toolkit:
-
specifier: ^1.7.8
-
version: 1.7.8
-
meriyah:
-
specifier: ^6.0.1
-
version: 6.0.1
-
packages/node-preload:
dependencies:
'@moonlight-mod/core':
···
packages/types:
dependencies:
'@moonlight-mod/lunast':
-
specifier: workspace:*
-
version: link:../lunast
+
specifier: git+https://github.com/moonlight-mod/lunast.git
+
version: https://codeload.github.com/moonlight-mod/lunast/tar.gz/af98b963bf8b6d00301229b094811a55f96eca0a
+
'@moonlight-mod/moonmap':
+
specifier: git+https://github.com/moonlight-mod/moonmap.git
+
version: https://codeload.github.com/moonlight-mod/moonmap/tar.gz/79cfb0f84f62c910ff6eb3cf314e045110b9d319
'@types/flux':
specifier: ^3.1.12
version: 3.1.12
···
specifier: workspace:*
version: link:../core
'@moonlight-mod/lunast':
-
specifier: workspace:*
-
version: link:../lunast
+
specifier: git+https://github.com/moonlight-mod/lunast.git
+
version: https://codeload.github.com/moonlight-mod/lunast/tar.gz/af98b963bf8b6d00301229b094811a55f96eca0a
+
'@moonlight-mod/mappings':
+
specifier: git+https://github.com/moonlight-mod/mappings.git
+
version: https://codeload.github.com/moonlight-mod/mappings/tar.gz/8512c9df931a4a62a03e23c64a7d378602806128(@moonlight-mod/lunast@https://codeload.github.com/moonlight-mod/lunast/tar.gz/af98b963bf8b6d00301229b094811a55f96eca0a)(@moonlight-mod/moonmap@https://codeload.github.com/moonlight-mod/moonmap/tar.gz/79cfb0f84f62c910ff6eb3cf314e045110b9d319)
+
'@moonlight-mod/moonmap':
+
specifier: git+https://github.com/moonlight-mod/moonmap.git
+
version: https://codeload.github.com/moonlight-mod/moonmap/tar.gz/79cfb0f84f62c910ff6eb3cf314e045110b9d319
packages:
···
'@humanwhocodes/object-schema@2.0.1':
resolution: {integrity: sha512-dvuCeX5fC9dXgJn9t+X5atfmgQAzUOWqS1254Gh0m6i8wKd10ebXkfNKiRK+1GWi/yTvvLDHpoxLr0xxxeslWw==}
deprecated: Use @eslint/object-schema instead
+
+
'@moonlight-mod/lunast@https://codeload.github.com/moonlight-mod/lunast/tar.gz/af98b963bf8b6d00301229b094811a55f96eca0a':
+
resolution: {tarball: https://codeload.github.com/moonlight-mod/lunast/tar.gz/af98b963bf8b6d00301229b094811a55f96eca0a}
+
version: 1.0.0
+
+
'@moonlight-mod/mappings@https://codeload.github.com/moonlight-mod/mappings/tar.gz/8512c9df931a4a62a03e23c64a7d378602806128':
+
resolution: {tarball: https://codeload.github.com/moonlight-mod/mappings/tar.gz/8512c9df931a4a62a03e23c64a7d378602806128}
+
version: 1.0.0
+
peerDependencies:
+
'@moonlight-mod/lunast': git+https://github.com/moonlight-mod/lunast.git
+
'@moonlight-mod/moonmap': git+https://github.com/moonlight-mod/moonmap.git
+
+
'@moonlight-mod/moonmap@https://codeload.github.com/moonlight-mod/moonmap/tar.gz/79cfb0f84f62c910ff6eb3cf314e045110b9d319':
+
resolution: {tarball: https://codeload.github.com/moonlight-mod/moonmap/tar.gz/79cfb0f84f62c910ff6eb3cf314e045110b9d319}
+
version: 1.0.0
'@nodelib/fs.scandir@2.1.5':
resolution: {integrity: sha512-vq24Bq3ym5HEQm2NKCr3yXDwjc7vTsEThRDnkp2DK9p1uqLR+DHurm/NOTo0KG7HYHU7eppKZj3MyqYuMBf62g==}
···
'@humanwhocodes/module-importer@1.0.1': {}
'@humanwhocodes/object-schema@2.0.1': {}
+
+
'@moonlight-mod/lunast@https://codeload.github.com/moonlight-mod/lunast/tar.gz/af98b963bf8b6d00301229b094811a55f96eca0a':
+
dependencies:
+
astring: 1.9.0
+
estree-toolkit: 1.7.8
+
meriyah: 6.0.1
+
+
'@moonlight-mod/mappings@https://codeload.github.com/moonlight-mod/mappings/tar.gz/8512c9df931a4a62a03e23c64a7d378602806128(@moonlight-mod/lunast@https://codeload.github.com/moonlight-mod/lunast/tar.gz/af98b963bf8b6d00301229b094811a55f96eca0a)(@moonlight-mod/moonmap@https://codeload.github.com/moonlight-mod/moonmap/tar.gz/79cfb0f84f62c910ff6eb3cf314e045110b9d319)':
+
dependencies:
+
'@moonlight-mod/lunast': https://codeload.github.com/moonlight-mod/lunast/tar.gz/af98b963bf8b6d00301229b094811a55f96eca0a
+
'@moonlight-mod/moonmap': https://codeload.github.com/moonlight-mod/moonmap/tar.gz/79cfb0f84f62c910ff6eb3cf314e045110b9d319
+
+
'@moonlight-mod/moonmap@https://codeload.github.com/moonlight-mod/moonmap/tar.gz/79cfb0f84f62c910ff6eb3cf314e045110b9d319': {}
'@nodelib/fs.scandir@2.1.5':
dependencies: