"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.stacktraceHook = void 0;
const fs_extra_1 = __importDefault(require("fs-extra"));
exports.stacktraceHook = async (testContext) => {
    const myObject = {};
    Error.captureStackTrace(myObject);
    try {
        const codeError = await extractCodeErrorDetails(myObject.stack);
        const metadata = {
            codeError,
        };
        testContext.addStepMetadata(metadata);
    }
    catch (err) {
    }
};
async function extractCodeErrorDetails(errorStack) {
    const lines = errorStack.split('\n');
    const userLine = lines[3];
    const firstSlashIndex = userLine.indexOf('/');
    const firstColonIndex = userLine.indexOf(':');
    const filepath = userLine.substr(firstSlashIndex, firstColonIndex - firstSlashIndex);
    const [row, column] = userLine.substr(firstColonIndex + 1).split(':').map(Number);
    const rowCountToShow = 3;
    const userFile = await fs_extra_1.default.readFile(filepath, 'utf8');
    const userLines = userFile.split('\n');
    const fromRowNumber = Math.max(row - rowCountToShow, 1);
    const toRowNumber = Math.min(row + rowCountToShow, userLines.length);
    const errorLines = userLines.slice(fromRowNumber - 1, toRowNumber);
    return {
        errorLines,
        fromRowNumber,
        toRowNumber,
        row,
        column,
    };
}
