eleventy-plugin-vento 5.5.0 → 5.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,11 @@
1
1
  # eleventy-plugin-vento
2
2
 
3
+ ## 5.5.1
4
+
5
+ ### Patch Changes
6
+
7
+ - 3702292: Partially revert 1087bec127bf569a601cb7afb76230b51f5be652, which introduced a regression causing the package to be published without first being built. (fixes #603)
8
+
3
9
  ## 5.5.0
4
10
 
5
11
  ### Minor Changes
@@ -0,0 +1,66 @@
1
+ import * as ventojs$1 from "ventojs";
2
+ import _UserConfig from "@11ty/eleventy/UserConfig";
3
+ import { Plugin } from "ventojs/core/environment.js";
4
+ //#region src/types/utilities.d.ts
5
+ /**
6
+ * Matches any given string so autocomplete in literal unions works as expected
7
+ */
8
+ type AnyString = string & Record<never, never>;
9
+ //#endregion
10
+ //#region src/types/eleventy.d.ts
11
+ interface UserConfig extends _UserConfig {
12
+ directories: {
13
+ input: string;
14
+ output: string;
15
+ includes: string;
16
+ layouts: string;
17
+ };
18
+ }
19
+ //#endregion
20
+ //#region src/types/options.d.ts
21
+ interface PluginOptions {
22
+ /**
23
+ * An array of Vento plugins
24
+ */
25
+ plugins: Plugin[];
26
+ /**
27
+ * Enables Vento's autotrim plugin.
28
+ * @example
29
+ * // Set to an array of tags
30
+ * autotrim: ['tag1', 'tag2']
31
+ * @example
32
+ * // Use Vento's defaults and Eleventy paired shortcodes
33
+ * // Setting `true` is functionally equivalent to both
34
+ * // `@vento` and `@11ty` being present
35
+ * autotrim: ['@vento', '@11ty']
36
+ * autotrim: true
37
+ */
38
+ autotrim: ('@11ty' | '@vento' | AnyString)[] | boolean;
39
+ /**
40
+ * Enable use of Eleventy filters
41
+ */
42
+ filters: boolean;
43
+ /**
44
+ * Enable use of Eleventy shortcodes
45
+ */
46
+ shortcodes: boolean;
47
+ /**
48
+ * Enable use of Eleventy paired shortcodes
49
+ */
50
+ pairedShortcodes: boolean;
51
+ /**
52
+ * A Vento configuration object.
53
+ * @see {@link https://vento.js.org/configuration/}
54
+ * @default
55
+ * {
56
+ * // Defaults to Eleventy's own `includes` directory
57
+ * includes: eleventyConfig.directories.includes
58
+ * }
59
+ */
60
+ ventoOptions: ventojs$1.Options;
61
+ }
62
+ //#endregion
63
+ //#region src/plugin.d.ts
64
+ declare function VentoPlugin(eleventyConfig: UserConfig, userOptions?: Partial<PluginOptions>): void;
65
+ //#endregion
66
+ export { VentoPlugin };
@@ -0,0 +1,257 @@
1
+ import path from "node:path";
2
+ import autotrimPlugin, { defaultTags } from "ventojs/plugins/auto_trim.js";
3
+ import ventojs from "ventojs";
4
+ import { VentoError } from "ventojs/core/errors.js";
5
+ import { styleText } from "node:util";
6
+ import createDebugger from "debug";
7
+ //#region src/utils/create-vento-tag.ts
8
+ function createVentoTag(tagInfo) {
9
+ let LEVEL = 1;
10
+ const IS_PAIRED = tagInfo.group === "paired";
11
+ const tag = (env, token, output, tokens) => {
12
+ const code = token[1];
13
+ if (!(code === tagInfo.name || code.startsWith(`${tagInfo.name} `))) return;
14
+ const { dataVarname } = env.options;
15
+ const thisArg = `{
16
+ page: ${dataVarname}.page,
17
+ eleventy: ${dataVarname}.eleventy
18
+ }`;
19
+ const fn = `__env.utils.eleventyFunctions.get('${tagInfo.group}:${tagInfo.name}')`;
20
+ const args = [code.replace(tagInfo.name, "").trim()];
21
+ const compiled = [];
22
+ if (IS_PAIRED) {
23
+ const nestedVarname = `__content${output.startsWith("__content") ? LEVEL++ : 0}`;
24
+ args.unshift(env.compileFilters(tokens, nestedVarname, env.options.autoescape));
25
+ compiled.push("{", `let ${nestedVarname} = "";`, ...env.compileTokens(tokens, nestedVarname, `/${tagInfo.name}`));
26
+ }
27
+ args.unshift(thisArg);
28
+ compiled.push("{", `const __result = await ${fn}.call(${args.filter(Boolean).join(", ")});`, `${output} += ${env.compileFilters(tokens, "__result", env.options.autoescape)}`, "}");
29
+ if (IS_PAIRED) compiled.push("}");
30
+ return compiled.join("\n");
31
+ };
32
+ return Object.defineProperty(tag, "name", { value: `${tagInfo.name}_${IS_PAIRED ? `EleventyPairedTag` : `EleventyTag`}` });
33
+ }
34
+ //#endregion
35
+ //#region src/utils/logging.ts
36
+ const debug = {
37
+ main: createDebugger("Eleventy:Vento"),
38
+ get cache() {
39
+ return this.main.extend("Cache");
40
+ },
41
+ get render() {
42
+ return this.main.extend("Render");
43
+ },
44
+ get error() {
45
+ return this.main.extend("Error");
46
+ }
47
+ };
48
+ function warn(...messages) {
49
+ for (const message of messages) console.error(styleText("gray", "[warning]"), styleText("yellow", message));
50
+ }
51
+ //#endregion
52
+ //#region src/utils/errors.ts
53
+ const LINE_TERMINATOR = /(\r\n?|[\n\u{2028}\u{2029}])/u;
54
+ var EleventyVentoError = class extends Error {
55
+ static async createFromContext(error) {
56
+ const ctx = await error.getContext();
57
+ const err = new this("An unknown error occured processing Vento templates", ctx, error);
58
+ if (ctx.position === void 0 || ctx.file === void 0) warn(`A \`${ctx.type}\` was thrown, but the exact position within the source code cannot be obtained`, "Use DEBUG=\"Eleventy:Vento*\" to view raw `ErrorContext` information");
59
+ debug.error("Received `ErrorContext` from Vento: %O", ctx);
60
+ if (ctx.file === void 0) return err;
61
+ err.message = `${ctx.type} in ${ctx.file}`;
62
+ if (ctx.position === void 0 || ctx.source === void 0) return err;
63
+ const sourceLines = codeToLines(ctx.source);
64
+ const [sourceLine, sourceColumn] = locateInCode(sourceLines, ctx.position);
65
+ err.message += `:${sourceLine}:${sourceColumn}:\n\n`;
66
+ const pad = sourceLine.toString().length;
67
+ const indent = " ".repeat(pad);
68
+ for (let line = Math.max(sourceLine - 3, 1); line <= sourceLine; line++) err.message += `${String(line).padStart(pad)} │ ${sourceLines[line - 1].trimEnd()}\n`;
69
+ err.message += `${indent} ${" ".repeat(sourceColumn - 1)}^`;
70
+ if (!ctx.code || ctx.line === void 0 || ctx.column === void 0) return err;
71
+ const codelines = codeToLines(ctx.code);
72
+ err.message += `\n\n${indent} │ /// compiled Vento function for ${ctx.file} ///\n${indent} │ ${codelines[ctx.line - 1].trimEnd()}\n${indent} ${" ".repeat(ctx.column - 1)}^`;
73
+ return err;
74
+ }
75
+ constructor(message, context, cause) {
76
+ super(message, { cause });
77
+ this.context = context;
78
+ }
79
+ };
80
+ /**
81
+ * Converts a code string to an array of lines
82
+ */
83
+ function codeToLines(code) {
84
+ const doubleLines = code.split(LINE_TERMINATOR);
85
+ const lines = [];
86
+ for (let i = 0; i < doubleLines.length; i += 2) lines.push(`${doubleLines[i]}${doubleLines[i + 1] ?? ""}`);
87
+ return lines;
88
+ }
89
+ /**
90
+ * Identifies the line/column location from a character index
91
+ */
92
+ function locateInCode(lines, position) {
93
+ if (position < 0) return [1, 1];
94
+ let index = 0;
95
+ for (const [line, content] of lines.entries()) {
96
+ const { length } = content;
97
+ if (position < index + length) return [line + 1, position - index + 1];
98
+ index += length;
99
+ }
100
+ throw new Error(`Positon ${position} is out of bounds for the provided source`);
101
+ }
102
+ //#endregion
103
+ //#region src/engine.ts
104
+ function createVentoEngine(options) {
105
+ const env = ventojs(options);
106
+ /**
107
+ * Load plugins into Vento environment
108
+ */
109
+ function loadPlugins(plugins) {
110
+ for (const plugin of plugins) env.use(plugin);
111
+ }
112
+ /**
113
+ * Load filters into Vento environment
114
+ */
115
+ function loadFilters(filters) {
116
+ for (const [name, fn] of Object.entries(filters)) env.filters[name] = function(...args) {
117
+ const { page, eleventy } = this.data;
118
+ return fn.apply({
119
+ ...this,
120
+ page,
121
+ eleventy
122
+ }, args);
123
+ };
124
+ }
125
+ /**
126
+ * Load shortcodes (tags) into Vento environment
127
+ */
128
+ function loadShortcodes(group, shortcodes) {
129
+ if (!(env.utils.eleventyFunctions instanceof Map)) env.utils.eleventyFunctions = /* @__PURE__ */ new Map();
130
+ for (const [name, fn] of Object.entries(shortcodes)) {
131
+ env.utils.eleventyFunctions.set(`${group}:${name}`, fn);
132
+ env.tags.push(createVentoTag({
133
+ name,
134
+ group
135
+ }));
136
+ }
137
+ }
138
+ /**
139
+ * Clear one or more items from Vento's cache
140
+ */
141
+ function removeCachedItems(items) {
142
+ for (let item of items) {
143
+ item = path.normalize(item);
144
+ debug.cache("Delete cache entry for %s", item);
145
+ env.cache.delete(item);
146
+ }
147
+ }
148
+ /**
149
+ * Given a source string and file, compile or get a cached template function,
150
+ * then produce an Eleventy render function for it and return it.
151
+ */
152
+ async function getRenderFunction(source, file, options) {
153
+ debug.main("Getting render function for `%s`", file);
154
+ let template = await env.cache.get(file);
155
+ if (template?.source === source) debug.cache("Cache HIT for `%s`, using precompiled template", file);
156
+ else {
157
+ try {
158
+ debug.cache("Cache MISS for `%s`, will compile new template function", file);
159
+ template = env.compile(source, file);
160
+ } catch (error) {
161
+ if (error instanceof VentoError) throw await EleventyVentoError.createFromContext(error);
162
+ throw error;
163
+ }
164
+ if (options?.cache !== false) env.cache.set(file, template);
165
+ }
166
+ const render = async (data) => {
167
+ try {
168
+ debug.render("Rendering %s", file);
169
+ const { content } = await template(data);
170
+ return content;
171
+ } catch (error) {
172
+ if (error instanceof VentoError) throw await EleventyVentoError.createFromContext(error);
173
+ throw error;
174
+ }
175
+ };
176
+ return render;
177
+ }
178
+ return {
179
+ loadPlugins,
180
+ loadFilters,
181
+ loadShortcodes,
182
+ removeCachedItems,
183
+ getRenderFunction
184
+ };
185
+ }
186
+ //#endregion
187
+ //#region src/plugin.ts
188
+ function VentoPlugin(eleventyConfig, userOptions) {
189
+ debug.main("Initializing eleventy-plugin-vento");
190
+ eleventyConfig.versionCheck(">=3.0.0");
191
+ const options = {
192
+ autotrim: false,
193
+ plugins: [],
194
+ filters: true,
195
+ shortcodes: true,
196
+ pairedShortcodes: true,
197
+ ventoOptions: { includes: eleventyConfig.directories.includes },
198
+ ...userOptions
199
+ };
200
+ debug.main("Merged default and user config: %O", options);
201
+ const filters = eleventyConfig.getFilters();
202
+ debug.main("Reading filters from Eleventy: %o", filters);
203
+ const shortcodes = eleventyConfig.getShortcodes();
204
+ debug.main("Reading shortcodes from Eleventy: %o", shortcodes);
205
+ const pairedShortcodes = eleventyConfig.getPairedShortcodes();
206
+ debug.main("Reading paired shortcodes from Eleventy: %o", pairedShortcodes);
207
+ if (options.autotrim) {
208
+ const tagSet = new Set(options.autotrim === true ? ["@vento", "@11ty"] : options.autotrim);
209
+ if (tagSet.has("@vento")) {
210
+ tagSet.delete("@vento");
211
+ for (const name of defaultTags) tagSet.add(name);
212
+ }
213
+ if (tagSet.has("@11ty")) {
214
+ tagSet.delete("@11ty");
215
+ for (const name in pairedShortcodes) tagSet.add(name);
216
+ }
217
+ debug.main("Enabled autotrim for tags: %o", tagSet);
218
+ options.plugins.push(autotrimPlugin({ tags: [...tagSet] }));
219
+ }
220
+ debug.main("Initializing Vento environment");
221
+ const engine = createVentoEngine(options.ventoOptions);
222
+ debug.main("Loading plugins: %o", options.plugins);
223
+ engine.loadPlugins(options.plugins);
224
+ if (options.filters) {
225
+ debug.main("Loading filters: %o", filters);
226
+ engine.loadFilters(filters);
227
+ }
228
+ if (options.shortcodes) {
229
+ debug.main("Loading shortcodes: %o", shortcodes);
230
+ engine.loadShortcodes("single", shortcodes);
231
+ }
232
+ if (options.pairedShortcodes) {
233
+ debug.main("Loading paired shortcodes: %o", pairedShortcodes);
234
+ engine.loadShortcodes("paired", pairedShortcodes);
235
+ }
236
+ debug.main("Adding Vento cache handler for eleventy.beforeWatch event");
237
+ eleventyConfig.on("eleventy.beforeWatch", engine.removeCachedItems);
238
+ debug.main("Registering .vto as a template format");
239
+ eleventyConfig.addTemplateFormats("vto");
240
+ debug.main("Registering .vto extension with eleventy");
241
+ eleventyConfig.addExtension("vto", {
242
+ outputFileExtension: "html",
243
+ read: true,
244
+ async compile(inputContent, inputPath) {
245
+ inputPath = path.normalize(inputPath);
246
+ return await engine.getRenderFunction(inputContent, inputPath, { cache: false });
247
+ },
248
+ compileOptions: { async permalink(permalinkContent, inputPath) {
249
+ if (typeof permalinkContent !== "string" || !/\{\{\s+.+\s+\}\}/.test(permalinkContent)) return permalinkContent;
250
+ inputPath = `EleventyVentoDynamicPermalink:${path.normalize(inputPath)}`;
251
+ return await engine.getRenderFunction(permalinkContent, inputPath);
252
+ } }
253
+ });
254
+ debug.main("eleventy-plugin-vento initialized");
255
+ }
256
+ //#endregion
257
+ export { VentoPlugin };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "eleventy-plugin-vento",
3
- "version": "5.5.0",
3
+ "version": "5.5.1",
4
4
  "description": "Adds support for the Vento templating language to Eleventy.",
5
5
  "type": "module",
6
6
  "engines": {
@@ -54,7 +54,7 @@
54
54
  "globals": "17.7.0",
55
55
  "knip": "6.26.0",
56
56
  "prettier": "3.9.5",
57
- "tsdown": "0.22.4",
57
+ "tsdown": "0.22.7",
58
58
  "typescript": "6.0.3",
59
59
  "typescript-eslint": "8.63.0",
60
60
  "vitest": "4.1.10"