Skip to content

Commit

Permalink
Make addPlugin async-friendly, fixes #2675
Browse files Browse the repository at this point in the history
  • Loading branch information
zachleat committed Oct 24, 2023
1 parent 7f0ada8 commit 70b2d1d
Show file tree
Hide file tree
Showing 3 changed files with 96 additions and 51 deletions.
12 changes: 6 additions & 6 deletions src/TemplateConfig.js
Original file line number Diff line number Diff line change
Expand Up @@ -263,7 +263,7 @@ class TemplateConfig {
*
* @param {Object} - the return Object from the user’s config file.
*/
processPlugins({ dir, pathPrefix }) {
async processPlugins({ dir, pathPrefix }) {
this.userConfig.dir = dir;
this.userConfig.pathPrefix = pathPrefix;

Expand All @@ -278,7 +278,7 @@ class TemplateConfig {
for (let { plugin, options, pluginNamespace } of this.userConfig.plugins) {
try {
this.userConfig.activeNamespace = pluginNamespace;
this.userConfig._executePlugin(plugin, options);
await this.userConfig._executePlugin(plugin, options);
} catch (e) {
let name = this.userConfig._getPluginName(plugin);
let namespaces = [storedActiveNamespace, pluginNamespace].filter((entry) => !!entry);
Expand All @@ -290,7 +290,7 @@ class TemplateConfig {

throw new EleventyPluginError(
`Error processing ${name ? `the \`${name}\`` : "a"} plugin${namespaceStr}`,
e
e,
);
}
}
Expand Down Expand Up @@ -325,7 +325,7 @@ class TemplateConfig {
Object.keys(localConfig.filters).length
) {
throw new EleventyConfigError(
"The `filters` configuration option was renamed in Eleventy 0.3.3 and removed in Eleventy 1.0. Please use the `addTransform` configuration method instead. Read more: https://www.11ty.dev/docs/config/#transforms"
"The `filters` configuration option was renamed in Eleventy 0.3.3 and removed in Eleventy 1.0. Please use the `addTransform` configuration method instead. Read more: https://www.11ty.dev/docs/config/#transforms",
);
}
} catch (err) {
Expand All @@ -335,7 +335,7 @@ class TemplateConfig {
(err.message && err.message.includes("Cannot find module")
? chalk.cyan(" You may need to run `npm install`.")
: ""),
err
err,
);
}
} else {
Expand Down Expand Up @@ -385,7 +385,7 @@ class TemplateConfig {
// Temporarily restore templateFormats
mergedConfig.templateFormats = templateFormats;

this.processPlugins(mergedConfig);
await this.processPlugins(mergedConfig);

delete mergedConfig.templateFormats;

Expand Down
95 changes: 51 additions & 44 deletions src/UserConfig.js
Original file line number Diff line number Diff line change
Expand Up @@ -145,7 +145,7 @@ class UserConfig {

if (typeof tagFn !== "function") {
throw new UserConfigError(
`EleventyConfig.addLiquidTag expects a callback function to be passed in for ${name}: addLiquidTag(name, function(liquidEngine) { return { parse: …, render: … } })`
`EleventyConfig.addLiquidTag expects a callback function to be passed in for ${name}: addLiquidTag(name, function(liquidEngine) { return { parse: …, render: … } })`,
);
}

Expand All @@ -171,13 +171,13 @@ class UserConfig {
if (this.nunjucksAsyncFilters[name]) {
debug(
chalk.yellow("Warning, overwriting a Nunjucks filter with `addNunjucksAsyncFilter(%o)`"),
name
name,
);
}

this.nunjucksAsyncFilters[name] = this.benchmarks.config.add(
`"${name}" Nunjucks Async Filter`,
callback
callback,
);
}

Expand All @@ -192,13 +192,13 @@ class UserConfig {
if (this.nunjucksFilters[name]) {
debug(
chalk.yellow("Warning, overwriting a Nunjucks filter with `addNunjucksFilter(%o)`"),
name
name,
);
}

this.nunjucksFilters[name] = this.benchmarks.config.add(
`"${name}" Nunjucks Filter`,
callback
callback,
);
}
}
Expand All @@ -209,13 +209,13 @@ class UserConfig {
if (this.handlebarsHelpers[name]) {
debug(
chalk.yellow("Warning, overwriting a Handlebars helper with `addHandlebarsHelper(%o)`."),
name
name,
);
}

this.handlebarsHelpers[name] = this.benchmarks.config.add(
`"${name}" Handlebars Helper`,
callback
callback,
);
}

Expand All @@ -236,7 +236,7 @@ class UserConfig {
let ret = callback.call(this, ...args);
if (ret instanceof Promise) {
throw new Error(
`Nunjucks *is* async-friendly with \`addFilter("${name}", async function() {})\` but you need to supply an \`async function\`. You returned a promise from \`addFilter("${name}", function() {})\`. Alternatively, use the \`addAsyncFilter("${name}")\` configuration API method.`
`Nunjucks *is* async-friendly with \`addFilter("${name}", async function() {})\` but you need to supply an \`async function\`. You returned a promise from \`addFilter("${name}", function() {})\`. Alternatively, use the \`addAsyncFilter("${name}")\` configuration API method.`,
);
}
return ret;
Expand Down Expand Up @@ -266,7 +266,7 @@ class UserConfig {

if (typeof tagFn !== "function") {
throw new UserConfigError(
`EleventyConfig.addNunjucksTag expects a callback function to be passed in for ${name}: addNunjucksTag(name, function(nunjucksEngine) {})`
`EleventyConfig.addNunjucksTag expects a callback function to be passed in for ${name}: addNunjucksTag(name, function(nunjucksEngine) {})`,
);
}

Expand All @@ -289,14 +289,14 @@ class UserConfig {
if (this.nunjucksGlobals[name]) {
debug(
chalk.yellow("Warning, overwriting a Nunjucks global with `addNunjucksGlobal(%o)`"),
name
name,
);
}

if (typeof globalType === "function") {
this.nunjucksGlobals[name] = this.benchmarks.config.add(
`"${name}" Nunjucks Global`,
globalType
globalType,
);
} else {
this.nunjucksGlobals[name] = globalType;
Expand Down Expand Up @@ -338,16 +338,18 @@ class UserConfig {

if (this.collections[name]) {
throw new UserConfigError(
`config.addCollection(${name}) already exists. Try a different name for your collection.`
`config.addCollection(${name}) already exists. Try a different name for your collection.`,
);
}

this.collections[name] = callback;
}

/* Async friendly in 3.0 */
addPlugin(plugin, options) {
if (this._pluginExecution) {
this._executePlugin(plugin, options);
// might return a promise
return this._executePlugin(plugin, options);
} else {
this.plugins.push({
plugin,
Expand All @@ -366,42 +368,47 @@ class UserConfig {
}
}

// Starting in 3.0 the plugin callback might be asynchronous!
_executePlugin(plugin, options) {
let name = this._getPluginName(plugin);
let ret;
debug(`Adding ${name || "anonymous"} plugin`);
let pluginBenchmark = this.benchmarks.aggregate.get("Configuration addPlugin");
if (typeof plugin === "function") {
pluginBenchmark.before();
this.benchmarks.config;
let configFunction = plugin;
configFunction(this, options);
ret = configFunction(this, options);
pluginBenchmark.after();
} else if (plugin && plugin.configFunction) {
pluginBenchmark.before();

if (options && typeof options.init === "function") {
// init is not yet async-friendly but it’s also barely used
options.init.call(this, plugin.initArguments || {});
}

plugin.configFunction(this, options);
ret = plugin.configFunction(this, options);
pluginBenchmark.after();
} else {
throw new UserConfigError(
"Invalid EleventyConfig.addPlugin signature. Should be a function or a valid Eleventy plugin object."
"Invalid EleventyConfig.addPlugin signature. Should be a function or a valid Eleventy plugin object.",
);
}
return ret;
}

getNamespacedName(name) {
return this.activeNamespace + name;
}

namespace(pluginNamespace, callback) {
async namespace(pluginNamespace, callback) {
let validNamespace = pluginNamespace && typeof pluginNamespace === "string";
if (validNamespace) {
this.activeNamespace = pluginNamespace || "";
}

callback();
await callback(this);

if (validNamespace) {
this.activeNamespace = "";
Expand Down Expand Up @@ -462,18 +469,18 @@ class UserConfig {
addTemplateFormats(templateFormats) {
this.templateFormatsAdded = this._normalizeTemplateFormats(
templateFormats,
this.templateFormatsAdded
this.templateFormatsAdded,
);
}

setLibrary(engineName, libraryInstance) {
if (engineName === "liquid" && Object.keys(this.liquidOptions).length) {
debug(
"WARNING: using `eleventyConfig.setLibrary` will override any configuration set using `.setLiquidOptions` via the config API. You’ll need to pass these options to the library yourself."
"WARNING: using `eleventyConfig.setLibrary` will override any configuration set using `.setLiquidOptions` via the config API. You’ll need to pass these options to the library yourself.",
);
} else if (engineName === "njk" && Object.keys(this.nunjucksEnvironmentOptions).length) {
debug(
"WARNING: using `eleventyConfig.setLibrary` will override any configuration set using `.setNunjucksEnvironmentOptions` via the config API. You’ll need to pass these options to the library yourself."
"WARNING: using `eleventyConfig.setLibrary` will override any configuration set using `.setNunjucksEnvironmentOptions` via the config API. You’ll need to pass these options to the library yourself.",
);
}

Expand Down Expand Up @@ -546,15 +553,15 @@ class UserConfig {
if (this.nunjucksAsyncShortcodes[name]) {
debug(
chalk.yellow(
"Warning, overwriting a Nunjucks Async Shortcode with `addNunjucksAsyncShortcode(%o)`"
"Warning, overwriting a Nunjucks Async Shortcode with `addNunjucksAsyncShortcode(%o)`",
),
name
name,
);
}

this.nunjucksAsyncShortcodes[name] = this.benchmarks.config.add(
`"${name}" Nunjucks Async Shortcode`,
callback
callback,
);
}

Expand All @@ -567,13 +574,13 @@ class UserConfig {
if (this.nunjucksShortcodes[name]) {
debug(
chalk.yellow("Warning, overwriting a Nunjucks Shortcode with `addNunjucksShortcode(%o)`"),
name
name,
);
}

this.nunjucksShortcodes[name] = this.benchmarks.config.add(
`"${name}" Nunjucks Shortcode`,
callback
callback,
);
}
}
Expand All @@ -584,13 +591,13 @@ class UserConfig {
if (this.liquidShortcodes[name]) {
debug(
chalk.yellow("Warning, overwriting a Liquid Shortcode with `addLiquidShortcode(%o)`"),
name
name,
);
}

this.liquidShortcodes[name] = this.benchmarks.config.add(
`"${name}" Liquid Shortcode`,
callback
callback,
);
}

Expand Down Expand Up @@ -625,15 +632,15 @@ class UserConfig {
if (this.nunjucksAsyncPairedShortcodes[name]) {
debug(
chalk.yellow(
"Warning, overwriting a Nunjucks Async Paired Shortcode with `addPairedNunjucksAsyncShortcode(%o)`"
"Warning, overwriting a Nunjucks Async Paired Shortcode with `addPairedNunjucksAsyncShortcode(%o)`",
),
name
name,
);
}

this.nunjucksAsyncPairedShortcodes[name] = this.benchmarks.config.add(
`"${name}" Nunjucks Async Paired Shortcode`,
callback
callback,
);
}

Expand All @@ -646,15 +653,15 @@ class UserConfig {
if (this.nunjucksPairedShortcodes[name]) {
debug(
chalk.yellow(
"Warning, overwriting a Nunjucks Paired Shortcode with `addPairedNunjucksShortcode(%o)`"
"Warning, overwriting a Nunjucks Paired Shortcode with `addPairedNunjucksShortcode(%o)`",
),
name
name,
);
}

this.nunjucksPairedShortcodes[name] = this.benchmarks.config.add(
`"${name}" Nunjucks Paired Shortcode`,
callback
callback,
);
}
}
Expand All @@ -665,15 +672,15 @@ class UserConfig {
if (this.liquidPairedShortcodes[name]) {
debug(
chalk.yellow(
"Warning, overwriting a Liquid Paired Shortcode with `addPairedLiquidShortcode(%o)`"
"Warning, overwriting a Liquid Paired Shortcode with `addPairedLiquidShortcode(%o)`",
),
name
name,
);
}

this.liquidPairedShortcodes[name] = this.benchmarks.config.add(
`"${name}" Liquid Paired Shortcode`,
callback
callback,
);
}

Expand All @@ -687,15 +694,15 @@ class UserConfig {
if (this.javascriptFunctions[name]) {
debug(
chalk.yellow(
"Warning, overwriting a JavaScript template function with `addJavaScriptFunction(%o)`"
"Warning, overwriting a JavaScript template function with `addJavaScriptFunction(%o)`",
),
name
name,
);
}

this.javascriptFunctions[name] = this.benchmarks.config.add(
`"${name}" JavaScript Function`,
callback
callback,
);
}

Expand Down Expand Up @@ -727,7 +734,7 @@ class UserConfig {
setBrowserSyncConfig() {
this._attemptedBrowserSyncUse = true;
debug(
"The `setBrowserSyncConfig` method was removed in Eleventy 2.0.0. Use `setServerOptions` with the new Eleventy development server or the `@11ty/eleventy-browser-sync` plugin moving forward."
"The `setBrowserSyncConfig` method was removed in Eleventy 2.0.0. Use `setServerOptions` with the new Eleventy development server or the `@11ty/eleventy-browser-sync` plugin moving forward.",
);
}

Expand Down Expand Up @@ -764,8 +771,8 @@ class UserConfig {
key: extension,
extension: extension,
},
options
)
options,
),
);
}
}
Expand All @@ -776,7 +783,7 @@ class UserConfig {
if (typeof parser !== "function") {
if (!("parser" in parser)) {
throw new Error(
"Expected `parser` property in second argument object to `eleventyConfig.addDataExtension`"
"Expected `parser` property in second argument object to `eleventyConfig.addDataExtension`",
);
}

Expand Down
Loading

0 comments on commit 70b2d1d

Please sign in to comment.