1
0

single-file-browser.js 6.8 KB

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