single-file-core.js 79 KB

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