single-file-core 1.1.76 → 1.1.78

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (37) hide show
  1. package/.eslintrc.js +0 -0
  2. package/LICENSE +0 -0
  3. package/core/constants.js +13 -0
  4. package/core/helper.js +604 -596
  5. package/core/index.js +2234 -2231
  6. package/core/infobar.js +276 -272
  7. package/core/util.js +408 -407
  8. package/modules/css-fonts-alt-minifier.js +342 -342
  9. package/modules/css-fonts-minifier.js +376 -376
  10. package/modules/css-matched-rules.js +0 -0
  11. package/modules/css-medias-alt-minifier.js +90 -90
  12. package/modules/css-rules-minifier.js +0 -0
  13. package/modules/html-images-alt-minifier.js +0 -0
  14. package/modules/html-minifier.js +0 -0
  15. package/modules/html-serializer.js +0 -0
  16. package/modules/index.js +0 -0
  17. package/modules/template-formatter.js +0 -0
  18. package/package.json +18 -18
  19. package/processors/frame-tree/content/content-frame-tree.js +426 -424
  20. package/processors/hooks/content/content-hooks-frames-web.js +0 -0
  21. package/processors/hooks/content/content-hooks-frames.js +0 -0
  22. package/processors/index.js +0 -0
  23. package/processors/lazy/content/content-lazy-loader.js +233 -233
  24. package/single-file-bootstrap.js +55 -55
  25. package/single-file-editor-helper.js +49 -49
  26. package/single-file-frames.js +0 -0
  27. package/single-file-hooks-frames.js +0 -0
  28. package/single-file-infobar.js +62 -62
  29. package/single-file.js +101 -101
  30. package/vendor/css-font-property-parser.js +0 -0
  31. package/vendor/css-media-query-parser.js +0 -0
  32. package/vendor/css-minifier.js +0 -0
  33. package/vendor/css-tree.js +0 -0
  34. package/vendor/css-unescape.js +0 -0
  35. package/vendor/html-srcset-parser.js +0 -0
  36. package/vendor/index.js +0 -0
  37. package/vendor/mime-type-parser.js +0 -0
@@ -1,343 +1,343 @@
1
- /*
2
- * Copyright 2010-2022 Gildas Lormeau
3
- * contact : gildas.lormeau <at> gmail.com
4
- *
5
- * This file is part of SingleFile.
6
- *
7
- * The code in this file is free software: you can redistribute it and/or
8
- * modify it under the terms of the GNU Affero General Public License
9
- * (GNU AGPL) as published by the Free Software Foundation, either version 3
10
- * of the License, or (at your option) any later version.
11
- *
12
- * The code in this file is distributed in the hope that it will be useful,
13
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
14
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero
15
- * General Public License for more details.
16
- *
17
- * As additional permission under GNU AGPL version 3 section 7, you may
18
- * distribute UNMODIFIED VERSIONS OF THIS file without the copy of the GNU
19
- * AGPL normally required by section 4, provided you include this license
20
- * notice and a URL through which recipients can access the Corresponding
21
- * Source.
22
- */
23
-
24
- /* global globalThis */
25
-
26
- import * as cssTree from "./../vendor/css-tree.js";
27
- import {
28
- normalizeFontFamily,
29
- getFontWeight
30
- } from "./../core/helper.js";
31
-
32
- const helper = {
33
- normalizeFontFamily,
34
- getFontWeight
35
- };
36
-
37
- const FontFace = globalThis.FontFace;
38
- const JSON = globalThis.JSON;
39
-
40
- const REGEXP_URL_SIMPLE_QUOTES_FN = /url\s*\(\s*'(.*?)'\s*\)/i;
41
- const REGEXP_URL_DOUBLE_QUOTES_FN = /url\s*\(\s*"(.*?)"\s*\)/i;
42
- const REGEXP_URL_NO_QUOTES_FN = /url\s*\(\s*(.*?)\s*\)/i;
43
- const REGEXP_URL_FUNCTION = /(url|local|-sf-url-original)\(.*?\)\s*(,|$)/g;
44
- const REGEXP_SIMPLE_QUOTES_STRING = /^'(.*?)'$/;
45
- const REGEXP_DOUBLE_QUOTES_STRING = /^"(.*?)"$/;
46
- const REGEXP_URL_FUNCTION_WOFF = /^url\(\s*["']?data:font\/(woff2?)/;
47
- const REGEXP_URL_FUNCTION_WOFF_ALT = /^url\(\s*["']?data:application\/x-font-(woff)/;
48
- const REGEXP_FONT_FORMAT = /\.([^.?#]+)((\?|#).*?)?$/;
49
- const REGEXP_FONT_FORMAT_VALUE = /format\((.*?)\)\s*,?$/;
50
- const REGEXP_FONT_SRC = /(.*?)\s*,?$/;
51
- const EMPTY_URL_SOURCE = /^url\(["']?data:[^,]*,?["']?\)/;
52
- const LOCAL_SOURCE = "local(";
53
- const MEDIA_ALL = "all";
54
- const FONT_STRETCHES = {
55
- "ultra-condensed": "50%",
56
- "extra-condensed": "62.5%",
57
- "condensed": "75%",
58
- "semi-condensed": "87.5%",
59
- "normal": "100%",
60
- "semi-expanded": "112.5%",
61
- "expanded": "125%",
62
- "extra-expanded": "150%",
63
- "ultra-expanded": "200%"
64
- };
65
- const FONT_MAX_LOAD_DELAY = 5000;
66
-
67
- export {
68
- process
69
- };
70
-
71
- async function process(doc, stylesheets, fontDeclarations, fontTests) {
72
- const fontsDetails = {
73
- fonts: new Map(),
74
- medias: new Map(),
75
- supports: new Map()
76
- };
77
- const stats = { rules: { processed: 0, discarded: 0 }, fonts: { processed: 0, discarded: 0 } };
78
- let sheetIndex = 0;
79
- stylesheets.forEach(stylesheetInfo => {
80
- const cssRules = stylesheetInfo.stylesheet.children;
81
- if (cssRules) {
82
- stats.rules.processed += cssRules.size;
83
- stats.rules.discarded += cssRules.size;
84
- if (stylesheetInfo.mediaText && stylesheetInfo.mediaText != MEDIA_ALL) {
85
- const mediaFontsDetails = createFontsDetailsInfo();
86
- fontsDetails.medias.set("media-" + sheetIndex + "-" + stylesheetInfo.mediaText, mediaFontsDetails);
87
- getFontsDetails(doc, cssRules, sheetIndex, mediaFontsDetails);
88
- } else {
89
- getFontsDetails(doc, cssRules, sheetIndex, fontsDetails);
90
- }
91
- }
92
- sheetIndex++;
93
- });
94
- processFontDetails(fontsDetails);
95
- await Promise.all([...stylesheets].map(async ([, stylesheetInfo], sheetIndex) => {
96
- const cssRules = stylesheetInfo.stylesheet.children;
97
- const media = stylesheetInfo.mediaText;
98
- if (cssRules) {
99
- if (media && media != MEDIA_ALL) {
100
- await processFontFaceRules(cssRules, sheetIndex, fontsDetails.medias.get("media-" + sheetIndex + "-" + media), fontDeclarations, fontTests, stats);
101
- } else {
102
- await processFontFaceRules(cssRules, sheetIndex, fontsDetails, fontDeclarations, fontTests, stats);
103
- }
104
- stats.rules.discarded -= cssRules.size;
105
- }
106
- }));
107
- return stats;
108
- }
109
-
110
- function getFontsDetails(doc, cssRules, sheetIndex, mediaFontsDetails) {
111
- let mediaIndex = 0, supportsIndex = 0;
112
- cssRules.forEach(ruleData => {
113
- if (ruleData.type == "Atrule" && ruleData.name == "media" && ruleData.block && ruleData.block.children && ruleData.prelude) {
114
- const mediaText = cssTree.generate(ruleData.prelude);
115
- const fontsDetails = createFontsDetailsInfo();
116
- mediaFontsDetails.medias.set("media-" + sheetIndex + "-" + mediaIndex + "-" + mediaText, fontsDetails);
117
- mediaIndex++;
118
- getFontsDetails(doc, ruleData.block.children, sheetIndex, fontsDetails);
119
- } else if (ruleData.type == "Atrule" && ruleData.name == "supports" && ruleData.block && ruleData.block.children && ruleData.prelude) {
120
- const supportsText = cssTree.generate(ruleData.prelude);
121
- const fontsDetails = createFontsDetailsInfo();
122
- mediaFontsDetails.supports.set("supports-" + sheetIndex + "-" + supportsIndex + "-" + supportsText, fontsDetails);
123
- supportsIndex++;
124
- getFontsDetails(doc, ruleData.block.children, sheetIndex, fontsDetails);
125
- } else if (ruleData.type == "Atrule" && ruleData.name == "font-face" && ruleData.block && ruleData.block.children) {
126
- const fontKey = getFontKey(ruleData);
127
- let fontInfo = mediaFontsDetails.fonts.get(fontKey);
128
- if (!fontInfo) {
129
- fontInfo = [];
130
- mediaFontsDetails.fonts.set(fontKey, fontInfo);
131
- }
132
- const src = getPropertyValue(ruleData, "src");
133
- if (src) {
134
- const fontSources = src.match(REGEXP_URL_FUNCTION);
135
- if (fontSources) {
136
- fontSources.forEach(source => fontInfo.unshift(source));
137
- }
138
- }
139
- }
140
- });
141
- }
142
-
143
- function processFontDetails(fontsDetails) {
144
- fontsDetails.fonts.forEach((fontInfo, fontKey) => {
145
- fontsDetails.fonts.set(fontKey, fontInfo.map(fontSource => {
146
- const fontFormatMatch = fontSource.match(REGEXP_FONT_FORMAT_VALUE);
147
- let fontFormat;
148
- const fontUrl = getURL(fontSource);
149
- if (fontFormatMatch && fontFormatMatch[1]) {
150
- fontFormat = fontFormatMatch[1].replace(REGEXP_SIMPLE_QUOTES_STRING, "$1").replace(REGEXP_DOUBLE_QUOTES_STRING, "$1").toLowerCase();
151
- }
152
- if (!fontFormat) {
153
- const fontFormatMatch = fontSource.match(REGEXP_URL_FUNCTION_WOFF);
154
- if (fontFormatMatch && fontFormatMatch[1]) {
155
- fontFormat = fontFormatMatch[1];
156
- } else {
157
- const fontFormatMatch = fontSource.match(REGEXP_URL_FUNCTION_WOFF_ALT);
158
- if (fontFormatMatch && fontFormatMatch[1]) {
159
- fontFormat = fontFormatMatch[1];
160
- }
161
- }
162
- }
163
- if (!fontFormat && fontUrl) {
164
- const fontFormatMatch = fontUrl.match(REGEXP_FONT_FORMAT);
165
- if (fontFormatMatch && fontFormatMatch[1]) {
166
- fontFormat = fontFormatMatch[1];
167
- }
168
- }
169
- return { src: fontSource.match(REGEXP_FONT_SRC)[1], fontUrl, format: fontFormat };
170
- }));
171
- });
172
- fontsDetails.medias.forEach(mediaFontsDetails => processFontDetails(mediaFontsDetails));
173
- fontsDetails.supports.forEach(supportsFontsDetails => processFontDetails(supportsFontsDetails));
174
- }
175
-
176
- async function processFontFaceRules(cssRules, sheetIndex, fontsDetails, fontDeclarations, fontTests, stats) {
177
- const removedRules = [];
178
- let mediaIndex = 0, supportsIndex = 0;
179
- for (let cssRule = cssRules.head; cssRule; cssRule = cssRule.next) {
180
- const ruleData = cssRule.data;
181
- if (ruleData.type == "Atrule" && ruleData.name == "media" && ruleData.block && ruleData.block.children && ruleData.prelude) {
182
- const mediaText = cssTree.generate(ruleData.prelude);
183
- await processFontFaceRules(ruleData.block.children, sheetIndex, fontsDetails.medias.get("media-" + sheetIndex + "-" + mediaIndex + "-" + mediaText), fontDeclarations, fontTests, stats);
184
- mediaIndex++;
185
- } else if (ruleData.type == "Atrule" && ruleData.name == "supports" && ruleData.block && ruleData.block.children && ruleData.prelude) {
186
- const supportsText = cssTree.generate(ruleData.prelude);
187
- await processFontFaceRules(ruleData.block.children, sheetIndex, fontsDetails.supports.get("supports-" + sheetIndex + "-" + supportsIndex + "-" + supportsText), fontDeclarations, fontTests, stats);
188
- supportsIndex++;
189
- } else if (ruleData.type == "Atrule" && ruleData.name == "font-face") {
190
- const key = getFontKey(ruleData);
191
- const fontInfo = fontsDetails.fonts.get(key);
192
- if (fontInfo) {
193
- const processed = await processFontFaceRule(ruleData, fontInfo, fontDeclarations, fontTests, stats);
194
- if (processed) {
195
- fontsDetails.fonts.delete(key);
196
- }
197
- } else {
198
- removedRules.push(cssRule);
199
- }
200
- }
201
- }
202
- removedRules.forEach(cssRule => cssRules.remove(cssRule));
203
- }
204
-
205
- async function processFontFaceRule(ruleData, fontInfo, fontDeclarations, fontTests, stats) {
206
- const removedNodes = [];
207
- for (let node = ruleData.block.children.head; node; node = node.next) {
208
- if (node.data.property == "src") {
209
- removedNodes.push(node);
210
- }
211
- }
212
- removedNodes.pop();
213
- removedNodes.forEach(node => ruleData.block.children.remove(node));
214
- const srcDeclaration = ruleData.block.children.filter(node => node.property == "src").tail;
215
- if (srcDeclaration) {
216
- await Promise.all(fontInfo.map(async source => {
217
- if (fontTests.has(source.src)) {
218
- source.valid = fontTests.get(source.src);
219
- } else {
220
- if (FontFace && source.fontUrl) {
221
- const fontFace = new FontFace("test-font", source.src);
222
- try {
223
- let timeout;
224
- await Promise.race([
225
- fontFace.load().then(() => fontFace.loaded).then(() => { source.valid = true; globalThis.clearTimeout(timeout); }),
226
- new Promise(resolve => timeout = globalThis.setTimeout(() => { source.valid = true; resolve(); }, FONT_MAX_LOAD_DELAY))
227
- ]);
228
- } catch (error) {
229
- const urlNodes = cssTree.findAll(srcDeclaration.data, node => node.type == "Url");
230
- const declarationFontURLs = Array.from(fontDeclarations).find(([node]) => urlNodes.includes(node) && node.value == source.fontUrl);
231
- if (declarationFontURLs && declarationFontURLs[1].length) {
232
- const fontURL = declarationFontURLs[1][0];
233
- if (fontURL) {
234
- const fontFace = new FontFace("test-font", "url(" + fontURL + ")");
235
- try {
236
- let timeout;
237
- await Promise.race([
238
- fontFace.load().then(() => fontFace.loaded).then(() => { source.valid = true; globalThis.clearTimeout(timeout); }),
239
- new Promise(resolve => timeout = globalThis.setTimeout(() => { source.valid = true; resolve(); }, FONT_MAX_LOAD_DELAY))
240
- ]);
241
- } catch (error) {
242
- // ignored
243
- }
244
- }
245
- } else {
246
- source.valid = true;
247
- }
248
- }
249
- } else {
250
- source.valid = true;
251
- }
252
- fontTests.set(source.src, source.valid);
253
- }
254
- }));
255
- const findSourceByFormat = (fontFormat, testValidity) => fontInfo.find(source => !source.src.match(EMPTY_URL_SOURCE) && source.format == fontFormat && (!testValidity || source.valid));
256
- const filterSources = fontSource => fontInfo.filter(source => source == fontSource || source.src.startsWith(LOCAL_SOURCE));
257
- stats.fonts.processed += fontInfo.length;
258
- stats.fonts.discarded += fontInfo.length;
259
- const woffFontFound =
260
- findSourceByFormat("woff2-variations", true) || findSourceByFormat("woff2", true) || findSourceByFormat("woff", true);
261
- if (woffFontFound) {
262
- fontInfo = filterSources(woffFontFound);
263
- } else {
264
- const ttfFontFound =
265
- findSourceByFormat("truetype-variations", true) || findSourceByFormat("truetype", true);
266
- if (ttfFontFound) {
267
- fontInfo = filterSources(ttfFontFound);
268
- } else {
269
- const otfFontFound =
270
- findSourceByFormat("opentype") || findSourceByFormat("embedded-opentype");
271
- if (otfFontFound) {
272
- fontInfo = filterSources(otfFontFound);
273
- } else {
274
- fontInfo = fontInfo.filter(source => !source.src.match(EMPTY_URL_SOURCE) && (source.valid) || source.src.startsWith(LOCAL_SOURCE));
275
- }
276
- }
277
- }
278
- stats.fonts.discarded -= fontInfo.length;
279
- fontInfo.reverse();
280
- try {
281
- srcDeclaration.data.value = cssTree.parse(fontInfo.map(fontSource => fontSource.src).join(","), { context: "value", parseCustomProperty: true });
282
- }
283
- catch (error) {
284
- // ignored
285
- }
286
- return true;
287
- } else {
288
- return false;
289
- }
290
- }
291
-
292
- function getPropertyValue(ruleData, propertyName) {
293
- let property;
294
- if (ruleData.block.children) {
295
- property = ruleData.block.children.filter(node => {
296
- try {
297
- return node.property == propertyName && !cssTree.generate(node.value).match(/\\9$/);
298
- } catch (error) {
299
- return node.property == propertyName;
300
- }
301
- }).tail;
302
- }
303
- if (property) {
304
- try {
305
- return cssTree.generate(property.data.value);
306
- } catch (error) {
307
- // ignored
308
- }
309
- }
310
- }
311
-
312
- function getFontKey(ruleData) {
313
- return JSON.stringify([
314
- helper.normalizeFontFamily(getPropertyValue(ruleData, "font-family")),
315
- helper.getFontWeight(getPropertyValue(ruleData, "font-weight") || "400"),
316
- getPropertyValue(ruleData, "font-style") || "normal",
317
- getPropertyValue(ruleData, "unicode-range"),
318
- getFontStretch(getPropertyValue(ruleData, "font-stretch")),
319
- getPropertyValue(ruleData, "font-variant") || "normal",
320
- getPropertyValue(ruleData, "font-feature-settings"),
321
- getPropertyValue(ruleData, "font-variation-settings")
322
- ]);
323
- }
324
-
325
- function getFontStretch(stretch) {
326
- return FONT_STRETCHES[stretch] || stretch;
327
- }
328
-
329
- function createFontsDetailsInfo() {
330
- return {
331
- fonts: new Map(),
332
- medias: new Map(),
333
- supports: new Map()
334
- };
335
- }
336
-
337
- function getURL(urlFunction) {
338
- urlFunction = urlFunction.replace(/url\(-sf-url-original\\\(\\"(.*?)\\"\\\)\\ /g, "");
339
- const urlMatch = urlFunction.match(REGEXP_URL_SIMPLE_QUOTES_FN) ||
340
- urlFunction.match(REGEXP_URL_DOUBLE_QUOTES_FN) ||
341
- urlFunction.match(REGEXP_URL_NO_QUOTES_FN);
342
- return urlMatch && urlMatch[1];
1
+ /*
2
+ * Copyright 2010-2022 Gildas Lormeau
3
+ * contact : gildas.lormeau <at> gmail.com
4
+ *
5
+ * This file is part of SingleFile.
6
+ *
7
+ * The code in this file is free software: you can redistribute it and/or
8
+ * modify it under the terms of the GNU Affero General Public License
9
+ * (GNU AGPL) as published by the Free Software Foundation, either version 3
10
+ * of the License, or (at your option) any later version.
11
+ *
12
+ * The code in this file is distributed in the hope that it will be useful,
13
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
14
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero
15
+ * General Public License for more details.
16
+ *
17
+ * As additional permission under GNU AGPL version 3 section 7, you may
18
+ * distribute UNMODIFIED VERSIONS OF THIS file without the copy of the GNU
19
+ * AGPL normally required by section 4, provided you include this license
20
+ * notice and a URL through which recipients can access the Corresponding
21
+ * Source.
22
+ */
23
+
24
+ /* global globalThis */
25
+
26
+ import * as cssTree from "./../vendor/css-tree.js";
27
+ import {
28
+ normalizeFontFamily,
29
+ getFontWeight
30
+ } from "./../core/helper.js";
31
+
32
+ const helper = {
33
+ normalizeFontFamily,
34
+ getFontWeight
35
+ };
36
+
37
+ const FontFace = globalThis.FontFace;
38
+ const JSON = globalThis.JSON;
39
+
40
+ const REGEXP_URL_SIMPLE_QUOTES_FN = /url\s*\(\s*'(.*?)'\s*\)/i;
41
+ const REGEXP_URL_DOUBLE_QUOTES_FN = /url\s*\(\s*"(.*?)"\s*\)/i;
42
+ const REGEXP_URL_NO_QUOTES_FN = /url\s*\(\s*(.*?)\s*\)/i;
43
+ const REGEXP_URL_FUNCTION = /(url|local|-sf-url-original)\(.*?\)\s*(,|$)/g;
44
+ const REGEXP_SIMPLE_QUOTES_STRING = /^'(.*?)'$/;
45
+ const REGEXP_DOUBLE_QUOTES_STRING = /^"(.*?)"$/;
46
+ const REGEXP_URL_FUNCTION_WOFF = /^url\(\s*["']?data:font\/(woff2?)/;
47
+ const REGEXP_URL_FUNCTION_WOFF_ALT = /^url\(\s*["']?data:application\/x-font-(woff)/;
48
+ const REGEXP_FONT_FORMAT = /\.([^.?#]+)((\?|#).*?)?$/;
49
+ const REGEXP_FONT_FORMAT_VALUE = /format\((.*?)\)\s*,?$/;
50
+ const REGEXP_FONT_SRC = /(.*?)\s*,?$/;
51
+ const EMPTY_URL_SOURCE = /^url\(["']?data:[^,]*,?["']?\)/;
52
+ const LOCAL_SOURCE = "local(";
53
+ const MEDIA_ALL = "all";
54
+ const FONT_STRETCHES = {
55
+ "ultra-condensed": "50%",
56
+ "extra-condensed": "62.5%",
57
+ "condensed": "75%",
58
+ "semi-condensed": "87.5%",
59
+ "normal": "100%",
60
+ "semi-expanded": "112.5%",
61
+ "expanded": "125%",
62
+ "extra-expanded": "150%",
63
+ "ultra-expanded": "200%"
64
+ };
65
+ const FONT_MAX_LOAD_DELAY = 5000;
66
+
67
+ export {
68
+ process
69
+ };
70
+
71
+ async function process(doc, stylesheets, fontDeclarations, fontTests) {
72
+ const fontsDetails = {
73
+ fonts: new Map(),
74
+ medias: new Map(),
75
+ supports: new Map()
76
+ };
77
+ const stats = { rules: { processed: 0, discarded: 0 }, fonts: { processed: 0, discarded: 0 } };
78
+ let sheetIndex = 0;
79
+ stylesheets.forEach(stylesheetInfo => {
80
+ const cssRules = stylesheetInfo.stylesheet.children;
81
+ if (cssRules) {
82
+ stats.rules.processed += cssRules.size;
83
+ stats.rules.discarded += cssRules.size;
84
+ if (stylesheetInfo.mediaText && stylesheetInfo.mediaText != MEDIA_ALL) {
85
+ const mediaFontsDetails = createFontsDetailsInfo();
86
+ fontsDetails.medias.set("media-" + sheetIndex + "-" + stylesheetInfo.mediaText, mediaFontsDetails);
87
+ getFontsDetails(doc, cssRules, sheetIndex, mediaFontsDetails);
88
+ } else {
89
+ getFontsDetails(doc, cssRules, sheetIndex, fontsDetails);
90
+ }
91
+ }
92
+ sheetIndex++;
93
+ });
94
+ processFontDetails(fontsDetails);
95
+ await Promise.all([...stylesheets].map(async ([, stylesheetInfo], sheetIndex) => {
96
+ const cssRules = stylesheetInfo.stylesheet.children;
97
+ const media = stylesheetInfo.mediaText;
98
+ if (cssRules) {
99
+ if (media && media != MEDIA_ALL) {
100
+ await processFontFaceRules(cssRules, sheetIndex, fontsDetails.medias.get("media-" + sheetIndex + "-" + media), fontDeclarations, fontTests, stats);
101
+ } else {
102
+ await processFontFaceRules(cssRules, sheetIndex, fontsDetails, fontDeclarations, fontTests, stats);
103
+ }
104
+ stats.rules.discarded -= cssRules.size;
105
+ }
106
+ }));
107
+ return stats;
108
+ }
109
+
110
+ function getFontsDetails(doc, cssRules, sheetIndex, mediaFontsDetails) {
111
+ let mediaIndex = 0, supportsIndex = 0;
112
+ cssRules.forEach(ruleData => {
113
+ if (ruleData.type == "Atrule" && ruleData.name == "media" && ruleData.block && ruleData.block.children && ruleData.prelude) {
114
+ const mediaText = cssTree.generate(ruleData.prelude);
115
+ const fontsDetails = createFontsDetailsInfo();
116
+ mediaFontsDetails.medias.set("media-" + sheetIndex + "-" + mediaIndex + "-" + mediaText, fontsDetails);
117
+ mediaIndex++;
118
+ getFontsDetails(doc, ruleData.block.children, sheetIndex, fontsDetails);
119
+ } else if (ruleData.type == "Atrule" && ruleData.name == "supports" && ruleData.block && ruleData.block.children && ruleData.prelude) {
120
+ const supportsText = cssTree.generate(ruleData.prelude);
121
+ const fontsDetails = createFontsDetailsInfo();
122
+ mediaFontsDetails.supports.set("supports-" + sheetIndex + "-" + supportsIndex + "-" + supportsText, fontsDetails);
123
+ supportsIndex++;
124
+ getFontsDetails(doc, ruleData.block.children, sheetIndex, fontsDetails);
125
+ } else if (ruleData.type == "Atrule" && ruleData.name == "font-face" && ruleData.block && ruleData.block.children) {
126
+ const fontKey = getFontKey(ruleData);
127
+ let fontInfo = mediaFontsDetails.fonts.get(fontKey);
128
+ if (!fontInfo) {
129
+ fontInfo = [];
130
+ mediaFontsDetails.fonts.set(fontKey, fontInfo);
131
+ }
132
+ const src = getPropertyValue(ruleData, "src");
133
+ if (src) {
134
+ const fontSources = src.match(REGEXP_URL_FUNCTION);
135
+ if (fontSources) {
136
+ fontSources.forEach(source => fontInfo.unshift(source));
137
+ }
138
+ }
139
+ }
140
+ });
141
+ }
142
+
143
+ function processFontDetails(fontsDetails) {
144
+ fontsDetails.fonts.forEach((fontInfo, fontKey) => {
145
+ fontsDetails.fonts.set(fontKey, fontInfo.map(fontSource => {
146
+ const fontFormatMatch = fontSource.match(REGEXP_FONT_FORMAT_VALUE);
147
+ let fontFormat;
148
+ const fontUrl = getURL(fontSource);
149
+ if (fontFormatMatch && fontFormatMatch[1]) {
150
+ fontFormat = fontFormatMatch[1].replace(REGEXP_SIMPLE_QUOTES_STRING, "$1").replace(REGEXP_DOUBLE_QUOTES_STRING, "$1").toLowerCase();
151
+ }
152
+ if (!fontFormat) {
153
+ const fontFormatMatch = fontSource.match(REGEXP_URL_FUNCTION_WOFF);
154
+ if (fontFormatMatch && fontFormatMatch[1]) {
155
+ fontFormat = fontFormatMatch[1];
156
+ } else {
157
+ const fontFormatMatch = fontSource.match(REGEXP_URL_FUNCTION_WOFF_ALT);
158
+ if (fontFormatMatch && fontFormatMatch[1]) {
159
+ fontFormat = fontFormatMatch[1];
160
+ }
161
+ }
162
+ }
163
+ if (!fontFormat && fontUrl) {
164
+ const fontFormatMatch = fontUrl.match(REGEXP_FONT_FORMAT);
165
+ if (fontFormatMatch && fontFormatMatch[1]) {
166
+ fontFormat = fontFormatMatch[1];
167
+ }
168
+ }
169
+ return { src: fontSource.match(REGEXP_FONT_SRC)[1], fontUrl, format: fontFormat };
170
+ }));
171
+ });
172
+ fontsDetails.medias.forEach(mediaFontsDetails => processFontDetails(mediaFontsDetails));
173
+ fontsDetails.supports.forEach(supportsFontsDetails => processFontDetails(supportsFontsDetails));
174
+ }
175
+
176
+ async function processFontFaceRules(cssRules, sheetIndex, fontsDetails, fontDeclarations, fontTests, stats) {
177
+ const removedRules = [];
178
+ let mediaIndex = 0, supportsIndex = 0;
179
+ for (let cssRule = cssRules.head; cssRule; cssRule = cssRule.next) {
180
+ const ruleData = cssRule.data;
181
+ if (ruleData.type == "Atrule" && ruleData.name == "media" && ruleData.block && ruleData.block.children && ruleData.prelude) {
182
+ const mediaText = cssTree.generate(ruleData.prelude);
183
+ await processFontFaceRules(ruleData.block.children, sheetIndex, fontsDetails.medias.get("media-" + sheetIndex + "-" + mediaIndex + "-" + mediaText), fontDeclarations, fontTests, stats);
184
+ mediaIndex++;
185
+ } else if (ruleData.type == "Atrule" && ruleData.name == "supports" && ruleData.block && ruleData.block.children && ruleData.prelude) {
186
+ const supportsText = cssTree.generate(ruleData.prelude);
187
+ await processFontFaceRules(ruleData.block.children, sheetIndex, fontsDetails.supports.get("supports-" + sheetIndex + "-" + supportsIndex + "-" + supportsText), fontDeclarations, fontTests, stats);
188
+ supportsIndex++;
189
+ } else if (ruleData.type == "Atrule" && ruleData.name == "font-face") {
190
+ const key = getFontKey(ruleData);
191
+ const fontInfo = fontsDetails.fonts.get(key);
192
+ if (fontInfo) {
193
+ const processed = await processFontFaceRule(ruleData, fontInfo, fontDeclarations, fontTests, stats);
194
+ if (processed) {
195
+ fontsDetails.fonts.delete(key);
196
+ }
197
+ } else {
198
+ removedRules.push(cssRule);
199
+ }
200
+ }
201
+ }
202
+ removedRules.forEach(cssRule => cssRules.remove(cssRule));
203
+ }
204
+
205
+ async function processFontFaceRule(ruleData, fontInfo, fontDeclarations, fontTests, stats) {
206
+ const removedNodes = [];
207
+ for (let node = ruleData.block.children.head; node; node = node.next) {
208
+ if (node.data.property == "src") {
209
+ removedNodes.push(node);
210
+ }
211
+ }
212
+ removedNodes.pop();
213
+ removedNodes.forEach(node => ruleData.block.children.remove(node));
214
+ const srcDeclaration = ruleData.block.children.filter(node => node.property == "src").tail;
215
+ if (srcDeclaration) {
216
+ await Promise.all(fontInfo.map(async source => {
217
+ if (fontTests.has(source.src)) {
218
+ source.valid = fontTests.get(source.src);
219
+ } else {
220
+ if (FontFace && source.fontUrl) {
221
+ const fontFace = new FontFace("test-font", source.src);
222
+ try {
223
+ let timeout;
224
+ await Promise.race([
225
+ fontFace.load().then(() => fontFace.loaded).then(() => { source.valid = true; globalThis.clearTimeout(timeout); }),
226
+ new Promise(resolve => timeout = globalThis.setTimeout(() => { source.valid = true; resolve(); }, FONT_MAX_LOAD_DELAY))
227
+ ]);
228
+ } catch (error) {
229
+ const urlNodes = cssTree.findAll(srcDeclaration.data, node => node.type == "Url");
230
+ const declarationFontURLs = Array.from(fontDeclarations).find(([node]) => urlNodes.includes(node) && node.value == source.fontUrl);
231
+ if (declarationFontURLs && declarationFontURLs[1].length) {
232
+ const fontURL = declarationFontURLs[1][0];
233
+ if (fontURL) {
234
+ const fontFace = new FontFace("test-font", "url(" + fontURL + ")");
235
+ try {
236
+ let timeout;
237
+ await Promise.race([
238
+ fontFace.load().then(() => fontFace.loaded).then(() => { source.valid = true; globalThis.clearTimeout(timeout); }),
239
+ new Promise(resolve => timeout = globalThis.setTimeout(() => { source.valid = true; resolve(); }, FONT_MAX_LOAD_DELAY))
240
+ ]);
241
+ } catch (error) {
242
+ // ignored
243
+ }
244
+ }
245
+ } else {
246
+ source.valid = true;
247
+ }
248
+ }
249
+ } else {
250
+ source.valid = true;
251
+ }
252
+ fontTests.set(source.src, source.valid);
253
+ }
254
+ }));
255
+ const findSourceByFormat = (fontFormat, testValidity) => fontInfo.find(source => !source.src.match(EMPTY_URL_SOURCE) && source.format == fontFormat && (!testValidity || source.valid));
256
+ const filterSources = fontSource => fontInfo.filter(source => source == fontSource || source.src.startsWith(LOCAL_SOURCE));
257
+ stats.fonts.processed += fontInfo.length;
258
+ stats.fonts.discarded += fontInfo.length;
259
+ const woffFontFound =
260
+ findSourceByFormat("woff2-variations", true) || findSourceByFormat("woff2", true) || findSourceByFormat("woff", true);
261
+ if (woffFontFound) {
262
+ fontInfo = filterSources(woffFontFound);
263
+ } else {
264
+ const ttfFontFound =
265
+ findSourceByFormat("truetype-variations", true) || findSourceByFormat("truetype", true);
266
+ if (ttfFontFound) {
267
+ fontInfo = filterSources(ttfFontFound);
268
+ } else {
269
+ const otfFontFound =
270
+ findSourceByFormat("opentype") || findSourceByFormat("embedded-opentype");
271
+ if (otfFontFound) {
272
+ fontInfo = filterSources(otfFontFound);
273
+ } else {
274
+ fontInfo = fontInfo.filter(source => !source.src.match(EMPTY_URL_SOURCE) && (source.valid) || source.src.startsWith(LOCAL_SOURCE));
275
+ }
276
+ }
277
+ }
278
+ stats.fonts.discarded -= fontInfo.length;
279
+ fontInfo.reverse();
280
+ try {
281
+ srcDeclaration.data.value = cssTree.parse(fontInfo.map(fontSource => fontSource.src).join(","), { context: "value", parseCustomProperty: true });
282
+ }
283
+ catch (error) {
284
+ // ignored
285
+ }
286
+ return true;
287
+ } else {
288
+ return false;
289
+ }
290
+ }
291
+
292
+ function getPropertyValue(ruleData, propertyName) {
293
+ let property;
294
+ if (ruleData.block.children) {
295
+ property = ruleData.block.children.filter(node => {
296
+ try {
297
+ return node.property == propertyName && !cssTree.generate(node.value).match(/\\9$/);
298
+ } catch (error) {
299
+ return node.property == propertyName;
300
+ }
301
+ }).tail;
302
+ }
303
+ if (property) {
304
+ try {
305
+ return cssTree.generate(property.data.value);
306
+ } catch (error) {
307
+ // ignored
308
+ }
309
+ }
310
+ }
311
+
312
+ function getFontKey(ruleData) {
313
+ return JSON.stringify([
314
+ helper.normalizeFontFamily(getPropertyValue(ruleData, "font-family")),
315
+ helper.getFontWeight(getPropertyValue(ruleData, "font-weight") || "400"),
316
+ getPropertyValue(ruleData, "font-style") || "normal",
317
+ getPropertyValue(ruleData, "unicode-range"),
318
+ getFontStretch(getPropertyValue(ruleData, "font-stretch")),
319
+ getPropertyValue(ruleData, "font-variant") || "normal",
320
+ getPropertyValue(ruleData, "font-feature-settings"),
321
+ getPropertyValue(ruleData, "font-variation-settings")
322
+ ]);
323
+ }
324
+
325
+ function getFontStretch(stretch) {
326
+ return FONT_STRETCHES[stretch] || stretch;
327
+ }
328
+
329
+ function createFontsDetailsInfo() {
330
+ return {
331
+ fonts: new Map(),
332
+ medias: new Map(),
333
+ supports: new Map()
334
+ };
335
+ }
336
+
337
+ function getURL(urlFunction) {
338
+ urlFunction = urlFunction.replace(/url\(-sf-url-original\\\(\\"(.*?)\\"\\\)\\ /g, "");
339
+ const urlMatch = urlFunction.match(REGEXP_URL_SIMPLE_QUOTES_FN) ||
340
+ urlFunction.match(REGEXP_URL_DOUBLE_QUOTES_FN) ||
341
+ urlFunction.match(REGEXP_URL_NO_QUOTES_FN);
342
+ return urlMatch && urlMatch[1];
343
343
  }