single-file-core.js 81 KB

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