Initial commit

This commit is contained in:
2024-11-03 17:41:45 +01:00
commit c1640c1754
8043 changed files with 775536 additions and 0 deletions

View File

@@ -0,0 +1,22 @@
on:
push:
branches-ignore:
- "gh-pages"
jobs:
build:
runs-on: ${{ matrix.os }}
strategy:
matrix:
os: ["ubuntu-latest", "macos-latest", "windows-latest"]
node: ["16", "18", "20"]
name: Node.js ${{ matrix.node }} on ${{ matrix.os }}
steps:
- uses: actions/checkout@v3
- name: Setup node
uses: actions/setup-node@v3
with:
node-version: ${{ matrix.node }}
- run: npm install
- run: npm test
env:
YARN_GPG: no

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.

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

@@ -0,0 +1,40 @@
# `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
const { find } = require("@11ty/dependency-tree-esm");
find("./my-file.js");
// returns ["./my-local-dependency.js"]
```

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

@@ -0,0 +1,84 @@
const path = require("path");
const { existsSync } = require("fs");
const { readFile } = require("fs/promises");
const acorn = require("acorn");
const normalizePath = require("normalize-path");
const { TemplatePath } = require("@11ty/eleventy-utils");
// 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);
}
async function findByContents(contents, filePath, alreadyParsedSet) {
// Should we use dependency-graph for these relationships?
let sources = new Set();
let ast = acorn.parse(contents, {sourceType: "module", ecmaVersion: "latest"});
for(let node of ast.body) {
if(node.type === "ImportDeclaration" && isNonBareSpecifier(node.source.value)) {
let normalized = normalizeImportSourceToFilePath(filePath, node.source.value);
if(sources.has(normalized) || normalized === filePath) {
continue;
}
sources.add(normalized);
}
}
// Recurse for nested deps
for(let source of sources) {
let s = await find(source, alreadyParsedSet);
for(let p of s) {
if(sources.has(p) || p === filePath) {
continue;
}
sources.add(p);
}
}
return Array.from(sources);
}
async function find(filePath, 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(alreadyParsedSet.has(normalized) || !existsSync(filePath)) {
return [];
}
alreadyParsedSet.add(normalized);
let contents = await readFile(normalized, { encoding: 'utf8' });
let sources = await findByContents(contents, normalized, alreadyParsedSet);
return sources;
}
module.exports = {
find
};

View File

@@ -0,0 +1,82 @@
# Dependency Graph Changelog
## 0.11.0 (March 5, 2021)
- Add `entryNodes` method that returns the nodes that nothing depends on - thanks [amcdnl](https://github.com/amcdnl)!
## 0.10.0 (January 9, 2021)
- Add `directDependenciesOf` and `directDependantsOf` methods for retrieving direct dependency information. (Fixes #40)
- Add aliases `dependentsOf` and `directDependentsOf`.
## 0.9.0 (February 10, 2020)
- Rewrite the topological sort DFS to be more efficient (and work!) on large graphs.
- No longer uses recursion to avoid stack overflows with large/deep graphs
- No longer is accidentally `O(N^2)` (thanks [willtennien](https://github.com/willtennien) for pointing this out!)
## 0.8.1 (December 3, 2019)
- Ensure all nodes are included in overallOrder when cycles are allowed. (Fixes #33)
## 0.8.0 (December 11, 2018)
- Add a `DepGraphCycleError` with cyclePath property - thanks [jhugman](https://github.com/jhugman)!
## 0.7.2 (August 30, 2018)
- Make constructor parameter optional in Typescript definition. (Fixes #26)
## 0.7.1 (June 5, 2018)
- Fix Typescript definition to include the new constructor arguments added in `0.7.0` - thanks [tbranyen](https://github.com/tbranyen)!
## 0.7.0 (January 17, 2018)
- Allow circular dependencies by passing in `{circular: true}` into the constructor - thanks [tbranyen](https://github.com/tbranyen)!
## 0.6.0 (October 22, 2017)
- Add a `size` method that will return the number of nodes in the graph.
- Add a `clone` method that will clone the graph. Any custom node data will only be shallow-copied. (Fixes #14)
## 0.5.2 (October 22, 2017)
- Add missing parameter in TypeScript definition. (Fixes #19)
## 0.5.1 (October 7, 2017)
- Now exposes Typescript type definition - thanks [vangorra](https://github.com/vangorra)!
## 0.5.0 (April 26, 2016)
- Add optional data parameter for the addNode method. (Fixes #12)
- Add methods getNodeData and setNodeData to manipulate the data associated with a node name. (Fixes #12)
- Change the hasNode method to be able to cope with falsy node data. (Fixes #12)
## 0.4.1 (Sept 3, 2015)
- Check all nodes for potential cycles when calculating overall order. (Fixes #8)
## 0.4.0 (Aug 1, 2015)
- Better error messages
- When a cycle is detected, the error message will now include the cycle in it. E.g `Dependency Cycle Found: a -> b -> c -> a` (Fixes #7)
- When calling `addDependency` if one of the nodes does not exist, the error will say which one it was (instead of saying that "one" of the two nodes did not exist and making you manually determine which one)
- Calling `overallOrder` on an empty graph will no longer throw an error about a dependency cycle. It will return an empty array.
## 0.3.0 (July 24, 2015)
- Fix issue where if you call `addNode` twice with the same name, it would clear all edges for that node. Now it will do nothing if a node with the specified name already exists. (Fixes #3)
## 0.2.1 (July 3, 2015)
- Fixed removeNode leaving references in outgoingEdges and reference to non-existent var edges - thanks [juhoha](https://github.com/juhoha)! (Fixes #2)
## 0.2.0 (May 1, 2015)
- Removed dependency on Underscore - thanks [myndzi](https://github.com/myndzi)! (Fixes #1)
## 0.1.0 (May 18, 2013)
- Initial Release - extracted out of asset-smasher

View File

@@ -0,0 +1,19 @@
Copyright (C) 2013-2020 by Jim Riecken
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.

View File

@@ -0,0 +1,78 @@
# Dependency Graph
Simple dependency graph
## Overview
This is a simple dependency graph useful for determining the order to do a list of things that depend on certain items being done before they are.
To use, `npm install dependency-graph` and then `require('dependency-graph').DepGraph`
## API
### DepGraph
Nodes in the graph are just simple strings with optional data associated with them.
- `addNode(name, data)` - add a node in the graph with optional data. If `data` is not given, `name` will be used as data
- `removeNode(name)` - remove a node from the graph
- `hasNode(name)` - check if a node exists in the graph
- `size()` - return the number of nodes in the graph
- `getNodeData(name)` - get the data associated with a node (will throw an `Error` if the node does not exist)
- `setNodeData(name, data)` - set the data for an existing node (will throw an `Error` if the node does not exist)
- `addDependency(from, to)` - add a dependency between two nodes (will throw an `Error` if one of the nodes does not exist)
- `removeDependency(from, to)` - remove a dependency between two nodes
- `clone()` - return a clone of the graph. Any data attached to the nodes will only be *shallow-copied*
- `dependenciesOf(name, leavesOnly)` - get an array containing the nodes that the specified node depends on (transitively). If `leavesOnly` is true, only nodes that do not depend on any other nodes will be returned in the array.
- `dependantsOf(name, leavesOnly)` (aliased as `dependentsOf`) - get an array containing the nodes that depend on the specified node (transitively). If `leavesOnly` is true, only nodes that do not have any dependants will be returned in the array.
- `directDependenciesOf(name)` - get an array containing the direct dependencies of the specified node
- `directDependantsOf(name)` (aliased as `directDependentsOf`) - get an array containing the nodes that directly depend on the specified node
- `overallOrder(leavesOnly)` - construct the overall processing order for the dependency graph. If `leavesOnly` is true, only nodes that do not depend on any other nodes will be returned.
- `entryNodes()` - array of nodes that have no dependants (i.e. nothing depends on them).
Dependency Cycles are detected when running `dependenciesOf`, `dependantsOf`, and `overallOrder` and if one is found, a `DepGraphCycleError` will be thrown that includes what the cycle was in the message as well as the `cyclePath` property: e.g. `Dependency Cycle Found: a -> b -> c -> a`. If you wish to silence this error, pass `circular: true` when instantiating `DepGraph` (more below).
## Examples
var DepGraph = require('dependency-graph').DepGraph;
var graph = new DepGraph();
graph.addNode('a');
graph.addNode('b');
graph.addNode('c');
graph.size() // 3
graph.addDependency('a', 'b');
graph.addDependency('b', 'c');
graph.dependenciesOf('a'); // ['c', 'b']
graph.dependenciesOf('b'); // ['c']
graph.dependantsOf('c'); // ['a', 'b']
graph.overallOrder(); // ['c', 'b', 'a']
graph.overallOrder(true); // ['c']
graph.entryNodes(); // ['a']
graph.addNode('d', 'data');
graph.getNodeData('d'); // 'data'
graph.setNodeData('d', 'newData');
graph.getNodeData('d'); // 'newData'
var circularGraph = new DepGraph({ circular: true });
circularGraph.addNode('a');
circularGraph.addNode('b');
circularGraph.addNode('c');
circularGraph.addNode('d');
circularGraph.addDependency('a', 'b');
circularGraph.addDependency('b', 'c'); // b depends on c
circularGraph.addDependency('c', 'a'); // c depends on a, which depends on b
circularGraph.addDependency('d', 'a');
circularGraph.dependenciesOf('b'); // ['a', 'c']
circularGraph.overallOrder(); // ['c', 'b', 'a', 'd']

View File

@@ -0,0 +1,364 @@
/**
* A simple dependency graph
*/
/**
* Helper for creating a Topological Sort using Depth-First-Search on a set of edges.
*
* Detects cycles and throws an Error if one is detected (unless the "circular"
* parameter is "true" in which case it ignores them).
*
* @param edges The set of edges to DFS through
* @param leavesOnly Whether to only return "leaf" nodes (ones who have no edges)
* @param result An array in which the results will be populated
* @param circular A boolean to allow circular dependencies
*/
function createDFS(edges, leavesOnly, result, circular) {
var visited = {};
return function (start) {
if (visited[start]) {
return;
}
var inCurrentPath = {};
var currentPath = [];
var todo = []; // used as a stack
todo.push({ node: start, processed: false });
while (todo.length > 0) {
var current = todo[todo.length - 1]; // peek at the todo stack
var processed = current.processed;
var node = current.node;
if (!processed) {
// Haven't visited edges yet (visiting phase)
if (visited[node]) {
todo.pop();
continue;
} else if (inCurrentPath[node]) {
// It's not a DAG
if (circular) {
todo.pop();
// If we're tolerating cycles, don't revisit the node
continue;
}
currentPath.push(node);
throw new DepGraphCycleError(currentPath);
}
inCurrentPath[node] = true;
currentPath.push(node);
var nodeEdges = edges[node];
// (push edges onto the todo stack in reverse order to be order-compatible with the old DFS implementation)
for (var i = nodeEdges.length - 1; i >= 0; i--) {
todo.push({ node: nodeEdges[i], processed: false });
}
current.processed = true;
} else {
// Have visited edges (stack unrolling phase)
todo.pop();
currentPath.pop();
inCurrentPath[node] = false;
visited[node] = true;
if (!leavesOnly || edges[node].length === 0) {
result.push(node);
}
}
}
};
}
/**
* Simple Dependency Graph
*/
var DepGraph = (exports.DepGraph = function DepGraph(opts) {
this.nodes = {}; // Node -> Node/Data (treated like a Set)
this.outgoingEdges = {}; // Node -> [Dependency Node]
this.incomingEdges = {}; // Node -> [Dependant Node]
this.circular = opts && !!opts.circular; // Allows circular deps
});
DepGraph.prototype = {
/**
* The number of nodes in the graph.
*/
size: function () {
return Object.keys(this.nodes).length;
},
/**
* Add a node to the dependency graph. If a node already exists, this method will do nothing.
*/
addNode: function (node, data) {
if (!this.hasNode(node)) {
// Checking the arguments length allows the user to add a node with undefined data
if (arguments.length === 2) {
this.nodes[node] = data;
} else {
this.nodes[node] = node;
}
this.outgoingEdges[node] = [];
this.incomingEdges[node] = [];
}
},
/**
* Remove a node from the dependency graph. If a node does not exist, this method will do nothing.
*/
removeNode: function (node) {
if (this.hasNode(node)) {
delete this.nodes[node];
delete this.outgoingEdges[node];
delete this.incomingEdges[node];
[this.incomingEdges, this.outgoingEdges].forEach(function (edgeList) {
Object.keys(edgeList).forEach(function (key) {
var idx = edgeList[key].indexOf(node);
if (idx >= 0) {
edgeList[key].splice(idx, 1);
}
}, this);
});
}
},
/**
* Check if a node exists in the graph
*/
hasNode: function (node) {
return this.nodes.hasOwnProperty(node);
},
/**
* Get the data associated with a node name
*/
getNodeData: function (node) {
if (this.hasNode(node)) {
return this.nodes[node];
} else {
throw new Error("Node does not exist: " + node);
}
},
/**
* Set the associated data for a given node name. If the node does not exist, this method will throw an error
*/
setNodeData: function (node, data) {
if (this.hasNode(node)) {
this.nodes[node] = data;
} else {
throw new Error("Node does not exist: " + node);
}
},
/**
* Add a dependency between two nodes. If either of the nodes does not exist,
* an Error will be thrown.
*/
addDependency: function (from, to) {
if (!this.hasNode(from)) {
throw new Error("Node does not exist: " + from);
}
if (!this.hasNode(to)) {
throw new Error("Node does not exist: " + to);
}
if (this.outgoingEdges[from].indexOf(to) === -1) {
this.outgoingEdges[from].push(to);
}
if (this.incomingEdges[to].indexOf(from) === -1) {
this.incomingEdges[to].push(from);
}
return true;
},
/**
* Remove a dependency between two nodes.
*/
removeDependency: function (from, to) {
var idx;
if (this.hasNode(from)) {
idx = this.outgoingEdges[from].indexOf(to);
if (idx >= 0) {
this.outgoingEdges[from].splice(idx, 1);
}
}
if (this.hasNode(to)) {
idx = this.incomingEdges[to].indexOf(from);
if (idx >= 0) {
this.incomingEdges[to].splice(idx, 1);
}
}
},
/**
* Return a clone of the dependency graph. If any custom data is attached
* to the nodes, it will only be shallow copied.
*/
clone: function () {
var source = this;
var result = new DepGraph();
var keys = Object.keys(source.nodes);
keys.forEach(function (n) {
result.nodes[n] = source.nodes[n];
result.outgoingEdges[n] = source.outgoingEdges[n].slice(0);
result.incomingEdges[n] = source.incomingEdges[n].slice(0);
});
return result;
},
/**
* Get an array containing the direct dependencies of the specified node.
*
* Throws an Error if the specified node does not exist.
*/
directDependenciesOf: function (node) {
if (this.hasNode(node)) {
return this.outgoingEdges[node].slice(0);
} else {
throw new Error("Node does not exist: " + node);
}
},
/**
* Get an array containing the nodes that directly depend on the specified node.
*
* Throws an Error if the specified node does not exist.
*/
directDependantsOf: function (node) {
if (this.hasNode(node)) {
return this.incomingEdges[node].slice(0);
} else {
throw new Error("Node does not exist: " + node);
}
},
/**
* Get an array containing the nodes that the specified node depends on (transitively).
*
* Throws an Error if the graph has a cycle, or the specified node does not exist.
*
* If `leavesOnly` is true, only nodes that do not depend on any other nodes will be returned
* in the array.
*/
dependenciesOf: function (node, leavesOnly) {
if (this.hasNode(node)) {
var result = [];
var DFS = createDFS(
this.outgoingEdges,
leavesOnly,
result,
this.circular
);
DFS(node);
var idx = result.indexOf(node);
if (idx >= 0) {
result.splice(idx, 1);
}
return result;
} else {
throw new Error("Node does not exist: " + node);
}
},
/**
* get an array containing the nodes that depend on the specified node (transitively).
*
* Throws an Error if the graph has a cycle, or the specified node does not exist.
*
* If `leavesOnly` is true, only nodes that do not have any dependants will be returned in the array.
*/
dependantsOf: function (node, leavesOnly) {
if (this.hasNode(node)) {
var result = [];
var DFS = createDFS(
this.incomingEdges,
leavesOnly,
result,
this.circular
);
DFS(node);
var idx = result.indexOf(node);
if (idx >= 0) {
result.splice(idx, 1);
}
return result;
} else {
throw new Error("Node does not exist: " + node);
}
},
/**
* Construct the overall processing order for the dependency graph.
*
* Throws an Error if the graph has a cycle.
*
* If `leavesOnly` is true, only nodes that do not depend on any other nodes will be returned.
*/
overallOrder: function (leavesOnly) {
var self = this;
var result = [];
var keys = Object.keys(this.nodes);
if (keys.length === 0) {
return result; // Empty graph
} else {
if (!this.circular) {
// Look for cycles - we run the DFS starting at all the nodes in case there
// are several disconnected subgraphs inside this dependency graph.
var CycleDFS = createDFS(this.outgoingEdges, false, [], this.circular);
keys.forEach(function (n) {
CycleDFS(n);
});
}
var DFS = createDFS(
this.outgoingEdges,
leavesOnly,
result,
this.circular
);
// Find all potential starting points (nodes with nothing depending on them) an
// run a DFS starting at these points to get the order
keys
.filter(function (node) {
return self.incomingEdges[node].length === 0;
})
.forEach(function (n) {
DFS(n);
});
// If we're allowing cycles - we need to run the DFS against any remaining
// nodes that did not end up in the initial result (as they are part of a
// subgraph that does not have a clear starting point)
if (this.circular) {
keys
.filter(function (node) {
return result.indexOf(node) === -1;
})
.forEach(function (n) {
DFS(n);
});
}
return result;
}
},
/**
* Get an array of nodes that have no dependants (i.e. nothing depends on them).
*/
entryNodes: function () {
var self = this;
return Object.keys(this.nodes).filter(function (node) {
return self.incomingEdges[node].length === 0;
});
}
};
// Create some aliases
DepGraph.prototype.directDependentsOf = DepGraph.prototype.directDependantsOf;
DepGraph.prototype.dependentsOf = DepGraph.prototype.dependantsOf;
/**
* Cycle error, including the path of the cycle.
*/
var DepGraphCycleError = (exports.DepGraphCycleError = function (cyclePath) {
var message = "Dependency Cycle Found: " + cyclePath.join(" -> ");
var instance = new Error(message);
instance.cyclePath = cyclePath;
Object.setPrototypeOf(instance, Object.getPrototypeOf(this));
if (Error.captureStackTrace) {
Error.captureStackTrace(instance, DepGraphCycleError);
}
return instance;
});
DepGraphCycleError.prototype = Object.create(Error.prototype, {
constructor: {
value: Error,
enumerable: false,
writable: true,
configurable: true
}
});
Object.setPrototypeOf(DepGraphCycleError, Error);

View File

@@ -0,0 +1,127 @@
declare module 'dependency-graph' {
export interface Options {
circular?: boolean;
}
export class DepGraph<T> {
/**
* Creates an instance of DepGraph with optional Options.
*/
constructor(opts?: Options);
/**
* The number of nodes in the graph.
*/
size(): number;
/**
* Add a node in the graph with optional data. If data is not given, name will be used as data.
* @param {string} name
* @param data
*/
addNode(name: string, data?: T): void;
/**
* Remove a node from the graph.
* @param {string} name
*/
removeNode(name: string): void;
/**
* Check if a node exists in the graph.
* @param {string} name
*/
hasNode(name: string): boolean;
/**
* Get the data associated with a node (will throw an Error if the node does not exist).
* @param {string} name
*/
getNodeData(name: string): T;
/**
* Set the data for an existing node (will throw an Error if the node does not exist).
* @param {string} name
* @param data
*/
setNodeData(name: string, data?: T): void;
/**
* Add a dependency between two nodes (will throw an Error if one of the nodes does not exist).
* @param {string} from
* @param {string} to
*/
addDependency(from: string, to: string): void;
/**
* Remove a dependency between two nodes.
* @param {string} from
* @param {string} to
*/
removeDependency(from: string, to: string): void;
/**
* Return a clone of the dependency graph (If any custom data is attached
* to the nodes, it will only be shallow copied).
*/
clone(): DepGraph<T>;
/**
* Get an array containing the direct dependency nodes of the specified node.
* @param name
*/
directDependenciesOf(name: string): string[];
/**
* Get an array containing the nodes that directly depend on the specified node.
* @param name
*/
directDependantsOf(name: string): string[];
/**
* Alias of `directDependantsOf`
*
* @see directDependantsOf
* @param {string} name
*/
directDependentsOf(name: string): string[];
/**
* Get an array containing the nodes that the specified node depends on (transitively). If leavesOnly is true, only nodes that do not depend on any other nodes will be returned in the array.
* @param {string} name
* @param {boolean} leavesOnly
*/
dependenciesOf(name: string, leavesOnly?: boolean): string[];
/**
* Get an array containing the nodes that depend on the specified node (transitively). If leavesOnly is true, only nodes that do not have any dependants will be returned in the array.
* @param {string} name
* @param {boolean} leavesOnly
*/
dependantsOf(name: string, leavesOnly?: boolean): string[];
/**
* Alias of `dependantsOf`
*
* @see dependantsOf
* @param name
* @param leavesOnly
*/
dependentsOf(name: string, leavesOnly?: boolean): string[];
/**
* Get an array of nodes that have no dependants (i.e. nothing depends on them).
*/
entryNodes(): string[];
/**
* Construct the overall processing order for the dependency graph. If leavesOnly is true, only nodes that do not depend on any other nodes will be returned.
* @param {boolean} leavesOnly
*/
overallOrder(leavesOnly?: boolean): string[];
}
export class DepGraphCycleError extends Error {
cyclePath: string[];
}
}

View File

@@ -0,0 +1,31 @@
{
"name": "dependency-graph",
"description": "Simple dependency graph.",
"version": "0.11.0",
"author": "Jim Riecken <jriecken@gmail.com>",
"keywords": [
"dependency",
"graph"
],
"license": "MIT",
"repository": {
"type": "git",
"url": "git://github.com/jriecken/dependency-graph.git"
},
"bugs": {
"url": "http://github.com/jriecken/dependency-graph/issues"
},
"main": "./lib/dep_graph.js",
"scripts": {
"test": "jasmine specs/**/*.js"
},
"dependencies": {},
"optionalDependencies": {},
"devDependencies": {
"jasmine": "3.5.0"
},
"engines": {
"node": ">= 0.6.0"
},
"types": "./lib/index.d.ts"
}

View File

@@ -0,0 +1,542 @@
var dep_graph = require("../lib/dep_graph");
var DepGraph = dep_graph.DepGraph;
describe("DepGraph", function () {
it("should be able to add/remove nodes", function () {
var graph = new DepGraph();
graph.addNode("Foo");
graph.addNode("Bar");
expect(graph.hasNode("Foo")).toBeTrue();
expect(graph.hasNode("Bar")).toBeTrue();
expect(graph.hasNode("NotThere")).toBeFalse();
graph.removeNode("Bar");
expect(graph.hasNode("Bar")).toBeFalse();
});
it("should calculate its size", function () {
var graph = new DepGraph();
expect(graph.size()).toBe(0);
graph.addNode("Foo");
graph.addNode("Bar");
expect(graph.size()).toBe(2);
graph.removeNode("Bar");
expect(graph.size()).toBe(1);
});
it("should treat the node data parameter as optional and use the node name as data if node data was not given", function () {
var graph = new DepGraph();
graph.addNode("Foo");
expect(graph.getNodeData("Foo")).toBe("Foo");
});
it("should be able to associate a node name with data on node add", function () {
var graph = new DepGraph();
graph.addNode("Foo", "data");
expect(graph.getNodeData("Foo")).toBe("data");
});
it("should be able to add undefined as node data", function () {
var graph = new DepGraph();
graph.addNode("Foo", undefined);
expect(graph.getNodeData("Foo")).toBeUndefined();
});
it("should return true when using hasNode with a node which has falsy data", function () {
var graph = new DepGraph();
var falsyData = ["", 0, null, undefined, false];
graph.addNode("Foo");
falsyData.forEach(function (data) {
graph.setNodeData("Foo", data);
expect(graph.hasNode("Foo")).toBeTrue();
// Just an extra check to make sure that the saved data is correct
expect(graph.getNodeData("Foo")).toBe(data);
});
});
it("should be able to set data after a node was added", function () {
var graph = new DepGraph();
graph.addNode("Foo", "data");
graph.setNodeData("Foo", "data2");
expect(graph.getNodeData("Foo")).toBe("data2");
});
it("should throw an error if we try to set data for a non-existing node", function () {
var graph = new DepGraph();
expect(function () {
graph.setNodeData("Foo", "data");
}).toThrow(new Error("Node does not exist: Foo"));
});
it("should throw an error if the node does not exists and we try to get data", function () {
var graph = new DepGraph();
expect(function () {
graph.getNodeData("Foo");
}).toThrow(new Error("Node does not exist: Foo"));
});
it("should do nothing if creating a node that already exists", function () {
var graph = new DepGraph();
graph.addNode("a");
graph.addNode("b");
graph.addDependency("a", "b");
graph.addNode("a");
expect(graph.dependenciesOf("a")).toEqual(["b"]);
});
it("should do nothing if removing a node that does not exist", function () {
var graph = new DepGraph();
graph.addNode("a");
expect(graph.hasNode("a")).toBeTrue();
graph.removeNode("a");
expect(graph.hasNode("Foo")).toBeFalse();
graph.removeNode("a");
expect(graph.hasNode("Foo")).toBeFalse();
});
it("should be able to add dependencies between nodes", function () {
var graph = new DepGraph();
graph.addNode("a");
graph.addNode("b");
graph.addNode("c");
graph.addDependency("a", "b");
graph.addDependency("a", "c");
expect(graph.dependenciesOf("a")).toEqual(["b", "c"]);
});
it("should find entry nodes", function () {
var graph = new DepGraph();
graph.addNode("a");
graph.addNode("b");
graph.addNode("c");
graph.addDependency("a", "b");
graph.addDependency("a", "c");
expect(graph.entryNodes()).toEqual(["a"]);
});
it("should throw an error if a node does not exist and a dependency is added", function () {
var graph = new DepGraph();
graph.addNode("a");
expect(function () {
graph.addDependency("a", "b");
}).toThrow(new Error("Node does not exist: b"));
});
it("should detect cycles", function () {
var graph = new DepGraph();
graph.addNode("a");
graph.addNode("b");
graph.addNode("c");
graph.addNode("d");
graph.addDependency("a", "b");
graph.addDependency("b", "c");
graph.addDependency("c", "a");
graph.addDependency("d", "a");
expect(function () {
graph.dependenciesOf("b");
}).toThrow(new dep_graph.DepGraphCycleError(["b", "c", "a", "b"]));
});
it("should allow cycles when configured", function () {
var graph = new DepGraph({ circular: true });
graph.addNode("a");
graph.addNode("b");
graph.addNode("c");
graph.addNode("d");
graph.addDependency("a", "b");
graph.addDependency("b", "c");
graph.addDependency("c", "a");
graph.addDependency("d", "a");
expect(graph.dependenciesOf("b")).toEqual(["a", "c"]);
expect(graph.overallOrder()).toEqual(["c", "b", "a", "d"]);
});
it(
"should include all nodes in overall order even from " +
"cycles in disconnected subgraphs when circular is true",
function () {
var graph = new DepGraph({ circular: true });
graph.addNode("2a");
graph.addNode("2b");
graph.addNode("2c");
graph.addDependency("2a", "2b");
graph.addDependency("2b", "2c");
graph.addDependency("2c", "2a");
graph.addNode("1a");
graph.addNode("1b");
graph.addNode("1c");
graph.addNode("1d");
graph.addNode("1e");
graph.addDependency("1a", "1b");
graph.addDependency("1a", "1c");
graph.addDependency("1b", "1c");
graph.addDependency("1c", "1d");
expect(graph.overallOrder()).toEqual([
"1d",
"1c",
"1b",
"1a",
"1e",
"2c",
"2b",
"2a"
]);
}
);
it("should detect cycles in overall order", function () {
var graph = new DepGraph();
graph.addNode("a");
graph.addNode("b");
graph.addNode("c");
graph.addNode("d");
graph.addDependency("a", "b");
graph.addDependency("b", "c");
graph.addDependency("c", "a");
graph.addDependency("d", "a");
expect(function () {
graph.overallOrder();
}).toThrow(new dep_graph.DepGraphCycleError(["a", "b", "c", "a"]));
});
it("should detect cycles in overall order when all nodes have dependants (incoming edges)", function () {
var graph = new DepGraph();
graph.addNode("a");
graph.addNode("b");
graph.addNode("c");
graph.addDependency("a", "b");
graph.addDependency("b", "c");
graph.addDependency("c", "a");
expect(function () {
graph.overallOrder();
}).toThrow(new dep_graph.DepGraphCycleError(["a", "b", "c", "a"]));
});
it(
"should detect cycles in overall order when there are several " +
"disconnected subgraphs (with one that does not have a cycle",
function () {
var graph = new DepGraph();
graph.addNode("a_1");
graph.addNode("a_2");
graph.addNode("b_1");
graph.addNode("b_2");
graph.addNode("b_3");
graph.addDependency("a_1", "a_2");
graph.addDependency("b_1", "b_2");
graph.addDependency("b_2", "b_3");
graph.addDependency("b_3", "b_1");
expect(function () {
graph.overallOrder();
}).toThrow(
new dep_graph.DepGraphCycleError(["b_1", "b_2", "b_3", "b_1"])
);
}
);
it("should retrieve dependencies and dependants in the correct order", function () {
var graph = new DepGraph();
graph.addNode("a");
graph.addNode("b");
graph.addNode("c");
graph.addNode("d");
graph.addDependency("a", "d");
graph.addDependency("a", "b");
graph.addDependency("b", "c");
graph.addDependency("d", "b");
expect(graph.dependenciesOf("a")).toEqual(["c", "b", "d"]);
expect(graph.dependenciesOf("b")).toEqual(["c"]);
expect(graph.dependenciesOf("c")).toEqual([]);
expect(graph.dependenciesOf("d")).toEqual(["c", "b"]);
expect(graph.dependantsOf("a")).toEqual([]);
expect(graph.dependantsOf("b")).toEqual(["a", "d"]);
expect(graph.dependantsOf("c")).toEqual(["a", "d", "b"]);
expect(graph.dependantsOf("d")).toEqual(["a"]);
// check the alias "dependentsOf"
expect(graph.dependentsOf("a")).toEqual([]);
expect(graph.dependentsOf("b")).toEqual(["a", "d"]);
expect(graph.dependentsOf("c")).toEqual(["a", "d", "b"]);
expect(graph.dependentsOf("d")).toEqual(["a"]);
});
it("should be able to retrieve direct dependencies/dependants", function () {
var graph = new DepGraph();
graph.addNode("a");
graph.addNode("b");
graph.addNode("c");
graph.addNode("d");
graph.addDependency("a", "d");
graph.addDependency("a", "b");
graph.addDependency("b", "c");
graph.addDependency("d", "b");
expect(graph.directDependenciesOf("a")).toEqual(["d", "b"]);
expect(graph.directDependenciesOf("b")).toEqual(["c"]);
expect(graph.directDependenciesOf("c")).toEqual([]);
expect(graph.directDependenciesOf("d")).toEqual(["b"]);
expect(graph.directDependantsOf("a")).toEqual([]);
expect(graph.directDependantsOf("b")).toEqual(["a", "d"]);
expect(graph.directDependantsOf("c")).toEqual(["b"]);
expect(graph.directDependantsOf("d")).toEqual(["a"]);
// check the alias "directDependentsOf"
expect(graph.directDependentsOf("a")).toEqual([]);
expect(graph.directDependentsOf("b")).toEqual(["a", "d"]);
expect(graph.directDependentsOf("c")).toEqual(["b"]);
expect(graph.directDependentsOf("d")).toEqual(["a"]);
});
it("should be able to resolve the overall order of things", function () {
var graph = new DepGraph();
graph.addNode("a");
graph.addNode("b");
graph.addNode("c");
graph.addNode("d");
graph.addNode("e");
graph.addDependency("a", "b");
graph.addDependency("a", "c");
graph.addDependency("b", "c");
graph.addDependency("c", "d");
expect(graph.overallOrder()).toEqual(["d", "c", "b", "a", "e"]);
});
it('should be able to only retrieve the "leaves" in the overall order', function () {
var graph = new DepGraph();
graph.addNode("a");
graph.addNode("b");
graph.addNode("c");
graph.addNode("d");
graph.addNode("e");
graph.addDependency("a", "b");
graph.addDependency("a", "c");
graph.addDependency("b", "c");
graph.addDependency("c", "d");
expect(graph.overallOrder(true)).toEqual(["d", "e"]);
});
it("should be able to give the overall order for a graph with several disconnected subgraphs", function () {
var graph = new DepGraph();
graph.addNode("a_1");
graph.addNode("a_2");
graph.addNode("b_1");
graph.addNode("b_2");
graph.addNode("b_3");
graph.addDependency("a_1", "a_2");
graph.addDependency("b_1", "b_2");
graph.addDependency("b_2", "b_3");
expect(graph.overallOrder()).toEqual(["a_2", "a_1", "b_3", "b_2", "b_1"]);
});
it("should give an empty overall order for an empty graph", function () {
var graph = new DepGraph();
expect(graph.overallOrder()).toEqual([]);
});
it("should still work after nodes are removed", function () {
var graph = new DepGraph();
graph.addNode("a");
graph.addNode("b");
graph.addNode("c");
graph.addDependency("a", "b");
graph.addDependency("b", "c");
expect(graph.dependenciesOf("a")).toEqual(["c", "b"]);
graph.removeNode("c");
expect(graph.dependenciesOf("a")).toEqual(["b"]);
});
it("should clone an empty graph", function () {
var graph = new DepGraph();
expect(graph.size()).toEqual(0);
var cloned = graph.clone();
expect(cloned.size()).toEqual(0);
expect(graph === cloned).toBeFalse();
});
it("should clone a non-empty graph", function () {
var graph = new DepGraph();
graph.addNode("a");
graph.addNode("b");
graph.addNode("c");
graph.addDependency("a", "b");
graph.addDependency("b", "c");
var cloned = graph.clone();
expect(graph === cloned).toBeFalse();
expect(cloned.hasNode("a")).toBeTrue();
expect(cloned.hasNode("b")).toBeTrue();
expect(cloned.hasNode("c")).toBeTrue();
expect(cloned.dependenciesOf("a")).toEqual(["c", "b"]);
expect(cloned.dependantsOf("c")).toEqual(["a", "b"]);
// Changes to the original graph shouldn't affect the clone
graph.removeNode("c");
expect(graph.dependenciesOf("a")).toEqual(["b"]);
expect(cloned.dependenciesOf("a")).toEqual(["c", "b"]);
graph.addNode("d");
graph.addDependency("b", "d");
expect(graph.dependenciesOf("a")).toEqual(["d", "b"]);
expect(cloned.dependenciesOf("a")).toEqual(["c", "b"]);
});
it("should only be a shallow clone", function () {
var graph = new DepGraph();
var data = { a: 42 };
graph.addNode("a", data);
var cloned = graph.clone();
expect(graph === cloned).toBeFalse();
expect(graph.getNodeData("a") === cloned.getNodeData("a")).toBeTrue();
graph.getNodeData("a").a = 43;
expect(cloned.getNodeData("a").a).toBe(43);
cloned.setNodeData("a", { a: 42 });
expect(cloned.getNodeData("a").a).toBe(42);
expect(graph.getNodeData("a") === cloned.getNodeData("a")).toBeFalse();
});
});
describe("DepGraph Performance", function () {
it("should not exceed max call stack with a very deep graph", function () {
var g = new DepGraph();
var expected = [];
for (var i = 0; i < 100000; i++) {
var istr = i.toString();
g.addNode(istr);
expected.push(istr);
if (i > 0) {
g.addDependency(istr, (i - 1).toString());
}
}
var order = g.overallOrder();
expect(order).toEqual(expected);
});
it("should run an a reasonable amount of time for a very large graph", function () {
var randInt = function (min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
};
var g = new DepGraph();
var nodes = [];
// Create a graph with 100000 nodes in it with 10 random connections to
// lower numbered nodes
for (var i = 0; i < 100000; i++) {
nodes.push(i.toString());
g.addNode(i.toString());
for (var j = 0; j < 10; j++) {
var dep = randInt(0, i);
if (i !== dep) {
g.addDependency(i.toString(), dep.toString());
}
}
}
var start = new Date().getTime();
g.overallOrder();
var end = new Date().getTime();
expect(start - end).toBeLessThan(1000);
});
});
describe("DepGraphCycleError", function () {
var DepGraphCycleError = dep_graph.DepGraphCycleError;
it("should have a message", function () {
var err = new DepGraphCycleError(["a", "b", "c", "a"]);
expect(err.message).toEqual("Dependency Cycle Found: a -> b -> c -> a");
});
it("should be an instanceof DepGraphCycleError", function () {
var err = new DepGraphCycleError(["a", "b", "c", "a"]);
expect(err instanceof DepGraphCycleError).toBeTrue();
expect(err instanceof Error).toBeTrue();
});
it("should have a cyclePath", function () {
var cyclePath = ["a", "b", "c", "a"];
var err = new DepGraphCycleError(cyclePath);
expect(err.cyclePath).toEqual(cyclePath);
});
});

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

@@ -0,0 +1,36 @@
{
"name": "@11ty/dependency-tree-esm",
"version": "1.0.0",
"description": "Finds all JavaScript ES Module dependencies from a filename.",
"main": "main.js",
"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",
"dependencies": {
"@11ty/eleventy-utils": "^1.0.2",
"acorn": "^8.10.0",
"dependency-graph": "^0.11.0",
"normalize-path": "^3.0.0"
},
"devDependencies": {
"ava": "^5.3.1"
},
"ava": {
"files": [
"./test/*.js"
],
"ignoredByWatcher": [
"./test/stubs/**"
]
}
}

View File

@@ -0,0 +1 @@
import "./circular-parent.js";

View File

@@ -0,0 +1 @@
import "./circular-child.js";

View File

@@ -0,0 +1,2 @@
import "./circular-self.js";
import "./empty.js";

View File

View File

@@ -0,0 +1,2 @@
import fs from "fs";
import * as fdklsjf from "./imported-secondary.js";

View File

@@ -0,0 +1,3 @@
import "fs";
export function hello() {}

View File

@@ -0,0 +1,3 @@
import * as fdklsjf from "./imported-secondary.js";
export function hello() {}

View File

@@ -0,0 +1 @@
import * as fdklsjf from "./nested.js";

View File

@@ -0,0 +1,2 @@
import fs from "fs";
import * as fdklsjf from "./imported.js";

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

@@ -0,0 +1,30 @@
const test = require("ava");
const { find } = require("../main.js");
test("Empty", async t => {
t.deepEqual(await find("./test/stubs/empty.js"), []);
});
test("Doesnt exist", async t => {
t.deepEqual(await find("./test/stubs/THIS_FILE_DOES_NOT_EXIST.js"), []);
});
test("Simple", async t => {
t.deepEqual(await find("./test/stubs/file.js"), ["./test/stubs/imported-secondary.js"]);
});
test("Nested two deep", async t => {
t.deepEqual(await find("./test/stubs/nested.js"), ["./test/stubs/imported.js", "./test/stubs/imported-secondary.js"]);
});
test("Nested three deep", async t => {
t.deepEqual(await find("./test/stubs/nested-grandchild.js"), ["./test/stubs/nested.js", "./test/stubs/imported.js", "./test/stubs/imported-secondary.js"]);
});
test("Circular", async t => {
t.deepEqual(await find("./test/stubs/circular-parent.js"), ["./test/stubs/circular-child.js"]);
});
test("Circular Self Reference", async t => {
t.deepEqual(await find("./test/stubs/circular-self.js"), ["./test/stubs/empty.js"]);
});

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.

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

@@ -0,0 +1,94 @@
# `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: [`dependency-tree-esm`](https://github.com/11ty/eleventy-dependency-tree-esm) for ES Modules.
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.

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

@@ -0,0 +1,132 @@
const path = require("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)
try {
require(absoluteFilename);
} 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(mod.children) {
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] ) {
for(let dependency of getDependenciesFor(relativeChildFilename, avoidCircular, options)) {
dependencies.add(dependency);
}
}
}
}
}
}
return dependencies;
}
function getCleanDependencyListFor(filename, options = {}) {
let deps = Array.from( getDependenciesFor(filename, null, options) );
return deps.map(filePath => {
if(filePath.startsWith("./")) {
return TemplatePath.standardizeFilePath(filePath);
}
return filePath; // node_module name
});
}
module.exports = getCleanDependencyListFor;
module.exports.getNodeModuleName = getNodeModuleName;

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

@@ -0,0 +1,39 @@
{
"name": "@11ty/dependency-tree",
"version": "3.0.1",
"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"
],
"ignoredByWatcher": [
"./test/stubs/**"
]
},
"devDependencies": {
"@sindresorhus/is": "^4.6.0",
"ava": "^5.3.1"
},
"dependencies": {
"@11ty/eleventy-utils": "^1.0.2"
}
}

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,294 @@
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 isErasing = oldUrl.searchParams.has("_11ty") && !newUrl.searchParams.has("_11ty");
if(!isErasing) {
// not a match if _11ty has a new value (not being erased)
return false;
}
oldUrl.searchParams.set("_11ty", "");
newUrl.searchParams.set("_11ty", "");
// 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);
}
}
class EleventyReload {
constructor() {
this.connectionMessageShown = false;
this.reconnectEventCallback = this.reconnect.bind(this);
}
init(options = {}) {
if (!("WebSocket" in window)) {
return;
}
let { protocol, host } = new URL(document.location.href);
// 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 (subtype === "css") {
for (let link of document.querySelectorAll(`link[rel="stylesheet"]`)) {
if (link.href) {
let url = new URL(link.href);
url.searchParams.set("_11ty", Date.now());
link.href = url.toString();
}
}
Util.log(`CSS updated without page reload.`);
} else {
let morphed = false;
try {
if((build.templates || []).length > 0) {
// Important: using `./` in `./morphdom.js` allows the special `.11ty` folder to be changed upstream
const { default: morphdom } = await import(`./morphdom.js`);
// { url, inputPath, content }
for (let template of build.templates || []) {
if (template.url === document.location.pathname) {
// Importantly, if this does not match but is still relevant (layout/include/etc), a full reload happens below. This could be improved.
if ((files || []).includes(template.inputPath)) {
// Notable limitation: this wont re-run script elements or JavaScript page lifecycle events (load/DOMContentLoaded)
morphed = true;
morphdom(document.documentElement, template.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(template.content);
Util.log(`HTML delta applied without page reload.`);
}
break;
}
}
}
} catch(e) {
Util.error( "Morphdom error", e );
}
if (!morphed) {
Util.log(`Page reload initiated.`);
window.location.reload();
}
}
}
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)
}

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

@@ -0,0 +1,58 @@
{
"name": "@11ty/eleventy-dev-server",
"version": "2.0.4",
"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": "^1.0.3",
"chokidar": "^3.6.0",
"debug": "^4.3.7",
"dev-ip": "^1.0.1",
"finalhandler": "^1.3.0",
"mime": "^3.0.0",
"minimist": "^1.2.8",
"morphdom": "^2.7.4",
"please-upgrade-node": "^3.2.0",
"send": "^0.19.0",
"ssri": "^11.0.0",
"urlpattern-polyfill": "^10.0.0",
"ws": "^8.18.0"
},
"devDependencies": {
"ava": "^6.1.3"
}
}

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

@@ -0,0 +1,950 @@
const path = require("node:path");
const fs = require("node:fs");
const finalhandler = require("finalhandler");
const WebSocket = require("ws");
const { WebSocketServer } = WebSocket;
const mime = require("mime");
const ssri = require("ssri");
const send = require("send");
const devip = require("dev-ip");
const chokidar = require("chokidar");
const { TemplatePath, isPlainObject } = require("@11ty/eleventy-utils");
const debug = require("debug")("Eleventy:DevServer");
const pkg = require("./package.json");
const wrapResponse = require("./server/wrapResponse.js");
if (!globalThis.URLPattern) {
require("urlpattern-polyfill");
}
const DEFAULT_OPTIONS = {
port: 8080,
liveReload: true, // Enable live reload at all
showAllHosts: false, // IP address based hosts (other than localhost)
injectedScriptsFolder: ".11ty", // Change the name of the special folder used for injected scripts
portReassignmentRetryCount: 10, // number of times to increment the port if in use
https: {}, // `key` and `cert`, required for http/2 and https
domDiff: true, // Use morphdom to apply DOM diffing delta updates to HTML
showVersion: false, // Whether or not to show the server version on the command line.
encoding: "utf-8", // Default file encoding
pathPrefix: "/", // May be overridden by Eleventy, adds a virtual base directory to your project
watch: [], // Globs to pass to separate dev server chokidar for watching
aliases: {}, // Aliasing feature
indexFileName: "index.html", // Allow custom index file name
useCache: false, // Use a cache for file contents
headers: {}, // Set default response headers
messageOnStart: ({ hosts, startupTime, version, options }) => {
let hostsStr = " started";
if(Array.isArray(hosts) && hosts.length > 0) {
// TODO what happens when the cert doesnt cover non-localhost hosts?
hostsStr = ` at ${hosts.join(" or ")}`;
}
return `Server${hostsStr}${options.showVersion ? ` (v${version})` : ""}`;
},
onRequest: {}, // Maps URLPatterns to dynamic callback functions that run on a request from a client.
// Example:
// "/foo/:name": function({ url, pattern, patternGroups }) {
// return {
// headers: {
// "Content-Type": "text/html",
// },
// body: `${url} ${JSON.stringify(patternGroups)}`
// }
// }
// Logger (fancier one is injected by Eleventy)
logger: {
info: console.log,
log: console.log,
error: console.error,
}
}
class EleventyDevServer {
static getServer(...args) {
return new EleventyDevServer(...args);
}
constructor(name, dir, options = {}) {
debug("Creating new Dev Server instance.")
this.name = name;
this.normalizeOptions(options);
this.fileCache = {};
// Directory to serve
if(!dir) {
throw new Error("Missing `dir` to serve.");
}
this.dir = dir;
this.logger = this.options.logger;
if(this.options.watch.length > 0) {
this.getWatcher();
}
}
normalizeOptions(options = {}) {
this.options = Object.assign({}, DEFAULT_OPTIONS, options);
// better names for options https://github.com/11ty/eleventy-dev-server/issues/41
if(options.folder !== undefined) {
this.options.injectedScriptsFolder = options.folder;
delete this.options.folder;
}
if(options.domdiff !== undefined) {
this.options.domDiff = options.domdiff;
delete this.options.domdiff;
}
if(options.enabled !== undefined) {
this.options.liveReload = options.enabled;
delete this.options.enabled;
}
this.options.pathPrefix = this.cleanupPathPrefix(this.options.pathPrefix);
}
get watcher() {
if(!this._watcher) {
debug("Watching %O", this.options.watch);
// TODO if using Eleventy and `watch` option includes output folder (_site) this will trigger two update events!
this._watcher = chokidar.watch(this.options.watch, {
// TODO allow chokidar configuration extensions (or re-use the ones in Eleventy)
ignored: ["**/node_modules/**", ".git"],
ignoreInitial: true,
// same values as Eleventy
awaitWriteFinish: {
stabilityThreshold: 150,
pollInterval: 25,
},
});
this._watcher.on("change", (path) => {
this.logger.log( `File changed: ${path} (skips build)` );
this.reloadFiles([path]);
});
this._watcher.on("add", (path) => {
this.logger.log( `File added: ${path} (skips build)` );
this.reloadFiles([path]);
});
}
return this._watcher;
}
getWatcher() {
return this.watcher;
}
watchFiles(files) {
if(Array.isArray(files)) {
files = files.map(entry => TemplatePath.stripLeadingDotSlash(entry));
debug("Also watching %O", files);
this.watcher.add(files);
}
}
cleanupPathPrefix(pathPrefix) {
if(!pathPrefix || pathPrefix === "/") {
return "/";
}
if(!pathPrefix.startsWith("/")) {
pathPrefix = `/${pathPrefix}`
}
if(!pathPrefix.endsWith("/")) {
pathPrefix = `${pathPrefix}/`;
}
return pathPrefix;
}
// Allowed list of files that can be served from outside `dir`
setAliases(aliases) {
if(aliases) {
this.passthroughAliases = aliases;
debug( "Setting aliases (emulated passthrough copy) %O", aliases );
}
}
matchPassthroughAlias(url) {
let aliases = Object.assign({}, this.options.aliases, this.passthroughAliases);
for(let targetUrl in aliases) {
if(!targetUrl) {
continue;
}
let file = aliases[targetUrl];
if(url.startsWith(targetUrl)) {
let inputDirectoryPath = file + url.slice(targetUrl.length);
// e.g. addPassthroughCopy("img/") but <img src="/img/built/IdthKOzqFA-350.png">
// generated by the image plugin (written to the output folder)
// If they do not exist in the input directory, this will fallback to the output directory.
if(fs.existsSync(inputDirectoryPath)) {
return inputDirectoryPath;
}
}
}
return false;
}
isFileInDirectory(dir, file) {
let absoluteDir = TemplatePath.absolutePath(dir);
let absoluteFile = TemplatePath.absolutePath(file);
return absoluteFile.startsWith(absoluteDir);
}
getOutputDirFilePath(filepath, filename = "") {
let computedPath;
if(filename === ".html") {
// avoid trailing slash for filepath/.html requests
let prefix = path.join(this.dir, filepath);
if(prefix.endsWith(path.sep)) {
prefix = prefix.substring(0, prefix.length - path.sep.length);
}
computedPath = prefix + filename;
} else {
computedPath = path.join(this.dir, filepath, filename);
}
computedPath = decodeURIComponent(computedPath);
if(!filename) { // is a direct URL request (not an implicit .html or index.html add)
let alias = this.matchPassthroughAlias(filepath);
if(alias) {
if(!this.isFileInDirectory(path.resolve("."), alias)) {
throw new Error("Invalid path");
}
return alias;
}
}
// Check that the file is in the output path (error if folks try use `..` in the filepath)
if(!this.isFileInDirectory(this.dir, computedPath)) {
throw new Error("Invalid path");
}
return computedPath;
}
isOutputFilePathExists(rawPath) {
return fs.existsSync(rawPath) && !TemplatePath.isDirectorySync(rawPath);
}
/* Use conventions documented here https://www.zachleat.com/web/trailing-slash/
* resource.html exists:
* /resource matches
* /resource/ redirects to /resource
* resource/index.html exists:
* /resource redirects to /resource/
* /resource/ matches
* both resource.html and resource/index.html exists:
* /resource matches /resource.html
* /resource/ matches /resource/index.html
*/
mapUrlToFilePath(url) {
// Note: `localhost` is not important here, any host would work
let u = new URL(url, "http://localhost/");
url = u.pathname;
// Remove PathPrefix from start of URL
if (this.options.pathPrefix !== "/") {
// Requests to root should redirect to new pathPrefix
if(url === "/") {
return {
statusCode: 302,
url: this.options.pathPrefix,
}
}
// Requests to anything outside of root should fail with 404
if (!url.startsWith(this.options.pathPrefix)) {
return {
statusCode: 404,
};
}
url = url.slice(this.options.pathPrefix.length - 1);
}
let rawPath = this.getOutputDirFilePath(url);
if (this.isOutputFilePathExists(rawPath)) {
return {
statusCode: 200,
filepath: rawPath,
};
}
let indexHtmlPath = this.getOutputDirFilePath(url, this.options.indexFileName);
let indexHtmlExists = fs.existsSync(indexHtmlPath);
let htmlPath = this.getOutputDirFilePath(url, ".html");
let htmlExists = fs.existsSync(htmlPath);
// /resource/ => /resource/index.html
if (indexHtmlExists && url.endsWith("/")) {
return {
statusCode: 200,
filepath: indexHtmlPath,
};
}
// /resource => resource.html
if (htmlExists && !url.endsWith("/")) {
return {
statusCode: 200,
filepath: htmlPath,
};
}
// /resource => redirect to /resource/
if (indexHtmlExists && !url.endsWith("/")) {
return {
statusCode: 301,
url: u.pathname + "/",
};
}
// /resource/ => redirect to /resource
if (htmlExists && url.endsWith("/")) {
return {
statusCode: 301,
url: u.pathname.substring(0, u.pathname.length - 1),
};
}
return {
statusCode: 404,
};
}
_getFileContents(localpath, rootDir) {
if(this.options.useCache && this.fileCache[localpath]) {
return this.fileCache[localpath];
}
let filepath;
let searchLocations = [];
if(rootDir) {
searchLocations.push(TemplatePath.absolutePath(rootDir, localpath));
}
// fallbacks for file:../ installations
searchLocations.push(TemplatePath.absolutePath(__dirname, localpath));
searchLocations.push(TemplatePath.absolutePath(__dirname, "../../../", localpath));
for(let loc of searchLocations) {
if(fs.existsSync(loc)) {
filepath = loc;
break;
}
}
let contents = fs.readFileSync(filepath, {
encoding: this.options.encoding,
});
if(this.options.useCache) {
this.fileCache[localpath] = contents;
}
return contents;
}
augmentContentWithNotifier(content, inlineContents = false, options = {}) {
let { integrityHash, scriptContents } = options;
if(!scriptContents) {
scriptContents = this._getFileContents("./client/reload-client.js");
}
if(!integrityHash) {
integrityHash = ssri.fromData(scriptContents);
}
// This isnt super necessary because its a local file, but its included anyway
let script = `<script type="module" integrity="${integrityHash}"${inlineContents ? `>${scriptContents}` : ` src="/${this.options.injectedScriptsFolder}/reload-client.js">`}</script>`;
if (content.includes("</head>")) {
return content.replace("</head>", `${script}</head>`);
}
// If the HTML document contains an importmap, insert the module script after the importmap element
let importMapRegEx = /<script type=\\?importmap\\?[^>]*>(\n|.)*?<\/script>/gmi;
let importMapMatch = content.match(importMapRegEx)?.[0];
if (importMapMatch) {
return content.replace(importMapMatch, `${importMapMatch}${script}`);
}
// <title> is the only *required* element in an HTML document
if (content.includes("</title>")) {
return content.replace("</title>", `</title>${script}`);
}
// If youve reached this section, your HTML is invalid!
// We want to be super forgiving here, because folks might be in-progress editing the document!
if (content.includes("</body>")) {
return content.replace("</body>", `${script}</body>`);
}
if (content.includes("</html>")) {
return content.replace("</html>", `${script}</html>`);
}
if (content.includes("<!doctype html>")) {
return content.replace("<!doctype html>", `<!doctype html>${script}`);
}
// Notably, works without content at all!!
return (content || "") + script;
}
getFileContentType(filepath, res) {
let contentType = res.getHeader("Content-Type");
// Content-Type might be already set via middleware
if (contentType) {
return contentType;
}
let mimeType = mime.getType(filepath);
if (!mimeType) {
return;
}
contentType = mimeType;
// We only want to append charset if the header is not already set
if (contentType === "text/html") {
contentType = `text/html; charset=${this.options.encoding}`;
}
return contentType;
}
renderFile(filepath, res) {
let contents = fs.readFileSync(filepath);
let contentType = this.getFileContentType(filepath, res);
for(const [key, value] of Object.entries(this.options.headers)){
res.setHeader(key, value);
}
if (!contentType) {
return res.end(contents);
}
res.setHeader("Content-Type", contentType);
if (contentType.startsWith("text/html")) {
// the string is important here, wrapResponse expects strings internally for HTML content (for now)
return res.end(contents.toString());
}
return res.end(contents);
}
async eleventyDevServerMiddleware(req, res, next) {
for(let urlPatternString in this.options.onRequest) {
let fn = this.options.onRequest[urlPatternString];
let fullPath = this.getServerPath(urlPatternString);
let p = new URLPattern({ pathname: fullPath });
// request url should already include pathprefix.
let fullUrl = this.getServerUrlRaw("localhost", req.url);
let match = p.exec(fullUrl);
let u = new URL(fullUrl);
if(match) {
let result = await fn({
url: u,
pattern: p,
patternGroups: match?.pathname?.groups || {},
});
if(!result && result !== "") {
continue;
}
if(typeof result === "string") {
return res.end(result);
}
if(isPlainObject(result)) {
if(typeof result.status === "number") {
res.statusCode = result.status;
}
if(isPlainObject(result.headers)) {
for(let name in result.headers) {
res.setHeader(name, result.headers[name]);
}
}
return res.end(result.body || "");
}
throw new Error(`Invalid return type from \`onRequest\` pattern for ${urlPatternString}: expected string or object.`);
}
}
if(req.url === `/${this.options.injectedScriptsFolder}/reload-client.js`) {
if(this.options.liveReload) {
res.setHeader("Content-Type", mime.getType("js"));
return res.end(this._getFileContents("./client/reload-client.js"));
}
} else if(req.url === `/${this.options.injectedScriptsFolder}/morphdom.js`) {
if(this.options.domDiff) {
res.setHeader("Content-Type", mime.getType("js"));
return res.end(this._getFileContents("./node_modules/morphdom/dist/morphdom-esm.js", path.resolve(".")));
}
}
next();
}
// This runs at the end of the middleware chain
eleventyProjectMiddleware(req, res) {
// Known issue with `finalhandler` and HTTP/2:
// UnsupportedWarning: Status message is not supported by HTTP/2 (RFC7540 8.1.2.4)
// https://github.com/pillarjs/finalhandler/pull/34
let lastNext = finalhandler(req, res, {
onerror: (e) => {
if (e.statusCode === 404) {
let localPath = TemplatePath.stripLeadingSubPath(
e.path,
TemplatePath.absolutePath(this.dir)
);
this.logger.error(
`HTTP ${e.statusCode}: Template not found in output directory (${this.dir}): ${localPath}`
);
} else {
this.logger.error(`HTTP ${e.statusCode}: ${e.message}`);
}
},
});
// middleware (maybe a serverless request) already set a body upstream, skip this part
if(!res._shouldForceEnd) {
let match = this.mapUrlToFilePath(req.url);
debug( req.url, match );
if (match) {
// Content-Range request, probably Safari trying to stream video
if (req.headers.range) {
return send(req, match.filepath).pipe(res);
}
if (match.statusCode === 200 && match.filepath) {
return this.renderFile(match.filepath, res);
}
// Redirects, usually for trailing slash to .html stuff
if (match.url) {
res.statusCode = match.statusCode;
res.setHeader("Location", match.url);
return res.end();
}
let raw404Path = this.getOutputDirFilePath("404.html");
if(match.statusCode === 404 && this.isOutputFilePathExists(raw404Path)) {
res.statusCode = match.statusCode;
res.isCustomErrorPage = true;
return this.renderFile(raw404Path, res);
}
}
}
if(res.body && !res.bodyUsed) {
if(res._shouldForceEnd) {
res.end();
} else {
let err = new Error("A response was never written to the stream. Are you missing a server middleware with `res.end()`?");
err.statusCode = 500;
lastNext(err);
return;
}
}
lastNext();
}
async onRequestHandler (req, res) {
res = wrapResponse(res, content => {
// check to see if this is a client fetch and not a navigation
let isXHR = req.headers["sec-fetch-mode"] && req.headers["sec-fetch-mode"] != "navigate";
if(this.options.liveReload !== false && !isXHR) {
let scriptContents = this._getFileContents("./client/reload-client.js");
let integrityHash = ssri.fromData(scriptContents);
// Bare (not-custom) finalhandler error pages have a Content-Security-Policy `default-src 'none'` that
// prevents the client script from executing, so we override it
if(res.statusCode !== 200 && !res.isCustomErrorPage) {
res.setHeader("Content-Security-Policy", `script-src '${integrityHash}'`);
}
return this.augmentContentWithNotifier(content, res.statusCode !== 200, {
scriptContents,
integrityHash
});
}
return content;
});
let middlewares = this.options.middleware || [];
middlewares = middlewares.slice();
// TODO because this runs at the very end of the middleware chain,
// if we move the static stuff up in the order we could use middleware to modify
// the static content in middleware!
middlewares.push(this.eleventyProjectMiddleware);
middlewares.reverse();
// Runs very first in the middleware chain
middlewares.push(this.eleventyDevServerMiddleware);
let bound = [];
let next;
for(let ware of middlewares) {
let fn;
if(next) {
fn = ware.bind(this, req, res, next);
} else {
fn = ware.bind(this, req, res);
}
bound.push(fn);
next = fn;
}
bound.reverse();
let [first] = bound;
await first();
}
getHosts() {
let hosts = new Set();
if(this.options.showAllHosts) {
for(let host of devip()) {
hosts.add(this.getServerUrl(host));
}
}
hosts.add(this.getServerUrl("localhost"));
return Array.from(hosts);
}
get server() {
if (this._server) {
return this._server;
}
this.start = Date.now();
// Check for secure server requirements, otherwise use HTTP
let { key, cert } = this.options.https;
if(key && cert) {
const { createSecureServer } = require("http2");
let options = {
allowHTTP1: true,
// Credentials
key: fs.readFileSync(key),
cert: fs.readFileSync(cert),
};
this._server = createSecureServer(options, this.onRequestHandler.bind(this));
this._serverProtocol = "https:";
} else {
const { createServer } = require("http");
this._server = createServer(this.onRequestHandler.bind(this));
this._serverProtocol = "http:";
}
this.portRetryCount = 0;
this._server.on("error", (err) => {
if (err.code == "EADDRINUSE") {
if (this.portRetryCount < this.options.portReassignmentRetryCount) {
this.portRetryCount++;
debug(
"Server already using port %o, trying the next port %o. Retry number %o of %o",
err.port,
err.port + 1,
this.portRetryCount,
this.options.portReassignmentRetryCount
);
this._serverListen(err.port + 1);
} else {
throw new Error(
`Tried ${this.options.portReassignmentRetryCount} different ports but they were all in use. You can a different starter port using --port on the command line.`
);
}
} else {
this._serverErrorHandler(err);
}
});
this._server.on("listening", (e) => {
this.setupReloadNotifier();
let logMessageCallback = typeof this.options.messageOnStart === "function" ? this.options.messageOnStart : () => false;
let hosts = this.getHosts();
let message = logMessageCallback({
hosts,
localhostUrl: this.getServerUrl("localhost"),
options: this.options,
version: pkg.version,
startupTime: Date.now() - this.start,
});
if(message) {
this.logger.info(message);
}
});
return this._server;
}
_serverListen(port) {
this.server.listen({
port,
});
}
getServerPath(pathname) {
// duplicate slashes
if(this.options.pathPrefix.endsWith("/") && pathname.startsWith("/")) {
pathname = pathname.slice(1);
}
return `${this.options.pathPrefix}${pathname}`;
}
getServerUrlRaw(host, pathname = "", isRaw = true) {
if(!this._server || !this._serverProtocol) {
throw new Error("Access to `serverUrl` property not yet available.");
}
let { port } = this._server.address();
return `${this._serverProtocol}//${host}:${port}${isRaw ? pathname : this.getServerPath(pathname)}`;
}
getServerUrl(host, pathname = "") {
return this.getServerUrlRaw(host, pathname, false);
}
async getPort() {
return new Promise(resolve => {
this.server.on("listening", (e) => {
let { port } = this._server.address();
resolve(port);
});
})
}
serve(port) {
this.getWatcher();
this._serverListen(port);
}
_serverErrorHandler(err) {
if (err.code == "EADDRINUSE") {
this.logger.error(`Server error: Port in use ${err.port}`);
} else {
this.logger.error(`Server error: ${err.message}`);
}
}
// Websocket Notifications
setupReloadNotifier() {
let updateServer = new WebSocketServer({
// includes the port
server: this.server,
});
updateServer.on("connection", (ws) => {
this.sendUpdateNotification({
type: "eleventy.status",
status: "connected",
});
});
updateServer.on("error", (err) => {
this._serverErrorHandler(err);
});
this.updateServer = updateServer;
}
// Broadcasts to all open browser windows
sendUpdateNotification(obj) {
if(!this.updateServer?.clients) {
return;
}
for(let client of this.updateServer.clients) {
if (client.readyState === WebSocket.OPEN) {
client.send(JSON.stringify(obj));
}
}
}
// Helper for promisifying close methods with callbacks, like http.Server or ws.WebSocketServer.
_closeServer(server) {
return new Promise((resolve, reject) => {
server.close(err => {
if (err) {
reject(err);
}
resolve();
});
});
}
async close() {
// Prevent multiple invocations.
if (this?._isClosing) {
return;
}
this._isClosing = true;
// TODO would be awesome to set a delayed redirect when port changed to redirect to new _server_
this.sendUpdateNotification({
type: "eleventy.status",
status: "disconnected",
});
if(this.updateServer) {
// Close all existing WS connections.
this.updateServer?.clients.forEach(socket => socket.close());
await this._closeServer(this.updateServer);
}
if(this._server?.listening) {
await this._closeServer(this.server);
}
if(this._watcher) {
await this._watcher.close();
delete this._watcher;
}
delete this._isClosing;
}
sendError({ error }) {
this.sendUpdateNotification({
type: "eleventy.error",
// Thanks https://stackoverflow.com/questions/18391212/is-it-not-possible-to-stringify-an-error-using-json-stringify
error: JSON.stringify(error, Object.getOwnPropertyNames(error)),
});
}
// reverse of mapUrlToFilePath
// /resource/ <= /resource/index.html
// /resource <= resource.html
getUrlsFromFilePath(path) {
if(this.dir === ".") {
path = `/${path}`
} else {
path = path.slice(this.dir.length);
}
let urls = [];
urls.push(path);
if(path.endsWith(`/${this.options.indexFileName}`)) {
urls.push(path.slice(0, -1 * this.options.indexFileName.length));
} else if(path.endsWith(".html")) {
urls.push(path.slice(0, -1 * ".html".length));
}
return urls;
}
// [{ url, inputPath, content }]
getBuildTemplatesFromFilePath(path) {
// We can skip this for non-html files, dom-diffing will not apply
if(!path.endsWith(".html")) {
return [];
}
let urls = this.getUrlsFromFilePath(path);
let obj = {
inputPath: path,
content: fs.readFileSync(path, "utf8"),
}
return urls.map(url => {
return Object.assign({ url }, obj);
});
}
reloadFiles(files, useDomDiffingForHtml = true) {
if(!Array.isArray(files)) {
throw new Error("reloadFiles method requires an array of file paths.");
}
let subtype;
if(!files.some((entry) => !entry.endsWith(".css"))) {
// all css changes
subtype = "css";
}
let templates = [];
if(useDomDiffingForHtml && this.options.domDiff) {
for(let filePath of files) {
if(!filePath.endsWith(".html")) {
continue;
}
for(let templateEntry of this.getBuildTemplatesFromFilePath(filePath)) {
templates.push(templateEntry);
}
}
}
this.reload({
files,
subtype,
build: {
templates
}
});
}
reload(event) {
let { subtype, files, build } = event;
if (build?.templates) {
build.templates = build.templates
.filter(entry => {
if(!this.options.domDiff) {
// Dont include any files if the dom diffing option is disabled
return false;
}
// Filter to only include watched templates that were updated
return (files || []).includes(entry.inputPath);
});
}
this.sendUpdateNotification({
type: "eleventy.reload",
subtype,
files,
build,
});
}
}
module.exports = EleventyDevServer;

View File

@@ -0,0 +1,129 @@
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 && contentType.startsWith("text/html")) {
if(this._wrappedTransformHtml && typeof this._wrappedTransformHtml === "function") {
result = this._wrappedTransformHtml(result);
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 {
// Buffers
for(let headers of this._wrappedHeaders) {
this._wrappedOriginalWriteHead(...headers);
}
if(data) {
this._wrappedOriginalWrite(data, encoding);
}
return this._wrappedOriginalEnd(callback);
}
}
return resp;
}
module.exports = wrapResponse;

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,66 @@
import { createRequire } from "node:module";
import bundleManagersPlugin from "./src/eleventy.bundleManagers.js";
import pruneEmptyBundlesPlugin from "./src/eleventy.pruneEmptyBundles.js";
import shortcodesPlugin from "./src/eleventy.shortcodes.js";
import debugUtil from "debug";
const require = createRequire(import.meta.url);
const debug = debugUtil("Eleventy:Bundle");
const pkg = require("./package.json");
function normalizeOptions(options = {}) {
options = Object.assign({
// Plugin defaults
bundles: [], // extra bundles: css, js, and html are guaranteed unless `bundles: false`
toFileDirectory: "bundle",
// post-process
transforms: [],
hoistDuplicateBundlesFor: [],
bundleExportKey: "bundle", // use a `bundle` export in a 11ty.js template to populate bundles
}, options);
if(options.bundles !== false) {
options.bundles = Array.from(new Set(["css", "js", "html", ...(options.bundles || [])]));
}
return options;
}
function eleventyBundlePlugin(eleventyConfig, pluginOptions = {}) {
eleventyConfig.versionCheck(pkg["11ty"].compatibility);
pluginOptions = normalizeOptions(pluginOptions);
if(!("getBundleManagers" in eleventyConfig) && !("addBundle" in eleventyConfig)) {
bundleManagersPlugin(eleventyConfig, pluginOptions);
}
pruneEmptyBundlesPlugin(eleventyConfig, pluginOptions);
// should this be unique too?
shortcodesPlugin(eleventyConfig, pluginOptions);
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: pkg.name
});
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.0",
"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"
},
"11ty": {
"compatibility": ">=3.0.0-alpha"
},
"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"
],
"ignoredByWatcher": [
"**/_site/**",
".cache"
]
},
"devDependencies": {
"@11ty/eleventy": "3.0.0-alpha.20",
"ava": "^5.3.1",
"postcss": "^8.4.31",
"postcss-nested": "^6.0.1",
"sass": "^1.69.5"
},
"dependencies": {
"debug": "^4.3.4",
"posthtml-match-helper": "^2.0.2"
}
}

View File

@@ -0,0 +1,76 @@
import fs from "node:fs";
import path from "node:path";
import { createHash } from "node:crypto";
import debugUtil from "debug";
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;
}
getFilenameHash(content) {
if(hashCache[content]) {
return hashCache[content];
}
let hash = createHash("sha256");
hash.update(content);
let base64hash = hash.digest('base64').replace(/=/g, "").replace(/\+/g, "-").replace(/\//g, "_");
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("/");
}
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 = 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,209 @@
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";
}
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);
let debugLoggedContent = codeContent.join("\n");
debug("Adding code to bundle %o for %o (bucket: %o, size: %o): %o", this.name, pageUrl, b, debugLoggedContent.length, debugLoggedContent.length > DEBUG_LOG_TRUNCATION_SIZE ? debugLoggedContent.slice(0, DEBUG_LOG_TRUNCATION_SIZE) + "…" : debugLoggedContent);
for(let content of codeContent) {
if(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);
debug("Retrieving %o for %o (buckets: %o)", this.name, url, buckets);
let set = new Set();
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]) {
set.add(entry);
}
}
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,153 @@
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) {
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);
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,74 @@
import { createRequire } from "node:module";
import debugUtil from "debug";
import { CodeManager } from "./CodeManager.js";
const require = createRequire(import.meta.url);
const debug = debugUtil("Eleventy:Bundle");
const pkg = require("../package.json");
function eleventyBundleManagers(eleventyConfig, pluginOptions = {}) {
if("getBundleManagers" in eleventyConfig || "addBundle" in eleventyConfig) {
throw new Error("Duplicate plugin calls for " + pkg.name);
}
let managers = {};
function addBundle(name, bundleOptions = {}) {
if(name in managers) {
debug("Bundle exists %o, skipping.", name);
// note: shortcode must still be added
} else {
debug("Creating new bundle %o", name);
managers[name] = new CodeManager(name);
if(bundleOptions.hoist !== undefined) {
managers[name].setHoisting(bundleOptions.hoist);
}
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,88 @@
import matchHelper from "posthtml-match-helper";
import debugUtil from "debug";
const debug = debugUtil("Eleventy:Bundle");
const ATTRS = {
keep: "eleventy:keep"
}
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"]`;
// `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 (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;
});
};
},
{
// 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");
function eleventyBundleShortcodes(eleventyConfig, pluginOptions = {}) {
let managers = eleventyConfig.getBundleManagers();
let writeToFileSystem = true;
let pagesUsingBundles = {};
eleventyConfig.on("eleventy.before", async ({ outputMode }) => {
if(Object.keys(managers).length === 0) {
return;
}
pagesUsingBundles = {};
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)}`);
}
let url = explicitUrl || this.page?.url;
if(url) {
pagesUsingBundles[url] = true;
}
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)}`);
}
let url = explicitUrl || this.page?.url;
if(url) {
pagesUsingBundles[url] = true;
}
return OutOfOrderRender.getAssetKey("file", type, bucket);
});
eleventyConfig.addTransform("@11ty/eleventy-bundle", function(content) {
// `page.outputPath` is required to perform bundle transform, unless
// we're running in Eleventy Serverless.
let missingOutputPath = !this.page.outputPath && process.env.ELEVENTY_SERVERLESS !== "true";
if(missingOutputPath || typeof content !== "string") {
return content;
}
// Only run if managers are in play
// Only run on pages that have fetched bundles via `getBundle` or `getBundleFileUrl`
if(Object.keys(managers).length === 0 || this.page.url && !pagesUsingBundles[this.page.url]) {
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);
});
};
export default eleventyBundleShortcodes;

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

@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2022 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.

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

@@ -0,0 +1,29 @@
<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)
[![npm Version](https://img.shields.io/npm/v/@11ty/eleventy-utils.svg?style=for-the-badge)](https://www.npmjs.com/package/@11ty/eleventy-utils)
## Installation
```
npm install @11ty/eleventy-utils
```
## 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))

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

@@ -0,0 +1,11 @@
const TemplatePath = require("./src/TemplatePath.js");
const isPlainObject = require("./src/IsPlainObject.js");
const Merge = require("./src/Merge.js");
const { DeepCopy } = Merge;
module.exports = {
TemplatePath,
isPlainObject,
Merge,
DeepCopy,
};

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

@@ -0,0 +1,47 @@
{
"name": "@11ty/eleventy-utils",
"version": "1.0.3",
"description": "Low level internal utilities to be shared amongst Eleventy projects",
"main": "index.js",
"files": [
"src",
"src/**",
"index.js",
"!test",
"!test/**"
],
"scripts": {
"test": "npx ava --verbose"
},
"license": "MIT",
"engines": {
"node": ">=12"
},
"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/",
"dependencies": {
"normalize-path": "^3.0.0"
},
"devDependencies": {
"ava": "^6.1.3"
}
}

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

@@ -0,0 +1,24 @@
/* Prior art: this utility was created for https://github.com/11ty/eleventy/issues/2214
* Inspired by implementations from `is-what`, `typechecker`, `jQuery`, and `lodash`
* `is-what`
* More reading at https://www.npmjs.com/package/is-what#user-content-isplainobject-vs-isanyobject
* if (Object.prototype.toString.call(value).slice(8, -1) !== 'Object') return false;
* return value.constructor === Object && Object.getPrototypeOf(value) === Object.prototype;
* `typechecker`
* return value !== null && typeof value === 'object' && value.__proto__ === Object.prototype;
* Notably jQuery and lodash have very similar implementations.
* For later, remember the `value === Object(value)` trick
*/
module.exports = function (value) {
if (value === null || typeof value !== "object") {
return false;
}
let proto = Object.getPrototypeOf(value);
return !proto || proto === Object.prototype;
};

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

@@ -0,0 +1,84 @@
"use strict";
// above is required for Object.freeze to fail correctly.
const isPlainObject = require("./IsPlainObject.js");
const OVERRIDE_PREFIX = "override:";
function cleanKey(key, prefix) {
if (prefix && key.startsWith(prefix)) {
return key.slice(prefix.length);
}
return key;
}
function getMergedItem(target, source, prefixes = {}) {
let { override } = prefixes;
// Shortcut for frozen source (if target does not exist)
if (!target && isPlainObject(source) && Object.isFrozen(source)) {
return source;
}
let sourcePlainObjectShortcut;
if (!target && isPlainObject(source)) {
// deep copy objects to avoid sharing and to effect key renaming
target = {};
sourcePlainObjectShortcut = true;
}
if (Array.isArray(target) && Array.isArray(source)) {
return target.concat(source);
} else if (isPlainObject(target)) {
if (sourcePlainObjectShortcut || isPlainObject(source)) {
for (let key in source) {
let overrideKey = cleanKey(key, override);
// An error happens here if the target is frozen
target[overrideKey] = getMergedItem(target[key], source[key], prefixes);
}
}
return target;
}
// number, string, class instance, etc
return source;
}
// The same as Merge but without override prefixes
function DeepCopy(targetObject, ...sources) {
for (let source of sources) {
if (!source) {
continue;
}
targetObject = getMergedItem(targetObject, source);
}
return targetObject;
}
function Merge(target, ...sources) {
// Remove override prefixes from root target.
if (isPlainObject(target)) {
for (let key in target) {
if (key.indexOf(OVERRIDE_PREFIX) === 0) {
target[key.slice(OVERRIDE_PREFIX.length)] = target[key];
delete target[key];
}
}
}
for (let source of sources) {
if (!source) {
continue;
}
target = getMergedItem(target, source, {
override: OVERRIDE_PREFIX,
});
}
return target;
}
module.exports = Merge;
module.exports.DeepCopy = DeepCopy;

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

@@ -0,0 +1,368 @@
const path = require("path");
const normalize = require("normalize-path");
const fs = require("fs");
function TemplatePath() {}
/**
* @returns {String} the absolute path to Eleventys project directory.
*/
TemplatePath.getWorkingDir = function () {
return TemplatePath.normalize(path.resolve("."));
};
/**
* Returns the directory portion of a path.
* Works for directory and file paths and paths ending in a glob pattern.
*
* @param {String} path A path
* @returns {String} the directory portion of a path.
*/
TemplatePath.getDir = function (path) {
if (TemplatePath.isDirectorySync(path)) {
return path;
}
return TemplatePath.getDirFromFilePath(path);
};
/**
* Returns the directory portion of a path that either points to a file
* or ends in a glob pattern. If `path` points to a directory,
* the returned value will have its last path segment stripped
* due to how [`path.parse`][1] works.
*
* [1]: https://nodejs.org/api/path.html#path_path_parse_path
*
* @param {String} path A path
* @returns {String} the directory portion of a path.
*/
TemplatePath.getDirFromFilePath = function (filePath) {
return path.parse(filePath).dir || ".";
};
/**
* Returns the last path segment in a path (no leading/trailing slashes).
*
* Assumes [`path.parse`][1] was called on `path` before.
*
* [1]: https://nodejs.org/api/path.html#path_path_parse_path
*
* @param {String} path A path
* @returns {String} the last path segment in a path
*/
TemplatePath.getLastPathSegment = function (path) {
if (!path.includes("/")) {
return path;
}
// Trim a trailing slash if there is one
path = path.replace(/\/$/, "");
return path.substr(path.lastIndexOf("/") + 1);
};
/**
* @param {String} path A path
* @returns {String[]} an array of paths pointing to each path segment of the
* provided `path`.
*/
TemplatePath.getAllDirs = function (path) {
// Trim a trailing slash if there is one
path = path.replace(/\/$/, "");
if (!path.includes("/")) {
return [path];
}
return path
.split("/")
.map((segment, index, array) => array.slice(0, index + 1).join("/"))
.filter((path) => path !== ".")
.reverse();
};
/**
* Normalizes a path, resolving single-dot and double-dot segments.
*
* Node.js [`path.normalize`][1] is called to strip a possible leading `"./"` segment.
*
* [1]: https://nodejs.org/api/path.html#path_path_normalize_path
*
* @param {String} thePath The path that should be normalized.
* @returns {String} the normalized path.
*/
TemplatePath.normalize = function (thePath) {
return normalize(path.normalize(thePath));
};
/**
* Joins all given path segments together.
*
* It uses Node.js [`path.join`][1] method and the [normalize-path][2] package.
*
* [1]: https://nodejs.org/api/path.html#path_path_join_paths
* [2]: https://www.npmjs.com/package/normalize-path
*
* @param {String[]} paths An arbitrary amount of path segments.
* @returns {String} the normalized and joined path.
*/
TemplatePath.join = function (...paths) {
return normalize(path.join(...paths));
};
/**
* Joins the given URL path segments and normalizes the resulting path.
* Maintains a single trailing slash if the last URL path argument
* had at least one.
*
* @param {String[]} urlPaths
* @returns {String} a normalized URL path described by the given URL path segments.
*/
TemplatePath.normalizeUrlPath = function (...urlPaths) {
const urlPath = path.posix.join(...urlPaths);
return urlPath.replace(/\/+$/, "/");
};
/**
* Joins the given path segments. Since the first path is absolute,
* the resulting path will be absolute as well.
*
* @param {String[]} paths
* @returns {String} the absolute path described by the given path segments.
*/
TemplatePath.absolutePath = function (...paths) {
let i = 0;
// check all the paths before we short circuit from the first index
for (let p of paths) {
if (path.isAbsolute(p) && i > 0) {
throw new Error(
`Only the first parameter to Template.absolutePath can be an absolute path. Received: ${p} from ${paths}`
);
}
i++;
}
let j = 0;
for (let p of paths) {
if (j === 0 && path.isAbsolute(p)) {
return TemplatePath.join(...paths);
}
j++;
}
return TemplatePath.join(TemplatePath.getWorkingDir(), ...paths);
};
/**
* Turns an absolute path into a path relative to the project directory.
*
* @param {String} absolutePath
* @returns {String} the relative path.
*/
TemplatePath.relativePath = function (absolutePath) {
return TemplatePath.stripLeadingSubPath(
absolutePath,
TemplatePath.getWorkingDir()
);
};
/**
* Adds a leading dot-slash segment to each path in the `paths` array.
*
* @param {String[]} paths
* @returns {String[]}
*/
TemplatePath.addLeadingDotSlashArray = function (paths) {
return paths.map((path) => TemplatePath.addLeadingDotSlash(path));
};
/**
* Adds a leading dot-slash segment to `path`.
*
* @param {String} path
* @returns {String}
*/
TemplatePath.addLeadingDotSlash = function (pathArg) {
if (pathArg === "." || pathArg === "..") {
return pathArg + "/";
}
if (
path.isAbsolute(pathArg) ||
pathArg.startsWith("./") ||
pathArg.startsWith("../")
) {
return pathArg;
}
return "./" + pathArg;
};
/**
* Removes a leading dot-slash segment.
*
* @param {String} path
* @returns {String} the `path` without a leading dot-slash segment.
*/
TemplatePath.stripLeadingDotSlash = function (path) {
return typeof path === "string" ? path.replace(/^\.\//, "") : path;
};
/**
* Determines whether a path starts with a given sub path.
*
* @param {String} path A path
* @param {String} subPath A path
* @returns {Boolean} whether `path` starts with `subPath`.
*/
TemplatePath.startsWithSubPath = function (path, subPath) {
path = TemplatePath.normalize(path);
subPath = TemplatePath.normalize(subPath);
return path.startsWith(subPath);
};
/**
* Removes the `subPath` at the start of `path` if present
* and returns the remainding path.
*
* @param {String} path A path
* @param {String} subPath A path
* @returns {String} the `path` without `subPath` at the start of it.
*/
TemplatePath.stripLeadingSubPath = function (path, subPath) {
path = TemplatePath.normalize(path);
subPath = TemplatePath.normalize(subPath);
if (subPath !== "." && path.startsWith(subPath)) {
return path.substr(subPath.length + 1);
}
return path;
};
/**
* @param {String} path A path
* @returns {Boolean} whether `path` points to an existing directory.
*/
TemplatePath.isDirectorySync = function (path) {
return fs.existsSync(path) && fs.statSync(path).isDirectory();
};
/**
* @param {String} path A path
* @returns {Boolean} whether `path` points to an existing directory.
*/
TemplatePath.isDirectory = async function (path) {
return new Promise((resolve) => {
fs.stat(path, (err, stats) => {
if (stats) {
resolve(stats.isDirectory());
}
resolve(false);
});
});
};
/**
* Appends a recursive wildcard glob pattern to `path`
* unless `path` is not a directory; then, `path` is assumed to be a file path
* and is left unchaged.
*
* @param {String} path
* @returns {String}
*/
TemplatePath.convertToRecursiveGlobSync = function (path) {
if (path === "") {
return "./**";
}
path = TemplatePath.addLeadingDotSlash(path);
if (TemplatePath.isDirectorySync(path)) {
return path + (!path.endsWith("/") ? "/" : "") + "**";
}
return path;
};
/**
* Appends a recursive wildcard glob pattern to `path`
* unless `path` is not a directory; then, `path` is assumed to be a file path
* and is left unchaged.
*
* @param {String} path
* @returns {String}
*/
TemplatePath.convertToRecursiveGlob = async function (path) {
if (path === "") {
return "./**";
}
path = TemplatePath.addLeadingDotSlash(path);
if (await TemplatePath.isDirectory(path)) {
return path + (!path.endsWith("/") ? "/" : "") + "**";
}
return path;
};
/**
* Returns the extension of the path without the leading dot.
* If the path has no extensions, the empty string is returned.
*
* @param {String} thePath
* @returns {String} the paths extension if it exists;
* otherwise, the empty string.
*/
TemplatePath.getExtension = function (thePath) {
return path.extname(thePath).replace(/^\./, "");
};
/**
* Removes the extension from a path.
*
* @param {String} path
* @param {String} extension
* @returns {String}
*/
TemplatePath.removeExtension = function (path, extension = undefined) {
if (extension === undefined) {
return path;
}
const pathExtension = TemplatePath.getExtension(path);
if (pathExtension !== "" && extension.endsWith(pathExtension)) {
return path.substring(0, path.lastIndexOf(pathExtension) - 1);
}
return path;
};
/**
* Accepts a relative file path that is using a standard directory separator and
* normalizes it using the local operating system separator.
* e.g. `./my/dir/` stays `./my/dir/` on *nix and becomes `.\\my\\dir\\` on Windows
*
* @param {String} filePath
* @returns {String} a file path with the correct local directory separator.
*/
TemplatePath.normalizeOperatingSystemFilePath = function (filePath, sep = "/") {
return filePath.split(sep).join(path.sep);
};
/**
* Accepts a relative file path with the local operating system directory separator and
* normalizes it using a forward slash directory separator. (Leaves trailing slash as-is)
* e.g. `./my/dir/` stays `./my/dir/` on *nix and becomes `.\\my\\dir\\` on Windows
*
* @param {String} filePath
* @returns {String} a file path with the correct local directory separator.
*/
TemplatePath.standardizeFilePath = function (filePath, sep = "/") {
return TemplatePath.addLeadingDotSlash(filePath.split(path.sep).join(sep));
};
module.exports = TemplatePath;

48
node_modules/@11ty/eleventy/CODE_OF_CONDUCT.md generated vendored Normal file
View File

@@ -0,0 +1,48 @@
# Eleventy Community Code of Conduct
View the [Code of Conduct](https://www.11ty.dev/docs/code-of-conduct/) on 11ty.dev
## Our Pledge
In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, gender identity and expression, level of experience, nationality, personal appearance, race, religion, or sexual identity and orientation.
## Our Standards
Examples of behavior that contributes to creating a positive environment include:
- Using welcoming and inclusive language
- Being respectful of differing viewpoints and experiences
- Gracefully accepting constructive criticism
- Focusing on what is best for the community
- Showing empathy towards other community members
Examples of unacceptable behavior by participants include:
- The use of sexualized language or imagery and unwelcome sexual attention or advances
- Trolling, insulting/derogatory comments, and personal or political attacks
- Public or private harassment
- Publishing others' private information, such as a physical or electronic address, without explicit permission
- Other conduct which could reasonably be considered inappropriate in a professional setting
## Our Responsibilities
Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior.
Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, chat messages, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful.
## Scope
This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers.
## Enforcement
Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at eleventy@zachleat.com. The project team will review and investigate all complaints, and will respond in a way that it deems appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately.
Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership.
## Attribution
This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, available at [http://contributor-covenant.org/version/1/4][version]
[homepage]: http://contributor-covenant.org
[version]: http://contributor-covenant.org/version/1/4/

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

@@ -0,0 +1,21 @@
MIT License
Copyright (c) 20172024 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.

47
node_modules/@11ty/eleventy/README.md generated vendored Normal file
View File

@@ -0,0 +1,47 @@
<p align="center"><img src="https://www.11ty.dev/img/logo-github.svg" width="200" height="200" alt="eleventy Logo"></p>
# eleventy 🕚⚡️🎈🐀
A simpler static site generator. An alternative to Jekyll. Written in JavaScript. Transforms a directory of templates (of varying types) into HTML.
Works with HTML, Markdown, JavaScript, Liquid, Nunjucks, with addons for WebC, Sass, Vue, Svelte, TypeScript, JSX, and many others!
## ➡ [Documentation](https://www.11ty.dev/docs/)
- Please star [this repo on GitHub](https://github.com/11ty/eleventy/)!
- Follow us on Mastodon [@eleventy@fosstodon.org](https://fosstodon.org/@eleventy) or Twitter [@eleven_ty](https://twitter.com/eleven_ty)
- Join us on [Discord](https://www.11ty.dev/blog/discord/)
- 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.svg?style=for-the-badge)](https://www.npmjs.com/package/@11ty/eleventy) [![GitHub issues](https://img.shields.io/github/issues/11ty/eleventy.svg?style=for-the-badge)](https://github.com/11ty/eleventy/issues) [![code style: prettier](https://img.shields.io/badge/code_style-prettier-ff69b4.svg?style=for-the-badge)](https://github.com/prettier/prettier) [![npm Downloads](https://img.shields.io/npm/dt/@11ty/eleventy.svg?style=for-the-badge)](https://www.npmjs.com/package/@11ty/eleventy)
## Installation
```
npm install @11ty/eleventy --save-dev
```
Read our [Getting Started guide](https://www.11ty.dev/docs/getting-started/).
## 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.
- [Continuous Integration on GitHub Actions](https://github.com/11ty/eleventy/actions/workflows/ci.yml)
- [Code Coverage Statistics](https://github.com/11ty/eleventy/blob/master/docs/coverage.md)
- [Benchmark for Performance Regressions](https://github.com/11ty/eleventy-benchmark)
## Community Roadmap
- [Top Feature Requests](https://github.com/11ty/eleventy/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/issues?q=is%3Aissue+is%3Aopen+label%3Abug+sort%3Areactions) (Add your own votes using the 👍 reaction)
## Plugins
See the [official docs on plugins](https://www.11ty.dev/docs/plugins/).

9
node_modules/@11ty/eleventy/SECURITY.md generated vendored Normal file
View File

@@ -0,0 +1,9 @@
# Security Policy
## Reporting a Vulnerability
Privately report a security issue by navigating to https://github.com/11ty/eleventy/security and using the “Report a vulnerability” button.
Read more at: https://docs.github.com/en/code-security/security-advisories/guidance-on-reporting-and-writing-information-about-vulnerabilities/privately-reporting-a-security-vulnerability
Alternatively, you may report security issues via an email to `security@11ty.dev`.

165
node_modules/@11ty/eleventy/cmd.cjs generated vendored Executable file
View File

@@ -0,0 +1,165 @@
#!/usr/bin/env node
// This file intentionally uses older code conventions to be as friendly
// as possible with error messaging to folks on older runtimes.
const pkg = require("./package.json");
require("please-upgrade-node")(pkg, {
message: function (requiredVersion) {
return (
"Eleventy " +
pkg.version +
" requires Node " +
requiredVersion +
". You will need to upgrade Node to use Eleventy!"
);
},
});
const minimist = require("minimist");
const debug = require("debug")("Eleventy:cmd");
(async function () {
const { EleventyErrorHandler } = await import("./src/Errors/EleventyErrorHandler.js");
class SimpleError extends Error {
constructor(...args) {
super(...args);
this.skipOriginalStack = true;
}
}
try {
const argv = minimist(process.argv.slice(2), {
string: ["input", "output", "formats", "config", "pathprefix", "port", "to", "incremental", "loader"],
boolean: [
"quiet",
"version",
"watch",
"dryrun",
"help",
"serve",
"ignore-initial",
],
default: {
quiet: null,
"ignore-initial": false,
"to": "fs",
},
unknown: function (unknownArgument) {
throw new Error(
`We dont know what '${unknownArgument}' is. Use --help to see the list of supported commands.`,
);
},
});
debug("command: eleventy %o", argv);
const { Eleventy } = await import("./src/Eleventy.js");
let ErrorHandler = new EleventyErrorHandler();
process.on("unhandledRejection", (error, promise) => {
ErrorHandler.fatal(error, "Unhandled rejection in promise");
});
process.on("uncaughtException", (error) => {
ErrorHandler.fatal(error, "Uncaught exception");
});
process.on("rejectionHandled", (promise) => {
ErrorHandler.warn(promise, "A promise rejection was handled asynchronously");
});
if (argv.version) {
console.log(Eleventy.getVersion());
return;
} else if (argv.help) {
console.log(Eleventy.getHelp());
return;
}
let elev = new Eleventy(argv.input, argv.output, {
source: "cli",
// --quiet and --quiet=true both resolve to true
quietMode: argv.quiet,
configPath: argv.config,
pathPrefix: argv.pathprefix,
runMode: argv.serve ? "serve" : argv.watch ? "watch" : "build",
dryRun: argv.dryrun,
loader: argv.loader,
});
// reuse ErrorHandler instance in Eleventy
ErrorHandler = elev.errorHandler;
// Before init
elev.setFormats(argv.formats);
// careful, we cant use async/await here to error properly
// with old node versions in `please-upgrade-node` above.
elev
.init()
.then(() => {
if (argv.to === "json" || argv.to === "ndjson") {
// override logging output
elev.setIsVerbose(false);
}
// Only relevant for watch/serve
elev.setIgnoreInitial(argv["ignore-initial"]);
if(argv.incremental) {
elev.setIncrementalFile(argv.incremental);
} else if(argv.incremental !== undefined) {
elev.setIncrementalBuild(argv.incremental === "" || argv.incremental);
}
if (argv.serve || argv.watch) {
if(argv.to === "json" || argv.to === "ndjson") {
throw new SimpleError("--to=json and --to=ndjson are not compatible with --serve or --watch.");
}
elev
.watch()
.then(() => {
if (argv.serve) {
elev.serve(argv.port);
}
}, error => {
// A build error occurred and we arent going to --serve
ErrorHandler.once("error", error, "Eleventy Error (Watch CLI)");
});
process.on("SIGINT", async () => {
await elev.stopWatch();
process.exitCode = 0;
});
} else {
if (!argv.to || argv.to === "fs") {
elev.write().catch(error => {
ErrorHandler.once("fatal", error, "Eleventy Error (FS CLI)");
});
} else if (argv.to === "json") {
elev.toJSON().then(function (result) {
console.log(JSON.stringify(result, null, 2));
}, error => {
ErrorHandler.once("fatal", error, "Eleventy Error (JSON CLI)");
});
} else if (argv.to === "ndjson") {
elev.toNDJSON().then(function (stream) {
stream.pipe(process.stdout);
}, error => {
ErrorHandler.once("fatal", error, "Eleventy Error (JSON CLI)");
});
} else {
throw new SimpleError(
`Invalid --to value: ${argv.to}. Supported values: \`fs\` (default), \`json\`, and \`ndjson\`.`,
);
}
}
}).catch(error => {
ErrorHandler.fatal(error, "Eleventy Error (CLI)");
});
} catch (error) {
let ErrorHandler = new EleventyErrorHandler();
ErrorHandler.fatal(error, "Eleventy Fatal Error (CLI)");
}
})();

155
node_modules/@11ty/eleventy/package.json generated vendored Normal file
View File

@@ -0,0 +1,155 @@
{
"name": "@11ty/eleventy",
"version": "3.0.0",
"description": "A simpler static site generator.",
"publishConfig": {
"access": "public",
"provenance": true
},
"type": "module",
"main": "./src/Eleventy.js",
"exports": {
"import": "./src/Eleventy.js",
"require": "./src/EleventyCommonJs.cjs"
},
"bin": {
"eleventy": "cmd.cjs"
},
"license": "MIT",
"engines": {
"node": ">=18"
},
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/11ty"
},
"keywords": [
"static-site-generator",
"static-site",
"ssg",
"documentation",
"website",
"jekyll",
"blog",
"templates",
"generator",
"framework",
"eleventy",
"11ty",
"html",
"markdown",
"liquid",
"nunjucks"
],
"scripts": {
"default": "npm run test",
"test": "npm run test:node && npm run test:ava",
"test:ava": "ava --verbose --timeout 20s",
"test:node": "node --test test_node/tests.js",
"format": "prettier . --write",
"check": "eslint src",
"check-types": "tsc",
"lint-staged": "lint-staged",
"coverage": "npx c8 ava && npx c8 report --reporter=json-summary && cp coverage/coverage-summary.json docs/_data/coverage.json && node cmd.cjs --config=docs/eleventy.coverage.js",
"prepare": "husky"
},
"author": "Zach Leatherman <zachleatherman@gmail.com> (https://zachleat.com/)",
"repository": {
"type": "git",
"url": "git://github.com/11ty/eleventy.git"
},
"bugs": "https://github.com/11ty/eleventy/issues",
"homepage": "https://www.11ty.dev/",
"ava": {
"environmentVariables": {},
"failFast": true,
"files": [
"./test/*.js",
"./test/_issues/**/*test.js"
],
"watchMode": {
"ignoreChanges": [
"./test/stubs*/**/*",
".cache"
]
}
},
"lint-staged": {
"*.{js,css,md}": [
"prettier --write"
]
},
"devDependencies": {
"@11ty/eleventy-img": "5.0.0-beta.10",
"@11ty/eleventy-plugin-rss": "^2.0.2",
"@11ty/eleventy-plugin-syntaxhighlight": "^5.0.0",
"@eslint/eslintrc": "^3.1.0",
"@eslint/js": "^9.11.1",
"@iarna/toml": "^2.2.5",
"@mdx-js/node-loader": "^3.0.1",
"@types/node": "^22.7.4",
"@vue/server-renderer": "^3.5.10",
"@zachleat/noop": "^1.0.4",
"ava": "^6.1.3",
"c8": "^10.1.2",
"cross-env": "^7.0.3",
"eslint": "^9.11.1",
"eslint-config-prettier": "^9.1.0",
"globals": "^15.10.0",
"husky": "^9.1.6",
"lint-staged": "^15.2.10",
"markdown-it-emoji": "^3.0.0",
"marked": "^14.1.2",
"prettier": "^3.3.3",
"pretty": "^2.0.0",
"react": "^18.3.1",
"react-dom": "^18.3.1",
"rimraf": "^6.0.1",
"sass": "^1.79.4",
"tsx": "^4.19.1",
"typescript": "^5.6.2",
"vue": "^3.5.10",
"zod": "^3.23.8",
"zod-validation-error": "^3.4.0"
},
"dependencies": {
"@11ty/dependency-tree": "^3.0.1",
"@11ty/dependency-tree-esm": "^1.0.0",
"@11ty/eleventy-dev-server": "^2.0.4",
"@11ty/eleventy-plugin-bundle": "^3.0.0",
"@11ty/eleventy-utils": "^1.0.3",
"@11ty/lodash-custom": "^4.17.21",
"@11ty/posthtml-urls": "^1.0.0",
"@11ty/recursive-copy": "^3.0.0",
"@sindresorhus/slugify": "^2.2.1",
"bcp-47-normalize": "^2.3.0",
"chardet": "^2.0.0",
"chokidar": "^3.6.0",
"cross-spawn": "^7.0.3",
"debug": "^4.3.7",
"dependency-graph": "^1.0.0",
"entities": "^5.0.0",
"fast-glob": "^3.3.2",
"filesize": "^10.1.6",
"graceful-fs": "^4.2.11",
"gray-matter": "^4.0.3",
"is-glob": "^4.0.3",
"iso-639-1": "^3.1.3",
"js-yaml": "^4.1.0",
"kleur": "^4.1.5",
"liquidjs": "^10.17.0",
"luxon": "^3.5.0",
"markdown-it": "^14.1.0",
"micromatch": "^4.0.8",
"minimist": "^1.2.8",
"moo": "^0.5.2",
"node-retrieve-globals": "^6.0.0",
"normalize-path": "^3.0.0",
"nunjucks": "^3.2.4",
"please-upgrade-node": "^3.2.0",
"posthtml": "^0.16.6",
"posthtml-match-helper": "^2.0.2",
"semver": "^7.6.3",
"slugify": "^1.6.6"
}
}

55
node_modules/@11ty/eleventy/src/Benchmark/Benchmark.js generated vendored Normal file
View File

@@ -0,0 +1,55 @@
import { performance } from "node:perf_hooks";
class Benchmark {
constructor() {
// TypeScript slop
this.timeSpent = 0;
this.timesCalled = 0;
this.beforeTimers = [];
}
reset() {
this.timeSpent = 0;
this.timesCalled = 0;
this.beforeTimers = [];
}
getNewTimestamp() {
if (performance) {
return performance.now();
}
return new Date().getTime();
}
incrementCount() {
this.timesCalled++;
}
// TODO(slightlyoff):
// disable all of these hrtime requests when not benchmarking
before() {
this.timesCalled++;
this.beforeTimers.push(this.getNewTimestamp());
}
after() {
if (!this.beforeTimers.length) {
throw new Error("You called Benchmark after() without a before().");
}
let before = this.beforeTimers.pop();
if (!this.beforeTimers.length) {
this.timeSpent += this.getNewTimestamp() - before;
}
}
getTimesCalled() {
return this.timesCalled;
}
getTotal() {
return this.timeSpent;
}
}
export default Benchmark;

View File

@@ -0,0 +1,135 @@
import debugUtil from "debug";
import ConsoleLogger from "../Util/ConsoleLogger.js";
import isAsyncFunction from "../Util/IsAsyncFunction.js";
import Benchmark from "./Benchmark.js";
const debugBenchmark = debugUtil("Eleventy:Benchmark");
class BenchmarkGroup {
constructor() {
this.benchmarks = {};
// Warning: aggregate benchmarks automatically default to false via BenchmarkManager->getBenchmarkGroup
this.isVerbose = true;
this.logger = new ConsoleLogger();
this.minimumThresholdMs = 50;
this.minimumThresholdPercent = 8;
}
setIsVerbose(isVerbose) {
this.isVerbose = isVerbose;
this.logger.isVerbose = isVerbose;
}
reset() {
for (var type in this.benchmarks) {
this.benchmarks[type].reset();
}
}
// TODO use addAsync everywhere instead
add(type, callback) {
let benchmark = (this.benchmarks[type] = new Benchmark());
/** @this {any} */
let fn = function (...args) {
benchmark.before();
let ret = callback.call(this, ...args);
benchmark.after();
return ret;
};
Object.defineProperty(fn, "__eleventyInternal", {
value: {
type: isAsyncFunction(callback) ? "async" : "sync",
callback,
},
});
return fn;
}
// callback must return a promise
// async addAsync(type, callback) {
// let benchmark = (this.benchmarks[type] = new Benchmark());
// benchmark.before();
// // dont await here.
// let promise = callback.call(this);
// promise.then(function() {
// benchmark.after();
// });
// return promise;
// }
setMinimumThresholdMs(minimumThresholdMs) {
let val = parseInt(minimumThresholdMs, 10);
if (isNaN(val)) {
throw new Error("`setMinimumThresholdMs` expects a number argument.");
}
this.minimumThresholdMs = val;
}
setMinimumThresholdPercent(minimumThresholdPercent) {
let val = parseInt(minimumThresholdPercent, 10);
if (isNaN(val)) {
throw new Error("`setMinimumThresholdPercent` expects a number argument.");
}
this.minimumThresholdPercent = val;
}
has(type) {
return !!this.benchmarks[type];
}
get(type) {
if (!this.benchmarks[type]) {
this.benchmarks[type] = new Benchmark();
}
return this.benchmarks[type];
}
padNumber(num, length) {
if (("" + num).length >= length) {
return num;
}
let prefix = new Array(length + 1).join(" ");
return (prefix + num).slice(-1 * length);
}
finish(label, totalTimeSpent) {
for (var type in this.benchmarks) {
let bench = this.benchmarks[type];
let isAbsoluteMinimumComparison = this.minimumThresholdMs > 0;
let totalForBenchmark = bench.getTotal();
let percent = Math.round((totalForBenchmark * 100) / totalTimeSpent);
let callCount = bench.getTimesCalled();
let output = {
ms: this.padNumber(totalForBenchmark.toFixed(0), 6),
percent: this.padNumber(percent, 3),
calls: this.padNumber(callCount, 5),
};
let str = `Benchmark ${output.ms}ms ${output.percent}% ${output.calls}× (${label}) ${type}`;
if (
isAbsoluteMinimumComparison &&
totalForBenchmark >= this.minimumThresholdMs &&
percent > this.minimumThresholdPercent
) {
this.logger.warn(str);
}
// Opt out of logging if low count (1× or 2×) or 0ms / 1%
if (
callCount > 1 || // called more than once
Math.round(totalForBenchmark) > 0 // more than 0.5ms
) {
debugBenchmark(str);
}
}
}
}
export default BenchmarkGroup;

View File

@@ -0,0 +1,73 @@
import { performance } from "node:perf_hooks";
import BenchmarkGroup from "./BenchmarkGroup.js";
// TODO this should not be a singleton, it belongs in the config or somewhere on the Eleventy instance.
class BenchmarkManager {
constructor() {
this.benchmarkGroups = {};
this.isVerbose = true;
this.start = this.getNewTimestamp();
}
reset() {
this.start = this.getNewTimestamp();
for (var j in this.benchmarkGroups) {
this.benchmarkGroups[j].reset();
}
}
getNewTimestamp() {
if (performance) {
return performance.now();
}
return new Date().getTime();
}
setVerboseOutput(isVerbose) {
this.isVerbose = !!isVerbose;
}
hasBenchmarkGroup(name) {
return name in this.benchmarkGroups;
}
getBenchmarkGroup(name) {
if (!this.benchmarkGroups[name]) {
this.benchmarkGroups[name] = new BenchmarkGroup();
// Special behavior for aggregate benchmarks
// so they dont console.log every time
if (name === "Aggregate") {
this.benchmarkGroups[name].setIsVerbose(false);
} else {
this.benchmarkGroups[name].setIsVerbose(this.isVerbose);
}
}
return this.benchmarkGroups[name];
}
getAll() {
return this.benchmarkGroups;
}
get(name) {
if (name) {
return this.getBenchmarkGroup(name);
}
return this.getAll();
}
finish() {
let totalTimeSpentBenchmarking = this.getNewTimestamp() - this.start;
for (var j in this.benchmarkGroups) {
this.benchmarkGroups[j].finish(j, totalTimeSpentBenchmarking);
}
}
}
export default BenchmarkManager;

121
node_modules/@11ty/eleventy/src/Data/ComputedData.js generated vendored Normal file
View File

@@ -0,0 +1,121 @@
import lodash from "@11ty/lodash-custom";
import debugUtil from "debug";
import ComputedDataQueue from "./ComputedDataQueue.js";
import ComputedDataTemplateString from "./ComputedDataTemplateString.js";
import ComputedDataProxy from "./ComputedDataProxy.js";
const { set: lodashSet, get: lodashGet } = lodash;
const debug = debugUtil("Eleventy:ComputedData");
class ComputedData {
constructor(config) {
this.computed = {};
this.symbolParseFunctions = {};
this.templateStringKeyLookup = {};
this.computedKeys = new Set();
this.declaredDependencies = {};
this.queue = new ComputedDataQueue();
this.config = config;
}
add(key, renderFn, declaredDependencies = [], symbolParseFn, templateInstance) {
this.computedKeys.add(key);
this.declaredDependencies[key] = declaredDependencies;
// bind config filters/JS functions
if (typeof renderFn === "function") {
let fns = {};
// TODO bug? no access to non-universal config things?
if (this.config) {
fns = this.config.javascriptFunctions;
}
renderFn = renderFn.bind({
...fns,
tmpl: templateInstance,
});
}
lodashSet(this.computed, key, renderFn);
if (symbolParseFn) {
lodashSet(this.symbolParseFunctions, key, symbolParseFn);
}
}
addTemplateString(key, renderFn, declaredDependencies = [], symbolParseFn, templateInstance) {
this.add(key, renderFn, declaredDependencies, symbolParseFn, templateInstance);
this.templateStringKeyLookup[key] = true;
}
async resolveVarOrder(data) {
let proxyByTemplateString = new ComputedDataTemplateString(this.computedKeys);
let proxyByProxy = new ComputedDataProxy(this.computedKeys);
for (let key of this.computedKeys) {
let computed = lodashGet(this.computed, key);
if (typeof computed !== "function") {
// add nodes for non functions (primitives like booleans, etc)
// This will not handle template strings, as they are normalized to functions
this.queue.addNode(key);
} else {
this.queue.uses(key, this.declaredDependencies[key]);
let symbolParseFn = lodashGet(this.symbolParseFunctions, key);
let varsUsed = [];
if (symbolParseFn) {
// use the parseForSymbols function in the TemplateEngine
varsUsed = symbolParseFn();
} else if (symbolParseFn !== false) {
// skip resolution is this is false (just use declaredDependencies)
let isTemplateString = !!this.templateStringKeyLookup[key];
let proxy = isTemplateString ? proxyByTemplateString : proxyByProxy;
varsUsed = await proxy.findVarsUsed(computed, data);
}
debug("%o accesses %o variables", key, varsUsed);
let filteredVarsUsed = varsUsed.filter((varUsed) => {
return (
(varUsed !== key && this.computedKeys.has(varUsed)) ||
varUsed.startsWith("collections.")
);
});
this.queue.uses(key, filteredVarsUsed);
}
}
}
async _setupDataEntry(data, order) {
debug("Computed data order of execution: %o", order);
for (let key of order) {
let computed = lodashGet(this.computed, key);
if (typeof computed === "function") {
let ret = await computed(data);
lodashSet(data, key, ret);
} else if (computed !== undefined) {
lodashSet(data, key, computed);
}
}
}
async setupData(data, orderFilter) {
await this.resolveVarOrder(data);
await this.processRemainingData(data, orderFilter);
}
async processRemainingData(data, orderFilter) {
// process all variables
let order = this.queue.getOrder();
if (orderFilter && typeof orderFilter === "function") {
order = order.filter(orderFilter.bind(this.queue));
}
await this._setupDataEntry(data, order);
this.queue.markComputed(order);
}
}
export default ComputedData;

View File

@@ -0,0 +1,131 @@
import lodash from "@11ty/lodash-custom";
import { isPlainObject } from "@11ty/eleventy-utils";
const { set: lodashSet, get: lodashGet } = lodash;
/* Calculates computed data using Proxies */
class ComputedDataProxy {
constructor(computedKeys) {
if (Array.isArray(computedKeys)) {
this.computedKeys = new Set(computedKeys);
} else {
this.computedKeys = computedKeys;
}
}
isArrayOrPlainObject(data) {
return Array.isArray(data) || isPlainObject(data);
}
getProxyData(data, keyRef) {
// WARNING: SIDE EFFECTS
// Set defaults for keys not already set on parent data
// TODO should make another effort to get rid of this,
// See the ProxyWrap util for more proxy handlers that will likely fix this
let undefinedValue = "__11TY_UNDEFINED__";
if (this.computedKeys) {
for (let key of this.computedKeys) {
if (lodashGet(data, key, undefinedValue) === undefinedValue) {
lodashSet(data, key, "");
}
}
}
let proxyData = this._getProxyData(data, keyRef);
return proxyData;
}
_getProxyForObject(dataObj, keyRef, parentKey = "") {
return new Proxy(
{},
{
get: (obj, key) => {
if (typeof key !== "string") {
return obj[key];
}
let newKey = `${parentKey ? `${parentKey}.` : ""}${key}`;
// Issue #1137
// Special case for Collections, always return an Array for collection keys
// so they it works fine with Array methods like `filter`, `map`, etc
if (newKey === "collections") {
keyRef.add(newKey);
return new Proxy(
{},
{
get: (target, key) => {
if (typeof key === "string") {
keyRef.add(`collections.${key}`);
return [];
}
return target[key];
},
},
);
}
let newData = this._getProxyData(dataObj[key], keyRef, newKey);
if (!this.isArrayOrPlainObject(newData)) {
keyRef.add(newKey);
}
return newData;
},
},
);
}
_getProxyForArray(dataArr, keyRef, parentKey = "") {
return new Proxy(new Array(dataArr.length), {
get: (obj, key) => {
if (Array.prototype.hasOwnProperty(key)) {
// remove `filter`, `constructor`, `map`, etc
keyRef.add(parentKey);
return obj[key];
}
// Hm, this needs to be better
if (key === "then") {
keyRef.add(parentKey);
return;
}
let newKey = `${parentKey}[${key}]`;
let newData = this._getProxyData(dataArr[key], keyRef, newKey);
if (!this.isArrayOrPlainObject(newData)) {
keyRef.add(newKey);
}
return newData;
},
});
}
_getProxyData(data, keyRef, parentKey = "") {
if (isPlainObject(data)) {
return this._getProxyForObject(data, keyRef, parentKey);
} else if (Array.isArray(data)) {
return this._getProxyForArray(data, keyRef, parentKey);
}
// everything else!
return data;
}
async findVarsUsed(fn, data = {}) {
let keyRef = new Set();
// careful, logging proxyData will mess with test results!
let proxyData = this.getProxyData(data, keyRef);
// squelch console logs for this fake proxy data pass 😅
// let savedLog = console.log;
// console.log = () => {};
await fn(proxyData);
// console.log = savedLog;
return Array.from(keyRef);
}
}
export default ComputedDataProxy;

View File

@@ -0,0 +1,64 @@
import { DepGraph as DependencyGraph } from "dependency-graph";
/* Keeps track of the dependency graph between computed data variables
* Removes keys from the graph when they are computed.
*/
class ComputedDataQueue {
constructor() {
this.graph = new DependencyGraph();
}
getOrder() {
return this.graph.overallOrder();
}
getOrderFor(name) {
return this.graph.dependenciesOf(name);
}
getDependsOn(name) {
return this.graph.dependantsOf(name);
}
isUsesStartsWith(name, prefix) {
if (name.startsWith(prefix)) {
return true;
}
return (
this.graph.dependenciesOf(name).filter((entry) => {
return entry.startsWith(prefix);
}).length > 0
);
}
addNode(name) {
if (!this.graph.hasNode(name)) {
this.graph.addNode(name);
}
}
_uses(graph, name, varsUsed = []) {
if (!graph.hasNode(name)) {
graph.addNode(name);
}
for (let varUsed of varsUsed) {
if (!graph.hasNode(varUsed)) {
graph.addNode(varUsed);
}
graph.addDependency(name, varUsed);
}
}
uses(name, varsUsed = []) {
this._uses(this.graph, name, varsUsed);
}
markComputed(varsComputed = []) {
for (let varComputed of varsComputed) {
this.graph.removeNode(varComputed);
}
}
}
export default ComputedDataQueue;

View File

@@ -0,0 +1,70 @@
import lodash from "@11ty/lodash-custom";
import debugUtil from "debug";
const { set: lodashSet } = lodash;
const debug = debugUtil("Eleventy:ComputedDataTemplateString");
/* Calculates computed data in Template Strings.
* Ideally we would use the Proxy approach but it doesnt work
* in some template languages that visit all available data even if
* it isnt used in the template (Nunjucks)
*/
class ComputedDataTemplateString {
constructor(computedKeys) {
if (Array.isArray(computedKeys)) {
this.computedKeys = new Set(computedKeys);
} else {
this.computedKeys = computedKeys;
}
// is this ¯\_(lisp)_/¯
// must be strings that wont be escaped by template languages
this.prefix = "(((11ty(((";
this.suffix = ")))11ty)))";
}
getProxyData() {
let proxyData = {};
// use these special strings as a workaround to check the rendered output
// cant use proxies here as some template languages trigger proxy for all
// keys in data
for (let key of this.computedKeys) {
// TODO dont allow to set eleventyComputed.page? other disallowed computed things?
lodashSet(proxyData, key, this.prefix + key + this.suffix);
}
return proxyData;
}
findVarsInOutput(output = "") {
let vars = new Set();
let splits = output.split(this.prefix);
for (let split of splits) {
let varName = split.slice(0, split.indexOf(this.suffix) < 0 ? 0 : split.indexOf(this.suffix));
if (varName) {
vars.add(varName);
}
}
return Array.from(vars);
}
async findVarsUsed(fn) {
let proxyData = this.getProxyData();
let output;
// Mitigation for #1061, errors with filters in the first pass shouldnt fail the whole thing.
try {
output = await fn(proxyData);
} catch (e) {
debug("Computed Data first pass data resolution error: %o", e);
}
// page.outputPath on serverless urls returns false.
if (typeof output === "string") {
return this.findVarsInOutput(output);
}
return [];
}
}
export default ComputedDataTemplateString;

737
node_modules/@11ty/eleventy/src/Data/TemplateData.js generated vendored Normal file
View File

@@ -0,0 +1,737 @@
import path from "node:path";
import semver from "semver";
import lodash from "@11ty/lodash-custom";
import { Merge, TemplatePath, isPlainObject } from "@11ty/eleventy-utils";
import debugUtil from "debug";
import unique from "../Util/Objects/Unique.js";
import TemplateGlob from "../TemplateGlob.js";
import EleventyExtensionMap from "../EleventyExtensionMap.js";
import EleventyBaseError from "../Errors/EleventyBaseError.js";
import TemplateDataInitialGlobalData from "./TemplateDataInitialGlobalData.js";
import { getEleventyPackageJson, getWorkingProjectPackageJson } from "../Util/ImportJsonSync.js";
import { EleventyImport, EleventyLoadContent } from "../Util/Require.js";
import { DeepFreeze } from "../Util/Objects/DeepFreeze.js";
const { set: lodashSet, get: lodashGet } = lodash;
const debugWarn = debugUtil("Eleventy:Warnings");
const debug = debugUtil("Eleventy:TemplateData");
const debugDev = debugUtil("Dev:Eleventy:TemplateData");
class TemplateDataConfigError extends EleventyBaseError {}
class TemplateDataParseError extends EleventyBaseError {}
class TemplateData {
constructor(eleventyConfig) {
if (!eleventyConfig) {
throw new TemplateDataConfigError("Missing `config`.");
}
this.eleventyConfig = eleventyConfig;
this.config = this.eleventyConfig.getConfig();
this.benchmarks = {
data: this.config.benchmarkManager.get("Data"),
aggregate: this.config.benchmarkManager.get("Aggregate"),
};
this.rawImports = {};
this.globalData = null;
this.templateDirectoryData = {};
this.isEsm = false;
this.initialGlobalData = new TemplateDataInitialGlobalData(this.eleventyConfig);
}
get dirs() {
return this.eleventyConfig.directories;
}
get inputDir() {
return this.dirs.input;
}
// if this was set but `falsy` we would fallback to inputDir
get dataDir() {
return this.dirs.data;
}
// This was async in 2.0 and prior but doesnt need to be any more.
getInputDir() {
return this.dirs.input;
}
getDataDir() {
return this.dataDir;
}
get _fsExistsCache() {
// It's common for data files not to exist, so we avoid going to the FS to
// re-check if they do via a quick-and-dirty cache.
return this.eleventyConfig.existsCache;
}
setFileSystemSearch(fileSystemSearch) {
this.fileSystemSearch = fileSystemSearch;
}
setProjectUsingEsm(isEsmProject) {
this.isEsm = !!isEsmProject;
}
get extensionMap() {
if (!this._extensionMap) {
this._extensionMap = new EleventyExtensionMap(this.eleventyConfig);
this._extensionMap.setFormats([]);
}
return this._extensionMap;
}
set extensionMap(map) {
this._extensionMap = map;
}
get environmentVariables() {
return this._env;
}
set environmentVariables(env) {
this._env = env;
}
/* Used by tests */
_setConfig(config) {
this.config = config;
}
getRawImports() {
if (!this.config.keys.package) {
debug(
"Opted-out of package.json assignment for global data with falsy value for `keys.package` configuration.",
);
return this.rawImports;
} else if (Object.keys(this.rawImports).length > 0) {
return this.rawImports;
}
try {
let pkgJson = getWorkingProjectPackageJson();
this.rawImports[this.config.keys.package] = pkgJson;
if (this.config.freezeReservedData) {
DeepFreeze(this.rawImports);
}
} catch (e) {
debug("Could not find or require package.json import for global data.");
}
return this.rawImports;
}
clearData() {
this.globalData = null;
this.configApiGlobalData = null;
this.templateDirectoryData = {};
}
_getGlobalDataGlobByExtension(extension) {
return TemplateGlob.normalizePath(this.dataDir, `/**/*.${extension}`);
}
// This is a backwards compatibility helper with the old `jsDataFileSuffix` configuration API
getDataFileSuffixes() {
// New API
if (Array.isArray(this.config.dataFileSuffixes)) {
return this.config.dataFileSuffixes;
}
// Backwards compatibility
if (this.config.jsDataFileSuffix) {
let suffixes = [];
suffixes.push(this.config.jsDataFileSuffix); // e.g. filename.11tydata.json
suffixes.push(""); // suffix-less for free with old API, e.g. filename.json
return suffixes;
}
return []; // if both of these entries are set to false, use no files
}
// This is used exclusively for --watch and --serve chokidar targets
async getTemplateDataFileGlob() {
let suffixes = this.getDataFileSuffixes();
let globSuffixesWithLeadingDot = new Set();
globSuffixesWithLeadingDot.add("json"); // covers .11tydata.json too
let globSuffixesWithoutLeadingDot = new Set();
// Typically using [ '.11tydata', '' ] suffixes to find data files
for (let suffix of suffixes) {
// TODO the `suffix` truthiness check is purely for backwards compat?
if (suffix && typeof suffix === "string") {
if (suffix.startsWith(".")) {
// .suffix.js
globSuffixesWithLeadingDot.add(`${suffix.slice(1)}.mjs`);
globSuffixesWithLeadingDot.add(`${suffix.slice(1)}.cjs`);
globSuffixesWithLeadingDot.add(`${suffix.slice(1)}.js`);
} else {
// "suffix.js" without leading dot
globSuffixesWithoutLeadingDot.add(`${suffix || ""}.mjs`);
globSuffixesWithoutLeadingDot.add(`${suffix || ""}.cjs`);
globSuffixesWithoutLeadingDot.add(`${suffix || ""}.js`);
}
}
}
// Configuration Data Extensions e.g. yaml
if (this.hasUserDataExtensions()) {
for (let extension of this.getUserDataExtensions()) {
globSuffixesWithLeadingDot.add(extension); // covers .11tydata.{extension} too
}
}
let paths = [];
if (globSuffixesWithLeadingDot.size > 0) {
paths.push(`${this.inputDir}**/*.{${Array.from(globSuffixesWithLeadingDot).join(",")}}`);
}
if (globSuffixesWithoutLeadingDot.size > 0) {
paths.push(`${this.inputDir}**/*{${Array.from(globSuffixesWithoutLeadingDot).join(",")}}`);
}
return TemplatePath.addLeadingDotSlashArray(paths);
}
// For spidering dependencies
// TODO Can we reuse getTemplateDataFileGlob instead? Maybe just filter off the .json files before scanning for dependencies
getTemplateJavaScriptDataFileGlob() {
let paths = [];
let suffixes = this.getDataFileSuffixes();
for (let suffix of suffixes) {
if (suffix) {
// TODO this check is purely for backwards compat and I kinda feel like it shouldnt be here
// paths.push(`${this.inputDir}/**/*${suffix || ""}.cjs`); // Same as above
paths.push(`${this.inputDir}**/*${suffix || ""}.js`);
}
}
return TemplatePath.addLeadingDotSlashArray(paths);
}
getGlobalDataGlob() {
let extGlob = this.getGlobalDataExtensionPriorities().join(",");
return [this._getGlobalDataGlobByExtension("{" + extGlob + "}")];
}
getWatchPathCache() {
return this.pathCache;
}
getGlobalDataExtensionPriorities() {
return this.getUserDataExtensions().concat(["json", "mjs", "cjs", "js"]);
}
static calculateExtensionPriority(path, priorities) {
for (let i = 0; i < priorities.length; i++) {
let ext = priorities[i];
if (path.endsWith(ext)) {
return i;
}
}
return priorities.length;
}
async getGlobalDataFiles() {
let priorities = this.getGlobalDataExtensionPriorities();
let fsBench = this.benchmarks.aggregate.get("Searching the file system (data)");
fsBench.before();
let globs = this.getGlobalDataGlob();
let paths = await this.fileSystemSearch.search("global-data", globs);
fsBench.after();
// sort paths according to extension priorities
// here we use reverse ordering, because paths with bigger index in array will override the first ones
// example [path/file.json, path/file.js] here js will override json
paths = paths.sort((first, second) => {
let p1 = TemplateData.calculateExtensionPriority(first, priorities);
let p2 = TemplateData.calculateExtensionPriority(second, priorities);
if (p1 < p2) {
return -1;
}
if (p1 > p2) {
return 1;
}
return 0;
});
this.pathCache = paths;
return paths;
}
getObjectPathForDataFile(dataFilePath) {
let reducedPath = TemplatePath.stripLeadingSubPath(dataFilePath, this.dataDir);
let parsed = path.parse(reducedPath);
let folders = parsed.dir ? parsed.dir.split("/") : [];
folders.push(parsed.name);
return folders;
}
async getAllGlobalData() {
let globalData = {};
let files = TemplatePath.addLeadingDotSlashArray(await this.getGlobalDataFiles());
this.config.events.emit("eleventy.globalDataFiles", files);
let dataFileConflicts = {};
for (let j = 0, k = files.length; j < k; j++) {
let data = await this.getDataValue(files[j]);
let objectPathTarget = this.getObjectPathForDataFile(files[j]);
// Since we're joining directory paths and an array is not usable as an objectkey since two identical arrays are not double equal,
// we can just join the array by a forbidden character ("/"" is chosen here, since it works on Linux, Mac and Windows).
// If at some point this isn't enough anymore, it would be possible to just use JSON.stringify(objectPathTarget) since that
// is guaranteed to work but is signifivcantly slower.
let objectPathTargetString = objectPathTarget.join(path.sep);
// if two global files have the same path (but different extensions)
// and conflict, lets merge them.
if (dataFileConflicts[objectPathTargetString]) {
debugWarn(
`merging global data from ${files[j]} with an already existing global data file (${dataFileConflicts[objectPathTargetString]}). Overriding existing keys.`,
);
let oldData = lodashGet(globalData, objectPathTarget);
data = TemplateData.mergeDeep(this.config.dataDeepMerge, oldData, data);
}
dataFileConflicts[objectPathTargetString] = files[j];
debug(`Found global data file ${files[j]} and adding as: ${objectPathTarget}`);
lodashSet(globalData, objectPathTarget, data);
}
return globalData;
}
async #getInitialGlobalData() {
let globalData = await this.initialGlobalData.getData();
if (!("eleventy" in globalData)) {
globalData.eleventy = {};
}
// #2293 for meta[name=generator]
const pkg = getEleventyPackageJson();
globalData.eleventy.version = semver.coerce(pkg.version).toString();
globalData.eleventy.generator = `Eleventy v${globalData.eleventy.version}`;
if (this.environmentVariables) {
if (!("env" in globalData.eleventy)) {
globalData.eleventy.env = {};
}
Object.assign(globalData.eleventy.env, this.environmentVariables);
}
if (this.dirs) {
if (!("directories" in globalData.eleventy)) {
globalData.eleventy.directories = {};
}
Object.assign(globalData.eleventy.directories, this.dirs.getUserspaceInstance());
}
// Reserved
if (this.config.freezeReservedData) {
DeepFreeze(globalData.eleventy);
}
return globalData;
}
async getInitialGlobalData() {
if (!this.configApiGlobalData) {
this.configApiGlobalData = this.#getInitialGlobalData();
}
return this.configApiGlobalData;
}
async #getGlobalData() {
let rawImports = this.getRawImports();
let configApiGlobalData = await this.getInitialGlobalData();
let globalJson = await this.getAllGlobalData();
let mergedGlobalData = Merge(globalJson, configApiGlobalData);
// OK: Shallow merge when combining rawImports (pkg) with global data files
return Object.assign({}, mergedGlobalData, rawImports);
}
async getGlobalData() {
if (!this.globalData) {
this.globalData = this.#getGlobalData();
}
return this.globalData;
}
/* Template and Directory data files */
async combineLocalData(localDataPaths) {
let localData = {};
if (!Array.isArray(localDataPaths)) {
localDataPaths = [localDataPaths];
}
// Filter out files we know don't exist to avoid overhead for checking
const dataPaths = await Promise.all(
localDataPaths.map((path) => {
if (this._fsExistsCache.exists(path)) {
return path;
}
return false;
}),
);
localDataPaths = dataPaths.filter((pathOrFalse) => {
return pathOrFalse === false ? false : true;
});
this.config.events.emit("eleventy.dataFiles", localDataPaths);
if (!localDataPaths.length) {
return localData;
}
let dataSource = {};
for (let path of localDataPaths) {
let dataForPath = await this.getDataValue(path);
if (!isPlainObject(dataForPath)) {
debug(
"Warning: Template and Directory data files expect an object to be returned, instead `%o` returned `%o`",
path,
dataForPath,
);
} else {
// clean up data for template/directory data files only.
let cleanedDataForPath = TemplateData.cleanupData(dataForPath);
for (let key in cleanedDataForPath) {
if (Object.prototype.hasOwnProperty.call(dataSource, key)) {
debugWarn(
"Local data files have conflicting data. Overwriting '%s' with data from '%s'. Previous data location was from '%s'",
key,
path,
dataSource[key],
);
}
dataSource[key] = path;
}
TemplateData.mergeDeep(this.config.dataDeepMerge, localData, cleanedDataForPath);
}
}
return localData;
}
async getTemplateDirectoryData(templatePath) {
if (!this.templateDirectoryData[templatePath]) {
let localDataPaths = await this.getLocalDataPaths(templatePath);
let importedData = await this.combineLocalData(localDataPaths);
this.templateDirectoryData[templatePath] = Object.assign({}, importedData);
}
return this.templateDirectoryData[templatePath];
}
getUserDataExtensions() {
if (!this.config.dataExtensions) {
return [];
}
// returning extensions in reverse order to create proper extension order
// later added formats will override first ones
return Array.from(this.config.dataExtensions.keys()).reverse();
}
getUserDataParser(extension) {
return this.config.dataExtensions.get(extension);
}
isUserDataExtension(extension) {
return this.config.dataExtensions && this.config.dataExtensions.has(extension);
}
hasUserDataExtensions() {
return this.config.dataExtensions && this.config.dataExtensions.size > 0;
}
async _parseDataFile(path, parser, options = {}) {
let readFile = !("read" in options) || options.read === true;
let rawInput;
if (readFile) {
rawInput = EleventyLoadContent(path, options);
}
if (readFile && !rawInput) {
return {};
}
try {
if (readFile) {
return parser(rawInput, path);
} else {
// path as a first argument is when `read: false`
// path as a second argument is for consistency with `read: true` API
return parser(path, path);
}
} catch (e) {
throw new TemplateDataParseError(`Having trouble parsing data file ${path}`, e);
}
}
// ignoreProcessing = false for global data files
// ignoreProcessing = true for local data files
async getDataValue(path) {
let extension = TemplatePath.getExtension(path);
if (extension === "js" || extension === "cjs" || extension === "mjs") {
// JS data file or required JSON (no preprocessing needed)
let localPath = TemplatePath.absolutePath(path);
let exists = this._fsExistsCache.exists(localPath);
// Make sure that relative lookups benefit from cache
this._fsExistsCache.markExists(path, exists);
if (!exists) {
return {};
}
let aggregateDataBench = this.benchmarks.aggregate.get("Data File");
aggregateDataBench.before();
let dataBench = this.benchmarks.data.get(`\`${path}\``);
dataBench.before();
let type = "cjs";
if (extension === "mjs" || (extension === "js" && this.isEsm)) {
type = "esm";
}
// We always need to use `import()`, as `require` isnt available in ESM.
let returnValue = await EleventyImport(localPath, type);
// TODO special exception for Global data `permalink.js`
// module.exports = (data) => `${data.page.filePathStem}/`; // Does not work
// module.exports = () => ((data) => `${data.page.filePathStem}/`); // Works
if (typeof returnValue === "function") {
let configApiGlobalData = await this.getInitialGlobalData();
returnValue = await returnValue(configApiGlobalData || {});
}
dataBench.after();
aggregateDataBench.after();
return returnValue;
} else if (this.isUserDataExtension(extension)) {
// Other extensions
let { parser, options } = this.getUserDataParser(extension);
return this._parseDataFile(path, parser, options);
} else if (extension === "json") {
// File to string, parse with JSON (preprocess)
const parser = (content) => JSON.parse(content);
return this._parseDataFile(path, parser);
} else {
throw new TemplateDataParseError(
`Could not find an appropriate data parser for ${path}. Do you need to add a plugin to your config file?`,
);
}
}
_pushExtensionsToPaths(paths, curpath, extensions) {
for (let extension of extensions) {
paths.push(curpath + "." + extension);
}
}
_addBaseToPaths(paths, base, extensions, nonEmptySuffixesOnly = false) {
let suffixes = this.getDataFileSuffixes();
for (let suffix of suffixes) {
suffix = suffix || "";
if (nonEmptySuffixesOnly && suffix === "") {
continue;
}
// data suffix
if (suffix) {
paths.push(base + suffix + ".js");
paths.push(base + suffix + ".cjs");
paths.push(base + suffix + ".mjs");
}
paths.push(base + suffix + ".json"); // default: .11tydata.json
// inject user extensions
this._pushExtensionsToPaths(paths, base + suffix, extensions);
}
}
async getLocalDataPaths(templatePath) {
let paths = [];
let parsed = path.parse(templatePath);
let inputDir = this.inputDir;
debugDev("getLocalDataPaths(%o)", templatePath);
debugDev("parsed.dir: %o", parsed.dir);
let userExtensions = this.getUserDataExtensions();
if (parsed.dir) {
let fileNameNoExt = this.extensionMap.removeTemplateExtension(parsed.base);
// default dataSuffix: .11tydata, is appended in _addBaseToPaths
debug("Using %o suffixes to find data files.", this.getDataFileSuffixes());
// Template data file paths
let filePathNoExt = parsed.dir + "/" + fileNameNoExt;
this._addBaseToPaths(paths, filePathNoExt, userExtensions);
// Directory data file paths
let allDirs = TemplatePath.getAllDirs(parsed.dir);
debugDev("allDirs: %o", allDirs);
for (let dir of allDirs) {
let lastDir = TemplatePath.getLastPathSegment(dir);
let dirPathNoExt = dir + "/" + lastDir;
if (inputDir) {
debugDev("dirStr: %o; inputDir: %o", dir, inputDir);
}
if (!inputDir || (dir.startsWith(inputDir) && dir !== inputDir)) {
if (this.config.dataFileDirBaseNameOverride) {
let indexDataFile = dir + "/" + this.config.dataFileDirBaseNameOverride;
this._addBaseToPaths(paths, indexDataFile, userExtensions, true);
} else {
this._addBaseToPaths(paths, dirPathNoExt, userExtensions);
}
}
}
// 0.11.0+ include root input dir files
// if using `docs/` as input dir, looks for docs/docs.json et al
if (inputDir) {
let lastInputDir = TemplatePath.addLeadingDotSlash(
TemplatePath.join(inputDir, TemplatePath.getLastPathSegment(inputDir)),
);
// in root input dir, search for index.11tydata.json et al
if (this.config.dataFileDirBaseNameOverride) {
let indexDataFile =
TemplatePath.getDirFromFilePath(lastInputDir) +
"/" +
this.config.dataFileDirBaseNameOverride;
this._addBaseToPaths(paths, indexDataFile, userExtensions, true);
} else if (lastInputDir !== "./") {
this._addBaseToPaths(paths, lastInputDir, userExtensions);
}
}
}
debug("getLocalDataPaths(%o): %o", templatePath, paths);
return unique(paths).reverse();
}
static mergeDeep(deepMerge, target, ...source) {
if (!deepMerge && deepMerge !== undefined) {
return Object.assign(target, ...source);
} else {
return TemplateData.merge(target, ...source);
}
}
static merge(target, ...source) {
return Merge(target, ...source);
}
/* Like cleanupData() but does not mutate */
static getCleanedTagsImmutable(data) {
let tags = [];
if (isPlainObject(data) && data.tags) {
if (typeof data.tags === "string") {
tags = (data.tags || "").split(",");
} else if (Array.isArray(data.tags)) {
tags = data.tags;
}
// Deduplicate tags
return [...new Set(tags)];
}
return tags;
}
static cleanupData(data) {
if (isPlainObject(data) && "tags" in data) {
if (typeof data.tags === "string") {
data.tags = data.tags ? [data.tags] : [];
} else if (data.tags === null) {
data.tags = [];
}
// Deduplicate tags
data.tags = [...new Set(data.tags)];
}
return data;
}
static getNormalizedExcludedCollections(data) {
let excludes = [];
let key = "eleventyExcludeFromCollections";
if (data?.[key] !== true) {
if (Array.isArray(data[key])) {
excludes = data[key];
} else if (typeof data[key] === "string") {
excludes = (data[key] || "").split(",");
}
}
return {
excludes,
excludeAll: data?.eleventyExcludeFromCollections === true,
};
}
/* Same as getIncludedTagNames() but may also include "all" */
static getIncludedCollectionNames(data) {
let tags = TemplateData.getCleanedTagsImmutable(data);
if (tags.length > 0) {
let { excludes, excludeAll } = TemplateData.getNormalizedExcludedCollections(data);
if (excludeAll) {
return [];
} else {
return ["all", ...tags].filter((tag) => !excludes.includes(tag));
}
} else {
return ["all"];
}
}
static getIncludedTagNames(data) {
let tags = TemplateData.getCleanedTagsImmutable(data);
if (tags.length > 0) {
let { excludes, excludeAll } = TemplateData.getNormalizedExcludedCollections(data);
if (excludeAll) {
return [];
} else {
return tags.filter((tag) => !excludes.includes(tag));
}
} else {
return [];
}
}
}
export default TemplateData;

View File

@@ -0,0 +1,40 @@
import lodash from "@11ty/lodash-custom";
import EleventyBaseError from "../Errors/EleventyBaseError.js";
const { set: lodashSet } = lodash;
class TemplateDataConfigError extends EleventyBaseError {}
class TemplateDataInitialGlobalData {
constructor(templateConfig) {
if (!templateConfig || templateConfig.constructor.name !== "TemplateConfig") {
throw new TemplateDataConfigError("Missing or invalid `templateConfig` (via Render plugin).");
}
this.templateConfig = templateConfig;
this.config = this.templateConfig.getConfig();
}
async getData() {
let globalData = {};
// via eleventyConfig.addGlobalData
if (this.config.globalData) {
let keys = Object.keys(this.config.globalData);
for (let key of keys) {
let returnValue = this.config.globalData[key];
// This section is problematic when used with eleventyComputed #3389
if (typeof returnValue === "function") {
returnValue = await returnValue();
}
lodashSet(globalData, key, returnValue);
}
}
return globalData;
}
}
export default TemplateDataInitialGlobalData;

1472
node_modules/@11ty/eleventy/src/Eleventy.js generated vendored Normal file

File diff suppressed because it is too large Load Diff

43
node_modules/@11ty/eleventy/src/EleventyCommonJs.cjs generated vendored Normal file
View File

@@ -0,0 +1,43 @@
function canRequireModules() {
// via --experimental-require-module or newer than Node 22 support when this flag is no longer necessary
try {
require("./Util/Objects/SampleModule.mjs");
return true;
} catch(e) {
if(e.code === "ERR_REQUIRE_ESM") {
return false;
}
// Rethrow if not an ESM require error.
throw e;
}
}
if(!canRequireModules()) {
let error = new Error(`\`require("@11ty/eleventy")\` is incompatible with Eleventy v3 and this version of Node. You have a few options:
1. (Easiest) Change the \`require\` to use a dynamic import inside of an asynchronous CommonJS configuration
callback, for example:
module.exports = async function {
const {EleventyRenderPlugin, EleventyI18nPlugin, EleventyHtmlBasePlugin} = await import("@11ty/eleventy");
}
2. (Easier) Update the JavaScript syntax in your configuration file from CommonJS to ESM (change \`require\`
to use \`import\` and rename the file to have an \`.mjs\` file extension).
3. (More work) Change your project to use ESM-first by adding \`"type": "module"\` to your package.json. Any
\`.js\` will need to be ported to use ESM syntax (or renamed to \`.cjs\`.)
4. (Short term workaround) Use the --experimental-require-module flag to enable this behavior. Read
more: https://nodejs.org/api/modules.html#loading-ecmascript-modules-using-require It is possible that the
newest version of Node has this enabled by default—you can try upgrading your version of Node.js.`);
error.skipOriginalStack = true;
throw error;
}
// If we made it here require(ESM) works fine (via --experimental-require-module or newer Node.js defaults)
let mod = require("./Eleventy.js");
module.exports = mod;

284
node_modules/@11ty/eleventy/src/EleventyExtensionMap.js generated vendored Normal file
View File

@@ -0,0 +1,284 @@
import { TemplatePath } from "@11ty/eleventy-utils";
import TemplateEngineManager from "./Engines/TemplateEngineManager.js";
import EleventyBaseError from "./Errors/EleventyBaseError.js";
class EleventyExtensionMapConfigError extends EleventyBaseError {}
class EleventyExtensionMap {
constructor(config) {
this.config = config;
this._spiderJsDepsCache = {};
/** @type {Array} */
this.validTemplateLanguageKeys;
}
setFormats(formatKeys = []) {
// raw
this.formatKeys = formatKeys;
this.unfilteredFormatKeys = formatKeys.map(function (key) {
return key.trim().toLowerCase();
});
this.validTemplateLanguageKeys = this.unfilteredFormatKeys.filter((key) =>
this.hasExtension(key),
);
this.passthroughCopyKeys = this.unfilteredFormatKeys.filter((key) => !this.hasExtension(key));
}
set config(cfg) {
if (!cfg || cfg.constructor.name !== "TemplateConfig") {
throw new EleventyExtensionMapConfigError(
"Missing or invalid `config` argument (via setter).",
);
}
this.eleventyConfig = cfg;
}
get config() {
return this.eleventyConfig.getConfig();
}
get engineManager() {
if (!this._engineManager) {
this._engineManager = new TemplateEngineManager(this.eleventyConfig);
}
return this._engineManager;
}
reset() {
this.engineManager.reset();
}
/* Used for layout path resolution */
getFileList(path, dir) {
if (!path) {
return [];
}
let files = [];
this.validTemplateLanguageKeys.forEach((key) => {
this.getExtensionsFromKey(key).forEach(function (extension) {
files.push((dir ? dir + "/" : "") + path + "." + extension);
});
});
return files;
}
// Warning: this would false positive on an include, but is only used
// on paths found from the file system glob search.
// TODO: Method name might just need to be renamed to something more accurate.
isFullTemplateFilePath(path) {
for (let extension of this.validTemplateLanguageKeys) {
if (path.endsWith(`.${extension}`)) {
return true;
}
}
return false;
}
getCustomExtensionEntry(extension) {
if (!this.config.extensionMap) {
return;
}
for (let entry of this.config.extensionMap) {
if (entry.extension === extension) {
return entry;
}
}
}
getValidExtensionsForPath(path) {
let extensions = new Set();
for (let extension in this.extensionToKeyMap) {
if (path.endsWith(`.${extension}`)) {
extensions.add(extension);
}
}
// if multiple extensions are valid, sort from longest to shortest
// e.g. .11ty.js and .js
let sorted = Array.from(extensions)
.filter((extension) => this.validTemplateLanguageKeys.includes(extension))
.sort((a, b) => b.length - a.length);
return sorted;
}
async shouldSpiderJavaScriptDependencies(path) {
let extensions = this.getValidExtensionsForPath(path);
for (let extension of extensions) {
if (extension in this._spiderJsDepsCache) {
return this._spiderJsDepsCache[extension];
}
let cls = await this.engineManager.getEngineClassByExtension(extension);
if (cls) {
let entry = this.getCustomExtensionEntry(extension);
let shouldSpider = cls.shouldSpiderJavaScriptDependencies(entry);
this._spiderJsDepsCache[extension] = shouldSpider;
return shouldSpider;
}
}
return false;
}
getPassthroughCopyGlobs(inputDir) {
return this._getGlobs(this.passthroughCopyKeys, inputDir);
}
getValidGlobs(inputDir) {
return this._getGlobs(this.validTemplateLanguageKeys, inputDir);
}
getGlobs(inputDir) {
return this._getGlobs(this.unfilteredFormatKeys, inputDir);
}
_getGlobs(formatKeys, inputDir) {
let dir = TemplatePath.convertToRecursiveGlobSync(inputDir);
let extensions = new Set();
for (let key of formatKeys) {
if (this.hasExtension(key)) {
for (let extension of this.getExtensionsFromKey(key)) {
extensions.add(extension);
}
} else {
extensions.add(key);
}
}
if (extensions.size === 1) {
return [`${dir}/*.${Array.from(extensions)[0]}`];
} else if (extensions.size > 1) {
return [
// extra curly brackets /*.{cjs,txt}
`${dir}/*.{${Array.from(extensions).join(",")}}`,
];
}
return [];
}
hasExtension(key) {
for (let extension in this.extensionToKeyMap) {
if (
this.extensionToKeyMap[extension].key === key ||
this.extensionToKeyMap[extension].aliasKey === key
) {
return true;
}
}
return false;
}
getExtensionsFromKey(key) {
let extensions = new Set();
for (let extension in this.extensionToKeyMap) {
if (this.extensionToKeyMap[extension].aliasKey) {
// only add aliased extension if explicitly referenced in formats
// overrides will not have an aliasKey (md => md)
if (this.extensionToKeyMap[extension].aliasKey === key) {
extensions.add(extension);
}
} else if (this.extensionToKeyMap[extension].key === key) {
extensions.add(extension);
}
}
return Array.from(extensions);
}
// Only `addExtension` configuration API extensions
getExtensionEntriesFromKey(key) {
let entries = new Set();
if ("extensionMap" in this.config) {
for (let entry of this.config.extensionMap) {
if (entry.key === key) {
entries.add(entry);
}
}
}
return Array.from(entries);
}
// Determines whether a path is a passthrough copy file or a template (via TemplateWriter)
hasEngine(pathOrKey) {
return !!this.getKey(pathOrKey);
}
getKey(pathOrKey) {
pathOrKey = (pathOrKey || "").toLowerCase();
for (let extension in this.extensionToKeyMap) {
if (pathOrKey === extension || pathOrKey.endsWith("." + extension)) {
let key =
this.extensionToKeyMap[extension].aliasKey || this.extensionToKeyMap[extension].key;
// must be a valid format key passed (e.g. via --formats)
if (this.validTemplateLanguageKeys.includes(key)) {
return key;
}
}
}
}
getExtensionEntry(pathOrKey) {
pathOrKey = (pathOrKey || "").toLowerCase();
for (let extension in this.extensionToKeyMap) {
if (pathOrKey === extension || pathOrKey.endsWith("." + extension)) {
return this.extensionToKeyMap[extension];
}
}
}
removeTemplateExtension(path) {
for (let extension in this.extensionToKeyMap) {
if (path === extension || path.endsWith("." + extension)) {
return path.slice(
0,
path.length - 1 - extension.length < 0 ? 0 : path.length - 1 - extension.length,
);
}
}
return path;
}
// keys are file extensions
// values are template language keys
get extensionToKeyMap() {
if (!this._extensionToKeyMap) {
this._extensionToKeyMap = {
md: { key: "md", extension: "md" },
html: { key: "html", extension: "html" },
njk: { key: "njk", extension: "njk" },
liquid: { key: "liquid", extension: "liquid" },
"11ty.js": { key: "11ty.js", extension: "11ty.js" },
"11ty.cjs": { key: "11ty.js", extension: "11ty.cjs" },
"11ty.mjs": { key: "11ty.js", extension: "11ty.mjs" },
};
if ("extensionMap" in this.config) {
for (let entry of this.config.extensionMap) {
// extension and key are only different when aliasing.
this._extensionToKeyMap[entry.extension] = entry;
}
}
}
return this._extensionToKeyMap;
}
getReadableFileExtensions() {
return Object.keys(this.extensionToKeyMap).join(" ");
}
}
export default EleventyExtensionMap;

517
node_modules/@11ty/eleventy/src/EleventyFiles.js generated vendored Normal file
View File

@@ -0,0 +1,517 @@
import fs from "node:fs";
import { TemplatePath, isPlainObject } from "@11ty/eleventy-utils";
import debugUtil from "debug";
import EleventyExtensionMap from "./EleventyExtensionMap.js";
import TemplateData from "./Data/TemplateData.js";
import TemplateGlob from "./TemplateGlob.js";
import TemplatePassthroughManager from "./TemplatePassthroughManager.js";
import EleventyBaseError from "./Errors/EleventyBaseError.js";
import checkPassthroughCopyBehavior from "./Util/PassthroughCopyBehaviorCheck.js";
const debug = debugUtil("Eleventy:EleventyFiles");
class EleventyFilesError extends EleventyBaseError {}
class EleventyFiles {
constructor(formats, eleventyConfig) {
if (!eleventyConfig) {
throw new EleventyFilesError("Missing `eleventyConfig`` argument.");
}
this.eleventyConfig = eleventyConfig;
this.config = eleventyConfig.getConfig();
this.aggregateBench = this.config.benchmarkManager.get("Aggregate");
this.formats = formats;
this.eleventyIgnoreContent = false;
}
get dirs() {
return this.eleventyConfig.directories;
}
get inputDir() {
return this.dirs.input;
}
get outputDir() {
return this.dirs.output;
}
get includesDir() {
return this.dirs.includes;
}
get layoutsDir() {
return this.dirs.layouts;
}
get dataDir() {
return this.dirs.data;
}
// Backwards compat
getDataDir() {
return this.dataDir;
}
setFileSystemSearch(fileSystemSearch) {
this.fileSystemSearch = fileSystemSearch;
}
init() {
if (this.dirs.inputFile || this.dirs.inputGlob) {
this.templateGlobs = TemplateGlob.map([this.dirs.inputFile || this.dirs.inputGlob]);
} else {
// Input is a directory
this.templateGlobs = this.extensionMap.getGlobs(this.inputDir);
}
this.initPassthroughManager();
this.setupGlobs();
}
get validTemplateGlobs() {
if (!this._validTemplateGlobs) {
let globs;
// Input is a file
if (this.inputFile) {
globs = this.templateGlobs;
} else {
// input is a directory
globs = this.extensionMap.getValidGlobs(this.inputDir);
}
this._validTemplateGlobs = globs;
}
return this._validTemplateGlobs;
}
get passthroughGlobs() {
let paths = new Set();
// stuff added in addPassthroughCopy()
for (let path of this.passthroughManager.getConfigPathGlobs()) {
paths.add(path);
}
// non-template language extensions
for (let path of this.extensionMap.getPassthroughCopyGlobs(this.inputDir)) {
paths.add(path);
}
return Array.from(paths);
}
restart() {
this.passthroughManager.reset();
this.setupGlobs();
this._glob = null;
}
/* For testing */
_setConfig(config) {
if (!config.ignores) {
config.ignores = new Set();
config.ignores.add("**/node_modules/**");
}
this.config = config;
}
/* Set command root for local project paths */
// This is only used by tests
_setLocalPathRoot(dir) {
this.localPathRoot = dir;
}
set extensionMap(extensionMap) {
this._extensionMap = extensionMap;
}
get extensionMap() {
// for tests
if (!this._extensionMap) {
this._extensionMap = new EleventyExtensionMap(this.eleventyConfig);
this._extensionMap.setFormats(this.formats);
this._extensionMap.config = this.eleventyConfig;
}
return this._extensionMap;
}
setRunMode(runMode) {
this.runMode = runMode;
}
initPassthroughManager() {
let mgr = new TemplatePassthroughManager(this.eleventyConfig);
mgr.setRunMode(this.runMode);
mgr.extensionMap = this.extensionMap;
mgr.setFileSystemSearch(this.fileSystemSearch);
this.passthroughManager = mgr;
}
getPassthroughManager() {
return this.passthroughManager;
}
setPassthroughManager(mgr) {
mgr.extensionMap = this.extensionMap;
this.passthroughManager = mgr;
}
set templateData(templateData) {
this._templateData = templateData;
}
get templateData() {
if (!this._templateData) {
this._templateData = new TemplateData(this.eleventyConfig);
}
return this._templateData;
}
setupGlobs() {
this.fileIgnores = this.getIgnores();
this.extraIgnores = this._getIncludesAndDataDirs();
this.uniqueIgnores = this.getIgnoreGlobs();
// Conditional added for tests that dont have a config
if (this.config?.events) {
this.config.events.emit("eleventy.ignores", this.uniqueIgnores);
}
this.normalizedTemplateGlobs = this.templateGlobs;
}
getIgnoreGlobs() {
let uniqueIgnores = new Set();
for (let ignore of this.fileIgnores) {
uniqueIgnores.add(ignore);
}
for (let ignore of this.extraIgnores) {
uniqueIgnores.add(ignore);
}
// Placing the config ignores last here is important to the tests
for (let ignore of this.config.ignores) {
uniqueIgnores.add(TemplateGlob.normalizePath(this.localPathRoot || ".", ignore));
}
return Array.from(uniqueIgnores);
}
static getFileIgnores(ignoreFiles) {
if (!Array.isArray(ignoreFiles)) {
ignoreFiles = [ignoreFiles];
}
let ignores = [];
for (let ignorePath of ignoreFiles) {
ignorePath = TemplatePath.normalize(ignorePath);
let dir = TemplatePath.getDirFromFilePath(ignorePath);
if (fs.existsSync(ignorePath) && fs.statSync(ignorePath).size > 0) {
let ignoreContent = fs.readFileSync(ignorePath, "utf8");
ignores = ignores.concat(EleventyFiles.normalizeIgnoreContent(dir, ignoreContent));
}
}
ignores.forEach((path) => debug(`${ignoreFiles} ignoring: ${path}`));
return ignores;
}
static normalizeIgnoreContent(dir, ignoreContent) {
let ignores = [];
if (ignoreContent) {
ignores = ignoreContent
.split("\n")
.map((line) => {
return line.trim();
})
.filter((line) => {
if (line.charAt(0) === "!") {
debug(
">>> When processing .gitignore/.eleventyignore, Eleventy does not currently support negative patterns but encountered one:",
);
debug(">>>", line);
debug("Follow along at https://github.com/11ty/eleventy/issues/693 to track support.");
}
// empty lines or comments get filtered out
return line.length > 0 && line.charAt(0) !== "#" && line.charAt(0) !== "!";
})
.map((line) => {
let path = TemplateGlob.normalizePath(dir, "/", line);
path = TemplatePath.addLeadingDotSlash(TemplatePath.relativePath(path));
try {
// Note these folders must exist to get /** suffix
let stat = fs.statSync(path);
if (stat.isDirectory()) {
return path + "/**";
}
return path;
} catch (e) {
return path;
}
});
}
return ignores;
}
setEleventyIgnoreContent(content) {
this.eleventyIgnoreContent = content;
}
getIgnores() {
let files = new Set();
for (let ignore of EleventyFiles.getFileIgnores(this.getIgnoreFiles())) {
files.add(ignore);
}
// testing API
if (this.eleventyIgnoreContent !== false) {
files.add(this.eleventyIgnoreContent);
}
// ignore output dir (unless this excludes all input)
// input: . and output: . (skip)
// input: ./content and output . (skip)
// input: . and output: ./_site (add)
if (!this.inputDir.startsWith(this.outputDir)) {
// both are already normalized in 3.0
files.add(TemplateGlob.map(this.outputDir + "/**"));
}
return Array.from(files);
}
getIgnoreFiles() {
let ignoreFiles = new Set();
let rootDirectory = this.localPathRoot || ".";
if (this.config.useGitIgnore) {
ignoreFiles.add(TemplatePath.join(rootDirectory, ".gitignore"));
}
if (this.eleventyIgnoreContent === false) {
let absoluteInputDir = TemplatePath.absolutePath(this.inputDir);
ignoreFiles.add(TemplatePath.join(rootDirectory, ".eleventyignore"));
if (rootDirectory !== absoluteInputDir) {
ignoreFiles.add(TemplatePath.join(this.inputDir, ".eleventyignore"));
}
}
return Array.from(ignoreFiles);
}
/* Backwards compat */
getIncludesDir() {
return this.includesDir;
}
/* Backwards compat */
getLayoutsDir() {
return this.layoutsDir;
}
getFileGlobs() {
return this.normalizedTemplateGlobs;
}
getRawFiles() {
return this.templateGlobs;
}
async getWatchPathCache() {
// Issue #1325: make sure passthrough copy files are not included here
if (!this.pathCache) {
throw new Error("Watching requires `.getFiles()` to be called first in EleventyFiles");
}
let ret = [];
// Filter out the passthrough copy paths.
for (let path of this.pathCache) {
if (
this.extensionMap.isFullTemplateFilePath(path) &&
(await this.extensionMap.shouldSpiderJavaScriptDependencies(path))
) {
ret.push(path);
}
}
return ret;
}
_globSearch() {
let globs = this.getFileGlobs();
// returns a promise
debug("Searching for: %o", globs);
return this.fileSystemSearch.search("templates", globs, {
ignore: this.uniqueIgnores,
});
}
getPathsWithVirtualTemplates(paths) {
// Support for virtual templates added in 3.0
if (this.config.virtualTemplates && isPlainObject(this.config.virtualTemplates)) {
let virtualTemplates = Object.keys(this.config.virtualTemplates)
.filter((path) => {
// Filter out includes/layouts
return this.dirs.isTemplateFile(path);
})
.map((path) => {
let fullVirtualPath = this.dirs.getInputPath(path);
if (!this.extensionMap.getKey(fullVirtualPath)) {
this.eleventyConfig.logger.warn(
`The virtual template at ${fullVirtualPath} is using a template format thats not valid for your project. Your project is using: "${this.formats}". Read more about formats: https://v3.11ty.dev/docs/config/#template-formats`,
);
}
return fullVirtualPath;
});
paths = paths.concat(virtualTemplates);
// Virtual templates can not live at the same place as files on the file system!
if (paths.length !== new Set(paths).size) {
let conflicts = {};
for (let path of paths) {
if (conflicts[path]) {
throw new Error(
`A virtual template had the same path as a file on the file system: "${path}"`,
);
}
conflicts[path] = true;
}
}
}
return paths;
}
async getFiles() {
let bench = this.aggregateBench.get("Searching the file system (templates)");
bench.before();
let globResults = await this._globSearch();
let paths = TemplatePath.addLeadingDotSlashArray(globResults);
bench.after();
// Note 2.0.0-canary.19 removed a `filter` option for custom template syntax here that was unpublished and unused.
paths = this.getPathsWithVirtualTemplates(paths);
this.pathCache = paths;
return paths;
}
getFileShape(paths, filePath) {
if (!filePath) {
return;
}
if (this.isPassthroughCopyFile(paths, filePath)) {
return "copy";
}
if (this.isFullTemplateFile(paths, filePath)) {
return "template";
}
// include/layout/unknown
}
isPassthroughCopyFile(paths, filePath) {
return this.passthroughManager.isPassthroughCopyFile(paths, filePath);
}
// Assumption here that filePath is not a passthrough copy file
isFullTemplateFile(paths, filePath) {
if (!filePath) {
return false;
}
for (let path of paths) {
if (path === filePath) {
return true;
}
}
return false;
}
/* For `eleventy --watch` */
getGlobWatcherFiles() {
// TODO improvement: tie the includes and data to specific file extensions (currently using `**`)
let directoryGlobs = this._getIncludesAndDataDirs();
if (checkPassthroughCopyBehavior(this.config, this.runMode)) {
return this.validTemplateGlobs.concat(directoryGlobs);
}
// Revert to old passthroughcopy copy files behavior
return this.validTemplateGlobs.concat(this.passthroughGlobs).concat(directoryGlobs);
}
/* For `eleventy --watch` */
getGlobWatcherFilesForPassthroughCopy() {
return this.passthroughGlobs;
}
/* For `eleventy --watch` */
async getGlobWatcherTemplateDataFiles() {
let templateData = this.templateData;
return await templateData.getTemplateDataFileGlob();
}
/* For `eleventy --watch` */
// TODO this isnt great but reduces complexity avoiding using TemplateData:getLocalDataPaths for each template in the cache
async getWatcherTemplateJavaScriptDataFiles() {
let globs = this.templateData.getTemplateJavaScriptDataFileGlob();
let bench = this.aggregateBench.get("Searching the file system (watching)");
bench.before();
let results = TemplatePath.addLeadingDotSlashArray(
await this.fileSystemSearch.search("js-dependencies", globs, {
ignore: ["**/node_modules/**"],
}),
);
bench.after();
return results;
}
/* Ignored by `eleventy --watch` */
getGlobWatcherIgnores() {
// convert to format without ! since they are passed in as a separate argument to glob watcher
let entries = new Set(
this.fileIgnores.map((ignore) => TemplatePath.stripLeadingDotSlash(ignore)),
);
for (let ignore of this.config.watchIgnores) {
entries.add(TemplateGlob.normalizePath(this.localPathRoot || ".", ignore));
}
// de-duplicated
return Array.from(entries);
}
_getIncludesAndDataDirs() {
let rawPaths = new Set();
rawPaths.add(this.includesDir);
if (this.layoutsDir) {
rawPaths.add(this.layoutsDir);
}
rawPaths.add(this.dataDir);
return Array.from(rawPaths)
.filter((entry) => {
// never ignore the input directory (even if config file returns "" for these)
return entry && entry !== this.inputDir;
})
.map((entry) => {
return TemplateGlob.map(entry + "**");
});
}
}
export default EleventyFiles;

305
node_modules/@11ty/eleventy/src/EleventyServe.js generated vendored Normal file
View File

@@ -0,0 +1,305 @@
import assert from "node:assert";
import debugUtil from "debug";
import { Merge, DeepCopy, TemplatePath } from "@11ty/eleventy-utils";
import EleventyDevServer from "@11ty/eleventy-dev-server";
import EleventyBaseError from "./Errors/EleventyBaseError.js";
import ConsoleLogger from "./Util/ConsoleLogger.js";
import PathPrefixer from "./Util/PathPrefixer.js";
import checkPassthroughCopyBehavior from "./Util/PassthroughCopyBehaviorCheck.js";
import { getModulePackageJson } from "./Util/ImportJsonSync.js";
import { EleventyImport } from "./Util/Require.js";
import { isGlobMatch } from "./Util/GlobMatcher.js";
const debug = debugUtil("Eleventy:EleventyServe");
class EleventyServeConfigError extends EleventyBaseError {}
const DEFAULT_SERVER_OPTIONS = {
module: "@11ty/eleventy-dev-server",
port: 8080,
// pathPrefix: "/",
// setup: function() {},
// logger: { info: function() {}, error: function() {} }
};
class EleventyServe {
constructor() {
this.logger = new ConsoleLogger();
this._initOptionsFetched = false;
this._aliases = undefined;
this._watchedFiles = new Set();
}
get config() {
if (!this.eleventyConfig) {
throw new EleventyServeConfigError(
"You need to set the eleventyConfig property on EleventyServe.",
);
}
return this.eleventyConfig.getConfig();
}
set config(config) {
throw new Error("Its not allowed to set config on EleventyServe. Set eleventyConfig instead.");
}
setAliases(aliases) {
this._aliases = aliases;
if (this._server && "setAliases" in this._server) {
this._server.setAliases(aliases);
}
}
get eleventyConfig() {
if (!this._eleventyConfig) {
throw new EleventyServeConfigError(
"You need to set the eleventyConfig property on EleventyServe.",
);
}
return this._eleventyConfig;
}
set eleventyConfig(config) {
this._eleventyConfig = config;
if (checkPassthroughCopyBehavior(this._eleventyConfig.userConfig, "serve")) {
this._eleventyConfig.userConfig.events.on("eleventy.passthrough", ({ map }) => {
// for-free passthrough copy
this.setAliases(map);
});
}
}
// TODO directorynorm
setOutputDir(outputDir) {
// TODO check if this is different and if so, restart server (if already running)
// This applies if you change the output directory in your config file during watch/serve
this.outputDir = outputDir;
}
async getServerModule(name) {
try {
if (!name || name === DEFAULT_SERVER_OPTIONS.module) {
return EleventyDevServer;
}
// Look for peer dep in local project
let projectNodeModulesPath = TemplatePath.absolutePath("./node_modules/");
let serverPath = TemplatePath.absolutePath(projectNodeModulesPath, name);
// No references outside of the project node_modules are allowed
if (!serverPath.startsWith(projectNodeModulesPath)) {
throw new Error("Invalid node_modules name for Eleventy server instance, received:" + name);
}
let serverPackageJson = getModulePackageJson(serverPath);
// Normalize with `main` entry from
if (TemplatePath.isDirectorySync(serverPath)) {
if (serverPackageJson.main) {
serverPath = TemplatePath.absolutePath(
projectNodeModulesPath,
name,
serverPackageJson.main,
);
} else {
throw new Error(
`Eleventy server ${name} is missing a \`main\` entry in its package.json file. Traversed up from ${serverPath}.`,
);
}
}
let module = await EleventyImport(serverPath);
if (!("getServer" in module)) {
throw new Error(
`Eleventy server module requires a \`getServer\` static method. Could not find one on module: \`${name}\``,
);
}
if (serverPackageJson["11ty"]?.compatibility) {
try {
this.eleventyConfig.userConfig.versionCheck(serverPackageJson["11ty"].compatibility);
} catch (e) {
this.logger.warn(`Warning: \`${name}\` Plugin Compatibility: ${e.message}`);
}
}
return module;
} catch (e) {
this.logger.error(
"There was an error with your custom Eleventy server. Were using the default server instead.\n" +
e.message,
);
debug("Eleventy server error %o", e);
return EleventyDevServer;
}
}
get options() {
if (this._options) {
return this._options;
}
this._options = Object.assign(
{
pathPrefix: PathPrefixer.normalizePathPrefix(this.config.pathPrefix),
logger: this.logger,
},
DEFAULT_SERVER_OPTIONS,
this.config.serverOptions,
);
this._savedConfigOptions = DeepCopy({}, this.config.serverOptions);
if (!this._initOptionsFetched && this.getSetupCallback()) {
throw new Error(
"Init options have not yet been fetched in the setup callback. This probably means that `init()` has not yet been called.",
);
}
return this._options;
}
get server() {
if (!this._server) {
throw new Error("Missing server instance. Did you call .initServerInstance?");
}
return this._server;
}
async initServerInstance() {
if (this._server) {
return;
}
let serverModule = await this.getServerModule(this.options.module);
// Static method `getServer` was already checked in `getServerModule`
this._server = serverModule.getServer("eleventy-server", this.outputDir, this.options);
this.setAliases(this._aliases);
if (this._globsNeedWatching) {
this._server.watchFiles(this._watchedFiles);
this._globsNeedWatching = false;
}
}
getSetupCallback() {
let setupCallback = this.config.serverOptions.setup;
if (setupCallback && typeof setupCallback === "function") {
return setupCallback;
}
}
async #init() {
let setupCallback = this.getSetupCallback();
if (setupCallback) {
let opts = await setupCallback();
this._initOptionsFetched = true;
if (opts) {
Merge(this.options, opts);
}
}
}
async init() {
if (!this._initPromise) {
this._initPromise = this.#init();
}
return this._initPromise;
}
// Port comes in here from --port on the command line
async serve(port) {
this._commandLinePort = port;
await this.init();
await this.initServerInstance();
this.server.serve(port || this.options.port);
}
async close() {
if (this._server) {
await this._server.close();
this._server = undefined;
}
}
async sendError({ error }) {
if (this._server) {
await this.server.sendError({
error,
});
}
}
// Restart the server entirely
// We dont want to use a native `restart` method (e.g. restart() in Vite) so that
// we can correctly handle a `module` property change (changing the server type)
async restart() {
// Blow away cached options
delete this._options;
await this.close();
// saved --port in `serve()`
await this.serve(this._commandLinePort);
// rewatch the saved watched files (passthrough copy)
if ("watchFiles" in this.server) {
this.server.watchFiles(this._watchedFiles);
}
}
// checkPassthroughCopyBehavior check is called upstream in Eleventy.js
// TODO globs are not removed from watcher
watchPassthroughCopy(globs) {
this._watchedFiles = globs;
if (this._server && "watchFiles" in this.server) {
this.server.watchFiles(globs);
this._globsNeedWatching = false;
} else {
this._globsNeedWatching = true;
}
}
isEmulatedPassthroughCopyMatch(filepath) {
return isGlobMatch(filepath, this._watchedFiles);
}
hasOptionsChanged() {
try {
assert.deepStrictEqual(this.config.serverOptions, this._savedConfigOptions);
return false;
} catch (e) {
return true;
}
}
// Live reload the server
async reload(reloadEvent = {}) {
if (!this._server) {
return;
}
// Restart the server if the options have changed
if (this.hasOptionsChanged()) {
debug("Server options changed, were restarting the server");
await this.restart();
} else {
await this.server.reload(reloadEvent);
}
}
}
export default EleventyServe;

131
node_modules/@11ty/eleventy/src/EleventyWatch.js generated vendored Executable file
View File

@@ -0,0 +1,131 @@
import { TemplatePath } from "@11ty/eleventy-utils";
import PathNormalizer from "./Util/PathNormalizer.js";
/* Decides when to watch and in what mode to watch
* Incremental builds dont batch changes, they queue.
* Nonincremental builds batch.
*/
class EleventyWatch {
constructor() {
this.incremental = false;
this.isActive = false;
this.activeQueue = [];
}
isBuildRunning() {
return this.isActive;
}
setBuildRunning() {
this.isActive = true;
// pop waiting queue into the active queue
this.activeQueue = this.popNextActiveQueue();
}
setBuildFinished() {
this.isActive = false;
this.activeQueue = [];
}
getIncrementalFile() {
if (this.incremental) {
return this.activeQueue.length ? this.activeQueue[0] : false;
}
return false;
}
/* Returns the changed files currently being operated on in the current `watch` build
* Works with or without incremental (though in incremental only one file per time will be processed)
*/
getActiveQueue() {
if (!this.isActive) {
return [];
} else if (this.incremental && this.activeQueue.length === 0) {
return [];
} else if (this.incremental) {
return [this.activeQueue[0]];
}
return this.activeQueue;
}
_queueMatches(file) {
let filterCallback;
if (typeof file === "function") {
filterCallback = file;
} else {
filterCallback = (path) => path === file;
}
return this.activeQueue.filter(filterCallback);
}
hasAllQueueFiles(file) {
return (
this.activeQueue.length > 0 && this.activeQueue.length === this._queueMatches(file).length
);
}
hasQueuedFile(file) {
if (file) {
return this._queueMatches(file).length > 0;
}
return false;
}
hasQueuedFiles(files) {
for (const file of files) {
if (this.hasQueuedFile(file)) {
return true;
}
}
return false;
}
get pendingQueue() {
if (!this._queue) {
this._queue = [];
}
return this._queue;
}
set pendingQueue(value) {
this._queue = value;
}
addToPendingQueue(path) {
if (path) {
path = PathNormalizer.normalizeSeperator(TemplatePath.addLeadingDotSlash(path));
this.pendingQueue.push(path);
}
}
getPendingQueueSize() {
return this.pendingQueue.length;
}
getPendingQueue() {
return this.pendingQueue;
}
getActiveQueueSize() {
return this.activeQueue.length;
}
// returns array
popNextActiveQueue() {
if (this.incremental) {
return this.pendingQueue.length ? [this.pendingQueue.shift()] : [];
}
let ret = this.pendingQueue.slice();
this.pendingQueue = [];
return ret;
}
}
export default EleventyWatch;

164
node_modules/@11ty/eleventy/src/EleventyWatchTargets.js generated vendored Normal file
View File

@@ -0,0 +1,164 @@
import { TemplatePath } from "@11ty/eleventy-utils";
import { DepGraph } from "dependency-graph";
import JavaScriptDependencies from "./Util/JavaScriptDependencies.js";
import eventBus from "./EventBus.js";
class EleventyWatchTargets {
#templateConfig;
constructor(templateConfig) {
this.targets = new Set();
this.dependencies = new Set();
this.newTargets = new Set();
this.isEsm = false;
this.graph = new DepGraph();
this.#templateConfig = templateConfig;
}
setProjectUsingEsm(isEsmProject) {
this.isEsm = !!isEsmProject;
}
isJavaScriptDependency(path) {
return this.dependencies.has(path);
}
reset() {
this.newTargets = new Set();
}
isWatched(target) {
return this.targets.has(target);
}
addToDependencyGraph(parent, deps) {
if (!this.graph.hasNode(parent)) {
this.graph.addNode(parent);
}
for (let dep of deps) {
if (!this.graph.hasNode(dep)) {
this.graph.addNode(dep);
}
this.graph.addDependency(parent, dep);
}
}
uses(parent, dep) {
return this.getDependenciesOf(parent).includes(dep);
}
getDependenciesOf(parent) {
if (!this.graph.hasNode(parent)) {
return [];
}
return this.graph.dependenciesOf(parent);
}
getDependantsOf(child) {
if (!this.graph.hasNode(child)) {
return [];
}
return this.graph.dependantsOf(child);
}
addRaw(targets, isDependency) {
for (let target of targets) {
let path = TemplatePath.addLeadingDotSlash(target);
if (!this.isWatched(path)) {
this.newTargets.add(path);
}
this.targets.add(path);
if (isDependency) {
this.dependencies.add(path);
}
}
}
static normalize(targets) {
if (!targets) {
return [];
} else if (Array.isArray(targets)) {
return targets;
}
return [targets];
}
// add only a target
add(targets) {
this.addRaw(EleventyWatchTargets.normalize(targets));
}
static normalizeToGlobs(targets) {
return EleventyWatchTargets.normalize(targets).map((entry) =>
TemplatePath.convertToRecursiveGlobSync(entry),
);
}
addAndMakeGlob(targets) {
this.addRaw(EleventyWatchTargets.normalizeToGlobs(targets));
}
// add only a targets dependencies
async addDependencies(targets, filterCallback) {
if (this.#templateConfig && !this.#templateConfig.shouldSpiderJavaScriptDependencies()) {
return;
}
targets = EleventyWatchTargets.normalize(targets);
let deps = await JavaScriptDependencies.getDependencies(targets, this.isEsm);
if (filterCallback) {
deps = deps.filter(filterCallback);
}
for (let target of targets) {
this.addToDependencyGraph(target, deps);
}
this.addRaw(deps, true);
}
setWriter(templateWriter) {
this.writer = templateWriter;
}
clearImportCacheFor(filePathArray) {
let paths = new Set();
for (const filePath of filePathArray) {
paths.add(filePath);
// Delete from require cache so that updates to the module are re-required
let importsTheChangedFile = this.getDependantsOf(filePath);
for (let dep of importsTheChangedFile) {
paths.add(dep);
}
let isImportedInTheChangedFile = this.getDependenciesOf(filePath);
for (let dep of isImportedInTheChangedFile) {
paths.add(dep);
}
// Use GlobalDependencyMap
if (this.#templateConfig) {
for (let dep of this.#templateConfig.usesGraph.getDependantsFor(filePath)) {
paths.add(dep);
}
}
}
eventBus.emit("eleventy.importCacheReset", paths);
}
getNewTargetsSinceLastReset() {
return Array.from(this.newTargets);
}
getTargets() {
return Array.from(this.targets);
}
}
export default EleventyWatchTargets;

338
node_modules/@11ty/eleventy/src/Engines/Custom.js generated vendored Normal file
View File

@@ -0,0 +1,338 @@
import TemplateEngine from "./TemplateEngine.js";
import getJavaScriptData from "../Util/GetJavaScriptData.js";
import eventBus from "../EventBus.js";
let lastModifiedFile = undefined;
eventBus.on("eleventy.resourceModified", (path) => {
lastModifiedFile = path;
});
class CustomEngine extends TemplateEngine {
constructor(name, eleventyConfig) {
super(name, eleventyConfig);
this.entry = this.getExtensionMapEntry();
this.needsInit = "init" in this.entry && typeof this.entry.init === "function";
this._defaultEngine = undefined;
// Enable cacheability for this template
if (this.entry?.compileOptions?.cache) {
this.cacheable = this.entry.compileOptions.cache;
} else if (this.needsToReadFileContents()) {
this.cacheable = true;
}
}
getExtensionMapEntry() {
if ("extensionMap" in this.config) {
let name = this.name.toLowerCase();
// Iterates over only the user config `addExtension` entries
for (let entry of this.config.extensionMap) {
let entryKey = (entry.aliasKey || entry.key || "").toLowerCase();
if (entryKey === name) {
return entry;
}
}
}
throw Error(
`Could not find a custom extension for ${this.name}. Did you add it to your config file?`,
);
}
setDefaultEngine(defaultEngine) {
this._defaultEngine = defaultEngine;
}
async getInstanceFromInputPath(inputPath) {
if (
"getInstanceFromInputPath" in this.entry &&
typeof this.entry.getInstanceFromInputPath === "function"
) {
// returns Promise
return this.entry.getInstanceFromInputPath(inputPath);
}
// aliased upstream type
if (
this._defaultEngine &&
"getInstanceFromInputPath" in this._defaultEngine &&
typeof this._defaultEngine.getInstanceFromInputPath === "function"
) {
// returns Promise
return this._defaultEngine.getInstanceFromInputPath(inputPath);
}
return false;
}
/**
* Whether to use the module loader directly
*
* @override
*/
useJavaScriptImport() {
if ("useJavaScriptImport" in this.entry) {
return this.entry.useJavaScriptImport;
}
if (
this._defaultEngine &&
"useJavaScriptImport" in this._defaultEngine &&
typeof this._defaultEngine.useJavaScriptImport === "function"
) {
return this._defaultEngine.useJavaScriptImport();
}
return false;
}
/**
* @override
*/
needsToReadFileContents() {
if ("read" in this.entry) {
return this.entry.read;
}
// Handle aliases to `11ty.js` templates, avoid reading files in the alias, see #2279
// Here, we are short circuiting fallback to defaultRenderer, does not account for compile
// functions that call defaultRenderer explicitly
if (this._defaultEngine && "needsToReadFileContents" in this._defaultEngine) {
return this._defaultEngine.needsToReadFileContents();
}
return true;
}
// If we init from multiple places, wait for the first init to finish before continuing on.
async _runningInit() {
if (this.needsInit) {
if (!this._initing) {
this._initBench = this.benchmarks.aggregate.get(`Engine (${this.name}) Init`);
this._initBench.before();
this._initing = this.entry.init.bind({
config: this.config,
bench: this.benchmarks.aggregate,
})();
}
await this._initing;
this.needsInit = false;
if (this._initBench) {
this._initBench.after();
this._initBench = undefined;
}
}
}
async getExtraDataFromFile(inputPath) {
if (this.entry.getData === false) {
return;
}
if (!("getData" in this.entry)) {
// Handle aliases to `11ty.js` templates, use upstream default engine data fetch, see #2279
if (this._defaultEngine && "getExtraDataFromFile" in this._defaultEngine) {
return this._defaultEngine.getExtraDataFromFile(inputPath);
}
return;
}
await this._runningInit();
if (typeof this.entry.getData === "function") {
let dataBench = this.benchmarks.aggregate.get(
`Engine (${this.name}) Get Data From File (Function)`,
);
dataBench.before();
let data = this.entry.getData(inputPath);
dataBench.after();
return data;
}
let keys = new Set();
if (this.entry.getData === true) {
keys.add("data");
} else if (Array.isArray(this.entry.getData)) {
for (let key of this.entry.getData) {
keys.add(key);
}
}
let dataBench = this.benchmarks.aggregate.get(`Engine (${this.name}) Get Data From File`);
dataBench.before();
let inst = await this.getInstanceFromInputPath(inputPath);
if (inst === false) {
dataBench.after();
return Promise.reject(
new Error(
`\`getInstanceFromInputPath\` callback missing from '${this.name}' template engine plugin. It is required when \`getData\` is in use. You can set \`getData: false\` to opt-out of this.`,
),
);
}
// override keys set at the plugin level in the individual template
if (inst.eleventyDataKey) {
keys = new Set(inst.eleventyDataKey);
}
let mixins;
if (this.config) {
// Object.assign usage: see TemplateRenderCustomTest.js: `JavaScript functions should not be mutable but not *that* mutable`
mixins = Object.assign({}, this.config.javascriptFunctions);
}
let promises = [];
for (let key of keys) {
promises.push(
getJavaScriptData(inst, inputPath, key, {
mixins,
isObjectRequired: key === "data",
}),
);
}
let results = await Promise.all(promises);
let data = {};
for (let result of results) {
Object.assign(data, result);
}
dataBench.after();
return data;
}
async compile(str, inputPath, ...args) {
await this._runningInit();
let defaultCompilationFn;
if (this._defaultEngine) {
defaultCompilationFn = async (data) => {
const renderFn = await this._defaultEngine.compile(str, inputPath, ...args);
return renderFn(data);
};
}
// Fall back to default compiler if the user does not provide their own
if (!this.entry.compile) {
if (defaultCompilationFn) {
return defaultCompilationFn;
} else {
throw new Error(
`Missing \`compile\` property for custom template syntax definition eleventyConfig.addExtension("${this.name}"). This is not necessary when aliasing to an existing template syntax.`,
);
}
}
// TODO generalize this (look at JavaScript.js)
let fn = this.entry.compile.bind({
config: this.config,
addDependencies: (from, toArray = []) => {
this.config.uses.addDependency(from, toArray);
},
defaultRenderer: defaultCompilationFn, // bind defaultRenderer to compile function
})(str, inputPath);
// Support `undefined` to skip compile/render
if (fn) {
// Bind defaultRenderer to render function
if ("then" in fn && typeof fn.then === "function") {
// Promise, wait to bind
return fn.then((fn) => {
if (typeof fn === "function") {
return fn.bind({
defaultRenderer: defaultCompilationFn,
});
}
return fn;
});
} else if ("bind" in fn && typeof fn.bind === "function") {
return fn.bind({
defaultRenderer: defaultCompilationFn,
});
}
}
return fn;
}
get defaultTemplateFileExtension() {
return this.entry.outputFileExtension ?? "html";
}
// Whether or not to wrap in Eleventy layouts
useLayouts() {
// TODO future change fallback to `this.defaultTemplateFileExtension === "html"`
return this.entry.useLayouts ?? true;
}
hasDependencies(inputPath) {
if (this.config.uses.getDependencies(inputPath) === false) {
return false;
}
return true;
}
isFileRelevantTo(inputPath, comparisonFile, includeLayouts) {
return this.config.uses.isFileRelevantTo(inputPath, comparisonFile, includeLayouts);
}
getCompileCacheKey(str, inputPath) {
// Return this separately so we know whether or not to use the cached version
// but still return a key to cache this new render for next time
let useCache = !this.isFileRelevantTo(inputPath, lastModifiedFile, false);
if (this.entry.compileOptions && "getCacheKey" in this.entry.compileOptions) {
if (typeof this.entry.compileOptions.getCacheKey !== "function") {
throw new Error(
`\`compileOptions.getCacheKey\` must be a function in addExtension for the ${this.name} type`,
);
}
return {
useCache,
key: this.entry.compileOptions.getCacheKey(str, inputPath),
};
}
let { key } = super.getCompileCacheKey(str, inputPath);
return {
useCache,
key,
};
}
permalinkNeedsCompilation(/*str*/) {
if (this.entry.compileOptions && "permalink" in this.entry.compileOptions) {
let p = this.entry.compileOptions.permalink;
if (p === "raw") {
return false;
}
// permalink: false is aliased to permalink: () => false
if (p === false) {
return () => false;
}
return this.entry.compileOptions.permalink;
}
// Breaking: default changed from `true` to `false` in 3.0.0-alpha.13
return false;
}
static shouldSpiderJavaScriptDependencies(entry) {
if (entry.compileOptions && "spiderJavaScriptDependencies" in entry.compileOptions) {
return entry.compileOptions.spiderJavaScriptDependencies;
}
return false;
}
}
export default CustomEngine;

View File

@@ -0,0 +1,34 @@
import { RetrieveGlobals } from "node-retrieve-globals";
// `javascript` Front Matter Type
export default function (frontMatterCode, context = {}) {
let { filePath } = context;
// context.language would be nice as a guard, but was unreliable
if (frontMatterCode.trimStart().startsWith("{")) {
return context.engines.jsLegacy.parse(frontMatterCode, context);
}
let vm = new RetrieveGlobals(frontMatterCode, {
filePath,
// ignored if vm.Module is stable (or --experimental-vm-modules)
transformEsmImports: true,
});
// Future warning until vm.Module is stable:
// If the frontMatterCode uses `import` this uses the `experimentalModuleApi`
// option in node-retrieve-globals to workaround https://github.com/zachleat/node-retrieve-globals/issues/2
let data = {
page: {
// Theoretically fileSlug and filePathStem could be added here but require extensionMap
inputPath: filePath,
},
};
// this is async, but its handled in Eleventy upstream.
return vm.getGlobalContext(data, {
reuseGlobal: true,
dynamicImport: true,
// addRequire: true,
});
}

28
node_modules/@11ty/eleventy/src/Engines/Html.js generated vendored Normal file
View File

@@ -0,0 +1,28 @@
import TemplateEngine from "./TemplateEngine.js";
class Html extends TemplateEngine {
constructor(name, eleventyConfig) {
super(name, eleventyConfig);
this.cacheable = true;
}
async compile(str, inputPath, preTemplateEngine) {
if (preTemplateEngine) {
let engine = await this.engineManager.getEngine(preTemplateEngine, this.extensionMap);
let fnReady = engine.compile(str, inputPath);
return async function (data) {
let fn = await fnReady;
return fn(data);
};
}
return function () {
// do nothing with data if parseHtmlWith is falsy
return str;
};
}
}
export default Html;

237
node_modules/@11ty/eleventy/src/Engines/JavaScript.js generated vendored Normal file
View File

@@ -0,0 +1,237 @@
import { TemplatePath, isPlainObject } from "@11ty/eleventy-utils";
import TemplateEngine from "./TemplateEngine.js";
import EleventyBaseError from "../Errors/EleventyBaseError.js";
import getJavaScriptData from "../Util/GetJavaScriptData.js";
import EventBusUtil from "../Util/EventBusUtil.js";
import { EleventyImport } from "../Util/Require.js";
import { augmentFunction, augmentObject } from "./Util/ContextAugmenter.js";
class JavaScriptTemplateNotDefined extends EleventyBaseError {}
class JavaScript extends TemplateEngine {
constructor(name, templateConfig) {
super(name, templateConfig);
this.instances = {};
this.cacheable = false;
EventBusUtil.soloOn("eleventy.templateModified", (inputPath, metadata = {}) => {
let { usedByDependants, relevantLayouts } = metadata;
// Remove from cached instances when modified
let instancesToDelete = [
inputPath,
...(usedByDependants || []),
...(relevantLayouts || []),
].map((entry) => TemplatePath.addLeadingDotSlash(entry));
for (let inputPath of instancesToDelete) {
if (inputPath in this.instances) {
delete this.instances[inputPath];
}
}
});
}
normalize(result) {
if (Buffer.isBuffer(result)) {
return result.toString();
}
return result;
}
// String, Buffer, Promise
// Function, Class
// Object
// Module
_getInstance(mod) {
let noop = function () {
return "";
};
let originalModData = mod?.data;
if (typeof mod === "object" && mod.default && this.eleventyConfig.getIsProjectUsingEsm()) {
mod = mod.default;
}
if (typeof mod === "string" || mod instanceof Buffer || mod.then) {
return { render: () => mod };
} else if (typeof mod === "function") {
if (mod.prototype?.data || mod.prototype?.render) {
if (!("render" in mod.prototype)) {
mod.prototype.render = noop;
}
if (!("data" in mod.prototype) && !mod.data && originalModData) {
mod.prototype.data = originalModData;
}
return new mod();
} else {
return {
...(originalModData ? { data: originalModData } : undefined),
render: mod,
};
}
} else if ("data" in mod || "render" in mod) {
if (!mod.render) {
mod.render = noop;
}
if (!mod.data && originalModData) {
mod.data = originalModData;
}
return mod;
}
}
async #getInstanceFromInputPath(inputPath) {
let mod;
let relativeInputPath =
this.eleventyConfig.directories.getInputPathRelativeToInputDirectory(inputPath);
if (this.eleventyConfig.userConfig.isVirtualTemplate(relativeInputPath)) {
mod = this.eleventyConfig.userConfig.virtualTemplates[relativeInputPath].content;
} else {
let isEsm = this.eleventyConfig.getIsProjectUsingEsm();
mod = await EleventyImport(inputPath, isEsm ? "esm" : "cjs");
}
let inst = this._getInstance(mod);
if (inst) {
this.instances[inputPath] = inst;
} else {
throw new JavaScriptTemplateNotDefined(
`No JavaScript template returned from ${inputPath}. Did you assign module.exports (CommonJS) or export (ESM)?`,
);
}
return inst;
}
async getInstanceFromInputPath(inputPath) {
if (!this.instances[inputPath]) {
this.instances[inputPath] = this.#getInstanceFromInputPath(inputPath);
}
return this.instances[inputPath];
}
/**
* JavaScript files defer to the module loader rather than read the files to strings
*
* @override
*/
needsToReadFileContents() {
return false;
}
/**
* Use the module loader directly
*
* @override
*/
useJavaScriptImport() {
return true;
}
async getExtraDataFromFile(inputPath) {
let inst = await this.getInstanceFromInputPath(inputPath);
return getJavaScriptData(inst, inputPath);
}
getJavaScriptFunctions(inst) {
let fns = {};
let configFns = this.config.javascriptFunctions;
for (let key in configFns) {
// prefer pre-existing `page` javascriptFunction, if one exists
fns[key] = augmentFunction(configFns[key], {
source: inst,
overwrite: false,
});
}
return fns;
}
// Backwards compat
static wrapJavaScriptFunction(inst, fn) {
return augmentFunction(fn, {
source: inst,
});
}
addExportsToBundles(inst, url) {
let cfg = this.eleventyConfig.userConfig;
if (!("getBundleManagers" in cfg)) {
return;
}
let managers = cfg.getBundleManagers();
for (let name in managers) {
let mgr = managers[name];
let key = mgr.getBundleExportKey();
if (!key) {
continue;
}
if (typeof inst[key] === "string") {
// export const css = ``;
mgr.addToPage(url, inst[key]);
} else if (isPlainObject(inst[key])) {
if (typeof inst[key][name] === "string") {
// Object with bundle names:
// export const bundle = {
// css: ``
// };
mgr.addToPage(url, inst[key][name]);
} else if (isPlainObject(inst[key][name])) {
// Object with bucket names:
// export const bundle = {
// css: {
// default: ``
// }
// };
for (let bucketName in inst[key][name]) {
mgr.addToPage(url, inst[key][name][bucketName], bucketName);
}
}
}
}
}
async compile(str, inputPath) {
let inst;
if (str) {
// When str has a value, it's being used for permalinks in data
inst = this._getInstance(str);
} else {
// For normal templates, str will be falsy.
inst = await this.getInstanceFromInputPath(inputPath);
}
if (inst?.render) {
return function (data = {}) {
// TODO does this do anything meaningful for non-classes?
// `inst` should have a normalized `render` function from _getInstance
// Map exports to bundles
if (data.page?.url) {
this.addExportsToBundles(inst, data.page.url);
}
augmentObject(inst, {
source: data,
overwrite: false,
});
Object.assign(inst, this.getJavaScriptFunctions(inst));
return this.normalize(inst.render.call(inst, data));
}.bind(this);
}
}
static shouldSpiderJavaScriptDependencies() {
return true;
}
}
export default JavaScript;

326
node_modules/@11ty/eleventy/src/Engines/Liquid.js generated vendored Normal file
View File

@@ -0,0 +1,326 @@
import moo from "moo";
import { Tokenizer, TokenKind, evalToken, Liquid as LiquidJs } from "liquidjs";
import { TemplatePath } from "@11ty/eleventy-utils";
// import debugUtil from "debug";
import TemplateEngine from "./TemplateEngine.js";
import { augmentObject } from "./Util/ContextAugmenter.js";
// const debug = debugUtil("Eleventy:Liquid");
class Liquid extends TemplateEngine {
static argumentLexerOptions = {
number: /[0-9]+\.*[0-9]*/,
doubleQuoteString: /"(?:\\["\\]|[^\n"\\])*"/,
singleQuoteString: /'(?:\\['\\]|[^\n'\\])*'/,
keyword: /[a-zA-Z0-9.\-_]+/,
"ignore:whitespace": /[, \t]+/, // includes comma separator
};
constructor(name, eleventyConfig) {
super(name, eleventyConfig);
this.liquidOptions = this.config.liquidOptions || {};
this.setLibrary(this.config.libraryOverrides.liquid);
this.argLexer = moo.compile(Liquid.argumentLexerOptions);
this.cacheable = true;
}
setLibrary(override) {
// warning, the include syntax supported here does not exactly match what Jekyll uses.
this.liquidLib = override || new LiquidJs(this.getLiquidOptions());
this.setEngineLib(this.liquidLib);
this.addFilters(this.config.liquidFilters);
// TODO these all go to the same place (addTag), add warnings for overwrites
this.addCustomTags(this.config.liquidTags);
this.addAllShortcodes(this.config.liquidShortcodes);
this.addAllPairedShortcodes(this.config.liquidPairedShortcodes);
}
getLiquidOptions() {
let defaults = {
root: [this.dirs.includes, this.dirs.input], // supplemented in compile with inputPath below
extname: ".liquid",
strictFilters: true,
// TODO?
// cache: true,
};
let options = Object.assign(defaults, this.liquidOptions || {});
// debug("Liquid constructor options: %o", options);
return options;
}
static wrapFilter(name, fn) {
/**
* @this {object}
*/
return function (...args) {
// Set this.eleventy and this.page
if (typeof this.context?.get === "function") {
augmentObject(this, {
source: this.context,
getter: (key, context) => context.get([key]),
lazy: this.context.strictVariables,
});
}
// We *dont* wrap this in an EleventyFilterError because Liquid has a better error message with line/column information in the template
return fn.call(this, ...args);
};
}
// Shortcodes
static normalizeScope(context) {
let obj = {};
if (context) {
obj.ctx = context; // Full context available on `ctx`
// Set this.eleventy and this.page
augmentObject(obj, {
source: context,
getter: (key, context) => context.get([key]),
lazy: context.strictVariables,
});
}
return obj;
}
addCustomTags(tags) {
for (let name in tags) {
this.addTag(name, tags[name]);
}
}
addFilters(filters) {
for (let name in filters) {
this.addFilter(name, filters[name]);
}
}
addFilter(name, filter) {
this.liquidLib.registerFilter(name, Liquid.wrapFilter(name, filter));
}
addTag(name, tagFn) {
let tagObj;
if (typeof tagFn === "function") {
tagObj = tagFn(this.liquidLib);
} else {
throw new Error(
"Liquid.addTag expects a callback function to be passed in: addTag(name, function(liquidEngine) { return { parse: …, render: … } })",
);
}
this.liquidLib.registerTag(name, tagObj);
}
addAllShortcodes(shortcodes) {
for (let name in shortcodes) {
this.addShortcode(name, shortcodes[name]);
}
}
addAllPairedShortcodes(shortcodes) {
for (let name in shortcodes) {
this.addPairedShortcode(name, shortcodes[name]);
}
}
static parseArguments(lexer, str) {
let argArray = [];
if (!lexer) {
lexer = moo.compile(Liquid.argumentLexerOptions);
}
if (typeof str === "string") {
lexer.reset(str);
let arg = lexer.next();
while (arg) {
/*{
type: 'doubleQuoteString',
value: '"test 2"',
text: '"test 2"',
toString: [Function: tokenToString],
offset: 0,
lineBreaks: 0,
line: 1,
col: 1 }*/
if (arg.type.indexOf("ignore:") === -1) {
// Push the promise into an array instead of awaiting it here.
// This forces the promises to run in order with the correct scope value for each arg.
// Otherwise they run out of order and can lead to undefined values for arguments in layout template shortcodes.
// console.log( arg.value, scope, engine );
argArray.push(arg.value);
}
arg = lexer.next();
}
}
return argArray;
}
static parseArgumentsBuiltin(args) {
let tokenizer = new Tokenizer(args);
let parsedArgs = [];
let value = tokenizer.readValue();
while (value) {
parsedArgs.push(value);
tokenizer.skipBlank();
if (tokenizer.peek() === ",") {
tokenizer.advance();
}
value = tokenizer.readValue();
}
tokenizer.end();
return parsedArgs;
}
addShortcode(shortcodeName, shortcodeFn) {
let _t = this;
this.addTag(shortcodeName, function (liquidEngine) {
return {
parse(tagToken) {
this.name = tagToken.name;
if (_t.config.liquidParameterParsing === "builtin") {
this.orderedArgs = Liquid.parseArgumentsBuiltin(tagToken.args);
// note that Liquid does have a Hash class for name-based argument parsing but offers no easy to support both modes in one class
} else {
this.legacyArgs = tagToken.args;
}
},
render: function* (ctx) {
let argArray = [];
if (this.legacyArgs) {
let rawArgs = Liquid.parseArguments(_t.argLexer, this.legacyArgs);
for (let arg of rawArgs) {
let b = yield liquidEngine.evalValue(arg, ctx);
argArray.push(b);
}
} else if (this.orderedArgs) {
for (let arg of this.orderedArgs) {
let b = yield evalToken(arg, ctx);
argArray.push(b);
}
}
let ret = yield shortcodeFn.call(Liquid.normalizeScope(ctx), ...argArray);
return ret;
},
};
});
}
addPairedShortcode(shortcodeName, shortcodeFn) {
let _t = this;
this.addTag(shortcodeName, function (liquidEngine) {
return {
parse(tagToken, remainTokens) {
this.name = tagToken.name;
if (_t.config.liquidParameterParsing === "builtin") {
this.orderedArgs = Liquid.parseArgumentsBuiltin(tagToken.args);
// note that Liquid does have a Hash class for name-based argument parsing but offers no easy to support both modes in one class
} else {
this.legacyArgs = tagToken.args;
}
this.templates = [];
var stream = liquidEngine.parser
.parseStream(remainTokens)
.on("template", (tpl) => this.templates.push(tpl))
.on("tag:end" + shortcodeName, () => stream.stop())
.on("end", () => {
throw new Error(`tag ${tagToken.raw} not closed`);
});
stream.start();
},
render: function* (ctx /*, emitter*/) {
let argArray = [];
if (this.legacyArgs) {
let rawArgs = Liquid.parseArguments(_t.argLexer, this.legacyArgs);
for (let arg of rawArgs) {
let b = yield liquidEngine.evalValue(arg, ctx);
argArray.push(b);
}
} else if (this.orderedArgs) {
for (let arg of this.orderedArgs) {
let b = yield evalToken(arg, ctx);
argArray.push(b);
}
}
const html = yield liquidEngine.renderer.renderTemplates(this.templates, ctx);
let ret = yield shortcodeFn.call(Liquid.normalizeScope(ctx), html, ...argArray);
return ret;
},
};
});
}
parseForSymbols(str) {
let tokenizer = new Tokenizer(str);
/** @type {Array} */
let tokens = tokenizer.readTopLevelTokens();
let symbols = tokens
.filter((token) => token.kind === TokenKind.Output)
.map((token) => {
// manually remove filters 😅
return token.content.split("|").map((entry) => entry.trim())[0];
});
return symbols;
}
// Dont return a boolean if permalink is a function (see TemplateContent->renderPermalink)
/** @returns {boolean|undefined} */
permalinkNeedsCompilation(str) {
if (typeof str === "string") {
return this.needsCompilation(str);
}
}
needsCompilation(str) {
let options = this.liquidLib.options;
return (
str.indexOf(options.tagDelimiterLeft) !== -1 ||
str.indexOf(options.outputDelimiterLeft) !== -1
);
}
async compile(str, inputPath) {
let engine = this.liquidLib;
let tmplReady = engine.parse(str, inputPath);
// Required for relative includes
let options = {};
if (!inputPath || inputPath === "liquid" || inputPath === "md") {
// do nothing
} else {
options.root = [TemplatePath.getDirFromFilePath(inputPath)];
}
return async function (data) {
let tmpl = await tmplReady;
return engine.render(tmpl, data, options);
};
}
}
export default Liquid;

93
node_modules/@11ty/eleventy/src/Engines/Markdown.js generated vendored Normal file
View File

@@ -0,0 +1,93 @@
import markdownIt from "markdown-it";
import TemplateEngine from "./TemplateEngine.js";
class Markdown extends TemplateEngine {
constructor(name, eleventyConfig) {
super(name, eleventyConfig);
this.markdownOptions = {};
this.setLibrary(this.config.libraryOverrides.md);
this.cacheable = true;
}
setLibrary(mdLib) {
this.mdLib = mdLib || markdownIt(this.getMarkdownOptions());
// Overrides a highlighter set in `markdownOptions`
// This is separate so devs can pass in a new mdLib and still use the official eleventy plugin for markdown highlighting
if (this.config.markdownHighlighter && typeof this.mdLib.set === "function") {
this.mdLib.set({
highlight: this.config.markdownHighlighter,
});
}
if (typeof this.mdLib.disable === "function") {
// Disable indented code blocks by default (Issue #2438)
this.mdLib.disable("code");
}
this.setEngineLib(this.mdLib);
}
setMarkdownOptions(options) {
this.markdownOptions = options;
}
getMarkdownOptions() {
// work with "mode" presets https://github.com/markdown-it/markdown-it#init-with-presets-and-options
if (typeof this.markdownOptions === "string") {
return this.markdownOptions;
}
return Object.assign(
{
html: true,
},
this.markdownOptions || {},
);
}
async compile(str, inputPath, preTemplateEngine, bypassMarkdown) {
let mdlib = this.mdLib;
if (preTemplateEngine) {
let engine;
if (typeof preTemplateEngine === "string") {
engine = await this.engineManager.getEngine(preTemplateEngine, this.extensionMap);
} else {
engine = preTemplateEngine;
}
let fnReady = engine.compile(str, inputPath);
if (bypassMarkdown) {
return async function (data) {
let fn = await fnReady;
return fn(data);
};
} else {
return async function (data) {
let fn = await fnReady;
let preTemplateEngineRender = await fn(data);
let finishedRender = mdlib.render(preTemplateEngineRender, data);
return finishedRender;
};
}
} else {
if (bypassMarkdown) {
return function () {
return str;
};
} else {
return function (data) {
return mdlib.render(str, data);
};
}
}
}
}
export default Markdown;

447
node_modules/@11ty/eleventy/src/Engines/Nunjucks.js generated vendored Executable file
View File

@@ -0,0 +1,447 @@
import NunjucksLib from "nunjucks";
import { TemplatePath } from "@11ty/eleventy-utils";
import TemplateEngine from "./TemplateEngine.js";
import EleventyBaseError from "../Errors/EleventyBaseError.js";
import EventBusUtil from "../Util/EventBusUtil.js";
import { augmentObject } from "./Util/ContextAugmenter.js";
class EleventyNunjucksError extends EleventyBaseError {}
class Nunjucks extends TemplateEngine {
constructor(name, eleventyConfig) {
super(name, eleventyConfig);
this.nunjucksEnvironmentOptions = this.config.nunjucksEnvironmentOptions || { dev: true };
this.nunjucksPrecompiledTemplates = this.config.nunjucksPrecompiledTemplates || {};
this._usingPrecompiled = Object.keys(this.nunjucksPrecompiledTemplates).length > 0;
this.setLibrary(this.config.libraryOverrides.njk);
this.cacheable = true;
}
_setEnv(override) {
if (override) {
this.njkEnv = override;
} else if (this._usingPrecompiled) {
// Precompiled templates to avoid eval!
const NodePrecompiledLoader = function () {};
NodePrecompiledLoader.prototype.getSource = (name) => {
// https://github.com/mozilla/nunjucks/blob/fd500902d7c88672470c87170796de52fc0f791a/nunjucks/src/precompiled-loader.js#L5
return {
src: {
type: "code",
obj: this.nunjucksPrecompiledTemplates[name],
},
// Maybe add this?
// path,
// noCache: true
};
};
this.njkEnv = new NunjucksLib.Environment(
new NodePrecompiledLoader(),
this.nunjucksEnvironmentOptions,
);
} else {
let paths = new Set();
paths.add(super.getIncludesDir());
paths.add(TemplatePath.getWorkingDir());
// Filter out undefined paths
let fsLoader = new NunjucksLib.FileSystemLoader(Array.from(paths).filter(Boolean));
this.njkEnv = new NunjucksLib.Environment(fsLoader, this.nunjucksEnvironmentOptions);
}
this.config.events.emit("eleventy.engine.njk", {
nunjucks: NunjucksLib,
environment: this.njkEnv,
});
}
setLibrary(override) {
this._setEnv(override);
// Correct, but overbroad. Better would be to evict more granularly, but
// resolution from paths isn't straightforward.
EventBusUtil.soloOn("eleventy.templateModified", (/*path*/) => {
this.njkEnv.invalidateCache();
});
this.setEngineLib(this.njkEnv);
this.addFilters(this.config.nunjucksFilters);
this.addFilters(this.config.nunjucksAsyncFilters, true);
// TODO these all go to the same place (addTag), add warnings for overwrites
// TODO(zachleat): variableName should work with quotes or without quotes (same as {% set %})
this.addPairedShortcode("setAsync", function (content, variableName) {
this.ctx[variableName] = content;
return "";
});
this.addCustomTags(this.config.nunjucksTags);
this.addAllShortcodes(this.config.nunjucksShortcodes);
this.addAllShortcodes(this.config.nunjucksAsyncShortcodes, true);
this.addAllPairedShortcodes(this.config.nunjucksPairedShortcodes);
this.addAllPairedShortcodes(this.config.nunjucksAsyncPairedShortcodes, true);
this.addGlobals(this.config.nunjucksGlobals);
}
addFilters(filters, isAsync) {
for (let name in filters) {
this.njkEnv.addFilter(name, Nunjucks.wrapFilter(name, filters[name]), isAsync);
}
}
static wrapFilter(name, fn) {
return function (...args) {
try {
augmentObject(this, {
source: this.ctx,
lazy: false, // context.env?.opts.throwOnUndefined,
});
return fn.call(this, ...args);
} catch (e) {
throw new EleventyNunjucksError(
`Error in Nunjucks Filter \`${name}\`${this.page ? ` (${this.page.inputPath})` : ""}`,
e,
);
}
};
}
// Shortcodes
static normalizeContext(context) {
let obj = {};
if (context.ctx) {
obj.ctx = context.ctx;
obj.env = context.env;
augmentObject(obj, {
source: context.ctx,
lazy: false, // context.env?.opts.throwOnUndefined,
});
}
return obj;
}
addCustomTags(tags) {
for (let name in tags) {
this.addTag(name, tags[name]);
}
}
addTag(name, tagFn) {
let tagObj;
if (typeof tagFn === "function") {
tagObj = tagFn(NunjucksLib, this.njkEnv);
} else {
throw new Error(
"Nunjucks.addTag expects a callback function to be passed in: addTag(name, function(nunjucksEngine) {})",
);
}
this.njkEnv.addExtension(name, tagObj);
}
addGlobals(globals) {
for (let name in globals) {
this.addGlobal(name, globals[name]);
}
}
addGlobal(name, globalFn) {
this.njkEnv.addGlobal(name, globalFn);
}
addAllShortcodes(shortcodes, isAsync = false) {
for (let name in shortcodes) {
this.addShortcode(name, shortcodes[name], isAsync);
}
}
addAllPairedShortcodes(shortcodes, isAsync = false) {
for (let name in shortcodes) {
this.addPairedShortcode(name, shortcodes[name], isAsync);
}
}
_getShortcodeFn(shortcodeName, shortcodeFn, isAsync = false) {
return function ShortcodeFunction() {
this.tags = [shortcodeName];
this.parse = function (parser, nodes) {
let args;
let tok = parser.nextToken();
args = parser.parseSignature(true, true);
// Nunjucks bug with non-paired custom tags bug still exists even
// though this issue is closed. Works fine for paired.
// https://github.com/mozilla/nunjucks/issues/158
if (args.children.length === 0) {
args.addChild(new nodes.Literal(0, 0, ""));
}
parser.advanceAfterBlockEnd(tok.value);
if (isAsync) {
return new nodes.CallExtensionAsync(this, "run", args);
}
return new nodes.CallExtension(this, "run", args);
};
this.run = function (...args) {
let resolve;
if (isAsync) {
resolve = args.pop();
}
let [context, ...argArray] = args;
if (isAsync) {
let ret = shortcodeFn.call(Nunjucks.normalizeContext(context), ...argArray);
// #3286 error messaging when the shortcode is not a promise
if (!ret?.then) {
resolve(
new EleventyNunjucksError(
`Error with Nunjucks shortcode \`${shortcodeName}\`: it was defined as asynchronous but was actually synchronous. This is important for Nunjucks.`,
),
);
}
ret.then(
function (returnValue) {
resolve(null, new NunjucksLib.runtime.SafeString("" + returnValue));
},
function (e) {
resolve(
new EleventyNunjucksError(`Error with Nunjucks shortcode \`${shortcodeName}\``, e),
);
},
);
} else {
try {
let ret = shortcodeFn.call(Nunjucks.normalizeContext(context), ...argArray);
return new NunjucksLib.runtime.SafeString("" + ret);
} catch (e) {
throw new EleventyNunjucksError(
`Error with Nunjucks shortcode \`${shortcodeName}\``,
e,
);
}
}
};
};
}
_getPairedShortcodeFn(shortcodeName, shortcodeFn, isAsync = false) {
return function PairedShortcodeFunction() {
this.tags = [shortcodeName];
this.parse = function (parser, nodes) {
var tok = parser.nextToken();
var args = parser.parseSignature(true, true);
parser.advanceAfterBlockEnd(tok.value);
var body = parser.parseUntilBlocks("end" + shortcodeName);
parser.advanceAfterBlockEnd();
return new nodes.CallExtensionAsync(this, "run", args, [body]);
};
this.run = function (...args) {
let resolve = args.pop();
let body = args.pop();
let [context, ...argArray] = args;
body(function (e, bodyContent) {
if (e) {
resolve(
new EleventyNunjucksError(
`Error with Nunjucks paired shortcode \`${shortcodeName}\``,
e,
),
);
}
if (isAsync) {
let ret = shortcodeFn.call(
Nunjucks.normalizeContext(context),
bodyContent,
...argArray,
);
// #3286 error messaging when the shortcode is not a promise
if (!ret?.then) {
throw new EleventyNunjucksError(
`Error with Nunjucks shortcode \`${shortcodeName}\`: it was defined as asynchronous but was actually synchronous. This is important for Nunjucks.`,
);
}
ret.then(
function (returnValue) {
resolve(null, new NunjucksLib.runtime.SafeString(returnValue));
},
function (e) {
resolve(
new EleventyNunjucksError(
`Error with Nunjucks paired shortcode \`${shortcodeName}\``,
e,
),
);
},
);
} else {
try {
resolve(
null,
new NunjucksLib.runtime.SafeString(
shortcodeFn.call(Nunjucks.normalizeContext(context), bodyContent, ...argArray),
),
);
} catch (e) {
resolve(
new EleventyNunjucksError(
`Error with Nunjucks paired shortcode \`${shortcodeName}\``,
e,
),
);
}
}
});
};
};
}
addShortcode(shortcodeName, shortcodeFn, isAsync = false) {
let fn = this._getShortcodeFn(shortcodeName, shortcodeFn, isAsync);
this.njkEnv.addExtension(shortcodeName, new fn());
}
addPairedShortcode(shortcodeName, shortcodeFn, isAsync = false) {
let fn = this._getPairedShortcodeFn(shortcodeName, shortcodeFn, isAsync);
this.njkEnv.addExtension(shortcodeName, new fn());
}
// Dont return a boolean if permalink is a function (see TemplateContent->renderPermalink)
permalinkNeedsCompilation(str) {
if (typeof str === "string") {
return this.needsCompilation(str);
}
}
needsCompilation(str) {
// Defend against syntax customisations:
// https://mozilla.github.io/nunjucks/api.html#customizing-syntax
let optsTags = this.njkEnv.opts.tags || {};
let blockStart = optsTags.blockStart || "{%";
let variableStart = optsTags.variableStart || "{{";
let commentStart = optsTags.variableStart || "{#";
return (
str.indexOf(blockStart) !== -1 ||
str.indexOf(variableStart) !== -1 ||
str.indexOf(commentStart) !== -1
);
}
_getParseExtensions() {
if (this._parseExtensions) {
return this._parseExtensions;
}
// add extensions so the parser knows about our custom tags/blocks
let ext = [];
for (let name in this.config.nunjucksTags) {
let fn = this._getShortcodeFn(name, () => {});
ext.push(new fn());
}
for (let name in this.config.nunjucksShortcodes) {
let fn = this._getShortcodeFn(name, () => {});
ext.push(new fn());
}
for (let name in this.config.nunjucksAsyncShortcodes) {
let fn = this._getShortcodeFn(name, () => {}, true);
ext.push(new fn());
}
for (let name in this.config.nunjucksPairedShortcodes) {
let fn = this._getPairedShortcodeFn(name, () => {});
ext.push(new fn());
}
for (let name in this.config.nunjucksAsyncPairedShortcodes) {
let fn = this._getPairedShortcodeFn(name, () => {}, true);
ext.push(new fn());
}
this._parseExtensions = ext;
return ext;
}
/* Outputs an Array of lodash get selectors */
parseForSymbols(str) {
const { parser, nodes } = NunjucksLib;
let obj = parser.parse(str, this._getParseExtensions());
let linesplit = str.split("\n");
let values = obj.findAll(nodes.Value);
let symbols = obj.findAll(nodes.Symbol).map((entry) => {
let name = [entry.value];
let nestedIndex = -1;
for (let val of values) {
if (nestedIndex > -1) {
/* deep.object.syntax */
if (linesplit[val.lineno].charAt(nestedIndex) === ".") {
name.push(val.value);
nestedIndex += val.value.length + 1;
} else {
nestedIndex = -1;
}
} else if (
val.lineno === entry.lineno &&
val.colno === entry.colno &&
val.value === entry.value
) {
nestedIndex = entry.colno + entry.value.length;
}
}
return name.join(".");
});
let uniqueSymbols = Array.from(new Set(symbols));
return uniqueSymbols;
}
async compile(str, inputPath) {
let tmpl;
// *All* templates are precompiled to avoid runtime eval
if (this._usingPrecompiled) {
tmpl = this.njkEnv.getTemplate(str, true);
} else if (!inputPath || inputPath === "njk" || inputPath === "md") {
tmpl = new NunjucksLib.Template(str, this.njkEnv, null, false);
} else {
tmpl = new NunjucksLib.Template(str, this.njkEnv, inputPath, false);
}
return function (data) {
return new Promise(function (resolve, reject) {
tmpl.render(data, function (err, res) {
if (err) {
reject(err);
} else {
resolve(res);
}
});
});
};
}
}
export default Nunjucks;

View File

@@ -0,0 +1,184 @@
import EleventyExtensionMap from "../EleventyExtensionMap.js";
import EleventyBaseError from "../Errors/EleventyBaseError.js";
class TemplateEngineConfigError extends EleventyBaseError {}
class TemplateEngine {
constructor(name, eleventyConfig) {
this.name = name;
this.engineLib = null;
this.cacheable = false;
if (!eleventyConfig) {
throw new TemplateEngineConfigError("Missing `eleventyConfig` argument.");
}
this.eleventyConfig = eleventyConfig;
}
get dirs() {
return this.eleventyConfig.directories;
}
get inputDir() {
return this.dirs.input;
}
get includesDir() {
return this.dirs.includes;
}
get config() {
if (this.eleventyConfig.constructor.name !== "TemplateConfig") {
throw new Error("Expecting a TemplateConfig instance.");
}
return this.eleventyConfig.getConfig();
}
get benchmarks() {
if (!this._benchmarks) {
this._benchmarks = {
aggregate: this.config.benchmarkManager.get("Aggregate"),
};
}
return this._benchmarks;
}
get engineManager() {
return this._engineManager;
}
set engineManager(manager) {
this._engineManager = manager;
}
get extensionMap() {
if (!this._extensionMap) {
this._extensionMap = new EleventyExtensionMap(this.eleventyConfig);
this._extensionMap.setFormats([]);
}
return this._extensionMap;
}
set extensionMap(map) {
this._extensionMap = map;
}
get extensions() {
if (!this._extensions) {
this._extensions = this.extensionMap.getExtensionsFromKey(this.name);
}
return this._extensions;
}
get extensionEntries() {
if (!this._extensionEntries) {
this._extensionEntries = this.extensionMap.getExtensionEntriesFromKey(this.name);
}
return this._extensionEntries;
}
getName() {
return this.name;
}
// Backwards compat
getIncludesDir() {
return this.includesDir;
}
/**
* @protected
*/
setEngineLib(engineLib) {
this.engineLib = engineLib;
// Run engine amendments (via issue #2438)
for (let amendment of this.config.libraryAmendments[this.name] || []) {
// TODO itd be nice if this were async friendly
amendment(engineLib);
}
}
getEngineLib() {
return this.engineLib;
}
async _testRender(str, data) {
// @ts-ignore
let fn = await this.compile(str);
return fn(data);
}
useJavaScriptImport() {
return false;
}
// JavaScript files defer to the module loader rather than read the files to strings
needsToReadFileContents() {
return true;
}
getExtraDataFromFile() {
return {};
}
getCompileCacheKey(str, inputPath) {
// Changing to use inputPath and contents, using only file contents (`str`) caused issues when two
// different files had identical content (2.0.0-canary.16)
// Caches are now segmented based on inputPath so using inputPath here is superfluous (2.0.0-canary.19)
// But we do want a non-falsy value here even if `str` is an empty string.
return {
useCache: true,
key: inputPath + str,
};
}
get defaultTemplateFileExtension() {
return "html";
}
// Whether or not to wrap in Eleventy layouts
useLayouts() {
return true;
}
/** @returns {boolean|undefined} */
permalinkNeedsCompilation(str) {
return this.needsCompilation();
}
// whether or not compile is needed or can we return the plaintext?
needsCompilation(str) {
return true;
}
/**
* Make sure compile is implemented downstream.
* @abstract
* @return {Promise}
*/
async compile() {
throw new Error("compile() must be implemented by engine");
}
// See https://v3.11ty.dev/docs/watch-serve/#watch-javascript-dependencies
static shouldSpiderJavaScriptDependencies() {
return false;
}
hasDependencies(inputPath) {
if (this.config.uses.getDependencies(inputPath) === false) {
return false;
}
return true;
}
isFileRelevantTo(inputPath, comparisonFile) {
return this.config.uses.isFileRelevantTo(inputPath, comparisonFile);
}
}
export default TemplateEngine;

View File

@@ -0,0 +1,197 @@
import debugUtil from "debug";
import EleventyBaseError from "../Errors/EleventyBaseError.js";
import { EleventyImportFromEleventy } from "../Util/Require.js";
const debug = debugUtil("Eleventy:TemplateEngineManager");
class TemplateEngineManagerConfigError extends EleventyBaseError {}
class TemplateEngineManager {
constructor(eleventyConfig) {
if (!eleventyConfig || eleventyConfig.constructor.name !== "TemplateConfig") {
throw new TemplateEngineManagerConfigError("Missing or invalid `config` argument.");
}
this.eleventyConfig = eleventyConfig;
this.engineCache = {};
this.importCache = {};
}
get config() {
return this.eleventyConfig.getConfig();
}
static isAlias(entry) {
if (entry.aliasKey) {
return true;
}
return entry.key !== entry.extension;
}
static isSimpleAlias(entry) {
if (!this.isAlias(entry)) {
return false;
}
// has keys other than key, extension, and aliasKey
return (
Object.keys(entry).some((key) => {
return key !== "key" && key !== "extension" && key !== "aliasKey";
}) === false
);
}
get keyToClassNameMap() {
if (!this._keyToClassNameMap) {
this._keyToClassNameMap = {
md: "Markdown",
html: "Html",
njk: "Nunjucks",
liquid: "Liquid",
"11ty.js": "JavaScript",
};
// Custom entries *can* overwrite default entries above
if ("extensionMap" in this.config) {
for (let entry of this.config.extensionMap) {
// either the key does not already exist or it is not a simple alias and is an override: https://v3.11ty.dev/docs/languages/custom/#overriding-an-existing-template-language
let existingTarget = this._keyToClassNameMap[entry.key];
let isAlias = TemplateEngineManager.isAlias(entry);
if (!existingTarget && isAlias) {
throw new Error(
`An attempt to alias ${entry.aliasKey} to ${entry.key} was made, but ${entry.key} is not a recognized template syntax.`,
);
}
if (isAlias) {
// only `key` and `extension`, not `compile` or other options
if (!TemplateEngineManager.isSimpleAlias(entry)) {
this._keyToClassNameMap[entry.aliasKey] = "Custom";
} else {
this._keyToClassNameMap[entry.aliasKey] = this._keyToClassNameMap[entry.key];
}
} else {
// not an alias, so `key` and `extension` are the same here.
// *can* override a built-in extension!
this._keyToClassNameMap[entry.key] = "Custom";
}
}
}
}
return this._keyToClassNameMap;
}
reset() {
this.engineCache = {};
}
getClassNameFromTemplateKey(key) {
return this.keyToClassNameMap[key];
}
hasEngine(name) {
return !!this.getClassNameFromTemplateKey(name);
}
isEngineRemovedFromCore(name) {
return ["ejs", "hbs", "mustache", "haml", "pug"].includes(name) && !this.hasEngine(name);
}
async getEngineClassByExtension(extension) {
if (this.importCache[extension]) {
return this.importCache[extension];
}
let promise;
// We include these as raw strings (and not more readable variables) so theyre parsed by a bundler.
if (extension === "md") {
promise = EleventyImportFromEleventy("./src/Engines/Markdown.js");
} else if (extension === "html") {
promise = EleventyImportFromEleventy("./src/Engines/Html.js");
} else if (extension === "njk") {
promise = EleventyImportFromEleventy("./src/Engines/Nunjucks.js");
} else if (extension === "liquid") {
promise = EleventyImportFromEleventy("./src/Engines/Liquid.js");
} else if (extension === "11ty.js") {
promise = EleventyImportFromEleventy("./src/Engines/JavaScript.js");
} else {
promise = this.getCustomEngineClass();
}
this.importCache[extension] = promise;
return promise;
}
async getCustomEngineClass() {
if (!this._CustomEngine) {
this._CustomEngine = EleventyImportFromEleventy("./src/Engines/Custom.js");
}
return this._CustomEngine;
}
async #getEngine(name, extensionMap) {
let cls = await this.getEngineClassByExtension(name);
let instance = new cls(name, this.eleventyConfig);
instance.extensionMap = extensionMap;
instance.engineManager = this;
let extensionEntry = extensionMap.getExtensionEntry(name);
// Override a built-in extension (md => md)
// If provided a "Custom" engine using addExtension, but that engine's instance is *not* custom,
// The user must be overriding a built-in engine i.e. addExtension('md', { ...overrideBehavior })
let className = this.getClassNameFromTemplateKey(name);
if (className === "Custom" && instance.constructor.name !== "CustomEngine") {
let CustomEngine = await this.getCustomEngineClass();
let overrideCustomEngine = new CustomEngine(name, this.eleventyConfig);
// Keep track of the "default" engine 11ty would normally use
// This allows the user to access the default engine in their override
overrideCustomEngine.setDefaultEngine(instance);
instance = overrideCustomEngine;
// Alias to a built-in extension (11ty.tsx => 11ty.js)
} else if (
instance.constructor.name === "CustomEngine" &&
TemplateEngineManager.isAlias(extensionEntry)
) {
// add defaultRenderer for complex aliases with their own compile functions.
let originalEngineInstance = await this.getEngine(extensionEntry.key, extensionMap);
instance.setDefaultEngine(originalEngineInstance);
}
return instance;
}
async getEngine(name, extensionMap) {
// Warning about engine deprecation
if (this.isEngineRemovedFromCore(name)) {
throw new Error(
`Per the 11ty Community Survey (2023), the "${name}" template language was moved from core to an officially supported plugin in v3.0. These plugins live here: https://github.com/11ty/eleventy-plugin-template-languages and are documented on their respective template language docs at https://v3.11ty.dev/docs/languages/ You are also empowered to implement *any* template language yourself using https://v3.11ty.dev/docs/languages/custom/`,
);
}
if (!this.hasEngine(name)) {
throw new Error(`Template Engine ${name} does not exist in getEngine()`);
}
// TODO these cached engines should be based on extensions not name, then we can remove the error in
// "Double override (not aliases) throws an error" test in TemplateRenderCustomTest.js
if (!this.engineCache[name]) {
debug("Engine cache miss %o (should only happen once per type)", name);
// Make sure cache key is based on name and not path
// Custom class is used for all plugins, cache once per plugin
this.engineCache[name] = this.#getEngine(name, extensionMap);
}
return this.engineCache[name];
}
}
export default TemplateEngineManager;

View File

@@ -0,0 +1,67 @@
const DATA_KEYS = ["page", "eleventy"];
function augmentFunction(fn, options = {}) {
let t = typeof fn;
if (t !== "function") {
throw new Error(
"Invalid type passed to `augmentFunction`. A function was expected and received: " + t,
);
}
/** @this {object} */
return function (...args) {
let context = augmentObject(this || {}, options);
return fn.call(context, ...args);
};
}
function augmentObject(targetObject, options = {}) {
options = Object.assign(
{
source: undefined, // where to copy from
overwrite: true,
lazy: false, // lazily fetch the property
// getter: function() {},
},
options,
);
for (let key of DATA_KEYS) {
// Skip if overwrite: false and prop already exists on target
if (!options.overwrite && targetObject[key]) {
continue;
}
if (options.lazy) {
let value;
if (typeof options.getter == "function") {
value = () => options.getter(key, options.source);
} else {
value = () => options.source?.[key];
}
// lazy getter important for Liquid strictVariables support
Object.defineProperty(targetObject, key, {
writable: true,
configurable: true,
enumerable: true,
value,
});
} else {
let value;
if (typeof options.getter == "function") {
value = options.getter(key, options.source);
} else {
value = options.source?.[key];
}
if (value) {
targetObject[key] = value;
}
}
}
return targetObject;
}
export { DATA_KEYS as augmentKeys, augmentFunction, augmentObject };

View File

@@ -0,0 +1,9 @@
import EleventyBaseError from "./EleventyBaseError.js";
class DuplicatePermalinkOutputError extends EleventyBaseError {
get removeDuplicateErrorStringFromOutput() {
return true;
}
}
export default DuplicatePermalinkOutputError;

View File

@@ -0,0 +1,24 @@
/**
* This class serves as basis for all Eleventy-specific errors.
* @ignore
*/
class EleventyBaseError extends Error {
/**
* @param {string} message - The error message to display.
* @param {unknown} [originalError] - The original error caught.
*/
constructor(message, originalError) {
super(message);
this.name = this.constructor.name;
if (Error.captureStackTrace) {
Error.captureStackTrace(this, this.constructor);
}
if (originalError) {
this.originalError = originalError;
}
}
}
export default EleventyBaseError;

View File

@@ -0,0 +1,151 @@
import util from "node:util";
import debugUtil from "debug";
import ConsoleLogger from "../Util/ConsoleLogger.js";
import EleventyErrorUtil from "./EleventyErrorUtil.js";
const debug = debugUtil("Eleventy:EleventyErrorHandler");
class EleventyErrorHandler {
constructor() {
this._isVerbose = true;
}
get isVerbose() {
return this._isVerbose;
}
set isVerbose(verbose) {
this._isVerbose = !!verbose;
this.logger.isVerbose = !!verbose;
}
get logger() {
if (!this._logger) {
this._logger = new ConsoleLogger();
this._logger.isVerbose = this.isVerbose;
}
return this._logger;
}
set logger(logger) {
this._logger = logger;
}
warn(e, msg) {
if (msg) {
this.initialMessage(msg, "warn", "yellow");
}
this.log(e, "warn");
}
fatal(e, msg) {
this.error(e, msg);
process.exitCode = 1;
}
once(type, e, msg) {
if (e.__errorAlreadyLogged) {
return;
}
this[type || "error"](e, msg);
Object.defineProperty(e, "__errorAlreadyLogged", {
value: true,
});
}
error(e, msg) {
if (msg) {
this.initialMessage(msg, "error", "red", true);
}
this.log(e, "error", undefined, true);
}
static getTotalErrorCount(e) {
let totalErrorCount = 0;
let errorCountRef = e;
while (errorCountRef) {
totalErrorCount++;
errorCountRef = errorCountRef.originalError;
}
return totalErrorCount;
}
//https://nodejs.org/api/process.html
log(e, type = "log", chalkColor = "", forceToConsole = false) {
if (process.env.DEBUG) {
debug("Full error object: %o", util.inspect(e, { showHidden: false, depth: null }));
}
let showStack = true;
if (e.skipOriginalStack) {
showStack = false;
}
let totalErrorCount = EleventyErrorHandler.getTotalErrorCount(e);
let ref = e;
let index = 1;
while (ref) {
let nextRef = ref.originalError;
// Nunjucks wraps errors and puts the original in error.cause
if (nextRef?.cause?.originalError) {
nextRef = nextRef.cause.originalError;
}
if (!nextRef && EleventyErrorUtil.hasEmbeddedError(ref.message)) {
nextRef = EleventyErrorUtil.deconvertErrorToObject(ref);
}
if (nextRef?.skipOriginalStack) {
showStack = false;
}
this.logger.message(
`${totalErrorCount > 1 ? `${index}. ` : ""}${(
EleventyErrorUtil.cleanMessage(ref.message) || "(No error message provided)"
).trim()}${ref.name !== "Error" ? ` (via ${ref.name})` : ""}`,
type,
chalkColor,
forceToConsole,
);
if (process.env.DEBUG) {
debug(`(${type} stack): ${ref.stack}`);
} else if (!nextRef) {
// last error in the loop
// remove duplicate error messages if the stack contains the original message output above
let stackStr = ref.stack || "";
if (e.removeDuplicateErrorStringFromOutput) {
stackStr = stackStr.replace(
`${ref.name}: ${ref.message}`,
"(Repeated output has been truncated…)",
);
}
if (showStack) {
this.logger.message(
"\nOriginal error stack trace: " + stackStr,
type,
chalkColor,
forceToConsole,
);
}
}
ref = nextRef;
index++;
}
}
initialMessage(message, type = "log", chalkColor = "blue", forceToConsole = false) {
if (message) {
this.logger.message(message + ":", type, chalkColor, forceToConsole);
}
}
}
export { EleventyErrorHandler };

View File

@@ -0,0 +1,72 @@
import TemplateContentPrematureUseError from "./TemplateContentPrematureUseError.js";
/* Hack to workaround the variety of error handling schemes in template languages */
class EleventyErrorUtil {
static get prefix() {
return ">>>>>11ty>>>>>";
}
static get suffix() {
return "<<<<<11ty<<<<<";
}
static hasEmbeddedError(msg) {
if (!msg) {
return false;
}
return msg.includes(EleventyErrorUtil.prefix) && msg.includes(EleventyErrorUtil.suffix);
}
static cleanMessage(msg) {
if (!msg) {
return "";
}
if (!EleventyErrorUtil.hasEmbeddedError(msg)) {
return "" + msg;
}
return msg.slice(0, Math.max(0, msg.indexOf(EleventyErrorUtil.prefix)));
}
static deconvertErrorToObject(error) {
if (!error || !error.message) {
throw new Error(`Could not convert error object from: ${error}`);
}
if (!EleventyErrorUtil.hasEmbeddedError(error.message)) {
return error;
}
let msg = error.message;
let objectString = msg.substring(
msg.indexOf(EleventyErrorUtil.prefix) + EleventyErrorUtil.prefix.length,
msg.lastIndexOf(EleventyErrorUtil.suffix),
);
let obj = JSON.parse(objectString);
obj.name = error.name;
return obj;
}
// pass an error through a random template engines error handling unscathed
static convertErrorToString(error) {
return (
EleventyErrorUtil.prefix +
JSON.stringify({ message: error.message, stack: error.stack }) +
EleventyErrorUtil.suffix
);
}
static isPrematureTemplateContentError(e) {
// TODO the rest of the template engines
return (
e instanceof TemplateContentPrematureUseError ||
(e.originalError &&
(e.originalError.name === "RenderError" ||
e.originalError.name === "UndefinedVariableError") &&
e.originalError.originalError instanceof TemplateContentPrematureUseError) || // Liquid
(e.message || "").indexOf("TemplateContentPrematureUseError") > -1
); // Nunjucks
}
}
export default EleventyErrorUtil;

View File

@@ -0,0 +1,5 @@
import EleventyBaseError from "./EleventyBaseError.js";
class TemplateContentPrematureUseError extends EleventyBaseError {}
export default TemplateContentPrematureUseError;

View File

@@ -0,0 +1,5 @@
import EleventyBaseError from "./EleventyBaseError.js";
class TemplateContentUnrenderedTemplateError extends EleventyBaseError {}
export default TemplateContentUnrenderedTemplateError;

View File

@@ -0,0 +1,5 @@
import EleventyBaseError from "./EleventyBaseError.js";
class UsingCircularTemplateContentReferenceError extends EleventyBaseError {}
export default UsingCircularTemplateContentReferenceError;

23
node_modules/@11ty/eleventy/src/EventBus.js generated vendored Normal file
View File

@@ -0,0 +1,23 @@
import debugUtil from "debug";
import EventEmitter from "./Util/AsyncEventEmitter.js";
const debug = debugUtil("Eleventy:EventBus");
/**
* @module 11ty/eleventy/EventBus
* @ignore
*/
debug("Setting up global EventBus.");
/**
* Provides a global event bus that modules deep down in the stack can
* subscribe to from a global singleton for decoupled pub/sub.
* @type {module:11ty/eleventy/Util/AsyncEventEmitter~AsyncEventEmitter}
*/
let bus = new EventEmitter();
bus.setMaxListeners(100);
debug("EventBus max listener count: %o", bus.getMaxListeners());
export default bus;

102
node_modules/@11ty/eleventy/src/FileSystemSearch.js generated vendored Normal file
View File

@@ -0,0 +1,102 @@
import fastglob from "fast-glob";
import { TemplatePath } from "@11ty/eleventy-utils";
import debugUtil from "debug";
import { isGlobMatch } from "./Util/GlobMatcher.js";
const debug = debugUtil("Eleventy:FastGlobManager");
class FileSystemSearch {
constructor() {
this.inputs = {};
this.outputs = {};
this.promises = {};
this.count = 0;
}
getCacheKey(key, globs, options) {
if (Array.isArray(globs)) {
globs = globs.sort();
}
return key + JSON.stringify(globs) + JSON.stringify(options);
}
// returns a promise
search(key, globs, options = {}) {
debug("Glob search (%o) searching for: %o", key, globs);
if (!Array.isArray(globs)) {
globs = [globs];
}
// Strip leading slashes from everything!
globs = globs.map((entry) => TemplatePath.stripLeadingDotSlash(entry));
if (options.ignore && Array.isArray(options.ignore)) {
options.ignore = options.ignore.map((entry) => TemplatePath.stripLeadingDotSlash(entry));
debug("Glob search (%o) ignoring: %o", key, options.ignore);
}
let cacheKey = this.getCacheKey(key, globs, options);
// Only after the promise has resolved
if (this.outputs[cacheKey]) {
return Array.from(this.outputs[cacheKey]);
}
if (!this.promises[cacheKey]) {
this.inputs[cacheKey] = {
input: globs,
options,
};
this.count++;
this.promises[cacheKey] = fastglob(
globs,
Object.assign(
{
caseSensitiveMatch: false, // insensitive
dot: true,
},
options,
),
).then((results) => {
this.outputs[cacheKey] = new Set(
results.map((entry) => TemplatePath.addLeadingDotSlash(entry)),
);
return Array.from(this.outputs[cacheKey]);
});
}
// may be an unresolved promise
return this.promises[cacheKey];
}
_modify(path, setOperation) {
path = TemplatePath.stripLeadingDotSlash(path);
let normalized = TemplatePath.addLeadingDotSlash(path);
for (let key in this.inputs) {
let { input, options } = this.inputs[key];
if (
isGlobMatch(path, input, {
ignore: options.ignore,
})
) {
this.outputs[key][setOperation](normalized);
}
}
}
add(path) {
this._modify(path, "add");
}
delete(path) {
this._modify(path, "delete");
}
}
export default FileSystemSearch;

View File

@@ -0,0 +1,20 @@
export default function getCollectionItem(collection, page, modifier = 0) {
let j = 0;
let index;
for (let item of collection) {
if (
item.inputPath === page.inputPath &&
(item.outputPath === page.outputPath || item.url === page.url)
) {
index = j;
break;
}
j++;
}
if (index !== undefined && collection?.length) {
if (index + modifier >= 0 && index + modifier < collection.length) {
return collection[index + modifier];
}
}
}

View File

@@ -0,0 +1,17 @@
// TODO locale-friendly, see GetLocaleCollectionItem.js)
export default function getCollectionItemIndex(collection, page) {
if (!page) {
page = this.page;
}
let j = 0;
for (let item of collection) {
if (
item.inputPath === page.inputPath &&
(item.outputPath === page.outputPath || item.url === page.url)
) {
return j;
}
j++;
}
}

View File

@@ -0,0 +1,47 @@
import getCollectionItem from "./GetCollectionItem.js";
// Work with I18n Plugin src/Plugins/I18nPlugin.js to retrieve root pages (not i18n pages)
function resolveRootPage(config, pageOverride, languageCode) {
let localeFilter = config.getFilter("locale_page");
if (!localeFilter || typeof localeFilter !== "function") {
return pageOverride;
}
// returns root/default-language `page` object
return localeFilter.call(this, pageOverride, languageCode);
}
function getLocaleCollectionItem(config, collection, pageOverride, langCode, indexModifier = 0) {
if (!langCode) {
// if page.lang exists (2.0.0-canary.14 and i18n plugin added, use page language)
if (this.page.lang) {
langCode = this.page.lang;
} else {
return getCollectionItem(collection, pageOverride || this.page, indexModifier);
}
}
let rootPage = resolveRootPage.call(this, config, pageOverride); // implied current page, default language
let modifiedRootItem = getCollectionItem(collection, rootPage, indexModifier);
if (!modifiedRootItem) {
return; // no root item exists for the previous/next page
}
// Resolve modified root `page` back to locale `page`
// This will return a non localized version of the page as a fallback
let modifiedLocalePage = resolveRootPage.call(this, config, modifiedRootItem.data.page, langCode);
// already localized (or default language)
if (!("__locale_page_resolved" in modifiedLocalePage)) {
return modifiedRootItem;
}
// find the modified locale `page` again in `collections.all`
let all =
this.collections?.all ||
this.ctx?.collections?.all ||
this.context?.environments?.collections?.all ||
[];
return getCollectionItem(all, modifiedLocalePage, 0);
}
export default getLocaleCollectionItem;

14
node_modules/@11ty/eleventy/src/Filters/Slug.js generated vendored Normal file
View File

@@ -0,0 +1,14 @@
import slugify from "slugify";
export default function (str, options = {}) {
return slugify(
"" + str,
Object.assign(
{
replacement: "-",
lower: true,
},
options,
),
);
}

14
node_modules/@11ty/eleventy/src/Filters/Slugify.js generated vendored Normal file
View File

@@ -0,0 +1,14 @@
import slugify from "@sindresorhus/slugify";
export default function (str, options = {}) {
return slugify(
"" + str,
Object.assign(
{
// lowercase: true, // default
decamelize: false,
},
options,
),
);
}

35
node_modules/@11ty/eleventy/src/Filters/Url.js generated vendored Normal file
View File

@@ -0,0 +1,35 @@
import { TemplatePath } from "@11ty/eleventy-utils";
import isValidUrl from "../Util/ValidUrl.js";
// Note: This filter is used in the Eleventy Navigation plugin in versions prior to 0.3.4
export default function (url, pathPrefix) {
// work with undefined
url = url || "";
if (isValidUrl(url) || (url.startsWith("//") && url !== "//")) {
return url;
}
if (pathPrefix === undefined || typeof pathPrefix !== "string") {
// When you retrieve this with config.getFilter("url") it
// grabs the pathPrefix argument from your config for you (see defaultConfig.js)
throw new Error("pathPrefix (String) is required in the `url` filter.");
}
let normUrl = TemplatePath.normalizeUrlPath(url);
let normRootDir = TemplatePath.normalizeUrlPath("/", pathPrefix);
let normFull = TemplatePath.normalizeUrlPath("/", pathPrefix, url);
let isRootDirTrailingSlash =
normRootDir.length && normRootDir.charAt(normRootDir.length - 1) === "/";
// minor difference with straight `normalize`, "" resolves to root dir and not "."
// minor difference with straight `normalize`, "/" resolves to root dir
if (normUrl === "/" || normUrl === normRootDir) {
return normRootDir + (!isRootDirTrailingSlash ? "/" : "");
} else if (normUrl.indexOf("/") === 0) {
return normFull;
}
return normUrl;
}

424
node_modules/@11ty/eleventy/src/GlobalDependencyMap.js generated vendored Normal file
View File

@@ -0,0 +1,424 @@
import { DepGraph } from "dependency-graph";
import debugUtil from "debug";
import { TemplatePath } from "@11ty/eleventy-utils";
import JavaScriptDependencies from "./Util/JavaScriptDependencies.js";
import PathNormalizer from "./Util/PathNormalizer.js";
const debug = debugUtil("Eleventy:Dependencies");
class GlobalDependencyMap {
// dependency-graph requires these keys to be alphabetic strings
static LAYOUT_KEY = "layout";
static COLLECTION_PREFIX = "__collection:";
#templateConfig;
reset() {
this._map = undefined;
}
setIsEsm(isEsm) {
this.isEsm = isEsm;
}
setTemplateConfig(templateConfig) {
this.#templateConfig = templateConfig;
}
setConfig(config) {
if (this.config) {
return;
}
this.config = config;
// These have leading dot slashes, but so do the paths from Eleventy
this.config.events.once("eleventy.layouts", async (layouts) => {
await this.addLayoutsToMap(layouts);
});
}
filterOutLayouts(nodes = []) {
return nodes.filter((node) => {
let data = this.map.getNodeData(node);
if (data?.type === GlobalDependencyMap.LAYOUT_KEY) {
return false;
}
return true;
});
}
filterOutCollections(nodes = []) {
return nodes.filter((node) => !node.startsWith(GlobalDependencyMap.COLLECTION_PREFIX));
}
removeLayoutNodes(normalizedLayouts) {
let nodes = this.map.overallOrder();
for (let node of nodes) {
let data = this.map.getNodeData(node);
if (!data || !data.type || data.type !== GlobalDependencyMap.LAYOUT_KEY) {
continue;
}
// previous layout is not in the new layout map (no templates are using it)
if (!normalizedLayouts[node]) {
this.map.removeNode(node);
}
// important: if the layout map changed to have different templates (but was not removed)
// this is already handled by `resetNode` called via TemplateMap
}
}
// Eleventy Layouts dont show up in the dependency graph, so we handle those separately
async addLayoutsToMap(layouts) {
let normalizedLayouts = this.normalizeLayoutsObject(layouts);
// Clear out any previous layout relationships to make way for the new ones
this.removeLayoutNodes(normalizedLayouts);
for (let layout in normalizedLayouts) {
// We add this pre-emptively to add the `layout` data
if (!this.map.hasNode(layout)) {
this.map.addNode(layout, {
type: GlobalDependencyMap.LAYOUT_KEY,
});
} else {
this.map.setNodeData(layout, {
type: GlobalDependencyMap.LAYOUT_KEY,
});
}
// Potential improvement: only add the first template in the chain for a template and manage any upstream layouts by their own relationships
for (let pageTemplate of normalizedLayouts[layout]) {
this.addDependency(pageTemplate, [layout]);
}
if (this.#templateConfig?.shouldSpiderJavaScriptDependencies()) {
let deps = await JavaScriptDependencies.getDependencies([layout], this.isEsm);
this.addDependency(layout, deps);
}
}
}
get map() {
if (!this._map) {
this._map = new DepGraph({ circular: true });
}
return this._map;
}
set map(graph) {
this._map = graph;
}
normalizeNode(node) {
if (!node) {
return;
}
// TODO tests for this
// Fix URL objects passed in (sass does this)
if (typeof node !== "string" && "toString" in node) {
node = node.toString();
}
if (typeof node !== "string") {
throw new Error("`addDependencies` files must be strings. Received:" + node);
}
return PathNormalizer.fullNormalization(node);
}
normalizeLayoutsObject(layouts) {
let o = {};
for (let rawLayout in layouts) {
let layout = this.normalizeNode(rawLayout);
o[layout] = layouts[rawLayout].map((entry) => this.normalizeNode(entry));
}
return o;
}
getDependantsFor(node) {
if (!node) {
return new Set();
}
node = this.normalizeNode(node);
if (!this.map.hasNode(node)) {
return new Set();
}
// Direct dependants and dependencies, both publish and consume from collections
return this.map.directDependantsOf(node);
}
hasNode(node) {
return this.map.hasNode(this.normalizeNode(node));
}
findCollectionsRemovedFrom(node, collectionNames) {
if (!this.hasNode(node)) {
return new Set();
}
let prevDeps = this.getDependantsFor(node)
.filter((entry) => {
return entry.startsWith(GlobalDependencyMap.COLLECTION_PREFIX);
})
.map((entry) => {
return GlobalDependencyMap.getEntryFromCollectionKey(entry);
});
let prevDepsSet = new Set(prevDeps);
let deleted = new Set();
for (let dep of prevDepsSet) {
if (!collectionNames.has(dep)) {
deleted.add(dep);
}
}
return deleted;
}
resetNode(node) {
node = this.normalizeNode(node);
if (!this.map.hasNode(node)) {
return;
}
// We dont want to remove relationships that consume this, controlled by the upstream content
// for (let dep of this.map.directDependantsOf(node)) {
// this.map.removeDependency(dep, node);
// }
for (let dep of this.map.directDependenciesOf(node)) {
this.map.removeDependency(node, dep);
}
}
getTemplatesThatConsumeCollections(collectionNames) {
let templates = new Set();
for (let name of collectionNames) {
let collectionName = GlobalDependencyMap.getCollectionKeyForEntry(name);
if (!this.map.hasNode(collectionName)) {
continue;
}
for (let node of this.map.dependantsOf(collectionName)) {
if (!node.startsWith(GlobalDependencyMap.COLLECTION_PREFIX)) {
let data = this.map.getNodeData(node);
if (!data || !data.type || data.type != GlobalDependencyMap.LAYOUT_KEY) {
templates.add(node);
}
}
}
}
return templates;
}
getLayoutsUsedBy(node) {
node = this.normalizeNode(node);
if (!this.map.hasNode(node)) {
return [];
}
let layouts = [];
// include self, if layout
if (this.map.getNodeData(node)?.type === GlobalDependencyMap.LAYOUT_KEY) {
layouts.push(node);
}
this.map.dependantsOf(node).forEach((node) => {
let data = this.map.getNodeData(node);
// we only want layouts
if (data?.type === GlobalDependencyMap.LAYOUT_KEY) {
return layouts.push(node);
}
});
return layouts;
}
// In order
// Does not include original templatePaths (unless *they* are second-order relevant)
getTemplatesRelevantToTemplateList(templatePaths) {
let overallOrder = this.map.overallOrder();
overallOrder = this.filterOutLayouts(overallOrder);
overallOrder = this.filterOutCollections(overallOrder);
let relevantLookup = {};
for (let inputPath of templatePaths) {
inputPath = TemplatePath.stripLeadingDotSlash(inputPath);
let deps = this.getDependencies(inputPath, false);
if (Array.isArray(deps)) {
let paths = this.filterOutCollections(deps);
for (let node of paths) {
relevantLookup[node] = true;
}
}
}
return overallOrder.filter((node) => {
if (relevantLookup[node]) {
return true;
}
return false;
});
}
// Layouts are not relevant to compile cache and can be ignored
getDependencies(node, includeLayouts = true) {
node = this.normalizeNode(node);
// `false` means the Node was unknown
if (!this.map.hasNode(node)) {
return false;
}
return this.map.dependenciesOf(node).filter((node) => {
if (includeLayouts) {
return true;
}
// When includeLayouts is `false` we want to filter out layouts
let data = this.map.getNodeData(node);
if (data?.type === GlobalDependencyMap.LAYOUT_KEY) {
return false;
}
return true;
});
}
// node arguments are already normalized
_addDependency(from, toArray = []) {
this.map.addNode(from);
if (!Array.isArray(toArray)) {
throw new Error("Second argument to `addDependency` must be an Array.");
}
// debug("%o depends on %o", from, toArray);
for (let to of toArray) {
if (!this.map.hasNode(to)) {
this.map.addNode(to);
}
if (from !== to) {
this.map.addDependency(from, to);
}
}
}
addDependency(from, toArray = []) {
this._addDependency(
this.normalizeNode(from),
toArray.map((to) => this.normalizeNode(to)),
);
}
static getEntryFromCollectionKey(entry) {
return entry.slice(GlobalDependencyMap.COLLECTION_PREFIX.length);
}
static getCollectionKeyForEntry(entry) {
return `${GlobalDependencyMap.COLLECTION_PREFIX}${entry}`;
}
addDependencyConsumesCollection(from, collectionName) {
let nodeName = this.normalizeNode(from);
debug("%o depends on collection: %o", nodeName, collectionName);
this._addDependency(nodeName, [GlobalDependencyMap.getCollectionKeyForEntry(collectionName)]);
}
addDependencyPublishesToCollection(from, collectionName) {
let normalizedFrom = this.normalizeNode(from);
this._addDependency(GlobalDependencyMap.getCollectionKeyForEntry(collectionName), [
normalizedFrom,
]);
}
// Layouts are not relevant to compile cache and can be ignored
hasDependency(from, to, includeLayouts) {
to = this.normalizeNode(to);
let deps = this.getDependencies(from, includeLayouts); // normalizes `from`
if (!deps) {
return false;
}
return deps.includes(to);
}
// Layouts are not relevant to compile cache and can be ignored
isFileRelevantTo(fullTemplateInputPath, comparisonFile, includeLayouts) {
fullTemplateInputPath = this.normalizeNode(fullTemplateInputPath);
comparisonFile = this.normalizeNode(comparisonFile);
// No watch/serve changed file
if (!comparisonFile) {
return false;
}
// The file that changed is the relevant file
if (fullTemplateInputPath === comparisonFile) {
return true;
}
// The file that changed is a dependency of the template
// comparisonFile is used by fullTemplateInputPath
if (this.hasDependency(fullTemplateInputPath, comparisonFile, includeLayouts)) {
return true;
}
return false;
}
isFileUsedBy(parent, child, includeLayouts) {
if (this.hasDependency(parent, child, includeLayouts)) {
// child is used by parent
return true;
}
return false;
}
stringify() {
return JSON.stringify(this.map, function replacer(key, value) {
// Serialize internal Map objects.
if (value instanceof Map) {
let obj = {};
for (let [k, v] of value) {
obj[k] = v;
}
return obj;
}
return value;
});
}
restore(persisted) {
let obj = JSON.parse(persisted);
let graph = new DepGraph({ circular: true });
// https://github.com/jriecken/dependency-graph/issues/44
// Restore top level serialized Map objects (in stringify above)
for (let key in obj) {
let map = graph[key];
for (let k in obj[key]) {
let v = obj[key][k];
map.set(k, v);
}
}
this.map = graph;
}
}
export default GlobalDependencyMap;

View File

@@ -0,0 +1,151 @@
import { DeepCopy } from "@11ty/eleventy-utils";
import urlFilter from "../Filters/Url.js";
import PathPrefixer from "../Util/PathPrefixer.js";
import { HtmlTransformer } from "../Util/HtmlTransformer.js";
import isValidUrl from "../Util/ValidUrl.js";
function addPathPrefixToUrl(url, pathPrefix, base) {
let u;
if (base) {
u = new URL(url, base);
} else {
u = new URL(url);
}
// Add pathPrefix **after** url is transformed using base
if (pathPrefix) {
u.pathname = PathPrefixer.joinUrlParts(pathPrefix, u.pathname);
}
return u.toString();
}
// pathprefix is only used when overrideBase is a full URL
function transformUrl(url, base, opts = {}) {
let { pathPrefix, pageUrl } = opts;
// full URL, return as-is
if (isValidUrl(url)) {
return url;
}
// Not a full URL, but with a full base URL
// e.g. relative urls like "subdir/", "../subdir", "./subdir"
if (isValidUrl(base)) {
// convert relative paths to absolute path first using pageUrl
if (pageUrl && !url.startsWith("/")) {
let urlObj = new URL(url, `http://example.com${pageUrl}`);
url = urlObj.pathname + (urlObj.hash || "");
}
return addPathPrefixToUrl(url, pathPrefix, base);
}
// Not a full URL, nor a full base URL (call the built-in `url` filter)
return urlFilter(url, base);
}
function eleventyHtmlBasePlugin(eleventyConfig, defaultOptions = {}) {
let opts = DeepCopy(
{
// eleventyConfig.pathPrefix is new in Eleventy 2.0.0-canary.15
// `base` can be a directory (for path prefix transformations)
// OR a full URL with origin and pathname
baseHref: eleventyConfig.pathPrefix,
extensions: "html",
},
defaultOptions,
);
// `filters` option to rename filters was removed in 3.0.0-alpha.13
// Renaming these would cause issues in other plugins (e.g. RSS)
if (opts.filters !== undefined) {
throw new Error(
"The `filters` option in the HTML Base plugin was removed to prevent future cross-plugin compatibility issues.",
);
}
if (opts.baseHref === undefined) {
throw new Error("The `base` option is required in the HTML Base plugin.");
}
eleventyConfig.addFilter("addPathPrefixToFullUrl", function (url) {
return addPathPrefixToUrl(url, eleventyConfig.pathPrefix);
});
// Apply to one URL
eleventyConfig.addFilter(
"htmlBaseUrl",
/** @this {object} */
function (url, baseOverride, pageUrlOverride) {
let base = baseOverride || opts.baseHref;
// Do nothing with a default base
if (base === "/") {
return url;
}
return transformUrl(url, base, {
pathPrefix: eleventyConfig.pathPrefix,
pageUrl: pageUrlOverride || this.page?.url,
});
},
);
// Apply to a block of HTML
eleventyConfig.addAsyncFilter(
"transformWithHtmlBase",
/** @this {object} */
function (content, baseOverride, pageUrlOverride) {
let base = baseOverride || opts.baseHref;
// Do nothing with a default base
if (base === "/") {
return content;
}
return HtmlTransformer.transformStandalone(content, (url) => {
return transformUrl(url.trim(), base, {
pathPrefix: eleventyConfig.pathPrefix,
pageUrl: pageUrlOverride || this.page?.url,
});
});
},
);
// Apply to all HTML output in your project
eleventyConfig.htmlTransformer.addUrlTransform(
opts.extensions,
/** @this {object} */
function (urlInMarkup) {
// baseHref override is via renderTransforms filter for adding the absolute URL (e.g. https://example.com/pathPrefix/) for RSS/Atom/JSON feeds
return transformUrl(urlInMarkup.trim(), this.baseHref || opts.baseHref, {
pathPrefix: eleventyConfig.pathPrefix,
pageUrl: this.url,
});
},
{
priority: -1, // run last (especially after PathToUrl transform)
enabled: function (context) {
// Enabled when pathPrefix is non-default or via renderTransforms
return context.baseHref || opts.baseHref !== "/";
},
},
);
}
Object.defineProperty(eleventyHtmlBasePlugin, "eleventyPackage", {
value: "@11ty/eleventy/html-base-plugin",
});
Object.defineProperty(eleventyHtmlBasePlugin, "eleventyPluginOptions", {
value: {
unique: true,
},
});
export default eleventyHtmlBasePlugin;
export { transformUrl as applyBaseToUrl };

317
node_modules/@11ty/eleventy/src/Plugins/I18nPlugin.js generated vendored Normal file
View File

@@ -0,0 +1,317 @@
import { bcp47Normalize } from "bcp-47-normalize";
import iso639 from "iso-639-1";
import { DeepCopy } from "@11ty/eleventy-utils";
// pathPrefix note:
// When using `locale_url` filter with the `url` filter, `locale_url` must run first like
// `| locale_url | url`. If you run `| url | locale_url` it wont match correctly.
// TODO improvement would be to throw an error if `locale_url` finds a url with the
// path prefix at the beginning? Would need a better way to know `url` has transformed a string
// rather than just raw comparison.
// e.g. --pathprefix=/en/ should return `/en/en/` for `/en/index.liquid`
class LangUtils {
static getLanguageCodeFromInputPath(filepath) {
return (filepath || "").split("/").find((entry) => Comparator.isLangCode(entry));
}
static getLanguageCodeFromUrl(url) {
let s = (url || "").split("/");
return s.length > 0 && Comparator.isLangCode(s[1]) ? s[1] : "";
}
static swapLanguageCodeNoCheck(str, langCode) {
let found = false;
return str
.split("/")
.map((entry) => {
// only match the first one
if (!found && Comparator.isLangCode(entry)) {
found = true;
return langCode;
}
return entry;
})
.join("/");
}
static swapLanguageCode(str, langCode) {
if (!Comparator.isLangCode(langCode)) {
return str;
}
return LangUtils.swapLanguageCodeNoCheck(str, langCode);
}
}
class Comparator {
// https://en.wikipedia.org/wiki/IETF_language_tag#Relation_to_other_standards
// Requires a ISO-639-1 language code at the start (2 characters before the first -)
static isLangCode(code) {
let [s] = (code || "").split("-");
if (!iso639.validate(s)) {
return false;
}
if (!bcp47Normalize(code)) {
return false;
}
return true;
}
static urlHasLangCode(url, code) {
if (!Comparator.isLangCode(code)) {
return false;
}
return url.split("/").some((entry) => entry === code);
}
}
function normalizeInputPath(inputPath, extensionMap) {
if (extensionMap) {
return extensionMap.removeTemplateExtension(inputPath);
}
return inputPath;
}
/*
* Input: {
* '/en-us/test/': './test/stubs-i18n/en-us/test.11ty.js',
* '/en/test/': './test/stubs-i18n/en/test.liquid',
* '/es/test/': './test/stubs-i18n/es/test.njk',
* '/non-lang-file/': './test/stubs-i18n/non-lang-file.njk'
* }
*
* Output: {
* '/en-us/test/': [ { url: '/en/test/' }, { url: '/es/test/' } ],
* '/en/test/': [ { url: '/en-us/test/' }, { url: '/es/test/' } ],
* '/es/test/': [ { url: '/en-us/test/' }, { url: '/en/test/' } ]
* }
*/
function getLocaleUrlsMap(urlToInputPath, extensionMap, options = {}) {
let filemap = {};
for (let url in urlToInputPath) {
// Group number comes from Pagination.js
let { inputPath: originalFilepath, groupNumber } = urlToInputPath[url];
let filepath = normalizeInputPath(originalFilepath, extensionMap);
let replaced =
LangUtils.swapLanguageCodeNoCheck(filepath, "__11ty_i18n") + `_group:${groupNumber}`;
if (!filemap[replaced]) {
filemap[replaced] = [];
}
let langCode = LangUtils.getLanguageCodeFromInputPath(originalFilepath);
if (!langCode) {
langCode = LangUtils.getLanguageCodeFromUrl(url);
}
if (!langCode) {
langCode = options.defaultLanguage;
}
if (langCode) {
filemap[replaced].push({
url,
lang: langCode,
label: iso639.getNativeName(langCode.split("-")[0]),
});
} else {
filemap[replaced].push({ url });
}
}
// Default sorted by lang code
for (let key in filemap) {
filemap[key].sort(function (a, b) {
if (a.lang < b.lang) {
return -1;
}
if (a.lang > b.lang) {
return 1;
}
return 0;
});
}
// map of input paths => array of localized urls
let urlMap = {};
for (let filepath in filemap) {
for (let entry of filemap[filepath]) {
let url = entry.url;
if (!urlMap[url]) {
urlMap[url] = filemap[filepath].filter((entry) => {
if (entry.lang) {
return true;
}
return entry.url !== url;
});
}
}
}
return urlMap;
}
function eleventyI18nPlugin(eleventyConfig, opts = {}) {
let options = DeepCopy(
{
defaultLanguage: "",
filters: {
url: "locale_url",
links: "locale_links",
},
errorMode: "strict", // allow-fallback, never
},
opts,
);
if (!options.defaultLanguage) {
throw new Error(
"You must specify a `defaultLanguage` in Eleventys Internationalization (I18N) plugin.",
);
}
let extensionMap;
eleventyConfig.on("eleventy.extensionmap", (map) => {
extensionMap = map;
});
let bench = eleventyConfig.benchmarkManager.get("Aggregate");
let contentMaps = {};
eleventyConfig.on("eleventy.contentMap", function ({ urlToInputPath, inputPathToUrl }) {
let b = bench.get("(i18n Plugin) Setting up content map.");
b.before();
contentMaps.inputPathToUrl = inputPathToUrl;
contentMaps.urlToInputPath = urlToInputPath;
contentMaps.localeUrlsMap = getLocaleUrlsMap(urlToInputPath, extensionMap, options);
b.after();
});
eleventyConfig.addGlobalData("eleventyComputed.page.lang", () => {
// if addGlobalData receives a function it will execute it immediately,
// so we return a nested function for computed data
return (data) => {
return LangUtils.getLanguageCodeFromUrl(data.page.url) || options.defaultLanguage;
};
});
// Normalize a theoretical URL based on the current pages language
// If a non-localized file exists, returns the URL without a language assigned
// Fails if no file exists (localized and not localized)
eleventyConfig.addFilter(options.filters.url, function (url, langCodeOverride) {
let langCode =
langCodeOverride ||
LangUtils.getLanguageCodeFromUrl(this.page?.url) ||
options.defaultLanguage;
// Already has a language code on it and has a relevant url with the target language code
if (
contentMaps.localeUrlsMap[url] ||
(!url.endsWith("/") && contentMaps.localeUrlsMap[`${url}/`])
) {
for (let existingUrlObj of contentMaps.localeUrlsMap[url] ||
contentMaps.localeUrlsMap[`${url}/`]) {
if (Comparator.urlHasLangCode(existingUrlObj.url, langCode)) {
return existingUrlObj.url;
}
}
}
// Needs the language code prepended to the URL
let prependedLangCodeUrl = `/${langCode}${url}`;
if (
contentMaps.localeUrlsMap[prependedLangCodeUrl] ||
(!prependedLangCodeUrl.endsWith("/") && contentMaps.localeUrlsMap[`${prependedLangCodeUrl}/`])
) {
return prependedLangCodeUrl;
}
if (
contentMaps.urlToInputPath[url] ||
(!url.endsWith("/") && contentMaps.urlToInputPath[`${url}/`])
) {
// this is not a localized file (independent of a language code)
if (options.errorMode === "strict") {
throw new Error(
`Localized file for URL ${prependedLangCodeUrl} was not found in your project. A non-localized version does exist—are you sure you meant to use the \`${options.filters.url}\` filter for this? You can bypass this error using the \`errorMode\` option in the I18N plugin (current value: "${options.errorMode}").`,
);
}
} else if (options.errorMode === "allow-fallback") {
// Youre linking to a localized file that doesnt exist!
throw new Error(
`Localized file for URL ${prependedLangCodeUrl} was not found in your project! You will need to add it if you want to link to it using the \`${options.filters.url}\` filter. You can bypass this error using the \`errorMode\` option in the I18N plugin (current value: "${options.errorMode}").`,
);
}
return url;
});
// Refactor to use url
// Find the links that are localized alternates to the inputPath argument
eleventyConfig.addFilter(options.filters.links, function (urlOverride) {
let url = urlOverride || this.page?.url;
return (contentMaps.localeUrlsMap[url] || []).filter((entry) => {
return entry.url !== url;
});
});
// Returns a `page`-esque variable for the root default language page
// If paginated, returns first result only
eleventyConfig.addFilter(
"locale_page", // This is not exposed in `options` because it is an Eleventy internals filter (used in get*CollectionItem filters)
function (pageOverride, languageCode) {
// both args here are optional
if (!languageCode) {
languageCode = options.defaultLanguage;
}
let page = pageOverride || this.page;
let url; // new url
if (contentMaps.localeUrlsMap[page.url]) {
for (let entry of contentMaps.localeUrlsMap[page.url]) {
if (entry.lang === languageCode) {
url = entry.url;
}
}
}
let inputPath = LangUtils.swapLanguageCode(page.inputPath, languageCode);
if (
!url ||
!Array.isArray(contentMaps.inputPathToUrl[inputPath]) ||
contentMaps.inputPathToUrl[inputPath].length === 0
) {
// no internationalized pages found
return page;
}
let result = {
// // note that the permalink/slug may be different for the localized file!
url,
inputPath,
filePathStem: LangUtils.swapLanguageCode(page.filePathStem, languageCode),
// outputPath is omitted here, not necessary for GetCollectionItem.js if url is provided
__locale_page_resolved: true,
};
return result;
},
);
}
export { Comparator, LangUtils };
Object.defineProperty(eleventyI18nPlugin, "eleventyPackage", {
value: "@11ty/eleventy/i18n-plugin",
});
Object.defineProperty(eleventyI18nPlugin, "eleventyPluginOptions", {
value: {
unique: true,
},
});
export default eleventyI18nPlugin;

View File

@@ -0,0 +1,103 @@
import matchHelper from "posthtml-match-helper";
import { decodeHTML } from "entities";
import slugifyFilter from "../Filters/Slugify.js";
import MemoizeUtil from "../Util/MemoizeFunction.js";
function getTextNodeContent(node) {
if (node.attrs?.["eleventy:id-ignore"] === "") {
delete node.attrs["eleventy:id-ignore"];
return "";
}
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 IdAttributePlugin(eleventyConfig, options = {}) {
if (!options.slugify) {
options.slugify = MemoizeUtil(slugifyFilter);
}
if (!options.selector) {
options.selector = "[id],h1,h2,h3,h4,h5,h6";
}
options.decodeEntities = options.decodeEntities ?? true;
options.checkDuplicates = options.checkDuplicates ?? "error";
eleventyConfig.htmlTransformer.addPosthtmlPlugin(
"html",
function (pluginOptions = {}) {
if (typeof options.filter === "function") {
if (options.filter(pluginOptions) === false) {
return function () {};
}
}
return function (tree) {
// One per page
let conflictCheck = {};
// Cache heading nodes for conflict resolution
let headingNodes = {};
tree.match(matchHelper(options.selector), function (node) {
if (node.attrs?.id) {
let id = node.attrs?.id;
if (conflictCheck[id]) {
conflictCheck[id]++;
if (headingNodes[id]) {
// Rename conflicting assigned heading id
let newId = `${id}-${conflictCheck[id]}`;
headingNodes[newId] = headingNodes[id];
headingNodes[newId].attrs.id = newId;
delete headingNodes[id];
} else if (options.checkDuplicates === "error") {
// Existing `id` conflicts with assigned heading id, throw error
throw new Error(
"Duplicate `id` attribute (" +
id +
") in markup on " +
pluginOptions.page.inputPath,
);
}
} else {
conflictCheck[id] = 1;
}
} else if (!node.attrs?.id && node.content) {
node.attrs = node.attrs || {};
let textContent = getTextNodeContent(node);
if (options.decodeEntities) {
textContent = decodeHTML(textContent);
}
let id = options.slugify(textContent);
if (conflictCheck[id]) {
conflictCheck[id]++;
id = `${id}-${conflictCheck[id]}`;
} else {
conflictCheck[id] = 1;
}
headingNodes[id] = node;
node.attrs.id = id;
}
return node;
});
};
} /* , {} // pluginOptions */,
);
}
export { IdAttributePlugin };

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