single-file-core.js 81 KB

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