single-file-core.js 84 KB

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