single-file-core.js 41 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067
  1. /*
  2. * Copyright 2018 Gildas Lormeau
  3. * contact : gildas.lormeau <at> gmail.com
  4. *
  5. * This file is part of SingleFile.
  6. *
  7. * SingleFile is free software: you can redistribute it and/or modify
  8. * it under the terms of the GNU Lesser General Public License as published by
  9. * the Free Software Foundation, either version 3 of the License, or
  10. * (at your option) any later version.
  11. *
  12. * SingleFile is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. * GNU Lesser General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU Lesser General Public License
  18. * along with SingleFile. If not, see <http://www.gnu.org/licenses/>.
  19. */
  20. this.SingleFileCore = this.SingleFileCore || (() => {
  21. const SELECTED_CONTENT_ATTRIBUTE_NAME = "data-single-file-selected-content";
  22. const SELECTED_CONTENT_ROOT_ATTRIBUTE_NAME = "data-single-file-selected-content-root";
  23. let Download, DOM, URL, sessionId = 0;
  24. function getClass(...args) {
  25. [Download, DOM, URL] = args;
  26. return class {
  27. constructor(options) {
  28. this.options = options;
  29. options.sessionId = sessionId;
  30. sessionId++;
  31. this.SELECTED_CONTENT_ATTRIBUTE_NAME = SELECTED_CONTENT_ATTRIBUTE_NAME;
  32. this.SELECTED_CONTENT_ROOT_ATTRIBUTE_NAME = SELECTED_CONTENT_ROOT_ATTRIBUTE_NAME;
  33. }
  34. async initialize() {
  35. this.processor = new PageProcessor(this.options);
  36. await this.processor.loadPage();
  37. await this.processor.initialize();
  38. }
  39. async preparePageData() {
  40. await this.processor.preparePageData();
  41. }
  42. getPageData() {
  43. return this.processor.getPageData();
  44. }
  45. };
  46. }
  47. // -------------
  48. // ProgressEvent
  49. // -------------
  50. const PAGE_LOADING = "page-loading";
  51. const PAGE_LOADED = "page-loaded";
  52. const RESOURCES_INITIALIZING = "resource-initializing";
  53. const RESOURCES_INITIALIZED = "resources-initialized";
  54. const RESOURCE_LOADED = "resource-loaded";
  55. const PAGE_ENDED = "page-ended";
  56. class ProgressEvent {
  57. constructor(type, details) {
  58. return { type, details, PAGE_LOADING, PAGE_LOADED, RESOURCES_INITIALIZING, RESOURCES_INITIALIZED, RESOURCE_LOADED, PAGE_ENDED };
  59. }
  60. }
  61. // -------------
  62. // PageProcessor
  63. // -------------
  64. const STAGES = [{
  65. sync: [
  66. { action: "removeUIElements" },
  67. { action: "replaceStyleContents" },
  68. { option: "removeSrcSet", action: "removeSrcSet" },
  69. { option: "removeFrames", action: "removeFrames" },
  70. { option: "removeImports", action: "removeImports" },
  71. { option: "removeScripts", action: "removeScripts" },
  72. { action: "removeDiscardedResources" },
  73. { action: "resetCharsetMeta" },
  74. { action: "setInputValues" },
  75. { option: "compressHTML", action: "compressHTML" },
  76. { option: "insertFaviconLink", action: "insertFaviconLink" },
  77. { action: "resolveHrefs" },
  78. { action: "replaceCanvasElements" },
  79. { option: "removeHiddenElements", action: "removeHiddenElements" }
  80. ],
  81. async: [
  82. { action: "inlineStylesheets" },
  83. { action: "linkStylesheets" },
  84. { action: "attributeStyles" },
  85. { option: "!removeFrames", action: "frames" },
  86. { option: "!removeImports", action: "htmlImports" }
  87. ]
  88. }, {
  89. sync: [
  90. { option: "removeUnusedStyles", action: "removeUnusedStyles" },
  91. { option: "compressHTML", action: "compressHTML" },
  92. { option: "removeAlternativeFonts", action: "removeAlternativeFonts" },
  93. { option: "compressCSS", action: "compressCSS" },
  94. ],
  95. async: [
  96. { action: "inlineStylesheets" },
  97. { action: "attributeStyles" },
  98. { action: "pageResources" },
  99. { option: "!removeScripts", action: "scripts" }
  100. ]
  101. }, {
  102. sync: [
  103. { option: "lazyLoadImages", action: "lazyLoadImages" },
  104. { option: "removeAlternativeFonts", action: "postRemoveAlternativeFonts" }
  105. ],
  106. async: [
  107. { option: "!removeFrames", action: "frames" },
  108. { option: "!removeImports", action: "htmlImports" },
  109. ]
  110. }, {
  111. sync: [
  112. { option: "compressHTML", action: "postCompressHTML" },
  113. { option: "insertSingleFileComment", action: "insertSingleFileComment" },
  114. { action: "removeDefaultHeadTags" }
  115. ]
  116. }];
  117. class PageProcessor {
  118. constructor(options) {
  119. this.options = options;
  120. this.options.url = this.options.url || this.options.doc.location.href;
  121. this.processor = new DOMProcessor(options);
  122. if (this.options.doc) {
  123. const docData = DOM.preProcessDoc(this.options.doc, this.options.win, this.options);
  124. this.options.canvasData = docData.canvasData;
  125. this.options.stylesheetContents = docData.stylesheetContents;
  126. this.options.imageData = docData.imageData;
  127. }
  128. this.options.content = this.options.content || (this.options.doc ? DOM.serialize(this.options.doc, false) : null);
  129. this.onprogress = options.onprogress || (() => { });
  130. }
  131. async loadPage() {
  132. this.onprogress(new ProgressEvent(PAGE_LOADING, { pageURL: this.options.url }));
  133. await this.processor.loadPage(this.options.content);
  134. this.onprogress(new ProgressEvent(PAGE_LOADED, { pageURL: this.options.url }));
  135. }
  136. async initialize() {
  137. this.onprogress(new ProgressEvent(RESOURCES_INITIALIZING, { pageURL: this.options.url }));
  138. await this.executeStage(0);
  139. this.pendingPromises = this.executeStage(1);
  140. if (this.options.doc) {
  141. DOM.postProcessDoc(this.options.doc, this.options);
  142. this.options.doc = null;
  143. this.options.win = null;
  144. }
  145. this.onprogress(new ProgressEvent(RESOURCES_INITIALIZED, { pageURL: this.options.url, index: 0, max: batchRequest.getMaxResources() }));
  146. }
  147. async preparePageData() {
  148. if (!this.options.windowId) {
  149. await this.processor.retrieveResources(
  150. details => {
  151. details.pageURL = this.options.url;
  152. this.onprogress(new ProgressEvent(RESOURCE_LOADED, details));
  153. });
  154. }
  155. await this.pendingPromises;
  156. await this.executeStage(2);
  157. await this.executeStage(3);
  158. }
  159. getPageData() {
  160. this.onprogress(new ProgressEvent(PAGE_ENDED, { pageURL: this.options.url }));
  161. return this.processor.getPageData();
  162. }
  163. async executeStage(step) {
  164. STAGES[step].sync.forEach(task => this.executeTask(task, !step));
  165. if (STAGES[step].async) {
  166. return Promise.all(STAGES[step].async.map(task => this.executeTask(task, !step)));
  167. }
  168. }
  169. executeTask(task, initialization) {
  170. if (!task.option || ((task.option.startsWith("!") && !this.options[task.option]) || this.options[task.option])) {
  171. return this.processor[task.action](initialization);
  172. }
  173. }
  174. }
  175. // --------
  176. // BatchRequest
  177. // --------
  178. class BatchRequest {
  179. constructor() {
  180. this.requests = new Map();
  181. }
  182. async addURL(resourceURL, asDataURI = true) {
  183. return new Promise((resolve, reject) => {
  184. const requestKey = JSON.stringify([resourceURL, asDataURI]);
  185. const resourceRequests = this.requests.get(requestKey);
  186. if (resourceRequests) {
  187. resourceRequests.push({ resolve, reject });
  188. } else {
  189. this.requests.set(requestKey, [{ resolve, reject }]);
  190. }
  191. });
  192. }
  193. getMaxResources() {
  194. return Array.from(this.requests.keys()).length;
  195. }
  196. async run(onloadListener, options) {
  197. const resourceURLs = Array.from(this.requests.keys());
  198. let indexResource = 0;
  199. return Promise.all(resourceURLs.map(async requestKey => {
  200. const [resourceURL, asDataURI] = JSON.parse(requestKey);
  201. const resourceRequests = this.requests.get(requestKey);
  202. try {
  203. const dataURI = await Download.getContent(resourceURL, { asDataURI, maxResourceSize: options.maxResourceSize, maxResourceSizeEnabled: options.maxResourceSizeEnabled });
  204. indexResource = indexResource + 1;
  205. onloadListener({ index: indexResource, max: resourceURLs.length, url: resourceURL });
  206. resourceRequests.forEach(resourceRequest => resourceRequest.resolve(dataURI));
  207. } catch (error) {
  208. indexResource = indexResource + 1;
  209. onloadListener({ index: indexResource, max: resourceURLs.length, url: resourceURL });
  210. resourceRequests.forEach(resourceRequest => resourceRequest.reject(error));
  211. }
  212. this.requests.delete(requestKey);
  213. }));
  214. }
  215. }
  216. // ------------
  217. // DOMProcessor
  218. // ------------
  219. const ESCAPED_FRAGMENT = "_escaped_fragment_=";
  220. const EMPTY_DATA_URI = "data:base64,";
  221. const batchRequest = new BatchRequest();
  222. class DOMProcessor {
  223. constructor(options) {
  224. this.options = options;
  225. this.stats = new Stats(options);
  226. this.baseURI = DomUtil.normalizeURL(options.url);
  227. }
  228. async loadPage(pageContent) {
  229. if (!pageContent || this.options.saveRawPage) {
  230. pageContent = await Download.getContent(this.baseURI, { asDataURI: false, maxResourceSize: this.options.maxResourceSize, maxResourceSizeEnabled: this.options.maxResourceSizeEnabled });
  231. }
  232. this.doc = DOM.createDoc(pageContent, this.baseURI);
  233. this.onEventAttributeNames = DOM.getOnEventAttributeNames(this.doc);
  234. if (!pageContent && this.doc.querySelector("meta[name=fragment][content=\"!\"]") && !this.baseURI.endsWith("?" + ESCAPED_FRAGMENT) && !this.baseURI.endsWith("&" + ESCAPED_FRAGMENT)) {
  235. await DOMProcessor.loadEscapedFragmentPage();
  236. }
  237. }
  238. async loadEscapedFragmentPage() {
  239. if (this.baseURI.includes("?")) {
  240. this.baseURI += "&";
  241. } else {
  242. this.baseURI += "?";
  243. }
  244. this.baseURI += ESCAPED_FRAGMENT;
  245. await this.loadPage();
  246. }
  247. async retrieveResources(onloadListener) {
  248. this.stats.set("processed", "resources", batchRequest.getMaxResources());
  249. await batchRequest.run(onloadListener, this.options);
  250. }
  251. getPageData() {
  252. DOM.postProcessDoc(this.doc, this.options);
  253. if (this.options.selected) {
  254. const rootElement = this.doc.querySelector("[" + SELECTED_CONTENT_ROOT_ATTRIBUTE_NAME + "]");
  255. if (rootElement) {
  256. DomProcessorHelper.isolateElements(rootElement);
  257. rootElement.removeAttribute(SELECTED_CONTENT_ROOT_ATTRIBUTE_NAME);
  258. rootElement.removeAttribute(SELECTED_CONTENT_ATTRIBUTE_NAME);
  259. }
  260. }
  261. const titleElement = this.doc.querySelector("title");
  262. let title;
  263. if (titleElement) {
  264. title = titleElement.textContent.trim();
  265. }
  266. const matchTitle = this.baseURI.match(/([^/]*)\/?(\.html?.*)$/) || this.baseURI.match(/\/\/([^/]*)\/?$/);
  267. const url = new URL(this.baseURI);
  268. let size;
  269. if (this.options.displayStats) {
  270. size = DOM.getContentSize(this.doc.documentElement.outerHTML);
  271. }
  272. const content = DOM.serialize(this.doc, this.options.compressHTML);
  273. if (this.options.displayStats) {
  274. const contentSize = DOM.getContentSize(content);
  275. this.stats.set("processed", "htmlBytes", contentSize);
  276. this.stats.add("discarded", "htmlBytes", size - contentSize);
  277. }
  278. return {
  279. stats: this.stats.data,
  280. title: title || (this.baseURI && matchTitle ? matchTitle[1] : (url.hostname ? url.hostname : "Untitled page")),
  281. content
  282. };
  283. }
  284. setInputValues() {
  285. this.doc.querySelectorAll("input").forEach(input => {
  286. const value = input.getAttribute(DOM.inputValueAttributeName(this.options.sessionId));
  287. if (value) {
  288. input.setAttribute("value", value);
  289. }
  290. });
  291. this.doc.querySelectorAll("textarea").forEach(textarea => {
  292. const value = textarea.getAttribute(DOM.inputValueAttributeName(this.options.sessionId));
  293. if (value) {
  294. textarea.textContent = value;
  295. }
  296. });
  297. this.doc.querySelectorAll("select").forEach(select => {
  298. select.querySelectorAll("option").forEach(option => {
  299. const selected = option.getAttribute(DOM.inputValueAttributeName(this.options.sessionId)) !== undefined;
  300. if (selected) {
  301. option.setAttribute("selected", "");
  302. }
  303. });
  304. });
  305. }
  306. lazyLoadImages() {
  307. DOM.lazyLoad(this.doc);
  308. }
  309. removeDiscardedResources() {
  310. 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\"])");
  311. this.stats.set("discarded", "objects", objectElements.length);
  312. objectElements.forEach(element => element.remove());
  313. const replacedAttributeValue = this.doc.querySelectorAll("link[rel~=preconnect], link[rel~=prerender], link[rel~=dns-prefetch], link[rel~=preload], link[rel~=prefetch]");
  314. replacedAttributeValue.forEach(element => {
  315. const relValue = element.getAttribute("rel").replace(/(preconnect|prerender|dns-prefetch|preload|prefetch)/g, "").trim();
  316. if (relValue.length) {
  317. element.setAttribute("rel", relValue);
  318. } else {
  319. element.remove();
  320. }
  321. });
  322. this.doc.querySelectorAll("meta[http-equiv=\"content-security-policy\"").forEach(element => element.remove());
  323. this.doc.querySelectorAll("a[ping]").forEach(element => element.removeAttribute("ping"));
  324. if (this.options.removeScripts) {
  325. this.onEventAttributeNames.forEach(attributeName => this.doc.querySelectorAll("[" + attributeName + "]").forEach(element => element.removeAttribute(attributeName)));
  326. this.doc.querySelectorAll("[href]").forEach(element => {
  327. if (element.href && element.href.match(/^\s*javascript:/)) {
  328. element.removeAttribute("href");
  329. }
  330. });
  331. this.doc.querySelectorAll("[src]").forEach(element => {
  332. if (element.src && element.src.match(/^\s*javascript:/)) {
  333. element.removeAttribute("src");
  334. }
  335. });
  336. }
  337. if (this.options.removeAudioSrc) {
  338. const audioSourceElements = this.doc.querySelectorAll("audio[src], audio > source[src]");
  339. this.stats.set("discarded", "audioSource", audioSourceElements.length);
  340. audioSourceElements.forEach(element => element.removeAttribute("src"));
  341. }
  342. if (this.options.removeVideoSrc) {
  343. const videoSourceElements = this.doc.querySelectorAll("video[src], video > source[src]");
  344. this.stats.set("discarded", "videoSource", videoSourceElements.length);
  345. videoSourceElements.forEach(element => element.removeAttribute("src"));
  346. }
  347. }
  348. removeDefaultHeadTags() {
  349. this.doc.querySelectorAll("base").forEach(element => element.remove());
  350. if (this.doc.head.querySelectorAll("*").length == 1 && this.doc.head.querySelector("meta[charset]") && this.doc.body.childNodes.length == 0) {
  351. this.doc.head.querySelector("meta[charset]").remove();
  352. }
  353. }
  354. removeUIElements() {
  355. this.doc.querySelectorAll("singlefile-infobar, singlefile-mask").forEach(element => element.remove());
  356. }
  357. removeScripts() {
  358. const scriptElements = this.doc.querySelectorAll("script:not([type=\"application/ld+json\"])");
  359. this.stats.set("discarded", "scripts", scriptElements.length);
  360. scriptElements.forEach(element => element.remove());
  361. }
  362. removeFrames() {
  363. const frameElements = this.doc.querySelectorAll("iframe, frame, object[type=\"text/html\"][data]");
  364. this.stats.set("discarded", "frames", frameElements.length);
  365. this.doc.querySelectorAll("iframe, frame, object[type=\"text/html\"][data]").forEach(element => element.remove());
  366. }
  367. removeImports() {
  368. const importElements = this.doc.querySelectorAll("link[rel=import]");
  369. this.stats.set("discarded", "imports", importElements.length);
  370. importElements.forEach(element => element.remove());
  371. }
  372. resetCharsetMeta() {
  373. this.doc.querySelectorAll("meta[charset], meta[http-equiv=\"content-type\"]").forEach(element => element.remove());
  374. const metaElement = this.doc.createElement("meta");
  375. metaElement.setAttribute("charset", "utf-8");
  376. this.doc.head.insertBefore(metaElement, this.doc.head.firstElementChild);
  377. }
  378. insertFaviconLink() {
  379. let faviconElement = this.doc.querySelector("link[href][rel=\"icon\"]");
  380. if (!faviconElement) {
  381. faviconElement = this.doc.querySelector("link[href][rel=\"shortcut icon\"]");
  382. }
  383. if (!faviconElement) {
  384. faviconElement = this.doc.createElement("link");
  385. faviconElement.setAttribute("type", "image/x-icon");
  386. faviconElement.setAttribute("rel", "shortcut icon");
  387. faviconElement.setAttribute("href", "/favicon.ico");
  388. }
  389. this.doc.head.appendChild(faviconElement);
  390. }
  391. resolveHrefs() {
  392. this.doc.querySelectorAll("[href]").forEach(element => {
  393. if (element.href) {
  394. const href = element.href.baseVal ? element.href.baseVal : element.href;
  395. const match = href.match(/(.*)#.*$/);
  396. if (!match || match[1] != this.baseURI) {
  397. element.setAttribute("href", href);
  398. }
  399. }
  400. });
  401. }
  402. removeUnusedStyles() {
  403. const stats = DOM.minifyCSS(this.doc);
  404. this.stats.set("processed", "cssRules", stats.processed);
  405. this.stats.set("discarded", "cssRules", stats.discarded);
  406. }
  407. removeAlternativeFonts() {
  408. DOM.minifyFonts(this.doc);
  409. }
  410. removeSrcSet() {
  411. this.doc.querySelectorAll("picture, img[srcset]").forEach(element => {
  412. const tagName = element.tagName.toLowerCase();
  413. const dataAttributeName = DOM.responsiveImagesAttributeName(this.options.sessionId);
  414. const imageData = this.options.imageData[Number(element.getAttribute(dataAttributeName))];
  415. element.removeAttribute(dataAttributeName);
  416. if (imageData) {
  417. if (tagName == "img") {
  418. if (imageData.source.src && imageData.source.naturalWidth > 1 && imageData.source.naturalHeight > 1) {
  419. element.removeAttribute("srcset");
  420. element.removeAttribute("sizes");
  421. element.src = imageData.source.src;
  422. }
  423. }
  424. if (tagName == "picture") {
  425. const imageElement = element.querySelector("img");
  426. if (imageData.source.src && imageData.source.naturalWidth > 1 && imageData.source.naturalHeight > 1) {
  427. imageElement.removeAttribute("srcset");
  428. imageElement.removeAttribute("sizes");
  429. imageElement.src = imageData.source.src;
  430. element.querySelectorAll("source").forEach(sourceElement => sourceElement.remove());
  431. } else {
  432. if (imageData.sources) {
  433. element.querySelectorAll("source").forEach(sourceElement => {
  434. if (!sourceElement.srcset && !sourceElement.dataset.srcset && !sourceElement.src) {
  435. sourceElement.remove();
  436. }
  437. });
  438. const sourceElements = element.querySelectorAll("source");
  439. if (sourceElements.length) {
  440. const lastSourceElement = sourceElements[sourceElements.length - 1];
  441. if (lastSourceElement.src) {
  442. imageElement.src = lastSourceElement.src;
  443. } else {
  444. imageElement.removeAttribute("src");
  445. }
  446. if (lastSourceElement.srcset || lastSourceElement.dataset.srcset) {
  447. imageElement.srcset = lastSourceElement.srcset || lastSourceElement.dataset.srcset;
  448. } else {
  449. imageElement.removeAttribute("srcset");
  450. }
  451. element.querySelectorAll("source").forEach(sourceElement => sourceElement.remove());
  452. }
  453. }
  454. }
  455. }
  456. }
  457. });
  458. }
  459. postRemoveAlternativeFonts() {
  460. DOM.minifyFonts(this.doc, true);
  461. if (this.options.compressCSS) {
  462. this.compressCSS();
  463. }
  464. }
  465. removeHiddenElements() {
  466. const hiddenElements = this.doc.querySelectorAll("[" + DOM.removedContentAttributeName(this.options.sessionId) + "]");
  467. this.stats.set("discarded", "hiddenElements", hiddenElements.length);
  468. hiddenElements.forEach(element => element.remove());
  469. }
  470. compressHTML() {
  471. let size;
  472. if (this.options.displayStats) {
  473. size = DOM.getContentSize(this.doc.documentElement.outerHTML);
  474. }
  475. DOM.minifyHTML(this.doc, { preservedSpaceAttributeName: DOM.preservedSpaceAttributeName(this.options.sessionId) });
  476. if (this.options.displayStats) {
  477. this.stats.add("discarded", "htmlBytes", size - DOM.getContentSize(this.doc.documentElement.outerHTML));
  478. }
  479. }
  480. postCompressHTML() {
  481. let size;
  482. if (this.options.displayStats) {
  483. size = DOM.getContentSize(this.doc.documentElement.outerHTML);
  484. }
  485. DOM.postMinifyHTML(this.doc);
  486. if (this.options.displayStats) {
  487. this.stats.add("discarded", "htmlBytes", size - DOM.getContentSize(this.doc.documentElement.outerHTML));
  488. }
  489. }
  490. compressCSS() {
  491. this.doc.querySelectorAll("style").forEach(styleElement => {
  492. if (styleElement) {
  493. styleElement.textContent = DOM.compressCSS(styleElement.textContent);
  494. }
  495. });
  496. this.doc.querySelectorAll("[style]").forEach(element => {
  497. element.setAttribute("style", DOM.compressCSS(element.getAttribute("style")));
  498. });
  499. }
  500. insertSingleFileComment() {
  501. const commentNode = this.doc.createComment("\n Archive processed by SingleFile \n url: " + this.baseURI + " \n saved date: " + new Date() + " \n");
  502. this.doc.documentElement.insertBefore(commentNode, this.doc.documentElement.firstChild);
  503. }
  504. replaceCanvasElements() {
  505. if (this.options.canvasData) {
  506. this.doc.querySelectorAll("canvas").forEach((canvasElement, indexCanvasElement) => {
  507. const canvasData = this.options.canvasData[indexCanvasElement];
  508. if (canvasData) {
  509. const imgElement = this.doc.createElement("img");
  510. imgElement.setAttribute("src", canvasData.dataURI);
  511. Array.from(canvasElement.attributes).forEach(attribute => {
  512. if (attribute.value) {
  513. imgElement.setAttribute(attribute.name, attribute.value);
  514. }
  515. });
  516. if (!imgElement.width && canvasData.width) {
  517. imgElement.style.pixelWidth = canvasData.width;
  518. }
  519. if (!imgElement.height && canvasData.height) {
  520. imgElement.style.pixelHeight = canvasData.height;
  521. }
  522. canvasElement.parentElement.replaceChild(imgElement, canvasElement);
  523. this.stats.add("processed", "canvas", 1);
  524. }
  525. });
  526. }
  527. }
  528. replaceStyleContents() {
  529. if (this.options.stylesheetContents) {
  530. this.doc.querySelectorAll("style").forEach((styleElement, styleIndex) => {
  531. if (this.options.stylesheetContents[styleIndex]) {
  532. styleElement.textContent = this.options.stylesheetContents[styleIndex];
  533. }
  534. });
  535. }
  536. }
  537. async pageResources() {
  538. const resourcePromises = [
  539. DomProcessorHelper.processAttribute(this.doc.querySelectorAll("link[href][rel*=\"icon\"]"), "href", this.baseURI),
  540. DomProcessorHelper.processAttribute(this.doc.querySelectorAll("object[type=\"image/svg+xml\"], object[type=\"image/svg-xml\"]"), "data", this.baseURI),
  541. DomProcessorHelper.processAttribute(this.doc.querySelectorAll("img[src], input[src][type=image], embed[src*=\".svg\"]"), "src", this.baseURI),
  542. DomProcessorHelper.processAttribute(this.doc.querySelectorAll("video[poster]"), "poster", this.baseURI),
  543. DomProcessorHelper.processAttribute(this.doc.querySelectorAll("*[background]"), "background", this.baseURI),
  544. DomProcessorHelper.processAttribute(this.doc.querySelectorAll("image"), "xlink:href", this.baseURI),
  545. DomProcessorHelper.processXLinks(this.doc.querySelectorAll("use"), this.baseURI),
  546. DomProcessorHelper.processSrcset(this.doc.querySelectorAll("[srcset]"), "srcset", this.baseURI)
  547. ];
  548. if (!this.options.removeAudioSrc) {
  549. resourcePromises.push(DomProcessorHelper.processAttribute(this.doc.querySelectorAll("audio[src], audio > source[src]"), "src", this.baseURI));
  550. }
  551. if (!this.options.removeVideoSrc) {
  552. resourcePromises.push(DomProcessorHelper.processAttribute(this.doc.querySelectorAll("video[src], video > source[src]"), "src", this.baseURI));
  553. }
  554. if (this.options.lazyLoadImages) {
  555. const imageSelectors = DOM.lazyLoaderImageSelectors();
  556. Object.keys(imageSelectors.src).forEach(selector => resourcePromises.push(DomProcessorHelper.processAttribute(this.doc.querySelectorAll(selector), imageSelectors.src[selector], this.baseURI)));
  557. Object.keys(imageSelectors.srcset).forEach(selector => resourcePromises.push(DomProcessorHelper.processSrcset(this.doc.querySelectorAll(selector), imageSelectors.srcset[selector], this.baseURI)));
  558. }
  559. await resourcePromises;
  560. }
  561. async inlineStylesheets(initialization) {
  562. await Promise.all(Array.from(this.doc.querySelectorAll("style")).map(async styleElement => {
  563. if (!initialization) {
  564. this.stats.add("processed", "styleSheets", 1);
  565. }
  566. let stylesheetContent = styleElement.textContent;
  567. if (initialization) {
  568. stylesheetContent = await DomProcessorHelper.resolveImportURLs(styleElement.textContent, this.baseURI, { maxResourceSize: this.options.maxResourceSize, maxResourceSizeEnabled: this.options.maxResourceSizeEnabled });
  569. } else {
  570. stylesheetContent = await DomProcessorHelper.processStylesheet(styleElement.textContent, this.baseURI);
  571. }
  572. styleElement.textContent = stylesheetContent;
  573. }));
  574. }
  575. async scripts() {
  576. await Promise.all(Array.from(this.doc.querySelectorAll("script[src]")).map(async scriptElement => {
  577. if (scriptElement.src) {
  578. this.stats.add("processed", "scripts", 1);
  579. const scriptContent = await Download.getContent(scriptElement.src, { asDataURI: false, maxResourceSize: this.options.maxResourceSize, maxResourceSizeEnabled: this.options.maxResourceSizeEnabled });
  580. scriptElement.textContent = scriptContent.replace(/<\/script>/gi, "<\\/script>");
  581. }
  582. scriptElement.removeAttribute("src");
  583. }));
  584. }
  585. async frames(initialization) {
  586. if (this.options.framesData) {
  587. const frameElements = Array.from(this.doc.querySelectorAll("iframe, frame, object[type=\"text/html\"][data]"));
  588. await Promise.all(frameElements.map(async frameElement => {
  589. DomProcessorHelper.setFrameEmptySrc(frameElement);
  590. frameElement.setAttribute("sandbox", "allow-scripts allow-same-origin");
  591. const frameWindowId = frameElement.getAttribute(DOM.windowIdAttributeName(this.options.sessionId));
  592. if (frameWindowId) {
  593. const frameData = this.options.framesData.find(frame => frame.windowId == frameWindowId);
  594. if (frameData) {
  595. if (initialization) {
  596. const options = Object.create(this.options);
  597. options.insertSingleFileComment = false;
  598. options.insertFaviconLink = false;
  599. options.doc = null;
  600. options.win = null;
  601. options.url = frameData.baseURI;
  602. options.windowId = frameWindowId;
  603. if (frameData.content) {
  604. options.content = frameData.content;
  605. options.canvasData = frameData.canvasData;
  606. options.stylesheetContents = frameData.stylesheetContents;
  607. options.currentSrcImages = frameData.currentSrcImages;
  608. frameData.processor = new PageProcessor(options);
  609. frameData.frameElement = frameElement;
  610. await frameData.processor.loadPage();
  611. return frameData.processor.initialize();
  612. }
  613. } else {
  614. if (frameData.processor) {
  615. this.stats.add("processed", "frames", 1);
  616. await frameData.processor.preparePageData();
  617. const pageData = await frameData.processor.getPageData();
  618. frameElement.removeAttribute(DOM.windowIdAttributeName(this.options.sessionId));
  619. DomProcessorHelper.setFrameContent(frameElement, pageData.content);
  620. this.stats.addAll(pageData);
  621. } else {
  622. this.stats.add("discarded", "frames", 1);
  623. }
  624. }
  625. }
  626. }
  627. }));
  628. }
  629. }
  630. async htmlImports(initialization) {
  631. const linkElements = Array.from(this.doc.querySelectorAll("link[rel=import][href]"));
  632. if (!this.relImportProcessors) {
  633. this.relImportProcessors = new Map();
  634. }
  635. await Promise.all(linkElements.map(async linkElement => {
  636. if (initialization) {
  637. const resourceURL = linkElement.href;
  638. const options = Object.create(this.options);
  639. options.insertSingleFileComment = false;
  640. options.insertFaviconLink = false;
  641. options.doc = null;
  642. options.win = null;
  643. options.url = resourceURL;
  644. if (resourceURL) {
  645. if (resourceURL && resourceURL != this.baseURI && DomUtil.testValidPath(resourceURL)) {
  646. const processor = new PageProcessor(options);
  647. this.relImportProcessors.set(linkElement, processor);
  648. await processor.loadPage();
  649. return processor.initialize();
  650. }
  651. }
  652. } else {
  653. linkElement.setAttribute("href", EMPTY_DATA_URI);
  654. const processor = this.relImportProcessors.get(linkElement);
  655. if (processor) {
  656. this.stats.add("processed", "imports", 1);
  657. this.relImportProcessors.delete(linkElement);
  658. const pageData = await processor.getPageData();
  659. linkElement.setAttribute("href", "data:text/html," + pageData.content);
  660. this.stats.addAll(pageData);
  661. } else {
  662. this.stats.add("discarded", "imports", 1);
  663. }
  664. }
  665. }));
  666. }
  667. async attributeStyles(initialization) {
  668. await Promise.all(Array.from(this.doc.querySelectorAll("[style]")).map(async element => {
  669. let stylesheetContent = element.getAttribute("style");
  670. if (initialization) {
  671. stylesheetContent = DomProcessorHelper.resolveStylesheetURLs(stylesheetContent, this.baseURI);
  672. } else {
  673. stylesheetContent = await DomProcessorHelper.processStylesheet(element.getAttribute("style"), this.baseURI);
  674. }
  675. element.setAttribute("style", stylesheetContent);
  676. }));
  677. }
  678. async linkStylesheets() {
  679. await Promise.all(Array.from(this.doc.querySelectorAll("link[rel*=stylesheet]")).map(async linkElement => {
  680. const stylesheetContent = await DomProcessorHelper.resolveLinkStylesheetURLs(linkElement.href, this.baseURI, linkElement.media, { maxResourceSize: this.options.maxResourceSize, maxResourceSizeEnabled: this.options.maxResourceSizeEnabled });
  681. const styleElement = this.doc.createElement("style");
  682. styleElement.textContent = stylesheetContent;
  683. linkElement.parentElement.replaceChild(styleElement, linkElement);
  684. }));
  685. }
  686. }
  687. // ---------
  688. // DomHelper
  689. // ---------
  690. class DomProcessorHelper {
  691. static setFrameEmptySrc(frameElement) {
  692. if (frameElement.tagName == "OBJECT") {
  693. frameElement.setAttribute("data", "data:text/html,");
  694. } else {
  695. frameElement.setAttribute("srcdoc", "");
  696. frameElement.removeAttribute("src");
  697. }
  698. }
  699. static setFrameContent(frameElement, content) {
  700. if (frameElement.tagName == "OBJECT") {
  701. frameElement.setAttribute("data", "data:text/html," + content);
  702. } else {
  703. frameElement.setAttribute("srcdoc", content);
  704. frameElement.removeAttribute("src");
  705. }
  706. }
  707. static isolateElements(rootElement) {
  708. rootElement.querySelectorAll("*").forEach(element => {
  709. if (element.getAttribute(SELECTED_CONTENT_ATTRIBUTE_NAME) == "") {
  710. element.removeAttribute(SELECTED_CONTENT_ATTRIBUTE_NAME);
  711. } else if (!element.querySelector("[" + SELECTED_CONTENT_ATTRIBUTE_NAME + "]")) {
  712. element.remove();
  713. }
  714. });
  715. isolateParentElements(rootElement.parentElement, rootElement);
  716. function isolateParentElements(parentElement, element) {
  717. if (parentElement) {
  718. Array.from(parentElement.childNodes).forEach(node => {
  719. if (node != element && node.tagName != "HEAD" && node.tagName != "STYLE") {
  720. node.remove();
  721. }
  722. });
  723. }
  724. element = element.parentElement;
  725. if (element && element.parentElement) {
  726. isolateParentElements(element.parentElement, element);
  727. }
  728. }
  729. }
  730. static async resolveImportURLs(stylesheetContent, baseURI, options) {
  731. stylesheetContent = DomProcessorHelper.resolveStylesheetURLs(stylesheetContent, baseURI);
  732. stylesheetContent = DomUtil.removeCssComments(stylesheetContent);
  733. const imports = DomUtil.getImportFunctions(stylesheetContent);
  734. await Promise.all(imports.map(async cssImport => {
  735. const match = DomUtil.matchImport(cssImport);
  736. if (match) {
  737. const resourceURL = DomUtil.normalizeURL(match.resourceURL);
  738. if (resourceURL != baseURI && resourceURL != ABOUT_BLANK_URI) {
  739. const styleSheetUrl = new URL(match.resourceURL, baseURI).href;
  740. let importedStylesheetContent = await Download.getContent(styleSheetUrl, { asDataURI: false, maxResourceSize: options.maxResourceSize, maxResourceSizeEnabled: options.maxResourceSizeEnabled });
  741. importedStylesheetContent = DomUtil.wrapMediaQuery(importedStylesheetContent, match.media);
  742. if (stylesheetContent.includes(cssImport)) {
  743. importedStylesheetContent = await DomProcessorHelper.resolveImportURLs(importedStylesheetContent, styleSheetUrl, options);
  744. stylesheetContent = stylesheetContent.replace(DomUtil.getRegExp(cssImport), importedStylesheetContent);
  745. }
  746. }
  747. }
  748. }));
  749. return stylesheetContent;
  750. }
  751. static resolveStylesheetURLs(stylesheetContent, baseURI) {
  752. const urlFunctions = DomUtil.getUrlFunctions(stylesheetContent);
  753. urlFunctions.map(urlFunction => {
  754. const originalResourceURL = DomUtil.matchURL(urlFunction);
  755. const resourceURL = DomUtil.normalizeURL(originalResourceURL);
  756. if (resourceURL && resourceURL != baseURI && DomUtil.testValidPath(resourceURL)) {
  757. const resolvedURL = new URL(resourceURL, baseURI).href;
  758. if (resourceURL != resolvedURL && stylesheetContent.includes(urlFunction)) {
  759. stylesheetContent = stylesheetContent.replace(DomUtil.getRegExp(urlFunction), urlFunction.replace(originalResourceURL, resolvedURL));
  760. }
  761. } else {
  762. if (resourceURL.startsWith(DATA_URI_PREFIX)) {
  763. const escapedResourceURL = resourceURL.replace(/&/g, "&amp;").replace(/\u00a0/g, "&nbsp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
  764. if (escapedResourceURL != resourceURL && stylesheetContent.includes(urlFunction)) {
  765. stylesheetContent = stylesheetContent.replace(DomUtil.getRegExp(urlFunction), urlFunction.replace(originalResourceURL, escapedResourceURL));
  766. }
  767. }
  768. }
  769. });
  770. return stylesheetContent;
  771. }
  772. static async resolveLinkStylesheetURLs(resourceURL, baseURI, media, options) {
  773. resourceURL = DomUtil.normalizeURL(resourceURL);
  774. if (resourceURL && resourceURL != baseURI && resourceURL != ABOUT_BLANK_URI) {
  775. let stylesheetContent = await Download.getContent(resourceURL, { asDataURI: false, maxResourceSize: options.maxResourceSize, maxResourceSizeEnabled: options.maxResourceSizeEnabled });
  776. stylesheetContent = await DomProcessorHelper.resolveImportURLs(stylesheetContent, resourceURL, options);
  777. stylesheetContent = DomUtil.wrapMediaQuery(stylesheetContent, media);
  778. return stylesheetContent;
  779. }
  780. }
  781. static async processStylesheet(stylesheetContent, baseURI) {
  782. stylesheetContent = DomProcessorHelper.resolveStylesheetURLs(stylesheetContent, baseURI);
  783. const urlFunctions = DomUtil.getUrlFunctions(stylesheetContent);
  784. await Promise.all(urlFunctions.map(async urlFunction => {
  785. const originalResourceURL = DomUtil.matchURL(urlFunction);
  786. const resourceURL = DomUtil.normalizeURL(originalResourceURL);
  787. if (resourceURL && resourceURL != baseURI && DomUtil.testValidPath(resourceURL) && stylesheetContent.includes(urlFunction)) {
  788. const dataURI = await batchRequest.addURL(resourceURL);
  789. stylesheetContent = stylesheetContent.replace(DomUtil.getRegExp(urlFunction), urlFunction.replace(originalResourceURL, dataURI));
  790. }
  791. }));
  792. return stylesheetContent;
  793. }
  794. static async processAttribute(resourceElements, attributeName, baseURI) {
  795. await Promise.all(Array.from(resourceElements).map(async resourceElement => {
  796. let resourceURL = resourceElement.getAttribute(attributeName);
  797. if (resourceURL) {
  798. resourceURL = DomUtil.normalizeURL(resourceURL);
  799. if (resourceURL && resourceURL != baseURI && DomUtil.testValidPath(resourceURL)) {
  800. try {
  801. const dataURI = await batchRequest.addURL(new URL(resourceURL, baseURI).href);
  802. resourceElement.setAttribute(attributeName, dataURI);
  803. } catch (error) {
  804. /* ignored */
  805. }
  806. }
  807. }
  808. }));
  809. }
  810. static async processXLinks(resourceElements, baseURI) {
  811. await Promise.all(Array.from(resourceElements).map(async resourceElement => {
  812. const originalResourceURL = resourceElement.getAttribute("xlink:href");
  813. if (originalResourceURL) {
  814. const resourceURL = DomUtil.normalizeURL(originalResourceURL);
  815. if (resourceURL && resourceURL != baseURI && DomUtil.testValidPath(resourceURL)) {
  816. try {
  817. const content = await batchRequest.addURL(new URL(resourceURL, baseURI).href, false);
  818. const DOMParser = DOM.getParser();
  819. if (DOMParser) {
  820. const svgDoc = new DOMParser().parseFromString(content, "image/svg+xml");
  821. const hashMatch = originalResourceURL.match(/(#.+?)$/);
  822. if (hashMatch && hashMatch[0]) {
  823. const symbolElement = svgDoc.querySelector(hashMatch[0]);
  824. if (symbolElement) {
  825. resourceElement.setAttribute("xlink:href", hashMatch[0]);
  826. resourceElement.parentElement.appendChild(symbolElement);
  827. }
  828. } else {
  829. resourceElement.setAttribute("xlink:href", "data:image/svg+xml," + content);
  830. }
  831. } else {
  832. resourceElement.setAttribute("xlink:href", "data:image/svg+xml," + content);
  833. }
  834. } catch (error) {
  835. /* ignored */
  836. }
  837. }
  838. }
  839. }));
  840. }
  841. static async processSrcset(resourceElements, attributeName, baseURI) {
  842. await Promise.all(Array.from(resourceElements).map(async resourceElement => {
  843. const srcset = DOM.parseSrcset(resourceElement.getAttribute(attributeName));
  844. const srcsetValues = await Promise.all(srcset.map(async srcsetValue => {
  845. const resourceURL = DomUtil.normalizeURL(srcsetValue.url);
  846. if (resourceURL && resourceURL != baseURI && DomUtil.testValidPath(resourceURL)) {
  847. try {
  848. const dataURI = await batchRequest.addURL(new URL(resourceURL, baseURI).href);
  849. return dataURI + (srcsetValue.w ? " " + srcsetValue.w + "w" : srcsetValue.d ? " " + srcsetValue.d + "x" : "");
  850. } catch (error) {
  851. /* ignored */
  852. }
  853. }
  854. }));
  855. resourceElement.setAttribute(attributeName, srcsetValues.join(", "));
  856. }));
  857. }
  858. }
  859. // -------
  860. // DomUtil
  861. // -------
  862. const DATA_URI_PREFIX = "data:";
  863. const BLOB_URI_PREFIX = "blob:";
  864. const HTTP_URI_PREFIX = /^https?:\/\//;
  865. const ABOUT_BLANK_URI = "about:blank";
  866. const NOT_EMPTY_URL = /^https?:\/\/.+/;
  867. const REGEXP_URL_FN = /(url\s*\(\s*'(.*?)'\s*\))|(url\s*\(\s*"(.*?)"\s*\))|(url\s*\(\s*(.*?)\s*\))/gi;
  868. const REGEXP_URL_SIMPLE_QUOTES_FN = /^url\s*\(\s*'(.*?)'\s*\)$/i;
  869. const REGEXP_URL_DOUBLE_QUOTES_FN = /^url\s*\(\s*"(.*?)"\s*\)$/i;
  870. const REGEXP_URL_NO_QUOTES_FN = /^url\s*\(\s*(.*?)\s*\)$/i;
  871. 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;
  872. const REGEXP_IMPORT_URL_SIMPLE_QUOTES_FN = /@import\s*url\s*\(\s*'(.*?)'\s*\)\s*(.*?)/i;
  873. const REGEXP_IMPORT_URL_DOUBLE_QUOTES_FN = /@import\s*url\s*\(\s*"(.*?)"\s*\)\s*(.*?)/i;
  874. const REGEXP_IMPORT_URL_NO_QUOTES_FN = /@import\s*url\s*\(\s*(.*?)\s*\)\s*(.*?)/i;
  875. const REGEXP_IMPORT_SIMPLE_QUOTES_FN = /@import\s*'(.*?)'\s*(.*?)/i;
  876. const REGEXP_IMPORT_DOUBLE_QUOTES_FN = /@import\s*"(.*?)"\s*(.*?)/i;
  877. const REGEXP_IMPORT_NO_QUOTES_FN = /@import\s*(.*?)\s*(.*?)/i;
  878. class DomUtil {
  879. static normalizeURL(url) {
  880. if (url.startsWith(DATA_URI_PREFIX)) {
  881. return url;
  882. } else {
  883. return url.split("#")[0];
  884. }
  885. }
  886. static getRegExp(string) {
  887. return new RegExp(string.replace(/([{}()^$&.*?/+|[\\\\]|\]|-)/g, "\\$1"), "gi");
  888. }
  889. static getUrlFunctions(stylesheetContent) {
  890. return Array.from(new Set(stylesheetContent.match(REGEXP_URL_FN) || []));
  891. }
  892. static getImportFunctions(stylesheetContent) {
  893. return stylesheetContent.match(REGEXP_IMPORT_FN) || [];
  894. }
  895. static matchURL(stylesheetContent) {
  896. const match = stylesheetContent.match(REGEXP_URL_SIMPLE_QUOTES_FN) ||
  897. stylesheetContent.match(REGEXP_URL_DOUBLE_QUOTES_FN) ||
  898. stylesheetContent.match(REGEXP_URL_NO_QUOTES_FN);
  899. return match && match[1];
  900. }
  901. static testValidPath(resourceURL) {
  902. return !resourceURL.startsWith(DATA_URI_PREFIX) && !resourceURL.startsWith(BLOB_URI_PREFIX) && resourceURL != ABOUT_BLANK_URI && (!resourceURL.match(HTTP_URI_PREFIX) || resourceURL.match(NOT_EMPTY_URL));
  903. }
  904. static matchImport(stylesheetContent) {
  905. const match = stylesheetContent.match(REGEXP_IMPORT_URL_SIMPLE_QUOTES_FN) ||
  906. stylesheetContent.match(REGEXP_IMPORT_URL_DOUBLE_QUOTES_FN) ||
  907. stylesheetContent.match(REGEXP_IMPORT_URL_NO_QUOTES_FN) ||
  908. stylesheetContent.match(REGEXP_IMPORT_SIMPLE_QUOTES_FN) ||
  909. stylesheetContent.match(REGEXP_IMPORT_DOUBLE_QUOTES_FN) ||
  910. stylesheetContent.match(REGEXP_IMPORT_NO_QUOTES_FN);
  911. if (match) {
  912. const [, resourceURL, media] = match;
  913. return { resourceURL, media };
  914. }
  915. }
  916. static removeCssComments(stylesheetContent) {
  917. let start, end;
  918. do {
  919. start = stylesheetContent.indexOf("/*");
  920. end = stylesheetContent.indexOf("*/", start);
  921. if (start != -1 && end != -1) {
  922. stylesheetContent = stylesheetContent.substring(0, start) + stylesheetContent.substr(end + 2);
  923. }
  924. } while (start != -1 && end != -1);
  925. return stylesheetContent;
  926. }
  927. static wrapMediaQuery(stylesheetContent, mediaQuery) {
  928. if (mediaQuery) {
  929. return "@media " + mediaQuery + "{ " + stylesheetContent + " }";
  930. } else {
  931. return stylesheetContent;
  932. }
  933. }
  934. }
  935. // -----
  936. // Stats
  937. // -----
  938. const STATS_DEFAULT_VALUES = {
  939. discarded: {
  940. htmlBytes: 0,
  941. hiddenElements: 0,
  942. imports: 0,
  943. scripts: 0,
  944. objects: 0,
  945. audioSource: 0,
  946. videoSource: 0,
  947. frames: 0,
  948. cssRules: 0
  949. },
  950. processed: {
  951. htmlBytes: 0,
  952. imports: 0,
  953. scripts: 0,
  954. frames: 0,
  955. cssRules: 0,
  956. canvas: 0,
  957. styleSheets: 0,
  958. resources: 0
  959. }
  960. };
  961. class Stats {
  962. constructor(options) {
  963. this.options = options;
  964. if (options.displayStats) {
  965. this.data = JSON.parse(JSON.stringify(STATS_DEFAULT_VALUES));
  966. }
  967. }
  968. set(type, subType, value) {
  969. if (this.options.displayStats) {
  970. this.data[type][subType] = value;
  971. }
  972. }
  973. add(type, subType, value) {
  974. if (this.options.displayStats) {
  975. this.data[type][subType] += value;
  976. }
  977. }
  978. addAll(pageData) {
  979. if (this.options.displayStats) {
  980. Object.keys(this.data.discarded).forEach(key => this.add("discarded", key, pageData.stats.discarded[key] || 0));
  981. Object.keys(this.data.processed).forEach(key => this.add("processed", key, pageData.stats.processed[key] || 0));
  982. }
  983. }
  984. }
  985. return { getClass };
  986. })();