uniapp-android-cli 0.0.0-stage → 0.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +382 -2
  3. package/bin/uni-pack.js +7 -0
  4. package/package.json +66 -4
  5. package/src/cli.js +242 -0
  6. package/src/commands/build.js +46 -0
  7. package/src/commands/debug.js +183 -0
  8. package/src/commands/device.js +309 -0
  9. package/src/commands/devices.js +23 -0
  10. package/src/commands/doctor.js +170 -0
  11. package/src/commands/init.js +488 -0
  12. package/src/commands/projects.js +31 -0
  13. package/src/commands/wgt.js +90 -0
  14. package/src/core/adb.js +292 -0
  15. package/src/core/build.js +438 -0
  16. package/src/core/config.js +208 -0
  17. package/src/core/debugPreset.js +56 -0
  18. package/src/core/devicePairing.js +153 -0
  19. package/src/core/errors.js +36 -0
  20. package/src/core/fsx.js +183 -0
  21. package/src/core/gradle.js +221 -0
  22. package/src/core/gradleLog.js +188 -0
  23. package/src/core/hash.js +18 -0
  24. package/src/core/hbuilderx.js +260 -0
  25. package/src/core/hbuilderxCli.js +168 -0
  26. package/src/core/initConfig.js +214 -0
  27. package/src/core/initEnv.js +140 -0
  28. package/src/core/interactive.js +93 -0
  29. package/src/core/logger.js +82 -0
  30. package/src/core/output.js +181 -0
  31. package/src/core/patch/assets.js +154 -0
  32. package/src/core/patch/gradle.js +166 -0
  33. package/src/core/patch/manifest.js +81 -0
  34. package/src/core/patch/nativePlugins.js +137 -0
  35. package/src/core/patch/projectManifest.js +66 -0
  36. package/src/core/patch/template.js +75 -0
  37. package/src/core/patch/utsPlugins.js +425 -0
  38. package/src/core/process.js +120 -0
  39. package/src/core/project.js +263 -0
  40. package/src/core/qrcode.js +13 -0
  41. package/src/core/resourceVersion.js +87 -0
  42. package/src/core/sdk.js +403 -0
  43. package/src/core/signing.js +102 -0
  44. package/src/core/templateCache.js +81 -0
  45. package/src/core/version.js +128 -0
  46. package/src/core/webBuild.js +77 -0
  47. package/src/core/wgt.js +98 -0
  48. package/src/core/workdir.js +44 -0
@@ -0,0 +1,214 @@
1
+ import { existsSync } from 'node:fs'
2
+ import path from 'node:path'
3
+
4
+ /**
5
+ * @typedef {{ ok: boolean, value?: string, message?: string }} Validation
6
+ */
7
+
8
+ const PACKAGE_RE = /^[a-z][a-z0-9_]*(\.[a-z0-9_]+)+$/i
9
+ const APPKEY_RE = /^[0-9a-f]{32}$/i
10
+
11
+ /**
12
+ * 空值表示「跳过」,交给构建期报错;交互时允许先不填。
13
+ * @param {string} value
14
+ * @returns {Validation}
15
+ */
16
+ export function validatePackageName(value) {
17
+ if (!value) {
18
+ return { ok: true, value: '' }
19
+ }
20
+ if (!PACKAGE_RE.test(value)) {
21
+ return { ok: false, message: '包名不合法,示例:uni.app.UNIF1A8702' }
22
+ }
23
+ return { ok: true, value }
24
+ }
25
+
26
+ /**
27
+ * @param {string} value
28
+ * @returns {Validation}
29
+ */
30
+ export function validateAppKey(value) {
31
+ if (!value) {
32
+ return { ok: true, value: '' }
33
+ }
34
+ if (!APPKEY_RE.test(value)) {
35
+ return { ok: false, message: 'AppKey 应为 32 位十六进制(0-9a-f)' }
36
+ }
37
+ return { ok: true, value: value.toLowerCase() }
38
+ }
39
+
40
+ /**
41
+ * 文件路径允许相对项目目录;不存在则重新询问。
42
+ * @param {string} projectDir
43
+ * @returns {(value: string) => Validation}
44
+ */
45
+ export function makeFileValidator(projectDir) {
46
+ return (value) => {
47
+ if (!value) {
48
+ return { ok: true, value: '' }
49
+ }
50
+ const resolved = path.isAbsolute(value) ? value : path.resolve(projectDir, value)
51
+ if (!existsSync(resolved)) {
52
+ return { ok: false, message: `找不到文件:${resolved}` }
53
+ }
54
+ return { ok: true, value: resolved }
55
+ }
56
+ }
57
+
58
+ /**
59
+ * @param {string} value
60
+ * @returns {Validation}
61
+ */
62
+ export function validateRequired(value) {
63
+ return value ? { ok: true, value } : { ok: false, message: '不能为空' }
64
+ }
65
+
66
+ /**
67
+ * @param {string} value
68
+ * @returns {Validation}
69
+ */
70
+ export function validateConfirm(value) {
71
+ if (!value || /^y(es)?$/i.test(value) || /^n(o)?$/i.test(value)) {
72
+ return { ok: true, value: value.toLowerCase() }
73
+ }
74
+ return { ok: false, message: '输入 Y 或 n' }
75
+ }
76
+
77
+ /**
78
+ * 最终确认必须显式回答:回车不默认同意,避免手快直接写配置。
79
+ * @param {string} value
80
+ * @returns {Validation}
81
+ */
82
+ export function validateExplicitConfirm(value) {
83
+ if (/^y(es)?$/i.test(value) || /^n(o)?$/i.test(value)) {
84
+ return { ok: true, value: value.toLowerCase() }
85
+ }
86
+ return { ok: false, message: '请输入 y 或 n(回车不会默认确认)' }
87
+ }
88
+
89
+ /**
90
+ * @param {string} value
91
+ * @returns {Validation}
92
+ */
93
+ export function validateCustomType(value) {
94
+ const text = String(value ?? '').trim().toLowerCase()
95
+ if (text === 'local' || text === 'device') {
96
+ return { ok: true, value: text }
97
+ }
98
+ return { ok: false, message: '输入 local 或 device' }
99
+ }
100
+
101
+ /**
102
+ * @param {string} value
103
+ * @returns {Validation}
104
+ */
105
+ export function validatePlayground(value) {
106
+ const text = String(value ?? '').trim().toLowerCase()
107
+ if (text === 'standard' || text === 'custom') {
108
+ return { ok: true, value: text }
109
+ }
110
+ return { ok: false, message: '输入 standard 或 custom' }
111
+ }
112
+
113
+ /**
114
+ * 项目内路径尽量写成相对路径,方便提交到仓库;项目外保留绝对路径。
115
+ * @param {string} projectDir
116
+ * @param {string} value
117
+ * @returns {string}
118
+ */
119
+ export function toProjectRelative(projectDir, value) {
120
+ const text = String(value ?? '').trim()
121
+ if (!text) {
122
+ return ''
123
+ }
124
+ const absolute = path.isAbsolute(text) ? text : path.resolve(projectDir, text)
125
+ const relative = path.relative(projectDir, absolute)
126
+ if (relative && !relative.startsWith('..') && !path.isAbsolute(relative)) {
127
+ return relative.split(path.sep).join('/')
128
+ }
129
+ return absolute
130
+ }
131
+
132
+ const PROJECT_ONLY_USER_FIELDS = ['appKey', 'package', 'signing', 'webBuild', 'outputDir', 'outputPrefix', 'debug']
133
+
134
+ // 版本/包名等以 manifest 为准,不写进任何配置,避免旧快照覆盖项目改动
135
+ const SNAPSHOT_FIELDS = ['name', 'appid', 'versionName', 'versionCode', 'minSdkVersion', 'targetSdkVersion', 'abiFilters']
136
+
137
+ /**
138
+ * 把 init 的结果拆成「项目级共享配置」与「本机用户配置」:
139
+ * - 项目配置:包名、AppKey、签名路径、输出目录、webBuild,可提交到仓库;
140
+ * - 用户配置:projectDir / type / sdkRoot / hbuilderxRoot 等本机路径;
141
+ * - 密码永远不写入任何配置。
142
+ * @param {Object} input
143
+ * @param {string} input.projectDir
144
+ * @param {'cli' | 'hbuilderx'} input.type
145
+ * @param {string} input.packageName
146
+ * @param {string} input.appKey
147
+ * @param {string} input.outputDir
148
+ * @param {string} [input.outputPrefix]
149
+ * @param {any} [input.webBuild]
150
+ * @param {{ keystore: string, keyAlias: string, keystoreProperties: string,
151
+ * storePasswordEnv?: string, keyPasswordEnv?: string }} input.signing
152
+ * @param {any} [input.existingProjectConfig]
153
+ * @param {any} [input.existingUserEntry]
154
+ * @param {Record<string, any>} [input.debug]
155
+ * @param {string} input.sdkRoot
156
+ * @param {string} [input.hbuilderxRoot]
157
+ * @returns {{ projectConfig: Record<string, any>, userEntry: Record<string, any> }}
158
+ */
159
+ export function splitInitConfig(input) {
160
+ const existingProject = input.existingProjectConfig ?? {}
161
+ const existingUser = input.existingUserEntry ?? {}
162
+ /** @type {Record<string, any>} */
163
+ const projectConfig = { ...existingProject }
164
+ for (const field of ['appid', 'name', 'versionName', 'versionCode', 'minSdkVersion', 'targetSdkVersion', 'abiFilters']) {
165
+ delete projectConfig[field]
166
+ }
167
+ projectConfig.type = input.type
168
+ if (input.packageName) {
169
+ projectConfig.package = input.packageName
170
+ } else {
171
+ delete projectConfig.package
172
+ }
173
+ if (input.appKey) {
174
+ projectConfig.appKey = input.appKey
175
+ } else {
176
+ delete projectConfig.appKey
177
+ }
178
+ projectConfig.outputDir = toProjectRelative(input.projectDir, input.outputDir) || 'apk'
179
+ if (input.outputPrefix) {
180
+ projectConfig.outputPrefix = input.outputPrefix
181
+ }
182
+ if (input.webBuild) {
183
+ projectConfig.webBuild = input.webBuild
184
+ }
185
+ const debug = {
186
+ ...(existingProject.debug ?? existingUser.debug ?? {}),
187
+ ...(input.debug ?? {}),
188
+ }
189
+ if (Object.keys(debug).length > 0) {
190
+ projectConfig.debug = debug
191
+ }
192
+ projectConfig.signing = {
193
+ ...(existingProject.signing ?? existingUser.signing ?? {}),
194
+ keystore: toProjectRelative(input.projectDir, input.signing.keystore),
195
+ keyAlias: String(input.signing.keyAlias ?? ''),
196
+ keystoreProperties: toProjectRelative(input.projectDir, input.signing.keystoreProperties),
197
+ storePasswordEnv: input.signing.storePasswordEnv || 'UNI_PACK_STORE_PASS',
198
+ keyPasswordEnv: input.signing.keyPasswordEnv || 'UNI_PACK_KEY_PASS',
199
+ }
200
+
201
+ /** @type {Record<string, any>} */
202
+ const userEntry = {
203
+ ...existingUser,
204
+ projectDir: input.projectDir,
205
+ type: input.type,
206
+ sdkRoot: input.sdkRoot,
207
+ hbuilderxRoot: input.hbuilderxRoot ?? existingUser.hbuilderxRoot ?? '',
208
+ }
209
+ for (const field of [...PROJECT_ONLY_USER_FIELDS, ...SNAPSHOT_FIELDS]) {
210
+ delete userEntry[field]
211
+ }
212
+
213
+ return { projectConfig, userEntry }
214
+ }
@@ -0,0 +1,140 @@
1
+ import { existsSync } from 'node:fs'
2
+ import path from 'node:path'
3
+ import { validateConfirm } from './initConfig.js'
4
+ import { resolveSdkRootInput } from './sdk.js'
5
+
6
+ /**
7
+ * @typedef {{ ok: boolean, value?: string, message?: string }} EnvValidation
8
+ */
9
+
10
+ const EXE = process.platform === 'win32' ? '.exe' : ''
11
+
12
+ /**
13
+ * 离线 SDK 必须能解析到含 HBuilder-Integrate-AS 的目录(支持解压后多一层同名目录)。
14
+ * @returns {(value: string) => Promise<EnvValidation>}
15
+ */
16
+ export function makeSdkRootValidator() {
17
+ return async (value) => {
18
+ if (!value) {
19
+ return { ok: false, message: '离线 SDK 不能为空,请填写解压后的 Android-SDK@x.yy 目录' }
20
+ }
21
+ const root = await resolveSdkRootInput(value)
22
+ if (!root) {
23
+ return { ok: false, message: '该目录下没有 HBuilder-Integrate-AS,检查离线 SDK 路径' }
24
+ }
25
+ return { ok: true, value: root }
26
+ }
27
+ }
28
+
29
+ /**
30
+ * @returns {(value: string) => EnvValidation}
31
+ */
32
+ export function makeHbuilderxValidator() {
33
+ return (value) => {
34
+ if (!value) {
35
+ return { ok: true, value: '' }
36
+ }
37
+ const root = path.resolve(value)
38
+ const found = [root, path.join(root, 'HBuilderX')].some((candidate) =>
39
+ existsSync(path.join(candidate, 'plugins', 'about', 'package.json')),
40
+ )
41
+ if (!found) {
42
+ return { ok: false, message: '不是 HBuilderX 安装目录(缺少 plugins/about/package.json)' }
43
+ }
44
+ return { ok: true, value: root }
45
+ }
46
+ }
47
+
48
+ /**
49
+ * @returns {(value: string) => EnvValidation}
50
+ */
51
+ export function makeAndroidSdkValidator() {
52
+ return (value) => {
53
+ if (!value) {
54
+ return { ok: true, value: '' }
55
+ }
56
+ const root = path.resolve(value)
57
+ const adb = path.join(root, 'platform-tools', `adb${EXE}`)
58
+ const buildTools = path.join(root, 'build-tools')
59
+ if (!existsSync(adb) || !existsSync(buildTools)) {
60
+ return { ok: false, message: 'Android SDK 下缺少 platform-tools/adb 或 build-tools' }
61
+ }
62
+ return { ok: true, value: root }
63
+ }
64
+ }
65
+
66
+ /**
67
+ * @returns {(value: string) => EnvValidation}
68
+ */
69
+ export function makeJdkValidator() {
70
+ return (value) => {
71
+ if (!value) {
72
+ return { ok: true, value: '' }
73
+ }
74
+ const root = path.resolve(value)
75
+ if (!existsSync(path.join(root, 'bin', `java${EXE}`))) {
76
+ return { ok: false, message: 'JDK 目录下缺少 bin/java,确认是 JDK 17+ 根目录' }
77
+ }
78
+ return { ok: true, value: root }
79
+ }
80
+ }
81
+
82
+ /**
83
+ * 机器级路径问答:路径缺失时强制补,已探测到则询问是否修改。
84
+ * @param {Object} options
85
+ * @param {{ ask: (options: any) => Promise<string> }} options.prompt
86
+ * @param {'cli' | 'hbuilderx'} options.type
87
+ * @param {import('./logger.js').Logger} options.logger
88
+ * @param {{ sdkPath: string, hbuilderxPath: string, androidSdkPath: string, jdkPath: string }} options.defaults
89
+ * @returns {Promise<{ sdkPath: string, hbuilderxPath: string, androidSdkPath: string, jdkPath: string }>}
90
+ */
91
+ export async function askEnvironmentPaths(options) {
92
+ const { prompt, type, logger } = options
93
+ let sdkPath = options.defaults.sdkPath || ''
94
+ let hbuilderxPath = options.defaults.hbuilderxPath || ''
95
+ let androidSdkPath = options.defaults.androidSdkPath || ''
96
+ let jdkPath = options.defaults.jdkPath || ''
97
+
98
+ const missingSdk = !sdkPath
99
+ const missingHbuilderx = type === 'hbuilderx' && !hbuilderxPath
100
+ logger.step('本机环境')
101
+ logger.info(`离线 SDK:${sdkPath || '(未找到)'}`)
102
+ if (type === 'hbuilderx') {
103
+ logger.info(`HBuilderX:${hbuilderxPath || '(未找到)'}`)
104
+ }
105
+ logger.info(`Android SDK:${androidSdkPath || '(未找到)'}`)
106
+ logger.info(`JDK:${jdkPath || '(未找到)'}`)
107
+
108
+ let editEnv = missingSdk || missingHbuilderx
109
+ if (!editEnv) {
110
+ const answer = await prompt.ask({ question: '要修改以上本机路径吗?[y/N]', validate: validateConfirm })
111
+ editEnv = /^y/.test(answer)
112
+ }
113
+ if (!editEnv) {
114
+ return { sdkPath, hbuilderxPath, androidSdkPath, jdkPath }
115
+ }
116
+
117
+ sdkPath = await prompt.ask({
118
+ question: '离线 SDK 根目录(含 HBuilder-Integrate-AS)',
119
+ defaultValue: sdkPath,
120
+ validate: makeSdkRootValidator(),
121
+ })
122
+ if (type === 'hbuilderx') {
123
+ hbuilderxPath = await prompt.ask({
124
+ question: 'HBuilderX 安装目录(留空跳过)',
125
+ defaultValue: hbuilderxPath,
126
+ validate: makeHbuilderxValidator(),
127
+ })
128
+ }
129
+ androidSdkPath = await prompt.ask({
130
+ question: 'Android SDK 根目录(留空自动探测)',
131
+ defaultValue: androidSdkPath,
132
+ validate: makeAndroidSdkValidator(),
133
+ })
134
+ jdkPath = await prompt.ask({
135
+ question: 'JDK 根目录(留空自动探测)',
136
+ defaultValue: jdkPath,
137
+ validate: makeJdkValidator(),
138
+ })
139
+ return { sdkPath, hbuilderxPath, androidSdkPath, jdkPath }
140
+ }
@@ -0,0 +1,93 @@
1
+ import { createInterface } from 'node:readline/promises'
2
+ import process from 'node:process'
3
+
4
+ /**
5
+ * @typedef {Object} PromptValidationResult
6
+ * @property {boolean} ok
7
+ * @property {string} [value]
8
+ * @property {string} [message]
9
+ * @typedef {(value: string) => PromptValidationResult | Promise<PromptValidationResult>} PromptValidator
10
+ * @typedef {{ question: string, defaultValue?: string, validate?: PromptValidator }} PromptOptions
11
+ */
12
+
13
+ /**
14
+ * 非交互环境(CI、管道、--json)不能停在问答上。
15
+ * @param {{ yes?: boolean, json?: boolean }} options
16
+ * @param {{ isTTY?: boolean }} [input]
17
+ * @param {Record<string, string | undefined>} [env]
18
+ * @returns {boolean}
19
+ */
20
+ export function canPrompt(options, input = process.stdin, env = process.env) {
21
+ if (options?.yes || options?.json) {
22
+ return false
23
+ }
24
+ if (env.UNI_PACK_NO_INPUT === '1') {
25
+ return false
26
+ }
27
+ return Boolean(/** @type {{ isTTY?: boolean }} */ (input).isTTY)
28
+ }
29
+
30
+ /**
31
+ * 简单的问答封装:回车用默认值,校验失败重新问,EOF/中断按默认值返回。
32
+ */
33
+ export class Prompt {
34
+ /**
35
+ * @param {{ input?: NodeJS.ReadableStream, output?: NodeJS.WritableStream, isTTY?: boolean }} [options]
36
+ */
37
+ constructor(options = {}) {
38
+ const input = options.input ?? process.stdin
39
+ const output = options.output ?? process.stdout
40
+ this.output = output
41
+ this.rl = createInterface({
42
+ input,
43
+ output,
44
+ terminal: options.isTTY ?? Boolean(/** @type {{ isTTY?: boolean }} */ (input).isTTY),
45
+ })
46
+ }
47
+
48
+ /**
49
+ * @param {PromptOptions} options
50
+ * @returns {Promise<string>}
51
+ */
52
+ async ask(options) {
53
+ const defaultValue = options.defaultValue ?? ''
54
+ const suffix = defaultValue ? `(${defaultValue})` : ''
55
+ for (;;) {
56
+ // 输入流被 Ctrl+D / 关闭时 question 可能永远不 resolve,和 close 事件赛跑
57
+ /** @type {(() => void) | null} */
58
+ let onClose = null
59
+ const closed = new Promise((resolve) => {
60
+ onClose = () => resolve(null)
61
+ this.rl.once('close', onClose)
62
+ })
63
+ let raw
64
+ try {
65
+ raw = await Promise.race([this.rl.question(`${options.question}${suffix}: `), closed])
66
+ } catch {
67
+ return defaultValue
68
+ } finally {
69
+ if (onClose) {
70
+ this.rl.removeListener('close', onClose)
71
+ }
72
+ }
73
+ if (raw === null) {
74
+ return defaultValue
75
+ }
76
+ const value = String(raw).trim() || defaultValue
77
+ if (!options.validate) {
78
+ return value
79
+ }
80
+ const result = await options.validate(value)
81
+ if (result.ok) {
82
+ return result.value ?? value
83
+ }
84
+ if (result.message) {
85
+ this.output.write(` ${result.message}\n`)
86
+ }
87
+ }
88
+ }
89
+
90
+ close() {
91
+ this.rl.close()
92
+ }
93
+ }
@@ -0,0 +1,82 @@
1
+ const SECRET_KEYS = /password|passwd|pwd|secret|token/i
2
+
3
+ /** @typedef {{ verbose: boolean, json: boolean }} LoggerOptions */
4
+
5
+ export class Logger {
6
+ /** @param {Partial<LoggerOptions>} [options] */
7
+ constructor(options = {}) {
8
+ this.verbose = Boolean(options.verbose)
9
+ this.json = Boolean(options.json)
10
+ }
11
+
12
+ /** @param {string} message */
13
+ step(message) {
14
+ if (!this.json) {
15
+ console.log(`\n▸ ${message}`)
16
+ }
17
+ }
18
+
19
+ /** @param {string} message */
20
+ info(message) {
21
+ if (!this.json) {
22
+ console.log(` ${message}`)
23
+ }
24
+ }
25
+
26
+ /** @param {string} message */
27
+ detail(message) {
28
+ if (!this.json && this.verbose) {
29
+ console.log(` ${message}`)
30
+ }
31
+ }
32
+
33
+ /** @param {string} message */
34
+ warn(message) {
35
+ if (!this.json) {
36
+ console.warn(` ! ${message}`)
37
+ }
38
+ }
39
+
40
+ /** @param {string} message */
41
+ success(message) {
42
+ if (!this.json) {
43
+ console.log(` ✓ ${message}`)
44
+ }
45
+ }
46
+
47
+ /**
48
+ * @param {unknown} value
49
+ * @param {unknown[]} [secrets]
50
+ */
51
+ redact(value, secrets = []) {
52
+ let text = typeof value === 'string' ? value : JSON.stringify(value)
53
+ for (const secret of secrets) {
54
+ if (typeof secret === 'string' && secret.length > 0) {
55
+ text = text.split(secret).join('***')
56
+ }
57
+ }
58
+ return text
59
+ }
60
+
61
+ /**
62
+ * @param {string} message
63
+ * @param {unknown} payload
64
+ */
65
+ output(message, payload) {
66
+ if (this.json) {
67
+ console.log(JSON.stringify({ message, ...(payload ?? {}) }, null, 2))
68
+ }
69
+ }
70
+ }
71
+
72
+ /**
73
+ * @param {Record<string, unknown>} object
74
+ */
75
+ export function redactObject(object) {
76
+ /** @type {Record<string, unknown>} */
77
+ const result = {}
78
+ for (const [key, value] of Object.entries(object)) {
79
+ result[key] = SECRET_KEYS.test(key) ? '***' : value
80
+ }
81
+ return result
82
+ }