single-file-core.js 61 KB

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