-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtemplate-loader.ts
More file actions
33 lines (30 loc) · 1.1 KB
/
Copy pathtemplate-loader.ts
File metadata and controls
33 lines (30 loc) · 1.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
import Handlebars from "handlebars";
import { readFileSync } from "node:fs";
import path from "node:path";
import { fileURLToPath } from "node:url";
import { registerHelpers } from "./handlebars-helpers.ts";
const here = path.dirname(fileURLToPath(import.meta.url));
export const TEMPLATES_DIR = path.resolve(here, "../../templates");
export type CompiledTemplate = (context: unknown) => string;
export function loadTemplate(relativePath: string): CompiledTemplate {
if (path.isAbsolute(relativePath)) {
throw new Error(
`template-loader/loadTemplate: absolute path rejected: '${relativePath}'`
);
}
const absolute = path.resolve(TEMPLATES_DIR, relativePath);
const relative = path.relative(TEMPLATES_DIR, absolute);
if (
relative === ".." ||
relative.startsWith(`..${path.sep}`) ||
path.isAbsolute(relative)
) {
throw new Error(
`template-loader/loadTemplate: path escapes templates dir: '${relativePath}'`
);
}
const source = readFileSync(absolute, "utf8");
const hb = Handlebars.create();
registerHelpers(hb);
return hb.compile(source, { noEscape: true });
}