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,81 @@
1
+ import { PackError, EXIT } from '../errors.js'
2
+ import { readText, writeText } from '../fsx.js'
3
+
4
+ /**
5
+ * @typedef {Object} ManifestPatchContext
6
+ * @property {string} packageName
7
+ * @property {string} appKey
8
+ * @property {string[]} permissions
9
+ * @property {{ name: string, required: string }[]} features
10
+ * @property {boolean} debug
11
+ */
12
+
13
+ /**
14
+ * @param {string} file
15
+ * @param {ManifestPatchContext} context
16
+ */
17
+ export async function patchAndroidManifest(file, context) {
18
+ let text = await readText(file)
19
+
20
+ if (!text.includes('package="')) {
21
+ throw new PackError('AndroidManifest.xml 缺少 package 属性', EXIT.PREFLIGHT)
22
+ }
23
+ text = text.replace(/package="[^"]*"/, `package="${context.packageName}"`)
24
+
25
+ text = removeBlocks(text, 'uses-permission')
26
+ text = removeBlocks(text, 'uses-feature')
27
+
28
+ const permissionLines = context.permissions
29
+ .filter((name, index, list) => list.indexOf(name) === index)
30
+ .map((name) => ` <uses-permission android:name="${name}"/>`)
31
+ .join('\n')
32
+ const featureLines = context.features
33
+ .map((feature) => ` <uses-feature android:name="${feature.name}" android:required="${feature.required}"/>`)
34
+ .join('\n')
35
+
36
+ const injected = [permissionLines, featureLines].filter(Boolean).join('\n')
37
+ text = text.replace(/<manifest([^>]*)>/, (match) => `${match}\n\n <!-- uni-pack 注入 -->\n${injected}\n`)
38
+
39
+ // 不硬编码 debuggable,交给 buildType 自动决定(否则 lint 的 HardcodedDebugMode 会直接失败)
40
+ text = text.replace(/\s*android:debuggable="[^"]*"/, '')
41
+ text = setApplicationAttr(text, 'android:usesCleartextTraffic', 'true')
42
+
43
+ if (text.includes('name="dcloud_appkey"')) {
44
+ text = text.replace(/(name="dcloud_appkey"\s*\n?\s*android:value=")[^"]*(")/, `$1${context.appKey}$2`)
45
+ } else {
46
+ text = text.replace(
47
+ /<\/application>/,
48
+ ` <meta-data\n android:name="dcloud_appkey"\n android:value="${context.appKey}" />\n </application>`,
49
+ )
50
+ }
51
+
52
+ if (!text.includes('LEANBACK_LAUNCHER')) {
53
+ text = text.replace(
54
+ /(<category android:name="android\.intent\.category\.LAUNCHER"\s*\/>)/,
55
+ '$1\n <category android:name="android.intent.category.LEANBACK_LAUNCHER" />',
56
+ )
57
+ }
58
+
59
+ await writeText(file, text)
60
+ }
61
+
62
+ /**
63
+ * @param {string} text
64
+ * @param {string} tagName
65
+ */
66
+ function removeBlocks(text, tagName) {
67
+ return text.replace(new RegExp(`\\s*<${tagName}[^>]*/>`, 'g'), '')
68
+ }
69
+
70
+ /**
71
+ * @param {string} text
72
+ * @param {string} attr
73
+ * @param {string} value
74
+ */
75
+ function setApplicationAttr(text, attr, value) {
76
+ const pattern = new RegExp(`${attr}="[^"]*"`)
77
+ if (pattern.test(text)) {
78
+ return text.replace(pattern, `${attr}="${value}"`)
79
+ }
80
+ return text.replace(/<application\b/, `<application\n ${attr}="${value}"`)
81
+ }
@@ -0,0 +1,137 @@
1
+ import path from 'node:path'
2
+ import { copyFile, readdir } from 'node:fs/promises'
3
+ import { PackError, EXIT } from '../errors.js'
4
+ import { ensureDir, exists, readJson, readText, writeText } from '../fsx.js'
5
+
6
+ /**
7
+ * HBuilderX 的 nativeplugins 在离线打包时需要手工集成:AAR 放进 libs,
8
+ * module 类型的插件还要在 dcloud_properties.xml 里注册。
9
+ * @param {Object} options
10
+ * @param {string} options.projectDir
11
+ * @param {string} options.moduleDir simpleDemo 目录
12
+ * @param {string} options.libsDir 构建工程的 simpleDemo/libs
13
+ * @param {import('../logger.js').Logger} options.logger
14
+ */
15
+ export async function applyNativePlugins(options) {
16
+ const sourceDir = path.join(options.projectDir, 'nativeplugins')
17
+ if (!(await exists(sourceDir))) {
18
+ return { plugins: [] }
19
+ }
20
+
21
+ const entries = await readdir(sourceDir, { withFileTypes: true }).catch(() => [])
22
+ /** @type {Array<{ name: string, features: Array<{ name: string, value: string }>, dependencies: string[] }>} */
23
+ const plugins = []
24
+ for (const entry of entries) {
25
+ if (!entry.isDirectory()) {
26
+ continue
27
+ }
28
+ const pluginDir = path.join(sourceDir, entry.name)
29
+ const packageFile = path.join(pluginDir, 'package.json')
30
+ if (!(await exists(packageFile))) {
31
+ options.logger.warn(`原生插件 ${entry.name} 没有 package.json,离线打包需手工集成`)
32
+ continue
33
+ }
34
+ const pkg = await readJson(packageFile).catch(() => ({}))
35
+ const android = pkg?._dp_nativeplugin?.android
36
+ if (!android) {
37
+ options.logger.detail(`原生插件 ${entry.name} 不含 Android 集成信息`)
38
+ continue
39
+ }
40
+
41
+ const copied = await copyPluginLibs(path.join(pluginDir, 'android'), options.libsDir)
42
+ const features = (Array.isArray(android.plugins) ? android.plugins : [])
43
+ .filter((item) => item && item.class)
44
+ .map((item) => ({ name: String(item.name ?? pkg.name ?? entry.name), value: String(item.class) }))
45
+ const dependencies = (Array.isArray(android.dependencies) ? android.dependencies : []).map(String)
46
+ plugins.push({ name: String(pkg.id ?? pkg.name ?? entry.name), features, dependencies })
47
+ options.logger.detail(`原生插件 ${entry.name}:AAR ${copied} 个,feature ${features.length} 个`)
48
+ }
49
+
50
+ if (plugins.length === 0) {
51
+ return { plugins }
52
+ }
53
+
54
+ await registerFeatures(options.moduleDir, plugins, options.logger)
55
+ await injectDependencies(options.moduleDir, plugins, options.logger)
56
+ return { plugins }
57
+ }
58
+
59
+ /**
60
+ * @param {string} androidDir
61
+ * @param {string} libsDir
62
+ * @returns {Promise<number>}
63
+ */
64
+ async function copyPluginLibs(androidDir, libsDir) {
65
+ if (!(await exists(androidDir))) {
66
+ return 0
67
+ }
68
+ const files = await readdir(androidDir, { recursive: true, withFileTypes: true }).catch(() => [])
69
+ let copied = 0
70
+ for (const file of files) {
71
+ if (!file.isFile() || !/\.(aar|jar)$/i.test(file.name)) {
72
+ continue
73
+ }
74
+ const source = path.join(file.parentPath ?? file.path, file.name)
75
+ await ensureDir(libsDir)
76
+ await copyFile(source, path.join(libsDir, file.name))
77
+ copied += 1
78
+ }
79
+ return copied
80
+ }
81
+
82
+ /**
83
+ * @param {string} moduleDir
84
+ * @param {Array<{ features: Array<{ name: string, value: string }> }>} plugins
85
+ * @param {import('../logger.js').Logger} logger
86
+ */
87
+ async function registerFeatures(moduleDir, plugins, logger) {
88
+ const file = path.join(moduleDir, 'src/main/assets/data/dcloud_properties.xml')
89
+ if (!(await exists(file))) {
90
+ logger.warn('找不到 dcloud_properties.xml,原生插件未注册')
91
+ return
92
+ }
93
+ let text = await readText(file)
94
+ const additions = []
95
+ for (const plugin of plugins) {
96
+ for (const feature of plugin.features) {
97
+ if (text.includes(`name="${feature.name}"`)) {
98
+ continue
99
+ }
100
+ additions.push(`\t\t<feature name="${feature.name}" value="${feature.value}"/>`)
101
+ }
102
+ }
103
+ if (additions.length === 0) {
104
+ return
105
+ }
106
+ if (!text.includes('</features>')) {
107
+ throw new PackError('dcloud_properties.xml 结构异常,无法注册原生插件', EXIT.PREFLIGHT)
108
+ }
109
+ text = text.replace('</features>', `${additions.join('\n')}\n\t</features>`)
110
+ await writeText(file, text)
111
+ }
112
+
113
+ /**
114
+ * @param {string} moduleDir
115
+ * @param {Array<{ dependencies: string[] }>} plugins
116
+ * @param {import('../logger.js').Logger} logger
117
+ */
118
+ async function injectDependencies(moduleDir, plugins, logger) {
119
+ const dependencies = [...new Set(plugins.flatMap((plugin) => plugin.dependencies))]
120
+ if (dependencies.length === 0) {
121
+ return
122
+ }
123
+ const file = path.join(moduleDir, 'build.gradle')
124
+ let text = await readText(file)
125
+ const lines = dependencies
126
+ .filter((dependency) => !text.includes(dependency))
127
+ .map((dependency) => ` implementation '${dependency}'`)
128
+ if (lines.length === 0) {
129
+ return
130
+ }
131
+ if (!/dependencies\s*\{/.test(text)) {
132
+ logger.warn('模板 build.gradle 没有 dependencies 块,原生插件依赖未注入')
133
+ return
134
+ }
135
+ text = text.replace(/dependencies\s*\{/, (match) => `${match}\n${lines.join('\n')}`)
136
+ await writeText(file, text)
137
+ }
@@ -0,0 +1,66 @@
1
+ import path from 'node:path'
2
+ import { exists, readText, writeText } from '../fsx.js'
3
+
4
+ /**
5
+ * HBuilderX 项目根的 AndroidManifest.xml 是「原生配置」,云打包时会合并进最终清单。
6
+ * 离线打包至少要把其中的权限与 application 下的 meta-data 带过去(例如 ScopedStorage)。
7
+ * @param {Object} options
8
+ * @param {string} options.targetFile 构建工程的 AndroidManifest.xml
9
+ * @param {string} options.projectDir
10
+ * @param {import('../logger.js').Logger} options.logger
11
+ */
12
+ export async function mergeProjectManifest(options) {
13
+ const source = path.join(options.projectDir, 'AndroidManifest.xml')
14
+ if (!(await exists(source))) {
15
+ return { permissions: 0, metaData: 0 }
16
+ }
17
+
18
+ const sourceText = await readText(source)
19
+ let target = await readText(options.targetFile)
20
+
21
+ const permissions = matchAll(sourceText, /<uses-permission\b[^>]*\/>/g).filter(
22
+ (element) => !target.includes(permissionName(element)),
23
+ )
24
+ const metaData = matchAll(sourceText, /<meta-data\b[\s\S]*?\/>/g).filter(
25
+ (element) => !target.includes(metaDataName(element)),
26
+ )
27
+
28
+ if (permissions.length > 0) {
29
+ target = target.replace(/<application\b/, `${permissions.join('\n ')}\n\n <application`)
30
+ }
31
+ if (metaData.length > 0) {
32
+ target = target.replace(
33
+ /<\/application>/,
34
+ `${metaData.map((element) => ` ${element.trim()}`).join('\n')}\n </application>`,
35
+ )
36
+ }
37
+
38
+ if (permissions.length > 0 || metaData.length > 0) {
39
+ await writeText(options.targetFile, target)
40
+ }
41
+ options.logger.detail(`合并项目 AndroidManifest:权限 ${permissions.length},meta-data ${metaData.length}`)
42
+ return { permissions: permissions.length, metaData: metaData.length }
43
+ }
44
+
45
+ /**
46
+ * @param {string} text
47
+ * @param {RegExp} pattern
48
+ * @returns {string[]}
49
+ */
50
+ function matchAll(text, pattern) {
51
+ return [...text.matchAll(pattern)].map((match) => match[0])
52
+ }
53
+
54
+ /**
55
+ * @param {string} element
56
+ */
57
+ function permissionName(element) {
58
+ return (/android:name="([^"]+)"/.exec(element)?.[1]) ?? element
59
+ }
60
+
61
+ /**
62
+ * @param {string} element
63
+ */
64
+ function metaDataName(element) {
65
+ return (/android:name="([^"]+)"/.exec(element)?.[1]) ?? element
66
+ }
@@ -0,0 +1,57 @@
1
+ import path from 'node:path'
2
+ import { copyTree, ensureDir, readText, writeText } from '../fsx.js'
3
+
4
+ const MARKERS = [
5
+ /\/\/ ===== SMARTPACK[\s\S]*?END =====[^\n]*\n?/g,
6
+ /<!-- ===== SMARTPACK[\s\S]*?END ===== -->\r?\n?/g,
7
+ ]
8
+
9
+ const SKIP = new Set([
10
+ '.gradle',
11
+ '.idea',
12
+ 'build',
13
+ 'local.properties',
14
+ 'simpleDemo/build',
15
+ 'simpleDemo/libs',
16
+ 'simpleDemo/src/main/assets/apps',
17
+ 'simpleDemo/test.jks',
18
+ 'simpleDemo/aw-pack.jks',
19
+ ])
20
+
21
+ /**
22
+ * 从 SDK 复制一份干净模板到工作目录,并清掉上一版插件留下的 SMARTPACK 注入块。
23
+ * @param {string} templateRoot
24
+ * @param {string} targetDir
25
+ */
26
+ export async function prepareTemplate(templateRoot, targetDir) {
27
+ await ensureDir(targetDir)
28
+ await copyTree(
29
+ templateRoot,
30
+ targetDir,
31
+ (relative) => SKIP.has(relative) || relative.startsWith('simpleDemo/build/'),
32
+ )
33
+
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)
40
+ }
41
+
42
+ return targetDir
43
+ }
44
+
45
+ /**
46
+ * @param {string} file
47
+ */
48
+ export async function stripMarkerBlocks(file) {
49
+ const text = await readText(file)
50
+ let stripped = text
51
+ for (const marker of MARKERS) {
52
+ stripped = stripped.replace(marker, '')
53
+ }
54
+ if (stripped !== text) {
55
+ await writeText(file, stripped)
56
+ }
57
+ }