code-share/server/api/preview/serve-html.ts

58 lines
1.7 KiB
TypeScript
Raw Normal View History

2024-02-22 12:14:58 +00:00
import db from "~/server/db";
import { FileSchema, file } from "~/server/db/schema/file";
2024-02-21 02:01:35 +07:00
import { and, eq, isNull } from "drizzle-orm";
2024-02-22 20:59:20 +00:00
import { IS_DEV } from "~/server/lib/consts";
import type { ProjectSettingsSchema } from "~/server/db/schema/project";
export const serveHtml = async (
fileData: FileSchema,
settings: Partial<ProjectSettingsSchema>
) => {
2024-02-21 02:01:35 +07:00
const layout = await db.query.file.findFirst({
where: and(
2024-02-22 20:59:20 +00:00
eq(file.projectId, fileData.projectId),
2024-02-21 02:01:35 +07:00
eq(file.filename, "_layout.html"),
fileData.parentId
? eq(file.parentId, fileData.parentId)
: isNull(file.parentId),
isNull(file.deletedAt)
),
});
let content = fileData.content || "";
if (layout?.content != null) {
content = layout.content.replace("{CONTENT}", content);
2024-02-21 02:01:35 +07:00
}
const bodyOpeningTagIdx = content.indexOf("<body");
const firstScriptTagIdx = content.indexOf("<script", bodyOpeningTagIdx);
2024-02-22 20:59:20 +00:00
const injectScripts = ['<script src="/js/hook-console.js"></script>'];
// prevent direct access
2024-02-24 08:19:34 +00:00
// if (!IS_DEV) {
// injectScripts.push(
// `<script>if (window === window.parent) {window.location.href = '/';}</script>`
// );
// }
2024-02-21 02:01:35 +07:00
// js import maps
const importMaps = settings?.js?.packages || [];
2024-02-21 02:01:35 +07:00
if (importMaps.length > 0) {
const imports = importMaps.reduce((a: any, b) => {
a[b.name] = b.url;
return a;
}, {});
const json = JSON.stringify({ imports });
2024-02-22 12:14:58 +00:00
injectScripts.unshift(`<script type="importmap">${json}</script>`);
2024-02-21 02:01:35 +07:00
}
if (firstScriptTagIdx >= 0 && injectScripts.length > 0) {
content =
content.substring(0, firstScriptTagIdx) +
injectScripts.filter((i) => !!i).join("") +
content.substring(firstScriptTagIdx);
}
return content;
};