single-file-core.js 67 KB

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