-
Notifications
You must be signed in to change notification settings - Fork 0
/
engine.js
87 lines (74 loc) · 2.55 KB
/
engine.js
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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
/**
* @file Function that handles creating the Vento environment. Exposes
* a simple API for Eleventy to interface with.
*
* @typedef {{eleventy?: Record<string, unknown>, page?: Record<string, unknown>}} EleventyContext
* @typedef {Context & Record<string, unknown>} EleventyData
* @typedef {(...args: unknown[]) => unknown} EleventyFunction
* @typedef {import('ventojs/src/environment.js').Environment} VentoEnvironment
* @typedef {VentoEnvironment & {
* utils: { _11ty: { ctx: Context, tags: Record<string, EleventyFunction> } }
* }} EleventyVentoEnvironment
*/
// External library
import ventojs from 'ventojs';
// Internal modules
import { createVentoTag } from './modules/create-vento-tag.js';
import { CONTEXT_DATA_KEYS } from './modules/utils.js';
/** @param {import('ventojs').Options} options */
export function createVentoEngine(options) {
/** @type {EleventyVentoEnvironment} */
const env = ventojs(options);
env.utils._11ty = { ctx: {}, functions: {} };
return {
/** @param {string} path */
getCachedSource(path) {
return env.cache.get(path)?.source;
},
/** @param {string} path */
emptyCache(path) {
return path ? env.cache.delete(path) : env.cache.clear();
},
/** @param {import('ventojs/src/environment.js').Plugin[]} plugins */
loadPlugins(plugins) {
for (const plugin of plugins) {
env.use(plugin);
}
},
/** @param {PageData} newContext */
loadContext(newContext) {
// Loop through allowed keys and load those into the context
for (const K of CONTEXT_DATA_KEYS) {
env.utils._11ty.ctx[K] = newContext[K];
}
},
/** @param {Record<string, EleventyFunction>} filters */
loadFilters(filters) {
for (const [name, fn] of Object.entries(filters)) {
env.filters[name] = (...args) => fn.apply(env.utils._11ty.ctx, args);
}
},
/**
* @param {Record<string, EleventyFunction>} shortcodes
* @param {boolean} paired
*/
loadShortcodes(shortcodes, paired = false) {
for (const [name, fn] of Object.entries(shortcodes)) {
env.utils._11ty.functions[name] = fn;
env.tags.push(createVentoTag(name, paired));
}
},
/** @param {{data: PageData, source: string, path: string}} input */
async process(input) {
// Reload context
this.loadContext(input.data);
// Before we compile, empty the cache if the input content doesn't match
if (env.cache.get(input.path)?.source !== input.source) {
env.cache.delete(input.path);
}
// Process the templates
const result = await env.runString(input.source, input.data, input.path);
return result.content;
},
};
}