single-file-util.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360
  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 globalThis */
  24. import * as vendor from "./vendor/index.js";
  25. import * as modules from "./modules/index.js";
  26. import * as helper from "./single-file-helper.js";
  27. const DEBUG = false;
  28. const ONE_MB = 1024 * 1024;
  29. const PREFIX_CONTENT_TYPE_TEXT = "text/";
  30. const DEFAULT_REPLACED_CHARACTERS = ["~", "+", "\\\\", "?", "%", "*", ":", "|", "\"", "<", ">", "\x00-\x1f", "\x7F"];
  31. const DEFAULT_REPLACEMENT_CHARACTER = "_";
  32. const URL = globalThis.URL;
  33. const DOMParser = globalThis.DOMParser;
  34. const Blob = globalThis.Blob;
  35. const FileReader = globalThis.FileReader;
  36. const fetch = (url, options) => globalThis.fetch(url, options);
  37. const crypto = globalThis.crypto;
  38. const TextDecoder = globalThis.TextDecoder;
  39. const TextEncoder = globalThis.TextEncoder;
  40. export {
  41. getInstance
  42. };
  43. function getInstance(utilOptions) {
  44. utilOptions = utilOptions || {};
  45. utilOptions.fetch = utilOptions.fetch || fetch;
  46. utilOptions.frameFetch = utilOptions.frameFetch || utilOptions.fetch || fetch;
  47. return {
  48. getContent,
  49. parseURL(resourceURL, baseURI) {
  50. if (baseURI === undefined) {
  51. return new URL(resourceURL);
  52. } else {
  53. return new URL(resourceURL, baseURI);
  54. }
  55. },
  56. resolveURL(resourceURL, baseURI) {
  57. return this.parseURL(resourceURL, baseURI).href;
  58. },
  59. getValidFilename(filename, replacedCharacters = DEFAULT_REPLACED_CHARACTERS, replacementCharacter = DEFAULT_REPLACEMENT_CHARACTER) {
  60. replacedCharacters.forEach(replacedCharacter => filename = filename.replace(new RegExp("[" + replacedCharacter + "]+", "g"), replacementCharacter));
  61. filename = filename
  62. .replace(/\.\.\//g, "")
  63. .replace(/^\/+/, "")
  64. .replace(/\/+/g, "/")
  65. .replace(/\/$/, "")
  66. .replace(/\.$/, "")
  67. .replace(/\.\//g, "." + replacementCharacter)
  68. .replace(/\/\./g, "/" + replacementCharacter);
  69. return filename;
  70. },
  71. parseDocContent(content, baseURI) {
  72. const doc = (new DOMParser()).parseFromString(content, "text/html");
  73. if (!doc.head) {
  74. doc.documentElement.insertBefore(doc.createElement("HEAD"), doc.body);
  75. }
  76. let baseElement = doc.querySelector("base");
  77. if (!baseElement || !baseElement.getAttribute("href")) {
  78. if (baseElement) {
  79. baseElement.remove();
  80. }
  81. baseElement = doc.createElement("base");
  82. baseElement.setAttribute("href", baseURI);
  83. doc.head.insertBefore(baseElement, doc.head.firstChild);
  84. }
  85. return doc;
  86. },
  87. parseXMLContent(content) {
  88. return (new DOMParser()).parseFromString(content, "text/xml");
  89. },
  90. parseSVGContent(content) {
  91. const doc = (new DOMParser()).parseFromString(content, "image/svg+xml");
  92. if (doc.querySelector("parsererror")) {
  93. return (new DOMParser()).parseFromString(content, "text/html");
  94. } else {
  95. return doc;
  96. }
  97. },
  98. async digest(algo, text) {
  99. try {
  100. const hash = await crypto.subtle.digest(algo, new TextEncoder("utf-8").encode(text));
  101. return hex(hash);
  102. } catch (error) {
  103. return "";
  104. }
  105. },
  106. getContentSize(content) {
  107. return new Blob([content]).size;
  108. },
  109. truncateText(content, maxSize) {
  110. const blob = new Blob([content]);
  111. const reader = new FileReader();
  112. reader.readAsText(blob.slice(0, maxSize));
  113. return new Promise((resolve, reject) => {
  114. reader.addEventListener("load", () => {
  115. if (content.startsWith(reader.result)) {
  116. resolve(reader.result);
  117. } else {
  118. this.truncateText(content, maxSize - 1).then(resolve).catch(reject);
  119. }
  120. }, false);
  121. reader.addEventListener("error", reject, false);
  122. });
  123. },
  124. minifyHTML(doc, options) {
  125. return modules.htmlMinifier.process(doc, options);
  126. },
  127. minifyCSSRules(stylesheets, styles, mediaAllInfo) {
  128. return modules.cssRulesMinifier.process(stylesheets, styles, mediaAllInfo);
  129. },
  130. removeUnusedFonts(doc, stylesheets, styles, options) {
  131. return modules.fontsMinifier.process(doc, stylesheets, styles, options);
  132. },
  133. removeAlternativeFonts(doc, stylesheets, fontURLs, fontTests) {
  134. return modules.fontsAltMinifier.process(doc, stylesheets, fontURLs, fontTests);
  135. },
  136. getMediaAllInfo(doc, stylesheets, styles) {
  137. return modules.matchedRules.getMediaAllInfo(doc, stylesheets, styles);
  138. },
  139. compressCSS(content, options) {
  140. return vendor.cssMinifier.processString(content, options);
  141. },
  142. minifyMedias(stylesheets) {
  143. return modules.mediasAltMinifier.process(stylesheets);
  144. },
  145. removeAlternativeImages(doc) {
  146. return modules.imagesAltMinifier.process(doc);
  147. },
  148. parseSrcset(srcset) {
  149. return vendor.srcsetParser.process(srcset);
  150. },
  151. preProcessDoc(doc, win, options) {
  152. return helper.preProcessDoc(doc, win, options);
  153. },
  154. postProcessDoc(doc, markedElements) {
  155. helper.postProcessDoc(doc, markedElements);
  156. },
  157. serialize(doc, compressHTML) {
  158. return modules.serializer.process(doc, compressHTML);
  159. },
  160. removeQuotes(string) {
  161. return helper.removeQuotes(string);
  162. },
  163. ON_BEFORE_CAPTURE_EVENT_NAME: helper.ON_BEFORE_CAPTURE_EVENT_NAME,
  164. ON_AFTER_CAPTURE_EVENT_NAME: helper.ON_AFTER_CAPTURE_EVENT_NAME,
  165. WIN_ID_ATTRIBUTE_NAME: helper.WIN_ID_ATTRIBUTE_NAME,
  166. REMOVED_CONTENT_ATTRIBUTE_NAME: helper.REMOVED_CONTENT_ATTRIBUTE_NAME,
  167. HIDDEN_CONTENT_ATTRIBUTE_NAME: helper.HIDDEN_CONTENT_ATTRIBUTE_NAME,
  168. HIDDEN_FRAME_ATTRIBUTE_NAME: helper.HIDDEN_FRAME_ATTRIBUTE_NAME,
  169. IMAGE_ATTRIBUTE_NAME: helper.IMAGE_ATTRIBUTE_NAME,
  170. POSTER_ATTRIBUTE_NAME: helper.POSTER_ATTRIBUTE_NAME,
  171. CANVAS_ATTRIBUTE_NAME: helper.CANVAS_ATTRIBUTE_NAME,
  172. HTML_IMPORT_ATTRIBUTE_NAME: helper.HTML_IMPORT_ATTRIBUTE_NAME,
  173. STYLE_ATTRIBUTE_NAME: helper.STYLE_ATTRIBUTE_NAME,
  174. INPUT_VALUE_ATTRIBUTE_NAME: helper.INPUT_VALUE_ATTRIBUTE_NAME,
  175. SHADOW_ROOT_ATTRIBUTE_NAME: helper.SHADOW_ROOT_ATTRIBUTE_NAME,
  176. PRESERVED_SPACE_ELEMENT_ATTRIBUTE_NAME: helper.PRESERVED_SPACE_ELEMENT_ATTRIBUTE_NAME,
  177. STYLESHEET_ATTRIBUTE_NAME: helper.STYLESHEET_ATTRIBUTE_NAME,
  178. SELECTED_CONTENT_ATTRIBUTE_NAME: helper.SELECTED_CONTENT_ATTRIBUTE_NAME,
  179. COMMENT_HEADER: helper.COMMENT_HEADER,
  180. COMMENT_HEADER_LEGACY: helper.COMMENT_HEADER_LEGACY,
  181. SINGLE_FILE_UI_ELEMENT_CLASS: helper.SINGLE_FILE_UI_ELEMENT_CLASS
  182. };
  183. async function getContent(resourceURL, options) {
  184. let response, startTime;
  185. const fetchResource = utilOptions.fetch;
  186. const fetchFrameResource = utilOptions.frameFetch;
  187. if (DEBUG) {
  188. startTime = Date.now();
  189. log(" // STARTED download url =", resourceURL, "asBinary =", options.asBinary);
  190. }
  191. if (options.blockMixedContent && /^https:/i.test(options.baseURI) && !/^https:/i.test(resourceURL)) {
  192. return { data: options.asBinary ? "data:null;base64," : "", resourceURL };
  193. }
  194. try {
  195. const accept = options.acceptHeaders[options.expectedType] || "*/*";
  196. if (options.frameId) {
  197. try {
  198. response = await fetchFrameResource(resourceURL, { frameId: options.frameId, referrer: options.resourceReferrer, headers: { accept } });
  199. } catch (error) {
  200. response = await fetchResource(resourceURL, { headers: { accept } });
  201. }
  202. } else {
  203. response = await fetchResource(resourceURL, { referrer: options.resourceReferrer, headers: { accept } });
  204. }
  205. } catch (error) {
  206. return { data: options.asBinary ? "data:null;base64," : "", resourceURL };
  207. }
  208. let buffer;
  209. try {
  210. buffer = await response.arrayBuffer();
  211. } catch (error) {
  212. return { data: options.asBinary ? "data:null;base64," : "", resourceURL };
  213. }
  214. resourceURL = response.url || resourceURL;
  215. let contentType = "", charset;
  216. try {
  217. const mimeType = new vendor.MIMEType(response.headers.get("content-type"));
  218. contentType = mimeType.type + "/" + mimeType.subtype;
  219. charset = mimeType.parameters.get("charset");
  220. } catch (error) {
  221. // ignored
  222. }
  223. if (!contentType) {
  224. contentType = guessMIMEType(options.expectedType, buffer);
  225. }
  226. if (!charset && options.charset) {
  227. charset = options.charset;
  228. }
  229. if (options.asBinary) {
  230. try {
  231. if (DEBUG) {
  232. log(" // ENDED download url =", resourceURL, "delay =", Date.now() - startTime);
  233. }
  234. if (options.maxResourceSizeEnabled && buffer.byteLength > options.maxResourceSize * ONE_MB) {
  235. return { data: "data:null;base64,", resourceURL };
  236. } else {
  237. const reader = new FileReader();
  238. reader.readAsDataURL(new Blob([buffer], { type: contentType + (options.charset ? ";charset=" + options.charset : "") }));
  239. const dataUri = await new Promise((resolve, reject) => {
  240. reader.addEventListener("load", () => resolve(reader.result), false);
  241. reader.addEventListener("error", reject, false);
  242. });
  243. return { data: dataUri, resourceURL };
  244. }
  245. } catch (error) {
  246. return { data: "data:null;base64,", resourceURL };
  247. }
  248. } else {
  249. if (response.status >= 400 || (options.validateTextContentType && contentType && !contentType.startsWith(PREFIX_CONTENT_TYPE_TEXT))) {
  250. return { data: "", resourceURL };
  251. }
  252. if (!charset) {
  253. charset = "utf-8";
  254. }
  255. if (DEBUG) {
  256. log(" // ENDED download url =", resourceURL, "delay =", Date.now() - startTime);
  257. }
  258. if (options.maxResourceSizeEnabled && buffer.byteLength > options.maxResourceSize * ONE_MB) {
  259. return { data: "", resourceURL, charset };
  260. } else {
  261. try {
  262. return { data: new TextDecoder(charset).decode(buffer), resourceURL, charset };
  263. } catch (error) {
  264. try {
  265. charset = "utf-8";
  266. return { data: new TextDecoder(charset).decode(buffer), resourceURL, charset };
  267. } catch (error) {
  268. return { data: "", resourceURL, charset };
  269. }
  270. }
  271. }
  272. }
  273. }
  274. }
  275. function guessMIMEType(expectedType, buffer) {
  276. if (expectedType == "image") {
  277. if (compareBytes([255, 255, 255, 255], [0, 0, 1, 0])) {
  278. return "image/x-icon";
  279. }
  280. if (compareBytes([255, 255, 255, 255], [0, 0, 2, 0])) {
  281. return "image/x-icon";
  282. }
  283. if (compareBytes([255, 255], [78, 77])) {
  284. return "image/bmp";
  285. }
  286. if (compareBytes([255, 255, 255, 255, 255, 255], [71, 73, 70, 56, 57, 97])) {
  287. return "image/gif";
  288. }
  289. if (compareBytes([255, 255, 255, 255, 255, 255], [71, 73, 70, 56, 59, 97])) {
  290. return "image/gif";
  291. }
  292. 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])) {
  293. return "image/webp";
  294. }
  295. if (compareBytes([255, 255, 255, 255, 255, 255, 255, 255], [137, 80, 78, 71, 13, 10, 26, 10])) {
  296. return "image/png";
  297. }
  298. if (compareBytes([255, 255, 255], [255, 216, 255])) {
  299. return "image/jpeg";
  300. }
  301. }
  302. if (expectedType == "font") {
  303. 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],
  304. [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])) {
  305. return "application/vnd.ms-fontobject";
  306. }
  307. if (compareBytes([255, 255, 255, 255], [0, 1, 0, 0])) {
  308. return "font/ttf";
  309. }
  310. if (compareBytes([255, 255, 255, 255], [79, 84, 84, 79])) {
  311. return "font/otf";
  312. }
  313. if (compareBytes([255, 255, 255, 255], [116, 116, 99, 102])) {
  314. return "font/collection";
  315. }
  316. if (compareBytes([255, 255, 255, 255], [119, 79, 70, 70])) {
  317. return "font/woff";
  318. }
  319. if (compareBytes([255, 255, 255, 255], [119, 79, 70, 50])) {
  320. return "font/woff2";
  321. }
  322. }
  323. function compareBytes(mask, pattern) {
  324. let patternMatch = true, index = 0;
  325. if (buffer.byteLength >= pattern.length) {
  326. const value = new Uint8Array(buffer, 0, mask.length);
  327. for (index = 0; index < mask.length && patternMatch; index++) {
  328. patternMatch = patternMatch && ((value[index] & mask[index]) == pattern[index]);
  329. }
  330. return patternMatch;
  331. }
  332. }
  333. }
  334. // https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/digest
  335. function hex(buffer) {
  336. const hexCodes = [];
  337. const view = new DataView(buffer);
  338. for (let i = 0; i < view.byteLength; i += 4) {
  339. const value = view.getUint32(i);
  340. const stringValue = value.toString(16);
  341. const padding = "00000000";
  342. const paddedValue = (padding + stringValue).slice(-padding.length);
  343. hexCodes.push(paddedValue);
  344. }
  345. return hexCodes.join("");
  346. }
  347. function log(...args) {
  348. console.log("S-File <browser>", ...args); // eslint-disable-line no-console
  349. }