"use strict";
/**
 * Copyright: (c) Myia SAS 2026.
 * This file and its contents are licensed under the AGPLv3 License.
 * Please see the LICENSE file at the root of this repository
 */
Object.defineProperty(exports, "__esModule", { value: true });
exports.createTryFinallyWrapperBuilder = createTryFinallyWrapperBuilder;
const global_names_1 = require("../../../trace-event-recorder/model/global-names");
function createTryFinallyWrapperBuilder(t, buildGlobalTraceCall) {
    function buildTryFinally(scope, tryBodyStmts, okArgs = []) {
        const errId = scope.generateUidIdentifier('traceErr');
        const threwId = scope.generateUidIdentifier('traceThrew');
        const rethrow = t.throwStatement(t.cloneNode(errId));
        rethrow._traced = true;
        const assignThrew = t.expressionStatement(t.assignmentExpression('=', t.cloneNode(threwId), t.booleanLiteral(true)));
        assignThrew._traced = true;
        const catchBlock = t.blockStatement([
            assignThrew,
            buildGlobalTraceCall(global_names_1.HEAL_THROW, [t.cloneNode(errId)]),
            rethrow,
        ]);
        const finallyBlock = t.blockStatement([
            t.ifStatement(t.unaryExpression('!', t.cloneNode(threwId)), t.blockStatement([buildGlobalTraceCall(global_names_1.HEAL_OK, okArgs)])),
        ]);
        finallyBlock.body.forEach((n) => {
            n._traced = true;
            const withConsequent = n;
            if (withConsequent.consequent)
                withConsequent.consequent._traced = true;
        });
        const tryStmt = t.tryStatement(t.blockStatement(tryBodyStmts), t.catchClause(errId, catchBlock), finallyBlock);
        tryStmt._traced = true;
        return { threwId, tryStmt };
    }
    function buildThrewDecl(threwId) {
        const decl = t.variableDeclaration('let', [
            t.variableDeclarator(threwId, t.booleanLiteral(false)),
        ]);
        decl._traced = true;
        return decl;
    }
    return { buildTryFinally, buildThrewDecl };
}
