single-file-util.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380
  1. /*
  2. * Copyright 2010-2020 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 = url => window.fetch(url);
  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. try {
  116. const hash = await crypto.subtle.digest(algo, new TextEncoder("utf-8").encode(text));
  117. return hex(hash);
  118. } catch (error) {
  119. return "";
  120. }
  121. },
  122. getContentSize(content) {
  123. return new Blob([content]).size;
  124. },
  125. truncateText(content, maxSize) {
  126. const blob = new Blob([content]);
  127. const reader = new FileReader();
  128. reader.readAsText(blob.slice(0, maxSize));
  129. return new Promise((resolve, reject) => {
  130. reader.addEventListener("load", () => {
  131. if (content.startsWith(reader.result)) {
  132. resolve(reader.result);
  133. } else {
  134. this.truncateText(content, maxSize - 1).then(resolve).catch(reject);
  135. }
  136. }, false);
  137. reader.addEventListener("error", reject, false);
  138. });
  139. },
  140. minifyHTML(doc, options) {
  141. return modules.htmlMinifier.process(doc, options);
  142. },
  143. minifyCSSRules(stylesheets, styles, mediaAllInfo) {
  144. return modules.cssRulesMinifier.process(stylesheets, styles, mediaAllInfo);
  145. },
  146. removeUnusedFonts(doc, stylesheets, styles, options) {
  147. return modules.fontsMinifier.process(doc, stylesheets, styles, options);
  148. },
  149. removeAlternativeFonts(doc, stylesheets, fontURLs, fontTests) {
  150. return modules.fontsAltMinifier.process(doc, stylesheets, fontURLs, fontTests);
  151. },
  152. getMediaAllInfo(doc, stylesheets, styles) {
  153. return modules.matchedRules.getMediaAllInfo(doc, stylesheets, styles);
  154. },
  155. compressCSS(content, options) {
  156. return vendor.cssMinifier.processString(content, options);
  157. },
  158. minifyMedias(stylesheets) {
  159. return modules.mediasAltMinifier.process(stylesheets);
  160. },
  161. removeAlternativeImages(doc) {
  162. return modules.imagesAltMinifier.process(doc);
  163. },
  164. parseSrcset(srcset) {
  165. return vendor.srcsetParser.process(srcset);
  166. },
  167. preProcessDoc(doc, win, options) {
  168. return helper.preProcessDoc(doc, win, options);
  169. },
  170. postProcessDoc(doc, markedElements) {
  171. helper.postProcessDoc(doc, markedElements);
  172. },
  173. serialize(doc, compressHTML) {
  174. return modules.serializer.process(doc, compressHTML);
  175. },
  176. removeQuotes(string) {
  177. return helper.removeQuotes(string);
  178. },
  179. waitForUserScript(eventPrefixName) {
  180. if (helper.waitForUserScript) {
  181. return helper.waitForUserScript(eventPrefixName);
  182. }
  183. },
  184. ON_BEFORE_CAPTURE_EVENT_NAME: helper.ON_BEFORE_CAPTURE_EVENT_NAME,
  185. ON_AFTER_CAPTURE_EVENT_NAME: helper.ON_AFTER_CAPTURE_EVENT_NAME,
  186. WIN_ID_ATTRIBUTE_NAME: helper.WIN_ID_ATTRIBUTE_NAME,
  187. REMOVED_CONTENT_ATTRIBUTE_NAME: helper.REMOVED_CONTENT_ATTRIBUTE_NAME,
  188. HIDDEN_CONTENT_ATTRIBUTE_NAME: helper.HIDDEN_CONTENT_ATTRIBUTE_NAME,
  189. HIDDEN_FRAME_ATTRIBUTE_NAME: helper.HIDDEN_FRAME_ATTRIBUTE_NAME,
  190. IMAGE_ATTRIBUTE_NAME: helper.IMAGE_ATTRIBUTE_NAME,
  191. POSTER_ATTRIBUTE_NAME: helper.POSTER_ATTRIBUTE_NAME,
  192. CANVAS_ATTRIBUTE_NAME: helper.CANVAS_ATTRIBUTE_NAME,
  193. HTML_IMPORT_ATTRIBUTE_NAME: helper.HTML_IMPORT_ATTRIBUTE_NAME,
  194. INPUT_VALUE_ATTRIBUTE_NAME: helper.INPUT_VALUE_ATTRIBUTE_NAME,
  195. SHADOW_ROOT_ATTRIBUTE_NAME: helper.SHADOW_ROOT_ATTRIBUTE_NAME,
  196. PRESERVED_SPACE_ELEMENT_ATTRIBUTE_NAME: helper.PRESERVED_SPACE_ELEMENT_ATTRIBUTE_NAME,
  197. STYLESHEET_ATTRIBUTE_NAME: helper.STYLESHEET_ATTRIBUTE_NAME,
  198. SELECTED_CONTENT_ATTRIBUTE_NAME: helper.SELECTED_CONTENT_ATTRIBUTE_NAME,
  199. COMMENT_HEADER: helper.COMMENT_HEADER,
  200. COMMENT_HEADER_LEGACY: helper.COMMENT_HEADER_LEGACY,
  201. SINGLE_FILE_UI_ELEMENT_CLASS: helper.SINGLE_FILE_UI_ELEMENT_CLASS
  202. };
  203. async function getContent(resourceURL, options) {
  204. let response, startTime;
  205. const fetchResource = utilOptions.fetch;
  206. const fetchFrameResource = utilOptions.frameFetch;
  207. if (DEBUG) {
  208. startTime = Date.now();
  209. log(" // STARTED download url =", resourceURL, "asBinary =", options.asBinary);
  210. }
  211. try {
  212. if (options.frameId) {
  213. try {
  214. response = await fetchFrameResource(resourceURL, { frameId: options.frameId, referrer: options.resourceReferrer });
  215. } catch (error) {
  216. response = await fetchResource(resourceURL);
  217. }
  218. } else {
  219. response = await fetchResource(resourceURL, { referrer: options.resourceReferrer });
  220. }
  221. } catch (error) {
  222. return { data: options.asBinary ? "data:null;base64," : "", resourceURL };
  223. }
  224. let buffer;
  225. try {
  226. buffer = await response.arrayBuffer();
  227. } catch (error) {
  228. return { data: options.asBinary ? "data:null;base64," : "", resourceURL };
  229. }
  230. resourceURL = response.url || resourceURL;
  231. let contentType = "", charset;
  232. try {
  233. const mimeType = new vendor.MIMEType(response.headers.get("content-type"));
  234. contentType = mimeType.type + "/" + mimeType.subtype;
  235. charset = mimeType.parameters.get("charset");
  236. } catch (error) {
  237. // ignored
  238. }
  239. if (!contentType) {
  240. contentType = guessMIMEType(options.expectedType, buffer);
  241. }
  242. if (!charset && options.charset) {
  243. charset = options.charset;
  244. }
  245. if (options.asBinary) {
  246. try {
  247. if (DEBUG) {
  248. log(" // ENDED download url =", resourceURL, "delay =", Date.now() - startTime);
  249. }
  250. if (options.maxResourceSizeEnabled && buffer.byteLength > options.maxResourceSize * ONE_MB) {
  251. return { data: "data:null;base64,", resourceURL };
  252. } else {
  253. const reader = new FileReader();
  254. reader.readAsDataURL(new Blob([buffer], { type: contentType + (options.charset ? ";charset=" + options.charset : "") }));
  255. const dataUri = await new Promise((resolve, reject) => {
  256. reader.addEventListener("load", () => resolve(reader.result), false);
  257. reader.addEventListener("error", reject, false);
  258. });
  259. return { data: dataUri, resourceURL };
  260. }
  261. } catch (error) {
  262. return { data: "data:null;base64,", resourceURL };
  263. }
  264. } else {
  265. if (response.status >= 400 || (options.validateTextContentType && contentType && !contentType.startsWith(PREFIX_CONTENT_TYPE_TEXT))) {
  266. return { data: "", resourceURL };
  267. }
  268. if (!charset) {
  269. charset = "utf-8";
  270. }
  271. if (DEBUG) {
  272. log(" // ENDED download url =", resourceURL, "delay =", Date.now() - startTime);
  273. }
  274. if (options.maxResourceSizeEnabled && buffer.byteLength > options.maxResourceSize * ONE_MB) {
  275. return { data: "", resourceURL, charset };
  276. } else {
  277. try {
  278. return { data: new TextDecoder(charset).decode(buffer), resourceURL, charset };
  279. } catch (error) {
  280. try {
  281. charset = "utf-8";
  282. return { data: new TextDecoder(charset).decode(buffer), resourceURL, charset };
  283. } catch (error) {
  284. return { data: "", resourceURL, charset };
  285. }
  286. }
  287. }
  288. }
  289. }
  290. }
  291. };
  292. function guessMIMEType(expectedType, buffer) {
  293. if (expectedType == "image") {
  294. if (compareBytes([255, 255, 255, 255], [0, 0, 1, 0])) {
  295. return "image/x-icon";
  296. }
  297. if (compareBytes([255, 255, 255, 255], [0, 0, 2, 0])) {
  298. return "image/x-icon";
  299. }
  300. if (compareBytes([255, 255], [78, 77])) {
  301. return "image/bmp";
  302. }
  303. if (compareBytes([255, 255, 255, 255, 255, 255], [71, 73, 70, 56, 57, 97])) {
  304. return "image/gif";
  305. }
  306. if (compareBytes([255, 255, 255, 255, 255, 255], [71, 73, 70, 56, 59, 97])) {
  307. return "image/gif";
  308. }
  309. if (compareBytes([255, 255, 255, 255, 0, 0, 0, 0, 255, 255, 255, 255, 255, 255], [82, 73, 70, 70, 0, 0, 0, 0, 87, 69, 66, 80, 86, 80])) {
  310. return "image/webp";
  311. }
  312. if (compareBytes([255, 255, 255, 255, 255, 255, 255, 255], [137, 80, 78, 71, 13, 10, 26, 10])) {
  313. return "image/png";
  314. }
  315. if (compareBytes([255, 255, 255], [255, 216, 255])) {
  316. return "image/jpeg";
  317. }
  318. }
  319. if (expectedType == "font") {
  320. if (compareBytes([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 255, 255],
  321. [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 76, 80])) {
  322. return "application/vnd.ms-fontobject";
  323. }
  324. if (compareBytes([255, 255, 255, 255], [0, 1, 0, 0])) {
  325. return "font/ttf";
  326. }
  327. if (compareBytes([255, 255, 255, 255], [79, 84, 84, 79])) {
  328. return "font/otf";
  329. }
  330. if (compareBytes([255, 255, 255, 255], [116, 116, 99, 102])) {
  331. return "font/collection";
  332. }
  333. if (compareBytes([255, 255, 255, 255], [119, 79, 70, 70])) {
  334. return "font/woff";
  335. }
  336. if (compareBytes([255, 255, 255, 255], [119, 79, 70, 50])) {
  337. return "font/woff2";
  338. }
  339. }
  340. function compareBytes(mask, pattern) {
  341. let patternMatch = true, index = 0;
  342. if (buffer.byteLength >= pattern.length) {
  343. const value = new Uint8Array(buffer, 0, mask.length);
  344. for (index = 0; index < mask.length && patternMatch; index++) {
  345. patternMatch = patternMatch && ((value[index] & mask[index]) == pattern[index]);
  346. }
  347. return patternMatch;
  348. }
  349. }
  350. }
  351. // https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/digest
  352. function hex(buffer) {
  353. const hexCodes = [];
  354. const view = new DataView(buffer);
  355. for (let i = 0; i < view.byteLength; i += 4) {
  356. const value = view.getUint32(i);
  357. const stringValue = value.toString(16);
  358. const padding = "00000000";
  359. const paddedValue = (padding + stringValue).slice(-padding.length);
  360. hexCodes.push(paddedValue);
  361. }
  362. return hexCodes.join("");
  363. }
  364. function log(...args) {
  365. console.log("S-File <browser>", ...args); // eslint-disable-line no-console
  366. }
  367. })();