single-file-core.js 43 KB

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