single-file-core.js 32 KB

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