"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.parseUTSModuleConfigJsonJars = exports.parseUTSModuleLibsJars = exports.kotlinDir = exports.createStderrListener = exports.getUniModulesJars = exports.getUniModulesCacheJars = exports.getUniModulesEncryptCacheJars = exports.checkAndroidVersionTips = exports.resolveJarPath = exports.resolveDexFile = exports.resolveAndroidArchiveOutputPath = exports.resolveD8Args = exports.D8_DEFAULT_ARGS = exports.resolveKotlincArgs = exports.compile = exports.resolveAndroidDepFiles = exports.hasDeps = exports.compileAndroidDex = exports.runKotlinDev = exports.runKotlinProd = exports.createKotlinResolveTypeReferenceName = void 0;
const os_1 = __importDefault(require("os"));
const fs_extra_1 = __importDefault(require("fs-extra"));
const path_1 = __importStar(require("path"));
const adm_zip_1 = __importDefault(require("adm-zip"));
const fast_glob_1 = require("fast-glob");
const shared_1 = require("@vue/shared");
const android_versions_1 = require("android-versions");
const shared_2 = require("./shared");
const utils_1 = require("./utils");
const stacktrace_1 = require("./stacktrace");
const manifest_1 = require("./manifest");
const kotlin_1 = require("./stacktrace/kotlin");
const uvue_1 = require("./uvue");
const dex_1 = require("./manifest/dex");
function createKotlinResolveTypeReferenceName(_namespace, _ast) {
    return (name) => name;
}
exports.createKotlinResolveTypeReferenceName = createKotlinResolveTypeReferenceName;
function parseKotlinPackage(filename) {
    const res = (0, utils_1.resolvePackage)(filename);
    if (!res) {
        return { id: '', package: '' };
    }
    return {
        id: res.id,
        package: (0, utils_1.parseKotlinPackageWithPluginId)(res.name, res.is_uni_modules),
    };
}
function isAppIOS(filename) {
    return (0, shared_2.normalizePath)(filename).includes('/utssdk/app-ios/');
}
async function runKotlinProd(filename, { outFilename, components, customElements, uniModuleId, isPlugin, isModule, isX, isSingleThread, isExtApi, hookClass, extApis, transform, sourceMap, uniModules, }) {
    // 文件有可能是 app-ios 里边的，因为编译到 android 时，为了保证不报错，可能会去读取 ios 下的 uts
    if (isAppIOS(filename)) {
        return;
    }
    const inputDir = process.env.UNI_INPUT_DIR;
    const outputDir = process.env.UNI_OUTPUT_DIR;
    const result = await compile(filename, {
        inputDir: isModule ? (0, uvue_1.uvueOutDir)('app-android') : inputDir,
        outputDir,
        sourceMap: !!sourceMap,
        components,
        customElements,
        isX,
        isSingleThread,
        isPlugin,
        isModule,
        isExtApi,
        extApis,
        transform,
        uniModules,
        outFilename,
    });
    if (!result) {
        return;
    }
    if (result.error) {
        throw (0, stacktrace_1.parseUTSSyntaxError)(result.error, inputDir);
    }
    const autoImportUniCloud = (0, utils_1.shouldAutoImportUniCloud)();
    const useUniCloudApi = result.inject_apis &&
        result.inject_apis.find((api) => api.startsWith('uniCloud.'));
    if (autoImportUniCloud && !useUniCloudApi) {
        result.inject_apis = result.inject_apis || [];
        result.inject_apis.push('uniCloud.importObject');
    }
    if (result.inject_apis && result.inject_apis.length) {
        if (isModule) {
            // noop
        }
        else if (isX && process.env.UNI_UTS_COMPILER_TYPE === 'cloud') {
            (0, utils_1.updateManifestModulesByCloud)('app-android', inputDir, result.inject_apis, extApis);
        }
        else {
            (0, utils_1.addPluginInjectApis)(result.inject_apis);
        }
    }
    // module 模式，不需要处理资源
    if (!isModule) {
        (0, utils_1.genUTSPlatformResource)(filename, {
            isX,
            pluginId: uniModuleId,
            inputDir,
            outputDir,
            platform: 'app-android',
            extname: '.kt',
            components,
            customElements,
            package: parseKotlinPackage(filename).package + '.',
            hookClass,
            result,
            provider: (0, utils_1.resolveConfigProvider)('app-android', uniModuleId, transform),
            uniModules,
        });
    }
    return result;
}
exports.runKotlinProd = runKotlinProd;
async function runKotlinDev(filename, { components, customElements, isX, isSingleThread, isPlugin, isExtApi, cacheDir, pluginRelativeDir, is_uni_modules, extApis, transform, sourceMap, uniModules, rewriteConsoleExpr, }) {
    // 文件有可能是 app-ios 里边的，因为编译到 android 时，为了保证不报错，可能会去读取 ios 下的 uts
    if (isAppIOS(filename)) {
        return;
    }
    const inputDir = process.env.UNI_INPUT_DIR;
    const outputDir = process.env.UNI_OUTPUT_DIR;
    const result = (await compile(filename, {
        inputDir,
        outputDir,
        sourceMap,
        components,
        customElements,
        isX,
        isSingleThread,
        isPlugin,
        isExtApi,
        extApis,
        transform,
        uniModules,
    }));
    if (!result) {
        return;
    }
    if (result.error) {
        throw (0, stacktrace_1.parseUTSSyntaxError)(result.error, inputDir);
    }
    result.type = 'kotlin';
    result.changed = [];
    const kotlinFile = (0, utils_1.resolveUTSPlatformFile)(filename, {
        isX,
        inputDir,
        outputDir,
        platform: 'app-android',
        extname: '.kt',
        package: '',
        result,
    });
    // 开发模式下，需要生成 dex
    if (fs_extra_1.default.existsSync(kotlinFile)) {
        const compilerServer = (0, utils_1.getCompilerServer)('uniapp-runextension');
        if (!compilerServer) {
            throw new Error(`项目使用了uts插件，正在安装 uts Android 运行扩展...`);
        }
        const { checkDependencies, checkRResources } = compilerServer;
        let deps = [];
        if (checkDependencies) {
            deps = await checkDeps(filename, checkDependencies);
        }
        let resDeps = [];
        if (checkRResources) {
            resDeps = await checkRes(filename, checkRResources);
        }
        // time = Date.now()
        const jarFile = resolveJarPath('app-android', cacheDir, pluginRelativeDir, kotlinFile);
        const waiting = { done: undefined };
        const kotlinFiles = [kotlinFile].concat(result.chunks?.map((chunk) => path_1.default.resolve(path_1.default.dirname(kotlinFile), chunk)) || []);
        const uniModuleDeps = [];
        if (transform?.uniExtApiProviderServicePlugin) {
            uniModuleDeps.push(...getUniModulesCacheJarsByPlugin(cacheDir, transform.uniExtApiProviderServicePlugin));
        }
        const extraJars = resolveLibs(filename)
            .concat(deps)
            .concat(resDeps)
            .concat(uniModuleDeps);
        const depJars = uniModules.length
            ? // 加密插件已经迁移到普通插件目录了，理论上不需要了
                getUniModulesEncryptCacheJars(cacheDir, uniModules) // 加密插件jar
                    .concat(getUniModulesCacheJars(cacheDir, uniModules)) // 普通插件jar
                    .concat(getUniModulesJars(outputDir, uniModules)) // cli版本插件jar（没有指定cache的时候,也不应该需要了，默认cache目录即可）
            : [];
        const { srcFiles, destFiles } = (0, utils_1.copyPlatformNativeLanguageFiles)(path_1.default.resolve(inputDir, pluginRelativeDir, 'utssdk', 'app-android'), path_1.default.resolve(outputDir, pluginRelativeDir, 'utssdk', 'app-android'), ['.kt', '.java'], rewriteConsoleExpr);
        kotlinFiles.push(...destFiles);
        result.deps = [...(result.deps || []), ...srcFiles];
        const { code, msg } = await compileAndroidDex(isX, compilerServer, kotlinFiles, jarFile, (0, utils_1.resolveSourceMapFile)(outputDir, kotlinFile), extraJars.concat(depJars), createStderrListener(outputDir, (0, shared_2.resolveSourceMapPath)(), waiting, kotlin_1.hbuilderFormatter));
        result.code = code;
        result.msg = msg;
        // 等待 stderrListener 执行完毕
        if (waiting.done) {
            await waiting.done;
        }
        if (!code) {
            try {
                // 其他插件或 x 需要该插件的 jar 做编译
                // fs.unlinkSync(jarFile)
                // 短期内先不删除，方便排查问题
                // fs.unlinkSync(kotlinFile)
            }
            catch (e) { }
            const dexFile = resolveDexFile(jarFile);
            if (fs_extra_1.default.existsSync(dexFile)) {
                const newDexFile = (0, manifest_1.restoreDex)(pluginRelativeDir, cacheDir, outputDir, is_uni_modules);
                if (newDexFile && cacheDir) {
                    // 缓存index.kt文件
                    (0, dex_1.storeIndexKt)(kotlinFile, pluginRelativeDir, cacheDir);
                }
                result.changed = [
                    (0, shared_2.normalizePath)(path_1.default.relative(outputDir, newDexFile || dexFile)),
                ];
            }
        }
        else if (msg) {
            console.error(msg);
        }
        // else {
        //   throw `${normalizePath(
        //     path.relative(process.env.UNI_INPUT_DIR, filename)
        //   )} 编译失败`
        // }
    }
    return result;
}
exports.runKotlinDev = runKotlinDev;
async function compileAndroidDex(isX, compilerServer, kotlinFiles, jarFile, sourceMapPath, depJars, stderrListener) {
    const inputDir = process.env.UNI_INPUT_DIR;
    const { getKotlincHome, compile: compileDex } = compilerServer;
    const options = {
        pageCount: 0,
        kotlinc: resolveKotlincArgs(kotlinFiles, jarFile, getKotlincHome(), getKotlinCompileJars(isX, depJars, compilerServer)),
        d8: resolveD8Args(jarFile),
        sourceRoot: inputDir,
        sourceMapPath,
        stderrListener,
    };
    // console.log('dex compile options: ', options)
    const result = await compileDex(options, inputDir);
    // console.log('dex compile time: ' + (Date.now() - time) + 'ms')
    return result;
}
exports.compileAndroidDex = compileAndroidDex;
function getKotlinCompileJars(isX, depJars, { getDefaultJar, getCompilerJar }) {
    if (getCompilerJar) {
        return getCompilerJar(depJars, isX ? 2 : undefined);
    }
    return getDefaultJar(isX ? 2 : undefined).concat(depJars);
}
function checkDeps(filename, checkDependencies) {
    const configJsonFile = resolveConfigJsonFile(filename);
    if (configJsonFile && hasDeps(configJsonFile)) {
        return checkDependencies(configJsonFile).then(({ code, msg, data }) => {
            if (code !== 0) {
                console.error(msg);
                return [];
            }
            return data;
        });
    }
    return Promise.resolve([]);
}
function hasDeps(configJsonFile) {
    const deps = (0, shared_2.parseJson)(fs_extra_1.default.readFileSync(configJsonFile, 'utf8')).dependencies || [];
    if ((0, shared_1.isArray)(deps) && deps.length) {
        return true;
    }
    return false;
}
exports.hasDeps = hasDeps;
function checkRes(filename, checkRResources) {
    const resDir = resolveResDir(filename);
    if (resDir) {
        return checkRResources(resDir).then(({ code, msg, data }) => {
            if (code !== 0) {
                console.error(msg);
                return [];
            }
            return [data.jarPath];
        });
    }
    return Promise.resolve([]);
}
function resolveResDir(filename) {
    const resDir = path_1.default.resolve((0, utils_1.resolveAndroidDir)(filename), 'res');
    if (fs_extra_1.default.existsSync(resDir)) {
        return resDir;
    }
}
function resolveAndroidResourceClass(filename) {
    const resDir = resolveResDir(filename);
    if (resDir && fs_extra_1.default.readdirSync(resDir).length) {
        const pkg = resolveAndroidManifestPackage(filename);
        if (pkg) {
            return pkg + '.R';
        }
    }
}
const packageRe = /\s+package="(.*)"/;
function resolveAndroidManifestPackage(filename) {
    const manifestXmlPath = path_1.default.resolve((0, utils_1.resolveAndroidDir)(filename), 'AndroidManifest.xml');
    if (fs_extra_1.default.existsSync(manifestXmlPath)) {
        const matches = fs_extra_1.default.readFileSync(manifestXmlPath, 'utf8').match(packageRe);
        if (matches && matches[1]) {
            return matches[1];
        }
    }
}
const deps = ['AndroidManifest.xml', 'config.json'];
function resolveAndroidDepFiles(filename) {
    const dir = (0, utils_1.resolveAndroidDir)(filename);
    return deps.map((dep) => path_1.default.resolve(dir, dep));
}
exports.resolveAndroidDepFiles = resolveAndroidDepFiles;
function resolveConfigJsonFile(filename) {
    const configJsonFile = path_1.default.resolve((0, utils_1.resolveAndroidDir)(filename), 'config.json');
    if (fs_extra_1.default.existsSync(configJsonFile)) {
        return configJsonFile;
    }
}
const DEFAULT_IMPORTS = [
    'kotlinx.coroutines.async',
    'kotlinx.coroutines.CoroutineScope',
    'kotlinx.coroutines.Deferred',
    'kotlinx.coroutines.Dispatchers',
    'io.dcloud.uts.Map',
    'io.dcloud.uts.Set',
    'io.dcloud.uts.UTSAndroid',
    'io.dcloud.uts.*',
    'io.dcloud.uniapp.*',
];
const DEFAULT_IMPORTS_VUE_X = [
    'io.dcloud.uniapp.framework.*',
    'io.dcloud.uniapp.vue.*',
    'io.dcloud.uniapp.vue.shared.*',
];
const DEFAULT_IMPORTS_X = ['io.dcloud.uniapp.runtime.*'];
async function compile(filename, { inputDir, outputDir, sourceMap, components, customElements, isX, isSingleThread, isPlugin, isModule, isExtApi, extApis, transform, uniModules, outFilename, }) {
    const { bundle, UTSTarget } = (0, utils_1.getUTSCompiler)();
    // let time = Date.now()
    const imports = [...DEFAULT_IMPORTS];
    if (isX) {
        imports.push(...DEFAULT_IMPORTS_X);
        if (!process.env.UNI_UTS_DISABLE_X_IMPORT) {
            imports.push(...DEFAULT_IMPORTS_VUE_X);
        }
    }
    const rClass = resolveAndroidResourceClass(filename);
    if (rClass) {
        imports.push(rClass);
    }
    if ((0, utils_1.shouldAutoImportUniCloud)()) {
        imports.push('io.dcloud.unicloud.*');
    }
    // 本地 provider
    if (transform?.uniExtApiProviderServicePlugin) {
        imports.push((0, utils_1.parseKotlinPackageWithPluginId)(transform.uniExtApiProviderServicePlugin, true) + '.*');
    }
    else {
        // 本地 provider 的时候，不要引入 io.dcloud.uniapp.extapi.*，因为里边包含了相同的类型定义
        imports.push('io.dcloud.uniapp.extapi.*');
    }
    const componentsCode = (0, utils_1.genComponentsCode)(filename, components, isX);
    const { package: pluginPackage, id: pluginId } = parseKotlinPackage(filename);
    const input = {
        root: (0, utils_1.resolveBundleInputRoot)('app-android', inputDir),
        filename: (0, utils_1.resolveBundleInputFileName)('app-android', filename),
        pluginId: isPlugin ? pluginId : '',
        paths: {
            vue: 'io.dcloud.uniapp.vue',
            '@dcloudio/uni-app': 'io.dcloud.uniapp.framework',
            '@dcloudio/uni-runtime': 'io.dcloud.uniapp.framework.runtime',
        },
        uniModules,
        uniModulesPrefix: process.env.UNI_UTS_MODULE_PREFIX || '',
    };
    // 必须判断input.filename，因为input.filename可能跟filename不一样（可能会变成.uvue目录的文件）
    const isUTSFileExists = fs_extra_1.default.existsSync(input.filename);
    if (componentsCode) {
        if (!isUTSFileExists) {
            input.fileContent = componentsCode;
        }
        else {
            input.fileContent =
                fs_extra_1.default.readFileSync(input.filename, 'utf8') + `\n` + componentsCode;
        }
    }
    else {
        // uts文件不存在，且也无组件
        if (!isUTSFileExists) {
            return;
        }
    }
    const options = {
        mode: process.env.NODE_ENV,
        hbxVersion: process.env.HX_Version || process.env.UNI_COMPILER_VERSION,
        input,
        output: {
            outFilename: outFilename ? outFilename : undefined,
            isX,
            isSingleThread,
            isPlugin,
            isModule,
            isExtApi,
            outDir: outputDir,
            package: pluginPackage,
            sourceMap: sourceMap ? (0, utils_1.resolveUTSSourceMapPath)() : false,
            extname: 'kt',
            imports,
            logFilename: isModule ? false : true,
            noColor: !(0, utils_1.isColorSupported)(),
            split: true,
            splitClass: false,
            disableSplitManifest: true,
            transform: {
                uniExtApiDefaultNamespace: 'io.dcloud.uniapp.extapi',
                uniExtApiNamespaces: extApis,
                uniExtApiDefaultParameters: (0, utils_1.parseExtApiDefaultParameters)(),
                enableNarrowType: false, // 这里的启用是把部分typeof转换成instanceof，这样确实好一点，但会引发一些kotlin之类的警告，暂不开启
                enableGenericsParameterDefaults: (0, utils_1.isEnableGenericsParameterDefaults)(),
                enableInlineReified: (0, utils_1.isEnableInlineReified)(),
                ...transform,
            },
        },
    };
    // console.log('bundle options', options)
    const result = await bundle(UTSTarget.KOTLIN, options);
    sourceMap &&
        (0, utils_1.moveRootIndexSourceMap)(filename, {
            isX,
            inputDir,
            outputDir,
            platform: 'app-android',
            extname: '.kt',
            package: '',
            result,
        });
    return (0, utils_1.normalizeUTSResult)('app-android', result);
}
exports.compile = compile;
function resolveKotlincArgs(files, dest, kotlinc, jars) {
    return [
        ...files,
        '-cp',
        resolveClassPath(jars),
        '-d',
        dest,
        '-kotlin-home',
        kotlinc,
        `-Xplugin=${path_1.default.resolve(__dirname, '../lib/kotlin/lib/uts-kotlin-compiler-plugin.jar')}`,
        '-P',
        'plugin:io.dcloud.uts.kotlin:tag=UTS',
        '-P',
        'plugin:io.dcloud.uts.kotlin:console=true',
    ];
}
exports.resolveKotlincArgs = resolveKotlincArgs;
exports.D8_DEFAULT_ARGS = ['--min-api', '19'];
function resolveD8Args(filename) {
    return [filename, ...exports.D8_DEFAULT_ARGS, '--output', resolveDexPath(filename)];
}
exports.resolveD8Args = resolveD8Args;
function resolveLibs(filename) {
    const libsPath = path_1.default.resolve((0, utils_1.resolveAndroidDir)(filename), 'libs');
    const libs = [];
    if (fs_extra_1.default.existsSync(libsPath)) {
        libs.push(...(0, fast_glob_1.sync)('*.jar', { cwd: libsPath, absolute: true }));
        const zips = (0, fast_glob_1.sync)('*.aar', { cwd: libsPath });
        zips.forEach((name) => {
            const outputPath = resolveAndroidArchiveOutputPath(name);
            // 每次都解压，避免aar或jar更新后，未解压
            const zip = new adm_zip_1.default(path_1.default.resolve(libsPath, name));
            zip.extractAllTo(outputPath, true);
            libs.push(...(0, fast_glob_1.sync)('**/*.jar', {
                cwd: outputPath,
                absolute: true,
            }));
        });
    }
    return libs;
}
function resolveAndroidArchiveOutputPath(aar) {
    return path_1.default.resolve(kotlinAARDir(process.env.UNI_OUTPUT_DIR), aar.replace('.aar', ''));
}
exports.resolveAndroidArchiveOutputPath = resolveAndroidArchiveOutputPath;
function resolveDexFile(jarFile) {
    return (0, shared_2.normalizePath)(path_1.default.resolve(path_1.default.dirname(jarFile), 'classes.dex'));
}
exports.resolveDexFile = resolveDexFile;
function resolveDexPath(filename) {
    return path_1.default.dirname(filename);
}
function resolveJarPath(platform, cacheDir, pluginRelativeDir, filename) {
    if (cacheDir) {
        return (0, path_1.join)(cacheDir, platform, 'uts', pluginRelativeDir, path_1.default.basename(filename).replace(path_1.default.extname(filename), '.jar'));
    }
    return filename.replace(path_1.default.extname(filename), '.jar');
}
exports.resolveJarPath = resolveJarPath;
function resolveClassPath(jars) {
    return jars.join(os_1.default.platform() === 'win32' ? ';' : ':');
}
function checkAndroidVersionTips(pluginId, pluginDir, is_uni_modules) {
    const configJsonFile = (0, path_1.join)(pluginDir, is_uni_modules ? 'utssdk' : '', 'app-android', 'config.json');
    if (configJsonFile && fs_extra_1.default.existsSync(configJsonFile)) {
        try {
            const configJson = (0, shared_2.parseJson)(fs_extra_1.default.readFileSync(configJsonFile, 'utf8'));
            const minSdkVersion = process.env.UNI_APP_X === 'true' ? 21 : 19;
            if (configJson.minSdkVersion &&
                parseInt(configJson.minSdkVersion) > minSdkVersion) {
                const androidVersion = (0, android_versions_1.get)(configJson.minSdkVersion);
                if (androidVersion) {
                    return `uts插件[${pluginId}]需在 Android ${androidVersion.semver} 版本及以上方可正常使用`;
                }
            }
        }
        catch (e) { }
    }
}
exports.checkAndroidVersionTips = checkAndroidVersionTips;
function getUniModulesEncryptCacheJars(cacheDir, plugins) {
    if (cacheDir) {
        return (0, fast_glob_1.sync)(`uni_modules/${createPluginGlob(plugins)}/*.jar`, {
            cwd: cacheDir,
            absolute: true,
        });
    }
    return [];
}
exports.getUniModulesEncryptCacheJars = getUniModulesEncryptCacheJars;
function getUniModulesCacheJarsByPlugin(cacheDir, plugin) {
    if (cacheDir) {
        return (0, fast_glob_1.sync)('app-android/uts/uni_modules/' + plugin + '/index.jar', {
            cwd: cacheDir,
            absolute: true,
        });
    }
    return [];
}
function getUniModulesCacheJars(cacheDir, plugins) {
    if (cacheDir) {
        return (0, fast_glob_1.sync)(`app-android/uts/uni_modules/${createPluginGlob(plugins)}/index.jar`, {
            cwd: cacheDir,
            absolute: true,
        });
    }
    return [];
}
exports.getUniModulesCacheJars = getUniModulesCacheJars;
function getUniModulesJars(outputDir, plugins) {
    return (0, fast_glob_1.sync)(`${createPluginGlob(plugins)}/utssdk/app-android/index.jar`, {
        cwd: path_1.default.resolve(outputDir, 'uni_modules'),
        absolute: true,
    });
}
exports.getUniModulesJars = getUniModulesJars;
function createPluginGlob(plugins) {
    if (plugins && plugins.length) {
        return plugins.length > 1 ? `(${plugins.join('|')})` : plugins[0];
    }
    return '*';
}
function createStderrListener(inputDir, sourceMapDir, waiting, format) {
    return async function stderrListener(data) {
        waiting.done = new Promise(async (resolve) => {
            let message = data.toString().trim();
            if (message) {
                try {
                    const messages = JSON.parse(message).filter((msg) => {
                        if (
                        // 暂时屏蔽 Unchecked cast: Any? to UTSArray<String>​
                        // Unchecked cast: Any to UTSArray<String>
                        msg.type === 'warning' &&
                            msg.message.includes('Unchecked cast: Any') &&
                            msg.message.includes('to UTSArray<')) {
                            return false;
                        }
                        return true;
                    });
                    if (messages.length) {
                        const msg = await (0, stacktrace_1.parseUTSKotlinStacktrace)(messages, {
                            inputDir,
                            sourceMapDir,
                            replaceTabsWithSpace: true,
                            format,
                        });
                        if (msg) {
                            // 异步输出，保证插件编译失败的日志在他之前输出，不能使用process.nextTick
                            setTimeout(() => {
                                console.log(msg);
                            });
                        }
                    }
                }
                catch (e) {
                    if (
                    // 屏蔽部分不需要的警告信息
                    !(message === ':' ||
                        message.includes('Warning in') ||
                        message.includes('desugaring of'))) {
                        // 异步输出，保证插件编译失败的日志在他之前输出
                        setTimeout(() => {
                            console.error(message);
                        });
                    }
                }
            }
            resolve();
        });
    };
}
exports.createStderrListener = createStderrListener;
function kotlinDir(_outputDir) {
    return process.env.UNI_APP_X_CACHE_DIR;
}
exports.kotlinDir = kotlinDir;
function kotlinAARDir(kotlinDir) {
    return path_1.default.resolve(kotlinDir, 'aar');
}
function parseUTSModuleLibsJars(plugins) {
    const jars = new Set();
    plugins.forEach((plugin) => {
        const libsPath = path_1.default.resolve(process.env.UNI_INPUT_DIR, 'uni_modules', plugin, 'utssdk', 'app-android', 'libs');
        if (fs_extra_1.default.existsSync(libsPath)) {
            (0, fast_glob_1.sync)('*.jar', { cwd: libsPath, absolute: true }).forEach((jar) => {
                jars.add(jar);
            });
            const aars = (0, fast_glob_1.sync)('*.aar', { cwd: libsPath });
            aars.forEach((name) => {
                const outputPath = resolveAndroidArchiveOutputPath(name);
                if (fs_extra_1.default.existsSync(outputPath)) {
                    (0, fast_glob_1.sync)('**/*.jar', {
                        cwd: outputPath,
                        absolute: true,
                    }).forEach((jar) => {
                        jars.add(jar);
                    });
                }
            });
        }
    });
    return [...jars];
}
exports.parseUTSModuleLibsJars = parseUTSModuleLibsJars;
async function checkDepsByPlugin(checkType, plugin, checkDependencies, checkDependenciesValid, checkError) {
    const configJsonFile = path_1.default.resolve(process.env.UNI_INPUT_DIR, 'uni_modules', plugin, 'utssdk', 'app-android', 'config.json');
    if (fs_extra_1.default.existsSync(configJsonFile) && hasDeps(configJsonFile)) {
        return checkDependencies(configJsonFile, {
            type: checkType,
            valid: checkDependenciesValid,
        }).then(({ code, msg, data }) => {
            if (code !== 0) {
                console.error(msg);
                checkError(plugin);
                return [];
            }
            return data;
        });
    }
    return Promise.resolve([]);
}
async function parseUTSModuleConfigJsonJars(checkType, plugins, checkDependencies, checkDependenciesValid, checkError) {
    const deps = new Set();
    for (const plugin of plugins) {
        ;
        (await checkDepsByPlugin(checkType, plugin, checkDependencies, checkDependenciesValid, checkError)).forEach((dep) => deps.add(dep));
    }
    return [...deps];
}
exports.parseUTSModuleConfigJsonJars = parseUTSModuleConfigJsonJars;
