single-file-core.js 72 KB

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