cook-ssg 2.0.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/LICENSE +21 -0
- package/README.md +445 -0
- package/bin/cook.js +66 -0
- package/package.json +75 -0
- package/patches/jsdom-fetch-fix.js +52 -0
- package/scripts/build.js +212 -0
- package/scripts/dev.js +119 -0
- package/scripts/plugins/apply-template.js +226 -0
- package/scripts/plugins/auto-components.js +215 -0
- package/scripts/plugins/bundle.js +338 -0
- package/scripts/plugins/copy-src.js +89 -0
- package/scripts/plugins/create-dir-from-file.js +144 -0
- package/scripts/plugins/create-dist.js +55 -0
- package/scripts/plugins/custom-plugins.js +118 -0
- package/scripts/plugins/declarative-shadow-dom.js +164 -0
- package/scripts/plugins/escape-code-blocks.js +54 -0
- package/scripts/plugins/generate-formats.js +361 -0
- package/scripts/plugins/generate-fragments.js +126 -0
- package/scripts/plugins/generate-sitemap-xml.js +216 -0
- package/scripts/plugins/minify-src.js +253 -0
- package/scripts/plugins/optimize-images.js +389 -0
- package/scripts/plugins/process-html-frontmatter.js +75 -0
- package/scripts/plugins/process-markdown.js +384 -0
- package/scripts/plugins/repeat-collection.js +296 -0
- package/scripts/plugins/replace-components.js +496 -0
- package/scripts/plugins/replace-external-link-protocol.js +171 -0
- package/scripts/plugins/replace-include.js +273 -0
- package/scripts/plugins/replace-inline.js +217 -0
- package/scripts/plugins/replace-template-strings.js +121 -0
- package/scripts/plugins/set-active-links.js +175 -0
- package/scripts/utils/config/config.js +277 -0
- package/scripts/utils/get-src/get-src.js +241 -0
- package/scripts/utils/logger/logger.js +47 -0
- package/scripts/utils/performance/performance.js +35 -0
- package/scripts/utils/spinner/spinner.js +112 -0
- package/scripts/utils/timer/timer.js +40 -0
- package/scripts/utils/util/util.js +719 -0
package/scripts/build.js
ADDED
|
@@ -0,0 +1,212 @@
|
|
|
1
|
+
// IMPORTS
|
|
2
|
+
// -----------------------------
|
|
3
|
+
import chalk from 'chalk';
|
|
4
|
+
import fs from 'fs-extra';
|
|
5
|
+
import { existsSync } from 'node:fs';
|
|
6
|
+
import { pathToFileURL } from 'node:url';
|
|
7
|
+
|
|
8
|
+
// UTILS
|
|
9
|
+
import Util, { runFileLoop, updatePage } from './utils/util/util.js';
|
|
10
|
+
|
|
11
|
+
// PLUGINS
|
|
12
|
+
// -----------------------------
|
|
13
|
+
import autoComponents from './plugins/auto-components.js';
|
|
14
|
+
import { bundleAdd, bundleBuild } from './plugins/bundle.js';
|
|
15
|
+
import copySrc from './plugins/copy-src.js';
|
|
16
|
+
import createDist from './plugins/create-dist.js';
|
|
17
|
+
import createDirFromFile from './plugins/create-dir-from-file.js';
|
|
18
|
+
import customPlugins from './plugins/custom-plugins.js';
|
|
19
|
+
import declarativeShadowDom from './plugins/declarative-shadow-dom.js';
|
|
20
|
+
import generateFormats from './plugins/generate-formats.js';
|
|
21
|
+
import generateFragments from './plugins/generate-fragments.js';
|
|
22
|
+
import generateSitemap from './plugins/generate-sitemap-xml.js';
|
|
23
|
+
import minifySrc from './plugins/minify-src.js';
|
|
24
|
+
import { optimizeImagesGenerate, optimizeImagesRewrite } from './plugins/optimize-images.js';
|
|
25
|
+
import processMarkdown from './plugins/process-markdown.js';
|
|
26
|
+
import repeatCollection from './plugins/repeat-collection.js';
|
|
27
|
+
import replaceComponents from './plugins/replace-components.js';
|
|
28
|
+
import applyTemplate from './plugins/apply-template.js';
|
|
29
|
+
import escapeCodeBlocks from './plugins/escape-code-blocks.js';
|
|
30
|
+
import processHtmlFrontmatter from './plugins/process-html-frontmatter.js';
|
|
31
|
+
import replaceInclude from './plugins/replace-include.js';
|
|
32
|
+
import replaceInline from './plugins/replace-inline.js';
|
|
33
|
+
import replaceMissingExternalLinkProtocol from './plugins/replace-external-link-protocol.js';
|
|
34
|
+
import replaceTemplateStrings from './plugins/replace-template-strings.js';
|
|
35
|
+
import setActiveLinks from './plugins/set-active-links.js';
|
|
36
|
+
|
|
37
|
+
// GET SOURCE
|
|
38
|
+
import { getDynamicFiles, getSrcConfig, getSrcFiles } from './utils/get-src/get-src.js';
|
|
39
|
+
|
|
40
|
+
// CONFIG
|
|
41
|
+
// Combined user overrides on top of internal defaults
|
|
42
|
+
import config, { plugins } from './utils/config/config.js';
|
|
43
|
+
|
|
44
|
+
const cwd = process.cwd();
|
|
45
|
+
|
|
46
|
+
// INTERNAL BUILD DATA-STORE
|
|
47
|
+
const store = {
|
|
48
|
+
// BUNDLE
|
|
49
|
+
// Init bundle plugin by creating temporary array for the build process.
|
|
50
|
+
// This will serve as a running cache so we don't bundle already-bundled files
|
|
51
|
+
// in subsequent pages in the file loop.
|
|
52
|
+
bundle: { css: {}, js: {}, },
|
|
53
|
+
// Cache custom plugins after first lookup (import)
|
|
54
|
+
plugins: {},
|
|
55
|
+
};
|
|
56
|
+
|
|
57
|
+
// USER'S DATA-STORE
|
|
58
|
+
// Get user's data config object. We pass it into plugins (when necessary)
|
|
59
|
+
// so that additional data can be added to it from plugins instead of needing
|
|
60
|
+
// to manually define everything from the start in `/config/data.js`
|
|
61
|
+
// Note: We init as empty object if user didn't create a `data.js` config file
|
|
62
|
+
const userDataPath = `${cwd}/config/data.js`;
|
|
63
|
+
const userDataPathExists = existsSync(userDataPath);
|
|
64
|
+
let data = {};
|
|
65
|
+
if (userDataPathExists) {
|
|
66
|
+
const dataModule = await import(pathToFileURL(userDataPath));
|
|
67
|
+
const exported = dataModule.default || dataModule;
|
|
68
|
+
data = typeof exported === 'function' ? await exported() : exported;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
// BUILD
|
|
73
|
+
// -----------------------------
|
|
74
|
+
|
|
75
|
+
class Build {
|
|
76
|
+
|
|
77
|
+
constructor() {}
|
|
78
|
+
|
|
79
|
+
async init() {
|
|
80
|
+
|
|
81
|
+
// Show init message
|
|
82
|
+
console.log(`${ chalk.blue('\n[Build]') } ${ chalk.blue.bold('`npm run build`') }`);
|
|
83
|
+
|
|
84
|
+
// PLUGIN: Create `/dist` if not already made
|
|
85
|
+
await createDist();
|
|
86
|
+
|
|
87
|
+
// PLUGIN: Copy `/src` to `/dist`
|
|
88
|
+
await copySrc();
|
|
89
|
+
|
|
90
|
+
// PLUGIN: Process markdown files (.md -> .html)
|
|
91
|
+
await processMarkdown({store, data});
|
|
92
|
+
|
|
93
|
+
// PLUGIN: Generate responsive image derivatives (AVIF/WebP at multiple widths)
|
|
94
|
+
await optimizeImagesGenerate({store});
|
|
95
|
+
|
|
96
|
+
// CUSTOM PLUGINS: Run custom user plugins before file loop
|
|
97
|
+
await customPlugins({store, data, plugins: plugins.before, log: 'Before' });
|
|
98
|
+
|
|
99
|
+
// GET THE ALLOWED FILES
|
|
100
|
+
let files = await getSrcFiles();
|
|
101
|
+
|
|
102
|
+
// ADD ANY DYNAMICALLY-GENERATED PAGES
|
|
103
|
+
// If pages were added in `this.data.dynamicPages` array, add them.
|
|
104
|
+
// NOTE: Runs after `createDirFromFile()` since .html pages not created yet.
|
|
105
|
+
files = getDynamicFiles(files);
|
|
106
|
+
|
|
107
|
+
// PLUGIN: Convert allowed /dist .html file to directory
|
|
108
|
+
await createDirFromFile({files, allowType: ['.html'] });
|
|
109
|
+
|
|
110
|
+
// THE FILES LOOP
|
|
111
|
+
await runFileLoop(files, fileLoop);
|
|
112
|
+
async function fileLoop(fileName) {
|
|
113
|
+
// Read and store the target file source.
|
|
114
|
+
// We'll pass the string around between the plugins
|
|
115
|
+
// then write back the updated/modified source to the file at the end
|
|
116
|
+
let file = await getSrcConfig({fileName});
|
|
117
|
+
|
|
118
|
+
// PLUGIN: Parse YAML front matter from HTML files
|
|
119
|
+
// Strips front matter from source, stores on file.frontMatter
|
|
120
|
+
await processHtmlFrontmatter({file, allowType: ['.html']});
|
|
121
|
+
|
|
122
|
+
// PLUGIN: HTML-escape <code-block data-escape> content for display
|
|
123
|
+
// Must run BEFORE any JSDOM-based plugin (applyTemplate, replaceInclude, etc.)
|
|
124
|
+
// because JSDOM would parse raw HTML/JS inside code-blocks as real DOM nodes
|
|
125
|
+
await escapeCodeBlocks({file, allowType: ['.html']});
|
|
126
|
+
|
|
127
|
+
// CUSTOM PLUGINS: Run custom user plugins during file loop
|
|
128
|
+
await customPlugins({file, store, data, plugins: plugins.default});
|
|
129
|
+
|
|
130
|
+
// PLUGIN: Apply layout template from [data-template] attribute
|
|
131
|
+
// Also checks file.frontMatter.layout as a fallback
|
|
132
|
+
await applyTemplate({file, store, allowType: ['.html']});
|
|
133
|
+
|
|
134
|
+
// PLUGIN: Replace `[data-include]` in files
|
|
135
|
+
// Runs after template: includes inside the template get resolved
|
|
136
|
+
await replaceInclude({file, store, allowType: ['.html']});
|
|
137
|
+
|
|
138
|
+
// PLUGIN: Repeat elements for each item in a collection
|
|
139
|
+
// Runs second: repeat generates DOM from data, resolving collection variables in attributes
|
|
140
|
+
// Must run before components so repeated custom elements get expanded individually
|
|
141
|
+
await repeatCollection({file, data, store, allowType: ['.html']});
|
|
142
|
+
|
|
143
|
+
// PLUGIN: Replace custom elements and data-component elements with templates
|
|
144
|
+
// Runs third: components expand templates with attribute values (their own ${var} replacement)
|
|
145
|
+
await replaceComponents({file, store, data, allowType: ['.html']});
|
|
146
|
+
|
|
147
|
+
// PLUGIN: Render all ES6 template strings
|
|
148
|
+
// Runs last: resolves ${var} across the fully assembled page (includes + components + repeats)
|
|
149
|
+
// Merge front matter data so page-level variables resolve alongside global data
|
|
150
|
+
const templateData = file.frontMatter ? { ...data, ...file.frontMatter } : data;
|
|
151
|
+
replaceTemplateStrings({file, data: templateData, allowType: ['.html', '.json', '.webmanifest']});
|
|
152
|
+
|
|
153
|
+
// PLUGIN: Rewrite <img> to <picture> with responsive srcset
|
|
154
|
+
await optimizeImagesRewrite({file, store, allowType: ['.html']});
|
|
155
|
+
|
|
156
|
+
// PLUGIN: Auto-detect custom elements and manage VB JS loading
|
|
157
|
+
await autoComponents({file, store, allowType: ['.html']});
|
|
158
|
+
|
|
159
|
+
// PLUGIN: Pre-render Declarative Shadow DOM for web components
|
|
160
|
+
await declarativeShadowDom({file, store, allowType: ['.html']});
|
|
161
|
+
|
|
162
|
+
// PLUGIN: Add missing `http://` to user-added external link `[href]` values (`[href="www.xxxx.com"]`)
|
|
163
|
+
await replaceMissingExternalLinkProtocol({file, allowType: ['.html']});
|
|
164
|
+
|
|
165
|
+
// PLUGIN: Replace `[data-inline]` with external `<link>` and `<script>` tags
|
|
166
|
+
await replaceInline({file, store, allowType: ['.html']});
|
|
167
|
+
|
|
168
|
+
// PLUGIN: Find `<a>` tags whose [href] value matches the current page (link active state)
|
|
169
|
+
setActiveLinks({file, allowType: ['.html']});
|
|
170
|
+
|
|
171
|
+
// PLUGIN: Compile grouped CSS or JS for bundling
|
|
172
|
+
bundleAdd({file, store, allowType: ['.html']});
|
|
173
|
+
|
|
174
|
+
// PLUGIN: Minify Source
|
|
175
|
+
await minifySrc({file, disallowType: ['.json', '.webmanifest']});
|
|
176
|
+
|
|
177
|
+
// Restore base64-encoded code-block content from escape-code-blocks plugin.
|
|
178
|
+
// Must run LAST — after all JSDOM-based plugins have finished processing.
|
|
179
|
+
if (file.src.includes('data-cook-esc')) {
|
|
180
|
+
file.src = file.src.replace(/<code-block([^>]*) data-cook-esc="([^"]+)"([^>]*)><\/code-block>/g,
|
|
181
|
+
(_, before, b64, after) => {
|
|
182
|
+
const decoded = Buffer.from(b64, 'base64').toString('utf-8');
|
|
183
|
+
return `<code-block${before}${after}>${decoded}</code-block>`;
|
|
184
|
+
});
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
// Write new, modified source back to the file
|
|
188
|
+
await updatePage(file);
|
|
189
|
+
|
|
190
|
+
return fileName;
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
// PLUGIN: Generate content-only fragments for SPA navigation
|
|
194
|
+
await generateFragments();
|
|
195
|
+
|
|
196
|
+
// PLUGIN: Generate multi-format output (markdown, JSON, feed, llms.txt)
|
|
197
|
+
await generateFormats({store, data});
|
|
198
|
+
|
|
199
|
+
// PLUGIN: Create `sitemap.xml` in the created `/dist` folder
|
|
200
|
+
await generateSitemap();
|
|
201
|
+
|
|
202
|
+
// PLUGIN: Build and create bundled file
|
|
203
|
+
await bundleBuild({store});
|
|
204
|
+
|
|
205
|
+
// CUSTOM PLUGINS: Run custom user plugins after file loop
|
|
206
|
+
await customPlugins({store, data, plugins: plugins.after, log: 'After' });
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
// Run build
|
|
212
|
+
(async () => await new Build().init())();
|
package/scripts/dev.js
ADDED
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
// IMPORTS
|
|
2
|
+
// -----------------------------
|
|
3
|
+
import browserSyncLib from 'browser-sync';
|
|
4
|
+
import chalk from 'chalk';
|
|
5
|
+
import { execSync } from 'node:child_process';
|
|
6
|
+
import { existsSync } from 'node:fs';
|
|
7
|
+
import path from 'node:path';
|
|
8
|
+
import { fileURLToPath } from 'node:url';
|
|
9
|
+
|
|
10
|
+
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
|
11
|
+
const buildScript = path.resolve(__dirname, 'build.js');
|
|
12
|
+
|
|
13
|
+
const browserSync = browserSyncLib.create('Dev Server');
|
|
14
|
+
|
|
15
|
+
// CONFIG
|
|
16
|
+
import { distPath, srcPath, startPath, fragments, watch, watchDefaults, watchReplace } from './utils/config/config.js';
|
|
17
|
+
|
|
18
|
+
// FILES TO WATCH
|
|
19
|
+
// The default file paths to watch
|
|
20
|
+
let watchFiles = watchDefaults;
|
|
21
|
+
// Did user add custom paths to `watch` in `/config/main.js`?
|
|
22
|
+
const userAddedWatch = watch && watch.length;
|
|
23
|
+
// If user set `watchReplace` option to TRUE, replace the defaults
|
|
24
|
+
if (watchReplace && userAddedWatch) watchFiles = watch;
|
|
25
|
+
// Otherwise, add their paths in addition to the defaults
|
|
26
|
+
else if (userAddedWatch) watchFiles = [...watchFiles, ...watch];
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
// CONTENT NEGOTIATION MIDDLEWARE
|
|
30
|
+
// -----------------------------
|
|
31
|
+
// Mirrors the Cloudflare Worker routing logic for local development.
|
|
32
|
+
// Serves fragments, markdown, and JSON based on request headers.
|
|
33
|
+
function contentNegotiationMiddleware(req, res, next) {
|
|
34
|
+
const accept = req.headers['accept'] || '';
|
|
35
|
+
const requestedWith = req.headers['x-requested-with'] || '';
|
|
36
|
+
const url = req.url;
|
|
37
|
+
|
|
38
|
+
// Fragment request (html-star navigation)
|
|
39
|
+
if (requestedWith.toLowerCase() === 'htmlstar') {
|
|
40
|
+
const fragmentFilename = (fragments && fragments.filename) || '_fragment.html';
|
|
41
|
+
const basePath = url.replace(/\/$/, '') || '';
|
|
42
|
+
const fragmentPath = `${basePath}/${fragmentFilename}`;
|
|
43
|
+
const fullPath = path.resolve(`${distPath}${fragmentPath}`);
|
|
44
|
+
if (existsSync(fullPath)) {
|
|
45
|
+
req.url = fragmentPath;
|
|
46
|
+
return next();
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
// Markdown request
|
|
51
|
+
if (accept.includes('text/markdown')) {
|
|
52
|
+
const basePath = url.replace(/\/$/, '') || '';
|
|
53
|
+
const mdPath = `/md${basePath}/index.md`;
|
|
54
|
+
const fullPath = path.resolve(`${distPath}${mdPath}`);
|
|
55
|
+
if (existsSync(fullPath)) {
|
|
56
|
+
req.url = mdPath;
|
|
57
|
+
return next();
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
// JSON request (explicit, not browser default)
|
|
62
|
+
if (accept.includes('application/json') && !accept.includes('text/html')) {
|
|
63
|
+
const basePath = url.replace(/\/$/, '') || '';
|
|
64
|
+
const jsonPath = `/api${basePath || '/index'}.json`;
|
|
65
|
+
const fullPath = path.resolve(`${distPath}${jsonPath}`);
|
|
66
|
+
if (existsSync(fullPath)) {
|
|
67
|
+
req.url = jsonPath;
|
|
68
|
+
return next();
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
next();
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
// INIT BROWSER-SYNC SERVER
|
|
77
|
+
// -----------------------------
|
|
78
|
+
browserSync.init({
|
|
79
|
+
// Hide BrowserSync popup messages in UI
|
|
80
|
+
notify: false,
|
|
81
|
+
// Open the site in the browser automatically
|
|
82
|
+
open: false,
|
|
83
|
+
// The `localhost` port number to use (Defaults to `:3000`)
|
|
84
|
+
port: parseInt(process.env.COOK_DEV_PORT, 10) || 3000,
|
|
85
|
+
// Where to serve `localhost` from (dev files)
|
|
86
|
+
server: {
|
|
87
|
+
baseDir: distPath,
|
|
88
|
+
index: startPath,
|
|
89
|
+
// Content negotiation middleware for fragment/markdown/JSON routing
|
|
90
|
+
middleware: [contentNegotiationMiddleware],
|
|
91
|
+
},
|
|
92
|
+
// Automatically reload on `.css`, `.html`, and `.js` file changes
|
|
93
|
+
//watch: true,
|
|
94
|
+
});
|
|
95
|
+
browserSync.emitter.on('init', () => {
|
|
96
|
+
console.log(`\n${ chalk.blue('[Browsersync]') } ${ chalk.blue.bold('`npm run dev`') }\n`);
|
|
97
|
+
});
|
|
98
|
+
|
|
99
|
+
// WATCH DEV FILES FOR LIVERELOAD
|
|
100
|
+
// --------------------------------
|
|
101
|
+
// Watch changes to `/src` files and run the build process to copy
|
|
102
|
+
// to `/dist` equivalent. This way we can run livereload on `/dist` to
|
|
103
|
+
// view replaced includes, and to avoid mutating `/src` files directly.
|
|
104
|
+
watchFiles.forEach(path => {
|
|
105
|
+
// Watch `/src` files for changes
|
|
106
|
+
browserSync.watch(`${srcPath}${path}`).on('change', file => {
|
|
107
|
+
// Store the changed file as an environment variable.
|
|
108
|
+
// Then when we run the build process below,
|
|
109
|
+
// we'll use this now-defined variable to dictate
|
|
110
|
+
// whether the whole build process is run, or just against
|
|
111
|
+
// this changed file.
|
|
112
|
+
process.env.DEV_CHANGED_PAGE = file;
|
|
113
|
+
// Run the build process
|
|
114
|
+
execSync(`NODE_ENV=development node "${buildScript}"`, {stdio: 'inherit'});
|
|
115
|
+
// Reload changed page
|
|
116
|
+
const fileDist = file.replace(`${srcPath}/`, `${distPath}/`);
|
|
117
|
+
browserSync.reload(fileDist);
|
|
118
|
+
});
|
|
119
|
+
});
|
|
@@ -0,0 +1,226 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @file apply-template.js
|
|
3
|
+
* @description Apply layout templates to HTML pages via [data-template].
|
|
4
|
+
*
|
|
5
|
+
* When a page's <html> or <body> element has data-template="name",
|
|
6
|
+
* the page's content is extracted and injected into the named layout
|
|
7
|
+
* template from src/layouts/{name}.html.
|
|
8
|
+
*
|
|
9
|
+
* Page metadata (title, description, etc.) is extracted from the source
|
|
10
|
+
* page and made available as ${var} placeholders in the template.
|
|
11
|
+
*
|
|
12
|
+
* Must run BEFORE replaceInclude so that includes inside templates
|
|
13
|
+
* are resolved normally.
|
|
14
|
+
*/
|
|
15
|
+
|
|
16
|
+
// IMPORTS
|
|
17
|
+
// -----------------------------
|
|
18
|
+
import chalk from 'chalk';
|
|
19
|
+
import { promises as fs } from 'node:fs';
|
|
20
|
+
import { existsSync } from 'node:fs';
|
|
21
|
+
import path from 'node:path';
|
|
22
|
+
import Util from '../utils/util/util.js';
|
|
23
|
+
|
|
24
|
+
// Config
|
|
25
|
+
import { srcPath, distPath } from '../utils/config/config.js';
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
// DEFINE
|
|
29
|
+
// -----------------------------
|
|
30
|
+
class ApplyTemplate {
|
|
31
|
+
constructor({ file, store, allowType, disallowType }) {
|
|
32
|
+
this.opts = { file, allowType, disallowType };
|
|
33
|
+
this.file = file;
|
|
34
|
+
this.store = store;
|
|
35
|
+
this.allowType = allowType;
|
|
36
|
+
this.disallowType = disallowType;
|
|
37
|
+
|
|
38
|
+
// Reuse the layout cache from process-markdown
|
|
39
|
+
if (!this.store.cachedLayouts) {
|
|
40
|
+
this.store.cachedLayouts = {};
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
// INIT
|
|
45
|
+
// -----------------------------
|
|
46
|
+
async init() {
|
|
47
|
+
// Early Exit: File type not allowed
|
|
48
|
+
const allowed = Util.isAllowedType(this.opts);
|
|
49
|
+
if (!allowed) return;
|
|
50
|
+
|
|
51
|
+
// Check for data-template attribute on <html> or <body>,
|
|
52
|
+
// falling back to file.frontMatter.layout if present
|
|
53
|
+
const templateName = this.findTemplateName()
|
|
54
|
+
|| (this.file.frontMatter && this.file.frontMatter.layout)
|
|
55
|
+
|| null;
|
|
56
|
+
if (!templateName) return;
|
|
57
|
+
|
|
58
|
+
// Load the template
|
|
59
|
+
const templateContent = await this.getTemplate(templateName);
|
|
60
|
+
if (!templateContent) return;
|
|
61
|
+
|
|
62
|
+
// Extract page metadata and content from the source page
|
|
63
|
+
const pageData = this.extractPageData();
|
|
64
|
+
|
|
65
|
+
// Merge page content into the template
|
|
66
|
+
this.file.src = this.applyTemplate(templateContent, pageData);
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/**
|
|
70
|
+
* Find the data-template attribute value from the page source.
|
|
71
|
+
* Checks <html data-template="..."> and <body data-template="...">.
|
|
72
|
+
* Uses regex to avoid a full DOM parse at this stage.
|
|
73
|
+
* @returns {string|null} Template name or null
|
|
74
|
+
*/
|
|
75
|
+
findTemplateName() {
|
|
76
|
+
// Match data-template on <html> or <body>
|
|
77
|
+
const match = this.file.src.match(/<(?:html|body)\s[^>]*data-template="([^"]+)"/i);
|
|
78
|
+
return match ? match[1] : null;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/**
|
|
82
|
+
* Load a template file from src/layouts/ (with caching).
|
|
83
|
+
* @param {string} name - Template name (e.g., "default", "product")
|
|
84
|
+
* @returns {string|null} Template content or null
|
|
85
|
+
*/
|
|
86
|
+
async getTemplate(name) {
|
|
87
|
+
// Check cache
|
|
88
|
+
if (this.store.cachedLayouts[name] !== undefined) {
|
|
89
|
+
return this.store.cachedLayouts[name];
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
// Build possible paths
|
|
93
|
+
const fileName = name.endsWith('.html') ? name : `${name}.html`;
|
|
94
|
+
const candidates = [
|
|
95
|
+
path.resolve(`${srcPath}/layouts/${fileName}`),
|
|
96
|
+
path.resolve(`${srcPath}/layouts/${name}/index.html`),
|
|
97
|
+
];
|
|
98
|
+
|
|
99
|
+
for (const candidate of candidates) {
|
|
100
|
+
if (existsSync(candidate)) {
|
|
101
|
+
try {
|
|
102
|
+
const content = await fs.readFile(candidate, 'utf-8');
|
|
103
|
+
this.store.cachedLayouts[name] = content;
|
|
104
|
+
return content;
|
|
105
|
+
} catch {
|
|
106
|
+
// Continue to next candidate
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
// Not found
|
|
112
|
+
this.store.cachedLayouts[name] = null;
|
|
113
|
+
return null;
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/**
|
|
117
|
+
* Extract metadata and content from the source page.
|
|
118
|
+
* Pulls title and description from <head>, and content from <body>.
|
|
119
|
+
* Also collects any data-* attributes from the data-template element
|
|
120
|
+
* as additional template variables.
|
|
121
|
+
* @returns {Object} { title, description, content, ...customVars }
|
|
122
|
+
*/
|
|
123
|
+
extractPageData() {
|
|
124
|
+
const data = {};
|
|
125
|
+
|
|
126
|
+
// Start with front matter data if available (from process-html-frontmatter plugin)
|
|
127
|
+
if (this.file.frontMatter) {
|
|
128
|
+
Object.assign(data, this.file.frontMatter);
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
// Extract <title> content (overrides front matter title if both present)
|
|
132
|
+
const titleMatch = this.file.src.match(/<title>([^<]*)<\/title>/i);
|
|
133
|
+
if (titleMatch) data.title = titleMatch[1];
|
|
134
|
+
|
|
135
|
+
// Extract <meta name="description"> content
|
|
136
|
+
const descMatch = this.file.src.match(/<meta\s+name="description"\s+content="([^"]*)"/i);
|
|
137
|
+
if (descMatch) data.description = descMatch[1];
|
|
138
|
+
|
|
139
|
+
// Extract data-* attributes from the element with data-template
|
|
140
|
+
// These become template variables (e.g., data-author="Kim" → ${author})
|
|
141
|
+
const templateElMatch = this.file.src.match(/<(?:html|body)\s([^>]*data-template="[^"]*"[^>]*)>/i);
|
|
142
|
+
if (templateElMatch) {
|
|
143
|
+
const attrs = templateElMatch[1];
|
|
144
|
+
const attrPattern = /data-(?!template)([a-z][a-z0-9-]*)="([^"]*)"/gi;
|
|
145
|
+
let attrMatch;
|
|
146
|
+
while ((attrMatch = attrPattern.exec(attrs)) !== null) {
|
|
147
|
+
// Convert kebab-case to camelCase for template vars
|
|
148
|
+
const key = attrMatch[1].replace(/-([a-z])/g, (_, c) => c.toUpperCase());
|
|
149
|
+
data[key] = attrMatch[2];
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
// For pages with front matter (no <body> wrapper), the entire file.src IS the content
|
|
154
|
+
let rawContent;
|
|
155
|
+
if (this.file.frontMatter && !this.file.src.match(/<body[\s>]/i)) {
|
|
156
|
+
rawContent = this.file.src.trim();
|
|
157
|
+
} else {
|
|
158
|
+
// Extract <body> inner content (the page content to inject)
|
|
159
|
+
// If <main> exists, use its innerHTML; otherwise use the full <body> innerHTML
|
|
160
|
+
const mainMatch = this.file.src.match(/<main[^>]*>([\s\S]*)<\/main>/i);
|
|
161
|
+
if (mainMatch) {
|
|
162
|
+
rawContent = mainMatch[1].trim();
|
|
163
|
+
} else {
|
|
164
|
+
const bodyMatch = this.file.src.match(/<body[^>]*>([\s\S]*)<\/body>/i);
|
|
165
|
+
if (bodyMatch) {
|
|
166
|
+
rawContent = bodyMatch[1].trim();
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
// Extract named slots from <template slot="name"> elements.
|
|
172
|
+
// These provide content for ${slot:name} placeholders in layouts.
|
|
173
|
+
// Remaining content (after slot extraction) becomes ${content}.
|
|
174
|
+
if (rawContent) {
|
|
175
|
+
const slotPattern = /<template\s+slot="([^"]+)">([\s\S]*?)<\/template>/gi;
|
|
176
|
+
let slotMatch;
|
|
177
|
+
while ((slotMatch = slotPattern.exec(rawContent)) !== null) {
|
|
178
|
+
data[`slot:${slotMatch[1]}`] = slotMatch[2].trim();
|
|
179
|
+
}
|
|
180
|
+
// Remove <template slot="..."> elements from content
|
|
181
|
+
data.content = rawContent.replace(slotPattern, '').trim();
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
return data;
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
/**
|
|
188
|
+
* Inject page data into the template.
|
|
189
|
+
* Replaces ${content} and other ${var} placeholders.
|
|
190
|
+
* @param {string} template - Template HTML
|
|
191
|
+
* @param {Object} pageData - Extracted page data
|
|
192
|
+
* @returns {string} Merged HTML
|
|
193
|
+
*/
|
|
194
|
+
applyTemplate(template, pageData) {
|
|
195
|
+
let html = template;
|
|
196
|
+
|
|
197
|
+
// Replace ${content} first
|
|
198
|
+
html = html.replace(/\$\{content\}/g, pageData.content || '');
|
|
199
|
+
|
|
200
|
+
// Replace other ${var} placeholders with page data
|
|
201
|
+
// Leave unmatched ones for later processing (e.g., ${siteTitle} resolved by replaceTemplateStrings)
|
|
202
|
+
// Exception: unmatched ${slot:...} placeholders are removed (no content provided for that slot)
|
|
203
|
+
html = html.replace(/\$\{([^}]+)\}/g, (match, key) => {
|
|
204
|
+
const trimmedKey = key.trim();
|
|
205
|
+
if (trimmedKey === 'content') return match; // Already replaced
|
|
206
|
+
if (pageData[trimmedKey] !== undefined) return pageData[trimmedKey];
|
|
207
|
+
// Remove unfilled slot placeholders rather than leaving them in output
|
|
208
|
+
if (trimmedKey.startsWith('slot:')) return '';
|
|
209
|
+
return match;
|
|
210
|
+
});
|
|
211
|
+
|
|
212
|
+
return html;
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
|
|
216
|
+
// EXPORT WRAPPER
|
|
217
|
+
// -----------------------------
|
|
218
|
+
static async export(opts) {
|
|
219
|
+
return new ApplyTemplate(opts).init();
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
|
|
224
|
+
// EXPORT
|
|
225
|
+
// -----------------------------
|
|
226
|
+
export default ApplyTemplate.export;
|