"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.HttpProvider = void 0;
const tiny_invariant_1 = __importDefault(require("tiny-invariant"));
const logger_1 = __importDefault(require("../logger"));
const cache_1 = require("../cache");
const shared_1 = require("./shared");
const util_1 = require("../util");
class HttpProvider {
    constructor(url, options) {
        this.url = url;
        this.config = options.config;
        this.responseParser = createResponseParser(this.config.responseParser);
    }
    id() {
        return this.url;
    }
    toString() {
        return `[HTTP Provider ${this.url}]`;
    }
    async callApi(prompt, context) {
        // Render all nested strings
        const nunjucks = (0, util_1.getNunjucksEngine)();
        const stringifiedConfig = (0, util_1.safeJsonStringify)(this.config);
        const renderedConfig = JSON.parse(nunjucks.renderString(stringifiedConfig, {
            prompt,
            ...context?.vars,
        }));
        const method = renderedConfig.method || 'POST';
        const headers = renderedConfig.headers || { 'Content-Type': 'application/json' };
        (0, tiny_invariant_1.default)(typeof method === 'string', 'Expected method to be a string');
        (0, tiny_invariant_1.default)(typeof headers === 'object', 'Expected headers to be an object');
        logger_1.default.debug(`Calling HTTP provider: ${this.url} with config: ${stringifiedConfig}`);
        let response;
        try {
            response = await (0, cache_1.fetchWithCache)(this.url, {
                method,
                headers,
                body: JSON.stringify(renderedConfig.body),
            }, shared_1.REQUEST_TIMEOUT_MS, 'json');
        }
        catch (err) {
            return {
                error: `HTTP call error: ${String(err)}`,
            };
        }
        logger_1.default.debug(`\tHTTP response: ${JSON.stringify(response.data)}`);
        return this.responseParser(response.data);
    }
}
exports.HttpProvider = HttpProvider;
function createResponseParser(parser) {
    if (typeof parser === 'function') {
        return parser;
    }
    if (typeof parser === 'string') {
        return new Function('json', `return ${parser}`);
    }
    return (data) => ({ output: data });
}
//# sourceMappingURL=http.js.map