single-file-core.js 33 KB

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