single-file-core.js 79 KB

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