/
includes_loader.ts
63 lines (50 loc) 路 1.36 KB
/
includes_loader.ts
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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
import { posix } from "../deps/path.ts";
import { Exception } from "./errors.ts";
import type { Data, Format, Reader } from "../core.ts";
export interface Options {
/** The reader instance used to read the files */
reader: Reader;
/** The default _includes directory */
includes: string;
}
/**
* Class to load _includes files.
*/
export default class IncludesLoader {
/** The filesystem reader */
reader: Reader;
/** Default _includes path */
includes: string;
constructor(options: Options) {
this.reader = options.reader;
this.includes = options.includes;
}
resolve(path: string, format: Format, from?: string): string | undefined {
let finalPath: string;
if (path.startsWith(".")) {
if (!from) {
throw new Exception(`Cannot load "${path}" without a base path`, {
path,
});
}
finalPath = posix.join("/", posix.dirname(from), path);
} else {
finalPath = posix.join("/", format.includesPath || this.includes, path);
}
return finalPath;
}
async load(
path: string,
format: Format,
from?: string,
): Promise<[string, Data] | undefined> {
const finalPath = this.resolve(path, format, from);
if (!finalPath || !format.pageLoader) {
return;
}
return [
finalPath,
await this.reader.read(finalPath, format.pageLoader),
];
}
}