single-file-core.js 59 KB

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