cook-ssg 2.3.0 → 2.5.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 CHANGED
@@ -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
@@ -207,6 +208,10 @@ export default {
207
208
  // absolute URLs you set yourself (sitemap.url, data.siteUrl).
208
209
  basePath: '',
209
210
 
211
+ // HTML pages that start with YAML front matter join collections.<folder>
212
+ // like markdown files (default: false)
213
+ collections: { html: false },
214
+
210
215
  // Sitemap: set url to enable (default: '' = no sitemap.xml)
211
216
  sitemap: {
212
217
  url: 'https://www.yoursite.com',
@@ -417,6 +422,7 @@ Generate repeated elements from arrays or collections. Perfect for blog listings
417
422
  **Data Sources:**
418
423
  - `collections.blog` - From markdown files in `/src/blog/`
419
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
420
426
  - `items` - From `/config/data.js`
421
427
  - Any array in your data configuration
422
428
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "cook-ssg",
3
- "version": "2.3.0",
3
+ "version": "2.5.0",
4
4
  "description": "Cook your static pages into a beautifully performing site. Static site generation the web platform way.",
5
5
  "type": "module",
6
6
  "bin": {
package/scripts/build.js CHANGED
@@ -22,8 +22,10 @@ import fingerprintAssets from './plugins/fingerprint-assets.js';
22
22
  import generateFormats from './plugins/generate-formats.js';
23
23
  import generateFragments from './plugins/generate-fragments.js';
24
24
  import generateSitemap from './plugins/generate-sitemap-xml.js';
25
+ import htmlCollections from './plugins/html-collections.js';
25
26
  import minifySrc from './plugins/minify-src.js';
26
27
  import { optimizeImagesGenerate, optimizeImagesRewrite } from './plugins/optimize-images.js';
28
+ import { packageComponentsCopy, packageComponentsInject } from './plugins/package-components.js';
27
29
  import processMarkdown from './plugins/process-markdown.js';
28
30
  import repeatCollection from './plugins/repeat-collection.js';
29
31
  import replaceComponents from './plugins/replace-components.js';
@@ -90,9 +92,17 @@ class Build {
90
92
  // PLUGIN: Process markdown files (.md -> .html)
91
93
  await processMarkdown({store, data});
92
94
 
95
+ // PLUGIN: HTML pages with front matter join collections (opt-in:
96
+ // `collections: { html: true }`). Pre-loop so data-repeat and the feed
97
+ // see every page; merges with markdown collections.
98
+ await htmlCollections({store, data});
99
+
93
100
  // PLUGIN: Generate responsive image derivatives (AVIF/WebP at multiple widths)
94
101
  await optimizeImagesGenerate({store});
95
102
 
103
+ // PLUGIN: Copy npm web-component packages (with a custom-elements.json) into dist
104
+ await packageComponentsCopy({store});
105
+
96
106
  // CUSTOM PLUGINS: Run custom user plugins before file loop
97
107
  await customPlugins({store, data, plugins: plugins.before, log: 'Before' });
98
108
 
@@ -172,6 +182,9 @@ class Build {
172
182
  // PLUGIN: Auto-detect custom elements and manage VB JS loading
173
183
  await autoComponents({file, store, allowType: ['.html']});
174
184
 
185
+ // PLUGIN: Add a module script for npm component packages used on the page
186
+ await packageComponentsInject({file, store, allowType: ['.html']});
187
+
175
188
  // PLUGIN: Pre-render Declarative Shadow DOM for web components
176
189
  await declarativeShadowDom({file, store, allowType: ['.html']});
177
190
 
@@ -22,7 +22,8 @@ import Logger from '../utils/logger/logger.js';
22
22
  import Util from '../utils/util/util.js';
23
23
 
24
24
  // Config
25
- import { distPath, fingerprint as fingerprintConfig } from '../utils/config/config.js';
25
+ import { distPath, siteRoot, fingerprint as fingerprintConfig } from '../utils/config/config.js';
26
+ import { siteRootDir } from '../utils/site-root/site-root.js';
26
27
 
27
28
 
28
29
  // ============================================================================
@@ -140,6 +141,9 @@ class FingerprintAssets {
140
141
  constructor(opts = {}) {
141
142
  // Optional per-call overrides (used by tests and custom pipelines)
142
143
  this.distPath = opts.distPath || distPath;
144
+ this.siteRoot = opts.siteRoot ?? siteRoot;
145
+ // Web paths ("/assets/x.css") are relative to the folder served at "/"
146
+ this.rootDir = siteRootDir(this.distPath, this.siteRoot);
143
147
  this.config = {
144
148
  enabled: false,
145
149
  hashLength: 8,
@@ -168,7 +172,7 @@ class FingerprintAssets {
168
172
  const manifest = await this.fingerprintFiles(candidates);
169
173
 
170
174
  // Phase 2: Rewrite HTML references
171
- const htmlFiles = (Util.getPaths(this.distPath, this.distPath, []) || [])
175
+ const htmlFiles = (Util.getPaths(this.rootDir, this.rootDir, []) || [])
172
176
  .filter(p => p.endsWith('.html'));
173
177
  let totalRewrites = 0;
174
178
  for (const htmlPath of htmlFiles) {
@@ -181,7 +185,7 @@ class FingerprintAssets {
181
185
  }
182
186
 
183
187
  // Phase 3: Write manifest
184
- const manifestFsPath = path.join(this.distPath, this.config.manifestPath);
188
+ const manifestFsPath = path.join(this.rootDir, this.config.manifestPath);
185
189
  await fs.writeFile(manifestFsPath, JSON.stringify(manifest, null, 2), 'utf-8');
186
190
 
187
191
  Logger.persist.success(
@@ -194,7 +198,7 @@ class FingerprintAssets {
194
198
  * Returns absolute paths.
195
199
  */
196
200
  async findCandidates() {
197
- const all = Util.getPaths(this.distPath, this.distPath, []) || [];
201
+ const all = Util.getPaths(this.rootDir, this.rootDir, []) || [];
198
202
  const excludes = this.config.excludePaths.map(p => (p instanceof RegExp ? p : new RegExp(p)));
199
203
  return all.filter(p => {
200
204
  // Skip source maps in the candidate list — handled alongside their source.
@@ -279,13 +283,13 @@ class FingerprintAssets {
279
283
  }
280
284
 
281
285
  // Build manifest keys as web paths starting with `/`
282
- const relOriginal = '/' + path.relative(this.distPath, absPath).split(path.sep).join('/');
283
- const relNew = '/' + path.relative(this.distPath, newAbs).split(path.sep).join('/');
286
+ const relOriginal = '/' + path.relative(this.rootDir, absPath).split(path.sep).join('/');
287
+ const relNew = '/' + path.relative(this.rootDir, newAbs).split(path.sep).join('/');
284
288
  manifest[relOriginal] = relNew;
285
289
 
286
290
  if (mapNewName) {
287
- const relMapOriginal = '/' + path.relative(this.distPath, mapAbs).split(path.sep).join('/');
288
- const relMapNew = '/' + path.relative(this.distPath, path.join(dir, mapNewName)).split(path.sep).join('/');
291
+ const relMapOriginal = '/' + path.relative(this.rootDir, mapAbs).split(path.sep).join('/');
292
+ const relMapNew = '/' + path.relative(this.rootDir, path.join(dir, mapNewName)).split(path.sep).join('/');
289
293
  manifest[relMapOriginal] = relMapNew;
290
294
  }
291
295
  }
@@ -306,7 +310,7 @@ class FingerprintAssets {
306
310
  const clean = splitUrlSuffix(spec).path;
307
311
  if (clean.startsWith('/')) return clean;
308
312
  if (clean.startsWith('./') || clean.startsWith('../')) {
309
- const dirRel = path.dirname(path.relative(this.distPath, absPath));
313
+ const dirRel = path.dirname(path.relative(this.rootDir, absPath));
310
314
  const joined = path.normalize(path.join(dirRel, clean));
311
315
  return '/' + joined.split(path.sep).join('/');
312
316
  }
@@ -345,7 +349,7 @@ class FingerprintAssets {
345
349
  * @returns {string[]}
346
350
  */
347
351
  orderByDependencies(candidates, contents) {
348
- const keyOf = p => '/' + path.relative(this.distPath, p).split(path.sep).join('/');
352
+ const keyOf = p => '/' + path.relative(this.rootDir, p).split(path.sep).join('/');
349
353
  const byKey = new Map(candidates.map(p => [keyOf(p), p]));
350
354
 
351
355
  const deps = new Map();
@@ -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
+ }
@@ -0,0 +1,170 @@
1
+ /**
2
+ * @file package-components.js
3
+ * @description Load npm web-component packages per page.
4
+ *
5
+ * Dependencies in the project's package.json that ship a custom-elements.json
6
+ * manifest get their built files (the entry's whole directory) copied to
7
+ * `<dist>/<path>/<package name>/`. Each page that uses one of the package's
8
+ * tags gets one `<script type="module">` appended to `<head>`.
9
+ *
10
+ * packageComponentsCopy({ store }) once, pre-loop; fills store.packageComponentsMap
11
+ * packageComponentsInject(...) per page, after autoComponents
12
+ */
13
+
14
+ // IMPORTS
15
+ // -----------------------------
16
+ import chalk from 'chalk';
17
+ import fs from 'fs-extra';
18
+ import path from 'node:path';
19
+ import Util from '../utils/util/util.js';
20
+
21
+ // Config
22
+ import { distPath, siteRoot, packageComponents as packageComponentsConfig } from '../utils/config/config.js';
23
+
24
+ import { siteRootDir } from '../utils/site-root/site-root.js';
25
+
26
+
27
+ // HELPERS
28
+ // -----------------------------
29
+ const getConfig = () => ({
30
+ enabled: true,
31
+ exclude: ['vanilla-breeze', 'cook-ssg'],
32
+ path: 'assets/components',
33
+ ...packageComponentsConfig,
34
+ });
35
+
36
+ const readJson = async (file) => {
37
+ try {
38
+ return await fs.readJson(file);
39
+ } catch {
40
+ return null;
41
+ }
42
+ };
43
+
44
+ /**
45
+ * Resolve a package's entry file from its package.json
46
+ * @param {Object} pkg - Parsed package.json
47
+ * @returns {string|null} Entry path as written (e.g. './dist/x.js')
48
+ */
49
+ function resolveEntry(pkg) {
50
+ const root = pkg.exports && pkg.exports['.'];
51
+ const candidates = [
52
+ root && typeof root === 'object' ? root.import : null,
53
+ root && typeof root === 'object' ? root.default : null,
54
+ typeof root === 'string' ? root : null,
55
+ pkg.module,
56
+ pkg.main,
57
+ ];
58
+ return candidates.find(c => typeof c === 'string' && c) || null;
59
+ }
60
+
61
+ /**
62
+ * Collect every tagName declared in a custom-elements manifest
63
+ * @param {Object} manifest
64
+ * @returns {string[]}
65
+ */
66
+ function manifestTags(manifest) {
67
+ const tags = new Set();
68
+ for (const mod of manifest.modules || []) {
69
+ for (const decl of mod.declarations || []) {
70
+ if (decl.tagName) tags.add(decl.tagName);
71
+ }
72
+ }
73
+ return [...tags];
74
+ }
75
+
76
+
77
+ // COPY (ONCE, PRE-LOOP)
78
+ // -----------------------------
79
+ export async function packageComponentsCopy({ store, siteRoot: siteRootOpt }) {
80
+ const config = getConfig();
81
+ store.packageComponentsMap = {};
82
+ if (!config.enabled) return;
83
+
84
+ const cwd = process.cwd();
85
+ const rootPkg = await readJson(path.join(cwd, 'package.json'));
86
+ if (!rootPkg || !rootPkg.dependencies) return;
87
+
88
+ const names = Object.keys(rootPkg.dependencies).filter(n => !config.exclude.includes(n));
89
+ const urlBase = config.path.replace(/^\/+|\/+$/g, '');
90
+
91
+ for (const name of names) {
92
+ const pkgDir = path.join(cwd, 'node_modules', name);
93
+ const skip = (why) => console.log(chalk.gray(`[package-components] Skipping ${name}: ${why}`));
94
+
95
+ const pkg = await readJson(path.join(pkgDir, 'package.json'));
96
+ if (!pkg) { skip('not installed'); continue; }
97
+
98
+ const manifestFile = typeof pkg.customElements === 'string' ? pkg.customElements : 'custom-elements.json';
99
+ const manifest = await readJson(path.join(pkgDir, manifestFile));
100
+ if (!manifest) { skip('no custom-elements manifest'); continue; }
101
+
102
+ const entry = resolveEntry(pkg);
103
+ if (!entry) { skip('no entry point'); continue; }
104
+
105
+ const entryAbs = path.resolve(pkgDir, entry);
106
+ if (!(await fs.pathExists(entryAbs))) { skip('entry file missing'); continue; }
107
+
108
+ const entryDir = path.dirname(entryAbs);
109
+ // Never copy the whole package root's parent or anything outside the package
110
+ if (path.relative(pkgDir, entryDir).startsWith('..')) { skip('entry outside package'); continue; }
111
+
112
+ const target = path.join(cwd, siteRootDir(distPath, siteRootOpt ?? siteRoot), urlBase, name);
113
+ await fs.copy(entryDir, target);
114
+
115
+ const rel = path.basename(entryAbs);
116
+ const url = `/${urlBase}/${name}/${rel}`;
117
+ for (const tag of manifestTags(manifest)) {
118
+ store.packageComponentsMap[tag] = url;
119
+ }
120
+ }
121
+
122
+ const count = Object.keys(store.packageComponentsMap).length;
123
+ if (count) console.log(chalk.green(`[package-components] ${count} tag(s) mapped`));
124
+ }
125
+
126
+
127
+ // INJECT (PER PAGE)
128
+ // -----------------------------
129
+ class PackageComponents {
130
+ constructor({ file, store, allowType, disallowType }) {
131
+ this.opts = { file, allowType, disallowType };
132
+ this.file = file;
133
+ this.store = store;
134
+ }
135
+
136
+ async init() {
137
+ const map = this.store.packageComponentsMap;
138
+ if (!map || Object.keys(map).length === 0) return;
139
+ if (!Util.isAllowedType(this.opts)) return;
140
+
141
+ const dom = Util.fileDom(this.file);
142
+ const document = dom.window.document;
143
+ const head = document.querySelector('head');
144
+ if (!head) return;
145
+
146
+ const present = new Set(
147
+ [...document.querySelectorAll('script[src]')].map(s => s.getAttribute('src'))
148
+ );
149
+ const added = new Set();
150
+
151
+ for (const el of document.querySelectorAll('*')) {
152
+ const url = map[el.tagName.toLowerCase()];
153
+ if (!url || present.has(url) || added.has(url)) continue;
154
+ const script = document.createElement('script');
155
+ script.setAttribute('type', 'module');
156
+ script.setAttribute('src', url);
157
+ head.appendChild(script);
158
+ added.add(url);
159
+ }
160
+
161
+ if (added.size) Util.commitDom(this.file, dom);
162
+ }
163
+
164
+ static async export(opts) {
165
+ return new PackageComponents(opts).init();
166
+ }
167
+ }
168
+
169
+ export const packageComponentsInject = PackageComponents.export;
170
+ export default packageComponentsInject;
@@ -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[page.collection].push({
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
- for (const collectionName of Object.keys(this.store.collections)) {
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
+ }
@@ -104,6 +104,11 @@ const defaultConfig = {
104
104
  // Markdown: Convert .md files to HTML with front matter support
105
105
  // Markdown files in /src are converted to HTML in /dist
106
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
+ },
107
112
  markdown: {
108
113
  // Default layout template to wrap content (null = basic HTML wrapper)
109
114
  layout: null,
@@ -128,6 +133,15 @@ const defaultConfig = {
128
133
  bundlePattern: /vanilla-breeze[^"']*\.js/,
129
134
  },
130
135
 
136
+ // Package Components: npm web-component packages (dependencies shipping a
137
+ // custom-elements.json) are copied to dist/<path>/<name>/ and loaded per page
138
+ // by a module script, only on pages that use their tags.
139
+ packageComponents: {
140
+ enabled: true,
141
+ exclude: ['vanilla-breeze', 'cook-ssg'],
142
+ path: 'assets/components',
143
+ },
144
+
131
145
  // Declarative Shadow DOM: Pre-render shadow DOM content for web components
132
146
  // Requires a DSD manifest (JSON mapping tag → shadow DOM HTML)
133
147
  // and VB components with: if (!this.shadowRoot) this.attachShadow({ mode: 'open' })
@@ -308,6 +322,7 @@ export const {
308
322
  basePath,
309
323
  buildOnlyPaths,
310
324
  bundle,
325
+ collections,
311
326
  components,
312
327
  convertPageToDirectory,
313
328
  distPath,
@@ -322,6 +337,7 @@ export const {
322
337
  inlineAttr,
323
338
  markdown,
324
339
  minifyHtmlConfigCustom,
340
+ packageComponents,
325
341
  plugins,
326
342
  pluginPath,
327
343
  repeat,