import opentelemetry from '@opentelemetry/api';
import { version } from '../../lib/version.js';
export const tracer = opentelemetry.trace.getTracer('libelaw', version);
export const method = (opts) => (target, prop, descriptor) => {
    const orig = descriptor.value;
    descriptor.value = function (...args) {
        const spanName = typeof opts?.name === 'function'
            ? opts.name(target, this, String(prop))
            : (opts?.name ?? `${target.constructor.name ?? target.name}.${String(prop)}`);
        const isAsync = orig.constructor.name === 'AsyncFunction';
        return isAsync
            ? asyncBlock(spanName, async (span) => {
                if (opts?.attributes)
                    span.setAttributes(opts?.attributes);
                return await orig.apply(this, args);
            })
            : block(spanName, (span) => {
                if (opts?.attributes)
                    span.setAttributes(opts?.attributes);
                return orig.apply(this, args);
            });
    };
};
export const asyncBlock = (name, block) => {
    return tracer.startActiveSpan(name, async (span) => {
        try {
            const res = await block(span);
            span.setStatus({ code: 1 });
            span.end();
            return res;
        }
        catch (err) {
            span.recordException(err);
            span.setStatus({ code: 2, message: String(err) });
            span.end();
            throw err;
        }
    });
};
export const block = (name, block) => {
    return tracer.startActiveSpan(name, (span) => {
        try {
            const res = block(span);
            span.setStatus({ code: 1 });
            span.end();
            return res;
        }
        catch (err) {
            span.recordException(err);
            span.setStatus({ code: 2, message: String(err) });
            span.end();
            throw err;
        }
    });
};
//# sourceMappingURL=tracing.js.map