/
includes_loader.ts
68 lines (52 loc) 路 1.44 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
64
65
66
67
68
import { posix } from "../deps/path.ts";
import { Exception } from "./errors.ts";
import type { Data, Formats, Reader } from "../core.ts";
export interface Options {
/** The reader instance used to read the files */
reader: Reader;
/** The default _includes directory */
includes: string;
/** The registered file formats */
formats: Formats;
}
/**
* Class to load _includes files.
*/
export default class IncludesLoader {
/** The filesystem reader */
reader: Reader;
/** Default _includes path */
includes: string;
/** List of extensions to load files and the loader used */
formats: Formats;
constructor(options: Options) {
this.reader = options.reader;
this.formats = options.formats;
this.includes = options.includes;
}
async load(path: string, from?: string): Promise<[string, Data] | undefined> {
const entry = this.formats.search(path);
if (!entry) {
return;
}
const [, format] = entry;
if (!format.pageLoader) {
return;
}
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,
await this.reader.read(finalPath, format.pageLoader),
];
}
}