single-file-core.js 44 KB

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