single-file-core.js 61 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419
  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. class DOMProcessor {
  261. constructor(options, batchRequest) {
  262. this.options = options;
  263. this.stats = new Stats(options);
  264. this.baseURI = DomUtil.normalizeURL(options.baseURI || options.url);
  265. this.batchRequest = batchRequest;
  266. }
  267. initialize() {
  268. this.maxResources = this.batchRequest.getMaxResources();
  269. if (!this.options.removeFrames) {
  270. this.options.framesData.forEach(frameData => this.maxResources += frameData.maxResources || 0);
  271. }
  272. this.stats.set("processed", "resources", this.maxResources);
  273. }
  274. async loadPage(pageContent) {
  275. if (!pageContent || this.options.saveRawPage) {
  276. pageContent = await Download.getContent(this.baseURI, { asDataURI: false, maxResourceSize: this.options.maxResourceSize, maxResourceSizeEnabled: this.options.maxResourceSizeEnabled });
  277. }
  278. this.doc = DOM.createDoc(pageContent, this.baseURI);
  279. this.onEventAttributeNames = DOM.getOnEventAttributeNames(this.doc);
  280. }
  281. async getPageData() {
  282. DOM.postProcessDoc(this.doc, this.options);
  283. const titleElement = this.doc.querySelector("title");
  284. this.options.title = titleElement ? titleElement.textContent.trim() : "";
  285. this.options.info = {};
  286. const descriptionElement = this.doc.querySelector("meta[name=description]");
  287. this.options.info.description = descriptionElement ? descriptionElement.content.trim() : "";
  288. this.options.info.lang = this.doc.documentElement.lang;
  289. const authorElement = this.doc.querySelector("meta[name=author]");
  290. this.options.info.author = authorElement ? authorElement.content.trim() : "";
  291. const creatorElement = this.doc.querySelector("meta[name=creator]");
  292. this.options.info.creator = creatorElement ? creatorElement.content.trim() : "";
  293. const publisherElement = this.doc.querySelector("meta[name=publisher]");
  294. this.options.info.publisher = publisherElement ? publisherElement.content.trim() : "";
  295. const url = new URL(this.baseURI);
  296. let size;
  297. if (this.options.displayStats) {
  298. size = DOM.getContentSize(this.doc.documentElement.outerHTML);
  299. }
  300. const content = DOM.serialize(this.doc, this.options.compressHTML);
  301. if (this.options.displayStats) {
  302. const contentSize = DOM.getContentSize(content);
  303. this.stats.set("processed", "HTML bytes", contentSize);
  304. this.stats.add("discarded", "HTML bytes", size - contentSize);
  305. }
  306. const filename = await DomProcessorHelper.getFilename(this.options, content);
  307. const matchTitle = this.baseURI.match(/([^/]*)\/?(\.html?.*)$/) || this.baseURI.match(/\/\/([^/]*)\/?$/);
  308. return {
  309. stats: this.stats.data,
  310. title: this.options.title || (this.baseURI && matchTitle ? matchTitle[1] : (url.hostname ? url.hostname : "")),
  311. filename,
  312. content
  313. };
  314. }
  315. removeUnselectedElements() {
  316. const rootElement = this.doc.querySelector("[" + SELECTED_CONTENT_ROOT_ATTRIBUTE_NAME + "]");
  317. if (rootElement) {
  318. DomProcessorHelper.isolateElements(rootElement);
  319. rootElement.removeAttribute(SELECTED_CONTENT_ROOT_ATTRIBUTE_NAME);
  320. rootElement.removeAttribute(SELECTED_CONTENT_ATTRIBUTE_NAME);
  321. }
  322. }
  323. setInputValues() {
  324. this.doc.querySelectorAll("input").forEach(input => {
  325. const value = input.getAttribute(DOM.inputValueAttributeName(this.options.sessionId));
  326. if (value) {
  327. input.setAttribute("value", value);
  328. }
  329. });
  330. this.doc.querySelectorAll("textarea").forEach(textarea => {
  331. const value = textarea.getAttribute(DOM.inputValueAttributeName(this.options.sessionId));
  332. if (value) {
  333. textarea.textContent = value;
  334. }
  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("title, meta").forEach(element => 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. this.doc.querySelectorAll("meta[charset], meta[http-equiv=\"content-type\"]").forEach(element => {
  452. const charSetDeclaration = element.content.split(";")[1];
  453. if (charSetDeclaration) {
  454. const charSet = charSetDeclaration.split("=")[1];
  455. if (charSet) {
  456. this.charSet = charSet.trim().toLowerCase();
  457. }
  458. }
  459. element.remove();
  460. });
  461. const metaElement = this.doc.createElement("meta");
  462. metaElement.setAttribute("charset", "utf-8");
  463. if (this.doc.head.firstChild) {
  464. this.doc.head.insertBefore(metaElement, this.doc.head.firstChild);
  465. } else {
  466. this.doc.head.appendChild(metaElement);
  467. }
  468. }
  469. insertFaviconLink() {
  470. let faviconElement = this.doc.querySelector("link[href][rel=\"icon\"]");
  471. if (!faviconElement) {
  472. faviconElement = this.doc.querySelector("link[href][rel=\"shortcut icon\"]");
  473. }
  474. if (!faviconElement) {
  475. faviconElement = this.doc.createElement("link");
  476. faviconElement.setAttribute("type", "image/x-icon");
  477. faviconElement.setAttribute("rel", "shortcut icon");
  478. faviconElement.setAttribute("href", "/favicon.ico");
  479. }
  480. this.doc.head.appendChild(faviconElement);
  481. }
  482. resolveHrefs() {
  483. this.doc.querySelectorAll("[href]").forEach(element => {
  484. if (element.href) {
  485. const href = element.href.baseVal ? element.href.baseVal : element.href;
  486. const normalizedHref = DomUtil.normalizeURL(href);
  487. if (!normalizedHref || normalizedHref != this.baseURI) {
  488. element.setAttribute("href", href);
  489. }
  490. }
  491. });
  492. }
  493. removeUnusedStyles() {
  494. if (!this.mediaAllInfo) {
  495. this.mediaAllInfo = DOM.getMediaAllInfo(this.doc);
  496. }
  497. const stats = DOM.minifyCSS(this.doc, this.mediaAllInfo);
  498. this.stats.set("processed", "CSS rules", stats.processed);
  499. this.stats.set("discarded", "CSS rules", stats.discarded);
  500. }
  501. removeAlternativeFonts() {
  502. DOM.minifyFonts(this.doc);
  503. }
  504. removeAlternativeImages() {
  505. DOM.removeAlternativeImages(this.doc, this.options);
  506. }
  507. postRemoveAlternativeFonts() {
  508. DOM.minifyFonts(this.doc, true);
  509. }
  510. removeHiddenElements() {
  511. const hiddenElements = this.doc.querySelectorAll("[" + DOM.removedContentAttributeName(this.options.sessionId) + "]");
  512. this.stats.set("discarded", "hidden elements", hiddenElements.length);
  513. this.stats.set("processed", "hidden elements", hiddenElements.length);
  514. hiddenElements.forEach(element => element.remove());
  515. }
  516. compressHTML() {
  517. let size;
  518. if (this.options.displayStats) {
  519. size = DOM.getContentSize(this.doc.documentElement.outerHTML);
  520. }
  521. DOM.minifyHTML(this.doc, { preservedSpaceAttributeName: DOM.preservedSpaceAttributeName(this.options.sessionId) });
  522. if (this.options.displayStats) {
  523. this.stats.add("discarded", "HTML bytes", size - DOM.getContentSize(this.doc.documentElement.outerHTML));
  524. }
  525. }
  526. removeAlternativeMedias() {
  527. const stats = DOM.minifyMedias(this.doc);
  528. this.stats.set("processed", "medias", stats.processed);
  529. this.stats.set("discarded", "medias", stats.discarded);
  530. }
  531. compressCSS() {
  532. this.doc.querySelectorAll("style").forEach(styleElement => {
  533. if (styleElement) {
  534. styleElement.textContent = DOM.compressCSS(styleElement.textContent);
  535. }
  536. });
  537. this.doc.querySelectorAll("[style]").forEach(element => {
  538. element.setAttribute("style", DOM.compressCSS(element.getAttribute("style")));
  539. });
  540. }
  541. insertSingleFileComment() {
  542. const commentNode = this.doc.createComment("\n Archive processed by SingleFile \n url: " + this.options.url + " \n saved date: " + new Date() + " \n");
  543. this.doc.documentElement.insertBefore(commentNode, this.doc.documentElement.firstChild);
  544. }
  545. replaceCanvasElements() {
  546. if (this.options.canvasData) {
  547. this.doc.querySelectorAll("canvas").forEach((canvasElement, indexCanvasElement) => {
  548. const canvasData = this.options.canvasData[indexCanvasElement];
  549. if (canvasData) {
  550. DomProcessorHelper.setBackgroundImage(canvasElement, "url(" + canvasData.dataURI + ")");
  551. this.stats.add("processed", "canvas", 1);
  552. }
  553. });
  554. }
  555. }
  556. insertFonts() {
  557. if (this.options.fontsData && this.options.fontsData.length) {
  558. let stylesheetContent = "";
  559. this.options.fontsData.forEach(fontStyles => {
  560. if (fontStyles["font-family"] && fontStyles.src) {
  561. stylesheetContent += "@font-face{";
  562. let stylesContent = "";
  563. Object.keys(fontStyles).forEach(fontStyle => {
  564. if (stylesContent) {
  565. stylesContent += ";";
  566. }
  567. stylesContent += fontStyle + ":" + fontStyles[fontStyle];
  568. });
  569. stylesheetContent += stylesContent + "}";
  570. }
  571. });
  572. if (stylesheetContent) {
  573. const styleElement = this.doc.createElement("style");
  574. styleElement.textContent = stylesheetContent;
  575. const existingStyleElement = this.doc.querySelector("style");
  576. if (existingStyleElement) {
  577. existingStyleElement.parentElement.insertBefore(styleElement, existingStyleElement);
  578. } else {
  579. this.doc.head.insertBefore(styleElement, this.doc.head.firstChild);
  580. }
  581. }
  582. }
  583. }
  584. replaceStyleContents() {
  585. if (this.options.stylesheetContents) {
  586. this.doc.querySelectorAll("style").forEach((styleElement, styleIndex) => {
  587. if (this.options.stylesheetContents[styleIndex]) {
  588. styleElement.textContent = this.options.stylesheetContents[styleIndex];
  589. }
  590. });
  591. }
  592. }
  593. insertVideoPosters() {
  594. if (this.options.postersData) {
  595. this.doc.querySelectorAll("video[src], video > source[src]").forEach((videoElement, videoIndex) => {
  596. if (!videoElement.poster && this.options.postersData[videoIndex]) {
  597. videoElement.setAttribute("poster", this.options.postersData[videoIndex]);
  598. }
  599. });
  600. }
  601. }
  602. async pageResources() {
  603. const resourcePromises = [
  604. DomProcessorHelper.processAttribute(this.doc, this.doc.querySelectorAll("link[href][rel*=\"icon\"]"), "href", PREFIX_DATA_URI_IMAGE, this.baseURI, this.options, this.batchRequest, false, true),
  605. 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),
  606. 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),
  607. DomProcessorHelper.processAttribute(this.doc, this.doc.querySelectorAll("embed[src*=\".svg\"]"), "src", PREFIX_DATA_URI_IMAGE_SVG, this.baseURI, this.options, this.batchRequest),
  608. DomProcessorHelper.processAttribute(this.doc, this.doc.querySelectorAll("video[poster]"), "poster", PREFIX_DATA_URI_IMAGE, this.baseURI, this.options, this.batchRequest),
  609. DomProcessorHelper.processAttribute(this.doc, this.doc.querySelectorAll("*[background]"), "background", PREFIX_DATA_URI_IMAGE, this.baseURI, this.options, this.batchRequest),
  610. DomProcessorHelper.processAttribute(this.doc, this.doc.querySelectorAll("image"), "xlink:href", PREFIX_DATA_URI_IMAGE, this.baseURI, this.options, this.batchRequest),
  611. DomProcessorHelper.processXLinks(this.doc.querySelectorAll("use"), this.baseURI, this.options, this.batchRequest),
  612. DomProcessorHelper.processSrcset(this.doc.querySelectorAll("img[srcset], source[srcset]"), "srcset", PREFIX_DATA_URI_IMAGE, this.baseURI, this.options, this.batchRequest)
  613. ];
  614. if (!this.options.removeAudioSrc) {
  615. 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));
  616. }
  617. if (!this.options.removeVideoSrc) {
  618. 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));
  619. }
  620. await resourcePromises;
  621. if (this.options.removeAlternativeImages) {
  622. const shortcutIcons = Array.from(this.doc.querySelectorAll("link[href][rel=\"icon\"], link[href][rel=\"shortcut icon\"]"));
  623. shortcutIcons.sort((linkElement1, linkElement2) => (parseInt(linkElement2.sizes, 10) || 16) - (parseInt(linkElement1.sizes, 10) || 16));
  624. const shortcutIcon = shortcutIcons[0];
  625. if (shortcutIcon) {
  626. this.doc.querySelectorAll("link[href][rel*=\"icon\"]").forEach(linkElement => {
  627. if (linkElement != shortcutIcon) {
  628. linkElement.remove();
  629. }
  630. });
  631. }
  632. }
  633. }
  634. async resolveStylesheetURLs() {
  635. 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 })));
  636. }
  637. async processStylesheets() {
  638. await Promise.all(Array.from(this.doc.querySelectorAll("style")).map(async styleElement => {
  639. this.stats.add("processed", "stylesheets", 1);
  640. styleElement.textContent = await DomProcessorHelper.processStylesheet(this.doc, styleElement.textContent, styleElement.sheet.cssRules, this.baseURI, this.options, this.batchRequest);
  641. }));
  642. }
  643. async processScripts() {
  644. await Promise.all(Array.from(this.doc.querySelectorAll("script[src]")).map(async scriptElement => {
  645. if (scriptElement.src) {
  646. this.stats.add("processed", "scripts", 1);
  647. const scriptContent = await Download.getContent(scriptElement.src, { asDataURI: false, maxResourceSize: this.options.maxResourceSize, maxResourceSizeEnabled: this.options.maxResourceSizeEnabled });
  648. scriptElement.textContent = scriptContent.replace(/<\/script>/gi, "<\\/script>");
  649. }
  650. scriptElement.removeAttribute("src");
  651. }));
  652. }
  653. async resolveFrameURLs() {
  654. if (this.options.framesData) {
  655. const frameElements = Array.from(this.doc.querySelectorAll("iframe, frame, object[type=\"text/html\"][data]"));
  656. await Promise.all(frameElements.map(async frameElement => {
  657. DomProcessorHelper.setFrameEmptySrc(frameElement);
  658. frameElement.setAttribute("sandbox", "allow-scripts allow-same-origin");
  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. DomProcessorHelper.setFrameContent(frameElement, pageData.content);
  703. this.stats.addAll(pageData);
  704. } else {
  705. this.stats.add("discarded", "frames", 1);
  706. }
  707. }
  708. }
  709. }));
  710. }
  711. }
  712. async resolveHtmlImportURLs() {
  713. const linkElements = Array.from(this.doc.querySelectorAll("link[rel=import][href]"));
  714. if (!this.relImportProcessors) {
  715. this.relImportProcessors = new Map();
  716. }
  717. await Promise.all(linkElements.map(async linkElement => {
  718. const resourceURL = linkElement.href;
  719. linkElement.removeAttribute("href");
  720. const options = Object.create(this.options);
  721. options.insertSingleFileComment = false;
  722. options.insertFaviconLink = false;
  723. options.doc = null;
  724. options.win = null;
  725. options.url = resourceURL;
  726. if (!DomUtil.testIgnoredPath(resourceURL) && DomUtil.testValidPath(resourceURL, this.baseURI, this.options.url)) {
  727. const processor = new PageProcessor(options);
  728. this.relImportProcessors.set(linkElement, processor);
  729. await processor.loadPage();
  730. return processor.initialize();
  731. }
  732. }));
  733. }
  734. async processHtmlImports() {
  735. const linkElements = Array.from(this.doc.querySelectorAll("link[rel=import][href]"));
  736. await Promise.all(linkElements.map(async linkElement => {
  737. const processor = this.relImportProcessors.get(linkElement);
  738. if (processor) {
  739. this.stats.add("processed", "HTML imports", 1);
  740. this.relImportProcessors.delete(linkElement);
  741. const pageData = await processor.getPageData();
  742. linkElement.setAttribute("href", "data:text/html," + pageData.content);
  743. this.stats.addAll(pageData);
  744. } else {
  745. this.stats.add("discarded", "HTML imports", 1);
  746. }
  747. }));
  748. }
  749. resolveStyleAttributeURLs() {
  750. Array.from(this.doc.querySelectorAll("[style]")).map(element => element.setAttribute("style", DomProcessorHelper.resolveStylesheetURLs(element.getAttribute("style"), this.baseURI, this.options)));
  751. }
  752. async processStyleAttributes() {
  753. 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))));
  754. }
  755. async resolveLinkedStylesheetURLs() {
  756. await Promise.all(Array.from(this.doc.querySelectorAll("link[rel*=stylesheet]")).map(async linkElement => {
  757. const options = { maxResourceSize: this.options.maxResourceSize, maxResourceSizeEnabled: this.options.maxResourceSizeEnabled, charSet: this.charSet };
  758. const stylesheetContent = await DomProcessorHelper.resolveLinkStylesheetURLs(linkElement.href, this.baseURI, options);
  759. const styleElement = this.doc.createElement("style");
  760. styleElement.media = linkElement.media;
  761. styleElement.textContent = stylesheetContent;
  762. linkElement.parentElement.replaceChild(styleElement, linkElement);
  763. }));
  764. }
  765. }
  766. // ---------
  767. // DomHelper
  768. // ---------
  769. const REGEXP_AMP = /&/g;
  770. const REGEXP_NBSP = /\u00a0/g;
  771. const REGEXP_START_TAG = /</g;
  772. const REGEXP_END_TAG = />/g;
  773. const REGEXP_URL_HASH = /(#.+?)$/;
  774. const PREFIX_DATA_URI_IMAGE = "data:image/";
  775. const PREFIX_DATA_URI_AUDIO = "data:audio/";
  776. const PREFIX_DATA_URI_VIDEO = "data:video/";
  777. const PREFIX_DATA_URI_IMAGE_SVG = "data:image/svg+xml";
  778. const PREFIX_DATA_URI_NO_MIMETYPE = "data:;";
  779. const PREFIX_DATA_URI_OCTET_STREAM = "data:application/octet-stream";
  780. const SINGLE_FILE_VARIABLE_NAME_PREFIX = "--sf-img-";
  781. class DomProcessorHelper {
  782. static async getFilename(options, content) {
  783. let filename = options.filenameTemplate;
  784. const date = new Date();
  785. const url = new URL(options.url);
  786. filename = await DomUtil.evalTemplateVariable(filename, "page-title", () => options.title || "No title");
  787. filename = await DomUtil.evalTemplateVariable(filename, "page-language", () => options.info.lang || "No language");
  788. filename = await DomUtil.evalTemplateVariable(filename, "page-description", () => options.info.description || "No description");
  789. filename = await DomUtil.evalTemplateVariable(filename, "page-author", () => options.info.author || "No author");
  790. filename = await DomUtil.evalTemplateVariable(filename, "page-creator", () => options.info.creator || "No creator");
  791. filename = await DomUtil.evalTemplateVariable(filename, "page-publisher", () => options.info.publisher || "No publisher");
  792. filename = await DomUtil.evalTemplateVariable(filename, "datetime-iso", () => date.toISOString());
  793. filename = await DomUtil.evalTemplateVariable(filename, "date-iso", () => date.toISOString().split("T")[0]);
  794. filename = await DomUtil.evalTemplateVariable(filename, "time-iso", () => date.toISOString().split("T")[1].split("Z")[0]);
  795. filename = await DomUtil.evalTemplateVariable(filename, "date-locale", () => date.toLocaleDateString());
  796. filename = await DomUtil.evalTemplateVariable(filename, "time-locale", () => date.toLocaleTimeString());
  797. filename = await DomUtil.evalTemplateVariable(filename, "day-locale", () => String(date.getDate()).padStart(2, "0"));
  798. filename = await DomUtil.evalTemplateVariable(filename, "month-locale", () => String(date.getMonth() + 1).padStart(2, "0"));
  799. filename = await DomUtil.evalTemplateVariable(filename, "year-locale", () => String(date.getFullYear()));
  800. filename = await DomUtil.evalTemplateVariable(filename, "datetime-locale", () => date.toLocaleString());
  801. filename = await DomUtil.evalTemplateVariable(filename, "datetime-utc", () => date.toUTCString());
  802. filename = await DomUtil.evalTemplateVariable(filename, "day-utc", () => String(date.getUTCDate()).padStart(2, "0"));
  803. filename = await DomUtil.evalTemplateVariable(filename, "month-utc", () => String(date.getUTCMonth() + 1).padStart(2, "0"));
  804. filename = await DomUtil.evalTemplateVariable(filename, "year-utc", () => String(date.getUTCFullYear()));
  805. filename = await DomUtil.evalTemplateVariable(filename, "hours-locale", () => String(date.getHours()).padStart(2, "0"));
  806. filename = await DomUtil.evalTemplateVariable(filename, "minutes-locale", () => String(date.getMinutes()).padStart(2, "0"));
  807. filename = await DomUtil.evalTemplateVariable(filename, "seconds-locale", () => String(date.getSeconds()).padStart(2, "0"));
  808. filename = await DomUtil.evalTemplateVariable(filename, "hours-utc", () => String(date.getUTCHours()).padStart(2, "0"));
  809. filename = await DomUtil.evalTemplateVariable(filename, "minutes-utc", () => String(date.getUTCMinutes()).padStart(2, "0"));
  810. filename = await DomUtil.evalTemplateVariable(filename, "seconds-utc", () => String(date.getUTCSeconds()).padStart(2, "0"));
  811. filename = await DomUtil.evalTemplateVariable(filename, "url-hash", () => url.hash.substring(1));
  812. filename = await DomUtil.evalTemplateVariable(filename, "url-host", () => url.host.replace(/\/$/, ""));
  813. filename = await DomUtil.evalTemplateVariable(filename, "url-hostname", () => url.hostname.replace(/\/$/, ""));
  814. filename = await DomUtil.evalTemplateVariable(filename, "url-href", () => url.href);
  815. filename = await DomUtil.evalTemplateVariable(filename, "url-password", () => url.password);
  816. filename = await DomUtil.evalTemplateVariable(filename, "url-pathname", () => url.pathname.replace(/^\//, "").replace(/\/$/, ""), true);
  817. filename = await DomUtil.evalTemplateVariable(filename, "url-port", () => url.port);
  818. filename = await DomUtil.evalTemplateVariable(filename, "url-protocol", () => url.protocol);
  819. filename = await DomUtil.evalTemplateVariable(filename, "url-search", () => url.search.substring(1));
  820. filename = await DomUtil.evalTemplateVariable(filename, "url-username", () => url.username);
  821. filename = await DomUtil.evalTemplateVariable(filename, "tab-id", () => String(options.tabId || "No tab id"));
  822. filename = await DomUtil.evalTemplateVariable(filename, "url-last-segment", () => DomUtil.getLastSegment(url));
  823. filename = await DomUtil.evalTemplateVariable(filename, "digest-sha-256", async () => DOM.digest("SHA-256", content));
  824. filename = await DomUtil.evalTemplateVariable(filename, "digest-sha-384", async () => DOM.digest("SHA-384", content));
  825. filename = await DomUtil.evalTemplateVariable(filename, "digest-sha-512", async () => DOM.digest("SHA-512", content));
  826. filename = filename.replace(/[~\\?%*:|"<>\x00-\x1f\x7F]+/g, "_"); // eslint-disable-line no-control-regex
  827. filename = filename.replace(/\.\.\//g, "").replace(/^\/+/, "").replace(/\/+/g, "/").replace(/\/$/, "");
  828. if (!options.backgroundSave) {
  829. filename = filename.replace(/\//g, "_");
  830. }
  831. if (filename.length > 192) {
  832. const extensionMatch = filename.match(/(\.[^.]{3,4})$/);
  833. const extension = extensionMatch && extensionMatch[0] && extensionMatch[0].length > 1 ? extensionMatch[0] : "";
  834. filename = filename.substring(0, 192 - extension.length) + "…" + extension;
  835. }
  836. if (!filename) {
  837. filename = "Unnamed page";
  838. }
  839. return filename;
  840. }
  841. static setBackgroundImage(element, url, style) {
  842. element.style.setProperty("background-blend-mode", "normal", "important");
  843. element.style.setProperty("background-clip", "content-box", "important");
  844. element.style.setProperty("background-position", style && style["background-position"] ? style["background-position"] : "center", "important");
  845. element.style.setProperty("background-color", style && style["background-color"] ? style["background-color"] : "transparent", "important");
  846. element.style.setProperty("background-image", url, "important");
  847. element.style.setProperty("background-size", style && style["background-size"] ? style["background-size"] : "100% 100%", "important");
  848. element.style.setProperty("background-origin", "content-box", "important");
  849. element.style.setProperty("background-repeat", "no-repeat", "important");
  850. }
  851. static setFrameEmptySrc(frameElement) {
  852. if (frameElement.tagName == "OBJECT") {
  853. frameElement.setAttribute("data", "data:text/html,");
  854. } else {
  855. frameElement.setAttribute("srcdoc", "");
  856. frameElement.removeAttribute("src");
  857. }
  858. }
  859. static setFrameContent(frameElement, content) {
  860. if (frameElement.tagName == "OBJECT") {
  861. frameElement.setAttribute("data", "data:text/html," + content);
  862. } else {
  863. frameElement.setAttribute("srcdoc", content);
  864. frameElement.removeAttribute("src");
  865. }
  866. }
  867. static isolateElements(rootElement) {
  868. rootElement.querySelectorAll("*:not(style)").forEach(element => {
  869. if (element.getAttribute(SELECTED_CONTENT_ATTRIBUTE_NAME) == "") {
  870. element.removeAttribute(SELECTED_CONTENT_ATTRIBUTE_NAME);
  871. } else if (!element.querySelector("[" + SELECTED_CONTENT_ATTRIBUTE_NAME + "]")) {
  872. element.remove();
  873. }
  874. });
  875. isolateParentElements(rootElement.parentElement, rootElement);
  876. function isolateParentElements(parentElement, element) {
  877. let elementFound = false;
  878. Array.from(parentElement.childNodes).forEach(node => {
  879. elementFound = elementFound || (node == element);
  880. if (node != element && node.tagName != "STYLE" && node.tagName != "LINK") {
  881. if (elementFound) {
  882. node.remove();
  883. } else {
  884. node.hidden = true;
  885. if (node.childNodes && node.childNodes.length) {
  886. Array.from(node.childNodes).forEach(node => node.remove());
  887. }
  888. }
  889. }
  890. });
  891. element = element.parentElement;
  892. if (element && element.parentElement && element.parentElement.tagName != "HTML") {
  893. isolateParentElements(element.parentElement, element);
  894. }
  895. }
  896. }
  897. static async resolveImportURLs(stylesheetContent, baseURI, options) {
  898. stylesheetContent = DomProcessorHelper.resolveStylesheetURLs(stylesheetContent, baseURI, options);
  899. stylesheetContent = DomUtil.removeCssComments(stylesheetContent);
  900. const imports = DomUtil.getImportFunctions(stylesheetContent);
  901. await Promise.all(imports.map(async cssImport => {
  902. const match = DomUtil.matchImport(cssImport);
  903. if (match) {
  904. let resourceURL = DomUtil.normalizeURL(match.resourceURL);
  905. if (!DomUtil.testIgnoredPath(resourceURL) && DomUtil.testValidPath(resourceURL, baseURI, options.url)) {
  906. resourceURL = new URL(match.resourceURL, baseURI).href;
  907. if (DomUtil.testValidURL(resourceURL, baseURI, options.url)) {
  908. let importedStylesheetContent = await Download.getContent(resourceURL, { asDataURI: false, maxResourceSize: options.maxResourceSize, maxResourceSizeEnabled: options.maxResourceSizeEnabled });
  909. importedStylesheetContent = DomUtil.wrapMediaQuery(importedStylesheetContent, match.media);
  910. if (stylesheetContent.includes(cssImport)) {
  911. importedStylesheetContent = await DomProcessorHelper.resolveImportURLs(importedStylesheetContent, resourceURL, options);
  912. stylesheetContent = stylesheetContent.replace(DomUtil.getRegExp(cssImport), importedStylesheetContent);
  913. }
  914. }
  915. }
  916. }
  917. }));
  918. return stylesheetContent;
  919. }
  920. static resolveStylesheetURLs(stylesheetContent, baseURI, options) {
  921. const urlFunctions = DomUtil.getUrlFunctions(stylesheetContent);
  922. urlFunctions.map(urlFunction => {
  923. const originalResourceURL = DomUtil.matchURL(urlFunction);
  924. const resourceURL = DomUtil.normalizeURL(originalResourceURL);
  925. if (!DomUtil.testIgnoredPath(resourceURL)) {
  926. if (DomUtil.testValidPath(resourceURL, baseURI, options.url)) {
  927. const resolvedURL = new URL(resourceURL, baseURI).href;
  928. if (DomUtil.testValidURL(resolvedURL, baseURI, options.url) && resourceURL != resolvedURL && stylesheetContent.includes(urlFunction)) {
  929. stylesheetContent = stylesheetContent.replace(DomUtil.getRegExp(urlFunction), urlFunction.replace(originalResourceURL, resolvedURL));
  930. }
  931. }
  932. } else {
  933. if (resourceURL.startsWith(DATA_URI_PREFIX)) {
  934. const escapedResourceURL = resourceURL.replace(REGEXP_AMP, "&amp;").replace(REGEXP_NBSP, "&nbsp;").replace(REGEXP_START_TAG, "&lt;").replace(REGEXP_END_TAG, "&gt;");
  935. if (escapedResourceURL != resourceURL && stylesheetContent.includes(urlFunction)) {
  936. stylesheetContent = stylesheetContent.replace(DomUtil.getRegExp(urlFunction), urlFunction.replace(originalResourceURL, escapedResourceURL));
  937. }
  938. }
  939. }
  940. });
  941. return stylesheetContent;
  942. }
  943. static async resolveLinkStylesheetURLs(resourceURL, baseURI, options) {
  944. resourceURL = DomUtil.normalizeURL(resourceURL);
  945. if (resourceURL && resourceURL != baseURI && resourceURL != ABOUT_BLANK_URI) {
  946. let stylesheetContent = await Download.getContent(resourceURL, { asDataURI: false, maxResourceSize: options.maxResourceSize, maxResourceSizeEnabled: options.maxResourceSizeEnabled, charSet: options.charSet });
  947. stylesheetContent = await DomProcessorHelper.resolveImportURLs(stylesheetContent, resourceURL, options);
  948. return stylesheetContent;
  949. }
  950. }
  951. static async processStylesheet(doc, stylesheetContent, cssRules, baseURI, options, batchRequest) {
  952. let sheetContent = "", variablesInfo = { index: 0, cssText: "" };
  953. const urlFunctions = DomUtil.getUrlFunctions(stylesheetContent);
  954. const resourceInfos = new Map();
  955. await Promise.all(urlFunctions.map(async urlFunction => {
  956. const originalResourceURL = DomUtil.matchURL(urlFunction);
  957. const resourceURL = DomUtil.normalizeURL(originalResourceURL);
  958. if (!DomUtil.testIgnoredPath(resourceURL)) {
  959. if (DomUtil.testValidURL(resourceURL, baseURI, options.url) && stylesheetContent.includes(urlFunction)) {
  960. const { content, indexResource, duplicate } = await batchRequest.addURL(resourceURL);
  961. urlFunction = "url(" + JSON.stringify(resourceURL) + ")";
  962. const regExpUrlFunction = DomUtil.getRegExp(urlFunction);
  963. if (duplicate && options.groupDuplicateImages) {
  964. resourceInfos.set(resourceURL, { regExpUrlFunction, indexResource, dataURI: content, variableName: "var(" + SINGLE_FILE_VARIABLE_NAME_PREFIX + indexResource + ")" });
  965. } else {
  966. resourceInfos.set(resourceURL, { regExpUrlFunction, indexResource, dataURI: content });
  967. }
  968. }
  969. }
  970. }));
  971. const rulesContent = processRules(cssRules);
  972. if (variablesInfo.cssText) {
  973. sheetContent += ":root{" + variablesInfo.cssText + "}";
  974. }
  975. return sheetContent + rulesContent;
  976. function processRules(cssRules) {
  977. let rulesContent = "";
  978. Array.from(cssRules).forEach(cssRule => {
  979. if (cssRule.type == CSSRule.MEDIA_RULE) {
  980. const mediaRulesContent = processRules(cssRule.cssRules);
  981. rulesContent += "@media " + Array.from(cssRule.media).join(",") + "{" + mediaRulesContent + "}";
  982. } else if (cssRule.type == CSSRule.STYLE_RULE) {
  983. rulesContent += processURLFunctions(cssRule.cssText);
  984. } else {
  985. rulesContent += processURLFunctions(cssRule.cssText, true);
  986. }
  987. });
  988. return rulesContent;
  989. }
  990. function processURLFunctions(cssText, preventGrouping) {
  991. const urlFunctions = DomUtil.getUrlFunctions(cssText);
  992. urlFunctions.forEach(urlFunction => {
  993. const originalResourceURL = DomUtil.matchURL(urlFunction);
  994. const resourceURL = DomUtil.normalizeURL(originalResourceURL);
  995. if (!DomUtil.testIgnoredPath(resourceURL)) {
  996. if (DomUtil.testValidURL(resourceURL, baseURI, options.url) && cssText.includes(urlFunction)) {
  997. const resourceInfo = resourceInfos.get(resourceURL);
  998. if (options.groupDuplicateImages && resourceInfo.variableName && !preventGrouping) {
  999. cssText = cssText.replace(resourceInfo.regExpUrlFunction, resourceInfo.variableName);
  1000. DomUtil.insertVariable(doc, resourceInfo.indexResource, resourceInfo.dataURI, options);
  1001. } else {
  1002. cssText = cssText.replace(resourceInfo.regExpUrlFunction, urlFunction.replace(originalResourceURL, resourceInfo.dataURI));
  1003. }
  1004. }
  1005. }
  1006. });
  1007. return cssText;
  1008. }
  1009. }
  1010. static async processAttribute(doc, resourceElements, attributeName, prefixDataURI, baseURI, options, batchRequest, processDuplicates, removeElementIfMissing) {
  1011. await Promise.all(Array.from(resourceElements).map(async resourceElement => {
  1012. let resourceURL = resourceElement.getAttribute(attributeName);
  1013. resourceURL = DomUtil.normalizeURL(resourceURL);
  1014. if (!DomUtil.testIgnoredPath(resourceURL)) {
  1015. resourceElement.setAttribute(attributeName, EMPTY_IMAGE);
  1016. if (DomUtil.testValidPath(resourceURL, baseURI, options.url)) {
  1017. resourceURL = new URL(resourceURL, baseURI).href;
  1018. if (DomUtil.testValidURL(resourceURL, baseURI, options.url)) {
  1019. const { content, indexResource, duplicate } = await batchRequest.addURL(resourceURL);
  1020. if (removeElementIfMissing && content == EMPTY_DATA_URI) {
  1021. resourceElement.remove();
  1022. } else {
  1023. if (content.startsWith(prefixDataURI) || content.startsWith(PREFIX_DATA_URI_NO_MIMETYPE) || content.startsWith(PREFIX_DATA_URI_OCTET_STREAM)) {
  1024. if (processDuplicates && duplicate && options.groupDuplicateImages && !content.startsWith(PREFIX_DATA_URI_IMAGE_SVG) && DomUtil.replaceImageSource(resourceElement, SINGLE_FILE_VARIABLE_NAME_PREFIX + indexResource, options)) {
  1025. DomUtil.insertVariable(doc, indexResource, content, options);
  1026. } else {
  1027. resourceElement.setAttribute(attributeName, content);
  1028. }
  1029. }
  1030. }
  1031. }
  1032. }
  1033. }
  1034. }));
  1035. }
  1036. static async processXLinks(resourceElements, baseURI, options, batchRequest) {
  1037. const attributeName = "xlink:href";
  1038. await Promise.all(Array.from(resourceElements).map(async resourceElement => {
  1039. const originalResourceURL = resourceElement.getAttribute(attributeName);
  1040. let resourceURL = DomUtil.normalizeURL(originalResourceURL);
  1041. if (DomUtil.testValidPath(resourceURL, baseURI, options.url) && !DomUtil.testIgnoredPath(resourceURL)) {
  1042. resourceElement.setAttribute(attributeName, EMPTY_IMAGE);
  1043. resourceURL = new URL(resourceURL, baseURI).href;
  1044. if (DomUtil.testValidURL(resourceURL, baseURI, options.url)) {
  1045. try {
  1046. const { content } = await batchRequest.addURL(resourceURL, false);
  1047. const DOMParser = DOM.getParser();
  1048. if (DOMParser) {
  1049. let svgDoc = new DOMParser().parseFromString(content, "image/svg+xml");
  1050. const hashMatch = originalResourceURL.match(REGEXP_URL_HASH);
  1051. if (hashMatch && hashMatch[0]) {
  1052. const symbolElement = svgDoc.querySelector(hashMatch[0]);
  1053. if (symbolElement) {
  1054. resourceElement.setAttribute(attributeName, hashMatch[0]);
  1055. resourceElement.parentElement.insertBefore(symbolElement, resourceElement.parentElement.firstChild);
  1056. }
  1057. } else {
  1058. resourceElement.setAttribute(attributeName, "data:image/svg+xml," + content);
  1059. }
  1060. } else {
  1061. resourceElement.setAttribute(attributeName, "data:image/svg+xml," + content);
  1062. }
  1063. } catch (error) {
  1064. /* ignored */
  1065. }
  1066. }
  1067. } else if (resourceURL == options.url) {
  1068. resourceElement.setAttribute(attributeName, originalResourceURL.substring(resourceURL.length));
  1069. }
  1070. }));
  1071. }
  1072. static async processSrcset(resourceElements, attributeName, prefixDataURI, baseURI, options, batchRequest) {
  1073. await Promise.all(Array.from(resourceElements).map(async resourceElement => {
  1074. const srcset = DOM.parseSrcset(resourceElement.getAttribute(attributeName));
  1075. const srcsetValues = await Promise.all(srcset.map(async srcsetValue => {
  1076. let resourceURL = DomUtil.normalizeURL(srcsetValue.url);
  1077. if (!DomUtil.testIgnoredPath(resourceURL)) {
  1078. if (DomUtil.testValidPath(resourceURL, baseURI, options.url)) {
  1079. resourceURL = new URL(resourceURL, baseURI).href;
  1080. if (DomUtil.testValidURL(resourceURL, baseURI, options.url)) {
  1081. const { content } = await batchRequest.addURL(resourceURL);
  1082. if (!content.startsWith(prefixDataURI) && !content.startsWith(PREFIX_DATA_URI_NO_MIMETYPE) && !content.startsWith(PREFIX_DATA_URI_OCTET_STREAM)) {
  1083. resourceElement.setAttribute(attributeName, EMPTY_IMAGE);
  1084. }
  1085. return content + (srcsetValue.w ? " " + srcsetValue.w + "w" : srcsetValue.d ? " " + srcsetValue.d + "x" : "");
  1086. } else {
  1087. return "";
  1088. }
  1089. } else {
  1090. return "";
  1091. }
  1092. }
  1093. }));
  1094. resourceElement.setAttribute(attributeName, srcsetValues.join(", "));
  1095. }));
  1096. }
  1097. }
  1098. // -------
  1099. // DomUtil
  1100. // -------
  1101. const DATA_URI_PREFIX = "data:";
  1102. const BLOB_URI_PREFIX = "blob:";
  1103. const HTTP_URI_PREFIX = /^https?:\/\//;
  1104. const FILE_URI_PREFIX = /^file:\/\//;
  1105. const EMPTY_URL = /^https?:\/\/+\s*$/;
  1106. const ABOUT_BLANK_URI = "about:blank";
  1107. const NOT_EMPTY_URL = /^(https?|file):\/\/.+/;
  1108. const REGEXP_URL_FN = /(url\s*\(\s*'(.*?)'\s*\))|(url\s*\(\s*"(.*?)"\s*\))|(url\s*\(\s*(.*?)\s*\))/gi;
  1109. const REGEXP_URL_SIMPLE_QUOTES_FN = /^url\s*\(\s*'(.*?)'\s*\)$/i;
  1110. const REGEXP_URL_DOUBLE_QUOTES_FN = /^url\s*\(\s*"(.*?)"\s*\)$/i;
  1111. const REGEXP_URL_NO_QUOTES_FN = /^url\s*\(\s*(.*?)\s*\)$/i;
  1112. 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;
  1113. const REGEXP_IMPORT_URL_SIMPLE_QUOTES_FN = /@import\s*url\s*\(\s*'(.*?)'\s*\)\s*(.*?)(;|$|})/i;
  1114. const REGEXP_IMPORT_URL_DOUBLE_QUOTES_FN = /@import\s*url\s*\(\s*"(.*?)"\s*\)\s*(.*?)(;|$|})/i;
  1115. const REGEXP_IMPORT_URL_NO_QUOTES_FN = /@import\s*url\s*\(\s*(.*?)\s*\)\s*(.*?)(;|$|})/i;
  1116. const REGEXP_IMPORT_SIMPLE_QUOTES_FN = /@import\s*'(.*?)'\s*(.*?)(;|$|})/i;
  1117. const REGEXP_IMPORT_DOUBLE_QUOTES_FN = /@import\s*"(.*?)"\s*(.*?)(;|$|})/i;
  1118. const REGEXP_IMPORT_NO_QUOTES_FN = /@import\s*(.*?)\s*(.*?)(;|$|})/i;
  1119. const REGEXP_ESCAPE = /([{}()^$&.*?/+|[\\\\]|\]|-)/g;
  1120. class DomUtil {
  1121. static normalizeURL(url) {
  1122. if (!url || url.startsWith(DATA_URI_PREFIX)) {
  1123. return url;
  1124. } else {
  1125. return url.split("#")[0];
  1126. }
  1127. }
  1128. static async evalTemplateVariable(template, variableName, valueGetter, dontReplaceSlash) {
  1129. const replaceRegExp = new RegExp("{\\s*" + variableName + "\\s*}", "g");
  1130. if (template.match(replaceRegExp)) {
  1131. let value = await valueGetter();
  1132. if (!dontReplaceSlash) {
  1133. value = value.replace(/\/+/g, "_");
  1134. }
  1135. return template.replace(replaceRegExp, value);
  1136. }
  1137. return template;
  1138. }
  1139. static getLastSegment(url) {
  1140. let lastSegmentMatch = url.pathname.match(/\/([^/]+)$/), lastSegment = lastSegmentMatch && lastSegmentMatch[0];
  1141. if (!lastSegment) {
  1142. lastSegmentMatch = url.href.match(/([^/]+)\/?$/);
  1143. lastSegment = lastSegmentMatch && lastSegmentMatch[0];
  1144. }
  1145. if (!lastSegment) {
  1146. lastSegmentMatch = lastSegment.match(/(.*)<\.[^.]+$/);
  1147. lastSegment = lastSegmentMatch && lastSegmentMatch[0];
  1148. }
  1149. if (!lastSegment) {
  1150. lastSegment = url.hostname.replace(/\/+/g, "_").replace(/\/$/, "");
  1151. }
  1152. lastSegment.replace(/\/$/, "").replace(/^\//, "");
  1153. return lastSegment;
  1154. }
  1155. static getRegExp(string) {
  1156. return new RegExp(string.replace(REGEXP_ESCAPE, "\\$1"), "gi");
  1157. }
  1158. static getUrlFunctions(stylesheetContent) {
  1159. return Array.from(new Set(stylesheetContent.match(REGEXP_URL_FN) || []));
  1160. }
  1161. static getImportFunctions(stylesheetContent) {
  1162. return stylesheetContent.match(REGEXP_IMPORT_FN) || [];
  1163. }
  1164. static matchURL(stylesheetContent) {
  1165. const match = stylesheetContent.match(REGEXP_URL_SIMPLE_QUOTES_FN) ||
  1166. stylesheetContent.match(REGEXP_URL_DOUBLE_QUOTES_FN) ||
  1167. stylesheetContent.match(REGEXP_URL_NO_QUOTES_FN);
  1168. return match && match[1];
  1169. }
  1170. static testIgnoredPath(resourceURL) {
  1171. return resourceURL && (resourceURL.startsWith(DATA_URI_PREFIX) || resourceURL.startsWith(BLOB_URI_PREFIX) || resourceURL == ABOUT_BLANK_URI);
  1172. }
  1173. static testValidPath(resourceURL, baseURI, docURL) {
  1174. return resourceURL && resourceURL != baseURI && resourceURL != docURL && !resourceURL.match(EMPTY_URL);
  1175. }
  1176. static testValidURL(resourceURL, baseURI, docURL) {
  1177. return DomUtil.testValidPath(resourceURL, baseURI, docURL) && (resourceURL.match(HTTP_URI_PREFIX) || resourceURL.match(FILE_URI_PREFIX)) && resourceURL.match(NOT_EMPTY_URL);
  1178. }
  1179. static matchImport(stylesheetContent) {
  1180. const match = stylesheetContent.match(REGEXP_IMPORT_URL_SIMPLE_QUOTES_FN) ||
  1181. stylesheetContent.match(REGEXP_IMPORT_URL_DOUBLE_QUOTES_FN) ||
  1182. stylesheetContent.match(REGEXP_IMPORT_URL_NO_QUOTES_FN) ||
  1183. stylesheetContent.match(REGEXP_IMPORT_SIMPLE_QUOTES_FN) ||
  1184. stylesheetContent.match(REGEXP_IMPORT_DOUBLE_QUOTES_FN) ||
  1185. stylesheetContent.match(REGEXP_IMPORT_NO_QUOTES_FN);
  1186. if (match) {
  1187. const [, resourceURL, media] = match;
  1188. return { resourceURL, media };
  1189. }
  1190. }
  1191. static removeCssComments(stylesheetContent) {
  1192. let start, end;
  1193. do {
  1194. start = stylesheetContent.indexOf("/*");
  1195. end = stylesheetContent.indexOf("*/", start + 2);
  1196. if (start != -1 && end != -1) {
  1197. stylesheetContent = stylesheetContent.substring(0, start) + stylesheetContent.substr(end + 2);
  1198. }
  1199. } while (start != -1 && end != -1);
  1200. return stylesheetContent;
  1201. }
  1202. static wrapMediaQuery(stylesheetContent, mediaQuery) {
  1203. if (mediaQuery) {
  1204. return "@media " + mediaQuery + "{ " + stylesheetContent + " }";
  1205. } else {
  1206. return stylesheetContent;
  1207. }
  1208. }
  1209. static insertVariable(doc, indexResource, content, options) {
  1210. const sheetAttributeName = DOM.sheetAttributeName(options.sessionId);
  1211. let styleElement = doc.querySelector("style[" + sheetAttributeName + "]"), insertedVariables;
  1212. if (!styleElement) {
  1213. styleElement = doc.createElement("style");
  1214. if (doc.head.firstChild) {
  1215. doc.head.insertBefore(styleElement, doc.head.firstChild);
  1216. } else {
  1217. doc.head.appendChild(styleElement);
  1218. }
  1219. styleElement.setAttribute(sheetAttributeName, "[]");
  1220. insertedVariables = [];
  1221. } else {
  1222. insertedVariables = JSON.parse(styleElement.getAttribute(sheetAttributeName));
  1223. }
  1224. if (!insertedVariables.includes(indexResource)) {
  1225. insertedVariables.push(indexResource);
  1226. styleElement.textContent = styleElement.textContent + `:root{${SINGLE_FILE_VARIABLE_NAME_PREFIX + indexResource}:url("${content}")}`;
  1227. styleElement.setAttribute(sheetAttributeName, JSON.stringify(insertedVariables));
  1228. }
  1229. }
  1230. static replaceImageSource(imgElement, variableName, options) {
  1231. const dataAttributeName = DOM.imagesAttributeName(options.sessionId);
  1232. if (imgElement.getAttribute(dataAttributeName) != null) {
  1233. const imgData = options.imageData[Number(imgElement.getAttribute(dataAttributeName))];
  1234. if (imgData.replaceable) {
  1235. 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>`);
  1236. const backgroundStyle = {};
  1237. const backgroundSize = (imgData.objectFit == "content" || imgData.objectFit == "cover") && imgData.objectFit;
  1238. if (backgroundSize) {
  1239. backgroundStyle["background-size"] = imgData.objectFit;
  1240. }
  1241. if (imgData.objectPosition) {
  1242. backgroundStyle["background-position"] = imgData.objectPosition;
  1243. }
  1244. if (imgData.backgroundColor) {
  1245. backgroundStyle["background-color"] = imgData.backgroundColor;
  1246. }
  1247. DomProcessorHelper.setBackgroundImage(imgElement, "var(" + variableName + ")", backgroundStyle);
  1248. imgElement.removeAttribute(dataAttributeName);
  1249. return true;
  1250. }
  1251. }
  1252. }
  1253. }
  1254. function log(...args) {
  1255. console.log("S-File <core> ", ...args); // eslint-disable-line no-console
  1256. }
  1257. // -----
  1258. // Stats
  1259. // -----
  1260. const STATS_DEFAULT_VALUES = {
  1261. discarded: {
  1262. "HTML bytes": 0,
  1263. "hidden elements": 0,
  1264. "HTML imports": 0,
  1265. scripts: 0,
  1266. objects: 0,
  1267. "audio sources": 0,
  1268. "video sources": 0,
  1269. frames: 0,
  1270. "CSS rules": 0,
  1271. canvas: 0,
  1272. stylesheets: 0,
  1273. resources: 0,
  1274. medias: 0
  1275. },
  1276. processed: {
  1277. "HTML bytes": 0,
  1278. "hidden elements": 0,
  1279. "HTML imports": 0,
  1280. scripts: 0,
  1281. objects: 0,
  1282. "audio sources": 0,
  1283. "video sources": 0,
  1284. frames: 0,
  1285. "CSS rules": 0,
  1286. canvas: 0,
  1287. stylesheets: 0,
  1288. resources: 0,
  1289. medias: 0
  1290. }
  1291. };
  1292. class Stats {
  1293. constructor(options) {
  1294. this.options = options;
  1295. if (options.displayStats) {
  1296. this.data = JSON.parse(JSON.stringify(STATS_DEFAULT_VALUES));
  1297. }
  1298. }
  1299. set(type, subType, value) {
  1300. if (this.options.displayStats) {
  1301. this.data[type][subType] = value;
  1302. }
  1303. }
  1304. add(type, subType, value) {
  1305. if (this.options.displayStats) {
  1306. this.data[type][subType] += value;
  1307. }
  1308. }
  1309. addAll(pageData) {
  1310. if (this.options.displayStats) {
  1311. Object.keys(this.data.discarded).forEach(key => this.add("discarded", key, pageData.stats.discarded[key] || 0));
  1312. Object.keys(this.data.processed).forEach(key => this.add("processed", key, pageData.stats.processed[key] || 0));
  1313. }
  1314. }
  1315. }
  1316. return { getClass };
  1317. })();