import { isSome } from "@jet/environment";
import * as validation from "@jet/environment/json/validation";
import { tryAwait } from "./promise-util";
/**
 * Creates a validation context for async operations and ensures proper cleanup.
 *
 * Wraps an async operation in a validation context, automatically handling
 * context cleanup even when errors occur. Optionally processes errors through
 * a provided error handler.
 *
 * @param name - The name for the validation context
 * @param producer - Async function that produces the result
 * @param errorHandler - Optional function to handle errors from the producer
 * @returns The result of the async operation
 */
export async function withAsyncValidationContext(name, producer, errorHandler) {
    validation.beginContext(name);
    let result = await tryAwait(producer());
    if (!result.success && isSome(errorHandler)) {
        result = await tryAwait(errorHandler(result.error));
    }
    validation.endContext();
    if (!result.success) {
        throw result.error;
    }
    else {
        return result.value;
    }
}
//# sourceMappingURL=validation-util.js.map