28 lines
896 B
TypeScript
28 lines
896 B
TypeScript
import type { Feature } from "@stc/contracts";
|
|
import { badRequest, body, json } from "./http";
|
|
|
|
const MAX = 200_000;
|
|
const ts = new Bun.Transpiler({ loader: "ts", target: "browser" });
|
|
|
|
/** Type-strips TypeScript for the in-browser runner (the worker itself runs plain JavaScript). */
|
|
export function transpileTs(code: string): string {
|
|
return ts.transformSync(code);
|
|
}
|
|
|
|
export function transpileRoutes(): Feature["routes"] {
|
|
return {
|
|
"/api/learner/transpile": {
|
|
POST: async (req) => {
|
|
const b = await body<{ code?: string }>(req);
|
|
if (!b || typeof b.code !== "string") return badRequest("code is required");
|
|
if (b.code.length > MAX) return badRequest("code is too long");
|
|
try {
|
|
return json({ code: transpileTs(b.code) });
|
|
} catch (e) {
|
|
return json({ error: (e as Error).message }, 422);
|
|
}
|
|
},
|
|
},
|
|
};
|
|
}
|