/** * Copyright 2026 aphrody-code * SPDX-License-Identifier: Apache-2.0 */ /** * @module bxc/server/app * * The one BXC HTTP API. Every HTTP surface is an adapter over * {@link createBxcApp}: * - `src/server/index.ts` — long-running server (`bun run server:start`); * - `src/cli/api.ts` — `bxc api` (bearer auth, custom host/port); * - `src/serverless/handler.ts` — `fetch`-style handler for serverless hosts. * * Heavy dependencies (browser, crawler, GraphQL, Google client) are imported * lazily inside handlers so adapters that never hit those routes keep a fast * cold start. */ import { Elysia, t } from "elysia"; import { cors } from "@elysiajs/cors"; import packageManifest from "../../package.json" with { type: "json" }; export interface BxcAppOptions { /** Mount Type-GraphQL at `/graphql`. Default: `true`. */ graphql?: boolean; /** Serve OpenAPI docs at `/swagger`. Default: `true`. */ swagger?: boolean; /** Per-request logging. Default: `true`. */ requestLogger?: boolean; /** Serve `/download` and installer scripts. Default: `true`. */ downloads?: boolean; /** Require `Authorization: Bearer ` on every route except health. */ authToken?: string | null; /** `Access-Control-Allow-Origin`. Default: `*`. */ corsOrigin?: string; } type ScrapeProfile = "static" | "fast" | "http" | "stealth" | "max"; const SCRAPE_PROFILES: readonly ScrapeProfile[] = ["static", "fast", "http", "stealth", "max"]; interface PageRecord { url: string; title: string; status: number; markdown: string; structured: unknown; openapi: unknown; timestamp: string; } function jsonError(status: number, error: string): Response { return Response.json({ ok: false, success: false, error }, { status }); } function parseJson(value: string | null | undefined, fallback: T): T { if (!value) return fallback; try { return JSON.parse(value) as T; } catch { return fallback; } } async function redisGet(key: string): Promise { try { const { redis } = await import("bun"); return await redis.get(key); } catch { // Redis is an optional cache: an unavailable server is a cache miss. return null; } } async function redisSet(key: string, value: string, ttlSeconds: number): Promise { try { const { redis } = await import("bun"); await redis.set(key, value, "EX", ttlSeconds); } catch { // Optional cache. } } async function readStoredPage(url: string): Promise { const { BxcDB } = await import("../db/BxcDB.ts"); const db = new BxcDB(); try { const row = db.getScrapeByUrl(url); if (!row) return null; return { url: row.url, title: parseJson<{ title?: string }>(row.metadata, {}).title ?? "", status: row.status, markdown: row.markdown ?? "", structured: parseJson(row.json_data, null), openapi: parseJson(row.openapi_spec, null), timestamp: row.timestamp, }; } finally { db.close(); } } /** * Resolve a page through the cache hierarchy: Redis → SQLite index → live * crawl (which persists into SQLite). */ async function loadPage( url: string, force = false, ): Promise<{ source: "redis" | "sqlite" | "live-crawl"; data: PageRecord } | null> { const cacheKey = `bxc:cache:url:${url}`; if (!force) { const cached = parseJson(await redisGet(cacheKey), null); if (cached) return { source: "redis", data: cached }; const stored = await readStoredPage(url); if (stored) { await redisSet(cacheKey, JSON.stringify(stored), 86_400); return { source: "sqlite", data: stored }; } } const { AutonomousCrawler } = await import("../crawler/AutonomousCrawler.ts"); const crawler = new AutonomousCrawler({ maxRequests: 1 }); await crawler.run([url]); const crawled = await readStoredPage(url); return crawled ? { source: "live-crawl", data: crawled } : null; } function classifyPlayer(player: Record | null | undefined): string[] { const tags: string[] = []; if (!player) return tags; const n = (key: string) => (typeof player[key] === "number" ? (player[key] as number) : 0); if (n("pac") >= 90) tags.push("Speedster"); else if (n("pac") >= 80) tags.push("Fast"); if (n("sho") >= 85) tags.push("Clinical Finisher"); if (n("pas") >= 85 && n("dri") >= 85) tags.push("Elite Playmaker"); if (n("def") >= 85 && n("phy") >= 85) tags.push("Defensive Wall"); if (n("div") >= 85 && n("ref") >= 85) tags.push("Wall GK"); const playstyles = typeof player.playstylesPlus === "string" ? parseJson(player.playstylesPlus, null) : player.playstylesPlus; if (Array.isArray(playstyles) && playstyles.length > 0) tags.push("Playstyles+ Star"); return tags; } async function scrapeUrl(url: string, profile: ScrapeProfile) { const { Browser } = await import("../api/browser.ts"); const page = await Browser.newPage({ profile }); try { const res = await page.goto(url); return { url, status: res.status, title: await page.title(), content: await page.content(), }; } finally { await page.close(); } } const ENDPOINTS = [ "GET /health", "POST /api/v1/scrape", "POST /api/v1/crawl", "GET /api/v1/crawl/stats", "GET /api/v1/crawl/failed", "POST /api/v1/crawl/replay", "GET /api/v1/page", "GET /api/v1/page/markdown", "GET /api/v1/page/openapi", "GET /api/v1/page/types", "GET /api/v1/search", "GET /api/v1/search/keyword", "GET /api/v1/search/semantic", "GET /api/v1/index/search", "POST /api/v1/extract", "GET /api/v1/autocomplete", "GET /api/v1/recon", "GET /api/v1/detect", "GET /api/v1/fut/player", "GET /api/v1/fut/price", ]; /** Build the BXC HTTP application without binding a port. */ export async function createBxcApp(options: BxcAppOptions = {}) { const corsOrigin = options.corsOrigin ?? "*"; const authToken = options.authToken ?? null; let app = new Elysia() .use(cors({ origin: corsOrigin === "*" ? true : corsOrigin })) .onError(({ code, error }) => { if (code === "NOT_FOUND") return jsonError(404, "Not Found"); if (code === "VALIDATION") return jsonError(400, String(error.message ?? error)); return undefined; }) .onBeforeHandle(({ request, path }) => { if (!authToken || path === "/health") return; if (request.headers.get("authorization") !== `Bearer ${authToken}`) { return jsonError(401, "unauthorized"); } }); if (options.requestLogger ?? true) { const { logger } = await import("@bogeychan/elysia-logger"); app = app.use(logger()) as unknown as typeof app; } if (options.swagger ?? true) { const { swagger } = await import("@elysiajs/swagger"); app = app.use( swagger({ path: "/swagger", documentation: { info: { title: "BXC API", description: "Agent web layer: scrape, crawl, index and search (REST + GraphQL)", version: packageManifest.version, }, }, }), ) as unknown as typeof app; } const jsonManifest = () => ({ ok: true, name: "bxc-api", status: "ok", runtime: "bun", bun: Bun.version, version: packageManifest.version, timestamp: Date.now(), docs: "https://aphrody.com/docs/bxc", download: "/#binaries", install: { bash: "curl -fsSL https://bxc.aphrody.com/install.sh | bash", powershell: "irm https://bxc.aphrody.com/install.ps1 | iex", }, endpoints: ENDPOINTS, }); app = app .get("/", jsonManifest) .get("/health", () => "OK") .get("/healthz", () => ({ ok: true })) as unknown as typeof app; if (options.downloads ?? true) { const [{ default: homeHtml }, { default: installSh }, { default: installPs1 }] = await Promise.all([ import("./home.html", { with: { type: "text" } }), import("../../install.sh", { with: { type: "text" } }), import("../../install.ps1", { with: { type: "text" } }), ]); const html = () => new Response(homeHtml as unknown as string, { headers: { "content-type": "text/html; charset=utf-8" }, }); const shell = () => new Response(installSh as unknown as string, { headers: { "content-type": "text/x-shellscript; charset=utf-8" }, }); const powershell = () => new Response(installPs1 as unknown as string, { headers: { "content-type": "text/plain; charset=utf-8" }, }); app = app .get("/", ({ request }) => { const accept = request.headers.get("accept") ?? ""; const ua = request.headers.get("user-agent") ?? ""; // Serve rich HTML homepage when requested by browser if ( accept.includes("text/html") || (!accept.includes("application/json") && !ua.startsWith("curl") && !ua.startsWith("Wget") && ua.length > 0) ) { return html(); } return jsonManifest(); }) .get("/download", html) .get("/downloads", html) .get("/install.sh", shell) .get("/install.ps1", powershell) .get("/install", ({ request }) => { const ua = request.headers.get("user-agent") ?? ""; if (ua.startsWith("curl") || ua.startsWith("Wget")) return shell(); if (ua.includes("PowerShell")) return powershell(); return html(); }) .get("/dl/:file", async ({ params, set }) => { const file = params.file; if (file.includes("..") || file.includes("/") || file.includes("\\")) { set.status = 400; return "Invalid filename"; } const candidates = [ `dist/standalone/${file}`, `dist/release/${file}`, `dist/${file}`, ]; for (const cand of candidates) { const bunFile = Bun.file(cand); if ((await bunFile.exists()) && bunFile.size > 0) { return new Response(bunFile); } } set.status = 302; set.headers["Location"] = `https://github.com/aphrody-code/bxc/releases/latest/download/${file}`; return undefined; }) as unknown as typeof app; } const api = new Elysia({ prefix: "/api/v1" }) .post( "/scrape", ({ body }) => scrapeUrl(body.url, (body.profile ?? "static") as ScrapeProfile), { body: t.Object({ url: t.String(), profile: t.Optional(t.Union(SCRAPE_PROFILES.map((p) => t.Literal(p)))), }), }, ) .post( "/crawl", async ({ body }) => { const { AutonomousCrawler } = await import("../crawler/AutonomousCrawler.ts"); const crawler = new AutonomousCrawler({ allowedDomains: body.allowedDomains, maxDepth: body.maxDepth, maxRequests: body.maxRequests, profile: body.profile as "static" | "fast" | "stealth" | "max" | undefined, }); crawler.run(body.urls).catch((err) => { console.error("[background-crawler] Error running crawl:", err); }); return { success: true, message: "Recursive crawl started in the background", stats: crawler.stats(), }; }, { body: t.Object({ urls: t.Array(t.String()), allowedDomains: t.Optional(t.Array(t.String())), maxDepth: t.Optional(t.Number()), maxRequests: t.Optional(t.Number()), profile: t.Optional(t.String()), }), }, ) .get("/crawl/stats", async () => { const { RequestQueue } = await import("../queue/RequestQueue.ts"); const queue = RequestQueue.open("bxc-autonomous-crawler"); try { return { success: true, stats: queue.stats() }; } finally { queue.close(); } }) .post("/crawl/replay", async () => { const { AutonomousCrawler } = await import("../crawler/AutonomousCrawler.ts"); const crawler = new AutonomousCrawler(); const count = crawler.replayFailed(); return { success: true, message: `Requeued ${count} failed requests from the dead-letter queue.`, stats: crawler.stats(), }; }) .get("/crawl/failed", async () => { const { AutonomousCrawler } = await import("../crawler/AutonomousCrawler.ts"); const failed = new AutonomousCrawler().deadLetterQueue(); return { success: true, count: failed.length, failed: failed.map((req) => ({ id: req.id, url: req.url, method: req.method, retries: req.retries, errorMessage: req.errorMessage, createdAt: req.createdAt, handledAt: req.handledAt, })), }; }) .get( "/page", async ({ query }) => { const page = await loadPage(query.url, query.force === "true"); return page ? { success: true, source: page.source, data: page.data } : { success: false, error: "Failed to scrape page" }; }, { query: t.Object({ url: t.String(), force: t.Optional(t.String()) }) }, ) .get( "/page/openapi", async ({ query }) => { const page = await loadPage(query.url); return page?.data.openapi ?? { error: "OpenAPI schema not available for this URL" }; }, { query: t.Object({ url: t.String() }) }, ) .get( "/page/markdown", async ({ query }) => { const page = await loadPage(query.url); return page?.data.markdown || "Markdown not available for this URL"; }, { query: t.Object({ url: t.String() }) }, ) .get( "/page/types", async ({ query }) => { const page = await loadPage(query.url); if (!page?.data.openapi) { return "Error: OpenAPI schema not found or could not be generated for this URL"; } const { generateTypeScriptTypes } = await import("../utils/typegen.ts"); const name = page.data.title.replace(/[^a-zA-Z0-9]/g, "") || "ScrapedData"; return generateTypeScriptTypes(page.data.openapi as never, name); }, { query: t.Object({ url: t.String() }) }, ) .get( "/search", async ({ query }) => { const { google } = await import("../google/index.ts"); const results = await google.search(query.q, { hl: query.hl ?? "en", gl: query.gl ?? "US", cacheTtlMs: Number(query.cacheTtlMs ?? 300_000), }); return { ok: true, query: query.q, results }; }, { query: t.Object({ q: t.String({ minLength: 1 }), hl: t.Optional(t.String()), gl: t.Optional(t.String()), cacheTtlMs: t.Optional(t.String()), }), }, ) .get( "/search/keyword", async ({ query }) => { const { BxcDB } = await import("../db/BxcDB.ts"); const db = new BxcDB(); try { const rows = db.searchFullText(query.q, Number.parseInt(query.limit ?? "10", 10)); return { success: true, query: query.q, results: rows.map((r) => ({ url: r.url, profile: r.profile, status: r.status, metadata: parseJson(r.metadata, {}), markdown: r.markdown ? `${r.markdown.slice(0, 300)}...` : "", timestamp: r.timestamp, rank: r.rank, })), }; } finally { db.close(); } }, { query: t.Object({ q: t.String(), limit: t.Optional(t.String()) }) }, ) .get( "/search/semantic", async ({ query }) => { const { BxcDB } = await import("../db/BxcDB.ts"); const { getEmbedding } = await import("../utils/vector.ts"); const queryVector = await getEmbedding(query.q); const db = new BxcDB(); try { const results = db.searchSemantic( queryVector, Number.parseInt(query.limit ?? "5", 10), Number.NEGATIVE_INFINITY, ); return { success: true, query: query.q, results: results.map((r) => ({ url: r.url, metadata: { title: r.title }, markdown: r.markdown ? `${r.markdown.slice(0, 300)}...` : "", similarity: r.similarity, })), }; } finally { db.close(); } }, { query: t.Object({ q: t.String(), limit: t.Optional(t.String()) }) }, ) .post( "/extract", async ({ body }) => { const { extractUrlWithSchema } = await import("../extract/index.ts"); const results = await Promise.all( body.urls.map(async (url) => { try { const result = await extractUrlWithSchema(url, body.schema, { profile: (body.profile ?? "http") as never, cache: body.useCache === false ? false : undefined, }); return { url, finalUrl: result.finalUrl, source: result.source, confidence: result.confidence, data: result.records ?? result.record, missingFields: result.missingFields, }; } catch (err) { return { url, error: err instanceof Error ? err.message : String(err) }; } }), ); return { ok: true, results }; }, { body: t.Object({ urls: t.Array(t.String({ minLength: 1 }), { minItems: 1, maxItems: 50 }), schema: t.Any(), profile: t.Optional(t.String()), useCache: t.Optional(t.Boolean()), }), }, ) .get( "/index/search", async ({ query }) => { const { BxcDB } = await import("../db/BxcDB.ts"); const db = new BxcDB(); try { const limit = Number.parseInt(query.limit ?? "8", 10); let vector: Float32Array | undefined; let model: string | undefined; if (query.mode !== "keyword") { const { defaultEmbedder } = await import("../embed/embedder.ts"); const embedder = await defaultEmbedder(); model = embedder.model; [vector] = await embedder.embed([query.q], "query"); await db.openVectorIndex(embedder.model, embedder.dim).catch(() => null); } const hits = query.mode === "keyword" ? db.searchChunks(query.q, limit) : db.searchChunksHybrid(query.q, vector, limit, { model }); return { ok: true, query: query.q, results: hits }; } finally { db.close(); } }, { query: t.Object({ q: t.String({ minLength: 1 }), limit: t.Optional(t.String()), mode: t.Optional(t.Union([t.Literal("hybrid"), t.Literal("keyword")])), }), }, ) .get( "/autocomplete", async ({ query }) => { const { googleAutocomplete } = await import("../google/verticals.ts"); return { ok: true, query: query.q, suggestions: await googleAutocomplete(query.q, { hl: query.hl, gl: query.gl }), }; }, { query: t.Object({ q: t.String({ minLength: 1 }), hl: t.Optional(t.String()), gl: t.Optional(t.String()), }), }, ) .get( "/recon", async ({ query }) => { const { recon } = await import("../cli/recon.ts"); return recon({ url: query.url, profile: "http", screenshot: false, json: true, quiet: true, plain: false, } as Parameters[0]); }, { query: t.Object({ url: t.String({ minLength: 1 }) }) }, ) .get( "/detect", async ({ query }) => { const { deepDetect } = await import("../detect-deep.ts"); return deepDetect(query.url, query.insecure === "true"); }, { query: t.Object({ url: t.String({ minLength: 1 }), insecure: t.Optional(t.String()) }) }, ) .get( "/fut/player", async ({ query }) => { const { scrapeFutGgPlayer } = await import("@aphrody/fut"); try { const data = await scrapeFutGgPlayer(query.url, (query.profile ?? "static") as never); return { success: true, data: { ...data, classifications: classifyPlayer(data as unknown as Record), }, }; } catch (e) { return { success: false, error: e instanceof Error ? e.message : String(e) }; } }, { query: t.Object({ url: t.String(), profile: t.Optional(t.String()) }) }, ) .get( "/fut/price", async ({ query }) => { const { scrapeFutBinPrice } = await import("@aphrody/fut"); try { const data = await scrapeFutBinPrice(query.url, (query.profile ?? "ghost") as never); return { success: true, data }; } catch (e) { return { success: false, error: e instanceof Error ? e.message : String(e) }; } }, { query: t.Object({ url: t.String(), profile: t.Optional(t.String()) }) }, ); app = app.use(api) as unknown as typeof app; if (options.graphql ?? true) { await import("reflect-metadata"); const [{ createYoga }, { buildSchema }, { ScrapeResolver }, { FutResolver }] = await Promise.all([ import("graphql-yoga"), import("type-graphql"), import("./graphql/resolvers/ScrapeResolver.ts"), import("@aphrody/fut"), ]); const schema = await buildSchema({ resolvers: [ScrapeResolver, FutResolver], validate: false }); const yoga = createYoga({ schema }); app = app.all("/graphql", ({ request }) => yoga.handle(request)) as unknown as typeof app; } return app; } export type BxcApp = Awaited>;