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.
Files changed (37) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +445 -0
  3. package/bin/cook.js +66 -0
  4. package/package.json +75 -0
  5. package/patches/jsdom-fetch-fix.js +52 -0
  6. package/scripts/build.js +212 -0
  7. package/scripts/dev.js +119 -0
  8. package/scripts/plugins/apply-template.js +226 -0
  9. package/scripts/plugins/auto-components.js +215 -0
  10. package/scripts/plugins/bundle.js +338 -0
  11. package/scripts/plugins/copy-src.js +89 -0
  12. package/scripts/plugins/create-dir-from-file.js +144 -0
  13. package/scripts/plugins/create-dist.js +55 -0
  14. package/scripts/plugins/custom-plugins.js +118 -0
  15. package/scripts/plugins/declarative-shadow-dom.js +164 -0
  16. package/scripts/plugins/escape-code-blocks.js +54 -0
  17. package/scripts/plugins/generate-formats.js +361 -0
  18. package/scripts/plugins/generate-fragments.js +126 -0
  19. package/scripts/plugins/generate-sitemap-xml.js +216 -0
  20. package/scripts/plugins/minify-src.js +253 -0
  21. package/scripts/plugins/optimize-images.js +389 -0
  22. package/scripts/plugins/process-html-frontmatter.js +75 -0
  23. package/scripts/plugins/process-markdown.js +384 -0
  24. package/scripts/plugins/repeat-collection.js +296 -0
  25. package/scripts/plugins/replace-components.js +496 -0
  26. package/scripts/plugins/replace-external-link-protocol.js +171 -0
  27. package/scripts/plugins/replace-include.js +273 -0
  28. package/scripts/plugins/replace-inline.js +217 -0
  29. package/scripts/plugins/replace-template-strings.js +121 -0
  30. package/scripts/plugins/set-active-links.js +175 -0
  31. package/scripts/utils/config/config.js +277 -0
  32. package/scripts/utils/get-src/get-src.js +241 -0
  33. package/scripts/utils/logger/logger.js +47 -0
  34. package/scripts/utils/performance/performance.js +35 -0
  35. package/scripts/utils/spinner/spinner.js +112 -0
  36. package/scripts/utils/timer/timer.js +40 -0
  37. package/scripts/utils/util/util.js +719 -0
@@ -0,0 +1,175 @@
1
+ /**
2
+ * @file set-active-links.js
3
+ * @description Add `[data-active]` state to `<a>` tags whose `[href]` value matches the current page
4
+ */
5
+
6
+ // IMPORT
7
+ // -----------------------------
8
+ import chalk from 'chalk';
9
+ import Util from '../utils/util/util.js';
10
+
11
+ // Config
12
+ import { distPath, activeLink } from '../utils/config/config.js';
13
+
14
+
15
+ // DEFINE
16
+ // -----------------------------
17
+ /**
18
+ * @description Add `[data-active]` state to `<a>` tags whose `[href]` value matches the current page
19
+ * @param {Object} obj - Deconstructed options object
20
+ * @property {Object} obj.file - The current file's info (name, extension, path, src, etc.)
21
+ * @property {Array} [obj.allowType] - Allowed file types (Opt-in)
22
+ * @property {Array} [obj.disallowType] - Disallowed file types (Opt-out)
23
+ */
24
+ class SetActiveLinks {
25
+ constructor({file, allowType, disallowType, excludePaths = []}) {
26
+ this.opts = {file, allowType, disallowType, excludePaths};
27
+ this.file = file;
28
+ this.allowType = allowType;
29
+ this.disallowType = disallowType;
30
+ this.excludePaths = excludePaths;
31
+
32
+ // Store holder for total # of replaced items
33
+ this.total = { active:0, activeParent:0 };
34
+
35
+ // Init terminal logging
36
+ if (process.env.LOGGER) Util.initLogging.call(this);
37
+ }
38
+
39
+ // INIT
40
+ // -----------------------------
41
+ // Note: `process.env.DEV_CHANGED_PAGE` is defined in `browserSync.watch()` in dev.js
42
+ async init() {
43
+ // Early Exit: File type not allowed
44
+ const allowed = Util.isAllowedType(this.opts);
45
+ if (!allowed) return;
46
+
47
+ // START LOGGING
48
+ this.startLog();
49
+
50
+ // Destructure options
51
+ const { file } = this;
52
+
53
+ // Make source traversable with JSDOM
54
+ let dom = Util.jsdom.dom({src: file.src});
55
+
56
+ // Find <a> tags and add active state
57
+ // if their [href] matches the current page url
58
+ // Note: Using `a[href]` instead of just `a` as selector, since a user may omit the `[href]` attribute
59
+ const $links = dom.window.document.querySelectorAll('a[href]');
60
+ $links.forEach((link,i) => this.setActive({file, link}));
61
+
62
+ // Store updated file source
63
+ file.src = Util.setSrc({dom});
64
+
65
+ // END LOGGING
66
+ this.endLog();
67
+ }
68
+
69
+ // HELPER METHODS
70
+ // -----------------------------
71
+
72
+ /**
73
+ * @description Set <a> tags to 'active' state if their [href] value file name matches the current file's name, or a parent-state iF an ancestor of the current page.
74
+ * @param {Object} opts - The arguments object
75
+ * @property {Object} file - The current file's props (ext,name,path,name)
76
+ * @property {Object} link - The current <a> tag being evaluated
77
+ * @private
78
+ */
79
+ setActive({file, link}) {
80
+ const currPath = Util.getFileName(file.path, distPath);
81
+ const linkPath = Util.getFileName(link.href, distPath);
82
+ const isParent = this.linkIsParent(file.path, linkPath);
83
+ if (linkPath === currPath) this.setActiveLink(link);
84
+ else if (isParent) this.setParentActiveLink(link);
85
+ }
86
+
87
+ /**
88
+ * @description Add active state to link as attribute or class based on user preference.
89
+ * @param {Object} link - The DOM element to modify
90
+ * @private
91
+ */
92
+ setActiveLink(link) {
93
+ // Use user-defined states or a default
94
+ const isAttribute = activeLink && (activeLink.type === 'attr' || activeLink.type === 'attribute');
95
+ // If user specified using an attribute, set the state via attribute
96
+ if (isAttribute) link.setAttribute(`data-${Util.attr.active}`,'');
97
+ // Or set as a class value
98
+ else link.classList.add(Util.attr.active);
99
+ // Increment counter for display in terminal logging
100
+ this.total.active += 1;
101
+ }
102
+
103
+ /**
104
+ * @description Add parent-active state to link as attribute or class based on user preference.
105
+ * @param {Object} link - The DOM element to modify
106
+ * @private
107
+ */
108
+ setParentActiveLink(link) {
109
+ // Use user-defined states or a default
110
+ const isAttribute = activeLink && (activeLink.type === 'attr' || activeLink.type === 'attribute');
111
+ // If user specified using an attribute, set the state via attribute
112
+ if (isAttribute) link.setAttribute(`data-${Util.attr.activeParent}`,'');
113
+ // Or set as a class value
114
+ else link.classList.add(Util.attr.activeParent);
115
+ // Increment counter for display in terminal logging
116
+ this.total.activeParent += 1;
117
+ }
118
+
119
+ /**
120
+ * @description Return true if `<a>` link's `[href]` target is a parent of the current page
121
+ * @param {String} pagePath - The full path of the current page being evaluated
122
+ * @param {String} linkPath - The current page `<a>` to evaluate
123
+ * @private
124
+ */
125
+ linkIsParent(pagePath, linkPath) {
126
+ const pagePathSplit = pagePath.split(`${distPath}/`)[1];
127
+ // Early Exit: No dist path
128
+ if (!pagePathSplit) return;
129
+ const pagePathParts = pagePathSplit.split('/');
130
+ const pagePathPartsLast = pagePathParts.pop();
131
+ // Return true if `linkPath` is one of the parts AND it is not the last part (we'll mark it as normal-active instead)
132
+ const isActivePage = linkPath === pagePathParts[pagePathParts.length - 1];
133
+ const isHierarchyPage = pagePathParts.indexOf(linkPath) > -1;
134
+ return !isActivePage && isHierarchyPage;
135
+ }
136
+
137
+
138
+ // LOGGING
139
+ // -----------------------------
140
+ // Display additional terminal logging when `process.env.LOGGER` enabled
141
+
142
+ startLog() {
143
+ // Early Exit: Logging not allowed
144
+ if (!process.env.LOGGER) return;
145
+ // Start Spinner
146
+ this.loading.start(chalk.magenta('Adding Link Active States'));
147
+ // Start timer
148
+ this.timer.start();
149
+ }
150
+
151
+ endLog() {
152
+ // Early Exit: Logging not allowed
153
+ if (!process.env.LOGGER) return;
154
+ // Stop Spinner and Timer
155
+ const {active,activeParent} = this.total;
156
+ if (active > 0 || activeParent > 0) {
157
+ this.loading.stop(`Set active links: ${chalk.magenta(active)} active and ${chalk.magenta(activeParent)} parent ${this.timer.end()}`);
158
+ }
159
+ // If no matches found, stop logger but don't show line in terminal
160
+ else this.loading.kill();
161
+ }
162
+
163
+
164
+ // EXPORT WRAPPER
165
+ // -----------------------------
166
+ // Export function wrapper instead of class for `build.js` simplicity
167
+ static async export(opts) {
168
+ return new SetActiveLinks(opts).init();
169
+ }
170
+ }
171
+
172
+
173
+ // EXPORT
174
+ // -----------------------------
175
+ export default SetActiveLinks.export;
@@ -0,0 +1,277 @@
1
+ // IMPORTS
2
+ // ----------------------------------
3
+ import fs from 'node:fs';
4
+ import merge from 'lodash.merge';
5
+ import { pathToFileURL } from 'node:url';
6
+
7
+ const cwd = process.cwd();
8
+
9
+ // GET USER'S CONFIG
10
+ // -----------------------------
11
+ // Store user's config, or set default if user omitted
12
+ const userConfigPath = `${cwd}/config/main.js`;
13
+ const userConfigPathExists = fs.existsSync(userConfigPath);
14
+ let userConfig = {};
15
+ if (userConfigPathExists) {
16
+ const userConfigModule = await import(pathToFileURL(userConfigPath));
17
+ userConfig = userConfigModule.default || userConfigModule;
18
+ }
19
+
20
+
21
+ // DEFINE DEFAULT CONFIG
22
+ // -----------------------------
23
+ const defaultConfig = {
24
+
25
+ // REQUIRED (CORE BUILD PROCESS REQUIREMENTS)
26
+ // --------------------------------------------
27
+
28
+ // Convert xxxx.html files to xxxx/index.html
29
+ // NOTE: If `disabled` set to `true`, you must add the .html extension in <a href="xxxx.html"> paths
30
+ // NOTE: `404.html` is excluded, since Firebase looks for the .html file, not a directory
31
+ convertPageToDirectory: {
32
+ disabled: false,
33
+ excludePaths: ['dist/404.html']
34
+ },
35
+ // The name of the compiled, 'public' directory (`dist`, `public`, etc.)
36
+ distPath: 'dist',
37
+ // The path to the dev source files. This is used for running the local dev livereload server.
38
+ srcPath: 'src',
39
+ // The file to load in `srcPath` if not `index.html`
40
+ startPath: 'index.html',
41
+ // The URL domain to use for the `sitemap.xml` entries
42
+ // Note: Enabling this auto-generates `sitemap.xml` in the `/dist` directory
43
+ sitemap: {
44
+ url: 'https://www.site.com',
45
+ // Exclude files from sitemap by adding the desired path regex
46
+ // Defaults are: Any `/assets` or `/includes` paths, and the root `404.html`
47
+ // excludePaths: [/\/assets/, /\/includes/, /^\/404.html/],
48
+ },
49
+
50
+
51
+ // REQUIRED (SITE-SPECIFIC CONFIG)
52
+ // ---------------------------------
53
+ // Add config items here for your own custom build plugins
54
+
55
+ // Build-Process Plugins: Add per-site plugins to use during build process.
56
+ // Note: Execution order is left-to-right, so add dependency plugins first
57
+ plugins: {
58
+ before: [],
59
+ default: [],
60
+ after: [],
61
+ },
62
+ // Default repo directory to find referenced plugins
63
+ pluginPath: 'plugins',
64
+
65
+ // CSS and JS Bundling
66
+ // NOTE: User can set `bundle: false` or `bundle: { enabled: false }`
67
+ // to disable bundling for production, even if bundle attributes are found.
68
+ bundle: {
69
+ // Path in 'dist' directory where the bundled files will be created
70
+ distPath: 'assets/bundle',
71
+ },
72
+
73
+ // Components: Replace custom elements and semantic HTML with templates
74
+ // Supports:
75
+ // - Custom elements: <site-header title="Welcome"></site-header>
76
+ // - Semantic HTML: <header data-component="header" data-title="Welcome"></header>
77
+ // Component templates use ${varName} for data and ${slot} for inner content
78
+ components: {
79
+ // Path to components directory (relative to srcPath/distPath)
80
+ path: 'components',
81
+ // Optional prefix for custom elements (e.g., 'site-' matches <site-header>)
82
+ prefix: null,
83
+ // Explicit mapping of element names to template files
84
+ // If not mapped, uses element name as filename (e.g., 'header' -> 'header.html')
85
+ mapping: {},
86
+ },
87
+
88
+ // Markdown: Convert .md files to HTML with front matter support
89
+ // Markdown files in /src are converted to HTML in /dist
90
+ // Front matter (YAML between ---) becomes template variables
91
+ markdown: {
92
+ // Default layout template to wrap content (null = basic HTML wrapper)
93
+ layout: null,
94
+ // Directory for layout templates (relative to srcPath)
95
+ layoutPath: 'layouts',
96
+ // Enable collections (group pages by directory)
97
+ collections: true,
98
+ // marked parser options
99
+ markedOptions: {
100
+ gfm: true, // GitHub Flavored Markdown
101
+ breaks: false, // Convert \n to <br>
102
+ },
103
+ },
104
+
105
+ // Auto-Components: Scan pages for custom elements and manage JS loading
106
+ // Pages using only CSS-only elements get zero VB JS.
107
+ // When a manifest is available, generates import maps for per-component loading.
108
+ autoComponents: {
109
+ enabled: false,
110
+ manifest: null,
111
+ cssOnly: [],
112
+ bundlePattern: /vanilla-breeze[^"']*\.js/,
113
+ },
114
+
115
+ // Declarative Shadow DOM: Pre-render shadow DOM content for web components
116
+ // Requires a DSD manifest (JSON mapping tag → shadow DOM HTML)
117
+ // and VB components with: if (!this.shadowRoot) this.attachShadow({ mode: 'open' })
118
+ dsd: {
119
+ enabled: false,
120
+ manifest: null,
121
+ },
122
+
123
+ // Build-only paths: directories in src/ that are used during build but should
124
+ // NOT be copied to dist/ (includes, components, layouts, etc.)
125
+ buildOnlyPaths: [],
126
+
127
+ // Formats: Generate multi-format output (markdown, JSON, Atom feed, llms.txt)
128
+ formats: {
129
+ markdown: true,
130
+ json: true,
131
+ feed: null,
132
+ llmsTxt: true,
133
+ },
134
+
135
+ // Fragments: Generate content-only HTML fragments for SPA navigation
136
+ // Each page gets a sibling _fragment.html containing the inner HTML of the selector
137
+ fragments: {
138
+ enabled: true,
139
+ selector: 'main',
140
+ filename: '_fragment.html',
141
+ },
142
+
143
+ // Repeat: Generate repeated elements from collections/arrays
144
+ // Usage: <article data-repeat="collections.blog as post">...</article>
145
+ // Supports limit and offset: "collections.blog | limit:5 | offset:2 as post"
146
+ repeat: {
147
+ // Attribute name for repeat directive
148
+ attribute: 'data-repeat',
149
+ // Remove the data-repeat attribute from output
150
+ removeAttribute: true,
151
+ },
152
+
153
+ // Images: Automatic responsive image optimization
154
+ // Generates AVIF/WebP derivatives at multiple widths, rewrites <img> to <picture>
155
+ images: {
156
+ enabled: true,
157
+ widths: [320, 640, 960, 1280, 1920],
158
+ formats: ['avif', 'webp'],
159
+ quality: { avif: 60, webp: 75, jpeg: 80, png: 80 },
160
+ sizes: '(min-width: 60rem) 960px, 100vw',
161
+ loading: 'lazy',
162
+ cache: '.cache/images',
163
+ },
164
+
165
+
166
+ // OPTIONAL
167
+ // -----------------------------
168
+
169
+ // Add regex patterns to include or exclude files from being modified once copied to the /dist directory
170
+ // For example, /dist\/manifest.json/ will include the manifest.json file, so template strings can be
171
+ // For example, /dist\/vendor/ will exclude files in /dist/vendor
172
+ // Can be single regexes: /dist\/path/ or new RegExp(/dist\path/)
173
+ // Or regexes in an array: [/dist\/path1/, new RegExp(/dist\path2/)]
174
+ // --
175
+ // INCLUDE
176
+ // -- Example: Include `/dist/manifest.json`, so template strings can be replaced.
177
+ includePaths: [
178
+ /dist\/manifest.webmanifest/,
179
+ ],
180
+ // -- Example: Exclude docs templates directory (/dist/assets/docs/)
181
+ excludePaths: [
182
+ /dist\/assets\/vendor/,
183
+ ],
184
+
185
+ // Define the 'active' state for both links whose `[href]` value matches the current page,
186
+ // as well as links who have part of the current page's url in them (parent-active state)
187
+ // By default, a `[class]` is added, with default values. The below config is not necessary,
188
+ // unless you want to change the type (attr|attribute|class), or the values
189
+ // activeLink: {
190
+ // // Default: class
191
+ // type: 'class',
192
+ // // Default: active
193
+ // activeState: 'active',
194
+ // // Default: active-parent
195
+ // parentState: 'active-parent',
196
+ // },
197
+
198
+ // Change the default [attribute] for includes and inline link/scripts
199
+ //includeAttr: 'include',
200
+ //inlineAttr: 'inline',
201
+
202
+ // Live reload dev browser when these files change
203
+ // Note: These are the default paths. Paths added by the user in their `/config/main.js` file as the `watch: []` property are added *in addition* to these.
204
+ // However, they may set the `watchReplace` option listed below, which will only watch their specified options and not the defaults.
205
+ watchDefaults: [
206
+ '/assets/css/*.css',
207
+ '/**/*.html',
208
+ '/assets/plugin/**/*.css',
209
+ '/assets/plugin/**/*.js',
210
+ ],
211
+ // User-added watched files (optional)
212
+ // Note: Only added here for documentation. Would only be added to user's config file.
213
+ //watch: [],
214
+ // Set this option to only watch the paths listed in this config file and not the default paths.
215
+ //watchReplace: true,
216
+
217
+ // customData: 'getWordpressData',
218
+ // babelOpts: {
219
+ // "plugins": ["@babel/plugin-transform-classes"],
220
+ // "presets": [
221
+ // ["@babel/preset-env", {
222
+ // "targets": {
223
+ // "browsers": [
224
+ // "> 1%",
225
+ // "last 2 versions",
226
+ // "not ie <= 11"
227
+ // ]
228
+ // }
229
+ // }]
230
+ // ]
231
+ // }
232
+ };
233
+
234
+
235
+ // COMBINE CONFIGS
236
+ // -----------------------------
237
+ // NOTE: Using Lodash `merge` instead of `Object.assign` because,
238
+ // there will be child objects and arrays, which would override
239
+ // instead of combine with the default versions.
240
+ const config = merge({}, defaultConfig, userConfig);
241
+
242
+
243
+
244
+ // EXPORT
245
+ // -----------------------------
246
+ export default config;
247
+
248
+ // Named exports for destructuring imports
249
+ export const {
250
+ activeLink,
251
+ autoComponents,
252
+ buildOnlyPaths,
253
+ bundle,
254
+ components,
255
+ convertPageToDirectory,
256
+ distPath,
257
+ dsd,
258
+ excludePaths,
259
+ formats,
260
+ fragments,
261
+ images,
262
+ includeAttr,
263
+ includePaths,
264
+ inlineAttr,
265
+ markdown,
266
+ minifyHtmlConfigCustom,
267
+ plugins,
268
+ pluginPath,
269
+ repeat,
270
+ replaceExternalLinkProtocol,
271
+ sitemap,
272
+ srcPath,
273
+ startPath,
274
+ watch,
275
+ watchDefaults,
276
+ watchReplace,
277
+ } = config;
@@ -0,0 +1,241 @@
1
+ /**
2
+ * @file get-src.js
3
+ * @description Get allowed source files for modification
4
+ */
5
+
6
+ // IMPORTS
7
+ // -----------------------------
8
+ import fs from 'node:fs/promises';
9
+ import { pathToFileURL } from 'node:url';
10
+ import { existsSync } from 'node:fs';
11
+ import Logger from '../logger/logger.js';
12
+ import Util from '../util/util.js';
13
+
14
+ // CONFIG
15
+ import { includePaths, excludePaths, distPath, srcPath } from '../config/config.js';
16
+
17
+ const cwd = process.cwd();
18
+
19
+ // DATA STORE
20
+ const userDataPath = `${cwd}/config/data.js`;
21
+ const userDataPathExists = existsSync(userDataPath);
22
+ let data = {};
23
+ if (userDataPathExists) {
24
+ const dataModule = await import(pathToFileURL(userDataPath));
25
+ const exported = dataModule.default || dataModule;
26
+ data = typeof exported === 'function' ? await exported() : exported;
27
+ }
28
+
29
+
30
+ // EXPORT
31
+ // -----------------------------
32
+ export {
33
+ getDynamicFiles,
34
+ getSrcConfig,
35
+ getSrcFiles,
36
+ getSrcImages
37
+ };
38
+
39
+
40
+ // PUBLIC METHODS
41
+ // -----------------------------
42
+
43
+ /**
44
+ * @description If the user added dynamic page information to the correct property
45
+ * in the data store, combine those pages with the static, manual .html pages.
46
+ * @param {Array} files - The array of user-created static .html file paths
47
+ * @returns {Array}
48
+ * @private
49
+ */
50
+ function getDynamicFiles(files) {
51
+ // Early Exit: User did not add dynamic pages to the data store or it was malformed
52
+ if (!data || !data.dynamicPages || !data.dynamicPages.length) return files;
53
+ // Otherwise, combine the the user's static .html pages with their dynamic pages
54
+ // whose path and source is stored, but does not exist as an .html file yet
55
+ return [...files, ...data.dynamicPages].flat();
56
+ }
57
+
58
+
59
+ /**
60
+ * @description - Store information for use in build plugins based on the current file
61
+ * @param {Object} Opts - Argument object
62
+ * @property {String} fileName - The filename of the targeted file
63
+ * @property {String} [excludeSrc] - Complie file meta without opening the file if you don't need the source
64
+ * @returns {Object}
65
+ * @private
66
+ */
67
+ async function getSrcConfig({fileName, excludeSrc = false }) {
68
+ // Early Exit: No file name given
69
+ if (!fileName) return;
70
+ // Init obj
71
+ let file = {};
72
+
73
+ // Store if it is a dynamic page
74
+ const isDynamic = typeof fileName !== 'string';
75
+ let dynamicSrc;
76
+
77
+ // IF A DYNAMIC PAGE
78
+ // If a dynamically-generated page, `fileName` is an object instead of a string path.
79
+ // Therefore, we need to get and format the dynamic object's path into the format we need,
80
+ // namely: dist_path/file_path
81
+ if (isDynamic) {
82
+ // Store source string since we're overriding the object
83
+ dynamicSrc = fileName.src;
84
+ // Check if path is already formatted to include the `dist` path
85
+ const regex = new RegExp(`^${distPath}`);
86
+ const path = fileName.path.match(regex) ? fileName.path : `${distPath}${fileName.path}`;
87
+ fileName = `${path}/index.html`;
88
+ }
89
+
90
+
91
+ // Store filename parts
92
+ let {ext,name,nameIfIndex} = Util.getFileParts(fileName);
93
+ file.ext = ext;
94
+ file.name = name;
95
+ file.nameIfIndex = nameIfIndex;
96
+ file.path = fileName;
97
+ if (isDynamic) file.isDynamic = true;
98
+
99
+ // Early Exit: Return the file meta details but skip the source
100
+ if (excludeSrc) return file;
101
+
102
+ // STORE FILE SOURCE
103
+ // If a dynamic page, just use the source in memory
104
+ if (isDynamic) file.src = dynamicSrc;
105
+ // Otherwise, it's a static .html page
106
+ // Get and read the file to store its page source
107
+ else file.src = await fs.readFile(fileName, 'utf-8');
108
+
109
+ // REMOVE COMMENTS
110
+ // Sanitize comments that have non-closing html elements in them. JSDOM will try to close it in the DOM
111
+ // but since there is no starting tag (it's in the comment) it will break the dom
112
+ file.src = removeCommentTags(file.src);
113
+
114
+ // Return file info
115
+ return file;
116
+ }
117
+
118
+ /**
119
+ * @description - Return all allowed files for the build process
120
+ * @param {Object} cb - The callback function once the files have been grouped
121
+ * @private
122
+ */
123
+ async function getSrcFiles() {
124
+ // Note: `process.env.DEV_CHANGED_PAGE` is defined in `browserSync.watch()` in dev.js
125
+
126
+ // Define files var
127
+ let files;
128
+
129
+ // FILE CHANGE
130
+ // If only a single page was updated, just run build process on it
131
+ // Note: If the page was an include, we need to rebuild all pages.
132
+ // Other pages may have had the include, but has since been replaced w/ static content
133
+ const isValidPageChange = Util.validatePageChange();
134
+ if (isValidPageChange) {
135
+ const getDistVersionOfChangedPage = process.env.DEV_CHANGED_PAGE.replace(srcPath, distPath);
136
+ files = [getDistVersionOfChangedPage];
137
+ }
138
+ // FULL BUILD
139
+ // Otherwise, find all allowed files, loop through them, and run the build plugins on them
140
+ else {
141
+ // Allowed page types
142
+ const userAllowedPaths = validatePaths(includePaths);
143
+ // Disallowed page types
144
+ // /dist/assets/scripts/vendor - Skip 3rd-party vendor files
145
+ const defaultExcludedPaths = [new RegExp(`${distPath}\/assets\/scripts\/vendor`)];
146
+ const userExcludedPaths = validatePaths(excludePaths);
147
+ const excludedPaths = [...defaultExcludedPaths, ...userExcludedPaths];
148
+ // Allowed page extensions
149
+ const allowedExt = ['css','html','js'];
150
+ // Get files in `/dist`
151
+ files = Util.getPaths(distPath, distPath, excludedPaths);
152
+ // Get only the allowed files by extension (.css, .html)
153
+ files = files.filter(fileName => manualAllow(fileName, userAllowedPaths) || Util.isExtension(fileName, allowedExt));
154
+ // Move known include files to the front of the array, so they are ideally built first
155
+ // before being replaced in other page files.
156
+ files = files.sort((a,b) => {
157
+ if (a.includes('/includes')) return -1;
158
+ return 1;
159
+ });
160
+ }
161
+ // Run tasks on matched files
162
+ return files;
163
+ }
164
+
165
+ /**
166
+ * @description - Return all allowed images for the build process
167
+ * @param {Object} cb - The callback function once the images have been grouped
168
+ * @private
169
+ */
170
+ async function getSrcImages(cb) {
171
+ // Show terminal message: Start
172
+ Logger.header('\nImage Tasks');
173
+
174
+ // Disallowed page types
175
+ // /dist/assets/scripts/vendor - Skip 3rd-party vendor images
176
+ const defaultExcludedPaths = [new RegExp(`${distPath}\/assets\/scripts\/vendor`)];
177
+ const userExcludedPaths = validatePaths(excludePaths);
178
+ const excludedPaths = [...defaultExcludedPaths, ...userExcludedPaths];
179
+ // Allowed page extensions
180
+ const allowedExt = ['jpg', 'jpeg', 'png', 'svg'];
181
+ // Get images in `/dist`
182
+ let images = Util.getPaths(distPath, distPath, excludedPaths);
183
+ // Get only the allowed images by extension (.css, .html)
184
+ images = images.filter(fileName => Util.isExtension(fileName, allowedExt));
185
+ // Run tasks on matched images
186
+ if (cb) cb(images);
187
+ }
188
+
189
+
190
+ // HELPER METHODS
191
+ // -----------------------------
192
+
193
+ /**
194
+ * @description Remove < and > from comments since non-closed tags
195
+ * will have the matching end tag added
196
+ */
197
+ function removeCommentTags(src) {
198
+ const commentsRegex = /\/\*[\s\S]*?\*\/|([^\\:]|^)\/\/.*$/gm;
199
+ const matches = src.match(commentsRegex);
200
+ if (!matches) return src;
201
+ let replaces;
202
+ matches.forEach(m => {
203
+ replaces = m.replace('<', '').replace('>', '');
204
+ src = src.replace(m, replaces);
205
+ });
206
+ return src;
207
+ }
208
+
209
+ // HELPER METHODS
210
+ // -----------------------------
211
+
212
+ /**
213
+ * @description Validate user entry and return in array if valid
214
+ * @param {*} paths - User entry to validate. If a valid, single regex, add to array and return
215
+ * @returns {Array}
216
+ * @private
217
+ */
218
+ function manualAllow(fileName, allowedPaths) {
219
+ const allowedPathLen = allowedPaths && allowedPaths.length;
220
+ if (!allowedPathLen) return false;
221
+ for (let i=0; i<allowedPathLen; i++) {
222
+ if (allowedPaths[i].test(fileName)) return true;
223
+ }
224
+ return false;
225
+ }
226
+
227
+ /**
228
+ * @description Validate user entry and return in array if valid
229
+ * @param {*} paths - User entry to validate. If a valid, single regex, add to array and return
230
+ * @returns {Array}
231
+ * @private
232
+ */
233
+ function validatePaths(paths) {
234
+ let pathArr = [];
235
+ // If user already added as array, just use that
236
+ if (paths && paths.length) return paths;
237
+ // If user gave a single regex, add it to an array
238
+ if (paths && typeof paths === 'object' && !Array.isArray(paths) && !paths.length) pathArr.push(paths);
239
+ // Return an array with either valid user regex(es) or an empty array
240
+ return pathArr;
241
+ }