single-file-browser.js 6.7 KB

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