UNPKG

un-oj

Version:

Unified Online Judge information collector.

82 lines (80 loc) 2.21 kB
import { NotFoundError, Platform, UnOJError, UnexpectedResponseError } from "../platform-BncnsqE0.js"; import { FetchError } from "ofetch"; import { load } from "cheerio"; //#region src/platforms/leetcode.ts const QUESTION_QUERY = ` query ($slug: String!) { question(titleSlug: $slug) { title content translatedTitle translatedContent difficulty exampleTestcases topicTags { slug } sampleTestCase } }`; const DEFAULT_BASE_URL = "https://leetcode.com"; /** * LeetCode platform. * * If you want to use LeetCode CN, set `baseURL` to `https://leetcode.cn`. */ var LeetCode = class extends Platform { constructor(options) { super(options, DEFAULT_BASE_URL); } /** Fetches a problem from LeetCode using internal API. */ async getProblem(slug) { let data; try { const res = await this.ofetch("/graphql", { method: "POST", body: { query: QUESTION_QUERY, variables: { slug } }, responseType: "json" }); data = res.data?.question; } catch (e) { if (e instanceof FetchError && e.data?.errors) { const errorMsg = e.data.errors[0]?.message; if (errorMsg?.includes("Not found")) throw new NotFoundError("problem"); } throw new UnOJError(`Failed to fetch problem ${slug}`, { cause: e }); } if (!data) throw new NotFoundError("problem"); const content = data.translatedContent || data.content; const title = data.translatedTitle || data.title; const samples = []; const $ = load(content); $("strong.example").each((_, el) => { const contents = $(el).parent().next().contents(); if (contents.length < 4) throw new UnexpectedResponseError(); const sample = { input: contents.eq(1).text().trim(), output: contents.eq(3).text().trim() }; if (contents.length > 4) sample.hint = contents.eq(5).text().trim(); samples.push(sample); }); return { id: slug, type: "traditional", title, link: new URL(`/problems/${slug}/`, this.baseURL).href, description: content, samples, timeLimit: void 0, memoryLimit: void 0, difficulty: data.difficulty, tags: data.topicTags.map((t) => t.slug) }; } }; //#endregion export { DEFAULT_BASE_URL, LeetCode as default };