single-file-core.js 70 KB

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