source: trip-planner-front/node_modules/critters/dist/critters.cjs@ 6fe77af

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

primeNG components

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