165 lines
6.3 KiB
TypeScript
165 lines
6.3 KiB
TypeScript
/** Моки внешних сервисов: повторяют контракты HTTP API Google и Telegram Bot API. */
|
||
import type { TgUpdate } from "../src/telegram.ts";
|
||
|
||
export interface MockCall {
|
||
url: string;
|
||
method: string;
|
||
body?: string;
|
||
}
|
||
|
||
function json(status: number, body: unknown): Response {
|
||
return new Response(JSON.stringify(body), { status, headers: { "Content-Type": "application/json" } });
|
||
}
|
||
|
||
const b64 = (s: string) => Buffer.from(s, "utf8").toString("base64url");
|
||
|
||
export interface MockMail {
|
||
id: string;
|
||
subject: string;
|
||
from: string;
|
||
body: string;
|
||
html?: boolean;
|
||
}
|
||
|
||
export interface MockEvent {
|
||
id: string;
|
||
summary: string;
|
||
description?: string;
|
||
start: string;
|
||
end: string;
|
||
}
|
||
|
||
/** mockGoogle: OAuth, Gmail, Calendar. */
|
||
export function mockGoogle(opts: { mails?: MockMail[]; events?: MockEvent[]; refreshValid?: boolean } = {}) {
|
||
const calls: MockCall[] = [];
|
||
const created: unknown[] = [];
|
||
const state = {
|
||
mails: opts.mails ?? [],
|
||
events: opts.events ?? [],
|
||
refreshValid: opts.refreshValid ?? true,
|
||
};
|
||
const fetchFn = (async (input: string | URL | Request, init?: RequestInit) => {
|
||
const url = String(input);
|
||
const method = init?.method ?? "GET";
|
||
const body = typeof init?.body === "string" ? init.body : init?.body ? String(init.body) : undefined;
|
||
calls.push({ url, method, body });
|
||
const auth = (init?.headers as Record<string, string> | undefined)?.Authorization;
|
||
if (url === "https://oauth2.googleapis.com/token") {
|
||
const p = new URLSearchParams(body);
|
||
if (p.get("grant_type") === "authorization_code") {
|
||
if (p.get("code") !== "good-code") return json(400, { error: "invalid_grant" });
|
||
return json(200, { access_token: "mock-access", expires_in: 3600, refresh_token: "mock-refresh" });
|
||
}
|
||
if (!state.refreshValid || p.get("refresh_token") !== "mock-refresh")
|
||
return json(400, { error: "invalid_grant" });
|
||
return json(200, { access_token: "mock-access", expires_in: 3600 });
|
||
}
|
||
if (auth !== "Bearer mock-access")
|
||
return json(401, { error: { message: "unauthenticated", status: "UNAUTHENTICATED" } });
|
||
if (url.startsWith("https://openidconnect.googleapis.com/v1/userinfo"))
|
||
return json(200, { email: "tanya@example.com" });
|
||
const msgList = /gmail\/v1\/users\/me\/messages\?/.exec(url);
|
||
if (msgList) return json(200, { messages: state.mails.map((m) => ({ id: m.id, threadId: `t${m.id}` })) });
|
||
const msg = /gmail\/v1\/users\/me\/messages\/([^?]+)\?format=full/.exec(url);
|
||
if (msg) {
|
||
const m = state.mails.find((x) => x.id === decodeURIComponent(msg[1] ?? ""));
|
||
if (!m) return json(404, { error: { message: "not found" } });
|
||
return json(200, {
|
||
id: m.id,
|
||
threadId: `t${m.id}`,
|
||
payload: {
|
||
mimeType: "multipart/alternative",
|
||
headers: [
|
||
{ name: "Subject", value: m.subject },
|
||
{ name: "From", value: m.from },
|
||
],
|
||
parts: [{ mimeType: m.html ? "text/html" : "text/plain", body: { data: b64(m.body) } }],
|
||
},
|
||
});
|
||
}
|
||
if (url.startsWith("https://www.googleapis.com/calendar/v3/calendars/primary/events")) {
|
||
if (method === "POST") {
|
||
const ev = JSON.parse(body ?? "{}");
|
||
created.push(ev);
|
||
return json(200, {
|
||
id: `created${created.length}`,
|
||
htmlLink: `https://calendar.google.com/event?eid=created${created.length}`,
|
||
});
|
||
}
|
||
return json(200, {
|
||
items: state.events.map((e) => ({
|
||
id: e.id,
|
||
summary: e.summary,
|
||
description: e.description,
|
||
start: { dateTime: e.start },
|
||
end: { dateTime: e.end },
|
||
htmlLink: `https://calendar.google.com/event?eid=${e.id}`,
|
||
})),
|
||
});
|
||
}
|
||
return json(404, { error: { message: `unexpected ${url}` } });
|
||
}) as typeof fetch;
|
||
return { fetchFn, calls, created, state };
|
||
}
|
||
|
||
/** mockTelegram: getMe, getWebhookInfo, getUpdates, sendMessage, answerCallbackQuery. */
|
||
export function mockTelegram(opts: { webhook?: string; conflict?: boolean } = {}) {
|
||
const sent: { chat_id: number | string; text: string; reply_markup?: unknown }[] = [];
|
||
const answers: { callback_query_id: string; text?: string }[] = [];
|
||
const queue: TgUpdate[] = [];
|
||
const calls: string[] = [];
|
||
const fetchFn = (async (input: string | URL | Request, init?: RequestInit) => {
|
||
const url = String(input);
|
||
const m = /^https:\/\/api\.telegram\.org\/botmock-token\/(\w+)$/.exec(url);
|
||
if (!m) return json(401, { ok: false, error_code: 401, description: "Unauthorized" });
|
||
const method = m[1] ?? "";
|
||
calls.push(method);
|
||
const params = JSON.parse(String(init?.body ?? "{}"));
|
||
switch (method) {
|
||
case "getMe":
|
||
return json(200, {
|
||
ok: true,
|
||
result: { id: 1, is_bot: true, first_name: "Foxy", username: "MyFoxy_bot_bot" },
|
||
});
|
||
case "getWebhookInfo":
|
||
return json(200, { ok: true, result: { url: opts.webhook ?? "", pending_update_count: 0 } });
|
||
case "getUpdates": {
|
||
if (opts.conflict)
|
||
return json(409, {
|
||
ok: false,
|
||
error_code: 409,
|
||
description: "Conflict: terminated by other getUpdates request",
|
||
});
|
||
const res = queue.filter((u) => params.offset === undefined || u.update_id >= params.offset);
|
||
queue.length = 0;
|
||
return json(200, { ok: true, result: res });
|
||
}
|
||
case "sendMessage":
|
||
sent.push(params);
|
||
return json(200, {
|
||
ok: true,
|
||
result: { message_id: sent.length, date: 0, chat: { id: params.chat_id, type: "private" } },
|
||
});
|
||
case "answerCallbackQuery":
|
||
answers.push(params);
|
||
return json(200, { ok: true, result: true });
|
||
case "deleteWebhook":
|
||
case "setWebhook":
|
||
return json(200, { ok: true, result: true });
|
||
default:
|
||
return json(404, { ok: false, error_code: 404, description: "Not Found" });
|
||
}
|
||
}) as typeof fetch;
|
||
return { fetchFn, sent, answers, queue, calls };
|
||
}
|
||
|
||
/** Один fetch на оба мока. */
|
||
export function combine(...fns: (typeof fetch)[]): typeof fetch {
|
||
return (async (input: string | URL | Request, init?: RequestInit) => {
|
||
const url = String(input);
|
||
const fn = url.startsWith("https://api.telegram.org/") ? fns[1] : fns[0];
|
||
if (!fn) throw new Error("no mock");
|
||
return fn(input, init);
|
||
}) as typeof fetch;
|
||
}
|