cook-ssg 2.2.1 → 2.2.3

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
@@ -151,12 +151,12 @@ The build process performs the following steps, in this order:
151
151
  * Pre-renders Declarative Shadow DOM from a manifest (`dsd` config)
152
152
  * Adds missing `http://` protocol to `www.`/`cdn.` links
153
153
  * Replaces inline placeholders (`[data-inline]`) with external source (production only)
154
- * Sets `<a>` tags whose `[href]` resolves to the current page as active (`class="active"`), ancestors as `class="active-parent"`
154
+ * Sets `<a>` tags whose `[href]` resolves to the current page as active (`class="active"` plus `aria-current="page"`), ancestors as `class="active-parent"`
155
155
  * Stores link/script files marked for bundling (`[data-bundle]`)
156
156
  * Minifies HTML, CSS, and JS source (production only)
157
157
  8. **Generates fragments** - A sibling `_fragment.html` per page for SPA-style navigation (`fragments` config)
158
158
  9. **Generates formats** - Markdown copies under `/md/`, JSON under `/api/`, Atom feed, and `llms.txt` (`formats` config)
159
- 10. **Creates `sitemap.xml`** - Auto-generated in `/dist` (fragments excluded)
159
+ 10. **Creates `sitemap.xml`** - When `sitemap.url` is set, written to the site root (`/dist`, or `/dist/<siteRoot>`); fragments excluded
160
160
  11. **Creates bundled files** - `.css` and `.js` bundles are written
161
161
  12. **Fingerprints assets** - Opt-in content-hash filenames with HTML and JS-import rewriting (`fingerprint` config)
162
162
  13. **Runs custom-user `after` plugins** - Runs once after file processing
@@ -194,7 +194,12 @@ export default {
194
194
  // Source directory (default: 'src')
195
195
  srcPath: 'src',
196
196
 
197
- // Sitemap configuration
197
+ // Subfolder of distPath served at "/" (default: '' = distPath itself).
198
+ // For pages kept in src/pages and deployed from dist/pages, set 'pages'
199
+ // so active links, the sitemap and formats use /docs/, not /pages/docs/.
200
+ siteRoot: '',
201
+
202
+ // Sitemap: set url to enable (default: '' = no sitemap.xml)
198
203
  sitemap: {
199
204
  url: 'https://www.yoursite.com',
200
205
  },
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "cook-ssg",
3
- "version": "2.2.1",
3
+ "version": "2.2.3",
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": {
@@ -20,17 +20,22 @@ import Util from '../utils/util/util.js';
20
20
  import Logger from '../utils/logger/logger.js';
21
21
 
22
22
  // Config
23
- import { distPath, srcPath, formats as formatsConfig } from '../utils/config/config.js';
23
+ import { distPath, siteRoot, srcPath, formats as formatsConfig } from '../utils/config/config.js';
24
+ import { siteRootDir, fileToUrlPath } from '../utils/site-root/site-root.js';
24
25
 
25
26
 
26
27
  // DEFINE
27
28
  // -----------------------------
28
29
  class GenerateFormats {
29
- constructor({ store, data, pages, distPath: distPathOverride }) {
30
+ constructor({ store, data, pages, distPath: distPathOverride, siteRoot: siteRootOverride }) {
30
31
  this.store = store;
31
32
  this.data = data || {};
32
33
  // Optional per-call overrides
33
34
  this.distPath = distPathOverride || distPath;
35
+ this.siteRoot = siteRootOverride ?? siteRoot;
36
+ // Served root: pages are read from, and md/ api/ feed.xml llms*.txt
37
+ // written to, the folder visitors see as "/"
38
+ this.rootDir = siteRootDir(this.distPath, this.siteRoot);
34
39
  // Optional shared page snapshot (see scripts/utils/site-pages) —
35
40
  // avoids re-walking dist and re-parsing every page. Doms are shared
36
41
  // and must be treated as read-only.
@@ -66,9 +71,9 @@ class GenerateFormats {
66
71
  // Use the shared snapshot when provided; otherwise walk + parse
67
72
  let pages = this.pages;
68
73
  if (!pages) {
69
- const htmlFiles = Util.getPaths(this.distPath, this.distPath, []);
74
+ const htmlFiles = Util.getPaths(this.rootDir, this.rootDir, []);
70
75
  const indexFiles = htmlFiles
71
- .filter(f => f.endsWith('/index.html') || f === `${this.distPath}/index.html`);
76
+ .filter(f => f.endsWith('/index.html') || f === `${this.rootDir}/index.html`);
72
77
  pages = indexFiles.map(filePath => ({ filePath, urlPath: null, dom: null }));
73
78
  }
74
79
  pages = pages.filter(p => !p.filePath.includes('/404/'));
@@ -108,7 +113,7 @@ class GenerateFormats {
108
113
  // Get the URL path from the dist file path
109
114
  // e.g., dist/blog/my-post/index.html → /blog/my-post/
110
115
  const urlPath = page.urlPath
111
- || page.filePath.replace(this.distPath, '').replace(/\/index\.html$/, '/').replace(/^$/, '/');
116
+ || fileToUrlPath(page.filePath, this.distPath, this.siteRoot);
112
117
 
113
118
  // Try to find corresponding markdown source
114
119
  const mdSourcePath = this.findMarkdownSource(urlPath);
@@ -156,8 +161,8 @@ class GenerateFormats {
156
161
  const content = await fs.readFile(mdSourcePath, 'utf-8');
157
162
  const trimmedPath = urlPath.replace(/^\//, '').replace(/\/$/, '');
158
163
  const outputPath = trimmedPath
159
- ? path.resolve(`${this.distPath}/md/${trimmedPath}/index.md`)
160
- : path.resolve(`${this.distPath}/md/index.md`);
164
+ ? path.resolve(`${this.rootDir}/md/${trimmedPath}/index.md`)
165
+ : path.resolve(`${this.rootDir}/md/index.md`);
161
166
 
162
167
  await fs.mkdir(path.dirname(outputPath), { recursive: true });
163
168
  await fs.writeFile(outputPath, content, 'utf-8');
@@ -208,7 +213,7 @@ class GenerateFormats {
208
213
 
209
214
  // Write JSON
210
215
  const trimmedPath = urlPath.replace(/^\//, '').replace(/\/$/, '') || 'index';
211
- const outputPath = path.resolve(`${this.distPath}/api/${trimmedPath}.json`);
216
+ const outputPath = path.resolve(`${this.rootDir}/api/${trimmedPath}.json`);
212
217
 
213
218
  await fs.mkdir(path.dirname(outputPath), { recursive: true });
214
219
  await fs.writeFile(outputPath, JSON.stringify(meta, null, 2), 'utf-8');
@@ -283,7 +288,7 @@ class GenerateFormats {
283
288
  xml += `</feed>
284
289
  `;
285
290
 
286
- await fs.writeFile(path.resolve(`${this.distPath}/feed.xml`), xml, 'utf-8');
291
+ await fs.writeFile(path.resolve(`${this.rootDir}/feed.xml`), xml, 'utf-8');
287
292
  this.stats.feed = true;
288
293
  }
289
294
 
@@ -297,7 +302,7 @@ class GenerateFormats {
297
302
  const pages = [];
298
303
  for (const page of pageEntries) {
299
304
  const urlPath = page.urlPath
300
- || page.filePath.replace(this.distPath, '').replace(/\/index\.html$/, '/').replace(/^$/, '/');
305
+ || fileToUrlPath(page.filePath, this.distPath, this.siteRoot);
301
306
  const mdSource = this.findMarkdownSource(urlPath);
302
307
  const trimmedPath = urlPath.replace(/^\//, '').replace(/\/$/, '');
303
308
 
@@ -403,7 +408,7 @@ class GenerateFormats {
403
408
  }
404
409
  }
405
410
 
406
- await fs.writeFile(path.resolve(`${this.distPath}/llms.txt`), content, 'utf-8');
411
+ await fs.writeFile(path.resolve(`${this.rootDir}/llms.txt`), content, 'utf-8');
407
412
  this.stats.llmsTxt = true;
408
413
  }
409
414
 
@@ -428,7 +433,7 @@ class GenerateFormats {
428
433
  // Collect pages and read their markdown content
429
434
  for (const page of pageEntries) {
430
435
  const urlPath = page.urlPath
431
- || page.filePath.replace(this.distPath, '').replace(/\/index\.html$/, '/').replace(/^$/, '/');
436
+ || fileToUrlPath(page.filePath, this.distPath, this.siteRoot);
432
437
  const mdSource = this.findMarkdownSource(urlPath);
433
438
  if (!mdSource) continue;
434
439
 
@@ -449,7 +454,7 @@ class GenerateFormats {
449
454
  } catch { /* skip unreadable files */ }
450
455
  }
451
456
 
452
- await fs.writeFile(path.resolve(`${this.distPath}/llms-full.txt`), content, 'utf-8');
457
+ await fs.writeFile(path.resolve(`${this.rootDir}/llms-full.txt`), content, 'utf-8');
453
458
  this.stats.llmsFullTxt = true;
454
459
  }
455
460
 
@@ -16,7 +16,8 @@ import Util from '../utils/util/util.js';
16
16
  import Logger from '../utils/logger/logger.js';
17
17
 
18
18
  // Config
19
- import { distPath, fragments as fragmentsConfig } from '../utils/config/config.js';
19
+ import { distPath, siteRoot, fragments as fragmentsConfig } from '../utils/config/config.js';
20
+ import { siteRootDir } from '../utils/site-root/site-root.js';
20
21
 
21
22
 
22
23
  // DEFINE
@@ -26,6 +27,7 @@ class GenerateFragments {
26
27
  this.total = 0;
27
28
  // Optional per-call overrides
28
29
  this.distPath = opts.distPath || distPath;
30
+ this.siteRoot = opts.siteRoot ?? siteRoot;
29
31
  // Optional shared page snapshot (see scripts/utils/site-pages) —
30
32
  // avoids re-walking dist and re-parsing every page
31
33
  this.pages = opts.pages || null;
@@ -62,8 +64,9 @@ class GenerateFragments {
62
64
  }
63
65
  } else {
64
66
  // Standalone: walk and parse ourselves
65
- const htmlFiles = Util.getPaths(this.distPath, this.distPath, []);
66
- const indexFiles = htmlFiles.filter(f => f.endsWith('/index.html') || f === `${this.distPath}/index.html`);
67
+ const rootDir = siteRootDir(this.distPath, this.siteRoot);
68
+ const htmlFiles = Util.getPaths(rootDir, rootDir, []);
69
+ const indexFiles = htmlFiles.filter(f => f.endsWith('/index.html') || f === `${rootDir}/index.html`);
67
70
 
68
71
  for (const filePath of indexFiles) {
69
72
  await this.generateFragment(filePath);
@@ -8,7 +8,8 @@ import Logger from '../utils/logger/logger.js';
8
8
  import Util from '../utils/util/util.js';
9
9
 
10
10
  // CONFIG
11
- import { distPath, fragments, sitemap, srcPath } from '../utils/config/config.js';
11
+ import { distPath, fragments, sitemap, siteRoot, srcPath } from '../utils/config/config.js';
12
+ import { siteRootDir } from '../utils/site-root/site-root.js';
12
13
 
13
14
 
14
15
  // DEFINE
@@ -22,6 +23,9 @@ class GenerateSitemap {
22
23
  // Optional per-call overrides (used by tests and custom pipelines)
23
24
  this.distPath = opts.distPath || distPath;
24
25
  this.sitemap = opts.sitemap || sitemap;
26
+ // Served root: only pages a visitor can reach are listed, and
27
+ // sitemap.xml lands where it is served (/sitemap.xml)
28
+ this.rootDir = siteRootDir(this.distPath, opts.siteRoot ?? siteRoot);
25
29
  // SPA fragment filename — fragment files are content duplicates of
26
30
  // their parent page and must never be listed as URLs
27
31
  this.fragmentsFilename = (fragments && fragments.filename) || '_fragment.html';
@@ -56,7 +60,7 @@ class GenerateSitemap {
56
60
  // Build XML source
57
61
  let xmlSrc = this.buildXML(files);
58
62
  // Create `sitemap.xml` and write source to it
59
- await fs.writeFile(`${this.distPath}/sitemap.xml`, xmlSrc);
63
+ await fs.writeFile(`${this.rootDir}/sitemap.xml`, xmlSrc);
60
64
  }
61
65
  catch (e) {
62
66
  Util.customWarn(e, 'Generate sitemap.xml (skipped)');
@@ -136,13 +140,13 @@ class GenerateSitemap {
136
140
  const allowedExt = ['html'];
137
141
  const excludedPaths = [];
138
142
  // Get files in `/dist`
139
- let files = Util.getPaths(this.distPath, this.distPath, excludedPaths);
143
+ let files = Util.getPaths(this.rootDir, this.rootDir, excludedPaths);
140
144
  // Get only the allowed files by extension (.css, .html)
141
145
  files = files.filter(fileName => Util.isExtension(fileName, allowedExt));
142
146
  // Skip SPA fragment files (content duplicates of their parent page)
143
147
  files = files.filter(fileName => !fileName.endsWith(`/${this.fragmentsFilename}`));
144
148
  // Format for xml: Remove `/dist`
145
- files = files.map(fileName => fileName.split(this.distPath)[1]);
149
+ files = files.map(fileName => fileName.slice(this.rootDir.length));
146
150
  // Format for xml: Remove `filename`
147
151
  files = files.map(fileName => this.formatDirPath(fileName));
148
152
  // Alphabetize files
@@ -9,7 +9,8 @@ import chalk from 'chalk';
9
9
  import Util from '../utils/util/util.js';
10
10
 
11
11
  // Config
12
- import { distPath, activeLink } from '../utils/config/config.js';
12
+ import { distPath, activeLink, siteRoot } from '../utils/config/config.js';
13
+ import { fileToUrlPath } from '../utils/site-root/site-root.js';
13
14
 
14
15
 
15
16
  // DEFINE
@@ -22,8 +23,10 @@ import { distPath, activeLink } from '../utils/config/config.js';
22
23
  * @property {Array} [obj.disallowType] - Disallowed file types (Opt-out)
23
24
  */
24
25
  class SetActiveLinks {
25
- constructor({file, allowType, disallowType, excludePaths = []}) {
26
+ constructor({file, allowType, disallowType, excludePaths = [], siteRoot: siteRootOpt}) {
26
27
  this.opts = {file, allowType, disallowType, excludePaths};
28
+ // Per-call override (tests, custom pipelines); defaults to config
29
+ this.siteRoot = siteRootOpt ?? siteRoot;
27
30
  this.file = file;
28
31
  this.allowType = allowType;
29
32
  this.disallowType = disallowType;
@@ -81,6 +84,8 @@ class SetActiveLinks {
81
84
  // marked /company/about/ active on /legal/about/ and even matched
82
85
  // external links whose URL ended in the same segment.
83
86
  const pageUrl = this.normalizePagePath(file.path);
87
+ // Page outside the served root (siteRoot): no visitor URL to compare
88
+ if (pageUrl === null) return;
84
89
  const linkUrl = this.normalizeHref(link.getAttribute('href'));
85
90
  if (linkUrl === null) return;
86
91
  if (linkUrl === pageUrl) this.setActiveLink(link);
@@ -98,10 +103,9 @@ class SetActiveLinks {
98
103
  * @private
99
104
  */
100
105
  normalizePagePath(pagePath) {
101
- let p = pagePath.startsWith(`${distPath}/`)
102
- ? pagePath.slice(distPath.length)
103
- : (pagePath.startsWith('/') ? pagePath : `/${pagePath}`);
104
- return this.normalizeUrlPath(p);
106
+ // dist/pages/docs/index.html → /docs/ when siteRoot is 'pages'
107
+ const p = fileToUrlPath(pagePath, distPath, this.siteRoot);
108
+ return p === null ? null : this.normalizeUrlPath(p);
105
109
  }
106
110
 
107
111
  /**
@@ -146,6 +150,9 @@ class SetActiveLinks {
146
150
  if (isAttribute) link.setAttribute(`data-${Util.attr.active}`,'');
147
151
  // Or set as a class value
148
152
  else link.classList.add(Util.attr.active);
153
+ // The accessible marker for "this link is the current page". Keep an
154
+ // author-set value (e.g. aria-current="step").
155
+ if (!link.hasAttribute('aria-current')) link.setAttribute('aria-current', 'page');
149
156
  // Increment counter for display in terminal logging
150
157
  this.total.active += 1;
151
158
  }
@@ -37,10 +37,17 @@ const defaultConfig = {
37
37
  srcPath: 'src',
38
38
  // The file to load in `srcPath` if not `index.html`
39
39
  startPath: 'index.html',
40
- // The URL domain to use for the `sitemap.xml` entries
41
- // Note: Enabling this auto-generates `sitemap.xml` in the `/dist` directory
40
+ // Subfolder of `distPath` that is served at "/" ('' = distPath itself).
41
+ // Set it when pages live in a subfolder you deploy on its own, e.g.
42
+ // src/pages → dist/pages with dist/pages as the host's output dir:
43
+ // `siteRoot: 'pages'`. Active links, the sitemap and the post-build page
44
+ // snapshot then use the URLs visitors actually see (/docs/, not /pages/docs/).
45
+ siteRoot: '',
46
+ // The URL domain to use for the `sitemap.xml` entries.
47
+ // Set `sitemap.url` to enable: `sitemap.xml` is written to the site root
48
+ // (`distPath`, or `distPath/siteRoot`). Left empty, no sitemap is written.
42
49
  sitemap: {
43
- url: 'https://www.site.com',
50
+ url: '',
44
51
  // Exclude files from sitemap by adding the desired path regex
45
52
  // Defaults are: Any `/assets` or `/includes` paths, and the root `404.html`
46
53
  // excludePaths: [/\/assets/, /\/includes/, /^\/404.html/],
@@ -311,6 +318,7 @@ export const {
311
318
  repeat,
312
319
  replaceExternalLinkProtocol,
313
320
  sitemap,
321
+ siteRoot,
314
322
  srcPath,
315
323
  startPath,
316
324
  watch,
@@ -11,17 +11,21 @@
11
11
 
12
12
  import { promises as fs } from 'node:fs';
13
13
  import Util from '../util/util.js';
14
- import { distPath as defaultDistPath } from '../config/config.js';
14
+ import { distPath as defaultDistPath, siteRoot as defaultSiteRoot } from '../config/config.js';
15
+ import { siteRootDir, fileToUrlPath } from '../site-root/site-root.js';
15
16
 
16
17
  /**
17
18
  * Collect all built index pages with their source and parsed document.
18
19
  * @param {string} [distPathArg] - Dist directory (defaults to config)
20
+ * @param {string} [siteRootArg] - Served subfolder of dist (defaults to config)
19
21
  * @returns {Promise<Array<{filePath: string, urlPath: string, src: string, dom: Object}>>}
20
22
  */
21
- export async function collectSitePages(distPathArg = defaultDistPath) {
22
- const htmlFiles = Util.getPaths(distPathArg, distPathArg, []) || [];
23
+ export async function collectSitePages(distPathArg = defaultDistPath, siteRootArg = defaultSiteRoot) {
24
+ // Walk only the served root: pages outside it have no visitor URL
25
+ const rootDir = siteRootDir(distPathArg, siteRootArg);
26
+ const htmlFiles = Util.getPaths(rootDir, rootDir, []) || [];
23
27
  const indexFiles = htmlFiles.filter(
24
- f => f.endsWith('/index.html') || f === `${distPathArg}/index.html`
28
+ f => f.endsWith('/index.html') || f === `${rootDir}/index.html`
25
29
  );
26
30
 
27
31
  const pages = [];
@@ -29,8 +33,8 @@ export async function collectSitePages(distPathArg = defaultDistPath) {
29
33
  const src = await fs.readFile(filePath, 'utf-8');
30
34
  const dom = Util.jsdom.dom({ src });
31
35
  // dist/blog/my-post/index.html → /blog/my-post/
32
- const relativePath = filePath.replace(distPathArg, '');
33
- const urlPath = relativePath.replace(/\/index\.html$/, '/').replace(/^$/, '/');
36
+ // (dist/pages/blog/my-post/index.html with siteRoot: 'pages')
37
+ const urlPath = fileToUrlPath(filePath, distPathArg, siteRootArg);
34
38
  pages.push({ filePath, urlPath, src, dom });
35
39
  }
36
40
  return pages;
@@ -0,0 +1,58 @@
1
+ /**
2
+ * @file site-root.js
3
+ * @description One mapping from built files to public URL paths.
4
+ *
5
+ * By default `distPath` is the web root: dist/blog/post/index.html is
6
+ * served at /blog/post/. Some sites keep pages in a subfolder and deploy
7
+ * only that folder (e.g. src/pages → dist/pages, with dist/pages as the
8
+ * host's output directory). `siteRoot: 'pages'` tells Cook that
9
+ * dist/pages/ is served at "/", so active links, the sitemap and the
10
+ * post-build page snapshot compute the URLs visitors actually see.
11
+ */
12
+
13
+ /**
14
+ * Normalize a siteRoot config value: '' | 'pages' | '/pages/' → '' | 'pages'
15
+ * @param {string} [siteRoot]
16
+ * @returns {string}
17
+ */
18
+ export function normalizeSiteRoot(siteRoot) {
19
+ return String(siteRoot || '').replace(/^\/+|\/+$/g, '');
20
+ }
21
+
22
+ /**
23
+ * Directory inside dist that is served at "/".
24
+ * @param {string} distPath
25
+ * @param {string} [siteRoot]
26
+ * @returns {string} e.g. 'dist' or 'dist/pages'
27
+ */
28
+ export function siteRootDir(distPath, siteRoot) {
29
+ const root = normalizeSiteRoot(siteRoot);
30
+ return root ? `${distPath}/${root}` : distPath;
31
+ }
32
+
33
+ /**
34
+ * Public URL path of a built file, or null when the file sits outside the
35
+ * served root (it is never reachable by a visitor).
36
+ * dist/index.html → /
37
+ * dist/blog/post/index.html → /blog/post/
38
+ * dist/about.html → /about.html
39
+ * dist/pages/docs/index.html → /docs/ (siteRoot: 'pages')
40
+ * dist/assets/x.html → null (siteRoot: 'pages')
41
+ * @param {string} filePath - Path as Cook sees it (starts with distPath)
42
+ * @param {string} distPath
43
+ * @param {string} [siteRoot]
44
+ * @returns {string|null}
45
+ */
46
+ export function fileToUrlPath(filePath, distPath, siteRoot) {
47
+ const rootDir = siteRootDir(distPath, siteRoot);
48
+ let rel;
49
+ if (filePath === rootDir) rel = '';
50
+ else if (filePath.startsWith(`${rootDir}/`)) rel = filePath.slice(rootDir.length);
51
+ // No siteRoot: tolerate paths given without the dist prefix (custom
52
+ // pipelines and tests pass 'about/index.html' or '/about/index.html').
53
+ else if (!normalizeSiteRoot(siteRoot)) rel = filePath;
54
+ else return null;
55
+ rel = rel.replace(/\/index\.html$/, '/');
56
+ if (!rel.startsWith('/')) rel = `/${rel}`;
57
+ return rel;
58
+ }
@@ -571,9 +571,16 @@ function newDOM({src, options}) {
571
571
  // We wrap it to provide a compatible interface for existing plugins
572
572
  jsdom.parseCount += 1;
573
573
  const parsed = parseHTML(src);
574
+ // linkedom always writes <!DOCTYPE html> (uppercase). Keep the doctype the
575
+ // author wrote (e.g. lowercase <!doctype html>, which HTML linters such as
576
+ // html-validate's doctype-style rule require) so output matches source.
577
+ const sourceDoctype = /^\s*(<!doctype\b[^>]*>)/i.exec(src)?.[1];
574
578
  return {
575
579
  window: { document: parsed.document },
576
- serialize: () => parsed.document.toString(),
580
+ serialize: () => {
581
+ const out = parsed.document.toString();
582
+ return sourceDoctype ? out.replace(/^<!doctype\b[^>]*>/i, sourceDoctype) : out;
583
+ },
577
584
  _document: parsed.document,
578
585
  };
579
586
  }