single-file-core.js 79 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912
  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).forEach(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).forEach(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. const frameWindowId = frameElement.getAttribute(util.WIN_ID_ATTRIBUTE_NAME);
  810. if (frameWindowId) {
  811. const frameData = this.options.frames.find(frame => frame.windowId == frameWindowId);
  812. if (frameData) {
  813. await initializeProcessor(frameData, frameElement, frameWindowId, this.batchRequest, Object.create(this.options));
  814. }
  815. }
  816. }));
  817. }
  818. async function initializeProcessor(frameData, frameElement, frameWindowId, batchRequest, options) {
  819. options.insertSingleFileComment = false;
  820. options.insertFaviconLink = false;
  821. options.doc = null;
  822. options.win = null;
  823. options.url = frameData.baseURI;
  824. options.windowId = frameWindowId;
  825. if (frameData.content) {
  826. options.content = frameData.content;
  827. options.canvases = frameData.canvases;
  828. options.fonts = frameData.fonts;
  829. options.stylesheets = frameData.stylesheets;
  830. options.images = frameData.images;
  831. options.posters = frameData.posters;
  832. options.usedFonts = frameData.usedFonts;
  833. options.shadowRoots = frameData.shadowRoots;
  834. options.imports = frameData.imports;
  835. frameData.runner = new Runner(options);
  836. frameData.frameElement = frameElement;
  837. await frameData.runner.loadPage();
  838. await frameData.runner.initialize();
  839. frameData.maxResources = batchRequest.getMaxResources();
  840. }
  841. }
  842. }
  843. insertShadowRootContents() {
  844. const doc = this.doc;
  845. const options = this.options;
  846. if (this.options.shadowRoots && this.options.shadowRoots.length) {
  847. processElement(this.doc);
  848. if (this.options.removeScripts) {
  849. this.doc.querySelectorAll("script[" + SCRIPT_TEMPLATE_SHADOW_ROOT + "]").forEach(element => element.remove());
  850. }
  851. const scriptElement = doc.createElement("script");
  852. scriptElement.setAttribute(SCRIPT_TEMPLATE_SHADOW_ROOT, "");
  853. 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)}})}})()`;
  854. doc.body.appendChild(scriptElement);
  855. }
  856. function processElement(element) {
  857. const shadowRootElements = Array.from((element.querySelectorAll("[" + util.SHADOW_ROOT_ATTRIBUTE_NAME + "]")));
  858. shadowRootElements.forEach(element => {
  859. const attributeValue = element.getAttribute(util.SHADOW_ROOT_ATTRIBUTE_NAME);
  860. if (attributeValue) {
  861. const shadowRootData = options.shadowRoots[Number(attributeValue)];
  862. if (shadowRootData) {
  863. const templateElement = doc.createElement("template");
  864. templateElement.setAttribute(SHADOW_MODE_ATTRIBUTE_NAME, shadowRootData.mode);
  865. if (shadowRootData.delegatesFocus) {
  866. templateElement.setAttribute(SHADOW_DELEGATE_FOCUS_ATTRIBUTE_NAME);
  867. }
  868. if (shadowRootData.adoptedStyleSheets) {
  869. shadowRootData.adoptedStyleSheets.forEach(stylesheetContent => {
  870. const styleElement = doc.createElement("style");
  871. styleElement.textContent = stylesheetContent;
  872. templateElement.appendChild(styleElement);
  873. });
  874. }
  875. const shadowDoc = util.parseDocContent(shadowRootData.content);
  876. if (shadowDoc.head) {
  877. const metaCharset = shadowDoc.head.querySelector("meta[charset]");
  878. if (metaCharset) {
  879. metaCharset.remove();
  880. }
  881. shadowDoc.head.childNodes.forEach(node => templateElement.appendChild(shadowDoc.importNode(node, true)));
  882. }
  883. if (shadowDoc.body) {
  884. shadowDoc.body.childNodes.forEach(node => templateElement.appendChild(shadowDoc.importNode(node, true)));
  885. }
  886. processElement(templateElement);
  887. if (element.firstChild) {
  888. element.insertBefore(templateElement, element.firstChild);
  889. } else {
  890. element.appendChild(templateElement);
  891. }
  892. }
  893. }
  894. });
  895. }
  896. }
  897. async resolveHtmlImportURLs() {
  898. const linkElements = Array.from(this.doc.querySelectorAll("link[rel=import][href]"));
  899. await Promise.all(linkElements.map(async linkElement => {
  900. const resourceURL = linkElement.href;
  901. linkElement.removeAttribute("href");
  902. const options = Object.create(this.options);
  903. options.insertSingleFileComment = false;
  904. options.insertFaviconLink = false;
  905. options.removeUnusedStyles = false;
  906. options.removeAlternativeMedias = false;
  907. options.removeUnusedFonts = false;
  908. options.removeHiddenElements = false;
  909. options.doc = null;
  910. options.win = null;
  911. options.url = resourceURL;
  912. const attributeValue = linkElement.getAttribute(util.HTML_IMPORT_ATTRIBUTE_NAME);
  913. if (attributeValue) {
  914. const importData = options.imports[Number(attributeValue)];
  915. if (importData) {
  916. options.content = importData.content;
  917. importData.runner = new Runner(options);
  918. await importData.runner.loadPage();
  919. await importData.runner.initialize();
  920. if (!options.removeImports) {
  921. importData.maxResources = importData.runner.batchRequest.getMaxResources();
  922. }
  923. importData.runner.getStyleSheets().forEach(stylesheet => {
  924. const importedStyleElement = this.doc.createElement("style");
  925. linkElement.insertAdjacentElement("afterEnd", importedStyleElement);
  926. this.stylesheets.set(importedStyleElement, stylesheet);
  927. });
  928. }
  929. }
  930. if (options.removeImports) {
  931. linkElement.remove();
  932. this.stats.add("discarded", "HTML imports", 1);
  933. }
  934. }));
  935. }
  936. removeUnusedStyles() {
  937. if (!this.mediaAllInfo) {
  938. this.mediaAllInfo = util.getMediaAllInfo(this.doc, this.stylesheets, this.styles);
  939. }
  940. const stats = util.minifyCSSRules(this.stylesheets, this.styles, this.mediaAllInfo);
  941. this.stats.set("processed", "CSS rules", stats.processed);
  942. this.stats.set("discarded", "CSS rules", stats.discarded);
  943. }
  944. removeUnusedFonts() {
  945. util.removeUnusedFonts(this.doc, this.stylesheets, this.styles, this.options);
  946. }
  947. removeAlternativeMedias() {
  948. const stats = util.minifyMedias(this.stylesheets);
  949. this.stats.set("processed", "medias", stats.processed);
  950. this.stats.set("discarded", "medias", stats.discarded);
  951. }
  952. async processStylesheets() {
  953. await Promise.all(Array.from(this.stylesheets).map(([, stylesheetInfo]) =>
  954. ProcessorHelper.processStylesheet(stylesheetInfo.stylesheet.children, this.baseURI, this.options, this.cssVariables, this.batchRequest)
  955. ));
  956. }
  957. async processStyleAttributes() {
  958. return Promise.all(Array.from(this.styles).map(([, declarationList]) =>
  959. ProcessorHelper.processStyle(declarationList.children.toArray(), this.baseURI, this.options, this.cssVariables, this.batchRequest)
  960. ));
  961. }
  962. async processPageResources() {
  963. const processAttributeArgs = [
  964. ["link[href][rel*=\"icon\"]", "href", false, true],
  965. ["object[type=\"image/svg+xml\"], object[type=\"image/svg-xml\"]", "data"],
  966. ["img[src], input[src][type=image]", "src", true],
  967. ["embed[src*=\".svg\"], embed[src*=\".pdf\"]", "src"],
  968. ["video[poster]", "poster"],
  969. ["*[background]", "background"],
  970. ["image", "xlink:href"]
  971. ];
  972. let resourcePromises = processAttributeArgs.map(([selector, attributeName, processDuplicates, removeElementIfMissing]) =>
  973. ProcessorHelper.processAttribute(this.doc.querySelectorAll(selector), attributeName, this.baseURI, this.options, this.cssVariables, this.styles, this.batchRequest, processDuplicates, removeElementIfMissing)
  974. );
  975. resourcePromises = resourcePromises.concat([
  976. ProcessorHelper.processXLinks(this.doc.querySelectorAll("use"), this.baseURI, this.options, this.batchRequest),
  977. ProcessorHelper.processSrcset(this.doc.querySelectorAll("img[srcset], source[srcset]"), "srcset", this.baseURI, this.batchRequest)
  978. ]);
  979. if (!this.options.removeAudioSrc) {
  980. resourcePromises.push(ProcessorHelper.processAttribute(this.doc.querySelectorAll("audio[src], audio > source[src]"), "src", this.baseURI, this.options, this.cssVariables, this.styles, this.batchRequest));
  981. }
  982. if (!this.options.removeVideoSrc) {
  983. resourcePromises.push(ProcessorHelper.processAttribute(this.doc.querySelectorAll("video[src], video > source[src]"), "src", this.baseURI, this.options, this.cssVariables, this.styles, this.batchRequest));
  984. }
  985. await Promise.all(resourcePromises);
  986. ProcessorHelper.processShortcutIcons(this.doc);
  987. }
  988. async processScripts() {
  989. await Promise.all(Array.from(this.doc.querySelectorAll("script[src]")).map(async scriptElement => {
  990. let resourceURL;
  991. const scriptSrc = scriptElement.getAttribute("src");
  992. scriptElement.removeAttribute("src");
  993. scriptElement.removeAttribute("integrity");
  994. scriptElement.textContent = "";
  995. try {
  996. resourceURL = util.resolveURL(scriptSrc, this.baseURI);
  997. } catch (error) {
  998. // ignored
  999. }
  1000. if (Util.testValidURL(resourceURL)) {
  1001. this.stats.add("processed", "scripts", 1);
  1002. const content = await util.getContent(resourceURL, {
  1003. asBinary: true,
  1004. maxResourceSize: this.options.maxResourceSize,
  1005. maxResourceSizeEnabled: this.options.maxResourceSizeEnabled,
  1006. referrerPolicy: this.options.referrerPolicy,
  1007. credentials: this.options.credentials
  1008. });
  1009. scriptElement.setAttribute("src", content.data);
  1010. }
  1011. }));
  1012. }
  1013. removeAlternativeImages() {
  1014. util.removeAlternativeImages(this.doc);
  1015. }
  1016. removeAlternativeFonts() {
  1017. util.removeAlternativeFonts(this.doc, this.stylesheets);
  1018. }
  1019. async processFrames() {
  1020. if (this.options.frames) {
  1021. const frameElements = Array.from(this.doc.querySelectorAll("iframe, frame, object[type=\"text/html\"][data]"));
  1022. await Promise.all(frameElements.map(async frameElement => {
  1023. const frameWindowId = frameElement.getAttribute(util.WIN_ID_ATTRIBUTE_NAME);
  1024. if (frameWindowId) {
  1025. const frameData = this.options.frames.find(frame => frame.windowId == frameWindowId);
  1026. if (frameData) {
  1027. this.options.frames = this.options.frames.filter(frame => frame.windowId != frameWindowId);
  1028. if (frameData.runner) {
  1029. this.stats.add("processed", "frames", 1);
  1030. await frameData.runner.run();
  1031. const pageData = await frameData.runner.getPageData();
  1032. frameElement.removeAttribute(util.WIN_ID_ATTRIBUTE_NAME);
  1033. let sandbox = "allow-popups allow-top-navigation allow-top-navigation-by-user-activation";
  1034. if (pageData.content.match(NOSCRIPT_TAG_FOUND) || pageData.content.match(SCRIPT_TAG_FOUND)) {
  1035. sandbox += " allow-scripts allow-same-origin";
  1036. }
  1037. frameElement.setAttribute("sandbox", sandbox);
  1038. if (frameElement.tagName == "OBJECT") {
  1039. frameElement.setAttribute("data", "data:text/html," + pageData.content);
  1040. } else {
  1041. if (frameElement.tagName == "FRAME") {
  1042. frameElement.setAttribute("src", "data:text/html," + pageData.content.replace(/#/g, "%23"));
  1043. } else {
  1044. frameElement.setAttribute("srcdoc", pageData.content);
  1045. frameElement.removeAttribute("src");
  1046. }
  1047. }
  1048. this.stats.addAll(pageData);
  1049. } else {
  1050. this.stats.add("discarded", "frames", 1);
  1051. }
  1052. }
  1053. }
  1054. }));
  1055. }
  1056. }
  1057. async processHtmlImports() {
  1058. const linkElements = Array.from(this.doc.querySelectorAll("link[rel=import]"));
  1059. await Promise.all(linkElements.map(async linkElement => {
  1060. const attributeValue = linkElement.getAttribute(util.HTML_IMPORT_ATTRIBUTE_NAME);
  1061. if (attributeValue) {
  1062. const importData = this.options.imports[Number(attributeValue)];
  1063. if (importData.runner) {
  1064. this.stats.add("processed", "HTML imports", 1);
  1065. await importData.runner.run();
  1066. const pageData = await importData.runner.getPageData();
  1067. linkElement.removeAttribute(util.HTML_IMPORT_ATTRIBUTE_NAME);
  1068. linkElement.setAttribute("href", "data:text/html," + pageData.content);
  1069. this.stats.addAll(pageData);
  1070. } else {
  1071. this.stats.add("discarded", "HTML imports", 1);
  1072. }
  1073. }
  1074. }));
  1075. }
  1076. replaceStylesheets() {
  1077. this.doc.querySelectorAll("style").forEach(styleElement => {
  1078. const stylesheetInfo = this.stylesheets.get(styleElement);
  1079. if (stylesheetInfo) {
  1080. this.stylesheets.delete(styleElement);
  1081. let stylesheetContent = cssTree.generate(stylesheetInfo.stylesheet);
  1082. styleElement.textContent = stylesheetContent;
  1083. if (stylesheetInfo.mediaText) {
  1084. styleElement.media = stylesheetInfo.mediaText;
  1085. }
  1086. } else {
  1087. styleElement.remove();
  1088. }
  1089. });
  1090. this.doc.querySelectorAll("link[rel*=stylesheet]").forEach(linkElement => {
  1091. const stylesheetInfo = this.stylesheets.get(linkElement);
  1092. if (stylesheetInfo) {
  1093. this.stylesheets.delete(linkElement);
  1094. const styleElement = this.doc.createElement("style");
  1095. if (stylesheetInfo.mediaText) {
  1096. styleElement.media = stylesheetInfo.mediaText;
  1097. }
  1098. let stylesheetContent = cssTree.generate(stylesheetInfo.stylesheet);
  1099. styleElement.textContent = stylesheetContent;
  1100. linkElement.parentElement.replaceChild(styleElement, linkElement);
  1101. } else {
  1102. linkElement.remove();
  1103. }
  1104. });
  1105. }
  1106. replaceStyleAttributes() {
  1107. this.doc.querySelectorAll("[style]").forEach(async element => {
  1108. const declarations = this.styles.get(element);
  1109. if (declarations) {
  1110. this.styles.delete(element);
  1111. let styleContent = cssTree.generate(declarations);
  1112. element.setAttribute("style", styleContent);
  1113. } else {
  1114. element.setAttribute("style", "");
  1115. }
  1116. });
  1117. }
  1118. insertVariables() {
  1119. if (this.cssVariables.size) {
  1120. const styleElement = this.doc.createElement("style");
  1121. const firstStyleElement = this.doc.head.querySelector("style");
  1122. if (firstStyleElement) {
  1123. this.doc.head.insertBefore(styleElement, firstStyleElement);
  1124. } else {
  1125. this.doc.head.appendChild(styleElement);
  1126. }
  1127. let stylesheetContent = "";
  1128. this.cssVariables.forEach((content, indexResource) => {
  1129. this.cssVariables.delete(indexResource);
  1130. if (stylesheetContent) {
  1131. stylesheetContent += ";";
  1132. }
  1133. stylesheetContent += `${SINGLE_FILE_VARIABLE_NAME_PREFIX + indexResource}:url("${content}")`;
  1134. });
  1135. styleElement.textContent = ":root{" + stylesheetContent + "}";
  1136. }
  1137. }
  1138. compressHTML() {
  1139. let size;
  1140. if (this.options.displayStats) {
  1141. size = util.getContentSize(this.doc.documentElement.outerHTML);
  1142. }
  1143. util.minifyHTML(this.doc, { PRESERVED_SPACE_ELEMENT_ATTRIBUTE_NAME: util.PRESERVED_SPACE_ELEMENT_ATTRIBUTE_NAME });
  1144. if (this.options.displayStats) {
  1145. this.stats.add("discarded", "HTML bytes", size - util.getContentSize(this.doc.documentElement.outerHTML));
  1146. }
  1147. }
  1148. async insertMAFFMetaData() {
  1149. const maffMetaData = await this.maffMetaDataPromise;
  1150. if (maffMetaData && maffMetaData.content) {
  1151. const NAMESPACE_RDF = "http://www.w3.org/1999/02/22-rdf-syntax-ns#";
  1152. const maffDoc = util.parseXMLContent(maffMetaData.content);
  1153. const originalURLElement = maffDoc.querySelector("RDF > Description > originalurl");
  1154. const archiveTimeElement = maffDoc.querySelector("RDF > Description > archivetime");
  1155. if (originalURLElement) {
  1156. this.options.saveUrl = originalURLElement.getAttributeNS(NAMESPACE_RDF, "resource");
  1157. }
  1158. if (archiveTimeElement) {
  1159. const value = archiveTimeElement.getAttributeNS(NAMESPACE_RDF, "resource");
  1160. if (value) {
  1161. const date = new Date(value);
  1162. if (!isNaN(date.getTime())) {
  1163. this.options.saveDate = new Date(value);
  1164. }
  1165. }
  1166. }
  1167. }
  1168. }
  1169. async setDocInfo() {
  1170. const titleElement = this.doc.querySelector("title");
  1171. const descriptionElement = this.doc.querySelector("meta[name=description]");
  1172. const authorElement = this.doc.querySelector("meta[name=author]");
  1173. const creatorElement = this.doc.querySelector("meta[name=creator]");
  1174. const publisherElement = this.doc.querySelector("meta[name=publisher]");
  1175. this.options.title = titleElement ? titleElement.textContent.trim() : "";
  1176. this.options.infobarContent = await ProcessorHelper.evalTemplate(this.options.infobarTemplate, this.options, null, true);
  1177. this.options.info = {
  1178. description: descriptionElement && descriptionElement.content ? descriptionElement.content.trim() : "",
  1179. lang: this.doc.documentElement.lang,
  1180. author: authorElement && authorElement.content ? authorElement.content.trim() : "",
  1181. creator: creatorElement && creatorElement.content ? creatorElement.content.trim() : "",
  1182. publisher: publisherElement && publisherElement.content ? publisherElement.content.trim() : ""
  1183. };
  1184. }
  1185. }
  1186. // ---------------
  1187. // ProcessorHelper
  1188. // ---------------
  1189. const DATA_URI_PREFIX = "data:";
  1190. const ABOUT_BLANK_URI = "about:blank";
  1191. const EMPTY_DATA_URI = "data:base64,";
  1192. const REGEXP_URL_HASH = /(#.+?)$/;
  1193. const PREFIX_DATA_URI_VND = "data:application/vnd.";
  1194. const SINGLE_FILE_VARIABLE_NAME_PREFIX = "--sf-img-";
  1195. class ProcessorHelper {
  1196. static async evalTemplate(template = "", options, content, dontReplaceSlash) {
  1197. const date = options.saveDate;
  1198. const url = util.parseURL(options.saveUrl);
  1199. template = await Util.evalTemplateVariable(template, "page-title", () => options.title || "No title", dontReplaceSlash, options.filenameReplacementCharacter);
  1200. template = await Util.evalTemplateVariable(template, "page-language", () => options.info.lang || "No language", dontReplaceSlash, options.filenameReplacementCharacter);
  1201. template = await Util.evalTemplateVariable(template, "page-description", () => options.info.description || "No description", dontReplaceSlash, options.filenameReplacementCharacter);
  1202. template = await Util.evalTemplateVariable(template, "page-author", () => options.info.author || "No author", dontReplaceSlash, options.filenameReplacementCharacter);
  1203. template = await Util.evalTemplateVariable(template, "page-creator", () => options.info.creator || "No creator", dontReplaceSlash, options.filenameReplacementCharacter);
  1204. template = await Util.evalTemplateVariable(template, "page-publisher", () => options.info.publisher || "No publisher", dontReplaceSlash, options.filenameReplacementCharacter);
  1205. template = await Util.evalTemplateVariable(template, "datetime-iso", () => date.toISOString(), dontReplaceSlash, options.filenameReplacementCharacter);
  1206. template = await Util.evalTemplateVariable(template, "date-iso", () => date.toISOString().split("T")[0], dontReplaceSlash, options.filenameReplacementCharacter);
  1207. template = await Util.evalTemplateVariable(template, "time-iso", () => date.toISOString().split("T")[1].split("Z")[0], dontReplaceSlash, options.filenameReplacementCharacter);
  1208. template = await Util.evalTemplateVariable(template, "date-locale", () => date.toLocaleDateString(), dontReplaceSlash, options.filenameReplacementCharacter);
  1209. template = await Util.evalTemplateVariable(template, "time-locale", () => date.toLocaleTimeString(), dontReplaceSlash, options.filenameReplacementCharacter);
  1210. template = await Util.evalTemplateVariable(template, "day-locale", () => String(date.getDate()).padStart(2, "0"), dontReplaceSlash, options.filenameReplacementCharacter);
  1211. template = await Util.evalTemplateVariable(template, "month-locale", () => String(date.getMonth() + 1).padStart(2, "0"), dontReplaceSlash, options.filenameReplacementCharacter);
  1212. template = await Util.evalTemplateVariable(template, "year-locale", () => String(date.getFullYear()), dontReplaceSlash, options.filenameReplacementCharacter);
  1213. template = await Util.evalTemplateVariable(template, "datetime-locale", () => date.toLocaleString(), dontReplaceSlash, options.filenameReplacementCharacter);
  1214. template = await Util.evalTemplateVariable(template, "datetime-utc", () => date.toUTCString(), dontReplaceSlash, options.filenameReplacementCharacter);
  1215. template = await Util.evalTemplateVariable(template, "day-utc", () => String(date.getUTCDate()).padStart(2, "0"), dontReplaceSlash, options.filenameReplacementCharacter);
  1216. template = await Util.evalTemplateVariable(template, "month-utc", () => String(date.getUTCMonth() + 1).padStart(2, "0"), dontReplaceSlash, options.filenameReplacementCharacter);
  1217. template = await Util.evalTemplateVariable(template, "year-utc", () => String(date.getUTCFullYear()), dontReplaceSlash, options.filenameReplacementCharacter);
  1218. template = await Util.evalTemplateVariable(template, "hours-locale", () => String(date.getHours()).padStart(2, "0"), dontReplaceSlash, options.filenameReplacementCharacter);
  1219. template = await Util.evalTemplateVariable(template, "minutes-locale", () => String(date.getMinutes()).padStart(2, "0"), dontReplaceSlash, options.filenameReplacementCharacter);
  1220. template = await Util.evalTemplateVariable(template, "seconds-locale", () => String(date.getSeconds()).padStart(2, "0"), dontReplaceSlash, options.filenameReplacementCharacter);
  1221. template = await Util.evalTemplateVariable(template, "hours-utc", () => String(date.getUTCHours()).padStart(2, "0"), dontReplaceSlash, options.filenameReplacementCharacter);
  1222. template = await Util.evalTemplateVariable(template, "minutes-utc", () => String(date.getUTCMinutes()).padStart(2, "0"), dontReplaceSlash, options.filenameReplacementCharacter);
  1223. template = await Util.evalTemplateVariable(template, "seconds-utc", () => String(date.getUTCSeconds()).padStart(2, "0"), dontReplaceSlash, options.filenameReplacementCharacter);
  1224. template = await Util.evalTemplateVariable(template, "url-hash", () => url.hash.substring(1) || "No hash", dontReplaceSlash, options.filenameReplacementCharacter);
  1225. template = await Util.evalTemplateVariable(template, "url-host", () => url.host.replace(/\/$/, "") || "No host", dontReplaceSlash, options.filenameReplacementCharacter);
  1226. template = await Util.evalTemplateVariable(template, "url-hostname", () => url.hostname.replace(/\/$/, "") || "No hostname", dontReplaceSlash, options.filenameReplacementCharacter);
  1227. template = await Util.evalTemplateVariable(template, "url-href", () => decodeURI(url.href) || "No href", dontReplaceSlash, options.filenameReplacementCharacter);
  1228. template = await Util.evalTemplateVariable(template, "url-referrer", () => decodeURI(options.referrer) || "No referrer", dontReplaceSlash, options.filenameReplacementCharacter);
  1229. template = await Util.evalTemplateVariable(template, "url-password", () => url.password || "No password", dontReplaceSlash, options.filenameReplacementCharacter);
  1230. template = await Util.evalTemplateVariable(template, "url-pathname", () => decodeURI(url.pathname).replace(/^\//, "").replace(/\/$/, "") || "No pathname", dontReplaceSlash === undefined ? true : dontReplaceSlash, options.filenameReplacementCharacter);
  1231. template = await Util.evalTemplateVariable(template, "url-port", () => url.port || "No port", dontReplaceSlash, options.filenameReplacementCharacter);
  1232. template = await Util.evalTemplateVariable(template, "url-protocol", () => url.protocol || "No protocol", dontReplaceSlash, options.filenameReplacementCharacter);
  1233. template = await Util.evalTemplateVariable(template, "url-search", () => url.search.substring(1) || "No search", dontReplaceSlash, options.filenameReplacementCharacter);
  1234. const params = url.search.substring(1).split("&").map(parameter => parameter.split("="));
  1235. for (const [name, value] of params) {
  1236. template = await Util.evalTemplateVariable(template, "url-search-" + name, () => value || "", dontReplaceSlash, options.filenameReplacementCharacter);
  1237. }
  1238. template = template.replace(/{\s*url-search-[^}\s]*\s*}/gi, "");
  1239. template = await Util.evalTemplateVariable(template, "url-username", () => url.username || "No username", dontReplaceSlash, options.filenameReplacementCharacter);
  1240. template = await Util.evalTemplateVariable(template, "tab-id", () => String(options.tabId || "No tab id"), dontReplaceSlash, options.filenameReplacementCharacter);
  1241. template = await Util.evalTemplateVariable(template, "tab-index", () => String(options.tabIndex || "No tab index"), dontReplaceSlash, options.filenameReplacementCharacter);
  1242. template = await Util.evalTemplateVariable(template, "url-last-segment", () => decodeURI(Util.getLastSegment(url, options.filenameReplacementCharacter)) || "No last segment", dontReplaceSlash, options.filenameReplacementCharacter);
  1243. if (content) {
  1244. template = await Util.evalTemplateVariable(template, "digest-sha-256", async () => util.digest("SHA-256", content), dontReplaceSlash, options.filenameReplacementCharacter);
  1245. template = await Util.evalTemplateVariable(template, "digest-sha-384", async () => util.digest("SHA-384", content), dontReplaceSlash, options.filenameReplacementCharacter);
  1246. template = await Util.evalTemplateVariable(template, "digest-sha-512", async () => util.digest("SHA-512", content), dontReplaceSlash, options.filenameReplacementCharacter);
  1247. }
  1248. return template.trim();
  1249. }
  1250. static setBackgroundImage(element, url, style) {
  1251. element.style.setProperty("background-blend-mode", "normal", "important");
  1252. element.style.setProperty("background-clip", "content-box", "important");
  1253. element.style.setProperty("background-position", style && style["background-position"] ? style["background-position"] : "center", "important");
  1254. element.style.setProperty("background-color", style && style["background-color"] ? style["background-color"] : "transparent", "important");
  1255. element.style.setProperty("background-image", url, "important");
  1256. element.style.setProperty("background-size", style && style["background-size"] ? style["background-size"] : "100% 100%", "important");
  1257. element.style.setProperty("background-origin", "content-box", "important");
  1258. element.style.setProperty("background-repeat", "no-repeat", "important");
  1259. }
  1260. static processShortcutIcons(doc) {
  1261. let shortcutIcon = Util.findShortcutIcon(Array.from(doc.querySelectorAll("link[href][rel=\"icon\"], link[href][rel=\"shortcut icon\"]")));
  1262. if (!shortcutIcon) {
  1263. shortcutIcon = Util.findShortcutIcon(Array.from(doc.querySelectorAll("link[href][rel*=\"icon\"]")));
  1264. if (shortcutIcon) {
  1265. shortcutIcon.rel = "icon";
  1266. }
  1267. }
  1268. if (shortcutIcon) {
  1269. doc.querySelectorAll("link[href][rel*=\"icon\"]").forEach(linkElement => {
  1270. if (linkElement != shortcutIcon) {
  1271. linkElement.remove();
  1272. }
  1273. });
  1274. }
  1275. }
  1276. static removeSingleLineCssComments(stylesheet) {
  1277. const removedRules = [];
  1278. for (let cssRule = stylesheet.children.head; cssRule; cssRule = cssRule.next) {
  1279. const ruleData = cssRule.data;
  1280. if (ruleData.type == "Raw" && ruleData.value && ruleData.value.trim().startsWith("//")) {
  1281. removedRules.push(cssRule);
  1282. }
  1283. }
  1284. removedRules.forEach(cssRule => stylesheet.children.remove(cssRule));
  1285. }
  1286. static async resolveImportURLs(stylesheetContent, baseURI, options, workStylesheet) {
  1287. stylesheetContent = ProcessorHelper.resolveStylesheetURLs(stylesheetContent, baseURI);
  1288. const imports = Util.getImportFunctions(stylesheetContent);
  1289. await Promise.all(imports.map(async cssImport => {
  1290. const match = Util.matchImport(cssImport);
  1291. if (match) {
  1292. let resourceURL = Util.normalizeURL(match.resourceURL);
  1293. if (!Util.testIgnoredPath(resourceURL) && Util.testValidPath(resourceURL)) {
  1294. try {
  1295. resourceURL = util.resolveURL(match.resourceURL, baseURI);
  1296. } catch (error) {
  1297. // ignored
  1298. }
  1299. if (Util.testValidURL(resourceURL)) {
  1300. const content = await util.getContent(resourceURL, {
  1301. maxResourceSize: options.maxResourceSize,
  1302. maxResourceSizeEnabled: options.maxResourceSizeEnabled,
  1303. validateTextContentType: true,
  1304. referrerPolicy: options.referrerPolicy,
  1305. credentials: options.credentials
  1306. });
  1307. resourceURL = content.resourceURL;
  1308. let importedStylesheetContent = Util.removeCssComments(content.data);
  1309. if (options.compressCSS) {
  1310. importedStylesheetContent = util.compressCSS(importedStylesheetContent);
  1311. }
  1312. importedStylesheetContent = Util.wrapMediaQuery(importedStylesheetContent, match.media);
  1313. if (stylesheetContent.includes(cssImport)) {
  1314. importedStylesheetContent = await ProcessorHelper.resolveImportURLs(importedStylesheetContent, resourceURL, options, workStylesheet);
  1315. workStylesheet.textContent = importedStylesheetContent;
  1316. if (workStylesheet.sheet.cssRules.length) {
  1317. stylesheetContent = stylesheetContent.replace(Util.getRegExp(cssImport), importedStylesheetContent);
  1318. } else {
  1319. stylesheetContent = stylesheetContent.replace(Util.getRegExp(cssImport), "");
  1320. }
  1321. }
  1322. }
  1323. }
  1324. }
  1325. }));
  1326. return stylesheetContent;
  1327. }
  1328. static resolveStylesheetURLs(stylesheetContent, baseURI) {
  1329. const urlFunctions = Util.getUrlFunctions(stylesheetContent);
  1330. urlFunctions.map(urlFunction => {
  1331. const originalResourceURL = Util.matchURL(urlFunction);
  1332. const resourceURL = Util.normalizeURL(originalResourceURL);
  1333. if (!Util.testIgnoredPath(resourceURL)) {
  1334. if (!resourceURL || Util.testValidPath(resourceURL)) {
  1335. let resolvedURL;
  1336. try {
  1337. resolvedURL = util.resolveURL(resourceURL, baseURI);
  1338. } catch (error) {
  1339. // ignored
  1340. }
  1341. if (Util.testValidURL(resolvedURL) && resourceURL != resolvedURL && stylesheetContent.includes(urlFunction)) {
  1342. stylesheetContent = stylesheetContent.replace(Util.getRegExp(urlFunction), urlFunction.replace(originalResourceURL, resolvedURL));
  1343. }
  1344. } else {
  1345. let newUrlFunction;
  1346. if (originalResourceURL) {
  1347. newUrlFunction = urlFunction.replace(originalResourceURL, EMPTY_DATA_URI);
  1348. } else {
  1349. newUrlFunction = "url(" + EMPTY_DATA_URI + ")";
  1350. }
  1351. stylesheetContent = stylesheetContent.replace(Util.getRegExp(urlFunction), newUrlFunction);
  1352. }
  1353. }
  1354. });
  1355. return stylesheetContent;
  1356. }
  1357. static async resolveLinkStylesheetURLs(resourceURL, baseURI, options, workStylesheet) {
  1358. resourceURL = Util.normalizeURL(resourceURL);
  1359. if (resourceURL && resourceURL != baseURI && resourceURL != ABOUT_BLANK_URI) {
  1360. const content = await util.getContent(resourceURL, {
  1361. maxResourceSize: options.maxResourceSize,
  1362. maxResourceSizeEnabled: options.maxResourceSizeEnabled,
  1363. charset: options.charset,
  1364. referrerPolicy: options.referrerPolicy,
  1365. credentials: options.credentials
  1366. });
  1367. resourceURL = content.resourceURL;
  1368. let stylesheetContent = Util.removeCssComments(content.data);
  1369. if (options.compressCSS) {
  1370. stylesheetContent = util.compressCSS(stylesheetContent);
  1371. }
  1372. stylesheetContent = await ProcessorHelper.resolveImportURLs(stylesheetContent, resourceURL, options, workStylesheet);
  1373. return stylesheetContent;
  1374. }
  1375. }
  1376. static async processStylesheet(cssRules, baseURI, options, cssVariables, batchRequest) {
  1377. const promises = [];
  1378. const removedRules = [];
  1379. for (let cssRule = cssRules.head; cssRule; cssRule = cssRule.next) {
  1380. const ruleData = cssRule.data;
  1381. if (ruleData.type == "Atrule" && ruleData.name == "charset") {
  1382. removedRules.push(cssRule);
  1383. } else if (ruleData.block && ruleData.block.children) {
  1384. if (ruleData.type == "Rule") {
  1385. promises.push(this.processStyle(ruleData.block.children.toArray(), baseURI, options, cssVariables, batchRequest));
  1386. } else if (ruleData.type == "Atrule" && (ruleData.name == "media" || ruleData.name == "supports")) {
  1387. promises.push(this.processStylesheet(ruleData.block.children, baseURI, options, cssVariables, batchRequest));
  1388. } else if (ruleData.type == "Atrule" && ruleData.name == "font-face") {
  1389. promises.push(processFontFaceRule(ruleData));
  1390. }
  1391. }
  1392. }
  1393. removedRules.forEach(cssRule => cssRules.remove(cssRule));
  1394. await Promise.all(promises);
  1395. async function processFontFaceRule(ruleData) {
  1396. await Promise.all(ruleData.block.children.toArray().map(async declaration => {
  1397. if (declaration.type == "Declaration" && declaration.value.children) {
  1398. const urlFunctions = Util.getUrlFunctions(Util.getCSSValue(declaration.value));
  1399. await Promise.all(urlFunctions.map(async urlFunction => {
  1400. const originalResourceURL = Util.matchURL(urlFunction);
  1401. const resourceURL = Util.normalizeURL(originalResourceURL);
  1402. if (!Util.testIgnoredPath(resourceURL)) {
  1403. if (Util.testValidURL(resourceURL)) {
  1404. let { content } = await batchRequest.addURL(resourceURL, true);
  1405. if (content != EMPTY_DATA_URI && !content.startsWith(PREFIX_DATA_URI_VND) && !content.startsWith(PREFIX_DATA_URI_IMAGE_SVG)) {
  1406. const validResource = await util.validFont(urlFunction);
  1407. if (!validResource) {
  1408. content = EMPTY_DATA_URI;
  1409. }
  1410. }
  1411. replaceURLs(declaration, originalResourceURL, content);
  1412. }
  1413. } else if (resourceURL.startsWith(DATA_URI_PREFIX) && !resourceURL.startsWith(PREFIX_DATA_URI_VND) && !resourceURL.startsWith(PREFIX_DATA_URI_IMAGE_SVG)) {
  1414. const validResource = await util.validFont(urlFunction);
  1415. if (!validResource) {
  1416. replaceURLs(declaration, originalResourceURL, EMPTY_DATA_URI);
  1417. }
  1418. }
  1419. }));
  1420. }
  1421. }));
  1422. function replaceURLs(declaration, oldURL, newURL) {
  1423. declaration.value.children.forEach(token => {
  1424. if (token.type == "Url" && util.removeQuotes(Util.getCSSValue(token.value)) == oldURL) {
  1425. token.value.value = newURL;
  1426. }
  1427. });
  1428. }
  1429. }
  1430. }
  1431. static async processStyle(declarations, baseURI, options, cssVariables, batchRequest) {
  1432. await Promise.all(declarations.map(async declaration => {
  1433. if (declaration.type == "Declaration" && declaration.value.children) {
  1434. const urlFunctions = Util.getUrlFunctions(Util.getCSSValue(declaration.value));
  1435. await Promise.all(urlFunctions.map(async urlFunction => {
  1436. const originalResourceURL = Util.matchURL(urlFunction);
  1437. const resourceURL = Util.normalizeURL(originalResourceURL);
  1438. if (!Util.testIgnoredPath(resourceURL)) {
  1439. if (Util.testValidURL(resourceURL)) {
  1440. let { content, indexResource, duplicate } = await batchRequest.addURL(resourceURL, true, true);
  1441. let variableDefined;
  1442. const tokens = [];
  1443. findURLToken(originalResourceURL, declaration.value.children, (token, parent, rootFunction) => {
  1444. if (duplicate && options.groupDuplicateImages && rootFunction) {
  1445. const value = cssTree.parse("var(" + SINGLE_FILE_VARIABLE_NAME_PREFIX + indexResource + ")", { context: "value" }).children.head;
  1446. tokens.push({ parent, token, value });
  1447. variableDefined = true;
  1448. } else {
  1449. token.data.value.value = content;
  1450. }
  1451. });
  1452. if (variableDefined) {
  1453. cssVariables.set(indexResource, content);
  1454. tokens.forEach(({ parent, token, value }) => parent.replace(token, value));
  1455. }
  1456. }
  1457. }
  1458. }));
  1459. }
  1460. }));
  1461. function findURLToken(url, children, callback, depth = 0) {
  1462. for (let token = children.head; token; token = token.next) {
  1463. if (token.data.children) {
  1464. findURLToken(url, token.data.children, callback, depth + 1);
  1465. }
  1466. if (token.data.type == "Url" && util.removeQuotes(Util.getCSSValue(token.data.value)) == url) {
  1467. callback(token, children, depth == 0);
  1468. }
  1469. }
  1470. }
  1471. }
  1472. static async processAttribute(resourceElements, attributeName, baseURI, options, cssVariables, styles, batchRequest, processDuplicates, removeElementIfMissing) {
  1473. await Promise.all(Array.from(resourceElements).map(async resourceElement => {
  1474. let resourceURL = resourceElement.getAttribute(attributeName);
  1475. resourceURL = Util.normalizeURL(resourceURL);
  1476. if (!Util.testIgnoredPath(resourceURL)) {
  1477. resourceElement.setAttribute(attributeName, EMPTY_IMAGE);
  1478. if (Util.testValidPath(resourceURL)) {
  1479. try {
  1480. resourceURL = util.resolveURL(resourceURL, baseURI);
  1481. } catch (error) {
  1482. // ignored
  1483. }
  1484. if (Util.testValidURL(resourceURL)) {
  1485. const { content, indexResource, duplicate } = await batchRequest.addURL(resourceURL, true, resourceElement.tagName == "IMG" && attributeName == "src");
  1486. if (removeElementIfMissing && content == EMPTY_DATA_URI) {
  1487. resourceElement.remove();
  1488. } else {
  1489. const forbiddenPrefixFound = PREFIXES_FORBIDDEN_DATA_URI.filter(prefixDataURI => content.startsWith(prefixDataURI)).length;
  1490. if (!forbiddenPrefixFound) {
  1491. const isSVG = content.startsWith(PREFIX_DATA_URI_IMAGE_SVG);
  1492. if (processDuplicates && duplicate && options.groupDuplicateImages && !isSVG) {
  1493. if (ProcessorHelper.replaceImageSource(resourceElement, SINGLE_FILE_VARIABLE_NAME_PREFIX + indexResource, options)) {
  1494. cssVariables.set(indexResource, content);
  1495. const declarationList = cssTree.parse(resourceElement.getAttribute("style"), { context: "declarationList" });
  1496. styles.set(resourceElement, declarationList);
  1497. } else {
  1498. resourceElement.setAttribute(attributeName, content);
  1499. }
  1500. } else {
  1501. resourceElement.setAttribute(attributeName, content);
  1502. }
  1503. }
  1504. }
  1505. }
  1506. }
  1507. }
  1508. }));
  1509. }
  1510. static async processXLinks(resourceElements, baseURI, options, batchRequest) {
  1511. const attributeName = "xlink:href";
  1512. await Promise.all(Array.from(resourceElements).map(async resourceElement => {
  1513. const originalResourceURL = resourceElement.getAttribute(attributeName);
  1514. let resourceURL = Util.normalizeURL(originalResourceURL);
  1515. if (Util.testValidPath(resourceURL) && !Util.testIgnoredPath(resourceURL)) {
  1516. resourceElement.setAttribute(attributeName, EMPTY_IMAGE);
  1517. try {
  1518. resourceURL = util.resolveURL(resourceURL, baseURI);
  1519. } catch (error) {
  1520. // ignored
  1521. }
  1522. if (Util.testValidURL(resourceURL)) {
  1523. const { content } = await batchRequest.addURL(resourceURL);
  1524. const hashMatch = originalResourceURL.match(REGEXP_URL_HASH);
  1525. if (hashMatch && hashMatch[0]) {
  1526. let symbolElement;
  1527. try {
  1528. symbolElement = util.parseSVGContent(content).querySelector(hashMatch[0]);
  1529. } catch (error) {
  1530. // ignored
  1531. }
  1532. if (symbolElement) {
  1533. resourceElement.setAttribute(attributeName, hashMatch[0]);
  1534. resourceElement.parentElement.insertBefore(symbolElement, resourceElement.parentElement.firstChild);
  1535. }
  1536. } else {
  1537. resourceElement.setAttribute(attributeName, PREFIX_DATA_URI_IMAGE_SVG + "," + content);
  1538. }
  1539. }
  1540. } else if (resourceURL == options.url) {
  1541. resourceElement.setAttribute(attributeName, originalResourceURL.substring(resourceURL.length));
  1542. }
  1543. }));
  1544. }
  1545. static async processSrcset(resourceElements, attributeName, baseURI, batchRequest) {
  1546. await Promise.all(Array.from(resourceElements).map(async resourceElement => {
  1547. const srcset = util.parseSrcset(resourceElement.getAttribute(attributeName));
  1548. const srcsetValues = await Promise.all(srcset.map(async srcsetValue => {
  1549. let resourceURL = Util.normalizeURL(srcsetValue.url);
  1550. if (!Util.testIgnoredPath(resourceURL)) {
  1551. if (Util.testValidPath(resourceURL)) {
  1552. try {
  1553. resourceURL = util.resolveURL(resourceURL, baseURI);
  1554. } catch (error) {
  1555. // ignored
  1556. }
  1557. if (Util.testValidURL(resourceURL)) {
  1558. const { content } = await batchRequest.addURL(resourceURL, true);
  1559. const forbiddenPrefixFound = PREFIXES_FORBIDDEN_DATA_URI.filter(prefixDataURI => content.startsWith(prefixDataURI)).length;
  1560. if (forbiddenPrefixFound) {
  1561. return "";
  1562. }
  1563. return content + (srcsetValue.w ? " " + srcsetValue.w + "w" : srcsetValue.d ? " " + srcsetValue.d + "x" : "");
  1564. } else {
  1565. return "";
  1566. }
  1567. } else {
  1568. return "";
  1569. }
  1570. } else {
  1571. return resourceURL + (srcsetValue.w ? " " + srcsetValue.w + "w" : srcsetValue.d ? " " + srcsetValue.d + "x" : "");
  1572. }
  1573. }));
  1574. resourceElement.setAttribute(attributeName, srcsetValues.join(", "));
  1575. }));
  1576. }
  1577. static replaceImageSource(imgElement, variableName, options) {
  1578. const attributeValue = imgElement.getAttribute(util.IMAGE_ATTRIBUTE_NAME);
  1579. if (attributeValue) {
  1580. const imageData = options.images[Number(imgElement.getAttribute(util.IMAGE_ATTRIBUTE_NAME))];
  1581. if (imageData && imageData.replaceable) {
  1582. 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>`);
  1583. const backgroundStyle = {};
  1584. const backgroundSize = (imageData.objectFit == "content" || imageData.objectFit == "cover") && imageData.objectFit;
  1585. if (backgroundSize) {
  1586. backgroundStyle["background-size"] = imageData.objectFit;
  1587. }
  1588. if (imageData.objectPosition) {
  1589. backgroundStyle["background-position"] = imageData.objectPosition;
  1590. }
  1591. if (imageData.backgroundColor) {
  1592. backgroundStyle["background-color"] = imageData.backgroundColor;
  1593. }
  1594. ProcessorHelper.setBackgroundImage(imgElement, "var(" + variableName + ")", backgroundStyle);
  1595. imgElement.removeAttribute(util.IMAGE_ATTRIBUTE_NAME);
  1596. return true;
  1597. }
  1598. }
  1599. }
  1600. }
  1601. // ----
  1602. // Util
  1603. // ----
  1604. const BLOB_URI_PREFIX = "blob:";
  1605. const HTTP_URI_PREFIX = /^https?:\/\//;
  1606. const FILE_URI_PREFIX = /^file:\/\//;
  1607. const EMPTY_URL = /^https?:\/\/+\s*$/;
  1608. const NOT_EMPTY_URL = /^(https?:\/\/|file:\/\/|blob:).+/;
  1609. const REGEXP_URL_FN = /(url\s*\(\s*'(.*?)'\s*\))|(url\s*\(\s*"(.*?)"\s*\))|(url\s*\(\s*(.*?)\s*\))/gi;
  1610. const REGEXP_URL_SIMPLE_QUOTES_FN = /^url\s*\(\s*'(.*?)'\s*\)$/i;
  1611. const REGEXP_URL_DOUBLE_QUOTES_FN = /^url\s*\(\s*"(.*?)"\s*\)$/i;
  1612. const REGEXP_URL_NO_QUOTES_FN = /^url\s*\(\s*(.*?)\s*\)$/i;
  1613. 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;
  1614. const REGEXP_IMPORT_URL_SIMPLE_QUOTES_FN = /@import\s*url\s*\(\s*'(.*?)'\s*\)\s*(.*?)(;|$|})/i;
  1615. const REGEXP_IMPORT_URL_DOUBLE_QUOTES_FN = /@import\s*url\s*\(\s*"(.*?)"\s*\)\s*(.*?)(;|$|})/i;
  1616. const REGEXP_IMPORT_URL_NO_QUOTES_FN = /@import\s*url\s*\(\s*(.*?)\s*\)\s*(.*?)(;|$|})/i;
  1617. const REGEXP_IMPORT_SIMPLE_QUOTES_FN = /@import\s*'(.*?)'\s*(.*?)(;|$|})/i;
  1618. const REGEXP_IMPORT_DOUBLE_QUOTES_FN = /@import\s*"(.*?)"\s*(.*?)(;|$|})/i;
  1619. const REGEXP_IMPORT_NO_QUOTES_FN = /@import\s*(.*?)\s*(.*?)(;|$|})/i;
  1620. const REGEXP_ESCAPE = /([{}()^$&.*?/+|[\\\\]|\]|-)/g;
  1621. class Util {
  1622. static normalizeURL(url) {
  1623. if (!url || url.startsWith(DATA_URI_PREFIX)) {
  1624. return url;
  1625. } else {
  1626. return url.split("#")[0];
  1627. }
  1628. }
  1629. static getCSSValue(value) {
  1630. let result = "";
  1631. try {
  1632. result = cssTree.generate(value);
  1633. } catch (error) {
  1634. // ignored
  1635. }
  1636. return result;
  1637. }
  1638. static getOnEventAttributeNames(doc) {
  1639. const element = doc.createElement("div");
  1640. const attributeNames = [];
  1641. for (const propertyName in element) {
  1642. if (propertyName.startsWith("on")) {
  1643. attributeNames.push(propertyName);
  1644. }
  1645. }
  1646. return attributeNames;
  1647. }
  1648. static async evalTemplateVariable(template, variableName, valueGetter, dontReplaceSlash, replacementCharacter) {
  1649. const replaceRegExp = new RegExp("{\\s*" + variableName.replace(/\W|_/g, "[$&]") + "\\s*}", "g");
  1650. if (template && template.match(replaceRegExp)) {
  1651. let value = await valueGetter();
  1652. if (!dontReplaceSlash) {
  1653. value = value.replace(/\/+/g, replacementCharacter);
  1654. }
  1655. return template.replace(replaceRegExp, value);
  1656. }
  1657. return template;
  1658. }
  1659. static getLastSegment(url, replacementCharacter) {
  1660. let lastSegmentMatch = url.pathname.match(/\/([^/]+)$/), lastSegment = lastSegmentMatch && lastSegmentMatch[0];
  1661. if (!lastSegment) {
  1662. lastSegmentMatch = url.href.match(/([^/]+)\/?$/);
  1663. lastSegment = lastSegmentMatch && lastSegmentMatch[0];
  1664. }
  1665. if (!lastSegment) {
  1666. lastSegmentMatch = lastSegment.match(/(.*)\.[^.]+$/);
  1667. lastSegment = lastSegmentMatch && lastSegmentMatch[0];
  1668. }
  1669. if (!lastSegment) {
  1670. lastSegment = url.hostname.replace(/\/+/g, replacementCharacter).replace(/\/$/, "");
  1671. }
  1672. lastSegmentMatch = lastSegment.match(/(.*)\.[^.]+$/);
  1673. if (lastSegmentMatch && lastSegmentMatch[1]) {
  1674. lastSegment = lastSegmentMatch[1];
  1675. }
  1676. lastSegment = lastSegment.replace(/\/$/, "").replace(/^\//, "");
  1677. return lastSegment;
  1678. }
  1679. static getRegExp(string) {
  1680. return new RegExp(string.replace(REGEXP_ESCAPE, "\\$1"), "gi");
  1681. }
  1682. static getUrlFunctions(stylesheetContent) {
  1683. return Array.from(new Set(stylesheetContent.match(REGEXP_URL_FN) || []));
  1684. }
  1685. static getImportFunctions(stylesheetContent) {
  1686. return stylesheetContent.match(REGEXP_IMPORT_FN) || [];
  1687. }
  1688. static findShortcutIcon(shortcutIcons) {
  1689. shortcutIcons = shortcutIcons.filter(linkElement => linkElement.href != EMPTY_IMAGE);
  1690. shortcutIcons.sort((linkElement1, linkElement2) => (parseInt(linkElement2.sizes, 10) || 16) - (parseInt(linkElement1.sizes, 10) || 16));
  1691. return shortcutIcons[0];
  1692. }
  1693. static matchURL(stylesheetContent) {
  1694. const match = stylesheetContent.match(REGEXP_URL_SIMPLE_QUOTES_FN) ||
  1695. stylesheetContent.match(REGEXP_URL_DOUBLE_QUOTES_FN) ||
  1696. stylesheetContent.match(REGEXP_URL_NO_QUOTES_FN);
  1697. return match && match[1];
  1698. }
  1699. static testIgnoredPath(resourceURL) {
  1700. return resourceURL && (resourceURL.startsWith(DATA_URI_PREFIX) || resourceURL == ABOUT_BLANK_URI);
  1701. }
  1702. static testValidPath(resourceURL) {
  1703. return resourceURL && !resourceURL.match(EMPTY_URL);
  1704. }
  1705. static testValidURL(resourceURL) {
  1706. return Util.testValidPath(resourceURL) && (resourceURL.match(HTTP_URI_PREFIX) || resourceURL.match(FILE_URI_PREFIX) || resourceURL.startsWith(BLOB_URI_PREFIX)) && resourceURL.match(NOT_EMPTY_URL);
  1707. }
  1708. static matchImport(stylesheetContent) {
  1709. const match = stylesheetContent.match(REGEXP_IMPORT_URL_SIMPLE_QUOTES_FN) ||
  1710. stylesheetContent.match(REGEXP_IMPORT_URL_DOUBLE_QUOTES_FN) ||
  1711. stylesheetContent.match(REGEXP_IMPORT_URL_NO_QUOTES_FN) ||
  1712. stylesheetContent.match(REGEXP_IMPORT_SIMPLE_QUOTES_FN) ||
  1713. stylesheetContent.match(REGEXP_IMPORT_DOUBLE_QUOTES_FN) ||
  1714. stylesheetContent.match(REGEXP_IMPORT_NO_QUOTES_FN);
  1715. if (match) {
  1716. const [, resourceURL, media] = match;
  1717. return { resourceURL, media };
  1718. }
  1719. }
  1720. static removeCssComments(stylesheetContent) {
  1721. let start, end;
  1722. do {
  1723. start = stylesheetContent.indexOf("/*");
  1724. end = stylesheetContent.indexOf("*/", start + 2);
  1725. if (start != -1 && end != -1) {
  1726. stylesheetContent = stylesheetContent.substring(0, start) + stylesheetContent.substr(end + 2);
  1727. }
  1728. } while (start != -1 && end != -1);
  1729. return stylesheetContent;
  1730. }
  1731. static wrapMediaQuery(stylesheetContent, mediaQuery) {
  1732. if (mediaQuery) {
  1733. return "@media " + mediaQuery + "{ " + stylesheetContent + " }";
  1734. } else {
  1735. return stylesheetContent;
  1736. }
  1737. }
  1738. }
  1739. function log(...args) {
  1740. console.log("S-File <core> ", ...args); // eslint-disable-line no-console
  1741. }
  1742. // -----
  1743. // Stats
  1744. // -----
  1745. const STATS_DEFAULT_VALUES = {
  1746. discarded: {
  1747. "HTML bytes": 0,
  1748. "hidden elements": 0,
  1749. "HTML imports": 0,
  1750. scripts: 0,
  1751. objects: 0,
  1752. "audio sources": 0,
  1753. "video sources": 0,
  1754. frames: 0,
  1755. "CSS rules": 0,
  1756. canvas: 0,
  1757. stylesheets: 0,
  1758. resources: 0,
  1759. medias: 0
  1760. },
  1761. processed: {
  1762. "HTML bytes": 0,
  1763. "hidden elements": 0,
  1764. "HTML imports": 0,
  1765. scripts: 0,
  1766. objects: 0,
  1767. "audio sources": 0,
  1768. "video sources": 0,
  1769. frames: 0,
  1770. "CSS rules": 0,
  1771. canvas: 0,
  1772. stylesheets: 0,
  1773. resources: 0,
  1774. medias: 0
  1775. }
  1776. };
  1777. class Stats {
  1778. constructor(options) {
  1779. this.options = options;
  1780. if (options.displayStats) {
  1781. this.data = JSON.parse(JSON.stringify(STATS_DEFAULT_VALUES));
  1782. }
  1783. }
  1784. set(type, subType, value) {
  1785. if (this.options.displayStats) {
  1786. this.data[type][subType] = value;
  1787. }
  1788. }
  1789. add(type, subType, value) {
  1790. if (this.options.displayStats) {
  1791. this.data[type][subType] += value;
  1792. }
  1793. }
  1794. addAll(pageData) {
  1795. if (this.options.displayStats) {
  1796. Object.keys(this.data.discarded).forEach(key => this.add("discarded", key, pageData.stats.discarded[key] || 0));
  1797. Object.keys(this.data.processed).forEach(key => this.add("processed", key, pageData.stats.processed[key] || 0));
  1798. }
  1799. }
  1800. }
  1801. return { getClass };
  1802. })();