diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 68314fb00..c3d019fd7 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -8,7 +8,7 @@ jobs: strategy: matrix: os: ["ubuntu-latest", "macos-latest", "windows-latest"] - node: ["14", "16", "18", "20"] + node: ["18", "20"] name: Node.js ${{ matrix.node }} on ${{ matrix.os }} steps: - uses: actions/checkout@v3 diff --git a/README.md b/README.md index 6c85acd31..16d893bae 100644 --- a/README.md +++ b/README.md @@ -4,7 +4,7 @@ A simpler static site generator. An alternative to Jekyll. Written in JavaScript. Transforms a directory of templates (of varying types) into HTML. -Works with HTML, Markdown, JavaScript, Liquid, Nunjucks, Handlebars, Mustache, EJS, Haml, Pug, with addons for WebC, Sass, Vue, Svelte, JSX, and many others! +Works with HTML, Markdown, JavaScript, Liquid, Nunjucks, with addons for WebC, Sass, Vue, Svelte, JSX, and many others! ## ➡ [Documentation](https://www.11ty.dev/docs/) diff --git a/cmd.cjs b/cmd.cjs new file mode 100755 index 000000000..2de7178e9 --- /dev/null +++ b/cmd.cjs @@ -0,0 +1,143 @@ +#!/usr/bin/env node + +// This file intentionally uses older code conventions to be as friendly +// as possible with error messaging to folks on older runtimes. + +const pkg = require("./package.json"); +require("please-upgrade-node")(pkg, { + message: function (requiredVersion) { + return ( + "Eleventy " + pkg.version + " requires Node " + + requiredVersion + + ". You will need to upgrade Node to use Eleventy!" + ); + }, +}); + +const debug = require("debug")("Eleventy:cmd"); + +(async function() { + const { default: EleventyErrorHandler } = await import("./src/EleventyErrorHandler.js"); + const { default: EleventyBaseError } = await import("./src/EleventyBaseError.js"); + + class EleventyCommandCheckError extends EleventyBaseError {} + + try { + let errorHandler = new EleventyErrorHandler(); + const argv = require("minimist")(process.argv.slice(2), { + string: ["input", "output", "formats", "config", "pathprefix", "port", "to"], + boolean: [ + "quiet", + "version", + "watch", + "dryrun", + "help", + "serve", + "incremental", + "ignore-initial", + ], + default: { + quiet: null, + "ignore-initial": false, + }, + unknown: function (unknownArgument) { + throw new EleventyCommandCheckError( + `We don’t know what '${unknownArgument}' is. Use --help to see the list of supported commands.` + ); + }, + }); + + debug("command: eleventy %o", argv); + const { Eleventy } = await import("./src/Eleventy.js"); + + process.on("unhandledRejection", (error, promise) => { + errorHandler.fatal(error, "Unhandled rejection in promise"); + }); + process.on("uncaughtException", (error) => { + errorHandler.fatal(error, "Uncaught exception"); + }); + process.on("rejectionHandled", (promise) => { + errorHandler.warn(promise, "A promise rejection was handled asynchronously"); + }); + + if (argv.version) { + console.log(Eleventy.getVersion()); + } else if (argv.help) { + console.log(Eleventy.getHelp()); + } else { + let elev = new Eleventy(argv.input, argv.output, { + source: "cli", + // --quiet and --quiet=true both resolve to true + quietMode: argv.quiet, + configPath: argv.config, + pathPrefix: argv.pathprefix, + runMode: argv.serve ? "serve" : argv.watch ? "watch" : "build", + dryRun: argv.dryrun, + }); + + // reuse ErrorHandler instance in Eleventy + errorHandler = elev.errorHandler; + + // careful, we can’t use async/await here to error properly + // with old node versions in `please-upgrade-node` above. + elev + .init() + .then(function () { + if (argv.to === "json" || argv.to === "ndjson") { + // override logging output + elev.setIsVerbose(false); + } + + elev.setIgnoreInitial(argv["ignore-initial"]); + elev.setIncrementalBuild(argv.incremental); + elev.setFormats(argv.formats); + + try { + if (argv.serve) { + let shouldStartServer = true; + elev + .watch() + .catch((e) => { + // Build failed but error message already displayed. + shouldStartServer = false; + // A build error occurred and we aren’t going to --serve + errorHandler.fatal(e, "Eleventy CLI Error"); + }) + .then(function () { + if (shouldStartServer) { + elev.serve(argv.port); + } + }); + } else if (argv.watch) { + elev.watch().catch((e) => { + // A build error occurred and we aren’t going to --watch + errorHandler.fatal(e, "Eleventy CLI Error"); + }); + } else { + if (argv.to === "json") { + elev.toJSON().then(function (result) { + console.log(JSON.stringify(result, null, 2)); + }); + } else if (argv.to === "ndjson") { + elev.toNDJSON().then(function (stream) { + stream.pipe(process.stdout); + }); + } else if (!argv.to || argv.to === "fs") { + elev.write(); + } else { + throw new EleventyCommandCheckError( + `Invalid --to value: ${argv.to}. Supported values: \`fs\` (default), \`json\`, and \`ndjson\`.` + ); + } + } + } catch (e) { + errorHandler.fatal(e, "Eleventy CLI Error"); + } + }) + .catch(errorHandler.fatal.bind(errorHandler)); + } + } catch (e) { + let errorHandler = new EleventyErrorHandler(); + errorHandler.fatal(e, "Eleventy CLI Fatal Error"); + } +})(); diff --git a/cmd.js b/cmd.js deleted file mode 100755 index cd4b7ac1c..000000000 --- a/cmd.js +++ /dev/null @@ -1,132 +0,0 @@ -#!/usr/bin/env node -const pkg = require("./package.json"); -require("please-upgrade-node")(pkg, { - message: function (requiredVersion) { - return ( - "Eleventy requires Node " + - requiredVersion + - ". You will need to upgrade Node to use Eleventy!" - ); - }, -}); -const debug = require("debug")("Eleventy:cmd"); - -const EleventyErrorHandler = require("./src/EleventyErrorHandler"); - -try { - let errorHandler = new EleventyErrorHandler(); - const EleventyCommandCheckError = require("./src/EleventyCommandCheckError"); - const argv = require("minimist")(process.argv.slice(2), { - string: ["input", "output", "formats", "config", "pathprefix", "port", "to"], - boolean: [ - "quiet", - "version", - "watch", - "dryrun", - "help", - "serve", - "incremental", - "ignore-initial", - ], - default: { - quiet: null, - "ignore-initial": false, - }, - unknown: function (unknownArgument) { - throw new EleventyCommandCheckError( - `We don’t know what '${unknownArgument}' is. Use --help to see the list of supported commands.` - ); - }, - }); - - debug("command: eleventy %o", argv); - const Eleventy = require("./src/Eleventy"); - - process.on("unhandledRejection", (error, promise) => { - errorHandler.fatal(error, "Unhandled rejection in promise"); - }); - process.on("uncaughtException", (error) => { - errorHandler.fatal(error, "Uncaught exception"); - }); - process.on("rejectionHandled", (promise) => { - errorHandler.warn(promise, "A promise rejection was handled asynchronously"); - }); - - if (argv.version) { - console.log(Eleventy.getVersion()); - } else if (argv.help) { - console.log(Eleventy.getHelp()); - } else { - let elev = new Eleventy(argv.input, argv.output, { - source: "cli", - // --quiet and --quiet=true both resolve to true - quietMode: argv.quiet, - configPath: argv.config, - pathPrefix: argv.pathprefix, - runMode: argv.serve ? "serve" : argv.watch ? "watch" : "build", - }); - - // reuse ErrorHandler instance in Eleventy - errorHandler = elev.errorHandler; - - if (argv.to === "json" || argv.to === "ndjson") { - // override logging output - elev.setIsVerbose(false); - } - - elev.setDryRun(argv.dryrun); - elev.setIgnoreInitial(argv["ignore-initial"]); - elev.setIncrementalBuild(argv.incremental); - elev.setFormats(argv.formats); - - // careful, we can’t use async/await here to error properly - // with old node versions in `please-upgrade-node` above. - elev - .init() - .then(function () { - try { - if (argv.serve) { - let shouldStartServer = true; - elev - .watch() - .catch((e) => { - // Build failed but error message already displayed. - shouldStartServer = false; - // A build error occurred and we aren’t going to --serve - }) - .then(function () { - if (shouldStartServer) { - elev.serve(argv.port); - } - }); - } else if (argv.watch) { - elev.watch().catch((e) => { - // A build error occurred and we aren’t going to --watch - }); - } else { - if (argv.to === "json") { - elev.toJSON().then(function (result) { - console.log(JSON.stringify(result, null, 2)); - }); - } else if (argv.to === "ndjson") { - elev.toNDJSON().then(function (stream) { - stream.pipe(process.stdout); - }); - } else if (!argv.to || argv.to === "fs") { - elev.write(); - } else { - throw new EleventyCommandCheckError( - `Invalid --to value: ${argv.to}. Supported values: \`fs\` (default), \`json\`, and \`ndjson\`.` - ); - } - } - } catch (e) { - errorHandler.fatal(e, "Eleventy CLI Error"); - } - }) - .catch(errorHandler.fatal.bind(errorHandler)); - } -} catch (e) { - let errorHandler = new EleventyErrorHandler(); - errorHandler.fatal(e, "Eleventy CLI Fatal Error"); -} diff --git a/docs/release-instructions.md b/docs/release-instructions.md index dd364d85d..16c127f86 100644 --- a/docs/release-instructions.md +++ b/docs/release-instructions.md @@ -2,12 +2,6 @@ - `@iarna/toml` has a 3.0 that we have never been on but it was released the same day as the last 2.x https://github.com/BinaryMuse/toml-node/commits/master (needs more investigation) -## List of dependencies that went ESM - -- `@sindresorhus/slugify` ESM at 2.x -- `multimatch` is ESM at 6 -- `bcp-47-normalize` at 1.x - # Release Procedure 1. (Optional) Update minor dependencies in package.json @@ -18,6 +12,7 @@ - 0.12.x+ requires Node 10+ - 1.x+ requires Node 12+ - 2.x+ requires Node 14+ + - 3.x+ requires Node 18+ 1. `rm -rf node_modules && rm -f package-lock.json && npm install` 1. `npm audit` 1. Make sure `npx ava` runs okay diff --git a/package.json b/package.json index a51d88634..d9bfc1c4c 100755 --- a/package.json +++ b/package.json @@ -6,13 +6,14 @@ "access": "public" }, "main": "src/Eleventy.js", + "type": "module", "types": "src/index.d.ts", "bin": { - "eleventy": "./cmd.js" + "eleventy": "./cmd.cjs" }, "license": "MIT", "engines": { - "node": ">=14" + "node": ">=18" }, "funding": { "type": "opencollective", @@ -34,19 +35,14 @@ "html", "markdown", "liquid", - "nunjucks", - "pug", - "handlebars", - "mustache", - "ejs", - "haml" + "nunjucks" ], "scripts": { "default": "npm run test", - "format": "prettier src/ --write", + "format": "prettier . --write", "test": "npx ava --verbose", "lint-staged": "lint-staged", - "coverage": "npx nyc ava && npx nyc report --reporter=json-summary && cp coverage/coverage-summary.json docs-src/_data/coverage.json && node cmd.js --config=docs-src/.eleventy.docs.js", + "coverage": "npx nyc ava && npx nyc report --reporter=json-summary && cp coverage/coverage-summary.json docs-src/_data/coverage.json && node cmd.cjs --config=docs-src/.eleventy.docs.js", "prepare": "husky install" }, "author": { @@ -78,60 +74,54 @@ ] }, "devDependencies": { - "@11ty/eleventy-plugin-syntaxhighlight": "^4.2.0", - "@11ty/eleventy-plugin-vue": "1.0.0-canary.8", - "@vue/server-renderer": "^3.2.47", - "ava": "^5.2.0", + "@11ty/eleventy-plugin-syntaxhighlight": "^5.0.0", + "@iarna/toml": "^2.2.5", + "@vue/server-renderer": "^3.3.4", + "ava": "^5.3.1", "husky": "^8.0.3", "js-yaml": "^4.1.0", - "lint-staged": "^13.2.0", + "lint-staged": "^13.2.3", "markdown-it-emoji": "^2.0.2", - "marked": "^4.3.0", + "marked": "^9.1.2", "nyc": "^15.1.0", - "prettier": "^2.8.7", + "prettier": "^3.0.3", "pretty": "^2.0.0", - "rimraf": "^4.4.1", - "sass": "^1.60.0", - "vue": "^3.2.47" + "rimraf": "^5.0.1", + "sass": "^1.63.6", + "vue": "^3.3.4" }, "dependencies": { - "@11ty/dependency-tree": "^2.0.1", + "@11ty/dependency-tree": "^3.0.0", + "@11ty/dependency-tree-esm": "^1.0.0", "@11ty/eleventy-dev-server": "^1.0.4", "@11ty/eleventy-utils": "^1.0.1", "@11ty/lodash-custom": "^4.17.21", - "@iarna/toml": "^2.2.5", - "@sindresorhus/slugify": "^1.1.2", - "bcp-47-normalize": "^1.1.1", + "@sindresorhus/slugify": "^2.2.1", + "bcp-47-normalize": "^2.3.0", "chokidar": "^3.5.3", "cross-spawn": "^7.0.3", "debug": "^4.3.4", "dependency-graph": "^0.11.0", - "ejs": "^3.1.9", - "fast-glob": "^3.2.12", + "fast-glob": "^3.3.0", "graceful-fs": "^4.2.11", "gray-matter": "^4.0.3", - "hamljs": "^0.6.2", - "handlebars": "^4.7.7", "is-glob": "^4.0.3", "iso-639-1": "^2.1.15", "kleur": "^4.1.5", - "liquidjs": "^10.7.0", + "liquidjs": "^10.8.4", "luxon": "^3.3.0", "markdown-it": "^13.0.1", "micromatch": "^4.0.5", "minimist": "^1.2.8", "moo": "^0.5.2", - "multimatch": "^5.0.0", - "mustache": "^4.2.0", + "multimatch": "^6.0.0", "normalize-path": "^3.0.0", - "nunjucks": "^3.2.3", - "path-to-regexp": "^6.2.1", + "nunjucks": "^3.2.4", "please-upgrade-node": "^3.2.0", "posthtml": "^0.16.6", "posthtml-urls": "^1.0.0", - "pug": "^3.0.2", "recursive-copy": "^2.0.14", - "semver": "^7.3.8", + "semver": "^7.5.4", "slugify": "^1.6.6" } } diff --git a/src/Benchmark.js b/src/Benchmark.js index 622e3ba9e..252d026fb 100644 --- a/src/Benchmark.js +++ b/src/Benchmark.js @@ -1,4 +1,4 @@ -const { performance } = require("perf_hooks"); +import { performance } from "node:perf_hooks"; class Benchmark { constructor() { @@ -49,4 +49,4 @@ class Benchmark { } } -module.exports = Benchmark; +export default Benchmark; diff --git a/src/BenchmarkGroup.js b/src/BenchmarkGroup.js index 94cf39d25..4dc3627a7 100644 --- a/src/BenchmarkGroup.js +++ b/src/BenchmarkGroup.js @@ -1,6 +1,9 @@ -const ConsoleLogger = require("./Util/ConsoleLogger"); -const Benchmark = require("./Benchmark"); -const debugBenchmark = require("debug")("Eleventy:Benchmark"); +import debugUtil from "debug"; + +import ConsoleLogger from "./Util/ConsoleLogger.js"; +import Benchmark from "./Benchmark.js"; + +const debugBenchmark = debugUtil("Eleventy:Benchmark"); class BenchmarkGroup { constructor() { @@ -59,9 +62,7 @@ class BenchmarkGroup { setMinimumThresholdPercent(minimumThresholdPercent) { let val = parseInt(minimumThresholdPercent, 10); if (isNaN(val)) { - throw new Error( - "`setMinimumThresholdPercent` expects a number argument." - ); + throw new Error("`setMinimumThresholdPercent` expects a number argument."); } this.minimumThresholdPercent = val; } @@ -102,8 +103,7 @@ class BenchmarkGroup { let str = `Benchmark ${output.ms}ms ${output.percent}% ${output.calls}× (${label}) ${type}`; if ( - (isAbsoluteMinimumComparison && - totalForBenchmark >= this.minimumThresholdMs) || + (isAbsoluteMinimumComparison && totalForBenchmark >= this.minimumThresholdMs) || percent > this.minimumThresholdPercent ) { this.logger.warn(str); @@ -121,4 +121,4 @@ class BenchmarkGroup { } } -module.exports = BenchmarkGroup; +export default BenchmarkGroup; diff --git a/src/BenchmarkManager.js b/src/BenchmarkManager.js index c656e3c5f..85acd3f2d 100644 --- a/src/BenchmarkManager.js +++ b/src/BenchmarkManager.js @@ -1,5 +1,6 @@ -const BenchmarkGroup = require("./BenchmarkGroup"); -const { performance } = require("perf_hooks"); +import { performance } from "node:perf_hooks"; + +import BenchmarkGroup from "./BenchmarkGroup.js"; // TODO this should not be a singleton, it belongs in the config or somewhere on the Eleventy instance. @@ -69,4 +70,4 @@ class BenchmarkManager { } } -module.exports = BenchmarkManager; +export default BenchmarkManager; diff --git a/src/ComputedData.js b/src/ComputedData.js index 13096876c..c2dfcf450 100644 --- a/src/ComputedData.js +++ b/src/ComputedData.js @@ -1,10 +1,12 @@ -const { set: lodashSet, get: lodashGet } = require("@11ty/lodash-custom"); +import lodash from "@11ty/lodash-custom"; +import debugUtil from "debug"; -const ComputedDataQueue = require("./ComputedDataQueue"); -const ComputedDataTemplateString = require("./ComputedDataTemplateString"); -const ComputedDataProxy = require("./ComputedDataProxy"); +import ComputedDataQueue from "./ComputedDataQueue.js"; +import ComputedDataTemplateString from "./ComputedDataTemplateString.js"; +import ComputedDataProxy from "./ComputedDataProxy.js"; -const debug = require("debug")("Eleventy:ComputedData"); +const { set: lodashSet, get: lodashGet } = lodash; +const debug = debugUtil("Eleventy:ComputedData"); class ComputedData { constructor(config) { @@ -113,4 +115,4 @@ class ComputedData { } } -module.exports = ComputedData; +export default ComputedData; diff --git a/src/ComputedDataProxy.js b/src/ComputedDataProxy.js index 2e41df833..32c6ed7a8 100644 --- a/src/ComputedDataProxy.js +++ b/src/ComputedDataProxy.js @@ -1,5 +1,7 @@ -const { set: lodashSet, get: lodashGet } = require("@11ty/lodash-custom"); -const { isPlainObject } = require("@11ty/eleventy-utils"); +import lodash from "@11ty/lodash-custom"; +import { isPlainObject } from "@11ty/eleventy-utils"; + +const { set: lodashSet, get: lodashGet } = lodash; /* Calculates computed data using Proxies */ class ComputedDataProxy { @@ -126,4 +128,4 @@ class ComputedDataProxy { } } -module.exports = ComputedDataProxy; +export default ComputedDataProxy; diff --git a/src/ComputedDataQueue.js b/src/ComputedDataQueue.js index c61517e0e..40baa6433 100644 --- a/src/ComputedDataQueue.js +++ b/src/ComputedDataQueue.js @@ -1,4 +1,4 @@ -const DependencyGraph = require("dependency-graph").DepGraph; +import { DepGraph as DependencyGraph } from "dependency-graph"; /* Keeps track of the dependency graph between computed data variables * Removes keys from the graph when they are computed. @@ -61,4 +61,4 @@ class ComputedDataQueue { } } -module.exports = ComputedDataQueue; +export default ComputedDataQueue; diff --git a/src/ComputedDataTemplateString.js b/src/ComputedDataTemplateString.js index 73e0005ac..b49d5f8d2 100644 --- a/src/ComputedDataTemplateString.js +++ b/src/ComputedDataTemplateString.js @@ -1,6 +1,8 @@ -const { set: lodashSet } = require("@11ty/lodash-custom"); +import lodash from "@11ty/lodash-custom"; +import debugUtil from "debug"; -const debug = require("debug")("Eleventy:ComputedDataTemplateString"); +const { set: lodashSet } = lodash; +const debug = debugUtil("Eleventy:ComputedDataTemplateString"); /* Calculates computed data in Template Strings. * Ideally we would use the Proxy approach but it doesn’t work @@ -65,4 +67,4 @@ class ComputedDataTemplateString { } } -module.exports = ComputedDataTemplateString; +export default ComputedDataTemplateString; diff --git a/src/Eleventy.js b/src/Eleventy.js index 3e29969c9..682546123 100644 --- a/src/Eleventy.js +++ b/src/Eleventy.js @@ -1,25 +1,31 @@ -const { TemplatePath } = require("@11ty/eleventy-utils"); -const { performance } = require("perf_hooks"); - -const pkg = require("../package.json"); -const TemplateData = require("./TemplateData"); -const TemplateWriter = require("./TemplateWriter"); -const EleventyExtensionMap = require("./EleventyExtensionMap"); -const EleventyErrorHandler = require("./EleventyErrorHandler"); -const EleventyBaseError = require("./EleventyBaseError"); -const EleventyServe = require("./EleventyServe"); -const EleventyWatch = require("./EleventyWatch"); -const EleventyWatchTargets = require("./EleventyWatchTargets"); -const EleventyFiles = require("./EleventyFiles"); -const ConsoleLogger = require("./Util/ConsoleLogger"); -const PathPrefixer = require("./Util/PathPrefixer"); -const TemplateConfig = require("./TemplateConfig"); -const FileSystemSearch = require("./FileSystemSearch"); -const PathNormalizer = require("./Util/PathNormalizer.js"); -const simplePlural = require("./Util/Pluralize"); -const checkPassthroughCopyBehavior = require("./Util/PassthroughCopyBehaviorCheck"); -const debug = require("debug")("Eleventy"); -const eventBus = require("./EventBus"); +import { performance } from "node:perf_hooks"; +import { TemplatePath } from "@11ty/eleventy-utils"; +import debugUtil from "debug"; + +import TemplateData from "./TemplateData.js"; +import TemplateWriter from "./TemplateWriter.js"; +import EleventyExtensionMap from "./EleventyExtensionMap.js"; +import EleventyErrorHandler from "./EleventyErrorHandler.js"; +import EleventyBaseError from "./EleventyBaseError.js"; +import EleventyServe from "./EleventyServe.js"; +import EleventyWatch from "./EleventyWatch.js"; +import EleventyWatchTargets from "./EleventyWatchTargets.js"; +import EleventyFiles from "./EleventyFiles.js"; +import ConsoleLogger from "./Util/ConsoleLogger.js"; +import PathPrefixer from "./Util/PathPrefixer.js"; +import TemplateConfig from "./TemplateConfig.js"; +import FileSystemSearch from "./FileSystemSearch.js"; +import PathNormalizer from "./Util/PathNormalizer.js"; +import simplePlural from "./Util/Pluralize.js"; +import checkPassthroughCopyBehavior from "./Util/PassthroughCopyBehaviorCheck.js"; +import eventBus from "./EventBus.js"; +import { getEleventyPackageJson, getWorkingProjectPackageJson } from "./Util/ImportJsonSync.js"; +import RenderPlugin from "./Plugins/RenderPlugin.js"; +import I18nPlugin from "./Plugins/I18nPlugin.js"; +import HtmlBasePlugin from "./Plugins/HtmlBasePlugin.js"; + +const pkg = getEleventyPackageJson(); +const debug = debugUtil("Eleventy"); /** * @module 11ty/eleventy/Eleventy @@ -34,26 +40,14 @@ const eventBus = require("./EventBus"); */ class Eleventy { constructor(input, output, options = {}, eleventyConfig = null) { - if (!eleventyConfig) { - this.eleventyConfig = new TemplateConfig(null, options.configPath); - } else { - this.eleventyConfig = eleventyConfig; - if (options.configPath) { - this.eleventyConfig.setProjectConfigPath(options.configPath); - } - } - - this.eleventyConfig.setLogger(this.logger); + /** @member {String} - Holds the path to the input directory. */ + this.rawInput = input; - /** - * @member {String} - The top level directory the site pretends to reside in - * @default "/" - */ - this.pathPrefix = options.pathPrefix || "/"; + /** @member {String} - Holds the path to the output directory. */ + this.rawOutput = output; - if (this.pathPrefix || this.pathPrefix === "") { - this.eleventyConfig.setPathPrefix(this.pathPrefix); - } + /** @member {TemplateConfig} - Override the config instance (for centralized config re-use) */ + this.eleventyConfig = eleventyConfig; /** * @member {Object} - Options object passed to the Eleventy constructor @@ -61,48 +55,104 @@ class Eleventy { */ this.options = options; - /* Programmatic API config */ - if (options.config && typeof options.config === "function") { - // TODO use return object here? - options.config(this.eleventyConfig.userConfig); - } + /** + * @member {String} - The top level directory the site pretends to reside in + * @default "/" + */ + this.pathPrefix = this.options.pathPrefix || "/"; /** * @member {String} - The path to Eleventy's config file. * @default null */ - this.configPath = options.configPath; + this.configPath = this.options.configPath; /** * @member {String} - Called via CLI (`cli`) or Programmatically (`script`) * @default "script" */ - this.source = options.source || "script"; + this.source = this.options.source || "script"; /** - * @member {Boolean} - Running in serverless mode + * @member {String} - One of build, serve, or watch + * @default "build" + */ + this.runMode = this.options.runMode || "build"; + + /** + * @member {Boolean} - Is Eleventy running in dry mode? * @default false */ - if ("isServerless" in options) { - this.isServerless = !!options.isServerless; - } else { - this.isServerless = !!process.env.AWS_LAMBDA_FUNCTION_NAME; - } + this.isDryRun = options.dryRun ?? false; /** - * @member {String} - One of build, serve, or watch - * @default "build" + * @member {Boolean} - Does the init() method still need to be run (or hasn’t finished yet) + * @default true + */ + this.needsInit = true; + + /** + * @member {Array} - Subset of template types. + * @default null + */ + this.formatsOverride = null; + + /** + * @member {Boolean} - Is this an incremental build? (only operates on a subset of input files) + * @default null */ - this.runMode = options.runMode || "build"; + this.isIncremental = false; + + /** + * @member {String} - If an incremental build, this is the file we’re operating on. + * @default null + */ + this.programmaticApiIncrementalFile = undefined; + + /** + * @member {Boolean} - Should we process files on first run? (The --ignore-initial feature) + * @default null + */ + this.isRunInitialBuild = true; + + /** + * @member {Boolean} - Has the async initialization for config run yet? + * @default null + */ + this._hasConfigInitialized = false; + } + + async initializeConfig() { + if (!this.eleventyConfig) { + this.eleventyConfig = new TemplateConfig(null, this.options.configPath); + } else if (this.options.configPath) { + await this.eleventyConfig.setProjectConfigPath(this.options.configPath); + } + + this.eleventyConfig.setProjectUsingEsm(this.isEsm); + this.eleventyConfig.setLogger(this.logger); + + if (this.pathPrefix || this.pathPrefix === "") { + this.eleventyConfig.setPathPrefix(this.pathPrefix); + } + + /* Programmatic API config */ + if (this.options.config && typeof this.options.config === "function") { + // TODO use return object here? + await this.options.config(this.eleventyConfig.userConfig); + } /** * @member {Object} - Initialize Eleventy environment variables * @default null */ - // both this.isServerless and this.runMode need to be set before this + // this.runMode need to be set before this this.env = this.getEnvironmentVariableValues(); this.initializeEnvironmentVariables(this.env); + // Async initialization of configuration + await this.eleventyConfig.init(); + /** * @member {Object} - Initialize Eleventy’s configuration, including the user config file */ @@ -123,59 +173,33 @@ class Eleventy { * @member {Boolean} - Is Eleventy running in verbose mode? * @default true */ - if (options.quietMode === true || options.quietMode === false) { + if (this.options.quietMode === true || this.options.quietMode === false) { // Set via --quiet - this.setIsVerbose(!options.quietMode); + this.setIsVerbose(!this.options.quietMode); this.verboseModeSetViaCommandLineParam = true; } else { // Fall back to configuration this.setIsVerbose(!this.config.quietMode); } - /** - * @member {Boolean} - Is Eleventy running in dry mode? - * @default false - */ - this.isDryRun = false; - - /** - * @member {Boolean} - Does the init() method still need to be run (or hasn’t finished yet) - * @default true - */ - this.needsInit = true; - /** * @member {Boolean} - Explicit input directory (usually used when input is a single file/serverless) */ - if (options.inputDir) { - this.setInputDir(options.inputDir); + if (this.options.inputDir) { + this.setInputDir(this.options.inputDir); } if (performance) { - // TODO this doesn’t reset in serverless mode correctly (cumulative from start of --serve/watch) debug("Eleventy warm up time (in ms) %o", performance.now()); } /** @member {Number} - The timestamp of Eleventy start. */ this.start = this.getNewTimestamp(); - /** - * @member {Array} - Subset of template types. - * @default null - */ - this.formatsOverride = null; - /** @member {Object} - tbd. */ this.eleventyServe = new EleventyServe(); - this.eleventyServe.config = this.config; this.eleventyServe.eleventyConfig = this.eleventyConfig; - /** @member {String} - Holds the path to the input directory. */ - this.rawInput = input; - - /** @member {String} - Holds the path to the output directory. */ - this.rawOutput = output; - /** @member {Object} - tbd. */ this.watchManager = new EleventyWatch(); @@ -187,9 +211,11 @@ class Eleventy { /** @member {Object} - tbd. */ this.fileSystemSearch = new FileSystemSearch(); - this.isIncremental = false; - this.programmaticApiIncrementalFile = undefined; - this.isRunInitialBuild = true; + this._hasConfigInitialized = true; + + if (this._preInitVerbose !== undefined) { + this.setIsVerbose(this._preInitVerbose); + } } getNewTimestamp() { @@ -264,7 +290,8 @@ class Eleventy { setPathPrefix(pathPrefix) { if (pathPrefix || pathPrefix === "") { this.eleventyConfig.setPathPrefix(pathPrefix); - this.config = this.eleventyConfig.getConfig(); + // TODO reset config + // this.config = this.eleventyConfig.getConfig(); } } @@ -376,6 +403,10 @@ class Eleventy { async init(options = {}) { options = Object.assign({ viaConfigReset: false }, options); + if (!this._hasConfigInitialized) { + await this.initializeConfig(); + } + await this.config.events.emit("eleventy.config", this.eleventyConfig); if (this.env) { @@ -395,6 +426,7 @@ class Eleventy { // this.eleventyServe.setWatcherOptions(this.getChokidarConfig()); this.templateData = new TemplateData(this.inputDir, this.eleventyConfig); + this.templateData.setProjectUsingEsm(this.isEsm); this.templateData.extensionMap = this.extensionMap; if (this.env) { this.templateData.environmentVariables = this.env; @@ -487,7 +519,7 @@ Verbose Output: ${this.verboseMode}`); } values.source = this.source; - values.isServerless = this.isServerless; + values.isServerless = false; // backwards compatibility return values; } @@ -503,15 +535,6 @@ Verbose Output: ${this.verboseMode}`); process.env.ELEVENTY_SOURCE = env.source; process.env.ELEVENTY_RUN_MODE = env.runMode; - - // https://github.com/11ty/eleventy/issues/1957 - // Note: when using --serve, ELEVENTY_SERVERLESS is also set in Serverless.js - - // Careful here, setting to false will cast to string "false" which is truthy. - if (env.isServerless) { - process.env.ELEVENTY_SERVERLESS = true; - debug("Setting process.env.ELEVENTY_SERVERLESS: %o", true); - } } /* Setter for verbose mode */ @@ -576,6 +599,11 @@ Verbose Output: ${this.verboseMode}`); * @param {Boolean} isVerbose - Shall Eleventy run in verbose mode? */ setIsVerbose(isVerbose) { + if (!this._hasConfigInitialized) { + this._preInitVerbose = isVerbose; + return; + } + // Debug mode should always run quiet (all output goes to debug logger) if (process.env.DEBUG) { isVerbose = false; @@ -588,7 +616,7 @@ Verbose Output: ${this.verboseMode}`); this.verboseMode = isVerbose; // Set verbose mode in config file - this.eleventyConfig.verbose = this.verboseMode; + this.eleventyConfig.verbose = isVerbose; } /** @@ -622,7 +650,7 @@ Verbose Output: ${this.verboseMode}`); */ setIncrementalFile(incrementalFile) { if (incrementalFile) { - // This is used for collections-friendly serverless mode. + // This is also used for collections-friendly serverless mode. this.setIgnoreInitial(true); this.setIncrementalBuild(true); @@ -714,11 +742,11 @@ Arguments: * * @method */ - resetConfig() { + async resetConfig() { this.env = this.getEnvironmentVariableValues(); this.initializeEnvironmentVariables(this.env); - this.eleventyConfig.reset(); + await this.eleventyConfig.reset(); this.config = this.eleventyConfig.getConfig(); this.eleventyServe.config = this.config; @@ -806,15 +834,16 @@ Arguments: this.watchManager.setBuildRunning(); let queue = this.watchManager.getActiveQueue(); + await this.config.events.emit("beforeWatch", queue); await this.config.events.emit("eleventy.beforeWatch", queue); - // Clear `require` cache for all files that triggered the rebuild - this.watchTargets.clearRequireCacheFor(queue); + // Clear `import` cache for all files that triggered the rebuild (sync event) + this.watchTargets.clearImportCacheFor(queue); // reset and reload global configuration if (isResetConfig) { - this.resetConfig(); + await this.resetConfig(); } await this.restart(); @@ -925,6 +954,21 @@ Arguments: benchmark.after(); } + get isEsm() { + if (this._isEsm === undefined) { + try { + // fetch from project’s package.json + let projectPackageJson = getWorkingProjectPackageJson(); + this._isEsm = projectPackageJson?.type === "module"; + } catch (e) { + debug("Could not find a project package.json for project’s ES Modules check: %O", e); + this._isEsm = false; + } + } + + return this._isEsm; + } + /** * Starts watching dependencies. * @@ -942,21 +986,24 @@ Arguments: return !dataDir || !TemplatePath.stripLeadingDotSlash(path).startsWith(dataDir); } + // Lazy resolve isEsm only for --watch + this.watchTargets.setProjectUsingEsm(this.isEsm); + // Template files .11ty.js - let templateFiles = this.eleventyFiles.getWatchPathCache(); - this.watchTargets.addDependencies(templateFiles); + let templateFiles = await this.eleventyFiles.getWatchPathCache(); + await this.watchTargets.addDependencies(templateFiles); // Config file dependencies - this.watchTargets.addDependencies( + await this.watchTargets.addDependencies( this.eleventyConfig.getLocalProjectConfigFiles(), filterOutGlobalDataFiles ); // Deps from Global Data (that aren’t in the global data directory, everything is watched there) let globalDataDeps = this.templateData.getWatchPathCache(); - this.watchTargets.addDependencies(globalDataDeps, filterOutGlobalDataFiles); + await this.watchTargets.addDependencies(globalDataDeps, filterOutGlobalDataFiles); - this.watchTargets.addDependencies( + await this.watchTargets.addDependencies( await this.eleventyFiles.getWatcherTemplateJavaScriptDataFiles() ); } @@ -1010,7 +1057,8 @@ Arguments: // eslint-disable-next-line no-useless-catch try { let moduleName = "chokidar"; - chokidar = require(moduleName); + let chokidarImport = await import(moduleName); + chokidar = chokidarImport.default; } catch (e) { throw e; } @@ -1048,6 +1096,7 @@ Arguments: try { let isResetConfig = this._shouldResetConfig([path]); this._addFileToWatchQueue(path, isResetConfig); + clearTimeout(watchDelay); await new Promise((resolve, reject) => { @@ -1112,7 +1161,7 @@ Arguments: * @returns {Promise<{}>} */ async write() { - return this.executeBuild(); + return this.executeBuild("fs"); } /** @@ -1242,10 +1291,11 @@ Arguments: } } -module.exports = Eleventy; -module.exports.EleventyServerless = require("./Serverless"); -module.exports.EleventyServerlessBundlerPlugin = require("./Plugins/ServerlessBundlerPlugin"); -module.exports.EleventyRenderPlugin = require("./Plugins/RenderPlugin"); -module.exports.EleventyEdgePlugin = require("./Plugins/EdgePlugin"); -module.exports.EleventyI18nPlugin = require("./Plugins/I18nPlugin"); -module.exports.EleventyHtmlBasePlugin = require("./Plugins/HtmlBasePlugin"); +export default Eleventy; + +export { + Eleventy, + RenderPlugin as EleventyRenderPlugin, + I18nPlugin as EleventyI18nPlugin, + HtmlBasePlugin as EleventyHtmlBasePlugin, +}; diff --git a/src/EleventyBaseError.js b/src/EleventyBaseError.js index 55682e4c2..f82ba3cb6 100644 --- a/src/EleventyBaseError.js +++ b/src/EleventyBaseError.js @@ -20,4 +20,4 @@ class EleventyBaseError extends Error { } } } -module.exports = EleventyBaseError; +export default EleventyBaseError; diff --git a/src/EleventyCommandCheckError.js b/src/EleventyCommandCheckError.js deleted file mode 100644 index b36fe94f0..000000000 --- a/src/EleventyCommandCheckError.js +++ /dev/null @@ -1,3 +0,0 @@ -const EleventyBaseError = require("./EleventyBaseError"); -class EleventyCommandCheckError extends EleventyBaseError {} -module.exports = EleventyCommandCheckError; diff --git a/src/EleventyErrorHandler.js b/src/EleventyErrorHandler.js index e041ed398..9e404b49e 100644 --- a/src/EleventyErrorHandler.js +++ b/src/EleventyErrorHandler.js @@ -1,6 +1,9 @@ -const ConsoleLogger = require("./Util/ConsoleLogger"); -const EleventyErrorUtil = require("./EleventyErrorUtil"); -const debug = require("debug")("Eleventy:EleventyErrorHandler"); +import debugUtil from "debug"; + +import ConsoleLogger from "./Util/ConsoleLogger.js"; +import EleventyErrorUtil from "./EleventyErrorUtil.js"; + +const debug = debugUtil("Eleventy:EleventyErrorHandler"); class EleventyErrorHandler { constructor() { @@ -111,4 +114,4 @@ class EleventyErrorHandler { } } -module.exports = EleventyErrorHandler; +export default EleventyErrorHandler; diff --git a/src/EleventyErrorUtil.js b/src/EleventyErrorUtil.js index 56a977697..3415ea47d 100644 --- a/src/EleventyErrorUtil.js +++ b/src/EleventyErrorUtil.js @@ -1,4 +1,4 @@ -const TemplateContentPrematureUseError = require("./Errors/TemplateContentPrematureUseError"); +import TemplateContentPrematureUseError from "./Errors/TemplateContentPrematureUseError.js"; /* Hack to workaround the variety of error handling schemes in template languages */ class EleventyErrorUtil { @@ -14,10 +14,7 @@ class EleventyErrorUtil { return false; } - return ( - msg.indexOf(EleventyErrorUtil.prefix) > -1 && - msg.indexOf(EleventyErrorUtil.suffix) > -1 - ); + return msg.indexOf(EleventyErrorUtil.prefix) > -1 && msg.indexOf(EleventyErrorUtil.suffix) > -1; } static cleanMessage(msg) { @@ -30,9 +27,7 @@ class EleventyErrorUtil { return msg.slice( 0, - msg.indexOf(EleventyErrorUtil.prefix) < 0 - ? 0 - : msg.indexOf(EleventyErrorUtil.prefix) + msg.indexOf(EleventyErrorUtil.prefix) < 0 ? 0 : msg.indexOf(EleventyErrorUtil.prefix) ); } @@ -70,11 +65,10 @@ class EleventyErrorUtil { (e.originalError && (e.originalError.name === "RenderError" || e.originalError.name === "UndefinedVariableError") && - e.originalError.originalError instanceof - TemplateContentPrematureUseError) || // Liquid + e.originalError.originalError instanceof TemplateContentPrematureUseError) || // Liquid (e.message || "").indexOf("TemplateContentPrematureUseError") > -1 ); // Nunjucks } } -module.exports = EleventyErrorUtil; +export default EleventyErrorUtil; diff --git a/src/EleventyExtensionMap.js b/src/EleventyExtensionMap.js index b9eec3d93..2fc1c6182 100644 --- a/src/EleventyExtensionMap.js +++ b/src/EleventyExtensionMap.js @@ -1,7 +1,7 @@ -const { TemplatePath } = require("@11ty/eleventy-utils"); +import { TemplatePath } from "@11ty/eleventy-utils"; -const TemplateEngineManager = require("./TemplateEngineManager"); -const EleventyBaseError = require("./EleventyBaseError"); +import TemplateEngineManager from "./TemplateEngineManager.js"; +import EleventyBaseError from "./EleventyBaseError.js"; class EleventyExtensionMapConfigError extends EleventyBaseError {} @@ -112,14 +112,14 @@ class EleventyExtensionMap { return sorted; } - shouldSpiderJavaScriptDependencies(path) { + async shouldSpiderJavaScriptDependencies(path) { let extensions = this.getValidExtensionsForPath(path); for (let extension of extensions) { if (extension in this._spiderJsDepsCache) { return this._spiderJsDepsCache[extension]; } - let cls = this.engineManager.getEngineClassByExtension(extension); + let cls = await this.engineManager.getEngineClassByExtension(extension); if (cls) { let entry = this.getCustomExtensionEntry(extension); let shouldSpider = cls.shouldSpiderJavaScriptDependencies(entry); @@ -232,17 +232,13 @@ class EleventyExtensionMap { get extensionToKeyMap() { if (!this._extensionToKeyMap) { this._extensionToKeyMap = { - ejs: "ejs", md: "md", html: "html", - hbs: "hbs", - mustache: "mustache", - haml: "haml", - pug: "pug", njk: "njk", liquid: "liquid", "11ty.js": "11ty.js", "11ty.cjs": "11ty.js", + "11ty.mjs": "11ty.js", }; if ("extensionMap" in this.config) { @@ -260,4 +256,4 @@ class EleventyExtensionMap { } } -module.exports = EleventyExtensionMap; +export default EleventyExtensionMap; diff --git a/src/EleventyFiles.js b/src/EleventyFiles.js index 380bdf8dc..3849a1fce 100644 --- a/src/EleventyFiles.js +++ b/src/EleventyFiles.js @@ -1,18 +1,18 @@ -const fs = require("fs"); +import fs from "node:fs"; -const { TemplatePath } = require("@11ty/eleventy-utils"); +import { TemplatePath } from "@11ty/eleventy-utils"; +import debugUtil from "debug"; -const EleventyExtensionMap = require("./EleventyExtensionMap"); -const TemplateData = require("./TemplateData"); -const TemplateGlob = require("./TemplateGlob"); -const TemplatePassthroughManager = require("./TemplatePassthroughManager"); -const EleventyBaseError = require("./EleventyBaseError"); -const checkPassthroughCopyBehavior = require("./Util/PassthroughCopyBehaviorCheck"); +import EleventyExtensionMap from "./EleventyExtensionMap.js"; +import TemplateData from "./TemplateData.js"; +import TemplateGlob from "./TemplateGlob.js"; +import TemplatePassthroughManager from "./TemplatePassthroughManager.js"; +import EleventyBaseError from "./EleventyBaseError.js"; +import checkPassthroughCopyBehavior from "./Util/PassthroughCopyBehaviorCheck.js"; -class EleventyFilesError extends EleventyBaseError {} +const debug = debugUtil("Eleventy:EleventyFiles"); -const debug = require("debug")("Eleventy:EleventyFiles"); -// const debugDev = require("debug")("Dev:Eleventy:EleventyFiles"); +class EleventyFilesError extends EleventyBaseError {} class EleventyFiles { constructor(input, outputDir, formats, eleventyConfig) { @@ -330,17 +330,17 @@ class EleventyFiles { return this.templateGlobs; } - getWatchPathCache() { + async getWatchPathCache() { // Issue #1325: make sure passthrough copy files are not included here if (!this.pathCache) { throw new Error("Watching requires `.getFiles()` to be called first in EleventyFiles"); } // Filter out the passthrough copy paths. - return this.pathCache.filter((path) => { + return this.pathCache.filter(async (path) => { return ( this.extensionMap.isFullTemplateFilePath(path) && - this.extensionMap.shouldSpiderJavaScriptDependencies(path) + (await this.extensionMap.shouldSpiderJavaScriptDependencies(path)) ); }); } @@ -460,4 +460,4 @@ class EleventyFiles { } } -module.exports = EleventyFiles; +export default EleventyFiles; diff --git a/src/EleventyServe.js b/src/EleventyServe.js index 27fdc285b..4a4606e4d 100644 --- a/src/EleventyServe.js +++ b/src/EleventyServe.js @@ -1,12 +1,16 @@ -const { TemplatePath } = require("@11ty/eleventy-utils"); +import { TemplatePath } from "@11ty/eleventy-utils"; +import EleventyDevServer from "@11ty/eleventy-dev-server"; +import debugUtil from "debug"; -const EleventyBaseError = require("./EleventyBaseError"); -const ConsoleLogger = require("./Util/ConsoleLogger"); -const PathPrefixer = require("./Util/PathPrefixer"); -const merge = require("./Util/Merge"); -const checkPassthroughCopyBehavior = require("./Util/PassthroughCopyBehaviorCheck"); +import EleventyBaseError from "./EleventyBaseError.js"; +import ConsoleLogger from "./Util/ConsoleLogger.js"; +import PathPrefixer from "./Util/PathPrefixer.js"; +import merge from "./Util/Merge.js"; +import checkPassthroughCopyBehavior from "./Util/PassthroughCopyBehaviorCheck.js"; +import { getModulePackageJson } from "./Util/ImportJsonSync.js"; +import { EleventyImport } from "./Util/Require.js"; -const debug = require("debug")("Eleventy:EleventyServe"); +const debug = debugUtil("Eleventy:EleventyServe"); class EleventyServeConfigError extends EleventyBaseError {} @@ -27,16 +31,17 @@ class EleventyServe { } get config() { - if (!this._config) { - throw new EleventyServeConfigError("You need to set the config property on EleventyServe."); + if (!this.eleventyConfig) { + throw new EleventyServeConfigError( + "You need to set the eleventyConfig property on EleventyServe." + ); } - return this._config; + return this.eleventyConfig.getConfig(); } set config(config) { - this._options = null; - this._config = config; + throw new Error("It’s not allowed to set config on EleventyServe. Set eleventyConfig instead."); } setAliases(aliases) { @@ -67,16 +72,16 @@ class EleventyServe { } } - async setOutputDir(outputDir) { + setOutputDir(outputDir) { // TODO check if this is different and if so, restart server (if already running) // This applies if you change the output directory in your config file during watch/serve this.outputDir = outputDir; } - getServerModule(name) { + async getServerModule(name) { try { if (!name || name === DEFAULT_SERVER_OPTIONS.module) { - return require(DEFAULT_SERVER_OPTIONS.module); + return EleventyDevServer; } // Look for peer dep in local project @@ -88,7 +93,7 @@ class EleventyServe { throw new Error("Invalid node_modules name for Eleventy server instance, received:" + name); } - let module = require(serverPath); + let module = await EleventyImport(serverPath); if (!("getServer" in module)) { throw new Error( @@ -96,10 +101,8 @@ class EleventyServe { ); } - let serverPackageJsonPath = TemplatePath.absolutePath(serverPath, "package.json"); - - let serverPackageJson = require(serverPackageJsonPath); - if (serverPackageJson["11ty"] && serverPackageJson["11ty"].compatibility) { + let serverPackageJson = getModulePackageJson(serverPath); + if (serverPackageJson["11ty"]?.compatibility) { try { this.eleventyConfig.userConfig.versionCheck(serverPackageJson["11ty"].compatibility); } catch (e) { @@ -114,7 +117,7 @@ class EleventyServe { e.message ); debug("Eleventy server error %o", e); - return require(DEFAULT_SERVER_OPTIONS.module); + return EleventyDevServer; } } @@ -145,22 +148,24 @@ class EleventyServe { } get server() { + if (!this._server) { + throw new Error("Missing server instance. Did you call .initServerInstance?"); + } + + return this._server; + } + + async initServerInstance() { if (this._server) { - return this._server; + return; } - let serverModule = this.getServerModule(this.options.module); + let serverModule = await this.getServerModule(this.options.module); // Static method `getServer` was already checked in `getServerModule` this._server = serverModule.getServer("eleventy-server", this.outputDir, this.options); this.setAliases(this._aliases); - - return this._server; - } - - set server(val) { - this._server = val; } getSetupCallback() { @@ -195,15 +200,16 @@ class EleventyServe { this._commandLinePort = port; await this.init(); + await this.initServerInstance(); this.server.serve(port || this.options.port); } async close() { if (this._server) { - await this.server.close(); + await this._server.close(); - this.server = undefined; + this._server = undefined; } } @@ -256,4 +262,4 @@ class EleventyServe { } } -module.exports = EleventyServe; +export default EleventyServe; diff --git a/src/EleventyShortcodeError.js b/src/EleventyShortcodeError.js index 126635339..8e6a6d83e 100644 --- a/src/EleventyShortcodeError.js +++ b/src/EleventyShortcodeError.js @@ -1,5 +1,5 @@ -const EleventyBaseError = require("./EleventyBaseError"); +import EleventyBaseError from "./EleventyBaseError.js"; class EleventyShortcodeError extends EleventyBaseError {} -module.exports = EleventyShortcodeError; +export default EleventyShortcodeError; diff --git a/src/EleventyWatch.js b/src/EleventyWatch.js index 250b99bb9..8ce8657b7 100755 --- a/src/EleventyWatch.js +++ b/src/EleventyWatch.js @@ -1,5 +1,6 @@ -const { TemplatePath } = require("@11ty/eleventy-utils"); -const PathNormalizer = require("./Util/PathNormalizer.js"); +import { TemplatePath } from "@11ty/eleventy-utils"; + +import PathNormalizer from "./Util/PathNormalizer.js"; /* Decides when to watch and in what mode to watch * Incremental builds don’t batch changes, they queue. @@ -125,4 +126,4 @@ class EleventyWatch { } } -module.exports = EleventyWatch; +export default EleventyWatch; diff --git a/src/EleventyWatchTargets.js b/src/EleventyWatchTargets.js index d01f645f7..92530c49b 100644 --- a/src/EleventyWatchTargets.js +++ b/src/EleventyWatchTargets.js @@ -1,8 +1,8 @@ -const { TemplatePath } = require("@11ty/eleventy-utils"); -const { DepGraph } = require("dependency-graph"); +import { TemplatePath } from "@11ty/eleventy-utils"; +import { DepGraph } from "dependency-graph"; -const deleteRequireCache = require("./Util/DeleteRequireCache"); -const JavaScriptDependencies = require("./Util/JavaScriptDependencies"); +import JavaScriptDependencies from "./Util/JavaScriptDependencies.js"; +import eventBus from "./EventBus.js"; class EleventyWatchTargets { constructor() { @@ -10,6 +10,7 @@ class EleventyWatchTargets { this.dependencies = new Set(); this.newTargets = new Set(); this._watchJavaScriptDependencies = true; + this.isEsm = false; this.graph = new DepGraph(); } @@ -22,6 +23,10 @@ class EleventyWatchTargets { return this._watchJavaScriptDependencies; } + setProjectUsingEsm(isEsmProject) { + this.isEsm = !!isEsmProject; + } + isJavaScriptDependency(path) { return this.dependencies.has(path); } @@ -105,13 +110,13 @@ class EleventyWatchTargets { } // add only a target’s dependencies - addDependencies(targets, filterCallback) { + async addDependencies(targets, filterCallback) { if (!this.watchJavaScriptDependencies) { return; } targets = EleventyWatchTargets.normalize(targets); - let deps = JavaScriptDependencies.getDependencies(targets); + let deps = await JavaScriptDependencies.getDependencies(targets, this.isEsm); if (filterCallback) { deps = deps.filter(filterCallback); } @@ -126,21 +131,24 @@ class EleventyWatchTargets { this.writer = templateWriter; } - clearRequireCacheFor(filePathArray) { + clearImportCacheFor(filePathArray) { + let paths = new Set(); for (const filePath of filePathArray) { - deleteRequireCache(filePath); + paths.add(filePath); // Delete from require cache so that updates to the module are re-required let importsTheChangedFile = this.getDependantsOf(filePath); for (let dep of importsTheChangedFile) { - deleteRequireCache(dep); + paths.add(dep); } let isImportedInTheChangedFile = this.getDependenciesOf(filePath); for (let dep of isImportedInTheChangedFile) { - deleteRequireCache(dep); + paths.add(dep); } } + + eventBus.emit("eleventy.importCacheReset", paths); } getNewTargetsSinceLastReset() { @@ -152,4 +160,4 @@ class EleventyWatchTargets { } } -module.exports = EleventyWatchTargets; +export default EleventyWatchTargets; diff --git a/src/Engines/Custom.js b/src/Engines/Custom.js index 1935e3012..0e7242853 100644 --- a/src/Engines/Custom.js +++ b/src/Engines/Custom.js @@ -1,6 +1,6 @@ -const TemplateEngine = require("./TemplateEngine"); -const getJavaScriptData = require("../Util/GetJavaScriptData"); -const eventBus = require("../EventBus.js"); +import TemplateEngine from "./TemplateEngine.js"; +import getJavaScriptData from "../Util/GetJavaScriptData.js"; +import eventBus from "../EventBus.js"; let lastModifiedFile = undefined; eventBus.on("eleventy.resourceModified", (path) => { @@ -12,8 +12,7 @@ class CustomEngine extends TemplateEngine { super(name, dirs, config); this.entry = this.getExtensionMapEntry(); - this.needsInit = - "init" in this.entry && typeof this.entry.init === "function"; + this.needsInit = "init" in this.entry && typeof this.entry.init === "function"; this._defaultEngine = undefined; @@ -55,10 +54,7 @@ class CustomEngine extends TemplateEngine { // Handle aliases to `11ty.js` templates, avoid reading files in the alias, see #2279 // Here, we are short circuiting fallback to defaultRenderer, does not account for compile // functions that call defaultRenderer explicitly - if ( - this._defaultEngine && - "needsToReadFileContents" in this._defaultEngine - ) { + if (this._defaultEngine && "needsToReadFileContents" in this._defaultEngine) { return this._defaultEngine.needsToReadFileContents(); } @@ -69,9 +65,7 @@ class CustomEngine extends TemplateEngine { async _runningInit() { if (this.needsInit) { if (!this._initing) { - this._initBench = this.benchmarks.aggregate.get( - `Engine (${this.name}) Init` - ); + this._initBench = this.benchmarks.aggregate.get(`Engine (${this.name}) Init`); this._initBench.before(); this._initing = this.entry.init.bind({ config: this.config, @@ -95,10 +89,7 @@ class CustomEngine extends TemplateEngine { if (!("getData" in this.entry)) { // Handle aliases to `11ty.js` templates, use upstream default engine data fetch, see #2279 - if ( - this._defaultEngine && - "getExtraDataFromFile" in this._defaultEngine - ) { + if (this._defaultEngine && "getExtraDataFromFile" in this._defaultEngine) { return this._defaultEngine.getExtraDataFromFile(inputPath); } @@ -135,9 +126,7 @@ class CustomEngine extends TemplateEngine { } } - let dataBench = this.benchmarks.aggregate.get( - `Engine (${this.name}) Get Data From File` - ); + let dataBench = this.benchmarks.aggregate.get(`Engine (${this.name}) Get Data From File`); dataBench.before(); let inst = await this.entry.getInstanceFromInputPath(inputPath); @@ -177,11 +166,7 @@ class CustomEngine extends TemplateEngine { let defaultRenderer; if (this._defaultEngine) { defaultRenderer = async (data) => { - const render = await this._defaultEngine.compile( - str, - inputPath, - ...args - ); + const render = await this._defaultEngine.compile(str, inputPath, ...args); return render(data); }; } @@ -231,11 +216,7 @@ class CustomEngine extends TemplateEngine { } isFileRelevantTo(inputPath, comparisonFile, includeLayouts) { - return this.config.uses.isFileRelevantTo( - inputPath, - comparisonFile, - includeLayouts - ); + return this.config.uses.isFileRelevantTo(inputPath, comparisonFile, includeLayouts); } getCompileCacheKey(str, inputPath) { @@ -243,10 +224,7 @@ class CustomEngine extends TemplateEngine { // but still return a key to cache this new render for next time let useCache = !this.isFileRelevantTo(inputPath, lastModifiedFile, false); - if ( - this.entry.compileOptions && - "getCacheKey" in this.entry.compileOptions - ) { + if (this.entry.compileOptions && "getCacheKey" in this.entry.compileOptions) { if (typeof this.entry.compileOptions.getCacheKey !== "function") { throw new Error( `\`compileOptions.getCacheKey\` must be a function in addExtension for the ${this.name} type` @@ -285,10 +263,7 @@ class CustomEngine extends TemplateEngine { } static shouldSpiderJavaScriptDependencies(entry) { - if ( - entry.compileOptions && - "spiderJavaScriptDependencies" in entry.compileOptions - ) { + if (entry.compileOptions && "spiderJavaScriptDependencies" in entry.compileOptions) { return entry.compileOptions.spiderJavaScriptDependencies; } @@ -296,4 +271,4 @@ class CustomEngine extends TemplateEngine { } } -module.exports = CustomEngine; +export default CustomEngine; diff --git a/src/Engines/Ejs.js b/src/Engines/Ejs.js deleted file mode 100644 index d8cc187c4..000000000 --- a/src/Engines/Ejs.js +++ /dev/null @@ -1,55 +0,0 @@ -const ejsLib = require("ejs"); -const TemplateEngine = require("./TemplateEngine"); - -class Ejs extends TemplateEngine { - constructor(name, dirs, config) { - super(name, dirs, config); - - this.ejsOptions = {}; - - this.setLibrary(this.config.libraryOverrides.ejs); - this.setEjsOptions(this.config.ejsOptions); - } - - setLibrary(lib) { - this.ejsLib = lib || ejsLib; - this.setEngineLib(this.ejsLib); - } - - getEngine() { - return this.ejsLib; - } - - setEjsOptions(options) { - this.ejsOptions = options; - } - - getEjsOptions() { - let includesDir = super.getIncludesDir(); - - return Object.assign( - { - root: "./" + includesDir, - compileDebug: true, - filename: "./" + includesDir, - }, - this.ejsOptions || {} - ); - } - - async compile(str, inputPath) { - let options = this.getEjsOptions(); - - if (inputPath && inputPath !== "ejs" && inputPath !== "md") { - options.filename = inputPath; - } - - let fn = this.ejsLib.compile(str, options); - - return function (data) { - return fn(data); - }; - } -} - -module.exports = Ejs; diff --git a/src/Engines/Haml.js b/src/Engines/Haml.js deleted file mode 100644 index 24795b081..000000000 --- a/src/Engines/Haml.js +++ /dev/null @@ -1,21 +0,0 @@ -const HamlLib = require("hamljs"); -const TemplateEngine = require("./TemplateEngine"); - -class Haml extends TemplateEngine { - constructor(name, dirs, config) { - super(name, dirs, config); - - this.setLibrary(this.config.libraryOverrides.haml); - } - - setLibrary(lib) { - this.hamlLib = lib || HamlLib; - this.setEngineLib(lib); - } - - async compile(str) { - return this.hamlLib.compile(str); - } -} - -module.exports = Haml; diff --git a/src/Engines/Handlebars.js b/src/Engines/Handlebars.js deleted file mode 100644 index 63b4e34c3..000000000 --- a/src/Engines/Handlebars.js +++ /dev/null @@ -1,73 +0,0 @@ -const HandlebarsLib = require("handlebars"); -const TemplateEngine = require("./TemplateEngine"); - -class Handlebars extends TemplateEngine { - constructor(name, dirs, config) { - super(name, dirs, config); - - this.setLibrary(this.config.libraryOverrides.hbs); - } - - setLibrary(lib) { - this.handlebarsLib = lib || HandlebarsLib; - this.setEngineLib(this.handlebarsLib); - - // TODO these all go to the same place (addHelper), add warnings for overwrites - this.addHelpers(this.config.handlebarsHelpers); - this.addShortcodes(this.config.handlebarsShortcodes); - this.addPairedShortcodes(this.config.handlebarsPairedShortcodes); - } - - addHelper(name, callback) { - this.handlebarsLib.registerHelper(name, callback); - } - - addHelpers(helpers) { - for (let name in helpers) { - // We don’t need to wrap helpers for `page` or `eleventy`, this is provided for free by Handlebars - this.addHelper(name, helpers[name]); - } - } - - addShortcodes(shortcodes) { - for (let name in shortcodes) { - this.addHelper(name, shortcodes[name]); - } - } - - addPairedShortcodes(shortcodes) { - for (let name in shortcodes) { - let callback = shortcodes[name]; - this.addHelper(name, function (...args) { - let options = args[args.length - 1]; - let content = ""; - if (options && options.fn) { - content = options.fn(this); - } - - return callback.call(this, content, ...args); - }); - } - } - - /** - * @override - */ - async cachePartialFiles() { - let ret = await super.cachePartialFiles(); - this.handlebarsLib.registerPartial(ret.partials); - return ret; - } - - async compile(str) { - // Ensure partials are cached and registered. - await this.getPartials(); - - let fn = this.handlebarsLib.compile(str); - return function (data) { - return fn(data); - }; - } -} - -module.exports = Handlebars; diff --git a/src/Engines/Html.js b/src/Engines/Html.js index 02c702d4c..d71d8d2ac 100644 --- a/src/Engines/Html.js +++ b/src/Engines/Html.js @@ -1,4 +1,4 @@ -const TemplateEngine = require("./TemplateEngine"); +import TemplateEngine from "./TemplateEngine.js"; class Html extends TemplateEngine { constructor(name, dirs, config) { @@ -8,7 +8,7 @@ class Html extends TemplateEngine { async compile(str, inputPath, preTemplateEngine) { if (preTemplateEngine) { - let engine = this.engineManager.getEngine( + let engine = await this.engineManager.getEngine( preTemplateEngine, this.dirs, this.extensionMap @@ -29,4 +29,4 @@ class Html extends TemplateEngine { } } -module.exports = Html; +export default Html; diff --git a/src/Engines/JavaScript.js b/src/Engines/JavaScript.js index 04cf4636b..60dbc67c2 100644 --- a/src/Engines/JavaScript.js +++ b/src/Engines/JavaScript.js @@ -1,9 +1,10 @@ -const { TemplatePath } = require("@11ty/eleventy-utils"); +import { TemplatePath } from "@11ty/eleventy-utils"; -const TemplateEngine = require("./TemplateEngine"); -const EleventyBaseError = require("../EleventyBaseError"); -const getJavaScriptData = require("../Util/GetJavaScriptData"); -const EventBusUtil = require("../Util/EventBusUtil"); +import TemplateEngine from "./TemplateEngine.js"; +import EleventyBaseError from "../EleventyBaseError.js"; +import getJavaScriptData from "../Util/GetJavaScriptData.js"; +import EventBusUtil from "../Util/EventBusUtil.js"; +import { EleventyImport } from "../Util/Require.js"; class JavaScriptTemplateNotDefined extends EleventyBaseError {} @@ -65,18 +66,20 @@ class JavaScript extends TemplateEngine { } } - getInstanceFromInputPath(inputPath) { + async getInstanceFromInputPath(inputPath) { if (this.instances[inputPath]) { return this.instances[inputPath]; } - const mod = require(TemplatePath.absolutePath(inputPath)); + let isEsm = this.eleventyConfig.getIsProjectUsingEsm(); + const mod = await EleventyImport(inputPath, isEsm ? "esm" : "cjs"); + let inst = this._getInstance(mod); if (inst) { this.instances[inputPath] = inst; } else { throw new JavaScriptTemplateNotDefined( - `No JavaScript template returned from ${inputPath} (did you assign to module.exports?)` + `No JavaScript template returned from ${inputPath}. Did you assign module.exports (CommonJS) or export (ESM)?` ); } return inst; @@ -92,7 +95,7 @@ class JavaScript extends TemplateEngine { } async getExtraDataFromFile(inputPath) { - let inst = this.getInstanceFromInputPath(inputPath); + let inst = await this.getInstanceFromInputPath(inputPath); return getJavaScriptData(inst, inputPath); } @@ -131,7 +134,7 @@ class JavaScript extends TemplateEngine { inst = this._getInstance(str); } else { // For normal templates, str will be falsy. - inst = this.getInstanceFromInputPath(inputPath); + inst = await this.getInstanceFromInputPath(inputPath); } if (inst && "render" in inst) { @@ -159,4 +162,4 @@ class JavaScript extends TemplateEngine { } } -module.exports = JavaScript; +export default JavaScript; diff --git a/src/Engines/Liquid.js b/src/Engines/Liquid.js index 787abddc4..4a2e1ca75 100644 --- a/src/Engines/Liquid.js +++ b/src/Engines/Liquid.js @@ -1,9 +1,11 @@ -const moo = require("moo"); -const liquidLib = require("liquidjs"); -const { TemplatePath } = require("@11ty/eleventy-utils"); +import moo from "moo"; +import liquidLib from "liquidjs"; +import { TemplatePath } from "@11ty/eleventy-utils"; +// import debugUtil from "debug"; -const TemplateEngine = require("./TemplateEngine"); -// const debug = require("debug")("Eleventy:Liquid"); +import TemplateEngine from "./TemplateEngine.js"; + +// const debug = debugUtil("Eleventy:Liquid"); class Liquid extends TemplateEngine { static argumentLexerOptions = { @@ -167,10 +169,7 @@ class Liquid extends TemplateEngine { argArray.push(b); } - let ret = yield shortcodeFn.call( - Liquid.normalizeScope(ctx), - ...argArray - ); + let ret = yield shortcodeFn.call(Liquid.normalizeScope(ctx), ...argArray); return ret; }, }; @@ -205,16 +204,9 @@ class Liquid extends TemplateEngine { argArray.push(b); } - const html = yield liquidEngine.renderer.renderTemplates( - this.templates, - ctx - ); + const html = yield liquidEngine.renderer.renderTemplates(this.templates, ctx); - let ret = yield shortcodeFn.call( - Liquid.normalizeScope(ctx), - html, - ...argArray - ); + let ret = yield shortcodeFn.call(Liquid.normalizeScope(ctx), html, ...argArray); // emitter.write(ret); return ret; }, @@ -270,4 +262,4 @@ class Liquid extends TemplateEngine { } } -module.exports = Liquid; +export default Liquid; diff --git a/src/Engines/Markdown.js b/src/Engines/Markdown.js index b464169fd..bf3b5cfed 100644 --- a/src/Engines/Markdown.js +++ b/src/Engines/Markdown.js @@ -1,6 +1,6 @@ -const markdownIt = require("markdown-it"); -const TemplateEngine = require("./TemplateEngine"); -// const debug = require("debug")("Eleventy:Markdown"); +import markdownIt from "markdown-it"; + +import TemplateEngine from "./TemplateEngine.js"; class Markdown extends TemplateEngine { constructor(name, dirs, config) { @@ -56,7 +56,7 @@ class Markdown extends TemplateEngine { if (preTemplateEngine) { let engine; if (typeof preTemplateEngine === "string") { - engine = this.engineManager.getEngine( + engine = await this.engineManager.getEngine( preTemplateEngine, this.dirs, this.extensionMap @@ -94,4 +94,4 @@ class Markdown extends TemplateEngine { } } -module.exports = Markdown; +export default Markdown; diff --git a/src/Engines/Mustache.js b/src/Engines/Mustache.js deleted file mode 100644 index df007b502..000000000 --- a/src/Engines/Mustache.js +++ /dev/null @@ -1,25 +0,0 @@ -const MustacheLib = require("mustache"); -const TemplateEngine = require("./TemplateEngine"); - -class Mustache extends TemplateEngine { - constructor(name, dirs, config) { - super(name, dirs, config); - - this.setLibrary(this.config.libraryOverrides.mustache); - } - - setLibrary(lib) { - this.mustacheLib = lib || MustacheLib; - this.setEngineLib(this.mustacheLib); - } - - async compile(str) { - let partials = await super.getPartials(); - - return function (data) { - return this.render(str, data, partials).trim(); - }.bind(this.mustacheLib); - } -} - -module.exports = Mustache; diff --git a/src/Engines/Nunjucks.js b/src/Engines/Nunjucks.js index 4aa6666dc..263dcbdfa 100755 --- a/src/Engines/Nunjucks.js +++ b/src/Engines/Nunjucks.js @@ -1,10 +1,10 @@ -const NunjucksLib = require("nunjucks"); -const { TemplatePath } = require("@11ty/eleventy-utils"); +import NunjucksLib from "nunjucks"; +import { TemplatePath } from "@11ty/eleventy-utils"; -const TemplateEngine = require("./TemplateEngine"); -const EleventyErrorUtil = require("../EleventyErrorUtil"); -const EleventyShortcodeError = require("../EleventyShortcodeError"); -const EventBusUtil = require("../Util/EventBusUtil"); +import TemplateEngine from "./TemplateEngine.js"; +import EleventyErrorUtil from "../EleventyErrorUtil.js"; +import EleventyShortcodeError from "../EleventyShortcodeError.js"; +import EventBusUtil from "../Util/EventBusUtil.js"; class Nunjucks extends TemplateEngine { constructor(name, dirs, config) { @@ -420,4 +420,4 @@ class Nunjucks extends TemplateEngine { } } -module.exports = Nunjucks; +export default Nunjucks; diff --git a/src/Engines/Pug.js b/src/Engines/Pug.js deleted file mode 100644 index 100b0c6f2..000000000 --- a/src/Engines/Pug.js +++ /dev/null @@ -1,42 +0,0 @@ -const PugLib = require("pug"); -const TemplateEngine = require("./TemplateEngine"); - -class Pug extends TemplateEngine { - constructor(name, dirs, config) { - super(name, dirs, config); - - this.pugOptions = this.config.pugOptions || {}; - - this.setLibrary(this.config.libraryOverrides.pug); - } - - setLibrary(override) { - this.pugLib = override || PugLib; - this.setEngineLib(this.pugLib); - } - - getPugOptions() { - let includesDir = super.getIncludesDir(); - - return Object.assign( - { - basedir: includesDir, - filename: includesDir, - }, - this.pugOptions || {} - ); - } - - async compile(str, inputPath) { - let options = this.getPugOptions(); - if (!inputPath || inputPath === "pug" || inputPath === "md") { - // do nothing - } else { - options.filename = inputPath; - } - - return this.pugLib.compile(str, options); - } -} - -module.exports = Pug; diff --git a/src/Engines/TemplateEngine.js b/src/Engines/TemplateEngine.js index a876ec127..2562be83a 100644 --- a/src/Engines/TemplateEngine.js +++ b/src/Engines/TemplateEngine.js @@ -1,11 +1,5 @@ -const fs = require("fs"); -const { TemplatePath } = require("@11ty/eleventy-utils"); - -const EleventyExtensionMap = require("../EleventyExtensionMap"); -const EleventyBaseError = require("../EleventyBaseError"); -const EventBusUtil = require("../Util/EventBusUtil"); - -const debug = require("debug")("Eleventy:TemplateEngine"); +import EleventyExtensionMap from "../EleventyExtensionMap.js"; +import EleventyBaseError from "../EleventyBaseError.js"; class TemplateEngineConfigError extends EleventyBaseError {} @@ -21,8 +15,6 @@ class TemplateEngine { this.inputDir = dirs.input; this.includesDir = dirs.includes; - this.resetPartials(); - this.engineLib = null; this.cacheable = false; @@ -89,101 +81,6 @@ class TemplateEngine { return this.includesDir; } - resetPartials() { - this.partialsHaveBeenCached = false; - this.partials = []; - this.partialsFiles = []; - } - - async getPartials() { - if (!this.partialsHaveBeenCached) { - let ret = await this.cachePartialFiles(); - this.partials = ret.partials; - this.partialsFiles = ret.files; - - EventBusUtil.soloOn("eleventy.resourceModified", (path) => { - if ((this.partialsFiles || []).includes(path)) { - this.resetPartials(); - } - }); - } - - return this.partials; - } - - /** - * Search for and cache partial files. - * - * This only runs if getPartials() is called, which only runs if you compile a Mustache/Handlebars template. - * - * @protected - */ - async cachePartialFiles() { - this.partialsHaveBeenCached = true; - - let results = []; - let partialFiles = []; - - if (this.includesDir) { - // TODO move this to use FileSystemSearch instead. - const fastglob = require("fast-glob"); - - let bench = this.benchmarks.aggregate.get("Searching the file system (partials)"); - bench.before(); - - let prefix = this.includesDir + "/**/*."; - await Promise.all( - this.extensions.map(async function (extension) { - partialFiles = partialFiles.concat( - await fastglob(prefix + extension, { - caseSensitiveMatch: false, - dot: true, - }) - ); - }) - ); - - bench.after(); - - results = await Promise.all( - partialFiles.map((partialFile) => { - partialFile = TemplatePath.addLeadingDotSlash(partialFile); - let partialPath = TemplatePath.stripLeadingSubPath(partialFile, this.includesDir); - let partialPathNoExt = partialPath; - this.extensions.forEach(function (extension) { - partialPathNoExt = TemplatePath.removeExtension(partialPathNoExt, "." + extension); - }); - - return fs.promises - .readFile(partialFile, { - encoding: "utf8", - }) - .then((content) => { - return { - content, - path: partialPathNoExt, - }; - }); - }) - ); - } - - let partials = {}; - for (let result of results) { - partials[result.path] = result.content; - } - - debug( - `${this.includesDir}/*.{${this.extensions}} found partials for: %o`, - Object.keys(partials) - ); - - return { - files: partialFiles, - partials, - }; - } - /** * @protected */ @@ -271,4 +168,4 @@ class TemplateEngine { } } -module.exports = TemplateEngine; +export default TemplateEngine; diff --git a/src/Errors/TemplateContentPrematureUseError.js b/src/Errors/TemplateContentPrematureUseError.js index 72822cc9a..e7fcc2e1a 100644 --- a/src/Errors/TemplateContentPrematureUseError.js +++ b/src/Errors/TemplateContentPrematureUseError.js @@ -1,5 +1,5 @@ -const EleventyBaseError = require("../EleventyBaseError"); +import EleventyBaseError from "../EleventyBaseError.js"; class TemplateContentPrematureUseError extends EleventyBaseError {} -module.exports = TemplateContentPrematureUseError; +export default TemplateContentPrematureUseError; diff --git a/src/Errors/TemplateContentUnrenderedTemplateError.js b/src/Errors/TemplateContentUnrenderedTemplateError.js index 35ea957b7..ee1dff1a4 100644 --- a/src/Errors/TemplateContentUnrenderedTemplateError.js +++ b/src/Errors/TemplateContentUnrenderedTemplateError.js @@ -1,5 +1,5 @@ -const EleventyBaseError = require("../EleventyBaseError"); +import EleventyBaseError from "../EleventyBaseError.js"; class TemplateContentUnrenderedTemplateError extends EleventyBaseError {} -module.exports = TemplateContentUnrenderedTemplateError; +export default TemplateContentUnrenderedTemplateError; diff --git a/src/Errors/UsingCircularTemplateContentReferenceError.js b/src/Errors/UsingCircularTemplateContentReferenceError.js index f5e9ea0ce..e9729aacb 100644 --- a/src/Errors/UsingCircularTemplateContentReferenceError.js +++ b/src/Errors/UsingCircularTemplateContentReferenceError.js @@ -1,5 +1,5 @@ -const EleventyBaseError = require("../EleventyBaseError"); +import EleventyBaseError from "../EleventyBaseError.js"; class UsingCircularTemplateContentReferenceError extends EleventyBaseError {} -module.exports = UsingCircularTemplateContentReferenceError; +export default UsingCircularTemplateContentReferenceError; diff --git a/src/EventBus.js b/src/EventBus.js index 682b87c3f..084292990 100644 --- a/src/EventBus.js +++ b/src/EventBus.js @@ -1,5 +1,8 @@ -const EventEmitter = require("./Util/AsyncEventEmitter"); -const debug = require("debug")("Eleventy:EventBus"); +import debugUtil from "debug"; + +import EventEmitter from "./Util/AsyncEventEmitter.js"; + +const debug = debugUtil("Eleventy:EventBus"); /** * @module 11ty/eleventy/EventBus @@ -14,4 +17,4 @@ debug("Setting up global EventBus."); let bus = new EventEmitter(); bus.setMaxListeners(100); -module.exports = bus; +export default bus; diff --git a/src/FileSystemSearch.js b/src/FileSystemSearch.js index 9e4e8e669..4d6ffc63d 100644 --- a/src/FileSystemSearch.js +++ b/src/FileSystemSearch.js @@ -1,8 +1,9 @@ -const fastglob = require("fast-glob"); -const micromatch = require("micromatch"); +import fastglob from "fast-glob"; +import micromatch from "micromatch"; +import { TemplatePath } from "@11ty/eleventy-utils"; +import debugUtil from "debug"; -const { TemplatePath } = require("@11ty/eleventy-utils"); -const debug = require("debug")("Eleventy:FastGlobManager"); +const debug = debugUtil("Eleventy:FastGlobManager"); class FileSystemSearch { constructor() { @@ -99,4 +100,4 @@ class FileSystemSearch { } } -module.exports = FileSystemSearch; +export default FileSystemSearch; diff --git a/src/Filters/GetCollectionItem.js b/src/Filters/GetCollectionItem.js index d436ec186..dc328793f 100644 --- a/src/Filters/GetCollectionItem.js +++ b/src/Filters/GetCollectionItem.js @@ -1,4 +1,4 @@ -module.exports = function getCollectionItem(collection, page, modifier = 0) { +export default function getCollectionItem(collection, page, modifier = 0) { let j = 0; let index; for (let item of collection) { @@ -17,4 +17,4 @@ module.exports = function getCollectionItem(collection, page, modifier = 0) { return collection[index + modifier]; } } -}; +} diff --git a/src/Filters/GetCollectionItemIndex.js b/src/Filters/GetCollectionItemIndex.js index 3bc03a3e5..b3f8c7203 100644 --- a/src/Filters/GetCollectionItemIndex.js +++ b/src/Filters/GetCollectionItemIndex.js @@ -1,5 +1,5 @@ // TODO locale-friendly, see GetLocaleCollectionItem.js) -module.exports = function getCollectionItemIndex(collection, page) { +export default function getCollectionItemIndex(collection, page) { if (!page) { page = this.page; } @@ -14,4 +14,4 @@ module.exports = function getCollectionItemIndex(collection, page) { } j++; } -}; +} diff --git a/src/Filters/GetLocaleCollectionItem.js b/src/Filters/GetLocaleCollectionItem.js index 4d51d7fc6..b8071a07b 100644 --- a/src/Filters/GetLocaleCollectionItem.js +++ b/src/Filters/GetLocaleCollectionItem.js @@ -1,4 +1,4 @@ -const getCollectionItem = require("./GetCollectionItem"); +import getCollectionItem from "./GetCollectionItem.js"; // Work with I18n Plugin src/Plugins/I18nPlugin.js to retrieve root pages (not i18n pages) function resolveRootPage(config, pageOverride, languageCode) { @@ -11,23 +11,13 @@ function resolveRootPage(config, pageOverride, languageCode) { return localeFilter.call(this, pageOverride, languageCode); } -function getLocaleCollectionItem( - config, - collection, - pageOverride, - langCode, - indexModifier = 0 -) { +function getLocaleCollectionItem(config, collection, pageOverride, langCode, indexModifier = 0) { if (!langCode) { // if page.lang exists (2.0.0-canary.14 and i18n plugin added, use page language) if (this.page.lang) { langCode = this.page.lang; } else { - return getCollectionItem( - collection, - pageOverride || this.page, - indexModifier - ); + return getCollectionItem(collection, pageOverride || this.page, indexModifier); } } @@ -39,12 +29,7 @@ function getLocaleCollectionItem( // Resolve modified root `page` back to locale `page` // This will return a non localized version of the page as a fallback - let modifiedLocalePage = resolveRootPage.call( - this, - config, - modifiedRootItem.data.page, - langCode - ); + let modifiedLocalePage = resolveRootPage.call(this, config, modifiedRootItem.data.page, langCode); // already localized (or default language) if (!("__locale_page_resolved" in modifiedLocalePage)) { return modifiedRootItem; @@ -59,4 +44,4 @@ function getLocaleCollectionItem( return getCollectionItem(all, modifiedLocalePage, 0); } -module.exports = getLocaleCollectionItem; +export default getLocaleCollectionItem; diff --git a/src/Filters/ServerlessUrl.js b/src/Filters/ServerlessUrl.js deleted file mode 100644 index efe0667ed..000000000 --- a/src/Filters/ServerlessUrl.js +++ /dev/null @@ -1,42 +0,0 @@ -const { compile } = require("path-to-regexp"); -const normalizeServerlessUrl = require("../Util/NormalizeServerlessUrl"); - -function stringify(url, urlData = {}) { - url = normalizeServerlessUrl(url); - - let fn = compile(url, { - encode: encodeURIComponent, - }); - return fn(urlData); -} - -module.exports = function (url, urlData = {}) { - if (Array.isArray(url)) { - let errors = []; - let urls = url - .slice() - .map((entry) => { - // if multiple serverless URLs exist, return the first one that matches - let result = false; - try { - result = stringify(entry, urlData); - } catch (e) { - errors.push(e.message); - } finally { - return result; - } - }) - .filter((entry) => !!entry); - - if (!urls.length) { - throw new Error( - "Looked through an array of serverless URLs but found no matches, errors: " + - errors.join(";") - ); - } - - return urls; - } - - return stringify(url, urlData); -}; diff --git a/src/Filters/Slug.js b/src/Filters/Slug.js index 9e9f13a47..a2c007738 100644 --- a/src/Filters/Slug.js +++ b/src/Filters/Slug.js @@ -1,6 +1,6 @@ -const slugify = require("slugify"); +import slugify from "slugify"; -module.exports = function (str, options = {}) { +export default function (str, options = {}) { return slugify( "" + str, Object.assign( @@ -11,4 +11,4 @@ module.exports = function (str, options = {}) { options ) ); -}; +} diff --git a/src/Filters/Slugify.js b/src/Filters/Slugify.js index 28fbdc433..e398e8a4a 100644 --- a/src/Filters/Slugify.js +++ b/src/Filters/Slugify.js @@ -1,6 +1,6 @@ -const slugify = require("@sindresorhus/slugify"); +import slugify from "@sindresorhus/slugify"; -module.exports = function (str, options = {}) { +export default function (str, options = {}) { return slugify( "" + str, Object.assign( @@ -11,4 +11,4 @@ module.exports = function (str, options = {}) { options ) ); -}; +} diff --git a/src/Filters/Url.js b/src/Filters/Url.js index 016053377..ce59c4bb7 100644 --- a/src/Filters/Url.js +++ b/src/Filters/Url.js @@ -1,4 +1,4 @@ -const { TemplatePath } = require("@11ty/eleventy-utils"); +import { TemplatePath } from "@11ty/eleventy-utils"; function isValidUrl(url) { try { @@ -11,7 +11,7 @@ function isValidUrl(url) { } // Note: This filter is used in the Eleventy Navigation plugin in versions prior to 0.3.4 -module.exports = function (url, pathPrefix) { +export default function (url, pathPrefix) { // work with undefined url = url || ""; @@ -40,4 +40,4 @@ module.exports = function (url, pathPrefix) { } return normUrl; -}; +} diff --git a/src/GlobalDependencyMap.js b/src/GlobalDependencyMap.js index 958bbe37b..a92c6b401 100644 --- a/src/GlobalDependencyMap.js +++ b/src/GlobalDependencyMap.js @@ -1,17 +1,18 @@ -const { DepGraph } = require("dependency-graph"); -const { TemplatePath } = require("@11ty/eleventy-utils"); -const debug = require("debug")("Eleventy:Dependencies"); +import { fileURLToPath } from "node:url"; -const PathNormalizer = require("./Util/PathNormalizer.js"); +import { DepGraph } from "dependency-graph"; +import { TemplatePath } from "@11ty/eleventy-utils"; +import debugUtil from "debug"; + +import PathNormalizer from "./Util/PathNormalizer.js"; + +const debug = debugUtil("Eleventy:Dependencies"); class GlobalDependencyMap { // dependency-graph requires these keys to be alphabetic strings static LAYOUT_KEY = "layout"; static COLLECTION_PREFIX = "__collection:"; - // URL object with a windows, with file:// already removed (from file:///C:/directory/ to /C:/directory/) - static WINDOWS_DRIVE_URL_PATH = /^\/\w\:\//; - reset() { this._map = undefined; } @@ -92,10 +93,7 @@ class GlobalDependencyMap { // Fix file:///Users/ or file:///C:/ paths passed in if (node.startsWith("file://")) { - node = node.slice("file://".length); - if (node.match(GlobalDependencyMap.WINDOWS_DRIVE_URL_PATH)) { - node = node.slice(1); // take off the leading slash, /C:/ becomes C:/ - } + node = fileURLToPath(node); } if (typeof node !== "string") { @@ -343,4 +341,4 @@ class GlobalDependencyMap { } } -module.exports = GlobalDependencyMap; +export default GlobalDependencyMap; diff --git a/src/Plugins/DefaultEdgeFunctionContent.js b/src/Plugins/DefaultEdgeFunctionContent.js deleted file mode 100644 index 1fbda5885..000000000 --- a/src/Plugins/DefaultEdgeFunctionContent.js +++ /dev/null @@ -1,28 +0,0 @@ -import { - EleventyEdge, - precompiledAppData, -} from "./_generated/eleventy-edge-app.js"; - -export default async (request, context) => { - try { - let edge = new EleventyEdge("%%EDGE_NAME%%", { - request, - context, - precompiled: precompiledAppData, - - // default is [], add more keys to opt-in e.g. ["appearance", "username"] - cookies: [], - }); - - edge.config((eleventyConfig) => { - // Add some custom Edge-specific configuration - // e.g. Fancier json output - // eleventyConfig.addFilter("json", obj => JSON.stringify(obj, null, 2)); - }); - - return await edge.handleResponse(); - } catch (e) { - console.log("ERROR", { e }); - return context.next(e); - } -}; diff --git a/src/Plugins/DefaultServerlessFunctionContent.js b/src/Plugins/DefaultServerlessFunctionContent.js deleted file mode 100644 index 009f26e61..000000000 --- a/src/Plugins/DefaultServerlessFunctionContent.js +++ /dev/null @@ -1,57 +0,0 @@ -const { EleventyServerless } = require("@11ty/eleventy"); - -// Explicit dependencies for the bundler from config file and global data. -// The file is generated by the Eleventy Serverless Bundler Plugin. -require("./eleventy-bundler-modules.js"); - -async function handler(event) { - let elev = new EleventyServerless("%%NAME%%", { - path: new URL(event.rawUrl).pathname, - query: event.multiValueQueryStringParameters || event.queryStringParameters, - functionsDir: "%%FUNCTIONS_DIR%%", - }); - - try { - let [page] = await elev.getOutput(); - - // If you want some of the data cascade available in `page.data`, use `eleventyConfig.dataFilterSelectors`. - // Read more: https://www.11ty.dev/docs/config/#data-filter-selectors - - return { - statusCode: 200, - headers: { - "Content-Type": "text/html; charset=UTF-8", - }, - body: page.content, - }; - } catch (error) { - // Only console log for matching serverless paths - // (otherwise you’ll see a bunch of BrowserSync 404s for non-dynamic URLs during --serve) - if (elev.isServerlessUrl(event.path)) { - console.log("Serverless Error:", error); - } - - return { - statusCode: error.httpStatusCode || 500, - body: JSON.stringify( - { - error: error.message, - }, - null, - 2 - ), - }; - } -} - -// Choose one: -// * Runs on each request: AWS Lambda, Netlify Function -// * Runs on first request only: Netlify On-demand Builder -// 1. Don’t forget to `npm install @netlify/functions` -// 2. Also use `redirects: "netlify-toml-builders"` in your config file’s serverless bundler options: -// https://www.11ty.dev/docs/plugins/serverless/#bundler-options - -exports.handler = handler; - -//const { builder } = require("@netlify/functions"); -//exports.handler = builder(handler); diff --git a/src/Plugins/Edge/EdgeTemplateDataID.js b/src/Plugins/Edge/EdgeTemplateDataID.js deleted file mode 100644 index 89764306b..000000000 --- a/src/Plugins/Edge/EdgeTemplateDataID.js +++ /dev/null @@ -1,39 +0,0 @@ -const { createHash } = require("crypto"); - -class EdgeTemplateDataID { - constructor() { - this.data = {}; - } - - reset() { - this.data = {}; - } - - hasData(data = {}) { - return Object.keys(data).length > 0; - } - - getDataKey(data = {}) { - if (!this.hasData(data)) { - return; - } - - let hash = createHash("sha256"); - hash.update(JSON.stringify(data)); - return "ELEVENTYEDGEDATA_" + hash.digest("hex"); - } - - addData(data) { - let key = this.getDataKey(data); - if (key) { - this.data[key] = data; - return key; - } - } - - toString() { - return `"buildTimeData": ${JSON.stringify(this.data, null, 2)}`; - } -} - -module.exports = EdgeTemplateDataID; diff --git a/src/Plugins/Edge/LiquidEdge.js b/src/Plugins/Edge/LiquidEdge.js deleted file mode 100644 index 37b7dc422..000000000 --- a/src/Plugins/Edge/LiquidEdge.js +++ /dev/null @@ -1,53 +0,0 @@ -const { Tokenizer, evalToken } = require("liquidjs"); - -function rawContentLiquidTag(liquidEngine, renderFn, tagName) { - // via https://github.com/harttle/liquidjs/blob/b5a22fa0910c708fe7881ef170ed44d3594e18f3/src/builtin/tags/raw.ts - return { - parse: function (tagToken, remainTokens) { - this.name = tagToken.name; - this.args = []; - this.tokens = []; - - const tokenizer = new Tokenizer(tagToken.args); - this.args = []; - while (!tokenizer.end()) { - let value = tokenizer.readValue(); - if (!value) { - break; - } - this.args.push(value); - } - - var stream = liquidEngine.parser - .parseStream(remainTokens) - .on("token", (token) => { - if (token.name === "end" + tagName) stream.stop(); - else this.tokens.push(token); - }) - .on("end", () => { - throw new Error(`tag ${tagToken.getText()} not closed`); - }); - - stream.start(); - }, - render: function* (ctx, emitter) { - let normalizedContext = {}; - if (ctx) { - normalizedContext.page = ctx.get(["page"]); - normalizedContext.eleventy = ctx.get(["eleventy"]); - } - - let argArray = []; - for (let arg of this.args) { - let b = yield evalToken(arg, ctx); - argArray.push(b); - } - - let body = this.tokens.map((token) => token.getText()).join(""); - - return renderFn.call(normalizedContext, tagName, body, ...argArray); - }, - }; -} - -module.exports = rawContentLiquidTag; diff --git a/src/Plugins/Edge/NunjucksEdge.js b/src/Plugins/Edge/NunjucksEdge.js deleted file mode 100644 index 76da56ebc..000000000 --- a/src/Plugins/Edge/NunjucksEdge.js +++ /dev/null @@ -1,105 +0,0 @@ -function rawContentNunjucksTag(nunjucks, nunjucksEnv, renderFn, tagName) { - return new (function () { - this.tags = [tagName]; - - this.parse = function (parser, nodes) { - var tok = parser.nextToken(); - - var args = parser.parseSignature(true, true); - const begun = parser.advanceAfterBlockEnd(tok.value); - - // This code was ripped from the Nunjucks parser for `raw` - // https://github.com/mozilla/nunjucks/blob/fd500902d7c88672470c87170796de52fc0f791a/nunjucks/src/parser.js#L655 - const endTagName = "end" + tagName; - // Look for upcoming raw blocks (ignore all other kinds of blocks) - const rawBlockRegex = new RegExp( - "([\\s\\S]*?){%\\s*(" + tagName + "|" + endTagName + ")\\s*(?=%})%}" - ); - let rawLevel = 1; - let str = ""; - let matches = null; - - // Exit when there's nothing to match - // or when we've found the matching "endraw" block - while ( - (matches = parser.tokens._extractRegex(rawBlockRegex)) && - rawLevel > 0 - ) { - const all = matches[0]; - const pre = matches[1]; - const blockName = matches[2]; - - // Adjust rawlevel - if (blockName === tagName) { - rawLevel += 1; - } else if (blockName === endTagName) { - rawLevel -= 1; - } - - // Add to str - if (rawLevel === 0) { - // We want to exclude the last "endraw" - str += pre; - // Move tokenizer to beginning of endraw block - parser.tokens.backN(all.length - pre.length); - } else { - str += all; - } - } - - let body = new nodes.Output(begun.lineno, begun.colno, [ - new nodes.TemplateData(begun.lineno, begun.colno, str), - ]); - return new nodes.CallExtensionAsync(this, "run", args, [body]); - }; - - this.run = function (...args) { - let resolve = args.pop(); - let body = args.pop(); - let [context, arg1, arg2, ...argArray] = args; - - let normalizedContext = {}; - if (context.ctx && context.ctx.page) { - normalizedContext.ctx = context.ctx; - normalizedContext.page = context.ctx.page; - } - if (context.ctx && context.ctx.eleventy) { - normalizedContext.eleventy = context.ctx.eleventy; - } - - body(function (e, bodyContent) { - if (e) { - resolve( - new Error( - `Error with Nunjucks paired shortcode \`${tagName}\`: ${e.message}` - ) - ); - } - - Promise.resolve( - renderFn.call( - normalizedContext, - tagName, - bodyContent, - arg1, // lang when edge(lang, data) and data when edge(data) - arg2, // data when edge(lang, data) (all handled downstream) - { nunjucks, nunjucksEnv } - ) - ) - .then(function (returnValue) { - resolve(null, new nunjucks.runtime.SafeString(returnValue)); - }) - .catch(function (e) { - resolve( - new Error( - `Error with Nunjucks paired shortcode \`${tagName}\`: ${e.message}` - ), - null - ); - }); - }); - }; - })(); -} - -module.exports = rawContentNunjucksTag; diff --git a/src/Plugins/Edge/PrecompiledNunjucks.js b/src/Plugins/Edge/PrecompiledNunjucks.js deleted file mode 100644 index 7536fa357..000000000 --- a/src/Plugins/Edge/PrecompiledNunjucks.js +++ /dev/null @@ -1,58 +0,0 @@ -const { createHash } = require("crypto"); - -class PrecompiledNunjucks { - constructor() { - this.rawTemplates = {}; - } - - getPrecompiledTemplateKey(str) { - let hash = createHash("sha256"); - hash.update(str); - return "EleventyEdgeNunjucksPrecompile:" + hash.digest("hex"); - } - - setLibraries({ nunjucks, nunjucksEnv }) { - this.nunjucks = nunjucks; - this.nunjucksEnv = nunjucksEnv; - } - - add(str) { - // for precompiled template object key - let key = this.getPrecompiledTemplateKey(str); - this.rawTemplates[key] = str; - return key; - } - - toString() { - let ret = []; - if (Object.keys(this.rawTemplates).length > 0) { - if (!this.nunjucks || !this.nunjucksEnv) { - throw new Error("Missing Nunjucks and Nunjucks environment"); - } - - for (let key in this.rawTemplates) { - let precompiled = this.nunjucks.precompileString( - this.rawTemplates[key], - { - name: key, - env: this.nunjucksEnv, - asFunction: true, - force: true, - wrapper: function ([tmpl], opts) { - // console.log( { templates, opts } ); - return `(function() {${tmpl.template}}())`; - }, - } - ); - - ret.push(`"${key}": ${precompiled},`); - } - } - - return `"nunjucksPrecompiled": { - ${ret.join("\n")} -}`; - } -} - -module.exports = PrecompiledNunjucks; diff --git a/src/Plugins/EdgePlugin.js b/src/Plugins/EdgePlugin.js deleted file mode 100644 index d647aea3b..000000000 --- a/src/Plugins/EdgePlugin.js +++ /dev/null @@ -1,222 +0,0 @@ -const path = require("path"); -const fs = require("fs"); -const fsp = fs.promises; -const { TemplatePath } = require("@11ty/eleventy-utils"); - -const rawContentLiquidTag = require("./Edge/LiquidEdge.js"); -const rawContentNunjucksTag = require("./Edge/NunjucksEdge.js"); -const PrecompiledNunjucks = require("./Edge/PrecompiledNunjucks.js"); -const EdgeTemplateDataID = require("./Edge/EdgeTemplateDataID.js"); - -class EdgeHelper { - constructor() { - this.ids = new EdgeTemplateDataID(); - this.precompiledTemplates = new PrecompiledNunjucks(); - } - - setOptions(options) { - this.options = options; - } - - getOutputPath(filepath) { - return TemplatePath.addLeadingDotSlash(path.join(this.options.functionsDir, filepath)); - } - - async writeDefaultEdgeFunctionFile() { - let filepath = this.getOutputPath("eleventy-edge.js"); - - if (fs.existsSync(filepath)) { - let contents = await fsp.readFile(filepath, "utf8"); - let trimmed = contents.trim(); - if ( - trimmed.startsWith(`import { EleventyEdge } from "./_generated/eleventy-edge.js";`) || - trimmed.startsWith(`import { EleventyEdge } from "eleventy:edge";`) - ) { - throw new Error( - `Experimental early adopter API change alert! Unfortunately the default imports for Eleventy Edge in the latest canary have changed. The easiest thing you can do is delete your existing \`${path.join( - this.options.functionsDir, - "eleventy-edge.js" - )}\` and let Eleventy generate a new one for you. The new import should be \`import { EleventyEdge, precompiledAppData } from "./_generated/eleventy-edge-app.js";\`` - ); - } - } else { - let defaultContentPath = TemplatePath.absolutePath( - __dirname, - "./DefaultEdgeFunctionContent.js" - ); - - let contents = await fsp.readFile(defaultContentPath, "utf8"); - contents = contents.replace(/\%\%EDGE_NAME\%\%/g, this.options.name); - contents = contents.replace(/\%\%EDGE_VERSION\%\%/g, this.options.eleventyEdgeVersion); - return fsp.writeFile(filepath, contents); - } - } -} - -let helper = new EdgeHelper(); - -function renderAsLiquid(functionName, body, langOverride, serializedData, extras = {}) { - // edge(serializedData) - // edge(langOverride, serializedData) - - // Langoverride was not specified, reorder arguments and move everything up - if (langOverride && typeof langOverride !== "string" && !serializedData) { - serializedData = langOverride; - langOverride = undefined; - } - - let syntax = langOverride || this.page.templateSyntax; - if (!syntax) { - throw new Error( - "Could not determine template syntax for Eleventy Edge. You may need to upgrade Eleventy!" - ); - } - - let languages = syntax.split(",").map((entry) => entry.trim()); - - let supportedLanguages = ["njk", "liquid", "html", "md"]; - if (!supportedLanguages.includes(languages[0])) { - throw new Error( - "The {% edge %} rendering shortcode does not yet support the `" + - languages[0] + - "` syntax as content to the helper." - ); - } - - // Deno deploy doesn’t work with eval, so we need to precompile to workaround eval on - // templates by precompiling all of our templates. - if (languages[0] === "njk") { - if (process.env.ELEVENTY_SERVERLESS) { - throw new Error( - 'Due to template language limitations (specifically: use of `eval`), {% edge "njk" %} is not a supported template language for the {% edge %} shortcode when used on an Eleventy Serverless template. You have three options here: 1. Use another template language on the shortcode (e.g. `{% edge "liquid" %}`). 2. Use {% renderTemplate %} or remove the {% edge %} call altogether (unless you’re using a cached On-demand Builder the rendering is happening at request-time anyway) 3. (Perhaps least ideal) Refactor this template render to run at build-time instead of serverless mode.' - ); - } - - body = helper.precompiledTemplates.add(body); - } - - let dataVar = ""; - let extraData = []; - if (helper.ids.hasData(serializedData)) { - let key = helper.ids.addData(serializedData); - if (key) { - if (process.env.ELEVENTY_SERVERLESS) { - if (languages[0] === "liquid") { - // We serialize this into the response (this data isn’t written to disk, but it may be saved in a CDN cache a la ODB) - for (let propName in serializedData) { - extraData.push( - `{% assign ${propName} = ${JSON.stringify(serializedData[propName])} %}` - ); - } - } - } else { - dataVar = ` ${key}`; - } - } - } - - let types = { - html: { comments: [""] }, - css: { comments: ["/*", "*/"] }, - js: { comments: ["/*", "*/"] }, - }; - - let type = "html"; - // when permalink is false, this.page.url is false - if (this.page.url) { - if (this.page.url.endsWith(".css")) { - type = "css"; - } else if (this.page.url.endsWith(".js")) { - // TODO more extensions here? - type = "js"; - } - } - - return `${ - types[type].comments[0] - }ELEVENTYEDGE_${functionName} "${syntax}"${dataVar} %}${extraData.join( - "" - )}${body}ELEVENTYEDGE_${functionName}${types[type].comments[1]}`; -} - -// Build time plugin to create ELEVENTYEDGE comments that will be later evaluated at the Edge -function EleventyEdgePlugin(eleventyConfig, opts = {}) { - let options = Object.assign( - { - name: "edge", - functionsDir: "./netlify/edge-functions/", - - // for the default Deno import - eleventyEdgeVersion: "2.0.2", - - // runtime compatibility check with Eleventy core version - compatibility: ">=2", - }, - opts - ); - - helper.setOptions(options); - - // TODO add middleware support so that we can just run on Eleventy Dev Server directly (needs ESM first) - // eleventyConfig.setServerOptions({ - // middleware: [ - // async (request, response, next) => { - // console.log( await next() ); - // } - // ] - // }) - - eleventyConfig.on("eleventy.engine.njk", ({ nunjucks, environment }) => { - helper.precompiledTemplates.setLibraries({ - nunjucks: nunjucks, - nunjucksEnv: environment, - }); - }); - - eleventyConfig.addNunjucksTag(options.name, function (nunjucksLib, nunjucksEnv) { - return rawContentNunjucksTag(nunjucksLib, nunjucksEnv, renderAsLiquid, options.name); - }); - - eleventyConfig.addLiquidTag(options.name, function (liquidEngine) { - return rawContentLiquidTag(liquidEngine, renderAsLiquid, options.name); - }); - - eleventyConfig.addJavaScriptFunction(options.name, async function (...args) { - return renderAsLiquid.call(this, options.name, ...args); - }); - - // Edge Functions with Serverless mode, don’t write files. - if (!process.env.ELEVENTY_SERVERLESS) { - // Generate app eleventy-edge-app.js file and generate default edge function (if needed) - eleventyConfig.on("eleventy.after", async () => { - await fsp.mkdir(path.join(options.functionsDir, "_generated"), { - recursive: true, - }); - - let content = []; - if (options.compatibility) { - content.push(`"eleventy": { "compatibility": "${options.compatibility}" }`); - } - content.push(helper.ids.toString()); - content.push(helper.precompiledTemplates.toString()); - - // New replacement for `eleventy:edge` and `eleventy-edge-app-data.js` imports. - await fsp.writeFile( - path.join(options.functionsDir, "_generated/eleventy-edge-app.js"), - `import { EleventyEdge } from "https://cdn.11ty.dev/edge@${ - options.eleventyEdgeVersion - }/eleventy-edge.js"; - -const precompiledAppData = { ${content.join(",\n")} }; - -export { EleventyEdge, precompiledAppData }` - ); - - await helper.writeDefaultEdgeFunctionFile(); - }); - } - - // TODO add a route checker to show a warning if edge shortcodes are used on pages that are not handled in edge function routes -} - -module.exports = EleventyEdgePlugin; diff --git a/src/Plugins/HtmlBasePlugin.js b/src/Plugins/HtmlBasePlugin.js index 49a5cb300..440d46efb 100644 --- a/src/Plugins/HtmlBasePlugin.js +++ b/src/Plugins/HtmlBasePlugin.js @@ -1,8 +1,9 @@ -const posthtml = require("posthtml"); -const urls = require("posthtml-urls"); -const urlFilter = require("../Filters/Url.js"); -const PathPrefixer = require("../Util/PathPrefixer.js"); -const { DeepCopy } = require("../Util/Merge"); +import posthtml from "posthtml"; +import urls from "posthtml-urls"; + +import urlFilter from "../Filters/Url.js"; +import PathPrefixer from "../Util/PathPrefixer.js"; +import { DeepCopy } from "../Util/Merge.js"; function isValidUrl(url) { try { @@ -65,7 +66,7 @@ async function addToAllHtmlUrls(htmlContent, callback, processOptions = {}) { return result.html; } -module.exports = function (eleventyConfig, defaultOptions = {}) { +export default function (eleventyConfig, defaultOptions = {}) { let opts = DeepCopy( { // eleventyConfig.pathPrefix is new in Eleventy 2.0.0-canary.15 @@ -86,31 +87,26 @@ module.exports = function (eleventyConfig, defaultOptions = {}) { ); if (opts.baseHref === undefined) { - throw new Error( - "The `base` option is required in the Eleventy HTML Base plugin." - ); + throw new Error("The `base` option is required in the Eleventy HTML Base plugin."); } eleventyConfig.addFilter(opts.filters.pathPrefix, function (url) { return addPathPrefixToUrl(url, eleventyConfig.pathPrefix); }); - eleventyConfig.addFilter( - opts.filters.base, - function (url, baseOverride, pageUrlOverride) { - let base = baseOverride || opts.baseHref; - - // Do nothing with a default base - if (base === "/") { - return url; - } + eleventyConfig.addFilter(opts.filters.base, function (url, baseOverride, pageUrlOverride) { + let base = baseOverride || opts.baseHref; - return transformUrl.call(this, url, base, { - pathPrefix: eleventyConfig.pathPrefix, - pageUrl: pageUrlOverride || this.page?.url, - }); + // Do nothing with a default base + if (base === "/") { + return url; } - ); + + return transformUrl.call(this, url, base, { + pathPrefix: eleventyConfig.pathPrefix, + pageUrl: pageUrlOverride || this.page?.url, + }); + }); eleventyConfig.addAsyncFilter( opts.filters.html, @@ -155,6 +151,6 @@ module.exports = function (eleventyConfig, defaultOptions = {}) { }); } } -}; +} -module.exports.applyBaseToUrl = transformUrl; +export { transformUrl as applyBaseToUrl }; diff --git a/src/Plugins/I18nPlugin.js b/src/Plugins/I18nPlugin.js index 64eef5cfc..0474db535 100644 --- a/src/Plugins/I18nPlugin.js +++ b/src/Plugins/I18nPlugin.js @@ -1,3 +1,8 @@ +import { bcp47Normalize } from "bcp-47-normalize"; +import iso639 from "iso-639-1"; + +import { DeepCopy } from "../Util/Merge.js"; + // pathPrefix note: // When using `locale_url` filter with the `url` filter, `locale_url` must run first like // `| locale_url | url`. If you run `| url | locale_url` it won’t match correctly. @@ -6,15 +11,10 @@ // path prefix at the beginning? Would need a better way to know `url` has transformed a string // rather than just raw comparison. // e.g. --pathprefix=/en/ should return `/en/en/` for `/en/index.liquid` -const { DeepCopy } = require("../Util/Merge"); -const bcp47Normalize = require("bcp-47-normalize"); -const iso639 = require("iso-639-1"); class LangUtils { static getLanguageCodeFromInputPath(filepath) { - return (filepath || "") - .split("/") - .find((entry) => Comparator.isLangCode(entry)); + return (filepath || "").split("/").find((entry) => Comparator.isLangCode(entry)); } static getLanguageCodeFromUrl(url) { @@ -189,12 +189,12 @@ function EleventyPlugin(eleventyConfig, opts = {}) { }, errorMode: "strict", // allow-fallback, never }, - opts + opts, ); if (!options.defaultLanguage) { throw new Error( - "You must specify a `defaultLanguage` in Eleventy’s Internationalization (I18N) plugin." + "You must specify a `defaultLanguage` in Eleventy’s Internationalization (I18N) plugin.", ); } @@ -206,88 +206,74 @@ function EleventyPlugin(eleventyConfig, opts = {}) { }); let contentMaps = {}; - eleventyConfig.on( - "eleventy.contentMap", - function ({ urlToInputPath, inputPathToUrl }) { - let bench = benchmarkManager.get("(i18n Plugin) Setting up content map."); - bench.before(); - contentMaps.inputPathToUrl = inputPathToUrl; - contentMaps.urlToInputPath = urlToInputPath; - - contentMaps.localeUrlsMap = getLocaleUrlsMap( - urlToInputPath, - extensionMap, - benchmarkManager - ); - bench.after(); - } - ); + eleventyConfig.on("eleventy.contentMap", function ({ urlToInputPath, inputPathToUrl }) { + let bench = benchmarkManager.get("(i18n Plugin) Setting up content map."); + bench.before(); + contentMaps.inputPathToUrl = inputPathToUrl; + contentMaps.urlToInputPath = urlToInputPath; + + contentMaps.localeUrlsMap = getLocaleUrlsMap(urlToInputPath, extensionMap, benchmarkManager); + bench.after(); + }); eleventyConfig.addGlobalData("eleventyComputed.page.lang", () => { // if addGlobalData receives a function it will execute it immediately, // so we return a nested function for computed data return (data) => { - return ( - LangUtils.getLanguageCodeFromUrl(data.page.url) || - options.defaultLanguage - ); + return LangUtils.getLanguageCodeFromUrl(data.page.url) || options.defaultLanguage; }; }); // Normalize a theoretical URL based on the current page’s language // If a non-localized file exists, returns the URL without a language assigned // Fails if no file exists (localized and not localized) - eleventyConfig.addFilter( - options.filters.url, - function (url, langCodeOverride) { - let langCode = - langCodeOverride || - LangUtils.getLanguageCodeFromUrl(this.page?.url) || - options.defaultLanguage; - - // Already has a language code on it and has a relevant url with the target language code - if ( - contentMaps.localeUrlsMap[url] || - (!url.endsWith("/") && contentMaps.localeUrlsMap[`${url}/`]) - ) { - for (let existingUrlObj of contentMaps.localeUrlsMap[url] || - contentMaps.localeUrlsMap[`${url}/`]) { - if (Comparator.urlHasLangCode(existingUrlObj.url, langCode)) { - return existingUrlObj.url; - } + eleventyConfig.addFilter(options.filters.url, function (url, langCodeOverride) { + let langCode = + langCodeOverride || + LangUtils.getLanguageCodeFromUrl(this.page?.url) || + options.defaultLanguage; + + // Already has a language code on it and has a relevant url with the target language code + if ( + contentMaps.localeUrlsMap[url] || + (!url.endsWith("/") && contentMaps.localeUrlsMap[`${url}/`]) + ) { + for (let existingUrlObj of contentMaps.localeUrlsMap[url] || + contentMaps.localeUrlsMap[`${url}/`]) { + if (Comparator.urlHasLangCode(existingUrlObj.url, langCode)) { + return existingUrlObj.url; } } + } - // Needs the language code prepended to the URL - let prependedLangCodeUrl = `/${langCode}${url}`; - if ( - contentMaps.localeUrlsMap[prependedLangCodeUrl] || - (!prependedLangCodeUrl.endsWith("/") && - contentMaps.localeUrlsMap[`${prependedLangCodeUrl}/`]) - ) { - return prependedLangCodeUrl; - } + // Needs the language code prepended to the URL + let prependedLangCodeUrl = `/${langCode}${url}`; + if ( + contentMaps.localeUrlsMap[prependedLangCodeUrl] || + (!prependedLangCodeUrl.endsWith("/") && contentMaps.localeUrlsMap[`${prependedLangCodeUrl}/`]) + ) { + return prependedLangCodeUrl; + } - if ( - contentMaps.urlToInputPath[url] || - (!url.endsWith("/") && contentMaps.urlToInputPath[`${url}/`]) - ) { - // this is not a localized file (independent of a language code) - if (options.errorMode === "strict") { - throw new Error( - `Localized file for URL ${prependedLangCodeUrl} was not found in your project. A non-localized version does exist—are you sure you meant to use the \`${options.filters.url}\` filter for this? You can bypass this error using the \`errorMode\` option in the I18N plugin (current value: "${options.errorMode}").` - ); - } - } else if (options.errorMode === "allow-fallback") { - // You’re linking to a localized file that doesn’t exist! + if ( + contentMaps.urlToInputPath[url] || + (!url.endsWith("/") && contentMaps.urlToInputPath[`${url}/`]) + ) { + // this is not a localized file (independent of a language code) + if (options.errorMode === "strict") { throw new Error( - `Localized file for URL ${prependedLangCodeUrl} was not found in your project! You will need to add it if you want to link to it using the \`${options.filters.url}\` filter. You can bypass this error using the \`errorMode\` option in the I18N plugin (current value: "${options.errorMode}").` + `Localized file for URL ${prependedLangCodeUrl} was not found in your project. A non-localized version does exist—are you sure you meant to use the \`${options.filters.url}\` filter for this? You can bypass this error using the \`errorMode\` option in the I18N plugin (current value: "${options.errorMode}").`, ); } - - return url; + } else if (options.errorMode === "allow-fallback") { + // You’re linking to a localized file that doesn’t exist! + throw new Error( + `Localized file for URL ${prependedLangCodeUrl} was not found in your project! You will need to add it if you want to link to it using the \`${options.filters.url}\` filter. You can bypass this error using the \`errorMode\` option in the I18N plugin (current value: "${options.errorMode}").`, + ); } - ); + + return url; + }); // Refactor to use url // Find the links that are localized alternates to the inputPath argument @@ -331,18 +317,15 @@ function EleventyPlugin(eleventyConfig, opts = {}) { // // note that the permalink/slug may be different for the localized file! url, inputPath, - filePathStem: LangUtils.swapLanguageCode( - page.filePathStem, - languageCode - ), + filePathStem: LangUtils.swapLanguageCode(page.filePathStem, languageCode), // outputPath is omitted here, not necessary for GetCollectionItem.js if url is provided __locale_page_resolved: true, }; return result; - } + }, ); } -module.exports = EleventyPlugin; -module.exports.Comparator = Comparator; -module.exports.LangUtils = LangUtils; +export { Comparator, LangUtils }; + +export default EleventyPlugin; diff --git a/src/Plugins/Pagination.js b/src/Plugins/Pagination.js index da395fc3c..584d36a66 100755 --- a/src/Plugins/Pagination.js +++ b/src/Plugins/Pagination.js @@ -1,10 +1,11 @@ -const { set: lodashSet, get: lodashGet, chunk: lodashChunk } = require("@11ty/lodash-custom"); -const { isPlainObject } = require("@11ty/eleventy-utils"); +import { isPlainObject } from "@11ty/eleventy-utils"; +import lodash from "@11ty/lodash-custom"; -const EleventyBaseError = require("../EleventyBaseError"); -const { DeepCopy } = require("../Util/Merge"); -const { ProxyWrap } = require("../Util/ProxyWrap"); -let serverlessUrlFilter = require("../Filters/ServerlessUrl"); +import EleventyBaseError from "../EleventyBaseError.js"; +import { DeepCopy } from "../Util/Merge.js"; +import { ProxyWrap } from "../Util/ProxyWrap.js"; + +const { set: lodashSet, get: lodashGet, chunk: lodashChunk } = lodash; class PaginationConfigError extends EleventyBaseError {} class PaginationError extends EleventyBaseError {} @@ -78,26 +79,10 @@ class Pagination { this.size = data.pagination.size; this.alias = data.pagination.alias; - // TODO do we need the full data set for serverless? this.fullDataSet = this._get(this.data, this._getDataKey()); // this returns an array this.target = this._resolveItems(); - - // truncate pagination data if user-supplied `serverlessFilter` function - if ( - data.pagination.serverless && - this._has(data, data.pagination.serverless) && - typeof data.pagination.serverlessFilter === "function" - ) { - // Warn: this doesn’t run filter/before/pagination transformations - // Warn: `pagination.pages`, pageNumber, links, hrefs, etc - let serverlessPaginationKey = this._get(data, data.pagination.serverless); - this.chunkedItems = [ - data.pagination.serverlessFilter(this.fullDataSet, serverlessPaginationKey), - ]; - } else { - this.chunkedItems = this.pagedItems; - } + this.chunkedItems = this.pagedItems; } setTemplate(tmpl) { @@ -322,59 +307,8 @@ class Pagination { // template for some things) let indices = new Set(); - let currentPageIndex; - - // Serverless pagination: - if (this._has(this.data, "pagination.serverless")) { - let serverlessPaginationKey; - - if (this.paginationTargetType === "object" && this.shouldResolveDataToObjectValues()) { - serverlessPaginationKey = Object.keys(this.fullDataSet)[0]; - } else { - serverlessPaginationKey = 0; - } - - if (this._has(this.data, this.data.pagination.serverless)) { - serverlessPaginationKey = this._get(this.data, this.data.pagination.serverless); - } - - // Typically this would be a string, not an object. - // But, we’re supporting `serverless: "eleventy.serverless.path"` so that all of - // the path params get passed to serverlessFilter, e.g. `serverlessFilter: function(paginationData, { slug, pagenumber })` - if (isPlainObject(serverlessPaginationKey)) { - indices.add(0); - } else if (this.paginationTargetType === "array") { - currentPageIndex = parseInt(serverlessPaginationKey, 10); - - indices.add(0); // first - if (currentPageIndex > 0) { - indices.add(currentPageIndex - 1); // previous - } - if (currentPageIndex >= 0 && currentPageIndex <= items.length - 1) { - indices.add(currentPageIndex); // current - } - if (currentPageIndex + 1 < items.length) { - indices.add(currentPageIndex + 1); // next - } - indices.add(items.length - 1); // last - } else if (this.paginationTargetType === "object") { - if (this.shouldResolveDataToObjectValues()) { - currentPageIndex = Object.keys(this.fullDataSet).findIndex( - (key) => key === serverlessPaginationKey - ); - } else { - currentPageIndex = items.findIndex((entry) => entry[0] === serverlessPaginationKey); - } - - // Array->findIndex returns -1 when not found - if (currentPageIndex !== -1) { - indices.add(currentPageIndex); // current - } - } - } else { - for (let j = 0; j <= items.length - 1; j++) { - indices.add(j); - } + for (let j = 0; j <= items.length - 1; j++) { + indices.add(j); } for (let pageNumber of indices) { @@ -393,30 +327,7 @@ class Pagination { Object.assign(paginationData.pagination, this.getOverrideDataPages(items, pageNumber)); if (this.alias) { - // When aliasing an object in serverless, use the object value and not the key - if ( - this.paginationTargetType === "object" && - this._has(this.data, this.data.pagination.serverless) - ) { - // This should maybe be the default for all object pagination, not just serverless ones? - let keys = this.getNormalizedItems(items[pageNumber]); - - if (Array.isArray(keys)) { - lodashSet( - paginationData, - this.alias, - key.map((key) => this._get(this.fullDataSet, key)) - ); - } else { - if (this.shouldResolveDataToObjectValues()) { - lodashSet(paginationData, this.alias, keys); - } else { - lodashSet(paginationData, this.alias, this._get(this.fullDataSet, keys)); - } - } - } else { - lodashSet(paginationData, this.alias, this.getNormalizedItems(items[pageNumber])); - } + lodashSet(paginationData, this.alias, this.getNormalizedItems(items[pageNumber])); } // Do *not* deep merge pagination data! See https://github.com/11ty/eleventy/issues/147#issuecomment-440802454 @@ -428,50 +339,6 @@ class Pagination { links.push("/" + rawPath); } - if (this._has(this.data, "pagination.serverless")) { - let keys = this.data.pagination.serverless.split("."); - let key = keys.pop(); - - let serverlessUrls = linkInstance.getServerlessUrls(); - let validUrls = Object.values(serverlessUrls).flat(); - - if (this.data.pagination.serverless !== "eleventy.serverless.path") { - validUrls = validUrls.filter((entry) => entry.includes(`/:${key}/`)); - } - - if (validUrls.length === 0) { - throw new Error( - `Serverless pagination template (${this.data.page.inputPath}) has no \`permalink.${key}\` with \`/:${key}/\`` - ); - } - - let filterData = {}; - - // Serverless URLs like `/blog/tags/:slug/page/:pagenumber/` need both `slug` and `pagenumber` - // so we attempt to resolve the extra data from the pagination chunk. - if (clonedData.eleventy?.serverless?.path) { - Object.assign(filterData, clonedData.eleventy?.serverless?.path); - } - - // get URL path information from data chunk - validUrls.forEach((url) => { - url.split("/").forEach((pathEntry) => { - if (pathEntry.startsWith(":")) { - let urlKey = pathEntry.slice(1); - if ( - items[pageNumber] && - items[pageNumber].length > 0 && - items[pageNumber][0][urlKey] - ) { - filterData[urlKey] = items[pageNumber][0][urlKey]; - } - } - }); - }); - - href = serverlessUrlFilter(validUrls[0], filterData); - } - hrefs.push(href); // page.url and page.outputPath are used to avoid another getOutputLocations call later, see Template->addComputedData @@ -497,11 +364,8 @@ class Pagination { index++; } - // Final output is filtered for serverless - return entries.filter((entry) => { - return !currentPageIndex || entry.pageNumber === currentPageIndex; - }); + return entries; } } -module.exports = Pagination; +export default Pagination; diff --git a/src/Plugins/RenderPlugin.js b/src/Plugins/RenderPlugin.js index 75d527c09..d48a2c51b 100644 --- a/src/Plugins/RenderPlugin.js +++ b/src/Plugins/RenderPlugin.js @@ -1,21 +1,21 @@ -const fs = require("fs"); -const fsp = fs.promises; -const { TemplatePath, isPlainObject } = require("@11ty/eleventy-utils"); +import { promises as fsp, default as fs } from "node:fs"; +import { TemplatePath, isPlainObject } from "@11ty/eleventy-utils"; // TODO add a first-class Markdown component to expose this using Markdown-only syntax (will need to be synchronous for markdown-it) -const Merge = require("../Util/Merge"); -const { ProxyWrap } = require("../Util/ProxyWrap"); -const TemplateDataInitialGlobalData = require("../TemplateDataInitialGlobalData"); -const EleventyShortcodeError = require("../EleventyShortcodeError"); -const TemplateRender = require("../TemplateRender"); -const TemplateConfig = require("../TemplateConfig"); -const EleventyErrorUtil = require("../EleventyErrorUtil"); -const Liquid = require("../Engines/Liquid"); +import Merge from "../Util/Merge.js"; +import { ProxyWrap } from "../Util/ProxyWrap.js"; +import TemplateDataInitialGlobalData from "../TemplateDataInitialGlobalData.js"; +import EleventyShortcodeError from "../EleventyShortcodeError.js"; +import TemplateRender from "../TemplateRender.js"; +import TemplateConfig from "../TemplateConfig.js"; +import EleventyErrorUtil from "../EleventyErrorUtil.js"; +import Liquid from "../Engines/Liquid.js"; async function compile(content, templateLang, { templateConfig, extensionMap } = {}) { if (!templateConfig) { templateConfig = new TemplateConfig(null, false); + await templateConfig.init(); } // Breaking change in 2.0+, previous default was `html` and now we default to the page template syntax @@ -34,10 +34,18 @@ async function compile(content, templateLang, { templateConfig, extensionMap } = let tr = new TemplateRender(templateLang, inputDir, templateConfig); tr.extensionMap = extensionMap; - tr.setEngineOverride(templateLang); + if (templateLang) { + await tr.setEngineOverride(templateLang); + } else { + await tr.init(); + } // TODO tie this to the class, not the extension - if (tr.engine.name === "11ty.js" || tr.engine.name === "11ty.cjs") { + if ( + tr.engine.name === "11ty.js" || + tr.engine.name === "11ty.cjs" || + tr.engine.name === "11ty.mjs" + ) { throw new Error( "11ty.js is not yet supported as a template engine for `renderTemplate`. Use `renderFile` instead!" ); @@ -58,18 +66,26 @@ async function compileFile(inputPath, { templateConfig, extensionMap, config } = ); } + let wasTemplateConfigMissing = false; if (!templateConfig) { templateConfig = new TemplateConfig(null, false); + wasTemplateConfigMissing = true; } if (config && typeof config === "function") { await config(templateConfig.userConfig); } + if (wasTemplateConfigMissing) { + await templateConfig.init(); + } let cfg = templateConfig.getConfig(); let tr = new TemplateRender(inputPath, cfg.dir.input, templateConfig); tr.extensionMap = extensionMap; + if (templateLang) { - tr.setEngineOverride(templateLang); + await tr.setEngineOverride(templateLang); + } else { + await tr.init(); } if (!tr.engine.needsToReadFileContents()) { @@ -344,10 +360,6 @@ function EleventyPlugin(eleventyConfig, options = {}) { } } -module.exports = EleventyPlugin; -module.exports.File = compileFile; -module.exports.String = compile; - // Will re-use the same configuration instance both at a top level and across any nested renders class RenderManager { constructor() { @@ -358,6 +370,18 @@ class RenderManager { templateConfig: this.templateConfig, accessGlobalData: true, }); + + this._hasConfigInitialized = false; + } + + async init() { + if (this._hasConfigInitialized) { + return this._hasConfigInitialized; + } + + this._hasConfigInitialized = this.templateConfig.init(); + await this._hasConfigInitialized; + return true; } // `callback` is async-friendly but requires await upstream @@ -378,12 +402,16 @@ class RenderManager { // because we don’t have access to the full data cascade—but // we still want configuration data added via `addGlobalData` async getData(...data) { + await this.init(); + let globalData = await this.initialGlobalData.getData(); let merged = Merge({}, globalData, ...data); return merged; } - compile(content, templateLang, options = {}) { + async compile(content, templateLang, options = {}) { + await this.init(); + // Missing here: extensionMap options.templateConfig = this.templateConfig; @@ -393,6 +421,8 @@ class RenderManager { } async render(fn, edgeData, buildTimeData) { + await this.init(); + let mergedData = await this.getData(edgeData); // Set .data for options.accessGlobalData feature let context = { @@ -403,4 +433,6 @@ class RenderManager { } } -module.exports.RenderManager = RenderManager; +export default EleventyPlugin; + +export { compileFile as File, compile as String, RenderManager }; diff --git a/src/Plugins/Serverless/NetlifyRedirects.js b/src/Plugins/Serverless/NetlifyRedirects.js deleted file mode 100644 index 15353435b..000000000 --- a/src/Plugins/Serverless/NetlifyRedirects.js +++ /dev/null @@ -1,118 +0,0 @@ -const fs = require("fs"); -const TOML = require("@iarna/toml"); -const debug = require("debug")("Eleventy:Serverless"); - -class NetlifyRedirects { - constructor(name) { - this.name = name; - } - - // keep non-generated redirects or those generated by a different serverless function - filterRedirects(redirects = [], newRedirects = []) { - let newRedirectNameLookup = {}; - for (let entry of newRedirects) { - if (entry._generated_by_eleventy_serverless) { - newRedirectNameLookup[entry._generated_by_eleventy_serverless] = true; - } - } - - return redirects.filter((entry) => { - // keep in place if not eleventy serverless redirect - if (!entry._generated_by_eleventy_serverless) { - return true; - - // keep in place eleventy serverless (but for another plugin) - } else if (entry._generated_by_eleventy_serverless !== this.name) { - return true; - } - - // keep in place if still in use and not stale! - if (newRedirectNameLookup[entry._generated_by_eleventy_serverless]) { - return true; - } - - return false; - }); - } - - getResults(newRedirects, config = {}) { - let redirects = this.filterRedirects(config.redirects, newRedirects); - - // Sort for stable order - newRedirects.sort((a, b) => { - if (a.from < b.from) { - return -1; - } else if (a.from > b.from) { - return 1; - } - return 0; - }); - - for (let r of newRedirects) { - let found = false; - for (let entry of redirects) { - if (r.from === entry.from && r.to === entry.to) { - found = true; - } - } - - if (!found) { - redirects.unshift(r); - } - } - - if (redirects.length) { - config.redirects = redirects; - } else { - delete config.redirects; - } - - return config; - } - - getNewRedirects(outputMap, target) { - if (!target) { - throw new Error( - `Missing redirect target in Eleventy Serverless Bundler Plugin. Received ${target}` - ); - } - - let newRedirects = []; - for (let url in outputMap) { - newRedirects.push({ - from: url, - to: `${target}${this.name}`, - status: 200, - force: true, - _generated_by_eleventy_serverless: this.name, - }); - } - - return newRedirects; - } - - // parse existing netlify.toml - getExistingConfig(filename = "./netlify.toml") { - if (fs.existsSync(filename)) { - return TOML.parse(fs.readFileSync(filename)); - } - - return {}; - } - - writeFile(outputMap, target) { - let newRedirects = this.getNewRedirects(outputMap, target); - - let configFilename = "./netlify.toml"; - let existingCfg = this.getExistingConfig(configFilename); - let results = this.getResults(newRedirects, existingCfg); - - fs.writeFileSync(configFilename, TOML.stringify(results)); - - debug( - `Eleventy Serverless (${this.name}), writing (×${newRedirects.length}): ${configFilename}` - ); - } -} - -module.exports = NetlifyRedirects; diff --git a/src/Plugins/ServerlessBundlerPlugin.js b/src/Plugins/ServerlessBundlerPlugin.js deleted file mode 100644 index d7a3bfff7..000000000 --- a/src/Plugins/ServerlessBundlerPlugin.js +++ /dev/null @@ -1,418 +0,0 @@ -const fs = require("fs"); -const fsp = fs.promises; -const path = require("path"); -const isGlob = require("is-glob"); -const copy = require("recursive-copy"); -const querystring = require("querystring"); -const { TemplatePath } = require("@11ty/eleventy-utils"); - -const NetlifyRedirects = require("./Serverless/NetlifyRedirects"); -const { EleventyRequire } = require("../Util/Require"); -const DirContains = require("../Util/DirContains"); -const JavaScriptDependencies = require("../Util/JavaScriptDependencies"); -const deleteRequireCache = require("../Util/DeleteRequireCache"); -const debug = require("debug")("Eleventy:Serverless"); - -// Provider specific -const redirectHandlers = { - "netlify-toml": function (name, outputMap) { - let r = new NetlifyRedirects(name); - return r.writeFile(outputMap, "/.netlify/functions/"); - }, - "netlify-toml-functions": function (name, outputMap) { - let r = new NetlifyRedirects(name); - return r.writeFile(outputMap, "/.netlify/functions/"); - }, - "netlify-toml-builders": function (name, outputMap) { - let r = new NetlifyRedirects(name); - return r.writeFile(outputMap, "/.netlify/builders/"); - }, -}; - -class BundlerHelper { - constructor(name, options, eleventyConfig) { - this.name = name; - this.options = options; - this.dir = path.join(options.functionsDir, name); - if (path.isAbsolute(this.dir)) { - throw new Error( - "Absolute paths are not yet supported for `functionsDir` in the serverless bundler. Received: " + - options.functionsDir - ); - } - - this.copyCount = 0; - this.eleventyConfig = eleventyConfig; - } - - reset() { - this.copyCount = 0; - } - - getOutputPath(filepath) { - return TemplatePath.addLeadingDotSlash(path.join(this.dir, filepath)); - } - - recursiveCopy(src, dest, options = {}) { - // skip this one if not a glob and doesn’t exist - if (!isGlob(src) && !fs.existsSync(src)) { - return; - } - - let finalDest = this.getOutputPath(dest || src); - debug(`Eleventy Serverless: Copying ${src} to ${finalDest}`); - - return copy( - src, - finalDest, - Object.assign( - { - overwrite: true, - dot: false, - junk: false, - results: false, - }, - this.options.copyOptions, - options - ) - ).on(copy.events.COPY_FILE_COMPLETE, () => { - this.copyCount++; - }); - } - - writeBundlerDependenciesFile(filename, deps = []) { - let fullPath = this.getOutputPath(filename); - if (deps.length === 0 && fs.existsSync(fullPath)) { - return; - } - - let modules = deps.map((name) => `require("${name}");`); - fs.writeFileSync(fullPath, modules.join("\n")); - this.copyCount++; - debug( - `Writing a file to make it very obvious to the serverless bundler which extra \`require\`s are needed from the config file (×${modules.length}): ${fullPath}` - ); - } - - writeDependencyEntryFile() { - // ensure these exist for requiring - if (this.options.copyEnabled) { - this.writeBundlerDependenciesFile("eleventy-app-config-modules.js"); - this.writeBundlerDependenciesFile("eleventy-app-globaldata-modules.js"); - this.writeBundlerDependenciesFile("eleventy-app-dirdata-modules.js"); - } - - // we write these even when copy is disabled because the serverless function expects it - this.writeBundlerDependenciesFile( - "eleventy-bundler-modules.js", - this.options.copyEnabled - ? [ - "./eleventy-app-config-modules.js", - "./eleventy-app-globaldata-modules.js", - "./eleventy-app-dirdata-modules.js", - ] - : [] - ); - } - - async copyFileList(fileList) { - let promises = []; - for (let file of fileList) { - promises.push(this.recursiveCopy(file)); - } - return Promise.all(promises); - } - - // Does *not* copy the original files (only the deps) - async processJavaScriptFiles(files, dependencyFilename) { - if (!this.options.copyEnabled) { - return; - } - - let nodeModules = JavaScriptDependencies.getDependencies(files, true); - this.writeBundlerDependenciesFile( - dependencyFilename, - nodeModules.filter((name) => this.options.excludeDependencies.indexOf(name) === -1) - ); - - let localModules = JavaScriptDependencies.getDependencies(files, false); - // promise - return this.copyFileList(localModules); - } - - // https://github.com/11ty/eleventy/issues/2422 - // This behavior is dictated by AWS Lambda https://aws.amazon.com/blogs/compute/support-for-multi-value-parameters-in-amazon-api-gateway/ - // Duplicate keys are provided as a single comma separated string - getSingleValueQueryParams(searchParams) { - let obj = {}; - for (let [key, value] of searchParams) { - if (!obj[key]) { - obj[key] = value; - } else { - obj[key] += `, ${value}`; - } - } - return obj; - } - - // https://github.com/11ty/eleventy/issues/2422 - // This behavior is dictated by AWS Lambda https://aws.amazon.com/blogs/compute/support-for-multi-value-parameters-in-amazon-api-gateway/ - // Duplicate keys are combined into one array of values - getMultiValueQueryParams(searchParams) { - return querystring.parse(searchParams.toString()); - } - - serverMiddleware() { - let serverlessFilepath = TemplatePath.addLeadingDotSlash( - path.join(TemplatePath.getWorkingDir(), this.dir, "index") - ); - - return async function EleventyServerlessMiddleware(req, res, next) { - deleteRequireCache(serverlessFilepath); - - let serverlessFunction = EleventyRequire(serverlessFilepath); - let url = new URL(req.url, "http://localhost/"); // any domain will do here, we just want the searchParams - - let start = new Date(); - let result = await serverlessFunction.handler({ - httpMethod: "GET", - path: url.pathname, - rawUrl: url.toString(), - - // @netlify/functions builder overwrites these to {} intentionally - // See https://github.com/netlify/functions/issues/38 - queryStringParameters: this.getSingleValueQueryParams(url.searchParams), - multiValueQueryStringParameters: this.getMultiValueQueryParams(url.searchParams), - }); - - if (result.statusCode === 404) { - // return static file - return next(); - } - - res.writeHead(result.statusCode, result.headers || {}); - res.write(result.body); - - this.eleventyConfig.logger.forceLog( - `Serverless (${this.name}): ${req.url} (${Date.now() - start}ms)` - ); - - // eleventy-dev-server 1.0.0-canary.10 and newer - if ("_shouldForceEnd" in res) { - res._shouldForceEnd = true; - next(); - } else { - // eleventy-dev-server 1.0.0-canary.9 and below - res.end(); - } - }.bind(this); - } - - async ensureDir() { - return fsp.mkdir(this.getOutputPath(""), { - recursive: true, - }); - } - - async writeServerlessFunctionFile() { - let filepath = this.getOutputPath("index.js"); - if (!fs.existsSync(filepath)) { - let defaultContentPath = TemplatePath.absolutePath( - __dirname, - "./DefaultServerlessFunctionContent.js" - ); - - let contents = await fsp.readFile(defaultContentPath, "utf8"); - contents = contents.replace(/\%\%NAME\%\%/g, this.name); - contents = contents.replace(/\%\%FUNCTIONS_DIR\%\%/g, this.options.functionsDir); - return fsp.writeFile(filepath, contents); - } - } -} - -function EleventyPlugin(eleventyConfig, options = {}) { - options = Object.assign( - { - name: "", - functionsDir: "./functions/", - copy: [], - - // https://www.npmjs.com/package/recursive-copy#usage - copyOptions: {}, - - // Dependencies explicitly declared from configuration and global data can be excluded and hidden from bundler. - // Excluded from: `eleventy-app-config-modules.js` and `eleventy-app-globaldata-modules.js` - excludeDependencies: [], - - // Add automated redirects (appends or creates, avoids duplicate entries) - // Also accepts a custom callback function(name, outputMap) - redirects: "netlify-toml", - - // Useful for local develop to disable all bundle copying - copyEnabled: true, - }, - options - ); - - if (!options.name) { - throw new Error("Serverless addPlugin second argument options object must have a name."); - } - - if (process.env.ELEVENTY_SOURCE === "cli") { - let helper = new BundlerHelper(options.name, options, eleventyConfig); - - eleventyConfig.setServerOptions({ - middleware: [helper.serverMiddleware()], - }); - - eleventyConfig.on("eleventy.before", async () => { - helper.reset(); - await helper.ensureDir(); - await helper.writeServerlessFunctionFile(); - helper.writeDependencyEntryFile(); - }); - - eleventyConfig.on("eleventy.after", async () => { - if (!options.copyEnabled) { - return; - } - - // extra copy targets - // we put these in after a build so that we can grab files generated _by_ the build too - if (options.copy && Array.isArray(options.copy)) { - let promises = []; - for (let cp of options.copy) { - if (typeof cp === "string") { - promises.push(helper.recursiveCopy(cp)); - } else if (cp.from && cp.to) { - promises.push(helper.recursiveCopy(cp.from, cp.to, cp.options)); - } else { - debug("Ignored extra copy %o (needs to be a string or a {from: '', to: ''})", cp); - } - } - await Promise.all(promises); - } - - eleventyConfig.logger.log( - `Serverless: ${helper.copyCount} file${ - helper.copyCount !== 1 ? "s" : "" - } bundled to ${helper.getOutputPath("")}.` - ); - }); - - eleventyConfig.on("eleventy.env", async (env) => { - await helper.ensureDir(); - - if (!options.copyEnabled) { - return; - } - - await helper.recursiveCopy(env.config, "eleventy.config.js"); - await helper.processJavaScriptFiles([env.config], "eleventy-app-config-modules.js"); - }); - - eleventyConfig.on("eleventy.globalDataFiles", async (fileList) => { - if (!options.copyEnabled) { - return; - } - // Note that originals are copied in `eleventy.directories` event below - await helper.processJavaScriptFiles(fileList, "eleventy-app-globaldata-modules.js"); - }); - - // directory data files only - eleventyConfig.on("eleventy.dataFiles", async (fileList) => { - if (!options.copyEnabled) { - return; - } - - await helper.copyFileList(fileList); - await helper.processJavaScriptFiles(fileList, "eleventy-app-dirdata-modules.js"); - }); - - eleventyConfig.on("eleventy.directories", async (dirs) => { - let promises = []; - if (options.copyEnabled) { - promises.push(helper.recursiveCopy(dirs.input)); - - if (!DirContains(dirs.input, dirs.data)) { - promises.push(helper.recursiveCopy(dirs.data)); - } - if (!DirContains(dirs.input, dirs.includes)) { - promises.push(helper.recursiveCopy(dirs.includes)); - } - if (dirs.layouts && !DirContains(dirs.input, dirs.layouts)) { - // TODO avoid copy if dirs.layouts is in dirs.input - promises.push(helper.recursiveCopy(dirs.layouts)); - } - } - - let filename = helper.getOutputPath("eleventy-serverless.json"); - promises.push( - fsp.writeFile( - filename, - JSON.stringify( - { - dir: dirs, - }, - null, - 2 - ) - ) - ); - debug(`Eleventy Serverless (${options.name}), writing ${filename}`); - this.copyCount++; - - await Promise.all(promises); - }); - - eleventyConfig.on("eleventy.serverlessUrlMap", (templateMap) => { - let outputMap = {}; - - for (let entry of templateMap) { - for (let key in entry.serverless) { - if (key !== options.name) { - continue; - } - let urls = entry.serverless[key]; - if (!Array.isArray(urls)) { - urls = [entry.serverless[key]]; - } - for (let eligibleUrl of urls) { - // ignore duplicates that have the same input file, via Pagination. - if (outputMap[eligibleUrl] === entry.inputPath) { - continue; - } - - // duplicates that don’t use the same input file, throw an error. - if (outputMap[eligibleUrl]) { - throw new Error( - `Serverless URL conflict: multiple input files are using the same URL path (in \`permalink\`): ${outputMap[eligibleUrl]} and ${entry.inputPath}` - ); - } - - outputMap[eligibleUrl] = entry.inputPath; - } - } - } - - // Maps input files to output paths - let mapEntryCount = Object.keys(outputMap).length; - // This is expected to exist even if empty - let filename = helper.getOutputPath("eleventy-serverless-map.json"); - fs.writeFileSync(filename, JSON.stringify(outputMap, null, 2)); - debug(`Eleventy Serverless (${options.name}), writing (×${mapEntryCount}): ${filename}`); - this.copyCount++; - - // Write redirects (even if no redirects exist for this function to handle deletes) - if (options.copyEnabled && options.redirects) { - if (typeof options.redirects === "string" && redirectHandlers[options.redirects]) { - redirectHandlers[options.redirects](options.name, outputMap); - } else if (typeof options.redirects === "function") { - options.redirects(options.name, outputMap); - } - } - }); - } -} - -module.exports = EleventyPlugin; diff --git a/src/Serverless.js b/src/Serverless.js deleted file mode 100644 index f6763f23f..000000000 --- a/src/Serverless.js +++ /dev/null @@ -1,252 +0,0 @@ -const path = require("path"); -const fs = require("fs"); -const { match } = require("path-to-regexp"); -const { TemplatePath } = require("@11ty/eleventy-utils"); - -const Eleventy = require("./Eleventy"); -const normalizeServerlessUrl = require("./Util/NormalizeServerlessUrl"); -const deleteRequireCache = require("./Util/DeleteRequireCache"); -const debug = require("debug")("Eleventy:Serverless"); - -class Serverless { - constructor(name, path, options = {}) { - this.name = name; - - // second argument is path - if (typeof path === "string") { - this.path = path; - } else { - // options is the second argument and path is inside options - options = path; - this.path = options.path; - } - - if (!this.path) { - throw new Error("`path` must exist in the options argument in Eleventy Serverless."); - } - - // ServerlessBundlerPlugin hard-codes to this (even if you used a different file name) - this.configFilename = "eleventy.config.js"; - - // Configuration Information - this.configInfoFilename = "eleventy-serverless.json"; - - // Maps input files to eligible serverless URLs - this.mapFilename = "eleventy-serverless-map.json"; - - this.options = Object.assign( - { - inputDir: null, // override only, we now inject this. - functionsDir: "functions/", - - matchUrlToPattern(path, urlToCompare) { - urlToCompare = normalizeServerlessUrl(urlToCompare); - - let fn = match(urlToCompare, { decode: decodeURIComponent }); - return fn(path); - }, - - // Query String Parameters - query: {}, - - // Configuration callback - config: function (eleventyConfig) {}, - - // Is serverless build scoped to a single template? - // Use `false` to make serverless more collections-friendly (but slower!) - // With `false` you don’t need precompiledCollections. - // Works great with on-demand builders - singleTemplateScope: true, - - // Inject shared collections - precompiledCollections: {}, - }, - options - ); - - this.dir = this.getProjectDir(); - } - - initializeEnvironmentVariables() { - this.serverlessEnvironmentVariableAlreadySet = !!process.env.ELEVENTY_SERVERLESS; - } - - deleteEnvironmentVariables() { - if (!this.serverlessEnvironmentVariableAlreadySet) { - delete process.env.ELEVENTY_SERVERLESS; - } - } - - getProjectDir() { - // TODO? improve with process.env.LAMBDA_TASK_ROOT—was `/var/task/` on lambda (not local) - let dir = path.join(this.options.functionsDir, this.name); - let paths = [ - path.join(TemplatePath.getWorkingDir(), dir), // netlify dev - path.join("/var/task/src/", dir), // AWS Lambda absolute path - path.join(TemplatePath.getWorkingDir()), // after the chdir below - ]; - - for (let path of paths) { - if (fs.existsSync(path)) { - return path; - } - } - - throw new Error(`Couldn’t find the "${dir}" directory. Looked in: ${paths}`); - } - - getContentMap() { - let fullPath = TemplatePath.absolutePath(this.dir, this.mapFilename); - debug(`Including content map (maps output URLs to input files) from ${fullPath}`); - - // TODO dedicated reset method, don’t delete this every time - deleteRequireCache(fullPath); - - return require(fullPath); - } - - getConfigInfo() { - let fullPath = TemplatePath.absolutePath(this.dir, this.configInfoFilename); - debug(`Including config info file from ${fullPath}`); - - // TODO dedicated reset method, don’t delete this every time - deleteRequireCache(fullPath); - - return require(fullPath); - } - - isServerlessUrl(urlPath) { - let contentMap = this.getContentMap(); - - for (let url in contentMap) { - if (this.options.matchUrlToPattern(urlPath, url)) { - return true; - } - } - return false; - } - - matchUrlPattern(urlPath) { - let contentMap = this.getContentMap(); - let matches = []; - - for (let url in contentMap) { - let result = this.options.matchUrlToPattern(urlPath, url); - if (result) { - matches.push({ - compareTo: url, - pathParams: result.params, - inputPath: contentMap[url], - }); - } - } - - if (matches.length) { - if (matches.length > 1) { - console.log( - `Eleventy Serverless conflict: there are multiple serverless paths that match the current URL (${urlPath}): ${JSON.stringify( - matches, - null, - 2 - )}` - ); - } - return matches[0]; - } - - return {}; - } - - async getOutput() { - if (this.dir.startsWith("/var/task/")) { - process.chdir(this.dir); - } - - let inputDir = this.options.input || this.options.inputDir || this.getConfigInfo().dir.input; - let configPath = path.join(this.dir, this.configFilename); - let { pathParams, inputPath } = this.matchUrlPattern(this.path); - - if (!pathParams || !inputPath) { - let err = new Error( - `No matching URL found for ${this.path} in ${JSON.stringify(this.getContentMap())}` - ); - err.httpStatusCode = 404; - throw err; - } - - debug(`Current dir: ${process.cwd()}`); - debug(`Project dir: ${this.dir}`); - debug(`Config path: ${configPath}`); - - debug(`Input dir: ${inputDir}`); - debug(`Requested URL: ${this.path}`); - debug("Path params: %o", pathParams); - debug(`Input path: ${inputPath}`); - - this.initializeEnvironmentVariables(); - - let isScoped = !!this.options.singleTemplateScope; - let projectInput = isScoped ? this.options.input || inputPath : inputDir; - - let elev = new Eleventy(projectInput, null, { - // https://github.com/11ty/eleventy/issues/1957 - isServerless: true, - configPath, - inputDir, - config: (eleventyConfig) => { - if (Object.keys(this.options.precompiledCollections).length > 0) { - eleventyConfig.setPrecompiledCollections(this.options.precompiledCollections); - } - - // Add the params to Global Data - let globalData = { - query: this.options.query, - path: pathParams, - }; - - eleventyConfig.addGlobalData("eleventy.serverless", globalData); - - if (this.options.config && typeof this.options.config === "function") { - this.options.config(eleventyConfig); - } - }, - }); - - if (!isScoped) { - elev.setIncrementalFile(this.options.input || inputPath); - } - - let json = await elev.toJSON(); - - // https://github.com/11ty/eleventy/issues/1957 - this.deleteEnvironmentVariables(); - - let filtered = []; - if (Array.isArray(json)) { - filtered = json.filter((entry) => { - return entry.inputPath === inputPath; - }); - } - - if (!filtered.length) { - let err = new Error( - `Couldn’t find any generated output from Eleventy (Input path: ${inputPath}, URL path parameters: ${JSON.stringify( - pathParams - )}).` - ); - err.httpStatusCode = 404; - throw err; - } - - return filtered; - } - - /* Deprecated, use `getOutput` directly instead. */ - async render() { - let json = await this.getOutput(); - - return json[0].content; - } -} - -module.exports = Serverless; diff --git a/src/Template.js b/src/Template.js index 88473751d..fb986cc55 100755 --- a/src/Template.js +++ b/src/Template.js @@ -1,36 +1,37 @@ -const fs = require("graceful-fs"); -const util = require("util"); +import util from "node:util"; +import os from "node:os"; +import path from "node:path"; + +import fs from "graceful-fs"; +import normalize from "normalize-path"; +import lodash from "@11ty/lodash-custom"; +import { DateTime } from "luxon"; +import { TemplatePath, isPlainObject } from "@11ty/eleventy-utils"; +import debugUtil from "debug"; + +import ConsoleLogger from "./Util/ConsoleLogger.js"; +import getDateFromGitLastUpdated from "./Util/DateGitLastUpdated.js"; +import getDateFromGitFirstAdded from "./Util/DateGitFirstAdded.js"; +import TemplateData from "./TemplateData.js"; +import TemplateContent from "./TemplateContent.js"; +import TemplatePermalink from "./TemplatePermalink.js"; +import TemplateLayout from "./TemplateLayout.js"; +import TemplateFileSlug from "./TemplateFileSlug.js"; +import ComputedData from "./ComputedData.js"; +import Pagination from "./Plugins/Pagination.js"; +import TemplateBehavior from "./TemplateBehavior.js"; +import TemplateContentPrematureUseError from "./Errors/TemplateContentPrematureUseError.js"; +import TemplateContentUnrenderedTemplateError from "./Errors/TemplateContentUnrenderedTemplateError.js"; +import EleventyBaseError from "./EleventyBaseError.js"; + +const { set: lodashSet, get: lodashGet } = lodash; const writeFile = util.promisify(fs.writeFile); const mkdir = util.promisify(fs.mkdir); -const os = require("os"); -const path = require("path"); -const normalize = require("normalize-path"); -const { set: lodashSet, get: lodashGet } = require("@11ty/lodash-custom"); -const { DateTime } = require("luxon"); -const { TemplatePath, isPlainObject } = require("@11ty/eleventy-utils"); - -const ConsoleLogger = require("./Util/ConsoleLogger"); -const getDateFromGitLastUpdated = require("./Util/DateGitLastUpdated"); -const getDateFromGitFirstAdded = require("./Util/DateGitFirstAdded"); - -const TemplateData = require("./TemplateData"); -const TemplateContent = require("./TemplateContent"); -const TemplatePermalink = require("./TemplatePermalink"); -const TemplateLayout = require("./TemplateLayout"); -const TemplateFileSlug = require("./TemplateFileSlug"); -const ComputedData = require("./ComputedData"); -const Pagination = require("./Plugins/Pagination"); -const TemplateBehavior = require("./TemplateBehavior"); - -const TemplateContentPrematureUseError = require("./Errors/TemplateContentPrematureUseError"); -const TemplateContentUnrenderedTemplateError = require("./Errors/TemplateContentUnrenderedTemplateError"); - -const EleventyBaseError = require("./EleventyBaseError"); -class EleventyTransformError extends EleventyBaseError {} +const debug = debugUtil("Eleventy:Template"); +const debugDev = debugUtil("Dev:Eleventy:Template"); -const debug = require("debug")("Eleventy:Template"); -const debugDev = require("debug")("Dev:Eleventy:Template"); +class EleventyTransformError extends EleventyBaseError {} class Template extends TemplateContent { constructor(templatePath, inputDir, outputDir, templateData, extensionMap, config) { @@ -67,8 +68,6 @@ class Template extends TemplateContent { this.behavior = new TemplateBehavior(this.config); this.behavior.setOutputFormat(this.outputFormat); - - this.serverlessUrls = null; } setTemplateData(templateData) { @@ -164,35 +163,11 @@ class Template extends TemplateContent { ); } - getServerlessUrls() { - if (!this.serverlessUrls) { - throw new Error( - "Permalink has not yet processed. Calls to Template->getServerlessUrls not yet allowed." - ); - } - return this.serverlessUrls; - } - - async initServerlessUrlsForEmptyPaginationTemplates(permalinkValue) { - if (isPlainObject(permalinkValue)) { - let buildlessPermalink = Object.assign({}, permalinkValue); - delete buildlessPermalink.build; - - if (Object.keys(buildlessPermalink).length) { - return this._getRawPermalinkInstance(buildlessPermalink); - } - } - } - async _getRawPermalinkInstance(permalinkValue) { let perm = new TemplatePermalink(permalinkValue, this.extraOutputSubdirectory); perm.setUrlTransforms(this.config.urlTransforms); - if (this.templateData) { - perm.setServerlessPathData(await this.templateData.getServerlessPathData()); - } this.behavior.setFromPermalink(perm); - this.serverlessUrls = perm.getServerlessUrls(); return perm; } @@ -677,7 +652,6 @@ class Template extends TemplateContent { } async getTemplates(data) { - // no pagination with permalink.serverless if (!Pagination.hasPagination(data)) { await this.addComputedData(data); @@ -845,11 +819,7 @@ class Template extends TemplateContent { } if (!mapEntry.template.behavior.isRenderable()) { - debug( - "Template not written %o from %o (via serverless permalink).", - page.outputPath, - mapEntry.template.inputPath - ); + debug("Template not written %o from %o.", page.outputPath, mapEntry.template.inputPath); return; } @@ -1008,4 +978,4 @@ class Template extends TemplateContent { } } -module.exports = Template; +export default Template; diff --git a/src/TemplateBehavior.js b/src/TemplateBehavior.js index 242a3ee1d..8c587139c 100644 --- a/src/TemplateBehavior.js +++ b/src/TemplateBehavior.js @@ -1,4 +1,4 @@ -const { isPlainObject } = require("@11ty/eleventy-utils"); +import { isPlainObject } from "@11ty/eleventy-utils"; class TemplateBehavior { constructor(config) { @@ -64,4 +64,4 @@ class TemplateBehavior { this.write = templatePermalink._writeToFileSystem; } } -module.exports = TemplateBehavior; +export default TemplateBehavior; diff --git a/src/TemplateCache.js b/src/TemplateCache.js index 76d492d90..9c17a04cf 100644 --- a/src/TemplateCache.js +++ b/src/TemplateCache.js @@ -1,6 +1,6 @@ -const { TemplatePath } = require("@11ty/eleventy-utils"); +import { TemplatePath } from "@11ty/eleventy-utils"; -const eventBus = require("./EventBus"); +import eventBus from "./EventBus.js"; // Note: this is only used for TemplateLayout right now but could be used for more // Just be careful because right now the TemplateLayout cache keys are not directly mapped to paths @@ -101,4 +101,4 @@ eventBus.on("eleventy.resourceModified", (path, usedBy, metadata = {}) => { }); // singleton -module.exports = layoutCache; +export default layoutCache; diff --git a/src/TemplateCollection.js b/src/TemplateCollection.js index 9e6bad616..331fffaf3 100755 --- a/src/TemplateCollection.js +++ b/src/TemplateCollection.js @@ -1,6 +1,7 @@ -const multimatch = require("multimatch"); -const Sortable = require("./Util/Sortable"); -const { TemplatePath } = require("@11ty/eleventy-utils"); +import multimatch from "multimatch"; +import { TemplatePath } from "@11ty/eleventy-utils"; + +import Sortable from "./Util/Sortable.js"; class TemplateCollection extends Sortable { constructor() { @@ -82,4 +83,4 @@ class TemplateCollection extends Sortable { } } -module.exports = TemplateCollection; +export default TemplateCollection; diff --git a/src/TemplateConfig.js b/src/TemplateConfig.js index 6e7bf0f29..385c96a67 100644 --- a/src/TemplateConfig.js +++ b/src/TemplateConfig.js @@ -1,18 +1,18 @@ -const fs = require("fs"); -const chalk = require("kleur"); -const { TemplatePath } = require("@11ty/eleventy-utils"); - -const EleventyBaseError = require("./EleventyBaseError.js"); -const UserConfig = require("./UserConfig.js"); -const GlobalDependencyMap = require("./GlobalDependencyMap.js"); - -const { EleventyRequire } = require("./Util/Require.js"); -const merge = require("./Util/Merge.js"); -const unique = require("./Util/Unique"); -const eventBus = require("./EventBus.js"); - -const debug = require("debug")("Eleventy:TemplateConfig"); -const debugDev = require("debug")("Dev:Eleventy:TemplateConfig"); +import fs from "node:fs"; +import chalk from "kleur"; +import { TemplatePath } from "@11ty/eleventy-utils"; +import debugUtil from "debug"; + +import { EleventyImport, EleventyImportFromEleventy } from "./Util/Require.js"; +import EleventyBaseError from "./EleventyBaseError.js"; +import UserConfig from "./UserConfig.js"; +import GlobalDependencyMap from "./GlobalDependencyMap.js"; +import merge from "./Util/Merge.js"; +import unique from "./Util/Unique.js"; +import eventBus from "./EventBus.js"; + +const debug = debugUtil("Eleventy:TemplateConfig"); +const debugDev = debugUtil("Dev:Eleventy:TemplateConfig"); /** * @module 11ty/eleventy/TemplateConfig @@ -65,7 +65,12 @@ class TemplateConfig { this.projectConfigPaths = [projectConfigPath]; } } else { - this.projectConfigPaths = [".eleventy.js", "eleventy.config.js", "eleventy.config.cjs"]; + this.projectConfigPaths = [ + ".eleventy.js", + "eleventy.config.js", + "eleventy.config.mjs", + "eleventy.config.cjs", + ]; } if (customRootConfig) { @@ -78,8 +83,8 @@ class TemplateConfig { this.customRootConfig = null; } - this.initializeRootConfig(); this.hasConfigMerged = false; + this.isEsm = false; } /* Setter for Logger */ @@ -117,14 +122,22 @@ class TemplateConfig { this._inputDir = inputDir; } + setProjectUsingEsm(isEsmProject) { + this.isEsm = !!isEsmProject; + } + + getIsProjectUsingEsm() { + return this.isEsm; + } + /** * Resets the configuration. */ - reset() { + async reset() { debugDev("Resetting configuration: TemplateConfig and UserConfig."); this.userConfig.reset(); - this.initializeRootConfig(); - this.forceReloadConfig(); + // await this.initializeRootConfig(); + await this.forceReloadConfig(); this.usesGraph.reset(); // Clear the compile cache @@ -140,12 +153,25 @@ class TemplateConfig { // nothing yet } + /** + * Async-friendly init method + */ + async init(overrides) { + await this.initializeRootConfig(); + if (overrides) { + this.appendToRootConfig(overrides); + } + + this.config = await this.mergeConfig(); + this.hasConfigMerged = true; + } + /** * Force a reload of the configuration object. */ - forceReloadConfig() { + async forceReloadConfig() { this.hasConfigMerged = false; - this.getConfig(); + await this.init(); } /** @@ -155,9 +181,7 @@ class TemplateConfig { */ getConfig() { if (!this.hasConfigMerged) { - debugDev("Merging via getConfig (first time)"); - this.config = this.mergeConfig(); - this.hasConfigMerged = true; + throw new Error("Invalid call to .getConfig(). Needs an .init() first."); } return this.config; } @@ -167,7 +191,7 @@ class TemplateConfig { * * @param {String} path - The new config path. */ - setProjectConfigPath(path) { + async setProjectConfigPath(path) { if (path !== undefined) { this.projectConfigPaths = [path]; } else { @@ -177,7 +201,7 @@ class TemplateConfig { if (this.hasConfigMerged) { // merge it again debugDev("Merging in getConfig again after setting the local project config path."); - this.forceReloadConfig(); + await this.forceReloadConfig(); } } @@ -204,7 +228,7 @@ class TemplateConfig { } if (!this.hasConfigMerged) { - this.getConfig(); + throw new Error("Config has not yet merged. Needs `init()`."); } return this.config.pathPrefix; @@ -213,12 +237,15 @@ class TemplateConfig { /** * Bootstraps the config object. */ - initializeRootConfig() { - this.rootConfig = this.customRootConfig || require("./defaultConfig.js"); + async initializeRootConfig() { + this.rootConfig = + this.customRootConfig || (await EleventyImportFromEleventy("./src/defaultConfig.js")); + if (typeof this.rootConfig === "function") { this.rootConfig = this.rootConfig.call(this, this.userConfig); // debug( "rootConfig is a function, after calling, this.userConfig is %o", this.userConfig ); } + debug("rootConfig %o", this.rootConfig); } @@ -236,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; @@ -251,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); @@ -263,7 +290,7 @@ class TemplateConfig { throw new EleventyPluginError( `Error processing ${name ? `the \`${name}\`` : "a"} plugin${namespaceStr}`, - e + e, ); } } @@ -276,7 +303,7 @@ class TemplateConfig { * * @returns {{}} merged - The merged config file object. */ - requireLocalConfigFile() { + async requireLocalConfigFile() { let localConfig = {}; let path = this.projectConfigPaths.filter((path) => path).find((path) => fs.existsSync(path)); @@ -284,17 +311,11 @@ class TemplateConfig { if (path) { try { - localConfig = EleventyRequire(path); + localConfig = await EleventyImport(path, this.isEsm ? "esm" : "cjs"); // debug( "localConfig require return value: %o", localConfig ); if (typeof localConfig === "function") { - localConfig = localConfig(this.userConfig); + localConfig = await localConfig(this.userConfig); // debug( "localConfig is a function, after calling, this.userConfig is %o", this.userConfig ); - - if (typeof localConfig === "object" && typeof localConfig.then === "function") { - throw new EleventyConfigError( - `Error in your Eleventy config file '${path}': Returning a promise is not yet supported.` - ); - } } // Still using removed `filters`? this was renamed to transforms @@ -304,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) { @@ -314,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 { @@ -330,8 +351,8 @@ class TemplateConfig { * @param {String} projectConfigPath - Path to project config. * @returns {{}} merged - The merged config file. */ - mergeConfig() { - let localConfig = this.requireLocalConfigFile(); + async mergeConfig() { + let localConfig = await this.requireLocalConfigFile(); // Template Formats: // 1. Root Config (usually defaultConfig.js) @@ -364,7 +385,7 @@ class TemplateConfig { // Temporarily restore templateFormats mergedConfig.templateFormats = templateFormats; - this.processPlugins(mergedConfig); + await this.processPlugins(mergedConfig); delete mergedConfig.templateFormats; @@ -421,4 +442,4 @@ class TemplateConfig { } } -module.exports = TemplateConfig; +export default TemplateConfig; diff --git a/src/TemplateContent.js b/src/TemplateContent.js index 65871a4f4..377c0c1c2 100644 --- a/src/TemplateContent.js +++ b/src/TemplateContent.js @@ -1,20 +1,24 @@ -const os = require("os"); -const fs = require("graceful-fs"); -const util = require("util"); +import os from "node:os"; +import util from "node:util"; + +import fs from "graceful-fs"; +import normalize from "normalize-path"; +import matter from "gray-matter"; +import lodash from "@11ty/lodash-custom"; +import { TemplatePath } from "@11ty/eleventy-utils"; +import debugUtil from "debug"; + +import EleventyExtensionMap from "./EleventyExtensionMap.js"; +import TemplateData from "./TemplateData.js"; +import TemplateRender from "./TemplateRender.js"; +import EleventyBaseError from "./EleventyBaseError.js"; +import EleventyErrorUtil from "./EleventyErrorUtil.js"; +import eventBus from "./EventBus.js"; + +const { set: lodashSet } = lodash; const readFile = util.promisify(fs.readFile); -const normalize = require("normalize-path"); -const matter = require("gray-matter"); -const { set: lodashSet } = require("@11ty/lodash-custom"); -const { TemplatePath } = require("@11ty/eleventy-utils"); - -const EleventyExtensionMap = require("./EleventyExtensionMap"); -const TemplateData = require("./TemplateData"); -const TemplateRender = require("./TemplateRender"); -const EleventyBaseError = require("./EleventyBaseError"); -const EleventyErrorUtil = require("./EleventyErrorUtil"); -const debug = require("debug")("Eleventy:TemplateContent"); -const debugDev = require("debug")("Dev:Eleventy:TemplateContent"); -const eventBus = require("./EventBus"); +const debug = debugUtil("Eleventy:TemplateContent"); +const debugDev = debugUtil("Dev:Eleventy:TemplateContent"); class TemplateContentConfigError extends EleventyBaseError {} class TemplateContentFrontMatterError extends EleventyBaseError {} @@ -114,9 +118,17 @@ class TemplateContent { } get templateRender() { + if (!this._templateRender) { + throw new Error("TemplateRender has not yet initialized."); + } + return this._templateRender; + } + + async getTemplateRender() { if (!this._templateRender) { this._templateRender = new TemplateRender(this.inputPath, this.inputDir, this.eleventyConfig); this._templateRender.extensionMap = this.extensionMap; + await this._templateRender.init(); } return this._templateRender; @@ -232,7 +244,8 @@ class TemplateContent { } async getInputContent() { - if (!this.engine.needsToReadFileContents()) { + let tr = await this.getTemplateRender(); + if (!tr.engine.needsToReadFileContents()) { return ""; } @@ -295,16 +308,6 @@ class TemplateContent { return frontMatterData[this.config.keys.engineOverride]; } - async setupTemplateRender(engineOverride, bypassMarkdown) { - if (engineOverride !== undefined) { - debugDev("%o overriding template engine to use %o", this.inputPath, engineOverride); - - this.templateRender.setEngineOverride(engineOverride, bypassMarkdown); - } else { - this.templateRender.setUseMarkdown(!bypassMarkdown); - } - } - _getCompileCache(str) { // Caches used to be bifurcated based on engine name, now they’re based on inputPath let inputPathMap = TemplateContent._compileCache.get(this.inputPath); @@ -315,11 +318,24 @@ class TemplateContent { let cacheable = this.engine.cacheable; let { useCache, key } = this.engine.getCompileCacheKey(str, this.inputPath); + + // We also tie the compile cache key to the UserConfig instance, to alleviate issues with global template cache + // Better to move the cache to the Eleventy instance instead, no? + // (This specifically failed I18nPluginTest cases with filters being cached across tests and not having access to each plugin’s options) + key = this.eleventyConfig.userConfig._getUniqueId() + key; + return [cacheable, key, inputPathMap, useCache]; } async compile(str, bypassMarkdown, engineOverride) { - await this.setupTemplateRender(engineOverride, bypassMarkdown); + let tr = await this.getTemplateRender(); + + if (engineOverride !== undefined) { + debugDev("%o overriding template engine to use %o", this.inputPath, engineOverride); + await tr.setEngineOverride(engineOverride, bypassMarkdown); + } else { + tr.setUseMarkdown(!bypassMarkdown); + } if (bypassMarkdown && !this.engine.needsCompilation(str)) { return async function () { @@ -327,7 +343,7 @@ class TemplateContent { }; } - debugDev("%o compile() using engine: %o", this.inputPath, this.templateRender.engineName); + debugDev("%o compile() using engine: %o", this.inputPath, tr.engineName); try { let res; @@ -358,7 +374,7 @@ class TemplateContent { let inputPathBenchmark = this.bench.get(`> Compile > ${this.inputPath}`); templateBenchmark.before(); inputPathBenchmark.before(); - let fn = await this.templateRender.getCompiledTemplate(str); + let fn = await tr.getCompiledTemplate(str); inputPathBenchmark.after(); templateBenchmark.after(); debugDev("%o getCompiledTemplate function created", this.inputPath); @@ -383,7 +399,8 @@ class TemplateContent { let engine = this.engine; // Don’t use markdown as the engine to parse for symbols - let preprocessorEngine = this.templateRender.getPreprocessorEngine(); // TODO pass in engineOverride here + // TODO pass in engineOverride here + let preprocessorEngine = this.templateRender.getPreprocessorEngine(); if (preprocessorEngine && engine.getName() !== preprocessorEngine) { let replacementEngine = this.templateRender.getEngineByName(preprocessorEngine); if (replacementEngine) { @@ -525,7 +542,8 @@ class TemplateContent { if (EleventyErrorUtil.isPrematureTemplateContentError(e)) { throw e; } else { - let engine = this.templateRender.getReadableEnginesList(); + let tr = await this.getTemplateRender(); + let engine = tr.getReadableEnginesList(); debug(`Having trouble rendering ${engine} template ${this.inputPath}: %O`, str); throw new TemplateContentRenderError( `Having trouble rendering ${engine} template ${this.inputPath}`, @@ -614,4 +632,4 @@ eventBus.on("eleventy.compileCacheReset", (path) => { TemplateContent._compileCache = new Map(); }); -module.exports = TemplateContent; +export default TemplateContent; diff --git a/src/TemplateData.js b/src/TemplateData.js index 8bc649427..39429c5f0 100644 --- a/src/TemplateData.js +++ b/src/TemplateData.js @@ -1,19 +1,22 @@ -const fs = require("fs"); -const path = require("path"); -const { set: lodashset, get: lodashget } = require("@11ty/lodash-custom"); -const { TemplatePath, isPlainObject } = require("@11ty/eleventy-utils"); - -const merge = require("./Util/Merge"); -const unique = require("./Util/Unique"); -const TemplateGlob = require("./TemplateGlob"); -const EleventyExtensionMap = require("./EleventyExtensionMap"); -const EleventyBaseError = require("./EleventyBaseError"); -const TemplateDataInitialGlobalData = require("./TemplateDataInitialGlobalData"); -const { EleventyRequire } = require("./Util/Require"); - -const debugWarn = require("debug")("Eleventy:Warnings"); -const debug = require("debug")("Eleventy:TemplateData"); -const debugDev = require("debug")("Dev:Eleventy:TemplateData"); +import fs from "node:fs"; +import path from "node:path"; + +import lodash from "@11ty/lodash-custom"; +import { TemplatePath, isPlainObject } from "@11ty/eleventy-utils"; +import debugUtil from "debug"; + +import merge from "./Util/Merge.js"; +import unique from "./Util/Unique.js"; +import TemplateGlob from "./TemplateGlob.js"; +import EleventyExtensionMap from "./EleventyExtensionMap.js"; +import EleventyBaseError from "./EleventyBaseError.js"; +import TemplateDataInitialGlobalData from "./TemplateDataInitialGlobalData.js"; +import { EleventyImport, EleventyLoadContent } from "./Util/Require.js"; + +const { set: lodashSet, get: lodashGet } = lodash; +const debugWarn = debugUtil("Eleventy:Warnings"); +const debug = debugUtil("Eleventy:TemplateData"); +const debugDev = debugUtil("Dev:Eleventy:TemplateData"); class FSExistsCache { constructor() { @@ -56,6 +59,7 @@ class TemplateData { this.rawImports = {}; this.globalData = null; this.templateDirectoryData = {}; + this.isEsm = false; // It's common for data files not to exist, so we avoid going to the FS to // re-check if they do via a quick-and-dirty cache. @@ -72,6 +76,10 @@ class TemplateData { this.directories = dirsObject; } + setProjectUsingEsm(isEsmProject) { + this.isEsm = !!isEsmProject; + } + get extensionMap() { if (!this._extensionMap) { this._extensionMap = new EleventyExtensionMap([], this.eleventyConfig); @@ -104,12 +112,11 @@ class TemplateData { : inputDir; } - getRawImports() { - let pkgPath = TemplatePath.absolutePath("package.json"); - + async getRawImports() { try { - this.rawImports[this.config.keys.package] = require(pkgPath); + this.rawImports[this.config.keys.package] = await EleventyImport("package.json", "json"); } catch (e) { + let pkgPath = TemplatePath.absolutePath("package.json"); debug("Could not find and/or require package.json for data preprocessing at %o", pkgPath); } @@ -188,10 +195,12 @@ class TemplateData { if (suffix && typeof suffix === "string") { if (suffix.startsWith(".")) { // .suffix.js + globSuffixesWithLeadingDot.add(`${suffix.slice(1)}.mjs`); globSuffixesWithLeadingDot.add(`${suffix.slice(1)}.cjs`); globSuffixesWithLeadingDot.add(`${suffix.slice(1)}.js`); } else { // "suffix.js" without leading dot + globSuffixesWithoutLeadingDot.add(`${suffix || ""}.mjs`); globSuffixesWithoutLeadingDot.add(`${suffix || ""}.cjs`); globSuffixesWithoutLeadingDot.add(`${suffix || ""}.js`); } @@ -247,7 +256,7 @@ class TemplateData { } getGlobalDataExtensionPriorities() { - return this.getUserDataExtensions().concat(["json", "cjs", "js"]); + return this.getUserDataExtensions().concat(["json", "mjs", "cjs", "js"]); } static calculateExtensionPriority(path, priorities) { @@ -298,7 +307,6 @@ class TemplateData { } async getAllGlobalData() { - let rawImports = this.getRawImports(); let globalData = {}; let files = TemplatePath.addLeadingDotSlashArray(await this.getGlobalDataFiles()); @@ -307,7 +315,7 @@ class TemplateData { let dataFileConflicts = {}; for (let j = 0, k = files.length; j < k; j++) { - let data = await this.getDataValue(files[j], rawImports); + let data = await this.getDataValue(files[j]); let objectPathTarget = this.getObjectPathForDataFile(files[j]); // Since we're joining directory paths and an array is not usable as an objectkey since two identical arrays are not double equal, @@ -323,13 +331,13 @@ class TemplateData { `merging global data from ${files[j]} with an already existing global data file (${dataFileConflicts[objectPathTargetString]}). Overriding existing keys.` ); - let oldData = lodashget(globalData, objectPathTarget); + let oldData = lodashGet(globalData, objectPathTarget); data = TemplateData.mergeDeep(this.config, oldData, data); } dataFileConflicts[objectPathTargetString] = files[j]; debug(`Found global data file ${files[j]} and adding as: ${objectPathTarget}`); - lodashset(globalData, objectPathTarget, data); + lodashSet(globalData, objectPathTarget, data); } return globalData; @@ -362,7 +370,7 @@ class TemplateData { } async getGlobalData() { - let rawImports = this.getRawImports(); + let rawImports = await this.getRawImports(); if (!this.globalData) { this.globalData = new Promise(async (resolve) => { @@ -399,7 +407,7 @@ class TemplateData { let dataSource = {}; for (let path of localDataPaths) { - let dataForPath = await this.getDataValue(path, null, true); + let dataForPath = await this.getDataValue(path); if (!isPlainObject(dataForPath)) { debug( "Warning: Template and Directory data files expect an object to be returned, instead `%o` returned `%o`", @@ -458,33 +466,12 @@ class TemplateData { return this.config.dataExtensions && this.config.dataExtensions.size > 0; } - async _loadFileContents(path, options = {}) { - let rawInput; - let encoding = "utf8"; - if ("encoding" in options) { - encoding = options.encoding; - } - - try { - rawInput = await fs.promises.readFile(path, encoding); - } catch (e) { - // if file does not exist, return nothing - } - - // Can return a buffer, string, etc - if (typeof rawInput === "string") { - return rawInput.trim(); - } - - return rawInput; - } - - async _parseDataFile(path, rawImports, ignoreProcessing, parser, options = {}) { + async _parseDataFile(path, parser, options = {}) { let readFile = !("read" in options) || options.read === true; let rawInput; if (readFile) { - rawInput = await this._loadFileContents(path, options); + rawInput = await EleventyLoadContent(path, options); } if (readFile && !rawInput) { @@ -506,10 +493,10 @@ class TemplateData { // ignoreProcessing = false for global data files // ignoreProcessing = true for local data files - async getDataValue(path, rawImports, ignoreProcessing) { + async getDataValue(path) { let extension = TemplatePath.getExtension(path); - if (extension === "js" || extension === "cjs") { + if (extension === "js" || extension === "cjs" || extension === "mjs") { // JS data file or require’d JSON (no preprocessing needed) let localPath = TemplatePath.absolutePath(path); let exists = this._fsExistsCache.exists(localPath); @@ -525,7 +512,14 @@ class TemplateData { let dataBench = this.benchmarks.data.get(`\`${path}\``); dataBench.before(); - let returnValue = EleventyRequire(localPath); + let type = "cjs"; + if (extension === "mjs" || (extension === "js" && this.isEsm)) { + type = "esm"; + } + + // We always need to use `import()`, as `require` isn’t available in ESM. + let returnValue = await EleventyImport(localPath, type); + // TODO special exception for Global data `permalink.js` // module.exports = (data) => `${data.page.filePathStem}/`; // Does not work // module.exports = () => ((data) => `${data.page.filePathStem}/`); // Works @@ -541,11 +535,11 @@ class TemplateData { // Other extensions let { parser, options } = this.getUserDataParser(extension); - return this._parseDataFile(path, rawImports, ignoreProcessing, parser, options); + return this._parseDataFile(path, parser, options); } else if (extension === "json") { // File to string, parse with JSON (preprocess) const parser = (content) => JSON.parse(content); - return this._parseDataFile(path, rawImports, ignoreProcessing, parser); + return this._parseDataFile(path, parser); } else { throw new TemplateDataParseError( `Could not find an appropriate data parser for ${path}. Do you need to add a plugin to your config file?` @@ -573,6 +567,7 @@ class TemplateData { if (suffix) { paths.push(base + suffix + ".js"); paths.push(base + suffix + ".cjs"); + paths.push(base + suffix + ".mjs"); } paths.push(base + suffix + ".json"); // default: .11tydata.json @@ -672,11 +667,6 @@ class TemplateData { return data; } - - async getServerlessPathData() { - let configApiGlobalData = await this.getInitialGlobalData(); - return configApiGlobalData?.eleventy?.serverless?.path; - } } -module.exports = TemplateData; +export default TemplateData; diff --git a/src/TemplateDataInitialGlobalData.js b/src/TemplateDataInitialGlobalData.js index 2ad04469e..0e940da27 100644 --- a/src/TemplateDataInitialGlobalData.js +++ b/src/TemplateDataInitialGlobalData.js @@ -1,6 +1,10 @@ -const pkg = require("../package.json"); -const semver = require("semver"); -const { set: lodashset } = require("@11ty/lodash-custom"); +import semver from "semver"; +import lodash from "@11ty/lodash-custom"; + +import { getEleventyPackageJson } from "./Util/ImportJsonSync.js"; + +const { set: lodashSet } = lodash; +const pkg = getEleventyPackageJson(); class TemplateDataInitialGlobalData { constructor(templateConfig) { @@ -24,7 +28,7 @@ class TemplateDataInitialGlobalData { returnValue = await returnValue(); } - lodashset(globalData, key, returnValue); + lodashSet(globalData, key, returnValue); } } @@ -39,4 +43,4 @@ class TemplateDataInitialGlobalData { } } -module.exports = TemplateDataInitialGlobalData; +export default TemplateDataInitialGlobalData; diff --git a/src/TemplateEngineManager.js b/src/TemplateEngineManager.js index c44ffa354..951ef5073 100644 --- a/src/TemplateEngineManager.js +++ b/src/TemplateEngineManager.js @@ -1,4 +1,6 @@ -const EleventyBaseError = require("./EleventyBaseError"); +import EleventyBaseError from "./EleventyBaseError.js"; +import { EleventyImportFromEleventy } from "./Util/Require.js"; + class TemplateEngineManagerConfigError extends EleventyBaseError {} class TemplateEngineManager { @@ -28,13 +30,8 @@ class TemplateEngineManager { get keyToClassNameMap() { if (!this._keyToClassNameMap) { this._keyToClassNameMap = { - ejs: "Ejs", md: "Markdown", html: "Html", - hbs: "Handlebars", - mustache: "Mustache", - haml: "Haml", - pug: "Pug", njk: "Nunjucks", liquid: "Liquid", "11ty.js": "JavaScript", @@ -77,34 +74,31 @@ class TemplateEngineManager { return !!this.getClassNameFromTemplateKey(name); } - getEngineClassByExtension(extension) { - // We include these as raw strings (and not more readable variables) so they’re parsed by the serverless bundler. - if (extension === "ejs") { - return require("./Engines/Ejs"); - } else if (extension === "md") { - return require("./Engines/Markdown"); + async getEngineClassByExtension(extension) { + // We include these as raw strings (and not more readable variables) so they’re parsed by a bundler. + if (extension === "md") { + return EleventyImportFromEleventy("./src/Engines/Markdown.js"); } else if (extension === "html") { - return require("./Engines/Html"); - } else if (extension === "hbs") { - return require("./Engines/Handlebars"); - } else if (extension === "mustache") { - return require("./Engines/Mustache"); - } else if (extension === "haml") { - return require("./Engines/Haml"); - } else if (extension === "pug") { - return require("./Engines/Pug"); + return EleventyImportFromEleventy("./src/Engines/Html.js"); } else if (extension === "njk") { - return require("./Engines/Nunjucks"); + return EleventyImportFromEleventy("./src/Engines/Nunjucks.js"); } else if (extension === "liquid") { - return require("./Engines/Liquid"); + return EleventyImportFromEleventy("./src/Engines/Liquid.js"); } else if (extension === "11ty.js") { - return require("./Engines/JavaScript"); + return EleventyImportFromEleventy("./src/Engines/JavaScript.js"); } else { - return require("./Engines/Custom"); + return this.getCustomEngineClass(); } } - getEngine(name, dirs, extensionMap) { + async getCustomEngineClass() { + if (!this._CustomEngine) { + this._CustomEngine = await EleventyImportFromEleventy("./src/Engines/Custom.js"); + } + return this._CustomEngine; + } + + async getEngine(name, dirs, extensionMap) { if (!this.hasEngine(name)) { throw new Error(`Template Engine ${name} does not exist in getEngine (dirs: ${dirs})`); } @@ -115,8 +109,7 @@ class TemplateEngineManager { return this.engineCache[name]; } - let cls = this.getEngineClassByExtension(name); - + let cls = await this.getEngineClassByExtension(name); let instance = new cls(name, dirs, this.eleventyConfig); instance.extensionMap = extensionMap; instance.engineManager = this; @@ -129,7 +122,7 @@ class TemplateEngineManager { this.getClassNameFromTemplateKey(name) === "Custom" && instance.constructor.name !== "CustomEngine" ) { - const CustomEngine = this.getEngineClassByExtension(); + const CustomEngine = await this.getCustomEngineClass(); const overrideCustomEngine = new CustomEngine(name, dirs, this.eleventyConfig); // Keep track of the "default" engine 11ty would normally use // This allows the user to access the default engine in their override @@ -144,4 +137,4 @@ class TemplateEngineManager { } } -module.exports = TemplateEngineManager; +export default TemplateEngineManager; diff --git a/src/TemplateFileSlug.js b/src/TemplateFileSlug.js index db45fa687..6bc0d4cc7 100644 --- a/src/TemplateFileSlug.js +++ b/src/TemplateFileSlug.js @@ -1,5 +1,5 @@ -const path = require("path"); -const { TemplatePath } = require("@11ty/eleventy-utils"); +import path from "node:path"; +import { TemplatePath } from "@11ty/eleventy-utils"; class TemplateFileSlug { constructor(inputPath, inputDir, extensionMap) { @@ -53,4 +53,4 @@ class TemplateFileSlug { } } -module.exports = TemplateFileSlug; +export default TemplateFileSlug; diff --git a/src/TemplateGlob.js b/src/TemplateGlob.js index 3674ca895..988cf89f9 100644 --- a/src/TemplateGlob.js +++ b/src/TemplateGlob.js @@ -1,12 +1,10 @@ -const { TemplatePath } = require("@11ty/eleventy-utils"); +import { TemplatePath } from "@11ty/eleventy-utils"; class TemplateGlob { static normalizePath(...paths) { if (paths[0].charAt(0) === "!") { throw new Error( - `TemplateGlob.normalizePath does not accept ! glob paths like: ${paths.join( - "" - )}` + `TemplateGlob.normalizePath does not accept ! glob paths like: ${paths.join("")}` ); } return TemplatePath.addLeadingDotSlash(TemplatePath.join(...paths)); @@ -34,4 +32,4 @@ class TemplateGlob { } } -module.exports = TemplateGlob; +export default TemplateGlob; diff --git a/src/TemplateLayout.js b/src/TemplateLayout.js index 54c7bc667..f23073f85 100644 --- a/src/TemplateLayout.js +++ b/src/TemplateLayout.js @@ -1,12 +1,13 @@ -const { TemplatePath } = require("@11ty/eleventy-utils"); +import { TemplatePath } from "@11ty/eleventy-utils"; +import debugUtil from "debug"; -const TemplateLayoutPathResolver = require("./TemplateLayoutPathResolver"); -const TemplateContent = require("./TemplateContent"); -const TemplateData = require("./TemplateData"); +import TemplateLayoutPathResolver from "./TemplateLayoutPathResolver.js"; +import TemplateContent from "./TemplateContent.js"; +import TemplateData from "./TemplateData.js"; +import templateCache from "./TemplateCache.js"; -const templateCache = require("./TemplateCache"); -// const debug = require("debug")("Eleventy:TemplateLayout"); -const debugDev = require("debug")("Dev:Eleventy:TemplateLayout"); +// const debug = debugUtil("Eleventy:TemplateLayout"); +const debugDev = debugUtil("Dev:Eleventy:TemplateLayout"); class TemplateLayout extends TemplateContent { constructor(key, inputDir, extensionMap, eleventyConfig) { @@ -250,4 +251,4 @@ class TemplateLayout extends TemplateContent { } } -module.exports = TemplateLayout; +export default TemplateLayout; diff --git a/src/TemplateLayoutPathResolver.js b/src/TemplateLayoutPathResolver.js index ef0399175..f25ca00aa 100644 --- a/src/TemplateLayoutPathResolver.js +++ b/src/TemplateLayoutPathResolver.js @@ -1,7 +1,7 @@ -const fs = require("fs"); -const { TemplatePath } = require("@11ty/eleventy-utils"); - -// const debug = require("debug")("Eleventy:TemplateLayoutPathResolver"); +import fs from "node:fs"; +import { TemplatePath } from "@11ty/eleventy-utils"; +// import debugUtil from "debug"; +// const debug = debugUtil("Eleventy:TemplateLayoutPathResolver"); class TemplateLayoutPathResolver { constructor(path, inputDir, extensionMap, eleventyConfig) { @@ -134,4 +134,4 @@ class TemplateLayoutPathResolver { } } -module.exports = TemplateLayoutPathResolver; +export default TemplateLayoutPathResolver; diff --git a/src/TemplateMap.js b/src/TemplateMap.js index 512fab66f..f75bdfe1d 100644 --- a/src/TemplateMap.js +++ b/src/TemplateMap.js @@ -1,14 +1,14 @@ -const DependencyGraph = require("dependency-graph").DepGraph; -const { isPlainObject } = require("@11ty/eleventy-utils"); +import { DepGraph as DependencyGraph } from "dependency-graph"; +import { isPlainObject } from "@11ty/eleventy-utils"; +import debugUtil from "debug"; -const TemplateCollection = require("./TemplateCollection"); -const EleventyErrorUtil = require("./EleventyErrorUtil"); +import TemplateCollection from "./TemplateCollection.js"; +import EleventyErrorUtil from "./EleventyErrorUtil.js"; +import UsingCircularTemplateContentReferenceError from "./Errors/UsingCircularTemplateContentReferenceError.js"; +import EleventyBaseError from "./EleventyBaseError.js"; -const UsingCircularTemplateContentReferenceError = require("./Errors/UsingCircularTemplateContentReferenceError"); -const EleventyBaseError = require("./EleventyBaseError"); - -const debug = require("debug")("Eleventy:TemplateMap"); -const debugDev = require("debug")("Dev:Eleventy:TemplateMap"); +const debug = debugUtil("Eleventy:TemplateMap"); +const debugDev = debugUtil("Dev:Eleventy:TemplateMap"); class TemplateMapConfigError extends EleventyBaseError {} @@ -27,7 +27,6 @@ class TemplateMap { this.map = []; this.collectionsData = null; this.cached = false; - this.configCollections = null; this.verboseOutput = true; this.collection = new TemplateCollection(); } @@ -414,12 +413,7 @@ class TemplateMap { map._pages = await map.template.getTemplates(map.data); if (map._pages.length === 0) { - // Setup serverlessUrls even if data set is 0 pages. This fixes 404 issue - // with full build not including Sanity drafts but serverless render does - // include Sanity drafts. - - // We want these empty-data pagination templates to show up in the serverlessUrlMap. - await map.template.initServerlessUrlsForEmptyPaginationTemplates(map.data.permalink); + // removed serverless code path } else { let counter = 0; for (let page of map._pages) { @@ -488,10 +482,6 @@ class TemplateMap { this.checkForDuplicatePermalinks(); await this.config.events.emitLazy("eleventy.layouts", () => this.generateLayoutsMap()); - - await this.config.events.emitLazy("eleventy.serverlessUrlMap", () => - this.generateServerlessUrlMap(orderedMap) - ); } generateInputUrlContentMap(orderedMap) { @@ -513,40 +503,6 @@ class TemplateMap { return entries; } - generateServerlessUrlMap(orderedMap) { - let entries = []; - for (let entry of orderedMap) { - // Pagination templates with 0 pages should still populate - // serverlessUrls into this event. We want these to still show up - // in the inputPath to URL map and in the redirects. - if (entry._pages.length === 0) { - let serverless = {}; - if (isPlainObject(entry.data.permalink)) { - // These are rendered in the template language! - Object.assign(serverless, entry.template.getServerlessUrls()); - entries.push({ - inputPath: entry.inputPath, - serverless, - }); - } - } else { - for (let page of entry._pages) { - let serverless = {}; - if (isPlainObject(page.data.permalink)) { - // These are rendered in the template language! - Object.assign(serverless, page.template.getServerlessUrls()); - - entries.push({ - inputPath: entry.inputPath, - serverless, - }); - } - } - } - } - return entries; - } - // TODO(slightlyoff): hot inner loop? getMapEntryForInputPath(inputPath) { for (let map of this.map) { @@ -654,21 +610,18 @@ class TemplateMap { return collections; } - setUserConfigCollections(configCollections) { - return (this.configCollections = configCollections); - } - + /* 3.0.0-alpha.1: setUserConfigCollections method removed (was only used for testing) */ isUserConfigCollectionName(name) { - let collections = this.configCollections || this.userConfig.getCollections(); + let collections = this.userConfig.getCollections(); return name && !!collections[name]; } getUserConfigCollectionNames() { - return Object.keys(this.configCollections || this.userConfig.getCollections()); + return Object.keys(this.userConfig.getCollections()); } async getUserConfigCollection(name) { - let configCollections = this.configCollections || this.userConfig.getCollections(); + let configCollections = this.userConfig.getCollections(); // This works with async now let result = await configCollections[name](this.collection); @@ -679,7 +632,7 @@ class TemplateMap { async _testGetUserConfigCollectionsData() { let collections = {}; - let configCollections = this.configCollections || this.userConfig.getCollections(); + let configCollections = this.userConfig.getCollections(); for (let name in configCollections) { collections[name] = configCollections[name](this.collection); @@ -813,4 +766,4 @@ ${permalinks[page.outputPath] } } -module.exports = TemplateMap; +export default TemplateMap; diff --git a/src/TemplatePassthrough.js b/src/TemplatePassthrough.js index 846eaf84c..54ba65b93 100644 --- a/src/TemplatePassthrough.js +++ b/src/TemplatePassthrough.js @@ -1,13 +1,15 @@ -const fs = require("fs"); -const path = require("path"); -const isGlob = require("is-glob"); -const copy = require("recursive-copy"); -const { TemplatePath } = require("@11ty/eleventy-utils"); +import fs from "node:fs"; +import path from "node:path"; -const EleventyBaseError = require("./EleventyBaseError"); -const checkPassthroughCopyBehavior = require("./Util/PassthroughCopyBehaviorCheck"); +import isGlob from "is-glob"; +import copy from "recursive-copy"; +import { TemplatePath } from "@11ty/eleventy-utils"; +import debugUtil from "debug"; -const debug = require("debug")("Eleventy:TemplatePassthrough"); +import EleventyBaseError from "./EleventyBaseError.js"; +import checkPassthroughCopyBehavior from "./Util/PassthroughCopyBehaviorCheck.js"; + +const debug = debugUtil("Eleventy:TemplatePassthrough"); class TemplatePassthroughError extends EleventyBaseError {} @@ -258,4 +260,4 @@ class TemplatePassthrough { } } -module.exports = TemplatePassthrough; +export default TemplatePassthrough; diff --git a/src/TemplatePassthroughManager.js b/src/TemplatePassthroughManager.js index 08cc3d8b6..497a16961 100644 --- a/src/TemplatePassthroughManager.js +++ b/src/TemplatePassthroughManager.js @@ -1,14 +1,15 @@ -const multimatch = require("multimatch"); -const isGlob = require("is-glob"); -const { TemplatePath } = require("@11ty/eleventy-utils"); +import multimatch from "multimatch"; +import isGlob from "is-glob"; +import { TemplatePath } from "@11ty/eleventy-utils"; +import debugUtil from "debug"; -const EleventyExtensionMap = require("./EleventyExtensionMap"); -const EleventyBaseError = require("./EleventyBaseError"); -const TemplatePassthrough = require("./TemplatePassthrough"); -const checkPassthroughCopyBehavior = require("./Util/PassthroughCopyBehaviorCheck"); +import EleventyExtensionMap from "./EleventyExtensionMap.js"; +import EleventyBaseError from "./EleventyBaseError.js"; +import TemplatePassthrough from "./TemplatePassthrough.js"; +import checkPassthroughCopyBehavior from "./Util/PassthroughCopyBehaviorCheck.js"; -const debug = require("debug")("Eleventy:TemplatePassthroughManager"); -const debugDev = require("debug")("Dev:Eleventy:TemplatePassthroughManager"); +const debug = debugUtil("Eleventy:TemplatePassthroughManager"); +const debugDev = debugUtil("Dev:Eleventy:TemplatePassthroughManager"); class TemplatePassthroughManagerConfigError extends EleventyBaseError {} class TemplatePassthroughManagerCopyError extends EleventyBaseError {} @@ -296,4 +297,4 @@ class TemplatePassthroughManager { } } -module.exports = TemplatePassthroughManager; +export default TemplatePassthroughManager; diff --git a/src/TemplatePermalink.js b/src/TemplatePermalink.js index e633d5f14..4a608265e 100644 --- a/src/TemplatePermalink.js +++ b/src/TemplatePermalink.js @@ -1,8 +1,6 @@ -const path = require("path"); -const normalize = require("normalize-path"); -const { TemplatePath, isPlainObject } = require("@11ty/eleventy-utils"); - -const serverlessUrlFilter = require("./Filters/ServerlessUrl"); +import path from "node:path"; +import normalize from "normalize-path"; +import { TemplatePath, isPlainObject } from "@11ty/eleventy-utils"; class TemplatePermalink { // `link` with template syntax should have already been rendered in Template.js @@ -24,9 +22,6 @@ class TemplatePermalink { if (typeof key !== "string") { continue; } - if (key !== "build" && link[key] !== false) { - this.primaryServerlessUrl = link[key]; // can be an array or string - } break; } } else { @@ -50,12 +45,7 @@ class TemplatePermalink { this.buildLink = buildLink; } - this.serverlessUrls = {}; - if (isLinkAnObject) { - Object.assign(this.serverlessUrls, link); - delete this.serverlessUrls.build; - // default if permalink is an Object but does not have a `build` prop if (!("build" in link)) { this._writeToFileSystem = false; @@ -74,14 +64,6 @@ class TemplatePermalink { return this._urlTransforms || []; } - setServerlessPathData(data) { - this.serverlessPathData = data; - } - - getServerlessUrls() { - return this.serverlessUrls; - } - _addDefaultLinkFilename(link) { return link + (link.slice(-1) === "/" ? "index.html" : ""); } @@ -95,11 +77,7 @@ class TemplatePermalink { let cleanLink = this._addDefaultLinkFilename(this.buildLink); let parsed = path.parse(cleanLink); - return TemplatePath.join( - parsed.dir, - this.extraPaginationSubdir, - parsed.base - ); + return TemplatePath.join(parsed.dir, this.extraPaginationSubdir, parsed.base); } // Used in url transforms feature @@ -120,9 +98,7 @@ class TemplatePermalink { if (compare.endsWith(needleHtml)) { return compare.slice(0, compare.length - needleHtml.length) + "/"; } else if (compare.endsWith(needleBareTrailingSlash)) { - return ( - compare.slice(0, compare.length - needleBareTrailingSlash.length) + "/" - ); + return compare.slice(0, compare.length - needleBareTrailingSlash.length) + "/"; } else if (compare.endsWith(needleBare)) { return compare.slice(0, compare.length - needleBare.length) + "/"; } @@ -131,42 +107,18 @@ class TemplatePermalink { } // This method is used to generate the `page.url` variable. - // Note that in serverless mode this should still exist to generate the content map // remove all index.html’s from links // index.html becomes / // test/index.html becomes test/ toHref() { - if (this.primaryServerlessUrl) { - if (this.serverlessPathData) { - let urls = serverlessUrlFilter( - this.primaryServerlessUrl, - this.serverlessPathData - ); - - // Array of *matching* serverless urls only - if (Array.isArray(urls)) { - // return first - return urls[0]; - } - - return urls; - } - - if (Array.isArray(this.primaryServerlessUrl)) { - // return first - return this.primaryServerlessUrl[0]; - } - - return this.primaryServerlessUrl; - } else if (!this.buildLink) { + if (!this.buildLink) { // empty or false return false; } let transformedLink = this.toOutputPath(); - let original = - (transformedLink.charAt(0) !== "/" ? "/" : "") + transformedLink; + let original = (transformedLink.charAt(0) !== "/" ? "/" : "") + transformedLink; let normalized = TemplatePermalink.normalizePathToUrl(original) || ""; for (let transform of this.urlTransforms) { @@ -216,39 +168,23 @@ class TemplatePermalink { return folders[folders.length - 1] === base; } - static generate( - dir, - filenameNoExt, - extraSubdir, - suffix, - fileExtension = "html" - ) { + static generate(dir, filenameNoExt, extraSubdir, suffix, fileExtension = "html") { let path; if (fileExtension === "html") { - let hasDupeFolder = TemplatePermalink._hasDuplicateFolder( - dir, - filenameNoExt - ); + let hasDupeFolder = TemplatePermalink._hasDuplicateFolder(dir, filenameNoExt); path = (dir ? dir + "/" : "") + - (filenameNoExt !== "index" && !hasDupeFolder - ? filenameNoExt + "/" - : "") + + (filenameNoExt !== "index" && !hasDupeFolder ? filenameNoExt + "/" : "") + "index" + (suffix || "") + ".html"; } else { - path = - (dir ? dir + "/" : "") + - filenameNoExt + - (suffix || "") + - "." + - fileExtension; + path = (dir ? dir + "/" : "") + filenameNoExt + (suffix || "") + "." + fileExtension; } return new TemplatePermalink(path, extraSubdir); } } -module.exports = TemplatePermalink; +export default TemplatePermalink; diff --git a/src/TemplateRender.js b/src/TemplateRender.js index 4a06bfdeb..ebd0698e9 100644 --- a/src/TemplateRender.js +++ b/src/TemplateRender.js @@ -1,9 +1,11 @@ -const { TemplatePath } = require("@11ty/eleventy-utils"); +import { TemplatePath } from "@11ty/eleventy-utils"; -const EleventyBaseError = require("./EleventyBaseError"); -const EleventyExtensionMap = require("./EleventyExtensionMap"); -const CustomEngine = require("./Engines/Custom.js"); -// const debug = require("debug")("Eleventy:TemplateRender"); +import EleventyBaseError from "./EleventyBaseError.js"; +import EleventyExtensionMap from "./EleventyExtensionMap.js"; +import CustomEngine from "./Engines/Custom.js"; + +// import debugUtil from "debug"; +// const debug = debugUtil("Eleventy:TemplateRender"); class TemplateRenderConfigError extends EleventyBaseError {} class TemplateRenderUnknownEngineError extends EleventyBaseError {} @@ -52,24 +54,29 @@ class TemplateRender { return this._extensionMap; } - getEngineByName(name) { - let engine = this.extensionMap.engineManager.getEngine(name, this.getDirs(), this.extensionMap); + async getEngineByName(name) { + let engine = await this.extensionMap.engineManager.getEngine( + name, + this.getDirs(), + this.extensionMap + ); engine.eleventyConfig = this.eleventyConfig; return engine; } // Runs once per template - init(engineNameOrPath) { + async init(engineNameOrPath) { + let name = engineNameOrPath || this.engineNameOrPath; this.extensionMap.config = this.eleventyConfig; - this._engineName = this.extensionMap.getKey(engineNameOrPath); + this._engineName = this.extensionMap.getKey(name); if (!this._engineName) { throw new TemplateRenderUnknownEngineError( - `Unknown engine for ${engineNameOrPath} (supported extensions: ${this.extensionMap.getReadableFileExtensions()})` + `Unknown engine for ${name} (supported extensions: ${this.extensionMap.getReadableFileExtensions()})` ); } - this._engine = this.getEngineByName(this._engineName); + this._engine = await this.getEngineByName(this._engineName); if (this.useMarkdown === undefined) { this.setUseMarkdown(this._engineName === "md"); @@ -78,14 +85,14 @@ class TemplateRender { get engineName() { if (!this._engineName) { - this.init(this.engineNameOrPath); + throw new Error("TemplateRender needs a call to the init() method."); } return this._engineName; } get engine() { if (!this._engine) { - this.init(this.engineNameOrPath); + throw new Error("TemplateRender needs a call to the init() method."); } return this._engine; } @@ -200,7 +207,7 @@ class TemplateRender { return this.extensionMap.getKey(this.engineNameOrPath); } - setEngineOverride(engineName, bypassMarkdown) { + async setEngineOverride(engineName, bypassMarkdown) { let engines = TemplateRender.parseEngineOverrides(engineName); // when overriding, Template Engines with HTML will instead use the Template Engine as primary and output HTML @@ -208,11 +215,11 @@ class TemplateRender { this.setHtmlEngine(false); if (!engines.length) { - this.init("html"); + await this.init("html"); return; } - this.init(engines[0]); + await this.init(engines[0]); let usingMarkdown = engines[0] === "md" && !bypassMarkdown; @@ -278,4 +285,4 @@ class TemplateRender { } } -module.exports = TemplateRender; +export default TemplateRender; diff --git a/src/TemplateWriter.js b/src/TemplateWriter.js index c4c5b64ba..9e5e4596f 100755 --- a/src/TemplateWriter.js +++ b/src/TemplateWriter.js @@ -1,17 +1,18 @@ -const { TemplatePath } = require("@11ty/eleventy-utils"); - -const Template = require("./Template"); -const TemplateMap = require("./TemplateMap"); -const EleventyFiles = require("./EleventyFiles"); -const EleventyExtensionMap = require("./EleventyExtensionMap"); -const EleventyBaseError = require("./EleventyBaseError"); -const EleventyErrorHandler = require("./EleventyErrorHandler"); -const EleventyErrorUtil = require("./EleventyErrorUtil"); -const FileSystemSearch = require("./FileSystemSearch"); -const ConsoleLogger = require("./Util/ConsoleLogger"); - -const debug = require("debug")("Eleventy:TemplateWriter"); -const debugDev = require("debug")("Dev:Eleventy:TemplateWriter"); +import { TemplatePath } from "@11ty/eleventy-utils"; +import debugUtil from "debug"; + +import Template from "./Template.js"; +import TemplateMap from "./TemplateMap.js"; +import EleventyFiles from "./EleventyFiles.js"; +import EleventyExtensionMap from "./EleventyExtensionMap.js"; +import EleventyBaseError from "./EleventyBaseError.js"; +import EleventyErrorHandler from "./EleventyErrorHandler.js"; +import EleventyErrorUtil from "./EleventyErrorUtil.js"; +import FileSystemSearch from "./FileSystemSearch.js"; +import ConsoleLogger from "./Util/ConsoleLogger.js"; + +const debug = debugUtil("Eleventy:TemplateWriter"); +const debugDev = debugUtil("Dev:Eleventy:TemplateWriter"); class TemplateWriterMissingConfigArgError extends EleventyBaseError {} class EleventyPassthroughCopyError extends EleventyBaseError {} @@ -469,4 +470,4 @@ class TemplateWriter { } } -module.exports = TemplateWriter; +export default TemplateWriter; diff --git a/src/UserConfig.js b/src/UserConfig.js index ad6b41aa9..b9db19b1c 100644 --- a/src/UserConfig.js +++ b/src/UserConfig.js @@ -1,13 +1,14 @@ -const chalk = require("kleur"); -const { DateTime } = require("luxon"); +import chalk from "kleur"; +import { DateTime } from "luxon"; +import debugUtil from "debug"; -const EventEmitter = require("./Util/AsyncEventEmitter"); -const EleventyCompatibility = require("./Util/Compatibility"); -const EleventyBaseError = require("./EleventyBaseError"); -const BenchmarkManager = require("./BenchmarkManager"); -const merge = require("./Util/Merge"); +import EventEmitter from "./Util/AsyncEventEmitter.js"; +import EleventyCompatibility from "./Util/Compatibility.js"; +import EleventyBaseError from "./EleventyBaseError.js"; +import BenchmarkManager from "./BenchmarkManager.js"; +import merge from "./Util/Merge.js"; -const debug = require("debug")("Eleventy:UserConfig"); +const debug = debugUtil("Eleventy:UserConfig"); class UserConfigError extends EleventyBaseError {} @@ -16,9 +17,15 @@ const ComparisonAsyncFunction = (async () => {}).constructor; // API to expose configuration options in config file class UserConfig { constructor() { + this._uniqueId = Math.random(); this.reset(); } + // Internally used in TemplateContent for cache keys + _getUniqueId() { + return this._uniqueId; + } + reset() { debug("Resetting EleventyConfig to initial values."); this.events = new EventEmitter(); @@ -50,13 +57,7 @@ class UserConfig { this.nunjucksPairedShortcodes = {}; this.nunjucksAsyncPairedShortcodes = {}; - this.handlebarsHelpers = {}; - this.handlebarsShortcodes = {}; - this.handlebarsPairedShortcodes = {}; - this.javascriptFunctions = {}; - this.pugOptions = {}; - this.ejsOptions = {}; this.markdownHighlighter = null; this.libraryOverrides = {}; @@ -144,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: … } })`, ); } @@ -170,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, ); } @@ -191,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, ); } } @@ -208,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, ); } @@ -235,14 +236,11 @@ 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; }); - - // TODO remove Handlebars helpers in Universal Filters. Use shortcodes instead (the Handlebars template syntax is the same). - this.addHandlebarsHelper(name, callback); } // Liquid, Nunjucks, and JS only @@ -257,17 +255,10 @@ class UserConfig { let ret = await callback.call(this, ...args); cb(null, ret); }); - - // Note: no handlebars } getFilter(name) { - return ( - this.javascriptFunctions[name] || - this.nunjucksFilters[name] || - this.liquidFilters[name] || - this.handlebarsHelpers[name] - ); + return this.javascriptFunctions[name] || this.nunjucksFilters[name] || this.liquidFilters[name]; } addNunjucksTag(name, tagFn) { @@ -275,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) {})`, ); } @@ -298,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; @@ -347,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, @@ -375,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 = ""; @@ -471,19 +469,18 @@ class UserConfig { addTemplateFormats(templateFormats) { this.templateFormatsAdded = this._normalizeTemplateFormats( templateFormats, - this.templateFormatsAdded + this.templateFormatsAdded, ); } setLibrary(engineName, libraryInstance) { - // Pug options are passed to `compile` and not in the library constructor so we don’t need to warn 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.", ); } @@ -500,8 +497,8 @@ class UserConfig { this.libraryAmendments[name].push(callback); } - setPugOptions(options) { - this.pugOptions = options; + setPugOptions() { + // no-op for backwards compat } setLiquidOptions(options) { @@ -516,8 +513,8 @@ class UserConfig { this.nunjucksPrecompiledTemplates = templates; } - setEjsOptions(options) { - this.ejsOptions = options; + setEjsOptions() { + // no-op for backwards compat } setDynamicPermalinks(enabled) { @@ -531,7 +528,7 @@ class UserConfig { addShortcode(name, callback) { // This method *requires* `async function` and will not work with `function` that returns a promise if (callback instanceof ComparisonAsyncFunction) { - this.addAsyncShortcode(name, callback); // Note: no handlebars + this.addAsyncShortcode(name, callback); return; } @@ -539,9 +536,6 @@ class UserConfig { this.addLiquidShortcode(name, callback); this.addJavaScriptFunction(name, callback); this.addNunjucksShortcode(name, callback); - - // Note: Handlebars is sync-only - this.addHandlebarsShortcode(name, callback); } addAsyncShortcode(name, callback) { @@ -551,8 +545,6 @@ class UserConfig { this.addNunjucksAsyncShortcode(name, callback); this.addLiquidShortcode(name, callback); this.addJavaScriptFunction(name, callback); - - // Note: Handlebars is not async-friendly } addNunjucksAsyncShortcode(name, callback) { @@ -561,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, ); } @@ -582,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, ); } } @@ -599,38 +591,24 @@ 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, ); } - addHandlebarsShortcode(name, callback) { - name = this.getNamespacedName(name); - - if (this.handlebarsShortcodes[name]) { - debug( - chalk.yellow( - "Warning, overwriting a Handlebars Shortcode with `addHandlebarsShortcode(%o)`" - ), - name - ); - } - - this.handlebarsShortcodes[name] = this.benchmarks.config.add( - `"${name}" Handlebars Shortcode`, - callback - ); + addHandlebarsShortcode() { + // no-op for backwards compat } addPairedShortcode(name, callback) { // This method *requires* `async function` and will not work with `function` that returns a promise if (callback instanceof ComparisonAsyncFunction) { - this.addPairedAsyncShortcode(name, callback); // Note: no handlebars + this.addPairedAsyncShortcode(name, callback); return; } @@ -638,9 +616,6 @@ class UserConfig { this.addPairedNunjucksShortcode(name, callback); this.addPairedLiquidShortcode(name, callback); this.addJavaScriptFunction(name, callback); - - // Note: Handlebars is sync-only - this.addPairedHandlebarsShortcode(name, callback); } // Undocumented method as a mitigation to reduce risk of #498 @@ -649,7 +624,6 @@ class UserConfig { this.addPairedNunjucksAsyncShortcode(name, callback); this.addPairedLiquidShortcode(name, callback); this.addJavaScriptFunction(name, callback); - // Note: Handlebars is sync-only } addPairedNunjucksAsyncShortcode(name, callback) { @@ -658,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, ); } @@ -679,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, ); } } @@ -698,34 +672,20 @@ 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, ); } - addPairedHandlebarsShortcode(name, callback) { - name = this.getNamespacedName(name); - - if (this.handlebarsPairedShortcodes[name]) { - debug( - chalk.yellow( - "Warning, overwriting a Handlebars Paired Shortcode with `addPairedHandlebarsShortcode(%o)`" - ), - name - ); - } - - this.handlebarsPairedShortcodes[name] = this.benchmarks.config.add( - `"${name}" Handlebars Paired Shortcode`, - callback - ); + addPairedHandlebarsShortcode() { + // no-op for backwards compat } addJavaScriptFunction(name, callback) { @@ -734,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, ); } @@ -774,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.", ); } @@ -811,8 +771,8 @@ class UserConfig { key: extension, extension: extension, }, - options - ) + options, + ), ); } } @@ -823,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`", ); } @@ -893,12 +853,7 @@ class UserConfig { nunjucksShortcodes: this.nunjucksShortcodes, nunjucksAsyncPairedShortcodes: this.nunjucksAsyncPairedShortcodes, nunjucksPairedShortcodes: this.nunjucksPairedShortcodes, - handlebarsHelpers: this.handlebarsHelpers, - handlebarsShortcodes: this.handlebarsShortcodes, - handlebarsPairedShortcodes: this.handlebarsPairedShortcodes, javascriptFunctions: this.javascriptFunctions, - pugOptions: this.pugOptions, - ejsOptions: this.ejsOptions, markdownHighlighter: this.markdownHighlighter, libraryOverrides: this.libraryOverrides, dynamicPermalinks: this.dynamicPermalinks, @@ -939,4 +894,4 @@ class UserConfig { } } -module.exports = UserConfig; +export default UserConfig; diff --git a/src/Util/AsyncEventEmitter.js b/src/Util/AsyncEventEmitter.js index e89da5a1c..6c5a3c23e 100644 --- a/src/Util/AsyncEventEmitter.js +++ b/src/Util/AsyncEventEmitter.js @@ -1,4 +1,4 @@ -const EventEmitter = require("events"); +import EventEmitter from "node:events"; /** * This class emits events asynchronously. @@ -47,4 +47,4 @@ class AsyncEventEmitter extends EventEmitter { } } -module.exports = AsyncEventEmitter; +export default AsyncEventEmitter; diff --git a/src/Util/Compatibility.js b/src/Util/Compatibility.js index a9d56c1cf..ccedd3acb 100644 --- a/src/Util/Compatibility.js +++ b/src/Util/Compatibility.js @@ -1,9 +1,10 @@ -const semver = require("semver"); -const path = require("path"); -const { TemplatePath } = require("@11ty/eleventy-utils"); +import semver from "semver"; +import debugUtil from "debug"; -const pkg = require("../../package.json"); -const debug = require("debug")("Eleventy:Compatibility"); +import { getEleventyPackageJson, getWorkingProjectPackageJson } from "./ImportJsonSync.js"; + +const pkg = getEleventyPackageJson(); +const debug = debugUtil("Eleventy:Compatibility"); class Compatibility { static NORMALIZE_PRERELEASE_REGEX = /\-canary\b/g; @@ -23,7 +24,7 @@ class Compatibility { try { // fetch from project’s package.json - let projectPackageJson = require(path.join(TemplatePath.getWorkingDir(), "package.json")); + let projectPackageJson = getWorkingProjectPackageJson(); return projectPackageJson["11ty"]?.compatibility; } catch (e) { debug("Could not find a project package.json for compatibility version check: %O", e); @@ -50,4 +51,4 @@ class Compatibility { } } -module.exports = Compatibility; +export default Compatibility; diff --git a/src/Util/ConsoleLogger.js b/src/Util/ConsoleLogger.js index 1ed56a80d..2696dac76 100644 --- a/src/Util/ConsoleLogger.js +++ b/src/Util/ConsoleLogger.js @@ -1,6 +1,8 @@ -const chalk = require("kleur"); -const debug = require("debug")("Eleventy:Logger"); -const Readable = require("stream").Readable; +import { Readable } from "node:stream"; +import chalk from "kleur"; +import debugUtil from "debug"; + +const debug = debugUtil("Eleventy:Logger"); /** * Logger implementation that logs to STDOUT. @@ -96,4 +98,4 @@ class ConsoleLogger { } } -module.exports = ConsoleLogger; +export default ConsoleLogger; diff --git a/src/Util/DateGitFirstAdded.js b/src/Util/DateGitFirstAdded.js index ea9447504..91b0e7940 100644 --- a/src/Util/DateGitFirstAdded.js +++ b/src/Util/DateGitFirstAdded.js @@ -1,4 +1,4 @@ -const spawn = require("cross-spawn"); +import spawn from "cross-spawn"; function getGitFirstAddedTimeStamp(filePath) { return ( @@ -16,9 +16,9 @@ function getGitFirstAddedTimeStamp(filePath) { } // return a Date -module.exports = function (inputPath) { +export default function (inputPath) { let timestamp = getGitFirstAddedTimeStamp(inputPath); if (timestamp) { return new Date(timestamp); } -}; +} diff --git a/src/Util/DateGitLastUpdated.js b/src/Util/DateGitLastUpdated.js index 905af887b..f06b4dcb6 100644 --- a/src/Util/DateGitLastUpdated.js +++ b/src/Util/DateGitLastUpdated.js @@ -1,4 +1,4 @@ -const spawn = require("cross-spawn"); +import spawn from "cross-spawn"; /* Thank you to Vuepress! * https://github.com/vuejs/vuepress/blob/89440ce552675859189ed4ab254ce19c4bba5447/packages/%40vuepress/plugin-last-updated/index.js @@ -20,9 +20,9 @@ function getGitLastUpdatedTimeStamp(filePath) { } // return a Date -module.exports = function (inputPath) { +export default function (inputPath) { let timestamp = getGitLastUpdatedTimeStamp(inputPath); if (timestamp) { return new Date(timestamp); } -}; +} diff --git a/src/Util/DeleteRequireCache.js b/src/Util/DeleteRequireCache.js deleted file mode 100644 index 7fdf985d6..000000000 --- a/src/Util/DeleteRequireCache.js +++ /dev/null @@ -1,24 +0,0 @@ -const path = require("path"); -const { TemplatePath } = require("@11ty/eleventy-utils"); -const debug = require("debug")("Eleventy:DeleteRequireCache"); - -/** - * Removes a nodejs module from the cache. - * The keys of the nodejs require cache are file paths based on the current operating system. - * @param {string} absolutePath An absolute POSIX path to the file. - */ -function deleteRequireCacheAbsolute(absolutePath) { - const normalizedPath = path.normalize(absolutePath); - debug("Deleting %o from `require` cache.", normalizedPath); - delete require.cache[normalizedPath]; -} - -function deleteRequireCache(localPath) { - let absolutePath = TemplatePath.absolutePath(localPath); - deleteRequireCacheAbsolute(absolutePath); -} - -module.exports = deleteRequireCache; // will transform local paths to absolute - -// Export for testing only -module.exports.deleteRequireCacheAbsolute = deleteRequireCacheAbsolute; diff --git a/src/Util/DirContains.js b/src/Util/DirContains.js index 982078204..fb449d832 100644 --- a/src/Util/DirContains.js +++ b/src/Util/DirContains.js @@ -1,9 +1,9 @@ -const path = require("path"); +import path from "node:path"; // Returns true if subfolder is in parent (accepts absolute or relative paths for both) -module.exports = function (parent, subfolder) { +export default function (parent, subfolder) { if (path.resolve(subfolder).startsWith(path.resolve(parent))) { return true; } return false; -}; +} diff --git a/src/Util/EventBusUtil.js b/src/Util/EventBusUtil.js index 959893773..586c46125 100644 --- a/src/Util/EventBusUtil.js +++ b/src/Util/EventBusUtil.js @@ -1,4 +1,4 @@ -const eventBus = require("../EventBus"); +import eventBus from "../EventBus.js"; class EventBusUtil { // Used for non-global subscriptions that will blow away the previous listener @@ -8,4 +8,4 @@ class EventBusUtil { } } -module.exports = EventBusUtil; +export default EventBusUtil; diff --git a/src/Util/GetJavaScriptData.js b/src/Util/GetJavaScriptData.js index 92d6fba50..65936db82 100644 --- a/src/Util/GetJavaScriptData.js +++ b/src/Util/GetJavaScriptData.js @@ -1,8 +1,8 @@ -const EleventyBaseError = require("../EleventyBaseError"); +import EleventyBaseError from "../EleventyBaseError.js"; class JavaScriptInvalidDataFormatError extends EleventyBaseError {} -module.exports = async function (inst, inputPath, key = "data", options = {}) { +export default async function (inst, inputPath, key = "data", options = {}) { let { mixins, isObjectRequired } = Object.assign( { mixins: {}, @@ -27,4 +27,4 @@ module.exports = async function (inst, inputPath, key = "data", options = {}) { } return result; } -}; +} diff --git a/src/Util/ImportJsonSync.js b/src/Util/ImportJsonSync.js new file mode 100644 index 000000000..0cc6f97b0 --- /dev/null +++ b/src/Util/ImportJsonSync.js @@ -0,0 +1,62 @@ +import fs from "node:fs"; + +import { TemplatePath } from "@11ty/eleventy-utils"; +import { normalizeFilePathInEleventyPackage } from "./Require.js"; + +// async version of this in Require.js + +// Used for JSON imports, suffering from Node warning that import assertions experimental but also +// throwing an error if you try to import() a JSON file without an import assertion. +function loadContentsSync(path, options = {}) { + let rawInput; + let encoding = "utf8"; + if ("encoding" in options) { + encoding = options.encoding; + } + + try { + rawInput = fs.readFileSync(path, encoding); + } catch (e) { + // if file does not exist, return nothing + } + + // Can return a buffer, string, etc + if (typeof rawInput === "string") { + rawInput = rawInput.trim(); + } + + return rawInput; +} + +function importJsonSync(filePath) { + if (!filePath.endsWith(".json")) { + throw new Error(`importJsonSync expects a .json file extension (received: ${filePath})`); + } + + let rawInput = loadContentsSync(filePath); + return JSON.parse(rawInput); +} + +// TODO cache +function getEleventyPackageJson() { + let filePath = normalizeFilePathInEleventyPackage("package.json"); + return importJsonSync(filePath); +} + +// TODO cache +function getModulePackageJson(dir) { + let filePath = TemplatePath.absolutePath(dir, "package.json"); + return importJsonSync(filePath); +} + +// TODO cache +function getWorkingProjectPackageJson() { + return getModulePackageJson(TemplatePath.getWorkingDir()); +} + +export { + importJsonSync, + getEleventyPackageJson, + getModulePackageJson, + getWorkingProjectPackageJson, +}; diff --git a/src/Util/JavaScriptDependencies.js b/src/Util/JavaScriptDependencies.js index 0c8899ed2..7af831cd1 100644 --- a/src/Util/JavaScriptDependencies.js +++ b/src/Util/JavaScriptDependencies.js @@ -1,29 +1,34 @@ -const dependencyTree = require("@11ty/dependency-tree"); -const { TemplatePath } = require("@11ty/eleventy-utils"); +import dependencyTree from "@11ty/dependency-tree"; +import { find } from "@11ty/dependency-tree-esm"; +import { TemplatePath } from "@11ty/eleventy-utils"; class JavaScriptDependencies { - static getDependencies(inputFiles, nodeModuleNamesOnly = false) { + static async getDependencies(inputFiles, isProjectUsingEsm) { let depSet = new Set(); // TODO does this need to work with aliasing? what other JS extensions will have deps? - let filtered = inputFiles.filter( - (file) => file.endsWith(".js") || file.endsWith(".cjs") + let commonJsFiles = inputFiles.filter( + (file) => (!isProjectUsingEsm && file.endsWith(".js")) || file.endsWith(".cjs") ); - for (let file of filtered) { + for (let file of commonJsFiles) { let modules = dependencyTree(file, { - nodeModuleNamesOnly, + nodeModuleNames: "exclude", allowNotFound: true, + }).map((dependency) => { + return TemplatePath.addLeadingDotSlash(TemplatePath.relativePath(dependency)); }); - if (!nodeModuleNamesOnly) { - modules = modules.map((dependency) => { - return TemplatePath.addLeadingDotSlash( - TemplatePath.relativePath(dependency) - ); - }); + for (let dep of modules) { + depSet.add(dep); } + } + let esmFiles = inputFiles.filter( + (file) => (isProjectUsingEsm && file.endsWith(".js")) || file.endsWith(".mjs") + ); + for (let file of esmFiles) { + let modules = await find(file); for (let dep of modules) { depSet.add(dep); } @@ -33,4 +38,4 @@ class JavaScriptDependencies { } } -module.exports = JavaScriptDependencies; +export default JavaScriptDependencies; diff --git a/src/Util/Merge.js b/src/Util/Merge.js index 7914058c0..4b36dfc05 100644 --- a/src/Util/Merge.js +++ b/src/Util/Merge.js @@ -1,4 +1,5 @@ -const { isPlainObject } = require("@11ty/eleventy-utils"); +import { isPlainObject } from "@11ty/eleventy-utils"; + const OVERRIDE_PREFIX = "override:"; function cleanKey(key, prefix) { @@ -67,5 +68,5 @@ function Merge(target, ...sources) { return target; } -module.exports = Merge; -module.exports.DeepCopy = DeepCopy; +export default Merge; +export { DeepCopy }; diff --git a/src/Util/NormalizeServerlessUrl.js b/src/Util/NormalizeServerlessUrl.js deleted file mode 100644 index 1b17db314..000000000 --- a/src/Util/NormalizeServerlessUrl.js +++ /dev/null @@ -1,7 +0,0 @@ -module.exports = function (url) { - // https://github.com/11ty/eleventy/issues/2067 - if (url.endsWith("/*")) { - return url.substring(0, url.length - 2) + "/(.*)"; - } - return url; -}; diff --git a/src/Util/PassthroughCopyBehaviorCheck.js b/src/Util/PassthroughCopyBehaviorCheck.js index 6c0b64ad2..98dfa3ef3 100644 --- a/src/Util/PassthroughCopyBehaviorCheck.js +++ b/src/Util/PassthroughCopyBehaviorCheck.js @@ -1,17 +1,16 @@ function isUsingEleventyDevServer(config) { return ( - !config.serverOptions.module || - config.serverOptions.module === "@11ty/eleventy-dev-server" + !config.serverOptions.module || config.serverOptions.module === "@11ty/eleventy-dev-server" ); } // Config opt-out via serverPassthroughCopyBehavior // False when other server is used // False when runMode is "build" or "watch" -module.exports = function (config, runMode) { +export default function (config, runMode) { return ( config.serverPassthroughCopyBehavior === "passthrough" && isUsingEleventyDevServer(config) && runMode === "serve" ); -}; +} diff --git a/src/Util/PathNormalizer.js b/src/Util/PathNormalizer.js index 255e2eb19..e77301724 100644 --- a/src/Util/PathNormalizer.js +++ b/src/Util/PathNormalizer.js @@ -1,4 +1,4 @@ -const path = require("path"); +import path from "node:path"; class PathNormalizer { static normalizeSeperator(inputPath) { @@ -9,4 +9,4 @@ class PathNormalizer { } } -module.exports = PathNormalizer; +export default PathNormalizer; diff --git a/src/Util/PathPrefixer.js b/src/Util/PathPrefixer.js index 6b0a4be80..2d5fe0696 100644 --- a/src/Util/PathPrefixer.js +++ b/src/Util/PathPrefixer.js @@ -1,5 +1,6 @@ -const path = require("path"); -const PathNormalizer = require("./PathNormalizer.js"); +import path from "node:path"; + +import PathNormalizer from "./PathNormalizer.js"; class PathPrefixer { static normalizePathPrefix(pathPrefix) { @@ -17,4 +18,4 @@ class PathPrefixer { } } -module.exports = PathPrefixer; +export default PathPrefixer; diff --git a/src/Util/Pluralize.js b/src/Util/Pluralize.js index cc51d8996..600f25b01 100644 --- a/src/Util/Pluralize.js +++ b/src/Util/Pluralize.js @@ -1,3 +1,3 @@ -module.exports = function (count, singleWord, pluralWord) { +export default function (count, singleWord, pluralWord) { return count === 1 ? singleWord : pluralWord; -}; +} diff --git a/src/Util/ProxyWrap.js b/src/Util/ProxyWrap.js index 66c9a283f..3974f5ece 100644 --- a/src/Util/ProxyWrap.js +++ b/src/Util/ProxyWrap.js @@ -1,4 +1,4 @@ -const { isPlainObject } = require("@11ty/eleventy-utils"); +import { isPlainObject } from "@11ty/eleventy-utils"; function wrapObject(target, fallback) { return new Proxy(target, { @@ -19,10 +19,7 @@ function wrapObject(target, fallback) { // Nunjucks needs this ownKeys(target) { // unique - let keys = new Set([ - ...Reflect.ownKeys(target), - ...Reflect.ownKeys(fallback), - ]); + let keys = new Set([...Reflect.ownKeys(target), ...Reflect.ownKeys(fallback)]); // console.log( "handler:ownKeys", keys ); return Array.from(keys); }, @@ -47,14 +44,10 @@ function wrapObject(target, fallback) { function ProxyWrap(target, fallback) { if (!isPlainObject(target) || !isPlainObject(fallback)) { - throw new Error( - "ProxyWrap expects objects for both the target and fallback" - ); + throw new Error("ProxyWrap expects objects for both the target and fallback"); } let wrapped = wrapObject(target, fallback); return wrapped; } -module.exports = { - ProxyWrap, -}; +export { ProxyWrap }; diff --git a/src/Util/Require.js b/src/Util/Require.js index 1d37aab6a..2c4fd437a 100644 --- a/src/Util/Require.js +++ b/src/Util/Require.js @@ -1,9 +1,137 @@ -const { TemplatePath } = require("@11ty/eleventy-utils"); +import fs from "node:fs"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; +import { createRequire } from "node:module"; -function requireLocal(localPath) { - let absolutePath = TemplatePath.absolutePath(localPath); +import { TemplatePath } from "@11ty/eleventy-utils"; + +import eventBus from "../EventBus.js"; + +// important to clear the require.cache in CJS projects +const require = createRequire(import.meta.url); + +// Used for JSON imports, suffering from Node warning that import assertions experimental but also +// throwing an error if you try to import() a JSON file without an import assertion. +async function loadContents(path, options = {}) { + let rawInput; + let encoding = "utf8"; + if ("encoding" in options) { + encoding = options.encoding; + } + + try { + rawInput = await fs.promises.readFile(path, encoding); + } catch (e) { + // if file does not exist, return nothing + } + + // Can return a buffer, string, etc + if (typeof rawInput === "string") { + rawInput = rawInput.trim(); + } + + return rawInput; +} + +let lastModifiedPaths = new Map(); +eventBus.on("eleventy.importCacheReset", (fileQueue) => { + for (let filePath of fileQueue) { + let absolutePath = TemplatePath.absolutePath(filePath); + lastModifiedPaths.set(absolutePath, Date.now()); + + // ESM Eleventy when using `import()` on a CJS project file still adds to require.cache + if (absolutePath in require?.cache) { + delete require.cache[absolutePath]; + } + } +}); + +async function dynamicImportAbsolutePath(absolutePath, type) { + if (absolutePath.endsWith(".json") || type === "json") { + // https://v8.dev/features/import-assertions#dynamic-import() is still experimental in Node 20 + let rawInput = await loadContents(absolutePath); + return JSON.parse(rawInput); + } + + let urlPath; + try { + let u = new URL(`file:${absolutePath}`); + + // Bust the import cache if this is the last modified file + if (lastModifiedPaths.has(absolutePath)) { + u.searchParams.set("_cache_bust", lastModifiedPaths.get(absolutePath)); + } + + urlPath = u.toString(); + } catch (e) { + urlPath = absolutePath; + } - return require(absolutePath); + let target = await import(urlPath); + + // If the only export is `default`, elevate to top (for ESM and CJS) + if (Object.keys(target).length === 1 && "default" in target) { + return target.default; + } + + // When using import() on a CommonJS file that exports an object sometimes it + // returns duplicated values in `default` key, e.g. `{ default: { key: value }, key: value }` + + // A few examples: + // module.exports = { key: false }; + // returns `{ default: { key: false }, key: false }` as not expected. + // module.exports = { key: true }; + // module.exports = { key: null }; + // module.exports = { key: undefined }; + // module.exports = { key: class {} }; + + // A few examples where it does not duplicate: + // module.exports = { key: 1 }; + // returns `{ default: { key: 1 } }` as expected. + // module.exports = { key: "value" }; + // module.exports = { key: {} }; + // module.exports = { key: [] }; + + if (type === "cjs" && "default" in target) { + let match = true; + for (let key in target) { + if (key === "default") { + continue; + } + if (target[key] !== target.default[key]) { + match = false; + } + } + + if (match) { + return target.default; + } + } + + // Otherwise return { default: value, named: value } + return target; +} + +function normalizeFilePathInEleventyPackage(file) { + // Back up from ./src/Util/Require.js + return path.resolve(fileURLToPath(import.meta.url), "../../../", file); +} + +async function dynamicImportFromEleventyPackage(file) { + // points to files relative to the top level Eleventy directory + let filePath = normalizeFilePathInEleventyPackage(file); + return dynamicImportAbsolutePath(filePath); +} + +async function dynamicImport(localPath, type) { + let absolutePath = TemplatePath.absolutePath(localPath); + // async + return dynamicImportAbsolutePath(absolutePath, type); } -module.exports.EleventyRequire = requireLocal; +export { + loadContents as EleventyLoadContent, + dynamicImport as EleventyImport, + dynamicImportFromEleventyPackage as EleventyImportFromEleventy, + normalizeFilePathInEleventyPackage, +}; diff --git a/src/Util/Sortable.js b/src/Util/Sortable.js index 6b375a44a..07cc4c81b 100644 --- a/src/Util/Sortable.js +++ b/src/Util/Sortable.js @@ -96,22 +96,13 @@ class Sortable { } static sortFunctionDate(mapA, mapB) { - return Sortable.sortFunctionNumericAscending( - mapA.date.getTime(), - mapB.date.getTime() - ); + return Sortable.sortFunctionNumericAscending(mapA.date.getTime(), mapB.date.getTime()); } static sortFunctionDateInputPath(mapA, mapB) { - let sortDate = Sortable.sortFunctionNumericAscending( - mapA.date.getTime(), - mapB.date.getTime() - ); + let sortDate = Sortable.sortFunctionNumericAscending(mapA.date.getTime(), mapB.date.getTime()); if (sortDate === 0) { - return Sortable.sortFunctionAlphabeticAscending( - mapA.inputPath, - mapB.inputPath - ); + return Sortable.sortFunctionAlphabeticAscending(mapA.inputPath, mapB.inputPath); } return sortDate; } @@ -142,4 +133,4 @@ class Sortable { } } -module.exports = Sortable; +export default Sortable; diff --git a/src/Util/Unique.js b/src/Util/Unique.js index ad92f8ee7..3a8ea6971 100644 --- a/src/Util/Unique.js +++ b/src/Util/Unique.js @@ -1,3 +1,3 @@ -module.exports = function Unique(arr) { +export default function Unique(arr) { return Array.from(new Set(arr)); -}; +} diff --git a/src/defaultConfig.js b/src/defaultConfig.js index fd5a39bea..aa6002339 100644 --- a/src/defaultConfig.js +++ b/src/defaultConfig.js @@ -1,11 +1,10 @@ -const urlFilter = require("./Filters/Url"); -const serverlessUrlFilter = require("./Filters/ServerlessUrl"); -const slugFilter = require("./Filters/Slug"); -const slugifyFilter = require("./Filters/Slugify"); -const getLocaleCollectionItem = require("./Filters/GetLocaleCollectionItem"); -const getCollectionItemIndex = require("./Filters/GetCollectionItemIndex"); +import urlFilter from "./Filters/Url.js"; +import slugFilter from "./Filters/Slug.js"; +import slugifyFilter from "./Filters/Slugify.js"; +import getLocaleCollectionItem from "./Filters/GetLocaleCollectionItem.js"; +import getCollectionItemIndex from "./Filters/GetCollectionItemIndex.js"; -module.exports = function (config) { +export default function (config) { let templateConfig = this; config.addFilter("slug", slugFilter); @@ -28,8 +27,6 @@ module.exports = function (config) { return input; }); - config.addFilter("serverlessUrl", serverlessUrlFilter); - config.addFilter("getCollectionItemIndex", function (collection, pageOverride) { return getCollectionItemIndex.call(this, collection, pageOverride); }); @@ -45,18 +42,7 @@ module.exports = function (config) { }); return { - templateFormats: [ - "liquid", - "ejs", - "md", - "hbs", - "mustache", - "haml", - "pug", - "njk", - "html", - "11ty.js", - ], + templateFormats: ["liquid", "md", "njk", "html", "11ty.js"], // if your site lives in a subdirectory, change this pathPrefix: "/", markdownTemplateEngine: "liquid", @@ -84,9 +70,7 @@ module.exports = function (config) { data: "_data", output: "_site", }, - // deprecated, use config.addHandlebarsHelper - handlebarsHelpers: {}, // deprecated, use config.addNunjucksFilter nunjucksFilters: {}, }; -}; +} diff --git a/src/index.d.ts b/src/index.d.ts index aa529eba7..854009308 100644 --- a/src/index.d.ts +++ b/src/index.d.ts @@ -1,3 +1,3 @@ -import UserConfig from "./UserConfig"; +import UserConfig from "./UserConfig.js"; export { UserConfig }; diff --git a/test/BenchmarkTest.js b/test/BenchmarkTest.js index 2ac78ebb6..3e97659c9 100644 --- a/test/BenchmarkTest.js +++ b/test/BenchmarkTest.js @@ -1,5 +1,5 @@ -const test = require("ava"); -const Benchmark = require("../src/Benchmark"); +import test from "ava"; +import Benchmark from "../src/Benchmark.js"; test("Standard Benchmark", async (t) => { await new Promise((resolve) => { diff --git a/test/CompatibilityTest.js b/test/CompatibilityTest.js index 6770b5e0e..17ca7370a 100644 --- a/test/CompatibilityTest.js +++ b/test/CompatibilityTest.js @@ -1,5 +1,5 @@ -const test = require("ava"); -const EleventyCompatibility = require("../src/Util/Compatibility"); +import test from "ava"; +import EleventyCompatibility from "../src/Util/Compatibility.js"; test(".canary- to .alpha- normalization (because pre-releases are alphabetic comparisons 😭)", (t) => { t.is(EleventyCompatibility.normalizeIdentifier("2.0.0"), "2.0.0"); diff --git a/test/ComputedDataProxyTest.js b/test/ComputedDataProxyTest.js index 673ac5f6c..53c507d09 100644 --- a/test/ComputedDataProxyTest.js +++ b/test/ComputedDataProxyTest.js @@ -1,5 +1,5 @@ -const test = require("ava"); -const ComputedDataProxy = require("../src/ComputedDataProxy"); +import test from "ava"; +import ComputedDataProxy from "../src/ComputedDataProxy.js"; test("Get vars used by function", async (t) => { let cd = new ComputedDataProxy(["key1"]); @@ -182,10 +182,7 @@ test("findVarsUsed with a computed key (target a string not used in the output)" }, }; - t.deepEqual(await cdg.findVarsUsed(data.computed.key, data), [ - "key2", - "key1", - ]); + t.deepEqual(await cdg.findVarsUsed(data.computed.key, data), ["key2", "key1"]); }); test("findVarsUsed with a deep computed reference that doesn’t exist in parent data", async (t) => { @@ -205,9 +202,7 @@ test("findVarsUsed with a deep computed reference that doesn’t exist in parent }, }; - t.deepEqual(await cdg.findVarsUsed(data.computed.deep.deep2, data), [ - "deep.deep1", - ]); + t.deepEqual(await cdg.findVarsUsed(data.computed.deep.deep2, data), ["deep.deep1"]); t.deepEqual(await cdg.findVarsUsed(data.computed.deep.deep1, data), ["key2"]); }); diff --git a/test/ComputedDataQueueTest.js b/test/ComputedDataQueueTest.js index 03281978d..37980bdd6 100644 --- a/test/ComputedDataQueueTest.js +++ b/test/ComputedDataQueueTest.js @@ -1,17 +1,11 @@ -const test = require("ava"); -const ComputedDataQueue = require("../src/ComputedDataQueue"); +import test from "ava"; +import ComputedDataQueue from "../src/ComputedDataQueue.js"; test("Standard uses", (t) => { let queue = new ComputedDataQueue(); queue.uses("permalink", ["var1", "var2"]); queue.uses("collections.all", ["var2", "var3"]); - t.deepEqual(queue.getOrder(), [ - "var1", - "var2", - "permalink", - "var3", - "collections.all", - ]); + t.deepEqual(queue.getOrder(), ["var1", "var2", "permalink", "var3", "collections.all"]); }); test("What does permalink use", (t) => { @@ -69,10 +63,5 @@ test("Permalink uses a collection (not yet supported in Eleventy)", (t) => { // After we process these queue.markComputed(["permalink", ...varsUsedByPermalink]); - t.deepEqual(queue.getOrder(), [ - "var3", - "collections.all", - "test", - "unrelated", - ]); + t.deepEqual(queue.getOrder(), ["var3", "collections.all", "test", "unrelated"]); }); diff --git a/test/ComputedDataTemplateStringTest.js b/test/ComputedDataTemplateStringTest.js index 5f2c4a531..0e3d30115 100644 --- a/test/ComputedDataTemplateStringTest.js +++ b/test/ComputedDataTemplateStringTest.js @@ -1,5 +1,5 @@ -const test = require("ava"); -const ComputedDataTemplateString = require("../src/ComputedDataTemplateString"); +import test from "ava"; +import ComputedDataTemplateString from "../src/ComputedDataTemplateString.js"; test("Get fake proxy data", (t) => { let cd = new ComputedDataTemplateString(["key1", "key2"]); @@ -23,16 +23,10 @@ test("Get vars from output", (t) => { let cd = new ComputedDataTemplateString(); t.deepEqual(cd.findVarsInOutput(""), []); t.deepEqual(cd.findVarsInOutput("slkdjfkljdsf"), []); - t.deepEqual( - cd.findVarsInOutput(`slkdjfkljdsf${cd.prefix}${cd.suffix}sldkjflkds`), - [] - ); - t.deepEqual( - cd.findVarsInOutput( - `slkdjfkljdsf${cd.prefix}firstVar${cd.suffix}sldkjflkds` - ), - ["firstVar"] - ); + t.deepEqual(cd.findVarsInOutput(`slkdjfkljdsf${cd.prefix}${cd.suffix}sldkjflkds`), []); + t.deepEqual(cd.findVarsInOutput(`slkdjfkljdsf${cd.prefix}firstVar${cd.suffix}sldkjflkds`), [ + "firstVar", + ]); t.deepEqual( cd.findVarsInOutput( `slkdjfkljdsf${cd.prefix}firstVar${cd.suffix}test${cd.prefix}firstVar${cd.suffix}sldkjflkds` diff --git a/test/ComputedDataTest.js b/test/ComputedDataTest.js index 7106e72bf..c9e647df2 100644 --- a/test/ComputedDataTest.js +++ b/test/ComputedDataTest.js @@ -1,6 +1,6 @@ -const test = require("ava"); -const ComputedData = require("../src/ComputedData"); -const TemplateConfig = require("../src/TemplateConfig"); +import test from "ava"; +import ComputedData from "../src/ComputedData.js"; +import TemplateConfig from "../src/TemplateConfig.js"; test("Basic get/set", async (t) => { let cd = new ComputedData(); @@ -330,13 +330,7 @@ test("Get var order", async (t) => { }; await cd.resolveVarOrder(data); - t.deepEqual(cd.queue.getOrder(), [ - "collections.all", - "key1", - "collections.dog", - "key2", - "key0", - ]); + t.deepEqual(cd.queue.getOrder(), ["collections.all", "key1", "collections.dog", "key2", "key0"]); }); test("Get var order and process it in two stages", async (t) => { @@ -397,6 +391,8 @@ test("Get var order and process it in two stages", async (t) => { test("Use JavaScript functions (filters) in computed data functions", async (t) => { let eleventyCfg = new TemplateConfig(); + await eleventyCfg.init(); + let cfg = eleventyCfg.getConfig(); cfg.javascriptFunctions.alwaysBlue = function (str) { return str + " is blue"; diff --git a/test/ConsoleLoggerTest.js b/test/ConsoleLoggerTest.js index 7d9836c46..9bd8cf1d9 100644 --- a/test/ConsoleLoggerTest.js +++ b/test/ConsoleLoggerTest.js @@ -1,5 +1,5 @@ -const test = require("ava"); -const ConsoleLogger = require("../src/Util/ConsoleLogger"); +import test from "ava"; +import ConsoleLogger from "../src/Util/ConsoleLogger.js"; test("Disable chalk", (t) => { let cl = new ConsoleLogger(); diff --git a/test/DeleteRequireCacheTest.js b/test/DeleteRequireCacheTest.js deleted file mode 100644 index 923a7e5ca..000000000 --- a/test/DeleteRequireCacheTest.js +++ /dev/null @@ -1,34 +0,0 @@ -const test = require("ava"); -const path = require("path"); -const { - deleteRequireCacheAbsolute, -} = require("../src/Util/DeleteRequireCache"); -const template = require("./stubs/function.11ty"); - -test("deleteRequireCache", (t) => { - const modulePath = path.normalize( - path.join(__dirname, "./stubs/function.11ty.js") - ); - const posixModulePath = useForwardSlashes(modulePath); - const windowsModulePath = useBackwardSlashes(modulePath); - - deleteRequireCacheAbsolute(posixModulePath); - - t.is(require.cache[windowsModulePath], undefined); -}); - -/** - * @param {string} path - * @returns {string} - */ -function useForwardSlashes(path) { - return path.replace(/\\/g, "/"); -} - -/** - * @param {string} path - * @returns {string} - */ -function useBackwardSlashes(path) { - return path.replace(/\//g, "\\"); -} diff --git a/test/DependencyGraphTest.js b/test/DependencyGraphTest.js index 87564ec71..fd030e238 100644 --- a/test/DependencyGraphTest.js +++ b/test/DependencyGraphTest.js @@ -1,7 +1,7 @@ -const test = require("ava"); +import test from "ava"; +import { DepGraph as DependencyGraph } from "dependency-graph"; test("Dependency graph nodes don’t require dependencies", async (t) => { - const DependencyGraph = require("dependency-graph").DepGraph; let graph = new DependencyGraph(); graph.addNode("all"); @@ -15,16 +15,10 @@ test("Dependency graph nodes don’t require dependencies", async (t) => { t.not(graph.overallOrder().indexOf("template-c"), -1); // in order of addition - t.deepEqual(graph.overallOrder(), [ - "all", - "template-a", - "template-b", - "template-c", - ]); + t.deepEqual(graph.overallOrder(), ["all", "template-a", "template-b", "template-c"]); }); test("Dependency graph assumptions", async (t) => { - const DependencyGraph = require("dependency-graph").DepGraph; let graph = new DependencyGraph(); graph.addNode("all"); @@ -46,7 +40,6 @@ test("Dependency graph assumptions", async (t) => { }); test("Do dependencies get removed when nodes are deleted?", async (t) => { - const DependencyGraph = require("dependency-graph").DepGraph; let graph = new DependencyGraph(); graph.addNode("template-a"); diff --git a/test/DirContainsTest.js b/test/DirContainsTest.js index c26148066..3dd06be6e 100644 --- a/test/DirContainsTest.js +++ b/test/DirContainsTest.js @@ -1,5 +1,5 @@ -const test = require("ava"); -const DirContains = require("../src/Util/DirContains.js"); +import test from "ava"; +import DirContains from "../src/Util/DirContains.js"; test("Compare to current dir", (t) => { t.true(DirContains(".", ".")); diff --git a/test/EleventyErrorHandlerTest.js b/test/EleventyErrorHandlerTest.js index f2d45e071..2e1c455d5 100644 --- a/test/EleventyErrorHandlerTest.js +++ b/test/EleventyErrorHandlerTest.js @@ -1,5 +1,5 @@ -const test = require("ava"); -const EleventyErrorHandler = require("../src/EleventyErrorHandler"); +import test from "ava"; +import EleventyErrorHandler from "../src/EleventyErrorHandler.js"; test("Log a warning, warning", (t) => { let errorHandler = new EleventyErrorHandler(); @@ -45,7 +45,7 @@ test("Log a warning, error", (t) => { errorHandler.error(new Error("Test error"), "It’s me"); - expected = `It’s me: (more in DEBUG output) + let expected = `It’s me: (more in DEBUG output) Test error (via Error) Original error stack trace: Error: Test error`; diff --git a/test/EleventyErrorUtilTest.js b/test/EleventyErrorUtilTest.js index a2ffb7fa7..a3a77e51e 100644 --- a/test/EleventyErrorUtilTest.js +++ b/test/EleventyErrorUtilTest.js @@ -1,14 +1,10 @@ -const test = require("ava"); -const EleventyErrorUtil = require("../src/EleventyErrorUtil"); +import test from "ava"; +import EleventyErrorUtil from "../src/EleventyErrorUtil.js"; const SAMPLE_ERROR = new Error("Nothing to see here"); -const { - cleanMessage, - hasEmbeddedError, - convertErrorToString, - deconvertErrorToObject, -} = EleventyErrorUtil; +const { cleanMessage, hasEmbeddedError, convertErrorToString, deconvertErrorToObject } = + EleventyErrorUtil; test("hasEmbeddedError()", (t) => { t.false(hasEmbeddedError("")); diff --git a/test/EleventyExtensionMapTest.js b/test/EleventyExtensionMapTest.js index 26dd5666f..a040ec66b 100644 --- a/test/EleventyExtensionMapTest.js +++ b/test/EleventyExtensionMapTest.js @@ -1,78 +1,81 @@ -const test = require("ava"); -const EleventyExtensionMap = require("../src/EleventyExtensionMap"); -const TemplateConfig = require("../src/TemplateConfig"); - -function getExtensionMap(formats, config = new TemplateConfig()) { +import test from "ava"; +import EleventyExtensionMap from "../src/EleventyExtensionMap.js"; +import TemplateConfig from "../src/TemplateConfig.js"; + +async function getExtensionMap(formats, config = new TemplateConfig()) { + if (config) { + await config.init(); + } let map = new EleventyExtensionMap(formats, config); return map; } -test("Empty formats", (t) => { - let map = getExtensionMap([]); +test("Empty formats", async (t) => { + let map = await getExtensionMap([]); t.deepEqual(map.getGlobs("."), []); }); -test("Single format", (t) => { - let map = getExtensionMap(["pug"]); - t.deepEqual(map.getGlobs("."), ["./**/*.pug"]); - t.deepEqual(map.getGlobs("src"), ["./src/**/*.pug"]); +test("Single format", async (t) => { + let map = await getExtensionMap(["liquid"]); + t.deepEqual(map.getGlobs("."), ["./**/*.liquid"]); + t.deepEqual(map.getGlobs("src"), ["./src/**/*.liquid"]); }); -test("Multiple formats", (t) => { - let map = getExtensionMap(["njk", "pug"]); - t.deepEqual(map.getGlobs("."), ["./**/*.{njk,pug}"]); - t.deepEqual(map.getGlobs("src"), ["./src/**/*.{njk,pug}"]); +test("Multiple formats", async (t) => { + let map = await getExtensionMap(["njk", "liquid"]); + t.deepEqual(map.getGlobs("."), ["./**/*.{njk,liquid}"]); + t.deepEqual(map.getGlobs("src"), ["./src/**/*.{njk,liquid}"]); }); -test("Invalid keys are filtered (using passthrough copy)", (t) => { - let map = getExtensionMap(["lksdjfjlsk"]); +test("Invalid keys are filtered (using passthrough copy)", async (t) => { + let map = await getExtensionMap(["lksdjfjlsk"]); t.deepEqual(map.getGlobs("."), ["./**/*.lksdjfjlsk"]); }); -test("Keys are mapped to lower case", (t) => { - let map = getExtensionMap(["PUG", "NJK"]); - t.deepEqual(map.getGlobs("."), ["./**/*.{pug,njk}"]); +test("Keys are mapped to lower case", async (t) => { + let map = await getExtensionMap(["LIQUID", "PUG", "NJK"]); + t.deepEqual(map.getGlobs("."), ["./**/*.{liquid,pug,njk}"]); }); -test("Pruned globs", (t) => { - let map = getExtensionMap(["pug", "njk", "png"]); +test("Pruned globs", async (t) => { + let map = await getExtensionMap(["liquid", "njk", "png"]); t.deepEqual(map.getPassthroughCopyGlobs("."), ["./**/*.png"]); }); -test("Empty path for fileList", (t) => { - let map = getExtensionMap(["njk", "pug"]); +test("Empty path for fileList", async (t) => { + let map = await getExtensionMap(["njk", "liquid"]); t.deepEqual(map.getFileList(), []); }); -test("fileList", (t) => { - let map = getExtensionMap(["njk", "pug"]); - t.deepEqual(map.getFileList("filename"), ["filename.njk", "filename.pug"]); +test("fileList", async (t) => { + let map = await getExtensionMap(["njk", "liquid"]); + t.deepEqual(map.getFileList("filename"), ["filename.njk", "filename.liquid"]); }); -test("fileList with dir", (t) => { - let map = getExtensionMap(["njk", "pug"]); +test("fileList with dir", async (t) => { + let map = await getExtensionMap(["njk", "liquid"]); t.deepEqual(map.getFileList("filename", "_includes"), [ "_includes/filename.njk", - "_includes/filename.pug", + "_includes/filename.liquid", ]); }); -test("fileList with dir in path", (t) => { - let map = getExtensionMap(["njk", "pug"]); +test("fileList with dir in path", async (t) => { + let map = await getExtensionMap(["njk", "liquid"]); t.deepEqual(map.getFileList("layouts/filename"), [ "layouts/filename.njk", - "layouts/filename.pug", + "layouts/filename.liquid", ]); }); -test("fileList with dir in path and dir", (t) => { - let map = getExtensionMap(["njk", "pug"]); +test("fileList with dir in path and dir", async (t) => { + let map = await getExtensionMap(["njk", "liquid", "pug"]); t.deepEqual(map.getFileList("layouts/filename", "_includes"), [ "_includes/layouts/filename.njk", - "_includes/layouts/filename.pug", + "_includes/layouts/filename.liquid", ]); }); -test("removeTemplateExtension", (t) => { - let map = getExtensionMap(["njk", "11ty.js"]); +test("removeTemplateExtension", async (t) => { + let map = await getExtensionMap(["njk", "11ty.js"]); t.is(map.removeTemplateExtension("component.njk"), "component"); t.is(map.removeTemplateExtension("component.11ty.js"), "component"); @@ -81,14 +84,14 @@ test("removeTemplateExtension", (t) => { t.is(map.removeTemplateExtension("component.js"), "component.js"); }); -test("hasEngine", (t) => { - let map = getExtensionMap(["liquid", "njk", "11ty.js", "ejs", "pug"]); - t.true(map.hasEngine("default.ejs")); - t.is(map.getKey("default.ejs"), "ejs"); +test("hasEngine", async (t) => { + let map = await getExtensionMap(["liquid", "njk", "11ty.js"]); + t.true(map.hasEngine("default.liquid")); + t.is(map.getKey("default.liquid"), "liquid"); t.falsy(map.getKey()); - t.is(map.getKey("EjS"), "ejs"); - t.true(map.hasEngine("EjS")); - t.true(map.hasEngine("ejs")); + t.is(map.getKey("LiQuid"), "liquid"); + t.true(map.hasEngine("LiqUiD")); + t.true(map.hasEngine("liquid")); t.falsy(map.getKey("sldkjfkldsj")); t.false(map.hasEngine("sldkjfkldsj")); @@ -99,14 +102,14 @@ test("hasEngine", (t) => { t.true(map.hasEngine("md")); }); -test("hasEngine no formats passed in", (t) => { - let map = getExtensionMap([]); - t.true(map.hasEngine("default.ejs")); - t.is(map.getKey("default.ejs"), "ejs"); +test("hasEngine no formats passed in", async (t) => { + let map = await getExtensionMap([]); + t.true(map.hasEngine("default.liquid")); + t.is(map.getKey("default.liquid"), "liquid"); t.falsy(map.getKey()); - t.is(map.getKey("EjS"), "ejs"); - t.true(map.hasEngine("EjS")); - t.true(map.hasEngine("ejs")); + t.is(map.getKey("LiQuid"), "liquid"); + t.true(map.hasEngine("LiqUiD")); + t.true(map.hasEngine("liquid")); t.falsy(map.getKey("sldkjfkldsj")); t.false(map.hasEngine("sldkjfkldsj")); @@ -118,8 +121,8 @@ test("hasEngine no formats passed in", (t) => { t.true(map.hasEngine("md")); }); -test("getKey", (t) => { - let map = getExtensionMap(["njk", "11ty.js", "md"]); +test("getKey", async (t) => { + let map = await getExtensionMap(["njk", "11ty.js", "md"]); t.is(map.getKey("component.njk"), "njk"); t.is(map.getKey("component.11ty.js"), "11ty.js"); t.is(map.getKey("11ty.js"), "11ty.js"); @@ -133,25 +136,26 @@ test("getKey", (t) => { t.is(map.getKey("component.js"), undefined); }); -test("isFullTemplateFilePath (not a passthrough copy extension)", (t) => { - let map = getExtensionMap(["liquid", "njk", "11ty.js", "ejs", "pug", "js", "css"]); +test("isFullTemplateFilePath (not a passthrough copy extension)", async (t) => { + let map = await getExtensionMap(["liquid", "njk", "11ty.js", "js", "css"]); t.true(map.isFullTemplateFilePath("template.liquid")); t.true(map.isFullTemplateFilePath("template.njk")); t.true(map.isFullTemplateFilePath("template.11ty.js")); - t.true(map.isFullTemplateFilePath("template.ejs")); - t.true(map.isFullTemplateFilePath("template.pug")); + t.false(map.isFullTemplateFilePath("template.ejs")); + t.false(map.isFullTemplateFilePath("template.pug")); t.false(map.isFullTemplateFilePath("passthrough.js")); t.false(map.isFullTemplateFilePath("passthrough.css")); }); -test("getValidExtensionsForPath", (t) => { +test("getValidExtensionsForPath", async (t) => { let cfg = new TemplateConfig(); cfg.userConfig.extensionMap.add({ key: "js", extension: "js", }); + await cfg.init(); - let map = getExtensionMap(["liquid", "njk", "11ty.js", "js"], cfg); + let map = await getExtensionMap(["liquid", "njk", "11ty.js", "js"], cfg); t.deepEqual(map.getValidExtensionsForPath("template.liquid"), ["liquid"]); t.deepEqual(map.getValidExtensionsForPath("template.11ty.js"), ["11ty.js", "js"]); @@ -160,18 +164,19 @@ test("getValidExtensionsForPath", (t) => { t.deepEqual(map.getValidExtensionsForPath("njk.liquid.11ty.js"), ["11ty.js", "js"]); }); -test("shouldSpiderJavaScriptDependencies", (t) => { +test("shouldSpiderJavaScriptDependencies", async (t) => { let cfg = new TemplateConfig(); cfg.userConfig.extensionMap.add({ key: "js", extension: "js", }); + await cfg.init(); - let map = getExtensionMap(["liquid", "njk", "11ty.js", "js"], cfg); + let map = await getExtensionMap(["liquid", "njk", "11ty.js", "js"], cfg); - t.deepEqual(map.shouldSpiderJavaScriptDependencies("template.liquid"), false); - t.deepEqual(map.shouldSpiderJavaScriptDependencies("template.njk"), false); - t.deepEqual(map.shouldSpiderJavaScriptDependencies("template.css"), false); - t.deepEqual(map.shouldSpiderJavaScriptDependencies("template.11ty.js"), true); - t.deepEqual(map.shouldSpiderJavaScriptDependencies("template.js"), false); + t.deepEqual(await map.shouldSpiderJavaScriptDependencies("template.liquid"), false); + t.deepEqual(await map.shouldSpiderJavaScriptDependencies("template.njk"), false); + t.deepEqual(await map.shouldSpiderJavaScriptDependencies("template.css"), false); + t.deepEqual(await map.shouldSpiderJavaScriptDependencies("template.11ty.js"), true); + t.deepEqual(await map.shouldSpiderJavaScriptDependencies("template.js"), false); }); diff --git a/test/EleventyFilesGitIgnoreEleventyIgnoreTest.js b/test/EleventyFilesGitIgnoreEleventyIgnoreTest.js index e81a649ed..eb462dd39 100644 --- a/test/EleventyFilesGitIgnoreEleventyIgnoreTest.js +++ b/test/EleventyFilesGitIgnoreEleventyIgnoreTest.js @@ -1,14 +1,16 @@ -const test = require("ava"); -const { TemplatePath } = require("@11ty/eleventy-utils"); +import test from "ava"; +import { TemplatePath } from "@11ty/eleventy-utils"; -const FileSystemSearch = require("../src/FileSystemSearch"); -const EleventyFiles = require("../src/EleventyFiles"); -const TemplateConfig = require("../src/TemplateConfig"); +import FileSystemSearch from "../src/FileSystemSearch.js"; +import EleventyFiles from "../src/EleventyFiles.js"; +import TemplateConfig from "../src/TemplateConfig.js"; /* .eleventyignore and .gitignore combos */ -test("Get ignores (no .eleventyignore no .gitignore)", (t) => { +test("Get ignores (no .eleventyignore no .gitignore)", async (t) => { let eleventyConfig = new TemplateConfig(); + await eleventyConfig.init(); + let evf = new EleventyFiles("test/stubs/ignore1", "test/stubs/ignore1/_site", [], eleventyConfig); evf.init(); @@ -25,8 +27,10 @@ test("Get ignores (no .eleventyignore no .gitignore)", (t) => { ]); }); -test("Get ignores (no .eleventyignore)", (t) => { +test("Get ignores (no .eleventyignore)", async (t) => { let eleventyConfig = new TemplateConfig(); + await eleventyConfig.init(); + let evf = new EleventyFiles("test/stubs/ignore2", "test/stubs/ignore2/_site", [], eleventyConfig); evf.init(); evf._setLocalPathRoot("./test/stubs/ignorelocalrootgitignore"); @@ -43,8 +47,10 @@ test("Get ignores (no .eleventyignore)", (t) => { ]); }); -test("Get ignores (no .eleventyignore, using setUseGitIgnore(false))", (t) => { +test("Get ignores (no .eleventyignore, using setUseGitIgnore(false))", async (t) => { let eleventyConfig = new TemplateConfig(); + await eleventyConfig.init(); + let evf = new EleventyFiles("test/stubs/ignore2", "test/stubs/ignore2/_site", [], eleventyConfig); evf.init(); @@ -64,8 +70,10 @@ test("Get ignores (no .eleventyignore, using setUseGitIgnore(false))", (t) => { t.deepEqual(evf.getIgnoreGlobs().slice(-1), ["./test/stubs/ignorelocalroot/**/node_modules/**"]); }); -test("Get ignores (no .gitignore)", (t) => { +test("Get ignores (no .gitignore)", async (t) => { let eleventyConfig = new TemplateConfig(); + await eleventyConfig.init(); + let evf = new EleventyFiles("test/stubs/ignore3", "test/stubs/ignore3/_site", [], eleventyConfig); evf.init(); evf._setLocalPathRoot("./test/stubs/ignorelocalroot"); @@ -83,8 +91,10 @@ test("Get ignores (no .gitignore)", (t) => { ]); }); -test("Get ignores (project .eleventyignore and root .gitignore)", (t) => { +test("Get ignores (project .eleventyignore and root .gitignore)", async (t) => { let eleventyConfig = new TemplateConfig(); + await eleventyConfig.init(); + let evf = new EleventyFiles("test/stubs/ignore4", "test/stubs/ignore4/_site", [], eleventyConfig); evf.init(); evf._setLocalPathRoot("./test/stubs/ignorelocalrootgitignore"); @@ -103,8 +113,10 @@ test("Get ignores (project .eleventyignore and root .gitignore)", (t) => { ]); }); -test("Get ignores (project .eleventyignore and root .gitignore, using setUseGitIgnore(false))", (t) => { +test("Get ignores (project .eleventyignore and root .gitignore, using setUseGitIgnore(false))", async (t) => { let eleventyConfig = new TemplateConfig(); + await eleventyConfig.init(); + let evf = new EleventyFiles("test/stubs/ignore4", "test/stubs/ignore4/_site", [], eleventyConfig); evf.init(); @@ -128,8 +140,10 @@ test("Get ignores (project .eleventyignore and root .gitignore, using setUseGitI ]); }); -test("Get ignores (no .eleventyignore .gitignore exists but empty)", (t) => { +test("Get ignores (no .eleventyignore .gitignore exists but empty)", async (t) => { let eleventyConfig = new TemplateConfig(); + await eleventyConfig.init(); + let evf = new EleventyFiles("test/stubs/ignore5", "test/stubs/ignore5/_site", [], eleventyConfig); evf.init(); @@ -146,8 +160,10 @@ test("Get ignores (no .eleventyignore .gitignore exists but empty)", (t) => { ]); }); -test("Get ignores (both .eleventyignore and .gitignore exists, but .gitignore is empty)", (t) => { +test("Get ignores (both .eleventyignore and .gitignore exists, but .gitignore is empty)", async (t) => { let eleventyConfig = new TemplateConfig(); + await eleventyConfig.init(); + let evf = new EleventyFiles("test/stubs/ignore6", "test/stubs/ignore6/_site", [], eleventyConfig); evf.init(); evf._setLocalPathRoot("./test/stubs/ignorelocalroot"); @@ -167,6 +183,7 @@ test("Get ignores (both .eleventyignore and .gitignore exists, but .gitignore is test("Bad expected output, this indicates a bug upstream in a dependency. Input to 'src' and empty includes dir (issue #403, full paths in eleventyignore)", async (t) => { let eleventyConfig = new TemplateConfig(); + await eleventyConfig.init(); let evf = new EleventyFiles("test/stubs-403", "test/stubs-403/_site", ["liquid"], eleventyConfig); evf.setEleventyIgnoreContent("!" + TemplatePath.absolutePath("test/stubs-403/_includes") + "/**"); @@ -192,6 +209,7 @@ test("Bad expected output, this indicates a bug upstream in a dependency. Input test("Workaround for Bad expected output, this indicates a bug upstream in a dependency. Input to 'src' and empty includes dir (issue #403, full paths in eleventyignore)", async (t) => { let eleventyConfig = new TemplateConfig(); + await eleventyConfig.init(); let evf = new EleventyFiles("test/stubs-403", "test/stubs-403/_site", ["liquid"], eleventyConfig); evf.setEleventyIgnoreContent("!./test/stubs-403/_includes/**"); evf._setConfig({ @@ -211,6 +229,8 @@ test("Workaround for Bad expected output, this indicates a bug upstream in a dep test("Issue #403: all .eleventyignores should be relative paths not absolute paths", async (t) => { let eleventyConfig = new TemplateConfig(); + await eleventyConfig.init(); + let evf = new EleventyFiles("test/stubs-403", "test/stubs-403/_site", ["liquid"], eleventyConfig); evf._setConfig({ useGitIgnore: false, @@ -232,8 +252,10 @@ test("Issue #403: all .eleventyignores should be relative paths not absolute pat ); }); -test("Same input and output directories, issues #186 and #1129", (t) => { +test("Same input and output directories, issues #186 and #1129", async (t) => { let eleventyConfig = new TemplateConfig(); + await eleventyConfig.init(); + let evf = new EleventyFiles("test/stubs/", "test/stubs/", [], eleventyConfig); evf._setConfig({ useGitIgnore: false, @@ -251,8 +273,10 @@ test("Same input and output directories, issues #186 and #1129", (t) => { ); }); -test("Single input file is in the output directory, issues #186", (t) => { +test("Single input file is in the output directory, issues #186", async (t) => { let eleventyConfig = new TemplateConfig(); + await eleventyConfig.init(); + let evf = new EleventyFiles("test/stubs/test.njk", "test/stubs/", ["njk"], eleventyConfig); evf._setConfig({ useGitIgnore: false, @@ -269,8 +293,10 @@ test("Single input file is in the output directory, issues #186", (t) => { ); }); -test("De-duplicated ignores", (t) => { +test("De-duplicated ignores", async (t) => { let eleventyConfig = new TemplateConfig(); + await eleventyConfig.init(); + let evf = new EleventyFiles( "test/stubs/ignore-dedupe", "test/stubs/ignore-dedupe/_site", diff --git a/test/EleventyFilesTest.js b/test/EleventyFilesTest.js index 8d20887b6..a1685dd02 100644 --- a/test/EleventyFilesTest.js +++ b/test/EleventyFilesTest.js @@ -1,9 +1,10 @@ -const test = require("ava"); -const fastglob = require("fast-glob"); -const EleventyFiles = require("../src/EleventyFiles"); -const TemplateConfig = require("../src/TemplateConfig"); -const FileSystemSearch = require("../src/FileSystemSearch"); -const TemplatePassthroughManager = require("../src/TemplatePassthroughManager"); +import test from "ava"; +import fastglob from "fast-glob"; + +import EleventyFiles from "../src/EleventyFiles.js"; +import TemplateConfig from "../src/TemplateConfig.js"; +import FileSystemSearch from "../src/FileSystemSearch.js"; +import TemplatePassthroughManager from "../src/TemplatePassthroughManager.js"; test("Dirs paths", async (t) => { let eleventyConfig = new TemplateConfig({ @@ -14,6 +15,7 @@ test("Dirs paths", async (t) => { output: "dist", }, }); + await eleventyConfig.init(); let evf = new EleventyFiles("src", "dist", [], eleventyConfig); @@ -32,6 +34,7 @@ test("Dirs paths (relative)", async (t) => { output: "dist", }, }); + await eleventyConfig.init(); let evf = new EleventyFiles("src", "dist", [], eleventyConfig); @@ -43,10 +46,11 @@ test("Dirs paths (relative)", async (t) => { test("getFiles", async (t) => { let eleventyConfig = new TemplateConfig(); + await eleventyConfig.init(); let evf = new EleventyFiles( "./test/stubs/writeTest", "./test/stubs/_writeTestSite", - ["ejs", "md"], + ["liquid", "md"], eleventyConfig ); evf.setFileSystemSearch(new FileSystemSearch()); @@ -57,10 +61,11 @@ test("getFiles", async (t) => { test("getFiles (without 11ty.js)", async (t) => { let eleventyConfig = new TemplateConfig(); + await eleventyConfig.init(); let evf = new EleventyFiles( "./test/stubs/writeTestJS", "./test/stubs/_writeTestJSSite", - ["ejs", "md"], + ["liquid", "md"], eleventyConfig ); evf.setFileSystemSearch(new FileSystemSearch()); @@ -71,24 +76,26 @@ test("getFiles (without 11ty.js)", async (t) => { test("getFiles (with 11ty.js)", async (t) => { let eleventyConfig = new TemplateConfig(); + await eleventyConfig.init(); let evf = new EleventyFiles( "./test/stubs/writeTestJS", "./test/stubs/_writeTestJSSite", - ["ejs", "md", "11ty.js"], + ["liquid", "md", "11ty.js"], eleventyConfig ); evf.setFileSystemSearch(new FileSystemSearch()); evf.init(); - t.deepEqual(await evf.getFiles(), ["./test/stubs/writeTestJS/test.11ty.js"]); + t.deepEqual(await evf.getFiles(), ["./test/stubs/writeTestJS/test.11ty.cjs"]); }); test("getFiles (with js, treated as passthrough copy)", async (t) => { let eleventyConfig = new TemplateConfig(); + await eleventyConfig.init(); let evf = new EleventyFiles( - "./test/stubs/writeTestJS", + "./test/stubs/writeTestJS-passthrough", "./test/stubs/_writeTestJSSite", - ["ejs", "md", "js"], + ["liquid", "md", "js"], eleventyConfig ); evf.setFileSystemSearch(new FileSystemSearch()); @@ -97,15 +104,19 @@ test("getFiles (with js, treated as passthrough copy)", async (t) => { const files = await evf.getFiles(); t.deepEqual( files.sort(), - ["./test/stubs/writeTestJS/sample.js", "./test/stubs/writeTestJS/test.11ty.js"].sort() + [ + "./test/stubs/writeTestJS-passthrough/sample.js", + "./test/stubs/writeTestJS-passthrough/test.11ty.js", + ].sort() ); - t.false(evf.extensionMap.hasEngine("./test/stubs/writeTestJS/sample.js")); - t.true(evf.extensionMap.hasEngine("./test/stubs/writeTestJS/test.11ty.js")); + t.false(evf.extensionMap.hasEngine("./test/stubs/writeTestJS-passthrough/sample.js")); + t.true(evf.extensionMap.hasEngine("./test/stubs/writeTestJS-passthrough/test.11ty.js")); }); test("getFiles (with case insensitivity)", async (t) => { let eleventyConfig = new TemplateConfig(); + await eleventyConfig.init(); let evf = new EleventyFiles( "./test/stubs/writeTestJS-casesensitive", "./test/stubs/_writeTestJSCaseSensitiveSite", @@ -128,26 +139,28 @@ test("getFiles (with case insensitivity)", async (t) => { test("Mutually exclusive Input and Output dirs", async (t) => { let eleventyConfig = new TemplateConfig(); + await eleventyConfig.init(); let evf = new EleventyFiles( "./test/stubs/writeTest", "./test/stubs/_writeTestSite", - ["ejs", "md"], + ["liquid", "md"], eleventyConfig ); evf.init(); let files = await fastglob(evf.getFileGlobs()); - t.deepEqual(evf.getRawFiles(), ["./test/stubs/writeTest/**/*.{ejs,md}"]); + t.deepEqual(evf.getRawFiles(), ["./test/stubs/writeTest/**/*.{liquid,md}"]); t.true(files.length > 0); t.is(files[0], "./test/stubs/writeTest/test.md"); }); test("Single File Input (deep path)", async (t) => { let eleventyConfig = new TemplateConfig(); + await eleventyConfig.init(); let evf = new EleventyFiles( "./test/stubs/index.html", "./test/stubs/_site", - ["ejs", "md"], + ["liquid", "md"], eleventyConfig ); evf.init(); @@ -160,6 +173,7 @@ test("Single File Input (deep path)", async (t) => { test("Single File Input (shallow path)", async (t) => { let eleventyConfig = new TemplateConfig(); + await eleventyConfig.init(); let evf = new EleventyFiles("README.md", "./test/stubs/_site", ["md"], eleventyConfig); evf.init(); @@ -174,6 +188,7 @@ test("Single File Input (shallow path)", async (t) => { test("Glob Input", async (t) => { let eleventyConfig = new TemplateConfig(); + await eleventyConfig.init(); let evf = new EleventyFiles( "./test/stubs/glob-pages/!(contact.md)", "./test/stubs/_site", @@ -217,7 +232,8 @@ test("Passed file name does not exist", (t) => { test(".eleventyignore files", async (t) => { let eleventyConfig = new TemplateConfig(); - let evf = new EleventyFiles("test/stubs", "test/stubs/_site", ["ejs", "md"], eleventyConfig); + await eleventyConfig.init(); + let evf = new EleventyFiles("test/stubs", "test/stubs/_site", ["liquid", "md"], eleventyConfig); evf.init(); let ignoredFiles = await fastglob("test/stubs/ignoredFolder/*.md"); t.is(ignoredFiles.length, 1); @@ -236,8 +252,10 @@ test(".eleventyignore files", async (t) => { ); }); -test("getTemplateData caching", (t) => { +test("getTemplateData caching", async (t) => { let eleventyConfig = new TemplateConfig(); + await eleventyConfig.init(); + let evf = new EleventyFiles("test/stubs", "test/stubs/_site", [], eleventyConfig); evf.init(); let templateDataFirstCall = evf.templateData; @@ -245,22 +263,27 @@ test("getTemplateData caching", (t) => { t.is(templateDataFirstCall, templateDataSecondCall); }); -test("getDataDir", (t) => { +test("getDataDir", async (t) => { let eleventyConfig = new TemplateConfig(); + await eleventyConfig.init(); + let evf = new EleventyFiles(".", "_site", [], eleventyConfig); evf.init(); t.is(evf.getDataDir(), "_data"); }); -test("getDataDir subdir", (t) => { +test("getDataDir subdir", async (t) => { let eleventyConfig = new TemplateConfig(); + await eleventyConfig.init(); + let evf = new EleventyFiles("test/stubs", "test/stubs/_site", [], eleventyConfig); evf.init(); t.is(evf.getDataDir(), "test/stubs/_data"); }); -test("Include and Data Dirs", (t) => { +test("Include and Data Dirs", async (t) => { let eleventyConfig = new TemplateConfig(); + await eleventyConfig.init(); let evf = new EleventyFiles("test/stubs", "test/stubs/_site", [], eleventyConfig); evf.init(); @@ -270,8 +293,9 @@ test("Include and Data Dirs", (t) => { ]); }); -test("Input to 'src' and empty includes dir (issue #403)", (t) => { +test("Input to 'src' and empty includes dir (issue #403)", async (t) => { let eleventyConfig = new TemplateConfig(); + await eleventyConfig.init(); let evf = new EleventyFiles("src", "src/_site", ["md", "liquid", "html"], eleventyConfig); evf.setEleventyIgnoreContent("!./src/_includes/**"); evf._setConfig({ @@ -295,6 +319,7 @@ test("Input to 'src' and empty includes dir (issue #403)", (t) => { test("Glob Watcher Files", async (t) => { let eleventyConfig = new TemplateConfig(); + await eleventyConfig.init(); let evf = new EleventyFiles("test/stubs", "test/stubs/_site", ["njk"], eleventyConfig); evf.init(); @@ -307,6 +332,7 @@ test("Glob Watcher Files", async (t) => { test("Glob Watcher Files with File Extension Passthroughs", async (t) => { let eleventyConfig = new TemplateConfig(); + await eleventyConfig.init(); let evf = new EleventyFiles("test/stubs", "test/stubs/_site", ["njk", "png"], eleventyConfig); evf.init(); @@ -320,7 +346,10 @@ test("Glob Watcher Files with File Extension Passthroughs", async (t) => { test("Glob Watcher Files with File Extension Passthroughs with Dev Server (for free passthrough copy #2456)", async (t) => { let eleventyConfig = new TemplateConfig(); + await eleventyConfig.init(); + eleventyConfig.userConfig.setServerPassthroughCopyBehavior("passthrough"); + eleventyConfig.config.serverPassthroughCopyBehavior = "passthrough"; let evf = new EleventyFiles("test/stubs", "test/stubs/_site", ["njk", "png"], eleventyConfig); evf.setRunMode("serve"); @@ -337,9 +366,15 @@ test("Glob Watcher Files with File Extension Passthroughs with Dev Server (for f test("Glob Watcher Files with Config Passthroughs (one template format)", async (t) => { let eleventyConfig = new TemplateConfig(); + await eleventyConfig.init(); + eleventyConfig.userConfig.passthroughCopies = { "test/stubs/img/": { outputPath: true }, }; + eleventyConfig.config.passthroughCopies = { + "test/stubs/img/": { outputPath: true }, + }; + let evf = new EleventyFiles("test/stubs", "test/stubs/_site", ["njk"], eleventyConfig); evf.init(); @@ -358,11 +393,17 @@ test("Glob Watcher Files with Config Passthroughs (one template format)", async test("Glob Watcher Files with Config Passthroughs (one template format) with Dev Server (for free passthrough copy #2456)", async (t) => { let eleventyConfig = new TemplateConfig(); + await eleventyConfig.init(); eleventyConfig.userConfig.setServerPassthroughCopyBehavior("passthrough"); + eleventyConfig.config.serverPassthroughCopyBehavior = "passthrough"; eleventyConfig.userConfig.passthroughCopies = { "test/stubs/img/": { outputPath: true }, }; + eleventyConfig.config.passthroughCopies = { + "test/stubs/img/": { outputPath: true }, + }; + let evf = new EleventyFiles("test/stubs", "test/stubs/_site", ["njk"], eleventyConfig); evf.setRunMode("serve"); evf.init(); @@ -383,11 +424,13 @@ test("Glob Watcher Files with Config Passthroughs (one template format) with Dev test("Glob Watcher Files with Config Passthroughs (no template formats)", async (t) => { let eleventyConfig = new TemplateConfig(); + await eleventyConfig.init(); + let evf = new EleventyFiles("test/stubs", "test/stubs/_site", [], eleventyConfig); evf.init(); t.deepEqual(await evf.getGlobWatcherTemplateDataFiles(), [ - "./test/stubs/**/*.{json,11tydata.cjs,11tydata.js}", + "./test/stubs/**/*.{json,11tydata.mjs,11tydata.cjs,11tydata.js}", ]); }); diff --git a/test/EleventyServeTest.js b/test/EleventyServeTest.js index ffc069cdd..d1baafbd3 100644 --- a/test/EleventyServeTest.js +++ b/test/EleventyServeTest.js @@ -1,13 +1,17 @@ -const test = require("ava"); -const EleventyServe = require("../src/EleventyServe"); -const TemplateConfig = require("../src/TemplateConfig"); +import test from "ava"; -async function getServerInstance(cfg) { +import EleventyServe from "../src/EleventyServe.js"; +import TemplateConfig from "../src/TemplateConfig.js"; + +async function getServerInstance(eleventyConfig) { let es = new EleventyServe(); - if (!cfg) { - cfg = new TemplateConfig().getConfig(); + if (!eleventyConfig) { + eleventyConfig = new TemplateConfig(); + await eleventyConfig.init(); } - es.config = cfg; + + es.eleventyConfig = eleventyConfig; + await es.init(); delete es.options.logger; @@ -32,10 +36,10 @@ test("Get Options", async (t) => { }); test("Get Options (with a pathPrefix)", async (t) => { - let cfg = new TemplateConfig().getConfig(); - cfg.pathPrefix = "/web/"; + let eleventyConfig = new TemplateConfig(); + await eleventyConfig.init({ pathPrefix: "/web/" }); - let es = await getServerInstance(cfg); + let es = await getServerInstance(eleventyConfig); es.setOutputDir("_site"); t.deepEqual(es.options, { @@ -57,14 +61,16 @@ test("Get Options (override in config)", async (t) => { test("Sanity test that default output is set correctly", async (t) => { let es = await getServerInstance(); es.setOutputDir("_site"); + await es.initServerInstance(); t.is(es.server.dir, "_site"); }); // This assert should work once updating the output dir of the server works. -test.skip("Custom output dir is set correctly", async (t) => { +test("Custom output dir is set correctly", async (t) => { let es = await getServerInstance(); es.setOutputDir("x"); + await es.initServerInstance(); t.is(es.outputDir, "x"); diff --git a/test/EleventyTest.js b/test/EleventyTest.js index d4be319af..aa992ed4e 100644 --- a/test/EleventyTest.js +++ b/test/EleventyTest.js @@ -1,14 +1,19 @@ -const test = require("ava"); -const fsp = require("fs").promises; -const eventBus = require("../src/EventBus.js"); -const Eleventy = require("../src/Eleventy"); -const TemplateContent = require("../src/TemplateContent"); -const EleventyWatchTargets = require("../src/EleventyWatchTargets"); -const TemplateMap = require("../src/TemplateMap"); -const TemplateConfig = require("../src/TemplateConfig"); -const DateGitFirstAdded = require("../src/Util/DateGitFirstAdded.js"); -const DateGitLastUpdated = require("../src/Util/DateGitLastUpdated"); -const normalizeNewLines = require("./Util/normalizeNewLines"); +import test from "ava"; +import fs from "fs"; +import lodash from "@11ty/lodash-custom"; + +import eventBus from "../src/EventBus.js"; +import Eleventy from "../src/Eleventy.js"; +import TemplateContent from "../src/TemplateContent.js"; +import EleventyWatchTargets from "../src/EleventyWatchTargets.js"; +import TemplateMap from "../src/TemplateMap.js"; +import TemplateConfig from "../src/TemplateConfig.js"; +import DateGitFirstAdded from "../src/Util/DateGitFirstAdded.js"; +import DateGitLastUpdated from "../src/Util/DateGitLastUpdated.js"; +import normalizeNewLines from "./Util/normalizeNewLines.js"; + +const fsp = fs.promises; +const lodashGet = lodash.get; test("Eleventy, defaults inherit from config", async (t) => { let elev = new Eleventy(); @@ -84,10 +89,11 @@ test("Eleventy file watching", async (t) => { "./test/stubs/.eleventyignore", "./.eleventy.js", "./eleventy.config.js", + "./eleventy.config.mjs", "./eleventy.config.cjs", - "./test/stubs/**/*.{json,11tydata.cjs,11tydata.js}", - "./test/stubs/deps/dep1.js", - "./test/stubs/deps/dep2.js", + "./test/stubs/**/*.{json,11tydata.mjs,11tydata.cjs,11tydata.js}", + "./test/stubs/deps/dep1.cjs", + "./test/stubs/deps/dep2.cjs", ]); }); @@ -122,8 +128,9 @@ test("Eleventy file watching (no JS dependencies)", async (t) => { "./test/stubs/.eleventyignore", "./.eleventy.js", "./eleventy.config.js", + "./eleventy.config.mjs", "./eleventy.config.cjs", - "./test/stubs/**/*.{json,11tydata.cjs,11tydata.js}", + "./test/stubs/**/*.{json,11tydata.mjs,11tydata.cjs,11tydata.js}", ]); }); @@ -599,9 +606,9 @@ test("Does pathPrefix affect page URLs", async (t) => { t.is(result.url, "/README/"); }); -test("Improvements to custom template syntax APIs (includes a layout file) #2258", async (t) => { +test.only("Improvements to custom template syntax APIs (includes a layout file) #2258", async (t) => { let elev = new Eleventy("./test/stubs-2258/", "./test/stubs-2258/_site", { - configPath: "./test/stubs-2258/eleventy.config.js", + configPath: "./test/stubs-2258/eleventy.config.cjs", }); // Restore previous contents @@ -662,7 +669,6 @@ ${newContents} await fsp.writeFile(includeFilePath, previousContents, { encoding: "utf8" }); }); -const { get: lodashGet } = require("@11ty/lodash-custom"); test("Lodash get (for pagination data target) object key with spaces, issue #2851", (t) => { let data = { collections: { diff --git a/test/EleventyWatchTargetsTest.js b/test/EleventyWatchTargetsTest.js index 1f80e4a0c..828987385 100644 --- a/test/EleventyWatchTargetsTest.js +++ b/test/EleventyWatchTargetsTest.js @@ -1,9 +1,12 @@ -const test = require("ava"); -const EleventyWatchTargets = require("../src/EleventyWatchTargets"); -const JavaScriptDependencies = require("../src/Util/JavaScriptDependencies"); +import test from "ava"; + +import EleventyWatchTargets from "../src/EleventyWatchTargets.js"; +import JavaScriptDependencies from "../src/Util/JavaScriptDependencies.js"; test("Basic", (t) => { let targets = new EleventyWatchTargets(); + targets.setProjectUsingEsm(true); + t.deepEqual(targets.getTargets(), []); targets.add(".eleventy.js"); @@ -12,6 +15,7 @@ test("Basic", (t) => { test("Removes duplicates", (t) => { let targets = new EleventyWatchTargets(); + targets.setProjectUsingEsm(true); targets.add(".eleventy.js"); targets.add("./.eleventy.js"); @@ -20,6 +24,7 @@ test("Removes duplicates", (t) => { test("Add array", (t) => { let targets = new EleventyWatchTargets(); + targets.setProjectUsingEsm(true); targets.add([".eleventy.js", "b.js"]); targets.add(["b.js", "c.js"]); @@ -28,132 +33,132 @@ test("Add array", (t) => { test("Add and make glob", (t) => { let targets = new EleventyWatchTargets(); + targets.setProjectUsingEsm(true); // Note the `test` directory must exist here for this to pass. targets.addAndMakeGlob(["test", "test/b.js"]); t.deepEqual(targets.getTargets(), ["./test/**", "./test/b.js"]); }); -test("JavaScript get dependencies", (t) => { +test("JavaScript get dependencies", async (t) => { t.deepEqual( - JavaScriptDependencies.getDependencies(["./test/stubs/config-deps.js"]), - ["./test/stubs/config-deps-upstream.js"] + await JavaScriptDependencies.getDependencies(["./test/stubs/config-deps.cjs"], true), + ["./test/stubs/config-deps-upstream.cjs"] ); }); -test("JavaScript addDependencies", (t) => { +test("JavaScript addDependencies", async (t) => { let targets = new EleventyWatchTargets(); - targets.addDependencies("./test/stubs/config-deps.js"); - t.deepEqual(targets.getTargets(), ["./test/stubs/config-deps-upstream.js"]); + targets.setProjectUsingEsm(true); - t.true( - targets.uses( - "./test/stubs/config-deps.js", - "./test/stubs/config-deps-upstream.js" - ) - ); - t.false( - targets.uses("./test/stubs/config-deps.js", "./test/stubs/config-deps.js") - ); + await targets.addDependencies("./test/stubs/config-deps.cjs"); + t.deepEqual(targets.getTargets(), ["./test/stubs/config-deps-upstream.cjs"]); + + t.true(targets.uses("./test/stubs/config-deps.cjs", "./test/stubs/config-deps-upstream.cjs")); + t.false(targets.uses("./test/stubs/config-deps.cjs", "./test/stubs/config-deps.cjs")); }); -test("JavaScript addDependencies (one file has two dependencies)", (t) => { +test("JavaScript addDependencies (one file has two dependencies)", async (t) => { let targets = new EleventyWatchTargets(); - targets.addDependencies("./test/stubs/dependencies/two-deps.11ty.js"); + targets.setProjectUsingEsm(true); + + await targets.addDependencies("./test/stubs/dependencies/two-deps.11ty.cjs"); t.deepEqual(targets.getTargets(), [ - "./test/stubs/dependencies/dep1.js", - "./test/stubs/dependencies/dep2.js", + "./test/stubs/dependencies/dep1.cjs", + "./test/stubs/dependencies/dep2.cjs", ]); t.true( targets.uses( - "./test/stubs/dependencies/two-deps.11ty.js", - "./test/stubs/dependencies/dep1.js" + "./test/stubs/dependencies/two-deps.11ty.cjs", + "./test/stubs/dependencies/dep1.cjs" ) ); t.true( targets.uses( - "./test/stubs/dependencies/two-deps.11ty.js", - "./test/stubs/dependencies/dep2.js" + "./test/stubs/dependencies/two-deps.11ty.cjs", + "./test/stubs/dependencies/dep2.cjs" ) ); t.false( targets.uses( - "./test/stubs/dependencies/two-deps.11ty.js", - "./test/stubs/dependencies/dep3.js" + "./test/stubs/dependencies/two-deps.11ty.cjs", + "./test/stubs/dependencies/dep3.cjs" ) ); }); -test("JavaScript addDependencies (skip JS deps)", (t) => { +test("JavaScript addDependencies (skip JS deps)", async (t) => { let targets = new EleventyWatchTargets(); + targets.setProjectUsingEsm(true); targets.watchJavaScriptDependencies = false; - targets.addDependencies("./test/stubs/dependencies/two-deps.11ty.js"); + await targets.addDependencies("./test/stubs/dependencies/two-deps.11ty.cjs"); + t.deepEqual(targets.getTargets(), []); t.false( targets.uses( - "./test/stubs/dependencies/two-deps.11ty.js", - "./test/stubs/dependencies/dep1.js" + "./test/stubs/dependencies/two-deps.11ty.cjs", + "./test/stubs/dependencies/dep1.cjs" ) ); t.false( targets.uses( - "./test/stubs/dependencies/two-deps.11ty.js", - "./test/stubs/dependencies/dep2.js" + "./test/stubs/dependencies/two-deps.11ty.cjs", + "./test/stubs/dependencies/dep2.cjs" ) ); t.false( targets.uses( - "./test/stubs/dependencies/two-deps.11ty.js", - "./test/stubs/dependencies/dep3.js" + "./test/stubs/dependencies/two-deps.11ty.cjs", + "./test/stubs/dependencies/dep3.cjs" ) ); }); -test("JavaScript addDependencies with a filter", (t) => { +test("JavaScript addDependencies with a filter", async (t) => { let targets = new EleventyWatchTargets(); - targets.addDependencies("./test/stubs/config-deps.js", function (path) { + targets.setProjectUsingEsm(true); + await targets.addDependencies("./test/stubs/config-deps.cjs", function (path) { return path.indexOf("./test/stubs/") === -1; }); t.deepEqual(targets.getTargets(), []); t.false( targets.uses( - "./test/stubs/dependencies/config-deps.js", - "./test/stubs/dependencies/config-deps-upstream.js" + "./test/stubs/dependencies/config-deps.cjs", + "./test/stubs/dependencies/config-deps-upstream.cjs" ) ); }); -test("add, addDependencies falsy values are filtered", (t) => { +test("add, addDependencies falsy values are filtered", async (t) => { let targets = new EleventyWatchTargets(); + targets.setProjectUsingEsm(true); targets.add(""); - targets.addDependencies(""); + await targets.addDependencies(""); t.deepEqual(targets.getTargets(), []); }); -test("add, addDependencies file does not exist", (t) => { +test("add, addDependencies file does not exist", async (t) => { let targets = new EleventyWatchTargets(); + targets.setProjectUsingEsm(true); + targets.add("./.eleventy-notfound.js"); // does not exist - targets.addDependencies("./.eleventy-notfound.js"); // does not exist + await targets.addDependencies("./.eleventy-notfound.js"); // does not exist t.deepEqual(targets.getTargets(), ["./.eleventy-notfound.js"]); }); test("getNewTargetsSinceLastReset", (t) => { let targets = new EleventyWatchTargets(); + targets.setProjectUsingEsm(true); + targets.add("./.eleventy-notfound.js"); // does not exist - t.deepEqual(targets.getNewTargetsSinceLastReset(), [ - "./.eleventy-notfound.js", - ]); - t.deepEqual(targets.getNewTargetsSinceLastReset(), [ - "./.eleventy-notfound.js", - ]); + t.deepEqual(targets.getNewTargetsSinceLastReset(), ["./.eleventy-notfound.js"]); + t.deepEqual(targets.getNewTargetsSinceLastReset(), ["./.eleventy-notfound.js"]); targets.reset(); targets.add("./.eleventy-notfound2.js"); - t.deepEqual(targets.getNewTargetsSinceLastReset(), [ - "./.eleventy-notfound2.js", - ]); + t.deepEqual(targets.getNewTargetsSinceLastReset(), ["./.eleventy-notfound2.js"]); targets.reset(); t.deepEqual(targets.getNewTargetsSinceLastReset(), []); diff --git a/test/EleventyWatchTest.js b/test/EleventyWatchTest.js index 895ba233d..12e95ae7e 100644 --- a/test/EleventyWatchTest.js +++ b/test/EleventyWatchTest.js @@ -1,5 +1,5 @@ -const test = require("ava"); -const EleventyWatch = require("../src/EleventyWatch"); +import test from "ava"; +import EleventyWatch from "../src/EleventyWatch.js"; test("Standard", (t) => { let watch = new EleventyWatch(); diff --git a/test/FileSystemSearchTest.js b/test/FileSystemSearchTest.js index df6a06ec3..909610f71 100644 --- a/test/FileSystemSearchTest.js +++ b/test/FileSystemSearchTest.js @@ -1,5 +1,5 @@ -const test = require("ava"); -const FileSystemSearch = require("../src/FileSystemSearch"); +import test from "ava"; +import FileSystemSearch from "../src/FileSystemSearch.js"; test("Base", async (t) => { let fs = new FileSystemSearch(); diff --git a/test/GetCollectionItemIndexTest.js b/test/GetCollectionItemIndexTest.js index 831b2b819..ebf0bd913 100644 --- a/test/GetCollectionItemIndexTest.js +++ b/test/GetCollectionItemIndexTest.js @@ -1,5 +1,5 @@ -const test = require("ava"); -const getCollectionItemIndex = require("../src/Filters/GetCollectionItemIndex"); +import test from "ava"; +import getCollectionItemIndex from "../src/Filters/GetCollectionItemIndex.js"; test("getCollectionItemIndex", (t) => { let first = { diff --git a/test/GetCollectionItemTest.js b/test/GetCollectionItemTest.js index 9f790e36e..8c71fd6f6 100644 --- a/test/GetCollectionItemTest.js +++ b/test/GetCollectionItemTest.js @@ -1,5 +1,6 @@ -const test = require("ava"); -const getCollectionItem = require("../src/Filters/GetCollectionItem"); +import test from "ava"; + +import getCollectionItem from "../src/Filters/GetCollectionItem.js"; test("getCollectionItem", (t) => { let first = { diff --git a/test/GlobalDependencyMapTest.js b/test/GlobalDependencyMapTest.js index a2f4a8f81..c4ed51dcc 100644 --- a/test/GlobalDependencyMapTest.js +++ b/test/GlobalDependencyMapTest.js @@ -1,5 +1,5 @@ -const test = require("ava"); -const GlobalDependencyMap = require("../src/GlobalDependencyMap.js"); +import test from "ava"; +import GlobalDependencyMap from "../src/GlobalDependencyMap.js"; test("Test map", (t) => { let map = new GlobalDependencyMap(); diff --git a/test/HtmlBasePluginTest.js b/test/HtmlBasePluginTest.js index 1324ad75c..472649a6c 100644 --- a/test/HtmlBasePluginTest.js +++ b/test/HtmlBasePluginTest.js @@ -1,17 +1,15 @@ -const test = require("ava"); -const HtmlBasePlugin = require("../src/Plugins/HtmlBasePlugin"); -const Eleventy = require("../src/Eleventy"); -const normalizeNewLines = require("./Util/normalizeNewLines"); +import test from "ava"; + +import { default as HtmlBasePlugin, applyBaseToUrl } from "../src/Plugins/HtmlBasePlugin.js"; +import Eleventy from "../src/Eleventy.js"; +import normalizeNewLines from "./Util/normalizeNewLines.js"; function getContentFor(results, filename) { - let content = results.filter((entry) => - entry.outputPath.endsWith(filename) - )[0].content; + let content = results.filter((entry) => entry.outputPath.endsWith(filename))[0].content; return normalizeNewLines(content.trim()); } test("Using the filter directly", async (t) => { - let { applyBaseToUrl } = HtmlBasePlugin; // url, base, pathprefix // default pathprefix @@ -21,10 +19,7 @@ test("Using the filter directly", async (t) => { t.is(applyBaseToUrl("../subdir/", "/"), "../subdir/"); t.is(applyBaseToUrl("./subdir/", "/"), "subdir/"); t.is(applyBaseToUrl("http://example.com/", "/"), "http://example.com/"); - t.is( - applyBaseToUrl("http://example.com/test/", "/"), - "http://example.com/test/" - ); + t.is(applyBaseToUrl("http://example.com/test/", "/"), "http://example.com/test/"); // relative url pathprefix is ignored t.is(applyBaseToUrl("/", "../"), "/"); @@ -33,10 +28,7 @@ test("Using the filter directly", async (t) => { t.is(applyBaseToUrl("../subdir/", "../"), "../subdir/"); t.is(applyBaseToUrl("./subdir/", "../"), "subdir/"); t.is(applyBaseToUrl("http://example.com/", "../"), "http://example.com/"); - t.is( - applyBaseToUrl("http://example.com/test/", "../"), - "http://example.com/test/" - ); + t.is(applyBaseToUrl("http://example.com/test/", "../"), "http://example.com/test/"); // with a pathprefix t.is(applyBaseToUrl("/", "/pathprefix/"), "/pathprefix/"); @@ -45,73 +37,31 @@ test("Using the filter directly", async (t) => { t.is(applyBaseToUrl("../subdir/", "/pathprefix/"), "../subdir/"); t.is(applyBaseToUrl("./subdir/", "/pathprefix/"), "subdir/"); t.is(applyBaseToUrl("http://url.com/", "/pathprefix/"), "http://url.com/"); - t.is( - applyBaseToUrl("http://url.com/test/", "/pathprefix/"), - "http://url.com/test/" - ); + t.is(applyBaseToUrl("http://url.com/test/", "/pathprefix/"), "http://url.com/test/"); // with a URL base t.is(applyBaseToUrl("/", "http://example.com/"), "http://example.com/"); - t.is( - applyBaseToUrl("/test/", "http://example.com/"), - "http://example.com/test/" - ); - t.is( - applyBaseToUrl("subdir/", "http://example.com/"), - "http://example.com/subdir/" - ); - t.is( - applyBaseToUrl("../subdir/", "http://example.com/"), - "http://example.com/subdir/" - ); - t.is( - applyBaseToUrl("./subdir/", "http://example.com/"), - "http://example.com/subdir/" - ); - t.is( - applyBaseToUrl("http://url.com/", "http://example.com/"), - "http://url.com/" - ); - t.is( - applyBaseToUrl("http://url.com/test/", "http://example.com/"), - "http://url.com/test/" - ); + t.is(applyBaseToUrl("/test/", "http://example.com/"), "http://example.com/test/"); + t.is(applyBaseToUrl("subdir/", "http://example.com/"), "http://example.com/subdir/"); + t.is(applyBaseToUrl("../subdir/", "http://example.com/"), "http://example.com/subdir/"); + t.is(applyBaseToUrl("./subdir/", "http://example.com/"), "http://example.com/subdir/"); + t.is(applyBaseToUrl("http://url.com/", "http://example.com/"), "http://url.com/"); + t.is(applyBaseToUrl("http://url.com/test/", "http://example.com/"), "http://url.com/test/"); // with a URL base with extra subdirectory - t.is( - applyBaseToUrl("/", "http://example.com/ignored/"), - "http://example.com/" - ); - t.is( - applyBaseToUrl("/test/", "http://example.com/ignored/"), - "http://example.com/test/" - ); - t.is( - applyBaseToUrl("subdir/", "http://example.com/deep/"), - "http://example.com/deep/subdir/" - ); - t.is( - applyBaseToUrl("../subdir/", "http://example.com/deep/"), - "http://example.com/subdir/" - ); - t.is( - applyBaseToUrl("./subdir/", "http://example.com/deep/"), - "http://example.com/deep/subdir/" - ); - t.is( - applyBaseToUrl("http://url.com/", "http://example.com/ignored/"), - "http://url.com/" - ); + t.is(applyBaseToUrl("/", "http://example.com/ignored/"), "http://example.com/"); + t.is(applyBaseToUrl("/test/", "http://example.com/ignored/"), "http://example.com/test/"); + t.is(applyBaseToUrl("subdir/", "http://example.com/deep/"), "http://example.com/deep/subdir/"); + t.is(applyBaseToUrl("../subdir/", "http://example.com/deep/"), "http://example.com/subdir/"); + t.is(applyBaseToUrl("./subdir/", "http://example.com/deep/"), "http://example.com/deep/subdir/"); + t.is(applyBaseToUrl("http://url.com/", "http://example.com/ignored/"), "http://url.com/"); t.is( applyBaseToUrl("http://url.com/test/", "http://example.com/ignored/"), "http://url.com/test/" ); // with a URL base and root pathprefix - t.is( - applyBaseToUrl("/", "http://example.com/", { pathPrefix: "/" }), - "http://example.com/" - ); + t.is(applyBaseToUrl("/", "http://example.com/", { pathPrefix: "/" }), "http://example.com/"); t.is( applyBaseToUrl("/test/", "http://example.com/", { pathPrefix: "/" }), "http://example.com/test/" @@ -295,6 +245,8 @@ test("Using the HTML base plugin (default values)", async (t) => { eleventyConfig.addPlugin(HtmlBasePlugin); }, }); + await elev.initializeConfig(); + elev.setIsVerbose(false); elev.disableLogger(); @@ -332,6 +284,9 @@ test("Using the HTML base plugin with pathPrefix: /test/", async (t) => { eleventyConfig.addPlugin(HtmlBasePlugin); }, }); + + await elev.initializeConfig(); + elev.setIsVerbose(false); elev.disableLogger(); @@ -372,6 +327,8 @@ test("Using the HTML base plugin with pathPrefix: /test/ and base: http://exampl }, }); + await elev.initializeConfig(); + elev.setIsVerbose(false); elev.disableLogger(); @@ -410,6 +367,8 @@ test("Using the HTML base plugin strips extra path in full URL base (default pat }, }); + await elev.initializeConfig(); + elev.setIsVerbose(false); elev.disableLogger(); @@ -450,6 +409,8 @@ test("Using the HTML base plugin strips extra path in full URL base (pathPrefix: }, }); + await elev.initializeConfig(); + elev.setIsVerbose(false); elev.disableLogger(); @@ -490,6 +451,8 @@ test("Opt out of the transform with falsy extensions list", async (t) => { }, }); + await elev.initializeConfig(); + elev.setIsVerbose(false); elev.disableLogger(); @@ -528,6 +491,8 @@ test("Base plugin with permalink: false, #2602", async (t) => { }, }); + await elev.initializeConfig(); + elev.setIsVerbose(false); elev.disableLogger(); diff --git a/test/I18nPluginTest.js b/test/I18nPluginTest.js index 37b79e47b..6e5126ab6 100644 --- a/test/I18nPluginTest.js +++ b/test/I18nPluginTest.js @@ -1,8 +1,7 @@ -const test = require("ava"); -const I18nPlugin = require("../src/Plugins/I18nPlugin"); -const { Comparator, LangUtils } = I18nPlugin; -const Eleventy = require("../src/Eleventy"); -const normalizeNewLines = require("./Util/normalizeNewLines"); +import test from "ava"; +import { Comparator, LangUtils, default as I18nPlugin } from "../src/Plugins/I18nPlugin.js"; +import Eleventy from "../src/Eleventy.js"; +import normalizeNewLines from "./Util/normalizeNewLines.js"; test("Comparator.isLangCode", (t) => { t.is(Comparator.isLangCode(null), false); @@ -29,44 +28,26 @@ test("LangUtils.swapLanguageCode", (t) => { }); test("Comparator.matchLanguageFolder", (t) => { - t.deepEqual(Comparator.matchLanguageFolder("/en/test.hbs", "/es/test.hbs"), [ - "en", - "es", - ]); + t.deepEqual(Comparator.matchLanguageFolder("/en/test.liquid", "/es/test.liquid"), ["en", "es"]); // Note that template extensions and input directory paths are removed upstream by the plugin - t.deepEqual(Comparator.matchLanguageFolder("/en/test", "/es/test"), [ - "en", - "es", - ]); - t.deepEqual(Comparator.matchLanguageFolder("/en-us/test", "/es/test"), [ - "en-us", - "es", - ]); - t.deepEqual(Comparator.matchLanguageFolder("/es-mx/test", "/en-us/test"), [ - "es-mx", - "en-us", - ]); - t.deepEqual(Comparator.matchLanguageFolder("en/test", "es/test"), [ - "en", - "es", - ]); + t.deepEqual(Comparator.matchLanguageFolder("/en/test", "/es/test"), ["en", "es"]); + t.deepEqual(Comparator.matchLanguageFolder("/en-us/test", "/es/test"), ["en-us", "es"]); + t.deepEqual(Comparator.matchLanguageFolder("/es-mx/test", "/en-us/test"), ["es-mx", "en-us"]); + t.deepEqual(Comparator.matchLanguageFolder("en/test", "es/test"), ["en", "es"]); t.deepEqual(Comparator.matchLanguageFolder("en/test", "src/test"), false); t.deepEqual(Comparator.matchLanguageFolder("en/test", "xx/test"), false); // Even though `src` is possibly valid, we only match the first one - t.deepEqual(Comparator.matchLanguageFolder("en/src/test", "es/src/test"), [ - "en", - "es", - ]); + t.deepEqual(Comparator.matchLanguageFolder("en/src/test", "es/src/test"), ["en", "es"]); // invalid first - t.is(Comparator.matchLanguageFolder("/e/test.hbs", "/es/test.hbs"), false); + t.is(Comparator.matchLanguageFolder("/e/test.liquid", "/es/test.liquid"), false); t.is(Comparator.matchLanguageFolder("/n/test", "/es/test"), false); t.is(Comparator.matchLanguageFolder("/eus/test", "/es/test"), false); // invalid second - t.is(Comparator.matchLanguageFolder("/en/test.hbs", "/e/test.hbs"), false); + t.is(Comparator.matchLanguageFolder("/en/test.liquid", "/e/test.liquid"), false); t.is(Comparator.matchLanguageFolder("/en/test", "/e/test"), false); t.is(Comparator.matchLanguageFolder("/en-us/test", "/s/test"), false); @@ -90,14 +71,14 @@ test("contentMap Event from Eleventy", async (t) => { t.is(Object.keys(maps).length, 2); t.deepEqual(maps.urlToInputPath, { "/en/": "./test/stubs-i18n/en/index.liquid", - "/en-us/": "./test/stubs-i18n/en-us/index.11ty.js", + "/en-us/": "./test/stubs-i18n/en-us/index.11ty.cjs", "/es/": "./test/stubs-i18n/es/index.njk", "/non-lang-file/": "./test/stubs-i18n/non-lang-file.njk", }); t.deepEqual(maps.inputPathToUrl, { "./test/stubs-i18n/en/index.liquid": ["/en/"], - "./test/stubs-i18n/en-us/index.11ty.js": ["/en-us/"], + "./test/stubs-i18n/en-us/index.11ty.cjs": ["/en-us/"], "./test/stubs-i18n/es/index.njk": ["/es/"], "./test/stubs-i18n/non-lang-file.njk": ["/non-lang-file/"], }); @@ -109,20 +90,24 @@ test("contentMap Event from Eleventy", async (t) => { }); function getContentFor(results, filename) { - let content = results.filter((entry) => entry.inputPath.endsWith(filename))[0] - .content; + let content = results.filter((entry) => entry.inputPath.endsWith(filename))[0].content; return normalizeNewLines(content.trim()); } -test("errorMode default", async (t) => { +test("errorMode default (strict)", async (t) => { let elev = new Eleventy("./test/stubs-i18n/", "./test/stubs-i18n/_site", { + quietMode: true, config: function (eleventyConfig) { eleventyConfig.addPlugin(I18nPlugin, { + _test: "this is from errorMode default (strict)", defaultLanguage: "en", // errorMode: "allow-fallback" }); }, }); + + // TODO get rid of these? + await elev.initializeConfig(); elev.setIsVerbose(false); elev.disableLogger(); @@ -135,6 +120,7 @@ test("locale_url and locale_links Filters", async (t) => { let elev = new Eleventy("./test/stubs-i18n/", "./test/stubs-i18n/_site", { config: function (eleventyConfig) { eleventyConfig.addPlugin(I18nPlugin, { + _test: "this is from locale_url and locale_links Filters", defaultLanguage: "en", errorMode: "allow-fallback", }); @@ -177,7 +163,7 @@ en` ); t.is( - getContentFor(results, "/en-us/index.11ty.js"), + getContentFor(results, "/en-us/index.11ty.cjs"), `/en-us/ /en-us/ /en-us/ diff --git a/test/JavaScriptDependenciesTest.js b/test/JavaScriptDependenciesTest.js index 3a61fc5c7..b311f1be3 100644 --- a/test/JavaScriptDependenciesTest.js +++ b/test/JavaScriptDependenciesTest.js @@ -1,24 +1,13 @@ -const test = require("ava"); -const JavaScriptDependencies = require("../src/Util/JavaScriptDependencies.js"); +import test from "ava"; +import JavaScriptDependencies from "../src/Util/JavaScriptDependencies.js"; -test("No node_modules", (t) => { - t.deepEqual( - JavaScriptDependencies.getDependencies([ - "./test/stubs-dependency-tree/index.js", - ]), - [ - "./test/stubs-dependency-tree/child.js", - "./test/stubs-dependency-tree/grandchild.js", - ] - ); -}); +test("No node_modules", async (t) => { + let deps = await JavaScriptDependencies.getDependencies([ + "./test/stubs-dependency-tree/index.cjs", + ]); -test("Only node_modules", (t) => { - t.deepEqual( - JavaScriptDependencies.getDependencies( - ["./test/stubs-dependency-tree/index.js"], - true - ), - ["kleur", "lodash"] - ); + t.deepEqual(deps, [ + "./test/stubs-dependency-tree/child.cjs", + "./test/stubs-dependency-tree/grandchild.cjs", + ]); }); diff --git a/test/MergeTest.js b/test/MergeTest.js index 5a589c327..8753f30cc 100644 --- a/test/MergeTest.js +++ b/test/MergeTest.js @@ -1,6 +1,6 @@ -const test = require("ava"); -const Merge = require("../src/Util/Merge"); -const DeepCopy = Merge.DeepCopy; +import test from "ava"; + +import { default as Merge, DeepCopy } from "../src/Util/Merge.js"; test("Shallow Merge", (t) => { t.deepEqual(Merge({}, {}), {}); diff --git a/test/NormalizeServerlessUrlTest.js b/test/NormalizeServerlessUrlTest.js deleted file mode 100644 index fc6b84f25..000000000 --- a/test/NormalizeServerlessUrlTest.js +++ /dev/null @@ -1,10 +0,0 @@ -const test = require("ava"); -const normalizeServerlessUrl = require("../src/Util/NormalizeServerlessUrl"); - -test("serverlessUrl Stringify", (t) => { - // Straight string - t.is(normalizeServerlessUrl("/test/"), "/test/"); - - // transform the trailing wildcard - t.is(normalizeServerlessUrl("/test/*"), "/test/(.*)"); -}); diff --git a/test/PaginationTest.js b/test/PaginationTest.js index c5b29750b..15b6fb627 100644 --- a/test/PaginationTest.js +++ b/test/PaginationTest.js @@ -1,15 +1,18 @@ -const test = require("ava"); -const TemplateData = require("../src/TemplateData"); -const Pagination = require("../src/Plugins/Pagination"); -const TemplateConfig = require("../src/TemplateConfig"); -const FileSystemSearch = require("../src/FileSystemSearch"); +import test from "ava"; +import slugify from "slugify"; -const getNewTemplate = require("./_getNewTemplateForTests"); -const getRenderedTmpls = require("./_getRenderedTemplates"); +import TemplateData from "../src/TemplateData.js"; +import Pagination from "../src/Plugins/Pagination.js"; +import TemplateConfig from "../src/TemplateConfig.js"; +import FileSystemSearch from "../src/FileSystemSearch.js"; +import getNewTemplate from "./_getNewTemplateForTests.js"; +import getRenderedTmpls from "./_getRenderedTemplates.js"; test("No data passed to pagination", async (t) => { let eleventyConfig = new TemplateConfig(); - let tmpl = getNewTemplate( + await eleventyConfig.init(); + + let tmpl = await getNewTemplate( "./test/stubs/paged/notpaged.njk", "./test/stubs/", "./dist", @@ -26,7 +29,9 @@ test("No data passed to pagination", async (t) => { test("No pagination", async (t) => { let eleventyConfig = new TemplateConfig(); - let tmpl = getNewTemplate( + await eleventyConfig.init(); + + let tmpl = await getNewTemplate( "./test/stubs/paged/notpaged.njk", "./test/stubs/", "./dist", @@ -47,7 +52,9 @@ test("No pagination", async (t) => { test("Empty paged data", async (t) => { let eleventyConfig = new TemplateConfig(); - let tmpl = getNewTemplate( + await eleventyConfig.init(); + + let tmpl = await getNewTemplate( "./test/stubs/paged/paged-empty.njk", "./test/stubs/", "./dist", @@ -67,7 +74,9 @@ test("Empty paged data", async (t) => { test("Empty paged data with generatePageOnEmptyData enabled", async (t) => { let eleventyConfig = new TemplateConfig(); - let tmpl = getNewTemplate( + await eleventyConfig.init(); + + let tmpl = await getNewTemplate( "./test/stubs/paged/paged-empty-pageonemptydata.njk", "./test/stubs/", "./dist", @@ -87,7 +96,9 @@ test("Empty paged data with generatePageOnEmptyData enabled", async (t) => { test("Pagination enabled in frontmatter", async (t) => { let eleventyConfig = new TemplateConfig(); - let tmpl = getNewTemplate( + await eleventyConfig.init(); + + let tmpl = await getNewTemplate( "./test/stubs/paged/pagedresolve.njk", "./test/stubs/", "./dist", @@ -111,7 +122,9 @@ test("Pagination enabled in frontmatter", async (t) => { test("Resolve paged data in frontmatter", async (t) => { let eleventyConfig = new TemplateConfig(); - let tmpl = getNewTemplate( + await eleventyConfig.init(); + + let tmpl = await getNewTemplate( "./test/stubs/paged/pagedresolve.njk", "./test/stubs/", "./dist", @@ -130,7 +143,9 @@ test("Resolve paged data in frontmatter", async (t) => { test("Paginate data in frontmatter", async (t) => { let eleventyConfig = new TemplateConfig(); - let tmpl = getNewTemplate( + await eleventyConfig.init(); + + let tmpl = await getNewTemplate( "./test/stubs/paged/pagedinlinedata.njk", "./test/stubs/", "./dist", @@ -158,11 +173,13 @@ test("Paginate data in frontmatter", async (t) => { test("Paginate external data file", async (t) => { let eleventyConfig = new TemplateConfig(); + await eleventyConfig.init(); + let dataObj = new TemplateData("./test/stubs/", eleventyConfig); dataObj.setFileSystemSearch(new FileSystemSearch()); await dataObj.getGlobalData(); - let tmpl = getNewTemplate( + let tmpl = await getNewTemplate( "./test/stubs/paged/paged.njk", "./test/stubs/", "./dist", @@ -193,14 +210,17 @@ test("Paginate external data file", async (t) => { }); test("Slugify test", (t) => { - const slugify = require("slugify"); t.is(slugify("This is a test", { lower: true }), "this-is-a-test"); t.is(slugify("This", { lower: true }), "this"); t.is(slugify("ThisLKSDFDS", { lower: true }), "thislksdfds"); }); test("Permalink with pagination variables", async (t) => { - let tmpl = getNewTemplate("./test/stubs/paged/pagedpermalink.njk", "./test/stubs/", "./dist"); + let tmpl = await getNewTemplate( + "./test/stubs/paged/pagedpermalink.njk", + "./test/stubs/", + "./dist" + ); let data = await tmpl.getData(); let pages = await tmpl.getTemplates(data); @@ -210,7 +230,7 @@ test("Permalink with pagination variables", async (t) => { }); test("Permalink with pagination variables (numeric)", async (t) => { - let tmpl = getNewTemplate( + let tmpl = await getNewTemplate( "./test/stubs/paged/pagedpermalinknumeric.njk", "./test/stubs/", "./dist" @@ -241,7 +261,7 @@ test("Permalink with pagination variables (numeric)", async (t) => { }); test("Permalink with pagination variables (numeric, one indexed)", async (t) => { - let tmpl = getNewTemplate( + let tmpl = await getNewTemplate( "./test/stubs/paged/pagedpermalinknumericoneindexed.njk", "./test/stubs/", "./dist" @@ -268,7 +288,7 @@ test("Permalink with pagination variables (numeric, one indexed)", async (t) => }); test("Permalink first and last page link with pagination variables (numeric)", async (t) => { - let tmpl = getNewTemplate( + let tmpl = await getNewTemplate( "./test/stubs/paged/pagedpermalinknumeric.njk", "./test/stubs/", "./dist" @@ -285,7 +305,7 @@ test("Permalink first and last page link with pagination variables (numeric)", a }); test("Permalink first and last page link with pagination variables (numeric, one indexed)", async (t) => { - let tmpl = getNewTemplate( + let tmpl = await getNewTemplate( "./test/stubs/paged/pagedpermalinknumericoneindexed.njk", "./test/stubs/", "./dist" @@ -302,7 +322,7 @@ test("Permalink first and last page link with pagination variables (numeric, one }); test("Alias to page data", async (t) => { - let tmpl = getNewTemplate("./test/stubs/paged/pagedalias.njk", "./test/stubs/", "./dist"); + let tmpl = await getNewTemplate("./test/stubs/paged/pagedalias.njk", "./test/stubs/", "./dist"); let data = await tmpl.getData(); let pages = await tmpl.getTemplates(data); @@ -315,7 +335,11 @@ test("Alias to page data", async (t) => { }); test("Alias to page data (size 2)", async (t) => { - let tmpl = getNewTemplate("./test/stubs/paged/pagedaliassize2.njk", "./test/stubs/", "./dist"); + let tmpl = await getNewTemplate( + "./test/stubs/paged/pagedaliassize2.njk", + "./test/stubs/", + "./dist" + ); let data = await tmpl.getData(); let pages = await tmpl.getTemplates(data); @@ -328,7 +352,11 @@ test("Alias to page data (size 2)", async (t) => { }); test("Permalink with pagination variables (and an if statement, nunjucks)", async (t) => { - let tmpl = getNewTemplate("./test/stubs/paged/pagedpermalinkif.njk", "./test/stubs/", "./dist"); + let tmpl = await getNewTemplate( + "./test/stubs/paged/pagedpermalinkif.njk", + "./test/stubs/", + "./dist" + ); let data = await tmpl.getData(); let pages = await tmpl.getTemplates(data); @@ -338,7 +366,7 @@ test("Permalink with pagination variables (and an if statement, nunjucks)", asyn }); test("Permalink with pagination variables (and an if statement, liquid)", async (t) => { - let tmpl = getNewTemplate( + let tmpl = await getNewTemplate( "./test/stubs/paged/pagedpermalinkif.liquid", "./test/stubs/", "./dist" @@ -352,7 +380,11 @@ test("Permalink with pagination variables (and an if statement, liquid)", async }); test("Template with Pagination", async (t) => { - let tmpl = getNewTemplate("./test/stubs/paged/pagedpermalinkif.njk", "./test/stubs/", "./dist"); + let tmpl = await getNewTemplate( + "./test/stubs/paged/pagedpermalinkif.njk", + "./test/stubs/", + "./dist" + ); let data = await tmpl.getData(); let outputPath = await tmpl.getOutputPath(data); @@ -364,11 +396,13 @@ test("Template with Pagination", async (t) => { test("Issue 135", async (t) => { let eleventyConfig = new TemplateConfig(); + await eleventyConfig.init(); + let dataObj = new TemplateData("./test/stubs/", eleventyConfig); dataObj.setFileSystemSearch(new FileSystemSearch()); await dataObj.getGlobalData(); - let tmpl = getNewTemplate( + let tmpl = await getNewTemplate( "./test/stubs/issue-135/template.njk", "./test/stubs/", "./dist", @@ -389,7 +423,11 @@ test("Issue 135", async (t) => { }); test("Template with Pagination, getTemplates has page variables set", async (t) => { - let tmpl = getNewTemplate("./test/stubs/paged/pagedpermalinkif.njk", "./test/stubs/", "./dist"); + let tmpl = await getNewTemplate( + "./test/stubs/paged/pagedpermalinkif.njk", + "./test/stubs/", + "./dist" + ); let data = await tmpl.getData(); let templates = await tmpl.getTemplates(data); @@ -401,7 +439,11 @@ test("Template with Pagination, getTemplates has page variables set", async (t) }); test("Template with Pagination, has page variables set", async (t) => { - let tmpl = getNewTemplate("./test/stubs/paged/pagedpermalinkif.njk", "./test/stubs/", "./dist"); + let tmpl = await getNewTemplate( + "./test/stubs/paged/pagedpermalinkif.njk", + "./test/stubs/", + "./dist" + ); let data = await tmpl.getData(); let pages = await getRenderedTmpls(tmpl, data); @@ -413,7 +455,7 @@ test("Template with Pagination, has page variables set", async (t) => { }); test("Page over an object (use keys)", async (t) => { - let tmpl = getNewTemplate("./test/stubs/paged/pagedobject.njk", "./test/stubs/", "./dist"); + let tmpl = await getNewTemplate("./test/stubs/paged/pagedobject.njk", "./test/stubs/", "./dist"); let data = await tmpl.getData(); let pages = await tmpl.getTemplates(data); @@ -433,7 +475,11 @@ test("Page over an object (use keys)", async (t) => { }); test("Page over an object (use values)", async (t) => { - let tmpl = getNewTemplate("./test/stubs/paged/pagedobjectvalues.njk", "./test/stubs/", "./dist"); + let tmpl = await getNewTemplate( + "./test/stubs/paged/pagedobjectvalues.njk", + "./test/stubs/", + "./dist" + ); let data = await tmpl.getData(); let pages = await tmpl.getTemplates(data); @@ -453,7 +499,7 @@ test("Page over an object (use values)", async (t) => { }); test("Page over an object (filtered, array)", async (t) => { - let tmpl = getNewTemplate( + let tmpl = await getNewTemplate( "./test/stubs/paged/pagedobjectfilterarray.njk", "./test/stubs/", "./dist" @@ -474,7 +520,7 @@ test("Page over an object (filtered, array)", async (t) => { }); test("Page over an object (filtered, string)", async (t) => { - let tmpl = getNewTemplate( + let tmpl = await getNewTemplate( "./test/stubs/paged/pagedobjectfilterstring.njk", "./test/stubs/", "./dist" @@ -497,7 +543,9 @@ test("Page over an object (filtered, string)", async (t) => { test("Pagination with deep data merge #147", async (t) => { let eleventyConfig = new TemplateConfig(); - let tmpl = getNewTemplate( + await eleventyConfig.init(); + + let tmpl = await getNewTemplate( "./test/stubs/paged/pagedinlinedata.njk", "./test/stubs/", "./dist", @@ -526,7 +574,7 @@ test("Pagination with deep data merge #147", async (t) => { }); test("Pagination with deep data merge with alias #147", async (t) => { - let tmpl = getNewTemplate("./test/stubs/paged/pagedalias.njk", "./test/stubs/", "./dist"); + let tmpl = await getNewTemplate("./test/stubs/paged/pagedalias.njk", "./test/stubs/", "./dist"); tmpl.config.dynamicPermalinks = true; tmpl.config.deepDataMerge = true; @@ -541,7 +589,7 @@ test("Pagination with deep data merge with alias #147", async (t) => { }); test("Paginate data in frontmatter (reversed)", async (t) => { - let tmpl = getNewTemplate( + let tmpl = await getNewTemplate( "./test/stubs/paged/pagedinlinedata-reverse.njk", "./test/stubs/", "./dist" @@ -564,8 +612,9 @@ test("Paginate data in frontmatter (reversed)", async (t) => { ); }); -test("No circular dependency (does not throw)", (t) => { +test("No circular dependency (does not throw)", async (t) => { let eleventyConfig = new TemplateConfig(); + await eleventyConfig.init(); new Pagination( null, @@ -585,9 +634,11 @@ test("No circular dependency (does not throw)", (t) => { t.true(true); }); -test("Circular dependency (pagination iterates over tag1 but also supplies pages to tag1)", (t) => { - t.throws(() => { +test("Circular dependency (pagination iterates over tag1 but also supplies pages to tag1)", async (t) => { + await t.throwsAsync(async () => { let eleventyConfig = new TemplateConfig(); + await eleventyConfig.init(); + new Pagination( null, { @@ -606,8 +657,10 @@ test("Circular dependency (pagination iterates over tag1 but also supplies pages }); }); -test("Circular dependency but should not error because it uses eleventyExcludeFromCollections", (t) => { +test("Circular dependency but should not error because it uses eleventyExcludeFromCollections", async (t) => { let eleventyConfig = new TemplateConfig(); + await eleventyConfig.init(); + new Pagination( null, { @@ -629,7 +682,7 @@ test("Circular dependency but should not error because it uses eleventyExcludeFr }); test("Pagination `before` Callback", async (t) => { - let tmpl = getNewTemplate("./test/stubs/paged/paged-before.njk", "./test/stubs/", "./dist"); + let tmpl = await getNewTemplate("./test/stubs/paged/paged-before.njk", "./test/stubs/", "./dist"); let data = await tmpl.getData(); let templates = await tmpl.getTemplates(data); @@ -638,7 +691,7 @@ test("Pagination `before` Callback", async (t) => { }); test("Pagination `before` Callback with metadata", async (t) => { - let tmpl = getNewTemplate( + let tmpl = await getNewTemplate( "./test/stubs/paged/paged-before-metadata.njk", "./test/stubs/", "./dist" @@ -650,7 +703,7 @@ test("Pagination `before` Callback with metadata", async (t) => { }); test("Pagination `before` Callback with a Filter", async (t) => { - let tmpl = getNewTemplate( + let tmpl = await getNewTemplate( "./test/stubs/paged/paged-before-filter.njk", "./test/stubs/", "./dist" @@ -663,7 +716,7 @@ test("Pagination `before` Callback with a Filter", async (t) => { }); test("Pagination `before` Callback with `reverse: true` (test order of operations)", async (t) => { - let tmpl = getNewTemplate( + let tmpl = await getNewTemplate( "./test/stubs/paged/paged-before-and-reverse.njk", "./test/stubs/", "./dist" @@ -676,11 +729,13 @@ test("Pagination `before` Callback with `reverse: true` (test order of operation test("Pagination new v0.10.0 href/hrefs", async (t) => { let eleventyConfig = new TemplateConfig(); + await eleventyConfig.init(); + let dataObj = new TemplateData("./test/stubs/", eleventyConfig); dataObj.setFileSystemSearch(new FileSystemSearch()); await dataObj.getGlobalData(); - let tmpl = getNewTemplate( + let tmpl = await getNewTemplate( "./test/stubs/paged/paged.njk", "./test/stubs/", "./dist", @@ -706,11 +761,13 @@ test("Pagination new v0.10.0 href/hrefs", async (t) => { test("Pagination new v0.10.0 page/pages", async (t) => { let eleventyConfig = new TemplateConfig(); + await eleventyConfig.init(); + let dataObj = new TemplateData("./test/stubs/", eleventyConfig); dataObj.setFileSystemSearch(new FileSystemSearch()); await dataObj.getGlobalData(); - let tmpl = getNewTemplate( + let tmpl = await getNewTemplate( "./test/stubs/paged/paged.njk", "./test/stubs/", "./dist", @@ -740,7 +797,7 @@ test("Pagination new v0.10.0 page/pages", async (t) => { }); test("Pagination new v0.10.0 alias", async (t) => { - let tmpl = getNewTemplate("./test/stubs/paged/pagedalias.njk", "./test/stubs/", "./dist"); + let tmpl = await getNewTemplate("./test/stubs/paged/pagedalias.njk", "./test/stubs/", "./dist"); let data = await tmpl.getData(); let templates = await tmpl.getTemplates(data); @@ -750,7 +807,11 @@ test("Pagination new v0.10.0 alias", async (t) => { }); test("Pagination make sure pageNumber is numeric for {{ pageNumber + 1 }} Issue #760", async (t) => { - let tmpl = getNewTemplate("./test/stubs/paged/pagedinlinedata.njk", "./test/stubs/", "./dist"); + let tmpl = await getNewTemplate( + "./test/stubs/paged/pagedinlinedata.njk", + "./test/stubs/", + "./dist" + ); let data = await tmpl.getData(); let templates = await tmpl.getTemplates(data); @@ -760,11 +821,13 @@ test("Pagination make sure pageNumber is numeric for {{ pageNumber + 1 }} Issue test("Pagination mutable global data", async (t) => { let eleventyConfig = new TemplateConfig(); + await eleventyConfig.init(); + let dataObj = new TemplateData("./test/stubs/paged-global-data-mutable/", eleventyConfig); dataObj.setFileSystemSearch(new FileSystemSearch()); await dataObj.getGlobalData(); - let tmpl = getNewTemplate( + let tmpl = await getNewTemplate( "./test/stubs/paged-global-data-mutable/paged-differing-data-set.njk", "./test/stubs/", "./dist", @@ -796,9 +859,11 @@ test("Pagination mutable global data", async (t) => { test("Pagination template/dir data files run once, Issue 919", async (t) => { let eleventyConfig = new TemplateConfig(); + await eleventyConfig.init(); + let dataObj = new TemplateData("./test/stubs-919/", eleventyConfig); - let tmpl = getNewTemplate( + let tmpl = await getNewTemplate( "./test/stubs-919/test.njk", "./test/stubs-919/", "./dist", @@ -816,7 +881,7 @@ test("Pagination template/dir data files run once, Issue 919", async (t) => { }); test("Pagination and eleventyComputed permalink, issue #1555 and #1865", async (t) => { - let tmpl = getNewTemplate( + let tmpl = await getNewTemplate( "./test/stubs/pagination-eleventycomputed-permalink.liquid", "./test/stubs/", "./dist" diff --git a/test/PassthroughCopyBehaviorTest.js b/test/PassthroughCopyBehaviorTest.js index 62897981b..4d9bd618c 100644 --- a/test/PassthroughCopyBehaviorTest.js +++ b/test/PassthroughCopyBehaviorTest.js @@ -1,5 +1,5 @@ -const test = require("ava"); -const checkPassthroughCopyBehavior = require("../src/Util/PassthroughCopyBehaviorCheck"); +import test from "ava"; +import checkPassthroughCopyBehavior from "../src/Util/PassthroughCopyBehaviorCheck.js"; test("Standard use", (t) => { t.is( diff --git a/test/PathNormalizerTest.js b/test/PathNormalizerTest.js index abd29304d..66353bbe6 100644 --- a/test/PathNormalizerTest.js +++ b/test/PathNormalizerTest.js @@ -1,17 +1,12 @@ -const test = require("ava"); -const path = require("path"); -const PathNormalizer = require("../src/Util/PathNormalizer"); +import test from "ava"; +import path from "path"; + +import PathNormalizer from "../src/Util/PathNormalizer.js"; test("PathNormalize Separator", (t) => { t.is(PathNormalizer.normalizeSeperator("."), "."); t.is(PathNormalizer.normalizeSeperator("a/b"), "a/b"); - t.is( - PathNormalizer.normalizeSeperator("a\\b").replace(/\\/g, path.sep), - "a/b" - ); - t.is( - PathNormalizer.normalizeSeperator("a\\b/c").replace(/\\/g, path.sep), - "a/b/c" - ); + t.is(PathNormalizer.normalizeSeperator("a\\b").replace(/\\/g, path.sep), "a/b"); + t.is(PathNormalizer.normalizeSeperator("a\\b/c").replace(/\\/g, path.sep), "a/b/c"); t.is(PathNormalizer.normalizeSeperator(undefined), undefined); }); diff --git a/test/PathPrefixer.js b/test/PathPrefixer.js index 12c9ac478..765d7b501 100644 --- a/test/PathPrefixer.js +++ b/test/PathPrefixer.js @@ -1,6 +1,7 @@ -const test = require("ava"); -const path = require("path"); -const PathPrefixer = require("../src/Util/PathPrefixer"); +import test from "ava"; +import path from "path"; + +import PathPrefixer from "../src/Util/PathPrefixer.js"; test("joinUrlParts", (t) => { t.is(PathPrefixer.joinUrlParts("a"), "a"); @@ -17,18 +18,9 @@ test("joinUrlParts (Windows)", (t) => { t.is(PathPrefixer.joinUrlParts("a\\b".replace(/\\/g, path.sep)), "a/b"); t.is(PathPrefixer.joinUrlParts("\\a\\b".replace(/\\/g, path.sep)), "/a/b"); t.is(PathPrefixer.joinUrlParts("a\\b\\c".replace(/\\/g, path.sep)), "a/b/c"); - t.is( - PathPrefixer.joinUrlParts("a\\b".replace(/\\/g, path.sep), "c"), - "a/b/c" - ); - t.is( - PathPrefixer.joinUrlParts("a\\b\\c\\".replace(/\\/g, path.sep)), - "a/b/c/" - ); - t.is( - PathPrefixer.joinUrlParts("a\\b/c\\".replace(/\\/g, path.sep)), - "a/b/c/" - ); + t.is(PathPrefixer.joinUrlParts("a\\b".replace(/\\/g, path.sep), "c"), "a/b/c"); + t.is(PathPrefixer.joinUrlParts("a\\b\\c\\".replace(/\\/g, path.sep)), "a/b/c/"); + t.is(PathPrefixer.joinUrlParts("a\\b/c\\".replace(/\\/g, path.sep)), "a/b/c/"); }); test("normalizePathPrefix", (t) => { diff --git a/test/PluralizeTest.js b/test/PluralizeTest.js index 95c34b761..db385d2b4 100644 --- a/test/PluralizeTest.js +++ b/test/PluralizeTest.js @@ -1,5 +1,6 @@ -const test = require("ava"); -const pluralize = require("../src/Util/Pluralize"); +import test from "ava"; + +import pluralize from "../src/Util/Pluralize.js"; test("Pluralize", (t) => { t.is(pluralize(0, "test", "tests"), "tests"); diff --git a/test/ProxyWrapTest.js b/test/ProxyWrapTest.js index a4f77e6a1..cbd2c8e6d 100644 --- a/test/ProxyWrapTest.js +++ b/test/ProxyWrapTest.js @@ -1,5 +1,5 @@ -const test = require("ava"); -const { ProxyWrap } = require("../src/Util/ProxyWrap.js"); +import test from "ava"; +import { ProxyWrap } from "../src/Util/ProxyWrap.js"; test("Basic wrap", (t) => { let test = ProxyWrap({}, { a: 1 }); diff --git a/test/SemverCheckTest.js b/test/SemverCheckTest.js index 0ed16cb3d..342932b59 100644 --- a/test/SemverCheckTest.js +++ b/test/SemverCheckTest.js @@ -1,5 +1,5 @@ -const test = require("ava"); -const semver = require("semver"); +import test from "ava"; +import semver from "semver"; test("Satisfies sanity checks with beta/canary", (t) => { t.true( diff --git a/test/ServerlessPluginNetlifyRedirectsTest.js b/test/ServerlessPluginNetlifyRedirectsTest.js deleted file mode 100644 index 6d54973b3..000000000 --- a/test/ServerlessPluginNetlifyRedirectsTest.js +++ /dev/null @@ -1,240 +0,0 @@ -const test = require("ava"); -const NetlifyRedirects = require("../src/Plugins/Serverless/NetlifyRedirects"); - -test("Starter", (t) => { - let r = new NetlifyRedirects("possum"); - let newRedirects = r.getNewRedirects( - { - "/dynamic-path/": "./test.njk", - }, - "/.netlify/builders/" - ); - - t.deepEqual(r.getResults(newRedirects), { - redirects: [ - { - _generated_by_eleventy_serverless: "possum", - force: true, - from: "/dynamic-path/", - status: 200, - to: "/.netlify/builders/possum", - }, - ], - }); -}); - -test("Delete redirects on empty", (t) => { - let r = new NetlifyRedirects("possum"); - let newRedirects = r.getNewRedirects({}, "/.netlify/builders/"); - - t.deepEqual(r.getResults(newRedirects), {}); -}); - -test("Add to Existing Content", (t) => { - let r = new NetlifyRedirects("possum"); - let newRedirects = r.getNewRedirects( - { - "/dynamic-path/": "./test.njk", - }, - "/.netlify/builders/" - ); - - let results = r.getResults(newRedirects, { - redirects: [ - { - force: true, - from: "/admin/*", - status: 200, - }, - ], - }); - - t.deepEqual(results, { - redirects: [ - { - _generated_by_eleventy_serverless: "possum", - force: true, - from: "/dynamic-path/", - status: 200, - to: "/.netlify/builders/possum", - }, - { - force: true, - from: "/admin/*", - status: 200, - }, - ], - }); -}); - -test("Add to Existing Content, exists already—keep order (serverless first)", (t) => { - let r = new NetlifyRedirects("possum"); - let newRedirects = r.getNewRedirects( - { - "/dynamic-path/": "./test.njk", - }, - "/.netlify/builders/" - ); - - let results = r.getResults(newRedirects, { - redirects: [ - { - _generated_by_eleventy_serverless: "possum", - force: true, - from: "/dynamic-path/", - status: 200, - to: "/.netlify/builders/possum", - }, - { - force: true, - from: "/admin/*", - status: 200, - }, - ], - }); - - t.deepEqual(results, { - redirects: [ - { - _generated_by_eleventy_serverless: "possum", - force: true, - from: "/dynamic-path/", - status: 200, - to: "/.netlify/builders/possum", - }, - { - force: true, - from: "/admin/*", - status: 200, - }, - ], - }); -}); - -test("Add to Existing Content, exists already—keep order (serverless second)", (t) => { - let r = new NetlifyRedirects("possum"); - let newRedirects = r.getNewRedirects( - { - "/dynamic-path/": "./test.njk", - }, - "/.netlify/builders/" - ); - - let results = r.getResults(newRedirects, { - redirects: [ - { - force: true, - from: "/admin/*", - status: 200, - }, - { - _generated_by_eleventy_serverless: "possum", - force: true, - from: "/dynamic-path/", - status: 200, - to: "/.netlify/builders/possum", - }, - ], - }); - - t.deepEqual(results, { - redirects: [ - { - force: true, - from: "/admin/*", - status: 200, - }, - { - _generated_by_eleventy_serverless: "possum", - force: true, - from: "/dynamic-path/", - status: 200, - to: "/.netlify/builders/possum", - }, - ], - }); -}); - -test("Remove stale path", (t) => { - let r = new NetlifyRedirects("possum"); - let newRedirects = r.getNewRedirects({}, "/.netlify/builders/"); - - let results = r.getResults(newRedirects, { - redirects: [ - { - force: true, - from: "/admin/*", - status: 200, - }, - { - _generated_by_eleventy_serverless: "possum", - force: true, - from: "/dynamic-path/", - status: 200, - to: "/.netlify/builders/possum", - }, - ], - }); - - t.deepEqual(results, { - redirects: [ - { - force: true, - from: "/admin/*", - status: 200, - }, - ], - }); -}); - -test("Additional test for #2392", (t) => { - let r = new NetlifyRedirects("possum"); - let newRedirects = r.getNewRedirects( - { - "/admin/*": "./test.njk", - }, - "/.netlify/builders/" - ); - - let results = r.getResults(newRedirects, { - redirects: [ - { - force: true, - from: "/admin/*", - to: "/.netlify/builders/possum", - _generated_by_eleventy_serverless: "possum", - status: 200, - conditions: { - Role: ["admin"], - }, - }, - { - force: true, - from: "/admin/*", - to: "/login/", - status: 401, - }, - ], - }); - - t.deepEqual(results, { - redirects: [ - { - force: true, - from: "/admin/*", - to: "/.netlify/builders/possum", - _generated_by_eleventy_serverless: "possum", - status: 200, - conditions: { - Role: ["admin"], - }, - }, - { - force: true, - from: "/admin/*", - to: "/login/", - status: 401, - }, - ], - }); -}); diff --git a/test/ServerlessTest.js b/test/ServerlessTest.js deleted file mode 100644 index a5ce0a08e..000000000 --- a/test/ServerlessTest.js +++ /dev/null @@ -1,35 +0,0 @@ -const test = require("ava"); -const EleventyServerless = require("../src/Serverless"); - -test("Test a one-template markdown render.", async (t) => { - let elev = new EleventyServerless("test1", { - path: "/", - query: {}, - inputDir: "./test/serverless-stubs/", - functionsDir: "./test/serverless-stubs/functions/", - }); - - t.is((await elev.render()).trim(), "

Hi

"); -}); - -test("Test a transform on serverless output.", async (t) => { - let elev = new EleventyServerless("test1", { - path: "/", - query: {}, - inputDir: "./test/serverless-stubs-config/", - functionsDir: "./test/serverless-stubs-config/functions/", - }); - - t.is((await elev.render()).trim(), "

Hi

Hi

"); -}); - -test("Test page.url on serverless output.", async (t) => { - let elev = new EleventyServerless("test1", { - path: "/sample/", - query: {}, - inputDir: "./test/serverless-stubs-page-url/", - functionsDir: "./test/serverless-stubs-page-url/functions/", - }); - - t.is((await elev.render()).trim(), "

/sample/

"); -}); diff --git a/test/ServerlessUrlTest.js b/test/ServerlessUrlTest.js deleted file mode 100644 index a3f0f34be..000000000 --- a/test/ServerlessUrlTest.js +++ /dev/null @@ -1,42 +0,0 @@ -const test = require("ava"); -const ServerlessUrl = require("../src/Filters/ServerlessUrl"); - -test("serverlessUrl Stringify", (t) => { - // Straight string - t.is(ServerlessUrl("/test/"), "/test/"); - - // Has data param but doesn’t use it - t.is(ServerlessUrl("/test/", { id: 1 }), "/test/"); - - // Has data param and does use it - t.is(ServerlessUrl("/test/:id/", { id: 1 }), "/test/1/"); - - // Throws error when it needs a data param - t.throws(() => ServerlessUrl("/test/:id/", {})); -}); - -// https://github.com/11ty/eleventy/issues/2067 -test("serverlessUrl Stringify wildcard", (t) => { - t.is(ServerlessUrl("/test/*", { 0: "" }), "/test/"); - t.is(ServerlessUrl("/test/*", { 0: "ldksjf" }), "/test/ldksjf"); -}); - -test("serverlessUrl Stringify Arrays", (t) => { - // Straight string - t.deepEqual(ServerlessUrl(["/test/", "/testb/"]), ["/test/", "/testb/"]); - - // Has data param but doesn’t use it - t.deepEqual(ServerlessUrl(["/test/", "/testb/"], { id: 1 }), [ - "/test/", - "/testb/", - ]); - - // Has data param and does use it - t.deepEqual(ServerlessUrl(["/test/:id/", "/testb/:id/"], { id: 1 }), [ - "/test/1/", - "/testb/1/", - ]); - - // Throws error when it needs a data param - t.throws(() => ServerlessUrl(["/test/:id/", "/testb/:id/"], {})); -}); diff --git a/test/SortableTest.js b/test/SortableTest.js index a187f1647..455e64f7e 100644 --- a/test/SortableTest.js +++ b/test/SortableTest.js @@ -1,6 +1,7 @@ -const test = require("ava"); -const { DateTime } = require("luxon"); -const Sortable = require("../src/Util/Sortable"); +import test from "ava"; +import { DateTime } from "luxon"; + +import Sortable from "../src/Util/Sortable.js"; test("get Sort Function", (t) => { let s = new Sortable(); diff --git a/test/TemplateCacheTest.js b/test/TemplateCacheTest.js index 5f262a2e7..7182c7713 100644 --- a/test/TemplateCacheTest.js +++ b/test/TemplateCacheTest.js @@ -1,21 +1,21 @@ -const test = require("ava"); -const templateCache = require("../src/TemplateCache"); +import test from "ava"; -const getNewTemplate = require("./_getNewTemplateForTests"); +import templateCache from "../src/TemplateCache.js"; +import getNewTemplate from "./_getNewTemplateForTests.js"; -test("Cache can save templates", (t) => { +test("Cache can save templates", async (t) => { templateCache.clear(); - let tmpl = getNewTemplate("./test/stubs/template.ejs", "./test/stubs/", "./dist"); + let tmpl = await getNewTemplate("./test/stubs/template.liquid", "./test/stubs/", "./dist"); templateCache.add(tmpl); t.is(templateCache.size(), 1); }); -test("TemplateCache clear", (t) => { +test("TemplateCache clear", async (t) => { templateCache.clear(); - let tmpl = getNewTemplate("./test/stubs/template.ejs", "./test/stubs/", "./dist"); + let tmpl = await getNewTemplate("./test/stubs/template.liquid", "./test/stubs/", "./dist"); templateCache.add(tmpl); t.is(templateCache.size(), 1); @@ -23,36 +23,36 @@ test("TemplateCache clear", (t) => { t.is(templateCache.size(), 0); }); -test("TemplateCache has", (t) => { +test("TemplateCache has", async (t) => { templateCache.clear(); - let tmpl = getNewTemplate("./test/stubs/template.ejs", "./test/stubs/", "./dist"); + let tmpl = await getNewTemplate("./test/stubs/template.liquid", "./test/stubs/", "./dist"); templateCache.add(tmpl); // Only TemplateLayout is cached - t.is(templateCache.has("./test/stubs/template.ejs"), false); + t.is(templateCache.has("./test/stubs/template.liquid"), false); }); -test("TemplateCache get success", (t) => { +test("TemplateCache get success", async (t) => { templateCache.clear(); - let tmpl = getNewTemplate("./test/stubs/template.ejs", "./test/stubs/", "./dist"); + let tmpl = await getNewTemplate("./test/stubs/template.liquid", "./test/stubs/", "./dist"); templateCache.add(tmpl); // Only TemplateLayout is cached t.throws(() => { - templateCache.get("./test/stubs/template.ejs"); + templateCache.get("./test/stubs/template.liquid"); }); }); -test("TemplateCache get fail", (t) => { +test("TemplateCache get fail", async (t) => { templateCache.clear(); - let tmpl = getNewTemplate("./test/stubs/template.ejs", "./test/stubs/", "./dist"); + let tmpl = await getNewTemplate("./test/stubs/template.liquid", "./test/stubs/", "./dist"); templateCache.add(tmpl); t.throws(function () { - templateCache.get("./test/stubs/template298374892.ejs"); + templateCache.get("./test/stubs/template298374892.liquid"); }); }); diff --git a/test/TemplateCollectionTest.js b/test/TemplateCollectionTest.js index 28c8de56b..698b4ac93 100644 --- a/test/TemplateCollectionTest.js +++ b/test/TemplateCollectionTest.js @@ -1,20 +1,13 @@ -const test = require("ava"); -const multimatch = require("multimatch"); -const Template = require("../src/Template"); -const TemplateConfig = require("../src/TemplateConfig"); -const Collection = require("../src/TemplateCollection"); -const Sortable = require("../src/Util/Sortable"); -const getNewTemplateForTests = require("../test/_getNewTemplateForTests"); +import test from "ava"; +import multimatch from "multimatch"; + +import TemplateConfig from "../src/TemplateConfig.js"; +import Collection from "../src/TemplateCollection.js"; +import Sortable from "../src/Util/Sortable.js"; +import getNewTemplateForTests from "../test/_getNewTemplateForTests.js"; function getNewTemplate(filename, input, output, eleventyConfig) { - return getNewTemplateForTests( - filename, - input, - output, - null, - null, - eleventyConfig - ); + return getNewTemplateForTests(filename, input, output, null, null, eleventyConfig); } function getNewTemplateByNumber(num, eleventyConfig) { @@ -39,9 +32,11 @@ async function addTemplate(collection, template) { test("Basic setup", async (t) => { let eleventyConfig = new TemplateConfig(); - let tmpl1 = getNewTemplateByNumber(1, eleventyConfig); - let tmpl2 = getNewTemplateByNumber(2, eleventyConfig); - let tmpl3 = getNewTemplateByNumber(3, eleventyConfig); + await eleventyConfig.init(); + + let tmpl1 = await getNewTemplateByNumber(1, eleventyConfig); + let tmpl2 = await getNewTemplateByNumber(2, eleventyConfig); + let tmpl3 = await getNewTemplateByNumber(3, eleventyConfig); let c = new Collection(); await addTemplate(c, tmpl1); @@ -53,9 +48,11 @@ test("Basic setup", async (t) => { test("sortFunctionDate", async (t) => { let eleventyConfig = new TemplateConfig(); - let tmpl1 = getNewTemplateByNumber(1, eleventyConfig); - let tmpl4 = getNewTemplateByNumber(4, eleventyConfig); - let tmpl5 = getNewTemplateByNumber(5, eleventyConfig); + await eleventyConfig.init(); + + let tmpl1 = await getNewTemplateByNumber(1, eleventyConfig); + let tmpl4 = await getNewTemplateByNumber(4, eleventyConfig); + let tmpl5 = await getNewTemplateByNumber(5, eleventyConfig); let c = new Collection(); await addTemplate(c, tmpl1); @@ -71,9 +68,11 @@ test("sortFunctionDate", async (t) => { test("sortFunctionDateInputPath", async (t) => { let eleventyConfig = new TemplateConfig(); - let tmpl1 = getNewTemplateByNumber(1, eleventyConfig); - let tmpl4 = getNewTemplateByNumber(4, eleventyConfig); - let tmpl5 = getNewTemplateByNumber(5, eleventyConfig); + await eleventyConfig.init(); + + let tmpl1 = await getNewTemplateByNumber(1, eleventyConfig); + let tmpl4 = await getNewTemplateByNumber(4, eleventyConfig); + let tmpl5 = await getNewTemplateByNumber(5, eleventyConfig); let c = new Collection(); await addTemplate(c, tmpl1); @@ -89,9 +88,11 @@ test("sortFunctionDateInputPath", async (t) => { test("getFilteredByTag", async (t) => { let eleventyConfig = new TemplateConfig(); - let tmpl1 = getNewTemplateByNumber(1, eleventyConfig); - let tmpl2 = getNewTemplateByNumber(2, eleventyConfig); - let tmpl3 = getNewTemplateByNumber(3, eleventyConfig); + await eleventyConfig.init(); + + let tmpl1 = await getNewTemplateByNumber(1, eleventyConfig); + let tmpl2 = await getNewTemplateByNumber(2, eleventyConfig); + let tmpl3 = await getNewTemplateByNumber(3, eleventyConfig); let c = new Collection(); await addTemplate(c, tmpl1); @@ -115,9 +116,11 @@ test("getFilteredByTag", async (t) => { test("getFilteredByTag (added out of order, sorted)", async (t) => { let eleventyConfig = new TemplateConfig(); - let tmpl1 = getNewTemplateByNumber(1, eleventyConfig); - let tmpl2 = getNewTemplateByNumber(2, eleventyConfig); - let tmpl3 = getNewTemplateByNumber(3, eleventyConfig); + await eleventyConfig.init(); + + let tmpl1 = await getNewTemplateByNumber(1, eleventyConfig); + let tmpl2 = await getNewTemplateByNumber(2, eleventyConfig); + let tmpl3 = await getNewTemplateByNumber(3, eleventyConfig); let c = new Collection(); await addTemplate(c, tmpl3); @@ -142,9 +145,11 @@ test("getFilteredByTag (added out of order, sorted)", async (t) => { test("getFilteredByTags", async (t) => { let eleventyConfig = new TemplateConfig(); - let tmpl1 = getNewTemplateByNumber(1, eleventyConfig); - let tmpl2 = getNewTemplateByNumber(2, eleventyConfig); - let tmpl3 = getNewTemplateByNumber(3, eleventyConfig); + await eleventyConfig.init(); + + let tmpl1 = await getNewTemplateByNumber(1, eleventyConfig); + let tmpl2 = await getNewTemplateByNumber(2, eleventyConfig); + let tmpl3 = await getNewTemplateByNumber(3, eleventyConfig); let c = new Collection(); await addTemplate(c, tmpl1); @@ -167,9 +172,11 @@ test("getFilteredByTags", async (t) => { test("getFilteredByTags (added out of order, sorted)", async (t) => { let eleventyConfig = new TemplateConfig(); - let tmpl1 = getNewTemplateByNumber(1, eleventyConfig); - let tmpl2 = getNewTemplateByNumber(2, eleventyConfig); - let tmpl3 = getNewTemplateByNumber(3, eleventyConfig); + await eleventyConfig.init(); + + let tmpl1 = await getNewTemplateByNumber(1, eleventyConfig); + let tmpl2 = await getNewTemplateByNumber(2, eleventyConfig); + let tmpl3 = await getNewTemplateByNumber(3, eleventyConfig); let c = new Collection(); await addTemplate(c, tmpl3); @@ -195,9 +202,11 @@ test("getFilteredByTags (added out of order, sorted)", async (t) => { test("getFilteredByGlob", async (t) => { let eleventyConfig = new TemplateConfig(); - let tmpl1 = getNewTemplateByNumber(1, eleventyConfig); - let tmpl6 = getNewTemplateByNumber(6, eleventyConfig); - let tmpl7 = getNewTemplateByNumber(7, eleventyConfig); + await eleventyConfig.init(); + + let tmpl1 = await getNewTemplateByNumber(1, eleventyConfig); + let tmpl6 = await getNewTemplateByNumber(6, eleventyConfig); + let tmpl7 = await getNewTemplateByNumber(7, eleventyConfig); let c = new Collection(); await addTemplate(c, tmpl1); @@ -211,9 +220,11 @@ test("getFilteredByGlob", async (t) => { test("getFilteredByGlob no dash dot", async (t) => { let eleventyConfig = new TemplateConfig(); - let tmpl1 = getNewTemplateByNumber(1, eleventyConfig); - let tmpl6 = getNewTemplateByNumber(6, eleventyConfig); - let tmpl7 = getNewTemplateByNumber(7, eleventyConfig); + await eleventyConfig.init(); + + let tmpl1 = await getNewTemplateByNumber(1, eleventyConfig); + let tmpl6 = await getNewTemplateByNumber(6, eleventyConfig); + let tmpl7 = await getNewTemplateByNumber(7, eleventyConfig); let c = new Collection(); await addTemplate(c, tmpl1); @@ -232,14 +243,15 @@ test("getFilteredByGlob no dash dot", async (t) => { test("partial match on tag string, issue 95", async (t) => { let eleventyConfig = new TemplateConfig(); + await eleventyConfig.init(); - let cat = getNewTemplate( + let cat = await getNewTemplate( "./test/stubs/issue-95/cat.md", "./test/stubs/", "./test/stubs/_site", eleventyConfig ); - let notacat = getNewTemplate( + let notacat = await getNewTemplate( "./test/stubs/issue-95/notacat.md", "./test/stubs/", "./test/stubs/_site", @@ -256,17 +268,11 @@ test("partial match on tag string, issue 95", async (t) => { test("multimatch assumptions, issue #127", async (t) => { t.deepEqual( - multimatch( - ["src/bookmarks/test.md"], - "**/+(bookmarks|posts|screencasts)/**/!(index)*.md" - ), + multimatch(["src/bookmarks/test.md"], "**/+(bookmarks|posts|screencasts)/**/!(index)*.md"), ["src/bookmarks/test.md"] ); t.deepEqual( - multimatch( - ["./src/bookmarks/test.md"], - "./**/+(bookmarks|posts|screencasts)/**/!(index)*.md" - ), + multimatch(["./src/bookmarks/test.md"], "./**/+(bookmarks|posts|screencasts)/**/!(index)*.md"), ["./src/bookmarks/test.md"] ); @@ -274,22 +280,21 @@ test("multimatch assumptions, issue #127", async (t) => { let globs = c.getGlobs("**/+(bookmarks|posts|screencasts)/**/!(index)*.md"); t.deepEqual(globs, ["./**/+(bookmarks|posts|screencasts)/**/!(index)*.md"]); - t.deepEqual(multimatch(["./src/bookmarks/test.md"], globs), [ - "./src/bookmarks/test.md", - ]); + t.deepEqual(multimatch(["./src/bookmarks/test.md"], globs), ["./src/bookmarks/test.md"]); t.deepEqual(multimatch(["./src/bookmarks/index.md"], globs), []); t.deepEqual(multimatch(["./src/bookmarks/index2.md"], globs), []); - t.deepEqual( - multimatch(["./src/_content/bookmarks/2018-03-27-git-message.md"], globs), - ["./src/_content/bookmarks/2018-03-27-git-message.md"] - ); + t.deepEqual(multimatch(["./src/_content/bookmarks/2018-03-27-git-message.md"], globs), [ + "./src/_content/bookmarks/2018-03-27-git-message.md", + ]); }); test("Sort in place (issue #352)", async (t) => { let eleventyConfig = new TemplateConfig(); - let tmpl1 = getNewTemplateByNumber(1, eleventyConfig); - let tmpl4 = getNewTemplateByNumber(4, eleventyConfig); - let tmpl5 = getNewTemplateByNumber(5, eleventyConfig); + await eleventyConfig.init(); + + let tmpl1 = await getNewTemplateByNumber(1, eleventyConfig); + let tmpl4 = await getNewTemplateByNumber(4, eleventyConfig); + let tmpl5 = await getNewTemplateByNumber(5, eleventyConfig); let c = new Collection(); await addTemplate(c, tmpl1); diff --git a/test/TemplateConfigTest.js b/test/TemplateConfigTest.js index dccb7b7ae..8fd07ea47 100644 --- a/test/TemplateConfigTest.js +++ b/test/TemplateConfigTest.js @@ -1,170 +1,126 @@ -const test = require("ava"); -const md = require("markdown-it"); -const TemplateConfig = require("../src/TemplateConfig"); +import test from "ava"; +import md from "markdown-it"; + +import TemplateConfig from "../src/TemplateConfig.js"; +import defaultConfig from "../src/defaultConfig.js"; test("Template Config local config overrides base config", async (t) => { - let templateCfg = new TemplateConfig( - require("../src/defaultConfig.js"), - "./test/stubs/config.js" - ); + let templateCfg = new TemplateConfig(defaultConfig, "./test/stubs/config.cjs"); + await templateCfg.init(); + let cfg = templateCfg.getConfig(); - t.is(cfg.markdownTemplateEngine, "ejs"); + t.is(cfg.markdownTemplateEngine, "njk"); t.is(cfg.templateFormats.join(","), "md,njk"); // merged, not overwritten t.true(Object.keys(cfg.keys).length > 1); - t.truthy(Object.keys(cfg.handlebarsHelpers).length); t.truthy(Object.keys(cfg.nunjucksFilters).length); t.is(Object.keys(cfg.transforms).length, 1); t.is( - cfg.transforms.prettyHtml( - `
`, - "test.html" - ), + cfg.transforms.prettyHtml(`
`, "test.html"), `
-` +`, ); }); -test("Add liquid tag", (t) => { - let templateCfg = new TemplateConfig( - require("../src/defaultConfig.js"), - "./test/stubs/config.js" - ); +test("Add liquid tag", async (t) => { + let templateCfg = new TemplateConfig(defaultConfig, "./test/stubs/config.cjs"); templateCfg.userConfig.addLiquidTag("myTagName", function () {}); + + await templateCfg.init(); + let cfg = templateCfg.getConfig(); t.not(Object.keys(cfg.liquidTags).indexOf("myTagName"), -1); }); -test("Add nunjucks tag", (t) => { - let templateCfg = new TemplateConfig( - require("../src/defaultConfig.js"), - "./test/stubs/config.js" - ); +test("Add nunjucks tag", async (t) => { + let templateCfg = new TemplateConfig(defaultConfig, "./test/stubs/config.cjs"); templateCfg.userConfig.addNunjucksTag("myNunjucksTag", function () {}); + + await templateCfg.init(); + let cfg = templateCfg.getConfig(); t.not(Object.keys(cfg.nunjucksTags).indexOf("myNunjucksTag"), -1); }); -test("Add nunjucks global", (t) => { - let templateCfg = new TemplateConfig( - require("../src/defaultConfig.js"), - "./test/stubs/config.js" - ); +test("Add nunjucks global", async (t) => { + let templateCfg = new TemplateConfig(defaultConfig, "./test/stubs/config.cjs"); templateCfg.userConfig.addNunjucksGlobal("myNunjucksGlobal1", function () {}); templateCfg.userConfig.addNunjucksGlobal("myNunjucksGlobal2", 42); + await templateCfg.init(); + let cfg = templateCfg.getConfig(); t.not(Object.keys(cfg.nunjucksGlobals).indexOf("myNunjucksGlobal1"), -1); t.not(Object.keys(cfg.nunjucksGlobals).indexOf("myNunjucksGlobal2"), -1); }); -test("Add liquid filter", (t) => { - let templateCfg = new TemplateConfig( - require("../src/defaultConfig.js"), - "./test/stubs/config.js" - ); - templateCfg.userConfig.addLiquidFilter( - "myFilterName", - function (liquidEngine) { - return {}; - } - ); - - let cfg = templateCfg.getConfig(); - t.not(Object.keys(cfg.liquidFilters).indexOf("myFilterName"), -1); -}); +test("Add liquid filter", async (t) => { + let templateCfg = new TemplateConfig(defaultConfig, "./test/stubs/config.cjs"); + templateCfg.userConfig.addLiquidFilter("myFilterName", function (liquidEngine) { + return {}; + }); -test("Add handlebars helper", (t) => { - let templateCfg = new TemplateConfig( - require("../src/defaultConfig.js"), - "./test/stubs/config.js" - ); - templateCfg.userConfig.addHandlebarsHelper("myHelperName", function () {}); + await templateCfg.init(); let cfg = templateCfg.getConfig(); - t.not(Object.keys(cfg.handlebarsHelpers).indexOf("myHelperName"), -1); + t.not(Object.keys(cfg.liquidFilters).indexOf("myFilterName"), -1); }); -test("Add nunjucks filter", (t) => { - let templateCfg = new TemplateConfig( - require("../src/defaultConfig.js"), - "./test/stubs/config.js" - ); +test("Add nunjucks filter", async (t) => { + let templateCfg = new TemplateConfig(defaultConfig, "./test/stubs/config.cjs"); templateCfg.userConfig.addNunjucksFilter("myFilterName", function () {}); + await templateCfg.init(); + let cfg = templateCfg.getConfig(); t.not(Object.keys(cfg.nunjucksFilters).indexOf("myFilterName"), -1); }); -test("Add universal filter", (t) => { - let templateCfg = new TemplateConfig( - require("../src/defaultConfig.js"), - "./test/stubs/config.js" - ); +test("Add universal filter", async (t) => { + let templateCfg = new TemplateConfig(defaultConfig, "./test/stubs/config.cjs"); templateCfg.userConfig.addFilter("myFilterName", function () {}); + await templateCfg.init(); + let cfg = templateCfg.getConfig(); t.not(Object.keys(cfg.liquidFilters).indexOf("myFilterName"), -1); - t.not(Object.keys(cfg.handlebarsHelpers).indexOf("myFilterName"), -1); t.not(Object.keys(cfg.nunjucksFilters).indexOf("myFilterName"), -1); }); -test("Add namespaced universal filter", (t) => { - let templateCfg = new TemplateConfig( - require("../src/defaultConfig.js"), - "./test/stubs/config.js" - ); +test("Add namespaced universal filter", async (t) => { + let templateCfg = new TemplateConfig(defaultConfig, "./test/stubs/config.cjs"); templateCfg.userConfig.namespace("testNamespace", function () { templateCfg.userConfig.addFilter("MyFilterName", function () {}); }); + await templateCfg.init(); + let cfg = templateCfg.getConfig(); - t.not( - Object.keys(cfg.liquidFilters).indexOf("testNamespaceMyFilterName"), - -1 - ); - t.not( - Object.keys(cfg.handlebarsHelpers).indexOf("testNamespaceMyFilterName"), - -1 - ); - t.not( - Object.keys(cfg.nunjucksFilters).indexOf("testNamespaceMyFilterName"), - -1 - ); + t.not(Object.keys(cfg.liquidFilters).indexOf("testNamespaceMyFilterName"), -1); + t.not(Object.keys(cfg.nunjucksFilters).indexOf("testNamespaceMyFilterName"), -1); }); -test("Add namespaced universal filter using underscore", (t) => { - let templateCfg = new TemplateConfig( - require("../src/defaultConfig.js"), - "./test/stubs/config.js" - ); +test("Add namespaced universal filter using underscore", async (t) => { + let templateCfg = new TemplateConfig(defaultConfig, "./test/stubs/config.cjs"); templateCfg.userConfig.namespace("testNamespace_", function () { templateCfg.userConfig.addFilter("myFilterName", function () {}); }); + await templateCfg.init(); + let cfg = templateCfg.getConfig(); - t.not( - Object.keys(cfg.liquidFilters).indexOf("testNamespace_myFilterName"), - -1 - ); - t.not( - Object.keys(cfg.handlebarsHelpers).indexOf("testNamespace_myFilterName"), - -1 - ); - t.not( - Object.keys(cfg.nunjucksFilters).indexOf("testNamespace_myFilterName"), - -1 - ); + t.not(Object.keys(cfg.liquidFilters).indexOf("testNamespace_myFilterName"), -1); + t.not(Object.keys(cfg.nunjucksFilters).indexOf("testNamespace_myFilterName"), -1); }); -test("Add namespaced plugin", (t) => { +test("Add namespaced plugin", async (t) => { let templateCfg = new TemplateConfig(); templateCfg.userConfig.namespace("testNamespace", function () { @@ -173,65 +129,42 @@ test("Add namespaced plugin", (t) => { }); }); + await templateCfg.init(); + let cfg = templateCfg.getConfig(); - t.not( - Object.keys(cfg.liquidFilters).indexOf("testNamespaceMyFilterName"), - -1 - ); - t.not( - Object.keys(cfg.handlebarsHelpers).indexOf("testNamespaceMyFilterName"), - -1 - ); - t.not( - Object.keys(cfg.nunjucksFilters).indexOf("testNamespaceMyFilterName"), - -1 - ); + t.not(Object.keys(cfg.liquidFilters).indexOf("testNamespaceMyFilterName"), -1); + t.not(Object.keys(cfg.nunjucksFilters).indexOf("testNamespaceMyFilterName"), -1); }); -test("Add namespaced plugin using underscore", (t) => { - let templateCfg = new TemplateConfig( - require("../src/defaultConfig.js"), - "./test/stubs/config.js" - ); +test("Add namespaced plugin using underscore", async (t) => { + let templateCfg = new TemplateConfig(defaultConfig, "./test/stubs/config.cjs"); templateCfg.userConfig.namespace("testNamespace_", function () { templateCfg.userConfig.addPlugin(function (config) { config.addFilter("myFilterName", function () {}); }); }); + await templateCfg.init(); + let cfg = templateCfg.getConfig(); - t.not( - Object.keys(cfg.liquidFilters).indexOf("testNamespace_myFilterName"), - -1 - ); - t.not( - Object.keys(cfg.handlebarsHelpers).indexOf("testNamespace_myFilterName"), - -1 - ); - t.not( - Object.keys(cfg.nunjucksFilters).indexOf("testNamespace_myFilterName"), - -1 - ); + t.not(Object.keys(cfg.liquidFilters).indexOf("testNamespace_myFilterName"), -1); + t.not(Object.keys(cfg.nunjucksFilters).indexOf("testNamespace_myFilterName"), -1); }); -test("Empty namespace", (t) => { - let templateCfg = new TemplateConfig( - require("../src/defaultConfig.js"), - "./test/stubs/config.js" - ); +test("Empty namespace", async (t) => { + let templateCfg = new TemplateConfig(defaultConfig, "./test/stubs/config.cjs"); templateCfg.userConfig.namespace("", function () { templateCfg.userConfig.addNunjucksFilter("myFilterName", function () {}); }); + await templateCfg.init(); + let cfg = templateCfg.getConfig(); t.not(Object.keys(cfg.nunjucksFilters).indexOf("myFilterName"), -1); }); -test("Nested Empty Inner namespace", (t) => { - let templateCfg = new TemplateConfig( - require("../src/defaultConfig.js"), - "./test/stubs/config.js" - ); +test("Nested Empty Inner namespace", async (t) => { + let templateCfg = new TemplateConfig(defaultConfig, "./test/stubs/config.cjs"); templateCfg.userConfig.namespace("testNs", function () { templateCfg.userConfig.namespace("", function () { @@ -239,21 +172,22 @@ test("Nested Empty Inner namespace", (t) => { }); }); + await templateCfg.init(); + let cfg = templateCfg.getConfig(); t.not(Object.keys(cfg.nunjucksFilters).indexOf("testNsmyFilterName"), -1); }); -test("Nested Empty Outer namespace", (t) => { - let templateCfg = new TemplateConfig( - require("../src/defaultConfig.js"), - "./test/stubs/config.js" - ); +test("Nested Empty Outer namespace", async (t) => { + let templateCfg = new TemplateConfig(defaultConfig, "./test/stubs/config.cjs"); templateCfg.userConfig.namespace("", function () { templateCfg.userConfig.namespace("testNs", function () { templateCfg.userConfig.addNunjucksFilter("myFilterName", function () {}); }); }); + await templateCfg.init(); + let cfg = templateCfg.getConfig(); t.not(Object.keys(cfg.nunjucksFilters).indexOf("testNsmyFilterName"), -1); }); @@ -261,24 +195,20 @@ test("Nested Empty Outer namespace", (t) => { // important for backwards compatibility with old // `module.exports = function (eleventyConfig, pluginNamespace) {` // plugin code -test("Non-string namespaces are ignored", (t) => { - let templateCfg = new TemplateConfig( - require("../src/defaultConfig.js"), - "./test/stubs/config.js" - ); +test("Non-string namespaces are ignored", async (t) => { + let templateCfg = new TemplateConfig(defaultConfig, "./test/stubs/config.cjs"); templateCfg.userConfig.namespace(["lkdsjflksd"], function () { templateCfg.userConfig.addNunjucksFilter("myFilterName", function () {}); }); + await templateCfg.init(); + let cfg = templateCfg.getConfig(); t.not(Object.keys(cfg.nunjucksFilters).indexOf("myFilterName"), -1); }); -test(".addPlugin oddity: I don’t think pluginNamespace was ever passed in here, but we don’t want this to break", (t) => { - let templateCfg = new TemplateConfig( - require("../src/defaultConfig.js"), - "./test/stubs/config.js" - ); +test(".addPlugin oddity: I don’t think pluginNamespace was ever passed in here, but we don’t want this to break", async (t) => { + let templateCfg = new TemplateConfig(defaultConfig, "./test/stubs/config.cjs"); templateCfg.userConfig.addPlugin(function (eleventyConfig, pluginNamespace) { eleventyConfig.namespace(pluginNamespace, () => { @@ -286,136 +216,125 @@ test(".addPlugin oddity: I don’t think pluginNamespace was ever passed in here }); }); + await templateCfg.init(); + let cfg = templateCfg.getConfig(); t.not(Object.keys(cfg.nunjucksFilters).indexOf("myFilterName"), -1); }); -test("Test url universal filter with custom pathPrefix (no slash)", (t) => { - let templateCfg = new TemplateConfig( - require("../src/defaultConfig.js"), - "./test/stubs/config.js" - ); +test("Test url universal filter with custom pathPrefix (no slash)", async (t) => { + let templateCfg = new TemplateConfig(defaultConfig, "./test/stubs/config.cjs"); templateCfg.setPathPrefix("/testdirectory/"); + + await templateCfg.init(); + let cfg = templateCfg.getConfig(); t.is(cfg.pathPrefix, "/testdirectory/"); }); -test("setTemplateFormats(string)", (t) => { - let templateCfg = new TemplateConfig( - require("../src/defaultConfig.js"), - "./test/stubs/config.js" - ); +test("setTemplateFormats(string)", async (t) => { + let templateCfg = new TemplateConfig(defaultConfig, "./test/stubs/config.cjs"); // 0.11.0 removes dupes - templateCfg.userConfig.setTemplateFormats("ejs,njk, liquid, njk"); + templateCfg.userConfig.setTemplateFormats("njk, liquid, njk"); + + await templateCfg.init(); let cfg = templateCfg.getConfig(); - t.deepEqual(cfg.templateFormats, ["ejs", "njk", "liquid"]); + t.deepEqual(cfg.templateFormats, ["njk", "liquid"]); }); -test("setTemplateFormats(array)", (t) => { - let templateCfg = new TemplateConfig( - require("../src/defaultConfig.js"), - "./test/stubs/config.js" - ); - templateCfg.userConfig.setTemplateFormats(["ejs", "njk", "liquid"]); +test("setTemplateFormats(array)", async (t) => { + let templateCfg = new TemplateConfig(defaultConfig, "./test/stubs/config.cjs"); + templateCfg.userConfig.setTemplateFormats(["njk", "liquid"]); + + await templateCfg.init(); let cfg = templateCfg.getConfig(); - t.deepEqual(cfg.templateFormats, ["ejs", "njk", "liquid"]); + t.deepEqual(cfg.templateFormats, ["njk", "liquid"]); }); -test("setTemplateFormats(array, size 1)", (t) => { - let templateCfg = new TemplateConfig( - require("../src/defaultConfig.js"), - "./test/stubs/config.js" - ); +test("setTemplateFormats(array, size 1)", async (t) => { + let templateCfg = new TemplateConfig(defaultConfig, "./test/stubs/config.cjs"); templateCfg.userConfig.setTemplateFormats(["liquid"]); + await templateCfg.init(); + let cfg = templateCfg.getConfig(); t.deepEqual(cfg.templateFormats, ["liquid"]); }); -test("setTemplateFormats(empty array)", (t) => { - let templateCfg = new TemplateConfig( - require("../src/defaultConfig.js"), - "./test/stubs/config.js" - ); +test("setTemplateFormats(empty array)", async (t) => { + let templateCfg = new TemplateConfig(defaultConfig, "./test/stubs/config.cjs"); templateCfg.userConfig.setTemplateFormats([]); + await templateCfg.init(); + let cfg = templateCfg.getConfig(); t.deepEqual(cfg.templateFormats, []); }); -test("setTemplateFormats(null)", (t) => { - let templateCfg = new TemplateConfig( - require("../src/defaultConfig.js"), - "./test/stubs/config.js" - ); +test("setTemplateFormats(null)", async (t) => { + let templateCfg = new TemplateConfig(defaultConfig, "./test/stubs/config.cjs"); templateCfg.userConfig.setTemplateFormats(null); + await templateCfg.init(); + let cfg = templateCfg.getConfig(); t.deepEqual(cfg.templateFormats.sort(), ["md", "njk"]); }); -test("setTemplateFormats(undefined)", (t) => { - let templateCfg = new TemplateConfig( - require("../src/defaultConfig.js"), - "./test/stubs/config.js" - ); +test("setTemplateFormats(undefined)", async (t) => { + let templateCfg = new TemplateConfig(defaultConfig, "./test/stubs/config.cjs"); templateCfg.userConfig.setTemplateFormats(undefined); + await templateCfg.init(); + let cfg = templateCfg.getConfig(); t.deepEqual(cfg.templateFormats.sort(), ["md", "njk"]); }); -test("multiple setTemplateFormats calls", (t) => { - let templateCfg = new TemplateConfig( - require("../src/defaultConfig.js"), - "./test/stubs/config.js" - ); +test("multiple setTemplateFormats calls", async (t) => { + let templateCfg = new TemplateConfig(defaultConfig, "./test/stubs/config.cjs"); templateCfg.userConfig.setTemplateFormats("njk"); templateCfg.userConfig.setTemplateFormats("pug"); + await templateCfg.init(); + let cfg = templateCfg.getConfig(); t.deepEqual(cfg.templateFormats, ["pug"]); }); -test("addTemplateFormats()", (t) => { - let templateCfg = new TemplateConfig( - require("../src/defaultConfig.js"), - "./test/stubs/config.js" - ); +test("addTemplateFormats()", async (t) => { + let templateCfg = new TemplateConfig(defaultConfig, "./test/stubs/config.cjs"); templateCfg.userConfig.addTemplateFormats("vue"); + await templateCfg.init(); let cfg = templateCfg.getConfig(); // should have ALL of the original defaults t.deepEqual(cfg.templateFormats, ["md", "njk", "vue"]); }); -test("both setTemplateFormats and addTemplateFormats", (t) => { +test("both setTemplateFormats and addTemplateFormats", async (t) => { // Template Formats can come from three places // defaultConfig.js config API (not used yet) // defaultConfig.js config return object // project config file config API // project config file config return object - let templateCfg = new TemplateConfig( - require("../src/defaultConfig.js"), - "./test/stubs/config.js" - ); + let templateCfg = new TemplateConfig(defaultConfig, "./test/stubs/config.cjs"); templateCfg.userConfig.addTemplateFormats("vue"); templateCfg.userConfig.setTemplateFormats("pug"); + await templateCfg.init(); let cfg = templateCfg.getConfig(); t.deepEqual(cfg.templateFormats, ["pug", "vue"]); }); -test("libraryOverrides", (t) => { +test("libraryOverrides", async (t) => { let mdLib = md(); - let templateCfg = new TemplateConfig( - require("../src/defaultConfig.js"), - "./test/stubs/config.js" - ); + let templateCfg = new TemplateConfig(defaultConfig, "./test/stubs/config.cjs"); templateCfg.userConfig.setLibrary("md", mdLib); + await templateCfg.init(); let cfg = templateCfg.getConfig(); t.falsy(cfg.libraryOverrides.ldkja); @@ -424,50 +343,46 @@ test("libraryOverrides", (t) => { t.deepEqual(mdLib, cfg.libraryOverrides.md); }); -test("addGlobalData", (t) => { - let templateCfg = new TemplateConfig( - require("../src/defaultConfig.js"), - "./test/stubs/config.js" - ); +test("addGlobalData", async (t) => { + let templateCfg = new TemplateConfig(defaultConfig, "./test/stubs/config.cjs"); templateCfg.userConfig.addGlobalData("function", () => new Date()); + await templateCfg.init(); + let cfg = templateCfg.getConfig(); t.not(Object.keys(cfg.globalData).indexOf("function"), -1); }); -test("Properly throws error on missing module #182", (t) => { - t.throws(function () { - let templateCfg = new TemplateConfig( - require("../src/defaultConfig.js"), - "./test/stubs/broken-config.js" - ); +test("Properly throws error on missing module #182", async (t) => { + await t.throwsAsync(async () => { + let templateCfg = new TemplateConfig(defaultConfig, "./test/stubs/broken-config.cjs"); + + await templateCfg.init(); templateCfg.getConfig(); }); }); -test("Properly throws error when config returns a Promise", (t) => { - t.throws(function () { - let templateCfg = new TemplateConfig( - require("../src/defaultConfig.js"), - "./test/stubs/config-promise.js" - ); +test("Properly throws error when config returns a Promise", async (t) => { + await t.throwsAsync(async () => { + let templateCfg = new TemplateConfig(defaultConfig, "./test/stubs/config-promise.js"); + await templateCfg.init(); + templateCfg.getConfig(); }); }); -test(".addWatchTarget adds a watch target", (t) => { - let templateCfg = new TemplateConfig( - require("../src/defaultConfig.js"), - "./test/stubs/config.js" - ); +test(".addWatchTarget adds a watch target", async (t) => { + let templateCfg = new TemplateConfig(defaultConfig, "./test/stubs/config.cjs"); templateCfg.userConfig.addWatchTarget("/testdirectory/"); + await templateCfg.init(); + let cfg = templateCfg.getConfig(); t.deepEqual(cfg.additionalWatchTargets, ["/testdirectory/"]); }); -test("Nested .addPlugin calls", (t) => { +test("Nested .addPlugin calls", async (t) => { t.plan(2); let templateCfg = new TemplateConfig(); @@ -479,10 +394,12 @@ test("Nested .addPlugin calls", (t) => { }); }); + await templateCfg.init(); + templateCfg.getConfig(); }); -test("Nested .addPlugin calls (×3)", (t) => { +test("Nested .addPlugin calls (×3)", async (t) => { t.plan(3); let templateCfg = new TemplateConfig(); @@ -498,10 +415,12 @@ test("Nested .addPlugin calls (×3)", (t) => { }); }); + await templateCfg.init(); + templateCfg.getConfig(); }); -test("Nested .addPlugin calls order", (t) => { +test("Nested .addPlugin calls order", async (t) => { t.plan(3); let templateCfg = new TemplateConfig(); let order = []; @@ -521,10 +440,12 @@ test("Nested .addPlugin calls order", (t) => { }); }); + await templateCfg.init(); + templateCfg.getConfig(); }); -test("Nested .addPlugin calls. More complex order", (t) => { +test("Nested .addPlugin calls. More complex order", async (t) => { t.plan(5); let templateCfg = new TemplateConfig(); let order = []; @@ -554,10 +475,12 @@ test("Nested .addPlugin calls. More complex order", (t) => { }); }); + await templateCfg.init(); + templateCfg.getConfig(); }); -test(".addPlugin has access to pathPrefix", (t) => { +test(".addPlugin has access to pathPrefix", async (t) => { t.plan(1); let templateCfg = new TemplateConfig(); @@ -565,10 +488,12 @@ test(".addPlugin has access to pathPrefix", (t) => { t.is(eleventyConfig.pathPrefix, "/"); }); + await templateCfg.init(); + templateCfg.getConfig(); }); -test(".addPlugin has access to pathPrefix (override method)", (t) => { +test(".addPlugin has access to pathPrefix (override method)", async (t) => { t.plan(1); let templateCfg = new TemplateConfig(); templateCfg.setPathPrefix("/test/"); @@ -577,19 +502,58 @@ test(".addPlugin has access to pathPrefix (override method)", (t) => { t.is(eleventyConfig.pathPrefix, "/test/"); }); + await templateCfg.init(); + templateCfg.getConfig(); }); -test("falsy pathPrefix should fall back to default", (t) => { +test("falsy pathPrefix should fall back to default", async (t) => { t.plan(1); - let templateCfg = new TemplateConfig( - require("../src/defaultConfig.js"), - "./test/stubs/config-empty-pathprefix.js" - ); + let templateCfg = new TemplateConfig(defaultConfig, "./test/stubs/config-empty-pathprefix.cjs"); templateCfg.userConfig.addPlugin(function (eleventyConfig) { t.is(eleventyConfig.pathPrefix, "/"); }); + await templateCfg.init(); + templateCfg.getConfig(); }); + +test("Add async plugin", async (t) => { + let templateCfg = new TemplateConfig(); + + await templateCfg.userConfig.addPlugin(async (eleventyConfig) => { + await new Promise((resolve) => { + setTimeout(() => { + eleventyConfig.addFilter("myFilterName", function () {}); + resolve(); + }, 10); + }); + }); + + await templateCfg.init(); + + let cfg = templateCfg.getConfig(); + t.not(Object.keys(cfg.liquidFilters).indexOf("myFilterName"), -1); + t.not(Object.keys(cfg.nunjucksFilters).indexOf("myFilterName"), -1); +}); + +test("Async namespace", async (t) => { + let templateCfg = new TemplateConfig(); + + await templateCfg.userConfig.namespace("testNamespace", async (eleventyConfig) => { + await new Promise((resolve) => { + setTimeout(() => { + eleventyConfig.addFilter("MyFilterName", function () {}); + resolve(); + }, 10); + }); + }); + + await templateCfg.init(); + + let cfg = templateCfg.getConfig(); + t.not(Object.keys(cfg.liquidFilters).indexOf("testNamespaceMyFilterName"), -1); + t.not(Object.keys(cfg.nunjucksFilters).indexOf("testNamespaceMyFilterName"), -1); +}); diff --git a/test/TemplateDataTest.js b/test/TemplateDataTest.js index 46daba8d5..061577c8f 100644 --- a/test/TemplateDataTest.js +++ b/test/TemplateDataTest.js @@ -1,7 +1,12 @@ -const test = require("ava"); -const TemplateData = require("../src/TemplateData"); -const TemplateConfig = require("../src/TemplateConfig"); -const FileSystemSearch = require("../src/FileSystemSearch"); +import test from "ava"; +import semver from "semver"; +import { createRequire } from "module"; + +import TemplateData from "../src/TemplateData.js"; +import TemplateConfig from "../src/TemplateConfig.js"; +import FileSystemSearch from "../src/FileSystemSearch.js"; + +const pkg = createRequire(import.meta.url)("../package.json"); async function testGetLocalData(tmplData, templatePath) { let localDataPaths = await tmplData.getLocalDataPaths(templatePath); @@ -16,17 +21,20 @@ async function testGetLocalData(tmplData, templatePath) { test("Create", async (t) => { let eleventyConfig = new TemplateConfig(); - let config = eleventyConfig.getConfig(); + await eleventyConfig.init(); + let dataObj = new TemplateData("./test/stubs/", eleventyConfig); dataObj.setFileSystemSearch(new FileSystemSearch()); let data = await dataObj.getGlobalData(); - t.true(Object.keys(data[config.keys.package]).length > 0); + t.true(Object.keys(data[eleventyConfig.getConfig().keys.package]).length > 0); }); test("getGlobalData()", async (t) => { let eleventyConfig = new TemplateConfig(); + await eleventyConfig.init(); + let config = eleventyConfig.getConfig(); let dataObj = new TemplateData("./test/stubs/", eleventyConfig); dataObj.setFileSystemSearch(new FileSystemSearch()); @@ -49,6 +57,8 @@ test("getGlobalData()", async (t) => { test("getGlobalData() use default processing (false)", async (t) => { let eleventyConfig = new TemplateConfig(); + await eleventyConfig.init(); + let dataObj = new TemplateData("./test/stubs/", eleventyConfig); dataObj.setFileSystemSearch(new FileSystemSearch()); @@ -65,6 +75,8 @@ test("Data dir does not exist", async (t) => { test("Add local data", async (t) => { let eleventyConfig = new TemplateConfig(); + await eleventyConfig.init(); + let dataObj = new TemplateData("./test/stubs/", eleventyConfig); dataObj.setFileSystemSearch(new FileSystemSearch()); @@ -87,6 +99,8 @@ test("Add local data", async (t) => { test("Get local data async JS", async (t) => { let eleventyConfig = new TemplateConfig(); + await eleventyConfig.init(); + let dataObj = new TemplateData("./test/stubs/", eleventyConfig); dataObj.setFileSystemSearch(new FileSystemSearch()); @@ -99,6 +113,8 @@ test("Get local data async JS", async (t) => { test("addLocalData() doesn’t exist but doesn’t fail (template file does exist)", async (t) => { let eleventyConfig = new TemplateConfig(); + await eleventyConfig.init(); + let dataObj = new TemplateData("./test/stubs/", eleventyConfig); dataObj.setFileSystemSearch(new FileSystemSearch()); @@ -117,6 +133,8 @@ test("addLocalData() doesn’t exist but doesn’t fail (template file does exis test("addLocalData() doesn’t exist but doesn’t fail (template file does not exist)", async (t) => { let eleventyConfig = new TemplateConfig(); + await eleventyConfig.init(); + let dataObj = new TemplateData("./test/stubs/", eleventyConfig); dataObj.setFileSystemSearch(new FileSystemSearch()); @@ -134,20 +152,26 @@ test("addLocalData() doesn’t exist but doesn’t fail (template file does not test("Global Dir Directory", async (t) => { let eleventyConfig = new TemplateConfig(); + await eleventyConfig.init(); + let dataObj = new TemplateData("./", eleventyConfig); - t.deepEqual(await dataObj.getGlobalDataGlob(), ["./_data/**/*.{json,cjs,js}"]); + t.deepEqual(await dataObj.getGlobalDataGlob(), ["./_data/**/*.{json,mjs,cjs,js}"]); }); test("Global Dir Directory with Constructor Path Arg", async (t) => { let eleventyConfig = new TemplateConfig(); + await eleventyConfig.init(); + let dataObj = new TemplateData("./test/stubs/", eleventyConfig); - t.deepEqual(await dataObj.getGlobalDataGlob(), ["./test/stubs/_data/**/*.{json,cjs,js}"]); + t.deepEqual(await dataObj.getGlobalDataGlob(), ["./test/stubs/_data/**/*.{json,mjs,cjs,js}"]); }); test("getAllGlobalData() with other data files", async (t) => { let eleventyConfig = new TemplateConfig(); + await eleventyConfig.init(); + let dataObj = new TemplateData("./test/stubs/", eleventyConfig); dataObj.setFileSystemSearch(new FileSystemSearch()); @@ -175,6 +199,8 @@ test("getAllGlobalData() with other data files", async (t) => { test("getAllGlobalData() with js object data file", async (t) => { let eleventyConfig = new TemplateConfig(); + await eleventyConfig.init(); + let dataObj = new TemplateData("./test/stubs/", eleventyConfig); dataObj.setFileSystemSearch(new FileSystemSearch()); @@ -183,7 +209,7 @@ test("getAllGlobalData() with js object data file", async (t) => { t.true( dataFilePaths.filter((path) => { - return path.indexOf("./test/stubs/_data/globalData2.js") === 0; + return path.indexOf("./test/stubs/_data/globalData2.cjs") === 0; }).length > 0 ); @@ -193,6 +219,8 @@ test("getAllGlobalData() with js object data file", async (t) => { test("getAllGlobalData() with js function data file", async (t) => { let eleventyConfig = new TemplateConfig(); + await eleventyConfig.init(); + let dataObj = new TemplateData("./test/stubs/", eleventyConfig); dataObj.setFileSystemSearch(new FileSystemSearch()); @@ -215,6 +243,8 @@ test("getAllGlobalData() with config globalData", async (t) => { eleventyConfig.userConfig.addGlobalData("example2", async () => "two"); eleventyConfig.userConfig.addGlobalData("example3", "static"); + await eleventyConfig.init(); + let dataObj = new TemplateData("./test/stubs/", eleventyConfig); dataObj.setFileSystemSearch(new FileSystemSearch()); @@ -227,6 +257,8 @@ test("getAllGlobalData() with config globalData", async (t) => { test("getAllGlobalData() with common js function data file", async (t) => { let eleventyConfig = new TemplateConfig(); + await eleventyConfig.init(); + let dataObj = new TemplateData("./test/stubs/", eleventyConfig); dataObj.setFileSystemSearch(new FileSystemSearch()); @@ -245,31 +277,37 @@ test("getAllGlobalData() with common js function data file", async (t) => { test("getDataValue() without template engine preprocessing", async (t) => { let eleventyConfig = new TemplateConfig(); + await eleventyConfig.init(); + let dataObj = new TemplateData("./test/stubs/", eleventyConfig); - let data = await dataObj.getDataValue("./test/stubs/_data/testDataEjs.json", { + let data = await dataObj.getDataValue("./test/stubs/_data/testDataLiquid.json", { pkg: { name: "pkgname" }, }); t.deepEqual(data, { datakey1: "datavalue1", - datakey2: "<%= pkg.name %>", + datakey2: "{{ pkg.name }}", }); }); test("getLocalDataPaths", async (t) => { let eleventyConfig = new TemplateConfig(); + await eleventyConfig.init(); + let dataObj = new TemplateData("./test/stubs/", eleventyConfig); let paths = await dataObj.getLocalDataPaths("./test/stubs/component/component.liquid"); t.deepEqual(paths, [ "./test/stubs/stubs.json", "./test/stubs/stubs.11tydata.json", + "./test/stubs/stubs.11tydata.mjs", "./test/stubs/stubs.11tydata.cjs", "./test/stubs/stubs.11tydata.js", "./test/stubs/component/component.json", "./test/stubs/component/component.11tydata.json", + "./test/stubs/component/component.11tydata.mjs", "./test/stubs/component/component.11tydata.cjs", "./test/stubs/component/component.11tydata.js", ]); @@ -278,21 +316,25 @@ test("getLocalDataPaths", async (t) => { test("getLocalDataPaths (with setDataFileBaseName #1699)", async (t) => { let eleventyConfig = new TemplateConfig(); eleventyConfig.userConfig.setDataFileBaseName("index"); + await eleventyConfig.init(); let dataObj = new TemplateData("./test/stubs/", eleventyConfig); let paths = await dataObj.getLocalDataPaths("./test/stubs/component/component.liquid"); t.deepEqual(paths, [ "./test/stubs/index.11tydata.json", + "./test/stubs/index.11tydata.mjs", "./test/stubs/index.11tydata.cjs", "./test/stubs/index.11tydata.js", "./test/stubs/component/index.11tydata.json", + "./test/stubs/component/index.11tydata.mjs", "./test/stubs/component/index.11tydata.cjs", "./test/stubs/component/index.11tydata.js", "./test/stubs/component/component.json", "./test/stubs/component/component.11tydata.json", + "./test/stubs/component/component.11tydata.mjs", "./test/stubs/component/component.11tydata.cjs", "./test/stubs/component/component.11tydata.js", ]); @@ -301,6 +343,7 @@ test("getLocalDataPaths (with setDataFileBaseName #1699)", async (t) => { test("getLocalDataPaths (with empty setDataFileSuffixes #1699)", async (t) => { let eleventyConfig = new TemplateConfig(); eleventyConfig.userConfig.setDataFileSuffixes([]); + await eleventyConfig.init(); let dataObj = new TemplateData("./test/stubs/", eleventyConfig); let paths = await dataObj.getLocalDataPaths("./test/stubs/component/component.liquid"); @@ -311,16 +354,19 @@ test("getLocalDataPaths (with empty setDataFileSuffixes #1699)", async (t) => { test("getLocalDataPaths (with setDataFileSuffixes override #1699)", async (t) => { let eleventyConfig = new TemplateConfig(); eleventyConfig.userConfig.setDataFileSuffixes([".howdy"]); + await eleventyConfig.init(); let dataObj = new TemplateData("./test/stubs/", eleventyConfig); let paths = await dataObj.getLocalDataPaths("./test/stubs/component/component.liquid"); t.deepEqual(paths, [ "./test/stubs/stubs.howdy.json", + "./test/stubs/stubs.howdy.mjs", "./test/stubs/stubs.howdy.cjs", "./test/stubs/stubs.howdy.js", "./test/stubs/component/component.howdy.json", + "./test/stubs/component/component.howdy.mjs", "./test/stubs/component/component.howdy.cjs", "./test/stubs/component/component.howdy.js", ]); @@ -329,6 +375,7 @@ test("getLocalDataPaths (with setDataFileSuffixes override #1699)", async (t) => test("getLocalDataPaths (with setDataFileSuffixes empty string override #1699)", async (t) => { let eleventyConfig = new TemplateConfig(); eleventyConfig.userConfig.setDataFileSuffixes([""]); + await eleventyConfig.init(); let dataObj = new TemplateData("./test/stubs/", eleventyConfig); let paths = await dataObj.getLocalDataPaths("./test/stubs/component/component.liquid"); @@ -339,6 +386,7 @@ test("getLocalDataPaths (with setDataFileSuffixes empty string override #1699)", test("getLocalDataPaths (with setDataFileSuffixes override with two entries #1699)", async (t) => { let eleventyConfig = new TemplateConfig(); eleventyConfig.userConfig.setDataFileSuffixes([".howdy", ""]); + await eleventyConfig.init(); let dataObj = new TemplateData("./test/stubs/", eleventyConfig); let paths = await dataObj.getLocalDataPaths("./test/stubs/component/component.liquid"); @@ -346,11 +394,13 @@ test("getLocalDataPaths (with setDataFileSuffixes override with two entries #169 t.deepEqual(paths, [ "./test/stubs/stubs.json", "./test/stubs/stubs.howdy.json", + "./test/stubs/stubs.howdy.mjs", "./test/stubs/stubs.howdy.cjs", "./test/stubs/stubs.howdy.js", "./test/stubs/component/component.json", "./test/stubs/component/component.howdy.json", + "./test/stubs/component/component.howdy.mjs", "./test/stubs/component/component.howdy.cjs", "./test/stubs/component/component.howdy.js", ]); @@ -361,20 +411,25 @@ test("getLocalDataPaths (with setDataFileSuffixes and setDataFileBaseName #1699) eleventyConfig.userConfig.setDataFileBaseName("index"); eleventyConfig.userConfig.setDataFileSuffixes([".howdy", ""]); + await eleventyConfig.init(); + let dataObj = new TemplateData("./test/stubs/", eleventyConfig); let paths = await dataObj.getLocalDataPaths("./test/stubs/component/component.liquid"); t.deepEqual(paths, [ "./test/stubs/index.howdy.json", + "./test/stubs/index.howdy.mjs", "./test/stubs/index.howdy.cjs", "./test/stubs/index.howdy.js", "./test/stubs/component/index.howdy.json", + "./test/stubs/component/index.howdy.mjs", "./test/stubs/component/index.howdy.cjs", "./test/stubs/component/index.howdy.js", "./test/stubs/component/component.json", "./test/stubs/component/component.howdy.json", + "./test/stubs/component/component.howdy.mjs", "./test/stubs/component/component.howdy.cjs", "./test/stubs/component/component.howdy.js", ]); @@ -382,20 +437,25 @@ test("getLocalDataPaths (with setDataFileSuffixes and setDataFileBaseName #1699) test("Deeper getLocalDataPaths", async (t) => { let eleventyConfig = new TemplateConfig(); + await eleventyConfig.init(); + let dataObj = new TemplateData("./", eleventyConfig); let paths = await dataObj.getLocalDataPaths("./test/stubs/component/component.liquid"); t.deepEqual(paths, [ "./test/test.json", "./test/test.11tydata.json", + "./test/test.11tydata.mjs", "./test/test.11tydata.cjs", "./test/test.11tydata.js", "./test/stubs/stubs.json", "./test/stubs/stubs.11tydata.json", + "./test/stubs/stubs.11tydata.mjs", "./test/stubs/stubs.11tydata.cjs", "./test/stubs/stubs.11tydata.js", "./test/stubs/component/component.json", "./test/stubs/component/component.11tydata.json", + "./test/stubs/component/component.11tydata.mjs", "./test/stubs/component/component.11tydata.cjs", "./test/stubs/component/component.11tydata.js", ]); @@ -403,16 +463,20 @@ test("Deeper getLocalDataPaths", async (t) => { test("getLocalDataPaths with an 11ty js template", async (t) => { let eleventyConfig = new TemplateConfig(); + await eleventyConfig.init(); + let dataObj = new TemplateData("./test/stubs/", eleventyConfig); let paths = await dataObj.getLocalDataPaths("./test/stubs/component/component.11ty.js"); t.deepEqual(paths, [ "./test/stubs/stubs.json", "./test/stubs/stubs.11tydata.json", + "./test/stubs/stubs.11tydata.mjs", "./test/stubs/stubs.11tydata.cjs", "./test/stubs/stubs.11tydata.js", "./test/stubs/component/component.json", "./test/stubs/component/component.11tydata.json", + "./test/stubs/component/component.11tydata.mjs", "./test/stubs/component/component.11tydata.cjs", "./test/stubs/component/component.11tydata.js", ]); @@ -420,16 +484,20 @@ test("getLocalDataPaths with an 11ty js template", async (t) => { test("getLocalDataPaths with inputDir passed in (trailing slash)", async (t) => { let eleventyConfig = new TemplateConfig(); + await eleventyConfig.init(); + let dataObj = new TemplateData("./test/stubs/", eleventyConfig); let paths = await dataObj.getLocalDataPaths("./test/stubs/component/component.liquid"); t.deepEqual(paths, [ "./test/stubs/stubs.json", "./test/stubs/stubs.11tydata.json", + "./test/stubs/stubs.11tydata.mjs", "./test/stubs/stubs.11tydata.cjs", "./test/stubs/stubs.11tydata.js", "./test/stubs/component/component.json", "./test/stubs/component/component.11tydata.json", + "./test/stubs/component/component.11tydata.mjs", "./test/stubs/component/component.11tydata.cjs", "./test/stubs/component/component.11tydata.js", ]); @@ -437,16 +505,20 @@ test("getLocalDataPaths with inputDir passed in (trailing slash)", async (t) => test("getLocalDataPaths with inputDir passed in (no trailing slash)", async (t) => { let eleventyConfig = new TemplateConfig(); + await eleventyConfig.init(); + let dataObj = new TemplateData("./test/stubs/", eleventyConfig); let paths = await dataObj.getLocalDataPaths("./test/stubs/component/component.liquid"); t.deepEqual(paths, [ "./test/stubs/stubs.json", "./test/stubs/stubs.11tydata.json", + "./test/stubs/stubs.11tydata.mjs", "./test/stubs/stubs.11tydata.cjs", "./test/stubs/stubs.11tydata.js", "./test/stubs/component/component.json", "./test/stubs/component/component.11tydata.json", + "./test/stubs/component/component.11tydata.mjs", "./test/stubs/component/component.11tydata.cjs", "./test/stubs/component/component.11tydata.js", ]); @@ -454,16 +526,20 @@ test("getLocalDataPaths with inputDir passed in (no trailing slash)", async (t) test("getLocalDataPaths with inputDir passed in (no leading slash)", async (t) => { let eleventyConfig = new TemplateConfig(); + await eleventyConfig.init(); + let dataObj = new TemplateData("test/stubs", eleventyConfig); let paths = await dataObj.getLocalDataPaths("./test/stubs/component/component.liquid"); t.deepEqual(paths, [ "./test/stubs/stubs.json", "./test/stubs/stubs.11tydata.json", + "./test/stubs/stubs.11tydata.mjs", "./test/stubs/stubs.11tydata.cjs", "./test/stubs/stubs.11tydata.js", "./test/stubs/component/component.json", "./test/stubs/component/component.11tydata.json", + "./test/stubs/component/component.11tydata.mjs", "./test/stubs/component/component.11tydata.cjs", "./test/stubs/component/component.11tydata.js", ]); @@ -471,18 +547,22 @@ test("getLocalDataPaths with inputDir passed in (no leading slash)", async (t) = test("getRawImports", async (t) => { let eleventyConfig = new TemplateConfig(); + await eleventyConfig.init(); + let dataObj = new TemplateData("test/stubs", eleventyConfig); - let data = dataObj.getRawImports(); + let data = await dataObj.getRawImports(); t.is(data.pkg.name, "@11ty/eleventy"); }); test("getTemplateDataFileGlob", async (t) => { let eleventyConfig = new TemplateConfig(); + await eleventyConfig.init(); + let tw = new TemplateData("test/stubs", eleventyConfig); t.deepEqual(await tw.getTemplateDataFileGlob(), [ - "./test/stubs/**/*.{json,11tydata.cjs,11tydata.js}", + "./test/stubs/**/*.{json,11tydata.mjs,11tydata.cjs,11tydata.js}", ]); }); @@ -518,6 +598,7 @@ test("Parent directory for data (Issue #337)", async (t) => { data: "../data/", }, }); + await eleventyConfig.init(); let dataObj = new TemplateData("./test/stubs-337/src/", eleventyConfig); dataObj.setInputDir("./test/stubs-337/src/"); dataObj.setFileSystemSearch(new FileSystemSearch()); @@ -536,6 +617,7 @@ test("Dots in datafile path (Issue #1242)", async (t) => { data: "_data/", }, }); + await eleventyConfig.init(); let dataObj = new TemplateData("./test/stubs-1242/", eleventyConfig); dataObj.setInputDir("./test/stubs-1242/"); dataObj.setFileSystemSearch(new FileSystemSearch()); @@ -552,6 +634,7 @@ test("Dots in datafile path (Issue #1242)", async (t) => { test("addGlobalData values", async (t) => { let eleventyConfig = new TemplateConfig(); + eleventyConfig.userConfig.addGlobalData("myFunction", () => "fn-value"); eleventyConfig.userConfig.addGlobalData("myPromise", () => { return new Promise((resolve) => { @@ -560,6 +643,8 @@ test("addGlobalData values", async (t) => { }); eleventyConfig.userConfig.addGlobalData("myAsync", async () => Promise.resolve("promise-value")); + await eleventyConfig.init(); + let dataObj = new TemplateData("./test/stubs-global-data-config-api/", eleventyConfig); dataObj.setFileSystemSearch(new FileSystemSearch()); let data = await dataObj.getGlobalData(); @@ -572,11 +657,14 @@ test("addGlobalData values", async (t) => { test("addGlobalData should execute once.", async (t) => { let count = 0; let eleventyConfig = new TemplateConfig(); + eleventyConfig.userConfig.addGlobalData("count", () => { count++; return count; }); + await eleventyConfig.init(); + let dataObj = new TemplateData("./test/stubs-global-data-config-api/", eleventyConfig); dataObj.setFileSystemSearch(new FileSystemSearch()); @@ -588,9 +676,12 @@ test("addGlobalData should execute once.", async (t) => { test("addGlobalData complex key", async (t) => { let eleventyConfig = new TemplateConfig(); + eleventyConfig.userConfig.addGlobalData("deep.nested.one", () => "first"); eleventyConfig.userConfig.addGlobalData("deep.nested.two", () => "second"); + await eleventyConfig.init(); + let dataObj = new TemplateData("./test/stubs-global-data-config-api-nested/", eleventyConfig); dataObj.setFileSystemSearch(new FileSystemSearch()); let data = await dataObj.getGlobalData(); @@ -602,14 +693,17 @@ test("addGlobalData complex key", async (t) => { test("eleventy.version and eleventy.generator returned from data", async (t) => { let eleventyConfig = new TemplateConfig(); + eleventyConfig.userConfig.addGlobalData("deep.nested.one", () => "first"); eleventyConfig.userConfig.addGlobalData("deep.nested.two", () => "second"); + await eleventyConfig.init(); + let dataObj = new TemplateData("./test/stubs-empty/", eleventyConfig); dataObj.setFileSystemSearch(new FileSystemSearch()); let data = await dataObj.getGlobalData(); - let version = require("semver").coerce(require("../package.json").version).toString(); + let version = semver.coerce(pkg.version).toString(); t.is(data.eleventy.version, version); t.is(data.eleventy.generator, `Eleventy v${version}`); @@ -620,6 +714,8 @@ test("eleventy.version and eleventy.generator returned from data", async (t) => test("getGlobalData() empty json file", async (t) => { let eleventyConfig = new TemplateConfig(); + await eleventyConfig.init(); + let dataObj = new TemplateData("./test/stubs-empty-json-data/", eleventyConfig); dataObj.setFileSystemSearch(new FileSystemSearch()); @@ -627,3 +723,16 @@ test("getGlobalData() empty json file", async (t) => { let data = await dataObj.getGlobalData(); t.deepEqual(data.empty, {}); }); + +test("ESM data file", async (t) => { + let eleventyConfig = new TemplateConfig(); + await eleventyConfig.init(); + + let dataObj = new TemplateData("./test/stubs-data-esm/", eleventyConfig); + dataObj.setFileSystemSearch(new FileSystemSearch()); + + let data = await dataObj.getGlobalData(); + t.is(data.module.default, "es module default"); + t.is(data.module.named, "es module named"); + t.is(data.commonjs, "commonjs default"); +}); diff --git a/test/TemplateEngineManagerTest.js b/test/TemplateEngineManagerTest.js index 19d9448de..beb5be7ff 100644 --- a/test/TemplateEngineManagerTest.js +++ b/test/TemplateEngineManagerTest.js @@ -1,19 +1,22 @@ -const test = require("ava"); -const TemplateEngineManager = require("../src/TemplateEngineManager"); -const TemplateConfig = require("../src/TemplateConfig"); +import test from "ava"; + +import TemplateEngineManager from "../src/TemplateEngineManager.js"; +import TemplateConfig from "../src/TemplateConfig.js"; test("Unsupported engine", async (t) => { - t.throws(() => { + await t.throwsAsync(async () => { let eleventyConfig = new TemplateConfig(); let tem = new TemplateEngineManager(eleventyConfig); - tem.getEngine("doesnotexist"); + await tem.getEngine("doesnotexist"); }); }); test("Supported engine", async (t) => { let eleventyConfig = new TemplateConfig(); + await eleventyConfig.init(); + let tem = new TemplateEngineManager(eleventyConfig); - t.truthy(tem.hasEngine("ejs")); + t.truthy(tem.hasEngine("11ty.js")); }); test("Supported custom engine", async (t) => { @@ -28,10 +31,12 @@ test("Supported custom engine", async (t) => { }; }, }); + await eleventyConfig.init(); + let tem = new TemplateEngineManager(eleventyConfig); t.truthy(tem.hasEngine("txt")); - let engine = tem.getEngine("txt"); + let engine = await tem.getEngine("txt"); let fn = await engine.compile("

This is plaintext

"); t.is(await fn({ author: "zach" }), "

This is plaintext

"); }); @@ -52,16 +57,17 @@ test("Custom engine with custom init", async (t) => { return () => str; }, }); + await eleventyConfig.init(); let config = eleventyConfig.getConfig(); let tem = new TemplateEngineManager(eleventyConfig); t.truthy(tem.hasEngine("custom1")); - let engine = tem.getEngine("custom1"); + let engine = await tem.getEngine("custom1"); let fn = await engine.compile("

This is plaintext

"); t.is(await fn({}), "

This is plaintext

"); - let engine2 = tem.getEngine("custom1"); + let engine2 = await tem.getEngine("custom1"); t.is(engine, engine2); let fn2 = await engine2.compile("

This is plaintext

"); @@ -71,22 +77,11 @@ test("Custom engine with custom init", async (t) => { t.is(compileCount, 2, "Should have only run the compile callback twice"); }); -test("Handlebars Helpers", async (t) => { - let eleventyConfig = new TemplateConfig(); - let tem = new TemplateEngineManager(eleventyConfig); - let engine = tem.getEngine("hbs"); - engine.addHelpers({ - uppercase: function (name) { - return name.toUpperCase(); - }, - }); - - let fn = await engine.compile("

{{uppercase author}}

"); - t.is(await fn({ author: "zach" }), "

ZACH

"); -}); - test("getEngineLib", async (t) => { let eleventyConfig = new TemplateConfig(); + await eleventyConfig.init(); + let tem = new TemplateEngineManager(eleventyConfig); - t.truthy(tem.getEngine("md").getEngineLib()); + let engine = await tem.getEngine("md"); + t.truthy(engine.getEngineLib()); }); diff --git a/test/TemplateEngineTest.js b/test/TemplateEngineTest.js index b11b8f2b0..20d0c2b5d 100644 --- a/test/TemplateEngineTest.js +++ b/test/TemplateEngineTest.js @@ -1,16 +1,19 @@ -const test = require("ava"); -const TemplateEngine = require("../src/Engines/TemplateEngine"); -const TemplateConfig = require("../src/TemplateConfig"); +import test from "ava"; + +import TemplateConfig from "../src/TemplateConfig.js"; +import TemplateEngine from "../src/Engines/TemplateEngine.js"; test("Unsupported engine", async (t) => { let eleventyConfig = new TemplateConfig(); - t.is( - new TemplateEngine("doesnotexist", null, eleventyConfig).getName(), - "doesnotexist" - ); + await eleventyConfig.init(); + + let engine = new TemplateEngine("doesnotexist", null, eleventyConfig); + t.is(engine.getName(), "doesnotexist"); }); test("Supported engine", async (t) => { let eleventyConfig = new TemplateConfig(); - t.is(new TemplateEngine("ejs", null, eleventyConfig).getName(), "ejs"); + await eleventyConfig.init(); + + t.is(new TemplateEngine("liquid", null, eleventyConfig).getName(), "liquid"); }); diff --git a/test/TemplateFileSlugTest.js b/test/TemplateFileSlugTest.js index 4cfa46fa5..25a6451a8 100644 --- a/test/TemplateFileSlugTest.js +++ b/test/TemplateFileSlugTest.js @@ -1,190 +1,193 @@ -const test = require("ava"); -const TemplateFileSlug = require("../src/TemplateFileSlug"); -const EleventyExtensionMap = require("../src/EleventyExtensionMap"); -const TemplateConfig = require("../src/TemplateConfig"); +import test from "ava"; -function getNewSlugInstance(path, inputDir) { +import TemplateFileSlug from "../src/TemplateFileSlug.js"; +import EleventyExtensionMap from "../src/EleventyExtensionMap.js"; +import TemplateConfig from "../src/TemplateConfig.js"; + +async function getNewSlugInstance(path, inputDir) { let eleventyConfig = new TemplateConfig(); + await eleventyConfig.init(); + let extensionMap = new EleventyExtensionMap([], eleventyConfig); let fs = new TemplateFileSlug(path, inputDir, extensionMap); return fs; } -test("Easy slug", (t) => { - let fs = getNewSlugInstance("./file.html"); +test("Easy slug", async (t) => { + let fs = await getNewSlugInstance("./file.html"); t.is(fs.getSlug(), "file"); t.is(fs.getFullPathWithoutExtension(), "/file"); }); -test("Easy slug with dot", (t) => { - let fs = getNewSlugInstance("./file.test.html"); +test("Easy slug with dot", async (t) => { + let fs = await getNewSlugInstance("./file.test.html"); t.is(fs.getSlug(), "file.test"); t.is(fs.getFullPathWithoutExtension(), "/file.test"); }); -test("Easy slug with dot 11ty.js", (t) => { - let fs = getNewSlugInstance("./file.test.11ty.js"); +test("Easy slug with dot 11ty.js", async (t) => { + let fs = await getNewSlugInstance("./file.test.11ty.js"); t.is(fs.getSlug(), "file.test"); t.is(fs.getFullPathWithoutExtension(), "/file.test"); }); -test("Easy slug with date", (t) => { - let fs = getNewSlugInstance("./2018-01-01-file.html"); +test("Easy slug with date", async (t) => { + let fs = await getNewSlugInstance("./2018-01-01-file.html"); t.is(fs.getSlug(), "file"); t.is(fs.getFullPathWithoutExtension(), "/file"); }); -test("Easy slug with date and dot in slug", (t) => { - let fs = getNewSlugInstance("./2018-01-01-file.test.html"); +test("Easy slug with date and dot in slug", async (t) => { + let fs = await getNewSlugInstance("./2018-01-01-file.test.html"); t.is(fs.getSlug(), "file.test"); t.is(fs.getFullPathWithoutExtension(), "/file.test"); }); -test("Easy slug, index", (t) => { - let fs = getNewSlugInstance("./index.html"); +test("Easy slug, index", async (t) => { + let fs = await getNewSlugInstance("./index.html"); t.is(fs.getSlug(), ""); t.is(fs.getFullPathWithoutExtension(), "/index"); }); -test("Easy slug with date, index", (t) => { - let fs = getNewSlugInstance("./2018-01-01-index.html"); +test("Easy slug with date, index", async (t) => { + let fs = await getNewSlugInstance("./2018-01-01-index.html"); t.is(fs.getSlug(), ""); t.is(fs.getFullPathWithoutExtension(), "/index"); }); -test("Easy slug with only a date and no suffix", (t) => { - let fs = getNewSlugInstance("./2018-01-01.html"); +test("Easy slug with only a date and no suffix", async (t) => { + let fs = await getNewSlugInstance("./2018-01-01.html"); t.is(fs.getSlug(), "2018-01-01"); t.is(fs.getFullPathWithoutExtension(), "/2018-01-01"); }); /* Directories */ -test("Easy slug with dir", (t) => { - let fs = getNewSlugInstance("./test/file.html"); +test("Easy slug with dir", async (t) => { + let fs = await getNewSlugInstance("./test/file.html"); t.is(fs.getSlug(), "file"); t.is(fs.getFullPathWithoutExtension(), "/test/file"); }); -test("Easy slug with dot with dir", (t) => { - let fs = getNewSlugInstance("./test/file.test.html"); +test("Easy slug with dot with dir", async (t) => { + let fs = await getNewSlugInstance("./test/file.test.html"); t.is(fs.getSlug(), "file.test"); t.is(fs.getFullPathWithoutExtension(), "/test/file.test"); }); -test("Easy slug with date with dir", (t) => { - let fs = getNewSlugInstance("./test/2018-01-01-file.html"); +test("Easy slug with date with dir", async (t) => { + let fs = await getNewSlugInstance("./test/2018-01-01-file.html"); t.is(fs.getSlug(), "file"); t.is(fs.getFullPathWithoutExtension(), "/test/file"); }); -test("Easy slug with date and dot in slug with dir", (t) => { - let fs = getNewSlugInstance("./test/2018-01-01-file.test.html"); +test("Easy slug with date and dot in slug with dir", async (t) => { + let fs = await getNewSlugInstance("./test/2018-01-01-file.test.html"); t.is(fs.getSlug(), "file.test"); t.is(fs.getFullPathWithoutExtension(), "/test/file.test"); }); -test("Easy slug, index with dir", (t) => { - let fs = getNewSlugInstance("./test/index.html"); +test("Easy slug, index with dir", async (t) => { + let fs = await getNewSlugInstance("./test/index.html"); t.is(fs.getSlug(), "test"); t.is(fs.getFullPathWithoutExtension(), "/test/index"); }); -test("Easy slug with date, index with dir", (t) => { - let fs = getNewSlugInstance("./test/2018-01-01-index.html"); +test("Easy slug with date, index with dir", async (t) => { + let fs = await getNewSlugInstance("./test/2018-01-01-index.html"); t.is(fs.getSlug(), "test"); t.is(fs.getFullPathWithoutExtension(), "/test/index"); }); -test("Strips date from dir name", (t) => { - let fs = getNewSlugInstance("./2021-11-20-my-awesome-post/index.md"); +test("Strips date from dir name", async (t) => { + let fs = await getNewSlugInstance("./2021-11-20-my-awesome-post/index.md"); t.is(fs.getSlug(), "my-awesome-post"); t.is(fs.getFullPathWithoutExtension(), "/2021-11-20-my-awesome-post/index"); }); /* Pass Input dir */ -test("Easy slug, input dir", (t) => { - let fs = getNewSlugInstance("./file.html", "."); +test("Easy slug, input dir", async (t) => { + let fs = await getNewSlugInstance("./file.html", "."); t.is(fs.getSlug(), "file"); t.is(fs.getFullPathWithoutExtension(), "/file"); }); -test("Easy slug with dot, input dir", (t) => { - let fs = getNewSlugInstance("./file.test.html", "."); +test("Easy slug with dot, input dir", async (t) => { + let fs = await getNewSlugInstance("./file.test.html", "."); t.is(fs.getSlug(), "file.test"); t.is(fs.getFullPathWithoutExtension(), "/file.test"); }); -test("Easy slug with date, input dir", (t) => { - let fs = getNewSlugInstance("./2018-01-01-file.html", "."); +test("Easy slug with date, input dir", async (t) => { + let fs = await getNewSlugInstance("./2018-01-01-file.html", "."); t.is(fs.getSlug(), "file"); t.is(fs.getFullPathWithoutExtension(), "/file"); }); -test("Easy slug with date and dot in slug, input dir", (t) => { - let fs = getNewSlugInstance("./2018-01-01-file.test.html", "."); +test("Easy slug with date and dot in slug, input dir", async (t) => { + let fs = await getNewSlugInstance("./2018-01-01-file.test.html", "."); t.is(fs.getSlug(), "file.test"); t.is(fs.getFullPathWithoutExtension(), "/file.test"); }); -test("Easy slug, index, input dir", (t) => { - let fs = getNewSlugInstance("./index.html", "."); +test("Easy slug, index, input dir", async (t) => { + let fs = await getNewSlugInstance("./index.html", "."); t.is(fs.getSlug(), ""); t.is(fs.getFullPathWithoutExtension(), "/index"); }); -test("Easy slug with date, index, input dir", (t) => { - let fs = getNewSlugInstance("./2018-01-01-index.html", "."); +test("Easy slug with date, index, input dir", async (t) => { + let fs = await getNewSlugInstance("./2018-01-01-index.html", "."); t.is(fs.getSlug(), ""); t.is(fs.getFullPathWithoutExtension(), "/index"); }); /* Directories and Input Dir */ -test("Easy slug with dir and input dir", (t) => { - let fs = getNewSlugInstance("./test/file.html", "./test"); +test("Easy slug with dir and input dir", async (t) => { + let fs = await getNewSlugInstance("./test/file.html", "./test"); t.is(fs.getSlug(), "file"); t.is(fs.getFullPathWithoutExtension(), "/file"); }); -test("Easy slug with dot with dir and input dir", (t) => { - let fs = getNewSlugInstance("./test/file.test.html", "./test"); +test("Easy slug with dot with dir and input dir", async (t) => { + let fs = await getNewSlugInstance("./test/file.test.html", "./test"); t.is(fs.getSlug(), "file.test"); t.is(fs.getFullPathWithoutExtension(), "/file.test"); }); -test("Easy slug with date with dir and input dir", (t) => { - let fs = getNewSlugInstance("./test/2018-01-01-file.html", "./test"); +test("Easy slug with date with dir and input dir", async (t) => { + let fs = await getNewSlugInstance("./test/2018-01-01-file.html", "./test"); t.is(fs.getSlug(), "file"); t.is(fs.getFullPathWithoutExtension(), "/file"); }); -test("Easy slug with date and dot in slug with dir and input dir", (t) => { - let fs = getNewSlugInstance("./test/2018-01-01-file.test.html", "./test"); +test("Easy slug with date and dot in slug with dir and input dir", async (t) => { + let fs = await getNewSlugInstance("./test/2018-01-01-file.test.html", "./test"); t.is(fs.getSlug(), "file.test"); t.is(fs.getFullPathWithoutExtension(), "/file.test"); }); -test("Easy slug, index with dir and input dir", (t) => { - let fs = getNewSlugInstance("./test/index.html", "./test"); +test("Easy slug, index with dir and input dir", async (t) => { + let fs = await getNewSlugInstance("./test/index.html", "./test"); t.is(fs.getSlug(), ""); t.is(fs.getFullPathWithoutExtension(), "/index"); }); -test("Easy slug with date, index with dir and input dir", (t) => { - let fs = getNewSlugInstance("./test/2018-01-01-index.html", "./test"); +test("Easy slug with date, index with dir and input dir", async (t) => { + let fs = await getNewSlugInstance("./test/2018-01-01-index.html", "./test"); t.is(fs.getSlug(), ""); t.is(fs.getFullPathWithoutExtension(), "/index"); }); -test("Easy slug with multiple dirs", (t) => { - let fs = getNewSlugInstance("./dir1/dir2/dir3/file.html", "."); +test("Easy slug with multiple dirs", async (t) => { + let fs = await getNewSlugInstance("./dir1/dir2/dir3/file.html", "."); t.is(fs.getSlug(), "file"); t.is(fs.getFullPathWithoutExtension(), "/dir1/dir2/dir3/file"); }); -test("Easy slug with multiple dirs and an index file", (t) => { - let fs = getNewSlugInstance("./dir1/dir2/dir3/index.html", "."); +test("Easy slug with multiple dirs and an index file", async (t) => { + let fs = await getNewSlugInstance("./dir1/dir2/dir3/index.html", "."); t.is(fs.getSlug(), "dir3"); t.is(fs.getFullPathWithoutExtension(), "/dir1/dir2/dir3/index"); }); diff --git a/test/TemplateGlobTest.js b/test/TemplateGlobTest.js index 6e14a8aa3..fbc2b48fd 100644 --- a/test/TemplateGlobTest.js +++ b/test/TemplateGlobTest.js @@ -1,8 +1,8 @@ -const test = require("ava"); -const fastglob = require("fast-glob"); -const { TemplatePath } = require("@11ty/eleventy-utils"); +import test from "ava"; +import fastglob from "fast-glob"; +import { TemplatePath } from "@11ty/eleventy-utils"; -const TemplateGlob = require("../src/TemplateGlob"); +import TemplateGlob from "../src/TemplateGlob.js"; test("TemplatePath assumptions", (t) => { t.is(TemplatePath.normalize("ignoredFolder"), "ignoredFolder"); @@ -40,14 +40,8 @@ test("Normalize with globstar and star and file extension", (t) => { }); test("NormalizePath with globstar and star and file extension", (t) => { - t.deepEqual( - TemplateGlob.normalizePath("views", "/", "**/*.json"), - "./views/**/*.json" - ); - t.deepEqual( - TemplateGlob.normalizePath("./views", "/", "**/*.json"), - "./views/**/*.json" - ); + t.deepEqual(TemplateGlob.normalizePath("views", "/", "**/*.json"), "./views/**/*.json"); + t.deepEqual(TemplateGlob.normalizePath("./views", "/", "**/*.json"), "./views/**/*.json"); }); test("NormalizePath with globstar and star and file extension (errors)", (t) => { @@ -119,10 +113,7 @@ test("fastglob assumptions", async (t) => { ]); t.is(glob3.length, 0); - let glob4 = await fastglob([ - "./test/stubs/ignoredFolder/*.md", - "!./test/stubs/ignoredFolder/**", - ]); + let glob4 = await fastglob(["./test/stubs/ignoredFolder/*.md", "!./test/stubs/ignoredFolder/**"]); t.is(glob4.length, 0); let glob5 = await fastglob([ diff --git a/test/TemplateLayoutPathResolverTest.js b/test/TemplateLayoutPathResolverTest.js index cff7982cd..45e4358de 100644 --- a/test/TemplateLayoutPathResolverTest.js +++ b/test/TemplateLayoutPathResolverTest.js @@ -1,129 +1,128 @@ -const test = require("ava"); -const TemplateConfig = require("../src/TemplateConfig"); -const TemplateLayoutPathResolver = require("../src/TemplateLayoutPathResolver"); -const EleventyExtensionMap = require("../src/EleventyExtensionMap"); +import test from "ava"; -function getResolverInstance(path, inputDir, { eleventyConfig, map } = {}) { +import TemplateConfig from "../src/TemplateConfig.js"; +import TemplateLayoutPathResolver from "../src/TemplateLayoutPathResolver.js"; +import EleventyExtensionMap from "../src/EleventyExtensionMap.js"; + +async function getResolverInstance(path, inputDir, { eleventyConfig, map } = {}) { if (!eleventyConfig) { eleventyConfig = new TemplateConfig(); + await eleventyConfig.init(); } if (!map) { - map = new EleventyExtensionMap( - ["liquid", "ejs", "md", "hbs", "mustache", "haml", "pug", "njk", "html", "11ty.js"], - eleventyConfig - ); + map = new EleventyExtensionMap(["liquid", "md", "njk", "html", "11ty.js"], eleventyConfig); } return new TemplateLayoutPathResolver(path, inputDir, map, eleventyConfig); } -test("Layout", (t) => { - let res = getResolverInstance("default", "./test/stubs"); - t.is(res.getFileName(), "default.ejs"); +test("Layout", async (t) => { + let res = await getResolverInstance("default", "./test/stubs"); + t.is(res.getFileName(), "default.liquid"); }); -test("Layout already has extension", (t) => { - let res = getResolverInstance("default.ejs", "./test/stubs"); - t.is(res.getFileName(), "default.ejs"); +test("Layout already has extension", async (t) => { + let res = await getResolverInstance("default.liquid", "./test/stubs"); + t.is(res.getFileName(), "default.liquid"); }); -test("Layout (uses empty string includes folder)", (t) => { +test("Layout (uses empty string includes folder)", async (t) => { let eleventyConfig = new TemplateConfig(); - eleventyConfig.appendToRootConfig({ - templateFormats: ["ejs"], + await eleventyConfig.init({ + templateFormats: ["liquid"], dir: { includes: "", }, }); - let res = getResolverInstance("includesemptystring", "./test/stubs", { + let res = await getResolverInstance("includesemptystring", "./test/stubs", { eleventyConfig, }); - t.is(res.getFileName(), "includesemptystring.ejs"); + t.is(res.getFileName(), "includesemptystring.liquid"); }); -test("Layout (uses empty string includes folder) already has extension", (t) => { +test("Layout (uses empty string includes folder) already has extension", async (t) => { let eleventyConfig = new TemplateConfig(); - eleventyConfig.appendToRootConfig({ - templateFormats: ["ejs"], + await eleventyConfig.init({ + templateFormats: ["liquid"], dir: { includes: "", }, }); - let res = getResolverInstance("includesemptystring.ejs", "./test/stubs", { + let res = await getResolverInstance("includesemptystring.liquid", "./test/stubs", { eleventyConfig, }); - t.is(res.getFileName(), "includesemptystring.ejs"); + t.is(res.getFileName(), "includesemptystring.liquid"); }); -test("Layout (uses layouts folder)", (t) => { +test("Layout (uses layouts folder)", async (t) => { let eleventyConfig = new TemplateConfig(); - eleventyConfig.appendToRootConfig({ - templateFormats: ["ejs"], + await eleventyConfig.init({ + templateFormats: ["liquid"], dir: { layouts: "_layouts", includes: "_includes", }, }); - let res = getResolverInstance("layoutsdefault", "./test/stubs", { + let res = await getResolverInstance("layoutsdefault", "./test/stubs", { eleventyConfig, }); - t.is(res.getFileName(), "layoutsdefault.ejs"); + t.is(res.getFileName(), "layoutsdefault.liquid"); }); -test("Layout (uses layouts folder) already has extension", (t) => { +test("Layout (uses layouts folder) already has extension", async (t) => { let eleventyConfig = new TemplateConfig(); - eleventyConfig.appendToRootConfig({ - templateFormats: ["ejs"], + await eleventyConfig.init({ + templateFormats: ["liquid"], dir: { layouts: "_layouts", includes: "_includes", }, }); - let res = getResolverInstance("layoutsdefault.ejs", "./test/stubs", { + let res = await getResolverInstance("layoutsdefault.liquid", "./test/stubs", { eleventyConfig, }); - t.is(res.getFileName(), "layoutsdefault.ejs"); + t.is(res.getFileName(), "layoutsdefault.liquid"); }); -test("Layout (uses empty string layouts folder)", (t) => { +test("Layout (uses empty string layouts folder)", async (t) => { let eleventyConfig = new TemplateConfig(); - eleventyConfig.appendToRootConfig({ - templateFormats: ["ejs"], + await eleventyConfig.init({ + templateFormats: ["liquid"], dir: { layouts: "", includes: "_includes", }, }); - let res = getResolverInstance("layoutsemptystring", "./test/stubs", { + let res = await getResolverInstance("layoutsemptystring", "./test/stubs", { eleventyConfig, }); - t.is(res.getFileName(), "layoutsemptystring.ejs"); + t.is(res.getFileName(), "layoutsemptystring.liquid"); }); -test("Layout (uses empty string layouts folder) no template resolution", (t) => { +test("Layout (uses empty string layouts folder) no template resolution", async (t) => { let eleventyConfig = new TemplateConfig(); eleventyConfig.userConfig.setLayoutResolution(false); - eleventyConfig.appendToRootConfig({ - templateFormats: ["ejs"], + await eleventyConfig.init({ + templateFormats: ["liquid"], dir: { layouts: "", includes: "_includes", }, }); - let res = getResolverInstance("layoutsemptystring", "./test/stubs", { + let res = await getResolverInstance("layoutsemptystring", "./test/stubs", { eleventyConfig, }); @@ -132,66 +131,66 @@ test("Layout (uses empty string layouts folder) no template resolution", (t) => }); }); -test("Layout (uses empty string layouts folder) already has extension", (t) => { +test("Layout (uses empty string layouts folder) already has extension", async (t) => { let eleventyConfig = new TemplateConfig(); - eleventyConfig.appendToRootConfig({ - templateFormats: ["ejs"], + await eleventyConfig.init({ + templateFormats: ["liquid"], dir: { layouts: "", includes: "_includes", }, }); - let res = getResolverInstance("layoutsemptystring.ejs", "./test/stubs", { + let res = await getResolverInstance("layoutsemptystring.liquid", "./test/stubs", { eleventyConfig, }); - t.is(res.getFileName(), "layoutsemptystring.ejs"); + t.is(res.getFileName(), "layoutsemptystring.liquid"); }); -test("Layout subdir", (t) => { - let res = getResolverInstance("layouts/inasubdir", "./test/stubs"); +test("Layout subdir", async (t) => { + let res = await getResolverInstance("layouts/inasubdir", "./test/stubs"); t.is(res.getFileName(), "layouts/inasubdir.njk"); }); -test("Layout subdir already has extension", (t) => { - let res = getResolverInstance("layouts/inasubdir.njk", "./test/stubs"); +test("Layout subdir already has extension", async (t) => { + let res = await getResolverInstance("layouts/inasubdir.njk", "./test/stubs"); t.is(res.getFileName(), "layouts/inasubdir.njk"); }); -test("Multiple layouts exist with the same file base, pick one", (t) => { - let res = getResolverInstance("multiple", "./test/stubs"); +test("Multiple layouts exist with the same file base, pick one", async (t) => { + let res = await getResolverInstance("multiple", "./test/stubs"); // pick the first one if multiple exist. - t.is(res.getFileName(), "multiple.ejs"); + t.is(res.getFileName(), "multiple.liquid"); }); -test("Multiple layouts exist but we are being explicit—layout already has extension", (t) => { - let res = getResolverInstance("multiple.ejs", "./test/stubs"); - t.is(res.getFileName(), "multiple.ejs"); +test("Multiple layouts exist but we are being explicit—layout already has extension", async (t) => { + let res = await getResolverInstance("multiple.liquid", "./test/stubs"); + t.is(res.getFileName(), "multiple.liquid"); - let res2 = getResolverInstance("multiple.md", "./test/stubs"); + let res2 = await getResolverInstance("multiple.md", "./test/stubs"); t.is(res2.getFileName(), "multiple.md"); }); -test("Layout is aliased to a new location", (t) => { - let tl = getResolverInstance("post", "./test/stubs"); - tl.addLayoutAlias("post", "layouts/post.ejs"); +test("Layout is aliased to a new location", async (t) => { + let tl = await getResolverInstance("post", "./test/stubs"); + tl.addLayoutAlias("post", "layouts/post.liquid"); tl.init(); - t.is(tl.getFileName(), "layouts/post.ejs"); + t.is(tl.getFileName(), "layouts/post.liquid"); }); -test("Global default with empty string alias", (t) => { - let tl = getResolverInstance("", "./test/stubs"); - tl.addLayoutAlias("", "layouts/post.ejs"); +test("Global default with empty string alias", async (t) => { + let tl = await getResolverInstance("", "./test/stubs"); + tl.addLayoutAlias("", "layouts/post.liquid"); tl.init(); - t.is(tl.getFileName(), "layouts/post.ejs"); + t.is(tl.getFileName(), "layouts/post.liquid"); }); -test("Global default with empty string alias (but no alias exists for this instance)", (t) => { - let tl = getResolverInstance("layout.ejs", "./test/stubs"); - tl.addLayoutAlias("", "layouts/post.ejs"); +test("Global default with empty string alias (but no alias exists for this instance)", async (t) => { + let tl = await getResolverInstance("layout.liquid", "./test/stubs"); + tl.addLayoutAlias("", "layouts/post.liquid"); tl.init(); t.throws(() => { @@ -200,8 +199,8 @@ test("Global default with empty string alias (but no alias exists for this insta }); test("Layout has no alias and does not exist", async (t) => { - let tl = getResolverInstance("shouldnotexist", "./test/stubs"); - tl.addLayoutAlias("post", "layouts/post.ejs"); + let tl = await getResolverInstance("shouldnotexist", "./test/stubs"); + tl.addLayoutAlias("post", "layouts/post.liquid"); tl.init(); t.throws(() => { diff --git a/test/TemplateLayoutTest.js b/test/TemplateLayoutTest.js index 80d876c6d..11576710b 100644 --- a/test/TemplateLayoutTest.js +++ b/test/TemplateLayoutTest.js @@ -1,34 +1,31 @@ -const test = require("ava"); -const TemplateConfig = require("../src/TemplateConfig"); -const TemplateLayout = require("../src/TemplateLayout"); -const EleventyExtensionMap = require("../src/EleventyExtensionMap"); +import test from "ava"; -function getTemplateLayoutInstance(key, inputDir, map) { +import TemplateConfig from "../src/TemplateConfig.js"; +import TemplateLayout from "../src/TemplateLayout.js"; +import EleventyExtensionMap from "../src/EleventyExtensionMap.js"; + +async function getTemplateLayoutInstance(key, inputDir, map) { let eleventyConfig = new TemplateConfig(); + await eleventyConfig.init(); if (!map) { - map = new EleventyExtensionMap( - ["liquid", "ejs", "md", "hbs", "mustache", "haml", "pug", "njk", "html", "11ty.js"], - eleventyConfig - ); + map = new EleventyExtensionMap(["liquid", "md", "njk", "html", "11ty.js"], eleventyConfig); } let layout = new TemplateLayout(key, inputDir, map, eleventyConfig); return layout; } -test("Creation", (t) => { - t.is( - getTemplateLayoutInstance("base", "./test/stubs").getInputPath(), - "./test/stubs/_includes/base.njk" - ); +test("Creation", async (t) => { + let tl = await getTemplateLayoutInstance("base", "./test/stubs"); + t.is(tl.getInputPath(), "./test/stubs/_includes/base.njk"); - t.throws(() => { - getTemplateLayoutInstance("doesnotexist", "./test/stubs").getInputPath(); + await t.throwsAsync(async () => { + await getTemplateLayoutInstance("doesnotexist", "./test/stubs"); }); }); test("Get Layout Chain", async (t) => { - let tl = getTemplateLayoutInstance("layouts/layout-inherit-a.njk", "./test/stubs"); + let tl = await getTemplateLayoutInstance("layouts/layout-inherit-a.njk", "./test/stubs"); await tl.getData(); @@ -40,7 +37,7 @@ test("Get Layout Chain", async (t) => { }); test("Get Front Matter Data", async (t) => { - let tl = getTemplateLayoutInstance("layouts/layout-inherit-a.njk", "./test/stubs"); + let tl = await getTemplateLayoutInstance("layouts/layout-inherit-a.njk", "./test/stubs"); t.is(tl.getInputPath(), "./test/stubs/_includes/layouts/layout-inherit-a.njk"); let data = await tl.getData(); @@ -87,7 +84,7 @@ test("Augment data with layoutContent", async (t) => { }); test("Render Layout", async (t) => { - let tl = getTemplateLayoutInstance("layouts/layout-inherit-a.njk", "./test/stubs"); + let tl = await getTemplateLayoutInstance("layouts/layout-inherit-a.njk", "./test/stubs"); t.is( ( await tl.render({ @@ -101,7 +98,7 @@ test("Render Layout", async (t) => { }); test("Render Layout (Pass in template content)", async (t) => { - let tl = getTemplateLayoutInstance("layouts/layout-inherit-a.njk", "./test/stubs"); + let tl = await getTemplateLayoutInstance("layouts/layout-inherit-a.njk", "./test/stubs"); t.is( ( await tl.render( @@ -114,7 +111,7 @@ test("Render Layout (Pass in template content)", async (t) => { }); test("Render Layout (Pass in undefined template content)", async (t) => { - let tl = getTemplateLayoutInstance("layouts/layout-contentdump.njk", "./test/stubs"); + let tl = await getTemplateLayoutInstance("layouts/layout-contentdump.njk", "./test/stubs"); t.is( await tl.render({ inherits: "a", secondinherits: "b", thirdinherits: "c" }, undefined), "this is bad a b a c" @@ -122,7 +119,7 @@ test("Render Layout (Pass in undefined template content)", async (t) => { }); test("Render Layout (Pass in null template content)", async (t) => { - let tl = getTemplateLayoutInstance("layouts/layout-contentdump.njk", "./test/stubs"); + let tl = await getTemplateLayoutInstance("layouts/layout-contentdump.njk", "./test/stubs"); t.is( await tl.render({ inherits: "a", secondinherits: "b", thirdinherits: "c" }, null), " a b a c" @@ -130,16 +127,22 @@ test("Render Layout (Pass in null template content)", async (t) => { }); test("Render Layout (Pass in empty template content)", async (t) => { - let tl = getTemplateLayoutInstance("layouts/layout-contentdump.njk", "./test/stubs"); + let tl = await getTemplateLayoutInstance("layouts/layout-contentdump.njk", "./test/stubs"); t.is(await tl.render({ inherits: "a", secondinherits: "b", thirdinherits: "c" }, ""), " a b a c"); }); test("Cache Duplicates (use full key for cache)", async (t) => { // if two different layouts used the same filename but had different inputdirs, make sure templatelayout cache is unique - let tla = getTemplateLayoutInstance("layout.njk", "./test/stubs/templateLayoutCacheDuplicates"); + let tla = await getTemplateLayoutInstance( + "layout.njk", + "./test/stubs/templateLayoutCacheDuplicates" + ); t.is((await tla.render({})).trim(), "Hello A"); - let tlb = getTemplateLayoutInstance("layout.njk", "./test/stubs/templateLayoutCacheDuplicates-b"); + let tlb = await getTemplateLayoutInstance( + "layout.njk", + "./test/stubs/templateLayoutCacheDuplicates-b" + ); t.is((await tlb.render({})).trim(), "Hello B"); t.is((await tla.render({})).trim(), "Hello A"); @@ -147,7 +150,10 @@ test("Cache Duplicates (use full key for cache)", async (t) => { test("Throw an error if a layout references itself as the layout", async (t) => { await t.throwsAsync(async () => { - const tl = getTemplateLayoutInstance("layout-cycle-self.njk", "./test/stubs-circular-layout"); + const tl = await getTemplateLayoutInstance( + "layout-cycle-self.njk", + "./test/stubs-circular-layout" + ); const layoutChain = await tl._testGetLayoutChain(); return layoutChain; @@ -156,7 +162,10 @@ test("Throw an error if a layout references itself as the layout", async (t) => test("Throw an error if a circular layout chain is detected", async (t) => { await t.throwsAsync(async () => { - const tl = getTemplateLayoutInstance("layout-cycle-a.njk", "./test/stubsstubs-circular-layout"); + const tl = await getTemplateLayoutInstance( + "layout-cycle-a.njk", + "./test/stubsstubs-circular-layout" + ); const layoutChain = await tl._testGetLayoutChain(); return layoutChain; }); diff --git a/test/TemplateMapTest-ComputedData.js b/test/TemplateMapTest-ComputedData.js index d50cef928..7c296cd6e 100644 --- a/test/TemplateMapTest-ComputedData.js +++ b/test/TemplateMapTest-ComputedData.js @@ -1,18 +1,18 @@ -const test = require("ava"); -const TemplateConfig = require("../src/TemplateConfig"); -const TemplateData = require("../src/TemplateData"); -const TemplateMap = require("../src/TemplateMap"); -const getNewTemplate = require("./_getNewTemplateForTests"); +import test from "ava"; + +import TemplateConfig from "../src/TemplateConfig.js"; +import TemplateData from "../src/TemplateData.js"; +import TemplateMap from "../src/TemplateMap.js"; +import getNewTemplate from "./_getNewTemplateForTests.js"; test("Computed data can see tag generated collections", async (t) => { let eleventyConfig = new TemplateConfig(); + await eleventyConfig.init(); + let tm = new TemplateMap(eleventyConfig); - let dataObj = new TemplateData( - "./test/stubs-computed-collections/", - eleventyConfig - ); - let tmpl = getNewTemplate( + let dataObj = new TemplateData("./test/stubs-computed-collections/", eleventyConfig); + let tmpl = await getNewTemplate( "./test/stubs-computed-collections/collections.njk", "./test/stubs-computed-collections/", "./dist", @@ -23,11 +23,8 @@ test("Computed data can see tag generated collections", async (t) => { await tm.add(tmpl); - let dataObj2 = new TemplateData( - "./test/stubs-computed-collections/", - eleventyConfig - ); - let tmpl2 = getNewTemplate( + let dataObj2 = new TemplateData("./test/stubs-computed-collections/", eleventyConfig); + let tmpl2 = await getNewTemplate( "./test/stubs-computed-collections/dog.njk", "./test/stubs-computed-collections/", "./dist", @@ -58,13 +55,12 @@ test("Computed data can see tag generated collections", async (t) => { test("Computed data can see paginated data, Issue #1138", async (t) => { let eleventyConfig = new TemplateConfig(); + await eleventyConfig.init(); + let tm = new TemplateMap(eleventyConfig); - let dataObj = new TemplateData( - "./test/stubs-computed-pagination/", - eleventyConfig - ); - let tmpl = getNewTemplate( + let dataObj = new TemplateData("./test/stubs-computed-pagination/", eleventyConfig); + let tmpl = await getNewTemplate( "./test/stubs-computed-pagination/paginated.njk", "./test/stubs-computed-pagination/", "./dist", @@ -75,12 +71,9 @@ test("Computed data can see paginated data, Issue #1138", async (t) => { await tm.add(tmpl); - let dataObj2 = new TemplateData( - "./test/stubs-computed-pagination/", - eleventyConfig - ); - let tmpl2 = getNewTemplate( - "./test/stubs-computed-pagination/child.11ty.js", + let dataObj2 = new TemplateData("./test/stubs-computed-pagination/", eleventyConfig); + let tmpl2 = await getNewTemplate( + "./test/stubs-computed-pagination/child.11ty.cjs", "./test/stubs-computed-pagination/", "./dist", dataObj2, @@ -122,14 +115,13 @@ test("Computed data can see paginated data, Issue #1138", async (t) => { test("Computed data in directory data file consumes data file data, Issue #1137", async (t) => { let eleventyConfig = new TemplateConfig(); + await eleventyConfig.init(); + let tm = new TemplateMap(eleventyConfig); - let dataObj = new TemplateData( - "./test/stubs-computed-dirdata/", - eleventyConfig - ); - let tmpl = getNewTemplate( - "./test/stubs-computed-dirdata/dir/first.11ty.js", + let dataObj = new TemplateData("./test/stubs-computed-dirdata/", eleventyConfig); + let tmpl = await getNewTemplate( + "./test/stubs-computed-dirdata/dir/first.11ty.cjs", "./test/stubs-computed-dirdata/", "./dist", dataObj, @@ -139,12 +131,9 @@ test("Computed data in directory data file consumes data file data, Issue #1137" await tm.add(tmpl); - let dataObj2 = new TemplateData( - "./test/stubs-computed-dirdata/", - eleventyConfig - ); - let tmpl2 = getNewTemplate( - "./test/stubs-computed-dirdata/dir/second.11ty.js", + let dataObj2 = new TemplateData("./test/stubs-computed-dirdata/", eleventyConfig); + let tmpl2 = await getNewTemplate( + "./test/stubs-computed-dirdata/dir/second.11ty.cjs", "./test/stubs-computed-dirdata/", "./dist", dataObj2, @@ -165,13 +154,12 @@ test("Computed data in directory data file consumes data file data, Issue #1137" test("Computed data can filter collections (and other array methods)", async (t) => { let eleventyConfig = new TemplateConfig(); + await eleventyConfig.init(); + let tm = new TemplateMap(eleventyConfig); - let dataObj = new TemplateData( - "./test/stubs-computed-collections-filter/", - eleventyConfig - ); - let tmpl = getNewTemplate( + let dataObj = new TemplateData("./test/stubs-computed-collections-filter/", eleventyConfig); + let tmpl = await getNewTemplate( "./test/stubs-computed-collections-filter/collections.njk", "./test/stubs-computed-collections-filter/", "./dist", @@ -182,11 +170,8 @@ test("Computed data can filter collections (and other array methods)", async (t) await tm.add(tmpl); - let dataObj2 = new TemplateData( - "./test/stubs-computed-collections-filter/", - eleventyConfig - ); - let tmpl2 = getNewTemplate( + let dataObj2 = new TemplateData("./test/stubs-computed-collections-filter/", eleventyConfig); + let tmpl2 = await getNewTemplate( "./test/stubs-computed-collections-filter/dog.njk", "./test/stubs-computed-collections-filter/", "./dist", diff --git a/test/TemplateMapTest.js b/test/TemplateMapTest.js index 222173232..9f9d10cae 100644 --- a/test/TemplateMapTest.js +++ b/test/TemplateMapTest.js @@ -1,13 +1,13 @@ -const test = require("ava"); -const TemplateMap = require("../src/TemplateMap"); -const TemplateCollection = require("../src/TemplateCollection"); -const UsingCircularTemplateContentReferenceError = require("../src/Errors/UsingCircularTemplateContentReferenceError"); -const TemplateContentUnrenderedTemplateError = require("../src/Errors/TemplateContentUnrenderedTemplateError"); -const normalizeNewLines = require("./Util/normalizeNewLines"); -const TemplateConfig = require("../src/TemplateConfig"); +import test from "ava"; -const getNewTemplateForTests = require("./_getNewTemplateForTests"); -const getRenderedTmpls = require("./_getRenderedTemplates"); +import TemplateMap from "../src/TemplateMap.js"; +import TemplateCollection from "../src/TemplateCollection.js"; +import UsingCircularTemplateContentReferenceError from "../src/Errors/UsingCircularTemplateContentReferenceError.js"; +import TemplateContentUnrenderedTemplateError from "../src/Errors/TemplateContentUnrenderedTemplateError.js"; +import normalizeNewLines from "./Util/normalizeNewLines.js"; +import TemplateConfig from "../src/TemplateConfig.js"; +import getNewTemplateForTests from "./_getNewTemplateForTests.js"; +import getRenderedTmpls from "./_getRenderedTemplates.js"; function getNewTemplate(filename, input, output, eleventyConfig) { return getNewTemplateForTests(filename, input, output, null, null, eleventyConfig); @@ -36,8 +36,9 @@ async function addTemplate(collection, template) { test("TemplateMap has collections added", async (t) => { let eleventyConfig = new TemplateConfig(); - let tmpl1 = getNewTemplateByNumber(1, eleventyConfig); - let tmpl2 = getNewTemplateByNumber(2, eleventyConfig); + await eleventyConfig.init(); + let tmpl1 = await getNewTemplateByNumber(1, eleventyConfig); + let tmpl2 = await getNewTemplateByNumber(2, eleventyConfig); let tm = new TemplateMap(eleventyConfig); await tm.add(tmpl1); @@ -50,8 +51,10 @@ test("TemplateMap has collections added", async (t) => { test("TemplateMap compared to Collection API", async (t) => { let eleventyConfig = new TemplateConfig(); - let tmpl1 = getNewTemplateByNumber(1, eleventyConfig); - let tmpl4 = getNewTemplateByNumber(4, eleventyConfig); + await eleventyConfig.init(); + + let tmpl1 = await getNewTemplateByNumber(1, eleventyConfig); + let tmpl4 = await getNewTemplateByNumber(4, eleventyConfig); let tm = new TemplateMap(eleventyConfig); await tm.add(tmpl1); await tm.add(tmpl4); @@ -75,8 +78,10 @@ test("TemplateMap compared to Collection API", async (t) => { test("populating the collection twice should clear the previous values (--watch was making it cumulative)", async (t) => { let eleventyConfig = new TemplateConfig(); - let tmpl1 = getNewTemplateByNumber(1, eleventyConfig); - let tmpl2 = getNewTemplateByNumber(2, eleventyConfig); + await eleventyConfig.init(); + + let tmpl1 = await getNewTemplateByNumber(1, eleventyConfig); + let tmpl2 = await getNewTemplateByNumber(2, eleventyConfig); let tm = new TemplateMap(eleventyConfig); await tm.add(tmpl1); @@ -90,8 +95,10 @@ test("populating the collection twice should clear the previous values (--watch test("TemplateMap adds collections data and has templateContent values", async (t) => { let eleventyConfig = new TemplateConfig(); - let tmpl1 = getNewTemplateByNumber(1, eleventyConfig); - let tmpl2 = getNewTemplateByNumber(2, eleventyConfig); + await eleventyConfig.init(); + + let tmpl1 = await getNewTemplateByNumber(1, eleventyConfig); + let tmpl2 = await getNewTemplateByNumber(2, eleventyConfig); let tm = new TemplateMap(eleventyConfig); await tm.add(tmpl1); @@ -124,7 +131,9 @@ test("TemplateMap adds collections data and has templateContent values", async ( test("TemplateMap circular references (map without templateContent)", async (t) => { let eleventyConfig = new TemplateConfig(); - let tmpl3 = getNewTemplateByNumber(3, eleventyConfig); + await eleventyConfig.init(); + + let tmpl3 = await getNewTemplateByNumber(3, eleventyConfig); let tm = new TemplateMap(eleventyConfig); await tm.add(tmpl3); @@ -145,8 +154,10 @@ test("TemplateMap circular references (map without templateContent)", async (t) test("TemplateMap circular references (map.templateContent)", async (t) => { let eleventyConfig = new TemplateConfig(); + await eleventyConfig.init(); + let tm = new TemplateMap(eleventyConfig); - let tmpl = getNewTemplate( + let tmpl = await getNewTemplate( "./test/stubs/templateMapCollection/templateContent.md", "./test/stubs/", "./test/stubs/_site", @@ -169,19 +180,21 @@ test("TemplateMap circular references (map.templateContent)", async (t) => { test("Issue #115, mixing pagination and collections", async (t) => { let eleventyConfig = new TemplateConfig(); - let tmplFoos = getNewTemplate( + await eleventyConfig.init(); + + let tmplFoos = await getNewTemplate( "./test/stubs/issue-115/template-foos.liquid", "./test/stubs/", "./test/stubs/_site", eleventyConfig ); - let tmplBars = getNewTemplate( + let tmplBars = await getNewTemplate( "./test/stubs/issue-115/template-bars.liquid", "./test/stubs/", "./test/stubs/_site", eleventyConfig ); - let tmplIndex = getNewTemplate( + let tmplIndex = await getNewTemplate( "./test/stubs/issue-115/index.liquid", "./test/stubs/", "./test/stubs/_site", @@ -234,19 +247,21 @@ This page is bars test("Issue #115 with layout, mixing pagination and collections", async (t) => { let eleventyConfig = new TemplateConfig(); - let tmplFoos = getNewTemplate( + await eleventyConfig.init(); + + let tmplFoos = await getNewTemplate( "./test/stubs/issue-115/template-foos.liquid", "./test/stubs/", "./test/stubs/_site", eleventyConfig ); - let tmplBars = getNewTemplate( + let tmplBars = await getNewTemplate( "./test/stubs/issue-115/template-bars.liquid", "./test/stubs/", "./test/stubs/_site", eleventyConfig ); - let tmplIndex = getNewTemplate( + let tmplIndex = await getNewTemplate( "./test/stubs/issue-115/index-with-layout.liquid", "./test/stubs/", "./test/stubs/_site", @@ -299,8 +314,10 @@ This page is bars test("TemplateMap adds collections data and has page data values using .cache()", async (t) => { let eleventyConfig = new TemplateConfig(); - let tmpl1 = getNewTemplateByNumber(1, eleventyConfig); - let tmpl2 = getNewTemplateByNumber(2, eleventyConfig); + await eleventyConfig.init(); + + let tmpl1 = await getNewTemplateByNumber(1, eleventyConfig); + let tmpl2 = await getNewTemplateByNumber(2, eleventyConfig); let tm = new TemplateMap(eleventyConfig); await tm.add(tmpl1); @@ -317,8 +334,10 @@ test("TemplateMap adds collections data and has page data values using .cache()" test("TemplateMap adds collections data and has page data values using ._testGetCollectionsData()", async (t) => { let eleventyConfig = new TemplateConfig(); - let tmpl1 = getNewTemplateByNumber(1, eleventyConfig); - let tmpl2 = getNewTemplateByNumber(2, eleventyConfig); + await eleventyConfig.init(); + + let tmpl1 = await getNewTemplateByNumber(1, eleventyConfig); + let tmpl2 = await getNewTemplateByNumber(2, eleventyConfig); let tm = new TemplateMap(eleventyConfig); await tm.add(tmpl1); @@ -339,18 +358,17 @@ test("TemplateMap adds collections data and has page data values using ._testGet test("Url should be available in user config collections API calls", async (t) => { let eleventyConfig = new TemplateConfig(); - let tmpl1 = getNewTemplateByNumber(1, eleventyConfig); - let tmpl2 = getNewTemplateByNumber(2, eleventyConfig); + eleventyConfig.userConfig.addCollection("userCollection", function (collection) { + return collection.getAll(); + }); + await eleventyConfig.init(); + + let tmpl1 = await getNewTemplateByNumber(1, eleventyConfig); + let tmpl2 = await getNewTemplateByNumber(2, eleventyConfig); let tm = new TemplateMap(eleventyConfig); await tm.add(tmpl1); await tm.add(tmpl2); - tm.setUserConfigCollections({ - userCollection: function (collection) { - let all = collection.getAll(); - return all; - }, - }); let collections = await tm._testGetCollectionsData(); t.truthy(collections.userCollection); @@ -370,21 +388,20 @@ test("Url should be available in user config collections API calls", async (t) = test("Url should be available in user config collections API calls (test in callback)", async (t) => { let eleventyConfig = new TemplateConfig(); - let tm = new TemplateMap(eleventyConfig); - tm.setUserConfigCollections({ - userCollection: function (collection) { - let all = collection.getAll(); - t.is(all[0].url, "/templateMapCollection/test1/"); - t.is(all[0].outputPath, "./test/stubs/_site/templateMapCollection/test1/index.html"); - t.is(all[1].url, "/templateMapCollection/test2/"); - t.is(all[1].outputPath, "./test/stubs/_site/templateMapCollection/test2/index.html"); - - return all; - }, + eleventyConfig.userConfig.addCollection("userCollection", function (collection) { + let all = collection.getAll(); + t.is(all[0].url, "/templateMapCollection/test1/"); + t.is(all[0].outputPath, "./test/stubs/_site/templateMapCollection/test1/index.html"); + t.is(all[1].url, "/templateMapCollection/test2/"); + t.is(all[1].outputPath, "./test/stubs/_site/templateMapCollection/test2/index.html"); + + return all; }); + await eleventyConfig.init(); - let tmpl1 = getNewTemplateByNumber(1, eleventyConfig); - let tmpl2 = getNewTemplateByNumber(2, eleventyConfig); + let tm = new TemplateMap(eleventyConfig); + let tmpl1 = await getNewTemplateByNumber(1, eleventyConfig); + let tmpl2 = await getNewTemplateByNumber(2, eleventyConfig); await tm.add(tmpl1); await tm.add(tmpl2); await tm.cache(); @@ -392,14 +409,16 @@ test("Url should be available in user config collections API calls (test in call test("Should be able to paginate a tag generated collection", async (t) => { let eleventyConfig = new TemplateConfig(); - let tmpl1 = getNewTemplateByNumber(1, eleventyConfig); - let tmpl2 = getNewTemplateByNumber(2, eleventyConfig); + await eleventyConfig.init(); + + let tmpl1 = await getNewTemplateByNumber(1, eleventyConfig); + let tmpl2 = await getNewTemplateByNumber(2, eleventyConfig); let tm = new TemplateMap(eleventyConfig); await tm.add(tmpl1); await tm.add(tmpl2); - let pagedTmpl = getNewTemplate( + let pagedTmpl = await getNewTemplate( "./test/stubs/templateMapCollection/paged-tag.md", "./test/stubs/", "./test/stubs/_site", @@ -414,14 +433,20 @@ test("Should be able to paginate a tag generated collection", async (t) => { test("Should be able to paginate a user config collection", async (t) => { let eleventyConfig = new TemplateConfig(); - let tmpl1 = getNewTemplateByNumber(1, eleventyConfig); - let tmpl2 = getNewTemplateByNumber(2, eleventyConfig); + eleventyConfig.userConfig.addCollection("userCollection", function (collection) { + let all = collection.getFilteredByTag("dog"); + return all; + }); + await eleventyConfig.init(); + + let tmpl1 = await getNewTemplateByNumber(1, eleventyConfig); + let tmpl2 = await getNewTemplateByNumber(2, eleventyConfig); let tm = new TemplateMap(eleventyConfig); await tm.add(tmpl1); await tm.add(tmpl2); - let pagedTmpl = getNewTemplate( + let pagedTmpl = await getNewTemplate( "./test/stubs/templateMapCollection/paged-cfg.md", "./test/stubs/", "./test/stubs/_site", @@ -429,13 +454,6 @@ test("Should be able to paginate a user config collection", async (t) => { ); await tm.add(pagedTmpl); - tm.setUserConfigCollections({ - userCollection: function (collection) { - let all = collection.getFilteredByTag("dog"); - return all; - }, - }); - let collections = await tm._testGetCollectionsData(); t.truthy(collections.userCollection); t.truthy(collections.userCollection.length); @@ -443,14 +461,22 @@ test("Should be able to paginate a user config collection", async (t) => { test("Should be able to paginate a user config collection (uses rendered permalink)", async (t) => { let eleventyConfig = new TemplateConfig(); - let tmpl1 = getNewTemplateByNumber(1, eleventyConfig); - let tmpl2 = getNewTemplateByNumber(2, eleventyConfig); + eleventyConfig.userConfig.addCollection("userCollection", function (collection) { + let all = collection.getFilteredByTag("dog"); + t.is(all[0].url, "/templateMapCollection/test1/"); + t.is(all[0].outputPath, "./test/stubs/_site/templateMapCollection/test1/index.html"); + return all; + }); + await eleventyConfig.init(); + + let tmpl1 = await getNewTemplateByNumber(1, eleventyConfig); + let tmpl2 = await getNewTemplateByNumber(2, eleventyConfig); let tm = new TemplateMap(eleventyConfig); await tm.add(tmpl1); await tm.add(tmpl2); - let pagedTmpl = getNewTemplate( + let pagedTmpl = await getNewTemplate( "./test/stubs/templateMapCollection/paged-cfg-permalink.md", "./test/stubs/", "./test/stubs/_site", @@ -458,15 +484,6 @@ test("Should be able to paginate a user config collection (uses rendered permali ); await tm.add(pagedTmpl); - tm.setUserConfigCollections({ - userCollection: function (collection) { - let all = collection.getFilteredByTag("dog"); - t.is(all[0].url, "/templateMapCollection/test1/"); - t.is(all[0].outputPath, "./test/stubs/_site/templateMapCollection/test1/index.html"); - return all; - }, - }); - let collections = await tm._testGetCollectionsData(); t.truthy(collections.userCollection); t.truthy(collections.userCollection.length); @@ -480,16 +497,22 @@ test("Should be able to paginate a user config collection (uses rendered permali test("Should be able to paginate a user config collection (paged template is also tagged)", async (t) => { let eleventyConfig = new TemplateConfig(); - let tmpl1 = getNewTemplateByNumber(1, eleventyConfig); - let tmpl2 = getNewTemplateByNumber(2, eleventyConfig); - let tmpl4 = getNewTemplateByNumber(4, eleventyConfig); + eleventyConfig.userConfig.addCollection("userCollection", function (collection) { + let all = collection.getFilteredByTag("dog"); + return all; + }); + await eleventyConfig.init(); + + let tmpl1 = await getNewTemplateByNumber(1, eleventyConfig); + let tmpl2 = await getNewTemplateByNumber(2, eleventyConfig); + let tmpl4 = await getNewTemplateByNumber(4, eleventyConfig); let tm = new TemplateMap(eleventyConfig); await tm.add(tmpl1); // has dog tag await tm.add(tmpl2); // does not have dog tag await tm.add(tmpl4); // has dog tag - let pagedTmpl = getNewTemplate( + let pagedTmpl = await getNewTemplate( "./test/stubs/templateMapCollection/paged-cfg-tagged.md", "./test/stubs/", "./test/stubs/_site", @@ -497,13 +520,6 @@ test("Should be able to paginate a user config collection (paged template is als ); await tm.add(pagedTmpl); - tm.setUserConfigCollections({ - userCollection: function (collection) { - let all = collection.getFilteredByTag("dog"); - return all; - }, - }); - let collections = await tm._testGetCollectionsData(); t.is(collections.dog.length, 2); @@ -514,16 +530,22 @@ test("Should be able to paginate a user config collection (paged template is als test("Should be able to paginate a user config collection (paged template is also tagged, add all pages to collections)", async (t) => { let eleventyConfig = new TemplateConfig(); - let tmpl1 = getNewTemplateByNumber(1, eleventyConfig); - let tmpl2 = getNewTemplateByNumber(2, eleventyConfig); - let tmpl4 = getNewTemplateByNumber(4, eleventyConfig); + eleventyConfig.userConfig.addCollection("userCollection", function (collection) { + let all = collection.getFilteredByTag("dog"); + return all; + }); + await eleventyConfig.init(); + + let tmpl1 = await getNewTemplateByNumber(1, eleventyConfig); + let tmpl2 = await getNewTemplateByNumber(2, eleventyConfig); + let tmpl4 = await getNewTemplateByNumber(4, eleventyConfig); let tm = new TemplateMap(eleventyConfig); await tm.add(tmpl1); // has dog tag await tm.add(tmpl2); // does not have dog tag await tm.add(tmpl4); // has dog tag - let pagedTmpl = getNewTemplate( + let pagedTmpl = await getNewTemplate( "./test/stubs/templateMapCollection/paged-cfg-tagged-apply-to-all.md", "./test/stubs/", "./test/stubs/_site", @@ -531,13 +553,6 @@ test("Should be able to paginate a user config collection (paged template is als ); await tm.add(pagedTmpl); - tm.setUserConfigCollections({ - userCollection: function (collection) { - let all = collection.getFilteredByTag("dog"); - return all; - }, - }); - let collections = await tm._testGetCollectionsData(); t.is(collections.dog.length, 2); @@ -549,16 +564,22 @@ test("Should be able to paginate a user config collection (paged template is als test("Should be able to paginate a user config collection (paged template is also tagged, uses custom rendered permalink)", async (t) => { let eleventyConfig = new TemplateConfig(); - let tmpl1 = getNewTemplateByNumber(1, eleventyConfig); - let tmpl2 = getNewTemplateByNumber(2, eleventyConfig); - let tmpl4 = getNewTemplateByNumber(4, eleventyConfig); + eleventyConfig.userConfig.addCollection("userCollection", function (collection) { + let all = collection.getFilteredByTag("dog"); + return all; + }); + await eleventyConfig.init(); + + let tmpl1 = await getNewTemplateByNumber(1, eleventyConfig); + let tmpl2 = await getNewTemplateByNumber(2, eleventyConfig); + let tmpl4 = await getNewTemplateByNumber(4, eleventyConfig); let tm = new TemplateMap(eleventyConfig); await tm.add(tmpl1); // has dog tag await tm.add(tmpl2); // does not have dog tag await tm.add(tmpl4); // has dog tag - let pagedTmpl = getNewTemplate( + let pagedTmpl = await getNewTemplate( "./test/stubs/templateMapCollection/paged-cfg-tagged-permalink.md", "./test/stubs/", "./test/stubs/_site", @@ -566,13 +587,6 @@ test("Should be able to paginate a user config collection (paged template is als ); await tm.add(pagedTmpl); - tm.setUserConfigCollections({ - userCollection: function (collection) { - let all = collection.getFilteredByTag("dog"); - return all; - }, - }); - let collections = await tm._testGetCollectionsData(); t.truthy(collections.haha); t.is(collections.haha.length, 1); @@ -581,16 +595,22 @@ test("Should be able to paginate a user config collection (paged template is als test("Should be able to paginate a user config collection (paged template is also tagged, uses custom rendered permalink, add all pages to collections)", async (t) => { let eleventyConfig = new TemplateConfig(); - let tmpl1 = getNewTemplateByNumber(1, eleventyConfig); - let tmpl2 = getNewTemplateByNumber(2, eleventyConfig); - let tmpl4 = getNewTemplateByNumber(4, eleventyConfig); + eleventyConfig.userConfig.addCollection("userCollection", function (collection) { + let all = collection.getFilteredByTag("dog"); + return all; + }); + await eleventyConfig.init(); + + let tmpl1 = await getNewTemplateByNumber(1, eleventyConfig); + let tmpl2 = await getNewTemplateByNumber(2, eleventyConfig); + let tmpl4 = await getNewTemplateByNumber(4, eleventyConfig); let tm = new TemplateMap(eleventyConfig); await tm.add(tmpl1); // has dog tag await tm.add(tmpl2); // does not have dog tag await tm.add(tmpl4); // has dog tag - let pagedTmpl = getNewTemplate( + let pagedTmpl = await getNewTemplate( "./test/stubs/templateMapCollection/paged-cfg-tagged-permalink-apply-to-all.md", "./test/stubs/", "./test/stubs/_site", @@ -598,13 +618,6 @@ test("Should be able to paginate a user config collection (paged template is als ); await tm.add(pagedTmpl); - tm.setUserConfigCollections({ - userCollection: function (collection) { - let all = collection.getFilteredByTag("dog"); - return all; - }, - }); - let collections = await tm._testGetCollectionsData(); t.truthy(collections.haha); t.is(collections.haha.length, 2); @@ -614,8 +627,10 @@ test("Should be able to paginate a user config collection (paged template is als test("TemplateMap render and templateContent are the same (templateContent doesn’t have layout but makes proper use of layout front matter data)", async (t) => { let eleventyConfig = new TemplateConfig(); + await eleventyConfig.init(); + let tm = new TemplateMap(eleventyConfig); - let tmplLayout = getNewTemplate( + let tmplLayout = await getNewTemplate( "./test/stubs/templateMapCollection/testWithLayout.md", "./test/stubs/", "./test/stubs/_site", @@ -632,16 +647,18 @@ test("TemplateMap render and templateContent are the same (templateContent doesn test("Should be able to paginate a tag generated collection (and it has templateContent)", async (t) => { let eleventyConfig = new TemplateConfig(); - let tmpl1 = getNewTemplateByNumber(1, eleventyConfig); - let tmpl2 = getNewTemplateByNumber(2, eleventyConfig); - let tmpl4 = getNewTemplateByNumber(4, eleventyConfig); + await eleventyConfig.init(); + + let tmpl1 = await getNewTemplateByNumber(1, eleventyConfig); + let tmpl2 = await getNewTemplateByNumber(2, eleventyConfig); + let tmpl4 = await getNewTemplateByNumber(4, eleventyConfig); let tm = new TemplateMap(eleventyConfig); await tm.add(tmpl1); // has dog tag await tm.add(tmpl2); // does not have dog tag await tm.add(tmpl4); // has dog tag - let pagedTmpl = getNewTemplate( + let pagedTmpl = await getNewTemplate( "./test/stubs/templateMapCollection/paged-tag-dogs-templateContent.md", "./test/stubs/", "./test/stubs/_site", @@ -676,16 +693,18 @@ test("Should be able to paginate a tag generated collection (and it has template test("Should be able to paginate a tag generated collection when aliased (and it has templateContent)", async (t) => { let eleventyConfig = new TemplateConfig(); - let tmpl1 = getNewTemplateByNumber(1, eleventyConfig); - let tmpl2 = getNewTemplateByNumber(2, eleventyConfig); - let tmpl4 = getNewTemplateByNumber(4, eleventyConfig); + await eleventyConfig.init(); + + let tmpl1 = await getNewTemplateByNumber(1, eleventyConfig); + let tmpl2 = await getNewTemplateByNumber(2, eleventyConfig); + let tmpl4 = await getNewTemplateByNumber(4, eleventyConfig); let tm = new TemplateMap(eleventyConfig); await tm.add(tmpl1); // has dog tag await tm.add(tmpl2); // does not have dog tag await tm.add(tmpl4); // has dog tag - let pagedTmpl = getNewTemplate( + let pagedTmpl = await getNewTemplate( "./test/stubs/templateMapCollection/paged-tag-dogs-templateContent-alias.md", "./test/stubs/", "./test/stubs/_site", @@ -713,16 +732,23 @@ test("Should be able to paginate a tag generated collection when aliased (and it test("Issue #253: Paginated template with a tag should put multiple pages into a collection", async (t) => { let eleventyConfig = new TemplateConfig(); - let tmpl1 = getNewTemplateByNumber(1, eleventyConfig); - let tmpl2 = getNewTemplateByNumber(2, eleventyConfig); - let tmpl4 = getNewTemplateByNumber(4, eleventyConfig); + eleventyConfig.userConfig.addCollection("userCollection", function (collection) { + // TODO test user config collections (no actual tests against this collection yet) + let all = collection.getFilteredByTag("dog"); + return all; + }); + await eleventyConfig.init(); + + let tmpl1 = await getNewTemplateByNumber(1, eleventyConfig); + let tmpl2 = await getNewTemplateByNumber(2, eleventyConfig); + let tmpl4 = await getNewTemplateByNumber(4, eleventyConfig); let tm = new TemplateMap(eleventyConfig); await tm.add(tmpl1); await tm.add(tmpl2); await tm.add(tmpl4); - let pagedTmpl = getNewTemplate( + let pagedTmpl = await getNewTemplate( "./test/stubs/tagged-pagination-multiples/test.njk", "./test/stubs/", "./test/stubs/_site", @@ -730,14 +756,6 @@ test("Issue #253: Paginated template with a tag should put multiple pages into a ); await tm.add(pagedTmpl); - // TODO test user config collections (no actual tests against this collection yet) - tm.setUserConfigCollections({ - userCollection: function (collection) { - let all = collection.getFilteredByTag("dog"); - return all; - }, - }); - let collections = await tm._testGetCollectionsData(); t.is(collections.dog.length, 2); @@ -749,28 +767,26 @@ test("Issue #253: Paginated template with a tag should put multiple pages into a test("getUserConfigCollectionNames", async (t) => { let eleventyConfig = new TemplateConfig(); - let tm = new TemplateMap(eleventyConfig); - - tm.setUserConfigCollections({ - userCollection: function (collection) { - return collection.getAll(); - }, - otherUserCollection: function (collection) { - return collection.getAll(); - }, + eleventyConfig.userConfig.addCollection("userCollection", function (collection) { + return collection.getAll(); + }); + eleventyConfig.userConfig.addCollection("otherUserCollection", function (collection) { + return collection.getAll(); }); + await eleventyConfig.init(); + let tm = new TemplateMap(eleventyConfig); t.deepEqual(tm.getUserConfigCollectionNames(), ["userCollection", "otherUserCollection"]); }); -test("isUserConfigCollectionName", (t) => { +test("isUserConfigCollectionName", async (t) => { let eleventyConfig = new TemplateConfig(); - let tm = new TemplateMap(eleventyConfig); - tm.setUserConfigCollections({ - userCollection: function (collection) { - return collection.getAll(); - }, + eleventyConfig.userConfig.addCollection("userCollection", function (collection) { + return collection.getAll(); }); + await eleventyConfig.init(); + + let tm = new TemplateMap(eleventyConfig); t.is(tm.isUserConfigCollectionName("userCollection"), true); t.is(tm.isUserConfigCollectionName("userCollection2"), false); @@ -778,8 +794,10 @@ test("isUserConfigCollectionName", (t) => { test("Dependency Map should have nodes that have no dependencies and no dependents", async (t) => { let eleventyConfig = new TemplateConfig(); - let tmpl1 = getNewTemplateByNumber(1, eleventyConfig); - let tmpl5 = getNewTemplateByNumber(5, eleventyConfig); + await eleventyConfig.init(); + + let tmpl1 = await getNewTemplateByNumber(1, eleventyConfig); + let tmpl5 = await getNewTemplateByNumber(5, eleventyConfig); let tm = new TemplateMap(eleventyConfig); await tm.add(tmpl1); @@ -796,19 +814,18 @@ test("Dependency Map should have nodes that have no dependencies and no dependen test("Dependency Map should have include orphan user config collections (in the correct order)", async (t) => { let eleventyConfig = new TemplateConfig(); - let tmpl1 = getNewTemplateByNumber(1, eleventyConfig); - let tmpl5 = getNewTemplateByNumber(5, eleventyConfig); + eleventyConfig.userConfig.addCollection("userCollection", function (collection) { + return collection.getAll(); + }); + await eleventyConfig.init(); + + let tmpl1 = await getNewTemplateByNumber(1, eleventyConfig); + let tmpl5 = await getNewTemplateByNumber(5, eleventyConfig); let tm = new TemplateMap(eleventyConfig); await tm.add(tmpl1); await tm.add(tmpl5); - tm.setUserConfigCollections({ - userCollection: function (collection) { - return collection.getAll(); - }, - }); - await tm.cache(); let [deps, delayedDeps] = tm.getFullTemplateMapOrder(); @@ -822,8 +839,10 @@ test("Dependency Map should have include orphan user config collections (in the test("Template pages should not have layouts when added to collections", async (t) => { let eleventyConfig = new TemplateConfig(); + await eleventyConfig.init(); + let tm = new TemplateMap(eleventyConfig); - let tmpl = getNewTemplate( + let tmpl = await getNewTemplate( "./test/stubs/collection-layout-wrap.njk", "./test/stubs/", "./test/stubs/_site", @@ -839,9 +858,11 @@ test("Template pages should not have layouts when added to collections", async ( test("Paginated template pages should not have layouts when added to collections", async (t) => { let eleventyConfig = new TemplateConfig(); + await eleventyConfig.init(); + let tm = new TemplateMap(eleventyConfig); - let pagedTmpl = getNewTemplate( + let pagedTmpl = await getNewTemplate( "./test/stubs/tagged-pagination-multiples-layout/test.njk", "./test/stubs/", "./test/stubs/_site", @@ -859,12 +880,14 @@ test("Paginated template pages should not have layouts when added to collections test("Tag pages. Allow pagination over all collections a la `data: collections`", async (t) => { let eleventyConfig = new TemplateConfig(); - let tmpl1 = getNewTemplateByNumber(1, eleventyConfig); - let tmpl2 = getNewTemplateByNumber(2, eleventyConfig); + await eleventyConfig.init(); + + let tmpl1 = await getNewTemplateByNumber(1, eleventyConfig); + let tmpl2 = await getNewTemplateByNumber(2, eleventyConfig); let tm = new TemplateMap(eleventyConfig); - let pagedTmpl = getNewTemplate( + let pagedTmpl = await getNewTemplate( "./test/stubs/page-target-collections/tagpages.njk", "./test/stubs/", "./test/stubs/_site", @@ -892,12 +915,14 @@ test("Tag pages. Allow pagination over all collections a la `data: collections`" test("Tag pages (all pages added to collections). Allow pagination over all collections a la `data: collections`", async (t) => { let eleventyConfig = new TemplateConfig(); - let tmpl1 = getNewTemplateByNumber(1, eleventyConfig); - let tmpl2 = getNewTemplateByNumber(2, eleventyConfig); + await eleventyConfig.init(); + + let tmpl1 = await getNewTemplateByNumber(1, eleventyConfig); + let tmpl2 = await getNewTemplateByNumber(2, eleventyConfig); let tm = new TemplateMap(eleventyConfig); - let pagedTmpl = getNewTemplate( + let pagedTmpl = await getNewTemplate( "./test/stubs/page-target-collections/tagpagesall.njk", "./test/stubs/", "./test/stubs/_site", @@ -925,12 +950,14 @@ test("Tag pages (all pages added to collections). Allow pagination over all coll test("eleventyExcludeFromCollections", async (t) => { let eleventyConfig = new TemplateConfig(); - let tmpl1 = getNewTemplateByNumber(1, eleventyConfig); + await eleventyConfig.init(); + + let tmpl1 = await getNewTemplateByNumber(1, eleventyConfig); let tm = new TemplateMap(eleventyConfig); await tm.add(tmpl1); - let excludedTmpl = getNewTemplate( + let excludedTmpl = await getNewTemplate( "./test/stubs/eleventyExcludeFromCollections.njk", "./test/stubs/", "./test/stubs/_site", @@ -951,12 +978,14 @@ test("eleventyExcludeFromCollections", async (t) => { test("eleventyExcludeFromCollections and permalink: false", async (t) => { let eleventyConfig = new TemplateConfig(); - let tmpl1 = getNewTemplateByNumber(1, eleventyConfig); + await eleventyConfig.init(); + + let tmpl1 = await getNewTemplateByNumber(1, eleventyConfig); let tm = new TemplateMap(eleventyConfig); await tm.add(tmpl1); - let excludedTmpl = getNewTemplate( + let excludedTmpl = await getNewTemplate( "./test/stubs/eleventyExcludeFromCollectionsPermalinkFalse.njk", "./test/stubs/", "./test/stubs/_site", @@ -977,12 +1006,14 @@ test("eleventyExcludeFromCollections and permalink: false", async (t) => { test("Paginate over collections.all", async (t) => { let eleventyConfig = new TemplateConfig(); - let tmpl1 = getNewTemplateByNumber(1, eleventyConfig); - let tmpl2 = getNewTemplateByNumber(2, eleventyConfig); + await eleventyConfig.init(); + + let tmpl1 = await getNewTemplateByNumber(1, eleventyConfig); + let tmpl2 = await getNewTemplateByNumber(2, eleventyConfig); let tm = new TemplateMap(eleventyConfig); - let pagedTmpl = getNewTemplate( + let pagedTmpl = await getNewTemplate( "./test/stubs/page-target-collections/paginateall.njk", "./test/stubs/", "./test/stubs/_site", @@ -1027,18 +1058,20 @@ test("Paginate over collections.all", async (t) => { test("Paginate over collections.all WITH a paginate over collections (tag pages)", async (t) => { let eleventyConfig = new TemplateConfig(); - let tmpl1 = getNewTemplateByNumber(1, eleventyConfig); - let tmpl2 = getNewTemplateByNumber(2, eleventyConfig); + await eleventyConfig.init(); + + let tmpl1 = await getNewTemplateByNumber(1, eleventyConfig); + let tmpl2 = await getNewTemplateByNumber(2, eleventyConfig); let tm = new TemplateMap(eleventyConfig); - let pagedTmpl = getNewTemplate( + let pagedTmpl = await getNewTemplate( "./test/stubs/page-target-collections/paginateall.njk", "./test/stubs/", "./test/stubs/_site", eleventyConfig ); - let tagPagesTmpl = getNewTemplate( + let tagPagesTmpl = await getNewTemplate( "./test/stubs/page-target-collections/tagpagesall.njk", "./test/stubs/", "./test/stubs/_site", @@ -1058,8 +1091,10 @@ test("Paginate over collections.all WITH a paginate over collections (tag pages) test("Test a transform with a layout (via templateMap)", async (t) => { t.plan(7); let eleventyConfig = new TemplateConfig(); + await eleventyConfig.init(); + let tm = new TemplateMap(eleventyConfig); - let tmpl = getNewTemplate( + let tmpl = await getNewTemplate( "./test/stubs-475/transform-layout/transform-layout.njk", "./test/stubs-475/", "./test/stubs-475/_site", @@ -1093,19 +1128,19 @@ test("Test a transform with a layout (via templateMap)", async (t) => { test("Async user collection addCollection method", async (t) => { let eleventyConfig = new TemplateConfig(); - let tmpl1 = getNewTemplateByNumber(1, eleventyConfig); + eleventyConfig.userConfig.addCollection("userCollection", async function (collection) { + return new Promise((resolve) => { + setTimeout(function () { + resolve(collection.getAll()); + }, 50); + }); + }); + await eleventyConfig.init(); + + let tmpl1 = await getNewTemplateByNumber(1, eleventyConfig); let tm = new TemplateMap(eleventyConfig); await tm.add(tmpl1); - tm.setUserConfigCollections({ - userCollection: async function (collection) { - return new Promise((resolve) => { - setTimeout(function () { - resolve(collection.getAll()); - }, 50); - }); - }, - }); let collections = await tm._testGetCollectionsData(); t.is(collections.userCollection[0].url, "/templateMapCollection/test1/"); @@ -1115,14 +1150,15 @@ test("Async user collection addCollection method", async (t) => { test("Duplicate permalinks in template map", async (t) => { let eleventyConfig = new TemplateConfig(); + await eleventyConfig.init(); - let tmpl1 = getNewTemplate( + let tmpl1 = await getNewTemplate( "./test/stubs/permalink-conflicts/test1.md", "./test/stubs/", "./test/stubs/_site", eleventyConfig ); - let tmpl2 = getNewTemplate( + let tmpl2 = await getNewTemplate( "./test/stubs/permalink-conflicts/test2.md", "./test/stubs/", "./test/stubs/_site", @@ -1139,14 +1175,15 @@ test("Duplicate permalinks in template map", async (t) => { test("No duplicate permalinks in template map, using false", async (t) => { let eleventyConfig = new TemplateConfig(); + await eleventyConfig.init(); - let tmpl1 = getNewTemplate( + let tmpl1 = await getNewTemplate( "./test/stubs/permalink-conflicts-false/test1.md", "./test/stubs/", "./test/stubs/_site", eleventyConfig ); - let tmpl2 = getNewTemplate( + let tmpl2 = await getNewTemplate( "./test/stubs/permalink-conflicts-false/test2.md", "./test/stubs/", "./test/stubs/_site", @@ -1162,14 +1199,15 @@ test("No duplicate permalinks in template map, using false", async (t) => { test("Duplicate permalinks in template map, no leading slash", async (t) => { let eleventyConfig = new TemplateConfig(); + await eleventyConfig.init(); - let tmpl1 = getNewTemplate( + let tmpl1 = await getNewTemplate( "./test/stubs/permalink-conflicts/test1.md", "./test/stubs/", "./test/stubs/_site", eleventyConfig ); - let tmpl3 = getNewTemplate( + let tmpl3 = await getNewTemplate( "./test/stubs/permalink-conflicts/test3.md", "./test/stubs/", "./test/stubs/_site", @@ -1187,9 +1225,10 @@ test("Duplicate permalinks in template map, no leading slash", async (t) => { test("TemplateMap circular references (map.templateContent) using eleventyExcludeFromCollections and collections.all", async (t) => { let eleventyConfig = new TemplateConfig(); + await eleventyConfig.init(); let tm = new TemplateMap(eleventyConfig); - let tmplExcluded = getNewTemplate( + let tmplExcluded = await getNewTemplate( "./test/stubs/issue-522/excluded.md", "./test/stubs/", "./test/stubs/_site", @@ -1197,7 +1236,7 @@ test("TemplateMap circular references (map.templateContent) using eleventyExclud ); await tm.add(tmplExcluded); - let tmpl = getNewTemplate( + let tmpl = await getNewTemplate( "./test/stubs/issue-522/template.md", "./test/stubs/", "./test/stubs/_site", @@ -1225,8 +1264,10 @@ test("TemplateMap circular references (map.templateContent) using eleventyExclud test("permalink object with build", async (t) => { let eleventyConfig = new TemplateConfig(); + await eleventyConfig.init(); + let tm = new TemplateMap(eleventyConfig); - let tmplLayout = getNewTemplate( + let tmplLayout = await getNewTemplate( "./test/stubs/permalink-build/permalink-build.md", "./test/stubs/", "./test/stubs/_site", @@ -1243,8 +1284,10 @@ test("permalink object with build", async (t) => { test("permalink object without build (defaults to `read` mode)", async (t) => { let eleventyConfig = new TemplateConfig(); + await eleventyConfig.init(); + let tm = new TemplateMap(eleventyConfig); - let tmpl = getNewTemplate( + let tmpl = await getNewTemplate( "./test/stubs/permalink-nobuild/permalink-nobuild.md", "./test/stubs/", "./test/stubs/_site", @@ -1267,146 +1310,10 @@ test("permalink object without build (defaults to `read` mode)", async (t) => { ); }); -test("serverlessUrlMap Event (without `build`, only `serverless`)", async (t) => { - t.plan(1); - - let eleventyConfig = new TemplateConfig(); - eleventyConfig.userConfig.on("eleventy.serverlessUrlMap", (templateMap) => { - t.deepEqual(templateMap, [ - { - inputPath: "./test/stubs/permalink-nobuild/permalink-nobuild.md", - serverless: { - serverless: "/url/", - }, - }, - ]); - }); - - let tm = new TemplateMap(eleventyConfig); - let tmpl = getNewTemplate( - "./test/stubs/permalink-nobuild/permalink-nobuild.md", - "./test/stubs/", - "./test/stubs/_site", - eleventyConfig - ); - - await tm.add(tmpl); - await tm.cache(); -}); - -test("serverlessUrlMap Event (with `build`)", async (t) => { - t.plan(1); - - let eleventyConfig = new TemplateConfig(); - eleventyConfig.userConfig.on("eleventy.serverlessUrlMap", (templateMap) => { - t.deepEqual(templateMap, [ - { - inputPath: "./test/stubs/permalink-build/permalink-build.md", - serverless: {}, - }, - ]); - }); - - let tm = new TemplateMap(eleventyConfig); - let tmpl = getNewTemplate( - "./test/stubs/permalink-build/permalink-build.md", - "./test/stubs/", - "./test/stubs/_site", - eleventyConfig - ); - - await tm.add(tmpl); - await tm.cache(); -}); - -test("serverlessUrlMap Event (with `build` and `serverless`)", async (t) => { - t.plan(1); - - let eleventyConfig = new TemplateConfig(); - eleventyConfig.userConfig.on("eleventy.serverlessUrlMap", (templateMap) => { - t.deepEqual(templateMap, [ - { - inputPath: "./test/stubs/permalink-build-serverless/permalink-build-serverless.md", - serverless: { - serverless: "/some-other-url/", - }, - }, - ]); - }); - - let tm = new TemplateMap(eleventyConfig); - let tmpl = getNewTemplate( - "./test/stubs/permalink-build-serverless/permalink-build-serverless.md", - "./test/stubs/", - "./test/stubs/_site", - eleventyConfig - ); - - await tm.add(tmpl); - await tm.cache(); -}); - -test("serverlessUrlMap Event (with templating on both `build` and `serverless`)", async (t) => { - t.plan(1); - - let eleventyConfig = new TemplateConfig(); - eleventyConfig.userConfig.on("eleventy.serverlessUrlMap", (templateMap) => { - t.deepEqual(templateMap, [ - { - inputPath: - "./test/stubs/permalink-build-serverless-rendered/permalink-build-serverless-rendered.md", - serverless: { - serverless: "/some-other-url/", - }, - }, - ]); - }); - - let tm = new TemplateMap(eleventyConfig); - let tmpl = getNewTemplate( - "./test/stubs/permalink-build-serverless-rendered/permalink-build-serverless-rendered.md", - "./test/stubs/", - "./test/stubs/_site", - eleventyConfig - ); - - await tm.add(tmpl); - await tm.cache(); -}); - -test("serverlessUrlMap Event (empty pagination template with `serverless` should still show up)", async (t) => { - t.plan(1); - - let eleventyConfig = new TemplateConfig(); - eleventyConfig.userConfig.on("eleventy.serverlessUrlMap", (templateMap) => { - t.deepEqual(templateMap, [ - { - inputPath: - "./test/stubs/permalink-serverless-empty-pagination/permalink-serverless-empty-pagination.md", - serverless: { - serverless: "/url/", - }, - }, - ]); - }); - - let tm = new TemplateMap(eleventyConfig); - let tmpl = getNewTemplate( - "./test/stubs/permalink-serverless-empty-pagination/permalink-serverless-empty-pagination.md", - "./test/stubs/", - "./test/stubs/_site", - eleventyConfig - ); - - await tm.add(tmpl); - await tm.cache(); -}); - test("eleventy.layouts Event", async (t) => { t.plan(1); let eleventyConfig = new TemplateConfig(); - eleventyConfig.userConfig.on("eleventy.layouts", (layoutMap) => { t.deepEqual(layoutMap, { "./test/stubs-layouts-event/_includes/first.liquid": ["./test/stubs-layouts-event/page.md"], @@ -1421,9 +1328,10 @@ test("eleventy.layouts Event", async (t) => { ], }); }); + await eleventyConfig.init(); let tm = new TemplateMap(eleventyConfig); - let tmpl = getNewTemplate( + let tmpl = await getNewTemplate( "./test/stubs-layouts-event/page.md", "./test/stubs-layouts-event/", "./test/stubs-layouts-event/_site", diff --git a/test/TemplatePassthroughManagerTest.js b/test/TemplatePassthroughManagerTest.js index ed7db766d..8be7411c5 100644 --- a/test/TemplatePassthroughManagerTest.js +++ b/test/TemplatePassthroughManagerTest.js @@ -1,15 +1,18 @@ -const test = require("ava"); -const fs = require("fs"); -const TemplatePassthroughManager = require("../src/TemplatePassthroughManager"); -const TemplateConfig = require("../src/TemplateConfig"); -const FileSystemSearch = require("../src/FileSystemSearch"); -const EleventyFiles = require("../src/EleventyFiles"); +import test from "ava"; +import fs from "fs"; + +import TemplatePassthroughManager from "../src/TemplatePassthroughManager.js"; +import TemplateConfig from "../src/TemplateConfig.js"; +import FileSystemSearch from "../src/FileSystemSearch.js"; +import EleventyFiles from "../src/EleventyFiles.js"; test("Get paths from Config", async (t) => { let eleventyConfig = new TemplateConfig(); eleventyConfig.userConfig.passthroughCopies = { img: { outputPath: true }, }; + await eleventyConfig.init(); + let mgr = new TemplatePassthroughManager(eleventyConfig); t.deepEqual(mgr.getConfigPaths(), [{ inputPath: "./img", outputPath: true, copyOptions: {} }]); @@ -21,6 +24,8 @@ test("isPassthroughCopyFile", async (t) => { img: { outputPath: true }, fonts: { outputPath: true }, }; + await eleventyConfig.init(); + let mgr = new TemplatePassthroughManager(eleventyConfig); t.truthy(mgr.isPassthroughCopyFile([], "./img/test.png")); @@ -49,6 +54,8 @@ test("Get glob paths from config", async (t) => { "test/stubs/img/**": { outputPath: "./" }, "test/stubs/img/*.js": { outputPath: "./" }, }; + await eleventyConfig.init(); + let mgr = new TemplatePassthroughManager(eleventyConfig); t.deepEqual(mgr.getConfigPathGlobs(), [ @@ -60,6 +67,8 @@ test("Get glob paths from config", async (t) => { test("Get file paths", async (t) => { let eleventyConfig = new TemplateConfig(); + await eleventyConfig.init(); + let mgr = new TemplatePassthroughManager(eleventyConfig); t.deepEqual(mgr.getNonTemplatePaths(["test.png"]), ["test.png"]); @@ -67,6 +76,8 @@ test("Get file paths", async (t) => { test("Get file paths (filter out real templates)", async (t) => { let eleventyConfig = new TemplateConfig(); + await eleventyConfig.init(); + let mgr = new TemplatePassthroughManager(eleventyConfig); t.deepEqual(mgr.getNonTemplatePaths(["test.njk"]), []); @@ -74,6 +85,8 @@ test("Get file paths (filter out real templates)", async (t) => { test("Get file paths (filter out real templates), multiple", async (t) => { let eleventyConfig = new TemplateConfig(); + await eleventyConfig.init(); + let mgr = new TemplatePassthroughManager(eleventyConfig); t.deepEqual(mgr.getNonTemplatePaths(["test.njk", "test.png"]), ["test.png"]); @@ -81,6 +94,8 @@ test("Get file paths (filter out real templates), multiple", async (t) => { test("Get file paths with a js file (filter out real templates), multiple", async (t) => { let eleventyConfig = new TemplateConfig(); + await eleventyConfig.init(); + let mgr = new TemplatePassthroughManager(eleventyConfig); t.deepEqual(mgr.getNonTemplatePaths(["test.njk", "test.js"]), ["test.js"]); @@ -89,6 +104,8 @@ test("Get file paths with a js file (filter out real templates), multiple", asyn // This test used to be for passthroughFileCopy: false in config test("Get file paths (one image path)", async (t) => { let eleventyConfig = new TemplateConfig(); + await eleventyConfig.init(); + let mgr = new TemplatePassthroughManager(eleventyConfig); t.deepEqual(mgr.getNonTemplatePaths(["test.png"]), ["test.png"]); @@ -103,6 +120,7 @@ test("Naughty paths outside of project dir", async (t) => { "./test/stubs/template-passthrough2/static/*.js": { outputPath: "../../" }, "./test/stubs/template-passthrough2/img.jpg": { outputPath: "../../" }, }; + await eleventyConfig.init(); let mgr = new TemplatePassthroughManager(eleventyConfig); @@ -131,6 +149,7 @@ test("getAllNormalizedPaths", async (t) => { eleventyConfig.userConfig.passthroughCopies = { img: { outputPath: true }, }; + await eleventyConfig.init(); let mgr = new TemplatePassthroughManager(eleventyConfig); t.deepEqual(mgr.getAllNormalizedPaths(), [ @@ -145,6 +164,7 @@ test("getAllNormalizedPaths with globs", async (t) => { "img/**": { outputPath: "./" }, "img/*.js": { outputPath: "./" }, }; + await eleventyConfig.init(); let mgr = new TemplatePassthroughManager(eleventyConfig); t.deepEqual(mgr.getAllNormalizedPaths(), [ @@ -162,6 +182,7 @@ test("Look for uniqueness on template passthrough paths #1677", async (t) => { outputPath: "./", }, }; + await eleventyConfig.init(); let files = new EleventyFiles( "test/stubs/template-passthrough-duplicates", diff --git a/test/TemplatePassthroughTest.js b/test/TemplatePassthroughTest.js index 92cd423d9..9fa4e2128 100644 --- a/test/TemplatePassthroughTest.js +++ b/test/TemplatePassthroughTest.js @@ -1,10 +1,13 @@ -const test = require("ava"); -const TemplateConfig = require("../src/TemplateConfig"); -const FileSystemSearch = require("../src/FileSystemSearch"); -const TemplatePassthrough = require("../src/TemplatePassthrough"); +import test from "ava"; -const getTemplatePassthrough = (path, outputDir, inputDir) => { +import TemplateConfig from "../src/TemplateConfig.js"; +import FileSystemSearch from "../src/FileSystemSearch.js"; +import TemplatePassthrough from "../src/TemplatePassthrough.js"; + +async function getTemplatePassthrough(path, outputDir, inputDir) { let eleventyConfig = new TemplateConfig(); + await eleventyConfig.init(); + let config = eleventyConfig.getConfig(); if (typeof path === "object") { @@ -21,21 +24,21 @@ const getTemplatePassthrough = (path, outputDir, inputDir) => { ); p.setFileSystemSearch(new FileSystemSearch()); return p; -}; +} -test("Constructor", (t) => { - let pass = getTemplatePassthrough("avatar.png", "_site", "."); +test("Constructor", async (t) => { + let pass = await getTemplatePassthrough("avatar.png", "_site", "."); t.truthy(pass); t.is(pass.outputPath, true); t.is(pass.getOutputPath(), "_site/avatar.png"); }); -test("Constructor, input directory in inputPath is stripped", (t) => { - let pass = getTemplatePassthrough("src/avatar.png", "_site", "src"); +test("Constructor, input directory in inputPath is stripped", async (t) => { + let pass = await getTemplatePassthrough("src/avatar.png", "_site", "src"); t.is(pass.outputPath, true); t.is(pass.getOutputPath(), "_site/avatar.png"); - let pass2 = getTemplatePassthrough( + let pass2 = await getTemplatePassthrough( { inputPath: "src/avatar.png", outputPath: "avatar.png" }, "_site", "src" @@ -44,12 +47,12 @@ test("Constructor, input directory in inputPath is stripped", (t) => { t.is(pass2.getOutputPath(), "_site/avatar.png"); }); -test("Constructor, input directory in inputPath is stripped, duplicate directory names", (t) => { - let pass = getTemplatePassthrough("src/src/avatar.png", "_site", "src"); +test("Constructor, input directory in inputPath is stripped, duplicate directory names", async (t) => { + let pass = await getTemplatePassthrough("src/src/avatar.png", "_site", "src"); t.is(pass.outputPath, true); t.is(pass.getOutputPath(), "_site/src/avatar.png"); - let pass2 = getTemplatePassthrough( + let pass2 = await getTemplatePassthrough( { inputPath: "src/src/avatar.png", outputPath: "src/avatar.png" }, "_site", "src" @@ -58,18 +61,22 @@ test("Constructor, input directory in inputPath is stripped, duplicate directory t.is(pass2.getOutputPath(), "_site/src/avatar.png"); }); -test("Constructor, input directory (object param, directory)", (t) => { - let pass = getTemplatePassthrough({ inputPath: "src/test", outputPath: "test" }, "_site", "src"); +test("Constructor, input directory (object param, directory)", async (t) => { + let pass = await getTemplatePassthrough( + { inputPath: "src/test", outputPath: "test" }, + "_site", + "src" + ); t.is(pass.outputPath, "test"); t.is(pass.getOutputPath(), "_site/test"); }); -test("Constructor, input directory, path missing input directory", (t) => { - let pass = getTemplatePassthrough("avatar.png", "_site", "src"); +test("Constructor, input directory, path missing input directory", async (t) => { + let pass = await getTemplatePassthrough("avatar.png", "_site", "src"); t.is(pass.outputPath, true); t.is(pass.getOutputPath(), "_site/avatar.png"); - let pass2 = getTemplatePassthrough( + let pass2 = await getTemplatePassthrough( { inputPath: "avatar.png", outputPath: "avatar.png" }, "_site", "src" @@ -78,31 +85,31 @@ test("Constructor, input directory, path missing input directory", (t) => { t.is(pass2.getOutputPath(), "_site/avatar.png"); }); -test("Constructor Dry Run", (t) => { - let pass = getTemplatePassthrough("avatar.png", "_site", "."); +test("Constructor Dry Run", async (t) => { + let pass = await getTemplatePassthrough("avatar.png", "_site", "."); pass.setDryRun(true); t.is(pass.outputPath, true); t.is(pass.isDryRun, true); }); -test("Origin path isn’t included in output when targeting a directory", (t) => { - let pass = getTemplatePassthrough("img", "_site", "_src"); +test("Origin path isn’t included in output when targeting a directory", async (t) => { + let pass = await getTemplatePassthrough("img", "_site", "_src"); t.is(pass.outputPath, true); t.is(pass.getOutputPath(), "_site/img"); }); -test("Origin path isn’t included in output when targeting a directory several levels deep", (t) => { - let pass = getTemplatePassthrough("img", "_site", "_src/subdir"); +test("Origin path isn’t included in output when targeting a directory several levels deep", async (t) => { + let pass = await getTemplatePassthrough("img", "_site", "_src/subdir"); t.is(pass.outputPath, true); t.is(pass.getOutputPath(), "_site/img"); }); -test("Target directory’s subdirectory structure is retained", (t) => { - let pass = getTemplatePassthrough("subdir/img", "_site", "_src"); +test("Target directory’s subdirectory structure is retained", async (t) => { + let pass = await getTemplatePassthrough("subdir/img", "_site", "_src"); t.is(pass.outputPath, true); t.is(pass.getOutputPath(), "_site/subdir/img"); - let pass2 = getTemplatePassthrough( + let pass2 = await getTemplatePassthrough( { inputPath: "subdir/img", outputPath: "subdir/img" }, "_site", "_src" @@ -110,60 +117,53 @@ test("Target directory’s subdirectory structure is retained", (t) => { t.is(pass2.getOutputPath(), "_site/subdir/img"); }); -test("Origin path isn’t included in output when targeting a file", (t) => { - let pass = getTemplatePassthrough("avatar.png", "_site", "_src"); +test("Origin path isn’t included in output when targeting a file", async (t) => { + let pass = await getTemplatePassthrough("avatar.png", "_site", "_src"); t.is(pass.outputPath, true); t.is(pass.getOutputPath(), "_site/avatar.png"); }); -test("Origin path isn’t included in output when targeting a file several levels deep", (t) => { - let pass = getTemplatePassthrough("avatar.png", "_site", "_src/subdir/img"); +test("Origin path isn’t included in output when targeting a file several levels deep", async (t) => { + let pass = await getTemplatePassthrough("avatar.png", "_site", "_src/subdir/img"); t.is(pass.outputPath, true); t.is(pass.getOutputPath(), "_site/avatar.png"); }); -test("Full input file path and deep input path", (t) => { - t.is( - getTemplatePassthrough("src/views/avatar.png", "_site", "src/views/").getOutputPath(), - "_site/avatar.png" - ); - t.is( - getTemplatePassthrough("src/views/avatar.png", "_site", "src/views").getOutputPath(), - "_site/avatar.png" - ); - t.is( - getTemplatePassthrough("src/views/avatar.png", "_site/", "src/views").getOutputPath(), - "_site/avatar.png" - ); - t.is( - getTemplatePassthrough("src/views/avatar.png", "./_site", "./src/views").getOutputPath(), - "_site/avatar.png" - ); - t.is( - getTemplatePassthrough("./src/views/avatar.png", "./_site/", "./src/views/").getOutputPath(), - "_site/avatar.png" - ); - t.is( - getTemplatePassthrough("./src/views/avatar.png", "_site", "src/views/").getOutputPath(), - "_site/avatar.png" - ); +test("Full input file path and deep input path", async (t) => { + let tp = await getTemplatePassthrough("src/views/avatar.png", "_site", "src/views/"); + t.is(tp.getOutputPath(), "_site/avatar.png"); + + let tp2 = await getTemplatePassthrough("src/views/avatar.png", "_site", "src/views"); + t.is(tp2.getOutputPath(), "_site/avatar.png"); + + let tp3 = await getTemplatePassthrough("src/views/avatar.png", "_site/", "src/views"); + t.is(tp3.getOutputPath(), "_site/avatar.png"); + + let tp4 = await getTemplatePassthrough("src/views/avatar.png", "./_site", "./src/views"); + t.is(tp4.getOutputPath(), "_site/avatar.png"); + + let tp5 = await getTemplatePassthrough("./src/views/avatar.png", "./_site/", "./src/views/"); + t.is(tp5.getOutputPath(), "_site/avatar.png"); + + let tp6 = await getTemplatePassthrough("./src/views/avatar.png", "_site", "src/views/"); + t.is(tp6.getOutputPath(), "_site/avatar.png"); }); -test(".htaccess", (t) => { - let pass = getTemplatePassthrough(".htaccess", "_site", "."); +test(".htaccess", async (t) => { + let pass = await getTemplatePassthrough(".htaccess", "_site", "."); t.is(pass.outputPath, true); t.is(pass.getOutputPath(), "_site/.htaccess"); }); -test(".htaccess with input dir", (t) => { - let pass = getTemplatePassthrough(".htaccess", "_site", "_src"); +test(".htaccess with input dir", async (t) => { + let pass = await getTemplatePassthrough(".htaccess", "_site", "_src"); t.is(pass.outputPath, true); t.is(pass.getOutputPath(), "_site/.htaccess"); }); test("getFiles where not glob and file does not exist", async (t) => { const inputPath = ".htaccess"; - let pass = getTemplatePassthrough(inputPath, "_site", "_src"); + let pass = await getTemplatePassthrough(inputPath, "_site", "_src"); t.is(pass.outputPath, true); const files = await pass.getFiles(inputPath); t.deepEqual(files, []); @@ -171,7 +171,7 @@ test("getFiles where not glob and file does not exist", async (t) => { test("getFiles where not glob and directory does not exist", async (t) => { const inputPath = "./test/stubs/template-passthrough/static/not-exists/"; - let pass = getTemplatePassthrough(inputPath, "_site", "_src"); + let pass = await getTemplatePassthrough(inputPath, "_site", "_src"); t.is(pass.outputPath, true); const files = await pass.getFiles(inputPath); t.deepEqual(files, []); @@ -179,7 +179,7 @@ test("getFiles where not glob and directory does not exist", async (t) => { test("getFiles with glob", async (t) => { const inputPath = "./test/stubs/template-passthrough/static/**"; - let pass = getTemplatePassthrough(inputPath, "_site", "_src"); + let pass = await getTemplatePassthrough(inputPath, "_site", "_src"); t.is(pass.outputPath, true); const files = await pass.getFiles(inputPath); @@ -207,7 +207,7 @@ test("getFiles with glob", async (t) => { }); test("getFiles with glob 2", async (t) => { const inputPath = "./test/stubs/template-passthrough/static/**/*.js"; - let pass = getTemplatePassthrough(inputPath, "_site", "_src"); + let pass = await getTemplatePassthrough(inputPath, "_site", "_src"); t.is(pass.outputPath, true); const files = await pass.getFiles(inputPath); t.deepEqual(files, ["./test/stubs/template-passthrough/static/test.js"]); @@ -215,13 +215,17 @@ test("getFiles with glob 2", async (t) => { }); test("Directory where outputPath is true", async (t) => { - let pass = getTemplatePassthrough({ inputPath: "./static", outputPath: true }, "_site", "_src"); + let pass = await getTemplatePassthrough( + { inputPath: "./static", outputPath: true }, + "_site", + "_src" + ); t.is(pass.outputPath, true); t.is(pass.getOutputPath(), "_site/static"); }); test("Nested directory where outputPath is remapped", async (t) => { - let pass = getTemplatePassthrough( + let pass = await getTemplatePassthrough( { inputPath: "./static/nested", outputPath: "./test" }, "_site", "_src" @@ -232,7 +236,7 @@ test("Nested directory where outputPath is remapped", async (t) => { test("Glob pattern", async (t) => { const globResolvedPath = "./test/stubs/template-passthrough/static/test.js"; - let pass = getTemplatePassthrough( + let pass = await getTemplatePassthrough( { inputPath: "./test/stubs/template-passthrough/static/*.js", outputPath: "./directory/", @@ -245,18 +249,18 @@ test("Glob pattern", async (t) => { }); test("Output paths match with different templatePassthrough methods", async (t) => { - let pass1 = getTemplatePassthrough( + let pass1 = await getTemplatePassthrough( { inputPath: "./static/nested", outputPath: "./test" }, "_site", "_src" ); - let pass2 = getTemplatePassthrough("avatar.png", "_site/test", "."); + let pass2 = await getTemplatePassthrough("avatar.png", "_site/test", "."); t.is(pass1.getOutputPathForGlobFile("avatar.png"), pass2.getOutputPath()); }); // ToDo: Currently can't do :( // test("File renamed", async t => { -// let pass = getTemplatePassthrough( +// let pass = await getTemplatePassthrough( // { // inputPath: "./test/stubs/template-passthrough/static/test.js", // outputPath: "./rename.js" @@ -269,7 +273,7 @@ test("Output paths match with different templatePassthrough methods", async (t) // }); test("Bug with incremental file copying to a directory output, issue #2278 #1038", async (t) => { - let pass1 = getTemplatePassthrough( + let pass1 = await getTemplatePassthrough( { inputPath: "./test/stubs/public/test.css", outputPath: "/" }, "test/stubs", "." @@ -279,7 +283,7 @@ test("Bug with incremental file copying to a directory output, issue #2278 #1038 }); test("Bug with incremental dir copying to a directory output, issue #2278 #1038", async (t) => { - let pass1 = getTemplatePassthrough( + let pass1 = await getTemplatePassthrough( { inputPath: "./test/stubs/public/", outputPath: "/" }, "test/stubs", "." diff --git a/test/TemplatePermalinkTest.js b/test/TemplatePermalinkTest.js index 1ea63a502..d032c13b2 100644 --- a/test/TemplatePermalinkTest.js +++ b/test/TemplatePermalinkTest.js @@ -1,5 +1,6 @@ -const test = require("ava"); -const TemplatePermalink = require("../src/TemplatePermalink"); +import test from "ava"; +import TemplatePermalink from "../src/TemplatePermalink.js"; + const { generate } = TemplatePermalink; test("Simple straight permalink", (t) => { @@ -41,18 +42,9 @@ test("Permalink without filename", (t) => { "/permalinksubfolder/index.html" ); - t.is( - new TemplatePermalink("permalinksubfolder/").toHref(), - "/permalinksubfolder/" - ); - t.is( - new TemplatePermalink("./permalinksubfolder/").toHref(), - "/permalinksubfolder/" - ); - t.is( - new TemplatePermalink("/permalinksubfolder/").toHref(), - "/permalinksubfolder/" - ); + t.is(new TemplatePermalink("permalinksubfolder/").toHref(), "/permalinksubfolder/"); + t.is(new TemplatePermalink("./permalinksubfolder/").toHref(), "/permalinksubfolder/"); + t.is(new TemplatePermalink("/permalinksubfolder/").toHref(), "/permalinksubfolder/"); }); test("Permalink with pagination subdir", (t) => { @@ -103,10 +95,7 @@ test("Permalink generate with new extension", (t) => { }); test("Permalink generate with subfolders", (t) => { - t.is( - generate("permalinksubfolder/", "index").toOutputPath(), - "permalinksubfolder/index.html" - ); + t.is(generate("permalinksubfolder/", "index").toOutputPath(), "permalinksubfolder/index.html"); t.is( generate("permalinksubfolder/", "test").toOutputPath(), "permalinksubfolder/test/index.html" @@ -116,14 +105,8 @@ test("Permalink generate with subfolders", (t) => { "permalinksubfolder/test/1/index-o.html" ); - t.is( - generate("permalinksubfolder/", "index").toHref(), - "/permalinksubfolder/" - ); - t.is( - generate("permalinksubfolder/", "test").toHref(), - "/permalinksubfolder/test/" - ); + t.is(generate("permalinksubfolder/", "index").toHref(), "/permalinksubfolder/"); + t.is(generate("permalinksubfolder/", "test").toHref(), "/permalinksubfolder/test/"); t.is( generate("permalinksubfolder/", "test", "1/", "-o").toHref(), "/permalinksubfolder/test/1/index-o.html" @@ -139,10 +122,7 @@ test("Permalink matching folder and filename", (t) => { t.is(hasDupe("component", "component"), true); t.is(hasDupe("component/", "component"), true); - t.is( - generate("component/", "component").toOutputPath(), - "component/index.html" - ); + t.is(generate("component/", "component").toOutputPath(), "component/index.html"); t.is(generate("component/", "component").toHref(), "/component/"); }); @@ -168,104 +148,12 @@ test("Permalink Object, just build", (t) => { }); }); -test("Permalink Object, serverless URLs", (t) => { - // serverless - t.is( - new TemplatePermalink({ - serverless: "permalinksubfolder/test.html", - }).toOutputPath(), - false - ); - - t.is( - new TemplatePermalink({ - serverless: "permalinksubfolder/test.html", - }).toHref(), - "permalinksubfolder/test.html" - ); - - // request - t.is( - new TemplatePermalink({ - request: "/url/", - }).toOutputPath(), - false - ); - - t.is( - new TemplatePermalink({ - request: "/url/", - }).toHref(), - "/url/" - ); - - // rando - t.is( - new TemplatePermalink({ - rando: "/url/", - }).toOutputPath(), - false - ); - - t.is( - new TemplatePermalink({ - rando: "/url/", - }).toHref(), - "/url/" - ); -}); - -test("Permalink Object, combo build and serverless URLs", (t) => { - t.is( - new TemplatePermalink({ - build: "/url/", - serverless: "/serverless/", - }).toOutputPath(), - "/url/index.html" - ); - - t.is( - new TemplatePermalink({ - build: "/url/", - serverless: "/serverless/", - }).toHref(), - "/url/" - ); - - // reordered, serverless is primary - t.is( - new TemplatePermalink({ - serverless: "/serverless/", - build: "/url/", - }).toOutputPath(), - "/url/index.html" - ); - - t.is( - new TemplatePermalink({ - serverless: "/serverless/", - build: "/url/", - }).toHref(), - "/serverless/" - ); -}); - test("Permalink Object, empty object", (t) => { t.is(new TemplatePermalink({}).toOutputPath(), false); t.is(new TemplatePermalink({}).toHref(), false); }); -test("Permalink Object, serverless with path params", (t) => { - let perm = new TemplatePermalink({ - serverless: "/serverless/:test/", - }); - perm.setServerlessPathData({ - test: "yeearg", - }); - t.is(perm.toHref(), "/serverless/yeearg/"); -}); - test("Permalink generate apache content negotiation #761", (t) => { let tp = new TemplatePermalink("index.es.html"); tp.setUrlTransforms([ diff --git a/test/TemplateRenderCustomTest.js b/test/TemplateRenderCustomTest.js index 00805f23e..a3e90fbdc 100644 --- a/test/TemplateRenderCustomTest.js +++ b/test/TemplateRenderCustomTest.js @@ -1,21 +1,27 @@ -const test = require("ava"); -const TemplateRender = require("../src/TemplateRender"); -const EleventyExtensionMap = require("../src/EleventyExtensionMap"); -const TemplateConfig = require("../src/TemplateConfig"); -const getNewTemplate = require("./_getNewTemplateForTests"); +import test from "ava"; +import { createSSRApp } from "vue"; +import { renderToString } from "@vue/server-renderer"; +import * as sass from "sass"; -const { createSSRApp } = require("vue"); -const { renderToString } = require("@vue/server-renderer"); +import TemplateRender from "../src/TemplateRender.js"; +import EleventyExtensionMap from "../src/EleventyExtensionMap.js"; +import TemplateConfig from "../src/TemplateConfig.js"; +import getNewTemplate from "./_getNewTemplateForTests.js"; -function getNewTemplateRender(name, inputDir, eleventyConfig, extensionMap) { +async function getNewTemplateRender(name, inputDir, eleventyConfig, extensionMap) { if (!eleventyConfig) { eleventyConfig = new TemplateConfig(); + await eleventyConfig.init(); } + if (!extensionMap) { extensionMap = new EleventyExtensionMap([], eleventyConfig); } + let tr = new TemplateRender(name, inputDir, eleventyConfig); tr.extensionMap = extensionMap; + await tr.init(); + return tr; } @@ -31,8 +37,9 @@ test("Custom plaintext Render", async (t) => { }, }); - let tr = getNewTemplateRender("txt", null, eleventyConfig); + await eleventyConfig.init(); + let tr = await getNewTemplateRender("txt", null, eleventyConfig); let fn = await tr.getCompiledTemplate("

Paragraph

"); t.is(await fn(), "

Paragraph

"); t.is(await fn({}), "

Paragraph

"); @@ -50,7 +57,9 @@ test("Custom Markdown Render with `compile` override", async (t) => { }, }); - let tr = getNewTemplateRender("md", null, eleventyConfig); + await eleventyConfig.init(); + + let tr = await getNewTemplateRender("md", null, eleventyConfig); let fn = await tr.getCompiledTemplate("# Markdown?"); t.is((await fn()).trim(), "# Markdown?"); @@ -68,7 +77,9 @@ test("Custom Markdown Render without `compile` override", async (t) => { }, }); - let tr = getNewTemplateRender("md", null, eleventyConfig); + await eleventyConfig.init(); + + let tr = await getNewTemplateRender("md", null, eleventyConfig); let fn = await tr.getCompiledTemplate("# Header"); t.is(initCalled, true); @@ -89,21 +100,19 @@ test("Custom Markdown Render with `compile` override + call to default compiler" }, }); - let tr = getNewTemplateRender("md", null, eleventyConfig); + await eleventyConfig.init(); + + let tr = await getNewTemplateRender("md", null, eleventyConfig); let fn = await tr.getCompiledTemplate("Hey {{name}}"); t.is((await fn()).trim(), "

Hey

"); - t.is( - (await fn({ name: "Zach" })).trim(), - "

Hey Zach

" - ); + t.is((await fn({ name: "Zach" })).trim(), "

Hey Zach

"); }); test("Custom Vue Render", async (t) => { - let tr = getNewTemplateRender("vue"); - + let eleventyConfig = new TemplateConfig(); // addExtension() API - tr.eleventyConfig.userConfig.addExtension("vue", { + eleventyConfig.userConfig.addExtension("vue", { compile: function (str) { return async function (data) { const app = createSSRApp({ @@ -117,18 +126,18 @@ test("Custom Vue Render", async (t) => { }; }, }); + await eleventyConfig.init(); + let tr = await getNewTemplateRender("vue", null, eleventyConfig); let fn = await tr.getCompiledTemplate('

Paragraph

'); t.is(await fn({ test: "Hello" }), "

Hello

"); }); test("Custom Sass Render", async (t) => { - const sass = require("sass"); - - let tr = getNewTemplateRender("sass"); + let eleventyConfig = new TemplateConfig(); // addExtension() API - tr.eleventyConfig.userConfig.addExtension("sass", { + eleventyConfig.userConfig.addExtension("sass", { compile: function (str, inputPath) { // TODO declare data variables as SASS variables? return async function (data) { @@ -149,19 +158,22 @@ test("Custom Sass Render", async (t) => { } else { resolve(result.css.toString("utf8")); } - } + }, ); }); }; }, }); + await eleventyConfig.init(); + + let tr = await getNewTemplateRender("sass", null, eleventyConfig); let fn = await tr.getCompiledTemplate("$color: blue; p { color: $color; }"); t.is( (await fn({})).trim(), `p { color: blue; -}` +}`, ); }); @@ -200,13 +212,15 @@ test("JavaScript functions should not be mutable but not *that* mutable", async }, }); - let tmpl = getNewTemplate( + await eleventyConfig.init(); + + let tmpl = await getNewTemplate( "./test/stubs-custom-extension/test.js1", "./test/stubs-custom-extension/", "dist", null, null, - eleventyConfig + eleventyConfig, ); let data = await tmpl.getData(); t.is(await tmpl.render(data), "

Paragraph

"); @@ -221,9 +235,9 @@ test("Return undefined in compile to ignore #2267", async (t) => { return; }, }); + await eleventyConfig.init(); - let tr = getNewTemplateRender("txt", null, eleventyConfig); - + let tr = await getNewTemplateRender("txt", null, eleventyConfig); let fn = await tr.getCompiledTemplate("

Paragraph

"); t.is(fn, undefined); }); @@ -233,73 +247,69 @@ test("Simple alias to Markdown Render", async (t) => { eleventyConfig.userConfig.addExtension("mdx", { key: "md", }); + await eleventyConfig.init(); - let tr = getNewTemplateRender("mdx", null, eleventyConfig); + let tr = await getNewTemplateRender("mdx", null, eleventyConfig); let fn = await tr.getCompiledTemplate("# Header"); t.is((await fn()).trim(), "

Header

"); t.is((await fn({})).trim(), "

Header

"); }); -test("Simple alias to JavaScript Render", async (t) => { +// NOTE: Breaking change in 3.0 `import` does not allow aliasing to non-.js file names +test.skip("Breaking Change (3.0): Simple alias to JavaScript Render", async (t) => { let eleventyConfig = new TemplateConfig(); eleventyConfig.userConfig.addExtension("11ty.custom", { key: "11ty.js", }); + await eleventyConfig.init(); - let fn = await getNewTemplateRender( - "./test/stubs/string.11ty.custom", - null, - eleventyConfig - ).getCompiledTemplate(); + let tr = await getNewTemplateRender("./test/stubs/string.11ty.custom", null, eleventyConfig); + let fn = await tr.getCompiledTemplate(); t.is(await fn({ name: "Bill" }), "

Zach

"); }); -test("Override to JavaScript Render", async (t) => { +// NOTE: Breaking change in 3.0 `import` does not allow aliasing to non-.js file names +test.skip("Breaking Change (3.0): Override to JavaScript Render", async (t) => { let eleventyConfig = new TemplateConfig(); eleventyConfig.userConfig.addExtension("11ty.custom", { key: "11ty.js", init: function () {}, }); + await eleventyConfig.init(); - let fn = await getNewTemplateRender( - "./test/stubs/string.11ty.custom", - null, - eleventyConfig - ).getCompiledTemplate(); + let tr = await getNewTemplateRender("./test/stubs/string.11ty.custom", null, eleventyConfig); + let fn = await tr.getCompiledTemplate(); t.is(await fn({ name: "Bill" }), "

Zach

"); }); -test("Two simple aliases to JavaScript Render", async (t) => { +// NOTE: Breaking change in 3.0 `import` does not allow aliasing to non-.js file names +test.skip("Breaking Change (3.0): Two simple aliases to JavaScript Render", async (t) => { t.plan(2); let eleventyConfig = new TemplateConfig(); - let map = new EleventyExtensionMap([], eleventyConfig); // reuse this - eleventyConfig.userConfig.addExtension(["11ty.custom", "11ty.possum"], { - key: "11ty.js", + key: "11ty.js", // esm }); + await eleventyConfig.init(); - let fn = await getNewTemplateRender( - "./test/stubs/string.11ty.custom", - null, - eleventyConfig, - map - ).getCompiledTemplate(); + let map = new EleventyExtensionMap([], eleventyConfig); // reuse this + + let tr = await getNewTemplateRender("./test/stubs/string.11ty.custom", null, eleventyConfig, map); + let fn = await tr.getCompiledTemplate(); t.is(await fn({}), "

Zach

"); - let fn2 = await getNewTemplateRender( + let tr2 = await getNewTemplateRender( "./test/stubs/string.11ty.possum", null, eleventyConfig, - map - ).getCompiledTemplate(); + map, + ); + let fn2 = await tr2.getCompiledTemplate(); t.is(await fn2({}), "

Possum

"); }); test("Double override (not aliases) throws an error", async (t) => { let eleventyConfig = new TemplateConfig(); - let map = new EleventyExtensionMap([], eleventyConfig); // reuse this - eleventyConfig.userConfig.addExtension(["11ty.custom", "11ty.possum"], { key: "11ty.js", init: function () { @@ -307,18 +317,23 @@ test("Double override (not aliases) throws an error", async (t) => { }, }); + await eleventyConfig.init(); + + let map = new EleventyExtensionMap([], eleventyConfig); // reuse this + await t.throwsAsync( async () => { - await getNewTemplateRender( + let tr = await getNewTemplateRender( "./test/stubs/string.11ty.custom", null, eleventyConfig, - map - ).getCompiledTemplate(); + map, + ); + await tr.getCompiledTemplate(); }, { message: 'An attempt was made to override the *already* overridden "11ty.js" template syntax via the `addExtension` configuration API. A maximum of one override is currently supported. If you’re trying to add an alias to an existing syntax, make sure only the `key` property is present in the addExtension options object.', - } + }, ); }); diff --git a/test/TemplateRenderEJSTest.js b/test/TemplateRenderEJSTest.js deleted file mode 100644 index ab0a82323..000000000 --- a/test/TemplateRenderEJSTest.js +++ /dev/null @@ -1,113 +0,0 @@ -const test = require("ava"); -const TemplateRender = require("../src/TemplateRender"); -const TemplateConfig = require("../src/TemplateConfig"); -const EleventyExtensionMap = require("../src/EleventyExtensionMap"); - -function getNewTemplateRender(name, inputDir) { - let eleventyConfig = new TemplateConfig(); - let tr = new TemplateRender(name, inputDir, eleventyConfig); - tr.extensionMap = new EleventyExtensionMap([], eleventyConfig); - return tr; -} - -// EJS -test("EJS", (t) => { - t.is(getNewTemplateRender("ejs").getEngineName(), "ejs"); - t.is( - getNewTemplateRender("./test/stubs/filename.ejs").getEngineName(), - "ejs" - ); -}); - -test("EJS Render", async (t) => { - let fn = await getNewTemplateRender("ejs").getCompiledTemplate( - "

<%= name %>

" - ); - t.is(await fn({ name: "Zach" }), "

Zach

"); -}); - -test("EJS Render Absolute Include, Fxn no Data", async (t) => { - // includes require a full filename passed in - let fn = await getNewTemplateRender( - "./test/stubs/filename.ejs", - "./test/stubs/" - ).getCompiledTemplate("

<%- include('/included') %>

"); - t.is(await fn(), "

This is an include.

"); -}); - -test("EJS Render Absolute Include, Fxn with Data", async (t) => { - // includes require a full filename passed in - let fn = await getNewTemplateRender( - "./test/stubs/filename.ejs", - "./test/stubs/" - ).getCompiledTemplate( - "

<%- include('/includedvar', { name: 'Bill' }) %>

" - ); - t.is(await fn(), "

This is an Bill.

"); -}); - -test("EJS Render Relative Include (no leading dot-slash for current dir)", async (t) => { - // includes require a full filename passed in - let fn = await getNewTemplateRender( - "./test/stubs/relative-ejs/dir/filename.ejs", - "./test/stubs/" - ).getCompiledTemplate("

<%- include('included') -%>

"); - t.is(await fn(), "

This is an include.

"); -}); - -test("EJS Render Relative Include Current dir to Subdir", async (t) => { - // includes require a full filename passed in - let fn = await getNewTemplateRender( - "./test/stubs/relative-ejs/filename.ejs", - "./test/stubs/" - ).getCompiledTemplate("

<%- include('./dir/included') -%>

"); - t.is(await fn(), "

This is an include.

"); -}); - -test("EJS Render Relative Include Parent dir to Subdir", async (t) => { - // includes require a full filename passed in - let fn = await getNewTemplateRender( - "./test/stubs/relative-ejs/dir/filename.ejs", - "./test/stubs/" - ).getCompiledTemplate("

<%- include('../dir/included') -%>

"); - t.is(await fn(), "

This is an include.

"); -}); - -test("EJS Render Relative Include, Fxn no Data", async (t) => { - // includes require a full filename passed in - let fn = await getNewTemplateRender( - "./test/stubs/filename.ejs", - "./test/stubs/" - ).getCompiledTemplate("

<%- include('_includes/included', {}) %>

"); - t.is(await fn(), "

This is an include.

"); -}); - -test("EJS Render Relative Include current dir to subdir, Fxn no Data", async (t) => { - // includes require a full filename passed in - let fn = await getNewTemplateRender( - "./test/stubs/relative-ejs/filename.ejs", - "./test/stubs/" - ).getCompiledTemplate("

<%- include('./dir/included', {}) %>

"); - t.is(await fn(), "

This is an include.

"); -}); - -test("EJS Render Relative Include, Fxn with Data", async (t) => { - // includes require a full filename passed in - let fn = await getNewTemplateRender( - "./test/stubs/filename.ejs", - "./test/stubs/" - ).getCompiledTemplate( - "

<%- include('_includes/includedvar', { name: 'Bill' }) %>

" - ); - t.is(await fn(), "

This is an Bill.

"); -}); - -test("EJS Render: with Library Override", async (t) => { - let tr = getNewTemplateRender("ejs"); - - let lib = require("ejs"); - tr.engine.setLibrary(lib); - - let fn = await tr.getCompiledTemplate("

<%= name %>

"); - t.is(await fn({ name: "Zach" }), "

Zach

"); -}); diff --git a/test/TemplateRenderHTMLTest.js b/test/TemplateRenderHTMLTest.js index 2027a5a0c..98e71f895 100644 --- a/test/TemplateRenderHTMLTest.js +++ b/test/TemplateRenderHTMLTest.js @@ -1,58 +1,47 @@ -const test = require("ava"); -const TemplateRender = require("../src/TemplateRender"); -const TemplateConfig = require("../src/TemplateConfig"); -const EleventyExtensionMap = require("../src/EleventyExtensionMap"); +import test from "ava"; +import TemplateRender from "../src/TemplateRender.js"; +import TemplateConfig from "../src/TemplateConfig.js"; +import EleventyExtensionMap from "../src/EleventyExtensionMap.js"; -function getNewTemplateRender(name, inputDir) { +async function getNewTemplateRender(name, inputDir) { let eleventyConfig = new TemplateConfig(); + await eleventyConfig.init(); + let tr = new TemplateRender(name, inputDir, eleventyConfig); tr.extensionMap = new EleventyExtensionMap([], eleventyConfig); + await tr.init(); return tr; } // HTML -test("HTML", (t) => { - t.is(getNewTemplateRender("html").getEngineName(), "html"); +test("HTML", async (t) => { + let tr = await getNewTemplateRender("html"); + t.is(tr.getEngineName(), "html"); }); test("HTML Render", async (t) => { - let fn = await getNewTemplateRender("html").getCompiledTemplate( - "

Paragraph

" - ); + let tr = await getNewTemplateRender("html"); + let fn = await tr.getCompiledTemplate("

Paragraph

"); t.is(await fn(), "

Paragraph

"); t.is(await fn({}), "

Paragraph

"); }); test("HTML Render: Parses HTML using liquid engine (default, with data)", async (t) => { - let fn = await getNewTemplateRender("html").getCompiledTemplate( - "

{{title}}

" - ); - t.is((await fn({ title: "My Title" })).trim(), "

My Title

"); -}); - -test("HTML Render: Parses HTML using ejs engine", async (t) => { - let tr = getNewTemplateRender("html"); - tr.setHtmlEngine("ejs"); - let fn = await tr.getCompiledTemplate("

<%=title %>

"); + let tr = await getNewTemplateRender("html"); + let fn = await tr.getCompiledTemplate("

{{title}}

"); t.is((await fn({ title: "My Title" })).trim(), "

My Title

"); }); test("HTML Render: Set HTML engine to false, don’t parse", async (t) => { - let tr = getNewTemplateRender("html"); + let tr = await getNewTemplateRender("html"); tr.setHtmlEngine(false); + let fn = await tr.getCompiledTemplate("

{{title}}

"); t.is((await fn()).trim(), "

{{title}}

"); }); -test("HTML Render: Pass in an override (ejs)", async (t) => { - let tr = getNewTemplateRender("html"); - tr.setHtmlEngine("ejs"); - let fn = await tr.getCompiledTemplate("

<%= title %>

"); - t.is((await fn({ title: "My Title" })).trim(), "

My Title

"); -}); - test("HTML Render: Pass in an override (liquid)", async (t) => { - let tr = getNewTemplateRender("html"); + let tr = await getNewTemplateRender("html"); tr.setHtmlEngine("liquid"); let fn = await tr.getCompiledTemplate("

{{title}}

"); diff --git a/test/TemplateRenderHamlTest.js b/test/TemplateRenderHamlTest.js deleted file mode 100644 index 02159df6f..000000000 --- a/test/TemplateRenderHamlTest.js +++ /dev/null @@ -1,31 +0,0 @@ -const test = require("ava"); -const TemplateRender = require("../src/TemplateRender"); -const TemplateConfig = require("../src/TemplateConfig"); -const EleventyExtensionMap = require("../src/EleventyExtensionMap"); - -function getNewTemplateRender(name, inputDir) { - let eleventyConfig = new TemplateConfig(); - let tr = new TemplateRender(name, inputDir, eleventyConfig); - tr.extensionMap = new EleventyExtensionMap([], eleventyConfig); - return tr; -} - -// Haml -test("Haml", (t) => { - t.is(getNewTemplateRender("haml").getEngineName(), "haml"); -}); - -test("Haml Render", async (t) => { - let fn = await getNewTemplateRender("haml").getCompiledTemplate("%p= name"); - t.is((await fn({ name: "Zach" })).trim(), "

Zach

"); -}); - -test("Haml Render: with Library Override", async (t) => { - let tr = getNewTemplateRender("haml"); - - let lib = require("hamljs"); - tr.engine.setLibrary(lib); - - let fn = await tr.getCompiledTemplate("%p= name"); - t.is((await fn({ name: "Zach" })).trim(), "

Zach

"); -}); diff --git a/test/TemplateRenderHandlebarsTest.js b/test/TemplateRenderHandlebarsTest.js deleted file mode 100644 index 4b92b7ad1..000000000 --- a/test/TemplateRenderHandlebarsTest.js +++ /dev/null @@ -1,355 +0,0 @@ -const test = require("ava"); -const TemplateRender = require("../src/TemplateRender"); -const TemplateConfig = require("../src/TemplateConfig"); -const EleventyExtensionMap = require("../src/EleventyExtensionMap"); - -function getNewTemplateRender(name, inputDir) { - let eleventyConfig = new TemplateConfig(); - let tr = new TemplateRender(name, inputDir, eleventyConfig); - tr.extensionMap = new EleventyExtensionMap([], eleventyConfig); - return tr; -} - -// Handlebars -test("Handlebars", (t) => { - t.is(getNewTemplateRender("hbs").getEngineName(), "hbs"); -}); - -test("Handlebars Render", async (t) => { - let fn = await getNewTemplateRender("hbs").getCompiledTemplate( - "

{{name}}

" - ); - t.is(await fn({ name: "Zach" }), "

Zach

"); -}); - -test("Handlebars Render Unescaped Output (no HTML)", async (t) => { - let fn = await getNewTemplateRender("hbs").getCompiledTemplate( - "

{{{name}}}

" - ); - t.is(await fn({ name: "Zach" }), "

Zach

"); -}); - -test("Handlebars Render Escaped Output", async (t) => { - let fn = await getNewTemplateRender("hbs").getCompiledTemplate( - "

{{name}}

" - ); - t.is(await fn({ name: "Zach" }), "

<b>Zach</b>

"); -}); - -test("Handlebars Render Unescaped Output (HTML)", async (t) => { - let fn = await getNewTemplateRender("hbs").getCompiledTemplate( - "

{{{name}}}

" - ); - t.is(await fn({ name: "Zach" }), "

Zach

"); -}); - -test("Handlebars Render Partial", async (t) => { - let fn = await getNewTemplateRender( - "hbs", - "./test/stubs/" - ).getCompiledTemplate("

{{> included}}

"); - t.is(await fn(), "

This is an include.

"); -}); - -test.skip("Handlebars Render Partial (Relative)", async (t) => { - let fn = await getNewTemplateRender( - "./test/stubs/does_not_exist_and_thats_ok.hbs", - "./test/stubs/" - ).getCompiledTemplate("

{{> ./included}}

"); - - // not supported yet. - t.is(await fn(), "

This is an includdde.

"); -}); - -test("Handlebars Render Partial (Subdirectory)", async (t) => { - let fn = await getNewTemplateRender( - "hbs", - "./test/stubs/" - ).getCompiledTemplate("

{{> subfolder/included}}

"); - t.is(await fn(), "

This is an include.

"); -}); - -test("Handlebars Render Partial with variable", async (t) => { - let fn = await getNewTemplateRender( - "hbs", - "./test/stubs/" - ).getCompiledTemplate("

{{> includedvar}}

"); - t.is(await fn({ name: "Zach" }), "

This is a Zach.

"); -}); - -test("Handlebars Render Partial with parameter", async (t) => { - let fn = await getNewTemplateRender( - "hbs", - "./test/stubs-hbs-partial-var/" - ).getCompiledTemplate("{{> myPartial parameter=name }}"); - t.is(await fn({ name: "Zach" }), "The result is Zach"); -}); - -test("Handlebars Render: with Library Override", async (t) => { - let tr = getNewTemplateRender("hbs"); - - let lib = require("handlebars"); - tr.engine.setLibrary(lib); - - let fn = await tr.getCompiledTemplate("

{{name}}

"); - t.is(await fn({ name: "Zach" }), "

Zach

"); -}); - -test("Handlebars Render Helper", async (t) => { - let tr = getNewTemplateRender("hbs"); - tr.engine.addHelpers({ - helpername: function () { - return "Zach"; - }, - }); - - let fn = await tr.getCompiledTemplate( - "

This is a {{helpername}} {{name}}.

" - ); - t.is(await fn({ name: "Zach" }), "

This is a Zach Zach.

"); -}); - -test("Handlebars Render Helper (uses argument)", async (t) => { - let tr = getNewTemplateRender("hbs"); - tr.engine.addHelpers({ - helpername2: function (name) { - return "Zach"; - }, - }); - - let fn = await tr.getCompiledTemplate( - "

This is a {{helpername2 name}}.

" - ); - t.is(await fn({ name: "Zach" }), "

This is a Zach.

"); -}); - -test("Handlebars Render Helper (uses string argument)", async (t) => { - let tr = getNewTemplateRender("hbs"); - tr.engine.addHelpers({ - helpername2: function (name) { - return name; - }, - }); - - let fn = await tr.getCompiledTemplate( - `

This is a {{helpername2 "Zach"}}.

` - ); - t.is(await fn({ name: "Zach" }), "

This is a Zach.

"); -}); - -test("Handlebars Render Shortcode", async (t) => { - t.plan(3); - let tr = getNewTemplateRender("hbs"); - tr.engine.addShortcodes({ - shortcodename: function (name) { - // Data in context - // Note Handlebars exposes all data while other template languages only expose { page }. See #741 - t.is(this.name, "Howdy"); - t.is(this.page.url, "/hi/"); - - return name.toUpperCase(); - }, - }); - - let fn = await tr.getCompiledTemplate( - "

This is a {{shortcodename name}}.

" - ); - t.is( - await fn({ name: "Howdy", page: { url: "/hi/" } }), - "

This is a HOWDY.

" - ); -}); - -test("Handlebars Render HTML in Shortcode (Issue #460)", async (t) => { - t.plan(2); - let tr = getNewTemplateRender("hbs"); - tr.engine.addShortcodes({ - shortcodenamehtml: function (name) { - // Data in context - // Note Handlebars exposes all data while other template languages only expose { page }. See #741 - t.is(this.name, "Howdy"); - - return `${name.toUpperCase()}`; - }, - }); - - let fn = await tr.getCompiledTemplate( - "

This is a {{{shortcodenamehtml name}}}.

" - ); - t.is(await fn({ name: "Howdy" }), "

This is a HOWDY.

"); -}); - -test("Handlebars Render Shortcode (Multiple args)", async (t) => { - t.plan(3); - - let tr = getNewTemplateRender("hbs"); - tr.engine.addShortcodes({ - shortcodename2: function (name, name2) { - // Data in context - // Note Handlebars exposes all data while other template languages only expose { page }. See #741 - t.is(this.name, "Howdy"); - t.is(this.name2, "Zach"); - - return name.toUpperCase() + name2.toUpperCase(); - }, - }); - - let fn = await tr.getCompiledTemplate( - "

This is a {{shortcodename2 name name2}}.

" - ); - t.is( - await fn({ name: "Howdy", name2: "Zach" }), - "

This is a HOWDYZACH.

" - ); -}); - -test("Handlebars Render Paired Shortcode", async (t) => { - t.plan(2); - - let tr = getNewTemplateRender("hbs"); - tr.engine.addPairedShortcodes({ - shortcodename3: function (content, name, options) { - // Data in context - // Note Handlebars exposes all data while other template languages only expose { page }. See #741 - t.is(this.name, "Howdy"); - - return (content + name).toUpperCase(); - }, - }); - - let fn = await tr.getCompiledTemplate( - "

This is a {{#shortcodename3 name}}Testing{{/shortcodename3}}.

" - ); - t.is(await fn({ name: "Howdy" }), "

This is a TESTINGHOWDY.

"); -}); - -test("Handlebars Render Paired Shortcode (HTML)", async (t) => { - t.plan(2); - - let tr = getNewTemplateRender("hbs"); - tr.engine.addPairedShortcodes({ - shortcodename3html: function (content, name, options) { - // Data in context - // Note Handlebars exposes all data while other template languages only expose { page }. See #741 - t.is(this.name, "Howdy"); - - return `${(content + name).toUpperCase()}`; - }, - }); - - let fn = await tr.getCompiledTemplate( - "

This is a {{#shortcodename3html name}}Testing{{/shortcodename3html}}.

" - ); - t.is( - await fn({ name: "Howdy" }), - "

This is a TESTINGHOWDY.

" - ); -}); - -test("Handlebars Render Paired Shortcode (Spaces)", async (t) => { - t.plan(2); - - let tr = getNewTemplateRender("hbs"); - tr.engine.addPairedShortcodes({ - shortcodename4: function (content, name, options) { - // Data in context - // Note Handlebars exposes all data while other template languages only expose { page }. See #741 - t.is(this.name, "Howdy"); - - return (content + name).toUpperCase(); - }, - }); - - let fn = await tr.getCompiledTemplate( - "

This is a {{# shortcodename4 name }}Testing{{/ shortcodename4 }}.

" - ); - t.is(await fn({ name: "Howdy" }), "

This is a TESTINGHOWDY.

"); -}); - -test("Handlebars Render Paired Shortcode with a Nested Single Shortcode", async (t) => { - t.plan(5); - - let tr = getNewTemplateRender("hbs"); - tr.engine.addShortcodes({ - shortcodechild: function (txt, options) { - // Data in context - // Note Handlebars exposes all data while other template languages only expose { page }. See #741 - t.is(this.name, "Howdy"); - t.is(this.name2, "Zach"); - - return txt; - }, - }); - - tr.engine.addPairedShortcodes({ - shortcodeparent: function (content, name, name2, options) { - // Data in context - // Note Handlebars exposes all data while other template languages only expose { page }. See #741 - t.is(this.name, "Howdy"); - t.is(this.name2, "Zach"); - - return (content + name + name2).toUpperCase(); - }, - }); - - let fn = await tr.getCompiledTemplate( - "

This is a {{# shortcodeparent name name2 }}{{shortcodechild 'CHILD CONTENT'}}{{/ shortcodeparent }}.

" - ); - t.is( - await fn({ name: "Howdy", name2: "Zach" }), - "

This is a CHILD CONTENTHOWDYZACH.

" - ); -}); - -test("Handlebars Render Raw Output (Issue #436)", async (t) => { - let tr = getNewTemplateRender("hbs"); - tr.engine.addHelpers({ - "raw-helper": function (options) { - return options.fn(); - }, - }); - - let fn = await tr.getCompiledTemplate( - "{{{{raw-helper}}}}{{bar}}{{{{/raw-helper}}}}" - ); - t.is(await fn({ name: "Zach" }), "{{bar}}"); -}); - -test("Handlebars Render Raw Output (Issue #436 with if statement)", async (t) => { - let tr = getNewTemplateRender("hbs"); - tr.engine.addHelpers({ - "raw-helper": function (options) { - return options.fn(); - }, - }); - - let fn = await tr.getCompiledTemplate( - `{{{{raw-helper}}}}{{#if ready}} -

Ready

-{{/if}}{{{{/raw-helper}}}}` - ); - t.is( - await fn({ name: "Zach" }), - `{{#if ready}} -

Ready

-{{/if}}` - ); -}); - -test("Handlebars Render #each with Global Variable (Issue #759)", async (t) => { - let fn = await getNewTemplateRender( - "hbs", - "./test/stubs/" - ).getCompiledTemplate( - `` - ); - t.is( - ( - await fn({ - name: "Zach", - navigation: [{ link: "a", text: "text" }], - }) - ).trim(), - `` - ); -}); diff --git a/test/TemplateRenderJavaScriptTest.js b/test/TemplateRenderJavaScriptTest.js index 8d14800b2..76ad22325 100644 --- a/test/TemplateRenderJavaScriptTest.js +++ b/test/TemplateRenderJavaScriptTest.js @@ -1,69 +1,78 @@ -const test = require("ava"); -const TemplateRender = require("../src/TemplateRender"); -const TemplateConfig = require("../src/TemplateConfig"); -const EleventyExtensionMap = require("../src/EleventyExtensionMap"); +import test from "ava"; -function getNewTemplateRender(name, inputDir, extendedConfig) { +import TemplateRender from "../src/TemplateRender.js"; +import TemplateConfig from "../src/TemplateConfig.js"; +import EleventyExtensionMap from "../src/EleventyExtensionMap.js"; + +async function getNewTemplateRender(name, inputDir, extendedConfig) { let eleventyConfig = new TemplateConfig(); - if (extendedConfig) { - eleventyConfig.appendToRootConfig(extendedConfig); - } + await eleventyConfig.init(extendedConfig); + let tr = new TemplateRender(name, inputDir, eleventyConfig); tr.extensionMap = new EleventyExtensionMap([], eleventyConfig); + await tr.init(); + return tr; } -test("JS", (t) => { - t.is(getNewTemplateRender("11ty.js").getEngineName(), "11ty.js"); - t.is(getNewTemplateRender("./test/stubs/filename.11ty.js").getEngineName(), "11ty.js"); - t.is(getNewTemplateRender("11ty.cjs").getEngineName(), "11ty.js"); - t.is(getNewTemplateRender("./test/stubs/filename.11ty.cjs").getEngineName(), "11ty.js"); +test("JS", async (t) => { + t.is((await getNewTemplateRender("11ty.js")).getEngineName(), "11ty.js"); + t.is((await getNewTemplateRender("./test/stubs/filename.11ty.js")).getEngineName(), "11ty.js"); + t.is((await getNewTemplateRender("11ty.cjs")).getEngineName(), "11ty.js"); + t.is((await getNewTemplateRender("./test/stubs/filename.11ty.cjs")).getEngineName(), "11ty.js"); }); test("JS Render a string (no data)", async (t) => { - let fn = await getNewTemplateRender("./test/stubs/string.11ty.js").getCompiledTemplate(); + let tr = await getNewTemplateRender("./test/stubs/string.11ty.cjs"); + let fn = await tr.getCompiledTemplate(); t.is(await fn({ name: "Bill" }), "

Zach

"); }); test("JS Render a promise (no data)", async (t) => { - let fn = await getNewTemplateRender("./test/stubs/promise.11ty.js").getCompiledTemplate(); + let tr = await getNewTemplateRender("./test/stubs/promise.11ty.cjs"); + let fn = await tr.getCompiledTemplate(); t.is(await fn({ name: "Bill" }), "

Zach

"); }); test("JS Render a buffer (no data)", async (t) => { - let fn = await getNewTemplateRender("./test/stubs/buffer.11ty.js").getCompiledTemplate(); + let tr = await getNewTemplateRender("./test/stubs/buffer.11ty.cjs"); + let fn = await tr.getCompiledTemplate(); t.is(await fn({ name: "Bill" }), "

tést

"); }); test("JS Render a function", async (t) => { - let fn = await getNewTemplateRender("./test/stubs/function.11ty.js").getCompiledTemplate(); + let tr = await getNewTemplateRender("./test/stubs/function.11ty.cjs"); + let fn = await tr.getCompiledTemplate(); t.is(await fn({ name: "Zach" }), "

Zach

"); t.is(await fn({ name: "Bill" }), "

Bill

"); }); test("JS Render a function (arrow syntax)", async (t) => { - let fn = await getNewTemplateRender("./test/stubs/function-arrow.11ty.js").getCompiledTemplate(); + let tr = await getNewTemplateRender("./test/stubs/function-arrow.11ty.cjs"); + let fn = await tr.getCompiledTemplate(); t.is(await fn({ name: "Zach" }), "

Zach

"); t.is(await fn({ name: "Bill" }), "

Bill

"); }); test("JS Render a function, returns a Buffer", async (t) => { - let fn = await getNewTemplateRender("./test/stubs/function-buffer.11ty.js").getCompiledTemplate(); + let tr = await getNewTemplateRender("./test/stubs/function-buffer.11ty.cjs"); + let fn = await tr.getCompiledTemplate(); t.is(await fn({ name: "tést" }), "

tést

"); t.is(await fn({ name: "Zach" }), "

Zach

"); t.is(await fn({ name: "Bill" }), "

Bill

"); }); test("JS Render a function (Markdown)", async (t) => { - let tr = getNewTemplateRender("./test/stubs/function-markdown.11ty.js"); - tr.setEngineOverride("11ty.js,md"); + let tr = await getNewTemplateRender("./test/stubs/function-markdown.11ty.cjs"); + await tr.setEngineOverride("11ty.js,md"); + let fn = await tr.getCompiledTemplate(); t.is((await fn({ name: "Zach" })).trim(), "

Zach

"); t.is((await fn({ name: "Bill" })).trim(), "

Bill

"); }); test("JS Render a function (Collections)", async (t) => { - let tr = getNewTemplateRender("./test/stubs/use-collection.11ty.js"); + let tr = await getNewTemplateRender("./test/stubs/use-collection.11ty.cjs"); let fn = await tr.getCompiledTemplate(); t.is( ( @@ -89,38 +98,44 @@ test("JS Render a function (Collections)", async (t) => { }); test("JS Render an async function", async (t) => { - let fn = await getNewTemplateRender("./test/stubs/function-async.11ty.js").getCompiledTemplate(); + let tr = await getNewTemplateRender("./test/stubs/function-async.11ty.cjs"); + let fn = await tr.getCompiledTemplate(); t.is(await fn({ name: "Zach" }), "

Zach

"); t.is(await fn({ name: "Bill" }), "

Bill

"); }); test("JS Render with a Class", async (t) => { - let fn = await getNewTemplateRender("./test/stubs/class.11ty.js").getCompiledTemplate(); + let tr = await getNewTemplateRender("./test/stubs/class.11ty.cjs"); + let fn = await tr.getCompiledTemplate(); t.is(await fn({ name: "Zach" }), "

ZachBillTed

"); t.is(await fn({ name: "Bill" }), "

BillBillTed

"); }); test("JS Render with a Class, returns a buffer", async (t) => { - let fn = await getNewTemplateRender("./test/stubs/class-buffer.11ty.js").getCompiledTemplate(); + let tr = await getNewTemplateRender("./test/stubs/class-buffer.11ty.cjs"); + let fn = await tr.getCompiledTemplate(); t.is(await fn({ name: "Zách" }), "

ZáchBillTed

"); t.is(await fn({ name: "Zach" }), "

ZachBillTed

"); t.is(await fn({ name: "Bill" }), "

BillBillTed

"); }); test("JS Render with a Class, async render", async (t) => { - let fn = await getNewTemplateRender("./test/stubs/class-async.11ty.js").getCompiledTemplate(); + let tr = await getNewTemplateRender("./test/stubs/class-async.11ty.cjs"); + let fn = await tr.getCompiledTemplate(); t.is(await fn({ name: "Zach" }), "

Zach

"); t.is(await fn({ name: "Bill" }), "

Bill

"); }); test("JS Render using Vue", async (t) => { - let fn = await getNewTemplateRender("./test/stubs/vue.11ty.js").getCompiledTemplate(); + let tr = await getNewTemplateRender("./test/stubs/vue.11ty.cjs"); + let fn = await tr.getCompiledTemplate(); t.is(await fn({ name: "Zach" }), "

Hello Zach, this is a Vue template.

"); t.is(await fn({ name: "Bill" }), "

Hello Bill, this is a Vue template.

"); }); test("JS Render using Vue (with a layout)", async (t) => { - let fn = await getNewTemplateRender("./test/stubs/vue-layout.11ty.js").getCompiledTemplate(); + let tr = await getNewTemplateRender("./test/stubs/vue-layout.11ty.cjs"); + let fn = await tr.getCompiledTemplate(); t.is( await fn({ name: "Zach" }), ` @@ -132,7 +147,7 @@ test("JS Render using Vue (with a layout)", async (t) => { test("JS Render with a function", async (t) => { t.plan(8); - let tr = getNewTemplateRender("./test/stubs/function-filter.11ty.js", undefined, { + let tr = await getNewTemplateRender("./test/stubs/function-filter.11ty.cjs", undefined, { javascriptFunctions: { upper: function (val) { t.is(this.page.url, "/hi/"); @@ -152,7 +167,7 @@ test("JS Render with a function", async (t) => { test("JS Render with a function and async filter", async (t) => { t.plan(4); - let tr = getNewTemplateRender("./test/stubs/function-async-filter.11ty.js", undefined, { + let tr = await getNewTemplateRender("./test/stubs/function-async-filter.11ty.cjs", undefined, { javascriptFunctions: { upper: function (val) { return new Promise((resolve) => { @@ -170,7 +185,7 @@ test("JS Render with a function and async filter", async (t) => { test("JS Render with a function prototype", async (t) => { t.plan(4); - let tr = getNewTemplateRender("./test/stubs/function-prototype.11ty.js", undefined, { + let tr = await getNewTemplateRender("./test/stubs/function-prototype.11ty.cjs", undefined, { javascriptFunctions: { upper: function (val) { t.is(this.page.url, "/hi/"); @@ -187,7 +202,7 @@ test("JS Render with a function prototype", async (t) => { test("JS Class Render with a function", async (t) => { t.plan(4); - let tr = getNewTemplateRender("./test/stubs/class-filter.11ty.js", undefined, { + let tr = await getNewTemplateRender("./test/stubs/class-filter.11ty.cjs", undefined, { javascriptFunctions: { upper: function (val) { t.is(this.page.url, "/hi/"); @@ -204,7 +219,7 @@ test("JS Class Render with a function", async (t) => { test("JS Class Async Render with a function", async (t) => { t.plan(4); - let tr = getNewTemplateRender("./test/stubs/class-async-filter.11ty.js", undefined, { + let tr = await getNewTemplateRender("./test/stubs/class-async-filter.11ty.cjs", undefined, { javascriptFunctions: { upper: function (val) { t.is(this.page.url, "/hi/"); @@ -220,7 +235,7 @@ test("JS Class Async Render with a function", async (t) => { }); test("JS Class Async Render with a function (sync function, throws error)", async (t) => { - let tr = getNewTemplateRender("./test/stubs/function-throws.11ty.js", undefined, { + let tr = await getNewTemplateRender("./test/stubs/function-throws.11ty.cjs", undefined, { javascriptFunctions: { upper: function (val) { throw new Error("JS Class Async Render with a function (sync function, throws error)"); @@ -239,7 +254,7 @@ test("JS Class Async Render with a function (sync function, throws error)", asyn }); test("JS Class Async Render with a function (async function, throws error)", async (t) => { - let tr = getNewTemplateRender("./test/stubs/function-throws-async.11ty.js", undefined, { + let tr = await getNewTemplateRender("./test/stubs/function-throws-async.11ty.cjs", undefined, { javascriptFunctions: { upper: async function (val) { throw new Error("JS Class Async Render with a function (async function, throws error)"); @@ -259,7 +274,7 @@ test("JS Class Async Render with a function (async function, throws error)", asy test("JS function has access to built in filters", async (t) => { t.plan(6); - let tr = getNewTemplateRender("./test/stubs/function-fns.11ty.js"); + let tr = await getNewTemplateRender("./test/stubs/function-fns.11ty.cjs"); let fn = await tr.getCompiledTemplate(); await fn({ avaTest: t, page: { url: "/hi/" } }); @@ -267,7 +282,7 @@ test("JS function has access to built in filters", async (t) => { test("Class has access to built in filters", async (t) => { t.plan(6); - let tr = getNewTemplateRender("./test/stubs/class-fns.11ty.js"); + let tr = await getNewTemplateRender("./test/stubs/class-fns.11ty.cjs"); let fn = await tr.getCompiledTemplate(); await fn({ avaTest: t, page: { url: "/hi/" } }); @@ -275,8 +290,7 @@ test("Class has access to built in filters", async (t) => { test("Class has page property already and keeps it", async (t) => { t.plan(2); - let tr = getNewTemplateRender("./test/stubs/class-fns-has-page.11ty.js"); - + let tr = await getNewTemplateRender("./test/stubs/class-fns-has-page.11ty.cjs"); let fn = await tr.getCompiledTemplate(); await fn({ avaTest: t, page: { url: "/hi/" } }); }); diff --git a/test/TemplateRenderLiquidTest.js b/test/TemplateRenderLiquidTest.js index a6f9f8e3b..08bcdd048 100644 --- a/test/TemplateRenderLiquidTest.js +++ b/test/TemplateRenderLiquidTest.js @@ -1,17 +1,20 @@ -const test = require("ava"); -const TemplateRender = require("../src/TemplateRender"); -const TemplateConfig = require("../src/TemplateConfig"); -const EleventyExtensionMap = require("../src/EleventyExtensionMap"); -const { Drop } = require("liquidjs"); +import test from "ava"; +import { Liquid, Drop } from "liquidjs"; -function getNewTemplateRender(name, inputDir, userConfig = {}) { +import TemplateRender from "../src/TemplateRender.js"; +import TemplateConfig from "../src/TemplateConfig.js"; +import EleventyExtensionMap from "../src/EleventyExtensionMap.js"; + +async function getNewTemplateRender(name, inputDir, userConfig = {}) { let eleventyConfig = new TemplateConfig(); for (let key in userConfig) { eleventyConfig.userConfig[key] = userConfig[key]; } + await eleventyConfig.init(); let tr = new TemplateRender(name, inputDir, eleventyConfig); tr.extensionMap = new EleventyExtensionMap([], eleventyConfig); + await tr.init(); return tr; } @@ -24,26 +27,26 @@ async function getPromise(resolveTo) { } // Liquid -test("Liquid", (t) => { - t.is(getNewTemplateRender("liquid").getEngineName(), "liquid"); +test("Liquid", async (t) => { + let tr = await getNewTemplateRender("liquid"); + t.is(tr.getEngineName(), "liquid"); }); test("Liquid Render Addition", async (t) => { - let fn = await getNewTemplateRender("liquid").getCompiledTemplate( - "

{{ number | plus: 1 }}

" - ); + let tr = await getNewTemplateRender("liquid"); + let fn = await tr.getCompiledTemplate("

{{ number | plus: 1 }}

"); t.is(await fn({ number: 1 }), "

2

"); }); test("Liquid Render Raw", async (t) => { - let fn = await getNewTemplateRender("liquid").getCompiledTemplate( - "

{% raw %}{{name}}{% endraw %}

" - ); + let tr = await getNewTemplateRender("liquid"); + let fn = await tr.getCompiledTemplate("

{% raw %}{{name}}{% endraw %}

"); t.is(await fn({ name: "tim" }), "

{{name}}

"); }); test("Liquid Render Raw Multiline", async (t) => { - let fn = await getNewTemplateRender("liquid").getCompiledTemplate( + let tr = await getNewTemplateRender("liquid"); + let fn = await tr.getCompiledTemplate( `

{% raw %} {{name}} {% endraw %}

` @@ -57,55 +60,48 @@ test("Liquid Render Raw Multiline", async (t) => { }); test("Liquid Render (with Helper)", async (t) => { - let fn = await getNewTemplateRender("liquid").getCompiledTemplate( - "

{{name | capitalize}}

" - ); + let tr = await getNewTemplateRender("liquid"); + let fn = await tr.getCompiledTemplate("

{{name | capitalize}}

"); t.is(await fn({ name: "tim" }), "

Tim

"); }); test("Liquid Render Include", async (t) => { - t.is( - getNewTemplateRender("liquid", "./test/stubs/").getEngineName(), - "liquid" - ); + let tr1 = await getNewTemplateRender("liquid", "./test/stubs/"); + t.is(tr1.getEngineName(), "liquid"); - let tr = await getNewTemplateRender("liquid", "./test/stubs/", { + let tr2 = await getNewTemplateRender("liquid", "./test/stubs/", { liquidOptions: { dynamicPartials: false, }, }); - let fn = await tr.getCompiledTemplate("

{% include included %}

"); + let fn = await tr2.getCompiledTemplate("

{% include included %}

"); t.is(await fn(), "

This is an include.

"); }); test("Liquid Render Relative Include (dynamicPartials off)", async (t) => { - t.is( - getNewTemplateRender("liquid", "./test/stubs/").getEngineName(), - "liquid" - ); + let tr1 = await getNewTemplateRender("liquid", "./test/stubs/"); + t.is(tr1.getEngineName(), "liquid"); - let tr = await getNewTemplateRender("liquid", "./test/stubs/", { + let tr2 = await getNewTemplateRender("liquid", "./test/stubs/", { liquidOptions: { dynamicPartials: false, }, }); // Important note: when inputPath is set to `liquid`, this *only* uses _includes relative paths in Liquid->compile - let fn = await tr.getCompiledTemplate("

{% include ./included %}

"); + let fn = await tr2.getCompiledTemplate("

{% include ./included %}

"); t.is(await fn(), "

This is an include.

"); }); test("Liquid Render Relative Include (dynamicPartials on)", async (t) => { - t.is( - getNewTemplateRender("liquid", "./test/stubs/").getEngineName(), - "liquid" - ); + let tr1 = await getNewTemplateRender("liquid", "./test/stubs/"); + t.is(tr1.getEngineName(), "liquid"); - let tr = await getNewTemplateRender("liquid", "./test/stubs/"); + let tr2 = await getNewTemplateRender("liquid", "./test/stubs/"); // Important note: when inputPath is set to `liquid`, this *only* uses _includes relative paths in Liquid->compile - let fn = await tr.getCompiledTemplate("

{% include './included' %}

"); + let fn = await tr2.getCompiledTemplate("

{% include './included' %}

"); t.is(await fn(), "

This is an include.

"); }); @@ -140,7 +136,7 @@ test("Liquid Render Relative (parent dir) Include", async (t) => { }); test("Liquid Render Relative (relative include should ignore _includes dir) Include", async (t) => { - let tr = getNewTemplateRender( + let tr = await getNewTemplateRender( "./test/stubs/does_not_exist_and_thats_ok.liquid", "./test/stubs/", {} @@ -151,57 +147,49 @@ test("Liquid Render Relative (relative include should ignore _includes dir) Incl }); test("Liquid Render Include with Liquid Suffix", async (t) => { - t.is( - getNewTemplateRender("liquid", "./test/stubs/").getEngineName(), - "liquid" - ); + let tr1 = await getNewTemplateRender("liquid", "./test/stubs/"); + t.is(tr1.getEngineName(), "liquid"); - let tr = await getNewTemplateRender("liquid", "./test/stubs/", { + let tr2 = await getNewTemplateRender("liquid", "./test/stubs/", { liquidOptions: { dynamicPartials: false, }, }); - let fn = await tr.getCompiledTemplate("

{% include included.liquid %}

"); + let fn = await tr2.getCompiledTemplate("

{% include included.liquid %}

"); t.is(await fn(), "

This is an include.

"); }); test("Liquid Render Include with HTML Suffix", async (t) => { - t.is( - getNewTemplateRender("liquid", "./test/stubs/").getEngineName(), - "liquid" - ); + let tr1 = await getNewTemplateRender("liquid", "./test/stubs/"); + t.is(tr1.getEngineName(), "liquid"); - let tr = await getNewTemplateRender("liquid", "./test/stubs/", { + let tr2 = await getNewTemplateRender("liquid", "./test/stubs/", { liquidOptions: { dynamicPartials: false, }, }); - let fn = await tr.getCompiledTemplate("

{% include included.html %}

"); + let fn = await tr2.getCompiledTemplate("

{% include included.html %}

"); t.is(await fn(), "

This is an include.

"); }); test("Liquid Render Include with HTML Suffix and Data Pass in", async (t) => { - t.is( - getNewTemplateRender("liquid", "./test/stubs/").getEngineName(), - "liquid" - ); + let tr1 = await getNewTemplateRender("liquid", "./test/stubs/"); + t.is(tr1.getEngineName(), "liquid"); - let tr = await getNewTemplateRender("liquid", "./test/stubs/", { + let tr2 = await getNewTemplateRender("liquid", "./test/stubs/", { liquidOptions: { dynamicPartials: false, }, }); - let fn = await tr.getCompiledTemplate( - "{% include included-data.html, myVariable: 'myValue' %}" - ); + let fn = await tr2.getCompiledTemplate("{% include included-data.html, myVariable: 'myValue' %}"); t.is((await fn()).trim(), "This is an include. myValue"); }); test("Liquid Custom Filter", async (t) => { - let tr = getNewTemplateRender("liquid", "./test/stubs/"); + let tr = await getNewTemplateRender("liquid", "./test/stubs/"); tr.engine.addFilter("prefixWithZach", function (val) { return "Zach" + val; }); @@ -210,7 +198,7 @@ test("Liquid Custom Filter", async (t) => { }); test("Liquid Async Filter", async (t) => { - let tr = getNewTemplateRender("liquid", "test/stubs"); + let tr = await getNewTemplateRender("liquid", "test/stubs"); tr.engine.addFilter("myAsyncFilter", async function (value) { return new Promise((resolve, reject) => { setTimeout(function () { @@ -224,7 +212,7 @@ test("Liquid Async Filter", async (t) => { }); test("Liquid Custom Tag prefixWithZach", async (t) => { - let tr = getNewTemplateRender("liquid", "./test/stubs/"); + let tr = await getNewTemplateRender("liquid", "./test/stubs/"); tr.engine.addTag("prefixWithZach", function (liquidEngine) { return { parse: function (tagToken, remainTokens) { @@ -237,14 +225,11 @@ test("Liquid Custom Tag prefixWithZach", async (t) => { }; }); - t.is( - await tr._testRender("{% prefixWithZach name %}", { name: "test" }), - "Zachtest" - ); + t.is(await tr._testRender("{% prefixWithZach name %}", { name: "test" }), "Zachtest"); }); test("Liquid Custom Tag postfixWithZach", async (t) => { - let tr = getNewTemplateRender("liquid", "./test/stubs/"); + let tr = await getNewTemplateRender("liquid", "./test/stubs/"); tr.engine.addTag("postfixWithZach", function (liquidEngine) { return { parse: function (tagToken, remainTokens) { @@ -257,14 +242,11 @@ test("Liquid Custom Tag postfixWithZach", async (t) => { }; }); - t.is( - await tr._testRender("{% postfixWithZach name %}", { name: "test" }), - "testZach" - ); + t.is(await tr._testRender("{% postfixWithZach name %}", { name: "test" }), "testZach"); }); test("Liquid Custom Tag Unquoted String", async (t) => { - let tr = getNewTemplateRender("liquid", "./test/stubs/"); + let tr = await getNewTemplateRender("liquid", "./test/stubs/"); tr.engine.addTag("testUnquotedStringTag", function (liquidEngine) { return { parse: function (tagToken, remainTokens) { @@ -277,23 +259,22 @@ test("Liquid Custom Tag Unquoted String", async (t) => { }); t.is( - await tr._testRender( - "{% testUnquotedStringTag _posts/2016-07-26-name-of-post.md %}", - { name: "test" } - ), + await tr._testRender("{% testUnquotedStringTag _posts/2016-07-26-name-of-post.md %}", { + name: "test", + }), "_posts/2016-07-26-name-of-post.mdZach" ); }); test("Liquid addTag errors", async (t) => { - let tr = getNewTemplateRender("liquid", "./test/stubs/"); + let tr = await getNewTemplateRender("liquid", "./test/stubs/"); t.throws(() => { tr.engine.addTag("badSecondArgument", {}); }); }); test("Liquid addTags", async (t) => { - let tr = getNewTemplateRender("liquid", "./test/stubs/"); + let tr = await getNewTemplateRender("liquid", "./test/stubs/"); tr.engine.addCustomTags({ postfixWithZach: function (liquidEngine) { return { @@ -308,16 +289,13 @@ test("Liquid addTags", async (t) => { }, }); - t.is( - await tr._testRender("{% postfixWithZach name %}", { name: "test" }), - "testZach" - ); + t.is(await tr._testRender("{% postfixWithZach name %}", { name: "test" }), "testZach"); }); test("Liquid Shortcode", async (t) => { t.plan(3); - let tr = getNewTemplateRender("liquid", "./test/stubs/"); + let tr = await getNewTemplateRender("liquid", "./test/stubs/"); tr.engine.addShortcode("postfixWithZach", function (str) { // Data in context t.is(this.page.url, "/hi/"); @@ -340,7 +318,7 @@ test("Liquid Shortcode", async (t) => { test("Liquid Shortcode returns promise", async (t) => { t.plan(2); - let tr = getNewTemplateRender("liquid", "./test/stubs/"); + let tr = await getNewTemplateRender("liquid", "./test/stubs/"); tr.engine.addShortcode("postfixWithZach", function (str) { // Data in context t.is(this.page.url, "/hi/"); @@ -366,7 +344,7 @@ test("Liquid Shortcode returns promise", async (t) => { test("Liquid Shortcode returns promise (await inside)", async (t) => { t.plan(2); - let tr = getNewTemplateRender("liquid", "./test/stubs/"); + let tr = await getNewTemplateRender("liquid", "./test/stubs/"); tr.engine.addShortcode("postfixWithZach", async function (str) { // Data in context t.is(this.page.url, "/hi/"); @@ -388,7 +366,7 @@ test("Liquid Shortcode returns promise (await inside)", async (t) => { test("Liquid Shortcode returns promise (no await inside)", async (t) => { t.plan(2); - let tr = getNewTemplateRender("liquid", "./test/stubs/"); + let tr = await getNewTemplateRender("liquid", "./test/stubs/"); tr.engine.addShortcode("postfixWithZach", async function (str) { // Data in context t.is(this.page.url, "/hi/"); @@ -408,7 +386,7 @@ test("Liquid Shortcode returns promise (no await inside)", async (t) => { test("Liquid Shortcode Safe Output", async (t) => { t.plan(2); - let tr = getNewTemplateRender("liquid", "./test/stubs/"); + let tr = await getNewTemplateRender("liquid", "./test/stubs/"); tr.engine.addShortcode("postfixWithZach", function (str) { // Data in context t.is(this.page.url, "/hi/"); @@ -428,7 +406,7 @@ test("Liquid Shortcode Safe Output", async (t) => { test("Liquid Paired Shortcode", async (t) => { t.plan(2); - let tr = getNewTemplateRender("liquid", "./test/stubs/"); + let tr = await getNewTemplateRender("liquid", "./test/stubs/"); tr.engine.addPairedShortcode("postfixWithZach", function (content, str) { // Data in context t.is(this.page.url, "/hi/"); @@ -436,22 +414,19 @@ test("Liquid Paired Shortcode", async (t) => { }); t.is( - await tr._testRender( - "{% postfixWithZach name %}Content{% endpostfixWithZach %}", - { - name: "test", - page: { - url: "/hi/", - }, - } - ), + await tr._testRender("{% postfixWithZach name %}Content{% endpostfixWithZach %}", { + name: "test", + page: { + url: "/hi/", + }, + }), "testContentZach" ); }); test("Liquid Async Paired Shortcode", async (t) => { t.plan(2); - let tr = getNewTemplateRender("liquid", "./test/stubs/"); + let tr = await getNewTemplateRender("liquid", "./test/stubs/"); tr.engine.addPairedShortcode("postfixWithZach", function (content, str) { // Data in context t.is(this.page.url, "/hi/"); @@ -463,15 +438,12 @@ test("Liquid Async Paired Shortcode", async (t) => { }); t.is( - await tr._testRender( - "{% postfixWithZach name %}Content{% endpostfixWithZach %}", - { - name: "test", - page: { - url: "/hi/", - }, - } - ), + await tr._testRender("{% postfixWithZach name %}Content{% endpostfixWithZach %}", { + name: "test", + page: { + url: "/hi/", + }, + }), "testContentZach" ); }); @@ -483,9 +455,7 @@ test("Liquid Render Include Subfolder", async (t) => { }, }); - let fn = await tr.getCompiledTemplate( - `

{% include subfolder/included.liquid %}

` - ); + let fn = await tr.getCompiledTemplate(`

{% include subfolder/included.liquid %}

`); t.is(await fn(), "

This is an include.

"); }); @@ -496,9 +466,7 @@ test("Liquid Render Include Subfolder HTML", async (t) => { }, }); - let fn = await tr.getCompiledTemplate( - `

{% include subfolder/included.html %}

` - ); + let fn = await tr.getCompiledTemplate(`

{% include subfolder/included.html %}

`); t.is(await fn(), "

This is an include.

"); }); @@ -509,9 +477,7 @@ test("Liquid Render Include Subfolder No file extension", async (t) => { }, }); - let fn = await tr.getCompiledTemplate( - `

{% include subfolder/included %}

` - ); + let fn = await tr.getCompiledTemplate(`

{% include subfolder/included %}

`); t.is(await fn(), "

This is an include.

"); }); @@ -519,55 +485,43 @@ test("Liquid Render Include Subfolder No file extension", async (t) => { // Note that we swapped the dynamicPartials default in Eleventy 1.0 from false to true test("Liquid Render Include Subfolder Single quotes", async (t) => { let tr = await getNewTemplateRender("liquid", "./test/stubs/"); - let fn = await tr.getCompiledTemplate( - `

{% include 'subfolder/included.liquid' %}

` - ); + let fn = await tr.getCompiledTemplate(`

{% include 'subfolder/included.liquid' %}

`); t.is(await fn(), "

This is an include.

"); }); test("Liquid Render Include Subfolder Double quotes", async (t) => { let tr = await getNewTemplateRender("liquid", "./test/stubs/"); - let fn = await tr.getCompiledTemplate( - `

{% include "subfolder/included.liquid" %}

` - ); + let fn = await tr.getCompiledTemplate(`

{% include "subfolder/included.liquid" %}

`); t.is(await fn(), "

This is an include.

"); }); test("Liquid Render Include Subfolder Single quotes HTML", async (t) => { let tr = await getNewTemplateRender("liquid", "./test/stubs/"); - let fn = await tr.getCompiledTemplate( - `

{% include 'subfolder/included.html' %}

` - ); + let fn = await tr.getCompiledTemplate(`

{% include 'subfolder/included.html' %}

`); t.is(await fn(), "

This is an include.

"); }); test("Liquid Render Include Subfolder Double quotes HTML", async (t) => { - let fn = await getNewTemplateRender( - "liquid", - "./test/stubs/" - ).getCompiledTemplate(`

{% include "subfolder/included.html" %}

`); + let tr = await getNewTemplateRender("liquid", "./test/stubs/"); + let fn = await tr.getCompiledTemplate(`

{% include "subfolder/included.html" %}

`); t.is(await fn(), "

This is an include.

"); }); test("Liquid Render Include Subfolder Single quotes No file extension", async (t) => { - let fn = await getNewTemplateRender( - "liquid", - "./test/stubs/" - ).getCompiledTemplate(`

{% include 'subfolder/included' %}

`); + let tr = await getNewTemplateRender("liquid", "./test/stubs/"); + let fn = await tr.getCompiledTemplate(`

{% include 'subfolder/included' %}

`); t.is(await fn(), "

This is an include.

"); }); test("Liquid Render Include Subfolder Double quotes No file extension", async (t) => { - let fn = await getNewTemplateRender( - "liquid", - "./test/stubs/" - ).getCompiledTemplate(`

{% include "subfolder/included" %}

`); + let tr = await getNewTemplateRender("liquid", "./test/stubs/"); + let fn = await tr.getCompiledTemplate(`

{% include "subfolder/included" %}

`); t.is(await fn(), "

This is an include.

"); }); /* End tests related to dynamicPartials */ test("Liquid Options Overrides", async (t) => { - let tr = getNewTemplateRender("liquid", "./test/stubs/", { + let tr = await getNewTemplateRender("liquid", "./test/stubs/", { liquidOptions: { dynamicPartials: false, }, @@ -578,79 +532,63 @@ test("Liquid Options Overrides", async (t) => { }); test("Liquid Render Include Subfolder Single quotes no extension dynamicPartials true", async (t) => { - let tr = getNewTemplateRender("liquid", "./test/stubs/"); - let fn = await tr.getCompiledTemplate( - `

{% include 'subfolder/included' %}

` - ); + let tr = await getNewTemplateRender("liquid", "./test/stubs/"); + let fn = await tr.getCompiledTemplate(`

{% include 'subfolder/included' %}

`); t.is(await fn(), "

This is an include.

"); }); test("Liquid Render Include Subfolder Single quotes (relative include current dir) dynamicPartials true", async (t) => { - let tr = getNewTemplateRender( + let tr = await getNewTemplateRender( "./test/stubs/does_not_exist_and_thats_ok.liquid", "./test/stubs/", {} ); - let fn = await tr.getCompiledTemplate( - `

{% include './relative-liquid/dir/included' %}

` - ); + let fn = await tr.getCompiledTemplate(`

{% include './relative-liquid/dir/included' %}

`); t.is(await fn(), "

TIME IS RELATIVE.

"); }); test("Liquid Render Include Subfolder Single quotes (relative include parent dir) dynamicPartials true", async (t) => { - let tr = getNewTemplateRender( + let tr = await getNewTemplateRender( "./test/stubs/subfolder/does_not_exist_and_thats_ok.liquid", "./test/stubs/", {} ); - let fn = await tr.getCompiledTemplate( - `

{% include '../relative-liquid/dir/included' %}

` - ); + let fn = await tr.getCompiledTemplate(`

{% include '../relative-liquid/dir/included' %}

`); t.is(await fn(), "

TIME IS RELATIVE.

"); }); test("Liquid Render Include Subfolder Double quotes no extension dynamicPartials true", async (t) => { - let tr = getNewTemplateRender("liquid", "./test/stubs/"); - let fn = await tr.getCompiledTemplate( - `

{% include "subfolder/included" %}

` - ); + let tr = await getNewTemplateRender("liquid", "./test/stubs/"); + let fn = await tr.getCompiledTemplate(`

{% include "subfolder/included" %}

`); t.is(await fn(), "

This is an include.

"); }); test("Liquid Render Include Subfolder Single quotes dynamicPartials true", async (t) => { - let tr = getNewTemplateRender("liquid", "./test/stubs/"); - let fn = await tr.getCompiledTemplate( - `

{% include 'subfolder/included.liquid' %}

` - ); + let tr = await getNewTemplateRender("liquid", "./test/stubs/"); + let fn = await tr.getCompiledTemplate(`

{% include 'subfolder/included.liquid' %}

`); t.is(await fn(), "

This is an include.

"); }); test("Liquid Render Include Subfolder Double quotes dynamicPartials true", async (t) => { - let tr = getNewTemplateRender("liquid", "./test/stubs/"); - let fn = await tr.getCompiledTemplate( - `

{% include "subfolder/included.liquid" %}

` - ); + let tr = await getNewTemplateRender("liquid", "./test/stubs/"); + let fn = await tr.getCompiledTemplate(`

{% include "subfolder/included.liquid" %}

`); t.is(await fn(), "

This is an include.

"); }); test("Liquid Render Include Subfolder Single quotes HTML dynamicPartials true", async (t) => { - let tr = getNewTemplateRender("liquid", "./test/stubs/"); - let fn = await tr.getCompiledTemplate( - `

{% include 'subfolder/included.html' %}

` - ); + let tr = await getNewTemplateRender("liquid", "./test/stubs/"); + let fn = await tr.getCompiledTemplate(`

{% include 'subfolder/included.html' %}

`); t.is(await fn(), "

This is an include.

"); }); test("Liquid Render Include Subfolder Double quotes HTML dynamicPartials true", async (t) => { - let tr = getNewTemplateRender("liquid", "./test/stubs/"); - let fn = await tr.getCompiledTemplate( - `

{% include "subfolder/included.html" %}

` - ); + let tr = await getNewTemplateRender("liquid", "./test/stubs/"); + let fn = await tr.getCompiledTemplate(`

{% include "subfolder/included.html" %}

`); t.is(await fn(), "

This is an include.

"); }); test("Liquid Render Include Subfolder Single quotes HTML dynamicPartials true, data passed in", async (t) => { - let tr = getNewTemplateRender("liquid", "./test/stubs/"); + let tr = await getNewTemplateRender("liquid", "./test/stubs/"); let fn = await tr.getCompiledTemplate( `

{% include 'subfolder/included.html', myVariable: 'myValue' %}

` ); @@ -658,7 +596,7 @@ test("Liquid Render Include Subfolder Single quotes HTML dynamicPartials true, d }); test("Liquid Render Include Subfolder Double quotes HTML dynamicPartials true, data passed in", async (t) => { - let tr = getNewTemplateRender("liquid", "./test/stubs/"); + let tr = await getNewTemplateRender("liquid", "./test/stubs/"); let fn = await tr.getCompiledTemplate( `

{% include "subfolder/included.html", myVariable: "myValue" %}

` ); @@ -666,8 +604,8 @@ test("Liquid Render Include Subfolder Double quotes HTML dynamicPartials true, d }); test("Liquid Render: with Library Override", async (t) => { - const tr = getNewTemplateRender("liquid"); - const { Liquid } = require("liquidjs"); + const tr = await getNewTemplateRender("liquid"); + tr.engine.setLibrary(new Liquid()); const fn = await tr.getCompiledTemplate("

{{name | capitalize}}

"); @@ -675,7 +613,7 @@ test("Liquid Render: with Library Override", async (t) => { }); test("Liquid Paired Shortcode with Tag Inside", async (t) => { - let tr = getNewTemplateRender("liquid", "./test/stubs/"); + let tr = await getNewTemplateRender("liquid", "./test/stubs/"); tr.engine.addPairedShortcode("postfixWithZach", function (content, str) { return str + content + "Zach"; }); @@ -690,7 +628,7 @@ test("Liquid Paired Shortcode with Tag Inside", async (t) => { }); test("Liquid Nested Paired Shortcode", async (t) => { - let tr = getNewTemplateRender("liquid", "./test/stubs/"); + let tr = await getNewTemplateRender("liquid", "./test/stubs/"); tr.engine.addPairedShortcode("postfixWithZach", function (content, str) { return str + content + "Zach"; }); @@ -705,7 +643,7 @@ test("Liquid Nested Paired Shortcode", async (t) => { }); test("Liquid Shortcode Multiple Args", async (t) => { - let tr = getNewTemplateRender("liquid", "./test/stubs/"); + let tr = await getNewTemplateRender("liquid", "./test/stubs/"); tr.engine.addShortcode("postfixWithZach", function (str, str2) { return str + str2 + "Zach"; }); @@ -720,37 +658,29 @@ test("Liquid Shortcode Multiple Args", async (t) => { }); test("Liquid Include Scope Leak", async (t) => { - t.is( - getNewTemplateRender("liquid", "./test/stubs/").getEngineName(), - "liquid" - ); + let tr1 = await getNewTemplateRender("liquid", "./test/stubs/"); + t.is(tr1.getEngineName(), "liquid"); // This is by design, `include` assigns value to its parent scope, // use `{% render %}` for separated, clean scope // see: https://github.com/harttle/liquidjs/issues/404#issuecomment-955660149 - let fn = await getNewTemplateRender( - "liquid", - "./test/stubs/" - ).getCompiledTemplate("

{% include 'scopeleak' %}{{ test }}

"); + let tr2 = await getNewTemplateRender("liquid", "./test/stubs/"); + let fn = await tr2.getCompiledTemplate("

{% include 'scopeleak' %}{{ test }}

"); t.is(await fn({ test: 1 }), "

22

"); }); test("Liquid Render Scope Leak", async (t) => { - t.is( - getNewTemplateRender("liquid", "./test/stubs/").getEngineName(), - "liquid" - ); + let tr1 = await getNewTemplateRender("liquid", "./test/stubs/"); + t.is(tr1.getEngineName(), "liquid"); - let fn = await getNewTemplateRender( - "liquid", - "./test/stubs/" - ).getCompiledTemplate("

{% render 'scopeleak' %}{{ test }}

"); + let tr2 = await getNewTemplateRender("liquid", "./test/stubs/"); + let fn = await tr2.getCompiledTemplate("

{% render 'scopeleak' %}{{ test }}

"); t.is(await fn({ test: 1 }), "

21

"); }); // Note: this strictFilters default changed in 1.0 from false to true test("Liquid Missing Filter Issue #183 (no strictFilters)", async (t) => { - let tr = getNewTemplateRender("liquid", "./test/stubs/", { + let tr = await getNewTemplateRender("liquid", "./test/stubs/", { liquidOptions: { strictFilters: false, }, @@ -766,7 +696,7 @@ test("Liquid Missing Filter Issue #183 (no strictFilters)", async (t) => { // Note: this strictFilters default changed in 1.0 from false to true test("Liquid Missing Filter Issue #183", async (t) => { - let tr = getNewTemplateRender("liquid", "./test/stubs/"); + let tr = await getNewTemplateRender("liquid", "./test/stubs/"); try { await tr._testRender("{{ 'test' | prefixWithZach }}", {}); @@ -777,9 +707,8 @@ test("Liquid Missing Filter Issue #183", async (t) => { }); test("Issue 258: Liquid Render Date", async (t) => { - let fn = await getNewTemplateRender("liquid").getCompiledTemplate( - "

{{ myDate }}

" - ); + let tr = await getNewTemplateRender("liquid"); + let fn = await tr.getCompiledTemplate("

{{ myDate }}

"); let dateStr = await fn({ myDate: new Date(Date.UTC(2016, 0, 1, 0, 0, 0)) }); t.is(dateStr.slice(0, 3), "

"); t.is(dateStr.slice(-4), "

"); @@ -787,7 +716,7 @@ test("Issue 258: Liquid Render Date", async (t) => { }); test("Issue 347: Liquid addTags with space in argument", async (t) => { - let tr = getNewTemplateRender("liquid", "./test/stubs/"); + let tr = await getNewTemplateRender("liquid", "./test/stubs/"); tr.engine.addCustomTags({ issue347CustomTag: function (liquidEngine) { return { @@ -811,19 +740,16 @@ test("Issue 347: Liquid addTags with space in argument", async (t) => { }); test("Issue 347: Liquid Shortcode, string argument", async (t) => { - let tr = getNewTemplateRender("liquid", "./test/stubs/"); + let tr = await getNewTemplateRender("liquid", "./test/stubs/"); tr.engine.addShortcode("issue347", function (str) { return str + "Zach"; }); - t.is( - await tr._testRender("{% issue347 'test' %}", { name: "alkdsjfkslja" }), - "testZach" - ); + t.is(await tr._testRender("{% issue347 'test' %}", { name: "alkdsjfkslja" }), "testZach"); }); test("Issue 347: Liquid Shortcode string argument with space, double quotes", async (t) => { - let tr = getNewTemplateRender("liquid", "./test/stubs/"); + let tr = await getNewTemplateRender("liquid", "./test/stubs/"); tr.engine.addShortcode("issue347b", function (str) { return str + "Zach"; }); @@ -837,19 +763,16 @@ test("Issue 347: Liquid Shortcode string argument with space, double quotes", as }); test("Issue 347: Liquid Shortcode string argument with space, single quotes", async (t) => { - let tr = getNewTemplateRender("liquid", "./test/stubs/"); + let tr = await getNewTemplateRender("liquid", "./test/stubs/"); tr.engine.addShortcode("issue347", function (str) { return str + "Zach"; }); - t.is( - await tr._testRender("{% issue347 'test 2' %}", { name: "alkdsjfkslja" }), - "test 2Zach" - ); + t.is(await tr._testRender("{% issue347 'test 2' %}", { name: "alkdsjfkslja" }), "test 2Zach"); }); test("Issue 347: Liquid Shortcode string argument with space, combination of quotes", async (t) => { - let tr = getNewTemplateRender("liquid", "./test/stubs/"); + let tr = await getNewTemplateRender("liquid", "./test/stubs/"); tr.engine.addShortcode("issue347", function (str, str2) { return str + str2 + "Zach"; }); @@ -863,7 +786,7 @@ test("Issue 347: Liquid Shortcode string argument with space, combination of quo }); test("Issue 347: Liquid Shortcode multiple arguments, comma separated", async (t) => { - let tr = getNewTemplateRender("liquid", "./test/stubs/"); + let tr = await getNewTemplateRender("liquid", "./test/stubs/"); tr.engine.addShortcode("issue347", function (str, str2) { return str + str2 + "Zach"; }); @@ -877,7 +800,7 @@ test("Issue 347: Liquid Shortcode multiple arguments, comma separated", async (t }); test("Issue 347: Liquid Shortcode multiple arguments, comma separated, one is an integer", async (t) => { - let tr = getNewTemplateRender("liquid", "./test/stubs/"); + let tr = await getNewTemplateRender("liquid", "./test/stubs/"); tr.engine.addShortcode("issue347", function (str, str2) { return str + str2 + "Zach"; }); @@ -891,7 +814,7 @@ test("Issue 347: Liquid Shortcode multiple arguments, comma separated, one is an }); test("Issue 347: Liquid Shortcode multiple arguments, comma separated, one is a float", async (t) => { - let tr = getNewTemplateRender("liquid", "./test/stubs/"); + let tr = await getNewTemplateRender("liquid", "./test/stubs/"); tr.engine.addShortcode("issue347", function (str, str2) { return str + str2 + "Zach"; }); @@ -905,29 +828,20 @@ test("Issue 347: Liquid Shortcode multiple arguments, comma separated, one is a }); test("Issue 347: Liquid Shortcode boolean argument", async (t) => { - let tr = getNewTemplateRender("liquid", "./test/stubs/"); + let tr = await getNewTemplateRender("liquid", "./test/stubs/"); tr.engine.addShortcode("issue347", function (bool) { return bool ? "Zach" : "Not Zach"; }); - t.is( - await tr._testRender("{% issue347 true %}", { name: "alkdsjfkslja" }), - "Zach" - ); - t.is( - await tr._testRender("{% issue347 false %}", { name: "alkdsjfkslja" }), - "Not Zach" - ); + t.is(await tr._testRender("{% issue347 true %}", { name: "alkdsjfkslja" }), "Zach"); + t.is(await tr._testRender("{% issue347 false %}", { name: "alkdsjfkslja" }), "Not Zach"); }); test("Issue 347: Liquid Paired Shortcode with Spaces", async (t) => { - let tr = getNewTemplateRender("liquid", "./test/stubs/"); - tr.engine.addPairedShortcode( - "postfixWithZach", - function (content, str1, num, str2) { - return str1 + num + str2 + content + "Zach"; - } - ); + let tr = await getNewTemplateRender("liquid", "./test/stubs/"); + tr.engine.addPairedShortcode("postfixWithZach", function (content, str1, num, str2) { + return str1 + num + str2 + content + "Zach"; + }); t.is( await tr._testRender( @@ -939,14 +853,14 @@ test("Issue 347: Liquid Paired Shortcode with Spaces", async (t) => { }); test("Liquid Render with dash variable Issue #567", async (t) => { - let tr = getNewTemplateRender("liquid"); + let tr = await getNewTemplateRender("liquid"); let fn = await tr.getCompiledTemplate("

{{ my-global-name }}

"); t.is(await fn({ "my-global-name": "Zach" }), "

Zach

"); }); test("Issue 600: Liquid Shortcode argument page.url", async (t) => { - let tr = getNewTemplateRender("liquid", "./test/stubs/"); + let tr = await getNewTemplateRender("liquid", "./test/stubs/"); tr.engine.addShortcode("issue600", function (str) { return str + "Zach"; }); @@ -960,7 +874,7 @@ test("Issue 600: Liquid Shortcode argument page.url", async (t) => { }); test("Issue 600: Liquid Shortcode argument with dashes", async (t) => { - let tr = getNewTemplateRender("liquid", "./test/stubs/"); + let tr = await getNewTemplateRender("liquid", "./test/stubs/"); tr.engine.addShortcode("issue600b", function (str) { return str + "Zach"; }); @@ -974,7 +888,7 @@ test("Issue 600: Liquid Shortcode argument with dashes", async (t) => { }); test("Issue 600: Liquid Shortcode argument with underscores", async (t) => { - let tr = getNewTemplateRender("liquid", "./test/stubs/"); + let tr = await getNewTemplateRender("liquid", "./test/stubs/"); tr.engine.addShortcode("issue600c", function (str) { return str + "Zach"; }); @@ -989,7 +903,7 @@ test("Issue 600: Liquid Shortcode argument with underscores", async (t) => { test("Issue 611: Run a function", async (t) => { // function calls in Nunjucks can be replaced by custom Drops - let tr = getNewTemplateRender("liquid", "./test/stubs/"); + let tr = await getNewTemplateRender("liquid", "./test/stubs/"); class CustomDrop extends Drop { valueOf() { return "alkdsjfksljaZach"; @@ -1004,7 +918,7 @@ test("Issue 611: Run a function", async (t) => { }); test("Liquid Shortcode (with sync function, error throwing)", async (t) => { - let tr = getNewTemplateRender("liquid", "./test/stubs/"); + let tr = await getNewTemplateRender("liquid", "./test/stubs/"); tr.engine.addShortcode("postfixWithZach", function (str) { throw new Error("Liquid Shortcode (with sync function, error throwing)"); }); @@ -1012,15 +926,11 @@ test("Liquid Shortcode (with sync function, error throwing)", async (t) => { let error = await t.throwsAsync(async () => { await tr._testRender("{% postfixWithZach name %}", { name: "test" }); }); - t.true( - error.message.indexOf( - "Liquid Shortcode (with sync function, error throwing)" - ) > -1 - ); + t.true(error.message.indexOf("Liquid Shortcode (with sync function, error throwing)") > -1); }); test("Liquid Shortcode (with async function, error throwing)", async (t) => { - let tr = getNewTemplateRender("liquid", "./test/stubs/"); + let tr = await getNewTemplateRender("liquid", "./test/stubs/"); tr.engine.addShortcode("postfixWithZach", async function (str) { throw new Error("Liquid Shortcode (with async function, error throwing)"); }); @@ -1028,91 +938,75 @@ test("Liquid Shortcode (with async function, error throwing)", async (t) => { let error = await t.throwsAsync(async () => { await tr._testRender("{% postfixWithZach name %}", { name: "test" }); }); - t.true( - error.message.indexOf( - "Liquid Shortcode (with async function, error throwing)" - ) > -1 - ); + t.true(error.message.indexOf("Liquid Shortcode (with async function, error throwing)") > -1); }); test("Liquid Render a false #1069", async (t) => { - let fn = await getNewTemplateRender("liquid").getCompiledTemplate( - "{{ falseValue }}" - ); + let tr = await getNewTemplateRender("liquid"); + let fn = await tr.getCompiledTemplate("{{ falseValue }}"); t.is(await fn({ falseValue: false }), "false"); }); test("Liquid Render Square Brackets #680 dash single quotes", async (t) => { - let fn = await getNewTemplateRender("liquid").getCompiledTemplate( - "

{{ test['hey-a'] }}

" - ); + let tr = await getNewTemplateRender("liquid"); + let fn = await tr.getCompiledTemplate("

{{ test['hey-a'] }}

"); t.is(await fn({ test: { "hey-a": 1 } }), "

1

"); }); test("Liquid Render Square Brackets #680 dash single quotes spaces", async (t) => { - let fn = await getNewTemplateRender("liquid").getCompiledTemplate( - "

{{ test[ 'hey-a' ] }}

" - ); + let tr = await getNewTemplateRender("liquid"); + let fn = await tr.getCompiledTemplate("

{{ test[ 'hey-a' ] }}

"); t.is(await fn({ test: { "hey-a": 1 } }), "

1

"); }); test("Liquid Render Square Brackets #680 dash double quotes", async (t) => { - let fn = await getNewTemplateRender("liquid").getCompiledTemplate( - '

{{ test["hey-a"] }}

' - ); + let tr = await getNewTemplateRender("liquid"); + let fn = await tr.getCompiledTemplate('

{{ test["hey-a"] }}

'); t.is(await fn({ test: { "hey-a": 1 } }), "

1

"); }); test("Liquid Render Square Brackets #680 dash double quotes spaces", async (t) => { - let fn = await getNewTemplateRender("liquid").getCompiledTemplate( - '

{{ test[ "hey-a" ] }}

' - ); + let tr = await getNewTemplateRender("liquid"); + let fn = await tr.getCompiledTemplate('

{{ test[ "hey-a" ] }}

'); t.is(await fn({ test: { "hey-a": 1 } }), "

1

"); }); test("Liquid Render Square Brackets #680 variable reference", async (t) => { - let fn = await getNewTemplateRender("liquid").getCompiledTemplate( - "

{{ test[ref] }}

" - ); + let tr = await getNewTemplateRender("liquid"); + let fn = await tr.getCompiledTemplate("

{{ test[ref] }}

"); t.is(await fn({ test: { "hey-a": 1 }, ref: "hey-a" }), "

1

"); }); test("Liquid Render Square Brackets #680 variable reference array", async (t) => { - let fn = await getNewTemplateRender("liquid").getCompiledTemplate( - "

{{ test[ref[0]] }}

" - ); + let tr = await getNewTemplateRender("liquid"); + let fn = await tr.getCompiledTemplate("

{{ test[ref[0]] }}

"); t.is(await fn({ test: { "hey-a": 1 }, ref: ["hey-a"] }), "

1

"); }); test("Liquid bypass compilation", async (t) => { - let tr = getNewTemplateRender("liquid"); + let tr = await getNewTemplateRender("liquid"); t.is(tr.engine.needsCompilation("

{{ me }}

"), true); - t.is( - tr.engine.needsCompilation("

{% comment %}{% endcomment %}

"), - true - ); + t.is(tr.engine.needsCompilation("

{% comment %}{% endcomment %}

"), true); t.is(tr.engine.needsCompilation("

test

"), false); }); test("Liquid reverse filter in {{ }}", async (t) => { + let tr = await getNewTemplateRender("liquid"); // https://liquidjs.com/filters/reverse.html - let fn = await getNewTemplateRender("liquid").getCompiledTemplate( - "{{ test | reverse | join: ',' }}" - ); + let fn = await tr.getCompiledTemplate("{{ test | reverse | join: ',' }}"); t.is(await fn({ test: [1, 2, 3] }), "3,2,1"); }); test("Liquid reverse filter in {% for %}", async (t) => { + let tr = await getNewTemplateRender("liquid"); // https://liquidjs.com/tags/for.html#reversed - let fn = await getNewTemplateRender("liquid").getCompiledTemplate( - "{% for num in test reversed %}{{ num }}{% endfor %}" - ); + let fn = await tr.getCompiledTemplate("{% for num in test reversed %}{{ num }}{% endfor %}"); t.is(await fn({ test: [1, 2, 3] }), "321"); }); test("Liquid Parse for Symbols", async (t) => { - let tr = getNewTemplateRender("liquid"); + let tr = await getNewTemplateRender("liquid"); let engine = tr.engine; t.deepEqual(engine.parseForSymbols("

{{ name }}

"), ["name"]); @@ -1120,24 +1014,14 @@ test("Liquid Parse for Symbols", async (t) => { "eleventy.deep.nested", ]); t.deepEqual(engine.parseForSymbols("

{{ a }} {{ b }}

"), ["a", "b"]); - t.deepEqual( - engine.parseForSymbols("

{% if true %}{{ c }}{% endif %}

"), - ["c"] - ); - t.deepEqual( - engine.parseForSymbols("

{% if false %}{{ c }}{% endif %}

"), - ["c"] - ); + t.deepEqual(engine.parseForSymbols("

{% if true %}{{ c }}{% endif %}

"), ["c"]); + t.deepEqual(engine.parseForSymbols("

{% if false %}{{ c }}{% endif %}

"), ["c"]); t.deepEqual(engine.parseForSymbols("{{ collections.all[0] }}>"), [ // Note that the Nunjucks parser returns collections.all "collections.all[0]", ]); - t.deepEqual(engine.parseForSymbols("{{ collections.mine }}>"), [ - "collections.mine", - ]); + t.deepEqual(engine.parseForSymbols("{{ collections.mine }}>"), ["collections.mine"]); - t.deepEqual(engine.parseForSymbols("{{ collections.mine | test }}>"), [ - "collections.mine", - ]); + t.deepEqual(engine.parseForSymbols("{{ collections.mine | test }}>"), ["collections.mine"]); }); diff --git a/test/TemplateRenderMarkdownPluginTest.js b/test/TemplateRenderMarkdownPluginTest.js index a7e34b998..09b21bac9 100644 --- a/test/TemplateRenderMarkdownPluginTest.js +++ b/test/TemplateRenderMarkdownPluginTest.js @@ -1,13 +1,17 @@ -const test = require("ava"); -const TemplateRender = require("../src/TemplateRender"); -const TemplateConfig = require("../src/TemplateConfig"); -const EleventyExtensionMap = require("../src/EleventyExtensionMap"); -const md = require("markdown-it"); +import test from "ava"; +import md from "markdown-it"; -function getNewTemplateRender(name, inputDir) { +import TemplateRender from "../src/TemplateRender.js"; +import TemplateConfig from "../src/TemplateConfig.js"; +import EleventyExtensionMap from "../src/EleventyExtensionMap.js"; + +async function getNewTemplateRender(name, inputDir) { let eleventyConfig = new TemplateConfig(); + await eleventyConfig.init(); + let tr = new TemplateRender(name, inputDir, eleventyConfig); tr.extensionMap = new EleventyExtensionMap([], eleventyConfig); + await tr.init(); return tr; } @@ -25,7 +29,7 @@ const createTestMarkdownPlugin = () => { }; test("Markdown Render: with HTML prerender, sends context data to the markdown library", async (t) => { - let tr = getNewTemplateRender("md"); + let tr = await getNewTemplateRender("md"); const plugin = createTestMarkdownPlugin(); let mdLib = md().use(plugin); @@ -40,7 +44,7 @@ test("Markdown Render: with HTML prerender, sends context data to the markdown l }); test("Markdown Render: without HTML prerender, sends context data to the markdown library", async (t) => { - let tr = getNewTemplateRender("md"); + let tr = await getNewTemplateRender("md"); const plugin = createTestMarkdownPlugin(); let mdLib = md().use(plugin); @@ -56,7 +60,7 @@ test("Markdown Render: without HTML prerender, sends context data to the markdow }); test("Markdown Render: renderer that only implements the render function", async (t) => { - let tr = getNewTemplateRender("md"); + let tr = await getNewTemplateRender("md"); tr.engine.setLibrary({ render: (content) => { const [_, text, href] = content.match(/\[(.*)\]\((.*)\)/); diff --git a/test/TemplateRenderMarkdownTest.js b/test/TemplateRenderMarkdownTest.js index cd2a94896..1bc4dbe54 100644 --- a/test/TemplateRenderMarkdownTest.js +++ b/test/TemplateRenderMarkdownTest.js @@ -1,61 +1,61 @@ -const test = require("ava"); -const md = require("markdown-it"); -const mdEmoji = require("markdown-it-emoji"); -const eleventySyntaxHighlightPlugin = require("@11ty/eleventy-plugin-syntaxhighlight"); - -const TemplateRender = require("../src/TemplateRender"); -const TemplateConfig = require("../src/TemplateConfig"); -const EleventyExtensionMap = require("../src/EleventyExtensionMap"); -const normalizeNewLines = require("./Util/normalizeNewLines"); - -function getNewTemplateRender(name, inputDir, eleventyConfig) { +import test from "ava"; +import md from "markdown-it"; +import mdEmoji from "markdown-it-emoji"; +import eleventySyntaxHighlightPlugin from "@11ty/eleventy-plugin-syntaxhighlight"; + +import TemplateRender from "../src/TemplateRender.js"; +import TemplateConfig from "../src/TemplateConfig.js"; +import Liquid from "../src/Engines/Liquid.js"; +import Nunjucks from "../src/Engines/Nunjucks.js"; +import EleventyExtensionMap from "../src/EleventyExtensionMap.js"; +import normalizeNewLines from "./Util/normalizeNewLines.js"; + +async function getNewTemplateRender(name, inputDir, eleventyConfig) { if (!eleventyConfig) { eleventyConfig = new TemplateConfig(); + await eleventyConfig.init(); } let tr = new TemplateRender(name, inputDir, eleventyConfig); tr.extensionMap = new EleventyExtensionMap([], eleventyConfig); + await tr.init(); return tr; } // Markdown -test("Markdown", (t) => { - t.is(getNewTemplateRender("md").getEngineName(), "md"); +test("Markdown", async (t) => { + let tr = await getNewTemplateRender("md"); + t.is(tr.getEngineName(), "md"); }); test("Markdown Render: Parses base markdown, no data", async (t) => { - let fn = await getNewTemplateRender("md").getCompiledTemplate("# My Title"); + let tr = await getNewTemplateRender("md"); + let fn = await tr.getCompiledTemplate("# My Title"); t.is((await fn()).trim(), "

My Title

"); }); test("Markdown Render: Markdown should work with HTML too", async (t) => { - let fn = await getNewTemplateRender("md").getCompiledTemplate( - "

My Title

" - ); + let tr = await getNewTemplateRender("md"); + let fn = await tr.getCompiledTemplate("

My Title

"); t.is((await fn()).trim(), "

My Title

"); }); test("Markdown Render: Parses markdown using liquid engine (default, with data)", async (t) => { - let fn = await getNewTemplateRender("md").getCompiledTemplate("# {{title}}"); + let tr = await getNewTemplateRender("md"); + let fn = await tr.getCompiledTemplate("# {{title}}"); t.is((await fn({ title: "My Title" })).trim(), "

My Title

"); }); -test("Markdown Render: Parses markdown using ejs engine", async (t) => { - let tr = getNewTemplateRender("md"); - tr.setMarkdownEngine("ejs"); - let fn = await tr.getCompiledTemplate("<%=title %>"); - t.is((await fn({ title: "My Title" })).trim(), "

My Title

"); -}); - test("Markdown Render: Ignore markdown, use only preprocess engine (useful for variable resolution in permalinks)", async (t) => { - let tr = getNewTemplateRender("md"); + let tr = await getNewTemplateRender("md"); tr.setUseMarkdown(false); + let fn = await tr.getCompiledTemplate("{{title}}"); t.is((await fn({ title: "My Title" })).trim(), "My Title"); }); test("Markdown Render: Skip markdown and preprocess engine (issue #466)", async (t) => { - let tr = getNewTemplateRender("md"); + let tr = await getNewTemplateRender("md"); tr.setMarkdownEngine(false); tr.setUseMarkdown(false); let fn = await tr.getCompiledTemplate("404.html"); @@ -63,29 +63,22 @@ test("Markdown Render: Skip markdown and preprocess engine (issue #466)", async }); test("Markdown Render: Set markdown engine to false, don’t parse", async (t) => { - let tr = getNewTemplateRender("md"); + let tr = await getNewTemplateRender("md"); tr.setMarkdownEngine(false); let fn = await tr.getCompiledTemplate("# {{title}}"); t.is((await fn()).trim(), "

{{title}}

"); }); test("Markdown Render: Set markdown engine to false, don’t parse (test with HTML input)", async (t) => { - let tr = getNewTemplateRender("md"); + let tr = await getNewTemplateRender("md"); tr.setMarkdownEngine(false); let fn = await tr.getCompiledTemplate("

{{title}}

"); t.is((await fn()).trim(), "

{{title}}

"); }); -test("Markdown Render: Pass in engine override (ejs)", async (t) => { - let tr = getNewTemplateRender("md"); - tr.setMarkdownEngine("ejs"); - let fn = await tr.getCompiledTemplate("# <%= title %>"); - t.is((await fn({ title: "My Title" })).trim(), "

My Title

"); -}); - test("Markdown Render: Pass in an override (liquid)", async (t) => { - let tr = getNewTemplateRender("md"); + let tr = await getNewTemplateRender("md"); tr.setMarkdownEngine("liquid"); let fn = await tr.getCompiledTemplate("# {{title}}"); @@ -93,17 +86,19 @@ test("Markdown Render: Pass in an override (liquid)", async (t) => { }); test("Markdown Render: Strikethrough", async (t) => { - let fn = await getNewTemplateRender("md").getCompiledTemplate("~~No~~"); + let tr = await getNewTemplateRender("md"); + let fn = await tr.getCompiledTemplate("~~No~~"); t.is((await fn()).trim(), "

No

"); }); test("Markdown Render: Strikethrough in a Header", async (t) => { - let fn = await getNewTemplateRender("md").getCompiledTemplate("# ~~No~~"); + let tr = await getNewTemplateRender("md"); + let fn = await tr.getCompiledTemplate("# ~~No~~"); t.is((await fn()).trim(), "

No

"); }); test("Markdown Render: with Library Override", async (t) => { - let tr = getNewTemplateRender("md"); + let tr = await getNewTemplateRender("md"); let mdLib = md(); tr.engine.setLibrary(mdLib); @@ -114,7 +109,7 @@ test("Markdown Render: with Library Override", async (t) => { }); test("Markdown Render: with Library Override and a Plugin", async (t) => { - let tr = getNewTemplateRender("md"); + let tr = await getNewTemplateRender("md"); let mdLib = md().use(mdEmoji); tr.engine.setLibrary(mdLib); @@ -125,7 +120,7 @@ test("Markdown Render: with Library Override and a Plugin", async (t) => { }); test("Markdown Render: use a custom highlighter", async (t) => { - let tr = getNewTemplateRender("md"); + let tr = await getNewTemplateRender("md"); let mdLib = md(); mdLib.set({ @@ -142,10 +137,12 @@ This is some code. }); test("Markdown Render: use prism highlighter (no language)", async (t) => { - let tr = getNewTemplateRender("md"); let eleventyConfig = new TemplateConfig(); let userConfig = eleventyConfig.userConfig; userConfig.addPlugin(eleventySyntaxHighlightPlugin); + await eleventyConfig.init(); + + let tr = await getNewTemplateRender("md", null, eleventyConfig); let markdownHighlight = eleventyConfig.getConfig().markdownHighlighter; let mdLib = md(); @@ -165,10 +162,12 @@ This is some code. }); test("Markdown Render: use prism highlighter", async (t) => { - let tr = getNewTemplateRender("md"); let eleventyConfig = new TemplateConfig(); let userConfig = eleventyConfig.userConfig; userConfig.addPlugin(eleventySyntaxHighlightPlugin); + await eleventyConfig.init(); + + let tr = await getNewTemplateRender("md"); let markdownHighlight = eleventyConfig.getConfig().markdownHighlighter; @@ -188,10 +187,12 @@ var key = "value"; }); test("Markdown Render: use prism highlighter (no space before language)", async (t) => { - let tr = getNewTemplateRender("md"); let eleventyConfig = new TemplateConfig(); let userConfig = eleventyConfig.userConfig; userConfig.addPlugin(eleventySyntaxHighlightPlugin); + await eleventyConfig.init(); + + let tr = await getNewTemplateRender("md", null, eleventyConfig); let markdownHighlight = eleventyConfig.getConfig().markdownHighlighter; @@ -211,11 +212,12 @@ var key = "value"; }); test("Markdown Render: use prism highlighter, line highlighting", async (t) => { - let tr = getNewTemplateRender("md"); let eleventyConfig = new TemplateConfig(); let userConfig = eleventyConfig.userConfig; userConfig.addPlugin(eleventySyntaxHighlightPlugin); + await eleventyConfig.init(); + let tr = await getNewTemplateRender("md", null, eleventyConfig); let markdownHighlight = eleventyConfig.getConfig().markdownHighlighter; let mdLib = md(); @@ -234,12 +236,16 @@ var key = "value"; }); test("Markdown Render: use prism highlighter, line highlighting with fallback `text` language.", async (t) => { - let tr = getNewTemplateRender("md"); let eleventyConfig = new TemplateConfig(); let userConfig = eleventyConfig.userConfig; userConfig.addPlugin(eleventySyntaxHighlightPlugin); - let markdownHighlight = eleventyConfig.getConfig().markdownHighlighter; + await eleventyConfig.init(); + + let tr = await getNewTemplateRender("md", null, eleventyConfig); + + let cfg = eleventyConfig.getConfig(); + let markdownHighlight = cfg.markdownHighlighter; let mdLib = md(); mdLib.set({ @@ -257,11 +263,12 @@ var key = "value"; }); test("Markdown Render: use Markdown inside of a Liquid shortcode (Issue #536)", async (t) => { - let tr = getNewTemplateRender("md"); let eleventyConfig = new TemplateConfig(); - let cls = require("../src/Engines/Liquid"); + await eleventyConfig.init(); + + let tr = await getNewTemplateRender("md", null, eleventyConfig); - let liquidEngine = new cls("liquid", tr.getDirs(), eleventyConfig); + let liquidEngine = new Liquid("liquid", tr.getDirs(), eleventyConfig); liquidEngine.addShortcode("testShortcode", function () { return "## My Other Title"; }); @@ -282,10 +289,11 @@ test("Markdown Render: use Markdown inside of a Liquid shortcode (Issue #536)", }); test("Markdown Render: use Markdown inside of a Nunjucks shortcode (Issue #536)", async (t) => { - let tr = getNewTemplateRender("md"); let eleventyConfig = new TemplateConfig(); - let cls = require("../src/Engines/Nunjucks"); - let nunjucksEngine = new cls("njk", tr.getDirs(), eleventyConfig); + await eleventyConfig.init(); + + let tr = await getNewTemplateRender("md", null, eleventyConfig); + let nunjucksEngine = new Nunjucks("njk", tr.getDirs(), eleventyConfig); nunjucksEngine.addShortcode("testShortcode", function () { return "## My Other Title"; }); @@ -306,10 +314,12 @@ test("Markdown Render: use Markdown inside of a Nunjucks shortcode (Issue #536)" }); test("Markdown Render: use Markdown inside of a Liquid paired shortcode (Issue #536)", async (t) => { - let tr = getNewTemplateRender("md"); let eleventyConfig = new TemplateConfig(); - let cls = require("../src/Engines/Liquid"); - let liquidEngine = new cls("liquid", tr.getIncludesDir(), eleventyConfig); + await eleventyConfig.init(); + + let tr = await getNewTemplateRender("md", null, eleventyConfig); + + let liquidEngine = new Liquid("liquid", tr.getIncludesDir(), eleventyConfig); liquidEngine.addPairedShortcode("testShortcode", function (content) { return content; }); @@ -330,11 +340,12 @@ test("Markdown Render: use Markdown inside of a Liquid paired shortcode (Issue # }); test("Markdown Render: use Markdown inside of a Nunjucks paired shortcode (Issue #536)", async (t) => { - let tr = getNewTemplateRender("md"); let eleventyConfig = new TemplateConfig(); + await eleventyConfig.init(); + + let tr = await getNewTemplateRender("md", null, eleventyConfig); - let cls = require("../src/Engines/Nunjucks"); - let nunjucksEngine = new cls("njk", tr.getDirs(), eleventyConfig); + let nunjucksEngine = new Nunjucks("njk", tr.getDirs(), eleventyConfig); nunjucksEngine.addPairedShortcode("testShortcode", function (content) { return content; }); @@ -355,14 +366,13 @@ test("Markdown Render: use Markdown inside of a Nunjucks paired shortcode (Issue }); test("Markdown Render: Disable indented code blocks by default. Issue #2438", async (t) => { - let fn = await getNewTemplateRender("md").getCompiledTemplate( - " This is a test" - ); + let tr = await getNewTemplateRender("md"); + let fn = await tr.getCompiledTemplate(" This is a test"); t.is((await fn()).trim(), "

This is a test

"); }); test("Markdown Render: setLibrary does not have disabled indented code blocks either. Issue #2438", async (t) => { - let tr = getNewTemplateRender("md"); + let tr = await getNewTemplateRender("md"); let mdLib = md(); tr.engine.setLibrary(mdLib); @@ -376,8 +386,9 @@ test("Markdown Render: use amendLibrary to re-enable indented code blocks. Issue let eleventyConfig = new TemplateConfig(); let userConfig = eleventyConfig.userConfig; userConfig.amendLibrary("md", (lib) => lib.enable("code")); + await eleventyConfig.init(); - let tr = getNewTemplateRender("md", null, eleventyConfig); + let tr = await getNewTemplateRender("md", null, eleventyConfig); let fn = await tr.getCompiledTemplate(" This is a test"); let content = await fn(); @@ -392,8 +403,9 @@ test("Markdown Render: amendLibrary works with setLibrary to re-enable indented let eleventyConfig = new TemplateConfig(); let userConfig = eleventyConfig.userConfig; userConfig.amendLibrary("md", (lib) => lib.enable("code")); + await eleventyConfig.init(); - let tr = getNewTemplateRender("md", null, eleventyConfig); + let tr = await getNewTemplateRender("md", null, eleventyConfig); let mdLib = md(); tr.engine.setLibrary(mdLib); @@ -420,8 +432,9 @@ test("Markdown Render: multiple amendLibrary calls. Issue #2438", async (t) => { t.true(true); lib.disable("code"); }); + await eleventyConfig.init(); - let tr = getNewTemplateRender("md", null, eleventyConfig); + let tr = await getNewTemplateRender("md", null, eleventyConfig); let fn = await tr.getCompiledTemplate(" This is a test"); let content = await fn(); @@ -432,8 +445,9 @@ test("Markdown Render: use amendLibrary to add a Plugin", async (t) => { let eleventyConfig = new TemplateConfig(); let userConfig = eleventyConfig.userConfig; userConfig.amendLibrary("md", (mdLib) => mdLib.use(mdEmoji)); + await eleventyConfig.init(); - let tr = getNewTemplateRender("md", null, eleventyConfig); + let tr = await getNewTemplateRender("md", null, eleventyConfig); let fn = await tr.getCompiledTemplate(":)"); t.is((await fn()).trim(), "

😃

"); }); diff --git a/test/TemplateRenderMustacheTest.js b/test/TemplateRenderMustacheTest.js deleted file mode 100644 index 30b2a4146..000000000 --- a/test/TemplateRenderMustacheTest.js +++ /dev/null @@ -1,89 +0,0 @@ -const test = require("ava"); -const TemplateRender = require("../src/TemplateRender"); -const TemplateConfig = require("../src/TemplateConfig"); -const EleventyExtensionMap = require("../src/EleventyExtensionMap"); - -function getNewTemplateRender(name, inputDir) { - let eleventyConfig = new TemplateConfig(); - let tr = new TemplateRender(name, inputDir, eleventyConfig); - tr.extensionMap = new EleventyExtensionMap([], eleventyConfig); - return tr; -} - -// Mustache -test("Mustache", async (t) => { - t.is(getNewTemplateRender("mustache").getEngineName(), "mustache"); -}); - -test("Mustache Render", async (t) => { - let fn = await getNewTemplateRender("mustache").getCompiledTemplate( - "

{{name}}

" - ); - t.is(await fn({ name: "Zach" }), "

Zach

"); -}); - -test("Mustache Render Partial (raw text content)", async (t) => { - let fn = await getNewTemplateRender( - "mustache", - "./test/stubs/" - ).getCompiledTemplate("

{{> included}}

"); - t.is(await fn(), "

This is an include.

"); -}); - -test.skip("Mustache Render Partial (relative path, raw text content)", async (t) => { - let fn = await getNewTemplateRender( - "./test/stubs/does_not_exist_and_thats_ok.mustache", - "./test/stubs/" - ).getCompiledTemplate("

{{> ./includedrelative}}

"); - t.is(await fn(), "

This is an includdde.

"); -}); - -test("Mustache Render Partial (uses a variable in content)", async (t) => { - let fn = await getNewTemplateRender( - "mustache", - "./test/stubs/" - ).getCompiledTemplate("

{{> includedvar}}

"); - t.is(await fn({ name: "Zach" }), "

This is a Zach.

"); -}); - -test("Mustache Render Partial (Subdirectory)", async (t) => { - let fn = await getNewTemplateRender( - "mustache", - "./test/stubs/" - ).getCompiledTemplate("

{{> subfolder/included}}

"); - t.is(await fn({ name: "Zach" }), "

This is an include.

"); -}); - -test("Mustache Render: with Library Override", async (t) => { - let tr = getNewTemplateRender("mustache"); - - let lib = require("mustache"); - tr.engine.setLibrary(lib); - - let fn = await tr.getCompiledTemplate("

{{name}}

"); - t.is(await fn({ name: "Zach" }), "

Zach

"); -}); - -test("Mustache Render Unescaped Output (no HTML)", async (t) => { - let fn = await getNewTemplateRender("mustache").getCompiledTemplate( - "

{{{name}}}

" - ); - t.is(await fn({ name: "Zach" }), "

Zach

"); -}); - -test("Mustache Render Escaped Output", async (t) => { - let fn = await getNewTemplateRender("mustache").getCompiledTemplate( - "

{{name}}

" - ); - t.is( - await fn({ name: "Zach" }), - "

<b>Zach</b>

" - ); -}); - -test("Mustache Render Unescaped Output (HTML)", async (t) => { - let fn = await getNewTemplateRender("mustache").getCompiledTemplate( - "

{{{name}}}

" - ); - t.is(await fn({ name: "Zach" }), "

Zach

"); -}); diff --git a/test/TemplateRenderNunjucksTest.js b/test/TemplateRenderNunjucksTest.js index c4b78a5a0..0f0dc7359 100644 --- a/test/TemplateRenderNunjucksTest.js +++ b/test/TemplateRenderNunjucksTest.js @@ -1,16 +1,20 @@ -const test = require("ava"); -const TemplateRender = require("../src/TemplateRender"); -const TemplateConfig = require("../src/TemplateConfig"); -const EleventyExtensionMap = require("../src/EleventyExtensionMap"); -const normalizeNewLines = require("./Util/normalizeNewLines"); +import test from "ava"; +import Nunjucks from "nunjucks"; -function getNewTemplateRender(name, inputDir, eleventyConfig) { +import TemplateRender from "../src/TemplateRender.js"; +import TemplateConfig from "../src/TemplateConfig.js"; +import EleventyExtensionMap from "../src/EleventyExtensionMap.js"; +import normalizeNewLines from "./Util/normalizeNewLines.js"; + +async function getNewTemplateRender(name, inputDir, eleventyConfig) { if (!eleventyConfig) { eleventyConfig = new TemplateConfig(); + await eleventyConfig.init(); } let tr = new TemplateRender(name, inputDir, eleventyConfig); tr.extensionMap = new EleventyExtensionMap([], eleventyConfig); + await tr.init(); return tr; } @@ -23,87 +27,79 @@ async function getPromise(resolveTo) { } // Nunjucks -test("Nunjucks", (t) => { - t.is(getNewTemplateRender("njk").getEngineName(), "njk"); +test("Nunjucks", async (t) => { + let tr = await getNewTemplateRender("njk"); + t.is(tr.getEngineName(), "njk"); }); test("Nunjucks Render", async (t) => { - let fn = await getNewTemplateRender("njk").getCompiledTemplate( - "

{{ name }}

" - ); + let tr = await getNewTemplateRender("njk"); + let fn = await tr.getCompiledTemplate("

{{ name }}

"); t.is(await fn({ name: "Zach" }), "

Zach

"); }); test("Nunjucks Render Addition", async (t) => { - let fn = await getNewTemplateRender("njk").getCompiledTemplate( - "

{{ number + 1 }}

" - ); + let tr = await getNewTemplateRender("njk"); + let fn = await tr.getCompiledTemplate("

{{ number + 1 }}

"); t.is(await fn({ number: 1 }), "

2

"); }); test("Nunjucks Render Extends", async (t) => { - let fn = await getNewTemplateRender("njk", "test/stubs").getCompiledTemplate( + let tr = await getNewTemplateRender("njk", "test/stubs"); + let fn = await tr.getCompiledTemplate( "{% extends 'base.njk' %}{% block content %}This is a child.{% endblock %}" ); t.is(await fn(), "

This is a child.

"); }); test("Nunjucks Render Relative Extends", async (t) => { - let fn = await getNewTemplateRender( + let tr = await getNewTemplateRender( "./test/stubs/njk-relative/dir/does_not_exist_and_thats_ok.njk", "test/stubs" - ).getCompiledTemplate( + ); + let fn = await tr.getCompiledTemplate( "{% extends '../dir/base.njk' %}{% block content %}This is a child.{% endblock %}" ); t.is(await fn(), "

This is a child.

"); }); test("Nunjucks Render Include", async (t) => { - let fn = await getNewTemplateRender("njk", "test/stubs").getCompiledTemplate( - "

{% include 'included.njk' %}

" - ); + let tr = await getNewTemplateRender("njk", "test/stubs"); + let fn = await tr.getCompiledTemplate("

{% include 'included.njk' %}

"); t.is(await fn(), "

This is an include.

"); }); test("Nunjucks Render Include (different extension)", async (t) => { - let fn = await getNewTemplateRender("njk", "test/stubs").getCompiledTemplate( - "

{% include 'included.nunj' %}

" - ); + let tr = await getNewTemplateRender("njk", "test/stubs"); + let fn = await tr.getCompiledTemplate("

{% include 'included.nunj' %}

"); t.is(await fn(), "

Nunjabusiness

"); }); test("Nunjucks Render Include (different extension, subdir)", async (t) => { - let fn = await getNewTemplateRender("njk", "test/stubs").getCompiledTemplate( - "

{% include 'subfolder/included.nunj' %}

" - ); + let tr = await getNewTemplateRender("njk", "test/stubs"); + let fn = await tr.getCompiledTemplate("

{% include 'subfolder/included.nunj' %}

"); t.is(await fn(), "

Nunjabusiness2

"); }); test("Nunjucks Render Relative Include Issue #190", async (t) => { - let tr = getNewTemplateRender( + let tr = await getNewTemplateRender( "./test/stubs/njk-relative/does_not_exist_and_thats_ok.njk", "./test/stubs" ); - let fn = await tr.getCompiledTemplate( - "

{% include './dir/included.njk' %}

" - ); + let fn = await tr.getCompiledTemplate("

{% include './dir/included.njk' %}

"); t.is(await fn(), "

HELLO FROM THE OTHER SIDE.

"); }); test("Nunjucks Render Relative Include (using ..) Issue #190", async (t) => { - let tr = getNewTemplateRender( + let tr = await getNewTemplateRender( "./test/stubs/njk-relative/dir/does_not_exist_and_thats_ok.njk", "./test/stubs" ); - let fn = await tr.getCompiledTemplate( - "

{% include '../dir/included.njk' %}

" - ); + let fn = await tr.getCompiledTemplate("

{% include '../dir/included.njk' %}

"); t.is(await fn(), "

HELLO FROM THE OTHER SIDE.

"); // should look in _includes too, related to Issue #633 - let fn2a = await tr.getCompiledTemplate( - "

{% include 'included-relative.njk' %}

" - ); + let fn2a = await tr.getCompiledTemplate("

{% include 'included-relative.njk' %}

"); t.is(await fn2a(), "

akdlsjafkljdskl

"); // should look in _includes too Issue #633 @@ -114,13 +110,11 @@ test("Nunjucks Render Relative Include (using ..) Issue #190", async (t) => { }); test("Nunjucks Render Relative Include (using current dir) Issue #190", async (t) => { - let tr = getNewTemplateRender( + let tr = await getNewTemplateRender( "./test/stubs/njk-relative/dir/does_not_exist_and_thats_ok.njk", "./test/stubs" ); - let fn = await tr.getCompiledTemplate( - "

{% include './included.njk' %}

" - ); + let fn = await tr.getCompiledTemplate("

{% include './included.njk' %}

"); t.is(await fn(), "

HELLO FROM THE OTHER SIDE.

"); // This fails because ./ doesn’t look in _includes (this is good) @@ -131,7 +125,7 @@ test("Nunjucks Render Relative Include (using current dir) Issue #190", async (t }); test("Nunjucks Render Relative Include (ambiguous path, file exists in _includes and in current dir) Issue #190", async (t) => { - let tr = getNewTemplateRender( + let tr = await getNewTemplateRender( "./test/stubs/njk-relative/dir/does_not_exist_and_thats_ok.njk", "./test/stubs" ); @@ -151,7 +145,7 @@ test("Nunjucks Render Relative Include (ambiguous path, file exists in _includes }); test("Nunjucks Async Filter", async (t) => { - let tr = getNewTemplateRender("njk", "test/stubs"); + let tr = await getNewTemplateRender("njk", "test/stubs"); let engine = tr.engine; engine.addFilters( { @@ -168,21 +162,19 @@ test("Nunjucks Async Filter", async (t) => { }); test("Nunjucks Render set with a filter", async (t) => { - let tr = getNewTemplateRender("njk", "test/stubs"); + let tr = await getNewTemplateRender("njk", "test/stubs"); let engine = tr.engine; engine.addFilters({ uppercase: function (str) { return str.toUpperCase(); }, }); - let fn = await tr.getCompiledTemplate( - `{% set test = "hi" | uppercase %}{{ test }}` - ); + let fn = await tr.getCompiledTemplate(`{% set test = "hi" | uppercase %}{{ test }}`); t.is((await fn()).trim(), `HI`); }); test("Nunjucks Render Include a JS file (Issue 398)", async (t) => { - let tr = getNewTemplateRender("njk", "test/stubs"); + let tr = await getNewTemplateRender("njk", "test/stubs"); let engine = tr.engine; engine.addFilters({ jsmin: function (str) { @@ -196,62 +188,59 @@ test("Nunjucks Render Include a JS file (Issue 398)", async (t) => { }); test("Nunjucks Render Include Subfolder", async (t) => { - let fn = await getNewTemplateRender("njk", "test/stubs").getCompiledTemplate( - "

{% include 'subfolder/included.html' %}

" - ); + let tr = await getNewTemplateRender("njk", "test/stubs"); + let fn = await tr.getCompiledTemplate("

{% include 'subfolder/included.html' %}

"); t.is(await fn(), "

This is an include.

"); }); test("Nunjucks Render Include Double Quotes", async (t) => { - let fn = await getNewTemplateRender("njk", "test/stubs").getCompiledTemplate( - `

{% include "included.njk" %}

` - ); + let tr = await getNewTemplateRender("njk", "test/stubs"); + let fn = await tr.getCompiledTemplate(`

{% include "included.njk" %}

`); t.is(await fn(), "

This is an include.

"); }); test("Nunjucks Render Include Subfolder Double Quotes", async (t) => { - let fn = await getNewTemplateRender("njk", "test/stubs").getCompiledTemplate( - `

{% include "subfolder/included.html" %}

` - ); + let tr = await getNewTemplateRender("njk", "test/stubs"); + let fn = await tr.getCompiledTemplate(`

{% include "subfolder/included.html" %}

`); t.is(await fn(), "

This is an include.

"); }); test("Nunjucks Render Imports", async (t) => { - let fn = await getNewTemplateRender("njk", "test/stubs").getCompiledTemplate( + let tr = await getNewTemplateRender("njk", "test/stubs"); + let fn = await tr.getCompiledTemplate( "{% import 'imports.njk' as forms %}
{{ forms.label('Name') }}
" ); t.is(await fn(), "
"); }); test("Nunjucks Render Relative Imports", async (t) => { - let fn = await getNewTemplateRender( + let tr = await getNewTemplateRender( "./test/stubs/njk-relative/dir/does_not_exist_and_thats_ok.njk", "test/stubs" - ).getCompiledTemplate( + ); + let fn = await tr.getCompiledTemplate( "{% import '../dir/imports.njk' as forms %}
{{ forms.label('Name') }}
" ); t.is(await fn(), "
"); }); test("Nunjucks Render Imports From", async (t) => { - let fn = await getNewTemplateRender("njk", "test/stubs").getCompiledTemplate( + let tr = await getNewTemplateRender("njk", "test/stubs"); + let fn = await tr.getCompiledTemplate( "{% from 'imports.njk' import label %}
{{ label('Name') }}
" ); t.is(await fn(), "
"); }); test("Nunjucks getEngineLib", async (t) => { - let tr = getNewTemplateRender("njk", "./test/stubs/"); + let tr = await getNewTemplateRender("njk", "./test/stubs/"); t.truthy(tr.engine.getEngineLib()); }); test("Nunjucks Render: with Library Override", async (t) => { - let tr = getNewTemplateRender("njk"); + let tr = await getNewTemplateRender("njk"); - let lib = require("nunjucks"); - let env = new lib.Environment( - new lib.FileSystemLoader("./test/stubs/_includes/") - ); + let env = new Nunjucks.Environment(new Nunjucks.FileSystemLoader("./test/stubs/_includes/")); tr.engine.setLibrary(env); let fn = await tr.getCompiledTemplate("

{{ name }}

"); @@ -259,33 +248,29 @@ test("Nunjucks Render: with Library Override", async (t) => { }); test("Nunjucks Render with getGlobals Issue #567", async (t) => { - let tr = getNewTemplateRender("njk"); + let tr = await getNewTemplateRender("njk"); let env = tr.engine.getEngineLib(); env.addGlobal("getGlobals", function () { return this.getVariables(); }); - let fn = await tr.getCompiledTemplate( - "

{{ getGlobals()['my-global-name'] }}

" - ); + let fn = await tr.getCompiledTemplate("

{{ getGlobals()['my-global-name'] }}

"); t.is(await fn({ "my-global-name": "Zach" }), "

Zach

"); }); test("Nunjucks Render with getVarFromString Filter Issue #567", async (t) => { - let tr = getNewTemplateRender("njk"); + let tr = await getNewTemplateRender("njk"); let env = tr.engine.getEngineLib(); env.addFilter("getVarFromString", function (varName) { return this.getVariables()[varName]; }); - let fn = await tr.getCompiledTemplate( - "

{{ 'my-global-name' | getVarFromString }}

" - ); + let fn = await tr.getCompiledTemplate("

{{ 'my-global-name' | getVarFromString }}

"); t.is(await fn({ "my-global-name": "Zach" }), "

Zach

"); }); test("Nunjucks Shortcode without args", async (t) => { - let tr = getNewTemplateRender("njk", "./test/stubs/"); + let tr = await getNewTemplateRender("njk", "./test/stubs/"); tr.engine.addShortcode("postfixWithZach", function () { return "Zach"; }); @@ -296,7 +281,7 @@ test("Nunjucks Shortcode without args", async (t) => { test("Nunjucks Shortcode", async (t) => { t.plan(3); - let tr = getNewTemplateRender("njk", "./test/stubs/"); + let tr = await getNewTemplateRender("njk", "./test/stubs/"); tr.engine.addShortcode("postfixWithZach", function (str) { // Data in context t.is(this.page.url, "/hi/"); @@ -320,7 +305,7 @@ test("Nunjucks Shortcode", async (t) => { test("Nunjucks Async Shortcode", async (t) => { t.plan(2); - let tr = getNewTemplateRender("njk", "./test/stubs/"); + let tr = await getNewTemplateRender("njk", "./test/stubs/"); tr.engine.addShortcode( "postfixWithZach", function (str) { @@ -350,7 +335,7 @@ test("Nunjucks Async Shortcode", async (t) => { test("Nunjucks Async function Shortcode", async (t) => { t.plan(2); - let tr = getNewTemplateRender("njk", "./test/stubs/"); + let tr = await getNewTemplateRender("njk", "./test/stubs/"); tr.engine.addShortcode( "postfixWithZach", async function (str) { @@ -374,13 +359,11 @@ test("Nunjucks Async function Shortcode", async (t) => { }); test("Nunjucks Async function Shortcode (with sync function, error throwing)", async (t) => { - let tr = getNewTemplateRender("njk", "./test/stubs/"); + let tr = await getNewTemplateRender("njk", "./test/stubs/"); tr.engine.addShortcode( "postfixWithZach", function (str) { - throw new Error( - "Nunjucks Async function Shortcode (with sync function, error throwing)" - ); + throw new Error("Nunjucks Async function Shortcode (with sync function, error throwing)"); }, true ); @@ -396,13 +379,11 @@ test("Nunjucks Async function Shortcode (with sync function, error throwing)", a }); test("Nunjucks Async function Shortcode (with async function, error throwing)", async (t) => { - let tr = getNewTemplateRender("njk", "./test/stubs/"); + let tr = await getNewTemplateRender("njk", "./test/stubs/"); tr.engine.addShortcode( "postfixWithZachError", async function (str) { - throw new Error( - "Nunjucks Async function Shortcode (with async function, error throwing)" - ); + throw new Error("Nunjucks Async function Shortcode (with async function, error throwing)"); }, true ); @@ -418,7 +399,7 @@ test("Nunjucks Async function Shortcode (with async function, error throwing)", }); test("Nunjucks Async function paired Shortcode (with sync function, error throwing)", async (t) => { - let tr = getNewTemplateRender("njk", "./test/stubs/"); + let tr = await getNewTemplateRender("njk", "./test/stubs/"); tr.engine.addPairedShortcode( "postfixWithZachError", function (str) { @@ -430,10 +411,9 @@ test("Nunjucks Async function paired Shortcode (with sync function, error throwi ); let error = await t.throwsAsync(async () => { - await tr._testRender( - "{% postfixWithZachError name %}hi{% endpostfixWithZachError %}", - { name: "test" } - ); + await tr._testRender("{% postfixWithZachError name %}hi{% endpostfixWithZachError %}", { + name: "test", + }); }); t.true( error.message.indexOf( @@ -443,7 +423,7 @@ test("Nunjucks Async function paired Shortcode (with sync function, error throwi }); test("Nunjucks Async function paired Shortcode (with async function, error throwing)", async (t) => { - let tr = getNewTemplateRender("njk", "./test/stubs/"); + let tr = await getNewTemplateRender("njk", "./test/stubs/"); tr.engine.addPairedShortcode( "postfixWithZachError", async function (str) { @@ -455,10 +435,9 @@ test("Nunjucks Async function paired Shortcode (with async function, error throw ); let error = await t.throwsAsync(async () => { - await tr._testRender( - "{% postfixWithZachError name %}hi{% endpostfixWithZachError %}", - { name: "test" } - ); + await tr._testRender("{% postfixWithZachError name %}hi{% endpostfixWithZachError %}", { + name: "test", + }); }); t.true( error.message.indexOf( @@ -470,7 +449,7 @@ test("Nunjucks Async function paired Shortcode (with async function, error throw test("Nunjucks Shortcode Safe Output", async (t) => { t.plan(2); - let tr = getNewTemplateRender("njk", "./test/stubs/"); + let tr = await getNewTemplateRender("njk", "./test/stubs/"); tr.engine.addShortcode("postfixWithZach", function (str) { // Data in context t.is(this.page.url, "/hi/"); @@ -490,7 +469,7 @@ test("Nunjucks Shortcode Safe Output", async (t) => { }); test("Nunjucks Shortcode return non-string value", async (t) => { - let tr = getNewTemplateRender("njk", "./test/stubs/"); + let tr = await getNewTemplateRender("njk", "./test/stubs/"); tr.engine.addShortcode("getYear", function () { return 2022; }); @@ -501,7 +480,7 @@ test("Nunjucks Shortcode return non-string value", async (t) => { test("Nunjucks Paired Shortcode", async (t) => { t.plan(2); - let tr = getNewTemplateRender("njk", "./test/stubs/"); + let tr = await getNewTemplateRender("njk", "./test/stubs/"); tr.engine.addPairedShortcode("postfixWithZach", function (content, str) { // Data in context t.is(this.page.url, "/hi/"); @@ -510,15 +489,12 @@ test("Nunjucks Paired Shortcode", async (t) => { }); t.is( - await tr._testRender( - "{% postfixWithZach name %}Content{% endpostfixWithZach %}", - { - name: "test", - page: { - url: "/hi/", - }, - } - ), + await tr._testRender("{% postfixWithZach name %}Content{% endpostfixWithZach %}", { + name: "test", + page: { + url: "/hi/", + }, + }), "testContentZach" ); }); @@ -526,7 +502,7 @@ test("Nunjucks Paired Shortcode", async (t) => { test("Nunjucks Async Paired Shortcode", async (t) => { t.plan(2); - let tr = getNewTemplateRender("njk", "./test/stubs/"); + let tr = await getNewTemplateRender("njk", "./test/stubs/"); tr.engine.addPairedShortcode( "postfixWithZach", function (content, str) { @@ -543,15 +519,12 @@ test("Nunjucks Async Paired Shortcode", async (t) => { ); t.is( - await tr._testRender( - "{% postfixWithZach name %}Content{% endpostfixWithZach %}", - { - name: "test", - page: { - url: "/hi/", - }, - } - ), + await tr._testRender("{% postfixWithZach name %}Content{% endpostfixWithZach %}", { + name: "test", + page: { + url: "/hi/", + }, + }), "testContentZach" ); }); @@ -559,7 +532,7 @@ test("Nunjucks Async Paired Shortcode", async (t) => { test("Nunjucks Nested Async Paired Shortcode", async (t) => { t.plan(3); - let tr = getNewTemplateRender("njk", "./test/stubs/"); + let tr = await getNewTemplateRender("njk", "./test/stubs/"); tr.engine.addPairedShortcode( "postfixWithZach", function (content, str) { @@ -591,7 +564,7 @@ test("Nunjucks Nested Async Paired Shortcode", async (t) => { }); test("Nunjucks Paired Shortcode without args", async (t) => { - let tr = getNewTemplateRender("njk", "./test/stubs/"); + let tr = await getNewTemplateRender("njk", "./test/stubs/"); tr.engine.addPairedShortcode("postfixWithZach", function (content) { // Data in context t.is(this.page.url, "/hi/"); @@ -600,15 +573,12 @@ test("Nunjucks Paired Shortcode without args", async (t) => { }); t.is( - await tr._testRender( - "{% postfixWithZach %}Content{% endpostfixWithZach %}", - { - name: "test", - page: { - url: "/hi/", - }, - } - ), + await tr._testRender("{% postfixWithZach %}Content{% endpostfixWithZach %}", { + name: "test", + page: { + url: "/hi/", + }, + }), "ContentZach" ); }); @@ -616,7 +586,7 @@ test("Nunjucks Paired Shortcode without args", async (t) => { test("Nunjucks Paired Shortcode with Tag Inside", async (t) => { t.plan(2); - let tr = getNewTemplateRender("njk", "./test/stubs/"); + let tr = await getNewTemplateRender("njk", "./test/stubs/"); tr.engine.addPairedShortcode("postfixWithZach", function (content, str) { // Data in context t.is(this.page.url, "/hi/"); @@ -642,7 +612,7 @@ test("Nunjucks Paired Shortcode with Tag Inside", async (t) => { test("Nunjucks Nested Paired Shortcode", async (t) => { t.plan(3); - let tr = getNewTemplateRender("njk", "./test/stubs/"); + let tr = await getNewTemplateRender("njk", "./test/stubs/"); tr.engine.addPairedShortcode("postfixWithZach", function (content, str) { // Data in context t.is(this.page.url, "/hi/"); @@ -668,7 +638,7 @@ test("Nunjucks Nested Paired Shortcode", async (t) => { test("Nunjucks Shortcode Multiple Args", async (t) => { t.plan(2); - let tr = getNewTemplateRender("njk", "./test/stubs/"); + let tr = await getNewTemplateRender("njk", "./test/stubs/"); tr.engine.addShortcode("postfixWithZach", function (str, str2) { // Data in context t.is(this.page.url, "/hi/"); @@ -689,7 +659,7 @@ test("Nunjucks Shortcode Multiple Args", async (t) => { }); test("Nunjucks Shortcode Multiple Args (Comma is required)", async (t) => { - let tr = getNewTemplateRender("njk", "./test/stubs/"); + let tr = await getNewTemplateRender("njk", "./test/stubs/"); tr.engine.addShortcode("postfixWithZach", function (str, str2) { return str + str2 + "Zach"; }); @@ -705,7 +675,7 @@ test("Nunjucks Shortcode Multiple Args (Comma is required)", async (t) => { test("Nunjucks Shortcode Named Args", async (t) => { t.plan(2); - let tr = getNewTemplateRender("njk", "./test/stubs/"); + let tr = await getNewTemplateRender("njk", "./test/stubs/"); tr.engine.addShortcode("postfixWithZach", function (arg) { // Data in context t.is(this.page.url, "/hi/"); @@ -728,7 +698,7 @@ test("Nunjucks Shortcode Named Args", async (t) => { test("Nunjucks Shortcode Named Args (Reverse Order)", async (t) => { t.plan(2); - let tr = getNewTemplateRender("njk", "./test/stubs/"); + let tr = await getNewTemplateRender("njk", "./test/stubs/"); tr.engine.addShortcode("postfixWithZach", function (arg) { // Data in context t.is(this.page.url, "/hi/"); @@ -751,7 +721,7 @@ test("Nunjucks Shortcode Named Args (Reverse Order)", async (t) => { test("Nunjucks Shortcode Named Args (JS notation)", async (t) => { t.plan(2); - let tr = getNewTemplateRender("njk", "./test/stubs/"); + let tr = await getNewTemplateRender("njk", "./test/stubs/"); tr.engine.addShortcode("postfixWithZach", function (arg) { // Data in context t.is(this.page.url, "/hi/"); @@ -772,7 +742,7 @@ test("Nunjucks Shortcode Named Args (JS notation)", async (t) => { }); test("Nunjucks Test if statements on arrays (Issue #524)", async (t) => { - let tr = getNewTemplateRender("njk", "./test/stubs/"); + let tr = await getNewTemplateRender("njk", "./test/stubs/"); t.is( await tr._testRender("{% if 'first' in tags %}Success.{% endif %}", { @@ -782,22 +752,16 @@ test("Nunjucks Test if statements on arrays (Issue #524)", async (t) => { ); t.is( - await tr._testRender( - "{% if 'sdfsdfs' in tags %}{% else %}Success.{% endif %}", - { - tags: ["first", "second"], - } - ), + await tr._testRender("{% if 'sdfsdfs' in tags %}{% else %}Success.{% endif %}", { + tags: ["first", "second"], + }), "Success." ); t.is( - await tr._testRender( - "{% if false %}{% elseif 'first' in tags %}Success.{% endif %}", - { - tags: ["first", "second"], - } - ), + await tr._testRender("{% if false %}{% elseif 'first' in tags %}Success.{% endif %}", { + tags: ["first", "second"], + }), "Success." ); @@ -809,29 +773,23 @@ test("Nunjucks Test if statements on arrays (Issue #524)", async (t) => { ); t.is( - await tr._testRender( - "{% if tags.includes('dsds') %}{% else %}Success.{% endif %}", - { - tags: ["first", "second"], - } - ), + await tr._testRender("{% if tags.includes('dsds') %}{% else %}Success.{% endif %}", { + tags: ["first", "second"], + }), "Success." ); t.is( - await tr._testRender( - "{% if false %}{% elseif tags.includes('first') %}Success.{% endif %}", - { - tags: ["first", "second"], - } - ), + await tr._testRender("{% if false %}{% elseif tags.includes('first') %}Success.{% endif %}", { + tags: ["first", "second"], + }), "Success." ); }); test("Issue 611: Run a function", async (t) => { // This does not work in Liquid - let tr = getNewTemplateRender("njk", "./test/stubs/"); + let tr = await getNewTemplateRender("njk", "./test/stubs/"); t.is( await tr._testRender("{{ test() }}", { @@ -844,7 +802,7 @@ test("Issue 611: Run a function", async (t) => { }); test("Nunjucks bypass compilation", async (t) => { - let tr = getNewTemplateRender("njk"); + let tr = await getNewTemplateRender("njk"); t.is(tr.engine.needsCompilation("

{{ me }}

"), true); t.is(tr.engine.needsCompilation("

{% tag %}{% endtag %}

"), true); @@ -852,7 +810,7 @@ test("Nunjucks bypass compilation", async (t) => { }); test("Nunjucks Parse for Symbols", async (t) => { - let tr = getNewTemplateRender("njk"); + let tr = await getNewTemplateRender("njk"); let engine = tr.engine; t.deepEqual(engine.parseForSymbols("

{{ name }}

"), ["name"]); @@ -860,21 +818,13 @@ test("Nunjucks Parse for Symbols", async (t) => { "eleventy.deep.nested", ]); t.deepEqual(engine.parseForSymbols("

{{ a }} {{ b }}

"), ["a", "b"]); - t.deepEqual( - engine.parseForSymbols("

{% if true %}{{ c }}{% endif %}

"), - ["c"] - ); - t.deepEqual( - engine.parseForSymbols("

{% if false %}{{ c }}{% endif %}

"), - ["c"] - ); + t.deepEqual(engine.parseForSymbols("

{% if true %}{{ c }}{% endif %}

"), ["c"]); + t.deepEqual(engine.parseForSymbols("

{% if false %}{{ c }}{% endif %}

"), ["c"]); t.deepEqual(engine.parseForSymbols("{{ collections.all[0] }}>"), [ // Note that the Liquid parser returns collections.all[0] "collections.all", ]); - t.deepEqual(engine.parseForSymbols("{{ collections.mine }}>"), [ - "collections.mine", - ]); + t.deepEqual(engine.parseForSymbols("{{ collections.mine }}>"), ["collections.mine"]); t.deepEqual(engine.parseForSymbols("{{ collections.mine | test }}>"), [ // TODO not ideal to have `test` in here? @@ -884,7 +834,7 @@ test("Nunjucks Parse for Symbols", async (t) => { }); test("Nunjucks Parse for Symbols with custom block", async (t) => { - let tr = getNewTemplateRender("njk"); + let tr = await getNewTemplateRender("njk"); let engine = tr.engine; engine.config.nunjucksShortcodes.test = function () {}; @@ -896,8 +846,9 @@ test("Use addNunjucksGlobal with function", async (t) => { templateConfig.userConfig.addNunjucksGlobal("fortytwo", function () { return 42; }); + await templateConfig.init(); - let tr = getNewTemplateRender("njk", null, templateConfig); + let tr = await getNewTemplateRender("njk", null, templateConfig); let fn = await tr.getCompiledTemplate("

{{ fortytwo() }}

"); t.is(await fn(), "

42

"); @@ -906,8 +857,9 @@ test("Use addNunjucksGlobal with function", async (t) => { test("Use addNunjucksGlobal with literal", async (t) => { let templateConfig = new TemplateConfig(); templateConfig.userConfig.addNunjucksGlobal("fortytwo", 42); + await templateConfig.init(); - let tr = getNewTemplateRender("njk", null, templateConfig); + let tr = await getNewTemplateRender("njk", null, templateConfig); let fn = await tr.getCompiledTemplate("

{{ fortytwo }}

"); t.is(await fn(), "

42

"); @@ -917,8 +869,9 @@ test("Use addNunjucksGlobal with literal", async (t) => { test.skip("Use addNunjucksGlobal with async function", async (t) => { let templateConfig = new TemplateConfig(); templateConfig.userConfig.addNunjucksGlobal("fortytwo", getPromise(42)); + await templateConfig.init(); - let tr = getNewTemplateRender("njk", null, templateConfig); + let tr = await getNewTemplateRender("njk", null, templateConfig); let fn = await tr.getCompiledTemplate("

{{ fortytwo() }}

"); t.is(await fn(), "

42

"); @@ -929,8 +882,9 @@ test("Use config driven Nunjucks Environment Options (throws on undefined variab templateConfig.userConfig.setNunjucksEnvironmentOptions({ throwOnUndefined: true, }); + await templateConfig.init(); - let tr = getNewTemplateRender("njk", null, templateConfig); + let tr = await getNewTemplateRender("njk", null, templateConfig); let fn = await tr.getCompiledTemplate("

{{ test }}

"); await t.throwsAsync(async () => { @@ -943,8 +897,9 @@ test("Use config driven Nunjucks Environment Options (autoescape)", async (t) => templateConfig.userConfig.setNunjucksEnvironmentOptions({ autoescape: false, }); + await templateConfig.init(); - let tr = getNewTemplateRender("njk", null, templateConfig); + let tr = await getNewTemplateRender("njk", null, templateConfig); let fn = await tr.getCompiledTemplate("

{{ test }}

"); t.is( @@ -957,18 +912,12 @@ test("Use config driven Nunjucks Environment Options (autoescape)", async (t) => test("Nunjucks Shortcode in a loop (everything is sync)", async (t) => { let templateConfig = new TemplateConfig(); - templateConfig.userConfig.addNunjucksShortcode( - "genericshortcode", - function (str) { - return str; - } - ); + templateConfig.userConfig.addNunjucksShortcode("genericshortcode", function (str) { + return str; + }); + await templateConfig.init(); - let tr = getNewTemplateRender( - "njk", - "./test/stubs-njk-async/", - templateConfig - ); + let tr = await getNewTemplateRender("njk", "./test/stubs-njk-async/", templateConfig); let fn = await tr.getCompiledTemplate( "{% for item in list %}{% include 'loop.njk' %}{% endfor %}" @@ -985,18 +934,12 @@ test("Nunjucks Shortcode in a loop (everything is sync)", async (t) => { // TODO! test.skip("Weird issue with number arguments in a loop (not parsing literals properly?)", async (t) => { let templateConfig = new TemplateConfig(); - templateConfig.userConfig.addNunjucksShortcode( - "genericshortcode", - function (str) { - return str; - } - ); + templateConfig.userConfig.addNunjucksShortcode("genericshortcode", function (str) { + return str; + }); + await templateConfig.init(); - let tr = getNewTemplateRender( - "njk", - "./test/stubs-njk-async/", - templateConfig - ); + let tr = await getNewTemplateRender("njk", "./test/stubs-njk-async/", templateConfig); let fn = await tr.getCompiledTemplate( "{% for item in list %}{{item}}-{% genericshortcode item %}{% endfor %}" ); @@ -1053,13 +996,12 @@ test("Use a precompiled Nunjucks template", async (t) => { }; })(), }); + await templateConfig.init(); - let tr = getNewTemplateRender("njk", null, templateConfig); + let tr = await getNewTemplateRender("njk", null, templateConfig); // Just pass a unique key in here if you’re using precompiled templates via config. - let fn = await tr.getCompiledTemplate( - "RenderDirect:BQAPaWxMHTxOqfCSB_bEoWTvtWt-obPbnZTUznRl9LA" - ); + let fn = await tr.getCompiledTemplate("RenderDirect:BQAPaWxMHTxOqfCSB_bEoWTvtWt-obPbnZTUznRl9LA"); t.is( normalizeNewLines( await fn({ @@ -1077,8 +1019,9 @@ test("Make sure addFilter is async-friendly for Nunjucks", async (t) => { templateConfig.userConfig.addFilter("fortytwo", async function (val, val2) { return getPromise(val + val2); }); + await templateConfig.init(); - let tr = getNewTemplateRender("njk", null, templateConfig); + let tr = await getNewTemplateRender("njk", null, templateConfig); let fn = await tr.getCompiledTemplate("

{{ 10 | fortytwo(2) }}

"); t.is(await fn(), "

12

"); @@ -1090,8 +1033,9 @@ test("Throw an error when you return a promise in addFilter for Nunjucks", async templateConfig.userConfig.addFilter("fortytwo", function () { return getPromise(42); }); + await templateConfig.init(); - let tr = getNewTemplateRender("njk", null, templateConfig); + let tr = await getNewTemplateRender("njk", null, templateConfig); let fn = await tr.getCompiledTemplate("

{{ 'hi' | fortytwo }}

"); await t.throwsAsync(fn); }); @@ -1102,8 +1046,9 @@ test("addAsyncFilter for Nunjucks", async (t) => { templateConfig.userConfig.addAsyncFilter("fortytwo", function (val, val2) { return getPromise(val + val2); }); + await templateConfig.init(); - let tr = getNewTemplateRender("njk", null, templateConfig); + let tr = await getNewTemplateRender("njk", null, templateConfig); let fn = await tr.getCompiledTemplate("

{{ 10 | fortytwo(2) }}

"); t.is(await fn(), "

12

"); @@ -1121,8 +1066,9 @@ test("Asynchronous filters (via addNunjucksFilter) for Nunjucks", async (t) => { }, true ); + await templateConfig.init(); - let tr = getNewTemplateRender("njk", null, templateConfig); + let tr = await getNewTemplateRender("njk", null, templateConfig); let fn = await tr.getCompiledTemplate("

{{ 10 | fortytwo(2) }}

"); t.is(await fn(), "

12

"); @@ -1131,16 +1077,14 @@ test("Asynchronous filters (via addNunjucksFilter) for Nunjucks", async (t) => { test("Asynchronous filters (via addNunjucksAsyncFilter) for Nunjucks", async (t) => { let templateConfig = new TemplateConfig(); // works without async function (can return promise) - templateConfig.userConfig.addNunjucksAsyncFilter( - "fortytwo", - function (value1, value2, callback) { - setTimeout(function () { - callback(null, value1 + value2); - }, 100); - } - ); + templateConfig.userConfig.addNunjucksAsyncFilter("fortytwo", function (value1, value2, callback) { + setTimeout(function () { + callback(null, value1 + value2); + }, 100); + }); + await templateConfig.init(); - let tr = getNewTemplateRender("njk", null, templateConfig); + let tr = await getNewTemplateRender("njk", null, templateConfig); let fn = await tr.getCompiledTemplate("

{{ 10 | fortytwo(2) }}

"); t.is(await fn(), "

12

"); diff --git a/test/TemplateRenderPluginTest.js b/test/TemplateRenderPluginTest.js index f6bbfc3ab..39afcf898 100644 --- a/test/TemplateRenderPluginTest.js +++ b/test/TemplateRenderPluginTest.js @@ -1,14 +1,13 @@ -const test = require("ava"); -const RenderPlugin = require("../src/Plugins/RenderPlugin"); -const RenderManager = RenderPlugin.RenderManager; -const RenderPluginFile = RenderPlugin.File; -const RenderPluginString = RenderPlugin.String; +import test from "ava"; -const VuePlugin = require("@11ty/eleventy-plugin-vue"); - -const Eleventy = require("../src/Eleventy"); -const normalizeNewLines = require("./Util/normalizeNewLines"); -const removeNewLines = require("./Util/removeNewLines"); +import { + default as RenderPlugin, + File as RenderPluginFile, + String as RenderPluginString, + RenderManager, +} from "../src/Plugins/RenderPlugin.js"; +import Eleventy from "../src/Eleventy.js"; +import normalizeNewLines from "./Util/normalizeNewLines.js"; async function getTestOutput(input, configCallback = function () {}) { let elev = new Eleventy(input, "./_site/", { @@ -23,8 +22,6 @@ async function getTestOutput(input, configCallback = function () {}) { // Careful with this! // elev.disableLogger(); - await elev.init(); - let result = await elev.toJSON(); if (!result.length) { @@ -40,9 +37,7 @@ async function getTestOutputForFile(inputFile, configCallback) { } test("Use liquid in nunjucks", async (t) => { - let html = await getTestOutputForFile( - "./test/stubs-render-plugin/liquid.njk" - ); + let html = await getTestOutputForFile("./test/stubs-render-plugin/liquid.njk"); t.is( html, `nunjucksHi @@ -54,9 +49,7 @@ test("Use liquid in nunjucks", async (t) => { }); test("Use liquid+markdown in 11ty.js", async (t) => { - let html = await getTestOutputForFile( - "./test/stubs-render-plugin/liquid-md.11ty.js" - ); + let html = await getTestOutputForFile("./test/stubs-render-plugin/liquid-md.11ty.cjs"); t.is( html, `

Markdown

@@ -67,24 +60,18 @@ test("Use liquid+markdown in 11ty.js", async (t) => { }); test("Use nunjucks in 11ty.js", async (t) => { - let html = await getTestOutputForFile( - "./test/stubs-render-plugin/nunjucks.11ty.js" - ); + let html = await getTestOutputForFile("./test/stubs-render-plugin/nunjucks.11ty.cjs"); t.is(html, `* iHtpircsavaj`); }); // This is not yet supported and currently throws an error. test.skip("Use 11ty.js in liquid", async (t) => { - let html = await getTestOutputForFile( - "./test/stubs-render-plugin/11tyjs.liquid" - ); + let html = await getTestOutputForFile("./test/stubs-render-plugin/11tyjs.liquid"); t.is(html, `TESTING`); }); test("Use nunjucks in liquid", async (t) => { - let html = await getTestOutputForFile( - "./test/stubs-render-plugin/nunjucks.liquid" - ); + let html = await getTestOutputForFile("./test/stubs-render-plugin/nunjucks.liquid"); t.is( html, `* iHdiuqil @@ -103,47 +90,8 @@ test("Use markdown in liquid", async (t) => { ); }); -test("Use vue in liquid", async (t) => { - let html = await getTestOutputForFile( - "./test/stubs-render-plugin/vue.liquid", - function (eleventyConfig) { - eleventyConfig.addPlugin(VuePlugin); - } - ); - t.is(html, `
HELLO WE ARE VUEING

liquidHi

`); -}); - -test("Use vue SFC file in liquid", async (t) => { - // We point this to a directory instead of a single input file because the Eleventy Vue plugin needs - // to be able to find the Vue SFC files too (and won’t if we point to a single input vue file) - let result = await getTestOutput( - "./test/stubs-render-plugin-vue/", - function (eleventyConfig) { - eleventyConfig.addPlugin(VuePlugin); - } - ); - let html = normalizeNewLines(result[0].content.trim()); - t.is(html, `liquidHi`); -}); - -test("Use nunjucks file in liquid (uses renderTemplate inside of the nunjucks file)", async (t) => { - let html = await getTestOutputForFile( - "./test/stubs-render-plugin/njk-file.liquid" - ); - t.is( - html, - `TESTING - -TESTING IN LIQUID - -* 999` - ); -}); - test("Use nunjucks file in njk (uses renderTemplate inside of the nunjucks file)", async (t) => { - let html = await getTestOutputForFile( - "./test/stubs-render-plugin/njk-file.njk" - ); + let html = await getTestOutputForFile("./test/stubs-render-plugin/njk-file.njk"); t.is( html, `TESTING @@ -155,16 +103,13 @@ TESTING IN LIQUID }); test("Use 11ty.js file in njk", async (t) => { - let html = await getTestOutputForFile( - "./test/stubs-render-plugin/11tyjs-file.njk" - ); + let html = await getTestOutputForFile("./test/stubs-render-plugin/11tyjs-file.njk"); t.is(html, `TESTING`); }); -test("Use txt file in njk (override to 11ty.js)", async (t) => { - let html = await getTestOutputForFile( - "./test/stubs-render-plugin/11tyjs-file-override.njk" - ); +// 3.0 breaking change, we can’t alias to 11ty.js any more +test.skip("Breaking Change (3.0): Use txt file in njk (override to 11ty.js)", async (t) => { + let html = await getTestOutputForFile("./test/stubs-render-plugin/11tyjs-file-override.njk"); t.is(html, `TESTING`); }); @@ -172,16 +117,12 @@ test("Use txt file in njk (override to 11ty.js)", async (t) => { // which is not ideal. test.skip("Use nunjucks file in liquid but it doesn’t exist", async (t) => { await t.throwsAsync(async () => { - await getTestOutputForFile( - "./test/stubs-render-plugin/njk-file-not-exist.liquid" - ); + await getTestOutputForFile("./test/stubs-render-plugin/njk-file-not-exist.liquid"); }); }); test("No syntax passed, uses parent page syntax: liquid", async (t) => { - let html = await getTestOutputForFile( - "./test/stubs-render-plugin/false.liquid" - ); + let html = await getTestOutputForFile("./test/stubs-render-plugin/false.liquid"); t.is( html, `# Hello Bruno @@ -190,9 +131,7 @@ test("No syntax passed, uses parent page syntax: liquid", async (t) => { }); test("No syntax passed (uses parent page syntax), but does pass data: liquid", async (t) => { - let html = await getTestOutputForFile( - "./test/stubs-render-plugin/data-no-templatelang.liquid" - ); + let html = await getTestOutputForFile("./test/stubs-render-plugin/data-no-templatelang.liquid"); t.is( html, `# Hello Bruno @@ -202,50 +141,25 @@ test("No syntax passed (uses parent page syntax), but does pass data: liquid", a // Not yet supported test.skip("renderFile but the target has front matter.", async (t) => { - let html = await getTestOutputForFile( - "./test/stubs-render-plugin/using-frontmatter.liquid" - ); + let html = await getTestOutputForFile("./test/stubs-render-plugin/using-frontmatter.liquid"); t.is(html, `frontmatterString`); }); // Idea from https://twitter.com/raymondcamden/status/1460961620247650312 test("Capture nunjucks render output to a liquid variable", async (t) => { - let html = await getTestOutputForFile( - "./test/stubs-render-plugin/capture-njk.liquid" - ); + let html = await getTestOutputForFile("./test/stubs-render-plugin/capture-njk.liquid"); t.is(html, `4`); }); // Idea from https://twitter.com/raymondcamden/status/1460961620247650312 // Possibly blocked by async in {% set %} https://github.com/mozilla/nunjucks/issues/815 test("Capture liquid render output to a njk variable", async (t) => { - let html = await getTestOutputForFile( - "./test/stubs-render-plugin/capture-liquid.njk" - ); + let html = await getTestOutputForFile("./test/stubs-render-plugin/capture-liquid.njk"); t.is(html, `4`); }); -test("Using a Vue renderFile inside of serverPrefetch (or `data`): Vue -> Liquid -> Markdown -> Vue", async (t) => { - // We point this to a directory instead of a single input file because the Eleventy Vue plugin needs - // to be able to find the Vue SFC files too (and won’t if we point to a single input vue file) - let result = await getTestOutput( - "./test/stubs-render-plugin-vue-nested/", - function (eleventyConfig) { - eleventyConfig.addPlugin(VuePlugin); - } - ); - - let html = removeNewLines(result[0].content.trim()); - t.is( - html, - `

This is 1.

2

` - ); -}); - test("Remap non-object data to data._ if object is not passed in", async (t) => { - let html = await getTestOutputForFile( - "./test/stubs-render-plugin/bad-data.njk" - ); + let html = await getTestOutputForFile("./test/stubs-render-plugin/bad-data.njk"); t.is(html, "string"); }); @@ -330,17 +244,14 @@ tested. }); test("Direct use of render file plugin, rendering Nunjucks (and nested Liquid)", async (t) => { - let fn = await RenderPluginFile( - "./test/stubs-render-plugin/liquid-direct.njk", - { - config: function (eleventyConfig) { - eleventyConfig.addPlugin(RenderPlugin); - eleventyConfig.addFilter("testing", function () { - return "tested."; - }); - }, - } - ); + let fn = await RenderPluginFile("./test/stubs-render-plugin/liquid-direct.njk", { + config: function (eleventyConfig) { + eleventyConfig.addPlugin(RenderPlugin); + eleventyConfig.addFilter("testing", function () { + return "tested."; + }); + }, + }); let data = { hi: "liquidHi", argData: { @@ -362,49 +273,35 @@ tested. }); test("Use page in renderTemplate (liquid in liquid)", async (t) => { - let html = await getTestOutputForFile( - "./test/stubs-render-plugin/liquid-page.liquid" - ); + let html = await getTestOutputForFile("./test/stubs-render-plugin/liquid-page.liquid"); t.is(html, `/liquid-page/`); }); test("Use page in renderTemplate (liquid in njk)", async (t) => { - let html = await getTestOutputForFile( - "./test/stubs-render-plugin/liquid-page.njk" - ); + let html = await getTestOutputForFile("./test/stubs-render-plugin/liquid-page.njk"); t.is(html, `/liquid-page/`); }); test("Use page in renderTemplate (njk in liquid)", async (t) => { - let html = await getTestOutputForFile( - "./test/stubs-render-plugin/njk-page.liquid" - ); + let html = await getTestOutputForFile("./test/stubs-render-plugin/njk-page.liquid"); t.is(html, `/njk-page/`); }); test("Use eleventy in renderTemplate (njk in liquid)", async (t) => { - let html = await getTestOutputForFile( - "./test/stubs-render-plugin/njk-eleventy.liquid" - ); + let html = await getTestOutputForFile("./test/stubs-render-plugin/njk-eleventy.liquid"); t.is(html, `1`); }); test("Use eleventy in renderTemplate (liquid in njk)", async (t) => { - let html = await getTestOutputForFile( - "./test/stubs-render-plugin/liquid-eleventy.njk" - ); + let html = await getTestOutputForFile("./test/stubs-render-plugin/liquid-eleventy.njk"); t.is(html, `1`); }); test.skip("Use nunjucks in liquid (access to all global data)", async (t) => { - let html = await getTestOutputForFile( - "./test/stubs-render-plugin/nunjucks-global.liquid" - ); + let html = await getTestOutputForFile("./test/stubs-render-plugin/nunjucks-global.liquid"); t.is(html, `globalHi`); }); test.skip("Use liquid in njk (access to all global data)", async (t) => { - let html = await getTestOutputForFile( - "./test/stubs-render-plugin/liquid-global.njk" - ); + let html = await getTestOutputForFile("./test/stubs-render-plugin/liquid-global.njk"); t.is(html, `globalHi`); }); diff --git a/test/TemplateRenderPugTest.js b/test/TemplateRenderPugTest.js deleted file mode 100644 index d369ff481..000000000 --- a/test/TemplateRenderPugTest.js +++ /dev/null @@ -1,166 +0,0 @@ -const test = require("ava"); -const TemplateRender = require("../src/TemplateRender"); -const TemplateConfig = require("../src/TemplateConfig"); -const EleventyExtensionMap = require("../src/EleventyExtensionMap"); - -function getNewTemplateRender(name, inputDir, config) { - let eleventyConfig = config; - if (!eleventyConfig) { - eleventyConfig = new TemplateConfig(); - } - - let tr = new TemplateRender(name, inputDir, eleventyConfig); - tr.extensionMap = new EleventyExtensionMap([], eleventyConfig); - return tr; -} - -// Pug -test("Pug", (t) => { - t.is(getNewTemplateRender("pug").getEngineName(), "pug"); -}); - -test("Pug Render", async (t) => { - let fn = await getNewTemplateRender("pug").getCompiledTemplate("p= name"); - t.is(await fn({ name: "Zach" }), "

Zach

"); -}); - -test("Pug Render Include (Absolute)", async (t) => { - let fn = await getNewTemplateRender("pug", "./test/stubs/") - .getCompiledTemplate(`p - include /included.pug`); - t.is(await fn({ name: "Zach" }), "

This is an include.

"); -}); - -test("Pug Render Include with Data", async (t) => { - let fn = await getNewTemplateRender("pug", "./test/stubs/") - .getCompiledTemplate(`p - include /includedvar.pug`); - t.is(await fn({ name: "Zach" }), "

This is Zach.

"); -}); - -test("Pug Render Include with Data, inline var overrides data", async (t) => { - let fn = await getNewTemplateRender("pug", "./test/stubs/") - .getCompiledTemplate(` -- var name = "Bill"; -p - include /includedvar.pug`); - t.is(await fn({ name: "Zach" }), "

This is Bill.

"); -}); - -test("Pug Render Extends (Layouts)", async (t) => { - let fn = await getNewTemplateRender("pug", "./test/stubs/") - .getCompiledTemplate(`extends /layout.pug -block content - h1= name`); - t.is(await fn({ name: "Zach" }), "

Zach

"); -}); - -test("Pug Render Extends (Relative, Layouts)", async (t) => { - let fn = await getNewTemplateRender( - "./test/stubs/does_not_exist_and_thats_ok.pug", - "./test/stubs/" - ).getCompiledTemplate(`extends ./layout-relative.pug -block content - h1= name`); - t.is(await fn({ name: "Zach" }), "

Zach

"); -}); - -test("Pug Render Include (Relative)", async (t) => { - let fn = await getNewTemplateRender("pug", "./test/stubs/") - .getCompiledTemplate(`p - include _includes/included.pug`); - t.is(await fn({ name: "Zach" }), "

This is an include.

"); -}); - -test("Pug Render Include (Relative, again)", async (t) => { - let fn = await getNewTemplateRender( - "./test/stubs/does_not_exist_and_thats_ok.pug", - "./test/stubs/" - ).getCompiledTemplate(`p - include included.pug`); - t.is( - await fn({ name: "Zach" }), - "

This is a relative include.

" - ); -}); - -test("Pug Render Include (Relative, dot slash)", async (t) => { - let fn = await getNewTemplateRender( - "./test/stubs/does_not_exist_and_thats_ok.pug", - "./test/stubs/" - ).getCompiledTemplate(`p - include ./included.pug`); - t.is( - await fn({ name: "Zach" }), - "

This is a relative include.

" - ); -}); - -test("Pug Render Include (Relative, dot dot slash)", async (t) => { - let fn = await getNewTemplateRender( - "./test/stubs/dir/does_not_exist_and_thats_ok.pug", - "./test/stubs/" - ).getCompiledTemplate(`p - include ../included.pug`); - t.is( - await fn({ name: "Zach" }), - "

This is a relative include.

" - ); -}); - -test("Pug Options Overrides", async (t) => { - let cfg = new TemplateConfig(); - cfg.userConfig.setPugOptions({ - testoption: "testoverride", - }); - let tr = getNewTemplateRender("pug", "./test/stubs/", cfg); - - let options = tr.engine.getPugOptions(); - t.is(options.testoption, "testoverride"); -}); - -test("Pug getEngineLib", async (t) => { - let tr = getNewTemplateRender("pug", "./test/stubs/"); - t.truthy(tr.engine.getEngineLib()); -}); - -test("Pug Render: with Library Override", async (t) => { - let tr = getNewTemplateRender("pug"); - - let lib = require("pug"); - tr.engine.setLibrary(lib); - - let fn = await tr.getCompiledTemplate("p= name"); - t.is(await fn({ name: "Zach" }), "

Zach

"); -}); - -test("Pug Filter", async (t) => { - let cfg = new TemplateConfig(); - cfg.userConfig.setPugOptions({ - filters: { - makeUppercase: function (text, options) { - return text.toUpperCase(); - }, - }, - }); - - let tr = getNewTemplateRender("pug", "./test/stubs/", cfg); - - let fn = await tr.getCompiledTemplate(`p - :makeUppercase() - Zach -`); - t.is(await fn({ name: "Test" }), "

ZACH

"); -}); - -test("Pug Render with Function", async (t) => { - let fn = await getNewTemplateRender("pug").getCompiledTemplate("p= name()"); - t.is( - await fn({ - name: function () { - return "Zach2"; - }, - }), - "

Zach2

" - ); -}); diff --git a/test/TemplateRenderTest.js b/test/TemplateRenderTest.js index 8fd18dcf3..b496ee51e 100644 --- a/test/TemplateRenderTest.js +++ b/test/TemplateRenderTest.js @@ -1,39 +1,41 @@ -const test = require("ava"); -const TemplateRender = require("../src/TemplateRender"); -const TemplateConfig = require("../src/TemplateConfig"); -const EleventyExtensionMap = require("../src/EleventyExtensionMap"); +import test from "ava"; -function getNewTemplateRender(name, inputDir) { +import TemplateRender from "../src/TemplateRender.js"; +import TemplateConfig from "../src/TemplateConfig.js"; +import EleventyExtensionMap from "../src/EleventyExtensionMap.js"; + +async function getNewTemplateRender(name, inputDir) { let eleventyConfig = new TemplateConfig(); + await eleventyConfig.init(); + let tr = new TemplateRender(name, inputDir, eleventyConfig); tr.extensionMap = new EleventyExtensionMap([], eleventyConfig); + await tr.init(); return tr; } -test("Basic", (t) => { - t.throws(() => { - let tr = getNewTemplateRender("sldkjfkldsj"); +test("Basic", async (t) => { + await t.throwsAsync(async () => { + let tr = await getNewTemplateRender("sldkjfkldsj"); tr.init("sldkjfkldsj"); }); }); test("Includes Dir", async (t) => { - t.is( - getNewTemplateRender("ejs", "./test/stubs").getIncludesDir(), - "test/stubs/_includes" - ); + let tr = await getNewTemplateRender("liquid", "./test/stubs"); + t.is(tr.getIncludesDir(), "test/stubs/_includes"); }); test("Invalid override", async (t) => { - let tr = getNewTemplateRender("ejs", "./test/stubs"); - t.throws(() => { - tr.setEngineOverride("lslkdjf"); + let tr = await getNewTemplateRender("liquid", "./test/stubs"); + await t.throwsAsync(async () => { + await tr.setEngineOverride("lslkdjf"); }); }); test("Valid Override", async (t) => { - let tr = getNewTemplateRender("ejs", "./test/stubs"); - tr.setEngineOverride("njk"); + let tr = await getNewTemplateRender("liquid", "./test/stubs"); + await tr.setEngineOverride("njk"); t.is(tr.getEngineName(), "njk"); t.truthy(tr.isEngine("njk")); }); @@ -46,25 +48,22 @@ test("Parse Overrides to get Prioritized Engine List", async (t) => { t.deepEqual(TemplateRender.parseEngineOverrides("html"), []); t.deepEqual(TemplateRender.parseEngineOverrides("html,html"), []); t.deepEqual(TemplateRender.parseEngineOverrides("html,md,md"), ["md"]); - t.deepEqual(TemplateRender.parseEngineOverrides("ejs,md"), ["md", "ejs"]); - t.deepEqual(TemplateRender.parseEngineOverrides("ejs"), ["ejs"]); + t.deepEqual(TemplateRender.parseEngineOverrides("liquid,md"), ["md", "liquid"]); + t.deepEqual(TemplateRender.parseEngineOverrides("liquid"), ["liquid"]); t.deepEqual(TemplateRender.parseEngineOverrides("njk"), ["njk"]); - t.deepEqual(TemplateRender.parseEngineOverrides("ejs,html"), ["ejs"]); - t.deepEqual(TemplateRender.parseEngineOverrides("ejs,md,html"), [ - "md", - "ejs", - ]); + t.deepEqual(TemplateRender.parseEngineOverrides("liquid,html"), ["liquid"]); + t.deepEqual(TemplateRender.parseEngineOverrides("liquid,md,html"), ["md", "liquid"]); t.deepEqual(TemplateRender.parseEngineOverrides("njk,njk"), ["njk"]); t.throws(function () { - TemplateRender.parseEngineOverrides("njk,ejs"); + TemplateRender.parseEngineOverrides("njk,liquid"); }); t.throws(function () { - TemplateRender.parseEngineOverrides("ejs,njk,html"); + TemplateRender.parseEngineOverrides("liquid,njk,html"); }); }); test("Make sure getEnginesList returns a string", async (t) => { - let tr = getNewTemplateRender("liquid", "./test/stubs"); + let tr = await getNewTemplateRender("liquid", "./test/stubs"); t.is(tr.getEnginesList("njk,md"), "njk,md"); }); diff --git a/test/TemplateTest-CompileOptions.js b/test/TemplateTest-CompileOptions.js index 841417912..a2a8a0dff 100644 --- a/test/TemplateTest-CompileOptions.js +++ b/test/TemplateTest-CompileOptions.js @@ -1,9 +1,8 @@ -const test = require("ava"); +import test from "ava"; -const TemplateConfig = require("../src/TemplateConfig"); -const TemplateData = require("../src/TemplateData"); - -const getNewTemplate = require("./_getNewTemplateForTests"); +import TemplateConfig from "../src/TemplateConfig.js"; +import TemplateData from "../src/TemplateData.js"; +import getNewTemplate from "./_getNewTemplateForTests.js"; test("Custom extension (.txt) with custom permalink compile function", async (t) => { let eleventyConfig = new TemplateConfig(); @@ -28,9 +27,10 @@ test("Custom extension (.txt) with custom permalink compile function", async (t) }; }, }); + await eleventyConfig.init(); let dataObj = new TemplateData("./test/stubs/", eleventyConfig); - let tmpl = getNewTemplate( + let tmpl = await getNewTemplate( "./test/stubs/custom-extension.txt", "./test/stubs/", "dist", @@ -63,9 +63,10 @@ test("Custom extension with and compileOptions.permalink = false", async (t) => }; }, }); + await eleventyConfig.init(); let dataObj = new TemplateData("./test/stubs/", eleventyConfig); - let tmpl = getNewTemplate( + let tmpl = await getNewTemplate( "./test/stubs/custom-extension.txt", "./test/stubs/", "dist", @@ -98,9 +99,10 @@ test("Custom extension with and opt-out of permalink compilation", async (t) => }; }, }); + await eleventyConfig.init(); let dataObj = new TemplateData("./test/stubs/", eleventyConfig); - let tmpl = getNewTemplate( + let tmpl = await getNewTemplate( "./test/stubs/custom-extension.txt", "./test/stubs/", "dist", @@ -141,9 +143,10 @@ test("Custom extension (.txt) with custom permalink compile function but no perm }; }, }); + await eleventyConfig.init(); let dataObj = new TemplateData("./test/stubs/", eleventyConfig); - let tmpl = getNewTemplate( + let tmpl = await getNewTemplate( "./test/stubs/custom-extension-no-permalink.txt", "./test/stubs/", "dist", @@ -182,9 +185,10 @@ test("Custom extension (.txt) with custom permalink compile function (that retur }; }, }); + await eleventyConfig.init(); let dataObj = new TemplateData("./test/stubs/", eleventyConfig); - let tmpl = getNewTemplate( + let tmpl = await getNewTemplate( "./test/stubs/custom-extension-no-permalink.txt", "./test/stubs/", "dist", @@ -223,9 +227,10 @@ test("Custom extension (.txt) with custom permalink compile function that return }; }, }); + await eleventyConfig.init(); let dataObj = new TemplateData("./test/stubs/", eleventyConfig); - let tmpl = getNewTemplate( + let tmpl = await getNewTemplate( "./test/stubs/custom-extension-no-permalink.txt", "./test/stubs/", "dist", @@ -257,9 +262,10 @@ test("Custom extension (.txt) that returns undefined from compile", async (t) => }; }, }); + await eleventyConfig.init(); let dataObj = new TemplateData("./test/stubs/", eleventyConfig); - let tmpl = getNewTemplate( + let tmpl = await getNewTemplate( "./test/stubs/custom-extension-no-permalink.txt", "./test/stubs/", "dist", diff --git a/test/TemplateTest-ComputedData.js b/test/TemplateTest-ComputedData.js index bcf7a4b57..b60fc87c6 100644 --- a/test/TemplateTest-ComputedData.js +++ b/test/TemplateTest-ComputedData.js @@ -1,7 +1,8 @@ -const test = require("ava"); -const TemplateData = require("../src/TemplateData"); -const getNewTemplate = require("./_getNewTemplateForTests"); -const TemplateConfig = require("../src/TemplateConfig"); +import test from "ava"; + +import TemplateData from "../src/TemplateData.js"; +import TemplateConfig from "../src/TemplateConfig.js"; +import getNewTemplate from "./_getNewTemplateForTests.js"; async function getRenderedData(tmpl, pageNumber = 0) { let data = await tmpl.getData(); @@ -10,7 +11,7 @@ async function getRenderedData(tmpl, pageNumber = 0) { } test("eleventyComputed", async (t) => { - let tmpl = getNewTemplate( + let tmpl = await getNewTemplate( "./test/stubs/eleventyComputed/first.njk", "./test/stubs/", "./dist" @@ -20,7 +21,7 @@ test("eleventyComputed", async (t) => { }); test("eleventyComputed overrides existing value.", async (t) => { - let tmpl = getNewTemplate( + let tmpl = await getNewTemplate( "./test/stubs/eleventyComputed/override.njk", "./test/stubs/", "./dist" @@ -31,7 +32,7 @@ test("eleventyComputed overrides existing value.", async (t) => { }); test("eleventyComputed overrides existing value and reuses that upstream value", async (t) => { - let tmpl = getNewTemplate( + let tmpl = await getNewTemplate( "./test/stubs/eleventyComputed/override-reuse.njk", "./test/stubs/", "./dist" @@ -42,7 +43,7 @@ test("eleventyComputed overrides existing value and reuses that upstream value", }); test("eleventyComputed permalink", async (t) => { - let tmpl = getNewTemplate( + let tmpl = await getNewTemplate( "./test/stubs/eleventyComputed/permalink.njk", "./test/stubs/", "./dist" @@ -58,7 +59,7 @@ test("eleventyComputed permalink", async (t) => { }); test("eleventyComputed simple permalink", async (t) => { - let tmpl = getNewTemplate( + let tmpl = await getNewTemplate( "./test/stubs/eleventyComputed/permalink-simple.njk", "./test/stubs/", "./dist" @@ -71,7 +72,7 @@ test("eleventyComputed simple permalink", async (t) => { }); test("eleventyComputed permalink using slug", async (t) => { - let tmpl = getNewTemplate( + let tmpl = await getNewTemplate( "./test/stubs/eleventyComputed/permalink-slug.njk", "./test/stubs/", "./dist" @@ -84,7 +85,7 @@ test("eleventyComputed permalink using slug", async (t) => { }); test("eleventyComputed js front matter (function)", async (t) => { - let tmpl = getNewTemplate( + let tmpl = await getNewTemplate( "./test/stubs/eleventyComputed/second.njk", "./test/stubs/", "./dist" @@ -95,7 +96,7 @@ test("eleventyComputed js front matter (function)", async (t) => { }); test("eleventyComputed js front matter key reuses and overrides", async (t) => { - let tmpl = getNewTemplate( + let tmpl = await getNewTemplate( "./test/stubs/eleventyComputed/third.njk", "./test/stubs/", "./dist" @@ -106,7 +107,7 @@ test("eleventyComputed js front matter key reuses and overrides", async (t) => { }); test("eleventyComputed true primitive", async (t) => { - let tmpl = getNewTemplate( + let tmpl = await getNewTemplate( "./test/stubs/eleventyComputed/true.njk", "./test/stubs/", "./dist" @@ -120,8 +121,10 @@ test("eleventyComputed true primitive", async (t) => { test("eleventyComputed relies on global data", async (t) => { let eleventyConfig = new TemplateConfig(); + await eleventyConfig.init(); + let dataObj = new TemplateData("./test/stubs/", eleventyConfig); - let tmpl = getNewTemplate( + let tmpl = await getNewTemplate( "./test/stubs/eleventyComputed/use-global-data.njk", "./test/stubs/", "./dist", @@ -139,12 +142,11 @@ test("eleventyComputed relies on global data", async (t) => { test("eleventyComputed intermixes with global data", async (t) => { let eleventyConfig = new TemplateConfig(); eleventyConfig.userConfig.setDataDeepMerge(true); - let dataObj = new TemplateData( - "./test/stubs-computed-global/", - eleventyConfig - ); + await eleventyConfig.init(); + + let dataObj = new TemplateData("./test/stubs-computed-global/", eleventyConfig); - let tmpl = getNewTemplate( + let tmpl = await getNewTemplate( "./test/stubs-computed-global/intermix.njk", "./test/stubs-computed-global/", "./dist", @@ -168,18 +170,24 @@ test("eleventyComputed intermixes with global data", async (t) => { }); test("eleventyComputed using symbol parsing on template strings (nunjucks)", async (t) => { - let tmpl = getNewTemplate( - "./test/stubs-computed-symbolparse/test.njk", - "./test/stubs-computed-symbolparse/", - "./test/stubs-computed-symbolparse/_site" - ); - tmpl.config.nunjucksFilters.fail = function (str) { + let eleventyConfig = await new TemplateConfig(); + eleventyConfig.userConfig.addNunjucksFilter("fail", function (str) { // Filter expects a certain String format, don’t use the (((11ty))) string hack if (!str || str.length !== 1) { throw new Error("Expect a one character string"); } return `${str}`; - }; + }); + await eleventyConfig.init(); + + let tmpl = await getNewTemplate( + "./test/stubs-computed-symbolparse/test.njk", + "./test/stubs-computed-symbolparse/", + "./test/stubs-computed-symbolparse/_site", + null, + null, + eleventyConfig + ); let data = await getRenderedData(tmpl); t.is(data.a, "a"); @@ -188,18 +196,24 @@ test("eleventyComputed using symbol parsing on template strings (nunjucks)", asy }); test("eleventyComputed using symbol parsing on template strings (liquid)", async (t) => { - let tmpl = getNewTemplate( - "./test/stubs-computed-symbolparse/test.liquid", - "./test/stubs-computed-symbolparse/", - "./test/stubs-computed-symbolparse/_site" - ); - tmpl.config.liquidFilters.fail = function (str) { + let eleventyConfig = await new TemplateConfig(); + eleventyConfig.userConfig.addLiquidFilter("fail", function (str) { // Filter expects a certain String format, don’t use the (((11ty))) string hack if (!str || str.length !== 1) { throw new Error("Expect a one character string: " + str); } return `${str}`; - }; + }); + await eleventyConfig.init(); + + let tmpl = await getNewTemplate( + "./test/stubs-computed-symbolparse/test.liquid", + "./test/stubs-computed-symbolparse/", + "./test/stubs-computed-symbolparse/_site", + null, + null, + eleventyConfig + ); let data = await getRenderedData(tmpl); t.is(data.a, "a"); @@ -208,7 +222,7 @@ test("eleventyComputed using symbol parsing on template strings (liquid)", async }); test("eleventyComputed render strings in arrays", async (t) => { - let tmpl = getNewTemplate( + let tmpl = await getNewTemplate( "./test/stubs-computed-array/test.liquid", "./test/stubs-computed-array/", "./test/stubs-computed-array/_site" diff --git a/test/TemplateTest-CustomExtensions.js b/test/TemplateTest-CustomExtensions.js index 2c99ddb1f..01bec7d1d 100644 --- a/test/TemplateTest-CustomExtensions.js +++ b/test/TemplateTest-CustomExtensions.js @@ -1,10 +1,9 @@ -const test = require("ava"); +import test from "ava"; +import { marked } from "marked"; -const TemplateConfig = require("../src/TemplateConfig"); -const TemplateData = require("../src/TemplateData"); -const TemplateContent = require("../src/TemplateContent"); - -const getNewTemplate = require("./_getNewTemplateForTests"); +import TemplateConfig from "../src/TemplateConfig.js"; +import TemplateData from "../src/TemplateData.js"; +import getNewTemplate from "./_getNewTemplateForTests.js"; test("Using getData: false without getInstanceFromInputPath works ok", async (t) => { let eleventyConfig = new TemplateConfig(); @@ -22,9 +21,10 @@ test("Using getData: false without getInstanceFromInputPath works ok", async (t) }; }, }); + await eleventyConfig.init(); let dataObj = new TemplateData("./test/stubs/", eleventyConfig); - let tmpl = getNewTemplate( + let tmpl = await getNewTemplate( "./test/stubs/custom-extension.txt", "./test/stubs/", "dist", @@ -53,9 +53,10 @@ test("Using getData: true without getInstanceFromInputPath should error", async }; }, }); + await eleventyConfig.init(); let dataObj = new TemplateData("./test/stubs/", eleventyConfig); - let tmpl = getNewTemplate( + let tmpl = await getNewTemplate( "./test/stubs/custom-extension.txt", "./test/stubs/", "dist", @@ -85,9 +86,10 @@ test("Using getData: [] without getInstanceFromInputPath should error", async (t }; }, }); + await eleventyConfig.init(); let dataObj = new TemplateData("./test/stubs/", eleventyConfig); - let tmpl = getNewTemplate( + let tmpl = await getNewTemplate( "./test/stubs/custom-extension.txt", "./test/stubs/", "dist", @@ -126,9 +128,10 @@ test("Using getData: true and getInstanceFromInputPath to get data from instance }; }, }); + await eleventyConfig.init(); let dataObj = new TemplateData("./test/stubs/", eleventyConfig); - let tmpl = getNewTemplate( + let tmpl = await getNewTemplate( "./test/stubs/custom-extension.txt", "./test/stubs/", "dist", @@ -167,9 +170,10 @@ test("Using eleventyDataKey to get a different key data from instance", async (t }; }, }); + await eleventyConfig.init(); let dataObj = new TemplateData("./test/stubs/", eleventyConfig); - let tmpl = getNewTemplate( + let tmpl = await getNewTemplate( "./test/stubs/custom-extension.txt", "./test/stubs/", "dist", @@ -191,9 +195,10 @@ test("Uses default renderer (no compile function) when you override an existing cache: false, }, }); + await eleventyConfig.init(); let dataObj = new TemplateData("./test/stubs/", eleventyConfig); - let tmpl = getNewTemplate( + let tmpl = await getNewTemplate( "./test/stubs/default.liquid", "./test/stubs/", "dist", @@ -224,9 +229,10 @@ test("Access to default renderer when you override an existing extension", async }; }, }); + await eleventyConfig.init(); let dataObj = new TemplateData("./test/stubs/", eleventyConfig); - let tmpl = getNewTemplate( + let tmpl = await getNewTemplate( "./test/stubs/default.liquid", "./test/stubs/", "dist", @@ -258,9 +264,10 @@ test("Overridden liquid gets used from a markdown template", async (t) => { }; }, }); + await eleventyConfig.init(); let dataObj = new TemplateData("./test/stubs/", eleventyConfig); - let tmpl = getNewTemplate( + let tmpl = await getNewTemplate( "./test/stubs/default.md", "./test/stubs/", "dist", @@ -274,8 +281,6 @@ test("Overridden liquid gets used from a markdown template", async (t) => { }); test("Use marked for markdown", async (t) => { - const { marked } = require("marked"); - t.plan(2); let eleventyConfig = new TemplateConfig(); @@ -294,9 +299,10 @@ test("Use marked for markdown", async (t) => { }; }, }); + await eleventyConfig.init(); let dataObj = new TemplateData("./test/stubs/", eleventyConfig); - let tmpl = getNewTemplate( + let tmpl = await getNewTemplate( "./test/stubs/default-no-liquid.md", "./test/stubs/", "dist", @@ -326,9 +332,10 @@ test("Use defaultRenderer for markdown", async (t) => { }; }, }); + await eleventyConfig.init(); let dataObj = new TemplateData("./test/stubs/", eleventyConfig); - let tmpl = getNewTemplate( + let tmpl = await getNewTemplate( "./test/stubs/default.md", "./test/stubs/", "dist", @@ -357,9 +364,10 @@ test("Front matter in a custom extension", async (t) => { }; }, }); + await eleventyConfig.init(); let dataObj = new TemplateData("./test/stubs/", eleventyConfig); - let tmpl = getNewTemplate( + let tmpl = await getNewTemplate( "./test/stubs/default-frontmatter.txt", "./test/stubs/", "dist", @@ -391,9 +399,10 @@ test("Access to default renderer when you override an existing extension (async }; }, }); + await eleventyConfig.init(); let dataObj = new TemplateData("./test/stubs/", eleventyConfig); - let tmpl = getNewTemplate( + let tmpl = await getNewTemplate( "./test/stubs/default.liquid", "./test/stubs/", "dist", @@ -424,9 +433,10 @@ test("Access to default renderer when you override an existing extension (async }; }, }); + await eleventyConfig.init(); let dataObj = new TemplateData("./test/stubs/", eleventyConfig); - let tmpl = getNewTemplate( + let tmpl = await getNewTemplate( "./test/stubs/default.liquid", "./test/stubs/", "dist", @@ -452,9 +462,10 @@ test("Return undefined in compile to ignore #2267", async (t) => { return; }, }); + await eleventyConfig.init(); let dataObj = new TemplateData("./test/stubs/", eleventyConfig); - let tmpl = getNewTemplate( + let tmpl = await getNewTemplate( "./test/stubs/custom-extension.txt", "./test/stubs/", "dist", @@ -480,9 +491,10 @@ test("Return undefined in compile to ignore (async compile function) #2350", asy return; }, }); + await eleventyConfig.init(); let dataObj = new TemplateData("./test/stubs/", eleventyConfig); - let tmpl = getNewTemplate( + let tmpl = await getNewTemplate( "./test/stubs/custom-extension.txt", "./test/stubs/", "dist", diff --git a/test/TemplateTest-DataCascade.js b/test/TemplateTest-DataCascade.js index f48a8f7f4..b085f77f1 100644 --- a/test/TemplateTest-DataCascade.js +++ b/test/TemplateTest-DataCascade.js @@ -1,17 +1,16 @@ -const test = require("ava"); -const getNewTemplate = require("./_getNewTemplateForTests"); -const TemplateConfig = require("../src/TemplateConfig"); -const TemplateData = require("../src/TemplateData"); +import test from "ava"; + +import TemplateConfig from "../src/TemplateConfig.js"; +import TemplateData from "../src/TemplateData.js"; +import getNewTemplate from "./_getNewTemplateForTests.js"; // Prior to and including 0.10.0 this mismatched the documentation)! (Issue #915) test("Layout front matter does not override template data files", async (t) => { let eleventyConfig = new TemplateConfig(); + await eleventyConfig.init(); - let dataObj = new TemplateData( - "./test/stubs-data-cascade/layout-data-files/", - eleventyConfig - ); - let tmpl = getNewTemplate( + let dataObj = new TemplateData("./test/stubs-data-cascade/layout-data-files/", eleventyConfig); + let tmpl = await getNewTemplate( "./test/stubs-data-cascade/layout-data-files/test.njk", "./test/stubs-data-cascade/layout-data-files/", "./dist", @@ -26,12 +25,10 @@ test("Layout front matter does not override template data files", async (t) => { test("Layout front matter should not override global data (sanity check, Issue 915)", async (t) => { let eleventyConfig = new TemplateConfig(); + await eleventyConfig.init(); - let dataObj = new TemplateData( - "./test/stubs-data-cascade/global-versus-layout/", - eleventyConfig - ); - let tmpl = getNewTemplate( + let dataObj = new TemplateData("./test/stubs-data-cascade/global-versus-layout/", eleventyConfig); + let tmpl = await getNewTemplate( "./test/stubs-data-cascade/global-versus-layout/test.njk", "./test/stubs-data-cascade/global-versus-layout/", "./dist", @@ -46,12 +43,13 @@ test("Layout front matter should not override global data (sanity check, Issue 9 test("Template data files should be more specific in data cascade than Layout front matter (breaking change in 1.0, issue 915)", async (t) => { let eleventyConfig = new TemplateConfig(); + await eleventyConfig.init(); let dataObj = new TemplateData( "./test/stubs-data-cascade/layout-versus-tmpldatafile/", eleventyConfig ); - let tmpl = getNewTemplate( + let tmpl = await getNewTemplate( "./test/stubs-data-cascade/layout-versus-tmpldatafile/test.njk", "./test/stubs-data-cascade/layout-versus-tmpldatafile/", "./dist", @@ -66,12 +64,13 @@ test("Template data files should be more specific in data cascade than Layout fr test("Directory data files should be more specific in data cascade than Layout front matter (breaking change in 1.0, issue 915)", async (t) => { let eleventyConfig = new TemplateConfig(); + await eleventyConfig.init(); let dataObj = new TemplateData( "./test/stubs-data-cascade/layout-versus-dirdatafile/src/", eleventyConfig ); - let tmpl = getNewTemplate( + let tmpl = await getNewTemplate( "./test/stubs-data-cascade/layout-versus-dirdatafile/src/test.njk", "./test/stubs-data-cascade/layout-versus-dirdatafile/src/", "./dist", diff --git a/test/TemplateTest-Dates.js b/test/TemplateTest-Dates.js index b1abc83fc..baccde0bd 100644 --- a/test/TemplateTest-Dates.js +++ b/test/TemplateTest-Dates.js @@ -1,5 +1,5 @@ -const test = require("ava"); -const getNewTemplate = require("./_getNewTemplateForTests"); +import test from "ava"; +import getNewTemplate from "./_getNewTemplateForTests.js"; async function getRenderedData(tmpl, pageNumber = 0) { let data = await tmpl.getData(); @@ -8,11 +8,7 @@ async function getRenderedData(tmpl, pageNumber = 0) { } test("getMappedDate (empty, assume created)", async (t) => { - let tmpl = getNewTemplate( - "./test/stubs/dates/file1.md", - "./test/stubs/", - "./dist" - ); + let tmpl = await getNewTemplate("./test/stubs/dates/file1.md", "./test/stubs/", "./dist"); let data = await getRenderedData(tmpl); let date = await tmpl.getMappedDate(data); @@ -21,11 +17,7 @@ test("getMappedDate (empty, assume created)", async (t) => { }); test("getMappedDate (explicit date, yaml String)", async (t) => { - let tmpl = getNewTemplate( - "./test/stubs/dates/file2.md", - "./test/stubs/", - "./dist" - ); + let tmpl = await getNewTemplate("./test/stubs/dates/file2.md", "./test/stubs/", "./dist"); let data = await getRenderedData(tmpl); let date = await tmpl.getMappedDate(data); @@ -35,11 +27,7 @@ test("getMappedDate (explicit date, yaml String)", async (t) => { }); test("getMappedDate (explicit date, yaml Date)", async (t) => { - let tmpl = getNewTemplate( - "./test/stubs/dates/file2b.md", - "./test/stubs/", - "./dist" - ); + let tmpl = await getNewTemplate("./test/stubs/dates/file2b.md", "./test/stubs/", "./dist"); let data = await getRenderedData(tmpl); let date = await tmpl.getMappedDate(data); @@ -49,19 +37,11 @@ test("getMappedDate (explicit date, yaml Date)", async (t) => { }); test("getMappedDate (explicit date, yaml Date and string should be the same)", async (t) => { - let tmplA = getNewTemplate( - "./test/stubs/dates/file2.md", - "./test/stubs/", - "./dist" - ); + let tmplA = await getNewTemplate("./test/stubs/dates/file2.md", "./test/stubs/", "./dist"); let dataA = await getRenderedData(tmplA); let stringDate = await tmplA.getMappedDate(dataA); - let tmplB = getNewTemplate( - "./test/stubs/dates/file2b.md", - "./test/stubs/", - "./dist" - ); + let tmplB = await getNewTemplate("./test/stubs/dates/file2b.md", "./test/stubs/", "./dist"); let dataB = await getRenderedData(tmplB); let yamlDate = await tmplB.getMappedDate(dataB); @@ -71,11 +51,7 @@ test("getMappedDate (explicit date, yaml Date and string should be the same)", a }); test("getMappedDate (modified date)", async (t) => { - let tmpl = getNewTemplate( - "./test/stubs/dates/file3.md", - "./test/stubs/", - "./dist" - ); + let tmpl = await getNewTemplate("./test/stubs/dates/file3.md", "./test/stubs/", "./dist"); let data = await getRenderedData(tmpl); let date = await tmpl.getMappedDate(data); @@ -84,11 +60,7 @@ test("getMappedDate (modified date)", async (t) => { }); test("getMappedDate (created date)", async (t) => { - let tmpl = getNewTemplate( - "./test/stubs/dates/file4.md", - "./test/stubs/", - "./dist" - ); + let tmpl = await getNewTemplate("./test/stubs/dates/file4.md", "./test/stubs/", "./dist"); let data = await getRenderedData(tmpl); let date = await tmpl.getMappedDate(data); @@ -97,7 +69,7 @@ test("getMappedDate (created date)", async (t) => { }); test("getMappedDate (falls back to filename date)", async (t) => { - let tmpl = getNewTemplate( + let tmpl = await getNewTemplate( "./test/stubs/dates/2018-01-01-file5.md", "./test/stubs/", "./dist" @@ -111,7 +83,7 @@ test("getMappedDate (falls back to filename date)", async (t) => { }); test("getMappedDate (found multiple dates, picks first)", async (t) => { - let tmpl = getNewTemplate( + let tmpl = await getNewTemplate( "./test/stubs/dates/2019-01-01-folder/2020-01-01-file.md", "./test/stubs/", "./dist" diff --git a/test/TemplateTest-JavaScript.js b/test/TemplateTest-JavaScript.js index 212559d63..927191b0e 100644 --- a/test/TemplateTest-JavaScript.js +++ b/test/TemplateTest-JavaScript.js @@ -1,11 +1,12 @@ -const test = require("ava"); -const semver = require("semver"); -const TemplateConfig = require("../src/TemplateConfig"); -const getNewTemplate = require("./_getNewTemplateForTests"); -const getRenderedTmpls = require("./_getRenderedTemplates"); +import test from "ava"; +import semver from "semver"; + +import TemplateConfig from "../src/TemplateConfig.js"; +import getNewTemplate from "./_getNewTemplateForTests.js"; +import getRenderedTmpls from "./_getRenderedTemplates.js"; test("JavaScript template type (function)", async (t) => { - let tmpl = getNewTemplate("./test/stubs/function.11ty.js", "./test/stubs/", "./dist"); + let tmpl = await getNewTemplate("./test/stubs/function.11ty.cjs", "./test/stubs/", "./dist"); let data = await tmpl.getData(); t.is(await tmpl.getOutputPath(data), "./dist/function/index.html"); @@ -20,7 +21,7 @@ test("JavaScript template type (function)", async (t) => { }); test("JavaScript template type (class with data getter)", async (t) => { - let tmpl = getNewTemplate("./test/stubs/class-data.11ty.js", "./test/stubs/", "./dist"); + let tmpl = await getNewTemplate("./test/stubs/class-data.11ty.cjs", "./test/stubs/", "./dist"); let data = await tmpl.getData(); t.is(await tmpl.getOutputPath(data), "./dist/class-data/index.html"); @@ -31,7 +32,7 @@ test("JavaScript template type (class with data getter)", async (t) => { }); test("JavaScript template type (class with data method)", async (t) => { - let tmpl = getNewTemplate("./test/stubs/class-data-fn.11ty.js", "./test/stubs/", "./dist"); + let tmpl = await getNewTemplate("./test/stubs/class-data-fn.11ty.cjs", "./test/stubs/", "./dist"); let data = await tmpl.getData(); t.is(await tmpl.getOutputPath(data), "./dist/class-data-fn/index.html"); @@ -43,7 +44,11 @@ test("JavaScript template type (class with data method)", async (t) => { if (semver.gte(process.version, "12.4.0")) { test("JavaScript template type (class fields)", async (t) => { - let tmpl = getNewTemplate("./test/stubs/classfields-data.11ty.js", "./test/stubs/", "./dist"); + let tmpl = await getNewTemplate( + "./test/stubs/classfields-data.11ty.cjs", + "./test/stubs/", + "./dist" + ); let data = await tmpl.getData(); t.is(await tmpl.getOutputPath(data), "./dist/classfields-data/index.html"); @@ -55,8 +60,8 @@ if (semver.gte(process.version, "12.4.0")) { } test("JavaScript template type (class with shorthand data method)", async (t) => { - let tmpl = getNewTemplate( - "./test/stubs/class-data-fn-shorthand.11ty.js", + let tmpl = await getNewTemplate( + "./test/stubs/class-data-fn-shorthand.11ty.cjs", "./test/stubs/", "./dist" ); @@ -70,7 +75,11 @@ test("JavaScript template type (class with shorthand data method)", async (t) => }); test("JavaScript template type (class with async data method)", async (t) => { - let tmpl = getNewTemplate("./test/stubs/class-async-data-fn.11ty.js", "./test/stubs/", "./dist"); + let tmpl = await getNewTemplate( + "./test/stubs/class-async-data-fn.11ty.cjs", + "./test/stubs/", + "./dist" + ); let data = await tmpl.getData(); t.is(await tmpl.getOutputPath(data), "./dist/class-async-data-fn/index.html"); @@ -82,7 +91,7 @@ test("JavaScript template type (class with async data method)", async (t) => { test("JavaScript template type (class with data getter and a javascriptFunction)", async (t) => { let eleventyConfig = new TemplateConfig(); - eleventyConfig.appendToRootConfig({ + await eleventyConfig.init({ javascriptFunctions: { upper: function (val) { return new String(val).toUpperCase(); @@ -90,8 +99,8 @@ test("JavaScript template type (class with data getter and a javascriptFunction) }, }); - let tmpl = getNewTemplate( - "./test/stubs/class-data-filter.11ty.js", + let tmpl = await getNewTemplate( + "./test/stubs/class-data-filter.11ty.cjs", "./test/stubs/", "./dist", null, @@ -108,7 +117,7 @@ test("JavaScript template type (class with data getter and a javascriptFunction) test("JavaScript template type (class with data method and a javascriptFunction)", async (t) => { let eleventyConfig = new TemplateConfig(); - eleventyConfig.appendToRootConfig({ + await eleventyConfig.init({ javascriptFunctions: { upper: function (val) { return new String(val).toUpperCase(); @@ -116,8 +125,8 @@ test("JavaScript template type (class with data method and a javascriptFunction) }, }); - let tmpl = getNewTemplate( - "./test/stubs/class-data-fn-filter.11ty.js", + let tmpl = await getNewTemplate( + "./test/stubs/class-data-fn-filter.11ty.cjs", "./test/stubs/", "./dist", null, @@ -133,14 +142,18 @@ test("JavaScript template type (class with data method and a javascriptFunction) }); test("JavaScript template type (class with data permalink)", async (t) => { - let tmpl = getNewTemplate("./test/stubs/class-data-permalink.11ty.js", "./test/stubs/", "./dist"); + let tmpl = await getNewTemplate( + "./test/stubs/class-data-permalink.11ty.cjs", + "./test/stubs/", + "./dist" + ); let data = await tmpl.getData(); t.is(await tmpl.getOutputPath(data), "./dist/my-permalink/index.html"); }); test("JavaScript template type (class with data permalink using a buffer)", async (t) => { - let tmpl = getNewTemplate( - "./test/stubs/class-data-permalink-buffer.11ty.js", + let tmpl = await getNewTemplate( + "./test/stubs/class-data-permalink-buffer.11ty.cjs", "./test/stubs/", "./dist" ); @@ -149,8 +162,8 @@ test("JavaScript template type (class with data permalink using a buffer)", asyn }); test("JavaScript template type (class with data permalink function)", async (t) => { - let tmpl = getNewTemplate( - "./test/stubs/class-data-permalink-fn.11ty.js", + let tmpl = await getNewTemplate( + "./test/stubs/class-data-permalink-fn.11ty.cjs", "./test/stubs/", "./dist" ); @@ -159,8 +172,8 @@ test("JavaScript template type (class with data permalink function)", async (t) }); test("JavaScript template type (class with data permalink function using a buffer)", async (t) => { - let tmpl = getNewTemplate( - "./test/stubs/class-data-permalink-fn-buffer.11ty.js", + let tmpl = await getNewTemplate( + "./test/stubs/class-data-permalink-fn-buffer.11ty.cjs", "./test/stubs/", "./dist" ); @@ -169,8 +182,8 @@ test("JavaScript template type (class with data permalink function using a buffe }); test("JavaScript template type (class with data permalink async function)", async (t) => { - let tmpl = getNewTemplate( - "./test/stubs/class-data-permalink-async-fn.11ty.js", + let tmpl = await getNewTemplate( + "./test/stubs/class-data-permalink-async-fn.11ty.cjs", "./test/stubs/", "./dist" ); @@ -179,8 +192,8 @@ test("JavaScript template type (class with data permalink async function)", asyn }); test("JavaScript template type (class with data permalink function using a filter)", async (t) => { - let tmpl = getNewTemplate( - "./test/stubs/class-data-permalink-fn-filter.11ty.js", + let tmpl = await getNewTemplate( + "./test/stubs/class-data-permalink-fn-filter.11ty.cjs", "./test/stubs/", "./dist" ); @@ -190,7 +203,7 @@ test("JavaScript template type (class with data permalink function using a filte }); test("JavaScript template type (should use the same class instance for data and render)", async (t) => { - let tmpl = getNewTemplate("./test/stubs/oneinstance.11ty.js", "./test/stubs/", "./dist"); + let tmpl = await getNewTemplate("./test/stubs/oneinstance.11ty.cjs", "./test/stubs/", "./dist"); let data = await tmpl.getData(); let pages = await getRenderedTmpls(tmpl, data); @@ -202,7 +215,11 @@ test("JavaScript template type (should use the same class instance for data and }); test("JavaScript template type (multiple exports)", async (t) => { - let tmpl = getNewTemplate("./test/stubs/multipleexports.11ty.js", "./test/stubs/", "./dist"); + let tmpl = await getNewTemplate( + "./test/stubs/multipleexports.11ty.cjs", + "./test/stubs/", + "./dist" + ); let data = await tmpl.getData(); let pages = await getRenderedTmpls(tmpl, data); @@ -211,8 +228,8 @@ test("JavaScript template type (multiple exports)", async (t) => { }); test("JavaScript template type (multiple exports, promises)", async (t) => { - let tmpl = getNewTemplate( - "./test/stubs/multipleexports-promises.11ty.js", + let tmpl = await getNewTemplate( + "./test/stubs/multipleexports-promises.11ty.cjs", "./test/stubs/", "./dist" ); @@ -226,7 +243,7 @@ test("JavaScript template type (multiple exports, promises)", async (t) => { }); test("JavaScript template type (object)", async (t) => { - let tmpl = getNewTemplate("./test/stubs/object.11ty.js", "./test/stubs/", "./dist"); + let tmpl = await getNewTemplate("./test/stubs/object.11ty.cjs", "./test/stubs/", "./dist"); let data = await tmpl.getData(); t.is(data.name, "Ted"); @@ -237,7 +254,11 @@ test("JavaScript template type (object)", async (t) => { }); test("JavaScript template type (object, no render method)", async (t) => { - let tmpl = getNewTemplate("./test/stubs/object-norender.11ty.js", "./test/stubs/", "./dist"); + let tmpl = await getNewTemplate( + "./test/stubs/object-norender.11ty.cjs", + "./test/stubs/", + "./dist" + ); let data = await tmpl.getData(); t.is(data.name, "Ted"); @@ -248,7 +269,11 @@ test("JavaScript template type (object, no render method)", async (t) => { }); test("JavaScript template type (class, no render method)", async (t) => { - let tmpl = getNewTemplate("./test/stubs/class-norender.11ty.js", "./test/stubs/", "./dist"); + let tmpl = await getNewTemplate( + "./test/stubs/class-norender.11ty.cjs", + "./test/stubs/", + "./dist" + ); let data = await tmpl.getData(); t.is(data.name, "Ted"); @@ -258,7 +283,11 @@ test("JavaScript template type (class, no render method)", async (t) => { t.is(pages[0].content.trim(), ""); }); test("JavaScript template type (data returns a string)", async (t) => { - let tmpl = getNewTemplate("./test/stubs/exports-flatdata.11ty.js", "./test/stubs/", "./dist"); + let tmpl = await getNewTemplate( + "./test/stubs/exports-flatdata.11ty.cjs", + "./test/stubs/", + "./dist" + ); await t.throwsAsync(async () => { await tmpl.getData(); diff --git a/test/TemplateTest.js b/test/TemplateTest.js index f5bb0a41b..49a55f015 100644 --- a/test/TemplateTest.js +++ b/test/TemplateTest.js @@ -1,18 +1,20 @@ -const test = require("ava"); -const fsp = require("fs").promises; -const pretty = require("pretty"); - -const TemplateConfig = require("../src/TemplateConfig"); -const TemplateData = require("../src/TemplateData"); -const FileSystemSearch = require("../src/FileSystemSearch"); -const EleventyExtensionMap = require("../src/EleventyExtensionMap"); -const EleventyErrorUtil = require("../src/EleventyErrorUtil"); -const TemplateContentPrematureUseError = require("../src/Errors/TemplateContentPrematureUseError"); -const normalizeNewLines = require("./Util/normalizeNewLines"); -const eventBus = require("../src/EventBus"); - -const getNewTemplate = require("./_getNewTemplateForTests"); -const getRenderedTmpls = require("./_getRenderedTemplates"); +import test from "ava"; +import fs from "fs"; +import pretty from "pretty"; +import TOML from "@iarna/toml"; + +import TemplateConfig from "../src/TemplateConfig.js"; +import TemplateData from "../src/TemplateData.js"; +import FileSystemSearch from "../src/FileSystemSearch.js"; +import EleventyExtensionMap from "../src/EleventyExtensionMap.js"; +import EleventyErrorUtil from "../src/EleventyErrorUtil.js"; +import TemplateContentPrematureUseError from "../src/Errors/TemplateContentPrematureUseError.js"; +import normalizeNewLines from "./Util/normalizeNewLines.js"; +import eventBus from "../src/EventBus.js"; +import getNewTemplate from "./_getNewTemplateForTests.js"; +import getRenderedTmpls from "./_getRenderedTemplates.js"; + +const fsp = fs.promises; async function getRenderedData(tmpl, pageNumber = 0) { let data = await tmpl.getData(); @@ -44,18 +46,22 @@ async function _testCompleteRender(tmpl) { return contents; } -test("getTemplateSubFolder", (t) => { - let tmpl = getNewTemplate("./test/stubs/template.ejs", "./test/stubs/", "./dist"); +test("getTemplateSubFolder", async (t) => { + let tmpl = await getNewTemplate("./test/stubs/template.liquid", "./test/stubs/", "./dist"); t.is(tmpl.getTemplateSubfolder(), ""); }); -test("getTemplateSubFolder, output is a subdir of input", (t) => { - let tmpl = getNewTemplate("./test/stubs/template.ejs", "./test/stubs/", "./test/stubs/_site"); +test("getTemplateSubFolder, output is a subdir of input", async (t) => { + let tmpl = await getNewTemplate( + "./test/stubs/template.liquid", + "./test/stubs/", + "./test/stubs/_site" + ); t.is(tmpl.getTemplateSubfolder(), ""); }); test("output path maps to an html file", async (t) => { - let tmpl = getNewTemplate("./test/stubs/template.ejs", "./test/stubs/", "./dist"); + let tmpl = await getNewTemplate("./test/stubs/template.liquid", "./test/stubs/", "./dist"); t.is(tmpl.parsed.dir, "./test/stubs"); t.is(tmpl.inputDir, "./test/stubs"); t.is(tmpl.outputDir, "./dist"); @@ -66,7 +72,11 @@ test("output path maps to an html file", async (t) => { }); test("subfolder outputs to a subfolder", async (t) => { - let tmpl = getNewTemplate("./test/stubs/subfolder/subfolder.ejs", "./test/stubs/", "./dist"); + let tmpl = await getNewTemplate( + "./test/stubs/subfolder/subfolder.liquid", + "./test/stubs/", + "./dist" + ); let data = await tmpl.getData(); t.is(tmpl.parsed.dir, "./test/stubs/subfolder"); t.is(tmpl.getTemplateSubfolder(), "subfolder"); @@ -74,8 +84,8 @@ test("subfolder outputs to a subfolder", async (t) => { }); test("subfolder outputs to double subfolder", async (t) => { - let tmpl = getNewTemplate( - "./test/stubs/subfolder/subfolder/subfolder.ejs", + let tmpl = await getNewTemplate( + "./test/stubs/subfolder/subfolder/subfolder.liquid", "./test/stubs/", "./dist" ); @@ -86,26 +96,34 @@ test("subfolder outputs to double subfolder", async (t) => { }); test("HTML files output to the same as the input directory have a file suffix added (only if index, this is not index).", async (t) => { - let tmpl = getNewTemplate("./test/stubs/testing.html", "./test/stubs", "./test/stubs"); + let tmpl = await getNewTemplate("./test/stubs/testing.html", "./test/stubs", "./test/stubs"); let data = await tmpl.getData(); t.is(await tmpl.getOutputPath(data), "./test/stubs/testing/index.html"); }); test("HTML files output to the same as the input directory have a file suffix added (only if index, this _is_ index).", async (t) => { - let tmpl = getNewTemplate("./test/stubs/index.html", "./test/stubs", "./test/stubs"); + let tmpl = await getNewTemplate("./test/stubs/index.html", "./test/stubs", "./test/stubs"); let data = await tmpl.getData(); t.is(await tmpl.getOutputPath(data), "./test/stubs/index-o.html"); }); test("HTML files output to the same as the input directory have a file suffix added (only if index, this _is_ index, subfolder).", async (t) => { - let tmpl = getNewTemplate("./test/stubs/subfolder/index.html", "./test/stubs", "./test/stubs"); + let tmpl = await getNewTemplate( + "./test/stubs/subfolder/index.html", + "./test/stubs", + "./test/stubs" + ); let data = await tmpl.getData(); t.is(await tmpl.getOutputPath(data), "./test/stubs/subfolder/index-o.html"); }); test("Test raw front matter from template (yaml)", async (t) => { // https://github.com/jonschlinkert/gray-matter/blob/master/examples/yaml.js - let tmpl = getNewTemplate("./test/stubs/templateFrontMatter.ejs", "./test/stubs/", "./dist"); + let tmpl = await getNewTemplate( + "./test/stubs/templateFrontMatter.liquid", + "./test/stubs/", + "./dist" + ); t.truthy(await tmpl.getInputContent(), "template exists and can be opened."); t.is((await tmpl.getFrontMatter()).data.key1, "value1"); @@ -121,7 +139,11 @@ test("Test raw front matter from template (yaml)", async (t) => { test("Test raw front matter from template (json)", async (t) => { // https://github.com/jonschlinkert/gray-matter/blob/master/examples/json.js - let tmpl = getNewTemplate("./test/stubs/templateFrontMatterJson.ejs", "./test/stubs/", "./dist"); + let tmpl = await getNewTemplate( + "./test/stubs/templateFrontMatterJson.liquid", + "./test/stubs/", + "./dist" + ); t.is((await tmpl.getFrontMatter()).data.key1, "value1"); t.is((await tmpl.getFrontMatter()).data.key3, "value3"); @@ -136,7 +158,11 @@ test("Test raw front matter from template (json)", async (t) => { test("Test raw front matter from template (js)", async (t) => { // https://github.com/jonschlinkert/gray-matter/blob/master/examples/javascript.js - let tmpl = getNewTemplate("./test/stubs/templateFrontMatterJs.ejs", "./test/stubs/", "./dist"); + let tmpl = await getNewTemplate( + "./test/stubs/templateFrontMatterJs.njk", + "./test/stubs/", + "./dist" + ); t.is((await tmpl.getFrontMatter()).data.key1, "value1"); t.is((await tmpl.getFrontMatter()).data.key3, "value3"); @@ -150,7 +176,11 @@ test("Test raw front matter from template (js)", async (t) => { }); test("Test that getData() works", async (t) => { - let tmpl = getNewTemplate("./test/stubs/templateFrontMatter.ejs", "./test/stubs/", "./dist"); + let tmpl = await getNewTemplate( + "./test/stubs/templateFrontMatter.liquid", + "./test/stubs/", + "./dist" + ); let data = await tmpl.getData(); t.is(data.key1, "value1"); @@ -159,10 +189,11 @@ test("Test that getData() works", async (t) => { test("One Layout (using new content var)", async (t) => { let eleventyConfig = new TemplateConfig(); + await eleventyConfig.init(); let dataObj = new TemplateData("./test/stubs/", eleventyConfig); - let tmpl = getNewTemplate( - "./test/stubs/templateWithLayout.ejs", + let tmpl = await getNewTemplate( + "./test/stubs/templateWithLayoutKey.liquid", "./test/stubs/", "dist", dataObj, @@ -188,10 +219,11 @@ test("One Layout (using new content var)", async (t) => { test("One Layout (using layoutContent)", async (t) => { let eleventyConfig = new TemplateConfig(); + await eleventyConfig.init(); let dataObj = new TemplateData("./test/stubs/", eleventyConfig); - let tmpl = getNewTemplate( - "./test/stubs/templateWithLayoutContent.ejs", + let tmpl = await getNewTemplate( + "./test/stubs/templateWithLayoutContent.liquid", "./test/stubs/", "dist", dataObj, @@ -217,10 +249,11 @@ test("One Layout (using layoutContent)", async (t) => { test("One Layout (layouts disabled)", async (t) => { let eleventyConfig = new TemplateConfig(); + await eleventyConfig.init(); let dataObj = new TemplateData("./test/stubs/", eleventyConfig); - let tmpl = getNewTemplate( - "./test/stubs/templateWithLayoutContent.ejs", + let tmpl = await getNewTemplate( + "./test/stubs/templateWithLayoutContent.liquid", "./test/stubs/", "dist", dataObj, @@ -241,8 +274,10 @@ test("One Layout (layouts disabled)", async (t) => { test("One Layout (liquid test)", async (t) => { let eleventyConfig = new TemplateConfig(); + await eleventyConfig.init(); + let dataObj = new TemplateData("./test/stubs/", eleventyConfig); - let tmpl = getNewTemplate( + let tmpl = await getNewTemplate( "./test/stubs/templateWithLayout.liquid", "./test/stubs/", "dist", @@ -269,10 +304,11 @@ test("One Layout (liquid test)", async (t) => { test("Two Layouts", async (t) => { let eleventyConfig = new TemplateConfig(); + await eleventyConfig.init(); let dataObj = new TemplateData("./test/stubs/", eleventyConfig); - let tmpl = getNewTemplate( - "./test/stubs/templateTwoLayouts.ejs", + let tmpl = await getNewTemplate( + "./test/stubs/templateTwoLayouts.liquid", "./test/stubs/", "dist", dataObj, @@ -300,8 +336,10 @@ test("Two Layouts", async (t) => { test("Liquid template", async (t) => { let eleventyConfig = new TemplateConfig(); + await eleventyConfig.init(); + let dataObj = new TemplateData("./test/stubs/", eleventyConfig); - let tmpl = getNewTemplate( + let tmpl = await getNewTemplate( "./test/stubs/formatTest.liquid", "./test/stubs/", "dist", @@ -314,26 +352,30 @@ test("Liquid template", async (t) => { }); test("Liquid template with include", async (t) => { - let tmpl = getNewTemplate("./test/stubs/includer.liquid", "./test/stubs/", "dist"); + let tmpl = await getNewTemplate("./test/stubs/includer.liquid", "./test/stubs/", "dist"); t.is((await tmpl.render(await tmpl.getData())).trim(), "

This is an include.

"); }); test("Permalink output directory", async (t) => { - let tmpl = getNewTemplate("./test/stubs/permalinked.ejs", "./test/stubs/", "./dist"); + let tmpl = await getNewTemplate("./test/stubs/permalinked.liquid", "./test/stubs/", "./dist"); let data = await tmpl.getData(); t.is(await tmpl.getOutputPath(data), "./dist/permalinksubfolder/index.html"); }); test("Permalink output directory from layout", async (t) => { - let tmpl = getNewTemplate("./test/stubs/permalink-in-layout.ejs", "./test/stubs/", "./dist"); + let tmpl = await getNewTemplate( + "./test/stubs/permalink-in-layout.liquid", + "./test/stubs/", + "./dist" + ); let data = await tmpl.getData(); t.is(await tmpl.getOutputPath(data), "./dist/hello/index.html"); }); test("Permalink output directory from layout (fileslug)", async (t) => { - let tmpl = getNewTemplate( - "./test/stubs/permalink-in-layout-fileslug.ejs", + let tmpl = await getNewTemplate( + "./test/stubs/permalink-in-layout-fileslug.liquid", "./test/stubs/", "./dist" ); @@ -343,8 +385,10 @@ test("Permalink output directory from layout (fileslug)", async (t) => { test("Layout from template-data-file that has a permalink (fileslug) Issue #121", async (t) => { let eleventyConfig = new TemplateConfig(); + await eleventyConfig.init(); + let dataObj = new TemplateData("./test/stubs/", eleventyConfig); - let tmpl = getNewTemplate( + let tmpl = await getNewTemplate( "./test/stubs/permalink-data-layout/test.njk", "./test/stubs/", "./dist", @@ -358,7 +402,7 @@ test("Layout from template-data-file that has a permalink (fileslug) Issue #121" }); test("Fileslug in an 11ty.js template Issue #588", async (t) => { - let tmpl = getNewTemplate("./test/stubs/fileslug.11ty.js", "./test/stubs/", "./dist"); + let tmpl = await getNewTemplate("./test/stubs/fileslug.11ty.cjs", "./test/stubs/", "./dist"); let data = await tmpl.getData(); let renderedTmpl = (await getRenderedTmpls(tmpl, data))[0]; @@ -367,11 +411,13 @@ test("Fileslug in an 11ty.js template Issue #588", async (t) => { test("Local template data file import (without a global data json)", async (t) => { let eleventyConfig = new TemplateConfig(); + await eleventyConfig.init(); + let dataObj = new TemplateData("./test/stubs/", eleventyConfig); dataObj.setFileSystemSearch(new FileSystemSearch()); await dataObj.getGlobalData(); - let tmpl = getNewTemplate( + let tmpl = await getNewTemplate( "./test/stubs/component/component.njk", "./test/stubs/", "./dist", @@ -382,10 +428,12 @@ test("Local template data file import (without a global data json)", async (t) = t.deepEqual(await dataObj.getLocalDataPaths(tmpl.getInputPath()), [ "./test/stubs/stubs.json", "./test/stubs/stubs.11tydata.json", + "./test/stubs/stubs.11tydata.mjs", "./test/stubs/stubs.11tydata.cjs", "./test/stubs/stubs.11tydata.js", "./test/stubs/component/component.json", "./test/stubs/component/component.11tydata.json", + "./test/stubs/component/component.11tydata.mjs", "./test/stubs/component/component.11tydata.cjs", "./test/stubs/component/component.11tydata.js", ]); @@ -395,11 +443,13 @@ test("Local template data file import (without a global data json)", async (t) = test("Local template data file import (two subdirectories deep)", async (t) => { let eleventyConfig = new TemplateConfig(); + await eleventyConfig.init(); + let dataObj = new TemplateData("./test/stubs/", eleventyConfig); dataObj.setFileSystemSearch(new FileSystemSearch()); await dataObj.getGlobalData(); - let tmpl = getNewTemplate( + let tmpl = await getNewTemplate( "./test/stubs/firstdir/seconddir/component.njk", "./test/stubs/", "./dist", @@ -409,18 +459,22 @@ test("Local template data file import (two subdirectories deep)", async (t) => { t.deepEqual(await dataObj.getLocalDataPaths(tmpl.getInputPath()), [ "./test/stubs/stubs.json", "./test/stubs/stubs.11tydata.json", + "./test/stubs/stubs.11tydata.mjs", "./test/stubs/stubs.11tydata.cjs", "./test/stubs/stubs.11tydata.js", "./test/stubs/firstdir/firstdir.json", "./test/stubs/firstdir/firstdir.11tydata.json", + "./test/stubs/firstdir/firstdir.11tydata.mjs", "./test/stubs/firstdir/firstdir.11tydata.cjs", "./test/stubs/firstdir/firstdir.11tydata.js", "./test/stubs/firstdir/seconddir/seconddir.json", "./test/stubs/firstdir/seconddir/seconddir.11tydata.json", + "./test/stubs/firstdir/seconddir/seconddir.11tydata.mjs", "./test/stubs/firstdir/seconddir/seconddir.11tydata.cjs", "./test/stubs/firstdir/seconddir/seconddir.11tydata.js", "./test/stubs/firstdir/seconddir/component.json", "./test/stubs/firstdir/seconddir/component.11tydata.json", + "./test/stubs/firstdir/seconddir/component.11tydata.mjs", "./test/stubs/firstdir/seconddir/component.11tydata.cjs", "./test/stubs/firstdir/seconddir/component.11tydata.js", ]); @@ -428,24 +482,34 @@ test("Local template data file import (two subdirectories deep)", async (t) => { test("Posts inherits local JSON, layouts", async (t) => { let eleventyConfig = new TemplateConfig(); + await eleventyConfig.init(); + let dataObj = new TemplateData("./test/stubs/", eleventyConfig); dataObj.setFileSystemSearch(new FileSystemSearch()); await dataObj.getGlobalData(); - let tmpl = getNewTemplate("./test/stubs/posts/post1.njk", "./test/stubs/", "./dist", dataObj); + let tmpl = await getNewTemplate( + "./test/stubs/posts/post1.njk", + "./test/stubs/", + "./dist", + dataObj + ); let localDataPaths = await dataObj.getLocalDataPaths(tmpl.getInputPath()); t.deepEqual(localDataPaths, [ "./test/stubs/stubs.json", "./test/stubs/stubs.11tydata.json", + "./test/stubs/stubs.11tydata.mjs", "./test/stubs/stubs.11tydata.cjs", "./test/stubs/stubs.11tydata.js", "./test/stubs/posts/posts.json", "./test/stubs/posts/posts.11tydata.json", + "./test/stubs/posts/posts.11tydata.mjs", "./test/stubs/posts/posts.11tydata.cjs", "./test/stubs/posts/posts.11tydata.js", "./test/stubs/posts/post1.json", "./test/stubs/posts/post1.11tydata.json", + "./test/stubs/posts/post1.11tydata.mjs", "./test/stubs/posts/post1.11tydata.cjs", "./test/stubs/posts/post1.11tydata.js", ]); @@ -468,20 +532,29 @@ test("Posts inherits local JSON, layouts", async (t) => { test("Template and folder name are the same, make sure data imports work ok", async (t) => { let eleventyConfig = new TemplateConfig(); + await eleventyConfig.init(); + let dataObj = new TemplateData("./test/stubs/", eleventyConfig); dataObj.setFileSystemSearch(new FileSystemSearch()); await dataObj.getGlobalData(); - let tmpl = getNewTemplate("./test/stubs/posts/posts.njk", "./test/stubs/", "./dist", dataObj); + let tmpl = await getNewTemplate( + "./test/stubs/posts/posts.njk", + "./test/stubs/", + "./dist", + dataObj + ); let localDataPaths = await dataObj.getLocalDataPaths(tmpl.getInputPath()); t.deepEqual(localDataPaths, [ "./test/stubs/stubs.json", "./test/stubs/stubs.11tydata.json", + "./test/stubs/stubs.11tydata.mjs", "./test/stubs/stubs.11tydata.cjs", "./test/stubs/stubs.11tydata.js", "./test/stubs/posts/posts.json", "./test/stubs/posts/posts.11tydata.json", + "./test/stubs/posts/posts.11tydata.mjs", "./test/stubs/posts/posts.11tydata.cjs", "./test/stubs/posts/posts.11tydata.js", ]); @@ -503,7 +576,7 @@ test("Template and folder name are the same, make sure data imports work ok", as }); test("Clone the template", async (t) => { - let tmpl = getNewTemplate("./test/stubs/default.ejs", "./test/stubs/", "./dist"); + let tmpl = await getNewTemplate("./test/stubs/default.liquid", "./test/stubs/", "./dist"); let data = await tmpl.getData(); @@ -516,7 +589,7 @@ test("Clone the template", async (t) => { }); test("getRenderedData() has all the page variables", async (t) => { - let tmpl = getNewTemplate("./test/stubs/template.ejs", "./test/stubs/", "./dist"); + let tmpl = await getNewTemplate("./test/stubs/template.liquid", "./test/stubs/", "./dist"); let data = await getRenderedData(tmpl); t.truthy(data.page.url); @@ -524,12 +597,12 @@ test("getRenderedData() has all the page variables", async (t) => { t.is(data.page.fileSlug, "template"); t.is(data.page.filePathStem, "/template"); t.truthy(data.page.date.getTime()); - t.is(data.page.inputPath, "./test/stubs/template.ejs"); + t.is(data.page.inputPath, "./test/stubs/template.liquid"); t.is(data.page.outputPath, "./dist/template/index.html"); }); test("Issue #603: page.date Liquid", async (t) => { - let tmpl = getNewTemplate("./test/stubs/pagedate.liquid", "./test/stubs/", "./dist"); + let tmpl = await getNewTemplate("./test/stubs/pagedate.liquid", "./test/stubs/", "./dist"); let data = await tmpl.getData(); t.truthy(data.page.date); @@ -540,7 +613,7 @@ test("Issue #603: page.date Liquid", async (t) => { }); test("Issue #603: page.date Nunjucks", async (t) => { - let tmpl = getNewTemplate("./test/stubs/pagedate.njk", "./test/stubs/", "./dist"); + let tmpl = await getNewTemplate("./test/stubs/pagedate.njk", "./test/stubs/", "./dist"); let data = await tmpl.getData(); t.truthy(data.page.date); @@ -552,7 +625,7 @@ test("Issue #603: page.date Nunjucks", async (t) => { test("Issue #603: page.date.toUTCString() Nunjucks", async (t) => { // Note this is not supported in Liquid - let tmpl = getNewTemplate("./test/stubs/pagedateutc.njk", "./test/stubs/", "./dist"); + let tmpl = await getNewTemplate("./test/stubs/pagedateutc.njk", "./test/stubs/", "./dist"); let data = await tmpl.getData(); t.truthy(data.page.date); @@ -563,7 +636,7 @@ test("Issue #603: page.date.toUTCString() Nunjucks", async (t) => { }); test("getTemplates() data has all the root variables", async (t) => { - let tmpl = getNewTemplate("./test/stubs/template.ejs", "./test/stubs/", "./dist"); + let tmpl = await getNewTemplate("./test/stubs/template.liquid", "./test/stubs/", "./dist"); let data = await tmpl.getData(); let templates = await tmpl.getTemplates(data); @@ -571,12 +644,12 @@ test("getTemplates() data has all the root variables", async (t) => { t.is(templates[0].fileSlug, "template"); t.is(templates[0].filePathStem, "/template"); t.truthy(templates[0].date.getTime()); - t.is(templates[0].inputPath, "./test/stubs/template.ejs"); + t.is(templates[0].inputPath, "./test/stubs/template.liquid"); t.is(templates[0].outputPath, "./dist/template/index.html"); }); test("getTemplates() data has all the page variables", async (t) => { - let tmpl = getNewTemplate("./test/stubs/template.ejs", "./test/stubs/", "./dist"); + let tmpl = await getNewTemplate("./test/stubs/template.liquid", "./test/stubs/", "./dist"); let data = await tmpl.getData(); let templates = await tmpl.getTemplates(data); @@ -584,13 +657,13 @@ test("getTemplates() data has all the page variables", async (t) => { t.is(templates[0].data.page.fileSlug, "template"); t.is(templates[0].filePathStem, "/template"); t.truthy(templates[0].data.page.date.getTime()); - t.is(templates[0].data.page.inputPath, "./test/stubs/template.ejs"); + t.is(templates[0].data.page.inputPath, "./test/stubs/template.liquid"); t.is(templates[0].data.page.outputPath, "./dist/template/index.html"); }); // Warning `getRenderedTemplates()` is a test function now, so this might be a test testing the tests test("getRenderedTemplates() data has all the page variables", async (t) => { - let tmpl = getNewTemplate("./test/stubs/template.ejs", "./test/stubs/", "./dist"); + let tmpl = await getNewTemplate("./test/stubs/template.liquid", "./test/stubs/", "./dist"); let data = await tmpl.getData(); let templates = await getRenderedTmpls(tmpl, data); @@ -598,33 +671,37 @@ test("getRenderedTemplates() data has all the page variables", async (t) => { t.is(templates[0].data.page.fileSlug, "template"); t.is(templates[0].filePathStem, "/template"); t.truthy(templates[0].data.page.date.getTime()); - t.is(templates[0].data.page.inputPath, "./test/stubs/template.ejs"); + t.is(templates[0].data.page.inputPath, "./test/stubs/template.liquid"); t.is(templates[0].data.page.outputPath, "./dist/template/index.html"); }); test("getRenderedData() has good slug (empty, index)", async (t) => { - let tmpl = getNewTemplate("./test/stubs/index.ejs", "./test/stubs/", "./dist"); + let tmpl = await getNewTemplate("./test/stubs/index.liquid", "./test/stubs/", "./dist"); let data = await getRenderedData(tmpl); t.is(data.page.fileSlug, ""); t.is(data.page.filePathStem, "/index"); }); test("getRenderedData() has good slug", async (t) => { - let tmpl = getNewTemplate("./test/stubs/includer.liquid", "./test/stubs/", "./dist"); + let tmpl = await getNewTemplate("./test/stubs/includer.liquid", "./test/stubs/", "./dist"); let data = await getRenderedData(tmpl); t.is(data.page.fileSlug, "includer"); t.is(data.page.filePathStem, "/includer"); }); -test("Override base templating engine from .liquid to ejs", async (t) => { - let tmpl = getNewTemplate("./test/stubs/overrides/test-ejs.liquid", "./test/stubs/", "./dist"); +test("Override base templating engine from .liquid to njk", async (t) => { + let tmpl = await getNewTemplate( + "./test/stubs/overrides/test-njk.liquid", + "./test/stubs/", + "./dist" + ); t.is((await tmpl.render(await tmpl.getData())).trim(), "My Title"); }); test("Override base templating engine from markdown to 11ty.js, then markdown", async (t) => { - let tmpl = getNewTemplate( - "./test/stubs/test-override-js-markdown.11ty.js", + let tmpl = await getNewTemplate( + "./test/stubs/test-override-js-markdown.11ty.cjs", "./test/stubs/", "./dist" ); @@ -633,37 +710,57 @@ test("Override base templating engine from markdown to 11ty.js, then markdown", }); test("Override base templating engine from .liquid to md", async (t) => { - let tmpl = getNewTemplate("./test/stubs/overrides/test-md.liquid", "./test/stubs/", "./dist"); + let tmpl = await getNewTemplate( + "./test/stubs/overrides/test-md.liquid", + "./test/stubs/", + "./dist" + ); t.is((await tmpl.render(await tmpl.getData())).trim(), "

My Title

"); }); -test("Override base templating engine from .liquid to ejs,md", async (t) => { - let tmpl = getNewTemplate("./test/stubs/overrides/test-multiple.md", "./test/stubs/", "./dist"); +test("Override base templating engine from .liquid to njk,md", async (t) => { + let tmpl = await getNewTemplate( + "./test/stubs/overrides/test-multiple.md", + "./test/stubs/", + "./dist" + ); t.is((await tmpl.render(await tmpl.getData())).trim(), "

My Title

"); }); -test("Override base templating engine from .njk to ejs,md", async (t) => { - let tmpl = getNewTemplate("./test/stubs/overrides/test-multiple2.njk", "./test/stubs/", "./dist"); +test("Override base templating engine from .njk to liquid,md", async (t) => { + let tmpl = await getNewTemplate( + "./test/stubs/overrides/test-multiple2.njk", + "./test/stubs/", + "./dist" + ); t.is((await tmpl.render(await tmpl.getData())).trim(), "

My Title

"); }); -test("Override base templating engine from .html to ejs", async (t) => { - let tmpl = getNewTemplate("./test/stubs/overrides/test.html", "./test/stubs/", "./dist"); +test("Override base templating engine from .html to njk", async (t) => { + let tmpl = await getNewTemplate("./test/stubs/overrides/test.html", "./test/stubs/", "./dist"); t.is((await tmpl.render(await tmpl.getData())).trim(), "

My Title

"); }); test("Override base templating engine from .html to (nothing)", async (t) => { - let tmpl = getNewTemplate("./test/stubs/overrides/test-empty.html", "./test/stubs/", "./dist"); + let tmpl = await getNewTemplate( + "./test/stubs/overrides/test-empty.html", + "./test/stubs/", + "./dist" + ); - t.is((await tmpl.render(await tmpl.getData())).trim(), "

<%= title %>

"); + t.is((await tmpl.render(await tmpl.getData())).trim(), "

{{ title }}

"); }); test("Override base templating engine should error with bad string", async (t) => { - let tmpl = getNewTemplate("./test/stubs/overrides/test-error.njk", "./test/stubs/", "./dist"); + let tmpl = await getNewTemplate( + "./test/stubs/overrides/test-error.njk", + "./test/stubs/", + "./dist" + ); await t.throwsAsync(async () => { await tmpl.render(await tmpl.getData()); @@ -671,35 +768,38 @@ test("Override base templating engine should error with bad string", async (t) = }); test("Override base templating engine (bypasses markdown)", async (t) => { - let tmpl = getNewTemplate("./test/stubs/overrides/test-bypass.md", "./test/stubs/", "./dist"); + let tmpl = await getNewTemplate( + "./test/stubs/overrides/test-bypass.md", + "./test/stubs/", + "./dist" + ); t.is((await tmpl.render(await tmpl.getData())).trim(), "# My Title"); }); test("Override base templating engine to (nothing)", async (t) => { - let tmpl = getNewTemplate("./test/stubs/overrides/test-empty.md", "./test/stubs/", "./dist"); + let tmpl = await getNewTemplate( + "./test/stubs/overrides/test-empty.md", + "./test/stubs/", + "./dist" + ); // not parsed - t.is((await tmpl.render(await tmpl.getData())).trim(), "# <%= title %>"); + t.is((await tmpl.render(await tmpl.getData())).trim(), "# {{ title }}"); }); -test("Override base templating engine from .ejs to njk", async (t) => { - let tmpl = getNewTemplate("./test/stubs/overrides/test.ejs", "./test/stubs/", "./dist"); +test("Override base templating engine from .njk to liquid (with a layout that uses njk)", async (t) => { + let tmpl = await getNewTemplate("./test/stubs/overrides/layout.njk", "./test/stubs/", "./dist"); - t.is((await tmpl.render(await tmpl.getData())).trim(), "My Title"); -}); - -test("Override base templating engine from .njk to ejs (with a layout that uses njk)", async (t) => { - let tmpl = getNewTemplate("./test/stubs/overrides/layout.njk", "./test/stubs/", "./dist"); - - t.is( - (await tmpl.render(await tmpl.getData())).trim(), - `

My Title

` - ); + t.is((await tmpl.render(await tmpl.getData())).trim(), `

8

`); }); test("Override base templating engine from .njk to nothing (with a layout that uses njk)", async (t) => { - let tmpl = getNewTemplate("./test/stubs/overrides/layoutfalse.njk", "./test/stubs/", "./dist"); + let tmpl = await getNewTemplate( + "./test/stubs/overrides/layoutfalse.njk", + "./test/stubs/", + "./dist" + ); t.is( (await tmpl.render(await tmpl.getData())).trim(), @@ -708,19 +808,7 @@ test("Override base templating engine from .njk to nothing (with a layout that u }); test("Using a markdown source file (with a layout that uses njk), markdown shouldn’t render in layout file", async (t) => { - let tmpl = getNewTemplate("./test/stubs/overrides/test.md", "./test/stubs/", "./dist"); - - t.is( - normalizeNewLines((await tmpl.render(await tmpl.getData())).trim()), - `# Layout header - -

My Title

-
` - ); -}); - -test("Override base templating engine from .md to ejs,md (with a layout that uses njk), markdown shouldn’t render in layout file", async (t) => { - let tmpl = getNewTemplate("./test/stubs/overrides/test2.md", "./test/stubs/", "./dist"); + let tmpl = await getNewTemplate("./test/stubs/overrides/test.md", "./test/stubs/", "./dist"); t.is( normalizeNewLines((await tmpl.render(await tmpl.getData())).trim()), @@ -732,7 +820,7 @@ test("Override base templating engine from .md to ejs,md (with a layout that use }); test("renderDirect on a markdown file, permalink should not render markdown", async (t) => { - let tmpl = getNewTemplate("./test/stubs/permalink-markdown.md", "./test/stubs/", "./dist"); + let tmpl = await getNewTemplate("./test/stubs/permalink-markdown.md", "./test/stubs/", "./dist"); let data = await tmpl.getData(); t.is( await tmpl.renderDirect("/news/my-test-file/index.html", {}, true), @@ -743,7 +831,11 @@ test("renderDirect on a markdown file, permalink should not render markdown", as }); test("renderDirect on a markdown file, permalink should not render markdown (with variable)", async (t) => { - let tmpl = getNewTemplate("./test/stubs/permalink-markdown-var.md", "./test/stubs/", "./dist"); + let tmpl = await getNewTemplate( + "./test/stubs/permalink-markdown-var.md", + "./test/stubs/", + "./dist" + ); let data = await tmpl.getData(); t.is( await tmpl.renderDirect("/news/{{ slug }}/index.html", { slug: "my-title" }, true), @@ -754,7 +846,7 @@ test("renderDirect on a markdown file, permalink should not render markdown (wit }); test("renderDirect on a markdown file, permalink should not render markdown (has override)", async (t) => { - let tmpl = getNewTemplate( + let tmpl = await getNewTemplate( "./test/stubs/permalink-markdown-override.md", "./test/stubs/", "./dist" @@ -772,7 +864,11 @@ test("renderDirect on a markdown file, permalink should not render markdown (has test("Test a transform", async (t) => { t.plan(2); - let tmpl = getNewTemplate("./test/stubs/template.ejs", "./test/stubs/", "./test/stubs/_site"); + let tmpl = await getNewTemplate( + "./test/stubs/template.liquid", + "./test/stubs/", + "./test/stubs/_site" + ); tmpl.addTransform("transformName", function (content, outputPath) { t.true(outputPath.endsWith(".html")); @@ -787,7 +883,11 @@ test("Test a transform", async (t) => { test("Test a transform (does it have this.inputPath?)", async (t) => { t.plan(3); - let tmpl = getNewTemplate("./test/stubs/template.ejs", "./test/stubs/", "./test/stubs/_site"); + let tmpl = await getNewTemplate( + "./test/stubs/template.liquid", + "./test/stubs/", + "./test/stubs/_site" + ); tmpl.addTransform("transformName", function (content, outputPath) { t.true(outputPath.endsWith(".html")); @@ -802,7 +902,7 @@ test("Test a transform (does it have this.inputPath?)", async (t) => { test("Test a transform with pages", async (t) => { t.plan(5); - let tmpl = getNewTemplate( + let tmpl = await getNewTemplate( "./test/stubs/transform-pages/template.njk", "./test/stubs/", "./test/stubs/_site" @@ -822,7 +922,7 @@ test("Test a transform with pages", async (t) => { test("Test a transform with a layout", async (t) => { t.plan(3); - let tmpl = getNewTemplate( + let tmpl = await getNewTemplate( "./test/stubs-475/transform-layout/transform-layout.njk", "./test/stubs-475/", "./test/stubs-475/_site" @@ -841,7 +941,11 @@ test("Test a transform with a layout", async (t) => { test("Test a single asynchronous transform", async (t) => { t.plan(2); - let tmpl = getNewTemplate("./test/stubs/template.ejs", "./test/stubs/", "./test/stubs/_site"); + let tmpl = await getNewTemplate( + "./test/stubs/template.liquid", + "./test/stubs/", + "./test/stubs/_site" + ); tmpl.addTransform("transformName", async function (content, outputPath) { t.true(outputPath.endsWith("template/index.html")); @@ -860,7 +964,11 @@ test("Test a single asynchronous transform", async (t) => { test("Test multiple asynchronous transforms", async (t) => { t.plan(3); - let tmpl = getNewTemplate("./test/stubs/template.ejs", "./test/stubs/", "./test/stubs/_site"); + let tmpl = await getNewTemplate( + "./test/stubs/template.liquid", + "./test/stubs/", + "./test/stubs/_site" + ); tmpl.addTransform("transformName", async function (content, outputPath) { t.true(outputPath.endsWith("template/index.html")); @@ -890,7 +998,7 @@ test("Test multiple asynchronous transforms", async (t) => { test("Test a linter", async (t) => { t.plan(4); - let tmpl = getNewTemplate( + let tmpl = await getNewTemplate( "./test/stubs/transform-pages/template.njk", "./test/stubs/", "./test/stubs/_site" @@ -905,7 +1013,7 @@ test("Test a linter", async (t) => { }); test("Front Matter Tags (Single)", async (t) => { - let tmpl = getNewTemplate( + let tmpl = await getNewTemplate( "./test/stubs/templatetest-frontmatter/single.njk", "./test/stubs/", "dist" @@ -921,7 +1029,7 @@ test("Front Matter Tags (Single)", async (t) => { }); test("Front Matter Tags (Multiple)", async (t) => { - let tmpl = getNewTemplate( + let tmpl = await getNewTemplate( "./test/stubs/templatetest-frontmatter/multiple.njk", "./test/stubs/", "dist" @@ -937,7 +1045,11 @@ test("Front Matter Tags (Multiple)", async (t) => { }); test("Front matter date with quotes (liquid), issue #258", async (t) => { - let tmpl = getNewTemplate("./test/stubs/frontmatter-date/test.liquid", "./test/stubs/", "dist"); + let tmpl = await getNewTemplate( + "./test/stubs/frontmatter-date/test.liquid", + "./test/stubs/", + "dist" + ); let data = await tmpl.getData(); t.is(data.mydate.toISOString(), "2009-04-15T11:34:34.000Z"); @@ -947,7 +1059,11 @@ test("Front matter date with quotes (liquid), issue #258", async (t) => { }); test("Front matter date with quotes (njk), issue #258", async (t) => { - let tmpl = getNewTemplate("./test/stubs/frontmatter-date/test.njk", "./test/stubs/", "dist"); + let tmpl = await getNewTemplate( + "./test/stubs/frontmatter-date/test.njk", + "./test/stubs/", + "dist" + ); let data = await tmpl.getData(); t.is(data.mydate.toISOString(), "2009-04-15T00:34:34.000Z"); @@ -960,11 +1076,13 @@ test("Data Cascade (Deep merge)", async (t) => { let eleventyConfig = new TemplateConfig(); // Default changed in 1.0 // eleventyConfig.userConfig.setDataDeepMerge(true); + await eleventyConfig.init(); + let dataObj = new TemplateData("./test/", eleventyConfig); dataObj.setFileSystemSearch(new FileSystemSearch()); await dataObj.getGlobalData(); - let tmpl = getNewTemplate( + let tmpl = await getNewTemplate( "./test/stubs/data-cascade/template.njk", "./test/stubs/", "./dist", @@ -993,11 +1111,13 @@ test("Data Cascade (Shallow merge)", async (t) => { let eleventyConfig = new TemplateConfig(); // Default changed in 1.0 eleventyConfig.userConfig.setDataDeepMerge(false); + await eleventyConfig.init(); + let dataObj = new TemplateData("./test/", eleventyConfig); dataObj.setFileSystemSearch(new FileSystemSearch()); await dataObj.getGlobalData(); - let tmpl = getNewTemplate( + let tmpl = await getNewTemplate( "./test/stubs/data-cascade/template.njk", "./test/stubs/", "./dist", @@ -1026,11 +1146,13 @@ test("Data Cascade Tag Merge (Deep merge)", async (t) => { let eleventyConfig = new TemplateConfig(); // Default changed in 1.0 // eleventyConfig.userConfig.setDataDeepMerge(true); + await eleventyConfig.init(); + let dataObj = new TemplateData("./test/stubs/", eleventyConfig); dataObj.setFileSystemSearch(new FileSystemSearch()); await dataObj.getGlobalData(); - let tmpl = getNewTemplate( + let tmpl = await getNewTemplate( "./test/stubs/data-cascade/template.njk", "./test/stubs/", "./dist", @@ -1047,11 +1169,13 @@ test("Data Cascade Tag Merge (Deep Merge - Deduplication)", async (t) => { let eleventyConfig = new TemplateConfig(); // Default changed in 1.0 // eleventyConfig.userConfig.setDataDeepMerge(true); + await eleventyConfig.init(); + let dataObj = new TemplateData("./test/stubs/", eleventyConfig); dataObj.setFileSystemSearch(new FileSystemSearch()); await dataObj.getGlobalData(); - let tmpl = getNewTemplate( + let tmpl = await getNewTemplate( "./test/stubs/data-cascade/template.njk", "./test/stubs/", "./dist", @@ -1068,11 +1192,13 @@ test("Data Cascade Tag Merge (Shallow merge)", async (t) => { let eleventyConfig = new TemplateConfig(); // Default changed in 1.0 eleventyConfig.userConfig.setDataDeepMerge(false); + await eleventyConfig.init(); + let dataObj = new TemplateData("./test/stubs/", eleventyConfig); dataObj.setFileSystemSearch(new FileSystemSearch()); await dataObj.getGlobalData(); - let tmpl = getNewTemplate( + let tmpl = await getNewTemplate( "./test/stubs/data-cascade/template.njk", "./test/stubs/", "./dist", @@ -1089,11 +1215,13 @@ test('Local data inherits tags string ([tags] vs "tags") Shallow Merge', async ( let eleventyConfig = new TemplateConfig(); // Default changed in 1.0 eleventyConfig.userConfig.setDataDeepMerge(false); + await eleventyConfig.init(); + let dataObj = new TemplateData("./test/stubs/", eleventyConfig); dataObj.setFileSystemSearch(new FileSystemSearch()); await dataObj.getGlobalData(); - let tmpl = getNewTemplate( + let tmpl = await getNewTemplate( "./test/stubs/local-data-tags/component.njk", "./test/stubs/", "./dist", @@ -1108,13 +1236,15 @@ test('Local data inherits tags string ([tags] vs "tags") Shallow Merge', async ( test('Local data inherits tags string ([tags] vs "tags") Deep Merge', async (t) => { let eleventyConfig = new TemplateConfig(); + await eleventyConfig.init(); + // Default changed in 1.0 // eleventyConfig.userConfig.setDataDeepMerge(true); let dataObj = new TemplateData("./test/stubs/", eleventyConfig); dataObj.setFileSystemSearch(new FileSystemSearch()); await dataObj.getGlobalData(); - let tmpl = getNewTemplate( + let tmpl = await getNewTemplate( "./test/stubs/local-data-tags/component.njk", "./test/stubs/", "./dist", @@ -1128,7 +1258,7 @@ test('Local data inherits tags string ([tags] vs "tags") Deep Merge', async (t) }); test("Throws a Premature Template Content Error (njk)", async (t) => { - let tmpl = getNewTemplate( + let tmpl = await getNewTemplate( "./test/stubs/prematureTemplateContent/test.njk", "./test/stubs/", "./test/stubs/_site" @@ -1143,7 +1273,7 @@ test("Throws a Premature Template Content Error (njk)", async (t) => { }); test("Throws a Premature Template Content Error from rendering (njk)", async (t) => { - let tmpl = getNewTemplate( + let tmpl = await getNewTemplate( "./test/stubs/prematureTemplateContent/test.njk", "./test/stubs/", "./test/stubs/_site" @@ -1168,7 +1298,7 @@ test("Throws a Premature Template Content Error from rendering (njk)", async (t) }); test("Throws a Premature Template Content Error (liquid)", async (t) => { - let tmpl = getNewTemplate( + let tmpl = await getNewTemplate( "./test/stubs/prematureTemplateContent/test.liquid", "./test/stubs/", "./test/stubs/_site" @@ -1183,23 +1313,8 @@ test("Throws a Premature Template Content Error (liquid)", async (t) => { }); test("Throws a Premature Template Content Error (11ty.js)", async (t) => { - let tmpl = getNewTemplate( - "./test/stubs/prematureTemplateContent/test.11ty.js", - "./test/stubs/", - "./test/stubs/_site" - ); - - let data = await tmpl.getData(); - let mapEntries = await tmpl.getTemplates(data); - let error = t.throws(() => { - mapEntries[0].templateContent; - }); - t.is(EleventyErrorUtil.isPrematureTemplateContentError(error), true); -}); - -test("Throws a Premature Template Content Error (pug)", async (t) => { - let tmpl = getNewTemplate( - "./test/stubs/prematureTemplateContent/test.pug", + let tmpl = await getNewTemplate( + "./test/stubs/prematureTemplateContent/test.11ty.cjs", "./test/stubs/", "./test/stubs/_site" ); @@ -1212,33 +1327,8 @@ test("Throws a Premature Template Content Error (pug)", async (t) => { t.is(EleventyErrorUtil.isPrematureTemplateContentError(error), true); }); -test("Throws a Premature Template Content Error from rendering (pug)", async (t) => { - let tmpl = getNewTemplate( - "./test/stubs/prematureTemplateContent/test.pug", - "./test/stubs/", - "./test/stubs/_site" - ); - - let data = await tmpl.getData(); - let mapEntries = await tmpl.getTemplateMapEntries(data); - let pageEntries = await tmpl.getTemplates({ - page: {}, - sample: { - get templateContent() { - throw new TemplateContentPrematureUseError( - "Tried to use templateContent too early (test.pug)" - ); - }, - }, - }); - let error = await t.throwsAsync(async () => { - await tmpl.renderPageEntry(mapEntries[0], pageEntries[0]); - }); - t.is(EleventyErrorUtil.isPrematureTemplateContentError(error), true); -}); - test("Throws a Premature Template Content Error (md)", async (t) => { - let tmpl = getNewTemplate( + let tmpl = await getNewTemplate( "./test/stubs/prematureTemplateContent/test.md", "./test/stubs/", "./test/stubs/_site" @@ -1253,7 +1343,7 @@ test("Throws a Premature Template Content Error (md)", async (t) => { }); test("Throws a Premature Template Content Error from rendering (md)", async (t) => { - let tmpl = getNewTemplate( + let tmpl = await getNewTemplate( "./test/stubs/prematureTemplateContent/test.md", "./test/stubs/", "./test/stubs/_site" @@ -1277,93 +1367,12 @@ test("Throws a Premature Template Content Error from rendering (md)", async (t) t.is(EleventyErrorUtil.isPrematureTemplateContentError(error), true); }); -test("Throws a Premature Template Content Error (hbs)", async (t) => { - let tmpl = getNewTemplate( - "./test/stubs/prematureTemplateContent/test.hbs", - "./test/stubs/", - "./test/stubs/_site" - ); - - let data = await tmpl.getData(); - let mapEntries = await tmpl.getTemplates(data); - let error = t.throws(() => { - mapEntries[0].templateContent; - }); - t.is(EleventyErrorUtil.isPrematureTemplateContentError(error), true); -}); - -test("Throws a Premature Template Content Error from rendering (hbs)", async (t) => { - let tmpl = getNewTemplate( - "./test/stubs/prematureTemplateContent/test.hbs", - "./test/stubs/", - "./test/stubs/_site" - ); - - let data = await tmpl.getData(); - let mapEntries = await tmpl.getTemplateMapEntries(data); - let pageEntries = await tmpl.getTemplates({ - page: {}, - sample: { - get templateContent() { - throw new TemplateContentPrematureUseError( - "Tried to use templateContent too early (test.hbs)" - ); - }, - }, - }); - let error = await t.throwsAsync(async () => { - await tmpl.renderPageEntry(mapEntries[0], pageEntries[0]); - }); - t.is(EleventyErrorUtil.isPrematureTemplateContentError(error), true); -}); - -test("Throws a Premature Template Content Error (mustache)", async (t) => { - let tmpl = getNewTemplate( - "./test/stubs/prematureTemplateContent/test.mustache", - "./test/stubs/", - "./test/stubs/_site" - ); - - let data = await tmpl.getData(); - let mapEntries = await tmpl.getTemplates(data); - let error = t.throws(() => { - mapEntries[0].templateContent; - }); - t.is(EleventyErrorUtil.isPrematureTemplateContentError(error), true); -}); - -test("Throws a Premature Template Content Error (ejs)", async (t) => { - let tmpl = getNewTemplate( - "./test/stubs/prematureTemplateContent/test.ejs", - "./test/stubs/", - "./test/stubs/_site" - ); - - let data = await tmpl.getData(); - let mapEntries = await tmpl.getTemplates(data); - let error = t.throws(() => { - mapEntries[0].templateContent; - }); - t.is(EleventyErrorUtil.isPrematureTemplateContentError(error), true); -}); - -test("Throws a Premature Template Content Error (haml)", async (t) => { - let tmpl = getNewTemplate( - "./test/stubs/prematureTemplateContent/test.haml", - "./test/stubs/", - "./test/stubs/_site" - ); - - let data = await tmpl.getData(); - let mapEntries = await tmpl.getTemplates(data); - let error = t.throws(() => { - mapEntries[0].templateContent; - }); - t.is(EleventyErrorUtil.isPrematureTemplateContentError(error), true); -}); - test("Issue 413 weird date format", async (t) => { - let tmpl = getNewTemplate("./test/stubs-413/date-frontmatter.md", "./test/stubs-413/", "./dist"); + let tmpl = await getNewTemplate( + "./test/stubs-413/date-frontmatter.md", + "./test/stubs-413/", + "./dist" + ); let error = await t.throwsAsync(async function () { await tmpl.getData(); @@ -1375,7 +1384,7 @@ test("Issue 413 weird date format", async (t) => { }); test("Custom Front Matter Parsing Options", async (t) => { - let tmpl = getNewTemplate( + let tmpl = await getNewTemplate( "./test/stubs/custom-frontmatter/template.njk", "./test/stubs/", "./dist" @@ -1400,7 +1409,7 @@ This is content.` }); test("Custom Front Matter Parsing Options (using alias)", async (t) => { - let tmpl = getNewTemplate( + let tmpl = await getNewTemplate( "./test/stubs/custom-frontmatter/template.njk", "./test/stubs/", "./dist" @@ -1424,7 +1433,7 @@ This is content.` }); test("Custom Front Matter Parsing Options (no newline before excerpt separator)", async (t) => { - let tmpl = getNewTemplate( + let tmpl = await getNewTemplate( "./test/stubs/custom-frontmatter/template-newline1.njk", "./test/stubs/", "./dist" @@ -1449,7 +1458,7 @@ This is content.` }); test("Custom Front Matter Parsing Options (no newline after excerpt separator)", async (t) => { - let tmpl = getNewTemplate( + let tmpl = await getNewTemplate( "./test/stubs/custom-frontmatter/template-newline3.njk", "./test/stubs/", "./dist" @@ -1467,7 +1476,7 @@ This is content.` }); test("Custom Front Matter Parsing Options (no newlines before or after excerpt separator)", async (t) => { - let tmpl = getNewTemplate( + let tmpl = await getNewTemplate( "./test/stubs/custom-frontmatter/template-newline2.njk", "./test/stubs/", "./dist" @@ -1481,7 +1490,7 @@ test("Custom Front Matter Parsing Options (no newlines before or after excerpt s }); test("Custom Front Matter Parsing Options (html comment separator)", async (t) => { - let tmpl = getNewTemplate( + let tmpl = await getNewTemplate( "./test/stubs/custom-frontmatter/template-excerpt-comment.njk", "./test/stubs/", "./dist" @@ -1505,9 +1514,7 @@ This is content.` test("Custom Front Matter Parsing Options (using TOML)", async (t) => { // Currently fails on Windows, needs https://github.com/jonschlinkert/gray-matter/issues/92 - const TOML = require("@iarna/toml"); - - let tmpl = getNewTemplate( + let tmpl = await getNewTemplate( "./test/stubs/custom-frontmatter/template-toml.njk", "./test/stubs/", "./dist" @@ -1529,7 +1536,11 @@ test("Custom Front Matter Parsing Options (using TOML)", async (t) => { }); test("global variable with dashes Issue #567 (liquid)", async (t) => { - let tmpl = getNewTemplate("./test/stubs/global-dash-variable.liquid", "./test/stubs/", "./dist"); + let tmpl = await getNewTemplate( + "./test/stubs/global-dash-variable.liquid", + "./test/stubs/", + "./dist" + ); let data = await tmpl.getData(); t.is(data["is-it-tasty"], "Yes"); @@ -1539,7 +1550,7 @@ test("global variable with dashes Issue #567 (liquid)", async (t) => { }); test("Issue #446: Layout has a permalink with a different template language than content", async (t) => { - let tmpl = getNewTemplate( + let tmpl = await getNewTemplate( "./test/stubs/layout-permalink-difflang/test.md", "./test/stubs/layout-permalink-difflang/", "dist" @@ -1554,7 +1565,7 @@ test("Issue #446: Layout has a permalink with a different template language than }); test("Get Layout Chain", async (t) => { - let tmpl = getNewTemplate( + let tmpl = await getNewTemplate( "./test/stubs-incremental/layout-chain/test.njk", "./test/stubs-incremental/layout-chain/", "./dist" @@ -1571,8 +1582,9 @@ test("Get Layout Chain", async (t) => { test("Engine Singletons", async (t) => { let eleventyConfig = new TemplateConfig(); + await eleventyConfig.init(); let map = new EleventyExtensionMap(["njk"], eleventyConfig); - let tmpl1 = getNewTemplate( + let tmpl1 = await getNewTemplate( "./test/stubs/engine-singletons/first.njk", "./test/stubs/engine-singletons/", "./dist", @@ -1580,7 +1592,7 @@ test("Engine Singletons", async (t) => { map, eleventyConfig ); - let tmpl2 = getNewTemplate( + let tmpl2 = await getNewTemplate( "./test/stubs/engine-singletons/second.njk", "./test/stubs/engine-singletons/", "./dist", @@ -1597,7 +1609,7 @@ test("Make sure layout cache takes new changes during watch (nunjucks)", async ( await fsp.writeFile(filePath, `alert("hi");`, { encoding: "utf8" }); - let tmpl = getNewTemplate( + let tmpl = await getNewTemplate( "./test/stubs-layout-cache/test.njk", "./test/stubs-layout-cache/", "./dist" @@ -1618,7 +1630,7 @@ test("Make sure layout cache takes new changes during watch (liquid)", async (t) let filePath = "./test/stubs-layout-cache/_includes/include-script-2.js"; await fsp.writeFile(filePath, `alert("hi");`, { encoding: "utf8" }); - let tmpl = getNewTemplate( + let tmpl = await getNewTemplate( "./test/stubs-layout-cache/test.liquid", "./test/stubs-layout-cache/", "./dist" @@ -1637,9 +1649,7 @@ test("Make sure layout cache takes new changes during watch (liquid)", async (t) test("Add Extension via Configuration (txt file)", async (t) => { let eleventyConfig = new TemplateConfig(); - eleventyConfig.userConfig.extensionMap.add({ - extension: "txt", - key: "txt", + eleventyConfig.userConfig.addExtension("txt", { isIncrementalMatch: function (incrementalFilePath) { // do some kind of check return this.inputPath === incrementalFilePath; @@ -1651,9 +1661,10 @@ test("Add Extension via Configuration (txt file)", async (t) => { }; }, }); + await eleventyConfig.init(); let map = new EleventyExtensionMap([], eleventyConfig); - let tmpl = getNewTemplate( + let tmpl = await getNewTemplate( "./test/stubs/default.txt", "./test/stubs/", "./dist", @@ -1688,7 +1699,7 @@ test("Add Extension via Configuration (txt file)", async (t) => { }); test("permalink object with build", async (t) => { - let tmpl = getNewTemplate( + let tmpl = await getNewTemplate( "./test/stubs/permalink-build/permalink-build.md", "./test/stubs/", "./test/stubs/_site" @@ -1698,40 +1709,13 @@ test("permalink object with build", async (t) => { t.is(await tmpl.getOutputHref(data), "/url/"); }); -test("permalink object without build", async (t) => { - let tmpl = getNewTemplate( - "./test/stubs/permalink-nobuild/permalink-nobuild.md", - "./test/stubs/", - "./test/stubs/_site" - ); - let data = await tmpl.getData(); - t.is(await tmpl.getRawOutputPath(data), false); - t.is(await tmpl.getOutputPath(data), false); - t.is(await tmpl.getOutputHref(data), "/url/"); -}); - test("permalink object _getLink", async (t) => { - let tmpl = getNewTemplate( + let tmpl = await getNewTemplate( "./test/stubs/permalink-nobuild/permalink-nobuild.md", "./test/stubs/", "./test/stubs/_site" ); - let link = await tmpl._getLink({ - permalink: { - serverless: "/serverless/", - }, - }); - t.is(await link.toOutputPath(), false); - t.is(await link.toHref(), "/serverless/"); - - t.deepEqual(link.getServerlessUrls(), { - serverless: "/serverless/", - }); - t.deepEqual(tmpl.getServerlessUrls(), { - serverless: "/serverless/", - }); - let link2 = await tmpl._getLink({ permalink: { build: "/build/", @@ -1739,68 +1723,10 @@ test("permalink object _getLink", async (t) => { }); t.is(await link2.toOutputPath(), "/build/index.html"); t.is(await link2.toHref(), "/build/"); - t.deepEqual(link2.getServerlessUrls(), {}); - t.deepEqual(tmpl.getServerlessUrls(), {}); - - let link3 = await tmpl._getLink({ - permalink: { - build: "/build/", - serverless: "/serverless/", - }, - }); - t.is(await link3.toOutputPath(), "/build/index.html"); - t.is(await link3.toHref(), "/build/"); - t.deepEqual(link3.getServerlessUrls(), { - serverless: "/serverless/", - }); - t.deepEqual(tmpl.getServerlessUrls(), { - serverless: "/serverless/", - }); - - // template syntax - let link4 = await tmpl._getLink({ - test: "a", - permalink: { - build: "/build{{ test }}/", - serverless: "/serverless{{ test }}/", - }, - }); - t.is(await link4.toOutputPath(), "/builda/index.html"); - t.is(await link4.toHref(), "/builda/"); - t.deepEqual(link4.getServerlessUrls(), { - serverless: "/serverlessa/", - }); - t.deepEqual(tmpl.getServerlessUrls(), { - serverless: "/serverlessa/", - }); }); -test("permalink object _getLink (array of serverless URLs)", async (t) => { - let tmpl = getNewTemplate( - "./test/stubs/permalink-nobuild/permalink-nobuild.md", - "./test/stubs/", - "./test/stubs/_site" - ); - - // Array of URLs is supported - let link4 = await tmpl._getLink({ - permalink: { - serverless: ["/serverless1/", "/serverless2/"], - }, - }); - t.is(await link4.toOutputPath(), false); - t.is(await link4.toHref(), "/serverless1/"); - - t.deepEqual(link4.getServerlessUrls(), { - serverless: ["/serverless1/", "/serverless2/"], - }); - t.deepEqual(tmpl.getServerlessUrls(), { - serverless: ["/serverless1/", "/serverless2/"], - }); -}); - -test("permalink object _getLink (array of serverless URLs with template syntax)", async (t) => { - let tmpl = getNewTemplate( +test("permalink object _getLink (array of invalid, previously serverless URLs)", async (t) => { + let tmpl = await getNewTemplate( "./test/stubs/permalink-nobuild/permalink-nobuild.md", "./test/stubs/", "./test/stubs/_site" @@ -1810,76 +1736,15 @@ test("permalink object _getLink (array of serverless URLs with template syntax)" let link = await tmpl._getLink({ test: "a", permalink: { - serverless: ["/serverless1{{ test }}/", "/serverless2{{ test }}/"], + someotherkey: [], }, }); t.is(await link.toOutputPath(), false); - t.is(await link.toHref(), "/serverless1a/"); - - t.deepEqual(link.getServerlessUrls(), { - serverless: ["/serverless1a/", "/serverless2a/"], - }); - t.deepEqual(tmpl.getServerlessUrls(), { - serverless: ["/serverless1a/", "/serverless2a/"], - }); -}); - -test("Do not resolve page.url from eleventy serverless data", async (t) => { - let tmpl = getNewTemplate( - "./test/stubs/permalink-build-serverless/permalink-build-serverless.md", - "./test/stubs/", - "./test/stubs/_site" - ); - let fakeData = { - permalink: { - serverless: "/serverless/", - }, - }; - let outputHref = await tmpl.getOutputHref(fakeData); - t.is(outputHref, "/serverless/"); - - let outputLink = await tmpl.getRawOutputPath(fakeData); - t.is(outputLink, false); - - let outputPath = await tmpl.getOutputPath(fakeData); - t.is(outputPath, false); - - let { href, rawPath, path } = await tmpl.getOutputLocations(fakeData); - t.is(href, "/serverless/"); - t.is(rawPath, false); - t.is(path, false); -}); - -test("Do not override page.url with serverless url", async (t) => { - let tmpl = getNewTemplate( - "./test/stubs/permalink-build-serverless/permalink-build-serverless.md", - "./test/stubs/", - "./test/stubs/_site" - ); - let fakeData = { - permalink: { - build: "/build/", - serverless: "/serverless/", - }, - }; - - let outputHref = await tmpl.getOutputHref(fakeData); - t.is(outputHref, "/build/"); - - let outputLink = await tmpl.getRawOutputPath(fakeData); - t.is(outputLink, "/build/index.html"); - - let outputPath = await tmpl.getOutputPath(fakeData); - t.is(outputPath, "./test/stubs/_site/build/index.html"); - - let { href, rawPath, path } = await tmpl.getOutputLocations(fakeData); - t.is(href, "/build/"); - t.is(rawPath, "/build/index.html"); - t.is(path, "./test/stubs/_site/build/index.html"); + t.is(await link.toHref(), false); }); test("Permalink is an object but an empty object (inherit default behavior)", async (t) => { - let tmpl = getNewTemplate( + let tmpl = await getNewTemplate( "./test/stubs/permalink-empty-object/empty-object.md", "./test/stubs/", "./test/stubs/_site" @@ -1901,22 +1766,9 @@ test("Permalink is an object but an empty object (inherit default behavior)", as t.is(path, "./test/stubs/_site/permalink-empty-object/empty-object/index.html"); }); -test("permalink function returns serverless object Issue #1898", async (t) => { - let tmpl = getNewTemplate( - "./test/stubs/stubs-computed-permalink//object.11ty.js", - "./test/stubs/stubs-computed-permalink/", - "./test/stubs/stubs-computed-permalink/_site" - ); - let data = await tmpl.getData(); - let [page] = await tmpl.getTemplates(data); - - t.is(page.url, "/i18n/en/"); - t.is(page.outputPath, false); -}); - test("eleventyComputed returns permalink object Issue #1898", async (t) => { - let tmpl = getNewTemplate( - "./test/stubs/stubs-computed-permalink/eleventycomputed-object.11ty.js", + let tmpl = await getNewTemplate( + "./test/stubs/stubs-computed-permalink/eleventycomputed-object.11ty.cjs", "./test/stubs/stubs-computed-permalink/", "./test/stubs/stubs-computed-permalink/_site" ); @@ -1925,12 +1777,12 @@ test("eleventyComputed returns permalink object Issue #1898", async (t) => { let [page] = await tmpl.getTemplates(data); t.is(page.url, "/i18n/en/"); - t.is(page.outputPath, false); + t.is(page.outputPath, "./test/stubs/stubs-computed-permalink/_site/i18n/en/index.html"); }); test("eleventyComputed returns nested permalink object Issue #1898", async (t) => { - let tmpl = getNewTemplate( - "./test/stubs/stubs-computed-permalink/eleventycomputed-nested-object.11ty.js", + let tmpl = await getNewTemplate( + "./test/stubs/stubs-computed-permalink/eleventycomputed-nested-object.11ty.cjs", "./test/stubs/stubs-computed-permalink/", "./test/stubs/stubs-computed-permalink/_site" ); @@ -1939,12 +1791,12 @@ test("eleventyComputed returns nested permalink object Issue #1898", async (t) = let [page] = await tmpl.getTemplates(data); t.is(page.url, "/i18n/en/"); - t.is(page.outputPath, false); + t.is(page.outputPath, "./test/stubs/stubs-computed-permalink/_site/i18n/en/index.html"); }); test("eleventyComputed returns permalink object using permalink string (with replace) Issue #1898", async (t) => { - let tmpl = getNewTemplate( - "./test/stubs/stubs-computed-permalink/eleventycomputed-object-replace.11ty.js", + let tmpl = await getNewTemplate( + "./test/stubs/stubs-computed-permalink/eleventycomputed-object-replace.11ty.cjs", "./test/stubs/stubs-computed-permalink/", "./test/stubs/stubs-computed-permalink/_site" ); @@ -1953,11 +1805,11 @@ test("eleventyComputed returns permalink object using permalink string (with rep let [page] = await tmpl.getTemplates(data); t.is(page.url, "/i18n/en/"); - t.is(page.outputPath, false); + t.is(page.outputPath, "./test/stubs/stubs-computed-permalink/_site/i18n/en/index.html"); }); test("page.templateSyntax works with templateEngineOverride", async (t) => { - let tmpl = getNewTemplate( + let tmpl = await getNewTemplate( "./test/stubs/overrides/page-templatesyntax.md", "./test/stubs/", "./dist" @@ -1969,16 +1821,14 @@ test("page.templateSyntax works with templateEngineOverride", async (t) => { // Inspired by https://github.com/11ty/eleventy/pull/1691 test("Error messaging, returning literals (not objects) from custom data extension", async (t) => { let eleventyConfig = new TemplateConfig(); + eleventyConfig.userConfig.addDataExtension("txt", { + parser: (s) => s, + }); + await eleventyConfig.init(); + let dataObj = new TemplateData("./test/stubs-1691/", eleventyConfig); - dataObj.config.dataExtensions = new Map([ - [ - "txt", - { - parser: (s) => s, - }, - ], - ]); - let tmpl = getNewTemplate( + + let tmpl = await getNewTemplate( "./test/stubs-1691/template.njk", "./test/stubs-1691/", "dist", diff --git a/test/TemplateTest_Permalink.js b/test/TemplateTest_Permalink.js index e46778569..43e1b45fc 100644 --- a/test/TemplateTest_Permalink.js +++ b/test/TemplateTest_Permalink.js @@ -1,9 +1,9 @@ -const test = require("ava"); -const fs = require("fs"); -const TemplateConfig = require("../src/TemplateConfig"); -const TemplateData = require("../src/TemplateData"); +import test from "ava"; +import fs from "fs"; -const getNewTemplate = require("./_getNewTemplateForTests"); +import TemplateConfig from "../src/TemplateConfig.js"; +import TemplateData from "../src/TemplateData.js"; +import getNewTemplate from "./_getNewTemplateForTests.js"; async function writeMapEntries(mapEntries) { let promises = []; @@ -33,7 +33,7 @@ async function getTemplateMapEntriesWithContent(template, data) { } test("permalink: false", async (t) => { - let tmpl = getNewTemplate( + let tmpl = await getNewTemplate( "./test/stubs/permalink-false/test.md", "./test/stubs/", "./test/stubs/_site" @@ -61,7 +61,7 @@ test("permalink: false", async (t) => { }); test("permalink: false inside of eleventyComputed, Issue #1754", async (t) => { - let tmpl = getNewTemplate( + let tmpl = await getNewTemplate( "./test/stubs/permalink-false-computed/test.md", "./test/stubs/", "./test/stubs/_site" @@ -87,7 +87,7 @@ test("permalink: false inside of eleventyComputed, Issue #1754", async (t) => { }); test("permalink: true", async (t) => { - let tmpl = getNewTemplate( + let tmpl = await getNewTemplate( "./test/stubs/permalink-true/permalink-true.md", "./test/stubs/", "./test/stubs/_site" @@ -100,7 +100,7 @@ test("permalink: true", async (t) => { }); test("Disable dynamic permalinks", async (t) => { - let tmpl = getNewTemplate( + let tmpl = await getNewTemplate( "./test/stubs/dynamic-permalink/test.njk", "./test/stubs/", "./test/stubs/_site" @@ -114,7 +114,7 @@ test("Disable dynamic permalinks", async (t) => { }); test("Permalink with variables!", async (t) => { - let tmpl = getNewTemplate("./test/stubs/permalinkdata.njk", "./test/stubs/", "./dist"); + let tmpl = await getNewTemplate("./test/stubs/permalinkdata.njk", "./test/stubs/", "./dist"); let data = await tmpl.getData(); @@ -122,13 +122,13 @@ test("Permalink with variables!", async (t) => { }); test("Permalink with variables and JS front matter!", async (t) => { - let tmpl = getNewTemplate("./test/stubs/permalinkdata-jsfn.njk", "./test/stubs/", "./dist"); + let tmpl = await getNewTemplate("./test/stubs/permalinkdata-jsfn.njk", "./test/stubs/", "./dist"); let data = await tmpl.getData(); t.is(await tmpl.getOutputPath(data), "./dist/subdir/slug/index.html"); }); test("Use a JavaScript function for permalink in any template language", async (t) => { - let tmpl = getNewTemplate( + let tmpl = await getNewTemplate( "./test/stubs/permalinkdata-jspermalinkfn.njk", "./test/stubs/", "./dist" @@ -139,13 +139,13 @@ test("Use a JavaScript function for permalink in any template language", async ( }); test("Permalink with dates!", async (t) => { - let tmpl = getNewTemplate("./test/stubs/permalinkdate.liquid", "./test/stubs/", "./dist"); + let tmpl = await getNewTemplate("./test/stubs/permalinkdate.liquid", "./test/stubs/", "./dist"); let data = await tmpl.getData(); t.is(await tmpl.getOutputPath(data), "./dist/2016/01/01/index.html"); }); test.skip("Permalink with dates on file name regex!", async (t) => { - let tmpl = getNewTemplate( + let tmpl = await getNewTemplate( "./test/stubs/2016-02-01-permalinkdate.liquid", "./test/stubs/", "./dist" @@ -156,8 +156,10 @@ test.skip("Permalink with dates on file name regex!", async (t) => { test("Reuse permalink in directory specific data file", async (t) => { let eleventyConfig = new TemplateConfig(); + await eleventyConfig.init(); + let dataObj = new TemplateData("./test/stubs/", eleventyConfig); - let tmpl = getNewTemplate( + let tmpl = await getNewTemplate( "./test/stubs/reuse-permalink/test1.liquid", "./test/stubs/", "./dist", @@ -168,19 +170,27 @@ test("Reuse permalink in directory specific data file", async (t) => { }); test("Using slugify filter!", async (t) => { - let tmpl = getNewTemplate("./test/slugify-filter/test.njk", "./test/slugify-filter/", "./dist"); + let tmpl = await getNewTemplate( + "./test/slugify-filter/test.njk", + "./test/slugify-filter/", + "./dist" + ); let data = await tmpl.getData(); t.is(await tmpl.getOutputPath(data), "./dist/subdir/slug-love-candidate-lyublyu/index.html"); }); test("Using slugify filter with comma and apostrophe", async (t) => { - let tmpl = getNewTemplate("./test/slugify-filter/comma.njk", "./test/slugify-filter/", "./dist"); + let tmpl = await getNewTemplate( + "./test/slugify-filter/comma.njk", + "./test/slugify-filter/", + "./dist" + ); let data = await tmpl.getData(); t.is(await tmpl.getOutputPath(data), "./dist/subdir/hi-i-m-zach/index.html"); }); test("Using slug filter with options params", async (t) => { - let tmpl = getNewTemplate( + let tmpl = await getNewTemplate( "./test/slugify-filter/slug-options.njk", "./test/slugify-filter/", "./dist" @@ -190,7 +200,7 @@ test("Using slug filter with options params", async (t) => { }); test("Using slugify filter with options params", async (t) => { - let tmpl = getNewTemplate( + let tmpl = await getNewTemplate( "./test/slugify-filter/slugify-options.njk", "./test/slugify-filter/", "./dist" @@ -200,7 +210,7 @@ test("Using slugify filter with options params", async (t) => { }); test("Using slugify filter with a number #854", async (t) => { - let tmpl = getNewTemplate( + let tmpl = await getNewTemplate( "./test/slugify-filter/slugify-number.njk", "./test/slugify-filter/", "./dist" @@ -210,7 +220,7 @@ test("Using slugify filter with a number #854", async (t) => { }); test("Using slug filter with a number #854", async (t) => { - let tmpl = getNewTemplate( + let tmpl = await getNewTemplate( "./test/slugify-filter/slug-number.njk", "./test/slugify-filter/", "./dist" @@ -220,7 +230,7 @@ test("Using slug filter with a number #854", async (t) => { }); test.skip("Using slugify filter with multibyte", async (t) => { - let tmpl = getNewTemplate( + let tmpl = await getNewTemplate( "./test/slugify-filter/multibyte.njk", "./test/slugify-filter/", "./dist" diff --git a/test/TemplateWriterTest.js b/test/TemplateWriterTest.js index b9d0a4d35..52bcbac1f 100644 --- a/test/TemplateWriterTest.js +++ b/test/TemplateWriterTest.js @@ -1,36 +1,38 @@ -const test = require("ava"); -const fs = require("fs"); -const { rimrafSync } = require("rimraf"); -const fastglob = require("fast-glob"); -const path = require("path"); -const EleventyFiles = require("../src/EleventyFiles"); -const EleventyExtensionMap = require("../src/EleventyExtensionMap"); -const TemplateWriter = require("../src/TemplateWriter"); -const TemplateConfig = require("../src/TemplateConfig"); -const normalizeNewLines = require("./Util/normalizeNewLines"); - -const getRenderedTmpls = require("./_getRenderedTemplates"); +import test from "ava"; +import fs from "fs"; +import { rimrafSync } from "rimraf"; +import fastglob from "fast-glob"; +import path from "path"; + +import EleventyFiles from "../src/EleventyFiles.js"; +import EleventyExtensionMap from "../src/EleventyExtensionMap.js"; +import TemplateWriter from "../src/TemplateWriter.js"; +import TemplateConfig from "../src/TemplateConfig.js"; +import normalizeNewLines from "./Util/normalizeNewLines.js"; +import getRenderedTmpls from "./_getRenderedTemplates.js"; // TODO make sure if output is a subdir of input dir that they don’t conflict. test("Output is a subdir of input", async (t) => { let eleventyConfig = new TemplateConfig(); + await eleventyConfig.init(); + let tw = new TemplateWriter( "./test/stubs/writeTest", "./test/stubs/writeTest/_writeTestSite", - ["ejs", "md"], + ["liquid", "md"], null, eleventyConfig ); let evf = new EleventyFiles( "./test/stubs/writeTest", "./test/stubs/writeTest/_writeTestSite", - ["ejs", "md"], + ["liquid", "md"], eleventyConfig ); evf.init(); let files = await fastglob(evf.getFileGlobs()); - t.deepEqual(evf.getRawFiles(), ["./test/stubs/writeTest/**/*.{ejs,md}"]); + t.deepEqual(evf.getRawFiles(), ["./test/stubs/writeTest/**/*.{liquid,md}"]); t.true(files.length > 0); let { template: tmpl } = tw._createTemplate(files[0]); @@ -42,10 +44,12 @@ test("Output is a subdir of input", async (t) => { test("_createTemplateMap", async (t) => { let eleventyConfig = new TemplateConfig(); + await eleventyConfig.init(); + let tw = new TemplateWriter( "./test/stubs/writeTest", "./test/stubs/_writeTestSite", - ["ejs", "md"], + ["liquid", "md"], null, eleventyConfig ); @@ -63,10 +67,12 @@ test("_createTemplateMap", async (t) => { test("_createTemplateMap (no leading dot slash)", async (t) => { let eleventyConfig = new TemplateConfig(); + await eleventyConfig.init(); + let tw = new TemplateWriter( "test/stubs/writeTest", "test/stubs/_writeTestSite", - ["ejs", "md"], + ["liquid", "md"], null, eleventyConfig ); @@ -78,6 +84,8 @@ test("_createTemplateMap (no leading dot slash)", async (t) => { test("_testGetCollectionsData", async (t) => { let eleventyConfig = new TemplateConfig(); + await eleventyConfig.init(); + let tw = new TemplateWriter( "./test/stubs/collection", "./test/stubs/_site", @@ -97,6 +105,8 @@ test("_testGetCollectionsData", async (t) => { // TODO remove this (used by other test things) test("_testGetAllTags", async (t) => { let eleventyConfig = new TemplateConfig(); + await eleventyConfig.init(); + let tw = new TemplateWriter( "./test/stubs/collection", "./test/stubs/_site", @@ -114,6 +124,8 @@ test("_testGetAllTags", async (t) => { test("Collection of files sorted by date", async (t) => { let eleventyConfig = new TemplateConfig(); + await eleventyConfig.init(); + let tw = new TemplateWriter( "./test/stubs/dates", "./test/stubs/_site", @@ -130,6 +142,8 @@ test("Collection of files sorted by date", async (t) => { test("__testGetCollectionsData with custom collection (ascending)", async (t) => { let eleventyConfig = new TemplateConfig(); + await eleventyConfig.init(); + let tw = new TemplateWriter( "./test/stubs/collection2", "./test/stubs/_site", @@ -154,6 +168,8 @@ test("__testGetCollectionsData with custom collection (ascending)", async (t) => test("__testGetCollectionsData with custom collection (descending)", async (t) => { let eleventyConfig = new TemplateConfig(); + await eleventyConfig.init(); + let tw = new TemplateWriter( "./test/stubs/collection2", "./test/stubs/_site", @@ -178,6 +194,8 @@ test("__testGetCollectionsData with custom collection (descending)", async (t) = test("__testGetCollectionsData with custom collection (filter only to markdown input)", async (t) => { let eleventyConfig = new TemplateConfig(); + await eleventyConfig.init(); + let tw = new TemplateWriter( "./test/stubs/collection2", "./test/stubs/_site", @@ -203,6 +221,8 @@ test("__testGetCollectionsData with custom collection (filter only to markdown i test("Pagination with a Collection", async (t) => { let eleventyConfig = new TemplateConfig(); + await eleventyConfig.init(); + let tw = new TemplateWriter( "./test/stubs/paged/collection", "./test/stubs/_site", @@ -231,6 +251,8 @@ test("Pagination with a Collection", async (t) => { test("Pagination with a Collection from another Paged Template", async (t) => { let eleventyConfig = new TemplateConfig(); + await eleventyConfig.init(); + let tw = new TemplateWriter( "./test/stubs/paged/cfg-collection-tag-cfg-collection", "./test/stubs/_site", @@ -261,6 +283,8 @@ test("Pagination with a Collection from another Paged Template", async (t) => { test("Pagination with a Collection (apply all pages to collections)", async (t) => { let eleventyConfig = new TemplateConfig(); + await eleventyConfig.init(); + let tw = new TemplateWriter( "./test/stubs/paged/collection-apply-to-all", "./test/stubs/_site", @@ -310,10 +334,12 @@ test("Pagination with a Collection (apply all pages to collections)", async (t) test("Use a collection inside of a template", async (t) => { let eleventyConfig = new TemplateConfig(); + await eleventyConfig.init(); + let tw = new TemplateWriter( "./test/stubs/collection-template", "./test/stubs/collection-template/_site", - ["ejs"], + ["liquid"], null, eleventyConfig ); @@ -325,12 +351,14 @@ test("Use a collection inside of a template", async (t) => { t.is(collectionsData.dog.length, 1); let mapEntry = templateMap.getMapEntryForInputPath( - "./test/stubs/collection-template/template.ejs" + "./test/stubs/collection-template/template.liquid" ); t.truthy(mapEntry); - t.is(mapEntry.inputPath, "./test/stubs/collection-template/template.ejs"); + t.is(mapEntry.inputPath, "./test/stubs/collection-template/template.liquid"); - let { template: mainTmpl } = tw._createTemplate("./test/stubs/collection-template/template.ejs"); + let { template: mainTmpl } = tw._createTemplate( + "./test/stubs/collection-template/template.liquid" + ); let data = await mainTmpl.getData(); let outputPath = await mainTmpl.getOutputPath(data); t.is(outputPath, "./test/stubs/collection-template/_site/template/index.html"); @@ -351,10 +379,12 @@ Template 1 dog` test("Use a collection inside of a layout", async (t) => { let eleventyConfig = new TemplateConfig(); + await eleventyConfig.init(); + let tw = new TemplateWriter( "./test/stubs/collection-layout", "./test/stubs/collection-layout/_site", - ["ejs"], + ["liquid"], null, eleventyConfig ); @@ -365,11 +395,13 @@ test("Use a collection inside of a layout", async (t) => { let collectionsData = await templateMap._testGetCollectionsData(); t.is(collectionsData.dog.length, 1); - let mapEntry = templateMap.getMapEntryForInputPath("./test/stubs/collection-layout/template.ejs"); + let mapEntry = templateMap.getMapEntryForInputPath( + "./test/stubs/collection-layout/template.liquid" + ); t.truthy(mapEntry); - t.is(mapEntry.inputPath, "./test/stubs/collection-layout/template.ejs"); + t.is(mapEntry.inputPath, "./test/stubs/collection-layout/template.liquid"); - let { template: mainTmpl } = tw._createTemplate("./test/stubs/collection-layout/template.ejs"); + let { template: mainTmpl } = tw._createTemplate("./test/stubs/collection-layout/template.liquid"); let data = await mainTmpl.getData(); let outputPath = await mainTmpl.getOutputPath(data); t.is(outputPath, "./test/stubs/collection-layout/_site/template/index.html"); @@ -388,8 +420,10 @@ Layout 1 dog` ); }); -test("Glob Watcher Files with Passthroughs", (t) => { +test("Glob Watcher Files with Passthroughs", async (t) => { let eleventyConfig = new TemplateConfig(); + await eleventyConfig.init(); + let tw = new TemplateWriter( "test/stubs", "test/stubs/_site", @@ -404,6 +438,8 @@ test("Pagination and TemplateContent", async (t) => { rimrafSync("./test/stubs/pagination-templatecontent/_site/"); let eleventyConfig = new TemplateConfig(); + await eleventyConfig.init(); + let tw = new TemplateWriter( "./test/stubs/pagination-templatecontent", "./test/stubs/pagination-templatecontent/_site", @@ -427,6 +463,8 @@ test("Pagination and TemplateContent", async (t) => { test("Custom collection returns array", async (t) => { let eleventyConfig = new TemplateConfig(); + await eleventyConfig.init(); + let tw = new TemplateWriter( "./test/stubs/collection2", "./test/stubs/_site", @@ -451,6 +489,8 @@ test("Custom collection returns array", async (t) => { test("Custom collection returns a string", async (t) => { let eleventyConfig = new TemplateConfig(); + await eleventyConfig.init(); + let tw = new TemplateWriter( "./test/stubs/collection2", "./test/stubs/_site", @@ -471,6 +511,8 @@ test("Custom collection returns a string", async (t) => { test("Custom collection returns an object", async (t) => { let eleventyConfig = new TemplateConfig(); + await eleventyConfig.init(); + let tw = new TemplateWriter( "./test/stubs/collection2", "./test/stubs/_site", @@ -491,6 +533,8 @@ test("Custom collection returns an object", async (t) => { test("fileSlug should exist in a collection", async (t) => { let eleventyConfig = new TemplateConfig(); + await eleventyConfig.init(); + let tw = new TemplateWriter( "./test/stubs/collection-slug", "./test/stubs/collection-slug/_site", @@ -515,6 +559,8 @@ test("fileSlug should exist in a collection", async (t) => { test("Write Test 11ty.js", async (t) => { let eleventyConfig = new TemplateConfig(); + await eleventyConfig.init(); + let tw = new TemplateWriter( "./test/stubs/writeTestJS", "./test/stubs/_writeTestJSSite", @@ -531,8 +577,8 @@ test("Write Test 11ty.js", async (t) => { evf.init(); let files = await fastglob(evf.getFileGlobs()); - t.deepEqual(evf.getRawFiles(), ["./test/stubs/writeTestJS/**/*.{11ty.js,11ty.cjs}"]); - t.deepEqual(files, ["./test/stubs/writeTestJS/test.11ty.js"]); + t.deepEqual(evf.getRawFiles(), ["./test/stubs/writeTestJS/**/*.{11ty.js,11ty.cjs,11ty.mjs}"]); + t.deepEqual(files, ["./test/stubs/writeTestJS/test.11ty.cjs"]); let { template: tmpl } = tw._createTemplate(files[0]); let data = await tmpl.getData(); @@ -642,6 +688,7 @@ test("Passthrough file output", async (t) => { outputPath: "./js/", }, }; + await eleventyConfig.init(); let tw = new TemplateWriter( "./test/stubs/template-passthrough/", diff --git a/test/TestUtilityTest.js b/test/TestUtilityTest.js index c5247bad8..7f4301434 100644 --- a/test/TestUtilityTest.js +++ b/test/TestUtilityTest.js @@ -1,5 +1,5 @@ -const test = require("ava"); -const normalizeNewLines = require("./Util/normalizeNewLines"); +import test from "ava"; +import normalizeNewLines from "./Util/normalizeNewLines.js"; test("normalizeNewLines", (t) => { t.is(normalizeNewLines("\n"), "\n"); diff --git a/test/UrlTest.js b/test/UrlTest.js index a3374bc6c..197d92ba3 100644 --- a/test/UrlTest.js +++ b/test/UrlTest.js @@ -1,9 +1,11 @@ -const test = require("ava"); -const TemplateConfig = require("../src/TemplateConfig.js"); -const url = require("../src/Filters/Url.js"); +import test from "ava"; +import TemplateConfig from "../src/TemplateConfig.js"; +import url from "../src/Filters/Url.js"; -test("Test url filter passing in pathPrefix from config", (t) => { +test("Test url filter passing in pathPrefix from config", async (t) => { let eleventyConfig = new TemplateConfig(); + await eleventyConfig.init(); + let pp = eleventyConfig.getConfig().pathPrefix; t.is(pp, "/"); @@ -11,8 +13,10 @@ test("Test url filter passing in pathPrefix from config", (t) => { t.is(url("/test", pp), "/test"); }); -test("Test url filter without passing in pathPrefix", (t) => { +test("Test url filter without passing in pathPrefix", async (t) => { let eleventyConfig = new TemplateConfig(); + await eleventyConfig.init(); + let urlFilter = eleventyConfig.userConfig.getFilter("url"); t.is(urlFilter("test"), "test"); @@ -23,18 +27,12 @@ test("Test url filter with passthrough urls", (t) => { // via https://gist.github.com/mxpv/034933deeebb26b62f14 t.is(url("http://foo.com/blah_blah", ""), "http://foo.com/blah_blah"); t.is(url("http://foo.com/blah_blah/", ""), "http://foo.com/blah_blah/"); - t.is( - url("http://foo.com/blah_blah_(wikipedia)", ""), - "http://foo.com/blah_blah_(wikipedia)" - ); + t.is(url("http://foo.com/blah_blah_(wikipedia)", ""), "http://foo.com/blah_blah_(wikipedia)"); t.is( url("http://foo.com/blah_blah_(wikipedia)_(again)", ""), "http://foo.com/blah_blah_(wikipedia)_(again)" ); - t.is( - url("http://www.example.com/wpstyle/?p=364", ""), - "http://www.example.com/wpstyle/?p=364" - ); + t.is(url("http://www.example.com/wpstyle/?p=364", ""), "http://www.example.com/wpstyle/?p=364"); t.is( url("https://www.example.com/foo/?bar=baz&inga=42&quux", ""), "https://www.example.com/foo/?bar=baz&inga=42&quux" @@ -49,28 +47,13 @@ test("Test url filter with passthrough urls", (t) => { ); t.is(url("http://userid@example.com", ""), "http://userid@example.com"); t.is(url("http://userid@example.com/", ""), "http://userid@example.com/"); - t.is( - url("http://userid@example.com:8080", ""), - "http://userid@example.com:8080" - ); - t.is( - url("http://userid@example.com:8080/", ""), - "http://userid@example.com:8080/" - ); - t.is( - url("http://userid:password@example.com", ""), - "http://userid:password@example.com" - ); - t.is( - url("http://userid:password@example.com/", ""), - "http://userid:password@example.com/" - ); + t.is(url("http://userid@example.com:8080", ""), "http://userid@example.com:8080"); + t.is(url("http://userid@example.com:8080/", ""), "http://userid@example.com:8080/"); + t.is(url("http://userid:password@example.com", ""), "http://userid:password@example.com"); + t.is(url("http://userid:password@example.com/", ""), "http://userid:password@example.com/"); t.is(url("http://142.42.1.1/", ""), "http://142.42.1.1/"); t.is(url("http://142.42.1.1:8080/", ""), "http://142.42.1.1:8080/"); - t.is( - url("http://foo.com/blah_(wikipedia)#cite-1", ""), - "http://foo.com/blah_(wikipedia)#cite-1" - ); + t.is(url("http://foo.com/blah_(wikipedia)#cite-1", ""), "http://foo.com/blah_(wikipedia)#cite-1"); t.is( url("http://foo.com/blah_(wikipedia)_blah#cite-1", ""), "http://foo.com/blah_(wikipedia)_blah#cite-1" @@ -101,10 +84,7 @@ test("Test url filter with passthrough urls", (t) => { t.is(url("http://➡.ws/䨹", ""), "http://➡.ws/䨹"); t.is(url("http://⌘.ws", ""), "http://⌘.ws"); t.is(url("http://⌘.ws/", ""), "http://⌘.ws/"); - t.is( - url("http://foo.com/unicode_(✪)_in_parens", ""), - "http://foo.com/unicode_(✪)_in_parens" - ); + t.is(url("http://foo.com/unicode_(✪)_in_parens", ""), "http://foo.com/unicode_(✪)_in_parens"); t.is(url("http://☺.damowmow.com/", ""), "http://☺.damowmow.com/"); t.is(url("http://مثال.إختبار", ""), "http://مثال.إختبار"); t.is(url("http://例子.测试", ""), "http://例子.测试"); diff --git a/test/UserConfigTest.js b/test/UserConfigTest.js index f58ad39ec..2a870b02d 100644 --- a/test/UserConfigTest.js +++ b/test/UserConfigTest.js @@ -1,5 +1,5 @@ -const test = require("ava"); -const UserConfig = require("../src/UserConfig"); +import test from "ava"; +import UserConfig from "../src/UserConfig.js"; test("Template Formats", (t) => { let userCfg = new UserConfig(); @@ -7,18 +7,12 @@ test("Template Formats", (t) => { t.falsy(userCfg.getMergingConfigObject().templateFormats); userCfg.setTemplateFormats("njk,liquid"); - t.deepEqual(userCfg.getMergingConfigObject().templateFormats, [ - "njk", - "liquid", - ]); + t.deepEqual(userCfg.getMergingConfigObject().templateFormats, ["njk", "liquid"]); // setting multiple times takes the last one userCfg.setTemplateFormats("njk,liquid,pug"); userCfg.setTemplateFormats("njk,liquid"); - t.deepEqual(userCfg.getMergingConfigObject().templateFormats, [ - "njk", - "liquid", - ]); + t.deepEqual(userCfg.getMergingConfigObject().templateFormats, ["njk", "liquid"]); }); test("Template Formats (Arrays)", (t) => { @@ -27,18 +21,12 @@ test("Template Formats (Arrays)", (t) => { t.falsy(userCfg.getMergingConfigObject().templateFormats); userCfg.setTemplateFormats(["njk", "liquid"]); - t.deepEqual(userCfg.getMergingConfigObject().templateFormats, [ - "njk", - "liquid", - ]); + t.deepEqual(userCfg.getMergingConfigObject().templateFormats, ["njk", "liquid"]); // setting multiple times takes the last one userCfg.setTemplateFormats(["njk", "liquid", "pug"]); userCfg.setTemplateFormats(["njk", "liquid"]); - t.deepEqual(userCfg.getMergingConfigObject().templateFormats, [ - "njk", - "liquid", - ]); + t.deepEqual(userCfg.getMergingConfigObject().templateFormats, ["njk", "liquid"]); }); // more in TemplateConfigTest.js @@ -155,41 +143,34 @@ test("Set manual Pass-through File Copy (glob patterns)", (t) => { test("Set Template Formats (string)", (t) => { let userCfg = new UserConfig(); - userCfg.setTemplateFormats("ejs, njk, liquid"); - t.deepEqual(userCfg.templateFormats, ["ejs", "njk", "liquid"]); + userCfg.setTemplateFormats("njk, liquid"); + t.deepEqual(userCfg.templateFormats, ["njk", "liquid"]); }); test("Set Template Formats (array)", (t) => { let userCfg = new UserConfig(); - userCfg.setTemplateFormats(["ejs", "njk", "liquid"]); - t.deepEqual(userCfg.templateFormats, ["ejs", "njk", "liquid"]); + userCfg.setTemplateFormats(["njk", "liquid"]); + t.deepEqual(userCfg.templateFormats, ["njk", "liquid"]); }); test("Set Template Formats (js passthrough copy)", (t) => { let userCfg = new UserConfig(); - userCfg.setTemplateFormats("ejs, njk, liquid, js"); - t.deepEqual(userCfg.templateFormats, ["ejs", "njk", "liquid", "js"]); + userCfg.setTemplateFormats("njk, liquid, js"); + t.deepEqual(userCfg.templateFormats, ["njk", "liquid", "js"]); }); test("Set Template Formats (11ty.js)", (t) => { let userCfg = new UserConfig(); - userCfg.setTemplateFormats("ejs, njk, liquid, 11ty.js"); - t.deepEqual(userCfg.templateFormats, ["ejs", "njk", "liquid", "11ty.js"]); + userCfg.setTemplateFormats("njk, liquid, 11ty.js"); + t.deepEqual(userCfg.templateFormats, ["njk", "liquid", "11ty.js"]); }); test("Add Template Formats", (t) => { let userCfg = new UserConfig(); - userCfg.addTemplateFormats("ejs"); userCfg.addTemplateFormats("njk"); userCfg.addTemplateFormats("webc"); userCfg.addTemplateFormats("liquid"); userCfg.addTemplateFormats("11ty.js"); - t.deepEqual(userCfg.templateFormatsAdded.sort(), [ - "11ty.js", - "ejs", - "liquid", - "njk", - "webc", - ]); + t.deepEqual(userCfg.templateFormatsAdded.sort(), ["11ty.js", "liquid", "njk", "webc"]); }); diff --git a/test/UserDataExtensionsTest.js b/test/UserDataExtensionsTest.js index 56d08cfb8..a2952ba6a 100644 --- a/test/UserDataExtensionsTest.js +++ b/test/UserDataExtensionsTest.js @@ -1,21 +1,18 @@ -const test = require("ava"); -const fs = require("fs"); -const TemplateConfig = require("../src/TemplateConfig"); -const FileSystemSearch = require("../src/FileSystemSearch"); -const TemplateData = require("../src/TemplateData"); -let yaml = require("js-yaml"); - -function injectDataExtensions(dataObj) { - dataObj.config.dataExtensions = new Map([ - ["yaml", { parser: (s) => yaml.load(s) }], - ["nosj", { parser: JSON.parse }], - ]); -} +import test from "ava"; +import fs from "fs"; +import yaml from "js-yaml"; + +import TemplateConfig from "../src/TemplateConfig.js"; +import FileSystemSearch from "../src/FileSystemSearch.js"; +import TemplateData from "../src/TemplateData.js"; test("Local data", async (t) => { let eleventyConfig = new TemplateConfig(); + eleventyConfig.userConfig.addDataExtension("yaml", { parser: (s) => yaml.load(s) }); + eleventyConfig.userConfig.addDataExtension("nosj", { parser: (s) => JSON.parse(s) }); + await eleventyConfig.init(); + let dataObj = new TemplateData("./test/stubs-630/", eleventyConfig); - injectDataExtensions(dataObj); dataObj.setFileSystemSearch(new FileSystemSearch()); let data = await dataObj.getGlobalData(); @@ -43,8 +40,11 @@ test("Local data", async (t) => { test("Local files", async (t) => { let eleventyConfig = new TemplateConfig(); + eleventyConfig.userConfig.addDataExtension("yaml", { parser: (s) => yaml.load(s) }); + eleventyConfig.userConfig.addDataExtension("nosj", { parser: (s) => JSON.parse(s) }); + await eleventyConfig.init(); + let dataObj = new TemplateData("./test/stubs-630/", eleventyConfig); - injectDataExtensions(dataObj); let files = await dataObj.getLocalDataPaths("./test/stubs-630/component-yaml/component.njk"); t.deepEqual(files, [ "./test/stubs-630/stubs-630.yaml", @@ -53,6 +53,7 @@ test("Local files", async (t) => { "./test/stubs-630/stubs-630.11tydata.yaml", "./test/stubs-630/stubs-630.11tydata.nosj", "./test/stubs-630/stubs-630.11tydata.json", + "./test/stubs-630/stubs-630.11tydata.mjs", "./test/stubs-630/stubs-630.11tydata.cjs", "./test/stubs-630/stubs-630.11tydata.js", "./test/stubs-630/component-yaml/component-yaml.yaml", @@ -61,6 +62,7 @@ test("Local files", async (t) => { "./test/stubs-630/component-yaml/component-yaml.11tydata.yaml", "./test/stubs-630/component-yaml/component-yaml.11tydata.nosj", "./test/stubs-630/component-yaml/component-yaml.11tydata.json", + "./test/stubs-630/component-yaml/component-yaml.11tydata.mjs", "./test/stubs-630/component-yaml/component-yaml.11tydata.cjs", "./test/stubs-630/component-yaml/component-yaml.11tydata.js", "./test/stubs-630/component-yaml/component.yaml", @@ -69,6 +71,7 @@ test("Local files", async (t) => { "./test/stubs-630/component-yaml/component.11tydata.yaml", "./test/stubs-630/component-yaml/component.11tydata.nosj", "./test/stubs-630/component-yaml/component.11tydata.json", + "./test/stubs-630/component-yaml/component.11tydata.mjs", "./test/stubs-630/component-yaml/component.11tydata.cjs", "./test/stubs-630/component-yaml/component.11tydata.js", ]); @@ -76,12 +79,15 @@ test("Local files", async (t) => { test("Global data", async (t) => { let eleventyConfig = new TemplateConfig(); + eleventyConfig.userConfig.addDataExtension("yaml", { parser: (s) => yaml.load(s) }); + eleventyConfig.userConfig.addDataExtension("nosj", { parser: (s) => JSON.parse(s) }); + await eleventyConfig.init(); + let dataObj = new TemplateData("./test/stubs-630/", eleventyConfig); - injectDataExtensions(dataObj); dataObj.setFileSystemSearch(new FileSystemSearch()); t.deepEqual(await dataObj.getGlobalDataGlob(), [ - "./test/stubs-630/_data/**/*.{nosj,yaml,json,cjs,js}", + "./test/stubs-630/_data/**/*.{nosj,yaml,json,mjs,cjs,js}", ]); let data = await dataObj.getGlobalData(); @@ -109,8 +115,11 @@ test("Global data", async (t) => { test("Global data merging and priority", async (t) => { let eleventyConfig = new TemplateConfig(); + eleventyConfig.userConfig.addDataExtension("yaml", { parser: (s) => yaml.load(s) }); + eleventyConfig.userConfig.addDataExtension("nosj", { parser: (s) => JSON.parse(s) }); + await eleventyConfig.init(); + let dataObj = new TemplateData("./test/stubs-630/", eleventyConfig); - injectDataExtensions(dataObj); dataObj.setFileSystemSearch(new FileSystemSearch()); let data = await dataObj.getGlobalData(); @@ -133,22 +142,17 @@ test("Binary data files, encoding: null", async (t) => { t.plan(2); let eleventyConfig = new TemplateConfig(); + eleventyConfig.userConfig.addDataExtension("jpg", { + parser: (s) => { + t.true(Buffer.isBuffer(s)); + // s is a Buffer, just return the length as a sample + return s.length; + }, + encoding: null, + }); + await eleventyConfig.init(); + let dataObj = new TemplateData("./test/stubs-2378/", eleventyConfig); - dataObj.config.dataExtensions = new Map([ - [ - "jpg", - { - parser: (s) => { - t.true(Buffer.isBuffer(s)); - // s is a Buffer, just return the length as a sample - return s.length; - }, - options: { - encoding: null, - }, - }, - ], - ]); dataObj.setFileSystemSearch(new FileSystemSearch()); let data = await dataObj.getGlobalData(); @@ -159,22 +163,17 @@ test("Binary data files, read: false", async (t) => { t.plan(2); let eleventyConfig = new TemplateConfig(); + eleventyConfig.userConfig.addDataExtension("jpg", { + parser: (s) => { + t.true(fs.existsSync(s)); + // s is a Buffer, just return the length as a sample + return s; + }, + read: false, + }); + await eleventyConfig.init(); + let dataObj = new TemplateData("./test/stubs-2378/", eleventyConfig); - dataObj.config.dataExtensions = new Map([ - [ - "jpg", - { - parser: (s) => { - t.true(fs.existsSync(s)); - // s is a Buffer, just return the length as a sample - return s; - }, - options: { - read: false, - }, - }, - ], - ]); dataObj.setFileSystemSearch(new FileSystemSearch()); let data = await dataObj.getGlobalData(); @@ -193,6 +192,7 @@ test("Binary data files, encoding: null (multiple data extensions)", async (t) = }, encoding: null, }); + await eleventyConfig.init(); let dataObj = new TemplateData("./test/stubs-2378/", eleventyConfig); dataObj.setFileSystemSearch(new FileSystemSearch()); diff --git a/test/Util/normalizeNewLines.js b/test/Util/normalizeNewLines.js index 613b6ac58..ba47d81bd 100644 --- a/test/Util/normalizeNewLines.js +++ b/test/Util/normalizeNewLines.js @@ -2,4 +2,4 @@ function normalizeNewLines(str) { return str.replace(/\r\n/g, "\n"); } -module.exports = normalizeNewLines; +export default normalizeNewLines; diff --git a/test/_getNewTemplateForTests.js b/test/_getNewTemplateForTests.js index c6d469be0..f02e2bf6f 100644 --- a/test/_getNewTemplateForTests.js +++ b/test/_getNewTemplateForTests.js @@ -1,24 +1,29 @@ -const EleventyExtensionMap = require("../src/EleventyExtensionMap"); -const TemplateConfig = require("../src/TemplateConfig"); -const Template = require("../src/Template"); -const FileSystemSearch = require("../src/FileSystemSearch"); +import EleventyExtensionMap from "../src/EleventyExtensionMap.js"; +import TemplateConfig from "../src/TemplateConfig.js"; +import Template from "../src/Template.js"; +import FileSystemSearch from "../src/FileSystemSearch.js"; -module.exports = function getNewTemplate( +export default async function getNewTemplate( path, inputDir, outputDir, templateData = null, map = null, - eleventyConfig = new TemplateConfig() + eleventyConfig = null ) { + if (!eleventyConfig) { + eleventyConfig = new TemplateConfig(); + await eleventyConfig.init(); + } + if (!map) { - map = new EleventyExtensionMap( - ["liquid", "ejs", "md", "hbs", "mustache", "haml", "pug", "njk", "html", "11ty.js"], - eleventyConfig - ); + map = new EleventyExtensionMap(["liquid", "md", "njk", "html", "11ty.js"], eleventyConfig); } if (templateData) { templateData.setFileSystemSearch(new FileSystemSearch()); } - return new Template(path, inputDir, outputDir, templateData, map, eleventyConfig); -}; + let tmpl = new Template(path, inputDir, outputDir, templateData, map, eleventyConfig); + await tmpl.getTemplateRender(); + + return tmpl; +} diff --git a/test/_getRenderedTemplates.js b/test/_getRenderedTemplates.js index 371e65c68..dc48e0ffc 100644 --- a/test/_getRenderedTemplates.js +++ b/test/_getRenderedTemplates.js @@ -1,4 +1,4 @@ -module.exports = async function getRenderedTemplates(template, data) { +export default async function getRenderedTemplates(template, data) { let pages = await template.getTemplates(data); await Promise.all( pages.map(async (page) => { @@ -8,4 +8,4 @@ module.exports = async function getRenderedTemplates(template, data) { }) ); return pages; -}; +} diff --git a/test/_issues/2250/2250-test.js b/test/_issues/2250/2250-test.js index d78a58988..aba681a22 100644 --- a/test/_issues/2250/2250-test.js +++ b/test/_issues/2250/2250-test.js @@ -1,5 +1,5 @@ -const test = require("ava"); -const Eleventy = require("../../../src/Eleventy"); +import test from "ava"; +import Eleventy from "../../../src/Eleventy.js"; test("Issue #2250, page is available in filters", async (t) => { let elev = new Eleventy("./test/_issues/2250/", "./test/_issues/2250/_site", { @@ -28,10 +28,4 @@ test("Issue #2250, page is available in filters", async (t) => { }); t.is(javascript[0].content.trim(), "/javascript/"); - - let handlebars = results.filter((entry) => { - return entry.url.startsWith("/handlebars/"); - }); - - t.is(handlebars[0].content.trim(), "/handlebars/"); }); diff --git a/test/_issues/2250/handlebars.hbs b/test/_issues/2250/handlebars.hbs deleted file mode 100644 index ce7cd146b..000000000 --- a/test/_issues/2250/handlebars.hbs +++ /dev/null @@ -1 +0,0 @@ -{{ getUrl }} \ No newline at end of file diff --git a/test/_issues/2250/javascript.11ty.js b/test/_issues/2250/javascript.11ty.cjs similarity index 100% rename from test/_issues/2250/javascript.11ty.js rename to test/_issues/2250/javascript.11ty.cjs diff --git a/test/_issues/975/975-test.js b/test/_issues/975/975-test.js index 0c7c1176d..4bbd14d32 100644 --- a/test/_issues/975/975-test.js +++ b/test/_issues/975/975-test.js @@ -1,27 +1,22 @@ -const test = require("ava"); -const TemplateMap = require("../../../src/TemplateMap"); -const TemplateConfig = require("../../../src/TemplateConfig"); +import test from "ava"; -const getNewTemplateForTests = require("../../_getNewTemplateForTests"); +import TemplateMap from "../../../src/TemplateMap.js"; +import TemplateConfig from "../../../src/TemplateConfig.js"; +import getNewTemplateForTests from "../../_getNewTemplateForTests.js"; function getNewTemplate(filename, input, output, eleventyConfig) { - return getNewTemplateForTests( - filename, - input, - output, - null, - null, - eleventyConfig - ); + return getNewTemplateForTests(filename, input, output, null, null, eleventyConfig); } test("Get ordered list of templates", async (t) => { let eleventyConfig = new TemplateConfig(); + await eleventyConfig.init(); + let tm = new TemplateMap(eleventyConfig); // These two templates are add-order-dependent await tm.add( - getNewTemplate( + await getNewTemplate( "./test/_issues/975/post.md", "./test/_issues/975/", "./test/_issues/975/_site", @@ -30,7 +25,7 @@ test("Get ordered list of templates", async (t) => { ); await tm.add( - getNewTemplate( + await getNewTemplate( "./test/_issues/975/another-post.md", "./test/_issues/975/", "./test/_issues/975/_site", @@ -40,7 +35,7 @@ test("Get ordered list of templates", async (t) => { // This template should always be last await tm.add( - getNewTemplate( + await getNewTemplate( "./test/_issues/975/index.md", "./test/_issues/975/", "./test/_issues/975/_site", @@ -58,11 +53,13 @@ test("Get ordered list of templates", async (t) => { test("Get ordered list of templates (reverse add)", async (t) => { let eleventyConfig = new TemplateConfig(); + await eleventyConfig.init(); + let tm = new TemplateMap(eleventyConfig); // This template should always be last await tm.add( - getNewTemplate( + await getNewTemplate( "./test/_issues/975/index.md", "./test/_issues/975/", "./test/_issues/975/_site", @@ -72,7 +69,7 @@ test("Get ordered list of templates (reverse add)", async (t) => { // These two templates are add-order-dependent await tm.add( - getNewTemplate( + await getNewTemplate( "./test/_issues/975/another-post.md", "./test/_issues/975/", "./test/_issues/975/_site", @@ -81,7 +78,7 @@ test("Get ordered list of templates (reverse add)", async (t) => { ); await tm.add( - getNewTemplate( + await getNewTemplate( "./test/_issues/975/post.md", "./test/_issues/975/", "./test/_issues/975/_site", diff --git a/test/cmdTest.js b/test/cmdTest.js index f1d5628ee..7b4e8dac9 100644 --- a/test/cmdTest.js +++ b/test/cmdTest.js @@ -1,34 +1,28 @@ -const test = require("ava"); -const { exec } = require("child_process"); +import test from "ava"; +import { exec } from "child_process"; test("Test command line exit code success", async (t) => { await new Promise((resolve) => { - exec( - "node ./cmd.js --input=test/stubs/exitCode_success --dryrun", - (error, stdout, stderr) => { - t.falsy(error); - resolve(); - } - ); + exec("node ./cmd.cjs --input=test/stubs/exitCode_success --dryrun", (error, stdout, stderr) => { + t.falsy(error); + resolve(); + }); }); }); test("Test command line exit code for template error", async (t) => { await new Promise((resolve) => { - exec( - "node ./cmd.js --input=test/stubs/exitCode --dryrun", - (error, stdout, stderr) => { - t.is(error.code, 1); - resolve(); - } - ); + exec("node ./cmd.cjs --input=test/stubs/exitCode --dryrun", (error, stdout, stderr) => { + t.is(error.code, 1); + resolve(); + }); }); }); test("Test command line exit code for global data error", async (t) => { await new Promise((resolve) => { exec( - "node ./cmd.js --input=test/stubs/exitCode_globalData --dryrun", + "node ./cmd.cjs --input=test/stubs/exitCode_globalData --dryrun", (error, stdout, stderr) => { t.is(error.code, 1); resolve(); @@ -40,7 +34,7 @@ test("Test command line exit code for global data error", async (t) => { test("Test data should not process in a --help", async (t) => { await new Promise((resolve) => { exec( - "node ./cmd.js --input=test/stubs/cmd-help-processing --help", + "node ./cmd.cjs --input=test/stubs/cmd-help-processing --help", (error, stdout, stderr) => { t.falsy(error); t.is(stdout.indexOf("THIS SHOULD NOT LOG TO CONSOLE"), -1); @@ -53,7 +47,7 @@ test("Test data should not process in a --help", async (t) => { test("Test data should not process in a --version", async (t) => { await new Promise((resolve) => { exec( - "node ./cmd.js --input=test/stubs/cmd-help-processing --version", + "node ./cmd.cjs --input=test/stubs/cmd-help-processing --version", (error, stdout, stderr) => { t.falsy(error); t.is(stdout.indexOf("THIS SHOULD NOT LOG TO CONSOLE"), -1); diff --git a/test/proxy-pagination-globaldata/tmpl3.hbs b/test/proxy-pagination-globaldata/tmpl3.hbs deleted file mode 100644 index 8316692d9..000000000 --- a/test/proxy-pagination-globaldata/tmpl3.hbs +++ /dev/null @@ -1,8 +0,0 @@ ---- -pages: - - page 1 -pagination: - data: pages - size: 1 ---- -{{ banner.content }} \ No newline at end of file diff --git a/test/serverless-stubs-config/functions/test1/eleventy-serverless-map.json b/test/serverless-stubs-config/functions/test1/eleventy-serverless-map.json deleted file mode 100644 index e04d1f71d..000000000 --- a/test/serverless-stubs-config/functions/test1/eleventy-serverless-map.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "/": "./test/serverless-stubs-config/test1.md" -} \ No newline at end of file diff --git a/test/serverless-stubs-config/functions/test1/eleventy.config.js b/test/serverless-stubs-config/functions/test1/eleventy.config.js deleted file mode 100644 index 70e37d8eb..000000000 --- a/test/serverless-stubs-config/functions/test1/eleventy.config.js +++ /dev/null @@ -1,5 +0,0 @@ -module.exports = function (eleventyConfig) { - eleventyConfig.addTransform("transform-html", function (content) { - return `${content}`.trim() + "

Hi

"; - }); -}; diff --git a/test/serverless-stubs-config/test1.md b/test/serverless-stubs-config/test1.md deleted file mode 100644 index fb35093f5..000000000 --- a/test/serverless-stubs-config/test1.md +++ /dev/null @@ -1,6 +0,0 @@ ---- -permalink: - test1: / ---- - -# Hi diff --git a/test/serverless-stubs-page-url/functions/test1/eleventy-serverless-map.json b/test/serverless-stubs-page-url/functions/test1/eleventy-serverless-map.json deleted file mode 100644 index 1da05e56f..000000000 --- a/test/serverless-stubs-page-url/functions/test1/eleventy-serverless-map.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "/:test/": "./test/serverless-stubs-page-url/test1.md" -} \ No newline at end of file diff --git a/test/serverless-stubs-page-url/test1.md b/test/serverless-stubs-page-url/test1.md deleted file mode 100644 index cb4e4cba3..000000000 --- a/test/serverless-stubs-page-url/test1.md +++ /dev/null @@ -1,6 +0,0 @@ ---- -permalink: - test1: /:test/ ---- - -# {{ page.url }} diff --git a/test/serverless-stubs/functions/test1/eleventy-serverless-map.json b/test/serverless-stubs/functions/test1/eleventy-serverless-map.json deleted file mode 100644 index 0d593ab76..000000000 --- a/test/serverless-stubs/functions/test1/eleventy-serverless-map.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "/": "./test/serverless-stubs/test1.md" -} \ No newline at end of file diff --git a/test/serverless-stubs/test1.md b/test/serverless-stubs/test1.md deleted file mode 100644 index fb35093f5..000000000 --- a/test/serverless-stubs/test1.md +++ /dev/null @@ -1,6 +0,0 @@ ---- -permalink: - test1: / ---- - -# Hi diff --git a/test/stubs-2258/eleventy.config.js b/test/stubs-2258/eleventy.config.cjs similarity index 100% rename from test/stubs-2258/eleventy.config.js rename to test/stubs-2258/eleventy.config.cjs diff --git a/test/stubs-2790/page.11ty.js b/test/stubs-2790/page.11ty.cjs similarity index 100% rename from test/stubs-2790/page.11ty.js rename to test/stubs-2790/page.11ty.cjs diff --git a/test/stubs-630/_data/globalData0.js b/test/stubs-630/_data/globalData0.cjs similarity index 100% rename from test/stubs-630/_data/globalData0.js rename to test/stubs-630/_data/globalData0.cjs diff --git a/test/stubs-630/_data/mergingGlobalData.js b/test/stubs-630/_data/mergingGlobalData.js index 16712f966..bc99caa9a 100644 --- a/test/stubs-630/_data/mergingGlobalData.js +++ b/test/stubs-630/_data/mergingGlobalData.js @@ -1,4 +1,4 @@ -module.exports = { +export default { datakey0: "js-value0", - jskey: "js" + jskey: "js", }; diff --git a/test/stubs-630/component-yaml/component.11tydata.js b/test/stubs-630/component-yaml/component.11tydata.cjs similarity index 100% rename from test/stubs-630/component-yaml/component.11tydata.js rename to test/stubs-630/component-yaml/component.11tydata.cjs diff --git a/test/stubs-919/test.11tydata.js b/test/stubs-919/test.11tydata.cjs similarity index 100% rename from test/stubs-919/test.11tydata.js rename to test/stubs-919/test.11tydata.cjs diff --git a/test/stubs-computed-dirdata/dir/dir.11tydata.js b/test/stubs-computed-dirdata/dir/dir.11tydata.cjs similarity index 100% rename from test/stubs-computed-dirdata/dir/dir.11tydata.js rename to test/stubs-computed-dirdata/dir/dir.11tydata.cjs diff --git a/test/stubs-computed-dirdata/dir/first.11ty.js b/test/stubs-computed-dirdata/dir/first.11ty.cjs similarity index 100% rename from test/stubs-computed-dirdata/dir/first.11ty.js rename to test/stubs-computed-dirdata/dir/first.11ty.cjs diff --git a/test/stubs-computed-dirdata/dir/second.11ty.js b/test/stubs-computed-dirdata/dir/second.11ty.cjs similarity index 100% rename from test/stubs-computed-dirdata/dir/second.11ty.js rename to test/stubs-computed-dirdata/dir/second.11ty.cjs diff --git a/test/stubs-computed-global/_data/eleventyComputed.js b/test/stubs-computed-global/_data/eleventyComputed.cjs similarity index 100% rename from test/stubs-computed-global/_data/eleventyComputed.js rename to test/stubs-computed-global/_data/eleventyComputed.cjs diff --git a/test/stubs-computed-pagination/child.11ty.js b/test/stubs-computed-pagination/child.11ty.cjs similarity index 100% rename from test/stubs-computed-pagination/child.11ty.js rename to test/stubs-computed-pagination/child.11ty.cjs diff --git a/test/stubs-data-cascade/global-versus-layout/_data/cascade.js b/test/stubs-data-cascade/global-versus-layout/_data/cascade.cjs similarity index 100% rename from test/stubs-data-cascade/global-versus-layout/_data/cascade.js rename to test/stubs-data-cascade/global-versus-layout/_data/cascade.cjs diff --git a/test/stubs-data-cascade/layout-data-files/test.11tydata.js b/test/stubs-data-cascade/layout-data-files/test.11tydata.cjs similarity index 100% rename from test/stubs-data-cascade/layout-data-files/test.11tydata.js rename to test/stubs-data-cascade/layout-data-files/test.11tydata.cjs diff --git a/test/stubs-data-cascade/layout-versus-dirdatafile/src/src.11tydata.js b/test/stubs-data-cascade/layout-versus-dirdatafile/src/src.11tydata.cjs similarity index 100% rename from test/stubs-data-cascade/layout-versus-dirdatafile/src/src.11tydata.js rename to test/stubs-data-cascade/layout-versus-dirdatafile/src/src.11tydata.cjs diff --git a/test/stubs-data-cascade/layout-versus-tmpldatafile/test.11tydata.js b/test/stubs-data-cascade/layout-versus-tmpldatafile/test.11tydata.cjs similarity index 100% rename from test/stubs-data-cascade/layout-versus-tmpldatafile/test.11tydata.js rename to test/stubs-data-cascade/layout-versus-tmpldatafile/test.11tydata.cjs diff --git a/test/stubs-data-esm/_data/commonjs.cjs b/test/stubs-data-esm/_data/commonjs.cjs new file mode 100644 index 000000000..fb9d5b95a --- /dev/null +++ b/test/stubs-data-esm/_data/commonjs.cjs @@ -0,0 +1 @@ +module.exports = "commonjs default"; \ No newline at end of file diff --git a/test/stubs-data-esm/_data/module.mjs b/test/stubs-data-esm/_data/module.mjs new file mode 100644 index 000000000..1abaf600d --- /dev/null +++ b/test/stubs-data-esm/_data/module.mjs @@ -0,0 +1,3 @@ +export const named = "es module named"; + +export default "es module default"; diff --git a/test/stubs-dependency-tree/child.cjs b/test/stubs-dependency-tree/child.cjs new file mode 100644 index 000000000..f0aec918a --- /dev/null +++ b/test/stubs-dependency-tree/child.cjs @@ -0,0 +1 @@ +require("./grandchild.cjs"); diff --git a/test/stubs-dependency-tree/child.js b/test/stubs-dependency-tree/child.js deleted file mode 100644 index 4874bc919..000000000 --- a/test/stubs-dependency-tree/child.js +++ /dev/null @@ -1 +0,0 @@ -require("./grandchild"); diff --git a/test/stubs-dependency-tree/grandchild.js b/test/stubs-dependency-tree/grandchild.cjs similarity index 100% rename from test/stubs-dependency-tree/grandchild.js rename to test/stubs-dependency-tree/grandchild.cjs diff --git a/test/stubs-dependency-tree/index.cjs b/test/stubs-dependency-tree/index.cjs new file mode 100644 index 000000000..d4c9bab60 --- /dev/null +++ b/test/stubs-dependency-tree/index.cjs @@ -0,0 +1,2 @@ +require("lodash"); +require("./child.cjs"); diff --git a/test/stubs-dependency-tree/index.js b/test/stubs-dependency-tree/index.js deleted file mode 100644 index c04aca49a..000000000 --- a/test/stubs-dependency-tree/index.js +++ /dev/null @@ -1,2 +0,0 @@ -require("lodash"); -require("./child.js"); diff --git a/test/stubs-global-data-config-api-nested/_data/deep.js b/test/stubs-global-data-config-api-nested/_data/deep.cjs similarity index 100% rename from test/stubs-global-data-config-api-nested/_data/deep.js rename to test/stubs-global-data-config-api-nested/_data/deep.cjs diff --git a/test/stubs-hbs-partial-var/_includes/myPartial.hbs b/test/stubs-hbs-partial-var/_includes/myPartial.hbs deleted file mode 100644 index 0fbd57a9e..000000000 --- a/test/stubs-hbs-partial-var/_includes/myPartial.hbs +++ /dev/null @@ -1 +0,0 @@ -The result is {{parameter}} \ No newline at end of file diff --git a/test/stubs-i18n/en-us/index.11ty.js b/test/stubs-i18n/en-us/index.11ty.cjs similarity index 100% rename from test/stubs-i18n/en-us/index.11ty.js rename to test/stubs-i18n/en-us/index.11ty.cjs diff --git a/test/stubs-render-plugin/11tyjs-file.njk b/test/stubs-render-plugin/11tyjs-file.njk index 27623d69d..a2d523b90 100644 --- a/test/stubs-render-plugin/11tyjs-file.njk +++ b/test/stubs-render-plugin/11tyjs-file.njk @@ -4,4 +4,4 @@ argData: hi: liquidHi bye: liquidBye --- -{% renderFile "./test/stubs-render-plugin/_includes/include.11ty.js", argData %} \ No newline at end of file +{% renderFile "./test/stubs-render-plugin/_includes/include.11ty.cjs", argData %} \ No newline at end of file diff --git a/test/stubs-render-plugin/_includes/include.11ty.js b/test/stubs-render-plugin/_includes/include.11ty.cjs similarity index 100% rename from test/stubs-render-plugin/_includes/include.11ty.js rename to test/stubs-render-plugin/_includes/include.11ty.cjs diff --git a/test/stubs-render-plugin/liquid-md.11ty.js b/test/stubs-render-plugin/liquid-md.11ty.cjs similarity index 100% rename from test/stubs-render-plugin/liquid-md.11ty.js rename to test/stubs-render-plugin/liquid-md.11ty.cjs diff --git a/test/stubs-render-plugin/nunjucks.11ty.js b/test/stubs-render-plugin/nunjucks.11ty.cjs similarity index 100% rename from test/stubs-render-plugin/nunjucks.11ty.js rename to test/stubs-render-plugin/nunjucks.11ty.cjs diff --git a/test/stubs/_data/globalData2.js b/test/stubs/_data/globalData2.cjs similarity index 100% rename from test/stubs/_data/globalData2.js rename to test/stubs/_data/globalData2.cjs diff --git a/test/stubs/_data/globalDataFn.js b/test/stubs/_data/globalDataFn.js index 2a27b03c9..ab166a711 100644 --- a/test/stubs/_data/globalDataFn.js +++ b/test/stubs/_data/globalDataFn.js @@ -1,7 +1,7 @@ -const dep1 = require("../deps/dep1"); +import dep1 from "../deps/dep1.cjs"; -module.exports = function() { +export default function () { return { - datakeyfromjsfn: "howdy" + datakeyfromjsfn: "howdy", }; -}; +} diff --git a/test/stubs/_data/globalDataFnCJS.cjs b/test/stubs/_data/globalDataFnCJS.cjs index e6835df91..3939ac33d 100644 --- a/test/stubs/_data/globalDataFnCJS.cjs +++ b/test/stubs/_data/globalDataFnCJS.cjs @@ -1,4 +1,4 @@ -const dep1 = require("../deps/dep1"); +const dep1 = require("../deps/dep1.cjs"); module.exports = function() { return { diff --git a/test/stubs/_data/testDataEjs.json b/test/stubs/_data/testDataLiquid.json similarity index 50% rename from test/stubs/_data/testDataEjs.json rename to test/stubs/_data/testDataLiquid.json index badaef2f0..2d715eca9 100644 --- a/test/stubs/_data/testDataEjs.json +++ b/test/stubs/_data/testDataLiquid.json @@ -1,4 +1,4 @@ { "datakey1": "datavalue1", - "datakey2": "<%= pkg.name %>" + "datakey2": "{{ pkg.name }}" } diff --git a/test/stubs/_includes/default.ejs b/test/stubs/_includes/default.liquid similarity index 100% rename from test/stubs/_includes/default.ejs rename to test/stubs/_includes/default.liquid diff --git a/test/stubs/_includes/defaultLayout.ejs b/test/stubs/_includes/defaultLayout.liquid similarity index 85% rename from test/stubs/_includes/defaultLayout.ejs rename to test/stubs/_includes/defaultLayout.liquid index 91a6e84e1..d834b634f 100644 --- a/test/stubs/_includes/defaultLayout.ejs +++ b/test/stubs/_includes/defaultLayout.liquid @@ -6,5 +6,5 @@ yearsPosted: 0.4 ---
- <%- content %> + {{ content }}
diff --git a/test/stubs/_includes/defaultLayoutLayoutContent.ejs b/test/stubs/_includes/defaultLayoutLayoutContent.liquid similarity index 81% rename from test/stubs/_includes/defaultLayoutLayoutContent.ejs rename to test/stubs/_includes/defaultLayoutLayoutContent.liquid index 5beea2c22..2b67ffff6 100644 --- a/test/stubs/_includes/defaultLayoutLayoutContent.ejs +++ b/test/stubs/_includes/defaultLayoutLayoutContent.liquid @@ -6,5 +6,5 @@ yearsPosted: 0.4 ---
- <%- layoutContent %> + {{ layoutContent }}
\ No newline at end of file diff --git a/test/stubs/_includes/defaultLayout_layoutContent.ejs b/test/stubs/_includes/defaultLayout_layoutContent.ejs deleted file mode 100644 index 5beea2c22..000000000 --- a/test/stubs/_includes/defaultLayout_layoutContent.ejs +++ /dev/null @@ -1,10 +0,0 @@ ---- -keylayout: valuelayout -postRank: 4 -daysPosted: 152 -yearsPosted: 0.4 ---- - -
- <%- layoutContent %> -
\ No newline at end of file diff --git a/test/stubs/_includes/included.ejs b/test/stubs/_includes/included.ejs deleted file mode 100644 index 6b622104c..000000000 --- a/test/stubs/_includes/included.ejs +++ /dev/null @@ -1 +0,0 @@ -This is an include. \ No newline at end of file diff --git a/test/stubs/_includes/included.hbs b/test/stubs/_includes/included.hbs deleted file mode 100644 index 6b622104c..000000000 --- a/test/stubs/_includes/included.hbs +++ /dev/null @@ -1 +0,0 @@ -This is an include. \ No newline at end of file diff --git a/test/stubs/_includes/included.mustache b/test/stubs/_includes/included.mustache deleted file mode 100644 index 6b622104c..000000000 --- a/test/stubs/_includes/included.mustache +++ /dev/null @@ -1 +0,0 @@ -This is an include. \ No newline at end of file diff --git a/test/stubs/_includes/included.pug b/test/stubs/_includes/included.pug deleted file mode 100644 index ea78a13ae..000000000 --- a/test/stubs/_includes/included.pug +++ /dev/null @@ -1 +0,0 @@ -span This is an include. \ No newline at end of file diff --git a/test/stubs/_includes/includedvar.ejs b/test/stubs/_includes/includedvar.ejs deleted file mode 100644 index 49dc2780b..000000000 --- a/test/stubs/_includes/includedvar.ejs +++ /dev/null @@ -1 +0,0 @@ -This is an <%= name %>. \ No newline at end of file diff --git a/test/stubs/_includes/includedvar.hbs b/test/stubs/_includes/includedvar.hbs deleted file mode 100644 index ea76fb624..000000000 --- a/test/stubs/_includes/includedvar.hbs +++ /dev/null @@ -1 +0,0 @@ -This is a {{name}}. \ No newline at end of file diff --git a/test/stubs/_includes/includedvar.mustache b/test/stubs/_includes/includedvar.mustache deleted file mode 100644 index ea76fb624..000000000 --- a/test/stubs/_includes/includedvar.mustache +++ /dev/null @@ -1 +0,0 @@ -This is a {{name}}. \ No newline at end of file diff --git a/test/stubs/_includes/includedvar.pug b/test/stubs/_includes/includedvar.pug deleted file mode 100644 index 95c03de86..000000000 --- a/test/stubs/_includes/includedvar.pug +++ /dev/null @@ -1 +0,0 @@ -span This is #{name}. \ No newline at end of file diff --git a/test/stubs/_includes/layout-a.ejs b/test/stubs/_includes/layout-a.liquid similarity index 83% rename from test/stubs/_includes/layout-a.ejs rename to test/stubs/_includes/layout-a.liquid index 49ff36f00..2b4fbf3f2 100644 --- a/test/stubs/_includes/layout-a.ejs +++ b/test/stubs/_includes/layout-a.liquid @@ -5,5 +5,5 @@ upstream: value2-a ---
- <%- content %> + {{ content }}
diff --git a/test/stubs/_includes/layout-b.ejs b/test/stubs/_includes/layout-b.liquid similarity index 83% rename from test/stubs/_includes/layout-b.ejs rename to test/stubs/_includes/layout-b.liquid index 05c6bb6d0..216e6f9c2 100644 --- a/test/stubs/_includes/layout-b.ejs +++ b/test/stubs/_includes/layout-b.liquid @@ -5,5 +5,5 @@ daysPosted: 154 ---
- <%- content %> + {{ content }}
diff --git a/test/stubs/_includes/layout.pug b/test/stubs/_includes/layout.pug deleted file mode 100644 index dc1969a8e..000000000 --- a/test/stubs/_includes/layout.pug +++ /dev/null @@ -1,3 +0,0 @@ -html - body - block content \ No newline at end of file diff --git a/test/stubs/_includes/layouts/post.ejs b/test/stubs/_includes/layouts/post.liquid similarity index 100% rename from test/stubs/_includes/layouts/post.ejs rename to test/stubs/_includes/layouts/post.liquid diff --git a/test/stubs/_includes/layouts/usescollection.ejs b/test/stubs/_includes/multiple.liquid similarity index 100% rename from test/stubs/_includes/layouts/usescollection.ejs rename to test/stubs/_includes/multiple.liquid diff --git a/test/stubs/_includes/permalink-in-layout/layout-fileslug.ejs b/test/stubs/_includes/permalink-in-layout/layout-fileslug.ejs deleted file mode 100644 index 0b7698c32..000000000 --- a/test/stubs/_includes/permalink-in-layout/layout-fileslug.ejs +++ /dev/null @@ -1,4 +0,0 @@ ---- -permalink: test/<%= page.fileSlug %>/ ---- -<%- content %> \ No newline at end of file diff --git a/test/stubs/_includes/permalink-in-layout/layout-fileslug.liquid b/test/stubs/_includes/permalink-in-layout/layout-fileslug.liquid new file mode 100644 index 000000000..920185e8d --- /dev/null +++ b/test/stubs/_includes/permalink-in-layout/layout-fileslug.liquid @@ -0,0 +1,4 @@ +--- +permalink: test/{{ page.fileSlug }}/ +--- +{{ content }} \ No newline at end of file diff --git a/test/stubs/_includes/permalink-in-layout/layout.ejs b/test/stubs/_includes/permalink-in-layout/layout.liquid similarity index 72% rename from test/stubs/_includes/permalink-in-layout/layout.ejs rename to test/stubs/_includes/permalink-in-layout/layout.liquid index e6d64bf9a..0ef8e024f 100644 --- a/test/stubs/_includes/permalink-in-layout/layout.ejs +++ b/test/stubs/_includes/permalink-in-layout/layout.liquid @@ -1,4 +1,4 @@ --- permalink: hello/index.html --- -<%- content %> \ No newline at end of file +{{ content }} \ No newline at end of file diff --git a/test/stubs/_includes/subfolder/included.hbs b/test/stubs/_includes/subfolder/included.hbs deleted file mode 100644 index 6b622104c..000000000 --- a/test/stubs/_includes/subfolder/included.hbs +++ /dev/null @@ -1 +0,0 @@ -This is an include. \ No newline at end of file diff --git a/test/stubs/_includes/subfolder/included.mustache b/test/stubs/_includes/subfolder/included.mustache deleted file mode 100644 index 6b622104c..000000000 --- a/test/stubs/_includes/subfolder/included.mustache +++ /dev/null @@ -1 +0,0 @@ -This is an include. \ No newline at end of file diff --git a/test/stubs/_includes/multiple.ejs b/test/stubs/_layouts/layoutsdefault.liquid similarity index 100% rename from test/stubs/_includes/multiple.ejs rename to test/stubs/_layouts/layoutsdefault.liquid diff --git a/test/stubs/broken-config.js b/test/stubs/broken-config.cjs similarity index 100% rename from test/stubs/broken-config.js rename to test/stubs/broken-config.cjs diff --git a/test/stubs/buffer.11ty.js b/test/stubs/buffer.11ty.cjs similarity index 100% rename from test/stubs/buffer.11ty.js rename to test/stubs/buffer.11ty.cjs diff --git a/test/stubs/class-async-data-fn.11ty.js b/test/stubs/class-async-data-fn.11ty.cjs similarity index 100% rename from test/stubs/class-async-data-fn.11ty.js rename to test/stubs/class-async-data-fn.11ty.cjs diff --git a/test/stubs/class-async-filter.11ty.js b/test/stubs/class-async-filter.11ty.cjs similarity index 100% rename from test/stubs/class-async-filter.11ty.js rename to test/stubs/class-async-filter.11ty.cjs diff --git a/test/stubs/class-async.11ty.js b/test/stubs/class-async.11ty.cjs similarity index 100% rename from test/stubs/class-async.11ty.js rename to test/stubs/class-async.11ty.cjs diff --git a/test/stubs/class-buffer.11ty.js b/test/stubs/class-buffer.11ty.cjs similarity index 100% rename from test/stubs/class-buffer.11ty.js rename to test/stubs/class-buffer.11ty.cjs diff --git a/test/stubs/class-data-filter.11ty.js b/test/stubs/class-data-filter.11ty.cjs similarity index 100% rename from test/stubs/class-data-filter.11ty.js rename to test/stubs/class-data-filter.11ty.cjs diff --git a/test/stubs/class-data-fn-filter.11ty.js b/test/stubs/class-data-fn-filter.11ty.cjs similarity index 100% rename from test/stubs/class-data-fn-filter.11ty.js rename to test/stubs/class-data-fn-filter.11ty.cjs diff --git a/test/stubs/class-data-fn-shorthand.11ty.js b/test/stubs/class-data-fn-shorthand.11ty.cjs similarity index 100% rename from test/stubs/class-data-fn-shorthand.11ty.js rename to test/stubs/class-data-fn-shorthand.11ty.cjs diff --git a/test/stubs/class-data-fn.11ty.js b/test/stubs/class-data-fn.11ty.cjs similarity index 100% rename from test/stubs/class-data-fn.11ty.js rename to test/stubs/class-data-fn.11ty.cjs diff --git a/test/stubs/class-data-permalink-async-fn.11ty.js b/test/stubs/class-data-permalink-async-fn.11ty.cjs similarity index 100% rename from test/stubs/class-data-permalink-async-fn.11ty.js rename to test/stubs/class-data-permalink-async-fn.11ty.cjs diff --git a/test/stubs/class-data-permalink-buffer.11ty.js b/test/stubs/class-data-permalink-buffer.11ty.cjs similarity index 100% rename from test/stubs/class-data-permalink-buffer.11ty.js rename to test/stubs/class-data-permalink-buffer.11ty.cjs diff --git a/test/stubs/class-data-permalink-fn-buffer.11ty.js b/test/stubs/class-data-permalink-fn-buffer.11ty.cjs similarity index 100% rename from test/stubs/class-data-permalink-fn-buffer.11ty.js rename to test/stubs/class-data-permalink-fn-buffer.11ty.cjs diff --git a/test/stubs/class-data-permalink-fn-filter.11ty.js b/test/stubs/class-data-permalink-fn-filter.11ty.cjs similarity index 100% rename from test/stubs/class-data-permalink-fn-filter.11ty.js rename to test/stubs/class-data-permalink-fn-filter.11ty.cjs diff --git a/test/stubs/class-data-permalink-fn.11ty.js b/test/stubs/class-data-permalink-fn.11ty.cjs similarity index 100% rename from test/stubs/class-data-permalink-fn.11ty.js rename to test/stubs/class-data-permalink-fn.11ty.cjs diff --git a/test/stubs/class-data-permalink.11ty.js b/test/stubs/class-data-permalink.11ty.cjs similarity index 100% rename from test/stubs/class-data-permalink.11ty.js rename to test/stubs/class-data-permalink.11ty.cjs diff --git a/test/stubs/class-data.11ty.js b/test/stubs/class-data.11ty.cjs similarity index 100% rename from test/stubs/class-data.11ty.js rename to test/stubs/class-data.11ty.cjs diff --git a/test/stubs/class-filter.11ty.js b/test/stubs/class-filter.11ty.cjs similarity index 100% rename from test/stubs/class-filter.11ty.js rename to test/stubs/class-filter.11ty.cjs diff --git a/test/stubs/class-fns-has-page.11ty.js b/test/stubs/class-fns-has-page.11ty.cjs similarity index 100% rename from test/stubs/class-fns-has-page.11ty.js rename to test/stubs/class-fns-has-page.11ty.cjs diff --git a/test/stubs/class-fns.11ty.js b/test/stubs/class-fns.11ty.cjs similarity index 100% rename from test/stubs/class-fns.11ty.js rename to test/stubs/class-fns.11ty.cjs diff --git a/test/stubs/class-norender.11ty.js b/test/stubs/class-norender.11ty.cjs similarity index 100% rename from test/stubs/class-norender.11ty.js rename to test/stubs/class-norender.11ty.cjs diff --git a/test/stubs/class-with-dep.11ty.js b/test/stubs/class-with-dep.11ty.cjs similarity index 90% rename from test/stubs/class-with-dep.11ty.js rename to test/stubs/class-with-dep.11ty.cjs index 2942a8a6d..5dc2c344e 100644 --- a/test/stubs/class-with-dep.11ty.js +++ b/test/stubs/class-with-dep.11ty.cjs @@ -4,14 +4,12 @@ class Test { returnsBill() { return "Bill"; } - static returnsTed() { return "Ted"; } - render({ name }) { return `

${name}${this.returnsBill()}${Test.returnsTed()}

`; } } -module.exports = Test; +module.exports = Test; \ No newline at end of file diff --git a/test/stubs/class.11ty.js b/test/stubs/class.11ty.cjs similarity index 100% rename from test/stubs/class.11ty.js rename to test/stubs/class.11ty.cjs diff --git a/test/stubs/classfields-data.11ty.js b/test/stubs/classfields-data.11ty.cjs similarity index 100% rename from test/stubs/classfields-data.11ty.js rename to test/stubs/classfields-data.11ty.cjs diff --git a/test/stubs/collection-layout/_includes/layout.ejs b/test/stubs/collection-layout/_includes/layout.ejs deleted file mode 100644 index 80c8f97ce..000000000 --- a/test/stubs/collection-layout/_includes/layout.ejs +++ /dev/null @@ -1,6 +0,0 @@ -Layout - -<%- content %> - -All <%= collections.all.length %> templates -Layout <%= collections.dog.length %> dog \ No newline at end of file diff --git a/test/stubs/collection-layout/_includes/layout.liquid b/test/stubs/collection-layout/_includes/layout.liquid new file mode 100644 index 000000000..92ba0bf29 --- /dev/null +++ b/test/stubs/collection-layout/_includes/layout.liquid @@ -0,0 +1,6 @@ +Layout + +{{ content }} + +All {{ collections.all | size }} templates +Layout {{ collections.dog | size }} dog \ No newline at end of file diff --git a/test/stubs/collection-layout/dog1.ejs b/test/stubs/collection-layout/dog1.liquid similarity index 100% rename from test/stubs/collection-layout/dog1.ejs rename to test/stubs/collection-layout/dog1.liquid diff --git a/test/stubs/collection-layout/template.ejs b/test/stubs/collection-layout/template.ejs deleted file mode 100644 index 9e8ba1f38..000000000 --- a/test/stubs/collection-layout/template.ejs +++ /dev/null @@ -1,4 +0,0 @@ ---- -layout: layout.ejs ---- -Template \ No newline at end of file diff --git a/test/stubs/collection-layout/template.liquid b/test/stubs/collection-layout/template.liquid new file mode 100644 index 000000000..430bd2b29 --- /dev/null +++ b/test/stubs/collection-layout/template.liquid @@ -0,0 +1,4 @@ +--- +layout: layout.liquid +--- +Template \ No newline at end of file diff --git a/test/stubs/collection-template/_includes/layout.ejs b/test/stubs/collection-template/_includes/layout.ejs deleted file mode 100644 index ef9a6ab92..000000000 --- a/test/stubs/collection-template/_includes/layout.ejs +++ /dev/null @@ -1,3 +0,0 @@ -Layout - -<%- content %> \ No newline at end of file diff --git a/test/stubs/collection-template/_includes/layout.liquid b/test/stubs/collection-template/_includes/layout.liquid new file mode 100644 index 000000000..8de4421d6 --- /dev/null +++ b/test/stubs/collection-template/_includes/layout.liquid @@ -0,0 +1,3 @@ +Layout + +{{ content }} \ No newline at end of file diff --git a/test/stubs/collection-template/dog1.ejs b/test/stubs/collection-template/dog1.liquid similarity index 100% rename from test/stubs/collection-template/dog1.ejs rename to test/stubs/collection-template/dog1.liquid diff --git a/test/stubs/collection-template/template.ejs b/test/stubs/collection-template/template.ejs deleted file mode 100644 index cdb900434..000000000 --- a/test/stubs/collection-template/template.ejs +++ /dev/null @@ -1,7 +0,0 @@ ---- -layout: layout.ejs ---- -Template - -All <%= collections.all.length %> templates -Template <%= collections.dog.length %> dog \ No newline at end of file diff --git a/test/stubs/collection-template/template.liquid b/test/stubs/collection-template/template.liquid new file mode 100644 index 000000000..5dc3b5665 --- /dev/null +++ b/test/stubs/collection-template/template.liquid @@ -0,0 +1,7 @@ +--- +layout: layout.liquid +--- +Template + +All {{ collections.all | size }} templates +Template {{ collections.dog | size }} dog \ No newline at end of file diff --git a/test/stubs/component-async/component.11tydata.js b/test/stubs/component-async/component.11tydata.js index cc248eaf1..9cbab475f 100644 --- a/test/stubs/component-async/component.11tydata.js +++ b/test/stubs/component-async/component.11tydata.js @@ -1,9 +1,9 @@ -module.exports = async function() { - return new Promise(resolve => { - setTimeout(function() { +export default async function () { + return new Promise((resolve) => { + setTimeout(function () { resolve({ - localdatakeyfromjs: "howdydoody" + localdatakeyfromjs: "howdydoody", }); }, 1); }); -}; +} diff --git a/test/stubs/component/component.11tydata.cjs b/test/stubs/component/component.11tydata.cjs index f9b055acb..862921eab 100644 --- a/test/stubs/component/component.11tydata.cjs +++ b/test/stubs/component/component.11tydata.cjs @@ -1,4 +1,4 @@ -const dep2 = require("../deps/dep2"); +const dep2 = require("../deps/dep2.cjs"); module.exports = { localdatakeyfromcjs: "common-js-howdydoody" diff --git a/test/stubs/component/component.11tydata.js b/test/stubs/component/component.11tydata.js index 88f198b73..647067cfd 100644 --- a/test/stubs/component/component.11tydata.js +++ b/test/stubs/component/component.11tydata.js @@ -1,5 +1,5 @@ -const dep2 = require("../deps/dep2"); +import dep2 from "../deps/dep2.cjs"; -module.exports = { - localdatakeyfromjs: "howdydoody" +export default { + localdatakeyfromjs: "howdydoody", }; diff --git a/test/stubs/config-deps-upstream.js b/test/stubs/config-deps-upstream.cjs similarity index 100% rename from test/stubs/config-deps-upstream.js rename to test/stubs/config-deps-upstream.cjs diff --git a/test/stubs/config-deps.js b/test/stubs/config-deps.cjs similarity index 63% rename from test/stubs/config-deps.js rename to test/stubs/config-deps.cjs index dd3ac6fd6..93496cced 100644 --- a/test/stubs/config-deps.js +++ b/test/stubs/config-deps.cjs @@ -1,5 +1,5 @@ const pretty = require("pretty"); -const Dep = require("./config-deps-upstream"); +const Dep = require("./config-deps-upstream.cjs"); module.exports = function(config) { return {}; diff --git a/test/stubs/config-empty-pathprefix.js b/test/stubs/config-empty-pathprefix.cjs similarity index 100% rename from test/stubs/config-empty-pathprefix.js rename to test/stubs/config-empty-pathprefix.cjs diff --git a/test/stubs/config.js b/test/stubs/config.cjs similarity index 94% rename from test/stubs/config.js rename to test/stubs/config.cjs index e4665426b..db7f0fdcf 100644 --- a/test/stubs/config.js +++ b/test/stubs/config.cjs @@ -11,7 +11,7 @@ module.exports = function (config) { } */ return { - markdownTemplateEngine: "ejs", + markdownTemplateEngine: "njk", templateFormats: ["md", "njk"], pathPrefix: "/testdir", diff --git a/test/stubs/data-cascade/template.11tydata.js b/test/stubs/data-cascade/template.11tydata.cjs similarity index 100% rename from test/stubs/data-cascade/template.11tydata.js rename to test/stubs/data-cascade/template.11tydata.cjs diff --git a/test/stubs/dependencies/dep1.js b/test/stubs/dependencies/dep1.cjs similarity index 100% rename from test/stubs/dependencies/dep1.js rename to test/stubs/dependencies/dep1.cjs diff --git a/test/stubs/dependencies/dep2.js b/test/stubs/dependencies/dep2.cjs similarity index 100% rename from test/stubs/dependencies/dep2.js rename to test/stubs/dependencies/dep2.cjs diff --git a/test/stubs/dependencies/two-deps.11ty.cjs b/test/stubs/dependencies/two-deps.11ty.cjs new file mode 100644 index 000000000..b056e23dd --- /dev/null +++ b/test/stubs/dependencies/two-deps.11ty.cjs @@ -0,0 +1,4 @@ +const dep1 = require("./dep1.cjs"); +const dep2 = require("./dep2.cjs"); + +module.exports = ""; diff --git a/test/stubs/dependencies/two-deps.11ty.js b/test/stubs/dependencies/two-deps.11ty.js deleted file mode 100644 index 018282839..000000000 --- a/test/stubs/dependencies/two-deps.11ty.js +++ /dev/null @@ -1,4 +0,0 @@ -const dep1 = require("./dep1"); -const dep2 = require("./dep2"); - -module.exports = ""; diff --git a/test/stubs/deps/dep1.js b/test/stubs/deps/dep1.cjs similarity index 100% rename from test/stubs/deps/dep1.js rename to test/stubs/deps/dep1.cjs diff --git a/test/stubs/deps/dep2.js b/test/stubs/deps/dep2.cjs similarity index 100% rename from test/stubs/deps/dep2.js rename to test/stubs/deps/dep2.cjs diff --git a/test/stubs/exports-flatdata.11ty.js b/test/stubs/exports-flatdata.11ty.cjs similarity index 100% rename from test/stubs/exports-flatdata.11ty.js rename to test/stubs/exports-flatdata.11ty.cjs diff --git a/test/stubs/fileslug.11ty.js b/test/stubs/fileslug.11ty.cjs similarity index 100% rename from test/stubs/fileslug.11ty.js rename to test/stubs/fileslug.11ty.cjs diff --git a/test/stubs/function-arrow.11ty.js b/test/stubs/function-arrow.11ty.cjs similarity index 100% rename from test/stubs/function-arrow.11ty.js rename to test/stubs/function-arrow.11ty.cjs diff --git a/test/stubs/function-async-filter.11ty.js b/test/stubs/function-async-filter.11ty.cjs similarity index 100% rename from test/stubs/function-async-filter.11ty.js rename to test/stubs/function-async-filter.11ty.cjs diff --git a/test/stubs/function-async.11ty.js b/test/stubs/function-async.11ty.cjs similarity index 100% rename from test/stubs/function-async.11ty.js rename to test/stubs/function-async.11ty.cjs diff --git a/test/stubs/function-buffer.11ty.js b/test/stubs/function-buffer.11ty.cjs similarity index 100% rename from test/stubs/function-buffer.11ty.js rename to test/stubs/function-buffer.11ty.cjs diff --git a/test/stubs/function-filter.11ty.js b/test/stubs/function-filter.11ty.cjs similarity index 100% rename from test/stubs/function-filter.11ty.js rename to test/stubs/function-filter.11ty.cjs diff --git a/test/stubs/function-fns.11ty.js b/test/stubs/function-fns.11ty.cjs similarity index 100% rename from test/stubs/function-fns.11ty.js rename to test/stubs/function-fns.11ty.cjs diff --git a/test/stubs/function-markdown.11ty.js b/test/stubs/function-markdown.11ty.cjs similarity index 100% rename from test/stubs/function-markdown.11ty.js rename to test/stubs/function-markdown.11ty.cjs diff --git a/test/stubs/function-prototype.11ty.js b/test/stubs/function-prototype.11ty.cjs similarity index 100% rename from test/stubs/function-prototype.11ty.js rename to test/stubs/function-prototype.11ty.cjs diff --git a/test/stubs/function-throws-async.11ty.js b/test/stubs/function-throws-async.11ty.cjs similarity index 100% rename from test/stubs/function-throws-async.11ty.js rename to test/stubs/function-throws-async.11ty.cjs diff --git a/test/stubs/function-throws.11ty.js b/test/stubs/function-throws.11ty.cjs similarity index 100% rename from test/stubs/function-throws.11ty.js rename to test/stubs/function-throws.11ty.cjs diff --git a/test/stubs/function.11ty.js b/test/stubs/function.11ty.cjs similarity index 100% rename from test/stubs/function.11ty.js rename to test/stubs/function.11ty.cjs diff --git a/test/stubs/included.hbs b/test/stubs/included.hbs deleted file mode 100644 index 28f1f1852..000000000 --- a/test/stubs/included.hbs +++ /dev/null @@ -1 +0,0 @@ -This is an includdde. \ No newline at end of file diff --git a/test/stubs/included.pug b/test/stubs/included.pug deleted file mode 100644 index c4fd5a685..000000000 --- a/test/stubs/included.pug +++ /dev/null @@ -1 +0,0 @@ -span This is a relative include. \ No newline at end of file diff --git a/test/stubs/includedrelative.ejs b/test/stubs/includedrelative.ejs deleted file mode 100644 index 3463e0a15..000000000 --- a/test/stubs/includedrelative.ejs +++ /dev/null @@ -1 +0,0 @@ -This is a relative include. \ No newline at end of file diff --git a/test/stubs/includedrelative.mustache b/test/stubs/includedrelative.mustache deleted file mode 100644 index 28f1f1852..000000000 --- a/test/stubs/includedrelative.mustache +++ /dev/null @@ -1 +0,0 @@ -This is an includdde. \ No newline at end of file diff --git a/test/stubs/_layouts/layoutsdefault.ejs b/test/stubs/includesemptystring.liquid similarity index 100% rename from test/stubs/_layouts/layoutsdefault.ejs rename to test/stubs/includesemptystring.liquid diff --git a/test/stubs/default.ejs b/test/stubs/index.liquid similarity index 100% rename from test/stubs/default.ejs rename to test/stubs/index.liquid diff --git a/test/stubs/layout-relative.pug b/test/stubs/layout-relative.pug deleted file mode 100644 index dc1969a8e..000000000 --- a/test/stubs/layout-relative.pug +++ /dev/null @@ -1,3 +0,0 @@ -html - body - block content \ No newline at end of file diff --git a/test/stubs/includesemptystring.ejs b/test/stubs/layoutsemptystring.liquid similarity index 100% rename from test/stubs/includesemptystring.ejs rename to test/stubs/layoutsemptystring.liquid diff --git a/test/stubs/local-data-tags/component.11tydata.js b/test/stubs/local-data-tags/component.11tydata.cjs similarity index 100% rename from test/stubs/local-data-tags/component.11tydata.js rename to test/stubs/local-data-tags/component.11tydata.cjs diff --git a/test/stubs/multipleexports-promises.11ty.js b/test/stubs/multipleexports-promises.11ty.cjs similarity index 100% rename from test/stubs/multipleexports-promises.11ty.js rename to test/stubs/multipleexports-promises.11ty.cjs diff --git a/test/stubs/multipleexports.11ty.js b/test/stubs/multipleexports.11ty.cjs similarity index 100% rename from test/stubs/multipleexports.11ty.js rename to test/stubs/multipleexports.11ty.cjs diff --git a/test/stubs/object-norender.11ty.js b/test/stubs/object-norender.11ty.cjs similarity index 100% rename from test/stubs/object-norender.11ty.js rename to test/stubs/object-norender.11ty.cjs diff --git a/test/stubs/object.11ty.js b/test/stubs/object.11ty.cjs similarity index 100% rename from test/stubs/object.11ty.js rename to test/stubs/object.11ty.cjs diff --git a/test/stubs/oneinstance.11ty.js b/test/stubs/oneinstance.11ty.cjs similarity index 100% rename from test/stubs/oneinstance.11ty.js rename to test/stubs/oneinstance.11ty.cjs diff --git a/test/stubs/overrides/layout.njk b/test/stubs/overrides/layout.njk index b2ef6a93a..50ca39c3c 100644 --- a/test/stubs/overrides/layout.njk +++ b/test/stubs/overrides/layout.njk @@ -1,6 +1,6 @@ --- -templateEngineOverride: ejs +templateEngineOverride: liquid title: My Title layout: layouts/engineOverrides.njk --- -

<%= title %>

\ No newline at end of file +

{{ title | size }}

\ No newline at end of file diff --git a/test/stubs/overrides/test-bypass.md b/test/stubs/overrides/test-bypass.md index 9f09d4bf6..3d0cc0683 100644 --- a/test/stubs/overrides/test-bypass.md +++ b/test/stubs/overrides/test-bypass.md @@ -1,6 +1,6 @@ --- -templateEngineOverride: ejs +templateEngineOverride: njk title: My Title --- -# <%= title %> +# {{ title }} diff --git a/test/stubs/overrides/test-ejs.liquid b/test/stubs/overrides/test-ejs.liquid deleted file mode 100644 index badd12bce..000000000 --- a/test/stubs/overrides/test-ejs.liquid +++ /dev/null @@ -1,5 +0,0 @@ ---- -templateEngineOverride: ejs -title: My Title ---- -<%= title %> diff --git a/test/stubs/overrides/test-empty.html b/test/stubs/overrides/test-empty.html index 8951af3c3..297b7dcd1 100644 --- a/test/stubs/overrides/test-empty.html +++ b/test/stubs/overrides/test-empty.html @@ -2,4 +2,4 @@ templateEngineOverride: title: My Title --- -

<%= title %>

+

{{ title }}

diff --git a/test/stubs/overrides/test-empty.md b/test/stubs/overrides/test-empty.md index 521d1ad6f..c5b239d94 100644 --- a/test/stubs/overrides/test-empty.md +++ b/test/stubs/overrides/test-empty.md @@ -3,4 +3,4 @@ templateEngineOverride: title: My Title --- -# <%= title %> +# {{ title }} diff --git a/test/stubs/overrides/test-error.njk b/test/stubs/overrides/test-error.njk index 7cf0cab4e..7a9a259e7 100644 --- a/test/stubs/overrides/test-error.njk +++ b/test/stubs/overrides/test-error.njk @@ -1,5 +1,5 @@ --- -templateEngineOverride: ejs,njk +templateEngineOverride: liquid,njk title: My Title --- -# <%= title %> +# {{ title }} diff --git a/test/stubs/overrides/test-multiple.md b/test/stubs/overrides/test-multiple.md index 097f5c481..f135c80c8 100644 --- a/test/stubs/overrides/test-multiple.md +++ b/test/stubs/overrides/test-multiple.md @@ -1,6 +1,6 @@ --- -templateEngineOverride: ejs,md +templateEngineOverride: njk,md title: My Title --- -# <%= title %> +# {{ title }} diff --git a/test/stubs/overrides/test-multiple2.njk b/test/stubs/overrides/test-multiple2.njk index c59324a3c..d5147f67d 100644 --- a/test/stubs/overrides/test-multiple2.njk +++ b/test/stubs/overrides/test-multiple2.njk @@ -1,5 +1,5 @@ --- -templateEngineOverride: ejs,md +templateEngineOverride: liquid,md title: My Title --- -# <%= title %> +# {{ title }} diff --git a/test/stubs/overrides/test.ejs b/test/stubs/overrides/test-njk.liquid similarity index 100% rename from test/stubs/overrides/test.ejs rename to test/stubs/overrides/test-njk.liquid diff --git a/test/stubs/overrides/test.html b/test/stubs/overrides/test.html index 9e1a5db22..8b483c3cf 100644 --- a/test/stubs/overrides/test.html +++ b/test/stubs/overrides/test.html @@ -1,5 +1,5 @@ --- -templateEngineOverride: ejs +templateEngineOverride: njk title: My Title --- -

<%= title %>

+

{{ title }}

diff --git a/test/stubs/overrides/test.liquid b/test/stubs/overrides/test.liquid new file mode 100644 index 000000000..7170e4147 --- /dev/null +++ b/test/stubs/overrides/test.liquid @@ -0,0 +1,5 @@ +--- +templateEngineOverride: njk +title: My Title +--- +{{ title }} diff --git a/test/stubs/overrides/test2.md b/test/stubs/overrides/test2.md deleted file mode 100644 index 53f857eb9..000000000 --- a/test/stubs/overrides/test2.md +++ /dev/null @@ -1,7 +0,0 @@ ---- -title: My Title -templateEngineOverride: ejs,md -layout: layouts/engineOverridesMd.njk ---- - -# <%= title %> diff --git a/test/stubs/paged-global-data-mutable/_data/testdata.js b/test/stubs/paged-global-data-mutable/_data/testdata.cjs similarity index 100% rename from test/stubs/paged-global-data-mutable/_data/testdata.js rename to test/stubs/paged-global-data-mutable/_data/testdata.cjs diff --git a/test/stubs/permalink-build-serverless-rendered/permalink-build-serverless-rendered.md b/test/stubs/permalink-build-serverless-rendered/permalink-build-serverless-rendered.md deleted file mode 100644 index 051ab7ff3..000000000 --- a/test/stubs/permalink-build-serverless-rendered/permalink-build-serverless-rendered.md +++ /dev/null @@ -1,9 +0,0 @@ ---- -slug1: "url" -slug2: "some-other-url" -permalink: - build: "/{{ slug1 }}/" - serverless: "/{{ slug2 }}/" ---- - -This should be the same as `permalink: /url/` diff --git a/test/stubs/permalink-build-serverless/permalink-build-serverless.md b/test/stubs/permalink-build-serverless/permalink-build-serverless.md deleted file mode 100644 index 49eb09c82..000000000 --- a/test/stubs/permalink-build-serverless/permalink-build-serverless.md +++ /dev/null @@ -1,7 +0,0 @@ ---- -permalink: - build: "/url/" - serverless: "/some-other-url/" ---- - -This should be the same as `permalink: /url/` diff --git a/test/stubs/permalink-in-layout-fileslug.ejs b/test/stubs/permalink-in-layout-fileslug.ejs deleted file mode 100644 index f8789ce2c..000000000 --- a/test/stubs/permalink-in-layout-fileslug.ejs +++ /dev/null @@ -1,4 +0,0 @@ ---- -layout: permalink-in-layout/layout-fileslug.ejs ---- -Current url: <%= permalink %> \ No newline at end of file diff --git a/test/stubs/permalink-in-layout-fileslug.liquid b/test/stubs/permalink-in-layout-fileslug.liquid new file mode 100644 index 000000000..69277c60d --- /dev/null +++ b/test/stubs/permalink-in-layout-fileslug.liquid @@ -0,0 +1,4 @@ +--- +layout: permalink-in-layout/layout-fileslug.liquid +--- +Current url: {{ permalink }} \ No newline at end of file diff --git a/test/stubs/permalink-in-layout.ejs b/test/stubs/permalink-in-layout.ejs deleted file mode 100644 index 6c47953de..000000000 --- a/test/stubs/permalink-in-layout.ejs +++ /dev/null @@ -1,4 +0,0 @@ ---- -layout: permalink-in-layout/layout.ejs ---- -Current url: <%= permalink %> \ No newline at end of file diff --git a/test/stubs/permalink-in-layout.liquid b/test/stubs/permalink-in-layout.liquid new file mode 100644 index 000000000..6be49d089 --- /dev/null +++ b/test/stubs/permalink-in-layout.liquid @@ -0,0 +1,4 @@ +--- +layout: permalink-in-layout/layout.liquid +--- +Current url: {{ permalink }} \ No newline at end of file diff --git a/test/stubs/permalink-nobuild/permalink-nobuild.md b/test/stubs/permalink-nobuild/permalink-nobuild.md index 390e4be65..a9d7aad11 100644 --- a/test/stubs/permalink-nobuild/permalink-nobuild.md +++ b/test/stubs/permalink-nobuild/permalink-nobuild.md @@ -1,6 +1,6 @@ --- permalink: - serverless: /url/ + someotherkey: /url/ --- This shouldn’t write to the file system or be rendered by a template engine. diff --git a/test/stubs/permalink-serverless-empty-pagination/permalink-serverless-empty-pagination.md b/test/stubs/permalink-serverless-empty-pagination/permalink-serverless-empty-pagination.md deleted file mode 100644 index 20bfaf844..000000000 --- a/test/stubs/permalink-serverless-empty-pagination/permalink-serverless-empty-pagination.md +++ /dev/null @@ -1,8 +0,0 @@ ---- -sampledata: [] -pagination: - data: sampledata - size: 1 -permalink: - serverless: /url/ ---- diff --git a/test/stubs/permalinked.ejs b/test/stubs/permalinked.liquid similarity index 62% rename from test/stubs/permalinked.ejs rename to test/stubs/permalinked.liquid index c73bcfc3a..bcaaeca35 100644 --- a/test/stubs/permalinked.ejs +++ b/test/stubs/permalinked.liquid @@ -1,4 +1,4 @@ --- permalink: permalinksubfolder/index.html --- -Current url: <%= permalink %> \ No newline at end of file +Current url: {{ permalink }} \ No newline at end of file diff --git a/test/stubs/prematureTemplateContent/test.11ty.js b/test/stubs/prematureTemplateContent/test.11ty.cjs similarity index 100% rename from test/stubs/prematureTemplateContent/test.11ty.js rename to test/stubs/prematureTemplateContent/test.11ty.cjs diff --git a/test/stubs/prematureTemplateContent/test.ejs b/test/stubs/prematureTemplateContent/test.ejs deleted file mode 100644 index e080c8428..000000000 --- a/test/stubs/prematureTemplateContent/test.ejs +++ /dev/null @@ -1 +0,0 @@ -<%= collections.all[0].templateContent %> \ No newline at end of file diff --git a/test/stubs/prematureTemplateContent/test.haml b/test/stubs/prematureTemplateContent/test.haml deleted file mode 100644 index aafbbc3c1..000000000 --- a/test/stubs/prematureTemplateContent/test.haml +++ /dev/null @@ -1 +0,0 @@ -%p= collections.all[0].templateContent \ No newline at end of file diff --git a/test/stubs/prematureTemplateContent/test.hbs b/test/stubs/prematureTemplateContent/test.hbs deleted file mode 100644 index cedc058a8..000000000 --- a/test/stubs/prematureTemplateContent/test.hbs +++ /dev/null @@ -1 +0,0 @@ -{{ sample.templateContent }} \ No newline at end of file diff --git a/test/stubs/prematureTemplateContent/test.mustache b/test/stubs/prematureTemplateContent/test.mustache deleted file mode 100644 index ff264d1ed..000000000 --- a/test/stubs/prematureTemplateContent/test.mustache +++ /dev/null @@ -1 +0,0 @@ -{{ collections.all[0].templateContent }} \ No newline at end of file diff --git a/test/stubs/prematureTemplateContent/test.pug b/test/stubs/prematureTemplateContent/test.pug deleted file mode 100644 index d11072702..000000000 --- a/test/stubs/prematureTemplateContent/test.pug +++ /dev/null @@ -1 +0,0 @@ -p= sample.templateContent \ No newline at end of file diff --git a/test/stubs/promise.11ty.js b/test/stubs/promise.11ty.cjs similarity index 100% rename from test/stubs/promise.11ty.js rename to test/stubs/promise.11ty.cjs diff --git a/test/stubs/relative-ejs/dir/included.ejs b/test/stubs/relative-ejs/dir/included.ejs deleted file mode 100644 index 6b622104c..000000000 --- a/test/stubs/relative-ejs/dir/included.ejs +++ /dev/null @@ -1 +0,0 @@ -This is an include. \ No newline at end of file diff --git a/test/stubs/string.11ty.js b/test/stubs/string.11ty.cjs similarity index 100% rename from test/stubs/string.11ty.js rename to test/stubs/string.11ty.cjs diff --git a/test/stubs/string.11ty.custom b/test/stubs/string.11ty.custom index e9aa24752..6b32cc46d 100644 --- a/test/stubs/string.11ty.custom +++ b/test/stubs/string.11ty.custom @@ -1 +1 @@ -module.exports = "

Zach

"; +export default "

Zach

"; diff --git a/test/stubs/string.11ty.possum b/test/stubs/string.11ty.possum index 195193ce3..646a5eda8 100644 --- a/test/stubs/string.11ty.possum +++ b/test/stubs/string.11ty.possum @@ -1 +1 @@ -module.exports = "

Possum

"; +export default "

Possum

"; diff --git a/test/stubs/stubs-computed-permalink/eleventycomputed-nested-object.11ty.js b/test/stubs/stubs-computed-permalink/eleventycomputed-nested-object.11ty.cjs similarity index 62% rename from test/stubs/stubs-computed-permalink/eleventycomputed-nested-object.11ty.js rename to test/stubs/stubs-computed-permalink/eleventycomputed-nested-object.11ty.cjs index d732abd32..6775b2342 100644 --- a/test/stubs/stubs-computed-permalink/eleventycomputed-nested-object.11ty.js +++ b/test/stubs/stubs-computed-permalink/eleventycomputed-nested-object.11ty.cjs @@ -2,8 +2,9 @@ module.exports.data = { lang: "en", eleventyComputed: { permalink: function (data) { + // console.log(">>>>", { data }); return { - serverless: `/i18n/${data.lang}/`, + build: `/i18n/${data.lang}/`, }; }, }, diff --git a/test/stubs/stubs-computed-permalink/eleventycomputed-object-replace.11ty.js b/test/stubs/stubs-computed-permalink/eleventycomputed-object-replace.11ty.cjs similarity index 72% rename from test/stubs/stubs-computed-permalink/eleventycomputed-object-replace.11ty.js rename to test/stubs/stubs-computed-permalink/eleventycomputed-object-replace.11ty.cjs index 6cd62d75e..f0407342d 100644 --- a/test/stubs/stubs-computed-permalink/eleventycomputed-object-replace.11ty.js +++ b/test/stubs/stubs-computed-permalink/eleventycomputed-object-replace.11ty.cjs @@ -4,7 +4,7 @@ module.exports.data = { eleventyComputed: { permalink: function (data) { return { - serverless: data.permalink.replace("{{lang}}", "en"), + build: data.permalink.replace("{{lang}}", "en"), }; }, }, diff --git a/test/stubs/stubs-computed-permalink/eleventycomputed-object.11ty.js b/test/stubs/stubs-computed-permalink/eleventycomputed-object.11ty.cjs similarity index 79% rename from test/stubs/stubs-computed-permalink/eleventycomputed-object.11ty.js rename to test/stubs/stubs-computed-permalink/eleventycomputed-object.11ty.cjs index 168fd619a..9fe210416 100644 --- a/test/stubs/stubs-computed-permalink/eleventycomputed-object.11ty.js +++ b/test/stubs/stubs-computed-permalink/eleventycomputed-object.11ty.cjs @@ -2,7 +2,7 @@ module.exports.data = { lang: "en", eleventyComputed: { permalink: { - serverless: function (data) { + build: function (data) { return `/i18n/${data.lang}/`; }, }, diff --git a/test/stubs/stubs-computed-permalink/object.11ty.js b/test/stubs/stubs-computed-permalink/object.11ty.js deleted file mode 100644 index f5234de26..000000000 --- a/test/stubs/stubs-computed-permalink/object.11ty.js +++ /dev/null @@ -1,8 +0,0 @@ -module.exports.data = { - lang: "en", - permalink: function (data) { - return { - serverless: `/i18n/${data.lang}/`, - }; - }, -}; diff --git a/test/stubs/subfolder/subfolder.ejs b/test/stubs/subfolder/subfolder.liquid similarity index 100% rename from test/stubs/subfolder/subfolder.ejs rename to test/stubs/subfolder/subfolder.liquid diff --git a/test/stubs/subfolder/subfolder/subfolder.ejs b/test/stubs/subfolder/subfolder/subfolder.ejs deleted file mode 100644 index e69de29bb..000000000 diff --git a/test/stubs/index.ejs b/test/stubs/subfolder/subfolder/subfolder.liquid similarity index 100% rename from test/stubs/index.ejs rename to test/stubs/subfolder/subfolder/subfolder.liquid diff --git a/test/stubs/template.ejs b/test/stubs/template.ejs deleted file mode 100644 index e69de29bb..000000000 diff --git a/test/stubs/layoutsemptystring.ejs b/test/stubs/template.liquid similarity index 100% rename from test/stubs/layoutsemptystring.ejs rename to test/stubs/template.liquid diff --git a/test/stubs/templateFrontMatter.ejs b/test/stubs/templateFrontMatter.liquid similarity index 55% rename from test/stubs/templateFrontMatter.ejs rename to test/stubs/templateFrontMatter.liquid index 93663edc4..f5acca003 100644 --- a/test/stubs/templateFrontMatter.ejs +++ b/test/stubs/templateFrontMatter.liquid @@ -3,4 +3,4 @@ key1: value1 key2: value2 key3: value3 --- -c:<%= key1 %>:<%= key2 %>:<%= key3 %> \ No newline at end of file +c:{{ key1 }}:{{ key2 }}:{{ key3 }} \ No newline at end of file diff --git a/test/stubs/templateFrontMatterJs.ejs b/test/stubs/templateFrontMatterJs.njk similarity index 70% rename from test/stubs/templateFrontMatterJs.ejs rename to test/stubs/templateFrontMatterJs.njk index 06128620e..508514fa6 100644 --- a/test/stubs/templateFrontMatterJs.ejs +++ b/test/stubs/templateFrontMatterJs.njk @@ -7,4 +7,4 @@ key3: "value3" } --- -c:<%= key1 %>:<%= key2("value2") %>:<%= key3 %> +c:{{ key1 }}:{{ key2("value2") }}:{{ key3 }} diff --git a/test/stubs/templateFrontMatterJson.ejs b/test/stubs/templateFrontMatterJson.liquid similarity index 66% rename from test/stubs/templateFrontMatterJson.ejs rename to test/stubs/templateFrontMatterJson.liquid index a414b471b..0e6057765 100644 --- a/test/stubs/templateFrontMatterJson.ejs +++ b/test/stubs/templateFrontMatterJson.liquid @@ -5,4 +5,4 @@ "key3": "value3" } --- -c:<%= key1 %>:<%= key2 %>:<%= key3 %> \ No newline at end of file +c:{{ key1 }}:{{ key2 }}:{{ key3 }} \ No newline at end of file diff --git a/test/stubs/templateTwoLayouts.ejs b/test/stubs/templateTwoLayouts.liquid similarity index 88% rename from test/stubs/templateTwoLayouts.ejs rename to test/stubs/templateTwoLayouts.liquid index d2da2d436..076263e1f 100644 --- a/test/stubs/templateTwoLayouts.ejs +++ b/test/stubs/templateTwoLayouts.liquid @@ -8,4 +8,4 @@ daysPosted: 152 yearsPosted: 0.4 --- -

<%= upstream %>

\ No newline at end of file +

{{ upstream }}

\ No newline at end of file diff --git a/test/stubs/templateWithLayoutBackCompat.ejs b/test/stubs/templateWithLayoutBackCompat.ejs deleted file mode 100644 index 7e7c4d96f..000000000 --- a/test/stubs/templateWithLayoutBackCompat.ejs +++ /dev/null @@ -1,8 +0,0 @@ ---- -layout: defaultLayout_layoutContent -keymain: valuemain -title: 'Font Aliasing, or How to Rename a Font in CSS' -permalink: /rename-font/ ---- - -

Hello.

\ No newline at end of file diff --git a/test/stubs/templateWithLayoutContent.ejs b/test/stubs/templateWithLayoutContent.liquid similarity index 100% rename from test/stubs/templateWithLayoutContent.ejs rename to test/stubs/templateWithLayoutContent.liquid diff --git a/test/stubs/templateWithLayout.ejs b/test/stubs/templateWithLayoutKey.liquid similarity index 100% rename from test/stubs/templateWithLayout.ejs rename to test/stubs/templateWithLayoutKey.liquid diff --git a/test/stubs/test-override-js-markdown.11ty.js b/test/stubs/test-override-js-markdown.11ty.cjs similarity index 100% rename from test/stubs/test-override-js-markdown.11ty.js rename to test/stubs/test-override-js-markdown.11ty.cjs diff --git a/test/stubs/use-collection.11ty.js b/test/stubs/use-collection.11ty.cjs similarity index 100% rename from test/stubs/use-collection.11ty.js rename to test/stubs/use-collection.11ty.cjs diff --git a/test/stubs/vue-layout.11ty.js b/test/stubs/vue-layout.11ty.cjs similarity index 100% rename from test/stubs/vue-layout.11ty.js rename to test/stubs/vue-layout.11ty.cjs diff --git a/test/stubs/vue.11ty.js b/test/stubs/vue.11ty.cjs similarity index 100% rename from test/stubs/vue.11ty.js rename to test/stubs/vue.11ty.cjs diff --git a/test/stubs/writeTestJS-passthrough/sample.js b/test/stubs/writeTestJS-passthrough/sample.js new file mode 100644 index 000000000..6b32cc46d --- /dev/null +++ b/test/stubs/writeTestJS-passthrough/sample.js @@ -0,0 +1 @@ +export default "

Zach

"; diff --git a/test/stubs/writeTestJS-passthrough/test.11ty.js b/test/stubs/writeTestJS-passthrough/test.11ty.js new file mode 100644 index 000000000..6b32cc46d --- /dev/null +++ b/test/stubs/writeTestJS-passthrough/test.11ty.js @@ -0,0 +1 @@ +export default "

Zach

"; diff --git a/test/stubs/writeTestJS/sample.js b/test/stubs/writeTestJS/sample.cjs similarity index 100% rename from test/stubs/writeTestJS/sample.js rename to test/stubs/writeTestJS/sample.cjs diff --git a/test/stubs/writeTestJS/test.11ty.js b/test/stubs/writeTestJS/test.11ty.cjs similarity index 100% rename from test/stubs/writeTestJS/test.11ty.js rename to test/stubs/writeTestJS/test.11ty.cjs