single-file-core.js 73 KB

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