single-file-browser.js 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297
  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, TextDecoder, Blob, fetch, base64, superFetch, parseSrcset, uglifycss, htmlmini, cssMinifier, fontsMinifier, lazyLoader, serializer, docHelper, mediasMinifier, TextEncoder, crypto, RulesMatcher */
  21. this.SingleFile = this.SingleFile || (() => {
  22. const ONE_MB = 1024 * 1024;
  23. const DEBUG = false;
  24. // --------
  25. // Download
  26. // --------
  27. let fetchResource;
  28. if (this.serializer === undefined) {
  29. this.serializer = {
  30. process(doc) {
  31. const docType = doc.doctype;
  32. let docTypeString = "";
  33. if (docType) {
  34. docTypeString = "<!DOCTYPE " + docType.nodeName;
  35. if (docType.publicId) {
  36. docTypeString += " PUBLIC \"" + docType.publicId + "\"";
  37. if (docType.systemId)
  38. docTypeString += " \"" + docType.systemId + "\"";
  39. } else if (docType.systemId)
  40. docTypeString += " SYSTEM \"" + docType.systemId + "\"";
  41. if (docType.internalSubset)
  42. docTypeString += " [" + docType.internalSubset + "]";
  43. docTypeString += "> ";
  44. }
  45. return docTypeString + doc.documentElement.outerHTML;
  46. }
  47. };
  48. }
  49. class Download {
  50. static async getContent(resourceURL, options) {
  51. let startTime;
  52. if (DEBUG) {
  53. startTime = Date.now();
  54. log(" // STARTED download url =", resourceURL, "asDataURI =", options.asDataURI);
  55. }
  56. let resourceContent;
  57. if (!fetchResource) {
  58. fetchResource = typeof superFetch == "undefined" ? fetch : superFetch.fetch;
  59. }
  60. try {
  61. resourceContent = await fetchResource(resourceURL);
  62. } catch (error) {
  63. return options && options.asDataURI ? "data:base64," : "";
  64. }
  65. if (resourceContent.status >= 400 && superFetch.hostFetch) {
  66. try {
  67. resourceContent = await superFetch.hostFetch(resourceURL);
  68. } catch (error) {
  69. return options && options.asDataURI ? "data:base64," : "";
  70. }
  71. }
  72. if (resourceContent.status >= 400) {
  73. return options && options.asDataURI ? "data:base64," : "";
  74. }
  75. let contentType = resourceContent.headers && resourceContent.headers.get("content-type");
  76. let charSet;
  77. if (contentType) {
  78. const matchContentType = contentType.toLowerCase().split(";");
  79. contentType = matchContentType[0].trim();
  80. if (contentType.indexOf("/") <= 0) {
  81. contentType = null;
  82. }
  83. const charSetValue = matchContentType[1] && matchContentType[1].trim();
  84. if (charSetValue) {
  85. const matchCharSet = charSetValue.match(/^charset=(.*)/);
  86. if (matchCharSet) {
  87. charSet = removeQuotes(matchCharSet[1]);
  88. }
  89. }
  90. }
  91. if (options && options.asDataURI) {
  92. try {
  93. const buffer = await resourceContent.arrayBuffer();
  94. if (DEBUG) {
  95. log(" // ENDED download url =", resourceURL, "delay =", Date.now() - startTime);
  96. }
  97. const dataURI = "data:" + (contentType || "") + ";" + "base64," + base64.fromByteArray(new Uint8Array(buffer));
  98. if (options.maxResourceSizeEnabled && buffer.byteLength > options.maxResourceSize * ONE_MB) {
  99. return "data:base64,";
  100. } else {
  101. return dataURI;
  102. }
  103. } catch (error) {
  104. return "data:base64,";
  105. }
  106. } else {
  107. if (!charSet) {
  108. const matchCharset = contentType && contentType.match(/\s*;\s*charset\s*=\s*"?([^";]*)"?(;|$)/i);
  109. if (matchCharset && matchCharset[1] || options.charSet) {
  110. charSet = (matchCharset && matchCharset[1].toLowerCase()) || options.charSet;
  111. }
  112. }
  113. if (!charSet) {
  114. charSet = "utf-8";
  115. }
  116. try {
  117. const arrayBuffer = await resourceContent.arrayBuffer();
  118. if (DEBUG) {
  119. log(" // ENDED download url =", resourceURL, "delay =", Date.now() - startTime);
  120. }
  121. const textContent = (new TextDecoder(charSet)).decode(arrayBuffer);
  122. if (options.maxResourceSizeEnabled && textContent.length > options.maxResourceSize * ONE_MB) {
  123. return "";
  124. } else {
  125. return textContent;
  126. }
  127. } catch (error) {
  128. return "";
  129. }
  130. }
  131. }
  132. }
  133. const REGEXP_SIMPLE_QUOTES_STRING = /^'(.*?)'$/;
  134. const REGEXP_DOUBLE_QUOTES_STRING = /^"(.*?)"$/;
  135. function removeQuotes(string) {
  136. string = string.toLowerCase().trim();
  137. if (string.match(REGEXP_SIMPLE_QUOTES_STRING)) {
  138. string = string.replace(REGEXP_SIMPLE_QUOTES_STRING, "$1");
  139. } else {
  140. string = string.replace(REGEXP_DOUBLE_QUOTES_STRING, "$1");
  141. }
  142. return string.trim();
  143. }
  144. // https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/digest
  145. function hex(buffer) {
  146. var hexCodes = [];
  147. var view = new DataView(buffer);
  148. for (var i = 0; i < view.byteLength; i += 4) {
  149. var value = view.getUint32(i);
  150. var stringValue = value.toString(16);
  151. var padding = "00000000";
  152. var paddedValue = (padding + stringValue).slice(-padding.length);
  153. hexCodes.push(paddedValue);
  154. }
  155. return hexCodes.join("");
  156. }
  157. // ---
  158. // DOM
  159. // ---
  160. class DOM {
  161. static createDoc(pageContent, baseURI) {
  162. const doc = (new DOMParser()).parseFromString(pageContent, "text/html");
  163. let baseElement = doc.querySelector("base");
  164. if (!baseElement || !baseElement.getAttribute("href")) {
  165. if (baseElement) {
  166. baseElement.remove();
  167. }
  168. baseElement = doc.createElement("base");
  169. baseElement.setAttribute("href", baseURI);
  170. doc.head.insertBefore(baseElement, doc.head.firstChild);
  171. }
  172. return doc;
  173. }
  174. static getOnEventAttributeNames(doc) {
  175. const element = doc.createElement("div");
  176. const attributeNames = [];
  177. for (let propertyName in element) {
  178. if (propertyName.startsWith("on")) {
  179. attributeNames.push(propertyName);
  180. }
  181. }
  182. return attributeNames;
  183. }
  184. static getParser() {
  185. return DOMParser;
  186. }
  187. static async digest(algo, text) {
  188. const hash = await crypto.subtle.digest(algo, new TextEncoder("utf-8").encode(text));
  189. return (hex(hash));
  190. }
  191. static getContentSize(content) {
  192. return new Blob([content]).size;
  193. }
  194. static minifyHTML(doc, options) {
  195. return htmlmini.process(doc, options);
  196. }
  197. static postMinifyHTML(doc) {
  198. return htmlmini.postProcess(doc);
  199. }
  200. static lazyLoad(doc) {
  201. return lazyLoader.process(doc);
  202. }
  203. static minifyCSS(doc, mediaAllInfo) {
  204. return cssMinifier.process(doc, mediaAllInfo);
  205. }
  206. static minifyFonts(doc, secondPass) {
  207. return fontsMinifier.process(doc, secondPass);
  208. }
  209. static getMediaAllInfo(doc) {
  210. const rulesMatcher = RulesMatcher.create(doc);
  211. return rulesMatcher.getMediaAllInfo();
  212. }
  213. static compressCSS(content, options) {
  214. return uglifycss.processString(content, options);
  215. }
  216. static minifyMedias(doc) {
  217. return mediasMinifier.process(doc);
  218. }
  219. static parseSrcset(srcset) {
  220. return parseSrcset.process(srcset);
  221. }
  222. static preProcessDoc(doc, win, options) {
  223. return docHelper.preProcessDoc(doc, win, options);
  224. }
  225. static postProcessDoc(doc, options) {
  226. docHelper.postProcessDoc(doc, options);
  227. }
  228. static serialize(doc, compressHTML) {
  229. return serializer.process(doc, compressHTML);
  230. }
  231. static lazyLoaderImageSelectors() {
  232. return lazyLoader.imageSelectors;
  233. }
  234. static windowIdAttributeName(sessionId) {
  235. return docHelper.windowIdAttributeName(sessionId);
  236. }
  237. static preservedSpaceAttributeName(sessionId) {
  238. return docHelper.preservedSpaceAttributeName(sessionId);
  239. }
  240. static removedContentAttributeName(sessionId) {
  241. return docHelper.removedContentAttributeName(sessionId);
  242. }
  243. static responsiveImagesAttributeName(sessionId) {
  244. return docHelper.responsiveImagesAttributeName(sessionId);
  245. }
  246. static imagesAttributeName(sessionId) {
  247. return docHelper.imagesAttributeName(sessionId);
  248. }
  249. static inputValueAttributeName(sessionId) {
  250. return docHelper.inputValueAttributeName(sessionId);
  251. }
  252. static sheetAttributeName(sessionId) {
  253. return docHelper.sheetAttributeName(sessionId);
  254. }
  255. }
  256. function log(...args) {
  257. console.log("S-File <browser>", ...args); // eslint-disable-line no-console
  258. }
  259. return { getClass: () => SingleFileCore.getClass(Download, DOM, URL) };
  260. })();