single-file-core 1.1.78 → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,801 @@
1
+ /*
2
+ * Copyright 2010-2022 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
+
24
+ /* global globalThis */
25
+
26
+ import * as cssTree from "./../../vendor/css-tree.js";
27
+ import {
28
+ normalizeFontFamily,
29
+ getFontWeight
30
+ } from "./../helper.js";
31
+
32
+ const JSON = globalThis.JSON;
33
+ const FontFace = globalThis.FontFace;
34
+
35
+ const ABOUT_BLANK_URI = "about:blank";
36
+ const UTF8_CHARSET = "utf-8";
37
+
38
+ const REGEXP_URL_SIMPLE_QUOTES_FN = /url\s*\(\s*'(.*?)'\s*\)/i;
39
+ const REGEXP_URL_DOUBLE_QUOTES_FN = /url\s*\(\s*"(.*?)"\s*\)/i;
40
+ const REGEXP_URL_NO_QUOTES_FN = /url\s*\(\s*(.*?)\s*\)/i;
41
+ const REGEXP_URL_FUNCTION = /(url|local|-sf-url-original)\(.*?\)\s*(,|$)/g;
42
+ const REGEXP_SIMPLE_QUOTES_STRING = /^'(.*?)'$/;
43
+ const REGEXP_DOUBLE_QUOTES_STRING = /^"(.*?)"$/;
44
+ const REGEXP_URL_FUNCTION_WOFF = /^url\(\s*["']?data:font\/(woff2?)/;
45
+ const REGEXP_URL_FUNCTION_WOFF_ALT = /^url\(\s*["']?data:application\/x-font-(woff)/;
46
+ const REGEXP_FONT_FORMAT = /\.([^.?#]+)((\?|#).*?)?$/;
47
+ const REGEXP_FONT_FORMAT_VALUE = /format\((.*?)\)\s*,?$/;
48
+ const REGEXP_FONT_SRC = /(.*?)\s*,?$/;
49
+ const EMPTY_URL_SOURCE = /^url\(["']?data:[^,]*,?["']?\)/;
50
+ const LOCAL_SOURCE = "local(";
51
+ const MEDIA_ALL = "all";
52
+ const FONT_STRETCHES = {
53
+ "ultra-condensed": "50%",
54
+ "extra-condensed": "62.5%",
55
+ "condensed": "75%",
56
+ "semi-condensed": "87.5%",
57
+ "normal": "100%",
58
+ "semi-expanded": "112.5%",
59
+ "expanded": "125%",
60
+ "extra-expanded": "150%",
61
+ "ultra-expanded": "200%"
62
+ };
63
+ const FONT_MAX_LOAD_DELAY = 5000;
64
+
65
+ let util;
66
+
67
+ import {
68
+ getProcessorHelperCommonClass,
69
+ getUpdatedResourceContent,
70
+ normalizeURL,
71
+ matchCharsetEquals,
72
+ getCharset,
73
+ getUrlFunctions,
74
+ getImportFunctions,
75
+ isDataURL,
76
+ replaceOriginalURLs,
77
+ testIgnoredPath,
78
+ testValidPath,
79
+ testValidURL
80
+ } from "./processor-helper-common.js";
81
+
82
+ export {
83
+ getProcessorHelperClass,
84
+ cssTree
85
+ };
86
+
87
+ function getProcessorHelperClass(utilInstance) {
88
+ util = utilInstance;
89
+ const ProcessorHelperCommon = getProcessorHelperCommonClass(util, cssTree);
90
+
91
+ return class ProcessorHelper extends ProcessorHelperCommon {
92
+ async processPageResources(doc, baseURI, options, resources, styles, batchRequest) {
93
+ const processAttributeArgs = [
94
+ ["link[href][rel*=\"icon\"]", "href", true],
95
+ ["object[type=\"image/svg+xml\"], object[type=\"image/svg-xml\"], object[data*=\".svg\"]", "data"],
96
+ ["img[src], input[src][type=image]", "src"],
97
+ ["embed[src*=\".svg\"]", "src"],
98
+ ["video[poster]", "poster"],
99
+ ["*[background]", "background"],
100
+ ["image", "xlink:href"],
101
+ ["image", "href"]
102
+ ];
103
+ if (options.blockImages) {
104
+ doc.querySelectorAll("svg").forEach(element => element.remove());
105
+ }
106
+ let resourcePromises = processAttributeArgs.map(([selector, attributeName, removeElementIfMissing]) =>
107
+ this.processAttribute(doc.querySelectorAll(selector), attributeName, baseURI, options, "image", resources, batchRequest, removeElementIfMissing)
108
+ );
109
+ resourcePromises = resourcePromises.concat([
110
+ this.processXLinks(doc.querySelectorAll("use"), doc, baseURI, options, batchRequest),
111
+ this.processSrcset(doc.querySelectorAll("img[srcset], source[srcset]"), baseURI, options, resources, batchRequest)
112
+ ]);
113
+ resourcePromises.push(this.processAttribute(doc.querySelectorAll("object[data*=\".pdf\"]"), "data", baseURI, options, null, resources, batchRequest));
114
+ resourcePromises.push(this.processAttribute(doc.querySelectorAll("embed[src*=\".pdf\"]"), "src", baseURI, options, null, resources, batchRequest));
115
+ resourcePromises.push(this.processAttribute(doc.querySelectorAll("audio[src], audio > source[src]"), "src", baseURI, options, "audio", resources, batchRequest));
116
+ resourcePromises.push(this.processAttribute(doc.querySelectorAll("video[src], video > source[src]"), "src", baseURI, options, "video", resources, batchRequest));
117
+ resourcePromises.push(this.processAttribute(doc.querySelectorAll("model[src]"), "src", baseURI, options, null, resources, batchRequest));
118
+ await Promise.all(resourcePromises);
119
+ if (options.saveFavicon) {
120
+ this.processShortcutIcons(doc);
121
+ }
122
+ }
123
+
124
+ async processLinkElement(element, stylesheetInfo, stylesheets, baseURI, options, workStyleElement, resources) {
125
+ if (element.tagName.toUpperCase() == "LINK") {
126
+ element.removeAttribute("integrity");
127
+ if (element.charset) {
128
+ options.charset = element.charset;
129
+ }
130
+ stylesheetInfo.url = element.href;
131
+ }
132
+ await this.processStylesheetElement(element, stylesheetInfo, stylesheets, baseURI, options, workStyleElement, resources);
133
+ }
134
+
135
+ async processStylesheetElement(element, stylesheetInfo, stylesheets, baseURI, options, workStyleElement, resources) {
136
+ if (options.blockStylesheets) {
137
+ if (element.tagName.toUpperCase() == "LINK") {
138
+ element.href = util.EMPTY_RESOURCE;
139
+ } else {
140
+ element.textContent = "";
141
+ }
142
+ } else {
143
+ if (element.tagName.toUpperCase() == "LINK") {
144
+ await this.resolveLinkStylesheetURLs(stylesheetInfo, element, element.href, baseURI, options, workStyleElement, resources, stylesheets);
145
+ } else {
146
+ stylesheets.set({ element }, stylesheetInfo);
147
+ stylesheetInfo.stylesheet = cssTree.parse(element.textContent, { context: "stylesheet", parseCustomProperty: true });
148
+ await this.resolveImportURLs(stylesheetInfo, baseURI, options, workStyleElement, resources, stylesheets);
149
+ }
150
+ }
151
+ }
152
+
153
+ replaceStylesheets(doc, stylesheets, resources, options) {
154
+ for (const [key, stylesheetInfo] of stylesheets) {
155
+ if (key.urlNode) {
156
+ const name = "stylesheet_" + resources.stylesheets.size + ".css";
157
+ if (!isDataURL(stylesheetInfo.url) && options.saveOriginalURLs) {
158
+ key.urlNode.value = "-sf-url-original(" + JSON.stringify(stylesheetInfo.url) + ") " + name;
159
+ } else {
160
+ key.urlNode.value = name;
161
+ }
162
+ resources.stylesheets.set(resources.stylesheets.size, { name, content: this.generateStylesheetContent(stylesheetInfo.stylesheet, options), url: stylesheetInfo.url });
163
+ }
164
+ }
165
+ for (const [key, stylesheetInfo] of stylesheets) {
166
+ if (key.element) {
167
+ if (key.element.tagName.toUpperCase() == "LINK") {
168
+ const linkElement = key.element;
169
+ const name = "stylesheet_" + resources.stylesheets.size + ".css";
170
+ linkElement.setAttribute("href", name);
171
+ resources.stylesheets.set(resources.stylesheets.size, { name, content: this.generateStylesheetContent(stylesheetInfo.stylesheet, options), url: stylesheetInfo.url });
172
+ } else {
173
+ const styleElement = key.element;
174
+ styleElement.textContent = this.generateStylesheetContent(stylesheetInfo.stylesheet, options);
175
+ }
176
+ }
177
+ }
178
+ }
179
+
180
+ async resolveImportURLs(stylesheetInfo, baseURI, options, workStylesheet, resources, stylesheets) {
181
+ const stylesheet = stylesheetInfo.stylesheet;
182
+ const scoped = stylesheetInfo.scoped;
183
+ this.resolveStylesheetURLs(stylesheet, baseURI, workStylesheet);
184
+ const imports = getImportFunctions(stylesheet);
185
+ await Promise.all(imports.map(async node => {
186
+ const urlNode = cssTree.find(node, node => node.type == "Url") || cssTree.find(node, node => node.type == "String");
187
+ if (urlNode) {
188
+ let resourceURL = normalizeURL(urlNode.value);
189
+ if (!testIgnoredPath(resourceURL) && testValidPath(resourceURL)) {
190
+ urlNode.value = util.EMPTY_RESOURCE;
191
+ try {
192
+ resourceURL = util.resolveURL(resourceURL, baseURI);
193
+ } catch (error) {
194
+ // ignored
195
+ }
196
+ if (testValidURL(resourceURL)) {
197
+ const mediaQueryListNode = cssTree.find(node, node => node.type == "MediaQueryList");
198
+ let mediaText;
199
+ if (mediaQueryListNode) {
200
+ mediaText = cssTree.generate(mediaQueryListNode);
201
+ }
202
+ const existingStylesheet = Array.from(stylesheets).find(([, stylesheetInfo]) => stylesheetInfo.resourceURL == resourceURL);
203
+ if (existingStylesheet) {
204
+ stylesheets.set({ urlNode }, {
205
+ url: resourceURL,
206
+ stylesheet: existingStylesheet[1].stylesheet, scoped
207
+ });
208
+ } else {
209
+ const stylesheetInfo = {
210
+ scoped,
211
+ mediaText
212
+ };
213
+ stylesheets.set({ urlNode }, stylesheetInfo);
214
+ const content = await this.getStylesheetContent(resourceURL, options);
215
+ stylesheetInfo.url = resourceURL = content.resourceURL;
216
+ const existingStylesheet = Array.from(stylesheets).find(([, stylesheetInfo]) => stylesheetInfo.resourceURL == resourceURL);
217
+ if (existingStylesheet) {
218
+ stylesheets.set({ urlNode }, { url: resourceURL, stylesheet: existingStylesheet[1].stylesheet, scoped });
219
+ } else {
220
+ content.data = getUpdatedResourceContent(resourceURL, content, options);
221
+ stylesheetInfo.stylesheet = cssTree.parse(content.data, { context: "stylesheet", parseCustomProperty: true });
222
+ await this.resolveImportURLs(stylesheetInfo, resourceURL, options, workStylesheet, resources, stylesheets);
223
+ }
224
+ }
225
+ }
226
+ }
227
+ }
228
+ }));
229
+ }
230
+
231
+ async resolveLinkStylesheetURLs(stylesheetInfo, element, resourceURL, baseURI, options, workStylesheet, resources, stylesheets) {
232
+ resourceURL = normalizeURL(resourceURL);
233
+ if (resourceURL && resourceURL != baseURI && resourceURL != ABOUT_BLANK_URI) {
234
+ const existingStylesheet = Array.from(stylesheets).find(([, otherStylesheetInfo]) => otherStylesheetInfo.resourceURL == resourceURL);
235
+ if (existingStylesheet) {
236
+ stylesheets.set({ element }, {
237
+ url: resourceURL,
238
+ stylesheet: existingStylesheet[1].stylesheet,
239
+ mediaText: stylesheetInfo.mediaText
240
+ });
241
+ } else {
242
+ stylesheets.set({ element }, stylesheetInfo);
243
+ const content = await util.getContent(resourceURL, {
244
+ maxResourceSize: options.maxResourceSize,
245
+ maxResourceSizeEnabled: options.maxResourceSizeEnabled,
246
+ charset: options.charset,
247
+ frameId: options.frameId,
248
+ resourceReferrer: options.resourceReferrer,
249
+ validateTextContentType: true,
250
+ baseURI: baseURI,
251
+ blockMixedContent: options.blockMixedContent,
252
+ expectedType: "stylesheet",
253
+ acceptHeaders: options.acceptHeaders,
254
+ networkTimeout: options.networkTimeout
255
+ });
256
+ if (!(matchCharsetEquals(content.data, content.charset) || matchCharsetEquals(content.data, options.charset))) {
257
+ options = Object.assign({}, options, { charset: getCharset(content.data) });
258
+ this.resolveLinkStylesheetURLs(stylesheetInfo, element, resourceURL, baseURI, options, workStylesheet, resources, stylesheets);
259
+ }
260
+ resourceURL = content.resourceURL;
261
+ if (existingStylesheet) {
262
+ stylesheets.set({ element }, {
263
+ url: resourceURL,
264
+ stylesheet: existingStylesheet[1].stylesheet,
265
+ mediaText: stylesheetInfo.mediaText
266
+ });
267
+ } else {
268
+ content.data = getUpdatedResourceContent(content.resourceURL, content, options);
269
+ stylesheetInfo.stylesheet = cssTree.parse(content.data, { context: "stylesheet", parseCustomProperty: true });
270
+ await this.resolveImportURLs(stylesheetInfo, resourceURL, options, workStylesheet, resources, stylesheets);
271
+ }
272
+ }
273
+ }
274
+ }
275
+
276
+ async processFrame(frameElement, pageData, resources, frameWindowId, frameData) {
277
+ const name = "frames/" + resources.frames.size + "/";
278
+ if (frameElement.tagName.toUpperCase() == "OBJECT") {
279
+ frameElement.setAttribute("data", name + "index.html");
280
+ } else {
281
+ frameElement.setAttribute("src", name + "index.html");
282
+ }
283
+ resources.frames.set(frameWindowId, { name, content: pageData.content, resources: pageData.resources, url: frameData.url });
284
+ }
285
+
286
+ async processStylesheet(cssRules, baseURI, options, resources, batchRequest) {
287
+ const promises = [];
288
+ const removedRules = [];
289
+ for (let cssRule = cssRules.head; cssRule; cssRule = cssRule.next) {
290
+ const ruleData = cssRule.data;
291
+ if (ruleData.type == "Atrule" && ruleData.name == "charset") {
292
+ removedRules.push(cssRule);
293
+ } else if (ruleData.block && ruleData.block.children) {
294
+ if (ruleData.type == "Rule") {
295
+ promises.push(this.processStyle(ruleData, options, resources, batchRequest));
296
+ } else if (ruleData.type == "Atrule" && (ruleData.name == "media" || ruleData.name == "supports")) {
297
+ promises.push(this.processStylesheet(ruleData.block.children, baseURI, options, resources, batchRequest));
298
+ } else if (ruleData.type == "Atrule" && ruleData.name == "font-face") {
299
+ promises.push(processFontFaceRule(ruleData));
300
+ }
301
+ }
302
+ }
303
+ removedRules.forEach(cssRule => cssRules.remove(cssRule));
304
+ await Promise.all(promises);
305
+
306
+ async function processFontFaceRule(ruleData) {
307
+ const urls = getUrlFunctions(ruleData);
308
+ await Promise.all(urls.map(async urlNode => {
309
+ const originalResourceURL = urlNode.value;
310
+ if (!options.blockFonts) {
311
+ const resourceURL = normalizeURL(originalResourceURL);
312
+ if (!testIgnoredPath(resourceURL) && testValidURL(resourceURL)) {
313
+ let { content, extension, indexResource, contentType } = await batchRequest.addURL(resourceURL,
314
+ { asBinary: true, expectedType: "font", baseURI, blockMixedContent: options.blockMixedContent });
315
+ const name = "fonts/" + indexResource + extension;
316
+ if (!isDataURL(resourceURL) && options.saveOriginalURLs) {
317
+ urlNode.value = "-sf-url-original(" + JSON.stringify(originalResourceURL) + ") " + name;
318
+ } else {
319
+ urlNode.value = name;
320
+ }
321
+ resources.fonts.set(indexResource, { name, content, extension, contentType, url: resourceURL });
322
+ }
323
+ } else {
324
+ urlNode.value = util.EMPTY_RESOURCE;
325
+ }
326
+ }));
327
+ }
328
+ }
329
+
330
+ async processStyle(ruleData, options, resources, batchRequest) {
331
+ const urls = getUrlFunctions(ruleData);
332
+ await Promise.all(urls.map(async urlNode => {
333
+ const originalResourceURL = urlNode.value;
334
+ if (!options.blockImages) {
335
+ const resourceURL = normalizeURL(originalResourceURL);
336
+ if (!testIgnoredPath(resourceURL) && testValidURL(resourceURL)) {
337
+ let { content, indexResource, contentType, extension } = await batchRequest.addURL(resourceURL,
338
+ { asBinary: true, expectedType: "image" });
339
+ const name = "images/" + indexResource + extension;
340
+ if (!isDataURL(resourceURL) && options.saveOriginalURLs) {
341
+ urlNode.value = "-sf-url-original(" + JSON.stringify(originalResourceURL) + ") " + name;
342
+ } else {
343
+ urlNode.value = name;
344
+ }
345
+ resources.images.set(indexResource, { name, content, extension, contentType, url: resourceURL });
346
+ }
347
+ } else {
348
+ urlNode.value = util.EMPTY_RESOURCE;
349
+ }
350
+ }));
351
+ }
352
+
353
+ async processAttribute(resourceElements, attributeName, baseURI, options, expectedType, resources, batchRequest, removeElementIfMissing) {
354
+ await Promise.all(Array.from(resourceElements).map(async resourceElement => {
355
+ let resourceURL = resourceElement.getAttribute(attributeName);
356
+ if (resourceURL != null) {
357
+ resourceURL = normalizeURL(resourceURL);
358
+ let originURL = resourceElement.dataset.singleFileOriginURL;
359
+ if (options.saveOriginalURLs && !isDataURL(resourceURL)) {
360
+ resourceElement.setAttribute("data-sf-original-" + attributeName, resourceURL);
361
+ }
362
+ delete resourceElement.dataset.singleFileOriginURL;
363
+ if (!options["block" + expectedType.charAt(0).toUpperCase() + expectedType.substring(1) + "s"]) {
364
+ if (!testIgnoredPath(resourceURL)) {
365
+ setAttributeEmpty(resourceElement, attributeName, expectedType);
366
+ if (testValidPath(resourceURL)) {
367
+ try {
368
+ resourceURL = util.resolveURL(resourceURL, baseURI);
369
+ } catch (error) {
370
+ // ignored
371
+ }
372
+ if (testValidURL(resourceURL)) {
373
+ let { content, indexResource, extension, contentType } = await batchRequest.addURL(resourceURL,
374
+ { asBinary: true, expectedType });
375
+ if (originURL) {
376
+ if (this.testEmptyResource(content)) {
377
+ try {
378
+ originURL = util.resolveURL(originURL, baseURI);
379
+ } catch (error) {
380
+ // ignored
381
+ }
382
+ try {
383
+ resourceURL = originURL;
384
+ content = (await util.getContent(resourceURL, {
385
+ asBinary: true,
386
+ expectedType,
387
+ maxResourceSize: options.maxResourceSize,
388
+ maxResourceSizeEnabled: options.maxResourceSizeEnabled,
389
+ frameId: options.windowId,
390
+ resourceReferrer: options.resourceReferrer,
391
+ acceptHeaders: options.acceptHeaders,
392
+ networkTimeout: options.networkTimeout
393
+ })).data;
394
+ } catch (error) {
395
+ // ignored
396
+ }
397
+ }
398
+ }
399
+ if (removeElementIfMissing && this.testEmptyResource(content)) {
400
+ resourceElement.remove();
401
+ } else if (!this.testEmptyResource(content)) {
402
+ const name = "images/" + indexResource + extension;
403
+ resourceElement.setAttribute(attributeName, name);
404
+ resources.images.set(indexResource, { name, content, extension, contentType, url: resourceURL });
405
+ }
406
+ }
407
+ }
408
+ }
409
+ } else {
410
+ setAttributeEmpty(resourceElement, attributeName, expectedType);
411
+ }
412
+ }
413
+ }));
414
+
415
+ function setAttributeEmpty(resourceElement, attributeName, expectedType) {
416
+ if (expectedType == "video" || expectedType == "audio") {
417
+ resourceElement.removeAttribute(attributeName);
418
+ } else {
419
+ resourceElement.setAttribute(attributeName, util.EMPTY_RESOURCE);
420
+ }
421
+ }
422
+ }
423
+
424
+ async processSrcset(resourceElements, baseURI, options, resources, batchRequest) {
425
+ await Promise.all(Array.from(resourceElements).map(async resourceElement => {
426
+ const originSrcset = resourceElement.getAttribute("srcset");
427
+ const srcset = util.parseSrcset(originSrcset);
428
+ if (options.saveOriginalURLs && !isDataURL(originSrcset)) {
429
+ resourceElement.setAttribute("data-sf-original-srcset", originSrcset);
430
+ }
431
+ if (!options.blockImages) {
432
+ const srcsetValues = await Promise.all(srcset.map(async srcsetValue => {
433
+ let resourceURL = normalizeURL(srcsetValue.url);
434
+ if (!testIgnoredPath(resourceURL)) {
435
+ if (testValidPath(resourceURL)) {
436
+ try {
437
+ resourceURL = util.resolveURL(resourceURL, baseURI);
438
+ } catch (error) {
439
+ // ignored
440
+ }
441
+ if (testValidURL(resourceURL)) {
442
+ const { content, indexResource, extension, contentType } = await batchRequest.addURL(resourceURL, { asBinary: true, expectedType: "image" });
443
+ const name = "images/" + indexResource + extension;
444
+ resources.images.set(indexResource, { name, content, extension, contentType, url: resourceURL });
445
+ return name + (srcsetValue.w ? " " + srcsetValue.w + "w" : srcsetValue.d ? " " + srcsetValue.d + "x" : "");
446
+ } else {
447
+ return "";
448
+ }
449
+ } else {
450
+ return "";
451
+ }
452
+ } else {
453
+ return resourceURL + (srcsetValue.w ? " " + srcsetValue.w + "w" : srcsetValue.d ? " " + srcsetValue.d + "x" : "");
454
+ }
455
+ }));
456
+ resourceElement.setAttribute("srcset", srcsetValues.join(", "));
457
+ } else {
458
+ resourceElement.setAttribute("srcset", "");
459
+ }
460
+ }));
461
+ }
462
+
463
+ testEmptyResource(resource) {
464
+ return !resource;
465
+ }
466
+
467
+ generateStylesheetContent(stylesheet, options) {
468
+ if (options.compressCSS) {
469
+ this.removeSingleLineCssComments(stylesheet);
470
+ }
471
+ this.replacePseudoClassDefined(stylesheet);
472
+ let stylesheetContent = cssTree.generate(stylesheet);
473
+ if (options.compressCSS) {
474
+ stylesheetContent = util.compressCSS(stylesheetContent);
475
+ }
476
+ if (options.saveOriginalURLs) {
477
+ stylesheetContent = replaceOriginalURLs(stylesheetContent);
478
+ }
479
+ return stylesheetContent;
480
+ }
481
+
482
+ getAdditionalPageData(doc, content, pageResources) {
483
+ const resources = {};
484
+ let textContent = content;
485
+ pageResources.stylesheets.forEach(resource => textContent += resource.content);
486
+ Object.keys(pageResources).forEach(resourceType => {
487
+ const unusedResources = Array.from(pageResources[resourceType]).filter(([, value]) => !textContent.includes(value.name));
488
+ unusedResources.forEach(([indexResource]) => pageResources[resourceType].delete(indexResource));
489
+ resources[resourceType] = Array.from(pageResources[resourceType].values());
490
+ });
491
+ const viewportElement = doc.head.querySelector("meta[name=viewport]");
492
+ const viewport = viewportElement ? viewportElement.content : null;
493
+ const doctype = util.getDoctypeString(doc);
494
+ return {
495
+ doctype,
496
+ resources,
497
+ viewport
498
+ };
499
+ }
500
+
501
+ removeAlternativeFonts(doc, stylesheets, fontResources, fontTests) {
502
+ return removeAlternativeFonts(doc, stylesheets, fontResources, fontTests);
503
+ }
504
+
505
+ async processScript(element, resourceURL) {
506
+ const content = await util.getContent(resourceURL, {
507
+ asBinary: true,
508
+ charset: this.charset != UTF8_CHARSET && this.charset,
509
+ maxResourceSize: this.options.maxResourceSize,
510
+ maxResourceSizeEnabled: this.options.maxResourceSizeEnabled,
511
+ frameId: this.options.windowId,
512
+ resourceReferrer: this.options.resourceReferrer,
513
+ baseURI: this.options.baseURI,
514
+ blockMixedContent: this.options.blockMixedContent,
515
+ expectedType: "script",
516
+ acceptHeaders: this.options.acceptHeaders,
517
+ networkTimeout: this.options.networkTimeout
518
+ });
519
+ content.data = getUpdatedResourceContent(resourceURL, content, this.options);
520
+ element.setAttribute("src", content.data);
521
+ }
522
+
523
+ setMetaCSP(metaElement) {
524
+ metaElement.content = "default-src 'none'; font-src 'self' data: blob:; img-src 'self' data: blob:; style-src 'self' 'unsafe-inline' data: blob:; frame-src 'self' data: blob:; media-src 'self' data: blob:; script-src 'self' 'unsafe-inline' data: blob:; object-src 'self' data: blob:;";
525
+ }
526
+
527
+ removeUnusedStylesheets() {
528
+ }
529
+ };
530
+ }
531
+
532
+ async function removeAlternativeFonts(doc, stylesheets, fontResources, fontTests) {
533
+ const fontsDetails = {
534
+ fonts: new Map(),
535
+ medias: new Map(),
536
+ supports: new Map()
537
+ };
538
+ const stats = { rules: { processed: 0, discarded: 0 }, fonts: { processed: 0, discarded: 0 } };
539
+ let sheetIndex = 0;
540
+ stylesheets.forEach(stylesheetInfo => {
541
+ const cssRules = stylesheetInfo.stylesheet.children;
542
+ if (cssRules) {
543
+ stats.rules.processed += cssRules.size;
544
+ stats.rules.discarded += cssRules.size;
545
+ if (stylesheetInfo.mediaText && stylesheetInfo.mediaText != MEDIA_ALL) {
546
+ const mediaFontsDetails = createFontsDetailsInfo();
547
+ fontsDetails.medias.set("media-" + sheetIndex + "-" + stylesheetInfo.mediaText, mediaFontsDetails);
548
+ getFontsDetails(doc, cssRules, sheetIndex, mediaFontsDetails);
549
+ } else {
550
+ getFontsDetails(doc, cssRules, sheetIndex, fontsDetails);
551
+ }
552
+ }
553
+ sheetIndex++;
554
+ });
555
+ processFontDetails(fontsDetails, fontResources);
556
+ await Promise.all([...stylesheets].map(async ([, stylesheetInfo], sheetIndex) => {
557
+ const cssRules = stylesheetInfo.stylesheet.children;
558
+ const media = stylesheetInfo.mediaText;
559
+ if (cssRules) {
560
+ if (media && media != MEDIA_ALL) {
561
+ await processFontFaceRules(cssRules, sheetIndex, fontsDetails.medias.get("media-" + sheetIndex + "-" + media), fontResources, fontTests, stats);
562
+ } else {
563
+ await processFontFaceRules(cssRules, sheetIndex, fontsDetails, fontResources, fontTests, stats);
564
+ }
565
+ stats.rules.discarded -= cssRules.size;
566
+ }
567
+ }));
568
+ return stats;
569
+ }
570
+
571
+ function getFontsDetails(doc, cssRules, sheetIndex, mediaFontsDetails) {
572
+ let mediaIndex = 0, supportsIndex = 0;
573
+ cssRules.forEach(ruleData => {
574
+ if (ruleData.type == "Atrule" && ruleData.name == "media" && ruleData.block && ruleData.block.children && ruleData.prelude) {
575
+ const mediaText = cssTree.generate(ruleData.prelude);
576
+ const fontsDetails = createFontsDetailsInfo();
577
+ mediaFontsDetails.medias.set("media-" + sheetIndex + "-" + mediaIndex + "-" + mediaText, fontsDetails);
578
+ mediaIndex++;
579
+ getFontsDetails(doc, ruleData.block.children, sheetIndex, fontsDetails);
580
+ } else if (ruleData.type == "Atrule" && ruleData.name == "supports" && ruleData.block && ruleData.block.children && ruleData.prelude) {
581
+ const supportsText = cssTree.generate(ruleData.prelude);
582
+ const fontsDetails = createFontsDetailsInfo();
583
+ mediaFontsDetails.supports.set("supports-" + sheetIndex + "-" + supportsIndex + "-" + supportsText, fontsDetails);
584
+ supportsIndex++;
585
+ getFontsDetails(doc, ruleData.block.children, sheetIndex, fontsDetails);
586
+ } else if (ruleData.type == "Atrule" && ruleData.name == "font-face" && ruleData.block && ruleData.block.children) {
587
+ const fontKey = getFontKey(ruleData);
588
+ let fontInfo = mediaFontsDetails.fonts.get(fontKey);
589
+ if (!fontInfo) {
590
+ fontInfo = [];
591
+ mediaFontsDetails.fonts.set(fontKey, fontInfo);
592
+ }
593
+ const src = getPropertyValue(ruleData, "src");
594
+ if (src) {
595
+ const fontSources = src.match(REGEXP_URL_FUNCTION);
596
+ if (fontSources) {
597
+ fontSources.forEach(source => fontInfo.unshift(source));
598
+ }
599
+ }
600
+ }
601
+ });
602
+ }
603
+
604
+ function processFontDetails(fontsDetails, fontResources) {
605
+ fontsDetails.fonts.forEach((fontInfo, fontKey) => {
606
+ fontsDetails.fonts.set(fontKey, fontInfo.map(fontSource => {
607
+ const fontFormatMatch = fontSource.match(REGEXP_FONT_FORMAT_VALUE);
608
+ let fontFormat;
609
+ const fontUrl = getURL(fontSource);
610
+ if (fontFormatMatch && fontFormatMatch[1]) {
611
+ fontFormat = fontFormatMatch[1].replace(REGEXP_SIMPLE_QUOTES_STRING, "$1").replace(REGEXP_DOUBLE_QUOTES_STRING, "$1").toLowerCase();
612
+ }
613
+ if (!fontFormat) {
614
+ const fontFormatMatch = fontSource.match(REGEXP_URL_FUNCTION_WOFF);
615
+ if (fontFormatMatch && fontFormatMatch[1]) {
616
+ fontFormat = fontFormatMatch[1];
617
+ } else {
618
+ const fontFormatMatch = fontSource.match(REGEXP_URL_FUNCTION_WOFF_ALT);
619
+ if (fontFormatMatch && fontFormatMatch[1]) {
620
+ fontFormat = fontFormatMatch[1];
621
+ }
622
+ }
623
+ }
624
+ if (!fontFormat && fontUrl) {
625
+ const fontFormatMatch = fontUrl.match(REGEXP_FONT_FORMAT);
626
+ if (fontFormatMatch && fontFormatMatch[1]) {
627
+ fontFormat = fontFormatMatch[1];
628
+ }
629
+ }
630
+ const fontResource = Array.from(fontResources.values()).find(info => info.name == fontUrl);
631
+ return { src: fontSource.match(REGEXP_FONT_SRC)[1], fontUrl, format: fontFormat, contentType: fontResource && fontResource.contentType };
632
+ }));
633
+ });
634
+ fontsDetails.medias.forEach(mediaFontsDetails => processFontDetails(mediaFontsDetails, fontResources));
635
+ fontsDetails.supports.forEach(supportsFontsDetails => processFontDetails(supportsFontsDetails, fontResources));
636
+ }
637
+
638
+ async function processFontFaceRules(cssRules, sheetIndex, fontsDetails, fontResources, fontTests, stats) {
639
+ const removedRules = [];
640
+ let mediaIndex = 0, supportsIndex = 0;
641
+ for (let cssRule = cssRules.head; cssRule; cssRule = cssRule.next) {
642
+ const ruleData = cssRule.data;
643
+ if (ruleData.type == "Atrule" && ruleData.name == "media" && ruleData.block && ruleData.block.children && ruleData.prelude) {
644
+ const mediaText = cssTree.generate(ruleData.prelude);
645
+ await processFontFaceRules(ruleData.block.children, sheetIndex, fontsDetails.medias.get("media-" + sheetIndex + "-" + mediaIndex + "-" + mediaText), fontResources, fontTests, stats);
646
+ mediaIndex++;
647
+ } else if (ruleData.type == "Atrule" && ruleData.name == "supports" && ruleData.block && ruleData.block.children && ruleData.prelude) {
648
+ const supportsText = cssTree.generate(ruleData.prelude);
649
+ await processFontFaceRules(ruleData.block.children, sheetIndex, fontsDetails.supports.get("supports-" + sheetIndex + "-" + supportsIndex + "-" + supportsText), fontResources, fontTests, stats);
650
+ supportsIndex++;
651
+ } else if (ruleData.type == "Atrule" && ruleData.name == "font-face") {
652
+ const key = getFontKey(ruleData);
653
+ const fontInfo = fontsDetails.fonts.get(key);
654
+ if (fontInfo) {
655
+ fontsDetails.fonts.delete(key);
656
+ await processFontFaceRule(ruleData, fontInfo, fontResources, fontTests, stats);
657
+ } else {
658
+ removedRules.push(cssRule);
659
+ }
660
+ }
661
+ }
662
+ removedRules.forEach(cssRule => cssRules.remove(cssRule));
663
+ }
664
+
665
+ async function processFontFaceRule(ruleData, fontInfo, fontResources, fontTests, stats) {
666
+ await Promise.all(fontInfo.map(async source => {
667
+ if (fontTests.has(source.src)) {
668
+ source.valid = fontTests.get(source.src);
669
+ } else {
670
+ if (FontFace && source.fontUrl) {
671
+ const resourceEntry = [...fontResources].find(([, resource]) => source.fontUrl && resource.name == source.fontUrl);
672
+ if (resourceEntry) {
673
+ const resource = resourceEntry[1];
674
+ const fontFace = new FontFace("test-font", new Uint8Array(resource.content).buffer);
675
+ try {
676
+ let timeout;
677
+ await Promise.race([
678
+ fontFace.load().then(() => fontFace.loaded).then(() => { source.valid = true; globalThis.clearTimeout(timeout); }),
679
+ new Promise(resolve => timeout = globalThis.setTimeout(() => { source.valid = true; resolve(); }, FONT_MAX_LOAD_DELAY))
680
+ ]);
681
+ } catch (error) {
682
+ const fontFace = new FontFace("test-font", "url(" + resource.url + ")");
683
+ try {
684
+ let timeout;
685
+ await Promise.race([
686
+ fontFace.load().then(() => fontFace.loaded).then(() => { source.valid = true; globalThis.clearTimeout(timeout); }),
687
+ new Promise(resolve => timeout = globalThis.setTimeout(() => { source.valid = true; resolve(); }, FONT_MAX_LOAD_DELAY))
688
+ ]);
689
+ } catch (error) {
690
+ // ignored
691
+ }
692
+ }
693
+ } else {
694
+ source.valid = true;
695
+ }
696
+ } else {
697
+ source.valid = true;
698
+ }
699
+ fontTests.set(source.src, source.valid);
700
+ }
701
+ }));
702
+ const findSourceByFormat = (fontFormat, testValidity) => fontInfo.find(source => !source.src.match(EMPTY_URL_SOURCE) && source.format == fontFormat && (!testValidity || source.valid));
703
+ const findSourceByContentType = (contentType, testValidity) => fontInfo.find(source => !source.src.match(EMPTY_URL_SOURCE) && source.contentType == contentType && (!testValidity || source.valid));
704
+ const filterSources = fontSource => fontInfo.filter(source => source == fontSource || source.src.startsWith(LOCAL_SOURCE));
705
+ stats.fonts.processed += fontInfo.length;
706
+ stats.fonts.discarded += fontInfo.length;
707
+ const woffFontFound =
708
+ findSourceByFormat("woff2-variations", true) || findSourceByFormat("woff2", true) || findSourceByFormat("woff", true) ||
709
+ findSourceByContentType("font/woff2", true) || findSourceByContentType("font/woff", true) || findSourceByContentType("application/font-woff", true) || findSourceByContentType("application/x-font-woff", true);
710
+ if (woffFontFound) {
711
+ fontInfo = filterSources(woffFontFound);
712
+ } else {
713
+ const ttfFontFound =
714
+ findSourceByFormat("truetype-variations", true) || findSourceByFormat("truetype", true) ||
715
+ findSourceByContentType("font/ttf", true) || findSourceByContentType("application/x-font-ttf", true) || findSourceByContentType("application/x-font-ttf", true) || findSourceByContentType("application/x-font-truetype", true);
716
+ if (ttfFontFound) {
717
+ fontInfo = filterSources(ttfFontFound);
718
+ } else {
719
+ const otfFontFound =
720
+ findSourceByFormat("opentype") || findSourceByFormat("embedded-opentype") ||
721
+ findSourceByContentType("font/otf") || findSourceByContentType("application/x-font-opentype") || findSourceByContentType("application/font-sfnt");
722
+ if (otfFontFound) {
723
+ fontInfo = filterSources(otfFontFound);
724
+ } else {
725
+ fontInfo = fontInfo.filter(source => !source.src.match(EMPTY_URL_SOURCE) && (source.valid) || source.src.startsWith(LOCAL_SOURCE));
726
+ }
727
+ }
728
+ }
729
+ stats.fonts.discarded -= fontInfo.length;
730
+ const removedNodes = [];
731
+ for (let node = ruleData.block.children.head; node; node = node.next) {
732
+ if (node.data.property == "src") {
733
+ removedNodes.push(node);
734
+ }
735
+ }
736
+ removedNodes.pop();
737
+ removedNodes.forEach(node => ruleData.block.children.remove(node));
738
+ const srcDeclaration = ruleData.block.children.filter(node => node.property == "src").tail;
739
+ if (srcDeclaration) {
740
+ fontInfo.reverse();
741
+ try {
742
+ srcDeclaration.data.value = cssTree.parse(fontInfo.map(fontSource => fontSource.src).join(","), { context: "value", parseCustomProperty: true });
743
+ }
744
+ catch (error) {
745
+ // ignored
746
+ }
747
+ }
748
+ }
749
+
750
+ function getPropertyValue(ruleData, propertyName) {
751
+ let property;
752
+ if (ruleData.block.children) {
753
+ property = ruleData.block.children.filter(node => {
754
+ try {
755
+ return node.property == propertyName && !cssTree.generate(node.value).match(/\\9$/);
756
+ } catch (error) {
757
+ return node.property == propertyName;
758
+ }
759
+ }).tail;
760
+ }
761
+ if (property) {
762
+ try {
763
+ return cssTree.generate(property.data.value);
764
+ } catch (error) {
765
+ // ignored
766
+ }
767
+ }
768
+ }
769
+
770
+ function getFontKey(ruleData) {
771
+ return JSON.stringify([
772
+ normalizeFontFamily(getPropertyValue(ruleData, "font-family")),
773
+ getFontWeight(getPropertyValue(ruleData, "font-weight") || "400"),
774
+ getPropertyValue(ruleData, "font-style") || "normal",
775
+ getPropertyValue(ruleData, "unicode-range"),
776
+ getFontStretch(getPropertyValue(ruleData, "font-stretch")),
777
+ getPropertyValue(ruleData, "font-variant") || "normal",
778
+ getPropertyValue(ruleData, "font-feature-settings"),
779
+ getPropertyValue(ruleData, "font-variation-settings")
780
+ ]);
781
+ }
782
+
783
+ function getFontStretch(stretch) {
784
+ return FONT_STRETCHES[stretch] || stretch;
785
+ }
786
+
787
+ function createFontsDetailsInfo() {
788
+ return {
789
+ fonts: new Map(),
790
+ medias: new Map(),
791
+ supports: new Map()
792
+ };
793
+ }
794
+
795
+ function getURL(urlFunction) {
796
+ urlFunction = urlFunction.replace(/url\(-sf-url-original\\\(\\"(.*?)\\"\\\)\\ /g, "");
797
+ const urlMatch = urlFunction.match(REGEXP_URL_SIMPLE_QUOTES_FN) ||
798
+ urlFunction.match(REGEXP_URL_DOUBLE_QUOTES_FN) ||
799
+ urlFunction.match(REGEXP_URL_NO_QUOTES_FN);
800
+ return urlMatch && urlMatch[1];
801
+ }