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,424 @@
1
+ import path from 'node:path'
2
+ import { copyFile, readdir, rm } from 'node:fs/promises'
3
+ import { copyTree, ensureDir, exists, readJsonc, readText, writeJson, writeText } from '../fsx.js'
4
+ import { PackError, EXIT } from '../errors.js'
5
+
6
+ const UTS_AAR = 'utsplugin-release.aar'
7
+ const DEFAULT_KOTLIN = '2.2.0'
8
+ const DEFAULT_COROUTINES = '1.8.1'
9
+
10
+ /**
11
+ * HBuilderX 编译后会把 UTS 插件的 Kotlin 源码放到产物/导出目录的 uni_modules 下,
12
+ * 官方离线打包要求把这些源码做成独立的 Android Library 模块。
13
+ * @param {{ projectDir: string, resourcesDir: string }} options
14
+ */
15
+ export async function scanUtsPlugins(options) {
16
+ const roots = [
17
+ path.join(options.resourcesDir, 'uni_modules'),
18
+ path.join(options.projectDir, 'unpackage', 'resources', 'uni_modules'),
19
+ path.join(options.projectDir, 'unpackage', 'resource', 'app-android', 'uni_modules'),
20
+ path.join(options.projectDir, 'unpackage', 'resources', 'app-android', 'uni_modules'),
21
+ ]
22
+
23
+ /** @type {Map<string, any>} */
24
+ const found = new Map()
25
+ for (const root of roots) {
26
+ if (!(await exists(root))) {
27
+ continue
28
+ }
29
+ const entries = await readdir(root, { withFileTypes: true }).catch(() => [])
30
+ for (const entry of entries) {
31
+ if (!entry.isDirectory() || found.has(entry.name)) {
32
+ continue
33
+ }
34
+ const androidDir = path.join(root, entry.name, 'utssdk', 'app-android')
35
+ if (!(await exists(androidDir))) {
36
+ continue
37
+ }
38
+ const sources = await findKotlinSources(path.join(androidDir, 'src'))
39
+ const configFile = path.join(androidDir, 'config.json')
40
+ const config = (await exists(configFile)) ? await readJsonc(configFile).catch(() => ({})) : {}
41
+ found.set(entry.name, {
42
+ name: entry.name,
43
+ androidDir,
44
+ config,
45
+ sourceCount: sources.length,
46
+ usable: sources.length > 0,
47
+ })
48
+ }
49
+ }
50
+ return [...found.values()]
51
+ }
52
+
53
+ /**
54
+ * @param {{ plugins: any[], gradleRoot: string, mainModule: string, compileSdkVersion: number,
55
+ * kotlinVersion?: string, coroutinesVersion?: string, logger: import('../logger.js').Logger }} options
56
+ */
57
+ export async function integrateUtsPlugins(options) {
58
+ const { plugins, gradleRoot, mainModule, compileSdkVersion, logger } = options
59
+ const kotlinVersion = options.kotlinVersion || DEFAULT_KOTLIN
60
+ const coroutinesVersion = options.coroutinesVersion || DEFAULT_COROUTINES
61
+ const usable = plugins.filter((plugin) => plugin.usable)
62
+ for (const plugin of plugins.filter((item) => !item.usable)) {
63
+ logger.warn(`UTS 插件 ${plugin.name} 没有编译后的 Kotlin 源码,已跳过(先执行一次 HBuilderX 编译)`)
64
+ }
65
+ if (usable.length === 0) {
66
+ return { modules: [] }
67
+ }
68
+
69
+ /** @type {Array<any>} */
70
+ const modules = []
71
+ for (const plugin of usable) {
72
+ const module = await createUtsModule({
73
+ plugin,
74
+ gradleRoot,
75
+ mainModule,
76
+ compileSdkVersion,
77
+ kotlinVersion,
78
+ coroutinesVersion,
79
+ })
80
+ modules.push(module)
81
+ logger.detail(`UTS 插件 ${plugin.name} → ${module.moduleName}`)
82
+ }
83
+
84
+ await patchRootBuildGradle(gradleRoot, modules, kotlinVersion)
85
+ await patchSettingsGradle(gradleRoot, modules)
86
+ await patchMainBuildGradle({ gradleRoot, mainModule, modules, kotlinVersion, coroutinesVersion })
87
+ await syncPluginLibs({ gradleRoot, mainModule, modules })
88
+ await registerComponents({ gradleRoot, mainModule, modules })
89
+ logger.success(`UTS 插件已集成:${modules.map((item) => item.name).join(', ')}`)
90
+ return { modules }
91
+ }
92
+
93
+ /**
94
+ * @param {string} dir
95
+ */
96
+ async function findKotlinSources(dir) {
97
+ if (!(await exists(dir))) {
98
+ return []
99
+ }
100
+ const entries = await readdir(dir, { recursive: true, withFileTypes: true }).catch(() => [])
101
+ return entries.filter((entry) => entry.isFile() && entry.name.endsWith('.kt'))
102
+ }
103
+
104
+ /**
105
+ * @param {Object} options
106
+ */
107
+ async function createUtsModule(options) {
108
+ const { plugin, gradleRoot, mainModule, compileSdkVersion, kotlinVersion, coroutinesVersion } = options
109
+ const moduleName = `uts-${sanitize(plugin.name)}`
110
+ const moduleDir = path.join(gradleRoot, moduleName)
111
+ await rm(moduleDir, { recursive: true, force: true })
112
+ const mainDir = path.join(moduleDir, 'src', 'main')
113
+ await ensureDir(mainDir)
114
+
115
+ const androidDir = plugin.androidDir
116
+ const srcDir = path.join(androidDir, 'src')
117
+ if (await exists(srcDir)) {
118
+ await copyTree(srcDir, path.join(mainDir, 'java'))
119
+ }
120
+ if (await exists(path.join(androidDir, 'res'))) {
121
+ await copyTree(path.join(androidDir, 'res'), path.join(mainDir, 'res'))
122
+ }
123
+ if (await exists(path.join(androidDir, 'assets'))) {
124
+ await copyTree(path.join(androidDir, 'assets'), path.join(mainDir, 'assets'))
125
+ }
126
+ if (await exists(path.join(androidDir, 'libs'))) {
127
+ await copyTree(path.join(androidDir, 'libs'), path.join(moduleDir, 'libs'))
128
+ }
129
+
130
+ const { namespace, manifest } = await readManifest(androidDir, plugin.name)
131
+ await writeText(path.join(mainDir, 'AndroidManifest.xml'), manifest)
132
+
133
+ const config = plugin.config ?? {}
134
+ const minSdk = Number(config.minSdkVersion) || 21
135
+ const abis = Array.isArray(config.abis) ? config.abis : []
136
+ const dependencies = []
137
+ for (const item of Array.isArray(config.dependencies) ? config.dependencies : []) {
138
+ if (typeof item === 'string') {
139
+ dependencies.push(` implementation '${item}'`)
140
+ } else if (item && typeof item.source === 'string') {
141
+ dependencies.push(` ${item.source}`)
142
+ }
143
+ }
144
+ const applyPlugins = (Array.isArray(config.project?.plugins) ? config.project.plugins : []).map(
145
+ (id) => `apply plugin: '${id}'`,
146
+ )
147
+
148
+ const abiBlock = abis.length > 0 ? ` ndk {\n abiFilters ${abis.map((abi) => `'${abi}'`).join(', ')}\n }\n` : ''
149
+ const content = [
150
+ "apply plugin: 'com.android.library'",
151
+ "apply plugin: 'kotlin-android'",
152
+ ...applyPlugins,
153
+ '',
154
+ 'android {',
155
+ ` namespace '${namespace}'`,
156
+ ` compileSdkVersion ${compileSdkVersion}`,
157
+ ' defaultConfig {',
158
+ ` minSdkVersion ${minSdk}`,
159
+ abiBlock + ' compileOptions {',
160
+ ' sourceCompatibility JavaVersion.VERSION_1_8',
161
+ ' targetCompatibility JavaVersion.VERSION_1_8',
162
+ ' }',
163
+ ' }',
164
+ ' kotlinOptions {',
165
+ ' jvmTarget = "1.8"',
166
+ ' }',
167
+ '}',
168
+ '',
169
+ 'dependencies {',
170
+ ` compileOnly fileTree(include: ['*.aar'], dir: '../${mainModule}/libs')`,
171
+ " compileOnly fileTree(include: ['*.aar', '*.jar'], dir: './libs')",
172
+ " compileOnly 'com.alibaba:fastjson:1.1.46.android'",
173
+ " compileOnly 'androidx.core:core-ktx:1.6.0'",
174
+ ` compileOnly 'org.jetbrains.kotlin:kotlin-stdlib:${kotlinVersion}'`,
175
+ ` compileOnly 'org.jetbrains.kotlin:kotlin-reflect:${kotlinVersion}'`,
176
+ ` compileOnly 'org.jetbrains.kotlinx:kotlinx-coroutines-core:${coroutinesVersion}'`,
177
+ ` compileOnly 'org.jetbrains.kotlinx:kotlinx-coroutines-android:${coroutinesVersion}'`,
178
+ ...dependencies,
179
+ '}',
180
+ '',
181
+ ].join('\n')
182
+ await writeText(path.join(moduleDir, 'build.gradle'), content)
183
+
184
+ return {
185
+ name: plugin.name,
186
+ moduleName,
187
+ moduleDir,
188
+ namespace,
189
+ androidDir,
190
+ hooksClass: config.hooksClass || '',
191
+ components: Array.isArray(config.components) ? config.components : [],
192
+ project: config.project ?? {},
193
+ }
194
+ }
195
+
196
+ /**
197
+ * @param {string} androidDir
198
+ * @param {string} pluginName
199
+ */
200
+ async function readManifest(androidDir, pluginName) {
201
+ const file = path.join(androidDir, 'AndroidManifest.xml')
202
+ const safe = javaPackageSegment(pluginName)
203
+ if (!(await exists(file))) {
204
+ return {
205
+ namespace: `uts.sdk.${safe}`,
206
+ manifest: '<?xml version="1.0" encoding="utf-8"?>\n<manifest xmlns:android="http://schemas.android.com/apk/res/android" />\n',
207
+ }
208
+ }
209
+ let text = await readText(file)
210
+ const namespace = /package="([^"]+)"/.exec(text)?.[1] || `uts.sdk.${safe}`
211
+ text = text.replace(/\s*package="[^"]*"/, '')
212
+ return { namespace, manifest: text }
213
+ }
214
+
215
+ /**
216
+ * @param {string} value
217
+ */
218
+ function javaPackageSegment(value) {
219
+ const cleaned = String(value ?? 'plugin').replace(/[^\w]/g, '')
220
+ const safe = cleaned || 'plugin'
221
+ return /^\d/.test(safe) ? `_${safe}` : safe
222
+ }
223
+
224
+ /**
225
+ * @param {string} gradleRoot
226
+ * @param {any[]} modules
227
+ * @param {string} kotlinVersion
228
+ */
229
+ async function patchRootBuildGradle(gradleRoot, modules, kotlinVersion) {
230
+ const file = path.join(gradleRoot, 'build.gradle')
231
+ let text = await readText(file)
232
+
233
+ const classpaths = new Set()
234
+ const repositories = new Set()
235
+ for (const module of modules) {
236
+ classpaths.add(`classpath 'org.jetbrains.kotlin:kotlin-gradle-plugin:${kotlinVersion}'`)
237
+ for (const item of Array.isArray(module.project.dependencies) ? module.project.dependencies : []) {
238
+ classpaths.add(`classpath '${item}'`)
239
+ }
240
+ for (const item of Array.isArray(module.project.repositories) ? module.project.repositories : []) {
241
+ repositories.add(String(item))
242
+ }
243
+ }
244
+
245
+ let prepended = false
246
+ if (!text.includes('kotlin-gradle-plugin')) {
247
+ if (/(buildscript\s*\{[\s\S]*?dependencies\s*\{)/.test(text)) {
248
+ text = text.replace(
249
+ /(buildscript\s*\{[\s\S]*?dependencies\s*\{)/,
250
+ (match) => `${match}\n ${[...classpaths].join('\n ')}`,
251
+ )
252
+ } else {
253
+ // 模板没有 buildscript 时补一个,保证 kotlin-android 插件能解析
254
+ const repoLines = [...repositories].map((item) => ` ${item}`).join('\n')
255
+ text = `buildscript {\n repositories {\n google()\n mavenCentral()\n${repoLines}\n }\n dependencies {\n ${[...classpaths].join('\n ')}\n }\n}\n${text}`
256
+ prepended = true
257
+ }
258
+ }
259
+ if (repositories.size > 0) {
260
+ const block = `\n ${[...repositories].join('\n ')}`
261
+ if (!prepended) {
262
+ text = text.replace(/(buildscript\s*\{[\s\S]*?repositories\s*\{)/, (match) => `${match}${block}`)
263
+ }
264
+ text = text.replace(/(allprojects\s*\{[\s\S]*?repositories\s*\{)/, (match) => `${match}${block}`)
265
+ }
266
+ await writeText(file, text)
267
+ }
268
+
269
+ /**
270
+ * @param {string} gradleRoot
271
+ * @param {any[]} modules
272
+ */
273
+ async function patchSettingsGradle(gradleRoot, modules) {
274
+ const file = path.join(gradleRoot, 'settings.gradle')
275
+ let text = await readText(file)
276
+ for (const module of modules) {
277
+ if (!new RegExp(`include\\s+['"]:${escapeRegExp(module.moduleName)}['"]`).test(text)) {
278
+ text += `\ninclude ':${module.moduleName}'`
279
+ }
280
+ }
281
+ await writeText(file, `${text.trimEnd()}\n`)
282
+ }
283
+
284
+ /**
285
+ * @param {{ gradleRoot: string, mainModule: string, modules: any[], kotlinVersion: string, coroutinesVersion: string }} options
286
+ */
287
+ async function patchMainBuildGradle(options) {
288
+ const file = path.join(options.gradleRoot, options.mainModule, 'build.gradle')
289
+ let text = await readText(file)
290
+
291
+ const dependencies = [
292
+ ...options.modules.map((module) => ` implementation project(':${module.moduleName}')`),
293
+ " implementation 'androidx.core:core-ktx:1.6.0'",
294
+ ` implementation "org.jetbrains.kotlin:kotlin-stdlib:${options.kotlinVersion}"`,
295
+ ` implementation "org.jetbrains.kotlin:kotlin-reflect:${options.kotlinVersion}"`,
296
+ ` implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core:${options.coroutinesVersion}"`,
297
+ ` implementation "org.jetbrains.kotlinx:kotlinx-coroutines-android:${options.coroutinesVersion}"`,
298
+ ]
299
+ text = insertIntoBlock(text, 'dependencies', dependencies.join('\n'))
300
+
301
+ const hooks = options.modules.map((module) => module.hooksClass).filter(Boolean)
302
+ if (hooks.length > 0) {
303
+ if (!/buildFeatures\s*\{[\s\S]*?buildConfig\s+true/.test(text)) {
304
+ text = text.replace(/(android\s*\{)/, `$1\n buildFeatures {\n buildConfig true\n }`)
305
+ }
306
+ const escaped = hooks.map((name) => `\\"${name}\\"`).join(',')
307
+ text = insertIntoBlock(text, 'defaultConfig', ` buildConfigField 'String[]', 'UTSHooksClassArray', '{${escaped}}'`)
308
+ }
309
+ await writeText(file, text)
310
+ }
311
+
312
+ /**
313
+ * @param {{ gradleRoot: string, mainModule: string, modules: any[] }} options
314
+ */
315
+ async function syncPluginLibs(options) {
316
+ const mainLibs = path.join(options.gradleRoot, options.mainModule, 'libs')
317
+ const jniLibs = path.join(options.gradleRoot, options.mainModule, 'src', 'main', 'jniLibs')
318
+ for (const module of options.modules) {
319
+ const libsDir = path.join(module.androidDir, 'libs')
320
+ if (!(await exists(libsDir))) {
321
+ continue
322
+ }
323
+ const entries = await readdir(libsDir, { withFileTypes: true })
324
+ for (const entry of entries) {
325
+ if (entry.isFile() && /\.(aar|jar)$/i.test(entry.name)) {
326
+ await ensureDir(mainLibs)
327
+ await copyFile(path.join(libsDir, entry.name), path.join(mainLibs, entry.name))
328
+ continue
329
+ }
330
+ if (entry.isDirectory()) {
331
+ const abiDir = path.join(libsDir, entry.name)
332
+ const files = await readdir(abiDir)
333
+ const sos = files.filter((name) => name.endsWith('.so'))
334
+ if (sos.length > 0) {
335
+ await ensureDir(path.join(jniLibs, entry.name))
336
+ for (const so of sos) {
337
+ await copyFile(path.join(abiDir, so), path.join(jniLibs, entry.name, so))
338
+ }
339
+ }
340
+ }
341
+ }
342
+ }
343
+ }
344
+
345
+ /**
346
+ * @param {{ gradleRoot: string, mainModule: string, modules: any[] }} options
347
+ */
348
+ async function registerComponents(options) {
349
+ const components = options.modules.flatMap((module) => module.components)
350
+ if (components.length === 0) {
351
+ return
352
+ }
353
+ const file = path.join(
354
+ options.gradleRoot,
355
+ options.mainModule,
356
+ 'src',
357
+ 'main',
358
+ 'assets',
359
+ 'dcloud_uniplugins.json',
360
+ )
361
+ /** @type {any} */
362
+ let data = { nativePlugins: [{ plugins: [] }] }
363
+ if (await exists(file)) {
364
+ data = await readJsonc(file).catch(() => data)
365
+ data.nativePlugins ??= [{ plugins: [] }]
366
+ data.nativePlugins[0] ??= { plugins: [] }
367
+ if (!Array.isArray(data.nativePlugins[0].plugins)) {
368
+ data.nativePlugins[0].plugins = []
369
+ }
370
+ }
371
+ const existing = new Set(data.nativePlugins[0].plugins.map((item) => `${item.type}:${item.name}`))
372
+ for (const component of components) {
373
+ if (!component?.name || !component?.class) {
374
+ continue
375
+ }
376
+ if (existing.has(`component:${component.name}`)) {
377
+ continue
378
+ }
379
+ data.nativePlugins[0].plugins.push({ type: 'component', name: component.name, class: component.class })
380
+ }
381
+ await writeJson(file, data)
382
+ }
383
+
384
+ /**
385
+ * 在指定的 Gradle 块(按花括号配对)末尾插入内容。
386
+ * @param {string} text
387
+ * @param {string} block
388
+ * @param {string} snippet
389
+ */
390
+ function insertIntoBlock(text, block, snippet) {
391
+ const match = new RegExp(`\\b${block}\\s*\\{`).exec(text)
392
+ if (!match) {
393
+ throw new PackError(`模板 build.gradle 缺少 ${block} 块`, EXIT.GRADLE)
394
+ }
395
+ const open = match.index + match[0].length - 1
396
+ let depth = 0
397
+ for (let index = open; index < text.length; index += 1) {
398
+ if (text[index] === '{') {
399
+ depth += 1
400
+ } else if (text[index] === '}') {
401
+ depth -= 1
402
+ if (depth === 0) {
403
+ return `${text.slice(0, index)}${snippet}\n${text.slice(index)}`
404
+ }
405
+ }
406
+ }
407
+ throw new PackError(`模板 build.gradle 的 ${block} 块不完整`, EXIT.GRADLE)
408
+ }
409
+
410
+ /**
411
+ * @param {string} value
412
+ */
413
+ function sanitize(value) {
414
+ return String(value ?? 'plugin').replace(/[^\w-]+/g, '-').replace(/^-+|-+$/g, '') || 'plugin'
415
+ }
416
+
417
+ /**
418
+ * @param {string} value
419
+ */
420
+ function escapeRegExp(value) {
421
+ return value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
422
+ }
423
+
424
+ export { UTS_AAR }
@@ -0,0 +1,71 @@
1
+ import { spawn } from 'node:child_process'
2
+ import path from 'node:path'
3
+
4
+ /**
5
+ * @typedef {Object} RunOptions
6
+ * @property {string} [cwd]
7
+ * @property {Record<string, string | undefined>} [env]
8
+ * @property {boolean} [allowFailure]
9
+ * @property {(line: string) => void} [onLine]
10
+ * @property {'inherit' | 'pipe'} [stdio]
11
+ */
12
+
13
+ /**
14
+ * @param {string} command
15
+ * @param {string[]} args
16
+ * @param {RunOptions} [options]
17
+ * @returns {Promise<{ code: number, stdout: string, stderr: string }>}
18
+ */
19
+ export function run(command, args, options = {}) {
20
+ const isWindows = process.platform === 'win32'
21
+ const resolved = isWindows && !path.extname(command) ? `${command}.cmd` : command
22
+ const isScript = isWindows && /\.(bat|cmd)$/i.test(resolved)
23
+ return new Promise((resolve, reject) => {
24
+ const child = spawn(resolved, args, {
25
+ cwd: options.cwd,
26
+ env: { ...process.env, ...options.env },
27
+ shell: isScript,
28
+ windowsHide: true,
29
+ stdio: ['ignore', 'pipe', 'pipe'],
30
+ })
31
+
32
+ let stdout = ''
33
+ let stderr = ''
34
+
35
+ /** @param {Buffer} chunk */
36
+ const consume = (chunk) => {
37
+ const text = chunk.toString()
38
+ if (!options.onLine) {
39
+ return text
40
+ }
41
+ for (const line of text.split(/\r?\n/)) {
42
+ if (line.trim()) {
43
+ options.onLine(line)
44
+ }
45
+ }
46
+ return text
47
+ }
48
+
49
+ child.stdout?.on('data', (chunk) => {
50
+ stdout += consume(chunk)
51
+ })
52
+ child.stderr?.on('data', (chunk) => {
53
+ stderr += consume(chunk)
54
+ })
55
+
56
+ child.on('error', reject)
57
+ child.on('close', (code) => {
58
+ const exitCode = code ?? 1
59
+ if (exitCode !== 0 && !options.allowFailure) {
60
+ const error = new Error(`${command} 退出码 ${exitCode}`)
61
+ // @ts-expect-error 附加诊断信息
62
+ error.stdout = stdout
63
+ // @ts-expect-error 附加诊断信息
64
+ error.stderr = stderr
65
+ reject(error)
66
+ return
67
+ }
68
+ resolve({ code: exitCode, stdout, stderr })
69
+ })
70
+ })
71
+ }