single-file-core.js 78 KB

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