single-file-core 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,371 @@
1
+ /*
2
+ * Copyright 2010-2020 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 * as fontPropertyParser from "./../vendor/css-font-property-parser.js";
28
+ import {
29
+ normalizeFontFamily,
30
+ flatten,
31
+ getFontWeight,
32
+ removeQuotes
33
+ } from "./../single-file-helper.js";
34
+
35
+ const helper = {
36
+ normalizeFontFamily,
37
+ flatten,
38
+ getFontWeight,
39
+ removeQuotes
40
+ };
41
+
42
+ const REGEXP_COMMA = /\s*,\s*/;
43
+ const REGEXP_DASH = /-/;
44
+ const REGEXP_QUESTION_MARK = /\?/g;
45
+ const REGEXP_STARTS_U_PLUS = /^U\+/i;
46
+ const VALID_FONT_STYLES = [/^normal$/, /^italic$/, /^oblique$/, /^oblique\s+/];
47
+
48
+ export {
49
+ process
50
+ };
51
+
52
+ function process(doc, stylesheets, styles, options) {
53
+ const stats = { rules: { processed: 0, discarded: 0 }, fonts: { processed: 0, discarded: 0 } };
54
+ const fontsInfo = { declared: [], used: [] };
55
+ const workStyleElement = doc.createElement("style");
56
+ let docContent = "";
57
+ doc.body.appendChild(workStyleElement);
58
+ stylesheets.forEach(stylesheetInfo => {
59
+ const cssRules = stylesheetInfo.stylesheet.children;
60
+ if (cssRules) {
61
+ stats.processed += cssRules.size;
62
+ stats.discarded += cssRules.size;
63
+ getFontsInfo(cssRules, fontsInfo);
64
+ docContent = getRulesTextContent(doc, cssRules, workStyleElement, docContent);
65
+ }
66
+ });
67
+ styles.forEach(declarations => {
68
+ const fontFamilyNames = getFontFamilyNames(declarations);
69
+ if (fontFamilyNames.length) {
70
+ fontsInfo.used.push(fontFamilyNames);
71
+ }
72
+ docContent = getDeclarationsTextContent(declarations.children, workStyleElement, docContent);
73
+ });
74
+ workStyleElement.remove();
75
+ docContent += doc.body.innerText;
76
+ if (globalThis.getComputedStyle && options.doc) {
77
+ fontsInfo.used = fontsInfo.used.map(fontNames => fontNames.map(familyName => {
78
+ const matchedVar = familyName.match(/^var\((--.*)\)$/);
79
+ if (matchedVar && matchedVar[1]) {
80
+ const computedFamilyName = globalThis.getComputedStyle(options.doc.body).getPropertyValue(matchedVar[1]);
81
+ return (computedFamilyName && computedFamilyName.split(",").map(name => helper.normalizeFontFamily(name))) || familyName;
82
+ }
83
+ return familyName;
84
+ }));
85
+ fontsInfo.used = fontsInfo.used.map(fontNames => helper.flatten(fontNames));
86
+ }
87
+ const variableFound = fontsInfo.used.find(fontNames => fontNames.find(fontName => fontName.startsWith("var(--")));
88
+ let unusedFonts, filteredUsedFonts;
89
+ if (variableFound) {
90
+ unusedFonts = [];
91
+ } else {
92
+ filteredUsedFonts = new Map();
93
+ fontsInfo.used.forEach(fontNames => fontNames.forEach(familyName => {
94
+ if (fontsInfo.declared.find(fontInfo => fontInfo.fontFamily == familyName)) {
95
+ const optionalData = options.usedFonts && options.usedFonts.filter(fontInfo => fontInfo[0] == familyName);
96
+ if (optionalData && optionalData.length) {
97
+ filteredUsedFonts.set(familyName, optionalData);
98
+ }
99
+ }
100
+ }));
101
+ unusedFonts = fontsInfo.declared.filter(fontInfo => !filteredUsedFonts.has(fontInfo.fontFamily));
102
+ }
103
+ stylesheets.forEach(stylesheetInfo => {
104
+ const cssRules = stylesheetInfo.stylesheet.children;
105
+ if (cssRules) {
106
+ filterUnusedFonts(cssRules, fontsInfo.declared, unusedFonts, filteredUsedFonts, docContent);
107
+ stats.rules.discarded -= cssRules.size;
108
+ }
109
+ });
110
+ return stats;
111
+ }
112
+
113
+ function getFontsInfo(cssRules, fontsInfo) {
114
+ cssRules.forEach(ruleData => {
115
+ if (ruleData.type == "Atrule" && (ruleData.name == "media" || ruleData.name == "supports") && ruleData.block && ruleData.block.children) {
116
+ getFontsInfo(ruleData.block.children, fontsInfo);
117
+ } else if (ruleData.type == "Rule") {
118
+ const fontFamilyNames = getFontFamilyNames(ruleData.block);
119
+ if (fontFamilyNames.length) {
120
+ fontsInfo.used.push(fontFamilyNames);
121
+ }
122
+ } else {
123
+ if (ruleData.type == "Atrule" && ruleData.name == "font-face") {
124
+ const fontFamily = helper.normalizeFontFamily(getDeclarationValue(ruleData.block.children, "font-family"));
125
+ if (fontFamily) {
126
+ const fontWeight = getDeclarationValue(ruleData.block.children, "font-weight") || "400";
127
+ const fontStyle = getDeclarationValue(ruleData.block.children, "font-style") || "normal";
128
+ const fontVariant = getDeclarationValue(ruleData.block.children, "font-variant") || "normal";
129
+ fontWeight.split(",").forEach(weightValue =>
130
+ fontsInfo.declared.push({ fontFamily, fontWeight: helper.getFontWeight(helper.removeQuotes(weightValue)), fontStyle, fontVariant }));
131
+ }
132
+ }
133
+ }
134
+ });
135
+ }
136
+
137
+ function filterUnusedFonts(cssRules, declaredFonts, unusedFonts, filteredUsedFonts, docContent) {
138
+ const removedRules = [];
139
+ for (let cssRule = cssRules.head; cssRule; cssRule = cssRule.next) {
140
+ const ruleData = cssRule.data;
141
+ if (ruleData.type == "Atrule" && (ruleData.name == "media" || ruleData.name == "supports") && ruleData.block && ruleData.block.children) {
142
+ filterUnusedFonts(ruleData.block.children, declaredFonts, unusedFonts, filteredUsedFonts, docContent);
143
+ } else if (ruleData.type == "Atrule" && ruleData.name == "font-face") {
144
+ const fontFamily = helper.normalizeFontFamily(getDeclarationValue(ruleData.block.children, "font-family"));
145
+ if (fontFamily) {
146
+ const unicodeRange = getDeclarationValue(ruleData.block.children, "unicode-range");
147
+ if (unusedFonts.find(fontInfo => fontInfo.fontFamily == fontFamily) || !testUnicodeRange(docContent, unicodeRange) || !testUsedFont(ruleData, fontFamily, declaredFonts, filteredUsedFonts)) {
148
+ removedRules.push(cssRule);
149
+ }
150
+ }
151
+ const removedDeclarations = [];
152
+ for (let declaration = ruleData.block.children.head; declaration; declaration = declaration.next) {
153
+ if (declaration.data.property == "font-display") {
154
+ removedDeclarations.push(declaration);
155
+ }
156
+ }
157
+ if (removedDeclarations.length) {
158
+ removedDeclarations.forEach(removedDeclaration => ruleData.block.children.remove(removedDeclaration));
159
+ }
160
+ }
161
+ }
162
+ removedRules.forEach(cssRule => cssRules.remove(cssRule));
163
+ }
164
+
165
+ function testUsedFont(ruleData, familyName, declaredFonts, filteredUsedFonts) {
166
+ let test;
167
+ const optionalUsedFonts = filteredUsedFonts && filteredUsedFonts.get(familyName);
168
+ if (optionalUsedFonts && optionalUsedFonts.length) {
169
+ let fontStyle = getDeclarationValue(ruleData.block.children, "font-style") || "normal";
170
+ if (VALID_FONT_STYLES.find(rule => fontStyle.trim().match(rule))) {
171
+ const fontWeight = helper.getFontWeight(getDeclarationValue(ruleData.block.children, "font-weight") || "400");
172
+ const declaredFontsWeights = declaredFonts
173
+ .filter(fontInfo => fontInfo.fontFamily == familyName && fontInfo.fontStyle == fontStyle)
174
+ .map(fontInfo => fontInfo.fontWeight)
175
+ .sort((weight1, weight2) => Number.parseInt(weight1, 10) - Number.parseInt(weight2, 10));
176
+ let usedFontWeights = optionalUsedFonts.map(fontInfo => getUsedFontWeight(fontInfo, fontStyle, declaredFontsWeights));
177
+ test = testFontweight(fontWeight, usedFontWeights);
178
+ if (!test) {
179
+ usedFontWeights = optionalUsedFonts.map(fontInfo => {
180
+ fontInfo = Array.from(fontInfo);
181
+ fontInfo[2] = "normal";
182
+ return getUsedFontWeight(fontInfo, fontStyle, declaredFontsWeights);
183
+ });
184
+ }
185
+ test = testFontweight(fontWeight, usedFontWeights);
186
+ } else {
187
+ test = true;
188
+ }
189
+ } else {
190
+ test = true;
191
+ }
192
+ return test;
193
+ }
194
+
195
+ function testFontweight(fontWeight, usedFontWeights) {
196
+ let test;
197
+ for (const value of fontWeight.split(/[ ,]/)) {
198
+ test = test || usedFontWeights.includes(helper.getFontWeight(helper.removeQuotes(value)));
199
+ }
200
+ return test;
201
+ }
202
+
203
+ function getDeclarationValue(declarations, propertyName) {
204
+ let property;
205
+ if (declarations) {
206
+ property = declarations.filter(declaration => declaration.property == propertyName).tail;
207
+ }
208
+ if (property) {
209
+ try {
210
+ return helper.removeQuotes(cssTree.generate(property.data.value)).toLowerCase();
211
+ } catch (error) {
212
+ // ignored
213
+ }
214
+ }
215
+ }
216
+
217
+ function getFontFamilyNames(declarations) {
218
+ let fontFamilyName = declarations.children.filter(node => node.property == "font-family").tail;
219
+ let fontFamilyNames = [];
220
+ if (fontFamilyName) {
221
+ let familyName = "";
222
+ if (fontFamilyName.data.value.children) {
223
+ fontFamilyName.data.value.children.forEach(node => {
224
+ if (node.type == "Operator" && node.value == "," && familyName) {
225
+ fontFamilyNames.push(helper.normalizeFontFamily(familyName));
226
+ familyName = "";
227
+ } else {
228
+ familyName += cssTree.generate(node);
229
+ }
230
+ });
231
+ } else {
232
+ fontFamilyName = cssTree.generate(fontFamilyName.data.value);
233
+ }
234
+ if (familyName) {
235
+ fontFamilyNames.push(helper.normalizeFontFamily(familyName));
236
+ }
237
+ }
238
+ const font = declarations.children.filter(node => node.property == "font").tail;
239
+ if (font && font.data && font.data.value) {
240
+ try {
241
+ const parsedFont = fontPropertyParser.parse(cssTree.generate(font.data.value));
242
+ parsedFont.family.forEach(familyName => fontFamilyNames.push(helper.normalizeFontFamily(familyName)));
243
+ } catch (error) {
244
+ // ignored
245
+ }
246
+ }
247
+ return fontFamilyNames;
248
+ }
249
+
250
+ function getUsedFontWeight(fontInfo, fontStyle, fontWeights) {
251
+ let foundWeight;
252
+ fontWeights = fontWeights.map(weight => String(Number.parseInt(weight, 10)));
253
+ if (fontInfo[2] == fontStyle) {
254
+ let fontWeight = Number(fontInfo[1]);
255
+ if (fontWeights.length > 1) {
256
+ if (fontWeight >= 400 && fontWeight <= 500) {
257
+ foundWeight = fontWeights.find(weight => weight >= fontWeight && weight <= 500);
258
+ if (!foundWeight) {
259
+ foundWeight = findDescendingFontWeight(fontWeight, fontWeights);
260
+ }
261
+ if (!foundWeight) {
262
+ foundWeight = findAscendingFontWeight(fontWeight, fontWeights);
263
+ }
264
+ }
265
+ if (fontWeight < 400) {
266
+ foundWeight = fontWeights.slice().reverse().find(weight => weight <= fontWeight);
267
+ if (!foundWeight) {
268
+ foundWeight = findAscendingFontWeight(fontWeight, fontWeights);
269
+ }
270
+ }
271
+ if (fontWeight > 500) {
272
+ foundWeight = fontWeights.find(weight => weight >= fontWeight);
273
+ if (!foundWeight) {
274
+ foundWeight = findDescendingFontWeight(fontWeight, fontWeights);
275
+ }
276
+ }
277
+ } else {
278
+ foundWeight = fontWeights[0];
279
+ }
280
+ }
281
+ return foundWeight;
282
+ }
283
+
284
+ function findDescendingFontWeight(fontWeight, fontWeights) {
285
+ return fontWeights.slice().reverse().find(weight => weight < fontWeight);
286
+ }
287
+
288
+ function findAscendingFontWeight(fontWeight, fontWeights) {
289
+ return fontWeights.find(weight => weight > fontWeight);
290
+ }
291
+
292
+ function getRulesTextContent(doc, cssRules, workStylesheet, content) {
293
+ cssRules.forEach(ruleData => {
294
+ if (ruleData.block && ruleData.block.children && ruleData.prelude && ruleData.prelude.children) {
295
+ if (ruleData.type == "Atrule" && (ruleData.name == "media" || ruleData.name == "supports")) {
296
+ content = getRulesTextContent(doc, ruleData.block.children, workStylesheet, content);
297
+ } else if (ruleData.type == "Rule") {
298
+ content = getDeclarationsTextContent(ruleData.block.children, workStylesheet, content);
299
+ }
300
+ }
301
+ });
302
+ return content;
303
+ }
304
+
305
+ function getDeclarationsTextContent(declarations, workStylesheet, content) {
306
+ const contentText = getDeclarationUnescapedValue(declarations, "content", workStylesheet);
307
+ const quotesText = getDeclarationUnescapedValue(declarations, "quotes", workStylesheet);
308
+ if (!content.includes(contentText)) {
309
+ content += contentText;
310
+ }
311
+ if (!content.includes(quotesText)) {
312
+ content += quotesText;
313
+ }
314
+ return content;
315
+ }
316
+
317
+ function getDeclarationUnescapedValue(declarations, property, workStylesheet) {
318
+ const rawValue = getDeclarationValue(declarations, property) || "";
319
+ if (rawValue) {
320
+ workStylesheet.textContent = "tmp { content:\"" + rawValue + "\"}";
321
+ if (workStylesheet.sheet && workStylesheet.sheet.cssRules) {
322
+ return helper.removeQuotes(workStylesheet.sheet.cssRules[0].style.getPropertyValue("content"));
323
+ } else {
324
+ return rawValue;
325
+ }
326
+ }
327
+ return "";
328
+ }
329
+
330
+ function testUnicodeRange(docContent, unicodeRange) {
331
+ if (unicodeRange) {
332
+ const unicodeRanges = unicodeRange.split(REGEXP_COMMA);
333
+ let invalid;
334
+ const result = unicodeRanges.filter(rangeValue => {
335
+ const range = rangeValue.split(REGEXP_DASH);
336
+ let regExpString;
337
+ if (range.length == 2) {
338
+ range[0] = transformRange(range[0]);
339
+ regExpString = "[" + range[0] + "-" + transformRange("U+" + range[1]) + "]";
340
+ }
341
+ if (range.length == 1) {
342
+ if (range[0].includes("?")) {
343
+ const firstRange = transformRange(range[0]);
344
+ const secondRange = firstRange;
345
+ regExpString = "[" + firstRange.replace(REGEXP_QUESTION_MARK, "0") + "-" + secondRange.replace(REGEXP_QUESTION_MARK, "F") + "]";
346
+ } else if (range[0]) {
347
+ regExpString = "[" + transformRange(range[0]) + "]";
348
+ }
349
+ }
350
+ if (regExpString) {
351
+ try {
352
+ return (new RegExp(regExpString, "u")).test(docContent);
353
+ } catch (error) {
354
+ invalid = true;
355
+ return false;
356
+ }
357
+ }
358
+ return true;
359
+ });
360
+ return !invalid && (!unicodeRanges.length || result.length);
361
+ }
362
+ return true;
363
+ }
364
+
365
+ function transformRange(range) {
366
+ range = range.replace(REGEXP_STARTS_U_PLUS, "");
367
+ while (range.length < 6) {
368
+ range = "0" + range;
369
+ }
370
+ return "\\u{" + range + "}";
371
+ }