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