Full Code of sub-store-org/Sub-Store for AI

master be19860cd0f7 cached
115 files
911.4 KB
225.9k tokens
473 symbols
1 requests
Download .txt
Showing preview only (953K chars total). Download the full file or copy to clipboard to get everything.
Repository: sub-store-org/Sub-Store
Branch: master
Commit: be19860cd0f7
Files: 115
Total size: 911.4 KB

Directory structure:
gitextract_j4ptg362/

├── .github/
│   └── workflows/
│       └── main.yml
├── .gitignore
├── LICENSE
├── README.md
├── backend/
│   ├── .babelrc
│   ├── .eslintrc.json
│   ├── .prettierrc.json
│   ├── banner
│   ├── bundle-esbuild.js
│   ├── bundle.js
│   ├── dev-esbuild.js
│   ├── dist/
│   │   └── .gitkeep
│   ├── gulpfile.babel.js
│   ├── jsconfig.json
│   ├── package.json
│   ├── patches/
│   │   └── http-proxy@1.18.1.patch
│   └── src/
│       ├── constants.js
│       ├── core/
│       │   ├── app.js
│       │   ├── proxy-utils/
│       │   │   ├── index.js
│       │   │   ├── parsers/
│       │   │   │   ├── index.js
│       │   │   │   └── peggy/
│       │   │   │       ├── loon.js
│       │   │   │       ├── loon.peg
│       │   │   │       ├── qx.js
│       │   │   │       ├── qx.peg
│       │   │   │       ├── surge.js
│       │   │   │       ├── surge.peg
│       │   │   │       ├── trojan-uri.js
│       │   │   │       └── trojan-uri.peg
│       │   │   ├── preprocessors/
│       │   │   │   └── index.js
│       │   │   ├── processors/
│       │   │   │   └── index.js
│       │   │   ├── producers/
│       │   │   │   ├── clash.js
│       │   │   │   ├── clashmeta.js
│       │   │   │   ├── egern.js
│       │   │   │   ├── index.js
│       │   │   │   ├── loon.js
│       │   │   │   ├── qx.js
│       │   │   │   ├── shadowrocket.js
│       │   │   │   ├── sing-box.js
│       │   │   │   ├── stash.js
│       │   │   │   ├── surfboard.js
│       │   │   │   ├── surge.js
│       │   │   │   ├── surgemac.js
│       │   │   │   ├── uri.js
│       │   │   │   ├── utils.js
│       │   │   │   └── v2ray.js
│       │   │   └── validators/
│       │   │       └── index.js
│       │   └── rule-utils/
│       │       ├── index.js
│       │       ├── parsers.js
│       │       ├── preprocessors.js
│       │       └── producers.js
│       ├── main.js
│       ├── products/
│       │   ├── cron-sync-artifacts.js
│       │   ├── resource-parser.loon.js
│       │   ├── sub-store-0.js
│       │   └── sub-store-1.js
│       ├── restful/
│       │   ├── artifacts.js
│       │   ├── collections.js
│       │   ├── download.js
│       │   ├── errors/
│       │   │   └── index.js
│       │   ├── file.js
│       │   ├── index.js
│       │   ├── miscs.js
│       │   ├── module.js
│       │   ├── node-info.js
│       │   ├── parser.js
│       │   ├── preview.js
│       │   ├── response.js
│       │   ├── settings.js
│       │   ├── sort.js
│       │   ├── subscriptions.js
│       │   ├── sync.js
│       │   └── token.js
│       ├── test/
│       │   └── proxy-parsers/
│       │       ├── loon.spec.js
│       │       ├── qx.spec.js
│       │       ├── surge.spec.js
│       │       └── testcases.js
│       ├── utils/
│       │   ├── database.js
│       │   ├── dns.js
│       │   ├── download.js
│       │   ├── env.js
│       │   ├── flow.js
│       │   ├── geo.js
│       │   ├── gist.js
│       │   ├── headers-resource-cache.js
│       │   ├── index.js
│       │   ├── logical.js
│       │   ├── migration.js
│       │   ├── resource-cache.js
│       │   ├── rs.js
│       │   ├── script-resource-cache.js
│       │   ├── user-agent.js
│       │   └── yaml.js
│       └── vendor/
│           ├── express.js
│           ├── md5.js
│           └── open-api.js
├── config/
│   ├── Egern.yaml
│   ├── Loon.plugin
│   ├── QX-Task.json
│   ├── QX.snippet
│   ├── README.md
│   ├── Stash.stoverride
│   ├── Surge-Beta.sgmodule
│   ├── Surge-Noability.sgmodule
│   ├── Surge-ability.sgmodule
│   └── Surge.sgmodule
├── scripts/
│   ├── demo.js
│   ├── fancy-characters.js
│   ├── ip-flag-node.js
│   ├── ip-flag.js
│   ├── media-filter.js
│   ├── revert.js
│   ├── tls-fingerprint.js
│   ├── udp-filter.js
│   └── vmess-ws-obfs-host.js
└── vs.code-workspace

================================================
FILE CONTENTS
================================================

================================================
FILE: .github/workflows/main.yml
================================================
name: build
on:
  workflow_dispatch:
  push:
    branches:
      - master
    paths:
      - "backend/package.json"
  pull_request:
    branches:
      - master
    paths:
      - "backend/package.json"
jobs:
  build:
    runs-on: ubuntu-latest
    steps:
      - name: Checkout
        uses: actions/checkout@v3
        with:
          ref: "master"
      - name: Set up Node.js
        uses: actions/setup-node@v3
        with:
          node-version: "20"
      - name: Install dependencies
        run: |
          npm install -g pnpm
          cd backend && pnpm i --no-frozen-lockfile
      # - name: Test
      #   run: |
      #     cd backend
      #     pnpm test
      # - name: Build
      #   run: |
      #     cd backend
      #     pnpm run build
      - name: Bundle
        run: |
          cd backend
          pnpm bundle:esbuild
      - id: tag
        name: Generate release tag
        run: |
          cd backend
          SUBSTORE_RELEASE=`node --eval="process.stdout.write(require('./package.json').version)"`
          echo "release_tag=$SUBSTORE_RELEASE" >> $GITHUB_OUTPUT
      - name: Prepare release
        run: |
          cd backend
          pnpm i -D conventional-changelog-cli
          pnpm run changelog
      - name: Release
        uses: softprops/action-gh-release@v1
        if: ${{ success() }}
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
        with:
          body_path: ./backend/CHANGELOG.md
          tag_name: ${{ steps.tag.outputs.release_tag }}
          # generate_release_notes: true
          files: |
            ./backend/sub-store.min.js
            ./backend/dist/sub-store-0.min.js
            ./backend/dist/sub-store-1.min.js
            ./backend/dist/sub-store-parser.loon.min.js
            ./backend/dist/cron-sync-artifacts.min.js
            ./backend/dist/sub-store.bundle.js
      - name: Git push assets to "release" branch
        run: |
          cd backend/dist || exit 1
          git init
          git config --local user.name "github-actions[bot]"
          git config --local user.email "github-actions[bot]@users.noreply.github.com"
          git checkout -b release
          git add .
          git commit -m "release: ${{ steps.tag.outputs.release_tag }}"
          git remote add origin "https://${{ github.actor }}:${{ secrets.GITHUB_TOKEN }}@github.com/${{ github.repository }}"
          git push -f -u origin release
      # - name: Sync to GitLab
      #   env:
      #     GITLAB_PIPELINE_TOKEN: ${{ secrets.GITLAB_PIPELINE_TOKEN }}
      #   run: |
      #     curl -X POST --fail -F token=$GITLAB_PIPELINE_TOKEN -F ref=master https://gitlab.com/api/v4/projects/48891296/trigger/pipeline


================================================
FILE: .gitignore
================================================
.DS_Store
# json config
sub-store.json
sub-store_*.json
root.json

# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
lerna-debug.log*

# 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

# 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 variables file
.env
.env.test

# parcel-bundler cache (https://parceljs.org/)
.cache
.parcel-cache

# Next.js build output
.next
out

# Nuxt.js build / generate output
.nuxt
# dist

# Gatsby files
.cache/
# 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

# 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.*

# Editor directories and files
.idea
.vscode
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw?

# Dist files
backend/dist/*
!backend/dist/.gitkeep
backend/sub-store.min.js

CHANGELOG.md

.codeartsdoer
.github/copilot-instructions.md

================================================
FILE: LICENSE
================================================
                   GNU AFFERO GENERAL PUBLIC LICENSE
                       Version 3, 19 November 2007

               Copyright (c) 2015 Ayuntamiento de Madrid

 Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
 Everyone is permitted to copy and distribute verbatim copies
 of this license document, but changing it is not allowed.

                            Preamble

  The GNU Affero General Public License is a free, copyleft license for
software and other kinds of works, specifically designed to ensure
cooperation with the community in the case of network server software.

  The licenses for most software and other practical works are designed
to take away your freedom to share and change the works.  By contrast,
our General Public Licenses are 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.

  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.

  Developers that use our General Public Licenses protect your rights
with two steps: (1) assert copyright on the software, and (2) offer
you this License which gives you legal permission to copy, distribute
and/or modify the software.

  A secondary benefit of defending all users' freedom is that
improvements made in alternate versions of the program, if they
receive widespread use, become available for other developers to
incorporate.  Many developers of free software are heartened and
encouraged by the resulting cooperation.  However, in the case of
software used on network servers, this result may fail to come about.
The GNU General Public License permits making a modified version and
letting the public access it on a server without ever releasing its
source code to the public.

  The GNU Affero General Public License is designed specifically to
ensure that, in such cases, the modified source code becomes available
to the community.  It requires the operator of a network server to
provide the source code of the modified version running there to the
users of that server.  Therefore, public use of a modified version, on
a publicly accessible server, gives the public access to the source
code of the modified version.

  An older license, called the Affero General Public License and
published by Affero, was designed to accomplish similar goals.  This is
a different license, not a version of the Affero GPL, but Affero has
released a new version of the Affero GPL which permits relicensing under
this license.

  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 Affero 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. Remote Network Interaction; Use with the GNU General Public License.

  Notwithstanding any other provision of this License, if you modify the
Program, your modified version must prominently offer all users
interacting with it remotely through a computer network (if your version
supports such interaction) an opportunity to receive the Corresponding
Source of your version by providing access to the Corresponding Source
from a network server at no charge, through some standard or customary
means of facilitating copying of software.  This Corresponding Source
shall include the Corresponding Source for any work covered by version 3
of the GNU General Public License that is incorporated pursuant to the
following paragraph.

  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 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 work with which it is combined will remain governed by version
3 of the GNU General Public License.

  14. Revised Versions of this License.

  The Free Software Foundation may publish revised and/or new versions of
the GNU Affero 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 Affero 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 Affero 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 Affero 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

            How to Apply These Terms to Your New Programs

  If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.

  To do so, attach the following notices to the program.  It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.

    <one line to give the program's name and a brief idea of what it does.>
    Copyright (C) <year>  <name of author>

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU Affero General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU Affero General Public License for more details.

    You should have received a copy of the GNU Affero General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.

Also add information on how to contact you by electronic and paper mail.

  If your software can interact with users remotely through a computer
network, you should also make sure that it provides a way for users to
get its source.  For example, if your program is a web application, its
interface could display a "Source" link that leads users to an archive
of the code.  There are many ways you could offer source, and different
solutions will be better for different programs; see section 13 for the
specific requirements.

  You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU AGPL, see
<http://www.gnu.org/licenses/>.


================================================
FILE: README.md
================================================
<div align="center">
<br>
<img width="200" src="https://raw.githubusercontent.com/cc63/ICON/main/Sub-Store.png" alt="Sub-Store">
<br>
<br>
<h2 align="center">Sub-Store<h2>
</div>

<p align="center" color="#6a737d">
Advanced Subscription Manager for QX, Loon, Surge, Stash, Egern and Shadowrocket.
</p>

[![Build](https://github.com/sub-store-org/Sub-Store/actions/workflows/main.yml/badge.svg)](https://github.com/sub-store-org/Sub-Store/actions/workflows/main.yml) ![GitHub](https://img.shields.io/github/license/sub-store-org/Sub-Store) ![GitHub issues](https://img.shields.io/github/issues/sub-store-org/Sub-Store) ![GitHub closed pull requests](https://img.shields.io/github/issues-pr-closed-raw/Peng-Ym/Sub-Store) ![Lines of code](https://img.shields.io/tokei/lines/github/sub-store-org/Sub-Store) ![Size](https://img.shields.io/github/languages/code-size/sub-store-org/Sub-Store)
<a href="https://trendshift.io/repositories/4572" target="_blank"><img src="https://trendshift.io/api/badge/repositories/4572" alt="sub-store-org%2FSub-Store | Trendshift" style="width: 250px; height: 55px;" width="250" height="55"/></a>
[!["Buy Me A Coffee"](https://www.buymeacoffee.com/assets/img/custom_images/orange_img.png)](https://www.buymeacoffee.com/PengYM)

[📚 文档/DOC](https://github.com/sub-store-org/Sub-Store/wiki)

Core functionalities:

1. Conversion among various formats.
2. Subscription formatting.
3. Collect multiple subscriptions in one URL.

> The following descriptions of features may not be updated in real-time. Please refer to the actual available features for accurate information.

## 1. Subscription Conversion

### Supported Input Formats

[本地节点怎么写/How To Write A Local Node](https://t.me/zhetengsha/824)

> ⚠️ Do not use `Shadowrocket` or `NekoBox` to export URI and then import it as input. The URIs exported in this way may not be standard URIs. However, we have already supported some very common non-standard URIs (such as VMess, VLESS).

- [x] Proxy URI Scheme(`socks5`, `socks5+tls`, `http`, `https`(it's ok))

  example: `socks5+tls://user:pass@ip:port#name`

- [x] URI(AnyTLS, SOCKS, SS, SSR, VMess, VLESS, Trojan, Hysteria, Hysteria 2, TUIC v5, WireGuard)
  > Please note, HTTP(s) does not have a standard URI format, so it is not supported. Please use other formats.
- [x] Clash Proxies YAML
- [x] Clash Proxy JSON/JSON5/YAML(single line)
  > [NaiveProxy](https://t.me/zhetengsha/4308)
- [x] QX (SS, SSR, VMess, Trojan, HTTP, SOCKS5, VLESS)
- [x] Loon (SS, SSR, VMess, Trojan, HTTP, SOCKS5, SOCKS5-TLS, WireGuard, VLESS, Hysteria 2, AnyTLS)
- [x] Surge (Direct, SS, VMess, Trojan, HTTP, SOCKS5, SOCKS5-TLS, AnyTLS, TrustTunnel, TUIC, Snell, Hysteria 2, SSH(Password authentication only), External Proxy Program(only for macOS), WireGuard(Surge to Surge))
- [x] mihomo(Clash.Meta) Compatible (Direct, SS, SSR, VMess, Trojan, HTTP, SOCKS5, Snell, VLESS, WireGuard, Hysteria, Hysteria 2, TUIC, SSH, mieru, sudoku, AnyTLS, MASQUE)

Deprecated(The frontend doesn't show it, but the backend still supports it, with the query parameter `target=Clash`):

- [x] Clash (SS, SSR, VMess, Trojan, HTTP, SOCKS5, Snell, VLESS, WireGuard)

### Supported Target Platforms

- [x] Plain JSON
- [x] Stash
- [x] Clash.Meta(mihomo)
- [x] Surfboard
- [x] Surge
- [x] SurgeMac(Use mihomo to support protocols that are not supported by Surge itself)
- [x] Loon
- [x] Egern
- [x] Shadowrocket
- [x] QX
- [x] sing-box
- [x] V2Ray
- [x] V2Ray URI

Deprecated:

- [x] Clash

## 2. Subscription Formatting

### Filtering

- [x] **Regex filter**
- [x] **Discard regex filter**
- [x] **Region filter**
- [x] **Type filter**
- [x] **Useless proxies filter**
- [x] **Script filter**

### Proxy Operations

- [x] **Set property operator**: set some proxy properties such as `udp`,`tfo`, `skip-cert-verify` etc.
- [x] **Flag operator**: add flags or remove flags for proxies.
- [x] **Sort operator**: sort proxies by name.
- [x] **Regex sort operator**: sort proxies by keywords (fallback to normal sort).
- [x] **Regex rename operator**: replace by regex in proxy names.
- [x] **Regex delete operator**: delete by regex in proxy names.
- [x] **Script operator**: modify proxy by script.
- [x] **Resolve Domain Operator**: resolve the domain of nodes to an IP address.

### Development

Install `pnpm`

Go to `backend` directories, install node dependencies:

```
pnpm i
```

```
SUB_STORE_BACKEND_API_PORT=3000 pnpm run --parallel "/^dev:.*/"
```

### Build

```
pnpm bundle:esbuild
```

## LICENSE

This project is under the GPL V3 LICENSE.

[![FOSSA Status](https://app.fossa.com/api/projects/git%2Bgithub.com%2FPeng-YM%2FSub-Store.svg?type=large)](https://app.fossa.com/projects/git%2Bgithub.com%2FPeng-YM%2FSub-Store?ref=badge_large)

## Star History

[![Star History Chart](https://api.star-history.com/svg?repos=sub-store-org/sub-store&type=Date)](https://star-history.com/#sub-store-org/sub-store&Date)

## Acknowledgements

- Special thanks to @KOP-XIAO for his awesome resource-parser. Please give a [star](https://github.com/KOP-XIAO/QuantumultX) for his great work!
- Special thanks to @Orz-3 and @58xinian for their awesome icons.

## Sponsors

[![image](./support.nodeseek.com_page_promotion_id=8.png)](https://yxvm.com)

[NodeSupport](https://github.com/NodeSeekDev/NodeSupport) sponsored this project.


================================================
FILE: backend/.babelrc
================================================
{
    "presets": [
        [
            "@babel/preset-env"
        ]
    ],
    "env": {
        "test": {
            "presets": [
                "@babel/preset-env"
            ]
        }
    },
    "plugins": [
        [
            "babel-plugin-relative-path-import",
            {
                "paths": [
                    {
                        "rootPathPrefix": "@",
                        "rootPathSuffix": "src"
                    }
                ]
            }
        ]
    ]
}

================================================
FILE: backend/.eslintrc.json
================================================
{
    "ignorePatterns": ["*.min.js", "src/vendor/*.js"],
    "env": {
        "browser": true,
        "es2021": true,
        "node": true
    },
    "extends": "eslint:recommended",
    "parserOptions": {
        "ecmaVersion": "latest",
        "sourceType": "module"
    },
    "rules": {
    }
}


================================================
FILE: backend/.prettierrc.json
================================================
{
    "singleQuote": true,
    "trailingComma": "all",
    "tabWidth": 4,
    "bracketSpacing": true
}


================================================
FILE: backend/banner
================================================
/**
 *  ███████╗██╗   ██╗██████╗       ███████╗████████╗ ██████╗ ██████╗ ███████╗
 *  ██╔════╝██║   ██║██╔══██╗      ██╔════╝╚══██╔══╝██╔═══██╗██╔══██╗██╔════╝
 *  ███████╗██║   ██║██████╔╝█████╗███████╗   ██║   ██║   ██║██████╔╝█████╗
 *  ╚════██║██║   ██║██╔══██╗╚════╝╚════██║   ██║   ██║   ██║██╔══██╗██╔══╝
 *  ███████║╚██████╔╝██████╔╝      ███████║   ██║   ╚██████╔╝██║  ██║███████╗
 *  ╚══════╝ ╚═════╝ ╚═════╝       ╚══════╝   ╚═╝    ╚═════╝ ╚═╝  ╚═╝╚══════╝
 * Advanced Subscription Manager for QX, Loon, Surge, Stash and Shadowrocket!
 * @updated: <%= updated %>
 * @version: <%= pkg.version %>
 * @author: Peng-YM
 * @github: https://github.com/sub-store-org/Sub-Store
 * @documentation: https://www.notion.so/Sub-Store-6259586994d34c11a4ced5c406264b46
 */



================================================
FILE: backend/bundle-esbuild.js
================================================
#!/usr/bin/env node
const fs = require('fs');
const path = require('path');
const { build } = require('esbuild');

!(async () => {
    const version = JSON.parse(
        fs.readFileSync(path.join(__dirname, 'package.json'), 'utf-8'),
    ).version.trim();

    const artifacts = [
        { src: 'src/main.js', dest: 'sub-store.min.js' },
        {
            src: 'src/products/resource-parser.loon.js',
            dest: 'dist/sub-store-parser.loon.min.js',
        },
        {
            src: 'src/products/cron-sync-artifacts.js',
            dest: 'dist/cron-sync-artifacts.min.js',
        },
        { src: 'src/products/sub-store-0.js', dest: 'dist/sub-store-0.min.js' },
        { src: 'src/products/sub-store-1.js', dest: 'dist/sub-store-1.min.js' },
    ];

    for await (const artifact of artifacts) {
        await build({
            entryPoints: [artifact.src],
            bundle: true,
            minify: true,
            sourcemap: false,
            platform: 'browser',
            format: 'iife',
            outfile: artifact.dest,
        });
    }

    let content = fs.readFileSync(path.join(__dirname, 'sub-store.min.js'), {
        encoding: 'utf8',
    });
    content = content.replace(
        /eval\(('|")(require\(('|").*?('|")\))('|")\)/g,
        '$2',
    );
    fs.writeFileSync(
        path.join(__dirname, 'dist/sub-store.no-bundle.js'),
        content,
        {
            encoding: 'utf8',
        },
    );

    await build({
        entryPoints: ['dist/sub-store.no-bundle.js'],
        bundle: true,
        minify: true,
        sourcemap: false,
        platform: 'node',
        format: 'cjs',
        outfile: 'dist/sub-store.bundle.js',
    });
    fs.writeFileSync(
        path.join(__dirname, 'dist/sub-store.bundle.js'),
        `// SUB_STORE_BACKEND_VERSION: ${version}
${fs.readFileSync(path.join(__dirname, 'dist/sub-store.bundle.js'), {
    encoding: 'utf8',
})}`,
        {
            encoding: 'utf8',
        },
    );
})()
    .catch((e) => {
        console.log(e);
    })
    .finally(() => {
        console.log('done');
    });


================================================
FILE: backend/bundle.js
================================================
#!/usr/bin/env node
const fs = require('fs');
const path = require('path');
const { build } = require('esbuild');

!(async () => {
    const version = JSON.parse(
        fs.readFileSync(path.join(__dirname, 'package.json'), 'utf-8'),
    ).version.trim();

    let content = fs.readFileSync(path.join(__dirname, 'sub-store.min.js'), {
        encoding: 'utf8',
    });
    content = content.replace(
        /eval\(('|")(require\(('|").*?('|")\))('|")\)/g,
        '$2',
    );
    fs.writeFileSync(
        path.join(__dirname, 'dist/sub-store.no-bundle.js'),
        content,
        {
            encoding: 'utf8',
        },
    );

    await build({
        entryPoints: ['dist/sub-store.no-bundle.js'],
        bundle: true,
        minify: true,
        sourcemap: true,
        platform: 'node',
        format: 'cjs',
        outfile: 'dist/sub-store.bundle.js',
    });
    fs.writeFileSync(
        path.join(__dirname, 'dist/sub-store.bundle.js'),
        `// SUB_STORE_BACKEND_VERSION: ${version}
${fs.readFileSync(path.join(__dirname, 'dist/sub-store.bundle.js'), {
    encoding: 'utf8',
})}`,
        {
            encoding: 'utf8',
        },
    );
})()
    .catch((e) => {
        console.log(e);
    })
    .finally(() => {
        console.log('done');
    });


================================================
FILE: backend/dev-esbuild.js
================================================
#!/usr/bin/env node
const { build } = require('esbuild');

!(async () => {
    const artifacts = [{ src: 'src/main.js', dest: 'sub-store.min.js' }];

    for await (const artifact of artifacts) {
        await build({
            entryPoints: [artifact.src],
            bundle: true,
            minify: false,
            sourcemap: false,
            platform: 'node',
            format: 'cjs',
            outfile: artifact.dest,
        });
    }
})()
    .catch((e) => {
        console.log(e);
    })
    .finally(() => {
        console.log('done');
    });


================================================
FILE: backend/dist/.gitkeep
================================================


================================================
FILE: backend/gulpfile.babel.js
================================================
import fs from 'fs';
import browserify from 'browserify';
import gulp from 'gulp';
import prettier from 'gulp-prettier';
import header from 'gulp-header';
import eslint from 'gulp-eslint-new';
import newFile from 'gulp-file';
import path from 'path';
import tap from 'gulp-tap';

import pkg from './package.json';

export function peggy() {
    return gulp.src('src/**/*.peg').pipe(
        tap(function (file) {
            const filename = path.basename(file.path).split('.')[0] + '.js';
            const raw = fs.readFileSync(file.path, 'utf8');
            const contents = `import * as peggy from 'peggy';
const grammars = String.raw\`\n${raw}\n\`;
let parser;
export default function getParser() {
    if (!parser) {
        parser = peggy.generate(grammars);
    }
    return parser;
}\n`;
            return newFile(filename, contents).pipe(
                gulp.dest(path.dirname(file.path)),
            );
        }),
    );
}

export function lint() {
    return gulp
        .src('src/**/*.js')
        .pipe(eslint({ fix: true }))
        .pipe(eslint.fix())
        .pipe(eslint.format())
        .pipe(eslint.failAfterError());
}

export function styles() {
    return gulp
        .src('src/**/*.js')
        .pipe(
            prettier({
                singleQuote: true,
                trailingComma: 'all',
                tabWidth: 4,
                bracketSpacing: true,
            }),
        )
        .pipe(gulp.dest((file) => file.base));
}

function scripts(src, dest) {
    return () => {
        return browserify(src)
            .transform('babelify', {
                presets: [['@babel/preset-env']],
                plugins: [
                    [
                        'babel-plugin-relative-path-import',
                        {
                            paths: [
                                {
                                    rootPathPrefix: '@',
                                    rootPathSuffix: 'src',
                                },
                            ],
                        },
                    ],
                ],
            })
            .plugin('tinyify')
            .bundle()
            .pipe(fs.createWriteStream(dest));
    };
}

function banner(dest) {
    return () =>
        gulp
            .src(dest)
            .pipe(
                header(fs.readFileSync('./banner', 'utf-8'), {
                    pkg,
                    updated: new Date().toLocaleString('zh-CN'),
                }),
            )
            .pipe(gulp.dest((file) => file.base));
}

const artifacts = [
    { src: 'src/main.js', dest: 'sub-store.min.js' },
    {
        src: 'src/products/resource-parser.loon.js',
        dest: 'dist/sub-store-parser.loon.min.js',
    },
    {
        src: 'src/products/cron-sync-artifacts.js',
        dest: 'dist/cron-sync-artifacts.min.js',
    },
    { src: 'src/products/sub-store-0.js', dest: 'dist/sub-store-0.min.js' },
    { src: 'src/products/sub-store-1.js', dest: 'dist/sub-store-1.min.js' },
];

export const build = gulp.series(
    gulp.parallel(
        artifacts.map((artifact) => scripts(artifact.src, artifact.dest)),
    ),
    gulp.parallel(artifacts.map((artifact) => banner(artifact.dest))),
);

const all = gulp.series(peggy, lint, styles, build);

export default all;


================================================
FILE: backend/jsconfig.json
================================================
{
  "compilerOptions": {
    "baseUrl": ".",
    "paths": {
      "@/*": ["src/*"]
    }
  }
}

================================================
FILE: backend/package.json
================================================
{
  "name": "sub-store",
  "version": "2.21.51",
  "description": "Advanced Subscription Manager for QX, Loon, Surge, Stash and Shadowrocket.",
  "main": "src/main.js",
  "scripts": {
    "preinstall": "npx only-allow pnpm",
    "test": "gulp peggy && npx cross-env BABEL_ENV=test mocha src/test/**/*.spec.js --require @babel/register --recursive",
    "serve": "node sub-store.min.js",
    "start": "nodemon -w src -w package.json --exec babel-node src/main.js",
    "dev:esbuild": "nodemon -w src -w package.json dev-esbuild.js",
    "dev:run": "nodemon -w sub-store.min.js sub-store.min.js",
    "build": "gulp",
    "bundle": "node bundle.js",
    "bundle:esbuild": "node bundle-esbuild.js",
    "changelog": "conventional-changelog -p cli -i CHANGELOG.md -s"
  },
  "author": "Peng-YM",
  "license": "GPL-3.0",
  "pnpm": {
    "patchedDependencies": {
      "http-proxy@1.18.1": "patches/http-proxy@1.18.1.patch"
    }
  },
  "dependencies": {
    "@maxmind/geoip2-node": "^5.0.0",
    "automerge": "1.0.1-preview.7",
    "body-parser": "^1.19.0",
    "buffer": "^6.0.3",
    "connect-history-api-fallback": "^2.0.0",
    "cron": "^3.1.6",
    "dns-packet": "^5.6.1",
    "dotenv": "^16.4.7",
    "express": "^4.17.1",
    "fastestsmallesttextencoderdecoder": "^1.0.22",
    "fetch-socks": "^1.3.2",
    "http-proxy-middleware": "^3.0.3",
    "ip-address": "^9.0.5",
    "js-base64": "^3.7.2",
    "json5": "^2.2.3",
    "jsrsasign": "^11.1.0",
    "lodash": "^4.17.21",
    "mime-types": "^2.1.35",
    "ms": "^2.1.3",
    "nanoid": "^3.3.3",
    "semver": "^7.6.3",
    "static-js-yaml": "^1.0.0",
    "undici": "^7.4.0"
  },
  "devDependencies": {
    "@babel/core": "^7.18.0",
    "@babel/node": "^7.17.10",
    "@babel/preset-env": "^7.18.0",
    "@babel/register": "^7.17.7",
    "@types/gulp": "^4.0.9",
    "babel-plugin-relative-path-import": "^2.0.1",
    "babelify": "^10.0.0",
    "browser-pack-flat": "^3.4.2",
    "browserify": "^17.0.0",
    "chai": "^4.3.6",
    "esbuild": "^0.19.8",
    "eslint": "^8.16.0",
    "gulp": "^4.0.2",
    "gulp-babel": "^8.0.0",
    "gulp-eslint-new": "^1.4.4",
    "gulp-file": "^0.4.0",
    "gulp-header": "^2.0.9",
    "gulp-prettier": "^4.0.0",
    "gulp-tap": "^2.0.0",
    "mocha": "^10.0.0",
    "nodemon": "^2.0.16",
    "peggy": "^2.0.1",
    "prettier": "2.6.2",
    "prettier-plugin-sort-imports": "^1.6.1",
    "tinyify": "^3.0.0"
  }
}

================================================
FILE: backend/patches/http-proxy@1.18.1.patch
================================================
diff --git a/lib/http-proxy/common.js b/lib/http-proxy/common.js
index 6513e81d80d5250ea249ea833f819ece67897c7e..486d4c896d65a3bb7cf63307af68facb3ddb886b 100644
--- a/lib/http-proxy/common.js
+++ b/lib/http-proxy/common.js
@@ -1,6 +1,5 @@
 var common   = exports,
     url      = require('url'),
-    extend   = require('util')._extend,
     required = require('requires-port');
 
 var upgradeHeader = /(^|,)\s*upgrade\s*($|,)/i,
@@ -40,10 +39,10 @@ common.setupOutgoing = function(outgoing, options, req, forward) {
   );
 
   outgoing.method = options.method || req.method;
-  outgoing.headers = extend({}, req.headers);
+  outgoing.headers = Object.assign({}, req.headers);
 
   if (options.headers){
-    extend(outgoing.headers, options.headers);
+    Object.assign(outgoing.headers, options.headers);
   }
 
   if (options.auth) {
diff --git a/lib/http-proxy/index.js b/lib/http-proxy/index.js
index 977a4b3622b9eaac27689f06347ea4c5173a96cd..88b2d0fcfa03c3aafa47c7e6d38e64412c45a7cc 100644
--- a/lib/http-proxy/index.js
+++ b/lib/http-proxy/index.js
@@ -1,5 +1,4 @@
 var httpProxy = module.exports,
-    extend    = require('util')._extend,
     parse_url = require('url').parse,
     EE3       = require('eventemitter3'),
     http      = require('http'),
@@ -47,9 +46,9 @@ function createRightProxy(type) {
         args[cntr] !== res
       ) {
         //Copy global options
-        requestOptions = extend({}, options);
+        requestOptions = Object.assign({}, options);
         //Overwrite with request options
-        extend(requestOptions, args[cntr]);
+        Object.assign(requestOptions, args[cntr]);
 
         cntr--;
       }


================================================
FILE: backend/src/constants.js
================================================
export const SCHEMA_VERSION_KEY = 'schemaVersion';
export const SETTINGS_KEY = 'settings';
export const SUBS_KEY = 'subs';
export const COLLECTIONS_KEY = 'collections';
export const FILES_KEY = 'files';
export const MODULES_KEY = 'modules';
export const ARTIFACTS_KEY = 'artifacts';
export const RULES_KEY = 'rules';
export const TOKENS_KEY = 'tokens';
export const GIST_BACKUP_KEY = 'Auto Generated Sub-Store Backup';
export const GIST_BACKUP_FILE_NAME = 'Sub-Store';
export const ARTIFACT_REPOSITORY_KEY = 'Sub-Store Artifacts Repository';
export const RESOURCE_CACHE_KEY = '#sub-store-cached-resource';
export const HEADERS_RESOURCE_CACHE_KEY = '#sub-store-cached-headers-resource';
export const SCRIPT_RESOURCE_CACHE_KEY = '#sub-store-cached-script-resource';
export const DEFAULT_CACHE_TTL = 60 * 60 * 1000; // 1 hour
export const DEFAULT_HEADERS_CACHE_TTL = 60 * 1000; // 1 min
export const DEFAULT_SCRIPT_CACHE_TTL = 48 * 3600 * 1000; // 48 hours


================================================
FILE: backend/src/core/app.js
================================================
import 'fastestsmallesttextencoderdecoder';
import { OpenAPI } from '@/vendor/open-api';

const $ = new OpenAPI('sub-store');
export default $;


================================================
FILE: backend/src/core/proxy-utils/index.js
================================================
import { Base64 } from 'js-base64';
import { Buffer } from 'buffer';
import rs from '@/utils/rs';
import YAML from '@/utils/yaml';
import download, { downloadFile } from '@/utils/download';
import {
    isIPv4,
    isIPv6,
    isValidPortNumber,
    isValidUUID,
    isNotBlank,
    ipAddress,
    getRandomPort,
    numberToString,
} from '@/utils';
import PROXY_PROCESSORS, { ApplyProcessor } from './processors';
import PROXY_PREPROCESSORS from './preprocessors';
import PROXY_PRODUCERS from './producers';
import PROXY_PARSERS from './parsers';
import $ from '@/core/app';
import { FILES_KEY, MODULES_KEY } from '@/constants';
import { findByName } from '@/utils/database';
import { produceArtifact } from '@/restful/sync';
import { getFlag, removeFlag, getISO, MMDB } from '@/utils/geo';
import Gist from '@/utils/gist';
import { isPresent } from './producers/utils';
import { doh } from '@/utils/dns';
import JSON5 from 'json5';

function preprocess(raw) {
    for (const processor of PROXY_PREPROCESSORS) {
        try {
            if (processor.test(raw)) {
                $.info(`Pre-processor [${processor.name}] activated`);
                return processor.parse(raw);
            }
        } catch (e) {
            $.error(`Parser [${processor.name}] failed\n Reason: ${e}`);
        }
    }
    return raw;
}

function parse(raw) {
    raw = preprocess(raw);
    // parse
    const lines = raw.split('\n');
    const proxies = [];
    let lastParser;

    for (let line of lines) {
        line = line.trim();
        if (line.length === 0) continue; // skip empty line
        let success = false;

        // try to parse with last used parser
        if (lastParser) {
            const [proxy, error] = tryParse(lastParser, line);
            if (!error) {
                proxies.push(lastParse(proxy));
                success = true;
            }
        }

        if (!success) {
            // search for a new parser
            for (const parser of PROXY_PARSERS) {
                const [proxy, error] = tryParse(parser, line);
                if (!error) {
                    proxies.push(lastParse(proxy));
                    lastParser = parser;
                    success = true;
                    $.info(`${parser.name} is activated`);
                    break;
                }
            }
        }

        if (!success) {
            $.error(`Failed to parse line: ${line}`);
        }
    }
    return proxies.filter((proxy) => {
        if (['vless', 'vmess'].includes(proxy.type)) {
            const isProxyUUIDValid = isValidUUID(proxy.uuid);
            if (!isProxyUUIDValid) {
                $.info(`UUID may be invalid: ${proxy.name} ${proxy.uuid}`);
            }
            // return isProxyUUIDValid;
        }
        return true;
    });
}

async function processFn(
    proxies,
    operators = [],
    targetPlatform,
    source,
    $options,
) {
    let context = {};
    for (const item of operators) {
        if (item.disabled) {
            $.log(
                `Skipping disabled operator: "${
                    item.type
                }" with arguments:\n >>> ${
                    JSON.stringify(item.args, null, 2) || 'None'
                }`,
            );
            continue;
        }
        // process script
        let script;
        let $arguments = {};
        if (item.type.indexOf('Script') !== -1) {
            const { mode, content } = item.args;
            if (mode === 'link') {
                let url = content || '';
                // extract link arguments
                const rawArgs = url.split('#');
                if (rawArgs.length > 1) {
                    try {
                        // 支持 `#${encodeURIComponent(JSON.stringify({arg1: "1"}))}`
                        $arguments = JSON.parse(decodeURIComponent(rawArgs[1]));
                    } catch (e) {
                        for (const pair of rawArgs[1].split('&')) {
                            const key = pair.split('=')[0];
                            const value = pair.split('=')[1];
                            // 部分兼容之前的逻辑 const value = pair.split('=')[1] || true;
                            $arguments[key] =
                                value == null || value === ''
                                    ? true
                                    : decodeURIComponent(value);
                        }
                    }
                }
                console.log(rawArgs);
                url = `${url.split('#')[0]}${
                    rawArgs[2]
                        ? `#${rawArgs[2]}`
                        : $arguments?.noCache != null ||
                          $arguments?.insecure != null
                        ? `#${rawArgs[1]}`
                        : ''
                }`;
                const downloadUrlMatch = url
                    .split('#')[0]
                    .match(/^\/api\/(file|module)\/(.+)/);
                if (downloadUrlMatch) {
                    let type = '';
                    try {
                        type = downloadUrlMatch?.[1];
                        let name = downloadUrlMatch?.[2];
                        if (name == null) {
                            throw new Error(`本地 ${type} URL 无效: ${url}`);
                        }
                        name = decodeURIComponent(name);
                        const key = type === 'module' ? MODULES_KEY : FILES_KEY;
                        const item = findByName($.read(key), name);
                        if (!item) {
                            throw new Error(`找不到 ${type}: ${name}`);
                        }

                        if (type === 'module') {
                            script = item.content;
                        } else {
                            script = await produceArtifact({
                                type: 'file',
                                name,
                            });
                        }
                    } catch (err) {
                        $.error(
                            `Error when loading ${type}: ${item.args.content}.\n Reason: ${err}`,
                        );
                        throw new Error(`无法加载 ${type}: ${url}`);
                    }
                } else if (url?.startsWith('/')) {
                    try {
                        const fs = eval(`require("fs")`);
                        script = fs.readFileSync(url.split('#')[0], 'utf8');
                        // $.info(`Script loaded: >>>\n ${script}`);
                    } catch (err) {
                        $.error(
                            `Error when reading local script: ${item.args.content}.\n Reason: ${err}`,
                        );
                        throw new Error(`无法从该路径读取脚本文件: ${url}`);
                    }
                } else {
                    // if this is a remote script, download it
                    try {
                        script = await download(url);
                        // $.info(`Script loaded: >>>\n ${script}`);
                    } catch (err) {
                        $.error(
                            `Error when downloading remote script: ${item.args.content}.\n Reason: ${err}`,
                        );
                        throw new Error(`无法下载脚本: ${url}`);
                    }
                }
            } else {
                script = content;
                $arguments = item.args.arguments || {};
            }
        }

        if (!PROXY_PROCESSORS[item.type]) {
            $.error(`Unknown operator: "${item.type}"`);
            continue;
        }

        $.log(
            `Applying "${item.type}" with arguments:\n >>> ${
                JSON.stringify(item.args, null, 2) || 'None'
            }`,
        );
        let processor;
        if (item.type.indexOf('Script') !== -1) {
            processor = PROXY_PROCESSORS[item.type](
                script,
                targetPlatform,
                $arguments,
                source,
                $options,
                context,
            );
        } else {
            processor = PROXY_PROCESSORS[item.type](item.args || {});
        }
        proxies = await ApplyProcessor(processor, proxies);
    }
    return proxies;
}

function produce(proxies, targetPlatform, type, opts = {}) {
    const producer = PROXY_PRODUCERS[targetPlatform];
    if (!producer) {
        throw new Error(`Target platform: ${targetPlatform} is not supported!`);
    }

    const sni_off_supported = /Surge|SurgeMac|Shadowrocket/i.test(
        targetPlatform,
    );

    // filter unsupported proxies
    proxies = proxies.filter((proxy) => {
        // 检查代理是否支持目标平台
        if (proxy.supported && proxy.supported[targetPlatform] === false) {
            return false;
        }

        // 对于 vless 和 vmess 代理,需要额外验证 UUID
        if (['vless', 'vmess'].includes(proxy.type)) {
            const isProxyUUIDValid = isValidUUID(proxy.uuid);
            if (!isProxyUUIDValid)
                $.info(`UUID may be invalid: ${proxy.name} ${proxy.uuid}`);
            // return isProxyUUIDValid;
        }

        return true;
    });

    proxies = proxies.map((proxy) => {
        proxy._resolved = proxy.resolved;

        if (!isNotBlank(proxy.name)) {
            proxy.name = `${proxy.type} ${proxy.server}:${proxy.port}`;
        }
        if (proxy['disable-sni']) {
            if (sni_off_supported) {
                proxy.sni = 'off';
            } else if (!['tuic'].includes(proxy.type)) {
                $.error(
                    `Target platform ${targetPlatform} does not support sni off. Proxy's fields (sni, tls-fingerprint and skip-cert-verify) will be modified.`,
                );
                proxy.sni = '';
                proxy['skip-cert-verify'] = true;
                delete proxy['tls-fingerprint'];
            }
        }

        // 处理 端口跳跃
        if (proxy.ports) {
            proxy.ports = String(proxy.ports);
            if (!['ClashMeta'].includes(targetPlatform)) {
                proxy.ports = proxy.ports.replace(/\//g, ',');
            }
            if (!proxy.port) {
                proxy.port = getRandomPort(proxy.ports);
            }
        }

        return proxy;
    });

    $.log(`Producing proxies for target: ${targetPlatform}`);
    if (typeof producer.type === 'undefined' || producer.type === 'SINGLE') {
        let list = proxies
            .map((proxy) => {
                try {
                    return producer.produce(proxy, type, opts);
                } catch (err) {
                    $.error(
                        `Cannot produce proxy: ${JSON.stringify(
                            proxy,
                            null,
                            2,
                        )}\nReason: ${err}`,
                    );
                    return '';
                }
            })
            .filter((line) => line.length > 0);
        list = type === 'internal' ? list : list.join('\n');
        if (
            targetPlatform.startsWith('Surge') &&
            proxies.length > 0 &&
            proxies.every((p) => p.type === 'wireguard')
        ) {
            list = `#!name=${proxies[0]?._subName}
#!desc=${proxies[0]?._desc ?? ''}
#!category=${proxies[0]?._category ?? ''}
${list}`;
        }
        return list;
    } else if (producer.type === 'ALL') {
        return producer.produce(proxies, type, opts);
    }
}

export const ProxyUtils = {
    parse,
    process: processFn,
    produce,
    ipAddress,
    getRandomPort,
    isIPv4,
    isIPv6,
    isIP,
    yaml: YAML,
    getFlag,
    removeFlag,
    getISO,
    MMDB,
    Gist,
    download,
    downloadFile,
    isValidUUID,
    doh,
    Buffer,
    Base64,
    JSON5,
};

function tryParse(parser, line) {
    if (!safeMatch(parser, line)) return [null, new Error('Parser mismatch')];
    try {
        const proxy = parser.parse(line);
        return [proxy, null];
    } catch (err) {
        return [null, err];
    }
}

function safeMatch(parser, line) {
    try {
        return parser.test(line);
    } catch (err) {
        return false;
    }
}

function formatTransportPath(path) {
    if (typeof path === 'string' || typeof path === 'number') {
        path = String(path).trim();

        if (path === '') {
            return '/';
        } else if (!path.startsWith('/')) {
            return '/' + path;
        }
    }
    return path;
}

function lastParse(proxy) {
    if (typeof proxy.cipher === 'string') {
        proxy.cipher = proxy.cipher.toLowerCase();
    }
    if (typeof proxy.password === 'number') {
        proxy.password = numberToString(proxy.password);
    }
    if (
        ['ss'].includes(proxy.type) &&
        proxy.cipher === 'none' &&
        !proxy.password
    ) {
        // https://github.com/MetaCubeX/mihomo/issues/1677
        proxy.password = '';
    }
    if (proxy.interface) {
        proxy['interface-name'] = proxy.interface;
        delete proxy.interface;
    }
    if (isValidPortNumber(proxy.port)) {
        proxy.port = parseInt(proxy.port, 10);
    }
    if (proxy.server) {
        proxy.server = `${proxy.server}`
            .trim()
            .replace(/^\[/, '')
            .replace(/\]$/, '');
    }
    if (proxy.network === 'ws') {
        if (!proxy['ws-opts'] && (proxy['ws-path'] || proxy['ws-headers'])) {
            proxy['ws-opts'] = {};
            if (proxy['ws-path']) {
                proxy['ws-opts'].path = proxy['ws-path'];
            }
            if (proxy['ws-headers']) {
                proxy['ws-opts'].headers = proxy['ws-headers'];
            }
        }
        delete proxy['ws-path'];
        delete proxy['ws-headers'];
    }

    const transportPath = proxy[`${proxy.network}-opts`]?.path;

    if (Array.isArray(transportPath)) {
        proxy[`${proxy.network}-opts`].path = transportPath.map((item) =>
            formatTransportPath(item),
        );
    } else if (transportPath != null) {
        proxy[`${proxy.network}-opts`].path =
            formatTransportPath(transportPath);
    }

    // network 逻辑有点乱了 可能还牵扯到别的逻辑 以后再优化...
    // 以 mihomo 为准的话, 其实应该是
    // network¶
    // 传输层,支持 ws/grpc,不配置或配置其他值则为 tcp
    if (proxy.type === 'trojan') {
        proxy.network = proxy.network || 'tcp';
    }
    // network¶
    // 传输层,支持 ws/http/h2/grpc,不配置或配置其他值则为 tcp
    if (['vmess'].includes(proxy.type)) {
        proxy.network = proxy.network || 'tcp';

        proxy.cipher = proxy.cipher || 'none';
        proxy.alterId = proxy.alterId || 0;
    }
    // network¶
    // 传输层,支持 ws/http/h2/grpc,不配置或配置其他值则为 tcp
    if (['vless'].includes(proxy.type)) {
        proxy.network = proxy.network || 'tcp';
    }
    if (
        [
            'trojan',
            'tuic',
            'hysteria',
            'hysteria2',
            'juicity',
            'anytls',
            'trusttunnel',
            'naive',
        ].includes(proxy.type)
    ) {
        proxy.tls = true;
    }
    if (proxy.network) {
        let transportHost = proxy[`${proxy.network}-opts`]?.headers?.Host;
        let transporthost = proxy[`${proxy.network}-opts`]?.headers?.host;
        if (proxy.network === 'h2') {
            if (!transporthost && transportHost) {
                proxy[`${proxy.network}-opts`].headers.host = transportHost;
                delete proxy[`${proxy.network}-opts`].headers.Host;
            }
        } else if (transporthost && !transportHost) {
            proxy[`${proxy.network}-opts`].headers.Host = transporthost;
            delete proxy[`${proxy.network}-opts`].headers.host;
        }
    }
    if (proxy.network === 'h2') {
        const host = proxy['h2-opts']?.headers?.host;
        const path = proxy['h2-opts']?.path;
        if (host && !Array.isArray(host)) {
            proxy['h2-opts'].headers.host = [host];
        }
        if (Array.isArray(path)) {
            proxy['h2-opts'].path = path[0];
        }
    }

    // 非 tls, 有 ws/http 传输层, 使用域名的节点, 将设置传输层 Host 防止之后域名解析后丢失域名(不覆盖现有的 Host)
    if (
        !proxy.tls &&
        ['ws', 'http'].includes(proxy.network) &&
        !proxy[`${proxy.network}-opts`]?.headers?.Host &&
        !isIP(proxy.server)
    ) {
        proxy[`${proxy.network}-opts`] = proxy[`${proxy.network}-opts`] || {};
        proxy[`${proxy.network}-opts`].headers =
            proxy[`${proxy.network}-opts`].headers || {};
        proxy[`${proxy.network}-opts`].headers.Host =
            ['vmess', 'vless'].includes(proxy.type) && proxy.network === 'http'
                ? [proxy.server]
                : proxy.server;
    }
    // 统一将 VMess 和 VLESS 的 http 传输层的 path 和 Host 处理为数组
    if (['vmess', 'vless'].includes(proxy.type) && proxy.network === 'http') {
        let transportPath = proxy[`${proxy.network}-opts`]?.path;
        let transportHost = proxy[`${proxy.network}-opts`]?.headers?.Host;
        if (transportHost && !Array.isArray(transportHost)) {
            proxy[`${proxy.network}-opts`].headers.Host = [transportHost];
        }
        if (transportPath && !Array.isArray(transportPath)) {
            proxy[`${proxy.network}-opts`].path = [transportPath];
        }
    }
    if (proxy.tls && !proxy.sni) {
        if (!isIP(proxy.server)) {
            proxy.sni = proxy.server;
        }
        if (!proxy.sni && proxy.network) {
            let transportHost = proxy[`${proxy.network}-opts`]?.headers?.Host;
            transportHost = Array.isArray(transportHost)
                ? transportHost[0]
                : transportHost;
            if (transportHost) {
                proxy.sni = transportHost;
            }
        }
    }
    // if (['hysteria', 'hysteria2', 'tuic'].includes(proxy.type)) {
    if (proxy.ports) {
        proxy.ports = String(proxy.ports).replace(/\//g, ',');
    } else {
        delete proxy.ports;
    }
    // }
    if (
        ['hysteria2'].includes(proxy.type) &&
        proxy.obfs &&
        !['salamander'].includes(proxy.obfs) &&
        !proxy['obfs-password']
    ) {
        proxy['obfs-password'] = proxy.obfs;
        proxy.obfs = 'salamander';
    }
    if (
        ['hysteria2'].includes(proxy.type) &&
        !proxy['obfs-password'] &&
        proxy['obfs_password']
    ) {
        proxy['obfs-password'] = proxy['obfs_password'];
        delete proxy['obfs_password'];
    }
    if (['vless'].includes(proxy.type)) {
        // 删除 reality-opts: {}
        if (
            proxy['reality-opts'] &&
            Object.keys(proxy['reality-opts']).length === 0
        ) {
            delete proxy['reality-opts'];
        }
        // 删除 grpc-opts: {}
        if (
            proxy['grpc-opts'] &&
            Object.keys(proxy['grpc-opts']).length === 0
        ) {
            delete proxy['grpc-opts'];
        }
        // 非 reality, 空 flow 没有意义
        if (
            (!proxy['reality-opts'] && !proxy.flow) ||
            ['null', null].includes(proxy.flow)
        ) {
            delete proxy.flow;
        }
        if (['http'].includes(proxy.network)) {
            let transportPath = proxy[`${proxy.network}-opts`]?.path;
            if (!transportPath) {
                if (!proxy[`${proxy.network}-opts`]) {
                    proxy[`${proxy.network}-opts`] = {};
                }
                proxy[`${proxy.network}-opts`].path = ['/'];
            }
        }
    }

    if (typeof proxy.name !== 'string') {
        if (/^\d+$/.test(proxy.name)) {
            proxy.name = `${proxy.name}`;
        } else {
            try {
                if (proxy.name?.data) {
                    proxy.name = Buffer.from(proxy.name.data).toString('utf8');
                } else {
                    proxy.name = Buffer.from(proxy.name).toString('utf8');
                }
            } catch (e) {
                $.error(`proxy.name decode failed\nReason: ${e}`);
                proxy.name = `${proxy.type} ${proxy.server}:${proxy.port}`;
            }
        }
    }
    if (['ws', 'http', 'h2'].includes(proxy.network)) {
        if (
            ['ws', 'h2'].includes(proxy.network) &&
            !proxy[`${proxy.network}-opts`]?.path
        ) {
            proxy[`${proxy.network}-opts`] =
                proxy[`${proxy.network}-opts`] || {};
            proxy[`${proxy.network}-opts`].path = '/';
        } else if (
            proxy.network === 'http' &&
            (!Array.isArray(proxy[`${proxy.network}-opts`]?.path) ||
                proxy[`${proxy.network}-opts`]?.path.every((i) => !i))
        ) {
            proxy[`${proxy.network}-opts`] =
                proxy[`${proxy.network}-opts`] || {};
            proxy[`${proxy.network}-opts`].path = ['/'];
        }
    }
    if (['', 'off'].includes(proxy.sni)) {
        proxy['disable-sni'] = true;
    }
    let caStr = proxy['ca_str'];
    if (proxy['ca-str']) {
        caStr = proxy['ca-str'];
    } else if (caStr) {
        delete proxy['ca_str'];
        proxy['ca-str'] = caStr;
    }
    try {
        if ($.env.isNode && !caStr && proxy['_ca']) {
            caStr = $.node.fs.readFileSync(proxy['_ca'], {
                encoding: 'utf8',
            });
        }
    } catch (e) {
        $.error(`Read ca file failed\nReason: ${e}`);
    }
    if (!proxy['tls-fingerprint'] && caStr) {
        proxy['tls-fingerprint'] = rs.generateFingerprint(caStr);
    }
    if (
        ['ss'].includes(proxy.type) &&
        isPresent(proxy, 'shadow-tls-password')
    ) {
        proxy.plugin = 'shadow-tls';
        proxy['plugin-opts'] = {
            host: proxy['shadow-tls-sni'],
            password: proxy['shadow-tls-password'],
            version: proxy['shadow-tls-version'],
        };
        delete proxy['shadow-tls-sni'];
        delete proxy['shadow-tls-password'];
        delete proxy['shadow-tls-version'];
    }
    if (['tuic'].includes(proxy.type)) {
        proxy.alpn = Array.isArray(proxy.alpn)
            ? proxy.alpn
            : [proxy.alpn || 'h3'];
        proxy['congestion-controller'] =
            proxy['congestion-controller'] || 'cubic';
        proxy['udp-relay-mode'] = proxy['udp-relay-mode'] || 'native';
    }
    if (['wireguard'].includes(proxy.type)) {
        if (Array.isArray(proxy.peers) && proxy.peers.length > 0) {
            const validPeer =
                proxy.peers.find((peer) => peer.ip && peer.ipv6) ||
                proxy.peers.find((peer) => peer.ip || peer.ipv6);
            if (validPeer) {
                if (!proxy.ip) {
                    proxy.ip = proxy.peers[0]?.ip;
                }
                if (!proxy.ipv6) {
                    proxy.ipv6 = proxy.peers[0]?.ipv6;
                }
            }
        }
        if (proxy.ip?.includes('/')) {
            const [ip] = proxy.ip.split('/');
            if (isIPv4(ip)) {
                proxy.ip = ip;
            }
        }
        if (proxy.ipv6?.includes('/')) {
            const [ip] = proxy.ipv6.split('/');
            if (isIPv6(ip)) {
                proxy.ipv6 = ip;
            }
        }
    }
    return proxy;
}

function isIP(ip) {
    return isIPv4(ip) || isIPv6(ip);
}


================================================
FILE: backend/src/core/proxy-utils/parsers/index.js
================================================
import {
    isIPv4,
    isIPv6,
    getIfNotBlank,
    isPresent,
    isNotBlank,
    getIfPresent,
    getRandomPort,
} from '@/utils';
import getSurgeParser from './peggy/surge';
import getLoonParser from './peggy/loon';
import getQXParser from './peggy/qx';
import getTrojanURIParser from './peggy/trojan-uri';
import $ from '@/core/app';
import JSON5 from 'json5';
import YAML from '@/utils/yaml';
import _ from 'lodash';

import { Base64 } from 'js-base64';

function surge_port_hopping(raw) {
    const [parts, port_hopping] =
        raw.match(
            /,\s*?port-hopping\s*?=\s*?["']?\s*?((\d+(-\d+)?)([,;]\d+(-\d+)?)*)\s*?["']?\s*?/,
        ) || [];
    return {
        port_hopping: port_hopping
            ? port_hopping.replace(/;/g, ',')
            : undefined,
        line: parts ? raw.replace(parts, '') : raw,
    };
}

function URI_PROXY() {
    // socks5+tls
    // socks5
    // http, https(可以这么写)
    const name = 'URI PROXY Parser';
    const test = (line) => {
        return /^(socks5\+tls|socks5|http|https):\/\//.test(line);
    };
    const parse = (line) => {
        // parse url
        // eslint-disable-next-line no-unused-vars
        let [__, type, tls, username, password, server, port, query, name] =
            line.match(
                /^(socks5|http|http)(\+tls|s)?:\/\/(?:(.*?):(.*?)@)?(.*?)(?::(\d+?))?\/?(\?.*?)?(?:#(.*?))?$/,
            );
        if (port) {
            port = parseInt(port, 10);
        } else {
            if (tls) {
                port = 443;
            } else if (type === 'http') {
                port = 80;
            } else {
                $.error(`port is not present in line: ${line}`);
                throw new Error(`port is not present in line: ${line}`);
            }
            $.info(`port is not present in line: ${line}, set to ${port}`);
        }

        const proxy = {
            name:
                name != null
                    ? decodeURIComponent(name)
                    : `${type} ${server}:${port}`,
            type,
            tls: tls ? true : false,
            server,
            port,
            username:
                username != null ? decodeURIComponent(username) : undefined,
            password:
                password != null ? decodeURIComponent(password) : undefined,
        };

        return proxy;
    };
    return { name, test, parse };
}
function URI_SOCKS() {
    const name = 'URI SOCKS Parser';
    const test = (line) => {
        return /^socks:\/\//.test(line);
    };
    const parse = (line) => {
        // parse url
        // eslint-disable-next-line no-unused-vars
        let [__, type, auth, server, port, query, name] = line.match(
            /^(socks)?:\/\/(?:(.*)@)?(.*?)(?::(\d+?))?(\?.*?)?(?:#(.*?))?$/,
        );
        if (port) {
            port = parseInt(port, 10);
        } else {
            $.error(`port is not present in line: ${line}`);
            throw new Error(`port is not present in line: ${line}`);
        }
        let username, password;
        if (auth) {
            const parsed = Base64.decode(decodeURIComponent(auth)).split(':');
            username = parsed[0];
            password = parsed[1];
        }

        const proxy = {
            name:
                name != null
                    ? decodeURIComponent(name)
                    : `${type} ${server}:${port}`,
            type: 'socks5',
            server,
            port,
            username,
            password,
        };

        return proxy;
    };
    return { name, test, parse };
}
// Parse SS URI format (only supports new SIP002, legacy format is depreciated).
// reference: https://github.com/shadowsocks/shadowsocks-org/wiki/SIP002-URI-Scheme
function URI_SS() {
    const name = 'URI SS Parser';
    const test = (line) => {
        return /^ss:\/\//.test(line);
    };
    const parse = (line) => {
        // parse url
        let content = line.split('ss://')[1];

        let name = line.split('#')[1];
        const proxy = {
            type: 'ss',
        };
        content = content.split('#')[0]; // strip proxy name
        // handle IPV4 and IPV6
        let serverAndPortArray = content.match(/@([^/?]*)(\/|\?|$)/);

        let rawUserInfoStr = decodeURIComponent(content.split('@')[0]); // 其实应该分隔之后, 用户名和密码再 decodeURIComponent. 但是问题不大
        let userInfoStr;
        if (rawUserInfoStr?.startsWith('2022-blake3-')) {
            userInfoStr = rawUserInfoStr;
        } else {
            userInfoStr = Base64.decode(rawUserInfoStr);
        }

        let query = '';
        if (!serverAndPortArray) {
            if (content.includes('?')) {
                const parsed = content.match(/^(.*)(\?.*)$/);
                content = parsed[1];
                query = parsed[2];
            }
            content = Base64.decode(content);

            if (query) {
                if (/(&|\?)v2ray-plugin=/.test(query)) {
                    const parsed = query.match(/(&|\?)v2ray-plugin=(.*?)(&|$)/);
                    let v2rayPlugin = parsed[2];
                    if (v2rayPlugin) {
                        proxy.plugin = 'v2ray-plugin';
                        proxy['plugin-opts'] = JSON.parse(
                            Base64.decode(v2rayPlugin),
                        );
                    }
                }
                content = `${content}${query}`;
            }
            userInfoStr = content.match(/(^.*)@/)?.[1];
            serverAndPortArray = content.match(/@([^/@]*)(\/|$)/);
        } else if (content.includes('?')) {
            const parsed = content.match(/(\?.*)$/);
            query = parsed[1];
        }
        const params = {};
        for (const addon of query.replace(/^\?/, '').split('&')) {
            if (addon) {
                const [key, valueRaw] = addon.split('=');
                let value = valueRaw;
                value = decodeURIComponent(valueRaw);
                params[key] = value;
            }
        }
        proxy.tls = params.security && params.security !== 'none';
        proxy['skip-cert-verify'] = !!params['allowInsecure'];
        proxy.sni = params['sni'] || params['peer'];
        proxy['client-fingerprint'] = params.fp;
        proxy.alpn = params.alpn
            ? decodeURIComponent(params.alpn).split(',')
            : undefined;

        if (params['ws']) {
            proxy.network = 'ws';
            _.set(proxy, 'ws-opts.path', params['wspath']);
        }

        if (params['type']) {
            let httpupgrade;
            proxy.network = params['type'];
            if (proxy.network === 'httpupgrade') {
                proxy.network = 'ws';
                httpupgrade = true;
            }
            if (['grpc'].includes(proxy.network)) {
                proxy[proxy.network + '-opts'] = {
                    'grpc-service-name': params['serviceName'],
                    '_grpc-type': params['mode'],
                    '_grpc-authority': params['authority'],
                };
            } else {
                if (params['path']) {
                    _.set(
                        proxy,
                        proxy.network + '-opts.path',
                        decodeURIComponent(params['path']),
                    );
                }
                if (params['host']) {
                    _.set(
                        proxy,
                        proxy.network + '-opts.headers.Host',
                        decodeURIComponent(params['host']),
                    );
                }
                if (httpupgrade) {
                    _.set(
                        proxy,
                        proxy.network + '-opts.v2ray-http-upgrade',
                        true,
                    );
                    _.set(
                        proxy,
                        proxy.network + '-opts.v2ray-http-upgrade-fast-open',
                        true,
                    );
                }
            }
            if (['reality'].includes(params.security)) {
                const opts = {};
                if (params.pbk) {
                    opts['public-key'] = params.pbk;
                }
                if (params.sid) {
                    opts['short-id'] = params.sid;
                }
                if (params.spx) {
                    opts['_spider-x'] = params.spx;
                }
                if (params.mode) {
                    proxy._mode = params.mode;
                }
                if (params.extra) {
                    proxy._extra = params.extra;
                }
                if (Object.keys(opts).length > 0) {
                    _.set(proxy, params.security + '-opts', opts);
                }
            }
        }

        proxy.udp = !!params['udp'];

        const serverAndPort = serverAndPortArray[1];
        const portIdx = serverAndPort.lastIndexOf(':');
        proxy.server = serverAndPort.substring(0, portIdx);
        proxy.port = `${serverAndPort.substring(portIdx + 1)}`.match(
            /\d+/,
        )?.[0];
        let userInfo = userInfoStr.match(/(^.*?):(.*$)/);
        proxy.cipher = userInfo?.[1];
        proxy.password = userInfo?.[2];
        // if (!proxy.cipher || !proxy.password) {
        //     userInfo = rawUserInfoStr.match(/(^.*?):(.*$)/);
        //     proxy.cipher = userInfo?.[1];
        //     proxy.password = userInfo?.[2];
        // }

        // handle obfs
        const pluginMatch = content.match(/[?&]plugin=([^&]+)/);
        const shadowTlsMatch = content.match(/[?&]shadow-tls=([^&]+)/);

        if (pluginMatch) {
            const pluginInfo = (
                'plugin=' + decodeURIComponent(pluginMatch[1])
            ).split(';');
            const params = {};
            for (const item of pluginInfo) {
                const [key, val] = item.split('=');
                if (key) params[key] = val || true; // some options like "tls" will not have value
            }
            switch (params.plugin) {
                case 'obfs-local':
                case 'simple-obfs':
                    proxy.plugin = 'obfs';
                    proxy['plugin-opts'] = {
                        mode: params.obfs,
                        host: getIfNotBlank(params['obfs-host']),
                    };
                    break;
                case 'v2ray-plugin':
                    proxy.plugin = 'v2ray-plugin';
                    proxy['plugin-opts'] = {
                        mode: 'websocket',
                        host:
                            getIfNotBlank(params['obfs-host']) ||
                            getIfNotBlank(params['host']),
                        path: getIfNotBlank(params.path),
                        tls: getIfPresent(params.tls),
                    };
                    break;
                case 'shadow-tls': {
                    proxy.plugin = 'shadow-tls';
                    const version = getIfNotBlank(params['version']);
                    proxy['plugin-opts'] = {
                        host: getIfNotBlank(params['host']),
                        password: getIfNotBlank(params['password']),
                        version: version ? parseInt(version, 10) : undefined,
                    };
                    break;
                }
                default:
                    throw new Error(
                        `Unsupported plugin option: ${params.plugin}`,
                    );
            }
        }
        // Shadowrocket
        if (shadowTlsMatch) {
            const params = JSON.parse(Base64.decode(shadowTlsMatch[1]));
            const version = getIfNotBlank(params['version']);
            const address = getIfNotBlank(params['address']);
            const port = getIfNotBlank(params['port']);
            proxy.plugin = 'shadow-tls';
            proxy['plugin-opts'] = {
                host: getIfNotBlank(params['host']),
                password: getIfNotBlank(params['password']),
                version: version ? parseInt(version, 10) : undefined,
            };
            if (address) {
                proxy.server = address;
            }
            if (port) {
                proxy.port = parseInt(port, 10);
            }
        }
        if (/(&|\?)uot=(1|true)/i.test(query)) {
            proxy['udp-over-tcp'] = true;
        }
        if (/(&|\?)tfo=(1|true)/i.test(query)) {
            proxy.tfo = true;
        }
        if (name != null) {
            name = decodeURIComponent(name);
        }
        proxy.name = name ?? `SS ${proxy.server}:${proxy.port}`;
        return proxy;
    };
    return { name, test, parse };
}

// Parse URI SSR format, such as ssr://xxx
function URI_SSR() {
    const name = 'URI SSR Parser';
    const test = (line) => {
        return /^ssr:\/\//.test(line);
    };
    const parse = (line) => {
        line = Base64.decode(line.split('ssr://')[1]);

        // handle IPV6 & IPV4 format
        let splitIdx = line.indexOf(':origin');
        if (splitIdx === -1) {
            splitIdx = line.indexOf(':auth_');
        }
        const serverAndPort = line.substring(0, splitIdx);
        const server = serverAndPort.substring(
            0,
            serverAndPort.lastIndexOf(':'),
        );
        const port = serverAndPort.substring(
            serverAndPort.lastIndexOf(':') + 1,
        );

        let params = line
            .substring(splitIdx + 1)
            .split('/?')[0]
            .split(':');
        let proxy = {
            type: 'ssr',
            server,
            port,
            protocol: params[0],
            cipher: params[1],
            obfs: params[2],
            password: Base64.decode(params[3]),
        };
        // get other params
        const other_params = {};
        line = line.split('/?')[1].split('&');
        if (line.length > 1) {
            for (const item of line) {
                let [key, val] = item.split('=');
                val = val.trim();
                if (val.length > 0 && val !== '(null)') {
                    other_params[key] = val;
                }
            }
        }
        proxy = {
            ...proxy,
            name: other_params.remarks
                ? Base64.decode(other_params.remarks)
                : proxy.server,
            'protocol-param': getIfNotBlank(
                Base64.decode(other_params.protoparam || '').replace(/\s/g, ''),
            ),
            'obfs-param': getIfNotBlank(
                Base64.decode(other_params.obfsparam || '').replace(/\s/g, ''),
            ),
        };
        return proxy;
    };

    return { name, test, parse };
}

// V2rayN URI VMess format
// reference: https://github.com/2dust/v2rayN/wiki/%E5%88%86%E4%BA%AB%E9%93%BE%E6%8E%A5%E6%A0%BC%E5%BC%8F%E8%AF%B4%E6%98%8E(ver-2)

// Quantumult VMess format
function URI_VMess() {
    const name = 'URI VMess Parser';
    const test = (line) => {
        return /^vmess:\/\//.test(line);
    };
    const parse = (line) => {
        line = line.split('vmess://')[1];
        let content = Base64.decode(line.replace(/\?.*?$/, ''));
        if (/=\s*vmess/.test(content)) {
            // Quantumult VMess URI format
            const partitions = content.split(',').map((p) => p.trim());
            // get keyword params
            const params = {};
            for (const part of partitions) {
                if (part.indexOf('=') !== -1) {
                    const [key, val] = part.split('=');
                    params[key.trim()] = val.trim();
                }
            }

            const proxy = {
                name: partitions[0].split('=')[0].trim(),
                type: 'vmess',
                server: partitions[1],
                port: partitions[2],
                cipher: getIfNotBlank(partitions[3], 'auto'),
                uuid: partitions[4].match(/^"(.*)"$/)[1],
                tls: params.obfs === 'wss',
                udp: getIfPresent(params['udp-relay']),
                tfo: getIfPresent(params['fast-open']),
                'skip-cert-verify': isPresent(params['tls-verification'])
                    ? !params['tls-verification']
                    : undefined,
            };

            // handle ws headers
            if (isPresent(params.obfs)) {
                if (params.obfs === 'ws' || params.obfs === 'wss') {
                    proxy.network = 'ws';
                    proxy['ws-opts'].path = (
                        getIfNotBlank(params['obfs-path']) || '"/"'
                    ).match(/^"(.*)"$/)[1];
                    let obfs_host = params['obfs-header'];
                    if (obfs_host && obfs_host.indexOf('Host') !== -1) {
                        obfs_host = obfs_host.match(
                            /Host:\s*([a-zA-Z0-9-.]*)/,
                        )[1];
                    }
                    if (isNotBlank(obfs_host)) {
                        proxy['ws-opts'].headers = {
                            Host: obfs_host,
                        };
                    }
                } else {
                    throw new Error(`Unsupported obfs: ${params.obfs}`);
                }
            }
            return proxy;
        } else {
            let params = {};

            try {
                // V2rayN URI format
                params = JSON.parse(content);
            } catch (e) {
                // Shadowrocket URI format
                // eslint-disable-next-line no-unused-vars
                let [__, base64Line, qs] = /(^[^?]+?)\/?\?(.*)$/.exec(line);
                content = Base64.decode(base64Line);

                for (const addon of qs.split('&')) {
                    const [key, valueRaw] = addon.split('=');
                    let value = valueRaw;
                    value = decodeURIComponent(valueRaw);
                    if (value.indexOf(',') === -1) {
                        params[key] = value;
                    } else {
                        params[key] = value.split(',');
                    }
                }
                // eslint-disable-next-line no-unused-vars
                let [___, cipher, uuid, server, port] =
                    /(^[^:]+?):([^:]+?)@(.*):(\d+)$/.exec(content);

                params.scy = cipher;
                params.id = uuid;
                params.port = port;
                params.add = server;
            }
            const server = params.add;
            const port = parseInt(getIfPresent(params.port), 10);
            const proxy = {
                name:
                    params.ps ??
                    params.remarks ??
                    params.remark ??
                    `VMess ${server}:${port}`,
                type: 'vmess',
                server,
                port,
                // https://github.com/2dust/v2rayN/wiki/Description-of-VMess-share-link
                // https://github.com/XTLS/Xray-core/issues/91
                cipher: [
                    'auto',
                    'aes-128-gcm',
                    'chacha20-poly1305',
                    'none',
                ].includes(params.scy)
                    ? params.scy
                    : 'auto',
                uuid: params.id,
                alterId: parseInt(
                    getIfPresent(params.aid ?? params.alterId, 0),
                    10,
                ),
                tls: ['tls', true, 1, '1'].includes(params.tls),
                'skip-cert-verify': isPresent(params.verify_cert)
                    ? !params.verify_cert
                    : undefined,
            };
            if (!proxy['skip-cert-verify'] && isPresent(params.allowInsecure)) {
                proxy['skip-cert-verify'] = /(TRUE)|1/i.test(
                    params.allowInsecure,
                );
            }
            // https://github.com/2dust/v2rayN/wiki/%E5%88%86%E4%BA%AB%E9%93%BE%E6%8E%A5%E6%A0%BC%E5%BC%8F%E8%AF%B4%E6%98%8E(ver-2)
            if (proxy.tls) {
                if (params.sni && params.sni !== '') {
                    proxy.sni = params.sni;
                } else if (params.peer && params.peer !== '') {
                    proxy.sni = params.peer;
                }
            }
            let httpupgrade = false;
            // handle obfs
            if (params.net === 'ws' || params.obfs === 'websocket') {
                proxy.network = 'ws';
            } else if (
                ['http'].includes(params.net) ||
                ['http'].includes(params.obfs) ||
                ['http'].includes(params.type)
            ) {
                proxy.network = 'http';
            } else if (['grpc', 'kcp', 'quic'].includes(params.net)) {
                proxy.network = params.net;
            } else if (
                params.net === 'httpupgrade' ||
                proxy.network === 'httpupgrade'
            ) {
                proxy.network = 'ws';
                httpupgrade = true;
            } else if (params.net === 'h2' || proxy.network === 'h2') {
                proxy.network = 'h2';
            }
            // 暂不支持 tcp + host + path
            // else if (params.net === 'tcp' || proxy.network === 'tcp') {
            //     proxy.network = 'tcp';
            // }
            if (proxy.network) {
                let transportHost = params.host ?? params.obfsParam;
                try {
                    const parsedObfs = JSON.parse(transportHost);
                    const parsedHost = parsedObfs?.Host;
                    if (parsedHost) {
                        transportHost = parsedHost;
                    }
                    // eslint-disable-next-line no-empty
                } catch (e) {}
                let transportPath = params.path;

                // 补上默认 path
                if (['ws'].includes(proxy.network)) {
                    transportPath = transportPath || '/';
                }

                if (proxy.network === 'http') {
                    if (transportHost) {
                        // 1)http(tcp)->host中间逗号(,)隔开
                        transportHost = transportHost
                            .split(',')
                            .map((i) => i.trim());
                        transportHost = Array.isArray(transportHost)
                            ? transportHost[0]
                            : transportHost;
                    }
                    if (transportPath) {
                        transportPath = Array.isArray(transportPath)
                            ? transportPath[0]
                            : transportPath;
                    } else {
                        transportPath = '/';
                    }
                }
                // 传输层应该有配置, 暂时不考虑兼容不给配置的节点
                if (
                    transportPath ||
                    transportHost ||
                    ['kcp', 'quic'].includes(proxy.network)
                ) {
                    if (['grpc'].includes(proxy.network)) {
                        proxy[`${proxy.network}-opts`] = {
                            'grpc-service-name': getIfNotBlank(transportPath),
                            '_grpc-type': getIfNotBlank(params.type),
                            '_grpc-authority': getIfNotBlank(params.authority),
                        };
                    } else if (['kcp', 'quic'].includes(proxy.network)) {
                        proxy[`${proxy.network}-opts`] = {
                            [`_${proxy.network}-type`]: getIfNotBlank(
                                params.type,
                            ),
                            [`_${proxy.network}-host`]: getIfNotBlank(
                                getIfNotBlank(transportHost),
                            ),
                            [`_${proxy.network}-path`]:
                                getIfNotBlank(transportPath),
                        };
                    } else {
                        const opts = {
                            path: getIfNotBlank(transportPath),
                            headers: { Host: getIfNotBlank(transportHost) },
                        };
                        if (httpupgrade) {
                            opts['v2ray-http-upgrade'] = true;
                            opts['v2ray-http-upgrade-fast-open'] = true;
                        }
                        proxy[`${proxy.network}-opts`] = opts;
                    }
                } else {
                    delete proxy.network;
                }
            }

            proxy['client-fingerprint'] = params.fp;
            proxy.alpn = params.alpn ? params.alpn.split(',') : undefined;
            // 然而 wiki 和 app 实测中都没有字段表示这个
            // proxy['skip-cert-verify'] = /(TRUE)|1/i.test(params.allowInsecure);

            return proxy;
        }
    };
    return { name, test, parse };
}

function URI_VLESS() {
    const name = 'URI VLESS Parser';
    const test = (line) => {
        return /^vless:\/\//.test(line);
    };
    const parse = (line) => {
        line = line.split('vless://')[1];
        let isShadowrocket;
        let parsed = /^(.*?)@(.*?):(\d+)\/?(\?(.*?))?(?:#(.*?))?$/.exec(line);
        if (!parsed) {
            // eslint-disable-next-line no-unused-vars
            let [_, base64, other] = /^(.*?)(\?.*?$)/.exec(line);
            line = `${Base64.decode(base64)}${other}`;
            parsed = /^(.*?)@(.*?):(\d+)\/?(\?(.*?))?(?:#(.*?))?$/.exec(line);
            isShadowrocket = true;
        }
        // eslint-disable-next-line no-unused-vars
        let [__, uuid, server, port, ___, addons = '', name] = parsed;
        if (isShadowrocket) {
            uuid = uuid.replace(/^.*?:/g, '');
        }

        port = parseInt(`${port}`, 10);
        uuid = decodeURIComponent(uuid);
        if (name != null) {
            name = decodeURIComponent(name);
        }

        const proxy = {
            type: 'vless',
            name,
            server,
            port,
            uuid,
        };
        const params = {};
        for (const addon of addons.split('&')) {
            if (addon) {
                const [key, valueRaw] = addon.split('=');
                let value = valueRaw;
                value = decodeURIComponent(valueRaw);
                params[key] = value;
            }
        }

        proxy.name =
            name ??
            params.remarks ??
            params.remark ??
            `VLESS ${server}:${port}`;

        proxy.tls = params.security && params.security !== 'none';
        if (isShadowrocket && /TRUE|1/i.test(params.tls)) {
            proxy.tls = true;
            params.security = params.security ?? 'reality';
        }
        proxy.sni = params.sni || params.peer;
        proxy.flow = params.flow;
        if (!proxy.flow && isShadowrocket && params.xtls) {
            // "none" is undefined
            const flow = [undefined, 'xtls-rprx-direct', 'xtls-rprx-vision'][
                params.xtls
            ];
            if (flow) {
                proxy.flow = flow;
            }
        }
        proxy['client-fingerprint'] = params.fp;
        proxy.alpn = params.alpn ? params.alpn.split(',') : undefined;
        proxy['skip-cert-verify'] = /(TRUE)|1/i.test(params.allowInsecure);
        proxy._echConfigList = getIfPresent(params.ech);
        proxy._pcs = getIfPresent(params.pcs);
        proxy._h2 = /(TRUE)|1/i.test(params.h2);

        if (['reality'].includes(params.security)) {
            const opts = {};
            if (params.pbk) {
                opts['public-key'] = params.pbk;
            }
            if (params.sid) {
                opts['short-id'] = params.sid;
            }
            if (params.spx) {
                opts['_spider-x'] = params.spx;
            }
            if (Object.keys(opts).length > 0) {
                // proxy[`${params.security}-opts`] = opts;
                proxy[`${params.security}-opts`] = opts;
            }
        }
        let httpupgrade = false;
        proxy.network = params.type;
        if (proxy.network === 'tcp' && params.headerType === 'http') {
            proxy.network = 'http';
        } else if (proxy.network === 'httpupgrade') {
            proxy.network = 'ws';
            httpupgrade = true;
        }
        if (!proxy.network && isShadowrocket && params.obfs) {
            proxy.network = params.obfs;
            if (['none'].includes(proxy.network)) {
                proxy.network = 'tcp';
            }
        }
        if (['websocket'].includes(proxy.network)) {
            proxy.network = 'ws';
        }

        if (proxy.network && !['tcp', 'none'].includes(proxy.network)) {
            const opts = {};
            const host = params.host ?? params.obfsParam;
            if (host) {
                if (params.obfsParam) {
                    try {
                        const parsed = JSON.parse(host);
                        opts.headers = parsed;
                    } catch (e) {
                        opts.headers = { Host: host };
                    }
                } else {
                    opts.headers = { Host: host };
                }
            }
            if (params.serviceName) {
                opts[`${proxy.network}-service-name`] = params.serviceName;
                if (['grpc'].includes(proxy.network) && params.authority) {
                    opts['_grpc-authority'] = params.authority;
                }
            } else if (isShadowrocket && params.path) {
                if (!['ws', 'http', 'h2'].includes(proxy.network)) {
                    opts[`${proxy.network}-service-name`] = params.path;
                    delete params.path;
                }
            }
            if (params.path) {
                opts.path = params.path;
            }
            // https://github.com/XTLS/Xray-core/issues/91
            if (['grpc'].includes(proxy.network)) {
                opts['_grpc-type'] = params.mode || 'gun';
            }
            if (httpupgrade) {
                opts['v2ray-http-upgrade'] = true;
                opts['v2ray-http-upgrade-fast-open'] = true;
            }
            if (Object.keys(opts).length > 0) {
                proxy[`${proxy.network}-opts`] = opts;
            }
            if (proxy.network === 'kcp') {
                // mKCP 种子。省略时不使用种子,但不可以为空字符串。建议 mKCP 用户使用 seed。
                if (params.seed) {
                    proxy.seed = params.seed;
                }
                // mKCP 的伪装头部类型。当前可选值有 none / srtp / utp / wechat-video / dtls / wireguard。省略时默认值为 none,即不使用伪装头部,但不可以为空字符串。
                proxy.headerType = params.headerType || 'none';
            }

            if (params.mode) {
                proxy._mode = params.mode;
            }
            if (params.extra) {
                proxy._extra = params.extra;
            }
        }
        if (params.encryption) {
            proxy.encryption = params.encryption;
        }
        if (params.pqv) {
            proxy._pqv = params.pqv;
        }

        return proxy;
    };
    return { name, test, parse };
}
function URI_AnyTLS() {
    const name = 'URI AnyTLS Parser';
    const test = (line) => {
        return /^anytls:\/\//.test(line);
    };
    const parse = (line) => {
        const parsed = URI_VLESS().parse(line.replace('anytls', 'vless'));
        // 偷个懒
        line = line.split(/anytls:\/\//)[1];
        // eslint-disable-next-line no-unused-vars
        let [__, password, server, port, addons = '', name] =
            /^(.*?)@(.*?)(?::(\d+))?\/?(?:\?(.*?))?(?:#(.*?))?$/.exec(line);
        password = decodeURIComponent(password);
        port = parseInt(`${port}`, 10);
        if (isNaN(port)) {
            port = 443;
        }
        password = decodeURIComponent(password);
        if (name != null) {
            name = decodeURIComponent(name);
        }
        name = name ?? `AnyTLS ${server}:${port}`;

        const proxy = {
            ...parsed,
            uuid: undefined,
            type: 'anytls',
            name,
            server,
            port,
            password,
        };

        for (const addon of addons.split('&')) {
            if (addon) {
                let [key, value] = addon.split('=');
                key = key.replace(/_/g, '-');
                value = decodeURIComponent(value);
                if (['alpn'].includes(key)) {
                    proxy[key] = value ? value.split(',') : undefined;
                } else if (['insecure'].includes(key)) {
                    proxy['skip-cert-verify'] = /(TRUE)|1/i.test(value);
                } else if (['udp'].includes(key)) {
                    proxy[key] = /(TRUE)|1/i.test(value);
                } else if (!Object.keys(proxy).includes(key)) {
                    proxy[key] = value;
                }
            }
        }
        if (['tcp'].includes(proxy.network) && !proxy['reality-opts']) {
            delete proxy.network;
            delete proxy.security;
        }
        return proxy;
    };
    return { name, test, parse };
}
function URI_Hysteria2() {
    const name = 'URI Hysteria2 Parser';
    const test = (line) => {
        return /^(hysteria2|hy2):\/\//.test(line);
    };
    const parse = (line) => {
        line = line.split(/(hysteria2|hy2):\/\//)[2];
        // 端口跳跃有两种写法:
        // 1. 服务器的地址和可选端口。如果省略端口,则默认为 443。
        // 端口部分支持 端口跳跃 的「多端口地址格式」。
        // https://hysteria.network/zh/docs/advanced/Port-Hopping
        // 2. 参数 mport
        let ports;
        /* eslint-disable no-unused-vars */
        let [
            __,
            password,
            server,
            ___,
            port,
            ____,
            _____,
            ______,
            _______,
            ________,
            addons = '',
            name,
        ] = /^(.*?)@(.*?)(:((\d+(-\d+)?)([,;]\d+(-\d+)?)*))?\/?(\?(.*?))?(?:#(.*?))?$/.exec(
            line,
        );

        /* eslint-enable no-unused-vars */
        if (/^\d+$/.test(port)) {
            port = parseInt(`${port}`, 10);
            if (isNaN(port)) {
                port = 443;
            }
        } else if (port) {
            ports = port;
            port = getRandomPort(ports);
        } else {
            port = 443;
        }

        password = decodeURIComponent(password);
        if (name != null) {
            name = decodeURIComponent(name);
        }
        name = name ?? `Hysteria2 ${server}:${port}`;

        const proxy = {
            type: 'hysteria2',
            name,
            server,
            port,
            ports,
            password,
        };

        const params = {};
        for (const addon of addons.split('&')) {
            if (addon) {
                const [key, valueRaw] = addon.split('=');
                let value = valueRaw;
                value = decodeURIComponent(valueRaw);
                params[key] = value;
            }
        }

        proxy.sni = params.sni;
        if (!proxy.sni && params.peer) {
            proxy.sni = params.peer;
        }
        if (params.obfs && params.obfs !== 'none') {
            proxy.obfs = params.obfs;
        }
        if (params.mport) {
            proxy.ports = params.mport;
        }
        proxy['obfs-password'] = params['obfs-password'];
        proxy['skip-cert-verify'] = /(TRUE)|1/i.test(params.insecure);
        proxy.tfo = /(TRUE)|1/i.test(params.fastopen);
        proxy['tls-fingerprint'] = params.pinSHA256;
        let hop_interval = params['hop-interval'] || params['hop_interval'];

        if (/^\d+$/.test(hop_interval)) {
            proxy['hop-interval'] = parseInt(`${hop_interval}`, 10);
        }
        let keepalive = params['keepalive'];

        if (/^\d+$/.test(keepalive)) {
            proxy['keepalive'] = parseInt(`${keepalive}`, 10);
        }

        return proxy;
    };
    return { name, test, parse };
}
function URI_Hysteria() {
    const name = 'URI Hysteria Parser';
    const test = (line) => {
        return /^(hysteria|hy):\/\//.test(line);
    };
    const parse = (line) => {
        line = line.split(/(hysteria|hy):\/\//)[2];
        // eslint-disable-next-line no-unused-vars
        let [__, server, ___, port, ____, addons = '', name] =
            /^(.*?)(:(\d+))?\/?(\?(.*?))?(?:#(.*?))?$/.exec(line);
        port = parseInt(`${port}`, 10);
        if (isNaN(port)) {
            port = 443;
        }
        if (name != null) {
            name = decodeURIComponent(name);
        }
        name = name ?? `Hysteria ${server}:${port}`;

        const proxy = {
            type: 'hysteria',
            name,
            server,
            port,
        };
        const params = {};
        for (const addon of addons.split('&')) {
            if (addon) {
                let [key, value] = addon.split('=');
                key = key.replace(/_/, '-');
                value = decodeURIComponent(value);
                if (['alpn'].includes(key)) {
                    proxy[key] = value ? value.split(',') : undefined;
                } else if (['insecure'].includes(key)) {
                    proxy['skip-cert-verify'] = /(TRUE)|1/i.test(value);
                } else if (['auth'].includes(key)) {
                    proxy['auth-str'] = value;
                } else if (['mport'].includes(key)) {
                    proxy['ports'] = value;
                } else if (['obfsParam'].includes(key)) {
                    proxy['obfs'] = value;
                } else if (['upmbps'].includes(key)) {
                    proxy['up'] = value;
                } else if (['downmbps'].includes(key)) {
                    proxy['down'] = value;
                } else if (['obfs'].includes(key)) {
                    // obfs: Obfuscation mode (optional, empty or "xplus")
                    proxy['_obfs'] = value || '';
                } else if (['fast-open', 'peer'].includes(key)) {
                    params[key] = value;
                } else if (!Object.keys(proxy).includes(key)) {
                    proxy[key] = value;
                }
            }
        }

        if (!proxy.sni && params.peer) {
            proxy.sni = params.peer;
        }
        if (!proxy['fast-open'] && params.fastopen) {
            proxy['fast-open'] = true;
        }
        if (!proxy.protocol) {
            // protocol: protocol to use ("udp", "wechat-video", "faketcp") (optional, default: "udp")
            proxy.protocol = 'udp';
        }

        return proxy;
    };
    return { name, test, parse };
}
function URI_TUIC() {
    const name = 'URI TUIC Parser';
    const test = (line) => {
        return /^tuic:\/\//.test(line);
    };
    const parse = (line) => {
        line = line.split(/tuic:\/\//)[1];
        // eslint-disable-next-line no-unused-vars
        let [__, auth, server, port, addons = '', name] =
            /^(.*?)@(.*?)(?::(\d+))?\/?(?:\?(.*?))?(?:#(.*?))?$/.exec(line);
        auth = decodeURIComponent(auth);
        let [uuid, ...passwordParts] = auth.split(':');
        let password = passwordParts.join(':');
        port = parseInt(`${port}`, 10);
        if (isNaN(port)) {
            port = 443;
        }
        password = decodeURIComponent(password);
        if (name != null) {
            name = decodeURIComponent(name);
        }
        name = name ?? `TUIC ${server}:${port}`;

        const proxy = {
            type: 'tuic',
            name,
            server,
            port,
            password,
            uuid,
        };

        for (const addon of addons.split('&')) {
            if (addon) {
                let [key, value] = addon.split('=');
                key = key.replace(/_/g, '-');
                value = decodeURIComponent(value);
                if (['alpn'].includes(key)) {
                    proxy[key] = value ? value.split(',') : undefined;
                } else if (['allow-insecure', 'insecure'].includes(key)) {
                    proxy['skip-cert-verify'] = /(TRUE)|1/i.test(value);
                } else if (['fast-open'].includes(key)) {
                    proxy.tfo = true;
                } else if (['disable-sni', 'reduce-rtt'].includes(key)) {
                    proxy[key] = /(TRUE)|1/i.test(value);
                } else if (key === 'congestion-control') {
                    proxy['congestion-controller'] = value;
                    delete proxy[key];
                } else if (!Object.keys(proxy).includes(key)) {
                    proxy[key] = value;
                }
            }
        }

        return proxy;
    };
    return { name, test, parse };
}
function URI_WireGuard() {
    const name = 'URI WireGuard Parser';
    const test = (line) => {
        return /^(wireguard|wg):\/\//.test(line);
    };
    const parse = (line) => {
        line = line.split(/(wireguard|wg):\/\//)[2];
        /* eslint-disable no-unused-vars */
        let [
            __,
            ___,
            privateKey,
            server,
            ____,
            port,
            _____,
            addons = '',
            name,
        ] = /^((.*?)@)?(.*?)(:(\d+))?\/?(\?(.*?))?(?:#(.*?))?$/.exec(line);
        /* eslint-enable no-unused-vars */

        port = parseInt(`${port}`, 10);
        if (isNaN(port)) {
            port = 51820;
        }
        privateKey = decodeURIComponent(privateKey);
        if (name != null) {
            name = decodeURIComponent(name);
        }
        name = name ?? `WireGuard ${server}:${port}`;
        const proxy = {
            type: 'wireguard',
            name,
            server,
            port,
            'private-key': privateKey,
            udp: true,
        };
        for (const addon of addons.split('&')) {
            if (addon) {
                let [key, value] = addon.split('=');
                key = key.replace(/_/, '-');
                value = decodeURIComponent(value);
                if (['reserved'].includes(key)) {
                    const parsed = value
                        .split(',')
                        .map((i) => parseInt(i.trim(), 10))
                        .filter((i) => Number.isInteger(i));
                    if (parsed.length === 3) {
                        proxy[key] = parsed;
                    }
                } else if (['address', 'ip'].includes(key)) {
                    value.split(',').map((i) => {
                        const ip = i
                            .trim()
                            .replace(/\/\d+$/, '')
                            .replace(/^\[/, '')
                            .replace(/\]$/, '');
                        if (isIPv4(ip)) {
                            proxy.ip = ip;
                        } else if (isIPv6(ip)) {
                            proxy.ipv6 = ip;
                        }
                    });
                } else if (['mtu'].includes(key)) {
                    const parsed = parseInt(value.trim(), 10);
                    if (Number.isInteger(parsed)) {
                        proxy[key] = parsed;
                    }
                } else if (/publickey/i.test(key)) {
                    proxy['public-key'] = value;
                } else if (/privatekey/i.test(key)) {
                    proxy['private-key'] = value;
                } else if (['udp'].includes(key)) {
                    proxy[key] = /(TRUE)|1/i.test(value);
                } else if (![...Object.keys(proxy), 'flag'].includes(key)) {
                    proxy[key] = value;
                }
            }
        }

        return proxy;
    };
    return { name, test, parse };
}

// Trojan URI format
function URI_Trojan() {
    const name = 'URI Trojan Parser';
    const test = (line) => {
        return /^trojan:\/\//.test(line);
    };

    const parse = (line) => {
        const matched = /^(trojan:\/\/.*?@.*?)(:(\d+))?\/?(\?.*?)?$/.exec(line);
        const port = matched?.[2];
        if (!port) {
            line = line.replace(matched[1], `${matched[1]}:443`);
        }
        let [newLine, name] = line.split(/#(.+)/, 2);
        const parser = getTrojanURIParser();
        const proxy = parser.parse(newLine);
        if (isNotBlank(name)) {
            try {
                proxy.name = decodeURIComponent(name);
            } catch (e) {
                console.log(e);
            }
        }
        return proxy;
    };
    return { name, test, parse };
}

function Clash_All() {
    const name = 'Clash Parser';
    const test = (line) => {
        let proxy;
        try {
            proxy = JSON5.parse(line);
        } catch (e) {
            proxy = YAML.parse(line);
        }
        return !!proxy?.type;
    };
    const parse = (line) => {
        let proxy;
        try {
            proxy = JSON5.parse(line);
        } catch (e) {
            proxy = YAML.parse(line);
        }
        if (
            ![
                'trusttunnel',
                'naive',
                'anytls',
                'mieru',
                'masque',
                'sudoku',
                'juicity',
                'ss',
                'ssr',
                'vmess',
                'socks5',
                'http',
                'snell',
                'trojan',
                'tuic',
                'vless',
                'hysteria',
                'hysteria2',
                'wireguard',
                'ssh',
                'direct',
            ].includes(proxy.type)
        ) {
            throw new Error(
                `Clash does not support proxy with type: ${proxy.type}`,
            );
        }

        // handle vmess sni
        if (['vmess', 'vless'].includes(proxy.type) && proxy.servername) {
            proxy.sni = proxy.servername;
            delete proxy.servername;
        }
        if (proxy['server-cert-fingerprint']) {
            proxy['tls-fingerprint'] = proxy['server-cert-fingerprint'];
        }
        if (proxy.fingerprint) {
            proxy['tls-fingerprint'] = proxy.fingerprint;
        }
        if (proxy['dialer-proxy']) {
            proxy['underlying-proxy'] = proxy['dialer-proxy'];
        }

        if (proxy['benchmark-url']) {
            proxy['test-url'] = proxy['benchmark-url'];
        }
        if (proxy['benchmark-timeout']) {
            proxy['test-timeout'] = proxy['benchmark-timeout'];
        }

        return proxy;
    };
    return { name, test, parse };
}

function QX_SS() {
    const name = 'QX SS Parser';
    const test = (line) => {
        return (
            /^shadowsocks\s*=/.test(line.split(',')[0].trim()) &&
            line.indexOf('ssr-protocol') === -1
        );
    };
    const parse = (line) => {
        const parser = getQXParser();
        return parser.parse(line);
    };
    return { name, test, parse };
}

function QX_SSR() {
    const name = 'QX SSR Parser';
    const test = (line) => {
        return (
            /^shadowsocks\s*=/.test(line.split(',')[0].trim()) &&
            line.indexOf('ssr-protocol') !== -1
        );
    };
    const parse = (line) => getQXParser().parse(line);
    return { name, test, parse };
}

function QX_VMess() {
    const name = 'QX VMess Parser';
    const test = (line) => {
        return /^vmess\s*=/.test(line.split(',')[0].trim());
    };
    const parse = (line) => getQXParser().parse(line);
    return { name, test, parse };
}

function QX_VLESS() {
    const name = 'QX VLESS Parser';
    const test = (line) => {
        return /^vless\s*=/.test(line.split(',')[0].trim());
    };
    const parse = (line) => getQXParser().parse(line);
    return { name, test, parse };
}

function QX_Trojan() {
    const name = 'QX Trojan Parser';
    const test = (line) => {
        return /^trojan\s*=/.test(line.split(',')[0].trim());
    };
    const parse = (line) => getQXParser().parse(line);
    return { name, test, parse };
}

function QX_Http() {
    const name = 'QX HTTP Parser';
    const test = (line) => {
        return /^http\s*=/.test(line.split(',')[0].trim());
    };
    const parse = (line) => getQXParser().parse(line);
    return { name, test, parse };
}

function QX_Socks5() {
    const name = 'QX Socks5 Parser';
    const test = (line) => {
        return /^socks5\s*=/.test(line.split(',')[0].trim());
    };
    const parse = (line) => getQXParser().parse(line);
    return { name, test, parse };
}

function Loon_SS() {
    const name = 'Loon SS Parser';
    const test = (line) => {
        return (
            line.split(',')[0].split('=')[1].trim().toLowerCase() ===
            'shadowsocks'
        );
    };
    const parse = (line) => getLoonParser().parse(line);
    return { name, test, parse };
}

function Loon_SSR() {
    const name = 'Loon SSR Parser';
    const test = (line) => {
        return (
            line.split(',')[0].split('=')[1].trim().toLowerCase() ===
            'shadowsocksr'
        );
    };
    const parse = (line) => getLoonParser().parse(line);
    return { name, test, parse };
}

function Loon_VMess() {
    const name = 'Loon VMess Parser';
    const test = (line) => {
        // distinguish between surge vmess
        return (
            /^.*=\s*vmess/i.test(line.split(',')[0]) &&
            line.indexOf('username') === -1
        );
    };
    const parse = (line) => getLoonParser().parse(line);
    return { name, test, parse };
}

function Loon_Vless() {
    const name = 'Loon Vless Parser';
    const test = (line) => {
        return /^.*=\s*vless/i.test(line.split(',')[0]);
    };
    const parse = (line) => getLoonParser().parse(line);
    return { name, test, parse };
}

function Loon_Trojan() {
    const name = 'Loon Trojan Parser';
    const test = (line) => {
        return /^.*=\s*trojan/i.test(line.split(',')[0]);
    };

    const parse = (line) => getLoonParser().parse(line);
    return { name, test, parse };
}
function Loon_AnyTLS() {
    const name = 'Loon AnyTLS Parser';
    const test = (line) => {
        return /^.*=\s*anytls/i.test(line.split(',')[0]);
    };

    const parse = (line) => getLoonParser().parse(line);
    return { name, test, parse };
}
function Loon_Hysteria2() {
    const name = 'Loon Hysteria2 Parser';
    const test = (line) => {
        return /^.*=\s*Hysteria2/i.test(line.split(',')[0]);
    };

    const parse = (line) => getLoonParser().parse(line);
    return { name, test, parse };
}

function Loon_Http() {
    const name = 'Loon HTTP Parser';
    const test = (line) => {
        return /^.*=\s*http/i.test(line.split(',')[0]);
    };

    const parse = (line) => getLoonParser().parse(line);
    return { name, test, parse };
}
function Loon_Socks5() {
    const name = 'Loon SOCKS5 Parser';
    const test = (line) => {
        return /^.*=\s*socks5/i.test(line.split(',')[0]);
    };

    const parse = (line) => getLoonParser().parse(line);
    return { name, test, parse };
}

function Loon_WireGuard() {
    const name = 'Loon WireGuard Parser';
    const test = (line) => {
        return /^.*=\s*wireguard/i.test(line.split(',')[0]);
    };

    const parse = (line) => {
        const name = line.match(
            /(^.*?)\s*?=\s*?wireguard\s*?,.+?\s*?=\s*?.+?/i,
        )?.[1];
        line = line.replace(name, '').replace(/^\s*?=\s*?wireguard\s*/i, '');
        let peers = line.match(
            /,\s*?peers\s*?=\s*?\[\s*?\{\s*?(.+?)\s*?\}\s*?\]/i,
        )?.[1];
        let serverPort = peers.match(
            /(,|^)\s*?endpoint\s*?=\s*?"?(.+?):(\d+)"?\s*?(,|$)/i,
        );
        let server = serverPort?.[2];
        let port = parseInt(serverPort?.[3], 10);
        let mtu = line.match(/(,|^)\s*?mtu\s*?=\s*?"?(\d+?)"?\s*?(,|$)/i)?.[2];
        if (mtu) {
            mtu = parseInt(mtu, 10);
        }
        let keepalive = line.match(
            /(,|^)\s*?keepalive\s*?=\s*?"?(\d+?)"?\s*?(,|$)/i,
        )?.[2];
        if (keepalive) {
            keepalive = parseInt(keepalive, 10);
        }
        let reserved = peers.match(
            /(,|^)\s*?reserved\s*?=\s*?"?(\[\s*?.+?\s*?\])"?\s*?(,|$)/i,
        )?.[2];
        if (reserved) {
            reserved = JSON.parse(reserved);
        }

        let dns;
        let dnsv4 = line.match(/(,|^)\s*?dns\s*?=\s*?"?(.+?)"?\s*?(,|$)/i)?.[2];
        let dnsv6 = line.match(
            /(,|^)\s*?dnsv6\s*?=\s*?"?(.+?)"?\s*?(,|$)/i,
        )?.[2];
        if (dnsv4 || dnsv6) {
            dns = [];
            if (dnsv4) {
                dns.push(dnsv4);
            }
            if (dnsv6) {
                dns.push(dnsv6);
            }
        }
        let allowedIps = peers
            .match(/(,|^)\s*?allowed-ips\s*?=\s*?"(.+?)"\s*?(,|$)/i)?.[2]
            ?.split(',')
            .map((i) => i.trim());
        let preSharedKey = peers.match(
            /(,|^)\s*?preshared-key\s*?=\s*?"?(.+?)"?\s*?(,|$)/i,
        )?.[2];
        let ip = line.match(
            /(,|^)\s*?interface-ip\s*?=\s*?"?(.+?)"?\s*?(,|$)/i,
        )?.[2];
        let ipv6 = line.match(
            /(,|^)\s*?interface-ipv6\s*?=\s*?"?(.+?)"?\s*?(,|$)/i,
        )?.[2];
        let publicKey = peers.match(
            /(,|^)\s*?public-key\s*?=\s*?"?(.+?)"?\s*?(,|$)/i,
        )?.[2];
        // https://github.com/MetaCubeX/mihomo/blob/0404e35be8736b695eae018a08debb175c1f96e6/docs/config.yaml#L717
        const proxy = {
            type: 'wireguard',
            name,
            server,
            port,
            ip,
            ipv6,
            'private-key': line.match(
                /(,|^)\s*?private-key\s*?=\s*?"?(.+?)"?\s*?(,|$)/i,
            )?.[2],
            'public-key': publicKey,
            mtu,
            keepalive,
            reserved,
            'allowed-ips': allowedIps,
            'preshared-key': preSharedKey,
            dns,
            udp: true,
            peers: [
                {
                    server,
                    port,
                    ip,
                    ipv6,
                    'public-key': publicKey,
                    'pre-shared-key': preSharedKey,
                    'allowed-ips': allowedIps,
                    reserved,
                },
            ],
        };

        proxy;
        if (Array.isArray(proxy.dns) && proxy.dns.length > 0) {
            proxy['remote-dns-resolve'] = true;
        }
        return proxy;
    };
    return { name, test, parse };
}

function Surge_Direct() {
    const name = 'Surge Direct Parser';
    const test = (line) => {
        return /^.*=\s*direct/.test(line.split(',')[0]);
    };
    const parse = (line) => getSurgeParser().parse(line);
    return { name, test, parse };
}
function Surge_AnyTLS() {
    const name = 'Surge AnyTLS Parser';
    const test = (line) => {
        return /^.*=\s*anytls/.test(line.split(',')[0]);
    };
    const parse = (line) => getSurgeParser().parse(line);
    return { name, test, parse };
}
function Surge_TrustTunnel() {
    const name = 'Surge TrustTunnel Parser';
    const test = (line) => {
        return /^.*=\s*trust-tunnel/.test(line.split(',')[0]);
    };
    const parse = (line) => getSurgeParser().parse(line);
    return { name, test, parse };
}
function Surge_SSH() {
    const name = 'Surge SSH Parser';
    const test = (line) => {
        return /^.*=\s*ssh/.test(line.split(',')[0]);
    };
    const parse = (line) => getSurgeParser().parse(line);
    return { name, test, parse };
}
function Surge_SS() {
    const name = 'Surge SS Parser';
    const test = (line) => {
        return /^.*=\s*ss/.test(line.split(',')[0]);
    };
    const parse = (line) => getSurgeParser().parse(line);
    return { name, test, parse };
}

function Surge_VMess() {
    const name = 'Surge VMess Parser';
    const test = (line) => {
        return (
            /^.*=\s*vmess/.test(line.split(',')[0]) &&
            line.indexOf('username') !== -1
        );
    };
    const parse = (line) => getSurgeParser().parse(line);
    return { name, test, parse };
}

function Surge_Trojan() {
    const name = 'Surge Trojan Parser';
    const test = (line) => {
        return /^.*=\s*trojan/.test(line.split(',')[0]);
    };
    const parse = (line) => getSurgeParser().parse(line);
    return { name, test, parse };
}

function Surge_Http() {
    const name = 'Surge HTTP Parser';
    const test = (line) => {
        return /^.*=\s*https?/.test(line.split(',')[0]);
    };
    const parse = (line) => getSurgeParser().parse(line);
    return { name, test, parse };
}

function Surge_Socks5() {
    const name = 'Surge Socks5 Parser';
    const test = (line) => {
        return /^.*=\s*socks5(-tls)?/.test(line.split(',')[0]);
    };
    const parse = (line) => getSurgeParser().parse(line);
    return { name, test, parse };
}

function Surge_External() {
    const name = 'Surge External Parser';
    const test = (line) => {
        return /^.*=\s*external/.test(line.split(',')[0]);
    };
    const parse = (line) => {
        let parsed = /^\s*(.*?)\s*?=\s*?external\s*?,\s*(.*?)\s*$/.exec(line);

        // eslint-disable-next-line no-unused-vars
        let [_, name, other] = parsed;
        line = other;

        // exec = "/usr/bin/ssh" 或 exec = /usr/bin/ssh
        let exec = /(,|^)\s*?exec\s*?=\s*"(.*?)"\s*?(,|$)/.exec(line)?.[2];
        if (!exec) {
            exec = /(,|^)\s*?exec\s*?=\s*(.*?)\s*?(,|$)/.exec(line)?.[2];
        }

        // local-port = "1080" 或 local-port = 1080
        let localPort = /(,|^)\s*?local-port\s*?=\s*"(.*?)"\s*?(,|$)/.exec(
            line,
        )?.[2];
        if (!localPort) {
            localPort = /(,|^)\s*?local-port\s*?=\s*(.*?)\s*?(,|$)/.exec(
                line,
            )?.[2];
        }
        // args = "-m", args = "rc4-md5"
        // args = -m, args = rc4-md5
        const argsRegex = /(,|^)\s*?args\s*?=\s*("(.*?)"|(.*?))(?=\s*?(,|$))/g;
        let argsMatch;
        const args = [];
        while ((argsMatch = argsRegex.exec(line)) !== null) {
            if (argsMatch[3] != null) {
                args.push(argsMatch[3]);
            } else if (argsMatch[4] != null) {
                args.push(argsMatch[4]);
            }
        }
        // addresses = "[ipv6]",,addresses = "ipv6", addresses = "ipv4"
        // addresses = [ipv6], addresses = ipv6, addresses = ipv4
        const addressesRegex =
            /(,|^)\s*?addresses\s*?=\s*("(.*?)"|(.*?))(?=\s*?(,|$))/g;
        let addressesMatch;
        const addresses = [];
        while ((addressesMatch = addressesRegex.exec(line)) !== null) {
            let ip;
            if (addressesMatch[3] != null) {
                ip = addressesMatch[3];
            } else if (addressesMatch[4] != null) {
                ip = addressesMatch[4];
            }
            if (ip != null) {
                ip = `${ip}`.trim().replace(/^\[/, '').replace(/\]$/, '');
            }
            if (isIP(ip)) {
                addresses.push(ip);
            }
        }

        const proxy = {
            type: 'external',
            name,
            exec,
            'local-port': localPort,
            args,
            addresses,
        };
        return proxy;
    };
    return { name, test, parse };
}

function Surge_Snell() {
    const name = 'Surge Snell Parser';
    const test = (line) => {
        return /^.*=\s*snell/.test(line.split(',')[0]);
    };
    const parse = (line) => getSurgeParser().parse(line);
    return { name, test, parse };
}

function Surge_Tuic() {
    const name = 'Surge Tuic Parser';
    const test = (line) => {
        return /^.*=\s*tuic(-v5)?/.test(line.split(',')[0]);
    };
    const parse = (raw) => {
        const { port_hopping, line } = surge_port_hopping(raw);
        const proxy = getSurgeParser().parse(line);
        proxy['ports'] = port_hopping;
        return proxy;
    };
    return { name, test, parse };
}
function Surge_WireGuard() {
    const name = 'Surge WireGuard Parser';
    const test = (line) => {
        return /^.*=\s*wireguard/.test(line.split(',')[0]);
    };
    const parse = (line) => getSurgeParser().parse(line);
    return { name, test, parse };
}

function Surge_Hysteria2() {
    const name = 'Surge Hysteria2 Parser';
    const test = (line) => {
        return /^.*=\s*hysteria2/.test(line.split(',')[0]);
    };
    const parse = (raw) => {
        const { port_hopping, line } = surge_port_hopping(raw);
        const proxy = getSurgeParser().parse(line);
        proxy['ports'] = port_hopping;
        return proxy;
    };
    return { name, test, parse };
}

function isIP(ip) {
    return isIPv4(ip) || isIPv6(ip);
}

export default [
    URI_PROXY(),
    URI_SOCKS(),
    URI_SS(),
    URI_SSR(),
    URI_VMess(),
    URI_VLESS(),
    URI_TUIC(),
    URI_WireGuard(),
    URI_Hysteria(),
    URI_Hysteria2(),
    URI_Trojan(),
    URI_AnyTLS(),
    Clash_All(),
    Surge_Direct(),
    Surge_AnyTLS(),
    Surge_TrustTunnel(),
    Surge_SSH(),
    Surge_SS(),
    Surge_VMess(),
    Surge_Trojan(),
    Surge_Http(),
    Surge_Snell(),
    Surge_Tuic(),
    Surge_WireGuard(),
    Surge_Hysteria2(),
    Surge_Socks5(),
    Surge_External(),
    Loon_SS(),
    Loon_SSR(),
    Loon_VMess(),
    Loon_Vless(),
    Loon_Hysteria2(),
    Loon_Trojan(),
    Loon_AnyTLS(),
    Loon_Http(),
    Loon_Socks5(),
    Loon_WireGuard(),
    QX_SS(),
    QX_SSR(),
    QX_VMess(),
    QX_VLESS(),
    QX_Trojan(),
    QX_Http(),
    QX_Socks5(),
];


================================================
FILE: backend/src/core/proxy-utils/parsers/peggy/loon.js
================================================
import * as peggy from 'peggy';
const grammars = String.raw`
// global initializer
{{
    function $set(obj, path, value) {
      if (Object(obj) !== obj) return obj;
      if (!Array.isArray(path)) path = path.toString().match(/[^.[\]]+/g) || [];
      path
        .slice(0, -1)
        .reduce((a, c, i) => (Object(a[c]) === a[c] ? a[c] : (a[c] = Math.abs(path[i + 1]) >> 0 === +path[i + 1] ? [] : {})), obj)[
        path[path.length - 1]
      ] = value;
      return obj;
    }
}}

// per-parser initializer
{
    const proxy = {};
    const obfs = {};
    const transport = {};
    const $ = {};

    function handleTransport() {
        if (transport.type === "tcp") { /* do nothing */ }
        else if (transport.type === "ws") {
            proxy.network = "ws";
            $set(proxy, "ws-opts.path", transport.path);
            $set(proxy, "ws-opts.headers.Host", transport.host);
        } else if (transport.type === "http") {
            proxy.network = "http";
            $set(proxy, "http-opts.path", transport.path);
            $set(proxy, "http-opts.headers.Host", transport.host);
        }
    }
}

start = (shadowsocksr/shadowsocks/vmess/vless/trojan/https/http/socks5/hysteria2/anytls) {
    return proxy;
}

shadowsocksr = tag equals "shadowsocksr"i address method password (ssr_protocol/ssr_protocol_param/obfs_ssr/obfs_ssr_param/obfs_host/obfs_uri/fast_open/udp_relay/udp_port/shadow_tls_version/shadow_tls_sni/shadow_tls_password/ip_mode/block_quic/others)*{
    proxy.type = "ssr";
    // handle ssr obfs
    proxy.obfs = obfs.type;
}
shadowsocks = tag equals "shadowsocks"i address method password (obfs_typev obfs_hostv)? (obfs_ss/obfs_host/obfs_uri/fast_open/udp_relay/udp_port/shadow_tls_version/shadow_tls_sni/shadow_tls_password/ip_mode/block_quic/udp_over_tcp/others)* {
    proxy.type = "ss";
    // handle ss obfs
    if (obfs.type == "http" || obfs.type === "tls") {
        proxy.plugin = "obfs";
        $set(proxy, "plugin-opts.mode", obfs.type);
        $set(proxy, "plugin-opts.host", obfs.host);
        $set(proxy, "plugin-opts.path", obfs.path);
    }
}
vmess = tag equals "vmess"i address method uuid (transport/transport_host/transport_path/over_tls/tls_name/sni/tls_verification/tls_cert_sha256/tls_pubkey_sha256/vmess_alterId/fast_open/udp_relay/ip_mode/public_key/short_id/block_quic/others)* {
    proxy.type = "vmess";
    proxy.cipher = proxy.cipher || "none";
    proxy.alterId = proxy.alterId || 0;
    handleTransport();
}
vless = tag equals "vless"i address uuid (transport/transport_host/transport_path/over_tls/tls_name/sni/tls_verification/tls_cert_sha256/tls_pubkey_sha256/fast_open/udp_relay/ip_mode/flow/public_key/short_id/block_quic/others)* {
    proxy.type = "vless";
    handleTransport();
}
trojan = tag equals "trojan"i address password (transport/transport_host/transport_path/over_tls/tls_name/sni/tls_verification/tls_cert_sha256/tls_pubkey_sha256/fast_open/udp_relay/ip_mode/block_quic/others)* {
    proxy.type = "trojan";
    handleTransport();
}
anytls = tag equals "anytls"i address password (transport/transport_host/transport_path/over_tls/tls_name/sni/tls_verification/tls_cert_sha256/tls_pubkey_sha256/fast_open/udp_relay/ip_mode/block_quic/idle_session_check_interval/idle_session_timeout/min_idle_session/max_stream_count/others)* {
    proxy.type = "anytls";
    handleTransport();
}
hysteria2 = tag equals "hysteria2"i address password (tls_name/sni/tls_verification/tls_cert_sha256/tls_pubkey_sha256/udp_relay/fast_open/download_bandwidth/salamander_password/ecn/ip_mode/block_quic/others)* {
    proxy.type = "hysteria2";
}
https = tag equals "https"i address (username password)? (tls_name/sni/tls_verification/tls_cert_sha256/tls_pubkey_sha256/fast_open/udp_relay/ip_mode/block_quic/others)* {
    proxy.type = "http";
    proxy.tls = true;
}
http = tag equals "http"i address (username password)? (fast_open/udp_relay/ip_mode/block_quic/others)* {
    proxy.type = "http";
}
socks5 = tag equals "socks5"i address (username password)? (over_tls/tls_name/sni/tls_verification/tls_cert_sha256/tls_pubkey_sha256/fast_open/udp_relay/ip_mode/block_quic/others)* {
    proxy.type = "socks5";
}

address = comma server:server comma port:port {
    proxy.server = server;
    proxy.port = port;
}

server = ip/domain

ip = & {
    const start = peg$currPos;
    let j = start;
    while (j < input.length) {
        if (input[j] === ",") break;
        j++;
    }
    peg$currPos = j;
    $.ip = input.substring(start, j).trim();
    return true;
} { return $.ip; }

domain = match:[0-9a-zA-z-_.]+ { 
    const domain = match.join(""); 
    if (/(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z0-9][a-z0-9-]{0,61}[a-z0-9]/.test(domain)) {
        return domain;
    }
    throw new Error("Invalid domain: " + domain);
}

port = digits:[0-9]+ { 
    const port = parseInt(digits.join(""), 10); 
    if (port >= 0 && port <= 65535) {
    	return port;
    }
    throw new Error("Invalid port number: " + port);
}

method = comma cipher:cipher { 
    proxy.cipher = cipher;
}
cipher = ("aes-128-cfb"/"aes-128-ctr"/"aes-128-gcm"/"aes-192-cfb"/"aes-192-ctr"/"aes-192-gcm"/"aes-256-cfb"/"aes-256-ctr"/"aes-256-gcm"/"auto"/"bf-cfb"/"camellia-128-cfb"/"camellia-192-cfb"/"camellia-256-cfb"/"chacha20-ietf-poly1305"/"chacha20-ietf"/"chacha20-poly1305"/"chacha20"/"none"/"rc4-md5"/"rc4"/"salsa20"/"xchacha20-ietf-poly1305"/"2022-blake3-aes-128-gcm"/"2022-blake3-aes-256-gcm");

username = & {
    let j = peg$currPos; 
    let start, end;
    let first = true;
    while (j < input.length) {
        if (input[j] === ',') {
            if (first) {
                start = j + 1;
                first = false;
            } else {
                end = j;
                break;
            }
        }
        j++;
    }
    const match = input.substring(start, end);
    if (match.indexOf("=") === -1) {
        $.username = match;
        peg$currPos = end;
        return true;
    }
} { proxy.username = $.username; }
password = comma '"' match:[^"]* '"' { proxy.password = match.join(""); }
uuid = comma '"' match:[^"]+ '"' { proxy.uuid = match.join(""); }

obfs_typev = comma type:("http"/"tls") { obfs.type = type; }
obfs_hostv = comma match:[^,]+ { obfs.host = match.join(""); }

obfs_ss = comma "obfs-name" equals type:("http"/"tls") { obfs.type = type; }

obfs_ssr = comma "obfs" equals type:("plain"/"http_simple"/"http_post"/"random_head"/"tls1.2_ticket_auth"/"tls1.2_ticket_fastauth") { obfs.type = type; }
obfs_ssr_param = comma "obfs-param" equals match:$[^,]+ { proxy["obfs-param"] = match; }

obfs_host = comma "obfs-host" equals match:[^,]+ { obfs.host = match.join("").replace(/^"(.*)"$/, '$1'); }
obfs_uri = comma "obfs-uri" equals uri:uri { obfs.path = uri; }
uri = $[^,]+

transport = comma "transport" equals type:("tcp"/"ws"/"http") { transport.type = type; }
transport_host = comma "host" equals match:[^,]+ { transport.host = match.join("").replace(/^"(.*)"$/, '$1'); }
transport_path = comma "path" equals path:uri { transport.path = path; }

ssr_protocol = comma "protocol" equals protocol:("origin"/"auth_sha1_v4"/"auth_aes128_md5"/"auth_aes128_sha1"/"auth_chain_a"/"auth_chain_b") { proxy.protocol = protocol; }
ssr_protocol_param = comma "protocol-param" equals param:$[^=,]+ { proxy["protocol-param"] = param; }

vmess_alterId = comma "alterId" equals alterId:$[0-9]+ { proxy.alterId = parseInt(alterId); } 

udp_port = comma "udp-port" equals match:$[0-9]+ { proxy["udp-port"] = parseInt(match.trim()); }
shadow_tls_version = comma "shadow-tls-version" equals match:$[0-9]+ { proxy["shadow-tls-version"] = parseInt(match.trim()); }
shadow_tls_sni = comma "shadow-tls-sni" equals match:[^,]+ { proxy["shadow-tls-sni"] = match.join(""); }
shadow_tls_password = comma "shadow-tls-password" equals match:[^,]+ { proxy["shadow-tls-password"] = match.join(""); }

over_tls = comma "over-tls" equals flag:bool { proxy.tls = flag; }
tls_name = comma sni:("tls-name") equals match:[^,]+ { proxy.sni = match.join("").replace(/^"(.*)"$/, '$1'); }
sni = comma "sni" equals match:[^,]+ { proxy.sni = match.join("").replace(/^"(.*)"$/, '$1'); }
tls_verification = comma "skip-cert-verify" equals flag:bool { proxy["skip-cert-verify"] = flag; }
tls_cert_sha256 = comma "tls-cert-sha256" equals match:[^,]+ { proxy["tls-fingerprint"] = match.join("").replace(/^"(.*)"$/, '$1'); }
tls_pubkey_sha256 = comma "tls-pubkey-sha256" equals match:[^,]+ { proxy["tls-pubkey-sha256"] = match.join("").replace(/^"(.*)"$/, '$1'); }

flow = comma "flow" equals match:[^,]+ { proxy["flow"] = match.join("").replace(/^"(.*)"$/, '$1'); }
public_key = comma "public-key" equals match:[^,]+ { proxy["reality-opts"] = proxy["reality-opts"] || {}; proxy["reality-opts"]["public-key"] = match.join("").replace(/^"(.*)"$/, '$1'); }
short_id = comma "short-id" equals match:[^,]+ { proxy["reality-opts"] = proxy["reality-opts"] || {}; proxy["reality-opts"]["short-id"] = match.join("").replace(/^"(.*)"$/, '$1'); }

fast_open = comma "fast-open" equals flag:bool { proxy.tfo = flag; }
udp_relay = comma "udp" equals flag:bool { proxy.udp = flag; }
ip_mode = comma "ip-mode" equals match:[^,]+ { proxy["ip-version"] = match.join(""); }

ecn = comma "ecn" equals flag:bool { proxy.ecn = flag; }
download_bandwidth = comma "download-bandwidth" equals match:[^,]+ { proxy.down = match.join(""); }
salamander_password = comma "salamander-password" equals match:[^,]+ { proxy['obfs-password'] = match.join(""); proxy.obfs = 'salamander'; }

block_quic = comma "block-quic" equals flag:bool { if(flag) proxy["block-quic"] = "on"; else proxy["block-quic"] = "off"; }

idle_session_check_interval = comma "idle-session-check-interval" equals match:$[0-9]+ { proxy["idle-session-check-interval"] = parseInt(match.trim()); }
idle_session_timeout = comma "idle-session-timeout" equals match:$[0-9]+ { proxy["idle-session-timeout"] = parseInt(match.trim()); }
min_idle_session = comma "min-idle-session" equals match:$[0-9]+ { proxy["min-idle-session"] = parseInt(match.trim()); }
max_stream_count = comma "max-stream-count" equals match:$[0-9]+ { proxy["max-stream-count"] = parseInt(match.trim()); }

udp_over_tcp = comma "udp-over-tcp" equals flag:bool { proxy["udp-over-tcp"] = true; proxy["udp-over-tcp-version"] = 2; }

tag = match:[^=,]* { proxy.name = match.join("").trim(); }
comma = _ "," _
equals = _ "=" _
_ = [ \r\t]*
bool = b:("true"/"false") { return b === "true" }
others = comma [^=,]+ equals [^=,]+
`;
let parser;
export default function getParser() {
    if (!parser) {
        parser = peggy.generate(grammars);
    }
    return parser;
}


================================================
FILE: backend/src/core/proxy-utils/parsers/peggy/loon.peg
================================================
// global initializer
{{
    function $set(obj, path, value) {
      if (Object(obj) !== obj) return obj;
      if (!Array.isArray(path)) path = path.toString().match(/[^.[\]]+/g) || [];
      path
        .slice(0, -1)
        .reduce((a, c, i) => (Object(a[c]) === a[c] ? a[c] : (a[c] = Math.abs(path[i + 1]) >> 0 === +path[i + 1] ? [] : {})), obj)[
        path[path.length - 1]
      ] = value;
      return obj;
    }
}}

// per-parser initializer
{
    const proxy = {};
    const obfs = {};
    const transport = {};
    const $ = {};

    function handleTransport() {
        if (transport.type === "tcp") { /* do nothing */ }
        else if (transport.type === "ws") {
            proxy.network = "ws";
            $set(proxy, "ws-opts.path", transport.path);
            $set(proxy, "ws-opts.headers.Host", transport.host);
        } else if (transport.type === "http") {
            proxy.network = "http";
            $set(proxy, "http-opts.path", transport.path);
            $set(proxy, "http-opts.headers.Host", transport.host);
        }
    }
}

start = (shadowsocksr/shadowsocks/vmess/vless/trojan/https/http/socks5/hysteria2/anytls) {
    return proxy;
}

shadowsocksr = tag equals "shadowsocksr"i address method password (ssr_protocol/ssr_protocol_param/obfs_ssr/obfs_ssr_param/obfs_host/obfs_uri/fast_open/udp_relay/udp_port/shadow_tls_version/shadow_tls_sni/shadow_tls_password/ip_mode/block_quic/udp_over_tcp/others)*{
    proxy.type = "ssr";
    // handle ssr obfs
    proxy.obfs = obfs.type;
}
shadowsocks = tag equals "shadowsocks"i address method password (obfs_typev obfs_hostv)? (obfs_ss/obfs_host/obfs_uri/fast_open/udp_relay/udp_port/shadow_tls_version/shadow_tls_sni/shadow_tls_password/ip_mode/block_quic/others)* {
    proxy.type = "ss";
    // handle ss obfs
    if (obfs.type == "http" || obfs.type === "tls") {
        proxy.plugin = "obfs";
        $set(proxy, "plugin-opts.mode", obfs.type);
        $set(proxy, "plugin-opts.host", obfs.host);
        $set(proxy, "plugin-opts.path", obfs.path);
    }
}
vmess = tag equals "vmess"i address method uuid (transport/transport_host/transport_path/over_tls/tls_name/sni/tls_verification/tls_cert_sha256/tls_pubkey_sha256/vmess_alterId/fast_open/udp_relay/ip_mode/public_key/short_id/block_quic/others)* {
    proxy.type = "vmess";
    proxy.cipher = proxy.cipher || "none";
    proxy.alterId = proxy.alterId || 0;
    handleTransport();
}
vless = tag equals "vless"i address uuid (transport/transport_host/transport_path/over_tls/tls_name/sni/tls_verification/tls_cert_sha256/tls_pubkey_sha256/fast_open/udp_relay/ip_mode/flow/public_key/short_id/block_quic/others)* {
    proxy.type = "vless";
    handleTransport();
}
trojan = tag equals "trojan"i address password (transport/transport_host/transport_path/over_tls/tls_name/sni/tls_verification/tls_cert_sha256/tls_pubkey_sha256/fast_open/udp_relay/ip_mode/block_quic/others)* {
    proxy.type = "trojan";
    handleTransport();
}
anytls = tag equals "anytls"i address password (transport/transport_host/transport_path/over_tls/tls_name/sni/tls_verification/tls_cert_sha256/tls_pubkey_sha256/fast_open/udp_relay/ip_mode/block_quic/idle_session_check_interval/idle_session_timeout/min_idle_session/max_stream_count/others)* {
    proxy.type = "anytls";
    handleTransport();
}
hysteria2 = tag equals "hysteria2"i address password (tls_name/sni/tls_verification/tls_cert_sha256/tls_pubkey_sha256/udp_relay/fast_open/download_bandwidth/salamander_password/ecn/ip_mode/block_quic/others)* {
    proxy.type = "hysteria2";
}
https = tag equals "https"i address (username password)? (tls_name/sni/tls_verification/tls_cert_sha256/tls_pubkey_sha256/fast_open/udp_relay/ip_mode/block_quic/others)* {
    proxy.type = "http";
    proxy.tls = true;
}
http = tag equals "http"i address (username password)? (fast_open/udp_relay/ip_mode/block_quic/others)* {
    proxy.type = "http";
}
socks5 = tag equals "socks5"i address (username password)? (over_tls/tls_name/sni/tls_verification/tls_cert_sha256/tls_pubkey_sha256/fast_open/udp_relay/ip_mode/block_quic/others)* {
    proxy.type = "socks5";
}

address = comma server:server comma port:port {
    proxy.server = server;
    proxy.port = port;
}

server = ip/domain

ip = & {
    const start = peg$currPos;
    let j = start;
    while (j < input.length) {
        if (input[j] === ",") break;
        j++;
    }
    peg$currPos = j;
    $.ip = input.substring(start, j).trim();
    return true;
} { return $.ip; }

domain = match:[0-9a-zA-z-_.]+ { 
    const domain = match.join(""); 
    if (/(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z0-9][a-z0-9-]{0,61}[a-z0-9]/.test(domain)) {
        return domain;
    }
    throw new Error("Invalid domain: " + domain);
}

port = digits:[0-9]+ { 
    const port = parseInt(digits.join(""), 10); 
    if (port >= 0 && port <= 65535) {
    	return port;
    }
    throw new Error("Invalid port number: " + port);
}

method = comma cipher:cipher { 
    proxy.cipher = cipher;
}
cipher = ("aes-128-cfb"/"aes-128-ctr"/"aes-128-gcm"/"aes-192-cfb"/"aes-192-ctr"/"aes-192-gcm"/"aes-256-cfb"/"aes-256-ctr"/"aes-256-gcm"/"auto"/"bf-cfb"/"camellia-128-cfb"/"camellia-192-cfb"/"camellia-256-cfb"/"chacha20-ietf-poly1305"/"chacha20-ietf"/"chacha20-poly1305"/"chacha20"/"none"/"rc4-md5"/"rc4"/"salsa20"/"xchacha20-ietf-poly1305"/"2022-blake3-aes-128-gcm"/"2022-blake3-aes-256-gcm");

username = & {
    let j = peg$currPos; 
    let start, end;
    let first = true;
    while (j < input.length) {
        if (input[j] === ',') {
            if (first) {
                start = j + 1;
                first = false;
            } else {
                end = j;
                break;
            }
        }
        j++;
    }
    const match = input.substring(start, end);
    if (match.indexOf("=") === -1) {
        $.username = match;
        peg$currPos = end;
        return true;
    }
} { proxy.username = $.username; }
password = comma '"' match:[^"]* '"' { proxy.password = match.join(""); }
uuid = comma '"' match:[^"]+ '"' { proxy.uuid = match.join(""); }

obfs_typev = comma type:("http"/"tls") { obfs.type = type; }
obfs_hostv = comma match:[^,]+ { obfs.host = match.join(""); }

obfs_ss = comma "obfs-name" equals type:("http"/"tls") { obfs.type = type; }

obfs_ssr = comma "obfs" equals type:("plain"/"http_simple"/"http_post"/"random_head"/"tls1.2_ticket_auth"/"tls1.2_ticket_fastauth") { obfs.type = type; }
obfs_ssr_param = comma "obfs-param" equals match:$[^,]+ { proxy["obfs-param"] = match; }

obfs_host = comma "obfs-host" equals match:[^,]+ { obfs.host = match.join("").replace(/^"(.*)"$/, '$1'); }
obfs_uri = comma "obfs-uri" equals uri:uri { obfs.path = uri; }
uri = $[^,]+

transport = comma "transport" equals type:("tcp"/"ws"/"http") { transport.type = type; }
transport_host = comma "host" equals match:[^,]+ { transport.host = match.join("").replace(/^"(.*)"$/, '$1'); }
transport_path = comma "path" equals path:uri { transport.path = path; }

ssr_protocol = comma "protocol" equals protocol:("origin"/"auth_sha1_v4"/"auth_aes128_md5"/"auth_aes128_sha1"/"auth_chain_a"/"auth_chain_b") { proxy.protocol = protocol; }
ssr_protocol_param = comma "protocol-param" equals param:$[^=,]+ { proxy["protocol-param"] = param; }

vmess_alterId = comma "alterId" equals alterId:$[0-9]+ { proxy.alterId = parseInt(alterId); } 

udp_port = comma "udp-port" equals match:$[0-9]+ { proxy["udp-port"] = parseInt(match.trim()); }
shadow_tls_version = comma "shadow-tls-version" equals match:$[0-9]+ { proxy["shadow-tls-version"] = parseInt(match.trim()); }
shadow_tls_sni = comma "shadow-tls-sni" equals match:[^,]+ { proxy["shadow-tls-sni"] = match.join(""); }
shadow_tls_password = comma "shadow-tls-password" equals match:[^,]+ { proxy["shadow-tls-password"] = match.join(""); }

over_tls = comma "over-tls" equals flag:bool { proxy.tls = flag; }
tls_name = comma sni:("tls-name") equals match:[^,]+ { proxy.sni = match.join("").replace(/^"(.*)"$/, '$1'); }
sni = comma "sni" equals match:[^,]+ { proxy.sni = match.join("").replace(/^"(.*)"$/, '$1'); }
tls_verification = comma "skip-cert-verify" equals flag:bool { proxy["skip-cert-verify"] = flag; }
tls_cert_sha256 = comma "tls-cert-sha256" equals match:[^,]+ { proxy["tls-fingerprint"] = match.join("").replace(/^"(.*)"$/, '$1'); }
tls_pubkey_sha256 = comma "tls-pubkey-sha256" equals match:[^,]+ { proxy["tls-pubkey-sha256"] = match.join("").replace(/^"(.*)"$/, '$1'); }

flow = comma "flow" equals match:[^,]+ { proxy["flow"] = match.join("").replace(/^"(.*)"$/, '$1'); }
public_key = comma "public-key" equals match:[^,]+ { proxy["reality-opts"] = proxy["reality-opts"] || {}; proxy["reality-opts"]["public-key"] = match.join("").replace(/^"(.*)"$/, '$1'); }
short_id = comma "short-id" equals match:[^,]+ { proxy["reality-opts"] = proxy["reality-opts"] || {}; proxy["reality-opts"]["short-id"] = match.join("").replace(/^"(.*)"$/, '$1'); }

fast_open = comma "fast-open" equals flag:bool { proxy.tfo = flag; }
udp_relay = comma "udp" equals flag:bool { proxy.udp = flag; }
ip_mode = comma "ip-mode" equals match:[^,]+ { proxy["ip-version"] = match.join(""); }

ecn = comma "ecn" equals flag:bool { proxy.ecn = flag; }
download_bandwidth = comma "download-bandwidth" equals match:[^,]+ { proxy.down = match.join(""); }
salamander_password = comma "salamander-password" equals match:[^,]+ { proxy['obfs-password'] = match.join(""); proxy.obfs = 'salamander'; }

block_quic = comma "block-quic" equals flag:bool { if(flag) proxy["block-quic"] = "on"; else proxy["block-quic"] = "off"; }

idle_session_check_interval = comma "idle-session-check-interval" equals match:$[0-9]+ { proxy["idle-session-check-interval"] = parseInt(match.trim()); }
idle_session_timeout = comma "idle-session-timeout" equals match:$[0-9]+ { proxy["idle-session-timeout"] = parseInt(match.trim()); }
min_idle_session = comma "min-idle-session" equals match:$[0-9]+ { proxy["min-idle-session"] = parseInt(match.trim()); }
max_stream_count = comma "max-stream-count" equals match:$[0-9]+ { proxy["max-stream-count"] = parseInt(match.trim()); }

udp_over_tcp = comma "udp-over-tcp" equals flag:bool { proxy["udp-over-tcp"] = true; proxy["udp-over-tcp-version"] = 2; }

tag = match:[^=,]* { proxy.name = match.join("").trim(); }
comma = _ "," _
equals = _ "=" _
_ = [ \r\t]*
bool = b:("true"/"false") { return b === "true" }
others = comma [^=,]+ equals [^=,]+

================================================
FILE: backend/src/core/proxy-utils/parsers/peggy/qx.js
================================================
import * as peggy from 'peggy';
const grammars = String.raw`
// global initializer
{{
    function $set(obj, path, value) {
      if (Object(obj) !== obj) return obj;
      if (!Array.isArray(path)) path = path.toString().match(/[^.[\]]+/g) || [];
      path
        .slice(0, -1)
        .reduce((a, c, i) => (Object(a[c]) === a[c] ? a[c] : (a[c] = Math.abs(path[i + 1]) >> 0 === +path[i + 1] ? [] : {})), obj)[
        path[path.length - 1]
      ] = value;
      return obj;
    }
}}

// per-parse initializer
{
	const proxy = {};
    const obfs = {};
    const $ = {};

    function handleObfs() {
        if (obfs.type === "ws" || obfs.type === "wss") {
            proxy.network = "ws";
            if (obfs.type === 'wss') {
                proxy.tls = true;
            }
            $set(proxy, "ws-opts.path", obfs.path);
            $set(proxy, "ws-opts.headers.Host", obfs.host);
        } else if (obfs.type === "over-tls") {
            proxy.tls = true;
        } else if (obfs.type === "http") {
            proxy.network = "http";
            $set(proxy, "http-opts.path", obfs.path);
            $set(proxy, "http-opts.headers.Host", obfs.host);
        }
    }
}

start = (trojan/shadowsocks/vmess/vless/http/socks5) {
    return proxy
}

trojan = "trojan" equals address
    (password/over_tls/tls_host/tls_pubkey_sha256/tls_alpn/tls_no_session_ticket/tls_no_session_reuse/tls_fingerprint/tls_verification/obfs/obfs_host/obfs_uri/tag/udp_relay/udp_over_tcp/fast_open/server_check_url/reality_base64_pubkey/reality_hex_shortid/others)* {
    proxy.type = "trojan";
    handleObfs();
}

shadowsocks = "shadowsocks" equals address
    (password/method/obfs_ssr/obfs_ss/obfs_host/obfs_uri/ssr_protocol/ssr_protocol_param/tls_pubkey_sha256/tls_alpn/tls_no_session_ticket/tls_no_session_reuse/tls_fingerprint/tls_verification/udp_relay/udp_over_tcp_new/fast_open/tag/server_check_url/reality_base64_pubkey/reality_hex_shortid/others)* {
    if (proxy.protocol || proxy.type === "ssr") {
        proxy.type = "ssr";
        if (!proxy.protocol) {
            proxy.protocol = "origin";
        }
        // handle ssr obfs
        if (obfs.host) proxy["obfs-param"] = obfs.host;
        if (obfs.type) proxy.obfs = obfs.type;
    } else {
        proxy.type = "ss";
        // handle ss obfs
        if (obfs.type == "http" || obfs.type === "tls") {
            proxy.plugin = "obfs";
            $set(proxy, "plugin-opts", {
                mode: obfs.type
            });
        } else if (obfs.type === "ws" || obfs.type === "wss") {
            proxy.plugin = "v2ray-plugin";
            $set(proxy, "plugin-opts.mode", "websocket");
            if (obfs.type === "wss") {
                $set(proxy, "plugin-opts.tls", true);
            }
        } else if (obfs.type === 'over-tls') {
            throw new Error('ss over-tls is not supported');
        }
        if (obfs.type) {
            $set(proxy, "plugin-opts.host", obfs.host);
            $set(proxy, "plugin-opts.path", obfs.path);
        }
    }
}

vmess = "vmess" equals address
    (uuid/method/over_tls/tls_host/tls_pubkey_sha256/tls_alpn/tls_no_session_ticket/tls_no_session_reuse/tls_fingerprint/tls_verification/tag/obfs/obfs_host/obfs_uri/udp_relay/udp_over_tcp/fast_open/aead/server_check_url/reality_base64_pubkey/reality_hex_shortid/others)* {
    proxy.type = "vmess";
    proxy.cipher = proxy.cipher || "none";
    if (proxy.aead === false) {
        proxy.alterId = 1;
    } else {
        proxy.alterId = 0;
    }
    handleObfs();
}

vless = "vless" equals address
    (uuid/method/over_tls/tls_host/tls_pubkey_sha256/tls_alpn/tls_no_session_ticket/tls_no_session_reuse/tls_fingerprint/tls_verification/tag/obfs/obfs_host/obfs_uri/udp_relay/udp_over_tcp/fast_open/aead/server_check_url/reality_base64_pubkey/reality_hex_shortid/vless_flow/others)* {
    proxy.type = "vless";
    proxy.cipher = proxy.cipher || "none";
    handleObfs();
}

http = "http" equals address 
    (username/password/over_tls/tls_host/tls_pubkey_sha256/tls_alpn/tls_no_session_ticket/tls_no_session_reuse/tls_fingerprint/tls_verification/tag/fast_open/udp_relay/udp_over_tcp/server_check_url/reality_base64_pubkey/reality_hex_shortid/others)*{
    proxy.type = "http";
}

socks5 = "socks5" equals address
    (username/password/password/over_tls/tls_host/tls_pubkey_sha256/tls_alpn/tls_no_session_ticket/tls_no_session_reuse/tls_fingerprint/tls_verification/tag/fast_open/udp_relay/udp_over_tcp/server_check_url/reality_base64_pubkey/reality_hex_shortid/others)* {
    proxy.type = "socks5";
}
    
address = server:server ":" port:port {
    proxy.server = server;
    proxy.port = port;
}
server = ip/domain

domain = match:[0-9a-zA-z-_.]+ { 
    const domain = match.join(""); 
    if (/(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z0-9][a-z0-9-]{0,61}[a-z0-9]/.test(domain)) {
        return domain;
    }
}

ip = & {
    const start = peg$currPos;
    let end;
    let j = start;
    while (j < input.length) {
        if (input[j] === ",") break;
        if (input[j] === ":") end = j;
        j++;
    }
    peg$currPos = end || j;
    $.ip = input.substring(start, end).trim();
    return true;
} { return $.ip; }

port = digits:[0-9]+ { 
    const port = parseInt(digits.join(""), 10); 
    if (port >= 0 && port <= 65535) {
    	return port;
    }
}

username = comma "username" equals username:[^,]+ { proxy.username = username.join("").trim(); }
password = comma "password" equals password:[^,]+ { proxy.password = password.join("").trim(); }
uuid = comma "password" equals uuid:[^,]+ { proxy.uuid = uuid.join("").trim(); }

method = comma "method" equals cipher:cipher { 
    proxy.cipher = cipher;
};
cipher = ("aes-128-cfb"/"aes-128-ctr"/"aes-128-gcm"/"aes-192-cfb"/"aes-192-ctr"/"aes-192-gcm"/"aes-256-cfb"/"aes-256-ctr"/"aes-256-gcm"/"bf-cfb"/"cast5-cfb"/"chacha20-ietf-poly1305"/"chacha20-ietf"/"chacha20-poly1305"/"chacha20"/"des-cfb"/"none"/"rc2-cfb"/"rc4-md5-6"/"rc4-md5"/"salsa20"/"xchacha20-ietf-poly1305"/"2022-blake3-aes-128-gcm"/"2022-blake3-aes-256-gcm");
aead = comma "aead" equals flag:bool { proxy.aead = flag; }

udp_relay = comma "udp-relay" equals flag:bool { proxy.udp = flag; }
udp_over_tcp = comma "udp-over-tcp" equals flag:bool { throw new Error("UDP over TCP is not supported"); }
udp_over_tcp_new = comma "udp-over-tcp" equals param:$[^=,]+ { if (param === "sp.v1") { proxy["udp-over-tcp"] = true; proxy["udp-over-tcp-version"] = 1; } else if (param === "sp.v2") { proxy["udp-over-tcp"] = true; proxy["udp-over-tcp-version"] = 2; } else if (param === "true") { proxy["_ssr_python_uot"] = true; } else { throw new Error("Invalid value for udp-over-tcp"); } }

fast_open = comma "fast-open" equals flag:bool { proxy.tfo = flag; }

over_tls = comma "over-tls" equals flag:bool { proxy.tls = flag; }
tls_host = comma sni:("tls-host") equals match:[^,]+ { proxy.sni = match.join("").replace(/^"(.*)"$/, '$1'); }
tls_verification = comma "tls-verification" equals flag:bool { 
    proxy["skip-cert-verify"] = !flag;
}
tls_fingerprint = comma "tls-cert-sha256" equals tls_fingerprint:$[^,]+ { proxy["tls-fingerprint"] = tls_fingerprint.trim(); }
tls_pubkey_sha256 = comma "tls-pubkey-sha256" equals param:$[^=,]+ { proxy["tls-pubkey-sha256"] = param; }
tls_alpn = comma "tls-alpn" equals param:$[^=,]+ { proxy["tls-alpn"] = param; }
tls_no_session_ticket = comma "tls-no-session-ticket" equals flag:bool { 
    proxy["tls-no-session-ticket"] = flag;
}
tls_no_session_reuse = comma "tls-no-session-reuse" equals flag:bool { 
    proxy["tls-no-session-reuse"] = flag;
}

obfs_ss = comma "obfs" equals type:("http"/"tls"/"wss"/"ws"/"over-tls") { obfs.type = type; return type; }
obfs_ssr = comma "obfs" equals type:("plain"/"http_simple"/"http_post"/"random_head"/"tls1.2_ticket_auth"/"tls1.2_ticket_fastauth") { proxy.type = "ssr"; obfs.type = type; return type; }
obfs = comma "obfs" equals type:("wss"/"ws"/"over-tls"/"http") { obfs.type = type; return type; };

obfs_host = comma "obfs-host" equals match:[^,]+ { obfs.host = match.join("").replace(/^"(.*)"$/, '$1'); }
obfs_uri = comma "obfs-uri" equals uri:uri { obfs.path = uri; }

ssr_protocol = comma "ssr-protocol" equals protocol:("origin"/"auth_sha1_v4"/"auth_aes128_md5"/"auth_aes128_sha1"/"auth_chain_a"/"auth_chain_b") { proxy.protocol = protocol; return protocol; }
ssr_protocol_param = comma "ssr-protocol-param" equals param:$[^=,]+ { proxy["protocol-param"] = param; }

reality_base64_pubkey = comma "reality-base64-pubkey" equals param:$[^=,]+ {
    $set(proxy, "reality-opts.public-key", param);
 }
reality_hex_shortid = comma "reality-hex-shortid" equals param:$[^=,]+ {
    $set(proxy, "reality-opts.short-id", param);
}

vless_flow = comma "vless-flow" equals param:$[^=,]+ { proxy["flow"] = param; }
server_check_url = comma "server_check_url" equals param:$[^=,]+ { proxy["test-url"] = param; }

uri = $[^,]+

tag = comma "tag" equals tag:[^=,]+ { proxy.name = tag.join(""); }
others = comma [^=,]+ equals [^=,]+
comma = _ "," _
equals = _ "=" _
_ = [ \r\t]*
bool = b:("true"/"false") { return b === "true" }
`;
let parser;
export default function getParser() {
    if (!parser) {
        parser = peggy.generate(grammars);
    }
    return parser;
}


================================================
FILE: backend/src/core/proxy-utils/parsers/peggy/qx.peg
================================================
// global initializer
{{
    function $set(obj, path, value) {
      if (Object(obj) !== obj) return obj;
      if (!Array.isArray(path)) path = path.toString().match(/[^.[\]]+/g) || [];
      path
        .slice(0, -1)
        .reduce((a, c, i) => (Object(a[c]) === a[c] ? a[c] : (a[c] = Math.abs(path[i + 1]) >> 0 === +path[i + 1] ? [] : {})), obj)[
        path[path.length - 1]
      ] = value;
      return obj;
    }
}}

// per-parse initializer
{
	const proxy = {};
    const obfs = {};
    const $ = {};

    function handleObfs() {
        if (obfs.type === "ws" || obfs.type === "wss") {
            proxy.network = "ws";
            if (obfs.type === 'wss') {
                proxy.tls = true;
            }
            $set(proxy, "ws-opts.path", obfs.path);
            $set(proxy, "ws-opts.headers.Host", obfs.host);
        } else if (obfs.type === "over-tls") {
            proxy.tls = true;
        } else if (obfs.type === "http") {
            proxy.network = "http";
            $set(proxy, "http-opts.path", obfs.path);
            $set(proxy, "http-opts.headers.Host", obfs.host);
        }
    }
}

start = (trojan/shadowsocks/vmess/vless/http/socks5) {
    return proxy
}

trojan = "trojan" equals address
    (password/over_tls/tls_host/tls_pubkey_sha256/tls_alpn/tls_no_session_ticket/tls_no_session_reuse/tls_fingerprint/tls_verification/obfs/obfs_host/obfs_uri/tag/udp_relay/udp_over_tcp/fast_open/server_check_url/reality_base64_pubkey/reality_hex_shortid/others)* {
    proxy.type = "trojan";
    handleObfs();
}

shadowsocks = "shadowsocks" equals address
    (password/method/obfs_ssr/obfs_ss/obfs_host/obfs_uri/ssr_protocol/ssr_protocol_param/tls_pubkey_sha256/tls_alpn/tls_no_session_ticket/tls_no_session_reuse/tls_fingerprint/tls_verification/udp_relay/udp_over_tcp_new/fast_open/tag/server_check_url/reality_base64_pubkey/reality_hex_shortid/others)* {
    if (proxy.protocol || proxy.type === "ssr") {
        proxy.type = "ssr";
        if (!proxy.protocol) {
            proxy.protocol = "origin";
        }
        // handle ssr obfs
        if (obfs.host) proxy["obfs-param"] = obfs.host;
        if (obfs.type) proxy.obfs = obfs.type;
    } else {
        proxy.type = "ss";
        // handle ss obfs
        if (obfs.type == "http" || obfs.type === "tls") {
            proxy.plugin = "obfs";
            $set(proxy, "plugin-opts", {
                mode: obfs.type
            });
        } else if (obfs.type === "ws" || obfs.type === "wss") {
            proxy.plugin = "v2ray-plugin";
            $set(proxy, "plugin-opts.mode", "websocket");
            if (obfs.type === "wss") {
                $set(proxy, "plugin-opts.tls", true);
            }
        } else if (obfs.type === 'over-tls') {
            throw new Error('ss over-tls is not supported');
        }
        if (obfs.type) {
            $set(proxy, "plugin-opts.host", obfs.host);
            $set(proxy, "plugin-opts.path", obfs.path);
        }
    }
}

vmess = "vmess" equals address
    (uuid/method/over_tls/tls_host/tls_pubkey_sha256/tls_alpn/tls_no_session_ticket/tls_no_session_reuse/tls_fingerprint/tls_verification/tag/obfs/obfs_host/obfs_uri/udp_relay/udp_over_tcp/fast_open/aead/server_check_url/reality_base64_pubkey/reality_hex_shortid/others)* {
    proxy.type = "vmess";
    proxy.cipher = proxy.cipher || "none";
    if (proxy.aead === false) {
        proxy.alterId = 1;
    } else {
        proxy.alterId = 0;
    }
    handleObfs();
}

vless = "vless" equals address
    (uuid/method/over_tls/tls_host/tls_pubkey_sha256/tls_alpn/tls_no_session_ticket/tls_no_session_reuse/tls_fingerprint/tls_verification/tag/obfs/obfs_host/obfs_uri/udp_relay/udp_over_tcp/fast_open/aead/server_check_url/reality_base64_pubkey/reality_hex_shortid/vless_flow/others)* {
    proxy.type = "vless";
    proxy.cipher = proxy.cipher || "none";
    handleObfs();
}

http = "http" equals address 
    (username/password/over_tls/tls_host/tls_pubkey_sha256/tls_alpn/tls_no_session_ticket/tls_no_session_reuse/tls_fingerprint/tls_verification/tag/fast_open/udp_relay/udp_over_tcp/server_check_url/reality_base64_pubkey/reality_hex_shortid/others)*{
    proxy.type = "http";
}

socks5 = "socks5" equals address
    (username/password/password/over_tls/tls_host/tls_pubkey_sha256/tls_alpn/tls_no_session_ticket/tls_no_session_reuse/tls_fingerprint/tls_verification/tag/fast_open/udp_relay/udp_over_tcp/server_check_url/reality_base64_pubkey/reality_hex_shortid/others)* {
    proxy.type = "socks5";
}
    
address = server:server ":" port:port {
    proxy.server = server;
    proxy.port = port;
}
server = ip/domain

domain = match:[0-9a-zA-z-_.]+ { 
    const domain = match.join(""); 
    if (/(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z0-9][a-z0-9-]{0,61}[a-z0-9]/.test(domain)) {
        return domain;
    }
}

ip = & {
    const start = peg$currPos;
    let end;
    let j = start;
    while (j < input.length) {
        if (input[j] === ",") break;
        if (input[j] === ":") end = j;
        j++;
    }
    peg$currPos = end || j;
    $.ip = input.substring(start, end).trim();
    return true;
} { return $.ip; }

port = digits:[0-9]+ { 
    const port = parseInt(digits.join(""), 10); 
    if (port >= 0 && port <= 65535) {
    	return port;
    }
}

username = comma "username" equals username:[^,]+ { proxy.username = username.join("").trim(); }
password = comma "password" equals password:[^,]+ { proxy.password = password.join("").trim(); }
uuid = comma "password" equals uuid:[^,]+ { proxy.uuid = uuid.join("").trim(); }

method = comma "method" equals cipher:cipher { 
    proxy.cipher = cipher;
};
cipher = ("aes-128-cfb"/"aes-128-ctr"/"aes-128-gcm"/"aes-192-cfb"/"aes-192-ctr"/"aes-192-gcm"/"aes-256-cfb"/"aes-256-ctr"/"aes-256-gcm"/"bf-cfb"/"cast5-cfb"/"chacha20-ietf-poly1305"/"chacha20-ietf"/"chacha20-poly1305"/"chacha20"/"des-cfb"/"none"/"rc2-cfb"/"rc4-md5-6"/"rc4-md5"/"salsa20"/"xchacha20-ietf-poly1305"/"2022-blake3-aes-128-gcm"/"2022-blake3-aes-256-gcm");
aead = comma "aead" equals flag:bool { proxy.aead = flag; }

udp_relay = comma "udp-relay" equals flag:bool { proxy.udp = flag; }
udp_over_tcp = comma "udp-over-tcp" equals flag:bool { throw new Error("UDP over TCP is not supported"); }
udp_over_tcp_new = comma "udp-over-tcp" equals param:$[^=,]+ { if (param === "sp.v1") { proxy["udp-over-tcp"] = true; proxy["udp-over-tcp-version"] = 1; } else if (param === "sp.v2") { proxy["udp-over-tcp"] = true; proxy["udp-over-tcp-version"] = 2; } else if (param === "true") { proxy["_ssr_python_uot"] = true; } else { throw new Error("Invalid value for udp-over-tcp"); } }

fast_open = comma "fast-open" equals flag:bool { proxy.tfo = flag; }

over_tls = comma "over-tls" equals flag:bool { proxy.tls = flag; }
tls_host = comma sni:("tls-host") equals match:[^,]+ { proxy.sni = match.join("").replace(/^"(.*)"$/, '$1'); }
tls_verification = comma "tls-verification" equals flag:bool { 
    proxy["skip-cert-verify"] = !flag;
}
tls_fingerprint = comma "tls-cert-sha256" equals tls_fingerprint:$[^,]+ { proxy["tls-fingerprint"] = tls_fingerprint.trim(); }
tls_pubkey_sha256 = comma "tls-pubkey-sha256" equals param:$[^=,]+ { proxy["tls-pubkey-sha256"] = param; }
tls_alpn = comma "tls-alpn" equals param:$[^=,]+ { proxy["tls-alpn"] = param; }
tls_no_session_ticket = comma "tls-no-session-ticket" equals flag:bool { 
    proxy["tls-no-session-ticket"] = flag;
}
tls_no_session_reuse = comma "tls-no-session-reuse" equals flag:bool { 
    proxy["tls-no-session-reuse"] = flag;
}

obfs_ss = comma "obfs" equals type:("http"/"tls"/"wss"/"ws"/"over-tls") { obfs.type = type; return type; }
obfs_ssr = comma "obfs" equals type:("plain"/"http_simple"/"http_post"/"random_head"/"tls1.2_ticket_auth"/"tls1.2_ticket_fastauth") { proxy.type = "ssr"; obfs.type = type; return type; }
obfs = comma "obfs" equals type:("wss"/"ws"/"over-tls"/"http") { obfs.type = type; return type; };

obfs_host = comma "obfs-host" equals match:[^,]+ { obfs.host = match.join("").replace(/^"(.*)"$/, '$1'); }
obfs_uri = comma "obfs-uri" equals uri:uri { obfs.path = uri; }

ssr_protocol = comma "ssr-protocol" equals protocol:("origin"/"auth_sha1_v4"/"auth_aes128_md5"/"auth_aes128_sha1"/"auth_chain_a"/"auth_chain_b") { proxy.protocol = protocol; return protocol; }
ssr_protocol_param = comma "ssr-protocol-param" equals param:$[^=,]+ { proxy["protocol-param"] = param; }

reality_base64_pubkey = comma "reality-base64-pubkey" equals param:$[^=,]+ {
    $set(proxy, "reality-opts.public-key", param);
 }
reality_hex_shortid = comma "reality-hex-shortid" equals param:$[^=,]+ {
    $set(proxy, "reality-opts.short-id", param);
}
vless_flow = comma "vless-flow" equals param:$[^=,]+ { proxy["flow"] = param; }
server_check_url = comma "server_check_url" equals param:$[^=,]+ { proxy["test-url"] = param; }

uri = $[^,]+

tag = comma "tag" equals tag:[^=,]+ { proxy.name = tag.join(""); }
others = comma [^=,]+ equals [^=,]+
comma = _ "," _
equals = _ "=" _
_ = [ \r\t]*
bool = b:("true"/"false") { return b === "true" }

================================================
FILE: backend/src/core/proxy-utils/parsers/peggy/surge.js
================================================
import * as peggy from 'peggy';
const grammars = String.raw`
// global initializer
{{
    function $set(obj, path, value) {
      if (Object(obj) !== obj) return obj;
      if (!Array.isArray(path)) path = path.toString().match(/[^.[\]]+/g) || [];
      path
        .slice(0, -1)
        .reduce((a, c, i) => (Object(a[c]) === a[c] ? a[c] : (a[c] = Math.abs(path[i + 1]) >> 0 === +path[i + 1] ? [] : {})), obj)[
        path[path.length - 1]
      ] = value;
      return obj;
    }
}}

// per-parser initializer
{
    const proxy = {};
    const obfs = {};
    const $ = {};

    function handleWebsocket() {
        if (obfs.type === "ws") {
            proxy.network = "ws";
            $set(proxy, "ws-opts.path", obfs.path);
            $set(proxy, "ws-opts.headers", obfs['ws-headers']);
            if (proxy['ws-opts'] && proxy['ws-opts']['headers'] && proxy['ws-opts']['headers'].Host) {
                proxy['ws-opts']['headers'].Host = proxy['ws-opts']['headers'].Host.replace(/^"(.*)"$/, '$1')
            }
        }
    }
    function handleShadowTLS() {
        if (proxy['shadow-tls-password'] && !proxy['shadow-tls-version']) {
            proxy['shadow-tls-version'] = 2;
        }
    }
}

start = (anytls/shadowsocks/vmess/trojan/https/http/snell/socks5/socks5_tls/tuic/tuic_v5/wireguard/hysteria2/ssh/trust_tunnel/direct) {
    return proxy;
}

shadowsocks = tag equals "ss" address (method/passwordk/obfs/obfs_host/obfs_uri/ip_version/underlying_proxy/tos/allow_other_interface/interface/test_url/test_udp/test_timeout/hybrid/no_error_alert/fast_open/tfo/udp_relay/shadow_tls_version/shadow_tls_sni/shadow_tls_password/block_quic/udp_port/others)* {
    proxy.type = "ss";
    // handle obfs
    if (obfs.type == "http" || obfs.type === "tls") {
        proxy.plugin = "obfs";
        $set(proxy, "plugin-opts.mode", obfs.type);
        $set(proxy, "plugin-opts.host", obfs.host);
        $set(proxy, "plugin-opts.path", obfs.path);
    }
    handleShadowTLS();
}
vmess = tag equals "vmess" address (vmess_uuid/vmess_aead/ws/ws_path/ws_headers/method/ip_version/underlying_proxy/tos/allow_other_interface/interface/test_url/test_udp/test_timeout/hybrid/no_error_alert/tls/sni/tls_fingerprint/tls_verification/fast_open/tfo/udp_relay/shadow_tls_version/shadow_tls_sni/shadow_tls_password/block_quic/others)* {
    proxy.type = "vmess";
    proxy.cipher = proxy.cipher || "none";
    // Surfboard 与 Surge 默认不一致, 不管 Surfboard https://getsurfboard.com/docs/profile-format/proxy/external-proxy/vmess
    if (proxy.aead) {
        proxy.alterId = 0;
    } else {
        proxy.alterId = 1;
    }
    handleWebsocket();
    handleShadowTLS();
}
trojan = tag equals "trojan" address (passwordk/ws/ws_path/ws_headers/tls/sni/tls_fingerprint/tls_verification/ip_version/underlying_proxy/tos/allow_other_interface/interface/test_url/test_udp/test_timeout/hybrid/no_error_alert/fast_open/tfo/udp_relay/shadow_tls_version/shadow_tls_sni/shadow_tls_password/block_quic/others)* {
    proxy.type = "trojan";
    handleWebsocket();
    handleShadowTLS();
}
https = tag equals "https" address (username password)? (usernamek passwordk)? (sni/tls_fingerprint/tls_verification/ip_version/underlying_proxy/tos/allow_other_interface/interface/test_url/test_udp/test_timeout/hybrid/no_error_alert/fast_open/tfo/shadow_tls_version/shadow_tls_sni/shadow_tls_password/block_quic/others)* {
    proxy.type = "http";
    proxy.tls = true;
    handleShadowTLS();
}
http = tag equals "http" address (username password)? (usernamek passwordk)? (ip_version/underlying_proxy/tos/allow_other_interface/interface/test_url/test_udp/test_timeout/hybrid/no_error_alert/fast_open/tfo/shadow_tls_version/shadow_tls_sni/shadow_tls_password/block_quic/others)* {
    proxy.type = "http";
    handleShadowTLS();
}
ssh = tag equals "ssh" address (username password)? (usernamek passwordk)? (server_fingerprint/idle_timeout/private_key/ip_version/underlying_proxy/tos/allow_other_interface/interface/test_url/test_udp/test_timeout/hybrid/no_error_alert/fast_open/tfo/shadow_tls_version/shadow_tls_sni/shadow_tls_password/block_quic/others)* {
    proxy.type = "ssh";
    handleShadowTLS();
}
snell = tag equals "snell" address (snell_version/snell_psk/obfs/obfs_host/obfs_uri/ip_version/underlying_proxy/tos/allow_other_interface/interface/test_url/test_udp/test_timeout/hybrid/no_error_alert/fast_open/tfo/udp_relay/reuse/shadow_tls_version/shadow_tls_sni/shadow_tls_password/block_quic/others)* {
    proxy.type = "snell";
    // handle obfs
    if (obfs.type == "http" || obfs.type === "tls") {
        $set(proxy, "obfs-opts.mode", obfs.type);
        $set(proxy, "obfs-opts.host", obfs.host);
        $set(proxy, "obfs-opts.path", obfs.path);
    }
    handleShadowTLS();
}
tuic = tag equals "tuic" address (alpn/token/ip_version/underlying_proxy/tos/allow_other_interface/interface/test_url/test_udp/test_timeout/hybrid/no_error_alert/tls_fingerprint/tls_verification/sni/fast_open/tfo/ecn/shadow_tls_version/shadow_tls_sni/shadow_tls_password/block_quic/port_hopping_interval/others)* {
    proxy.type = "tuic";
    handleShadowTLS();
}
tuic_v5 = tag equals "tuic-v5" address (alpn/passwordk/uuidk/ip_version/underlying_proxy/tos/allow_other_interface/interface/test_url/test_udp/test_timeout/hybrid/no_error_alert/tls_fingerprint/tls_verification/sni/fast_open/tfo/ecn/shadow_tls_version/shadow_tls_sni/shadow_tls_password/block_quic/port_hopping_interval/others)* {
    proxy.type = "tuic";
    proxy.version = 5;
    handleShadowTLS();
}
wireguard = tag equals "wireguard" (section_name/no_error_alert/ip_version/underlying_proxy/tos/allow_other_interface/interface/test_url/test_udp/test_timeout/hybrid/shadow_tls_version/shadow_tls_sni/shadow_tls_password/block_quic/others)* {
    proxy.type = "wireguard-surge";
    handleShadowTLS();
}
hysteria2 = tag equals "hysteria2" address (no_error_alert/ip_version/underlying_proxy/tos/allow_other_interface/interface/test_url/test_udp/test_timeout/hybrid/sni/tls_verification/passwordk/tls_fingerprint/download_bandwidth/ecn/shadow_tls_version/shadow_tls_sni/shadow_tls_password/block_quic/port_hopping_interval/salamander_password/others)* {
    proxy.type = "hysteria2";
    handleShadowTLS();
}
socks5 = tag equals "socks5" address (username password)? (usernamek passwordk)? (udp_relay/no_error_alert/ip_version/underlying_proxy/tos/allow_other_interface/interface/test_url/test_udp/test_timeout/hybrid/fast_open/tfo/shadow_tls_version/shadow_tls_sni/shadow_tls_password/block_quic/others)* {
    proxy.type = "socks5";
    handleShadowTLS();
}
socks5_tls = tag equals "socks5-tls" address (username password)? (usernamek passwordk)? (udp_relay/no_error_alert/ip_version/underlying_proxy/tos/allow_other_interface/interface/test_url/test_udp/test_timeout/hybrid/sni/tls_fingerprint/tls_verification/fast_open/tfo/shadow_tls_version/shadow_tls_sni/shadow_tls_password/block_quic/others)* {
    proxy.type = "socks5";
    proxy.tls = true;
    handleShadowTLS();
}
anytls = tag equals "anytls" address (passwordk/reuse/ip_version/underlying_proxy/tos/allow_other_interface/interface/test_url/test_udp/test_timeout/hybrid/no_error_alert/tls_fingerprint/tls_verification/sni/fast_open/tfo/block_quic/others)* {
    proxy.type = "anytls";
    proxy.tls = true;
}
trust_tunnel = tag equals "trust-tunnel" address (usernamek/passwordk/reuse/ip_version/underlying_proxy/tos/allow_other_interface/interface/test_url/test_udp/test_timeout/hybrid/no_error_alert/tls_fingerprint/tls_verification/sni/fast_open/tfo/block_quic/others)* {
    proxy.type = "trusttunnel";
    proxy.tls = true;
}

direct = tag equals "direct" (udp_relay/ip_version/underlying_proxy/tos/allow_other_interface/interface/test_url/test_udp/test_timeout/hybrid/no_error_alert/fast_open/tfo/block_quic/others)* {
    proxy.type = "direct";
}
address = comma server:server comma port:port {
    proxy.server = server;
    proxy.port = port;
}

server = ip/domain

ip = & {
    const start = peg$currPos;
    let j = start;
    while (j < input.length) {
        if (input[j] === ",") break;
        j++;
    }
    peg$currPos = j;
    $.ip = input.substring(start, j).trim();
    return true;
} { return $.ip; }

domain = match:[0-9a-zA-z-_.]+ { 
    const domain = match.join(""); 
    if (/(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z0-9][a-z0-9-]{0,61}[a-z0-9]/.test(domain)) {
        return domain;
    }
}

port = digits:[0-9]+ { 
    const port = parseInt(digits.join(""), 10); 
    if (port >= 0 && port <= 65535) {
    	return port;
    }
}

port_hopping_interval = comma "port-hopping-interval" equals match:$[0-9]+ { proxy["hop-interval"] = parseInt(match.trim()); }

username = & {
    let j = peg$currPos; 
    let start, end;
    let first = true;
    while (j < input.length) {
        if (input[j] === ',') {
            if (first) {
                start = j + 1;
                first = false;
            } else {
                end = j;
                break;
            }
        }
        j++;
    }
    const match = input.substring(start, end);
    if (match.indexOf("=") === -1) {
        $.username = match;
        peg$currPos = end;
        return true;
    }
} { proxy.username = $.username.trim().replace(/^"(.*?)"$/, '$1').replace(/^'(.*?)'$/, '$1'); }
password = comma match:[^,]+ { proxy.password = match.join("").replace(/^"(.*)"$/, '$1').replace(/^'(.*?)'$/, '$1'); }

tls = comma "tls" equals flag:bool { proxy.tls = flag; }
sni = comma "sni" equals match:[^,]+ { 
    const sni = match.join("").replace(/^"(.*)"$/, '$1');
    if (sni === "off") {
        proxy["disable-sni"] = true;
    } else {
        proxy.sni = sni;
    }
}
tls_verification = comma "skip-cert-verify" equals flag:bool { proxy["skip-cert-verify"] = flag; }
tls_fingerprint = comma "server-cert-fingerprint-sha256" equals tls_fingerprint:$[^,]+ { proxy["tls-fingerprint"] = tls_fingerprint.trim(); }

snell_psk = comma "psk" equals match:[^,]+ { proxy.psk = match.join(""); }
snell_version = comma "version" equals match:$[0-9]+ { proxy.version = parseInt(match.trim()); }

usernamek = comma "username" equals match:[^,]+ { proxy.username = match.join("").replace(/^"(.*?)"$/, '$1').replace(/^'(.*?)'$/, '$1'); }
passwordk = comma "password" equals match:[^,]+ { proxy.password = match.join("").replace(/^"(.*?)"$/, '$1').replace(/^'(.*?)'$/, '$1'); }
vmess_uuid = comma "username" equals match:[^,]+ { proxy.uuid = match.join(""); }
vmess_aead = comma "vmess-aead" equals flag:bool { proxy.aead = flag; }

method = comma "encrypt-method" equals cipher:cipher {
    proxy.cipher = cipher;
}
cipher = ("aes-128-cfb"/"aes-128-ctr"/"aes-128-gcm"/"aes-192-cfb"/"aes-192-ctr"/"aes-192-gcm"/"aes-256-cfb"/"aes-256-ctr"/"aes-256-gcm"/"bf-cfb"/"camellia-128-cfb"/"camellia-192-cfb"/"camellia-256-cfb"/"cast5-cfb"/"chacha20-ietf-poly1305"/"chacha20-ietf"/"chacha20-poly1305"/"chacha20"/"des-cfb"/"idea-cfb"/"none"/"rc2-cfb"/"rc4-md5"/"rc4"/"salsa20"/"seed-cfb"/"xchacha20-ietf-poly1305"/"2022-blake3-aes-128-gcm"/"2022-blake3-aes-256-gcm");

ws = comma "ws" equals flag:bool { obfs.type = "ws"; }
ws_headers = comma "ws-headers" equals headers:$[^,]+ {
    const pairs = headers.split("|");
    const result = {};
    pairs.forEach(pair => {
        const [key, value] = pair.trim().split(":");
        result[key.trim()] = value.trim().replace(/^"(.*?)"$/, '$1').replace(/^'(.*?)'$/, '$1');
    })
    obfs["ws-headers"] = result;
}
ws_path = comma "ws-path" equals path:uri { obfs.path = path.trim().replace(/^"(.*?)"$/, '$1').replace(/^'(.*?)'$/, '$1'); }

obfs = comma "obfs" equals type:("http"/"tls") { obfs.type = type; }
obfs_host = comma "obfs-host" equals match:[^,]+ { obfs.host = match.join("").replace(/^"(.*)"$/, '$1'); };
obfs_uri = comma "obfs-uri" equals path:uri { obfs.path = path }
uri = $[^,]+

udp_relay = comma "udp-relay" equals flag:bool { proxy.udp = flag; }
fast_open = comma "fast-open" equals flag:bool { proxy.tfo = flag; }
reuse = comma "reuse" equals flag:bool { proxy.reuse = flag; }
ecn = comma "ecn" equals flag:bool { proxy.ecn = flag; }
tfo = comma "tfo" equals flag:bool { proxy.tfo = flag; }
ip_version = comma "ip-version" equals match:[^,]+ { proxy["ip-version"] = match.join(""); }
section_name = comma "section-name" equals match:[^,]+ { proxy["section-name"] = match.join(""); }
no_error_alert = comma "no-error-alert" equals match:[^,]+ { proxy["no-error-alert"] = match.join(""); }
underlying_proxy = comma "underlying-proxy" equals match:[^,]+ { proxy["underlying-proxy"] = match.join(""); }
download_bandwidth = comma "download-bandwidth" equals match:[^,]+ { proxy.down = match.join(""); }
test_url = comma "test-url" equals match:[^,]+ { proxy["test-url"] = match.join(""); }
test_udp = comma "test-udp" equals match:[^,]+ { proxy["test-udp"] = match.join(""); }
test_timeout = comma "test-timeout" equals match:$[0-9]+ { proxy["test-timeout"] = parseInt(match.trim()); }
tos = comma "tos" equals match:$[0-9]+ { proxy.tos = parseInt(match.trim()); }
interface = comma "interface" equals match:[^,]+ { proxy.interface = match.join(""); }
allow_other_interface = comma "allow-other-interface" equals flag:bool { proxy["allow-other-interface"] = flag; }
hybrid = comma "hybrid" equals flag:bool { proxy.hybrid = flag; }
idle_timeout = comma "idle-timeout" equals match:$[0-9]+ { proxy["idle-timeout"] = parseInt(match.trim()); }
private_key = comma "private-key" equals match:[^,]+ { proxy["keystore-private-key"] = match.join("").replace(/^"(.*)"$/, '$1'); }
server_fingerprint = comma "server-fingerprint" equals match:[^,]+ { proxy["server-fingerprint"] = match.join("").replace(/^"(.*)"$/, '$1'); }
block_quic = comma "block-quic" equals match:[^,]+ { proxy["block-quic"] = match.join(""); }
udp_port = comma "udp-port" equals match:$[0-9]+ { proxy["udp-port"] = parseInt(match.trim()); }
shadow_tls_version = comma "shadow-tls-version" equals match:$[0-9]+ { proxy["shadow-tls-version"] = parseInt(match.trim()); }
shadow_tls_sni = comma "shadow-tls-sni" equals match:[^,]+ { proxy["shadow-tls-sni"] = match.join(""); }
shadow_tls_password = comma "shadow-tls-password" equals match:[^,]+ { proxy["shadow-tls-password"] = ma
Download .txt
gitextract_j4ptg362/

├── .github/
│   └── workflows/
│       └── main.yml
├── .gitignore
├── LICENSE
├── README.md
├── backend/
│   ├── .babelrc
│   ├── .eslintrc.json
│   ├── .prettierrc.json
│   ├── banner
│   ├── bundle-esbuild.js
│   ├── bundle.js
│   ├── dev-esbuild.js
│   ├── dist/
│   │   └── .gitkeep
│   ├── gulpfile.babel.js
│   ├── jsconfig.json
│   ├── package.json
│   ├── patches/
│   │   └── http-proxy@1.18.1.patch
│   └── src/
│       ├── constants.js
│       ├── core/
│       │   ├── app.js
│       │   ├── proxy-utils/
│       │   │   ├── index.js
│       │   │   ├── parsers/
│       │   │   │   ├── index.js
│       │   │   │   └── peggy/
│       │   │   │       ├── loon.js
│       │   │   │       ├── loon.peg
│       │   │   │       ├── qx.js
│       │   │   │       ├── qx.peg
│       │   │   │       ├── surge.js
│       │   │   │       ├── surge.peg
│       │   │   │       ├── trojan-uri.js
│       │   │   │       └── trojan-uri.peg
│       │   │   ├── preprocessors/
│       │   │   │   └── index.js
│       │   │   ├── processors/
│       │   │   │   └── index.js
│       │   │   ├── producers/
│       │   │   │   ├── clash.js
│       │   │   │   ├── clashmeta.js
│       │   │   │   ├── egern.js
│       │   │   │   ├── index.js
│       │   │   │   ├── loon.js
│       │   │   │   ├── qx.js
│       │   │   │   ├── shadowrocket.js
│       │   │   │   ├── sing-box.js
│       │   │   │   ├── stash.js
│       │   │   │   ├── surfboard.js
│       │   │   │   ├── surge.js
│       │   │   │   ├── surgemac.js
│       │   │   │   ├── uri.js
│       │   │   │   ├── utils.js
│       │   │   │   └── v2ray.js
│       │   │   └── validators/
│       │   │       └── index.js
│       │   └── rule-utils/
│       │       ├── index.js
│       │       ├── parsers.js
│       │       ├── preprocessors.js
│       │       └── producers.js
│       ├── main.js
│       ├── products/
│       │   ├── cron-sync-artifacts.js
│       │   ├── resource-parser.loon.js
│       │   ├── sub-store-0.js
│       │   └── sub-store-1.js
│       ├── restful/
│       │   ├── artifacts.js
│       │   ├── collections.js
│       │   ├── download.js
│       │   ├── errors/
│       │   │   └── index.js
│       │   ├── file.js
│       │   ├── index.js
│       │   ├── miscs.js
│       │   ├── module.js
│       │   ├── node-info.js
│       │   ├── parser.js
│       │   ├── preview.js
│       │   ├── response.js
│       │   ├── settings.js
│       │   ├── sort.js
│       │   ├── subscriptions.js
│       │   ├── sync.js
│       │   └── token.js
│       ├── test/
│       │   └── proxy-parsers/
│       │       ├── loon.spec.js
│       │       ├── qx.spec.js
│       │       ├── surge.spec.js
│       │       └── testcases.js
│       ├── utils/
│       │   ├── database.js
│       │   ├── dns.js
│       │   ├── download.js
│       │   ├── env.js
│       │   ├── flow.js
│       │   ├── geo.js
│       │   ├── gist.js
│       │   ├── headers-resource-cache.js
│       │   ├── index.js
│       │   ├── logical.js
│       │   ├── migration.js
│       │   ├── resource-cache.js
│       │   ├── rs.js
│       │   ├── script-resource-cache.js
│       │   ├── user-agent.js
│       │   └── yaml.js
│       └── vendor/
│           ├── express.js
│           ├── md5.js
│           └── open-api.js
├── config/
│   ├── Egern.yaml
│   ├── Loon.plugin
│   ├── QX-Task.json
│   ├── QX.snippet
│   ├── README.md
│   ├── Stash.stoverride
│   ├── Surge-Beta.sgmodule
│   ├── Surge-Noability.sgmodule
│   ├── Surge-ability.sgmodule
│   └── Surge.sgmodule
├── scripts/
│   ├── demo.js
│   ├── fancy-characters.js
│   ├── ip-flag-node.js
│   ├── ip-flag.js
│   ├── media-filter.js
│   ├── revert.js
│   ├── tls-fingerprint.js
│   ├── udp-filter.js
│   └── vmess-ws-obfs-host.js
└── vs.code-workspace
Download .txt
SYMBOL INDEX (473 symbols across 76 files)

FILE: backend/gulpfile.babel.js
  function peggy (line 13) | function peggy() {
  function lint (line 34) | function lint() {
  function styles (line 43) | function styles() {
  function scripts (line 57) | function scripts(src, dest) {
  function banner (line 82) | function banner(dest) {

FILE: backend/src/constants.js
  constant SCHEMA_VERSION_KEY (line 1) | const SCHEMA_VERSION_KEY = 'schemaVersion';
  constant SETTINGS_KEY (line 2) | const SETTINGS_KEY = 'settings';
  constant SUBS_KEY (line 3) | const SUBS_KEY = 'subs';
  constant COLLECTIONS_KEY (line 4) | const COLLECTIONS_KEY = 'collections';
  constant FILES_KEY (line 5) | const FILES_KEY = 'files';
  constant MODULES_KEY (line 6) | const MODULES_KEY = 'modules';
  constant ARTIFACTS_KEY (line 7) | const ARTIFACTS_KEY = 'artifacts';
  constant RULES_KEY (line 8) | const RULES_KEY = 'rules';
  constant TOKENS_KEY (line 9) | const TOKENS_KEY = 'tokens';
  constant GIST_BACKUP_KEY (line 10) | const GIST_BACKUP_KEY = 'Auto Generated Sub-Store Backup';
  constant GIST_BACKUP_FILE_NAME (line 11) | const GIST_BACKUP_FILE_NAME = 'Sub-Store';
  constant ARTIFACT_REPOSITORY_KEY (line 12) | const ARTIFACT_REPOSITORY_KEY = 'Sub-Store Artifacts Repository';
  constant RESOURCE_CACHE_KEY (line 13) | const RESOURCE_CACHE_KEY = '#sub-store-cached-resource';
  constant HEADERS_RESOURCE_CACHE_KEY (line 14) | const HEADERS_RESOURCE_CACHE_KEY = '#sub-store-cached-headers-resource';
  constant SCRIPT_RESOURCE_CACHE_KEY (line 15) | const SCRIPT_RESOURCE_CACHE_KEY = '#sub-store-cached-script-resource';
  constant DEFAULT_CACHE_TTL (line 16) | const DEFAULT_CACHE_TTL = 60 * 60 * 1000;
  constant DEFAULT_HEADERS_CACHE_TTL (line 17) | const DEFAULT_HEADERS_CACHE_TTL = 60 * 1000;
  constant DEFAULT_SCRIPT_CACHE_TTL (line 18) | const DEFAULT_SCRIPT_CACHE_TTL = 48 * 3600 * 1000;

FILE: backend/src/core/proxy-utils/index.js
  function preprocess (line 30) | function preprocess(raw) {
  function parse (line 44) | function parse(raw) {
  function processFn (line 95) | async function processFn(
  function produce (line 237) | function produce(proxies, targetPlatform, type, opts = {}) {
  function tryParse (line 357) | function tryParse(parser, line) {
  function safeMatch (line 367) | function safeMatch(parser, line) {
  function formatTransportPath (line 375) | function formatTransportPath(path) {
  function lastParse (line 388) | function lastParse(proxy) {
  function isIP (line 704) | function isIP(ip) {

FILE: backend/src/core/proxy-utils/parsers/index.js
  function surge_port_hopping (line 21) | function surge_port_hopping(raw) {
  function URI_PROXY (line 34) | function URI_PROXY() {
  function URI_SOCKS (line 82) | function URI_SOCKS() {
  function URI_SS (line 124) | function URI_SS() {
  function URI_SSR (line 364) | function URI_SSR() {
  function URI_VMess (line 433) | function URI_VMess() {
  function URI_VLESS (line 676) | function URI_VLESS() {
  function URI_AnyTLS (line 851) | function URI_AnyTLS() {
  function URI_Hysteria2 (line 908) | function URI_Hysteria2() {
  function URI_Hysteria (line 1006) | function URI_Hysteria() {
  function URI_TUIC (line 1077) | function URI_TUIC() {
  function URI_WireGuard (line 1135) | function URI_WireGuard() {
  function URI_Trojan (line 1222) | function URI_Trojan() {
  function Clash_All (line 1249) | function Clash_All() {
  function QX_SS (line 1324) | function QX_SS() {
  function QX_SSR (line 1339) | function QX_SSR() {
  function QX_VMess (line 1351) | function QX_VMess() {
  function QX_VLESS (line 1360) | function QX_VLESS() {
  function QX_Trojan (line 1369) | function QX_Trojan() {
  function QX_Http (line 1378) | function QX_Http() {
  function QX_Socks5 (line 1387) | function QX_Socks5() {
  function Loon_SS (line 1396) | function Loon_SS() {
  function Loon_SSR (line 1408) | function Loon_SSR() {
  function Loon_VMess (line 1420) | function Loon_VMess() {
  function Loon_Vless (line 1433) | function Loon_Vless() {
  function Loon_Trojan (line 1442) | function Loon_Trojan() {
  function Loon_AnyTLS (line 1451) | function Loon_AnyTLS() {
  function Loon_Hysteria2 (line 1460) | function Loon_Hysteria2() {
  function Loon_Http (line 1470) | function Loon_Http() {
  function Loon_Socks5 (line 1479) | function Loon_Socks5() {
  function Loon_WireGuard (line 1489) | function Loon_WireGuard() {
  function Surge_Direct (line 1597) | function Surge_Direct() {
  function Surge_AnyTLS (line 1605) | function Surge_AnyTLS() {
  function Surge_TrustTunnel (line 1613) | function Surge_TrustTunnel() {
  function Surge_SSH (line 1621) | function Surge_SSH() {
  function Surge_SS (line 1629) | function Surge_SS() {
  function Surge_VMess (line 1638) | function Surge_VMess() {
  function Surge_Trojan (line 1650) | function Surge_Trojan() {
  function Surge_Http (line 1659) | function Surge_Http() {
  function Surge_Socks5 (line 1668) | function Surge_Socks5() {
  function Surge_External (line 1677) | function Surge_External() {
  function Surge_Snell (line 1750) | function Surge_Snell() {
  function Surge_Tuic (line 1759) | function Surge_Tuic() {
  function Surge_WireGuard (line 1772) | function Surge_WireGuard() {
  function Surge_Hysteria2 (line 1781) | function Surge_Hysteria2() {
  function isIP (line 1795) | function isIP(ip) {

FILE: backend/src/core/proxy-utils/parsers/peggy/loon.js
  function getParser (line 217) | function getParser() {

FILE: backend/src/core/proxy-utils/parsers/peggy/qx.js
  function getParser (line 209) | function getParser() {

FILE: backend/src/core/proxy-utils/parsers/peggy/surge.js
  function getParser (line 273) | function getParser() {

FILE: backend/src/core/proxy-utils/parsers/peggy/trojan-uri.js
  function getParser (line 163) | function getParser() {

FILE: backend/src/core/proxy-utils/preprocessors/index.js
  function HTML (line 5) | function HTML() {
  function Base64Encoded (line 13) | function Base64Encoded() {
  function fallbackBase64Encoded (line 53) | function fallbackBase64Encoded() {
  function Clash (line 73) | function Clash() {
  function SSD (line 121) | function SSD() {
  function FullConfig (line 165) | function FullConfig() {

FILE: backend/src/core/proxy-utils/processors/index.js
  function isObject (line 26) | function isObject(item) {
  function trimWrap (line 29) | function trimWrap(str) {
  function deepMerge (line 35) | function deepMerge(target, _other) {
  function ConditionalFilter (line 85) | function ConditionalFilter({ rule }) {
  function isMatch (line 94) | function isMatch(rule, proxy) {
  function QuickSettingOperator (line 128) | function QuickSettingOperator(args) {
  function FlagOperator (line 169) | function FlagOperator({ mode, tw }) {
  function HandleDuplicateOperator (line 198) | function HandleDuplicateOperator(arg) {
  function SortOperator (line 271) | function SortOperator(order = 'asc') {
  function RegexSortOperator (line 293) | function RegexSortOperator(input) {
  function getRegexOrder (line 324) | function getRegexOrder(expressions, str) {
  function RegexRenameOperator (line 337) | function RegexRenameOperator(regex) {
  function RegexDeleteOperator (line 355) | function RegexDeleteOperator(regex) {
  function ScriptOperator (line 380) | function ScriptOperator(
  function parseIP4P (line 500) | function parseIP4P(IP4P) {
  constant DOMAIN_RESOLVERS (line 527) | const DOMAIN_RESOLVERS = {
  function ResolveDomainOperator (line 688) | function ResolveDomainOperator({
  function isIP (line 833) | function isIP(ip) {
  function isAscii (line 839) | function isAscii(str) {
  function UselessFilter (line 847) | function UselessFilter() {
  function RegionFilter (line 882) | function RegionFilter(input) {
  function RegexFilter (line 912) | function RegexFilter({ regex = [], keep = true }) {
  function buildRegex (line 926) | function buildRegex(str, ...options) {
  function TypeFilter (line 937) | function TypeFilter(input) {
  function ScriptFilter (line 967) | function ScriptFilter(
  function ApplyFilter (line 1037) | async function ApplyFilter(filter, objs) {
  function ApplyOperator (line 1073) | async function ApplyOperator(operator, objs) {
  function ApplyProcessor (line 1116) | async function ApplyProcessor(processor, objs) {
  function shuffle (line 1125) | function shuffle(array) {
  function clone (line 1146) | function clone(object) {
  function createDynamicFunction (line 1150) | function createDynamicFunction(name, script, $arguments, $options) {

FILE: backend/src/core/proxy-utils/producers/clash.js
  function Clash_Producer (line 4) | function Clash_Producer() {

FILE: backend/src/core/proxy-utils/producers/clashmeta.js
  function ClashMeta_Producer (line 11) | function ClashMeta_Producer() {

FILE: backend/src/core/proxy-utils/producers/egern.js
  function Egern_Producer (line 3) | function Egern_Producer() {

FILE: backend/src/core/proxy-utils/producers/index.js
  function JSON_Producer (line 15) | function JSON_Producer() {

FILE: backend/src/core/proxy-utils/producers/loon.js
  function Loon_Producer (line 15) | function Loon_Producer() {
  function shadowsocks (line 54) | function shadowsocks(proxy) {
  function shadowsocksr (line 190) | function shadowsocksr(proxy) {
  function trojan (line 267) | function trojan(proxy) {
  function anytls (line 329) | function anytls(proxy) {
  function vmess (line 384) | function vmess(proxy) {
  function vless (line 483) | function vless(proxy) {
  function http (line 589) | function http(proxy) {
  function socks5 (line 620) | function socks5(proxy) {
  function wireguard (line 658) | function wireguard(proxy) {
  function hysteria2 (line 732) | function hysteria2(proxy) {

FILE: backend/src/core/proxy-utils/producers/qx.js
  function QX_Producer (line 5) | function QX_Producer() {
  function shadowsocks (line 57) | function shadowsocks(proxy) {
  function shadowsocksr (line 185) | function shadowsocksr(proxy) {
  function trojan (line 223) | function trojan(proxy) {
  function vmess (line 300) | function vmess(proxy) {
  function vless (line 405) | function vless(proxy) {
  function http (line 507) | function http(proxy) {
  function socks5 (line 568) | function socks5(proxy) {
  function needTls (line 629) | function needTls(proxy) {

FILE: backend/src/core/proxy-utils/producers/shadowrocket.js
  function Shadowrocket_Producer (line 4) | function Shadowrocket_Producer() {

FILE: backend/src/core/proxy-utils/producers/sing-box.js
  function singbox_Producer (line 944) | function singbox_Producer() {

FILE: backend/src/core/proxy-utils/producers/stash.js
  function Stash_Producer (line 4) | function Stash_Producer() {

FILE: backend/src/core/proxy-utils/producers/surfboard.js
  function Surfboard_Producer (line 7) | function Surfboard_Producer() {
  function anytls (line 42) | function anytls(proxy) {
  function snell (line 65) | function snell(proxy) {
  function shadowsocks (line 100) | function shadowsocks(proxy) {
  function trojan (line 157) | function trojan(proxy) {
  function vmess (line 184) | function vmess(proxy) {
  function http (line 215) | function http(proxy) {
  function socks5 (line 235) | function socks5(proxy) {
  function wireguard (line 255) | function wireguard(proxy) {
  function handleTransport (line 268) | function handleTransport(result, proxy) {

FILE: backend/src/core/proxy-utils/producers/surge.js
  function Surge_Producer (line 15) | function Surge_Producer() {
  function shadowsocks (line 80) | function shadowsocks(proxy) {
  function trojan (line 224) | function trojan(proxy) {
  function anytls (line 307) | function anytls(proxy) {
  function trusttunnel (line 372) | function trusttunnel(proxy) {
  function vmess (line 439) | function vmess(proxy, includeUnsupportedProxy) {
  function ssh (line 529) | function ssh(proxy) {
  function http (line 595) | function http(proxy) {
  function direct (line 676) | function direct(proxy) {
  function socks5 (line 726) | function socks5(proxy) {
  function snell (line 807) | function snell(proxy) {
  function tuic (line 889) | function tuic(proxy) {
  function wireguard (line 991) | function wireguard(proxy) {
  function wireguard_surge (line 1106) | function wireguard_surge(proxy) {
  function hysteria2 (line 1168) | function hysteria2(proxy, includeUnsupportedProxy) {
  function handleTransport (line 1276) | function handleTransport(result, proxy, includeUnsupportedProxy) {

FILE: backend/src/core/proxy-utils/producers/surgemac.js
  function SurgeMac_Producer (line 12) | function SurgeMac_Producer() {
  function external (line 39) | function external(proxy) {
  function shadowsocksr (line 83) | function shadowsocksr(proxy) {
  function mihomo (line 125) | function mihomo(proxy, type, opts) {
  function isIP (line 194) | function isIP(ip) {

FILE: backend/src/core/proxy-utils/producers/uri.js
  function vless (line 5) | function vless(proxy) {
  function URI_Producer (line 138) | function URI_Producer() {

FILE: backend/src/core/proxy-utils/producers/utils.js
  class Result (line 3) | class Result {
    method constructor (line 4) | constructor(proxy) {
    method append (line 9) | append(data) {
    method appendIfPresent (line 16) | appendIfPresent(data, attr) {
    method toString (line 22) | toString() {
  function isPresent (line 27) | function isPresent(obj, attr) {

FILE: backend/src/core/proxy-utils/producers/v2ray.js
  constant URI (line 6) | const URI = URI_Producer();
  function V2Ray_Producer (line 8) | function V2Ray_Producer() {

FILE: backend/src/core/rule-utils/index.js
  function preprocess (line 7) | function preprocess(raw) {
  function parse (line 21) | function parse(raw) {
  function produce (line 37) | function produce(rules, targetPlatform) {

FILE: backend/src/core/rule-utils/parsers.js
  constant RULE_TYPES_MAPPING (line 1) | const RULE_TYPES_MAPPING = [
  function AllRuleParser (line 17) | function AllRuleParser() {

FILE: backend/src/core/rule-utils/preprocessors.js
  function HTML (line 1) | function HTML() {
  function ClashProvider (line 9) | function ClashProvider() {

FILE: backend/src/core/rule-utils/producers.js
  function QXFilter (line 3) | function QXFilter() {
  function SurgeRuleSet (line 31) | function SurgeRuleSet() {
  function LoonRules (line 46) | function LoonRules() {
  function ClashRuleProvider (line 63) | function ClashRuleProvider() {

FILE: backend/src/products/cron-sync-artifacts.js
  function produceArtifacts (line 51) | async function produceArtifacts(names, type) {
  function doSync (line 73) | async function doSync() {

FILE: backend/src/products/sub-store-0.js
  function serve (line 30) | function serve() {

FILE: backend/src/products/sub-store-1.js
  function serve (line 25) | function serve() {

FILE: backend/src/restful/artifacts.js
  function register (line 17) | function register($app) {
  function restoreArtifacts (line 35) | async function restoreArtifacts(_, res) {
  function getAllArtifacts (line 102) | function getAllArtifacts(req, res) {
  function replaceArtifact (line 107) | function replaceArtifact(req, res) {
  function getArtifact (line 113) | async function getArtifact(req, res) {
  function createArtifact (line 132) | function createArtifact(req, res) {
  function updateArtifact (line 162) | function updateArtifact(req, res) {
  function deleteArtifact (line 198) | async function deleteArtifact(req, res) {
  function validateArtifactName (line 241) | function validateArtifactName(name) {
  function syncToGist (line 245) | async function syncToGist(files) {

FILE: backend/src/restful/collections.js
  function register (line 8) | function register($app) {
  function createCollection (line 23) | function createCollection(req, res) {
  function getCollection (line 52) | function getCollection(req, res) {
  function updateCollection (line 84) | function updateCollection(req, res) {
  function deleteCollection (line 137) | function deleteCollection(req, res) {
  function getAllCollections (line 146) | function getAllCollections(req, res) {
  function replaceCollection (line 151) | function replaceCollection(req, res) {

FILE: backend/src/restful/download.js
  function register (line 18) | function register($app) {
  function downloadSubscription (line 89) | async function downloadSubscription(req, res) {
  function downloadCollection (line 408) | async function downloadCollection(req, res) {
  function nezhaMonitor (line 700) | async function nezhaMonitor(proxy, index, query) {
  function nezhaTransform (line 779) | function nezhaTransform(output) {

FILE: backend/src/restful/errors/index.js
  class BaseError (line 1) | class BaseError {
    method constructor (line 2) | constructor(code, message, details) {
  class InternalServerError (line 9) | class InternalServerError extends BaseError {
    method constructor (line 10) | constructor(code, message, details) {
  class RequestInvalidError (line 16) | class RequestInvalidError extends BaseError {
    method constructor (line 17) | constructor(code, message, details) {
  class ResourceNotFoundError (line 23) | class ResourceNotFoundError extends BaseError {
    method constructor (line 24) | constructor(code, message, details) {
  class NetworkError (line 30) | class NetworkError extends BaseError {
    method constructor (line 31) | constructor(code, message, details) {

FILE: backend/src/restful/file.js
  function register (line 14) | function register($app) {
  function createFile (line 31) | function createFile(req, res) {
  function getFile (line 52) | async function getFile(req, res, next) {
  function getWholeFile (line 236) | function getWholeFile(req, res) {
  function updateFile (line 268) | function updateFile(req, res) {
  function deleteFile (line 310) | function deleteFile(req, res) {
  function getAllFiles (line 319) | function getAllFiles(req, res) {
  function getAllWholeFiles (line 327) | function getAllWholeFiles(req, res) {
  function replaceFile (line 332) | function replaceFile(req, res) {

FILE: backend/src/restful/index.js
  function serve (line 26) | function serve() {

FILE: backend/src/restful/miscs.js
  function register (line 21) | function register($app) {
  function getEnv (line 98) | function getEnv(req, res) {
  function refresh (line 117) | async function refresh(_, res) {
  function gistBackupAction (line 129) | async function gistBackupAction(action, keep, encode) {
  function gistBackup (line 245) | async function gistBackup(req, res) {

FILE: backend/src/restful/module.js
  function register (line 8) | function register($app) {
  function createModule (line 23) | function createModule(req, res) {
  function getModule (line 44) | function getModule(req, res) {
  function updateModule (line 64) | function updateModule(req, res) {
  function deleteModule (line 91) | function deleteModule(req, res) {
  function getAllModules (line 100) | function getAllModules(req, res) {
  function replaceModule (line 109) | function replaceModule(req, res) {

FILE: backend/src/restful/node-info.js
  function register (line 6) | function register($app) {
  function getNodeInfo (line 10) | async function getNodeInfo(req, res) {

FILE: backend/src/restful/parser.js
  function register (line 5) | function register($app) {
  function proxy_parser (line 22) | function proxy_parser(req, res) {
  function rule_parser (line 41) | function rule_parser(req, res) {

FILE: backend/src/restful/preview.js
  function register (line 9) | function register($app) {
  function previewFile (line 15) | async function previewFile(req, res) {
  function compareSub (line 107) | async function compareSub(req, res) {
  function compareCollection (line 204) | async function compareCollection(req, res) {

FILE: backend/src/restful/response.js
  function success (line 1) | function success(resp, data, statusCode) {
  function failed (line 8) | function failed(resp, error, statusCode) {

FILE: backend/src/restful/settings.js
  function register (line 7) | function register($app) {
  function getSettings (line 13) | async function getSettings(req, res) {
  function updateSettings (line 38) | async function updateSettings(req, res) {
  function updateAvatar (line 81) | async function updateAvatar() {
  function updateArtifactStore (line 138) | async function updateArtifactStore() {

FILE: backend/src/restful/sort.js
  function register (line 11) | function register($app) {
  function sortSubs (line 19) | function sortSubs(req, res) {
  function sortCollections (line 27) | function sortCollections(req, res) {
  function sortArtifacts (line 35) | function sortArtifacts(req, res) {
  function sortFiles (line 45) | function sortFiles(req, res) {
  function sortTokens (line 53) | function sortTokens(req, res) {

FILE: backend/src/restful/subscriptions.js
  function register (line 25) | function register($app) {
  function getFlowInfo (line 40) | async function getFlowInfo(req, res) {
  function createSubscription (line 231) | function createSubscription(req, res) {
  function getSubscription (line 261) | function getSubscription(req, res) {
  function updateSubscription (line 294) | function updateSubscription(req, res) {
  function deleteSubscription (line 358) | function deleteSubscription(req, res) {
  function getAllSubscriptions (line 376) | function getAllSubscriptions(req, res) {
  function replaceSubscriptions (line 381) | function replaceSubscriptions(req, res) {

FILE: backend/src/restful/sync.js
  function register (line 17) | function register($app) {
  function produceArtifact (line 26) | async function produceArtifact({
  function syncArtifacts (line 603) | async function syncArtifacts() {
  function syncAllArtifacts (line 775) | async function syncAllArtifacts(_, res) {
  function syncArtifact (line 793) | async function syncArtifact(req, res) {

FILE: backend/src/restful/token.js
  function register (line 7) | function register($app) {
  function deleteToken (line 17) | function deleteToken(req, res) {
  function getAllTokens (line 37) | function getAllTokens(req, res) {
  function signToken (line 52) | async function signToken(req, res) {

FILE: backend/src/test/proxy-parsers/testcases.js
  function createTestCases (line 1) | function createTestCases() {

FILE: backend/src/utils/database.js
  function findByName (line 1) | function findByName(list, name, field = 'name') {
  function findIndexByName (line 5) | function findIndexByName(list, name, field = 'name') {
  function deleteByName (line 9) | function deleteByName(list, name, field = 'name') {
  function updateByName (line 14) | function updateByName(list, name, newItem, field = 'name') {

FILE: backend/src/utils/dns.js
  function doh (line 6) | async function doh({ url, domain, type = 'A', timeout, edns }) {

FILE: backend/src/utils/download.js
  function download (line 25) | async function download(
  function downloadFile (line 357) | async function downloadFile(url, file) {

FILE: backend/src/utils/flow.js
  function getFlowField (line 8) | function getFlowField(headers) {
  function getFlowHeaders (line 28) | async function getFlowHeaders(
  function parseFlowHeaders (line 235) | function parseFlowHeaders(flowHeaders) {
  function flowTransfer (line 284) | function flowTransfer(flow, unit = 'B') {
  function validCheck (line 293) | function validCheck(flow) {
  function getRmainingDays (line 316) | function getRmainingDays(opt = {}) {
  function normalizeFlowHeader (line 373) | function normalizeFlowHeader(flowHeaders, splitHeaders) {

FILE: backend/src/utils/geo.js
  function getFlag (line 132) | function getFlag(name) {
  function getISO (line 503) | function getISO(name) {
  function removeFlag (line 508) | function removeFlag(str) {
  class MMDB (line 514) | class MMDB {
    method constructor (line 515) | constructor({ country, asn } = {}) {
    method geoip (line 544) | geoip(ip) {
    method ipaso (line 547) | ipaso(ip) {
    method ipasn (line 550) | ipasn(ip) {

FILE: backend/src/utils/gist.js
  class Gist (line 9) | class Gist {
    method constructor (line 10) | constructor({ token, key, syncPlatform }) {
    method locate (line 110) | async locate() {
    method upload (line 138) | async upload(input) {
    method download (line 276) | async download(filename) {

FILE: backend/src/utils/headers-resource-cache.js
  class ResourceCache (line 8) | class ResourceCache {
    method constructor (line 9) | constructor() {
    method _cleanup (line 27) | _cleanup(prefix, ttl) {
    method revokeAll (line 43) | revokeAll() {
    method _persist (line 48) | _persist() {
    method gettime (line 52) | gettime(id) {
    method get (line 60) | get(id, ttl, remove) {
    method set (line 74) | set(id, value, ttl) {
  function normalizeTTL (line 84) | function normalizeTTL(ttl) {
  function getTTL (line 91) | function getTTL() {

FILE: backend/src/utils/index.js
  constant IPV4_REGEX (line 3) | const IPV4_REGEX = /^((25[0-5]|(2[0-4]|1\d|[1-9]|)\d)(\.(?!$)|$)){4}$/;
  constant IPV6_REGEX (line 6) | const IPV6_REGEX =
  function isIPv4 (line 9) | function isIPv4(ip) {
  function isIPv6 (line 13) | function isIPv6(ip) {
  function isValidPortNumber (line 17) | function isValidPortNumber(port) {
  function isNotBlank (line 23) | function isNotBlank(str) {
  function getIfNotBlank (line 27) | function getIfNotBlank(str, defaultValue) {
  function isPresent (line 31) | function isPresent(obj) {
  function getIfPresent (line 35) | function getIfPresent(obj, defaultValue) {
  function getPolicyDescriptor (line 39) | function getPolicyDescriptor(str) {
  function getRandomInt (line 97) | function getRandomInt(min, max) {
  function getRandomPort (line 103) | function getRandomPort(portString) {
  function numberToString (line 114) | function numberToString(value) {
  function isValidUUID (line 120) | function isValidUUID(uuid) {
  function formatDateTime (line 129) | function formatDateTime(date, format = 'YYYY-MM-DD_HH-mm-ss') {
  function isPlainObject (line 153) | function isPlainObject(obj) {

FILE: backend/src/utils/logical.js
  function AND (line 1) | function AND(...args) {
  function OR (line 5) | function OR(...args) {
  function NOT (line 9) | function NOT(array) {
  function FULL (line 13) | function FULL(length, bool) {

FILE: backend/src/utils/migration.js
  function migrate (line 12) | function migrate() {
  function migrateV2 (line 16) | function migrateV2() {
  function doMigrationV2 (line 26) | function doMigrationV2() {

FILE: backend/src/utils/resource-cache.js
  class ResourceCache (line 8) | class ResourceCache {
    method constructor (line 9) | constructor() {
    method _cleanup (line 27) | _cleanup(prefix, ttl) {
    method revokeAll (line 43) | revokeAll() {
    method _persist (line 48) | _persist() {
    method gettime (line 52) | gettime(id) {
    method get (line 60) | get(id, ttl, remove) {
    method set (line 74) | set(id, value, ttl) {
  function normalizeTTL (line 84) | function normalizeTTL(ttl) {
  function getTTL (line 91) | function getTTL() {

FILE: backend/src/utils/rs.js
  function generateFingerprint (line 3) | function generateFingerprint(caStr) {

FILE: backend/src/utils/script-resource-cache.js
  class ResourceCache (line 8) | class ResourceCache {
    method constructor (line 9) | constructor() {
    method _cleanup (line 27) | _cleanup(prefix, ttl) {
    method revokeAll (line 43) | revokeAll() {
    method _persist (line 48) | _persist() {
    method gettime (line 52) | gettime(id) {
    method get (line 60) | get(id, ttl, remove) {
    method set (line 74) | set(id, value, ttl) {
  function normalizeTTL (line 84) | function normalizeTTL(ttl) {
  function getTTL (line 91) | function getTTL() {

FILE: backend/src/utils/user-agent.js
  function getUserAgentFromHeaders (line 5) | function getUserAgentFromHeaders(headers) {
  function getPlatformFromUserAgent (line 22) | function getPlatformFromUserAgent({ ua, UA, accept }) {
  function getPlatformFromHeaders (line 59) | function getPlatformFromHeaders(headers) {
  function shouldIncludeUnsupportedProxy (line 64) | function shouldIncludeUnsupportedProxy(platform, headers) {

FILE: backend/src/utils/yaml.js
  function retry (line 3) | function retry(fn, content, ...args) {
  function safeLoad (line 19) | function safeLoad(content, ...args) {
  function load (line 22) | function load(content, ...args) {
  function safeDump (line 25) | function safeDump(content, ...args) {
  function dump (line 28) | function dump(content, ...args) {

FILE: backend/src/vendor/express.js
  function express (line 4) | function express({ substore: $, port, host }) {
  function formatHeaders (line 272) | function formatHeaders(headers) {
  function patternMatched (line 280) | function patternMatched(pattern, path) {
  function extractURL (line 304) | function extractURL(url) {
  function extractPathParams (line 325) | function extractPathParams(pattern, path) {

FILE: backend/src/vendor/md5.js
  function hex_md5 (line 21) | function hex_md5(s) {
  function b64_md5 (line 25) | function b64_md5(s) {
  function any_md5 (line 29) | function any_md5(s, e) {
  function hex_hmac_md5 (line 33) | function hex_hmac_md5(k, d) {
  function b64_hmac_md5 (line 37) | function b64_hmac_md5(k, d) {
  function any_hmac_md5 (line 41) | function any_hmac_md5(k, d, e) {
  function md5_vm_test (line 48) | function md5_vm_test() {
  function rstr_md5 (line 55) | function rstr_md5(s) {
  function rstr_hmac_md5 (line 62) | function rstr_hmac_md5(key, data) {
  function rstr2hex (line 80) | function rstr2hex(input) {
  function rstr2b64 (line 99) | function rstr2b64(input) {
  function rstr2any (line 125) | function rstr2any(input, encoding) {
  function str2rstr_utf8 (line 171) | function str2rstr_utf8(input) {
  function str2rstr_utf16le (line 212) | function str2rstr_utf16le(input) {
  function str2rstr_utf16be (line 222) | function str2rstr_utf16be(input) {
  function rstr2binl (line 236) | function rstr2binl(input) {
  function binl2rstr (line 247) | function binl2rstr(input) {
  function binl_md5 (line 257) | function binl_md5(x, len) {
  function md5_cmn (line 352) | function md5_cmn(q, a, b, x, s, t) {
  function md5_ff (line 356) | function md5_ff(a, b, c, d, x, s, t) {
  function md5_gg (line 360) | function md5_gg(a, b, c, d, x, s, t) {
  function md5_hh (line 364) | function md5_hh(a, b, c, d, x, s, t) {
  function md5_ii (line 368) | function md5_ii(a, b, c, d, x, s, t) {
  function safe_add (line 376) | function safe_add(x, y) {
  function bit_rol (line 385) | function bit_rol(num, cnt) {

FILE: backend/src/vendor/open-api.js
  function isPlainObject (line 15) | function isPlainObject(obj) {
  function parseSocks5Uri (line 23) | function parseSocks5Uri(uri) {
  class OpenAPI (line 43) | class OpenAPI {
    method constructor (line 44) | constructor(name = 'untitled', debug = false) {
    method initCache (line 81) | initCache() {
    method persistCache (line 158) | persistCache() {
    method write (line 182) | write(data, key) {
    method read (line 204) | read(key) {
    method delete (line 225) | delete(key) {
    method notify (line 248) | notify(title, subtitle = '', content = '', options = {}) {
    method log (line 345) | log(msg) {
    method info (line 349) | info(msg) {
    method error (line 353) | error(msg) {
    method wait (line 357) | wait(millisec) {
    method done (line 361) | done(value = {}) {
  function ENV (line 374) | function ENV() {
  function HTTP (line 388) | function HTTP(defaultOptions = { baseURL: '' }) {

FILE: scripts/demo.js
  function operator (line 1) | function operator(proxies = [], targetPlatform, context) {

FILE: scripts/fancy-characters.js
  function operator (line 16) | function operator(proxies) {
  function isNumber (line 57) | function isNumber(code) { return code >= 48 && code <= 57; }

FILE: scripts/ip-flag-node.js
  function operator (line 5) | async function operator(proxies) {
  function queryIpApi (line 34) | async function queryIpApi(proxy) {
  function getFlagEmoji (line 60) | function getFlagEmoji(countryCode) {
  function removeFlag (line 70) | function removeFlag(str) {
  function sleep (line 76) | function sleep(ms) {

FILE: scripts/ip-flag.js
  constant RESOURCE_CACHE_KEY (line 1) | const RESOURCE_CACHE_KEY = '#sub-store-cached-resource';
  constant CACHE_EXPIRATION_TIME_MS (line 2) | const CACHE_EXPIRATION_TIME_MS = 10 * 60 * 1000;
  class ResourceCache (line 5) | class ResourceCache {
    method constructor (line 6) | constructor(expires) {
    method _cleanup (line 15) | _cleanup() {
    method revokeAll (line 34) | revokeAll() {
    method _persist (line 39) | _persist() {
    method get (line 43) | get(id) {
    method set (line 51) | set(id, value) {
  function operator (line 59) | async function operator(proxies) {
  function queryIpApi (line 103) | async function queryIpApi(proxy) {
  function getId (line 151) | function getId(proxy) {
  function getFlagEmoji (line 155) | function getFlagEmoji(countryCode) {
  function removeFlag (line 165) | function removeFlag(str) {
  function sleep (line 171) | function sleep(ms) {
  function M (line 175) | function M(d) { for (var _, m = "0123456789ABCDEF", f = "", r = 0; r < d...
  function X (line 175) | function X(d) { for (var _ = Array(d.length >> 2), m = 0; m < _.length; ...
  function V (line 175) | function V(d) { for (var _ = "", m = 0; m < 32 * d.length; m += 8)_ += S...
  function Y (line 175) | function Y(d, _) { d[_ >> 5] |= 128 << _ % 32, d[14 + (_ + 64 >>> 9 << 4...
  function md5_cmn (line 175) | function md5_cmn(d, _, m, f, r, i) { return safe_add(bit_rol(safe_add(sa...
  function md5_ff (line 175) | function md5_ff(d, _, m, f, r, i, n) { return md5_cmn(_ & m | ~_ & f, d,...
  function md5_gg (line 175) | function md5_gg(d, _, m, f, r, i, n) { return md5_cmn(_ & f | m & ~f, d,...
  function md5_hh (line 175) | function md5_hh(d, _, m, f, r, i, n) { return md5_cmn(_ ^ m ^ f, d, _, r...
  function md5_ii (line 175) | function md5_ii(d, _, m, f, r, i, n) { return md5_cmn(m ^ (_ | ~f), d, _...
  function safe_add (line 175) | function safe_add(d, _) { var m = (65535 & d) + (65535 & _); return (d >...
  function bit_rol (line 175) | function bit_rol(d, _) { return d << _ | d >>> 32 - _ }

FILE: scripts/revert.js
  function ENV (line 5) | function ENV(){const e="function"==typeof require&&"undefined"!=typeof $...
  function HTTP (line 5) | function HTTP(e={baseURL:""}){const{isQX:t,isLoon:s,isSurge:o,isScriptab...
  function API (line 5) | function API(e="untitled",t=!1){const{isQX:s,isLoon:o,isSurge:n,isNode:i...

FILE: scripts/tls-fingerprint.js
  function operator (line 6) | function operator(proxies) {

FILE: scripts/udp-filter.js
  function filter (line 4) | function filter(proxies) {

FILE: scripts/vmess-ws-obfs-host.js
  function operator (line 6) | function operator(proxies) {
Condensed preview — 115 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (973K chars).
[
  {
    "path": ".github/workflows/main.yml",
    "chars": 2701,
    "preview": "name: build\non:\n  workflow_dispatch:\n  push:\n    branches:\n      - master\n    paths:\n      - \"backend/package.json\"\n  pu"
  },
  {
    "path": ".gitignore",
    "chars": 2105,
    "preview": ".DS_Store\n# json config\nsub-store.json\nsub-store_*.json\nroot.json\n\n# Logs\nlogs\n*.log\nnpm-debug.log*\nyarn-debug.log*\nyarn"
  },
  {
    "path": "LICENSE",
    "chars": 34577,
    "preview": "                   GNU AFFERO GENERAL PUBLIC LICENSE\n                       Version 3, 19 November 2007\n\n               "
  },
  {
    "path": "README.md",
    "chars": 5311,
    "preview": "<div align=\"center\">\n<br>\n<img width=\"200\" src=\"https://raw.githubusercontent.com/cc63/ICON/main/Sub-Store.png\" alt=\"Sub"
  },
  {
    "path": "backend/.babelrc",
    "chars": 506,
    "preview": "{\n    \"presets\": [\n        [\n            \"@babel/preset-env\"\n        ]\n    ],\n    \"env\": {\n        \"test\": {\n           "
  },
  {
    "path": "backend/.eslintrc.json",
    "chars": 301,
    "preview": "{\n    \"ignorePatterns\": [\"*.min.js\", \"src/vendor/*.js\"],\n    \"env\": {\n        \"browser\": true,\n        \"es2021\": true,\n "
  },
  {
    "path": "backend/.prettierrc.json",
    "chars": 103,
    "preview": "{\n    \"singleQuote\": true,\n    \"trailingComma\": \"all\",\n    \"tabWidth\": 4,\n    \"bracketSpacing\": true\n}\n"
  },
  {
    "path": "backend/banner",
    "chars": 770,
    "preview": "/**\n *  ███████╗██╗   ██╗██████╗       ███████╗████████╗ ██████╗ ██████╗ ███████╗\n *  ██╔════╝██║   ██║██╔══██╗      ██╔"
  },
  {
    "path": "backend/bundle-esbuild.js",
    "chars": 2104,
    "preview": "#!/usr/bin/env node\nconst fs = require('fs');\nconst path = require('path');\nconst { build } = require('esbuild');\n\n!(asy"
  },
  {
    "path": "backend/bundle.js",
    "chars": 1281,
    "preview": "#!/usr/bin/env node\nconst fs = require('fs');\nconst path = require('path');\nconst { build } = require('esbuild');\n\n!(asy"
  },
  {
    "path": "backend/dev-esbuild.js",
    "chars": 567,
    "preview": "#!/usr/bin/env node\nconst { build } = require('esbuild');\n\n!(async () => {\n    const artifacts = [{ src: 'src/main.js', "
  },
  {
    "path": "backend/dist/.gitkeep",
    "chars": 0,
    "preview": ""
  },
  {
    "path": "backend/gulpfile.babel.js",
    "chars": 3307,
    "preview": "import fs from 'fs';\nimport browserify from 'browserify';\nimport gulp from 'gulp';\nimport prettier from 'gulp-prettier';"
  },
  {
    "path": "backend/jsconfig.json",
    "chars": 94,
    "preview": "{\n  \"compilerOptions\": {\n    \"baseUrl\": \".\",\n    \"paths\": {\n      \"@/*\": [\"src/*\"]\n    }\n  }\n}"
  },
  {
    "path": "backend/package.json",
    "chars": 2400,
    "preview": "{\n  \"name\": \"sub-store\",\n  \"version\": \"2.21.51\",\n  \"description\": \"Advanced Subscription Manager for QX, Loon, Surge, St"
  },
  {
    "path": "backend/patches/http-proxy@1.18.1.patch",
    "chars": 1653,
    "preview": "diff --git a/lib/http-proxy/common.js b/lib/http-proxy/common.js\nindex 6513e81d80d5250ea249ea833f819ece67897c7e..486d4c8"
  },
  {
    "path": "backend/src/constants.js",
    "chars": 954,
    "preview": "export const SCHEMA_VERSION_KEY = 'schemaVersion';\nexport const SETTINGS_KEY = 'settings';\nexport const SUBS_KEY = 'subs"
  },
  {
    "path": "backend/src/core/app.js",
    "chars": 144,
    "preview": "import 'fastestsmallesttextencoderdecoder';\nimport { OpenAPI } from '@/vendor/open-api';\n\nconst $ = new OpenAPI('sub-sto"
  },
  {
    "path": "backend/src/core/proxy-utils/index.js",
    "chars": 23081,
    "preview": "import { Base64 } from 'js-base64';\nimport { Buffer } from 'buffer';\nimport rs from '@/utils/rs';\nimport YAML from '@/ut"
  },
  {
    "path": "backend/src/core/proxy-utils/parsers/index.js",
    "chars": 61197,
    "preview": "import {\n    isIPv4,\n    isIPv6,\n    getIfNotBlank,\n    isPresent,\n    isNotBlank,\n    getIfPresent,\n    getRandomPort,\n"
  },
  {
    "path": "backend/src/core/proxy-utils/parsers/peggy/loon.js",
    "chars": 10619,
    "preview": "import * as peggy from 'peggy';\nconst grammars = String.raw`\n// global initializer\n{{\n    function $set(obj, path, value"
  },
  {
    "path": "backend/src/core/proxy-utils/parsers/peggy/loon.peg",
    "chars": 10415,
    "preview": "// global initializer\n{{\n    function $set(obj, path, value) {\n      if (Object(obj) !== obj) return obj;\n      if (!Arr"
  },
  {
    "path": "backend/src/core/proxy-utils/parsers/peggy/qx.js",
    "chars": 9232,
    "preview": "import * as peggy from 'peggy';\nconst grammars = String.raw`\n// global initializer\n{{\n    function $set(obj, path, value"
  },
  {
    "path": "backend/src/core/proxy-utils/parsers/peggy/qx.peg",
    "chars": 9027,
    "preview": "// global initializer\n{{\n    function $set(obj, path, value) {\n      if (Object(obj) !== obj) return obj;\n      if (!Arr"
  },
  {
    "path": "backend/src/core/proxy-utils/parsers/peggy/surge.js",
    "chars": 15001,
    "preview": "import * as peggy from 'peggy';\nconst grammars = String.raw`\n// global initializer\n{{\n    function $set(obj, path, value"
  },
  {
    "path": "backend/src/core/proxy-utils/parsers/peggy/surge.peg",
    "chars": 14796,
    "preview": "// global initializer\n{{\n    function $set(obj, path, value) {\n      if (Object(obj) !== obj) return obj;\n      if (!Arr"
  },
  {
    "path": "backend/src/core/proxy-utils/parsers/peggy/trojan-uri.js",
    "chars": 4119,
    "preview": "import * as peggy from 'peggy';\nconst grammars = String.raw`\n// global initializer\n{{\n  function $set(obj, path, value) "
  },
  {
    "path": "backend/src/core/proxy-utils/parsers/peggy/trojan-uri.peg",
    "chars": 3915,
    "preview": "// global initializer\n{{\n  function $set(obj, path, value) {\n    if (Object(obj) !== obj) return obj;\n    if (!Array.isA"
  },
  {
    "path": "backend/src/core/proxy-utils/preprocessors/index.js",
    "chars": 5421,
    "preview": "import { safeLoad } from '@/utils/yaml';\nimport { Base64 } from 'js-base64';\nimport $ from '@/core/app';\n\nfunction HTML("
  },
  {
    "path": "backend/src/core/proxy-utils/processors/index.js",
    "chars": 41282,
    "preview": "import resourceCache from '@/utils/resource-cache';\nimport scriptResourceCache from '@/utils/script-resource-cache';\nimp"
  },
  {
    "path": "backend/src/core/proxy-utils/producers/clash.js",
    "chars": 9120,
    "preview": "import { isPresent } from '@/core/proxy-utils/producers/utils';\nimport $ from '@/core/app';\n\nexport default function Cla"
  },
  {
    "path": "backend/src/core/proxy-utils/producers/clashmeta.js",
    "chars": 12630,
    "preview": "import { isPresent } from '@/core/proxy-utils/producers/utils';\n\nconst ipVersions = {\n    dual: 'dual',\n    'v4-only': '"
  },
  {
    "path": "backend/src/core/proxy-utils/producers/egern.js",
    "chars": 25369,
    "preview": "import { isPresent } from './utils';\n\nexport default function Egern_Producer() {\n    const type = 'ALL';\n    const produ"
  },
  {
    "path": "backend/src/core/proxy-utils/producers/index.js",
    "chars": 1798,
    "preview": "import Surge_Producer from './surge';\nimport SurgeMac_Producer from './surgemac';\nimport Clash_Producer from './clash';\n"
  },
  {
    "path": "backend/src/core/proxy-utils/producers/loon.js",
    "chars": 24780,
    "preview": "/* eslint-disable no-case-declarations */\nconst targetPlatform = 'Loon';\nimport { isPresent, Result } from './utils';\nim"
  },
  {
    "path": "backend/src/core/proxy-utils/producers/qx.js",
    "chars": 18420,
    "preview": "import { isPresent, Result } from './utils';\n\nconst targetPlatform = 'QX';\n\nexport default function QX_Producer() {\n    "
  },
  {
    "path": "backend/src/core/proxy-utils/producers/shadowrocket.js",
    "chars": 11711,
    "preview": "import { isPresent } from '@/core/proxy-utils/producers/utils';\nimport $ from '@/core/app';\n\nexport default function Sha"
  },
  {
    "path": "backend/src/core/proxy-utils/producers/sing-box.js",
    "chars": 44747,
    "preview": "import ClashMeta_Producer from './clashmeta';\nimport $ from '@/core/app';\nimport { isIPv4, isIPv6, isPlainObject } from "
  },
  {
    "path": "backend/src/core/proxy-utils/producers/stash.js",
    "chars": 14543,
    "preview": "import { isPresent } from '@/core/proxy-utils/producers/utils';\nimport $ from '@/core/app';\n\nexport default function Sta"
  },
  {
    "path": "backend/src/core/proxy-utils/producers/surfboard.js",
    "chars": 8988,
    "preview": "import { Result, isPresent } from './utils';\nimport { isNotBlank } from '@/utils';\n// import $ from '@/core/app';\n\nconst"
  },
  {
    "path": "backend/src/core/proxy-utils/producers/surge.js",
    "chars": 42398,
    "preview": "import { Result, isPresent } from './utils';\nimport { isNotBlank, getIfNotBlank } from '@/utils';\nimport $ from '@/core/"
  },
  {
    "path": "backend/src/core/proxy-utils/producers/surgemac.js",
    "chars": 6578,
    "preview": "import { Base64 } from 'js-base64';\nimport { Result, isPresent } from './utils';\nimport Surge_Producer from './surge';\ni"
  },
  {
    "path": "backend/src/core/proxy-utils/producers/uri.js",
    "chars": 35690,
    "preview": "/* eslint-disable no-case-declarations */\nimport { Base64 } from 'js-base64';\nimport { isIPv6 } from '@/utils';\n\nfunctio"
  },
  {
    "path": "backend/src/core/proxy-utils/producers/utils.js",
    "chars": 623,
    "preview": "import _ from 'lodash';\n\nexport class Result {\n    constructor(proxy) {\n        this.proxy = proxy;\n        this.output "
  },
  {
    "path": "backend/src/core/proxy-utils/producers/v2ray.js",
    "chars": 775,
    "preview": "/* eslint-disable no-case-declarations */\nimport { Base64 } from 'js-base64';\nimport URI_Producer from './uri';\nimport $"
  },
  {
    "path": "backend/src/core/proxy-utils/validators/index.js",
    "chars": 0,
    "preview": ""
  },
  {
    "path": "backend/src/core/rule-utils/index.js",
    "chars": 2140,
    "preview": "import RULE_PREPROCESSORS from './preprocessors';\nimport RULE_PRODUCERS from './producers';\nimport RULE_PARSERS from './"
  },
  {
    "path": "backend/src/core/rule-utils/parsers.js",
    "chars": 2112,
    "preview": "const RULE_TYPES_MAPPING = [\n    [/^(DOMAIN|host|HOST)$/, 'DOMAIN'],\n    [/^(DOMAIN-KEYWORD|host-keyword|HOST-KEYWORD)$/"
  },
  {
    "path": "backend/src/core/rule-utils/preprocessors.js",
    "chars": 500,
    "preview": "function HTML() {\n    const name = 'HTML';\n    const test = (raw) => /^<!DOCTYPE html>/.test(raw);\n    // simply discard"
  },
  {
    "path": "backend/src/core/rule-utils/producers.js",
    "chars": 3065,
    "preview": "import YAML from '@/utils/yaml';\n\nfunction QXFilter() {\n    const type = 'SINGLE';\n    const func = (rule) => {\n        "
  },
  {
    "path": "backend/src/main.js",
    "chars": 1004,
    "preview": "/**\n *  ███████╗██╗   ██╗██████╗       ███████╗████████╗ ██████╗ ██████╗ ███████╗\n *  ██╔════╝██║   ██║██╔══██╗      ██╔"
  },
  {
    "path": "backend/src/products/cron-sync-artifacts.js",
    "chars": 8669,
    "preview": "import { version } from '../../package.json';\nimport {\n    SETTINGS_KEY,\n    ARTIFACTS_KEY,\n    SUBS_KEY,\n    COLLECTION"
  },
  {
    "path": "backend/src/products/resource-parser.loon.js",
    "chars": 3347,
    "preview": "/* eslint-disable no-undef */\nimport { ProxyUtils } from '@/core/proxy-utils';\nimport { RuleUtils } from '@/core/rule-ut"
  },
  {
    "path": "backend/src/products/sub-store-0.js",
    "chars": 1264,
    "preview": "/**\n * 路由拆分 - 本文件只包含不涉及到解析器的 RESTFul API\n */\n\nimport { version } from '../../package.json';\nconsole.log(\n    `\n┅┅┅┅┅┅┅┅┅"
  },
  {
    "path": "backend/src/products/sub-store-1.js",
    "chars": 903,
    "preview": "/**\n * 路由拆分 - 本文件仅包含使用到解析器的 RESTFul API\n */\n\nimport { version } from '../../package.json';\nimport migrate from '@/utils/"
  },
  {
    "path": "backend/src/restful/artifacts.js",
    "chars": 8236,
    "preview": "import $ from '@/core/app';\n\nimport {\n    ARTIFACT_REPOSITORY_KEY,\n    ARTIFACTS_KEY,\n    SETTINGS_KEY,\n} from '@/consta"
  },
  {
    "path": "backend/src/restful/collections.js",
    "chars": 4638,
    "preview": "import { deleteByName, findByName, updateByName } from '@/utils/database';\nimport { COLLECTIONS_KEY, ARTIFACTS_KEY, FILE"
  },
  {
    "path": "backend/src/restful/download.js",
    "chars": 29866,
    "preview": "import {\n    getPlatformFromHeaders,\n    shouldIncludeUnsupportedProxy,\n} from '@/utils/user-agent';\nimport { ProxyUtils"
  },
  {
    "path": "backend/src/restful/errors/index.js",
    "chars": 892,
    "preview": "class BaseError {\n    constructor(code, message, details) {\n        this.code = code;\n        this.message = message;\n  "
  },
  {
    "path": "backend/src/restful/file.js",
    "chars": 10256,
    "preview": "import { deleteByName, findByName, updateByName } from '@/utils/database';\nimport { getFlowHeaders, normalizeFlowHeader "
  },
  {
    "path": "backend/src/restful/index.js",
    "chars": 21787,
    "preview": "import { Base64 } from 'js-base64';\nimport _ from 'lodash';\nimport express from '@/vendor/express';\nimport $ from '@/cor"
  },
  {
    "path": "backend/src/restful/miscs.js",
    "chars": 9694,
    "preview": "import { Base64 } from 'js-base64';\nimport _ from 'lodash';\nimport $ from '@/core/app';\nimport { ENV } from '@/vendor/op"
  },
  {
    "path": "backend/src/restful/module.js",
    "chars": 3073,
    "preview": "import { deleteByName, findByName, updateByName } from '@/utils/database';\nimport { MODULES_KEY } from '@/constants';\nim"
  },
  {
    "path": "backend/src/restful/node-info.js",
    "chars": 1759,
    "preview": "import producer from '@/core/proxy-utils/producers';\nimport { HTTP } from '@/vendor/open-api';\nimport { failed, success "
  },
  {
    "path": "backend/src/restful/parser.js",
    "chars": 1461,
    "preview": "import { success, failed } from '@/restful/response';\nimport { ProxyUtils } from '@/core/proxy-utils';\nimport { RuleUtil"
  },
  {
    "path": "backend/src/restful/preview.js",
    "chars": 13655,
    "preview": "import { InternalServerError } from './errors';\nimport { ProxyUtils } from '@/core/proxy-utils';\nimport { findByName } f"
  },
  {
    "path": "backend/src/restful/response.js",
    "chars": 523,
    "preview": "export function success(resp, data, statusCode) {\n    resp.status(statusCode || 200).json({\n        status: 'success',\n "
  },
  {
    "path": "backend/src/restful/settings.js",
    "chars": 5786,
    "preview": "import { SETTINGS_KEY, ARTIFACT_REPOSITORY_KEY } from '@/constants';\nimport { success, failed } from './response';\nimpor"
  },
  {
    "path": "backend/src/restful/sort.js",
    "chars": 1842,
    "preview": "import {\n    ARTIFACTS_KEY,\n    COLLECTIONS_KEY,\n    SUBS_KEY,\n    FILES_KEY,\n    TOKENS_KEY,\n} from '@/constants';\nimpo"
  },
  {
    "path": "backend/src/restful/subscriptions.js",
    "chars": 11520,
    "preview": "import {\n    NetworkError,\n    InternalServerError,\n    ResourceNotFoundError,\n    RequestInvalidError,\n} from './errors"
  },
  {
    "path": "backend/src/restful/sync.js",
    "chars": 32786,
    "preview": "import $ from '@/core/app';\nimport {\n    ARTIFACTS_KEY,\n    COLLECTIONS_KEY,\n    RULES_KEY,\n    SUBS_KEY,\n    FILES_KEY,"
  },
  {
    "path": "backend/src/restful/token.js",
    "chars": 6499,
    "preview": "import { ENV } from '@/vendor/open-api';\nimport { TOKENS_KEY, SUBS_KEY, FILES_KEY, COLLECTIONS_KEY } from '@/constants';"
  },
  {
    "path": "backend/src/test/proxy-parsers/loon.spec.js",
    "chars": 5120,
    "preview": "import getLoonParser from '@/core/proxy-utils/parsers/peggy/loon';\nimport { describe, it } from 'mocha';\nimport testcase"
  },
  {
    "path": "backend/src/test/proxy-parsers/qx.spec.js",
    "chars": 5103,
    "preview": "import getQXParser from '@/core/proxy-utils/parsers/peggy/qx';\nimport { describe, it } from 'mocha';\nimport testcases fr"
  },
  {
    "path": "backend/src/test/proxy-parsers/surge.spec.js",
    "chars": 4928,
    "preview": "import getSurgeParser from '@/core/proxy-utils/parsers/peggy/surge';\nimport { describe, it } from 'mocha';\nimport testca"
  },
  {
    "path": "backend/src/test/proxy-parsers/testcases.js",
    "chars": 25415,
    "preview": "function createTestCases() {\n    const name = 'name';\n    const server = 'example.com';\n    const port = 10086;\n\n    con"
  },
  {
    "path": "backend/src/utils/database.js",
    "chars": 524,
    "preview": "export function findByName(list, name, field = 'name') {\n    return list.find((item) => item[field] === name);\n}\n\nexport"
  },
  {
    "path": "backend/src/utils/dns.js",
    "chars": 1514,
    "preview": "import $ from '@/core/app';\nimport dnsPacket from 'dns-packet';\nimport { Buffer } from 'buffer';\nimport { isIPv4 } from "
  },
  {
    "path": "backend/src/utils/download.js",
    "chars": 12502,
    "preview": "import { SETTINGS_KEY, FILES_KEY, MODULES_KEY } from '@/constants';\nimport { HTTP, ENV } from '@/vendor/open-api';\nimpor"
  },
  {
    "path": "backend/src/utils/env.js",
    "chars": 1809,
    "preview": "import { version as substoreVersion } from '../../package.json';\nimport { ENV } from '@/vendor/open-api';\n\nconst {\n    i"
  },
  {
    "path": "backend/src/utils/flow.js",
    "chars": 17591,
    "preview": "import { SETTINGS_KEY } from '@/constants';\nimport { HTTP, ENV } from '@/vendor/open-api';\nimport { hex_md5 } from '@/ve"
  },
  {
    "path": "backend/src/utils/geo.js",
    "chars": 15237,
    "preview": "import $ from '@/core/app';\n\nconst ISOFlags = {\n    '🏳️‍🌈': ['EXP', 'BAND'],\n    '🇸🇱': ['TEST', 'SOS'],\n    '🇲🇵': ['MP',"
  },
  {
    "path": "backend/src/utils/gist.js",
    "chars": 10473,
    "preview": "import { HTTP, ENV } from '@/vendor/open-api';\nimport { getPolicyDescriptor } from '@/utils';\nimport $ from '@/core/app'"
  },
  {
    "path": "backend/src/utils/headers-resource-cache.js",
    "chars": 2814,
    "preview": "import $ from '@/core/app';\nimport {\n    HEADERS_RESOURCE_CACHE_KEY,\n    DEFAULT_HEADERS_CACHE_TTL,\n    SETTINGS_KEY,\n} "
  },
  {
    "path": "backend/src/utils/index.js",
    "chars": 5670,
    "preview": "import * as ipAddress from 'ip-address';\n// source: https://stackoverflow.com/a/36760050\nconst IPV4_REGEX = /^((25[0-5]|"
  },
  {
    "path": "backend/src/utils/logical.js",
    "chars": 353,
    "preview": "function AND(...args) {\n    return args.reduce((a, b) => a.map((c, i) => b[i] && c));\n}\n\nfunction OR(...args) {\n    retu"
  },
  {
    "path": "backend/src/utils/migration.js",
    "chars": 4407,
    "preview": "import {\n    SUBS_KEY,\n    COLLECTIONS_KEY,\n    SCHEMA_VERSION_KEY,\n    ARTIFACTS_KEY,\n    RULES_KEY,\n    FILES_KEY,\n   "
  },
  {
    "path": "backend/src/utils/resource-cache.js",
    "chars": 2743,
    "preview": "import $ from '@/core/app';\nimport {\n    RESOURCE_CACHE_KEY,\n    DEFAULT_CACHE_TTL,\n    SETTINGS_KEY,\n} from '@/constant"
  },
  {
    "path": "backend/src/utils/rs.js",
    "chars": 289,
    "preview": "import rs from 'jsrsasign';\n\nexport function generateFingerprint(caStr) {\n    const hex = rs.pemtohex(caStr);\n    const "
  },
  {
    "path": "backend/src/utils/script-resource-cache.js",
    "chars": 2804,
    "preview": "import $ from '@/core/app';\nimport {\n    SCRIPT_RESOURCE_CACHE_KEY,\n    DEFAULT_SCRIPT_CACHE_TTL,\n    SETTINGS_KEY,\n} fr"
  },
  {
    "path": "backend/src/utils/user-agent.js",
    "chars": 3256,
    "preview": "import gte from 'semver/functions/gte';\nimport coerce from 'semver/functions/coerce';\nimport $ from '@/core/app';\n\nexpor"
  },
  {
    "path": "backend/src/utils/yaml.js",
    "chars": 1010,
    "preview": "import YAML from 'static-js-yaml';\n\nfunction retry(fn, content, ...args) {\n    try {\n        return fn(content, ...args)"
  },
  {
    "path": "backend/src/vendor/express.js",
    "chars": 10320,
    "preview": "/* eslint-disable no-undef */\nimport { ENV } from './open-api';\n\nexport default function express({ substore: $, port, ho"
  },
  {
    "path": "backend/src/vendor/md5.js",
    "chars": 12610,
    "preview": "/*\n * A JavaScript implementation of the RSA Data Security, Inc. MD5 Message\n * Digest Algorithm, as defined in RFC 1321"
  },
  {
    "path": "backend/src/vendor/open-api.js",
    "chars": 23167,
    "preview": "/* eslint-disable no-undef */\nconst isQX = typeof $task !== 'undefined';\nconst isLoon = typeof $loon !== 'undefined';\n//"
  },
  {
    "path": "config/Egern.yaml",
    "chars": 2085,
    "preview": "name: Sub-Store\ndescription: \"支持 Surge 正式版的参数设置功能. 测落地功能 ability: http-client-policy, 同步配置的定时 cronexp: 55 23 * * *\"\ncomp"
  },
  {
    "path": "config/Loon.plugin",
    "chars": 1025,
    "preview": "#!name=Sub-Store\n#!desc=高级订阅管理工具. 定时任务默认为每天 23 点 55 分, 可在插件设置中自定义. 定时任务指定时将订阅/文件上传到私有 Gist. 在前端, 叫做 '同步' 或 '同步配置'\n#!open"
  },
  {
    "path": "config/QX-Task.json",
    "chars": 342,
    "preview": "{\n  \"name\": \"Sub-Store\",\n  \"description\": \"定时任务默认为每天 23 点 55 分. 定时任务指定时将订阅/文件上传到私有 Gist. 在前端, 叫做 '同步' 或 '同步配置'\",\n  \"task"
  },
  {
    "path": "config/QX.snippet",
    "chars": 358,
    "preview": "hostname=sub.store\n\n^https?:\\/\\/sub\\.store\\/((download)|api\\/(preview|sync|(utils\\/node-info))) url script-analyze-echo-"
  },
  {
    "path": "config/README.md",
    "chars": 3577,
    "preview": "# Sub-Store 配置指南\n\n## 查看更新说明:\n\nSub-Store Releases: [`https://github.com/sub-store-org/Sub-Store/releases`](https://github"
  },
  {
    "path": "config/Stash.stoverride",
    "chars": 1045,
    "preview": "name: Sub-Store\ndesc: 高级订阅管理工具 @Peng-YM. 定时任务默认为每天  23 点 55 分. 定时任务指定时将订阅/文件上传到私有 Gist. 在前端, 叫做 '同步' 或 '同步配置'\nicon: http"
  },
  {
    "path": "config/Surge-Beta.sgmodule",
    "chars": 2168,
    "preview": "#!name=Sub-Store(β)\n#!desc=支持 Surge 正式版的参数设置功能. 测落地功能 ability: http-client-policy, 同步配置的定时 cronexp: 55 23 * * *\n#!catego"
  },
  {
    "path": "config/Surge-Noability.sgmodule",
    "chars": 997,
    "preview": "#!name=Sub-Store\n#!desc=高级订阅管理工具 @Peng-YM  无 ability 参数版本,不会爆内存, 如果需要使用指定节点功能 例如[加旗帜脚本或者cname脚本] 可以用带 ability 参数. 定时任务默认"
  },
  {
    "path": "config/Surge-ability.sgmodule",
    "chars": 913,
    "preview": "#!name=Sub-Store\n#!desc=高级订阅管理工具 @Peng-YM  带 ability 参数版本, 使用 jsc 引擎时, 可能会爆内存, 如果不需要使用指定节点功能 例如[加旗帜脚本或者cname脚本] 可以用不带 ab"
  },
  {
    "path": "config/Surge.sgmodule",
    "chars": 2165,
    "preview": "#!name=Sub-Store\n#!desc=支持 Surge 正式版的参数设置功能. 测落地功能 ability: http-client-policy, 同步配置的定时 cronexp: 55 23 * * *\n#!category="
  },
  {
    "path": "scripts/demo.js",
    "chars": 13135,
    "preview": "function operator(proxies = [], targetPlatform, context) {\n  // 支持快捷操作 不一定要写一个 function\n  // 可参考 https://t.me/zhetengsha"
  },
  {
    "path": "scripts/fancy-characters.js",
    "chars": 6454,
    "preview": "/**\n * 节点名改为花里胡哨字体,仅支持英文字符和数字\n *\n * 【字体】\n * 可参考:https://www.dute.org/weird-fonts\n * serif-bold, serif-italic, serif-bold"
  },
  {
    "path": "scripts/ip-flag-node.js",
    "chars": 2092,
    "preview": "const $ = $substore;\n\nconst {onlyFlagIP = true} = $arguments\n\nasync function operator(proxies) {\n    const BATCH_SIZE = "
  },
  {
    "path": "scripts/ip-flag.js",
    "chars": 9290,
    "preview": "const RESOURCE_CACHE_KEY = '#sub-store-cached-resource';\nconst CACHE_EXPIRATION_TIME_MS = 10 * 60 * 1000;\nconst $ = $sub"
  },
  {
    "path": "scripts/media-filter.js",
    "chars": 0,
    "preview": ""
  },
  {
    "path": "scripts/revert.js",
    "chars": 4777,
    "preview": "const $ = API()\n$.write(\"{}\", \"#sub-store\")\n$.done()\n\nfunction ENV(){const e=\"function\"==typeof require&&\"undefined\"!=ty"
  },
  {
    "path": "scripts/tls-fingerprint.js",
    "chars": 229,
    "preview": "/**\n * 为节点添加 tls 证书指纹\n * 示例\n * #fingerprint=...\n */\nfunction operator(proxies) {\n    const { fingerprint } = $arguments;"
  },
  {
    "path": "scripts/udp-filter.js",
    "chars": 84,
    "preview": "/**\n * 过滤 UDP 节点\n */\nfunction filter(proxies) {\n  return proxies.map(p => p.udp);\n}\n"
  },
  {
    "path": "scripts/vmess-ws-obfs-host.js",
    "chars": 419,
    "preview": "/**\n * 为 VMess WebSocket 节点修改混淆 host\n * 示例\n * #host=google.com\n */\nfunction operator(proxies) {\n    const { host } = $ar"
  },
  {
    "path": "vs.code-workspace",
    "chars": 60,
    "preview": "{\n\t\"folders\": [\n\t\t{\n\t\t\t\"path\": \".\"\n\t\t}\n\t],\n\t\"settings\": {}\n}"
  }
]

About this extraction

This page contains the full source code of the sub-store-org/Sub-Store GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 115 files (911.4 KB), approximately 225.9k tokens, and a symbol index with 473 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.

Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.

Copied to clipboard!