doc-util.js 8.3 KB

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