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.
@@ -0,0 +1,157 @@
1
+ import os from 'node:os'
2
+ import path from 'node:path'
3
+ import { PackError, EXIT } from './errors.js'
4
+ import { exists, readJson, writeJson } from './fsx.js'
5
+ import { detectProject, isUniappProject } from './project.js'
6
+
7
+ export const CONFIG_DIR = path.join(os.homedir(), '.uniapp-android-cli')
8
+ export const CONFIG_FILE = path.join(CONFIG_DIR, 'config.json')
9
+ export const PROJECT_CONFIG_FILE = 'uni-pack.config.json'
10
+
11
+ /** @returns {any} */
12
+ export function defaultConfig() {
13
+ return {
14
+ version: 1,
15
+ sdk: {
16
+ root: '',
17
+ searchDirs: [],
18
+ template: 'HBuilder-Integrate-AS',
19
+ libsDir: 'SDK/libs',
20
+ dataDir: 'SDK/assets/data',
21
+ },
22
+ hbuilderx: {
23
+ root: '',
24
+ searchDirs: [],
25
+ },
26
+ android: {
27
+ sdkDir: '',
28
+ buildTools: '',
29
+ jdk: '',
30
+ },
31
+ workDir: path.join(CONFIG_DIR, 'work'),
32
+ projects: {},
33
+ }
34
+ }
35
+
36
+ /** @returns {Promise<any>} */
37
+ export async function loadConfig() {
38
+ const base = defaultConfig()
39
+ if (!(await exists(CONFIG_FILE))) {
40
+ return base
41
+ }
42
+ const user = await readJson(CONFIG_FILE)
43
+ return mergeConfig(base, user)
44
+ }
45
+
46
+ /**
47
+ * @param {any} base
48
+ * @param {any} override
49
+ */
50
+ export function mergeConfig(base, override) {
51
+ return {
52
+ ...base,
53
+ ...override,
54
+ sdk: { ...base.sdk, ...(override?.sdk ?? {}) },
55
+ hbuilderx: { ...base.hbuilderx, ...(override?.hbuilderx ?? {}) },
56
+ android: { ...base.android, ...(override?.android ?? {}) },
57
+ projects: { ...(base.projects ?? {}), ...(override?.projects ?? {}) },
58
+ }
59
+ }
60
+
61
+ /** @param {any} config */
62
+ export async function saveConfig(config) {
63
+ await writeJson(CONFIG_FILE, config)
64
+ }
65
+
66
+ /**
67
+ * @param {any} config
68
+ * @param {string} [nameOrPath]
69
+ * @param {string} [cwd]
70
+ */
71
+ export async function resolveProject(config, nameOrPath, cwd = process.cwd()) {
72
+ const projects = config.projects ?? {}
73
+ const target = nameOrPath ?? cwd
74
+
75
+ if (projects[target]) {
76
+ return finalizeProject(config, target, projects[target])
77
+ }
78
+
79
+ const absolute = path.resolve(target)
80
+ const byPath = Object.entries(projects).find(([, entry]) => {
81
+ const dir = path.resolve(String(entry.projectDir ?? ''))
82
+ return dir.toLowerCase() === absolute.toLowerCase()
83
+ })
84
+ if (byPath) {
85
+ return finalizeProject(config, byPath[0], byPath[1])
86
+ }
87
+
88
+ if (!nameOrPath) {
89
+ if (!(await isUniappProject(absolute))) {
90
+ throw new PackError('当前目录不是 uni-app 项目,请用 --project 指定项目目录或先在配置里登记', EXIT.CONFIG)
91
+ }
92
+ return finalizeProject(config, path.basename(absolute), { projectDir: absolute })
93
+ }
94
+
95
+ if (!(await isUniappProject(absolute))) {
96
+ throw new PackError(`找不到项目:${nameOrPath}(既不是已登记的项目名,也不是 uni-app 项目目录)`, EXIT.CONFIG)
97
+ }
98
+ return finalizeProject(config, path.basename(absolute), { projectDir: absolute })
99
+ }
100
+
101
+ /**
102
+ * CLI 的 Vue 2 项目通常用 build:app-plus(产物 dist/build/app-plus),
103
+ * Vue 3 项目用 build:app-android(产物 dist/build/app)。
104
+ * @param {string} type
105
+ * @param {string} projectDir
106
+ * @returns {Promise<any>}
107
+ */
108
+ export async function resolveDefaultWebBuild(type, projectDir) {
109
+ if (type === 'hbuilderx') {
110
+ return { mode: 'hbuilderx', outputDir: 'unpackage/dist/build/app-plus' }
111
+ }
112
+ const packageFile = path.join(projectDir, 'package.json')
113
+ const pkg = (await exists(packageFile)) ? await readJson(packageFile).catch(() => ({})) : {}
114
+ const scripts = pkg.scripts ?? {}
115
+ if (!scripts['build:app-android'] && scripts['build:app-plus']) {
116
+ return { command: 'pnpm', args: ['run', 'build:app-plus'], outputDir: 'dist/build/app-plus' }
117
+ }
118
+ return { command: 'pnpm', args: ['run', 'build:app-android'], outputDir: 'dist/build/app' }
119
+ }
120
+
121
+ /**
122
+ * @param {any} config
123
+ * @param {string} name
124
+ * @param {any} entry
125
+ */
126
+ async function finalizeProject(config, name, entry) {
127
+ const projectDir = path.resolve(String(entry.projectDir ?? process.cwd()))
128
+ const localFile = path.join(projectDir, PROJECT_CONFIG_FILE)
129
+ const local = (await exists(localFile)) ? await readJson(localFile) : {}
130
+ const layout = await detectProject(projectDir)
131
+ const detectedType = layout.type === 'unknown' ? 'cli' : layout.type
132
+ const type = String(local.type ?? entry.type ?? detectedType)
133
+
134
+ // 输出目录跟着项目走;全局 outputDir 不再参与,避免多项目互相覆盖。
135
+ const outputDir = String(local.outputDir ?? entry.outputDir ?? path.join(projectDir, 'apk'))
136
+
137
+ const defaultWebBuild = await resolveDefaultWebBuild(type, projectDir)
138
+
139
+ const merged = {
140
+ name,
141
+ projectDir,
142
+ inputDir: layout.inputDir,
143
+ ...entry,
144
+ ...local,
145
+ type,
146
+ outputDir: path.isAbsolute(outputDir) ? outputDir : path.resolve(projectDir, outputDir),
147
+ signing: { ...(entry.signing ?? {}), ...(local.signing ?? {}) },
148
+ debug: { ...(entry.debug ?? {}), ...(local.debug ?? {}) },
149
+ webBuild: {
150
+ ...defaultWebBuild,
151
+ ...(entry.webBuild ?? {}),
152
+ ...(local.webBuild ?? {}),
153
+ },
154
+ }
155
+
156
+ return { config, project: merged }
157
+ }
@@ -0,0 +1,152 @@
1
+ import crypto from 'node:crypto'
2
+ import { PackError, EXIT } from './errors.js'
3
+
4
+ /**
5
+ * 手机端把二维码里的 S 当作 mDNS 实例名、P 当作配对码:
6
+ * 设置 → 开发者选项 → 无线调试 → 使用二维码配对设备。
7
+ * 实例名需满足 RFC6763:≤15 字符,字母数字与连字符。
8
+ * @returns {string}
9
+ */
10
+ export function createServiceName() {
11
+ return `unipack-${crypto.randomBytes(3).toString('hex')}`
12
+ }
13
+
14
+ /**
15
+ * @param {string} value
16
+ * @returns {string}
17
+ */
18
+ export function validateServiceName(value) {
19
+ const text = String(value ?? '').trim()
20
+ if (!text) {
21
+ return createServiceName()
22
+ }
23
+ const valid =
24
+ text.length <= 15 &&
25
+ /^[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?$/.test(text) &&
26
+ !text.includes('--') &&
27
+ /[A-Za-z]/.test(text)
28
+ if (!valid) {
29
+ throw new PackError(`服务名不合法:${text}`, EXIT.DEVICE, {
30
+ hint: '长度不超过 15,仅字母数字和连字符,首尾为字母或数字,不能有连续连字符,且至少含一个字母',
31
+ })
32
+ }
33
+ return text
34
+ }
35
+
36
+ /**
37
+ * @returns {string}
38
+ */
39
+ export function createPairingCode() {
40
+ return String(crypto.randomInt(100000, 1000000))
41
+ }
42
+
43
+ /**
44
+ * @param {string} code
45
+ * @returns {string}
46
+ */
47
+ export function validatePairingCode(code) {
48
+ const text = String(code ?? '').trim()
49
+ if (!text) {
50
+ return createPairingCode()
51
+ }
52
+ if (!/^\d{6}$/.test(text)) {
53
+ throw new PackError(`配对码不合法:${text}`, EXIT.DEVICE, { hint: '配对码为 6 位数字' })
54
+ }
55
+ return text
56
+ }
57
+
58
+ /**
59
+ * @param {string} service
60
+ * @param {string} code
61
+ * @returns {string}
62
+ */
63
+ export function pairingPayload(service, code) {
64
+ return `WIFI:T:ADB;S:${service};P:${code};;`
65
+ }
66
+
67
+ /**
68
+ * @typedef {{ name: string, type: string, host: string, port: number, address: string }} MdnsLike
69
+ */
70
+
71
+ /**
72
+ * 手机扫码后广播的实例名不一定等于二维码里的 S:优先取新出现的配对服务,
73
+ * 名字匹配其次,最后才接受当前唯一的配对服务。
74
+ * @param {MdnsLike[]} services
75
+ * @param {Set<string>} seen 扫码前已存在的地址
76
+ * @param {string} service 二维码里的服务名
77
+ * @returns {MdnsLike | null}
78
+ */
79
+ export function selectPairingService(services, seen, service) {
80
+ const pairing = services.filter((item) => item.type === 'pairing')
81
+ const fresh = pairing.filter((item) => !seen.has(item.address))
82
+ const named = fresh.find((item) => item.name.startsWith(`${service}.`))
83
+ if (named) {
84
+ return named
85
+ }
86
+ if (fresh.length === 1) {
87
+ return fresh[0]
88
+ }
89
+ if (pairing.length === 1) {
90
+ return pairing[0]
91
+ }
92
+ return null
93
+ }
94
+
95
+ /**
96
+ * @param {string} value
97
+ * @returns {string}
98
+ */
99
+ export function normalizePairingAddress(value) {
100
+ const text = String(value ?? '').trim()
101
+ if (!text) {
102
+ throw new PackError('请输入配对地址', EXIT.DEVICE, { hint: '手机无线调试页显示的 IP:端口,例如 192.168.1.20:37123' })
103
+ }
104
+ if (/^\[[^\]]+\]:\d+$/.test(text) || /^[^:]+:\d+$/.test(text)) {
105
+ return text
106
+ }
107
+ throw new PackError(`配对地址需要带端口:${text}`, EXIT.DEVICE, {
108
+ hint: '使用手机“使用配对码配对设备”弹窗里显示的 IP:端口,不是连接端口 5555',
109
+ })
110
+ }
111
+
112
+ /**
113
+ * @param {string} address
114
+ * @returns {string}
115
+ */
116
+ export function hostOf(address) {
117
+ const text = String(address ?? '')
118
+ const bracketed = /^\[([^\]]+)\]:\d+$/.exec(text)
119
+ if (bracketed) {
120
+ return bracketed[1]
121
+ }
122
+ return text.replace(/:\d+$/, '')
123
+ }
124
+
125
+ /**
126
+ * @param {string} value
127
+ * @returns {string}
128
+ */
129
+ export function normalizeAddress(value) {
130
+ const text = String(value ?? '').trim()
131
+ if (!text) {
132
+ throw new PackError('请输入设备地址,例如 192.168.1.20:5555', EXIT.DEVICE)
133
+ }
134
+ if (/^\[[^\]]+\]:\d+$/.test(text)) {
135
+ return text
136
+ }
137
+ if (/^\[[^\]]+\]$/.test(text)) {
138
+ return `${text}:5555`
139
+ }
140
+ const colons = (text.match(/:/g) ?? []).length
141
+ if (colons === 0) {
142
+ return `${text}:5555`
143
+ }
144
+ if (colons === 1) {
145
+ const [, port] = text.split(':')
146
+ if (!/^\d+$/.test(port)) {
147
+ throw new PackError(`端口不合法:${text}`, EXIT.DEVICE, { hint: '格式为 <ip>:<端口>,例如 192.168.1.20:5555' })
148
+ }
149
+ return text
150
+ }
151
+ return `[${text}]:5555`
152
+ }
@@ -0,0 +1,36 @@
1
+ export const EXIT = {
2
+ OK: 0,
3
+ CONFIG: 2,
4
+ PREFLIGHT: 3,
5
+ WEB_BUILD: 4,
6
+ GRADLE: 5,
7
+ SIGN: 6,
8
+ DEVICE: 7,
9
+ WGT: 8,
10
+ }
11
+
12
+ export class PackError extends Error {
13
+ /**
14
+ * @param {string} message
15
+ * @param {number} [code]
16
+ * @param {{ hint?: string, cause?: unknown }} [options]
17
+ */
18
+ constructor(message, code = EXIT.CONFIG, options = {}) {
19
+ super(message, { cause: options.cause })
20
+ this.name = 'PackError'
21
+ this.code = code
22
+ this.hint = options.hint
23
+ }
24
+ }
25
+
26
+ /**
27
+ * @param {unknown} error
28
+ * @returns {{ code: number, message: string, hint?: string }}
29
+ */
30
+ export function toFailure(error) {
31
+ if (error instanceof PackError) {
32
+ return { code: error.code, message: error.message, hint: error.hint }
33
+ }
34
+ const message = error instanceof Error ? error.message : String(error)
35
+ return { code: 1, message }
36
+ }
@@ -0,0 +1,172 @@
1
+ import { cp, mkdir, readFile, readdir, rm, stat, writeFile } from 'node:fs/promises'
2
+ import path from 'node:path'
3
+
4
+ /**
5
+ * @param {string} dir
6
+ */
7
+ export async function ensureDir(dir) {
8
+ await mkdir(dir, { recursive: true })
9
+ }
10
+
11
+ /**
12
+ * @param {string} dir
13
+ */
14
+ export async function emptyDir(dir) {
15
+ await rm(dir, { recursive: true, force: true })
16
+ await mkdir(dir, { recursive: true })
17
+ }
18
+
19
+ /**
20
+ * @param {string} file
21
+ */
22
+ export async function readJson(file) {
23
+ return JSON.parse(await readFile(file, 'utf8'))
24
+ }
25
+
26
+ /**
27
+ * HBuilderX 的 manifest.json 是 JSONC:带注释、末尾逗号。字符串里的 // 不能被当成注释。
28
+ * @param {string} text
29
+ * @returns {any}
30
+ */
31
+ export function parseJsonc(text) {
32
+ const source = text.replace(/^/, '')
33
+ let output = ''
34
+ let inString = false
35
+ let escaped = false
36
+ for (let index = 0; index < source.length; index += 1) {
37
+ const char = source[index]
38
+ const next = source[index + 1]
39
+ if (inString) {
40
+ output += char
41
+ if (escaped) {
42
+ escaped = false
43
+ } else if (char === '\\') {
44
+ escaped = true
45
+ } else if (char === '"') {
46
+ inString = false
47
+ }
48
+ continue
49
+ }
50
+ if (char === '"') {
51
+ inString = true
52
+ output += char
53
+ continue
54
+ }
55
+ if (char === '/' && next === '/') {
56
+ while (index < source.length && source[index] !== '\n') {
57
+ index += 1
58
+ }
59
+ output += '\n'
60
+ continue
61
+ }
62
+ if (char === '/' && next === '*') {
63
+ index += 2
64
+ while (index < source.length && !(source[index] === '*' && source[index + 1] === '/')) {
65
+ index += 1
66
+ }
67
+ index += 1
68
+ continue
69
+ }
70
+ if (char === ',') {
71
+ let lookahead = index + 1
72
+ while (lookahead < source.length) {
73
+ if (/\s/.test(source[lookahead])) {
74
+ lookahead += 1
75
+ continue
76
+ }
77
+ if (source[lookahead] === '/' && source[lookahead + 1] === '/') {
78
+ lookahead += 2
79
+ while (lookahead < source.length && source[lookahead] !== '\n') {
80
+ lookahead += 1
81
+ }
82
+ continue
83
+ }
84
+ if (source[lookahead] === '/' && source[lookahead + 1] === '*') {
85
+ lookahead += 2
86
+ while (lookahead < source.length && !(source[lookahead] === '*' && source[lookahead + 1] === '/')) {
87
+ lookahead += 1
88
+ }
89
+ lookahead += 2
90
+ continue
91
+ }
92
+ break
93
+ }
94
+ if (source[lookahead] === '}' || source[lookahead] === ']') {
95
+ continue
96
+ }
97
+ }
98
+ output += char
99
+ }
100
+ return JSON.parse(output)
101
+ }
102
+
103
+ /**
104
+ * @param {string} file
105
+ * @returns {Promise<any>}
106
+ */
107
+ export async function readJsonc(file) {
108
+ return parseJsonc(await readFile(file, 'utf8'))
109
+ }
110
+
111
+ /**
112
+ * @param {string} file
113
+ * @param {unknown} value
114
+ */
115
+ export async function writeJson(file, value) {
116
+ await ensureDir(path.dirname(file))
117
+ await writeFile(file, `${JSON.stringify(value, null, 2)}\n`, 'utf8')
118
+ }
119
+
120
+ /**
121
+ * @param {string} file
122
+ */
123
+ export async function exists(file) {
124
+ try {
125
+ await stat(file)
126
+ return true
127
+ } catch {
128
+ return false
129
+ }
130
+ }
131
+
132
+ /**
133
+ * 递归复制,skip 返回 true 的相对路径会被跳过。
134
+ * @param {string} from
135
+ * @param {string} to
136
+ * @param {(relativePath: string, isDirectory: boolean) => boolean} [skip]
137
+ */
138
+ export async function copyTree(from, to, skip) {
139
+ await cp(from, to, {
140
+ recursive: true,
141
+ filter: (source) => {
142
+ const relative = path.relative(from, source).split(path.sep).join('/')
143
+ if (!relative) {
144
+ return true
145
+ }
146
+ return !(skip?.(relative, false) ?? false)
147
+ },
148
+ })
149
+ }
150
+
151
+ /**
152
+ * @param {string} dir
153
+ */
154
+ export async function listFiles(dir) {
155
+ return readdir(dir, { withFileTypes: true })
156
+ }
157
+
158
+ /**
159
+ * @param {string} file
160
+ */
161
+ export async function readText(file) {
162
+ return readFile(file, 'utf8')
163
+ }
164
+
165
+ /**
166
+ * @param {string} file
167
+ * @param {string} text
168
+ */
169
+ export async function writeText(file, text) {
170
+ await ensureDir(path.dirname(file))
171
+ await writeFile(file, text, 'utf8')
172
+ }
@@ -0,0 +1,75 @@
1
+ import path from 'node:path'
2
+ import { PackError, EXIT } from './errors.js'
3
+ import { ensureDir, writeText } from './fsx.js'
4
+ import { run } from './process.js'
5
+
6
+ /**
7
+ * @param {Object} options
8
+ * @param {string} options.gradlew
9
+ * @param {string} options.cwd
10
+ * @param {'assembleRelease' | 'assembleDebug'} options.task
11
+ * @param {string} options.javaHome
12
+ * @param {string} options.androidSdkDir
13
+ * @param {boolean} [options.offline]
14
+ * @param {import('./logger.js').Logger} options.logger
15
+ */
16
+ export async function runGradle(options) {
17
+ const args = [`:simpleDemo:${options.task}`, '--no-daemon', '--console=plain']
18
+ if (options.offline) {
19
+ args.push('--offline')
20
+ }
21
+
22
+ const logLines = []
23
+ const logFile = path.join(options.cwd, '..', 'logs', `gradle-${Date.now()}.log`)
24
+
25
+ try {
26
+ await run(options.gradlew, args, {
27
+ cwd: options.cwd,
28
+ env: {
29
+ JAVA_HOME: options.javaHome,
30
+ ANDROID_HOME: options.androidSdkDir,
31
+ ANDROID_SDK_ROOT: options.androidSdkDir,
32
+ },
33
+ onLine: (line) => {
34
+ logLines.push(line)
35
+ options.logger.detail(line)
36
+ },
37
+ })
38
+ } catch (error) {
39
+ const output = logLines.join('\n')
40
+ await ensureDir(path.dirname(logFile))
41
+ await writeText(logFile, output)
42
+ throw new PackError('Gradle 构建失败', EXIT.GRADLE, {
43
+ hint: `${diagnose(output)}\n完整日志:${logFile}`,
44
+ cause: error,
45
+ })
46
+ }
47
+
48
+ await ensureDir(path.dirname(logFile))
49
+ await writeText(logFile, logLines.join('\n'))
50
+ options.logger.success(`Gradle ${options.task} 完成`)
51
+ return logFile
52
+ }
53
+
54
+ /**
55
+ * @param {string} output
56
+ */
57
+ function diagnose(output) {
58
+ if (/Could not resolve|Could not download|Could not GET/i.test(output)) {
59
+ return '依赖下载失败:检查网络,或先联网成功构建一次再使用 --offline'
60
+ }
61
+ if (/Manifest merger failed/i.test(output)) {
62
+ return 'AndroidManifest 合并失败:检查包名、权限与模板内容是否冲突'
63
+ }
64
+ if (/Duplicate class/i.test(output)) {
65
+ return 'AAR 重复:检查 libs 目录是否有多余的重复依赖'
66
+ }
67
+ if (/SDK location not found|sdk\.dir/i.test(output)) {
68
+ return 'Android SDK 路径不正确:检查配置里的 android.sdkDir 与 local.properties'
69
+ }
70
+ if (/Unsupported class file major version|Unsupported Java/i.test(output)) {
71
+ return 'JDK 版本不匹配:确认 JAVA_HOME 指向 JDK 17+'
72
+ }
73
+ const failure = output.split('\n').filter((line) => /FAILURE|What went wrong|Caused by|error:/i.test(line)).slice(0, 6)
74
+ return failure.length > 0 ? failure.join('\n') : '查看完整 Gradle 日志定位问题'
75
+ }