single-file-core.js 32 KB

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