single-file-core.js 78 KB

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