single-file-core.js 44 KB

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