"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.parseUTSSwiftPluginStacktrace = void 0;
const path_1 = __importDefault(require("path"));
const fs_extra_1 = __importDefault(require("fs-extra"));
const sourceMap_1 = require("../sourceMap");
const utils_1 = require("./utils");
const utils_2 = require("../utils");
const uniModulesSwiftUTSRe = /(.*).swift:([0-9]+):([0-9]+):\s+error:\s+(.*)/;
async function parseUTSSwiftPluginStacktrace({ stacktrace, sourceRoot, sourceMapFile, }) {
    const res = [];
    const lines = stacktrace.split(utils_1.splitRE);
    for (let i = 0; i < lines.length; i++) {
        const line = lines[i];
        const codes = await parseUTSStacktraceLine(line, uniModulesSwiftUTSRe, sourceMapFile, sourceRoot);
        if (codes && codes.length) {
            const message = codes[0];
            res.push('\u200Cerror: ' + message + '\u200C');
            res.push(...codes.slice(1));
        }
        else {
            res.push(line);
        }
    }
    return utils_2.SPECIAL_CHARS.ERROR_BLOCK + res.join('\n') + utils_2.SPECIAL_CHARS.ERROR_BLOCK;
}
exports.parseUTSSwiftPluginStacktrace = parseUTSSwiftPluginStacktrace;
async function parseUTSStacktraceLine(lineStr, re, sourceMapFile, sourceRoot) {
    const uniModulesMatches = lineStr.match(re);
    if (!uniModulesMatches) {
        return;
    }
    const lines = [];
    const [, filename, line, column, message] = uniModulesMatches;
    // uts编译出来的入口index.swift
    if (!filename.endsWith('/app-ios/src/index')) {
        // 移除 src 目录，混编的假sourcemap，需要读取源码
        sourceMapFile =
            filename.replace('/app-ios/src/', '/app-ios/') + '.swift.fake.map';
    }
    const originalPosition = await (0, sourceMap_1.originalPositionFor)({
        sourceMapFile,
        line: parseInt(line),
        column: parseInt(column),
        withSourceContent: true,
    });
    if (originalPosition.source) {
        lines.push(`${message}`);
        lines.push(`at ${originalPosition.source.split('?')[0]}:${originalPosition.line}:${originalPosition.column}`);
        // 混编的假sourcemap，需要读取源码
        if (sourceMapFile.endsWith('.fake.map') && process.env.UNI_INPUT_DIR) {
            const file = path_1.default.join(process.env.UNI_INPUT_DIR, sourceMapFile.replace('.fake.map', ''));
            if (fs_extra_1.default.existsSync(file)) {
                originalPosition.sourceContent = fs_extra_1.default.readFileSync(file, 'utf-8');
            }
        }
        if (originalPosition.line !== null &&
            originalPosition.column !== null &&
            originalPosition.sourceContent) {
            lines.push((0, utils_1.generateCodeFrame)(originalPosition.sourceContent, {
                line: originalPosition.line,
                column: originalPosition.column,
            }).replace(/\t/g, ' '));
        }
    }
    else {
        lines.push(lineStr);
    }
    return lines;
}
