├── .editorconfig
├── .eslintignore
├── .eslintrc.js
├── .github
├── ISSUE_TEMPLATE
│ └── 1.bug-report.yml
├── dependabot.yml
└── workflows
│ └── release.yml.bak
├── .gitignore
├── .prettierignore
├── .prettierrc.js
├── CHANGELOG.md
├── CODE_OF_CONDUCT.md
├── CONTRIBUTING.md
├── LICENSE
├── README.md
├── SECURITY.md
├── images
└── logo.svg
├── package.json
├── rollup.config.js
├── scripts
└── pkg.js
├── src
├── cli
│ ├── commands
│ │ ├── ttapkg.ts
│ │ └── wxapkg.ts
│ ├── config
│ │ └── outputConfig.ts
│ └── index.ts
├── core
│ ├── base
│ │ ├── BaseDecryptor.ts
│ │ ├── BaseExtractor.ts
│ │ ├── BaseParser.ts
│ │ └── controller
│ │ │ ├── ConfigController.ts
│ │ │ ├── PathController.ts
│ │ │ ├── SaveController.ts
│ │ │ ├── TraverseController.ts
│ │ │ └── WorkerController.ts
│ └── wxapkg
│ │ ├── WxapkgAppConfigParser.ts
│ │ ├── WxapkgController.ts
│ │ ├── WxapkgDecompiler.ts
│ │ ├── WxapkgDecryptor.ts
│ │ ├── WxapkgEnums.ts
│ │ ├── WxapkgExtractor.ts
│ │ ├── WxapkgScriptParser.ts
│ │ ├── WxapkgWxmlParser.ts
│ │ ├── WxapkgWxssParser.ts
│ │ ├── index.ts
│ │ ├── types.d.ts
│ │ ├── utils
│ │ ├── checkWxapkg.ts
│ │ ├── createPage.ts
│ │ └── getWccVersion.ts
│ │ ├── worker.ts
│ │ └── wxml-parser
│ │ ├── index.ts
│ │ ├── parseWxml.ts
│ │ ├── parseZArray.ts
│ │ └── utils.ts
├── enum
│ └── PackageSuffix.ts
├── index.ts
└── utils
│ ├── ast.ts
│ ├── classes
│ └── Saver.ts
│ ├── clearConsole.ts
│ ├── colors.ts
│ ├── crypto.ts
│ ├── deepCopy.ts
│ ├── exceptions.ts
│ ├── getConfigurator.ts
│ ├── hasOwnProperty.ts
│ ├── isDev.ts
│ ├── isWorkerRuntime.ts
│ ├── logger.ts
│ ├── matchScripts.ts
│ ├── reformat.ts
│ └── transformStyle.ts
├── test
└── .gitkeep
├── tsconfig.json
└── yarn.lock
/.editorconfig:
--------------------------------------------------------------------------------
1 | root = true
2 |
3 | [*]
4 | charset = utf-8
5 | indent_style = space
6 | indent_size = 2
7 | end_of_line = lf
8 | insert_final_newline = true
9 | trim_trailing_whitespace = true
10 |
--------------------------------------------------------------------------------
/.eslintignore:
--------------------------------------------------------------------------------
1 | node_modules
2 | dist
3 | scripts
4 | rollup.config.js
5 |
6 | parseWxml.ts
7 | parseZArray.ts
8 |
--------------------------------------------------------------------------------
/.eslintrc.js:
--------------------------------------------------------------------------------
1 | // eslint-disable-next-line no-undef
2 | module.exports = {
3 | env: {
4 | browser: false,
5 | es2021: true,
6 | },
7 | extends: ['eslint:recommended', 'plugin:@typescript-eslint/recommended'],
8 | overrides: [],
9 | parser: '@typescript-eslint/parser',
10 | parserOptions: {
11 | ecmaVersion: 'latest',
12 | sourceType: 'module',
13 | },
14 | plugins: ['@typescript-eslint'],
15 | rules: {},
16 | }
17 |
--------------------------------------------------------------------------------
/.github/ISSUE_TEMPLATE/1.bug-report.yml:
--------------------------------------------------------------------------------
1 | title: "[Bug]: "
2 | labels: ["bug"]
3 | name: 🐛 Bug report
4 | assignees: "@r3x5ur"
5 | description: 创建报告以帮助我们改进
6 |
7 | body:
8 | - type: markdown
9 | attributes:
10 | value: |
11 | **🤝感谢提交**
12 | **📝请填写以下字段,便于更好的排查和解决问题,共同维护靠大家**
13 | - type: input
14 | attributes:
15 | label: unveilr版本
16 | description: 填写 `unveilr -v` 的输出
17 | validations:
18 | required: true
19 | - type: dropdown
20 | id: sys-version
21 | attributes:
22 | label: 操作系统
23 | description: 运行时的操作系统
24 | options:
25 | - windows
26 | - linux
27 | - macOS
28 | validations:
29 | required: true
30 | - type: input
31 | attributes:
32 | label: 运行时命令
33 | description: 路径自己脱敏如:`unveilr /path/to/dir`
34 | validations:
35 | required: true
36 | - type: textarea
37 | attributes:
38 | label: 重现步骤
39 | description: 输入有关您的错误的详细信息
40 | validations:
41 | required: true
42 | - type: textarea
43 | attributes:
44 | label: 预期结果
45 | description: 请提供文本输出而不是屏幕截图
46 | validations:
47 | required: true
48 | - type: textarea
49 | attributes:
50 | label: 实际结果
51 | description: 请提供文本输出而不是屏幕截图
52 | validations:
53 | required: true
54 | - type: textarea
55 | attributes:
56 | label: 其他信息
57 | description: 其他你觉得可能有用的信息
58 |
--------------------------------------------------------------------------------
/.github/dependabot.yml:
--------------------------------------------------------------------------------
1 | # To get started with Dependabot version updates, you'll need to specify which
2 | # package ecosystems to update and where the package manifests are located.
3 | # Please see the documentation for all configuration options:
4 | # https://docs.github.com/github/administering-a-repository/configuration-options-for-dependency-updates
5 |
6 | version: 2
7 | updates:
8 | - package-ecosystem: "npm" # See documentation for possible values
9 | directory: "/" # Location of package manifests
10 | schedule:
11 | interval: "weekly"
12 |
--------------------------------------------------------------------------------
/.github/workflows/release.yml.bak:
--------------------------------------------------------------------------------
1 | name: Release
2 | permissions:
3 | contents: write
4 | on:
5 | push:
6 | tags:
7 | - "v*"
8 | jobs:
9 | build-and-release:
10 | runs-on: ubuntu-latest
11 | steps:
12 | - name: Checkout code
13 | uses: actions/checkout@v2
14 |
15 | - name: Setup Node.js and Yarn
16 | uses: actions/setup-node@v2
17 | with:
18 | node-version: '14.x'
19 | cache: 'yarn'
20 |
21 | - name: Install dependencies
22 | run: yarn
23 |
24 | - name: Build
25 | run: yarn pkg
26 |
27 | - name: "Build Changelog"
28 | id: build_changelog
29 | uses: mikepenz/release-changelog-builder-action@v3.7.0
30 |
31 | - name: Create Release and Upload Release Asset
32 | uses: softprops/action-gh-release@v1
33 | if: startsWith(github.ref, 'refs/tags/')
34 | with:
35 | tag_name: ${{ github.ref_name }}
36 | name: ${{ github.ref_name }}
37 | body: |
38 | ${{steps.build_changelog.outputs.changelog}}
39 | draft: true
40 | prerelease: true
41 | files: release/*.tar.gz
42 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | # Logs
2 | logs
3 | *.log
4 | npm-debug.log*
5 | yarn-debug.log*
6 | yarn-error.log*
7 | lerna-debug.log*
8 | .pnpm-debug.log*
9 |
10 | # Diagnostic reports (https://nodejs.org/api/report.html)
11 | report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json
12 |
13 | # Runtime data
14 | pids
15 | *.pid
16 | *.seed
17 | *.pid.lock
18 |
19 | # Directory for instrumented libs generated by jscoverage/JSCover
20 | lib-cov
21 |
22 | # Coverage directory used by tools like istanbul
23 | coverage
24 | *.lcov
25 |
26 | # nyc test coverage
27 | .nyc_output
28 |
29 | # Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files)
30 | .grunt
31 |
32 | # Bower dependency directory (https://bower.io/)
33 | bower_components
34 |
35 | # node-waf configuration
36 | .lock-wscript
37 |
38 | # Compiled binary addons (https://nodejs.org/api/addons.html)
39 | build/Release
40 |
41 | # Dependency directories
42 | node_modules/
43 | jspm_packages/
44 |
45 | # Snowpack dependency directory (https://snowpack.dev/)
46 | web_modules/
47 |
48 | # TypeScript cache
49 | *.tsbuildinfo
50 |
51 | # Optional npm cache directory
52 | .npm
53 |
54 | # Optional eslint cache
55 | .eslintcache
56 |
57 | # Optional stylelint cache
58 | .stylelintcache
59 |
60 | # Microbundle cache
61 | .rpt2_cache/
62 | .rts2_cache_cjs/
63 | .rts2_cache_es/
64 | .rts2_cache_umd/
65 |
66 | # Optional REPL history
67 | .node_repl_history
68 |
69 | # Output of 'npm pack'
70 | *.tgz
71 |
72 | # Yarn Integrity file
73 | .yarn-integrity
74 |
75 | # dotenv environment variable files
76 | .env
77 | .env.development.local
78 | .env.test.local
79 | .env.production.local
80 | .env.local
81 |
82 | # parcel-bundler cache (https://parceljs.org/)
83 | .cache
84 | .parcel-cache
85 |
86 | # Next.js build output
87 | .next
88 | out
89 |
90 | # Nuxt.js build / generate output
91 | .nuxt
92 | dist
93 |
94 | # Gatsby files
95 | .cache/
96 | # Comment in the public line in if your project uses Gatsby and not Next.js
97 | # https://nextjs.org/blog/next-9-1#public-directory-support
98 | # public
99 |
100 | # vuepress build output
101 | .vuepress/dist
102 |
103 | # vuepress v2.x temp and cache directory
104 | .temp
105 |
106 | # Docusaurus cache and generated files
107 | .docusaurus
108 |
109 | # Serverless directories
110 | .serverless/
111 |
112 | # FuseBox cache
113 | .fusebox/
114 |
115 | # DynamoDB Local files
116 | .dynamodb/
117 |
118 | # TernJS port file
119 | .tern-port
120 |
121 | # Stores VSCode versions used for testing VSCode extensions
122 | .vscode-test
123 |
124 | # yarn v2
125 | .yarn/cache
126 | .yarn/unplugged
127 | .yarn/build-state.yml
128 | .yarn/install-state.gz
129 | .pnp.*
130 |
131 |
132 | .idea/
133 | files/
134 | release/
135 | .npmrc
136 | .release.lock
137 | .DS_Store
138 |
--------------------------------------------------------------------------------
/.prettierignore:
--------------------------------------------------------------------------------
1 | wxml-parser-js
2 |
--------------------------------------------------------------------------------
/.prettierrc.js:
--------------------------------------------------------------------------------
1 | module.exports = {
2 | // 一行最多 120 字符
3 | printWidth: 120,
4 | // 使用 2 个空格缩进
5 | tabWidth: 2,
6 | // 不使用 tab 缩进,而使用空格
7 | useTabs: false,
8 | // 行尾需要有分号
9 | semi: false,
10 | // 使用单引号代替双引号
11 | singleQuote: true,
12 | // 对象的 key 仅在必要时用引号
13 | quoteProps: 'as-needed',
14 | // jsx 不使用单引号,而使用双引号
15 | jsxSingleQuote: false,
16 | // 末尾使用逗号
17 | trailingComma: 'all',
18 | // 大括号内的首尾需要空格 { foo: bar }
19 | bracketSpacing: true,
20 | // jsx 标签的反尖括号需要换行
21 | jsxBracketSameLine: false,
22 | // 箭头函数,只有一个参数的时候,也需要括号
23 | arrowParens: 'always',
24 | // 每个文件格式化的范围是文件的全部内容
25 | rangeStart: 0,
26 | rangeEnd: Infinity,
27 | // 不需要写文件开头的 @prettier
28 | requirePragma: false,
29 | // 不需要自动在文件开头插入 @prettier
30 | insertPragma: false,
31 | // 使用默认的折行标准
32 | proseWrap: 'preserve',
33 | // 根据显示样式决定 html 要不要折行
34 | htmlWhitespaceSensitivity: 'css',
35 | // 换行符使用 lf
36 | endOfLine: 'lf',
37 | };
38 |
--------------------------------------------------------------------------------
/CHANGELOG.md:
--------------------------------------------------------------------------------
1 | # 更改日志
2 |
3 | ### [:bookmark:v2.0.2 :loud_sound:2023-05-20](https://github.com/r3x5ur/unveilr/tree/v2.0.2)
4 | * .DS_ Store is a hidden configuration file for Mac and should be ignored by @KelvinF97 in https://github.com/r3x5ur/unveilr/pull/108
5 | * :art: opt: Project structure adjustment by @r3x5ur in https://github.com/r3x5ur/unveilr/pull/109
6 | * fix(wxml-parser): Cannot create property '_type' on string xx by @XinRoom in https://github.com/r3x5ur/unveilr/pull/110
7 | * Bump vm2 from 3.9.17 to 3.9.18 by @dependabot in https://github.com/r3x5ur/unveilr/pull/112
8 | * Bump @typescript-eslint/eslint-plugin from 5.59.2 to 5.59.6 by @dependabot in https://github.com/r3x5ur/unveilr/pull/116
9 | * Bump @rollup/plugin-commonjs from 24.1.0 to 25.0.0 by @dependabot in https://github.com/r3x5ur/unveilr/pull/115
10 | * Bump rollup from 3.21.5 to 3.21.7 by @dependabot in https://github.com/r3x5ur/unveilr/pull/113
11 | * :tada: feat: try ttapkg by @r3x5ur in https://github.com/r3x5ur/unveilr/pull/118
12 | * ✨ feat: auto complete configuration
13 | ### [:bookmark:v2.0.1 :loud_sound:2023-04-21](https://github.com/r3x5ur/unveilr/tree/v2.0.1)
14 | * 解决一些小bug
15 | ### [:bookmark:v2.0.0 :loud_sound:2023-04-13](https://github.com/r3x5ur/unveilr/tree/v2.0.0)
16 | * Bump @babel/core from 7.21.0 to 7.21.3 by @dependabot in https://github.com/r3x5ur/unveilr/pull/22
17 | * Bump prettier from 2.8.4 to 2.8.5 by @dependabot in https://github.com/r3x5ur/unveilr/pull/19
18 | * Bump @typescript-eslint/eslint-plugin from 5.54.0 to 5.56.0 by @dependabot in https://github.com/r3x5ur/unveilr/pull/21
19 | * Bump tsconfig-paths from 3.14.2 to 4.1.2 by @dependabot in https://github.com/r3x5ur/unveilr/pull/20
20 | * 添加更友好的 bug-report by @unveilr in https://github.com/r3x5ur/unveilr/pull/30
21 | * [PR] 添加 wcc_version 检测 by @r3x5ur in https://github.com/r3x5ur/unveilr/pull/33
22 | * Bump @typescript-eslint/parser from 5.56.0 to 5.57.0 by @dependabot in https://github.com/r3x5ur/unveilr/pull/35
23 | * Bump typescript from 4.9.5 to 5.0.2 by @dependabot in https://github.com/r3x5ur/unveilr/pull/39
24 | * Bump prettier from 2.8.6 to 2.8.7 by @dependabot in https://github.com/r3x5ur/unveilr/pull/38
25 | * Bump @typescript-eslint/eslint-plugin from 5.56.0 to 5.57.0 by @dependabot in https://github.com/r3x5ur/unveilr/pull/37
26 | * Bump rollup from 3.20.0 to 3.20.2 by @dependabot in https://github.com/r3x5ur/unveilr/pull/36
27 | * [PR] 添加CI工具 by @r3x5ur in https://github.com/r3x5ur/unveilr/pull/41
28 | * :bug:(clean) "Clean rely parse (Resolves #40)" by @r3x5ur in https://github.com/r3x5ur/unveilr/pull/42
29 | * :fire:(core) "Add APP_V4 support(Resolves #29)" by @r3x5ur in https://github.com/r3x5ur/unveilr/pull/43
30 | * [PR] fix bug (#45,#46) by @r3x5ur in https://github.com/r3x5ur/unveilr/pull/47
31 | * [PR] 解决多个bug by @r3x5ur in https://github.com/r3x5ur/unveilr/pull/55
32 | * ⬆️ Bump tsconfig-paths from 4.1.2 to 4.2.0 by @dependabot in https://github.com/r3x5ur/unveilr/pull/63
33 | * ⬆️ Bump @babel/core from 7.21.3 to 7.21.4 by @dependabot in https://github.com/r3x5ur/unveilr/pull/60
34 | * ⬆️ Bump @typescript-eslint/parser from 5.57.0 to 5.57.1 by @dependabot in https://github.com/r3x5ur/unveilr/pull/59
35 | * ⬆️ Bump @typescript-eslint/parser from 5.57.1 to 5.58.0 by @dependabot in https://github.com/r3x5ur/unveilr/pull/72
36 | * ⬆️ Bump compressing from 1.8.0 to 1.9.0 by @dependabot in https://github.com/r3x5ur/unveilr/pull/71
37 | * ⬆️ Bump @typescript-eslint/eslint-plugin from 5.57.0 to 5.58.0 by @dependabot in https://github.com/r3x5ur/unveilr/pull/70
38 | * ⬆️ Bump typescript from 5.0.2 to 5.0.4 by @dependabot in https://github.com/r3x5ur/unveilr/pull/69
39 | * [PR] fix (core) "zArray Some cases of abnormal" by @r3x5ur in https://github.com/r3x5ur/unveilr/pull/77
40 | * hide unneeded message by @dem0ns in https://github.com/r3x5ur/unveilr/pull/78
41 | * [PR] fix (type) "deepCopy build error" by @r3x5ur in https://github.com/r3x5ur/unveilr/pull/79
42 | * [PR] feat(cli) "add `--clear-output` option by @r3x5ur in https://github.com/r3x5ur/unveilr/pull/80
43 | #### New Contributors
44 | * @dependabot made their first contribution in https://github.com/r3x5ur/unveilr/pull/22
45 | * @dem0ns made their first contribution in https://github.com/r3x5ur/unveilr/pull/78
46 | **Full Changelog**: https://github.com/r3x5ur/unveilr/compare/v1.0.2...v2.0.0
47 |
--------------------------------------------------------------------------------
/CODE_OF_CONDUCT.md:
--------------------------------------------------------------------------------
1 | # Contributor Covenant Code of Conduct
2 |
3 | ## Our Pledge
4 |
5 | We as members, contributors, and leaders pledge to make participation in our
6 | community a harassment-free experience for everyone, regardless of age, body
7 | size, visible or invisible disability, ethnicity, sex characteristics, gender
8 | identity and expression, level of experience, education, socio-economic status,
9 | nationality, personal appearance, race, religion, or sexual identity
10 | and orientation.
11 |
12 | We pledge to act and interact in ways that contribute to an open, welcoming,
13 | diverse, inclusive, and healthy community.
14 |
15 | ## Our Standards
16 |
17 | Examples of behavior that contributes to a positive environment for our
18 | community include:
19 |
20 | * Demonstrating empathy and kindness toward other people
21 | * Being respectful of differing opinions, viewpoints, and experiences
22 | * Giving and gracefully accepting constructive feedback
23 | * Accepting responsibility and apologizing to those affected by our mistakes,
24 | and learning from the experience
25 | * Focusing on what is best not just for us as individuals, but for the
26 | overall community
27 |
28 | Examples of unacceptable behavior include:
29 |
30 | * The use of sexualized language or imagery, and sexual attention or
31 | advances of any kind
32 | * Trolling, insulting or derogatory comments, and personal or political attacks
33 | * Public or private harassment
34 | * Publishing others' private information, such as a physical or email
35 | address, without their explicit permission
36 | * Other conduct which could reasonably be considered inappropriate in a
37 | professional setting
38 |
39 | ## Enforcement Responsibilities
40 |
41 | Community leaders are responsible for clarifying and enforcing our standards of
42 | acceptable behavior and will take appropriate and fair corrective action in
43 | response to any behavior that they deem inappropriate, threatening, offensive,
44 | or harmful.
45 |
46 | Community leaders have the right and responsibility to remove, edit, or reject
47 | comments, commits, code, wiki edits, issues, and other contributions that are
48 | not aligned to this Code of Conduct, and will communicate reasons for moderation
49 | decisions when appropriate.
50 |
51 | ## Scope
52 |
53 | This Code of Conduct applies within all community spaces, and also applies when
54 | an individual is officially representing the community in public spaces.
55 | Examples of representing our community include using an official e-mail address,
56 | posting via an official social media account, or acting as an appointed
57 | representative at an online or offline event.
58 |
59 | ## Enforcement
60 |
61 | Instances of abusive, harassing, or otherwise unacceptable behavior may be
62 | reported to the community leaders responsible for enforcement at
63 | 2352327206@qq.com.
64 | All complaints will be reviewed and investigated promptly and fairly.
65 |
66 | All community leaders are obligated to respect the privacy and security of the
67 | reporter of any incident.
68 |
69 | ## Enforcement Guidelines
70 |
71 | Community leaders will follow these Community Impact Guidelines in determining
72 | the consequences for any action they deem in violation of this Code of Conduct:
73 |
74 | ### 1. Correction
75 |
76 | **Community Impact**: Use of inappropriate language or other behavior deemed
77 | unprofessional or unwelcome in the community.
78 |
79 | **Consequence**: A private, written warning from community leaders, providing
80 | clarity around the nature of the violation and an explanation of why the
81 | behavior was inappropriate. A public apology may be requested.
82 |
83 | ### 2. Warning
84 |
85 | **Community Impact**: A violation through a single incident or series
86 | of actions.
87 |
88 | **Consequence**: A warning with consequences for continued behavior. No
89 | interaction with the people involved, including unsolicited interaction with
90 | those enforcing the Code of Conduct, for a specified period of time. This
91 | includes avoiding interactions in community spaces as well as external channels
92 | like social media. Violating these terms may lead to a temporary or
93 | permanent ban.
94 |
95 | ### 3. Temporary Ban
96 |
97 | **Community Impact**: A serious violation of community standards, including
98 | sustained inappropriate behavior.
99 |
100 | **Consequence**: A temporary ban from any sort of interaction or public
101 | communication with the community for a specified period of time. No public or
102 | private interaction with the people involved, including unsolicited interaction
103 | with those enforcing the Code of Conduct, is allowed during this period.
104 | Violating these terms may lead to a permanent ban.
105 |
106 | ### 4. Permanent Ban
107 |
108 | **Community Impact**: Demonstrating a pattern of violation of community
109 | standards, including sustained inappropriate behavior, harassment of an
110 | individual, or aggression toward or disparagement of classes of individuals.
111 |
112 | **Consequence**: A permanent ban from any sort of public interaction within
113 | the community.
114 |
115 | ## Attribution
116 |
117 | This Code of Conduct is adapted from the [Contributor Covenant][homepage],
118 | version 2.0, available at
119 | https://www.contributor-covenant.org/version/2/0/code_of_conduct.html.
120 |
121 | Community Impact Guidelines were inspired by [Mozilla's code of conduct
122 | enforcement ladder](https://github.com/mozilla/diversity).
123 |
124 | [homepage]: https://www.contributor-covenant.org
125 |
126 | For answers to common questions about this code of conduct, see the FAQ at
127 | https://www.contributor-covenant.org/faq. Translations are available at
128 | https://www.contributor-covenant.org/translations.
129 |
--------------------------------------------------------------------------------
/CONTRIBUTING.md:
--------------------------------------------------------------------------------
1 | ## 🤩🤩🤩
2 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 |
635 | Copyright (C)
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | Copyright (C)
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | 
2 | [][repo]
3 | [][repo]
4 | [](https://t.me/unveilr)
5 | [][repo]
6 | [][repo]
7 | [][repo]
8 | [][repo]
9 |
10 |
11 | ## 免责声明
12 | - **本程序仅供于学习交流,请使用者遵守《中华人民共和国网络安全法》,勿将此工具用于非法操作,开发者不负任何连带法律责任。**
13 | - **如有任何侵权相关问题,请联系作者。**
14 | - **本工具仅面向合法授权的企业安全建设行为,如您需要测试本工具的可用性,请自行搭建测试环境。**
15 | - **在使用本工具进行时,您应确保该行为符合当地的法律法规,并且已经取得了足够的授权。**
16 |
17 | ### 什么是unveilr?
18 | > [
][repo]
19 | > `unveilr` 是一款小程序安全评估工具,支持小程序的代码审计和发现敏感信息泄露、接口未授权等安全问题
20 |
21 | ### ✅安装方法
22 | - 使用 `node > 12` 环境自行构建
23 | - 不会安装的[找我](https://t.me/unveilr)
24 |
25 | ### 📝参数详解
26 |
27 | - 子命令默认为 `wx`
28 | > [
][repo]
29 |
30 | | 子命令 | 参数 | 解释 |
31 | |------|---------------------------|------------------------------------------------|
32 | | | `-l, --log-level ` | 设置日志等级 `debug`,`info`,`warn`,`error` 默认 `info` |
33 | | | `-v, --version` | 打印版本号并退出 |
34 | | `wx` | `` | 包的路径,可以是多个,也可以是一个目录 |
35 | | `wx` | `-i, --appid ` | 手动提供`appid` (仅在评估`windows`上的包时有效) |
36 | | `wx` | `-f, --format` | 格式化输出 |
37 | | `wx` | `--no-clear-decompile` | 解析后的残留文件将不会被清除 |
38 | | `wx` | `--no-clear-save` | 要保存的路径将不会被清除 |
39 | | `wx` | `--no-parse` | 只提取文件,但不会解析 |
40 | | `wx` | `-d, --depth ` | 设置从目录中查找深度,默认: `1` 设置为`0`时不限制深度 |
41 | | `wx` | ` -o, --output ` | 设置输出目录 |
42 | | `wx` | `--clear-output` | 当输出目录不为空时程序将终止,提供该参数表示强制清空输出目录 |
43 |
44 |
45 | ### [💡提交问题](https://github.com/r3x5ur/unveilr/issues)
46 |
47 | ### [📝更改日志](https://github.com/r3x5ur/unveilr/blob/master/CHANGELOG.md)
48 |
49 | ### 💬其他说明
50 |
51 | - 本程序现在使用的开源协议是 [GPL-3.0](https://www.gnu.org/licenses/gpl-3.0.html)
52 | - 使用请标明出处,并遵循开源协议
53 |
54 |
55 |
56 | [repo]:https://github.com/r3x5ur/unveilr
57 |
--------------------------------------------------------------------------------
/SECURITY.md:
--------------------------------------------------------------------------------
1 | # 提交安全问题
2 |
--------------------------------------------------------------------------------
/images/logo.svg:
--------------------------------------------------------------------------------
1 |
2 |
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "unveilr",
3 | "author": "r3x5ur",
4 | "version": "2.0.2",
5 | "displayName": "一款小程序安全评估工具",
6 | "keywords": [
7 | "wxapkg",
8 | "微信小程序",
9 | "微信小游戏",
10 | "unveilr",
11 | "抖音小程序",
12 | "抖音小游戏"
13 | ],
14 | "description": "一款小程序安全评估工具,支持小程序的代码审计和发现敏感信息泄露、接口未授权等安全问题",
15 | "main": "dist/index.js",
16 | "license": "GPL-3.0",
17 | "repository": {
18 | "type": "git",
19 | "url": "https://github.com/r3x5ur/unveilr"
20 | },
21 | "bugs": "https://github.com/r3x5ur/unveilr/issues",
22 | "engines": {
23 | "node": ">=12.0.0"
24 | },
25 | "scripts": {
26 | "eslint": "eslint --fix src --ext .ts --max-warnings=0",
27 | "dev": "ts-node-dev -r tsconfig-paths/register --respawn --transpile-only src/index.ts",
28 | "run": "ts-node -r tsconfig-paths/register --transpile-only src/index.ts",
29 | "ts-node": "ts-node -r tsconfig-paths/register --transpile-only",
30 | "build": "npx rollup -c --bundleConfigAsCjs"
31 | },
32 | "dependencies": {
33 | "@babel/core": "^7.21.3",
34 | "chalk": "4.1.2",
35 | "commander": "^10.0.0",
36 | "crypto-js": "^4.1.1",
37 | "css-tree": "^2.3.1",
38 | "escodegen": "^2.0.0",
39 | "esprima": "^4.0.1",
40 | "observable-fns": "^0.6.1",
41 | "prettier": "^2.8.8",
42 | "threads": "^1.7.0",
43 | "vm2": "^3.9.19",
44 | "winston": "^3.8.2"
45 | },
46 | "devDependencies": {
47 | "@rollup/plugin-babel": "^6.0.3",
48 | "@rollup/plugin-commonjs": "^25.0.0",
49 | "@rollup/plugin-json": "^6.0.0",
50 | "@rollup/plugin-node-resolve": "^15.0.1",
51 | "@types/babel__core": "^7.20.0",
52 | "@types/babel__traverse": "^7.18.3",
53 | "@types/crypto-js": "^4.1.1",
54 | "@types/css-tree": "^2.3.1",
55 | "@types/escodegen": "^0.0.7",
56 | "@types/esprima": "^4.0.3",
57 | "@types/node": "^18.14.4",
58 | "@types/prettier": "^2.7.2",
59 | "@typescript-eslint/eslint-plugin": "^5.59.7",
60 | "@typescript-eslint/parser": "^5.59.7",
61 | "babel-plugin-static-fs": "^3.0.0",
62 | "compressing": "^1.8.0",
63 | "eslint": "8.22.0",
64 | "javascript-obfuscator": "^4.0.2",
65 | "pkg": "^5.8.1",
66 | "rollup": "^3.23.0",
67 | "rollup-plugin-clear": "^2.0.7",
68 | "rollup-plugin-license": "^3.0.1",
69 | "rollup-plugin-obfuscator": "^1.0.3",
70 | "rollup-plugin-terser": "^7.0.2",
71 | "rollup-plugin-typescript2": "^0.34.1",
72 | "ts-node-dev": "^2.0.0",
73 | "tsconfig-paths": "^4.1.2",
74 | "typescript": "^5.0.2"
75 | }
76 | }
77 |
--------------------------------------------------------------------------------
/rollup.config.js:
--------------------------------------------------------------------------------
1 | import { join } from 'path'
2 | import json from '@rollup/plugin-json'
3 | import commonjs from '@rollup/plugin-commonjs'
4 | import nodeResolve from '@rollup/plugin-node-resolve'
5 | import typescript from 'rollup-plugin-typescript2'
6 | import license from 'rollup-plugin-license'
7 | import clear from 'rollup-plugin-clear'
8 | import babel from '@rollup/plugin-babel'
9 | import staticFs from 'babel-plugin-static-fs'
10 | import obfuscator from 'rollup-plugin-obfuscator'
11 | import { terser } from 'rollup-plugin-terser'
12 | import { dependencies } from './package.json'
13 | import { basename, dirname } from 'path'
14 |
15 | const output = {
16 | dir: 'dist',
17 | format: 'cjs',
18 | manualChunks(id) {
19 | if (id.endsWith('worker.ts')) {
20 | return ['chunk', basename(dirname(id))].join('-')
21 | }
22 | },
23 | }
24 | export default {
25 | input: 'src/index.ts',
26 | output,
27 | external: Object.keys(dependencies).filter((item) => item !== 'vm2'),
28 | plugins: [
29 | clear({
30 | targets: [output.dir],
31 | }),
32 | typescript({
33 | tsconfigOverride: {
34 | compilerOptions: {
35 | module: 'ES2015',
36 | declaration: false,
37 | },
38 | },
39 | }),
40 | babel({
41 | babelHelpers: 'inline',
42 | plugins: [staticFs],
43 | }),
44 | commonjs(),
45 | nodeResolve({ preferBuiltins: true }),
46 | json(),
47 | obfuscator({
48 | options: {
49 | compact: false,
50 | splitStrings: true,
51 | debugProtection: true,
52 | controlFlowFlattening: true,
53 | },
54 | }),
55 | terser(),
56 | license({
57 | banner: {
58 | commentStyle: 'ignored',
59 | content:
60 | '<%= pkg.name %> v<%= pkg.version %>\n' +
61 | '(c) 2023 <%= pkg.author %>\n' +
62 | 'Released under the <%= pkg.license %> License.',
63 | },
64 | thirdParty: {
65 | output: join(__dirname, 'dist', 'dependencies.txt'),
66 | },
67 | }),
68 | ],
69 | cache: false,
70 | strictDeprecations: true,
71 | treeshake: {
72 | moduleSideEffects: false,
73 | propertyReadSideEffects: false,
74 | tryCatchDeoptimization: false,
75 | },
76 | }
77 |
--------------------------------------------------------------------------------
/scripts/pkg.js:
--------------------------------------------------------------------------------
1 | const { rmSync, readdirSync } = require('fs')
2 | const { join } = require('path')
3 | const { execSync } = require('child_process')
4 | const { exec } = require('pkg')
5 | const { name, version } = require('../package.json')
6 | const { tgz } = require('compressing')
7 |
8 | const distIndex = 'dist/index.js'
9 | const release = 'release'
10 |
11 | function log(message) {
12 | console.log(`[PKG] ${message}`)
13 | }
14 |
15 | /**
16 | * - nodeRange (node8), node10, node12, node14, node16 or latest
17 | * - platform alpine, linux, linuxstatic, win, macos, (freebsd)
18 | * - arch x64, arm64, (armv6, armv7)
19 | * */
20 | async function pkg(targets) {
21 | log('Clean up old binaries...')
22 | rmSync(release, { force: true, recursive: true })
23 | targets = targets || [
24 | 'node14-win-x64',
25 | 'node14-win-arm64',
26 | 'node14-macos-x64',
27 | 'node14-macos-arm64',
28 | 'node14-linux-x64',
29 | 'node14-linux-arm64',
30 | ]
31 | const pkgCmd =
32 | `-C GZip -t ${targets.toString()} --no-bytecode --public-packages "*" --public -o ${release}/${name}@${version} ${distIndex}`
33 | .split(' ')
34 | .filter(Boolean)
35 | log('Generating binaries...')
36 | await exec(pkgCmd)
37 | }
38 |
39 | async function _tgz() {
40 | const files = readdirSync(release)
41 | for (const p of files) {
42 | const source = join(release, p)
43 | const dest = source + '.tar.gz'
44 | log(`Generating dest ${dest}`)
45 | await tgz.compressFile(source, dest)
46 | rmSync(source)
47 | }
48 | }
49 | async function main() {
50 | log('Building distribution...')
51 | execSync('yarn build')
52 | // await pkg()
53 | await pkg(['node14-win-x64']).then()
54 | // await _tgz()
55 | }
56 |
57 | main().then()
58 |
--------------------------------------------------------------------------------
/src/cli/commands/ttapkg.ts:
--------------------------------------------------------------------------------
1 | import { Command } from 'commander'
2 |
3 | const ttCommand = new Command('tt')
4 |
5 | export default ttCommand
6 |
--------------------------------------------------------------------------------
/src/cli/commands/wxapkg.ts:
--------------------------------------------------------------------------------
1 | import { Command, Argument, Option, CommanderError } from 'commander'
2 | import { outputConfig } from '@/cli/config/outputConfig'
3 |
4 | const wxCommand = new Command('wx')
5 | // read-depth
6 | const noParseOption = new Option('-p, --no-parse', 'Only extract files, do not parse').implies({
7 | clearDecompile: false,
8 | })
9 | const depthOptions = new Option(
10 | '-d, --depth ',
11 | 'Set the search depth from the directory, no limit depth when set to 0',
12 | )
13 | .argParser((v) => {
14 | const depth = parseInt(v)
15 | if (isNaN(depth)) throw new CommanderError(1, 'depth.error', 'Invalid depth')
16 | return depth
17 | })
18 | .default(1)
19 | wxCommand
20 | .option('-i, --appid ', 'Provide `appid` manually (only works when evaluating packages on `windows`)')
21 | .option('-f, --format', 'Reformatted output')
22 | .option('--no-clear-parsed', 'Residual files after parsing will not be cleared')
23 | .option('--no-clear-save', 'Paths to save will not be cleared')
24 | .addOption(noParseOption)
25 | .addOption(depthOptions)
26 | .option('-o, --output ', 'Set output path, default: main package whit out')
27 | .option('--clear-output', 'Empty the specified output folder')
28 | .description('Security assessment for wx applet')
29 | .addArgument(new Argument('', 'The path of the package can be multiple or a directory'))
30 | .showHelpAfterError()
31 | .configureOutput(outputConfig)
32 | export default wxCommand
33 |
34 | export interface WxConfigurator {
35 | appid?: string
36 | format?: boolean
37 | clearDecompile: boolean
38 | clearSave: boolean
39 | parse: boolean
40 | depth: number
41 | output?: string
42 | clearOutput?: boolean
43 | packages: string[]
44 | }
45 |
--------------------------------------------------------------------------------
/src/cli/config/outputConfig.ts:
--------------------------------------------------------------------------------
1 | import { OutputConfiguration } from 'commander'
2 | import { green, red, yellow } from '@utils/colors'
3 |
4 | export const outputConfig: OutputConfiguration = {
5 | writeOut(str: string) {
6 | process.stdout.write(green(str))
7 | },
8 | writeErr(str: string) {
9 | process.stdout.write(yellow(str))
10 | },
11 | outputError(str: string, write) {
12 | write(red(str))
13 | },
14 | }
15 |
--------------------------------------------------------------------------------
/src/cli/index.ts:
--------------------------------------------------------------------------------
1 | import { Command, Option } from 'commander'
2 | import wxCommand, { WxConfigurator } from '@/cli/commands/wxapkg'
3 | import { LoggerLevel } from '@utils/logger'
4 | import { outputConfig } from '@/cli/config/outputConfig'
5 | // import ttCommand from '@/cli/commands/ttapkg'
6 |
7 | export interface CliConfigurator {
8 | global: {
9 | logLevel: LoggerLevel
10 | }
11 | wx: WxConfigurator
12 | }
13 |
14 | export function registerCommand(version: string, name: string, _argv?: string[]): CliConfigurator {
15 | const argv = _argv || process.argv
16 | const logLevel = new Option('-l, --log-level ', 'Set log level')
17 | .choices(['debug', 'info', 'warn', 'error'])
18 | .default('info')
19 | const cmd = new Command(name)
20 | cmd
21 | .usage('[wx] [options]')
22 | .version(version, '-v, --version')
23 | .addOption(logLevel)
24 | .addCommand(wxCommand, { isDefault: true })
25 | // .addCommand(ttCommand)
26 | .addHelpText(
27 | 'after',
28 | `
29 | Example:
30 | $ ${name} /path/to/dir/ Default wx subcommand
31 | $ ${name} -f /path/to/dir/ Reformat output
32 | $ ${name} -f -o /target/dir/ /path/to/dir/ Reformat output & set output path
33 | ...
34 | `,
35 | )
36 | .showHelpAfterError()
37 | .configureOutput(outputConfig)
38 | .parse(argv)
39 | if (!argv.length) return cmd.help({ error: true })
40 | return {
41 | global: cmd.opts(),
42 | wx: {
43 | ...wxCommand.opts(),
44 | packages: wxCommand.args,
45 | },
46 | } as CliConfigurator
47 | }
48 |
--------------------------------------------------------------------------------
/src/core/base/BaseDecryptor.ts:
--------------------------------------------------------------------------------
1 | import { PathController, ProduciblePath } from './controller/PathController'
2 | import { Saver } from '@utils/classes/Saver'
3 | import { BaseError } from '@utils/exceptions'
4 | import { BaseLogger } from '@utils/logger'
5 |
6 | export class DecryptorError extends BaseError {}
7 | export class BaseDecryptor extends BaseLogger {
8 | readonly pathCtrl: PathController
9 | protected suffix: string
10 | readonly saver: Saver
11 | constructor(path: ProduciblePath) {
12 | super()
13 | this.pathCtrl = PathController.make(path)
14 | this.saver = new Saver(this.pathCtrl.dirname)
15 | }
16 |
17 | get decipherable() {
18 | return this.pathCtrl.isFile && this.pathCtrl.suffixWithout === this.suffix
19 | }
20 |
21 | decrypt(): void {
22 | if (!this.decipherable) {
23 | DecryptorError.throw(`File ${this.pathCtrl.logpath} cannot be decrypted!`)
24 | }
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/src/core/base/BaseExtractor.ts:
--------------------------------------------------------------------------------
1 | import { PathController, ProduciblePath } from './controller/PathController'
2 | import { BaseError } from '@utils/exceptions'
3 | import { BaseLogger } from '@utils/logger'
4 |
5 | export class ExtractorError extends BaseError {}
6 | export class BaseExtractor extends BaseLogger {
7 | readonly pathCtrl: PathController
8 | protected suffix: string
9 | constructor(path: ProduciblePath) {
10 | super()
11 | this.pathCtrl = PathController.make(path)
12 | }
13 |
14 | get extractable() {
15 | return this.pathCtrl.isFile && this.pathCtrl.suffixWithout === this.suffix
16 | }
17 |
18 | extract(): void {
19 | if (!this.extractable) {
20 | ExtractorError.throw(`File ${this.pathCtrl.logpath} cannot be extracted!`)
21 | }
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/src/core/base/BaseParser.ts:
--------------------------------------------------------------------------------
1 | import { Saver } from '@utils/classes/Saver'
2 | import { BaseError } from '@utils/exceptions'
3 | import { BaseLogger } from '@utils/logger'
4 |
5 | export class ParserError extends BaseError {}
6 | export abstract class BaseParser extends BaseLogger {
7 | protected saver: Saver
8 | protected constructor(saver: Saver) {
9 | super()
10 | this.saver = saver
11 | }
12 | abstract parse(...args: unknown[]): unknown
13 | }
14 |
--------------------------------------------------------------------------------
/src/core/base/controller/ConfigController.ts:
--------------------------------------------------------------------------------
1 | import { CliConfigurator } from '@/cli'
2 |
3 | export class ConfigController {
4 | private readonly config: CliConfigurator
5 | private constructor(config: CliConfigurator) {
6 | this.config = config
7 | }
8 |
9 | get innerConfig(): Readonly {
10 | return Object.freeze(this.config)
11 | }
12 |
13 | get logLevel() {
14 | return this.config.global.logLevel
15 | }
16 | get WXReformat() {
17 | return this.config.wx.format
18 | }
19 | get WXClearDecompile() {
20 | return this.WXParse && this.config.wx.clearDecompile
21 | }
22 | get WXClearSave() {
23 | return this.config.wx.clearSave
24 | }
25 | get WXDepth() {
26 | return this.config.wx.depth
27 | }
28 | get WXParse() {
29 | return this.config.wx.parse
30 | }
31 | get WXPackages() {
32 | return this.config.wx.packages
33 | }
34 | get WXAppId() {
35 | return this.config.wx.appid
36 | }
37 | get WXOutput() {
38 | return this.config.wx.output
39 | }
40 | get WxClearOutput() {
41 | return this.config.wx.clearOutput
42 | }
43 |
44 | static instance: ConfigController
45 |
46 | static init(config: CliConfigurator): void {
47 | if (!ConfigController.instance) {
48 | ConfigController.instance = new ConfigController(config)
49 | }
50 | }
51 |
52 | static getInstance(): ConfigController {
53 | if (!ConfigController.instance) throw ReferenceError('ConfigController is not initialized')
54 | return ConfigController.instance
55 | }
56 | }
57 |
58 | export function getConfig(key: T): ConfigController[T] {
59 | const inst = ConfigController.getInstance()
60 | if (!key) throw ReferenceError(`Config name is required`)
61 | return inst[key]
62 | }
63 |
64 | export function initializeConfig(config: CliConfigurator) {
65 | ConfigController.init(config)
66 | }
67 |
68 | export function getInnerConfig() {
69 | const inst = ConfigController.getInstance()
70 | return inst.innerConfig
71 | }
72 |
--------------------------------------------------------------------------------
/src/core/base/controller/PathController.ts:
--------------------------------------------------------------------------------
1 | import {
2 | readFileSync,
3 | WriteFileOptions,
4 | writeFileSync,
5 | statSync,
6 | existsSync,
7 | mkdirSync,
8 | readdirSync,
9 | copyFileSync,
10 | unlinkSync,
11 | rmdirSync,
12 | rmSync,
13 | } from 'fs'
14 | import { readdir, readFile, writeFile, unlink, rm } from 'fs/promises'
15 | import { sep, dirname, extname, join, resolve, basename, relative, isAbsolute } from 'path'
16 | import { ObjectEncodingOptions, OpenMode } from 'node:fs'
17 | import { Abortable } from 'node:events'
18 | import { grey } from '@utils/colors'
19 |
20 | export type ProduciblePath = string | PathController
21 | export type Optional = T | null
22 | export type ReadDirStringOption =
23 | | (ObjectEncodingOptions & {
24 | withFileTypes?: false | undefined
25 | })
26 | | BufferEncoding
27 | | null
28 | export type ReadBufferOption =
29 | | ({
30 | encoding?: null | undefined
31 | flag?: OpenMode | undefined
32 | } & Abortable)
33 | | null
34 | export type ReadStringOption =
35 | | (ObjectEncodingOptions &
36 | Abortable & {
37 | flag?: OpenMode | undefined
38 | })
39 | | BufferEncoding
40 | | null
41 |
42 | export class PathController {
43 | readonly path: string
44 | exists = false
45 | isDirectory = false
46 | isFile = false
47 |
48 | constructor(path?: string) {
49 | this.path = path || ''
50 | this.reload()
51 | }
52 |
53 | reload(): this {
54 | this.exists = existsSync(this.path)
55 | if (this.exists) {
56 | try {
57 | const stat = statSync(this.path)
58 | this.isDirectory = stat.isDirectory()
59 | this.isFile = stat.isFile()
60 | } catch (e) {
61 | if (e.errno === -4058) this.exists = false
62 | this.isDirectory = false
63 | this.isFile = false
64 | }
65 | }
66 | return this
67 | }
68 | get suffix(): string {
69 | return extname(this.path)
70 | }
71 |
72 | get suffixWithout(): string {
73 | return this.suffix.slice(1)
74 | }
75 |
76 | get abspath(): string {
77 | return resolve(this.path)
78 | }
79 |
80 | get unixpath(): string {
81 | if (sep === '/') return this.path
82 | return this.path.replace(/\\/g, '/')
83 | }
84 |
85 | get absunixpath(): string {
86 | return PathController.make(this.abspath).unixpath
87 | }
88 |
89 | get logpath(): string {
90 | const dirML = 80
91 | const s =
92 | this.abspath.length - this.basename.length <= dirML
93 | ? this.abspath
94 | : this.abspath.slice(0, dirML) + '...' + this.basename
95 | return grey(s)
96 | }
97 |
98 | get dirname(): string {
99 | if (this.isDirectory) return this.path
100 | if (this.isFile) return dirname(this.path)
101 | return dirname(this.path)
102 | }
103 |
104 | get basename(): string {
105 | return basename(this.path)
106 | }
107 |
108 | get basenameWithout(): string {
109 | return basename(this.path, this.suffix)
110 | }
111 |
112 | get isAbs() {
113 | return isAbsolute(this.path)
114 | }
115 |
116 | relative(p: ProduciblePath): PathController {
117 | return PathController.make(relative(this.path, PathController.make(p).path))
118 | }
119 |
120 | async readdir(opt?: ReadDirStringOption, absolutePath?: boolean): Promise {
121 | if (!this.isDirectory) return null
122 | const list = await readdir(this.path, opt)
123 | return absolutePath ? list.map((v) => resolve(this.abspath, v)) : list
124 | }
125 |
126 | async read(opt?: ReadBufferOption): Promise
127 | async read(opt?: ReadStringOption): Promise
128 | async read(opt?: never): Promise {
129 | if (!this.isFile) return null
130 | return await readFile(this.path, opt)
131 | }
132 |
133 | readSync(opt?: ReadBufferOption): Buffer
134 | readSync(opt?: ReadStringOption): string
135 | readSync(opt?: never): Buffer | string {
136 | return readFileSync(this.path, opt)
137 | }
138 |
139 | async write(data: string | NodeJS.ArrayBufferView, options?: WriteFileOptions): Promise {
140 | await writeFile(this.abspath, data, options)
141 | return this
142 | }
143 | writeSync(data: string | NodeJS.ArrayBufferView, options?: WriteFileOptions): this {
144 | writeFileSync(this.abspath, data, options)
145 | return this
146 | }
147 |
148 | async writeJSON(data: object): Promise {
149 | return this.write(JSON.stringify(data, null, 2), 'utf8')
150 | }
151 |
152 | writeJSONSync(data: object): this {
153 | return this.writeSync(JSON.stringify(data, null, 2), 'utf8')
154 | }
155 |
156 | copy(_target: ProduciblePath): PathController {
157 | // copy single path
158 | const target = PathController.make(_target)
159 | if (this.isFile) return copyFileSync(this.path, target.mkdir().abspath), this
160 | // deep copy multiple directory
161 | if (this.isDirectory) {
162 | target.mkdir(true)
163 | this.deepListDir().forEach((t) => {
164 | const _tp = PathController.make(join(target.abspath, t.replace(this.abspath, '')))
165 | copyFileSync(t, _tp.mkdir().abspath)
166 | })
167 | return this
168 | }
169 | return this
170 | }
171 |
172 | move(_target: ProduciblePath): PathController {
173 | this.copy(_target).abspath
174 | if (this.isFile) unlinkSync(this.abspath)
175 | else if (this.isDirectory) rmdirSync(this.abspath, { recursive: true })
176 | return PathController.make(_target)
177 | }
178 |
179 | mkdir(self?: boolean): Optional {
180 | if (this.exists) return this
181 | const _path = self ? this.path : dirname(this.path)
182 | mkdirSync(_path, { recursive: true })
183 | this.reload()
184 | return this
185 | }
186 | async unlink(): Promise {
187 | await unlink(this.abspath)
188 | // this.reload()
189 | }
190 | unlinkSync(): void {
191 | unlinkSync(this.abspath)
192 | this.reload()
193 | }
194 | deepListDir(depth: number): string[]
195 | deepListDir(absolute?: boolean, depth?: number): string[]
196 | deepListDir(arg1?: boolean | number, arg2?: number): string[] {
197 | if (!this.isDirectory) return []
198 | const list: string[] = []
199 | let absolute: boolean
200 | let depth: number
201 | const deepPath = absolute ? this.absunixpath : this.unixpath
202 | switch (arguments.length) {
203 | case 0:
204 | absolute = false
205 | depth = Number.MAX_SAFE_INTEGER
206 | break
207 | case 1:
208 | if (typeof arg1 === 'boolean') {
209 | absolute = arg1
210 | depth = Number.MAX_SAFE_INTEGER
211 | } else if (typeof arg1 === 'number') {
212 | absolute = false
213 | depth = arg1 || Number.MAX_SAFE_INTEGER
214 | } else {
215 | throw new Error('arg1 must be boolean or number')
216 | }
217 | break
218 | case 2:
219 | absolute = arg1 as boolean
220 | depth = arg2 || Number.MAX_SAFE_INTEGER
221 | }
222 | const listFile = (dir: string): void => {
223 | readdirSync(dir).forEach((item) => {
224 | const fullPath = join(dir, item)
225 | if (statSync(fullPath).isDirectory()) {
226 | if (depth !== Number.MAX_SAFE_INTEGER) {
227 | // 一层不需要往下判断了
228 | if (depth === 1) return
229 | let prevDeep
230 | if (dir === deepPath) prevDeep = 1
231 | else {
232 | const croppedPath = PathController.make(dir).crop(deepPath).unixpath
233 | prevDeep = croppedPath.split('/').length + 1
234 | }
235 | if (prevDeep >= depth) return
236 | }
237 | listFile(fullPath)
238 | } else {
239 | list.push(fullPath)
240 | }
241 | })
242 | }
243 | listFile(deepPath)
244 | return list
245 | }
246 |
247 | join(...paths: string[]): PathController {
248 | return PathController.make(join(this.path, ...paths))
249 | }
250 |
251 | whitout(suffix?: string): PathController {
252 | return this.join('..', this.basenameWithout + (suffix || ''))
253 | }
254 |
255 | unix(): PathController {
256 | return PathController.make(this.unixpath)
257 | }
258 |
259 | crop(path: ProduciblePath): PathController {
260 | const newPath = this.unixpath.replace(PathController.make(path).unixpath + '/', '')
261 | return PathController.make(newPath)
262 | }
263 |
264 | async rmrf() {
265 | await rm(this.abspath, { recursive: true, force: true })
266 | }
267 | rmrfSync() {
268 | rmSync(this.abspath, { recursive: true, force: true })
269 | }
270 |
271 | toString(): string {
272 | return this.logpath
273 | }
274 |
275 | static unix(path: ProduciblePath): PathController {
276 | return PathController.make(path).unix()
277 | }
278 |
279 | static whitout(path: ProduciblePath, suffix?: string): PathController {
280 | return PathController.make(path).whitout(suffix)
281 | }
282 |
283 | static make(path?: ProduciblePath): PathController {
284 | path = path || ''
285 | return path instanceof PathController ? path : new PathController(path)
286 | }
287 |
288 | static dir(path: ProduciblePath): PathController {
289 | return PathController.make(PathController.make(path).dirname)
290 | }
291 | }
292 |
293 | export function isProduciblePath(value: unknown): value is ProduciblePath {
294 | return typeof value === 'string' || value instanceof PathController
295 | }
296 |
--------------------------------------------------------------------------------
/src/core/base/controller/SaveController.ts:
--------------------------------------------------------------------------------
1 | import { BaseLogger } from '@utils/logger'
2 | import { PathController, ProduciblePath } from './PathController'
3 | import { info } from '@utils/colors'
4 | import { checkSupport, reformat } from '@utils/reformat'
5 |
6 | export type SaveAble = string | Buffer | object
7 | export interface SaveAbleItem {
8 | key: string
9 | buffer: SaveAble
10 | }
11 | type Bucket = Map
12 |
13 | export class SaveController extends BaseLogger {
14 | static instance: SaveController
15 | static isClean = false
16 | static isSafeMode = false
17 | static isReFormat = false
18 | static readonly OVERRIDE_FILES: string[] = []
19 | static getInstance(): SaveController {
20 | if (!SaveController.instance) {
21 | SaveController.instance = new SaveController()
22 | }
23 | return SaveController.instance
24 | }
25 | static setIsClean(isClean: boolean) {
26 | SaveController.isClean = isClean
27 | }
28 | static setIsSafeMode(isSafeMode: boolean) {
29 | SaveController.isSafeMode = isSafeMode
30 | isSafeMode && getSaveController().logger.warn(`Safe mode is enabled, Will not write files to disk`)
31 | }
32 | static addOverrideFiles(overrideFiles: string[]) {
33 | SaveController.OVERRIDE_FILES.push(...overrideFiles)
34 | }
35 |
36 | static setIsReFormat(isReFormat: boolean) {
37 | SaveController.isReFormat = isReFormat
38 | isReFormat && getSaveController().logger.warn(`Turning on code formatting can slow down some operations`)
39 | }
40 |
41 | private readonly fileBucket: Bucket
42 | private constructor() {
43 | super('Bucket')
44 | this.fileBucket = new Map()
45 | }
46 | get keys() {
47 | return Array.from(this.fileBucket.keys())
48 | }
49 |
50 | // 返回长度最大的数据
51 | private saveAbleMax(s1: SaveAble, s2: SaveAble): SaveAble
52 | private saveAbleMax(...args: SaveAble[]): SaveAble {
53 | const length = (s: SaveAble) => (Buffer.isBuffer(s) || typeof s === 'string' ? s.length : JSON.stringify(s).length)
54 | const map = new Map()
55 | args.forEach((_s) => map.set(length(_s), _s))
56 | return map.get(Math.max(...map.keys()))
57 | }
58 |
59 | set(path: string, buffer: SaveAble) {
60 | if (!path) return
61 | if (!PathController.make(path).isAbs) {
62 | this.logger.warn(`Path ${path} is not absolute!`)
63 | return
64 | }
65 | if (this.fileBucket.has(path)) {
66 | // 部分文件需要被覆盖不需要比较
67 | if (!SaveController.OVERRIDE_FILES.includes(PathController.make(path).basename)) {
68 | buffer = this.saveAbleMax(this.fileBucket.get(path), buffer)
69 | }
70 | }
71 | this.fileBucket.set(path, buffer)
72 | }
73 | get(path: string): T | null {
74 | if (!path) return null
75 | const ctrl = PathController.make(path)
76 | return (this.fileBucket.get(ctrl.isAbs ? ctrl.path : ctrl.abspath) as T) || null
77 | }
78 | delete(path: string, force?: boolean): boolean {
79 | if (!force && !SaveController.isClean) return false
80 | if (!path) return false
81 | const ctrl = PathController.make(path)
82 | if (!ctrl.isAbs) return false
83 | return this.fileBucket.delete(ctrl.path)
84 | }
85 | pop(path: string, force?: boolean): T | null {
86 | const data: T = this.get(path)
87 | this.delete(path, force)
88 | return data || null
89 | }
90 |
91 | private async saveFile(path: string, buffer: SaveAble) {
92 | const ctrl = PathController.make(path)
93 | if (!buffer) {
94 | this.logger.debug(`You are trying to save a falsy data to ${ctrl.logpath}`)
95 | buffer = ''
96 | }
97 | ctrl.mkdir()
98 | let type
99 | const flush = async (key: 'write' | 'writeUtf8' | 'writeJSON') => {
100 | switch (key) {
101 | case 'write':
102 | await ctrl.write(buffer as Buffer)
103 | break
104 | case 'writeUtf8':
105 | await ctrl.write(String(buffer), 'utf8')
106 | break
107 | case 'writeJSON':
108 | await ctrl.writeJSON(buffer as object)
109 | break
110 | }
111 | }
112 | let retPromise: Promise
113 | if (typeof buffer === 'string') {
114 | retPromise = flush('writeUtf8')
115 | type = `source-${ctrl.suffixWithout}`
116 | } else if (Buffer.isBuffer(buffer)) {
117 | retPromise = flush('write')
118 | type = 'binary'
119 | } else if (typeof buffer === 'object') {
120 | retPromise = flush('writeJSON')
121 | type = 'json'
122 | } else {
123 | this.logger.warn(`Path ${ctrl.path} not allow write type: ${typeof buffer}`)
124 | retPromise = flush('writeUtf8')
125 | }
126 | type && this.logger.debug(`File ${type} save to ${ctrl.logpath}`)
127 | return retPromise
128 | }
129 | async flashDisk() {
130 | if (SaveController.isSafeMode) return
131 | this.logger.debug('Flashing disk...')
132 | const promiseAll = this.keys
133 | .map((path) => {
134 | try {
135 | let buffer = this.pop(path, true)
136 | if (SaveController.isReFormat && checkSupport(path)) {
137 | buffer = reformat(path, saveAble2String(buffer))
138 | }
139 | return this.saveFile(path, buffer)
140 | } catch (e) {
141 | this.logger.error(`Error when saving file ${path}: ${e}`)
142 | }
143 | return null
144 | })
145 | .filter(Boolean)
146 | await Promise.all(promiseAll)
147 | const count = promiseAll.length.toString()
148 | count && this.logger.info(`Storage has written ${info(count)} files`)
149 | }
150 | find(prefix: string): SaveAbleItem[] {
151 | const keys = this.fileBucket.keys()
152 | const result: SaveAbleItem[] = []
153 | if (!prefix) return []
154 | for (const key of keys) {
155 | if (!key.startsWith(prefix)) continue
156 | const buffer = this.get(key)
157 | if (!buffer) continue
158 | result.push({ key, buffer })
159 | }
160 | return result.filter(Boolean)
161 | }
162 | }
163 |
164 | export async function flashDisk() {
165 | await getSaveController().flashDisk()
166 | }
167 |
168 | export function findBuffer(path: ProduciblePath): SaveAbleItem[] {
169 | const prefix = PathController.make(path).abspath
170 | return getSaveController().find(prefix)
171 | }
172 |
173 | export function saveAble2String(buffer: SaveAble): string {
174 | if (!buffer) return ''
175 | if (Buffer.isBuffer(buffer)) return buffer.toString()
176 | if (typeof buffer === 'string') return buffer
177 | return JSON.stringify(buffer)
178 | }
179 |
180 | export function getSaveController() {
181 | return SaveController.getInstance()
182 | }
183 |
--------------------------------------------------------------------------------
/src/core/base/controller/TraverseController.ts:
--------------------------------------------------------------------------------
1 | import { TraverseOptions, Visitor } from '@babel/traverse'
2 | import { BabelFileResult } from '@babel/core'
3 | import { ProduciblePath } from './PathController'
4 | import { BuildParams, traverseAST } from '@utils/ast'
5 |
6 | export class TraverseController {
7 | visitors: Visitor
8 | private fileBuilder: BabelFileResult | ProduciblePath | BuildParams
9 | constructor(path: ProduciblePath, opt?: TraverseOptions)
10 | constructor(builder: BuildParams, opt?: TraverseOptions)
11 | constructor(file: BabelFileResult, opt?: TraverseOptions)
12 | constructor(fileBuilder: BabelFileResult | ProduciblePath | BuildParams, visitor?: Visitor) {
13 | this.setFileBuilder(fileBuilder)
14 | this.addVisitors(visitor)
15 | }
16 |
17 | addVisitors(...visitors: Visitor[]): this {
18 | this.visitors = this._mergeVisitors(...visitors)
19 | return this
20 | }
21 |
22 | async traverse(opt?: Pick): Promise {
23 | return traverseAST(this.fileBuilder as BuildParams, { ...this.visitors, ...opt })
24 | }
25 |
26 | private _mergeVisitors(...source: Visitor[]): Visitor {
27 | const dataMap = {}
28 | ;[this.visitors, ...source].filter(Boolean).forEach((item) => {
29 | if (typeof item !== 'object') return
30 | Object.keys(item).forEach((key) => {
31 | if (Array.isArray(dataMap[key])) {
32 | dataMap[key].push(item[key])
33 | } else {
34 | dataMap[key] = [item[key]]
35 | }
36 | })
37 | })
38 | Object.keys(dataMap).forEach((key) => {
39 | const fs = [...dataMap[key]]
40 | dataMap[key] = (...args) => fs.forEach((f) => f.apply(this, args))
41 | })
42 | return dataMap
43 | }
44 |
45 | setFileBuilder(v: BabelFileResult | ProduciblePath | BuildParams): this {
46 | this.fileBuilder = v
47 | return this
48 | }
49 | }
50 |
--------------------------------------------------------------------------------
/src/core/base/controller/WorkerController.ts:
--------------------------------------------------------------------------------
1 | import { ModuleThread, Pool, spawn, Thread, Worker } from 'threads'
2 | import { QueuedTask, TaskRunFunction } from 'threads/dist/master/pool-types'
3 | import { cpus } from 'os'
4 | import { ModuleMethods } from 'threads/dist/types/master'
5 | import { PathController } from './/PathController'
6 | import { BaseError } from '@utils/exceptions'
7 |
8 | export type EachCallback = (
9 | result?: R,
10 | index?: number,
11 | results?: Array, R>>,
12 | ) => void
13 | export class WorkerError extends BaseError {}
14 | export class WorkerController {
15 | results: Array, R>>
16 | private tasks: Array, R>>
17 | private readonly workerPath: string
18 | private readonly poolSize: number
19 | private pool: Pool
20 | constructor(workerPath: string | NodeModule, poolSize?: number) {
21 | this.tasks = []
22 | this.results = []
23 | const _relative = (p: string) => PathController.make(__dirname).relative(p).unixpath
24 | this.workerPath = typeof workerPath === 'string' ? workerPath : _relative(workerPath.id)
25 | this.poolSize = poolSize || cpus().length
26 | }
27 |
28 | async start(callback: EachCallback, terminate?: boolean): Promise
29 | async start(terminate?: boolean): Promise
30 | async start(v?: EachCallback | boolean, _terminate?: boolean): Promise {
31 | let callback,
32 | terminate = _terminate
33 | if (typeof v === 'function') {
34 | callback = v
35 | } else terminate = Boolean(v)
36 | if (!this.tasks.length) return
37 | this.pool = Pool(() => spawn(new Worker(this.workerPath)), this.poolSize)
38 | this.results = this.tasks.map((task) => this.pool.queue(task))
39 | await this.pool.completed()
40 | this.tasks = []
41 | callback && (await this.forEach(callback))
42 | terminate && (await this.terminate())
43 | }
44 | addTask(...runners: TaskRunFunction, R>[]) {
45 | runners.forEach((runner) => this.tasks.push(runner))
46 | }
47 |
48 | async terminate() {
49 | if (!this.pool) WorkerError.throw('The worker pool has not started yet, please start it first')
50 | await this.pool.terminate()
51 | delete this.pool
52 | }
53 |
54 | async forEach(callback: EachCallback): Promise {
55 | await Promise.all(
56 | this.results.map((task, index) => {
57 | return task.then((result) => callback(result, index, this.results))
58 | }),
59 | )
60 | this.results = []
61 | }
62 | }
63 |
--------------------------------------------------------------------------------
/src/core/wxapkg/WxapkgAppConfigParser.ts:
--------------------------------------------------------------------------------
1 | import { Visitor } from '@babel/core'
2 | import { filter } from 'observable-fns'
3 | import { md5 } from '@utils/crypto'
4 | import { info } from '@utils/colors'
5 | import { Saver } from '@utils/classes/Saver'
6 | import { ParserError, BaseParser } from '@base/BaseParser'
7 | import { findBuffer, SaveAble } from '@baseController/SaveController'
8 | import { PathController, ProduciblePath } from '@baseController/PathController'
9 | import { AppConfigServiceSubject, S2Observable, TVSubject } from './types'
10 | import { WxapkgKeyFile } from './WxapkgEnums'
11 | import { PageInfo, createPage } from './utils/createPage'
12 |
13 | interface TabBarItem {
14 | iconPath?: string
15 | iconData?: string
16 | selectedIconPath?: string
17 | selectedIconData?: string
18 | pagePath?: string
19 | }
20 | export class WxapkgAppConfigParser extends BaseParser {
21 | private serviceSource: string
22 | private sources: string
23 | isGame = false
24 |
25 | constructor(saver: Saver) {
26 | super(saver)
27 | }
28 | async parse(observable: S2Observable): Promise {
29 | try {
30 | if (this.isGame) return this.parseGame()
31 | const isDisallowPlugins = true
32 | const dirCtrl = this.saver.saveDirectory
33 | const config = {
34 | ...JSON.parse(this.sources),
35 | pop(key, _default?: T): T {
36 | const result = config[key]
37 | delete config[key]
38 | return result || _default
39 | },
40 | }
41 | // 处理入口
42 | const entryPagePath = PathController.make(config.pop('entryPagePath'))
43 | const pages: string[] = config.pop('pages')
44 | isDisallowPlugins && config.pop('plugins')
45 | const global = config.pop('global')
46 | const epp = entryPagePath.whitout().unixpath
47 | const seenPage = new Set()
48 | const save = (path: ProduciblePath, buffer: SaveAble) => {
49 | const filename = PathController.make(path).unixpath
50 | if (seenPage.has(filename)) return
51 | seenPage.add(filename)
52 | this.saver.add(path, buffer)
53 | }
54 | pages.splice(pages.indexOf(epp), 1)
55 | pages.unshift(epp)
56 | // 处理分包路径
57 | const subPackages: Array<{ [key: string]: unknown }> = config.pop('subPackages')
58 | if (subPackages) {
59 | subPackages.forEach((subPack) => {
60 | const root = subPack.root as string
61 | isDisallowPlugins && delete subPack['plugins']
62 | const _subPages = (subPack.pages as string[]) || pages.filter((p) => p.startsWith(root))
63 | subPack.pages = Array.from(new Set(_subPages)).map((page) => {
64 | let _index: number
65 | while ((_index = pages.indexOf(page)) > -1) pages.splice(_index, 1)
66 | return page.replace(root, '')
67 | })
68 | })
69 | this.logger.info(`AppConfigParser detected ${info(subPackages.length.toString())} subpackages`)
70 | }
71 | // 处理 ext.json
72 | const extAppid = config.pop('extAppid')
73 | const ext = config.pop('ext')
74 | if (extAppid && ext) {
75 | const logPath = dirCtrl.join('ext.json').writeJSONSync({ extEnable: true, extAppid, ext }).logpath
76 | this.logger.info(`Ext save to ${logPath}`)
77 | }
78 | // tabBar
79 | const tabBar = config.pop('tabBar')
80 | const ignoreSuffixes = 'wxml,wxs,wxss,html,json'
81 | if (tabBar && Array.isArray(tabBar.list)) {
82 | const hashMap: Record = Object.create(null)
83 | findBuffer(dirCtrl).forEach(({ key, buffer }) => {
84 | const pCtrl = PathController.unix(key)
85 | if (ignoreSuffixes.includes(pCtrl.suffixWithout)) return
86 | if (!Buffer.isBuffer(buffer)) return
87 | hashMap[md5(buffer)] = pCtrl.crop(dirCtrl.absunixpath).unixpath
88 | })
89 | tabBar.list.forEach((item: TabBarItem) => {
90 | item.pagePath = PathController.make(item.pagePath).whitout().unixpath
91 | if (item.iconData) {
92 | const path = hashMap[md5(item.iconData, true)]
93 | if (path) {
94 | item.iconPath = PathController.make(path).unixpath
95 | delete item.iconData
96 | }
97 | }
98 | if (item.selectedIconData) {
99 | const path = hashMap[md5(item.selectedIconData, true)]
100 | if (path) {
101 | item.selectedIconPath = PathController.make(path).unixpath
102 | delete item.selectedIconData
103 | }
104 | }
105 | })
106 | }
107 | // usingComponents
108 | const page: PageInfo = config.pop('page')
109 | config.pop('renderer')
110 | Object.keys(page).forEach((key) => {
111 | const usingComponents = page[key].window.usingComponents
112 | if (!usingComponents || !Object.keys(usingComponents).length) return
113 | Object.keys(usingComponents).forEach((k) => {
114 | const p = (usingComponents[k] as string).replace(/plugin(-private)?:\/\//, '/__plugin__/')
115 | const file = p.startsWith('/') ? p.slice(1) : PathController.make(key).join('..', p).unixpath
116 | page[file] = page[file] || Object.create(null)
117 | page[file].window = page[file].window || Object.create(null)
118 | page[file].window.component = true
119 | })
120 | })
121 | const result = Object.assign(config, {
122 | debug: true,
123 | tabBar,
124 | subPackages,
125 | ...global,
126 | pages,
127 | })
128 | save(WxapkgKeyFile.APP_JSON, result)
129 | // usingComponents -> json
130 | if (!this.serviceSource) ParserError.throw(`Service source not found!`)
131 | let resolve
132 | const promise = new Promise((_resolve) => (resolve = _resolve))
133 | observable.pipe>(filter((v) => v.AppConfigService)).subscribe({
134 | next: (value) => {
135 | Object.entries(value.AppConfigService).forEach((args) => save(...args))
136 | },
137 | complete() {
138 | Object.keys(page).forEach((key) => {
139 | createPage(key, page[key]).forEach((args) => save(...args))
140 | })
141 | resolve && resolve()
142 | },
143 | })
144 | return promise
145 | } catch (e) {
146 | ParserError.throw('Parse failed! ' + e.message)
147 | }
148 | }
149 | parseGame() {
150 | const config = JSON.parse(this.sources)
151 | const subPackages = config['subPackages']
152 | subPackages && this.logger.info(`AppConfigParser detected ${info(subPackages.length.toString())} subpackages`)
153 | this.saver.add(WxapkgKeyFile.GAME_JSON, this.sources)
154 | }
155 |
156 | setServiceSource(source: string) {
157 | this.serviceSource = source
158 | }
159 | setSources(sources: string) {
160 | this.sources = sources
161 | }
162 | setIsGame(isGame: boolean) {
163 | this.isGame = isGame
164 | }
165 | static visitor(subject: AppConfigServiceSubject): Visitor {
166 | return {
167 | AssignmentExpression(path) {
168 | const left = path.node.left
169 | if (
170 | left &&
171 | left.type === 'MemberExpression' &&
172 | left.object.type === 'Identifier' &&
173 | left.object.name === '__wxAppCode__' &&
174 | left.property.type === 'StringLiteral' &&
175 | left.property.value.endsWith('.json')
176 | ) {
177 | const key = left.property.value
178 | path.traverse({
179 | ObjectExpression(p) {
180 | if (p.parentKey === 'right') {
181 | subject.next({
182 | AppConfigService: {
183 | [key]: p.getSource(),
184 | },
185 | })
186 | }
187 | },
188 | })
189 | }
190 | },
191 | }
192 | }
193 | }
194 |
--------------------------------------------------------------------------------
/src/core/wxapkg/WxapkgController.ts:
--------------------------------------------------------------------------------
1 | import { info } from '@utils/colors'
2 | import { BaseLogger } from '@utils/logger'
3 | import { BaseError } from '@utils/exceptions'
4 | import { flashDisk } from '@baseController/SaveController'
5 | import { getConfig, getInnerConfig } from '@baseController/ConfigController'
6 | import { WorkerController } from '@baseController/WorkerController'
7 | import { PathController, ProduciblePath } from '@baseController/PathController'
8 | import { TraverseVisitorKeys } from './types'
9 | import { WxapkgDecompiler } from './WxapkgDecompiler'
10 | import { WxapkgWxmlParser } from './WxapkgWxmlParser'
11 | import { WxapkgAppConfigParser } from './WxapkgAppConfigParser'
12 | import { createExposed, traverseModule } from './worker'
13 |
14 | export class WxapkgError extends BaseError {}
15 | export type ParsersKey = TraverseVisitorKeys | 'WxmlParserV1'
16 | export type TraverseData = {
17 | source: string
18 | visitors: ParsersKey[]
19 | decompiler?: WxapkgDecompiler
20 | }
21 | export type TraverseExposed = ReturnType
22 | export interface WxapkgControllerOptions {
23 | wxapkgList: ProduciblePath[]
24 | wxAppId?: string
25 | mainSaveDir?: ProduciblePath
26 | }
27 |
28 | export class WxapkgController extends BaseLogger {
29 | private readonly decompilers: WxapkgDecompiler[]
30 | private readonly mainSaveDir: PathController
31 | // 解析结果的Promise
32 | private readonly parsersPromise: Promise[]
33 | constructor(wxapkgList: ProduciblePath[])
34 | constructor(...wxapkgList: ProduciblePath[])
35 | constructor(options: WxapkgControllerOptions)
36 | constructor(v: WxapkgControllerOptions | ProduciblePath[] | ProduciblePath) {
37 | super()
38 | const options: WxapkgControllerOptions = Object.create(null)
39 | if (Array.isArray(v)) options.wxapkgList = v
40 | else Object.assign(options, v)
41 | const { wxapkgList, mainSaveDir, wxAppId } = options
42 | if (mainSaveDir) this.mainSaveDir = PathController.make(mainSaveDir)
43 | if (!wxapkgList.length) WxapkgError.throw(`No wxapkg available`)
44 | // 初始化反编译器
45 | this.decompilers = wxapkgList.map((p) => {
46 | const decompiler = new WxapkgDecompiler(p)
47 | wxAppId && decompiler.setExtractorWxAppId(wxAppId)
48 | return decompiler
49 | })
50 | this.parsersPromise = []
51 | }
52 |
53 | extractorSave() {
54 | // 保存之前清理一下之前的结果
55 | this.clearOldResult()
56 | // 保存提取之后的结果
57 | this.decompilers.forEach((d) => d.extractorSave())
58 | }
59 | extract(isNoParse: boolean) {
60 | // 提取文件
61 | this.decompilers.forEach((d) => d.extract())
62 | // 不解析直接保存结果
63 | if (isNoParse) return this.extractorSave()
64 | // 检测主包
65 | let mainDecompiler: WxapkgDecompiler
66 | this.decompilers.forEach((d) => {
67 | if (d.isMainPackage) {
68 | if (mainDecompiler) WxapkgError.throw(`There can only be one main package`)
69 | mainDecompiler = d
70 | }
71 | })
72 | // 不存在主包直接保存结果
73 | if (!mainDecompiler) return this.extractorSave()
74 | // 存在主包把其他子包的保存路径指向主包
75 | if (this.mainSaveDir) {
76 | const output = this.mainSaveDir
77 | mainDecompiler.saveDir = output
78 | if (output.isDirectory && output.deepListDir(1).length) {
79 | if (!getConfig('WxClearOutput'))
80 | WxapkgError.throw(`This output path is not empty, please use ${info('--clear-output')} force cleanup`)
81 | mainDecompiler.saveDir.rmrfSync()
82 | }
83 | }
84 | this.decompilers.forEach((d) => {
85 | if (d === mainDecompiler) return
86 | // 小程序插件暂时不能放到主包内
87 | if (d.isAppPlugin) return
88 | d.saveDir = mainDecompiler.saveDir
89 | })
90 | this.extractorSave()
91 | }
92 |
93 | clearOldResult() {
94 | if (!getConfig('WXClearSave')) return
95 | Array.from(new Set(this.decompilers.map((d) => d.saveDir))).forEach((ctrl) => {
96 | ctrl.rmrfSync()
97 | this.logger.debug(`Cleaned old result ${ctrl.logpath}`)
98 | })
99 | }
100 |
101 | async invokeTraverseWorker(): Promise {
102 | const forEachVisitors = (decompiler: WxapkgDecompiler, visitors: ParsersKey[], exposed: TraverseExposed) => {
103 | const seen = new Set()
104 | visitors.forEach((key) => {
105 | if (key === 'WxmlParserV1') {
106 | const wxml = decompiler.parsers.WxmlParserV1 as WxapkgWxmlParser
107 | return wxml.parseV1()
108 | }
109 | if (key === 'AppConfigService') {
110 | const appConfig = decompiler.parsers.AppConfigService as WxapkgAppConfigParser
111 | if (appConfig.isGame) return appConfig.parseGame()
112 | }
113 | const parserLike = decompiler.parsers[key]
114 | exposed.setVisitor(key)
115 | !seen.has(parserLike) && this.parsersPromise.push(parserLike.parse(exposed.observable()))
116 | seen.add(parserLike)
117 | })
118 | }
119 | const results = await Promise.all(this.decompilers.map((d) => d.makeParserTraverse()))
120 | const temp: TraverseData[] = []
121 | results.forEach((items) => {
122 | if (!items) return
123 | temp.push(...items)
124 | })
125 | const tasks = temp.filter(Boolean)
126 | if (!tasks.length) {
127 | this.logger.warn('No task to traverse')
128 | return
129 | }
130 | if (tasks.length === 1) {
131 | const { decompiler, visitors, source } = tasks[0]
132 | const exposed = createExposed()
133 | forEachVisitors(decompiler, visitors, exposed)
134 | await exposed.startTraverse(source)
135 | } else {
136 | const wCtrl = new WorkerController(traverseModule)
137 | tasks.forEach((item) => {
138 | const { decompiler, visitors, source } = item
139 | wCtrl.addTask((exposed) => {
140 | exposed.initWorker(getInnerConfig())
141 | forEachVisitors(decompiler, visitors, exposed)
142 | return exposed.startTraverse(source)
143 | })
144 | })
145 | await wCtrl.start(true)
146 | }
147 | }
148 |
149 | async saveFiles() {
150 | await Promise.all(this.parsersPromise)
151 | this.decompilers.forEach((d) => d.save())
152 | await flashDisk()
153 | }
154 |
155 | async exploit() {
156 | const isParse = getConfig('WXParse')
157 | this.extract(!isParse)
158 | isParse && (await this.invokeTraverseWorker())
159 | await this.saveFiles()
160 | }
161 | }
162 |
--------------------------------------------------------------------------------
/src/core/wxapkg/WxapkgDecompiler.ts:
--------------------------------------------------------------------------------
1 | import { Observable } from 'observable-fns'
2 | import { BaseLogger } from '@utils/logger'
3 | import { matchScripts } from '@utils/matchScripts'
4 | import { info } from '@utils/colors'
5 | import { Saver } from '@utils/classes/Saver'
6 | import { PathController, ProduciblePath } from '@baseController/PathController'
7 | import { getConfig } from '@baseController/ConfigController'
8 | import { getSaveController, saveAble2String } from '@baseController/SaveController'
9 | import { getWccVersion } from './utils/getWccVersion'
10 | import { WxapkgExtractor } from './WxapkgExtractor'
11 | import { ParserLike, TVSubjectType } from './types'
12 | import { WxapkgKeyFile, WxapkgType } from './WxapkgEnums'
13 | import { ParsersKey, TraverseData } from './WxapkgController'
14 | import { WxapkgScriptParser } from './WxapkgScriptParser'
15 | import { WxapkgWxssParser } from './WxapkgWxssParser'
16 | import { WxapkgAppConfigParser } from './WxapkgAppConfigParser'
17 | import { WxapkgWxmlParser } from './WxapkgWxmlParser'
18 |
19 | interface SetAppOptions {
20 | viewSource?: string
21 | appConfigSource?: string
22 | serviceSource?: string
23 | setAppConfig?: boolean
24 | }
25 |
26 | export class WxapkgDecompiler extends BaseLogger {
27 | // 包路径
28 | private readonly pathCtrl: PathController
29 | // 解包器
30 | private readonly extractor: WxapkgExtractor
31 | // 解析器
32 | readonly parsers: Record, Promise>>
33 | // 解析后使用的保存器
34 | private readonly saver: Saver
35 | // 遍历列表
36 | private readonly traverseList: TraverseData[]
37 | // 是否使用 V1 版本解析器
38 | get isParserV1() {
39 | const type = this.extractor.type
40 | // prettier-ignore
41 | return (
42 | type === WxapkgType.APP_V1 ||
43 | type === WxapkgType.APP_V2 ||
44 | type === WxapkgType.APP_SUBPACKAGE_V1
45 | )
46 | }
47 | // 是否使用 V3 版本解析器
48 | get isParserV3() {
49 | const type = this.extractor.type
50 | return (
51 | type === WxapkgType.APP_V3 ||
52 | type === WxapkgType.APP_V4 ||
53 | type === WxapkgType.APP_SUBPACKAGE_V2 ||
54 | type === WxapkgType.APP_PLUGIN_V1
55 | )
56 | }
57 | // 是否是主包
58 | get isMainPackage() {
59 | return this.extractor.isMainPackage
60 | }
61 | // 是否是子包
62 | get isSubpackage() {
63 | return this.extractor.isSubpackage
64 | }
65 | get isAppPlugin() {
66 | return this.extractor.isAppPlugin
67 | }
68 | // 当前包路径
69 | get path(): PathController {
70 | return this.pathCtrl
71 | }
72 | // 源码目录
73 | get sourceDir(): PathController {
74 | return this.extractor.sourceDir
75 | }
76 | // 保存的目录
77 | get saveDir(): PathController {
78 | return this.saver.saveDirectory
79 | }
80 | set saveDir(dir: ProduciblePath) {
81 | dir = dir || this.path.whitout()
82 | this.extractor.setSaver(dir)
83 | this.saver.saveDirectory = dir
84 | }
85 |
86 | constructor(path: ProduciblePath) {
87 | super()
88 | this.pathCtrl = PathController.make(path)
89 | // 默认保存路径为 path.whitout()
90 | this.extractor = new WxapkgExtractor({ path: this.path })
91 | this.saver = new Saver(this.extractor.saveDirectory)
92 | this.parsers = Object.create(null)
93 | this.traverseList = []
94 | }
95 | setExtractorWxAppId(appid: string) {
96 | this.extractor.setWxAppId(appid)
97 | }
98 | extract() {
99 | this.extractor.extract()
100 | }
101 | extractorSave(): void {
102 | this.extractor.save()
103 | }
104 | async makeParserTraverse(): Promise {
105 | if (this.extractor.isFramework) return []
106 | this.initParsers()
107 | await this.initTraverseList()
108 | const list = this.traverseList.filter((item) => item.source)
109 | if (!list.length) this.logger.warn(`File ${this.path.logpath} no data to parse`)
110 | return list.map((item) => Object.assign({ decompiler: this }, item))
111 | }
112 | initParsers() {
113 | if (!this.extractor.extracted) return
114 | this.parsers.ScriptParser = new WxapkgScriptParser(this.saver)
115 | switch (this.extractor.type) {
116 | case WxapkgType.APP_V1:
117 | case WxapkgType.APP_V2:
118 | case WxapkgType.APP_V3:
119 | case WxapkgType.APP_V4:
120 | case WxapkgType.APP_SUBPACKAGE_V1:
121 | case WxapkgType.APP_SUBPACKAGE_V2:
122 | case WxapkgType.APP_PLUGIN_V1:
123 | {
124 | const wxss = new WxapkgWxssParser(this.saver)
125 | this.parsers.WxssParser = wxss
126 | this.parsers.WxssParserCommon = wxss
127 | this.parsers.WxssParserCommon2 = wxss
128 | if (!this.isSubpackage) {
129 | this.parsers.AppConfigService = new WxapkgAppConfigParser(this.saver)
130 | }
131 | // 虽然实例一样,但是名字不一样,使用的解析器也不一样
132 | if (this.isParserV1) {
133 | this.parsers.WxmlParserV1 = new WxapkgWxmlParser(this.saver)
134 | } else if (this.isParserV3) {
135 | this.parsers.WxmlParserV3 = new WxapkgWxmlParser(this.saver)
136 | }
137 | }
138 | break
139 | case WxapkgType.GAME:
140 | this.parsers.AppConfigService = new WxapkgAppConfigParser(this.saver)
141 | break
142 | case WxapkgType.GAME_SUBPACKAGE:
143 | case WxapkgType.GAME_PLUGIN:
144 | break
145 | }
146 | }
147 | async initTraverseList() {
148 | if (!this.extractor.extracted) return
149 | // 源码路径
150 | const sourceDir = this.sourceDir
151 | const getSource = (keyFile: WxapkgKeyFile) => {
152 | const ctrl = sourceDir.join(keyFile)
153 | return saveAble2String(getSaveController().get(ctrl.abspath))
154 | }
155 | const setApp = async (options?: SetAppOptions) => {
156 | const {
157 | serviceSource = getSource(WxapkgKeyFile.APP_SERVICE),
158 | viewSource = getSource(WxapkgKeyFile.APP_WXSS),
159 | appConfigSource,
160 | setAppConfig = true,
161 | } = options || {}
162 | const wccVersion = getWccVersion(viewSource)
163 | if (wccVersion) {
164 | this.logger.info(`The package ${this.pathCtrl.logpath} wcc version is: [${info(wccVersion)}]`)
165 | }
166 | if (setAppConfig) {
167 | const appConfigSource$1 = appConfigSource || getSource(WxapkgKeyFile.APP_CONFIG)
168 | const ACParser = this.parsers.AppConfigService as WxapkgAppConfigParser
169 | ACParser.setSources(appConfigSource$1)
170 | ACParser.setServiceSource(serviceSource)
171 | this.traverseList.push({
172 | source: serviceSource,
173 | visitors: ['AppConfigService', 'ScriptParser'],
174 | })
175 | } else {
176 | this.traverseList.push({
177 | source: serviceSource,
178 | visitors: ['ScriptParser'],
179 | })
180 | }
181 | const styleResource = [viewSource, WxapkgWxssParser.getHTMLStyleSource(sourceDir)].join(';\n')
182 | this.traverseList.push({
183 | source: styleResource,
184 | visitors: ['WxssParser', 'WxssParserCommon', 'WxssParserCommon2'],
185 | })
186 | if (this.isParserV1) {
187 | this.traverseList.push({
188 | source: viewSource,
189 | visitors: ['WxmlParserV1'],
190 | })
191 | const wxml = this.parsers.WxmlParserV1 as WxapkgWxmlParser
192 | wxml.setSource(viewSource)
193 | } else if (this.isParserV3) {
194 | this.traverseList.push({
195 | source: viewSource,
196 | visitors: ['WxmlParserV3'],
197 | })
198 | }
199 | }
200 | const setOtherScript = async (name: WxapkgKeyFile) => {
201 | this.traverseList.push({
202 | source: getSource(name),
203 | visitors: ['ScriptParser'],
204 | })
205 | }
206 |
207 | switch (this.extractor.type) {
208 | case WxapkgType.APP_V1:
209 | case WxapkgType.APP_V4:
210 | await setApp({ viewSource: matchScripts(getSource(WxapkgKeyFile.PAGE_FRAME_HTML)) })
211 | break
212 | case WxapkgType.APP_V2:
213 | case WxapkgType.APP_V3:
214 | await setApp()
215 | break
216 | case WxapkgType.APP_SUBPACKAGE_V1:
217 | case WxapkgType.APP_SUBPACKAGE_V2:
218 | await setApp({
219 | viewSource: getSource(WxapkgKeyFile.PAGE_FRAME),
220 | setAppConfig: false,
221 | })
222 | break
223 | case WxapkgType.APP_PLUGIN_V1:
224 | await setApp({
225 | viewSource: getSource(WxapkgKeyFile.PAGEFRAME),
226 | serviceSource: getSource(WxapkgKeyFile.APPSERVICE),
227 | setAppConfig: false,
228 | })
229 | break
230 | case WxapkgType.GAME:
231 | {
232 | const appConfigSource = getSource(WxapkgKeyFile.APP_CONFIG)
233 | const gameSource = getSource(WxapkgKeyFile.GAME)
234 | const subContext = getSource(WxapkgKeyFile.SUBCONTEXT)
235 | const source = [gameSource, subContext].filter(Boolean).join(';\n')
236 | const ACParser = this.parsers.AppConfigService as WxapkgAppConfigParser
237 | ACParser.setSources(appConfigSource)
238 | ACParser.setIsGame(true)
239 | this.traverseList.push({
240 | source: source,
241 | visitors: ['AppConfigService'],
242 | })
243 | await setOtherScript(WxapkgKeyFile.GAME)
244 | }
245 | break
246 | case WxapkgType.GAME_SUBPACKAGE:
247 | await setOtherScript(WxapkgKeyFile.GAME)
248 | break
249 | case WxapkgType.GAME_PLUGIN:
250 | await setOtherScript(WxapkgKeyFile.PLUGIN)
251 | break
252 | }
253 | }
254 | save() {
255 | if (this.extractor.isFramework) return
256 | this.saver.merge()
257 | getConfig('WXClearDecompile') && this.cleanup()
258 | }
259 | cleanup() {
260 | const dirCtrl = this.sourceDir
261 | this.logger.debug(`Start cleaning ${dirCtrl.logpath}`)
262 | const unlinks = [
263 | '.appservice.js',
264 | 'appservice.js',
265 | 'app-config.json',
266 | 'app-service.js',
267 | 'app-wxss.js',
268 | 'appservice.app.js',
269 | 'common.app.js',
270 | 'page-frame.js',
271 | 'page-frame.html',
272 | 'pageframe.js',
273 | 'webview.app.js',
274 | 'subContext.js',
275 | 'plugin.js',
276 | ]
277 | const inst = getSaveController()
278 | unlinks.forEach((p) => inst.delete(dirCtrl.join(p).abspath))
279 | }
280 | }
281 |
--------------------------------------------------------------------------------
/src/core/wxapkg/WxapkgDecryptor.ts:
--------------------------------------------------------------------------------
1 | import { BaseDecryptor, DecryptorError } from '@base/BaseDecryptor'
2 | import { checkWxapkg } from './utils/checkWxapkg'
3 | import { PackageSuffix } from '@enum/PackageSuffix'
4 | import { isProduciblePath, PathController, ProduciblePath } from '@baseController/PathController'
5 | import { decryptBuffer } from '@utils/crypto'
6 | import { info } from '@utils/colors'
7 |
8 | export interface WxapkgDecryptorOptions {
9 | path: ProduciblePath
10 | wxAppId?: string
11 | target?: ProduciblePath
12 | salt?: string
13 | iv?: string
14 | }
15 |
16 | export class WxapkgDecryptor extends BaseDecryptor {
17 | wxAppId: string
18 | readonly target: PathController
19 | readonly salt: string
20 | readonly iv: string
21 | private decryptedBuffer: Buffer
22 |
23 | constructor(options: WxapkgDecryptorOptions)
24 | constructor(path: ProduciblePath, wxAppId?: string, target?: ProduciblePath)
25 | constructor(path: WxapkgDecryptorOptions | ProduciblePath, wxAppId?: string, target?: ProduciblePath) {
26 | let options
27 | if (arguments.length === 1) {
28 | if (isProduciblePath(path)) {
29 | options = { path } as WxapkgDecryptorOptions
30 | } else {
31 | options = path as WxapkgDecryptorOptions
32 | }
33 | } else {
34 | options = {
35 | path,
36 | wxAppId,
37 | target: arguments.length === 3 ? target : void 0,
38 | } as WxapkgDecryptorOptions
39 | }
40 | super(options.path)
41 | this.suffix = PackageSuffix.WXAPKG
42 | this.wxAppId = options.wxAppId
43 | this.salt = options.salt || 'saltiest'
44 | this.iv = options.iv || 'the\x20iv:\x2016\x20bytes'
45 | this.target = options.target ? PathController.make(options.target) : void 0
46 | this._calcWxAppId()
47 | }
48 |
49 | get result(): Buffer {
50 | return this.decryptedBuffer
51 | }
52 |
53 | _calcWxAppId(): void {
54 | if (this.wxAppId) return
55 | const _result = this.pathCtrl.abspath.match(/wx[a-z\d]{16}/g)
56 | if (!_result) throw new DecryptorError('wxAppId must be required!')
57 | this.wxAppId = _result[0]
58 | this.logger.info(`From ${this.pathCtrl.logpath} detected wxAppId: ${info(this.wxAppId)}`)
59 | }
60 |
61 | checkWxAppId() {
62 | if (!this.wxAppId || !/^wx[a-z\d]{16}$/.test(this.wxAppId)) {
63 | throw new DecryptorError(`wxAppId ${this.wxAppId || ''} must be a valid wxAppId`)
64 | }
65 | }
66 |
67 | decrypt(buffer?: Buffer): void {
68 | super.decrypt()
69 | buffer = buffer || this.pathCtrl.readSync()
70 | this._decrypt(buffer)
71 | }
72 |
73 | private _decrypt(buffer: Buffer) {
74 | try {
75 | this.checkWxAppId()
76 | const wxAppId = this.wxAppId
77 | const header = buffer.subarray(6, 0x406)
78 | const contents = buffer.subarray(0x406)
79 | const oriHeader = decryptBuffer(header, wxAppId, this.salt, this.iv)
80 | const xorKey = wxAppId.length < 2 ? 0x66 : wxAppId.charCodeAt(wxAppId.length - 2)
81 | const oriContents = Buffer.from(contents.map((b) => b ^ xorKey))
82 | this.decryptedBuffer = Buffer.concat([oriHeader.subarray(0, 0x3ff), oriContents])
83 | if (!checkWxapkg(this.decryptedBuffer)) DecryptorError.throw('Please check if wxAppId is correct')
84 | this.logger.debug('Decryption successful!')
85 | } catch (e) {
86 | throw new DecryptorError('Decryption failed! ' + e.message)
87 | }
88 | }
89 |
90 | async save(target?: ProduciblePath) {
91 | this.saver.add(target || this.target, this.result)
92 | }
93 |
94 | static decryptResult(options: WxapkgDecryptorOptions): Buffer
95 | static decryptResult(path: ProduciblePath, wxAppId?: string, target?: ProduciblePath): Buffer
96 | static decryptResult(o: WxapkgDecryptorOptions | ProduciblePath, wxAppId?: string): Buffer {
97 | const inst = isProduciblePath(o) ? new WxapkgDecryptor(o, wxAppId) : new WxapkgDecryptor(o)
98 | inst.decrypt()
99 | return inst.result
100 | }
101 | }
102 |
--------------------------------------------------------------------------------
/src/core/wxapkg/WxapkgEnums.ts:
--------------------------------------------------------------------------------
1 | // 微信包关键文件名
2 | export enum WxapkgKeyFile {
3 | APP_CONFIG = 'app-config.json',
4 | APP_SERVICE = 'app-service.js',
5 | PAGE_FRAME_HTML = 'page-frame.html',
6 | APP_WXSS = 'app-wxss.js',
7 | COMMON_APP = 'common.app.js',
8 | APP_JSON = 'app.json',
9 | WORKERS = 'workers.js',
10 | PAGE_FRAME = 'page-frame.js',
11 | APPSERVICE = 'appservice.js',
12 | PAGEFRAME = 'pageframe.js',
13 |
14 | GAME = 'game.js',
15 | GAME_JSON = 'game.json',
16 | SUBCONTEXT = 'subContext.js',
17 |
18 | PLUGIN = 'plugin.js',
19 | PLUGIN_JSON = 'plugin.json',
20 |
21 | PROJECT_PRIVATE_CONFIG = 'project.private.config.json',
22 | }
23 |
24 | export enum WxapkgType {
25 | /**
26 | * 包含文件 {@link WxapkgKeyFile.PAGE_FRAME_HTML}
27 | * 相关数据就保存在此文件中
28 | * */
29 | APP_V1 = 'APP_V1',
30 | APP_V2 = 'APP_V2',
31 | APP_V3 = 'APP_V3',
32 | APP_V4 = 'APP_V4',
33 | /** 对标 {@link APP_V1},{@link APP_V2}*/
34 | APP_SUBPACKAGE_V1 = 'APP_SUBPACKAGE_V1',
35 | /** 对标 {@link APP_V3}*/
36 | APP_SUBPACKAGE_V2 = 'APP_SUBPACKAGE_V2',
37 | // 小程序插件
38 | APP_PLUGIN_V1 = 'APP_PLUGIN_V1',
39 | // 微信小游戏主包
40 | GAME = 'GAME',
41 | // 微信小游戏分包
42 | GAME_SUBPACKAGE = 'GAME_SUBPACKAGE',
43 | // 小游戏插件
44 | GAME_PLUGIN = 'GAME_PLUGIN',
45 | // runtime framework
46 | FRAMEWORK = 'FRAMEWORK',
47 | }
48 |
--------------------------------------------------------------------------------
/src/core/wxapkg/WxapkgExtractor.ts:
--------------------------------------------------------------------------------
1 | import { BaseExtractor, ExtractorError } from '@base/BaseExtractor'
2 | import { WxapkgDecryptor } from './WxapkgDecryptor'
3 | import { checkMacEncryption, checkWxapkg, checkWxapkgType } from './utils/checkWxapkg'
4 | import { WxapkgKeyFile, WxapkgType } from './WxapkgEnums'
5 | import { PackageSuffix } from '@enum/PackageSuffix'
6 | import { isProduciblePath, PathController, ProduciblePath } from '@baseController/PathController'
7 | import { Saver } from '@utils/classes/Saver'
8 | import { info, link } from '@utils/colors'
9 |
10 | export interface WxapkgFileHeader {
11 | infoLength: number
12 | dataLength: number
13 | }
14 |
15 | export interface WxapkgFileInfo {
16 | name: string
17 | start: number
18 | end: number
19 | }
20 |
21 | export interface WxapkgExtractorOptions {
22 | path: ProduciblePath
23 | wxAppId?: string
24 | saveDir?: ProduciblePath
25 | }
26 |
27 | export class WxapkgExtractor extends BaseExtractor {
28 | private wxAppId: string
29 | private saver: Saver
30 | private wxapkgType: WxapkgType
31 | private sourcePath: string
32 | private isExtracted: boolean
33 |
34 | constructor(path: ProduciblePath)
35 | constructor(options: WxapkgExtractorOptions)
36 | constructor(v: WxapkgExtractorOptions | ProduciblePath) {
37 | if (isProduciblePath(v)) {
38 | super(v)
39 | } else {
40 | const { path, saveDir, wxAppId } = v
41 | super(path)
42 | this.setSaver(saveDir)
43 | this.wxAppId = wxAppId
44 | }
45 | this.isExtracted = false
46 | this.suffix = PackageSuffix.WXAPKG
47 | }
48 |
49 | // 是否提取完成
50 | get extracted() {
51 | if (!this.isExtracted) ExtractorError.throw(`Need to extract first`)
52 | return true
53 | }
54 |
55 | // 包类型
56 | get type() {
57 | if (!this.wxapkgType) ExtractorError.throw(`WxapkgType not available, No extract or unsupported packages`)
58 | return this.wxapkgType
59 | }
60 |
61 | // 是否主包
62 | get isMainPackage() {
63 | return (
64 | this.type === WxapkgType.APP_V1 ||
65 | this.type === WxapkgType.APP_V2 ||
66 | this.type === WxapkgType.APP_V3 ||
67 | this.type === WxapkgType.APP_V4 ||
68 | this.type === WxapkgType.GAME
69 | )
70 | }
71 |
72 | // 是否是分包
73 | get isSubpackage() {
74 | return (
75 | this.type === WxapkgType.APP_SUBPACKAGE_V1 ||
76 | this.type === WxapkgType.APP_SUBPACKAGE_V2 ||
77 | this.type === WxapkgType.GAME_SUBPACKAGE
78 | )
79 | }
80 |
81 | // 是否是小程序插件
82 | get isAppPlugin() {
83 | return this.type === WxapkgType.APP_PLUGIN_V1
84 | }
85 |
86 | // 是否是游戏插件
87 | get isGamePlugin() {
88 | return this.type === WxapkgType.GAME_PLUGIN
89 | }
90 |
91 | // 是否是插件
92 | get isPlugin() {
93 | return this.isAppPlugin || this.isGamePlugin
94 | }
95 |
96 | // 是否是运行框架
97 | get isFramework() {
98 | return this.type === WxapkgType.FRAMEWORK
99 | }
100 |
101 | // 设置保存的路径
102 | setSaver(saveDir: ProduciblePath | undefined) {
103 | saveDir = saveDir || this.pathCtrl.whitout()
104 | if (!this.saver) {
105 | this.saver = new Saver(saveDir)
106 | return
107 | }
108 | this.saver.saveDirectory = saveDir
109 | }
110 |
111 | // 设置WxAppId
112 | setWxAppId(appid: string) {
113 | this.wxAppId = appid
114 | }
115 |
116 | save() {
117 | this.saver.merge()
118 | }
119 |
120 | get saveDirectory() {
121 | return this.saver.saveDirectory
122 | }
123 |
124 | get sourceDir(): PathController {
125 | return this.saveDirectory.join(this.sourcePath)
126 | }
127 |
128 | // 获取文件头信息
129 | getFileHeader(buf: Buffer): WxapkgFileHeader {
130 | if (!checkWxapkg(buf)) ExtractorError.throw(`File ${this.pathCtrl.logpath} is an invalid package!`)
131 | const unknownInfo = buf.readUInt32BE(1)
132 | unknownInfo && this.logger.warn('UnknownInfo: ', unknownInfo)
133 | return {
134 | infoLength: buf.readUInt32BE(5),
135 | dataLength: buf.readUInt32BE(9),
136 | }
137 | }
138 |
139 | // 获取包内的文件信息
140 | getFileByRaw(buf: Buffer): WxapkgFileInfo[] {
141 | const fileCount = buf.readUInt32BE(0)
142 | this.logger.debug(`Read file count ${fileCount}`)
143 | let _offset = 4
144 | return Array(fileCount)
145 | .fill(0)
146 | .map(() => {
147 | const nameOffset = buf.readUInt32BE(_offset)
148 | _offset += 4
149 | const name = buf.toString('utf8', _offset, _offset + nameOffset)
150 | _offset += nameOffset
151 | const start = buf.readUInt32BE(_offset)
152 | _offset += 4
153 | const end = start + buf.readUInt32BE(_offset)
154 | _offset += 4
155 | return {
156 | name,
157 | start,
158 | end,
159 | }
160 | })
161 | }
162 |
163 | extractInner(buf: Buffer): void {
164 | const isEncrypted = buf.subarray(0, 6).toString('hex') === '56314d4d5758'
165 | if (isEncrypted) {
166 | this.logger.debug(`File ${this.pathCtrl.logpath} encrypted, Starting decrypt`)
167 | const buffer = WxapkgDecryptor.decryptResult(this.pathCtrl, this.wxAppId)
168 | return this.extractInner(buffer)
169 | }
170 | this.logger.debug(`Starting extract ${this.pathCtrl.logpath}`)
171 | const { dataLength, infoLength } = this.getFileHeader(buf.subarray(0, 14))
172 | this.logger.debug(`Header info length ${infoLength}`)
173 | this.logger.debug(`Header data length ${dataLength}`)
174 | const files = this.getFileByRaw(buf.subarray(14, infoLength + 14))
175 | this.logger.debug(`Starting save extracted files`)
176 | let isExistProjectPrivateConfig = false
177 | const pathList = files.map((file) => {
178 | const { name, start, end } = file
179 | const path = name.startsWith('/') ? name.slice(1) : name
180 | if (path === WxapkgKeyFile.PROJECT_PRIVATE_CONFIG) isExistProjectPrivateConfig = true
181 | this.saver.add(path, buf.subarray(start, end))
182 | const basename = PathController.make(path).basename
183 | return { path, basename }
184 | })
185 | // 如果没有配置文件则添加默认配置
186 | if (!isExistProjectPrivateConfig) {
187 | this.saver.add(WxapkgKeyFile.PROJECT_PRIVATE_CONFIG, {
188 | setting: {
189 | es6: false,
190 | urlCheck: false,
191 | },
192 | })
193 | }
194 | const type = checkWxapkgType(pathList.map(({ basename }) => basename))
195 | if (!type) this.logger.warn(`Parsed packages are not supported`)
196 | this.logger.info(`The package ${this.pathCtrl.logpath} type is: [${info(type)}]`)
197 | this.wxapkgType = type
198 | if (type === WxapkgType.FRAMEWORK) {
199 | this.logger.warn(`Running the framework does not require unpacking`)
200 | this.isExtracted = true
201 | return
202 | }
203 | const isPlugin = this.isPlugin
204 | let sp = null
205 | pathList.forEach((item) => {
206 | const { basename } = item
207 | const isAvailable =
208 | basename === WxapkgKeyFile.APP_SERVICE ||
209 | basename === WxapkgKeyFile.APPSERVICE ||
210 | basename === WxapkgKeyFile.GAME ||
211 | (isPlugin && basename === WxapkgKeyFile.PLUGIN_JSON)
212 | if (!isAvailable) return
213 | if (!sp) return (sp = item)
214 | const currentLen = item.path.split('/').length
215 | const oldLen = sp.path.split('/').length
216 | sp = currentLen < oldLen ? item : sp
217 | })
218 | if (!sp) ExtractorError.throw(`File ${this.pathCtrl.logpath} source directory not found`)
219 | this.sourcePath = PathController.make(sp.path || '.').dirname
220 | this.isExtracted = true
221 | }
222 |
223 | extract(save?: boolean) {
224 | super.extract()
225 | const buf = this.pathCtrl.readSync()
226 | if (!checkMacEncryption(buf)) {
227 | const target = link(info('https://github.com/TinyNiko/mac_wxapkg_decrypt'))
228 | ExtractorError.throw(
229 | `Package ${this.pathCtrl.logpath} is an encrypted package for Mac
230 | please use ${target} to decrypt it before using it`,
231 | )
232 | }
233 | this.extractInner(buf)
234 | save && this.save()
235 | }
236 | }
237 |
--------------------------------------------------------------------------------
/src/core/wxapkg/WxapkgScriptParser.ts:
--------------------------------------------------------------------------------
1 | import { filter } from 'observable-fns'
2 | import { BaseParser } from '@base/BaseParser'
3 | import { Visitor } from '@babel/core'
4 | import { S2Observable, ScriptParserSubject, TVSubject } from './types'
5 | import { Saver } from '@utils/classes/Saver'
6 | import { PathController } from '@baseController/PathController'
7 |
8 | export class WxapkgScriptParser extends BaseParser {
9 | constructor(saver: Saver) {
10 | super(saver)
11 | }
12 | async parse(observable: S2Observable): Promise {
13 | let resolve
14 | const promise = new Promise((_resolve) => (resolve = _resolve))
15 | observable.pipe>(filter((v) => v.ScriptParser)).subscribe({
16 | next: (value) => {
17 | Object.entries(value.ScriptParser).forEach(([path, buffer]) => {
18 | // 小游戏插件以目录作为名字的define
19 | if (path.startsWith('__plugin__')) {
20 | if (!PathController.make(path).suffixWithout) {
21 | path = '__plugin__/index.js'
22 | }
23 | }
24 | this.saver.add(path, buffer)
25 | })
26 | },
27 | complete() {
28 | resolve && resolve()
29 | },
30 | })
31 | return promise
32 | }
33 |
34 | static visitor(subject: ScriptParserSubject): Visitor {
35 | return {
36 | CallExpression(path) {
37 | const callee = path.node.callee
38 | if (callee.type === 'Identifier' && callee.name === 'define') {
39 | const args = path.get('arguments')
40 | const [filenamePathNode, sourcePathNode] = args
41 | if (!filenamePathNode.isStringLiteral()) return
42 | if (!sourcePathNode.isFunctionExpression()) return
43 | const filename = filenamePathNode.node.value
44 | const block = sourcePathNode.get('body')
45 | let _blockSource = block.getSource()
46 | _blockSource = _blockSource.startsWith('\x7b') ? _blockSource.slice(1) : _blockSource
47 | _blockSource = _blockSource.endsWith('\x7d') ? _blockSource.slice(0, -1) : _blockSource
48 | const source = _blockSource
49 | subject.next({
50 | ScriptParser: {
51 | [filename]: source,
52 | },
53 | })
54 | }
55 | },
56 | }
57 | }
58 | }
59 |
--------------------------------------------------------------------------------
/src/core/wxapkg/WxapkgWxmlParser.ts:
--------------------------------------------------------------------------------
1 | import { BaseParser } from '@base/BaseParser'
2 | import { Saver } from '@utils/classes/Saver'
3 | import { parseWxml, parseZArrayFromCode } from './wxml-parser'
4 | import { S2Observable, TraverseResult, TVSubject, WxmlParserV3Subject, ZArray } from './types'
5 | import { Visitor } from '@babel/traverse'
6 | import { filter } from 'observable-fns'
7 | import { deepCopy } from '@utils/deepCopy'
8 | import { SaveAble } from '@baseController/SaveController'
9 |
10 | const zArrayFunctionNameRE = /gz\$gwx\d*_[A-Za-z_0-9]+/
11 | const scopeNameRE = /\$gwx\d*$|\$gwx\d*_[A-Za-z_0-9]+/
12 | function getFirst(p: T | T[]) {
13 | return (Array.isArray(p) ? p : [p])[0]
14 | }
15 | function getZArrayKey(functionName: string): string {
16 | const match = functionName.match(/_\d+$/)
17 | return match ? match[0] : ''
18 | }
19 | function makeVisitor(result: TraverseResult): Visitor {
20 | const data: ZArray = { mul: Object.create(null) }
21 | const visitor: Visitor = {
22 | FunctionExpression(path) {
23 | const parent = path.getFunctionParent()
24 | if (!parent) return
25 | if (!parent.isFunctionDeclaration()) return
26 | const fn = parent.get('id')
27 | if (!fn) return
28 | const functionName = fn.getSource()
29 | if (!zArrayFunctionNameRE.test(functionName)) return
30 | const list = path.get('body.body')
31 | const blocks = Array.isArray(list) ? list : [list]
32 | const key = getZArrayKey(functionName)
33 | if (!key) return
34 | data.mul[key] = deepCopy(parseZArrayFromCode(blocks.map((p) => p.getSource()).join('\n'))) as unknown[]
35 | },
36 | VariableDeclarator(path) {
37 | const id = path.get('id')
38 | const init = path.get('init')
39 | const defName = id.getSource()
40 | if (defName === 'nnm' && init.isObjectExpression()) {
41 | result.json = init.getSource()
42 | }
43 | },
44 | }
45 | result.z = data
46 | return visitor
47 | }
48 | export class WxapkgWxmlParser extends BaseParser {
49 | private sources: string
50 | constructor(saver: Saver) {
51 | super(saver)
52 | }
53 | async parse(observable: S2Observable): Promise {
54 | let resolve
55 | const promise = new Promise((_resolve) => (resolve = _resolve))
56 | // 订阅wxml解析器
57 | observable.pipe>(filter((v) => v.WxmlParserV3)).subscribe({
58 | next: (value) => {
59 | const data = value.WxmlParserV3
60 | if (!data) return
61 | const { code, json, z } = data
62 | const dir = this.dir
63 | parseWxml(code, dir, json, z).then((result) => {
64 | Object.entries(result).forEach(([path, buffer]) => this.saver.add(path, buffer))
65 | })
66 | },
67 | complete() {
68 | resolve && resolve()
69 | },
70 | })
71 | return promise
72 | }
73 |
74 | async parseV1() {
75 | const result = await parseWxml(this.sources, this.dir)
76 | Object.entries(result).forEach(([path, buffer]) => this.saver.add(path, buffer as SaveAble))
77 | }
78 |
79 | get dir() {
80 | return this.saver.saveDirectory.path
81 | }
82 |
83 | static visitorV3(subject: WxmlParserV3Subject): Visitor {
84 | return {
85 | BlockStatement(path) {
86 | const parent = path.parentPath
87 | if (!parent) return
88 | if (!parent.isFunctionExpression()) return
89 | const params = parent.get('params')
90 | if (params.length !== 2) return
91 | if (params[0].getSource() !== 'path' || params[1].getSource() !== 'global') return
92 | const fn = path.find((p) => p.isAssignmentExpression())
93 | if (!fn) return
94 | const scopeName = getFirst(fn.get('left')).getSource()
95 | if (!scopeNameRE.test(scopeName)) return
96 | const result: TraverseResult = Object.create(null)
97 | path.traverse(makeVisitor(result))
98 | const contents = path.get('body').filter((p) => !p.isIfStatement())
99 | let next = 0
100 | const sourceIndex = contents.findIndex((p) => {
101 | if (p.isVariableDeclaration()) {
102 | const id = getFirst(p.get('declarations.0.id'))
103 | if (id && id.isIdentifier()) {
104 | const defineName = id.getSource()
105 | if (defineName === 'nv_require') {
106 | next = 1
107 | return true
108 | }
109 | return defineName === 'x'
110 | }
111 | }
112 | return false
113 | })
114 | const source = contents
115 | .slice(sourceIndex + next)
116 | .map((p) => p.getSource())
117 | .join('\n')
118 | result.scope = scopeName
119 | result.code = source
120 | subject.next({ WxmlParserV3: result })
121 | },
122 | }
123 | }
124 |
125 | setSource(sources: string) {
126 | this.sources = sources
127 | }
128 | }
129 |
--------------------------------------------------------------------------------
/src/core/wxapkg/WxapkgWxssParser.ts:
--------------------------------------------------------------------------------
1 | import { PathController, ProduciblePath } from '@baseController/PathController'
2 | import { matchScripts } from '@utils/matchScripts'
3 | import {
4 | Dict,
5 | S2Observable,
6 | TVSubject,
7 | WxssParserCommon2Subject,
8 | WxssParserCommonSubject,
9 | WxssParserSubject,
10 | } from './types'
11 | import { Visitor } from '@babel/core'
12 | import { Saver } from '@utils/classes/Saver'
13 | import { filter } from 'observable-fns'
14 | import { transformStyle } from '@utils/transformStyle'
15 | import { WxapkgKeyFile } from './WxapkgEnums'
16 | import { md5 } from '@utils/crypto'
17 | import { getLogger } from '@utils/logger'
18 | import { parseJSONFromJSCode } from '@utils/ast'
19 | import { findBuffer, getSaveController, saveAble2String } from '@baseController/SaveController'
20 | import { BaseParser } from '@base/BaseParser'
21 |
22 | function makeCStyleName(index: number): string {
23 | return `./@unveilr/wxss/unveilr.${md5(index.toString()).slice(-6)}.wxss`
24 | }
25 | export function styleConversion(k: string, source: string): string {
26 | const logger = getLogger('StyleConversion')
27 | const data = parseJSONFromJSCode(source)
28 | if (!Array.isArray(data)) return
29 |
30 | const handleEl = (el) => {
31 | if (!Array.isArray(el)) return el
32 | // [1] 是个分割符
33 | if (el.length === 1 && el[0] === 1) return ''
34 | switch (el[0]) {
35 | // 属性值单位 rpx
36 | case 0:
37 | return el[1] + 'rpx'
38 | // 导入
39 | case 2: {
40 | const _el = el[1]
41 | let path
42 | if (typeof _el === 'number') {
43 | path = makeCStyleName(_el)
44 | } else if (typeof _el === 'string') {
45 | path = _el
46 | } else {
47 | if (Array.isArray(_el)) return handleEl(_el)
48 | logger.warn(`Unprocessed element found: ${JSON.stringify(_el)}`)
49 | return ''
50 | }
51 | if (!path) return ''
52 | const target = PathController.make(k).relative(path).unixpath
53 | return target ? `@import "${path.replace('./', '/')}";\n` : ''
54 | }
55 | default:
56 | logger.warn(`Unprocessed data found: ${JSON.stringify(el)}`)
57 | return ''
58 | }
59 | }
60 | const newData = data.map((el) => handleEl(el)).join('')
61 | return transformStyle(newData).buffer
62 | }
63 |
64 | export class WxapkgWxssParser extends BaseParser {
65 | constructor(saver: Saver) {
66 | super(saver)
67 | }
68 |
69 | static getHTMLStyleSource(findDir: ProduciblePath): string {
70 | const htmlSources: string[] = []
71 | const findDirCtrl = PathController.make(findDir)
72 | const saveCtrl = getSaveController()
73 | const suffixes = ['.appservice.js', '.common.js', '.webview.js']
74 | findBuffer(findDirCtrl).forEach(({ key, buffer }) => {
75 | const ctrl = PathController.make(key)
76 | if (ctrl.suffixWithout.toLowerCase() !== 'html') return
77 | if (ctrl.basename === WxapkgKeyFile.PAGE_FRAME_HTML) return
78 | const s = saveAble2String(buffer)
79 | s && htmlSources.push(matchScripts(s))
80 | if (ctrl.suffixWithout.toLowerCase() === 'html') {
81 | suffixes.forEach((suffix) => saveCtrl.delete(ctrl.whitout(suffix).abspath))
82 | }
83 | saveCtrl.delete(ctrl.abspath)
84 | })
85 | return htmlSources.filter(Boolean).join(';\n')
86 | }
87 |
88 | async parse(observable: S2Observable): Promise {
89 | const addSaver = (data: Dict) => {
90 | Object.entries(data).forEach((args) => this.saver.add(...args))
91 | }
92 | let resolve
93 | const promise = new Promise((_resolve) => (resolve = _resolve))
94 | // 订阅公共样式
95 | observable.pipe>(filter((v) => v.WxssParserCommon)).subscribe({
96 | next: (data) => addSaver(data.WxssParserCommon),
97 | complete() {
98 | resolve && resolve()
99 | },
100 | })
101 | // 订阅公共样式2 _C
102 | observable.pipe>(filter((v) => v.WxssParserCommon2)).subscribe({
103 | next: (data) => addSaver(data.WxssParserCommon2),
104 | complete() {
105 | resolve && resolve()
106 | },
107 | })
108 | // 订阅非公共样式
109 | observable.pipe>(filter((v) => v.WxssParser)).subscribe({
110 | next: (data) => addSaver(data.WxssParser),
111 | complete() {
112 | resolve && resolve()
113 | },
114 | })
115 | return promise
116 | }
117 | // 读取 `setCssToHead` 函数
118 | static visitorSetCssToHead(subject: WxssParserSubject): Visitor {
119 | return {
120 | CallExpression(path) {
121 | const callee = path.node.callee
122 | if (callee.type === 'Identifier' && callee.name === 'setCssToHead') {
123 | const args = path.get('arguments')
124 | if (!args.length || (args.length === 1 && args[0].getSource() === '[]')) return
125 | // 第二项是错误信息
126 | if (args.length === 3) args.splice(1, 1)
127 | const [sources, _path] = args.map((p) => {
128 | const data = parseJSONFromJSCode(p.getSource())
129 | return data.path ? data.path : data
130 | })
131 | subject.next({
132 | WxssParser: {
133 | [_path]: styleConversion(_path, JSON.stringify(sources)),
134 | },
135 | })
136 | }
137 | },
138 | }
139 | }
140 | // 读取 `__COMMON_STYLESHEETS__`
141 | static visitorCommonStyle(subject: WxssParserCommonSubject): Visitor {
142 | return {
143 | MemberExpression(path) {
144 | const node = path.node
145 | if (
146 | node.object.type === 'Identifier' &&
147 | node.property.type === 'StringLiteral' &&
148 | node.object.name === '__COMMON_STYLESHEETS__'
149 | ) {
150 | const p = node.property.value
151 | subject.next({
152 | WxssParserCommon: {
153 | [p]: styleConversion(p, path.getOpposite().getSource()),
154 | },
155 | })
156 | }
157 | },
158 | }
159 | }
160 | // 读取 `_C` 数组
161 | static visitorCArray(subject: WxssParserCommon2Subject): Visitor {
162 | return {
163 | VariableDeclarator(path) {
164 | const id = path.get('id')
165 | const init = path.get('init')
166 | if (!(id && init)) return
167 | if (id.isIdentifier() && id.getSource() === '_C' && init.isArrayExpression()) {
168 | init.get('elements').forEach((el, index) => {
169 | const p = makeCStyleName(index)
170 | subject.next({
171 | WxssParserCommon2: {
172 | [p]: styleConversion(p, el.getSource()),
173 | },
174 | })
175 | })
176 | }
177 | },
178 | }
179 | }
180 | }
181 |
--------------------------------------------------------------------------------
/src/core/wxapkg/index.ts:
--------------------------------------------------------------------------------
1 | import { SaveController } from '@baseController/SaveController'
2 | import { getConfig } from '@baseController/ConfigController'
3 | import { PathController } from '@baseController/PathController'
4 | import { PackageSuffix } from '@enum/PackageSuffix'
5 | import { WxapkgController } from '@core/wxapkg/WxapkgController'
6 | import { WxapkgKeyFile } from '@core/wxapkg/WxapkgEnums'
7 |
8 | export async function invokeWxapkg() {
9 | SaveController.setIsClean(getConfig('WXClearDecompile'))
10 | SaveController.setIsReFormat(getConfig('WXReformat'))
11 | SaveController.addOverrideFiles([WxapkgKeyFile.GAME, WxapkgKeyFile.PLUGIN])
12 | // SaveController.setIsSafeMode(true)
13 | const packages = getConfig('WXPackages')
14 | function filterWxapkg(ctrl: PathController) {
15 | return ctrl.isFile && ctrl.suffixWithout === PackageSuffix.WXAPKG
16 | }
17 | const depth = getConfig('WXDepth')
18 | const wxapkgList: PathController[] = []
19 | for (const pack of packages) {
20 | const ctrl = PathController.make(pack)
21 | if (ctrl.isDirectory) {
22 | const list = ctrl
23 | .deepListDir(depth)
24 | .map((p) => PathController.make(p))
25 | .filter((p) => filterWxapkg(p))
26 | wxapkgList.push(...list)
27 | } else {
28 | wxapkgList.push(ctrl)
29 | }
30 | }
31 | return new WxapkgController({
32 | wxapkgList,
33 | wxAppId: getConfig('WXAppId'),
34 | mainSaveDir: getConfig('WXOutput'),
35 | }).exploit()
36 | }
37 |
--------------------------------------------------------------------------------
/src/core/wxapkg/types.d.ts:
--------------------------------------------------------------------------------
1 | import { Visitor } from '@babel/core'
2 | import { Observable, Subject } from 'threads/observable'
3 |
4 | export interface TraverseVisitorMap {
5 | AppConfigService: Visitor
6 | WxssParser: Visitor
7 | WxssParserCommon: Visitor
8 | WxssParserCommon2: Visitor
9 | ScriptParser: Visitor
10 | WxmlParserV3: Visitor
11 | }
12 | export type TraverseVisitorKeys = keyof TraverseVisitorMap
13 | export type Dict = { [key: string]: T }
14 | export type SubjectType = { [name in K]: V }
15 | export type TVSubjectType = SubjectType
16 | export type TVSubject = Subject
17 | export type AppConfigServiceSubject = Subject>
18 | export type WxssParserSubject = Subject>
19 | export type WxssParserCommonSubject = Subject>
20 | export type WxssParserCommon2Subject = Subject>
21 | export type ScriptParserSubject = Subject>
22 | export type WxmlParserV3Subject = Subject>
23 | export type S2Observable> = T extends Subject ? Observable : never
24 | export type ParserLike = {
25 | parse(...args: Args[]): Ret
26 | }
27 | export type ZArray = { mul: Record }
28 | export interface TraverseResult {
29 | z: ZArray
30 | json: string
31 | code: string
32 | scope: string
33 | }
34 |
--------------------------------------------------------------------------------
/src/core/wxapkg/utils/checkWxapkg.ts:
--------------------------------------------------------------------------------
1 | import { WxapkgKeyFile, WxapkgType } from '../WxapkgEnums'
2 | import { isProduciblePath, PathController, ProduciblePath } from '@baseController/PathController'
3 |
4 | export function checkMacEncryption(buf: Buffer): boolean {
5 | const encryptedForMac = 'WAPkgEncryptedTagForMac'
6 | return buf.subarray(-encryptedForMac.length).toString() !== encryptedForMac
7 | }
8 | export function checkWxapkg(path: ProduciblePath): boolean
9 | export function checkWxapkg(buff: Buffer): boolean
10 | export function checkWxapkg(v: ProduciblePath | Buffer): boolean {
11 | const buf = (isProduciblePath(v) ? PathController.make(v).readSync() : v) as Buffer
12 | return buf.readUInt8(0) === 0xbe && buf.readUInt8(13) === 0xed
13 | }
14 |
15 | function _getWxapkgType(fileList: string[]): WxapkgType {
16 | if (fileList.every((filename) => filename.startsWith('WA'))) return WxapkgType.FRAMEWORK
17 | // APP_V1/APP_V4
18 | if (fileList.includes(WxapkgKeyFile.PAGE_FRAME_HTML)) {
19 | if (fileList.includes(WxapkgKeyFile.COMMON_APP)) return WxapkgType.APP_V4
20 | return WxapkgType.APP_V1
21 | }
22 | // APP_V3/APP_SUBPACKAGE_V2
23 | if (fileList.includes(WxapkgKeyFile.COMMON_APP))
24 | return fileList.includes(WxapkgKeyFile.APP_WXSS) ? WxapkgType.APP_V3 : WxapkgType.APP_SUBPACKAGE_V2
25 | // APP_V2/APP_SUBPACKAGE_V1
26 | if (fileList.includes(WxapkgKeyFile.PAGE_FRAME))
27 | return fileList.includes(WxapkgKeyFile.APP_WXSS) ? WxapkgType.APP_V2 : WxapkgType.APP_SUBPACKAGE_V1
28 | // GAME/GAME_SUBPACKAGE
29 | if (fileList.includes(WxapkgKeyFile.GAME))
30 | return fileList.includes(WxapkgKeyFile.APP_CONFIG) ? WxapkgType.GAME : WxapkgType.GAME_SUBPACKAGE
31 | // APP_PLUGIN_V1/GAME_PLUGIN
32 | if (fileList.includes(WxapkgKeyFile.PLUGIN_JSON)) {
33 | if (fileList.includes(WxapkgKeyFile.APPSERVICE)) return WxapkgType.APP_PLUGIN_V1
34 | if (fileList.includes(WxapkgKeyFile.PLUGIN)) return WxapkgType.GAME_PLUGIN
35 | }
36 | // not found
37 | return null
38 | }
39 | export function checkWxapkgType(path: ProduciblePath): Promise
40 | export function checkWxapkgType(list: string[]): WxapkgType
41 | export function checkWxapkgType(v: ProduciblePath | string[]): Promise | WxapkgType {
42 | if (isProduciblePath(v)) {
43 | const pCtrl = PathController.make(v)
44 | if (!pCtrl.isDirectory) throw Error(`Path ${v} is not a directory`)
45 | return pCtrl.readdir().then((fileList) => _getWxapkgType(fileList))
46 | } else {
47 | return _getWxapkgType(v)
48 | }
49 | }
50 |
--------------------------------------------------------------------------------
/src/core/wxapkg/utils/createPage.ts:
--------------------------------------------------------------------------------
1 | import { PathController, ProduciblePath } from '@baseController/PathController'
2 | import { SaveAble } from '@baseController/SaveController'
3 |
4 | export interface PageInfo {
5 | [key: string]: {
6 | window: {
7 | usingComponents?: { [key: string]: unknown }
8 | [key: string]: unknown
9 | }
10 | }
11 | }
12 |
13 | type PageResult = Array<[ProduciblePath, SaveAble]>
14 |
15 | export function createPage(path: ProduciblePath, data: PageInfo[string]): PageResult {
16 | const pCtrl = PathController.make(path)
17 | const unixpath = pCtrl.whitout().unixpath
18 | const window = data.window
19 | const isComponent = Boolean(window.component)
20 | const LICENSE = 'Generated by @unveilr'
21 | const fileContents = {
22 | wxml: `\n${unixpath}`,
23 | json: window,
24 | js: `/* ${LICENSE} */\n${isComponent ? 'Component' : 'Page'}({})`,
25 | wxss: `/* ${LICENSE} */`,
26 | }
27 | return Object.entries(fileContents).map(([suffix, buffer]) => [pCtrl.whitout(`.${suffix}`), buffer])
28 | }
29 |
--------------------------------------------------------------------------------
/src/core/wxapkg/utils/getWccVersion.ts:
--------------------------------------------------------------------------------
1 | export function getWccVersion(source: string): string | null {
2 | const regex = /\/\*(v\S+?)\*\//
3 | if (!source) return null
4 | const result = source.match(regex)
5 | if (Array.isArray(result) && result[1]) return result[1]
6 | return null
7 | }
8 |
--------------------------------------------------------------------------------
/src/core/wxapkg/worker.ts:
--------------------------------------------------------------------------------
1 | import { expose } from 'threads/worker'
2 | import { isWorkerRuntime } from '@utils/isWorkerRuntime'
3 | import { Observable, Subject } from 'threads/observable'
4 | import { Visitor } from '@babel/core'
5 | import { TraverseController } from '@baseController/TraverseController'
6 | import { initializeConfig } from '@baseController/ConfigController'
7 | import { TraverseVisitorKeys, TraverseVisitorMap, TVSubjectType } from './types'
8 | import { WxapkgAppConfigParser } from './WxapkgAppConfigParser'
9 | import { WxapkgWxssParser } from './WxapkgWxssParser'
10 | import { WxapkgScriptParser } from './WxapkgScriptParser'
11 | import { WxapkgWxmlParser } from './WxapkgWxmlParser'
12 |
13 | export function createExposed() {
14 | const subject = new Subject()
15 | const visitors: Partial = {}
16 | const visitorsFn: Record Visitor> = {
17 | AppConfigService: WxapkgAppConfigParser.visitor,
18 | WxssParser: WxapkgWxssParser.visitorSetCssToHead,
19 | WxssParserCommon: WxapkgWxssParser.visitorCommonStyle,
20 | WxssParserCommon2: WxapkgWxssParser.visitorCArray,
21 | ScriptParser: WxapkgScriptParser.visitor,
22 | WxmlParserV3: WxapkgWxmlParser.visitorV3,
23 | }
24 | return {
25 | // worker 运行时需要复制一份配置
26 | initWorker(config: Parameters[0]) {
27 | initializeConfig(config)
28 | },
29 | async startTraverse(code: string) {
30 | const tCtrl = new TraverseController({ code })
31 | tCtrl.addVisitors(...Object.values(visitors))
32 | await tCtrl.traverse()
33 | subject.complete()
34 | },
35 | setVisitor(...keys: Array) {
36 | keys.forEach((key) => (visitors[key] = visitorsFn[key](subject)))
37 | },
38 | observable() {
39 | return Observable.from(subject)
40 | },
41 | }
42 | }
43 |
44 | if (isWorkerRuntime()) {
45 | expose(createExposed())
46 | }
47 |
48 | export const traverseModule = module
49 |
--------------------------------------------------------------------------------
/src/core/wxapkg/wxml-parser/index.ts:
--------------------------------------------------------------------------------
1 | export { parseWxml } from './parseWxml'
2 | export { parseZArrayFromCode } from './parseZArray'
3 |
--------------------------------------------------------------------------------
/src/core/wxapkg/wxml-parser/parseWxml.ts:
--------------------------------------------------------------------------------
1 | import { resolve } from 'path'
2 | import { VM } from 'vm2'
3 | import { parseScript } from 'esprima'
4 | import { generate } from 'escodegen'
5 | import { parserZArray, restoreGroup } from './parseZArray'
6 | import { removeInvalidLineCode, toDir, getZArrayKey } from './utils'
7 | import { ZArray } from '../types'
8 |
9 | export interface ParserResult {
10 | [filename: string]: string
11 | }
12 |
13 | const saveMapper = {}
14 | function analyze(core, z, namePool, xPool, fakePool = {}, zMulName = '0') {
15 | function anaRecursion(core, fakePool = {}) {
16 | return analyze(core, z, namePool, xPool, fakePool, zMulName)
17 | }
18 |
19 | function push(name, elem) {
20 | namePool[name] = elem
21 | }
22 |
23 | function pushSon(pname, son) {
24 | if (fakePool[pname]) fakePool[pname].son.push(son)
25 | else namePool[pname].son.push(son)
26 | }
27 |
28 | for (let ei = 0; ei < core.length; ei++) {
29 | let e = core[ei]
30 | switch (e.type) {
31 | case 'ExpressionStatement': {
32 | let f = e.expression
33 | if (f.callee) {
34 | if (f.callee.type == 'Identifier') {
35 | switch (f.callee.name) {
36 | case '_r':
37 | namePool[f.arguments[0].name].v[f.arguments[1].value] = z[f.arguments[2].value]
38 | break
39 | case '_rz':
40 | namePool[f.arguments[1].name].v[f.arguments[2].value] = z.mul[zMulName][f.arguments[3].value]
41 | break
42 | case '_':
43 | pushSon(f.arguments[0].name, namePool[f.arguments[1].name])
44 | break
45 | case '_2':
46 | {
47 | let item = f.arguments[6].value //def:item
48 | let index = f.arguments[7].value //def:index
49 | let data = z[f.arguments[0].value]
50 | let key = generate(f.arguments[8]).slice(1, -1) //f.arguments[8].value;//def:""
51 | let obj = namePool[f.arguments[5].name]
52 | let gen = namePool[f.arguments[1].name]
53 | if (gen.tag == 'gen') {
54 | let ret = gen.func.body.body.pop().argument.name
55 | anaRecursion(gen.func.body.body, { [ret]: obj })
56 | }
57 | obj.v['wx:for'] = data
58 | if (index != 'index') obj.v['wx:for-index'] = index
59 | if (item != 'item') obj.v['wx:for-item'] = item
60 | if (key != '') obj.v['wx:key'] = key
61 | }
62 | break
63 | case '_2z':
64 | {
65 | let item = f.arguments[7].value //def:item
66 | let index = f.arguments[8].value //def:index
67 | let data = z.mul[zMulName][f.arguments[1].value]
68 | let key = generate(f.arguments[9]).slice(1, -1) //f.arguments[9].value;//def:""
69 | let obj = namePool[f.arguments[6].name]
70 | let gen = namePool[f.arguments[2].name]
71 | if (gen.tag == 'gen') {
72 | let ret = gen.func.body.body.pop().argument.name
73 | anaRecursion(gen.func.body.body, { [ret]: obj })
74 | }
75 | obj.v['wx:for'] = data
76 | if (index != 'index') obj.v['wx:for-index'] = index
77 | if (item != 'item') obj.v['wx:for-item'] = item
78 | if (key != '') obj.v['wx:key'] = key
79 | }
80 | break
81 | case '_ic':
82 | pushSon(f.arguments[5].name, {
83 | tag: 'include',
84 | son: [],
85 | v: { src: xPool[f.arguments[0].property.value] },
86 | })
87 | break
88 | case '_ai':
89 | {
90 | //template import
91 | let to = Object.keys(fakePool)[0]
92 | if (to)
93 | pushSon(to, {
94 | tag: 'import',
95 | son: [],
96 | v: { src: xPool[f.arguments[1].property.value] },
97 | })
98 | else throw Error('Unexpected fake pool')
99 | }
100 | break
101 | case '_af':
102 | //ignore _af
103 | break
104 | default:
105 | throw Error('Unknown expression callee name ' + f.callee.name)
106 | }
107 | } else if (f.callee.type == 'MemberExpression') {
108 | if (f.callee.object.name == 'cs' || f.callee.property.name == 'pop') break
109 | throw Error('Unknown member expression')
110 | } else throw Error('Unknown callee type ' + f.callee.type)
111 | } else if (f.type == 'AssignmentExpression' && f.operator == '=') {
112 | //no special use
113 | } else throw Error('Unknown expression statement.')
114 | break
115 | }
116 | case 'VariableDeclaration':
117 | for (let dec of e.declarations) {
118 | if (dec.init.type == 'CallExpression') {
119 | switch (dec.init.callee.name) {
120 | case '_n':
121 | push(dec.id.name, {
122 | tag: dec.init.arguments[0].value,
123 | son: [],
124 | v: {},
125 | })
126 | break
127 | case '_v':
128 | push(dec.id.name, { tag: 'block', son: [], v: {} })
129 | break
130 | case '_o':
131 | push(dec.id.name, {
132 | tag: '__textNode__',
133 | textNode: true,
134 | content: z[dec.init.arguments[0].value],
135 | })
136 | break
137 | case '_oz':
138 | push(dec.id.name, {
139 | tag: '__textNode__',
140 | textNode: true,
141 | content: z.mul[zMulName][dec.init.arguments[1].value],
142 | })
143 | break
144 | case '_m':
145 | {
146 | // const arg2 = dec.init.arguments[2]
147 | // if (arg2 && arg2.elements && arg2.elements.length > 0)
148 | // throw Error('Noticable generics content: ' + arg2.toString())
149 | let mv = {}
150 | let name = null
151 | let base = 0
152 | for (let x of dec.init.arguments[1].elements) {
153 | let v = x.value
154 | if (!v && typeof v != 'number') {
155 | if (x.type == 'UnaryExpression' && x.operator == '-') v = -x.argument.value
156 | else throw Error('Unknown type of object in _m attrs array: ' + x.type)
157 | }
158 | if (name === null) {
159 | name = v
160 | } else {
161 | if (base + v < 0) mv[name] = null
162 | else {
163 | mv[name] = z[base + v]
164 | if (base == 0) base = v
165 | }
166 | name = null
167 | }
168 | }
169 | push(dec.id.name, {
170 | tag: dec.init.arguments[0].value,
171 | son: [],
172 | v: mv,
173 | })
174 | }
175 | break
176 | case '_mz':
177 | {
178 | // if (dec.init.arguments[3].elements.length > 0)
179 | // throw Error('Noticable generics content: ' + dec.init.arguments[3].toString())
180 | let mv = {}
181 | let name = null,
182 | base = 0
183 | for (let x of dec.init.arguments[2].elements) {
184 | let v = x.value
185 | if (!v && typeof v != 'number') {
186 | if (x.type == 'UnaryExpression' && x.operator == '-') v = -x.argument.value
187 | else throw Error('Unknown type of object in _mz attrs array: ' + x.type)
188 | }
189 | if (name === null) {
190 | name = v
191 | } else {
192 | if (base + v < 0) mv[name] = null
193 | else {
194 | mv[name] = z.mul[zMulName][base + v]
195 | if (base == 0) base = v
196 | }
197 | name = null
198 | }
199 | }
200 | push(dec.id.name, {
201 | tag: dec.init.arguments[1].value,
202 | son: [],
203 | v: mv,
204 | })
205 | }
206 | break
207 | case '_gd': //template use/is
208 | {
209 | let is = namePool[dec.init.arguments[1].name].content
210 | let data = null,
211 | obj = null
212 | ei++
213 | for (let e of core[ei].consequent.body) {
214 | if (e.type == 'VariableDeclaration') {
215 | for (let f of e.declarations) {
216 | if (f.init.type == 'LogicalExpression' && f.init.left.type == 'CallExpression') {
217 | if (f.init.left.callee.name == '_1') data = z[f.init.left.arguments[0].value]
218 | else if (f.init.left.callee.name == '_1z')
219 | data = z.mul[zMulName][f.init.left.arguments[1].value]
220 | }
221 | }
222 | } else if (e.type == 'ExpressionStatement') {
223 | let f = e.expression
224 | if (
225 | f.type == 'AssignmentExpression' &&
226 | f.operator == '=' &&
227 | f.left.property &&
228 | f.left.property.name == 'wxXCkey'
229 | ) {
230 | obj = f.left.object.name
231 | }
232 | }
233 | }
234 | namePool[obj].tag = 'template'
235 | Object.assign(namePool[obj].v, { is: is, data: data })
236 | }
237 | break
238 | default: {
239 | let funName = dec.init.callee.name
240 | zMulName = getZArrayKey(funName)
241 | if (!zMulName) throw Error('Unknown init callee ' + funName)
242 | }
243 | }
244 | } else if (dec.init.type == 'FunctionExpression') {
245 | push(dec.id.name, { tag: 'gen', func: dec.init })
246 | } else if (dec.init.type == 'MemberExpression') {
247 | if (
248 | dec.init.object.type == 'MemberExpression' &&
249 | dec.init.object.object.name == 'e_' &&
250 | dec.init.object.property.type == 'MemberExpression' &&
251 | dec.init.object.property.object.name == 'x'
252 | ) {
253 | if (dec.init.property.name == 'j') {
254 | //include
255 | //do nothing
256 | } else if (dec.init.property.name == 'i') {
257 | //import
258 | //do nothing
259 | } else throw Error('Unknown member expression declaration.')
260 | } else throw Error('Unknown member expression declaration.')
261 | } else throw Error('Unknown declaration init type ' + dec.init.type)
262 | }
263 | break
264 | case 'IfStatement':
265 | if (e.test.callee.name.startsWith('_o')) {
266 | // ts-ignore
267 | const parse_OFun = (e) => {
268 | if (e.test.callee.name == '_o') return z[e.test.arguments[0].value]
269 | else if (e.test.callee.name == '_oz') return z.mul[zMulName][e.test.arguments[1].value]
270 | else throw Error('Unknown if statement test callee name:' + e.test.callee.name)
271 | }
272 |
273 | let vname = e.consequent.body[0].expression.left.object.name
274 | let nif: any = { tag: 'block', v: { 'wx:if': parse_OFun(e) }, son: [] }
275 | anaRecursion(e.consequent.body, { [vname]: nif })
276 | pushSon(vname, nif)
277 | if (e.alternate) {
278 | while (e.alternate && e.alternate.type == 'IfStatement') {
279 | e = e.alternate
280 | nif = { tag: 'block', v: { 'wx:elif': parse_OFun(e) }, son: [] } as unknown
281 | anaRecursion(e.consequent.body, { [vname]: nif })
282 | pushSon(vname, nif)
283 | }
284 | if (e.alternate && e.alternate.type == 'BlockStatement') {
285 | e = e.alternate
286 | nif = { tag: 'block', v: { 'wx:else': null }, son: [] }
287 | anaRecursion(e.body, { [vname]: nif })
288 | pushSon(vname, nif)
289 | }
290 | }
291 | } else throw Error('Unknown if statement.')
292 | break
293 | default:
294 | throw Error('Unknown type ' + e.type)
295 | }
296 | }
297 | }
298 | function wxmlify(str, isText?: boolean) {
299 | if (typeof str == 'undefined' || str === null) return 'Empty' //throw Error("Empty str in "+(isText?"text":"prop"));
300 | if (isText) return str //may have some bugs in some specific case(undocumented by tx)
301 | else return str.replace(/"/g, '\\"')
302 | }
303 | function elemToString(elem, dep, moreInfo = false) {
304 | const longerList = [] //put tag name which can't be style.
305 | const indent = ' '.repeat(4)
306 |
307 | function isTextTag(elem) {
308 | return elem.tag == '__textNode__' && elem.textNode
309 | }
310 |
311 | function elemRecursion(elem, dep) {
312 | return elemToString(elem, dep, moreInfo)
313 | }
314 |
315 | function trimMerge(rets) {
316 | let needTrimLeft = false,
317 | ans: any = ''
318 | for (let ret of rets) {
319 | if (ret.textNode == 1) {
320 | if (!needTrimLeft) {
321 | needTrimLeft = true
322 | ans = ans.trimRight()
323 | }
324 | } else if (needTrimLeft) {
325 | needTrimLeft = false
326 | ret = ret.trimLeft()
327 | }
328 | ans += ret
329 | }
330 | return ans
331 | }
332 |
333 | if (isTextTag(elem)) {
334 | //In comment, you can use typify text node, which beautify its code, but may destroy ui.
335 | //So, we use a "hack" way to solve this problem by letting typify program stop when face textNode
336 | let str: any = new String(wxmlify(elem.content, true))
337 | str.textNode = 1
338 | return wxmlify(str, true) //indent.repeat(dep)+wxmlify(elem.content.trim(),true)+"\n";
339 | }
340 | if (elem.tag == 'block' && !moreInfo) {
341 | if (elem.son.length == 1 && !isTextTag(elem.son[0])) {
342 | let ok = true,
343 | s = elem.son[0]
344 | for (let x in elem.v)
345 | if (x in s.v) {
346 | ok = false
347 | break
348 | }
349 | if (
350 | ok &&
351 | !(('wx:for' in s.v || 'wx:if' in s.v) && ('wx:if' in elem.v || 'wx:else' in elem.v || 'wx:elif' in elem.v))
352 | ) {
353 | //if for and if in one tag, the default result is an if in for. And we should block if nested in elif/else been combined.
354 | Object.assign(s.v, elem.v)
355 | return elemRecursion(s, dep)
356 | }
357 | } else if (Object.keys(elem.v).length == 0) {
358 | let ret = []
359 | for (let s of elem.son) ret.push(elemRecursion(s, dep))
360 | return trimMerge(ret)
361 | }
362 | }
363 | let ret = indent.repeat(dep) + '<' + elem.tag
364 | for (let v in elem.v) ret += ' ' + v + (elem.v[v] !== null ? '="' + wxmlify(elem.v[v]) + '"' : '')
365 | if (elem.son.length == 0) {
366 | if (longerList.includes(elem.tag)) return ret + ' />\n'
367 | else return ret + '>' + elem.tag + '>\n'
368 | }
369 | ret += '>\n'
370 | let rets = [ret]
371 | for (let s of elem.son) rets.push(elemRecursion(s, dep + 1))
372 | rets.push(indent.repeat(dep) + '' + elem.tag + '>\n')
373 | return trimMerge(rets)
374 | }
375 | function doWxml(state, dir, name, code, z, xPool, rDs, wxsList, moreInfo) {
376 | // require('fs').writeFileSync('src/test/doWxml.js', code, {flag: 'a'})
377 | let rname = code
378 | .slice(code.lastIndexOf('return') + 6)
379 | .replace(/[;}]/g, '')
380 | .trim()
381 | code = code.slice(code.indexOf('\n'), code.lastIndexOf('return')).trim()
382 | // require('fs').writeFileSync('src/test/doWxml.js', code, {flag: 'a'})
383 | const r = { son: [] }
384 | analyze(parseScript(code).body, z, { [rname]: r }, xPool, { [rname]: r })
385 | const ans = []
386 | // 保存解析结果
387 | for (const elem of r.son) {
388 | ans.push(elemToString(elem, 0, moreInfo))
389 | }
390 | const result = [ans.join('')]
391 | for (let v in rDs) {
392 | state[0] = v
393 | let oriCode = rDs[v].toString()
394 | let rname = oriCode
395 | .slice(oriCode.lastIndexOf('return') + 6)
396 | .replace(/[;}]/g, '')
397 | .trim()
398 | let tryPtr = oriCode.indexOf('\ntry{')
399 | let zPtr = oriCode.indexOf('var z=gz$gwx')
400 | let code = oriCode.slice(tryPtr + 5, oriCode.lastIndexOf('\n}catch(')).trim()
401 | if (zPtr !== -1 && tryPtr > zPtr) {
402 | let attach = oriCode.slice(zPtr)
403 | attach = attach.slice(0, attach.indexOf('()')) + '()\n'
404 | code = attach + code
405 | }
406 | let r = { tag: 'template', v: { name: v }, son: [] }
407 | analyze(parseScript(code).body, z, { [rname]: r }, xPool, { [rname]: r })
408 | result.unshift(elemToString(r, 0, moreInfo))
409 | }
410 | // 添加wxs导入代码
411 | name = resolve(dir, name)
412 | if (wxsList[name]) result.push(wxsList[name])
413 | saveMapper[name] = result.join('')
414 | }
415 | function tryWxml(dir, name, code, z, xPool, rDs, wxsList, moreInfo) {
416 | let state = [null]
417 | doWxml(state, dir, name, code, z, xPool, rDs, wxsList, moreInfo)
418 | }
419 | function doWxs(code, name?: string) {
420 | name = name || ''
421 | name = name.substring(0, name.lastIndexOf('/') + 1)
422 | const before = 'nv_module={nv_exports:{}};'
423 | const re = new RegExp(('p_' + name).replace(/\//g, '\\/'), 'g')
424 | return removeInvalidLineCode(
425 | code
426 | .slice(code.indexOf(before) + before.length, code.lastIndexOf('return nv_module.nv_exports;}'))
427 | .replace(re, '')
428 | .replace(/nv_/g, '')
429 | .replace(/(require\(.*?\))\(\)/g, '$1'),
430 | )
431 | }
432 |
433 | function parser(code, dir, json, z) {
434 | let rD = {}
435 | let rE = {}
436 | let rF = {}
437 | let requireInfo = {}
438 | let x = [] // 文件名列表
439 | let vm = new VM({
440 | sandbox: {
441 | d_: rD,
442 | e_: rE,
443 | f_: rF,
444 | __receive__(data) {
445 | ;[x, requireInfo] = data
446 | },
447 | nv_require(path) {
448 | return () => path
449 | },
450 | },
451 | })
452 | vm.run(`${code}\n__receive__([x,${json}])`)
453 | // 导入名称与文件名的映射
454 | const pF = {}
455 | // 外部wxs文件引入代码
456 | const wxsImportCodeMap = {}
457 | // rF 保存的是wxs
458 | for (const filename in rF) {
459 | // 文件名
460 | const name = resolve(dir, (filename[0] === '/' ? '.' : '') + filename)
461 | const wxsItem = rF[filename]
462 |
463 | // 解析格式: `f_['./pages/my/util.wxs'] = nv_require('p_./pages/my/util.wxs')`
464 | if (typeof wxsItem == 'function') {
465 | const requireName = wxsItem()
466 | pF[requireName] = filename
467 | saveMapper[name] = doWxs(requireInfo[requireName].toString(), filename)
468 | }
469 | // 解析格式: `f_['./pages/my/vip.wxml']['util'] = f_['./pages/my/util.wxs'] || nv_require('p_./pages/my/util.wxs')`
470 | else if (typeof wxsItem == 'object') {
471 | const wxsResult = []
472 | for (const moduleName in wxsItem) {
473 | const requireName = wxsItem[moduleName]()
474 | // 内嵌的wxs
475 | if (requireName.includes(':')) {
476 | const resultWxs = doWxs(requireInfo[requireName].toString())
477 | wxsResult.push(`${resultWxs}`)
478 | }
479 | // 导入外部文件
480 | else {
481 | const _file = pF[requireName] || requireName.slice(2)
482 | const src = toDir(_file, filename)
483 | wxsResult.push(``)
484 | }
485 | wxsImportCodeMap[name] = wxsResult.join('\n')
486 | }
487 | }
488 | }
489 | // rE 保存的是wxml的虚拟DOM
490 | // x 是文件名列表
491 | for (let name in rE) {
492 | tryWxml(dir, name, rE[name].f.toString(), z, x, rD[name], wxsImportCodeMap, void 0)
493 | }
494 | return saveMapper
495 | }
496 |
497 | export function parseWxml(code: string, dir: string): Promise
498 | export function parseWxml(code: string, dir: string, json: string, z: ZArray): Promise
499 | export async function parseWxml(...args) {
500 | if (arguments.length === 4) {
501 | const [code, dir, json, z] = args
502 | return parser(code, dir, json, restoreGroup(z))
503 | }
504 | if (arguments.length === 2) {
505 | let [code, dir] = args
506 | const z = await parserZArray(code)
507 | const before = '\nvar nv_require=function(){var nnm='
508 | const beforeIndex = code.lastIndexOf(before)
509 | let json
510 | if (beforeIndex !== -1) {
511 | code = code.slice(code.lastIndexOf(before) + before.length, code.lastIndexOf('if(path&&e_[path]){'))
512 | json = code.slice(0, code.indexOf('};') + 1)
513 | let endOfRequire = code.indexOf('()\r\n') + 4
514 | if (endOfRequire === 3) endOfRequire = code.indexOf('()\n') + 3
515 | code = code.slice(endOfRequire)
516 | } else {
517 | const rollbackIndex = code.lastIndexOf('})(z);d_[')
518 | if (rollbackIndex === -1) throw Error('Parsing wxml failed, Unsupported file')
519 | code = code.slice(rollbackIndex + 6, code.lastIndexOf('if(path&&e_[path]){'))
520 | code += 'var x = [...new Set(Object.keys(e_))]'
521 | json = '{}'
522 | }
523 | // try {
524 | // return parser(code, dir, json, z)
525 | // } catch (e) {
526 | // throw Error('Parsing wxml failed, ' + e.trace)
527 | // }
528 | return parser(code, dir, json, z)
529 | }
530 | throw RangeError('Parsing wxml failed, arguments must be 2 or 4')
531 | }
532 |
--------------------------------------------------------------------------------
/src/core/wxapkg/wxml-parser/parseZArray.ts:
--------------------------------------------------------------------------------
1 | import { VM } from 'vm2'
2 | import { getZArrayKey } from './utils'
3 |
4 | function catchZGroup(code, groupPreStr, cb) {
5 | const debugPre = '(function(z){var a=11;function Z(ops,debugLine){'
6 | const zArr = {}
7 | for (const preStr of groupPreStr) {
8 | let content = code.slice(code.indexOf(preStr))
9 | // eslint-disable-next-line prefer-const
10 | let z = []
11 | content = content.slice(content.indexOf('(function(z){var a=11;'))
12 | content = content.slice(0, content.indexOf('})(__WXML_GLOBAL__.ops_cached.$gwx')) + '})(z);'
13 | const vm = new VM({ sandbox: { z: z, debugInfo: [] } })
14 | vm.run(content)
15 | if (content.startsWith(debugPre)) for (let i = 0; i < z.length; i++) z[i] = z[i][1]
16 | const zArrKey = getZArrayKey(preStr.match(/(\S+)\(\s*\)/)[1])
17 | zArr[zArrKey] = z
18 | }
19 | cb({ mul: zArr })
20 | }
21 |
22 | function catchZ(code, cb) {
23 | const groupTest = code.match(/function gz\$gwx(\d*_\d+)\(\)\{\s*if\( __WXML_GLOBAL__\.ops_cached\.\$gwx\d*_\d+\)/g)
24 | if (groupTest !== null) return catchZGroup(code, groupTest, cb)
25 | const z = []
26 | const vm = new VM({
27 | sandbox: {
28 | z: z,
29 | debugInfo: [],
30 | },
31 | })
32 | let lastPtr = code.lastIndexOf('(z);__WXML_GLOBAL__.ops_set.$gwx=z;')
33 | if (lastPtr === -1) lastPtr = code.lastIndexOf('(z);__WXML_GLOBAL__.ops_set.$gwx')
34 | if (lastPtr === -1) lastPtr = code.lastIndexOf('(z);')
35 | code = code.slice(code.lastIndexOf('(function(z){var a=11;function Z(ops){z.push(ops)}'), lastPtr + 4)
36 | vm.run(code)
37 | cb(z)
38 | }
39 |
40 | function restoreSingle(ops, withScope = false) {
41 | if (typeof ops == 'undefined') return ''
42 |
43 | function scope(value) {
44 | if (value.startsWith('{') && value.endsWith('}')) return withScope ? value : '{' + value + '}'
45 | return withScope ? value : '{{' + value + '}}'
46 | }
47 |
48 | function enBrace(value, type = '{') {
49 | if (
50 | value.startsWith('{') ||
51 | value.startsWith('[') ||
52 | value.startsWith('(') ||
53 | value.endsWith('}') ||
54 | value.endsWith(']') ||
55 | value.endsWith(')')
56 | )
57 | value = ' ' + value + ' '
58 | switch (type) {
59 | case '{':
60 | return '{' + value + '}'
61 | case '[':
62 | return '[' + value + ']'
63 | case '(':
64 | return '(' + value + ')'
65 | default:
66 | throw Error('Unknown brace type ' + type)
67 | }
68 | }
69 |
70 | function restoreNext(ops, w = withScope) {
71 | return restoreSingle(ops, w)
72 | }
73 |
74 | function jsoToWxon(obj) {
75 | //convert JS Object to WeChat Object Notation(No quotes@key+str)
76 | let ans = ''
77 | if (typeof obj === 'undefined') {
78 | return 'undefined'
79 | } else if (obj === null) {
80 | return 'null'
81 | } else if (obj instanceof RegExp) {
82 | return obj.toString()
83 | } else if (obj instanceof Array) {
84 | for (let i = 0; i < obj.length; i++) ans += ',' + jsoToWxon(obj[i])
85 | return enBrace(ans.slice(1), '[')
86 | } else if (typeof obj == 'object') {
87 | for (const k in obj) ans += ',' + k + ':' + jsoToWxon(obj[k])
88 | return enBrace(ans.slice(1), '{')
89 | } else if (typeof obj == 'string') {
90 | const parts = obj.split('"'),
91 | ret = []
92 | for (const part of parts) {
93 | const atoms = part.split("'"),
94 | ans = []
95 | for (const atom of atoms) ans.push(JSON.stringify(atom).slice(1, -1))
96 | ret.push(ans.join("\\'"))
97 | }
98 | return "'" + ret.join('"') + "'"
99 | } else return JSON.stringify(obj)
100 | }
101 |
102 | const op = ops[0]
103 | if (typeof op != 'object') {
104 | switch (op) {
105 | case 3: //string
106 | return ops[1] //may cause problems if wx use it to be string
107 | case 1: //direct value
108 | return scope(jsoToWxon(ops[1]))
109 | case 11: //values list, According to var a = 11;
110 | // eslint-disable-next-line no-case-declarations
111 | let ans = ''
112 | ops.shift()
113 | for (const perOp of ops) ans += restoreNext(perOp)
114 | return ans
115 | }
116 | } else {
117 | let ans: any = ''
118 | switch (
119 | op[0] //vop
120 | ) {
121 | case 2: {
122 | //arithmetic operator
123 | const getPrior = (op, len) => {
124 | const priorList = {
125 | '?:': 4,
126 | '&&': 6,
127 | '||': 5,
128 | '+': 13,
129 | '*': 14,
130 | '/': 14,
131 | '%': 14,
132 | '|': 7,
133 | '^': 8,
134 | '&': 9,
135 | '!': 16,
136 | '~': 16,
137 | '===': 10,
138 | '==': 10,
139 | '!=': 10,
140 | '!==': 10,
141 | '>=': 11,
142 | '<=': 11,
143 | '>': 11,
144 | '<': 11,
145 | '<<': 12,
146 | '>>': 12,
147 | '-': len == 3 ? 13 : 16,
148 | }
149 | return priorList[op] ? priorList[op] : 0
150 | }
151 |
152 | const getOp = (i) => {
153 | let ret = restoreNext(ops[i], true)
154 | if (ops[i] instanceof Object && typeof ops[i][0] == 'object' && ops[i][0][0] == 2) {
155 | //Add brackets if we need
156 | if (getPrior(op[1], ops.length) > getPrior(ops[i][0][1], ops[i].length)) ret = enBrace(ret, '(')
157 | }
158 | return ret
159 | }
160 |
161 | switch (op[1]) {
162 | case '?:':
163 | ans = getOp(1) + '?' + getOp(2) + ':' + getOp(3)
164 | break
165 | case '!':
166 | case '~':
167 | ans = op[1] + getOp(1)
168 | break
169 | case '-':
170 | if (ops.length != 3) {
171 | ans = op[1] + getOp(1)
172 | break
173 | } //shoud not add more in there![fall through]
174 | default:
175 | ans = getOp(1) + op[1] + getOp(2)
176 | }
177 | break
178 | }
179 | case 4: //unknown-arrayStart?
180 | ans = restoreNext(ops[1], true)
181 | break
182 | case 5: {
183 | //merge-array
184 | switch (ops.length) {
185 | case 2:
186 | ans = enBrace(restoreNext(ops[1], true), '[')
187 | break
188 | case 1:
189 | ans = '[]'
190 | break
191 | default: {
192 | const a = restoreNext(ops[1], true)
193 | if (a.startsWith('[') && a.endsWith(']')) {
194 | if (a != '[]') {
195 | ans = enBrace(a.slice(1, -1).trim() + ',' + restoreNext(ops[2], true), '[')
196 | } else {
197 | ans = enBrace(restoreNext(ops[2], true), '[')
198 | }
199 | } else {
200 | ans = enBrace('...' + a + ',' + restoreNext(ops[2], true), '[') //may/must not support in fact
201 | }
202 | }
203 | }
204 | break
205 | }
206 | case 6: {
207 | //get value of an object
208 | const sonName = restoreNext(ops[2], true)
209 | if (sonName._type === 'var') ans = restoreNext(ops[1], true) + enBrace(sonName, '[')
210 | else {
211 | let attach = ''
212 | if (/^[A-Za-z_][A-Za-z\d_]*$/.test(sonName) /*is a qualified id*/) attach = '.' + sonName
213 | else attach = enBrace(sonName, '[')
214 | ans = restoreNext(ops[1], true) + attach
215 | }
216 | break
217 | }
218 | case 7: {
219 | //get value of str
220 | switch (ops[1][0]) {
221 | case 11:
222 | ans = enBrace('__unTestedGetValue:' + enBrace(jsoToWxon(ops), '['), '{')
223 | break
224 | case 3:
225 | ans = new String(ops[1][1])
226 | ans._type = 'var'
227 | break
228 | default:
229 | throw Error('Unknown type to get value')
230 | }
231 | break
232 | }
233 | case 8: //first object
234 | ans = enBrace(ops[1] + ':' + restoreNext(ops[2], true), '{') //ops[1] have only this way to define
235 | break
236 | case 9: {
237 | //object
238 | const type = (x) => {
239 | if (x.startsWith('...')) return 1
240 | if (x.startsWith('{') && x.endsWith('}')) return 0
241 | return 2
242 | }
243 |
244 | let a = restoreNext(ops[1], true)
245 | let b = restoreNext(ops[2], true)
246 | const xa = type(a),
247 | xb = type(b)
248 | if (xa == 2 || xb == 2) ans = enBrace('__unkownMerge:' + enBrace(a + ',' + b, '['), '{')
249 | else {
250 | if (!xa) a = a.slice(1, -1).trim()
251 | if (!xb) b = b.slice(1, -1).trim()
252 | ans = enBrace(a + ',' + b, '{')
253 | }
254 | break
255 | }
256 | case 10: //...object
257 | ans = '...' + restoreNext(ops[1], true)
258 | break
259 | case 12: {
260 | const arr = restoreNext(ops[2], true)
261 | if (arr.startsWith('[') && arr.endsWith(']')) {
262 | ans = restoreNext(ops[1], true) + enBrace(arr.slice(1, -1).trim(), '(')
263 | } else {
264 | ans = restoreNext(ops[1], true) + '.apply' + enBrace('null,' + arr, '(')
265 | }
266 | break
267 | }
268 | default:
269 | ans = enBrace('__unkownSpecific:' + jsoToWxon(ops), '{')
270 | }
271 | return scope(ans)
272 | }
273 | }
274 |
275 | export function restoreGroup(z) {
276 | const ans = {}
277 | for (const g in z.mul) {
278 | const singleAns = []
279 | for (const e of z.mul[g]) singleAns.push(restoreSingle(e, false))
280 | ans[g] = singleAns
281 | }
282 | const ret: any = {} //Keep a null array for remaining global Z array.
283 | ret.mul = ans
284 | return ret
285 | }
286 |
287 | function restoreAll(z) {
288 | if (z.mul) return restoreGroup(z)
289 | const ans = []
290 | for (const e of z) ans.push(restoreSingle(e, false))
291 | return ans
292 | }
293 |
294 | export async function parserZArray(code) {
295 | return new Promise((resolve, reject) => {
296 | try {
297 | catchZ(code, (z) => resolve(restoreAll(z)))
298 | } catch (e) {
299 | reject(Error('GetZArray fail: ' + e.message))
300 | }
301 | })
302 | }
303 |
304 | export function parseZArrayFromCode(code: string): unknown[] {
305 | const z = []
306 | new VM({ sandbox: { z } }).run(code)
307 | return z
308 | }
309 |
--------------------------------------------------------------------------------
/src/core/wxapkg/wxml-parser/utils.ts:
--------------------------------------------------------------------------------
1 | export function removeInvalidLineCode(code) {
2 | const invalidRe = /\s*[a-z]\x20?=\x20?VM2_INTERNAL_STATE_DO_NOT_USE_OR_PROGRAM_WILL_FAIL\.handleException\([a-z]\);?/g
3 | return code.replace(invalidRe, '')
4 | }
5 | export function toDir(to, from) {
6 | //get relative path without posix/win32 problem
7 | if (from[0] == '.') from = from.slice(1)
8 | if (to[0] == '.') to = to.slice(1)
9 | from = from.replace(/\\/g, '/')
10 | to = to.replace(/\\/g, '/')
11 | let a = Math.min(to.length, from.length)
12 | for (let i = 1, m = Math.min(to.length, from.length); i <= m; i++)
13 | if (!to.startsWith(from.slice(0, i))) {
14 | a = i - 1
15 | break
16 | }
17 | const pub = from.slice(0, a)
18 | const len = pub.lastIndexOf('/') + 1
19 | const k = from.slice(len)
20 | let ret = ''
21 | for (let i = 0; i < k.length; i++) if (k[i] == '/') ret += '../'
22 | return ret + to.slice(len)
23 | }
24 | export function getZArrayKey(functionName) {
25 | const match = functionName.match(/_\d+$/)
26 | return match ? match[0] : ''
27 | }
28 |
--------------------------------------------------------------------------------
/src/enum/PackageSuffix.ts:
--------------------------------------------------------------------------------
1 | // 包的文件名后缀
2 | export enum PackageSuffix {
3 | WXAPKG = 'wxapkg',
4 | }
5 |
--------------------------------------------------------------------------------
/src/index.ts:
--------------------------------------------------------------------------------
1 | import { clearConsole } from '@utils/clearConsole'
2 | import { registerGlobalException } from '@utils/exceptions'
3 | import { initializeConfig, getConfig } from '@baseController/ConfigController'
4 | import { getConfigurator } from '@utils/getConfigurator'
5 | import { invokeWxapkg } from '@core/wxapkg'
6 | ;(async () => {
7 | initializeConfig(getConfigurator())
8 | getConfig('logLevel') === 'debug' && clearConsole()
9 | registerGlobalException()
10 | await invokeWxapkg()
11 | })()
12 |
--------------------------------------------------------------------------------
/src/utils/ast.ts:
--------------------------------------------------------------------------------
1 | import * as babel from '@babel/core'
2 | import { traverse, Visitor, BabelFileResult } from '@babel/core'
3 | import { TraverseOptions } from '@babel/traverse'
4 | import { isProduciblePath, PathController, ProduciblePath } from '@baseController/PathController'
5 | import { error } from '@utils/colors'
6 |
7 | export async function buildAST(path: ProduciblePath): Promise
8 | export async function buildAST(code: string, filename: string): Promise
9 |
10 | export async function buildAST(v: ProduciblePath | string, filename?: string): Promise {
11 | let code = v as string
12 | if (!filename) {
13 | const pCtrl = PathController.make(v as ProduciblePath)
14 | filename = pCtrl.abspath
15 | code = await pCtrl.read('utf8')
16 | }
17 | const ast = await babel.parseAsync(code, { sourceFileName: filename, sourceType: 'script' })
18 | return new babel['File']({ filename }, { ast, code })
19 | }
20 |
21 | export type BuildParams = { code: string; filename?: string }
22 |
23 | export async function traverseAST(path: ProduciblePath, opt?: TraverseOptions): Promise
24 | export async function traverseAST(builder: BuildParams, opt?: TraverseOptions): Promise
25 | export async function traverseAST(file: BabelFileResult, opt?: TraverseOptions): Promise
26 | export async function traverseAST(
27 | v: ProduciblePath | BuildParams | BabelFileResult,
28 | opt?: TraverseOptions,
29 | ): Promise {
30 | if (isProduciblePath(v)) {
31 | const file = await buildAST(v)
32 | return traverse(file.ast, opt)
33 | }
34 | if (typeof v === 'object' && v['code'] && (v['filename'] = v['filename'] || '.')) {
35 | const file = await buildAST(v['code'], v['filename'])
36 | return traverse(file.ast, opt)
37 | }
38 | return traverse((v as BabelFileResult).ast, opt)
39 | }
40 | export { Visitor }
41 |
42 | export function parseJSONFromJSCode(code: string, context?: object) {
43 | // 防止恶意代码
44 | const file = new babel['File']({ filename: '.' }, { ast: babel.parseSync(code, { sourceType: 'script' }), code })
45 | traverse(file.ast, {
46 | CallExpression(path) {
47 | throw Error(`This code snippet is not safe: ${error(path.getSource())}`)
48 | },
49 | AssignmentExpression(path) {
50 | throw Error(`This code snippet is not safe: ${error(path.getSource())}`)
51 | },
52 | })
53 | const fn = Function('context', `with(context){return JSON.stringify(${code})}`)
54 | try {
55 | return JSON.parse(fn({ JSON, ...context }))
56 | } catch (e) {
57 | console.log(fn.toString())
58 | }
59 | }
60 |
--------------------------------------------------------------------------------
/src/utils/classes/Saver.ts:
--------------------------------------------------------------------------------
1 | import { PathController, ProduciblePath } from '@baseController/PathController'
2 | import { getSaveController, SaveAble, SaveController } from '@baseController/SaveController'
3 | import { BaseLogger } from '@utils/logger'
4 | import { BaseError } from '@utils/exceptions'
5 | import { isWorkerRuntime } from '@utils/isWorkerRuntime'
6 |
7 | export class SavingError extends BaseError {}
8 | interface SaverItem {
9 | path: ProduciblePath
10 | buffer: SaveAble
11 | }
12 | export class Saver extends BaseLogger {
13 | private baseDir: PathController
14 | private saveList: SaverItem[]
15 | private readonly saveCtrl: SaveController
16 | constructor(baseDir?: ProduciblePath) {
17 | if (isWorkerRuntime()) throw Error(`Saver cannot run on Worker!`)
18 | super()
19 | this.saveList = []
20 | this.saveDirectory = baseDir
21 | this.saveCtrl = getSaveController()
22 | }
23 | set saveDirectory(dir: ProduciblePath) {
24 | this.baseDir = PathController.make(dir)
25 | }
26 | get saveDirectory(): PathController {
27 | return this.baseDir
28 | }
29 |
30 | add(path: ProduciblePath, buffer: SaveAble, force?: boolean): this {
31 | const ctrl = PathController.make(path)
32 | if (ctrl.isAbs) {
33 | this.saveCtrl.set(ctrl.path, buffer)
34 | } else if (force) {
35 | this.saveCtrl.set(ctrl.abspath, buffer)
36 | } else {
37 | this.saveList.push({ path, buffer })
38 | }
39 | return this
40 | }
41 | /**
42 | * @desc 合并到全局桶内
43 | * @description 为什么不直接放到桶内?
44 | * 因为 baseDir 会变化,
45 | * 需要重新计算最终路径
46 | * */
47 | merge(): this {
48 | this.saveList.forEach((item) => {
49 | const { path, buffer } = item
50 | const pCtrl = PathController.make(path)
51 | let target = pCtrl
52 | if (!pCtrl.isAbs) {
53 | if (!this.baseDir) SavingError.throw(`BaseDir is not a directory!`)
54 | target = this.baseDir.join(pCtrl.path)
55 | }
56 | this.saveCtrl.set(target.abspath, buffer)
57 | })
58 | return this
59 | }
60 | }
61 |
--------------------------------------------------------------------------------
/src/utils/clearConsole.ts:
--------------------------------------------------------------------------------
1 | export function clearConsole(toStart?: boolean): void {
2 | process.stdout.write('\u001b[2J')
3 | process.stdout.write('\u001b[1;1H')
4 | toStart && process.stdout.write('\u001b[3J')
5 | }
6 |
--------------------------------------------------------------------------------
/src/utils/colors.ts:
--------------------------------------------------------------------------------
1 | import chalk from 'chalk'
2 | export const info = chalk.blue.bold
3 | export const error = chalk.white.bgRed
4 | export const grey = chalk.grey.bold
5 | export const link = chalk.underline
6 | export const bold = chalk.bold
7 | export const red = chalk.red
8 | export const yellow = chalk.yellow
9 | export const green = chalk.green
10 |
--------------------------------------------------------------------------------
/src/utils/crypto.ts:
--------------------------------------------------------------------------------
1 | import * as CryptoJS from 'crypto-js'
2 |
3 | export function BufferToWordArray(buffer: Buffer): CryptoJS.lib.WordArray {
4 | return CryptoJS.lib.WordArray.create(buffer as unknown as number[], buffer.length)
5 | }
6 |
7 | export function WordArrayToBuffer(wordArray: CryptoJS.lib.WordArray): Buffer {
8 | return Buffer.from(wordArray.toString(CryptoJS.enc.Hex), 'hex')
9 | }
10 |
11 | export function encryptBuffer(buffer: Buffer, password: string, salt: string, iv: string): Buffer {
12 | if (buffer.length % 32 !== 0) throw Error('Invalid buffer Length: ' + buffer.length)
13 | const key = CryptoJS.PBKDF2(password, salt, {
14 | keySize: 256 / 32,
15 | iterations: 1000,
16 | hasher: CryptoJS.algo.SHA1,
17 | })
18 | const cipher = CryptoJS.AES.encrypt(BufferToWordArray(buffer), key, {
19 | iv: CryptoJS.enc.Utf8.parse(iv),
20 | mode: CryptoJS.mode.CBC,
21 | padding: CryptoJS.pad.NoPadding,
22 | })
23 | return WordArrayToBuffer(cipher.ciphertext)
24 | }
25 |
26 | export function decryptBuffer(buffer: Buffer, password: string, salt: string, iv: string): Buffer {
27 | if (buffer.length % 32 !== 0) throw Error('Invalid buffer Length: ' + buffer.length)
28 | const key = CryptoJS.PBKDF2(password, salt, {
29 | keySize: 256 / 32,
30 | iterations: 1000,
31 | hasher: CryptoJS.algo.SHA1,
32 | })
33 | const cipher = CryptoJS.AES.decrypt(BufferToWordArray(buffer).toString(CryptoJS.enc.Base64), key, {
34 | iv: CryptoJS.enc.Utf8.parse(iv),
35 | mode: CryptoJS.mode.CBC,
36 | padding: CryptoJS.pad.NoPadding,
37 | })
38 | return WordArrayToBuffer(cipher)
39 | }
40 | export function md5(b64Str: string, fromBase64: true): string
41 | export function md5(buffer: Buffer): string
42 | export function md5(message: string): string
43 | export function md5(_message: string | Buffer | CryptoJS.lib.WordArray, fromBase64?: boolean): string {
44 | let message: string | CryptoJS.lib.WordArray
45 | if (typeof _message === 'string' && fromBase64) {
46 | message = CryptoJS.enc.Base64.parse(_message)
47 | } else if (_message instanceof Buffer) {
48 | message = BufferToWordArray(_message)
49 | } else message = _message
50 | return CryptoJS.MD5(message).toString(CryptoJS.enc.Hex)
51 | }
52 |
--------------------------------------------------------------------------------
/src/utils/deepCopy.ts:
--------------------------------------------------------------------------------
1 | import { hasOwnProperty } from '@utils/hasOwnProperty'
2 |
3 | type UnknownObject = Record
4 |
5 | export function deepCopy(obj: unknown): unknown {
6 | // 处理非对象和特殊对象的情况
7 | if (obj === null || typeof obj !== 'object') {
8 | return obj
9 | }
10 |
11 | // 处理日期对象
12 | if (obj instanceof Date) {
13 | const _copy = new Date()
14 | _copy.setTime(obj.getTime())
15 | return _copy
16 | }
17 |
18 | // 处理数组对象
19 | if (obj instanceof Array) {
20 | const copy: unknown[] = []
21 | for (let i = 0, len = obj.length; i < len; i++) {
22 | copy[i] = deepCopy(obj[i])
23 | }
24 | return copy
25 | }
26 |
27 | // 处理普通对象
28 | if (obj instanceof Object) {
29 | const copy: UnknownObject = {}
30 | const _object = obj as UnknownObject
31 | for (const key in _object) {
32 | if (hasOwnProperty(_object, key)) {
33 | copy[key] = deepCopy(_object[key])
34 | }
35 | }
36 | return copy
37 | }
38 |
39 | throw new Error("Unable to copy obj! Its type isn't supported.")
40 | }
41 |
--------------------------------------------------------------------------------
/src/utils/exceptions.ts:
--------------------------------------------------------------------------------
1 | import { BaseLogger } from '@utils/logger'
2 |
3 | class GlobalExceptionCaught extends BaseLogger {
4 | constructor() {
5 | super('Exception')
6 | const ignores = 'exit,cancel,pass'.split(',')
7 | const handler = (e: Error | string) => {
8 | !ignores.includes(String(e)) && this.logger.error(e)
9 | process.exit(1)
10 | }
11 | process.on('uncaughtException', handler)
12 | process.on('unhandledRejection', handler)
13 | this.logger.debug('Global exception interception is enabled')
14 | }
15 | }
16 |
17 | export function registerGlobalException() {
18 | return new GlobalExceptionCaught()
19 | }
20 |
21 | export class BaseError extends Error {
22 | constructor(msg: string) {
23 | super(msg)
24 | this.name = this.constructor.name
25 | Error.captureStackTrace && Error.captureStackTrace(this, this.constructor)
26 | }
27 |
28 | static make(msg: string) {
29 | return new this(msg)
30 | }
31 |
32 | static throw(msg: string) {
33 | throw this.make(msg)
34 | }
35 | }
36 |
--------------------------------------------------------------------------------
/src/utils/getConfigurator.ts:
--------------------------------------------------------------------------------
1 | import { isDevelopment } from '@utils/isDev'
2 | import { CliConfigurator, registerCommand } from '@/cli'
3 | import { version, name } from '../../package.json'
4 |
5 | export function getConfigurator(dev?: boolean): CliConfigurator {
6 | const IS_DEV = dev || isDevelopment()
7 | if (!IS_DEV) return registerCommand(version, name)
8 | return {
9 | global: {
10 | logLevel: 'info',
11 | },
12 | wx: {
13 | // appid: '',
14 | format: false,
15 | clearDecompile: true,
16 | clearSave: true,
17 | parse: false,
18 | depth: 1,
19 | // output: '',
20 | packages: ['files'],
21 | },
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/src/utils/hasOwnProperty.ts:
--------------------------------------------------------------------------------
1 | export function hasOwnProperty(o: T, name: keyof T): boolean {
2 | return Object.prototype.hasOwnProperty.call(o, name)
3 | }
4 |
--------------------------------------------------------------------------------
/src/utils/isDev.ts:
--------------------------------------------------------------------------------
1 | import { PathController } from '@baseController/PathController'
2 | export function isDevelopment() {
3 | return PathController.make(process.argv[1]).suffixWithout === 'ts'
4 | }
5 |
--------------------------------------------------------------------------------
/src/utils/isWorkerRuntime.ts:
--------------------------------------------------------------------------------
1 | import { isMainThread } from 'worker_threads'
2 |
3 | export function isWorkerRuntime(): boolean {
4 | return !isMainThread
5 | }
6 |
--------------------------------------------------------------------------------
/src/utils/logger.ts:
--------------------------------------------------------------------------------
1 | import { bold, grey, yellow } from '@utils/colors'
2 | import { createLogger, format, Logger, transports } from 'winston'
3 | import { getConfig } from '@baseController/ConfigController'
4 |
5 | const { combine, timestamp, printf, colorize } = format
6 | const levels = { error: 0, warn: 1, info: 2, debug: 3 }
7 |
8 | export type LoggerLevel = keyof typeof levels
9 | export function getLogger(name?: string, level?: LoggerLevel): Logger {
10 | return createLogger({
11 | level: level || getConfig('logLevel'),
12 | levels,
13 | format: combine(
14 | timestamp({ format: 'HH:mm:ss' }),
15 | printf((info) => {
16 | const LEVEL = `[${bold(info.level.toUpperCase())}]`
17 | const TIME = grey(info.timestamp)
18 | const SCOPE = yellow(`<${info.scope}>`)
19 | const MESSAGE = ((m) => {
20 | if (m instanceof Error) return m.stack
21 | return m.message
22 | })(info)
23 | return [LEVEL, TIME, SCOPE, MESSAGE].join(' ')
24 | }),
25 | colorize({ all: true }),
26 | ),
27 | defaultMeta: { scope: name || 'Core' },
28 | transports: [new transports.Console({ stderrLevels: ['error'] })],
29 | })
30 | }
31 | export class BaseLogger {
32 | readonly logger: Logger
33 | constructor(name?: string, level?: LoggerLevel) {
34 | name = name || this.constructor.name
35 | this.logger = getLogger(name.length < 4 ? void 0 : name, level)
36 | }
37 | }
38 |
--------------------------------------------------------------------------------
/src/utils/matchScripts.ts:
--------------------------------------------------------------------------------
1 | export function matchScripts(source: string): string {
2 | const matchRegex = /