single-file-core.js 61 KB

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