single-file-core.js 75 KB

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