single-file-core.js 82 KB

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