"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.adapters = void 0;
const SECRET_HEADER = "X-Telegram-Bot-Api-Secret-Token";
const SECRET_HEADER_LOWERCASE = SECRET_HEADER.toLowerCase();
const WRONG_TOKEN_ERROR = "secret token is wrong";
const ok = () => new Response(null, { status: 200 });
const okJson = (json) => new Response(json, {
    status: 200,
    headers: { "Content-Type": "application/json" },
});
const unauthorized = () => new Response('"unauthorized"', {
    status: 401,
    statusText: WRONG_TOKEN_ERROR,
});
/** express web framework */
const express = (req, res) => ({
    update: Promise.resolve(req.body),
    header: req.header(SECRET_HEADER),
    end: () => res.end(),
    respond: (json) => {
        res.set("Content-Type", "application/json");
        res.send(json);
    },
    unauthorized: () => {
        res.status(401).send(WRONG_TOKEN_ERROR);
    },
});
/** koa web framework */
const koa = (ctx) => ({
    update: Promise.resolve(ctx.request.body),
    header: ctx.get(SECRET_HEADER),
    end: () => {
        ctx.body = "";
    },
    respond: (json) => {
        ctx.set("Content-Type", "application/json");
        ctx.response.body = json;
    },
    unauthorized: () => {
        ctx.status = 401;
    },
});
/** fastify web framework */
const fastify = (req, reply) => ({
    update: Promise.resolve(req.body),
    header: req.headers[SECRET_HEADER_LOWERCASE],
    end: () => reply.status(200).send(),
    respond: (json) => reply.send(json),
    unauthorized: () => reply.code(401).send(WRONG_TOKEN_ERROR),
});
const serveHttp = (requestEvent) => ({
    update: requestEvent.request.json(),
    header: requestEvent.request.headers.get(SECRET_HEADER) || undefined,
    end: () => requestEvent.respondWith(ok()),
    respond: (json) => requestEvent.respondWith(okJson(json)),
    unauthorized: () => requestEvent.respondWith(unauthorized()),
});
/** std/http web server */
const stdHttp = (req) => {
    let resolveResponse;
    return {
        update: req.json(),
        header: req.headers.get(SECRET_HEADER) || undefined,
        end: () => {
            if (resolveResponse)
                resolveResponse(ok());
        },
        respond: (json) => {
            if (resolveResponse)
                resolveResponse(okJson(json));
        },
        unauthorized: () => {
            if (resolveResponse)
                resolveResponse(unauthorized());
        },
        handlerReturn: new Promise((resolve) => {
            resolveResponse = resolve;
        }),
    };
};
/** oak web framework */
const oak = (ctx) => ({
    update: ctx.request.body({ type: "json" }).value,
    header: ctx.request.headers.get(SECRET_HEADER) || undefined,
    end: () => {
        ctx.response.status = 200;
    },
    respond: (json) => {
        ctx.response.type = "json";
        ctx.response.body = json;
    },
    unauthorized: () => {
        ctx.response.status = 401;
    },
});
/** Node.js native 'http' and 'https' modules */
const http = (req, res) => {
    const secretHeaderFromRequest = req.headers[SECRET_HEADER_LOWERCASE];
    return {
        update: new Promise((resolve, reject) => {
            const chunks = [];
            req.on("data", (chunk) => chunks.push(chunk))
                .once("end", () => {
                // @ts-ignore `Buffer` is Node-only
                const raw = Buffer.concat(chunks).toString("utf-8");
                resolve(JSON.parse(raw));
            })
                .once("error", reject);
        }),
        header: Array.isArray(secretHeaderFromRequest)
            ? secretHeaderFromRequest[0]
            : secretHeaderFromRequest,
        end: () => res.end(),
        respond: (json) => res
            .writeHead(200, { "Content-Type": "application/json" })
            .end(json),
        unauthorized: () => res.writeHead(401).end(WRONG_TOKEN_ERROR),
    };
};
/** AWS lambda serverless functions */
const awsLambda = (event, _context, callback) => ({
    update: JSON.parse(event.body),
    header: event.headers[SECRET_HEADER],
    end: () => callback(null, { statusCode: 200 }),
    respond: (json) => callback(null, {
        statusCode: 200,
        headers: { "Content-Type": "application/json" },
        body: json,
    }),
    unauthorized: () => callback(null, { statusCode: 401 }),
});
/** AWS lambda async/await serverless functions */
const awsLambdaAsync = (event, _context) => {
    let resolveResponse;
    return {
        update: JSON.parse(event.body),
        header: event.headers[SECRET_HEADER],
        end: () => resolveResponse({ statusCode: 200 }),
        respond: (json) => resolveResponse({
            statusCode: 200,
            headers: { "Content-Type": "application/json" },
            body: json,
        }),
        unauthorized: () => resolveResponse({ statusCode: 401 }),
        handlerReturn: new Promise((resolve) => {
            resolveResponse = resolve;
        }),
    };
};
/** Azure Functions */
const azure = (context, req) => ({
    update: Promise.resolve(req.body),
    header: context.res.headers[SECRET_HEADER],
    end: () => (context.res = {
        status: 200,
        body: "",
    }),
    respond: (json) => {
        context.res.set("Content-Type", "application/json");
        context.res.send(json);
    },
    unauthorized: () => {
        context.res.send(401, WRONG_TOKEN_ERROR);
    },
});
/** Next.js Serverless Functions */
const nextJs = (req, res) => ({
    update: Promise.resolve(req.body),
    header: req.headers[SECRET_HEADER_LOWERCASE],
    end: () => res.end(),
    respond: (json) => res.status(200).json(json),
    unauthorized: () => res.status(401).send(WRONG_TOKEN_ERROR),
});
/** Sveltekit Serverless Functions */
const sveltekit = ({ request }) => {
    let resolveResponse;
    return {
        update: Promise.resolve(request.json()),
        header: request.headers.get(SECRET_HEADER) || undefined,
        end: () => {
            if (resolveResponse)
                resolveResponse(ok());
        },
        respond: (json) => {
            if (resolveResponse)
                resolveResponse(okJson(json));
        },
        unauthorized: () => {
            if (resolveResponse)
                resolveResponse(unauthorized());
        },
        handlerReturn: new Promise((resolve) => {
            resolveResponse = resolve;
        }),
    };
};
/** Native CloudFlare workers (service worker) */
const cloudflare = (event) => {
    let resolveResponse;
    event.respondWith(new Promise((resolve) => {
        resolveResponse = resolve;
    }));
    return {
        update: event.request.json(),
        header: event.request.headers.get(SECRET_HEADER) || undefined,
        end: () => {
            resolveResponse(ok());
        },
        respond: (json) => {
            resolveResponse(okJson(json));
        },
        unauthorized: () => {
            resolveResponse(unauthorized());
        },
    };
};
/** Native CloudFlare workers (module worker) */
const cloudflareModule = (request) => {
    let resolveResponse;
    return {
        update: request.json(),
        header: request.headers.get(SECRET_HEADER) || undefined,
        end: () => {
            resolveResponse(ok());
        },
        respond: (json) => {
            resolveResponse(okJson(json));
        },
        unauthorized: () => {
            resolveResponse(unauthorized());
        },
        handlerReturn: new Promise((resolve) => {
            resolveResponse = resolve;
        }),
    };
};
/** hono web framework */
const hono = (ctx) => {
    let resolveResponse;
    return {
        update: ctx.req.json(),
        header: ctx.req.headers.get(SECRET_HEADER) || undefined,
        end: () => {
            resolveResponse(ctx.body());
        },
        respond: (json) => {
            ctx.header('Content-Type", "application/json');
            resolveResponse(ctx.body(json));
        },
        unauthorized: () => {
            ctx.status(401);
            ctx.statusText(WRONG_TOKEN_ERROR);
            resolveResponse(ctx.body());
        },
        handlerReturn: new Promise((resolve) => {
            resolveResponse = resolve;
        }),
    };
};
/** worktop CloudFlare workers framework */
const worktop = (req, res) => ({
    update: Promise.resolve(req.body.json()),
    header: req.headers.get(SECRET_HEADER),
    end: () => res.end(),
    respond: (json) => res.send(200, json),
    unauthorized: () => res.send(401, WRONG_TOKEN_ERROR),
});
// Please open a PR if you want to add another adapter
exports.adapters = {
    express,
    koa,
    fastify,
    serveHttp,
    "std/http": stdHttp,
    oak,
    http,
    https: http,
    "aws-lambda": awsLambda,
    "aws-lambda-async": awsLambdaAsync,
    azure,
    "next-js": nextJs,
    sveltekit,
    cloudflare,
    "cloudflare-mod": cloudflareModule,
    hono,
    worktop,
};
