single-file-browser.js 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303
  1. /*
  2. * Copyright 2018 Gildas Lormeau
  3. * contact : gildas.lormeau <at> gmail.com
  4. *
  5. * This file is part of SingleFile.
  6. *
  7. * SingleFile is free software: you can redistribute it and/or modify
  8. * it under the terms of the GNU Lesser General Public License as published by
  9. * the Free Software Foundation, either version 3 of the License, or
  10. * (at your option) any later version.
  11. *
  12. * SingleFile 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
  15. * GNU Lesser General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU Lesser General Public License
  18. * along with SingleFile. If not, see <http://www.gnu.org/licenses/>.
  19. */
  20. /* global SingleFileCore, DOMParser, URL, setTimeout, TextDecoder, Blob, fetch, FileReader, superFetch, srcsetParser, cssMinifier, htmlMinifier, cssRulesMinifier, fontsMinifier, fontsAltMinifier, serializer, docHelper, mediasMinifier, TextEncoder, crypto, matchedRules, imagesMinifier, FontFace, cssTree */
  21. this.SingleFile = this.SingleFile || (() => {
  22. const ONE_MB = 1024 * 1024;
  23. const DEBUG = false;
  24. const PREFIX_CONTENT_TYPE_TEXT = "text/";
  25. const FONT_FACE_TEST_MAX_DELAY = 1000;
  26. // --------
  27. // Download
  28. // --------
  29. let fetchResource;
  30. if (this.serializer === undefined) {
  31. this.serializer = {
  32. process(doc) {
  33. const docType = doc.doctype;
  34. let docTypeString = "";
  35. if (docType) {
  36. docTypeString = "<!DOCTYPE " + docType.nodeName;
  37. if (docType.publicId) {
  38. docTypeString += " PUBLIC \"" + docType.publicId + "\"";
  39. if (docType.systemId)
  40. docTypeString += " \"" + docType.systemId + "\"";
  41. } else if (docType.systemId)
  42. docTypeString += " SYSTEM \"" + docType.systemId + "\"";
  43. if (docType.internalSubset)
  44. docTypeString += " [" + docType.internalSubset + "]";
  45. docTypeString += "> ";
  46. }
  47. return docTypeString + doc.documentElement.outerHTML;
  48. }
  49. };
  50. }
  51. class Download {
  52. static async getContent(resourceURL, options) {
  53. let resourceContent, startTime;
  54. if (DEBUG) {
  55. startTime = Date.now();
  56. log(" // STARTED download url =", resourceURL, "asDataURI =", options.asDataURI);
  57. }
  58. if (!fetchResource) {
  59. fetchResource = typeof superFetch == "undefined" ? fetch : superFetch.fetch;
  60. }
  61. try {
  62. resourceContent = await fetchResource(resourceURL);
  63. } catch (error) {
  64. return options && options.asDataURI ? "data:base64," : "";
  65. }
  66. if (resourceContent.status >= 400) {
  67. return options && options.asDataURI ? "data:base64," : "";
  68. }
  69. let contentType = resourceContent.headers && resourceContent.headers.get("content-type");
  70. let charSet;
  71. if (contentType) {
  72. const matchContentType = contentType.toLowerCase().split(";");
  73. contentType = matchContentType[0].trim();
  74. if (contentType.indexOf("/") <= 0) {
  75. contentType = null;
  76. }
  77. const charSetValue = matchContentType[1] && matchContentType[1].trim();
  78. if (charSetValue) {
  79. const matchCharSet = charSetValue.match(/^charset=(.*)/);
  80. if (matchCharSet) {
  81. charSet = docHelper.removeQuotes(matchCharSet[1]);
  82. }
  83. }
  84. }
  85. if (options && options.asDataURI) {
  86. try {
  87. if (DEBUG) {
  88. log(" // ENDED download url =", resourceURL, "delay =", Date.now() - startTime);
  89. }
  90. const buffer = await resourceContent.arrayBuffer();
  91. if (options.maxResourceSizeEnabled && buffer.byteLength > options.maxResourceSize * ONE_MB) {
  92. return "data:base64,";
  93. } else {
  94. const reader = new FileReader();
  95. reader.readAsDataURL(new Blob([buffer], { type: contentType }));
  96. const dataURI = await new Promise((resolve, reject) => {
  97. reader.addEventListener("load", () => resolve(reader.result), false);
  98. reader.addEventListener("error", reject, false);
  99. });
  100. return dataURI;
  101. }
  102. } catch (error) {
  103. return "data:base64,";
  104. }
  105. } else {
  106. if (options.validateTextContentType && contentType && !contentType.startsWith(PREFIX_CONTENT_TYPE_TEXT)) {
  107. return "";
  108. }
  109. if (!charSet) {
  110. const matchCharset = contentType && contentType.match(/\s*;\s*charset\s*=\s*"?([^";]*)"?(;|$)/i);
  111. if (matchCharset && matchCharset[1] || options.charSet) {
  112. charSet = (matchCharset && matchCharset[1].toLowerCase()) || options.charSet;
  113. }
  114. }
  115. if (!charSet) {
  116. charSet = "utf-8";
  117. }
  118. let buffer;
  119. try {
  120. buffer = await resourceContent.arrayBuffer();
  121. } catch (error) {
  122. return "";
  123. }
  124. if (DEBUG) {
  125. log(" // ENDED download url =", resourceURL, "delay =", Date.now() - startTime);
  126. }
  127. if (options.maxResourceSizeEnabled && buffer.byteLength > options.maxResourceSize * ONE_MB) {
  128. return "";
  129. } else {
  130. try {
  131. return new TextDecoder(charSet).decode(buffer);
  132. } catch (error) {
  133. try {
  134. return new TextDecoder("utf-8").decode(buffer);
  135. } catch (error) {
  136. return "";
  137. }
  138. }
  139. }
  140. }
  141. }
  142. }
  143. // https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/digest
  144. function hex(buffer) {
  145. var hexCodes = [];
  146. var view = new DataView(buffer);
  147. for (var i = 0; i < view.byteLength; i += 4) {
  148. var value = view.getUint32(i);
  149. var stringValue = value.toString(16);
  150. var padding = "00000000";
  151. var paddedValue = (padding + stringValue).slice(-padding.length);
  152. hexCodes.push(paddedValue);
  153. }
  154. return hexCodes.join("");
  155. }
  156. // ---
  157. // DOM
  158. // ---
  159. class DOM {
  160. static createDoc(pageContent, baseURI) {
  161. const doc = (new DOMParser()).parseFromString(pageContent, "text/html");
  162. let baseElement = doc.querySelector("base");
  163. if (!baseElement || !baseElement.getAttribute("href")) {
  164. if (baseElement) {
  165. baseElement.remove();
  166. }
  167. baseElement = doc.createElement("base");
  168. baseElement.setAttribute("href", baseURI);
  169. doc.head.insertBefore(baseElement, doc.head.firstChild);
  170. }
  171. return doc;
  172. }
  173. static getOnEventAttributeNames(doc) {
  174. const element = doc.createElement("div");
  175. const attributeNames = [];
  176. for (const propertyName in element) {
  177. if (propertyName.startsWith("on")) {
  178. attributeNames.push(propertyName);
  179. }
  180. }
  181. return attributeNames;
  182. }
  183. static getParser() {
  184. return DOMParser;
  185. }
  186. static async digest(algo, text) {
  187. const hash = await crypto.subtle.digest(algo, new TextEncoder("utf-8").encode(text));
  188. return (hex(hash));
  189. }
  190. static getContentSize(content) {
  191. return new Blob([content]).size;
  192. }
  193. static async validFont(urlFunction) {
  194. try {
  195. const font = new FontFace("font-test", urlFunction);
  196. await Promise.race([font.load(), new Promise(resolve => setTimeout(() => resolve(true), FONT_FACE_TEST_MAX_DELAY))]);
  197. return true;
  198. } catch (error) {
  199. return false;
  200. }
  201. }
  202. static minifyHTML(doc, options) {
  203. return htmlMinifier.process(doc, options);
  204. }
  205. static postMinifyHTML(doc) {
  206. return htmlMinifier.postProcess(doc);
  207. }
  208. static minifyCSSRules(stylesheets, styles, mediaAllInfo) {
  209. return cssRulesMinifier.process(stylesheets, styles, mediaAllInfo);
  210. }
  211. static removeUnusedFonts(doc, stylesheets, styles, options) {
  212. return fontsMinifier.process(doc, stylesheets, styles, options);
  213. }
  214. static removeAlternativeFonts(doc, stylesheets) {
  215. return fontsAltMinifier.process(doc, stylesheets);
  216. }
  217. static getMediaAllInfo(doc, docStyle) {
  218. return matchedRules.getMediaAllInfo(doc, docStyle);
  219. }
  220. static compressCSS(content, options) {
  221. return cssMinifier.processString(content, options);
  222. }
  223. static minifyMedias(stylesheets) {
  224. return mediasMinifier.process(stylesheets);
  225. }
  226. static removeAlternativeImages(doc, options) {
  227. return imagesMinifier.process(doc, options);
  228. }
  229. static parseSrcset(srcset) {
  230. return srcsetParser.process(srcset);
  231. }
  232. static preProcessDoc(doc, win, options) {
  233. return docHelper.preProcessDoc(doc, win, options);
  234. }
  235. static postProcessDoc(doc, options) {
  236. docHelper.postProcessDoc(doc, options);
  237. }
  238. static serialize(doc, compressHTML) {
  239. return serializer.process(doc, compressHTML);
  240. }
  241. static removeQuotes(string) {
  242. return docHelper.removeQuotes(string);
  243. }
  244. static windowIdAttributeName(sessionId) {
  245. return docHelper.windowIdAttributeName(sessionId);
  246. }
  247. static preservedSpaceAttributeName(sessionId) {
  248. return docHelper.preservedSpaceAttributeName(sessionId);
  249. }
  250. static removedContentAttributeName(sessionId) {
  251. return docHelper.removedContentAttributeName(sessionId);
  252. }
  253. static imagesAttributeName(sessionId) {
  254. return docHelper.imagesAttributeName(sessionId);
  255. }
  256. static inputValueAttributeName(sessionId) {
  257. return docHelper.inputValueAttributeName(sessionId);
  258. }
  259. static shadowRootAttributeName(sessionId) {
  260. return docHelper.shadowRootAttributeName(sessionId);
  261. }
  262. }
  263. function log(...args) {
  264. console.log("S-File <browser>", ...args); // eslint-disable-line no-console
  265. }
  266. return { getClass: () => SingleFileCore.getClass(Download, DOM, URL, cssTree) };
  267. })();