single-file-util.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310
  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 DEFAULT_REPLACED_CHARACTERS = ["~", "+", "\\\\", "?", "%", "*", ":", "|", "\"", "<", ">", "\x00-\x1f", "\x7F"];
  29. const DEFAULT_REPLACEMENT_CHARACTER = "_";
  30. const URL = window.URL;
  31. const DOMParser = window.DOMParser;
  32. const Blob = window.Blob;
  33. const FileReader = window.FileReader;
  34. const fetch = window.fetch;
  35. const crypto = window.crypto;
  36. const TextDecoder = window.TextDecoder;
  37. const TextEncoder = window.TextEncoder;
  38. const singlefile = this.singlefile;
  39. return {
  40. getInstance(utilOptions) {
  41. const modules = singlefile.lib.modules;
  42. const vendor = singlefile.lib.vendor;
  43. const helper = singlefile.lib.helper;
  44. if (modules.serializer === undefined) {
  45. modules.serializer = {
  46. process(doc) {
  47. const docType = doc.doctype;
  48. let docTypeString = "";
  49. if (docType) {
  50. docTypeString = "<!DOCTYPE " + docType.nodeName;
  51. if (docType.publicId) {
  52. docTypeString += " PUBLIC \"" + docType.publicId + "\"";
  53. if (docType.systemId)
  54. docTypeString += " \"" + docType.systemId + "\"";
  55. } else if (docType.systemId)
  56. docTypeString += " SYSTEM \"" + docType.systemId + "\"";
  57. if (docType.internalSubset)
  58. docTypeString += " [" + docType.internalSubset + "]";
  59. docTypeString += "> ";
  60. }
  61. return docTypeString + doc.documentElement.outerHTML;
  62. }
  63. };
  64. }
  65. utilOptions = utilOptions || {};
  66. utilOptions.fetch = utilOptions.fetch || fetch;
  67. utilOptions.frameFetch = utilOptions.frameFetch || utilOptions.fetch || fetch;
  68. return {
  69. getContent,
  70. parseURL(resourceURL, baseURI) {
  71. if (baseURI === undefined) {
  72. return new URL(resourceURL);
  73. } else {
  74. return new URL(resourceURL, baseURI);
  75. }
  76. },
  77. resolveURL(resourceURL, baseURI) {
  78. return this.parseURL(resourceURL, baseURI).href;
  79. },
  80. getValidFilename(filename, replacedCharacters = DEFAULT_REPLACED_CHARACTERS, replacementCharacter = DEFAULT_REPLACEMENT_CHARACTER) {
  81. replacedCharacters.forEach(replacedCharacter => filename = filename.replace(new RegExp("[" + replacedCharacter + "]+", "g"), replacementCharacter));
  82. filename = filename
  83. .replace(/\.\.\//g, "")
  84. .replace(/^\/+/, "")
  85. .replace(/\/+/g, "/")
  86. .replace(/\/$/, "")
  87. .replace(/\.$/, "")
  88. .replace(/\.\//g, "." + replacementCharacter)
  89. .replace(/\/\./g, "/" + replacementCharacter);
  90. return filename;
  91. },
  92. parseDocContent(content, baseURI) {
  93. const doc = (new DOMParser()).parseFromString(content, "text/html");
  94. if (!doc.head) {
  95. doc.documentElement.insertBefore(doc.createElement("HEAD"), doc.body);
  96. }
  97. let baseElement = doc.querySelector("base");
  98. if (!baseElement || !baseElement.getAttribute("href")) {
  99. if (baseElement) {
  100. baseElement.remove();
  101. }
  102. baseElement = doc.createElement("base");
  103. baseElement.setAttribute("href", baseURI);
  104. doc.head.insertBefore(baseElement, doc.head.firstChild);
  105. }
  106. return doc;
  107. },
  108. parseXMLContent(content) {
  109. return (new DOMParser()).parseFromString(content, "text/xml");
  110. },
  111. parseSVGContent(content) {
  112. return (new DOMParser()).parseFromString(content, "image/svg+xml");
  113. },
  114. async digest(algo, text) {
  115. const hash = await crypto.subtle.digest(algo, new TextEncoder("utf-8").encode(text));
  116. return hex(hash);
  117. },
  118. getContentSize(content) {
  119. return new Blob([content]).size;
  120. },
  121. async truncateText(content, maxSize) {
  122. const blob = new Blob([content]);
  123. const reader = new FileReader();
  124. reader.readAsText(blob.slice(0, maxSize));
  125. return new Promise((resolve, reject) => {
  126. reader.addEventListener("load", () => {
  127. if (content.startsWith(reader.result)) {
  128. resolve(reader.result);
  129. } else {
  130. this.truncateText(content, maxSize - 1).then(resolve).catch(reject);
  131. }
  132. }, false);
  133. reader.addEventListener("error", reject, false);
  134. });
  135. },
  136. minifyHTML(doc, options) {
  137. return modules.htmlMinifier.process(doc, options);
  138. },
  139. postMinifyHTML(doc) {
  140. return modules.htmlMinifier.postProcess(doc);
  141. },
  142. minifyCSSRules(stylesheets, styles, mediaAllInfo) {
  143. return modules.cssRulesMinifier.process(stylesheets, styles, mediaAllInfo);
  144. },
  145. removeUnusedFonts(doc, stylesheets, styles, options) {
  146. return modules.fontsMinifier.process(doc, stylesheets, styles, options);
  147. },
  148. removeAlternativeFonts(doc, stylesheets) {
  149. return modules.fontsAltMinifier.process(doc, stylesheets);
  150. },
  151. getMediaAllInfo(doc, stylesheets, styles) {
  152. return modules.matchedRules.getMediaAllInfo(doc, stylesheets, styles);
  153. },
  154. compressCSS(content, options) {
  155. return vendor.cssMinifier.processString(content, options);
  156. },
  157. minifyMedias(stylesheets) {
  158. return modules.mediasAltMinifier.process(stylesheets);
  159. },
  160. removeAlternativeImages(doc) {
  161. return modules.imagesAltMinifier.process(doc);
  162. },
  163. parseSrcset(srcset) {
  164. return vendor.srcsetParser.process(srcset);
  165. },
  166. preProcessDoc(doc, win, options) {
  167. return helper.preProcessDoc(doc, win, options);
  168. },
  169. postProcessDoc(doc, markedElements) {
  170. helper.postProcessDoc(doc, markedElements);
  171. },
  172. serialize(doc, compressHTML) {
  173. return modules.serializer.process(doc, compressHTML);
  174. },
  175. removeQuotes(string) {
  176. return helper.removeQuotes(string);
  177. },
  178. async waitForUserScript(eventPrefixName) {
  179. if (helper.waitForUserScript) {
  180. return helper.waitForUserScript(eventPrefixName);
  181. }
  182. },
  183. ON_BEFORE_CAPTURE_EVENT_NAME: helper.ON_BEFORE_CAPTURE_EVENT_NAME,
  184. ON_AFTER_CAPTURE_EVENT_NAME: helper.ON_AFTER_CAPTURE_EVENT_NAME,
  185. WIN_ID_ATTRIBUTE_NAME: helper.WIN_ID_ATTRIBUTE_NAME,
  186. REMOVED_CONTENT_ATTRIBUTE_NAME: helper.REMOVED_CONTENT_ATTRIBUTE_NAME,
  187. HIDDEN_CONTENT_ATTRIBUTE_NAME: helper.HIDDEN_CONTENT_ATTRIBUTE_NAME,
  188. IMAGE_ATTRIBUTE_NAME: helper.IMAGE_ATTRIBUTE_NAME,
  189. POSTER_ATTRIBUTE_NAME: helper.POSTER_ATTRIBUTE_NAME,
  190. CANVAS_ATTRIBUTE_NAME: helper.CANVAS_ATTRIBUTE_NAME,
  191. HTML_IMPORT_ATTRIBUTE_NAME: helper.HTML_IMPORT_ATTRIBUTE_NAME,
  192. INPUT_VALUE_ATTRIBUTE_NAME: helper.INPUT_VALUE_ATTRIBUTE_NAME,
  193. SHADOW_ROOT_ATTRIBUTE_NAME: helper.SHADOW_ROOT_ATTRIBUTE_NAME,
  194. PRESERVED_SPACE_ELEMENT_ATTRIBUTE_NAME: helper.PRESERVED_SPACE_ELEMENT_ATTRIBUTE_NAME,
  195. STYLESHEET_ATTRIBUTE_NAME: helper.STYLESHEET_ATTRIBUTE_NAME,
  196. SELECTED_CONTENT_ATTRIBUTE_NAME: helper.SELECTED_CONTENT_ATTRIBUTE_NAME
  197. };
  198. async function getContent(resourceURL, options) {
  199. let response, startTime;
  200. const fetchResource = utilOptions.fetch;
  201. const fetchFrameResource = utilOptions.frameFetch;
  202. if (DEBUG) {
  203. startTime = Date.now();
  204. log(" // STARTED download url =", resourceURL, "asBinary =", options.asBinary);
  205. }
  206. try {
  207. if (options.frameId) {
  208. response = await fetchFrameResource(resourceURL, options.frameId);
  209. } else {
  210. response = await fetchResource(resourceURL);
  211. }
  212. } catch (error) {
  213. return { data: options.asBinary ? "data:null;base64," : "", resourceURL };
  214. }
  215. const buffer = await response.arrayBuffer();
  216. resourceURL = response.url || resourceURL;
  217. let contentType = response.headers.get("content-type");
  218. let charset;
  219. if (contentType) {
  220. const matchContentType = contentType.toLowerCase().split(";");
  221. contentType = matchContentType[0].trim();
  222. if (!contentType.includes("/")) {
  223. contentType = null;
  224. }
  225. const charsetValue = matchContentType[1] && matchContentType[1].trim();
  226. if (charsetValue) {
  227. const matchCharset = charsetValue.match(/^charset=(.*)/);
  228. if (matchCharset && matchCharset[1]) {
  229. charset = helper.removeQuotes(matchCharset[1].trim());
  230. }
  231. }
  232. }
  233. if (!charset && options.charset) {
  234. charset = options.charset;
  235. }
  236. if (options.asBinary) {
  237. try {
  238. if (DEBUG) {
  239. log(" // ENDED download url =", resourceURL, "delay =", Date.now() - startTime);
  240. }
  241. if (options.maxResourceSizeEnabled && buffer.byteLength > options.maxResourceSize * ONE_MB) {
  242. return { data: "data:null;base64,", resourceURL };
  243. } else {
  244. const reader = new FileReader();
  245. reader.readAsDataURL(new Blob([buffer], { type: contentType }));
  246. const dataUri = await new Promise((resolve, reject) => {
  247. reader.addEventListener("load", () => resolve(reader.result), false);
  248. reader.addEventListener("error", reject, false);
  249. });
  250. return { data: dataUri, resourceURL };
  251. }
  252. } catch (error) {
  253. return { data: "data:null;base64,", resourceURL };
  254. }
  255. } else {
  256. if (response.status >= 400 || (options.validateTextContentType && contentType && !contentType.startsWith(PREFIX_CONTENT_TYPE_TEXT))) {
  257. return { data: "", resourceURL };
  258. }
  259. if (!charset) {
  260. charset = "utf-8";
  261. }
  262. if (DEBUG) {
  263. log(" // ENDED download url =", resourceURL, "delay =", Date.now() - startTime);
  264. }
  265. if (options.maxResourceSizeEnabled && buffer.byteLength > options.maxResourceSize * ONE_MB) {
  266. return { data: "", resourceURL, charset };
  267. } else {
  268. try {
  269. return { data: new TextDecoder(charset).decode(buffer), resourceURL, charset };
  270. } catch (error) {
  271. try {
  272. charset = "utf-8";
  273. return { data: new TextDecoder(charset).decode(buffer), resourceURL, charset };
  274. } catch (error) {
  275. return { data: "", resourceURL, charset };
  276. }
  277. }
  278. }
  279. }
  280. }
  281. }
  282. };
  283. // https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/digest
  284. function hex(buffer) {
  285. const hexCodes = [];
  286. const view = new DataView(buffer);
  287. for (let i = 0; i < view.byteLength; i += 4) {
  288. const value = view.getUint32(i);
  289. const stringValue = value.toString(16);
  290. const padding = "00000000";
  291. const paddedValue = (padding + stringValue).slice(-padding.length);
  292. hexCodes.push(paddedValue);
  293. }
  294. return hexCodes.join("");
  295. }
  296. function log(...args) {
  297. console.log("S-File <browser>", ...args); // eslint-disable-line no-console
  298. }
  299. })();