single-file-core.js 31 KB

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