this repo has no description
1import { getEntry } from "astro:content";
2import { defineMiddleware } from "astro:middleware";
3import { JSDOM } from "jsdom";
4
5export const onRequest = defineMiddleware(async ({ locals, url }, next) => {
6 locals.lang = process.env.LANG === "fr" ? "fr" : "en";
7 locals.locale = (process.env.LOCALE ||
8 "en-US") as `${typeof locals.lang}-${string}`;
9 locals.buildCommit =
10 // Explicit commit
11 process.env.BUILD_COMMIT ||
12 // Netlify
13 process.env.COMMIT_REF ||
14 // Cloudflare Pages
15 process.env.CF_PAGES_COMMIT_SHA ||
16 // Fallback
17 "dev";
18
19 const response = await next();
20
21 if (
22 ["application/json", "text/plain"].includes(
23 response.headers.get("content-type")?.split(";")[0] || "",
24 )
25 ) {
26 return response;
27 }
28
29 const dom = new JSDOM(await response.text(), {
30 url: url.toString(),
31 contentType: response.headers.get("content-type") || "text/html",
32 });
33
34 for (const translatable of dom.window.document.querySelectorAll("[i18n]")) {
35 const key = translatable.textContent?.trim();
36 if (!key) continue;
37
38 const translation =
39 locals.lang === "fr"
40 ? await getEntry("frenchMessages", key)
41 : { data: { msgstr: key } };
42
43 translatable.removeAttribute("i18n");
44 if (translation) {
45 translatable.innerHTML = translation.data.msgstr;
46 }
47 }
48
49 for (const translatable of dom.window.document.querySelectorAll("i18n")) {
50 const key = translatable.innerHTML?.trim();
51 if (!key) continue;
52
53 const translation =
54 locals.lang === "fr" ? await getEntry("frenchMessages", key) : undefined;
55
56 translatable.outerHTML = translation?.data.msgstr ?? key;
57 }
58
59 return new Response(dom.serialize(), {
60 status: 200,
61 headers: response.headers,
62 });
63});