cook-ssg 2.1.3 → 2.2.1

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.
Files changed (36) hide show
  1. package/README.md +48 -20
  2. package/package.json +4 -9
  3. package/scripts/build.js +91 -26
  4. package/scripts/dev.js +46 -16
  5. package/scripts/plugins/apply-template.js +8 -17
  6. package/scripts/plugins/auto-components.js +2 -2
  7. package/scripts/plugins/bundle.js +6 -3
  8. package/scripts/plugins/copy-src.js +1 -1
  9. package/scripts/plugins/create-dir-from-file.js +4 -2
  10. package/scripts/plugins/create-dist.js +1 -2
  11. package/scripts/plugins/custom-plugins.js +1 -1
  12. package/scripts/plugins/declarative-shadow-dom.js +2 -2
  13. package/scripts/plugins/escape-code-blocks.js +22 -1
  14. package/scripts/plugins/fingerprint-assets.js +133 -13
  15. package/scripts/plugins/generate-formats.js +49 -39
  16. package/scripts/plugins/generate-fragments.js +24 -14
  17. package/scripts/plugins/generate-sitemap-xml.js +38 -15
  18. package/scripts/plugins/minify-src.js +98 -72
  19. package/scripts/plugins/optimize-images.js +80 -26
  20. package/scripts/plugins/process-markdown.js +12 -25
  21. package/scripts/plugins/repeat-collection.js +70 -45
  22. package/scripts/plugins/replace-components.js +82 -60
  23. package/scripts/plugins/replace-external-link-protocol.js +16 -31
  24. package/scripts/plugins/replace-include.js +34 -19
  25. package/scripts/plugins/replace-inline.js +6 -3
  26. package/scripts/plugins/replace-template-strings.js +2 -50
  27. package/scripts/plugins/set-active-links.js +57 -26
  28. package/scripts/utils/config/config.js +29 -5
  29. package/scripts/utils/get-src/get-src.js +9 -45
  30. package/scripts/utils/interpolate/interpolate.js +83 -0
  31. package/scripts/utils/logger/logger.js +8 -3
  32. package/scripts/utils/site-pages/site-pages.js +37 -0
  33. package/scripts/utils/source-file/source-file.js +64 -0
  34. package/scripts/utils/user-data/user-data.js +45 -0
  35. package/scripts/utils/util/util.js +88 -46
  36. package/patches/jsdom-fetch-fix.js +0 -52
@@ -26,6 +26,9 @@ const jsdom = {
26
26
  baseUrl: 'https://localhost',
27
27
  dom: newDOM,
28
28
  frag: newFrag,
29
+ // Number of full-document parses performed (observable in tests to
30
+ // guard the parse-once model against regressions)
31
+ parseCount: 0,
29
32
  }
30
33
 
31
34
  // STATIC CONFIG
@@ -57,10 +60,13 @@ export {
57
60
  createDirectory,
58
61
  customError,
59
62
  customKill,
63
+ customWarn,
60
64
  deepClone,
61
65
  encodeTag,
62
66
  escapeUrlString,
63
67
  fakePromise,
68
+ fileDom,
69
+ commitDom,
64
70
  getFileName,
65
71
  getFileParts,
66
72
  getFilePath,
@@ -92,10 +98,13 @@ export default {
92
98
  createDirectory,
93
99
  customError,
94
100
  customKill,
101
+ customWarn,
95
102
  deepClone,
96
103
  encodeTag,
97
104
  escapeUrlString,
98
105
  fakePromise,
106
+ fileDom,
107
+ commitDom,
99
108
  getFileName,
100
109
  getFileParts,
101
110
  getFilePath,
@@ -131,18 +140,10 @@ export default {
131
140
  * @private
132
141
  */
133
142
  function addDirectory(file) {
134
- // Destructure object props
135
- const {isDynamic,path} = file;
136
- // Get the file path without the `.html`
137
- // NOTE: For dynamically-created pages, they didn't run through the 'convert to directory' plugin
138
- // So we need to do that here, by dropping the full `index.html`
139
- // Static-page Example: `path/to/file.html` becomes `path/to/file`
140
- // Dynamic-page Example: `path/to/file/index.html` becomes `path/to/file`
141
- const splitOn = isDynamic ? 'index.html' : '.';
142
- const pathSplit = path.split(splitOn)[0];
143
- const filePath = pathSplit.match(/\/index$/) ? pathSplit.substring(4, -1) : pathSplit;
144
- // Create the parent directories
145
- fs.mkdirpSync(filePath);
143
+ // Create the file's parent directories (everything before the filename)
144
+ // so the following fs.writeFile has a destination to write into.
145
+ const parentDir = file.path.split('/').slice(0, -1).join('/');
146
+ if (parentDir) fs.mkdirpSync(parentDir);
146
147
  }
147
148
 
148
149
  /**
@@ -159,9 +160,9 @@ function addDirectory(file) {
159
160
  */
160
161
  function addDynamicPage(path,src,store) {
161
162
  // Early Exit: Invalid data provided
162
- if (!path) customKill(`addDynamicPage(): No page path provided`);
163
- if (!src) customKill(`addDynamicPage(): No page source provided`);
164
- if (!store) customKill(`addDynamicPage(): No data store provided`);
163
+ if (!path) throw new Error('addDynamicPage(): No page path provided');
164
+ if (!src) throw new Error('addDynamicPage(): No page source provided');
165
+ if (!store) throw new Error('addDynamicPage(): No data store provided');
165
166
  // If desired page collection property doesn't exist on the target store object, add it
166
167
  if (!store.dynamicPages) store.dynamicPages = [];
167
168
  // Add entry to data store
@@ -316,6 +317,18 @@ function customError(e, label = 'Error') {
316
317
  customKill('Build Stopped');
317
318
  }
318
319
 
320
+ /**
321
+ * @description Always-visible warning for recoverable, per-file problems.
322
+ * Never exits — the build continues and reports at the end.
323
+ * @param {Object|String} e - The error (or message)
324
+ * @param {String} [label] - Context label (page path, plugin name)
325
+ * @private
326
+ */
327
+ function customWarn(e, label = 'Warning') {
328
+ console.log(chalk.bold.yellow(`\n${label}`));
329
+ console.log(e && e.message ? e.message : e);
330
+ }
331
+
319
332
  /**
320
333
  * @description Custom terminal `kill -9 node` when you need to stop
321
334
  * all terminal activity on exception/error.
@@ -407,8 +420,12 @@ function getFileParts(path) {
407
420
  // If last split item is `index.html`, store its parent directory (if option to convert pages to directories is enabled)
408
421
  // If not, there will be a lot of pages with `file.name` as
409
422
  const fileNameIfIndex = !convertPageToDirectory.disabled && fileName === 'index.html' ? fileSplit[fileSplit.length - 2] : undefined;
410
- const fileNameSplit = fileName.split('.');
411
- return { name: fileNameSplit[0], nameIfIndex: fileNameIfIndex, ext: fileNameSplit[1] };
423
+ // The extension is everything after the LAST dot — `lib.min.js` is a
424
+ // .js file, `report.2024.html` is an .html file.
425
+ const lastDot = fileName.lastIndexOf('.');
426
+ const name = lastDot > 0 ? fileName.slice(0, lastDot) : fileName;
427
+ const ext = lastDot > 0 ? fileName.slice(lastDot + 1) : undefined;
428
+ return { name, nameIfIndex: fileNameIfIndex, ext };
412
429
  }
413
430
 
414
431
  /**
@@ -432,8 +449,14 @@ function getFilePath(path) {
432
449
  * @returns {Array} - An array of paths
433
450
  * @private
434
451
  */
435
- function getPaths(originalPath, path, ignorePattern, paths = []) {
452
+ function getPaths(originalPath, path, ignorePattern, paths = [], compiledPatterns) {
436
453
  try {
454
+ // Compile exclusion patterns ONCE per walk (previously a new RegExp
455
+ // was constructed per pattern per file). The `g` flag is stripped:
456
+ // global regexes are stateful under .test() and misskip matches.
457
+ const patterns = compiledPatterns || (ignorePattern || []).map(p =>
458
+ p instanceof RegExp ? new RegExp(p.source, p.flags.replace('g', '')) : new RegExp(p)
459
+ );
437
460
  // Obtain a list of files and folders
438
461
  const files = readdirSync(path);
439
462
  files.forEach(file => {
@@ -444,18 +467,11 @@ function getPaths(originalPath, path, ignorePattern, paths = []) {
444
467
  // We won't do anything to it once it is copied to /dist
445
468
  // This is handy for `/dist/assets/scripts/vendor`, for example, since that is code likely already minified
446
469
  // and outside of the user's control
447
- let allowed = true, pattern, match;
448
- if (ignorePattern) {
449
- ignorePattern.forEach(p => {
450
- pattern = new RegExp(p, 'g');
451
- match = currentFilePath.match(pattern);
452
- if (match && match.length) allowed = false;
453
- })
454
- }
470
+ const allowed = !patterns.some(re => re.test(currentFilePath));
455
471
  // Include file to use in build process
456
472
  if (allowed) {
457
473
  if (fd.isDirectory()) {
458
- paths = [...paths, ...getPaths(originalPath, currentFilePath, ignorePattern)];
474
+ getPaths(originalPath, currentFilePath, ignorePattern, paths, patterns);
459
475
  } else {
460
476
  paths.push(currentFilePath);
461
477
  }
@@ -553,6 +569,7 @@ function isExtension(fileName, target) {
553
569
  function newDOM({src, options}) {
554
570
  // LinkeDOM's parseHTML returns { document, window, ... }
555
571
  // We wrap it to provide a compatible interface for existing plugins
572
+ jsdom.parseCount += 1;
556
573
  const parsed = parseHTML(src);
557
574
  return {
558
575
  window: { document: parsed.document },
@@ -572,6 +589,33 @@ function newFrag(src) {
572
589
  return document.body;
573
590
  }
574
591
 
592
+ /**
593
+ * @description Get the (shared, cached) DOM for a file. SourceFile
594
+ * instances expose a lazily-parsed cached document so consecutive DOM
595
+ * plugins share ONE parse; plain objects (tests, ad-hoc callers) get a
596
+ * fresh parse of file.src.
597
+ * @param {Object} file - SourceFile or plain {src} object
598
+ * @returns {Object} dom wrapper ({ window.document, serialize })
599
+ */
600
+ function fileDom(file) {
601
+ if (typeof file.markDomDirty === 'function') return file.dom;
602
+ return jsdom.dom({ src: file.src });
603
+ }
604
+
605
+ /**
606
+ * @description Record that a plugin mutated the file's DOM. SourceFile
607
+ * defers serialization until file.src is next read; plain objects are
608
+ * serialized immediately (backward compatible).
609
+ * @param {Object} file - SourceFile or plain {src} object
610
+ * @param {Object} dom - The dom returned by fileDom(file)
611
+ * @param {Boolean} [changed=true] - Pass false when nothing was mutated
612
+ */
613
+ function commitDom(file, dom, changed = true) {
614
+ if (!changed) return;
615
+ if (typeof file.markDomDirty === 'function') file.markDomDirty();
616
+ else file.src = setSrc({ dom });
617
+ }
618
+
575
619
  /**
576
620
  * @description Custom `Promise.all` that sends information to a callback fn when each promise is returned
577
621
  * @param {Array} arr - The items to promisify and run method against
@@ -587,7 +631,7 @@ function promiseAll(arr, method, cb, pageLabel) {
587
631
  for (const promise of promises) {
588
632
  promise
589
633
  .then(data => cb({length, data}))
590
- .catch(err => customKill(`killed: ${err}${ ` in ${pageLabel}` || '' }`));
634
+ .catch(err => customWarn(err, pageLabel ? `promiseAll: ${pageLabel}` : 'promiseAll'));
591
635
  }
592
636
  }
593
637
  return Promise.all(promises);
@@ -639,22 +683,16 @@ async function runFileLoop(files, method) {
639
683
  * @param {*} param0
640
684
  */
641
685
  function setSrc({dom, path}) {
642
- let result;
643
-
644
686
  // Dom Fragment (from newFrag — a body element used as container)
645
- if (!dom.window) {
646
- result = dom.innerHTML;
647
- }
648
- // Full HTML document
649
- else {
650
- const document = dom.window.document;
651
- const isFullDoc = !!document.doctype;
652
-
653
- if (isFullDoc) result = dom.serialize();
654
- else result = `${document.head.innerHTML}${document.body.innerHTML}`;
655
- }
687
+ if (!dom.window) return dom.innerHTML;
656
688
 
657
- return result;
689
+ // Document from newDOM: linkedom serializes exactly what was parsed —
690
+ // partials stay partial (no wrapper gained), full documents keep their
691
+ // doctype and all <html>/<head>/<body> attributes. (The old
692
+ // head.innerHTML + body.innerHTML fallback for doctype-less input was
693
+ // a real-jsdom workaround; it silently dropped <html lang>, body
694
+ // classes, and returned '' for partials under linkedom.)
695
+ return dom.serialize();
658
696
  }
659
697
 
660
698
  /**
@@ -695,8 +733,12 @@ async function updatePage(file) {
695
733
  function validatePageChange() {
696
734
  // Page was changed when using localhost BrowserSync live reloading (`npm run dev`)
697
735
  const changedDevPage = process.env.DEV_CHANGED_PAGE;
698
- // Was the changed page an include file?
699
- const isInclude = changedDevPage && !!changedDevPage.match(/\/(include)|(template)/);
700
- // Return true (valid) if it was a page change AND it wasn't an include file
701
- return changedDevPage && !isInclude;
736
+ // Build-only files (includes, templates/layouts, components) are baked
737
+ // into other pages, so changing one must force a FULL rebuild — the
738
+ // single-page fast path would copy the file into dist and leave every
739
+ // dependent page stale. Match whole directory segments only: a PAGE
740
+ // named template-strings-demo.html is still a fast-path page change.
741
+ const isBuildOnly = changedDevPage && /\/(includes?|templates?|components?|layouts?)\//.test(changedDevPage);
742
+ // Return true (valid) if it was a page change AND it wasn't a build-only file
743
+ return changedDevPage && !isBuildOnly;
702
744
  }
@@ -1,52 +0,0 @@
1
- // jsdom fetch fix patch
2
- // See original issue: https://github.com/jsdom/jsdom/pull/2510
3
- // Note: This patch may no longer be needed in jsdom 27.x+ as the fix was merged upstream.
4
- // The patch will silently skip if the target file structure has changed.
5
-
6
- import fs from 'fs-extra';
7
- import { fileURLToPath } from 'node:url';
8
- import path from 'node:path';
9
-
10
- const __dirname = path.dirname(fileURLToPath(import.meta.url));
11
-
12
- // Resolve jsdom relative to Cook's own node_modules (works whether Cook is
13
- // the project root or installed as a dependency inside another project)
14
- const filePath = path.resolve(__dirname, '..', 'node_modules', 'jsdom', 'lib', 'jsdom', 'browser', 'resources', 'per-document-resource-loader.js');
15
-
16
- try {
17
- // Check if file exists first
18
- if (!fs.existsSync(filePath)) {
19
- // File doesn't exist - jsdom structure may have changed, skip patch
20
- console.log('[jsdom-patch] Target file not found, skipping patch (may not be needed in this jsdom version)');
21
- process.exit(0);
22
- }
23
-
24
- let src = fs.readFileSync(filePath, 'utf-8');
25
-
26
- // Check if patch is already applied
27
- if (src.includes('if (this._resourceLoader === null) return null;')) {
28
- console.log('[jsdom-patch] Patch already applied, skipping');
29
- process.exit(0);
30
- }
31
-
32
- // Find target and add fix immediately inside the `fetch()` callback
33
- const fetchRegex = /fetch\(url,\s*{\s*element,\s*onLoad,\s*onError\s*}\)\s*{/gm;
34
-
35
- if (!fetchRegex.test(src)) {
36
- console.log('[jsdom-patch] Target pattern not found, skipping patch (may not be needed in this jsdom version)');
37
- process.exit(0);
38
- }
39
-
40
- // Reset regex lastIndex after test
41
- fetchRegex.lastIndex = 0;
42
-
43
- src = src.replace(fetchRegex, `fetch(url, { element, onLoad, onError }) { if (this._resourceLoader === null) return null;`);
44
-
45
- // Write new src back to file
46
- fs.writeFileSync(filePath, src, 'utf-8');
47
- console.log('[jsdom-patch] Patch applied successfully');
48
- }
49
- catch (err) {
50
- console.warn('[jsdom-patch] Warning: Could not apply jsdom patch:', err.message);
51
- // Don't fail the install, just warn
52
- }