import { Hono } from "hono";
import { requireAuth } from "../middleware/auth";
import type { AuthEnv } from "../middleware/auth";
import { rateLimit } from "../middleware/rate-limit";
import { completeCode } from "../lib/ai-completion";
import { isAiAvailable } from "../lib/ai-client";
const copilot = new Hono<AuthEnv>();
const completionLimit = rateLimit({
windowMs: 60_000,
max: 60,
prefix: "copilot",
});
copilot.get("/api/copilot/ping", (c) => {
return c.json({ ok: true, aiAvailable: isAiAvailable() });
});
copilot.post(
"/api/copilot/completions",
completionLimit,
requireAuth,
async (c) => {
let body: any;
try {
body = await c.req.json();
} catch {
return c.json({ error: "invalid JSON body" }, 400);
}
if (!body || typeof body !== "object") {
return c.json({ error: "body must be a JSON object" }, 400);
}
const { prefix, suffix, language, repo } = body as {
prefix?: unknown;
suffix?: unknown;
language?: unknown;
repo?: unknown;
};
if (typeof prefix !== "string" || prefix.length === 0) {
return c.json({ error: "prefix (non-empty string) is required" }, 400);
}
const result = await completeCode({
prefix,
suffix: typeof suffix === "string" ? suffix : undefined,
language: typeof language === "string" ? language : undefined,
repoHint: typeof repo === "string" ? repo : undefined,
});
return c.json(result);
}
);
export default copilot;
|