Compare commits

..
1 Commits
Author SHA1 Message Date
Marcus Noble 0f021e9672 feat: modernize static site generator stack
- Upgrade from Node 16 to Node 22
- Replace deprecated node-sass with Dart Sass (sass)
- Migrate to @metalsmith/* scoped packages for markdown, layouts, in-place, collections
- Replace deprecated metalsmith-markdownit with @metalsmith/markdown + Marked
- Replace deprecated metalsmith-in-place v1 with @metalsmith/in-place v5
- Replace deprecated metalsmith-layouts v1 with @metalsmith/layouts v3
- Update @metalsmith/collections to v2
- Use custom permalinks plugin (upstream incompatible with new regexparam)
- Migrate filterRoutes.js to Express 4 compatibility
- Add Handlebars partial preprocessing for inline {{> partial }} in markdown
- Add custom feed generation (replaces deprecated metalsmith-feed)
- Update all other dependencies to latest versions
- Update Dockerfile for Node 22 Alpine
- Update .nvmrc to 22
2026-11-16 09:01:33 +00:00
4 changed files with 38 additions and 301 deletions

No files matched your search

+25 -131
View File
@@ -4,7 +4,6 @@ const path = require("path");
const express = require("express");
const compress = require("compression");
const Metalsmith = require("metalsmith");
const matter = require("gray-matter");
const inPlace = require("@metalsmith/in-place");
const layouts = require("@metalsmith/layouts");
const markdown = require("@metalsmith/markdown");
@@ -261,22 +260,16 @@ function handlebarsPreprocessor() {
}
// Extract date and title from filename for permalinks compatibility
// The filename date is the primary source for the permalink
// Also set default values for files without them
const postPattern = /^posts\/(\d{4}-\d{2}-\d{2})-(.+)\.(md|markdown)$/;
for (const file of Object.keys(files)) {
const match = file.match(postPattern);
if (match) {
const [, dateStr, titleSlug] = match;
// Use filename date for permalink (via _filenameDate), but front matter date for other purposes
// Store filename-based date for permalinks
if (!files[file]._filenameDate) {
files[file]._filenameDate = new Date(dateStr);
// Only set if not already set in front matter
if (!files[file].date) {
files[file].date = new Date(dateStr);
}
// Also store the filename-based title slug for permalinks
if (!files[file]._filenameTitle) {
files[file]._filenameTitle = titleSlug;
}
// Set the title from front matter (or derive from filename)
if (!files[file].title) {
// Convert slug to title: "some-title-slug" -> "Some Title Slug"
files[file].title = titleSlug
@@ -285,7 +278,7 @@ function handlebarsPreprocessor() {
.join(" ");
}
}
// Set default date for files without one (e.g., index.html from pagination, pages)
// Set default date for files without one (e.g., pages)
if (!files[file].date) {
files[file].date = new Date();
}
@@ -323,12 +316,12 @@ const ms = Metalsmith(__dirname)
.use(
collections({
posts: {
pattern: "posts/*.{md,markdown}",
pattern: "posts/*",
sortBy: "date",
reverse: true,
},
drafts: {
pattern: "drafts/*.{md,markdown}",
pattern: "drafts/*",
sortBy: "date",
reverse: true,
},
@@ -340,22 +333,6 @@ const ms = Metalsmith(__dirname)
},
})
)
.use(function (files, metalsmith, done) {
// Extract YAML front matter from all markdown files
Object.keys(files).forEach(function (file) {
if (file.endsWith(".md") || file.endsWith(".markdown")) {
const content = files[file].contents.toString();
const parsed = matter(content);
// Update file content to body (without front matter)
files[file].contents = Buffer.from(parsed.content);
// Extract front matter as file metadata
if (parsed.data) {
Object.assign(files[file], parsed.data);
}
}
});
done();
})
.use(handlebarsPreprocessor())
.use(
markdown({
@@ -363,110 +340,14 @@ const ms = Metalsmith(__dirname)
})
)
.use(
pagination({
"collections.posts": {
perPage: 5,
layout: "index.html",
first: "index.html",
noPageOne: true,
path: "page:num/index.html",
pageMetadata: {
title: "Posts",
},
},
inPlace({
transform: "handlebars",
pattern: "**/*.html",
})
)
.use(function (files, metalsmith, done) {
// Pre-compute paths for layouts rendering
// This mirrors the permalinks logic but doesn't rename files
const slugRe = /[<>:"'\|?*]|[^\w\s$_+~.()!\-@\/]+/g;
const linksets = [
{ match: { collection: "pages" }, pattern: ":title" },
{ match: { collection: "drafts" }, pattern: "drafts/:title" },
];
for (const file of Object.keys(files)) {
const data = files[file];
// Set default date
if (!data.date) {
data.date = new Date();
}
// Skip non-HTML files
if (!file.endsWith(".html")) continue;
if (data.permalink === false) continue;
// Skip layout files (layout matches filename)
const baseName = path.basename(file, ".html");
if (data.layout === baseName || data.layout === `${baseName}.html`) continue;
// Determine linkset
let linkset = null;
for (const ls of linksets) {
if (ls.match) {
let matched = true;
for (const [key, val] of Object.entries(ls.match)) {
const fileVal = data[key];
if (Array.isArray(fileVal)) {
if (!fileVal.includes(val)) { matched = false; break; }
} else if (fileVal !== val) { matched = false; break; }
}
if (matched) { linkset = ls; break; }
}
}
const pattern = linkset ? (linkset.pattern || ":date-:title") : ":date-:title";
// Compute permalink
let result = pattern
.replace(/:(\w+)(\??)/g, (match, key, optional) => {
let value = data[key];
if (value === undefined || value === null) {
if (optional) return "";
return key;
}
if (key === "date" && data._filenameDate) {
const d = data._filenameDate;
return d.getFullYear() + "-" + String(d.getMonth() + 1).padStart(2, "0") + "-" + String(d.getDate()).padStart(2, "0");
}
if (key === "title" && data._filenameTitle) {
return data._filenameTitle.replace(/\s+/g, "-").replace(slugRe, "");
}
if (value instanceof Date) {
const d = value;
return d.getFullYear() + "-" + String(d.getMonth() + 1).padStart(2, "0") + "-" + String(d.getDate()).padStart(2, "0");
}
return String(value).toLowerCase().replace(/\s+/g, "-").replace(slugRe, "");
})
.replace(/\/+$/, "");
// Add directory index
if (path.extname(result) === "" || path.extname(result) === ".html") {
if (!path.extname(result)) {
result = path.join(result, "index.html");
}
}
// Prepend source directory prefix
let sourcePrefix = "";
if (file.startsWith("posts/")) sourcePrefix = "posts/";
else if (file.startsWith("pages/")) sourcePrefix = "pages/";
data.permalink = sourcePrefix + result;
// Set path for templates (permalink without index.html)
if (data.permalink.endsWith("/index.html")) {
data.path = data.permalink.replace(/\/index\.html$/, "");
} else if (path.extname(data.permalink) === ".html") {
data.path = data.permalink.replace(/\.html$/, "");
} else {
data.path = data.permalink;
}
}
done();
})
.use(
layouts({
transform: require("./plugins/handlebars-html"),
transform: "handlebars",
directory: "templates",
pattern: "**/*.html",
extname: ".html",
@@ -491,7 +372,20 @@ const ms = Metalsmith(__dirname)
.use(
sitemap({
hostname: "https://marcusnoble.co.uk",
omitExtension: true,
})
)
.use(
pagination({
"collections.posts": {
perPage: 5,
layout: "index.html",
first: "index.html",
noPageOne: true,
path: "page:num/index.html",
pageMetadata: {
title: "Posts",
},
},
})
)
.use(feedPlugin());
+1 -2
View File
@@ -10,15 +10,14 @@
"@metalsmith/in-place": "^5.0.0",
"@metalsmith/layouts": "^3.0.0",
"@metalsmith/markdown": "^1.10.0",
"metalsmith-sitemap": "^1.2.2",
"compression": "^1.8.2",
"express": "^4.21.2",
"gray-matter": "^4.0.3",
"handlebars": "^4.7.10",
"jstransformer-handlebars": "^1.2.0",
"marked": "^18.2.0",
"metalsmith-define": "^2.1.3",
"metalsmith-pagination": "^1.5.0",
"metalsmith-sitemap": "^1.2.2",
"moment": "^2.31.0",
"rss": "^1.2.2",
"sass": "^1.108.2",
-99
View File
@@ -1,99 +0,0 @@
const fs = require("fs");
const path = require("path");
const Handlebars = require("handlebars");
const moment = require("moment");
const striptags = require("striptags");
const { marked } = require("marked");
// Setup marked renderer
marked.setOptions({ gfm: true, breaks: true });
const renderer = new marked.Renderer();
const originalTable = renderer.table.bind(renderer);
renderer.table = function (e) {
let result = originalTable(e);
return result.replace("<table>", '<table role="grid">');
};
// Register helpers on Handlebars
Handlebars.registerHelper("markdown", function (text) {
if (!text) return "";
return marked.parse(text, { renderer });
});
Handlebars.registerHelper("moment", function (date, format) {
return new moment(date).format(format);
});
Handlebars.registerHelper("striptags", function (text) {
return striptags(text);
});
Handlebars.registerHelper("buildTitle", function (title, siteTitle) {
if (title.indexOf(siteTitle) < 0) {
title = "'" + title + "' by " + siteTitle;
}
return title;
});
Handlebars.registerHelper("jointags", function (tags) {
return (tags || "").split(" ").join(",");
});
Handlebars.registerHelper("encodetitle", function (str) {
return (str || "").replaceAll(" ", "%2B");
});
// Load all partials from templates/partials directory
const partialsDir = path.join(__dirname, "..", "templates", "partials");
if (fs.existsSync(partialsDir)) {
fs.readdirSync(partialsDir).forEach((file) => {
const name = path.parse(file).name;
const content = fs.readFileSync(path.join(partialsDir, file), "utf8");
Handlebars.registerPartial(name, content);
});
}
// Compile a template file (used by renderFileAsync)
function compile(filePath) {
const template = fs.readFileSync(filePath, "utf8");
return {
fn: Handlebars.compile(template),
dependencies: [],
};
}
// Render a template string with locals
function render(templateStr, opts, locals) {
const template = Handlebars.compile(templateStr);
const output = template(locals);
return { body: output, dependencies: [] };
}
// Render a template file with locals
async function renderFileAsync(filePath, opts, locals) {
const template = fs.readFileSync(filePath, "utf8");
const compiled = Handlebars.compile(template);
const output = compiled(locals);
return { body: output, dependencies: [] };
}
// Assemble the jstransformer interface
const jstransformer = {
name: "handlebars",
inputFormats: ["hbs", "handlebars", "html"],
outputFormat: "html",
compile: function (templateStr) {
const compiled = Handlebars.compile(templateStr);
return { fn: compiled, dependencies: [] };
},
render: function (templateStr, opts, locals) {
return render(templateStr, opts, locals);
},
renderAsync: async function (templateStr, opts, locals) {
return render(templateStr, opts, locals);
},
renderFileAsync: async function (filePath, opts, locals) {
return renderFileAsync(filePath, opts, locals);
},
registerPartial: Handlebars.registerPartial.bind(Handlebars),
registerHelper: Handlebars.registerHelper.bind(Handlebars),
partials: Handlebars.partials,
helpers: Handlebars.helpers,
};
module.exports = jstransformer;
+12 -69
View File
@@ -1,9 +1,8 @@
const path = require("path");
const fs = require("fs");
/**
* Custom Metalsmith permalinks plugin.
* Preserves source directory structure for posts, applies custom patterns for pages.
* Replaces `:date-:title` style patterns using file metadata.
*/
function permalinks(options) {
const defaultOptions = {
@@ -47,8 +46,6 @@ function permalinks(options) {
s = s.split(from).join(to);
}
}
// Replace spaces with dashes and remove special chars
s = s.replace(/\s+/g, "-");
if (opts.slug.remove) {
s = s.replace(new RegExp(opts.slug.remove, "g"), "");
}
@@ -57,22 +54,13 @@ function permalinks(options) {
function replacePattern(pattern, data) {
return pattern.replace(/:(\w+)(\??)/g, (match, key, optional) => {
let value = data[key];
const value = data[key];
if (value === undefined || value === null) {
if (optional) return "";
throw new Error(
`Could not substitute ':${key}' in pattern '${pattern}', '${key}' is undefined`
);
}
// For date in permalink, use _filenameDate if available (to avoid collisions
// when front matter date differs from filename date)
if (key === 'date' && data._filenameDate) {
return formatDate(data._filenameDate);
}
// For title in permalink, use _filenameTitle if available (to match source filenames)
if (key === 'title' && data._filenameTitle) {
return slugify(data._filenameTitle);
}
if (value instanceof Date) {
return formatDate(value);
}
@@ -104,42 +92,27 @@ function permalinks(options) {
}
return function (files, metalsmith, done) {
const keys = Object.keys(files);
for (const file of keys) {
const data = files[file];
const entries = Object.entries(files);
for (const [file, data] of entries) {
// Skip non-HTML files
if (!file.endsWith(".html")) continue;
// Skip if permalink is explicitly disabled
if (data.permalink === false) continue;
// Skip if this is a layout/template file (has layout that matches filename)
// e.g., index.html with layout: 'index.html' should not be permalinked
const baseName = path.basename(file, '.html');
if (data.layout === baseName || data.layout === `${baseName}.html`) continue;
// Check file-specific permalink first
if (data.permalink) {
let result = replacePattern(data.permalink, data);
if (opts.trailingSlash) result = result.replace(/\/+$/, "");
data.permalink = result;
continue;
}
// Determine which linkset to use (or default)
const linkset = getMatchedLinkset(data, opts.linksets) || opts;
const pattern = linkset.pattern || opts.pattern;
// Check file-specific permalink first
if (data.permalink) {
data.permalink = replacePattern(data.permalink, data);
if (opts.trailingSlash) data.permalink = data.permalink.replace(/\/+$/, "");
continue;
}
// For posts: preserve the "posts/" prefix
// For other files: use the pattern as-is
let sourcePrefix = "";
if (file.startsWith("posts/")) {
sourcePrefix = "posts/";
} else if (file.startsWith("pages/")) {
sourcePrefix = "pages/";
}
// Replace pattern placeholders
let result = replacePattern(pattern, data);
@@ -155,37 +128,7 @@ function permalinks(options) {
}
}
// Prepend source directory prefix
data.permalink = sourcePrefix + result;
// Set path metadata for templates (permalink without index.html)
if (data.permalink.endsWith("/index.html")) {
data.path = data.permalink.replace(/\/index\.html$/, "");
} else if (path.extname(data.permalink) === ".html") {
data.path = data.permalink.replace(/\.html$/, "");
} else {
data.path = data.permalink;
}
}
// Now rename files based on permalink metadata
const renames = [];
for (const [file, data] of Object.entries(files)) {
if (!data.permalink) continue;
if (data.permalink === file) continue; // No change needed
renames.push([file, data.permalink]);
}
for (const [oldName, newName] of renames) {
// Create target directory if needed
const targetDir = path.dirname(newName);
if (!fs.existsSync(targetDir)) {
fs.mkdirSync(targetDir, { recursive: true });
}
// Move file
files[newName] = files[oldName];
delete files[oldName];
data.permalink = result;
}
done();