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
|
@@ -0,0 +1,496 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @file replace-components.js
|
|
3
|
+
* @description Replace custom elements and semantic HTML components with templates
|
|
4
|
+
*
|
|
5
|
+
* Supports two patterns:
|
|
6
|
+
* 1. Custom elements: <site-header title="Welcome"></site-header>
|
|
7
|
+
* 2. Semantic HTML with data-component: <header data-component="header" data-title="Welcome"></header>
|
|
8
|
+
*
|
|
9
|
+
* Component templates can use:
|
|
10
|
+
* - ${attributeName} for data from element attributes
|
|
11
|
+
* - ${slot} for inner HTML content
|
|
12
|
+
*
|
|
13
|
+
* Component templates may contain <style> blocks. These are:
|
|
14
|
+
* - Extracted before rendering (not duplicated per instance)
|
|
15
|
+
* - Deduplicated per component name
|
|
16
|
+
* - Template variables resolved with global data
|
|
17
|
+
* - Consolidated into a single <style> in <head>
|
|
18
|
+
* Authors can use native @scope and @layer for CSS scoping.
|
|
19
|
+
*/
|
|
20
|
+
|
|
21
|
+
// IMPORTS
|
|
22
|
+
// -----------------------------
|
|
23
|
+
import chalk from 'chalk';
|
|
24
|
+
import { promises as fs } from 'node:fs';
|
|
25
|
+
import { existsSync } from 'node:fs';
|
|
26
|
+
import path from 'node:path';
|
|
27
|
+
import Util from '../utils/util/util.js';
|
|
28
|
+
|
|
29
|
+
// Config
|
|
30
|
+
import { distPath, srcPath, components as componentsConfig } from '../utils/config/config.js';
|
|
31
|
+
|
|
32
|
+
// DEFINE
|
|
33
|
+
// -----------------------------
|
|
34
|
+
class ReplaceComponents {
|
|
35
|
+
constructor({ file, store, data, allowType, disallowType }) {
|
|
36
|
+
this.opts = { file, allowType, disallowType };
|
|
37
|
+
this.file = file;
|
|
38
|
+
this.store = store;
|
|
39
|
+
this.data = data || {};
|
|
40
|
+
this.allowType = allowType;
|
|
41
|
+
this.disallowType = disallowType;
|
|
42
|
+
|
|
43
|
+
// Component stats
|
|
44
|
+
this.total = 0;
|
|
45
|
+
this.replaced = [];
|
|
46
|
+
|
|
47
|
+
// Component configuration with defaults
|
|
48
|
+
this.config = {
|
|
49
|
+
path: 'components',
|
|
50
|
+
prefix: null,
|
|
51
|
+
mapping: {},
|
|
52
|
+
...componentsConfig
|
|
53
|
+
};
|
|
54
|
+
|
|
55
|
+
// Collected component styles (keyed by componentName for deduplication)
|
|
56
|
+
this.collectedStyles = {};
|
|
57
|
+
|
|
58
|
+
// Cache for component templates
|
|
59
|
+
if (!this.store.cachedComponents) this.store.cachedComponents = {};
|
|
60
|
+
|
|
61
|
+
// Init terminal logging
|
|
62
|
+
if (process.env.LOGGER) Util.initLogging.call(this);
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
// INIT
|
|
66
|
+
// -----------------------------
|
|
67
|
+
async init() {
|
|
68
|
+
// Early Exit: File type not allowed
|
|
69
|
+
const allowed = Util.isAllowedType(this.opts);
|
|
70
|
+
if (!allowed) return;
|
|
71
|
+
|
|
72
|
+
// Store string source as traversable DOM
|
|
73
|
+
const dom = Util.jsdom.dom({ src: this.file.src });
|
|
74
|
+
const document = dom.window.document;
|
|
75
|
+
|
|
76
|
+
// Find all components to replace
|
|
77
|
+
const components = this.findComponents(document);
|
|
78
|
+
this.total = components.length;
|
|
79
|
+
|
|
80
|
+
// Early Exit: No components found
|
|
81
|
+
if (this.total === 0) return;
|
|
82
|
+
|
|
83
|
+
// START LOGGING
|
|
84
|
+
this.startLog();
|
|
85
|
+
|
|
86
|
+
// Process each component
|
|
87
|
+
for (const component of components) {
|
|
88
|
+
await this.replaceComponent(component);
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
// Inject collected component styles into <head>
|
|
92
|
+
this.injectCollectedStyles(document);
|
|
93
|
+
|
|
94
|
+
// Store updated file source
|
|
95
|
+
this.file.src = Util.setSrc({ dom });
|
|
96
|
+
|
|
97
|
+
// END LOGGING
|
|
98
|
+
this.endLog();
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/**
|
|
102
|
+
* Find all component elements in the document
|
|
103
|
+
* @param {Document} document - The JSDOM document
|
|
104
|
+
* @returns {Array} Array of component info objects
|
|
105
|
+
*/
|
|
106
|
+
findComponents(document) {
|
|
107
|
+
const components = [];
|
|
108
|
+
|
|
109
|
+
// 1. Find custom elements (hyphenated tag names)
|
|
110
|
+
// Custom elements must contain a hyphen per spec
|
|
111
|
+
const allElements = document.querySelectorAll('*');
|
|
112
|
+
for (const el of allElements) {
|
|
113
|
+
const tagName = el.tagName.toLowerCase();
|
|
114
|
+
|
|
115
|
+
// Custom element (contains hyphen)
|
|
116
|
+
if (tagName.includes('-')) {
|
|
117
|
+
components.push({
|
|
118
|
+
element: el,
|
|
119
|
+
type: 'custom-element',
|
|
120
|
+
name: tagName,
|
|
121
|
+
componentName: this.resolveComponentName(tagName, 'custom-element')
|
|
122
|
+
});
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
// 2. Find elements with data-component attribute
|
|
127
|
+
const dataComponents = document.querySelectorAll('[data-component]');
|
|
128
|
+
for (const el of dataComponents) {
|
|
129
|
+
const componentAttr = el.getAttribute('data-component');
|
|
130
|
+
if (componentAttr) {
|
|
131
|
+
components.push({
|
|
132
|
+
element: el,
|
|
133
|
+
type: 'data-component',
|
|
134
|
+
name: componentAttr,
|
|
135
|
+
componentName: this.resolveComponentName(componentAttr, 'data-component')
|
|
136
|
+
});
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
return components;
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
/**
|
|
144
|
+
* Resolve component name to template file path
|
|
145
|
+
* @param {string} name - The component identifier
|
|
146
|
+
* @param {string} type - 'custom-element' or 'data-component'
|
|
147
|
+
* @returns {string} Component template filename
|
|
148
|
+
*/
|
|
149
|
+
resolveComponentName(name, type) {
|
|
150
|
+
// Check explicit mapping first
|
|
151
|
+
if (this.config.mapping && this.config.mapping[name]) {
|
|
152
|
+
return this.config.mapping[name];
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
// For custom elements, strip prefix if configured
|
|
156
|
+
let componentName = name;
|
|
157
|
+
if (type === 'custom-element' && this.config.prefix) {
|
|
158
|
+
if (name.startsWith(this.config.prefix)) {
|
|
159
|
+
componentName = name.slice(this.config.prefix.length);
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
// Default: use name as filename (add .html if needed)
|
|
164
|
+
return componentName.endsWith('.html') ? componentName : `${componentName}.html`;
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
/**
|
|
168
|
+
* Replace a component element with its template
|
|
169
|
+
* @param {Object} componentInfo - Component information object
|
|
170
|
+
*/
|
|
171
|
+
async replaceComponent(componentInfo) {
|
|
172
|
+
const { element, type, name, componentName } = componentInfo;
|
|
173
|
+
|
|
174
|
+
try {
|
|
175
|
+
// Get component template
|
|
176
|
+
const template = await this.getComponentTemplate(componentName);
|
|
177
|
+
if (!template) {
|
|
178
|
+
if (process.env.LOGGER) {
|
|
179
|
+
console.log(chalk.yellow(` [warn] Component template not found: ${componentName}`));
|
|
180
|
+
}
|
|
181
|
+
return;
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
// Extract <style> blocks from template (deduplicate per component)
|
|
185
|
+
const { html: htmlTemplate, css } = this.extractStyles(template);
|
|
186
|
+
if (css && !this.collectedStyles[componentName]) {
|
|
187
|
+
// Resolve template variables in CSS with global data only
|
|
188
|
+
this.collectedStyles[componentName] = this.renderTemplate(css, this.data);
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
// Extract data from element attributes
|
|
192
|
+
const componentData = this.extractComponentData(element, type);
|
|
193
|
+
|
|
194
|
+
// Extract named and default slot content from children
|
|
195
|
+
this.extractSlots(element, componentData);
|
|
196
|
+
|
|
197
|
+
// Merge with global data (component data takes precedence)
|
|
198
|
+
const mergedData = { ...this.data, ...componentData };
|
|
199
|
+
|
|
200
|
+
// Replace template variables with data (style-free HTML only)
|
|
201
|
+
const renderedContent = this.renderTemplate(htmlTemplate, mergedData);
|
|
202
|
+
|
|
203
|
+
// Insert rendered content and remove original element
|
|
204
|
+
element.insertAdjacentHTML('afterend', renderedContent);
|
|
205
|
+
|
|
206
|
+
// Transfer non-data attributes to the first valid replaced element
|
|
207
|
+
this.transferAttributes(element, type);
|
|
208
|
+
|
|
209
|
+
// Remove the original component element
|
|
210
|
+
element.remove();
|
|
211
|
+
|
|
212
|
+
this.replaced.push(name);
|
|
213
|
+
} catch (err) {
|
|
214
|
+
Util.customError(err, `replace-components.js: Error replacing ${name}`);
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
/**
|
|
219
|
+
* Get component template content (with caching)
|
|
220
|
+
* @param {string} componentName - Component template filename
|
|
221
|
+
* @returns {string|null} Template content or null if not found
|
|
222
|
+
*/
|
|
223
|
+
async getComponentTemplate(componentName) {
|
|
224
|
+
// Check cache first
|
|
225
|
+
if (this.store.cachedComponents[componentName] !== undefined) {
|
|
226
|
+
return this.store.cachedComponents[componentName];
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
// Build path to component template
|
|
230
|
+
// Read from srcPath since build-only dirs (components/) may not be in dist
|
|
231
|
+
const basePath = `${srcPath}/${this.config.path}`;
|
|
232
|
+
const directPath = path.resolve(`${basePath}/${componentName}`);
|
|
233
|
+
const dirPath = path.resolve(`${basePath}/${componentName.replace('.html', '/index.html')}`);
|
|
234
|
+
|
|
235
|
+
let componentPath = null;
|
|
236
|
+
if (existsSync(directPath)) {
|
|
237
|
+
componentPath = directPath;
|
|
238
|
+
} else if (existsSync(dirPath)) {
|
|
239
|
+
componentPath = dirPath;
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
// Check if component exists
|
|
243
|
+
if (!componentPath) {
|
|
244
|
+
this.store.cachedComponents[componentName] = null;
|
|
245
|
+
return null;
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
try {
|
|
249
|
+
const content = await fs.readFile(componentPath, 'utf-8');
|
|
250
|
+
this.store.cachedComponents[componentName] = content;
|
|
251
|
+
return content;
|
|
252
|
+
} catch (err) {
|
|
253
|
+
this.store.cachedComponents[componentName] = null;
|
|
254
|
+
return null;
|
|
255
|
+
}
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
/**
|
|
259
|
+
* Extract data from element attributes
|
|
260
|
+
* @param {Element} element - The component element
|
|
261
|
+
* @param {string} type - Component type
|
|
262
|
+
* @returns {Object} Data object from attributes
|
|
263
|
+
*/
|
|
264
|
+
extractComponentData(element, type) {
|
|
265
|
+
const data = {};
|
|
266
|
+
|
|
267
|
+
for (const attr of element.attributes) {
|
|
268
|
+
const name = attr.name;
|
|
269
|
+
const value = attr.value;
|
|
270
|
+
|
|
271
|
+
// Skip data-component attribute itself
|
|
272
|
+
if (name === 'data-component') continue;
|
|
273
|
+
|
|
274
|
+
// Handle data-* attributes (strip 'data-' prefix)
|
|
275
|
+
if (name.startsWith('data-')) {
|
|
276
|
+
const key = this.camelCase(name.slice(5));
|
|
277
|
+
data[key] = value;
|
|
278
|
+
}
|
|
279
|
+
// For custom elements, all attributes are data
|
|
280
|
+
else if (type === 'custom-element') {
|
|
281
|
+
const key = this.camelCase(name);
|
|
282
|
+
data[key] = value;
|
|
283
|
+
}
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
// Also add the original tag name as a variable
|
|
287
|
+
data.tagName = element.tagName.toLowerCase();
|
|
288
|
+
|
|
289
|
+
return data;
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
/**
|
|
293
|
+
* Extract named and default slot content from element children.
|
|
294
|
+
* Children with a slot="name" attribute provide named slot content.
|
|
295
|
+
* Remaining children (and text nodes) form the default ${slot}.
|
|
296
|
+
* Results are stored on the componentData object as:
|
|
297
|
+
* - componentData.slot (default slot — all non-named content)
|
|
298
|
+
* - componentData['slot:name'] (named slots)
|
|
299
|
+
* @param {Element} element - The component element
|
|
300
|
+
* @param {Object} componentData - Data object to populate
|
|
301
|
+
*/
|
|
302
|
+
extractSlots(element, componentData) {
|
|
303
|
+
const namedSlots = {};
|
|
304
|
+
const defaultParts = [];
|
|
305
|
+
|
|
306
|
+
for (const child of Array.from(element.childNodes)) {
|
|
307
|
+
// Element nodes may carry a slot attribute
|
|
308
|
+
if (child.nodeType === 1 /* ELEMENT_NODE */) {
|
|
309
|
+
const slotName = child.getAttribute && child.getAttribute('slot');
|
|
310
|
+
if (slotName) {
|
|
311
|
+
// Remove the slot attribute from the content before injecting
|
|
312
|
+
child.removeAttribute('slot');
|
|
313
|
+
// If the same slot name appears more than once, concatenate
|
|
314
|
+
namedSlots[slotName] = (namedSlots[slotName] || '') + child.outerHTML;
|
|
315
|
+
} else {
|
|
316
|
+
defaultParts.push(child.outerHTML);
|
|
317
|
+
}
|
|
318
|
+
}
|
|
319
|
+
// Text nodes (and others) go to the default slot
|
|
320
|
+
else if (child.textContent.trim()) {
|
|
321
|
+
defaultParts.push(child.textContent);
|
|
322
|
+
}
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
// Default slot — everything that wasn't assigned to a named slot
|
|
326
|
+
componentData.slot = defaultParts.join('').trim();
|
|
327
|
+
|
|
328
|
+
// Named slots — keyed as "slot:name"
|
|
329
|
+
for (const [name, html] of Object.entries(namedSlots)) {
|
|
330
|
+
componentData[`slot:${name}`] = html;
|
|
331
|
+
}
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
/**
|
|
335
|
+
* Extract <style> blocks from a component template string.
|
|
336
|
+
* Returns the HTML without styles and the collected CSS text.
|
|
337
|
+
* @param {string} template - Raw template string
|
|
338
|
+
* @returns {{ html: string, css: string }}
|
|
339
|
+
*/
|
|
340
|
+
extractStyles(template) {
|
|
341
|
+
const styleRegex = /<style[^>]*>([\s\S]*?)<\/style>/gi;
|
|
342
|
+
const cssBlocks = [];
|
|
343
|
+
let match;
|
|
344
|
+
|
|
345
|
+
while ((match = styleRegex.exec(template)) !== null) {
|
|
346
|
+
const block = match[1].trim();
|
|
347
|
+
if (block) cssBlocks.push(block);
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
const html = template.replace(styleRegex, '').trim();
|
|
351
|
+
const css = cssBlocks.join('\n');
|
|
352
|
+
|
|
353
|
+
return { html, css };
|
|
354
|
+
}
|
|
355
|
+
|
|
356
|
+
/**
|
|
357
|
+
* Inject all collected component styles into <head> as a single <style>.
|
|
358
|
+
* @param {Document} document - The JSDOM document
|
|
359
|
+
*/
|
|
360
|
+
injectCollectedStyles(document) {
|
|
361
|
+
const entries = Object.entries(this.collectedStyles);
|
|
362
|
+
if (entries.length === 0) return;
|
|
363
|
+
|
|
364
|
+
const cssText = entries
|
|
365
|
+
.map(([name, css]) => `/* ${name} */\n${css}`)
|
|
366
|
+
.join('\n\n');
|
|
367
|
+
|
|
368
|
+
const head = document.head || document.querySelector('head');
|
|
369
|
+
if (!head) return;
|
|
370
|
+
|
|
371
|
+
const styleEl = document.createElement('style');
|
|
372
|
+
styleEl.textContent = cssText;
|
|
373
|
+
head.appendChild(styleEl);
|
|
374
|
+
}
|
|
375
|
+
|
|
376
|
+
/**
|
|
377
|
+
* Render template by replacing variables with data
|
|
378
|
+
* @param {string} template - Template string
|
|
379
|
+
* @param {Object} data - Data object
|
|
380
|
+
* @returns {string} Rendered template
|
|
381
|
+
*/
|
|
382
|
+
renderTemplate(template, data) {
|
|
383
|
+
// Replace ${slot:name} named slots (and ${slot} default)
|
|
384
|
+
// Also replace ${varName} with data values
|
|
385
|
+
// Supports nested: ${user.name}
|
|
386
|
+
return template.replace(/\$\{([^}]+)\}/g, (match, key) => {
|
|
387
|
+
const trimmedKey = key.trim();
|
|
388
|
+
|
|
389
|
+
// Check data directly (handles "slot", "slot:name", and regular vars)
|
|
390
|
+
if (data[trimmedKey] !== undefined && data[trimmedKey] !== null) {
|
|
391
|
+
return data[trimmedKey];
|
|
392
|
+
}
|
|
393
|
+
|
|
394
|
+
// Handle nested properties (e.g., user.name) — but not slot:name (already checked)
|
|
395
|
+
if (trimmedKey.includes('.')) {
|
|
396
|
+
const value = this.getNestedValue(data, trimmedKey);
|
|
397
|
+
if (value !== undefined && value !== null) {
|
|
398
|
+
return value;
|
|
399
|
+
}
|
|
400
|
+
}
|
|
401
|
+
|
|
402
|
+
// Named slot not provided — remove the placeholder (empty string)
|
|
403
|
+
if (trimmedKey.startsWith('slot:')) {
|
|
404
|
+
return '';
|
|
405
|
+
}
|
|
406
|
+
|
|
407
|
+
// Keep the original ${var} if not found (allows for later processing)
|
|
408
|
+
return match;
|
|
409
|
+
});
|
|
410
|
+
}
|
|
411
|
+
|
|
412
|
+
/**
|
|
413
|
+
* Get nested value from object using dot notation
|
|
414
|
+
* @param {Object} obj - Source object
|
|
415
|
+
* @param {string} path - Dot-notation path
|
|
416
|
+
* @returns {*} Value or undefined
|
|
417
|
+
*/
|
|
418
|
+
getNestedValue(obj, path) {
|
|
419
|
+
return path.split('.').reduce((current, key) => {
|
|
420
|
+
return current && current[key] !== undefined ? current[key] : undefined;
|
|
421
|
+
}, obj);
|
|
422
|
+
}
|
|
423
|
+
|
|
424
|
+
/**
|
|
425
|
+
* Transfer non-component attributes to the first valid replaced element
|
|
426
|
+
* @param {Element} originalElement - The original component element
|
|
427
|
+
* @param {string} type - Component type
|
|
428
|
+
*/
|
|
429
|
+
transferAttributes(originalElement, type) {
|
|
430
|
+
const nextEl = originalElement.nextElementSibling;
|
|
431
|
+
if (!nextEl) return;
|
|
432
|
+
|
|
433
|
+
// Attributes to skip
|
|
434
|
+
const skipAttrs = ['data-component'];
|
|
435
|
+
if (type === 'custom-element') {
|
|
436
|
+
// For custom elements, we've already used all attributes as data
|
|
437
|
+
// Only transfer class and id
|
|
438
|
+
for (const attr of ['class', 'id']) {
|
|
439
|
+
const value = originalElement.getAttribute(attr);
|
|
440
|
+
if (value) {
|
|
441
|
+
const existing = nextEl.getAttribute(attr) || '';
|
|
442
|
+
nextEl.setAttribute(attr, existing ? `${existing} ${value}` : value);
|
|
443
|
+
}
|
|
444
|
+
}
|
|
445
|
+
} else {
|
|
446
|
+
// For data-component, transfer non-data-* attributes
|
|
447
|
+
for (const attr of originalElement.attributes) {
|
|
448
|
+
if (!attr.name.startsWith('data-') && !skipAttrs.includes(attr.name)) {
|
|
449
|
+
// Merge classes, replace others
|
|
450
|
+
if (attr.name === 'class') {
|
|
451
|
+
const existing = nextEl.getAttribute('class') || '';
|
|
452
|
+
nextEl.setAttribute('class', existing ? `${existing} ${attr.value}` : attr.value);
|
|
453
|
+
} else {
|
|
454
|
+
nextEl.setAttribute(attr.name, attr.value);
|
|
455
|
+
}
|
|
456
|
+
}
|
|
457
|
+
}
|
|
458
|
+
}
|
|
459
|
+
}
|
|
460
|
+
|
|
461
|
+
/**
|
|
462
|
+
* Convert kebab-case to camelCase
|
|
463
|
+
* @param {string} str - Kebab-case string
|
|
464
|
+
* @returns {string} camelCase string
|
|
465
|
+
*/
|
|
466
|
+
camelCase(str) {
|
|
467
|
+
return str.replace(/-([a-z])/g, (_, letter) => letter.toUpperCase());
|
|
468
|
+
}
|
|
469
|
+
|
|
470
|
+
// LOGGING
|
|
471
|
+
// -----------------------------
|
|
472
|
+
startLog() {
|
|
473
|
+
if (!process.env.LOGGER) return;
|
|
474
|
+
this.loading.start(chalk.magenta('Replacing Components'));
|
|
475
|
+
this.timer.start();
|
|
476
|
+
}
|
|
477
|
+
|
|
478
|
+
endLog() {
|
|
479
|
+
if (!process.env.LOGGER) return;
|
|
480
|
+
if (this.total > 0) {
|
|
481
|
+
this.loading.stop(`Replaced ${chalk.magenta(this.replaced.length)} components ${this.timer.end()}`);
|
|
482
|
+
} else {
|
|
483
|
+
this.loading.kill();
|
|
484
|
+
}
|
|
485
|
+
}
|
|
486
|
+
|
|
487
|
+
// EXPORT WRAPPER
|
|
488
|
+
// -----------------------------
|
|
489
|
+
static async export(opts) {
|
|
490
|
+
return new ReplaceComponents(opts).init();
|
|
491
|
+
}
|
|
492
|
+
}
|
|
493
|
+
|
|
494
|
+
// EXPORT
|
|
495
|
+
// -----------------------------
|
|
496
|
+
export default ReplaceComponents.export;
|
|
@@ -0,0 +1,171 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @file replace-external-link-protocol.js
|
|
3
|
+
* @description For targeted `<a>` tags, add `http://` in front of the href value,
|
|
4
|
+
* if it starts with `www` and wasn't added with a protocol (`http://` or `https://`).
|
|
5
|
+
* Without this, the build process interprets it as a local link
|
|
6
|
+
* and will append the current window location origin.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
// IMPORT
|
|
10
|
+
// -----------------------------
|
|
11
|
+
const cwd = process.cwd();
|
|
12
|
+
import chalk from 'chalk';
|
|
13
|
+
import Logger from '../utils/logger/logger.js';
|
|
14
|
+
import Util from '../utils/util/util.js';
|
|
15
|
+
|
|
16
|
+
// USER 'MAIN.JS' CONFIG
|
|
17
|
+
import {
|
|
18
|
+
distPath,
|
|
19
|
+
replaceExternalLinkProtocol as replaceExternalLinkProtocolConfig,
|
|
20
|
+
} from '../utils/config/config.js';
|
|
21
|
+
|
|
22
|
+
const replaceExternalLinkProtocol = replaceExternalLinkProtocolConfig || {enabled:true};
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
// DEFINE
|
|
26
|
+
// -----------------------------
|
|
27
|
+
/**
|
|
28
|
+
* @description Replace non-protocol `www.` and `cdn.` link paths to avoid them being treated as relative links.
|
|
29
|
+
* @param {Object} obj - Deconstructed options object
|
|
30
|
+
* @property {Object} obj.file - The current file's info (name, extension, path, src, etc.)
|
|
31
|
+
* @property {Array} [obj.allowType] - Allowed file types (Opt-in)
|
|
32
|
+
* @property {Array} [obj.disallowType] - Disallowed file types (Opt-out)
|
|
33
|
+
*/
|
|
34
|
+
class ReplaceExternalLinkProtocol {
|
|
35
|
+
constructor({file, allowType, disallowType, excludePaths = []}) {
|
|
36
|
+
this.opts = {file, allowType, disallowType, excludePaths};
|
|
37
|
+
this.file = file;
|
|
38
|
+
this.allowType = allowType;
|
|
39
|
+
this.disallowType = disallowType;
|
|
40
|
+
this.excludePaths = excludePaths;
|
|
41
|
+
|
|
42
|
+
// Store holder for total # of replaced items
|
|
43
|
+
this.total = 0;
|
|
44
|
+
|
|
45
|
+
// Init terminal logging
|
|
46
|
+
if (process.env.LOGGER) Util.initLogging.call(this);
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
// INIT
|
|
50
|
+
// -----------------------------
|
|
51
|
+
// Note: `process.env.DEV_CHANGED_PAGE` is defined in `browserSync.watch()` in dev.js
|
|
52
|
+
async init() {
|
|
53
|
+
// Early Exit: User opted out of this plugin
|
|
54
|
+
if (!replaceExternalLinkProtocol.enabled) return;
|
|
55
|
+
// Early Exit: File type not allowed
|
|
56
|
+
const allowed = Util.isAllowedType(this.opts);
|
|
57
|
+
if (!allowed) return;
|
|
58
|
+
|
|
59
|
+
// START LOGGING
|
|
60
|
+
this.startLog();
|
|
61
|
+
|
|
62
|
+
// Destructure options
|
|
63
|
+
const { file } = this;
|
|
64
|
+
|
|
65
|
+
// Make source traversable with JSDOM
|
|
66
|
+
let dom = Util.jsdom.dom({src: file.src});
|
|
67
|
+
|
|
68
|
+
// Find <a>, <link>, and <script> tags
|
|
69
|
+
const $link = dom.window.document.querySelectorAll('link');
|
|
70
|
+
const $links = dom.window.document.querySelectorAll('a');
|
|
71
|
+
const $script = dom.window.document.querySelectorAll('script');
|
|
72
|
+
|
|
73
|
+
// Add `http://` to qualifying a tags
|
|
74
|
+
// Replace leading `//` to qualifying tags
|
|
75
|
+
if ($link) $link.forEach(el => this.replaceMissingProtocol({file, el}));
|
|
76
|
+
if ($links) $links.forEach(el => this.replaceMissingProtocol({file, el}));
|
|
77
|
+
if ($script) $script.forEach(el => this.replaceMissingProtocol({file, el}));
|
|
78
|
+
|
|
79
|
+
// Store updated file source
|
|
80
|
+
this.file.src = Util.setSrc({dom});
|
|
81
|
+
|
|
82
|
+
// END LOGGING
|
|
83
|
+
this.endLog();
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
// HELPER METHODS
|
|
87
|
+
// -----------------------------
|
|
88
|
+
|
|
89
|
+
/**
|
|
90
|
+
* @description Evaluate `<a>` tag `[href]` value, and set protocol if link is external and protocol not added by the user
|
|
91
|
+
* @example Replace: `<a href="www.xxxx.com">`
|
|
92
|
+
* @example Does Not Replace: `<a href="https://www.xxxx.com">`
|
|
93
|
+
* @param {Object} opts - The arguments object
|
|
94
|
+
* @property {Object} file - The current file's props (ext,name,path,name)
|
|
95
|
+
* @property {Object} el - The current <a>, <link>, or <script> tag being evaluated
|
|
96
|
+
* @private
|
|
97
|
+
*/
|
|
98
|
+
replaceMissingProtocol({file, scope, el}) {
|
|
99
|
+
// Get source type (`href` or `src`)
|
|
100
|
+
let srcType = el.href || el.src;
|
|
101
|
+
// Early Exit: Tag does not have `[href]` or `[src]` or attribute value is empty string
|
|
102
|
+
// Example: Someone adds an old-school anchor jump point: `<a id="jump-point"></a>`
|
|
103
|
+
if (!srcType || srcType === '') return;
|
|
104
|
+
// Get href path
|
|
105
|
+
const linkPath = Util.getFileName(srcType, distPath);
|
|
106
|
+
// Only replace for `www` and `cdn` instances, unless user defined their own
|
|
107
|
+
const domainTargets = replaceExternalLinkProtocol.match || Util.replaceExternalLinkProtocolDefaults;
|
|
108
|
+
const isTargetMatch = domainTargets.indexOf(linkPath) > -1;
|
|
109
|
+
const pathType = el.href ? 'href' : 'src';
|
|
110
|
+
// Update path
|
|
111
|
+
if (isTargetMatch) this.replaceExternal(file, el, pathType);
|
|
112
|
+
// Increment total counter
|
|
113
|
+
if (isTargetMatch) this.total += 1;
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/**
|
|
117
|
+
* @description Create new, fixed external path
|
|
118
|
+
* @property {Object} file - The current file's props (ext,name,path,name)
|
|
119
|
+
* @property {Object} el - The current <a>, <link>, or <script> tag being evaluated
|
|
120
|
+
* @property {String} type - Either the element's `[href]` or `[src]` prop to write new value to
|
|
121
|
+
* @private
|
|
122
|
+
*/
|
|
123
|
+
replaceExternal(file, el, type) {
|
|
124
|
+
// Split path on /
|
|
125
|
+
let linkPathSplit = el[type].split('/');
|
|
126
|
+
// Filter out ''
|
|
127
|
+
linkPathSplit = linkPathSplit.filter(s => s);
|
|
128
|
+
// Find if 'localhost' is in the path name
|
|
129
|
+
// We'll only replace these, as they represent the links we want to convert
|
|
130
|
+
if (linkPathSplit.indexOf('localhost') === -1) return;
|
|
131
|
+
el[type] = `http://${linkPathSplit[linkPathSplit.length-1]}`;
|
|
132
|
+
// Show terminal message
|
|
133
|
+
// Logger.success(`/${file.path} - Added 'http://' to [href="${linkPathSplit[linkPathSplit.length-1]}"]: ${ chalk.green(el[type]) }`);
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
// LOGGING
|
|
138
|
+
// -----------------------------
|
|
139
|
+
// Display additional terminal logging when `process.env.LOGGER` enabled
|
|
140
|
+
|
|
141
|
+
startLog() {
|
|
142
|
+
// Early Exit: Logging not allowed
|
|
143
|
+
if (!process.env.LOGGER) return;
|
|
144
|
+
// Start Spinner
|
|
145
|
+
this.loading.start(chalk.magenta('Replacing Missing Link Protocol'));
|
|
146
|
+
// Start timer
|
|
147
|
+
this.timer.start();
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
endLog() {
|
|
151
|
+
// Early Exit: Logging not allowed
|
|
152
|
+
if (!process.env.LOGGER) return;
|
|
153
|
+
// Stop Spinner and Timer
|
|
154
|
+
if (this.total > 0) this.loading.stop(`Replaced ${chalk.magenta(this.total)} missing link protocols ${this.timer.end()}`);
|
|
155
|
+
// If no matches found, stop logger but don't show line in terminal
|
|
156
|
+
else this.loading.kill();
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
// EXPORT WRAPPER
|
|
161
|
+
// -----------------------------
|
|
162
|
+
// Export function wrapper instead of class for `build.js` simplicity
|
|
163
|
+
static async export(opts) {
|
|
164
|
+
return new ReplaceExternalLinkProtocol(opts).init();
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
// EXPORT
|
|
170
|
+
// -----------------------------
|
|
171
|
+
export default ReplaceExternalLinkProtocol.export;
|