This commit is contained in:
2026-03-31 16:38:22 -07:00
commit 38940436a7
2112 changed files with 376929 additions and 0 deletions

1
node_modules/.bin/acorn generated vendored Symbolic link
View File

@ -0,0 +1 @@
../acorn/bin/acorn

1
node_modules/.bin/eleventy generated vendored Symbolic link
View File

@ -0,0 +1 @@
../@11ty/eleventy/cmd.cjs

1
node_modules/.bin/eleventy-dev-server generated vendored Symbolic link
View File

@ -0,0 +1 @@
../@11ty/eleventy-dev-server/cmd.js

1
node_modules/.bin/errno generated vendored Symbolic link
View File

@ -0,0 +1 @@
../errno/cli.js

1
node_modules/.bin/esparse generated vendored Symbolic link
View File

@ -0,0 +1 @@
../esprima/bin/esparse.js

1
node_modules/.bin/esvalidate generated vendored Symbolic link
View File

@ -0,0 +1 @@
../esprima/bin/esvalidate.js

1
node_modules/.bin/image-size generated vendored Symbolic link
View File

@ -0,0 +1 @@
../image-size/bin/image-size.js

1
node_modules/.bin/js-yaml generated vendored Symbolic link
View File

@ -0,0 +1 @@
../js-yaml/bin/js-yaml.js

1
node_modules/.bin/liquid generated vendored Symbolic link
View File

@ -0,0 +1 @@
../liquidjs/bin/liquid.js

1
node_modules/.bin/liquidjs generated vendored Symbolic link
View File

@ -0,0 +1 @@
../liquidjs/bin/liquid.js

1
node_modules/.bin/markdown-it generated vendored Symbolic link
View File

@ -0,0 +1 @@
../markdown-it/bin/markdown-it.mjs

1
node_modules/.bin/mime generated vendored Symbolic link
View File

@ -0,0 +1 @@
../mime/cli.js

1
node_modules/.bin/nunjucks-precompile generated vendored Symbolic link
View File

@ -0,0 +1 @@
../nunjucks/bin/precompile

1
node_modules/.bin/semver generated vendored Symbolic link
View File

@ -0,0 +1 @@
../semver/bin/semver.js

2018
node_modules/.package-lock.json generated vendored Normal file

File diff suppressed because it is too large Load Diff

21
node_modules/@11ty/dependency-tree-esm/LICENSE generated vendored Normal file
View File

@ -0,0 +1,21 @@
MIT License
Copyright (c) 2023 Zach Leatherman
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

53
node_modules/@11ty/dependency-tree-esm/README.md generated vendored Normal file
View File

@ -0,0 +1,53 @@
# `dependency-tree-esm`
Returns an unordered array of local paths to dependencies of a Node ES module JavaScript file.
* See also: [`dependency-tree`](https://github.com/11ty/eleventy-dependency-tree) for the CommonJS version.
This is used by Eleventy to find dependencies of a JavaScript file to watch for changes to re-run Eleventys build.
## Installation
```
npm install --save-dev @11ty/dependency-tree-esm
```
## Features
* Ignores bare specifiers (e.g. `import "my-package"`)
* Ignores Nodes built-ins (e.g. `import "path"`)
* Handles circular dependencies
* Returns an empty set if the file does not exist.
## Usage
```js
// my-file.js
// if my-local-dependency.js has dependencies, it will include those too
import "./my-local-dependency.js";
// ignored, is a built-in
import path from "path";
```
```js
import { find } from "@11ty/dependency-tree-esm";
// CommonJS is fine too
// const { find } = require("@11ty/dependency-tree-esm");
await find("./my-file.js");
// returns ["./my-local-dependency.js"]
```
Return a [dependency-graph](https://github.com/jriecken/dependency-graph) instance:
```js
import { findGraph } from "@11ty/dependency-tree-esm";
// CommonJS is fine too
// const { find } = require("@11ty/dependency-tree-esm");
(await findGraph("./my-file.js")).overallOrder();
// returns ["./my-local-dependency.js", "./my-file.js"]
```

173
node_modules/@11ty/dependency-tree-esm/main.js generated vendored Normal file
View File

@ -0,0 +1,173 @@
const path = require("node:path");
const { readFileSync, existsSync } = require("node:fs");
const acorn = require("acorn");
const normalizePath = require("normalize-path");
const { TemplatePath } = require("@11ty/eleventy-utils");
const { DepGraph } = require("dependency-graph");
// Is *not* a bare specifier (e.g. 'some-package')
// https://nodejs.org/dist/latest-v18.x/docs/api/esm.html#terminology
function isNonBareSpecifier(importSource) {
// Change \\ to / on Windows
let normalized = normalizePath(importSource);
// Relative specifier (e.g. './startup.js')
if(normalized.startsWith("./") || normalized.startsWith("../")) {
return true;
}
// Absolute specifier (e.g. 'file:///opt/nodejs/config.js')
if(normalized.startsWith("file:")) {
return true;
}
return false;
}
function normalizeFilePath(filePath) {
return TemplatePath.standardizeFilePath(path.relative(".", filePath));
}
function normalizeImportSourceToFilePath(filePath, source) {
let { dir } = path.parse(filePath);
let normalized = path.join(dir, source);
return normalizeFilePath(normalized);
}
function getImportAttributeType(attributes = []) {
for(let node of attributes) {
if(node.type === "ImportAttribute" && node.key.type === "Identifier" && node.key.name === "type") {
return node.value.value;
}
}
}
async function getSources(filePath, contents, options = {}) {
let { parserOverride } = Object.assign({}, options);
let sources = new Set();
let sourcesToRecurse = new Set();
let ast = (parserOverride || acorn).parse(contents, {
sourceType: "module",
ecmaVersion: "latest",
});
for(let node of ast.body) {
if(node.type === "ImportDeclaration" && isNonBareSpecifier(node.source.value)) {
let importAttributeType = getImportAttributeType(node?.attributes);
let normalized = normalizeImportSourceToFilePath(filePath, node.source.value);
if(normalized !== filePath) {
sources.add(normalized);
// Recurse typeless (JavaScript) import types only
// Right now only `css` and `json` are valid but others might come later
if(!importAttributeType) {
sourcesToRecurse.add(normalized);
}
}
}
}
return {
sources,
sourcesToRecurse,
}
}
// second argument used to be `alreadyParsedSet = new Set()`, keep that backwards compat
async function find(filePath, options = {}) {
if(options instanceof Set) {
options = {
alreadyParsedSet: options
};
}
if(!options.alreadyParsedSet) {
options.alreadyParsedSet = new Set();
}
// TODO add a cache here
// Unfortunately we need to read the entire file, imports need to be at the top level but they can be anywhere 🫠
let normalized = normalizeFilePath(filePath);
if(options.alreadyParsedSet.has(normalized) || !existsSync(filePath)) {
return [];
}
options.alreadyParsedSet.add(normalized);
let contents = readFileSync(normalized, { encoding: 'utf8' });
let { sources, sourcesToRecurse } = await getSources(filePath, contents, options);
// Recurse for nested deps
for(let source of sourcesToRecurse) {
let s = await find(source, options);
for(let p of s) {
if(sources.has(p) || p === filePath) {
continue;
}
sources.add(p);
}
}
return Array.from(sources);
}
function mergeGraphs(rootGraph, ...graphs) {
if(!(rootGraph instanceof DepGraph)) {
throw new Error("Incorrect type passed to mergeGraphs, expected DepGraph");
}
for(let g of graphs) {
for(let node of g.overallOrder()) {
if(!rootGraph.hasNode(node)) {
rootGraph.addNode(node);
}
for(let dep of g.directDependenciesOf(node)) {
rootGraph.addDependency(node, dep);
}
}
}
}
// second argument used to be `alreadyParsedSet = new Set()`, keep that backwards compat
async function findGraph(filePath, options = {}) {
if(options instanceof Set) {
options = {
alreadyParsedSet: options
};
}
if(!options.alreadyParsedSet) {
options.alreadyParsedSet = new Set();
}
let graph = new DepGraph();
let normalized = normalizeFilePath(filePath);
graph.addNode(filePath);
if(options.alreadyParsedSet.has(normalized) || !existsSync(filePath)) {
return graph;
}
options.alreadyParsedSet.add(normalized);
let contents = readFileSync(normalized, "utf8");
let { sources, sourcesToRecurse } = await getSources(filePath, contents, options);
for(let source of sources) {
if(!graph.hasNode(source)) {
graph.addNode(source);
}
graph.addDependency(normalized, source);
}
// Recurse for nested deps
for(let source of sourcesToRecurse) {
let recursedGraph = await findGraph(source, options);
mergeGraphs(graph, recursedGraph);
}
return graph;
}
module.exports = {
find,
findGraph,
mergeGraphs,
};

26
node_modules/@11ty/dependency-tree-esm/package.json generated vendored Normal file
View File

@ -0,0 +1,26 @@
{
"name": "@11ty/dependency-tree-esm",
"version": "2.0.4",
"description": "Finds all JavaScript ES Module dependencies from a filename.",
"main": "main.js",
"type": "commonjs",
"scripts": {
"test": "echo \"Error: run tests from root directory\" && exit 1"
},
"repository": {
"type": "git",
"url": "git+https://github.com/11ty/eleventy-utils.git"
},
"author": {
"name": "Zach Leatherman",
"email": "zach@zachleat.com",
"url": "https://zachleat.com/"
},
"license": "MIT",
"dependencies": {
"@11ty/eleventy-utils": "^2.0.7",
"acorn": "^8.15.0",
"dependency-graph": "^1.0.0",
"normalize-path": "^3.0.0"
}
}

21
node_modules/@11ty/dependency-tree/LICENSE generated vendored Normal file
View File

@ -0,0 +1,21 @@
MIT License
Copyright (c) 2019 Zach Leatherman
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

109
node_modules/@11ty/dependency-tree/README.md generated vendored Normal file
View File

@ -0,0 +1,109 @@
# `@11ty/dependency-tree`
Returns an unordered array of local paths to dependencies of a CommonJS node JavaScript file (everything it or any of its dependencies `require`s).
* See also: [`@11ty/dependency-tree-esm`](https://github.com/11ty/eleventy-utils/tree/main/parse-deps-esm) for the ESM version.
* See also: [`@11ty/dependency-tree-typescript`](https://github.com/11ty/eleventy-utils/tree/main/parse-deps-typescript) for the TypeScript version.
Reduced feature (faster) alternative to the [`dependency-tree` package](https://www.npmjs.com/package/dependency-tree). This is used by Eleventy to find dependencies of a JavaScript file to watch for changes to re-run Eleventys build.
## Big Huge Caveat
⚠ A big caveat to this plugin is that it will require the file in order to build a dependency tree. So if your module has side effects and you dont want it to execute—do not use this!
## Installation
```
npm install --save-dev @11ty/dependency-tree
```
## Features
* Ignores `node_modules`
* Or, use `nodeModuleNames` to control whether or not `node_modules` package names are included (added in v2.0.1)
* Ignores Nodes built-ins (e.g. `path`)
* Handles circular dependencies (Node does this too)
## Usage
```js
// my-file.js
// if my-local-dependency.js has dependencies, it will include those too
const test = require("./my-local-dependency.js");
// ignored, is a built-in
const path = require("path");
```
```js
const DependencyTree = require("@11ty/dependency-tree");
DependencyTree("./my-file.js");
// returns ["./my-local-dependency.js"]
```
### `allowNotFound`
```js
const DependencyTree = require("@11ty/dependency-tree");
DependencyTree("./this-does-not-exist.js"); // throws an error
DependencyTree("./this-does-not-exist.js", { allowNotFound: true });
// returns []
```
### `nodeModuleNames`
(Added in v2.0.1) Controls whether or not node package names are included in the list of dependencies.
* `nodeModuleNames: "include"`: included alongside the local JS files.
* `nodeModuleNames: "exclude"` (default): node module package names are excluded.
* `nodeModuleNames: "only"`: only node module package names are returned.
```js
// my-file.js:
require("./my-local-dependency.js");
require("@11ty/eleventy");
```
```js
const DependencyTree = require("@11ty/dependency-tree");
DependencyTree("./my-file.js");
// returns ["./my-local-dependency.js"]
DependencyTree("./my-file.js", { nodeModuleNames: "exclude" });
// returns ["./my-local-dependency.js"]
DependencyTree("./my-file.js", { nodeModuleNames: "include" });
// returns ["./my-local-dependency.js", "@11ty/eleventy"]
DependencyTree("./my-file.js", { nodeModuleNames: "only" });
// returns ["@11ty/eleventy"]
```
#### (Deprecated) `nodeModuleNamesOnly`
(Added in v2.0.0) Changed to use `nodeModuleNames` option instead. Backwards compatibility is maintained automatically.
* `nodeModuleNamesOnly: false` is mapped to `nodeModuleNames: "exclude"`
* `nodeModuleNamesOnly: true` is mapped to `nodeModuleNames: "only"`
If both `nodeModuleNamesOnly` and `nodeModuleNames` are included in options, `nodeModuleNames` takes precedence.
### `getPackagesByType` method
_Added in v4.0.2._
```js
const DependencyTree = require("@11ty/dependency-tree");
const {getPackagesByType} = DependencyTree;
// With `require(esm)` support, some targets may be modules!
// Return separate lists for commonjs and esm lists
getPackagesByType("./my-file.js");
// returns { commonjs: ["./my-file.js"], esm: [] }
```

157
node_modules/@11ty/dependency-tree/main.js generated vendored Normal file
View File

@ -0,0 +1,157 @@
const path = require("node:path");
const { TemplatePath } = require("@11ty/eleventy-utils");
function getAbsolutePath(filename) {
let normalizedFilename = path.normalize(filename); // removes dot slash
let hasDotSlash = filename.startsWith("./");
return hasDotSlash ? path.join(path.resolve("."), normalizedFilename) : normalizedFilename;
}
function getRelativePath(filename) {
let normalizedFilename = path.normalize(filename); // removes dot slash
let workingDirectory = path.resolve(".");
let result = "./" + (normalizedFilename.startsWith(workingDirectory) ? normalizedFilename.substr(workingDirectory.length + 1) : normalizedFilename);
return result;
}
function getNodeModuleName(filename) {
let foundNodeModules = false;
let moduleName = [];
let s = filename.split(path.sep);
for(let entry of s) {
if(entry === '.pnpm') {
foundNodeModules = false;
}
if(foundNodeModules) {
moduleName.push(entry);
if(!entry.startsWith("@")) {
return moduleName.join("/");
}
}
if(entry === "node_modules") {
foundNodeModules = true;
}
}
return false;
}
/* unordered */
function getDependenciesFor(filename, avoidCircular, optionsArg = {}) {
// backwards compatibility with `nodeModuleNamesOnly` boolean option
// Using `nodeModuleNames` property moving forward
if(("nodeModuleNamesOnly" in optionsArg) && !("nodeModuleNames" in optionsArg)) {
if(optionsArg.nodeModuleNamesOnly === true) {
optionsArg.nodeModuleNames = "only";
}
if(optionsArg.nodeModuleNamesOnly === false) {
optionsArg.nodeModuleNames = "exclude";
}
}
let options = Object.assign({
allowNotFound: false,
nodeModuleNames: "exclude", // also "include" or "only"
}, optionsArg);
let absoluteFilename = getAbsolutePath(filename);
let modules = new Set();
try {
let res = require(absoluteFilename);
if(res[Symbol.toStringTag] === "Module" || res.__esModule) {
modules.add(filename);
}
} catch(e) {
if(e.code === "MODULE_NOT_FOUND" && options.allowNotFound) {
// do nothing
} else {
throw e;
}
}
let mod;
for(let entry in require.cache) {
if(entry === absoluteFilename) {
mod = require.cache[entry];
break;
}
}
let dependencies = new Set();
if(!mod) {
if(!options.allowNotFound) {
throw new Error(`Could not find ${filename} in @11ty/dependency-tree`);
}
} else {
let relativeFilename = getRelativePath(mod.filename);
if(!avoidCircular) {
avoidCircular = {};
} else if(options.nodeModuleNames !== "only") {
dependencies.add(relativeFilename);
}
avoidCircular[relativeFilename] = true;
if(Array.isArray(mod.children) && mod.children.length > 0) {
for(let child of mod.children) {
let relativeChildFilename = getRelativePath(child.filename);
let nodeModuleName = getNodeModuleName(child.filename);
if(options.nodeModuleNames !== "exclude" && nodeModuleName) {
dependencies.add(nodeModuleName);
}
// Add dependencies of this dependency (not top level node_modules)
if(nodeModuleName === false) {
if(!dependencies.has(relativeChildFilename) && // avoid infinite looping with circular deps
!avoidCircular[relativeChildFilename] ) {
let { commonjs, esm } = getDependenciesFor(relativeChildFilename, avoidCircular, options);
for(let dependency of commonjs) {
dependencies.add(dependency);
}
for(let dependency of esm) {
modules.add(dependency);
}
}
}
}
}
}
return {
esm: modules,
commonjs: dependencies,
}
}
function normalizeList(packageSet) {
return Array.from( packageSet ).map(filePath => {
if(filePath.startsWith("./")) {
return TemplatePath.standardizeFilePath(filePath);
}
return filePath; // node_module name
})
}
function getCleanDependencyListFor(filename, options = {}) {
let { commonjs } = getDependenciesFor(filename, null, options);
return normalizeList(commonjs);
}
function getCleanDependencyListByTypeFor(filename, options = {}) {
let { commonjs, esm } = getDependenciesFor(filename, null, options);
return {
commonjs: normalizeList(commonjs),
esm: normalizeList(esm),
};
}
module.exports = getCleanDependencyListFor;
module.exports.getPackagesByType = getCleanDependencyListByTypeFor;
module.exports.getNodeModuleName = getNodeModuleName;

42
node_modules/@11ty/dependency-tree/package.json generated vendored Normal file
View File

@ -0,0 +1,42 @@
{
"name": "@11ty/dependency-tree",
"version": "4.0.2",
"description": "Finds all JavaScript CommmonJS require() dependencies from a filename.",
"main": "main.js",
"files": [
"main.js",
"!test",
"!test/**"
],
"scripts": {
"test": "npx ava"
},
"repository": {
"type": "git",
"url": "git+https://github.com/11ty/eleventy-dependency-tree.git"
},
"author": {
"name": "Zach Leatherman",
"email": "zach@zachleat.com",
"url": "https://zachleat.com/"
},
"license": "MIT",
"ava": {
"files": [
"./test/*.js"
],
"watchMode": {
"ignoreChanged": [
"./test/stubs/**"
]
}
},
"devDependencies": {
"@sindresorhus/is": "^4.6.0",
"ava": "^6.4.1",
"semver": "^7.7.3"
},
"dependencies": {
"@11ty/eleventy-utils": "^2.0.1"
}
}

60
node_modules/@11ty/eleventy-dev-server/README.md generated vendored Normal file
View File

@ -0,0 +1,60 @@
<p align="center"><img src="https://www.11ty.dev/img/logo-github.svg" width="200" height="200" alt="11ty Logo"></p>
# eleventy-dev-server 🕚⚡️🎈🐀
A minimal, modern, generic, hot-reloading local web server to help web developers.
## ➡ [Documentation](https://www.11ty.dev/docs/watch-serve/#eleventy-dev-server)
- Please star [Eleventy on GitHub](https://github.com/11ty/eleventy/)!
- Follow us on Twitter [@eleven_ty](https://twitter.com/eleven_ty)
- Support [11ty on Open Collective](https://opencollective.com/11ty)
- [11ty on npm](https://www.npmjs.com/org/11ty)
- [11ty on GitHub](https://github.com/11ty)
[![npm Version](https://img.shields.io/npm/v/@11ty/eleventy-dev-server.svg?style=for-the-badge)](https://www.npmjs.com/package/@11ty/eleventy-dev-server)
## Installation
This is bundled with `@11ty/eleventy` (and you do not need to install it separately) in Eleventy v2.0.
## CLI
Eleventy Dev Server now also includes a CLI. The CLI is for **standalone** (non-Eleventy) use only: separate installation is unnecessary if youre using this server with `@11ty/eleventy`.
```sh
npm install -g @11ty/eleventy-dev-server
# Alternatively, install locally into your project
npm install @11ty/eleventy-dev-server
```
This package requires Node 18 or newer.
### CLI Usage
```sh
# Serve the current directory
npx @11ty/eleventy-dev-server
# Serve a different subdirectory (also aliased as --input)
npx @11ty/eleventy-dev-server --dir=_site
# Disable the `domdiff` feature
npx @11ty/eleventy-dev-server --domdiff=false
# Full command list in the Help
npx @11ty/eleventy-dev-server --help
```
## Tests
```
npm run test
```
- We use the [ava JavaScript test runner](https://github.com/avajs/ava) ([Assertions documentation](https://github.com/avajs/ava/blob/master/docs/03-assertions.md))
## Changelog
* `v2.0.0` bumps Node.js minimum to 18.

89
node_modules/@11ty/eleventy-dev-server/cli.js generated vendored Normal file
View File

@ -0,0 +1,89 @@
const pkg = require("./package.json");
const EleventyDevServer = require("./server.js");
const Logger = {
info: function(...args) {
console.log( "[11ty/eleventy-dev-server]", ...args );
},
error: function(...args) {
console.error( "[11ty/eleventy-dev-server]", ...args );
},
fatal: function(...args) {
Logger.error(...args);
process.exitCode = 1;
}
};
Logger.log = Logger.info;
class Cli {
static getVersion() {
return pkg.version;
}
static getHelp() {
return `Usage:
eleventy-dev-server
eleventy-dev-server --dir=_site
eleventy-dev-server --port=3000
Arguments:
--version
--dir=.
Directory to serve (default: \`.\`)
--input (alias for --dir)
--port=8080
Run the web server on this port (default: \`8080\`)
Will autoincrement if already in use.
--domdiff (enabled, default)
--domdiff=false (disabled)
Apply HTML changes without a full page reload.
--help`;
}
static getDefaultOptions() {
return {
port: "8080",
input: ".",
domDiff: true,
}
}
async serve(options = {}) {
this.options = Object.assign(Cli.getDefaultOptions(), options);
this.server = EleventyDevServer.getServer("eleventy-dev-server-cli", this.options.input, {
// TODO allow server configuration extensions
showVersion: true,
logger: Logger,
domDiff: this.options.domDiff,
// CLI watches all files in the folder by default
// this is different from Eleventy usage!
watch: [ this.options.input ],
});
this.server.serve(this.options.port);
// TODO? send any errors here to the server too
// with server.sendError({ error });
}
close() {
if(this.server) {
return this.server.close();
}
}
}
module.exports = {
Logger,
Cli
}

View File

@ -0,0 +1,336 @@
class Util {
static pad(num, digits = 2) {
let zeroes = new Array(digits + 1).join(0);
return `${zeroes}${num}`.slice(-1 * digits);
}
static log(message) {
Util.output("log", message);
}
static error(message, error) {
Util.output("error", message, error);
}
static output(type, ...messages) {
let now = new Date();
let date = `${Util.pad(now.getUTCHours())}:${Util.pad(
now.getUTCMinutes()
)}:${Util.pad(now.getUTCSeconds())}.${Util.pad(
now.getUTCMilliseconds(),
3
)}`;
console[type](`[11ty][${date} UTC]`, ...messages);
}
static capitalize(word) {
return word.substr(0, 1).toUpperCase() + word.substr(1);
}
static matchRootAttributes(htmlContent) {
// Workaround for morphdom bug with attributes on <html> https://github.com/11ty/eleventy-dev-server/issues/6
// Note also `childrenOnly: true` above
const parser = new DOMParser();
let parsed = parser.parseFromString(htmlContent, "text/html");
let parsedDoc = parsed.documentElement;
let newAttrs = parsedDoc.getAttributeNames();
let docEl = document.documentElement;
// Remove old
let removedAttrs = docEl.getAttributeNames().filter(name => !newAttrs.includes(name));
for(let attr of removedAttrs) {
docEl.removeAttribute(attr);
}
// Add new
for(let attr of newAttrs) {
docEl.setAttribute(attr, parsedDoc.getAttribute(attr));
}
}
static isEleventyLinkNodeMatch(from, to) {
// Issue #18 https://github.com/11ty/eleventy-dev-server/issues/18
// Dont update a <link> if the _11ty searchParam is the only thing thats different
if(from.tagName !== "LINK" || to.tagName !== "LINK") {
return false;
}
let oldWithoutHref = from.cloneNode();
let newWithoutHref = to.cloneNode();
oldWithoutHref.removeAttribute("href");
newWithoutHref.removeAttribute("href");
// if all other attributes besides href match
if(!oldWithoutHref.isEqualNode(newWithoutHref)) {
return false;
}
let oldUrl = new URL(from.href);
let newUrl = new URL(to.href);
// morphdom wants to force href="style.css?_11ty" => href="style.css"
let paramName = EleventyReload.QUERY_PARAM;
let isErasing = oldUrl.searchParams.has(paramName) && !newUrl.searchParams.has(paramName);
if(!isErasing) {
// not a match if _11ty has a new value (not being erased)
return false;
}
oldUrl.searchParams.set(paramName, "");
newUrl.searchParams.set(paramName, "");
// is a match if erasing and the rest of the href matches too
return oldUrl.toString() === newUrl.toString();
}
// https://github.com/patrick-steele-idem/morphdom/issues/178#issuecomment-652562769
static runScript(source, target) {
let script = document.createElement('script');
// copy over the attributes
for(let attr of [...source.attributes]) {
script.setAttribute(attr.nodeName ,attr.nodeValue);
}
script.innerHTML = source.innerHTML;
(target || source).replaceWith(script);
}
static fullPageReload() {
Util.log(`Page reload initiated.`);
window.location.reload();
}
}
class EleventyReload {
static QUERY_PARAM = "_11ty";
static reloadTypes = {
css: (files, build = {}) => {
// Initiate a full page refresh if a CSS change is made but does match any stylesheet url
// `build.stylesheets` available in Eleventy v3.0.1-alpha.5+
if(Array.isArray(build.stylesheets)) {
let match = false;
for (let link of document.querySelectorAll(`link[rel="stylesheet"]`)) {
if (link.href) {
let url = new URL(link.href);
if(build.stylesheets.includes(url.pathname)) {
match = true;
}
}
}
if(!match) {
Util.fullPageReload();
return;
}
}
for (let link of document.querySelectorAll(`link[rel="stylesheet"]`)) {
if (link.href) {
let url = new URL(link.href);
url.searchParams.set(this.QUERY_PARAM, Date.now());
link.href = url.toString();
}
}
Util.log(`CSS updated without page reload.`);
},
default: async (files, build = {}) => {
let morphed = false;
let domdiffTemplates = (build?.templates || []).filter(({url, inputPath}) => {
return url === document.location.pathname && (files || []).includes(inputPath);
});
if(domdiffTemplates.length === 0) {
Util.fullPageReload();
return;
}
try {
// Important: using `./` allows the `.11ty` folder name to be changed
const { default: morphdom } = await import(`./morphdom.js`);
for (let {url, inputPath, content} of domdiffTemplates) {
// Notable limitation: this wont re-run script elements or JavaScript page lifecycle events (load/DOMContentLoaded)
morphed = true;
morphdom(document.documentElement, content, {
childrenOnly: true,
onBeforeElUpdated: function (fromEl, toEl) {
if (fromEl.nodeName === "SCRIPT" && toEl.nodeName === "SCRIPT") {
if(toEl.innerHTML !== fromEl.innerHTML) {
Util.log(`JavaScript modified, reload initiated.`);
window.location.reload();
}
return false;
}
// Speed-up trick from morphdom docs
// https://dom.spec.whatwg.org/#concept-node-equals
if (fromEl.isEqualNode(toEl)) {
return false;
}
if(Util.isEleventyLinkNodeMatch(fromEl, toEl)) {
return false;
}
return true;
},
addChild: function(parent, child) {
// Declarative Shadow DOM https://github.com/11ty/eleventy-dev-server/issues/90
if(child.nodeName === "TEMPLATE" && child.hasAttribute("shadowrootmode")) {
let root = parent.shadowRoot;
if(root) {
// remove all shadow root children
while(root.firstChild) {
root.removeChild(root.firstChild);
}
}
for(let newChild of child.content.childNodes) {
root.appendChild(newChild);
}
} else {
parent.appendChild(child);
}
},
onNodeAdded: function (node) {
if (node.nodeName === 'SCRIPT') {
Util.log(`JavaScript added, reload initiated.`);
window.location.reload();
}
},
onElUpdated: function(node) {
// Re-attach custom elements
if(customElements.get(node.tagName.toLowerCase())) {
let placeholder = document.createElement("div");
node.replaceWith(placeholder);
requestAnimationFrame(() => {
placeholder.replaceWith(node);
placeholder = undefined;
});
}
}
});
Util.matchRootAttributes(content);
Util.log(`HTML delta applied without page reload.`);
}
} catch(e) {
Util.error( "Morphdom error", e );
}
if (!morphed) {
Util.fullPageReload();
}
}
}
constructor() {
this.connectionMessageShown = false;
this.reconnectEventCallback = this.reconnect.bind(this);
}
init(options = {}) {
if (!("WebSocket" in window)) {
return;
}
let documentUrl = new URL(document.location.href);
let reloadPort = new URL(import.meta.url).searchParams.get("reloadPort");
if(reloadPort) {
documentUrl.port = reloadPort;
}
let { protocol, host } = documentUrl;
// works with http (ws) and https (wss)
let websocketProtocol = protocol.replace("http", "ws");
let socket = new WebSocket(`${websocketProtocol}//${host}`);
socket.addEventListener("message", async (event) => {
try {
let data = JSON.parse(event.data);
// Util.log( JSON.stringify(data, null, 2) );
let { type } = data;
if (type === "eleventy.reload") {
await this.onreload(data);
} else if (type === "eleventy.msg") {
Util.log(`${data.message}`);
} else if (type === "eleventy.error") {
// Log Eleventy build errors
// Extra parsing for Node Error objects
let e = JSON.parse(data.error);
Util.error(`Build error: ${e.message}`, e);
} else if (type === "eleventy.status") {
// Full page reload on initial reconnect
if (data.status === "connected" && options.mode === "reconnect") {
window.location.reload();
}
if(data.status === "connected") {
// With multiple windows, only show one connection message
if(!this.isConnected) {
Util.log(Util.capitalize(data.status));
}
this.connectionMessageShown = true;
} else {
if(data.status === "disconnected") {
this.addReconnectListeners();
}
Util.log(Util.capitalize(data.status));
}
} else {
Util.log("Unknown event type", data);
}
} catch (e) {
Util.error(`Error parsing ${event.data}: ${e.message}`, e);
}
});
socket.addEventListener("open", () => {
// no reconnection when the connect is already open
this.removeReconnectListeners();
});
socket.addEventListener("close", () => {
this.connectionMessageShown = false;
this.addReconnectListeners();
});
}
reconnect() {
Util.log( "Reconnecting…" );
this.init({ mode: "reconnect" });
}
async onreload({ subtype, files, build }) {
if(!EleventyReload.reloadTypes[subtype]) {
subtype = "default";
}
await EleventyReload.reloadTypes[subtype](files, build);
}
addReconnectListeners() {
this.removeReconnectListeners();
window.addEventListener("focus", this.reconnectEventCallback);
window.addEventListener("visibilitychange", this.reconnectEventCallback);
}
removeReconnectListeners() {
window.removeEventListener("focus", this.reconnectEventCallback);
window.removeEventListener("visibilitychange", this.reconnectEventCallback);
}
}
let reloader = new EleventyReload();
reloader.init();

77
node_modules/@11ty/eleventy-dev-server/cmd.js generated vendored Executable file
View File

@ -0,0 +1,77 @@
#!/usr/bin/env node
const pkg = require("./package.json");
// Node check
require("please-upgrade-node")(pkg, {
message: function (requiredVersion) {
return (
"eleventy-dev-server requires Node " +
requiredVersion +
". You will need to upgrade Node!"
);
},
});
const { Logger, Cli } = require("./cli.js");
const debug = require("debug")("Eleventy:DevServer");
try {
const defaults = Cli.getDefaultOptions();
for(let key in defaults) {
if(key.toLowerCase() !== key) {
defaults[key.toLowerCase()] = defaults[key];
delete defaults[key];
}
}
const argv = require("minimist")(process.argv.slice(2), {
string: [
"dir",
"input", // alias for dir
"port",
],
boolean: [
"version",
"help",
"domdiff",
],
default: defaults,
unknown: function (unknownArgument) {
throw new Error(
`We dont know what '${unknownArgument}' is. Use --help to see the list of supported commands.`
);
},
});
debug("command: eleventy-dev-server %o", argv);
process.on("unhandledRejection", (error, promise) => {
Logger.fatal("Unhandled rejection in promise:", promise, error);
});
process.on("uncaughtException", (error) => {
Logger.fatal("Uncaught exception:", error);
});
if (argv.version) {
console.log(Cli.getVersion());
} else if (argv.help) {
console.log(Cli.getHelp());
} else {
let cli = new Cli();
cli.serve({
input: argv.dir || argv.input,
port: argv.port,
domDiff: argv.domdiff,
});
process.on("SIGINT", async () => {
await cli.close();
process.exitCode = 0;
});
}
} catch (e) {
Logger.fatal("Fatal Error:", e)
}

57
node_modules/@11ty/eleventy-dev-server/package.json generated vendored Normal file
View File

@ -0,0 +1,57 @@
{
"name": "@11ty/eleventy-dev-server",
"version": "2.0.8",
"description": "A minimal, modern, generic, hot-reloading local web server to help web developers.",
"main": "server.js",
"scripts": {
"test": "npx ava --verbose",
"sample": "node cmd.js --input=test/stubs"
},
"license": "MIT",
"engines": {
"node": ">=18"
},
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/11ty"
},
"bin": {
"eleventy-dev-server": "./cmd.js"
},
"keywords": [
"eleventy",
"server",
"cli"
],
"publishConfig": {
"access": "public"
},
"author": {
"name": "Zach Leatherman",
"email": "zachleatherman@gmail.com",
"url": "https://zachleat.com/"
},
"repository": {
"type": "git",
"url": "git://github.com/11ty/eleventy-dev-server.git"
},
"bugs": "https://github.com/11ty/eleventy-dev-server/issues",
"homepage": "https://github.com/11ty/eleventy-dev-server/",
"dependencies": {
"@11ty/eleventy-utils": "^2.0.1",
"chokidar": "^3.6.0",
"debug": "^4.4.0",
"finalhandler": "^1.3.1",
"mime": "^3.0.0",
"minimist": "^1.2.8",
"morphdom": "^2.7.4",
"please-upgrade-node": "^3.2.0",
"send": "^1.1.0",
"ssri": "^11.0.0",
"urlpattern-polyfill": "^10.0.0",
"ws": "^8.18.1"
},
"devDependencies": {
"ava": "^6.2.0"
}
}

1024
node_modules/@11ty/eleventy-dev-server/server.js generated vendored Normal file

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,9 @@
const os = require("node:os");
const INTERFACE_FAMILIES = ["IPv4"];
module.exports = function() {
return Object.values(os.networkInterfaces()).flat().filter(interface => {
return interface.internal === false && INTERFACE_FAMILIES.includes(interface.family);
}).map(interface => interface.address);
};

View File

@ -0,0 +1,130 @@
function getContentType(headers) {
if(!headers) {
return;
}
for(let key in headers) {
if(key.toLowerCase() === "content-type") {
return headers[key];
}
}
}
// Inspired by `resp-modifier` https://github.com/shakyShane/resp-modifier/blob/4a000203c9db630bcfc3b6bb8ea2abc090ae0139/index.js
function wrapResponse(resp, transformHtml) {
resp._wrappedOriginalWrite = resp.write;
resp._wrappedOriginalWriteHead = resp.writeHead;
resp._wrappedOriginalEnd = resp.end;
resp._wrappedHeaders = [];
resp._wrappedTransformHtml = transformHtml;
resp._hasEnded = false;
resp._shouldForceEnd = false;
// Compatibility with web standards Response()
Object.defineProperty(resp, "body", {
// Returns write cache
get: function() {
if(typeof this._writeCache === "string") {
return this._writeCache;
}
},
// Usage:
// res.body = ""; // overwrite existing content
// res.body += ""; // append to existing content, can also res.write("") to append
set: function(data) {
if(typeof data === "string") {
this._writeCache = data;
}
}
});
// Compatibility with web standards Response()
Object.defineProperty(resp, "bodyUsed", {
get: function() {
return this._hasEnded;
}
})
// Original signature writeHead(statusCode[, statusMessage][, headers])
resp.writeHead = function(statusCode, ...args) {
let headers = args[args.length - 1];
// statusMessage is a string
if(typeof headers !== "string") {
this._contentType = getContentType(headers);
}
if((this._contentType || "").startsWith("text/html")) {
this._wrappedHeaders.push([statusCode, ...args]);
} else {
return this._wrappedOriginalWriteHead(statusCode, ...args);
}
return this;
}
// data can be a String or Buffer
resp.write = function(data, ...args) {
if(typeof data === "string") {
if(!this._writeCache) {
this._writeCache = "";
}
// TODO encoding and callback args
this._writeCache += data;
} else {
// Buffers
return this._wrappedOriginalWrite(data, ...args);
}
return this;
}
// data can be a String or Buffer
resp.end = function(data, encoding, callback) {
resp._hasEnded = true;
if(typeof this._writeCache === "string" || typeof data === "string") {
// Strings
if(!this._writeCache) {
this._writeCache = "";
}
if(typeof data === "string") {
this._writeCache += data;
}
let result = this._writeCache;
// Only transform HTML
// Note the “setHeader versus writeHead” note on https://nodejs.org/api/http.html#responsewriteheadstatuscode-statusmessage-headers
let contentType = this._contentType || getContentType(this.getHeaders());
if(contentType?.startsWith("text/html")) {
if(this._wrappedTransformHtml && typeof this._wrappedTransformHtml === "function") {
result = this._wrappedTransformHtml(result);
// uncompressed size: https://github.com/w3c/ServiceWorker/issues/339
this.setHeader("Content-Length", Buffer.byteLength(result));
}
}
for(let headers of this._wrappedHeaders) {
this._wrappedOriginalWriteHead(...headers);
}
this._writeCache = [];
this._wrappedOriginalWrite(result, encoding)
return this._wrappedOriginalEnd(callback);
} else {
// Buffer or Uint8Array
for(let headers of this._wrappedHeaders) {
this._wrappedOriginalWriteHead(...headers);
}
if(data) {
this._wrappedOriginalWrite(data, encoding);
}
return this._wrappedOriginalEnd(callback);
}
}
return resp;
}
module.exports = wrapResponse;

55
node_modules/@11ty/eleventy-fetch/README.md generated vendored Normal file
View File

@ -0,0 +1,55 @@
<p align="center"><img src="https://www.11ty.dev/img/logo-github.svg" width="200" height="200" alt="eleventy Logo"></p>
# eleventy-fetch
_Requires Node 18+_
Formerly known as [`@11ty/eleventy-cache-assets`](https://www.npmjs.com/package/@11ty/eleventy-cache-assets).
Fetch network resources and cache them so you dont bombard your API (or other resources). Do this at configurable intervals—not with every build! Once per minute, or once per hour, once per day, or however often you like!
With the added benefit that if one successful request completes, you can now work offline!
This plugin can save any kind of asset—JSON, HTML, images, videos, etc.
## [The full `eleventy-fetch` documentation is on 11ty.dev](https://www.11ty.dev/docs/plugins/cache/).
- _This is a plugin for the [Eleventy static site generator](https://www.11ty.dev/)._
- Find more [Eleventy plugins](https://www.11ty.dev/docs/plugins/).
- Please star [Eleventy on GitHub](https://github.com/11ty/eleventy/), follow [@eleven_ty](https://twitter.com/eleven_ty) on Twitter, and support [11ty on Open Collective](https://opencollective.com/11ty)
[![npm Version](https://img.shields.io/npm/v/@11ty/eleventy-fetch.svg?style=for-the-badge)](https://www.npmjs.com/package/@11ty/eleventy-fetch) [![GitHub issues](https://img.shields.io/github/issues/11ty/eleventy-fetch.svg?style=for-the-badge)](https://github.com/11ty/eleventy/issues)
## Installation
```
npm install @11ty/eleventy-fetch
```
_[The full `eleventy-fetch` documentation is on 11ty.dev](https://www.11ty.dev/docs/plugins/cache/)._
## Tests
```
npm run test
```
- We use the [ava JavaScript test runner](https://github.com/avajs/ava) ([Assertions documentation](https://github.com/avajs/ava/blob/master/docs/03-assertions.md))
- To keep tests fast, thou shalt try to avoid writing files in tests.
<!--
## Roadmap
* Add support for tiered asset requests, e.g. CSS requests background-images and web fonts, for example.
## Open Questions
* `flat-cache` save method seems to be synchronous, is there a better async one?
* Our cache stores raw buffers internally, which are pretty bloated compared to the original. Surely there is a more efficient way to do this. Maybe store the files in their original format.
-->
## Community Roadmap
- [Top Feature Requests](https://github.com/11ty/eleventy-fetch/issues?q=label%3Aneeds-votes+sort%3Areactions-%2B1-desc+label%3Aenhancement) (Add your own votes using the 👍 reaction)
- [Top Bugs 😱](https://github.com/11ty/eleventy-fetch/issues?q=is%3Aissue+is%3Aopen+label%3Abug+sort%3Areactions-%2B1-desc) (Add your own votes using the 👍 reaction)
- [Newest Bugs 🙀](https://github.com/11ty/eleventy-fetch/issues?q=is%3Aopen+is%3Aissue+label%3Abug)

94
node_modules/@11ty/eleventy-fetch/eleventy-fetch.js generated vendored Normal file
View File

@ -0,0 +1,94 @@
const { default: PQueue } = require("p-queue");
const debug = require("debug")("Eleventy:Fetch");
const Sources = require("./src/Sources.js");
const RemoteAssetCache = require("./src/RemoteAssetCache.js");
const AssetCache = require("./src/AssetCache.js");
const DirectoryManager = require("./src/DirectoryManager.js");
const globalOptions = {
type: "buffer",
directory: ".cache",
concurrency: 10,
fetchOptions: {},
dryRun: false, // dont write anything to the file system
// *does* affect cache key hash
removeUrlQueryParams: false,
// runs after removeUrlQueryParams, does not affect cache key hash
// formatUrlForDisplay: function(url) {
// return url;
// },
verbose: false, // Changed in 3.0+
hashLength: 30,
};
/* Queue */
let queue = new PQueue({
concurrency: globalOptions.concurrency,
});
queue.on("active", () => {
debug(`Concurrency: ${queue.concurrency}, Size: ${queue.size}, Pending: ${queue.pending}`);
});
let instCache = {};
let directoryManager = new DirectoryManager();
function createRemoteAssetCache(source, rawOptions = {}) {
if (!Sources.isFullUrl(source) && !Sources.isValidSource(source)) {
return Promise.reject(new Error("Invalid source. Received: " + source));
}
let options = Object.assign({}, globalOptions, rawOptions);
let sourceKey = RemoteAssetCache.getRequestId(source, options);
if(!sourceKey) {
return Promise.reject(Sources.getInvalidSourceError(source));
}
if(instCache[sourceKey]) {
return instCache[sourceKey];
}
let inst = new RemoteAssetCache(source, options.directory, options);
inst.setQueue(queue);
inst.setDirectoryManager(directoryManager);
instCache[sourceKey] = inst;
return inst;
}
module.exports = function (source, options) {
let instance = createRemoteAssetCache(source, options);
return instance.queue();
};
Object.defineProperty(module.exports, "concurrency", {
get: function () {
return queue.concurrency;
},
set: function (concurrency) {
queue.concurrency = concurrency;
},
});
module.exports.Fetch = createRemoteAssetCache;
// Deprecated API kept for backwards compat, instead: use default export directly.
// Intentional: queueCallback is ignored here
module.exports.queue = function(source, queueCallback, options) {
let instance = createRemoteAssetCache(source, options);
return instance.queue();
};
module.exports.Util = {
isFullUrl: Sources.isFullUrl,
};
module.exports.RemoteAssetCache = RemoteAssetCache;
module.exports.AssetCache = AssetCache;
module.exports.Sources = Sources;

66
node_modules/@11ty/eleventy-fetch/package.json generated vendored Normal file
View File

@ -0,0 +1,66 @@
{
"name": "@11ty/eleventy-fetch",
"version": "5.1.2",
"description": "Fetch and locally cache remote API calls and assets.",
"publishConfig": {
"access": "public"
},
"repository": {
"type": "git",
"url": "git+https://github.com/11ty/eleventy-fetch.git"
},
"main": "eleventy-fetch.js",
"scripts": {
"test": "ava",
"sample": "node sample",
"format": "prettier . --write"
},
"files": [
"src/",
"eleventy-fetch.js"
],
"engines": {
"node": ">=18"
},
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/11ty"
},
"keywords": [
"eleventy",
"eleventy-utility"
],
"author": {
"name": "Zach Leatherman",
"email": "zachleatherman@gmail.com",
"url": "https://zachleat.com/"
},
"license": "MIT",
"bugs": {
"url": "https://github.com/11ty/eleventy-fetch/issues"
},
"homepage": "https://github.com/11ty/eleventy-fetch#readme",
"devDependencies": {
"ava": "^6.4.1",
"prettier": "^3.7.3"
},
"dependencies": {
"@11ty/eleventy-utils": "^2.0.7",
"@rgrove/parse-xml": "^4.2.0",
"debug": "^4.4.3",
"flatted": "^3.4.2",
"p-queue": "6.6.2"
},
"ava": {
"failFast": false,
"files": [
"./test/*.js"
],
"watchMode": {
"ignoreChanges": [
"**/.cache/**",
"**/.customcache/**"
]
}
}
}

270
node_modules/@11ty/eleventy-fetch/src/AssetCache.js generated vendored Normal file
View File

@ -0,0 +1,270 @@
const fs = require("node:fs");
const path = require("node:path");
const { DateCompare, createHashHexSync } = require("@11ty/eleventy-utils");
const FileCache = require("./FileCache.js");
const Sources = require("./Sources.js");
const debugUtil = require("debug");
const debug = debugUtil("Eleventy:Fetch");
class AssetCache {
#source;
#hash;
#customFilename;
#cache;
#cacheDirectory;
#cacheLocationDirty = false;
#directoryManager;
constructor(source, cacheDirectory, options = {}) {
if(!Sources.isValidSource(source)) {
throw Sources.getInvalidSourceError(source);
}
let uniqueKey = AssetCache.getCacheKey(source, options);
this.uniqueKey = uniqueKey;
this.hash = AssetCache.getHash(uniqueKey, options.hashLength);
this.cacheDirectory = cacheDirectory || ".cache";
this.options = options;
this.defaultDuration = "1d";
this.duration = options.duration || this.defaultDuration;
// Compute the filename only once
if (typeof this.options.filenameFormat === "function") {
this.#customFilename = AssetCache.cleanFilename(this.options.filenameFormat(uniqueKey, this.hash));
if (typeof this.#customFilename !== "string" || this.#customFilename.length === 0) {
throw new Error(`The provided filenameFormat callback function needs to return valid filename characters.`);
}
}
}
log(message) {
if (this.options.verbose) {
console.log(`[11ty/eleventy-fetch] ${message}`);
} else {
debug(message);
}
}
static cleanFilename(filename) {
// Ensure no illegal characters are present (Windows or Linux: forward/backslash, chevrons, colon, double-quote, pipe, question mark, asterisk)
if (filename.match(/([\/\\<>:"|?*]+?)/)) {
let sanitizedFilename = filename.replace(/[\/\\<>:"|?*]+/g, "");
debug(
`[@11ty/eleventy-fetch] Some illegal characters were removed from the cache filename: ${filename} will be cached as ${sanitizedFilename}.`,
);
return sanitizedFilename;
}
return filename;
}
static getCacheKey(source, options) {
// RemoteAssetCache passes in a string here, which skips this check (requestId is already used upstream)
if (Sources.isValidComplexSource(source)) {
if(options.requestId) {
return options.requestId;
}
if(typeof source.toString === "function") {
// return source.toString();
let toStr = source.toString();
if(toStr !== "function() {}" && toStr !== "[object Object]") {
return toStr;
}
}
throw Sources.getInvalidSourceError(source);
}
return source;
}
// Defult hashLength also set in global options, duplicated here for tests
// v5.0+ key can be Array or literal
static getHash(key, hashLength = 30) {
if (!Array.isArray(key)) {
key = [key];
}
let result = createHashHexSync(...key);
return result.slice(0, hashLength);
}
get source() {
return this.#source;
}
set source(source) {
this.#source = source;
}
get hash() {
return this.#hash;
}
set hash(value) {
if (value !== this.#hash) {
this.#cacheLocationDirty = true;
}
this.#hash = value;
}
get cacheDirectory() {
return this.#cacheDirectory;
}
set cacheDirectory(dir) {
if (dir !== this.#cacheDirectory) {
this.#cacheLocationDirty = true;
}
this.#cacheDirectory = dir;
}
get cacheFilename() {
if (typeof this.#customFilename === "string" && this.#customFilename.length > 0) {
return this.#customFilename;
}
return `eleventy-fetch-${this.hash}`;
}
get rootDir() {
// Work in an AWS Lambda (serverless)
// https://docs.aws.amazon.com/lambda/latest/dg/configuration-envvars.html
// Bad: LAMBDA_TASK_ROOT is /var/task/ on AWS so we must use ELEVENTY_ROOT
// When using ELEVENTY_ROOT, cacheDirectory must be relative
// (we are bundling the cache files into the serverless function)
if (
process.env.LAMBDA_TASK_ROOT &&
process.env.ELEVENTY_ROOT &&
!this.cacheDirectory.startsWith("/")
) {
return path.resolve(process.env.ELEVENTY_ROOT, this.cacheDirectory);
}
// otherwise, it is recommended to use somewhere in /tmp/ for serverless (otherwise it wont write)
return path.resolve(this.cacheDirectory);
}
get cachePath() {
return path.join(this.rootDir, this.cacheFilename);
}
get cache() {
if (!this.#cache || this.#cacheLocationDirty) {
let cache = new FileCache(this.cacheFilename, {
dir: this.rootDir,
source: this.source,
});
cache.setDefaultType(this.options.type);
cache.setDryRun(this.options.dryRun);
cache.setDirectoryManager(this.#directoryManager);
this.#cache = cache;
this.#cacheLocationDirty = false;
}
return this.#cache;
}
getDurationMs(duration = "0s") {
return DateCompare.getDurationMs(duration);
}
setDirectoryManager(manager) {
this.#directoryManager = manager;
}
async save(contents, type = "buffer", metadata = {}) {
if(!contents) {
throw new Error("save(contents) expects contents (was falsy)");
}
this.cache.set(type, contents, metadata);
// Dry-run handled downstream
this.cache.save();
}
getCachedContents() {
return this.cache.getContents();
}
getCachedValue() {
if(this.options.returnType === "response") {
return {
...this.cachedObject.metadata?.response,
body: this.getCachedContents(),
cache: "hit",
}
}
return this.getCachedContents();
}
getCachedTimestamp() {
return this.cachedObject?.cachedAt;
}
isCacheValid(duration = this.duration) {
if(!this.cachedObject || !this.cachedObject?.cachedAt) {
return false;
}
if(this.cachedObject?.type && DateCompare.isTimestampWithinDuration(this.cachedObject?.cachedAt, duration)) {
return this.cache.hasContents(this.cachedObject?.type); // check file system to make files havent been purged.
}
return false;
}
get cachedObject() {
return this.cache.get();
}
// Deprecated
needsToFetch(duration) {
return !this.isCacheValid(duration);
}
// This is only included for completenes—not on the docs.
async fetch(optionsOverride = {}) {
if (this.isCacheValid(optionsOverride.duration)) {
// promise
debug(`Using cached version of: ${this.uniqueKey}`);
return this.getCachedValue();
}
debug(`Saving ${this.uniqueKey} to ${this.cacheFilename}`);
await this.save(this.source, optionsOverride.type);
return this.source;
}
// for testing
hasAnyCacheFiles() {
for(let p of this.cache.getAllPossibleFilePaths()) {
if(fs.existsSync(p)) {
return true;
}
}
return false;
}
// for testing
async destroy() {
await Promise.all(this.cache.getAllPossibleFilePaths().map(path => {
if (fs.existsSync(path)) {
return fs.unlinkSync(path);
}
}))
}
}
module.exports = AssetCache;

View File

@ -0,0 +1,22 @@
const fs = require("node:fs");
const debugAssets = require("debug")("Eleventy:Assets");
class DirectoryManager {
#dirs = new Set();
isCreated(dir) {
return this.#dirs.has(dir);
}
create(dir) {
if(this.isCreated(dir)) {
return;
}
this.#dirs.add(dir);
debugAssets("Creating directory %o", dir);
fs.mkdirSync(dir, { recursive: true });
}
}
module.exports = DirectoryManager;

24
node_modules/@11ty/eleventy-fetch/src/ExistsCache.js generated vendored Normal file
View File

@ -0,0 +1,24 @@
const fs = require("node:fs");
// const debug = require("debug")("Eleventy:Assets");
class ExistsCache {
#checks = new Map();
#count = 0;
set(target, value) {
this.#checks.set(target, Boolean(value));
}
exists(target) {
if(this.#checks.has(target)) {
return this.#checks.get(target);
}
let exists = fs.existsSync(target);
this.#count++;
this.#checks.set(target, exists);
return exists;
}
}
module.exports = ExistsCache;

237
node_modules/@11ty/eleventy-fetch/src/FileCache.js generated vendored Normal file
View File

@ -0,0 +1,237 @@
const fs = require("node:fs");
const path = require("node:path");
const debugUtil = require("debug");
const { parse } = require("flatted");
const debug = debugUtil("Eleventy:Fetch");
const debugAssets = debugUtil("Eleventy:Assets");
const DirectoryManager = require("./DirectoryManager.js");
const ExistsCache = require("./ExistsCache.js");
let existsCache = new ExistsCache();
class FileCache {
#source;
#directoryManager;
#metadata;
#defaultType;
#contents;
#dryRun = false;
#cacheDirectory = ".cache";
#savePending = false;
#counts = {
read: 0,
write: 0,
};
constructor(cacheFilename, options = {}) {
this.cacheFilename = cacheFilename;
if(options.dir) {
this.#cacheDirectory = options.dir;
}
if(options.source) {
this.#source = options.source;
}
}
setDefaultType(type) {
if(type) {
this.#defaultType = type;
}
}
setDryRun(val) {
this.#dryRun = Boolean(val);
}
setDirectoryManager(manager) {
this.#directoryManager = manager;
}
ensureDir() {
if (this.#dryRun || existsCache.exists(this.#cacheDirectory)) {
return;
}
if(!this.#directoryManager) {
// standalone fallback (for tests)
this.#directoryManager = new DirectoryManager();
}
this.#directoryManager.create(this.#cacheDirectory);
}
set(type, contents, extraMetadata = {}) {
this.#savePending = true;
this.#metadata = {
cachedAt: Date.now(),
type,
// source: this.#source,
metadata: extraMetadata,
};
this.#contents = contents;
}
get fsPath() {
return path.join(this.#cacheDirectory, this.cacheFilename);
}
getContentsPath(type) {
if(!type) {
throw new Error("Missing cache type for " + this.fsPath);
}
// normalize to storage type
if(type === "xml") {
type = "text";
} else if(type === "parsed-xml") {
type = "json";
}
return `${this.fsPath}.${type}`;
}
// only when side loaded (buffer content)
get contentsPath() {
return this.getContentsPath(this.#metadata?.type);
}
get() {
if(this.#metadata) {
return this.#metadata;
}
if(!existsCache.exists(this.fsPath)) {
return;
}
debug(`Fetching from cache ${this.fsPath}`);
if(this.#source) {
debugAssets("[11ty/eleventy-fetch] Reading via %o", this.#source);
} else {
debugAssets("[11ty/eleventy-fetch] Reading %o", this.fsPath);
}
this.#counts.read++;
let data = fs.readFileSync(this.fsPath, "utf8");
let json;
// Backwards compatibility with previous caches usingn flat-cache and `flatted`
if(data.startsWith(`[["1"],`)) {
let flattedParsed = parse(data);
if(flattedParsed?.[0]?.value) {
json = flattedParsed?.[0]?.value
}
} else {
json = JSON.parse(data);
}
this.#metadata = json;
return json;
}
_backwardsCompatGetContents(rawData, type) {
if (type === "json") {
return rawData.contents;
} else if (type === "text") {
return rawData.contents.toString();
}
// buffer
return Buffer.from(rawData.contents);
}
hasContents(type) {
if(this.#contents) {
return true;
}
if(this.get()?.contents) { // backwards compat with very old caches
return true;
}
return existsCache.exists(this.getContentsPath(type));
}
getType() {
return this.#metadata?.type || this.#defaultType;
}
getContents() {
if(this.#contents) {
return this.#contents;
}
let metadata = this.get();
// backwards compat with old caches
if(metadata?.contents) {
// already parsed, part of the top level file
let normalizedContent = this._backwardsCompatGetContents(this.get(), this.getType());
this.#contents = normalizedContent;
return normalizedContent;
}
if(!existsCache.exists(this.contentsPath)) {
return;
}
debug(`Fetching from cache ${this.contentsPath}`);
if(this.#source) {
debugAssets("[11ty/eleventy-fetch] Reading (side loaded) via %o", this.#source);
} else {
debugAssets("[11ty/eleventy-fetch] Reading (side loaded) %o", this.contentsPath);
}
// It is intentional to store contents in a separate file from the metadata: we dont want to
// have to read the entire contents via JSON.parse (or otherwise) to check the cache validity.
this.#counts.read++;
let type = metadata?.type || this.getType();
let data = fs.readFileSync(this.contentsPath);
if (type === "json" || type === "parsed-xml") {
data = JSON.parse(data);
}
this.#contents = data;
return data;
}
save() {
if(this.#dryRun || !this.#savePending || this.#metadata && Object.keys(this.#metadata) === 0) {
return;
}
this.ensureDir(); // doesnt add to counts (yet?)
// contents before metadata
debugAssets("[11ty/eleventy-fetch] Writing %o (side loaded) from %o", this.contentsPath, this.#source);
this.#counts.write++;
// the contents must exist before the cache metadata are saved below
let contents = this.#contents;
let type = this.getType();
if (type === "json" || type === "parsed-xml") {
contents = JSON.stringify(contents);
}
fs.writeFileSync(this.contentsPath, contents);
debug(`Writing ${this.contentsPath}`);
this.#counts.write++;
debugAssets("[11ty/eleventy-fetch] Writing %o from %o", this.fsPath, this.#source);
fs.writeFileSync(this.fsPath, JSON.stringify(this.#metadata), "utf8");
debug(`Writing ${this.fsPath}`);
}
// for testing
getAllPossibleFilePaths() {
let types = ["text", "buffer", "json"];
let paths = new Set();
paths.add(this.fsPath);
for(let type of types) {
paths.add(this.getContentsPath(type));
}
return Array.from(paths);
}
}
module.exports = FileCache;

View File

@ -0,0 +1,235 @@
const debugUtil = require("debug");
const { parseXml } = require('@rgrove/parse-xml');
const Sources = require("./Sources.js");
const AssetCache = require("./AssetCache.js");
const debug = debugUtil("Eleventy:Fetch");
const debugAssets = debugUtil("Eleventy:Assets");
class RemoteAssetCache extends AssetCache {
#queue;
#queuePromise;
#fetchPromise;
#lastFetchType;
constructor(source, cacheDirectory, options = {}) {
let requestId = RemoteAssetCache.getRequestId(source, options);
super(requestId, cacheDirectory, options);
this.source = source;
this.options = options;
this.displayUrl = RemoteAssetCache.convertUrlToString(source, options);
this.fetchCount = 0;
}
static getRequestId(source, options = {}) {
if (Sources.isValidComplexSource(source)) {
return this.getCacheKey(source, options);
}
if (options.removeUrlQueryParams) {
let cleaned = this.cleanUrl(source);
return this.getCacheKey(cleaned, options);
}
return this.getCacheKey(source, options);
}
static getCacheKey(source, options) {
let cacheKey = {
source: AssetCache.getCacheKey(source, options),
};
if(options.type === "xml" || options.type === "parsed-xml") {
cacheKey.type = options.type;
}
if (options.fetchOptions) {
if (options.fetchOptions.method && options.fetchOptions.method !== "GET") {
cacheKey.method = options.fetchOptions.method;
}
if (options.fetchOptions.body) {
cacheKey.body = options.fetchOptions.body;
}
}
if(Object.keys(cacheKey).length > 1) {
return JSON.stringify(cacheKey);
}
return cacheKey.source;
}
static cleanUrl(url) {
if(!Sources.isFullUrl(url)) {
return url;
}
let cleanUrl;
if(typeof url === "string" || typeof url.toString === "function") {
cleanUrl = new URL(url);
} else if(url instanceof URL) {
cleanUrl = url;
} else {
throw new Error("Invalid source for cleanUrl: " + url)
}
cleanUrl.search = new URLSearchParams([]);
return cleanUrl.toString();
}
static convertUrlToString(source, options = {}) {
// removes query params
source = RemoteAssetCache.cleanUrl(source);
let { formatUrlForDisplay } = options;
if (formatUrlForDisplay && typeof formatUrlForDisplay === "function") {
return "" + formatUrlForDisplay(source);
}
return "" + source;
}
async getResponseValue(response, type) {
if (type === "json") {
return response.json();
} else if (type === "text" || type === "xml") {
return response.text();
} else if(type === "parsed-xml") {
return parseXml(await response.text());
}
return Buffer.from(await response.arrayBuffer());
}
setQueue(queue) {
this.#queue = queue;
}
// Returns raw Promise
queue() {
if(!this.#queue) {
throw new Error("Missing `#queue` instance.");
}
if(!this.#queuePromise) {
// optionsOverride not supported on fetch here for re-use
this.#queuePromise = this.#queue.add(() => this.fetch()).catch((e) => {
this.#queuePromise = undefined;
throw e;
});
}
return this.#queuePromise;
}
isCacheValid(duration = undefined) {
// uses this.options.duration if not explicitly defined here
return super.isCacheValid(duration);
}
// if last fetch was a cache hit (no fetch occurred) or a cache miss (fetch did occur)
// used by Eleventy Image in disk cache checks.
wasLastFetchCacheHit() {
return this.#lastFetchType === "hit";
}
async #fetch(optionsOverride = {}) {
// Important: no disk writes when dryRun
// As of Fetch v4, reads are now allowed!
if (this.isCacheValid(optionsOverride.duration)) {
debug(`Cache hit for ${this.displayUrl}`);
this.#lastFetchType = "hit";
return super.getCachedValue();
}
this.#lastFetchType = "miss";
try {
let isDryRun = optionsOverride.dryRun || this.options.dryRun;
this.log(`Fetching ${this.displayUrl}`);
let body;
let metadata = {};
let type = optionsOverride.type || this.options.type;
if (typeof this.source === "object" && typeof this.source.then === "function") {
body = await this.source;
} else if (typeof this.source === "function") {
// sync or async function
body = await this.source();
} else {
let fetchOptions = optionsOverride.fetchOptions || this.options.fetchOptions || {};
if(!Sources.isFullUrl(this.source)) {
throw Sources.getInvalidSourceError(this.source);
}
this.fetchCount++;
debugAssets("[11ty/eleventy-fetch] Fetching %o", this.source);
// v5: now using global (Node-native or otherwise) fetch instead of node-fetch
let response;
let error;
try {
response = await fetch(this.source, fetchOptions);
if (response?.ok) {
metadata.response = {
url: response.url,
status: response.status,
headers: Object.fromEntries(response.headers.entries()),
};
body = await this.getResponseValue(response, type);
}
} catch(e) {
error = e;
}
if(!response?.ok || error) {
let errorMessage = response?.status || response?.statusText ? ` (${response?.status}): ${response.statusText}` : `: ${error.message}`;
throw new Error(`Bad response for ${this.displayUrl}${errorMessage}`, {
cause: error || response
})
}
}
if (!isDryRun) {
await super.save(body, type, metadata);
}
if(this.options.returnType === "response") {
return {
...metadata.response,
body,
cache: "miss",
}
}
return body;
} catch (e) {
if (this.cachedObject && this.getDurationMs(this.duration) > 0) {
debug(`Error fetching ${this.displayUrl}. Message: ${e.message}`);
debug(`Failing gracefully with an expired cache entry.`);
return super.getCachedValue();
} else {
return Promise.reject(e);
}
}
}
// async but not explicitly declared for promise equality checks
// returns a Promise
async fetch(optionsOverride = {}) {
if(!this.#fetchPromise) {
// one at a time. clear when finished
this.#fetchPromise = this.#fetch(optionsOverride).finally(() => {
this.#fetchPromise = undefined;
});
}
return this.#fetchPromise;
}
}
module.exports = RemoteAssetCache;

50
node_modules/@11ty/eleventy-fetch/src/Sources.js generated vendored Normal file
View File

@ -0,0 +1,50 @@
class Sources {
static isFullUrl(url) {
try {
if(url instanceof URL) {
return true;
}
new URL(url);
return true;
} catch (e) {
// invalid url OR already a local path
return false;
}
}
static isValidSource(source) {
// String (url?)
if(typeof source === "string") {
return true;
}
if(this.isValidComplexSource(source)) {
return true;
}
return false;
}
static isValidComplexSource(source) {
// Async/sync Function
if(typeof source === "function") {
return true;
}
if(typeof source === "object") {
// Raw promise
if(typeof source.then === "function") {
return true;
}
// anything string-able
if(typeof source.toString === "function") {
return true;
}
}
return false;
}
static getInvalidSourceError(source, errorCause) {
return new Error("Invalid source: must be a string, function, or Promise. If a function or Promise, you must provide a `toString()` method or an `options.requestId` unique key. Received: " + source, { cause: errorCause });
}
}
module.exports = Sources;

40
node_modules/@11ty/eleventy-img/README.md generated vendored Normal file
View File

@ -0,0 +1,40 @@
<p align="center"><img src="https://www.11ty.dev/img/logo-github.svg" width="200" height="200" alt="eleventy Logo"></p>
# eleventy-img
Requires Node 18+
Low level utility to perform build-time image transformations for both vector and raster images. Output multiple sizes, save multiple formats, cache remote images locally. Uses the [sharp](https://sharp.pixelplumbing.com/) image processor.
You maintain full control of your HTML. Use with `<picture>` or `<img>` or CSS `background-image`, or others! Works great to add `width` and `height` to your images!
## [The full `eleventy-img` documentation is on 11ty.dev](https://www.11ty.dev/docs/plugins/image/).
* _This is a plugin for the [Eleventy static site generator](https://www.11ty.dev/)._
* Find more [Eleventy plugins](https://www.11ty.dev/docs/plugins/).
* Please star [Eleventy on GitHub](https://github.com/11ty/eleventy/), follow [@eleven_ty](https://twitter.com/eleven_ty) on Twitter, and support [11ty on Open Collective](https://opencollective.com/11ty)
[![npm Version](https://img.shields.io/npm/v/@11ty/eleventy-img.svg?style=for-the-badge)](https://www.npmjs.com/package/@11ty/eleventy-img) [![GitHub issues](https://img.shields.io/github/issues/11ty/eleventy-img.svg?style=for-the-badge)](https://github.com/11ty/eleventy-img/issues)
## Installation
```
npm install --save-dev @11ty/eleventy-img
```
_[The full `eleventy-img` documentation is on 11ty.dev](https://www.11ty.dev/docs/plugins/image/)._
## Tests
```
npm run test
```
- We use the [ava JavaScript test runner](https://github.com/avajs/ava) ([Assertions documentation](https://github.com/avajs/ava/blob/master/docs/03-assertions.md))
- To keep tests fast, thou shalt try to avoid writing files in tests.
## Community Roadmap
- [Top Feature Requests](https://github.com/11ty/eleventy-img/issues?q=label%3Aneeds-votes+sort%3Areactions-%2B1-desc+label%3Aenhancement) (Add your own votes using the 👍 reaction)
- [Top Bugs 😱](https://github.com/11ty/eleventy-img/issues?q=is%3Aissue+is%3Aopen+label%3Abug+sort%3Areactions-%2B1-desc) (Add your own votes using the 👍 reaction)
- [Newest Bugs 🙀](https://github.com/11ty/eleventy-img/issues?q=is%3Aopen+is%3Aissue+label%3Abug)

131
node_modules/@11ty/eleventy-img/eleventy-image.webc generated vendored Normal file
View File

@ -0,0 +1,131 @@
<!---
Supported attribute list:
* src (required)
* width
* formats
* url-path
* output-dir
<img
webc:is="eleventy-image"
src="./src/img/possum-geri.png"
alt="The possum is Eleventys mascot"
width="222, 350"
class="some-custom-class"
sizes="(min-width: 43.75em) 100px, 15vw">
Alternative attribute formats:
:width="[222, 350]"
formats="avif,webp,jpeg"
:formats="['avif', 'webp', 'jpeg']"
--->
<script webc:type="js">
const path = require("path");
// TODO expose this for re-use in a provided shortcode.
async function imagePlugin(attributes, globalPluginOptions) {
if(!attributes.src) {
throw new Error("Missing `src` attribute on <eleventy-image>");
}
// TODO allow remote optimization automatically on full urls
let imagePackage;
let defaultGlobalAttributes;
if(globalPluginOptions) {
defaultGlobalAttributes = globalPluginOptions.defaultAttributes;
delete globalPluginOptions.defaultAttributes;
imagePackage = globalPluginOptions.packages?.image;
delete globalPluginOptions.packages;
}
if(!imagePackage) {
imagePackage = require("@11ty/eleventy-img");
}
let instanceOptions = {};
// Note that multiple widths require a `sizes`
if(attributes.width) {
if(typeof attributes.width === "string") {
instanceOptions.widths = attributes.width.split(",").map(entry => parseInt(entry, 10));
delete attributes.width;
} else if(Array.isArray(attributes.width)) {
instanceOptions.widths = attributes.width;
delete attributes.width;
}
}
if(attributes.formats) {
if(typeof attributes.formats === "string") {
instanceOptions.formats = attributes.formats.split(",").map(entry => entry.trim());
delete attributes.formats;
} else if(Array.isArray(attributes.formats)) {
instanceOptions.formats = attributes.formats;
delete attributes.formats;
}
}
// These defaults are set only if addPlugin was **not** called:
if(!globalPluginOptions) {
// Using eleventy.directories global data (Eleventy 2.0.2+)
if(eleventy.directories) {
instanceOptions.urlPath = "/img/";
// write to output folder by default
instanceOptions.outputDir = path.join(eleventy.directories.output, instanceOptions.urlPath);
}
}
// Overrides via attributes (hopefully you dont need these)
if(attributes.urlPath) {
instanceOptions.urlPath = attributes.urlPath;
delete attributes.urlPath;
if(eleventy.directories && !attributes.outputDir) {
// use output folder if available (Eleventy v2.0.2+)
instanceOptions.outputDir = path.join(eleventy.directories.output, instanceOptions.urlPath);
}
}
if(attributes.outputDir) {
instanceOptions.outputDir = attributes.outputDir;
delete attributes.outputDir;
}
let options = Object.assign({}, globalPluginOptions, instanceOptions);
// see Util.addConfig
if(globalPluginOptions.eleventyConfig) {
Object.defineProperty(options, "eleventyConfig", {
value: globalPluginOptions.eleventyConfig,
enumerable: false,
});
}
let metadata = await imagePackage(src, options);
let imageAttributes = Object.assign({}, defaultGlobalAttributes, attributes);
// You bet we throw an error on missing alt in `imageAttributes` (alt="" works okay)
return imagePackage.generateHTML(metadata, imageAttributes);
};
(async () => {
let globalPluginOptions;
// fetch global options from from addPlugin call
if(typeof __private_eleventyImageConfigurationOptions === "function") {
globalPluginOptions = __private_eleventyImageConfigurationOptions();
}
if(!("filterPublicAttributes" in webc)) {
throw new Error("The <eleventy-image> WebC component requires WebC v0.10.1+");
}
let attributes = webc.filterPublicAttributes(webc.attributes);
return imagePlugin(attributes, globalPluginOptions);
})();
</script>

29
node_modules/@11ty/eleventy-img/eslint.config.mjs generated vendored Normal file
View File

@ -0,0 +1,29 @@
import { defineConfig } from "eslint/config";
import pluginJs from "@eslint/js";
import pluginStylistic from "@stylistic/eslint-plugin-js";
import globals from "globals";
const GLOB_JS = '**/*.?([cm])js';
export default defineConfig([
{
files: [GLOB_JS],
plugins: {
js: pluginJs,
"@stylistic/js": pluginStylistic
},
extends: [
"js/recommended",
],
languageOptions: {
ecmaVersion: 2022,
sourceType: "module",
globals: { ...globals.node },
},
rules: {
"@stylistic/js/indent": ["error", 2],
"@stylistic/js/linebreak-style": ["error", "unix"],
"@stylistic/js/semi": ["error", "always"],
},
},
]);

151
node_modules/@11ty/eleventy-img/img.js generated vendored Normal file
View File

@ -0,0 +1,151 @@
const {default: PQueue} = require("p-queue");
const DeferCounter = require("./src/defer-counter.js");
const BuildLogger = require("./src/build-logger.js");
const Util = require("./src/util.js");
const Image = require("./src/image.js");
const DirectoryManager = require("./src/directory-manager.js");
// For exports
const getImageSize = require("image-size");
const ImagePath = require("./src/image-path.js");
const debug = require("debug")("Eleventy:Image");
const GLOBAL_OPTIONS = require("./src/global-options.js").defaults;
const { memCache, diskCache } = require("./src/caches.js");
let deferCounter = new DeferCounter();
let buildLogger = new BuildLogger();
let directoryManager = new DirectoryManager();
/* Queue */
let processingQueue = new PQueue({
concurrency: GLOBAL_OPTIONS.concurrency
});
processingQueue.on("active", () => {
debug( `Concurrency: ${processingQueue.concurrency}, Size: ${processingQueue.size}, Pending: ${processingQueue.pending}` );
});
// TODO move this into build-logger.js
function setupLogger(eleventyConfig, opts) {
if(typeof eleventyConfig?.logger?.logWithOptions !== "function" || Util.isRequested(opts?.generatedVia)) {
return;
}
buildLogger.setupOnce(eleventyConfig, () => {
// before build
deferCounter.resetCount();
memCache.resetCount();
diskCache.resetCount();
}, () => {
// after build
let [memoryCacheHit] = memCache.getCount();
let [diskCacheHit, diskCacheMiss] = diskCache.getCount();
// these are unique images, multiple requests to optimize the same image are de-duplicated
let deferCount = deferCounter.getCount();
let cachedCount = memoryCacheHit + diskCacheHit;
let optimizedCount = diskCacheMiss + diskCacheHit + memoryCacheHit + deferCount;
let msg = [];
msg.push(`${optimizedCount} ${optimizedCount !== 1 ? "images" : "image"} optimized`);
if(cachedCount > 0 || deferCount > 0) {
let innerMsg = [];
if(cachedCount > 0) {
innerMsg.push(`${cachedCount} cached`);
}
if(deferCount > 0) {
innerMsg.push(`${deferCount} deferred`);
}
msg.push(` (${innerMsg.join(", ")})`);
}
if(optimizedCount > 0 || cachedCount > 0 || deferCount > 0) {
eleventyConfig?.logger?.logWithOptions({
message: msg.join(""),
prefix: "[11ty/eleventy-img]",
color: "green",
});
}
});
}
function createImage(src, opts = {}) {
let eleventyConfig = opts.eleventyConfig;
if(opts?.eleventyConfig && {}.propertyIsEnumerable.call(opts, "eleventyConfig")) {
delete opts.eleventyConfig;
Util.addConfig(eleventyConfig, opts);
}
let img = Image.create(src, opts);
img.setQueue(processingQueue);
img.setBuildLogger(buildLogger);
img.setDirectoryManager(directoryManager);
setupLogger(eleventyConfig, opts);
if(opts.transformOnRequest) {
deferCounter.increment(src);
}
return img;
};
function queueImage(src, opts = {}) {
if(src.constructor?.name === "UserConfig") {
throw new Error(`Eleventy Images default export is not an Eleventy Plugin and cannot be used with \`eleventyConfig.addPlugin()\`. Use the \`eleventyImageTransformPlugin\` named export instead, like this: \`import { eleventyImageTransformPlugin } from '@11ty/eleventy-img';\` or this: \`const { eleventyImageTransformPlugin } = require('@11ty/eleventy-img');\``);
}
let img = createImage(src, opts);
return img.queue();
}
// Exports
module.exports = queueImage;
Object.defineProperty(module.exports, "concurrency", {
get: function() {
return processingQueue.concurrency;
},
set: function(concurrency) {
processingQueue.concurrency = concurrency;
},
});
module.exports.Util = Util;
module.exports.Image = Image;
module.exports.ImagePath = ImagePath;
module.exports.ImageSize = getImageSize;
// Backwards compat
module.exports.statsSync = Image.statsSync;
module.exports.statsByDimensionsSync = Image.statsByDimensionsSync;
module.exports.getFormats = Image.getFormatsArray;
module.exports.getWidths = Image.getValidWidths;
module.exports.getHash = function getHash(src, options) {
let img = new Image(src, options);
return img.getHash();
};
module.exports.setupLogger = setupLogger;
const generateHTML = require("./src/generate-html.js");
module.exports.generateHTML = generateHTML;
module.exports.generateObject = generateHTML.generateObject;
const { eleventyWebcOptionsPlugin } = require("./src/webc-options-plugin.js");
module.exports.eleventyImagePlugin = eleventyWebcOptionsPlugin;
module.exports.eleventyImageWebcOptionsPlugin = eleventyWebcOptionsPlugin;
const { eleventyImageTransformPlugin } = require("./src/transform-plugin.js");
module.exports.eleventyImageTransformPlugin = eleventyImageTransformPlugin;
const { eleventyImageOnRequestDuringServePlugin } = require("./src/on-request-during-serve-plugin.js");
module.exports.eleventyImageOnRequestDuringServePlugin = eleventyImageOnRequestDuringServePlugin;

75
node_modules/@11ty/eleventy-img/package.json generated vendored Normal file
View File

@ -0,0 +1,75 @@
{
"name": "@11ty/eleventy-img",
"version": "6.0.4",
"description": "Low level utility to perform build-time image transformations.",
"publishConfig": {
"access": "public"
},
"main": "img.js",
"engines": {
"node": ">=18"
},
"scripts": {
"pretest": "eslint img.js src/**.js test/**.js",
"test": "ava --no-worker-threads",
"watch": "ava --no-worker-threads --watch",
"sample": "cd sample && node sample.js"
},
"repository": {
"type": "git",
"url": "git+https://github.com/11ty/eleventy-img.git"
},
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/11ty"
},
"keywords": [
"eleventy",
"eleventy-utility"
],
"author": {
"name": "Zach Leatherman",
"email": "zachleatherman@gmail.com",
"url": "https://zachleat.com/"
},
"license": "MIT",
"bugs": {
"url": "https://github.com/11ty/eleventy-img/issues"
},
"homepage": "https://github.com/11ty/eleventy-img#readme",
"dependencies": {
"@11ty/eleventy-fetch": "^5.1.0",
"@11ty/eleventy-utils": "^2.0.7",
"brotli-size": "^4.0.0",
"debug": "^4.4.0",
"entities": "^6.0.0",
"image-size": "^1.2.1",
"p-queue": "^6.6.2",
"sharp": "^0.33.5"
},
"devDependencies": {
"@11ty/eleventy": "^3.0.0",
"@11ty/eleventy-plugin-webc": "^0.11.2",
"@eslint/js": "^9.26.0",
"@stylistic/eslint-plugin-js": "^4.2.0",
"ava": "^6.3.0",
"eslint": "^9.26.0",
"exifr": "^7.1.3",
"globals": "^16.1.0",
"pixelmatch": "^5.3.0"
},
"ava": {
"failFast": false,
"files": [
"./test/*.{js,cjs,mjs}"
],
"watchMode": {
"ignoreChanges": [
"./.cache/*",
"./img/*",
"./test/img/*",
"./test/**/generated*"
]
}
}
}

View File

@ -0,0 +1,3 @@
module.exports = function() {
throw new Error("`svgCompressionSize: 'br'` feature is not supported in browser.");
};

View File

@ -0,0 +1,5 @@
const brotliSize = require("brotli-size");
module.exports = function(contents) {
return brotliSize.sync(contents);
};

View File

@ -0,0 +1,3 @@
module.exports = function() {
throw new Error("Sharp is not supported in browser.");
};

View File

@ -0,0 +1,3 @@
const sharp = require("sharp");
module.exports = sharp;

66
node_modules/@11ty/eleventy-img/src/build-logger.js generated vendored Normal file
View File

@ -0,0 +1,66 @@
const path = require("node:path");
const { TemplatePath } = require("@11ty/eleventy-utils");
const Util = require("./util.js");
class BuildLogger {
#eleventyConfig;
constructor() {
this.hasAssigned = false;
}
setupOnce(eleventyConfig, beforeCallback, afterCallback) {
if(this.hasAssigned) {
return;
}
this.hasAssigned = true;
this.#eleventyConfig = eleventyConfig;
eleventyConfig.on("eleventy.before", beforeCallback);
eleventyConfig.on("eleventy.after", afterCallback);
eleventyConfig.on("eleventy.reset", () => {
this.hasAssigned = false;
beforeCallback(); // we run this on reset because the before callback will have disappeared (as the config reset)
});
}
getFriendlyImageSource(imageSource) {
if(Buffer.isBuffer(imageSource)) {
return `<Buffer>`;
}
if(Util.isRemoteUrl(imageSource)) {
return imageSource;
}
if(path.isAbsolute(imageSource)) {
// convert back to relative url
return TemplatePath.addLeadingDotSlash(path.relative(path.resolve("."), imageSource));
}
return TemplatePath.addLeadingDotSlash(imageSource);
}
log(message, options = {}, logOptions = {}) {
if(typeof this.#eleventyConfig?.logger?.logWithOptions !== "function" || options.transformOnRequest) {
return;
}
this.#eleventyConfig.logger.logWithOptions(Object.assign({
message: `${message}${options.generatedVia ? ` (${options.generatedVia})` : ""}`,
type: "log",
prefix: "[11ty/eleventy-img]"
}, logOptions));
}
error(message, options = {}, logOptions = {}) {
logOptions.type = "error";
logOptions.force = true;
this.log(message, options, logOptions);
}
}
module.exports = BuildLogger;

16
node_modules/@11ty/eleventy-img/src/caches.js generated vendored Normal file
View File

@ -0,0 +1,16 @@
const MemoryCache = require("./memory-cache.js");
const DiskCache = require("./disk-cache.js");
const ExistsCache = require("./exists-cache.js");
let memCache = new MemoryCache();
let existsCache = new ExistsCache();
let diskCache = new DiskCache();
diskCache.setExistsCache(existsCache);
module.exports = {
memCache,
diskCache,
existsCache
};

27
node_modules/@11ty/eleventy-img/src/defer-counter.js generated vendored Normal file
View File

@ -0,0 +1,27 @@
class DeferCounter {
constructor() {
this.resetCount();
}
resetCount() {
this.deferCount = 0;
this.inputs = new Map();
}
getCount() {
return this.deferCount;
}
increment(input) {
if(input) {
if(this.inputs.has(input)) {
return;
}
this.inputs.set(input, true);
}
this.deferCount++;
}
}
module.exports = DeferCounter;

View File

@ -0,0 +1,29 @@
const fs = require("node:fs");
const path = require("node:path");
const debugUtil = require("debug");
const debugAssets = debugUtil("Eleventy:Assets");
class DirectoryManager {
#dirs = new Set();
isCreated(dir) {
return this.#dirs.has(dir);
}
create(dir) {
if(this.isCreated(dir)) {
return;
}
this.#dirs.add(dir);
debugAssets("[11ty/eleventy-img] Creating directory %o", dir);
fs.mkdirSync(dir, { recursive: true });
}
createFromFile(filepath) {
let dir = path.dirname(filepath);
this.create(dir);
}
}
module.exports = DirectoryManager;

54
node_modules/@11ty/eleventy-img/src/disk-cache.js generated vendored Normal file
View File

@ -0,0 +1,54 @@
// const debug = require("debug")("Eleventy:Image");
class DiskCache {
#existsCache;
constructor() {
this.hitCounter = 0;
this.missCounter = 0;
this.inputs = new Map();
}
setExistsCache(existsCache) {
this.#existsCache = existsCache;
}
resetCount() {
this.hitCounter = 0;
this.missCounter = 0;
}
getCount() {
return [this.hitCounter, this.missCounter];
}
isCached(targetFile, sourceInput, incrementCounts = true) {
if(!this.#existsCache) {
throw new Error("Missing `#existsCache`");
}
// Disk cache runs once per output file, so we only increment counts once per input
if(this.inputs.has(sourceInput)) {
incrementCounts = false;
}
this.inputs.set(sourceInput, true);
if(this.#existsCache?.exists(targetFile)) {
if(incrementCounts) {
this.hitCounter++;
}
// debug("Images re-used (via disk cache): %o", this.hitCounter);
return true;
}
if(incrementCounts) {
this.missCounter++;
}
return false;
}
}
module.exports = DiskCache;

40
node_modules/@11ty/eleventy-img/src/exists-cache.js generated vendored Normal file
View File

@ -0,0 +1,40 @@
const fs = require("node:fs");
const Util = require("./util.js");
// Checks both files and directories
class ExistsCache {
#exists = new Map();
constructor() {
this.lookupCount = 0;
}
get size() {
return this.#exists.size;
}
has(path) {
return this.#exists.has(path);
}
// Relative paths (to root directory) expected (but not enforced due to perf costs)
exists(path) {
if(Util.isFullUrl(path)) {
return false;
}
if (!this.#exists.has(path)) {
let exists = fs.existsSync(path);
this.lookupCount++;
// mark for next time
this.#exists.set(path, Boolean(exists));
return exists;
}
return this.#exists.get(path);
}
}
module.exports = ExistsCache;

View File

@ -0,0 +1,14 @@
const fs = require("node:fs");
const debugUtil = require("debug");
const debugAssets = debugUtil("Eleventy:Assets");
module.exports = async function createSvg(sharpInstance) {
let input = sharpInstance.options.input;
let svgBuffer = input.buffer;
if(svgBuffer) { // remote URL already has buffer
return svgBuffer;
} else { // local file system
debugAssets("[11ty/eleventy-img] Reading %o", input.file);
return fs.readFileSync(input.file);
}
};

220
node_modules/@11ty/eleventy-img/src/generate-html.js generated vendored Normal file
View File

@ -0,0 +1,220 @@
const { escapeAttribute } = require("entities");
const LOWSRC_FORMAT_PREFERENCE = ["jpeg", "png", "gif", "svg", "webp", "avif"];
const CHILDREN_OBJECT_KEY = "@children";
function generateSrcset(metadataFormatEntry) {
if(!Array.isArray(metadataFormatEntry)) {
return "";
}
return metadataFormatEntry.map(entry => entry.srcset).join(", ");
}
/*
Returns:
e.g. { img: { alt: "", src: "" }
e.g. { img: { alt: "", src: "", srcset: "", sizes: "" } }
e.g. { picture: {
class: "",
@children: [
{ source: { srcset: "", sizes: "" } },
{ source: { srcset: "", sizes: "" } },
{ img: { alt: "", src: "", srcset: "", sizes: "" } },
]
}
*/
function generateObject(metadata, userDefinedImgAttributes = {}, userDefinedPictureAttributes = {}, options = {}) {
let htmlOptions = options?.htmlOptions || {};
let imgAttributes = Object.assign({}, options?.defaultAttributes, htmlOptions?.imgAttributes, userDefinedImgAttributes);
let pictureAttributes = Object.assign({}, htmlOptions?.pictureAttributes, userDefinedPictureAttributes);
// The attributes.src gets overwritten later on. Save it here to make the error outputs less cryptic.
let originalSrc = imgAttributes.src;
if(imgAttributes.alt === undefined) {
// You bet we throw an error on missing alt (alt="" works okay)
throw new Error(`Missing \`alt\` attribute on eleventy-img shortcode from: ${originalSrc}`);
}
let formats = Object.keys(metadata);
let values = Object.values(metadata);
let entryCount = 0;
for(let imageFormat of values) {
entryCount += imageFormat.length;
}
if(entryCount === 0) {
throw new Error("No image results found from `eleventy-img` in generateHTML. Expects a results object similar to: https://www.11ty.dev/docs/plugins/image/#usage.");
}
let lowsrc;
let lowsrcFormat;
for(let format of LOWSRC_FORMAT_PREFERENCE) {
if((format in metadata) && metadata[format].length) {
lowsrcFormat = format;
lowsrc = metadata[lowsrcFormat];
break;
}
}
// Handle if empty intersection between format and LOWSRC_FORMAT_PREFERENCE (e.g. gif)
// If theres only one format in the results, use that
if(!lowsrc && formats.length === 1) {
lowsrcFormat = formats[0];
lowsrc = metadata[lowsrcFormat];
}
if(!lowsrc || !lowsrc.length) {
throw new Error(`Could not find the lowest <img> source for responsive markup for ${originalSrc}`);
}
imgAttributes.src = lowsrc[0].url;
if(htmlOptions.fallback === "largest" || htmlOptions.fallback === undefined) {
imgAttributes.width = lowsrc[lowsrc.length - 1].width;
imgAttributes.height = lowsrc[lowsrc.length - 1].height;
} else if(htmlOptions.fallback === "smallest") {
imgAttributes.width = lowsrc[0].width;
imgAttributes.height = lowsrc[0].height;
} else {
throw new Error("Invalid `fallback` option specified. 'largest' and 'smallest' are supported. Received: " + htmlOptions.fallback);
}
let imgAttributesWithoutSizes = Object.assign({}, imgAttributes);
delete imgAttributesWithoutSizes.sizes;
// <img>: one format and one size
if(entryCount === 1) {
return {
img: imgAttributesWithoutSizes
};
}
// Per the HTML specification sizes is required srcset is using the `w` unit
// https://html.spec.whatwg.org/dev/semantics.html#the-link-element:attr-link-imagesrcset-4
// Using the default "100vw" is okay
let missingSizesErrorMessage = `Missing \`sizes\` attribute on eleventy-img shortcode from: ${originalSrc}. Workarounds: 1. Use a single output width for this image 2. Use \`loading="lazy"\` (which uses sizes="auto" though browser support currently varies)`;
// <img srcset>: one format and multiple sizes
if(formats.length === 1) { // implied entryCount > 1
if(entryCount > 1 && !imgAttributes.sizes) {
// Use `sizes="auto"` when using `loading="lazy"` instead of throwing an error.
if(imgAttributes.loading === "lazy") {
imgAttributes.sizes = "auto";
} else {
throw new Error(missingSizesErrorMessage);
}
}
let imgAttributesCopy = Object.assign({}, imgAttributesWithoutSizes);
imgAttributesCopy.srcset = generateSrcset(lowsrc);
imgAttributesCopy.sizes = imgAttributes.sizes;
return {
img: imgAttributesCopy
};
}
let children = [];
values.filter(imageFormat => {
return imageFormat.length > 0 && (lowsrcFormat !== imageFormat[0].format);
}).forEach(imageFormat => {
if(imageFormat.length > 1 && !imgAttributes.sizes) {
if(imgAttributes.loading === "lazy") {
imgAttributes.sizes = "auto";
} else {
throw new Error(missingSizesErrorMessage);
}
}
let sourceAttrs = {
type: imageFormat[0].sourceType,
srcset: generateSrcset(imageFormat),
};
if(imgAttributes.sizes) {
sourceAttrs.sizes = imgAttributes.sizes;
}
children.push({
"source": sourceAttrs
});
});
/*
Add lowsrc as an img, for browsers that dont support picture or the formats provided in source
If we have more than one size, we can use srcset and sizes.
If the browser doesn't support those attributes, it should ignore them.
*/
let imgAttributesForPicture = Object.assign({}, imgAttributesWithoutSizes);
if (lowsrc.length > 1) {
if (!imgAttributes.sizes) {
// Per the HTML specification sizes is required srcset is using the `w` unit
// https://html.spec.whatwg.org/dev/semantics.html#the-link-element:attr-link-imagesrcset-4
// Using the default "100vw" is okay
throw new Error(missingSizesErrorMessage);
}
imgAttributesForPicture.srcset = generateSrcset(lowsrc);
imgAttributesForPicture.sizes = imgAttributes.sizes;
}
children.push({
"img": imgAttributesForPicture
});
return {
"picture": {
...pictureAttributes,
[CHILDREN_OBJECT_KEY]: children,
}
};
}
function mapObjectToHTML(tagName, attrs = {}) {
let attrHtml = Object.entries(attrs).map(entry => {
let [key, value] = entry;
if(key === CHILDREN_OBJECT_KEY) {
return false;
}
// Issue #82
if(key === "alt") {
return `${key}="${value ? escapeAttribute(value) : ""}"`;
}
return `${key}="${value}"`;
}).filter(keyPair => Boolean(keyPair)).join(" ");
return `<${tagName}${attrHtml ? ` ${attrHtml}` : ""}>`;
}
function generateHTML(metadata, attributes = {}, htmlOptionsOverride = {}) {
let htmlOptions = Object.assign({}, metadata?.eleventyImage?.htmlOptions, htmlOptionsOverride);
let isInline = htmlOptions.whitespaceMode !== "block";
let markup = [];
// htmlOptions.imgAttributes and htmlOptions.pictureAttributes are merged in generateObject
let obj = generateObject(metadata, attributes, {}, { htmlOptions });
for(let tag in obj) {
markup.push(mapObjectToHTML(tag, obj[tag]));
// <picture>
if(Array.isArray(obj[tag]?.[CHILDREN_OBJECT_KEY])) {
for(let child of obj[tag][CHILDREN_OBJECT_KEY]) {
let childTagName = Object.keys(child)[0];
markup.push((!isInline ? " " : "") + mapObjectToHTML(childTagName, child[childTagName]));
}
markup.push(`</${tag}>`);
}
}
return markup.join(!isInline ? "\n" : "");
}
module.exports = generateHTML;
module.exports.generateObject = generateObject;

121
node_modules/@11ty/eleventy-img/src/global-options.js generated vendored Normal file
View File

@ -0,0 +1,121 @@
const path = require("node:path");
const os = require("node:os");
const Util = require("./util.js");
const svgHook = require("./format-hooks/svg.js");
const DEFAULTS = {
widths: ["auto"],
formats: ["webp", "jpeg"], // "png", "svg", "avif"
formatFiltering: ["transparent", "animated"],
// Via https://github.com/11ty/eleventy-img/issues/258
concurrency: Math.min(Math.max(8, os.availableParallelism()), 16),
urlPath: "/img/",
outputDir: "img/",
// true to skip raster formats if SVG input is found
// "size" to skip raster formats if larger than SVG input
svgShortCircuit: false,
svgAllowUpscale: true,
svgCompressionSize: "", // "br" to report SVG `size` property in metadata as Brotli compressed
// overrideInputFormat: false, // internal, used to force svg output in statsSync et al
sharpOptions: {}, // options passed to the Sharp constructor
sharpWebpOptions: {}, // options passed to the Sharp webp output method
sharpPngOptions: {}, // options passed to the Sharp png output method
sharpJpegOptions: {}, // options passed to the Sharp jpeg output method
sharpAvifOptions: {}, // options passed to the Sharp avif output method
formatHooks: {
svg: svgHook,
},
cacheDuration: "1d", // deprecated, use cacheOptions.duration
// disk cache for remote assets
cacheOptions: {
// duration: "1d",
// directory: ".cache",
// removeUrlQueryParams: false,
// fetchOptions: {},
},
filenameFormat: null,
// urlFormat allows you to return a full URL to an image including the domain.
// Useful when youre using your own hosted image service (probably via .statsSync or .statsByDimensionsSync)
// Note: when you use this, metadata will not include .filename or .outputPath
urlFormat: null,
// If true, skips all image processing, just return stats. Doesnt read files, doesnt write files.
// Important to note that `dryRun: true` performs image processing and includes a buffer—this does not.
// Useful when used with `urlFormat` above.
// Better than .statsSync* functions, because this will use the in-memory cache and de-dupe requests. Those will not.
statsOnly: false,
remoteImageMetadata: {}, // For `statsOnly` remote images, this needs to be populated with { width, height, format? }
useCache: true, // in-memory and disk cache
dryRun: false, // Also returns a buffer instance in the return object. Doesnt write anything to the file system
hashLength: 10, // Truncates the hash to this length
fixOrientation: false, // always rotate images to ensure correct orientation
// When the original width is smaller than the desired output width, this is the minimum size difference
// between the next smallest image width that will generate one extra width in the output.
// e.g. when using `widths: [400, 800]`, the source image would need to be at least (400 * 1.25 =) 500px wide
// to generate two outputs (400px, 500px). If the source image is less than 500px, only one output will
// be generated (400px).
// Read more at https://github.com/11ty/eleventy-img/issues/184 and https://github.com/11ty/eleventy-img/pull/190
minimumThreshold: 1.25,
// During --serve mode in Eleventy, this will generate images on request instead of part of the build skipping
// writes to the file system and speeding up builds!
transformOnRequest: false,
// operate on Sharp instance manually.
transform: undefined,
// return HTML from generateHTML directly
returnType: "object", // or "html"
// Defaults used when generateHTML is called from a result set
htmlOptions: {
imgAttributes: {},
pictureAttributes: {},
whitespaceMode: "inline", // "block"
// the <img> will use the largest dimensions for width/height (when multiple output widths are specified)
// see https://github.com/11ty/eleventy-img/issues/63
fallback: "largest", // or "smallest"
},
// v5.0.0 Removed `extensions`, option to override output format with new file extension. It wasnt being used anywhere or documented.
// v6.0.0, removed `useCacheValidityInHash: true` see https://github.com/11ty/eleventy-img/issues/146#issuecomment-2555741376
};
function getGlobalOptions(eleventyConfig, options, via) {
let directories = eleventyConfig.directories;
let globalOptions = Object.assign({
packages: {
image: require("../"),
},
outputDir: path.join(directories.output, options.urlPath || ""),
failOnError: true,
}, options);
globalOptions.directories = directories;
globalOptions.generatedVia = via;
Util.addConfig(eleventyConfig, globalOptions);
return globalOptions;
}
module.exports = {
getGlobalOptions,
defaults: DEFAULTS,
};

View File

@ -0,0 +1,140 @@
const eleventyImage = require("../img.js");
const Util = require("./util.js");
const ATTR_PREFIX = "eleventy:";
const CHILDREN_OBJECT_KEY = "@children";
const ATTR = {
IGNORE: `${ATTR_PREFIX}ignore`,
WIDTHS: `${ATTR_PREFIX}widths`,
FORMATS: `${ATTR_PREFIX}formats`,
OUTPUT: `${ATTR_PREFIX}output`,
OPTIONAL: `${ATTR_PREFIX}optional`,
PICTURE: `${ATTR_PREFIX}pictureattr:`,
};
function getPictureAttributesFromImgNode(attrs = {}) {
let pictureAttrs = {};
for(let key in attrs) {
// <img eleventy:pictureattr:NAME="VALUE"> hoists to `<picture NAME="VALUE">
// e.g. <img eleventy:pictureattr:class="outer"> hoists to <picture class="outer">
if(key.startsWith(ATTR.PICTURE)) {
pictureAttrs[key.slice(ATTR.PICTURE.length)] = attrs[key];
}
}
return pictureAttrs;
}
function convertToPosthtmlNode(obj) {
// node.tag
// node.attrs
// node.content
let node = {};
let [key] = Object.keys(obj);
node.tag = key;
let children = obj[key]?.[CHILDREN_OBJECT_KEY];
let attributes = {};
for(let attrKey in obj[key]) {
if(attrKey !== CHILDREN_OBJECT_KEY) {
attributes[attrKey] = obj[key][attrKey];
}
}
node.attrs = attributes;
if(Array.isArray(children)) {
node.content = obj[key]?.[CHILDREN_OBJECT_KEY]
.filter(child => Boolean(child))
.map(child => {
return convertToPosthtmlNode(child);
});
}
return node;
}
function isValidSimpleWidthAttribute(width) {
// `width` must be a single integer (not comma separated). Dont use invalid HTML in width attribute. Use eleventy:widths if you want more complex support
return (""+width) == (""+parseInt(width, 10));
}
async function imageAttributesToPosthtmlNode(attributes, instanceOptions, globalPluginOptions) {
if(!attributes.src) {
throw new Error("Missing `src` attribute for `@11ty/eleventy-img`");
}
if(!globalPluginOptions) {
throw new Error("Missing global defaults for `@11ty/eleventy-img`: did you call addPlugin?");
}
if(!instanceOptions) {
instanceOptions = {};
}
// overrides global widths
if(attributes.width && isValidSimpleWidthAttribute(attributes.width)) {
// Support `width` but only single value
instanceOptions.widths = [ parseInt(attributes.width, 10) ];
} else if(attributes[ATTR.WIDTHS] && typeof attributes[ATTR.WIDTHS] === "string") {
instanceOptions.widths = attributes[ATTR.WIDTHS].split(",").map(entry => parseInt(entry, 10));
}
if(attributes[ATTR.FORMATS] && typeof attributes[ATTR.FORMATS] === "string") {
instanceOptions.formats = attributes[ATTR.FORMATS].split(",");
}
let options = Object.assign({}, globalPluginOptions, instanceOptions);
Util.addConfig(globalPluginOptions.eleventyConfig, options);
let metadata = await eleventyImage(attributes.src, options);
let pictureAttributes = getPictureAttributesFromImgNode(attributes);
cleanAttrs(attributes);
// You bet we throw an error on missing alt in `imageAttributes` (alt="" works okay)
let obj = await eleventyImage.generateObject(metadata, attributes, pictureAttributes, options);
return convertToPosthtmlNode(obj);
}
function cleanAttrs(attrs = {}) {
for(let key in attrs) {
if(key.startsWith(ATTR_PREFIX)) {
delete attrs?.[key];
}
}
}
function cleanTag(node) {
// Delete all prefixed attributes
cleanAttrs(node?.attrs);
}
function isIgnored(node) {
return node?.attrs && node?.attrs?.[ATTR.IGNORE] !== undefined;
}
function isOptional(node, comparisonValue) {
let attrValue = node?.attrs && node?.attrs?.[ATTR.OPTIONAL];
if(attrValue !== undefined) {
// if comparisonValue is not specified, return true
if(comparisonValue === undefined) {
return true;
}
return attrValue === comparisonValue;
}
return false;
}
function getOutputDirectory(node) {
return node?.attrs?.[ATTR.OUTPUT];
}
module.exports = {
imageAttributesToPosthtmlNode,
cleanTag,
isIgnored,
isOptional,
getOutputDirectory,
};

30
node_modules/@11ty/eleventy-img/src/image-path.js generated vendored Normal file
View File

@ -0,0 +1,30 @@
const path = require("node:path");
class ImagePath {
static filenameFormat(id, src, width, format) { // and options
if (width) {
return `${id}-${width}.${format}`;
}
return `${id}.${format}`;
}
static getFilename(id, src, width, format, options = {}) {
if (typeof options.filenameFormat === "function") {
let filename = options.filenameFormat(id, src, width, format, options);
// if options.filenameFormat returns falsy, use fallback filename
if(filename) {
return filename;
}
}
return ImagePath.filenameFormat(id, src, width, format, options);
}
static convertFilePathToUrl(dir, filename) {
let src = path.join(dir, filename);
return src.split(path.sep).join("/");
}
}
module.exports = ImagePath;

930
node_modules/@11ty/eleventy-img/src/image.js generated vendored Normal file
View File

@ -0,0 +1,930 @@
const fs = require("node:fs");
const fsp = fs.promises;
const path = require("node:path");
const getImageSize = require("image-size");
const debugUtil = require("debug");
const { createHashSync } = require("@11ty/eleventy-utils");
const { Fetch } = require("@11ty/eleventy-fetch");
const sharp = require("./adapters/sharp.js");
const brotliSize = require("./adapters/brotli-size.js");
const Util = require("./util.js");
const ImagePath = require("./image-path.js");
const generateHTML = require("./generate-html.js");
const GLOBAL_OPTIONS = require("./global-options.js").defaults;
const { existsCache, memCache, diskCache } = require("./caches.js");
const debug = debugUtil("Eleventy:Image");
const debugAssets = debugUtil("Eleventy:Assets");
const MIME_TYPES = {
"jpeg": "image/jpeg",
"webp": "image/webp",
"png": "image/png",
"svg": "image/svg+xml",
"avif": "image/avif",
"gif": "image/gif",
};
const FORMAT_ALIASES = {
"jpg": "jpeg",
// if youre working from a mime type input, lets alias it back to svg
"svg+xml": "svg",
};
const ANIMATED_TYPES = [
"webp",
"gif",
];
const TRANSPARENCY_TYPES = [
"avif",
"png",
"webp",
"gif",
"svg",
];
const MINIMUM_TRANSPARENCY_TYPES = [
"png",
"gif",
"svg",
];
class Image {
#input;
#contents = {};
#queue;
#queuePromise;
#buildLogger;
#computedHash;
#directoryManager;
constructor(src, options = {}) {
if(!src) {
throw new Error("`src` is a required argument to the eleventy-img utility (can be a String file path, String URL, or Buffer).");
}
this.src = src;
this.isRemoteUrl = typeof src === "string" && Util.isRemoteUrl(src);
this.rawOptions = options;
this.options = Object.assign({}, GLOBAL_OPTIONS, options);
// Compatible with eleventy-dev-server and Eleventy 3.0.0-alpha.7+ in serve mode.
if(this.options.transformOnRequest && !this.options.urlFormat) {
this.options.urlFormat = function({ src, width, format }/*, imageOptions*/, options) {
return `/.11ty/image/?src=${encodeURIComponent(src)}&width=${width}&format=${format}${options.generatedVia ? `&via=${options.generatedVia}` : ""}`;
};
this.options.statsOnly = true;
}
if(this.isRemoteUrl) {
this.cacheOptions = Object.assign({
type: "buffer",
// deprecated in Eleventy Image, but we already prefer this.cacheOptions.duration automatically
duration: this.options.cacheDuration,
// Issue #117: re-use eleventy-img dryRun option value for eleventy-fetch dryRun
dryRun: this.options.dryRun,
}, this.options.cacheOptions);
// v6.0.0 this now inherits eleventy-fetch option defaults
this.assetCache = Fetch(src, this.cacheOptions);
}
}
setQueue(queue) {
this.#queue = queue;
}
setBuildLogger(buildLogger) {
this.#buildLogger = buildLogger;
}
setDirectoryManager(manager) {
this.#directoryManager = manager;
}
get directoryManager() {
if(!this.#directoryManager) {
throw new Error("Missing #directoryManager");
}
return this.#directoryManager;
}
get buildLogger() {
if(!this.#buildLogger) {
throw new Error("Missing #buildLogger. Call `setBuildLogger`");
}
return this.#buildLogger;
}
// In memory cache is up front, handles promise de-duping from input (this does not use getHash)
// Note: output cache is also in play below (uses getHash)
getInMemoryCacheKey() {
let opts = Util.getSortedObject(this.options);
opts.__originalSrc = this.src;
if(this.isRemoteUrl) {
opts.sourceUrl = this.src; // the source url
} else if(Buffer.isBuffer(this.src)) {
opts.sourceUrl = this.src.toString();
opts.__originalSize = this.src.length;
} else {
// Important: do not cache this
opts.__originalSize = fs.statSync(this.src).size;
}
return JSON.stringify(opts, function(key, value) {
// allows `transform` functions to be truthy for in-memory key
if (typeof value === "function") {
return "<fn>" + (value.name || "");
}
return value;
});
}
getFileContents(overrideLocalFilePath) {
if(!overrideLocalFilePath && this.isRemoteUrl) {
return false;
}
let src = overrideLocalFilePath || this.src;
if(!this.#contents[src]) {
// perf: check to make sure its not a string first
if(typeof src !== "string" && Buffer.isBuffer(src)) {
this.#contents[src] = src;
} else {
debugAssets("[11ty/eleventy-img] Reading %o", src);
this.#contents[src] = fs.readFileSync(src);
}
}
// Always <Buffer>
return this.#contents[src];
}
static getValidWidths(originalWidth, widths = [], allowUpscale = false, minimumThreshold = 1) {
// replace any falsy values with the original width
let valid = widths.map(width => !width || width === 'auto' ? originalWidth : width);
// Convert strings to numbers, "400" (floats are not allowed in sharp)
valid = valid.map(width => parseInt(width, 10));
// Replace any larger-than-original widths with the original width if upscaling is not allowed.
// This ensures that if a larger width has been requested, we're at least providing the closest
// non-upscaled image that we can.
if (!allowUpscale) {
let lastWidthWasBigEnough = true; // first one is always valid
valid = valid.sort((a, b) => a - b).map(width => {
if(width > originalWidth) {
if(lastWidthWasBigEnough) {
return originalWidth;
}
return -1;
}
lastWidthWasBigEnough = originalWidth > Math.floor(width * minimumThreshold);
return width;
}).filter(width => width > 0);
}
// Remove duplicates (e.g., if null happens to coincide with an explicit width
// or a user passes in multiple duplicate values, or multiple larger-than-original
// widths have resulted in the original width being included multiple times)
valid = [...new Set(valid)];
// sort ascending
return valid.sort((a, b) => a - b);
}
static getFormatsArray(formats, autoFormat, svgShortCircuit, isAnimated, hasTransparency) {
if(formats && formats.length) {
if(typeof formats === "string") {
formats = formats.split(",");
}
formats = formats.map(format => {
if(autoFormat) {
if((!format || format === "auto")) {
format = autoFormat;
}
}
if(FORMAT_ALIASES[format]) {
return FORMAT_ALIASES[format];
}
return format;
});
if(svgShortCircuit !== "size") {
// svg must come first for possible short circuiting
formats.sort((a, b) => {
if(a === "svg") {
return -1;
} else if(b === "svg") {
return 1;
}
return 0;
});
}
if(isAnimated) {
let validAnimatedFormats = formats.filter(f => ANIMATED_TYPES.includes(f));
// override formats if a valid animated format is found, otherwise leave as-is
if(validAnimatedFormats.length > 0) {
debug("Filtering non-animated formats from output: from %o to %o", formats, validAnimatedFormats);
formats = validAnimatedFormats;
} else {
debug("No animated output formats found for animated image, using original formats (may be a static image): %o", formats);
}
}
if(hasTransparency) {
let minimumValidTransparencyFormats = formats.filter(f => MINIMUM_TRANSPARENCY_TYPES.includes(f));
// override formats if a valid animated format is found, otherwise leave as-is
if(minimumValidTransparencyFormats.length > 0) {
let validTransparencyFormats = formats.filter(f => TRANSPARENCY_TYPES.includes(f));
debug("Filtering non-transparency-friendly formats from output: from %o to %o", formats, validTransparencyFormats);
formats = validTransparencyFormats;
} else {
debug("At least one transparency-friendly output format of %o must be included if the source image has an alpha channel, skipping formatFiltering and using original formats: %o", MINIMUM_TRANSPARENCY_TYPES, formats);
}
}
// Remove duplicates (e.g., if null happens to coincide with an explicit format
// or a user passes in multiple duplicate values)
formats = [...new Set(formats)];
return formats;
}
return [];
}
#transformRawFiles(files = []) {
let byType = {};
for(let file of files) {
if(!byType[file.format]) {
byType[file.format] = [];
}
byType[file.format].push(file);
}
for(let type in byType) {
// sort by width, ascending (for `srcset`)
byType[type].sort((a, b) => {
return a.width - b.width;
});
}
let filterLargeRasterImages = this.options.svgShortCircuit === "size";
let svgEntry = byType.svg;
let svgSize = svgEntry && svgEntry.length && svgEntry[0].size;
if(filterLargeRasterImages && svgSize) {
for(let type of Object.keys(byType)) {
if(type === "svg") {
continue;
}
let svgAdded = false;
let originalFormatKept = false;
byType[type] = byType[type].map(entry => {
if(entry.size > svgSize) {
if(!svgAdded) {
svgAdded = true;
// need at least one raster smaller than SVG to do this trick
if(originalFormatKept) {
return svgEntry[0];
}
// all rasters are bigger
return false;
}
return false;
}
originalFormatKept = true;
return entry;
}).filter(entry => entry);
}
}
return byType;
}
#finalizeResults(results = {}) {
// used when results are passed to generate HTML, we maintain some internal metadata about the options used.
let imgAttributes = this.options.htmlOptions?.imgAttributes || {};
imgAttributes.src = this.src;
Object.defineProperty(results, "eleventyImage", {
enumerable: false,
writable: false,
value: {
htmlOptions: {
whitespaceMode: this.options.htmlOptions?.whitespaceMode,
imgAttributes,
pictureAttributes: this.options.htmlOptions?.pictureAttributes,
fallback: this.options.htmlOptions?.fallback,
},
}
});
// renamed `return` to `returnType` to match Fetch API in v6.0.0-beta.3
if(this.options.returnType === "html" || this.options.return === "html") {
return generateHTML(results);
}
return results;
}
getSharpOptionsForFormat(format) {
if(format === "webp") {
return this.options.sharpWebpOptions;
} else if(format === "jpeg") {
return this.options.sharpJpegOptions;
} else if(format === "png") {
return this.options.sharpPngOptions;
} else if(format === "avif") {
return this.options.sharpAvifOptions;
}
return {};
}
async getInput() {
// internal cache
if(!this.#input) {
if(this.isRemoteUrl) {
// fetch remote image Buffer
this.#input = this.assetCache.queue();
} else {
// not actually a promise, this is sync
this.#input = this.getFileContents();
}
}
return this.#input;
}
getHash() {
if (this.#computedHash) {
return this.#computedHash;
}
// debug("Creating hash for %o", this.src);
let hashContents = [];
if(existsCache.exists(this.src)) {
let fileContents = this.getFileContents();
// If the file starts with whitespace or the '<' character, it might be SVG.
// Otherwise, skip the expensive buffer.toString() call
// (no point in unicode encoding a binary file)
let fileContentsPrefix = fileContents?.slice(0, 1)?.toString()?.trim();
if (!fileContentsPrefix || fileContentsPrefix[0] == "<") {
// remove all newlines for hashing for better cross-OS hash compatibility (Issue #122)
let fileContentsStr = fileContents.toString();
let firstFour = fileContentsStr.trim().slice(0, 5);
if(firstFour === "<svg " || firstFour === "<?xml") {
fileContents = fileContentsStr.replace(/\r|\n/g, '');
}
}
hashContents.push(fileContents);
} else {
// probably a remote URL
hashContents.push(this.src);
// `useCacheValidityInHash` was removed in v6.0.0, but well keep this as part of the hash to maintain consistent hashes across versions
if(this.isRemoteUrl && this.assetCache && this.cacheOptions) {
hashContents.push(`ValidCache:true`);
}
}
// We ignore all keys not relevant to the file processing/output (including `widths`, which is a suffix added to the filename)
// e.g. `widths: [300]` and `widths: [300, 600]`, with all else being equal the 300px output of each should have the same hash
let keysToKeep = [
"sharpOptions",
"sharpWebpOptions",
"sharpPngOptions",
"sharpJpegOptions",
"sharpAvifOptions"
].sort();
let hashObject = {};
// The code currently assumes are keysToKeep are Object literals (see Util.getSortedObject)
for(let key of keysToKeep) {
if(this.options[key]) {
hashObject[key] = Util.getSortedObject(this.options[key]);
}
}
hashContents.push(JSON.stringify(hashObject));
let base64hash = createHashSync(...hashContents);
let truncated = base64hash.substring(0, this.options.hashLength);
this.#computedHash = truncated;
return truncated;
}
getStat(outputFormat, width, height) {
let url;
let outputFilename;
if(this.options.urlFormat && typeof this.options.urlFormat === "function") {
let hash;
if(!this.options.statsOnly) {
hash = this.getHash();
}
url = this.options.urlFormat({
hash,
src: this.src,
width,
format: outputFormat,
}, this.options);
} else {
let hash = this.getHash();
outputFilename = ImagePath.getFilename(hash, this.src, width, outputFormat, this.options);
if(Util.isFullUrl(this.options.urlPath)) {
url = new URL(outputFilename, this.options.urlPath).toString();
} else {
url = ImagePath.convertFilePathToUrl(this.options.urlPath, outputFilename);
}
}
let statEntry = {
format: outputFormat,
width: width,
height: height,
url: url,
sourceType: MIME_TYPES[outputFormat],
srcset: `${url} ${width}w`,
// Not available in stats* functions below
// size // only after processing
};
if(outputFilename) {
statEntry.filename = outputFilename; // optional
statEntry.outputPath = path.join(this.options.outputDir, outputFilename); // optional
}
return statEntry;
}
// https://jdhao.github.io/2019/07/31/image_rotation_exif_info/
// Orientations 5 to 8 mean image is rotated ±90º (width/height are flipped)
needsRotation(orientation) {
// Sharp's metadata API exposes undefined EXIF orientations >8 as 1 (normal) but check anyways
return orientation >= 5 && orientation <= 8;
}
isAnimated(metadata) {
// sharp options have animated image support enabled
if(!this.options?.sharpOptions?.animated) {
return false;
}
let isAnimationFriendlyFormat = ANIMATED_TYPES.includes(metadata.format);
if(!isAnimationFriendlyFormat) {
return false;
}
if(metadata?.pages) {
// input has multiple pages: https://sharp.pixelplumbing.com/api-input#metadata
// this is *unknown* when not called from `resize` (limited metadata available)
return metadata?.pages > 1;
}
// Best guess
return isAnimationFriendlyFormat;
}
getEntryFormat(metadata) {
return metadata.format || this.options.overrideInputFormat;
}
// metadata so far: width, height, format
// src is used to calculate the output file names
getFullStats(metadata) {
let results = [];
let isImageAnimated = this.isAnimated(metadata) && Array.isArray(this.options.formatFiltering) && this.options.formatFiltering.includes("animated");
let hasAlpha = metadata.hasAlpha && Array.isArray(this.options.formatFiltering) && this.options.formatFiltering.includes("transparent");
let entryFormat = this.getEntryFormat(metadata);
let outputFormats = Image.getFormatsArray(this.options.formats, entryFormat, this.options.svgShortCircuit, isImageAnimated, hasAlpha);
if (this.needsRotation(metadata.orientation)) {
[metadata.height, metadata.width] = [metadata.width, metadata.height];
}
if(metadata.pageHeight) {
// When the { animated: true } option is provided to sharp, animated
// image formats like gifs or webp will have an inaccurate `height` value
// in their metadata which is actually the height of every single frame added together.
// In these cases, the metadata will contain an additional `pageHeight` property which
// is the height that the image should be displayed at.
metadata.height = metadata.pageHeight;
}
for(let outputFormat of outputFormats) {
if(!outputFormat || outputFormat === "auto") {
throw new Error("When using statsSync or statsByDimensionsSync, `formats: [null | 'auto']` to use the native image format is not supported.");
}
if(outputFormat === "svg") {
if(entryFormat === "svg") {
let svgStats = this.getStat("svg", metadata.width, metadata.height);
// SVG metadata.size is only available with Buffer input (remote urls)
if(metadata.size) {
// Note this is unfair for comparison with raster formats because its uncompressed (no GZIP, etc)
svgStats.size = metadata.size;
}
results.push(svgStats);
if(this.options.svgShortCircuit === true) {
break;
} else {
continue;
}
} else {
debug("Skipping SVG output for %o: received raster input.", this.src);
continue;
}
} else { // not outputting SVG (might still be SVG input though!)
let widths = Image.getValidWidths(metadata.width, this.options.widths, metadata.format === "svg" && this.options.svgAllowUpscale, this.options.minimumThreshold);
for(let width of widths) {
let height = Image.getAspectRatioHeight(metadata, width);
results.push(this.getStat(outputFormat, width, height));
}
}
}
return this.#transformRawFiles(results);
}
static getDimensionsFromSharp(sharpInstance, stat) {
let dims = {};
if(sharpInstance.options.width > -1) {
dims.width = sharpInstance.options.width;
dims.resized = true;
}
if(sharpInstance.options.height > -1) {
dims.height = sharpInstance.options.height;
dims.resized = true;
}
if(dims.width || dims.height) {
if(!dims.width) {
dims.width = Image.getAspectRatioWidth(stat, dims.height);
}
if(!dims.height) {
dims.height = Image.getAspectRatioHeight(stat, dims.width);
}
}
return dims;
}
static getAspectRatioWidth(originalDimensions, newHeight) {
return Math.floor(newHeight * originalDimensions.width / originalDimensions.height);
}
static getAspectRatioHeight(originalDimensions, newWidth) {
// Warning: if this is a guess via statsByDimensionsSync and that guess is wrong
// The aspect ratio will be wrong and any height/widths returned will be wrong!
return Math.floor(newWidth * originalDimensions.height / originalDimensions.width);
}
getOutputSize(contents, filePath) {
if(contents) {
if(this.options.svgCompressionSize === "br") {
return brotliSize(contents);
}
if("length" in contents) {
return contents.length;
}
}
// fallback to looking on local file system
if(!filePath) {
throw new Error("`filePath` expected.");
}
return fs.statSync(filePath).size;
}
isOutputCached(targetFile, sourceInput) {
if(!this.options.useCache) {
return false;
}
// last cache was a miss, so we must write to disk
if(this.assetCache && !this.assetCache.wasLastFetchCacheHit()) {
return false;
}
if(!diskCache.isCached(targetFile, sourceInput, !Util.isRequested(this.options.generatedVia))) {
return false;
}
return true;
}
// src should be a file path to an image or a buffer
async resize(input) {
let sharpInputImage = sharp(input, Object.assign({
// Deprecated by sharp, use `failOn` option instead
// https://github.com/lovell/sharp/blob/1533bf995acda779313fc178d2b9d46791349961/lib/index.d.ts#L915
failOnError: false,
}, this.options.sharpOptions));
// Must find the image format from the metadata
// File extensions lie or may not be present in the src url!
let sharpMetadata = await sharpInputImage.metadata();
let outputFilePromises = [];
let fullStats = this.getFullStats(sharpMetadata);
for(let outputFormat in fullStats) {
for(let stat of fullStats[outputFormat]) {
if(this.isOutputCached(stat.outputPath, input)) {
// Cached images already exist in output
let outputFileContents;
if(this.options.dryRun || outputFormat === "svg" && this.options.svgCompressionSize === "br") {
outputFileContents = this.getFileContents(stat.outputPath);
}
if(this.options.dryRun) {
stat.buffer = outputFileContents;
}
stat.size = this.getOutputSize(outputFileContents, stat.outputPath);
outputFilePromises.push(Promise.resolve(stat));
continue;
}
let sharpInstance = sharpInputImage.clone();
let transform = this.options.transform;
let isTransformResize = false;
if(transform) {
if(typeof transform !== "function") {
throw new Error("Expected `function` type in `transform` option. Received: " + transform);
}
await transform(sharpInstance);
// Resized in a transform (maybe for a crop)
let dims = Image.getDimensionsFromSharp(sharpInstance, stat);
if(dims.resized) {
isTransformResize = true;
// Overwrite current `stat` object with new sizes and file names
stat = this.getStat(stat.format, dims.width, dims.height);
}
}
// https://github.com/11ty/eleventy-img/issues/244
sharpInstance.keepIccProfile();
// Output images do not include orientation metadata (https://github.com/11ty/eleventy-img/issues/52)
// Use sharp.rotate to bake orientation into the image (https://github.com/lovell/sharp/blob/v0.32.6/docs/api-operation.md#rotate):
// > If no angle is provided, it is determined from the EXIF data. Mirroring is supported and may infer the use of a flip operation.
// > The use of rotate without an angle will remove the EXIF Orientation tag, if any.
if(this.options.fixOrientation || this.needsRotation(sharpMetadata.orientation)) {
sharpInstance.rotate();
}
if(!isTransformResize) {
if(stat.width < sharpMetadata.width || (this.options.svgAllowUpscale && sharpMetadata.format === "svg")) {
let resizeOptions = {
width: stat.width
};
if(sharpMetadata.format !== "svg" || !this.options.svgAllowUpscale) {
resizeOptions.withoutEnlargement = true;
}
sharpInstance.resize(resizeOptions);
}
}
// Format hooks take priority over Sharp processing.
// format hooks are only used for SVG out of the box
if(this.options.formatHooks && this.options.formatHooks[outputFormat]) {
let hookResult = await this.options.formatHooks[outputFormat].call(stat, sharpInstance);
if(hookResult) {
stat.size = this.getOutputSize(hookResult);
if(this.options.dryRun) {
stat.buffer = Buffer.from(hookResult);
outputFilePromises.push(Promise.resolve(stat));
} else {
this.directoryManager.createFromFile(stat.outputPath);
debugAssets("[11ty/eleventy-img] Writing %o", stat.outputPath);
outputFilePromises.push(fsp.writeFile(stat.outputPath, hookResult).then(() => stat));
}
}
} else { // not a format hook
let sharpFormatOptions = this.getSharpOptionsForFormat(outputFormat);
let hasFormatOptions = Object.keys(sharpFormatOptions).length > 0;
if(hasFormatOptions || outputFormat && sharpMetadata.format !== outputFormat) {
// https://github.com/lovell/sharp/issues/3680
// Fix heic regression in sharp 0.33
if(outputFormat === "heic" && !sharpFormatOptions.compression) {
sharpFormatOptions.compression = "av1";
}
sharpInstance.toFormat(outputFormat, sharpFormatOptions);
}
if(!this.options.dryRun && stat.outputPath) {
// Should never write when dryRun is true
this.directoryManager.createFromFile(stat.outputPath);
debugAssets("[11ty/eleventy-img] Writing %o", stat.outputPath);
outputFilePromises.push(
sharpInstance.toFile(stat.outputPath)
.then(info => {
stat.size = info.size;
return stat;
})
);
} else {
outputFilePromises.push(sharpInstance.toBuffer({ resolveWithObject: true }).then(({ data, info }) => {
stat.buffer = data;
stat.size = info.size;
return stat;
}));
}
}
if(stat.outputPath) {
if(this.options.dryRun) {
debug( "Generated %o", stat.url );
} else {
debug( "Wrote %o", stat.outputPath );
}
}
}
}
return Promise.all(outputFilePromises).then(files => this.#finalizeResults(this.#transformRawFiles(files)));
}
async getStatsOnly() {
if(typeof this.src !== "string" || !this.options.statsOnly) {
return;
}
let input;
if(Util.isRemoteUrl(this.src)) {
if(this.rawOptions.remoteImageMetadata?.width && this.rawOptions.remoteImageMetadata?.height) {
return this.getFullStats({
width: this.rawOptions.remoteImageMetadata.width,
height: this.rawOptions.remoteImageMetadata.height,
format: this.rawOptions.remoteImageMetadata.format, // only required if you want to use the "auto" format
guess: true,
});
}
// Fetch remote image to operate on it
// `remoteImageMetadata` is no longer required for statsOnly on remote images
input = await this.getInput();
}
// Local images
try {
// Related to https://github.com/11ty/eleventy-img/issues/295
let { width, height, type } = getImageSize(input || this.src);
return this.getFullStats({
width,
height,
format: type // only required if you want to use the "auto" format
});
} catch(e) {
throw new Error(`Eleventy Image error (statsOnly): \`image-size\` on "${this.src}" failed. Original error: ${e.message}`);
}
}
// returns raw Promise
queue() {
if(!this.#queue) {
return Promise.reject(new Error("Missing #queue."));
}
if(this.#queuePromise) {
return this.#queuePromise;
}
debug("Processing %o (in-memory cache miss), options: %o", this.src, this.options);
this.#queuePromise = this.#queue.add(async () => {
try {
if(typeof this.src === "string" && this.options.statsOnly) {
return this.getStatsOnly();
}
this.buildLogger.log(`Processing ${this.buildLogger.getFriendlyImageSource(this.src)}`, this.options);
let input = await this.getInput();
return this.resize(input);
} catch(e) {
this.buildLogger.error(`Error: ${e.message} (via ${this.buildLogger.getFriendlyImageSource(this.src)})`, this.options);
if(this.options.failOnError) {
throw e;
}
}
});
return this.#queuePromise;
}
// Factory to return from cache if available
static create(src, options = {}) {
let img = new Image(src, options);
// use resolved options for this
if(!img.options.useCache) {
return img;
}
let key = img.getInMemoryCacheKey();
let cached = memCache.get(key, !options.transformOnRequest && !Util.isRequested(options.generatedVia));
if(cached) {
return cached;
}
memCache.add(key, img);
return img;
}
/* `statsSync` doesnt generate any files, but will tell you where
* the asynchronously generated files will end up! This is useful
* in synchronous-only template environments where you need the
* image URLs synchronously but cant rely on the files being in
* the correct location yet.
*
* `options.dryRun` is still asynchronous but also doesnt generate
* any files.
*/
statsSync() {
if(this.isRemoteUrl) {
throw new Error("`statsSync` is not supported with remote sources. Use `statsByDimensionsSync(src, width, height, options)` instead.");
}
let dimensions = getImageSize(this.src);
return this.getFullStats({
width: dimensions.width,
height: dimensions.height,
format: dimensions.type,
});
}
static statsSync(src, opts) {
if(typeof src === "string" && Util.isRemoteUrl(src)) {
throw new Error("`statsSync` is not supported with remote sources. Use `statsByDimensionsSync(src, width, height, options)` instead.");
}
let img = Image.create(src, opts);
return img.statsSync();
}
statsByDimensionsSync(width, height) {
let dimensions = {
width,
height,
guess: true
};
return this.getFullStats(dimensions);
}
static statsByDimensionsSync(src, width, height, opts) {
let img = Image.create(src, opts);
return img.statsByDimensionsSync(width, height);
}
}
module.exports = Image;

54
node_modules/@11ty/eleventy-img/src/memory-cache.js generated vendored Normal file
View File

@ -0,0 +1,54 @@
const debug = require("debug")("Eleventy:Image");
class MemoryCache {
constructor() {
this.cache = {};
this.hitCounter = 0;
this.missCounter = 0;
}
resetCount() {
this.hitCounter = 0;
this.missCounter = 0;
}
getCount() {
return [this.hitCounter, this.missCounter];
}
add(key, results) {
this.cache[key] = {
results
};
debug("Unique images processed: %o", this.size());
}
get(key, incrementCounts = false) {
if(this.cache[key]) {
if(incrementCounts) {
this.hitCounter++;
}
// debug("Images re-used (via in-memory cache): %o", this.hitCounter);
// may return promise
return this.cache[key].results;
}
if(incrementCounts) {
this.missCounter++;
}
return false;
}
has(key) {
return key in this.cache;
}
size() {
return Object.keys(this.cache).length;
}
}
module.exports = MemoryCache;

View File

@ -0,0 +1,105 @@
const fs = require("node:fs");
const { TemplatePath } = require("@11ty/eleventy-utils");
const eleventyImage = require("../img.js");
const setupLogger = eleventyImage.setupLogger;
const Util = require("./util.js");
const debug = require("debug")("Eleventy:Image");
function eleventyImageOnRequestDuringServePlugin(eleventyConfig, options = {}) {
try {
// Throw an error if the application is not using Eleventy 3.0.0-alpha.7 or newer (including prereleases).
eleventyConfig.versionCheck(">=3.0.0-alpha.7");
} catch(e) {
console.log( `[11ty/eleventy-img] Warning: your version of Eleventy is incompatible with the dynamic image rendering plugin (see \`eleventyImageOnRequestDuringServePlugin\`). Any dynamically rendered images will 404 (be missing) during --serve mode but will not affect the standard build output: ${e.message}` );
}
setupLogger(eleventyConfig, {});
// Eleventy 3.0 or newer only.
eleventyConfig.setServerOptions({
onRequest: {
// TODO work with dev-servers option for `injectedScriptsFolder`
"/.11ty/image/": async function({ url }) {
// src could be file path or full url
let src = url.searchParams.get("src");
let imageFormat = url.searchParams.get("format");
let width = parseInt(url.searchParams.get("width"), 10);
let via = url.searchParams.get("via");
let defaultOptions;
if(via === "webc") {
defaultOptions = eleventyConfig.getFilter("__private_eleventyImageConfigurationOptions")();
} else if(via === "transform") {
defaultOptions = eleventyConfig.getFilter("__private_eleventyImageTransformConfigurationOptions")();
}
// if using this plugin directly (not via webc or transform), global default options will need to be passed in to the `addPlugin` call directly
// Prefer options passed to this plugin, fallback to Transform plugin or WebC options if the image source was generated via those options.
let opts = Object.assign({}, defaultOptions, options, {
widths: [width || "auto"],
formats: [imageFormat || "auto"],
dryRun: true,
cacheOptions: {
// We *do* want to write files to .cache for re-use here.
dryRun: false
},
transformOnRequest: false, // use the built images so we dont go in a loop
generatedVia: Util.KEYS.requested,
});
Util.addConfig(eleventyConfig, opts);
debug( `%o transformed on request to %o at %o width.`, src, imageFormat, width );
try {
if(!Util.isFullUrl(src)) {
// Image path on file system must be in working directory
src = TemplatePath.absolutePath(".", src);
if(!fs.existsSync(src) || !src.startsWith(TemplatePath.absolutePath("."))) {
throw new Error(`Invalid path: ${src}`);
}
}
let stats = await eleventyImage(src, opts);
let format = Object.keys(stats).pop();
let stat = stats[format][0];
if(!stat) {
throw new Error("Invalid image format.");
}
if(!stat.buffer) {
throw new Error("Could not find `buffer` property for image.");
}
return {
headers: {
// TODO Set cache headers to match eleventy-fetch cache options (though remote fetchs are still written to .cache)
"Content-Type": stat.sourceType,
},
body: stat.buffer,
};
} catch (error) {
debug("Error attempting to transform %o: %O", src, error);
return {
status: 500,
headers: {
"Content-Type": "image/svg+xml",
"x-error-message": error.message
},
body: `<svg version="1.1" xmlns="http://www.w3.org/2000/svg" width="${width}" height="${width}" x="0" y="0" viewBox="0 0 1569.4 2186" xml:space="preserve" aria-hidden="true" focusable="false"><style>.st0{fill:#bbb;stroke:#bbb;stroke-width:28;stroke-miterlimit:10}</style><g><path class="st0" d="M562.2 1410.1c-9 0-13.5-12-13.5-36.1V778.9c0-11.5-2.3-16.9-7-16.2-28.4 7.2-42.7 10.8-43.1 10.8-7.9.7-11.8-7.2-11.8-23.7v-51.7c0-14.3 4.3-22.4 12.9-24.2l142.2-36.6c1.1-.3 2.7-.5 4.8-.5 7.9 0 11.8 8.4 11.8 25.3v712c0 24.1-4.7 36.1-14 36.1l-82.3-.1zM930.5 1411.2c-14.4 0-26.8-1-37.4-3-10.6-2-21.6-6.5-33.1-13.5s-20.9-16.6-28.3-28.8-13.4-29.3-18-51.2-7-47.9-7-78.1V960.4c0-7.2-2-10.8-5.9-10.8h-33.4c-9 0-13.5-8.6-13.5-25.8v-29.1c0-17.6 4.5-26.4 13.5-26.4h33.4c3.9 0 5.9-4.8 5.9-14.5l9.7-209.5c1.1-19 5.7-28.5 14-28.5h53.9c9 0 13.5 9.5 13.5 28.5v209.5c0 9.7 2.1 14.5 6.5 14.5H973c9 0 13.5 8.8 13.5 26.4v29.1c0 17.2-4.5 25.8-13.5 25.8h-68.9c-2.5 0-4.2.6-5.1 1.9-.9 1.2-1.3 4.2-1.3 8.9v277.9c0 20.8 1.3 38.2 4 52s6.6 24 11.8 30.4 10.4 10.8 15.6 12.9c5.2 2.2 11.6 3.2 19.1 3.2h38.2c9.7 0 14.5 6.7 14.5 19.9v32.3c0 14.7-5.2 22.1-15.6 22.1l-54.8.1zM1137.2 1475.8c8.2 0 15.4-6.7 21.5-20.2s9.2-32.6 9.2-57.4c0-5.8-3.6-25.7-10.8-59.8l-105.6-438.9c-.7-5-1.1-9-1.1-11.9 0-12.9 2.7-19.4 8.1-19.4h65.2c5 0 9.1 1.7 12.4 5.1s5.8 10.3 7.5 20.7l70 370.5c1.4 4.3 2.3 6.5 2.7 6.5 1.4 0 2.2-2 2.2-5.9l54.9-369.5c1.4-10.8 3.7-18 6.7-21.8s6.9-5.7 11.6-5.7h45.2c6.1 0 9.2 7 9.2 21 0 3.2-.4 7.4-1.1 12.4l-95.9 499.3c-7.5 41.3-15.8 72.9-24.8 94.8s-19 36.8-30.2 44.7c-11.1 7.9-25.8 12-44.2 12.4h-5.4c-29.1 0-48.8-7.7-59.2-23.2-2.9-3.2-4.3-11.5-4.3-24.8 0-26.6 4.3-39.9 12.9-39.9.7 0 7.2 1.8 19.4 5.4 12.4 3.8 20.3 5.6 23.9 5.6z"/><g><path class="st0" d="M291.2 1411.1c-9 0-13.5-12-13.5-36.1V779.9c0-11.5-2.3-16.9-7-16.2-28.4 7.2-42.7 10.8-43.1 10.8-7.9.7-11.8-7.2-11.8-23.7v-51.7c0-14.3 4.3-22.4 12.9-24.2L371 638.2c1.1-.3 2.7-.5 4.8-.5 7.9 0 11.8 8.4 11.8 25.3v712c0 24.1-4.7 36.1-14 36.1h-82.4z"/></g></g></svg>`,
};
}
}
}
});
}
module.exports = {
eleventyImageOnRequestDuringServePlugin,
};

210
node_modules/@11ty/eleventy-img/src/transform-plugin.js generated vendored Normal file
View File

@ -0,0 +1,210 @@
const path = require("node:path");
const Util = require("./util.js");
const { imageAttributesToPosthtmlNode, getOutputDirectory, cleanTag, isIgnored, isOptional } = require("./image-attrs-to-posthtml-node.js");
const { getGlobalOptions } = require("./global-options.js");
const { eleventyImageOnRequestDuringServePlugin } = require("./on-request-during-serve-plugin.js");
const PLACEHOLDER_DATA_URI = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNgYAAAAAMAASsJTYQAAAAASUVORK5CYII=";
const ATTRS = {
ORIGINAL_SOURCE: "eleventy:internal_original_src",
};
function getSrcAttributeValue(sourceNode/*, rootTargetNode*/) {
// Debatable TODO: use rootTargetNode (if `picture`) to retrieve a potentially higher quality source from <source srcset>
return sourceNode.attrs?.src;
}
function assignAttributes(rootTargetNode, newNode) {
// only copy attributes if old and new tag name are the same (picture => picture, img => img)
if(rootTargetNode.tag !== newNode.tag) {
delete rootTargetNode.attrs;
}
if(!rootTargetNode.attrs) {
rootTargetNode.attrs = {};
}
// Copy all new attributes to target
if(newNode.attrs) {
Object.assign(rootTargetNode.attrs, newNode.attrs);
}
}
function getOutputLocations(originalSource, outputDirectoryFromAttribute, pageContext, options) {
let projectOutputDirectory = options.directories.output;
if(outputDirectoryFromAttribute) {
if(path.isAbsolute(outputDirectoryFromAttribute)) {
return {
outputDir: path.join(projectOutputDirectory, outputDirectoryFromAttribute),
urlPath: outputDirectoryFromAttribute,
};
}
return {
outputDir: path.join(projectOutputDirectory, pageContext.url, outputDirectoryFromAttribute),
urlPath: path.join(pageContext.url, outputDirectoryFromAttribute),
};
}
if(options.urlPath) {
// do nothing, user has specified directories in the plugin options.
return {};
}
if(path.isAbsolute(originalSource)) {
// if the path is an absolute one (relative to the content directory) write to a global output directory to avoid duplicate writes for identical source images.
return {
outputDir: path.join(projectOutputDirectory, "/img/"),
urlPath: "/img/",
};
}
// If original source is a relative one, this colocates images to the template output.
let dir = path.dirname(pageContext.outputPath);
// filename is included in url: ./dir/post.html => /dir/post.html
if(pageContext.outputPath.endsWith(pageContext.url)) {
// remove file name
let split = pageContext.url.split("/");
split[split.length - 1] = "";
return {
outputDir: dir,
urlPath: split.join("/"),
};
}
// filename is not included in url: ./dir/post/index.html => /dir/post/
return {
outputDir: dir,
urlPath: pageContext.url,
};
}
function transformTag(context, sourceNode, rootTargetNode, opts) {
let originalSource = getSrcAttributeValue(sourceNode, rootTargetNode);
if(!originalSource) {
return sourceNode;
}
let { inputPath } = context.page;
sourceNode.attrs.src = Util.normalizeImageSource({
input: opts.directories.input,
inputPath,
}, originalSource, {
isViaHtml: true, // this reference came from HTML, so we can decode the file name
});
if(sourceNode.attrs.src !== originalSource) {
sourceNode.attrs[ATTRS.ORIGINAL_SOURCE] = originalSource;
}
let outputDirectoryFromAttribute = getOutputDirectory(sourceNode);
let instanceOptions = getOutputLocations(originalSource, outputDirectoryFromAttribute, context.page, opts);
// returns promise
return imageAttributesToPosthtmlNode(sourceNode.attrs, instanceOptions, opts).then(newNode => {
// node.tag
// node.attrs
// node.content
assignAttributes(rootTargetNode, newNode);
rootTargetNode.tag = newNode.tag;
rootTargetNode.content = newNode.content;
}, (error) => {
if(isOptional(sourceNode) || !opts.failOnError) {
if(isOptional(sourceNode, "keep")) {
// replace with the original source value, no image transformation is taking place
if(sourceNode.attrs[ATTRS.ORIGINAL_SOURCE]) {
sourceNode.attrs.src = sourceNode.attrs[ATTRS.ORIGINAL_SOURCE];
}
// leave as-is, likely 404 when a user visits the page
} else if(isOptional(sourceNode, "placeholder")) {
// transparent png
sourceNode.attrs.src = PLACEHOLDER_DATA_URI;
} else if(isOptional(sourceNode)) {
delete sourceNode.attrs.src;
}
// optional or dont fail on error
cleanTag(sourceNode);
return Promise.resolve();
}
return Promise.reject(error);
});
}
function eleventyImageTransformPlugin(eleventyConfig, options = {}) {
options = Object.assign({
extensions: "html",
transformOnRequest: process.env.ELEVENTY_RUN_MODE === "serve",
}, options);
if(options.transformOnRequest !== false) {
// Add the on-request plugin automatically (unless opt-out in this plugins options only)
eleventyConfig.addPlugin(eleventyImageOnRequestDuringServePlugin);
}
// Notably, global options are not shared automatically with the WebC `eleventyImagePlugin` above.
// Devs can pass in the same object to both if they want!
let opts = getGlobalOptions(eleventyConfig, options, "transform");
eleventyConfig.addJavaScriptFunction("__private_eleventyImageTransformConfigurationOptions", () => {
return opts;
});
function posthtmlPlugin(context) {
return async (tree) => {
let promises = [];
let match = tree.match;
tree.match({ tag: 'picture' }, pictureNode => {
match.call(pictureNode, { tag: 'img' }, imgNode => {
imgNode._insideOfPicture = true;
if(!isIgnored(imgNode) && !imgNode?.attrs?.src?.startsWith("data:")) {
promises.push(transformTag(context, imgNode, pictureNode, opts));
}
return imgNode;
});
return pictureNode;
});
tree.match({ tag: 'img' }, (imgNode) => {
if(imgNode._insideOfPicture) {
delete imgNode._insideOfPicture;
} else if(isIgnored(imgNode) || imgNode?.attrs?.src?.startsWith("data:")) {
cleanTag(imgNode);
} else {
promises.push(transformTag(context, imgNode, imgNode, opts));
}
return imgNode;
});
await Promise.all(promises);
return tree;
};
}
if(!eleventyConfig.htmlTransformer || !("addPosthtmlPlugin" in eleventyConfig.htmlTransformer)) {
throw new Error("[@11ty/eleventy-img] `eleventyImageTransformPlugin` is not compatible with this version of Eleventy. You will need to use v3.0.0 or newer.");
}
eleventyConfig.htmlTransformer.addPosthtmlPlugin(options.extensions, posthtmlPlugin, {
priority: -1, // we want this to go before <base> or inputpath to url
});
}
module.exports = {
eleventyImageTransformPlugin,
};

78
node_modules/@11ty/eleventy-img/src/util.js generated vendored Normal file
View File

@ -0,0 +1,78 @@
const path = require("node:path");
class Util {
static KEYS = {
requested: "requested"
};
/*
* Does not mutate, returns new Object.
*/
static getSortedObject(unordered) {
let keys = Object.keys(unordered).sort();
let obj = {};
for(let key of keys) {
obj[key] = unordered[key];
}
return obj;
}
static isRemoteUrl(url) {
try {
const validUrl = new URL(url);
if (validUrl.protocol.startsWith("https:") || validUrl.protocol.startsWith("http:")) {
return true;
}
return false;
// eslint-disable-next-line no-unused-vars
} catch(e) {
// invalid url OR local path
return false;
}
}
static normalizeImageSource({ input, inputPath }, src, options = {}) {
let { isViaHtml } = Object.assign({
isViaHtml: false
}, options);
if(Util.isFullUrl(src)) {
return src;
}
if(isViaHtml) {
src = decodeURIComponent(src);
}
if(!path.isAbsolute(src)) {
// if the image src is relative, make it relative to the template file (inputPath);
let dir = path.dirname(inputPath);
return path.join(dir, src);
}
// if the image src is absolute, make it relative to the input/content directory.
return path.join(input, src);
}
static isRequested(generatedVia) {
return generatedVia === this.KEYS.requested;
}
static addConfig(eleventyConfig, options) {
if(!eleventyConfig) {
return;
}
Object.defineProperty(options, "eleventyConfig", {
value: eleventyConfig,
enumerable: false,
});
}
}
// Temporary alias for changes made in https://github.com/11ty/eleventy-img/pull/138
Util.isFullUrl = Util.isRemoteUrl;
module.exports = Util;

View File

@ -0,0 +1,23 @@
const { getGlobalOptions } = require("./global-options.js");
const { eleventyImageOnRequestDuringServePlugin } = require("./on-request-during-serve-plugin.js");
function eleventyWebcOptionsPlugin(eleventyConfig, options = {}) {
options = Object.assign({
transformOnRequest: process.env.ELEVENTY_RUN_MODE === "serve",
}, options);
// Notably, global options are not shared automatically with the `eleventyImageTransformPlugin` below.
// Devs can pass in the same object to both if they want!
eleventyConfig.addJavaScriptFunction("__private_eleventyImageConfigurationOptions", () => {
return getGlobalOptions(eleventyConfig, options, "webc");
});
if(options.transformOnRequest !== false) {
// Add the on-request plugin automatically (unless opt-out in this plugins options only)
eleventyConfig.addPlugin(eleventyImageOnRequestDuringServePlugin);
}
}
module.exports = {
eleventyWebcOptionsPlugin,
};

26
node_modules/@11ty/eleventy-navigation/.eleventy.js generated vendored Normal file
View File

@ -0,0 +1,26 @@
const pkg = require("./package.json");
const EleventyNavigation = require("./eleventy-navigation");
// export the configuration function for plugin
module.exports = function(eleventyConfig) {
try {
eleventyConfig.versionCheck(pkg["11ty"].compatibility);
} catch(e) {
console.log( `WARN: Eleventy Plugin (${pkg.name}) Compatibility: ${e.message}` );
}
eleventyConfig.addFilter("eleventyNavigation", EleventyNavigation.findNavigationEntries);
eleventyConfig.addFilter("eleventyNavigationBreadcrumb", EleventyNavigation.findBreadcrumbEntries);
eleventyConfig.addFilter("eleventyNavigationToHtml", function(pages, options) {
return EleventyNavigation.toHtml.call(eleventyConfig, pages, options);
});
eleventyConfig.addFilter("eleventyNavigationToMarkdown", function(pages, options) {
return EleventyNavigation.toMarkdown.call(eleventyConfig, pages, options);
});
};
module.exports.navigation = {
find: EleventyNavigation.findNavigationEntries,
findBreadcrumbs: EleventyNavigation.findBreadcrumbEntries,
getDependencyGraph: EleventyNavigation.getDependencyGraph,
};

View File

@ -0,0 +1,22 @@
name: Node Unit Tests
on: [push, pull_request]
permissions: read-all
jobs:
build:
runs-on: ${{ matrix.os }}
strategy:
matrix:
os: ["ubuntu-latest", "macos-latest", "windows-latest"]
node: ["18", "20", "22", "24"]
name: Node.js ${{ matrix.node }} on ${{ matrix.os }}
steps:
- uses: actions/checkout@692973e3d937129bcbf40652eb9f2f61becf3332 # 4.1.7
- name: Setup node
uses: actions/setup-node@1e60f620b9541d16bece96c5465dc8ee9832be0b # 4.0.3
with:
node-version: ${{ matrix.node }}
# cache: npm
- run: npm install
- run: npm test
env:
YARN_GPG: no

View File

@ -0,0 +1,25 @@
name: Publish Release to npm
on:
release:
types: [published]
permissions: read-all
jobs:
build:
runs-on: ubuntu-latest
environment: GitHub Publish
permissions:
contents: read
id-token: write
steps:
- uses: actions/checkout@692973e3d937129bcbf40652eb9f2f61becf3332 # 4.1.7
- uses: actions/setup-node@1e60f620b9541d16bece96c5465dc8ee9832be0b # 4.0.3
with:
node-version: "22"
registry-url: 'https://registry.npmjs.org'
- run: npm install -g npm@latest
- run: npm ci
- run: npm test
- if: ${{ github.event.release.tag_name != '' && env.NPM_PUBLISH_TAG != '' }}
run: npm publish --provenance --access=public --tag=${{ env.NPM_PUBLISH_TAG }}
env:
NPM_PUBLISH_TAG: ${{ contains(github.event.release.tag_name, '-beta.') && 'beta' || 'latest' }}

21
node_modules/@11ty/eleventy-navigation/LICENSE generated vendored Normal file
View File

@ -0,0 +1,21 @@
MIT License
Copyright (c) 20192025 Zach Leatherman @zachleat
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

9
node_modules/@11ty/eleventy-navigation/README.md generated vendored Normal file
View File

@ -0,0 +1,9 @@
<p align="center"><img src="https://www.11ty.dev/img/logo-github.svg" width="200" height="200" alt="11ty Logo"></p>
# eleventy-navigation 🕚⚡️🎈🐀
A plugin for creating hierarchical navigation in Eleventy projects. Supports breadcrumbs too!
Used [in production on 11ty.dev](https://www.11ty.dev/docs/)!
## Read the [Full Documentation on 11ty.dev](https://www.11ty.dev/docs/plugins/navigation/)

View File

@ -0,0 +1,277 @@
const DepGraph = require("dependency-graph").DepGraph;
function findNavigationEntries(nodes = [], key = "") {
let keys = key.split(",").filter(k => Boolean(k));
let pages = {};
for(let entry of nodes) {
let data = entry?.data || {};
if(data?.eleventyNavigation) {
let {eleventyNavigation} = data || {};
let pageKey;
if(!key && !eleventyNavigation.parent) { // top level (no parents)
pageKey = "__default";
} else if(keys.includes(eleventyNavigation.parent)) {
pageKey = eleventyNavigation.parent;
}
if(pageKey) {
if(!pages[pageKey]) {
pages[pageKey] = [];
}
let url = eleventyNavigation.url ?? data?.page?.url;
pages[pageKey].push(Object.assign({ data }, eleventyNavigation, {
...(url ? { url } : {}),
pluginType: "eleventy-navigation",
...(keys.length > 0 ? { parentKey: eleventyNavigation.parent } : {}),
}));
}
}
}
return Object.values(pages).flat().sort(function(a, b) {
if(a.pinned && b.pinned) {
return (a.order || 0) - (b.order || 0);
}
let order = [a.order, b.order];
if(a.pinned) {
order[0] = -Infinity;
}
if(b.pinned) {
order[1] = -Infinity;
}
if(order[0] === undefined && order[1] === undefined) {
return 0;
}
if(order[1] === undefined) {
return -1;
}
if(order[0] === undefined) {
return 1;
}
return order[0] - order[1];
}).map(function(entry) {
if(!entry.title) {
entry.title = entry.key;
}
if(entry.key) {
entry.children = findNavigationEntries(nodes, entry.key);
}
return entry;
});
}
function findDependencies(pages, depGraph, parentKey) {
for( let page of pages ) {
depGraph.addNode(page.key, page);
if(parentKey) {
depGraph.addDependency(page.key, parentKey);
}
if(page.children) {
findDependencies(page.children, depGraph, page.key);
}
}
}
function getDependencyGraph(nodes) {
let pages = findNavigationEntries(nodes);
let graph = new DepGraph();
findDependencies(pages, graph);
return graph;
}
function isOptionMatch(options, name) {
// Liquid.js issue #35
if(Array.isArray(options)) {
return options[options.indexOf(name)]
}
return options[name];
}
function findBreadcrumbEntries(nodes, activeKey, options = {}) {
let graph = getDependencyGraph(nodes);
if (isOptionMatch(options, "allowMissing") && !graph.hasNode(activeKey)) {
// Fail gracefully if the key isn't in the graph
return [];
}
let deps = graph.dependenciesOf(activeKey);
if(isOptionMatch(options, "includeSelf")) {
deps.push(activeKey);
}
return activeKey ? deps.map(key => {
let data = Object.assign({}, graph.getNodeData(key));
delete data.children;
data._isBreadcrumb = true;
return data;
}) : [];
}
function getUrlFilter(eleventyConfig) {
// eleventyConfig.pathPrefix was first available in Eleventy 2.0.0-canary.15
// And in Eleventy 2.0.0-canary.15 we recommend the a built-in transform for pathPrefix
if(eleventyConfig.pathPrefix !== undefined) {
return function(url) {
return url;
};
}
if("getFilter" in eleventyConfig) {
// v0.10.0 and above
return eleventyConfig.getFilter("url");
} else if("nunjucksFilters" in eleventyConfig) {
// backwards compat, hardcoded key
return eleventyConfig.nunjucksFilters.url;
} else {
// Theoretically we could just move on here with a `url => url` but then `pathPrefix`
// would not work and it wouldnt be obvious why—so lets fail loudly to avoid that.
throw new Error("Could not find a `url` filter for the eleventy-navigation plugin in eleventyNavigationToHtml filter.");
}
}
function buildHtmlAttr(name, values) {
// values could be array or string
if (!values || !values.length) {
return '';
}
const valueStr = Array.isArray(values) ? values.join(" ") : values;
return ` ${name}="${valueStr}"`;
}
function buildAllHtmlAttrs(attrs) {
return attrs.reduce((acc, { name, values }) => acc + buildHtmlAttr(name, values), '');
}
function navigationToHtml(pages, options = {}) {
options = Object.assign({
listElement: "ul",
listItemElement: "li",
listClass: "",
listItemClass: "",
listItemHasChildrenClass: "",
activeKey: "",
activeListItemClass: "",
anchorClass: "",
activeAnchorClass: "",
useAriaCurrentAttr: false,
showExcerpt: false,
isChildList: false,
useTopLevelDetails: false,
anchorElementWithoutHref: "a", // default, better to use span
}, options);
let isChildList = !!options.isChildList;
options.isChildList = true;
let urlFilter;
if(pages.length && pages[0].pluginType !== "eleventy-navigation") {
throw new Error("Incorrect argument passed to eleventyNavigationToHtml filter. You must call `eleventyNavigation` or `eleventyNavigationBreadcrumb` first, like: `collection.all | eleventyNavigation | eleventyNavigationToHtml | safe`");
}
return pages.length ? `<${options.listElement}${!isChildList && options.listClass ? ` class="${options.listClass}"` : ''}>${pages.map(entry => {
let liClass = [];
let aClass = [];
let aAttrs = [];
if(options.listItemClass) {
liClass.push(options.listItemClass);
}
if(options.anchorClass) {
aClass.push(options.anchorClass);
}
if(entry.url) {
if(!urlFilter) {
// dont get if not used
urlFilter = getUrlFilter(this);
}
aAttrs.push({name: "href", values: urlFilter(entry.url)})
}
if(options.activeKey === entry.key) {
if(options.activeListItemClass) {
liClass.push(options.activeListItemClass);
}
if(options.activeAnchorClass) {
aClass.push(options.activeAnchorClass);
}
if(options.useAriaCurrentAttr) {
aAttrs.push({ name: "aria-current", values: "page" });
}
}
if(options.listItemHasChildrenClass && entry.children && entry.children.length) {
liClass.push(options.listItemHasChildrenClass);
}
if(aClass.length) {
aAttrs.push({ name: "class", values: aClass });
}
let postfix = "";
// Helper to show pin/order in text:
// let hasOrder = entry.order || entry.order === 0;
// if(process.env.ELEVENTY_RUN_MODE === "serve" && (hasOrder || entry.pinned)) {
// postfix = ` (${entry.pinned ? "📌" : ""}${entry.order ?? ""})`;
// }
let aAttrsStr = buildAllHtmlAttrs(aAttrs);
let hasLink = aAttrs.find(entry => entry.name === "href");
let itemTitle = entry.title + postfix;
let titleHtmlStart = `<a${aAttrsStr}>${itemTitle}</a>`;
// purely defensive use of `useTopLevelDetails` here
if(options.anchorElementWithoutHref && !hasLink) {
titleHtmlStart = `<${options.anchorElementWithoutHref}>${itemTitle}</${options.anchorElementWithoutHref}>`;
}
let titleHtmlEnd = "";
if(options.useTopLevelDetails && !isChildList && entry.children) {
if(hasLink) {
// `<a>` must be sibling: no other interactive elements in <summary>
titleHtmlStart = `${titleHtmlStart}<details><summary>${itemTitle}</summary>`;
} else {
titleHtmlStart = `<details><summary>${itemTitle}</summary>`;
}
titleHtmlEnd = "</details>";
}
let childContentStr = entry.children ? navigationToHtml.call(this, entry.children, options) : "";
return `<${options.listItemElement}${buildHtmlAttr("class", liClass)}>${titleHtmlStart}${options.showExcerpt && entry.excerpt ? `: ${entry.excerpt}` : ""}${childContentStr}${titleHtmlEnd}</${options.listItemElement}>`;
}).join("\n")}</${options.listElement}>` : "";
}
function navigationToMarkdown(pages, options = {}) {
options = Object.assign({
showExcerpt: false,
childDepth: 0
}, options);
let childDepth = 1 + options.childDepth;
options.childDepth++;
let urlFilter;
if(pages.length && pages[0].pluginType !== "eleventy-navigation") {
throw new Error("Incorrect argument passed to eleventyNavigationToMarkdown filter. You must call `eleventyNavigation` or `eleventyNavigationBreadcrumb` first, like: `collection.all | eleventyNavigation | eleventyNavigationToMarkdown | safe`");
}
let indent = (new Array(childDepth)).join(" ") || "";
return pages.length ? `${pages.map(entry => {
if(entry.url && !urlFilter) {
// dont get if not used
urlFilter = getUrlFilter(this);
}
return `${indent}* ${entry.url ? `[` : ""}${entry.title}${entry.url ? `](${urlFilter(entry.url)})` : ""}${options.showExcerpt && entry.excerpt ? `: ${entry.excerpt}` : ""}\n${entry.children ? navigationToMarkdown.call(this, entry.children, options) : ""}`;
}).join("")}` : "";
}
module.exports = {
getDependencyGraph,
findNavigationEntries,
findBreadcrumbEntries,
toHtml: navigationToHtml,
toMarkdown: navigationToMarkdown
};

49
node_modules/@11ty/eleventy-navigation/package.json generated vendored Normal file
View File

@ -0,0 +1,49 @@
{
"name": "@11ty/eleventy-navigation",
"version": "1.0.5",
"publishConfig": {
"access": "public"
},
"description": "A plugin for creating hierarchical navigation in Eleventy projects. Supports breadcrumbs too!",
"main": ".eleventy.js",
"scripts": {
"test": "npx ava",
"sample": "npx @11ty/eleventy --input=sample --output=sample/_site --config=sample/.eleventy.js"
},
"repository": {
"type": "git",
"url": "git+https://github.com/11ty/eleventy-navigation.git"
},
"bugs": {
"url": "https://github.com/11ty/eleventy-navigation/issues"
},
"homepage": "https://www.11ty.dev/docs/plugins/navigation/",
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/11ty"
},
"keywords": [
"eleventy",
"eleventy-plugin"
],
"author": {
"name": "Zach Leatherman",
"email": "zachleatherman@gmail.com",
"url": "https://zachleat.com/"
},
"license": "MIT",
"11ty": {
"compatibility": ">=0.7 || >=1.0.0-canary"
},
"devDependencies": {
"ava": "^6.4.1"
},
"dependencies": {
"dependency-graph": "^1.0.0"
},
"ava": {
"files": [
"./test/*.js"
]
}
}

View File

@ -0,0 +1,9 @@
const EleventyNavigationPlugin = require("../");
module.exports = function(eleventyConfig) {
eleventyConfig.addPlugin(EleventyNavigationPlugin);
return {
pathPrefix: "/sdljfkaldsjlfka/"
}
};

View File

@ -0,0 +1,5 @@
---
eleventyNavigation:
key: Bats
parent: Mammals
---

View File

@ -0,0 +1,5 @@
---
eleventyNavigation:
key: Humans
parent: Mammals
---

View File

@ -0,0 +1,19 @@
<h2>Full List</h2>
{{ collections.all | eleventyNavigation | dump(2) }}
{{ collections.all | eleventyNavigation | eleventyNavigationToHtml }}
<h2>Breadcrumb for Bats</h2>
{{
collections.all
| eleventyNavigationBreadcrumb: "Bats"
| dump(2)
}}
{{
collections.all
| eleventyNavigationBreadcrumb: "Bats"
| eleventyNavigationToHtml
}}

View File

@ -0,0 +1,4 @@
---
eleventyNavigation:
key: Mammals
---

View File

@ -0,0 +1,4 @@
---
eleventyNavigation:
---
This page has no key.

View File

@ -0,0 +1,3 @@
---
---
This page has no navigation.

View File

@ -0,0 +1,11 @@
<h2>Full List</h2>
{{ collections.all | eleventyNavigation | dump(2) | safe }}
{{ collections.all | eleventyNavigation | eleventyNavigationToHtml | safe }}
<h2>Breadcrumb for Bats</h2>
{{ collections.all | eleventyNavigationBreadcrumb("Bats") | dump(2) | safe }}
{{ collections.all | eleventyNavigationBreadcrumb("Bats") | eleventyNavigationToHtml | safe }}

View File

@ -0,0 +1,747 @@
const test = require("ava");
const EleventyNavigation = require("../eleventy-navigation");
test("Empty navigation", t => {
t.deepEqual(EleventyNavigation.findNavigationEntries(), []);
});
test("One root page navigation", t => {
let obj = EleventyNavigation.findNavigationEntries([
{
data: {
eleventyNavigation: {
key: "root1"
},
page: {
url: "root1.html"
}
}
}
]);
t.is(obj[0].key, "root1");
t.is(obj[0].pluginType, "eleventy-navigation");
// Warning, title must be preserved per the public API
t.is(obj[0].title, "root1");
// Warning, url must be preserved per the public API
t.is(obj[0].url, "root1.html");
t.is(obj[0].children.length, 0);
});
test("One root page navigation with separate title", t => {
let obj = EleventyNavigation.findNavigationEntries([
{
data: {
eleventyNavigation: {
key: "root1",
title: "Another title"
},
page: {
url: "root1.html"
}
}
}
]);
t.is(obj[0].key, "root1");
t.is(obj[0].pluginType, "eleventy-navigation");
t.is(obj[0].title, "Another title");
t.is(obj[0].children.length, 0);
});
test("One root, one child page navigation", t => {
let obj = EleventyNavigation.findNavigationEntries([
{
data: {
eleventyNavigation: {
key: "root1"
},
page: {
url: "root1.html"
}
}
},
{
data: {
eleventyNavigation: {
parent: "root1",
key: "child1"
},
page: {
url: "child1.html"
}
}
}
]);
t.is(obj[0].key, "root1");
t.is(obj[0].children.length, 1);
t.is(obj[0].children[0].parent, "root1");
t.is(obj[0].children[0].key, "child1");
});
test("Three layers deep navigation", t => {
let obj = EleventyNavigation.findNavigationEntries([
{
data: {
eleventyNavigation: {
key: "root1"
},
page: {
url: "root1.html"
}
}
},
{
data: {
eleventyNavigation: {
parent: "root1",
key: "child1"
},
page: {
url: "child1.html"
}
}
},
{
data: {
eleventyNavigation: {
parent: "child1",
key: "grandchild1"
},
page: {
url: "grandchild1.html"
}
}
}
]);
t.is(obj[0].key, "root1");
t.is(obj[0].children.length, 1);
t.is(obj[0].children[0].parent, "root1");
t.is(obj[0].children[0].key, "child1");
t.is(obj[0].children[0].children[0].parent, "child1");
t.is(obj[0].children[0].children[0].key, "grandchild1");
});
test("One root, three child navigation (order)", t => {
let obj = EleventyNavigation.findNavigationEntries([
{
data: {
eleventyNavigation: {
key: "root1"
},
page: {
url: "root1.html"
}
}
},
{
data: {
eleventyNavigation: {
parent: "root1",
key: "child1",
order: 3
},
page: {
url: "child1.html"
}
}
},
{
data: {
eleventyNavigation: {
parent: "root1",
key: "child2",
order: 1
},
page: {
url: "child2.html"
}
}
},
{
data: {
eleventyNavigation: {
parent: "root1",
key: "child3",
order: 2
},
page: {
url: "child3.html"
}
}
},
{
data: {
eleventyNavigation: {
parent: "root1",
key: "child4"
},
page: {
url: "child4.html"
}
}
}
]);
t.is(obj[0].key, "root1");
t.is(obj[0].children.length, 4);
t.is(obj[0].children.map(e => e.key).join(","), "child2,child3,child1,child4");
});
test("One root, three child navigation, one with 0 (order)", t => {
let obj = EleventyNavigation.findNavigationEntries([
{
data: {
eleventyNavigation: {
key: "root1"
},
page: {
url: "root1.html"
}
}
},
{
data: {
eleventyNavigation: {
parent: "root1",
key: "child1",
order: 3
},
page: {
url: "child1.html"
}
}
},
{
data: {
eleventyNavigation: {
parent: "root1",
key: "child2",
order: 0
},
page: {
url: "child2.html"
}
}
},
{
data: {
eleventyNavigation: {
parent: "root1",
key: "child3",
order: 2
},
page: {
url: "child3.html"
}
}
},
{
data: {
eleventyNavigation: {
parent: "root1",
key: "child4"
},
page: {
url: "child4.html"
}
}
}
]);
t.is(obj[0].key, "root1");
t.is(obj[0].children.length, 4);
t.is(obj[0].children.map(e => e.key).join(","), "child2,child3,child1,child4");
});
test("One root, three child navigation (implied order)", t => {
let obj = EleventyNavigation.findNavigationEntries([
{
data: {
eleventyNavigation: {
key: "root1"
},
page: {
url: "root1.html"
}
}
},
{
data: {
eleventyNavigation: {
parent: "root1",
key: "child1",
order: 3
},
page: {
url: "child1.html"
}
}
},
{
data: {
eleventyNavigation: {
parent: "root1",
key: "child2"
},
page: {
url: "child2.html"
}
}
},
{
data: {
eleventyNavigation: {
parent: "root1",
key: "child3",
order: -1
},
page: {
url: "child3.html"
}
}
}
]);
t.is(obj[0].key, "root1");
t.is(obj[0].children.length, 3);
t.is(obj[0].children.map(e => e.key).join(","), "child3,child1,child2");
});
test("Show throw an error without a config", t => {
let obj = EleventyNavigation.findNavigationEntries([
{
data: {
eleventyNavigation: {
key: "root1"
},
page: {
url: "root1.html"
}
}
}
]);
t.throws(() => {
EleventyNavigation.toHtml(obj);
});
});
let fakeConfig = {
nunjucksFilters: {
url: url => url
}
};
let fakeNavigationEntries = [
{
data: {
eleventyNavigation: {
key: "root1"
},
page: {
url: "root1.html"
}
}
},
{
data: {
eleventyNavigation: {
parent: "root1",
key: "child1"
},
page: {
url: "child1.html"
}
}
}
];
let fakeNavigationEntriesEmptyUrl = [
{
data: {
eleventyNavigation: {
key: "root1"
},
page: {
url: "root1.html"
}
}
},
{
data: {
eleventyNavigation: {
parent: "root1",
key: "child1"
},
page: {
url: false
}
}
}
];
test("Checking active class on output HTML", t => {
let obj = EleventyNavigation.findNavigationEntries(fakeNavigationEntries);
let html = EleventyNavigation.toHtml.call(fakeConfig, obj);
t.is(html, `<ul><li><a href="root1.html">root1</a><ul><li><a href="child1.html">child1</a></li></ul></li></ul>`);
let activeHtmlItem = EleventyNavigation.toHtml.call(fakeConfig, obj, {
activeKey: "child1",
activeListItemClass: "this-is-the-active-item"
});
t.is(activeHtmlItem, `<ul><li><a href="root1.html">root1</a><ul><li class="this-is-the-active-item"><a href="child1.html">child1</a></li></ul></li></ul>`);
let activeHtmlAnchor = EleventyNavigation.toHtml.call(fakeConfig, obj, {
activeKey: "child1",
activeAnchorClass: "this-is-the-active-anchor"
});
t.is(activeHtmlAnchor, `<ul><li><a href="root1.html">root1</a><ul><li><a href="child1.html" class="this-is-the-active-anchor">child1</a></li></ul></li></ul>`);
let activeHtmlItemAndAnchor = EleventyNavigation.toHtml.call(fakeConfig, obj, {
activeKey: "child1",
activeListItemClass: "this-is-the-active-item",
activeAnchorClass: "this-is-the-active-anchor"
});
t.is(activeHtmlItemAndAnchor, `<ul><li><a href="root1.html">root1</a><ul><li class="this-is-the-active-item"><a href="child1.html" class="this-is-the-active-anchor">child1</a></li></ul></li></ul>`);
});
test("Checking aria-current option on output HTML", t => {
let obj = EleventyNavigation.findNavigationEntries(fakeNavigationEntries);
let html = EleventyNavigation.toHtml.call(fakeConfig, obj);
t.true(html.indexOf(`<li><a href="child1.html">child1</a></li>`) > -1);
let activeHtmlAnchor = EleventyNavigation.toHtml.call(fakeConfig, obj, {
activeKey: "child1",
useAriaCurrentAttr: true
});
t.true(activeHtmlAnchor.indexOf(`<li><a href="child1.html" aria-current="page">child1</a></li>`) > -1);
});
test("Checking has children class on output HTML", t => {
let obj = EleventyNavigation.findNavigationEntries(fakeNavigationEntries);
let activeHtml = EleventyNavigation.toHtml.call(fakeConfig, obj, {
listItemHasChildrenClass: "item-has-children"
});
t.true(activeHtml.indexOf(`<li class="item-has-children"><a href="root1.html">root1</a>`) > -1);
t.true(activeHtml.indexOf(`<li><a href="child1.html">child1</a></li>`) > -1);
});
test("URL override", t => {
let obj = EleventyNavigation.findNavigationEntries([
{
data: {
eleventyNavigation: {
key: "root1",
url: "https://www.zachleat.com/"
},
page: {
url: "root1.html"
}
}
}
]);
t.is(obj[0].url, "https://www.zachleat.com/");
});
test("Breadcrumbs", t => {
let obj = EleventyNavigation.findBreadcrumbEntries([
{
data: {
eleventyNavigation: {
key: "root1"
},
page: {
url: "root1.html"
}
}
},
{
data: {
eleventyNavigation: {
parent: "root1",
key: "child1"
},
page: {
url: "child1.html"
}
}
},
{
data: {
eleventyNavigation: {
parent: "child1",
key: "grandchild1"
},
page: {
url: "grandchild1.html"
}
}
}
], "grandchild1");
t.is(obj.length, 2);
t.is(obj[0].key, "root1");
t.is(obj[1].key, "child1");
});
test("Breadcrumbs (include self)", t => {
let obj = EleventyNavigation.findBreadcrumbEntries([
{
data: {
eleventyNavigation: {
key: "root1"
},
page: {
url: "root1.html"
}
}
},
{
data: {
eleventyNavigation: {
parent: "root1",
key: "child1"
},
page: {
url: "child1.html"
}
}
},
{
data: {
eleventyNavigation: {
parent: "child1",
key: "grandchild1"
},
page: {
url: "grandchild1.html"
}
}
}
], "grandchild1", {
includeSelf: true
});
t.is(obj.length, 3);
t.is(obj[0].key, "root1");
t.is(obj[1].key, "child1");
t.is(obj[2].key, "grandchild1");
});
test("Breadcrumbs (options.allowMissing)", t => {
const entries = EleventyNavigation.findBreadcrumbEntries(
[],
"orphan",
{allowMissing: true}
);
t.is(entries.length, 0);
});
test("Output markdown", t => {
let obj = EleventyNavigation.findNavigationEntries([
{
data: {
eleventyNavigation: {
key: "root1"
},
page: {
url: "root1.html"
}
}
},
{
data: {
eleventyNavigation: {
parent: "root1",
key: "child1"
},
page: {
url: "child1.html"
}
}
},
{
data: {
eleventyNavigation: {
parent: "child1",
key: "grandchild1"
},
page: {
url: "grandchild1.html"
}
}
}
]);
let html = EleventyNavigation.toMarkdown.call(fakeConfig, obj);
t.is(html, `* [root1](root1.html)
* [child1](child1.html)
* [grandchild1](grandchild1.html)
`);
});
test("Navigation entry contains page data", t => {
let obj = EleventyNavigation.findNavigationEntries([
{
data: {
eleventyNavigation: {
key: "root1"
},
page: {
url: "root1.html"
},
tags: [
"robot",
"lesbian"
],
collections: {}
}
}
]);
// Page data like tags should be included in the obj
t.deepEqual(obj[0].data.tags, ["robot", "lesbian"]);
});
test("Missing url", t => {
let obj = EleventyNavigation.findNavigationEntries([
{
data: {
eleventyNavigation: {
key: "root1",
}
}
}
]);
t.is(EleventyNavigation.toHtml.call(fakeConfig, obj), `<ul><li><a>root1</a></li></ul>`);
});
test("Multiple roots", t => {
let obj = EleventyNavigation.findNavigationEntries([
{
data: {
eleventyNavigation: {
key: "root1"
}
}
},
{
data: {
eleventyNavigation: {
parent: "root1",
key: "child1",
}
}
},
{
data: {
eleventyNavigation: {
key: "root2"
},
}
},
{
data: {
eleventyNavigation: {
parent: "root2",
key: "child3",
}
}
}
]);
t.deepEqual(obj.map(e => e.key), ["root1", "root2"]);
t.deepEqual(obj[0].children.map(e => e.key), ["child1"]);
t.deepEqual(obj[1].children.map(e => e.key), ["child3"]);
});
test("Multiple roots, multiple keys", t => {
let obj = EleventyNavigation.findNavigationEntries([
{
data: {
eleventyNavigation: {
key: "root1"
}
}
},
{
data: {
eleventyNavigation: {
parent: "root1",
key: "child1",
}
}
},
{
data: {
eleventyNavigation: {
key: "root2"
},
}
},
{
data: {
eleventyNavigation: {
parent: "root2",
key: "child3",
}
}
}
], "root1,root2");
t.deepEqual(obj.map(e => e.key), ["child1", "child3"]);
t.deepEqual(obj[0].children.map(e => e.key), []);
t.deepEqual(obj[1].children.map(e => e.key), []);
});
test("Breadcrumb include self", t => {
let nodes = [
{
data: {
eleventyNavigation: {
key: "root1",
}
}
}
];
let obj = EleventyNavigation.findBreadcrumbEntries(nodes, "root1", { includeSelf: true });
t.is(EleventyNavigation.toHtml(obj), `<ul><li><a>root1</a></li></ul>`);
});
test("Breadcrumb include self (Liquid.js #35)", t => {
let nodes = [
{
data: {
eleventyNavigation: {
key: "root1",
}
}
}
];
let obj = EleventyNavigation.findBreadcrumbEntries(nodes, "root1", [ "includeSelf", true ]);
t.is(EleventyNavigation.toHtml(obj), `<ul><li><a>root1</a></li></ul>`);
});
test("Use top level details", t => {
let obj = EleventyNavigation.findNavigationEntries(fakeNavigationEntries);
let html = EleventyNavigation.toHtml.call(fakeConfig, obj, {
useTopLevelDetails: true
});
t.is(html, `<ul><li><a href="root1.html">root1</a><details><summary>root1</summary><ul><li><a href="child1.html">child1</a></li></ul></details></li></ul>`);
});
test("Use top level details with empty url", t => {
let obj = EleventyNavigation.findNavigationEntries(fakeNavigationEntriesEmptyUrl);
let html = EleventyNavigation.toHtml.call(fakeConfig, obj, {
useTopLevelDetails: true,
anchorElementWithoutHref: "span",
});
t.is(html, `<ul><li><a href="root1.html">root1</a><details><summary>root1</summary><ul><li><span>child1</span></li></ul></details></li></ul>`);
});

337
node_modules/@11ty/eleventy-plugin-bundle/README.md generated vendored Normal file
View File

@ -0,0 +1,337 @@
# eleventy-plugin-bundle
Little bundles of code, little bundles of joy.
Create minimal per-page or app-level bundles of CSS, JavaScript, or HTML to be included in your Eleventy project.
Makes it easy to implement Critical CSS, in-use-only CSS/JS bundles, SVG icon libraries, or secondary HTML content to load via XHR.
## Why?
This project is a minimum-viable-bundler and asset pipeline in Eleventy. It does not perform any transpilation or code manipulation (by default). The code you put in is the code you get out (with configurable `transforms` if youd like to modify the code).
For more larger, more complex use cases you may want to use a more full featured bundler like Vite, Parcel, Webpack, rollup, esbuild, or others.
But do note that a full-featured bundler has a significant build performance cost, so take care to weigh the cost of using that style of bundler against whether or not this plugin has sufficient functionality for your use case—especially as the platform matures and we see diminishing returns on code transpilation (ES modules everywhere).
## Installation
No installation necessary. Starting with Eleventy `v3.0.0-alpha.10` and newer, this plugin is now bundled with Eleventy.
## Usage
By default, Bundle Plugin v2.0 does not include any default bundles. You must add these yourself via `eleventyConfig.addBundle`. One notable exception happens when using the WebC Eleventy Plugin, which adds `css`, `js`, and `html` bundles for you.
To create a bundle type, use `eleventyConfig.addBundle` in your Eleventy configuration file (default `.eleventy.js`):
```js
// .eleventy.js
export default function(eleventyConfig) {
eleventyConfig.addBundle("css");
};
```
This does two things:
1. Creates a new `css` shortcode for adding arbitrary code to this bundle
2. Adds `"css"` as an eligible type argument to the `getBundle` and `getBundleFileUrl` shortcodes.
### Full options list
```js
export default function(eleventyConfig) {
eleventyConfig.addBundle("css", {
// (Optional) Folder (relative to output directory) files will write to
toFileDirectory: "bundle",
// (Optional) File extension used for bundle file output, defaults to bundle name
outputFileExtension: "css",
// (Optional) Name of shortcode for use in templates, defaults to bundle name
shortcodeName: "css",
// shortcodeName: false, // disable this feature.
// (Optional) Modify bundle content
transforms: [],
// (Optional) If two identical code blocks exist in non-default buckets, theyll be hoisted to the first bucket in common.
hoist: true,
// (Optional) In 11ty.js templates, having a named export of `bundle` will populate your bundles.
bundleExportKey: "bundle",
// bundleExportKey: false, // disable this feature.
});
};
```
Read more about [`hoist` and duplicate bundle hoisting](https://github.com/11ty/eleventy-plugin-bundle/issues/5).
### Universal Shortcodes
The following Universal Shortcodes (available in `njk`, `liquid`, `hbs`, `11ty.js`, and `webc`) are provided by this plugin:
* `getBundle` to retrieve bundled code as a string.
* `getBundleFileUrl` to create a bundle file on disk and retrieve the URL to that file.
Heres a [real-world commit showing this in use on the `eleventy-base-blog` project](https://github.com/11ty/eleventy-base-blog/commit/c9595d8f42752fa72c66991c71f281ea960840c9?diff=split).
### Example: Add bundle code in a Markdown file in Eleventy
```md
# My Blog Post
This is some content, I am writing markup.
{% css %}
em { font-style: italic; }
{% endcss %}
## More Markdown
{% css %}
strong { font-weight: bold; }
{% endcss %}
```
Renders to:
```html
<h1>My Blog Post</h1>
<p>This is some content, I am writing markup.</p>
<h2>More Markdown</h2>
```
Note that the bundled code is excluded!
_There are a few [more examples below](#examples)!_
### Render bundle code
```html
<!-- Use this *anywhere*: a layout file, content template, etc -->
<style>{% getBundle "css" %}</style>
<!--
You can add more code to the bundle after calling
getBundle and it will be included.
-->
{% css %}* { color: orange; }{% endcss %}
```
### Write a bundle to a file
Writes the bundle content to a content-hashed file location in your output directory and returns the URL to the file for use like this:
```html
<link rel="stylesheet" href="{% getBundleFileUrl "css" %}">
```
Note that writing bundles to files will likely be slower for empty-cache first time visitors but better cached in the browser for repeat-views (and across multiple pages, too).
### Asset bucketing
```html
<!-- This goes into a `defer` bucket (the bucket can be any string value) -->
{% css "defer" %}em { font-style: italic; }{% endcss %}
```
```html
<!-- Pass the arbitrary `defer` bucket name as an additional argument -->
<style>{% getBundle "css", "defer" %}</style>
<link rel="stylesheet" href="{% getBundleFileUrl 'css', 'defer' %}">
```
A `default` bucket is implied:
```html
<!-- These two statements are the same -->
{% css %}em { font-style: italic; }{% endcss %}
{% css "default" %}em { font-style: italic; }{% endcss %}
<!-- These two are the same too -->
<style>{% getBundle "css" %}</style>
<style>{% getBundle "css", "default" %}</style>
```
### Examples
#### Critical CSS
```js
// .eleventy.js
export default function(eleventyConfig) {
eleventyConfig.addBundle("css");
};
```
Use asset bucketing to divide CSS between the `default` bucket and a `defer` bucket, loaded asynchronously.
_(Note that some HTML boilerplate has been omitted from the sample below)_
```html
<!-- … -->
<head>
<!-- Inlined critical styles -->
<style>{% getBundle "css" %}</style>
<!-- Deferred non-critical styles -->
<link rel="stylesheet" href="{% getBundleFileUrl 'css', 'defer' %}" media="print" onload="this.media='all'">
<noscript>
<link rel="stylesheet" href="{% getBundleFileUrl 'css', 'defer' %}">
</noscript>
</head>
<body>
<!-- This goes into a `default` bucket -->
{% css %}/* Inline in the head, great with @font-face! */{% endcss %}
<!-- This goes into a `defer` bucket (the bucket can be any string value) -->
{% css "defer" %}/* Load me later */{% endcss %}
</body>
<!-- … -->
```
**Related**:
* Check out the [demo of Critical CSS using Eleventy Edge](https://demo-eleventy-edge.netlify.app/critical-css/) for a repeat view optimization without JavaScript.
* You may want to improve the above code with [`fetchpriority`](https://www.smashingmagazine.com/2022/04/boost-resource-loading-new-priority-hint-fetchpriority/) when [browser support improves](https://caniuse.com/mdn-html_elements_link_fetchpriority).
#### SVG Icon Library
Here an `svg` is bundle is created.
```js
// .eleventy.js
export default function(eleventyConfig) {
eleventyConfig.addBundle("svg");
};
```
```html
<svg width="0" height="0" aria-hidden="true" style="position: absolute;">
<defs>{% getBundle "svg" %}</defs>
</svg>
<!-- And anywhere on your page you can add icons to the set -->
{% svg %}
<g id="icon-close"><path d="…" /></g>
{% endsvg %}
And now you can use `icon-close` in as many SVG instances as youd like (without repeating the heftier SVG content).
<svg><use xlink:href="#icon-close"></use></svg>
<svg><use xlink:href="#icon-close"></use></svg>
<svg><use xlink:href="#icon-close"></use></svg>
<svg><use xlink:href="#icon-close"></use></svg>
```
#### React Helmet-style `<head>` additions
```js
// .eleventy.js
export default function(eleventyConfig) {
eleventyConfig.addBundle("html");
};
```
This might exist in an Eleventy layout file:
```html
<head>
{% getBundle "html", "head" %}
</head>
```
And then in your content you might want to page-specific `preconnect`:
```html
{% html "head" %}
<link href="https://v1.opengraph.11ty.dev" rel="preconnect" crossorigin>
{% endhtml %}
```
#### Bundle Sass with the Render Plugin
You can render template syntax inside of the `{% css %}` shortcode too, if youd like to do more advanced things using Eleventy template types.
This example assumes you have added the [Render plugin](https://www.11ty.dev/docs/plugins/render/) and the [`scss` custom template type](https://www.11ty.dev/docs/languages/custom/) to your Eleventy configuration file.
```html
{% css %}
{% renderTemplate "scss" %}
h1 { .test { color: red; } }
{% endrenderTemplate %}
{% endcss %}
```
Now the compiled Sass is available in your default bundle and will show up in `getBundle` and `getBundleFileUrl`.
#### Use with [WebC](https://www.11ty.dev/docs/languages/webc/)
Starting with `@11ty/eleventy-plugin-webc@0.9.0` (track at [issue #48](https://github.com/11ty/eleventy-plugin-webc/issues/48)) this plugin is used by default in the Eleventy WebC plugin. Specifically, [WebC Bundler Mode](https://www.11ty.dev/docs/languages/webc/#css-and-js-(bundler-mode)) now uses the bundle plugin under the hood.
To add CSS to a bundle in WebC, you would use a `<style>` element in a WebC page or component:
```html
<style>/* This is bundled. */</style>
<style webc:keep>/* Do not bundle me—leave as is */</style>
```
To add JS to a page bundle in WebC, you would use a `<script>` element in a WebC page or component:
```html
<script>/* This is bundled. */</script>
<script webc:keep>/* Do not bundle me—leave as is */</script>
```
* Existing calls via WebC helpers `getCss` or `getJs` (e.g. `<style @raw="getCss(page.url)">`) have been wired up to `getBundle` (for `"css"` and `"js"` respectively) automatically.
* For consistency, you may prefer using the bundle plugin method names everywhere: `<style @raw="getBundle('css')">` and `<script @raw="getBundle('js')">` both work fine.
* Outside of WebC, the Universal Filters `webcGetCss` and `webcGetJs` were removed in Eleventy `v3.0.0-alpha.10` in favor of the `getBundle` Universal Shortcode (`{% getBundle "css" %}` and `{% getBundle "js" %}` respectively).
#### Modify the bundle output
You can wire up your own async-friendly callbacks to transform the bundle output too. Heres a quick example of [`postcss` integration](https://github.com/postcss/postcss#js-api).
```js
const postcss = require("postcss");
const postcssNested = require("postcss-nested");
export default function(eleventyConfig) {
eleventyConfig.addBundle("css", {
transforms: [
async function(content) {
// this.type returns the bundle name.
// Same as Eleventy transforms, this.page is available here.
let result = await postcss([postcssNested]).process(content, { from: this.page.inputPath, to: null });
return result.css;
}
]
});
};
```
## Advanced
### Limitations
Bundles do not support nesting or recursion (yet?). If this will be useful to you, please file an issue!
<!--
Version Two:
* Think about Eleventy transform order, scenarios where this transform needs to run first.
* JavaScript API independent of eleventy
* Clean up the _site/bundle folder on exit?
* Example ideas:
* App bundle and page bundle
* can we make this work for syntax highlighting? or just defer to WebC for this?
{% css %}
<style>
em { font-style: italic; }
</style>
{% endcss %}
* a way to declare dependencies? or just defer to buckets here
* What if we want to add code duplicates? Adding `alert(1);` `alert(1);` to alert twice?
* sourcemaps (maybe via magic-string module or https://www.npmjs.com/package/concat-with-sourcemaps)
-->

View File

@ -0,0 +1,72 @@
import bundleManagersPlugin from "./src/eleventy.bundleManagers.js";
import pruneEmptyBundlesPlugin from "./src/eleventy.pruneEmptyBundles.js";
import globalShortcodesAndTransforms from "./src/eleventy.shortcodes.js";
import debugUtil from "debug";
const debug = debugUtil("Eleventy:Bundle");
function normalizeOptions(options = {}) {
options = Object.assign({
// Plugin defaults
// Extra bundles
// css, js, and html are guaranteed unless `bundles: false`
bundles: [],
toFileDirectory: "bundle",
// post-process
transforms: [],
hoistDuplicateBundlesFor: [],
bundleExportKey: "bundle", // use a `bundle` export in a 11ty.js template to populate bundles
force: false, // force overwrite of existing getBundleManagers and addBundle configuration API methods
}, options);
if(options.bundles !== false) {
options.bundles = Array.from(new Set(["css", "js", "html", ...(options.bundles || [])]));
}
return options;
}
function eleventyBundlePlugin(eleventyConfig, pluginOptions = {}) {
eleventyConfig.versionCheck(">=3.0.0");
pluginOptions = normalizeOptions(pluginOptions);
let alreadyAdded = "getBundleManagers" in eleventyConfig || "addBundle" in eleventyConfig;
if(!alreadyAdded || pluginOptions.force) {
if(alreadyAdded && pluginOptions.force) {
debug("Bundle plugin already added via `addPlugin`, add was forced via `force: true`");
}
bundleManagersPlugin(eleventyConfig, pluginOptions);
}
// These cant be unique (dont skip re-add above), when the configuration file resets they need to be added again
pruneEmptyBundlesPlugin(eleventyConfig, pluginOptions);
globalShortcodesAndTransforms(eleventyConfig, pluginOptions);
// Support subsequent calls like addPlugin(BundlePlugin, { bundles: [] });
if(Array.isArray(pluginOptions.bundles)) {
debug("Adding bundles via `addPlugin`: %o", pluginOptions.bundles)
pluginOptions.bundles.forEach(name => {
let isHoisting = Array.isArray(pluginOptions.hoistDuplicateBundlesFor) && pluginOptions.hoistDuplicateBundlesFor.includes(name);
eleventyConfig.addBundle(name, {
hoist: isHoisting,
outputFileExtension: name, // default as `name`
shortcodeName: name, // `false` will skip shortcode
transforms: pluginOptions.transforms,
toFileDirectory: pluginOptions.toFileDirectory,
bundleExportKey: pluginOptions.bundleExportKey, // `false` will skip bundle export
});
});
}
};
// This is used to find the package name for this plugin (used in eleventy-plugin-webc to prevent dupes)
Object.defineProperty(eleventyBundlePlugin, "eleventyPackage", {
value: "@11ty/eleventy-plugin-bundle"
});
export default eleventyBundlePlugin;
export { normalizeOptions };

62
node_modules/@11ty/eleventy-plugin-bundle/package.json generated vendored Normal file
View File

@ -0,0 +1,62 @@
{
"name": "@11ty/eleventy-plugin-bundle",
"version": "3.0.7",
"description": "Little bundles of code, little bundles of joy.",
"main": "eleventy.bundle.js",
"type": "module",
"scripts": {
"sample": "DEBUG=Eleventy:Bundle npx @11ty/eleventy --config=sample/sample-config.js --input=sample --serve",
"test": "npx ava"
},
"publishConfig": {
"access": "public"
},
"license": "MIT",
"engines": {
"node": ">=18"
},
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/11ty"
},
"keywords": [
"eleventy",
"eleventy-plugin"
],
"repository": {
"type": "git",
"url": "git://github.com/11ty/eleventy-plugin-bundle.git"
},
"bugs": "https://github.com/11ty/eleventy-plugin-bundle/issues",
"homepage": "https://www.11ty.dev/",
"author": {
"name": "Zach Leatherman",
"email": "zachleatherman@gmail.com",
"url": "https://zachleat.com/"
},
"ava": {
"failFast": true,
"files": [
"test/*.js",
"test/*.mjs"
],
"watchMode": {
"ignoreChanges": [
"**/_site/**",
".cache"
]
}
},
"devDependencies": {
"@11ty/eleventy": "^3.0.0",
"ava": "^6.2.0",
"postcss": "^8.5.3",
"postcss-nested": "^7.0.2",
"sass": "^1.86.3"
},
"dependencies": {
"@11ty/eleventy-utils": "^2.0.2",
"debug": "^4.4.0",
"posthtml-match-helper": "^2.0.3"
}
}

View File

@ -0,0 +1,75 @@
import fs from "node:fs";
import path from "node:path";
import debugUtil from "debug";
import { createHash } from "@11ty/eleventy-utils";
const debug = debugUtil("Eleventy:Bundle");
const hashCache = {};
const directoryExistsCache = {};
const writingCache = new Set();
class BundleFileOutput {
constructor(outputDirectory, bundleDirectory) {
this.outputDirectory = outputDirectory;
this.bundleDirectory = bundleDirectory || "";
this.hashLength = 10;
this.fileExtension = undefined;
}
setFileExtension(ext) {
this.fileExtension = ext;
}
async getFilenameHash(content) {
if(hashCache[content]) {
return hashCache[content];
}
let base64hash = await createHash(content);
let filenameHash = base64hash.substring(0, this.hashLength);
hashCache[content] = filenameHash;
return filenameHash;
}
getFilename(filename, extension) {
return filename + (extension && !extension.startsWith(".") ? `.${extension}` : "");
}
modifyPathToUrl(dir, filename) {
return "/" + path.join(dir, filename).split(path.sep).join("/");
}
async writeBundle(content, type, writeToFileSystem) {
// do not write a bundle, do not return a file name is content is empty
if(!content) {
return;
}
let dir = path.join(this.outputDirectory, this.bundleDirectory);
let filenameHash = await this.getFilenameHash(content);
let filename = this.getFilename(filenameHash, this.fileExtension || type);
if(writeToFileSystem) {
let fullPath = path.join(dir, filename);
// no duplicate writes, this may be improved with a fs exists check, but it would only save the first write
if(!writingCache.has(fullPath)) {
writingCache.add(fullPath);
if(!directoryExistsCache[dir]) {
fs.mkdirSync(dir, { recursive: true });
directoryExistsCache[dir] = true;
}
debug("Writing bundle %o", fullPath);
fs.writeFileSync(fullPath, content);
}
}
return this.modifyPathToUrl(this.bundleDirectory, filename);
}
}
export { BundleFileOutput };

View File

@ -0,0 +1,231 @@
import { BundleFileOutput } from "./BundleFileOutput.js";
import debugUtil from "debug";
const debug = debugUtil("Eleventy:Bundle");
const DEBUG_LOG_TRUNCATION_SIZE = 200;
class CodeManager {
// code is placed in this bucket by default
static DEFAULT_BUCKET_NAME = "default";
// code is hoisted to this bucket when necessary
static HOISTED_BUCKET_NAME = "default";
constructor(name) {
this.name = name;
this.trimOnAdd = true;
// TODO unindent on add
this.reset();
this.transforms = [];
this.isHoisting = true;
this.fileExtension = undefined;
this.toFileDirectory = undefined;
this.bundleExportKey = "bundle";
this.runsAfterHtmlTransformer = false;
this.pluckedSelector = undefined;
}
setDelayed(isDelayed) {
this.runsAfterHtmlTransformer = Boolean(isDelayed);
}
isDelayed() {
return this.runsAfterHtmlTransformer;
}
// posthtml-match-selector friendly
setPluckedSelector(selector) {
this.pluckedSelector = selector;
}
getPluckedSelector() {
return this.pluckedSelector;
}
setFileExtension(ext) {
this.fileExtension = ext;
}
setHoisting(enabled) {
this.isHoisting = !!enabled;
}
setBundleDirectory(dir) {
this.toFileDirectory = dir;
}
setBundleExportKey(key) {
this.bundleExportKey = key;
}
getBundleExportKey() {
return this.bundleExportKey;
}
reset() {
this.pages = {};
}
static normalizeBuckets(bucket) {
if(Array.isArray(bucket)) {
return bucket;
} else if(typeof bucket === "string") {
return bucket.split(",");
}
return [CodeManager.DEFAULT_BUCKET_NAME];
}
setTransforms(transforms) {
if(!Array.isArray(transforms)) {
throw new Error("Array expected to setTransforms");
}
this.transforms = transforms;
}
_initBucket(pageUrl, bucket) {
if(!this.pages[pageUrl][bucket]) {
this.pages[pageUrl][bucket] = new Set();
}
}
addToPage(pageUrl, code = [], bucket) {
if(!Array.isArray(code) && code) {
code = [code];
}
if(code.length === 0) {
return;
}
if(!this.pages[pageUrl]) {
this.pages[pageUrl] = {};
}
let buckets = CodeManager.normalizeBuckets(bucket);
let codeContent = code.map(entry => {
if(this.trimOnAdd) {
return entry.trim();
}
return entry;
});
for(let b of buckets) {
this._initBucket(pageUrl, b);
for(let content of codeContent) {
if(content) {
if(!this.pages[pageUrl][b].has(content)) {
debug("Adding code to bundle %o for %o (bucket: %o, size: %o): %o", this.name, pageUrl, b, content.length, content.length > DEBUG_LOG_TRUNCATION_SIZE ? content.slice(0, DEBUG_LOG_TRUNCATION_SIZE) + "…" : content);
this.pages[pageUrl][b].add(content);
}
}
}
}
}
async runTransforms(str, pageData, buckets) {
for (let callback of this.transforms) {
str = await callback.call(
{
page: pageData,
type: this.name,
buckets: buckets
},
str
);
}
return str;
}
getBucketsForPage(pageData) {
let pageUrl = pageData.url;
if(!this.pages[pageUrl]) {
return [];
}
return Object.keys(this.pages[pageUrl]);
}
getRawForPage(pageData, buckets = undefined) {
let url = pageData.url;
if(!this.pages[url]) {
debug("No bundle code found for %o on %o, %O", this.name, url, this.pages);
return new Set();
}
buckets = CodeManager.normalizeBuckets(buckets);
let set = new Set();
let size = 0;
for(let b of buckets) {
if(!this.pages[url][b]) {
// Just continue, if you retrieve code from a bucket that doesnt exist or has no code, it will return an empty set
continue;
}
for(let entry of this.pages[url][b]) {
size += entry.length;
set.add(entry);
}
}
debug("Retrieving %o for %o (buckets: %o, entries: %o, size: %o)", this.name, url, buckets, set.size, size);
return set;
}
async getForPage(pageData, buckets = undefined) {
let set = this.getRawForPage(pageData, buckets);
let bundleContent = Array.from(set).join("\n");
// returns promise
return this.runTransforms(bundleContent, pageData, buckets);
}
async writeBundle(pageData, buckets, options = {}) {
let url = pageData.url;
if(!this.pages[url]) {
debug("No bundle code found for %o on %o, %O", this.name, url, this.pages);
return "";
}
let { output, write } = options;
buckets = CodeManager.normalizeBuckets(buckets);
// TODO the bundle output URL might be useful in the transforms for sourcemaps
let content = await this.getForPage(pageData, buckets);
let writer = new BundleFileOutput(output, this.toFileDirectory);
writer.setFileExtension(this.fileExtension);
return writer.writeBundle(content, this.name, write);
}
// Used when a bucket is output multiple times on a page and needs to be hoisted
hoistBucket(pageData, bucketName) {
let newTargetBucketName = CodeManager.HOISTED_BUCKET_NAME;
if(!this.isHoisting || bucketName === newTargetBucketName) {
return;
}
let url = pageData.url;
if(!this.pages[url] || !this.pages[url][bucketName]) {
debug("No bundle code found for %o on %o, %O", this.name, url, this.pages);
return;
}
debug("Code in bucket (%o) is being hoisted to a new bucket (%o)", bucketName, newTargetBucketName);
this._initBucket(url, newTargetBucketName);
for(let codeEntry of this.pages[url][bucketName]) {
this.pages[url][bucketName].delete(codeEntry);
this.pages[url][newTargetBucketName].add(codeEntry);
}
// delete the bucket
delete this.pages[url][bucketName];
}
}
export { CodeManager };

View File

@ -0,0 +1,158 @@
import debugUtil from "debug";
const debug = debugUtil("Eleventy:Bundle");
/* This class defers any `bundleGet` calls to a post-build transform step,
* to allow `getBundle` to be called before all of the `css` additions have been processed
*/
class OutOfOrderRender {
static SPLIT_REGEX = /(\/\*__EleventyBundle:[^:]*:[^:]*:[^:]*:EleventyBundle__\*\/)/;
static SEPARATOR = ":";
constructor(content) {
this.content = content;
this.managers = {};
}
// type if `get` (return string) or `file` (bundle writes to file, returns file url)
static getAssetKey(type, name, bucket) {
if(Array.isArray(bucket)) {
bucket = bucket.join(",");
} else if(typeof bucket === "string") {
} else {
bucket = "";
}
return `/*__EleventyBundle:${type}:${name}:${bucket || "default"}:EleventyBundle__*/`
}
static parseAssetKey(str) {
if(str.startsWith("/*__EleventyBundle:")) {
let [prefix, type, name, bucket, suffix] = str.split(OutOfOrderRender.SEPARATOR);
return { type, name, bucket };
}
return false;
}
setAssetManager(name, assetManager) {
this.managers[name] = assetManager;
}
setOutputDirectory(dir) {
this.outputDirectory = dir;
}
normalizeMatch(match) {
let ret = OutOfOrderRender.parseAssetKey(match)
return ret || match;
}
findAll() {
let matches = this.content.split(OutOfOrderRender.SPLIT_REGEX);
let ret = [];
for(let match of matches) {
ret.push(this.normalizeMatch(match));
}
return ret;
}
setWriteToFileSystem(isWrite) {
this.writeToFileSystem = isWrite;
}
getAllBucketsForPage(pageData) {
let availableBucketsForPage = new Set();
for(let name in this.managers) {
for(let bucket of this.managers[name].getBucketsForPage(pageData)) {
availableBucketsForPage.add(`${name}::${bucket}`);
}
}
return availableBucketsForPage;
}
getManager(name) {
if(!this.managers[name]) {
throw new Error(`No asset manager found for ${name}. Known names: ${Object.keys(this.managers)}`);
}
return this.managers[name];
}
async replaceAll(pageData, stage = 0) {
let matches = this.findAll();
let availableBucketsForPage = this.getAllBucketsForPage(pageData);
let usedBucketsOnPage = new Set();
let bucketsOutputStringCount = {};
let bucketsFileCount = {};
for(let match of matches) {
if(typeof match === "string") {
continue;
}
// type is `file` or `get`
let {type, name, bucket} = match;
let key = `${name}::${bucket}`;
if(!usedBucketsOnPage.has(key)) {
usedBucketsOnPage.add(key);
}
if(type === "get") {
if(!bucketsOutputStringCount[key]) {
bucketsOutputStringCount[key] = 0;
}
bucketsOutputStringCount[key]++;
} else if(type === "file") {
if(!bucketsFileCount[key]) {
bucketsFileCount[key] = 0;
}
bucketsFileCount[key]++;
}
}
// Hoist code in non-default buckets that are output multiple times
// Only hoist if 2+ `get` OR 1+ `get` and 1+ `file`
for(let bucketInfo in bucketsOutputStringCount) {
let stringOutputCount = bucketsOutputStringCount[bucketInfo];
if(stringOutputCount > 1 || stringOutputCount === 1 && bucketsFileCount[bucketInfo] > 0) {
let [name, bucketName] = bucketInfo.split("::");
this.getManager(name).hoistBucket(pageData, bucketName);
}
}
let content = await Promise.all(matches.map(match => {
if(typeof match === "string") {
return match;
}
let {type, name, bucket} = match;
let manager = this.getManager(name);
// Quit early if in stage 0, run delayed replacements if in stage 1+
if(typeof manager.isDelayed === "function" && manager.isDelayed() && stage === 0) {
return OutOfOrderRender.getAssetKey(type, name, bucket);
}
if(type === "get") {
// returns promise
return manager.getForPage(pageData, bucket);
} else if(type === "file") {
// returns promise
return manager.writeBundle(pageData, bucket, {
output: this.outputDirectory,
write: this.writeToFileSystem,
});
}
return "";
}));
for(let bucketInfo of availableBucketsForPage) {
if(!usedBucketsOnPage.has(bucketInfo)) {
let [name, bucketName] = bucketInfo.split("::");
debug(`WARNING! \`${pageData.inputPath}\` has unbundled \`${name}\` assets (in the '${bucketName}' bucket) that were not written to or used on the page. You might want to add a call to \`getBundle('${name}', '${bucketName}')\` to your content! Learn more: https://github.com/11ty/eleventy-plugin-bundle#asset-bucketing`);
}
}
return content.join("");
}
}
export { OutOfOrderRender };

View File

@ -0,0 +1,69 @@
import debugUtil from "debug";
import matchHelper from "posthtml-match-helper";
const debug = debugUtil("Eleventy:Bundle");
const ATTRS = {
ignore: "eleventy:ignore",
bucket: "eleventy:bucket",
};
const POSTHTML_PLUGIN_NAME = "11ty/eleventy/html-bundle-plucker";
function hasAttribute(node, name) {
return node?.attrs?.[name] !== undefined;
}
function addHtmlPlucker(eleventyConfig, bundleManager) {
let matchSelector = bundleManager.getPluckedSelector();
if(!matchSelector) {
throw new Error("Internal error: missing plucked selector on bundle manager.");
}
eleventyConfig.htmlTransformer.addPosthtmlPlugin(
"html",
function (context = {}) {
let pageUrl = context?.url;
if(!pageUrl) {
throw new Error("Internal error: missing `url` property from context.");
}
return function (tree, ...args) {
tree.match(matchHelper(matchSelector), function (node) {
try {
// ignore
if(hasAttribute(node, ATTRS.ignore)) {
delete node.attrs[ATTRS.ignore];
return node;
}
if(Array.isArray(node?.content) && node.content.length > 0) {
// TODO make this better decoupled
if(node?.content.find(entry => entry.includes(`/*__EleventyBundle:`))) {
// preserve {% getBundle %} calls as-is
return node;
}
let bucketName = node?.attrs?.[ATTRS.bucket];
bundleManager.addToPage(pageUrl, [ ...node.content ], bucketName);
return { attrs: [], content: [], tag: false };
}
} catch(e) {
debug(`Bundle plucker: error adding content to bundle in HTML Assets: %o`, e);
return node;
}
return node;
});
};
},
{
// pluginOptions
name: POSTHTML_PLUGIN_NAME,
},
);
}
export { addHtmlPlucker };

View File

@ -0,0 +1,85 @@
import debugUtil from "debug";
import { CodeManager } from "./CodeManager.js";
import { addHtmlPlucker } from "./bundlePlucker.js"
const debug = debugUtil("Eleventy:Bundle");
function eleventyBundleManagers(eleventyConfig, pluginOptions = {}) {
if(pluginOptions.force) {
// no errors
} else if(("getBundleManagers" in eleventyConfig || "addBundle" in eleventyConfig)) {
throw new Error("Duplicate addPlugin calls for @11ty/eleventy-plugin-bundle");
}
let managers = {};
function addBundle(name, bundleOptions = {}) {
if(name in managers) {
// note: shortcode must still be added
debug("Bundle exists %o, skipping.", name);
} else {
debug("Creating new bundle %o", name);
managers[name] = new CodeManager(name);
if(bundleOptions.delayed !== undefined) {
managers[name].setDelayed(bundleOptions.delayed);
}
if(bundleOptions.hoist !== undefined) {
managers[name].setHoisting(bundleOptions.hoist);
}
if(bundleOptions.bundleHtmlContentFromSelector !== undefined) {
managers[name].setPluckedSelector(bundleOptions.bundleHtmlContentFromSelector);
managers[name].setDelayed(true); // must override `delayed` above
addHtmlPlucker(eleventyConfig, managers[name]);
}
if(bundleOptions.bundleExportKey !== undefined) {
managers[name].setBundleExportKey(bundleOptions.bundleExportKey);
}
if(bundleOptions.outputFileExtension) {
managers[name].setFileExtension(bundleOptions.outputFileExtension);
}
if(bundleOptions.toFileDirectory) {
managers[name].setBundleDirectory(bundleOptions.toFileDirectory);
}
if(bundleOptions.transforms) {
managers[name].setTransforms(bundleOptions.transforms);
}
}
// if undefined, defaults to `name`
if(bundleOptions.shortcodeName !== false) {
let shortcodeName = bundleOptions.shortcodeName || name;
// e.g. `css` shortcode to add code to page bundle
// These shortcode names are not configurable on purpose (for wider plugin compatibility)
eleventyConfig.addPairedShortcode(shortcodeName, function addContent(content, bucket, explicitUrl) {
let url = explicitUrl || this.page?.url;
if(url) { // dont add if a file doesnt have an output URL
managers[name].addToPage(url, content, bucket);
}
return "";
});
}
};
eleventyConfig.addBundle = addBundle;
eleventyConfig.getBundleManagers = function() {
return managers;
};
eleventyConfig.on("eleventy.before", async () => {
for(let key in managers) {
managers[key].reset();
}
});
};
export default eleventyBundleManagers;

View File

@ -0,0 +1,105 @@
import matchHelper from "posthtml-match-helper";
import debugUtil from "debug";
const debug = debugUtil("Eleventy:Bundle");
const ATTRS = {
keep: "eleventy:keep"
};
const POSTHTML_PLUGIN_NAME = "11ty/eleventy-bundle/prune-empty";
function getTextNodeContent(node) {
if (!node.content) {
return "";
}
return node.content
.map((entry) => {
if (typeof entry === "string") {
return entry;
}
if (Array.isArray(entry.content)) {
return getTextNodeContent(entry);
}
return "";
})
.join("");
}
function eleventyPruneEmptyBundles(eleventyConfig, options = {}) {
// Right now script[src],link[rel="stylesheet"] nodes are removed if the final bundles are empty.
// `false` to disable
options.pruneEmptySelector = options.pruneEmptySelector ?? `style,script,link[rel="stylesheet"]`;
// Subsequent call can remove a previously added `addPosthtmlPlugin` entry
// htmlTransformer.remove is v3.0.1-alpha.4+
if(typeof eleventyConfig.htmlTransformer.remove === "function") {
eleventyConfig.htmlTransformer.remove("html", entry => {
if(entry.name === POSTHTML_PLUGIN_NAME) {
return true;
}
// Temporary workaround for missing `name` property.
let fnStr = entry.fn.toString();
return !entry.name && fnStr.startsWith("function (pluginOptions = {}) {") && fnStr.includes(`tree.match(matchHelper(options.pruneEmptySelector), function (node)`);
});
}
// `false` disables this plugin
if(options.pruneEmptySelector === false) {
return;
}
if(!eleventyConfig.htmlTransformer || !eleventyConfig.htmlTransformer?.constructor?.SUPPORTS_PLUGINS_ENABLED_CALLBACK) {
debug("You will need to upgrade your version of Eleventy core to remove empty bundle tags automatically (v3 or newer).");
return;
}
eleventyConfig.htmlTransformer.addPosthtmlPlugin(
"html",
function bundlePruneEmptyPosthtmlPlugin(pluginOptions = {}) {
return function (tree) {
tree.match(matchHelper(options.pruneEmptySelector), function (node) {
if(node.attrs && node.attrs[ATTRS.keep] !== undefined) {
delete node.attrs[ATTRS.keep];
return node;
}
// <link rel="stylesheet" href="">
if(node.tag === "link") {
if(node.attrs?.rel === "stylesheet" && (node.attrs?.href || "").trim().length === 0) {
return false;
}
} else {
let content = getTextNodeContent(node);
if(!content) {
// <script></script> or <script src=""></script>
if(node.tag === "script" && (node.attrs?.src || "").trim().length === 0) {
return false;
}
// <style></style>
if(node.tag === "style") {
return false;
}
}
}
return node;
});
};
},
{
name: POSTHTML_PLUGIN_NAME,
// the `enabled` callback for plugins is available on v3.0.0-alpha.20+ and v3.0.0-beta.2+
enabled: () => {
return Object.keys(eleventyConfig.getBundleManagers()).length > 0;
}
}
);
}
export default eleventyPruneEmptyBundles;

View File

@ -0,0 +1,83 @@
import { OutOfOrderRender } from "./OutOfOrderRender.js";
import debugUtil from "debug";
const debug = debugUtil("Eleventy:Bundle");
export default function(eleventyConfig, pluginOptions = {}) {
let managers = eleventyConfig.getBundleManagers();
let writeToFileSystem = true;
function bundleTransform(content, stage = 0) {
// Only run if content is string
// Only run if managers are in play
if(typeof content !== "string" || Object.keys(managers).length === 0) {
return content;
}
debug("Processing %o", this.page.url);
let render = new OutOfOrderRender(content);
for(let key in managers) {
render.setAssetManager(key, managers[key]);
}
render.setOutputDirectory(eleventyConfig.directories.output);
render.setWriteToFileSystem(writeToFileSystem);
return render.replaceAll(this.page, stage);
}
eleventyConfig.on("eleventy.before", async ({ outputMode }) => {
if(Object.keys(managers).length === 0) {
return;
}
if(outputMode !== "fs") {
writeToFileSystem = false;
debug("Skipping writing to the file system due to output mode: %o", outputMode);
}
});
// e.g. `getBundle` shortcode to get code in current page bundle
// bucket can be an array
// This shortcode name is not configurable on purpose (for wider plugin compatibility)
eleventyConfig.addShortcode("getBundle", function getContent(type, bucket, explicitUrl) {
if(!type || !(type in managers) || Object.keys(managers).length === 0) {
throw new Error(`Invalid bundle type: ${type}. Available options: ${Object.keys(managers)}`);
}
return OutOfOrderRender.getAssetKey("get", type, bucket);
});
// write a bundle to the file system
// This shortcode name is not configurable on purpose (for wider plugin compatibility)
eleventyConfig.addShortcode("getBundleFileUrl", function(type, bucket, explicitUrl) {
if(!type || !(type in managers) || Object.keys(managers).length === 0) {
throw new Error(`Invalid bundle type: ${type}. Available options: ${Object.keys(managers)}`);
}
return OutOfOrderRender.getAssetKey("file", type, bucket);
});
eleventyConfig.addTransform("@11ty/eleventy-bundle", function (content) {
let hasNonDelayedManagers = Boolean(Object.values(eleventyConfig.getBundleManagers()).find(manager => {
return typeof manager.isDelayed !== "function" || !manager.isDelayed();
}));
if(hasNonDelayedManagers) {
return bundleTransform.call(this, content, 0);
}
return content;
});
eleventyConfig.addPlugin((eleventyConfig) => {
// Delayed bundles *MUST* not alter URLs
eleventyConfig.addTransform("@11ty/eleventy-bundle/delayed", function (content) {
let hasDelayedManagers = Boolean(Object.values(eleventyConfig.getBundleManagers()).find(manager => {
return typeof manager.isDelayed === "function" && manager.isDelayed();
}));
if(hasDelayedManagers) {
return bundleTransform.call(this, content, 1);
}
return content;
});
});
};

21
node_modules/@11ty/eleventy-utils/LICENSE generated vendored Normal file
View File

@ -0,0 +1,21 @@
MIT License
Copyright (c) 20222024 Zach Leatherman @zachleat
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

27
node_modules/@11ty/eleventy-utils/README.md generated vendored Normal file
View File

@ -0,0 +1,27 @@
<p align="center"><img src="https://www.11ty.dev/img/logo-github.png" alt="eleventy Logo"></p>
# eleventy-utils 🕚⚡️🎈🐀
Low level internal utilities to be shared amongst Eleventy projects.
## ➡ [Documentation](https://www.11ty.dev/docs/)
- Please star [Eleventy on GitHub](https://github.com/11ty/eleventy/)!
- Follow us on Twitter [@eleven_ty](https://twitter.com/eleven_ty)
- Support [11ty on Open Collective](https://opencollective.com/11ty)
- [11ty on npm](https://www.npmjs.com/org/11ty)
- [11ty on GitHub](https://github.com/11ty)
## Installation
```
npm install @11ty/eleventy-utils
```
## Tests
```
npm run test
```
- We use the native NodeJS [test runner](https://nodejs.org/api/test.html#test-runner) and ([assertions](https://nodejs.org/api/assert.html#assert))

20
node_modules/@11ty/eleventy-utils/index.js generated vendored Normal file
View File

@ -0,0 +1,20 @@
const TemplatePath = require("./src/TemplatePath.js");
const isPlainObject = require("./src/IsPlainObject.js");
const Merge = require("./src/Merge.js");
const DateCompare = require("./src/DateCompare.js");
const { DeepCopy } = Merge;
const { createHash, createHashHex, createHashSync, createHashHexSync } = require("./src/CreateHash.js");
const Buffer = require("./src/Buffer.js");
module.exports = {
TemplatePath,
isPlainObject,
Merge,
DeepCopy,
DateCompare,
createHash,
createHashHex,
createHashSync,
createHashHexSync,
Buffer,
};

42
node_modules/@11ty/eleventy-utils/package.json generated vendored Normal file
View File

@ -0,0 +1,42 @@
{
"name": "@11ty/eleventy-utils",
"version": "2.0.7",
"description": "Low level internal utilities to be shared amongst Eleventy projects",
"main": "index.js",
"files": [
"src",
"src/**",
"index.js",
"!test",
"!test/**"
],
"scripts": {
"test": "node --test",
"watch": "node --test --watch"
},
"license": "MIT",
"engines": {
"node": ">=18"
},
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/11ty"
},
"keywords": [
"eleventy"
],
"publishConfig": {
"access": "public"
},
"author": {
"name": "Zach Leatherman",
"email": "zachleatherman@gmail.com",
"url": "https://zachleat.com/"
},
"repository": {
"type": "git",
"url": "git://github.com/11ty/eleventy-utils.git"
},
"bugs": "https://github.com/11ty/eleventy-utils/issues",
"homepage": "https://github.com/11ty/eleventy-utils/"
}

10
node_modules/@11ty/eleventy-utils/src/Buffer.js generated vendored Normal file
View File

@ -0,0 +1,10 @@
function isBuffer(inst) {
if(typeof Buffer !== "undefined") {
return Buffer.isBuffer(inst);
}
return inst instanceof Uint8Array;
}
module.exports = {
isBuffer
}

27
node_modules/@11ty/eleventy-utils/src/CreateHash.js generated vendored Normal file
View File

@ -0,0 +1,27 @@
const { Hash } = require("./HashTypes.js");
// same output as node:crypto above (though now async).
async function createHash(...content) {
return Hash.create().toBase64Url(...content);
}
async function createHashHex(...content) {
return Hash.create().toHex(...content);
}
// Slower, but this feature does not require WebCrypto
function createHashSync(...content) {
return Hash.createSync().toBase64Url(...content);
}
function createHashHexSync(...content) {
return Hash.createSync().toHex(...content);
}
module.exports = {
createHash,
createHashSync,
createHashHex,
createHashHexSync,
};

41
node_modules/@11ty/eleventy-utils/src/DateCompare.js generated vendored Normal file
View File

@ -0,0 +1,41 @@
class DateCompare {
static isTimestampWithinDuration(timestamp, duration, compareDate = Date.now()) {
// the default duration is Infinity (also "*")
if (!duration || duration === "*" || duration === Infinity) {
return true;
}
let expiration = timestamp + this.getDurationMs(duration);
// still valid
if (expiration > compareDate) {
return true;
}
// expired
return false;
}
static getDurationMs(duration = "0s") {
let durationUnits = duration.slice(-1);
let durationMultiplier;
if (durationUnits === "s") {
durationMultiplier = 1;
} else if (durationUnits === "m") {
durationMultiplier = 60;
} else if (durationUnits === "h") {
durationMultiplier = 60 * 60;
} else if (durationUnits === "d") {
durationMultiplier = 60 * 60 * 24;
} else if (durationUnits === "w") {
durationMultiplier = 60 * 60 * 24 * 7;
} else if (durationUnits === "y") {
durationMultiplier = 60 * 60 * 24 * 365;
}
let durationValue = parseInt(duration.slice(0, duration.length - 1), 10);
return durationValue * durationMultiplier * 1000;
}
}
module.exports = DateCompare;

158
node_modules/@11ty/eleventy-utils/src/HashTypes.js generated vendored Normal file
View File

@ -0,0 +1,158 @@
const { base64UrlSafe } = require("./Url.js");
const { isBuffer } = require("./Buffer.js");
const sha256 = require("./lib-sha256.js");
function hasNodeCryptoModule() {
try {
require("node:crypto");
return true;
} catch(e) {
return false;
}
}
const HAS_NODE_CRYPTO = hasNodeCryptoModule();
class Hash {
static create() {
if(typeof globalThis.crypto === "undefined") {
// Backwards compat with Node Crypto, since WebCrypto (crypto global) is Node 20+
if(HAS_NODE_CRYPTO) {
return NodeCryptoHash;
}
return ScriptHash;
}
return WebCryptoHash;
}
// Does not use WebCrypto (as WebCrypto is async-only)
static createSync() {
if(HAS_NODE_CRYPTO) {
return NodeCryptoHash;
}
return ScriptHash;
}
static toBase64(bytes) {
let str = Array.from(bytes, (b) => String.fromCodePoint(b)).join("");
// `btoa` Node 16+
return btoa(str);
}
// Thanks https://evanhahn.com/the-best-way-to-concatenate-uint8arrays/ (Public domain)
static mergeUint8Array(...arrays) {
let totalLength = arrays.reduce(
(total, uint8array) => total + uint8array.byteLength,
0
);
let result = new Uint8Array(totalLength);
let offset = 0;
arrays.forEach((uint8array) => {
result.set(uint8array, offset);
offset += uint8array.byteLength;
});
return result;
}
static bufferToBase64Url(hashBuffer) {
return base64UrlSafe(this.toBase64(new Uint8Array(hashBuffer)));
}
static bufferToHex(hashBuffer) {
return Array.from(new Uint8Array(hashBuffer))
.map((b) => b.toString(16).padStart(2, "0"))
.join("");
}
}
class WebCryptoHash extends Hash {
static async toHash(...content) {
let encoder = new TextEncoder();
let input = this.mergeUint8Array(...content.map(c => {
if(isBuffer(c)) {
return c;
}
return encoder.encode(c);
}));
// `crypto` is Node 20+
return crypto.subtle.digest("SHA-256", input);
}
static async toBase64Url(...content) {
return this.toHash(...content).then(hashBuffer => {
return this.bufferToBase64Url(hashBuffer);
});
}
static async toHex(...content) {
return this.toHash(...content).then(hashBuffer => {
return this.bufferToHex(hashBuffer);
});
}
static toBase64UrlSync() {
throw new Error("Synchronous methods are not available in the Web Crypto API.");
}
static toHexSync() {
throw new Error("Synchronous methods are not available in the Web Crypto API.");
}
}
class NodeCryptoHash extends Hash {
static toHash(...content) {
// This *needs* to be a dynamic require for proper bundling.
const { createHash } = require("node:crypto");
let hash = createHash("sha256");
for(let c of content) {
hash.update(c);
}
return hash;
}
static toBase64Url(...content) {
// Note that Node does include a `digest("base64url")` that is supposedly Node 14+ but curiously failed on Stackblitzs Node 16.
let base64 = this.toHash(...content).digest("base64");
return base64UrlSafe(base64);
}
static toHex(...content) {
return this.toHash(...content).digest("hex");
}
// aliases
static toBase64UrlSync = this.toBase64Url;
static toHexSync = this.toHex;
}
class ScriptHash extends Hash {
static toHash(...content) {
let hash = sha256();
for(let c of content) {
hash.add(c);
}
return hash.digest();
}
static toBase64Url(...content) {
let hashBuffer = this.toHash(...content);
return this.bufferToBase64Url(hashBuffer);
}
static toHex(...content) {
let hashBuffer = this.toHash(...content);
return this.bufferToHex(hashBuffer);
}
// aliases
static toBase64UrlSync = this.toBase64Url;
static toHexSync = this.toHex;
}
module.exports = { Hash, NodeCryptoHash, ScriptHash, WebCryptoHash }

Some files were not shown because too many files have changed in this diff Show More