uniapp-android-cli 0.1.0 → 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.
@@ -1,31 +1,38 @@
1
1
  import path from 'node:path'
2
- import { CONFIG_FILE, loadConfig, resolveDefaultWebBuild, saveConfig } from '../core/config.js'
2
+ import { CONFIG_FILE, PROJECT_CONFIG_FILE, loadConfig, resolveDefaultWebBuild, saveConfig } from '../core/config.js'
3
3
  import { PackError, EXIT } from '../core/errors.js'
4
- import { exists, readText } from '../core/fsx.js'
4
+ import { exists, readJson, readText, writeJson } from '../core/fsx.js'
5
5
  import { resolveHbuilderx } from '../core/hbuilderx.js'
6
+ import { Prompt, canPrompt } from '../core/interactive.js'
7
+ import {
8
+ makeFileValidator,
9
+ splitInitConfig,
10
+ toProjectRelative,
11
+ validateAppKey,
12
+ validateConfirm,
13
+ validateCustomType,
14
+ validateExplicitConfirm,
15
+ validatePackageName,
16
+ validatePlayground,
17
+ validateRequired,
18
+ } from '../core/initConfig.js'
19
+ import { askEnvironmentPaths } from '../core/initEnv.js'
6
20
  import { Logger } from '../core/logger.js'
7
21
  import { detectVueVersion, normalizeManifest, readProjectManifest, readProjectPackage } from '../core/project.js'
8
22
  import { findSdkForVersion, resolveSdkRootInput } from '../core/sdk.js'
9
23
  import { readCompilerVersion, readSdkVersion, versionMismatchHint } from '../core/version.js'
10
24
 
11
- // 这些字段以 manifest 为准;旧配置里的快照会在重跑 init 时清掉。
12
- const SNAPSHOT_FIELDS = [
13
- 'name',
14
- 'appid',
15
- 'versionName',
16
- 'versionCode',
17
- 'minSdkVersion',
18
- 'targetSdkVersion',
19
- 'abiFilters',
20
- ]
21
-
22
25
  /**
26
+ * 初始化:探测环境与项目信息,交互式补全项目级配置,
27
+ * 把可共享字段写入 <项目>/uni-pack.config.json,把本机路径写入用户配置。
23
28
  * @param {Record<string, any>} options
24
29
  */
25
30
  export async function initCommand(options) {
26
31
  const logger = new Logger(options)
27
32
  const projectDir = path.resolve(options.project ?? options.cwd ?? process.cwd())
28
33
  const config = await loadConfig()
34
+ const projectConfigFile = path.join(projectDir, PROJECT_CONFIG_FILE)
35
+ const existingProject = (await exists(projectConfigFile)) ? await readJson(projectConfigFile).catch(() => ({})) : {}
29
36
 
30
37
  const { manifest, type } = await readProjectManifest(projectDir)
31
38
  const vueVersion = await detectVueVersion(projectDir, manifest, type)
@@ -33,82 +40,247 @@ export async function initCommand(options) {
33
40
  const resolved = normalizeManifest(manifest, { package: fallbackPackage }, { validate: false })
34
41
  const key = projectKey(resolved)
35
42
  const existing = config.projects?.[key] ?? {}
43
+ const existingSigning = { ...(existing.signing ?? {}), ...(existingProject.signing ?? {}) }
36
44
 
37
- const hbuilderx = type === 'hbuilderx' ? await resolveHbuilderx(config, { projectDir, explicit: options.hbuilderx }) : null
38
- const compiler = await readCompilerVersion({ ...existing, type, projectDir }, { hbuilderxRoot: hbuilderx?.root })
45
+ let hbuilderx =
46
+ type === 'hbuilderx'
47
+ ? await resolveHbuilderx(config, { projectDir, explicit: options.hbuilderx ?? existingProject.hbuilderxRoot })
48
+ : null
49
+ let compiler = await readCompilerVersion(
50
+ { ...existing, ...existingProject, type, projectDir },
51
+ { hbuilderxRoot: hbuilderx?.root },
52
+ )
53
+
54
+ let sdkRoot = ''
55
+ let sdkVersion = null
56
+ try {
57
+ sdkRoot = await resolveSdkRoot({
58
+ config,
59
+ explicit: options.sdk,
60
+ existingRoot: existingProject.sdkRoot ?? existing.sdkRoot,
61
+ version: compiler.version,
62
+ })
63
+ sdkVersion = await readSdkVersion(sdkRoot)
64
+ } catch (error) {
65
+ if (!canPrompt(options)) {
66
+ throw error
67
+ }
68
+ logger.warn(error instanceof Error ? error.message : String(error))
69
+ logger.info('稍后可以填写离线 SDK 路径')
70
+ }
71
+ let androidSdk = await resolveAndroidSdk(options.androidSdk ?? config.android.sdkDir)
72
+ let javaHome = await resolveJdk(options.jdk ?? config.android.jdk)
73
+
74
+ let hbuilderxPath = String(hbuilderx?.root ?? options.hbuilderx ?? existingProject.hbuilderxRoot ?? '')
75
+ let sdkPath = String(sdkRoot || options.sdk || '')
76
+ let androidSdkPath = String(androidSdk || options.androidSdk || '')
77
+ let jdkPath = String(javaHome || options.jdk || '')
39
78
 
40
- const sdkRoot = await resolveSdkRoot({
41
- config,
42
- explicit: options.sdk,
43
- existingRoot: existing.sdkRoot,
44
- version: compiler.version,
45
- })
46
- const sdkVersion = await readSdkVersion(sdkRoot)
47
- const androidSdk = await resolveAndroidSdk(options.androidSdk ?? config.android.sdkDir)
48
- const javaHome = await resolveJdk(options.jdk ?? config.android.jdk)
49
79
  const certificateDir = path.join(projectDir, 'certificate/android')
50
- const properties = path.join(certificateDir, 'keystore.properties')
51
- const keystore =
52
- options.keystore ||
53
- (await detectKeystore(certificateDir)) ||
54
- String(existing.signing?.keystore ?? '')
55
- const alias = (await exists(properties)) ? await readProperty(properties, 'keyAlias') : ''
56
- config.sdk = { ...config.sdk, root: config.sdk.root || sdkRoot }
57
- config.hbuilderx = { ...config.hbuilderx, root: config.hbuilderx.root || hbuilderx?.root || '' }
58
- config.android = {
59
- ...config.android,
60
- sdkDir: androidSdk || config.android.sdkDir || '',
61
- jdk: javaHome || config.android.jdk || '',
80
+ const conventionalProperties = path.join(certificateDir, 'keystore.properties')
81
+ const detectedKeystore = (await detectKeystore(certificateDir)) || ''
82
+ const explicitProperties = String(options.keystoreProperties ?? '').trim()
83
+ const explicitKeystore = String(options.keystore ?? '').trim()
84
+
85
+ let packageName = String(resolved.packageName || existingProject.package || existing.package || '')
86
+ let appKey = String(options.appkey ?? existingProject.appKey ?? existing.appKey ?? '')
87
+ let keystorePath = explicitKeystore
88
+ ? absoluteFrom(projectDir, explicitKeystore)
89
+ : absoluteFrom(projectDir, existingSigning.keystore) || detectedKeystore
90
+ let propertiesPath = explicitProperties
91
+ ? path.resolve(projectDir, explicitProperties)
92
+ : absoluteFrom(projectDir, existingSigning.keystoreProperties) ||
93
+ ((await exists(conventionalProperties)) ? conventionalProperties : '')
94
+ let keyAlias =
95
+ String(options.keyAlias ?? '') ||
96
+ String(existingSigning.keyAlias ?? '') ||
97
+ ((await exists(propertiesPath)) ? await readProperty(propertiesPath, 'keyAlias') : '')
98
+ let outputDir =
99
+ toProjectRelative(projectDir, String(existingProject.outputDir ?? existing.outputDir ?? 'apk')) || 'apk'
100
+ const existingDebug = { ...(existingProject.debug ?? existing.debug ?? {}) }
101
+ const debugConfig = {
102
+ ...existingDebug,
103
+ launchActivity: existingDebug.launchActivity ?? 'io.dcloud.PandoraEntry',
104
+ }
105
+
106
+ if (explicitKeystore && !(await exists(keystorePath))) {
107
+ throw new PackError(`找不到 --keystore 指定的证书:${keystorePath}`, EXIT.CONFIG)
108
+ }
109
+ if (explicitProperties && !(await exists(propertiesPath))) {
110
+ throw new PackError(`找不到 --keystore-properties 指定的文件:${propertiesPath}`, EXIT.CONFIG)
111
+ }
112
+
113
+ if (canPrompt(options)) {
114
+ logger.step('初始化配置')
115
+ logger.info('直接回车保留括号内的默认值;密码不会在这里收集,构建时再提供')
116
+ const prompt = new Prompt()
117
+ const fileValidator = makeFileValidator(projectDir)
118
+ try {
119
+ packageName = await prompt.ask({
120
+ question: 'Android 包名',
121
+ defaultValue: packageName,
122
+ validate: validatePackageName,
123
+ })
124
+ appKey = await prompt.ask({
125
+ question: 'DCloud AppKey(32 位十六进制,留空跳过)',
126
+ defaultValue: appKey,
127
+ validate: validateAppKey,
128
+ })
129
+ keystorePath = await prompt.ask({
130
+ question: '签名证书路径(留空跳过)',
131
+ defaultValue: keystorePath,
132
+ validate: fileValidator,
133
+ })
134
+ keyAlias = await prompt.ask({ question: '签名别名 keyAlias', defaultValue: keyAlias })
135
+ propertiesPath = await prompt.ask({
136
+ question: 'keystore.properties 路径(留空则用环境变量提供密码)',
137
+ defaultValue: propertiesPath,
138
+ validate: fileValidator,
139
+ })
140
+ outputDir = await prompt.ask({
141
+ question: 'APK 输出目录',
142
+ defaultValue: outputDir,
143
+ validate: validateRequired,
144
+ })
145
+
146
+ const envAnswers = await askEnvironmentPaths({
147
+ prompt,
148
+ type: /** @type {'cli' | 'hbuilderx'} */ (type),
149
+ logger,
150
+ defaults: { sdkPath, hbuilderxPath, androidSdkPath, jdkPath },
151
+ })
152
+ sdkPath = envAnswers.sdkPath
153
+ hbuilderxPath = envAnswers.hbuilderxPath
154
+ androidSdkPath = envAnswers.androidSdkPath
155
+ jdkPath = envAnswers.jdkPath
156
+
157
+ const useHbuilderx = await prompt.ask({
158
+ question: '使用 HBuilderX 热重载调试?[y/N]',
159
+ defaultValue: debugConfig.strategy === 'hbuilderx' ? 'y' : type === 'hbuilderx' ? 'y' : 'n',
160
+ validate: validateConfirm,
161
+ })
162
+ if (/^y/.test(useHbuilderx)) {
163
+ debugConfig.strategy = 'hbuilderx'
164
+ debugConfig.playground = await prompt.ask({
165
+ question: '基座类型(standard/custom)',
166
+ defaultValue: debugConfig.playground ?? 'custom',
167
+ validate: validatePlayground,
168
+ })
169
+ if (debugConfig.playground === 'custom') {
170
+ debugConfig.customType = await prompt.ask({
171
+ question: '自定义基座类型(local/device)',
172
+ defaultValue: debugConfig.customType ?? 'local',
173
+ validate: validateCustomType,
174
+ })
175
+ }
176
+ } else {
177
+ debugConfig.strategy = 'legacy'
178
+ }
179
+
180
+ const confirmed = await prompt.ask({
181
+ question: '确认写入以上配置?(y/n)',
182
+ validate: validateExplicitConfirm,
183
+ })
184
+ if (/^n/.test(confirmed)) {
185
+ logger.info('已取消,未写入任何配置')
186
+ return { key, config, cancelled: true }
187
+ }
188
+ } finally {
189
+ prompt.close()
190
+ }
62
191
  }
63
- const next = { ...existing }
64
- for (const field of SNAPSHOT_FIELDS) {
65
- delete next[field]
192
+
193
+ // 交互里改过机器级路径后,用最终值重新解析编译器与离线 SDK
194
+ if (hbuilderxPath && hbuilderxPath !== hbuilderx?.root) {
195
+ hbuilderx = await resolveHbuilderx(config, { projectDir, explicit: hbuilderxPath })
66
196
  }
197
+ compiler = await readCompilerVersion(
198
+ { ...existing, ...existingProject, type, projectDir },
199
+ { hbuilderxRoot: hbuilderx?.root },
200
+ )
201
+ if (sdkPath && sdkPath !== sdkRoot) {
202
+ const resolved = await resolveSdkRootInput(sdkPath)
203
+ if (!resolved) {
204
+ throw new PackError(`离线 SDK 路径无效:${sdkPath}`, EXIT.PREFLIGHT, {
205
+ hint: '应指向包含 HBuilder-Integrate-AS 的 Android-SDK@x.yy 目录',
206
+ })
207
+ }
208
+ sdkRoot = resolved
209
+ }
210
+ if (!sdkRoot) {
211
+ sdkRoot = await resolveSdkRoot({
212
+ config,
213
+ explicit: sdkPath || options.sdk,
214
+ existingRoot: existingProject.sdkRoot ?? existing.sdkRoot,
215
+ version: compiler.version,
216
+ })
217
+ }
218
+ sdkVersion = sdkRoot ? await readSdkVersion(sdkRoot) : null
219
+ if (androidSdkPath) {
220
+ androidSdk = androidSdkPath
221
+ }
222
+ if (jdkPath) {
223
+ javaHome = jdkPath
224
+ }
225
+
226
+ if (!keyAlias && propertiesPath && (await exists(propertiesPath))) {
227
+ keyAlias = await readProperty(propertiesPath, 'keyAlias')
228
+ }
229
+
67
230
  const defaultWebBuild = await resolveDefaultWebBuild(type, projectDir)
231
+ const baseWebBuild = existingProject.webBuild ?? existing.webBuild
68
232
  const webBuild =
69
233
  type === 'hbuilderx'
70
- ? existing.webBuild?.mode === 'hbuilderx'
71
- ? existing.webBuild
234
+ ? baseWebBuild?.mode === 'hbuilderx'
235
+ ? baseWebBuild
72
236
  : defaultWebBuild
73
- : (existing.webBuild ?? defaultWebBuild)
237
+ : (baseWebBuild ?? defaultWebBuild)
74
238
 
239
+ const { projectConfig, userEntry } = splitInitConfig({
240
+ projectDir,
241
+ type: /** @type {'cli' | 'hbuilderx'} */ (type),
242
+ packageName,
243
+ appKey,
244
+ outputDir,
245
+ outputPrefix: String(existingProject.outputPrefix ?? existing.outputPrefix ?? ''),
246
+ webBuild,
247
+ signing: {
248
+ keystore: keystorePath,
249
+ keyAlias,
250
+ keystoreProperties: propertiesPath,
251
+ storePasswordEnv: existingSigning.storePasswordEnv,
252
+ keyPasswordEnv: existingSigning.keyPasswordEnv,
253
+ },
254
+ existingProjectConfig: existingProject,
255
+ existingUserEntry: existing,
256
+ debug: debugConfig,
257
+ sdkRoot,
258
+ hbuilderxRoot: hbuilderx?.root ?? existingProject.hbuilderxRoot ?? existing.hbuilderxRoot ?? '',
259
+ })
260
+
261
+ await writeJson(projectConfigFile, projectConfig)
262
+ config.sdk = { ...config.sdk, root: sdkRoot || config.sdk.root || '' }
263
+ config.hbuilderx = { ...config.hbuilderx, root: hbuilderx?.root || config.hbuilderx.root || '' }
264
+ config.android = {
265
+ ...config.android,
266
+ sdkDir: androidSdk || config.android.sdkDir || '',
267
+ jdk: javaHome || config.android.jdk || '',
268
+ }
75
269
  config.projects = {
76
270
  ...(config.projects ?? {}),
77
- [key]: {
78
- ...next,
79
- projectDir,
80
- type,
81
- sdkRoot,
82
- hbuilderxRoot: hbuilderx?.root ?? existing.hbuilderxRoot ?? '',
83
- package: fallbackPackage || resolved.packageName || existing.package || '',
84
- appKey: options.appkey ?? existing.appKey ?? '',
85
- outputDir: existing.outputDir ?? path.join(projectDir, 'apk'),
86
- webBuild,
87
- signing: {
88
- ...(existing.signing ?? {}),
89
- keystore,
90
- keyAlias: options.keyAlias || alias || existing.signing?.keyAlias || 'key0',
91
- keystoreProperties: (await exists(properties))
92
- ? properties
93
- : (existing.signing?.keystoreProperties ?? ''),
94
- storePasswordEnv: existing.signing?.storePasswordEnv ?? 'UNI_PACK_STORE_PASS',
95
- keyPasswordEnv: existing.signing?.keyPasswordEnv ?? 'UNI_PACK_KEY_PASS',
96
- },
97
- debug: {
98
- ...(existing.debug ?? {}),
99
- launchActivity: existing.debug?.launchActivity ?? 'io.dcloud.PandoraEntry',
100
- },
101
- },
271
+ [key]: userEntry,
102
272
  }
103
-
104
273
  await saveConfig(config)
105
274
 
106
275
  logger.step('已写入配置')
107
- logger.info(CONFIG_FILE)
276
+ logger.info(`项目配置:${projectConfigFile}`)
277
+ logger.info(`用户配置:${CONFIG_FILE}`)
108
278
  logger.info(
109
- `项目:${key}(${type === 'hbuilderx' ? 'HBuilderX' : 'CLI'},Vue ${vueVersion}) ${resolved.appid} ${resolved.packageName || '(未配置包名)'}`,
279
+ `项目:${key}(${type === 'hbuilderx' ? 'HBuilderX' : 'CLI'},Vue ${vueVersion}) ${resolved.appid}`,
110
280
  )
111
281
  logger.info(`版本:${resolved.versionName}(${resolved.versionCode}),以 manifest.json 为准`)
282
+ logger.info(`包名:${projectConfig.package || '(未配置)'}`)
283
+ logger.info(`AppKey:${projectConfig.appKey ? '已配置' : '(未配置)'}`)
112
284
  logger.info(`编译器:${compiler.version ?? '未知'}(${compiler.source})`)
113
285
  logger.info(`离线 SDK:${sdkRoot}(${sdkVersion ?? '版本未知'})`)
114
286
  if (compiler.version && sdkVersion && compiler.version !== sdkVersion) {
@@ -122,13 +294,28 @@ export async function initCommand(options) {
122
294
  }
123
295
  logger.info(`Android SDK:${androidSdk || '(未找到)'}`)
124
296
  logger.info(`JDK:${javaHome || '(未找到,构建时用 JAVA_HOME)'}`)
125
- logger.info(`输出:${config.projects[key].outputDir}`)
126
- logger.info(`证书:${keystore || '(未找到,请手工填写 signing.keystore)'}`)
127
- if (!config.projects[key].package) {
297
+ logger.info(`输出:${path.resolve(projectDir, String(projectConfig.outputDir))}`)
298
+ logger.info(`证书:${projectConfig.signing.keystore || '(未配置,构建会失败)'}`)
299
+ if (projectConfig.signing.keystoreProperties) {
300
+ logger.info(`密码文件:${projectConfig.signing.keystoreProperties}`)
301
+ }
302
+ if (!projectConfig.package) {
128
303
  logger.warn('未配置包名:请在 manifest.json 的 app-plus.distribute.android.packagename 填写,或重跑 init 时加 --package')
129
304
  }
130
- if (!config.projects[key].appKey) {
131
- logger.warn('未填写 DCloud AppKey,请在配置的 appKey 字段补齐(后台按 appid + 包名 + 证书 SHA1 绑定)')
305
+ if (!projectConfig.appKey) {
306
+ logger.warn('未填写 DCloud AppKey,请在项目配置 appKey 字段补齐(后台按 appid + 包名 + 证书 SHA1 绑定)')
307
+ }
308
+ if (projectConfig.signing.keystore && !projectConfig.signing.keyAlias) {
309
+ logger.warn('未配置签名别名 keyAlias:构建会失败,可在 keystore.properties 里补 keyAlias')
310
+ }
311
+ if (
312
+ projectConfig.signing.keystore &&
313
+ !projectConfig.signing.keystoreProperties &&
314
+ !hasSigningEnv(projectConfig.signing)
315
+ ) {
316
+ logger.warn(
317
+ `未配置密码来源:提供 keystore.properties,或设置环境变量 ${projectConfig.signing.storePasswordEnv} / ${projectConfig.signing.keyPasswordEnv},或构建时传 --store-password/--key-password`,
318
+ )
132
319
  }
133
320
  if (type === 'hbuilderx' && !hbuilderx) {
134
321
  logger.warn('未找到 HBuilderX:构建时无法编译源码,请用 --hbuilderx <目录> 指定或设置 HBUILDERX_HOME')
@@ -141,7 +328,7 @@ export async function initCommand(options) {
141
328
  }
142
329
  logger.info(`下一步:uni-pack doctor -p "${projectDir}"`)
143
330
 
144
- return { key, config }
331
+ return { key, config, projectConfig }
145
332
  }
146
333
 
147
334
  /**
@@ -149,9 +336,33 @@ export async function initCommand(options) {
149
336
  * @param {{ name: string, packageName: string, appid: string }} resolved
150
337
  */
151
338
  function projectKey(resolved) {
152
- return [resolved.name, resolved.packageName, resolved.appid]
153
- .map((value) => String(value ?? '').toLowerCase().replace(/[^\w]+/g, '-').replace(/^-+|-+$/g, ''))
154
- .find(Boolean) ?? 'app'
339
+ return (
340
+ [resolved.name, resolved.packageName, resolved.appid]
341
+ .map((value) => String(value ?? '').toLowerCase().replace(/[^\w]+/g, '-').replace(/^-+|-+$/g, ''))
342
+ .find(Boolean) ?? 'app'
343
+ )
344
+ }
345
+
346
+ /**
347
+ * @param {string} projectDir
348
+ * @param {string} value
349
+ * @returns {string}
350
+ */
351
+ function absoluteFrom(projectDir, value) {
352
+ const text = String(value ?? '').trim()
353
+ if (!text) {
354
+ return ''
355
+ }
356
+ return path.isAbsolute(text) ? text : path.resolve(projectDir, text)
357
+ }
358
+
359
+ /**
360
+ * @param {{ storePasswordEnv?: string, keyPasswordEnv?: string }} signing
361
+ * @returns {boolean}
362
+ */
363
+ function hasSigningEnv(signing) {
364
+ const names = [signing.storePasswordEnv, signing.keyPasswordEnv].filter(Boolean)
365
+ return names.some((name) => Boolean(process.env[String(name)]))
155
366
  }
156
367
 
157
368
  /**
@@ -0,0 +1,31 @@
1
+ import path from 'node:path'
2
+ import { loadConfig } from '../core/config.js'
3
+ import { Logger } from '../core/logger.js'
4
+
5
+ /**
6
+ * @param {Record<string, any>} options
7
+ */
8
+ export async function projectsCommand(options) {
9
+ const logger = new Logger(options)
10
+ const config = await loadConfig()
11
+ const entries = Object.entries(config.projects ?? {})
12
+ const projects = entries.map(([name, entry]) => ({
13
+ name,
14
+ projectDir: String(entry.projectDir ?? ''),
15
+ type: String(entry.type ?? ''),
16
+ outputDir: String(entry.outputDir ?? ''),
17
+ }))
18
+
19
+ if (projects.length === 0) {
20
+ logger.warn('还没有登记项目:在项目目录执行 uni-pack init -p .')
21
+ } else {
22
+ logger.step(`已登记项目(${projects.length})`)
23
+ for (const project of projects) {
24
+ const basename = path.basename(project.projectDir)
25
+ logger.info(`${project.name}${basename && basename !== project.name ? `(${basename})` : ''} ${project.projectDir} ${project.type || '(未知类型)'}`)
26
+ }
27
+ logger.info('可以这样用:uni-pack build -p <项目名或目录名>')
28
+ }
29
+ logger.output('projects', { ok: true, projects })
30
+ return projects
31
+ }
@@ -1,10 +1,13 @@
1
1
  import path from 'node:path'
2
2
  import { loadConfig, resolveProject } from '../core/config.js'
3
- import { ensureDir, exists } from '../core/fsx.js'
3
+ import { PackError, EXIT } from '../core/errors.js'
4
+ import { exists } from '../core/fsx.js'
4
5
  import { resolveHbuilderx } from '../core/hbuilderx.js'
5
6
  import { Logger } from '../core/logger.js'
6
- import { detectVueVersion, readProjectManifest } from '../core/project.js'
7
+ import { detectVueVersion, normalizeManifest, readProjectManifest } from '../core/project.js'
8
+ import { assertResourceVersion } from '../core/resourceVersion.js'
7
9
  import { runWebBuild } from '../core/webBuild.js'
10
+ import { resolveBuildTempDir, resolveWorkRoot } from '../core/workdir.js'
8
11
  import { writeWgt } from '../core/wgt.js'
9
12
 
10
13
  /**
@@ -17,30 +20,71 @@ export async function wgtCommand(options) {
17
20
  const { manifest, type } = await readProjectManifest(project.projectDir)
18
21
  project.type = type
19
22
  const vueVersion = await detectVueVersion(project.projectDir, manifest, type)
23
+ const resolved = normalizeManifest(
24
+ manifest,
25
+ {
26
+ appid: project.appid,
27
+ name: project.name,
28
+ versionName: project.versionName,
29
+ versionCode: project.versionCode,
30
+ },
31
+ { validate: false },
32
+ )
20
33
 
21
34
  const hbuilderx = type === 'hbuilderx' ? await resolveHbuilderx(config, { project }) : null
35
+ const workRoot = resolveWorkRoot(config, project)
36
+ const buildTemp = resolveBuildTempDir(workRoot)
22
37
  let resourcesDir = path.resolve(
23
38
  project.projectDir,
24
39
  String(project.webBuild?.outputDir ?? (type === 'hbuilderx' ? 'unpackage/dist/build/app-plus' : 'dist/build/app')),
25
40
  )
26
41
  if (options.skipWeb) {
27
42
  if (!(await exists(path.join(resourcesDir, 'app-service.js')))) {
28
- throw new Error('--skip-web 但前端产物不存在,请先构建')
43
+ throw new PackError('--skip-web 但前端产物不存在,请先构建', EXIT.WEB_BUILD, {
44
+ hint: '先执行 pnpm build:app-android(或 HBuilderX 编译),或去掉 --skip-web',
45
+ })
29
46
  }
30
47
  logger.info(`跳过前端构建,使用 ${resourcesDir}`)
31
48
  } else {
32
- resourcesDir = (await runWebBuild(project, logger, { hbuilderx: hbuilderx ?? undefined, vueVersion })).dir
49
+ resourcesDir = (
50
+ await runWebBuild(project, logger, {
51
+ hbuilderx: hbuilderx ?? undefined,
52
+ vueVersion,
53
+ tempDir: buildTemp.tempDir,
54
+ })
55
+ ).dir
33
56
  }
34
57
 
58
+ const resourceVersion = await assertResourceVersion({
59
+ resourcesDir,
60
+ expected: resolved,
61
+ skip: Boolean(options.skipResourceCheck),
62
+ logger,
63
+ })
64
+
35
65
  const appid = String(project.appid ?? manifest.appid)
36
66
  const outputDir = path.resolve(options.out ?? path.join(project.projectDir, 'unpackage/release/wgt'))
37
- await ensureDir(outputDir)
67
+ const versionName = resourceVersion.versionName || resolved.versionName
68
+ const versionCode = resourceVersion.versionCode || resolved.versionCode
38
69
 
39
70
  logger.step('生成 wgt')
40
- const result = await writeWgt({ resourcesDir, outputFile: path.join(outputDir, `${appid}.wgt`) })
71
+ const result = await writeWgt({ resourcesDir, outputDir, appid, versionName, versionCode })
41
72
  logger.success(`wgt:${result.file}(${(result.size / 1024 / 1024).toFixed(1)} MB)`)
73
+ logger.info(`版本清单:${result.meta}`)
74
+ logger.info(`固定入口:${result.latest}(硬链到最新版本)`)
42
75
  logger.info(`sha256:${result.sha256}`)
43
76
 
44
- logger.output('wgt', { ok: true, file: result.file, sha256: result.sha256, size: result.size })
77
+ logger.output('wgt', {
78
+ ok: true,
79
+ file: result.file,
80
+ latest: result.latest,
81
+ meta: result.meta,
82
+ sha256: result.sha256,
83
+ size: result.size,
84
+ versionName,
85
+ versionCode,
86
+ resourceVersion: resourceVersion.versionName,
87
+ resourceVersionCode: resourceVersion.versionCode,
88
+ })
45
89
  return result
46
90
  }
package/src/core/adb.js CHANGED
@@ -17,26 +17,39 @@ export async function mdnsSupported(adb) {
17
17
  }
18
18
 
19
19
  /**
20
- * 解析 `adb mdns services` 输出,兼容 IPv4 与 [IPv6]:port。
20
+ * 解析 `adb mdns services` 输出,兼容两种格式:
21
+ * - 新版 3 列:<实例名> <服务类型> <host>:<port>
22
+ * - 老版 2 列:<实例名含服务类型> <host>:<port>
23
+ * 同时兼容 IPv4 与 [IPv6]:port。
21
24
  * @param {string} stdout
22
25
  * @returns {MdnsService[]}
23
26
  */
24
27
  export function parseMdnsServices(stdout) {
25
28
  /** @type {MdnsService[]} */
26
29
  const services = []
27
- for (const line of stdout.split(/\r?\n/)) {
28
- const match = /^(\S+)\s+(\[[^\]]+\]|[^\s:]+):(\d+)\s*$/.exec(line.trim())
30
+ for (const rawLine of stdout.split(/\r?\n/)) {
31
+ const line = rawLine.trim()
32
+ if (!line || /^List of discovered/i.test(line)) {
33
+ continue
34
+ }
35
+ const fields = line.split(/\s+/)
36
+ if (fields.length < 2) {
37
+ continue
38
+ }
39
+ const addressToken = fields[fields.length - 1]
40
+ const match = /^(\[[^\]]+\]|[^\s:]+):(\d+)$/.exec(addressToken)
29
41
  if (!match) {
30
42
  continue
31
43
  }
32
- const name = match[1]
33
- const host = match[2].replace(/^\[|\]$/g, '')
34
- const type = name.includes('_adb-tls-pairing._tcp')
44
+ const name = fields[0]
45
+ const typeText = fields.length > 2 ? fields.slice(1, -1).join(' ') : name
46
+ const host = match[1].replace(/^\[|\]$/g, '')
47
+ const type = typeText.includes('_adb-tls-pairing._tcp')
35
48
  ? 'pairing'
36
- : name.includes('_adb-tls-connect._tcp')
49
+ : typeText.includes('_adb-tls-connect._tcp')
37
50
  ? 'connect'
38
51
  : 'other'
39
- services.push({ name, type, host, port: Number(match[3]), address: `${host}:${match[3]}` })
52
+ services.push({ name, type, host, port: Number(match[2]), address: `${host}:${match[2]}` })
40
53
  }
41
54
  return services
42
55
  }
@@ -151,15 +164,60 @@ export async function listDevices(adb) {
151
164
  })
152
165
  }
153
166
 
167
+ /**
168
+ * 按完整序列号、型号或唯一子串找设备。多设备时避免手抄长序列号。
169
+ * @param {Device[]} devices
170
+ * @param {string | undefined} input
171
+ * @returns {Device | null}
172
+ */
173
+ export function matchDevice(devices, input) {
174
+ const query = String(input ?? '').trim()
175
+ if (!query) {
176
+ return null
177
+ }
178
+ const exact = devices.find((device) => device.serial === query)
179
+ if (exact) {
180
+ return exact
181
+ }
182
+ const lower = query.toLowerCase()
183
+ const byModel = devices.filter((device) => device.model && device.model.toLowerCase() === lower)
184
+ if (byModel.length === 1) {
185
+ return byModel[0]
186
+ }
187
+ const matches = devices.filter(
188
+ (device) =>
189
+ device.serial.toLowerCase().includes(lower) || (device.model && device.model.toLowerCase().includes(lower)),
190
+ )
191
+ if (matches.length === 1) {
192
+ return matches[0]
193
+ }
194
+ if (matches.length > 1) {
195
+ throw new PackError(`设备不唯一:${query}`, EXIT.DEVICE, {
196
+ hint: `候选:${matches.map(formatDevice).join(';')}`,
197
+ })
198
+ }
199
+ return null
200
+ }
201
+
202
+ /**
203
+ * @param {Device} device
204
+ * @returns {string}
205
+ */
206
+ function formatDevice(device) {
207
+ return `${device.serial}${device.model ? `(${device.model})` : ''}`
208
+ }
209
+
154
210
  /**
155
211
  * @param {Device[]} devices
156
- * @param {string} [serial]
212
+ * @param {string} [input] 完整序列号、型号或唯一子串
157
213
  */
158
- export function pickDevice(devices, serial) {
159
- if (serial) {
160
- const match = devices.find((device) => device.serial === serial)
214
+ export function pickDevice(devices, input) {
215
+ if (input) {
216
+ const match = matchDevice(devices, input)
161
217
  if (!match) {
162
- throw new PackError(`找不到设备:${serial}`, EXIT.DEVICE)
218
+ throw new PackError(`找不到设备:${input}`, EXIT.DEVICE, {
219
+ hint: `可用设备:${devices.map(formatDevice).join(';') || '(无)'};支持序列号后缀或型号`,
220
+ })
163
221
  }
164
222
  return match
165
223
  }