Host bundle from 5895305a367404f0bed3cb180176a6f81a53bffc

This commit is contained in:
github-actions[bot] 2026-08-09 07:27:56 +00:00
commit 4877be9502
244 changed files with 21712 additions and 0 deletions

21
.editorconfig Normal file
View file

@ -0,0 +1,21 @@
root = true
[*]
indent_style = space
indent_size = 2
end_of_line = crlf
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = true
max_line_length = 120
[*.json]
indent_style = space
indent_size = 2
[*.{js,jsx,ts,tsx}]
indent_style = space
indent_size = 4
quote_type = single
semi = false
trailing_comma = all

58
.github/workflows/build.yml vendored Normal file
View file

@ -0,0 +1,58 @@
name: Build
on:
workflow_dispatch:
push:
branches:
- dev
- main
pull_request:
branches:
- dev
jobs:
build:
name: Build
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Restore Bun cache
uses: actions/cache@v4
with:
path: ~/.bun/install/cache
key: ${{ runner.os }}-bun-${{ hashFiles('**/bun.lock') }}
restore-keys: |
${{ runner.os }}-bun-
- name: Setup Bun
uses: oven-sh/setup-bun@v2
with:
bun-version: latest
- name: Install dependencies
run: bun install --frozen-lockfile --production
- name: Build development bundle
run: bun run build --dev
- name: Upload development bundle
uses: actions/upload-artifact@v4
with:
name: revenge-bundle-development
path: dist/revenge.bundle
if-no-files-found: error
- name: Clear build
run: rm -rf dist
- name: Build production bundle
run: bun run build
- name: Upload production bundle
uses: actions/upload-artifact@v4
with:
name: revenge-bundle
path: dist/revenge.bundle
if-no-files-found: error

54
.github/workflows/host-bundle.yml vendored Normal file
View file

@ -0,0 +1,54 @@
name: Host Revenge Bundle
on:
workflow_dispatch:
push:
branches:
- main
jobs:
build-and-host:
runs-on: ubuntu-latest
permissions:
contents: write
steps:
- name: Checkout
uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Restore Bun cache
uses: actions/cache@v4
with:
path: ~/.bun/install/cache
key: ${{ runner.os }}-bun-${{ hashFiles('**/bun.lock') }}
restore-keys: |
${{ runner.os }}-bun-
- name: Setup Bun
uses: oven-sh/setup-bun@v2
with:
bun-version: latest
- name: Install dependencies
run: bun install --frozen-lockfile --production
- name: Build production bundle
run: bun run build
- name: Publish bundle to hosting branch
run: |
cp dist/revenge.bundle /tmp/revenge.bundle
git config --global user.name "github-actions[bot]"
git config --global user.email "41898282+github-actions[bot]@users.noreply.github.com"
if git show-ref --verify --quiet "refs/heads/hosting"; then
git checkout hosting
git rm -rf .
else
git checkout --orphan hosting
fi
rm -rf *
cp /tmp/revenge.bundle ./revenge.bundle
git add revenge.bundle
git commit -m "Host bundle from ${GITHUB_SHA}" || true
git push --force origin hosting

178
.gitignore vendored Normal file
View file

@ -0,0 +1,178 @@
# Based on https://raw.githubusercontent.com/github/gitignore/main/Node.gitignore
# Logs
logs
_.log
npm-debug.log_
yarn-debug.log*
yarn-error.log*
lerna-debug.log*
.pnpm-debug.log*
# Caches
.cache
# Diagnostic reports (https://nodejs.org/api/report.html)
report.[0-9]_.[0-9]_.[0-9]_.[0-9]_.json
# Runtime data
pids
_.pid
_.seed
*.pid.lock
# Directory for instrumented libs generated by jscoverage/JSCover
lib-cov
# Coverage directory used by tools like istanbul
coverage
*.lcov
# nyc test coverage
.nyc_output
# Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files)
.grunt
# Bower dependency directory (https://bower.io/)
bower_components
# node-waf configuration
.lock-wscript
# Compiled binary addons (https://nodejs.org/api/addons.html)
build/Release
# Dependency directories
node_modules/
jspm_packages/
# Snowpack dependency directory (https://snowpack.dev/)
web_modules/
# TypeScript cache
*.tsbuildinfo
# Optional npm cache directory
.npm
# Optional eslint cache
.eslintcache
# Optional stylelint cache
.stylelintcache
# Microbundle cache
.rpt2_cache/
.rts2_cache_cjs/
.rts2_cache_es/
.rts2_cache_umd/
# Optional REPL history
.node_repl_history
# Output of 'npm pack'
*.tgz
# Yarn Integrity file
.yarn-integrity
# dotenv environment variable files
.env
.env.development.local
.env.test.local
.env.production.local
.env.local
# parcel-bundler cache (https://parceljs.org/)
.parcel-cache
# Next.js build output
.next
out
# Nuxt.js build / generate output
.nuxt
dist
# Gatsby files
# Comment in the public line in if your project uses Gatsby and not Next.js
# https://nextjs.org/blog/next-9-1#public-directory-support
# public
# vuepress build output
.vuepress/dist
# vuepress v2.x temp and cache directory
.temp
# Docusaurus cache and generated files
.docusaurus
# Serverless directories
.serverless/
# FuseBox cache
.fusebox/
# DynamoDB Local files
.dynamodb/
# TernJS port file
.tern-port
# Stores VSCode versions used for testing VSCode extensions
.vscode-test
# yarn v2
.yarn/cache
.yarn/unplugged
.yarn/build-state.yml
.yarn/install-state.gz
.pnp.*
# IntelliJ based IDEs
.idea
# Finder (MacOS) folder config
.DS_Store
# Private
.private

8
.vscode/settings.json vendored Normal file
View file

@ -0,0 +1,8 @@
{
"editor.codeActionsOnSave": {
"source.biome": "explicit",
"source.fixAll.biome": "explicit",
"source.organizeImports.biome": "explicit",
"source.removeUnusedImports": "explicit"
}
}

5
CONTRIBUTORS.md Normal file
View file

@ -0,0 +1,5 @@
# Contributors
Thanks to everyone who has helped make Revenge Next better!
- Rosie (ressurexitcalcator)

621
LICENSE Normal file
View file

@ -0,0 +1,621 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS

122
README.md Normal file
View file

@ -0,0 +1,122 @@
<p align="center">
<picture>
<source
width="512px"
media="(prefers-color-scheme: dark)"
srcset="assets/wordmark/wordmark+slogan-dark.svg"
>
<img
width="512px"
src="assets/wordmark/wordmark+slogan-light.svg"
>
</picture>
<br>
<a href="https://discord.com/invite/ddcQf3s2Uq">
<picture>
<source height="32px" media="(prefers-color-scheme: dark)" srcset="https://user-images.githubusercontent.com/13122796/178032563-d4e084b7-244e-4358-af50-26bde6dd4996.png" />
<img height="32px" src="https://user-images.githubusercontent.com/13122796/178032563-d4e084b7-244e-4358-af50-26bde6dd4996.png" />
</picture>
</a>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
<a href="https://github.com/revenge-mod">
<picture>
<source height="32px" media="(prefers-color-scheme: dark)" srcset="https://i.ibb.co/dMMmCrW/Git-Hub-Mark.png" />
<img height="32px" src="https://i.ibb.co/9wV3HGF/Git-Hub-Mark-Light.png" />
</picture>
</a>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
</a>
</p>
# Revenge
**Discord, your way.** Revenge is a client modification for Discord Android.
Revenge aims to be a lightweight and lightning-fast client modification for Discord Android, while being user-friendly and developer-first. It provides a powerful framework, allowing developers to make add-ons with ease. The sky is the limit!
## ❓ About
This repository releases Hermes Bytecode to be executed on official Discord Android clients. The bytecode is not standalone and is meant to be used with official bootstrappers listed in the [⬇️ Download](#️-download) section.
## 💪 Features
- **🔌 Plugins**: Extend Discord with custom features
- **🎨 Themes & Fonts**: Customize Discord's appearance to your liking
- **🧪 Experiments**: Try out Discord's new features before they're rolled out
## ⬇️ Download
These are the official Revenge ways to install Revenge:
- **📵 Non-root**: [Revenge Manager](https://github.com/revenge-mod/revenge-manager/releases/latest)
- **🩹 Root with Xposed**: [RevengeXposed](https://github.com/revenge-mod/revenge-xposed/releases/latest)
Using the installation methods above will currently install [Revenge Classic](https://github.com/revenge-mod/revenge-bundle). You'll need to update from Revenge Classic to Revenge Next manually.
### ⬆️ Updating to Revenge Next
> **It is recommended to do a separate installation of Revenge before updating to Revenge Next.**
> Revenge Next does not offer an easy way to downgrade to Revenge Classic.
To update to Revenge Next from Revenge Classic, follow these steps:
1. Download the latest release asset from [Revenge Next's Actions tab](https://github.com/revenge-mod/revenge-bundle-next/actions/workflows/build.yml).
2. Extract the built bundle and host a local HTTP server that serves the `revenge.bundle` file.
3. In Revenge Classic, go to **Settings** > **Revenge**, and toggle on **Developer Settings**.
4. Navigate back, and head into the **Developer** section.
5. Edit the **Load from custom URL** field to point to the URL of the `revenge.bundle` file you hosted.
6. Restart Discord, and you should be running Revenge Next!
### 🔄️ Updating builds
Revenge Next is updated regularly with new features and bug fixes. To update to the latest build, follow these steps:
1. Host a HTTP server that points to a new `revenge.bundle` file.
2. Head to **Settings** > **Developer** (under the **Revenge** section).
3. Tap on the **Evaluate JavaScript** option.
4. Paste and evaluate the following snippet. Make sure to modify the URL to point to your newly hosted `revenge.bundle` file:
```js
var REVENGE_UPDATE_URL = "<URL here, keep the quotes>";
revenge.discord.native.FileModule.writeFile("documents", "pyoncord/loader.json", JSON.stringify({"customLoadUrl":{"enabled":true,"url":REVENGE_UPDATE_URL}}), "utf8");
"URL updated, please reload Revenge"
```
5. Restart Discord.
## 👷 Developing with Revenge Next
You'll need to have [Bun](https://bun.com/) installed. Once you have Bun, follow these steps:
```sh
# Install dependencies
bun install
```
---
```sh
# Build Revenge Next
bun run build
# Build Revenge Next with debugging enabled (slow, don't use in production)
bun run build --dev
```
```sh
# Start the development server
bun run dev
# Build as production
bun run dev --prod
```
<sub>Builds are generated at `dist/revenge.bundle`.</sub>
```sh
# Build types for external consumers
bun run types
```
<sub>Types are generated at `dist/types`. To consume, include `<dir>/globals.d.ts`, and map `@revenge-mod/*` to `<dir>/lib/*`.</sub>
<br>
<sub>Bundlers will need to map imports to property access on `revenge` turning `kebab-case` and `snake_case` to `camelCase`.</sub>
<sub>Example: `@revenge-mod/discord/modules/main_tabs_v2` to `revenge.discord.modules.mainTabsV2`</sub>

View file

@ -0,0 +1,4 @@
<svg width="320" height="320" viewBox="0 0 320 320" fill="none" xmlns="http://www.w3.org/2000/svg">
<path fill-rule="evenodd" clip-rule="evenodd" d="M9.26979 99H294.723L312.234 215.273C312.723 222.597 310.021 229.993 304.839 235.184L265.514 274.935C260.741 279.717 254.27 283.273 247.514 283.273H182.785C168.723 283.273 152.981 270.126 152.981 256.073V255.61C152.981 250.056 156.895 244.851 160.088 240.605L160.088 240.605L160.288 240.339L75.9944 236.224C73.9944 236.135 69.0077 236.055 62.9899 235.984C43.5233 235.762 27.1144 221.37 24.4033 202.09L8.74994 103.006C8.84706 101.648 9.02178 100.311 9.26979 99ZM84.5458 137.592L139.983 152.446C139.994 152.788 140 153.132 140 153.477C140 170.045 126.568 183.477 110 183.477C93.4314 183.477 79.9999 170.045 79.9999 153.477C79.9999 147.643 81.665 142.198 84.5458 137.592ZM180.019 152.4L235.429 137.553C238.325 142.168 240 147.627 240 153.477C240 170.045 226.568 183.477 210 183.477C193.431 183.477 180 170.045 180 153.477C180 153.116 180.006 152.757 180.019 152.4Z" fill="white"/>
<path fill-rule="evenodd" clip-rule="evenodd" d="M288.328 82.0258C288.569 83.4188 289.198 84.7073 290.018 85.8593C292.71 89.6425 294.372 94.0776 294.688 98.766L295.899 106.809C296.628 111.647 292.881 116 287.988 116H17.6382C13.7018 116 10.3504 113.136 9.73617 109.248L8.89299 103.911C8.79798 103.31 8.76815 102.697 8.82742 102.091C10.4271 85.7347 23.3039 72.6711 39.7278 70.9082L87.1856 63.328C89.9772 62.8821 92.7967 63.9426 94.6025 66.1175L105.915 79.7431C107.719 81.9152 110.533 82.9759 113.322 82.5343L203.656 68.2267C205.851 67.8792 207.802 66.6347 209.042 64.7913L222.878 44.2296C224.116 42.3892 226.063 41.1457 228.253 40.7958L247.639 37.6994C265.683 35.7705 282.181 48.0371 285.523 65.8683L288.328 82.0258Z" fill="white"/>
</svg>

After

Width:  |  Height:  |  Size: 1.7 KiB

View file

@ -0,0 +1,4 @@
<svg width="320" height="320" viewBox="0 0 320 320" fill="none" xmlns="http://www.w3.org/2000/svg">
<path fill-rule="evenodd" clip-rule="evenodd" d="M9.26979 99H294.723L312.234 215.273C312.723 222.597 310.021 229.993 304.839 235.184L265.514 274.935C260.741 279.717 254.27 283.273 247.514 283.273H182.785C168.723 283.273 152.981 270.126 152.981 256.073V255.61C152.981 250.056 156.895 244.851 160.088 240.605L160.088 240.605L160.288 240.339L75.9944 236.224C73.9944 236.135 69.0077 236.055 62.9899 235.984C43.5233 235.762 27.1144 221.37 24.4033 202.09L8.74994 103.006C8.84706 101.648 9.02178 100.311 9.26979 99ZM84.5458 137.592L139.983 152.446C139.994 152.788 140 153.132 140 153.477C140 170.045 126.568 183.477 110 183.477C93.4314 183.477 79.9999 170.045 79.9999 153.477C79.9999 147.643 81.665 142.198 84.5458 137.592ZM180.019 152.4L235.429 137.553C238.325 142.168 240 147.627 240 153.477C240 170.045 226.568 183.477 210 183.477C193.431 183.477 180 170.045 180 153.477C180 153.116 180.006 152.757 180.019 152.4Z" fill="black"/>
<path fill-rule="evenodd" clip-rule="evenodd" d="M288.328 82.0258C288.569 83.4188 289.198 84.7073 290.018 85.8593C292.71 89.6425 294.372 94.0776 294.688 98.766L295.899 106.809C296.628 111.647 292.881 116 287.988 116H17.6382C13.7018 116 10.3504 113.136 9.73617 109.248L8.89299 103.911C8.79798 103.31 8.76815 102.697 8.82742 102.091C10.4271 85.7347 23.3039 72.6711 39.7278 70.9082L87.1856 63.328C89.9772 62.8821 92.7967 63.9426 94.6025 66.1175L105.915 79.7431C107.719 81.9152 110.533 82.9759 113.322 82.5343L203.656 68.2267C205.851 67.8792 207.802 66.6347 209.042 64.7913L222.878 44.2296C224.116 42.3892 226.063 41.1457 228.253 40.7958L247.639 37.6994C265.683 35.7705 282.181 48.0371 285.523 65.8683L288.328 82.0258Z" fill="black"/>
</svg>

After

Width:  |  Height:  |  Size: 1.7 KiB

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 19 KiB

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 19 KiB

113
biome.json Normal file
View file

@ -0,0 +1,113 @@
{
"$schema": "https://biomejs.dev/schemas/2.5.6/schema.json",
"assist": {
"actions": {
"source": {
"organizeImports": {
"level": "on",
"options": {
"groups": [
{
"type": false
}
]
}
}
}
},
"enabled": true
},
"files": {
"includes": [
"**/*.js",
"**/*.json",
"**/*.ts",
"**/*.tsx",
"**/*.jsx",
"**/*.mjs"
],
"ignoreUnknown": true
},
"formatter": {
"useEditorconfig": true
},
"javascript": {
"formatter": {
"arrowParentheses": "asNeeded",
"enabled": true,
"quoteProperties": "asNeeded",
"quoteStyle": "single",
"semicolons": "asNeeded",
"trailingCommas": "all"
}
},
"json": {
"parser": {
"allowComments": true,
"allowTrailingCommas": true
}
},
"linter": {
"enabled": true,
"rules": {
"preset": "recommended",
"a11y": {
"useKeyWithClickEvents": {
"level": "off"
}
},
"complexity": {
"noBannedTypes": {
"level": "warn"
},
"noCommaOperator": {
"level": "off"
},
"useArrowFunction": {
"level": "warn"
}
},
"performance": {
"noDelete": {
"level": "warn"
}
},
"style": {
"noNonNullAssertion": {
"level": "off"
},
"useImportType": {
"level": "warn",
"options": {
"style": "separatedType"
}
},
"useNodejsImportProtocol": {
"level": "off"
},
"useTemplate": {
"level": "warn"
}
},
"suspicious": {
"noAssignInExpressions": {
"level": "off"
},
"noConfusingVoidType": {
"level": "off"
},
"noExplicitAny": {
"level": "off"
},
"useIterableCallbackReturn": {
"level": "off"
}
}
}
},
"vcs": {
"clientKind": "git",
"enabled": true,
"useIgnoreFile": true
}
}

591
bun.lock Normal file
View file

@ -0,0 +1,591 @@
{
"lockfileVersion": 1,
"configVersion": 1,
"workspaces": {
"": {
"name": "@revenge-mod/revenge",
"dependencies": {
"@revenge-mod/assets": "workspace:*",
"@revenge-mod/components": "workspace:*",
"@revenge-mod/discord": "workspace:*",
"@revenge-mod/externals": "workspace:*",
"@revenge-mod/json-storage": "workspace:*",
"@revenge-mod/modules": "workspace:*",
"@revenge-mod/patcher": "workspace:*",
"@revenge-mod/plugins": "workspace:*",
"@revenge-mod/react": "workspace:*",
"@revenge-mod/utils": "workspace:*",
"@swc/core": "^1.15.43",
"chalk": "^6.0.0",
"hermes-compiler": "250829098.0.15",
"magic-string": "^1.1.0",
"react-native-click-outside": "^0.1.1",
"rolldown": "1.2.1",
},
"devDependencies": {
"@biomejs/biome": "^2.5.5",
"@parcel/watcher": "^2.6.0",
"@react-native-clipboard/clipboard": "^1.16.3",
"@types/bun": "^1.3.14",
"react-native-safe-area-context": "^5.8.0",
"rolldown-plugin-dts": "^0.27.14",
},
"peerDependencies": {
"@react-navigation/core": "^7.14.0",
"@react-navigation/native": "^7.1.28",
"@react-navigation/stack": "^7.7.2",
"@shopify/flash-list": "2.3.2",
"@types/node": "^25.9.2",
"@types/react": "^19.2.17",
"buffer": "^6.0.3",
"react": "19.1.0",
"react-native": "0.86.0",
"typescript": "^7.0.2",
},
},
"lib/assets": {
"name": "@revenge-mod/assets",
},
"lib/components": {
"name": "@revenge-mod/components",
},
"lib/discord": {
"name": "@revenge-mod/discord",
},
"lib/externals": {
"name": "@revenge-mod/externals",
},
"lib/json-storage": {
"name": "@revenge-mod/json-storage",
},
"lib/modules": {
"name": "@revenge-mod/modules",
},
"lib/patcher": {
"name": "@revenge-mod/patcher",
},
"lib/plugins": {
"name": "@revenge-mod/plugins",
},
"lib/react": {
"name": "@revenge-mod/react",
},
"lib/utils": {
"name": "@revenge-mod/utils",
},
},
"trustedDependencies": [
"@biomejs/biome",
"@swc/core",
"@parcel/watcher",
],
"patchedDependencies": {
"react-native-click-outside@0.1.1": "patches/react-native-click-outside@0.1.1.patch",
},
"overrides": {
"@react-native/codegen": "npm:dry-uninstall",
"@react-native/community-cli-plugin": "npm:dry-uninstall",
"babel-jest": "npm:dry-uninstall",
"babel-plugin-syntax-hermes-parser": "npm:dry-uninstall",
"jsc-android": "npm:dry-uninstall",
"react-devtools-core": "npm:dry-uninstall",
"react-native-gesture-handler": "npm:dry-uninstall",
"react-native-screens": "npm:dry-uninstall",
"recyclerlistview": "npm:dry-uninstall",
},
"packages": {
"@babel/code-frame": ["@babel/code-frame@7.29.7", "", { "dependencies": { "@babel/helper-validator-identifier": "^7.29.7", "js-tokens": "^4.0.0", "picocolors": "^1.1.1" } }, "sha512-Aup7aUOfpbAUg2ROOJN6Iw5f9DMBlzu0mIkm/malLQFN/YQgO48wCj0Kxa3sEHJvPVFg7siR+qRInwXd2qhQKw=="],
"@babel/generator": ["@babel/generator@7.29.7", "", { "dependencies": { "@babel/parser": "^7.29.7", "@babel/types": "^7.29.7", "@jridgewell/gen-mapping": "^0.3.12", "@jridgewell/trace-mapping": "^0.3.28", "jsesc": "^3.0.2" } }, "sha512-DkXD5OJQaAQIdZ1bt3UZdEnHAn9Imd3IVBdX03UFe+ony9Ojw5pzr9YVKGDY1jt+Gcn/FnGkNf8r+Vj5NOJWtQ=="],
"@babel/helper-globals": ["@babel/helper-globals@7.29.7", "", {}, "sha512-3nQVUAtvkKH9zahfWgw96Jc/uFOmjACE1kQz82E2lqWmHBgjzbNlsC22nuQTfahmWeQtTq5nQ/4Nnd2A1wj4zA=="],
"@babel/helper-string-parser": ["@babel/helper-string-parser@7.29.7", "", {}, "sha512-Pb5ijPrZ89GDH8223L4UP8i6QApWxs04RbPQJTeWDV0/keR2E36MeKnyr6LYmUUvqRRI+Iv87SuF1W6ErINzYw=="],
"@babel/helper-validator-identifier": ["@babel/helper-validator-identifier@7.29.7", "", {}, "sha512-qehxGkRj55h/ff8EMaJ+cYhyaKlHIxqYDn682wQD7RNp9UujOQsHog2uS0r2vzr4pW+sXf90NeeayjcNaX3fFg=="],
"@babel/parser": ["@babel/parser@7.29.7", "", { "dependencies": { "@babel/types": "^7.29.7" }, "bin": "./bin/babel-parser.js" }, "sha512-hnORnjP/1P/zFEndoeX+n+t1RwWRJiJpM/jO7FW32Kn9r5+sJB2JWOdYo4L6k78j15eCwY3Gm/7364B1EMwtNg=="],
"@babel/runtime": ["@babel/runtime@8.0.0", "", {}, "sha512-sL6cvO2IfkSu/iU+zs2S/w01B7A8V7suXSIKEN4hPFFdZoiPGxrj5pAG0lCaqLWiEIrjKzdznIWuaLcxPR53qw=="],
"@babel/template": ["@babel/template@7.29.7", "", { "dependencies": { "@babel/code-frame": "^7.29.7", "@babel/parser": "^7.29.7", "@babel/types": "^7.29.7" } }, "sha512-puq+Gf35oI24FeN11LkoUQFqv9uwNeWpxXZi/Ji3rRIoKAzKnxRaZ+Gkj0vKS9ZCiTESfng1N9LyOyXvo+m+Gg=="],
"@babel/traverse": ["@babel/traverse@7.29.7", "", { "dependencies": { "@babel/code-frame": "^7.29.7", "@babel/generator": "^7.29.7", "@babel/helper-globals": "^7.29.7", "@babel/parser": "^7.29.7", "@babel/template": "^7.29.7", "@babel/types": "^7.29.7", "debug": "^4.3.1" } }, "sha512-EhlfNQtZ+NK22w5BM61ciuiq1m58ed33Wr1Xan//ZRTy6hgjnwyCffRYwzsGXdASJSUJ1guZILsErh1eQcl+zw=="],
"@babel/types": ["@babel/types@7.29.7", "", { "dependencies": { "@babel/helper-string-parser": "^7.29.7", "@babel/helper-validator-identifier": "^7.29.7" } }, "sha512-4zBIxpPzowiZpusoFkyGVwakdRJUyuH5PxQ/PrqghfdFWWasvnCdPfQXHrenDai+gyLARulZjZowCOj6fjT4pA=="],
"@biomejs/biome": ["@biomejs/biome@2.5.6", "", { "optionalDependencies": { "@biomejs/cli-darwin-arm64": "2.5.6", "@biomejs/cli-darwin-x64": "2.5.6", "@biomejs/cli-linux-arm64": "2.5.6", "@biomejs/cli-linux-arm64-musl": "2.5.6", "@biomejs/cli-linux-x64": "2.5.6", "@biomejs/cli-linux-x64-musl": "2.5.6", "@biomejs/cli-win32-arm64": "2.5.6", "@biomejs/cli-win32-x64": "2.5.6" }, "bin": { "biome": "bin/biome" } }, "sha512-lxVNjv7UF6KfhMJfL9gaUHbWdJdHbsAj6OSmwSYNdhRuG67NxNQ4Xdvh3TUxsSK9sBzJBQhEJj3AopmmNJ5pSA=="],
"@biomejs/cli-darwin-arm64": ["@biomejs/cli-darwin-arm64@2.5.6", "", { "os": "darwin", "cpu": "arm64" }, "sha512-zMOLZP4oMrjh6m1zcSj1ud2awUPgTuMVbmQhYYWL7J8HwCnbHHBvTm7VBTRuY7epT5bez76IpKYQ11ZAqHFlnw=="],
"@biomejs/cli-darwin-x64": ["@biomejs/cli-darwin-x64@2.5.6", "", { "os": "darwin", "cpu": "x64" }, "sha512-JAC1VqzvO7Th5ZplU0G2uGfkZbxEe9uDDektPAhF0JLusoz1w+T4okp2bkykI0bbaO2vslKiRfj4gU43JaGreA=="],
"@biomejs/cli-linux-arm64": ["@biomejs/cli-linux-arm64@2.5.6", "", { "os": "linux", "cpu": "arm64" }, "sha512-6XsYwCFkp5sMxl85ffhgeGpGgs6A7dRYFnkceZ7WVxvycuTnGdD5xa534Z3xfrBQ0JCMK/mujT6ZNPJoghedwg=="],
"@biomejs/cli-linux-arm64-musl": ["@biomejs/cli-linux-arm64-musl@2.5.6", "", { "os": "linux", "cpu": "arm64" }, "sha512-eUa3jeeYvfMt19LBeh6E5PUZpxnTC4JqNWo+EDjTtQjAr2xLGnWaxACtVU1DQqmHYbvThlJzLX+ZsYgrqh2qVw=="],
"@biomejs/cli-linux-x64": ["@biomejs/cli-linux-x64@2.5.6", "", { "os": "linux", "cpu": "x64" }, "sha512-Pop9VXCFUhFTMfFefZ39S+u2rOPyNp5iHlxbZRwXGACHLy2r0jjiRgJHmaEKJzL3SyxlVeGShXhvvElvWowonA=="],
"@biomejs/cli-linux-x64-musl": ["@biomejs/cli-linux-x64-musl@2.5.6", "", { "os": "linux", "cpu": "x64" }, "sha512-2Vp13QdKysH3HIWLaYLhUUwbK+jbZonJD1K+Lr0d0RO4wH7mkYd43vJixEDm8cUWrowoRz4UUHF1nm9Ae7ym8A=="],
"@biomejs/cli-win32-arm64": ["@biomejs/cli-win32-arm64@2.5.6", "", { "os": "win32", "cpu": "arm64" }, "sha512-tDGshcm6BdkZOCGnTDX0Y8/U4IfBSlnUU7T56nNDuPEfed+aHg+u8G36NB43fJVl0Os6+QURXIE1yuD7AaEofA=="],
"@biomejs/cli-win32-x64": ["@biomejs/cli-win32-x64@2.5.6", "", { "os": "win32", "cpu": "x64" }, "sha512-WN05KwXnTO/2J45RQPvzZMXf7tZUIofHoR35xIPfCo7pQ2RFidxI8sfb5mGsaTxdMmEOzHzOPRCdA5/fCpc7xQ=="],
"@emnapi/core": ["@emnapi/core@2.0.0-alpha.3", "", { "dependencies": { "@emnapi/wasi-threads": "2.0.1", "tslib": "^2.4.0" } }, "sha512-AZypUeJ/yByuxyS7BlSNRDOMLMlROYtjYdIAuBmJssVz1UJDSeYxLrdizhXCFYhedC5bqd/ASy8EuNXbVVXp9g=="],
"@emnapi/runtime": ["@emnapi/runtime@2.0.0-alpha.3", "", { "dependencies": { "tslib": "^2.4.0" } }, "sha512-hFPAhMUjJD9BSyCANEISPOogeXC9Zo9ZQl7L6vKnaVsMkCtzznaW/naYypeyl0Gv5rYfWYsZbpixTMpjDJzQeA=="],
"@emnapi/wasi-threads": ["@emnapi/wasi-threads@2.0.1", "", { "dependencies": { "tslib": "^2.4.0" } }, "sha512-9DsSk+o5NBX0CCJT8s0EROGSGxjR/tKu6aBTaVyq+SjAEQH4XcdcRxPBRzsBLizTTJ49MJjF+jgu3qnO9GLQcQ=="],
"@jest/schemas": ["@jest/schemas@29.6.3", "", { "dependencies": { "@sinclair/typebox": "^0.27.8" } }, "sha512-mo5j5X+jIZmJQveBKeS/clAueipV7KgiX1vMgCxam1RNYiqE1w62n0/tJJnHtjW8ZHcQco5gY85jA3mi0L+nSA=="],
"@jridgewell/gen-mapping": ["@jridgewell/gen-mapping@0.3.13", "", { "dependencies": { "@jridgewell/sourcemap-codec": "^1.5.0", "@jridgewell/trace-mapping": "^0.3.24" } }, "sha512-2kkt/7niJ6MgEPxF0bYdQ6etZaA+fQvDcLKckhy1yIQOzaoKjBBjSj63/aLVjYE3qhRt5dvM+uUyfCg6UKCBbA=="],
"@jridgewell/resolve-uri": ["@jridgewell/resolve-uri@3.1.2", "", {}, "sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw=="],
"@jridgewell/sourcemap-codec": ["@jridgewell/sourcemap-codec@1.5.5", "", {}, "sha512-cYQ9310grqxueWbl+WuIUIaiUaDcj7WOq5fVhEljNVgRfOUhY9fy2zTvfoqWsnebh8Sl70VScFbICvJnLKB0Og=="],
"@jridgewell/trace-mapping": ["@jridgewell/trace-mapping@0.3.31", "", { "dependencies": { "@jridgewell/resolve-uri": "^3.1.0", "@jridgewell/sourcemap-codec": "^1.4.14" } }, "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw=="],
"@napi-rs/wasm-runtime": ["@napi-rs/wasm-runtime@1.2.0", "", { "dependencies": { "@tybys/wasm-util": "^0.10.3" }, "peerDependencies": { "@emnapi/core": "^2.0.0-alpha.3", "@emnapi/runtime": "^2.0.0-alpha.3" } }, "sha512-kDoONqMa+VnZ4vvvu/ZUurpJ4gkZU57e7g69qpNgWhYcZFPUHZM2CEMKm+cG6ufDVALbjMvfmMjFVqaK7uEMnA=="],
"@oxc-project/types": ["@oxc-project/types@0.142.0", "", {}, "sha512-7W+2q5AKQVU36fkaryontrHn3YDt1RyUYXatw9i5H8ocYe2sPKSFB6eS8WNPeRKiN1qAWWZUPm7gwFzJGrccqQ=="],
"@parcel/watcher": ["@parcel/watcher@2.6.0", "", { "dependencies": { "detect-libc": "^2.0.3", "is-glob": "^4.0.3", "node-addon-api": "^7.0.0", "picomatch": "^4.0.4" }, "optionalDependencies": { "@parcel/watcher-android-arm64": "2.6.0", "@parcel/watcher-darwin-arm64": "2.6.0", "@parcel/watcher-darwin-x64": "2.6.0", "@parcel/watcher-freebsd-x64": "2.6.0", "@parcel/watcher-linux-arm-glibc": "2.6.0", "@parcel/watcher-linux-arm-musl": "2.6.0", "@parcel/watcher-linux-arm64-glibc": "2.6.0", "@parcel/watcher-linux-arm64-musl": "2.6.0", "@parcel/watcher-linux-x64-glibc": "2.6.0", "@parcel/watcher-linux-x64-musl": "2.6.0", "@parcel/watcher-win32-arm64": "2.6.0", "@parcel/watcher-win32-x64": "2.6.0" } }, "sha512-7FNeNl8NCE7aINx7WXiKQrPYZWC/hvrTsmk6zmxbI7LTXE7hVek/n8AfVgpe2y82zl3w0HvCHN0bVKMBoJcC0w=="],
"@parcel/watcher-android-arm64": ["@parcel/watcher-android-arm64@2.6.0", "", { "os": "android", "cpu": "arm64" }, "sha512-trgpLSCKRC/huFjXX/Smh+0sWe4+YtKfktIToiMl59ghz7z+qkH6kMvNnUbLyRs9N11t8l4svSCs1+5B3rOAhA=="],
"@parcel/watcher-darwin-arm64": ["@parcel/watcher-darwin-arm64@2.6.0", "", { "os": "darwin", "cpu": "arm64" }, "sha512-Y3QV0gl7Q1zbfueunkWIERICbEojQFCgpyG7YqOGNFLsckXyI1xu9mAIUpKY9QBYzBtSkN8dBPwd3yiAO9ovMw=="],
"@parcel/watcher-darwin-x64": ["@parcel/watcher-darwin-x64@2.6.0", "", { "os": "darwin", "cpu": "x64" }, "sha512-Ohv6OpzhUfKYD7Beb8kDvG0jbIxORCYY1JRdZnaBtnjjkJxgD7ZVL0nw2sCYd0yTMKTvz3nnTnOF3cDifK+kvw=="],
"@parcel/watcher-freebsd-x64": ["@parcel/watcher-freebsd-x64@2.6.0", "", { "os": "freebsd", "cpu": "x64" }, "sha512-5HmXvDgs8VK+74jF9y9/2FE3/OnlcKmc56tjmSrEuZjpSZOGL+fvAu+HKJBdPs9uwoP2hE6TlSUpXZ/C5jUFmQ=="],
"@parcel/watcher-linux-arm-glibc": ["@parcel/watcher-linux-arm-glibc@2.6.0", "", { "os": "linux", "cpu": "arm" }, "sha512-Ps/hui3A+vMbjdqlqAowK2ZL8+BO8dBjxeWXj6npTBs3jx4wWmbPpaLuqwrQrSqIVMCnpWo238bJ1U37GhQOYg=="],
"@parcel/watcher-linux-arm-musl": ["@parcel/watcher-linux-arm-musl@2.6.0", "", { "os": "linux", "cpu": "arm" }, "sha512-9c6AUHgHoG+IY88MRIHupztQiQnrbqHYQjkM2btA+Bf/wQnQMuiD0Wfk1EVv3TlNT3x41uU71rn6E4xh/+zvkw=="],
"@parcel/watcher-linux-arm64-glibc": ["@parcel/watcher-linux-arm64-glibc@2.6.0", "", { "os": "linux", "cpu": "arm64" }, "sha512-yHRqS2owEXe6Hic9z6Mh1ECsCd+ODVOGvZDyciqRd21+v+o+DnXMOrw50DSpIG2sb8GPEaPPmfeCAWKPJdq46g=="],
"@parcel/watcher-linux-arm64-musl": ["@parcel/watcher-linux-arm64-musl@2.6.0", "", { "os": "linux", "cpu": "arm64" }, "sha512-WhB2e/V7rqdHHWZusBSPuy5Ei8S6lSz6FE5TKKQz5h3a0O+C+mhY7vxU9b/stqvMb8beLnPY82ZrFTLKs+SrKA=="],
"@parcel/watcher-linux-x64-glibc": ["@parcel/watcher-linux-x64-glibc@2.6.0", "", { "os": "linux", "cpu": "x64" }, "sha512-ulGE6x6Oz6iAwg75T8YQSoguBWasniIbX+QWpaYPcCnDOpdWX3k+4xbEYPZVLxOuoJI+svJJPD3sEj8G7lrQ3A=="],
"@parcel/watcher-linux-x64-musl": ["@parcel/watcher-linux-x64-musl@2.6.0", "", { "os": "linux", "cpu": "x64" }, "sha512-tkBYKt7YQrjIJWYDnto2YgO8MRkjlMTSNoRHzsXinBqbLdeOM3L32wPZJvIZxqaLMfSlS/4sUjH/6STVP/XDLw=="],
"@parcel/watcher-win32-arm64": ["@parcel/watcher-win32-arm64@2.6.0", "", { "os": "win32", "cpu": "arm64" }, "sha512-gIZAP23jaHjGWasY/TY6yL7NHFClf0Ga7FN+iINvk+KN94rhm94lYZhFsbYFNcA04/onvGD9kKmiJLJB2HbNwQ=="],
"@parcel/watcher-win32-x64": ["@parcel/watcher-win32-x64@2.6.0", "", { "os": "win32", "cpu": "x64" }, "sha512-cA+/pXV2YkfxlIcXOQ5fSWqAzzPyD78/x5qbK/I0vUkrlYHA8TIz+MXjAbGouguKVSI4bOmkTSJ1/poVSsgt+A=="],
"@react-native-clipboard/clipboard": ["@react-native-clipboard/clipboard@1.16.3", "", { "peerDependencies": { "react": ">= 16.9.0", "react-native": ">= 0.61.5", "react-native-macos": ">= 0.61.0", "react-native-windows": ">= 0.61.0" }, "optionalPeers": ["react-native-macos", "react-native-windows"] }, "sha512-cMIcvoZKIrShzJHEaHbTAp458R9WOv0fB6UyC7Ek4Qk561Ow/DrzmmJmH/rAZg21Z6ixJ4YSdFDC14crqIBmCQ=="],
"@react-native/assets-registry": ["@react-native/assets-registry@0.86.0", "", {}, "sha512-nIaXbm2jX1OTYp0qbviJ3O6KZivoE8z3BnhUQ2LsqfZSWRoOK/n1qsiAr6oALiNKWnXY3j2KPwtYORnZzp8xew=="],
"@react-native/codegen": ["dry-uninstall@0.3.0", "", {}, "sha512-b8h94RVpETWkVV59x62NsY++79bM7Si6Dxq7a4iVxRcJU3ZJJ4vaiC7wUZwM8WDK0ySRL+i+T/1SMAzbJLejYA=="],
"@react-native/community-cli-plugin": ["dry-uninstall@0.3.0", "", {}, "sha512-b8h94RVpETWkVV59x62NsY++79bM7Si6Dxq7a4iVxRcJU3ZJJ4vaiC7wUZwM8WDK0ySRL+i+T/1SMAzbJLejYA=="],
"@react-native/gradle-plugin": ["@react-native/gradle-plugin@0.86.0", "", {}, "sha512-a1RcfaEDqWExCGfCwadIxt4l8FvKYgFqeMf2uzeKyAOnb+vTGNIeCvifFL2MqvgaeYxlER437HbMIajGcuJ1pQ=="],
"@react-native/js-polyfills": ["@react-native/js-polyfills@0.86.0", "", {}, "sha512-zYy/Cjd1VTnZ2iCNaG9bDF9C3l2ntESiPRscjIlI5FKugu6aeTwsDSv1aI8Bc4Kp3vEdoVg+UQhLAhE4svREaQ=="],
"@react-native/normalize-colors": ["@react-native/normalize-colors@0.86.0", "", {}, "sha512-kG0wfCGghUKlfxkJyyHCDVutWVYWK7/DG58ojA/4v9EfulgF+osuSQmlbNb3rcKX58qutm7JcldSeVLgGFha9g=="],
"@react-native/virtualized-lists": ["@react-native/virtualized-lists@0.86.0", "", { "dependencies": { "invariant": "^2.2.4", "nullthrows": "^1.1.1" }, "peerDependencies": { "@types/react": "^19.2.0", "react": "*", "react-native": "0.86.0" }, "optionalPeers": ["@types/react"] }, "sha512-4/ZLXdf/OSpPDVO0AsQ1SJdRIzt5t9BNQ46QwGgxvX7/cirYR5k8KXctNGGgW8lQo2gZChEfY2zFCZg9nM/jiw=="],
"@react-navigation/core": ["@react-navigation/core@7.21.11", "", { "dependencies": { "@react-navigation/routers": "^7.6.4", "escape-string-regexp": "^4.0.0", "fast-deep-equal": "^3.1.3", "nanoid": "^3.3.11", "query-string": "^7.1.3", "react-is": "^19.1.0", "use-latest-callback": "^0.2.4", "use-sync-external-store": "^1.5.0" }, "peerDependencies": { "react": ">= 18.2.0" } }, "sha512-bCW1PsLA/eOXDOukcJFEzlcL3Zpy8DJuDCfkDDwAQlAgoSZ/J9+ZeDRUMmCUi6xbnFgvFEEIMertaLeErOFP0Q=="],
"@react-navigation/elements": ["@react-navigation/elements@2.9.36", "", { "dependencies": { "color": "^4.2.3", "use-latest-callback": "^0.2.4", "use-sync-external-store": "^1.5.0" }, "peerDependencies": { "@react-native-masked-view/masked-view": ">= 0.2.0", "@react-navigation/native": "^7.3.14", "react": ">= 18.2.0", "react-native": "*", "react-native-safe-area-context": ">= 4.0.0" }, "optionalPeers": ["@react-native-masked-view/masked-view"] }, "sha512-+10x9s5v2Q7FwAYdSmPMgILtxZyC5e4hWJQu8g5o3u4p8DUToTBmGvys/UvmEr+h9xmm0Go42qw9Ff2ape53kQ=="],
"@react-navigation/native": ["@react-navigation/native@7.3.14", "", { "dependencies": { "@react-navigation/core": "^7.21.11", "escape-string-regexp": "^4.0.0", "fast-deep-equal": "^3.1.3", "nanoid": "^3.3.11", "standard-navigation": "^0.0.8", "use-latest-callback": "^0.2.4" }, "peerDependencies": { "react": ">= 18.2.0", "react-native": "*" } }, "sha512-hcKTDNBuuAA1/xW6QeKYmMPVhk5W9dKGQpPmn5dQeeePwMpu5OZ14NOgwKH0w9D3tg2jupojTcVL0tsx5DTFXg=="],
"@react-navigation/routers": ["@react-navigation/routers@7.6.4", "", { "dependencies": { "nanoid": "^3.3.11" } }, "sha512-GI7eJm8/KsZUQaYcXvEExikKurRZRgEsSzyZ7faENfi65yqJBCXjDMwyN1pF6pNW1MoLH1ErDwDivFxY6BzD3w=="],
"@react-navigation/stack": ["@react-navigation/stack@7.10.17", "", { "dependencies": { "@react-navigation/elements": "^2.9.36", "color": "^4.2.3", "use-latest-callback": "^0.2.4" }, "peerDependencies": { "@react-navigation/native": "^7.3.14", "react": ">= 18.2.0", "react-native": "*", "react-native-gesture-handler": ">= 2.0.0", "react-native-safe-area-context": ">= 4.0.0", "react-native-screens": ">= 4.0.0" } }, "sha512-2b/AC8YxfPkFsN8DZGjrMiX6G86unbEonE0E8dA5LugzfKF/s28VBM7yBwZKRsp3ys5aVCvt/Z3zviQA/uGAIA=="],
"@revenge-mod/assets": ["@revenge-mod/assets@workspace:lib/assets"],
"@revenge-mod/components": ["@revenge-mod/components@workspace:lib/components"],
"@revenge-mod/discord": ["@revenge-mod/discord@workspace:lib/discord"],
"@revenge-mod/externals": ["@revenge-mod/externals@workspace:lib/externals"],
"@revenge-mod/json-storage": ["@revenge-mod/json-storage@workspace:lib/json-storage"],
"@revenge-mod/modules": ["@revenge-mod/modules@workspace:lib/modules"],
"@revenge-mod/patcher": ["@revenge-mod/patcher@workspace:lib/patcher"],
"@revenge-mod/plugins": ["@revenge-mod/plugins@workspace:lib/plugins"],
"@revenge-mod/react": ["@revenge-mod/react@workspace:lib/react"],
"@revenge-mod/utils": ["@revenge-mod/utils@workspace:lib/utils"],
"@rolldown/binding-android-arm64": ["@rolldown/binding-android-arm64@1.2.1", "", { "os": "android", "cpu": "arm64" }, "sha512-02hOeOSryYxVrOIphmLAsqnCJWxwlzFk+pEt/N/i6OgT3lShHO7xGCU5cpgchRDHboAEbSjzgGh+O/u1GswQmA=="],
"@rolldown/binding-darwin-arm64": ["@rolldown/binding-darwin-arm64@1.2.1", "", { "os": "darwin", "cpu": "arm64" }, "sha512-fMsTOnN0OjFm3CyppWPitKnc8UlliVARUULW6cfU6AIqjdtgmSFWSk9vecHzZduv/yMWIHDlRhM1e8Iff9uAfA=="],
"@rolldown/binding-darwin-x64": ["@rolldown/binding-darwin-x64@1.2.1", "", { "os": "darwin", "cpu": "x64" }, "sha512-1wjKdz/XLGKHaTNHjQveQ/B23TKx4ItAqm1JbyVuvNPc4Ze0Fb48s49TAd/2zcplPl8okE/UbTgmlVfwT7eFeQ=="],
"@rolldown/binding-freebsd-x64": ["@rolldown/binding-freebsd-x64@1.2.1", "", { "os": "freebsd", "cpu": "x64" }, "sha512-Fa0jHR07E7YBN4vOEsbVf2briYNsuOowfLJaXULZM0ldMlaCaj2LJgLMbMe4iacRyZmvR8efFhgR9wKuGclQUg=="],
"@rolldown/binding-linux-arm-gnueabihf": ["@rolldown/binding-linux-arm-gnueabihf@1.2.1", "", { "os": "linux", "cpu": "arm" }, "sha512-pzkgu1SSHGgRRyRZ4fbmSgmajbVt+epaLP99NDjFft69v/ypfTi6swBMiVdh2EkQ0OSnHE1lZDM7DRGkyAzUpA=="],
"@rolldown/binding-linux-arm64-gnu": ["@rolldown/binding-linux-arm64-gnu@1.2.1", "", { "os": "linux", "cpu": "arm64" }, "sha512-QI5SEDY8cbiYWHx0VO4vIc3UlS6a32vXHjU8Qy/17adEmZIPuByJg13UEvo9c/UCiUkdcVWY83C+b+JrwnNyUg=="],
"@rolldown/binding-linux-arm64-musl": ["@rolldown/binding-linux-arm64-musl@1.2.1", "", { "os": "linux", "cpu": "arm64" }, "sha512-Sm41FyCeXqmYcERoYOCbGIL5hNfd8w9LQ7Y61Bev48HkcjaJqV/iiVOaiDxjVTRMS+QKrZmD8cfPt4uMVnvM+A=="],
"@rolldown/binding-linux-ppc64-gnu": ["@rolldown/binding-linux-ppc64-gnu@1.2.1", "", { "os": "linux", "cpu": "ppc64" }, "sha512-2x+WhXTGl9yJYPbltW/BSEPTVz9OIWQyER4N+gJEDWkkn904eRcBzELqh/Hf7K0w/ubGbKNMv0ZC+94QK/IFEg=="],
"@rolldown/binding-linux-s390x-gnu": ["@rolldown/binding-linux-s390x-gnu@1.2.1", "", { "os": "linux", "cpu": "s390x" }, "sha512-eEjmQpuRQayHPWWnywaWHkFT3ToPbP3RYy42VVd/B9aBGDA+Ol25EIWHxKQST3IiWJjikCWUF7KtbfqwZrzVwQ=="],
"@rolldown/binding-linux-x64-gnu": ["@rolldown/binding-linux-x64-gnu@1.2.1", "", { "os": "linux", "cpu": "x64" }, "sha512-/Orga1fZYkLc/56jBICcHrKchl8Z2UKdDSr3LG9ToWO1lQ6a4Livk9Xz+9WN91zsz5QR3XQz2NNoSDEvP6qadw=="],
"@rolldown/binding-linux-x64-musl": ["@rolldown/binding-linux-x64-musl@1.2.1", "", { "os": "linux", "cpu": "x64" }, "sha512-xxBJRL+0q0Kce7orznGWLuylHDY65vuARXZRpX+hPdv+DqK2c3NlCsVA98tlWzWNEE7yPqA/1NQ5nnCrj49Y5A=="],
"@rolldown/binding-openharmony-arm64": ["@rolldown/binding-openharmony-arm64@1.2.1", "", { "os": "none", "cpu": "arm64" }, "sha512-M6AdXIXw3s+/8XpKMzdGDEXGS1S7kwUsy+rcTIUIOx5Ge4nXKCtAFHFV9YKkXvGcC5WMoTjAteLzlsQROVI0Yw=="],
"@rolldown/binding-wasm32-wasi": ["@rolldown/binding-wasm32-wasi@1.2.1", "", { "dependencies": { "@emnapi/core": "2.0.0-alpha.3", "@emnapi/runtime": "2.0.0-alpha.3", "@napi-rs/wasm-runtime": "^1.2.0" } }, "sha512-/TX0SoRGojHzSAHpfVBbavRVSazg5U3h3Y3VXfcc0cdugq6kxdqw8LPGFiPr+/7gE/60zRcsOY2Vi9b9eT0jww=="],
"@rolldown/binding-win32-arm64-msvc": ["@rolldown/binding-win32-arm64-msvc@1.2.1", "", { "os": "win32", "cpu": "arm64" }, "sha512-EvRrivJieyHG+AO9lleZWgq+g0+S7oV2C51yuqlcyU/R9net+sI4Pj0F+lUoP2bEr6TWX3SqFaaS0SzfLxSzkw=="],
"@rolldown/binding-win32-x64-msvc": ["@rolldown/binding-win32-x64-msvc@1.2.1", "", { "os": "win32", "cpu": "x64" }, "sha512-Z4eCmn5QJ/5+azF9knpLWKfVd9aidn0mAe9TpJgvBLId9Ax3t0+JVxBmT25Bv7NBbVW1TZyKjQjQReouMeH5UQ=="],
"@rolldown/pluginutils": ["@rolldown/pluginutils@1.0.1", "", {}, "sha512-2j9bGt5Jh8hj+vPtgzPtl72j0yRxHAyumoo6TNfAjsLB04UtpSvPbPcDcBMxz7n+9CYB0c1GxQFxYRg2jimqGw=="],
"@shopify/flash-list": ["@shopify/flash-list@2.3.2", "", { "peerDependencies": { "@babel/runtime": "*", "react": "*", "react-native": "*" } }, "sha512-vQnd0y0Ag11yzS30llaeCrtIU3xYTMe7KEOP3dveLImnVjQEUw6BEg1+Ztja6aODlVNz1BpvxtlQ5eZGxiLwKw=="],
"@sinclair/typebox": ["@sinclair/typebox@0.27.12", "", {}, "sha512-hhyNJ+nbR6ZR7pToHvllEFun9TL0sbL+tk/ON75lo+Xas054uez98qRbsuNt7MBCyZKK4+8Yli/OAGZhmfBZ/g=="],
"@swc/core": ["@swc/core@1.15.47", "", { "dependencies": { "@swc/counter": "^0.1.3", "@swc/types": "^0.1.27" }, "optionalDependencies": { "@swc/core-darwin-arm64": "1.15.47", "@swc/core-darwin-x64": "1.15.47", "@swc/core-linux-arm-gnueabihf": "1.15.47", "@swc/core-linux-arm64-gnu": "1.15.47", "@swc/core-linux-arm64-musl": "1.15.47", "@swc/core-linux-ppc64-gnu": "1.15.47", "@swc/core-linux-s390x-gnu": "1.15.47", "@swc/core-linux-x64-gnu": "1.15.47", "@swc/core-linux-x64-musl": "1.15.47", "@swc/core-win32-arm64-msvc": "1.15.47", "@swc/core-win32-ia32-msvc": "1.15.47", "@swc/core-win32-x64-msvc": "1.15.47" }, "peerDependencies": { "@swc/helpers": ">=0.5.17" }, "optionalPeers": ["@swc/helpers"] }, "sha512-FbsO5JcfOjfH38W/rohBRBweJeERsAuIP4f377lmkmxTcq9exjtx4SkRuZY5CdfhR2CBVwDIJegBpJDffwNsOg=="],
"@swc/core-darwin-arm64": ["@swc/core-darwin-arm64@1.15.47", "", { "os": "darwin", "cpu": "arm64" }, "sha512-GsoMtan3ojGGMGFbl31mmRu5ctZ56re8grGE8mO/OHJ8O+JRkzod02fe7X6ZQ8JvamA3imkEkx/h3u+vsOgPgA=="],
"@swc/core-darwin-x64": ["@swc/core-darwin-x64@1.15.47", "", { "os": "darwin", "cpu": "x64" }, "sha512-leTi7Rx3KF4zcC637iqWgk9SoV8VXAD8ppQYXsep63px5A/UftOcxLN1pmr8Z1si/YvX90ompP/rHgpYkgwXWg=="],
"@swc/core-linux-arm-gnueabihf": ["@swc/core-linux-arm-gnueabihf@1.15.47", "", { "os": "linux", "cpu": "arm" }, "sha512-hBqHuoWKKIsKmDBn9qVeWqj5GWZhtlcczVaqQmNRXsDfq+voR5CxKRfamA367QjJXtceYuliLFfEL8QsskRM2g=="],
"@swc/core-linux-arm64-gnu": ["@swc/core-linux-arm64-gnu@1.15.47", "", { "os": "linux", "cpu": "arm64" }, "sha512-TBxvRz+B4K205TWHHZxWVxkC2RFNP/Mz3PNcECBos5PsKwxjg3QSJzdoebr0VCf0Bfh8HOPldKxAP/8XkFe9gA=="],
"@swc/core-linux-arm64-musl": ["@swc/core-linux-arm64-musl@1.15.47", "", { "os": "linux", "cpu": "arm64" }, "sha512-3Yu3Uq/VgytqsPjTMbkPU1ExADytbdWbruJYhA584E9jrpE2Ki+R6VVPoZCeAVk1Cb7QxcRTgblw6bSa6a/R+w=="],
"@swc/core-linux-ppc64-gnu": ["@swc/core-linux-ppc64-gnu@1.15.47", "", { "os": "linux", "cpu": "ppc64" }, "sha512-wfdMi5IaOaNtmh2/6geRoxIdNfqylUZFdtzTKS655y1axWfIWyx7As74vv0wVdjeCIZ3WmCI9odDd4rUttXOSQ=="],
"@swc/core-linux-s390x-gnu": ["@swc/core-linux-s390x-gnu@1.15.47", "", { "os": "linux", "cpu": "s390x" }, "sha512-3hHYBY0yx8Ez7GMRrkhXHQzMdR5IZA6Wq5Ee4svlgwvSECLpnAJ9+0AimEGUFDvuLwE7nV/2+PYe8+Nm4rvNcQ=="],
"@swc/core-linux-x64-gnu": ["@swc/core-linux-x64-gnu@1.15.47", "", { "os": "linux", "cpu": "x64" }, "sha512-TjfhjgP/jGCfFHYC3JQPhJA1HwErbIJ9JfREDc1KNkvY6P0LodCgKVIlQ5deeTbkG7ih3bF5PHJLuLpaZjdRyQ=="],
"@swc/core-linux-x64-musl": ["@swc/core-linux-x64-musl@1.15.47", "", { "os": "linux", "cpu": "x64" }, "sha512-CQpS8Ge/avfjZd0UEwG/sds83Uu32deQXcV1Jo3jD0mmvQQqtYAjpsDZXugmheeAwmt+YIuoVtVHro8LMYHqsQ=="],
"@swc/core-win32-arm64-msvc": ["@swc/core-win32-arm64-msvc@1.15.47", "", { "os": "win32", "cpu": "arm64" }, "sha512-0W8IKHsUTYiT7G2RqtOoVWk+89yzZikIiDUb/sCK6BmQDBhN91hQSfyUtW12jhEWLzYgcfmisfsZrmZE+84U1A=="],
"@swc/core-win32-ia32-msvc": ["@swc/core-win32-ia32-msvc@1.15.47", "", { "os": "win32", "cpu": "ia32" }, "sha512-ZIp49d2Z4/ka2jO9otOg4hDvTdPmp86kVOgS2M5FCPI7eKKZ1W0boxWn+8XeZrfERtFGW0AlMRm4JhlJa7l3NA=="],
"@swc/core-win32-x64-msvc": ["@swc/core-win32-x64-msvc@1.15.47", "", { "os": "win32", "cpu": "x64" }, "sha512-2h8Iek95vnixkBRCo+H8p09+Q5ll2NgSMFrWTy0iKt7+/t+8/T5mBpiT6c0ZxSS7wcWjwZ9sGZkK70tTSYHdDw=="],
"@swc/counter": ["@swc/counter@0.1.3", "", {}, "sha512-e2BR4lsJkkRlKZ/qCHPw9ZaSxc0MVUd7gtbtaB7aMvHeJVYe8sOB8DBZkP2DtISHGSku9sCK6T6cnY0CtXrOCQ=="],
"@swc/types": ["@swc/types@0.1.27", "", { "dependencies": { "@swc/counter": "^0.1.3" } }, "sha512-K6h3iUlqeM946U4sXFYeahefR1YBbXJvko+hv8WS8/0BNJ4OHiHRywMnQUJCqkR7Y9+hqQ1TvEpiKqUhz7NEFg=="],
"@tybys/wasm-util": ["@tybys/wasm-util@0.10.3", "", { "dependencies": { "tslib": "^2.4.0" } }, "sha512-F3fo1MYrRJYL3zER0OUOmkutjr1Vp23m7OsSgp7nq4SP6OqX6C/56XFIPAl5bt3zaBRjmW7SGz3u/6LwFpYcOg=="],
"@types/bun": ["@types/bun@1.3.14", "", { "dependencies": { "bun-types": "1.3.14" } }, "sha512-h1hFqFVcvAvD9j9K7ZW7vd82aSA+rTdznZa+5bwvCwqSB1jmmfLcbIWhOLx1/+boy/xmjgCs/OMUL8hRJSmnPw=="],
"@types/node": ["@types/node@26.1.2", "", { "dependencies": { "undici-types": "~8.3.0" } }, "sha512-Vu4a5UFA9rIIFJ7rB/Vaafh9lrCQszopTCx6KjFboXTGQbPNasehVR5TEiithSDGyd1DEiUByggTZsg8jukeIg=="],
"@types/react": ["@types/react@19.2.17", "", { "dependencies": { "csstype": "^3.2.2" } }, "sha512-MXfmqaVPEVgkBT/aY0aGCkRWWtByiYQXo3xdQ8r5RzuFrPiRn8Gar2tQdXSUQ2GKV3bkXckek89V8wQBY2Q/Aw=="],
"@typescript/typescript-aix-ppc64": ["@typescript/typescript-aix-ppc64@7.0.2", "", { "os": "aix", "cpu": "ppc64" }, "sha512-MTKKkWB7p/0E9xi1d1tHtZ5PiLkGEMIq88pK2CubZjOsLtYTLqhgIgi6zepFa+9GHZ6h05NMCkQxGKiPXMxXtQ=="],
"@typescript/typescript-darwin-arm64": ["@typescript/typescript-darwin-arm64@7.0.2", "", { "os": "darwin", "cpu": "arm64" }, "sha512-gowzar9MwS/aRWp6f3a4KUqzRjAZjOsmGNCM6LcTgXum+dBfgsBVMN+AgvOCCbguXyick6LJhpBszxMebJ8syA=="],
"@typescript/typescript-darwin-x64": ["@typescript/typescript-darwin-x64@7.0.2", "", { "os": "darwin", "cpu": "x64" }, "sha512-SZ9xZInqApNlNGc9s0W1VSsktYSOe9cFqNOIqmN1Gs8SmkjKZYFt017G4VwPxASInODuAdbTW7sXiFUf893RgA=="],
"@typescript/typescript-freebsd-arm64": ["@typescript/typescript-freebsd-arm64@7.0.2", "", { "os": "freebsd", "cpu": "arm64" }, "sha512-W5NH4y/J0plIIS5b2xvTEkU7JFxyqdMAOgf+Ilhl0vHQXKO5dZoxd+C/jEtq56c4F3wk71RB4BMRQ2XdI+bwYQ=="],
"@typescript/typescript-freebsd-x64": ["@typescript/typescript-freebsd-x64@7.0.2", "", { "os": "freebsd", "cpu": "x64" }, "sha512-UMGDx5sTpzNw3WiPebH7l90IWfJggEd+egHt/q6p7/Cm3zqoV7VxkGXt+3DxPIw8CcmvAB0j3sVVfbhX+M4Tpw=="],
"@typescript/typescript-linux-arm": ["@typescript/typescript-linux-arm@7.0.2", "", { "os": "linux", "cpu": "arm" }, "sha512-gffT3xPz9sR7j/YJExkyPntrI0P2EP9XbOyWzth2/Gs0RstK+90RBcO0ncXoXy/beYll1SXw846Nf2zdnEz0QQ=="],
"@typescript/typescript-linux-arm64": ["@typescript/typescript-linux-arm64@7.0.2", "", { "os": "linux", "cpu": "arm64" }, "sha512-Qh4eU4/y3yDjnfjjyPYihMj5/ODIlmt+Bzu17OI+fiSRDW57QmU5SiN63exPRNJPKUzcc1INa1NXdrJ+MqHjUQ=="],
"@typescript/typescript-linux-loong64": ["@typescript/typescript-linux-loong64@7.0.2", "", { "os": "linux", "cpu": "none" }, "sha512-uEHck9i8hoAzXPiYRib1O7miOnz23SxIeVl6F4LXox+qov1K35jHcEW6VHKvZI+pyvl7fZEP4MCU5LYvIq1GuQ=="],
"@typescript/typescript-linux-mips64el": ["@typescript/typescript-linux-mips64el@7.0.2", "", { "os": "linux", "cpu": "none" }, "sha512-R4KvAMnE43W5Qeqb0Ly56O3mWMWIAgsMyz36DCaycd5nbg/9kzm0liw3JocfRqyJY0KPmzFjbswozXyW0DnIYA=="],
"@typescript/typescript-linux-ppc64": ["@typescript/typescript-linux-ppc64@7.0.2", "", { "os": "linux", "cpu": "ppc64" }, "sha512-DORx5b3sd/4S7eayxm4FQv+A7CrkUIGRaHiwI8oiHTAI1fAPWhF4J0vAlkC8biAlHSVVwxMQ3tjZ2/DVbnQiiA=="],
"@typescript/typescript-linux-riscv64": ["@typescript/typescript-linux-riscv64@7.0.2", "", { "os": "linux", "cpu": "none" }, "sha512-wf0jqEDOjrPRnKwYRyyJDRo11KMbvMFrU+q4zqKyChODBzvlkbhNQfKvLxQCcwTpdDaXSHZTVuh0JoCrKCUMHQ=="],
"@typescript/typescript-linux-s390x": ["@typescript/typescript-linux-s390x@7.0.2", "", { "os": "linux", "cpu": "s390x" }, "sha512-IkwJc3L7yhytWd/ewjyxNDfOmswCm9GWMJT/ue/dU4aZNbwZeYAetq42VyLmsmSjvoX7z74X6ZaYCtzAr0EuGw=="],
"@typescript/typescript-linux-x64": ["@typescript/typescript-linux-x64@7.0.2", "", { "os": "linux", "cpu": "x64" }, "sha512-EYdf2cNg7rgCWJnxCdJ+F3V39O8ihb37eHAu1LK8oAFizgTQbPOK7zHHXbPt8rX24COqODXeI3sIf0fCXG7H/A=="],
"@typescript/typescript-netbsd-arm64": ["@typescript/typescript-netbsd-arm64@7.0.2", "", { "os": "none", "cpu": "arm64" }, "sha512-+polYF4MF04aPpO5FTkHran9yUQDSXqy5GiSDKpsll5jy3l3+g9QLhpf39T+ePtefhXLOGrLl0QIjkQP6VnelA=="],
"@typescript/typescript-netbsd-x64": ["@typescript/typescript-netbsd-x64@7.0.2", "", { "os": "none", "cpu": "x64" }, "sha512-8YIT0EHM/3dq10ZOVF/A7pc/YSMtbcecct4rWtexrnSCHOPcpC2KTLXfTCR6vDpnSiY12heNb1GiN/wu+T/FyA=="],
"@typescript/typescript-openbsd-arm64": ["@typescript/typescript-openbsd-arm64@7.0.2", "", { "os": "openbsd", "cpu": "arm64" }, "sha512-APT8+ClYnuYm1u9+kgGXoMj2VzWzcymwh2gNSQVySHfkRDGOTVkoWLjCmOQSaO+PoqQ57B0flRp9SA+7GnnkzQ=="],
"@typescript/typescript-openbsd-x64": ["@typescript/typescript-openbsd-x64@7.0.2", "", { "os": "openbsd", "cpu": "x64" }, "sha512-yX7s+Q0Dln0Dt9tEzZsAjXXR/+ytBM7AlglaqyeMPxQszJ1JhlJdZ6jLA+IzldHtflX81em7lDao1xXu+aRRkg=="],
"@typescript/typescript-sunos-x64": ["@typescript/typescript-sunos-x64@7.0.2", "", { "os": "sunos", "cpu": "x64" }, "sha512-dLJDGaLZ1D4HPQn62u1n8mBDkJREwMsAkCdkwd4Ieqw+x3TUyTsqY0YiBCtE6H6OzzgGk3iuZ3vFWRS+E8/d1g=="],
"@typescript/typescript-win32-arm64": ["@typescript/typescript-win32-arm64@7.0.2", "", { "os": "win32", "cpu": "arm64" }, "sha512-Gyl1Vy6OsWesLzmq+EP0Fb7b4Nid5232AvcA2SFcdYreldpNtYFFofPjnt62y9hQy7VTaZp65ICJjuAQRaVcIQ=="],
"@typescript/typescript-win32-x64": ["@typescript/typescript-win32-x64@7.0.2", "", { "os": "win32", "cpu": "x64" }, "sha512-0BQ3HkAHHlKLSp1qRvf3SUhGpGsDuhB/jgFw75guyqbxJqEaS0Cw/VFO8i2nHglJUzQCRtMMR/IBAKE3ETMC4g=="],
"@yuku-codegen/binding-darwin-arm64": ["@yuku-codegen/binding-darwin-arm64@0.8.1", "", { "os": "darwin", "cpu": "arm64" }, "sha512-Ck0RmDBLc+R0dZpfTXmJFAvcuPf+npbJF1T/VhC9pPDGjNEOGwn4DwFcjhg//DfNIO+xgktsLSt5S4v0MFrToA=="],
"@yuku-codegen/binding-darwin-x64": ["@yuku-codegen/binding-darwin-x64@0.8.1", "", { "os": "darwin", "cpu": "x64" }, "sha512-6BDLLWi8wHbCghgkajS+OeVJX2jLY9pY9HV/qH9daLP1XCyMSPssEiXjKyPiJq+St5b+zcPgMEBF8cgJDNhMMQ=="],
"@yuku-codegen/binding-freebsd-x64": ["@yuku-codegen/binding-freebsd-x64@0.8.1", "", { "os": "freebsd", "cpu": "x64" }, "sha512-Rd1PHfw2mxC8y00kWxYWDClnBC1NbSwPuq0zKLYPggE7mlOnV+eQ15futtaz/Q4BP+jOtEv9elxvP7by20h6Kw=="],
"@yuku-codegen/binding-linux-arm-gnu": ["@yuku-codegen/binding-linux-arm-gnu@0.8.1", "", { "os": "linux", "cpu": "arm" }, "sha512-/XGncN6jQ/CwXNgWwo+XnsUmILY1q1mbS1f38XnYOHw3DOKOISxVIAlD9IsmdrHLAUAncFlgFS3ky4OO9fvjyg=="],
"@yuku-codegen/binding-linux-arm-musl": ["@yuku-codegen/binding-linux-arm-musl@0.8.1", "", { "os": "linux", "cpu": "arm" }, "sha512-Rxut53qx3JbTkQ8+A6I8Lrplwz55HQVCjEsTsWF1uOpfgALdvuKSMPIE0gVqefEEcOSA9ASklbNacmXwiqnaMw=="],
"@yuku-codegen/binding-linux-arm64-gnu": ["@yuku-codegen/binding-linux-arm64-gnu@0.8.1", "", { "os": "linux", "cpu": "arm64" }, "sha512-hBNkUPHX04BjB2oIIgIlYT2tog9x0rmBVkZep0f4LLYyFhdJfYM/s2pJ0c8ehQhhkQaJFokW4CxGhiVvVLlzWg=="],
"@yuku-codegen/binding-linux-arm64-musl": ["@yuku-codegen/binding-linux-arm64-musl@0.8.1", "", { "os": "linux", "cpu": "arm64" }, "sha512-ePZZnmOxArA4jA3AWlJj3WdY5z1ahQSLwAYrv7mozkJVcrBz2wZgy8l9ukcHFpTxPyhxCAea4gBSZEqqsCYE3A=="],
"@yuku-codegen/binding-linux-x64-gnu": ["@yuku-codegen/binding-linux-x64-gnu@0.8.1", "", { "os": "linux", "cpu": "x64" }, "sha512-LGAEXnQ4Xg/BtOuEirABwa9ByUTXFjealqXXAHVFb8EEmZu5QeHLtsdB2MA2IcYVAgW/QPkyqfnd80R4FltI2A=="],
"@yuku-codegen/binding-linux-x64-musl": ["@yuku-codegen/binding-linux-x64-musl@0.8.1", "", { "os": "linux", "cpu": "x64" }, "sha512-PPDMcQIKCNTOaLBBKh9SBM1EAPcsvnlShMAxq2D/twnSCSEUI9LfrR+G9J4P3o+46ZS4WN8mjZsj8p4PKOnKgw=="],
"@yuku-codegen/binding-win32-arm64": ["@yuku-codegen/binding-win32-arm64@0.8.1", "", { "os": "win32", "cpu": "arm64" }, "sha512-W8A1QpstKYhg4e56s13L4ByQprQ1OXY3QFoNPIh6+4v/DEgqfhJ9ApU++e7zHQCQrhYjyQC/uWtxUcRqpyL/7Q=="],
"@yuku-codegen/binding-win32-x64": ["@yuku-codegen/binding-win32-x64@0.8.1", "", { "os": "win32", "cpu": "x64" }, "sha512-zH7g7pLjfl3uZaNvYzd1PnCerU9fvhS16B7Z0z4Ai0S/oaGI53Y2xh8ylFDvDvmquEP7vay4O/zuLgvZeEsxVA=="],
"@yuku-parser/binding-darwin-arm64": ["@yuku-parser/binding-darwin-arm64@0.8.1", "", { "os": "darwin", "cpu": "arm64" }, "sha512-iKQinrhsdxsGJ38msw4KaD7yotWw5N2nqMLeOPD+ttpZQKJc9nGL3VHMtISzCJ9Q09g0N3m91mYRFnIbXfhhig=="],
"@yuku-parser/binding-darwin-x64": ["@yuku-parser/binding-darwin-x64@0.8.1", "", { "os": "darwin", "cpu": "x64" }, "sha512-k7zt2H3sWbYzwTGAK2TT6ma18w1XpwFAWgmBHiaMGHVe63aArrtO+55r6g7chXJ4joB6lb8SxYFyRQ974xfawQ=="],
"@yuku-parser/binding-freebsd-x64": ["@yuku-parser/binding-freebsd-x64@0.8.1", "", { "os": "freebsd", "cpu": "x64" }, "sha512-tQjrlkE/vYEBXZ+pM59FerIVD4Zfs2OpRvN3e8oo12pTcAbwTTxteZKWaedfUsZr+gKO4tLLAaFaFIwa5fQJFw=="],
"@yuku-parser/binding-linux-arm-gnu": ["@yuku-parser/binding-linux-arm-gnu@0.8.1", "", { "os": "linux", "cpu": "arm" }, "sha512-LZQgyer5d5i1f5oot+x6EhANXPD4FeCgz2CiSiWFSFBeG1U2m5jz65LD8gZwzy4CP4QVxQFyX9BazVRskTbwuQ=="],
"@yuku-parser/binding-linux-arm-musl": ["@yuku-parser/binding-linux-arm-musl@0.8.1", "", { "os": "linux", "cpu": "arm" }, "sha512-69G1N4bPkygrus/ahtFxVdv9lzfvS65fuyMdDknn5BZU/gfFGBJyHeJ8UGgLPTyR3YptlJMuZhEkdgp6Qhfz2g=="],
"@yuku-parser/binding-linux-arm64-gnu": ["@yuku-parser/binding-linux-arm64-gnu@0.8.1", "", { "os": "linux", "cpu": "arm64" }, "sha512-XL5+JpKCl1ghQTnZezy41NzmPdk4rZ6s0Z8qvGsgNPJ6yrSD7Ne8iz20SZZd/nW720qHiJy/ux62rwzZ+/clMg=="],
"@yuku-parser/binding-linux-arm64-musl": ["@yuku-parser/binding-linux-arm64-musl@0.8.1", "", { "os": "linux", "cpu": "arm64" }, "sha512-Rj290yfrWlrV4/+HrAuoeJXMHdoNubJWKdhg1QDa/mvqa8MUYFd4IHuVYjP/WdQzEgOAWGrLC48vcnge6U3jbg=="],
"@yuku-parser/binding-linux-x64-gnu": ["@yuku-parser/binding-linux-x64-gnu@0.8.1", "", { "os": "linux", "cpu": "x64" }, "sha512-d3IDkhAxiUTVuGI6BKIMKUyLe7ZxMY5yLqyvvTqJD1WPnE0eJTsLeRFRBv7/HXsnAzDs0IgvoG5bjvUkHZ5kSg=="],
"@yuku-parser/binding-linux-x64-musl": ["@yuku-parser/binding-linux-x64-musl@0.8.1", "", { "os": "linux", "cpu": "x64" }, "sha512-Oyp+2gGYKK/AvN2ZoauRn1LGPdkjME5/TE/l4a9mT0JdNeiRTvno42383bt04MWnAZcYS4Hv7YsiFOXUBeLdpA=="],
"@yuku-parser/binding-win32-arm64": ["@yuku-parser/binding-win32-arm64@0.8.1", "", { "os": "win32", "cpu": "arm64" }, "sha512-H77lYgICWRZycGmLaojzg0aSs3Z3v8SZWkcEjl1Ql3s+Km2SyiQcZ7RGq++Wh5nJxpiDJGAzYDC74XqMNm2ZHg=="],
"@yuku-parser/binding-win32-x64": ["@yuku-parser/binding-win32-x64@0.8.1", "", { "os": "win32", "cpu": "x64" }, "sha512-ABniFzqYYn64NUEgmHTb6JxEzAlpmPu4cpMFjMBlR6cJXqL+vd7K1ae/yrt+NhUduHkJWJqG4lbHbV2yp9el3w=="],
"@yuku-toolchain/types": ["@yuku-toolchain/types@0.8.1", "", {}, "sha512-HcGEV3kOn9evBTm2ARYOFNKAI7sY9twQozCVd9EVdlsBlnKi0a2iv8xXxYVHFCBQpX3SvvPXBhk8lcK6NUTdNg=="],
"abort-controller": ["abort-controller@3.0.0", "", { "dependencies": { "event-target-shim": "^5.0.0" } }, "sha512-h8lQ8tacZYnR3vNQTgibj+tODHI5/+l06Au2Pcriv/Gmet0eaj4TwWH41sO9wnHDiQsEj19q0drzdWdeAHtweg=="],
"anser": ["anser@1.4.10", "", {}, "sha512-hCv9AqTQ8ycjpSd3upOJd7vFwW1JaoYQ7tpham03GJ1ca8/65rqn0RpaWpItOAd6ylW9wAw6luXYPJIyPFVOww=="],
"ansi-regex": ["ansi-regex@5.0.1", "", {}, "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ=="],
"ansi-styles": ["ansi-styles@5.2.0", "", {}, "sha512-Cxwpt2SfTzTtXcfOlzGEee8O+c+MmUgGrNiBcXnuWxuFJHe6a5Hz7qwhwe5OgaSYI0IJvkLqWX1ASG+cJOkEiA=="],
"asap": ["asap@2.0.6", "", {}, "sha512-BSHWgDSAiKs50o2Re8ppvp3seVHXSRM44cdSsT9FfNEUUZLOGWVCsiWaRPWM1Znn+mqZ1OfVZ3z3DWEzSp7hRA=="],
"babel-plugin-syntax-hermes-parser": ["dry-uninstall@0.3.0", "", {}, "sha512-b8h94RVpETWkVV59x62NsY++79bM7Si6Dxq7a4iVxRcJU3ZJJ4vaiC7wUZwM8WDK0ySRL+i+T/1SMAzbJLejYA=="],
"base64-js": ["base64-js@1.5.1", "", {}, "sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA=="],
"buffer": ["buffer@6.0.3", "", { "dependencies": { "base64-js": "^1.3.1", "ieee754": "^1.2.1" } }, "sha512-FTiCpNxtwiZZHEZbcbTIcZjERVICn9yq/pDFkTl95/AxzD1naBctN7YO68riM/gLSDY7sdrMby8hofADYuuqOA=="],
"bun-types": ["bun-types@1.3.14", "", { "dependencies": { "@types/node": "*" } }, "sha512-4N0ig0fEomHt5R0KCFWjovxow98rIoRwKolrYdCcknNwMekCXRnWEUvgu5soYV8QXtVsrUD8B95MBOZGPvr6KQ=="],
"chalk": ["chalk@6.0.0", "", {}, "sha512-2uNTXIuTTxk7ciZgAU1BQcgnchcG0xXnrs6jzkQfj9SsRa9M2s5zE8WT96hS6KmG4MzWHSrvH43DF1m4XRkrFg=="],
"cliui": ["cliui@8.0.1", "", { "dependencies": { "string-width": "^4.2.0", "strip-ansi": "^6.0.1", "wrap-ansi": "^7.0.0" } }, "sha512-BSeNnyus75C4//NQ9gQt1/csTXyo/8Sb+afLAkzAptFuMsod9HFokGNudZpi/oQV73hnVK+sR+5PVRMd+Dr7YQ=="],
"color": ["color@4.2.3", "", { "dependencies": { "color-convert": "^2.0.1", "color-string": "^1.9.0" } }, "sha512-1rXeuUUiGGrykh+CeBdu5Ie7OJwinCgQY0bc7GCRxy5xVHy+moaqkpL/jqQq0MtQOeYcrqEz4abc5f0KtU7W4A=="],
"color-convert": ["color-convert@2.0.1", "", { "dependencies": { "color-name": "~1.1.4" } }, "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ=="],
"color-name": ["color-name@1.1.4", "", {}, "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA=="],
"color-string": ["color-string@1.9.1", "", { "dependencies": { "color-name": "^1.0.0", "simple-swizzle": "^0.2.2" } }, "sha512-shrVawQFojnZv6xM40anx4CkoDP+fZsw/ZerEMsW/pyzsRbElpsL/DBVW7q3ExxwusdNXI3lXpuhEZkzs8p5Eg=="],
"commander": ["commander@12.1.0", "", {}, "sha512-Vw8qHK3bZM9y/P10u3Vib8o/DdkvA2OtPtZvD871QKjy74Wj1WSKFILMPRPSdUSx5RFK1arlJzEtA4PkFgnbuA=="],
"csstype": ["csstype@3.2.3", "", {}, "sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ=="],
"debug": ["debug@4.4.3", "", { "dependencies": { "ms": "^2.1.3" } }, "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA=="],
"decode-uri-component": ["decode-uri-component@0.2.2", "", {}, "sha512-FqUYQ+8o158GyGTrMFJms9qh3CqTKvAqgqsTnkLI8sKu0028orqBhxNMFkFen0zGyg6epACD32pjVk58ngIErQ=="],
"detect-libc": ["detect-libc@2.1.2", "", {}, "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ=="],
"dts-resolver": ["dts-resolver@3.0.0", "", { "peerDependencies": { "oxc-resolver": ">=11.0.0" }, "optionalPeers": ["oxc-resolver"] }, "sha512-1T1f+z+4tl9XD+m+0HBgWoL/nm0bOIffyWaUuUSBlFg/86IWvfx+wjNaO/ybU0AJzG9/Mi5hBUgGV6zCmWEN7Q=="],
"emoji-regex": ["emoji-regex@8.0.0", "", {}, "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A=="],
"escalade": ["escalade@3.2.0", "", {}, "sha512-WUj2qlxaQtO4g6Pq5c29GTcWGDyd8itL8zTlipgECz3JesAiiOKotd8JU6otB3PACgG6xkJUyVhboMS+bje/jA=="],
"escape-string-regexp": ["escape-string-regexp@4.0.0", "", {}, "sha512-TtpcNJ3XAzx3Gq8sWRzJaVajRs0uVxA2YAkdb1jm2YkPz4G6egUFAyA3n5vtEIZefPk5Wa4UXbKuS5fKkJWdgA=="],
"event-target-shim": ["event-target-shim@5.0.1", "", {}, "sha512-i/2XbnSz/uxRCU6+NdVJgKWDTM427+MqYbkQzD321DuCQJUqOuJKIA0IM2+W2xtYHdKOmZ4dR6fExsd4SXL+WQ=="],
"fast-deep-equal": ["fast-deep-equal@3.1.3", "", {}, "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q=="],
"fdir": ["fdir@6.5.0", "", { "peerDependencies": { "picomatch": "^3 || ^4" }, "optionalPeers": ["picomatch"] }, "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg=="],
"filter-obj": ["filter-obj@1.1.0", "", {}, "sha512-8rXg1ZnX7xzy2NGDVkBVaAy+lSlPNwad13BtgSlLuxfIslyt5Vg64U7tFcCt4WS1R0hvtnQybT/IyCkGZ3DpXQ=="],
"flow-enums-runtime": ["flow-enums-runtime@0.0.6", "", {}, "sha512-3PYnM29RFXwvAN6Pc/scUfkI7RwhQ/xqyLUyPNlXUp9S40zI8nup9tUSrTLSVnWGBN38FNiGWbwZOB6uR4OGdw=="],
"get-caller-file": ["get-caller-file@2.0.5", "", {}, "sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg=="],
"get-tsconfig": ["get-tsconfig@5.0.0-beta.5", "", { "dependencies": { "resolve-pkg-maps": "^1.0.0" } }, "sha512-/6gFNr0N04nob252sTQxyFLi3eKFRqIg1I87YcqAMT1i6SQrSF6KujUEQrtrjMV0H/eejTCltLdDSTEMzHbnsQ=="],
"hermes-compiler": ["hermes-compiler@250829098.0.15", "", {}, "sha512-GJiEBl2JgT8FsRcY9DOBYW9L0KGRij58y7FeINJOaqWdYIrf/o3hi8NCsW3CV+XbG1vAwEeuXvwg4+xMJ8cc3g=="],
"ieee754": ["ieee754@1.2.1", "", {}, "sha512-dcyqhDvX1C46lXZcVqCpK+FtMRQVdIMN6/Df5js2zouUsqG7I6sFxitIC+7KYK29KdXOLHdu9zL4sFnoVQnqaA=="],
"invariant": ["invariant@2.2.4", "", { "dependencies": { "loose-envify": "^1.0.0" } }, "sha512-phJfQVBuaJM5raOpJjSfkiD6BpbCE4Ns//LaXl6wGYtUBY83nWS6Rf9tXm2e8VaK60JEjYldbPif/A2B1C2gNA=="],
"is-arrayish": ["is-arrayish@0.3.4", "", {}, "sha512-m6UrgzFVUYawGBh1dUsWR5M2Clqic9RVXC/9f8ceNlv2IcO9j9J/z8UoCLPqtsPBFNzEpfR3xftohbfqDx8EQA=="],
"is-extglob": ["is-extglob@2.1.1", "", {}, "sha512-SbKbANkN603Vi4jEZv49LeVJMn4yGwsbzZworEoyEiutsN3nJYdbO36zfhGJ6QEDpOZIFkDtnq5JRxmvl3jsoQ=="],
"is-fullwidth-code-point": ["is-fullwidth-code-point@3.0.0", "", {}, "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg=="],
"is-glob": ["is-glob@4.0.3", "", { "dependencies": { "is-extglob": "^2.1.1" } }, "sha512-xelSayHH36ZgE7ZWhli7pW34hNbNl8Ojv5KVmkJD4hBdD3th8Tfk9vYasLM+mXWOZhFkgZfxhLSnrwRr4elSSg=="],
"js-tokens": ["js-tokens@4.0.0", "", {}, "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ=="],
"jsesc": ["jsesc@3.1.0", "", { "bin": { "jsesc": "bin/jsesc" } }, "sha512-/sM3dO2FOzXjKQhJuo0Q173wf2KOo8t4I8vHy6lF9poUp7bKT0/NHE8fPX23PwfhnykfqnC2xRxOnVw5XuGIaA=="],
"loose-envify": ["loose-envify@1.4.0", "", { "dependencies": { "js-tokens": "^3.0.0 || ^4.0.0" }, "bin": { "loose-envify": "cli.js" } }, "sha512-lyuxPGr/Wfhrlem2CL/UcnUc1zcqKAImBDzukY7Y5F/yQiNdko6+fRLevlw1HgMySw7f611UIY408EtxRSoK3Q=="],
"magic-string": ["magic-string@1.1.0", "", { "dependencies": { "@jridgewell/sourcemap-codec": "^1.5.5" } }, "sha512-kS3VHe0nEPST2saQV4Rbkchcd3UBRkVTQHo1D3h/ZTwFDhai/mfKkmtPAtD129EOI7K3HlHIsFOt0WrI2/oU9g=="],
"memoize-one": ["memoize-one@5.2.1", "", {}, "sha512-zYiwtZUcYyXKo/np96AGZAckk+FWWsUdJ3cHGGmld7+AhvcWmQyGCYUh1hc4Q/pkOhb65dQR/pqCyK0cOaHz4Q=="],
"metro-runtime": ["metro-runtime@0.84.4", "", { "dependencies": { "@babel/runtime": "^7.25.0", "flow-enums-runtime": "^0.0.6" } }, "sha512-Jibypds4g7AhzdRKY+kDoj51s5EXMwgyp5ddtlreDAsWefMdOx+agWqgm0H2XSZ/ueanHHVM89fnf5OJnlxa8Q=="],
"metro-source-map": ["metro-source-map@0.84.4", "", { "dependencies": { "@babel/traverse": "^7.29.0", "@babel/types": "^7.29.0", "flow-enums-runtime": "^0.0.6", "invariant": "^2.2.4", "metro-symbolicate": "0.84.4", "nullthrows": "^1.1.1", "ob1": "0.84.4", "source-map": "^0.5.6", "vlq": "^1.0.0" } }, "sha512-jbWkPxIesVuo1IWkvezmMJld6iu8nD62GsrZiV6jP37AOdbo4OBq1FJ+qkOg8sV05wAHB//jAbziuW0SlJfW4g=="],
"metro-symbolicate": ["metro-symbolicate@0.84.4", "", { "dependencies": { "flow-enums-runtime": "^0.0.6", "invariant": "^2.2.4", "metro-source-map": "0.84.4", "nullthrows": "^1.1.1", "source-map": "^0.5.6", "vlq": "^1.0.0" }, "bin": { "metro-symbolicate": "src/index.js" } }, "sha512-OnfpacxUqGPZQ27t8qK9mFa7uqHIlVWeqRqkCbvMvreEBiamEeOn8krKtcwgP5M4cYDPwuSmCTopHMVthqG4zA=="],
"ms": ["ms@2.1.3", "", {}, "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA=="],
"nanoid": ["nanoid@3.3.16", "", { "bin": { "nanoid": "bin/nanoid.cjs" } }, "sha512-bzlKTyNJ7+LdGIIwy8ijFpIqEQIvafahV7eYykJ8Cvh42EdJeODoJ6gUJXpQJvej1BddH8OqTXZNE/KfbWAu8Q=="],
"node-addon-api": ["node-addon-api@7.1.1", "", {}, "sha512-5m3bsyrjFWE1xf7nz7YXdN4udnVtXK6/Yfgn5qnahL6bCkf2yKt4k3nuTKAtT4r3IG8JNR2ncsIMdZuAzJjHQQ=="],
"nullthrows": ["nullthrows@1.1.1", "", {}, "sha512-2vPPEi+Z7WqML2jZYddDIfy5Dqb0r2fze2zTxNNknZaFpVHU3mFB3R+DWeJWGVx0ecvttSGlJTI+WG+8Z4cDWw=="],
"ob1": ["ob1@0.84.4", "", { "dependencies": { "flow-enums-runtime": "^0.0.6" } }, "sha512-eJXMpz4aQHXF/YBB9ddqZDIS+ooO91hObo9FoW/xBkr54/zCwYYCDqT/O54vNo8kOkWs5Ou/y28NgdrV0edQNA=="],
"obug": ["obug@2.1.4", "", {}, "sha512-4a+OsYv9UktOJKE+l1A4OufDgdRF9PifWj+tJnHURo/P+WOxpG4GzUFL9qCalmWauao6ogiG+QvnCovwPoyAWA=="],
"picocolors": ["picocolors@1.1.1", "", {}, "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA=="],
"picomatch": ["picomatch@4.0.5", "", {}, "sha512-RvwwcruNjI1ncT5xRakeyS9Lf8lcItv34KD+aif+VH9kduAyfYBipGh12274xtenIPZ119/R9BdTBa8gAwSh0A=="],
"pretty-format": ["pretty-format@29.7.0", "", { "dependencies": { "@jest/schemas": "^29.6.3", "ansi-styles": "^5.0.0", "react-is": "^18.0.0" } }, "sha512-Pdlw/oPxN+aXdmM9R00JVC9WVFoCLTKJvDVLgmJ+qAffBMxsV85l/Lu7sNx4zSzPyoL2euImuEwHhOXdEgNFZQ=="],
"promise": ["promise@8.3.0", "", { "dependencies": { "asap": "~2.0.6" } }, "sha512-rZPNPKTOYVNEEKFaq1HqTgOwZD+4/YHS5ukLzQCypkj+OkYx7iv0mA91lJlpPPZ8vMau3IIGj5Qlwrx+8iiSmg=="],
"query-string": ["query-string@7.1.3", "", { "dependencies": { "decode-uri-component": "^0.2.2", "filter-obj": "^1.1.0", "split-on-first": "^1.0.0", "strict-uri-encode": "^2.0.0" } }, "sha512-hh2WYhq4fi8+b+/2Kg9CEge4fDPvHS534aOOvOZeQ3+Vf2mCFsaFBYj0i+iXcAq6I9Vzp5fjMFBlONvayDC1qg=="],
"react": ["react@19.1.0", "", {}, "sha512-FS+XFBNvn3GTAWq26joslQgWNoFu08F4kl0J4CgdNKADkdSGXQyTCnKteIAJy96Br6YbpEU1LSzV5dYtjMkMDg=="],
"react-devtools-core": ["dry-uninstall@0.3.0", "", {}, "sha512-b8h94RVpETWkVV59x62NsY++79bM7Si6Dxq7a4iVxRcJU3ZJJ4vaiC7wUZwM8WDK0ySRL+i+T/1SMAzbJLejYA=="],
"react-is": ["react-is@19.2.8", "", {}, "sha512-s5un28nYxKJw5gvUHyW5PCC28CvBqLu9r3cWgzHT4Vo/5fqqkFcdRYsGcKf50WMPpjjFZS5d76fn3YCo2njKwQ=="],
"react-native": ["react-native@0.86.0", "", { "dependencies": { "@react-native/assets-registry": "0.86.0", "@react-native/codegen": "0.86.0", "@react-native/community-cli-plugin": "0.86.0", "@react-native/gradle-plugin": "0.86.0", "@react-native/js-polyfills": "0.86.0", "@react-native/normalize-colors": "0.86.0", "@react-native/virtualized-lists": "0.86.0", "abort-controller": "^3.0.0", "anser": "^1.4.9", "ansi-regex": "^5.0.0", "babel-plugin-syntax-hermes-parser": "0.36.0", "base64-js": "^1.5.1", "commander": "^12.0.0", "flow-enums-runtime": "^0.0.6", "hermes-compiler": "250829098.0.14", "invariant": "^2.2.4", "memoize-one": "^5.0.0", "metro-runtime": "^0.84.3", "metro-source-map": "^0.84.3", "nullthrows": "^1.1.1", "pretty-format": "^29.7.0", "promise": "^8.3.0", "react-devtools-core": "^6.1.5", "react-refresh": "^0.14.0", "regenerator-runtime": "^0.13.2", "scheduler": "0.27.0", "semver": "^7.1.3", "stacktrace-parser": "^0.1.10", "tinyglobby": "^0.2.15", "whatwg-fetch": "^3.0.0", "ws": "^7.5.10", "yargs": "^17.6.2" }, "peerDependencies": { "@react-native/jest-preset": "0.86.0", "@types/react": "^19.1.1", "react": "^19.2.3" }, "optionalPeers": ["@react-native/jest-preset", "@types/react"], "bin": { "react-native": "cli.js" } }, "sha512-17ALh/dd6AO4pgOVmOO5Axll5PbErEo3XFyLokyzW6usyi+OShIEPwUW26wLPlhVifgSOIfECCH0WN+0IqtJ1w=="],
"react-native-click-outside": ["react-native-click-outside@0.1.1", "", { "peerDependencies": { "react": "*", "react-native": "*" } }, "sha512-gNLLTGG4sdajzE1m2nHP2JtFN/COznGgS98r8IC7IClIkoNtdAtYOPpNvXGv/Hav6ra4qVtSJUFEyb19TuKneQ=="],
"react-native-gesture-handler": ["dry-uninstall@0.3.0", "", {}, "sha512-b8h94RVpETWkVV59x62NsY++79bM7Si6Dxq7a4iVxRcJU3ZJJ4vaiC7wUZwM8WDK0ySRL+i+T/1SMAzbJLejYA=="],
"react-native-safe-area-context": ["react-native-safe-area-context@5.8.0", "", { "peerDependencies": { "react": "*", "react-native": "*" } }, "sha512-t+ZsAVzY/wWzzx34vqGbo3/as9EEESJdbyZNL7Yg5EYX+toYMtMqFoDDCvqZUi35eeGVsXc6pAaEk4edMwbuCQ=="],
"react-native-screens": ["dry-uninstall@0.3.0", "", {}, "sha512-b8h94RVpETWkVV59x62NsY++79bM7Si6Dxq7a4iVxRcJU3ZJJ4vaiC7wUZwM8WDK0ySRL+i+T/1SMAzbJLejYA=="],
"react-refresh": ["react-refresh@0.14.2", "", {}, "sha512-jCvmsr+1IUSMUyzOkRcvnVbX3ZYC6g9TDrDbFuFmRDq7PD4yaGbLKNQL6k2jnArV8hjYxh7hVhAZB6s9HDGpZA=="],
"regenerator-runtime": ["regenerator-runtime@0.13.11", "", {}, "sha512-kY1AZVr2Ra+t+piVaJ4gxaFaReZVH40AKNo7UCX6W+dEwBo/2oZJzqfuN1qLq1oL45o56cPaTXELwrTh8Fpggg=="],
"require-directory": ["require-directory@2.1.1", "", {}, "sha512-fGxEI7+wsG9xrvdjsrlmL22OMTTiHRwAMroiEeMgq8gzoLC/PQr7RsRDSTLUg/bZAZtF+TVIkHc6/4RIKrui+Q=="],
"resolve-pkg-maps": ["resolve-pkg-maps@1.0.0", "", {}, "sha512-seS2Tj26TBVOC2NIc2rOe2y2ZO7efxITtLZcGSOnHHNOQ7CkiUBfw0Iw2ck6xkIhPwLhKNLS8BO+hEpngQlqzw=="],
"rolldown": ["rolldown@1.2.1", "", { "dependencies": { "@oxc-project/types": "=0.142.0", "@rolldown/pluginutils": "^1.0.0" }, "optionalDependencies": { "@rolldown/binding-android-arm64": "1.2.1", "@rolldown/binding-darwin-arm64": "1.2.1", "@rolldown/binding-darwin-x64": "1.2.1", "@rolldown/binding-freebsd-x64": "1.2.1", "@rolldown/binding-linux-arm-gnueabihf": "1.2.1", "@rolldown/binding-linux-arm64-gnu": "1.2.1", "@rolldown/binding-linux-arm64-musl": "1.2.1", "@rolldown/binding-linux-ppc64-gnu": "1.2.1", "@rolldown/binding-linux-s390x-gnu": "1.2.1", "@rolldown/binding-linux-x64-gnu": "1.2.1", "@rolldown/binding-linux-x64-musl": "1.2.1", "@rolldown/binding-openharmony-arm64": "1.2.1", "@rolldown/binding-wasm32-wasi": "1.2.1", "@rolldown/binding-win32-arm64-msvc": "1.2.1", "@rolldown/binding-win32-x64-msvc": "1.2.1" }, "bin": { "rolldown": "./bin/cli.mjs" } }, "sha512-4FKJhg8d3OiyQOA6Q1Q0hoFFpW9/OoX+VsHzpECsdsIZoOArrAK90gl59YK/Z+gnDel45bgJZK03ozH/9bCqEw=="],
"rolldown-plugin-dts": ["rolldown-plugin-dts@0.27.14", "", { "dependencies": { "dts-resolver": "^3.0.0", "get-tsconfig": "5.0.0-beta.5", "obug": "^2.1.4", "yuku-ast": "^0.8.0", "yuku-codegen": "^0.8.0", "yuku-parser": "^0.8.0" }, "peerDependencies": { "@typescript/native-preview": "*", "@volar/typescript": "~2.4.0", "rolldown": "^1.0.0", "typescript": "^5.0.0 || ^6.0.0 || ~7.0.0", "vue-tsc": "~3.2.0 || ~3.3.0" }, "optionalPeers": ["@typescript/native-preview", "@volar/typescript", "typescript", "vue-tsc"] }, "sha512-ZvuDDwoIpRK9RPxDXratCpklFO9QZZWndf/sd0VBFb4LEj0jj07UcHK9OCh7V4XiFz2Z89ziyBC2K6tJiDjrbw=="],
"scheduler": ["scheduler@0.27.0", "", {}, "sha512-eNv+WrVbKu1f3vbYJT/xtiF5syA5HPIMtf9IgY/nKg0sWqzAUEvqY/xm7OcZc/qafLx/iO9FgOmeSAp4v5ti/Q=="],
"semver": ["semver@7.8.5", "", { "bin": { "semver": "bin/semver.js" } }, "sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA=="],
"simple-swizzle": ["simple-swizzle@0.2.4", "", { "dependencies": { "is-arrayish": "^0.3.1" } }, "sha512-nAu1WFPQSMNr2Zn9PGSZK9AGn4t/y97lEm+MXTtUDwfP0ksAIX4nO+6ruD9Jwut4C49SB1Ws+fbXsm/yScWOHw=="],
"source-map": ["source-map@0.5.7", "", {}, "sha512-LbrmJOMUSdEVxIKvdcJzQC+nQhe8FUZQTXQy6+I75skNgn3OoQ0DZA8YnFa7gp8tqtL3KPf1kmo0R5DoApeSGQ=="],
"split-on-first": ["split-on-first@1.1.0", "", {}, "sha512-43ZssAJaMusuKWL8sKUBQXHWOpq8d6CfN/u1p4gUzfJkM05C8rxTmYrkIPTXapZpORA6LkkzcUulJ8FqA7Uudw=="],
"stacktrace-parser": ["stacktrace-parser@0.1.11", "", { "dependencies": { "type-fest": "^0.7.1" } }, "sha512-WjlahMgHmCJpqzU8bIBy4qtsZdU9lRlcZE3Lvyej6t4tuOuv1vk57OW3MBrj6hXBFx/nNoC9MPMTcr5YA7NQbg=="],
"standard-navigation": ["standard-navigation@0.0.8", "", { "peerDependencies": { "react": "*" } }, "sha512-TyVbo7INUDWtsUWDFn8RR7kwR87U0S4xHfLfbbnyeC581TmmyqQ+eM+nPw8rQTSD8QitRVcYfPaSHr/QJiUy1g=="],
"strict-uri-encode": ["strict-uri-encode@2.0.0", "", {}, "sha512-QwiXZgpRcKkhTj2Scnn++4PKtWsH0kpzZ62L2R6c/LUVYv7hVnZqcg2+sMuT6R7Jusu1vviK/MFsu6kNJfWlEQ=="],
"string-width": ["string-width@4.2.3", "", { "dependencies": { "emoji-regex": "^8.0.0", "is-fullwidth-code-point": "^3.0.0", "strip-ansi": "^6.0.1" } }, "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g=="],
"strip-ansi": ["strip-ansi@6.0.1", "", { "dependencies": { "ansi-regex": "^5.0.1" } }, "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A=="],
"tinyglobby": ["tinyglobby@0.2.17", "", { "dependencies": { "fdir": "^6.5.0", "picomatch": "^4.0.4" } }, "sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g=="],
"tslib": ["tslib@2.8.1", "", {}, "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w=="],
"type-fest": ["type-fest@0.7.1", "", {}, "sha512-Ne2YiiGN8bmrmJJEuTWTLJR32nh/JdL1+PSicowtNb0WFpn59GK8/lfD61bVtzguz7b3PBt74nxpv/Pw5po5Rg=="],
"typescript": ["typescript@7.0.2", "", { "optionalDependencies": { "@typescript/typescript-aix-ppc64": "7.0.2", "@typescript/typescript-darwin-arm64": "7.0.2", "@typescript/typescript-darwin-x64": "7.0.2", "@typescript/typescript-freebsd-arm64": "7.0.2", "@typescript/typescript-freebsd-x64": "7.0.2", "@typescript/typescript-linux-arm": "7.0.2", "@typescript/typescript-linux-arm64": "7.0.2", "@typescript/typescript-linux-loong64": "7.0.2", "@typescript/typescript-linux-mips64el": "7.0.2", "@typescript/typescript-linux-ppc64": "7.0.2", "@typescript/typescript-linux-riscv64": "7.0.2", "@typescript/typescript-linux-s390x": "7.0.2", "@typescript/typescript-linux-x64": "7.0.2", "@typescript/typescript-netbsd-arm64": "7.0.2", "@typescript/typescript-netbsd-x64": "7.0.2", "@typescript/typescript-openbsd-arm64": "7.0.2", "@typescript/typescript-openbsd-x64": "7.0.2", "@typescript/typescript-sunos-x64": "7.0.2", "@typescript/typescript-win32-arm64": "7.0.2", "@typescript/typescript-win32-x64": "7.0.2" }, "bin": { "tsc": "bin/tsc" } }, "sha512-8FYau96o3NKOhbjKi/qNvG/W5jhzxkbdm5sj9AbZ/5T5sWqn3hJgLfGx27sRKZWTvyzCP8dLRBTf5tBTSRVUNA=="],
"undici-types": ["undici-types@8.3.0", "", {}, "sha512-j375ScV60dom+YkPFIfTLcOiPxkN/buHz5GobjLhixFuANaNs3C9l4GmrWqejgXWJ7BbJcFYpTEUkS1Ge8bpZQ=="],
"use-latest-callback": ["use-latest-callback@0.2.6", "", { "peerDependencies": { "react": ">=16.8" } }, "sha512-FvRG9i1HSo0wagmX63Vrm8SnlUU3LMM3WyZkQ76RnslpBrX694AdG4A0zQBx2B3ZifFA0yv/BaEHGBnEax5rZg=="],
"use-sync-external-store": ["use-sync-external-store@1.6.0", "", { "peerDependencies": { "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0" } }, "sha512-Pp6GSwGP/NrPIrxVFAIkOQeyw8lFenOHijQWkUTrDvrF4ALqylP2C/KCkeS9dpUM3KvYRQhna5vt7IL95+ZQ9w=="],
"vlq": ["vlq@1.0.1", "", {}, "sha512-gQpnTgkubC6hQgdIcRdYGDSDc+SaujOdyesZQMv6JlfQee/9Mp0Qhnys6WxDWvQnL5WZdT7o2Ul187aSt0Rq+w=="],
"whatwg-fetch": ["whatwg-fetch@3.6.20", "", {}, "sha512-EqhiFU6daOA8kpjOWTL0olhVOF3i7OrFzSYiGsEMB8GcXS+RrzauAERX65xMeNWVqxA6HXH2m69Z9LaKKdisfg=="],
"wrap-ansi": ["wrap-ansi@7.0.0", "", { "dependencies": { "ansi-styles": "^4.0.0", "string-width": "^4.1.0", "strip-ansi": "^6.0.0" } }, "sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q=="],
"ws": ["ws@7.5.13", "", { "peerDependencies": { "bufferutil": "^4.0.1", "utf-8-validate": "^5.0.2" }, "optionalPeers": ["bufferutil", "utf-8-validate"] }, "sha512-rsKI6xDBFVf4r/x8XyChGK04QR/XHroxs/jUcoWvtEZM8TPU/X/uIY9B1CsSzYws9ZJb/6bbBu7dPhFW00CAoA=="],
"y18n": ["y18n@5.0.8", "", {}, "sha512-0pfFzegeDWJHJIAmTLRP2DwHjdF5s7jo9tuztdQxAhINCdvS+3nGINqPd00AphqJR/0LhANUS6/+7SCb98YOfA=="],
"yargs": ["yargs@17.7.3", "", { "dependencies": { "cliui": "^8.0.1", "escalade": "^3.1.1", "get-caller-file": "^2.0.5", "require-directory": "^2.1.1", "string-width": "^4.2.3", "y18n": "^5.0.5", "yargs-parser": "^21.1.1" } }, "sha512-GZtjxm/J/4TSxuL3FNYjCmLktBTnIw/rVmKSIyKeYAZpmJB2ig9VauCC5xsa82GNKVKDAqpOn3KVzNt0zmrU0g=="],
"yargs-parser": ["yargs-parser@21.1.1", "", {}, "sha512-tVpsJW7DdjecAiFpbIB1e3qxIQsE6NoPc5/eTdrbbIC4h0LVsWhnoa3g+m2HclBIujHzsxZ4VJVA+GUuc2/LBw=="],
"yuku-ast": ["yuku-ast@0.8.1", "", { "dependencies": { "@yuku-toolchain/types": "^0.8.1" } }, "sha512-+k1E2f08y0k1+vpdD1KUCzDh2JXvwirMa8YR2Jr7VCS4zAo3eT5A/HbJCqaVGd6idaPY0gwLM9C4seEY4h10Hw=="],
"yuku-codegen": ["yuku-codegen@0.8.1", "", { "dependencies": { "@yuku-toolchain/types": "^0.8.1" }, "optionalDependencies": { "@yuku-codegen/binding-darwin-arm64": "0.8.1", "@yuku-codegen/binding-darwin-x64": "0.8.1", "@yuku-codegen/binding-freebsd-x64": "0.8.1", "@yuku-codegen/binding-linux-arm-gnu": "0.8.1", "@yuku-codegen/binding-linux-arm-musl": "0.8.1", "@yuku-codegen/binding-linux-arm64-gnu": "0.8.1", "@yuku-codegen/binding-linux-arm64-musl": "0.8.1", "@yuku-codegen/binding-linux-x64-gnu": "0.8.1", "@yuku-codegen/binding-linux-x64-musl": "0.8.1", "@yuku-codegen/binding-win32-arm64": "0.8.1", "@yuku-codegen/binding-win32-x64": "0.8.1" } }, "sha512-/4Sbg9K9HpCe3PidmMbs9TzJ62gq3KmQY279TB0EGKdMoM8LfcmIg4E9wS2J/ylbFuQaWcYqf5dBKr8zubdlKA=="],
"yuku-parser": ["yuku-parser@0.8.1", "", { "dependencies": { "@yuku-toolchain/types": "^0.8.1", "yuku-ast": "^0.8.1" }, "optionalDependencies": { "@yuku-parser/binding-darwin-arm64": "0.8.1", "@yuku-parser/binding-darwin-x64": "0.8.1", "@yuku-parser/binding-freebsd-x64": "0.8.1", "@yuku-parser/binding-linux-arm-gnu": "0.8.1", "@yuku-parser/binding-linux-arm-musl": "0.8.1", "@yuku-parser/binding-linux-arm64-gnu": "0.8.1", "@yuku-parser/binding-linux-arm64-musl": "0.8.1", "@yuku-parser/binding-linux-x64-gnu": "0.8.1", "@yuku-parser/binding-linux-x64-musl": "0.8.1", "@yuku-parser/binding-win32-arm64": "0.8.1", "@yuku-parser/binding-win32-x64": "0.8.1" } }, "sha512-YvUz2jdFMIq0QjN8LmI32ox+RBCn3l8VToAXVQ5QFfLTxSxmGZS6JP80ptePEju+CpeTdINLmUm7Ewodzh1QnQ=="],
"metro-runtime/@babel/runtime": ["@babel/runtime@7.29.7", "", {}, "sha512-Nq8OhGWiZIZGV6hLHoyAKLLcJihP/xFeBMGJoUrxTX2psI8dCifzLhZISFb+VWS3wFMRDmCGw5R+dOySCqPLhw=="],
"pretty-format/react-is": ["react-is@18.3.1", "", {}, "sha512-/LLMVyas0ljjAtoYiPqYiL8VWXzUUdThrmU5+n20DZv+a+ClRoevUzw5JxU+Ieh5/c87ytoTBV9G1FiKfNJdmg=="],
"react-native/hermes-compiler": ["hermes-compiler@250829098.0.14", "", {}, "sha512-5meXwsZxgiqFaJjNzwjzI9IyUkuGGBisu+z9BvQWmGVpjH6nz11hgqkyxe4dl8UAdyIV4lTbz91+Dlnjz0VxqA=="],
"wrap-ansi/ansi-styles": ["ansi-styles@4.3.0", "", { "dependencies": { "color-convert": "^2.0.1" } }, "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg=="],
}
}

2
bunfig.toml Normal file
View file

@ -0,0 +1,2 @@
[install]
linker = "isolated"

16
lib/assets/package.json Normal file
View file

@ -0,0 +1,16 @@
{
"name": "@revenge-mod/assets",
"private": true,
"type": "module",
"exports": {
".": {
"default": "./src/index.ts"
},
"./preinit": {
"default": "./src/preinit.ts"
},
"./types": {
"types": "./src/types.ts"
}
}
}

View file

@ -0,0 +1,4 @@
import type { Asset, CustomAsset } from './types'
export const aCustoms = new Set<CustomAsset>()
export const aOverrides = new WeakMap<Asset, Asset>()

52
lib/assets/src/caches.ts Normal file
View file

@ -0,0 +1,52 @@
import {
callNativeMethod,
callNativeMethodSync,
} from '@revenge-mod/modules/native'
import { debounce } from '@revenge-mod/utils/callback'
import type { Metro } from '@revenge-mod/modules/types'
import type { Asset } from './types'
const ExpectedCacheVersion = 2
export const Uncached: Cache = {
data: {},
version: ExpectedCacheVersion,
}
// In-memory cache
export let cache: Cache =
callNativeMethodSync('revenge.caches.assets.read', []) ?? Uncached
if (cache.version !== ExpectedCacheVersion) {
Uncached.outdated = true
cache = Uncached
}
export interface Cache {
data: {
[key: Asset['name']]: {
[key: Asset['type']]: Metro.ModuleID
}
}
version: number
/** Indicates if the loader cache on an outdated format */
outdated?: boolean
}
const save = debounce(() => {
callNativeMethod('revenge.caches.assets.write', [cache.data])
}, 1000)
export function cacheAsset(asset: Asset, moduleId: Metro.ModuleID) {
const reg = (cache.data[asset.name] ??= {})
reg[asset.type] = moduleId
save()
}
declare module '@revenge-mod/modules/native' {
interface NativeMethods {
'revenge.caches.assets.read': [[], Cache | null]
'revenge.caches.assets.write': [[data: Cache['data']], void]
}
}

159
lib/assets/src/index.ts Normal file
View file

@ -0,0 +1,159 @@
import { Platform } from 'react-native'
import { aCustoms, aOverrides } from './_internal'
import { cache } from './caches'
import { AssetsRegistry } from './preinit'
import type {
Asset,
AssetId,
CustomAsset,
PackagerAsset,
RegisterableAsset,
} from './types'
export {
AssetsRegistry,
AssetsRegistryModuleId,
} from './preinit'
// Resolve reference once and keep in closure
const metroRequire = __r
// iOS cannot display SVGs
let _preferredType: Asset['type'] = Platform.OS === 'ios' ? 'png' : 'svg'
/**
* Set the preferred asset type. This is used to determine which asset to use when multiple types are available.
*
* @param type The preferred asset type.
*/
export function setPreferredAssetType(type: Asset['type']) {
_preferredType = type
}
/**
* Yields all assets, both packager and custom.
*/
export function* getAssets(): Generator<Asset> {
yield* getPackagerAssets()
yield* getCustomAssets()
}
/**
* Yields all registered custom assets.
*/
export function* getCustomAssets(): Generator<CustomAsset> {
for (const asset of aCustoms) yield asset
}
/**
* Yields all registered packager assets, including ones with same name but different types.
*/
export function* getPackagerAssets(): Generator<PackagerAsset> {
for (const reg of Object.values(cache.data))
for (const moduleId of Object.values(reg))
yield AssetsRegistry.getAssetByID(metroRequire(moduleId))
}
/**
* Get an asset by its name.
* If more than one asset is registered with the same name, this will return the one with the preferred type, or the first registered one.
*
* @param name The asset name.
* @param type The preferred asset type, defaults to the current preferred type.
*/
export function getAssetByName(
name: string,
type?: Asset['type'],
): Asset | undefined {
const id = getAssetIdByName(name, type)
if (id !== undefined) return AssetsRegistry.getAssetByID(id)
}
/**
* Gets all assets matching the name.
*
* @param name The asset name.
* @returns A record keyed by the type of the asset, with the value being the asset itself.
*/
export function getAssetsByName(
name: string,
): Record<Asset['type'], Asset> | undefined {
const reg = cache.data[name]
if (!reg) return
return Object.entries(reg).reduce(
(acc, [type, mid]) => {
acc[type as Asset['type']] = AssetsRegistry.getAssetByID(
metroRequire(mid),
)!
return acc
},
{} as Record<Asset['type'], Asset>,
)
}
/**
* Get an asset ID by its name.
*
* If more than one asset is registered with the same name, this will return the one with the preferred type.
*
* Unless **explicitly** calling with a preferred type,
* another asset with type mismatching the {@link setPreferredAssetType current preferred type} may be returned as a fallback.
*
* @param name The asset name.
* @param type The preferred asset type, defaults to the current preferred type.
*/
export function getAssetIdByName(
name: string,
type?: Asset['type'],
): AssetId | undefined {
const reg = cache.data[name]
if (!reg) return
if (type !== undefined) {
const mid = reg[type]
return mid && metroRequire(mid)
}
let mid = reg[_preferredType]
mid ??= Object.values(reg)[0]
return mid && metroRequire(mid)
}
/**
* Register an asset with the given name.
*
* @param asset The asset to register.
* @returns The asset ID.
*/
export function registerAsset(asset: RegisterableAsset): AssetId {
if (cache.data[asset.name]?.[asset.type] !== undefined)
throw new Error(
`Asset with name ${asset.name} and type ${asset.type} already exists!`,
)
aCustoms.add(asset as CustomAsset)
// @ts-expect-error
return AssetsRegistry.registerAsset(asset)
}
/**
* Override an asset with a custom asset.
*
* @param asset The asset to override.
* @param override The custom asset to override with.
*/
export function addAssetOverride(asset: Asset, override: Asset) {
aOverrides.set(asset, override)
}
/**
* Remove an asset override.
*
* @param asset The asset to remove the override for.
* @returns The asset that was removed.
*/
export function removeAssetOverride(asset: Asset) {
return aOverrides.delete(asset)
}

143
lib/assets/src/preinit.ts Normal file
View file

@ -0,0 +1,143 @@
import { lookupModules, waitForModules } from '@revenge-mod/modules/finders'
import {
withDependencies,
withName,
withProps,
} from '@revenge-mod/modules/finders/filters'
import {
mInitializingId,
mUninitialized,
} from '@revenge-mod/modules/metro/patches'
import { getModuleDependencies } from '@revenge-mod/modules/metro/utils'
import { proxify } from '@revenge-mod/utils/proxy'
import { aOverrides } from './_internal'
import { cache, cacheAsset, Uncached } from './caches'
import type { Metro } from '@revenge-mod/modules/types'
import type { ReactNative } from '@revenge-mod/react/types'
import type { Asset, PackagerAsset } from './types'
const { relative } = withDependencies
// https://github.com/facebook/react-native/blob/main/packages/react-native/Libraries/Image/AssetSourceResolver.js
const withAssetSourceResolver = withDependencies([
withName('_classCallCheck'),
withName('_createClass'),
relative(1),
relative(2),
null,
null,
])
const cachedOnly = { cached: true }
// Tracking/caching assets
const unsubAR = waitForModules(
withProps<ReactNative.AssetsRegistry>('registerAsset'),
(exports, id) => {
AssetsRegistryModuleId = id
AssetsRegistry = exports as ReactNative.AssetsRegistry
// There are two matching exports. One is the original, and one is a re-export.
// The original asset-registry is simply required by the re-exported one with no changes.
// This is the re-exported registry, because it has dependencies.
// We can begin the caching process here, asset registrar modules have the reexported registry as a dependency.
if (getModuleDependencies(id)!.length) {
unsubAR()
if (cache === Uncached) {
// Resolve reference once and keep in closure
const metroRequire = __r
// More fragile way, but also more performant:
// There is exactly one asset before the reexported asset registry :/
const firstAssetModuleId = id - 1
for (const mId of mUninitialized) {
if (mId < firstAssetModuleId) continue
const deps = getModuleDependencies(mId)!
if (deps.length === 1 && deps[0] === id) metroRequire(mId)
}
}
// We already patched the original asset registry, so we don't need to patch again.
return
}
const orig = exports.registerAsset
exports.registerAsset = (asset: Asset) => {
const result = orig(asset as PackagerAsset)
// Cache and set moduleId for packager assets only
if ((asset as PackagerAsset).__packager_asset) {
asset.moduleId = mInitializingId
cacheAsset(asset, mInitializingId!)
}
return (asset.id = result)
}
},
cachedOnly,
)
/**
* If you need to use this ID during `preInit`, unproxify {@link AssetsRegistry} first.
*
* ```js
* preInit() {
* unproxify(AssetsRegistry)
* // Module ID will now be set!
* AssetsRegistryModuleId // ...
* }
* ```
*/
export let AssetsRegistryModuleId: Metro.ModuleID | undefined
export let AssetsRegistry: ReactNative.AssetsRegistry = proxify(() => {
if (AssetsRegistryModuleId !== undefined) return __r(AssetsRegistryModuleId)
for (const [, id] of lookupModules(withDependencies([[]]), {
initialize: false,
})) {
const deps = getModuleDependencies(id)!
// The module next to assets-registry is AssetSourceResolver
if (withAssetSourceResolver(deps[0] + 1)) {
const module = __r(id)
// ID will be set by the wait below
if (module?.registerAsset) return (AssetsRegistry = module)
}
}
throw new Error('assets-registry not found')
})
// TODO: Native overrides?
// Asset overrides
const unsubRAS = waitForModules(
withName<{
addCustomSourceTransformer: (
transformer: (arg: { asset: Asset }) => PackagerAsset,
) => void
}>('resolveAssetSource'),
rAS => {
unsubRAS()
// Custom assets
// Why do we need to do this? Because RN/Discord (unsure which) will attempt to resolve the asset via its path, which we don't provide via custom assets.
// This will result in a crash, because it tries to read the path and run checks on it, but the path is undefined.
// @ts-expect-error
rAS.addCustomSourceTransformer(({ asset }) => {
if (!(asset as PackagerAsset).__packager_asset) return asset
})
// Asset overrides
// @ts-expect-error
rAS.addCustomSourceTransformer(({ asset }) => aOverrides.get(asset))
},
cachedOnly,
)
if (cache === Uncached) {
// Initialize the module immediately, so we can cache assets ASAP
AssetsRegistry.getAssetByID(0)
}

25
lib/assets/src/types.ts Normal file
View file

@ -0,0 +1,25 @@
import type { Metro } from '@revenge-mod/modules/types'
import type { ReactNative } from '@revenge-mod/react/types'
export type Asset = PackagerAsset | CustomAsset
export type AssetId = number
export type PackagerAsset = ReactNative.AssetsRegistry.PackagerAsset
export interface CustomAsset
extends Pick<PackagerAsset, 'name' | 'width' | 'height' | 'type' | 'id'> {
uri: string
moduleId?: undefined
}
export type RegisterableAsset = Omit<CustomAsset, 'id'>
declare module '@revenge-mod/react/types' {
export namespace ReactNative {
export namespace AssetsRegistry {
export interface PackagerAsset {
id: AssetId
moduleId: Metro.ModuleID
}
}
}
}

View file

@ -0,0 +1,28 @@
{
"name": "@revenge-mod/components",
"private": true,
"type": "module",
"exports": {
".": {
"default": "./src/index.ts"
},
"./FormSwitch": {
"default": "./src/FormSwitch.tsx"
},
"./Page": {
"default": "./src/Page.tsx"
},
"./SearchInput": {
"default": "./src/SearchInput.tsx"
},
"./TableRowAssetIcon": {
"default": "./src/TableRowAssetIcon.tsx"
},
"./types": {
"types": "./src/types.ts"
},
"./_": {
"default": "./src/_internal.ts"
}
}
}

View file

@ -0,0 +1,17 @@
import { FormSwitch as Switch } from '@revenge-mod/discord/design'
import { View } from 'react-native'
import { styles } from './_internal'
import type { DiscordModules } from '@revenge-mod/discord/types'
/**
* A switch component that is styled to match Discord's configuration
*/
export default function FormSwitch(
props: DiscordModules.Components.FormSwitchProps,
) {
return (
<View style={props.disabled && styles.disabled}>
<Switch {...props} />
</View>
)
}

View file

@ -0,0 +1,15 @@
import { Design } from '@revenge-mod/discord/design'
import { PageSpacing, styles } from './_internal'
import type { DiscordModules } from '@revenge-mod/discord/types'
export default function Page(props: DiscordModules.Components.StackProps) {
return (
<Design.Stack
spacing={PageSpacing}
style={[styles.grow, styles.pagePadding]}
{...props}
>
{props.children}
</Design.Stack>
)
}

View file

@ -0,0 +1,19 @@
import { Design } from '@revenge-mod/discord/design'
import { lookupGeneratedIconComponent } from '@revenge-mod/utils/discord'
import type { DiscordModules } from '@revenge-mod/discord/types'
const MagnifyingGlassIcon = lookupGeneratedIconComponent('MagnifyingGlassIcon')
export default function SearchInput(
props: DiscordModules.Components.TextInputProps,
) {
return (
<Design.TextInput
leadingIcon={MagnifyingGlassIcon}
placeholder="Search"
returnKeyType="search"
size="md"
{...props}
/>
)
}

View file

@ -0,0 +1,27 @@
import { getAssetIdByName } from '@revenge-mod/assets'
import { Design } from '@revenge-mod/discord/design'
import type { DiscordModules } from '@revenge-mod/discord/types'
export default function TableRowAssetIcon(props: TableRowAssetIconProps) {
return (
<Design.TableRow.Icon
source={props.name ? getAssetIdByName(props.name)! : props.id!}
{...props}
/>
)
}
export type TableRowAssetIconProps = Omit<
DiscordModules.Components.TableRowIconProps,
'source'
> &
(
| {
name: string
id?: never
}
| {
name?: never
id: number
}
)

View file

@ -0,0 +1,19 @@
import { StyleSheet } from 'react-native'
export const styles = StyleSheet.create({
disabled: {
opacity: 0.5,
},
flex: {
flex: 1,
},
grow: {
flexGrow: 1,
},
pagePadding: {
paddingHorizontal: 16,
paddingTop: 12,
},
})
export const PageSpacing = 24

View file

@ -0,0 +1,4 @@
export { default as FormSwitch } from './FormSwitch'
export { default as Page } from './Page'
export { default as SearchInput } from './SearchInput'
export { default as TableRowAssetIcon } from './TableRowAssetIcon'

View file

@ -0,0 +1,12 @@
export interface PluginApiComponents {
FormSwitch: typeof import('@revenge-mod/components/FormSwitch').default
Page: typeof import('@revenge-mod/components/Page').default
SearchInput: typeof import('@revenge-mod/components/SearchInput').default
TableRowAssetIcon: typeof import('@revenge-mod/components/TableRowAssetIcon').default
}
declare module '@revenge-mod/plugins/types' {
export interface UnscopedInitPluginApi {
components: PluginApiComponents
}
}

70
lib/discord/package.json Normal file
View file

@ -0,0 +1,70 @@
{
"name": "@revenge-mod/discord",
"private": true,
"type": "module",
"exports": {
"./actions": {
"default": "./src/actions.ts"
},
"./common": {
"default": "./src/common/index.ts"
},
"./common/app-start-performance": {
"default": "./src/common/app-start-performance.ts"
},
"./common/constants": {
"default": "./src/common/constants.ts"
},
"./common/flux": {
"default": "./src/common/flux.ts"
},
"./common/import-tracker": {
"default": "./src/common/import-tracker.ts"
},
"./common/logger": {
"default": "./src/common/logger.ts"
},
"./common/tokens": {
"default": "./src/common/tokens.ts"
},
"./common/utils": {
"default": "./src/common/utils.ts"
},
"./design": {
"default": "./src/design.ts"
},
"./flux": {
"default": "./src/flux/index.ts"
},
"./native": {
"default": "./src/native.ts"
},
"./preinit": {
"default": "./src/preinit.ts"
},
"./start": {
"default": "./src/start.ts"
},
"./modules/main_tabs_v2": {
"default": "./src/modules/main_tabs_v2.ts"
},
"./modules/settings": {
"default": "./src/modules/settings/index.ts"
},
"./modules/settings/renderer": {
"default": "./src/modules/settings/renderer.ts"
},
"./utils/modules/finders": {
"default": "./src/utils/modules/finders.ts"
},
"./utils/modules/metro/subscriptions": {
"default": "./src/utils/modules/metro/subscriptions.ts"
},
"./types": {
"types": "./src/types/index.ts"
},
"./_/modules/settings": {
"default": "./src/modules/settings/_internal.ts"
}
}
}

View file

@ -0,0 +1,93 @@
import { lookupModule, lookupModules } from '@revenge-mod/modules/finders'
import {
withDependencies,
withoutProps,
withProps,
} from '@revenge-mod/modules/finders/filters'
import {
ReactJSXRuntimeModuleId,
ReactModuleId,
ReactNativeModuleId,
} from '@revenge-mod/react'
import { proxify } from '@revenge-mod/utils/proxy'
import { DispatcherModuleId } from './common/flux'
import { ImportTrackerModuleId } from './common/import-tracker'
import type { DiscordModules } from './types'
const { relative, loose } = withDependencies
// modules/action_sheet/native/ActionSheetActionCreators.tsx
export let ActionSheetActionCreators: DiscordModules.Actions.ActionSheetActionCreators =
proxify(
() => {
const [module] = lookupModule(
withProps<DiscordModules.Actions.ActionSheetActionCreators>(
'hideActionSheet',
'openLazy',
).and(
withDependencies(
loose([
null,
ReactModuleId,
ReactJSXRuntimeModuleId,
DispatcherModuleId,
relative(1),
relative(2),
]),
),
),
)
if (module) return (ActionSheetActionCreators = module)
},
{
hint: {},
},
)!
// actions/native/AlertActionCreators.tsx
export let AlertActionCreators: DiscordModules.Actions.AlertActionCreators =
proxify(
() => {
const [module] = lookupModule(
withProps<DiscordModules.Actions.AlertActionCreators>(
'openAlert',
).and(
withDependencies([
null,
null,
[ReactNativeModuleId, ImportTrackerModuleId],
relative(1),
relative(2),
ImportTrackerModuleId,
]),
),
)
if (module) return (AlertActionCreators = module)
},
{
hint: {},
},
)!
// modules/toast/native/ToastActionCreators.tsx
export let ToastActionCreators: DiscordModules.Actions.ToastActionCreators =
proxify(() => {
// [Dispatcher, ImportTracker]
// Many other modules share the same dependencies, the second yielded should be the correct module.
const generator = lookupModules(
withProps<DiscordModules.Actions.ToastActionCreators>('open')
.and(withoutProps('init'))
.and(
withDependencies([
DispatcherModuleId,
ImportTrackerModuleId,
]),
),
)
for (const [module] of generator)
if (module.open.length === 1) return (ToastActionCreators = module)
})!

View file

@ -0,0 +1 @@
export { AppStartPerformance } from '../preinit'

View file

@ -0,0 +1,21 @@
import { lookupModule } from '@revenge-mod/modules/finders'
import {
withDependencies,
withProps,
} from '@revenge-mod/modules/finders/filters'
import type { DiscordModules } from '@revenge-mod/discord/types'
const { loose, relative } = withDependencies
export const [Constants, ConstantsModuleId] = lookupModule(
withProps<DiscordModules.Constants>('ME')
.and(
withDependencies(
loose([
null,
relative.withDependencies(loose([relative(2, true)]), 1),
]),
),
)
.keyAs('revenge.discord.common.Constants'),
)

View file

@ -0,0 +1,25 @@
import { lookupModule } from '@revenge-mod/modules/finders'
import {
withDependencies,
withProps,
} from '@revenge-mod/modules/finders/filters'
import { ImportTrackerModuleId } from '../patches/import-tracker'
import type { Metro } from '@revenge-mod/modules/types'
import type { DiscordModules } from '../types'
const { relative, loose } = withDependencies
// ../discord_common/js/packages/flux
export const [Dispatcher, DispatcherModuleId] = lookupModule(
withProps<DiscordModules.Flux.Dispatcher>('_interceptors').and(
withDependencies([
relative(1),
null,
null,
withDependencies(loose([relative(1), relative(2)])),
null,
ImportTrackerModuleId,
]),
),
) as [DiscordModules.Flux.Dispatcher, Metro.ModuleID]

View file

@ -0,0 +1 @@
export { ImportTrackerModuleId } from '../patches/import-tracker'

View file

@ -0,0 +1,9 @@
import { lookupModule } from '@revenge-mod/modules/finders'
import { withName } from '@revenge-mod/modules/finders/filters'
import type { DiscordModules } from '@revenge-mod/discord/types'
import type { Metro } from '@revenge-mod/modules/types'
// ../discord_common/js/packages/logger/Logger.tsx
export const [Logger, LoggerModuleId] = lookupModule(
withName<typeof DiscordModules.Logger>('Logger'),
) as [typeof DiscordModules.Logger, Metro.ModuleID]

View file

@ -0,0 +1,9 @@
import { lookupModule } from '@revenge-mod/modules/finders'
import { withProps } from '@revenge-mod/modules/finders/filters'
import type { Metro } from '@revenge-mod/modules/types'
// ../discord_common/js/packages/tokens/native.tsx
export const [Tokens, TokensModuleId] = lookupModule(withProps('RawColor')) as [
any,
Metro.ModuleID,
]

View file

@ -0,0 +1,35 @@
import { lookupModule } from '@revenge-mod/modules/finders'
import {
withDependencies,
withName,
} from '@revenge-mod/modules/finders/filters'
import { proxify } from '@revenge-mod/utils/proxy'
import { ImportTrackerModuleId } from '../patches/import-tracker'
import type { DiscordModules } from '../types'
// ../discord_common/js/shared/utils/TypedEventEmitter.tsx
/**
* Do not use the `error` event, as the module will handle it specially for some reason.
*/
export let TypedEventEmitter: typeof DiscordModules.Utils.TypedEventEmitter =
proxify(() => {
const [module] = lookupModule(
withName<typeof DiscordModules.Utils.TypedEventEmitter>(
'TypedEventEmitter',
)
.and(
withDependencies([[], ImportTrackerModuleId]).or(
// TODO: Remove when stable > 341202
withDependencies([
withName('_classCallCheck'),
withName('_createClass'),
[],
ImportTrackerModuleId,
]),
),
)
.keyAs('revenge.discord.common.utils.TypedEventEmitter'),
)
if (module) return (TypedEventEmitter = module)
})!

116
lib/discord/src/design.ts Normal file
View file

@ -0,0 +1,116 @@
import { lookupModule, lookupModules } from '@revenge-mod/modules/finders'
import { withDependencies } from '@revenge-mod/modules/finders/filters'
import { getModuleDependencies } from '@revenge-mod/modules/metro/utils'
import {
ReactJSXRuntimeModuleId,
ReactModuleId,
ReactNativeModuleId,
} from '@revenge-mod/react'
import { proxify } from '@revenge-mod/utils/proxy'
import { ImportTrackerModuleId } from './common/import-tracker'
import type { DiscordModules } from './types'
const { loose } = withDependencies
/**
* The lowest amount of dependencies `design/native.tsx` is expected to have.
*
* It's a barrel module exporting the whole design system,
* so it always has a lot of dependencies (~140 as of 341202).
*
* This is only used as a filter, and is checked before anything else for performance reasons.
*/
const DesignMinimumDependencies = 64
// design/native.tsx
export let Design: Design = proxify(
() => {
// ID: 13171
// [3909, 4608, 5182, 13172, 2, ...] (141 dependencies)
const [, id] = lookupModule(
withDependencies<Design>(
loose([
[ImportTrackerModuleId],
[ImportTrackerModuleId],
[ReactNativeModuleId, ImportTrackerModuleId],
[ImportTrackerModuleId],
ImportTrackerModuleId,
...Array<null>(DesignMinimumDependencies - 5).fill(null),
]),
).keyAs('revenge.discord.design.Design'),
{
initialize: false,
},
)
if (id === undefined) return
const module = __r(id)!
if (module.TableRow && module.Button) return (Design = module)
},
{
hint: {},
},
)!
// design/components/Forms/native/FormSwitch.native.tsx
export let FormSwitch: DiscordModules.Components.FormSwitch = proxify(() => {
// TODO: Possibly come up with a better dependency fingerprinting API
// to not have to deal with this bullshit
for (const [, id] of lookupModules(
withDependencies(
loose([
null,
ReactModuleId,
ReactNativeModuleId,
ReactJSXRuntimeModuleId,
]),
).keyAs('revenge.discord.design.FormSwitch'),
{
initialize: false,
},
)) {
const deps = getModuleDependencies(id)!
if (deps.at(-1) !== ImportTrackerModuleId) continue
if (deps.at(-4) === id + 2 && deps.at(-5) === id + 1) {
const FormSwitch_ = __r(id)!.FormSwitch
if (FormSwitch_) return (FormSwitch = FormSwitch_)
}
}
})!
export interface Design {
createStyles: DiscordModules.Components.Styles.CreateStylesFunction
useTooltip: DiscordModules.Components.UseTooltipFunction
TextStyleSheet: DiscordModules.Components.Styles.TextStyleSheet
ActionSheet: DiscordModules.Components.ActionSheet
ActionSheetRow: DiscordModules.Components.ActionSheetRow
ActionSheetSwitchRow: DiscordModules.Components.ActionSheetSwitchRow
BottomSheetTitleHeader: DiscordModules.Components.BottomSheetTitleHeader
AlertActionButton: DiscordModules.Components.AlertActionButton
AlertModal: DiscordModules.Components.AlertModal
Button: DiscordModules.Components.Button
Card: DiscordModules.Components.Card
ContextMenu: DiscordModules.Components.ContextMenu
ContextMenuItem: DiscordModules.Components.ContextMenuItem
FloatingActionButton: DiscordModules.Components.FloatingActionButton
IconButton: DiscordModules.Components.IconButton
ImageButton: DiscordModules.Components.ImageButton
LayerScope: DiscordModules.Components.LayerScope
NavigatorHeader: DiscordModules.Components.NavigatorHeader
Stack: DiscordModules.Components.Stack
Slider: DiscordModules.Components.Slider
TableCheckboxRow: DiscordModules.Components.TableCheckboxRow
TableRadioGroup: typeof DiscordModules.Components.TableRadioGroup
TableRadioRow: typeof DiscordModules.Components.TableRadioRow
TableRow: DiscordModules.Components.TableRow
TableRowGroup: DiscordModules.Components.TableRowGroup
TableSwitchRow: DiscordModules.Components.TableSwitchRow
Text: DiscordModules.Components.Text
TextArea: DiscordModules.Components.TextArea
TextField: DiscordModules.Components.TextField
TextInput: DiscordModules.Components.TextInput
}

View file

@ -0,0 +1,67 @@
import { fPatches, fPatchesAll } from '../patches/flux'
import type { DiscordModules } from '../types'
export type FluxEventDispatchPatch<T extends object = object> = (
payload: DiscordModules.Flux.DispatcherPayload & T,
) => (DiscordModules.Flux.DispatcherPayload & T) | undefined | void
/**
* Registers a patch for all Flux events.
*
* @see {@link onFluxEventDispatched} for more details.
*
* @param patch The patch function to apply when any Flux event is dispatched.
* @returns A function that can be used to remove the patch.
*/
export function onAnyFluxEventDispatched(patch: FluxEventDispatchPatch) {
fPatchesAll.add(patch)
return () => {
fPatchesAll.delete(patch)
}
}
/**
* Registers a patch for a specific Flux event type.
* @param type The type of the Flux event to patch.
* @param patch The patch function to apply when the event is dispatched.
* @returns A function that can be used to remove the patch.
*
* @example Blocking the disptach
* ```ts
* // Returning falsy values will prevent the event from being dispatched.
* onFluxEventDispatched('TYPING_START', () => {})
* ```
*
* @example Modifying the payload
* ```ts
* onFluxEventDispatched('TYPING_START', payload => {
* // Send the typing event to this channel instead.
* payload.channelId = '123456789012345678'
* // Make sure to return the modified payload!
* return payload
* })
* ```
*
* @example Reading and passing through the payload
* ```ts
* onFluxEventDispatched('TYPING_START', payload => {
* console.log('Typing started:', payload)
* // Do nothing, just return the payload.
* return payload
* })
* ```
*/
export function onFluxEventDispatched<T extends object = object>(
type: DiscordModules.Flux.DispatcherPayload['type'],
patch: FluxEventDispatchPatch<T>,
) {
let set = fPatches.get(type)
if (!set) fPatches.set(type, (set = new Set<FluxEventDispatchPatch>()))
set.add(patch)
return () => {
set.delete(patch)
}
}

View file

@ -0,0 +1,2 @@
export * from './dispatcher'
export * from './stores'

View file

@ -0,0 +1,159 @@
import { ImportTrackerModuleId } from '@revenge-mod/discord/common/import-tracker'
import {
lookupModule,
lookupModules,
waitForModules,
} from '@revenge-mod/modules/finders'
import {
createFilterGenerator,
withDependencies,
withName,
} from '@revenge-mod/modules/finders/filters'
import { getModuleDependencies } from '@revenge-mod/modules/metro/utils'
import { asap, noop } from '@revenge-mod/utils/callback'
import {
cache,
cacheFilterResultForId,
Uncached,
} from '../../../modules/src/caches'
import { FilterResultFlags } from '../../../modules/src/finders/_internal'
import {
FilterFlag,
FilterScopes,
} from '../../../modules/src/finders/filters/constants'
import type {
Filter,
FilterGenerator,
} from '@revenge-mod/modules/finders/filters'
import type { DiscordModules } from '../types'
/// STORES
const _stores: Record<string, DiscordModules.Flux.Store> = {}
/**
* A proxy that allows you to access Flux stores by their name, including uninitialized stores.
*
* Use `Reflect.ownKeys()` on this proxy to get a list of all initialized stores.
*
* @see {@link getStore} for a way to get stores lazily.
*/
export const Stores = new Proxy(_stores, {
ownKeys: target => Reflect.ownKeys(target),
get: (target, prop: string) =>
target[prop] ?? lookupModule(withStoreName(prop))[0],
})
/**
* Gets a Flux store by its name, and calls the provided callback with the store.
*
* @param name The name of the store to get.
* @param callback A callback that will be called with the store once it is found.
* @returns A function that can be used to cancel the wait for the store.
*/
export function getStore<T>(
name: string,
callback: (store: DiscordModules.Flux.Store<T>) => void,
) {
const store = _stores[name]
if (store) {
callback(store as DiscordModules.Flux.Store<T>)
return noop
}
return waitForModules(withStoreName<T>(name), callback, { cached: true })
}
/// STORE FILTERING
/*
Flux Store dependencies: [
_classCallCheck
_createClass
_possibleConstructorReturn
bound getPrototypeOf
_inherits
(...), // (any amount of dependencies)
ImportTracker
]
*/
const withLeadingFluxStoreDeps = withDependencies(
withDependencies.loose([
withName('_classCallCheck'),
withName('_createClass'),
withName('_possibleConstructorReturn'),
withName('bound getPrototypeOf'),
withName('_inherits'),
]),
)
export type WithStore = FilterGenerator<
<T>() => Filter<{
Result: DiscordModules.Flux.Store<T>
RequiresExports: boolean
Scopes: [
typeof FilterScopes.Uninitialized,
typeof FilterScopes.Initialized,
]
}>
>
/**
* A dynamic filter that matches all Flux stores.
*/
export const withStore = createFilterGenerator(
(_, id, exports) => {
if (exports) return Boolean(exports._dispatchToken)
else {
if (!withLeadingFluxStoreDeps(id)) return false
const deps = getModuleDependencies(id)!
return deps[deps.length - 1] === ImportTrackerModuleId
}
},
() => 'revenge.discord.store',
FilterFlag.Dynamic,
FilterScopes.Uninitialized | FilterScopes.Initialized,
) as WithStore
export type WithStoreName = FilterGenerator<
<T>(name: string) => Filter<{
Result: DiscordModules.Flux.Store<T>
RequiresExports: true
Scopes: [
typeof FilterScopes.Uninitialized,
typeof FilterScopes.Initialized,
]
}>
>
/**
* A with-exports filter that matches a Flux store by its name.
*/
export const withStoreName = createFilterGenerator(
([name], _, exports) =>
exports?.getName?.length === 0 && exports.getName() === name,
([name]) => `revenge.discord.storeName(${name})`,
FilterFlag.RequiresExports,
FilterScopes.Uninitialized | FilterScopes.Initialized,
) as WithStoreName
/// STORE CACHING
waitForModules(withStore(), (store, id) => {
const name = store.getName()
// Cache stores
cacheFilterResultForId(
withStoreName.keyFor([name]),
id,
FilterResultFlags.Default,
)
Stores[name] = store
})
if (cache === Uncached)
asap(() => {
const lookup = lookupModules(withStore())
while (lookup.next().done);
})

View file

@ -0,0 +1,44 @@
import { lookupModule } from '@revenge-mod/modules/finders'
import {
withDependencies,
withProps,
} from '@revenge-mod/modules/finders/filters'
import { proxify } from '@revenge-mod/utils/proxy'
import { ImportTrackerModuleId } from '../common/import-tracker'
import type { NavigationContainerRef } from '@react-navigation/core'
const { loose, relative } = withDependencies
export interface RootNavigationRef {
getRootNavigationRef<
T extends object = Record<string, unknown>,
>(): NavigationContainerRef<T>
}
// modules/main_tabs_v2/RootNavigationRef.native.tsx
export let RootNavigationRef: RootNavigationRef = proxify(
() => {
const [module] = lookupModule(
withProps<RootNavigationRef>('getRootNavigationRef')
.and(
withDependencies([
loose([
relative.withDependencies([], 1),
relative.withDependencies(
loose([relative(1), relative(2)]),
2,
),
]),
// TODO: Decouple?
ImportTrackerModuleId,
]),
)
.keyAs('revenge.discord.modules.mainTabsV2.RootNavigationRef'),
)
if (module) return (RootNavigationRef = module)
},
{
hint: {},
},
)!

View file

@ -0,0 +1,27 @@
import { noop } from '@revenge-mod/utils/callback'
import type {
SettingsItem,
SettingsModulesLoadedSubscription,
SettingsSection,
} from '.'
// Sections to splice in the SettingsOverviewScreen
export const sSections: Record<string, SettingsSection> = {}
// SETTING_RENDERER_CONFIG settings
export const sConfig: Record<string, SettingsItem> = {}
export const sSubscriptions = new Set<SettingsModulesLoadedSubscription>()
/**
* Refresh IDs and re-render callbacks for the settings UI.
*
* IDs increment when a refresh is requested.
* Patches check if they changed and recomputes/rerenders the hooks/components.
*/
export const sRefresher = {
navigator: 0,
overviewScreen: 0,
callNavigator: noop,
callOverviewScreen: noop,
callSearchableSettingsList: noop,
}

View file

@ -0,0 +1,158 @@
import { noop } from '@revenge-mod/utils/callback'
import { sLoaded } from '../../start'
import { sConfig, sRefresher, sSections, sSubscriptions } from './_internal'
import type { DiscordModules } from '../../types'
export type SettingsItem = DiscordModules.Modules.Settings.SettingsItem
export type SettingsSection = DiscordModules.Modules.Settings.SettingsSection
export type SettingsModulesLoadedSubscription = () => void
/**
* Checks if the settings modules are loaded.
*/
export function isSettingsModulesLoaded() {
return sLoaded
}
/**
* Subscribes to when settings modules are loaded.
* Plugins should ideally register their settings in the given callback to ensure fast startup time.
*
* If settings modules are already loaded, the callback will be called immediately.
*
* @param subcription The subscription function to call when the settings modules are loaded.
* @returns A function to unsubscribe from the event.
*/
export function onSettingsModulesLoaded(
subcription: SettingsModulesLoadedSubscription,
) {
if (isSettingsModulesLoaded()) {
subcription()
return noop
}
sSubscriptions.add(subcription)
return () => {
sSubscriptions.delete(subcription)
}
}
/**
* Registers a settings section with a given key.
*
* @param key The key to register the settings section with.
* @param section The settings section to register.
* @returns A function to unregister the settings section.
*/
export function registerSettingsSection(key: string, section: SettingsSection) {
sSections[key] = section
return () => {
delete sSections[key]
}
}
/**
* Registers a settings item with a given key.
*
* @param key The key to register the settings item with.
* @param item The settings item to register.
* @returns A function to unregister the settings item.
*/
export function registerSettingsItem(key: string, item: SettingsItem) {
sConfig[key] = item
return () => {
delete sConfig[key]
}
}
/**
* Registers multiple settings items at once.
*
* @param record The settings items to register.
* @returns A function to unregister the settings items.
*/
export function registerSettingsItems(record: Record<string, SettingsItem>) {
Object.assign(sConfig, record)
return () => {
for (const key of Object.keys(record)) delete sConfig[key]
}
}
/**
* Adds a settings item to an existing section.
*
* @param key The section to add the settings item to.
* @param item The settings item to add.
* @param index The index to insert the settings item at. Defaults to -1 (end of the section).
* @returns A function to remove the settings item from the section.
*/
export function addSettingsItemToSection(
key: string,
item: string,
index?: number,
): () => void
/**
* Adds a settings item to an existing section.
*
* @param key The section to add the settings item to.
* @param fn A function that takes the current settings items and returns the new settings items. Removing items will result in an error.
* @returns A function to remove the settings items from the section.
*/
export function addSettingsItemToSection(
key: string,
fn: (items: string[]) => string[],
): () => void
export function addSettingsItemToSection(
key: string,
item: string | ((items: string[]) => string[]),
index = -1,
) {
const section = sSections[key]
if (!section) throw new Error(`Section "${key}" does not exist`)
if (typeof item === 'function') {
const before = [...section.settings]
const after = [...item(before)]
const added = after.filter(i => !before.includes(i))
const removed = before.filter(i => !after.includes(i))
if (removed.length > 0)
throw new Error(
`Cannot remove settings items from section "${key}"`,
)
section.settings = after
return () => {
section.settings = section.settings.filter(i => !added.includes(i))
}
} else {
const actualIndex =
index < 0 ? section.settings.length + (index + 1) : index
section.settings.splice(actualIndex, 0, item)
return () => {
const idx = section.settings.indexOf(item)
if (idx !== -1) section.settings.splice(idx, 1)
}
}
}
function refreshSettingsOverviewScreen() {
sRefresher.overviewScreen++
sRefresher.callOverviewScreen()
}
function refreshSettingsNavigator() {
sRefresher.navigator++
sRefresher.callNavigator()
sRefresher.callSearchableSettingsList()
}
/**
* Refreshes the settings UI.
*/
export function refreshSettings() {
refreshSettingsOverviewScreen()
refreshSettingsNavigator()
}

View file

@ -0,0 +1,46 @@
import { lookupModule } from '@revenge-mod/modules/finders'
import {
withDependencies,
withProps,
} from '@revenge-mod/modules/finders/filters'
import {
ReactJSXRuntimeModuleId,
ReactModuleId,
ReactNativeModuleId,
} from '@revenge-mod/react'
import { proxify } from '@revenge-mod/utils/proxy'
import type { DiscordModules } from '../../types'
const { loose, relative } = withDependencies
export type SettingListRenderer =
DiscordModules.Modules.Settings.SettingListRenderer
// modules/settings/native/renderer/SettingListRenderer.tsx
export let SettingListRenderer: SettingListRenderer = proxify(
() => {
const [module] = lookupModule(
withProps<SettingListRenderer>('SettingsList')
.and(
withDependencies(
loose([
ReactModuleId,
ReactNativeModuleId,
relative(1),
relative(2),
null,
ReactJSXRuntimeModuleId,
]),
),
)
.keyAs(
'revenge.discord.modules.settings.renderer.SettingListRenderer',
),
)
if (module) return (SettingListRenderer = module)
},
{
hint: {},
},
)!

55
lib/discord/src/native.ts Normal file
View file

@ -0,0 +1,55 @@
import { getNativeModule } from '@revenge-mod/modules/native'
import { proxify } from '@revenge-mod/utils/proxy'
import type { DiscordNativeModules } from './types/native'
/**
* Naming conventions:
* - Always use the most recent module name (if we can do it in a non-breaking way)
* - If the module name starts with "Native", remove it
* - If the module name starts with "RTN", remove it
* - If the module name ends with "Module", include it
* - If the module name ends with "Manager", include it
*/
export let CacheModule: DiscordNativeModules.CacheModule = proxify(() => {
const module = getNativeModule<typeof CacheModule>('NativeCacheModule')
if (module) return (CacheModule = module)
})!
export let FileModule: DiscordNativeModules.FileModule = proxify(() => {
const module = getNativeModule<typeof FileModule>('NativeFileModule')
if (module) return (FileModule = module)
})!
export let ClientInfoModule: DiscordNativeModules.ClientInfoModule = proxify(
() => {
const module = getNativeModule<typeof ClientInfoModule>(
'NativeClientInfoModule',
)
if (module) return (ClientInfoModule = module)
},
)!
export let DeviceModule: DiscordNativeModules.DeviceModule = proxify(() => {
const module = getNativeModule<typeof DeviceModule>('NativeDeviceModule')
if (module) return (DeviceModule = module)
})!
export let ThemeModule: DiscordNativeModules.ThemeModule = proxify(() => {
const module = getNativeModule<typeof ThemeModule>('NativeThemeModule')
if (module) return (ThemeModule = module)
})!
export let BundleUpdaterManager: DiscordNativeModules.BundleUpdaterManager =
proxify(() => {
const module = getNativeModule<typeof BundleUpdaterManager>(
'BundleUpdaterManager',
)
if (module) return (BundleUpdaterManager = module)
})!

View file

@ -0,0 +1,30 @@
import { Dispatcher } from '../common/flux'
import type { FluxEventDispatchPatch } from '../flux/dispatcher'
export const fPatchesAll: Set<FluxEventDispatchPatch<any>> = new Set()
export const fPatches: Map<string, Set<FluxEventDispatchPatch<any>>> = new Map()
const originalDispatch = Dispatcher.dispatch.bind(Dispatcher)
Dispatcher.dispatch = payload => {
let res: typeof payload | undefined | void = payload
for (const patch of fPatchesAll)
try {
res = patch(res!)
if (!res) break
} catch {}
if (res) {
const specifics = fPatches.get(payload.type)
if (specifics?.size)
for (const patch of specifics)
try {
res = patch(res!)
if (!res) break
} catch {}
}
if (res) return originalDispatch(res)
// If res is undefined, the event is blocked
return Promise.resolve()
}

View file

@ -0,0 +1,36 @@
import { getModules } from '@revenge-mod/modules/finders'
import { withProps } from '@revenge-mod/modules/finders/filters'
import { mInitializingId } from '@revenge-mod/modules/metro/patches'
import type { Metro } from '@revenge-mod/modules/types'
export type ModuleFinishedImportingCallback = (
id: Metro.ModuleID,
path: string,
) => void
export const sImportedPath = new Set<ModuleFinishedImportingCallback>()
export const mImportedPaths = new Map<string, Metro.ModuleID>()
export let ImportTrackerModuleId: Metro.ModuleID
getModules(withProps('fileFinishedImporting'), (exports, id) => {
ImportTrackerModuleId = id
const orig = exports.fileFinishedImporting
exports.fileFinishedImporting = (path: string) => {
orig(path)
const id = mInitializingId!
mImportedPaths.set(path, id)
executeImportedPathSubscriptions(id, path)
}
})
export function executeImportedPathSubscriptions(
id: Metro.ModuleID,
path: string,
) {
for (const cb of sImportedPath)
try {
cb(id, path)
} catch {}
}

View file

@ -0,0 +1,34 @@
import { lookupModule } from '@revenge-mod/modules/finders'
import {
withDependencies,
withName,
withProps,
} from '@revenge-mod/modules/finders/filters'
import { ImportTrackerModuleId } from './patches/import-tracker'
import type { Metro } from '@revenge-mod/modules/types'
import type { DiscordModules } from './types'
const [, _asyncToGeneratorModuleId] = lookupModule(
withName('_asyncToGenerator'),
)
const [, _classCallCheckModuleId] = lookupModule(withName('_classCallCheck'))
const [, _createClassModuleId] = lookupModule(withName('_createClass'))
// ../discord_common/js/packages/app-start-performance/AppStartPerformance.tsx
export const [AppStartPerformance] = lookupModule(
withProps<DiscordModules.AppStartPerformance>('markAndLog').and(
withDependencies([_asyncToGeneratorModuleId, ImportTrackerModuleId]).or(
// TODO: Remove once stable >341202
withDependencies([
_asyncToGeneratorModuleId,
_classCallCheckModuleId,
_createClassModuleId,
ImportTrackerModuleId,
]),
),
),
) as [DiscordModules.AppStartPerformance, Metro.ModuleID]
AppStartPerformance.mark('👊', 'Pre-init')
import './patches/flux'

43
lib/discord/src/start.ts Normal file
View file

@ -0,0 +1,43 @@
import { waitForModules } from '@revenge-mod/modules/finders'
import { withProps } from '@revenge-mod/modules/finders/filters'
import { sConfig, sSubscriptions } from './modules/settings/_internal'
import type { SettingsItem } from './modules/settings'
export let sLoaded = false
const unsubSRC = waitForModules(
withProps<{ SETTING_RENDERER_CONFIG: Record<string, SettingsItem> }>(
'SETTING_RENDERER_CONFIG',
),
SettingRendererConfig => {
unsubSRC()
sLoaded = true
for (const sub of sSubscriptions)
try {
sub()
} catch {}
// We don't ever need to call this again
sSubscriptions.clear()
let { SETTING_RENDERER_CONFIG: ORIGINAL } = SettingRendererConfig
Object.defineProperty(
SettingRendererConfig,
'SETTING_RENDERER_CONFIG',
{
get: () =>
({
...ORIGINAL,
...sConfig,
}) as Record<string, SettingsItem>,
set: v => (ORIGINAL = v),
},
)
},
{
cached: true,
},
)

View file

@ -0,0 +1,7 @@
import type { DiscordModules } from '.'
declare module '@revenge-mod/plugins/types' {
export interface InitPluginApi<O extends PluginApiExtensionsOptions> {
logger: DiscordModules.Logger
}
}

View file

@ -0,0 +1,734 @@
import type { StackScreenProps } from '@react-navigation/stack'
import type { ReactNavigationParamList } from '@revenge-mod/externals/react-navigation'
import type { AnyFunction } from '@revenge-mod/utils/types'
import type {
ComponentProps,
ComponentType,
FC,
MemoExoticComponent,
ReactElement,
ReactNode,
RefAttributes,
RefObject,
} from 'react'
import type {
ImageSourcePropType,
ImageStyle,
PressableProps,
TextInputProps as RNTextInputProps,
TextProps as RNTextProps,
StyleProp,
TextStyle,
View,
ViewProps,
ViewStyle,
} from 'react-native'
export * from './api'
export * from './native'
export * from './polyfills'
export namespace DiscordModules {
export namespace Flux {
export interface DispatcherPayload {
type: string
[key: PropertyKey]: any
}
export type DispatcherDependency = any
export interface StoreChangeCallbacks {
add(cb: () => void): void
addConditional(cb: () => boolean): void
listeners: Set<() => void>
remove(cb: () => void): void
has(cb: () => void): boolean
hasAny(): boolean
invokeAll(): void
}
export type Store<T = object> = T & {
addChangeListener(cb: () => void): void
removeChangeListener(cb: () => void): void
addReactChangeListener(cb: () => void): void
removeReactChangeListener(cb: () => void): void
addConditionalChangeListener(cb: () => boolean): void
callback(cb: () => void): void
throttledCallback(): unknown
getName(): string
__getLocalVars?(): object
_changeCallbacks: StoreChangeCallbacks
_isInitialized: boolean
_version: number
_reactChangeCallbacks: StoreChangeCallbacks
_dispatchToken: string
}
export interface Dispatcher {
_actionHandlers: unknown
_interceptors?: ((
payload: DispatcherPayload,
) => undefined | boolean)[]
_currentDispatchActionType: undefined | string
_processingWaitQueue: boolean
_subscriptions: Record<
string,
Set<(payload: DispatcherPayload) => void>
>
_waitQueue: unknown[]
addDependencies(
node1: DispatcherDependency,
node2: DispatcherDependency,
): void
dispatch(payload: DispatcherPayload): Promise<void>
flushWaitQueue(): void
isDispatching(): boolean
register(
name: string,
actionHandler: Record<string, (e: DispatcherPayload) => void>,
storeDidChange: (e: DispatcherPayload) => boolean,
): string
setInterceptor(
interceptor?: (
payload: DispatcherPayload,
) => undefined | boolean,
): void
/**
* Subscribes to an action type
* @param actionType The action type to subscribe to
* @param callback The callback to call when the action is dispatched
*/
subscribe(
actionType: string,
callback: (payload: DispatcherPayload) => void,
): void
/**
* Unsubscribes from an action type
* @param actionType The action type to unsubscribe from
* @param callback The callback to remove
*/
unsubscribe(
actionType: string,
callback: (payload: DispatcherPayload) => void,
): void
wait(cb: () => void): void
}
}
export namespace AppStartPerformance {
export type MarkArgs = [emoji: string, log: string, delta?: number]
}
export interface AppStartPerformance {
mark(...args: AppStartPerformance.MarkArgs): void
markAndLog(logger: Logger, ...args: AppStartPerformance.MarkArgs): void
[index: string]: unknown
}
export interface Constants {
[K: string]: string | number | boolean | null | AnyFunction | Constants
}
/**
* Discord's `Logger` class.
*
* Logs will be shown in the **Debug Logs** section in settings.
*/
export declare class Logger {
constructor(tag: string)
logDangerously(...args: unknown[]): void
log(...args: unknown[]): void
error(...args: unknown[]): void
warn(...args: unknown[]): void
info(...args: unknown[]): void
time(...args: unknown[]): void
trace(...args: unknown[]): void
fileOnly(...args: unknown[]): void
verboseDangerously(...args: unknown[]): void
verbose(...args: unknown[]): void
}
export namespace Actions {
export interface AlertActionCreators {
openAlert(key: string, alert: ReactElement): void
dismissAlert(key: string): void
dismissAlerts(): void
// TODO
useAlertStore(): unknown
}
export interface ToastActionCreators {
open(options: {
key: string
content?: string
icon?: number | FC
IconComponent?: FC
/**
* The icon's color, same string format as `<Text>`'s color prop
*/
iconColor?: string
containerStyle?: ViewStyle
}): void
close(): void
}
export interface ActionSheetActionCreators {
openLazy<T extends ComponentType<any>>(
sheet: Promise<{ default: T }>,
key: string,
props: ComponentProps<T>,
): void
hideActionSheet(key?: string): void
}
// export namespace ActionSheetActionCreators {
// interface SimpleActionSheetOption {
// icon?: number
// label: string
// isDestructive?: boolean
// disabled?: boolean
// onPress?(): void
// }
// function showSimpleActionSheet(options: {
// key: string
// header: {
// title: string
// icon?: ReactNode
// onClose?(): void
// }
// options: SimpleActionSheetOption[]
// }): void
// }
}
export namespace Components {
export namespace Styles {
export type TextType = 'heading' | 'text'
export type BasicTextSize = 'sm' | 'md' | 'lg'
export type BasicTextSizeWithExtraLarges =
| BasicTextSize
| 'xl'
| 'xxl'
export type TextSize = BasicTextSizeWithExtraLarges | 'xs' | 'xxs'
export type TextWeight = 'normal' | 'medium' | 'semibold' | 'bold'
export type TextWeightWithExtraBold = TextWeight | 'extrabold'
export type RedesignTextCategory =
| 'message-preview'
| 'channel-title'
export type TextVariant =
| `heading-${BasicTextSizeWithExtraLarges}/${TextWeightWithExtraBold}`
| `text-${TextSize}/${TextWeight}`
| `display-${BasicTextSize}`
| `redesign/${RedesignTextCategory}/${TextWeight}`
| 'redesign/heading-18/bold'
| 'eyebrow'
export type TextStyleSheet = Record<TextVariant, TextStyle>
export type CreateStylesFunction = <
const S extends Record<
string,
TextStyle | ViewStyle | ImageStyle
>,
>(
styles: S,
) => () => S
}
export type UseTooltipFunction = (
ref: RefObject<View | null>,
props: UseTooltipFunctionProps,
) => unknown
export interface UseTooltipFunctionProps {
label: string
position?: 'top' | 'bottom'
visible?: boolean
onPress?: () => void
}
export interface BaseButtonProps
extends PressableProps,
RefAttributes<View> {
disabled?: boolean
size?: ButtonSize
variant?:
| 'primary'
| 'secondary'
| 'tertiary'
| 'destructive'
| 'active'
| 'primary-overlay'
| 'secondary-overlay'
loading?: boolean
grow?: boolean
scaleAmountInPx?: number
}
export interface ButtonProps extends BaseButtonProps {
icon?: number
loading?: boolean
iconPosition?: 'start' | 'end'
renderIcon?(): ReactNode
renderRightIcon?(): ReactNode
renderShine?(): ReactNode
renderLinearGradient?(): ReactNode
cornerRadius?: number
textStyle?: TextStyle
loadingColorLight?: string
loadingColorDark?: string
text: string
}
// Buttons
export type ButtonSize = 'sm' | 'md' | 'lg'
export type Button = FC<ButtonProps>
export interface IconButtonProps extends BaseButtonProps {
icon: number
label?: string
}
export type IconButton = FC<IconButtonProps>
export interface ImageButtonProps extends BaseButtonProps {
image: ImageSourcePropType
}
export type ImageButton = FC<ImageButtonProps>
export interface FloatingActionButtonProps {
icon: number
onPress: () => void
disabled?: boolean
positionBottom?: number
accessibilityLabel?: string
}
export type FloatingActionButton = FC<FloatingActionButtonProps>
export interface StackProps extends ViewProps {
spacing?: number
align?: ViewStyle['alignItems']
justify?: ViewStyle['justifyContent']
direction?: 'vertical' | 'horizontal'
}
export type Stack = FC<StackProps>
export interface CardProps extends ViewProps {
start?: boolean
end?: boolean
variant?: 'primary' | 'secondary' | 'transparent'
border?: 'faint' | 'normal' | 'strong' | 'subtle' | 'none'
shadow?: 'none' | 'low' | 'medium' | 'high' | 'border' | 'ledge'
children: ReactNode
}
export type Card = FC<CardProps>
// Inputs
export interface TextFieldProps {
onChange?: (value: string) => void
onBlur?: () => void
onFocus?: () => void
leadingIcon?: FC
trailingIcon?: FC
leadingText?: string
trailingText?: string
description?: string
errorMessage?: string
isDisabled?: boolean
focusable?: boolean
editable?: boolean
status?: TextFieldStatus
defaultValue?: string
value?: string
placeholder?: string
placeholderTextColor?: string
maxLength?: number
multiline?: boolean
autoFocus?: boolean
secureTextEntry?: boolean
returnKeyType?: RNTextInputProps['returnKeyType']
isClearable?: boolean
size?: TextFieldSize
style?: StyleProp<ViewStyle>
}
export type TextFieldSize = 'sm' | 'md' | 'lg'
export type TextFieldStatus = 'default' | 'error'
export interface TextInputProps extends TextFieldProps {
isRound?: boolean
label?: string
}
export interface TextAreaProps
extends Omit<TextInputProps, 'multiline'> {}
export type TextInput = FC<TextInputProps>
export type TextField = FC<TextFieldProps>
export type TextArea = FC<TextAreaProps>
export interface FormSwitchProps extends ViewProps {
value: boolean
onValueChange(value: boolean): void
disabled?: boolean
}
export type FormSwitch = FC<FormSwitchProps>
// TODO
// export type FormRadio = FC
// export type FormCheckbox = FC
export interface ActionSheetProps {
children: ReactNode
}
export type ActionSheet = FC<ActionSheetProps>
export interface ActionSheetCloseButtonProps
extends Pick<ComponentProps<IconButton>, 'variant' | 'onPress'> {}
export type ActionSheetCloseButton = FC<ActionSheetCloseButtonProps>
export type ActionSheetRow = TableRow
export type ActionSheetRowIcon = TableRowIcon
export type ActionSheetRowGroup = TableRowGroup
export type ActionSheetSwitchRow = TableSwitchRow
// TODO
// export type ActionSheetIconHeader = FC
// export type ActionSheetHeaderBar = FC
export interface BottomSheetTitleHeaderProps {
leading?: ReactNode
title: string
trailing?: ReactNode
}
export type BottomSheetTitleHeader = FC<BottomSheetTitleHeaderProps>
export type IconSize =
| 'extraSmall10'
| 'extraSmall'
| 'small'
| 'small20'
| 'medium'
| 'large'
| 'custom'
| 'refreshSmall16'
| 'small14'
export type TableRowVariant = 'default' | 'danger'
export interface TableCheckboxRowProps
extends Omit<TableRowProps, 'trailing'> {
checked: boolean
value: string
}
export type TableCheckboxRow = FC<TableCheckboxRowProps>
export interface TableRadioGroupProps<T = string>
extends TableRowGroupProps {
children: ReactNode
onChange: (value: T) => void
defaultValue?: T
}
export interface TableRadioRowProps<T = any> extends TableRowProps {
label: string
value: T
}
export declare function TableRadioGroup<T>(
props: TableRadioGroupProps<T>,
): ReactElement
export declare function TableRadioRow<T>(
props: TableRadioRowProps<T>,
): ReactElement
export interface TableRowProps {
label: string
subLabel?: ReactNode
icon?: ReactNode
trailing?: ReactNode
arrow?: boolean
onPress?: PressableProps['onPress']
disabled?: boolean
draggable?: boolean
dragHandlePressableProps?: PressableProps
labelLineClamp?: number
subLabelLineClamp?: number
start?: boolean
end?: boolean
variant?: TableRowVariant
}
export interface TableRow extends FC<TableRowProps> {
Arrow: FC
Icon: TableRowIcon
Group: TableRowGroup
TrailingText: TableRowTrailingText
}
export interface TableSwitchRowProps
extends Omit<TableRowProps, 'trailing'> {
accessibilityHint?: string
value: boolean
onValueChange(value: boolean): void
}
export type TableSwitchRow = FC<TableSwitchRowProps>
export interface TableRowGroupProps {
title?: string
description?: string
hasIcons?: boolean
accessibilityLabel?: string
accessibilityRole?: string
children: ReactNode
}
export type TableRowGroup = FC<TableRowGroupProps>
export interface TableRowGroupTitleProps {
title: string
}
export type TableRowGroupTitle = FC<TableRowGroupTitleProps>
export type TableRowIconVariant =
| 'default'
| 'danger'
| 'secondary'
| 'translucent'
export interface TableRowIconProps {
source: ImageSourcePropType
variant?: TableRowIconVariant
}
export type TableRowIcon = FC<TableRowIconProps>
export interface TableRowTrailingTextProps {
text: string
}
export type TableRowTrailingText = FC<TableRowTrailingTextProps>
export interface AlertModalProps {
title?: ReactNode
content?: ReactNode
extraContent?: ReactNode
actions?: ReactNode
}
export type AlertModal = FC<AlertModalProps>
export type AlertActionButton = Button
export interface ContextMenuProps {
title: ReactNode
triggerOnLongPress?: boolean
items: Array<ContextMenuItem | ContextMenuItem[]>
align?: 'left' | 'right' | 'above' | 'below'
children: (props: Partial<BaseButtonProps>) => ReactNode
}
export type ContextMenu = FC<ContextMenuProps>
export interface ContextMenuItem {
label: string
IconComponent?: FC
variant?: 'default' | 'destructive'
action(): void
}
export interface TextProps extends RNTextProps {
variant?: Styles.TextVariant
color?: string
style?: StyleProp<TextStyle>
lineClamp?: number
ellipsizeMode?: 'head' | 'middle' | 'tail' | 'clip'
tabularNumbers?: boolean
children?: ReactNode
}
export type Text = FC<TextProps>
export interface IntlLinkProps {
target: string
children?: ReactNode
}
export type IntlLink = FC<IntlLinkProps>
export interface SliderProps {
step: number
value: number
minimumValue: number
maximumValue: number
onValueChange: (value: number) => void
onSlidingStart?: () => void
onSlidingComplete?: (value: number) => void
startIcon?: ReactNode
endIcon?: ReactNode
}
export type Slider = FC<SliderProps>
export interface NavigatorHeaderProps {
icon?: ReactNode
title: string
subtitle?: string
}
export type NavigatorHeader = FC<NavigatorHeaderProps>
export interface LayerScopeProps {
children?: ReactNode
zIndex?: number
}
export type LayerScope = FC<LayerScopeProps>
}
export namespace Modules {
export namespace Settings {
export interface SettingListRenderer {
SettingsList: SettingsList
SearchableSettingsList: SearchableSettingsList
}
export interface SettingsListProps {
containerStyle?: StyleProp<ViewStyle>
initialSetting?: string
node: {
type: 'list'
ListHeaderComponent?: ComponentType
ListFooterComponent?: ComponentType
sections: Array<{
label?: string | ReactNode
settings: string[]
subLabel?: string | ReactNode
}>
}
}
export type SettingsList = MemoExoticComponent<
FC<SettingsListProps>
>
// TODO: Type props properly
export type SearchableSettingsList = MemoExoticComponent<
FC<SettingsListProps>
>
export interface SettingsSection {
label: string
settings: string[]
index?: number
}
interface BaseSettingsItem {
useTitle: () => string
parent: string | null
unsearchable?: boolean
variant?: Components.TableRowProps['variant']
IconComponent?: () => ReactNode
usePredicate?: () => boolean
useTrailing?: () => ReactNode
useDescription?: () => string
useIsDisabled?: () => boolean
}
export interface PressableSettingsItem extends BaseSettingsItem {
type: 'pressable'
withArrow?: boolean
onPress?: () => void
}
export interface ToggleSettingsItem extends BaseSettingsItem {
type: 'toggle'
useValue: () => boolean
onValueChange?: (value: boolean) => void
}
export interface RouteSettingsItem extends BaseSettingsItem {
type: 'route'
screen: {
route: string
getComponent(): ComponentType<
StackScreenProps<ReactNavigationParamList>
>
}
}
export interface StaticSettingsItem extends BaseSettingsItem {
type: 'static'
}
export type SettingsItem =
| PressableSettingsItem
| ToggleSettingsItem
| RouteSettingsItem
| StaticSettingsItem
}
}
export namespace Utils {
export namespace TypedEventEmitter {
export type DefaultEventMap = [never]
export type EventMap<T> = Record<keyof T, any[]> | DefaultEventMap
export type Listener<T, K extends keyof T> = T[K] extends any[]
? (...args: T[K]) => void
: never
}
export declare class TypedEventEmitter<
T extends Record<string, any[]> = Record<string, any[]>,
> {
addListener<K extends keyof T>(
event: K,
listener: TypedEventEmitter.Listener<T, K>,
): this
on<K extends keyof T>(
event: K,
listener: TypedEventEmitter.Listener<T, K>,
): this
once<K extends keyof T>(
event: K,
listener: TypedEventEmitter.Listener<T, K>,
): this
removeListener<K extends keyof T>(
event: K,
listener: TypedEventEmitter.Listener<T, K>,
): this
off<K extends keyof T>(
event: K,
listener: TypedEventEmitter.Listener<T, K>,
): this
removeAllListeners(event?: keyof T): this
emit<K extends keyof T>(event: K, ...args: T[K]): boolean
listenerCount<K extends keyof T>(
event: K,
listener?: TypedEventEmitter.Listener<T, K>,
): number
}
}
}

View file

@ -0,0 +1,254 @@
export namespace DiscordNativeModules {
/**
* Key-value storage
*/
export interface CacheModule {
/**
* Get the value for the given `key`, or null
* @param key The key to fetch
*/
getItem: (key: string) => Promise<string | null>
/**
* Deletes the value for the given `key`
* @param key The key to delete
*/
removeItem: (key: string) => void
/**
* Sets the value of `key` to `value`
*/
setItem: (key: string, value: string) => void
/**
* Goes through every item in storage and returns it, excluding the keys specified in `exclude`.
* @param exclude A list of items to exclude from result
*/
refresh: (exclude: string[]) => Promise<Record<string, string>>
/**
* Clears ALL of Discord's settings.
*/
clear: () => void
}
/**
* File manager
*/
export interface FileModule {
/**
* @param path **Full** path to file
*/
fileExists: (path: string) => Promise<boolean>
/**
* Reads an asset from the given URI
* @param nameOrUri The name or URI to read from (`http://` scheme is supported)
* @param encoding The encoding to read the asset with
* @returns
*/
readAsset: (
nameOrUri: string,
encoding: 'base64' | 'utf8',
) => Promise<string>
/**
* Allowed URI schemes on Android: `file://`, `content://` ([See here](https://developer.android.com/reference/android/content/ContentResolver#accepts-the-following-uri-schemes:_3))
*/
getSize: (uri: string) => Promise<boolean>
/**
* @param path **Full** path to file
* @param encoding Set to `base64` in order to encode response
*/
readFile(path: string, encoding: 'base64' | 'utf8'): Promise<string>
saveFileToGallery?(
uri: string,
fileName: string,
fileType: 'PNG' | 'JPEG',
): Promise<string>
/**
* @param storageDir Either `cache` or `documents`.
* @param path Path in `storageDir`, parents are recursively created.
* @param data The data to write to the file
* @param encoding Set to `base64` if `data` is base64 encoded.
* @returns Promise that resolves to path of the file once it got written
*/
writeFile(
storageDir: 'cache' | 'documents',
path: string,
data: string,
encoding: 'base64' | 'utf8',
): Promise<string>
/**
* Removes a file from the path given.
* @param storageDir Either `cache` or `documents`
* @param path Path to the file to be removed
*/
removeFile(
storageDir: 'cache' | 'documents',
path: string,
): Promise<boolean>
/**
* Clear the folder from the path given
* (!) On Android, this only clears all *files* and not subdirectories!
* @param storageDir Either `cache` or `documents`
* @param path Path to the folder to be cleared
* @returns Whether the clearance succeeded
*/
clearFolder(
storageDir: 'cache' | 'documents',
path: string,
): Promise<boolean>
getConstants(): {
/**
* The path the `documents` storage dir (see {@link writeFile}) represents.
*/
DocumentsDirPath: string
CacheDirPath: string
}
}
/**
* Client information
*/
export interface ClientInfoModule {
getConstants(): {
/**
* Sentry ingestion DSN URL for alpha/beta builds
*/
SentryAlphaBetaDsn: string
/**
* Sentry ingestion DSN URL for staff builds (?)
*/
SentryStaffDsn: string
/**
* Sentry ingestion DSN URL for stable builds
*/
SentryDsn: string
DeviceVendorID: string
Manifest: string
/**
* Version code
*
* Follows the format of `{MINOR}{CHANNEL}{PATCH}` for `{MINOR}.{PATCH} ({CHANNEL})`
* - `248200` for `248.0 (alpha)`
* - `247105` for `247.5 (beta)`
* - `246011` for `246.11 (stable)`
*/
Build: string
/**
* Version string
*
* Eg. `248.0`
*/
Version: string
/**
* Release channel
*/
ReleaseChannel: string
/**
* Matches `Version`
*/
OTABuild: string
/**
* Identifier for the installed client
*
* - **Android**: Package name
* - **iOS**: Bundle ID
*/
Identifier: string
}
}
/**
* OTA updates, app reloads, etc.
*/
export interface BundleUpdaterManager {
/**
* Reloads the app
*/
reload(): void
}
/**
* Device information
*/
export interface DeviceModule {
/**
* Returns the screen size of the device
*/
getScreenSize(): { width: number; height: number }
getConstants(): {
/**
* Maximum CPU frequency
* @example "2.00"
*/
maxCpuFreq: string
/**
* The brand of the device
* - On Android, returns the value of `ro.product.brand`
*/
deviceBrand: string
/**
* Whether the device is using gesture navigation
*/
isGestureNavigationEnabled: boolean
/**
* The manufacturer of the device
* - On Android, returns the value of `ro.product.manufacturer`
*/
deviceManufacturer: string
/**
* RAM size in gigabytes (most likely an approximation)
* @example "3.62"
*/
ramSize: string
/**
* The device's DPI setting
*/
smallestScreenWidth: number
/**
* The version of the system
* - On Android, returns the value of `ro.build.version.sdk`
*/
systemVersion: string
/**
* Whether the system taskbar navigation is enabled
*/
isTaskBarEnabled: boolean
/**
* The name of the device product
* - On Android, returns the value of `ro.product.name`
*/
deviceProduct: string
/**
* The model of the device
* - On Android, returns the value of `ro.product.model`
*/
deviceModel: string
/**
* The name of the device
* - On Android, returns the value of `ro.product.device`
*/
device: string
/**
* The name of the device board
* - On Android, returns the value of `{ro.product.manufacturer}_{ro.soc.model}`
* @example "Google_Tensor G4" // ro.product.manufacturer=Google; ro.soc.model=Tensor G4
*/
socName: string
}
}
/**
* Manage theme settings, saturation settings, etc.
*
* This only manages the native-side components and already-rendered native components will need to be re-rendered to apply changes.
*/
export interface ThemeModule {
/**
* Sets the saturation value
* @param saturation The saturation value to set
*/
updateSaturation(saturation: number): void
/**
* Sets the theme
* @param theme The theme to set
*/
updateTheme(theme: 'dark' | 'light'): void
}
}

View file

@ -0,0 +1,9 @@
/**
* Namespace import, as bundling types changes the named import back to `Buffer`,
* which makes the global reference itself.
*/
import type * as NodeBuffer from 'buffer'
declare global {
var Buffer: typeof NodeBuffer.Buffer
}

View file

@ -0,0 +1,107 @@
import { NotFoundResult } from '@revenge-mod/modules/finders'
import { onModuleInitialized } from '@revenge-mod/modules/metro/subscriptions'
import { getInitializedModuleExports } from '@revenge-mod/modules/metro/utils'
import { noop } from '@revenge-mod/utils/callback'
import { mImportedPaths } from '../../patches/import-tracker'
import { onModuleFinishedImporting } from './metro/subscriptions'
import type {
GetModulesCallback,
GetModulesUnsubscribeFunction,
LookupNotFoundResult,
WaitForModulesCallback,
WaitForModulesUnsubscribeFunction,
} from '@revenge-mod/modules/finders'
import type { Metro } from '@revenge-mod/modules/types'
/**
* Lookup an initialized module by its imported path.
*
* Think of it as if you are doing a `import * as exports from path`, the app must have already initialized the module or this will return `undefined`.
*
* @param path The path to lookup the module by.
* @returns The module exports if the module is initialized, or `undefined` if the module is not found or not initialized.
*
* @example
* ```ts
* const [{ default: Logger }] = lookupModuleWithImportedPath<{ default: typeof DiscordModules.Logger }>('modules/debug/Logger.tsx')
* ```
*/
export function lookupModuleWithImportedPath<T = any>(
path: string,
): [exports: T, id: Metro.ModuleID] | LookupNotFoundResult {
const id = mImportedPaths.get(path)
return id === undefined
? NotFoundResult
: [getInitializedModuleExports(id), id]
}
/**
* Wait for a module to initialize by its imported path. **Callback won't be called if the module is already initialized!**
*
* Once callback is called, the subscription will be removed automatically, because modules have unique imported paths.
*
* Think of it as if you are doing `import * as exports from path`, and you are also waiting for the app to initialize the module by itself.
*
* @param path The path to wait for.
* @param callback The callback to call once the module is initialized.
* @returns A function to unsubscribe.
*
* @example
* ```ts
* waitForModuleWithImportedPath(
* 'utils/PlatformUtils.tsx',
* (exports, id) => {
* // Do something with the module...
* }
* )
* ```
*/
export function waitForModuleWithImportedPath<T = any>(
path: string,
callback: WaitForModulesCallback<T>,
): WaitForModulesUnsubscribeFunction {
const unsub = onModuleFinishedImporting((id, cmpPath) => {
if (path === cmpPath) {
unsub()
// Module is not fully initialized yet, so we need to wait for it
onModuleInitialized(id, (id, exports) => {
callback(exports, id)
})
}
})
return unsub
}
/**
* Get a single module by its imported path.
* Once a module is found, unsubscription happens automatically, since imported paths are unique.
*
* @param path The path to find the module by.
* @param options The options to use for the find.
* @returns A promise that resolves to the module's exports or rejects if the find is aborted before the module is found.
*
* @example
* ```ts
* getModuleWithImportedPath('modules/main_tabs_v2/native/settings/SettingsConstants.tsx', SettingsConstants => {
* console.log('Settings page opened') // Logs once the module is initialized
* })
* ```
*/
export function getModuleWithImportedPath<T>(
path: string,
callback: GetModulesCallback<T>,
): GetModulesUnsubscribeFunction {
const [exports, id] = lookupModuleWithImportedPath(path)
if (id !== undefined) {
callback(exports, id)
return noop
}
const unsub = waitForModuleWithImportedPath(path, (exports, id) => {
unsub()
callback(exports, id)
})
return unsub
}

View file

@ -0,0 +1,19 @@
import { sImportedPath } from '../../../patches/import-tracker'
import type { ModuleFinishedImportingCallback } from '../../../patches/import-tracker'
/**
* Registers a callback to be called when a module with a specific import path is initialized.
*
* @see {@link initializedModuleHasBadExports} to avoid bad module exports.
*
* @param callback The callback to be called.
* @returns A function that unregisters the callback.
*/
export function onModuleFinishedImporting(
callback: ModuleFinishedImportingCallback,
) {
sImportedPath.add(callback)
return () => {
sImportedPath.delete(callback)
}
}

18
lib/externals/README.md vendored Normal file
View file

@ -0,0 +1,18 @@
# @revenge-mod/externals
This package provides common external libraries bundled in React Native apps, but this does not guarantee that they will be available.
This is done to ensure that Revenge's core APIs won't change if the external libraries are removed from the app.
## Libraries
For obvious reasons, this package only maintains lookups for specific versions of libraries that Discord uses.
However, it can be adapted to work with any other React Native apps.
- `@react-navigation/native`
- `@react-navigation/stack`
- `@shopify/flash-list`
- `util` (`browserify/node-util`)

22
lib/externals/package.json vendored Normal file
View file

@ -0,0 +1,22 @@
{
"name": "@revenge-mod/externals",
"private": true,
"type": "module",
"exports": {
"./browserify": {
"default": "./src/browserify.ts"
},
"./react-native-clipboard": {
"default": "./src/react-native-clipboard.ts"
},
"./react-native-safe-area-context": {
"default": "./src/react-native-safe-area-context.ts"
},
"./react-navigation": {
"default": "./src/react-navigation.ts"
},
"./shopify": {
"default": "./src/shopify.ts"
}
}
}

27
lib/externals/src/browserify.ts vendored Normal file
View file

@ -0,0 +1,27 @@
import { lookupModule } from '@revenge-mod/modules/finders'
import {
withDependencies,
withProps,
} from '@revenge-mod/modules/finders/filters'
import { proxify } from '@revenge-mod/utils/proxy'
const { loose, relative } = withDependencies
export let nodeUtil: typeof import('node:util') = proxify(
() => {
const [module] = lookupModule(
withProps<typeof nodeUtil>('inspect').and(
withDependencies([
loose([relative(2, true), relative(4, true)]),
[],
[],
]),
),
)
if (module) return (nodeUtil = module)
},
{
hint: {},
},
)!

View file

@ -0,0 +1,58 @@
import { lookupModule } from '@revenge-mod/modules/finders'
import {
withDependencies,
withProps,
} from '@revenge-mod/modules/finders/filters'
import { ReactModuleId, ReactNativeModuleId } from '@revenge-mod/react'
import { destructure, proxify } from '@revenge-mod/utils/proxy'
const { relative } = withDependencies
let ClipboardModule: typeof import('@react-native-clipboard/clipboard') =
proxify(
() => {
// ID: 4790
// r6 = 4790;
// r5 = [4791, 4792];
// r6 = 4791;
// r5 = [175, 4792];
// r6 = 4792;
// r5 = [27, 4793];
const [module] = lookupModule(
withProps<typeof ClipboardModule>('useClipboard').and(
withDependencies([
relative.withDependencies(
[ReactModuleId, relative(2, true)],
1,
),
relative.withDependencies(
[ReactNativeModuleId, relative(3, true)],
2,
),
]),
),
)
if (module) {
Clipboard = module.default
useClipboard = module.useClipboard
return (ClipboardModule = module)
}
},
{
hint: {},
},
)!
export let { default: Clipboard, useClipboard } = destructure(ClipboardModule, {
default: {
hint: {},
},
useClipboard: {
hint: () => {},
},
})

View file

@ -0,0 +1,58 @@
import { lookupModule } from '@revenge-mod/modules/finders'
import {
withDependencies,
withProps,
} from '@revenge-mod/modules/finders/filters'
import {
ReactJSXRuntimeModuleId,
ReactModuleId,
ReactNativeModuleId,
} from '@revenge-mod/react'
import { proxify } from '@revenge-mod/utils/proxy'
import type { ComparableDependencyMap } from '@revenge-mod/modules/finders/filters'
const { relative, loose } = withDependencies
const withSafeAreaContextModule = (
/* first dependency's dependencies */
firstDependencyDependencies: ComparableDependencyMap,
) =>
withDependencies(
// first dependency is next to this module, but we also need to check its dependencies
// hence relative.withDependencies(firstDependencyDependencies, 1),
loose([relative.withDependencies(firstDependencyDependencies, 1)]),
)
export let ReactNativeSafeAreaContext: typeof import('react-native-safe-area-context') =
proxify(
() => {
// TODO: Slice 1 and use once stable >341202, first dependency is dropped in modern
const oldDeps = [
null,
null,
ReactModuleId,
ReactNativeModuleId,
ReactJSXRuntimeModuleId,
relative.withDependencies([relative(1)], 1),
]
const [module] = lookupModule(
withProps<typeof ReactNativeSafeAreaContext>('SafeAreaProvider')
.and(
withSafeAreaContextModule(oldDeps.slice(1)).or(
withSafeAreaContextModule(oldDeps),
),
)
.keyAs(
'revenge.externals.ReactNativeSafeAreaContext.ReactNativeSafeAreaContext',
),
)
if (module) {
return (ReactNativeSafeAreaContext = module)
}
},
{
hint: {},
},
)!

69
lib/externals/src/react-navigation.ts vendored Normal file
View file

@ -0,0 +1,69 @@
import { lookupModule } from '@revenge-mod/modules/finders'
import {
withDependencies,
withName,
withProps,
} from '@revenge-mod/modules/finders/filters'
import { ReactJSXRuntimeModuleId, ReactModuleId } from '@revenge-mod/react'
import { proxify } from '@revenge-mod/utils/proxy'
const { loose, relative } = withDependencies
export let ReactNavigationNative: typeof import('@react-navigation/native') =
proxify(
() => {
const [module] = lookupModule(
withProps<typeof ReactNavigationNative>('useLinkTo').and(
withDependencies(
loose([
[],
loose([
[
withName('_createClass'),
withName('_classCallCheck'),
],
]),
]),
),
),
)
if (module) return (ReactNavigationNative = module)
},
{
hint: {},
},
)!
export let ReactNavigationStack: typeof import('@react-navigation/stack') =
proxify(
() => {
const firstDep = relative.withDependencies(
loose([[[]], ReactModuleId, ReactJSXRuntimeModuleId]),
1,
)
const [module] = lookupModule(
withProps<typeof ReactNavigationStack>('StackView')
.and(withDependencies(loose([firstDep, null, relative(2)])))
.keyAs(
'revenge.externals.ReactNavigation.ReactNavigationStack',
),
)
if (module) return (ReactNavigationStack = module)
},
{
hint: {},
},
)!
export interface ReactNavigationParamList {
[Page: string]: any
}
declare global {
namespace ReactNavigation {
interface RootParamList extends ReactNavigationParamList {}
}
}

54
lib/externals/src/shopify.ts vendored Normal file
View file

@ -0,0 +1,54 @@
import { ImportTrackerModuleId } from '@revenge-mod/discord/common/import-tracker'
import { lookupModule } from '@revenge-mod/modules/finders'
import {
withDependencies,
withProps,
} from '@revenge-mod/modules/finders/filters'
import {
ReactJSXRuntimeModuleId,
ReactModuleId,
ReactNativeModuleId,
} from '@revenge-mod/react'
import { proxify } from '@revenge-mod/utils/proxy'
export let FlashList: typeof import('@shopify/flash-list') = proxify(
() => {
const [module] = lookupModule(
withProps<typeof FlashList>('FlashList')
.and(
withDependencies([
ReactModuleId,
ReactNativeModuleId,
ReactJSXRuntimeModuleId,
null,
null,
null,
null,
null,
// TODO: Decouple?
ImportTrackerModuleId,
]).or(
// TODO: Remove when stable > 340206+
// [React, JSXRuntime, (Platform), (FlashListExports), (Reanimated), (RNBottomSheet), (BottomSheet), ImportTracker]
withDependencies([
ReactModuleId,
ReactJSXRuntimeModuleId,
null,
null,
null,
null,
null,
// TODO: Decouple?
ImportTrackerModuleId,
]),
),
)
.keyAs('revenge.externals.Shopify.FlashList'),
)
if (module) return (FlashList = module)
},
{
hint: {},
},
)!

View file

@ -0,0 +1,16 @@
{
"name": "@revenge-mod/json-storage",
"private": true,
"type": "module",
"exports": {
".": {
"default": "./src/index.ts"
},
"./init": {
"default": "./src/init.ts"
},
"./types": {
"types": "./src/types.ts"
}
}
}

View file

@ -0,0 +1,248 @@
import {
exists as fsExists,
getConstants,
readFile,
rm,
writeFile,
} from '@revenge-mod/modules/native/fs'
import { pluginStorageDirFor } from '@revenge-mod/plugins/constants'
import { getErrorStack } from '@revenge-mod/utils/error'
import { cloneDeep, mergeDeep } from '@revenge-mod/utils/object'
import type { AnyObject, DeepPartial, If } from '@revenge-mod/utils/types'
/**
* Get the storage path for a plugin's JSON storage document.
*
* @param id The plugin ID.
* @param file The file name (or relative path) of the storage document inside the plugin's storage directory.
*/
export const pluginStoragePathFor = (id: string, file = 'storage.json') =>
`${pluginStorageDirFor(id)}/${file}`
export type JsonStorageSubscription<T extends AnyObject = AnyObject> = (
update: DeepPartial<T>,
mode: (typeof JsonStorageUpdateMode)[keyof typeof JsonStorageUpdateMode],
) => void
export const JsonStorageUpdateMode = {
/**
* The update will be merged into the existing storage.
*/
Merge: 0,
/**
* The update will replace the existing storage.
*/
Replace: 1,
/**
* Same behavior as {@link JsonStorageUpdateMode.Replace}, but for when the storage is being synced from disk.
* E.g. on initial load, or when the storage file is deleted and recreated.
*/
Load: 2,
} as const
/**
* Create a new JSON storage object.
*
* @param path The path to the storage document.
* - Relative paths resolve against the app data directory (`/data/data/<pkg>` on Android).
* Use `files/...` for app data or `cache/...` for cache on Android.
* - Absolute paths are used as-is.
*
* @param options Options for the storage.
*/
export function JsonStorage<T extends AnyObject>(
this: JsonStorage<T>,
path: string,
options?: JsonStorageOptions<T>,
) {
const fullPath = path.startsWith('/')
? path
: `${getConstants().data}/${path}`
const subscriptions = new Set<JsonStorageSubscription<T>>()
this.loaded = false
this.exists = () => fsExists(fullPath)
this.delete = async function () {
await rm(fullPath)
const success = !(await this.exists())
if (this.loaded && success) await this.get()
return success
}
this.subscribe = callback => {
subscriptions.add(callback)
return () => subscriptions.delete(callback)
}
async function write(storage: JsonStorage<T>) {
try {
const contents = JSON.stringify(storage.cache)
await writeFile(fullPath, contents)
} catch (e) {
nativeLoggingHook(
`Failed to write storage (${fullPath}): ${getErrorStack(e)}`,
2,
)
}
}
this.get = async function () {
if (!(await this.exists())) {
this.cache = cloneDeep(options?.default ?? {})
await write(this)
this.loaded = true
return this.cache
}
const contents = await readFile(fullPath)
if (contents) {
this.loaded = true
try {
const cache = (this.cache = JSON.parse(contents))
for (const sub of subscriptions)
sub(cache, JsonStorageUpdateMode.Load)
return cache
} catch (e) {
nativeLoggingHook(
`Failed to parse storage (${fullPath}): ${getErrorStack(e)}`,
2,
)
}
}
}
this.set = async function (value: any, replace?: boolean) {
if (!this.cache) await this.get()
if (replace) this.cache = value as T
else mergeDeep(this.cache as T, value as DeepPartial<T>)
await write(this)
for (const sub of subscriptions)
sub(
value,
replace
? JsonStorageUpdateMode.Replace
: JsonStorageUpdateMode.Merge,
)
}
if (options?.load) this.get()
}
// React is only initialized right before the init stage, so this is a dummy method
// See init.ts in api.json-storage plugin for the actual implementation
JsonStorage.prototype.use = () => {
throw new Error('JsonStorage#use can only be called after the init stage!')
}
/**
* Get a JSON storage object for a given path.
*
* @param path The path to the storage document.
* - Relative paths resolve against the app data directory (`/data/data/<pkg>` on Android).
* Use `files/...` for app data or `cache/...` for cache on Android.
* - Absolute paths are used as-is.
*/
export function getJsonStorage<T extends AnyObject = AnyObject>(
path: string,
options?: JsonStorageOptions<T>,
): JsonStorage<T> {
const storage: JsonStorage<T> = Object.create(JsonStorage.prototype)
JsonStorage.call(storage, path, options)
return storage
}
export interface JsonStorageOptions<T extends AnyObject = AnyObject> {
/**
* The default value to use for the storage. This will also be used for cache.
*
* @default {}
*/
default?: T
/**
* Automatically load the storage after creating the instance.
*
* @default false
*/
load?: boolean
}
export type UseJsonStorageFilter<T extends AnyObject = AnyObject> = (
...params: Parameters<JsonStorageSubscription<T>>
) => any
export interface JsonStorage<T extends AnyObject> {
/**
* Whether the storage has been loaded. If the storage is not loaded, `storage.cache` may be `undefined`.
* If you have `options.default` set, you can use this property to check if `storage.cache` is the default value or not.
*/
loaded: boolean
/**
* The cached storage object. Set once `get()` is called, and updated on `set()`.
* You should not modify this directly.
*/
cache?: T | AnyObject
/**
* Use the storage in a React component. The component will re-render when the storage is updated.
*
* This can only be used in the `init` stage or later, as it requires React to be initialized.
*
* @example
* ```tsx
* type Settings = { key: boolean, nested: { key: boolean } }
*
* const SettingsStorage = getJsonStorage<Settings>('settings.json')
*
* const MyComponent = () => {
* // Re-renders every time any of the keys in the settings object change
* const settings = SettingsStorage.use()
* // const settings: Settings | undefined
*
* // ...
* }
*
* const MyComponent2 = () => {
* // Re-renders every time the new value matches the filter
* const settings = SettingsStorage.use(val => val.key !== undefined)
* // const settings: Settings | undefined
*
* // ...
* }
*/
use(filter?: UseJsonStorageFilter<T>): T | undefined
/**
* Subscribe to storage updates.
*
* @param callback The callback to call when the storage is updated.
* @returns A function to unsubscribe.
*/
subscribe(callback: JsonStorageSubscription<T>): () => void
/**
* Reads the storage from disk.
* If the storage does not exist, it will be created with the default value.
*/
get(): Promise<T>
/**
* Set the storage.
*
* @param value The value to merge into the storage.
* @param replace If true, replaces the entire storage instead of merging.
*/
set(value: DeepPartial<T>): Promise<void>
set<Replace extends boolean>(
value: If<Replace, T, DeepPartial<T>>,
replace: Replace,
): Promise<void>
/**
* Whether the storage is exists.
*/
exists(): Promise<boolean>
/**
* Delete the storage.
*/
delete(): Promise<boolean>
}

View file

@ -0,0 +1,24 @@
import { JsonStorage } from '@revenge-mod/json-storage'
import { useReRender } from '@revenge-mod/utils/react'
import { useLayoutEffect } from 'react'
import type { JsonStorageSubscription } from '@revenge-mod/json-storage'
const proto = JsonStorage.prototype as JsonStorage<any>
// Actual implementation of JsonStorage#use
proto.use = function (filter) {
if (!this.cache) this.get()
const reRender = useReRender()
useLayoutEffect(() => {
const sub: JsonStorageSubscription = filter
? (update, mode) => {
if (filter(update, mode)) reRender()
}
: reRender
return this.subscribe(sub)
}, [filter, reRender])
return this.cache
}

View file

@ -0,0 +1,31 @@
import type { AnyObject } from '@revenge-mod/utils/types'
import type { JsonStorage, JsonStorageOptions } from '.'
declare module '@revenge-mod/plugins/types' {
export interface UnscopedPreInitPluginApi {
jsonStorage: typeof import('.')
}
export interface PluginApiExtensionsOptions {
jsonStorage?: AnyObject
}
export interface PluginOptions<O extends PluginApiExtensionsOptions> {
jsonStorage?: JsonStorageOptions<NonNullable<O['jsonStorage']>> & {
/**
* File name (or relative path) of the storage document inside the
* plugin's storage directory.
*
* @default 'storage.json'
*/
file?: string
}
}
export interface InitPluginApi<O extends PluginApiExtensionsOptions> {
/**
* The plugin JSON storage.
*/
jsonStorage: JsonStorage<NonNullable<O['jsonStorage']>>
}
}

34
lib/modules/package.json Normal file
View file

@ -0,0 +1,34 @@
{
"name": "@revenge-mod/modules",
"private": true,
"type": "module",
"exports": {
"./finders/filters": {
"default": "./src/finders/filters/index.ts"
},
"./finders": {
"default": "./src/finders/index.ts"
},
"./metro/subscriptions": {
"default": "./src/metro/subscriptions/index.ts"
},
"./metro/patches": {
"default": "./src/metro/patches.ts"
},
"./metro/utils": {
"default": "./src/metro/utils.ts"
},
"./native": {
"default": "./src/native/index.ts"
},
"./native/app": {
"default": "./src/native/app.ts"
},
"./native/fs": {
"default": "./src/native/fs.ts"
},
"./types": {
"types": "./src/types.ts"
}
}
}

86
lib/modules/src/caches.ts Normal file
View file

@ -0,0 +1,86 @@
import {
callNativeMethod,
callNativeMethodSync,
} from '@revenge-mod/modules/native'
import { debounce } from '@revenge-mod/utils/callback'
import type { Metro } from '@revenge-mod/modules/types'
import type { FilterResultFlag } from './finders/_internal'
import type { Filter } from './finders/filters'
const ExpectedCacheVersion = 3
export const Uncached: Cache = {
blacklist: [],
finds: {},
version: ExpectedCacheVersion,
}
// In-memory cache
export let cache: Cache =
callNativeMethodSync('revenge.caches.modules.read', []) ?? Uncached
if (cache.version !== ExpectedCacheVersion) {
Uncached.outdated = true
cache = Uncached
}
export type Blacklist = Metro.ModuleID[]
export type Finds = Record<
Filter['key'],
Record<Metro.ModuleID, FilterResultFlag> | null
>
export interface Cache {
blacklist: Blacklist
finds: Finds
version: number
/** Indicates if the loader cache on an outdated format */
outdated?: boolean
}
const save = debounce(() => {
callNativeMethod('revenge.caches.modules.write', [
cache.blacklist,
cache.finds,
])
}, 1000)
export function cacheBlacklistedModule(id: Metro.ModuleID): boolean {
cache.blacklist.push(id)
save()
return true
}
export function cacheFilterResultForId(
key: keyof Finds,
id: Metro.ModuleID,
flag: FilterResultFlag,
): FilterResultFlag {
const reg = (cache.finds[key] ??= {})
reg[id] = flag
save()
return flag
}
export function cacheFilterNotFound(key: keyof Finds) {
cache.finds[key] = null
}
export const getFilterMatches = (
key: keyof Finds,
): Finds[keyof Finds] | undefined => cache.finds[key]
export const getBlacklistedModules = () => cache.blacklist
declare module '@revenge-mod/modules/native' {
interface NativeMethods {
'revenge.caches.modules.read': [[], Cache | null]
'revenge.caches.modules.write': [
[blacklist: Blacklist, finds: Finds],
void,
]
}
}

View file

@ -0,0 +1,165 @@
import { getCurrentStack } from '@revenge-mod/utils/error'
import { cacheFilterResultForId } from '../caches'
import { mInitialized } from '../metro/patches'
import { metroRequire } from '../metro/runtime'
import { FilterFlag } from './filters'
import type { If } from '@revenge-mod/utils/types'
import type { Metro } from '../types'
import type { Filter } from './filters'
export interface RunFilterOptions {
/**
* Whether to skip checking the default export.
*
* @default false
*/
skipDefault?: boolean
/**
* Whether to allow initializing modules to confirm their exports.
*
* @default true
*/
initialize?: boolean
}
export type RunFilterReturnExportsOptions<
ReturnNamespace extends boolean = boolean,
> = RunFilterOptions &
If<
ReturnNamespace,
{
/**
* Whether to return the whole module with all exports instead of just the default export **if the default export matches**.
*
* @default false
*/
returnNamespace: true
},
{
returnNamespace?: false
}
>
export const FilterResultFlags = {
/**
* A module was found, without exports filtering.
*/
Found: 1,
/**
* A module was found, and the filter matched the default export.
*/
Default: 2,
/**
* A module was found, and the filter matched the module namespace.
*/
Namespace: 3,
}
export type FilterResultFlag =
(typeof FilterResultFlags)[keyof typeof FilterResultFlags]
export const FilterResultFlagToHumanReadable: Record<FilterResultFlag, string> =
{
[FilterResultFlags.Default]: '\u001b[94mdefault\u001b[0m',
[FilterResultFlags.Namespace]: '\u001b[35mnamespace\u001b[0m',
[FilterResultFlags.Found]: '\u001b[96mexportsless\u001b[0m',
}
const noDefaultExportsCache = new Set<Metro.ModuleID>()
// The reason this returns a flag is because flags are never falsy, while exports may be falsy when using ID-only filters (eg. `withDependencies`).
// Currently, we only have options that are relevant for checking exports
// If we add more options later on, do NOT forget about
// adding them here, and passing them in the lookup* functions
export function runFilter(
filter: Filter<{ Result: any; RequiresExports: false; Scopes: any[] }>,
id: Metro.ModuleID,
): FilterResultFlag | undefined
export function runFilter(
filter: Filter,
id: Metro.ModuleID,
exports: Metro.ModuleExports,
options?: RunFilterOptions,
): FilterResultFlag | undefined
export function runFilter(
filter: Filter,
id: Metro.ModuleID,
exports?: Metro.ModuleExports,
options?: RunFilterOptions,
): FilterResultFlag | undefined {
if (exports === undefined) {
if (filter.flags & FilterFlag.RequiresExports) return
const filter_ = filter as Filter<{
Result: any
RequiresExports: false
Scopes: any[]
}>
if (filter_(id)) {
if (options?.initialize ?? true) {
const module = metroRequire(id)
// Check if the required module is not blacklisted
if (mInitialized.has(id)) {
if (__BUILD_FLAG_DEBUG_MODULE_LOOKUPS__) {
const flag = runFilter(filter, id, module, options)
if (!flag) DEBUG_warnPartialFilterMatch(id, filter.key)
return flag
} else return runFilter(filter, id, module, options)
} else return
}
return FilterResultFlags.Found
}
return
}
const filter_ = filter as Filter<{
Result: any
RequiresExports: true
Scopes: any[]
}>
if (filter_(id, exports))
return cacheFilterResultForId(
filter.key,
id,
FilterResultFlags.Namespace,
)
if (options?.skipDefault) return
if (noDefaultExportsCache.has(id)) return
if (!('default' in exports)) {
noDefaultExportsCache.add(id)
return
}
const { default: defaultExport } = exports
if (filter_(id, defaultExport))
return cacheFilterResultForId(filter.key, id, FilterResultFlags.Default)
}
export function exportsFromFilterResultFlag(
flag: FilterResultFlag,
exports: Metro.ModuleExports,
options?: RunFilterReturnExportsOptions,
) {
if (flag === FilterResultFlags.Default && !options?.returnNamespace)
return exports.default
return exports
}
/**
* Warns the developer that the filter matched during exportsless comparison, but not during the full comparison.
* This will cause modules to be initialized unnecessarily, and may cause issues.
*/
function DEBUG_warnPartialFilterMatch(id: Metro.ModuleID, key: string) {
nativeLoggingHook(
`\u001b[33m${key} matched module ${id} partially.\n${getCurrentStack()}\u001b[0m`,
2,
)
}

View file

@ -0,0 +1,199 @@
import { FilterFlag } from './constants'
import { createFilterGenerator } from './utils'
import type { Metro } from '@revenge-mod/modules/types'
import type {
Filter,
FilterBase,
FilterGenerator,
FilterInfoOf,
MergeFilterInfo,
UnionFilterInfo,
} from '.'
const compositeHandler = <G extends (a: FilterBase, b: FilterBase) => any>(
sameHandler: G,
dynamicHandler: G,
) =>
((a, b) =>
a.flags === b.flags
? sameHandler(a, b)
: a.flags === FilterFlag.RequiresExports
? dynamicHandler(a, b)
: dynamicHandler(b, a)) as G
const compositeArrayHandler = <
G extends (args: [a: FilterBase, b: FilterBase]) => any,
>(
sameHandler: G,
dynamicHandler: G,
) =>
(([a, b]) =>
a.flags === b.flags
? sameHandler([a, b])
: a.flags === FilterFlag.RequiresExports
? dynamicHandler([a, b])
: dynamicHandler([b, a])) as G
export type And = FilterGenerator<
<F1 extends FilterBase, F2 extends FilterBase>(
f1: F1,
f2: F2,
) => Filter<MergeFilterInfo<FilterInfoOf<F1>, FilterInfoOf<F2>>>
>
const andKeyGenerator = ([a, b]: Parameters<And>) =>
`revenge.and(${a.key},${b.key})`
const andScopesGenerator = ([a, b]: Parameters<And>) => a.scopes | b.scopes
const sameFlagsAnd = createFilterGenerator(
([a, b], id, exports) => a(id, exports) && b(id, exports),
andKeyGenerator,
([a]) => a.flags,
andScopesGenerator,
) as And
const andFallbackCache = new WeakMap<FilterBase, Set<Metro.ModuleID>>()
const dynamicFlagsAnd = createFilterGenerator(
([filter, fallbackFilter], id, exports) => {
if (exports) {
if (filter(id, exports)) {
// Avoid running the fallback filter if we already know the first one passed
const cache = andFallbackCache.get(fallbackFilter)
return (
// biome-ignore lint/complexity/useOptionalChain: Hot path should be optimized
(cache && cache.has(id)) || fallbackFilter(id, exports)
)
}
return false
}
const result = fallbackFilter(id)
if (result) {
// Cache fallback hits to avoid calling the fallback filter again
// Fallback filters are usually more expensive
let set = andFallbackCache.get(fallbackFilter)
if (!set) andFallbackCache.set(fallbackFilter, (set = new Set()))
set.add(id)
}
return result
},
andKeyGenerator,
FilterFlag.Dynamic,
andScopesGenerator,
) as And
/**
* Combines two filters into one, returning true if **every** filter matches.
*
* If each filter has different flags,
*
* @param filters The filters to combine.
*
* @example With filter helpers (preferred)
* ```ts
* const [SomeModule] = lookupModule(
* withProps('x', 'name')
* .and(withName('SomeName'))
* .and(withDependencies([1, 485, null, 2])),
* )
* ```
*
* @example
* ```ts
* const [SomeModule] = lookupModule(
* and(
* and(withProps('x', 'name'), withName('SomeName')),
* withDependencies([1, 485, null, 2]),
* ),
* )
* ```
*/
export const and = Object.assign(
compositeHandler(sameFlagsAnd, dynamicFlagsAnd),
{
keyFor: compositeArrayHandler(
sameFlagsAnd.keyFor,
dynamicFlagsAnd.keyFor,
),
flagsFor: compositeArrayHandler(
sameFlagsAnd.flagsFor,
dynamicFlagsAnd.flagsFor,
),
defaultScopesFor: compositeArrayHandler(
sameFlagsAnd.defaultScopesFor,
dynamicFlagsAnd.defaultScopesFor,
),
},
) satisfies And
export type Or = FilterGenerator<
<F1 extends FilterBase, F2 extends FilterBase>(
f1: F1,
f2: F2,
) => Filter<UnionFilterInfo<FilterInfoOf<F1>, FilterInfoOf<F2>>>
>
const orKeyGenerator = ([a, b]: Parameters<Or>) =>
`revenge.or(${a.key},${b.key})`
const orScopesGenerator = ([a, b]: Parameters<Or>) => a.scopes | b.scopes
const sameFlagOr = createFilterGenerator(
([a, b], id, exports) => a(id, exports) || b(id, exports),
orKeyGenerator,
([a]) => a.flags,
orScopesGenerator,
) as Or
const dynamicFlagOr = createFilterGenerator(
([filter, fallbackFilter], id, exports) => {
// TODO(PalmDevs): Potential optimization: Add fallback cache here too?
if (exports) return filter(id, exports) || fallbackFilter(id, exports)
return fallbackFilter(id)
},
orKeyGenerator,
FilterFlag.Dynamic,
orScopesGenerator,
) as Or
/**
* Combines two filters into one, returning true if **some** filters match.
*
* @param filters The filters to combine.
*
* @example With filter helpers (preferred)
* ```ts
* const [SomeModule] = lookupModule(
* withProps('x', 'name')
* .or(withName('SomeName'))
* .or(withDependencies([1, 485, null, 2])),
* )
* ```
*
* @example
* ```ts
* const [SomeModule] = lookupModule(
* or(
* or(withProps('x', 'name'), withName('SomeName')),
* withDependencies([1, 485, null, 2]),
* ),
* )
* ```
*/
export const or = Object.assign(
compositeHandler<Or>(sameFlagOr, dynamicFlagOr),
{
keyFor: compositeArrayHandler(sameFlagOr.keyFor, dynamicFlagOr.keyFor),
flagsFor: compositeArrayHandler(
sameFlagOr.flagsFor,
dynamicFlagOr.flagsFor,
),
defaultScopesFor: compositeArrayHandler(
sameFlagOr.defaultScopesFor,
dynamicFlagOr.defaultScopesFor,
),
},
) satisfies Or

View file

@ -0,0 +1,64 @@
export const FilterFlag = {
/**
* This filter works with and without module exports.
* Allowing for both initialized and uninitialized modules to be matched.
*/
Dynamic: 0,
/**
* This filter requires module exports to work.
* Only initialized modules will be matched.
*/
RequiresExports: 1,
} as const
/**
* @see {@link FilterFlag}
*/
export type FilterFlag = number
/**
* Scopes to limit filters to certain module states.
*/
export const FilterScopes = {
/**
* Include all modules (both initialized and uninitialized, including blacklisted).
* This overrides {@link FilterScopes.Uninitialized} and {@link FilterScopes.Initialized}.
*/
All: 1,
/**
* Include uninitialized modules in the search.
*/
Uninitialized: 2,
/**
* Include initialized modules from the search.
*/
Initialized: 4,
} as const
export type FilterScope = (typeof FilterScopes)[keyof typeof FilterScopes]
/**
* @see {@link FilterScopes}
*/
export type FilterScopeValue = number
export interface FilterInfo {
/**
* The result type of the filter.
*/
Result: any
/**
* Whether the filter requires exports to work.
*/
RequiresExports: boolean
/**
* Scopes the filter matches modules in.
*/
Scopes: FilterScope[]
}
export interface DefaultFilterInfo extends FilterInfo {
Result: any
RequiresExports: boolean
Scopes: FilterScope[]
}

View file

@ -0,0 +1,318 @@
import { getCurrentStack } from '@revenge-mod/utils/error'
import {
getInitializedModuleExports,
getModuleDependencies,
} from '../../metro/utils'
import { runFilter } from '../_internal'
import { FilterFlag, FilterScopes } from './constants'
import { createFilterGenerator } from './utils'
import type { Metro } from '../../types'
import type { Filter, FilterGenerator } from './utils'
export interface ComparableDependencyMap
extends Array<
| Metro.ModuleID
| number
| null
| undefined
| ComparableDependencyMap
| Filter
> {
l?: boolean
r?: number
}
/**
* Filter modules by their dependency map.
*
* @param deps The dependency map to check for, can be a sparse array or have `null` to be any dependency ("dynamic"). **Order and size matters!**
*
* To do proper fingerprinting for modules:
* @see {@link withDependencies.loose} to loosen the checks.
* @see {@link withDependencies.relative} to compare dependencies relatively.
*
* @example
* ```ts
* const { loose, relative } = withDependencies
*
* // Logger's module ID is 5
* // It has 3 dependencies [4, ?, 2]
*
* const [Logger] = lookupModule(withDependencies([4, null, 2]))
* // or
* const [Logger] = lookupModule(withDependencies([4, , 2]))
*
* // Relative dependencies
* const [Logger] = lookupModule(withDependencies([relative(-1), null, 2]))
*
* // Nested dependencies
* // The last dependency (module ID 2) would need to have zero dependencies:
* const [Logger] = lookupModule(withDependencies([4, null, []]))
*
* // Loose dependencies
* // Module having these dependencies: [4, ...], [4, ..., ...], [4, ..., ..., ...], etc. would match:
* const [SomeOtherModule] = lookupModule(withDependencies(loose([4])))
*
* // Using filters as dependencies
* // Match modules with specific exports in their dependencies
* const [Module] = lookupModule(withDependencies([
* withProps('open'), // first dependency must have an 'open' property
* withName('MyComponent'), // second dependency must have name === 'MyComponent'
* 69, // third dependency must be module ID 69
* null, // fourth dependency can be anything
* 420, // fifth dependency must be module ID 420
* 2 // sixth dependency must be module ID 2
* ]))
* ```
*
* @example With filter helpers (preferred)
* ```ts
* const [Logger] = lookupModule(
* withProps('log')
* .withDependencies([4, null, 2]),
* )
* ```
*/
const withDependencies_ = createFilterGenerator<Parameters<WithDependencies>>(
([deps], id) => depCompare(getModuleDependencies(id)!, deps, id, id),
deps => `revenge.deps(${depGenFilterKey(deps)})`,
FilterFlag.Dynamic,
FilterScopes.Uninitialized | FilterScopes.Initialized,
) as WithDependencies
export const withDependencies = __DEV__
? (((deps: ComparableDependencyMap) => {
// Warn about using undefined in deps, which is likely a mistake
for (let i = 0; i < deps.length; i++) {
if (deps[i] === undefined)
DEBUG_warnBadWithDependenciesFilter(deps, i)
}
return withDependencies_(deps)
}) as WithDependencies)
: withDependencies_
withDependencies.loose = loose
withDependencies.relative = relative
type WithDependencies = FilterGenerator<
<T>(deps: ComparableDependencyMap) => Filter<{
Result: T
RequiresExports: false
Scopes: [
typeof FilterScopes.Uninitialized,
typeof FilterScopes.Initialized,
]
}>
> & {
loose: typeof loose
relative: typeof relative
}
/**
* Make this set of comparable dependencies as loose.
*
* Making a dependency loose skips the exact length check, but the order of the set dependencies still matters.
* If you mark an index as dynamic, the same index must also be present in the other map during comparison to pass.
*
* @param deps The dependency map to make loose. This permanently modifies the array.
* @returns The modified dependency map.
*/
function loose(deps: ComparableDependencyMap) {
deps.l = true
return deps
}
const RelativeSignBit = 1 << 30
const RelativeBit = 1 << 29
const RelativeRootBit = 1 << 28
const RelativeBitMask = ~(RelativeSignBit | RelativeBit | RelativeRootBit)
/**
* Marks this dependency to compare relatively to the module ID being compared.
*
* @param magnitude The relative magnitude to use when comparing module IDs. Positive values mean the dependency's module ID is greater than the module being compared, negative values mean it's less.
* @param root Marks this dependency to compare relatively to the root (returning) module ID being compared. Useful for nested comparisons where you want to compare by the root module ID instead of the parent's module ID of the nested dependency.
*/
function relative(magnitude: Metro.ModuleID, root?: boolean) {
magnitude =
(magnitude < 0 ? -magnitude | RelativeSignBit : magnitude) | RelativeBit
if (root) magnitude |= RelativeRootBit
return magnitude
}
/**
* Marks this dependency to compare relatively to the module ID being compared, with an additional dependencies check.
*
* @param deps The dependency map to add the relative dependency to. This permanently modifies the array.
* @param magnitude The relative magnitude to use when comparing module IDs. Positive values mean the dependency's module ID is greater than the module being compared, negative values mean it's less.
* @param root Whether to use {@link relative.toRoot} instead of {@link relative}. Defaults to `false`.
* @returns The modified dependency map.
*
* @see {@link withDependencies}
* @see {@link relative}
*
* @example
* ```ts
* const { relative } = withDependencies
*
* // This filter will match modules having one dependency that is its module ID + 1
* // And module ID + 1 would have exactly two dependencies: [Any, 2]
* withDependencies(
* relative.withDependencies(
* [null, 2],
* 1, // Always the next module to the one being compared
* true, // The module ID being compared matches the returning (root) module ID
* )
* )
* ```
*/
relative.withDependencies = (
deps: ComparableDependencyMap,
magnitude: Metro.ModuleID,
root?: boolean,
) => {
deps.r = relative(magnitude, root)
return deps
}
/**
* Warns the developer about a bad `withDependencies` filter using `undefined` in its comparisons.
*
* - `undefined` should only be used as a fallback to when a module ID can really not be found.
* - Use `null` instead to indicate a dynamic dependency.
*/
function DEBUG_warnBadWithDependenciesFilter(
deps: ComparableDependencyMap,
index: number,
) {
nativeLoggingHook(
`\u001b[33mBad withDependencies filter, undefined ID at index ${index} (if intentional, set to null): [${depGenFilterKey(deps)}]\n${getCurrentStack()}\u001b[0m`,
2,
)
}
function depCompare(
a: Metro.ModuleID[],
b: ComparableDependencyMap,
root: Metro.ModuleID,
parent: Metro.ModuleID,
): boolean {
const lenA = a.length
const lenB = b.length
if (b.l ? lenA < lenB : lenA !== lenB) return false
for (let i = 0; i < lenB; i++) {
const compare = b[i]
if (__DEV__ && compare === undefined)
DEBUG_warnBadWithDependenciesFilter(b, i)
// Skip dynamic
if (compare == null) continue
const id = a[i]
// Very rare case where a module dependency has an unused `null` dependency
// TODO: Probably a Metro/Discord bug?
if (id === null) return false
switch (typeof compare) {
case 'function': {
const filter = compare
if (!runFilter(filter, id, getInitializedModuleExports(id)))
return false
continue
}
case 'object': {
const nested = compare as ComparableDependencyMap
// relative.withDependencies?
if (nested.r && !depShallowCompare(nested.r, id, root, parent))
return false
if (depCompare(getModuleDependencies(id)!, nested, root, id))
continue
return false
}
default: {
if (depShallowCompare(compare as number, id, root, parent))
continue
return false
}
}
}
return true
}
function depShallowCompare(
compare: number,
id: Metro.ModuleID,
root: Metro.ModuleID,
parent: Metro.ModuleID,
) {
// relative?
if (compare & RelativeBit)
compare =
(compare & RelativeRootBit ? root : parent) +
depGetRelMagnitude(compare)
return compare === id
}
function depGetRelMagnitude(dep: number) {
const sign = dep & RelativeSignBit
dep = dep & RelativeBitMask
if (sign) dep = -dep
return dep
}
function depGenFilterKey(deps: ComparableDependencyMap): string {
let key = ''
for (let i = 0; i < deps.length; i++) {
const dep = deps[i]
if (dep == null) {
key += ','
continue
}
switch (typeof dep) {
case 'function': {
// It's a filter function
const filter = dep as any
key += `${filter.key},`
break
}
case 'object': {
// It's a nested dependency array
const nested = dep as ComparableDependencyMap
if (nested.l) key += '#'
// relative.withDependencies?
if (nested.r) key += `${depGenRelativeKeyPart(nested.r)}:`
key += `[${depGenFilterKey(nested)}],`
break
}
default: {
const numDep = dep as number
if (numDep & RelativeBit)
key += `${depGenRelativeKeyPart(numDep)},`
else key += `${numDep},`
break
}
}
}
return key.substring(0, key.length - 1)
}
function depGenRelativeKeyPart(dep: number) {
const magnitude = depGetRelMagnitude(dep)
const prefix = dep & RelativeRootBit ? '~' : '^'
return `${prefix}${magnitude}`
}

View file

@ -0,0 +1,150 @@
import { isModuleExportBad } from '@revenge-mod/modules/metro/utils'
import { FilterFlag, FilterScopes } from './constants'
import { createFilterGenerator } from './utils'
import type { Filter, FilterGenerator } from './utils'
export * from './constants'
export * from './utils'
type FilterRequiringExports<T> = Filter<{
Result: T
RequiresExports: true
Scopes: [typeof FilterScopes.Initialized]
}>
/**
* Filter modules by their exports having all of the specified properties.
*
* @param prop The property to check for.
* @param props More properties to check for (optional).
*
* @example
* ```ts
* const [React] = lookupModule(withProps<typeof import('react')>('createElement'))
* // const React: typeof import('react')
* ```
*/
export const withProps = createFilterGenerator<Parameters<WithProps>>(
(props, _, exports) => {
const type = typeof exports
if (isModuleExportBad(exports)) return false
if (type === 'object' || type === 'function') {
for (const prop of props) {
if (prop in exports) continue
return false
}
return true
}
return false
},
props => `revenge.props(${props.join(',')})`,
FilterFlag.RequiresExports,
FilterScopes.Initialized,
) as WithProps
export type WithProps = FilterGenerator<
<T extends Record<string, any> = Record<string, any>>(
prop: keyof T,
...props: Array<keyof T>
) => FilterRequiringExports<T>
>
/**
* Filter modules by their exports having none of the specified properties.
*
* @param prop The property to check for.
* @param props More properties to check for (optional).
*/
export const withoutProps = createFilterGenerator<Parameters<WithoutProps>>(
(props, _, exports) => {
const type = typeof exports
if ((type === 'object' && exports !== null) || type === 'function')
for (const prop of props) if (prop in exports) return false
return true
},
props => `revenge.withoutProps(${props.join(',')})`,
FilterFlag.RequiresExports,
FilterScopes.Initialized,
) as WithoutProps
export type WithoutProps = FilterGenerator<
<T extends Record<string, any>>(
prop: string,
...props: string[]
) => FilterRequiringExports<T>
>
/**
* Filter modules by their exports having only the specified property.
*
* @param prop The property to check for.
*
* @example
* ```ts
* const [FormSwitchModule] = lookupModule(withSingleProp('FormSwitch'))
* // const FormSwitchModule: { FormSwitch: any }
* ```
*/
export const withSingleProp = createFilterGenerator<Parameters<WithSingleProp>>(
([prop], _, exports) => {
if (typeof exports === 'object' && exports !== null && prop in exports)
return Reflect.ownKeys(exports).length === 1
return false
},
([prop]) => `revenge.singleProp(${prop})`,
FilterFlag.RequiresExports,
FilterScopes.Initialized,
) as WithSingleProp
export type WithSingleProp = FilterGenerator<
<T extends Record<string, any>>(prop: keyof T) => FilterRequiringExports<T>
>
/**
* Filter modules by their exports having the specified name.
*
* Usually used for function components or classes.
*
* @param name The name to check for.
*
* @example Auto-typing as object
* ```ts
* const [SomeComponent] = lookupModule(withName('SomeComponent'))
* // const SomeComponent: { name: 'SomeComponent' }
* ```
*
* @example Typing as function component
* ```ts
* type MyComponent = React.FC<{ foo: string }>
*
* const [MyComponent] = lookupModule(withName<MyComponent>('MyComponent'))
* // const MyComponent: MyComponent & { name: 'MyComponent' }
* ```
*
* @example Typing as class
* ```
* interface SomeClass {
* someMethod(): void
* }
*
* const [SomeClass] = lookupModule(withName<{ new(param: string): SomeClass }>('SomeClass'))
* // const SomeClass: { new(): SomeClass, name: 'SomeClass' }
*/
export const withName = createFilterGenerator<Parameters<WithName>>(
([name], _, exports) => exports?.name === name,
([name]) => `revenge.name(${name})`,
FilterFlag.RequiresExports,
FilterScopes.Initialized,
) as WithName
export type WithName = FilterGenerator<
<T extends object = object>(name: string) => FilterRequiringExports<T>
>
export * from './composite'
export * from './dynamic'

View file

@ -0,0 +1,249 @@
import { getErrorStack } from '@revenge-mod/utils/error'
import { withProps } from '.'
import { and, or } from './composite'
import { FilterScopes } from './constants'
import type { Metro } from '@revenge-mod/modules/types'
import type { If, LogicalAnd } from '@revenge-mod/utils/types'
import type {
DefaultFilterInfo,
FilterFlag,
FilterInfo,
FilterScope,
FilterScopes as FilterScopesObject,
FilterScopeValue,
} from './constants'
export type FilterResult<F> = F extends Filter<infer I> ? I['Result'] : never
export type FilterRequiresExports<F> =
F extends Filter<infer I> ? I['RequiresExports'] : never
export type FilterInfoOf<F> = F extends Filter<infer I> ? I : FilterInfo
export interface FilterBase<Info extends FilterInfo = DefaultFilterInfo> {
(
...args: If<
Info['RequiresExports'],
[id: Metro.ModuleID, exports: Metro.ModuleExports],
[id: Metro.ModuleID, exports?: never]
>
): boolean
key: string
flags: If<
Info['RequiresExports'],
(typeof FilterFlag)['RequiresExports'],
FilterFlag
>
scopes: FilterScopeValue
}
export type Filter<Info extends FilterInfo = DefaultFilterInfo> =
FilterHelpers<Info> & FilterBase<Info>
export type MergeFilterInfo<I1 extends FilterInfo, I2 extends FilterInfo> = {
Result: I1['Result'] & I2['Result']
RequiresExports: LogicalAnd<I1['RequiresExports'], I2['RequiresExports']>
Scopes: [...I1['Scopes'], ...I2['Scopes']]
}
export type UnionFilterInfo<I1 extends FilterInfo, I2 extends FilterInfo> = {
Result: I1['Result'] | I2['Result']
RequiresExports: LogicalAnd<I1['RequiresExports'], I2['RequiresExports']>
Scopes: [...I1['Scopes'], ...I2['Scopes']]
}
export interface FilterHelpers<Info extends FilterInfo = DefaultFilterInfo> {
/**
* Manually the key for this filter.
*
* **Don't use this unless you know what you're doing.** Only API exports should be using this.
*
* @param key The key to set for this filter.
*/
keyAs<T extends FilterBase<any>>(this: T, key: string): T
/**
* Combines this filter with another filter, returning a new filter that matches if **both** filters match.
*
* @param filter The filter to combine with.
*/
and<T extends FilterBase<any>, F extends FilterBase<any>>(
this: T,
filter: F,
): Filter<MergeFilterInfo<Info, FilterInfoOf<F>>>
/**
* Combines this filter with another filter, returning a new filter that matches if **either** filter matches.
*
* @param filter The filter to combine with.
*/
or<T extends Filter<Info>, F extends FilterBase<any>>(
this: T,
filter: F,
): Filter<UnionFilterInfo<Info, FilterInfoOf<F>>>
/**
* Creates a new instance of this filter.
*/
// biome-ignore format: Preserve special property name syntax for 'new' keyword
'new'(this: Filter<Info>): Filter<Info>
/**
* Scopes this filter to match specific modules.
*
* @param scopes The scopes of modules to match.
*/
scope<T extends Filter<Info>, const S extends FilterScope[]>(
this: T,
...scopes: If<
Info['RequiresExports'],
[typeof FilterScopesObject.Initialized],
S
>
): Filter<
Info & {
Scopes: If<
Info['RequiresExports'],
[typeof FilterScopesObject.Initialized],
S
>
}
>
}
export type FilterGenerator<G extends (...args: any[]) => Filter> = G & {
keyFor(args: Parameters<G>): string
flagsFor(args: Parameters<G>): FilterFlag
defaultScopesFor(args: Parameters<G>): FilterScopeValue
}
const Helpers: FilterHelpers = Object.setPrototypeOf(
{
keyAs(key) {
this.key = key
return this
},
and(filter) {
return and(this, filter)
},
or(filter) {
return or(this, filter)
},
new() {
const newFilter = ((
id: Metro.ModuleID,
exports?: Metro.ModuleExports,
) => this(id, exports)) as typeof this
Object.assign(newFilter, this)
return Object.setPrototypeOf(newFilter, Helpers)
},
scope(...scopes) {
const filter = this.new()
filter.scopes = 0
for (const scope of scopes) filter.scopes |= scope
return filter
},
} satisfies FilterHelpers,
Function.prototype,
)
/**
* Create a filter generator.
*
* @param filter The function that filters the modules.
* @param keyFor The function that generates the key for the filter.
* @param flagFor The function that generates the flags for the filter, or a static flag.
* @param defaultScopesFor The function that generates the default scopes for the filter, or static scopes. Defaults to {@link FilterScopes.Initialized}.
* @returns A function that generates a filter with the specified arguments.
*
* @example
* ```ts
* const custom = createFilterGenerator<[arg1: number, arg2: string]>(
* ([arg1, arg2], id, exports) => {
* // WARNING: exports can be Proxy or nullish, so be careful when using it
* // filter logic
* return true
* },
* ([arg1, arg2]) => `custom(${arg1}, ${arg2})`
* )
* ```
*
* @see {@link withProps} for an example on custom-typed filters.
*/
export function createFilterGenerator<A extends any[]>(
filter: (
args: A,
id: Metro.ModuleID,
exports: Metro.ModuleExports,
) => boolean,
keyFor: (args: A) => string,
flagFor: ((args: A) => FilterFlag) | FilterFlag,
defaultScopesFor?: ((args: A) => FilterScopeValue) | FilterScopeValue,
): FilterGenerator<(...args: A) => Filter>
export function createFilterGenerator<A extends any[]>(
filter: (args: A, id: Metro.ModuleID) => boolean,
keyFor: (args: A) => string,
flagFor: ((args: A) => FilterFlag) | FilterFlag,
defaultScopesFor?: ((args: A) => FilterScopeValue) | FilterScopeValue,
): FilterGenerator<(...args: A) => Filter>
export function createFilterGenerator<A extends any[]>(
filter: (
args: A,
id: Metro.ModuleID,
exports?: Metro.ModuleExports,
) => boolean,
keyFor: (args: A) => string,
flagFor: ((args: A) => FilterFlag) | FilterFlag,
defaultScopesFor?: ((args: A) => FilterScopeValue) | FilterScopeValue,
): FilterGenerator<(...args: A) => Filter> {
type GeneratorType = ReturnType<typeof createFilterGenerator<A>>
const isFlagsStatic = typeof flagFor === 'number'
const defaultScopes = defaultScopesFor ?? FilterScopes.Initialized
const isDefaultScopesStatic = typeof defaultScopes === 'number'
const generator: GeneratorType = (...args: A) => {
const filter_ = ((
id: Metro.ModuleID,
exports?: Metro.ModuleExports,
) => {
try {
return filter(args, id, exports)
} catch (e) {
DEBUG_warnFilterThrown(id, keyFor(args), e)
return false
}
}) as ReturnType<GeneratorType>
filter_.key = keyFor(args)
filter_.flags = isFlagsStatic ? flagFor : flagFor(args)
filter_.scopes = isDefaultScopesStatic
? defaultScopes
: defaultScopes(args)
return Object.setPrototypeOf(filter_, Helpers)
}
generator.flagsFor = isFlagsStatic
? () => flagFor
: (args: A) => flagFor(args)
generator.defaultScopesFor = isDefaultScopesStatic
? () => defaultScopes
: defaultScopes
generator.keyFor = keyFor
return generator
}
function DEBUG_warnFilterThrown(
id: Metro.ModuleID,
key: string,
error: unknown,
) {
nativeLoggingHook(
`\u001b[31mFilter ${key} threw an error for module ${id}:\n${getErrorStack(error)}\u001b[0m`,
3,
)
}

View file

@ -0,0 +1,118 @@
import { onModuleInitialized } from '@revenge-mod/modules/metro/subscriptions'
import { isModuleInitialized } from '@revenge-mod/modules/metro/utils'
import { asap, noop } from '@revenge-mod/utils/callback'
import { FilterScopes } from './filters'
import { lookupModule, lookupModules } from './lookup'
import { waitForModules } from './wait'
import type { Metro } from '../types'
import type { Filter, FilterResult } from './filters'
import type { LookupModulesOptions } from './lookup'
import type { WaitForModulesOptions, WaitForModulesResult } from './wait'
export type GetModulesOptions<ReturnNamespace extends boolean = boolean> =
WaitForModulesOptions<ReturnNamespace> &
LookupModulesOptions<ReturnNamespace, true> & {
/**
* The maximum number of modules to get.
*
* @default 1
*/
max?: number
}
export type GetModulesResult<
F extends Filter,
O extends GetModulesOptions,
> = WaitForModulesResult<F, O>
export type GetModulesCallback<T> = (exports: T, id: Metro.ModuleID) => any
export type GetModulesUnsubscribeFunction = () => void
/**
* Get modules matching the filter.
* If the matching modules are already initialized, the callback will be called immediately.
* Otherwise, it will be called when the matching modules are initialized.
*
* @param filter The filter to use to find the module.
* @param options The options to use for the find.
* @returns A function to unsubscribe.
*
* @example
* ```ts
* getModules(withProps<typeof import('react')>('createElement'), React => {
* // Immediately called because React is always initialized when plugins are loaded
* })
*
* getModules(withProps<typeof import('@shopify/flash-list')>('FlashList'), FlashList => {
* // Called when the module is initialized
* })
*
* // Get multiple modules matching the filter
* getModules(withProps<ReactNative.AssetsRegistry>('registerAsset'), AssetsRegistry => {
* // Called 2 times, once for each module that matches the filter
* }, { max: 2 })
* ```
*/
export function getModules<F extends Filter>(
filter: F,
callback: GetModulesCallback<FilterResult<F>>,
): GetModulesUnsubscribeFunction
export function getModules<F extends Filter, const O extends GetModulesOptions>(
filter: F,
callback: GetModulesCallback<GetModulesResult<F, O>>,
options: O,
): GetModulesUnsubscribeFunction
export function getModules(
filter: Filter,
callback: GetModulesCallback<any>,
options?: GetModulesOptions,
) {
let max = options?.max ?? 1
// Only lookup modules that are already initialized
const lookupFilter = filter.scope(FilterScopes.Initialized)
function handleModule(
exports: Metro.ModuleExports | undefined,
id: Metro.ModuleID,
) {
if (isModuleInitialized(id)) {
// Run callback at the end of the event loop. This ensures that the noop is returned first.
// Module is already initialized, there is likely no harm calling the callback late.
asap(() => {
callback(exports, id)
})
} else {
// Module is not initialized, wait for it to be initialized before calling the callback.
onModuleInitialized(id, (_, exports) => {
callback(exports, id)
})
}
}
if (max === 1) {
const [exports, id] = lookupModule(lookupFilter, options!)
if (id !== undefined) {
handleModule(exports, id)
return noop
}
} else
for (const [exports, id] of lookupModules(lookupFilter, options!)) {
handleModule(exports, id)
if (!--max) return noop
}
const unsub = waitForModules(
filter,
(exports, id) => {
if (!--max) unsub()
callback(exports, id)
},
options!,
)
return unsub
}

View file

@ -0,0 +1,3 @@
export * from './get'
export * from './lookup'
export * from './wait'

View file

@ -0,0 +1,373 @@
import { getCurrentStack } from '@revenge-mod/utils/error'
import { proxify } from '@revenge-mod/utils/proxy'
import { cacheFilterNotFound, getFilterMatches } from '../caches'
import { mInitialized, mList, mUninitialized } from '../metro/patches'
import { metroRequire } from '../metro/runtime'
import {
getInitializedModuleExports,
isModuleInitialized,
} from '../metro/utils'
import {
exportsFromFilterResultFlag,
FilterResultFlagToHumanReadable,
runFilter,
} from './_internal'
import { FilterScopes } from './filters'
import type { If, Not } from '@revenge-mod/utils/types'
import type { MaybeDefaultExportMatched, Metro } from '../types'
import type {
FilterResultFlag,
RunFilterReturnExportsOptions,
} from './_internal'
import type { Filter, FilterResult } from './filters'
export type LookupModulesOptions<
ReturnNamespace extends boolean = boolean,
Initialize extends boolean = boolean,
> = RunFilterReturnExportsOptions<ReturnNamespace> & {
/**
* Whether to use cached lookup results.
*/
cached?: boolean
} & If<
Not<Initialize>,
{
initialize: false
},
{
/**
* Whether to initialize matching uninitialized modules.
*
* **This will initialize any modules that match the exportsless filter and may cause unintended side effects.**
*/
initialize?: true
}
>
export type LookupModulesResult<
F extends Filter,
O extends LookupModulesOptions,
> = [exports: LookupFilterResult<F, O>, id: Metro.ModuleID]
type LookupFilterResult<F extends Filter, O extends LookupModulesOptions> =
O extends LookupModulesOptions<any, false>
? InitializedLookupFilterResult<F, O> | undefined
: InitializedLookupFilterResult<F, O>
type InitializedLookupFilterResult<
F extends Filter,
O extends LookupModulesOptions,
> =
O extends RunFilterReturnExportsOptions<true>
? MaybeDefaultExportMatched<FilterResult<F>>
: FilterResult<F>
export const NotFoundResult: readonly [] = Object.freeze([])
export type LookupNotFoundResult = typeof NotFoundResult
/**
* Lookup modules.
*
* @param filter The filter to use.
* @param options The options to use for the lookup.
* @returns A generator that yields the module exports that match the filter.
*
* @example
* ```ts
* const lookup = lookupModules(withProps('x'))
* // Log all module exports that has exports.x
* for (const [exports, id] of lookup) console.log(id, exports)
* ```
*/
export function lookupModules<F extends Filter>(
filter: F,
): Generator<LookupModulesResult<F, object>, undefined>
export function lookupModules<
F extends Filter,
const O extends LookupModulesOptions,
>(filter: F, options: O): Generator<LookupModulesResult<F, O>, undefined>
export function* lookupModules(filter: Filter, options?: LookupModulesOptions) {
let notFound = true
let cached: Set<Metro.ModuleID> | undefined
const scopes = filter.scopes
const includeAll = scopes & FilterScopes.All
const includeInit = includeAll || scopes & FilterScopes.Initialized
const includeUninit = includeAll || scopes & FilterScopes.Uninitialized
if (options?.cached ?? true) {
const notInit = !(options?.initialize ?? true)
const reg = getFilterMatches(filter.key)
// Return early if previous lookup was a full lookup and no modules were found
if (reg === null) return
if (reg) {
cached = new Set()
for (const sId of Object.keys(reg)) {
const flag = reg[sId as unknown as keyof typeof reg]
const id = Number(sId)
let exports: Metro.ModuleExports | undefined
if (includeInit && isModuleInitialized(id))
exports = getInitializedModuleExports(id)
else if (includeUninit) {
if (notInit) {
yield [undefined, id]
continue
}
exports = metroRequire(id)
} else continue
cached.add(id)
if (__BUILD_FLAG_DEBUG_MODULE_LOOKUPS__)
DEBUG_logLookupMatched(filter.key, flag, id, true)
yield [exportsFromFilterResultFlag(flag, exports, options), id]
}
}
}
if (includeAll) {
for (const id of mList.keys()) {
// biome-ignore lint/complexity/useOptionalChain: Hot path should be optimized
if (cached && cached.has(id)) continue
const flag = runFilter(
filter,
id,
getInitializedModuleExports(id),
options,
)
if (flag) {
notFound = false
if (__BUILD_FLAG_DEBUG_MODULE_LOOKUPS__)
DEBUG_logLookupMatched(filter.key, flag, id)
yield [
exportsFromFilterResultFlag(
flag,
getInitializedModuleExports(id),
options,
),
id,
]
}
}
} else {
if (includeInit)
for (const id of mInitialized) {
// biome-ignore lint/complexity/useOptionalChain: Hot path should be optimized
if (cached && cached.has(id)) continue
const exports = getInitializedModuleExports(id)
const flag = runFilter(filter, id, exports, options)
if (flag) {
notFound = false
if (__BUILD_FLAG_DEBUG_MODULE_LOOKUPS__)
DEBUG_logLookupMatched(filter.key, flag, id)
yield [
exportsFromFilterResultFlag(flag, exports, options),
id,
]
}
}
if (includeUninit)
for (const id of mUninitialized) {
// biome-ignore lint/complexity/useOptionalChain: Hot path should be optimized
if (cached && cached.has(id)) continue
const flag = runFilter(filter, id, undefined, options)
if (flag) {
notFound = false
if (__BUILD_FLAG_DEBUG_MODULE_LOOKUPS__)
DEBUG_logLookupMatched(filter.key, flag, id)
yield [
exportsFromFilterResultFlag(
flag,
getInitializedModuleExports(id),
options,
),
id,
]
}
}
}
// Cache if nothing was found in a full lookup
if (notFound && includeAll) cacheFilterNotFound(filter.key)
if (__BUILD_FLAG_DEBUG_MODULE_LOOKUPS__ && notFound)
DEBUG_warnLookupNoMatch(filter.key)
}
/**
* Lookup a module. Skipping creating a `Generator`.
*
* @see {@link lookupModules} for more documentation.
*
* @param filter The filter to use.
* @param options The options to use for the lookup.
* @returns The first module exports that match the filter.
*
* @example
* ```ts
* const [React, ReactModuleId] = lookupModule(withProps<typeof import('react')>('createElement'))
* ```
*/
export function lookupModule<F extends Filter>(
filter: F,
): LookupModulesResult<F, object> | LookupNotFoundResult
export function lookupModule<
F extends Filter,
const O extends LookupModulesOptions,
>(filter: F, options: O): LookupModulesResult<F, O> | LookupNotFoundResult
export function lookupModule(filter: Filter, options?: LookupModulesOptions) {
const scopes = filter.scopes
const includeAll = scopes & FilterScopes.All
const includeInit = includeAll || scopes & FilterScopes.Initialized
const includeUninit = includeAll || scopes & FilterScopes.Uninitialized
if (options?.cached ?? true) {
const notInit = !(options?.initialize ?? true)
const reg = getFilterMatches(filter.key)
// Return early if previous lookup was a full lookup and no modules were found
if (reg === null) return NotFoundResult
if (reg)
for (const sId of Object.keys(reg)) {
const flag = reg[sId as unknown as keyof typeof reg]
const id = Number(sId)
let exports: Metro.ModuleExports | undefined
if (includeInit && isModuleInitialized(id))
exports = getInitializedModuleExports(id)
else if (includeUninit) {
if (notInit) return [undefined, id]
exports = metroRequire(id)
} else continue
if (__BUILD_FLAG_DEBUG_MODULE_LOOKUPS__)
DEBUG_logLookupMatched(filter.key, flag, id, true)
return [exportsFromFilterResultFlag(flag, exports, options), id]
}
}
if (includeAll) {
for (const id of mList.keys()) {
const flag = runFilter(
filter,
id,
getInitializedModuleExports(id),
options,
)
if (flag) {
if (__BUILD_FLAG_DEBUG_MODULE_LOOKUPS__)
DEBUG_logLookupMatched(filter.key, flag, id)
return [
exportsFromFilterResultFlag(
flag,
getInitializedModuleExports(id),
options,
),
id,
]
}
}
} else {
if (includeInit)
for (const id of mInitialized) {
const exports = getInitializedModuleExports(id)
const flag = runFilter(filter, id, exports, options)
if (flag) {
if (__BUILD_FLAG_DEBUG_MODULE_LOOKUPS__)
DEBUG_logLookupMatched(filter.key, flag, id)
return [
exportsFromFilterResultFlag(flag, exports, options),
id,
]
}
}
if (includeUninit)
for (const id of mUninitialized) {
const flag = runFilter(filter, id, undefined, options)
if (flag) {
if (__BUILD_FLAG_DEBUG_MODULE_LOOKUPS__)
DEBUG_logLookupMatched(filter.key, flag, id)
return [
exportsFromFilterResultFlag(
flag,
getInitializedModuleExports(id),
options,
),
id,
]
}
}
}
// Cache if nothing was found in a full lookup
if (includeAll) cacheFilterNotFound(filter.key)
if (__BUILD_FLAG_DEBUG_MODULE_LOOKUPS__) DEBUG_warnLookupNoMatch(filter.key)
return NotFoundResult
}
const __DEBUG_TRACER_IGNORE_LIST__ = __BUILD_FLAG_DEBUG_MODULE_LOOKUPS__
? proxify(
() => [
require('./get').getModules,
isModuleInitialized(0) &&
require('@revenge-mod/utils/discord')
.lookupGeneratedIconComponent,
],
{ hint: [] },
)
: []
/**
* Logs to the developer that a module was found, how it is found, and whether it was a cached result.
*/
function DEBUG_logLookupMatched(
key: string,
flag: FilterResultFlag,
id: Metro.ModuleID,
cached?: boolean,
) {
nativeLoggingHook(
`\u001b[32mSuccessful lookup: \u001b[33m${key}\u001b[0m (matched ${id}, ${FilterResultFlagToHumanReadable[flag]}${cached ? ', \u001b[92mcached\u001b[0m' : ''})`,
1,
)
}
/**
* Warns the developer that no module was found for the given filter.
* This is useful for debugging purposes, especially when using filters that are expected to match a module.
*/
function DEBUG_warnLookupNoMatch(key: string) {
const stack = getCurrentStack()
for (const func of __DEBUG_TRACER_IGNORE_LIST__)
if (stack.includes(func.name)) return
nativeLoggingHook(`\u001b[31mFailed lookup: ${key}\n${stack}\u001b[0m`, 2)
}

View file

@ -0,0 +1,181 @@
import { noop } from '@revenge-mod/utils/callback'
import { getFilterMatches } from '../caches'
import { mInitialized } from '../metro/patches'
import {
onAnyModuleInitialized,
onModuleInitialized,
} from '../metro/subscriptions'
import {
exportsFromFilterResultFlag,
FilterResultFlagToHumanReadable,
runFilter,
} from './_internal'
import { FilterScopes } from './filters'
import type { MaybeDefaultExportMatched, Metro } from '../types'
import type {
FilterResultFlag,
RunFilterReturnExportsOptions,
} from './_internal'
import type { Filter, FilterResult } from './filters'
export type WaitForModulesUnsubscribeFunction = () => void
export type WaitForModulesCallback<T> = (exports: T, id: Metro.ModuleID) => any
export type WaitForModulesOptions<ReturnNamespace extends boolean = boolean> =
RunFilterReturnExportsOptions<ReturnNamespace> & {
/**
* Use cached results **only** (if possible).
* If there is no cache result, this works as if you did not pass this option at all.
*
* By default, waits cache results but does not use them, because new modules may still be found.
* Use this option as an optimization if you are sure that you don't need to find new modules once results are cached.
*
* @default false
*/
cached?: boolean
}
export type WaitForModulesResult<
F extends Filter,
O extends WaitForModulesOptions,
> =
O extends RunFilterReturnExportsOptions<true>
? MaybeDefaultExportMatched<FilterResult<F>>
: FilterResult<F>
/**
* Wait for modules to initialize. **Callback won't be called if the module is already initialized!**
*
* @param filter The filter to use.
* @param callback The callback to call when matching modules are initialized.
* @param options The options to use for the wait.
* @returns A function to unsubscribe.
*
* @example
* ```ts
* const unsub = waitForModules(
* withName<typeof import('@shopify/flash-list')>('FlashList'),
* // (exports: typeof import('@shopify/flash-list'), id: Metro.ModuleID) => any
* (exports, id) => {
* unsub()
* // Do something with the module...
* }
* )
* ```
*/
export function waitForModules<F extends Filter>(
filter: F,
callback: WaitForModulesCallback<WaitForModulesResult<F, object>>,
): WaitForModulesUnsubscribeFunction
export function waitForModules<
F extends Filter,
O extends WaitForModulesOptions,
>(
filter: F,
callback: WaitForModulesCallback<WaitForModulesResult<F, O>>,
options: O,
): WaitForModulesUnsubscribeFunction
export function waitForModules(
filter: Filter,
callback: WaitForModulesCallback<any>,
options?: WaitForModulesOptions,
): WaitForModulesUnsubscribeFunction {
if (options?.cached) {
const reg = getFilterMatches(filter.key)
if (reg === null) return noop
if (reg) {
if (__BUILD_FLAG_DEBUG_MODULE_WAITS__)
nativeLoggingHook(
`\u001b[32mUsing cached results for wait: \u001b[33m${filter.key}\u001b[0m`,
1,
)
const runCachedCallback = (
id: Metro.ModuleID,
exports: Metro.ModuleExports,
) => {
const flag = reg[id]
if (__BUILD_FLAG_DEBUG_MODULE_WAITS__)
DEBUG_logWaitMatched(filter.key, id, flag, true)
callback(
exportsFromFilterResultFlag(flag, exports, options),
id,
)
}
const cleanups: Array<() => void> = []
for (const sId of Object.keys(reg)) {
const id = Number(sId)
if (mInitialized.has(id)) continue
cleanups.push(onModuleInitialized(id, runCachedCallback))
}
return () => {
for (const cleanup of cleanups) cleanup()
}
}
}
if (__BUILD_FLAG_DEBUG_MODULE_WAITS__)
nativeLoggingHook(
`\u001b[94mWaiting for module matching: \u001b[93m${filter.key}\u001b[0m`,
1,
)
return onAnyModuleInitialized(
filter.scopes & FilterScopes.All
? (id, exports) => {
const flag = runFilter(filter, id, exports, options)
if (flag) {
if (__BUILD_FLAG_DEBUG_MODULE_WAITS__)
DEBUG_logWaitMatched(filter.key, id, flag)
callback(
exportsFromFilterResultFlag(flag, exports, options),
id,
)
}
}
: (id, exports) => {
if (mInitialized.has(id)) {
const flag = runFilter(filter, id, exports, options)
if (flag) {
if (__BUILD_FLAG_DEBUG_MODULE_WAITS__)
DEBUG_logWaitMatched(filter.key, id, flag)
callback(
exportsFromFilterResultFlag(
flag,
exports,
options,
),
id,
)
}
}
},
)
}
/**
* Logs to the developer that a module wait has matched.
*/
function DEBUG_logWaitMatched(
key: string,
id: Metro.ModuleID,
flag: FilterResultFlag,
cached?: boolean,
) {
nativeLoggingHook(
`\u001b[32mWait matched: \u001b[33m${key}\u001b[0m (matched ${id}, ${FilterResultFlagToHumanReadable[flag]}${cached ? ', \u001b[92mcached\u001b[0m' : ''})`,
1,
)
}

View file

@ -0,0 +1,195 @@
import { cache, cacheBlacklistedModule, Uncached } from '../caches'
import {
global,
metroImportAll,
metroImportDefault,
metroRequire,
} from './runtime'
import type { Metro, RevengeMetro } from '../types'
export let mInitializingId: Metro.ModuleID | undefined
/** Uninitialized IDs (not blacklisted) */
export const mUninitialized = new Set<Metro.ModuleID>()
/** Initialized IDs (not blacklisted) */
export const mInitialized = new Set<Metro.ModuleID>()
export const mDeps = new Map<Metro.ModuleID, Metro.DependencyMap>()
export const mList: RevengeMetro.ModuleList = new Map()
/**
* Metro allows a bundle to be split into segments.
*
* A segment registers itself with `globalThis.__registerSegment(segmentId, moduleDefiner, moduleIds?)`:
* - `moduleDefiner(id)` is a callback that triggers the (deferred) `__d(...)`
* call for module `id` belonging to this segment.
* - `moduleIds` (optional, non-zero segments) is the list of module IDs that
* live in this segment, so the runtime can route requires to the right
* definer before the segment has actually defined them.
*
* When `metroRequire(id)` is called and `id` is not yet in `mList`, we look up
* its segment, invoke that segment's definer (which is expected to call
* `__d(...)` synchronously), and retry the lookup.
*
* @see https://github.com/facebook/metro/blob/6d63660/packages/metro-runtime/src/polyfills/require.js#L387
*/
export const mSegmentDefiners: Array<
((moduleId: Metro.ModuleID) => void) | undefined
> = []
export const mModuleIdToSegmentId = new Map<Metro.ModuleID, number>()
const registerSegment: Metro.RegisterSegmentFn = (
segmentId,
moduleDefiner,
moduleIds,
) => {
mSegmentDefiners[segmentId] = moduleDefiner
if (moduleIds) {
for (const id of moduleIds) {
if (!mList.has(id) && !mModuleIdToSegmentId.has(id)) {
mModuleIdToSegmentId.set(id, segmentId)
}
}
}
}
/**
* Resolve a module that is not yet present in `mList` by invoking its segment definer (if available)
*
* @returns The freshly-registered definition or `undefined`.
*/
export function loadModuleFromSegment(
moduleId: Metro.ModuleID,
): RevengeMetro.ModuleDefinition | undefined {
const segmentId = mModuleIdToSegmentId.get(moduleId) ?? 0
const definer = mSegmentDefiners[segmentId]
if (!definer) return undefined
definer(moduleId)
mModuleIdToSegmentId.delete(moduleId)
return mList.get(moduleId)
}
const metroDefine = (
factory: Metro.FactoryFn,
id: Metro.ModuleID,
dependencyMap: Metro.DependencyMap,
) => {
mDeps.set(id, dependencyMap!)
mUninitialized.add(id)
const def: RevengeMetro.ModuleDefinition = {
flags: 0,
module: undefined,
factory: () => {
// def.module set in metroRequire before factory is called
handleFactoryCall(factory, def.module!)
},
importedDefault: undefined,
importedAll: undefined,
error: undefined,
}
mList.set(id, def)
}
/**
* Patching Metro's `__d` function to handle module definitions.
* We roll our own implementation of Metro's core functions.
*
* Here's how Metro sets itself up:
* 1. `__METRO_GLOBAL_PREFIX__ = ""`
* 2. `${__METRO_GLOBAL_PREFIX__}__d = function define(...) {}`
* - Why don't we patch it here? Because we need to know the value of `__METRO_GLOBAL_PREFIX__` first
* - And since Revenge runs before everything else, we need to patch in the next steps:
* - We chose to patch it in 4. because we can access all the global functions at that point.
* 3. `__r`, `__d`, `__c` is set
* 4. `__registerSegment` is set
* - **PATCH**: Set `__d` to our own implementation.
* - **PATCH**: Set `__registerSegment` to our own implementation.
*
* 5. `clear()`
* - Metro clears the module list directly with `clear()` and not `__c()`.
* 6. `metroRequire.importDefault = ...`, `metroRequire.importAll = ...`
* 7. `global.__registerSegment = registerSegment`
* - **PATCH**: Replace `__registerSegment` with our own implementation so that
* segment-loaded modules become resolvable through our runtime.
* 8. `__d(..., 0, [...])`
* - The first module is defined with ID 0, which is the index module.
* - **PATCH**: Override the `importDefault` and `importAll` functions in `__r`.
* #. `__d` is called with subsequent module definitions
* #. Segments are loaded and registered via `__registerSegment(...)`
*/
const defineKey = `${__METRO_GLOBAL_PREFIX__}__d` as const
// First __d call
globalThis[defineKey] = function define(origFactory, id, deps) {
// Set own implementation of metroImportDefault and metroImportAll
metroRequire.importDefault = metroImportDefault
metroRequire.importAll = metroImportAll
// Set to the actual custom implementation
globalThis[defineKey] = metroDefine
// Call the custom implementation
metroDefine(origFactory, id, deps)
}
globalThis.__registerSegment = registerSegment
// Why don't we use all the arguments from Metro.FactoryFn?
// Because there's too many for Hermes to be able to use its dedicated CallN operation
// which only supports up to 4 arguments. (Call, Call1, Call2, Call3, Call4)
function handleFactoryCall(
factory: Metro.FactoryFn,
moduleObject: Metro.Module,
) {
const prevId = mInitializingId
mInitializingId = moduleObject.id!
try {
factory(
global,
metroRequire,
metroImportDefault,
metroImportAll,
moduleObject,
moduleObject.exports,
mDeps.get(mInitializingId)!,
)
const { exports } = moduleObject
// If we don't have the ID in mUninitialized, it means the module is blacklisted
if (mUninitialized.has(mInitializingId)) {
// Blacklist exports that:
// - are primitives (https://developer.mozilla.org/en-US/docs/Glossary/Primitive)
// - are empty objects
switch (typeof exports) {
case 'function':
mInitialized.add(mInitializingId)
break
// biome-ignore lint/suspicious/noFallthroughSwitchClause: Intentional
case 'object': {
if (Reflect.ownKeys(exports).length) {
mInitialized.add(mInitializingId)
break
}
}
default:
cacheBlacklistedModule(mInitializingId)
}
}
} finally {
mUninitialized.delete(mInitializingId)
mInitializingId = prevId
}
}
/// MODULE PATCHES AND BLACKLISTS
// Restore blacklists
if (cache !== Uncached)
for (const id of cache.blacklist) mUninitialized.delete(id)

View file

@ -0,0 +1,124 @@
/**
* A minimal implementation of Metro's runtime with little overhead.
* Making initialization faster and use less resources.
*
* Also avoids cloning exports, allowing for patches to be applied directly without checking for clones.
*/
import { callNativeMethodSync } from '@revenge-mod/modules/native'
import { getErrorStack } from '@revenge-mod/utils/error'
import { FullVersion } from '~constants'
import { loadModuleFromSegment, mInitializingId, mList } from './patches'
import {
executeInitializeSubscriptions,
executeRequireSubscriptions,
} from './subscriptions/_internal'
import type { Metro } from '../types'
export const mErrorChain: Metro.ModuleID[] = []
export const Initialized = 1 << 0
const HasError = 1 << 1
const HasImportedDefault = 1 << 2
const HasImportedAll = 1 << 3
const Initializing = 1 << 4
const InitializedOrInitializing = Initialized | Initializing
const NotInitializedOrInitializingMask = ~InitializedOrInitializing
export const global = globalThis
export const metroRequire = (moduleId => {
let mod = mList.get(moduleId)
// Module isn't registered yet, maybe it's in another segment that hasn't been loaded yet.
if (!mod) mod = loadModuleFromSegment(moduleId)
if (!mod) throw new Error(`Requiring unknown module: ${moduleId}`)
let { flags, module: moduleObject } = mod
if (flags & InitializedOrInitializing) return moduleObject!.exports
if (flags & HasError) {
// Swallow the error and return an empty object, like what Metro does.
// throw mod.error
return moduleObject!.exports
}
mod.flags |= Initializing
moduleObject = mod.module = {
exports: {},
id: moduleId,
}
executeRequireSubscriptions(moduleId)
try {
const { factory } = mod
mod.factory = undefined
factory!()
} catch (e) {
mod.flags = (flags & NotInitializedOrInitializingMask) | HasError
mod.error = e
const msg = `Module ${mInitializingId} failed to initialize:\n\n${getErrorStack(e)}`
if (__DEV__) {
callNativeMethodSync('revenge.alertError', [msg, FullVersion])
} else {
nativeLoggingHook(msg, 2)
}
// Some modifications can cause modules to fail by initializing them in the wrong order, we can't just blacklist them
// cacheBlacklistedModule(mInitializingId)
// So... it wasn't a great idea to throw, Discord has pushed a broken build that has some failing modules
// Vanilla Metro would swallow the error and just return an empty object as the exports..., insanity
// // @ts-expect-error: Not documented, but used by React Native
// if (global.ErrorUtils) global.ErrorUtils.reportFatalError(e)
// else throw e
mErrorChain.push(moduleId)
return (moduleObject.exports = {})
}
mod.flags = (flags & NotInitializedOrInitializingMask) | Initialized
executeInitializeSubscriptions(moduleId, moduleObject.exports)
return moduleObject.exports
}) as Metro.Require
global.__r = metroRequire
export const metroImportDefault: Metro.RequireFn = moduleId => {
const exports = metroRequire(moduleId)
// metroRequire may have lazily registered the module via a segment, so we
// look up the definition after the require call.
const mod = mList.get(moduleId)!
if (mod.flags & HasImportedDefault) return mod.importedDefault
mod.flags |= HasImportedDefault
return (mod.importedDefault = exports?.__esModule
? exports.default
: exports)
}
export const metroImportAll: Metro.RequireFn = moduleId => {
const exports = metroRequire(moduleId)
const mod = mList.get(moduleId)!
if (mod.flags & HasImportedAll) return mod.importedAll
// Our implementation doesn't match Metro's because we modify the exports directly instead of cloning
// But this is why ours is superior, it allows patching the exports without needing to do it more than a single time
if (!exports?.__esModule) exports.default = exports
mod.flags |= HasImportedAll
return (mod.importedAll = exports)
}

View file

@ -0,0 +1,48 @@
import type { Metro } from '../../types'
import type { ModuleFirstRequiredCallback, ModuleInitializedCallback } from '.'
export const sRequireAny = new Set<ModuleFirstRequiredCallback>()
export const sRequire = new Map<
Metro.ModuleID,
Set<ModuleFirstRequiredCallback>
>()
export const sInitializeAny = new Set<ModuleInitializedCallback>()
export const sInitialize = new Map<
Metro.ModuleID,
Set<ModuleInitializedCallback>
>()
export function executeRequireSubscriptions(id: Metro.ModuleID) {
for (const cb of sRequireAny)
try {
cb(id)
} catch {}
if (sRequire.has(id)) {
for (const cb of sRequire.get(id)!)
try {
cb(id)
} catch {}
sRequire.delete(id)
}
}
export function executeInitializeSubscriptions(
id: Metro.ModuleID,
exports: Metro.ModuleExports,
) {
for (const cb of sInitializeAny)
try {
cb(id, exports)
} catch {}
if (sInitialize.has(id)) {
for (const cb of sInitialize.get(id)!)
try {
cb(id, exports)
} catch {}
sInitialize.delete(id)
}
}

View file

@ -0,0 +1,94 @@
import { sInitialize, sInitializeAny, sRequire, sRequireAny } from './_internal'
import type { Metro } from '../../types'
export type ModuleFirstRequiredCallback = (id: Metro.ModuleID) => void
export type ModuleInitializedCallback = (
id: Metro.ModuleID,
exports: Metro.ModuleExports,
) => void
/**
* Registers a callback to be called when any module is initialized.
*
* This runs after the module factory has been executed, but before the module is considered initialized by Metro.
* However, Revenge APIs will consider the module initialized at this point.
*
* @see {@link initializedModuleHasBadExports} to avoid bad module exports.
*
* @param callback The callback to be called.
* @returns A function that unregisters the callback.
*/
export function onAnyModuleInitialized(callback: ModuleInitializedCallback) {
sInitializeAny.add(callback)
return () => {
sInitializeAny.delete(callback)
}
}
/**
* Registers a callback to be called when a specific module is initialized.
*
* This runs after the module factory has been executed, but before the module is considered initialized by Metro.
* However, Revenge APIs will consider the module initialized at this point.
*
* @see {@link initializedModuleHasBadExports} to avoid bad module exports.
*
* @param id The ID of the module.
* @param callback The callback to be called.
* @returns A function that unregisters the callback.
*/
export function onModuleInitialized(
id: Metro.ModuleID,
callback: ModuleInitializedCallback,
) {
let set = sInitialize.get(id)
if (!set) sInitialize.set(id, (set = new Set()))
set.add(callback)
return () => {
set.delete(callback)
}
}
/**
* Registers a callback to be called when any module is being initialized.
*
* This runs before the module factory is executed.
*
* @see {@link initializedModuleHasBadExports} to avoid bad module exports.
*
* @param callback The callback to be called.
* @returns A function that unregisters the callback.
*/
export function onAnyModuleFirstRequired(
callback: ModuleFirstRequiredCallback,
) {
sRequireAny.add(callback)
return () => {
sRequireAny.delete(callback)
}
}
/**
* Registers a callback to be called when a specific module is being initialized.
*
* This runs before the module factory is executed.
*
* @see {@link initializedModuleHasBadExports} to avoid bad module exports.
*
* @param id The ID of the module.
* @param callback The callback to be called.
* @returns A function that unregisters the callback.
*/
export function onModuleFirstRequired(
id: Metro.ModuleID,
callback: ModuleFirstRequiredCallback,
) {
let set = sRequire.get(id)
if (!set) sRequire.set(id, (set = new Set()))
set.add(callback)
return () => {
set.delete(callback)
}
}

View file

@ -0,0 +1,56 @@
import { mDeps, mList } from './patches'
import { Initialized } from './runtime'
import type { Metro } from '../types'
/**
* Returns the dependencies of a module.
* @param id The module ID.
* @returns The dependency map of the module, or `undefined` if the module does not exist.
*/
export function getModuleDependencies(
id: Metro.ModuleID,
): Metro.DependencyMap | undefined {
return mDeps.get(id)
}
/**
* Returns whether a module is initialized.
* @param id The module ID.
* @returns Non-zero number if the module is initialized, `0` if it is not initialized or does not exist.
*/
export function isModuleInitialized(id: Metro.ModuleID): number | undefined {
// biome-ignore lint/suspicious/noNonNullAssertedOptionalChain: Hot path, undefined & <n> === 0
return mList.get(id)?.flags! & Initialized
}
/**
* Returns the exports of an initialized module.
*
* @see {@link isModuleInitialized} to check if the module is initialized.
*
* @param id The module ID.
* @returns The exports of the module, or `undefined` if the module is not initialized or does not exist.
*/
export function getInitializedModuleExports(
id: Metro.ModuleID,
): Metro.ModuleExports | undefined {
return mList.get(id)?.module?.exports
}
const CATCH_ALL_TEST = Symbol()
/**
* Returns whether a particular module export is bad.
* This is used for filter functions to check whether an export is filterable.
* @param exp The export to check.
*/
export function isModuleExportBad(
exp: Metro.ModuleExports[PropertyKey],
): boolean {
return (
// Nullish?
exp == null ||
// Does it have some non-existent key? (Turbo modules)
(typeof exp === 'object' && CATCH_ALL_TEST in exp)
)
}

View file

@ -0,0 +1,11 @@
import { callNativeMethodSync } from '@revenge-mod/modules/native'
export function reloadApp() {
callNativeMethodSync('revenge.app.reload', [])
}
declare module '@revenge-mod/modules/native' {
interface NativeMethods {
'revenge.app.reload': [[], null]
}
}

View file

@ -0,0 +1,61 @@
import {
callNativeMethod,
callNativeMethodSync,
} from '@revenge-mod/modules/native'
export function readFile(path: string) {
return callNativeMethod('revenge.fs.read', [path])
}
export function writeFile(path: string, data: string) {
return callNativeMethod('revenge.fs.write', [path, data])
}
export function exists(path: string) {
return callNativeMethod('revenge.fs.exists', [path])
}
export function rm(path: string) {
return callNativeMethod('revenge.fs.delete', [path])
}
export function existsSync(path: string) {
return callNativeMethodSync('revenge.fs.exists', [path])
}
export function readFileSync(path: string) {
return callNativeMethodSync('revenge.fs.read', [path])
}
export function writeFileSync(path: string, data: string) {
return callNativeMethodSync('revenge.fs.write', [path, data])
}
export function rmSync(path: string) {
return callNativeMethodSync('revenge.fs.delete', [path])
}
export function deleteFileSync(path: string) {
return callNativeMethodSync('revenge.fs.delete', [path])
}
export function getConstants() {
return callNativeMethodSync('revenge.fs.getConstants', [])
}
declare module '@revenge-mod/modules/native' {
export interface NativeMethods {
'revenge.fs.getConstants': [
[],
{
data: string
files: string
cache: string
},
]
'revenge.fs.read': [[path: string], string]
'revenge.fs.write': [[path: string, data: string], void]
'revenge.fs.exists': [[path: string], boolean]
'revenge.fs.delete': [[path: string], boolean]
}
}

View file

@ -0,0 +1,179 @@
import { getCurrentStack, getErrorStack } from '@revenge-mod/utils/error'
import type { AnyFunction } from '@revenge-mod/utils/types'
const turboModuleProxy = globalThis.__turboModuleProxy
/**
* Backwards compatible way to get a native module. Throws an error if the module is not found.
*
* Use this as a replacement to `TurboModuleRegistry.getEnforcing()`.
*
* @see {@link https://github.com/facebook/react-native/blob/main/packages/react-native/Libraries/TurboModule/TurboModuleRegistry.js#L19-L39 React Native's source}
*
* @param name The name of the native module to get.
*/
export function getNativeModule<T>(name: string): T | null {
const module =
// Non-bridgeless with TurboModules
turboModuleProxy?.(name) ??
// Bridgeless & legacy modules
nativeModuleProxy[name]
if (module) return module as T
throw new Error(`Unable to access native module: ${name}`)
}
const Bridge = getNativeModule<{
getBBox(handle: number, options: object): object
}>('RNSVGRenderableModule')!
const BridgePromise = getNativeModule<{
readAsDataURL(map: object): Promise<any>
}>('FileReaderModule')!
function makePayload(name: string, args: any[]): object {
return {
revenge: {
method: name,
args: args,
},
}
}
/**
* Calls a method on the native module and returns a promise that resolves with the result.
*
* @param name The name of the native method to call.
* @param args The arguments to pass to the native method.
* @returns A promise that resolves with the result of the native method call.
*/
export async function callNativeMethod<N extends MethodName>(
name: N,
args: MethodArgs<N>,
): Promise<MethodResult<N>> {
try {
const result = await BridgePromise.readAsDataURL(
makePayload(name, args),
)
if ('error' in result) throw result.error
if ('result' in result) return result.result as MethodResult<N>
throw 'The module did not return a valid result. The native hook must have failed.'
} catch (error) {
throw new Error(`Call failed: ${error}`)
}
}
/**
* Calls a method on the native module synchronously and returns the result.
*
* Only use synchronous methods when absolutely necessary, as they block JS execution until the native method returns.
*
* @param name The name of the native method to call.
* @param args The arguments to pass to the native method.
* @returns The result of the native method call.
*/
export function callNativeMethodSync<N extends MethodName>(
name: N,
args: MethodArgs<N>,
): MethodResult<N> {
try {
const result = Bridge.getBBox(0, makePayload(name, args))
if ('error' in result) throw result.error
if ('result' in result) return result.result as MethodResult<N>
throw 'The module did not return a valid result. The native hook must have failed.'
} catch (error) {
throw new Error(`Call failed: ${error}`)
}
}
/**
* Get the bridge information.
*/
export function getBridgeInfo(): BridgeInfo | null {
try {
return callNativeMethodSync('revenge.info', [])
} catch (e) {
nativeLoggingHook(
`\u001b[31mFailed to get native bridge info: ${e}\u001b[0m`,
2,
)
return null
}
}
const CallableReturnNativeMethodName = 'revenge.__callableReturn' as const
const CallableModuleName = 'RevengeBridge'
const ExposedJSMethods: {
[methodName: string]: AnyFunction
} = {}
/**
* Registers a JS method that can be called from native code.
*
* @param name The name of the method to register.
* @param method The method implementation.
*/
export function registerJSMethod(name: string, method: AnyFunction) {
if (__DEV__ && ExposedJSMethods[name])
nativeLoggingHook(
`\u001b[33mWarning: Overwriting existing registered JS method: ${name}\n${getCurrentStack()}\u001b[0m`,
1,
)
ExposedJSMethods[name] = _wrapJSMethod(method)
}
function _wrapJSMethod(method: AnyFunction) {
return (...args: any[]) => {
try {
const ret = method(...args)
if (ret instanceof Promise)
ret.then(
result => _returnJSCall({ result: result ?? null }),
error => _returnJSCall({ error: getErrorStack(error) }),
)
else _returnJSCall({ result: ret ?? null })
} catch (error) {
_returnJSCall({ error: getErrorStack(error) })
}
}
}
function _returnJSCall(payload: object) {
callNativeMethodSync(CallableReturnNativeMethodName, [payload])
}
RN$registerCallableModule(
CallableModuleName,
() =>
new Proxy(ExposedJSMethods, {
get(target, prop: string) {
const method = target[prop]
if (!method)
return () => {
// Can't catch this native side, this will crash the app
throw new Error(`JS method not found: ${prop}`)
}
return method
},
}),
)
export interface BridgeInfo {
name: string
version: number
}
export type MethodName = Extract<keyof NativeMethods, string>
export type MethodArgs<T extends MethodName> = NativeMethods[T][0]
export type MethodResult<T extends MethodName> = NativeMethods[T][1]
export interface NativeMethods {
'revenge.info': [[], BridgeInfo]
[CallableReturnNativeMethodName]: [[payload: object], void]
}

101
lib/modules/src/types.ts Normal file
View file

@ -0,0 +1,101 @@
import type { If } from '@revenge-mod/utils/types'
/**
* Metro is a bundler for React Native.
*
* @see {@link https://github.com/facebook/metro/blob/main/packages/metro-runtime/src/polyfills/require.js}
*/
export namespace Metro {
export type DependencyMap = Array<ModuleID>
export type FactoryFn = (
global: object,
require: RequireFn,
metroImportDefault: RequireFn,
metroImportAll: RequireFn,
moduleObject: Module,
exports: ModuleExports,
dependencyMap: DependencyMap,
) => void
export type RegisterSegmentFn = (
segmentId: number,
moduleDefiner: (moduleId: ModuleID) => void,
moduleIds?: ReadonlyArray<ModuleID> | null,
) => void
export type ModuleID = number
export interface ModuleDefinition<Initialized = boolean> {
/**
* Dependencies of this module (set to `undefined` once the module is initialized)
*/
dependencyMap: If<Initialized, undefined, DependencyMap>
/**
* Error that occurred during initialization
*/
error?: any
/**
* Factory function that initializes the module
*/
factory: If<Initialized, undefined, FactoryFn>
/**
* Whether an error occurred during initialization
*/
hasError: boolean
importedAll: ModuleExports
importedDefault: ModuleExports
/**
* Whether factory has been successfully called
* */
isInitialized: boolean
publicModule: Module
}
export type Module = {
id?: ModuleID
exports: ModuleExports
}
export type ModuleList = Map<ModuleID, ModuleDefinition>
export type RequireFn = (id: ModuleID) => ModuleExports
export type DefineFn = (
factory: FactoryFn,
moduleId: ModuleID,
dependencyMap: DependencyMap,
) => void
export type ClearFn = () => ModuleList
export interface Require extends RequireFn {
importDefault: RequireFn
importAll: RequireFn
}
export type ModuleExports = any
}
export namespace RevengeMetro {
export type Module = {
id: Metro.ModuleID
exports: Metro.ModuleExports
}
export type ModuleDefinition<Initialized = boolean> = {
flags: number
module?: Module
factory: If<Initialized, undefined, () => void>
importedDefault?: Metro.ModuleExports
importedAll?: Metro.ModuleExports
error?: If<Initialized, undefined, any>
}
export type ModuleList = Map<Metro.ModuleID, ModuleDefinition>
}
/**
* Maybe the default export matched instead of the namespace, because you're using `options.returnNamespace`.
*/
export type MaybeDefaultExportMatched<T> = T | { default: T }

121
lib/patcher/LICENSE Normal file
View file

@ -0,0 +1,121 @@
Creative Commons Legal Code
CC0 1.0 Universal
CREATIVE COMMONS CORPORATION IS NOT A LAW FIRM AND DOES NOT PROVIDE
LEGAL SERVICES. DISTRIBUTION OF THIS DOCUMENT DOES NOT CREATE AN
ATTORNEY-CLIENT RELATIONSHIP. CREATIVE COMMONS PROVIDES THIS
INFORMATION ON AN "AS-IS" BASIS. CREATIVE COMMONS MAKES NO WARRANTIES
REGARDING THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS
PROVIDED HEREUNDER, AND DISCLAIMS LIABILITY FOR DAMAGES RESULTING FROM
THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS PROVIDED
HEREUNDER.
Statement of Purpose
The laws of most jurisdictions throughout the world automatically confer
exclusive Copyright and Related Rights (defined below) upon the creator
and subsequent owner(s) (each and all, an "owner") of an original work of
authorship and/or a database (each, a "Work").
Certain owners wish to permanently relinquish those rights to a Work for
the purpose of contributing to a commons of creative, cultural and
scientific works ("Commons") that the public can reliably and without fear
of later claims of infringement build upon, modify, incorporate in other
works, reuse and redistribute as freely as possible in any form whatsoever
and for any purposes, including without limitation commercial purposes.
These owners may contribute to the Commons to promote the ideal of a free
culture and the further production of creative, cultural and scientific
works, or to gain reputation or greater distribution for their Work in
part through the use and efforts of others.
For these and/or other purposes and motivations, and without any
expectation of additional consideration or compensation, the person
associating CC0 with a Work (the "Affirmer"), to the extent that he or she
is an owner of Copyright and Related Rights in the Work, voluntarily
elects to apply CC0 to the Work and publicly distribute the Work under its
terms, with knowledge of his or her Copyright and Related Rights in the
Work and the meaning and intended legal effect of CC0 on those rights.
1. Copyright and Related Rights. A Work made available under CC0 may be
protected by copyright and related or neighboring rights ("Copyright and
Related Rights"). Copyright and Related Rights include, but are not
limited to, the following:
i. the right to reproduce, adapt, distribute, perform, display,
communicate, and translate a Work;
ii. moral rights retained by the original author(s) and/or performer(s);
iii. publicity and privacy rights pertaining to a person's image or
likeness depicted in a Work;
iv. rights protecting against unfair competition in regards to a Work,
subject to the limitations in paragraph 4(a), below;
v. rights protecting the extraction, dissemination, use and reuse of data
in a Work;
vi. database rights (such as those arising under Directive 96/9/EC of the
European Parliament and of the Council of 11 March 1996 on the legal
protection of databases, and under any national implementation
thereof, including any amended or successor version of such
directive); and
vii. other similar, equivalent or corresponding rights throughout the
world based on applicable law or treaty, and any national
implementations thereof.
2. Waiver. To the greatest extent permitted by, but not in contravention
of, applicable law, Affirmer hereby overtly, fully, permanently,
irrevocably and unconditionally waives, abandons, and surrenders all of
Affirmer's Copyright and Related Rights and associated claims and causes
of action, whether now known or unknown (including existing as well as
future claims and causes of action), in the Work (i) in all territories
worldwide, (ii) for the maximum duration provided by applicable law or
treaty (including future time extensions), (iii) in any current or future
medium and for any number of copies, and (iv) for any purpose whatsoever,
including without limitation commercial, advertising or promotional
purposes (the "Waiver"). Affirmer makes the Waiver for the benefit of each
member of the public at large and to the detriment of Affirmer's heirs and
successors, fully intending that such Waiver shall not be subject to
revocation, rescission, cancellation, termination, or any other legal or
equitable action to disrupt the quiet enjoyment of the Work by the public
as contemplated by Affirmer's express Statement of Purpose.
3. Public License Fallback. Should any part of the Waiver for any reason
be judged legally invalid or ineffective under applicable law, then the
Waiver shall be preserved to the maximum extent permitted taking into
account Affirmer's express Statement of Purpose. In addition, to the
extent the Waiver is so judged Affirmer hereby grants to each affected
person a royalty-free, non transferable, non sublicensable, non exclusive,
irrevocable and unconditional license to exercise Affirmer's Copyright and
Related Rights in the Work (i) in all territories worldwide, (ii) for the
maximum duration provided by applicable law or treaty (including future
time extensions), (iii) in any current or future medium and for any number
of copies, and (iv) for any purpose whatsoever, including without
limitation commercial, advertising or promotional purposes (the
"License"). The License shall be deemed effective as of the date CC0 was
applied by Affirmer to the Work. Should any part of the License for any
reason be judged legally invalid or ineffective under applicable law, such
partial invalidity or ineffectiveness shall not invalidate the remainder
of the License, and in such case Affirmer hereby affirms that he or she
will not (i) exercise any of his or her remaining Copyright and Related
Rights in the Work or (ii) assert any associated claims and causes of
action with respect to the Work, in either case contrary to Affirmer's
express Statement of Purpose.
4. Limitations and Disclaimers.
a. No trademark or patent rights held by Affirmer are waived, abandoned,
surrendered, licensed or otherwise affected by this document.
b. Affirmer offers the Work as-is and makes no representations or
warranties of any kind concerning the Work, express, implied,
statutory or otherwise, including without limitation warranties of
title, merchantability, fitness for a particular purpose, non
infringement, or the absence of latent or other defects, accuracy, or
the present or absence of errors, whether or not discoverable, all to
the greatest extent permissible under applicable law.
c. Affirmer disclaims responsibility for clearing rights of other persons
that may apply to the Work or any use thereof, including without
limitation any person's Copyright and Related Rights in the Work.
Further, Affirmer disclaims responsibility for obtaining any necessary
consents, permissions or other rights required for any use of the
Work.
d. Affirmer understands and acknowledges that Creative Commons is not a
party to this document and has no duty or obligation with respect to
this CC0 or use of the Work.

341
lib/patcher/README.md Normal file
View file

@ -0,0 +1,341 @@
# @revenge-mod/patcher
This is a JavaScript library that allows to monkey patch functions in a way that is easy to use and understand.
It is made by [ryan-0324](https://github.com/ryan-0324) [(source uploaded on Discord)](https://discord.com/channels/1205207689832038522/1284131216156655646/1316076586981789709) and licensed under [CC0](./LICENSE).
This source code is polished and adapted to work with Revenge. We do not claim any rights to this library. You may use it granted you follow the license.
## How does this work?
Think of hooks as separate functions that are called `before`, `after`, or `instead` of the original function.
You can use them to modify the behavior of the original function, or to add new functionality.
### Before hooks
Before hooks allow you to modify the arguments passed to the original function, or to perform some action before the original function is called.
```js
import { before } from '@revenge-mod/patcher'
const obj = {
method: (a) => console.log('Original method called with:', a)
}
before(obj, 'method', ([a]) => {
console.log('Before method called with:', a)
// Modify arguments by returning new array
return [a + 1]
})
obj.method(2)
// CONSOLE OUTPUT:
// Before method called with: 2
// Original method called with: 3
```
### After hooks
After hooks allow you to modify the return value of the original function, or to perform some action after the original function is called.
```js
import { after } from '@revenge-mod/patcher'
const obj = {
method: (a) => a * 2
}
after(obj, 'method', (result) => {
console.log('After method called with result:', result)
// Modify return value
return result + 1
})
console.log(obj.method(2)) // 5
// CONSOLE OUTPUT:
// After method called with result: 4
// 5
```
### Instead hooks
Instead hooks allow you to completely replace the original function with a new one, while still being able to call the original function if needed.
```js
import { instead } from '@revenge-mod/patcher'
const obj = {
method: (a) => {
console.log('Original method called with:', a)
return 'original result'
}
}
instead(obj, 'method', ([a], original) => {
console.log('Instead method called with:', a)
// Call the original function if needed
const originalResult = original('modified')
console.log('Original method was called')
// Return a new value
return 'new value'
})
console.log(obj.method('test')) // 'new value'
// CONSOLE OUTPUT:
// Instead method called with: test
// Original method called with: modified
// Original method was called
// new value
```
### Combining hooks
You can combine multiple hooks on the same function.
```js
import { before, after, instead } from '@revenge-mod/patcher'
const obj = {
method: (a) => a * 2
}
before(obj, 'method', ([a]) => {
console.log('Before method called with:', a)
return [a + 1] // 2 becomes 3
})
instead(obj, 'method', ([a], original) => {
console.log('Instead method called with:', a)
const result = original(a) // Call original with modified arg (3)
console.log('Original method returned:', result)
return result + 1 // 6 becomes 7
})
after(obj, 'method', (result) => {
console.log('After method called with result:', result)
return result + 1 // 7 becomes 8
})
console.log(obj.method(2)) // 8
// CONSOLE OUTPUT:
// Before method called with: 2
// Instead method called with: 3
// Original method returned: 6
// After method called with result: 7
// 8
```
### Stacking hooks
Stacking multiple hooks of same type will execute them in a specific order:
1. **Before hooks** (execute in reverse order - last added runs first)
2. **Instead hooks** (only the last added executes, unless calling original)
3. **After hooks** (execute in order - first added runs first)
Using multiple `before` hooks will execute them in **reverse order** (LIFO - Last In, First Out):
```js
import { before } from '@revenge-mod/patcher'
const obj = {
method: (a) => console.log('Original method called with:', a)
}
before(obj, 'method', ([a]) => {
console.log('First before hook called with:', a)
return [a + 1]
})
before(obj, 'method', ([a]) => {
console.log('Second before hook called with:', a)
return [a + 2]
})
obj.method(2)
// CONSOLE OUTPUT:
// Second before hook called with: 2
// First before hook called with: 4
// Original method called with: 5
```
Multiple `after` hooks execute in **normal order** (FIFO - First In, First Out):
```js
import { after } from '@revenge-mod/patcher'
const obj = {
method: (a) => a * 2
}
after(obj, 'method', (result) => {
console.log('First after hook called with result:', result)
return result + 1
})
after(obj, 'method', (result) => {
console.log('Second after hook called with result:', result)
return result + 2
})
console.log(obj.method(2)) // 7
// CONSOLE OUTPUT:
// First after hook called with result: 4
// Second after hook called with result: 5
// 7
```
Multiple `instead` hooks will only execute the **last one added**. To chain them, you must call the original function:
```js
import { instead } from '@revenge-mod/patcher'
const obj = {
method: (a) => `original-${a}`
}
instead(obj, 'method', ([a], original) => {
console.log('First instead hook called with:', a)
return `first-${original(a)}`
})
instead(obj, 'method', ([a], original) => {
console.log('Second instead hook called with:', a)
// Calling original will execute the previous instead hook
return `second-${original(a)}`
})
console.log(obj.method('test')) // 'second-first-original-test'
// CONSOLE OUTPUT:
// Second instead hook called with: test
// First instead hook called with: test
// second-first-original-test
```
### Removing hooks
Each hook returns an unpatch function that removes the hook:
```js
import { before } from '@revenge-mod/patcher'
const obj = {
method: (a) => console.log('Original method called with:', a)
}
const unpatch = before(obj, 'method', ([a]) => {
console.log('Before method called with:', a)
return [a + 1]
})
obj.method(2)
// CONSOLE OUTPUT:
// Before method called with: 2
// Original method called with: 3
unpatch() // Remove the hook
obj.method(2)
// CONSOLE OUTPUT:
// Original method called with: 2
```
Unpatch functions are safe to call multiple times and won't throw errors.
### Hook priority
All hooks support an optional priority parameter to control execution order. Higher priority hooks execute before lower priority hooks.
```js
import { before, after, instead, HookPriority } from '@revenge-mod/patcher'
const obj = {
method: (a) => a
}
// Before hooks execute in ascending priority order (lowest to highest)
before(obj, 'method', (args) => {
console.log('Low priority before hook')
return args
}, { priority: HookPriority.LOW })
before(obj, 'method', (args) => {
console.log('High priority before hook')
return args
}, { priority: HookPriority.HIGH })
obj.method(1)
// CONSOLE OUTPUT:
// Low priority before hook
// High priority before hook
// After hooks execute in descending priority order (highest to lowest)
after(obj, 'method', (result) => {
console.log('High priority after hook')
return result
}, { priority: HookPriority.HIGH })
after(obj, 'method', (result) => {
console.log('Low priority after hook')
return result
}, { priority: HookPriority.LOW })
obj.method(1)
// CONSOLE OUTPUT:
// High priority after hook
// Low priority after hook
// Instead hooks execute in descending priority order (highest to lowest)
instead(obj, 'method', function (args, original) {
console.log('High priority instead hook')
return original.apply(this, args)
}, { priority: HookPriority.HIGH })
instead(obj, 'method', function (args, original) {
console.log('Low priority instead hook')
return original.apply(this, args)
}, { priority: HookPriority.LOW })
obj.method(1)
// CONSOLE OUTPUT:
// High priority instead hook
// Low priority instead hook
```
Priority constants:
- `HookPriority.HIGHEST` (1000)
- `HookPriority.HIGH` (500)
- `HookPriority.NORMAL` (0) - default
- `HookPriority.LOW` (-500)
- `HookPriority.LOWEST` (-1000)
You can also use custom numeric values for fine-grained control.
### Constructor patching
You can also patch constructor functions:
```js
import { before } from '@revenge-mod/patcher'
class MyClass {
constructor(value) {
this.value = value
}
}
const exports = { MyClass }
before(exports, 'MyClass', ([value]) => {
console.log('Constructor called with:', value)
return [`modified-${value}`]
})
const instance = new exports.MyClass('test')
console.log(instance.value) // 'modified-test'
// CONSOLE OUTPUT:
// Constructor called with: test
// modified-test
```

19
lib/patcher/package.json Normal file
View file

@ -0,0 +1,19 @@
{
"name": "@revenge-mod/patcher",
"author": {
"name": "ryan-0324",
"email": "77452312+ryan-0324@users.noreply.github.com",
"url": "https://github.com/ryan-0324"
},
"license": "CC0-1.0",
"private": true,
"type": "module",
"exports": {
".": {
"default": "./src/index.ts"
},
"./types": {
"types": "./src/types.ts"
}
}
}

View file

@ -0,0 +1,190 @@
import type {
AbstractNewable,
AfterHook,
BeforeHook,
Callable,
FiniteDomain,
InsteadHook,
UnknownFunction,
} from './types'
export interface FunctionProxyState<
T extends UnknownFunction = UnknownFunction,
> {
readonly proxy: T
readonly target: T
}
export interface PatchedFunctionProxyState<
Key extends PropertyKey = PropertyKey,
Value extends UnknownFunction = UnknownFunction,
> extends FunctionProxyState<Value> {
/** Must have a function valued property whose key is {@link key}. */
readonly parent: Record<Key, Value>
readonly key: Key
before: HookNode<BeforeHook<Value>> | undefined
instead: InsteadHookNode<Value> | undefined
after: HookNode<AfterHook<Value>> | undefined
}
export interface HookNode<Hook extends UnknownFunction = UnknownFunction> {
/** Checked so that hook node lists are not cleared if an unpatch function is called more than once. */
unpatched: boolean
/** Can be undefined only in instances that are not in a hook node list. */
hook: Hook | undefined
priority: number
prev: HookNode<Hook> | undefined
next: HookNode<Hook> | undefined
}
export interface InsteadHookNode<T extends UnknownFunction = UnknownFunction>
extends HookNode<InsteadHook<T>>,
FunctionProxyState<T> {
hook: InsteadHook<T> | undefined
priority: number
prev: InsteadHookNode<T> | undefined
next: InsteadHookNode<T> | undefined
}
/** @throws {TypeError} When `hookNode` is defined, its hook and that of all other hook nodes in its list must also be defined. */
function applyHooks<T>(hookNode: HookNode<(arg: T) => T> | undefined, arg: T) {
while (hookNode) {
// Save a reference to the next hook node in case the current hook calls unpatch.
const { next, hook } = hookNode
// Indirectly call the hook so as to not give it access to its hook node.
arg = hook!(arg)
hookNode = next
}
return arg
}
export const patchedFunctionProxyHandler = {
apply<T extends Callable>(
state: PatchedFunctionProxyState<PropertyKey, T>,
receiver: ThisParameterType<T>,
args: Parameters<T>,
) {
args = applyHooks(state.before, args)
const { instead } = state
let result: ReturnType<T>
if (instead === undefined)
result = Reflect.apply(state.target, receiver, args)
else
result = Reflect.apply(
// Call the instead hook directly, not through its proxy
instead.hook!,
receiver,
[
args,
instead.next === undefined
? state.target
: instead.next.proxy,
],
)
result = applyHooks(state.after, result)
return result
},
construct<T extends AbstractNewable<never, object>>(
state: PatchedFunctionProxyState<PropertyKey, T>,
args: ConstructorParameters<T>,
ctor: AbstractNewable,
) {
args = applyHooks(state.before, args)
const { instead } = state
let result: InstanceType<T>
if (instead === undefined)
result = Reflect.construct(state.target, args, ctor)
else
result = Reflect.construct(
// Call the instead hook directly, not through its proxy
instead.hook!,
[
args,
instead.next === undefined
? state.target
: instead.next.proxy,
],
ctor,
)
result = applyHooks(state.after, result)
return result
},
defineProperty: (state, key, descriptor) =>
Reflect.defineProperty(state.target, key, descriptor),
deleteProperty: (state, key) => Reflect.deleteProperty(state.target, key),
get: (state, key, receiver: unknown) =>
Reflect.get(state.target, key, receiver),
getOwnPropertyDescriptor: (state, key) =>
Reflect.getOwnPropertyDescriptor(state.target, key),
getPrototypeOf: state => Reflect.getPrototypeOf(state.target),
has: (state, key) => Reflect.has(state.target, key),
isExtensible: state => Reflect.isExtensible(state.target),
ownKeys: state => Reflect.ownKeys(state.target),
preventExtensions: state => Reflect.preventExtensions(state.target),
set: (state, key, value: unknown, receiver: unknown) =>
Reflect.set(state.target, key, value, receiver),
setPrototypeOf: (state, prototype) =>
Reflect.setPrototypeOf(state.target, prototype),
} as const satisfies Required<ProxyHandler<FunctionProxyState>>
interface PatchedFunctionProxyStateMap extends WeakMap<UnknownFunction, any> {
readonly delete: (key: UnknownFunction) => boolean
readonly get: <K extends UnknownFunction>(
key: K,
) => PatchedFunctionProxyState<PropertyKey, K> | undefined
readonly has: (key: UnknownFunction) => boolean
readonly set: <K extends UnknownFunction>(
key: K,
value: PatchedFunctionProxyState<PropertyKey, K>,
) => this
}
/** proxy -> state */
export const patchedFunctionProxyStates: PatchedFunctionProxyStateMap =
new WeakMap<UnknownFunction>()
export function createPatchedFunctionProxy<
Key extends PropertyKey,
Value extends UnknownFunction,
>(
target: Value,
parent: Record<Key, Value>,
key: FiniteDomain<Key>,
before: HookNode<BeforeHook<Value>> | undefined,
instead: InsteadHookNode<Value> | undefined,
after: HookNode<AfterHook<Value>> | undefined,
): PatchedFunctionProxyState<Key, Value> {
// biome-ignore lint/complexity/useArrowFunction: We need a function that has a constructor
const state = function () {}
// The handler makes the proxy behave as state.target.
const proxy: Value = new Proxy(state, patchedFunctionProxyHandler) as any
state.proxy = proxy
state.target = target
state.parent = parent
state.key = key
state.before = before
state.instead = instead
state.after = after
patchedFunctionProxyStates.set(proxy, state)
parent[key] = proxy
return state
}
export function unproxy(state: PatchedFunctionProxyState) {
const { parent, key, proxy } = state
if (parent[key] === proxy) {
parent[key] = state.target
patchedFunctionProxyStates.delete(proxy)
}
}

View file

@ -0,0 +1,135 @@
import {
createPatchedFunctionProxy,
patchedFunctionProxyStates,
unproxy,
} from '../_internal'
import type { HookNode, PatchedFunctionProxyState } from '../_internal'
import type {
AfterHook,
FiniteDomain,
HookOptions,
UnknownFunction,
UnpatchFunction,
} from '../types'
function unpatchAfter<T extends UnknownFunction>(
state: PatchedFunctionProxyState<PropertyKey, T>,
hookNode: HookNode<AfterHook<T>>,
) {
if (hookNode.unpatched) return
hookNode.unpatched = true
hookNode.hook = undefined
const { prev, next } = hookNode
if (prev === undefined) {
state.after = next
if (next === undefined) {
if (state.before === undefined && state.instead === undefined)
unproxy(state)
return
}
} else {
prev.next = next
hookNode.prev = undefined
if (next === undefined) return
}
next.prev = prev
hookNode.next = undefined
}
/**
* After hooks allow you to modify the return value of the original function, or to perform some action after the original function is called.
*
* ```js
* import { after } from '@revenge-mod/patcher'
*
* const obj = {
* method: (a) => a * 2
* }
*
* after(obj, 'method', (result) => {
* console.log('After method called with result:', result)
* // Modify return value
* return result + 1
* })
*
* console.log(obj.method(2)) // 5
* // CONSOLE OUTPUT:
* // After method called with result: 4
* // 5
* ```
*
* @param parent The parent object containing the method to patch.
* @param key The key of the method to patch.
* @param hook The hook function to execute after the original method.
* @param options Optional configuration including priority.
*
* @returns A function to unpatch.
*/
export function after<
Parent extends Record<Key, UnknownFunction>,
Key extends keyof Parent,
>(
parent: Parent,
key: Key,
hook: AfterHook<Parent[Key]>,
options?: HookOptions,
): UnpatchFunction
export function after<Key extends PropertyKey, Value extends UnknownFunction>(
parent: Record<Key, Value>,
key: FiniteDomain<Key>,
hook: AfterHook<Value>,
options?: HookOptions,
): UnpatchFunction {
const target = parent[key]
const priority = options?.priority ?? 0
let state = patchedFunctionProxyStates.get(target)
let hookNode: HookNode<typeof hook>
if (state?.parent === parent && state.key === key) {
let current = state.after
let prev: HookNode<typeof hook> | undefined
while (current && current.priority > priority) {
prev = current
current = current.next
}
hookNode = {
hook,
priority,
next: current,
prev,
unpatched: false,
}
if (prev) {
prev.next = hookNode
} else {
state.after = hookNode
}
if (current) {
current.prev = hookNode
}
} else {
hookNode = {
hook,
priority,
next: undefined,
prev: undefined,
unpatched: false,
}
state = createPatchedFunctionProxy(
target,
parent,
key,
undefined,
undefined,
hookNode,
)
}
return unpatchAfter.bind(undefined, state, hookNode)
}

View file

@ -0,0 +1,135 @@
import {
createPatchedFunctionProxy,
patchedFunctionProxyStates,
unproxy,
} from '../_internal'
import type { HookNode, PatchedFunctionProxyState } from '../_internal'
import type {
BeforeHook,
FiniteDomain,
HookOptions,
UnknownFunction,
UnpatchFunction,
} from '../types'
function unpatchBefore<T extends UnknownFunction>(
state: PatchedFunctionProxyState<PropertyKey, T>,
hookNode: HookNode<BeforeHook<T>>,
) {
if (hookNode.unpatched) return
hookNode.unpatched = true
hookNode.hook = undefined
const { prev, next } = hookNode
if (prev === undefined) {
state.before = next
if (next === undefined) {
if (state.instead === undefined && state.after === undefined)
unproxy(state)
return
}
} else {
prev.next = next
hookNode.prev = undefined
if (next === undefined) return
}
next.prev = prev
hookNode.next = undefined
}
/**
* Before hooks allow you to modify the arguments passed to the original function, or to perform some action before the original function is called.
*
* ```js
* import { before } from '@revenge-mod/patcher'
*
* const obj = {
* method: (a) => console.log('Original method called with:', a)
* }
*
* before(obj, 'method', ([a]) => {
* console.log('Before method called with:', a)
* // Modify arguments by returning new array
* return [a + 1]
* })
*
* obj.method(2)
* // CONSOLE OUTPUT:
* // Before method called with: 2
* // Original method called with: 3
* ```
*
* @param parent The parent object containing the method to patch.
* @param key The key of the method to patch.
* @param hook The hook function to execute before the original method.
* @param options Optional configuration including priority.
*
* @returns A function to unpatch.
*/
export function before<
Parent extends Record<Key, UnknownFunction>,
Key extends keyof Parent,
>(
parent: Parent,
key: Key,
hook: BeforeHook<Parent[Key]>,
options?: HookOptions,
): UnpatchFunction
export function before<Key extends PropertyKey, Value extends UnknownFunction>(
parent: Record<Key, Value>,
key: FiniteDomain<Key>,
hook: BeforeHook<Value>,
options?: HookOptions,
): UnpatchFunction {
const target = parent[key]
const priority = options?.priority ?? 0
let state = patchedFunctionProxyStates.get(target)
let hookNode: HookNode<typeof hook>
if (state?.parent === parent && state.key === key) {
let current = state.before
let prev: HookNode<typeof hook> | undefined
while (current && current.priority < priority) {
prev = current
current = current.next
}
hookNode = {
hook,
priority,
next: current,
prev,
unpatched: false,
}
if (prev) {
prev.next = hookNode
} else {
state.before = hookNode
}
if (current) {
current.prev = hookNode
}
} else {
hookNode = {
hook,
priority,
next: undefined,
prev: undefined,
unpatched: false,
}
state = createPatchedFunctionProxy(
target,
parent,
key,
hookNode,
undefined,
undefined,
)
}
return unpatchBefore.bind(undefined, state, hookNode)
}

View file

@ -0,0 +1,177 @@
import {
createPatchedFunctionProxy,
patchedFunctionProxyHandler,
patchedFunctionProxyStates,
unproxy,
} from '../_internal'
import type {
FunctionProxyState,
InsteadHookNode,
PatchedFunctionProxyState,
} from '../_internal'
import type {
AbstractNewable,
Callable,
FiniteDomain,
HookOptions,
InsteadHook,
UnknownFunction,
UnpatchFunction,
} from '../types'
const insteadHookProxyHandler = {
...patchedFunctionProxyHandler,
apply<T extends Callable>(
hookNode: InsteadHookNode<T>,
receiver: ThisParameterType<T>,
args: Parameters<T>,
) {
const { next, hook } = hookNode
return Reflect.apply(hook!, receiver, [
args,
next === undefined ? hookNode.target : next.proxy,
])
},
construct<T extends AbstractNewable<never, object>>(
hookNode: InsteadHookNode<T>,
args: ConstructorParameters<T>,
ctor: AbstractNewable,
) {
const { next, hook } = hookNode
return Reflect.construct(
hook!,
[args, next === undefined ? hookNode.target : next.proxy],
ctor,
)
},
} as const satisfies Required<ProxyHandler<FunctionProxyState>>
function unpatchInstead<T extends UnknownFunction>(
state: PatchedFunctionProxyState<PropertyKey, T>,
hookNode: InsteadHookNode<T>,
) {
if (hookNode.unpatched) return
hookNode.unpatched = true
hookNode.hook = undefined
const { prev, next } = hookNode
if (prev === undefined) {
state.instead = next
if (next === undefined) {
if (state.before === undefined && state.after === undefined)
unproxy(state)
return
}
} else {
prev.next = next
hookNode.prev = undefined
if (next === undefined) return
}
next.prev = prev
hookNode.next = undefined
}
/**
* Instead hooks allow you to completely replace the original function with a new one, while still being able to call the original function if needed.
*
* ```js
* import { instead } from '@revenge-mod/patcher'
*
* const obj = {
* method: (a) => {
* console.log('Original method called with:', a)
* return 'original result'
* }
* }
*
* instead(obj, 'method', ([a], original) => {
* console.log('Instead method called with:', a)
* // Call the original function if needed
* const originalResult = original('modified')
* console.log('Original method was called')
*
* // Return a new value
* return 'new value'
* })
*
* console.log(obj.method('test')) // 'new value'
* // CONSOLE OUTPUT:
* // Instead method called with: test
* // Original method called with: modified
* // Original method was called
* // new value
* ```
*
* @param parent The parent object containing the method to patch.
* @param key The key of the method to patch.
* @param hook The hook function to execute instead of the original method.
* @param options Optional configuration including priority.
*
* @return A function to unpatch.
*/
export function instead<
Parent extends Record<Key, UnknownFunction>,
Key extends keyof Parent,
>(
parent: Parent,
key: Key,
hook: InsteadHook<Parent[Key]>,
options?: HookOptions,
): UnpatchFunction
export function instead<Key extends PropertyKey, Value extends UnknownFunction>(
parent: Record<Key, Value>,
key: FiniteDomain<Key>,
hook: InsteadHook<Value>,
options?: HookOptions,
): UnpatchFunction {
const target = parent[key]
const priority = options?.priority ?? 0
let state = patchedFunctionProxyStates.get(target)
// biome-ignore lint/complexity/useArrowFunction: We need a function that has a constructor
const hookNode = function () {}
// The handler makes the proxy behave as target.
hookNode.proxy = new Proxy<any>(hookNode, insteadHookProxyHandler) as Value
hookNode.target = target
hookNode.unpatched = false
hookNode.hook = hook
hookNode.priority = priority
hookNode.prev = undefined
if (state?.parent === parent && state.key === key) {
let current = state.instead
let prev: InsteadHookNode<Value> | undefined
while (current && current.priority > priority) {
prev = current
current = current.next
}
hookNode.next = current
if (prev) {
prev.next = hookNode
hookNode.prev = prev
} else {
state.instead = hookNode
}
if (current) {
current.prev = hookNode
}
} else {
hookNode.next = undefined
state = createPatchedFunctionProxy(
target,
parent,
key,
undefined,
hookNode,
undefined,
)
}
return unpatchInstead.bind(undefined, state, hookNode)
}

View file

@ -0,0 +1,665 @@
import { beforeEach, describe, expect, mock, test } from 'bun:test'
import { after, before, HookPriority, instead } from '.'
describe('Patcher', () => {
let originalMethod: (...args: any[]) => string
let obj: { method: typeof originalMethod }
beforeEach(() => {
originalMethod = mock(s => s ?? 'original')
obj = {
method: originalMethod,
}
})
describe('before', () => {
test('should execute callback before original method', () => {
const beforeCallback = mock(args => args)
before(obj, 'method', beforeCallback)
obj.method('arg1', 'arg2')
expect(beforeCallback).toHaveBeenCalledWith(['arg1', 'arg2'])
expect(originalMethod).toHaveBeenCalled()
})
test('should allow modifying arguments', () => {
before(obj, 'method', args => {
args[0] = 'modified'
return args
})
obj.method('original')
expect(originalMethod).toHaveBeenCalledWith('modified')
})
test('should unpatch correctly', () => {
const beforeCallback = mock(args => {
args[0] = 'modified'
return args
})
const unpatch = before(obj, 'method', beforeCallback)
// Test that patch is working
obj.method('original')
expect(originalMethod).toHaveBeenCalledWith('modified')
// Unpatch
unpatch()
// Test that patch is removed
obj.method('original')
expect(originalMethod).toHaveBeenCalledWith('original')
expect(beforeCallback).toHaveBeenCalledTimes(1) // Only called before unpatch
})
test('should handle multiple before hooks and unpatch correctly', () => {
const firstHook = mock(args => {
args[0] = 'first'
return args
})
const secondHook = mock(args => {
args[0] = `${args[0]}-second`
return args
})
const unpatch2 = before(obj, 'method', secondHook)
const unpatch1 = before(obj, 'method', firstHook)
obj.method('original')
expect(originalMethod).toHaveBeenCalledWith('first-second')
// Unpatch second hook
unpatch2()
obj.method('original')
expect(originalMethod).toHaveBeenCalledWith('first')
// Unpatch first hook
unpatch1()
obj.method('original')
expect(originalMethod).toHaveBeenCalledWith('original')
})
test('should not crash when unpatch is called multiple times', () => {
const beforeCallback = mock(args => args)
const unpatch = before(obj, 'method', beforeCallback)
unpatch()
expect(() => unpatch()).not.toThrow()
expect(() => unpatch()).not.toThrow()
})
})
describe('after', () => {
test('should execute callback after original method', () => {
const afterCallback = mock(() => 'original')
after(obj, 'method', afterCallback)
const result = obj.method()
expect(afterCallback).toHaveBeenCalledWith('original')
expect(result).toBe('original')
})
test('should allow modifying return value', () => {
after(obj, 'method', () => 'modified')
const result = obj.method()
expect(result).toBe('modified')
})
test('should unpatch correctly', () => {
const afterCallback = mock(() => 'modified')
const unpatch = after(obj, 'method', afterCallback)
// Test that patch is working
let result = obj.method()
expect(result).toBe('modified')
expect(afterCallback).toHaveBeenCalledWith('original')
// Unpatch
unpatch()
// Test that patch is removed
result = obj.method()
expect(result).toBe('original')
expect(afterCallback).toHaveBeenCalledTimes(1) // Only called before unpatch
})
test('should handle multiple after hooks and unpatch correctly', () => {
const firstHook = mock(result => `${result}-first`)
const secondHook = mock(result => `${result}-second`)
const unpatch1 = after(obj, 'method', firstHook)
const unpatch2 = after(obj, 'method', secondHook)
let result = obj.method()
expect(result).toBe('original-second-first')
// Unpatch second hook (most recent)
unpatch2()
result = obj.method()
expect(result).toBe('original-first')
// Unpatch first hook
unpatch1()
result = obj.method()
expect(result).toBe('original')
})
test('should not crash when unpatch is called multiple times', () => {
const afterCallback = mock(result => result)
const unpatch = after(obj, 'method', afterCallback)
unpatch()
expect(() => unpatch()).not.toThrow()
expect(() => unpatch()).not.toThrow()
})
})
describe('instead', () => {
test('should replace original method', () => {
const replacement = mock(() => 'replaced')
instead(obj, 'method', replacement)
const result = obj.method('arg1')
expect(replacement).toHaveBeenCalledWith(
['arg1'],
expect.any(Function),
)
expect(originalMethod).not.toHaveBeenCalled()
expect(result).toBe('replaced')
})
test('should provide access to original method', () => {
instead(obj, 'method', (_args, original) => {
return `${original()} modified`
})
const result = obj.method()
expect(result).toBe('original modified')
})
test('should unpatch correctly', () => {
const replacement = mock(() => 'replaced')
const unpatch = instead(obj, 'method', replacement)
// Test that patch is working
let result = obj.method()
expect(result).toBe('replaced')
expect(originalMethod).not.toHaveBeenCalled()
// Unpatch
unpatch()
// Test that patch is removed
result = obj.method()
expect(result).toBe('original')
expect(originalMethod).toHaveBeenCalled()
expect(replacement).toHaveBeenCalledTimes(1) // Only called before unpatch
})
test('should handle multiple instead hooks and unpatch correctly', () => {
const firstHook = mock((_args, original) => `first-${original()}`)
const secondHook = mock((_args, original) => `second-${original()}`)
const unpatch1 = instead(obj, 'method', firstHook)
const unpatch2 = instead(obj, 'method', secondHook)
let result = obj.method()
expect(result).toBe('second-first-original')
// Unpatch second hook (most recent)
unpatch2()
result = obj.method()
expect(result).toBe('first-original')
// Unpatch first hook
unpatch1()
result = obj.method()
expect(result).toBe('original')
})
test('should not crash when unpatch is called multiple times', () => {
const replacement = mock(() => 'replaced')
const unpatch = instead(obj, 'method', replacement)
unpatch()
expect(() => unpatch()).not.toThrow()
expect(() => unpatch()).not.toThrow()
})
})
describe('mixed hooks', () => {
test('should handle before + after', () => {
const beforeHook = mock(args => {
args[0] = 'modified'
return args
})
const afterHook = mock(result => `${result}-after`)
const unpatchBefore = before(obj, 'method', beforeHook)
const unpatchAfter = after(obj, 'method', afterHook)
let result = obj.method('original')
expect(result).toBe('modified-after')
expect(beforeHook).toHaveBeenCalledWith(['modified'])
expect(afterHook).toHaveBeenCalledWith('modified')
// Unpatch after hook
unpatchAfter()
result = obj.method('original')
expect(result).toBe('modified')
// Unpatch before hook
unpatchBefore()
result = obj.method('original')
expect(result).toBe('original')
})
test('should handle instead + before', () => {
const insteadHook = mock(
(args, original) => `${original(...args)}-instead`,
)
const beforeHook = mock(args => {
args[0] = 'modified'
return args
})
const unpatchInstead = instead(obj, 'method', insteadHook)
const unpatchBefore = before(obj, 'method', beforeHook)
let result = obj.method('original')
expect(result).toBe('modified-instead')
expect(insteadHook).toHaveBeenCalledWith(
['modified'],
expect.any(Function),
)
expect(beforeHook).toHaveBeenCalledWith(['modified'])
// Unpatch before hook
unpatchBefore()
result = obj.method('original')
expect(result).toBe('original-instead')
// Unpatch instead hook
unpatchInstead()
result = obj.method('original')
expect(result).toBe('original')
})
test('should handle instead + after', () => {
const insteadHook = mock(() => 'oops')
const afterHook = mock(result => `${result}-after`)
const unpatchInstead = instead(obj, 'method', insteadHook)
const unpatchAfter = after(obj, 'method', afterHook)
let result = obj.method('original')
expect(result).toBe('oops-after')
expect(insteadHook).toHaveBeenCalledWith(
['original'],
expect.any(Function),
)
expect(afterHook).toHaveBeenCalledWith('oops')
// Unpatch after hook
unpatchAfter()
result = obj.method('original')
expect(result).toBe('oops')
// Unpatch instead hook
unpatchInstead()
result = obj.method('original')
expect(result).toBe('original')
})
test('should handle instead + before + after', () => {
const insteadHook = mock(
(args, original) => `${original(...args)}-instead`,
)
const beforeHook = mock(args => {
args[0] = 'modified'
return args
})
const afterHook = mock(result => `${result}-after`)
const unpatchInstead = instead(obj, 'method', insteadHook)
const unpatchBefore = before(obj, 'method', beforeHook)
const unpatchAfter = after(obj, 'method', afterHook)
let result = obj.method('original')
expect(result).toBe('modified-instead-after')
expect(insteadHook).toHaveBeenCalledWith(
['modified'],
expect.any(Function),
)
expect(beforeHook).toHaveBeenCalledWith(['modified'])
expect(afterHook).toHaveBeenCalledWith('modified-instead')
// Unpatch after hook
unpatchAfter()
result = obj.method('original')
expect(result).toBe('modified-instead')
// Unpatch before hook
unpatchBefore()
result = obj.method('original')
expect(result).toBe('original-instead')
// Unpatch instead hook
unpatchInstead()
result = obj.method('original')
expect(result).toBe('original')
})
test('should handle before + after + instead', () => {
const beforeHook = mock(args => {
args[0] = 'before-modified'
return args
})
const afterHook = mock(result => `${result}-after`)
const insteadHook = mock(
(args, original) => `${original(...args)}-instead`,
)
const unpatchBefore = before(obj, 'method', beforeHook)
const unpatchAfter = after(obj, 'method', afterHook)
const unpatchInstead = instead(obj, 'method', insteadHook)
let result = obj.method('original')
expect(result).toBe('before-modified-instead-after')
expect(beforeHook).toHaveBeenCalledWith(['before-modified'])
expect(afterHook).toHaveBeenCalledWith('before-modified-instead')
expect(insteadHook).toHaveBeenCalledWith(
['before-modified'],
expect.any(Function),
)
// Unpatch after hook
unpatchAfter()
result = obj.method('original')
expect(result).toBe('before-modified-instead')
// Unpatch before hook
unpatchBefore()
result = obj.method('original')
expect(result).toBe('original-instead')
// Unpatch instead hook
unpatchInstead()
result = obj.method('original')
expect(result).toBe('original')
})
test('should restore original method when all hooks are unpatched', () => {
const originalRef = obj.method
const unpatch1 = before(obj, 'method', args => args)
const unpatch2 = after(obj, 'method', result => result)
// Method should be patched
expect(obj.method).not.toBe(originalRef)
unpatch1()
// Still patched because after hook remains
expect(obj.method).not.toBe(originalRef)
unpatch2()
// Should be restored to original
expect(obj.method).toBe(originalRef)
})
})
// describe('error handling', () => {
// test('should throw error for invalid parent', () => {
// expect(() => before(null as any, 'method', () => [])).toThrow()
// expect(() => before(undefined as any, 'method', () => [])).toThrow()
// expect(() => before('string' as any, 'method', () => [])).toThrow()
// })
// test('should throw error for non-existent property', () => {
// expect(() => before(obj, 'nonExistent' as any, () => [])).toThrow(
// "Property 'nonExistent' does not exist on parent",
// )
// })
// test('should throw error for non-function property', () => {
// const objWithNonFunction = { prop: 'not a function' }
// expect(() =>
// before(objWithNonFunction, 'prop' as any, () => []),
// ).toThrow("Property 'prop' is not a function")
// })
// test('should throw error for invalid hook', () => {
// expect(() => before(obj, 'method', null as any)).toThrow()
// expect(() => before(obj, 'method', 'string' as any)).toThrow()
// })
// })
describe('constructor patching', () => {
test('should patch constructor functions', () => {
class TestClass {
value: string
constructor(value: string) {
this.value = value
}
}
const obj = { TestClass }
const beforeHook = mock(args => {
args[0] = 'modified'
return args
})
before(obj, 'TestClass', beforeHook)
const instance = new obj.TestClass('original')
expect(instance.value).toBe('modified')
expect(beforeHook).toHaveBeenCalledWith(['modified'])
})
})
describe('priority system', () => {
test('before hooks should execute in ascending priority order', () => {
const order: number[] = []
before(
obj,
'method',
args => {
order.push(2)
return args
},
{ priority: HookPriority.NORMAL },
)
before(
obj,
'method',
args => {
order.push(1)
return args
},
{ priority: HookPriority.LOWEST },
)
before(
obj,
'method',
args => {
order.push(3)
return args
},
{ priority: HookPriority.HIGHEST },
)
obj.method()
expect(order).toEqual([1, 2, 3])
})
test('after hooks should execute in descending priority order', () => {
const order: number[] = []
after(
obj,
'method',
result => {
order.push(2)
return result
},
{ priority: HookPriority.NORMAL },
)
after(
obj,
'method',
result => {
order.push(3)
return result
},
{ priority: HookPriority.LOWEST },
)
after(
obj,
'method',
result => {
order.push(1)
return result
},
{ priority: HookPriority.HIGHEST },
)
obj.method()
expect(order).toEqual([1, 2, 3])
})
test('instead hooks should execute highest priority first', () => {
const order: number[] = []
instead(
obj,
'method',
(args, original) => {
order.push(1)
return `1-${original(...args)}`
},
{ priority: HookPriority.LOWEST },
)
instead(
obj,
'method',
(args, original) => {
order.push(2)
return `2-${original(...args)}`
},
{ priority: HookPriority.NORMAL },
)
instead(
obj,
'method',
(args, original) => {
order.push(3)
return `3-${original(...args)}`
},
{ priority: HookPriority.HIGHEST },
)
const result = obj.method()
expect(order).toEqual([3, 2, 1])
expect(result).toBe('3-2-1-original')
})
test('before hooks with custom priority values', () => {
const order: number[] = []
before(
obj,
'method',
args => {
order.push(2)
return args
},
{ priority: 0 },
)
before(
obj,
'method',
args => {
order.push(1)
return args
},
{ priority: -100 },
)
before(
obj,
'method',
args => {
order.push(3)
return args
},
{ priority: 100 },
)
before(
obj,
'method',
args => {
order.push(4)
return args
},
{ priority: 150 },
)
obj.method()
expect(order).toEqual([1, 2, 3, 4])
})
test('hooks without priority should default to 0', () => {
const order: number[] = []
before(
obj,
'method',
args => {
order.push(2)
return args
},
{ priority: -10 },
)
before(obj, 'method', args => {
order.push(3)
return args
})
before(
obj,
'method',
args => {
order.push(4)
return args
},
{ priority: 10 },
)
obj.method()
expect(order).toEqual([2, 3, 4])
})
})
})

5
lib/patcher/src/index.ts Normal file
View file

@ -0,0 +1,5 @@
export * from './hooks/after'
export * from './hooks/before'
export * from './hooks/instead'
export { HookPriority } from './types'
export type { HookOptions } from './types'

238
lib/patcher/src/types.ts Normal file
View file

@ -0,0 +1,238 @@
export type FiniteDomain<Key extends PropertyKey> = unknown extends (
Key extends unknown
? object extends Record<Key, unknown>
? unknown
: never
: never
)
? never
: Key
export type UnknownFunction = Callable | AbstractNewable
export type Callable<
This = never,
Args extends readonly unknown[] = never,
Return = unknown,
> = (this: This, ...args: Args) => Return
export type AbstractNewable<
Args extends readonly unknown[] = never,
Return = unknown,
> = abstract new (...args: Args) => Return
export type ConcreteNewable<
Args extends readonly unknown[] = never,
Return = unknown,
> = new (...args: Args) => Return
export type UnionToIntersection<Union> = (
Union extends unknown
? (arg: Union) => unknown
: never
) extends (arg: infer Intersection) => unknown
? Intersection & Union
: never
export type BeforeHook<T extends UnknownFunction = UnknownFunction> =
OverloadUnion<T> extends infer U
? 0 extends 1 & U
? (args: any) => any
: UnionToIntersection<
U extends Callable<never, infer Args>
? (args: Args) => Args
: U extends ConcreteNewable<infer Args>
? (args: Args) => Args
: never
>
: never
export type InsteadHook<T extends UnknownFunction = UnknownFunction> =
OverloadUnion<T> extends infer U
? 0 extends 1 & U
?
| ((this: any, args: any[], originalFunction: T) => any)
| (abstract new (
args: any[],
originalFunction: T,
) => any)
: UnionToIntersection<
U extends Callable<infer This, infer Args, infer Return>
? (this: This, args: Args, originalFunction: T) => Return
: U extends ConcreteNewable<infer Args, infer Return>
? abstract new (
args: Args,
originalFunction: T,
) => Return
: never
>
: never
export type AfterHook<T extends UnknownFunction = UnknownFunction> =
OverloadUnion<T> extends infer U
? 0 extends 1 & U
? (result: any) => any
: UnionToIntersection<
U extends Callable<never, never, infer Return>
? (result: Return) => Return
: U extends ConcreteNewable<never, infer Return>
? (result: Return) => Return
: never
>
: never
/** @see {@link https://github.com/microsoft/TypeScript/issues/32164#issuecomment-1146737709} */
export type OverloadUnion<
Overload extends UnknownFunction,
PartialOverload = OmitOverloads<Overload>,
> = 0 extends 1 & Overload
? any
: Overload extends Callable<infer CThis, infer CArgs, infer CReturn>
? Overload extends AbstractNewable<infer NArgs, infer NReturn>
? OverloadUnionCallableNewable<
Overload,
PartialOverload,
Callable<CThis, CArgs, CReturn>,
ConcreteNewable<NArgs, NReturn>
>
: OverloadUnionCallable<
Overload,
PartialOverload,
Callable<CThis, CArgs, CReturn>
>
: Overload extends AbstractNewable<infer NArgs, infer NReturn>
? OverloadUnionNewable<
Overload,
PartialOverload,
ConcreteNewable<NArgs, NReturn>
>
: never
export type OmitOverloads<T> = { [Key in keyof T]: T[Key] }
export type OverloadUnionCallableNewable<
Overload extends Callable & AbstractNewable,
PartialOverload,
CurrentCallable extends Callable,
CurrentNewable extends ConcreteNewable,
> =
| OverloadUnionCallableNewableInner<
CurrentCallable & CurrentNewable & Overload,
CurrentCallable & CurrentNewable & PartialOverload,
CurrentCallable & CurrentNewable
>
| CurrentCallable
| CurrentNewable
export type OverloadUnionCallableNewableInner<
Overload extends Callable & AbstractNewable,
PartialOverload,
PreviousOverload extends Callable & ConcreteNewable,
> = PartialOverload extends Overload
? never
: Overload extends Callable<infer CThis, infer CArgs, infer CReturn>
? Overload extends AbstractNewable<infer NArgs, infer NReturn>
? // Detects infinite recursion caused by generic overloads.
Callable<CThis, CArgs, CReturn> &
ConcreteNewable<NArgs, NReturn> extends PreviousOverload
? PreviousOverload extends Callable<CThis, CArgs, CReturn> &
ConcreteNewable<NArgs, NReturn>
? any
: OverloadUnionCallableNewable<
Overload,
PartialOverload,
Callable<CThis, CArgs, CReturn>,
ConcreteNewable<NArgs, NReturn>
>
: OverloadUnionCallableNewable<
Overload,
PartialOverload,
Callable<CThis, CArgs, CReturn>,
ConcreteNewable<NArgs, NReturn>
>
: never
: never
export type OverloadUnionCallable<
Overload extends Callable,
PartialOverload,
CurrentCallable extends Callable,
> =
| OverloadUnionCallableInner<
CurrentCallable & Overload,
CurrentCallable & PartialOverload,
CurrentCallable
>
| CurrentCallable
export type OverloadUnionCallableInner<
Overload extends Callable,
PartialOverload,
PreviousOverload extends Callable,
> = PartialOverload extends Overload
? never
: Overload extends Callable<infer This, infer Args, infer Return>
? // Detects infinite recursion caused by generic overloads.
Callable<This, Args, Return> extends PreviousOverload
? PreviousOverload extends Callable<This, Args, Return>
? any
: OverloadUnionCallable<
Overload,
PartialOverload,
Callable<This, Args, Return>
>
: OverloadUnionCallable<
Overload,
PartialOverload,
Callable<This, Args, Return>
>
: never
export type OverloadUnionNewable<
Overload extends AbstractNewable,
PartialOverload,
CurrentNewable extends ConcreteNewable,
> =
| OverloadUnionNewableInner<
CurrentNewable & Overload,
CurrentNewable & PartialOverload,
CurrentNewable
>
| CurrentNewable
export type OverloadUnionNewableInner<
Overload extends AbstractNewable,
PartialOverload,
PreviousOverload extends ConcreteNewable,
> = PartialOverload extends Overload
? never
: Overload extends AbstractNewable<infer Args, infer Return>
? // Detects infinite recursion caused by generic overloads.
ConcreteNewable<Args, Return> extends PreviousOverload
? PartialOverload extends ConcreteNewable<Args, Return>
? any
: OverloadUnionNewable<
Overload,
PartialOverload,
ConcreteNewable<Args, Return>
>
: OverloadUnionNewable<
Overload,
PartialOverload,
ConcreteNewable<Args, Return>
>
: never
export type UnpatchFunction = () => void
export enum HookPriority {
LOWEST = -1000,
LOW = -500,
NORMAL = 0,
HIGH = 500,
HIGHEST = 1000,
}
export interface HookOptions {
priority?: number
}

29
lib/patcher/tsconfig.json Normal file
View file

@ -0,0 +1,29 @@
{
"compilerOptions": {
// Environment setup & latest features
"lib": ["ESNext"],
"target": "ESNext",
"module": "ESNext",
"moduleDetection": "force",
"types": ["bun"],
// Bundler mode
"moduleResolution": "bundler",
"allowImportingTsExtensions": true,
"verbatimModuleSyntax": true,
"noEmit": true,
// Best practices
"strict": true,
"skipLibCheck": true,
"skipDefaultLibCheck": true,
"noFallthroughCasesInSwitch": true,
"noUncheckedIndexedAccess": true,
// Some stricter flags (disabled by default)
"noUnusedLocals": false,
"noUnusedParameters": false,
"noPropertyAccessFromIndexSignature": false
},
"include": ["src"]
}

Some files were not shown because too many files have changed in this diff Show more