cook-ssg 2.4.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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "cook-ssg",
3
- "version": "2.4.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
@@ -25,6 +25,7 @@ import generateSitemap from './plugins/generate-sitemap-xml.js';
25
25
  import htmlCollections from './plugins/html-collections.js';
26
26
  import minifySrc from './plugins/minify-src.js';
27
27
  import { optimizeImagesGenerate, optimizeImagesRewrite } from './plugins/optimize-images.js';
28
+ import { packageComponentsCopy, packageComponentsInject } from './plugins/package-components.js';
28
29
  import processMarkdown from './plugins/process-markdown.js';
29
30
  import repeatCollection from './plugins/repeat-collection.js';
30
31
  import replaceComponents from './plugins/replace-components.js';
@@ -99,6 +100,9 @@ class Build {
99
100
  // PLUGIN: Generate responsive image derivatives (AVIF/WebP at multiple widths)
100
101
  await optimizeImagesGenerate({store});
101
102
 
103
+ // PLUGIN: Copy npm web-component packages (with a custom-elements.json) into dist
104
+ await packageComponentsCopy({store});
105
+
102
106
  // CUSTOM PLUGINS: Run custom user plugins before file loop
103
107
  await customPlugins({store, data, plugins: plugins.before, log: 'Before' });
104
108
 
@@ -178,6 +182,9 @@ class Build {
178
182
  // PLUGIN: Auto-detect custom elements and manage VB JS loading
179
183
  await autoComponents({file, store, allowType: ['.html']});
180
184
 
185
+ // PLUGIN: Add a module script for npm component packages used on the page
186
+ await packageComponentsInject({file, store, allowType: ['.html']});
187
+
181
188
  // PLUGIN: Pre-render Declarative Shadow DOM for web components
182
189
  await declarativeShadowDom({file, store, allowType: ['.html']});
183
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,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;
@@ -133,6 +133,15 @@ const defaultConfig = {
133
133
  bundlePattern: /vanilla-breeze[^"']*\.js/,
134
134
  },
135
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
+
136
145
  // Declarative Shadow DOM: Pre-render shadow DOM content for web components
137
146
  // Requires a DSD manifest (JSON mapping tag → shadow DOM HTML)
138
147
  // and VB components with: if (!this.shadowRoot) this.attachShadow({ mode: 'open' })
@@ -328,6 +337,7 @@ export const {
328
337
  inlineAttr,
329
338
  markdown,
330
339
  minifyHtmlConfigCustom,
340
+ packageComponents,
331
341
  plugins,
332
342
  pluginPath,
333
343
  repeat,