single-file-util.js 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244
  1. /*
  2. * Copyright 2010-2019 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 DOMParser, URL, Blob, FileReader */
  24. this.singlefile.lib.util = this.singlefile.lib.util || (() => {
  25. const DEBUG = false;
  26. const ONE_MB = 1024 * 1024;
  27. const PREFIX_CONTENT_TYPE_TEXT = "text/";
  28. return {
  29. getInstance: (modules, util) => {
  30. if (modules.serializer === undefined) {
  31. modules.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. return {
  52. getContent,
  53. parseURL(resourceURL, baseURI) {
  54. if (baseURI === undefined) {
  55. return new URL(resourceURL);
  56. } else {
  57. return new URL(resourceURL, baseURI);
  58. }
  59. },
  60. resolveURL(resourceURL, baseURI) {
  61. return this.parseURL(resourceURL, baseURI).href;
  62. },
  63. parseDocContent(content, baseURI) {
  64. const doc = (new DOMParser()).parseFromString(content, "text/html");
  65. if (!doc.head) {
  66. doc.documentElement.insertBefore(doc.createElement("HEAD"), doc.body);
  67. }
  68. let baseElement = doc.querySelector("base");
  69. if (!baseElement || !baseElement.getAttribute("href")) {
  70. if (baseElement) {
  71. baseElement.remove();
  72. }
  73. baseElement = doc.createElement("base");
  74. baseElement.setAttribute("href", baseURI);
  75. doc.head.insertBefore(baseElement, doc.head.firstChild);
  76. }
  77. return doc;
  78. },
  79. parseXMLContent(content) {
  80. return (new DOMParser()).parseFromString(content, "text/xml");
  81. },
  82. parseSVGContent(content) {
  83. return (new DOMParser()).parseFromString(content, "image/svg+xml");
  84. },
  85. async digest(algo, text) {
  86. return util.digestText(algo, text);
  87. },
  88. getContentSize(content) {
  89. return new Blob([content]).size;
  90. },
  91. async truncateText(content, maxSize) {
  92. const blob = new Blob([content]);
  93. const reader = new FileReader();
  94. reader.readAsText(blob.slice(0, maxSize));
  95. return new Promise((resolve, reject) => {
  96. reader.addEventListener("load", () => {
  97. if (content.startsWith(reader.result)) {
  98. resolve(reader.result);
  99. } else {
  100. this.truncateText(content, maxSize - 1).then(resolve).catch(reject);
  101. }
  102. }, false);
  103. reader.addEventListener("error", reject, false);
  104. });
  105. },
  106. minifyHTML(doc, options) {
  107. return modules.htmlMinifier.process(doc, options);
  108. },
  109. postMinifyHTML(doc) {
  110. return modules.htmlMinifier.postProcess(doc);
  111. },
  112. minifyCSSRules(stylesheets, styles, mediaAllInfo) {
  113. return modules.cssRulesMinifier.process(stylesheets, styles, mediaAllInfo);
  114. },
  115. removeUnusedFonts(doc, stylesheets, styles, options) {
  116. return modules.fontsMinifier.process(doc, stylesheets, styles, options);
  117. },
  118. removeAlternativeFonts(doc, stylesheets) {
  119. return modules.fontsAltMinifier.process(doc, stylesheets);
  120. },
  121. getMediaAllInfo(doc, stylesheets, styles) {
  122. return modules.matchedRules.getMediaAllInfo(doc, stylesheets, styles);
  123. },
  124. compressCSS(content, options) {
  125. return modules.cssMinifier.processString(content, options);
  126. },
  127. minifyMedias(stylesheets) {
  128. return modules.mediasAltMinifier.process(stylesheets);
  129. },
  130. removeAlternativeImages(doc) {
  131. return modules.imagesAltMinifier.process(doc);
  132. },
  133. parseSrcset(srcset) {
  134. return modules.srcsetParser.process(srcset);
  135. },
  136. preProcessDoc(doc, win, options) {
  137. return modules.helper.preProcessDoc(doc, win, options);
  138. },
  139. postProcessDoc(doc, markedElements) {
  140. modules.helper.postProcessDoc(doc, markedElements);
  141. },
  142. serialize(doc, compressHTML) {
  143. return modules.serializer.process(doc, compressHTML);
  144. },
  145. removeQuotes(string) {
  146. return modules.helper.removeQuotes(string);
  147. },
  148. WIN_ID_ATTRIBUTE_NAME: modules.helper.WIN_ID_ATTRIBUTE_NAME,
  149. REMOVED_CONTENT_ATTRIBUTE_NAME: modules.helper.REMOVED_CONTENT_ATTRIBUTE_NAME,
  150. IMAGE_ATTRIBUTE_NAME: modules.helper.IMAGE_ATTRIBUTE_NAME,
  151. POSTER_ATTRIBUTE_NAME: modules.helper.POSTER_ATTRIBUTE_NAME,
  152. CANVAS_ATTRIBUTE_NAME: modules.helper.CANVAS_ATTRIBUTE_NAME,
  153. HTML_IMPORT_ATTRIBUTE_NAME: modules.helper.HTML_IMPORT_ATTRIBUTE_NAME,
  154. INPUT_VALUE_ATTRIBUTE_NAME: modules.helper.INPUT_VALUE_ATTRIBUTE_NAME,
  155. SHADOW_ROOT_ATTRIBUTE_NAME: modules.helper.SHADOW_ROOT_ATTRIBUTE_NAME,
  156. PRESERVED_SPACE_ELEMENT_ATTRIBUTE_NAME: modules.helper.PRESERVED_SPACE_ELEMENT_ATTRIBUTE_NAME,
  157. STYLESHEET_ATTRIBUTE_NAME: modules.helper.STYLESHEET_ATTRIBUTE_NAME
  158. };
  159. async function getContent(resourceURL, options) {
  160. let resourceContent, startTime;
  161. if (DEBUG) {
  162. startTime = Date.now();
  163. log(" // STARTED download url =", resourceURL, "asBinary =", options.asBinary);
  164. }
  165. try {
  166. resourceContent = await util.getResourceContent(resourceURL);
  167. } catch (error) {
  168. return { data: options.asBinary ? "data:base64," : "", resourceURL };
  169. }
  170. resourceURL = resourceContent.getUrl();
  171. let contentType = resourceContent.getContentType();
  172. let charset;
  173. if (contentType) {
  174. const matchContentType = contentType.toLowerCase().split(";");
  175. contentType = matchContentType[0].trim();
  176. if (!contentType.includes("/")) {
  177. contentType = null;
  178. }
  179. const charsetValue = matchContentType[1] && matchContentType[1].trim();
  180. if (charsetValue) {
  181. const matchCharset = charsetValue.match(/^charset=(.*)/);
  182. if (matchCharset && matchCharset[1]) {
  183. charset = modules.helper.removeQuotes(matchCharset[1].trim());
  184. }
  185. }
  186. }
  187. if (!charset && options.charset) {
  188. charset = options.charset;
  189. }
  190. if (options.asBinary) {
  191. try {
  192. if (DEBUG) {
  193. log(" // ENDED download url =", resourceURL, "delay =", Date.now() - startTime);
  194. }
  195. if (options.maxResourceSizeEnabled && resourceContent.getSize() > options.maxResourceSize * ONE_MB) {
  196. return { data: "data:base64,", resourceURL };
  197. } else {
  198. const dataUri = await resourceContent.getDataUri(contentType);
  199. return { data: dataUri, resourceURL };
  200. }
  201. } catch (error) {
  202. return { data: "data:base64,", resourceURL };
  203. }
  204. } else {
  205. if (resourceContent.getStatusCode() >= 400 || (options.validateTextContentType && contentType && !contentType.startsWith(PREFIX_CONTENT_TYPE_TEXT))) {
  206. return { data: "", resourceURL };
  207. }
  208. if (!charset) {
  209. charset = "utf-8";
  210. }
  211. if (DEBUG) {
  212. log(" // ENDED download url =", resourceURL, "delay =", Date.now() - startTime);
  213. }
  214. if (options.maxResourceSizeEnabled && resourceContent.getSize() > options.maxResourceSize * ONE_MB) {
  215. return { data: "", resourceURL, charset };
  216. } else {
  217. try {
  218. return { data: resourceContent.getText(charset), resourceURL, charset };
  219. } catch (error) {
  220. try {
  221. charset = "utf-8";
  222. return { data: resourceContent.getText(charset), resourceURL, charset };
  223. } catch (error) {
  224. return { data: "", resourceURL, charset };
  225. }
  226. }
  227. }
  228. }
  229. }
  230. }
  231. };
  232. function log(...args) {
  233. console.log("S-File <browser>", ...args); // eslint-disable-line no-console
  234. }
  235. })();