"use strict";
// Generated by bynkc — do not edit by hand.
// bynk runtime — shared by every emitted module.
Object.defineProperty(exports, "__esModule", { value: true });
exports.HttpResult = exports.InMemoryStorage = exports.None = exports.Some = exports.Err = exports.Ok = void 0;
exports.makeTestState = makeTestState;
exports.boundaryError = boundaryError;
exports.callService = callService;
exports.matchPath = matchPath;
exports.httpResultToResponse = httpResultToResponse;
const Ok = (value) => ({ tag: "Ok", value });
exports.Ok = Ok;
const Err = (error) => ({ tag: "Err", error });
exports.Err = Err;
const Some = (value) => ({ tag: "Some", value });
exports.Some = Some;
exports.None = { tag: "None" };
class InMemoryStorage {
    data = new Map();
    async get(key) {
        return this.data.get(key);
    }
    async put(key, value) {
        this.data.set(key, value);
    }
    async delete(key) {
        return this.data.delete(key);
    }
    async list(options) {
        const prefix = options?.prefix ?? "";
        const out = new Map();
        for (const [k, v] of this.data) {
            if (k.startsWith(prefix))
                out.set(k, v);
        }
        return out;
    }
}
exports.InMemoryStorage = InMemoryStorage;
function makeTestState(name) {
    return {
        storage: new InMemoryStorage(),
        id: { name },
    };
}
function boundaryError(error) {
    const e = new Error(`BoundaryError: ${error.kind}`);
    e.boundaryError = error;
    return e;
}
async function callService(binding, servicePath, argsJson, deserialiseResult) {
    const request = new Request(`http://internal/_bynk/call/${servicePath}`, {
        method: "POST",
        headers: { "content-type": "application/json" },
        body: JSON.stringify(argsJson),
    });
    const response = await binding.fetch(request);
    if (!response.ok) {
        throw boundaryError({
            kind: "Transport",
            status: response.status,
            details: await response.text(),
        });
    }
    let responseJson;
    try {
        responseJson = (await response.json());
    }
    catch (e) {
        throw boundaryError({ kind: "MalformedJson", details: String(e) });
    }
    const result = deserialiseResult(responseJson);
    if (result.tag === "Err") {
        throw boundaryError(result.error);
    }
    return result.value;
}
exports.HttpResult = {
    Ok: (value) => ({ tag: "Ok", value }),
    Created: (value) => ({ tag: "Created", value }),
    NoContent: { tag: "NoContent" },
    BadRequest: (message) => ({ tag: "BadRequest", message }),
    Unauthorized: { tag: "Unauthorized" },
    Forbidden: { tag: "Forbidden" },
    NotFound: { tag: "NotFound" },
    Conflict: (message) => ({ tag: "Conflict", message }),
    UnprocessableEntity: (message) => ({
        tag: "UnprocessableEntity",
        message,
    }),
    ServerError: (message) => ({ tag: "ServerError", message }),
};
// Match a path pattern (e.g., "/orders/:id") against a request path.
// Returns the captured parameter map, or null on no match.
function matchPath(pattern, path) {
    const patternSegments = pattern.split("/").filter(Boolean);
    const pathSegments = path.split("/").filter(Boolean);
    if (patternSegments.length !== pathSegments.length)
        return null;
    const params = {};
    for (let i = 0; i < patternSegments.length; i++) {
        const p = patternSegments[i];
        if (p.startsWith(":")) {
            params[p.slice(1)] = decodeURIComponent(pathSegments[i]);
        }
        else if (p !== pathSegments[i]) {
            return null;
        }
    }
    return { params };
}
// Serialise an HttpResult<T> to a Response. The variant determines the
// HTTP status code; the body (if any) is JSON-encoded.
function httpResultToResponse(result, serialiseValue) {
    switch (result.tag) {
        case "Ok":
            return new Response(JSON.stringify(serialiseValue(result.value)), {
                status: 200,
                headers: { "content-type": "application/json" },
            });
        case "Created":
            return new Response(JSON.stringify(serialiseValue(result.value)), {
                status: 201,
                headers: { "content-type": "application/json" },
            });
        case "NoContent":
            return new Response(null, { status: 204 });
        case "BadRequest":
            return new Response(JSON.stringify({ error: result.message }), {
                status: 400,
                headers: { "content-type": "application/json" },
            });
        case "Unauthorized":
            return new Response(null, { status: 401 });
        case "Forbidden":
            return new Response(null, { status: 403 });
        case "NotFound":
            return new Response(null, { status: 404 });
        case "Conflict":
            return new Response(JSON.stringify({ error: result.message }), {
                status: 409,
                headers: { "content-type": "application/json" },
            });
        case "UnprocessableEntity":
            return new Response(JSON.stringify({ error: result.message }), {
                status: 422,
                headers: { "content-type": "application/json" },
            });
        case "ServerError":
            return new Response(JSON.stringify({ error: result.message }), {
                status: 500,
                headers: { "content-type": "application/json" },
            });
    }
}
