This commit is contained in:
Daniel Ledda
2024-10-31 23:46:23 +01:00
parent 314ccaa677
commit bcb820f35e
36 changed files with 4427 additions and 61 deletions

View File

@@ -2,15 +2,19 @@ import { CompilerOptions, transpile, TranspileOptions } from "jsr:@deno/emit";
import denoJson from "./deno.json" with { type: "json" };
const contentTypes = {
'js': "application/javascript; charset=utf-8",
"js": "application/javascript; charset=utf-8",
// https://github.com/denoland/deno_ast/blob/ea1ccec37e1aa8e5e1e70f983a7ed1472d0e132a/src/media_type.rs#L117
'ts': "text/typescript; charset=utf-8",
'jsx': "text/jsx; charset=utf-8",
'tsx': "text/tsx; charset=utf-8",
"ts": "text/typescript; charset=utf-8",
"jsx": "text/jsx; charset=utf-8",
"tsx": "text/tsx; charset=utf-8",
} as const;
const transpileOptions = (extension: keyof typeof contentTypes, tsCode: string, targetUrlStr: string): TranspileOptions => ({
const transpileOptions = (
extension: keyof typeof contentTypes,
tsCode: string,
targetUrlStr: string,
): TranspileOptions => ({
importMap: {
imports: denoJson.imports,
},
@@ -21,16 +25,20 @@ const transpileOptions = (extension: keyof typeof contentTypes, tsCode: string,
kind: "module",
specifier,
content: correctContent ? tsCode : "",
headers: { "content-type": contentTypes[correctContent ? extension : 'js'] },
headers: { "content-type": contentTypes[correctContent ? extension : "js"] },
});
},
});
export default async function transpileResponse(response: Response, requestUrl: string, filepath?: string): Promise<Response> {
const url = new URL(`ts-serve:///${ requestUrl }`);
export default async function transpileResponse(
response: Response,
requestUrl: string,
filepath?: string,
): Promise<Response> {
const url = new URL(`ts-serve:///${requestUrl}`);
const pathname = filepath !== undefined ? filepath : url.pathname;
const extension = pathname.split('.').at(-1) ?? '';
if (response.status === 200 && (extension === 'ts' || extension === 'tsx' || extension === 'jsx')) {
const extension = pathname.split(".").at(-1) ?? "";
if (response.status === 200 && (extension === "ts" || extension === "tsx" || extension === "jsx")) {
const tsCode = await response.text();
const targetUrlStr = url.toString();
try {
@@ -44,9 +52,9 @@ export default async function transpileResponse(response: Response, requestUrl:
headers: response.headers,
});
} catch (e) {
console.error('[transpileResponse]: Error transpiling!\n', e);
if (typeof e === 'string') {
return new Response('Internal Server Error', {
console.error("[transpileResponse]: Error transpiling!\n", e);
if (typeof e === "string") {
return new Response("Internal Server Error", {
status: 500,
headers: response.headers,
});