single-file-core.js 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770
  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. const SELECTED_CONTENT_ATTRIBUTE_NAME = "data-single-file-selected-content";
  22. let Download, DOM, URL;
  23. function SingleFileCore(...args) {
  24. [Download, DOM, URL] = args;
  25. return class {
  26. static async initialize(options) {
  27. const processor = new PageProcessor(options);
  28. processor.onprogress = options.onprogress;
  29. await processor.loadPage(options.content);
  30. return async () => {
  31. await processor.initialize();
  32. return await processor.getPageData();
  33. };
  34. }
  35. };
  36. }
  37. // -------------
  38. // ProgressEvent
  39. // -------------
  40. const PAGE_LOADING = "page-loading";
  41. const PAGE_LOADED = "page-loaded";
  42. const RESOURCES_INITIALIZING = "resource-initializing";
  43. const RESOURCES_INITIALIZED = "resources-initialized";
  44. const RESOURCE_LOADING = "resource-loading";
  45. const RESOURCE_LOADED = "resource-loaded";
  46. const PAGE_ENDED = "page-ended";
  47. class ProgressEvent {
  48. constructor(type, details) {
  49. return { type, details, PAGE_LOADING, PAGE_LOADED, RESOURCES_INITIALIZING, RESOURCES_INITIALIZED, RESOURCE_LOADING, RESOURCE_LOADED, PAGE_ENDED };
  50. }
  51. }
  52. // -------------
  53. // PageProcessor
  54. // -------------
  55. class PageProcessor {
  56. constructor(options) {
  57. this.options = options;
  58. this.processor = new DOMProcessor(options);
  59. }
  60. async loadPage(pageContent) {
  61. if (this.onprogress) {
  62. this.onprogress(new ProgressEvent(PAGE_LOADING, { pageURL: this.options.url }));
  63. }
  64. await this.processor.loadPage(pageContent);
  65. if (this.onprogress) {
  66. this.onprogress(new ProgressEvent(PAGE_LOADED, { pageURL: this.options.url }));
  67. }
  68. }
  69. async initialize() {
  70. if (this.onprogress) {
  71. this.onprogress(new ProgressEvent(RESOURCES_INITIALIZING, { pageURL: this.options.url }));
  72. }
  73. if (!this.options.jsEnabled || (this.options.saveRawPage && this.options.removeScripts)) {
  74. this.processor.insertNoscriptContents();
  75. }
  76. if (this.options.lazyLoadImages) {
  77. this.processor.lazyLoadImages();
  78. }
  79. if (this.options.removeFrames) {
  80. this.processor.removeFrames();
  81. }
  82. if (this.options.removeImports) {
  83. this.processor.removeImports();
  84. }
  85. if (this.options.removeScripts) {
  86. this.processor.removeScripts();
  87. }
  88. this.processor.removeDiscardedResources();
  89. this.processor.resetCharsetMeta();
  90. if (this.options.compressHTML) {
  91. this.processor.compressHTML();
  92. }
  93. if (this.options.insertFaviconLink) {
  94. this.processor.insertFaviconLink();
  95. }
  96. this.processor.resolveHrefs();
  97. if (this.options.insertSingleFileComment) {
  98. this.processor.insertSingleFileCommentNode();
  99. }
  100. this.processor.replaceCanvasElements();
  101. if (this.options.removeHiddenElements) {
  102. this.processor.removeHiddenElements();
  103. }
  104. if (this.options.removeUnusedCSSRules) {
  105. this.processor.removeUnusedCSSRules();
  106. }
  107. const initializationPromises = [this.processor.inlineStylesheets(true), this.processor.linkStylesheets(), this.processor.attributeStyles(true)];
  108. if (!this.options.removeFrames) {
  109. initializationPromises.push(this.processor.frames(true));
  110. }
  111. if (!this.options.removeImports) {
  112. initializationPromises.push(this.processor.htmlImports(true));
  113. }
  114. await Promise.all(initializationPromises);
  115. this.pendingPromises = [this.processor.inlineStylesheets(), this.processor.attributeStyles(), this.processor.pageResources()];
  116. if (!this.options.removeScripts) {
  117. this.pendingPromises.push(this.processor.scripts());
  118. }
  119. if (this.onprogress) {
  120. this.onprogress(new ProgressEvent(RESOURCES_INITIALIZED, { pageURL: this.options.url, index: 0, max: batchRequest.getMaxResources() }));
  121. }
  122. }
  123. async getPageData() {
  124. await this.processor.retrieveResources(
  125. details => {
  126. if (this.onprogress) {
  127. details.pageURL = this.options.url;
  128. this.onprogress(new ProgressEvent(RESOURCE_LOADING, details));
  129. }
  130. },
  131. details => {
  132. if (this.onprogress) {
  133. details.pageURL = this.options.url;
  134. this.onprogress(new ProgressEvent(RESOURCE_LOADED, details));
  135. }
  136. });
  137. await this.pendingPromises;
  138. if (this.options.removeUnusedCSSRules) {
  139. this.processor.removeUnusedCSSRules();
  140. }
  141. if (!this.options.removeFrames) {
  142. await this.processor.frames();
  143. }
  144. if (!this.options.removeImports) {
  145. await this.processor.htmlImports();
  146. }
  147. if (this.onprogress) {
  148. this.onprogress(new ProgressEvent(PAGE_ENDED, { pageURL: this.options.url }));
  149. }
  150. return this.processor.getPageData();
  151. }
  152. }
  153. // --------
  154. // BatchRequest
  155. // --------
  156. class BatchRequest {
  157. constructor() {
  158. this.requests = new Map();
  159. }
  160. async addURL(resourceURL) {
  161. return new Promise((resolve, reject) => {
  162. const resourceRequests = this.requests.get(resourceURL);
  163. if (resourceRequests) {
  164. resourceRequests.push({ resolve, reject });
  165. } else {
  166. this.requests.set(resourceURL, [{ resolve, reject }]);
  167. }
  168. });
  169. }
  170. getMaxResources() {
  171. return Array.from(this.requests.keys()).length;
  172. }
  173. async run(beforeListener, afterListener) {
  174. const resourceURLs = Array.from(this.requests.keys());
  175. let indexResource = 1, indexAfterResource = 1;
  176. return Promise.all(resourceURLs.map(async resourceURL => {
  177. let error;
  178. const resourceRequests = this.requests.get(resourceURL);
  179. beforeListener({ index: indexResource, max: resourceURLs.length, url: resourceURL, error });
  180. indexResource = indexResource + 1;
  181. try {
  182. const dataURI = await Download.getContent(resourceURL, true);
  183. resourceRequests.map(resourceRequest => resourceRequest.resolve(dataURI));
  184. } catch (responseError) {
  185. error = responseError;
  186. resourceRequests.map(resourceRequest => resourceRequest.reject(error));
  187. }
  188. afterListener({ index: indexAfterResource, max: resourceURLs.length, url: resourceURL, error });
  189. indexAfterResource = indexAfterResource + 1;
  190. this.requests.delete(resourceURL);
  191. }));
  192. }
  193. }
  194. // ------------
  195. // DOMProcessor
  196. // ------------
  197. const ESCAPED_FRAGMENT = "_escaped_fragment_=";
  198. const batchRequest = new BatchRequest();
  199. class DOMProcessor {
  200. constructor(options) {
  201. this.options = options;
  202. this.baseURI = options.url;
  203. }
  204. async loadPage(pageContent) {
  205. if (!pageContent || this.options.saveRawPage) {
  206. pageContent = await Download.getContent(this.baseURI);
  207. }
  208. this.dom = DOM.create(pageContent, this.baseURI);
  209. this.DOMParser = this.dom.DOMParser;
  210. this.getComputedStyle = this.dom.getComputedStyle;
  211. this.doc = this.dom.document;
  212. if (!pageContent && this.doc.querySelector("meta[name=fragment][content=\"!\"]") && !this.baseURI.endsWith("?" + ESCAPED_FRAGMENT) && !this.baseURI.endsWith("&" + ESCAPED_FRAGMENT)) {
  213. await DOMProcessor.loadEscapedFragmentPage();
  214. }
  215. }
  216. async loadEscapedFragmentPage() {
  217. if (this.baseURI.includes("?")) {
  218. this.baseURI += "&";
  219. } else {
  220. this.baseURI += "?";
  221. }
  222. this.baseURI += ESCAPED_FRAGMENT;
  223. await this.loadPage();
  224. }
  225. async retrieveResources(beforeListener, afterListener) {
  226. await batchRequest.run(beforeListener, afterListener);
  227. }
  228. getPageData() {
  229. if (this.options.selected) {
  230. const selectedElement = this.doc.querySelector("[" + SELECTED_CONTENT_ATTRIBUTE_NAME + "]");
  231. DomProcessorHelper.isolateElement(selectedElement.parentElement, selectedElement);
  232. selectedElement.removeAttribute(SELECTED_CONTENT_ATTRIBUTE_NAME);
  233. }
  234. const titleElement = this.doc.querySelector("title");
  235. let title;
  236. if (titleElement) {
  237. title = titleElement.textContent.trim();
  238. }
  239. return {
  240. title: title || (this.baseURI ? this.baseURI.match(/([^/]*)\/?$/) : ""),
  241. content: this.dom.serialize()
  242. };
  243. }
  244. insertNoscriptContents() {
  245. if (this.DOMParser) {
  246. this.doc.querySelectorAll("noscript").forEach(element => {
  247. const fragment = this.doc.createDocumentFragment();
  248. Array.from(element.childNodes).forEach(node => {
  249. const parsedNode = new this.DOMParser().parseFromString(node.nodeValue, "text/html");
  250. Array.from(parsedNode.head.childNodes).concat(Array.from(parsedNode.body.childNodes)).forEach(node => {
  251. this.doc.importNode(node);
  252. fragment.appendChild(node);
  253. });
  254. });
  255. element.parentElement.replaceChild(fragment, element);
  256. });
  257. }
  258. }
  259. lazyLoadImages() {
  260. this.doc.querySelectorAll("img[data-src]").forEach(imgElement => {
  261. if (imgElement.dataset.src && imgElement.src != imgElement.dataset.src) {
  262. imgElement.src = imgElement.dataset.src;
  263. }
  264. });
  265. }
  266. removeDiscardedResources() {
  267. this.doc.querySelectorAll("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());
  268. this.doc.querySelectorAll("[onload]").forEach(element => element.removeAttribute("onload"));
  269. this.doc.querySelectorAll("audio[src], video[src]").forEach(element => element.removeAttribute("src"));
  270. }
  271. removeScripts() {
  272. this.doc.querySelectorAll("script").forEach(element => element.remove());
  273. }
  274. removeFrames() {
  275. this.doc.querySelectorAll("iframe, frame").forEach(element => element.remove());
  276. }
  277. removeImports() {
  278. this.doc.querySelectorAll("link[rel=import]").forEach(element => element.remove());
  279. }
  280. resetCharsetMeta() {
  281. this.doc.querySelectorAll("meta[charset]").forEach(element => element.remove());
  282. const metaElement = this.doc.createElement("meta");
  283. metaElement.setAttribute("charset", "utf-8");
  284. this.doc.head.insertBefore(metaElement, this.doc.head.firstElementChild);
  285. }
  286. insertFaviconLink() {
  287. let faviconElement = this.doc.querySelectorAll("link[href][rel*=\"icon\"]")[0];
  288. if (!faviconElement) {
  289. faviconElement = this.doc.createElement("link");
  290. faviconElement.setAttribute("type", "image/x-icon");
  291. faviconElement.setAttribute("rel", "shortcut icon");
  292. faviconElement.setAttribute("href", "/favicon.ico");
  293. this.doc.head.appendChild(faviconElement);
  294. }
  295. }
  296. resolveHrefs() {
  297. this.doc.querySelectorAll("[href]").forEach(element => element.setAttribute("href", element.href));
  298. }
  299. removeUnusedCSSRules() {
  300. const doc = this.doc;
  301. doc.querySelectorAll("style").forEach(style => {
  302. const cssRules = [];
  303. if (style.sheet) {
  304. processRules(style.sheet.cssRules, cssRules);
  305. style.innerText = cssRules.join("");
  306. }
  307. });
  308. function processRules(rules, cssRules) {
  309. if (rules) {
  310. Array.from(rules).forEach(rule => {
  311. if (rule.media) {
  312. cssRules.push("@media " + Array.prototype.join.call(rule.media, ",") + " {");
  313. processRules(rule.cssRules, cssRules);
  314. cssRules.push("}");
  315. } else if (rule.selectorText) {
  316. const selector = rule.selectorText.replace(/::after|::before|::first-line|::first-letter|:focus|:hover/gi, "").trim();
  317. if (selector) {
  318. try {
  319. if (doc.querySelector(selector)) {
  320. cssRules.push(rule.cssText);
  321. }
  322. } catch (e) {
  323. cssRules.push(rule.cssText);
  324. }
  325. }
  326. } else {
  327. cssRules.push(rule.cssText);
  328. }
  329. });
  330. }
  331. }
  332. }
  333. removeHiddenElements() {
  334. this.doc.querySelectorAll("html > body *:not(style):not(script):not(link)").forEach(element => {
  335. if (this.getComputedStyle) {
  336. const style = this.getComputedStyle(element);
  337. if (element.hidden || style.visibility == "hidden" || style.display == "none" || style.opacity == 0) {
  338. element.remove();
  339. }
  340. }
  341. });
  342. }
  343. compressHTML() {
  344. const textNodesWalker = this.doc.createTreeWalker(this.doc.documentElement, 4, null, false);
  345. let node = textNodesWalker.nextNode();
  346. while (node) {
  347. let element = node.parentElement;
  348. while (element && element.tagName != "PRE") {
  349. element = element.parentElement;
  350. }
  351. if (!element) {
  352. node.textContent = node.textContent.replace(/ +/g, " ");
  353. node.textContent = node.textContent.replace(/\n+/g, " ");
  354. }
  355. node = textNodesWalker.nextNode();
  356. }
  357. const commentNodesWalker = this.doc.createTreeWalker(this.doc.documentElement, 128, null, false);
  358. node = commentNodesWalker.nextNode();
  359. let removedNodes = [];
  360. while (node) {
  361. removedNodes.push(node);
  362. node = commentNodesWalker.nextNode();
  363. }
  364. removedNodes.forEach(node => node.remove());
  365. }
  366. insertSingleFileCommentNode() {
  367. const commentNode = this.doc.createComment("\n Archive processed by SingleFile \n url: " + this.baseURI + " \n saved date: " + new Date() + " \n");
  368. this.doc.documentElement.insertBefore(commentNode, this.doc.documentElement.firstChild);
  369. }
  370. replaceCanvasElements() {
  371. if (this.options.canvasData) {
  372. this.doc.querySelectorAll("canvas").forEach((canvasElement, indexCanvasElement) => {
  373. const canvasData = this.options.canvasData[indexCanvasElement];
  374. if (canvasData) {
  375. const imgElement = this.doc.createElement("img");
  376. imgElement.setAttribute("src", canvasData.dataURI);
  377. Array.from(canvasElement.attributes).forEach(attribute => {
  378. if (attribute.value) {
  379. imgElement.setAttribute(attribute.name, attribute.value);
  380. }
  381. });
  382. if (!imgElement.width && canvasData.width) {
  383. imgElement.style.pixelWidth = canvasData.width;
  384. }
  385. if (!imgElement.height && canvasData.height) {
  386. imgElement.style.pixelHeight = canvasData.height;
  387. }
  388. canvasElement.parentElement.replaceChild(imgElement, canvasElement);
  389. }
  390. });
  391. }
  392. }
  393. async pageResources() {
  394. await Promise.all([
  395. DomProcessorHelper.processAttribute(this.doc.querySelectorAll("link[href][rel*=\"icon\"]"), "href", this.baseURI),
  396. 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),
  397. DomProcessorHelper.processAttribute(this.doc.querySelectorAll("video[poster]"), "poster", this.baseURI),
  398. DomProcessorHelper.processAttribute(this.doc.querySelectorAll("*[background]"), "background", this.baseURI),
  399. DomProcessorHelper.processAttribute(this.doc.querySelectorAll("image, use"), "xlink:href", this.baseURI),
  400. DomProcessorHelper.processSrcset(this.doc.querySelectorAll("[srcset]"), this.baseURI, this.dom)
  401. ]);
  402. }
  403. async inlineStylesheets(initialization) {
  404. await Promise.all(Array.from(this.doc.querySelectorAll("style")).map(async styleElement => {
  405. const stylesheetContent = initialization ? await DomProcessorHelper.resolveImportURLs(styleElement.textContent, this.baseURI) : await DomProcessorHelper.processStylesheet(styleElement.textContent, this.baseURI);
  406. styleElement.textContent = this.options.compressCSS ? this.dom.uglifycss(stylesheetContent) : stylesheetContent;
  407. }));
  408. }
  409. async scripts() {
  410. await Promise.all(Array.from(this.doc.querySelectorAll("script[src]")).map(async scriptElement => {
  411. if (scriptElement.src) {
  412. const scriptContent = await Download.getContent(scriptElement.src);
  413. scriptElement.textContent = scriptContent.replace(/<\/script>/gi, "<\\/script>");
  414. }
  415. scriptElement.removeAttribute("src");
  416. }));
  417. }
  418. async frames(initialization) {
  419. let frameElements = this.doc.querySelectorAll("iframe, frame");
  420. frameElements = DomUtil.removeNoScriptFrames(frameElements);
  421. await Promise.all(frameElements.map(async (frameElement, frameIndex) => {
  422. const frameWindowId = (this.options.windowId || "0") + "." + frameIndex;
  423. const frameData = this.options.framesData.find(frame => frame.windowId == frameWindowId);
  424. if (frameData) {
  425. if (initialization) {
  426. const options = {
  427. insertSingleFileComment: false,
  428. insertFaviconLink: false,
  429. url: frameData.baseURI,
  430. windowId: frameWindowId,
  431. removeHiddenElements: this.options.removeHiddenElements,
  432. removeUnusedCSSRules: this.options.removeUnusedCSSRules,
  433. jsEnabled: this.options.jsEnabled,
  434. removeScripts: this.options.removeScripts,
  435. saveRawPage: this.options.saveRawPage,
  436. compressHTML: this.options.compressHTML,
  437. compressCSS: this.options.compressCSS,
  438. lazyLoadImages: this.options.lazyLoadImages,
  439. framesData: this.options.framesData
  440. };
  441. if (frameData.content) {
  442. frameData.processor = new PageProcessor(options);
  443. frameData.frameElement = frameElement;
  444. await frameData.processor.loadPage(frameData.content);
  445. return frameData.processor.initialize();
  446. }
  447. } else {
  448. if (frameData.processor) {
  449. const pageData = await frameData.processor.getPageData();
  450. frameElement.setAttribute("src", "data:text/html," + pageData.content);
  451. } else {
  452. frameElement.setAttribute("src", "about:blank");
  453. }
  454. }
  455. } else {
  456. frameElement.setAttribute("src", "about:blank");
  457. }
  458. }));
  459. }
  460. async htmlImports(initialization) {
  461. let linkElements = this.doc.querySelectorAll("link[rel=import][href]");
  462. linkElements = DomUtil.removeNoScriptFrames(linkElements);
  463. if (!this.relImportProcessors) {
  464. this.relImportProcessors = new Map();
  465. }
  466. await Promise.all(linkElements.map(async linkElement => {
  467. if (initialization) {
  468. const resourceURL = linkElement.href;
  469. const options = {
  470. insertSingleFileComment: false,
  471. insertFaviconLink: false,
  472. url: resourceURL,
  473. removeHiddenElements: this.options.removeHiddenElements,
  474. removeUnusedCSSRules: this.options.removeUnusedCSSRules,
  475. jsEnabled: this.options.jsEnabled,
  476. removeScripts: this.options.removeScripts,
  477. saveRawPage: this.options.saveRawPage,
  478. compressHTML: this.options.compressHTML,
  479. compressCSS: this.options.compressCSS,
  480. lazyLoadImages: this.options.lazyLoadImages,
  481. framesData: this.options.framesData
  482. };
  483. if (resourceURL) {
  484. if (resourceURL && resourceURL != this.baseURI && DomUtil.testValidPath(resourceURL)) {
  485. const processor = new PageProcessor(options);
  486. this.relImportProcessors.set(linkElement, processor);
  487. await processor.loadPage();
  488. return processor.initialize();
  489. }
  490. }
  491. } else {
  492. const processor = this.relImportProcessors.get(linkElement);
  493. if (processor) {
  494. this.relImportProcessors.delete(linkElement);
  495. const pageData = await processor.getPageData();
  496. linkElement.setAttribute("href", "data:text/html," + pageData.content);
  497. } else {
  498. linkElement.setAttribute("href", "about:blank");
  499. }
  500. }
  501. }));
  502. }
  503. async attributeStyles(initialization) {
  504. await Promise.all(Array.from(this.doc.querySelectorAll("[style]")).map(async element => {
  505. const stylesheetContent = initialization ? await DomProcessorHelper.resolveImportURLs(element.getAttribute("style"), this.baseURI) : await DomProcessorHelper.processStylesheet(element.getAttribute("style"), this.baseURI);
  506. element.setAttribute("style", stylesheetContent);
  507. }));
  508. }
  509. async linkStylesheets() {
  510. await Promise.all(Array.from(this.doc.querySelectorAll("link[rel*=stylesheet]")).map(async linkElement => {
  511. const stylesheetContent = await DomProcessorHelper.resolveLinkStylesheetURLs(linkElement.href, this.baseURI, linkElement.media);
  512. const styleElement = this.doc.createElement("style");
  513. styleElement.textContent = this.options.compressCSS ? this.dom.uglifycss(stylesheetContent) : stylesheetContent;
  514. linkElement.parentElement.replaceChild(styleElement, linkElement);
  515. }));
  516. }
  517. }
  518. // ---------
  519. // DomHelper
  520. // ---------
  521. class DomProcessorHelper {
  522. static isolateElement(parentElement, element) {
  523. Array.from(parentElement.childNodes).forEach(node => {
  524. if (node == element) {
  525. node.removeAttribute("style");
  526. node.style.all = "unset";
  527. } else {
  528. if (node.tagName != "HEAD" && node.tagName != "STYLE") {
  529. node.remove();
  530. }
  531. }
  532. });
  533. element = element.parentElement;
  534. if (element.parentElement) {
  535. DomProcessorHelper.isolateElement(element.parentElement, element);
  536. }
  537. }
  538. static async resolveImportURLs(stylesheetContent, baseURI) {
  539. stylesheetContent = DomUtil.removeCssComments(stylesheetContent);
  540. const imports = DomUtil.getImportFunctions(stylesheetContent);
  541. await Promise.all(imports.map(async cssImport => {
  542. const match = DomUtil.matchImport(cssImport);
  543. if (match) {
  544. const resourceURL = DomUtil.normalizeURL(match.resourceURL);
  545. if (resourceURL != baseURI && resourceURL != ABOUT_BLANK_URI) {
  546. let importedStylesheetContent = await Download.getContent(new URL(match.resourceURL, baseURI).href);
  547. importedStylesheetContent = DomUtil.wrapMediaQuery(importedStylesheetContent, match.media);
  548. if (stylesheetContent.indexOf(cssImport) != -1) {
  549. stylesheetContent = stylesheetContent.replace(cssImport, importedStylesheetContent);
  550. }
  551. }
  552. }
  553. }));
  554. stylesheetContent = DomProcessorHelper.resolveStylesheetURLs(stylesheetContent, baseURI);
  555. if (imports.length) {
  556. return await DomProcessorHelper.resolveImportURLs(stylesheetContent, baseURI);
  557. } else {
  558. return stylesheetContent;
  559. }
  560. }
  561. static resolveStylesheetURLs(stylesheetContent, baseURI) {
  562. const urlFunctions = DomUtil.getUrlFunctions(stylesheetContent);
  563. urlFunctions.map(urlFunction => {
  564. let resourceURL = DomUtil.matchURL(urlFunction);
  565. resourceURL = DomUtil.normalizeURL(resourceURL);
  566. if (resourceURL && resourceURL != baseURI && DomUtil.testValidPath(resourceURL)) {
  567. stylesheetContent = stylesheetContent.replace(urlFunction, urlFunction.replace(resourceURL, new URL(resourceURL, baseURI).href));
  568. }
  569. });
  570. return stylesheetContent;
  571. }
  572. static async resolveLinkStylesheetURLs(resourceURL, baseURI, media) {
  573. resourceURL = DomUtil.normalizeURL(resourceURL);
  574. if (resourceURL && resourceURL != baseURI && resourceURL != ABOUT_BLANK_URI) {
  575. let stylesheetContent = await Download.getContent(resourceURL);
  576. stylesheetContent = await DomProcessorHelper.resolveImportURLs(stylesheetContent, resourceURL);
  577. stylesheetContent = DomUtil.wrapMediaQuery(stylesheetContent, media);
  578. return stylesheetContent;
  579. }
  580. }
  581. static async processStylesheet(stylesheetContent, baseURI) {
  582. const urlFunctions = DomUtil.getUrlFunctions(stylesheetContent);
  583. await Promise.all(urlFunctions.map(async urlFunction => {
  584. let resourceURL = DomUtil.matchURL(urlFunction);
  585. resourceURL = DomUtil.normalizeURL(resourceURL);
  586. if (resourceURL && resourceURL != baseURI && DomUtil.testValidPath(resourceURL)) {
  587. const dataURI = await batchRequest.addURL(resourceURL);
  588. stylesheetContent = stylesheetContent.replace(urlFunction, urlFunction.replace(resourceURL, dataURI));
  589. }
  590. }));
  591. return stylesheetContent;
  592. }
  593. static async processAttribute(resourceElements, attributeName, baseURI) {
  594. await Promise.all(Array.from(resourceElements).map(async resourceElement => {
  595. let resourceURL = resourceElement.getAttribute(attributeName);
  596. if (resourceURL) {
  597. resourceURL = DomUtil.normalizeURL(resourceURL);
  598. if (resourceURL && resourceURL != baseURI && DomUtil.testValidPath(resourceURL)) {
  599. try {
  600. const dataURI = await batchRequest.addURL(new URL(resourceURL, baseURI).href);
  601. resourceElement.setAttribute(attributeName, dataURI);
  602. } catch (e) {
  603. // ignored
  604. }
  605. }
  606. }
  607. }));
  608. }
  609. static async processSrcset(resourceElements, baseURI, dom) {
  610. await Promise.all(Array.from(resourceElements).map(async resourceElement => {
  611. const srcset = dom.parseSrcset(resourceElement.getAttribute("srcset"));
  612. const srcsetValues = await Promise.all(srcset.map(async srcsetValue => {
  613. const resourceURL = DomUtil.normalizeURL(srcsetValue.url);
  614. if (resourceURL && resourceURL != baseURI && DomUtil.testValidPath(resourceURL)) {
  615. try {
  616. const dataURI = await batchRequest.addURL(new URL(resourceURL, baseURI).href);
  617. return dataURI + (srcsetValue.w ? " " + srcsetValue.w + "w" : srcsetValue.d ? " " + srcsetValue.d + "x" : "");
  618. } catch (e) {
  619. // ignored
  620. }
  621. }
  622. }));
  623. resourceElement.setAttribute("srcset", srcsetValues.join(","));
  624. }));
  625. }
  626. }
  627. // -------
  628. // DomUtil
  629. // -------
  630. const DATA_URI_PREFIX = "data:";
  631. const BLOB_URI_PREFIX = "blob:";
  632. const ABOUT_BLANK_URI = "about:blank";
  633. const REGEXP_URL_FN = /(url\s*\(\s*'([^']*)'\s*\))|(url\s*\(\s*"([^"]*)"\s*\))|(url\s*\(\s*([^)]*)\s*\))/gi;
  634. const REGEXP_URL_SIMPLE_QUOTES_FN = /^url\s*\(\s*'([^']*)'\s*\)$/i;
  635. const REGEXP_URL_DOUBLE_QUOTES_FN = /^url\s*\(\s*"([^"]*)"\s*\)$/i;
  636. const REGEXP_URL_NO_QUOTES_FN = /^url\s*\(\s*([^)]*)\s*\)$/i;
  637. 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*([^;]*);?)|(@import\s*"([^"]*)"\s*([^;]*);?)|(@import\s*([^;]*)\s*([^;]*);?)/gi;
  638. const REGEXP_IMPORT_URL_SIMPLE_QUOTES_FN = /@import\s*url\s*\(\s*'([^']*)'\s*\)\s*([^;]*)/i;
  639. const REGEXP_IMPORT_URL_DOUBLE_QUOTES_FN = /@import\s*url\s*\(\s*"([^"]*)"\s*\)\s*([^;]*)/i;
  640. const REGEXP_IMPORT_URL_NO_QUOTES_FN = /@import\s*url\s*\(\s*([^)]*)\s*\)\s*([^;]*)/i;
  641. const REGEXP_IMPORT_SIMPLE_QUOTES_FN = /@import\s*'([^']*)'\s*([^;]*)/i;
  642. const REGEXP_IMPORT_DOUBLE_QUOTES_FN = /@import\s*"([^"]*)"\s*([^;]*)/i;
  643. const REGEXP_IMPORT_NO_QUOTES_FN = /@import\s*([^;]*)\s*([^;]*)/i;
  644. class DomUtil {
  645. static normalizeURL(url) {
  646. return url.split("#")[0];
  647. }
  648. static getUrlFunctions(stylesheetContent) {
  649. return stylesheetContent.match(REGEXP_URL_FN) || [];
  650. }
  651. static getImportFunctions(stylesheetContent) {
  652. return stylesheetContent.match(REGEXP_IMPORT_FN) || [];
  653. }
  654. static matchURL(stylesheetContent) {
  655. const match = stylesheetContent.match(REGEXP_URL_SIMPLE_QUOTES_FN) ||
  656. stylesheetContent.match(REGEXP_URL_DOUBLE_QUOTES_FN) ||
  657. stylesheetContent.match(REGEXP_URL_NO_QUOTES_FN);
  658. return match && match[1];
  659. }
  660. static testValidPath(resourceURL) {
  661. return !resourceURL.startsWith(DATA_URI_PREFIX) && !resourceURL.startsWith(BLOB_URI_PREFIX) && resourceURL != ABOUT_BLANK_URI;
  662. }
  663. static matchImport(stylesheetContent) {
  664. const match = stylesheetContent.match(REGEXP_IMPORT_URL_SIMPLE_QUOTES_FN) ||
  665. stylesheetContent.match(REGEXP_IMPORT_URL_DOUBLE_QUOTES_FN) ||
  666. stylesheetContent.match(REGEXP_IMPORT_URL_NO_QUOTES_FN) ||
  667. stylesheetContent.match(REGEXP_IMPORT_SIMPLE_QUOTES_FN) ||
  668. stylesheetContent.match(REGEXP_IMPORT_DOUBLE_QUOTES_FN) ||
  669. stylesheetContent.match(REGEXP_IMPORT_NO_QUOTES_FN);
  670. if (match) {
  671. const [, resourceURL, media] = match;
  672. return { resourceURL, media };
  673. }
  674. }
  675. static removeCssComments(stylesheetContent) {
  676. let start, end;
  677. do {
  678. start = stylesheetContent.indexOf("/*");
  679. end = stylesheetContent.indexOf("*/", start);
  680. if (start != -1 && end != -1) {
  681. stylesheetContent = stylesheetContent.substring(0, start) + stylesheetContent.substr(end + 2);
  682. }
  683. } while (start != -1 && end != -1);
  684. return stylesheetContent;
  685. }
  686. static wrapMediaQuery(stylesheetContent, mediaQuery) {
  687. if (mediaQuery) {
  688. return "@media " + mediaQuery + "{ " + stylesheetContent + " }";
  689. } else {
  690. return stylesheetContent;
  691. }
  692. }
  693. static removeNoScriptFrames(frameElements) {
  694. return Array.from(frameElements).filter(element => {
  695. element = element.parentElement;
  696. while (element && element.tagName != "NOSCRIPT") {
  697. element = element.parentElement;
  698. }
  699. return !element;
  700. });
  701. }
  702. }
  703. return SingleFileCore;
  704. })();
  705. if (typeof module != "undefined") {
  706. module.exports = SingleFileCore;
  707. }