cook-ssg 2.2.3 → 2.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +17 -3
- package/package.json +1 -1
- package/scripts/build.js +12 -0
- package/scripts/plugins/apply-base-path.js +201 -0
- package/scripts/plugins/html-collections.js +211 -0
- package/scripts/plugins/process-markdown.js +3 -26
- package/scripts/utils/collections/collections.js +54 -0
- package/scripts/utils/config/config.js +15 -0
package/README.md
CHANGED
|
@@ -2,9 +2,9 @@
|
|
|
2
2
|
|
|
3
3
|
A static site build system with templating, bundling, and optimization features.
|
|
4
4
|
|
|
5
|
-
**
|
|
5
|
+
**Docs:** https://profpowell.github.io/cook/
|
|
6
6
|
**License:** MIT
|
|
7
|
-
**Node.js:** >=
|
|
7
|
+
**Node.js:** >=20.9.0
|
|
8
8
|
|
|
9
9
|
[Getting Started](#getting-started) | [View/Run the site code](#viewrun-the-site-code) | [Environment Flags](#environment-flags) | [Build Process](#build-process) | [NPM Run Scripts](#npm-run-scripts)
|
|
10
10
|
|
|
@@ -134,6 +134,7 @@ The build process performs the following steps, in this order:
|
|
|
134
134
|
1. **Creates `/dist`** - Removes existing dist folder and recreates it
|
|
135
135
|
2. **Copies `/src` to `/dist`** - All source files are copied (excludes `.md` files and `buildOnlyPaths`)
|
|
136
136
|
3. **Processes Markdown** - Converts `.md` files to `.html` with front matter support; groups pages into `collections.*` by directory
|
|
137
|
+
* With `collections: { html: true }`, HTML pages that start with YAML front matter join the same collections
|
|
137
138
|
4. **Generates image derivatives** - Responsive AVIF/WebP variants at configured widths, with a cross-build disk cache (`images` config)
|
|
138
139
|
5. **Runs custom-user `before` plugins** - Runs once before file processing
|
|
139
140
|
6. **Converts pages to directories** - `about.html` becomes `about/index.html` for extensionless URLs
|
|
@@ -159,7 +160,8 @@ The build process performs the following steps, in this order:
|
|
|
159
160
|
10. **Creates `sitemap.xml`** - When `sitemap.url` is set, written to the site root (`/dist`, or `/dist/<siteRoot>`); fragments excluded
|
|
160
161
|
11. **Creates bundled files** - `.css` and `.js` bundles are written
|
|
161
162
|
12. **Fingerprints assets** - Opt-in content-hash filenames with HTML and JS-import rewriting (`fingerprint` config)
|
|
162
|
-
13. **
|
|
163
|
+
13. **Applies `basePath`** - When set, prefixes root-relative URLs in built HTML for sub-path hosting (production only)
|
|
164
|
+
14. **Runs custom-user `after` plugins** - Runs once after file processing
|
|
163
165
|
|
|
164
166
|
A page that fails during the loop is reported (with its path) and skipped; the rest of the site still builds, a failure summary prints at the end, and the process exits non-zero so CI catches it.
|
|
165
167
|
|
|
@@ -199,6 +201,17 @@ export default {
|
|
|
199
201
|
// so active links, the sitemap and formats use /docs/, not /pages/docs/.
|
|
200
202
|
siteRoot: '',
|
|
201
203
|
|
|
204
|
+
// URL path the site is served under (default: '' = domain root).
|
|
205
|
+
// For a GitHub Pages project site at https://user.github.io/repo/ set
|
|
206
|
+
// '/repo': links stay written as '/docs/' and production builds output
|
|
207
|
+
// '/repo/docs/'. `cook dev` ignores it. Include the base path in
|
|
208
|
+
// absolute URLs you set yourself (sitemap.url, data.siteUrl).
|
|
209
|
+
basePath: '',
|
|
210
|
+
|
|
211
|
+
// HTML pages that start with YAML front matter join collections.<folder>
|
|
212
|
+
// like markdown files (default: false)
|
|
213
|
+
collections: { html: false },
|
|
214
|
+
|
|
202
215
|
// Sitemap: set url to enable (default: '' = no sitemap.xml)
|
|
203
216
|
sitemap: {
|
|
204
217
|
url: 'https://www.yoursite.com',
|
|
@@ -409,6 +422,7 @@ Generate repeated elements from arrays or collections. Perfect for blog listings
|
|
|
409
422
|
**Data Sources:**
|
|
410
423
|
- `collections.blog` - From markdown files in `/src/blog/`
|
|
411
424
|
- `collections.docs` - From markdown files in `/src/docs/`
|
|
425
|
+
- HTML pages with front matter in those folders too, when `collections: { html: true }` is set
|
|
412
426
|
- `items` - From `/config/data.js`
|
|
413
427
|
- Any array in your data configuration
|
|
414
428
|
|
package/package.json
CHANGED
package/scripts/build.js
CHANGED
|
@@ -10,6 +10,7 @@ import Util, { runFileLoop, updatePage } from './utils/util/util.js';
|
|
|
10
10
|
|
|
11
11
|
// PLUGINS
|
|
12
12
|
// -----------------------------
|
|
13
|
+
import applyBasePath from './plugins/apply-base-path.js';
|
|
13
14
|
import autoComponents from './plugins/auto-components.js';
|
|
14
15
|
import { bundleAdd, bundleBuild } from './plugins/bundle.js';
|
|
15
16
|
import copySrc from './plugins/copy-src.js';
|
|
@@ -21,6 +22,7 @@ import fingerprintAssets from './plugins/fingerprint-assets.js';
|
|
|
21
22
|
import generateFormats from './plugins/generate-formats.js';
|
|
22
23
|
import generateFragments from './plugins/generate-fragments.js';
|
|
23
24
|
import generateSitemap from './plugins/generate-sitemap-xml.js';
|
|
25
|
+
import htmlCollections from './plugins/html-collections.js';
|
|
24
26
|
import minifySrc from './plugins/minify-src.js';
|
|
25
27
|
import { optimizeImagesGenerate, optimizeImagesRewrite } from './plugins/optimize-images.js';
|
|
26
28
|
import processMarkdown from './plugins/process-markdown.js';
|
|
@@ -89,6 +91,11 @@ class Build {
|
|
|
89
91
|
// PLUGIN: Process markdown files (.md -> .html)
|
|
90
92
|
await processMarkdown({store, data});
|
|
91
93
|
|
|
94
|
+
// PLUGIN: HTML pages with front matter join collections (opt-in:
|
|
95
|
+
// `collections: { html: true }`). Pre-loop so data-repeat and the feed
|
|
96
|
+
// see every page; merges with markdown collections.
|
|
97
|
+
await htmlCollections({store, data});
|
|
98
|
+
|
|
92
99
|
// PLUGIN: Generate responsive image derivatives (AVIF/WebP at multiple widths)
|
|
93
100
|
await optimizeImagesGenerate({store});
|
|
94
101
|
|
|
@@ -224,6 +231,11 @@ class Build {
|
|
|
224
231
|
// user-defined `after` plugins so they see fingerprinted output.
|
|
225
232
|
await fingerprintAssets();
|
|
226
233
|
|
|
234
|
+
// PLUGIN: Prefix root-relative URLs in built HTML with `basePath`
|
|
235
|
+
// (sub-path hosting, e.g. GitHub Pages project sites). Runs after every
|
|
236
|
+
// built-in post-loop plugin so they all work with plain root paths.
|
|
237
|
+
await applyBasePath();
|
|
238
|
+
|
|
227
239
|
// CUSTOM PLUGINS: Run custom user plugins after file loop
|
|
228
240
|
await customPlugins({store, data, plugins: plugins.after, log: 'After' });
|
|
229
241
|
|
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @file apply-base-path.js
|
|
3
|
+
* @description Prefix root-relative URLs in built HTML with `basePath`.
|
|
4
|
+
*
|
|
5
|
+
* For sites served from a sub-path, e.g. a GitHub Pages project site at
|
|
6
|
+
* https://user.github.io/repo/. Authors keep writing root-relative URLs
|
|
7
|
+
* (`/docs/`, `/assets/css/site.css`) as if the site were at "/"; this
|
|
8
|
+
* post-pass rewrites them to `/repo/docs/`, `/repo/assets/css/site.css`.
|
|
9
|
+
*
|
|
10
|
+
* Runs once over the served root after every other built-in post-loop
|
|
11
|
+
* plugin (fragments, formats, sitemap, bundles, fingerprinting), so all of
|
|
12
|
+
* them keep working with plain root-relative paths. Skipped in
|
|
13
|
+
* development so `cook dev` still serves the site at "/".
|
|
14
|
+
*
|
|
15
|
+
* Rewritten:
|
|
16
|
+
* - href, src, action, formaction, poster, data (object) on any element
|
|
17
|
+
* - every candidate in srcset
|
|
18
|
+
* - url(/...) in style attributes and <style> blocks
|
|
19
|
+
* - keys and values of <script type="importmap"> imports and scopes
|
|
20
|
+
* Left alone:
|
|
21
|
+
* - relative, absolute (https:, mailto:, data:...) and protocol-relative (//) URLs
|
|
22
|
+
* - URLs already under basePath (the pass is idempotent)
|
|
23
|
+
* - text content (code samples showing href="/..." stay as written)
|
|
24
|
+
* - CSS/JS files, sitemap.xml, md/, api/ JSON and llms*.txt. Absolute
|
|
25
|
+
* URLs there come from `sitemap.url` / `data.siteUrl`, so include the
|
|
26
|
+
* base path in those values (https://user.github.io/repo).
|
|
27
|
+
*/
|
|
28
|
+
|
|
29
|
+
// IMPORTS
|
|
30
|
+
// -----------------------------
|
|
31
|
+
import { promises as fs } from 'node:fs';
|
|
32
|
+
import Logger from '../utils/logger/logger.js';
|
|
33
|
+
import Util from '../utils/util/util.js';
|
|
34
|
+
import { siteRootDir } from '../utils/site-root/site-root.js';
|
|
35
|
+
|
|
36
|
+
// Config
|
|
37
|
+
import { basePath as basePathConfig, distPath, siteRoot } from '../utils/config/config.js';
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
// ============================================================================
|
|
41
|
+
// Pure helpers (exported for unit testing)
|
|
42
|
+
// ============================================================================
|
|
43
|
+
|
|
44
|
+
const URL_ATTRS = ['href', 'src', 'action', 'formaction', 'poster', 'data'];
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* Normalize a basePath config value: '' | '/' | 'repo' | '/repo/' → '' | '/repo'
|
|
48
|
+
* @param {string} [basePath]
|
|
49
|
+
* @returns {string}
|
|
50
|
+
*/
|
|
51
|
+
export function normalizeBasePath(basePath) {
|
|
52
|
+
const trimmed = String(basePath || '').trim().replace(/^\/+|\/+$/g, '');
|
|
53
|
+
return trimmed ? `/${trimmed}` : '';
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* Prefix a single URL when it is root-relative and not already under basePath.
|
|
58
|
+
* @param {string} url
|
|
59
|
+
* @param {string} base - Normalized base ('/repo')
|
|
60
|
+
* @returns {string}
|
|
61
|
+
*/
|
|
62
|
+
export function prefixUrl(url, base) {
|
|
63
|
+
if (!base || typeof url !== 'string') return url;
|
|
64
|
+
// Root-relative only: "/x", not "//cdn", not "x", not "https://"
|
|
65
|
+
if (!url.startsWith('/') || url.startsWith('//')) return url;
|
|
66
|
+
// Already prefixed: "/repo", "/repo/", "/repo/x", "/repo?q", "/repo#h"
|
|
67
|
+
if (url.startsWith(base) && (url.length === base.length || /^[/?#]/.test(url[base.length]))) return url;
|
|
68
|
+
return `${base}${url}`;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/**
|
|
72
|
+
* Prefix every candidate URL in a srcset value.
|
|
73
|
+
* @param {string} srcset - e.g. "/a-320.webp 320w, /a-640.webp 640w"
|
|
74
|
+
* @param {string} base
|
|
75
|
+
* @returns {string}
|
|
76
|
+
*/
|
|
77
|
+
export function prefixSrcset(srcset, base) {
|
|
78
|
+
return srcset
|
|
79
|
+
.split(',')
|
|
80
|
+
.map(candidate => candidate.replace(/^(\s*)(\S+)/, (m, ws, url) => `${ws}${prefixUrl(url, base)}`))
|
|
81
|
+
.join(',');
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/**
|
|
85
|
+
* Prefix root-relative url(...) references in CSS text.
|
|
86
|
+
* @param {string} css
|
|
87
|
+
* @param {string} base
|
|
88
|
+
* @returns {string}
|
|
89
|
+
*/
|
|
90
|
+
export function prefixCssUrls(css, base) {
|
|
91
|
+
return css.replace(/url\(\s*(['"]?)(\/[^'")\s]*)\1\s*\)/g,
|
|
92
|
+
(m, quote, url) => `url(${quote}${prefixUrl(url, base)}${quote})`);
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/**
|
|
96
|
+
* Prefix an import map's specifier keys and address values.
|
|
97
|
+
* @param {string} json - Import map JSON text
|
|
98
|
+
* @param {string} base
|
|
99
|
+
* @returns {string} Rewritten JSON, or the input unchanged if it does not parse
|
|
100
|
+
*/
|
|
101
|
+
export function prefixImportMap(json, base) {
|
|
102
|
+
let map;
|
|
103
|
+
try { map = JSON.parse(json); } catch { return json; }
|
|
104
|
+
const remap = (obj) => Object.fromEntries(
|
|
105
|
+
Object.entries(obj || {}).map(([k, v]) => [prefixUrl(k, base), prefixUrl(v, base)])
|
|
106
|
+
);
|
|
107
|
+
if (map.imports) map.imports = remap(map.imports);
|
|
108
|
+
if (map.scopes) {
|
|
109
|
+
map.scopes = Object.fromEntries(
|
|
110
|
+
Object.entries(map.scopes).map(([scope, entries]) => [prefixUrl(scope, base), remap(entries)])
|
|
111
|
+
);
|
|
112
|
+
}
|
|
113
|
+
return JSON.stringify(map);
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/**
|
|
117
|
+
* Rewrite root-relative URLs in an HTML document or fragment.
|
|
118
|
+
* @param {string} html
|
|
119
|
+
* @param {string} basePath - Raw or normalized base path
|
|
120
|
+
* @returns {{ html: string, rewrites: number }} Input returned untouched when nothing changed
|
|
121
|
+
*/
|
|
122
|
+
export function rewriteBasePath(html, basePath) {
|
|
123
|
+
const base = normalizeBasePath(basePath);
|
|
124
|
+
if (!base) return { html, rewrites: 0 };
|
|
125
|
+
|
|
126
|
+
const dom = Util.jsdom.dom({ src: html });
|
|
127
|
+
const document = dom.window.document;
|
|
128
|
+
let rewrites = 0;
|
|
129
|
+
|
|
130
|
+
const set = (el, attr, next) => {
|
|
131
|
+
if (next !== el.getAttribute(attr)) {
|
|
132
|
+
el.setAttribute(attr, next);
|
|
133
|
+
rewrites += 1;
|
|
134
|
+
}
|
|
135
|
+
};
|
|
136
|
+
|
|
137
|
+
for (const attr of URL_ATTRS) {
|
|
138
|
+
document.querySelectorAll(`[${attr}]`).forEach(el => set(el, attr, prefixUrl(el.getAttribute(attr), base)));
|
|
139
|
+
}
|
|
140
|
+
document.querySelectorAll('[srcset]').forEach(el => set(el, 'srcset', prefixSrcset(el.getAttribute('srcset'), base)));
|
|
141
|
+
document.querySelectorAll('[style]').forEach(el => set(el, 'style', prefixCssUrls(el.getAttribute('style'), base)));
|
|
142
|
+
|
|
143
|
+
document.querySelectorAll('style').forEach(el => {
|
|
144
|
+
const next = prefixCssUrls(el.textContent, base);
|
|
145
|
+
if (next !== el.textContent) { el.textContent = next; rewrites += 1; }
|
|
146
|
+
});
|
|
147
|
+
document.querySelectorAll('script[type="importmap"]').forEach(el => {
|
|
148
|
+
const next = prefixImportMap(el.textContent, base);
|
|
149
|
+
if (next !== el.textContent) { el.textContent = next; rewrites += 1; }
|
|
150
|
+
});
|
|
151
|
+
|
|
152
|
+
if (rewrites === 0) return { html, rewrites: 0 };
|
|
153
|
+
return { html: Util.setSrc({ dom }), rewrites };
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
// ============================================================================
|
|
158
|
+
// Plugin
|
|
159
|
+
// ============================================================================
|
|
160
|
+
|
|
161
|
+
class ApplyBasePath {
|
|
162
|
+
constructor(opts = {}) {
|
|
163
|
+
// Optional per-call overrides (used by tests and custom pipelines)
|
|
164
|
+
this.basePath = normalizeBasePath(opts.basePath ?? basePathConfig);
|
|
165
|
+
this.distPath = opts.distPath || distPath;
|
|
166
|
+
this.siteRoot = opts.siteRoot ?? siteRoot;
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
async init() {
|
|
170
|
+
if (!this.basePath) return;
|
|
171
|
+
// `cook dev` serves dist at "/": prefixed links would 404 locally
|
|
172
|
+
if (process.env.NODE_ENV === 'development') return;
|
|
173
|
+
|
|
174
|
+
Logger.persist.header(`\nApply basePath ${this.basePath}`);
|
|
175
|
+
|
|
176
|
+
const rootDir = siteRootDir(this.distPath, this.siteRoot);
|
|
177
|
+
const htmlFiles = (Util.getPaths(rootDir, rootDir, []) || []).filter(p => p.endsWith('.html'));
|
|
178
|
+
|
|
179
|
+
let files = 0;
|
|
180
|
+
let total = 0;
|
|
181
|
+
for (const htmlPath of htmlFiles) {
|
|
182
|
+
const original = await fs.readFile(htmlPath, 'utf-8');
|
|
183
|
+
const { html, rewrites } = rewriteBasePath(original, this.basePath);
|
|
184
|
+
if (rewrites > 0) {
|
|
185
|
+
await fs.writeFile(htmlPath, html, 'utf-8');
|
|
186
|
+
files += 1;
|
|
187
|
+
total += rewrites;
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
Logger.persist.success(`Prefixed ${total} URL(s) in ${files} HTML file(s)`);
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
|
|
196
|
+
// EXPORT WRAPPER
|
|
197
|
+
// -----------------------------
|
|
198
|
+
export default async (opts) => {
|
|
199
|
+
const plugin = new ApplyBasePath(opts);
|
|
200
|
+
await plugin.init();
|
|
201
|
+
};
|
|
@@ -0,0 +1,211 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @file html-collections.js
|
|
3
|
+
* @description HTML pages with YAML front matter join collections, the way
|
|
4
|
+
* markdown files do. Opt-in: `collections: { html: true }`.
|
|
5
|
+
*
|
|
6
|
+
* Runs before the file loop (right after markdown) so `data-repeat`,
|
|
7
|
+
* the Atom feed and the JSON formats see every page:
|
|
8
|
+
*
|
|
9
|
+
* src/posts/hello.html ---
|
|
10
|
+
* title: Hello
|
|
11
|
+
* date: 2026-11-01
|
|
12
|
+
* ---
|
|
13
|
+
* <p>...</p>
|
|
14
|
+
*
|
|
15
|
+
* → collections.posts = [{ title: 'Hello', url: '/posts/hello/', slug: 'hello', date: '2026-11-01', ... }]
|
|
16
|
+
*
|
|
17
|
+
* Rules (match markdown collections and the built output):
|
|
18
|
+
* - collection = first folder under the served root (srcPath, or
|
|
19
|
+
* srcPath/<siteRoot>); files at the root or outside it join none
|
|
20
|
+
* - only files that start with `---` front matter; `draft: true` is skipped
|
|
21
|
+
* - buildOnlyPaths folders and excludePaths (tested on the dist path) skipped
|
|
22
|
+
* - URL follows convertPageToDirectory (posts/a.html → /posts/a/)
|
|
23
|
+
* - newest date first, undated last; merged with markdown collections
|
|
24
|
+
*/
|
|
25
|
+
|
|
26
|
+
// IMPORTS
|
|
27
|
+
// -----------------------------
|
|
28
|
+
import chalk from 'chalk';
|
|
29
|
+
import { promises as fs } from 'node:fs';
|
|
30
|
+
import { existsSync } from 'node:fs';
|
|
31
|
+
import path from 'node:path';
|
|
32
|
+
import matter from 'gray-matter';
|
|
33
|
+
import Logger from '../utils/logger/logger.js';
|
|
34
|
+
import Util from '../utils/util/util.js';
|
|
35
|
+
import { addToCollection, sortCollections, toCollectionItem } from '../utils/collections/collections.js';
|
|
36
|
+
import { normalizeSiteRoot } from '../utils/site-root/site-root.js';
|
|
37
|
+
|
|
38
|
+
// Config
|
|
39
|
+
import {
|
|
40
|
+
buildOnlyPaths as buildOnlyPathsConfig,
|
|
41
|
+
collections as collectionsConfig,
|
|
42
|
+
convertPageToDirectory,
|
|
43
|
+
distPath as distPathConfig,
|
|
44
|
+
excludePaths as excludePathsConfig,
|
|
45
|
+
siteRoot as siteRootConfig,
|
|
46
|
+
srcPath as srcPathConfig,
|
|
47
|
+
} from '../utils/config/config.js';
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
// ============================================================================
|
|
51
|
+
// Pure helpers (exported for unit testing)
|
|
52
|
+
// ============================================================================
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* Path of a file relative to the served root, or null when outside it.
|
|
56
|
+
* @param {string} relPath - Relative to srcPath, e.g. 'pages/posts/a.html'
|
|
57
|
+
* @param {string} [siteRoot]
|
|
58
|
+
* @returns {string|null} e.g. 'posts/a.html'
|
|
59
|
+
*/
|
|
60
|
+
function servedRelPath(relPath, siteRoot) {
|
|
61
|
+
const root = normalizeSiteRoot(siteRoot);
|
|
62
|
+
if (!root) return relPath;
|
|
63
|
+
return relPath.startsWith(`${root}/`) ? relPath.slice(root.length + 1) : null;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* Collection name for an HTML page: its first folder under the served root.
|
|
68
|
+
* @param {string} relPath - Relative to srcPath, e.g. 'posts/a.html'
|
|
69
|
+
* @param {string} [siteRoot]
|
|
70
|
+
* @returns {string|null}
|
|
71
|
+
*/
|
|
72
|
+
export function htmlCollectionName(relPath, siteRoot) {
|
|
73
|
+
const served = servedRelPath(relPath, siteRoot);
|
|
74
|
+
if (!served) return null;
|
|
75
|
+
const parts = served.split('/');
|
|
76
|
+
return parts.length > 1 ? parts[0] : null;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/**
|
|
80
|
+
* Visitor URL of an HTML page once built.
|
|
81
|
+
* @param {string} relPath - Relative to srcPath
|
|
82
|
+
* @param {Object} opts
|
|
83
|
+
* @param {string} [opts.siteRoot]
|
|
84
|
+
* @param {boolean} [opts.convertDisabled] - convertPageToDirectory.disabled
|
|
85
|
+
* @param {boolean} [opts.convertExcluded] - Page matches convertPageToDirectory.excludePaths
|
|
86
|
+
* @returns {string|null}
|
|
87
|
+
*/
|
|
88
|
+
export function htmlPageUrl(relPath, { siteRoot, convertDisabled, convertExcluded } = {}) {
|
|
89
|
+
const served = servedRelPath(relPath, siteRoot);
|
|
90
|
+
if (served === null) return null;
|
|
91
|
+
let url = `/${served}`;
|
|
92
|
+
if (/(^|\/)index\.html$/.test(served)) return url.replace(/index\.html$/, '');
|
|
93
|
+
if (convertDisabled || convertExcluded) return url;
|
|
94
|
+
return url.replace(/\.html$/, '/');
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/**
|
|
98
|
+
* Collection page data for an HTML page (same shape as markdown pages).
|
|
99
|
+
* @param {string} relPath - Relative to srcPath
|
|
100
|
+
* @param {Object} frontMatter - Parsed YAML
|
|
101
|
+
* @param {Object} opts - Same as htmlPageUrl
|
|
102
|
+
* @returns {Object}
|
|
103
|
+
*/
|
|
104
|
+
export function htmlPageData(relPath, frontMatter, opts = {}) {
|
|
105
|
+
const base = path.basename(relPath, '.html');
|
|
106
|
+
const slug = base === 'index' ? path.basename(path.dirname(relPath)) : base;
|
|
107
|
+
const rawDate = frontMatter.date;
|
|
108
|
+
const parsed = rawDate ? new Date(rawDate) : null;
|
|
109
|
+
const valid = parsed && !isNaN(parsed);
|
|
110
|
+
return {
|
|
111
|
+
...frontMatter,
|
|
112
|
+
title: frontMatter.title || Util.convertToCapSpaces(slug, 'kebab'),
|
|
113
|
+
url: htmlPageUrl(relPath, opts),
|
|
114
|
+
slug,
|
|
115
|
+
collection: htmlCollectionName(relPath, opts.siteRoot),
|
|
116
|
+
date: templateDate(rawDate),
|
|
117
|
+
// Parsed Date is only for sorting
|
|
118
|
+
_dateSort: valid ? parsed : null,
|
|
119
|
+
};
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
/**
|
|
123
|
+
* Date string for templates, on the calendar day the author wrote.
|
|
124
|
+
* - YAML dates (gray-matter gives a UTC-midnight Date) → YYYY-MM-DD
|
|
125
|
+
* - Strings starting YYYY-MM-DD keep that day; converting through UTC
|
|
126
|
+
* would move "2026-11-01T23:30:00-05:00" to 2026-11-02
|
|
127
|
+
* - Any other string is kept as written, like markdown pages
|
|
128
|
+
* @param {Date|string|undefined} rawDate
|
|
129
|
+
* @returns {string|null}
|
|
130
|
+
*/
|
|
131
|
+
function templateDate(rawDate) {
|
|
132
|
+
if (!rawDate) return null;
|
|
133
|
+
if (rawDate instanceof Date) return isNaN(rawDate) ? null : rawDate.toISOString().split('T')[0];
|
|
134
|
+
const str = String(rawDate);
|
|
135
|
+
const ymd = str.match(/^\d{4}-\d{2}-\d{2}/);
|
|
136
|
+
return ymd ? ymd[0] : str;
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
// ============================================================================
|
|
141
|
+
// Plugin
|
|
142
|
+
// ============================================================================
|
|
143
|
+
|
|
144
|
+
/**
|
|
145
|
+
* @param {Object} opts
|
|
146
|
+
* @param {Object} opts.store - Build store; collections are merged into store.collections
|
|
147
|
+
* @param {Object} opts.data - User data; data.collections is set
|
|
148
|
+
* @param {string} [opts.srcPath] - Overrides config (tests, custom pipelines)
|
|
149
|
+
* @param {string} [opts.distPath]
|
|
150
|
+
* @param {string} [opts.siteRoot]
|
|
151
|
+
* @param {boolean} [opts.enabled] - Defaults to config `collections.html`
|
|
152
|
+
* @param {string[]} [opts.buildOnlyPaths]
|
|
153
|
+
* @param {Array<RegExp|string>} [opts.excludePaths]
|
|
154
|
+
*/
|
|
155
|
+
export default async function htmlCollections({
|
|
156
|
+
store,
|
|
157
|
+
data,
|
|
158
|
+
srcPath = srcPathConfig,
|
|
159
|
+
distPath = distPathConfig,
|
|
160
|
+
siteRoot = siteRootConfig,
|
|
161
|
+
enabled = collectionsConfig && collectionsConfig.html,
|
|
162
|
+
buildOnlyPaths = buildOnlyPathsConfig || [],
|
|
163
|
+
excludePaths = excludePathsConfig || [],
|
|
164
|
+
}) {
|
|
165
|
+
if (!enabled || !existsSync(srcPath)) return;
|
|
166
|
+
|
|
167
|
+
const excludes = excludePaths.map(p => (p instanceof RegExp ? p : new RegExp(p)));
|
|
168
|
+
const convertExcludes = (convertPageToDirectory && convertPageToDirectory.excludePaths) || [];
|
|
169
|
+
const convertDisabled = !!(convertPageToDirectory && convertPageToDirectory.disabled);
|
|
170
|
+
|
|
171
|
+
const files = (Util.getPaths(srcPath, srcPath, []) || []).filter(f => f.endsWith('.html'));
|
|
172
|
+
if (!store.collections) store.collections = {};
|
|
173
|
+
|
|
174
|
+
let collected = 0;
|
|
175
|
+
for (const file of files) {
|
|
176
|
+
const relPath = path.relative(srcPath, file).split(path.sep).join('/');
|
|
177
|
+
if (buildOnlyPaths.some(dir => relPath === dir || relPath.startsWith(`${dir}/`))) continue;
|
|
178
|
+
|
|
179
|
+
const distFile = `${distPath}/${relPath}`;
|
|
180
|
+
if (excludes.some(r => r.test(distFile))) continue;
|
|
181
|
+
|
|
182
|
+
const collection = htmlCollectionName(relPath, siteRoot);
|
|
183
|
+
if (!collection) continue;
|
|
184
|
+
|
|
185
|
+
const src = await fs.readFile(file, 'utf-8');
|
|
186
|
+
if (!src.startsWith('---')) continue;
|
|
187
|
+
|
|
188
|
+
let frontMatter;
|
|
189
|
+
try {
|
|
190
|
+
({ data: frontMatter } = matter(src));
|
|
191
|
+
} catch (err) {
|
|
192
|
+
console.warn(chalk.yellow(`\n[html-collections] ${relPath}: invalid front matter (skipped from collections)`));
|
|
193
|
+
console.warn(` ${err && err.message ? err.message : err}`);
|
|
194
|
+
continue;
|
|
195
|
+
}
|
|
196
|
+
if (!frontMatter || !Object.keys(frontMatter).length || frontMatter.draft === true) continue;
|
|
197
|
+
|
|
198
|
+
const convertExcluded = convertExcludes.some(str => distFile.includes(str));
|
|
199
|
+
const page = htmlPageData(relPath, frontMatter, { siteRoot, convertDisabled, convertExcluded });
|
|
200
|
+
addToCollection(store.collections, collection, toCollectionItem(page));
|
|
201
|
+
collected += 1;
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
sortCollections(store.collections);
|
|
205
|
+
data.collections = store.collections;
|
|
206
|
+
|
|
207
|
+
if (collected) {
|
|
208
|
+
Logger.persist.header('\nHTML Collections');
|
|
209
|
+
Logger.persist.success(`Collected ${collected} HTML page(s)`);
|
|
210
|
+
}
|
|
211
|
+
}
|
|
@@ -16,6 +16,7 @@ import Util from '../utils/util/util.js';
|
|
|
16
16
|
import { renderTemplate } from '../utils/interpolate/interpolate.js';
|
|
17
17
|
|
|
18
18
|
// Config
|
|
19
|
+
import { addToCollection, sortCollections, toCollectionItem } from '../utils/collections/collections.js';
|
|
19
20
|
import { distPath, srcPath, markdown as markdownConfig } from '../utils/config/config.js';
|
|
20
21
|
|
|
21
22
|
|
|
@@ -323,37 +324,13 @@ ${pageData.content}
|
|
|
323
324
|
|
|
324
325
|
for (const page of this.processedFiles) {
|
|
325
326
|
if (page.collection) {
|
|
326
|
-
// Initialize collection array if needed
|
|
327
|
-
if (!this.store.collections[page.collection]) {
|
|
328
|
-
this.store.collections[page.collection] = [];
|
|
329
|
-
}
|
|
330
|
-
|
|
331
327
|
// Add page to collection (without full content to save memory)
|
|
332
|
-
this.store.collections
|
|
333
|
-
title: page.title,
|
|
334
|
-
url: page.url,
|
|
335
|
-
slug: page.slug,
|
|
336
|
-
date: page.date,
|
|
337
|
-
description: page.description,
|
|
338
|
-
// Include any other front matter fields except content
|
|
339
|
-
...Object.fromEntries(
|
|
340
|
-
Object.entries(page).filter(([key]) =>
|
|
341
|
-
!['content', 'sourcePath', 'outputPath', 'collection'].includes(key)
|
|
342
|
-
)
|
|
343
|
-
),
|
|
344
|
-
});
|
|
328
|
+
addToCollection(this.store.collections, page.collection, toCollectionItem(page));
|
|
345
329
|
}
|
|
346
330
|
}
|
|
347
331
|
|
|
348
332
|
// Sort collections by date (newest first)
|
|
349
|
-
|
|
350
|
-
this.store.collections[collectionName].sort((a, b) => {
|
|
351
|
-
if (!a._dateSort && !b._dateSort) return 0;
|
|
352
|
-
if (!a._dateSort) return 1;
|
|
353
|
-
if (!b._dateSort) return -1;
|
|
354
|
-
return b._dateSort - a._dateSort;
|
|
355
|
-
});
|
|
356
|
-
}
|
|
333
|
+
sortCollections(this.store.collections);
|
|
357
334
|
}
|
|
358
335
|
|
|
359
336
|
// EXPORT WRAPPER
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @file collections.js
|
|
3
|
+
* @description Shared helpers for building collections (markdown and HTML
|
|
4
|
+
* pages grouped by folder, exposed as `collections.<name>` in templates).
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
/** Page keys used only during the build, never exposed to templates. */
|
|
8
|
+
const BUILD_ONLY_KEYS = ['content', 'sourcePath', 'outputPath', 'collection'];
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* Shape a page into a collection item: title/url/slug/date/description
|
|
12
|
+
* first, then every other front matter field, minus build-only keys
|
|
13
|
+
* (`content` is dropped to save memory).
|
|
14
|
+
* @param {Object} page
|
|
15
|
+
* @returns {Object}
|
|
16
|
+
*/
|
|
17
|
+
export function toCollectionItem(page) {
|
|
18
|
+
return {
|
|
19
|
+
title: page.title,
|
|
20
|
+
url: page.url,
|
|
21
|
+
slug: page.slug,
|
|
22
|
+
date: page.date,
|
|
23
|
+
description: page.description,
|
|
24
|
+
...Object.fromEntries(Object.entries(page).filter(([key]) => !BUILD_ONLY_KEYS.includes(key))),
|
|
25
|
+
};
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* Append an item to a named collection, creating it if needed.
|
|
30
|
+
* @param {Object<string, Object[]>} collections
|
|
31
|
+
* @param {string} name
|
|
32
|
+
* @param {Object} item
|
|
33
|
+
*/
|
|
34
|
+
export function addToCollection(collections, name, item) {
|
|
35
|
+
if (!collections[name]) collections[name] = [];
|
|
36
|
+
collections[name].push(item);
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* Sort every collection in place: newest `_dateSort` first, undated items
|
|
41
|
+
* last, original order kept for ties (Array#sort is stable).
|
|
42
|
+
* @param {Object<string, Object[]>} collections
|
|
43
|
+
*/
|
|
44
|
+
export function sortCollections(collections) {
|
|
45
|
+
for (const items of Object.values(collections)) {
|
|
46
|
+
if (!Array.isArray(items)) continue;
|
|
47
|
+
items.sort((a, b) => {
|
|
48
|
+
if (!a._dateSort && !b._dateSort) return 0;
|
|
49
|
+
if (!a._dateSort) return 1;
|
|
50
|
+
if (!b._dateSort) return -1;
|
|
51
|
+
return b._dateSort - a._dateSort;
|
|
52
|
+
});
|
|
53
|
+
}
|
|
54
|
+
}
|
|
@@ -43,6 +43,14 @@ const defaultConfig = {
|
|
|
43
43
|
// `siteRoot: 'pages'`. Active links, the sitemap and the post-build page
|
|
44
44
|
// snapshot then use the URLs visitors actually see (/docs/, not /pages/docs/).
|
|
45
45
|
siteRoot: '',
|
|
46
|
+
// URL path the site is served under ('' = domain root). Set it for
|
|
47
|
+
// sub-path hosting such as a GitHub Pages project site
|
|
48
|
+
// (https://user.github.io/repo/ → `basePath: '/repo'`). Write links as
|
|
49
|
+
// usual ('/docs/'); production builds prefix root-relative URLs in the
|
|
50
|
+
// built HTML ('/repo/docs/'). `cook dev` ignores it and serves at "/".
|
|
51
|
+
// Include the base path in absolute URLs you configure yourself:
|
|
52
|
+
// `sitemap.url` and `data.siteUrl` ('https://user.github.io/repo').
|
|
53
|
+
basePath: '',
|
|
46
54
|
// The URL domain to use for the `sitemap.xml` entries.
|
|
47
55
|
// Set `sitemap.url` to enable: `sitemap.xml` is written to the site root
|
|
48
56
|
// (`distPath`, or `distPath/siteRoot`). Left empty, no sitemap is written.
|
|
@@ -96,6 +104,11 @@ const defaultConfig = {
|
|
|
96
104
|
// Markdown: Convert .md files to HTML with front matter support
|
|
97
105
|
// Markdown files in /src are converted to HTML in /dist
|
|
98
106
|
// Front matter (YAML between ---) becomes template variables
|
|
107
|
+
// Collections from HTML pages: pages that start with YAML front matter
|
|
108
|
+
// join `collections.<first folder>` like markdown files do (opt-in).
|
|
109
|
+
collections: {
|
|
110
|
+
html: false,
|
|
111
|
+
},
|
|
99
112
|
markdown: {
|
|
100
113
|
// Default layout template to wrap content (null = basic HTML wrapper)
|
|
101
114
|
layout: null,
|
|
@@ -297,8 +310,10 @@ export default config;
|
|
|
297
310
|
export const {
|
|
298
311
|
activeLink,
|
|
299
312
|
autoComponents,
|
|
313
|
+
basePath,
|
|
300
314
|
buildOnlyPaths,
|
|
301
315
|
bundle,
|
|
316
|
+
collections,
|
|
302
317
|
components,
|
|
303
318
|
convertPageToDirectory,
|
|
304
319
|
distPath,
|