single-file-core.js 73 KB

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