djledda.de main
25'ten fazla konu seçemezsiniz Konular bir harf veya rakamla başlamalı, kısa çizgiler ('-') içerebilir ve en fazla 35 karakter uzunluğunda olabilir.
 
 

66 satır
2.4 KiB

  1. import { CompilerOptions, transpile, TranspileOptions } from "jsr:@deno/emit";
  2. import denoJson from "./deno.json" with { type: "json" };
  3. const contentTypes = {
  4. "js": "application/javascript; charset=utf-8",
  5. // https://github.com/denoland/deno_ast/blob/ea1ccec37e1aa8e5e1e70f983a7ed1472d0e132a/src/media_type.rs#L117
  6. "ts": "text/typescript; charset=utf-8",
  7. "jsx": "text/jsx; charset=utf-8",
  8. "tsx": "text/tsx; charset=utf-8",
  9. } as const;
  10. const transpileOptions = (
  11. extension: keyof typeof contentTypes,
  12. tsCode: string,
  13. targetUrlStr: string,
  14. ): TranspileOptions => ({
  15. importMap: {
  16. imports: denoJson.imports,
  17. },
  18. compilerOptions: denoJson.compilerOptions as CompilerOptions,
  19. load(specifier) {
  20. const correctContent = specifier === targetUrlStr;
  21. return Promise.resolve({
  22. kind: "module",
  23. specifier,
  24. content: correctContent ? tsCode : "",
  25. headers: { "content-type": contentTypes[correctContent ? extension : "js"] },
  26. });
  27. },
  28. });
  29. export default async function transpileResponse(
  30. response: Response,
  31. requestUrl: string,
  32. filepath?: string,
  33. ): Promise<Response> {
  34. const url = new URL(`ts-serve:///${requestUrl}`);
  35. const pathname = filepath !== undefined ? filepath : url.pathname;
  36. const extension = pathname.split(".").at(-1) ?? "";
  37. if (response.status === 200 && (extension === "ts" || extension === "tsx" || extension === "jsx")) {
  38. const tsCode = await response.text();
  39. const targetUrlStr = url.toString();
  40. try {
  41. const result = await transpile(url, transpileOptions(extension, tsCode, targetUrlStr));
  42. const jsCode = result.get(targetUrlStr);
  43. response.headers.delete("content-length");
  44. response.headers.set("content-type", contentTypes.js);
  45. return new Response(jsCode, {
  46. status: response.status,
  47. statusText: response.statusText,
  48. headers: response.headers,
  49. });
  50. } catch (e) {
  51. console.error("[transpileResponse]: Error transpiling!\n", e);
  52. if (typeof e === "string") {
  53. return new Response("Internal Server Error", {
  54. status: 500,
  55. headers: response.headers,
  56. });
  57. }
  58. }
  59. }
  60. return response;
  61. }