cook-ssg 2.6.0 → 2.8.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/bin/cook.js CHANGED
@@ -23,6 +23,7 @@ Usage:
23
23
  cook build Build the site (production)
24
24
  cook dev Build + live-reload dev server
25
25
  cook dev --port N Dev server on a custom port (default: 3000)
26
+ cook check-layouts Check src/layouts and src/includes against the layout format
26
27
  cook --help Show this help
27
28
  cook --version Show version
28
29
  `);
@@ -48,6 +49,32 @@ switch (command) {
48
49
  break;
49
50
  }
50
51
 
52
+ case 'check-layouts': {
53
+ const { listLayouts } = await import('../scripts/layouts.js');
54
+ const { layouts, includes, problems } = await listLayouts(process.cwd());
55
+ let failed = false;
56
+ for (const { file, line, message } of problems) {
57
+ failed = true;
58
+ console.log(`${file}:${line}: ${message}`);
59
+ }
60
+ const report = (dir, items) => {
61
+ for (const item of items) {
62
+ for (const { line, message } of item.problems) {
63
+ failed = true;
64
+ console.log(`src/${dir}/${item.file}:${line}: ${message}`);
65
+ }
66
+ }
67
+ };
68
+ report('layouts', layouts);
69
+ report('includes', includes);
70
+ const plain = layouts.filter(l => l.kind === 'plain').length
71
+ + includes.filter(i => !i.ok && i.problems.length === 0).length;
72
+ const editable = layouts.filter(l => l.editable).length;
73
+ const withProblems = [...layouts, ...includes].filter(i => i.problems.length > 0).length;
74
+ console.log(`${layouts.length} layouts, ${includes.length} includes: ${editable} editable, ${plain} plain, ${withProblems} with problems`);
75
+ process.exit(failed ? 1 : 0);
76
+ }
77
+
51
78
  case '--version':
52
79
  case '-v':
53
80
  console.log(pkg.version);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "cook-ssg",
3
- "version": "2.6.0",
3
+ "version": "2.8.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": {
@@ -10,7 +10,8 @@
10
10
  "exports": {
11
11
  ".": "./scripts/build.js",
12
12
  "./build": "./scripts/build.js",
13
- "./dev": "./scripts/dev.js"
13
+ "./dev": "./scripts/dev.js",
14
+ "./layouts": "./scripts/layouts.js"
14
15
  },
15
16
  "files": [
16
17
  "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 { programsData, programHeaders, allPrograms, loadProgramAreas } from './plugins/programs.js';
28
29
  import { themeInject, resetThemeCache } from './plugins/theme.js';
29
30
  import { packageComponentsCopy, packageComponentsInject } from './plugins/package-components.js';
30
31
  import processMarkdown from './plugins/process-markdown.js';
@@ -38,6 +39,7 @@ import replaceInclude from './plugins/replace-include.js';
38
39
  import replaceInline from './plugins/replace-inline.js';
39
40
  import replaceMissingExternalLinkProtocol from './plugins/replace-external-link-protocol.js';
40
41
  import replaceTemplateStrings from './plugins/replace-template-strings.js';
42
+ import conditionalSections from './plugins/conditional-sections.js';
41
43
  import setActiveLinks from './plugins/set-active-links.js';
42
44
 
43
45
  // GET SOURCE
@@ -48,7 +50,8 @@ import { collectSitePages } from './utils/site-pages/site-pages.js';
48
50
 
49
51
  // CONFIG
50
52
  // Combined user overrides on top of internal defaults
51
- import config, { plugins } from './utils/config/config.js';
53
+ import config, { plugins, distPath, siteRoot } from './utils/config/config.js';
54
+ import { siteRootDir } from './utils/site-root/site-root.js';
52
55
 
53
56
  const cwd = process.cwd();
54
57
 
@@ -84,6 +87,9 @@ class Build {
84
87
  // Show init message
85
88
  console.log(`${ chalk.blue('\n[Build]') } ${ chalk.blue.bold('`npm run build`') }`);
86
89
 
90
+ // Program areas must be known before any pass runs (copySrc is first)
91
+ loadProgramAreas();
92
+
87
93
  // PLUGIN: Create `/dist` if not already made
88
94
  await createDist();
89
95
 
@@ -98,6 +104,9 @@ class Build {
98
104
  // see every page; merges with markdown collections.
99
105
  await htmlCollections({store, data});
100
106
 
107
+ // PLUGIN: Programs: `programs` / `programAreas` data from config/programs.json
108
+ await programsData({data});
109
+
101
110
  // PLUGIN: Generate responsive image derivatives (AVIF/WebP at multiple widths)
102
111
  await optimizeImagesGenerate({store});
103
112
 
@@ -122,7 +131,8 @@ class Build {
122
131
  // A failing page is recorded and skipped — one bad page must not
123
132
  // kill the other N-1. Failures are reported after the loop and the
124
133
  // process exits non-zero so CI/deploys still catch them.
125
- const failedPages = [];
134
+ // Markdown pages that failed the same way (a broken layout chain) count too.
135
+ const failedPages = [...(store.failedMarkdownPages || [])];
126
136
  await runFileLoop(files, fileLoop);
127
137
  async function fileLoop(fileName) {
128
138
  let file;
@@ -156,7 +166,7 @@ class Build {
156
166
 
157
167
  // PLUGIN: Apply layout template from [data-template] attribute
158
168
  // Also checks file.frontMatter.layout as a fallback
159
- await applyTemplate({file, store, allowType: ['.html']});
169
+ await applyTemplate({file, store, data, allowType: ['.html']});
160
170
 
161
171
  // PLUGIN: Replace `[data-include]` in files
162
172
  // Runs after template: includes inside the template get resolved
@@ -171,6 +181,10 @@ class Build {
171
181
  // Runs third: components expand templates with attribute values (their own ${var} replacement)
172
182
  await replaceComponents({file, store, data, allowType: ['.html']});
173
183
 
184
+ // PLUGIN: data-if / data-unless left after layouts and repeats (includes, site data)
185
+ // Every remaining key is known here, from data and front matter; a missing one is not set
186
+ conditionalSections({file, data, allowType: ['.html']});
187
+
174
188
  // PLUGIN: Render all ES6 template strings
175
189
  // Runs last: resolves ${var} across the fully assembled page (includes + components + repeats)
176
190
  // Merge front matter data so page-level variables resolve alongside global data
@@ -247,6 +261,15 @@ class Build {
247
261
  // built-in post-loop plugin so they all work with plain root paths.
248
262
  await applyBasePath();
249
263
 
264
+ // Sandboxed programs: `_headers` rules (Cloudflare Pages, Netlify) appended
265
+ // to the site's own `_headers`, which copySrc already placed in dist.
266
+ if (!Util.validatePageChange()) {
267
+ const headersFile = path.join(siteRootDir(distPath, siteRoot), '_headers');
268
+ const existing = fs.existsSync(headersFile) ? fs.readFileSync(headersFile, 'utf-8') : null;
269
+ const headers = programHeaders(allPrograms(), existing);
270
+ if (headers !== null) fs.writeFileSync(headersFile, headers);
271
+ }
272
+
250
273
  // CUSTOM PLUGINS: Run custom user plugins after file loop
251
274
  await customPlugins({store, data, plugins: plugins.after, log: 'After' });
252
275
 
package/scripts/dev.js CHANGED
@@ -8,6 +8,8 @@ import path from 'node:path';
8
8
  // In-process rebuilds: no cold Node process per save — module imports,
9
9
  // config, and (for single-page rebuilds) template caches stay warm
10
10
  import { runBuild } from './build.js';
11
+ import fs from 'fs-extra';
12
+ import { loadProgramAreas, isProgramFile } from './plugins/programs.js';
11
13
 
12
14
  const browserSync = browserSyncLib.create('Dev Server');
13
15
 
@@ -113,6 +115,21 @@ async function rebuild(file) {
113
115
  }
114
116
  building = true;
115
117
 
118
+ // A change inside a program folder is copied as is: no page build
119
+ loadProgramAreas();
120
+ if (isProgramFile(file, srcPath)) {
121
+ const fileDist = file.replace(`${srcPath}/`, `${distPath}/`);
122
+ try {
123
+ await fs.copy(file, fileDist);
124
+ browserSync.reload(fileDist);
125
+ } catch (err) {
126
+ console.error(chalk.red(`\n[dev] Could not copy ${file}: ${err && err.message ? err.message : err}`));
127
+ }
128
+ building = false;
129
+ if (queuedFile) { const next = queuedFile; queuedFile = null; rebuild(next); }
130
+ return;
131
+ }
132
+
116
133
  // DEV_CHANGED_PAGE tells the build whether to run the whole pipeline
117
134
  // or just this changed file (see validatePageChange)
118
135
  process.env.DEV_CHANGED_PAGE = file;
@@ -152,3 +169,7 @@ watchFiles.forEach(watchPath => {
152
169
  // A change forces a full rebuild so every page picks up the new theme.
153
170
  const themeJson = `${process.cwd()}/config/theme.json`;
154
171
  browserSync.watch(themeJson).on('change', file => { rebuild(file); }).on('add', file => { rebuild(file); });
172
+
173
+ // config/programs.json (Vanilla Press) feeds the programs data: rebuild on change.
174
+ const programsJson = `${process.cwd()}/config/programs.json`;
175
+ browserSync.watch(programsJson).on('change', file => { rebuild(file); }).on('add', file => { rebuild(file); });
@@ -0,0 +1,9 @@
1
+ /**
2
+ * @file layouts.js
3
+ * @description Public entry point (`cook-ssg/layouts`): the layout checker,
4
+ * the layout lister and the format constants.
5
+ */
6
+
7
+ export { checkLayout } from './utils/layouts/check.js';
8
+ export { listLayouts, loadSiteNames } from './utils/layouts/list.js';
9
+ export { FORMAT, PAGE_LAYOUTS, DOCUMENT_FIELDS } from './utils/layouts/vocabulary.js';
@@ -35,6 +35,7 @@ import { siteRootDir } from '../utils/site-root/site-root.js';
35
35
 
36
36
  // Config
37
37
  import { basePath as basePathConfig, distPath, siteRoot } from '../utils/config/config.js';
38
+ import { isProgramFile } from './programs.js';
38
39
 
39
40
 
40
41
  // ============================================================================
@@ -174,7 +175,7 @@ class ApplyBasePath {
174
175
  Logger.persist.header(`\nApply basePath ${this.basePath}`);
175
176
 
176
177
  const rootDir = siteRootDir(this.distPath, this.siteRoot);
177
- const htmlFiles = (Util.getPaths(rootDir, rootDir, []) || []).filter(p => p.endsWith('.html'));
178
+ const htmlFiles = (Util.getPaths(rootDir, rootDir, []) || []).filter(p => p.endsWith('.html') && !isProgramFile(p, rootDir));
178
179
 
179
180
  let files = 0;
180
181
  let total = 0;
@@ -20,7 +20,8 @@ import { promises as fs } from 'node:fs';
20
20
  import { existsSync } from 'node:fs';
21
21
  import path from 'node:path';
22
22
  import Util from '../utils/util/util.js';
23
- import { renderTemplate } from '../utils/interpolate/interpolate.js';
23
+ import { renderLayout, extractSlots, findTemplatedTag, templateDataAttrs } from '../utils/layouts/render.js';
24
+ import { layoutConditionals } from '../utils/layouts/conditionals.js';
24
25
 
25
26
  // Config
26
27
  import { srcPath, distPath } from '../utils/config/config.js';
@@ -29,10 +30,11 @@ import { srcPath, distPath } from '../utils/config/config.js';
29
30
  // DEFINE
30
31
  // -----------------------------
31
32
  class ApplyTemplate {
32
- constructor({ file, store, allowType, disallowType }) {
33
+ constructor({ file, store, data, allowType, disallowType }) {
33
34
  this.opts = { file, allowType, disallowType };
34
35
  this.file = file;
35
36
  this.store = store;
37
+ this.data = data || {};
36
38
  this.allowType = allowType;
37
39
  this.disallowType = disallowType;
38
40
 
@@ -56,15 +58,14 @@ class ApplyTemplate {
56
58
  || null;
57
59
  if (!templateName) return;
58
60
 
59
- // Load the template
60
- const templateContent = await this.getTemplate(templateName);
61
- if (!templateContent) return;
62
-
63
61
  // Extract page metadata and content from the source page
64
62
  const pageData = this.extractPageData();
65
63
 
66
- // Merge page content into the template
67
- this.file.src = this.applyTemplate(templateContent, pageData);
64
+ // Merge page content into the template (and, for a child layout,
65
+ // its parents). null: the layout wasn't found, leave the page as is.
66
+ const rendered = await this.applyTemplate(templateName, pageData);
67
+ if (rendered === null) return;
68
+ this.file.src = rendered;
68
69
  }
69
70
 
70
71
  /**
@@ -74,9 +75,9 @@ class ApplyTemplate {
74
75
  * @returns {string|null} Template name or null
75
76
  */
76
77
  findTemplateName() {
77
- // Match data-template on <html> or <body>
78
- const match = this.file.src.match(/<(?:html|body)\s[^>]*data-template="([^"]+)"/i);
79
- return match ? match[1] : null;
78
+ // Match data-template on <html> or <body>, value in any quoting
79
+ const tag = findTemplatedTag(this.file.src);
80
+ return tag ? tag.name : null;
80
81
  }
81
82
 
82
83
  /**
@@ -139,16 +140,10 @@ class ApplyTemplate {
139
140
 
140
141
  // Extract data-* attributes from the element with data-template
141
142
  // These become template variables (e.g., data-author="Kim" → ${author})
142
- const templateElMatch = this.file.src.match(/<(?:html|body)\s([^>]*data-template="[^"]*"[^>]*)>/i);
143
- if (templateElMatch) {
144
- const attrs = templateElMatch[1];
145
- const attrPattern = /data-(?!template)([a-z][a-z0-9-]*)="([^"]*)"/gi;
146
- let attrMatch;
147
- while ((attrMatch = attrPattern.exec(attrs)) !== null) {
148
- // Convert kebab-case to camelCase for template vars
149
- const key = attrMatch[1].replace(/-([a-z])/g, (_, c) => c.toUpperCase());
150
- data[key] = attrMatch[2];
151
- }
143
+ // (any quoting; kebab-case names become camelCase vars)
144
+ const templateEl = findTemplatedTag(this.file.src);
145
+ if (templateEl) {
146
+ Object.assign(data, templateDataAttrs(templateEl.attrs));
152
147
  }
153
148
 
154
149
  // For pages with front matter (no <body> wrapper), the entire file.src IS the content
@@ -169,37 +164,39 @@ class ApplyTemplate {
169
164
  }
170
165
  }
171
166
 
172
- // Extract named slots from <template slot="name"> elements.
167
+ // Extract named slots from top-level <template slot="name"> elements
168
+ // (nested <template>s inside a slot are kept whole).
173
169
  // These provide content for ${slot:name} placeholders in layouts.
174
170
  // Remaining content (after slot extraction) becomes ${content}.
175
171
  if (rawContent) {
176
- const slotPattern = /<template\s+slot="([^"]+)">([\s\S]*?)<\/template>/gi;
177
- let slotMatch;
178
- while ((slotMatch = slotPattern.exec(rawContent)) !== null) {
179
- data[`slot:${slotMatch[1]}`] = slotMatch[2].trim();
172
+ const { content, slots } = extractSlots(rawContent);
173
+ for (const [name, value] of Object.entries(slots)) {
174
+ data[`slot:${name}`] = value;
180
175
  }
181
- // Remove <template slot="..."> elements from content
182
- data.content = rawContent.replace(slotPattern, '').trim();
176
+ data.content = content;
183
177
  }
184
178
 
185
179
  return data;
186
180
  }
187
181
 
188
182
  /**
189
- * Inject page data into the template.
183
+ * Render the page through the named layout and any layouts it extends.
190
184
  * Replaces ${content} and other ${var} placeholders.
191
- * @param {string} template - Template HTML
185
+ * @param {string} name - Layout name
192
186
  * @param {Object} pageData - Extracted page data
193
- * @returns {string} Merged HTML
187
+ * @returns {Promise<string|null>} Merged HTML, or null if the layout is missing
194
188
  */
195
- applyTemplate(template, pageData) {
196
- // Shared interpolator: single pass over the LAYOUT only, callback
189
+ applyTemplate(name, pageData) {
190
+ // Shared interpolator: single pass over each LAYOUT only, callback
197
191
  // insertion (page content with $-patterns and ${...} in code samples
198
192
  // is never scanned), unmatched vars deferred to replaceTemplateStrings,
199
193
  // unfilled ${slot:...} removed. ${content} always resolves (empty
200
194
  // string when the page produced none).
201
- return renderTemplate(template, { ...pageData, content: pageData.content || '' }, {
202
- removeUnmatchedSlots: true,
195
+ return renderLayout(name, { ...pageData, content: pageData.content || '' }, {
196
+ loadLayout: (layoutName) => this.getTemplate(layoutName),
197
+ data: this.data,
198
+ // data-if / data-unless on page fields, slots and site data
199
+ conditionals: layoutConditionals,
203
200
  });
204
201
  }
205
202
 
@@ -0,0 +1,34 @@
1
+ /**
2
+ * @file conditional-sections.js
3
+ * @description The late `data-if` / `data-unless` pass, right before
4
+ * `replaceTemplateStrings`. Layouts decide page fields and slots, and
5
+ * `data-repeat` decides `alias.x` keys per item; what is left here (from
6
+ * includes, or keys a layout couldn't know) is decided from
7
+ * `{ ...data, ...file.frontMatter }`. Every key is known here: a missing
8
+ * one is not set.
9
+ *
10
+ * A page with neither marker is left exactly as it is.
11
+ */
12
+
13
+ // IMPORTS
14
+ // -----------------------------
15
+ import Util from '../utils/util/util.js';
16
+ import { lateConditionals } from '../utils/layouts/conditionals.js';
17
+
18
+
19
+ // DEFINE
20
+ // -----------------------------
21
+ /**
22
+ * @param {Object} opts
23
+ * @property {Object} opts.file - Current file info
24
+ * @property {Object} opts.data - User data from config/data.js
25
+ * @property {Array} [opts.allowType] - Allowed file types
26
+ * @property {Array} [opts.disallowType] - Disallowed file types
27
+ */
28
+ export default function conditionalSections({ file, data, allowType, disallowType }) {
29
+ // Early Exit: File type not allowed
30
+ if (!Util.isAllowedType({ file, allowType, disallowType })) return;
31
+
32
+ const values = file.frontMatter ? { ...data, ...file.frontMatter } : (data || {});
33
+ file.src = lateConditionals(file.src, values);
34
+ }
@@ -10,6 +10,7 @@ import chalk from 'chalk';
10
10
  import fs from 'fs-extra';
11
11
  import Logger from '../utils/logger/logger.js';
12
12
  import Util from '../utils/util/util.js';
13
+ import { isProgramFile } from './programs.js';
13
14
 
14
15
  // Config
15
16
  import { buildOnlyPaths, distPath, srcPath } from '../utils/config/config.js';
@@ -63,6 +64,8 @@ class CopySrc {
63
64
  if (pattern.test(src)) return false;
64
65
  }
65
66
  }
67
+ // Program folders ship untouched: every file, markdown included
68
+ if (isProgramFile(src, srcPath)) return true;
66
69
  // Skip directories (allow them to be traversed, filtering happens on files/subdirs)
67
70
  if (fs.lstatSync(src).isDirectory()) return true;
68
71
  // ---
@@ -13,6 +13,7 @@ import Logger from '../utils/logger/logger.js';
13
13
  import Spinner from '../utils/spinner/spinner.js';
14
14
  import Timer from '../utils/timer/timer.js';
15
15
  import { convertPageToDirectory, distPath } from '../utils/config/config.js';
16
+ import { isProgramFile } from './programs.js';
16
17
  import { getSrcConfig } from '../utils/get-src/get-src.js';
17
18
 
18
19
  const cwd = process.cwd();
@@ -99,6 +100,9 @@ class CreateDirFromFile {
99
100
  const allowed = utils.isAllowedType({file, allowType, disallowType});
100
101
  if (!allowed) return;
101
102
 
103
+ // Early Exit: program folders ship untouched
104
+ if (isProgramFile(fileName, distPath)) return;
105
+
102
106
  // Early Exit: Do not create directory if current file is an index.html page
103
107
  if (file.name === 'index') return;
104
108
 
@@ -24,6 +24,7 @@ import Util from '../utils/util/util.js';
24
24
  // Config
25
25
  import { distPath, siteRoot, fingerprint as fingerprintConfig } from '../utils/config/config.js';
26
26
  import { siteRootDir } from '../utils/site-root/site-root.js';
27
+ import { isProgramFile } from './programs.js';
27
28
 
28
29
 
29
30
  // ============================================================================
@@ -173,7 +174,7 @@ class FingerprintAssets {
173
174
 
174
175
  // Phase 2: Rewrite HTML references
175
176
  const htmlFiles = (Util.getPaths(this.rootDir, this.rootDir, []) || [])
176
- .filter(p => p.endsWith('.html'));
177
+ .filter(p => p.endsWith('.html') && !isProgramFile(p, this.rootDir));
177
178
  let totalRewrites = 0;
178
179
  for (const htmlPath of htmlFiles) {
179
180
  const original = await fs.readFile(htmlPath, 'utf-8');
@@ -203,6 +204,7 @@ class FingerprintAssets {
203
204
  return all.filter(p => {
204
205
  // Skip source maps in the candidate list — handled alongside their source.
205
206
  if (p.endsWith('.map')) return false;
207
+ if (isProgramFile(p, this.rootDir)) return false;
206
208
  const ext = path.extname(p);
207
209
  if (!this.config.types.includes(ext)) return false;
208
210
  if (excludes.some(r => r.test(p))) return false;
@@ -10,6 +10,7 @@ import Util from '../utils/util/util.js';
10
10
  // CONFIG
11
11
  import { distPath, fragments, sitemap, siteRoot, srcPath } from '../utils/config/config.js';
12
12
  import { siteRootDir } from '../utils/site-root/site-root.js';
13
+ import { isProgramFile } from './programs.js';
13
14
 
14
15
 
15
16
  // DEFINE
@@ -145,6 +146,8 @@ class GenerateSitemap {
145
146
  files = files.filter(fileName => Util.isExtension(fileName, allowedExt));
146
147
  // Skip SPA fragment files (content duplicates of their parent page)
147
148
  files = files.filter(fileName => !fileName.endsWith(`/${this.fragmentsFilename}`));
149
+ // Program folders are not site pages
150
+ files = files.filter(fileName => !isProgramFile(fileName, this.rootDir));
148
151
  // Format for xml: Remove `/dist`
149
152
  files = files.map(fileName => fileName.slice(this.rootDir.length));
150
153
  // Format for xml: Remove `filename`
@@ -34,6 +34,7 @@ import Logger from '../utils/logger/logger.js';
34
34
  import Util from '../utils/util/util.js';
35
35
  import { addToCollection, sortCollections, toCollectionItem } from '../utils/collections/collections.js';
36
36
  import { normalizeSiteRoot } from '../utils/site-root/site-root.js';
37
+ import { isInProgram } from './programs.js';
37
38
 
38
39
  // Config
39
40
  import {
@@ -174,6 +175,7 @@ export default async function htmlCollections({
174
175
  let collected = 0;
175
176
  for (const file of files) {
176
177
  const relPath = path.relative(srcPath, file).split(path.sep).join('/');
178
+ if (isInProgram(relPath)) continue;
177
179
  if (buildOnlyPaths.some(dir => relPath === dir || relPath.startsWith(`${dir}/`))) continue;
178
180
 
179
181
  const distFile = `${distPath}/${relPath}`;
@@ -24,6 +24,7 @@ import Util from '../utils/util/util.js';
24
24
 
25
25
  // Config
26
26
  import { distPath, images as imagesConfig } from '../utils/config/config.js';
27
+ import { isProgramFile } from './programs.js';
27
28
 
28
29
 
29
30
  // ============================================================================
@@ -113,6 +114,7 @@ class OptimizeImagesGenerate {
113
114
  const allPaths = Util.getPaths(dir, dir, []);
114
115
  if (!allPaths) return [];
115
116
  return allPaths.filter(p => {
117
+ if (isProgramFile(p, dir)) return false;
116
118
  const ext = path.extname(p).toLowerCase();
117
119
  if (!rasterExts.includes(ext)) return false;
118
120
  // Skip our own generated derivatives (foo-320w.webp) — rescanning
@@ -13,10 +13,12 @@ import { marked } from 'marked';
13
13
  import matter from 'gray-matter';
14
14
  import Logger from '../utils/logger/logger.js';
15
15
  import Util from '../utils/util/util.js';
16
- import { renderTemplate } from '../utils/interpolate/interpolate.js';
16
+ import { renderLayout, LayoutChainError } from '../utils/layouts/render.js';
17
+ import { layoutConditionals } from '../utils/layouts/conditionals.js';
17
18
 
18
19
  // Config
19
20
  import { addToCollection, sortCollections, toCollectionItem } from '../utils/collections/collections.js';
21
+ import { isProgramFile } from './programs.js';
20
22
  import { distPath, srcPath, markdown as markdownConfig } from '../utils/config/config.js';
21
23
 
22
24
 
@@ -62,6 +64,10 @@ class ProcessMarkdown {
62
64
 
63
65
  // Track processed files
64
66
  this.processedFiles = [];
67
+
68
+ // Pages whose layout chain is broken (cycle, too deep): build errors,
69
+ // reported with the page loop's failures. Reset every build.
70
+ this.store.failedMarkdownPages = [];
65
71
  }
66
72
 
67
73
  // INIT
@@ -111,7 +117,7 @@ class ProcessMarkdown {
111
117
  const entries = Util.getPaths(dir, dir, []);
112
118
 
113
119
  for (const entry of entries) {
114
- if (entry.endsWith('.md')) {
120
+ if (entry.endsWith('.md') && !isProgramFile(entry, srcPath)) {
115
121
  files.push(entry);
116
122
  }
117
123
  }
@@ -165,6 +171,13 @@ class ProcessMarkdown {
165
171
  });
166
172
 
167
173
  } catch (err) {
174
+ if (err instanceof LayoutChainError) {
175
+ // A layout cycle or over-deep chain fails the build, as for HTML pages
176
+ this.store.failedMarkdownPages.push({ page: filePath, error: err });
177
+ console.warn(chalk.yellow(`\n[build] Page failed: ${filePath}`));
178
+ console.warn(` ${err.message}`);
179
+ return;
180
+ }
168
181
  Util.customWarn(err, `ProcessMarkdown: ${filePath} (page skipped)`);
169
182
  }
170
183
  }
@@ -220,24 +233,38 @@ class ProcessMarkdown {
220
233
  * @returns {string} Final HTML
221
234
  */
222
235
  async applyLayout(layoutName, pageData) {
223
- // Get layout template
224
- const layoutContent = await this.getLayout(layoutName);
225
-
226
- if (!layoutContent) {
227
- // Fallback to basic HTML if layout not found
228
- console.log(chalk.yellow(` Layout "${layoutName}" not found, using basic HTML`));
229
- return this.buildBasicHtml(pageData);
230
- }
231
-
232
- // Shared interpolator: single pass over the LAYOUT only — markdown
236
+ // Shared interpolator: single pass over each LAYOUT only — markdown
233
237
  // content (which legitimately contains ${...} and $-patterns in code
234
238
  // samples) is never scanned for substitution. Page data wins over
235
- // global data; ${content} always resolves.
236
- return renderTemplate(layoutContent, {
239
+ // global data; ${content} always resolves. A child layout is applied,
240
+ // then its parent, and so on.
241
+ let missingParent = false;
242
+ const finalHtml = await renderLayout(layoutName, {
237
243
  ...this.data,
238
244
  ...pageData,
239
245
  content: pageData.content ?? '',
246
+ }, {
247
+ loadLayout: (name) => this.getLayout(name),
248
+ data: this.data,
249
+ // data-if / data-unless on page fields, slots and site data. Page
250
+ // fields are decided here: by the page loop they are gone (ruling P5).
251
+ conditionals: layoutConditionals,
252
+ // A plain layout keeps unfilled ${slot:x}, as it always has here
253
+ removeUnmatchedSlots: false,
254
+ // The layout exists but a layout it extends doesn't: say which
255
+ onMissingParent: (message) => {
256
+ missingParent = true;
257
+ console.log(chalk.yellow(` ${message}, using basic HTML`));
258
+ },
240
259
  });
260
+
261
+ if (finalHtml === null) {
262
+ // Fallback to basic HTML if layout not found
263
+ if (!missingParent) console.log(chalk.yellow(` Layout "${layoutName}" not found, using basic HTML`));
264
+ return this.buildBasicHtml(pageData);
265
+ }
266
+
267
+ return finalHtml;
241
268
  }
242
269
 
243
270
  /**