uniapp-android-cli 0.0.0-stage → 0.1.0
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.
- package/LICENSE +21 -0
- package/README.md +595 -2
- package/bin/uni-pack.js +7 -0
- package/package.json +66 -4
- package/src/cli.js +184 -0
- package/src/commands/build.js +42 -0
- package/src/commands/debug.js +83 -0
- package/src/commands/device.js +303 -0
- package/src/commands/devices.js +23 -0
- package/src/commands/doctor.js +160 -0
- package/src/commands/init.js +277 -0
- package/src/commands/wgt.js +46 -0
- package/src/core/adb.js +234 -0
- package/src/core/build.js +374 -0
- package/src/core/config.js +157 -0
- package/src/core/devicePairing.js +152 -0
- package/src/core/errors.js +36 -0
- package/src/core/fsx.js +172 -0
- package/src/core/gradle.js +75 -0
- package/src/core/hbuilderx.js +258 -0
- package/src/core/logger.js +82 -0
- package/src/core/output.js +74 -0
- package/src/core/patch/assets.js +154 -0
- package/src/core/patch/gradle.js +128 -0
- package/src/core/patch/manifest.js +81 -0
- package/src/core/patch/nativePlugins.js +137 -0
- package/src/core/patch/projectManifest.js +66 -0
- package/src/core/patch/template.js +57 -0
- package/src/core/patch/utsPlugins.js +424 -0
- package/src/core/process.js +71 -0
- package/src/core/project.js +250 -0
- package/src/core/qrcode.js +13 -0
- package/src/core/sdk.js +398 -0
- package/src/core/signing.js +84 -0
- package/src/core/version.js +128 -0
- package/src/core/webBuild.js +69 -0
- package/src/core/wgt.js +76 -0
|
@@ -0,0 +1,258 @@
|
|
|
1
|
+
import os from 'node:os'
|
|
2
|
+
import path from 'node:path'
|
|
3
|
+
import { readdir } from 'node:fs/promises'
|
|
4
|
+
import { PackError, EXIT } from './errors.js'
|
|
5
|
+
import { exists, readJson } from './fsx.js'
|
|
6
|
+
import { run } from './process.js'
|
|
7
|
+
|
|
8
|
+
const VUE3_COMPILER = {
|
|
9
|
+
vueVersion: 3,
|
|
10
|
+
dir: path.join('plugins', 'uniapp-cli-vite'),
|
|
11
|
+
entry: path.join('node_modules', '@dcloudio', 'vite-plugin-uni', 'bin', 'uni.js'),
|
|
12
|
+
args: ['build', '-p', 'app'],
|
|
13
|
+
platform: 'app',
|
|
14
|
+
}
|
|
15
|
+
const VUE2_COMPILER = {
|
|
16
|
+
vueVersion: 2,
|
|
17
|
+
dir: path.join('plugins', 'uniapp-cli'),
|
|
18
|
+
entry: path.join('bin', 'uniapp-cli.js'),
|
|
19
|
+
args: [],
|
|
20
|
+
platform: 'app-plus',
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* Vue 2 与 Vue 3 的 HBuilderX 编译入口不同,按 manifest.vueVersion 选择。
|
|
25
|
+
* @param {number | string | undefined} vueVersion
|
|
26
|
+
*/
|
|
27
|
+
export function selectHbuilderxCompiler(vueVersion) {
|
|
28
|
+
return Number(vueVersion) === 2 ? VUE2_COMPILER : VUE3_COMPILER
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* about/package.json 的版本形如 5.34.2026102909;编译器写进 manifest 的是前两段。
|
|
33
|
+
* @param {string} version
|
|
34
|
+
* @returns {string}
|
|
35
|
+
*/
|
|
36
|
+
export function normalizeHbuilderxVersion(version) {
|
|
37
|
+
const parts = String(version ?? '').split('.')
|
|
38
|
+
return parts.length >= 2 ? `${parts[0]}.${parts[1]}` : String(version ?? '')
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* @param {string} dir
|
|
43
|
+
* @returns {Promise<{ root: string, version: string } | null>}
|
|
44
|
+
*/
|
|
45
|
+
async function probeInstall(dir) {
|
|
46
|
+
const dirs = [dir, path.join(dir, 'HBuilderX')]
|
|
47
|
+
for (const candidate of dirs) {
|
|
48
|
+
const about = path.join(candidate, 'plugins', 'about', 'package.json')
|
|
49
|
+
const hasCompiler =
|
|
50
|
+
(await exists(path.join(candidate, VUE3_COMPILER.dir))) ||
|
|
51
|
+
(await exists(path.join(candidate, VUE2_COMPILER.dir)))
|
|
52
|
+
if (!(await exists(about)) || !hasCompiler) {
|
|
53
|
+
continue
|
|
54
|
+
}
|
|
55
|
+
const pkg = await readJson(about).catch(() => ({}))
|
|
56
|
+
if (pkg.name !== 'about') {
|
|
57
|
+
continue
|
|
58
|
+
}
|
|
59
|
+
return { root: candidate, version: normalizeHbuilderxVersion(pkg.version) }
|
|
60
|
+
}
|
|
61
|
+
return null
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/**
|
|
65
|
+
* @param {string} dir
|
|
66
|
+
* @returns {Promise<Array<{ root: string, version: string }>>}
|
|
67
|
+
*/
|
|
68
|
+
async function scanRoot(dir) {
|
|
69
|
+
/** @type {Array<{ root: string, version: string }>} */
|
|
70
|
+
const found = []
|
|
71
|
+
const direct = await probeInstall(dir)
|
|
72
|
+
if (direct) {
|
|
73
|
+
found.push(direct)
|
|
74
|
+
}
|
|
75
|
+
const entries = await readdir(dir, { withFileTypes: true }).catch(() => [])
|
|
76
|
+
for (const entry of entries) {
|
|
77
|
+
if (!entry.isDirectory() || !/hbuilderx/i.test(entry.name)) {
|
|
78
|
+
continue
|
|
79
|
+
}
|
|
80
|
+
const install = await probeInstall(path.join(dir, entry.name))
|
|
81
|
+
if (install) {
|
|
82
|
+
found.push(install)
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
return found
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/**
|
|
89
|
+
* @param {string[]} [extraDirs]
|
|
90
|
+
* @returns {Promise<Array<{ root: string, version: string }>>}
|
|
91
|
+
*/
|
|
92
|
+
export async function listHbuilderxInstalls(extraDirs = []) {
|
|
93
|
+
/** @type {string[]} */
|
|
94
|
+
const roots = [
|
|
95
|
+
...extraDirs,
|
|
96
|
+
process.env.HBUILDERX_HOME,
|
|
97
|
+
process.env.HX_APP_ROOT,
|
|
98
|
+
'C:/Program Files',
|
|
99
|
+
'C:/Program Files (x86)',
|
|
100
|
+
'C:/Soft',
|
|
101
|
+
'D:/',
|
|
102
|
+
'D:/Soft',
|
|
103
|
+
'D:/soft',
|
|
104
|
+
'D:/sort',
|
|
105
|
+
'E:/',
|
|
106
|
+
os.homedir(),
|
|
107
|
+
path.join(os.homedir(), 'AppData', 'Local'),
|
|
108
|
+
]
|
|
109
|
+
.filter((item) => typeof item === 'string' && item.trim() !== '')
|
|
110
|
+
.map((item) => String(item))
|
|
111
|
+
|
|
112
|
+
const seen = new Set()
|
|
113
|
+
/** @type {Array<{ root: string, version: string }>} */
|
|
114
|
+
const installs = []
|
|
115
|
+
for (const root of roots) {
|
|
116
|
+
for (const install of await scanRoot(path.resolve(String(root)))) {
|
|
117
|
+
const key = install.root.toLowerCase()
|
|
118
|
+
if (seen.has(key)) {
|
|
119
|
+
continue
|
|
120
|
+
}
|
|
121
|
+
seen.add(key)
|
|
122
|
+
installs.push(install)
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
installs.sort((a, b) => compareVersion(b.version, a.version))
|
|
126
|
+
return installs
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
/**
|
|
130
|
+
* @param {string} a
|
|
131
|
+
* @param {string} b
|
|
132
|
+
*/
|
|
133
|
+
function compareVersion(a, b) {
|
|
134
|
+
const left = String(a).split('.').map(Number)
|
|
135
|
+
const right = String(b).split('.').map(Number)
|
|
136
|
+
for (let index = 0; index < Math.max(left.length, right.length); index += 1) {
|
|
137
|
+
const diff = (left[index] || 0) - (right[index] || 0)
|
|
138
|
+
if (diff !== 0) {
|
|
139
|
+
return diff
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
return 0
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
/**
|
|
146
|
+
* 项目上次用 HBuilderX 编译时写进产物 manifest 的版本,用来挑对应版本的 HBuilderX。
|
|
147
|
+
* @param {string} projectDir
|
|
148
|
+
* @returns {Promise<string>}
|
|
149
|
+
*/
|
|
150
|
+
export async function readLastBuiltVersion(projectDir) {
|
|
151
|
+
const file = path.join(projectDir, 'unpackage/dist/build/app-plus/manifest.json')
|
|
152
|
+
if (!(await exists(file))) {
|
|
153
|
+
return ''
|
|
154
|
+
}
|
|
155
|
+
const manifest = await readJson(file).catch(() => ({}))
|
|
156
|
+
return String(manifest?.['app-plus']?.['uni-app']?.compilerVersion ?? '')
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
/**
|
|
160
|
+
* 解析顺序:显式指定 → 环境变量 → 上次构建版本对应的安装 → 最新安装。
|
|
161
|
+
* @param {any} config
|
|
162
|
+
* @param {{ project?: any, explicit?: string, projectDir?: string }} [options]
|
|
163
|
+
* @returns {Promise<{ root: string, version: string } | null>}
|
|
164
|
+
*/
|
|
165
|
+
export async function resolveHbuilderx(config, options = {}) {
|
|
166
|
+
const projectDir = String(options.projectDir ?? options.project?.projectDir ?? '')
|
|
167
|
+
const explicit = [
|
|
168
|
+
options.explicit,
|
|
169
|
+
options.project?.hbuilderxRoot,
|
|
170
|
+
config?.hbuilderx?.root,
|
|
171
|
+
process.env.HBUILDERX_HOME,
|
|
172
|
+
process.env.HX_APP_ROOT,
|
|
173
|
+
].filter((item) => typeof item === 'string').filter((item) => item.trim() !== '')
|
|
174
|
+
|
|
175
|
+
for (const candidate of explicit) {
|
|
176
|
+
const install = await probeInstall(path.resolve(candidate))
|
|
177
|
+
if (install) {
|
|
178
|
+
return install
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
const installs = await listHbuilderxInstalls([...(config?.hbuilderx?.searchDirs ?? [])])
|
|
183
|
+
if (installs.length === 0) {
|
|
184
|
+
return null
|
|
185
|
+
}
|
|
186
|
+
if (projectDir) {
|
|
187
|
+
const lastVersion = await readLastBuiltVersion(projectDir)
|
|
188
|
+
const matched = installs.find((install) => install.version === lastVersion)
|
|
189
|
+
if (matched) {
|
|
190
|
+
return matched
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
return installs[0]
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
/**
|
|
197
|
+
* 用 HBuilderX 自带的 node + uni-app 编译器构建,产物结构与 HBuilderX 发行一致。
|
|
198
|
+
* @param {Object} options
|
|
199
|
+
* @param {string} options.root
|
|
200
|
+
* @param {string} options.version
|
|
201
|
+
* @param {string} options.inputDir
|
|
202
|
+
* @param {string} options.outputDir
|
|
203
|
+
* @param {number | string} [options.vueVersion] 2 或 3;默认 3
|
|
204
|
+
* @param {import('./logger.js').Logger} options.logger
|
|
205
|
+
*/
|
|
206
|
+
export async function runHbuilderxBuild(options) {
|
|
207
|
+
const { root, version, inputDir, outputDir, logger } = options
|
|
208
|
+
const compiler = selectHbuilderxCompiler(options.vueVersion ?? 3)
|
|
209
|
+
const pluginDir = path.join(root, compiler.dir)
|
|
210
|
+
const entry = path.join(pluginDir, compiler.entry)
|
|
211
|
+
if (!(await exists(entry))) {
|
|
212
|
+
throw new PackError(`HBuilderX 缺少 Vue ${compiler.vueVersion} 编译器:${entry}`, EXIT.WEB_BUILD, {
|
|
213
|
+
hint: `确认 manifest.json 的 vueVersion 是否正确,或升级 HBuilderX 后重试`,
|
|
214
|
+
})
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
const node = await resolveNode(root)
|
|
218
|
+
logger.step(`构建前端资源:HBuilderX ${version}(Vue ${compiler.vueVersion})`)
|
|
219
|
+
try {
|
|
220
|
+
await run(node, [entry, ...compiler.args], {
|
|
221
|
+
cwd: pluginDir,
|
|
222
|
+
env: {
|
|
223
|
+
HX_Version: version,
|
|
224
|
+
RUN_BY_HBUILDERX: '1',
|
|
225
|
+
UNI_HBUILDERX_PLUGINS: path.join(root, 'plugins'),
|
|
226
|
+
UNI_CLI_CONTEXT: pluginDir,
|
|
227
|
+
UNI_INPUT_DIR: inputDir,
|
|
228
|
+
UNI_OUTPUT_DIR: outputDir,
|
|
229
|
+
UNI_PLATFORM: compiler.platform,
|
|
230
|
+
NODE_ENV: 'production',
|
|
231
|
+
},
|
|
232
|
+
onLine: (line) => logger.detail(line),
|
|
233
|
+
})
|
|
234
|
+
} catch (error) {
|
|
235
|
+
const detail = error instanceof Error ? error.message : String(error)
|
|
236
|
+
throw new PackError('前端构建失败(HBuilderX 编译器)', EXIT.WEB_BUILD, {
|
|
237
|
+
hint: `${detail}\n可用 HBuilderX 打开项目手工编译一次,确认项目本身能编译通过`,
|
|
238
|
+
cause: error,
|
|
239
|
+
})
|
|
240
|
+
}
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
/**
|
|
244
|
+
* @param {string} root
|
|
245
|
+
* @returns {Promise<string>}
|
|
246
|
+
*/
|
|
247
|
+
async function resolveNode(root) {
|
|
248
|
+
const candidates = [
|
|
249
|
+
path.join(root, 'plugins', 'node', process.platform === 'win32' ? 'node.exe' : 'bin/node'),
|
|
250
|
+
path.join(root, 'plugins', 'node', 'node.exe'),
|
|
251
|
+
]
|
|
252
|
+
for (const candidate of candidates) {
|
|
253
|
+
if (await exists(candidate)) {
|
|
254
|
+
return candidate
|
|
255
|
+
}
|
|
256
|
+
}
|
|
257
|
+
return process.execPath
|
|
258
|
+
}
|
|
@@ -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
|
+
}
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto'
|
|
2
|
+
import { copyFile, readFile, readdir } from 'node:fs/promises'
|
|
3
|
+
import path from 'node:path'
|
|
4
|
+
import { PackError, EXIT } from './errors.js'
|
|
5
|
+
import { ensureDir, writeJson } from './fsx.js'
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* @param {string} dir
|
|
9
|
+
* @param {'release' | 'debug'} mode
|
|
10
|
+
*/
|
|
11
|
+
export async function findApk(dir, mode) {
|
|
12
|
+
if (!dir) {
|
|
13
|
+
throw new PackError('未指定 Gradle 输出目录', EXIT.GRADLE)
|
|
14
|
+
}
|
|
15
|
+
const entries = await readdir(dir, { withFileTypes: true }).catch(() => [])
|
|
16
|
+
const candidates = entries.filter((entry) => entry.isFile() && entry.name.endsWith('.apk'))
|
|
17
|
+
const preferred =
|
|
18
|
+
candidates.find((entry) => entry.name === `simpleDemo-${mode}.apk`) ??
|
|
19
|
+
candidates.find((entry) => entry.name === `app-${mode}.apk`) ??
|
|
20
|
+
candidates.find((entry) => entry.name.includes(mode)) ??
|
|
21
|
+
candidates[0]
|
|
22
|
+
if (!preferred) {
|
|
23
|
+
throw new PackError(`Gradle 未产出 APK:${dir}`, EXIT.GRADLE)
|
|
24
|
+
}
|
|
25
|
+
return path.join(dir, preferred.name)
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* @param {Object} options
|
|
30
|
+
* @param {string} options.apk
|
|
31
|
+
* @param {string} options.outputDir
|
|
32
|
+
* @param {string} options.baseName
|
|
33
|
+
* @param {string} options.mode
|
|
34
|
+
* @param {string} options.workDir
|
|
35
|
+
* @param {Record<string, unknown>} [options.record]
|
|
36
|
+
*/
|
|
37
|
+
export async function publishApk(options) {
|
|
38
|
+
await ensureDir(options.outputDir)
|
|
39
|
+
const stamp = timestamp()
|
|
40
|
+
const fileName = `${options.baseName}_${options.mode}_${stamp}.apk`
|
|
41
|
+
const target = path.join(options.outputDir, fileName)
|
|
42
|
+
const latest = path.join(options.outputDir, `${options.baseName}_${options.mode}_latest.apk`)
|
|
43
|
+
|
|
44
|
+
await copyFile(options.apk, target)
|
|
45
|
+
await copyFile(options.apk, latest)
|
|
46
|
+
|
|
47
|
+
const sha256 = createHash('sha256').update(await readFile(target)).digest('hex')
|
|
48
|
+
await writeJson(path.join(options.workDir, '.uni-pack-build.json'), {
|
|
49
|
+
...(options.record ?? {}),
|
|
50
|
+
mode: options.mode,
|
|
51
|
+
apk: target,
|
|
52
|
+
latest,
|
|
53
|
+
sha256,
|
|
54
|
+
builtAt: new Date().toISOString(),
|
|
55
|
+
})
|
|
56
|
+
|
|
57
|
+
return { target, latest, sha256 }
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
function timestamp() {
|
|
61
|
+
const now = new Date()
|
|
62
|
+
const pad = (value) => String(value).padStart(2, '0')
|
|
63
|
+
return `${now.getFullYear()}${pad(now.getMonth() + 1)}${pad(now.getDate())}_${pad(now.getHours())}${pad(now.getMinutes())}`
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* @param {string} projectName
|
|
68
|
+
* @param {string} versionName
|
|
69
|
+
* @param {number} versionCode
|
|
70
|
+
*/
|
|
71
|
+
export function apkBaseName(projectName, versionName, versionCode) {
|
|
72
|
+
const safe = projectName.replace(/[^\w.-]+/g, '-').replace(/^-+|-+$/g, '') || 'app'
|
|
73
|
+
return `${safe}_${versionName}_${versionCode}`
|
|
74
|
+
}
|
|
@@ -0,0 +1,154 @@
|
|
|
1
|
+
import path from 'node:path'
|
|
2
|
+
import { PackError, EXIT } from '../errors.js'
|
|
3
|
+
import { copyTree, ensureDir, exists, readText, writeText } from '../fsx.js'
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* @typedef {Object} AssetsContext
|
|
7
|
+
* @property {string} moduleDir simpleDemo 目录
|
|
8
|
+
* @property {string} dataDir SDK assets/data
|
|
9
|
+
* @property {string} resourcesDir 构建产物 dist/build/app 或 unpackage/dist/build/app-plus
|
|
10
|
+
* @property {string} appid
|
|
11
|
+
* @property {string} appName
|
|
12
|
+
* @property {string} versionName
|
|
13
|
+
* @property {boolean} debug
|
|
14
|
+
* @property {string} projectDir
|
|
15
|
+
* @property {any} [manifest] 项目 manifest,用于读取图标与启动图路径
|
|
16
|
+
*/
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* @param {AssetsContext} context
|
|
20
|
+
*/
|
|
21
|
+
export async function applyAssets(context) {
|
|
22
|
+
const mainDir = path.join(context.moduleDir, 'src/main')
|
|
23
|
+
const appsDir = path.join(mainDir, 'assets/apps')
|
|
24
|
+
const assetsData = path.join(mainDir, 'assets/data')
|
|
25
|
+
|
|
26
|
+
await copyTree(context.dataDir, assetsData)
|
|
27
|
+
|
|
28
|
+
const wwwDir = path.join(appsDir, context.appid, 'www')
|
|
29
|
+
// UTS 插件的 utssdk 是编译期资源,HBuilderX 的产物不会打进 www
|
|
30
|
+
await copyTree(context.resourcesDir, wwwDir, (relative) => /^uni_modules\/[^/]+\/utssdk(\/|$)/.test(relative))
|
|
31
|
+
await writeControlFile(assetsData, context)
|
|
32
|
+
await patchStrings(mainDir, context.appName)
|
|
33
|
+
await applyIcons(mainDir, context.projectDir, context.manifest)
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* @param {string} assetsData
|
|
38
|
+
* @param {AssetsContext} context
|
|
39
|
+
*/
|
|
40
|
+
async function writeControlFile(assetsData, context) {
|
|
41
|
+
const root = context.debug ? '<hbuilder debug="true">' : '<hbuilder>'
|
|
42
|
+
const xml = `${root}\n<apps>\n <app appid="${context.appid}" appver="${context.versionName}"/>\n</apps>\n</hbuilder>\n`
|
|
43
|
+
await writeText(path.join(assetsData, 'dcloud_control.xml'), xml)
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* @param {string} mainDir
|
|
48
|
+
* @param {string} appName
|
|
49
|
+
*/
|
|
50
|
+
async function patchStrings(mainDir, appName) {
|
|
51
|
+
const file = path.join(mainDir, 'res/values/strings.xml')
|
|
52
|
+
const text = await readText(file)
|
|
53
|
+
if (!text.includes('name="app_name"')) {
|
|
54
|
+
throw new PackError('模板 strings.xml 缺少 app_name', EXIT.PREFLIGHT)
|
|
55
|
+
}
|
|
56
|
+
await writeText(file, text.replace(/(name="app_name">)[^<]*(<)/, `$1${escapeXml(appName)}$2`))
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
const ICON_DENSITIES = ['hdpi', 'xhdpi', 'xxhdpi', 'xxxhdpi']
|
|
60
|
+
const CLIENT_ICON_FILES = { hdpi: '72x72.png', xhdpi: '96x96.png', xxhdpi: '144x144.png', xxxhdpi: '192x192.png' }
|
|
61
|
+
|
|
62
|
+
/**
|
|
63
|
+
* 图标与启动图优先用 manifest 声明的路径(CLI 与 HBuilderX 都适用),
|
|
64
|
+
* 其次回退到两种项目各自的默认目录。
|
|
65
|
+
* @param {string} mainDir
|
|
66
|
+
* @param {string} projectDir
|
|
67
|
+
* @param {any} [manifest]
|
|
68
|
+
*/
|
|
69
|
+
async function applyIcons(mainDir, projectDir, manifest) {
|
|
70
|
+
const distribute = manifest?.['app-plus']?.distribute ?? {}
|
|
71
|
+
const manifestIcons = distribute.icons?.android ?? {}
|
|
72
|
+
const manifestSplash = distribute.splashscreen?.android ?? {}
|
|
73
|
+
|
|
74
|
+
for (const density of ICON_DENSITIES) {
|
|
75
|
+
const source = await firstExisting([
|
|
76
|
+
resolveMaybeRelative(projectDir, manifestIcons[density]),
|
|
77
|
+
path.join(projectDir, 'src/static/app/icons', CLIENT_ICON_FILES[density]),
|
|
78
|
+
path.join(projectDir, 'unpackage/res/icons', CLIENT_ICON_FILES[density]),
|
|
79
|
+
])
|
|
80
|
+
if (source) {
|
|
81
|
+
await copyFile(source, path.join(mainDir, `res/drawable-${density}/icon.png`))
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
const splash = await firstExisting([
|
|
85
|
+
resolveMaybeRelative(projectDir, manifestSplash[density]),
|
|
86
|
+
path.join(projectDir, 'src/static/app/splash', `splash-${density}.png`),
|
|
87
|
+
path.join(projectDir, 'unpackage/res/splash/splash.png'),
|
|
88
|
+
path.join(projectDir, 'unpackage/res/splash', `splash-${density}.png`),
|
|
89
|
+
])
|
|
90
|
+
if (splash) {
|
|
91
|
+
await copyFile(splash, path.join(mainDir, `res/drawable-${density}/splash.png`))
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
const fallbackIcon = await firstExisting([
|
|
96
|
+
resolveMaybeRelative(projectDir, manifestIcons.xxxhdpi),
|
|
97
|
+
path.join(projectDir, 'src/static/app/icons/192x192.png'),
|
|
98
|
+
path.join(projectDir, 'unpackage/res/icons/192x192.png'),
|
|
99
|
+
])
|
|
100
|
+
if (fallbackIcon) {
|
|
101
|
+
await copyFile(fallbackIcon, path.join(mainDir, 'res/drawable/icon.png'))
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
const fallbackSplash = await firstExisting([
|
|
105
|
+
resolveMaybeRelative(projectDir, manifestSplash.xxhdpi),
|
|
106
|
+
path.join(projectDir, 'src/static/app/splash/splash-xxhdpi.png'),
|
|
107
|
+
path.join(projectDir, 'unpackage/res/splash/splash.png'),
|
|
108
|
+
])
|
|
109
|
+
if (fallbackSplash) {
|
|
110
|
+
await copyFile(fallbackSplash, path.join(mainDir, 'res/drawable/splash.png'))
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/**
|
|
115
|
+
* @param {string} projectDir
|
|
116
|
+
* @param {unknown} value
|
|
117
|
+
* @returns {string}
|
|
118
|
+
*/
|
|
119
|
+
function resolveMaybeRelative(projectDir, value) {
|
|
120
|
+
if (typeof value !== 'string' || !value.trim()) {
|
|
121
|
+
return ''
|
|
122
|
+
}
|
|
123
|
+
return path.isAbsolute(value) ? value : path.join(projectDir, value)
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
/**
|
|
127
|
+
* @param {string[]} candidates
|
|
128
|
+
* @returns {Promise<string>}
|
|
129
|
+
*/
|
|
130
|
+
async function firstExisting(candidates) {
|
|
131
|
+
for (const candidate of candidates) {
|
|
132
|
+
if (candidate && (await exists(candidate))) {
|
|
133
|
+
return candidate
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
return ''
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
/**
|
|
140
|
+
* @param {string} from
|
|
141
|
+
* @param {string} to
|
|
142
|
+
*/
|
|
143
|
+
async function copyFile(from, to) {
|
|
144
|
+
await ensureDir(path.dirname(to))
|
|
145
|
+
const { copyFile: copy } = await import('node:fs/promises')
|
|
146
|
+
await copy(from, to)
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
/**
|
|
150
|
+
* @param {string} value
|
|
151
|
+
*/
|
|
152
|
+
function escapeXml(value) {
|
|
153
|
+
return value.replace(/[<>&"]/g, (char) => ({ '<': '<', '>': '>', '&': '&', '"': '"' })[char] ?? char)
|
|
154
|
+
}
|
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
import path from 'node:path'
|
|
2
|
+
import { PackError, EXIT } from '../errors.js'
|
|
3
|
+
import { readText, writeText } from '../fsx.js'
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* 精确替换:匹配 0 次或多次都视为错误,避免模板变化后静默失效。
|
|
7
|
+
* @param {string} text
|
|
8
|
+
* @param {RegExp} pattern
|
|
9
|
+
* @param {string | ((...args: string[]) => string)} replacement
|
|
10
|
+
* @param {string} label
|
|
11
|
+
*/
|
|
12
|
+
export function replaceExactlyOnce(text, pattern, replacement, label) {
|
|
13
|
+
const flags = pattern.flags.includes('g') ? pattern.flags : `${pattern.flags}g`
|
|
14
|
+
const global = new RegExp(pattern.source, flags)
|
|
15
|
+
const matches = [...text.matchAll(global)]
|
|
16
|
+
if (matches.length !== 1) {
|
|
17
|
+
throw new PackError(`模板替换失败(${label}):期望命中 1 次,实际 ${matches.length} 次`, EXIT.GRADLE)
|
|
18
|
+
}
|
|
19
|
+
return text.replace(global, /** @type {any} */ (typeof replacement === 'string' ? replacement : replacement))
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* @typedef {Object} GradlePatchContext
|
|
24
|
+
* @property {string} packageName
|
|
25
|
+
* @property {string} versionName
|
|
26
|
+
* @property {number} versionCode
|
|
27
|
+
* @property {number} minSdkVersion
|
|
28
|
+
* @property {number} targetSdkVersion
|
|
29
|
+
* @property {number} compileSdkVersion
|
|
30
|
+
* @property {string} buildToolsVersion
|
|
31
|
+
* @property {string[]} abiFilters
|
|
32
|
+
* @property {{ keyAlias: string, keyPassword: string, storePassword: string }} signing
|
|
33
|
+
*/
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* @param {string} file
|
|
37
|
+
* @param {GradlePatchContext} context
|
|
38
|
+
*/
|
|
39
|
+
export async function patchAppGradle(file, context) {
|
|
40
|
+
let text = await readText(file)
|
|
41
|
+
|
|
42
|
+
text = replaceExactlyOnce(text, /compileSdkVersion\s+\d+/, `compileSdkVersion ${context.compileSdkVersion}`, 'compileSdkVersion')
|
|
43
|
+
text = replaceExactlyOnce(
|
|
44
|
+
text,
|
|
45
|
+
/buildToolsVersion\s+'[^']*'/,
|
|
46
|
+
`buildToolsVersion '${context.buildToolsVersion}'`,
|
|
47
|
+
'buildToolsVersion',
|
|
48
|
+
)
|
|
49
|
+
text = replaceExactlyOnce(text, /namespace\s+'[^']*'/, `namespace '${context.packageName}'`, 'namespace')
|
|
50
|
+
text = replaceExactlyOnce(
|
|
51
|
+
text,
|
|
52
|
+
/applicationId\s+"[^"]*"/,
|
|
53
|
+
`applicationId "${context.packageName}"`,
|
|
54
|
+
'applicationId',
|
|
55
|
+
)
|
|
56
|
+
text = replaceExactlyOnce(text, /minSdkVersion\s+\d+/, `minSdkVersion ${context.minSdkVersion}`, 'minSdkVersion')
|
|
57
|
+
text = replaceExactlyOnce(
|
|
58
|
+
text,
|
|
59
|
+
/targetSdkVersion\s+\d+/,
|
|
60
|
+
`targetSdkVersion ${context.targetSdkVersion}`,
|
|
61
|
+
'targetSdkVersion',
|
|
62
|
+
)
|
|
63
|
+
text = replaceExactlyOnce(text, /versionCode\s+\d+/, `versionCode ${context.versionCode}`, 'versionCode')
|
|
64
|
+
text = replaceExactlyOnce(text, /versionName\s+"[^"]*"/, `versionName "${context.versionName}"`, 'versionName')
|
|
65
|
+
|
|
66
|
+
const abi = context.abiFilters.map((item) => `'${item}'`).join(', ')
|
|
67
|
+
const ndkPattern = /ndk\s*\{\s*abiFilters[^}]*\}/
|
|
68
|
+
if (ndkPattern.test(text)) {
|
|
69
|
+
text = replaceExactlyOnce(text, ndkPattern, `ndk {\n abiFilters ${abi}\n }`, 'abiFilters')
|
|
70
|
+
} else {
|
|
71
|
+
text = replaceExactlyOnce(
|
|
72
|
+
text,
|
|
73
|
+
/multiDexEnabled\s+true/,
|
|
74
|
+
`multiDexEnabled true\n ndk {\n abiFilters ${abi}\n }`,
|
|
75
|
+
'abiFilters(insert)',
|
|
76
|
+
)
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
const signingBlock = [
|
|
80
|
+
'signingConfigs {',
|
|
81
|
+
' config {',
|
|
82
|
+
` keyAlias '${context.signing.keyAlias}'`,
|
|
83
|
+
` keyPassword '${context.signing.keyPassword}'`,
|
|
84
|
+
" storeFile file('aw-pack.jks')",
|
|
85
|
+
` storePassword '${context.signing.storePassword}'`,
|
|
86
|
+
' v1SigningEnabled true',
|
|
87
|
+
' v2SigningEnabled true',
|
|
88
|
+
' }',
|
|
89
|
+
' }',
|
|
90
|
+
].join('\n')
|
|
91
|
+
text = replaceExactlyOnce(text, /signingConfigs\s*\{[\s\S]*?\n {4}\}/, signingBlock, 'signingConfigs')
|
|
92
|
+
|
|
93
|
+
// targetSdk 30 是电视端的既定配置,关掉对应的 lint 阻断
|
|
94
|
+
if (!text.includes('ExpiredTargetSdkVersion')) {
|
|
95
|
+
text = replaceExactlyOnce(
|
|
96
|
+
text,
|
|
97
|
+
/buildTypes\s*\{/,
|
|
98
|
+
"lint {\n disable 'ExpiredTargetSdkVersion'\n }\n buildTypes {",
|
|
99
|
+
'lint',
|
|
100
|
+
)
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
await writeText(file, text)
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/**
|
|
107
|
+
* @param {string} file
|
|
108
|
+
* @param {string} androidSdkDir
|
|
109
|
+
*/
|
|
110
|
+
export async function patchRootGradle(file, androidSdkDir) {
|
|
111
|
+
let text = await readText(file)
|
|
112
|
+
if (!text.includes('maven { url \'https://jitpack.io\' }')) {
|
|
113
|
+
text = text.replace(
|
|
114
|
+
/allprojects\s*\{[\s\S]*?repositories\s*\{/,
|
|
115
|
+
(match) => `${match}\n maven { url 'https://jitpack.io' }`,
|
|
116
|
+
)
|
|
117
|
+
if (!text.includes('jitpack.io')) {
|
|
118
|
+
throw new PackError('模板根 build.gradle 结构异常,无法注入 jitpack 仓库', EXIT.GRADLE, {
|
|
119
|
+
hint: '换一份干净的离线 SDK 再试',
|
|
120
|
+
})
|
|
121
|
+
}
|
|
122
|
+
await writeText(file, text)
|
|
123
|
+
}
|
|
124
|
+
await writeText(
|
|
125
|
+
path.join(path.dirname(file), 'local.properties'),
|
|
126
|
+
`sdk.dir=${androidSdkDir.replace(/\\/g, '/')}\n`,
|
|
127
|
+
)
|
|
128
|
+
}
|