import fs, { constants as FS } from "fs/promises";
import url from "url";
import { codeFrameColumns } from "next/dist/compiled/babel/code-frame";
import { launchEditor } from "../internal/helpers/launchEditor";
const currentSourcesByFile = new Map();
async function batchedTraceSource(project, frame) {
    const file = frame.file ? decodeURIComponent(frame.file) : undefined;
    if (!file) {
        return;
    }
    const sourceFrame = await project.traceSource(frame);
    if (!sourceFrame) {
        return;
    }
    let source;
    // Don't show code frames for node_modules. These can also often be large bundled files.
    if (!sourceFrame.file.includes("node_modules") && !sourceFrame.isInternal) {
        let sourcePromise = currentSourcesByFile.get(sourceFrame.file);
        if (!sourcePromise) {
            sourcePromise = project.getSourceForAsset(sourceFrame.file);
            currentSourcesByFile.set(sourceFrame.file, sourcePromise);
            setTimeout(()=>{
                // Cache file reads for 100ms, as frames will often reference the same
                // files and can be large.
                currentSourcesByFile.delete(sourceFrame.file);
            }, 100);
        }
        source = await sourcePromise;
    }
    var _sourceFrame_methodName, _ref;
    return {
        frame: {
            file: sourceFrame.file,
            lineNumber: sourceFrame.line,
            column: sourceFrame.column,
            methodName: (_ref = (_sourceFrame_methodName = sourceFrame.methodName) != null ? _sourceFrame_methodName : frame.methodName) != null ? _ref : "<unknown>",
            arguments: []
        },
        source: source != null ? source : null
    };
}
export async function createOriginalStackFrame(project, frame) {
    const traced = await batchedTraceSource(project, frame);
    if (!traced) {
        return null;
    }
    var _traced_frame_lineNumber, _traced_frame_column;
    return {
        originalStackFrame: traced.frame,
        originalCodeFrame: traced.source === null ? null : codeFrameColumns(traced.source, {
            start: {
                // 1-based, but -1 means start line without highlighting
                line: (_traced_frame_lineNumber = traced.frame.lineNumber) != null ? _traced_frame_lineNumber : -1,
                // 1-based, but 0 means whole line without column highlighting
                column: (_traced_frame_column = traced.frame.column) != null ? _traced_frame_column : 0
            }
        }, {
            forceColor: true
        })
    };
}
function stackFrameFromQuery(query) {
    return {
        file: query.file,
        methodName: query.methodName,
        line: typeof query.lineNumber === "string" ? parseInt(query.lineNumber, 10) : 0,
        column: typeof query.column === "string" ? parseInt(query.column, 10) : null,
        isServer: query.isServer === "true"
    };
}
export function getOverlayMiddleware(project) {
    return async function(req, res) {
        const { pathname, query } = url.parse(req.url, true);
        if (pathname === "/__nextjs_original-stack-frame") {
            const frame = stackFrameFromQuery(query);
            let originalStackFrame;
            try {
                originalStackFrame = await createOriginalStackFrame(project, frame);
            } catch (e) {
                res.statusCode = 500;
                res.write(e.message);
                res.end();
                return;
            }
            if (originalStackFrame === null) {
                res.statusCode = 404;
                res.write("Unable to resolve sourcemap");
                res.end();
                return;
            }
            res.statusCode = 200;
            res.setHeader("Content-Type", "application/json");
            res.write(Buffer.from(JSON.stringify(originalStackFrame)));
            res.end();
            return;
        } else if (pathname === "/__nextjs_launch-editor") {
            var _frame_file;
            const frame = stackFrameFromQuery(query);
            const filePath = (_frame_file = frame.file) == null ? void 0 : _frame_file.toString();
            if (filePath === undefined) {
                res.statusCode = 400;
                res.write("Bad Request");
                res.end();
                return;
            }
            const fileExists = await fs.access(filePath, FS.F_OK).then(()=>true, ()=>false);
            if (!fileExists) {
                res.statusCode = 204;
                res.write("No Content");
                res.end();
                return;
            }
            try {
                var _frame_line, _frame_column;
                launchEditor(filePath, (_frame_line = frame.line) != null ? _frame_line : 1, (_frame_column = frame.column) != null ? _frame_column : 1);
            } catch (err) {
                console.log("Failed to launch editor:", err);
                res.statusCode = 500;
                res.write("Internal Server Error");
                res.end();
                return;
            }
            res.statusCode = 204;
            res.end();
        }
    };
}

//# sourceMappingURL=middleware-turbopack.js.map