cook-ssg 2.6.0 → 2.7.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 +1 -1
- package/scripts/build.js +18 -1
- package/scripts/dev.js +21 -0
- package/scripts/plugins/apply-base-path.js +2 -1
- package/scripts/plugins/copy-src.js +3 -0
- package/scripts/plugins/create-dir-from-file.js +4 -0
- package/scripts/plugins/fingerprint-assets.js +3 -1
- package/scripts/plugins/generate-sitemap-xml.js +3 -0
- package/scripts/plugins/html-collections.js +2 -0
- package/scripts/plugins/optimize-images.js +2 -0
- package/scripts/plugins/process-markdown.js +2 -1
- package/scripts/plugins/programs.js +214 -0
- package/scripts/utils/config/config.js +15 -1
- package/scripts/utils/get-src/get-src.js +6 -2
- package/scripts/utils/site-pages/site-pages.js +2 -1
- package/scripts/utils/util/util.js +1 -1
package/package.json
CHANGED
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';
|
|
@@ -48,7 +49,8 @@ import { collectSitePages } from './utils/site-pages/site-pages.js';
|
|
|
48
49
|
|
|
49
50
|
// CONFIG
|
|
50
51
|
// Combined user overrides on top of internal defaults
|
|
51
|
-
import config, { plugins } from './utils/config/config.js';
|
|
52
|
+
import config, { plugins, distPath, siteRoot } from './utils/config/config.js';
|
|
53
|
+
import { siteRootDir } from './utils/site-root/site-root.js';
|
|
52
54
|
|
|
53
55
|
const cwd = process.cwd();
|
|
54
56
|
|
|
@@ -84,6 +86,9 @@ class Build {
|
|
|
84
86
|
// Show init message
|
|
85
87
|
console.log(`${ chalk.blue('\n[Build]') } ${ chalk.blue.bold('`npm run build`') }`);
|
|
86
88
|
|
|
89
|
+
// Program areas must be known before any pass runs (copySrc is first)
|
|
90
|
+
loadProgramAreas();
|
|
91
|
+
|
|
87
92
|
// PLUGIN: Create `/dist` if not already made
|
|
88
93
|
await createDist();
|
|
89
94
|
|
|
@@ -98,6 +103,9 @@ class Build {
|
|
|
98
103
|
// see every page; merges with markdown collections.
|
|
99
104
|
await htmlCollections({store, data});
|
|
100
105
|
|
|
106
|
+
// PLUGIN: Programs: `programs` / `programAreas` data from config/programs.json
|
|
107
|
+
await programsData({data});
|
|
108
|
+
|
|
101
109
|
// PLUGIN: Generate responsive image derivatives (AVIF/WebP at multiple widths)
|
|
102
110
|
await optimizeImagesGenerate({store});
|
|
103
111
|
|
|
@@ -247,6 +255,15 @@ class Build {
|
|
|
247
255
|
// built-in post-loop plugin so they all work with plain root paths.
|
|
248
256
|
await applyBasePath();
|
|
249
257
|
|
|
258
|
+
// Sandboxed programs: `_headers` rules (Cloudflare Pages, Netlify) appended
|
|
259
|
+
// to the site's own `_headers`, which copySrc already placed in dist.
|
|
260
|
+
if (!Util.validatePageChange()) {
|
|
261
|
+
const headersFile = path.join(siteRootDir(distPath, siteRoot), '_headers');
|
|
262
|
+
const existing = fs.existsSync(headersFile) ? fs.readFileSync(headersFile, 'utf-8') : null;
|
|
263
|
+
const headers = programHeaders(allPrograms(), existing);
|
|
264
|
+
if (headers !== null) fs.writeFileSync(headersFile, headers);
|
|
265
|
+
}
|
|
266
|
+
|
|
250
267
|
// CUSTOM PLUGINS: Run custom user plugins after file loop
|
|
251
268
|
await customPlugins({store, data, plugins: plugins.after, log: 'After' });
|
|
252
269
|
|
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); });
|
|
@@ -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;
|
|
@@ -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
|
|
@@ -17,6 +17,7 @@ import { renderTemplate } from '../utils/interpolate/interpolate.js';
|
|
|
17
17
|
|
|
18
18
|
// Config
|
|
19
19
|
import { addToCollection, sortCollections, toCollectionItem } from '../utils/collections/collections.js';
|
|
20
|
+
import { isProgramFile } from './programs.js';
|
|
20
21
|
import { distPath, srcPath, markdown as markdownConfig } from '../utils/config/config.js';
|
|
21
22
|
|
|
22
23
|
|
|
@@ -111,7 +112,7 @@ class ProcessMarkdown {
|
|
|
111
112
|
const entries = Util.getPaths(dir, dir, []);
|
|
112
113
|
|
|
113
114
|
for (const entry of entries) {
|
|
114
|
-
if (entry.endsWith('.md')) {
|
|
115
|
+
if (entry.endsWith('.md') && !isProgramFile(entry, srcPath)) {
|
|
115
116
|
files.push(entry);
|
|
116
117
|
}
|
|
117
118
|
}
|
|
@@ -0,0 +1,214 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @file programs.js
|
|
3
|
+
* @description Programs: folders of hand-written HTML/JS (`src/<area>/<slug>/`)
|
|
4
|
+
* that Cook leaves untouched. Reads config/programs.json, validates areas and
|
|
5
|
+
* cards, exposes `programs` / `programAreas` data, and answers "is this path
|
|
6
|
+
* inside a program folder" (isInProgram) for the other build passes.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
import chalk from 'chalk';
|
|
10
|
+
import fs from 'node:fs';
|
|
11
|
+
import path from 'node:path';
|
|
12
|
+
import { getPrograms, srcPath, buildOnlyPaths } from '../utils/config/config.js';
|
|
13
|
+
|
|
14
|
+
const SLUG = /^[a-z0-9]+(-[a-z0-9]+)*$/;
|
|
15
|
+
const isSlug = (v) => typeof v === 'string' && SLUG.test(v);
|
|
16
|
+
const TAG = '[programs] ';
|
|
17
|
+
export const RESERVED_AREAS = ['media', 'assets', 'layouts', 'includes'];
|
|
18
|
+
|
|
19
|
+
const isObj = (v) => !!v && typeof v === 'object' && !Array.isArray(v);
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* Validate raw config/programs.json.
|
|
23
|
+
* @param {unknown} raw
|
|
24
|
+
* @param {{ srcEntries: string[], buildOnlyPaths: string[], hasIndex: (area: string, slug: string) => boolean }} ctx
|
|
25
|
+
*/
|
|
26
|
+
export function normalizePrograms(raw, { srcEntries = [], buildOnlyPaths: buildOnly = [], hasIndex = () => true } = {}) {
|
|
27
|
+
const warnings = [];
|
|
28
|
+
const areas = [];
|
|
29
|
+
const programs = [];
|
|
30
|
+
// A slug-shaped area that collides with a page folder (R10): no programs data, but its
|
|
31
|
+
// subfolders stay program folders (untouched) and its sandboxed cards keep their rule.
|
|
32
|
+
const protectedAreas = [];
|
|
33
|
+
const protectedPrograms = [];
|
|
34
|
+
if (!isObj(raw)) return { areas, programs, warnings, protectedAreas, protectedPrograms };
|
|
35
|
+
|
|
36
|
+
const taken = new Set(srcEntries);
|
|
37
|
+
const buildOnlySet = new Set(buildOnly.map(p => String(p).replace(/^\/+|\/+$/g, '')));
|
|
38
|
+
const byPath = Object.create(null);
|
|
39
|
+
const protectedByPath = Object.create(null);
|
|
40
|
+
|
|
41
|
+
for (const a of Array.isArray(raw.areas) ? raw.areas : []) {
|
|
42
|
+
const p = isObj(a) ? a.path : undefined;
|
|
43
|
+
let why = null;
|
|
44
|
+
if (!isSlug(p)) why = 'use one lowercase segment (a-z, 0-9, hyphens)';
|
|
45
|
+
else if (RESERVED_AREAS.includes(p)) why = 'that name is reserved';
|
|
46
|
+
else if (buildOnlySet.has(p)) why = 'it is a buildOnlyPaths entry';
|
|
47
|
+
else if (byPath[p] || protectedByPath[p]) why = 'duplicate area';
|
|
48
|
+
else if (taken.has(p)) {
|
|
49
|
+
const area = { path: p, sandbox: a.sandbox === true };
|
|
50
|
+
protectedByPath[p] = area;
|
|
51
|
+
protectedAreas.push(area);
|
|
52
|
+
warnings.push(`${TAG}area ${JSON.stringify(p)} ignored: the site already has a page or folder with that name `
|
|
53
|
+
+ '(no programs data for it; its subfolders still ship untouched as program folders)');
|
|
54
|
+
continue;
|
|
55
|
+
}
|
|
56
|
+
if (why) {
|
|
57
|
+
warnings.push(`${TAG}area ${JSON.stringify(p)} ignored: ${why}`);
|
|
58
|
+
continue;
|
|
59
|
+
}
|
|
60
|
+
const area = { path: p, title: typeof a.title === 'string' && a.title ? a.title : p, sandbox: a.sandbox === true };
|
|
61
|
+
byPath[p] = area;
|
|
62
|
+
areas.push(area);
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
const seen = new Set();
|
|
66
|
+
for (const c of Array.isArray(raw.programs) ? raw.programs : []) {
|
|
67
|
+
const label = isObj(c) ? `${c.area}/${c.slug}` : JSON.stringify(c);
|
|
68
|
+
if (isObj(c) && protectedByPath[c.area]) {
|
|
69
|
+
if (isSlug(c.slug) && !seen.has(label)) {
|
|
70
|
+
seen.add(label);
|
|
71
|
+
protectedPrograms.push({
|
|
72
|
+
area: c.area, slug: c.slug, sandbox: typeof c.sandbox === 'boolean' ? c.sandbox : protectedByPath[c.area].sandbox,
|
|
73
|
+
});
|
|
74
|
+
}
|
|
75
|
+
continue;
|
|
76
|
+
}
|
|
77
|
+
if (!isObj(c) || !byPath[c.area]) {
|
|
78
|
+
warnings.push(`${TAG}program ${label} ignored: unknown area`);
|
|
79
|
+
continue;
|
|
80
|
+
}
|
|
81
|
+
if (!isSlug(c.slug)) {
|
|
82
|
+
warnings.push(`${TAG}program ${label} ignored: bad slug (use a-z, 0-9, hyphens)`);
|
|
83
|
+
continue;
|
|
84
|
+
}
|
|
85
|
+
if (seen.has(label)) {
|
|
86
|
+
warnings.push(`${TAG}program ${label} ignored: duplicate`);
|
|
87
|
+
continue;
|
|
88
|
+
}
|
|
89
|
+
seen.add(label);
|
|
90
|
+
const tags = Array.isArray(c.tags) ? c.tags.filter(t => typeof t === 'string') : [];
|
|
91
|
+
programs.push({
|
|
92
|
+
...c,
|
|
93
|
+
title: typeof c.title === 'string' && c.title ? c.title : c.slug,
|
|
94
|
+
tags,
|
|
95
|
+
url: `/${c.area}/${c.slug}/`,
|
|
96
|
+
sandbox: typeof c.sandbox === 'boolean' ? c.sandbox : byPath[c.area].sandbox,
|
|
97
|
+
hasIndex: !!hasIndex(c.area, c.slug),
|
|
98
|
+
});
|
|
99
|
+
}
|
|
100
|
+
return { areas, programs, warnings, protectedAreas, protectedPrograms };
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
const num = (v) => (typeof v === 'number' && Number.isFinite(v) ? v : Infinity);
|
|
104
|
+
|
|
105
|
+
function sortPrograms(list) {
|
|
106
|
+
return list.slice().sort((a, b) => {
|
|
107
|
+
const da = String(a.date || ''), db = String(b.date || '');
|
|
108
|
+
if (da !== db) return da < db ? 1 : -1;
|
|
109
|
+
const o = num(a.order) - num(b.order);
|
|
110
|
+
if (o) return o < 0 ? -1 : 1;
|
|
111
|
+
return String(a.title).localeCompare(String(b.title));
|
|
112
|
+
});
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
// Names in src/ that an area path may not reuse. A page `demos.html|md` is the
|
|
116
|
+
// area's list page (with or without the `demos/` folder yet), so it does not
|
|
117
|
+
// count; a folder holding pages of its own (a blog) does, as does any other file.
|
|
118
|
+
function readSrcEntries(dir) {
|
|
119
|
+
let ents;
|
|
120
|
+
try { ents = fs.readdirSync(dir, { withFileTypes: true }); } catch { return []; }
|
|
121
|
+
const holdsPages = (name) => {
|
|
122
|
+
try {
|
|
123
|
+
return fs.readdirSync(path.join(dir, name), { withFileTypes: true })
|
|
124
|
+
.some(e => e.isFile() && /\.(html|md)$/.test(e.name) && e.name !== 'index.html');
|
|
125
|
+
} catch { return false; }
|
|
126
|
+
};
|
|
127
|
+
const out = new Set();
|
|
128
|
+
for (const e of ents) {
|
|
129
|
+
if (e.isDirectory()) { if (holdsPages(e.name)) out.add(e.name); }
|
|
130
|
+
else if (!/\.(html|md)$/.test(e.name)) out.add(e.name);
|
|
131
|
+
}
|
|
132
|
+
return [...out];
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
function load() {
|
|
136
|
+
const hasIndex = (area, slug) => fs.existsSync(path.join(srcPath, area, slug, 'index.html'));
|
|
137
|
+
return normalizePrograms(getPrograms(), { srcEntries: readSrcEntries(srcPath), buildOnlyPaths, hasIndex });
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
let areaPaths = [];
|
|
141
|
+
|
|
142
|
+
/** Every area whose subfolders are program folders: the valid ones and the colliding ones (R10). */
|
|
143
|
+
const protectedPaths = ({ areas, protectedAreas }) => [...areas, ...protectedAreas].map(a => a.path);
|
|
144
|
+
|
|
145
|
+
/** Compute the area list for this build (programsData calls it). */
|
|
146
|
+
export function loadProgramAreas() {
|
|
147
|
+
areaPaths = protectedPaths(load());
|
|
148
|
+
return areaPaths;
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
/** Valid area paths from the current config. */
|
|
152
|
+
export function programAreaPaths() {
|
|
153
|
+
return load().areas.map(a => a.path);
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
/**
|
|
157
|
+
* Is relPath (relative to src or dist, `/` separators) inside <area>/<sub>/?
|
|
158
|
+
* @param {string} relPath
|
|
159
|
+
*/
|
|
160
|
+
export function isInProgram(relPath) {
|
|
161
|
+
if (!areaPaths.length || typeof relPath !== 'string') return false;
|
|
162
|
+
const parts = relPath.replace(/\\/g, '/').replace(/^\.?\/+/, '').split('/');
|
|
163
|
+
return parts.length >= 3 && areaPaths.includes(parts[0]);
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
/**
|
|
167
|
+
* Is filePath (as the build passes see it, e.g. `dist/demos/x/y.html`) inside a
|
|
168
|
+
* program folder? baseDir is the directory the path is relative to (dist, src).
|
|
169
|
+
* @param {string} filePath
|
|
170
|
+
* @param {string} baseDir
|
|
171
|
+
*/
|
|
172
|
+
export function isProgramFile(filePath, baseDir) {
|
|
173
|
+
if (!areaPaths.length || typeof filePath !== 'string') return false;
|
|
174
|
+
return isInProgram(path.relative(baseDir, filePath).split(path.sep).join('/'));
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
/** Set `programs` and `programAreas` on the data store. */
|
|
178
|
+
export async function programsData({ data }) {
|
|
179
|
+
const loaded = load();
|
|
180
|
+
const { areas, programs, warnings } = loaded;
|
|
181
|
+
areaPaths = protectedPaths(loaded);
|
|
182
|
+
for (const w of warnings) console.log(chalk.yellow(w));
|
|
183
|
+
const shown = sortPrograms(programs.filter(p => p.listed === true && p.hasIndex))
|
|
184
|
+
.map(({ hasIndex, ...card }) => card);
|
|
185
|
+
data.programs = shown;
|
|
186
|
+
const byArea = Object.create(null);
|
|
187
|
+
for (const a of areas) byArea[a.path] = shown.filter(p => p.area === a.path);
|
|
188
|
+
data.programAreas = byArea;
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
const SANDBOX_RULE = 'Content-Security-Policy: sandbox allow-scripts allow-forms allow-popups allow-pointer-lock allow-modals';
|
|
192
|
+
|
|
193
|
+
/**
|
|
194
|
+
* Cloudflare Pages / Netlify `_headers` text: the site's own rules, then a
|
|
195
|
+
* sandbox block for each sandboxed program (listed or not), in program order.
|
|
196
|
+
* @param {Array<{area: string, slug: string, sandbox?: boolean}>} programs
|
|
197
|
+
* @param {string|null} existing - The site's own `_headers` text, if any
|
|
198
|
+
* @returns {string|null} null when no program is sandboxed
|
|
199
|
+
*/
|
|
200
|
+
export function programHeaders(programs, existing) {
|
|
201
|
+
const sandboxed = (programs || []).filter(p => p.sandbox === true);
|
|
202
|
+
if (!sandboxed.length) return null;
|
|
203
|
+
const blocks = sandboxed.map(p => `/${p.area}/${p.slug}/*\n ${SANDBOX_RULE}\n`).join('\n');
|
|
204
|
+
return existing ? `${existing}\n${blocks}` : blocks;
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
/**
|
|
208
|
+
* Programs (listed and unlisted) from the current config, for `_headers`: the valid ones,
|
|
209
|
+
* then those in a colliding area (R10), whose sandbox rule must still be written.
|
|
210
|
+
*/
|
|
211
|
+
export function allPrograms() {
|
|
212
|
+
const { programs, protectedPrograms } = load();
|
|
213
|
+
return [...programs, ...protectedPrograms];
|
|
214
|
+
}
|
|
@@ -35,6 +35,20 @@ function getTheme() {
|
|
|
35
35
|
}
|
|
36
36
|
}
|
|
37
37
|
|
|
38
|
+
// config/programs.json (written by Vanilla Press): areas of hand-written programs and their cards
|
|
39
|
+
const programsJsonPath = `${cwd}/config/programs.json`;
|
|
40
|
+
|
|
41
|
+
/** The programs config. Re-read on every call, like getTheme. */
|
|
42
|
+
function getPrograms() {
|
|
43
|
+
if (!fs.existsSync(programsJsonPath)) return undefined;
|
|
44
|
+
try {
|
|
45
|
+
return JSON.parse(fs.readFileSync(programsJsonPath, 'utf8'));
|
|
46
|
+
} catch (err) {
|
|
47
|
+
console.log(chalk.yellow(`[programs] config/programs.json: ${err.message}`));
|
|
48
|
+
return undefined;
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
|
|
38
52
|
|
|
39
53
|
// DEFINE DEFAULT CONFIG
|
|
40
54
|
// -----------------------------
|
|
@@ -335,7 +349,7 @@ const config = mergeConfigs(defaultConfig, userConfig);
|
|
|
335
349
|
export default config;
|
|
336
350
|
|
|
337
351
|
// Named exports for destructuring imports
|
|
338
|
-
export { getTheme };
|
|
352
|
+
export { getTheme, getPrograms };
|
|
339
353
|
export const {
|
|
340
354
|
activeLink,
|
|
341
355
|
autoComponents,
|
|
@@ -8,6 +8,7 @@
|
|
|
8
8
|
import fs from 'node:fs/promises';
|
|
9
9
|
import Logger from '../logger/logger.js';
|
|
10
10
|
import Util from '../util/util.js';
|
|
11
|
+
import { isProgramFile } from '../../plugins/programs.js';
|
|
11
12
|
import { SourceFile } from '../source-file/source-file.js';
|
|
12
13
|
|
|
13
14
|
// CONFIG
|
|
@@ -116,7 +117,8 @@ async function getSrcFiles() {
|
|
|
116
117
|
const isValidPageChange = Util.validatePageChange();
|
|
117
118
|
if (isValidPageChange) {
|
|
118
119
|
const getDistVersionOfChangedPage = process.env.DEV_CHANGED_PAGE.replace(srcPath, distPath);
|
|
119
|
-
|
|
120
|
+
// A file inside a program folder is only copied (copySrc), never built
|
|
121
|
+
files = isProgramFile(getDistVersionOfChangedPage, distPath) ? [] : [getDistVersionOfChangedPage];
|
|
120
122
|
}
|
|
121
123
|
// FULL BUILD
|
|
122
124
|
// Otherwise, find all allowed files, loop through them, and run the build plugins on them
|
|
@@ -134,6 +136,8 @@ async function getSrcFiles() {
|
|
|
134
136
|
files = Util.getPaths(distPath, distPath, excludedPaths);
|
|
135
137
|
// Get only the allowed files by extension (.css, .html)
|
|
136
138
|
files = files.filter(fileName => manualAllow(fileName, userAllowedPaths) || Util.isExtension(fileName, allowedExt));
|
|
139
|
+
// Program folders ship untouched
|
|
140
|
+
files = files.filter(fileName => !isProgramFile(fileName, distPath));
|
|
137
141
|
// Move known include files to the front of the array, so they are ideally built first
|
|
138
142
|
// before being replaced in other page files.
|
|
139
143
|
files = files.sort((a,b) => {
|
|
@@ -164,7 +168,7 @@ async function getSrcImages(cb) {
|
|
|
164
168
|
// Get images in `/dist`
|
|
165
169
|
let images = Util.getPaths(distPath, distPath, excludedPaths);
|
|
166
170
|
// Get only the allowed images by extension (.css, .html)
|
|
167
|
-
images = images.filter(fileName => Util.isExtension(fileName, allowedExt));
|
|
171
|
+
images = images.filter(fileName => Util.isExtension(fileName, allowedExt) && !isProgramFile(fileName, distPath));
|
|
168
172
|
// Run tasks on matched images
|
|
169
173
|
if (cb) cb(images);
|
|
170
174
|
}
|
|
@@ -13,6 +13,7 @@ import { promises as fs } from 'node:fs';
|
|
|
13
13
|
import Util from '../util/util.js';
|
|
14
14
|
import { distPath as defaultDistPath, siteRoot as defaultSiteRoot } from '../config/config.js';
|
|
15
15
|
import { siteRootDir, fileToUrlPath } from '../site-root/site-root.js';
|
|
16
|
+
import { isProgramFile } from '../../plugins/programs.js';
|
|
16
17
|
|
|
17
18
|
/**
|
|
18
19
|
* Collect all built index pages with their source and parsed document.
|
|
@@ -25,7 +26,7 @@ export async function collectSitePages(distPathArg = defaultDistPath, siteRootAr
|
|
|
25
26
|
const rootDir = siteRootDir(distPathArg, siteRootArg);
|
|
26
27
|
const htmlFiles = Util.getPaths(rootDir, rootDir, []) || [];
|
|
27
28
|
const indexFiles = htmlFiles.filter(
|
|
28
|
-
f => f.endsWith('/index.html') || f === `${rootDir}/index.html`
|
|
29
|
+
f => (f.endsWith('/index.html') || f === `${rootDir}/index.html`) && !isProgramFile(f, rootDir)
|
|
29
30
|
);
|
|
30
31
|
|
|
31
32
|
const pages = [];
|
|
@@ -746,7 +746,7 @@ function validatePageChange() {
|
|
|
746
746
|
// dependent page stale. Match whole directory segments only: a PAGE
|
|
747
747
|
// named template-strings-demo.html is still a fast-path page change.
|
|
748
748
|
const isBuildOnly = changedDevPage && (/\/(includes?|templates?|components?|layouts?)\//.test(changedDevPage)
|
|
749
|
-
|| /\/config\/theme\.json$/.test(changedDevPage));
|
|
749
|
+
|| /\/config\/(theme|programs)\.json$/.test(changedDevPage));
|
|
750
750
|
// Return true (valid) if it was a page change AND it wasn't a build-only file
|
|
751
751
|
return changedDevPage && !isBuildOnly;
|
|
752
752
|
}
|