css-fonts-alt-minifier.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331
  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. /* global window, globalThis */
  24. this.singlefile.lib.modules.fontsAltMinifier = this.singlefile.lib.modules.fontsAltMinifier || (globalThis => {
  25. const singlefile = this.singlefile;
  26. const FontFace = globalThis.FontFace;
  27. const REGEXP_URL_SIMPLE_QUOTES_FN = /url\s*\(\s*'(.*?)'\s*\)/i;
  28. const REGEXP_URL_DOUBLE_QUOTES_FN = /url\s*\(\s*"(.*?)"\s*\)/i;
  29. const REGEXP_URL_NO_QUOTES_FN = /url\s*\(\s*(.*?)\s*\)/i;
  30. const REGEXP_URL_FUNCTION = /(url|local)\(.*?\)\s*(,|$)/g;
  31. const REGEXP_SIMPLE_QUOTES_STRING = /^'(.*?)'$/;
  32. const REGEXP_DOUBLE_QUOTES_STRING = /^"(.*?)"$/;
  33. const REGEXP_URL_FUNCTION_WOFF = /^url\(\s*["']?data:font\/(woff2?)/;
  34. const REGEXP_URL_FUNCTION_WOFF_ALT = /^url\(\s*["']?data:application\/x-font-(woff)/;
  35. const REGEXP_FONT_FORMAT = /\.([^.?#]+)((\?|#).*?)?$/;
  36. const REGEXP_FONT_FORMAT_VALUE = /format\((.*?)\)\s*,?$/;
  37. const REGEXP_FONT_SRC = /(.*?)\s*,?$/;
  38. const EMPTY_URL_SOURCE = /^url\(["']?data:[^,]*,?["']?\)/;
  39. const LOCAL_SOURCE = "local(";
  40. const MEDIA_ALL = "all";
  41. const FONT_STRETCHES = {
  42. "ultra-condensed": "50%",
  43. "extra-condensed": "62.5%",
  44. "condensed": "75%",
  45. "semi-condensed": "87.5%",
  46. "normal": "100%",
  47. "semi-expanded": "112.5%",
  48. "expanded": "125%",
  49. "extra-expanded": "150%",
  50. "ultra-expanded": "200%"
  51. };
  52. const FONT_MAX_LOAD_DELAY = 5000;
  53. return {
  54. process
  55. };
  56. async function process(doc, stylesheets, fontURLs, fontTests) {
  57. const fontsDetails = {
  58. fonts: new Map(),
  59. medias: new Map(),
  60. supports: new Map()
  61. };
  62. const stats = { rules: { processed: 0, discarded: 0 }, fonts: { processed: 0, discarded: 0 } };
  63. let sheetIndex = 0;
  64. stylesheets.forEach(stylesheetInfo => {
  65. const cssRules = stylesheetInfo.stylesheet.children;
  66. if (cssRules) {
  67. stats.rules.processed += cssRules.getSize();
  68. stats.rules.discarded += cssRules.getSize();
  69. if (stylesheetInfo.mediaText && stylesheetInfo.mediaText != MEDIA_ALL) {
  70. const mediaFontsDetails = createFontsDetailsInfo();
  71. fontsDetails.medias.set("media-" + sheetIndex + "-" + stylesheetInfo.mediaText, mediaFontsDetails);
  72. getFontsDetails(doc, cssRules, sheetIndex, mediaFontsDetails);
  73. } else {
  74. getFontsDetails(doc, cssRules, sheetIndex, fontsDetails);
  75. }
  76. }
  77. sheetIndex++;
  78. });
  79. processFontDetails(fontsDetails);
  80. await Promise.all([...stylesheets].map(async ([, stylesheetInfo], sheetIndex) => {
  81. const cssRules = stylesheetInfo.stylesheet.children;
  82. const media = stylesheetInfo.mediaText;
  83. if (cssRules) {
  84. if (media && media != MEDIA_ALL) {
  85. await processFontFaceRules(cssRules, sheetIndex, fontsDetails.medias.get("media-" + sheetIndex + "-" + media), fontURLs, fontTests, stats);
  86. } else {
  87. await processFontFaceRules(cssRules, sheetIndex, fontsDetails, fontURLs, fontTests, stats);
  88. }
  89. stats.rules.discarded -= cssRules.getSize();
  90. }
  91. }));
  92. return stats;
  93. }
  94. function getFontsDetails(doc, cssRules, sheetIndex, mediaFontsDetails) {
  95. const cssTree = singlefile.lib.vendor.cssTree;
  96. let mediaIndex = 0, supportsIndex = 0;
  97. cssRules.forEach(ruleData => {
  98. if (ruleData.type == "Atrule" && ruleData.name == "media" && ruleData.block && ruleData.block.children && ruleData.prelude) {
  99. const mediaText = cssTree.generate(ruleData.prelude);
  100. const fontsDetails = createFontsDetailsInfo();
  101. mediaFontsDetails.medias.set("media-" + sheetIndex + "-" + mediaIndex + "-" + mediaText, fontsDetails);
  102. mediaIndex++;
  103. getFontsDetails(doc, ruleData.block.children, sheetIndex, fontsDetails);
  104. } else if (ruleData.type == "Atrule" && ruleData.name == "supports" && ruleData.block && ruleData.block.children && ruleData.prelude) {
  105. const supportsText = cssTree.generate(ruleData.prelude);
  106. const fontsDetails = createFontsDetailsInfo();
  107. mediaFontsDetails.supports.set("supports-" + sheetIndex + "-" + supportsIndex + "-" + supportsText, fontsDetails);
  108. supportsIndex++;
  109. getFontsDetails(doc, ruleData.block.children, sheetIndex, fontsDetails);
  110. } else if (ruleData.type == "Atrule" && ruleData.name == "font-face" && ruleData.block && ruleData.block.children) {
  111. const fontKey = getFontKey(ruleData);
  112. let fontInfo = mediaFontsDetails.fonts.get(fontKey);
  113. if (!fontInfo) {
  114. fontInfo = [];
  115. mediaFontsDetails.fonts.set(fontKey, fontInfo);
  116. }
  117. const src = getPropertyValue(ruleData, "src");
  118. if (src) {
  119. const fontSources = src.match(REGEXP_URL_FUNCTION);
  120. if (fontSources) {
  121. fontSources.forEach(source => fontInfo.unshift(source));
  122. }
  123. }
  124. }
  125. });
  126. }
  127. function processFontDetails(fontsDetails) {
  128. fontsDetails.fonts.forEach((fontInfo, fontKey) => {
  129. fontsDetails.fonts.set(fontKey, fontInfo.map(fontSource => {
  130. const fontFormatMatch = fontSource.match(REGEXP_FONT_FORMAT_VALUE);
  131. let fontFormat;
  132. const urlMatch = fontSource.match(REGEXP_URL_SIMPLE_QUOTES_FN) ||
  133. fontSource.match(REGEXP_URL_DOUBLE_QUOTES_FN) ||
  134. fontSource.match(REGEXP_URL_NO_QUOTES_FN);
  135. const fontUrl = urlMatch && urlMatch[1];
  136. if (fontFormatMatch && fontFormatMatch[1]) {
  137. fontFormat = fontFormatMatch[1].replace(REGEXP_SIMPLE_QUOTES_STRING, "$1").replace(REGEXP_DOUBLE_QUOTES_STRING, "$1").toLowerCase();
  138. }
  139. if (!fontFormat) {
  140. const fontFormatMatch = fontSource.match(REGEXP_URL_FUNCTION_WOFF);
  141. if (fontFormatMatch && fontFormatMatch[1]) {
  142. fontFormat = fontFormatMatch[1];
  143. } else {
  144. const fontFormatMatch = fontSource.match(REGEXP_URL_FUNCTION_WOFF_ALT);
  145. if (fontFormatMatch && fontFormatMatch[1]) {
  146. fontFormat = fontFormatMatch[1];
  147. }
  148. }
  149. }
  150. if (!fontFormat && fontUrl) {
  151. const fontFormatMatch = fontUrl.match(REGEXP_FONT_FORMAT);
  152. if (fontFormatMatch && fontFormatMatch[1]) {
  153. fontFormat = fontFormatMatch[1];
  154. }
  155. }
  156. return { src: fontSource.match(REGEXP_FONT_SRC)[1], fontUrl, format: fontFormat };
  157. }));
  158. });
  159. fontsDetails.medias.forEach(mediaFontsDetails => processFontDetails(mediaFontsDetails));
  160. fontsDetails.supports.forEach(supportsFontsDetails => processFontDetails(supportsFontsDetails));
  161. }
  162. async function processFontFaceRules(cssRules, sheetIndex, fontsDetails, fontURLs, fontTests, stats) {
  163. const cssTree = singlefile.lib.vendor.cssTree;
  164. const removedRules = [];
  165. let mediaIndex = 0, supportsIndex = 0;
  166. for (let cssRule = cssRules.head; cssRule; cssRule = cssRule.next) {
  167. const ruleData = cssRule.data;
  168. if (ruleData.type == "Atrule" && ruleData.name == "media" && ruleData.block && ruleData.block.children && ruleData.prelude) {
  169. const mediaText = cssTree.generate(ruleData.prelude);
  170. await processFontFaceRules(ruleData.block.children, sheetIndex, fontsDetails.medias.get("media-" + sheetIndex + "-" + mediaIndex + "-" + mediaText), fontURLs, fontTests, stats);
  171. mediaIndex++;
  172. } else if (ruleData.type == "Atrule" && ruleData.name == "supports" && ruleData.block && ruleData.block.children && ruleData.prelude) {
  173. const supportsText = cssTree.generate(ruleData.prelude);
  174. await processFontFaceRules(ruleData.block.children, sheetIndex, fontsDetails.supports.get("supports-" + sheetIndex + "-" + supportsIndex + "-" + supportsText), fontURLs, fontTests, stats);
  175. supportsIndex++;
  176. } else if (ruleData.type == "Atrule" && ruleData.name == "font-face") {
  177. const key = getFontKey(ruleData);
  178. const fontInfo = fontsDetails.fonts.get(key);
  179. if (fontInfo) {
  180. const processed = await processFontFaceRule(ruleData, fontInfo, fontURLs, fontTests, stats);
  181. if (processed) {
  182. fontsDetails.fonts.delete(key);
  183. }
  184. } else {
  185. removedRules.push(cssRule);
  186. }
  187. }
  188. }
  189. removedRules.forEach(cssRule => cssRules.remove(cssRule));
  190. }
  191. async function processFontFaceRule(ruleData, fontInfo, fontURLs, fontTests, stats) {
  192. const cssTree = singlefile.lib.vendor.cssTree;
  193. const removedNodes = [];
  194. for (let node = ruleData.block.children.head; node; node = node.next) {
  195. if (node.data.property == "src") {
  196. removedNodes.push(node);
  197. }
  198. }
  199. removedNodes.pop();
  200. removedNodes.forEach(node => ruleData.block.children.remove(node));
  201. const srcDeclaration = ruleData.block.children.filter(node => node.property == "src").tail;
  202. if (srcDeclaration) {
  203. await Promise.all(fontInfo.map(async (source, sourceIndex) => {
  204. if (fontTests.has(source.src)) {
  205. source.valid = fontTests.get(source.src);
  206. } else {
  207. if (FontFace) {
  208. const fontFace = new FontFace("test-font", source.src);
  209. try {
  210. await fontFace.load();
  211. await fontFace.loaded;
  212. source.valid = true;
  213. } catch (error) {
  214. const declarationFontURLs = fontURLs.get(srcDeclaration.data);
  215. if (declarationFontURLs) {
  216. const fontURL = declarationFontURLs[declarationFontURLs.length - sourceIndex - 1];
  217. if (fontURL) {
  218. const fontFace = new FontFace("test-font", "url(" + fontURL + ")");
  219. try {
  220. await Promise.race(
  221. [
  222. fontFace.load().then(() => fontFace.loaded).then(() => source.valid = true),
  223. new Promise(resolve => globalThis.setTimeout(() => { source.valid = true; resolve(); }, FONT_MAX_LOAD_DELAY))
  224. ]);
  225. } catch (error) {
  226. // ignored
  227. }
  228. }
  229. } else {
  230. source.valid = true;
  231. }
  232. }
  233. } else {
  234. source.valid = true;
  235. }
  236. fontTests.set(source.src, source.valid);
  237. }
  238. }));
  239. const findSource = (fontFormat, testValidity) => fontInfo.find(source => !source.src.match(EMPTY_URL_SOURCE) && source.format == fontFormat && (!testValidity || source.valid));
  240. const filterSource = fontSource => fontInfo.filter(source => source == fontSource || source.src.startsWith(LOCAL_SOURCE));
  241. stats.fonts.processed += fontInfo.length;
  242. stats.fonts.discarded += fontInfo.length;
  243. const woffFontFound = findSource("woff2-variations", true) || findSource("woff2", true) || findSource("woff", true);
  244. if (woffFontFound) {
  245. fontInfo = filterSource(woffFontFound);
  246. } else {
  247. const ttfFontFound = findSource("truetype-variations", true) || findSource("truetype", true);
  248. if (ttfFontFound) {
  249. fontInfo = filterSource(ttfFontFound);
  250. } else {
  251. const otfFontFound = findSource("opentype") || findSource("embedded-opentype");
  252. if (otfFontFound) {
  253. fontInfo = filterSource(otfFontFound);
  254. } else {
  255. fontInfo = fontInfo.filter(source => !source.src.match(EMPTY_URL_SOURCE) && (source.valid) || source.src.startsWith(LOCAL_SOURCE));
  256. }
  257. }
  258. }
  259. stats.fonts.discarded -= fontInfo.length;
  260. fontInfo.reverse();
  261. try {
  262. srcDeclaration.data.value = cssTree.parse(fontInfo.map(fontSource => fontSource.src).join(","), { context: "value" });
  263. }
  264. catch (error) {
  265. // ignored
  266. }
  267. return true;
  268. } else {
  269. return false;
  270. }
  271. }
  272. function getPropertyValue(ruleData, propertyName) {
  273. const cssTree = singlefile.lib.vendor.cssTree;
  274. let property;
  275. if (ruleData.block.children) {
  276. property = ruleData.block.children.filter(node => {
  277. try {
  278. return node.property == propertyName && !cssTree.generate(node.value).match(/\\9$/);
  279. } catch (error) {
  280. return node.property == propertyName;
  281. }
  282. }).tail;
  283. }
  284. if (property) {
  285. try {
  286. return cssTree.generate(property.data.value);
  287. } catch (error) {
  288. // ignored
  289. }
  290. }
  291. }
  292. function getFontKey(ruleData) {
  293. return JSON.stringify([
  294. singlefile.lib.helper.normalizeFontFamily(getPropertyValue(ruleData, "font-family")),
  295. singlefile.lib.helper.getFontWeight(getPropertyValue(ruleData, "font-weight") || "400"),
  296. getPropertyValue(ruleData, "font-style") || "normal",
  297. getPropertyValue(ruleData, "unicode-range"),
  298. getFontStretch(getPropertyValue(ruleData, "font-stretch")),
  299. getPropertyValue(ruleData, "font-variant") || "normal",
  300. getPropertyValue(ruleData, "font-feature-settings"),
  301. getPropertyValue(ruleData, "font-variation-settings")
  302. ]);
  303. }
  304. function getFontStretch(stretch) {
  305. return FONT_STRETCHES[stretch] || stretch;
  306. }
  307. function createFontsDetailsInfo() {
  308. return {
  309. fonts: new Map(),
  310. medias: new Map(),
  311. supports: new Map()
  312. };
  313. }
  314. })(typeof globalThis == "object" ? globalThis : window);