"use strict";
var __webpack_require__ = {};
(()=>{
    __webpack_require__.d = (exports1, definition)=>{
        for(var key in definition)if (__webpack_require__.o(definition, key) && !__webpack_require__.o(exports1, key)) Object.defineProperty(exports1, key, {
            enumerable: true,
            get: definition[key]
        });
    };
})();
(()=>{
    __webpack_require__.o = (obj, prop)=>Object.prototype.hasOwnProperty.call(obj, prop);
})();
(()=>{
    __webpack_require__.r = (exports1)=>{
        if ('undefined' != typeof Symbol && Symbol.toStringTag) Object.defineProperty(exports1, Symbol.toStringTag, {
            value: 'Module'
        });
        Object.defineProperty(exports1, '__esModule', {
            value: true
        });
    };
})();
var __webpack_exports__ = {};
__webpack_require__.r(__webpack_exports__);
__webpack_require__.d(__webpack_exports__, {
    splitReportHtmlByExecution: ()=>splitReportHtmlByExecution,
    ReportMergingTool: ()=>ReportMergingTool,
    isDirectoryModeReport: ()=>isDirectoryModeReport,
    dedupeExecutionsKeepLatest: ()=>dedupeExecutionsKeepLatest,
    collectDedupedExecutions: ()=>collectDedupedExecutions
});
const external_node_fs_namespaceObject = require("node:fs");
const external_node_path_namespaceObject = require("node:path");
const common_namespaceObject = require("@midscene/shared/common");
const utils_namespaceObject = require("@midscene/shared/utils");
const index_js_namespaceObject = require("./agent/index.js");
const html_utils_js_namespaceObject = require("./dump/html-utils.js");
const screenshot_store_js_namespaceObject = require("./dump/screenshot-store.js");
const external_types_js_namespaceObject = require("./types.js");
const external_utils_js_namespaceObject = require("./utils.js");
function _define_property(obj, key, value) {
    if (key in obj) Object.defineProperty(obj, key, {
        value: value,
        enumerable: true,
        configurable: true,
        writable: true
    });
    else obj[key] = value;
    return obj;
}
function isDirectoryModeReport(reportFilePath) {
    const reportDir = external_node_path_namespaceObject.dirname(reportFilePath);
    return 'index.html' === external_node_path_namespaceObject.basename(reportFilePath) && (0, external_node_fs_namespaceObject.existsSync)(external_node_path_namespaceObject.join(reportDir, 'screenshots'));
}
function dedupeExecutionsKeepLatest(executions) {
    let noIdCounter = 0;
    const deduped = new Map();
    for (const exec of executions){
        const key = exec.id || `__no_id_${noIdCounter++}`;
        deduped.set(key, exec);
    }
    return Array.from(deduped.values());
}
class ReportMergingTool {
    createEmptyDumpString(groupName, groupDescription) {
        return new external_types_js_namespaceObject.ReportActionDump({
            sdkVersion: '',
            groupName,
            groupDescription,
            modelBriefs: [],
            executions: []
        }).serialize();
    }
    append(reportInfo) {
        this.reportInfos.push(reportInfo);
    }
    clear() {
        this.reportInfos = [];
    }
    mergeDumpScripts(contents) {
        const unescaped = contents.map((c)=>(0, utils_namespaceObject.antiEscapeScriptTag)(c)).filter((c)=>c.length > 0);
        if (0 === unescaped.length) return '';
        if (1 === unescaped.length) return unescaped[0];
        const base = external_types_js_namespaceObject.ReportActionDump.fromSerializedString(unescaped[0]);
        const allExecutions = [
            ...base.executions
        ];
        for(let i = 1; i < unescaped.length; i++){
            const other = external_types_js_namespaceObject.ReportActionDump.fromSerializedString(unescaped[i]);
            allExecutions.push(...other.executions);
        }
        base.executions = dedupeExecutionsKeepLatest(allExecutions);
        return base.serialize();
    }
    mergeReports(reportFileName = 'AUTO', opts) {
        const { rmOriginalReports = false, overwrite = false } = opts ?? {};
        if (0 === this.reportInfos.length) {
            (0, utils_namespaceObject.logMsg)('No reports to merge');
            return null;
        }
        const targetDir = (0, common_namespaceObject.getMidsceneRunSubDir)('report');
        const hasDirectoryModeReport = this.reportInfos.some((info)=>{
            const reportFilePath = info.reportFilePath;
            return Boolean(reportFilePath && isDirectoryModeReport(reportFilePath));
        });
        const resolvedName = 'AUTO' === reportFileName ? (0, index_js_namespaceObject.getReportFileName)('merged-report') : reportFileName;
        const outputFilePath = hasDirectoryModeReport ? external_node_path_namespaceObject.resolve(targetDir, resolvedName, 'index.html') : external_node_path_namespaceObject.resolve(targetDir, `${resolvedName}.html`);
        if ('AUTO' !== reportFileName && (0, external_node_fs_namespaceObject.existsSync)(outputFilePath)) {
            if (!overwrite) throw new Error(`Report file already exists: ${outputFilePath}\nSet overwrite to true to overwrite this file.`);
            if (hasDirectoryModeReport) (0, external_node_fs_namespaceObject.rmSync)(external_node_path_namespaceObject.dirname(outputFilePath), {
                recursive: true,
                force: true
            });
            else (0, external_node_fs_namespaceObject.unlinkSync)(outputFilePath);
        }
        if (hasDirectoryModeReport) (0, external_node_fs_namespaceObject.mkdirSync)(external_node_path_namespaceObject.dirname(outputFilePath), {
            recursive: true
        });
        (0, utils_namespaceObject.logMsg)(`Start merging ${this.reportInfos.length} reports...\nCreating template file...`);
        try {
            const htmlEndTag = '</html>';
            const tpl = (0, external_utils_js_namespaceObject.getReportTpl)();
            const htmlEndIdx = tpl.lastIndexOf(htmlEndTag);
            const tplWithoutClose = -1 !== htmlEndIdx ? tpl.slice(0, htmlEndIdx) : tpl;
            (0, external_node_fs_namespaceObject.appendFileSync)(outputFilePath, tplWithoutClose);
            if (hasDirectoryModeReport) (0, external_node_fs_namespaceObject.appendFileSync)(outputFilePath, (0, html_utils_js_namespaceObject.getBaseUrlFixScript)());
            for(let i = 0; i < this.reportInfos.length; i++){
                const reportInfo = this.reportInfos[i];
                (0, utils_namespaceObject.logMsg)(`Processing report ${i + 1}/${this.reportInfos.length}`);
                const { reportAttributes } = reportInfo;
                let dumpString = this.createEmptyDumpString(reportAttributes.testTitle, reportAttributes.testDescription);
                let mergedGroupId = `merged-group-${i}`;
                if (reportInfo.reportFilePath) {
                    if (isDirectoryModeReport(reportInfo.reportFilePath)) {
                        const reportDir = external_node_path_namespaceObject.dirname(reportInfo.reportFilePath);
                        const screenshotsDir = external_node_path_namespaceObject.join(reportDir, 'screenshots');
                        const mergedScreenshotsDir = external_node_path_namespaceObject.join(external_node_path_namespaceObject.dirname(outputFilePath), 'screenshots');
                        (0, external_node_fs_namespaceObject.mkdirSync)(mergedScreenshotsDir, {
                            recursive: true
                        });
                        for (const file of (0, external_node_fs_namespaceObject.readdirSync)(screenshotsDir)){
                            const src = external_node_path_namespaceObject.join(screenshotsDir, file);
                            const dest = external_node_path_namespaceObject.join(mergedScreenshotsDir, file);
                            (0, external_node_fs_namespaceObject.copyFileSync)(src, dest);
                        }
                    } else (0, html_utils_js_namespaceObject.streamImageScriptsToFile)(reportInfo.reportFilePath, outputFilePath);
                    const allDumps = (0, html_utils_js_namespaceObject.extractAllDumpScriptsSync)(reportInfo.reportFilePath).filter((d)=>d.openTag.includes('data-group-id'));
                    const groupIdMatch = allDumps[0]?.openTag.match(/data-group-id="([^"]+)"/);
                    if (groupIdMatch) mergedGroupId = decodeURIComponent(groupIdMatch[1]);
                    const extractedDumpString = allDumps.length > 0 ? this.mergeDumpScripts(allDumps.map((d)=>d.content)) : (0, html_utils_js_namespaceObject.extractLastDumpScriptSync)(reportInfo.reportFilePath);
                    if (extractedDumpString) dumpString = extractedDumpString;
                }
                const reportHtmlStr = `${(0, external_utils_js_namespaceObject.reportHTMLContent)({
                    dumpString,
                    attributes: {
                        'data-group-id': mergedGroupId,
                        playwright_test_duration: reportAttributes.testDuration,
                        playwright_test_status: reportAttributes.testStatus,
                        playwright_test_title: reportAttributes.testTitle,
                        playwright_test_id: reportAttributes.testId,
                        playwright_test_description: reportAttributes.testDescription,
                        is_merged: true
                    }
                }, void 0, void 0, false)}\n`;
                (0, external_node_fs_namespaceObject.appendFileSync)(outputFilePath, reportHtmlStr);
            }
            (0, external_node_fs_namespaceObject.appendFileSync)(outputFilePath, `${htmlEndTag}\n`);
            (0, utils_namespaceObject.logMsg)(`Successfully merged new report: ${outputFilePath}`);
            if (rmOriginalReports) {
                for (const info of this.reportInfos)if (info.reportFilePath) try {
                    if (isDirectoryModeReport(info.reportFilePath)) {
                        const reportDir = external_node_path_namespaceObject.dirname(info.reportFilePath);
                        (0, external_node_fs_namespaceObject.rmSync)(reportDir, {
                            recursive: true,
                            force: true
                        });
                    } else (0, external_node_fs_namespaceObject.unlinkSync)(info.reportFilePath);
                } catch (error) {
                    (0, utils_namespaceObject.logMsg)(`Error deleting report ${info.reportFilePath}: ${error}`);
                }
                (0, utils_namespaceObject.logMsg)(`Removed ${this.reportInfos.length} original reports`);
            }
            return outputFilePath;
        } catch (error) {
            (0, utils_namespaceObject.logMsg)(`Error in mergeReports: ${error}`);
            throw error;
        }
    }
    constructor(){
        _define_property(this, "reportInfos", []);
    }
}
function collectDedupedExecutions(htmlPath) {
    let baseDump = null;
    let executionSerial = 0;
    const latestSerialByExecutionId = new Map();
    (0, html_utils_js_namespaceObject.streamDumpScriptsSync)(htmlPath, (dumpScript)=>{
        if (!dumpScript.openTag.includes('data-group-id')) return false;
        const groupedDump = external_types_js_namespaceObject.ReportActionDump.fromSerializedString((0, utils_namespaceObject.antiEscapeScriptTag)(dumpScript.content));
        for (const execution of groupedDump.executions){
            executionSerial += 1;
            if (execution.id) latestSerialByExecutionId.set(execution.id, executionSerial);
        }
        return false;
    });
    const executions = [];
    executionSerial = 0;
    (0, html_utils_js_namespaceObject.streamDumpScriptsSync)(htmlPath, (dumpScript)=>{
        if (!dumpScript.openTag.includes('data-group-id')) return false;
        const groupedDump = external_types_js_namespaceObject.ReportActionDump.fromSerializedString((0, utils_namespaceObject.antiEscapeScriptTag)(dumpScript.content));
        if (!baseDump) baseDump = groupedDump;
        for (const execution of groupedDump.executions){
            executionSerial += 1;
            if (!execution.id || latestSerialByExecutionId.get(execution.id) === executionSerial) executions.push(execution);
        }
        return false;
    });
    if (!baseDump) throw new Error(`No report dump scripts found in ${htmlPath}`);
    return {
        baseDump,
        executions
    };
}
function extensionByMimeType(mimeType) {
    if ('image/png' === mimeType) return 'png';
    if ('image/jpeg' === mimeType) return 'jpeg';
    throw new Error(`Unsupported screenshot mime type: ${mimeType}`);
}
function externalizeScreenshotsInExecution(execution, opts) {
    const visit = (node)=>{
        if (Array.isArray(node)) {
            for (const item of node)visit(item);
            return;
        }
        if ('object' != typeof node || null === node) return;
        const ref = (0, screenshot_store_js_namespaceObject.normalizeScreenshotRef)(node);
        if (ref) {
            const ext = extensionByMimeType(ref.mimeType);
            const fileName = `${ref.id}.${ext}`;
            const relativePath = `./screenshots/${fileName}`;
            const absolutePath = external_node_path_namespaceObject.join(opts.screenshotsDir, fileName);
            if (!opts.writtenFiles.has(fileName)) {
                const resolved = (0, screenshot_store_js_namespaceObject.resolveScreenshotSource)(ref, {
                    reportPath: opts.htmlPath
                });
                if ('data-uri' === resolved.type) {
                    const rawBase64 = resolved.dataUri.replace(/^data:image\/[a-zA-Z+]+;base64,/, '');
                    (0, external_node_fs_namespaceObject.writeFileSync)(absolutePath, Buffer.from(rawBase64, 'base64'));
                } else (0, external_node_fs_namespaceObject.copyFileSync)(resolved.filePath, absolutePath);
                opts.writtenFiles.add(fileName);
            }
            ref.storage = 'file';
            ref.path = relativePath;
            return;
        }
        for (const value of Object.values(node))visit(value);
    };
    visit(execution);
}
function splitReportHtmlByExecution(options) {
    const { htmlPath, outputDir } = options;
    const screenshotsDir = external_node_path_namespaceObject.join(outputDir, 'screenshots');
    (0, external_node_fs_namespaceObject.mkdirSync)(outputDir, {
        recursive: true
    });
    (0, external_node_fs_namespaceObject.mkdirSync)(screenshotsDir, {
        recursive: true
    });
    const executionJsonFiles = [];
    const writtenScreenshotFiles = new Set();
    const { baseDump, executions } = collectDedupedExecutions(htmlPath);
    let fileIndex = 0;
    for (const execution of executions){
        fileIndex += 1;
        externalizeScreenshotsInExecution(execution, {
            htmlPath,
            screenshotsDir,
            writtenFiles: writtenScreenshotFiles
        });
        const singleExecutionDump = new external_types_js_namespaceObject.ReportActionDump({
            sdkVersion: baseDump.sdkVersion,
            groupName: baseDump.groupName,
            groupDescription: baseDump.groupDescription,
            modelBriefs: baseDump.modelBriefs,
            deviceType: baseDump.deviceType,
            executions: [
                execution
            ]
        });
        const jsonFilePath = external_node_path_namespaceObject.join(outputDir, `${fileIndex}.execution.json`);
        (0, external_node_fs_namespaceObject.writeFileSync)(jsonFilePath, singleExecutionDump.serialize(2), 'utf-8');
        executionJsonFiles.push(jsonFilePath);
    }
    return {
        executionJsonFiles,
        screenshotFiles: Array.from(writtenScreenshotFiles).sort().map((fileName)=>external_node_path_namespaceObject.join(screenshotsDir, fileName))
    };
}
exports.ReportMergingTool = __webpack_exports__.ReportMergingTool;
exports.collectDedupedExecutions = __webpack_exports__.collectDedupedExecutions;
exports.dedupeExecutionsKeepLatest = __webpack_exports__.dedupeExecutionsKeepLatest;
exports.isDirectoryModeReport = __webpack_exports__.isDirectoryModeReport;
exports.splitReportHtmlByExecution = __webpack_exports__.splitReportHtmlByExecution;
for(var __rspack_i in __webpack_exports__)if (-1 === [
    "ReportMergingTool",
    "collectDedupedExecutions",
    "dedupeExecutionsKeepLatest",
    "isDirectoryModeReport",
    "splitReportHtmlByExecution"
].indexOf(__rspack_i)) exports[__rspack_i] = __webpack_exports__[__rspack_i];
Object.defineProperty(exports, '__esModule', {
    value: true
});

//# sourceMappingURL=report.js.map