single-file-core.js 59 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406
  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 CSSRule */
  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 DEBUG = false;
  25. let Download, DOM, URL, sessionId = 0;
  26. function getClass(...args) {
  27. [Download, DOM, URL] = args;
  28. return class {
  29. constructor(options) {
  30. this.options = options;
  31. options.sessionId = sessionId;
  32. sessionId++;
  33. this.SELECTED_CONTENT_ATTRIBUTE_NAME = SELECTED_CONTENT_ATTRIBUTE_NAME;
  34. this.SELECTED_CONTENT_ROOT_ATTRIBUTE_NAME = SELECTED_CONTENT_ROOT_ATTRIBUTE_NAME;
  35. }
  36. async initialize() {
  37. this.processor = new PageProcessor(this.options);
  38. await this.processor.loadPage();
  39. await this.processor.initialize();
  40. }
  41. async preparePageData() {
  42. await this.processor.preparePageData();
  43. }
  44. async getPageData() {
  45. return this.processor.getPageData();
  46. }
  47. };
  48. }
  49. // -------------
  50. // ProgressEvent
  51. // -------------
  52. const PAGE_LOADING = "page-loading";
  53. const PAGE_LOADED = "page-loaded";
  54. const RESOURCES_INITIALIZING = "resource-initializing";
  55. const RESOURCES_INITIALIZED = "resources-initialized";
  56. const RESOURCE_LOADED = "resource-loaded";
  57. const PAGE_ENDED = "page-ended";
  58. class ProgressEvent {
  59. constructor(type, details) {
  60. return { type, details, PAGE_LOADING, PAGE_LOADED, RESOURCES_INITIALIZING, RESOURCES_INITIALIZED, RESOURCE_LOADED, PAGE_ENDED };
  61. }
  62. }
  63. // -------------
  64. // PageProcessor
  65. // -------------
  66. const STAGES = [{
  67. sequential: [
  68. { action: "repairDocument" },
  69. { action: "replaceStyleContents" },
  70. { option: "removeVideoSrc", action: "insertVideoPosters" },
  71. { option: "removeSrcSet", action: "removeSrcSet" },
  72. { option: "removeFrames", action: "removeFrames" },
  73. { option: "removeImports", action: "removeImports" },
  74. { option: "removeScripts", action: "removeScripts" },
  75. { action: "removeDiscardedResources" },
  76. { action: "resetCharsetMeta" },
  77. { action: "setInputValues" },
  78. { option: "insertFaviconLink", action: "insertFaviconLink" },
  79. { action: "resolveHrefs" },
  80. { action: "replaceCanvasElements" },
  81. { action: "insertFonts" },
  82. { option: "removeHiddenElements", action: "removeHiddenElements" }
  83. ],
  84. parallel: [
  85. { action: "resolveStylesheetURLs" },
  86. { action: "resolveLinkedStylesheetURLs" },
  87. { action: "resolveStyleAttributeURLs" },
  88. { option: "!removeFrames", action: "resolveFrameURLs" },
  89. { option: "!removeImports", action: "resolveHtmlImportURLs" }
  90. ]
  91. }, {
  92. sequential: [
  93. { option: "removeUnusedStyles", action: "removeUnusedStyles" },
  94. { option: "removeAlternativeMedias", action: "removeAlternativeMedias" }
  95. ],
  96. parallel: [
  97. { action: "processStylesheets" },
  98. { action: "processStyleAttributes" },
  99. { action: "pageResources" },
  100. { option: "!removeScripts", action: "processScripts" }
  101. ]
  102. }, {
  103. sequential: [
  104. { option: "lazyLoadImages", action: "lazyLoadImages" },
  105. { option: "removeAlternativeFonts", action: "removeAlternativeFonts" },
  106. { option: "compressCSS", action: "compressCSS" }
  107. ],
  108. parallel: [
  109. { option: "!removeFrames", action: "processFrames" },
  110. { option: "!removeImports", action: "processHtmlImports" },
  111. ]
  112. }, {
  113. sequential: [
  114. { option: "compressHTML", action: "compressHTML" },
  115. { option: "insertSingleFileComment", action: "insertSingleFileComment" },
  116. { action: "cleanup" }
  117. ]
  118. }];
  119. class PageProcessor {
  120. constructor(options) {
  121. this.options = options;
  122. this.options.url = this.options.url || this.options.doc.location.href;
  123. this.options.baseURI = this.options.doc && this.options.doc.baseURI;
  124. this.batchRequest = new BatchRequest();
  125. this.processor = new DOMProcessor(options, this.batchRequest);
  126. if (this.options.doc) {
  127. const docData = DOM.preProcessDoc(this.options.doc, this.options.win, this.options);
  128. this.options.canvasData = docData.canvasData;
  129. this.options.fontsData = docData.fontsData;
  130. this.options.stylesheetContents = docData.stylesheetContents;
  131. this.options.responsiveImageData = docData.responsiveImageData;
  132. this.options.imageData = docData.imageData;
  133. this.options.postersData = docData.postersData;
  134. }
  135. this.options.content = this.options.content || (this.options.doc ? DOM.serialize(this.options.doc, false) : null);
  136. this.onprogress = options.onprogress || (() => { });
  137. }
  138. async loadPage() {
  139. this.onprogress(new ProgressEvent(PAGE_LOADING, { pageURL: this.options.url }));
  140. await this.processor.loadPage(this.options.content);
  141. this.onprogress(new ProgressEvent(PAGE_LOADED, { pageURL: this.options.url }));
  142. }
  143. async initialize() {
  144. this.onprogress(new ProgressEvent(RESOURCES_INITIALIZING, { pageURL: this.options.url }));
  145. await this.executeStage(0);
  146. this.pendingPromises = this.executeStage(1);
  147. if (this.options.doc) {
  148. DOM.postProcessDoc(this.options.doc, this.options);
  149. this.options.doc = null;
  150. this.options.win = null;
  151. }
  152. }
  153. async preparePageData() {
  154. if (!this.options.windowId) {
  155. this.processor.initialize(this.batchRequest);
  156. this.onprogress(new ProgressEvent(RESOURCES_INITIALIZED, { pageURL: this.options.url, index: 0, max: this.processor.maxResources }));
  157. }
  158. await this.batchRequest.run(details => {
  159. details.pageURL = this.options.url;
  160. this.onprogress(new ProgressEvent(RESOURCE_LOADED, details));
  161. }, this.options);
  162. await this.pendingPromises;
  163. await this.executeStage(2);
  164. await this.executeStage(3);
  165. }
  166. async getPageData() {
  167. if (!this.options.windowId) {
  168. this.onprogress(new ProgressEvent(PAGE_ENDED, { pageURL: this.options.url }));
  169. }
  170. return this.processor.getPageData();
  171. }
  172. async executeStage(step) {
  173. if (DEBUG) {
  174. log("**** STARTED STAGE", step, "****");
  175. }
  176. STAGES[step].sequential.forEach(task => {
  177. let startTime;
  178. if (DEBUG) {
  179. startTime = Date.now();
  180. log(" -- STARTED task =", task.action);
  181. }
  182. this.executeTask(task);
  183. if (DEBUG) {
  184. log(" -- ENDED task =", task.action, "delay =", Date.now() - startTime);
  185. }
  186. });
  187. if (STAGES[step].parallel) {
  188. return await Promise.all(STAGES[step].parallel.map(task => {
  189. let startTime;
  190. if (DEBUG) {
  191. startTime = Date.now();
  192. log(" // STARTED task =", task.action);
  193. }
  194. const promise = this.executeTask(task);
  195. if (DEBUG) {
  196. promise.then(() => log(" // ENDED task =", task.action, "delay =", Date.now() - startTime));
  197. }
  198. return promise;
  199. }));
  200. }
  201. if (DEBUG) {
  202. log("**** ENDED STAGE", step, "****");
  203. }
  204. }
  205. executeTask(task) {
  206. if (!task.option || ((task.option.startsWith("!") && !this.options[task.option]) || this.options[task.option])) {
  207. return this.processor[task.action]();
  208. }
  209. }
  210. }
  211. // --------
  212. // BatchRequest
  213. // --------
  214. class BatchRequest {
  215. constructor() {
  216. this.requests = new Map();
  217. }
  218. async addURL(resourceURL, asDataURI = true) {
  219. return new Promise((resolve, reject) => {
  220. const requestKey = JSON.stringify([resourceURL, asDataURI]);
  221. const resourceRequests = this.requests.get(requestKey);
  222. if (resourceRequests) {
  223. resourceRequests.push({ resolve, reject });
  224. } else {
  225. this.requests.set(requestKey, [{ resolve, reject }]);
  226. }
  227. });
  228. }
  229. getMaxResources() {
  230. return Array.from(this.requests.keys()).length;
  231. }
  232. async run(onloadListener, options) {
  233. const resourceURLs = Array.from(this.requests.keys());
  234. let indexResource = 0;
  235. return Promise.all(resourceURLs.map(async requestKey => {
  236. const [resourceURL, asDataURI] = JSON.parse(requestKey);
  237. const resourceRequests = this.requests.get(requestKey);
  238. try {
  239. const resourceContent = await Download.getContent(resourceURL, { asDataURI, maxResourceSize: options.maxResourceSize, maxResourceSizeEnabled: options.maxResourceSizeEnabled });
  240. indexResource = indexResource + 1;
  241. onloadListener({ index: indexResource, url: resourceURL });
  242. resourceRequests.forEach(resourceRequest => resourceRequest.resolve({ content: resourceContent, indexResource, duplicate: Boolean(resourceRequests.length > 1) }));
  243. } catch (error) {
  244. indexResource = indexResource + 1;
  245. onloadListener({ index: indexResource, url: resourceURL });
  246. resourceRequests.forEach(resourceRequest => resourceRequest.reject(error));
  247. }
  248. this.requests.delete(requestKey);
  249. }));
  250. }
  251. }
  252. // ------------
  253. // DOMProcessor
  254. // ------------
  255. const EMPTY_DATA_URI = "data:base64,";
  256. const EMPTY_IMAGE = "data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==";
  257. class DOMProcessor {
  258. constructor(options, batchRequest) {
  259. this.options = options;
  260. this.stats = new Stats(options);
  261. this.baseURI = DomUtil.normalizeURL(options.baseURI || options.url);
  262. this.batchRequest = batchRequest;
  263. }
  264. initialize() {
  265. this.maxResources = this.batchRequest.getMaxResources();
  266. if (!this.options.removeFrames) {
  267. this.options.framesData.forEach(frameData => this.maxResources += frameData.maxResources || 0);
  268. }
  269. this.stats.set("processed", "resources", this.maxResources);
  270. }
  271. async loadPage(pageContent) {
  272. if (!pageContent || this.options.saveRawPage) {
  273. pageContent = await Download.getContent(this.baseURI, { asDataURI: false, maxResourceSize: this.options.maxResourceSize, maxResourceSizeEnabled: this.options.maxResourceSizeEnabled });
  274. }
  275. this.doc = DOM.createDoc(pageContent, this.baseURI);
  276. this.onEventAttributeNames = DOM.getOnEventAttributeNames(this.doc);
  277. }
  278. async getPageData() {
  279. DOM.postProcessDoc(this.doc, this.options);
  280. if (this.options.selected) {
  281. const rootElement = this.doc.querySelector("[" + SELECTED_CONTENT_ROOT_ATTRIBUTE_NAME + "]");
  282. if (rootElement) {
  283. DomProcessorHelper.isolateElements(rootElement);
  284. rootElement.removeAttribute(SELECTED_CONTENT_ROOT_ATTRIBUTE_NAME);
  285. rootElement.removeAttribute(SELECTED_CONTENT_ATTRIBUTE_NAME);
  286. }
  287. }
  288. const titleElement = this.doc.querySelector("title");
  289. this.options.title = titleElement ? titleElement.textContent.trim() : "";
  290. this.options.info = {};
  291. const descriptionElement = this.doc.querySelector("meta[name=description]");
  292. this.options.info.description = descriptionElement ? descriptionElement.content.trim() : "";
  293. this.options.info.lang = this.doc.documentElement.lang;
  294. const authorElement = this.doc.querySelector("meta[name=author]");
  295. this.options.info.author = authorElement ? authorElement.content.trim() : "";
  296. const creatorElement = this.doc.querySelector("meta[name=creator]");
  297. this.options.info.creator = creatorElement ? creatorElement.content.trim() : "";
  298. const publisherElement = this.doc.querySelector("meta[name=publisher]");
  299. this.options.info.publisher = publisherElement ? publisherElement.content.trim() : "";
  300. const url = new URL(this.baseURI);
  301. let size;
  302. if (this.options.displayStats) {
  303. size = DOM.getContentSize(this.doc.documentElement.outerHTML);
  304. }
  305. const content = DOM.serialize(this.doc, this.options.compressHTML);
  306. if (this.options.displayStats) {
  307. const contentSize = DOM.getContentSize(content);
  308. this.stats.set("processed", "HTML bytes", contentSize);
  309. this.stats.add("discarded", "HTML bytes", size - contentSize);
  310. }
  311. const filename = await DomProcessorHelper.getFilename(this.options, content);
  312. const matchTitle = this.baseURI.match(/([^/]*)\/?(\.html?.*)$/) || this.baseURI.match(/\/\/([^/]*)\/?$/);
  313. return {
  314. stats: this.stats.data,
  315. title: this.options.title || (this.baseURI && matchTitle ? matchTitle[1] : (url.hostname ? url.hostname : "")),
  316. filename,
  317. content
  318. };
  319. }
  320. setInputValues() {
  321. this.doc.querySelectorAll("input").forEach(input => {
  322. const value = input.getAttribute(DOM.inputValueAttributeName(this.options.sessionId));
  323. if (value) {
  324. input.setAttribute("value", value);
  325. }
  326. });
  327. this.doc.querySelectorAll("textarea").forEach(textarea => {
  328. const value = textarea.getAttribute(DOM.inputValueAttributeName(this.options.sessionId));
  329. if (value) {
  330. textarea.textContent = value;
  331. }
  332. });
  333. this.doc.querySelectorAll("select").forEach(select => {
  334. select.querySelectorAll("option").forEach(option => {
  335. const selected = option.getAttribute(DOM.inputValueAttributeName(this.options.sessionId)) != null;
  336. if (selected) {
  337. option.setAttribute("selected", "");
  338. }
  339. });
  340. });
  341. }
  342. lazyLoadImages() {
  343. DOM.lazyLoad(this.doc);
  344. }
  345. removeDiscardedResources() {
  346. const objectElements = this.doc.querySelectorAll("applet, meta[http-equiv=refresh], object[data]:not([type=\"image/svg+xml\"]):not([type=\"image/svg-xml\"]):not([type=\"text/html\"]), embed[src]:not([src*=\".svg\"])");
  347. this.stats.set("discarded", "objects", objectElements.length);
  348. this.stats.set("processed", "objects", objectElements.length);
  349. objectElements.forEach(element => element.remove());
  350. const replacedAttributeValue = this.doc.querySelectorAll("link[rel~=preconnect], link[rel~=prerender], link[rel~=dns-prefetch], link[rel~=preload], link[rel~=prefetch]");
  351. replacedAttributeValue.forEach(element => {
  352. const relValue = element.getAttribute("rel").replace(/(preconnect|prerender|dns-prefetch|preload|prefetch)/g, "").trim();
  353. if (relValue.length) {
  354. element.setAttribute("rel", relValue);
  355. } else {
  356. element.remove();
  357. }
  358. });
  359. this.doc.querySelectorAll("meta[http-equiv=\"content-security-policy\"]").forEach(element => element.remove());
  360. if (this.options.compressHTML) {
  361. this.doc.querySelectorAll("input[type=hidden]").forEach(element => element.remove());
  362. }
  363. this.doc.querySelectorAll("a[ping]").forEach(element => element.removeAttribute("ping"));
  364. if (this.options.removeScripts) {
  365. this.onEventAttributeNames.forEach(attributeName => this.doc.querySelectorAll("[" + attributeName + "]").forEach(element => element.removeAttribute(attributeName)));
  366. this.doc.querySelectorAll("[href]").forEach(element => {
  367. if (element.href && element.href.match && element.href.match(/^\s*javascript:/)) {
  368. element.removeAttribute("href");
  369. }
  370. });
  371. this.doc.querySelectorAll("[src]").forEach(element => {
  372. if (element.src && element.src.match(/^\s*javascript:/)) {
  373. element.removeAttribute("src");
  374. }
  375. });
  376. }
  377. const audioSourceElements = this.doc.querySelectorAll("audio[src], audio > source[src]");
  378. this.stats.set("processed", "audio sources", audioSourceElements.length);
  379. if (this.options.removeAudioSrc) {
  380. this.stats.set("discarded", "audio sources", audioSourceElements.length);
  381. audioSourceElements.forEach(element => element.removeAttribute("src"));
  382. }
  383. const videoSourceElements = this.doc.querySelectorAll("video[src], video > source[src]");
  384. this.stats.set("processed", "video sources", videoSourceElements.length);
  385. if (this.options.removeVideoSrc) {
  386. this.stats.set("discarded", "video sources", videoSourceElements.length);
  387. videoSourceElements.forEach(element => element.removeAttribute("src"));
  388. }
  389. }
  390. cleanup() {
  391. this.doc.querySelectorAll("style[data-single-file-sheet]").forEach(element => element.removeAttribute("data-single-file-sheet"));
  392. this.doc.querySelectorAll("base").forEach(element => element.remove());
  393. if (this.doc.head.querySelectorAll("*").length == 1 && this.doc.head.querySelector("meta[charset]") && this.doc.body.childNodes.length == 0) {
  394. this.doc.head.querySelector("meta[charset]").remove();
  395. }
  396. }
  397. repairDocument() {
  398. this.doc.querySelectorAll("singlefile-infobar, singlefile-mask").forEach(element => element.remove());
  399. this.doc.body.querySelectorAll("title, meta, link").forEach(element => this.doc.head.appendChild(element));
  400. }
  401. removeScripts() {
  402. const scriptElements = this.doc.querySelectorAll("script:not([type=\"application/ld+json\"])");
  403. this.stats.set("discarded", "scripts", scriptElements.length);
  404. this.stats.set("processed", "scripts", scriptElements.length);
  405. scriptElements.forEach(element => element.remove());
  406. }
  407. removeFrames() {
  408. const frameElements = this.doc.querySelectorAll("iframe, frame, object[type=\"text/html\"][data]");
  409. this.stats.set("discarded", "frames", frameElements.length);
  410. this.stats.set("processed", "frames", frameElements.length);
  411. this.doc.querySelectorAll("iframe, frame, object[type=\"text/html\"][data]").forEach(element => element.remove());
  412. }
  413. removeImports() {
  414. const importElements = this.doc.querySelectorAll("link[rel=import]");
  415. this.stats.set("discarded", "HTML imports", importElements.length);
  416. this.stats.set("processed", "HTML imports", importElements.length);
  417. importElements.forEach(element => element.remove());
  418. }
  419. resetCharsetMeta() {
  420. this.doc.querySelectorAll("meta[charset], meta[http-equiv=\"content-type\"]").forEach(element => {
  421. const charSetDeclaration = element.content.split(";")[1];
  422. if (charSetDeclaration) {
  423. const charSet = charSetDeclaration.split("=")[1];
  424. if (charSet) {
  425. this.charSet = charSet.trim().toLowerCase();
  426. }
  427. }
  428. element.remove();
  429. });
  430. const metaElement = this.doc.createElement("meta");
  431. metaElement.setAttribute("charset", "utf-8");
  432. if (this.doc.head.firstChild) {
  433. this.doc.head.insertBefore(metaElement, this.doc.head.firstChild);
  434. } else {
  435. this.doc.head.appendChild(metaElement);
  436. }
  437. }
  438. insertFaviconLink() {
  439. let faviconElement = this.doc.querySelector("link[href][rel=\"icon\"]");
  440. if (!faviconElement) {
  441. faviconElement = this.doc.querySelector("link[href][rel=\"shortcut icon\"]");
  442. }
  443. if (!faviconElement) {
  444. faviconElement = this.doc.createElement("link");
  445. faviconElement.setAttribute("type", "image/x-icon");
  446. faviconElement.setAttribute("rel", "shortcut icon");
  447. faviconElement.setAttribute("href", "/favicon.ico");
  448. }
  449. this.doc.head.appendChild(faviconElement);
  450. }
  451. resolveHrefs() {
  452. this.doc.querySelectorAll("[href]").forEach(element => {
  453. if (element.href) {
  454. const href = element.href.baseVal ? element.href.baseVal : element.href;
  455. const normalizedHref = DomUtil.normalizeURL(href);
  456. if (!normalizedHref || normalizedHref != this.baseURI) {
  457. element.setAttribute("href", href);
  458. }
  459. }
  460. });
  461. }
  462. removeUnusedStyles() {
  463. if (!this.mediaAllInfo) {
  464. this.mediaAllInfo = DOM.getMediaAllInfo(this.doc);
  465. }
  466. const stats = DOM.minifyCSS(this.doc, this.mediaAllInfo);
  467. this.stats.set("processed", "CSS rules", stats.processed);
  468. this.stats.set("discarded", "CSS rules", stats.discarded);
  469. }
  470. removeAlternativeFonts() {
  471. DOM.minifyFonts(this.doc);
  472. }
  473. removeSrcSet() {
  474. this.doc.querySelectorAll("picture, img[srcset]").forEach(element => {
  475. const tagName = element.tagName.toLowerCase();
  476. const dataAttributeName = DOM.responsiveImagesAttributeName(this.options.sessionId);
  477. const responsiveImageData = this.options.responsiveImageData[Number(element.getAttribute(dataAttributeName))];
  478. element.removeAttribute(dataAttributeName);
  479. if (responsiveImageData) {
  480. if (tagName == "img") {
  481. if (responsiveImageData.source.src && responsiveImageData.source.naturalWidth > 1 && responsiveImageData.source.naturalHeight > 1) {
  482. element.removeAttribute("srcset");
  483. element.removeAttribute("sizes");
  484. element.src = responsiveImageData.source.src;
  485. }
  486. }
  487. if (tagName == "picture") {
  488. const imageElement = element.querySelector("img");
  489. if (responsiveImageData.source && responsiveImageData.source.src && responsiveImageData.source.naturalWidth > 1 && responsiveImageData.source.naturalHeight > 1) {
  490. imageElement.removeAttribute("srcset");
  491. imageElement.removeAttribute("sizes");
  492. imageElement.src = responsiveImageData.source.src;
  493. element.querySelectorAll("source").forEach(sourceElement => sourceElement.remove());
  494. } else {
  495. if (responsiveImageData.sources) {
  496. element.querySelectorAll("source").forEach(sourceElement => {
  497. if (!sourceElement.srcset && !sourceElement.dataset.srcset && !sourceElement.src) {
  498. sourceElement.remove();
  499. }
  500. });
  501. const sourceElements = element.querySelectorAll("source");
  502. if (sourceElements.length) {
  503. const lastSourceElement = sourceElements[sourceElements.length - 1];
  504. if (imageElement) {
  505. if (lastSourceElement.src) {
  506. imageElement.src = lastSourceElement.src;
  507. } else {
  508. imageElement.removeAttribute("src");
  509. }
  510. if (lastSourceElement.srcset || lastSourceElement.dataset.srcset) {
  511. imageElement.srcset = lastSourceElement.srcset || lastSourceElement.dataset.srcset;
  512. } else {
  513. imageElement.removeAttribute("srcset");
  514. }
  515. element.querySelectorAll("source").forEach(sourceElement => sourceElement.remove());
  516. }
  517. }
  518. }
  519. }
  520. }
  521. }
  522. });
  523. }
  524. postRemoveAlternativeFonts() {
  525. DOM.minifyFonts(this.doc, true);
  526. }
  527. removeHiddenElements() {
  528. const hiddenElements = this.doc.querySelectorAll("[" + DOM.removedContentAttributeName(this.options.sessionId) + "]");
  529. this.stats.set("discarded", "hidden elements", hiddenElements.length);
  530. this.stats.set("processed", "hidden elements", hiddenElements.length);
  531. hiddenElements.forEach(element => element.remove());
  532. }
  533. compressHTML() {
  534. let size;
  535. if (this.options.displayStats) {
  536. size = DOM.getContentSize(this.doc.documentElement.outerHTML);
  537. }
  538. DOM.minifyHTML(this.doc, { preservedSpaceAttributeName: DOM.preservedSpaceAttributeName(this.options.sessionId) });
  539. if (this.options.displayStats) {
  540. this.stats.add("discarded", "HTML bytes", size - DOM.getContentSize(this.doc.documentElement.outerHTML));
  541. }
  542. }
  543. removeAlternativeMedias() {
  544. const stats = DOM.minifyMedias(this.doc);
  545. this.stats.set("processed", "medias", stats.processed);
  546. this.stats.set("discarded", "medias", stats.discarded);
  547. }
  548. compressCSS() {
  549. this.doc.querySelectorAll("style").forEach(styleElement => {
  550. if (styleElement) {
  551. styleElement.textContent = DOM.compressCSS(styleElement.textContent);
  552. }
  553. });
  554. this.doc.querySelectorAll("[style]").forEach(element => {
  555. element.setAttribute("style", DOM.compressCSS(element.getAttribute("style")));
  556. });
  557. }
  558. insertSingleFileComment() {
  559. const commentNode = this.doc.createComment("\n Archive processed by SingleFile \n url: " + this.baseURI + " \n saved date: " + new Date() + " \n");
  560. this.doc.documentElement.insertBefore(commentNode, this.doc.documentElement.firstChild);
  561. }
  562. replaceCanvasElements() {
  563. if (this.options.canvasData) {
  564. this.doc.querySelectorAll("canvas").forEach((canvasElement, indexCanvasElement) => {
  565. const canvasData = this.options.canvasData[indexCanvasElement];
  566. if (canvasData) {
  567. DomProcessorHelper.setBackgroundImage(canvasElement, "url(" + canvasData.dataURI + ")");
  568. this.stats.add("processed", "canvas", 1);
  569. }
  570. });
  571. }
  572. }
  573. insertFonts() {
  574. if (this.options.fontsData && this.options.fontsData.length) {
  575. let stylesheetContent = "";
  576. this.options.fontsData.forEach(fontStyles => {
  577. if (fontStyles["font-family"] && fontStyles.src) {
  578. stylesheetContent += "@font-face{";
  579. let stylesContent = "";
  580. Object.keys(fontStyles).forEach(fontStyle => {
  581. if (stylesContent) {
  582. stylesContent += ";";
  583. }
  584. stylesContent += fontStyle + ":" + fontStyles[fontStyle];
  585. });
  586. stylesheetContent += stylesContent + "}";
  587. }
  588. });
  589. if (stylesheetContent) {
  590. const styleElement = this.doc.createElement("style");
  591. styleElement.textContent = stylesheetContent;
  592. const existingStyleElement = this.doc.querySelector("style");
  593. if (existingStyleElement) {
  594. existingStyleElement.parentElement.insertBefore(styleElement, existingStyleElement);
  595. } else {
  596. this.doc.head.insertBefore(styleElement, this.doc.head.firstChild);
  597. }
  598. }
  599. }
  600. }
  601. replaceStyleContents() {
  602. if (this.options.stylesheetContents) {
  603. this.doc.querySelectorAll("style").forEach((styleElement, styleIndex) => {
  604. if (this.options.stylesheetContents[styleIndex]) {
  605. styleElement.textContent = this.options.stylesheetContents[styleIndex];
  606. }
  607. });
  608. }
  609. }
  610. insertVideoPosters() {
  611. if (this.options.postersData) {
  612. this.doc.querySelectorAll("video[src], video > source[src]").forEach((videoElement, videoIndex) => {
  613. if (!videoElement.poster && this.options.postersData[videoIndex]) {
  614. videoElement.setAttribute("poster", this.options.postersData[videoIndex]);
  615. }
  616. });
  617. }
  618. }
  619. async pageResources() {
  620. const resourcePromises = [
  621. DomProcessorHelper.processAttribute(this.doc, this.doc.querySelectorAll("link[href][rel*=\"icon\"]"), "href", PREFIX_DATA_URI_IMAGE, this.baseURI, this.batchRequest, this.options, false, true),
  622. DomProcessorHelper.processAttribute(this.doc, this.doc.querySelectorAll("object[type=\"image/svg+xml\"], object[type=\"image/svg-xml\"]"), "data", PREFIX_DATA_URI_IMAGE_SVG, this.baseURI, this.batchRequest, this.options),
  623. DomProcessorHelper.processAttribute(this.doc, this.doc.querySelectorAll("img[src], input[src][type=image]"), "src", PREFIX_DATA_URI_IMAGE, this.baseURI, this.batchRequest, this.options, true),
  624. DomProcessorHelper.processAttribute(this.doc, this.doc.querySelectorAll("embed[src*=\".svg\"]"), "src", PREFIX_DATA_URI_IMAGE_SVG, this.baseURI, this.batchRequest, this.options),
  625. DomProcessorHelper.processAttribute(this.doc, this.doc.querySelectorAll("video[poster]"), "poster", PREFIX_DATA_URI_IMAGE, this.baseURI, this.batchRequest, this.options),
  626. DomProcessorHelper.processAttribute(this.doc, this.doc.querySelectorAll("*[background]"), "background", PREFIX_DATA_URI_IMAGE, this.baseURI, this.batchRequest, this.options),
  627. DomProcessorHelper.processAttribute(this.doc, this.doc.querySelectorAll("image"), "xlink:href", PREFIX_DATA_URI_IMAGE, this.baseURI, this.batchRequest, this.options),
  628. DomProcessorHelper.processXLinks(this.doc, this.doc.querySelectorAll("use"), this.baseURI, this.batchRequest),
  629. DomProcessorHelper.processSrcset(this.doc, this.doc.querySelectorAll("img[srcset], source[srcset]"), "srcset", PREFIX_DATA_URI_IMAGE, this.baseURI, this.batchRequest)
  630. ];
  631. if (!this.options.removeAudioSrc) {
  632. resourcePromises.push(DomProcessorHelper.processAttribute(this.doc, this.doc.querySelectorAll("audio[src], audio > source[src]"), "src", PREFIX_DATA_URI_AUDIO, this.baseURI, this.batchRequest, this.options));
  633. }
  634. if (!this.options.removeVideoSrc) {
  635. resourcePromises.push(DomProcessorHelper.processAttribute(this.doc, this.doc.querySelectorAll("video[src], video > source[src]"), "src", PREFIX_DATA_URI_VIDEO, this.baseURI, this.batchRequest, this.options));
  636. }
  637. if (this.options.lazyLoadImages) {
  638. const imageSelectors = DOM.lazyLoaderImageSelectors();
  639. Object.keys(imageSelectors.src).forEach(selector => resourcePromises.push(DomProcessorHelper.processAttribute(this.doc, this.doc.querySelectorAll(selector), imageSelectors.src[selector], PREFIX_DATA_URI_IMAGE, this.baseURI, this.batchRequest, this.options)));
  640. Object.keys(imageSelectors.srcset).forEach(selector => resourcePromises.push(DomProcessorHelper.processSrcset(this.doc, this.doc.querySelectorAll(selector), imageSelectors.srcset[selector], PREFIX_DATA_URI_IMAGE, this.baseURI, this.batchRequest)));
  641. }
  642. await resourcePromises;
  643. }
  644. async resolveStylesheetURLs() {
  645. await Promise.all(Array.from(this.doc.querySelectorAll("style")).map(async styleElement => styleElement.textContent = await DomProcessorHelper.resolveImportURLs(styleElement.textContent, this.baseURI, { maxResourceSize: this.options.maxResourceSize, maxResourceSizeEnabled: this.options.maxResourceSizeEnabled })));
  646. }
  647. async processStylesheets() {
  648. await Promise.all(Array.from(this.doc.querySelectorAll("style")).map(async styleElement => {
  649. this.stats.add("processed", "stylesheets", 1);
  650. styleElement.textContent = await DomProcessorHelper.processStylesheet(this.doc, styleElement.textContent, styleElement.sheet.cssRules, this.baseURI, this.options, this.batchRequest);
  651. }));
  652. }
  653. async processScripts() {
  654. await Promise.all(Array.from(this.doc.querySelectorAll("script[src]")).map(async scriptElement => {
  655. if (scriptElement.src) {
  656. this.stats.add("processed", "scripts", 1);
  657. const scriptContent = await Download.getContent(scriptElement.src, { asDataURI: false, maxResourceSize: this.options.maxResourceSize, maxResourceSizeEnabled: this.options.maxResourceSizeEnabled });
  658. scriptElement.textContent = scriptContent.replace(/<\/script>/gi, "<\\/script>");
  659. }
  660. scriptElement.removeAttribute("src");
  661. }));
  662. }
  663. async resolveFrameURLs() {
  664. if (this.options.framesData) {
  665. const frameElements = Array.from(this.doc.querySelectorAll("iframe, frame, object[type=\"text/html\"][data]"));
  666. await Promise.all(frameElements.map(async frameElement => {
  667. DomProcessorHelper.setFrameEmptySrc(frameElement);
  668. frameElement.setAttribute("sandbox", "allow-scripts allow-same-origin");
  669. const frameWindowId = frameElement.getAttribute(DOM.windowIdAttributeName(this.options.sessionId));
  670. if (frameWindowId) {
  671. const frameData = this.options.framesData.find(frame => frame.windowId == frameWindowId);
  672. if (frameData) {
  673. const options = Object.create(this.options);
  674. options.insertSingleFileComment = false;
  675. options.insertFaviconLink = false;
  676. options.doc = null;
  677. options.win = null;
  678. options.url = frameData.baseURI;
  679. options.windowId = frameWindowId;
  680. if (frameData.content) {
  681. options.content = frameData.content;
  682. options.canvasData = frameData.canvasData;
  683. options.stylesheetContents = frameData.stylesheetContents;
  684. options.currentSrcImages = frameData.currentSrcImages;
  685. options.fontsData = frameData.fontsData;
  686. options.imageData = frameData.imageData;
  687. options.responsiveImageData = frameData.responsiveImageData;
  688. frameData.processor = new PageProcessor(options);
  689. frameData.frameElement = frameElement;
  690. await frameData.processor.loadPage();
  691. await frameData.processor.initialize();
  692. frameData.maxResources = this.batchRequest.getMaxResources();
  693. }
  694. }
  695. }
  696. }));
  697. }
  698. }
  699. async processFrames() {
  700. if (this.options.framesData) {
  701. const frameElements = Array.from(this.doc.querySelectorAll("iframe, frame, object[type=\"text/html\"][data]"));
  702. await Promise.all(frameElements.map(async frameElement => {
  703. const frameWindowId = frameElement.getAttribute(DOM.windowIdAttributeName(this.options.sessionId));
  704. if (frameWindowId) {
  705. const frameData = this.options.framesData.find(frame => frame.windowId == frameWindowId);
  706. if (frameData) {
  707. if (frameData.processor) {
  708. this.stats.add("processed", "frames", 1);
  709. await frameData.processor.preparePageData();
  710. const pageData = await frameData.processor.getPageData();
  711. frameElement.removeAttribute(DOM.windowIdAttributeName(this.options.sessionId));
  712. DomProcessorHelper.setFrameContent(frameElement, pageData.content);
  713. this.stats.addAll(pageData);
  714. } else {
  715. this.stats.add("discarded", "frames", 1);
  716. }
  717. }
  718. }
  719. }));
  720. }
  721. }
  722. async resolveHtmlImportURLs() {
  723. const linkElements = Array.from(this.doc.querySelectorAll("link[rel=import][href]"));
  724. if (!this.relImportProcessors) {
  725. this.relImportProcessors = new Map();
  726. }
  727. await Promise.all(linkElements.map(async linkElement => {
  728. const resourceURL = linkElement.href;
  729. linkElement.setAttribute("href", EMPTY_DATA_URI);
  730. const options = Object.create(this.options);
  731. options.insertSingleFileComment = false;
  732. options.insertFaviconLink = false;
  733. options.doc = null;
  734. options.win = null;
  735. options.url = resourceURL;
  736. if (!DomUtil.testIgnoredPath(resourceURL) && DomUtil.testValidPath(resourceURL, this.baseURI)) {
  737. const processor = new PageProcessor(options);
  738. this.relImportProcessors.set(linkElement, processor);
  739. await processor.loadPage();
  740. return processor.initialize();
  741. }
  742. }));
  743. }
  744. async processHtmlImports() {
  745. const linkElements = Array.from(this.doc.querySelectorAll("link[rel=import][href]"));
  746. await Promise.all(linkElements.map(async linkElement => {
  747. const processor = this.relImportProcessors.get(linkElement);
  748. if (processor) {
  749. this.stats.add("processed", "HTML imports", 1);
  750. this.relImportProcessors.delete(linkElement);
  751. const pageData = await processor.getPageData();
  752. linkElement.setAttribute("href", "data:text/html," + pageData.content);
  753. this.stats.addAll(pageData);
  754. } else {
  755. this.stats.add("discarded", "HTML imports", 1);
  756. }
  757. }));
  758. }
  759. async resolveStyleAttributeURLs() {
  760. await Promise.all(Array.from(this.doc.querySelectorAll("[style]")).map(async element => element.setAttribute("style", DomProcessorHelper.resolveStylesheetURLs(element.getAttribute("style"), this.baseURI))));
  761. }
  762. async processStyleAttributes() {
  763. await Promise.all(Array.from(this.doc.querySelectorAll("[style]")).map(async element => element.setAttribute("style", await DomProcessorHelper.processStylesheet(this.doc, element.getAttribute("style"), [{ type: CSSRule.STYLE_RULE, cssText: element.getAttribute("style") }], this.baseURI, this.options, this.batchRequest))));
  764. }
  765. async resolveLinkedStylesheetURLs() {
  766. await Promise.all(Array.from(this.doc.querySelectorAll("link[rel*=stylesheet]")).map(async linkElement => {
  767. const options = { maxResourceSize: this.options.maxResourceSize, maxResourceSizeEnabled: this.options.maxResourceSizeEnabled, charSet: this.charSet };
  768. const stylesheetContent = await DomProcessorHelper.resolveLinkStylesheetURLs(linkElement.href, this.baseURI, linkElement.media, options);
  769. const styleElement = this.doc.createElement("style");
  770. styleElement.textContent = stylesheetContent;
  771. linkElement.parentElement.replaceChild(styleElement, linkElement);
  772. }));
  773. }
  774. }
  775. // ---------
  776. // DomHelper
  777. // ---------
  778. const REGEXP_AMP = /&/g;
  779. const REGEXP_NBSP = /\u00a0/g;
  780. const REGEXP_START_TAG = /</g;
  781. const REGEXP_END_TAG = />/g;
  782. const REGEXP_URL_HASH = /(#.+?)$/;
  783. const PREFIX_DATA_URI_IMAGE = "data:image/";
  784. const PREFIX_DATA_URI_AUDIO = "data:audio/";
  785. const PREFIX_DATA_URI_VIDEO = "data:video/";
  786. const PREFIX_DATA_URI_IMAGE_SVG = "data:image/svg+xml";
  787. const PREFIX_DATA_URI_NO_MIMETYPE = "data:;";
  788. const PREFIX_DATA_URI_OCTET_STREAM = "data:application/octet-stream";
  789. const SINGLE_FILE_VARIABLE_NAME_PREFIX = "--sf-img-";
  790. class DomProcessorHelper {
  791. static async getFilename(options, content) {
  792. let filename = options.filenameTemplate;
  793. const date = new Date();
  794. const url = new URL(options.url);
  795. filename = await DomUtil.evalTemplateVariable(filename, "page-title", () => options.title || "No title");
  796. filename = await DomUtil.evalTemplateVariable(filename, "page-language", () => options.info.lang || "No language");
  797. filename = await DomUtil.evalTemplateVariable(filename, "page-description", () => options.info.description || "No description");
  798. filename = await DomUtil.evalTemplateVariable(filename, "page-author", () => options.info.author || "No author");
  799. filename = await DomUtil.evalTemplateVariable(filename, "page-creator", () => options.info.creator || "No creator");
  800. filename = await DomUtil.evalTemplateVariable(filename, "page-publisher", () => options.info.publisher || "No publisher");
  801. filename = await DomUtil.evalTemplateVariable(filename, "datetime-iso", () => date.toISOString());
  802. filename = await DomUtil.evalTemplateVariable(filename, "date-iso", () => date.toISOString().split("T")[0]);
  803. filename = await DomUtil.evalTemplateVariable(filename, "time-iso", () => date.toISOString().split("T")[1].split("Z")[0]);
  804. filename = await DomUtil.evalTemplateVariable(filename, "date-locale", () => date.toLocaleDateString());
  805. filename = await DomUtil.evalTemplateVariable(filename, "time-locale", () => date.toLocaleTimeString());
  806. filename = await DomUtil.evalTemplateVariable(filename, "day-locale", () => String(date.getDate()));
  807. filename = await DomUtil.evalTemplateVariable(filename, "month-locale", () => String(date.getMonth()));
  808. filename = await DomUtil.evalTemplateVariable(filename, "year-locale", () => String(date.getFullYear()));
  809. filename = await DomUtil.evalTemplateVariable(filename, "datetime-locale", () => date.toLocaleString());
  810. filename = await DomUtil.evalTemplateVariable(filename, "datetime-utc", () => date.toUTCString());
  811. filename = await DomUtil.evalTemplateVariable(filename, "day-utc", () => String(date.getUTCDate()));
  812. filename = await DomUtil.evalTemplateVariable(filename, "month-utc", () => String(date.getUTCMonth()));
  813. filename = await DomUtil.evalTemplateVariable(filename, "year-utc", () => String(date.getUTCFullYear()));
  814. filename = await DomUtil.evalTemplateVariable(filename, "url-hash", () => url.hash.substring(1));
  815. filename = await DomUtil.evalTemplateVariable(filename, "url-host", () => url.host.replace(/\/$/, ""));
  816. filename = await DomUtil.evalTemplateVariable(filename, "url-hostname", () => url.hostname.replace(/\/$/, ""));
  817. filename = await DomUtil.evalTemplateVariable(filename, "url-href", () => url.href);
  818. filename = await DomUtil.evalTemplateVariable(filename, "url-password", () => url.password);
  819. filename = await DomUtil.evalTemplateVariable(filename, "url-pathname", () => url.pathname.replace(/^\//, "").replace(/\/$/, ""), true);
  820. filename = await DomUtil.evalTemplateVariable(filename, "url-port", () => url.port);
  821. filename = await DomUtil.evalTemplateVariable(filename, "url-protocol", () => url.protocol);
  822. filename = await DomUtil.evalTemplateVariable(filename, "url-search", () => url.search.substring(1));
  823. filename = await DomUtil.evalTemplateVariable(filename, "url-username", () => url.username);
  824. filename = await DomUtil.evalTemplateVariable(filename, "tab-id", () => String(options.tabId || "No tab id"));
  825. filename = await DomUtil.evalTemplateVariable(filename, "url-last-segment", () => DomUtil.getLastSegment(url));
  826. filename = await DomUtil.evalTemplateVariable(filename, "digest-sha-256", async () => DOM.digest("SHA-256", content));
  827. filename = await DomUtil.evalTemplateVariable(filename, "digest-sha-384", async () => DOM.digest("SHA-384", content));
  828. filename = await DomUtil.evalTemplateVariable(filename, "digest-sha-512", async () => DOM.digest("SHA-512", content));
  829. filename = filename.replace(/[~\\?%*:|"<>\x00-\x1f\x7F]+/g, "_"); // eslint-disable-line no-control-regex
  830. filename = filename.replace(/\.\.\//g, "").replace(/^\/+/, "").replace(/\/+/g, "/").replace(/\/$/, "");
  831. if (!options.backgroundSave) {
  832. filename = filename.replace(/\//g, "_");
  833. }
  834. if (filename.length > 192) {
  835. const extensionMatch = filename.match(/(\.[^.]{3,4})$/);
  836. const extension = extensionMatch && extensionMatch[0] && extensionMatch[0].length > 1 ? extensionMatch[0] : "";
  837. filename = filename.substring(0, 192 - extension.length) + "…" + extension;
  838. }
  839. if (!filename) {
  840. filename = "Unnamed page";
  841. }
  842. return filename;
  843. }
  844. static setBackgroundImage(element, url) {
  845. element.style.setProperty("background-blend-mode", "normal");
  846. element.style.setProperty("background-clip", "content-box");
  847. element.style.setProperty("background-position", "center");
  848. element.style.setProperty("background-color", "transparent", "important");
  849. element.style.setProperty("background-image", url, "important");
  850. element.style.setProperty("background-size", "contain", "important");
  851. element.style.setProperty("background-origin", "content-box", "important");
  852. element.style.setProperty("background-repeat", "no-repeat", "important");
  853. }
  854. static setFrameEmptySrc(frameElement) {
  855. if (frameElement.tagName == "OBJECT") {
  856. frameElement.setAttribute("data", "data:text/html,");
  857. } else {
  858. frameElement.setAttribute("srcdoc", "");
  859. frameElement.removeAttribute("src");
  860. }
  861. }
  862. static setFrameContent(frameElement, content) {
  863. if (frameElement.tagName == "OBJECT") {
  864. frameElement.setAttribute("data", "data:text/html," + content);
  865. } else {
  866. frameElement.setAttribute("srcdoc", content);
  867. frameElement.removeAttribute("src");
  868. }
  869. }
  870. static isolateElements(rootElement) {
  871. rootElement.querySelectorAll("*").forEach(element => {
  872. if (element.getAttribute(SELECTED_CONTENT_ATTRIBUTE_NAME) == "") {
  873. element.removeAttribute(SELECTED_CONTENT_ATTRIBUTE_NAME);
  874. } else if (!element.querySelector("[" + SELECTED_CONTENT_ATTRIBUTE_NAME + "]")) {
  875. element.remove();
  876. }
  877. });
  878. isolateParentElements(rootElement.parentElement, rootElement);
  879. function isolateParentElements(parentElement, element) {
  880. if (parentElement) {
  881. Array.from(parentElement.childNodes).forEach(node => {
  882. if (node != element && node.tagName != "HEAD" && node.tagName != "STYLE") {
  883. node.remove();
  884. }
  885. });
  886. }
  887. element = element.parentElement;
  888. if (element && element.parentElement) {
  889. isolateParentElements(element.parentElement, element);
  890. }
  891. }
  892. }
  893. static async resolveImportURLs(stylesheetContent, baseURI, options) {
  894. stylesheetContent = DomProcessorHelper.resolveStylesheetURLs(stylesheetContent, baseURI);
  895. stylesheetContent = DomUtil.removeCssComments(stylesheetContent);
  896. const imports = DomUtil.getImportFunctions(stylesheetContent);
  897. await Promise.all(imports.map(async cssImport => {
  898. const match = DomUtil.matchImport(cssImport);
  899. if (match) {
  900. let resourceURL = DomUtil.normalizeURL(match.resourceURL);
  901. if (!DomUtil.testIgnoredPath(resourceURL) && DomUtil.testValidPath(resourceURL)) {
  902. resourceURL = new URL(match.resourceURL, baseURI).href;
  903. if (DomUtil.testValidURL(resourceURL, baseURI)) {
  904. let importedStylesheetContent = await Download.getContent(resourceURL, { asDataURI: false, maxResourceSize: options.maxResourceSize, maxResourceSizeEnabled: options.maxResourceSizeEnabled });
  905. importedStylesheetContent = DomUtil.wrapMediaQuery(importedStylesheetContent, match.media);
  906. if (stylesheetContent.includes(cssImport)) {
  907. importedStylesheetContent = await DomProcessorHelper.resolveImportURLs(importedStylesheetContent, resourceURL, options);
  908. stylesheetContent = stylesheetContent.replace(DomUtil.getRegExp(cssImport), importedStylesheetContent);
  909. }
  910. }
  911. }
  912. }
  913. }));
  914. return stylesheetContent;
  915. }
  916. static resolveStylesheetURLs(stylesheetContent, baseURI) {
  917. const urlFunctions = DomUtil.getUrlFunctions(stylesheetContent);
  918. urlFunctions.map(urlFunction => {
  919. const originalResourceURL = DomUtil.matchURL(urlFunction);
  920. const resourceURL = DomUtil.normalizeURL(originalResourceURL);
  921. if (!DomUtil.testIgnoredPath(resourceURL)) {
  922. if (DomUtil.testValidPath(resourceURL, baseURI)) {
  923. const resolvedURL = new URL(resourceURL, baseURI).href;
  924. if (DomUtil.testValidURL(resolvedURL, baseURI) && resourceURL != resolvedURL && stylesheetContent.includes(urlFunction)) {
  925. stylesheetContent = stylesheetContent.replace(DomUtil.getRegExp(urlFunction), urlFunction.replace(originalResourceURL, resolvedURL));
  926. }
  927. }
  928. } else {
  929. if (resourceURL.startsWith(DATA_URI_PREFIX)) {
  930. const escapedResourceURL = resourceURL.replace(REGEXP_AMP, "&amp;").replace(REGEXP_NBSP, "&nbsp;").replace(REGEXP_START_TAG, "&lt;").replace(REGEXP_END_TAG, "&gt;");
  931. if (escapedResourceURL != resourceURL && stylesheetContent.includes(urlFunction)) {
  932. stylesheetContent = stylesheetContent.replace(DomUtil.getRegExp(urlFunction), urlFunction.replace(originalResourceURL, escapedResourceURL));
  933. }
  934. }
  935. }
  936. });
  937. return stylesheetContent;
  938. }
  939. static async resolveLinkStylesheetURLs(resourceURL, baseURI, media, options) {
  940. resourceURL = DomUtil.normalizeURL(resourceURL);
  941. if (resourceURL && resourceURL != baseURI && resourceURL != ABOUT_BLANK_URI) {
  942. let stylesheetContent = await Download.getContent(resourceURL, { asDataURI: false, maxResourceSize: options.maxResourceSize, maxResourceSizeEnabled: options.maxResourceSizeEnabled, charSet: options.charSet });
  943. stylesheetContent = await DomProcessorHelper.resolveImportURLs(stylesheetContent, resourceURL, options);
  944. stylesheetContent = DomUtil.wrapMediaQuery(stylesheetContent, media);
  945. return stylesheetContent;
  946. }
  947. }
  948. static async processStylesheet(doc, stylesheetContent, cssRules, baseURI, options, batchRequest) {
  949. let sheetContent = "", variablesInfo = { index: 0, cssText: "" };
  950. const urlFunctions = DomUtil.getUrlFunctions(stylesheetContent);
  951. const resourceInfos = new Map();
  952. await Promise.all(urlFunctions.map(async urlFunction => {
  953. const originalResourceURL = DomUtil.matchURL(urlFunction);
  954. const resourceURL = DomUtil.normalizeURL(originalResourceURL);
  955. if (!DomUtil.testIgnoredPath(resourceURL)) {
  956. if (DomUtil.testValidURL(resourceURL, baseURI) && stylesheetContent.includes(urlFunction)) {
  957. const { content, indexResource, duplicate } = await batchRequest.addURL(resourceURL);
  958. urlFunction = "url(" + JSON.stringify(resourceURL) + ")";
  959. const regExpUrlFunction = DomUtil.getRegExp(urlFunction);
  960. if (duplicate && options.groupDuplicateImages) {
  961. resourceInfos.set(resourceURL, { regExpUrlFunction, indexResource, dataURI: content, variableName: "var(" + SINGLE_FILE_VARIABLE_NAME_PREFIX + indexResource + ")" });
  962. } else {
  963. resourceInfos.set(resourceURL, { regExpUrlFunction, indexResource, dataURI: content });
  964. }
  965. }
  966. }
  967. }));
  968. const rulesContent = processRules(cssRules);
  969. if (variablesInfo.cssText) {
  970. sheetContent += ":root{" + variablesInfo.cssText + "}";
  971. }
  972. return sheetContent + rulesContent;
  973. function processRules(cssRules) {
  974. let rulesContent = "";
  975. Array.from(cssRules).forEach(cssRule => {
  976. if (cssRule.type == CSSRule.MEDIA_RULE) {
  977. const mediaRulesContent = processRules(cssRule.cssRules);
  978. rulesContent += "@media " + Array.from(cssRule.media).join(",") + "{" + mediaRulesContent + "}";
  979. } else if (cssRule.type == CSSRule.STYLE_RULE) {
  980. rulesContent += processURLFunctions(cssRule.cssText);
  981. } else {
  982. rulesContent += processURLFunctions(cssRule.cssText, true);
  983. }
  984. });
  985. return rulesContent;
  986. }
  987. function processURLFunctions(cssText, preventGrouping) {
  988. const urlFunctions = DomUtil.getUrlFunctions(cssText);
  989. urlFunctions.forEach(urlFunction => {
  990. const originalResourceURL = DomUtil.matchURL(urlFunction);
  991. const resourceURL = DomUtil.normalizeURL(originalResourceURL);
  992. if (!DomUtil.testIgnoredPath(resourceURL)) {
  993. if (DomUtil.testValidURL(resourceURL, baseURI) && cssText.includes(urlFunction)) {
  994. const resourceInfo = resourceInfos.get(resourceURL);
  995. if (options.groupDuplicateImages && resourceInfo.variableName && !preventGrouping) {
  996. cssText = cssText.replace(resourceInfo.regExpUrlFunction, resourceInfo.variableName);
  997. DomUtil.insertVariable(doc, resourceInfo.indexResource, resourceInfo.dataURI, options);
  998. } else {
  999. cssText = cssText.replace(resourceInfo.regExpUrlFunction, urlFunction.replace(originalResourceURL, resourceInfo.dataURI));
  1000. }
  1001. }
  1002. }
  1003. });
  1004. return cssText;
  1005. }
  1006. }
  1007. static async processAttribute(doc, resourceElements, attributeName, prefixDataURI, baseURI, batchRequest, options, processDuplicates, removeElementIfMissing) {
  1008. await Promise.all(Array.from(resourceElements).map(async resourceElement => {
  1009. let resourceURL = resourceElement.getAttribute(attributeName);
  1010. resourceURL = DomUtil.normalizeURL(resourceURL);
  1011. if (!DomUtil.testIgnoredPath(resourceURL)) {
  1012. resourceElement.setAttribute(attributeName, EMPTY_IMAGE);
  1013. if (DomUtil.testValidPath(resourceURL, baseURI)) {
  1014. resourceURL = new URL(resourceURL, baseURI).href;
  1015. if (DomUtil.testValidURL(resourceURL, baseURI)) {
  1016. try {
  1017. const { content, indexResource, duplicate } = await batchRequest.addURL(resourceURL);
  1018. if (removeElementIfMissing && content == EMPTY_DATA_URI) {
  1019. resourceElement.remove();
  1020. } else {
  1021. if (content.startsWith(prefixDataURI) || content.startsWith(PREFIX_DATA_URI_NO_MIMETYPE) || content.startsWith(PREFIX_DATA_URI_OCTET_STREAM)) {
  1022. if (processDuplicates && duplicate && options.groupDuplicateImages && DomUtil.replaceImageSource(resourceElement, SINGLE_FILE_VARIABLE_NAME_PREFIX + indexResource, options)) {
  1023. DomUtil.insertVariable(doc, indexResource, content, options);
  1024. } else {
  1025. resourceElement.setAttribute(attributeName, content);
  1026. }
  1027. }
  1028. }
  1029. } catch (error) {
  1030. /* ignored */
  1031. }
  1032. }
  1033. }
  1034. }
  1035. }));
  1036. }
  1037. static async processXLinks(doc, resourceElements, baseURI, batchRequest) {
  1038. const attributeName = "xlink:href";
  1039. await Promise.all(Array.from(resourceElements).map(async resourceElement => {
  1040. const originalResourceURL = resourceElement.getAttribute(attributeName);
  1041. let resourceURL = DomUtil.normalizeURL(originalResourceURL);
  1042. if (DomUtil.testValidPath(resourceURL) && !DomUtil.testIgnoredPath(resourceURL)) {
  1043. resourceElement.setAttribute(attributeName, EMPTY_IMAGE);
  1044. resourceURL = new URL(resourceURL, baseURI).href;
  1045. if (DomUtil.testValidURL(resourceURL, baseURI)) {
  1046. try {
  1047. const { content } = await batchRequest.addURL(resourceURL, false);
  1048. const DOMParser = DOM.getParser();
  1049. if (DOMParser) {
  1050. const svgDoc = new DOMParser().parseFromString(content, "image/svg+xml");
  1051. const hashMatch = originalResourceURL.match(REGEXP_URL_HASH);
  1052. if (hashMatch && hashMatch[0]) {
  1053. const symbolElement = svgDoc.querySelector(hashMatch[0]);
  1054. if (symbolElement) {
  1055. resourceElement.setAttribute(attributeName, hashMatch[0]);
  1056. resourceElement.parentElement.insertBefore(symbolElement, resourceElement.parentElement.firstChild);
  1057. }
  1058. } else {
  1059. resourceElement.setAttribute(attributeName, "data:image/svg+xml," + content);
  1060. }
  1061. } else {
  1062. resourceElement.setAttribute(attributeName, "data:image/svg+xml," + content);
  1063. }
  1064. } catch (error) {
  1065. /* ignored */
  1066. }
  1067. }
  1068. }
  1069. }));
  1070. }
  1071. static async processSrcset(doc, resourceElements, attributeName, prefixDataURI, baseURI, batchRequest) {
  1072. await Promise.all(Array.from(resourceElements).map(async resourceElement => {
  1073. const srcset = DOM.parseSrcset(resourceElement.getAttribute(attributeName));
  1074. const srcsetValues = await Promise.all(srcset.map(async srcsetValue => {
  1075. let resourceURL = DomUtil.normalizeURL(srcsetValue.url);
  1076. if (!DomUtil.testIgnoredPath(resourceURL)) {
  1077. if (DomUtil.testValidPath(resourceURL)) {
  1078. resourceURL = new URL(resourceURL, baseURI).href;
  1079. if (DomUtil.testValidURL(resourceURL, baseURI)) {
  1080. try {
  1081. const { content } = await batchRequest.addURL(resourceURL);
  1082. if (!content.startsWith(prefixDataURI) && !content.startsWith(PREFIX_DATA_URI_NO_MIMETYPE) && !content.startsWith(PREFIX_DATA_URI_OCTET_STREAM)) {
  1083. resourceElement.setAttribute(attributeName, EMPTY_IMAGE);
  1084. }
  1085. return content + (srcsetValue.w ? " " + srcsetValue.w + "w" : srcsetValue.d ? " " + srcsetValue.d + "x" : "");
  1086. } catch (error) {
  1087. resourceElement.setAttribute(attributeName, EMPTY_IMAGE);
  1088. }
  1089. } else {
  1090. resourceElement.setAttribute(attributeName, EMPTY_IMAGE);
  1091. }
  1092. } else {
  1093. resourceElement.setAttribute(attributeName, EMPTY_IMAGE);
  1094. }
  1095. }
  1096. }));
  1097. resourceElement.setAttribute(attributeName, srcsetValues.join(", "));
  1098. }));
  1099. }
  1100. }
  1101. // -------
  1102. // DomUtil
  1103. // -------
  1104. const DATA_URI_PREFIX = "data:";
  1105. const BLOB_URI_PREFIX = "blob:";
  1106. const HTTP_URI_PREFIX = /^https?:\/\//;
  1107. const EMPTY_URL = /^https?:\/\/+\s*$/;
  1108. const ABOUT_BLANK_URI = "about:blank";
  1109. const NOT_EMPTY_URL = /^https?:\/\/.+/;
  1110. const REGEXP_URL_FN = /(url\s*\(\s*'(.*?)'\s*\))|(url\s*\(\s*"(.*?)"\s*\))|(url\s*\(\s*(.*?)\s*\))/gi;
  1111. const REGEXP_URL_SIMPLE_QUOTES_FN = /^url\s*\(\s*'(.*?)'\s*\)$/i;
  1112. const REGEXP_URL_DOUBLE_QUOTES_FN = /^url\s*\(\s*"(.*?)"\s*\)$/i;
  1113. const REGEXP_URL_NO_QUOTES_FN = /^url\s*\(\s*(.*?)\s*\)$/i;
  1114. 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;
  1115. const REGEXP_IMPORT_URL_SIMPLE_QUOTES_FN = /@import\s*url\s*\(\s*'(.*?)'\s*\)\s*(.*?)(;|$|})/i;
  1116. const REGEXP_IMPORT_URL_DOUBLE_QUOTES_FN = /@import\s*url\s*\(\s*"(.*?)"\s*\)\s*(.*?)(;|$|})/i;
  1117. const REGEXP_IMPORT_URL_NO_QUOTES_FN = /@import\s*url\s*\(\s*(.*?)\s*\)\s*(.*?)(;|$|})/i;
  1118. const REGEXP_IMPORT_SIMPLE_QUOTES_FN = /@import\s*'(.*?)'\s*(.*?)(;|$|})/i;
  1119. const REGEXP_IMPORT_DOUBLE_QUOTES_FN = /@import\s*"(.*?)"\s*(.*?)(;|$|})/i;
  1120. const REGEXP_IMPORT_NO_QUOTES_FN = /@import\s*(.*?)\s*(.*?)(;|$|})/i;
  1121. const REGEXP_ESCAPE = /([{}()^$&.*?/+|[\\\\]|\]|-)/g;
  1122. class DomUtil {
  1123. static normalizeURL(url) {
  1124. if (!url || url.startsWith(DATA_URI_PREFIX)) {
  1125. return url;
  1126. } else {
  1127. return url.split("#")[0];
  1128. }
  1129. }
  1130. static async evalTemplateVariable(template, variableName, valueGetter, dontReplaceSlash) {
  1131. const replaceRegExp = new RegExp("{\\s*" + variableName + "\\s*}", "g");
  1132. if (template.match(replaceRegExp)) {
  1133. let value = await valueGetter();
  1134. if (!dontReplaceSlash) {
  1135. value = value.replace(/\/+/g, "_");
  1136. }
  1137. return template.replace(replaceRegExp, value);
  1138. }
  1139. return template;
  1140. }
  1141. static getLastSegment(url) {
  1142. let lastSegmentMatch = url.pathname.match(/\/([^/]+)$/);
  1143. let lastSegment = lastSegmentMatch && lastSegmentMatch[0];
  1144. if (!lastSegment) {
  1145. lastSegmentMatch = url.href.match(/([^/]+)\/?$/);
  1146. lastSegment = lastSegmentMatch && lastSegmentMatch[0];
  1147. }
  1148. if (!lastSegment) {
  1149. lastSegmentMatch = lastSegment.match(/(.*)<\.[^.]+$/);
  1150. lastSegment = lastSegmentMatch && lastSegmentMatch[0];
  1151. }
  1152. if (!lastSegment) {
  1153. lastSegment = url.hostname.replace(/\/+/g, "_").replace(/\/$/, "");
  1154. }
  1155. lastSegment.replace(/\/$/, "").replace(/^\//, "");
  1156. return lastSegment;
  1157. }
  1158. static getRegExp(string) {
  1159. return new RegExp(string.replace(REGEXP_ESCAPE, "\\$1"), "gi");
  1160. }
  1161. static getUrlFunctions(stylesheetContent) {
  1162. return Array.from(new Set(stylesheetContent.match(REGEXP_URL_FN) || []));
  1163. }
  1164. static getImportFunctions(stylesheetContent) {
  1165. return stylesheetContent.match(REGEXP_IMPORT_FN) || [];
  1166. }
  1167. static matchURL(stylesheetContent) {
  1168. const match = stylesheetContent.match(REGEXP_URL_SIMPLE_QUOTES_FN) ||
  1169. stylesheetContent.match(REGEXP_URL_DOUBLE_QUOTES_FN) ||
  1170. stylesheetContent.match(REGEXP_URL_NO_QUOTES_FN);
  1171. return match && match[1];
  1172. }
  1173. static testIgnoredPath(resourceURL) {
  1174. return resourceURL && (resourceURL.startsWith(DATA_URI_PREFIX) || resourceURL.startsWith(BLOB_URI_PREFIX) || resourceURL == ABOUT_BLANK_URI);
  1175. }
  1176. static testValidPath(resourceURL, baseURI) {
  1177. return resourceURL && resourceURL != baseURI && !resourceURL.match(EMPTY_URL);
  1178. }
  1179. static testValidURL(resourceURL, baseURI) {
  1180. return DomUtil.testValidPath(resourceURL, baseURI) && resourceURL.match(HTTP_URI_PREFIX) && resourceURL.match(NOT_EMPTY_URL);
  1181. }
  1182. static matchImport(stylesheetContent) {
  1183. const match = stylesheetContent.match(REGEXP_IMPORT_URL_SIMPLE_QUOTES_FN) ||
  1184. stylesheetContent.match(REGEXP_IMPORT_URL_DOUBLE_QUOTES_FN) ||
  1185. stylesheetContent.match(REGEXP_IMPORT_URL_NO_QUOTES_FN) ||
  1186. stylesheetContent.match(REGEXP_IMPORT_SIMPLE_QUOTES_FN) ||
  1187. stylesheetContent.match(REGEXP_IMPORT_DOUBLE_QUOTES_FN) ||
  1188. stylesheetContent.match(REGEXP_IMPORT_NO_QUOTES_FN);
  1189. if (match) {
  1190. const [, resourceURL, media] = match;
  1191. return { resourceURL, media };
  1192. }
  1193. }
  1194. static removeCssComments(stylesheetContent) {
  1195. let start, end;
  1196. do {
  1197. start = stylesheetContent.indexOf("/*");
  1198. end = stylesheetContent.indexOf("*/", start + 2);
  1199. if (start != -1 && end != -1) {
  1200. stylesheetContent = stylesheetContent.substring(0, start) + stylesheetContent.substr(end + 2);
  1201. }
  1202. } while (start != -1 && end != -1);
  1203. return stylesheetContent;
  1204. }
  1205. static wrapMediaQuery(stylesheetContent, mediaQuery) {
  1206. if (mediaQuery) {
  1207. return "@media " + mediaQuery + "{ " + stylesheetContent + " }";
  1208. } else {
  1209. return stylesheetContent;
  1210. }
  1211. }
  1212. static insertVariable(doc, indexResource, content, options) {
  1213. const sheetAttributeName = DOM.sheetAttributeName(options.sessionId);
  1214. let styleElement = doc.querySelector("style[" + sheetAttributeName + "]"), insertedVariables;
  1215. if (!styleElement) {
  1216. styleElement = doc.createElement("style");
  1217. if (doc.head.firstChild) {
  1218. doc.head.insertBefore(styleElement, doc.head.firstChild);
  1219. } else {
  1220. doc.head.appendChild(styleElement);
  1221. }
  1222. styleElement.setAttribute(sheetAttributeName, "[]");
  1223. insertedVariables = [];
  1224. } else {
  1225. insertedVariables = JSON.parse(styleElement.getAttribute(sheetAttributeName));
  1226. }
  1227. if (!insertedVariables.includes(indexResource)) {
  1228. insertedVariables.push(indexResource);
  1229. styleElement.textContent = styleElement.textContent + `:root{${SINGLE_FILE_VARIABLE_NAME_PREFIX + indexResource}:url("${content}")}`;
  1230. styleElement.setAttribute(sheetAttributeName, JSON.stringify(insertedVariables));
  1231. }
  1232. }
  1233. static replaceImageSource(imgElement, variableName, options) {
  1234. const dataAttributeName = DOM.imagesAttributeName(options.sessionId);
  1235. if (imgElement.getAttribute(dataAttributeName) != null) {
  1236. const imgData = options.imageData[Number(imgElement.getAttribute(dataAttributeName))];
  1237. imgElement.setAttribute("src", `data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" width="${imgData.pxWidth}" height="${imgData.pxHeight}"><rect fill-opacity="0"/></svg>`);
  1238. DomProcessorHelper.setBackgroundImage(imgElement, "var(" + variableName + ")");
  1239. imgElement.removeAttribute(dataAttributeName);
  1240. return true;
  1241. }
  1242. }
  1243. }
  1244. function log(...args) {
  1245. console.log("S-File <core> ", ...args); // eslint-disable-line no-console
  1246. }
  1247. // -----
  1248. // Stats
  1249. // -----
  1250. const STATS_DEFAULT_VALUES = {
  1251. discarded: {
  1252. "HTML bytes": 0,
  1253. "hidden elements": 0,
  1254. "HTML imports": 0,
  1255. scripts: 0,
  1256. objects: 0,
  1257. "audio sources": 0,
  1258. "video sources": 0,
  1259. frames: 0,
  1260. "CSS rules": 0,
  1261. canvas: 0,
  1262. stylesheets: 0,
  1263. resources: 0,
  1264. medias: 0
  1265. },
  1266. processed: {
  1267. "HTML bytes": 0,
  1268. "hidden elements": 0,
  1269. "HTML imports": 0,
  1270. scripts: 0,
  1271. objects: 0,
  1272. "audio sources": 0,
  1273. "video sources": 0,
  1274. frames: 0,
  1275. "CSS rules": 0,
  1276. canvas: 0,
  1277. stylesheets: 0,
  1278. resources: 0,
  1279. medias: 0
  1280. }
  1281. };
  1282. class Stats {
  1283. constructor(options) {
  1284. this.options = options;
  1285. if (options.displayStats) {
  1286. this.data = JSON.parse(JSON.stringify(STATS_DEFAULT_VALUES));
  1287. }
  1288. }
  1289. set(type, subType, value) {
  1290. if (this.options.displayStats) {
  1291. this.data[type][subType] = value;
  1292. }
  1293. }
  1294. add(type, subType, value) {
  1295. if (this.options.displayStats) {
  1296. this.data[type][subType] += value;
  1297. }
  1298. }
  1299. addAll(pageData) {
  1300. if (this.options.displayStats) {
  1301. Object.keys(this.data.discarded).forEach(key => this.add("discarded", key, pageData.stats.discarded[key] || 0));
  1302. Object.keys(this.data.processed).forEach(key => this.add("processed", key, pageData.stats.processed[key] || 0));
  1303. }
  1304. }
  1305. }
  1306. return { getClass };
  1307. })();