single-file-core.js 81 KB

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