1
0

single-file-core.js 79 KB

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