single-file-core.js 72 KB

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