single-file-util.js 9.1 KB

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