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,488 @@
1
+ import path from 'node:path'
2
+ import { CONFIG_FILE, PROJECT_CONFIG_FILE, loadConfig, resolveDefaultWebBuild, saveConfig } from '../core/config.js'
3
+ import { PackError, EXIT } from '../core/errors.js'
4
+ import { exists, readJson, readText, writeJson } from '../core/fsx.js'
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'
20
+ import { Logger } from '../core/logger.js'
21
+ import { detectVueVersion, normalizeManifest, readProjectManifest, readProjectPackage } from '../core/project.js'
22
+ import { findSdkForVersion, resolveSdkRootInput } from '../core/sdk.js'
23
+ import { readCompilerVersion, readSdkVersion, versionMismatchHint } from '../core/version.js'
24
+
25
+ /**
26
+ * 初始化:探测环境与项目信息,交互式补全项目级配置,
27
+ * 把可共享字段写入 <项目>/uni-pack.config.json,把本机路径写入用户配置。
28
+ * @param {Record<string, any>} options
29
+ */
30
+ export async function initCommand(options) {
31
+ const logger = new Logger(options)
32
+ const projectDir = path.resolve(options.project ?? options.cwd ?? process.cwd())
33
+ const config = await loadConfig()
34
+ const projectConfigFile = path.join(projectDir, PROJECT_CONFIG_FILE)
35
+ const existingProject = (await exists(projectConfigFile)) ? await readJson(projectConfigFile).catch(() => ({})) : {}
36
+
37
+ const { manifest, type } = await readProjectManifest(projectDir)
38
+ const vueVersion = await detectVueVersion(projectDir, manifest, type)
39
+ const fallbackPackage = String(options.package ?? '') || (await readProjectPackage(projectDir))
40
+ const resolved = normalizeManifest(manifest, { package: fallbackPackage }, { validate: false })
41
+ const key = projectKey(resolved)
42
+ const existing = config.projects?.[key] ?? {}
43
+ const existingSigning = { ...(existing.signing ?? {}), ...(existingProject.signing ?? {}) }
44
+
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 || '')
78
+
79
+ const certificateDir = path.join(projectDir, 'certificate/android')
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
+ }
191
+ }
192
+
193
+ // 交互里改过机器级路径后,用最终值重新解析编译器与离线 SDK
194
+ if (hbuilderxPath && hbuilderxPath !== hbuilderx?.root) {
195
+ hbuilderx = await resolveHbuilderx(config, { projectDir, explicit: hbuilderxPath })
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
+
230
+ const defaultWebBuild = await resolveDefaultWebBuild(type, projectDir)
231
+ const baseWebBuild = existingProject.webBuild ?? existing.webBuild
232
+ const webBuild =
233
+ type === 'hbuilderx'
234
+ ? baseWebBuild?.mode === 'hbuilderx'
235
+ ? baseWebBuild
236
+ : defaultWebBuild
237
+ : (baseWebBuild ?? defaultWebBuild)
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
+ }
269
+ config.projects = {
270
+ ...(config.projects ?? {}),
271
+ [key]: userEntry,
272
+ }
273
+ await saveConfig(config)
274
+
275
+ logger.step('已写入配置')
276
+ logger.info(`项目配置:${projectConfigFile}`)
277
+ logger.info(`用户配置:${CONFIG_FILE}`)
278
+ logger.info(
279
+ `项目:${key}(${type === 'hbuilderx' ? 'HBuilderX' : 'CLI'},Vue ${vueVersion}) ${resolved.appid}`,
280
+ )
281
+ logger.info(`版本:${resolved.versionName}(${resolved.versionCode}),以 manifest.json 为准`)
282
+ logger.info(`包名:${projectConfig.package || '(未配置)'}`)
283
+ logger.info(`AppKey:${projectConfig.appKey ? '已配置' : '(未配置)'}`)
284
+ logger.info(`编译器:${compiler.version ?? '未知'}(${compiler.source})`)
285
+ logger.info(`离线 SDK:${sdkRoot}(${sdkVersion ?? '版本未知'})`)
286
+ if (compiler.version && sdkVersion && compiler.version !== sdkVersion) {
287
+ logger.warn(`版本不一致:编译器 ${compiler.version} / 离线 SDK ${sdkVersion}`)
288
+ for (const line of versionMismatchHint({ compiler: compiler.version, sdk: sdkVersion }, { type }).split('\n')) {
289
+ logger.warn(line.trim())
290
+ }
291
+ }
292
+ if (type === 'hbuilderx') {
293
+ logger.info(`HBuilderX:${hbuilderx?.root || '(未找到)'}`)
294
+ }
295
+ logger.info(`Android SDK:${androidSdk || '(未找到)'}`)
296
+ logger.info(`JDK:${javaHome || '(未找到,构建时用 JAVA_HOME)'}`)
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) {
303
+ logger.warn('未配置包名:请在 manifest.json 的 app-plus.distribute.android.packagename 填写,或重跑 init 时加 --package')
304
+ }
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
+ )
319
+ }
320
+ if (type === 'hbuilderx' && !hbuilderx) {
321
+ logger.warn('未找到 HBuilderX:构建时无法编译源码,请用 --hbuilderx <目录> 指定或设置 HBUILDERX_HOME')
322
+ }
323
+ if (!androidSdk) {
324
+ logger.warn('未找到 Android SDK:设置环境变量 ANDROID_HOME,或执行 uni-pack init --android-sdk <目录>')
325
+ }
326
+ if (!javaHome) {
327
+ logger.warn('未找到 JDK:设置环境变量 JAVA_HOME 指向 JDK 17+')
328
+ }
329
+ logger.info(`下一步:uni-pack doctor -p "${projectDir}"`)
330
+
331
+ return { key, config, projectConfig }
332
+ }
333
+
334
+ /**
335
+ * 项目名可能是中文,退化成空串时依次用包名、appid 兜底,避免多个项目共用同一个 key。
336
+ * @param {{ name: string, packageName: string, appid: string }} resolved
337
+ */
338
+ function projectKey(resolved) {
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)]))
366
+ }
367
+
368
+ /**
369
+ * @param {Object} options
370
+ * @param {any} options.config
371
+ * @param {string} [options.explicit]
372
+ * @param {string} [options.existingRoot]
373
+ * @param {string | null} [options.version]
374
+ * @returns {Promise<string>}
375
+ */
376
+ async function resolveSdkRoot(options) {
377
+ const explicit = String(options.explicit ?? '').trim()
378
+ if (explicit) {
379
+ const root = await resolveSdkRootInput(explicit)
380
+ if (!root) {
381
+ throw new PackError(`离线 SDK 路径无效:${explicit}`, EXIT.PREFLIGHT, {
382
+ hint: '--sdk 应指向包含 HBuilder-Integrate-AS 的 Android-SDK@x.yy 目录',
383
+ })
384
+ }
385
+ return root
386
+ }
387
+
388
+ const configured = [options.existingRoot, options.config.sdk?.root, process.env.UNI_SDK_ROOT]
389
+ .map((item) => String(item ?? '').trim())
390
+ .filter(Boolean)
391
+ for (const candidate of configured) {
392
+ const root = await resolveSdkRootInput(candidate)
393
+ if (root) {
394
+ const version = await readSdkVersion(root)
395
+ if (!options.version || !version || version === options.version) {
396
+ return root
397
+ }
398
+ }
399
+ }
400
+
401
+ if (options.version) {
402
+ const matched = await findSdkForVersion(options.config, options.version)
403
+ if (matched) {
404
+ return matched
405
+ }
406
+ }
407
+
408
+ for (const candidate of [options.config.sdk?.root, process.env.UNI_SDK_ROOT]) {
409
+ const root = await resolveSdkRootInput(String(candidate ?? ''))
410
+ if (root) {
411
+ return root
412
+ }
413
+ }
414
+
415
+ throw new PackError('未找到 DCloud Android 离线 SDK', EXIT.PREFLIGHT, {
416
+ hint: [
417
+ '任选一种方式指定:',
418
+ ' 1) uni-pack init -p <项目> --sdk <含 HBuilder-Integrate-AS 的目录>',
419
+ ' 2) 设置环境变量 UNI_SDK_ROOT=<目录>',
420
+ ` 3) 在 ${CONFIG_FILE} 里填写 sdk.root`,
421
+ ].join('\n'),
422
+ })
423
+ }
424
+
425
+ /**
426
+ * @param {string | undefined} explicit
427
+ */
428
+ async function resolveAndroidSdk(explicit) {
429
+ const candidates = [
430
+ explicit,
431
+ process.env.ANDROID_HOME,
432
+ process.env.ANDROID_SDK_ROOT,
433
+ 'C:/develop/android-sdk',
434
+ ]
435
+ for (const candidate of candidates) {
436
+ const value = String(candidate ?? '').trim()
437
+ if (value && (await exists(value))) {
438
+ return path.resolve(value)
439
+ }
440
+ }
441
+ return ''
442
+ }
443
+
444
+ /**
445
+ * @param {string | undefined} explicit
446
+ */
447
+ async function resolveJdk(explicit) {
448
+ const candidates = [
449
+ explicit,
450
+ process.env.JAVA_HOME,
451
+ 'C:/Program Files/Java/jdk-21',
452
+ 'C:/Program Files/Java/jdk-17',
453
+ ]
454
+ for (const candidate of candidates) {
455
+ const value = String(candidate ?? '').trim()
456
+ if (!value) {
457
+ continue
458
+ }
459
+ const java = path.join(value, 'bin', process.platform === 'win32' ? 'java.exe' : 'java')
460
+ if (await exists(java)) {
461
+ return path.resolve(value)
462
+ }
463
+ }
464
+ return ''
465
+ }
466
+
467
+ /**
468
+ * @param {string} dir
469
+ */
470
+ async function detectKeystore(dir) {
471
+ const { readdir } = await import('node:fs/promises')
472
+ if (!(await exists(dir))) {
473
+ return ''
474
+ }
475
+ const entries = await readdir(dir)
476
+ const keystore = entries.find((entry) => entry.endsWith('.keystore') || entry.endsWith('.jks'))
477
+ return keystore ? path.join(dir, keystore) : ''
478
+ }
479
+
480
+ /**
481
+ * @param {string} file
482
+ * @param {string} key
483
+ */
484
+ async function readProperty(file, key) {
485
+ const text = await readText(file)
486
+ const match = new RegExp(`^\\s*${key}\\s*=\\s*(.*)$`, 'm').exec(text)
487
+ return match?.[1]?.trim() ?? ''
488
+ }
@@ -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
+ }
@@ -0,0 +1,90 @@
1
+ import path from 'node:path'
2
+ import { loadConfig, resolveProject } from '../core/config.js'
3
+ import { PackError, EXIT } from '../core/errors.js'
4
+ import { exists } from '../core/fsx.js'
5
+ import { resolveHbuilderx } from '../core/hbuilderx.js'
6
+ import { Logger } from '../core/logger.js'
7
+ import { detectVueVersion, normalizeManifest, readProjectManifest } from '../core/project.js'
8
+ import { assertResourceVersion } from '../core/resourceVersion.js'
9
+ import { runWebBuild } from '../core/webBuild.js'
10
+ import { resolveBuildTempDir, resolveWorkRoot } from '../core/workdir.js'
11
+ import { writeWgt } from '../core/wgt.js'
12
+
13
+ /**
14
+ * @param {Record<string, any>} options
15
+ */
16
+ export async function wgtCommand(options) {
17
+ const logger = new Logger(options)
18
+ const config = await loadConfig()
19
+ const { project } = await resolveProject(config, options.project, options.cwd)
20
+ const { manifest, type } = await readProjectManifest(project.projectDir)
21
+ project.type = type
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
+ )
33
+
34
+ const hbuilderx = type === 'hbuilderx' ? await resolveHbuilderx(config, { project }) : null
35
+ const workRoot = resolveWorkRoot(config, project)
36
+ const buildTemp = resolveBuildTempDir(workRoot)
37
+ let resourcesDir = path.resolve(
38
+ project.projectDir,
39
+ String(project.webBuild?.outputDir ?? (type === 'hbuilderx' ? 'unpackage/dist/build/app-plus' : 'dist/build/app')),
40
+ )
41
+ if (options.skipWeb) {
42
+ if (!(await exists(path.join(resourcesDir, 'app-service.js')))) {
43
+ throw new PackError('--skip-web 但前端产物不存在,请先构建', EXIT.WEB_BUILD, {
44
+ hint: '先执行 pnpm build:app-android(或 HBuilderX 编译),或去掉 --skip-web',
45
+ })
46
+ }
47
+ logger.info(`跳过前端构建,使用 ${resourcesDir}`)
48
+ } else {
49
+ resourcesDir = (
50
+ await runWebBuild(project, logger, {
51
+ hbuilderx: hbuilderx ?? undefined,
52
+ vueVersion,
53
+ tempDir: buildTemp.tempDir,
54
+ })
55
+ ).dir
56
+ }
57
+
58
+ const resourceVersion = await assertResourceVersion({
59
+ resourcesDir,
60
+ expected: resolved,
61
+ skip: Boolean(options.skipResourceCheck),
62
+ logger,
63
+ })
64
+
65
+ const appid = String(project.appid ?? manifest.appid)
66
+ const outputDir = path.resolve(options.out ?? path.join(project.projectDir, 'unpackage/release/wgt'))
67
+ const versionName = resourceVersion.versionName || resolved.versionName
68
+ const versionCode = resourceVersion.versionCode || resolved.versionCode
69
+
70
+ logger.step('生成 wgt')
71
+ const result = await writeWgt({ resourcesDir, outputDir, appid, versionName, versionCode })
72
+ logger.success(`wgt:${result.file}(${(result.size / 1024 / 1024).toFixed(1)} MB)`)
73
+ logger.info(`版本清单:${result.meta}`)
74
+ logger.info(`固定入口:${result.latest}(硬链到最新版本)`)
75
+ logger.info(`sha256:${result.sha256}`)
76
+
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
+ })
89
+ return result
90
+ }