source: trip-planner-front/node_modules/critters/dist/critters.mjs@ e29cc2e

Last change on this file since e29cc2e was e29cc2e, checked in by Ema <ema_spirova@…>, 3 years ago

primeNG components

  • Property mode set to 100644
File size: 33.5 KB
Line 
1import path from 'path';
2import prettyBytes from 'pretty-bytes';
3import parse5 from 'parse5';
4import { selectOne, selectAll } from 'css-select';
5import treeAdapter from 'parse5-htmlparser2-tree-adapter';
6import { parse, stringify } from 'postcss';
7import chalk from 'chalk';
8
9/**
10 * Copyright 2018 Google LLC
11 *
12 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
13 * use this file except in compliance with the License. You may obtain a copy of
14 * the License at
15 *
16 * http://www.apache.org/licenses/LICENSE-2.0
17 *
18 * Unless required by applicable law or agreed to in writing, software
19 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
20 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
21 * License for the specific language governing permissions and limitations under
22 * the License.
23 */
24
25const PARSE5_OPTS = {
26 treeAdapter
27};
28/**
29 * Parse HTML into a mutable, serializable DOM Document.
30 * The DOM implementation is an htmlparser2 DOM enhanced with basic DOM mutation methods.
31 * @param {String} html HTML to parse into a Document instance
32 */
33
34function createDocument(html) {
35 const document =
36 /** @type {HTMLDocument} */
37 parse5.parse(html, PARSE5_OPTS);
38 defineProperties(document, DocumentExtensions); // Extend Element.prototype with DOM manipulation methods.
39
40 const scratch = document.createElement('div'); // Get a reference to the base Node class - used by createTextNode()
41
42 document.$$Node = scratch.constructor;
43 const elementProto = Object.getPrototypeOf(scratch);
44 defineProperties(elementProto, ElementExtensions);
45 elementProto.ownerDocument = document;
46 return document;
47}
48/**
49 * Serialize a Document to an HTML String
50 * @param {HTMLDocument} document A Document, such as one created via `createDocument()`
51 */
52
53function serializeDocument(document) {
54 return parse5.serialize(document, PARSE5_OPTS);
55}
56/** @typedef {treeAdapter.Document & typeof ElementExtensions} HTMLDocument */
57
58/**
59 * Methods and descriptors to mix into Element.prototype
60 * @private
61 */
62
63const ElementExtensions = {
64 /** @extends treeAdapter.Element.prototype */
65 nodeName: {
66 get() {
67 return this.tagName.toUpperCase();
68 }
69
70 },
71 id: reflectedProperty('id'),
72 className: reflectedProperty('class'),
73
74 insertBefore(child, referenceNode) {
75 if (!referenceNode) return this.appendChild(child);
76 treeAdapter.insertBefore(this, child, referenceNode);
77 return child;
78 },
79
80 appendChild(child) {
81 treeAdapter.appendChild(this, child);
82 return child;
83 },
84
85 removeChild(child) {
86 treeAdapter.detachNode(child);
87 },
88
89 remove() {
90 treeAdapter.detachNode(this);
91 },
92
93 textContent: {
94 get() {
95 return getText(this);
96 },
97
98 set(text) {
99 this.children = [];
100 treeAdapter.insertText(this, text);
101 }
102
103 },
104
105 setAttribute(name, value) {
106 if (this.attribs == null) this.attribs = {};
107 if (value == null) value = '';
108 this.attribs[name] = value;
109 },
110
111 removeAttribute(name) {
112 if (this.attribs != null) {
113 delete this.attribs[name];
114 }
115 },
116
117 getAttribute(name) {
118 return this.attribs != null && this.attribs[name];
119 },
120
121 hasAttribute(name) {
122 return this.attribs != null && this.attribs[name] != null;
123 },
124
125 getAttributeNode(name) {
126 const value = this.getAttribute(name);
127 if (value != null) return {
128 specified: true,
129 value
130 };
131 }
132
133};
134/**
135 * Methods and descriptors to mix into the global document instance
136 * @private
137 */
138
139const DocumentExtensions = {
140 /** @extends treeAdapter.Document.prototype */
141 // document is just an Element in htmlparser2, giving it a nodeType of ELEMENT_NODE.
142 // TODO: verify if these are needed for css-select
143 nodeType: {
144 get() {
145 return 9;
146 }
147
148 },
149 contentType: {
150 get() {
151 return 'text/html';
152 }
153
154 },
155 nodeName: {
156 get() {
157 return '#document';
158 }
159
160 },
161 documentElement: {
162 get() {
163 // Find the first <html> element within the document
164 return this.childNodes.filter(child => String(child.tagName).toLowerCase() === 'html');
165 }
166
167 },
168 compatMode: {
169 get() {
170 const compatMode = {
171 'no-quirks': 'CSS1Compat',
172 quirks: 'BackCompat',
173 'limited-quirks': 'CSS1Compat'
174 };
175 return compatMode[treeAdapter.getDocumentMode(this)];
176 }
177
178 },
179 body: {
180 get() {
181 return this.querySelector('body');
182 }
183
184 },
185
186 createElement(name) {
187 return treeAdapter.createElement(name, null, []);
188 },
189
190 createTextNode(text) {
191 // there is no dedicated createTextNode equivalent exposed in htmlparser2's DOM
192 const Node = this.$$Node;
193 return new Node({
194 type: 'text',
195 data: text,
196 parent: null,
197 prev: null,
198 next: null
199 });
200 },
201
202 querySelector(sel) {
203 return selectOne(sel, this.documentElement);
204 },
205
206 querySelectorAll(sel) {
207 if (sel === ':root') {
208 return this;
209 }
210
211 return selectAll(sel, this.documentElement);
212 }
213
214};
215/**
216 * Essentially `Object.defineProperties()`, except function values are assigned as value descriptors for convenience.
217 * @private
218 */
219
220function defineProperties(obj, properties) {
221 for (const i in properties) {
222 const value = properties[i];
223 Object.defineProperty(obj, i, typeof value === 'function' ? {
224 value
225 } : value);
226 }
227}
228/**
229 * Create a property descriptor defining a getter/setter pair alias for a named attribute.
230 * @private
231 */
232
233
234function reflectedProperty(attributeName) {
235 return {
236 get() {
237 return this.getAttribute(attributeName);
238 },
239
240 set(value) {
241 this.setAttribute(attributeName, value);
242 }
243
244 };
245}
246/**
247 * Helper to get the text content of a node
248 * https://github.com/fb55/domutils/blob/master/src/stringify.ts#L21
249 * @private
250 */
251
252
253function getText(node) {
254 if (Array.isArray(node)) return node.map(getText).join('');
255 if (treeAdapter.isElementNode(node)) return node.name === 'br' ? '\n' : getText(node.children);
256 if (treeAdapter.isTextNode(node)) return node.data;
257 return '';
258}
259
260/**
261 * Copyright 2018 Google LLC
262 *
263 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
264 * use this file except in compliance with the License. You may obtain a copy of
265 * the License at
266 *
267 * http://www.apache.org/licenses/LICENSE-2.0
268 *
269 * Unless required by applicable law or agreed to in writing, software
270 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
271 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
272 * License for the specific language governing permissions and limitations under
273 * the License.
274 */
275/**
276 * Parse a textual CSS Stylesheet into a Stylesheet instance.
277 * Stylesheet is a mutable postcss AST with format similar to CSSOM.
278 * @see https://github.com/postcss/postcss/
279 * @private
280 * @param {String} stylesheet
281 * @returns {css.Stylesheet} ast
282 */
283
284function parseStylesheet(stylesheet) {
285 return parse(stylesheet);
286}
287/**
288 * Serialize a postcss Stylesheet to a String of CSS.
289 * @private
290 * @param {css.Stylesheet} ast A Stylesheet to serialize, such as one returned from `parseStylesheet()`
291 * @param {Object} options Options used by the stringify logic
292 * @param {Boolean} [options.compress] Compress CSS output (removes comments, whitespace, etc)
293 */
294
295function serializeStylesheet(ast, options) {
296 let cssStr = '';
297 stringify(ast, (result, node, type) => {
298 var _node$raws;
299
300 if (!options.compress) {
301 cssStr += result;
302 return;
303 } // Simple minification logic
304
305
306 if ((node == null ? void 0 : node.type) === 'comment') return;
307
308 if ((node == null ? void 0 : node.type) === 'decl') {
309 const prefix = node.prop + node.raws.between;
310 cssStr += result.replace(prefix, prefix.trim());
311 return;
312 }
313
314 if (type === 'start') {
315 if (node.type === 'rule' && node.selectors) {
316 cssStr += node.selectors.join(',') + '{';
317 } else {
318 cssStr += result.replace(/\s\{$/, '{');
319 }
320
321 return;
322 }
323
324 if (type === 'end' && result === '}' && node != null && (_node$raws = node.raws) != null && _node$raws.semicolon) {
325 cssStr = cssStr.slice(0, -1);
326 }
327
328 cssStr += result.trim();
329 });
330 return cssStr;
331}
332/**
333 * Converts a walkStyleRules() iterator to mark nodes with `.$$remove=true` instead of actually removing them.
334 * This means they can be removed in a second pass, allowing the first pass to be nondestructive (eg: to preserve mirrored sheets).
335 * @private
336 * @param {Function} iterator Invoked on each node in the tree. Return `false` to remove that node.
337 * @returns {(rule) => void} nonDestructiveIterator
338 */
339
340function markOnly(predicate) {
341 return rule => {
342 const sel = rule.selectors;
343
344 if (predicate(rule) === false) {
345 rule.$$remove = true;
346 }
347
348 rule.$$markedSelectors = rule.selectors;
349
350 if (rule._other) {
351 rule._other.$$markedSelectors = rule._other.selectors;
352 }
353
354 rule.selectors = sel;
355 };
356}
357/**
358 * Apply filtered selectors to a rule from a previous markOnly run.
359 * @private
360 * @param {css.Rule} rule The Rule to apply marked selectors to (if they exist).
361 */
362
363function applyMarkedSelectors(rule) {
364 if (rule.$$markedSelectors) {
365 rule.selectors = rule.$$markedSelectors;
366 }
367
368 if (rule._other) {
369 applyMarkedSelectors(rule._other);
370 }
371}
372/**
373 * Recursively walk all rules in a stylesheet.
374 * @private
375 * @param {css.Rule} node A Stylesheet or Rule to descend into.
376 * @param {Function} iterator Invoked on each node in the tree. Return `false` to remove that node.
377 */
378
379function walkStyleRules(node, iterator) {
380 node.nodes = node.nodes.filter(rule => {
381 if (hasNestedRules(rule)) {
382 walkStyleRules(rule, iterator);
383 }
384
385 rule._other = undefined;
386 rule.filterSelectors = filterSelectors;
387 return iterator(rule) !== false;
388 });
389}
390/**
391 * Recursively walk all rules in two identical stylesheets, filtering nodes into one or the other based on a predicate.
392 * @private
393 * @param {css.Rule} node A Stylesheet or Rule to descend into.
394 * @param {css.Rule} node2 A second tree identical to `node`
395 * @param {Function} iterator Invoked on each node in the tree. Return `false` to remove that node from the first tree, true to remove it from the second.
396 */
397
398function walkStyleRulesWithReverseMirror(node, node2, iterator) {
399 if (node2 === null) return walkStyleRules(node, iterator);
400 [node.nodes, node2.nodes] = splitFilter(node.nodes, node2.nodes, (rule, index, rules, rules2) => {
401 const rule2 = rules2[index];
402
403 if (hasNestedRules(rule)) {
404 walkStyleRulesWithReverseMirror(rule, rule2, iterator);
405 }
406
407 rule._other = rule2;
408 rule.filterSelectors = filterSelectors;
409 return iterator(rule) !== false;
410 });
411} // Checks if a node has nested rules, like @media
412// @keyframes are an exception since they are evaluated as a whole
413
414function hasNestedRules(rule) {
415 return rule.nodes && rule.nodes.length && rule.nodes.some(n => n.type === 'rule' || n.type === 'atrule') && rule.name !== 'keyframes';
416} // Like [].filter(), but applies the opposite filtering result to a second copy of the Array without a second pass.
417// This is just a quicker version of generating the compliment of the set returned from a filter operation.
418
419
420function splitFilter(a, b, predicate) {
421 const aOut = [];
422 const bOut = [];
423
424 for (let index = 0; index < a.length; index++) {
425 if (predicate(a[index], index, a, b)) {
426 aOut.push(a[index]);
427 } else {
428 bOut.push(a[index]);
429 }
430 }
431
432 return [aOut, bOut];
433} // can be invoked on a style rule to subset its selectors (with reverse mirroring)
434
435
436function filterSelectors(predicate) {
437 if (this._other) {
438 const [a, b] = splitFilter(this.selectors, this._other.selectors, predicate);
439 this.selectors = a;
440 this._other.selectors = b;
441 } else {
442 this.selectors = this.selectors.filter(predicate);
443 }
444}
445
446const LOG_LEVELS = ['trace', 'debug', 'info', 'warn', 'error', 'silent'];
447const defaultLogger = {
448 trace(msg) {
449 console.trace(msg);
450 },
451
452 debug(msg) {
453 console.debug(msg);
454 },
455
456 warn(msg) {
457 console.warn(chalk.yellow(msg));
458 },
459
460 error(msg) {
461 console.error(chalk.bold.red(msg));
462 },
463
464 info(msg) {
465 console.info(chalk.bold.blue(msg));
466 },
467
468 silent() {}
469
470};
471function createLogger(logLevel) {
472 const logLevelIdx = LOG_LEVELS.indexOf(logLevel);
473 return LOG_LEVELS.reduce((logger, type, index) => {
474 if (index >= logLevelIdx) {
475 logger[type] = defaultLogger[type];
476 } else {
477 logger[type] = defaultLogger.silent;
478 }
479
480 return logger;
481 }, {});
482}
483
484/**
485 * Copyright 2018 Google LLC
486 *
487 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
488 * use this file except in compliance with the License. You may obtain a copy of
489 * the License at
490 *
491 * http://www.apache.org/licenses/LICENSE-2.0
492 *
493 * Unless required by applicable law or agreed to in writing, software
494 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
495 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
496 * License for the specific language governing permissions and limitations under
497 * the License.
498 */
499/**
500 * The mechanism to use for lazy-loading stylesheets.
501 *
502 * Note: <kbd>JS</kbd> indicates a strategy requiring JavaScript (falls back to `<noscript>` unless disabled).
503 *
504 * - **default:** Move stylesheet links to the end of the document and insert preload meta tags in their place.
505 * - **"body":** Move all external stylesheet links to the end of the document.
506 * - **"media":** Load stylesheets asynchronously by adding `media="not x"` and removing once loaded. <kbd>JS</kbd>
507 * - **"swap":** Convert stylesheet links to preloads that swap to `rel="stylesheet"` once loaded ([details](https://www.filamentgroup.com/lab/load-css-simpler/#the-code)). <kbd>JS</kbd>
508 * - **"swap-high":** Use `<link rel="alternate stylesheet preload">` and swap to `rel="stylesheet"` once loaded ([details](http://filamentgroup.github.io/loadCSS/test/new-high.html)). <kbd>JS</kbd>
509 * - **"js":** Inject an asynchronous CSS loader similar to [LoadCSS](https://github.com/filamentgroup/loadCSS) and use it to load stylesheets. <kbd>JS</kbd>
510 * - **"js-lazy":** Like `"js"`, but the stylesheet is disabled until fully loaded.
511 * @typedef {(default|'body'|'media'|'swap'|'swap-high'|'js'|'js-lazy')} PreloadStrategy
512 * @public
513 */
514
515/**
516 * Controls which keyframes rules are inlined.
517 *
518 * - **"critical":** _(default)_ inline keyframes rules that are used by the critical CSS.
519 * - **"all":** Inline all keyframes rules.
520 * - **"none":** Remove all keyframes rules.
521 * @typedef {('critical'|'all'|'none')} KeyframeStrategy
522 * @private
523 * @property {String} keyframes Which {@link KeyframeStrategy keyframe strategy} to use (default: `critical`)_
524 */
525
526/**
527 * Controls log level of the plugin. Specifies the level the logger should use. A logger will
528 * not produce output for any log level beneath the specified level. Available levels and order
529 * are:
530 *
531 * - **"info"** _(default)_
532 * - **"warn"**
533 * - **"error"**
534 * - **"trace"**
535 * - **"debug"**
536 * - **"silent"**
537 * @typedef {('info'|'warn'|'error'|'trace'|'debug'|'silent')} LogLevel
538 * @public
539 */
540
541/**
542 * Custom logger interface:
543 * @typedef {object} Logger
544 * @public
545 * @property {function(String)} trace - Prints a trace message
546 * @property {function(String)} debug - Prints a debug message
547 * @property {function(String)} info - Prints an information message
548 * @property {function(String)} warn - Prints a warning message
549 * @property {function(String)} error - Prints an error message
550 */
551
552/**
553 * All optional. Pass them to `new Critters({ ... })`.
554 * @public
555 * @typedef Options
556 * @property {String} path Base path location of the CSS files _(default: `''`)_
557 * @property {String} publicPath Public path of the CSS resources. This prefix is removed from the href _(default: `''`)_
558 * @property {Boolean} external Inline styles from external stylesheets _(default: `true`)_
559 * @property {Number} inlineThreshold Inline external stylesheets smaller than a given size _(default: `0`)_
560 * @property {Number} minimumExternalSize If the non-critical external stylesheet would be below this size, just inline it _(default: `0`)_
561 * @property {Boolean} pruneSource Remove inlined rules from the external stylesheet _(default: `false`)_
562 * @property {Boolean} mergeStylesheets Merged inlined stylesheets into a single <style> tag _(default: `true`)_
563 * @property {String[]} additionalStylesheets Glob for matching other stylesheets to be used while looking for critical CSS _(default: ``)_.
564 * @property {String} preload Which {@link PreloadStrategy preload strategy} to use
565 * @property {Boolean} noscriptFallback Add `<noscript>` fallback to JS-based strategies
566 * @property {Boolean} inlineFonts Inline critical font-face rules _(default: `false`)_
567 * @property {Boolean} preloadFonts Preloads critical fonts _(default: `true`)_
568 * @property {Boolean} fonts Shorthand for setting `inlineFonts`+`preloadFonts`
569 * - Values:
570 * - `true` to inline critical font-face rules and preload the fonts
571 * - `false` to don't inline any font-face rules and don't preload fonts
572 * @property {String} keyframes Controls which keyframes rules are inlined.
573 * - Values:
574 * - `"critical"`: _(default)_ inline keyframes rules used by the critical CSS
575 * - `"all"` inline all keyframes rules
576 * - `"none"` remove all keyframes rules
577 * @property {Boolean} compress Compress resulting critical CSS _(default: `true`)_
578 * @property {String} logLevel Controls {@link LogLevel log level} of the plugin _(default: `"info"`)_
579 * @property {object} logger Provide a custom logger interface {@link Logger logger}
580 */
581
582class Critters {
583 /** @private */
584 constructor(options) {
585 this.options = Object.assign({
586 logLevel: 'info',
587 path: '',
588 publicPath: '',
589 reduceInlineStyles: true,
590 pruneSource: false,
591 additionalStylesheets: []
592 }, options || {});
593 this.urlFilter = this.options.filter;
594
595 if (this.urlFilter instanceof RegExp) {
596 this.urlFilter = this.urlFilter.test.bind(this.urlFilter);
597 }
598
599 this.logger = this.options.logger || createLogger(this.options.logLevel);
600 }
601 /**
602 * Read the contents of a file from the specified filesystem or disk
603 */
604
605
606 readFile(filename) {
607 const fs = this.fs;
608 return new Promise((resolve, reject) => {
609 const callback = (err, data) => {
610 if (err) reject(err);else resolve(data);
611 };
612
613 if (fs && fs.readFile) {
614 fs.readFile(filename, callback);
615 } else {
616 require('fs').readFile(filename, 'utf8', callback);
617 }
618 });
619 }
620 /**
621 * Apply critical CSS processing to the html
622 */
623
624
625 async process(html) {
626 const start = process.hrtime.bigint(); // Parse the generated HTML in a DOM we can mutate
627
628 const document = createDocument(html);
629
630 if (this.options.additionalStylesheets.length > 0) {
631 this.embedAdditionalStylesheet(document);
632 } // `external:false` skips processing of external sheets
633
634
635 if (this.options.external !== false) {
636 const externalSheets = [].slice.call(document.querySelectorAll('link[rel="stylesheet"]'));
637 await Promise.all(externalSheets.map(link => this.embedLinkedStylesheet(link, document)));
638 } // go through all the style tags in the document and reduce them to only critical CSS
639
640
641 const styles = this.getAffectedStyleTags(document);
642 await Promise.all(styles.map(style => this.processStyle(style, document)));
643
644 if (this.options.mergeStylesheets !== false && styles.length !== 0) {
645 await this.mergeStylesheets(document);
646 } // serialize the document back to HTML and we're done
647
648
649 const output = serializeDocument(document);
650 const end = process.hrtime.bigint();
651 this.logger.info('Time ' + parseFloat(end - start) / 1000000.0);
652 return output;
653 }
654 /**
655 * Get the style tags that need processing
656 */
657
658
659 getAffectedStyleTags(document) {
660 const styles = [].slice.call(document.querySelectorAll('style')); // `inline:false` skips processing of inline stylesheets
661
662 if (this.options.reduceInlineStyles === false) {
663 return styles.filter(style => style.$$external);
664 }
665
666 return styles;
667 }
668
669 async mergeStylesheets(document) {
670 const styles = this.getAffectedStyleTags(document);
671
672 if (styles.length === 0) {
673 this.logger.warn('Merging inline stylesheets into a single <style> tag skipped, no inline stylesheets to merge');
674 return;
675 }
676
677 const first = styles[0];
678 let sheet = first.textContent;
679
680 for (let i = 1; i < styles.length; i++) {
681 const node = styles[i];
682 sheet += node.textContent;
683 node.remove();
684 }
685
686 first.textContent = sheet;
687 }
688 /**
689 * Given href, find the corresponding CSS asset
690 */
691
692
693 async getCssAsset(href) {
694 const outputPath = this.options.path;
695 const publicPath = this.options.publicPath; // CHECK - the output path
696 // path on disk (with output.publicPath removed)
697
698 let normalizedPath = href.replace(/^\//, '');
699 const pathPrefix = (publicPath || '').replace(/(^\/|\/$)/g, '') + '/';
700
701 if (normalizedPath.indexOf(pathPrefix) === 0) {
702 normalizedPath = normalizedPath.substring(pathPrefix.length).replace(/^\//, '');
703 } // Ignore remote stylesheets
704
705
706 if (/^https:\/\//.test(normalizedPath) || href.startsWith('//')) {
707 return undefined;
708 }
709
710 const filename = path.resolve(outputPath, normalizedPath);
711 let sheet;
712
713 try {
714 sheet = await this.readFile(filename);
715 } catch (e) {
716 this.logger.warn(`Unable to locate stylesheet: ${filename}`);
717 }
718
719 return sheet;
720 }
721
722 checkInlineThreshold(link, style, sheet) {
723 if (this.options.inlineThreshold && sheet.length < this.options.inlineThreshold) {
724 const href = style.$$name;
725 style.$$reduce = false;
726 this.logger.info(`\u001b[32mInlined all of ${href} (${sheet.length} was below the threshold of ${this.options.inlineThreshold})\u001b[39m`);
727 link.remove();
728 return true;
729 }
730
731 return false;
732 }
733 /**
734 * Inline the stylesheets from options.additionalStylesheets (assuming it passes `options.filter`)
735 */
736
737
738 async embedAdditionalStylesheet(document) {
739 const styleSheetsIncluded = [];
740 const sources = await Promise.all(this.options.additionalStylesheets.map(cssFile => {
741 if (styleSheetsIncluded.includes(cssFile)) {
742 return;
743 }
744
745 styleSheetsIncluded.push(cssFile);
746 const style = document.createElement('style');
747 style.$$external = true;
748 return this.getCssAsset(cssFile, style).then(sheet => [sheet, style]);
749 }));
750 sources.forEach(([sheet, style]) => {
751 if (!sheet) return;
752 style.textContent = sheet;
753 document.head.appendChild(style);
754 });
755 }
756 /**
757 * Inline the target stylesheet referred to by a <link rel="stylesheet"> (assuming it passes `options.filter`)
758 */
759
760
761 async embedLinkedStylesheet(link, document) {
762 const href = link.getAttribute('href');
763 const media = link.getAttribute('media');
764 const preloadMode = this.options.preload; // skip filtered resources, or network resources if no filter is provided
765
766 if (this.urlFilter ? this.urlFilter(href) : !(href || '').match(/\.css$/)) {
767 return Promise.resolve();
768 } // the reduced critical CSS gets injected into a new <style> tag
769
770
771 const style = document.createElement('style');
772 style.$$external = true;
773 const sheet = await this.getCssAsset(href, style);
774
775 if (!sheet) {
776 return;
777 }
778
779 style.textContent = sheet;
780 style.$$name = href;
781 style.$$links = [link];
782 link.parentNode.insertBefore(style, link);
783
784 if (this.checkInlineThreshold(link, style, sheet)) {
785 return;
786 } // CSS loader is only injected for the first sheet, then this becomes an empty string
787
788
789 let cssLoaderPreamble = "function $loadcss(u,m,l){(l=document.createElement('link')).rel='stylesheet';l.href=u;document.head.appendChild(l)}";
790 const lazy = preloadMode === 'js-lazy';
791
792 if (lazy) {
793 cssLoaderPreamble = cssLoaderPreamble.replace('l.href', "l.media='print';l.onload=function(){l.media=m};l.href");
794 } // Allow disabling any mutation of the stylesheet link:
795
796
797 if (preloadMode === false) return;
798 let noscriptFallback = false;
799
800 if (preloadMode === 'body') {
801 document.body.appendChild(link);
802 } else {
803 link.setAttribute('rel', 'preload');
804 link.setAttribute('as', 'style');
805
806 if (preloadMode === 'js' || preloadMode === 'js-lazy') {
807 const script = document.createElement('script');
808 const js = `${cssLoaderPreamble}$loadcss(${JSON.stringify(href)}${lazy ? ',' + JSON.stringify(media || 'all') : ''})`; // script.appendChild(document.createTextNode(js));
809
810 script.textContent = js;
811 link.parentNode.insertBefore(script, link.nextSibling);
812 style.$$links.push(script);
813 cssLoaderPreamble = '';
814 noscriptFallback = true;
815 } else if (preloadMode === 'media') {
816 // @see https://github.com/filamentgroup/loadCSS/blob/af1106cfe0bf70147e22185afa7ead96c01dec48/src/loadCSS.js#L26
817 link.setAttribute('rel', 'stylesheet');
818 link.removeAttribute('as');
819 link.setAttribute('media', 'print');
820 link.setAttribute('onload', `this.media='${media || 'all'}'`);
821 noscriptFallback = true;
822 } else if (preloadMode === 'swap-high') {
823 // @see http://filamentgroup.github.io/loadCSS/test/new-high.html
824 link.setAttribute('rel', 'alternate stylesheet preload');
825 link.setAttribute('title', 'styles');
826 link.setAttribute('onload', `this.title='';this.rel='stylesheet'`);
827 noscriptFallback = true;
828 } else if (preloadMode === 'swap') {
829 link.setAttribute('onload', "this.rel='stylesheet'");
830 noscriptFallback = true;
831 } else {
832 const bodyLink = document.createElement('link');
833 bodyLink.setAttribute('rel', 'stylesheet');
834 if (media) bodyLink.setAttribute('media', media);
835 bodyLink.setAttribute('href', href);
836 document.body.appendChild(bodyLink);
837 style.$$links.push(bodyLink);
838 }
839 }
840
841 if (this.options.noscriptFallback !== false && noscriptFallback) {
842 const noscript = document.createElement('noscript');
843 const noscriptLink = document.createElement('link');
844 noscriptLink.setAttribute('rel', 'stylesheet');
845 noscriptLink.setAttribute('href', href);
846 if (media) noscriptLink.setAttribute('media', media);
847 noscript.appendChild(noscriptLink);
848 link.parentNode.insertBefore(noscript, link.nextSibling);
849 style.$$links.push(noscript);
850 }
851 }
852 /**
853 * Prune the source CSS files
854 */
855
856
857 pruneSource(style, before, sheetInverse) {
858 // if external stylesheet would be below minimum size, just inline everything
859 const minSize = this.options.minimumExternalSize;
860 const name = style.$$name;
861
862 if (minSize && sheetInverse.length < minSize) {
863 this.logger.info(`\u001b[32mInlined all of ${name} (non-critical external stylesheet would have been ${sheetInverse.length}b, which was below the threshold of ${minSize})\u001b[39m`);
864 style.textContent = before; // remove any associated external resources/loaders:
865
866 if (style.$$links) {
867 for (const link of style.$$links) {
868 const parent = link.parentNode;
869 if (parent) parent.removeChild(link);
870 }
871 }
872
873 return true;
874 }
875
876 return false;
877 }
878 /**
879 * Parse the stylesheet within a <style> element, then reduce it to contain only rules used by the document.
880 */
881
882
883 async processStyle(style, document) {
884 if (style.$$reduce === false) return;
885 const name = style.$$name ? style.$$name.replace(/^\//, '') : 'inline CSS';
886 const options = this.options; // const document = style.ownerDocument;
887
888 const head = document.querySelector('head');
889 let keyframesMode = options.keyframes || 'critical'; // we also accept a boolean value for options.keyframes
890
891 if (keyframesMode === true) keyframesMode = 'all';
892 if (keyframesMode === false) keyframesMode = 'none';
893 let sheet = style.textContent; // store a reference to the previous serialized stylesheet for reporting stats
894
895 const before = sheet; // Skip empty stylesheets
896
897 if (!sheet) return;
898 const ast = parseStylesheet(sheet);
899 const astInverse = options.pruneSource ? parseStylesheet(sheet) : null; // a string to search for font names (very loose)
900
901 let criticalFonts = '';
902 const failedSelectors = [];
903 const criticalKeyframeNames = []; // Walk all CSS rules, marking unused rules with `.$$remove=true` for removal in the second pass.
904 // This first pass is also used to collect font and keyframe usage used in the second pass.
905
906 walkStyleRules(ast, markOnly(rule => {
907 if (rule.type === 'rule') {
908 // Filter the selector list down to only those match
909 rule.filterSelectors(sel => {
910 // Strip pseudo-elements and pseudo-classes, since we only care that their associated elements exist.
911 // This means any selector for a pseudo-element or having a pseudo-class will be inlined if the rest of the selector matches.
912 if (sel === ':root' || sel.match(/^::?(before|after)$/)) {
913 return true;
914 }
915
916 sel = sel.replace(/(?<!\\)::?[a-z-]+(?![a-z-(])/gi, '').replace(/::?not\(\s*\)/g, '').trim();
917 if (!sel) return false;
918
919 try {
920 return document.querySelector(sel) != null;
921 } catch (e) {
922 failedSelectors.push(sel + ' -> ' + e.message);
923 return false;
924 }
925 }); // If there are no matched selectors, remove the rule:
926
927 if (!rule.selector) {
928 return false;
929 }
930
931 if (rule.nodes) {
932 for (let i = 0; i < rule.nodes.length; i++) {
933 const decl = rule.nodes[i]; // detect used fonts
934
935 if (decl.prop && decl.prop.match(/\bfont(-family)?\b/i)) {
936 criticalFonts += ' ' + decl.value;
937 } // detect used keyframes
938
939
940 if (decl.prop === 'animation' || decl.prop === 'animation-name') {
941 // @todo: parse animation declarations and extract only the name. for now we'll do a lazy match.
942 const names = decl.value.split(/\s+/);
943
944 for (let j = 0; j < names.length; j++) {
945 const name = names[j].trim();
946 if (name) criticalKeyframeNames.push(name);
947 }
948 }
949 }
950 }
951 } // keep font rules, they're handled in the second pass:
952
953
954 if (rule.type === 'atrule' && rule.name === 'font-face') return; // If there are no remaining rules, remove the whole rule:
955
956 const rules = rule.nodes && rule.nodes.filter(rule => !rule.$$remove);
957 return !rules || rules.length !== 0;
958 }));
959
960 if (failedSelectors.length !== 0) {
961 this.logger.warn(`${failedSelectors.length} rules skipped due to selector errors:\n ${failedSelectors.join('\n ')}`);
962 }
963
964 const shouldPreloadFonts = options.fonts === true || options.preloadFonts === true;
965 const shouldInlineFonts = options.fonts !== false && options.inlineFonts === true;
966 const preloadedFonts = []; // Second pass, using data picked up from the first
967
968 walkStyleRulesWithReverseMirror(ast, astInverse, rule => {
969 // remove any rules marked in the first pass
970 if (rule.$$remove === true) return false;
971 applyMarkedSelectors(rule); // prune @keyframes rules
972
973 if (rule.type === 'atrule' && rule.name === 'keyframes') {
974 if (keyframesMode === 'none') return false;
975 if (keyframesMode === 'all') return true;
976 return criticalKeyframeNames.indexOf(rule.params) !== -1;
977 } // prune @font-face rules
978
979
980 if (rule.type === 'atrule' && rule.name === 'font-face') {
981 let family, src;
982
983 for (let i = 0; i < rule.nodes.length; i++) {
984 const decl = rule.nodes[i];
985
986 if (decl.prop === 'src') {
987 // @todo parse this properly and generate multiple preloads with type="font/woff2" etc
988 src = (decl.value.match(/url\s*\(\s*(['"]?)(.+?)\1\s*\)/) || [])[2];
989 } else if (decl.prop === 'font-family') {
990 family = decl.value;
991 }
992 }
993
994 if (src && shouldPreloadFonts && preloadedFonts.indexOf(src) === -1) {
995 preloadedFonts.push(src);
996 const preload = document.createElement('link');
997 preload.setAttribute('rel', 'preload');
998 preload.setAttribute('as', 'font');
999 preload.setAttribute('crossorigin', 'anonymous');
1000 preload.setAttribute('href', src.trim());
1001 head.appendChild(preload);
1002 } // if we're missing info, if the font is unused, or if critical font inlining is disabled, remove the rule:
1003
1004
1005 if (!family || !src || criticalFonts.indexOf(family) === -1 || !shouldInlineFonts) {
1006 return false;
1007 }
1008 }
1009 });
1010 sheet = serializeStylesheet(ast, {
1011 compress: this.options.compress !== false
1012 }); // If all rules were removed, get rid of the style element entirely
1013
1014 if (sheet.trim().length === 0) {
1015 if (style.parentNode) {
1016 style.remove();
1017 }
1018
1019 return;
1020 }
1021
1022 let afterText = '';
1023 let styleInlinedCompletely = false;
1024
1025 if (options.pruneSource) {
1026 const sheetInverse = serializeStylesheet(astInverse, {
1027 compress: this.options.compress !== false
1028 });
1029 styleInlinedCompletely = this.pruneSource(style, before, sheetInverse);
1030
1031 if (styleInlinedCompletely) {
1032 const percent = sheetInverse.length / before.length * 100;
1033 afterText = `, reducing non-inlined size ${percent | 0}% to ${prettyBytes(sheetInverse.length)}`;
1034 }
1035 } // replace the inline stylesheet with its critical'd counterpart
1036
1037
1038 if (!styleInlinedCompletely) {
1039 style.textContent = sheet;
1040 } // output stats
1041
1042
1043 const percent = sheet.length / before.length * 100 | 0;
1044 this.logger.info('\u001b[32mInlined ' + prettyBytes(sheet.length) + ' (' + percent + '% of original ' + prettyBytes(before.length) + ') of ' + name + afterText + '.\u001b[39m');
1045 }
1046
1047}
1048
1049export default Critters;
Note: See TracBrowser for help on using the repository browser.