var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
    if (kind === "m") throw new TypeError("Private method is not writable");
    if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
    if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
    return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
};
var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
    if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
    if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
    return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
};
var _HTTP_fetch, _HTTP_namespace;
import { FetchResponse, } from '@devvit/protos/types/devvit/plugin/http/http.js';
import { Header } from '@devvit/shared-types/Header.js';
import { Hostname } from '@devvit/shared-types/HostnameUtil.js';
export class HTTP {
    constructor(aFetchImpl, namespace) {
        _HTTP_fetch.set(this, void 0);
        _HTTP_namespace.set(this, void 0);
        this.assertEnvironment();
        __classPrivateFieldSet(this, _HTTP_fetch, aFetchImpl, "f");
        __classPrivateFieldSet(this, _HTTP_namespace, namespace, "f");
    }
    async Fetch(request, metadata) {
        const data = { ...request.data };
        if (['get', 'head'].includes(data.method?.toLowerCase())) {
            delete data.body;
        }
        // Allowed HTTP method validation for User Actors
        const allowedHTTPMethods = ['GET', 'HEAD', 'POST', 'PUT', 'DELETE', 'OPTIONS', 'PATCH'];
        const caller = metadata?.[Header.Caller]?.values[0];
        if (!caller) {
            throw Error('Caller header not found in Metadata during HTTP Fetch');
        }
        if (!Hostname.isSystem(caller, __classPrivateFieldGet(this, _HTTP_namespace, "f"))) {
            if (!allowedHTTPMethods.includes(data.method?.toUpperCase())) {
                throw Error(`HTTP Fetch request with method:${data.method} is not allowed`);
            }
        }
        const response = await __classPrivateFieldGet(this, _HTTP_fetch, "f").call(globalThis, request.url, data);
        return FetchResponse.fromPartial({
            url: response.url,
            body: new Uint8Array(await response.arrayBuffer()),
            status: response.status,
            headers: Object.fromEntries(response.headers.entries()),
        });
    }
}
_HTTP_fetch = new WeakMap(), _HTTP_namespace = new WeakMap();
