uniapp-android-cli 0.1.0 → 0.1.3

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.
@@ -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
+ }
@@ -1,8 +1,8 @@
1
- import { createHash } from 'node:crypto'
2
- import { copyFile, readFile, readdir } from 'node:fs/promises'
1
+ import { appendFile, copyFile, readdir, rm, stat } from 'node:fs/promises'
3
2
  import path from 'node:path'
4
3
  import { PackError, EXIT } from './errors.js'
5
- import { ensureDir, writeJson } from './fsx.js'
4
+ import { ensureDir, replaceHardLink, writeJson } from './fsx.js'
5
+ import { fileHash } from './hash.js'
6
6
 
7
7
  /**
8
8
  * @param {string} dir
@@ -26,13 +26,20 @@ export async function findApk(dir, mode) {
26
26
  }
27
27
 
28
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]
29
+ * @typedef {Object} PublishApkOptions
30
+ * @property {string} apk Gradle 产出的 APK
31
+ * @property {string} outputDir 项目 apk 目录
32
+ * @property {string} baseName <展示名>_<版本>_<版本号>
33
+ * @property {'release' | 'debug'} mode
34
+ * @property {string} workDir 构建工作目录,用于写 .uni-pack-build.json
35
+ * @property {Record<string, unknown>} [record]
36
+ * @property {import('./logger.js').Logger} [logger]
37
+ * @property {number} [prune] 只保留最近 n 个时间戳包(0 表示只留 latest)
38
+ */
39
+
40
+ /**
41
+ * 发布 APK:时间戳副本 + latest 硬链 + 同名清单 + builds.jsonl + 可选清理。
42
+ * @param {PublishApkOptions} options
36
43
  */
37
44
  export async function publishApk(options) {
38
45
  await ensureDir(options.outputDir)
@@ -42,19 +49,100 @@ export async function publishApk(options) {
42
49
  const latest = path.join(options.outputDir, `${options.baseName}_${options.mode}_latest.apk`)
43
50
 
44
51
  await copyFile(options.apk, target)
45
- await copyFile(options.apk, latest)
46
52
 
47
- const sha256 = createHash('sha256').update(await readFile(target)).digest('hex')
48
- await writeJson(path.join(options.workDir, '.uni-pack-build.json'), {
53
+ let latestLinked = true
54
+ try {
55
+ await replaceHardLink(target, latest)
56
+ } catch (error) {
57
+ latestLinked = false
58
+ const detail = error instanceof Error ? error.message : String(error)
59
+ options.logger?.warn(`latest 硬链失败(${detail}),已回退为复制`)
60
+ await copyFile(target, latest)
61
+ }
62
+
63
+ const size = (await stat(target)).size
64
+ const sha256 = await fileHash(target)
65
+ const builtAt = new Date().toISOString()
66
+ const record = {
49
67
  ...(options.record ?? {}),
50
68
  mode: options.mode,
51
69
  apk: target,
52
70
  latest,
53
71
  sha256,
54
- builtAt: new Date().toISOString(),
55
- })
72
+ size,
73
+ builtAt,
74
+ }
75
+
76
+ const recordFile = `${target}.json`
77
+ await writeJson(recordFile, record)
78
+ await appendFile(path.join(options.outputDir, 'builds.jsonl'), `${JSON.stringify(record)}\n`, 'utf8')
79
+ await writeJson(path.join(options.workDir, '.uni-pack-build.json'), record)
80
+
81
+ if (options.prune !== undefined) {
82
+ await pruneApks({ outputDir: options.outputDir, mode: options.mode, keep: options.prune, logger: options.logger })
83
+ }
84
+
85
+ return { target, latest, sha256, size, recordFile, latestLinked }
86
+ }
87
+
88
+ /**
89
+ * 按时间保留最近 n 个时间戳包(同目录、同一 mode),latest 与 builds.jsonl 不动。
90
+ * @param {Object} options
91
+ * @param {string} options.outputDir
92
+ * @param {'release' | 'debug'} [options.mode] 只清理该 mode;不传时两种都清
93
+ * @param {number} options.keep
94
+ * @param {import('./logger.js').Logger} [options.logger]
95
+ * @returns {Promise<string[]>} 删除的文件名
96
+ */
97
+ export async function pruneApks(options) {
98
+ const keep = Number(options.keep)
99
+ if (!Number.isInteger(keep) || keep < 0) {
100
+ throw new PackError(`--prune 需要一个非负整数,收到:${String(options.keep)}`, EXIT.CONFIG, {
101
+ hint: '例如 --prune 5 表示每个 mode 只保留最近 5 个时间戳 APK,latest 永远保留',
102
+ })
103
+ }
56
104
 
57
- return { target, latest, sha256 }
105
+ const entries = await readdir(options.outputDir, { withFileTypes: true }).catch(() => [])
106
+ const modePattern = options.mode ? escapeRegExp(options.mode) : 'release|debug'
107
+ const pattern = new RegExp(`^(.+)_(${modePattern})_(\\d{8}_\\d{4})\\.apk$`)
108
+ /** @type {Map<'release' | 'debug', Array<{ name: string, stamp: string }>>} */
109
+ const groups = new Map()
110
+ for (const entry of entries) {
111
+ if (!entry.isFile()) {
112
+ continue
113
+ }
114
+ const match = pattern.exec(entry.name)
115
+ if (!match) {
116
+ continue
117
+ }
118
+ const mode = /** @type {'release' | 'debug'} */ (match[2])
119
+ const list = groups.get(mode) ?? []
120
+ list.push({ name: entry.name, stamp: match[3] })
121
+ groups.set(mode, list)
122
+ }
123
+
124
+ const deleted = []
125
+ for (const list of groups.values()) {
126
+ list.sort((left, right) => right.stamp.localeCompare(left.stamp))
127
+ for (const item of list.slice(keep)) {
128
+ const apk = path.join(options.outputDir, item.name)
129
+ await rm(apk, { force: true })
130
+ await rm(`${apk}.json`, { force: true })
131
+ deleted.push(item.name)
132
+ }
133
+ }
134
+
135
+ if (deleted.length > 0) {
136
+ options.logger?.info(`已清理 ${deleted.length} 个旧 APK(保留最近 ${keep} 个时间戳包)`)
137
+ }
138
+ return deleted
139
+ }
140
+
141
+ /**
142
+ * @param {string} value
143
+ */
144
+ function escapeRegExp(value) {
145
+ return value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
58
146
  }
59
147
 
60
148
  function timestamp() {
@@ -63,6 +151,25 @@ function timestamp() {
63
151
  return `${now.getFullYear()}${pad(now.getMonth() + 1)}${pad(now.getDate())}_${pad(now.getHours())}${pad(now.getMinutes())}`
64
152
  }
65
153
 
154
+ /**
155
+ * APK 前缀:显式 outputPrefix > manifest 展示名 > 项目标识/appid。
156
+ * 中文展示名清洗后会变成空串,不能直接退化成 "app",否则多项目会互相撞名。
157
+ * @param {{ outputPrefix?: string, name?: string }} project
158
+ * @param {{ name?: string, appid?: string }} resolved
159
+ * @returns {string}
160
+ */
161
+ export function resolveApkPrefix(project, resolved) {
162
+ const explicit = String(project.outputPrefix ?? '').trim()
163
+ if (explicit) {
164
+ return explicit
165
+ }
166
+ const display = String(resolved.name ?? '').trim()
167
+ if (display && display.replace(/[^\w.-]+/g, '').length > 0) {
168
+ return display
169
+ }
170
+ return String(project.name ?? resolved.appid ?? 'app')
171
+ }
172
+
66
173
  /**
67
174
  * @param {string} projectName
68
175
  * @param {string} versionName
@@ -13,6 +13,7 @@ import { copyTree, ensureDir, exists, readText, writeText } from '../fsx.js'
13
13
  * @property {boolean} debug
14
14
  * @property {string} projectDir
15
15
  * @property {any} [manifest] 项目 manifest,用于读取图标与启动图路径
16
+ * @property {import('../logger.js').Logger} [logger]
16
17
  */
17
18
 
18
19
  /**
@@ -30,7 +31,7 @@ export async function applyAssets(context) {
30
31
  await copyTree(context.resourcesDir, wwwDir, (relative) => /^uni_modules\/[^/]+\/utssdk(\/|$)/.test(relative))
31
32
  await writeControlFile(assetsData, context)
32
33
  await patchStrings(mainDir, context.appName)
33
- await applyIcons(mainDir, context.projectDir, context.manifest)
34
+ await applyIcons(mainDir, context.projectDir, context.manifest, context.logger)
34
35
  }
35
36
 
36
37
  /**
@@ -61,54 +62,84 @@ const CLIENT_ICON_FILES = { hdpi: '72x72.png', xhdpi: '96x96.png', xxhdpi: '144x
61
62
 
62
63
  /**
63
64
  * 图标与启动图优先用 manifest 声明的路径(CLI 与 HBuilderX 都适用),
64
- * 其次回退到两种项目各自的默认目录。
65
+ * 其次回退到两种项目各自的默认目录。只配置部分密度时,用已有最高密度补齐;
66
+ * 完全没配置时保留 SDK 模板资源,并提示使用默认图。
65
67
  * @param {string} mainDir
66
68
  * @param {string} projectDir
67
69
  * @param {any} [manifest]
70
+ * @param {import('../logger.js').Logger} [logger]
68
71
  */
69
- async function applyIcons(mainDir, projectDir, manifest) {
72
+ async function applyIcons(mainDir, projectDir, manifest, logger) {
70
73
  const distribute = manifest?.['app-plus']?.distribute ?? {}
71
74
  const manifestIcons = distribute.icons?.android ?? {}
72
75
  const manifestSplash = distribute.splashscreen?.android ?? {}
73
76
 
77
+ const icons = await resolveDensitySources(projectDir, manifestIcons, (density) => [
78
+ path.join(projectDir, 'src/static/app/icons', CLIENT_ICON_FILES[density]),
79
+ path.join(projectDir, 'unpackage/res/icons', CLIENT_ICON_FILES[density]),
80
+ ])
81
+ const splash = await resolveDensitySources(projectDir, manifestSplash, (density) => [
82
+ path.join(projectDir, 'src/static/app/splash', `splash-${density}.png`),
83
+ path.join(projectDir, 'unpackage/res/splash/splash.png'),
84
+ path.join(projectDir, 'unpackage/res/splash', `splash-${density}.png`),
85
+ ])
86
+
87
+ const bestIcon = bestSource(icons)
88
+ const bestSplash = bestSource(splash)
89
+
74
90
  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`))
91
+ const icon = icons[density] || bestIcon
92
+ if (icon) {
93
+ await copyFile(icon, path.join(mainDir, `res/drawable-${density}/icon.png`))
82
94
  }
83
95
 
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`))
96
+ const splashSource = splash[density] || bestSplash
97
+ if (splashSource) {
98
+ await copyFile(splashSource, path.join(mainDir, `res/drawable-${density}/splash.png`))
92
99
  }
93
100
  }
94
101
 
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
+ if (bestIcon) {
103
+ await copyFile(bestIcon, path.join(mainDir, 'res/drawable/icon.png'))
104
+ } else {
105
+ logger?.warn('未配置应用图标(app-plus.distribute.icons.android),使用 SDK 默认图标(DCloud),发布前请替换')
102
106
  }
107
+ if (bestSplash) {
108
+ await copyFile(bestSplash, path.join(mainDir, 'res/drawable/splash.png'))
109
+ } else {
110
+ logger?.warn('未配置启动图(app-plus.distribute.splashscreen.android),使用 SDK 默认启动图,发布前请替换')
111
+ }
112
+ }
103
113
 
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'))
114
+ /**
115
+ * @param {string} projectDir
116
+ * @param {Record<string, any>} declared
117
+ * @param {(density: string) => string[]} defaults
118
+ * @returns {Promise<Record<string, string>>}
119
+ */
120
+ async function resolveDensitySources(projectDir, declared, defaults) {
121
+ /** @type {Record<string, string>} */
122
+ const sources = {}
123
+ for (const density of ICON_DENSITIES) {
124
+ const source = await firstExisting([resolveMaybeRelative(projectDir, declared[density]), ...defaults(density)])
125
+ if (source) {
126
+ sources[density] = source
127
+ }
128
+ }
129
+ return sources
130
+ }
131
+
132
+ /**
133
+ * @param {Record<string, string>} sources
134
+ * @returns {string}
135
+ */
136
+ function bestSource(sources) {
137
+ for (const density of [...ICON_DENSITIES].reverse()) {
138
+ if (sources[density]) {
139
+ return sources[density]
140
+ }
111
141
  }
142
+ return ''
112
143
  }
113
144
 
114
145
  /**
@@ -19,6 +19,42 @@ export function replaceExactlyOnce(text, pattern, replacement, label) {
19
19
  return text.replace(global, /** @type {any} */ (typeof replacement === 'string' ? replacement : replacement))
20
20
  }
21
21
 
22
+ const CORE_DEPENDENCIES = [
23
+ { key: 'com.squareup.okhttp3:okhttp', line: 'implementation "com.squareup.okhttp3:okhttp:3.12.12"' },
24
+ { key: 'com.facebook.fresco:middleware', line: 'implementation "com.facebook.fresco:middleware:3.4.0"' },
25
+ { key: 'com.facebook.fresco:webpsupport', line: 'implementation "com.facebook.fresco:webpsupport:3.4.0"' },
26
+ { key: 'com.facebook.fresco:animated-webp', line: 'implementation "com.facebook.fresco:animated-webp:3.4.0"' },
27
+ {
28
+ key: 'androidx.legacy:legacy-support-v4',
29
+ line: 'implementation "androidx.legacy:legacy-support-v4:1.0.0"',
30
+ },
31
+ { key: 'net.lingala.zip4j:zip4j', line: 'implementation "net.lingala.zip4j:zip4j:2.11.5"' },
32
+ {
33
+ key: 'com.github.bumptech.glide:compiler',
34
+ line: 'annotationProcessor "com.github.bumptech.glide:compiler:4.9.0"',
35
+ },
36
+ ]
37
+
38
+ /**
39
+ * 部分 SDK 模板的核心依赖放在 SMARTPACK 标记块里,模板被清理或换成干净版本时可能缺失。
40
+ * zip4j 缺失会让 RuntimeFeatureImpl 在后台线程抛 NoClassDefFoundError 并闪退。
41
+ * @param {string} text
42
+ * @returns {string}
43
+ */
44
+ export function ensureCoreDependencies(text) {
45
+ const missing = CORE_DEPENDENCIES.filter((item) => !text.includes(item.key))
46
+ if (missing.length === 0) {
47
+ return text
48
+ }
49
+ const snippet = missing.map((item) => ` ${item.line}`).join('\n')
50
+ const match = /dependencies\s*\{/.exec(text)
51
+ if (!match) {
52
+ throw new PackError('模板 build.gradle 缺少 dependencies 块', EXIT.GRADLE)
53
+ }
54
+ const open = match.index + match[0].length
55
+ return `${text.slice(0, open)}\n${snippet}${text.slice(open)}`
56
+ }
57
+
22
58
  /**
23
59
  * @typedef {Object} GradlePatchContext
24
60
  * @property {string} packageName
@@ -76,13 +112,14 @@ export async function patchAppGradle(file, context) {
76
112
  )
77
113
  }
78
114
 
115
+ // 密码不落盘:只写环境变量名,由 runGradle 在子进程 env 里注入
79
116
  const signingBlock = [
80
117
  'signingConfigs {',
81
118
  ' config {',
82
119
  ` keyAlias '${context.signing.keyAlias}'`,
83
- ` keyPassword '${context.signing.keyPassword}'`,
120
+ " keyPassword System.getenv('UNI_PACK_KEY_PASS')",
84
121
  " storeFile file('aw-pack.jks')",
85
- ` storePassword '${context.signing.storePassword}'`,
122
+ " storePassword System.getenv('UNI_PACK_STORE_PASS')",
86
123
  ' v1SigningEnabled true',
87
124
  ' v2SigningEnabled true',
88
125
  ' }',
@@ -100,6 +137,7 @@ export async function patchAppGradle(file, context) {
100
137
  )
101
138
  }
102
139
 
140
+ text = ensureCoreDependencies(text)
103
141
  await writeText(file, text)
104
142
  }
105
143
 
@@ -1,8 +1,10 @@
1
1
  import path from 'node:path'
2
+ import { copyFile } from 'node:fs/promises'
2
3
  import { copyTree, ensureDir, readText, writeText } from '../fsx.js'
3
4
 
4
5
  const MARKERS = [
5
- /\/\/ ===== SMARTPACK[\s\S]*?END =====[^\n]*\n?/g,
6
+ // CORE DEPS 是 SDK 运行时依赖(zip4j、okhttp 等),不是插件注入,必须保留
7
+ /\/\/ ===== SMARTPACK (?!CORE DEPS)[\s\S]*?END =====[^\n]*\n?/g,
6
8
  /<!-- ===== SMARTPACK[\s\S]*?END ===== -->\r?\n?/g,
7
9
  ]
8
10
 
@@ -18,8 +20,16 @@ const SKIP = new Set([
18
20
  'simpleDemo/aw-pack.jks',
19
21
  ])
20
22
 
23
+ // 这些文件每次构建都会按项目改写,增量复用时也必须从干净模板重新覆盖
24
+ const PATCHED_FILES = [
25
+ 'build.gradle',
26
+ 'settings.gradle',
27
+ 'simpleDemo/build.gradle',
28
+ 'simpleDemo/src/main/AndroidManifest.xml',
29
+ ]
30
+
21
31
  /**
22
- * 从 SDK 复制一份干净模板到工作目录,并清掉上一版插件留下的 SMARTPACK 注入块。
32
+ * 从 SDK 复制一份干净模板到工作目录(首次构建或 SDK/模板变化时使用)。
23
33
  * @param {string} templateRoot
24
34
  * @param {string} targetDir
25
35
  */
@@ -30,16 +40,24 @@ export async function prepareTemplate(templateRoot, targetDir) {
30
40
  targetDir,
31
41
  (relative) => SKIP.has(relative) || relative.startsWith('simpleDemo/build/'),
32
42
  )
43
+ await refreshTemplateFiles(templateRoot, targetDir)
44
+ return targetDir
45
+ }
33
46
 
34
- for (const file of [
35
- path.join(targetDir, 'build.gradle'),
36
- path.join(targetDir, 'simpleDemo/build.gradle'),
37
- path.join(targetDir, 'simpleDemo/src/main/AndroidManifest.xml'),
38
- ]) {
39
- await stripMarkerBlocks(file)
47
+ /**
48
+ * 只把会被 patch 改写的几个文件恢复成模板原文,并清掉上一版插件留下的 SMARTPACK 注入块。
49
+ * 增量构建时用它代替整棵模板复制。
50
+ * @param {string} templateRoot
51
+ * @param {string} targetDir
52
+ */
53
+ export async function refreshTemplateFiles(templateRoot, targetDir) {
54
+ for (const relative of PATCHED_FILES) {
55
+ const source = path.join(templateRoot, relative)
56
+ const target = path.join(targetDir, relative)
57
+ await ensureDir(path.dirname(target))
58
+ await copyFile(source, target)
59
+ await stripMarkerBlocks(target)
40
60
  }
41
-
42
- return targetDir
43
61
  }
44
62
 
45
63
  /**
@@ -65,6 +65,7 @@ export async function integrateUtsPlugins(options) {
65
65
  if (usable.length === 0) {
66
66
  return { modules: [] }
67
67
  }
68
+ logger.detail(`UTS Kotlin 版本:${kotlinVersion}(${options.kotlinVersion ? '模板声明' : '默认兜底'})`)
68
69
 
69
70
  /** @type {Array<any>} */
70
71
  const modules = []