single-file-core 1.9.0 → 1.10.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.
package/core/index.js CHANGED
@@ -105,6 +105,7 @@ const STAGES = [{
105
105
  sequential: [
106
106
  { action: "preProcessPage" },
107
107
  { option: "loadDeferredContentKeepZoomLevel", action: "resetZoomLevel" },
108
+ { option: "loadDeferredContentKeepEmulatedScreenSize", action: "resetZoomLevel" },
108
109
  { action: "replaceStyleContents" },
109
110
  { action: "replaceInvalidElements" },
110
111
  { action: "resetCharsetMeta" },
@@ -58,10 +58,14 @@ const REGEXP_FONT_FORMAT_SUPPORTS = /^(\S+)\s+supports\s+(.+)$/;
58
58
  const REGEXP_FONT_SRC = /(.*?)\s*,?$/;
59
59
  const MEDIA_ALL = "all";
60
60
  const Blob = globalThis.Blob;
61
+ const atob = globalThis.atob;
62
+ const TextDecoder = globalThis.TextDecoder;
63
+ const Uint8Array = globalThis.Uint8Array;
61
64
  const Image = globalThis.Image;
62
65
  const OffscreenCanvas = globalThis.OffscreenCanvas;
63
66
  const DEFAULT_IMAGE_QUALITY = 0.8;
64
67
  const SVG_NAMESPACE = "http://www.w3.org/2000/svg";
68
+ const XMLNS_NAMESPACE = "http://www.w3.org/2000/xmlns/";
65
69
 
66
70
  let util, cssTree;
67
71
 
@@ -81,7 +85,10 @@ export {
81
85
  resizeImage,
82
86
  toDataURI,
83
87
  getReferrerPolicy,
84
- getStylesheetReferrer
88
+ getStylesheetReferrer,
89
+ getURLHash,
90
+ getSVGFragmentContent,
91
+ getSVGFragmentDataURI
85
92
  };
86
93
 
87
94
  function getProcessorHelperCommonClass(utilInstance, cssTreeInstance) {
@@ -159,16 +166,7 @@ class ProcessorHelperCommon {
159
166
  const response = await batchRequest.addURL(resourceURL, { expectedType: "image" });
160
167
  const svgDoc = util.parseSVGContent(response.content);
161
168
  if (hashMatch && hashMatch[0]) {
162
- const symbolId = hashMatch[0].substring(1);
163
- let symbolElement = svgDoc.getElementById(symbolId);
164
- if (!symbolElement) {
165
- try {
166
- symbolElement = svgDoc.getElementById(decodeURIComponent(symbolId));
167
- // eslint-disable-next-line no-unused-vars
168
- } catch (error) {
169
- // ignored
170
- }
171
- }
169
+ const symbolElement = getFragmentElement(svgDoc, hashMatch[0]);
172
170
  if (symbolElement) {
173
171
  resourceElement.setAttribute(attributeName, hashMatch[0]);
174
172
  resourceElement.parentElement.insertBefore(symbolElement, resourceElement.parentElement.firstChild);
@@ -421,7 +419,7 @@ class ProcessorHelperCommon {
421
419
  }
422
420
  }
423
421
  if (testValidURL(resolvedURL)) {
424
- urlNode.value = resolvedURL;
422
+ urlNode.value = resolvedURL + getURLHash(originalResourceURL);
425
423
  if (stylesheetReferrer && stylesheetReferrers && !stylesheetReferrers.has(normalizeURL(resolvedURL))) {
426
424
  stylesheetReferrers.set(normalizeURL(resolvedURL), stylesheetReferrer);
427
425
  }
@@ -906,6 +904,93 @@ function isDataURL(url) {
906
904
  return url && (url.startsWith(DATA_URI_PREFIX) || url.startsWith(BLOB_URI_PREFIX));
907
905
  }
908
906
 
907
+ function getURLHash(url) {
908
+ const hashMatch = url && !isDataURL(url) && url.match(REGEXP_URL_HASH);
909
+ return hashMatch ? hashMatch[0] : "";
910
+ }
911
+
912
+ function getFragmentElement(svgDoc, hash) {
913
+ const fragmentId = hash.substring(1);
914
+ let element = svgDoc.getElementById(fragmentId);
915
+ if (!element) {
916
+ try {
917
+ element = svgDoc.getElementById(decodeURIComponent(fragmentId));
918
+ } catch {
919
+ // ignored
920
+ }
921
+ }
922
+ return element;
923
+ }
924
+
925
+ function getSVGFragmentContent(svgContent, hash) {
926
+ const svgDoc = util.parseSVGContent(svgContent);
927
+ const rootElement = svgDoc.documentElement && svgDoc.documentElement.localName == "svg" ? svgDoc.documentElement : svgDoc.querySelector("svg");
928
+ const element = rootElement && getFragmentElement(svgDoc, hash);
929
+ if (element) {
930
+ let fragmentElement;
931
+ if (element.localName == "view") {
932
+ const viewBox = parseViewBox(element.getAttribute("viewBox"));
933
+ if (viewBox) {
934
+ const tileElement = Array.from(rootElement.querySelectorAll("svg")).find(svgElement => testViewBoxMatch(svgElement, viewBox));
935
+ if (tileElement) {
936
+ fragmentElement = getStandaloneSVG(tileElement);
937
+ } else {
938
+ fragmentElement = rootElement.cloneNode(true);
939
+ fragmentElement.setAttribute("viewBox", viewBox.join(" "));
940
+ }
941
+ }
942
+ } else if (element.localName == "symbol") {
943
+ fragmentElement = svgDoc.createElementNS(SVG_NAMESPACE, "svg");
944
+ ["viewBox", "preserveAspectRatio"].forEach(attributeName => {
945
+ if (element.hasAttribute(attributeName)) {
946
+ fragmentElement.setAttribute(attributeName, element.getAttribute(attributeName));
947
+ }
948
+ });
949
+ Array.from(rootElement.children).filter(child => child.localName == "defs").forEach(defsElement => fragmentElement.appendChild(defsElement.cloneNode(true)));
950
+ Array.from(element.childNodes).forEach(childNode => fragmentElement.appendChild(childNode.cloneNode(true)));
951
+ } else if (element.localName == "svg" && element != rootElement) {
952
+ fragmentElement = getStandaloneSVG(element);
953
+ }
954
+ if (fragmentElement) {
955
+ if (!fragmentElement.hasAttribute("xmlns")) {
956
+ fragmentElement.setAttributeNS(XMLNS_NAMESPACE, "xmlns", SVG_NAMESPACE);
957
+ }
958
+ return fragmentElement.outerHTML;
959
+ }
960
+ }
961
+ }
962
+
963
+ async function getSVGFragmentDataURI(dataURI, hash) {
964
+ const base64Index = dataURI.indexOf(";base64,");
965
+ if (base64Index != -1) {
966
+ const bytes = Uint8Array.from(atob(dataURI.substring(base64Index + 8)), character => character.charCodeAt(0));
967
+ const fragmentContent = getSVGFragmentContent(new TextDecoder().decode(bytes), hash);
968
+ if (fragmentContent) {
969
+ return getDataURI(new Blob([fragmentContent], { type: "image/svg+xml" }));
970
+ }
971
+ }
972
+ return dataURI + hash;
973
+ }
974
+
975
+ function getStandaloneSVG(svgElement) {
976
+ const standaloneElement = svgElement.cloneNode(true);
977
+ standaloneElement.removeAttribute("x");
978
+ standaloneElement.removeAttribute("y");
979
+ return standaloneElement;
980
+ }
981
+
982
+ function parseViewBox(value) {
983
+ const viewBox = value ? value.trim().split(/[\s,]+/).map(Number) : [];
984
+ if (viewBox.length == 4 && viewBox.every(number => !Number.isNaN(number))) {
985
+ return viewBox;
986
+ }
987
+ }
988
+
989
+ function testViewBoxMatch(svgElement, viewBox) {
990
+ const [x, y, width, height] = ["x", "y", "width", "height"].map(attributeName => Number(svgElement.getAttribute(attributeName) || (attributeName == "x" || attributeName == "y" ? 0 : NaN)));
991
+ return x == viewBox[0] && y == viewBox[1] && width == viewBox[2] && height == viewBox[3];
992
+ }
993
+
909
994
  function replaceOriginalURLs(stylesheetContent) {
910
995
  return stylesheetContent.replace(/url\(-sf-url-original\\\(\\"(.*?)\\"\\\)\\ /g, "/* original URL: $1 */url(");
911
996
  }
@@ -77,7 +77,9 @@ import {
77
77
  getReferrerPolicy,
78
78
  getStylesheetReferrer,
79
79
  resizeImage,
80
- toDataURI
80
+ toDataURI,
81
+ getURLHash,
82
+ getSVGFragmentDataURI
81
83
  } from "./processor-helper-common.js";
82
84
  import { getFontWeight } from "./../helper.js";
83
85
 
@@ -146,11 +148,15 @@ function getProcessorHelperClass(utilInstance) {
146
148
  });
147
149
  }
148
150
  });
151
+ const originIndexes = new Map();
152
+ if (options.groupDuplicateStylesheets) {
153
+ new Set(options.inlineStylesheetsRefs.values()).forEach(stylesheetRefIndex => originIndexes.set(options.inlineStylesheets.get(stylesheetRefIndex).styleElement, stylesheetRefIndex));
154
+ }
149
155
  styleElements.forEach(element => {
150
156
  const stylesheetInfo = stylesheets.get(element);
151
157
  if (stylesheetInfo) {
152
158
  stylesheets.delete(element);
153
- const stylesheetRefIndex = options.inlineStylesheetsRefs.get(element);
159
+ const stylesheetRefIndex = options.inlineStylesheetsRefs.has(element) ? options.inlineStylesheetsRefs.get(element) : originIndexes.get(element);
154
160
  if (stylesheetRefIndex !== undefined) {
155
161
  if (options.groupDuplicateStylesheets) {
156
162
  if (!doc.querySelector("style[" + DUPLICATE_STYLESHEET_ATTRIBUTE_NAME + "=\"" + stylesheetRefIndex + "\"]")) {
@@ -296,7 +302,7 @@ function getProcessorHelperClass(utilInstance) {
296
302
  async processFrame(frameElement, pageData, options) {
297
303
  let sandbox = "allow-popups allow-top-navigation-by-user-activation";
298
304
  if (pageData.content.match(NOSCRIPT_TAG_FOUND) || pageData.content.match(CANVAS_TAG_FOUND) || pageData.content.match(SCRIPT_TAG_FOUND) || options.saveRawPage) {
299
- sandbox += " allow-scripts allow-modals allow-popups allow-downloads allow-pointer-lock allow-presentation";
305
+ sandbox += " allow-scripts allow-modals allow-downloads allow-pointer-lock";
300
306
  }
301
307
  frameElement.setAttribute("sandbox", sandbox);
302
308
  if (frameElement.tagName.toUpperCase() == "OBJECT") {
@@ -340,8 +346,13 @@ function getProcessorHelperClass(utilInstance) {
340
346
  if (!testIgnoredPath(resourceURL) && testValidURL(resourceURL)) {
341
347
  let { content, indexResource, duplicate } = await batchRequest.addURL(resourceURL, { asBinary: true, expectedType: "image", groupDuplicates: options.groupDuplicateImages, ...getStylesheetReferrer(resourceURL, options) });
342
348
  if (!originalResourceURL.startsWith("#")) {
349
+ const hash = getURLHash(originalResourceURL);
350
+ const svgFragment = Boolean(hash) && content.startsWith(PREFIX_DATA_URI_IMAGE_SVG);
351
+ if (svgFragment) {
352
+ content = await getSVGFragmentDataURI(content, hash);
353
+ }
343
354
  const maxSizeDuplicateImages = options.maxSizeDuplicateImages || SINGLE_FILE_VARIABLE_MAX_SIZE;
344
- if (duplicate && options.groupDuplicateImages && util.getContentSize(content) < maxSizeDuplicateImages) {
355
+ if (!svgFragment && duplicate && options.groupDuplicateImages && util.getContentSize(content) < maxSizeDuplicateImages) {
345
356
  const varNode = cssTree.parse("var(" + SINGLE_FILE_VARIABLE_NAME_PREFIX + indexResource + ")", { context: "value" });
346
357
  for (let keyName of Object.keys(varNode.children.head.data)) {
347
358
  urlNode[keyName] = varNode.children.head.data[keyName];
@@ -366,6 +377,7 @@ function getProcessorHelperClass(utilInstance) {
366
377
  await Promise.all(Array.from(resourceElements).map(async resourceElement => {
367
378
  let resourceURL = resourceElement.getAttribute(attributeName);
368
379
  if (resourceURL != null) {
380
+ const hash = getURLHash(resourceURL);
369
381
  resourceURL = normalizeURL(resourceURL);
370
382
  let originURL = resourceElement.dataset.singleFileOriginURL;
371
383
  if (options.saveOriginalURLs && !isDataURL(resourceURL)) {
@@ -442,6 +454,9 @@ function getProcessorHelperClass(utilInstance) {
442
454
  }
443
455
  if (!forbiddenPrefixFound) {
444
456
  const isSVG = content.startsWith(PREFIX_DATA_URI_IMAGE_SVG);
457
+ if (isSVG && hash) {
458
+ content = await getSVGFragmentDataURI(content, hash);
459
+ }
445
460
  const maxSizeDuplicateImages = options.maxSizeDuplicateImages || SINGLE_FILE_VARIABLE_MAX_SIZE;
446
461
  if (processDuplicates && duplicate && !isSVG && util.getContentSize(content) < maxSizeDuplicateImages) {
447
462
  if (this.replaceImageSource(resourceElement, SINGLE_FILE_VARIABLE_NAME_PREFIX + indexResource, options)) {
@@ -28,6 +28,8 @@ import * as fontGlyphsMinifier from "./../../modules/font-glyphs-minifier.js";
28
28
  const JSON = globalThis.JSON;
29
29
  const FontFace = globalThis.FontFace;
30
30
  const Blob = globalThis.Blob;
31
+ const TextDecoder = globalThis.TextDecoder;
32
+ const TextEncoder = globalThis.TextEncoder;
31
33
 
32
34
  const ABOUT_BLANK_URI = "about:blank";
33
35
  const UTF8_CHARSET = "utf-8";
@@ -38,6 +40,7 @@ const EMPTY_URL_SOURCE = /^url\(["']?data:[^,]*,?["']?\)/;
38
40
  const LOCAL_SOURCE = "local(";
39
41
  const FONT_MAX_LOAD_DELAY = 5000;
40
42
  const SCRIPT_EXTENSION = ".js";
43
+ const SVG_EXTENSION = ".svg";
41
44
  const LINK_OWN_ATTRIBUTE_NAMES = ["rel", "type", "href", "media"];
42
45
  const CROSS_ORIGIN_ATTRIBUTE_NAME = "crossorigin";
43
46
  const SOURCE_TAG_NAME = "SOURCE";
@@ -64,7 +67,9 @@ import {
64
67
  getReferrerPolicy,
65
68
  getStylesheetReferrer,
66
69
  resizeImage,
67
- toDataURI
70
+ toDataURI,
71
+ getURLHash,
72
+ getSVGFragmentContent
68
73
  } from "./processor-helper-common.js";
69
74
 
70
75
  export {
@@ -314,7 +319,7 @@ function getProcessorHelperClass(utilInstance) {
314
319
  const name = "frames/" + resources.frames.size + "/";
315
320
  let sandbox = "allow-popups allow-top-navigation-by-user-activation allow-scripts";
316
321
  if (pageData.content.match(NOSCRIPT_TAG_FOUND) || pageData.content.match(CANVAS_TAG_FOUND) || pageData.content.match(SCRIPT_TAG_FOUND) || options.saveRawPage) {
317
- sandbox += " allow-modals allow-popups allow-downloads allow-pointer-lock allow-presentation";
322
+ sandbox += " allow-modals allow-downloads allow-pointer-lock";
318
323
  }
319
324
  frameElement.setAttribute("sandbox", sandbox);
320
325
  if (frameElement.tagName.toUpperCase() == "OBJECT") {
@@ -389,7 +394,7 @@ function getProcessorHelperClass(utilInstance) {
389
394
  const resourcesBySize = new Map();
390
395
  [...images]
391
396
  .filter(([, resource]) => resource.content && resource.content.length)
392
- .sort(([indexResource], [otherIndexResource]) => indexResource - otherIndexResource)
397
+ .sort(([indexResource], [otherIndexResource]) => compareResourceKeys(indexResource, otherIndexResource))
393
398
  .forEach(([indexResource, resource]) => {
394
399
  const sameSizeResources = resourcesBySize.get(resource.content.length) || [];
395
400
  const original = sameSizeResources.find(previousResource => testSameContent(previousResource.content, resource.content));
@@ -435,14 +440,15 @@ function getProcessorHelperClass(utilInstance) {
435
440
  if ((!testIgnoredPath(resourceURL) && testValidURL(resourceURL)) || testGeneratedDataURI(resourceURL, options)) {
436
441
  let { content, indexResource, contentType, extension } = await batchRequest.addURL(resourceURL,
437
442
  { asBinary: true, expectedType: "image", ...getStylesheetReferrer(resourceURL, options) });
438
- const name = this.testEmptyResource(content) ? util.EMPTY_RESOURCE : "images/" + indexResource + extension;
443
+ const emptyResource = this.testEmptyResource(content);
444
+ const imageResource = emptyResource ? { urlValue: util.EMPTY_RESOURCE } : getImageResource(content, indexResource, extension, getURLHash(originalResourceURL));
439
445
  if (!isDataURL(resourceURL) && options.saveOriginalURLs) {
440
- urlNode.value = "-sf-url-original(" + JSON.stringify(originalResourceURL) + ") " + name;
446
+ urlNode.value = "-sf-url-original(" + JSON.stringify(originalResourceURL) + ") " + imageResource.urlValue;
441
447
  } else {
442
- urlNode.value = name;
448
+ urlNode.value = imageResource.urlValue;
443
449
  }
444
- if (!this.testEmptyResource(content)) {
445
- resources.images.set(indexResource, { name, content, extension, contentType, url: resourceURL });
450
+ if (!emptyResource) {
451
+ resources.images.set(imageResource.key, { name: imageResource.name, content: imageResource.content, extension, contentType, url: resourceURL });
446
452
  }
447
453
  }
448
454
  } else {
@@ -455,6 +461,7 @@ function getProcessorHelperClass(utilInstance) {
455
461
  await Promise.all(Array.from(resourceElements).map(async resourceElement => {
456
462
  let resourceURL = resourceElement.getAttribute(attributeName);
457
463
  if (resourceURL != null) {
464
+ const hash = getURLHash(resourceURL);
458
465
  resourceURL = normalizeURL(resourceURL);
459
466
  let originURL = resourceElement.dataset.singleFileOriginURL;
460
467
  if (options.saveOriginalURLs && !isDataURL(resourceURL)) {
@@ -514,10 +521,10 @@ function getProcessorHelperClass(utilInstance) {
514
521
  if (removeElementIfMissing && this.testEmptyResource(content)) {
515
522
  resourceElement.remove();
516
523
  } else if (!this.testEmptyResource(content)) {
517
- const name = "images/" + indexResource + extension;
518
- resourceElement.setAttribute(attributeName, name);
524
+ const imageResource = getImageResource(content, indexResource, extension, hash);
525
+ resourceElement.setAttribute(attributeName, imageResource.urlValue);
519
526
  removeCrossOriginAttribute(resourceElement);
520
- resources.images.set(indexResource, { name, content, extension, contentType, url: resourceURL });
527
+ resources.images.set(imageResource.key, { name: imageResource.name, content: imageResource.content, extension, contentType, url: resourceURL });
521
528
  }
522
529
  }
523
530
  }
@@ -777,11 +784,33 @@ function getResourceName(value) {
777
784
  }
778
785
 
779
786
  function replaceResourceName(urlNode, canonicalNames) {
787
+ const hash = getURLHash(urlNode.value.substring(urlNode.value.lastIndexOf(" ") + 1));
788
+ const value = hash ? urlNode.value.substring(0, urlNode.value.length - hash.length) : urlNode.value;
780
789
  canonicalNames.forEach((canonicalName, name) => {
781
- if (urlNode.value == name) {
782
- urlNode.value = canonicalName;
783
- } else if (urlNode.value.endsWith(" " + name)) {
784
- urlNode.value = urlNode.value.substring(0, urlNode.value.length - name.length) + canonicalName;
790
+ if (value == name) {
791
+ urlNode.value = canonicalName + hash;
792
+ } else if (value.endsWith(" " + name)) {
793
+ urlNode.value = value.substring(0, value.length - name.length) + canonicalName + hash;
785
794
  }
786
795
  });
796
+ }
797
+
798
+ function getImageResource(content, indexResource, extension, hash) {
799
+ const name = "images/" + indexResource + extension;
800
+ if (hash && extension == SVG_EXTENSION) {
801
+ const fragmentContent = getSVGFragmentContent(new TextDecoder().decode(content), hash);
802
+ if (fragmentContent) {
803
+ const fragmentName = "images/" + indexResource + "-" + hash.substring(1).replace(/[^\w-]/g, "_") + extension;
804
+ return { content: new TextEncoder().encode(fragmentContent), key: indexResource + hash, name: fragmentName, urlValue: fragmentName };
805
+ } else {
806
+ return { content, key: indexResource, name, urlValue: name + hash };
807
+ }
808
+ }
809
+ return { content, key: indexResource, name, urlValue: name };
810
+ }
811
+
812
+ function compareResourceKeys(resourceKey, otherResourceKey) {
813
+ const index = parseInt(resourceKey, 10);
814
+ const otherIndex = parseInt(otherResourceKey, 10);
815
+ return index == otherIndex ? String(resourceKey).localeCompare(String(otherResourceKey)) : index - otherIndex;
787
816
  }
package/core/util.js CHANGED
@@ -649,10 +649,10 @@ function guessMIMEType(expectedType, buffer) {
649
649
  }
650
650
 
651
651
  function compareBytes(mask, pattern) {
652
- let patternMatch = true, index = 0;
652
+ let patternMatch = true;
653
653
  if (buffer.byteLength >= pattern.length) {
654
654
  const value = new Uint8Array(buffer, 0, mask.length);
655
- for (index = 0; index < mask.length && patternMatch; index++) {
655
+ for (let index = 0; index < mask.length && patternMatch; index++) {
656
656
  patternMatch = patternMatch && ((value[index] & mask[index]) == pattern[index]);
657
657
  }
658
658
  return patternMatch;
@@ -473,7 +473,7 @@ function buildScopeContext(parsedPrelude, processingContext, docContext) {
473
473
  const excludeSelectors = parsedPrelude && parsedPrelude.exclude ? parsedPrelude.exclude : [];
474
474
  const includeAnalysis = analyzeScopeSelectors(includeSelectors, processingContext.hasDefaultNamespace);
475
475
  const excludeAnalysis = analyzeScopeSelectors(excludeSelectors, processingContext.hasDefaultNamespace);
476
- let rootElements = [];
476
+ let rootElements;
477
477
  if (includeSelectors.length) {
478
478
  rootElements = collectScopeRootElements(includeSelectors, scopeStack, docContext);
479
479
  if (!rootElements.length && includeAnalysis.hasNestedUnqueryablePseudoClass) {
@@ -673,7 +673,6 @@ function compareSpecificities(specificityA, specificityB) {
673
673
  function analyzeSelector(selector, defaultNamespace) {
674
674
  let hasUnqueryableSelector = Boolean(defaultNamespace);
675
675
  let hasNestedUnqueryablePseudoClass = false;
676
- let startsWithCombinator = false;
677
676
  let functionalPseudoClassDepth = 0;
678
677
  cssTree.walk(selector, {
679
678
  enter(node) {
@@ -711,7 +710,7 @@ function analyzeSelector(selector, defaultNamespace) {
711
710
  }
712
711
  });
713
712
  const firstChild = selector.children.head.data;
714
- startsWithCombinator = firstChild && firstChild.type === COMBINATOR_NAME;
713
+ const startsWithCombinator = firstChild && firstChild.type === COMBINATOR_NAME;
715
714
  return { hasUnqueryableSelector, hasNestedUnqueryablePseudoClass, startsWithCombinator };
716
715
  }
717
716
 
@@ -96,6 +96,7 @@ const REGEXP_COMBINING_CHARACTER = /^[\p{M}ᅠ-ᇿ]$/u;
96
96
  const BIDI_MIRRORING_PAIRS = "\u0028\u0029\u003C\u003E\u005B\u005D\u007B\u007D\u00AB\u00BB\u0F3A\u0F3B\u0F3C\u0F3D\u169B\u169C\u2039\u203A\u2045\u2046\u207D\u207E\u208D\u208E\u2208\u220B\u2209\u220C\u220A\u220D\u2215\u29F5\u221D\u{1DB10}\u221F\u2BFE\u2220\u29A3\u2221\u299B\u2222\u29A0\u2224\u2AEE\u223C\u223D\u2243\u22CD\u2245\u224C\u2252\u2253\u2254\u2255\u2264\u2265\u2266\u2267\u2268\u2269\u226A\u226B\u226E\u226F\u2270\u2271\u2272\u2273\u2274\u2275\u2276\u2277\u2278\u2279\u227A\u227B\u227C\u227D\u227E\u227F\u2280\u2281\u2282\u2283\u2284\u2285\u2286\u2287\u2288\u2289\u228A\u228B\u228F\u2290\u2291\u2292\u2298\u29B8\u22A2\u22A3\u22A6\u2ADE\u22A8\u2AE4\u22A9\u2AE3\u22AB\u2AE5\u22B0\u22B1\u22B2\u22B3\u22B4\u22B5\u22B6\u22B7\u22B8\u27DC\u22C9\u22CA\u22CB\u22CC\u22D0\u22D1\u22D6\u22D7\u22D8\u22D9\u22DA\u22DB\u22DC\u22DD\u22DE\u22DF\u22E0\u22E1\u22E2\u22E3\u22E4\u22E5\u22E6\u22E7\u22E8\u22E9\u22EA\u22EB\u22EC\u22ED\u22F0\u22F1\u22F2\u22FA\u22F3\u22FB\u22F4\u22FC\u22F6\u22FD\u22F7\u22FE\u2308\u2309\u230A\u230B\u2329\u232A\u2768\u2769\u276A\u276B\u276C\u276D\u276E\u276F\u2770\u2771\u2772\u2773\u2774\u2775\u27C3\u27C4\u27C5\u27C6\u27C8\u27C9\u27CB\u27CD\u27D5\u27D6\u27DD\u27DE\u27E2\u27E3\u27E4\u27E5\u27E6\u27E7\u27E8\u27E9\u27EA\u27EB\u27EC\u27ED\u27EE\u27EF\u2983\u2984\u2985\u2986\u2987\u2988\u2989\u298A\u298B\u298C\u298D\u2990\u298E\u298F\u2991\u2992\u2993\u2994\u2995\u2996\u2997\u2998\u29A4\u29A5\u29A8\u29A9\u29AA\u29AB\u29AC\u29AD\u29AE\u29AF\u29C0\u29C1\u29C4\u29C5\u29CF\u29D0\u29D1\u29D2\u29D4\u29D5\u29D8\u29D9\u29DA\u29DB\u29E8\u29E9\u29F8\u29F9\u29FC\u29FD\u2A2B\u2A2C\u2A2D\u2A2E\u2A34\u2A35\u2A3C\u2A3D\u2A64\u2A65\u2A79\u2A7A\u2A7B\u2A7C\u2A7D\u2A7E\u2A7F\u2A80\u2A81\u2A82\u2A83\u2A84\u2A85\u2A86\u2A87\u2A88\u2A89\u2A8A\u2A8B\u2A8C\u2A8D\u2A8E\u2A8F\u2A90\u2A91\u2A92\u2A93\u2A94\u2A95\u2A96\u2A97\u2A98\u2A99\u2A9A\u2A9B\u2A9C\u2A9D\u2A9E\u2A9F\u2AA0\u2AA1\u2AA2\u2AA6\u2AA7\u2AA8\u2AA9\u2AAA\u2AAB\u2AAC\u2AAD\u2AAF\u2AB0\u2AB1\u2AB2\u2AB3\u2AB4\u2AB5\u2AB6\u2AB7\u2AB8\u2AB9\u2ABA\u2ABB\u2ABC\u2ABD\u2ABE\u2ABF\u2AC0\u2AC1\u2AC2\u2AC3\u2AC4\u2AC5\u2AC6\u2AC7\u2AC8\u2AC9\u2ACA\u2ACB\u2ACC\u2ACD\u2ACE\u2ACF\u2AD0\u2AD1\u2AD2\u2AD3\u2AD4\u2AD5\u2AD6\u2AEC\u2AED\u2AF7\u2AF8\u2AF9\u2AFA\u2E02\u2E03\u2E04\u2E05\u2E09\u2E0A\u2E0C\u2E0D\u2E1C\u2E1D\u2E20\u2E21\u2E22\u2E23\u2E24\u2E25\u2E26\u2E27\u2E28\u2E29\u2E55\u2E56\u2E57\u2E58\u2E59\u2E5A\u2E5B\u2E5C\u2E62\u2E63\u3008\u3009\u300A\u300B\u300C\u300D\u300E\u300F\u3010\u3011\u3014\u3015\u3016\u3017\u3018\u3019\u301A\u301B\uFE59\uFE5A\uFE5B\uFE5C\uFE5D\uFE5E\uFE64\uFE65\uFF08\uFF09\uFF1C\uFF1E\uFF3B\uFF3D\uFF5B\uFF5D\uFF5F\uFF60\uFF62\uFF63\u{1DB03}\u{1DB04}\u{1DB05}\u{1DB06}\u{1DB08}\u{1DB09}";
97
97
 
98
98
 
99
+ const ALIGNMENT_ZONE_CHAR_CODES = [0x58, 0x78];
99
100
  const DROPPED_TABLES = ["DSIG"];
100
101
  const TAG_CMAP = "cmap";
101
102
  const TAG_GLYF = "glyf";
@@ -221,6 +222,7 @@ function getDrawableCharCodes(charCodeRanges) {
221
222
  }
222
223
  return false;
223
224
  };
225
+ ALIGNMENT_ZONE_CHAR_CODES.forEach(charCode => addCharacter(String.fromCodePoint(charCode)));
224
226
  charCodeRanges.forEach(([fromCharCode, toCharCode]) => {
225
227
  for (let charCode = fromCharCode; charCode <= toCharCode; charCode++) {
226
228
  const character = String.fromCodePoint(charCode);
@@ -25,6 +25,8 @@ const VOID_TAG_NAMES = ["AREA", "BASE", "BASEFONT", "BGSOUND", "BR", "COL", "COM
25
25
 
26
26
  const Node_ELEMENT_NODE = 1;
27
27
  const Node_TEXT_NODE = 3;
28
+ const Node_CDATA_SECTION_NODE = 4;
29
+ const Node_PROCESSING_INSTRUCTION_NODE = 7;
28
30
  const Node_COMMENT_NODE = 8;
29
31
 
30
32
  // see https://www.w3.org/TR/html5/syntax.html#optional-tags
@@ -78,12 +80,16 @@ function process(doc, compressHTML, omittedEndTagElements) {
78
80
  }
79
81
 
80
82
  function serialize(node, compressHTML, omittedEndTagElements) {
81
- if (node.nodeType == Node_TEXT_NODE) {
83
+ if (node.nodeType == Node_TEXT_NODE || node.nodeType == Node_CDATA_SECTION_NODE) {
82
84
  return serializeTextNode(node);
83
85
  } else if (node.nodeType == Node_COMMENT_NODE) {
84
86
  return serializeCommentNode(node);
87
+ } else if (node.nodeType == Node_PROCESSING_INSTRUCTION_NODE) {
88
+ return serializeProcessingInstructionNode(node);
85
89
  } else if (node.nodeType == Node_ELEMENT_NODE) {
86
90
  return serializeElement(node, compressHTML, omittedEndTagElements);
91
+ } else {
92
+ return "";
87
93
  }
88
94
  }
89
95
 
@@ -107,6 +113,11 @@ function serializeCommentNode(commentNode) {
107
113
  return "<!--" + commentNode.textContent + "-->";
108
114
  }
109
115
 
116
+ function serializeProcessingInstructionNode(processingInstructionNode) {
117
+ const data = processingInstructionNode.data;
118
+ return "<?" + processingInstructionNode.target + (data ? " " + data : "") + "?>";
119
+ }
120
+
110
121
  function serializeElement(element, compressHTML, omittedEndTagElements) {
111
122
  const tagName = getTagName(element);
112
123
  const omittedStartTag = compressHTML && OMITTED_START_TAGS.find(omittedStartTag => tagName == getTagName(omittedStartTag) && omittedStartTag.accept(element));
@@ -16910,7 +16910,7 @@ async function formatFilename(content, doc, options) {
16910
16910
  }
16911
16911
  const suffix = "…" + extension;
16912
16912
  const maxLength = Math.max(options.filenameMaxLength - (options.filenameMaxLengthUnit == "bytes" ? getContentSize(suffix) : suffix.length), 0);
16913
- filename = options.filenameMaxLengthUnit == "bytes" ? await truncateText(filename, maxLength) : filename.substring(0, maxLength);
16913
+ filename = options.filenameMaxLengthUnit == "bytes" ? await truncateText(filename, maxLength) : truncateCharacters(filename, maxLength);
16914
16914
  filename = filename + suffix;
16915
16915
  }
16916
16916
  if (!filename) {
@@ -17321,6 +17321,11 @@ function getLastSegment(url, replacementCharacter) {
17321
17321
  return lastSegment;
17322
17322
  }
17323
17323
 
17324
+ function truncateCharacters(content, maxLength) {
17325
+ const truncatedContent = content.substring(0, maxLength);
17326
+ return /[\uD800-\uDBFF]$/.test(truncatedContent) ? truncatedContent.slice(0, -1) : truncatedContent;
17327
+ }
17328
+
17324
17329
  async function truncateText(content, maxSize) {
17325
17330
  const blob = new Blob([content]);
17326
17331
  const truncatedBlob = blob.slice(0, maxSize);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "single-file-core",
3
- "version": "1.9.0",
3
+ "version": "1.10.0",
4
4
  "description": "SingleFile Core",
5
5
  "author": "Gildas Lormeau",
6
6
  "license": "AGPL-3.0-or-later",
@@ -29,7 +29,7 @@
29
29
  },
30
30
  "homepage": "https://github.com/gildas-lormeau/single-file-core#readme",
31
31
  "devDependencies": {
32
- "@eslint/js": "^9.39.5",
32
+ "@eslint/js": "^10.0.1",
33
33
  "eslint": "^10.9.1",
34
34
  "happy-dom": "^20.14.5"
35
35
  }
@@ -70,7 +70,8 @@ const FRAME_OPTION_NAMES = [
70
70
  "loadDeferredContentMinZoomFactor",
71
71
  "loadDeferredContentDispatchScrollEvent",
72
72
  "loadDeferredContentBlockCookies",
73
- "loadDeferredContentBlockStorage"
73
+ "loadDeferredContentBlockStorage",
74
+ "loadDeferredContentKeepEmulatedScreenSize"
74
75
  ];
75
76
  const TARGET_ORIGIN = "*";
76
77
  const TIMEOUT_INIT_REQUEST_MESSAGE = 2000;
@@ -109,7 +109,7 @@
109
109
  document.addEventListener(LOAD_DEFERRED_CONTENT_KEEP_ZOOM_LEVEL_START_EVENT, onLoadDeferredContentKeepZoomLevelStart);
110
110
  document.addEventListener(LOAD_DEFERRED_CONTENT_END_EVENT, onLoadDeferredContentEnd);
111
111
  document.addEventListener(LOAD_DEFERRED_CONTENT_KEEP_ZOOM_LEVEL_END_EVENT, onLoadDeferredContentKeepZoomLevelEnd);
112
- document.addEventListener(LOAD_DEFERRED_CONTENT_RESET_EVENT, resetScreenSize);
112
+ document.addEventListener(LOAD_DEFERRED_CONTENT_RESET_EVENT, onLoadDeferredContentReset);
113
113
  document.addEventListener(LOAD_DEFERRED_CONTENT_RESET_ZOOM_LEVEL_EVENT, onLoadDeferredContentResetZoomLevel);
114
114
  document.addEventListener(DISPATCH_SCROLL_START_EVENT, onDispatchScrollStart);
115
115
  document.addEventListener(DISPATCH_SCROLL_END_EVENT, onDispatchScrollEnd);
@@ -125,11 +125,11 @@
125
125
  }
126
126
 
127
127
  function onLoadDeferredContentStart(event) {
128
- loadDeferredContentStart(false, getMinZoomFactor(event));
128
+ loadDeferredContentStart(false, getMinZoomFactor(event), getKeepEmulatedScreenSize(event));
129
129
  }
130
130
 
131
131
  function onLoadDeferredContentKeepZoomLevelStart(event) {
132
- loadDeferredContentStart(true, getMinZoomFactor(event));
132
+ loadDeferredContentStart(true, getMinZoomFactor(event), getKeepEmulatedScreenSize(event));
133
133
  }
134
134
 
135
135
  function getMinZoomFactor(event) {
@@ -142,12 +142,37 @@
142
142
  }
143
143
  }
144
144
 
145
- function onLoadDeferredContentEnd() {
146
- loadDeferredContentEnd();
145
+ function getKeepEmulatedScreenSize(event) {
146
+ try {
147
+ const { keepEmulatedScreenSize } = JSON.parse(event.detail);
148
+ return Boolean(keepEmulatedScreenSize);
149
+ // eslint-disable-next-line no-unused-vars
150
+ } catch (error) {
151
+ return false;
152
+ }
153
+ }
154
+
155
+ function onLoadDeferredContentEnd(event) {
156
+ loadDeferredContentEnd(false, getKeepEmulatedScreenSize(event));
157
+ }
158
+
159
+ function onLoadDeferredContentKeepZoomLevelEnd(event) {
160
+ loadDeferredContentEnd(true, getKeepEmulatedScreenSize(event));
147
161
  }
148
162
 
149
- function onLoadDeferredContentKeepZoomLevelEnd() {
150
- loadDeferredContentEnd(true);
163
+ function onLoadDeferredContentReset(event) {
164
+ if (getKeepEmulatedScreenSize(event)) {
165
+ const minHeight = document.documentElement.style.getPropertyValue("-sf-min-height");
166
+ const minHeightPriority = document.documentElement.style.getPropertyPriority("-sf-min-height");
167
+ document.documentElement.style.setProperty("min-height", minHeight, minHeightPriority);
168
+ document.documentElement.style.removeProperty("-sf-transform");
169
+ document.documentElement.style.removeProperty("-sf-transform-origin");
170
+ document.documentElement.style.removeProperty("-sf-min-height");
171
+ resetScreenSize();
172
+ dispatchResizeEvent();
173
+ } else {
174
+ resetScreenSize();
175
+ }
151
176
  }
152
177
 
153
178
  function onLoadDeferredContentResetZoomLevel() {
@@ -238,7 +263,7 @@
238
263
  }
239
264
  }
240
265
 
241
- function loadDeferredContentStart(keepZoomLevel, minZoomFactor) {
266
+ function loadDeferredContentStart(keepZoomLevel, minZoomFactor, keepEmulatedScreenSize) {
242
267
  const scrollingElement = document.scrollingElement || document.documentElement;
243
268
  const clientHeight = scrollingElement.clientHeight;
244
269
  const clientWidth = scrollingElement.clientWidth;
@@ -327,14 +352,17 @@
327
352
  document.documentElement.style.setProperty("transform", translation + "scale3d(" + zoomFactor + ", " + zoomFactor + ", 1)", "important");
328
353
  document.documentElement.style.setProperty("min-height", (100 / zoomFactor) + "vh", "important");
329
354
  dispatchResizeEvent();
330
- if (keepZoomLevel) {
355
+ if (keepZoomLevel || keepEmulatedScreenSize) {
331
356
  document.documentElement.style.setProperty("-sf-transform", transform, transformPriority);
332
357
  document.documentElement.style.setProperty("-sf-transform-origin", transformOrigin, transformOriginPriority);
333
358
  document.documentElement.style.setProperty("-sf-min-height", minHeight, minHeightPriority);
334
- } else {
359
+ }
360
+ if (!keepZoomLevel) {
335
361
  document.documentElement.style.setProperty("transform", transform, transformPriority);
336
362
  document.documentElement.style.setProperty("transform-origin", transformOrigin, transformOriginPriority);
337
- document.documentElement.style.setProperty("min-height", minHeight, minHeightPriority);
363
+ if (!keepEmulatedScreenSize) {
364
+ document.documentElement.style.setProperty("min-height", minHeight, minHeightPriority);
365
+ }
338
366
  }
339
367
  }
340
368
  if (!keepZoomLevel) {
@@ -363,7 +391,7 @@
363
391
  }
364
392
  }
365
393
 
366
- function loadDeferredContentEnd(keepZoomLevel) {
394
+ function loadDeferredContentEnd(keepZoomLevel, keepEmulatedScreenSize) {
367
395
  document.querySelectorAll("[" + LAZY_LOAD_ATTRIBUTE + "]").forEach(element => {
368
396
  element.loading = "lazy";
369
397
  element.removeAttribute(LAZY_LOAD_ATTRIBUTE);
@@ -380,7 +408,9 @@
380
408
  delete globalThis._singleFileImage;
381
409
  }
382
410
  if (!keepZoomLevel) {
383
- resetScreenSize();
411
+ if (!keepEmulatedScreenSize) {
412
+ resetScreenSize();
413
+ }
384
414
  dispatchResizeEvent();
385
415
  }
386
416
  }
@@ -123,7 +123,7 @@ function loadDeferredContentStart(options) {
123
123
  if (options.loadDeferredContentDispatchScrollEvent) {
124
124
  document.dispatchEvent(new CustomEvent(DISPATCH_SCROLL_START_EVENT));
125
125
  }
126
- const detail = JSON.stringify({ minZoomFactor: options.loadDeferredContentMinZoomFactor });
126
+ const detail = JSON.stringify({ minZoomFactor: options.loadDeferredContentMinZoomFactor, keepEmulatedScreenSize: Boolean(options.loadDeferredContentKeepEmulatedScreenSize) });
127
127
  if (options.loadDeferredContentKeepZoomLevel) {
128
128
  document.dispatchEvent(new CustomEvent(LOAD_DEFERRED_CONTENT_KEEP_ZOOM_LEVEL_START_EVENT, { detail }));
129
129
  } else {
@@ -141,17 +141,23 @@ function loadDeferredContentEnd(options) {
141
141
  if (options.loadDeferredContentDispatchScrollEvent) {
142
142
  document.dispatchEvent(new CustomEvent(DISPATCH_SCROLL_END_EVENT));
143
143
  }
144
+ const detail = getScreenSizeDetail(options);
144
145
  if (options.loadDeferredContentKeepZoomLevel) {
145
- document.dispatchEvent(new CustomEvent(LOAD_DEFERRED_CONTENT_KEEP_ZOOM_LEVEL_END_EVENT));
146
+ document.dispatchEvent(new CustomEvent(LOAD_DEFERRED_CONTENT_KEEP_ZOOM_LEVEL_END_EVENT, { detail }));
146
147
  } else {
147
- document.dispatchEvent(new CustomEvent(LOAD_DEFERRED_CONTENT_END_EVENT));
148
+ document.dispatchEvent(new CustomEvent(LOAD_DEFERRED_CONTENT_END_EVENT, { detail }));
148
149
  }
149
150
  }
150
151
 
151
152
  function loadDeferredContentResetZoomLevel(options) {
153
+ const detail = getScreenSizeDetail(options);
152
154
  if (options.loadDeferredContentKeepZoomLevel) {
153
- document.dispatchEvent(new CustomEvent(LOAD_DEFERRED_CONTENT_RESET_ZOOM_LEVEL_EVENT));
155
+ document.dispatchEvent(new CustomEvent(LOAD_DEFERRED_CONTENT_RESET_ZOOM_LEVEL_EVENT, { detail }));
154
156
  } else {
155
- document.dispatchEvent(new CustomEvent(LOAD_DEFERRED_CONTENT_RESET_EVENT));
157
+ document.dispatchEvent(new CustomEvent(LOAD_DEFERRED_CONTENT_RESET_EVENT, { detail }));
156
158
  }
159
+ }
160
+
161
+ function getScreenSizeDetail(options) {
162
+ return JSON.stringify({ keepEmulatedScreenSize: Boolean(options.loadDeferredContentKeepEmulatedScreenSize) });
157
163
  }