single-file-core.js 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503
  1. /*
  2. * Copyright 2018 Gildas Lormeau
  3. * contact : gildas.lormeau <at> gmail.com
  4. *
  5. * This file is part of SingleFile.
  6. *
  7. * SingleFile is free software: you can redistribute it and/or modify
  8. * it under the terms of the GNU Lesser General Public License as published by
  9. * the Free Software Foundation, either version 3 of the License, or
  10. * (at your option) any later version.
  11. *
  12. * SingleFile 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
  15. * GNU Lesser General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU Lesser General Public License
  18. * along with SingleFile. If not, see <http://www.gnu.org/licenses/>.
  19. */
  20. const SingleFileCore = (() => {
  21. let Download, DOM, URL;
  22. function SingleFileCore(...args) {
  23. [Download, DOM, URL] = args;
  24. return class {
  25. static async process(options) {
  26. const processor = new PageProcessor(options);
  27. processor.onprogress = options.onprogress;
  28. await processor.loadPage(options.content);
  29. await processor.initialize();
  30. return await processor.getContent();
  31. }
  32. };
  33. }
  34. // -------------
  35. // PageProcessor
  36. // -------------
  37. class PageProcessor {
  38. constructor(options) {
  39. this.options = options;
  40. this.processor = new DOMProcessor(options.url);
  41. }
  42. async loadPage(pageContent) {
  43. if (this.onprogress) {
  44. this.onprogress({ type: "page-loading", details: { pageURL: this.options.url } });
  45. }
  46. await this.processor.loadPage(pageContent);
  47. if (this.onprogress) {
  48. this.onprogress({ type: "page-loaded", details: { pageURL: this.options.url } });
  49. }
  50. }
  51. async initialize() {
  52. if (this.onprogress) {
  53. this.onprogress({ type: "resources-initializing", details: { pageURL: this.options.url } });
  54. }
  55. if (!this.options.jsEnabled) {
  56. this.processor.insertNoscriptContents();
  57. }
  58. this.processor.removeDiscardedResources();
  59. this.processor.resetCharsetMeta();
  60. this.processor.insertFaviconLink();
  61. this.processor.resolveHrefs();
  62. await Promise.all([this.processor.inlineStylesheets(true), this.processor.linkStylesheets()], this.processor.attributeStyles(true));
  63. this.pendingPromises = Promise.all([this.processor.inlineStylesheets(), this.processor.attributeStyles(), this.processor.pageResources()]);
  64. if (this.onprogress) {
  65. this.onprogress({ type: "resources-initialized", details: { pageURL: this.options.url, index: 0, max: batchRequest.getMaxResources() } });
  66. }
  67. }
  68. async getContent() {
  69. await this.processor.retrieveResources(
  70. details => {
  71. if (this.onprogress) {
  72. details.pageURL = this.options.url;
  73. this.onprogress({ type: "resource-loading", details });
  74. }
  75. },
  76. details => {
  77. if (this.onprogress) {
  78. details.pageURL = this.options.url;
  79. this.onprogress({ type: "resource-loaded", details });
  80. }
  81. });
  82. await this.pendingPromises;
  83. if (this.options.removeUnusedCSSRules) {
  84. this.processor.removeUnusedCSSRules();
  85. }
  86. if (this.options.removeHiddenElements) {
  87. this.processor.removeHiddenElements();
  88. }
  89. if (this.onprogress) {
  90. this.onprogress({ type: "page-ended", details: { pageURL: this.options.url } });
  91. }
  92. return this.processor.getContent();
  93. }
  94. }
  95. // --------
  96. // BatchRequest
  97. // --------
  98. class BatchRequest {
  99. constructor() {
  100. this.requests = new Map();
  101. }
  102. async addURL(resourceURL) {
  103. return new Promise((resolve, reject) => {
  104. const resourceRequests = this.requests.get(resourceURL);
  105. if (resourceRequests) {
  106. resourceRequests.push({ resolve, reject });
  107. } else {
  108. this.requests.set(resourceURL, [{ resolve, reject }]);
  109. }
  110. });
  111. }
  112. getMaxResources() {
  113. return Array.from(this.requests.keys()).length;
  114. }
  115. async run(beforeListener, afterListener) {
  116. const resourceURLs = Array.from(this.requests.keys());
  117. let indexResource = 1, indexAfterResource = 1;
  118. return Promise.all(resourceURLs.map(async resourceURL => {
  119. let error;
  120. const resourceRequests = this.requests.get(resourceURL);
  121. beforeListener({ index: indexResource, max: resourceURLs.length, url: resourceURL, error });
  122. indexResource = indexResource + 1;
  123. try {
  124. const dataURI = await Download.getContent(resourceURL, true);
  125. resourceRequests.map(resourceRequest => resourceRequest.resolve(dataURI));
  126. } catch (responseError) {
  127. error = responseError;
  128. resourceRequests.map(resourceRequest => resourceRequest.reject(error));
  129. }
  130. afterListener({ index: indexAfterResource, max: resourceURLs.length, url: resourceURL, error });
  131. indexAfterResource = indexAfterResource + 1;
  132. this.requests.delete(resourceURL);
  133. }));
  134. }
  135. }
  136. // ------------
  137. // DOMProcessor
  138. // ------------
  139. const ESCAPED_FRAGMENT = "_escaped_fragment_=";
  140. const batchRequest = new BatchRequest();
  141. class DOMProcessor {
  142. constructor(url) {
  143. this.baseURI = url;
  144. }
  145. async loadPage(pageContent) {
  146. if (!pageContent) {
  147. pageContent = await Download.getContent(this.baseURI);
  148. }
  149. this.dom = DOM.create(pageContent, this.baseURI);
  150. this.DOMParser = this.dom.DOMParser;
  151. this.getComputedStyle = this.dom.getComputedStyle;
  152. this.doc = this.dom.document;
  153. if (!pageContent && this.doc.querySelector("meta[name=fragment][content=\"!\"]") && !this.baseURI.endsWith("?" + ESCAPED_FRAGMENT) && !this.baseURI.endsWith("&" + ESCAPED_FRAGMENT)) {
  154. await DOMProcessor.loadEscapedFragmentPage();
  155. }
  156. }
  157. async loadEscapedFragmentPage() {
  158. if (this.baseURI.includes("?")) {
  159. this.baseURI += "&";
  160. } else {
  161. this.baseURI += "?";
  162. }
  163. this.baseURI += ESCAPED_FRAGMENT;
  164. await this.loadPage();
  165. }
  166. async retrieveResources(beforeListener, afterListener) {
  167. await batchRequest.run(beforeListener, afterListener);
  168. }
  169. getContent() {
  170. const titleElement = this.doc.head.querySelector("title");
  171. let title;
  172. if (titleElement) {
  173. title = titleElement.textContent.trim();
  174. }
  175. return {
  176. title: title || this.baseURI.match(/([^/]*)\/?$/),
  177. content: this.dom.serialize()
  178. };
  179. }
  180. insertNoscriptContents() {
  181. if (this.DOMParser) {
  182. this.doc.querySelectorAll("noscript").forEach(element => {
  183. const fragment = this.doc.createDocumentFragment();
  184. Array.from(element.childNodes).forEach(node => {
  185. const parsedNode = new this.DOMParser().parseFromString(node.nodeValue, "text/html");
  186. Array.from(parsedNode.head.childNodes).concat(Array.from(parsedNode.body.childNodes)).forEach(node => {
  187. this.doc.importNode(node);
  188. fragment.appendChild(node);
  189. });
  190. });
  191. element.parentElement.replaceChild(fragment, element);
  192. });
  193. }
  194. }
  195. removeDiscardedResources() {
  196. this.doc.querySelectorAll("script, iframe, frame, applet, meta[http-equiv=refresh], object:not([type=\"image/svg+xml\"]):not([type=\"image/svg-xml\"]), embed:not([src*=\".svg\"]), link[rel*=preload], link[rel*=prefetch]").forEach(element => element.remove());
  197. this.doc.querySelectorAll("[onload]").forEach(element => element.removeAttribute("onload"));
  198. this.doc.querySelectorAll("audio[src], video[src]").forEach(element => element.removeAttribute("src"));
  199. }
  200. resetCharsetMeta() {
  201. this.doc.querySelectorAll("meta[charset]").forEach(element => element.remove());
  202. const metaElement = this.doc.createElement("meta");
  203. metaElement.setAttribute("charset", "utf-8");
  204. this.doc.head.insertBefore(metaElement, this.doc.head.firstElementChild);
  205. }
  206. insertFaviconLink() {
  207. let faviconElement = this.doc.querySelectorAll("link[href][rel*=\"icon\"]")[0];
  208. if (!faviconElement) {
  209. faviconElement = this.doc.createElement("link");
  210. faviconElement.setAttribute("type", "image/x-icon");
  211. faviconElement.setAttribute("rel", "shortcut icon");
  212. faviconElement.setAttribute("href", "/favicon.ico");
  213. this.doc.head.appendChild(faviconElement);
  214. }
  215. }
  216. resolveHrefs() {
  217. this.doc.querySelectorAll("[href]").forEach(element => element.setAttribute("href", element.href));
  218. }
  219. removeUnusedCSSRules() {
  220. const doc = this.doc;
  221. doc.querySelectorAll("style").forEach(style => {
  222. const cssRules = [];
  223. if (style.sheet) {
  224. processRules(style.sheet.rules, cssRules);
  225. style.innerText = cssRules.join("");
  226. }
  227. });
  228. function processRules(rules, cssRules) {
  229. Array.from(rules).forEach(rule => {
  230. if (rule.media) {
  231. cssRules.push("@media " + Array.prototype.join.call(rule.media, ",") + " {");
  232. processRules(rule.cssRules, cssRules);
  233. cssRules.push("}");
  234. } else if (rule.selectorText) {
  235. const selector = rule.selectorText.replace(/::after|::before|::first-line|::first-letter|:focus|:hover/gi, "").trim();
  236. if (selector) {
  237. try {
  238. if (doc.querySelector(selector)) {
  239. cssRules.push(rule.cssText);
  240. }
  241. } catch (e) {
  242. cssRules.push(rule.cssText);
  243. }
  244. }
  245. } else {
  246. cssRules.push(rule.cssText);
  247. }
  248. });
  249. }
  250. }
  251. removeHiddenElements() {
  252. this.doc.querySelectorAll("html > body *:not(style):not(script):not(link)").forEach(element => {
  253. if (this.getComputedStyle) {
  254. const style = this.getComputedStyle(element);
  255. if ((style.visibility == "hidden" || style.display == "none" || style.opacity == 0)) {
  256. element.remove();
  257. }
  258. }
  259. });
  260. }
  261. async pageResources() {
  262. await Promise.all([
  263. DomProcessorHelper.processAttribute(this.doc.querySelectorAll("link[href][rel*=\"icon\"]"), "href", this.baseURI),
  264. DomProcessorHelper.processAttribute(this.doc.querySelectorAll("img[src], input[src][type=image], object[type=\"image/svg+xml\"], object[type=\"image/svg-xml\"], embed[src*=\".svg\"]"), "src", this.baseURI),
  265. DomProcessorHelper.processAttribute(this.doc.querySelectorAll("video[poster]"), "poster", this.baseURI),
  266. DomProcessorHelper.processAttribute(this.doc.querySelectorAll("*[background]"), "background", this.baseURI),
  267. DomProcessorHelper.processAttribute(this.doc.querySelectorAll("image, use"), "xlink:href", this.baseURI),
  268. DomProcessorHelper.processSrcSet(this.doc.querySelectorAll("[srcset]"), this.baseURI)
  269. ]);
  270. }
  271. async inlineStylesheets(initialization) {
  272. await Promise.all(Array.from(this.doc.querySelectorAll("style")).map(async styleElement => {
  273. let stylesheetContent = initialization ? await DomProcessorHelper.resolveImportURLs(styleElement.textContent, this.baseURI) : await DomProcessorHelper.processStylesheet(styleElement.textContent, this.baseURI);
  274. // stylesheetContent = DomUtil.wrapMediaQuery(stylesheetContent, styleElement.media);
  275. styleElement.textContent = stylesheetContent;
  276. }));
  277. }
  278. async attributeStyles(initialization) {
  279. await Promise.all(Array.from(this.doc.querySelectorAll("[style]")).map(async element => {
  280. const stylesheetContent = initialization ? await DomProcessorHelper.resolveImportURLs(element.getAttribute("style"), this.baseURI) : await DomProcessorHelper.processStylesheet(element.getAttribute("style"), this.baseURI);
  281. element.setAttribute("style", stylesheetContent);
  282. }));
  283. }
  284. async linkStylesheets() {
  285. await Promise.all(Array.from(this.doc.querySelectorAll("link[rel*=stylesheet]")).map(async linkElement => {
  286. const stylesheetContent = await DomProcessorHelper.resolveLinkStylesheetURLs(linkElement.href, this.baseURI, linkElement.media);
  287. if (stylesheetContent) {
  288. const styleElement = this.doc.createElement("style");
  289. styleElement.textContent = stylesheetContent;
  290. linkElement.parentElement.replaceChild(styleElement, linkElement);
  291. }
  292. }));
  293. }
  294. }
  295. // ---------
  296. // DomHelper
  297. // ---------
  298. const DATA_URI_PREFIX = "data:";
  299. class DomProcessorHelper {
  300. static async resolveImportURLs(stylesheetContent, baseURI) {
  301. stylesheetContent = DomUtil.removeCssComments(stylesheetContent);
  302. const imports = DomUtil.getImportFunctions(stylesheetContent);
  303. await Promise.all(imports.map(async cssImport => {
  304. const match = DomUtil.matchImport(cssImport);
  305. if (match) {
  306. const resourceURL = DomUtil.normalizeURL(match.resourceURL);
  307. if (resourceURL != baseURI && !match.resourceURL.startsWith(DATA_URI_PREFIX)) {
  308. let importedStylesheetContent = await Download.getContent(new URL(match.resourceURL, baseURI).href);
  309. importedStylesheetContent = DomUtil.wrapMediaQuery(importedStylesheetContent, match.media);
  310. if (stylesheetContent.indexOf(cssImport) != -1) {
  311. stylesheetContent = stylesheetContent.replace(cssImport, importedStylesheetContent);
  312. }
  313. }
  314. }
  315. }));
  316. stylesheetContent = DomProcessorHelper.resolveStylesheetURLs(stylesheetContent, baseURI);
  317. if (imports.length) {
  318. return await DomProcessorHelper.resolveImportURLs(stylesheetContent, baseURI);
  319. } else {
  320. return stylesheetContent;
  321. }
  322. }
  323. static resolveStylesheetURLs(stylesheetContent, baseURI) {
  324. const urlFunctions = DomUtil.getUrlFunctions(stylesheetContent);
  325. urlFunctions.map(urlFunction => {
  326. let resourceURL = DomUtil.matchURL(urlFunction);
  327. resourceURL = DomUtil.normalizeURL(resourceURL);
  328. if (resourceURL && resourceURL != baseURI && !resourceURL.startsWith(DATA_URI_PREFIX)) {
  329. stylesheetContent = stylesheetContent.replace(urlFunction, urlFunction.replace(resourceURL, new URL(resourceURL, baseURI).href));
  330. }
  331. });
  332. return stylesheetContent;
  333. }
  334. static async resolveLinkStylesheetURLs(resourceURL, baseURI, media) {
  335. resourceURL = DomUtil.normalizeURL(resourceURL);
  336. if (resourceURL && resourceURL != baseURI && !resourceURL.startsWith(DATA_URI_PREFIX)) {
  337. let stylesheetContent = await Download.getContent(resourceURL);
  338. stylesheetContent = await DomProcessorHelper.resolveImportURLs(stylesheetContent, resourceURL);
  339. stylesheetContent = DomUtil.wrapMediaQuery(stylesheetContent, media);
  340. return stylesheetContent;
  341. }
  342. }
  343. static async processStylesheet(stylesheetContent, baseURI) {
  344. const urlFunctions = DomUtil.getUrlFunctions(stylesheetContent);
  345. await Promise.all(urlFunctions.map(async urlFunction => {
  346. let resourceURL = DomUtil.matchURL(urlFunction);
  347. resourceURL = DomUtil.normalizeURL(resourceURL);
  348. if (resourceURL && resourceURL != baseURI && !resourceURL.startsWith(DATA_URI_PREFIX)) {
  349. const dataURI = await batchRequest.addURL(resourceURL);
  350. stylesheetContent = stylesheetContent.replace(urlFunction, urlFunction.replace(resourceURL, dataURI));
  351. }
  352. }));
  353. return stylesheetContent;
  354. }
  355. static async processAttribute(resourceElements, attributeName, baseURI) {
  356. await Promise.all(Array.from(resourceElements).map(async resourceElement => {
  357. let resourceURL = resourceElement.getAttribute(attributeName);
  358. if (resourceURL) {
  359. resourceURL = DomUtil.normalizeURL(resourceURL);
  360. if (resourceURL && resourceURL != baseURI && !resourceURL.startsWith(DATA_URI_PREFIX)) {
  361. try {
  362. const dataURI = await batchRequest.addURL(new URL(resourceURL, baseURI).href);
  363. resourceElement.setAttribute(attributeName, dataURI);
  364. } catch (e) {
  365. // ignored
  366. }
  367. }
  368. }
  369. }));
  370. }
  371. static async processSrcSet(resourceElements, baseURI) {
  372. await Promise.all(Array.from(resourceElements).map(async resourceElement => {
  373. const attributeValue = resourceElement.getAttribute("srcset");
  374. const srcSet = await Promise.all(attributeValue.split(",").map(async src => {
  375. let [resourceURL, descriptor] = src.trim().split(/\s+/);
  376. resourceURL = DomUtil.normalizeURL(resourceURL);
  377. if (resourceURL && resourceURL != baseURI && !resourceURL.startsWith(DATA_URI_PREFIX)) {
  378. try {
  379. const dataURI = await batchRequest.addURL(new URL(resourceURL, baseURI).href);
  380. return dataURI + (descriptor ? " " + descriptor : "");
  381. } catch (e) {
  382. // ignored
  383. }
  384. }
  385. }));
  386. resourceElement.setAttribute("srcset", srcSet.join(","));
  387. }));
  388. }
  389. }
  390. // -------
  391. // DomUtil
  392. // -------
  393. const REGEXP_URL_FN = /(url\s*\(\s*'([^']*)'\s*\))|(url\s*\(\s*"([^"]*)"\s*\))|(url\s*\(\s*([^)]*)\s*\))/gi;
  394. const REGEXP_URL_SIMPLE_QUOTES_FN = /^url\s*\(\s*'([^']*)'\s*\)$/i;
  395. const REGEXP_URL_DOUBLE_QUOTES_FN = /^url\s*\(\s*"([^"]*)"\s*\)$/i;
  396. const REGEXP_URL_NO_QUOTES_FN = /^url\s*\(\s*([^)]*)\s*\)$/i;
  397. const REGEXP_IMPORT_FN = /(@import\s*url\s*\(\s*'([^']*)'\s*\)\s*([^;]*);?)|(@import\s*url\s*\(\s*"([^"]*)"\s*\)\s*([^;]*);?)|(@import\s*url\s*\(\s*([^)]*)\s*\)\s*([^;]*);?)|(@import\s*\(\s*'([^']*)'\s*\)\s*([^;]*);?)|(@import\s*\(\s*"([^"]*)"\s*\)\s*([^;]*);?)|(@import\s*\(\s*([^)]*)\s*\)\s*([^;]*);?)/gi;
  398. const REGEXP_IMPORT_URL_SIMPLE_QUOTES_FN = /@import\s*url\s*\(\s*'([^']*)'\s*\)\s*([^;]*)/i;
  399. const REGEXP_IMPORT_URL_DOUBLE_QUOTES_FN = /@import\s*url\s*\(\s*"([^"]*)"\s*\)\s*([^;]*)/i;
  400. const REGEXP_IMPORT_URL_NO_QUOTES_FN = /@import\s*url\s*\(\s*([^)]*)\s*\)\s*([^;]*)/i;
  401. const REGEXP_IMPORT_SIMPLE_QUOTES_FN = /@import\s*\(\s*'([^']*)'\s*\)\s*([^;]*)/i;
  402. const REGEXP_IMPORT_DOUBLE_QUOTES_FN = /@import\s*\(\s*"([^"]*)"\s*\)\s*([^;]*)/i;
  403. const REGEXP_IMPORT_NO_QUOTES_FN = /@import\s*\(\s*([^)]*)\s*\)\s*([^;]*)/i;
  404. class DomUtil {
  405. static normalizeURL(url) {
  406. return url.split("#")[0];
  407. }
  408. static getUrlFunctions(stylesheetContent) {
  409. return stylesheetContent.match(REGEXP_URL_FN) || [];
  410. }
  411. static getImportFunctions(stylesheetContent) {
  412. return stylesheetContent.match(REGEXP_IMPORT_FN) || [];
  413. }
  414. static matchURL(stylesheetContent) {
  415. const match = stylesheetContent.match(REGEXP_URL_SIMPLE_QUOTES_FN) ||
  416. stylesheetContent.match(REGEXP_URL_DOUBLE_QUOTES_FN) ||
  417. stylesheetContent.match(REGEXP_URL_NO_QUOTES_FN);
  418. return match && match[1];
  419. }
  420. static matchImport(stylesheetContent) {
  421. const match = stylesheetContent.match(REGEXP_IMPORT_URL_SIMPLE_QUOTES_FN) ||
  422. stylesheetContent.match(REGEXP_IMPORT_URL_DOUBLE_QUOTES_FN) ||
  423. stylesheetContent.match(REGEXP_IMPORT_URL_NO_QUOTES_FN) ||
  424. stylesheetContent.match(REGEXP_IMPORT_SIMPLE_QUOTES_FN) ||
  425. stylesheetContent.match(REGEXP_IMPORT_DOUBLE_QUOTES_FN) ||
  426. stylesheetContent.match(REGEXP_IMPORT_NO_QUOTES_FN);
  427. if (match) {
  428. const [, resourceURL, media] = match;
  429. return { resourceURL, media };
  430. }
  431. }
  432. static removeCssComments(stylesheetContent) {
  433. let start, end;
  434. do {
  435. start = stylesheetContent.indexOf("/*");
  436. end = stylesheetContent.indexOf("*/", start);
  437. if (start != -1 && end != -1) {
  438. stylesheetContent = stylesheetContent.substring(0, start) + stylesheetContent.substr(end + 2);
  439. }
  440. } while (start != -1 && end != -1);
  441. return stylesheetContent;
  442. }
  443. static wrapMediaQuery(stylesheetContent, mediaQuery) {
  444. if (mediaQuery) {
  445. return "@media " + mediaQuery + "{ " + stylesheetContent + " }";
  446. } else {
  447. return stylesheetContent;
  448. }
  449. }
  450. }
  451. return SingleFileCore;
  452. })();
  453. if (typeof module != "undefined") {
  454. module.exports = SingleFileCore;
  455. }