···1-# LunAST
2-3-LunAST is an experimental in-development [AST](https://en.wikipedia.org/wiki/Abstract_syntax_tree)-based remapper and patcher for Webpack modules.
4-5-## Introduction
6-7-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:
8-9-- Even the smallest change can break patches, which can require lots of maintenance, especially on large Discord bundler changes.
10-- 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.
11-- Making complicated patches is extremely difficult and means your patch has more points of failure.
12-13-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.
14-15-## Usage
16-17-### Embedding into your own code
18-19-LunAST is not ready to be used in other projects just yet. In the future, LunAST will be a standalone library.
20-21-### Registering a processor
22-23-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.
24-25-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.
26-27-LunAST includes some core processors, and extensions can register their own processors (citation needed).
28-29-```ts
30-register({
31- name: "UniqueIDForTheProcessorSystem",
32- find: "some string or regex to search for", // optional
33- priority: 0, // optional
34- process({ id, ast, lunast }) {
35- // do some stuff with the ast
36- return false; // return true to unregister
37- }
38-});
39-```
40-41-### Mapping with LunAST
42-43-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.
44-45-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.
46-47-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.
48-49-```ts
50-process({ id, ast, lunast }) {
51- let exportName: string | null = null;
52-53- // some code to discover the export name...
54-55- if (exportName != null) {
56- lunast.addType({
57- name: "SomeModule",
58- fields: [
59- {
60- name: "SomeComponent",
61- unmapped: exportName
62- }
63- ]
64- });
65- lunast.addModule({
66- name: "SomeModule",
67- id,
68- type: "SomeModule"
69- });
70- return true;
71- }
72-73- return false;
74-}
75-```
76-77-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.
78-79-After all this, fetch the remapped module and its remapped field:
80-81-```ts
82-moonlight.lunast.remap("SomeModule").SomeComponent
83-```
84-85-### Patching with LunAST
86-87-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.
88-89-You can use the `magicAST` function to turn some JavaScript code into another AST node, and then merge/replace the original AST.
90-91-**After you modify the AST, call the markDirty function.** LunAST will not know to replace the module otherwise.
92-93-```ts
94-process({ ast, markDirty }) {
95- const node = /* do something with the AST */;
96- if (node != null) {
97- const replacement = magicAST("return 1 + 1");
98- node.replaceWith(replacement);
99- markDirty();
100- return true;
101- }
102-103- return false;
104-}
105-```
106-107-## FAQ
108-109-### How do you fetch the scripts to parse?
110-111-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.
112-113-### Isn't this slow?
114-115-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.
116-117-You can measure how long LunAST took to process with the `moonlight.lunast.elapsed` variable.
118-119-### Does this mean patches are dead?
120-121-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.
122-123-[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.
124-125-### This API surface seems kind of bad
126-127-This is still in heavy development and all suggestions on how to improve it are welcome. :3
128-129-### Can I help?
130-131-Discussion takes place in the [moonlight Discord server](https://discord.gg/FdZBTFCP6F) and its `#lunast-devel` channel.
···1-# LunAST TODO
2-3-- [ ] Experiment more! We need to know what's bad with this
4-- [ ] Write utility functions for imports, exports, etc.
5- - [ ] Imports
6- - [x] Exports
7- - [ ] Constant bindings for an object
8-- [ ] Map Z/ZP to default
9-- [x] Steal Webpack require and use it in our LunAST instance
10-- [ ] Map `import` statements to LunAST
11-- [x] Support patching in the AST
12- - 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
13- - We already have a `priority` system for this
14-- [ ] Run in parallel with service workers
15- - This is gonna require making Webpack entrypoint async and us doing kickoff ourselves
16-- [ ] Support lazy loaded chunks
17- - Works right now, but will break when caching is implemented
18-- [ ] Split into a new repo on GitHub, publish to NPM maybe
19-- [ ] Implement caching based off of the client build and LunAST commit
20- - Means you only have to have a long client start once per client build
21-- [ ] Process in CI to use if available on startup
22- - Should mean, if you're lucky, client starts only take the extra time to make the request
···1-// This kinda sucks, TODO figure out a better way to do this dynamically
2-import "./modules/test";
3-4-export type Remapped = Record<string, never>;
···1-import type LunAST from ".";
2-import type { Program } from "estree-toolkit/dist/generated/types";
3-4-export type Processor = {
5- name: string;
6- find?: (string | RegExp)[] | (string | RegExp);
7- priority?: number;
8- manual?: boolean;
9- process: (state: ProcessorState) => boolean;
10-};
11-export type ProcessorState = {
12- id: string;
13- ast: Program;
14- lunast: LunAST;
15- markDirty: () => void;
16- trigger: (id: string, tag: string) => void;
17-};
···00000000000000000
-16
packages/lunast/src/types.ts
···1-export type RemapModule = {
2- name: string; // the name you require it by in your code
3- id: string; // the resolved webpack module ID (usually a number)
4- type: string;
5-};
6-7-export type RemapType = {
8- name: string;
9- fields: RemapField[];
10-};
11-12-export type RemapField = {
13- name: string; // the name of the field in the proxy (human readable)
14- unmapped?: string; // the name of the field in discord source (minified)
15- type?: string;
16-};
···0000000000000000
-211
packages/lunast/src/utils.ts
···1-import type { Processor } from "./remap";
2-import { traverse, is, Scope, Binding, NodePath } from "estree-toolkit";
3-// FIXME something's fishy with these types
4-import type {
5- Expression,
6- ExpressionStatement,
7- ObjectExpression,
8- Program,
9- ReturnStatement
10-} from "estree-toolkit/dist/generated/types";
11-import { parse } from "meriyah";
12-13-export const processors: Processor[] = [];
14-15-export function register(processor: Processor) {
16- processors.push(processor);
17-}
18-19-export function getProcessors() {
20- // Clone the array to prevent mutation
21- return [...processors];
22-}
23-24-export type ExpressionWithScope = {
25- expression: Expression;
26- scope: Scope;
27-};
28-29-function getParent(path: NodePath) {
30- let parent = path.parentPath;
31- while (!is.program(parent)) {
32- parent = parent?.parentPath ?? null;
33- if (
34- parent == null ||
35- parent.node == null ||
36- ![
37- "FunctionExpression",
38- "ExpressionStatement",
39- "CallExpression",
40- "Program"
41- ].includes(parent.node.type)
42- ) {
43- return null;
44- }
45- }
46-47- if (!is.functionExpression(path.parent)) return null;
48- return path.parent;
49-}
50-51-export function getExports(ast: Program) {
52- const ret: Record<string, ExpressionWithScope> = {};
53-54- traverse(ast, {
55- $: { scope: true },
56- BlockStatement(path) {
57- if (path.scope == null) return;
58- const parent = getParent(path);
59- if (parent == null) return;
60-61- for (let i = 0; i < parent.params.length; i++) {
62- const param = parent.params[i];
63- if (!is.identifier(param)) continue;
64- const binding: Binding | undefined = path.scope!.getBinding(param.name);
65- if (!binding) continue;
66-67- // module
68- if (i === 0) {
69- for (const reference of binding.references) {
70- if (!is.identifier(reference.node)) continue;
71- if (!is.assignmentExpression(reference.parentPath?.parentPath))
72- continue;
73-74- const exportsNode = reference.parentPath?.parentPath.node;
75- if (!is.memberExpression(exportsNode?.left)) continue;
76- if (!is.identifier(exportsNode.left.property)) continue;
77- if (exportsNode.left.property.name !== "exports") continue;
78-79- const exports = exportsNode?.right;
80- if (!is.objectExpression(exports)) continue;
81-82- for (const property of exports.properties) {
83- if (!is.property(property)) continue;
84- if (!is.identifier(property.key)) continue;
85- if (!is.expression(property.value)) continue;
86- ret[property.key.name] = {
87- expression: property.value,
88- scope: path.scope
89- };
90- }
91- }
92- }
93- // TODO: exports
94- else if (i === 1) {
95- for (const reference of binding.references) {
96- if (!is.identifier(reference.node)) continue;
97- if (reference.parentPath == null) continue;
98- if (!is.memberExpression(reference.parentPath.node)) continue;
99- if (!is.identifier(reference.parentPath.node.property)) continue;
100-101- const assignmentExpression = reference.parentPath.parentPath?.node;
102- if (!is.assignmentExpression(assignmentExpression)) continue;
103-104- ret[reference.parentPath.node.property.name] = {
105- expression: assignmentExpression.right,
106- scope: path.scope
107- };
108- }
109- }
110- }
111- }
112- });
113-114- return ret;
115-}
116-117-// TODO: util function to resolve the value of an expression
118-export function getPropertyGetters(ast: Program) {
119- const ret: Record<string, ExpressionWithScope> = {};
120-121- traverse(ast, {
122- $: { scope: true },
123- CallExpression(path) {
124- if (path.scope == null) return;
125- if (!is.callExpression(path.node)) return;
126- if (!is.memberExpression(path.node.callee)) return;
127- if (!is.identifier(path.node?.callee?.property)) return;
128- if (path.node.callee.property.name !== "d") return;
129-130- const arg = path.node.arguments.find((node): node is ObjectExpression =>
131- is.objectExpression(node)
132- );
133- if (!arg) return;
134-135- for (const property of arg.properties) {
136- if (!is.property(property)) continue;
137- if (!is.identifier(property.key)) continue;
138- if (!is.functionExpression(property.value)) continue;
139- if (!is.blockStatement(property.value.body)) continue;
140-141- const returnStatement = property.value.body.body.find(
142- (node): node is ReturnStatement => is.returnStatement(node)
143- );
144- if (!returnStatement || !returnStatement.argument) continue;
145- ret[property.key.name] = {
146- expression: returnStatement.argument,
147- scope: path.scope
148- };
149- }
150-151- this.stop();
152- }
153- });
154-155- return ret;
156-}
157-158-// The ESTree types are mismatched with estree-toolkit, but ESTree is a standard so this is fine
159-export function parseFixed(code: string): Program {
160- return parse(code) as any as Program;
161-}
162-163-export function magicAST(code: string) {
164- // Wraps code in an IIFE so you can type `return` and all that goodies
165- // Might not work for some other syntax issues but oh well
166- const tree = parse("(()=>{" + code + "})()");
167-168- const expressionStatement = tree.body[0] as ExpressionStatement;
169- if (!is.expressionStatement(expressionStatement)) return null;
170- if (!is.callExpression(expressionStatement.expression)) return null;
171- if (!is.arrowFunctionExpression(expressionStatement.expression.callee))
172- return null;
173- if (!is.blockStatement(expressionStatement.expression.callee.body))
174- return null;
175- return expressionStatement.expression.callee.body;
176-}
177-178-export function getImports(ast: Program) {
179- const ret: Record<string, ExpressionWithScope> = {};
180-181- traverse(ast, {
182- $: { scope: true },
183- BlockStatement(path) {
184- if (path.scope == null) return;
185- const parent = getParent(path);
186- if (parent == null) return;
187-188- const require = parent.params[2];
189- if (!is.identifier(require)) return;
190- const references = path.scope.getOwnBinding(require.name)?.references;
191- if (references == null) return;
192- for (const reference of references) {
193- if (!is.callExpression(reference.parentPath)) continue;
194- if (reference.parentPath.node?.arguments.length !== 1) continue;
195- if (!is.variableDeclarator(reference.parentPath.parentPath)) continue;
196- if (!is.identifier(reference.parentPath.parentPath.node?.id)) continue;
197-198- const moduleId = reference.parentPath.node.arguments[0];
199- if (!is.literal(moduleId)) continue;
200- if (moduleId.value == null) continue;
201-202- ret[moduleId.value.toString()] = {
203- expression: reference.parentPath.parentPath.node.id,
204- scope: path.scope
205- };
206- }
207- }
208- });
209-210- return ret;
211-}
···8} from "./extension";
9import type EventEmitter from "events";
10import type LunAST from "@moonlight-mod/lunast";
01112export type MoonlightHost = {
13 asarPath: string;
···46 getNatives: (ext: string) => any | undefined;
47 getLogger: (id: string) => Logger;
48 lunast: LunAST;
049};
5051export enum MoonlightEnv {
···8} from "./extension";
9import type EventEmitter from "events";
10import type LunAST from "@moonlight-mod/lunast";
11+import type Moonmap from "@moonlight-mod/moonmap";
1213export type MoonlightHost = {
14 asarPath: string;
···47 getNatives: (ext: string) => any | undefined;
48 getLogger: (id: string) => Logger;
49 lunast: LunAST;
50+ moonmap: Moonmap;
51};
5253export enum MoonlightEnv {
+3
packages/types/src/index.ts
···19export * from "./logger";
20export * as constants from "./constants";
2100022declare global {
23 const MOONLIGHT_ENV: MoonlightEnv;
24 const MOONLIGHT_PROD: boolean;
···19export * from "./logger";
20export * as constants from "./constants";
2122+export type { AST } from "@moonlight-mod/lunast";
23+export { ModuleExport, ModuleExportType } from "@moonlight-mod/moonmap";
24+25declare global {
26 const MOONLIGHT_ENV: MoonlightEnv;
27 const MOONLIGHT_PROD: boolean;