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(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. const promise = this.executeTask(task);
  218. promise.then(() => this.onprogress(new ProgressEvent(STAGE_TASK_ENDED, { pageURL: this.options.url, step, task: task.action, frame })));
  219. if (DEBUG) {
  220. promise.then(() => log(" // ENDED task =", task.action, "delay =", Date.now() - startTime));
  221. }
  222. return promise;
  223. }));
  224. } else {
  225. parallelTasksPromise = Promise.resolve();
  226. }
  227. this.onprogress(new ProgressEvent(STAGE_ENDED, { pageURL: this.options.url, step, frame }));
  228. if (DEBUG) {
  229. log("**** ENDED STAGE", step, "****");
  230. }
  231. return parallelTasksPromise;
  232. }
  233. executeTask(task) {
  234. if (!task.option || ((task.option.startsWith("!") && !this.options[task.option]) || this.options[task.option])) {
  235. return this.processor[task.action]();
  236. }
  237. }
  238. }
  239. // --------
  240. // BatchRequest
  241. // --------
  242. class BatchRequest {
  243. constructor() {
  244. this.requests = new Map();
  245. }
  246. async addURL(resourceURL, asDataURI = true) {
  247. return new Promise((resolve, reject) => {
  248. const requestKey = JSON.stringify([resourceURL, asDataURI]);
  249. const resourceRequests = this.requests.get(requestKey);
  250. if (resourceRequests) {
  251. resourceRequests.push({ resolve, reject });
  252. } else {
  253. this.requests.set(requestKey, [{ resolve, reject }]);
  254. }
  255. });
  256. }
  257. getMaxResources() {
  258. return Array.from(this.requests.keys()).length;
  259. }
  260. async run(onloadListener, options) {
  261. const resourceURLs = Array.from(this.requests.keys());
  262. let indexResource = 0;
  263. return Promise.all(resourceURLs.map(async requestKey => {
  264. const [resourceURL, asDataURI] = JSON.parse(requestKey);
  265. const resourceRequests = this.requests.get(requestKey);
  266. try {
  267. const resourceContent = await Download.getContent(resourceURL, { asDataURI, maxResourceSize: options.maxResourceSize, maxResourceSizeEnabled: options.maxResourceSizeEnabled });
  268. indexResource = indexResource + 1;
  269. onloadListener({ index: indexResource, url: resourceURL });
  270. resourceRequests.forEach(resourceRequest => resourceRequest.resolve({ content: resourceContent, indexResource, duplicate: Boolean(resourceRequests.length > 1) }));
  271. } catch (error) {
  272. indexResource = indexResource + 1;
  273. onloadListener({ index: indexResource, url: resourceURL });
  274. resourceRequests.forEach(resourceRequest => resourceRequest.reject(error));
  275. }
  276. this.requests.delete(requestKey);
  277. }));
  278. }
  279. }
  280. // ------------
  281. // DOMProcessor
  282. // ------------
  283. const EMPTY_DATA_URI = "data:base64,";
  284. const EMPTY_IMAGE = "data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==";
  285. const SCRIPT_TAG_FOUND = /<script/gi;
  286. const NOSCRIPT_TAG_FOUND = /<noscript/gi;
  287. class DOMProcessor {
  288. constructor(options, batchRequest) {
  289. this.options = options;
  290. this.stats = new Stats(options);
  291. this.baseURI = DomUtil.normalizeURL(options.baseURI || options.url);
  292. this.batchRequest = batchRequest;
  293. this.stylesheets = new Map();
  294. this.styles = new Map();
  295. this.cssVariables = new Map();
  296. }
  297. initialize() {
  298. this.maxResources = this.batchRequest.getMaxResources();
  299. if (!this.options.removeFrames) {
  300. this.options.framesData.forEach(frameData => this.maxResources += frameData.maxResources || 0);
  301. }
  302. this.stats.set("processed", "resources", this.maxResources);
  303. }
  304. async loadPage(pageContent) {
  305. if (!pageContent || this.options.saveRawPage) {
  306. pageContent = await Download.getContent(this.baseURI, { asDataURI: false, maxResourceSize: this.options.maxResourceSize, maxResourceSizeEnabled: this.options.maxResourceSizeEnabled });
  307. }
  308. this.doc = DOM.createDoc(pageContent, this.baseURI);
  309. this.onEventAttributeNames = DOM.getOnEventAttributeNames(this.doc);
  310. }
  311. async getPageData() {
  312. DOM.postProcessDoc(this.doc, this.options);
  313. const url = new URL(this.baseURI);
  314. if (this.options.insertSingleFileComment) {
  315. const infobarContent = (this.options.infobarContent || "").replace(/\\n/g, "\n").replace(/\\t/g, "\t");
  316. const commentNode = this.doc.createComment("\n Page saved with SingleFile" +
  317. " \n url: " + this.options.url +
  318. " \n saved date: " + new Date() +
  319. (infobarContent ? " \n info: " + infobarContent : "") + "\n");
  320. this.doc.documentElement.insertBefore(commentNode, this.doc.documentElement.firstChild);
  321. }
  322. let size;
  323. if (this.options.displayStats) {
  324. size = DOM.getContentSize(this.doc.documentElement.outerHTML);
  325. }
  326. const content = DOM.serialize(this.doc, this.options.compressHTML);
  327. if (this.options.displayStats) {
  328. const contentSize = DOM.getContentSize(content);
  329. this.stats.set("processed", "HTML bytes", contentSize);
  330. this.stats.add("discarded", "HTML bytes", size - contentSize);
  331. }
  332. let filename = await DomProcessorHelper.evalTemplate(this.options.filenameTemplate, this.options, content);
  333. filename = filename.replace(/[~\\?%*:|"<>\x00-\x1f\x7F]+/g, "_"); // eslint-disable-line no-control-regex
  334. filename = filename.replace(/\.\.\//g, "").replace(/^\/+/, "").replace(/\/+/g, "/").replace(/\/$/, "");
  335. if (!this.options.backgroundSave) {
  336. filename = filename.replace(/\//g, "_");
  337. }
  338. if (filename.length > 192) {
  339. const extensionMatch = filename.match(/(\.[^.]{3,4})$/);
  340. const extension = extensionMatch && extensionMatch[0] && extensionMatch[0].length > 1 ? extensionMatch[0] : "";
  341. filename = filename.substring(0, 192 - extension.length) + "…" + extension;
  342. }
  343. if (!filename) {
  344. filename = "Unnamed page";
  345. }
  346. const matchTitle = this.baseURI.match(/([^/]*)\/?(\.html?.*)$/) || this.baseURI.match(/\/\/([^/]*)\/?$/);
  347. return {
  348. stats: this.stats.data,
  349. title: this.options.title || (this.baseURI && matchTitle ? matchTitle[1] : (url.hostname ? url.hostname : "")),
  350. filename,
  351. content
  352. };
  353. }
  354. removeUnselectedElements() {
  355. const rootElement = this.doc.querySelector("[" + SELECTED_CONTENT_ROOT_ATTRIBUTE_NAME + "]");
  356. if (rootElement) {
  357. DomProcessorHelper.isolateElements(rootElement);
  358. rootElement.removeAttribute(SELECTED_CONTENT_ROOT_ATTRIBUTE_NAME);
  359. rootElement.removeAttribute(SELECTED_CONTENT_ATTRIBUTE_NAME);
  360. }
  361. }
  362. setInputValues() {
  363. this.doc.querySelectorAll("input").forEach(input => {
  364. const value = input.getAttribute(DOM.inputValueAttributeName(this.options.sessionId));
  365. input.setAttribute("value", value || "");
  366. });
  367. this.doc.querySelectorAll("textarea").forEach(textarea => {
  368. const value = textarea.getAttribute(DOM.inputValueAttributeName(this.options.sessionId));
  369. textarea.textContent = value || "";
  370. });
  371. this.doc.querySelectorAll("select").forEach(select => {
  372. select.querySelectorAll("option").forEach(option => {
  373. const selected = option.getAttribute(DOM.inputValueAttributeName(this.options.sessionId)) != null;
  374. if (selected) {
  375. option.setAttribute("selected", "");
  376. }
  377. });
  378. });
  379. }
  380. removeDiscardedResources() {
  381. 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\"])");
  382. this.stats.set("discarded", "objects", objectElements.length);
  383. this.stats.set("processed", "objects", objectElements.length);
  384. objectElements.forEach(element => element.remove());
  385. const replacedAttributeValue = this.doc.querySelectorAll("link[rel~=preconnect], link[rel~=prerender], link[rel~=dns-prefetch], link[rel~=preload], link[rel~=prefetch]");
  386. replacedAttributeValue.forEach(element => {
  387. const relValue = element.getAttribute("rel").replace(/(preconnect|prerender|dns-prefetch|preload|prefetch)/g, "").trim();
  388. if (relValue.length) {
  389. element.setAttribute("rel", relValue);
  390. } else {
  391. element.remove();
  392. }
  393. });
  394. this.doc.querySelectorAll("meta[http-equiv=\"content-security-policy\"]").forEach(element => element.remove());
  395. if (this.options.compressHTML) {
  396. this.doc.querySelectorAll("input[type=hidden]").forEach(element => element.remove());
  397. }
  398. this.doc.querySelectorAll("a[ping]").forEach(element => element.removeAttribute("ping"));
  399. if (this.options.removeScripts) {
  400. this.onEventAttributeNames.forEach(attributeName => this.doc.querySelectorAll("[" + attributeName + "]").forEach(element => element.removeAttribute(attributeName)));
  401. this.doc.querySelectorAll("[href]").forEach(element => {
  402. if (element.href && element.href.match && element.href.match(/^\s*javascript:/)) {
  403. element.setAttribute("href", "");
  404. }
  405. });
  406. this.doc.querySelectorAll("[src]").forEach(element => {
  407. if (element.src && element.src.match(/^\s*javascript:/)) {
  408. element.removeAttribute("src");
  409. }
  410. });
  411. }
  412. const audioSourceElements = this.doc.querySelectorAll("audio[src], audio > source[src]");
  413. this.stats.set("processed", "audio sources", audioSourceElements.length);
  414. if (this.options.removeAudioSrc) {
  415. this.stats.set("discarded", "audio sources", audioSourceElements.length);
  416. audioSourceElements.forEach(element => {
  417. if (element.tagName == "SOURCE") {
  418. element.remove();
  419. } else {
  420. audioSourceElements.forEach(element => element.removeAttribute("src"));
  421. }
  422. });
  423. }
  424. const videoSourceElements = this.doc.querySelectorAll("video[src], video > source[src]");
  425. this.stats.set("processed", "video sources", videoSourceElements.length);
  426. if (this.options.removeVideoSrc) {
  427. this.stats.set("discarded", "video sources", videoSourceElements.length);
  428. videoSourceElements.forEach(element => {
  429. if (element.tagName == "SOURCE") {
  430. element.remove();
  431. } else {
  432. videoSourceElements.forEach(element => element.removeAttribute("src"));
  433. }
  434. });
  435. }
  436. }
  437. async end() {
  438. const metaCharset = this.doc.head.querySelector("meta[charset]");
  439. if (metaCharset) {
  440. this.doc.head.insertBefore(metaCharset, this.doc.head.firstChild);
  441. }
  442. this.doc.querySelectorAll("base").forEach(element => element.remove());
  443. if (this.doc.head.querySelectorAll("*").length == 1 && metaCharset && this.doc.body.childNodes.length == 0) {
  444. this.doc.head.querySelector("meta[charset]").remove();
  445. }
  446. const titleElement = this.doc.querySelector("title");
  447. const descriptionElement = this.doc.querySelector("meta[name=description]");
  448. const authorElement = this.doc.querySelector("meta[name=author]");
  449. const creatorElement = this.doc.querySelector("meta[name=creator]");
  450. const publisherElement = this.doc.querySelector("meta[name=publisher]");
  451. this.options.title = titleElement ? titleElement.textContent.trim() : "";
  452. this.options.infobarContent = await DomProcessorHelper.evalTemplate(this.options.infobarTemplate, this.options, null, true);
  453. this.options.info = {
  454. description: descriptionElement ? descriptionElement.content.trim() : "",
  455. lang: this.doc.documentElement.lang,
  456. author: authorElement ? authorElement.content.trim() : "",
  457. creator: creatorElement ? creatorElement.content.trim() : "",
  458. publisher: publisherElement ? publisherElement.content.trim() : ""
  459. };
  460. }
  461. preProcessPage() {
  462. this.doc.querySelectorAll("singlefile-infobar, singlefile-mask, singlefile-logs-window").forEach(element => element.remove());
  463. if (this.options.win) {
  464. 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));
  465. }
  466. if (this.options.imageData) {
  467. const dataAttributeName = DOM.imagesAttributeName(this.options.sessionId);
  468. this.doc.querySelectorAll("img").forEach(imgElement => {
  469. const imgData = this.options.imageData[Number(imgElement.getAttribute(dataAttributeName))];
  470. if (this.options.removeHiddenElements && imgData.size && !imgData.size.pxWidth && !imgData.size.pxHeight) {
  471. imgElement.setAttribute("src", EMPTY_IMAGE);
  472. } else if (imgData.currentSrc) {
  473. imgElement.setAttribute("src", imgData.currentSrc);
  474. }
  475. });
  476. if (this.options.lazyLoadImages) {
  477. this.doc.querySelectorAll("img[data-src]").forEach(imgElement => {
  478. const imgData = this.options.imageData[Number(imgElement.getAttribute(dataAttributeName))];
  479. if ((!imgElement.getAttribute("src") || imgElement.getAttribute("src") == EMPTY_IMAGE) && imgElement.getAttribute("data-src")) {
  480. imgData.src = imgElement.dataset.src;
  481. imgElement.setAttribute("src", imgElement.dataset.src);
  482. imgElement.removeAttribute("data-src");
  483. }
  484. });
  485. this.doc.querySelectorAll("img[data-srcset]").forEach(imgElement => {
  486. if (!imgElement.getAttribute("srcset") && imgElement.getAttribute("data-srcset")) {
  487. imgElement.setAttribute("srcset", imgElement.dataset.srcset);
  488. imgElement.removeAttribute("data-srcset");
  489. }
  490. });
  491. }
  492. }
  493. }
  494. removeScripts() {
  495. const scriptElements = this.doc.querySelectorAll("script:not([type=\"application/ld+json\"])");
  496. this.stats.set("discarded", "scripts", scriptElements.length);
  497. this.stats.set("processed", "scripts", scriptElements.length);
  498. scriptElements.forEach(element => element.remove());
  499. }
  500. removeFrames() {
  501. const frameElements = this.doc.querySelectorAll("iframe, frame, object[type=\"text/html\"][data]");
  502. this.stats.set("discarded", "frames", frameElements.length);
  503. this.stats.set("processed", "frames", frameElements.length);
  504. this.doc.querySelectorAll("iframe, frame, object[type=\"text/html\"][data]").forEach(element => element.remove());
  505. }
  506. removeImports() {
  507. const importElements = this.doc.querySelectorAll("link[rel=import]");
  508. this.stats.set("discarded", "HTML imports", importElements.length);
  509. this.stats.set("processed", "HTML imports", importElements.length);
  510. importElements.forEach(element => element.remove());
  511. }
  512. resetCharsetMeta() {
  513. let charSet;
  514. this.doc.querySelectorAll("meta[charset], meta[http-equiv=\"content-type\"]").forEach(element => {
  515. const charSetDeclaration = element.content.split(";")[1];
  516. if (charSetDeclaration && !charSet) {
  517. charSet = charSetDeclaration.split("=")[1];
  518. if (charSet) {
  519. this.charSet = charSet.trim().toLowerCase();
  520. }
  521. }
  522. element.remove();
  523. });
  524. const metaElement = this.doc.createElement("meta");
  525. metaElement.setAttribute("charset", "utf-8");
  526. if (this.doc.head.firstChild) {
  527. this.doc.head.insertBefore(metaElement, this.doc.head.firstChild);
  528. } else {
  529. this.doc.head.appendChild(metaElement);
  530. }
  531. }
  532. insertFaviconLink() {
  533. let faviconElement = this.doc.querySelector("link[href][rel=\"icon\"]");
  534. if (!faviconElement) {
  535. faviconElement = this.doc.querySelector("link[href][rel=\"shortcut icon\"]");
  536. }
  537. if (!faviconElement) {
  538. faviconElement = this.doc.createElement("link");
  539. faviconElement.setAttribute("type", "image/x-icon");
  540. faviconElement.setAttribute("rel", "shortcut icon");
  541. faviconElement.setAttribute("href", "/favicon.ico");
  542. }
  543. this.doc.head.appendChild(faviconElement);
  544. }
  545. resolveHrefs() {
  546. this.doc.querySelectorAll("[href]").forEach(element => {
  547. const href = element.getAttribute("href");
  548. if (!DomUtil.testIgnoredPath(href) && DomUtil.testValidPath(href, this.baseURI, this.options.url)) {
  549. const normalizedHref = DomUtil.normalizeURL(href);
  550. if (element.tagName == "LINK") {
  551. try {
  552. element.setAttribute("href", new URL(href, this.options.baseURI || this.options.url));
  553. } catch (error) {
  554. if (element.tagName == "LINK") {
  555. element.setAttribute("href", EMPTY_URL);
  556. }
  557. }
  558. } else if (normalizedHref == href) {
  559. try {
  560. element.setAttribute("href", new URL(normalizedHref, this.options.baseURI || this.options.url));
  561. } catch (error) {
  562. // ignored
  563. }
  564. }
  565. }
  566. });
  567. }
  568. removeUnusedStyles() {
  569. if (!this.mediaAllInfo) {
  570. this.mediaAllInfo = DOM.getMediaAllInfo(this.doc, { stylesheets: this.stylesheets, styles: this.styles });
  571. }
  572. const stats = DOM.minifyCSSRules(this.stylesheets, this.styles, this.mediaAllInfo);
  573. this.stats.set("processed", "CSS rules", stats.processed);
  574. this.stats.set("discarded", "CSS rules", stats.discarded);
  575. }
  576. removeUnusedFonts() {
  577. DOM.removeUnusedFonts(this.doc, this.stylesheets, this.styles, this.options);
  578. }
  579. removeAlternativeFonts() {
  580. DOM.removeAlternativeFonts(this.doc, this.stylesheets);
  581. }
  582. removeAlternativeImages() {
  583. DOM.removeAlternativeImages(this.doc);
  584. }
  585. removeHiddenElements() {
  586. const hiddenElements = this.doc.querySelectorAll("[" + DOM.removedContentAttributeName(this.options.sessionId) + "]");
  587. this.stats.set("discarded", "hidden elements", hiddenElements.length);
  588. this.stats.set("processed", "hidden elements", hiddenElements.length);
  589. hiddenElements.forEach(element => element.remove());
  590. }
  591. compressHTML() {
  592. let size;
  593. if (this.options.displayStats) {
  594. size = DOM.getContentSize(this.doc.documentElement.outerHTML);
  595. }
  596. DOM.minifyHTML(this.doc, { preservedSpaceAttributeName: DOM.preservedSpaceAttributeName(this.options.sessionId) });
  597. if (this.options.displayStats) {
  598. this.stats.add("discarded", "HTML bytes", size - DOM.getContentSize(this.doc.documentElement.outerHTML));
  599. }
  600. }
  601. removeAlternativeMedias() {
  602. const stats = DOM.minifyMedias(this.stylesheets);
  603. this.stats.set("processed", "medias", stats.processed);
  604. this.stats.set("discarded", "medias", stats.discarded);
  605. }
  606. replaceCanvasElements() {
  607. if (this.options.canvasData) {
  608. this.doc.querySelectorAll("canvas").forEach((canvasElement, indexCanvasElement) => {
  609. const canvasData = this.options.canvasData[indexCanvasElement];
  610. if (canvasData) {
  611. DomProcessorHelper.setBackgroundImage(canvasElement, "url(" + canvasData.dataURI + ")");
  612. this.stats.add("processed", "canvas", 1);
  613. }
  614. });
  615. }
  616. }
  617. insertFonts() {
  618. if (this.options.fontsData && this.options.fontsData.length) {
  619. let stylesheetContent = "";
  620. this.options.fontsData.forEach(fontStyles => {
  621. if (fontStyles["font-family"] && fontStyles.src) {
  622. stylesheetContent += "@font-face{";
  623. let stylesContent = "";
  624. Object.keys(fontStyles).forEach(fontStyle => {
  625. if (stylesContent) {
  626. stylesContent += ";";
  627. }
  628. stylesContent += fontStyle + ":" + fontStyles[fontStyle];
  629. });
  630. stylesheetContent += stylesContent + "}";
  631. }
  632. });
  633. if (stylesheetContent) {
  634. const styleElement = this.doc.createElement("style");
  635. styleElement.textContent = stylesheetContent;
  636. const existingStyleElement = this.doc.querySelector("style");
  637. if (existingStyleElement) {
  638. existingStyleElement.parentElement.insertBefore(styleElement, existingStyleElement);
  639. } else {
  640. this.doc.head.insertBefore(styleElement, this.doc.head.firstChild);
  641. }
  642. }
  643. }
  644. }
  645. replaceStyleContents() {
  646. if (this.options.stylesheetContents) {
  647. this.doc.querySelectorAll("style").forEach((styleElement, styleIndex) => {
  648. if (this.options.stylesheetContents[styleIndex]) {
  649. styleElement.textContent = this.options.stylesheetContents[styleIndex];
  650. }
  651. });
  652. }
  653. }
  654. insertShadowRootContents() {
  655. if (this.options.shadowRootContents) {
  656. this.doc.querySelectorAll("[" + DOM.shadowRootAttributeName(this.options.sessionId) + "]").forEach((element, elementIndex) => {
  657. const DOMParser = DOM.getParser();
  658. const elementInfo = this.options.shadowRootContents[elementIndex];
  659. if (DOMParser && elementInfo) {
  660. const frameElement = this.doc.createElement("iframe");
  661. frameElement.setAttribute("style", "all:initial!important;border:0!important;width:100%!important;height:" + elementInfo.height + "px!important");
  662. const windowId = "shadow-" + this.options.framesData.length;
  663. frameElement.setAttribute(DOM.windowIdAttributeName(this.options.sessionId), windowId);
  664. this.options.framesData.push({ windowId, content: elementInfo.content, baseURI: this.baseURI });
  665. element.appendChild(frameElement);
  666. }
  667. });
  668. }
  669. }
  670. insertVideoPosters() {
  671. if (this.options.postersData) {
  672. this.doc.querySelectorAll("video[src], video > source[src]").forEach((element, videoIndex) => {
  673. let videoElement;
  674. if (element.tagName == "VIDEO") {
  675. videoElement = element;
  676. } else {
  677. videoElement = element.parentElement;
  678. }
  679. if (!videoElement.poster && this.options.postersData[videoIndex]) {
  680. videoElement.setAttribute("poster", this.options.postersData[videoIndex]);
  681. }
  682. });
  683. }
  684. }
  685. async processPageResources() {
  686. const processAttributeArgs = [
  687. ["link[href][rel*=\"icon\"]", "href", "data:", false, true],
  688. ["object[type=\"image/svg+xml\"], object[type=\"image/svg-xml\"]", "data", PREFIX_DATA_URI_IMAGE_SVG],
  689. ["img[src], input[src][type=image]", "src", PREFIX_DATA_URI_IMAGE, true],
  690. ["embed[src*=\".svg\"]", "src", PREFIX_DATA_URI_IMAGE_SVG],
  691. ["video[poster]", "poster", PREFIX_DATA_URI_IMAGE],
  692. ["*[background]", "background", PREFIX_DATA_URI_IMAGE],
  693. ["image", "xlink:href", PREFIX_DATA_URI_IMAGE]
  694. ];
  695. let resourcePromises = processAttributeArgs.map(([selector, attributeName, prefixDataURI, processDuplicates, removeElementIfMissing]) =>
  696. DomProcessorHelper.processAttribute(this.doc, this.doc.querySelectorAll(selector), attributeName, prefixDataURI, this.baseURI, this.options, this.cssVariables, this.styles, this.batchRequest, processDuplicates, removeElementIfMissing)
  697. );
  698. resourcePromises = resourcePromises.concat([
  699. DomProcessorHelper.processXLinks(this.doc.querySelectorAll("use"), this.baseURI, this.options, this.batchRequest),
  700. DomProcessorHelper.processSrcset(this.doc.querySelectorAll("img[srcset], source[srcset]"), "srcset", PREFIX_DATA_URI_IMAGE, this.baseURI, this.options, this.batchRequest)
  701. ]);
  702. if (!this.options.removeAudioSrc) {
  703. 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));
  704. }
  705. if (!this.options.removeVideoSrc) {
  706. 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));
  707. }
  708. await Promise.all(resourcePromises);
  709. DomProcessorHelper.processShortcutIcons(this.doc);
  710. }
  711. async resolveStylesheetURLs() {
  712. await Promise.all(Array.from(this.doc.querySelectorAll("style, link[rel*=stylesheet]"))
  713. .map(async element => {
  714. let mediaText;
  715. if (element.media) {
  716. mediaText = element.media;
  717. }
  718. this.stylesheets.set(element, { mediaText });
  719. const options = { maxResourceSize: this.options.maxResourceSize, maxResourceSizeEnabled: this.options.maxResourceSizeEnabled, url: this.options.url, charSet: this.charSet, compressCSS: this.options.compressCSS };
  720. const isLinkTag = element.tagName.toLowerCase() == "link";
  721. if (isLinkTag && element.rel.includes("alternate") && element.title) {
  722. element.remove();
  723. } else {
  724. let stylesheetContent;
  725. if (isLinkTag) {
  726. if (element.charset) {
  727. options.charSet = element.charset;
  728. }
  729. stylesheetContent = await DomProcessorHelper.resolveLinkStylesheetURLs(element.href, this.baseURI, options);
  730. } else {
  731. stylesheetContent = await DomProcessorHelper.resolveImportURLs(element.textContent, this.baseURI, options);
  732. }
  733. let stylesheet;
  734. try {
  735. stylesheet = cssTree.parse(stylesheetContent);
  736. } catch (error) {
  737. // ignored
  738. }
  739. if (stylesheet && stylesheet.children) {
  740. if (this.options.compressCSS) {
  741. const removedRules = [];
  742. for (let cssRule = stylesheet.children.head; cssRule; cssRule = cssRule.next) {
  743. if (cssRule.data.type == "Raw" && cssRule.data.value && cssRule.data.value.trim().startsWith("//")) {
  744. removedRules.push(cssRule);
  745. }
  746. }
  747. removedRules.forEach(cssRule => stylesheet.children.remove(cssRule));
  748. }
  749. this.stylesheets.get(element).stylesheet = stylesheet;
  750. }
  751. }
  752. }));
  753. }
  754. async processStylesheets() {
  755. await Promise.all(Array.from(this.stylesheets).map(([, stylesheetInfo]) =>
  756. DomProcessorHelper.processStylesheet(stylesheetInfo.stylesheet.children, this.baseURI, this.options, this.cssVariables, this.batchRequest)
  757. ));
  758. }
  759. replaceStylesheets() {
  760. this.doc.querySelectorAll("style").forEach(styleElement => {
  761. const stylesheetInfo = this.stylesheets.get(styleElement);
  762. if (stylesheetInfo) {
  763. let stylesheetContent = cssTree.generate(stylesheetInfo.stylesheet);
  764. styleElement.textContent = stylesheetContent;
  765. if (stylesheetInfo.mediaText) {
  766. styleElement.media = stylesheetInfo.mediaText;
  767. }
  768. } else {
  769. styleElement.remove();
  770. }
  771. });
  772. this.doc.querySelectorAll("link[rel*=stylesheet]").forEach(linkElement => {
  773. const stylesheetInfo = this.stylesheets.get(linkElement);
  774. if (stylesheetInfo) {
  775. const styleElement = this.doc.createElement("style");
  776. if (stylesheetInfo.mediaText) {
  777. styleElement.media = stylesheetInfo.mediaText;
  778. }
  779. let stylesheetContent = cssTree.generate(stylesheetInfo.stylesheet);
  780. styleElement.textContent = stylesheetContent;
  781. linkElement.parentElement.replaceChild(styleElement, linkElement);
  782. } else {
  783. linkElement.remove();
  784. }
  785. });
  786. }
  787. insertVariables() {
  788. if (this.cssVariables.size) {
  789. const styleElement = this.doc.createElement("style");
  790. const firstStyleElement = this.doc.head.querySelector("style");
  791. if (firstStyleElement) {
  792. this.doc.head.insertBefore(styleElement, firstStyleElement);
  793. } else {
  794. this.doc.head.appendChild(styleElement);
  795. }
  796. let stylesheetContent = "";
  797. this.cssVariables.forEach((content, indexResource) => {
  798. if (stylesheetContent) {
  799. stylesheetContent += ";";
  800. }
  801. stylesheetContent += `${SINGLE_FILE_VARIABLE_NAME_PREFIX + indexResource}:url("${content}")`;
  802. });
  803. styleElement.textContent = ":root{" + stylesheetContent + "}";
  804. }
  805. }
  806. async processScripts() {
  807. await Promise.all(Array.from(this.doc.querySelectorAll("script[src]")).map(async scriptElement => {
  808. if (scriptElement.src) {
  809. this.stats.add("processed", "scripts", 1);
  810. const scriptContent = await Download.getContent(scriptElement.src, { asDataURI: false, maxResourceSize: this.options.maxResourceSize, maxResourceSizeEnabled: this.options.maxResourceSizeEnabled });
  811. scriptElement.textContent = scriptContent.replace(/<\/script>/gi, "<\\/script>");
  812. }
  813. scriptElement.removeAttribute("src");
  814. }));
  815. }
  816. async resolveFrameURLs() {
  817. if (this.options.framesData) {
  818. const frameElements = Array.from(this.doc.querySelectorAll("iframe, frame, object[type=\"text/html\"][data]"));
  819. await Promise.all(frameElements.map(async frameElement => {
  820. DomProcessorHelper.setFrameEmptySrc(frameElement);
  821. const frameWindowId = frameElement.getAttribute(DOM.windowIdAttributeName(this.options.sessionId));
  822. if (frameWindowId) {
  823. const frameData = this.options.framesData.find(frame => frame.windowId == frameWindowId);
  824. if (frameData) {
  825. await initializeProcessor(frameData, frameElement, frameWindowId, this.batchRequest, Object.create(this.options));
  826. }
  827. }
  828. }));
  829. }
  830. async function initializeProcessor(frameData, frameElement, frameWindowId, batchRequest, options) {
  831. options.insertSingleFileComment = false;
  832. options.insertFaviconLink = false;
  833. options.doc = null;
  834. options.win = null;
  835. options.url = frameData.baseURI;
  836. options.windowId = frameWindowId;
  837. if (frameData.content) {
  838. options.content = frameData.content;
  839. options.canvasData = frameData.canvasData;
  840. options.stylesheetContents = frameData.stylesheetContents;
  841. options.fontsData = frameData.fontsData;
  842. options.imageData = frameData.imageData;
  843. options.usedFonts = frameData.usedFonts;
  844. frameData.processor = new PageProcessor(options);
  845. frameData.frameElement = frameElement;
  846. await frameData.processor.loadPage();
  847. await frameData.processor.initialize();
  848. frameData.maxResources = batchRequest.getMaxResources();
  849. }
  850. }
  851. }
  852. async processFrames() {
  853. if (this.options.framesData) {
  854. const frameElements = Array.from(this.doc.querySelectorAll("iframe, frame, object[type=\"text/html\"][data]"));
  855. await Promise.all(frameElements.map(async frameElement => {
  856. const frameWindowId = frameElement.getAttribute(DOM.windowIdAttributeName(this.options.sessionId));
  857. if (frameWindowId) {
  858. const frameData = this.options.framesData.find(frame => frame.windowId == frameWindowId);
  859. if (frameData) {
  860. if (frameData.processor) {
  861. this.stats.add("processed", "frames", 1);
  862. await frameData.processor.run();
  863. const pageData = await frameData.processor.getPageData();
  864. frameElement.removeAttribute(DOM.windowIdAttributeName(this.options.sessionId));
  865. if (pageData.content.match(NOSCRIPT_TAG_FOUND) || pageData.content.match(SCRIPT_TAG_FOUND)) {
  866. frameElement.setAttribute("sandbox", "allow-scripts allow-same-origin");
  867. } else {
  868. frameElement.setAttribute("sandbox", "");
  869. }
  870. DomProcessorHelper.setFrameContent(frameElement, pageData.content);
  871. this.stats.addAll(pageData);
  872. } else {
  873. this.stats.add("discarded", "frames", 1);
  874. }
  875. }
  876. }
  877. }));
  878. }
  879. }
  880. async resolveHtmlImportURLs() {
  881. const linkElements = Array.from(this.doc.querySelectorAll("link[rel=import][href]"));
  882. if (!this.relImportProcessors) {
  883. this.relImportProcessors = new Map();
  884. }
  885. await Promise.all(linkElements.map(async linkElement => {
  886. const resourceURL = linkElement.href;
  887. linkElement.removeAttribute("href");
  888. const options = Object.create(this.options);
  889. options.insertSingleFileComment = false;
  890. options.insertFaviconLink = false;
  891. options.doc = null;
  892. options.win = null;
  893. options.url = resourceURL;
  894. if (!DomUtil.testIgnoredPath(resourceURL) && DomUtil.testValidPath(resourceURL, this.baseURI, this.options.url)) {
  895. const processor = new PageProcessor(options);
  896. this.relImportProcessors.set(linkElement, processor);
  897. await processor.loadPage();
  898. return processor.initialize();
  899. }
  900. }));
  901. }
  902. async processHtmlImports() {
  903. const linkElements = Array.from(this.doc.querySelectorAll("link[rel=import][href]"));
  904. await Promise.all(linkElements.map(async linkElement => {
  905. const processor = this.relImportProcessors.get(linkElement);
  906. if (processor) {
  907. this.stats.add("processed", "HTML imports", 1);
  908. this.relImportProcessors.delete(linkElement);
  909. const pageData = await processor.getPageData();
  910. linkElement.setAttribute("href", "data:text/html," + pageData.content);
  911. this.stats.addAll(pageData);
  912. } else {
  913. this.stats.add("discarded", "HTML imports", 1);
  914. }
  915. }));
  916. }
  917. resolveStyleAttributeURLs() {
  918. this.doc.querySelectorAll("[style]").forEach(element => {
  919. let styleContent = element.getAttribute("style");
  920. if (this.options.compressCSS) {
  921. styleContent = DOM.compressCSS(styleContent);
  922. }
  923. styleContent = DomProcessorHelper.resolveStylesheetURLs(styleContent, this.baseURI, this.options);
  924. const declarationList = cssTree.parse(styleContent, { context: "declarationList" });
  925. this.styles.set(element, declarationList);
  926. });
  927. }
  928. async processStyleAttributes() {
  929. return Promise.all(Array.from(this.styles).map(([, declarationList]) =>
  930. DomProcessorHelper.processStyle(declarationList.children.toArray(), this.baseURI, this.options, this.cssVariables, this.batchRequest)
  931. ));
  932. }
  933. replaceStyleAttributes() {
  934. this.doc.querySelectorAll("[style]").forEach(async element => {
  935. const declarations = this.styles.get(element);
  936. if (declarations) {
  937. let styleContent = cssTree.generate(declarations);
  938. element.setAttribute("style", styleContent);
  939. } else {
  940. element.setAttribute("style", "");
  941. }
  942. });
  943. }
  944. }
  945. // ---------
  946. // DomHelper
  947. // ---------
  948. const REGEXP_AMP = /&/g;
  949. const REGEXP_NBSP = /\u00a0/g;
  950. const REGEXP_START_TAG = /</g;
  951. const REGEXP_END_TAG = />/g;
  952. const REGEXP_URL_HASH = /(#.+?)$/;
  953. const PREFIX_DATA_URI_IMAGE = "data:image/";
  954. const PREFIX_DATA_URI_AUDIO = "data:audio/";
  955. const PREFIX_DATA_URI_VIDEO = "data:video/";
  956. const PREFIX_DATA_URI_IMAGE_SVG = "data:image/svg+xml";
  957. const PREFIX_DATA_URI_NO_MIMETYPE = "data:;";
  958. const PREFIX_DATA_URI_OCTET_STREAM = /^data:(application|binary)\/octet-stream/;
  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)) {
  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)) {
  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. })();