@deot/vc 1.0.50 → 1.0.52

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.
@@ -203,7 +203,7 @@
203
203
  return target;
204
204
  };
205
205
 
206
- const getStyle$1 = (el, name) => {
206
+ const getStyle$2 = (el, name) => {
207
207
  if (IS_SERVER$2 || !name) return "";
208
208
  if (name === "float") {
209
209
  name = "cssFloat";
@@ -219,8 +219,8 @@
219
219
  const isScroller = (el, options) => {
220
220
  if (IS_SERVER$2 || !el) return false;
221
221
  const { className, direction } = options || {};
222
- let overflow = getStyle$1(el, `overflow-${direction ? "y" : "x"}`);
223
- overflow = overflow || getStyle$1(el, "overflow");
222
+ let overflow = getStyle$2(el, `overflow-${direction ? "y" : "x"}`);
223
+ overflow = overflow || getStyle$2(el, "overflow");
224
224
  return !!(overflow.match(/(scroll|auto)/) || className?.test(el.className));
225
225
  };
226
226
 
@@ -6615,7 +6615,7 @@
6615
6615
  * @returns {boolean}
6616
6616
  */
6617
6617
 
6618
- function isSafari$1() {
6618
+ function isSafari$2() {
6619
6619
  return !!(navigator.vendor && navigator.vendor.match(/apple/i));
6620
6620
  }
6621
6621
 
@@ -7493,7 +7493,7 @@
7493
7493
  // that's because I want to show image before it's fully loaded,
7494
7494
  // as browser can render parts of image while it is loading.
7495
7495
  // We do not do this in Safari due to partial loading bug.
7496
- if (supportsDecode && this.slide && (!this.slide.isActive || isSafari$1())) {
7496
+ if (supportsDecode && this.slide && (!this.slide.isActive || isSafari$2())) {
7497
7497
  this.isDecoding = true; // purposefully using finally instead of then,
7498
7498
  // as if srcset sizes changes dynamically - it may cause decode error
7499
7499
 
@@ -7524,7 +7524,7 @@
7524
7524
  return;
7525
7525
  }
7526
7526
 
7527
- if (this.isImageContent() && this.isDecoding && !isSafari$1()) {
7527
+ if (this.isImageContent() && this.isDecoding && !isSafari$2()) {
7528
7528
  // add image to slide when it becomes active,
7529
7529
  // even if it's not finished decoding
7530
7530
  this.appendImage();
@@ -11305,7 +11305,7 @@
11305
11305
  ...listeners
11306
11306
  }), {
11307
11307
  prepend: slots.prepend && (() => slots.prepend?.()),
11308
- append: props2.step ? slots.append ? () => slots.append?.() : () => {
11308
+ append: slots.append ? () => slots.append?.() : props2.step ? () => {
11309
11309
  return vue.createVNode("div", {
11310
11310
  "class": "vc-input-number__icon"
11311
11311
  }, [vue.createVNode("div", {
@@ -20542,23 +20542,103 @@
20542
20542
  tag: {
20543
20543
  type: String,
20544
20544
  default: "div"
20545
+ },
20546
+ // useCORS
20547
+ crossOrigin: {
20548
+ type: String,
20549
+ // ''. 'anonymous', 'use-credentials'
20550
+ default: "anonymous",
20551
+ validator: (v) => /^(|anonymous|use-credentials)$/.test(v)
20552
+ },
20553
+ transformSource: Function,
20554
+ // 传递给snap-dom的配置项
20555
+ options: {
20556
+ type: Object,
20557
+ default: () => ({})
20545
20558
  }
20546
20559
  };
20547
- const COMPONENT_NAME$Z = "vc-html-to-image";
20548
- const HTMLToImage = /* @__PURE__ */ vue.defineComponent({
20560
+ const COMPONENT_NAME$Z = "vc-snapshot";
20561
+ const Snapshot = /* @__PURE__ */ vue.defineComponent({
20549
20562
  name: COMPONENT_NAME$Z,
20550
20563
  props: props$H,
20564
+ emits: ["ready"],
20551
20565
  setup(props2, {
20552
- slots
20566
+ emit,
20567
+ slots,
20568
+ expose
20553
20569
  }) {
20570
+ const current = vue.ref();
20571
+ const instance = vue.ref();
20572
+ const refresh = async () => {
20573
+ if (!props2.crossOrigin) return;
20574
+ const transformSource = props2.transformSource || VcInstance.options.Snapshot?.transformSource || ((v) => v);
20575
+ return Promise.all(Array.from(current.value.querySelectorAll("img")).map((node) => {
20576
+ return new Promise((resolve) => {
20577
+ (async () => {
20578
+ let url;
20579
+ try {
20580
+ url = await transformSource(node.src);
20581
+ } catch (e) {
20582
+ console.error(e);
20583
+ }
20584
+ const image = new Image();
20585
+ image.crossOrigin = props2.crossOrigin;
20586
+ image.src = `${url}?=${(/* @__PURE__ */ new Date()).getTime()}`;
20587
+ image.onload = () => {
20588
+ node.src = image.src;
20589
+ resolve(1);
20590
+ };
20591
+ image.onerror = () => resolve(0);
20592
+ })();
20593
+ });
20594
+ }));
20595
+ };
20596
+ const toDataURL = async () => {
20597
+ await refresh();
20598
+ return instance.value.toRaw();
20599
+ };
20600
+ const download = async (options) => {
20601
+ await refresh();
20602
+ const _download = VcInstance.options.Snapshot?.download || (() => false);
20603
+ const allow = _download(options);
20604
+ if (allow && allow.then) {
20605
+ allow.catch(() => {
20606
+ instance.value.download(options);
20607
+ });
20608
+ return;
20609
+ }
20610
+ allow || instance.value.download(options);
20611
+ };
20612
+ expose({
20613
+ instance,
20614
+ refresh,
20615
+ toDataURL,
20616
+ download
20617
+ });
20618
+ vue.onMounted(async () => {
20619
+ try {
20620
+ let snapDOM = window.snapdom || await Promise.resolve().then(() => snapdom$1);
20621
+ snapDOM = snapDOM.snapdom || snapDOM;
20622
+ instance.value = await snapDOM(current.value, props2.options);
20623
+ emit("ready", {
20624
+ instance: instance.value,
20625
+ dependencies: {
20626
+ snapDOM
20627
+ }
20628
+ });
20629
+ } catch (e) {
20630
+ throw new VcError("snapshot", e);
20631
+ }
20632
+ });
20554
20633
  return () => {
20555
20634
  return vue.createVNode("div", {
20556
- "class": "vc-html-to-image"
20635
+ "ref": current,
20636
+ "class": "vc-snapshot"
20557
20637
  }, [slots?.default?.()]);
20558
20638
  };
20559
20639
  }
20560
20640
  });
20561
- const MHTMLToImage = HTMLToImage;
20641
+ const MSnapshot = Snapshot;
20562
20642
  const MIcon = Icon;
20563
20643
  const props$G = {
20564
20644
  src: String,
@@ -23632,6 +23712,7 @@
23632
23712
  checked,
23633
23713
  classes,
23634
23714
  computedLabel,
23715
+ isDisabled,
23635
23716
  handleChange,
23636
23717
  handleFocus,
23637
23718
  handleBlur
@@ -23651,7 +23732,7 @@
23651
23732
  }, null)]), vue.createVNode("input", {
23652
23733
  "checked": checked.value,
23653
23734
  "name": radioName.value,
23654
- "disabled": props2.disabled,
23735
+ "disabled": isDisabled.value,
23655
23736
  "type": "radio",
23656
23737
  "onChange": handleChange,
23657
23738
  "onFocus": handleFocus,
@@ -23663,7 +23744,11 @@
23663
23744
  const COMPONENT_NAME$x = "vc-radio-button";
23664
23745
  const RadioButton = /* @__PURE__ */ vue.defineComponent({
23665
23746
  name: COMPONENT_NAME$x,
23666
- props: props$m,
23747
+ props: {
23748
+ ...props$m,
23749
+ labelStyle: [String, Object],
23750
+ labelClass: [String, Object]
23751
+ },
23667
23752
  emits: ["update:modelValue", "change"],
23668
23753
  setup(props2, {
23669
23754
  slots
@@ -23674,6 +23759,7 @@
23674
23759
  checked,
23675
23760
  classes,
23676
23761
  computedLabel,
23762
+ isDisabled,
23677
23763
  handleChange,
23678
23764
  handleFocus,
23679
23765
  handleBlur
@@ -23685,12 +23771,15 @@
23685
23771
  }, [vue.createVNode("input", {
23686
23772
  "checked": checked.value,
23687
23773
  "name": radioName.value,
23688
- "disabled": props2.disabled,
23774
+ "disabled": isDisabled.value,
23689
23775
  "type": "radio",
23690
23776
  "onChange": handleChange,
23691
23777
  "onFocus": handleFocus,
23692
23778
  "onBlur": handleBlur
23693
- }, null), slots.default ? slots.default() : computedLabel.value && vue.createVNode("span", null, [computedLabel.value])]);
23779
+ }, null), vue.createVNode("span", {
23780
+ "class": [props2.labelClass, "vc-radio-button__label"],
23781
+ "style": props2.labelStyle
23782
+ }, [slots.default ? slots.default() : computedLabel.value || ""])]);
23694
23783
  };
23695
23784
  }
23696
23785
  });
@@ -23796,6 +23885,7 @@
23796
23885
  checked,
23797
23886
  classes,
23798
23887
  computedLabel,
23888
+ isDisabled,
23799
23889
  handleChange,
23800
23890
  handleFocus,
23801
23891
  handleBlur
@@ -23815,7 +23905,7 @@
23815
23905
  }, null)]), vue.createVNode("input", {
23816
23906
  "checked": checked.value,
23817
23907
  "name": radioName.value,
23818
- "disabled": props2.disabled,
23908
+ "disabled": isDisabled.value,
23819
23909
  "type": "radio",
23820
23910
  "onChange": handleChange,
23821
23911
  "onFocus": handleFocus,
@@ -26235,7 +26325,7 @@
26235
26325
  let hiddenEl$1;
26236
26326
  const getFitIndex = (options = {}) => {
26237
26327
  const { el: el2, line, value, suffix, indent = 0 } = options;
26238
- let lineHeight = parseInt(getStyle$1(el2, "line-height"), 10);
26328
+ let lineHeight = parseInt(getStyle$2(el2, "line-height"), 10);
26239
26329
  if (!hiddenEl$1) {
26240
26330
  hiddenEl$1 = document.createElement("div");
26241
26331
  document.body.appendChild(hiddenEl$1);
@@ -26247,7 +26337,7 @@
26247
26337
  boxSizing,
26248
26338
  sizingStyle
26249
26339
  } = utils.getComputedStyle(el2, SIZING_STYLE$1);
26250
- const textIndent = `text-indent: ${parseInt(getStyle$1(el2, "text-indent"), 10) + indent}px;`;
26340
+ const textIndent = `text-indent: ${parseInt(getStyle$2(el2, "text-indent"), 10) + indent}px;`;
26251
26341
  hiddenEl$1.setAttribute("style", `${sizingStyle};${textIndent};${HIDDEN_TEXT_STYLE}`);
26252
26342
  let sideHeight = paddingSize || 0;
26253
26343
  boxSizing === "border-box" && (sideHeight += borderSize);
@@ -31829,8 +31919,8 @@
31829
31919
  MFormItem,
31830
31920
  Fragment,
31831
31921
  MFragment,
31832
- HTMLToImage,
31833
- MHTMLToImage,
31922
+ Snapshot,
31923
+ MSnapshot,
31834
31924
  Icon,
31835
31925
  MIcon,
31836
31926
  Image: Image$1$1,
@@ -55025,10 +55115,10 @@
55025
55115
  return styleChanged;
55026
55116
  }
55027
55117
  function bindPathAndTextCommonStyle(ctx, el, prevEl, forceSetAll, scope) {
55028
- var style = getStyle(el, scope.inHover);
55118
+ var style = getStyle$1(el, scope.inHover);
55029
55119
  var prevStyle = forceSetAll
55030
55120
  ? null
55031
- : (prevEl && getStyle(prevEl, scope.inHover) || {});
55121
+ : (prevEl && getStyle$1(prevEl, scope.inHover) || {});
55032
55122
  if (style === prevStyle) {
55033
55123
  return false;
55034
55124
  }
@@ -55079,7 +55169,7 @@
55079
55169
  return styleChanged;
55080
55170
  }
55081
55171
  function bindImageStyle(ctx, el, prevEl, forceSetAll, scope) {
55082
- return bindCommonProps(ctx, getStyle(el, scope.inHover), prevEl && getStyle(prevEl, scope.inHover), forceSetAll, scope);
55172
+ return bindCommonProps(ctx, getStyle$1(el, scope.inHover), prevEl && getStyle$1(prevEl, scope.inHover), forceSetAll, scope);
55083
55173
  }
55084
55174
  function setContextTransform(ctx, el) {
55085
55175
  var m = el.transform;
@@ -55138,7 +55228,7 @@
55138
55228
  scope.batchFill = '';
55139
55229
  scope.batchStroke = '';
55140
55230
  }
55141
- function getStyle(el, inHover) {
55231
+ function getStyle$1(el, inHover) {
55142
55232
  return inHover ? (el.__hoverStyle || el.style) : el.style;
55143
55233
  }
55144
55234
  function brushSingle(ctx, el) {
@@ -55192,7 +55282,7 @@
55192
55282
  else if (!canBatchPath) {
55193
55283
  flushPathDrawn(ctx, scope);
55194
55284
  }
55195
- var style = getStyle(el, scope.inHover);
55285
+ var style = getStyle$1(el, scope.inHover);
55196
55286
  if (el instanceof Path) {
55197
55287
  if (scope.lastDrawType !== DRAW_TYPE_PATH) {
55198
55288
  forceSetStyle = true;
@@ -72579,7 +72669,7 @@
72579
72669
  if (!coordSys.axisPointerEnabled) {
72580
72670
  return;
72581
72671
  }
72582
- var coordSysKey = makeKey(coordSys.model);
72672
+ var coordSysKey = makeKey$1(coordSys.model);
72583
72673
  var axesInfoInCoordSys = result.coordSysAxesInfo[coordSysKey] = {};
72584
72674
  result.coordSysMap[coordSysKey] = coordSys;
72585
72675
  // Set tooltip (like 'cross') is a convenient way to show axisPointer
@@ -72619,7 +72709,7 @@
72619
72709
  axisPointerModel = fromTooltip ? makeAxisPointerModel(axis, baseTooltipModel, globalAxisPointerModel, ecModel, fromTooltip, triggerTooltip) : axisPointerModel;
72620
72710
  var snap = axisPointerModel.get('snap');
72621
72711
  var triggerEmphasis = axisPointerModel.get('triggerEmphasis');
72622
- var axisKey = makeKey(axis.model);
72712
+ var axisKey = makeKey$1(axis.model);
72623
72713
  var involveSeries = triggerTooltip || snap || axis.type === 'category';
72624
72714
  // If result.axesInfo[key] exist, override it (tooltip has higher priority).
72625
72715
  var axisInfo = result.axesInfo[axisKey] = {
@@ -72691,7 +72781,7 @@
72691
72781
  if (!coordSys || seriesTooltipTrigger === 'none' || seriesTooltipTrigger === false || seriesTooltipTrigger === 'item' || seriesTooltipShow === false || seriesModel.get(['axisPointer', 'show'], true) === false) {
72692
72782
  return;
72693
72783
  }
72694
- each$f(result.coordSysAxesInfo[makeKey(coordSys.model)], function (axisInfo) {
72784
+ each$f(result.coordSysAxesInfo[makeKey$1(coordSys.model)], function (axisInfo) {
72695
72785
  var axis = axisInfo.axis;
72696
72786
  if (coordSys.getAxis(axis.dim) === axis) {
72697
72787
  axisInfo.seriesModels.push(seriesModel);
@@ -72769,7 +72859,7 @@
72769
72859
  }
72770
72860
  function getAxisInfo$1(axisModel) {
72771
72861
  var coordSysAxesInfo = (axisModel.ecModel.getComponent('axisPointer') || {}).coordSysAxesInfo;
72772
- return coordSysAxesInfo && coordSysAxesInfo.axesInfo[makeKey(axisModel)];
72862
+ return coordSysAxesInfo && coordSysAxesInfo.axesInfo[makeKey$1(axisModel)];
72773
72863
  }
72774
72864
  function getAxisPointerModel(axisModel) {
72775
72865
  var axisInfo = getAxisInfo$1(axisModel);
@@ -72782,7 +72872,7 @@
72782
72872
  * @param {module:echarts/model/Model} model
72783
72873
  * @return {string} unique key
72784
72874
  */
72785
- function makeKey(model) {
72875
+ function makeKey$1(model) {
72786
72876
  return model.type + '||' + model.id;
72787
72877
  }
72788
72878
 
@@ -95075,7 +95165,7 @@
95075
95165
  return;
95076
95166
  }
95077
95167
  var coordSysModel = axisInfo.coordSys.model;
95078
- var coordSysKey = makeKey(coordSysModel);
95168
+ var coordSysKey = makeKey$1(coordSysModel);
95079
95169
  var coordSysItem = dataByCoordSys.map[coordSysKey];
95080
95170
  if (!coordSysItem) {
95081
95171
  coordSysItem = dataByCoordSys.map[coordSysKey] = {
@@ -112304,7 +112394,7 @@
112304
112394
  * @returns {boolean}
112305
112395
  */
112306
112396
 
112307
- function isSafari() {
112397
+ function isSafari$1() {
112308
112398
  return !!(navigator.vendor && navigator.vendor.match(/apple/i));
112309
112399
  }
112310
112400
 
@@ -117339,7 +117429,7 @@
117339
117429
  // that's because I want to show image before it's fully loaded,
117340
117430
  // as browser can render parts of image while it is loading.
117341
117431
  // We do not do this in Safari due to partial loading bug.
117342
- if (supportsDecode && this.slide && (!this.slide.isActive || isSafari())) {
117432
+ if (supportsDecode && this.slide && (!this.slide.isActive || isSafari$1())) {
117343
117433
  this.isDecoding = true; // purposefully using finally instead of then,
117344
117434
  // as if srcset sizes changes dynamically - it may cause decode error
117345
117435
 
@@ -117370,7 +117460,7 @@
117370
117460
  return;
117371
117461
  }
117372
117462
 
117373
- if (this.isImageContent() && this.isDecoding && !isSafari()) {
117463
+ if (this.isImageContent() && this.isDecoding && !isSafari$1()) {
117374
117464
  // add image to slide when it becomes active,
117375
117465
  // even if it's not finished decoding
117376
117466
  this.appendImage();
@@ -132197,6 +132287,4137 @@
132197
132287
  default: Quill
132198
132288
  }, Symbol.toStringTag, { value: 'Module' }));
132199
132289
 
132290
+ /*
132291
+ * snapdom
132292
+ * v.1.9.14
132293
+ * Author Juan Martin Muda
132294
+ * License MIT
132295
+ **/
132296
+
132297
+
132298
+ // src/core/cache.js
132299
+ var cache = {
132300
+ image: /* @__PURE__ */ new Map(),
132301
+ background: /* @__PURE__ */ new Map(),
132302
+ resource: /* @__PURE__ */ new Map(),
132303
+ defaultStyle: /* @__PURE__ */ new Map(),
132304
+ baseStyle: /* @__PURE__ */ new Map(),
132305
+ computedStyle: /* @__PURE__ */ new WeakMap(),
132306
+ font: /* @__PURE__ */ new Set(),
132307
+ session: {
132308
+ styleMap: /* @__PURE__ */ new Map(),
132309
+ styleCache: /* @__PURE__ */ new WeakMap(),
132310
+ nodeMap: /* @__PURE__ */ new Map()
132311
+ }
132312
+ };
132313
+ function applyCachePolicy(policy = "soft") {
132314
+ switch (policy) {
132315
+ case "auto": {
132316
+ cache.session.styleMap = /* @__PURE__ */ new Map();
132317
+ cache.session.nodeMap = /* @__PURE__ */ new Map();
132318
+ return;
132319
+ }
132320
+ case "soft": {
132321
+ cache.session.styleMap = /* @__PURE__ */ new Map();
132322
+ cache.session.nodeMap = /* @__PURE__ */ new Map();
132323
+ cache.session.styleCache = /* @__PURE__ */ new WeakMap();
132324
+ return;
132325
+ }
132326
+ case "full": {
132327
+ return;
132328
+ }
132329
+ case "disabled": {
132330
+ cache.session.styleMap = /* @__PURE__ */ new Map();
132331
+ cache.session.nodeMap = /* @__PURE__ */ new Map();
132332
+ cache.session.styleCache = /* @__PURE__ */ new WeakMap();
132333
+ cache.computedStyle = /* @__PURE__ */ new WeakMap();
132334
+ cache.baseStyle = /* @__PURE__ */ new Map();
132335
+ cache.defaultStyle = /* @__PURE__ */ new Map();
132336
+ cache.image = /* @__PURE__ */ new Map();
132337
+ cache.background = /* @__PURE__ */ new Map();
132338
+ cache.resource = /* @__PURE__ */ new Map();
132339
+ cache.font = /* @__PURE__ */ new Set();
132340
+ return;
132341
+ }
132342
+ default: {
132343
+ cache.session.styleMap = /* @__PURE__ */ new Map();
132344
+ cache.session.nodeMap = /* @__PURE__ */ new Map();
132345
+ cache.session.styleCache = /* @__PURE__ */ new WeakMap();
132346
+ return;
132347
+ }
132348
+ }
132349
+ }
132350
+
132351
+ // src/utils/helpers.js
132352
+ function extractURL(value) {
132353
+ const match = value.match(/url\((['"]?)(.*?)(\1)\)/);
132354
+ if (!match) return null;
132355
+ const url = match[2].trim();
132356
+ if (url.startsWith("#")) return null;
132357
+ return url;
132358
+ }
132359
+ function stripTranslate(transform) {
132360
+ if (!transform || transform === "none") return "";
132361
+ let cleaned = transform.replace(/translate[XY]?\([^)]*\)/g, "");
132362
+ cleaned = cleaned.replace(/matrix\(([^)]+)\)/g, (_, values) => {
132363
+ const parts = values.split(",").map((s) => s.trim());
132364
+ if (parts.length !== 6) return `matrix(${values})`;
132365
+ parts[4] = "0";
132366
+ parts[5] = "0";
132367
+ return `matrix(${parts.join(", ")})`;
132368
+ });
132369
+ cleaned = cleaned.replace(/matrix3d\(([^)]+)\)/g, (_, values) => {
132370
+ const parts = values.split(",").map((s) => s.trim());
132371
+ if (parts.length !== 16) return `matrix3d(${values})`;
132372
+ parts[12] = "0";
132373
+ parts[13] = "0";
132374
+ return `matrix3d(${parts.join(", ")})`;
132375
+ });
132376
+ return cleaned.trim().replace(/\s{2,}/g, " ");
132377
+ }
132378
+ function safeEncodeURI(uri) {
132379
+ if (/%[0-9A-Fa-f]{2}/.test(uri)) return uri;
132380
+ try {
132381
+ return encodeURI(uri);
132382
+ } catch {
132383
+ return uri;
132384
+ }
132385
+ }
132386
+
132387
+ // src/modules/snapFetch.js
132388
+ function createSnapLogger(prefix = "[snapDOM]", { ttlMs = 5 * 6e4, maxEntries = 12 } = {}) {
132389
+ const seen = /* @__PURE__ */ new Map();
132390
+ let emitted = 0;
132391
+ function log(level, key, msg) {
132392
+ if (emitted >= maxEntries) return;
132393
+ const now = Date.now();
132394
+ const until = seen.get(key) || 0;
132395
+ if (until > now) return;
132396
+ seen.set(key, now + ttlMs);
132397
+ emitted++;
132398
+ if (level === "warn" && console && console.warn) console.warn(`${prefix} ${msg}`);
132399
+ else if (console && console.error) console.error(`${prefix} ${msg}`);
132400
+ }
132401
+ return {
132402
+ warnOnce(key, msg) {
132403
+ log("warn", key, msg);
132404
+ },
132405
+ errorOnce(key, msg) {
132406
+ log("error", key, msg);
132407
+ },
132408
+ reset() {
132409
+ seen.clear();
132410
+ emitted = 0;
132411
+ }
132412
+ };
132413
+ }
132414
+ var snapLogger = createSnapLogger("[snapDOM]", { ttlMs: 3 * 6e4, maxEntries: 10 });
132415
+ var _inflight = /* @__PURE__ */ new Map();
132416
+ var _errorCache = /* @__PURE__ */ new Map();
132417
+ function isSpecialURL(url) {
132418
+ return /^data:|^blob:|^about:blank$/i.test(url);
132419
+ }
132420
+ function isAlreadyProxied(url, useProxy) {
132421
+ try {
132422
+ const baseHref = typeof location !== "undefined" && location.href ? location.href : "http://localhost/";
132423
+ const proxyBaseRaw = useProxy.includes("{url}") ? useProxy.split("{url}")[0] : useProxy;
132424
+ const proxyBase = new URL(proxyBaseRaw || ".", baseHref);
132425
+ const u = new URL(url, baseHref);
132426
+ if (u.origin === proxyBase.origin) return true;
132427
+ const sp = u.searchParams;
132428
+ if (sp && (sp.has("url") || sp.has("target"))) return true;
132429
+ } catch {
132430
+ }
132431
+ return false;
132432
+ }
132433
+ function shouldProxy(url, useProxy) {
132434
+ if (!useProxy) return false;
132435
+ if (isSpecialURL(url)) return false;
132436
+ if (isAlreadyProxied(url, useProxy)) return false;
132437
+ try {
132438
+ const base = typeof location !== "undefined" && location.href ? location.href : "http://localhost/";
132439
+ const u = new URL(url, base);
132440
+ return typeof location !== "undefined" ? u.origin !== location.origin : true;
132441
+ } catch {
132442
+ return !!useProxy;
132443
+ }
132444
+ }
132445
+ function applyProxy(url, useProxy) {
132446
+ if (!useProxy) return url;
132447
+ if (useProxy.includes("{url}")) {
132448
+ return useProxy.replace("{urlRaw}", safeEncodeURI(url)).replace("{url}", encodeURIComponent(url));
132449
+ }
132450
+ if (/[?&]url=?$/.test(useProxy)) {
132451
+ return `${useProxy}${encodeURIComponent(url)}`;
132452
+ }
132453
+ if (useProxy.endsWith("?")) {
132454
+ return `${useProxy}url=${encodeURIComponent(url)}`;
132455
+ }
132456
+ if (useProxy.endsWith("/")) {
132457
+ return `${useProxy}${safeEncodeURI(url)}`;
132458
+ }
132459
+ const sep = useProxy.includes("?") ? "&" : "?";
132460
+ return `${useProxy}${sep}url=${encodeURIComponent(url)}`;
132461
+ }
132462
+ function blobToDataURL(blob) {
132463
+ return new Promise((res, rej) => {
132464
+ const fr = new FileReader();
132465
+ fr.onload = () => res(String(fr.result || ""));
132466
+ fr.onerror = () => rej(new Error("read_failed"));
132467
+ fr.readAsDataURL(blob);
132468
+ });
132469
+ }
132470
+ function makeKey(url, o) {
132471
+ return [
132472
+ o.as || "blob",
132473
+ o.timeout ?? 3e3,
132474
+ o.useProxy || "",
132475
+ o.errorTTL ?? 8e3,
132476
+ url
132477
+ ].join("|");
132478
+ }
132479
+ async function snapFetch(url, options = {}) {
132480
+ const as = options.as ?? "blob";
132481
+ const timeout = options.timeout ?? 3e3;
132482
+ const useProxy = options.useProxy || "";
132483
+ const errorTTL = options.errorTTL ?? 8e3;
132484
+ const headers = options.headers || {};
132485
+ const silent = !!options.silent;
132486
+ if (/^data:/i.test(url)) {
132487
+ try {
132488
+ if (as === "text") {
132489
+ return { ok: true, data: String(url), status: 200, url, fromCache: false };
132490
+ }
132491
+ if (as === "dataURL") {
132492
+ return {
132493
+ ok: true,
132494
+ data: String(url),
132495
+ status: 200,
132496
+ url,
132497
+ fromCache: false,
132498
+ mime: String(url).slice(5).split(";")[0] || ""
132499
+ };
132500
+ }
132501
+ const [, meta = "", data = ""] = String(url).match(/^data:([^,]*),(.*)$/) || [];
132502
+ const isBase64 = /;base64/i.test(meta);
132503
+ const bin = isBase64 ? atob(data) : decodeURIComponent(data);
132504
+ const bytes = new Uint8Array([...bin].map((c) => c.charCodeAt(0)));
132505
+ const b = new Blob([bytes], { type: (meta || "").split(";")[0] || "" });
132506
+ return { ok: true, data: b, status: 200, url, fromCache: false, mime: b.type || "" };
132507
+ } catch {
132508
+ return { ok: false, data: null, status: 0, url, fromCache: false, reason: "special_url_error" };
132509
+ }
132510
+ }
132511
+ if (/^blob:/i.test(url)) {
132512
+ try {
132513
+ const resp = await fetch(url);
132514
+ if (!resp.ok) {
132515
+ return { ok: false, data: null, status: resp.status, url, fromCache: false, reason: "http_error" };
132516
+ }
132517
+ const blob = await resp.blob();
132518
+ const mime = blob.type || resp.headers.get("content-type") || "";
132519
+ if (as === "dataURL") {
132520
+ const dataURL = await blobToDataURL(blob);
132521
+ return { ok: true, data: dataURL, status: resp.status, url, fromCache: false, mime };
132522
+ }
132523
+ if (as === "text") {
132524
+ const text = await blob.text();
132525
+ return { ok: true, data: text, status: resp.status, url, fromCache: false, mime };
132526
+ }
132527
+ return { ok: true, data: blob, status: resp.status, url, fromCache: false, mime };
132528
+ } catch {
132529
+ return { ok: false, data: null, status: 0, url, fromCache: false, reason: "network" };
132530
+ }
132531
+ }
132532
+ if (/^about:blank$/i.test(url)) {
132533
+ if (as === "dataURL") {
132534
+ return {
132535
+ ok: true,
132536
+ data: "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR4nGMAAQAABQABDQottAAAAABJRU5ErkJggg==",
132537
+ status: 200,
132538
+ url,
132539
+ fromCache: false,
132540
+ mime: "image/png"
132541
+ };
132542
+ }
132543
+ return { ok: true, data: as === "text" ? "" : new Blob([]), status: 200, url, fromCache: false };
132544
+ }
132545
+ const key = makeKey(url, { as, timeout, useProxy, errorTTL });
132546
+ const e = _errorCache.get(key);
132547
+ if (e && e.until > Date.now()) {
132548
+ return { ...e.result, fromCache: true };
132549
+ } else if (e) {
132550
+ _errorCache.delete(key);
132551
+ }
132552
+ const inflight = _inflight.get(key);
132553
+ if (inflight) return inflight;
132554
+ const finalURL = shouldProxy(url, useProxy) ? applyProxy(url, useProxy) : url;
132555
+ let cred = options.credentials;
132556
+ if (!cred) {
132557
+ try {
132558
+ const base = typeof location !== "undefined" && location.href ? location.href : "http://localhost/";
132559
+ const u = new URL(url, base);
132560
+ const sameOrigin = typeof location !== "undefined" && u.origin === location.origin;
132561
+ cred = sameOrigin ? "include" : "omit";
132562
+ } catch {
132563
+ cred = "omit";
132564
+ }
132565
+ }
132566
+ const ctrl = new AbortController();
132567
+ const timer = setTimeout(() => ctrl.abort("timeout"), timeout);
132568
+ const p = (async () => {
132569
+ try {
132570
+ const resp = await fetch(finalURL, { signal: ctrl.signal, credentials: cred, headers });
132571
+ if (!resp.ok) {
132572
+ const result = { ok: false, data: null, status: resp.status, url: finalURL, fromCache: false, reason: "http_error" };
132573
+ if (errorTTL > 0) _errorCache.set(key, { until: Date.now() + errorTTL, result });
132574
+ if (!silent) {
132575
+ const short = `${resp.status} ${resp.statusText || ""}`.trim();
132576
+ snapLogger.warnOnce(
132577
+ `http:${resp.status}:${as}:${new URL(url, location?.href ?? "http://localhost/").origin}`,
132578
+ `HTTP error ${short} while fetching ${as} ${url}`
132579
+ );
132580
+ }
132581
+ options.onError && options.onError(result);
132582
+ return result;
132583
+ }
132584
+ if (as === "text") {
132585
+ const text = await resp.text();
132586
+ return { ok: true, data: text, status: resp.status, url: finalURL, fromCache: false };
132587
+ }
132588
+ const blob = await resp.blob();
132589
+ const mime = blob.type || resp.headers.get("content-type") || "";
132590
+ if (as === "dataURL") {
132591
+ const dataURL = await blobToDataURL(blob);
132592
+ return { ok: true, data: dataURL, status: resp.status, url: finalURL, fromCache: false, mime };
132593
+ }
132594
+ return { ok: true, data: blob, status: resp.status, url: finalURL, fromCache: false, mime };
132595
+ } catch (err) {
132596
+ const reason = err && typeof err === "object" && "name" in err && err.name === "AbortError" ? String(err.message || "").includes("timeout") ? "timeout" : "abort" : "network";
132597
+ const result = { ok: false, data: null, status: 0, url: finalURL, fromCache: false, reason };
132598
+ if (!/^blob:/i.test(url) && errorTTL > 0) {
132599
+ _errorCache.set(key, { until: Date.now() + errorTTL, result });
132600
+ }
132601
+ if (!silent) {
132602
+ const k = `${reason}:${as}:${new URL(url, location?.href ?? "http://localhost/").origin}`;
132603
+ const tips = reason === "timeout" ? `Timeout after ${timeout}ms. Consider increasing timeout or using a proxy for ${url}` : reason === "abort" ? `Request aborted while fetching ${as} ${url}` : `Network/CORS issue while fetching ${as} ${url}. A proxy may be required`;
132604
+ snapLogger.errorOnce(k, tips);
132605
+ }
132606
+ options.onError && options.onError(result);
132607
+ return result;
132608
+ } finally {
132609
+ clearTimeout(timer);
132610
+ _inflight.delete(key);
132611
+ }
132612
+ })();
132613
+ _inflight.set(key, p);
132614
+ return p;
132615
+ }
132616
+
132617
+ // src/utils/image.js
132618
+ function createBackground(baseCanvas, backgroundColor) {
132619
+ if (!backgroundColor || !baseCanvas.width || !baseCanvas.height) {
132620
+ return baseCanvas;
132621
+ }
132622
+ const temp = document.createElement("canvas");
132623
+ temp.width = baseCanvas.width;
132624
+ temp.height = baseCanvas.height;
132625
+ const ctx = temp.getContext("2d");
132626
+ ctx.fillStyle = backgroundColor;
132627
+ ctx.fillRect(0, 0, temp.width, temp.height);
132628
+ ctx.drawImage(baseCanvas, 0, 0);
132629
+ return temp;
132630
+ }
132631
+ async function inlineSingleBackgroundEntry(entry, options = {}) {
132632
+ const isGradient = /^((repeating-)?(linear|radial|conic)-gradient)\(/i.test(entry);
132633
+ if (isGradient || entry.trim() === "none") {
132634
+ return entry;
132635
+ }
132636
+ const rawUrl = extractURL(entry);
132637
+ if (!rawUrl) {
132638
+ return entry;
132639
+ }
132640
+ const encodedUrl = safeEncodeURI(rawUrl);
132641
+ if (cache.background.has(encodedUrl)) {
132642
+ const dataUrl = cache.background.get(encodedUrl);
132643
+ return dataUrl ? `url("${dataUrl}")` : "none";
132644
+ }
132645
+ try {
132646
+ const dataUrl = await snapFetch(encodedUrl, { as: "dataURL", useProxy: options.useProxy });
132647
+ if (dataUrl.ok) {
132648
+ cache.background.set(encodedUrl, dataUrl.data);
132649
+ return `url("${dataUrl.data}")`;
132650
+ }
132651
+ cache.background.set(encodedUrl, null);
132652
+ return "none";
132653
+ } catch {
132654
+ cache.background.set(encodedUrl, null);
132655
+ return "none";
132656
+ }
132657
+ }
132658
+
132659
+ // src/utils/css.js
132660
+ var NO_CAPTURE_TAGS = /* @__PURE__ */ new Set([
132661
+ "meta",
132662
+ "script",
132663
+ "noscript",
132664
+ "title",
132665
+ "link",
132666
+ "template"
132667
+ ]);
132668
+ var NO_DEFAULTS_TAGS = /* @__PURE__ */ new Set([
132669
+ // non-painting / head stuff
132670
+ "meta",
132671
+ "link",
132672
+ "style",
132673
+ "title",
132674
+ "noscript",
132675
+ "script",
132676
+ "template",
132677
+ // SVG whole namespace (safe for LeaderLine/presentation attrs)
132678
+ "g",
132679
+ "defs",
132680
+ "use",
132681
+ "marker",
132682
+ "mask",
132683
+ "clipPath",
132684
+ "pattern",
132685
+ "path",
132686
+ "polygon",
132687
+ "polyline",
132688
+ "line",
132689
+ "circle",
132690
+ "ellipse",
132691
+ "rect",
132692
+ "filter",
132693
+ "lineargradient",
132694
+ "radialgradient",
132695
+ "stop"
132696
+ ]);
132697
+ var commonTags = [
132698
+ "div",
132699
+ "span",
132700
+ "p",
132701
+ "a",
132702
+ "img",
132703
+ "ul",
132704
+ "li",
132705
+ "button",
132706
+ "input",
132707
+ "select",
132708
+ "textarea",
132709
+ "label",
132710
+ "section",
132711
+ "article",
132712
+ "header",
132713
+ "footer",
132714
+ "nav",
132715
+ "main",
132716
+ "aside",
132717
+ "h1",
132718
+ "h2",
132719
+ "h3",
132720
+ "h4",
132721
+ "h5",
132722
+ "h6",
132723
+ "table",
132724
+ "thead",
132725
+ "tbody",
132726
+ "tr",
132727
+ "td",
132728
+ "th"
132729
+ ];
132730
+ function precacheCommonTags() {
132731
+ for (let tag of commonTags) {
132732
+ const t = String(tag).toLowerCase();
132733
+ if (NO_CAPTURE_TAGS.has(t)) continue;
132734
+ if (NO_DEFAULTS_TAGS.has(t)) continue;
132735
+ getDefaultStyleForTag(t);
132736
+ }
132737
+ }
132738
+ function getDefaultStyleForTag(tagName) {
132739
+ tagName = String(tagName).toLowerCase();
132740
+ if (NO_DEFAULTS_TAGS.has(tagName)) {
132741
+ const empty = {};
132742
+ cache.defaultStyle.set(tagName, empty);
132743
+ return empty;
132744
+ }
132745
+ if (cache.defaultStyle.has(tagName)) {
132746
+ return cache.defaultStyle.get(tagName);
132747
+ }
132748
+ let sandbox = document.getElementById("snapdom-sandbox");
132749
+ if (!sandbox) {
132750
+ sandbox = document.createElement("div");
132751
+ sandbox.id = "snapdom-sandbox";
132752
+ sandbox.setAttribute("data-snapdom-sandbox", "true");
132753
+ sandbox.setAttribute("aria-hidden", "true");
132754
+ sandbox.style.position = "absolute";
132755
+ sandbox.style.left = "-9999px";
132756
+ sandbox.style.top = "-9999px";
132757
+ sandbox.style.width = "0px";
132758
+ sandbox.style.height = "0px";
132759
+ sandbox.style.overflow = "hidden";
132760
+ document.body.appendChild(sandbox);
132761
+ }
132762
+ const el = document.createElement(tagName);
132763
+ el.style.all = "initial";
132764
+ sandbox.appendChild(el);
132765
+ const styles = getComputedStyle(el);
132766
+ const defaults = {};
132767
+ for (let prop of styles) {
132768
+ if (shouldIgnoreProp(prop)) continue;
132769
+ const value = styles.getPropertyValue(prop);
132770
+ defaults[prop] = value;
132771
+ }
132772
+ sandbox.removeChild(el);
132773
+ cache.defaultStyle.set(tagName, defaults);
132774
+ return defaults;
132775
+ }
132776
+ var NO_PAINT_TOKEN = /(?:^|-)(animation|transition)(?:-|$)/i;
132777
+ var NO_PAINT_PREFIX = /^(--|view-timeline|scroll-timeline|animation-trigger|offset-|position-try|app-region|interactivity|overlay|view-transition|-webkit-locale|-webkit-user-(?:drag|modify)|-webkit-tap-highlight-color|-webkit-text-security)$/i;
132778
+ var NO_PAINT_EXACT = /* @__PURE__ */ new Set([
132779
+ // Interaction hints
132780
+ "cursor",
132781
+ "pointer-events",
132782
+ "touch-action",
132783
+ "user-select",
132784
+ // Printing/speech/reading-mode hints
132785
+ "print-color-adjust",
132786
+ "speak",
132787
+ "reading-flow",
132788
+ "reading-order",
132789
+ // Anchoring/container/timeline scopes (metadata for layout queries)
132790
+ "anchor-name",
132791
+ "anchor-scope",
132792
+ "container-name",
132793
+ "container-type",
132794
+ "timeline-scope"
132795
+ ]);
132796
+ function shouldIgnoreProp(prop) {
132797
+ const p = String(prop).toLowerCase();
132798
+ if (NO_PAINT_EXACT.has(p)) return true;
132799
+ if (NO_PAINT_PREFIX.test(p)) return true;
132800
+ if (NO_PAINT_TOKEN.test(p)) return true;
132801
+ return false;
132802
+ }
132803
+ function getStyleKey(snapshot, tagName) {
132804
+ tagName = String(tagName || "").toLowerCase();
132805
+ if (NO_DEFAULTS_TAGS.has(tagName)) {
132806
+ return "";
132807
+ }
132808
+ const entries = [];
132809
+ const defaults = getDefaultStyleForTag(tagName);
132810
+ for (let [prop, value] of Object.entries(snapshot)) {
132811
+ if (shouldIgnoreProp(prop)) continue;
132812
+ const def = defaults[prop];
132813
+ if (value && value !== def) entries.push(`${prop}:${value}`);
132814
+ }
132815
+ entries.sort();
132816
+ return entries.join(";");
132817
+ }
132818
+ function collectUsedTagNames(root) {
132819
+ const tagSet = /* @__PURE__ */ new Set();
132820
+ if (root.nodeType !== Node.ELEMENT_NODE && root.nodeType !== Node.DOCUMENT_FRAGMENT_NODE) {
132821
+ return [];
132822
+ }
132823
+ if (root.tagName) {
132824
+ tagSet.add(root.tagName.toLowerCase());
132825
+ }
132826
+ if (typeof root.querySelectorAll === "function") {
132827
+ root.querySelectorAll("*").forEach((el) => tagSet.add(el.tagName.toLowerCase()));
132828
+ }
132829
+ return Array.from(tagSet);
132830
+ }
132831
+ function generateDedupedBaseCSS(usedTagNames) {
132832
+ const groups = /* @__PURE__ */ new Map();
132833
+ for (let tagName of usedTagNames) {
132834
+ const styles = cache.defaultStyle.get(tagName);
132835
+ if (!styles) continue;
132836
+ const key = Object.entries(styles).map(([k, v]) => `${k}:${v};`).sort().join("");
132837
+ if (!key) continue;
132838
+ if (!groups.has(key)) {
132839
+ groups.set(key, []);
132840
+ }
132841
+ groups.get(key).push(tagName);
132842
+ }
132843
+ let css = "";
132844
+ for (let [styleBlock, tagList] of groups.entries()) {
132845
+ css += `${tagList.join(",")} { ${styleBlock} }
132846
+ `;
132847
+ }
132848
+ return css;
132849
+ }
132850
+ function generateCSSClasses(styleMap) {
132851
+ const keys = Array.from(new Set(styleMap.values())).filter(Boolean).sort();
132852
+ const classMap = /* @__PURE__ */ new Map();
132853
+ let i = 1;
132854
+ for (const k of keys) classMap.set(k, `c${i++}`);
132855
+ return classMap;
132856
+ }
132857
+ function getStyle(el, pseudo = null) {
132858
+ if (!(el instanceof Element)) {
132859
+ return window.getComputedStyle(el, pseudo);
132860
+ }
132861
+ let map = cache.computedStyle.get(el);
132862
+ if (!map) {
132863
+ map = /* @__PURE__ */ new Map();
132864
+ cache.computedStyle.set(el, map);
132865
+ }
132866
+ if (!map.has(pseudo)) {
132867
+ const st = window.getComputedStyle(el, pseudo);
132868
+ map.set(pseudo, st);
132869
+ }
132870
+ return map.get(pseudo);
132871
+ }
132872
+ function snapshotComputedStyle(style) {
132873
+ const snap = {};
132874
+ for (let prop of style) {
132875
+ snap[prop] = style.getPropertyValue(prop);
132876
+ }
132877
+ return snap;
132878
+ }
132879
+ function splitBackgroundImage(bg) {
132880
+ const parts = [];
132881
+ let depth = 0;
132882
+ let lastIndex = 0;
132883
+ for (let i = 0; i < bg.length; i++) {
132884
+ const char = bg[i];
132885
+ if (char === "(") depth++;
132886
+ if (char === ")") depth--;
132887
+ if (char === "," && depth === 0) {
132888
+ parts.push(bg.slice(lastIndex, i).trim());
132889
+ lastIndex = i + 1;
132890
+ }
132891
+ }
132892
+ parts.push(bg.slice(lastIndex).trim());
132893
+ return parts;
132894
+ }
132895
+
132896
+ // src/utils/browser.js
132897
+ function idle(fn, { fast = false } = {}) {
132898
+ if (fast) return fn();
132899
+ if ("requestIdleCallback" in window) {
132900
+ requestIdleCallback(fn, { timeout: 50 });
132901
+ } else {
132902
+ setTimeout(fn, 1);
132903
+ }
132904
+ }
132905
+ function isSafari() {
132906
+ const ua = typeof navigator !== "undefined" && navigator.userAgent ? navigator.userAgent : "";
132907
+ const isSafariUA = /^((?!chrome|android).)*safari/i.test(ua);
132908
+ const isUIWebView = /AppleWebKit/i.test(ua) && /Mobile/i.test(ua) && !/Safari/i.test(ua);
132909
+ const isWeChatUA = /(MicroMessenger|wxwork|WeCom|WindowsWechat|MacWechat)/i.test(ua);
132910
+ return isSafariUA || isUIWebView || isWeChatUA;
132911
+ }
132912
+
132913
+ // src/modules/styles.js
132914
+ var snapshotCache = /* @__PURE__ */ new WeakMap();
132915
+ var snapshotKeyCache = /* @__PURE__ */ new Map();
132916
+ var __epoch = 0;
132917
+ function bumpEpoch() {
132918
+ __epoch++;
132919
+ }
132920
+ var __wired = false;
132921
+ function setupInvalidationOnce(root = document.documentElement) {
132922
+ if (__wired) return;
132923
+ __wired = true;
132924
+ try {
132925
+ const domObs = new MutationObserver(() => bumpEpoch());
132926
+ domObs.observe(root, { subtree: true, childList: true, characterData: true, attributes: true });
132927
+ } catch {
132928
+ }
132929
+ try {
132930
+ const headObs = new MutationObserver(() => bumpEpoch());
132931
+ headObs.observe(document.head, { subtree: true, childList: true, characterData: true, attributes: true });
132932
+ } catch {
132933
+ }
132934
+ try {
132935
+ const f = document.fonts;
132936
+ if (f) {
132937
+ f.addEventListener?.("loadingdone", bumpEpoch);
132938
+ f.ready?.then(() => bumpEpoch()).catch(() => {
132939
+ });
132940
+ }
132941
+ } catch {
132942
+ }
132943
+ }
132944
+ function snapshotComputedStyleFull(style, options = {}) {
132945
+ const out = {};
132946
+ const vis = style.getPropertyValue("visibility");
132947
+ for (let i = 0; i < style.length; i++) {
132948
+ const prop = style[i];
132949
+ let val = style.getPropertyValue(prop);
132950
+ if ((prop === "background-image" || prop === "content") && val.includes("url(") && !val.includes("data:")) {
132951
+ val = "none";
132952
+ }
132953
+ out[prop] = val;
132954
+ }
132955
+ if (options.embedFonts) {
132956
+ const EXTRA_FONT_PROPS = [
132957
+ "font-feature-settings",
132958
+ "font-variation-settings",
132959
+ "font-kerning",
132960
+ "font-variant",
132961
+ "font-variant-ligatures",
132962
+ "font-optical-sizing"
132963
+ ];
132964
+ for (const prop of EXTRA_FONT_PROPS) {
132965
+ if (out[prop]) continue;
132966
+ try {
132967
+ const v = style.getPropertyValue(prop);
132968
+ if (v) out[prop] = v;
132969
+ } catch {
132970
+ }
132971
+ }
132972
+ }
132973
+ if (vis === "hidden") out.opacity = "0";
132974
+ return out;
132975
+ }
132976
+ var __snapshotSig = /* @__PURE__ */ new WeakMap();
132977
+ function styleSignature(snap) {
132978
+ let sig = __snapshotSig.get(snap);
132979
+ if (sig) return sig;
132980
+ const entries = Object.entries(snap).sort((a, b) => a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0);
132981
+ sig = entries.map(([k, v]) => `${k}:${v}`).join(";");
132982
+ __snapshotSig.set(snap, sig);
132983
+ return sig;
132984
+ }
132985
+ function getSnapshot(el, preStyle = null, options = {}) {
132986
+ const rec = snapshotCache.get(el);
132987
+ if (rec && rec.epoch === __epoch) return rec.snapshot;
132988
+ const style = preStyle || getComputedStyle(el);
132989
+ const snap = snapshotComputedStyleFull(style, options);
132990
+ stripHeightForWrappers(el, style, snap);
132991
+ snapshotCache.set(el, { epoch: __epoch, snapshot: snap });
132992
+ return snap;
132993
+ }
132994
+ function _resolveCtx(sessionOrCtx, opts) {
132995
+ if (sessionOrCtx && sessionOrCtx.session && sessionOrCtx.persist) return sessionOrCtx;
132996
+ if (sessionOrCtx && (sessionOrCtx.styleMap || sessionOrCtx.styleCache || sessionOrCtx.nodeMap)) {
132997
+ return {
132998
+ session: sessionOrCtx,
132999
+ persist: {
133000
+ snapshotKeyCache,
133001
+ defaultStyle: cache.defaultStyle,
133002
+ baseStyle: cache.baseStyle,
133003
+ image: cache.image,
133004
+ resource: cache.resource,
133005
+ background: cache.background,
133006
+ font: cache.font
133007
+ },
133008
+ options: opts || {}
133009
+ };
133010
+ }
133011
+ return {
133012
+ session: cache.session,
133013
+ persist: {
133014
+ snapshotKeyCache,
133015
+ defaultStyle: cache.defaultStyle,
133016
+ baseStyle: cache.baseStyle,
133017
+ image: cache.image,
133018
+ resource: cache.resource,
133019
+ background: cache.background,
133020
+ font: cache.font
133021
+ },
133022
+ options: sessionOrCtx || opts || {}
133023
+ };
133024
+ }
133025
+ async function inlineAllStyles(source, clone, sessionOrCtx, opts) {
133026
+ if (source.tagName === "STYLE") return;
133027
+ const ctx = _resolveCtx(sessionOrCtx, opts);
133028
+ const resetMode = ctx.options && ctx.options.cache || "auto";
133029
+ if (resetMode !== "disabled") setupInvalidationOnce(document.documentElement);
133030
+ if (resetMode === "disabled" && !ctx.session.__bumpedForDisabled) {
133031
+ bumpEpoch();
133032
+ snapshotKeyCache.clear();
133033
+ ctx.session.__bumpedForDisabled = true;
133034
+ }
133035
+ if (NO_DEFAULTS_TAGS.has(source.tagName?.toLowerCase())) {
133036
+ const author = source.getAttribute?.("style");
133037
+ if (author) clone.setAttribute("style", author);
133038
+ }
133039
+ const { session, persist } = ctx;
133040
+ if (!session.styleCache.has(source)) {
133041
+ session.styleCache.set(source, getComputedStyle(source));
133042
+ }
133043
+ const pre = session.styleCache.get(source);
133044
+ const snap = getSnapshot(source, pre, ctx.options);
133045
+ const sig = styleSignature(snap);
133046
+ let key = persist.snapshotKeyCache.get(sig);
133047
+ if (!key) {
133048
+ const tag = source.tagName?.toLowerCase() || "div";
133049
+ key = getStyleKey(snap, tag);
133050
+ persist.snapshotKeyCache.set(sig, key);
133051
+ }
133052
+ session.styleMap.set(clone, key);
133053
+ }
133054
+ function isReplaced(el) {
133055
+ return el instanceof HTMLImageElement || el instanceof HTMLCanvasElement || el instanceof HTMLVideoElement || el instanceof HTMLIFrameElement || el instanceof SVGElement || el instanceof HTMLObjectElement || el instanceof HTMLEmbedElement;
133056
+ }
133057
+ function hasBox(cs) {
133058
+ if (cs.backgroundImage && cs.backgroundImage !== "none") return true;
133059
+ if (cs.backgroundColor && cs.backgroundColor !== "rgba(0, 0, 0, 0)" && cs.backgroundColor !== "transparent") return true;
133060
+ if ((parseFloat(cs.borderTopWidth) || 0) > 0) return true;
133061
+ if ((parseFloat(cs.borderBottomWidth) || 0) > 0) return true;
133062
+ if ((parseFloat(cs.paddingTop) || 0) > 0) return true;
133063
+ if ((parseFloat(cs.paddingBottom) || 0) > 0) return true;
133064
+ const ob = cs.overflowBlock || cs.overflowY || "visible";
133065
+ return ob !== "visible";
133066
+ }
133067
+ function isFlexOrGridItem(el) {
133068
+ const p = el.parentElement;
133069
+ if (!p) return false;
133070
+ const pd = getComputedStyle(p).display || "";
133071
+ return pd.includes("flex") || pd.includes("grid");
133072
+ }
133073
+ function hasFlowFast(el, cs) {
133074
+ if (el.textContent && /\S/.test(el.textContent)) return true;
133075
+ const f = el.firstElementChild, l = el.lastElementChild;
133076
+ if (f && f.tagName === "BR" || l && l.tagName === "BR") return true;
133077
+ const sh = el.scrollHeight;
133078
+ if (sh === 0) return false;
133079
+ const pt = parseFloat(cs.paddingTop) || 0;
133080
+ const pb = parseFloat(cs.paddingBottom) || 0;
133081
+ return sh > pt + pb;
133082
+ }
133083
+ function stripHeightForWrappers(el, cs, snap) {
133084
+ if (el instanceof HTMLElement && el.style && el.style.height) return;
133085
+ const disp = cs.display || "";
133086
+ if (disp.includes("flex") || disp.includes("grid")) return;
133087
+ if (isReplaced(el)) return;
133088
+ const pos = cs.position;
133089
+ if (pos === "absolute" || pos === "fixed" || pos === "sticky") return;
133090
+ if (cs.transform !== "none") return;
133091
+ if (hasBox(cs)) return;
133092
+ if (isFlexOrGridItem(el)) return;
133093
+ if (!hasFlowFast(el, cs)) return;
133094
+ delete snap.height;
133095
+ delete snap["block-size"];
133096
+ }
133097
+
133098
+ // src/modules/CSSVar.js
133099
+ function resolveCSSVars(sourceEl, cloneEl) {
133100
+ if (!(sourceEl instanceof Element) || !(cloneEl instanceof Element)) return;
133101
+ const styleAttr = sourceEl.getAttribute?.("style");
133102
+ let hasVar = !!(styleAttr && styleAttr.includes("var("));
133103
+ if (!hasVar && sourceEl.attributes?.length) {
133104
+ const attrs = sourceEl.attributes;
133105
+ for (let i = 0; i < attrs.length; i++) {
133106
+ const a = attrs[i];
133107
+ if (a && typeof a.value === "string" && a.value.includes("var(")) {
133108
+ hasVar = true;
133109
+ break;
133110
+ }
133111
+ }
133112
+ }
133113
+ if (!hasVar) return;
133114
+ let cs;
133115
+ try {
133116
+ cs = getComputedStyle(sourceEl);
133117
+ } catch {
133118
+ return;
133119
+ }
133120
+ const author = sourceEl.style;
133121
+ if (author && author.length) {
133122
+ for (let i = 0; i < author.length; i++) {
133123
+ const prop = author[i];
133124
+ const val = author.getPropertyValue(prop);
133125
+ if (!val || !val.includes("var(")) continue;
133126
+ const resolved = cs.getPropertyValue(prop);
133127
+ if (resolved) {
133128
+ try {
133129
+ cloneEl.style.setProperty(prop, resolved.trim(), author.getPropertyPriority(prop));
133130
+ } catch {
133131
+ }
133132
+ }
133133
+ }
133134
+ }
133135
+ if (sourceEl.attributes?.length) {
133136
+ const attrs = sourceEl.attributes;
133137
+ for (let i = 0; i < attrs.length; i++) {
133138
+ const a = attrs[i];
133139
+ if (!a || typeof a.value !== "string" || !a.value.includes("var(")) continue;
133140
+ const propName = a.name;
133141
+ let resolved = "";
133142
+ try {
133143
+ resolved = cs.getPropertyValue(propName);
133144
+ } catch {
133145
+ }
133146
+ if (resolved) {
133147
+ try {
133148
+ cloneEl.style.setProperty(propName, resolved.trim());
133149
+ } catch {
133150
+ }
133151
+ }
133152
+ }
133153
+ }
133154
+ }
133155
+
133156
+ // src/core/clone.js
133157
+ function idleCallback(childList, callback, fast) {
133158
+ return Promise.all(childList.map((child) => {
133159
+ return new Promise((resolve) => {
133160
+ function deal() {
133161
+ idle((deadline) => {
133162
+ const hasIdleBudget = deadline && typeof deadline.timeRemaining === "function" ? deadline.timeRemaining() > 0 : true;
133163
+ if (hasIdleBudget) {
133164
+ callback(child, resolve);
133165
+ } else {
133166
+ deal();
133167
+ }
133168
+ }, { fast });
133169
+ }
133170
+ deal();
133171
+ });
133172
+ }));
133173
+ }
133174
+ function addNotSlottedRightmost(sel) {
133175
+ sel = sel.trim();
133176
+ if (!sel) return sel;
133177
+ if (/:not\(\s*\[data-sd-slotted\]\s*\)\s*$/.test(sel)) return sel;
133178
+ return `${sel}:not([data-sd-slotted])`;
133179
+ }
133180
+ function wrapWithScope(selectorList, scopeSelector, excludeSlotted = true) {
133181
+ return selectorList.split(",").map((s) => s.trim()).filter(Boolean).map((s) => {
133182
+ if (s.startsWith(":where(")) return s;
133183
+ if (s.startsWith("@")) return s;
133184
+ const body = excludeSlotted ? addNotSlottedRightmost(s) : s;
133185
+ return `:where(${scopeSelector} ${body})`;
133186
+ }).join(", ");
133187
+ }
133188
+ function rewriteShadowCSS(cssText, scopeSelector) {
133189
+ if (!cssText) return "";
133190
+ cssText = cssText.replace(/:host\(([^)]+)\)/g, (_, sel) => {
133191
+ return `:where(${scopeSelector}:is(${sel.trim()}))`;
133192
+ });
133193
+ cssText = cssText.replace(/:host\b/g, `:where(${scopeSelector})`);
133194
+ cssText = cssText.replace(/:host-context\(([^)]+)\)/g, (_, sel) => {
133195
+ return `:where(:where(${sel.trim()}) ${scopeSelector})`;
133196
+ });
133197
+ cssText = cssText.replace(/::slotted\(([^)]+)\)/g, (_, sel) => {
133198
+ return `:where(${scopeSelector} ${sel.trim()})`;
133199
+ });
133200
+ cssText = cssText.replace(/(^|})(\s*)([^@}{]+){/g, (_, brace, ws, selectorList) => {
133201
+ const wrapped = wrapWithScope(
133202
+ selectorList,
133203
+ scopeSelector,
133204
+ /*excludeSlotted*/
133205
+ true
133206
+ );
133207
+ return `${brace}${ws}${wrapped}{`;
133208
+ });
133209
+ return cssText;
133210
+ }
133211
+ function nextShadowScopeId(sessionCache) {
133212
+ sessionCache.shadowScopeSeq = (sessionCache.shadowScopeSeq || 0) + 1;
133213
+ return `s${sessionCache.shadowScopeSeq}`;
133214
+ }
133215
+ function extractShadowCSS(sr) {
133216
+ let css = "";
133217
+ try {
133218
+ sr.querySelectorAll("style").forEach((s) => {
133219
+ css += (s.textContent || "") + "\n";
133220
+ });
133221
+ const sheets = sr.adoptedStyleSheets || [];
133222
+ for (const sh of sheets) {
133223
+ try {
133224
+ if (sh && sh.cssRules) {
133225
+ for (const rule of sh.cssRules) css += rule.cssText + "\n";
133226
+ }
133227
+ } catch {
133228
+ }
133229
+ }
133230
+ } catch {
133231
+ }
133232
+ return css;
133233
+ }
133234
+ function injectScopedStyle(hostClone, cssText, scopeId) {
133235
+ if (!cssText) return;
133236
+ const style = document.createElement("style");
133237
+ style.setAttribute("data-sd", scopeId);
133238
+ style.textContent = cssText;
133239
+ hostClone.insertBefore(style, hostClone.firstChild || null);
133240
+ }
133241
+ function freezeImgSrcset(original, cloned) {
133242
+ try {
133243
+ const chosen = original.currentSrc || original.src || "";
133244
+ if (!chosen) return;
133245
+ cloned.setAttribute("src", chosen);
133246
+ cloned.removeAttribute("srcset");
133247
+ cloned.removeAttribute("sizes");
133248
+ cloned.loading = "eager";
133249
+ cloned.decoding = "sync";
133250
+ } catch {
133251
+ }
133252
+ }
133253
+ function collectCustomPropsFromCSS(cssText) {
133254
+ const out = /* @__PURE__ */ new Set();
133255
+ if (!cssText) return out;
133256
+ const re = /var\(\s*(--[A-Za-z0-9_-]+)\b/g;
133257
+ let m;
133258
+ while (m = re.exec(cssText)) out.add(m[1]);
133259
+ return out;
133260
+ }
133261
+ function resolveCustomProp(el, name) {
133262
+ try {
133263
+ const cs = getComputedStyle(el);
133264
+ let v = cs.getPropertyValue(name).trim();
133265
+ if (v) return v;
133266
+ } catch {
133267
+ }
133268
+ try {
133269
+ const rootCS = getComputedStyle(document.documentElement);
133270
+ let v = rootCS.getPropertyValue(name).trim();
133271
+ if (v) return v;
133272
+ } catch {
133273
+ }
133274
+ return "";
133275
+ }
133276
+ function buildSeedCustomPropsRule(hostEl, names, scopeSelector) {
133277
+ const decls = [];
133278
+ for (const name of names) {
133279
+ const val = resolveCustomProp(hostEl, name);
133280
+ if (val) decls.push(`${name}: ${val};`);
133281
+ }
133282
+ if (!decls.length) return "";
133283
+ return `${scopeSelector}{${decls.join("")}}
133284
+ `;
133285
+ }
133286
+ function markSlottedSubtree(root) {
133287
+ if (!root) return;
133288
+ if (root.nodeType === Node.ELEMENT_NODE) {
133289
+ root.setAttribute("data-sd-slotted", "");
133290
+ }
133291
+ if (root.querySelectorAll) {
133292
+ root.querySelectorAll("*").forEach((el) => el.setAttribute("data-sd-slotted", ""));
133293
+ }
133294
+ }
133295
+ async function getAccessibleIframeDocument(iframe, attempts = 3) {
133296
+ const probe = () => {
133297
+ try {
133298
+ return iframe.contentDocument || iframe.contentWindow?.document || null;
133299
+ } catch {
133300
+ return null;
133301
+ }
133302
+ };
133303
+ let doc = probe();
133304
+ let i = 0;
133305
+ while (i < attempts && (!doc || !doc.body && !doc.documentElement)) {
133306
+ await new Promise((r) => setTimeout(r, 0));
133307
+ doc = probe();
133308
+ i++;
133309
+ }
133310
+ return doc && (doc.body || doc.documentElement) ? doc : null;
133311
+ }
133312
+ function measureContentBox(el) {
133313
+ const rect = el.getBoundingClientRect();
133314
+ let bl = 0, br = 0, bt = 0, bb = 0;
133315
+ try {
133316
+ const cs = getComputedStyle(el);
133317
+ bl = parseFloat(cs.borderLeftWidth) || 0;
133318
+ br = parseFloat(cs.borderRightWidth) || 0;
133319
+ bt = parseFloat(cs.borderTopWidth) || 0;
133320
+ bb = parseFloat(cs.borderBottomWidth) || 0;
133321
+ } catch {
133322
+ }
133323
+ const contentWidth = Math.max(0, Math.round(rect.width - (bl + br)));
133324
+ const contentHeight = Math.max(0, Math.round(rect.height - (bt + bb)));
133325
+ return { contentWidth, contentHeight, rect };
133326
+ }
133327
+ function pinIframeViewport(doc, w, h) {
133328
+ const style = doc.createElement("style");
133329
+ style.setAttribute("data-sd-iframe-pin", "");
133330
+ style.textContent = `html, body {margin: 0 !important;padding: 0 !important;width: ${w}px !important;height: ${h}px !important;min-width: ${w}px !important;min-height: ${h}px !important;box-sizing: border-box !important;overflow: hidden !important;background-clip: border-box !important;}`;
133331
+ (doc.head || doc.documentElement).appendChild(style);
133332
+ return () => {
133333
+ try {
133334
+ style.remove();
133335
+ } catch {
133336
+ }
133337
+ };
133338
+ }
133339
+ async function rasterizeIframe(iframe, sessionCache, options) {
133340
+ const doc = await getAccessibleIframeDocument(iframe, 3);
133341
+ if (!doc) throw new Error("iframe document not accessible/ready");
133342
+ const { contentWidth, contentHeight, rect } = measureContentBox(iframe);
133343
+ const snap = options?.snap;
133344
+ if (!snap || typeof snap.toPng !== "function") {
133345
+ throw new Error("snapdom.toPng not available in iframe or window");
133346
+ }
133347
+ const nested = { ...options, scale: 1 };
133348
+ const unpin = pinIframeViewport(doc, contentWidth, contentHeight);
133349
+ let imgEl;
133350
+ try {
133351
+ imgEl = await snap.toPng(doc.documentElement, nested);
133352
+ } finally {
133353
+ unpin();
133354
+ }
133355
+ imgEl.style.display = "block";
133356
+ imgEl.style.width = `${contentWidth}px`;
133357
+ imgEl.style.height = `${contentHeight}px`;
133358
+ const wrapper = document.createElement("div");
133359
+ sessionCache.nodeMap.set(wrapper, iframe);
133360
+ inlineAllStyles(iframe, wrapper, sessionCache, options);
133361
+ wrapper.style.overflow = "hidden";
133362
+ wrapper.style.display = "block";
133363
+ if (!wrapper.style.width) wrapper.style.width = `${Math.round(rect.width)}px`;
133364
+ if (!wrapper.style.height) wrapper.style.height = `${Math.round(rect.height)}px`;
133365
+ wrapper.appendChild(imgEl);
133366
+ return wrapper;
133367
+ }
133368
+ async function deepClone(node, sessionCache, options) {
133369
+ if (!node) throw new Error("Invalid node");
133370
+ const clonedAssignedNodes = /* @__PURE__ */ new Set();
133371
+ let pendingSelectValue = null;
133372
+ let pendingTextAreaValue = null;
133373
+ if (node.nodeType === Node.ELEMENT_NODE) {
133374
+ const tag = (node.localName || node.tagName || "").toLowerCase();
133375
+ if (node.id === "snapdom-sandbox" || node.hasAttribute("data-snapdom-sandbox")) {
133376
+ return null;
133377
+ }
133378
+ if (NO_CAPTURE_TAGS.has(tag)) {
133379
+ return null;
133380
+ }
133381
+ }
133382
+ if (node.nodeType === Node.TEXT_NODE) {
133383
+ return node.cloneNode(true);
133384
+ }
133385
+ if (node.nodeType !== Node.ELEMENT_NODE) {
133386
+ return node.cloneNode(true);
133387
+ }
133388
+ if (node.getAttribute("data-capture") === "exclude") {
133389
+ if (options.excludeMode === "hide") {
133390
+ const spacer = document.createElement("div");
133391
+ const rect = node.getBoundingClientRect();
133392
+ spacer.style.cssText = `display:inline-block;width:${rect.width}px;height:${rect.height}px;visibility:hidden;`;
133393
+ return spacer;
133394
+ } else if (options.excludeMode === "remove") {
133395
+ return null;
133396
+ }
133397
+ }
133398
+ if (options.exclude && Array.isArray(options.exclude)) {
133399
+ for (const selector of options.exclude) {
133400
+ try {
133401
+ if (node.matches?.(selector)) {
133402
+ if (options.excludeMode === "hide") {
133403
+ const spacer = document.createElement("div");
133404
+ const rect = node.getBoundingClientRect();
133405
+ spacer.style.cssText = `display:inline-block;width:${rect.width}px;height:${rect.height}px;visibility:hidden;`;
133406
+ return spacer;
133407
+ } else if (options.excludeMode === "remove") {
133408
+ return null;
133409
+ }
133410
+ }
133411
+ } catch (err) {
133412
+ console.warn(`Invalid selector in exclude option: ${selector}`, err);
133413
+ }
133414
+ }
133415
+ }
133416
+ if (typeof options.filter === "function") {
133417
+ try {
133418
+ if (!options.filter(node)) {
133419
+ if (options.filterMode === "hide") {
133420
+ const spacer = document.createElement("div");
133421
+ const rect = node.getBoundingClientRect();
133422
+ spacer.style.cssText = `display:inline-block;width:${rect.width}px;height:${rect.height}px;visibility:hidden;`;
133423
+ return spacer;
133424
+ } else if (options.filterMode === "remove") {
133425
+ return null;
133426
+ }
133427
+ }
133428
+ } catch (err) {
133429
+ console.warn("Error in filter function:", err);
133430
+ }
133431
+ }
133432
+ if (node.tagName === "IFRAME") {
133433
+ let sameOrigin = false;
133434
+ try {
133435
+ sameOrigin = !!(node.contentDocument || node.contentWindow?.document);
133436
+ } catch {
133437
+ sameOrigin = false;
133438
+ }
133439
+ if (sameOrigin) {
133440
+ try {
133441
+ const wrapper = await rasterizeIframe(node, sessionCache, options);
133442
+ return wrapper;
133443
+ } catch (err) {
133444
+ console.warn("[SnapDOM] iframe rasterization failed, fallback:", err);
133445
+ }
133446
+ }
133447
+ if (options.placeholders) {
133448
+ const fallback = document.createElement("div");
133449
+ fallback.style.cssText = `width:${node.offsetWidth}px;height:${node.offsetHeight}px;background-image:repeating-linear-gradient(45deg,#ddd,#ddd 5px,#f9f9f9 5px,#f9f9f9 10px);display:flex;align-items:center;justify-content:center;font-size:12px;color:#555;border:1px solid #aaa;`;
133450
+ inlineAllStyles(node, fallback, sessionCache, options);
133451
+ return fallback;
133452
+ } else {
133453
+ const rect = node.getBoundingClientRect();
133454
+ const spacer = document.createElement("div");
133455
+ spacer.style.cssText = `display:inline-block;width:${rect.width}px;height:${rect.height}px;visibility:hidden;`;
133456
+ inlineAllStyles(node, spacer, sessionCache, options);
133457
+ return spacer;
133458
+ }
133459
+ }
133460
+ if (node.getAttribute("data-capture") === "placeholder") {
133461
+ const clone2 = node.cloneNode(false);
133462
+ sessionCache.nodeMap.set(clone2, node);
133463
+ inlineAllStyles(node, clone2, sessionCache, options);
133464
+ const placeholder = document.createElement("div");
133465
+ placeholder.textContent = node.getAttribute("data-placeholder-text") || "";
133466
+ placeholder.style.cssText = "color:#666;font-size:12px;text-align:center;line-height:1.4;padding:0.5em;box-sizing:border-box;";
133467
+ clone2.appendChild(placeholder);
133468
+ return clone2;
133469
+ }
133470
+ if (node.tagName === "CANVAS") {
133471
+ const dataURL = node.toDataURL();
133472
+ const img = document.createElement("img");
133473
+ img.src = dataURL;
133474
+ img.width = node.width;
133475
+ img.height = node.height;
133476
+ sessionCache.nodeMap.set(img, node);
133477
+ inlineAllStyles(node, img, sessionCache, options);
133478
+ return img;
133479
+ }
133480
+ let clone;
133481
+ try {
133482
+ clone = node.cloneNode(false);
133483
+ resolveCSSVars(node, clone);
133484
+ sessionCache.nodeMap.set(clone, node);
133485
+ if (node.tagName === "IMG") {
133486
+ freezeImgSrcset(node, clone);
133487
+ try {
133488
+ const rect = node.getBoundingClientRect();
133489
+ let w = Math.round(rect.width || 0);
133490
+ let h = Math.round(rect.height || 0);
133491
+ if (!w || !h) {
133492
+ const computed = window.getComputedStyle(node);
133493
+ const cssW = parseFloat(computed.width) || 0;
133494
+ const cssH = parseFloat(computed.height) || 0;
133495
+ const attrW = parseInt(node.getAttribute("width") || "", 10) || 0;
133496
+ const attrH = parseInt(node.getAttribute("height") || "", 10) || 0;
133497
+ const propW = node.width || node.naturalWidth || 0;
133498
+ const propH = node.height || node.naturalHeight || 0;
133499
+ w = Math.round(w || cssW || attrW || propW || 0);
133500
+ h = Math.round(h || cssH || attrH || propH || 0);
133501
+ }
133502
+ if (w) clone.dataset.snapdomWidth = String(w);
133503
+ if (h) clone.dataset.snapdomHeight = String(h);
133504
+ } catch {
133505
+ }
133506
+ }
133507
+ } catch (err) {
133508
+ console.error("[Snapdom] Failed to clone node:", node, err);
133509
+ throw err;
133510
+ }
133511
+ if (node instanceof HTMLTextAreaElement) {
133512
+ const rect = node.getBoundingClientRect();
133513
+ clone.style.width = `${rect.width}px`;
133514
+ clone.style.height = `${rect.height}px`;
133515
+ }
133516
+ if (node instanceof HTMLInputElement) {
133517
+ clone.value = node.value;
133518
+ clone.setAttribute("value", node.value);
133519
+ if (node.checked !== void 0) {
133520
+ clone.checked = node.checked;
133521
+ if (node.checked) clone.setAttribute("checked", "");
133522
+ if (node.indeterminate) clone.indeterminate = node.indeterminate;
133523
+ }
133524
+ }
133525
+ if (node instanceof HTMLSelectElement) {
133526
+ pendingSelectValue = node.value;
133527
+ }
133528
+ if (node instanceof HTMLTextAreaElement) {
133529
+ pendingTextAreaValue = node.value;
133530
+ }
133531
+ inlineAllStyles(node, clone, sessionCache, options);
133532
+ if (node.shadowRoot) {
133533
+ let callback2 = function(child, resolve) {
133534
+ if (child.nodeType === Node.ELEMENT_NODE && child.tagName === "STYLE") {
133535
+ return resolve(null);
133536
+ } else {
133537
+ deepClone(child, sessionCache, options).then((clonedChild) => {
133538
+ resolve(clonedChild || null);
133539
+ }).catch(() => {
133540
+ resolve(null);
133541
+ });
133542
+ }
133543
+ };
133544
+ try {
133545
+ const slots = node.shadowRoot.querySelectorAll("slot");
133546
+ for (const s of slots) {
133547
+ let assigned = [];
133548
+ try {
133549
+ assigned = s.assignedNodes?.({ flatten: true }) || s.assignedNodes?.() || [];
133550
+ } catch {
133551
+ assigned = s.assignedNodes?.() || [];
133552
+ }
133553
+ for (const an of assigned) clonedAssignedNodes.add(an);
133554
+ }
133555
+ } catch {
133556
+ }
133557
+ const scopeId = nextShadowScopeId(sessionCache);
133558
+ const scopeSelector = `[data-sd="${scopeId}"]`;
133559
+ try {
133560
+ clone.setAttribute("data-sd", scopeId);
133561
+ } catch {
133562
+ }
133563
+ const rawCSS = extractShadowCSS(node.shadowRoot);
133564
+ const rewritten = rewriteShadowCSS(rawCSS, scopeSelector);
133565
+ const neededVars = collectCustomPropsFromCSS(rawCSS);
133566
+ const seed = buildSeedCustomPropsRule(node, neededVars, scopeSelector);
133567
+ injectScopedStyle(clone, seed + rewritten, scopeId);
133568
+ const shadowFrag = document.createDocumentFragment();
133569
+ const cloneList2 = await idleCallback(Array.from(node.shadowRoot.childNodes), callback2, options.fast);
133570
+ shadowFrag.append(...cloneList2.filter((clonedChild) => !!clonedChild));
133571
+ clone.appendChild(shadowFrag);
133572
+ }
133573
+ if (node.tagName === "SLOT") {
133574
+ let callback2 = function(child, resolve) {
133575
+ deepClone(child, sessionCache, options).then((clonedChild) => {
133576
+ if (clonedChild) {
133577
+ markSlottedSubtree(clonedChild);
133578
+ }
133579
+ resolve(clonedChild || null);
133580
+ }).catch(() => {
133581
+ resolve(null);
133582
+ });
133583
+ };
133584
+ const assigned = node.assignedNodes?.({ flatten: true }) || [];
133585
+ const nodesToClone = assigned.length > 0 ? assigned : Array.from(node.childNodes);
133586
+ const fragment = document.createDocumentFragment();
133587
+ const cloneList2 = await idleCallback(Array.from(nodesToClone), callback2, options.fast);
133588
+ fragment.append(...cloneList2.filter((clonedChild) => !!clonedChild));
133589
+ return fragment;
133590
+ }
133591
+ function callback(child, resolve) {
133592
+ if (clonedAssignedNodes.has(child)) return resolve(null);
133593
+ deepClone(child, sessionCache, options).then((clonedChild) => {
133594
+ resolve(clonedChild || null);
133595
+ }).catch(() => {
133596
+ resolve(null);
133597
+ });
133598
+ }
133599
+ const cloneList = await idleCallback(Array.from(node.childNodes), callback, options.fast);
133600
+ clone.append(...cloneList.filter((clonedChild) => !!clonedChild));
133601
+ if (pendingSelectValue !== null && clone instanceof HTMLSelectElement) {
133602
+ clone.value = pendingSelectValue;
133603
+ for (const opt of clone.options) {
133604
+ if (opt.value === pendingSelectValue) {
133605
+ opt.setAttribute("selected", "");
133606
+ } else {
133607
+ opt.removeAttribute("selected");
133608
+ }
133609
+ }
133610
+ }
133611
+ if (pendingTextAreaValue !== null && clone instanceof HTMLTextAreaElement) {
133612
+ clone.textContent = pendingTextAreaValue;
133613
+ }
133614
+ return clone;
133615
+ }
133616
+
133617
+ // src/modules/iconFonts.js
133618
+ var defaultIconFonts = [
133619
+ // /uicons/i,
133620
+ /font\s*awesome/i,
133621
+ /material\s*icons/i,
133622
+ /ionicons/i,
133623
+ /glyphicons/i,
133624
+ /feather/i,
133625
+ /bootstrap\s*icons/i,
133626
+ /remix\s*icons/i,
133627
+ /heroicons/i,
133628
+ /layui/i,
133629
+ /lucide/i
133630
+ ];
133631
+ var userIconFonts = [];
133632
+ function extendIconFonts(fonts) {
133633
+ const list = Array.isArray(fonts) ? fonts : [fonts];
133634
+ for (const f of list) {
133635
+ if (f instanceof RegExp) {
133636
+ userIconFonts.push(f);
133637
+ } else if (typeof f === "string") {
133638
+ userIconFonts.push(new RegExp(f, "i"));
133639
+ } else {
133640
+ console.warn("[snapdom] Ignored invalid iconFont value:", f);
133641
+ }
133642
+ }
133643
+ }
133644
+ function isIconFont2(input) {
133645
+ const text = typeof input === "string" ? input : "";
133646
+ const candidates = [...defaultIconFonts, ...userIconFonts];
133647
+ for (const rx of candidates) {
133648
+ if (rx instanceof RegExp && rx.test(text)) return true;
133649
+ }
133650
+ if (/icon/i.test(text) || /glyph/i.test(text) || /symbols/i.test(text) || /feather/i.test(text) || /fontawesome/i.test(text)) return true;
133651
+ return false;
133652
+ }
133653
+
133654
+ // src/modules/fonts.js
133655
+ async function iconToImage(unicodeChar, fontFamily, fontWeight, fontSize = 32, color = "#000") {
133656
+ fontFamily = fontFamily.replace(/^['"]+|['"]+$/g, "");
133657
+ const dpr = window.devicePixelRatio || 1;
133658
+ try {
133659
+ await document.fonts.ready;
133660
+ } catch {
133661
+ }
133662
+ const span = document.createElement("span");
133663
+ span.textContent = unicodeChar;
133664
+ span.style.position = "absolute";
133665
+ span.style.visibility = "hidden";
133666
+ span.style.fontFamily = `"${fontFamily}"`;
133667
+ span.style.fontWeight = fontWeight || "normal";
133668
+ span.style.fontSize = `${fontSize}px`;
133669
+ span.style.lineHeight = "1";
133670
+ span.style.whiteSpace = "nowrap";
133671
+ span.style.padding = "0";
133672
+ span.style.margin = "0";
133673
+ document.body.appendChild(span);
133674
+ const rect = span.getBoundingClientRect();
133675
+ const width = Math.ceil(rect.width);
133676
+ const height = Math.ceil(rect.height);
133677
+ document.body.removeChild(span);
133678
+ const canvas = document.createElement("canvas");
133679
+ canvas.width = Math.max(1, width * dpr);
133680
+ canvas.height = Math.max(1, height * dpr);
133681
+ const ctx = canvas.getContext("2d");
133682
+ ctx.scale(dpr, dpr);
133683
+ ctx.font = fontWeight ? `${fontWeight} ${fontSize}px "${fontFamily}"` : `${fontSize}px "${fontFamily}"`;
133684
+ ctx.textAlign = "left";
133685
+ ctx.textBaseline = "top";
133686
+ ctx.fillStyle = color;
133687
+ ctx.fillText(unicodeChar, 0, 0);
133688
+ return {
133689
+ dataUrl: canvas.toDataURL(),
133690
+ width,
133691
+ height
133692
+ };
133693
+ }
133694
+ var GENERIC_FAMILIES = /* @__PURE__ */ new Set([
133695
+ "serif",
133696
+ "sans-serif",
133697
+ "monospace",
133698
+ "cursive",
133699
+ "fantasy",
133700
+ "system-ui",
133701
+ "emoji",
133702
+ "math",
133703
+ "fangsong",
133704
+ "ui-serif",
133705
+ "ui-sans-serif",
133706
+ "ui-monospace",
133707
+ "ui-rounded"
133708
+ ]);
133709
+ function pickPrimaryFamily(familyList) {
133710
+ if (!familyList) return "";
133711
+ for (let raw of familyList.split(",")) {
133712
+ let f = raw.trim().replace(/^['"]+|['"]+$/g, "");
133713
+ if (!f) continue;
133714
+ if (!GENERIC_FAMILIES.has(f.toLowerCase())) return f;
133715
+ }
133716
+ return "";
133717
+ }
133718
+ function normWeight(w) {
133719
+ const t = String(w ?? "400").trim().toLowerCase();
133720
+ if (t === "normal") return 400;
133721
+ if (t === "bold") return 700;
133722
+ const n = parseInt(t, 10);
133723
+ return Number.isFinite(n) ? Math.min(900, Math.max(100, n)) : 400;
133724
+ }
133725
+ function normStyle(s) {
133726
+ const t = String(s ?? "normal").trim().toLowerCase();
133727
+ if (t.startsWith("italic")) return "italic";
133728
+ if (t.startsWith("oblique")) return "oblique";
133729
+ return "normal";
133730
+ }
133731
+ function normStretchPct(st) {
133732
+ const m = String(st ?? "100%").match(/(\d+(?:\.\d+)?)\s*%/);
133733
+ return m ? Math.max(50, Math.min(200, parseFloat(m[1]))) : 100;
133734
+ }
133735
+ function parseWeightSpec(spec) {
133736
+ const s = String(spec || "400").trim();
133737
+ const m = s.match(/^(\d{2,3})\s+(\d{2,3})$/);
133738
+ if (m) {
133739
+ const a = normWeight(m[1]), b = normWeight(m[2]);
133740
+ return { min: Math.min(a, b), max: Math.max(a, b) };
133741
+ }
133742
+ const v = normWeight(s);
133743
+ return { min: v, max: v };
133744
+ }
133745
+ function parseStyleSpec(spec) {
133746
+ const t = String(spec || "normal").trim().toLowerCase();
133747
+ if (t === "italic") return { kind: "italic" };
133748
+ if (t.startsWith("oblique")) return { kind: "oblique" };
133749
+ return { kind: "normal" };
133750
+ }
133751
+ function parseStretchSpec(spec) {
133752
+ const s = String(spec || "100%").trim();
133753
+ const mm = s.match(/(\d+(?:\.\d+)?)\s*%\s+(\d+(?:\.\d+)?)\s*%/);
133754
+ if (mm) {
133755
+ const a = parseFloat(mm[1]), b = parseFloat(mm[2]);
133756
+ return { min: Math.min(a, b), max: Math.max(a, b) };
133757
+ }
133758
+ const m = s.match(/(\d+(?:\.\d+)?)\s*%/);
133759
+ const v = m ? parseFloat(m[1]) : 100;
133760
+ return { min: v, max: v };
133761
+ }
133762
+ function isLikelyFontStylesheet(href, requiredFamilies) {
133763
+ if (!href) return false;
133764
+ try {
133765
+ const u = new URL(href, location.href);
133766
+ const sameOrigin = u.origin === location.origin;
133767
+ if (sameOrigin) return true;
133768
+ const host = u.host.toLowerCase();
133769
+ const FONT_HOSTS = [
133770
+ "fonts.googleapis.com",
133771
+ "fonts.gstatic.com",
133772
+ "use.typekit.net",
133773
+ "p.typekit.net",
133774
+ "kit.fontawesome.com",
133775
+ "use.fontawesome.com"
133776
+ ];
133777
+ if (FONT_HOSTS.some((h) => host.endsWith(h))) return true;
133778
+ const path = (u.pathname + u.search).toLowerCase();
133779
+ if (/\bfont(s)?\b/.test(path) || /\.woff2?(\b|$)/.test(path)) return true;
133780
+ for (const fam of requiredFamilies) {
133781
+ const tokenA = fam.toLowerCase().replace(/\s+/g, "+");
133782
+ const tokenB = fam.toLowerCase().replace(/\s+/g, "-");
133783
+ if (path.includes(tokenA) || path.includes(tokenB)) return true;
133784
+ }
133785
+ return false;
133786
+ } catch {
133787
+ return false;
133788
+ }
133789
+ }
133790
+ function familiesFromRequired(required) {
133791
+ const out = /* @__PURE__ */ new Set();
133792
+ for (const k of required || []) {
133793
+ const fam = String(k).split("__")[0]?.trim();
133794
+ if (fam) out.add(fam);
133795
+ }
133796
+ return out;
133797
+ }
133798
+ function rewriteRelativeUrls(cssText, baseHref) {
133799
+ if (!cssText) return cssText;
133800
+ return cssText.replace(
133801
+ /url\(\s*(['"]?)([^)'"]+)\1\s*\)/g,
133802
+ (m, q, u) => {
133803
+ const src = (u || "").trim();
133804
+ if (!src || /^data:|^blob:|^https?:|^file:|^about:/i.test(src)) return m;
133805
+ let abs = src;
133806
+ try {
133807
+ abs = new URL(src, baseHref || location.href).href;
133808
+ } catch {
133809
+ }
133810
+ return `url("${abs}")`;
133811
+ }
133812
+ );
133813
+ }
133814
+ var IMPORT_ANY_RE = /@import\s+(?:url\(\s*(['"]?)([^)"']+)\1\s*\)|(['"])([^"']+)\3)([^;]*);/g;
133815
+ var MAX_IMPORT_DEPTH = 4;
133816
+ async function inlineImportsAndRewrite(cssText, ownerHref, useProxy) {
133817
+ if (!cssText) return cssText;
133818
+ const visited = /* @__PURE__ */ new Set();
133819
+ function normalizeUrl(u, base) {
133820
+ try {
133821
+ return new URL(u, base || location.href).href;
133822
+ } catch {
133823
+ return u;
133824
+ }
133825
+ }
133826
+ async function resolveOnce(text, baseHref, depth = 0) {
133827
+ if (depth > MAX_IMPORT_DEPTH) {
133828
+ console.warn(`[snapDOM] @import depth exceeded (${MAX_IMPORT_DEPTH}) at ${baseHref}`);
133829
+ return text;
133830
+ }
133831
+ let out = "";
133832
+ let last = 0;
133833
+ let m;
133834
+ while (m = IMPORT_ANY_RE.exec(text)) {
133835
+ out += text.slice(last, m.index);
133836
+ last = IMPORT_ANY_RE.lastIndex;
133837
+ const rawUrl = (m[2] || m[4] || "").trim();
133838
+ const absUrl = normalizeUrl(rawUrl, baseHref);
133839
+ if (visited.has(absUrl)) {
133840
+ console.warn(`[snapDOM] Skipping circular @import: ${absUrl}`);
133841
+ continue;
133842
+ }
133843
+ visited.add(absUrl);
133844
+ let imported = "";
133845
+ try {
133846
+ const r = await snapFetch(absUrl, { as: "text", useProxy, silent: true });
133847
+ if (r.ok && typeof r.data === "string") imported = r.data;
133848
+ } catch {
133849
+ }
133850
+ if (imported) {
133851
+ imported = rewriteRelativeUrls(imported, absUrl);
133852
+ imported = await resolveOnce(imported, absUrl, depth + 1);
133853
+ out += `
133854
+ /* inlined: ${absUrl} */
133855
+ ${imported}
133856
+ `;
133857
+ } else {
133858
+ out += m[0];
133859
+ }
133860
+ }
133861
+ out += text.slice(last);
133862
+ return out;
133863
+ }
133864
+ let rewritten = rewriteRelativeUrls(cssText, ownerHref || location.href);
133865
+ rewritten = await resolveOnce(rewritten, ownerHref || location.href, 0);
133866
+ return rewritten;
133867
+ }
133868
+ var URL_RE = /url\((["']?)([^"')]+)\1\)/g;
133869
+ var FACE_RE = /@font-face[^{}]*\{[^}]*\}/g;
133870
+ function parseUnicodeRange(ur) {
133871
+ if (!ur) return [];
133872
+ const ranges = [];
133873
+ const parts = ur.split(",").map((s) => s.trim()).filter(Boolean);
133874
+ for (const p of parts) {
133875
+ const m = p.match(/^U\+([0-9A-Fa-f?]+)(?:-([0-9A-Fa-f?]+))?$/);
133876
+ if (!m) continue;
133877
+ const a = m[1], b = m[2];
133878
+ const expand = (hex) => {
133879
+ if (!hex.includes("?")) return parseInt(hex, 16);
133880
+ const min = parseInt(hex.replace(/\?/g, "0"), 16);
133881
+ const max = parseInt(hex.replace(/\?/g, "F"), 16);
133882
+ return [min, max];
133883
+ };
133884
+ if (b) {
133885
+ const A = expand(a), B = expand(b);
133886
+ const min = Array.isArray(A) ? A[0] : A;
133887
+ const max = Array.isArray(B) ? B[1] : B;
133888
+ ranges.push([Math.min(min, max), Math.max(min, max)]);
133889
+ } else {
133890
+ const X = expand(a);
133891
+ if (Array.isArray(X)) ranges.push([X[0], X[1]]);
133892
+ else ranges.push([X, X]);
133893
+ }
133894
+ }
133895
+ return ranges;
133896
+ }
133897
+ function unicodeIntersects(used, ranges) {
133898
+ if (!ranges.length) return true;
133899
+ if (!used || used.size === 0) return true;
133900
+ for (const cp of used) {
133901
+ for (const [a, b] of ranges) if (cp >= a && cp <= b) return true;
133902
+ }
133903
+ return false;
133904
+ }
133905
+ function extractSrcUrls(srcValue, baseHref) {
133906
+ const urls = [];
133907
+ if (!srcValue) return urls;
133908
+ for (const m of srcValue.matchAll(URL_RE)) {
133909
+ let u = (m[2] || "").trim();
133910
+ if (!u || u.startsWith("data:")) continue;
133911
+ if (!/^https?:/i.test(u)) {
133912
+ try {
133913
+ u = new URL(u, baseHref || location.href).href;
133914
+ } catch {
133915
+ }
133916
+ }
133917
+ urls.push(u);
133918
+ }
133919
+ return urls;
133920
+ }
133921
+ async function inlineUrlsInCssBlock(cssBlock, baseHref, useProxy = "") {
133922
+ let out = cssBlock;
133923
+ for (const m of cssBlock.matchAll(URL_RE)) {
133924
+ const raw = extractURL(m[0]);
133925
+ if (!raw) continue;
133926
+ let abs = raw;
133927
+ if (!abs.startsWith("http") && !abs.startsWith("data:")) {
133928
+ try {
133929
+ abs = new URL(abs, baseHref || location.href).href;
133930
+ } catch {
133931
+ }
133932
+ }
133933
+ if (isIconFont2(abs)) continue;
133934
+ if (cache.resource?.has(abs)) {
133935
+ cache.font?.add(abs);
133936
+ out = out.replace(m[0], `url(${cache.resource.get(abs)})`);
133937
+ continue;
133938
+ }
133939
+ if (cache.font?.has(abs)) continue;
133940
+ try {
133941
+ const r = await snapFetch(abs, { as: "dataURL", useProxy, silent: true });
133942
+ if (r.ok && typeof r.data === "string") {
133943
+ const b64 = r.data;
133944
+ cache.resource?.set(abs, b64);
133945
+ cache.font?.add(abs);
133946
+ out = out.replace(m[0], `url(${b64})`);
133947
+ }
133948
+ } catch {
133949
+ console.warn("[snapDOM] Failed to fetch font resource:", abs);
133950
+ }
133951
+ }
133952
+ return out;
133953
+ }
133954
+ function subsetFromRanges(ranges) {
133955
+ if (!ranges.length) return null;
133956
+ const hit = (a, b) => ranges.some(([x, y]) => !(y < a || x > b));
133957
+ const latin = hit(0, 255) || hit(305, 305);
133958
+ const latinExt = hit(256, 591) || hit(7680, 7935);
133959
+ const greek = hit(880, 1023);
133960
+ const cyr = hit(1024, 1279);
133961
+ const viet = hit(7840, 7929) || hit(258, 259) || hit(416, 417) || hit(431, 432);
133962
+ if (viet) return "vietnamese";
133963
+ if (cyr) return "cyrillic";
133964
+ if (greek) return "greek";
133965
+ if (latinExt) return "latin-ext";
133966
+ if (latin) return "latin";
133967
+ return null;
133968
+ }
133969
+ function buildSimpleExcluder(ex = {}) {
133970
+ const famSet = new Set((ex.families || []).map((s) => String(s).toLowerCase()));
133971
+ const domSet = new Set((ex.domains || []).map((s) => String(s).toLowerCase()));
133972
+ const subSet = new Set((ex.subsets || []).map((s) => String(s).toLowerCase()));
133973
+ return (meta, parsedRanges) => {
133974
+ if (famSet.size && famSet.has(meta.family.toLowerCase())) return true;
133975
+ if (domSet.size) {
133976
+ for (const u of meta.srcUrls) {
133977
+ try {
133978
+ if (domSet.has(new URL(u).host.toLowerCase())) return true;
133979
+ } catch {
133980
+ }
133981
+ }
133982
+ }
133983
+ if (subSet.size) {
133984
+ const label = subsetFromRanges(parsedRanges);
133985
+ if (label && subSet.has(label)) return true;
133986
+ }
133987
+ return false;
133988
+ };
133989
+ }
133990
+ function dedupeFontFaces(cssText) {
133991
+ if (!cssText) return cssText;
133992
+ const FACE_RE_G = /@font-face[^{}]*\{[^}]*\}/gi;
133993
+ const seen = /* @__PURE__ */ new Set();
133994
+ const out = [];
133995
+ for (const block of cssText.match(FACE_RE_G) || []) {
133996
+ const familyRaw = block.match(/font-family:\s*([^;]+);/i)?.[1] || "";
133997
+ const family = pickPrimaryFamily(familyRaw);
133998
+ const weightSpec = (block.match(/font-weight:\s*([^;]+);/i)?.[1] || "400").trim();
133999
+ const styleSpec = (block.match(/font-style:\s*([^;]+);/i)?.[1] || "normal").trim();
134000
+ const stretchSpec = (block.match(/font-stretch:\s*([^;]+);/i)?.[1] || "100%").trim();
134001
+ const urange = (block.match(/unicode-range:\s*([^;]+);/i)?.[1] || "").trim();
134002
+ const srcRaw = (block.match(/src\s*:\s*([^;]+);/i)?.[1] || "").trim();
134003
+ const urls = extractSrcUrls(srcRaw, location.href);
134004
+ const srcPart = urls.length ? urls.map((u) => String(u).toLowerCase()).sort().join("|") : srcRaw.toLowerCase();
134005
+ const key = [
134006
+ String(family || "").toLowerCase(),
134007
+ weightSpec,
134008
+ styleSpec,
134009
+ stretchSpec,
134010
+ urange.toLowerCase(),
134011
+ srcPart
134012
+ ].join("|");
134013
+ if (!seen.has(key)) {
134014
+ seen.add(key);
134015
+ out.push(block);
134016
+ }
134017
+ }
134018
+ if (out.length === 0) return cssText;
134019
+ let i = 0;
134020
+ return cssText.replace(FACE_RE_G, () => out[i++] || "");
134021
+ }
134022
+ function buildFontsCacheKey(required, exclude, localFonts, useProxy) {
134023
+ const req = Array.from(required || []).sort().join("|");
134024
+ const ex = exclude ? JSON.stringify({
134025
+ families: (exclude.families || []).map((s) => String(s).toLowerCase()).sort(),
134026
+ domains: (exclude.domains || []).map((s) => String(s).toLowerCase()).sort(),
134027
+ subsets: (exclude.subsets || []).map((s) => String(s).toLowerCase()).sort()
134028
+ }) : "";
134029
+ const lf = (localFonts || []).map((f) => `${(f.family || "").toLowerCase()}::${f.weight || "normal"}::${f.style || "normal"}::${f.src || ""}`).sort().join("|");
134030
+ const px = useProxy || "";
134031
+ return `fonts-embed-css::req=${req}::ex=${ex}::lf=${lf}::px=${px}`;
134032
+ }
134033
+ async function collectFacesFromSheet(sheet, baseHref, emitFace, ctx) {
134034
+ let rules;
134035
+ try {
134036
+ rules = sheet.cssRules || [];
134037
+ } catch {
134038
+ return;
134039
+ }
134040
+ const normalizeUrl = (u, base) => {
134041
+ try {
134042
+ return new URL(u, base || location.href).href;
134043
+ } catch {
134044
+ return u;
134045
+ }
134046
+ };
134047
+ for (const rule of rules) {
134048
+ if (rule.type === CSSRule.IMPORT_RULE && rule.styleSheet) {
134049
+ const childHref = rule.href ? normalizeUrl(rule.href, baseHref) : baseHref;
134050
+ if (ctx.depth >= MAX_IMPORT_DEPTH) {
134051
+ console.warn(`[snapDOM] CSSOM import depth exceeded (${MAX_IMPORT_DEPTH}) at ${childHref}`);
134052
+ continue;
134053
+ }
134054
+ if (childHref && ctx.visitedSheets.has(childHref)) {
134055
+ console.warn(`[snapDOM] Skipping circular CSSOM import: ${childHref}`);
134056
+ continue;
134057
+ }
134058
+ if (childHref) ctx.visitedSheets.add(childHref);
134059
+ const nextCtx = { ...ctx, depth: (ctx.depth || 0) + 1 };
134060
+ await collectFacesFromSheet(rule.styleSheet, childHref, emitFace, nextCtx);
134061
+ continue;
134062
+ }
134063
+ if (rule.type === CSSRule.FONT_FACE_RULE) {
134064
+ const famRaw = (rule.style.getPropertyValue("font-family") || "").trim();
134065
+ const family = pickPrimaryFamily(famRaw);
134066
+ if (!family || isIconFont2(family)) continue;
134067
+ const weightSpec = (rule.style.getPropertyValue("font-weight") || "400").trim();
134068
+ const styleSpec = (rule.style.getPropertyValue("font-style") || "normal").trim();
134069
+ const stretchSpec = (rule.style.getPropertyValue("font-stretch") || "100%").trim();
134070
+ const srcRaw = (rule.style.getPropertyValue("src") || "").trim();
134071
+ const urange = (rule.style.getPropertyValue("unicode-range") || "").trim();
134072
+ if (!ctx.faceMatchesRequired(family, styleSpec, weightSpec, stretchSpec)) continue;
134073
+ const ranges = parseUnicodeRange(urange);
134074
+ if (!unicodeIntersects(ctx.usedCodepoints, ranges)) continue;
134075
+ const meta = {
134076
+ family,
134077
+ weightSpec,
134078
+ styleSpec,
134079
+ stretchSpec,
134080
+ unicodeRange: urange,
134081
+ srcRaw,
134082
+ srcUrls: extractSrcUrls(srcRaw, baseHref || location.href),
134083
+ href: baseHref || location.href
134084
+ };
134085
+ if (ctx.simpleExcluder && ctx.simpleExcluder(meta, ranges)) continue;
134086
+ if (/url\(/i.test(srcRaw)) {
134087
+ const inlinedSrc = await inlineUrlsInCssBlock(srcRaw, baseHref || location.href, ctx.useProxy);
134088
+ await emitFace(`@font-face{font-family:${family};src:${inlinedSrc};font-style:${styleSpec};font-weight:${weightSpec};font-stretch:${stretchSpec};${urange ? `unicode-range:${urange};` : ""}}`);
134089
+ } else {
134090
+ await emitFace(`@font-face{font-family:${family};src:${srcRaw};font-style:${styleSpec};font-weight:${weightSpec};font-stretch:${stretchSpec};${urange ? `unicode-range:${urange};` : ""}}`);
134091
+ }
134092
+ }
134093
+ }
134094
+ }
134095
+ async function embedCustomFonts({
134096
+ required,
134097
+ usedCodepoints,
134098
+ exclude = void 0,
134099
+ localFonts = [],
134100
+ useProxy = ""
134101
+ } = {}) {
134102
+ if (!(required instanceof Set)) required = /* @__PURE__ */ new Set();
134103
+ if (!(usedCodepoints instanceof Set)) usedCodepoints = /* @__PURE__ */ new Set();
134104
+ const requiredIndex = /* @__PURE__ */ new Map();
134105
+ for (const key of required) {
134106
+ const [fam, w, s, st] = String(key).split("__");
134107
+ if (!fam) continue;
134108
+ const arr = requiredIndex.get(fam) || [];
134109
+ arr.push({ w: parseInt(w, 10), s, st: parseInt(st, 10) });
134110
+ requiredIndex.set(fam, arr);
134111
+ }
134112
+ function faceMatchesRequired(fam, styleSpec, weightSpec, stretchSpec) {
134113
+ if (!requiredIndex.has(fam)) return false;
134114
+ const need = requiredIndex.get(fam);
134115
+ const ws = parseWeightSpec(weightSpec);
134116
+ const ss = parseStyleSpec(styleSpec);
134117
+ const ts = parseStretchSpec(stretchSpec);
134118
+ const faceIsRange = ws.min !== ws.max;
134119
+ const faceSingleW = ws.min;
134120
+ const styleOK = (reqKind) => ss.kind === "normal" && reqKind === "normal" || ss.kind !== "normal" && (reqKind === "italic" || reqKind === "oblique");
134121
+ let exactMatched = false;
134122
+ for (const r of need) {
134123
+ const wOk = faceIsRange ? r.w >= ws.min && r.w <= ws.max : r.w === faceSingleW;
134124
+ const sOk = styleOK(normStyle(r.s));
134125
+ const tOk = r.st >= ts.min && r.st <= ts.max;
134126
+ if (wOk && sOk && tOk) {
134127
+ exactMatched = true;
134128
+ break;
134129
+ }
134130
+ }
134131
+ if (exactMatched) return true;
134132
+ if (!faceIsRange) {
134133
+ for (const r of need) {
134134
+ const sOk = styleOK(normStyle(r.s));
134135
+ const tOk = r.st >= ts.min && r.st <= ts.max;
134136
+ const nearWeight = Math.abs(faceSingleW - r.w) <= 300;
134137
+ if (nearWeight && sOk && tOk) return true;
134138
+ }
134139
+ }
134140
+ return false;
134141
+ }
134142
+ const simpleExcluder = buildSimpleExcluder(exclude);
134143
+ const cacheKey = buildFontsCacheKey(required, exclude, localFonts, useProxy);
134144
+ if (cache.resource?.has(cacheKey)) {
134145
+ return cache.resource.get(cacheKey);
134146
+ }
134147
+ const requiredFamilies = familiesFromRequired(required);
134148
+ const importUrls = [];
134149
+ const IMPORT_ANY_RE_LOCAL = IMPORT_ANY_RE;
134150
+ for (const styleTag of document.querySelectorAll("style")) {
134151
+ const cssText = styleTag.textContent || "";
134152
+ for (const m of cssText.matchAll(IMPORT_ANY_RE_LOCAL)) {
134153
+ const u = (m[2] || m[4] || "").trim();
134154
+ if (!u || isIconFont2(u)) continue;
134155
+ const hasLink = !!document.querySelector(`link[rel="stylesheet"][href="${u}"]`);
134156
+ if (!hasLink) importUrls.push(u);
134157
+ }
134158
+ }
134159
+ if (importUrls.length) {
134160
+ await Promise.all(importUrls.map((u) => new Promise((resolve) => {
134161
+ if (document.querySelector(`link[rel="stylesheet"][href="${u}"]`)) return resolve(null);
134162
+ const link = document.createElement("link");
134163
+ link.rel = "stylesheet";
134164
+ link.href = u;
134165
+ link.setAttribute("data-snapdom", "injected-import");
134166
+ link.onload = () => resolve(link);
134167
+ link.onerror = () => resolve(null);
134168
+ document.head.appendChild(link);
134169
+ })));
134170
+ }
134171
+ let finalCSS = "";
134172
+ const linkNodes = Array.from(document.querySelectorAll('link[rel="stylesheet"]')).filter((l) => !!l.href);
134173
+ for (const link of linkNodes) {
134174
+ try {
134175
+ if (isIconFont2(link.href)) continue;
134176
+ let cssText = "";
134177
+ let sameOrigin = false;
134178
+ try {
134179
+ sameOrigin = new URL(link.href, location.href).origin === location.origin;
134180
+ } catch {
134181
+ }
134182
+ if (!sameOrigin) {
134183
+ if (!isLikelyFontStylesheet(link.href, requiredFamilies)) continue;
134184
+ }
134185
+ if (sameOrigin) {
134186
+ const sheet = Array.from(document.styleSheets).find((s) => s.href === link.href);
134187
+ if (sheet) {
134188
+ try {
134189
+ const rules = sheet.cssRules || [];
134190
+ cssText = Array.from(rules).map((r) => r.cssText).join("");
134191
+ } catch {
134192
+ }
134193
+ }
134194
+ }
134195
+ if (!cssText) {
134196
+ const res = await snapFetch(link.href, { as: "text", useProxy });
134197
+ cssText = res.data;
134198
+ if (isIconFont2(link.href)) continue;
134199
+ }
134200
+ cssText = await inlineImportsAndRewrite(cssText, link.href, useProxy);
134201
+ let facesOut = "";
134202
+ for (const face of cssText.match(FACE_RE) || []) {
134203
+ const famRaw = (face.match(/font-family:\s*([^;]+);/i)?.[1] || "").trim();
134204
+ const family = pickPrimaryFamily(famRaw);
134205
+ if (!family || isIconFont2(family)) continue;
134206
+ const weightSpec = (face.match(/font-weight:\s*([^;]+);/i)?.[1] || "400").trim();
134207
+ const styleSpec = (face.match(/font-style:\s*([^;]+);/i)?.[1] || "normal").trim();
134208
+ const stretchSpec = (face.match(/font-stretch:\s*([^;]+);/i)?.[1] || "100%").trim();
134209
+ const urange = (face.match(/unicode-range:\s*([^;]+);/i)?.[1] || "").trim();
134210
+ const srcRaw = (face.match(/src\s*:\s*([^;]+);/i)?.[1] || "").trim();
134211
+ const srcUrls = extractSrcUrls(srcRaw, link.href);
134212
+ if (!faceMatchesRequired(family, styleSpec, weightSpec, stretchSpec)) continue;
134213
+ const ranges = parseUnicodeRange(urange);
134214
+ if (!unicodeIntersects(usedCodepoints, ranges)) continue;
134215
+ const meta = { family, weightSpec, styleSpec, stretchSpec, unicodeRange: urange, srcRaw, srcUrls, href: link.href };
134216
+ if (exclude && simpleExcluder(meta, ranges)) continue;
134217
+ const newFace = /url\(/i.test(srcRaw) ? await inlineUrlsInCssBlock(face, link.href, useProxy) : face;
134218
+ facesOut += newFace;
134219
+ }
134220
+ if (facesOut.trim()) finalCSS += facesOut;
134221
+ } catch {
134222
+ console.warn("[snapDOM] Failed to process stylesheet:", link.href);
134223
+ }
134224
+ }
134225
+ const ctx = {
134226
+ requiredIndex,
134227
+ usedCodepoints,
134228
+ faceMatchesRequired,
134229
+ simpleExcluder: exclude ? buildSimpleExcluder(exclude) : null,
134230
+ useProxy,
134231
+ visitedSheets: /* @__PURE__ */ new Set(),
134232
+ depth: 0
134233
+ };
134234
+ for (const sheet of document.styleSheets) {
134235
+ if (sheet.href && linkNodes.some((l) => l.href === sheet.href)) continue;
134236
+ try {
134237
+ const rootHref = sheet.href || location.href;
134238
+ if (rootHref) ctx.visitedSheets.add(rootHref);
134239
+ await collectFacesFromSheet(
134240
+ sheet,
134241
+ rootHref,
134242
+ async (faceCss) => {
134243
+ finalCSS += faceCss;
134244
+ },
134245
+ ctx
134246
+ );
134247
+ } catch {
134248
+ }
134249
+ }
134250
+ try {
134251
+ for (const f of document.fonts || []) {
134252
+ if (!f || !f.family || f.status !== "loaded" || !f._snapdomSrc) continue;
134253
+ const fam = String(f.family).replace(/^['"]+|['"]+$/g, "");
134254
+ if (isIconFont2(fam)) continue;
134255
+ if (!requiredIndex.has(fam)) continue;
134256
+ if (exclude?.families && exclude.families.some((n) => String(n).toLowerCase() === fam.toLowerCase())) {
134257
+ continue;
134258
+ }
134259
+ let b64 = f._snapdomSrc;
134260
+ if (!String(b64).startsWith("data:")) {
134261
+ if (cache.resource?.has(f._snapdomSrc)) {
134262
+ b64 = cache.resource.get(f._snapdomSrc);
134263
+ cache.font?.add(f._snapdomSrc);
134264
+ } else if (!cache.font?.has(f._snapdomSrc)) {
134265
+ try {
134266
+ const r = await snapFetch(f._snapdomSrc, { as: "dataURL", useProxy, silent: true });
134267
+ if (r.ok && typeof r.data === "string") {
134268
+ b64 = r.data;
134269
+ cache.resource?.set(f._snapdomSrc, b64);
134270
+ cache.font?.add(f._snapdomSrc);
134271
+ } else {
134272
+ continue;
134273
+ }
134274
+ } catch {
134275
+ console.warn("[snapDOM] Failed to fetch dynamic font src:", f._snapdomSrc);
134276
+ continue;
134277
+ }
134278
+ }
134279
+ }
134280
+ finalCSS += `@font-face{font-family:'${fam}';src:url(${b64});font-style:${f.style || "normal"};font-weight:${f.weight || "normal"};}`;
134281
+ }
134282
+ } catch {
134283
+ }
134284
+ for (const font of localFonts) {
134285
+ if (!font || typeof font !== "object") continue;
134286
+ const family = String(font.family || "").replace(/^['"]+|['"]+$/g, "");
134287
+ if (!family || isIconFont2(family)) continue;
134288
+ if (!requiredIndex.has(family)) continue;
134289
+ if (exclude?.families && exclude.families.some((n) => String(n).toLowerCase() === family.toLowerCase())) continue;
134290
+ const weight = font.weight != null ? String(font.weight) : "normal";
134291
+ const style = font.style != null ? String(font.style) : "normal";
134292
+ const stretch = font.stretchPct != null ? `${font.stretchPct}%` : "100%";
134293
+ const src = String(font.src || "");
134294
+ let b64 = src;
134295
+ if (!b64.startsWith("data:")) {
134296
+ if (cache.resource?.has(src)) {
134297
+ b64 = cache.resource.get(src);
134298
+ cache.font?.add(src);
134299
+ } else if (!cache.font?.has(src)) {
134300
+ try {
134301
+ const r = await snapFetch(src, { as: "dataURL", useProxy, silent: true });
134302
+ if (r.ok && typeof r.data === "string") {
134303
+ b64 = r.data;
134304
+ cache.resource?.set(src, b64);
134305
+ cache.font?.add(src);
134306
+ } else {
134307
+ continue;
134308
+ }
134309
+ } catch {
134310
+ console.warn("[snapDOM] Failed to fetch localFonts src:", src);
134311
+ continue;
134312
+ }
134313
+ }
134314
+ }
134315
+ finalCSS += `@font-face{font-family:'${family}';src:url(${b64});font-style:${style};font-weight:${weight};font-stretch:${stretch};}`;
134316
+ }
134317
+ if (finalCSS) {
134318
+ finalCSS = dedupeFontFaces(finalCSS);
134319
+ cache.resource?.set(cacheKey, finalCSS);
134320
+ }
134321
+ return finalCSS;
134322
+ }
134323
+ function collectUsedFontVariants(root) {
134324
+ const req = /* @__PURE__ */ new Set();
134325
+ if (!root) return req;
134326
+ const tw = document.createTreeWalker(root, NodeFilter.SHOW_ELEMENT, null);
134327
+ const addFromStyle = (cs) => {
134328
+ const family = pickPrimaryFamily(cs.fontFamily);
134329
+ if (!family) return;
134330
+ const key = (w, s, st) => `${family}__${normWeight(w)}__${normStyle(s)}__${normStretchPct(st)}`;
134331
+ req.add(key(cs.fontWeight, cs.fontStyle, cs.fontStretch));
134332
+ };
134333
+ addFromStyle(getComputedStyle(root));
134334
+ const csBeforeRoot = getComputedStyle(root, "::before");
134335
+ if (csBeforeRoot && csBeforeRoot.content && csBeforeRoot.content !== "none") addFromStyle(csBeforeRoot);
134336
+ const csAfterRoot = getComputedStyle(root, "::after");
134337
+ if (csAfterRoot && csAfterRoot.content && csAfterRoot.content !== "none") addFromStyle(csAfterRoot);
134338
+ while (tw.nextNode()) {
134339
+ const el = (
134340
+ /** @type {Element} */
134341
+ tw.currentNode
134342
+ );
134343
+ const cs = getComputedStyle(el);
134344
+ addFromStyle(cs);
134345
+ const b = getComputedStyle(el, "::before");
134346
+ if (b && b.content && b.content !== "none") addFromStyle(b);
134347
+ const a = getComputedStyle(el, "::after");
134348
+ if (a && a.content && a.content !== "none") addFromStyle(a);
134349
+ }
134350
+ return req;
134351
+ }
134352
+ function collectUsedCodepoints(root) {
134353
+ const used = /* @__PURE__ */ new Set();
134354
+ const pushText = (txt) => {
134355
+ if (!txt) return;
134356
+ for (const ch of txt) used.add(ch.codePointAt(0));
134357
+ };
134358
+ const walker = document.createTreeWalker(root, NodeFilter.SHOW_ELEMENT | NodeFilter.SHOW_TEXT, null);
134359
+ while (walker.nextNode()) {
134360
+ const n = walker.currentNode;
134361
+ if (n.nodeType === Node.TEXT_NODE) {
134362
+ pushText(n.nodeValue || "");
134363
+ } else if (n.nodeType === Node.ELEMENT_NODE) {
134364
+ const el = (
134365
+ /** @type {Element} */
134366
+ n
134367
+ );
134368
+ for (const pseudo of ["::before", "::after"]) {
134369
+ const cs = getComputedStyle(el, pseudo);
134370
+ const c = cs?.getPropertyValue("content");
134371
+ if (!c || c === "none") continue;
134372
+ if (/^"/.test(c) || /^'/.test(c)) {
134373
+ pushText(c.slice(1, -1));
134374
+ } else {
134375
+ const matches = c.match(/\\[0-9A-Fa-f]{1,6}/g);
134376
+ if (matches) {
134377
+ for (const m of matches) {
134378
+ try {
134379
+ used.add(parseInt(m.slice(1), 16));
134380
+ } catch {
134381
+ }
134382
+ }
134383
+ }
134384
+ }
134385
+ }
134386
+ }
134387
+ }
134388
+ return used;
134389
+ }
134390
+ async function ensureFontsReady(families, warmupRepetitions = 2) {
134391
+ try {
134392
+ await document.fonts.ready;
134393
+ } catch {
134394
+ }
134395
+ const fams = Array.from(families || []).filter(Boolean);
134396
+ if (fams.length === 0) return;
134397
+ const warmupOnce = () => {
134398
+ const container = document.createElement("div");
134399
+ container.style.cssText = "position:absolute!important;left:-9999px!important;top:0!important;opacity:0!important;pointer-events:none!important;contain:layout size style;";
134400
+ for (const fam of fams) {
134401
+ const span = document.createElement("span");
134402
+ span.textContent = "AaBbGg1234\xC1\xC9\xCD\xD3\xDA\xE7\xF1\u2014\u221E";
134403
+ span.style.fontFamily = `"${fam}"`;
134404
+ span.style.fontWeight = "700";
134405
+ span.style.fontStyle = "italic";
134406
+ span.style.fontSize = "32px";
134407
+ span.style.lineHeight = "1";
134408
+ span.style.whiteSpace = "nowrap";
134409
+ span.style.margin = "0";
134410
+ span.style.padding = "0";
134411
+ container.appendChild(span);
134412
+ }
134413
+ document.body.appendChild(container);
134414
+ container.offsetWidth;
134415
+ document.body.removeChild(container);
134416
+ };
134417
+ for (let i = 0; i < Math.max(1, warmupRepetitions); i++) {
134418
+ warmupOnce();
134419
+ await new Promise((r) => requestAnimationFrame(() => requestAnimationFrame(r)));
134420
+ }
134421
+ }
134422
+
134423
+ // src/modules/counter.js
134424
+ function hasCounters(input) {
134425
+ return /\bcounter\s*\(|\bcounters\s*\(/.test(input || "");
134426
+ }
134427
+ function unquoteDoubleStrings(s) {
134428
+ return (s || "").replace(/"([^"]*)"/g, "$1");
134429
+ }
134430
+ function alpha(n, upper = false) {
134431
+ let s = "", x = Math.max(1, n);
134432
+ while (x > 0) {
134433
+ x--;
134434
+ s = String.fromCharCode(97 + x % 26) + s;
134435
+ x = Math.floor(x / 26);
134436
+ }
134437
+ return upper ? s.toUpperCase() : s;
134438
+ }
134439
+ function roman(n, upper = true) {
134440
+ const map = [[1e3, "M"], [900, "CM"], [500, "D"], [400, "CD"], [100, "C"], [90, "XC"], [50, "L"], [40, "XL"], [10, "X"], [9, "IX"], [5, "V"], [4, "IV"], [1, "I"]];
134441
+ let num = Math.max(1, Math.min(3999, n)), out = "";
134442
+ for (const [v, sym] of map) while (num >= v) {
134443
+ out += sym;
134444
+ num -= v;
134445
+ }
134446
+ return upper ? out : out.toLowerCase();
134447
+ }
134448
+ function formatCounter(value, style) {
134449
+ switch ((style || "decimal").toLowerCase()) {
134450
+ case "decimal":
134451
+ return String(Math.max(0, value));
134452
+ case "decimal-leading-zero":
134453
+ return (value < 10 ? "0" : "") + String(Math.max(0, value));
134454
+ case "lower-alpha":
134455
+ return alpha(value, false);
134456
+ case "upper-alpha":
134457
+ return alpha(value, true);
134458
+ case "lower-roman":
134459
+ return roman(value, false);
134460
+ case "upper-roman":
134461
+ return roman(value, true);
134462
+ default:
134463
+ return String(Math.max(0, value));
134464
+ }
134465
+ }
134466
+ function buildCounterContext(root) {
134467
+ const nodeCounters = /* @__PURE__ */ new WeakMap();
134468
+ const rootEl = root instanceof Document ? root.documentElement : root;
134469
+ const isLi = (el) => el && el.tagName === "LI";
134470
+ const countPrevLi = (li) => {
134471
+ let c = 0, p = li?.parentElement;
134472
+ if (!p) return 0;
134473
+ for (const sib of p.children) {
134474
+ if (sib === li) break;
134475
+ if (sib.tagName === "LI") c++;
134476
+ }
134477
+ return c;
134478
+ };
134479
+ const cloneMap = (m) => {
134480
+ const out = /* @__PURE__ */ new Map();
134481
+ for (const [k, arr] of m) out.set(k, arr.slice());
134482
+ return out;
134483
+ };
134484
+ const applyTo = (baseMap, parentMap, el) => {
134485
+ const map = cloneMap(baseMap);
134486
+ let reset;
134487
+ try {
134488
+ reset = el.style?.counterReset || getComputedStyle(el).counterReset;
134489
+ } catch {
134490
+ }
134491
+ if (reset && reset !== "none") {
134492
+ for (const part of reset.split(",")) {
134493
+ const toks = part.trim().split(/\s+/);
134494
+ const name = toks[0];
134495
+ const val = Number.isFinite(Number(toks[1])) ? Number(toks[1]) : 0;
134496
+ if (!name) continue;
134497
+ const parentStack = parentMap.get(name);
134498
+ if (parentStack && parentStack.length) {
134499
+ const s = parentStack.slice();
134500
+ s.push(val);
134501
+ map.set(name, s);
134502
+ } else {
134503
+ map.set(name, [val]);
134504
+ }
134505
+ }
134506
+ }
134507
+ let inc;
134508
+ try {
134509
+ inc = el.style?.counterIncrement || getComputedStyle(el).counterIncrement;
134510
+ } catch {
134511
+ }
134512
+ if (inc && inc !== "none") {
134513
+ for (const part of inc.split(",")) {
134514
+ const toks = part.trim().split(/\s+/);
134515
+ const name = toks[0];
134516
+ const by = Number.isFinite(Number(toks[1])) ? Number(toks[1]) : 1;
134517
+ if (!name) continue;
134518
+ const stack = map.get(name) || [];
134519
+ if (stack.length === 0) stack.push(0);
134520
+ stack[stack.length - 1] += by;
134521
+ map.set(name, stack);
134522
+ }
134523
+ }
134524
+ try {
134525
+ const cs = getComputedStyle(el);
134526
+ if (cs.display === "list-item" && isLi(el)) {
134527
+ const p = el.parentElement;
134528
+ let idx = 1;
134529
+ if (p && p.tagName === "OL") {
134530
+ const startAttr = p.getAttribute("start");
134531
+ const start = Number.isFinite(Number(startAttr)) ? Number(startAttr) : 1;
134532
+ const prev = countPrevLi(el);
134533
+ const ownAttr = el.getAttribute("value");
134534
+ idx = Number.isFinite(Number(ownAttr)) ? Number(ownAttr) : start + prev;
134535
+ } else {
134536
+ idx = 1 + countPrevLi(el);
134537
+ }
134538
+ const s = map.get("list-item") || [];
134539
+ if (s.length === 0) s.push(0);
134540
+ s[s.length - 1] = idx;
134541
+ map.set("list-item", s);
134542
+ }
134543
+ } catch {
134544
+ }
134545
+ return map;
134546
+ };
134547
+ const build = (el, parentMap, carryMap) => {
134548
+ const curr = applyTo(carryMap, parentMap, el);
134549
+ nodeCounters.set(el, curr);
134550
+ let nextCarry = curr;
134551
+ for (const child of el.children) {
134552
+ const childCarry = build(child, curr, nextCarry);
134553
+ nextCarry = childCarry;
134554
+ }
134555
+ return curr;
134556
+ };
134557
+ const empty = /* @__PURE__ */ new Map();
134558
+ build(rootEl, empty, empty);
134559
+ return {
134560
+ /**
134561
+ * Get top value for counter name at given node.
134562
+ * @param {Element} node
134563
+ * @param {string} name
134564
+ */
134565
+ get(node, name) {
134566
+ const s = nodeCounters.get(node)?.get(name);
134567
+ return s && s.length ? s[s.length - 1] : 0;
134568
+ },
134569
+ /**
134570
+ * Get full stack for counter name at given node.
134571
+ * @param {Element} node
134572
+ * @param {string} name
134573
+ */
134574
+ getStack(node, name) {
134575
+ const s = nodeCounters.get(node)?.get(name);
134576
+ return s ? s.slice() : [];
134577
+ }
134578
+ };
134579
+ }
134580
+ function resolveCountersInContent(raw, node, ctx) {
134581
+ if (!raw || raw === "none") return raw;
134582
+ try {
134583
+ const RX = /\b(counter|counters)\s*\(([^)]+)\)/g;
134584
+ let out = raw.replace(RX, (_, fn, args) => {
134585
+ const parts = String(args).split(",").map((s) => s.trim());
134586
+ if (fn === "counter") {
134587
+ const name = parts[0]?.replace(/^["']|["']$/g, "");
134588
+ const style = (parts[1] || "decimal").toLowerCase();
134589
+ const v = ctx.get(node, name);
134590
+ return formatCounter(v, style);
134591
+ } else {
134592
+ const name = parts[0]?.replace(/^["']|["']$/g, "");
134593
+ const sep = parts[1]?.replace(/^["']|["']$/g, "") ?? "";
134594
+ const style = (parts[2] || "decimal").toLowerCase();
134595
+ const stack = ctx.getStack(node, name);
134596
+ if (!stack.length) return "";
134597
+ const pieces = stack.map((v) => formatCounter(v, style));
134598
+ return pieces.join(sep);
134599
+ }
134600
+ });
134601
+ return unquoteDoubleStrings(out);
134602
+ } catch {
134603
+ return "- ";
134604
+ }
134605
+ }
134606
+
134607
+ // src/modules/pseudo.js
134608
+ var counterCtx = null;
134609
+ var __siblingCounters = /* @__PURE__ */ new WeakMap();
134610
+ function unquoteDoubleStrings2(s) {
134611
+ return (s || "").replace(/"([^"]*)"/g, "$1");
134612
+ }
134613
+ function collapseCssContent(raw) {
134614
+ if (!raw) return "";
134615
+ const tokens = [];
134616
+ const rx = /"([^"]*)"/g;
134617
+ let m;
134618
+ while (m = rx.exec(raw)) tokens.push(m[1]);
134619
+ if (tokens.length) return tokens.join("");
134620
+ return unquoteDoubleStrings2(raw);
134621
+ }
134622
+ function withSiblingOverrides(node, base) {
134623
+ const parent = node.parentElement;
134624
+ const map = parent ? __siblingCounters.get(parent) : null;
134625
+ if (!map) return base;
134626
+ return {
134627
+ get(n, name) {
134628
+ const v = base.get(n, name);
134629
+ const ov = map.get(name);
134630
+ return typeof ov === "number" ? Math.max(v, ov) : v;
134631
+ },
134632
+ getStack(n, name) {
134633
+ const s = base.getStack(n, name);
134634
+ if (!s.length) return s;
134635
+ const ov = map.get(name);
134636
+ if (typeof ov === "number") {
134637
+ const out = s.slice();
134638
+ out[out.length - 1] = Math.max(out[out.length - 1], ov);
134639
+ return out;
134640
+ }
134641
+ return s;
134642
+ }
134643
+ };
134644
+ }
134645
+ function deriveCounterCtxForPseudo(node, pseudoStyle, baseCtx) {
134646
+ const modStacks = /* @__PURE__ */ new Map();
134647
+ function parseListDecl(value) {
134648
+ const out = [];
134649
+ if (!value || value === "none") return out;
134650
+ for (const part of String(value).split(",")) {
134651
+ const toks = part.trim().split(/\s+/);
134652
+ const name = toks[0];
134653
+ const num = Number.isFinite(Number(toks[1])) ? Number(toks[1]) : void 0;
134654
+ if (name) out.push({ name, num });
134655
+ }
134656
+ return out;
134657
+ }
134658
+ const resets = parseListDecl(pseudoStyle?.counterReset);
134659
+ const incs = parseListDecl(pseudoStyle?.counterIncrement);
134660
+ function getStackDerived(name) {
134661
+ if (modStacks.has(name)) return modStacks.get(name).slice();
134662
+ let stack = baseCtx.getStack(node, name);
134663
+ stack = stack.length ? stack.slice() : [];
134664
+ const r = resets.find((x) => x.name === name);
134665
+ if (r) {
134666
+ const val = Number.isFinite(r.num) ? r.num : 0;
134667
+ stack = stack.length ? [...stack, val] : [val];
134668
+ }
134669
+ const inc = incs.find((x) => x.name === name);
134670
+ if (inc) {
134671
+ const by = Number.isFinite(inc.num) ? inc.num : 1;
134672
+ if (stack.length === 0) stack = [0];
134673
+ stack[stack.length - 1] += by;
134674
+ }
134675
+ modStacks.set(name, stack.slice());
134676
+ return stack;
134677
+ }
134678
+ return {
134679
+ get(_node, name) {
134680
+ const s = getStackDerived(name);
134681
+ return s.length ? s[s.length - 1] : 0;
134682
+ },
134683
+ getStack(_node, name) {
134684
+ return getStackDerived(name);
134685
+ },
134686
+ /** expone increments del pseudo para que el caller pueda propagar a hermanos */
134687
+ __incs: incs
134688
+ };
134689
+ }
134690
+ function resolvePseudoContentAndIncs(node, pseudo, baseCtx) {
134691
+ let ps;
134692
+ try {
134693
+ ps = getComputedStyle(node, pseudo);
134694
+ } catch {
134695
+ }
134696
+ const raw = ps?.content;
134697
+ if (!raw || raw === "none" || raw === "normal") return { text: "", incs: [] };
134698
+ const baseWithSiblings = withSiblingOverrides(node, baseCtx);
134699
+ const derived = deriveCounterCtxForPseudo(node, ps, baseWithSiblings);
134700
+ let resolved = hasCounters(raw) ? resolveCountersInContent(raw, node, derived) : raw;
134701
+ const text = collapseCssContent(resolved);
134702
+ return { text, incs: derived.__incs || [] };
134703
+ }
134704
+ async function inlinePseudoElements(source, clone, sessionCache, options) {
134705
+ if (!(source instanceof Element) || !(clone instanceof Element)) return;
134706
+ if (!counterCtx) {
134707
+ try {
134708
+ counterCtx = buildCounterContext(source.ownerDocument || document);
134709
+ } catch {
134710
+ }
134711
+ }
134712
+ for (const pseudo of ["::before", "::after", "::first-letter"]) {
134713
+ try {
134714
+ const style = getStyle(source, pseudo);
134715
+ if (!style || typeof style[Symbol.iterator] !== "function") continue;
134716
+ const isEmptyPseudo = style.content === "none" && style.backgroundImage === "none" && style.backgroundColor === "transparent" && (style.borderStyle === "none" || parseFloat(style.borderWidth) === 0) && (!style.transform || style.transform === "none") && style.display === "inline";
134717
+ if (isEmptyPseudo) continue;
134718
+ if (pseudo === "::first-letter") {
134719
+ const normal = getComputedStyle(source);
134720
+ const isMeaningful = style.color !== normal.color || style.fontSize !== normal.fontSize || style.fontWeight !== normal.fontWeight;
134721
+ if (!isMeaningful) continue;
134722
+ const textNode = Array.from(clone.childNodes).find(
134723
+ (n) => n.nodeType === Node.TEXT_NODE && n.textContent?.trim().length > 0
134724
+ );
134725
+ if (!textNode) continue;
134726
+ const text = textNode.textContent;
134727
+ const match = text.match(/^([^\p{L}\p{N}\s]*[\p{L}\p{N}](?:['’])?)/u);
134728
+ const first = match?.[0];
134729
+ const rest = text.slice(first?.length || 0);
134730
+ if (!first || /[\uD800-\uDFFF]/.test(first)) continue;
134731
+ const span = document.createElement("span");
134732
+ span.textContent = first;
134733
+ span.dataset.snapdomPseudo = "::first-letter";
134734
+ const snapshot2 = snapshotComputedStyle(style);
134735
+ const key2 = getStyleKey(snapshot2, "span");
134736
+ sessionCache.styleMap.set(span, key2);
134737
+ const restNode = document.createTextNode(rest);
134738
+ clone.replaceChild(restNode, textNode);
134739
+ clone.insertBefore(span, restNode);
134740
+ continue;
134741
+ }
134742
+ const rawContent = style.content;
134743
+ const { text: cleanContent, incs } = resolvePseudoContentAndIncs(source, pseudo, counterCtx);
134744
+ const bg = style.backgroundImage;
134745
+ const bgColor = style.backgroundColor;
134746
+ const fontFamily = style.fontFamily;
134747
+ const fontSize = parseInt(style.fontSize) || 32;
134748
+ const fontWeight = parseInt(style.fontWeight) || false;
134749
+ const color = style.color || "#000";
134750
+ const borderStyle = style.borderStyle;
134751
+ const borderWidth = parseFloat(style.borderWidth);
134752
+ const transform = style.transform;
134753
+ const isIconFont22 = isIconFont2(fontFamily);
134754
+ const hasExplicitContent = rawContent !== "none" && cleanContent !== "";
134755
+ const hasBg = bg && bg !== "none";
134756
+ const hasBgColor = bgColor && bgColor !== "transparent" && bgColor !== "rgba(0, 0, 0, 0)";
134757
+ const hasBorder = borderStyle && borderStyle !== "none" && borderWidth > 0;
134758
+ const hasTransform = transform && transform !== "none";
134759
+ const shouldRender = hasExplicitContent || hasBg || hasBgColor || hasBorder || hasTransform;
134760
+ if (!shouldRender) {
134761
+ if (incs && incs.length && source.parentElement) {
134762
+ const map = __siblingCounters.get(source.parentElement) || /* @__PURE__ */ new Map();
134763
+ for (const { name } of incs) {
134764
+ if (!name) continue;
134765
+ const baseWithSibs = withSiblingOverrides(source, counterCtx);
134766
+ const derived = deriveCounterCtxForPseudo(source, getComputedStyle(source, pseudo), baseWithSibs);
134767
+ const finalVal = derived.get(source, name);
134768
+ map.set(name, finalVal);
134769
+ }
134770
+ __siblingCounters.set(source.parentElement, map);
134771
+ }
134772
+ continue;
134773
+ }
134774
+ const pseudoEl = document.createElement("span");
134775
+ pseudoEl.dataset.snapdomPseudo = pseudo;
134776
+ pseudoEl.style.verticalAlign = "middle";
134777
+ pseudoEl.style.pointerEvents = "none";
134778
+ const snapshot = snapshotComputedStyle(style);
134779
+ const key = getStyleKey(snapshot, "span");
134780
+ sessionCache.styleMap.set(pseudoEl, key);
134781
+ if (isIconFont22 && cleanContent && cleanContent.length === 1) {
134782
+ const { dataUrl, width: w, height: h } = await iconToImage(cleanContent, fontFamily, fontWeight, fontSize, color);
134783
+ const imgEl = document.createElement("img");
134784
+ imgEl.src = dataUrl;
134785
+ imgEl.style = `height:${fontSize}px;width:${w / h * fontSize}px;object-fit:contain;`;
134786
+ pseudoEl.appendChild(imgEl);
134787
+ clone.dataset.snapdomHasIcon = "true";
134788
+ } else if (cleanContent && cleanContent.startsWith("url(")) {
134789
+ const rawUrl = extractURL(cleanContent);
134790
+ if (rawUrl?.trim()) {
134791
+ try {
134792
+ const imgEl = document.createElement("img");
134793
+ const dataUrl = await snapFetch(safeEncodeURI(rawUrl), { as: "dataURL", useProxy: options.useProxy });
134794
+ imgEl.src = dataUrl.data;
134795
+ imgEl.style = `width:${fontSize}px;height:auto;object-fit:contain;`;
134796
+ pseudoEl.appendChild(imgEl);
134797
+ } catch (e) {
134798
+ console.error(`[snapdom] Error in pseudo ${pseudo} for`, source, e);
134799
+ }
134800
+ }
134801
+ } else if (!isIconFont22 && hasExplicitContent) {
134802
+ pseudoEl.textContent = cleanContent;
134803
+ }
134804
+ pseudoEl.style.background = "none";
134805
+ if ("mask" in pseudoEl.style) {
134806
+ pseudoEl.style.mask = "none";
134807
+ }
134808
+ if (hasBg) {
134809
+ try {
134810
+ const bgSplits = splitBackgroundImage(bg);
134811
+ const newBgParts = await Promise.all(bgSplits.map(inlineSingleBackgroundEntry));
134812
+ pseudoEl.style.backgroundImage = newBgParts.join(", ");
134813
+ } catch (e) {
134814
+ console.warn(`[snapdom] Failed to inline background-image for ${pseudo}`, e);
134815
+ }
134816
+ }
134817
+ if (hasBgColor) pseudoEl.style.backgroundColor = bgColor;
134818
+ const hasContent2 = pseudoEl.childNodes.length > 0 || pseudoEl.textContent?.trim() !== "";
134819
+ const hasVisibleBox = hasContent2 || hasBg || hasBgColor || hasBorder || hasTransform;
134820
+ if (incs && incs.length && source.parentElement) {
134821
+ const map = __siblingCounters.get(source.parentElement) || /* @__PURE__ */ new Map();
134822
+ const baseWithSibs = withSiblingOverrides(source, counterCtx);
134823
+ const derived = deriveCounterCtxForPseudo(source, getComputedStyle(source, pseudo), baseWithSibs);
134824
+ for (const { name } of incs) {
134825
+ if (!name) continue;
134826
+ const finalVal = derived.get(source, name);
134827
+ map.set(name, finalVal);
134828
+ }
134829
+ __siblingCounters.set(source.parentElement, map);
134830
+ }
134831
+ if (!hasVisibleBox) continue;
134832
+ if (pseudo === "::before") {
134833
+ clone.insertBefore(pseudoEl, clone.firstChild);
134834
+ } else {
134835
+ clone.appendChild(pseudoEl);
134836
+ }
134837
+ } catch (e) {
134838
+ console.warn(`[snapdom] Failed to capture ${pseudo} for`, source, e);
134839
+ }
134840
+ }
134841
+ const sChildren = Array.from(source.children);
134842
+ const cChildren = Array.from(clone.children).filter((child) => !child.dataset.snapdomPseudo);
134843
+ for (let i = 0; i < Math.min(sChildren.length, cChildren.length); i++) {
134844
+ await inlinePseudoElements(sChildren[i], cChildren[i], sessionCache, options);
134845
+ }
134846
+ }
134847
+
134848
+ // src/modules/svgDefs.js
134849
+ function inlineExternalDefsAndSymbols(rootElement) {
134850
+ if (!rootElement) return;
134851
+ const usedIds = /* @__PURE__ */ new Set();
134852
+ rootElement.querySelectorAll("use").forEach((use) => {
134853
+ const href = use.getAttribute("xlink:href") || use.getAttribute("href");
134854
+ if (href && href.startsWith("#")) {
134855
+ usedIds.add(href.slice(1));
134856
+ }
134857
+ });
134858
+ if (!usedIds.size) return;
134859
+ const allGlobal = Array.from(document.querySelectorAll("svg > symbol, svg > defs"));
134860
+ const globalSymbols = allGlobal.filter((el) => el.tagName.toLowerCase() === "symbol");
134861
+ const globalDefs = allGlobal.filter((el) => el.tagName.toLowerCase() === "defs");
134862
+ let container = rootElement.querySelector("svg.inline-defs-container");
134863
+ if (!container) {
134864
+ container = document.createElementNS("http://www.w3.org/2000/svg", "svg");
134865
+ container.setAttribute("aria-hidden", "true");
134866
+ container.setAttribute("style", "position: absolute; width: 0; height: 0; overflow: hidden;");
134867
+ container.classList.add("inline-defs-container");
134868
+ rootElement.insertBefore(container, rootElement.firstChild);
134869
+ }
134870
+ const existingIds = /* @__PURE__ */ new Set();
134871
+ rootElement.querySelectorAll("symbol[id], defs > *[id]").forEach((el) => {
134872
+ existingIds.add(el.id);
134873
+ });
134874
+ usedIds.forEach((id) => {
134875
+ if (existingIds.has(id)) return;
134876
+ const symbol = globalSymbols.find((sym) => sym.id === id);
134877
+ if (symbol) {
134878
+ container.appendChild(symbol.cloneNode(true));
134879
+ existingIds.add(id);
134880
+ return;
134881
+ }
134882
+ for (const defs of globalDefs) {
134883
+ const defEl = defs.querySelector(`#${CSS.escape(id)}`);
134884
+ if (defEl) {
134885
+ let defsContainer = container.querySelector("defs");
134886
+ if (!defsContainer) {
134887
+ defsContainer = document.createElementNS("http://www.w3.org/2000/svg", "defs");
134888
+ container.appendChild(defsContainer);
134889
+ }
134890
+ defsContainer.appendChild(defEl.cloneNode(true));
134891
+ existingIds.add(id);
134892
+ break;
134893
+ }
134894
+ }
134895
+ });
134896
+ }
134897
+
134898
+ // src/modules/changeCSS.js
134899
+ function freezeSticky(originalRoot, cloneRoot) {
134900
+ if (!originalRoot || !cloneRoot) return;
134901
+ const scrollTop = originalRoot.scrollTop || 0;
134902
+ if (!scrollTop) return;
134903
+ if (getComputedStyle(cloneRoot).position === "static") {
134904
+ cloneRoot.style.position = "relative";
134905
+ }
134906
+ const rootRect = originalRoot.getBoundingClientRect();
134907
+ const viewportH = originalRoot.clientHeight;
134908
+ const PH_ATTR = "data-snap-ph";
134909
+ const walker = document.createTreeWalker(originalRoot, NodeFilter.SHOW_ELEMENT);
134910
+ while (walker.nextNode()) {
134911
+ const el = (
134912
+ /** @type {HTMLElement} */
134913
+ walker.currentNode
134914
+ );
134915
+ const cs = getComputedStyle(el);
134916
+ const pos = cs.position;
134917
+ if (pos !== "sticky" && pos !== "-webkit-sticky") continue;
134918
+ const topInit = _toPx(cs.top);
134919
+ const bottomInit = _toPx(cs.bottom);
134920
+ if (topInit == null && bottomInit == null) continue;
134921
+ const path = _pathOf(el, originalRoot);
134922
+ const cloneEl = _findByPathIgnoringPlaceholders(cloneRoot, path, PH_ATTR);
134923
+ if (!cloneEl) continue;
134924
+ const elRect = el.getBoundingClientRect();
134925
+ const widthPx = elRect.width;
134926
+ const heightPx = elRect.height;
134927
+ const leftPx = elRect.left - rootRect.left;
134928
+ if (!(widthPx > 0 && heightPx > 0)) continue;
134929
+ if (!Number.isFinite(leftPx)) continue;
134930
+ const topAbsPx = topInit != null ? topInit + scrollTop : scrollTop + (viewportH - heightPx - /** bottomInit non-null */
134931
+ bottomInit);
134932
+ if (!Number.isFinite(topAbsPx)) continue;
134933
+ const zParsed = Number.parseInt(cs.zIndex, 10);
134934
+ const hasZ = Number.isFinite(zParsed);
134935
+ const overlayZ = hasZ ? Math.max(zParsed, 1) + 1 : 2;
134936
+ const placeholderZ = hasZ ? zParsed - 1 : 0;
134937
+ const ph = cloneEl.cloneNode(false);
134938
+ ph.setAttribute(PH_ATTR, "1");
134939
+ ph.style.position = "sticky";
134940
+ ph.style.left = `${leftPx}px`;
134941
+ ph.style.top = `${topAbsPx}px`;
134942
+ ph.style.width = `${widthPx}px`;
134943
+ ph.style.height = `${heightPx}px`;
134944
+ ph.style.visibility = "hidden";
134945
+ ph.style.zIndex = String(placeholderZ);
134946
+ ph.style.overflow = "hidden";
134947
+ ph.style.background = "transparent";
134948
+ ph.style.boxShadow = "none";
134949
+ ph.style.filter = "none";
134950
+ cloneEl.parentElement?.insertBefore(ph, cloneEl);
134951
+ cloneEl.style.position = "absolute";
134952
+ cloneEl.style.left = `${leftPx}px`;
134953
+ cloneEl.style.top = `${topAbsPx}px`;
134954
+ cloneEl.style.bottom = "auto";
134955
+ cloneEl.style.zIndex = String(overlayZ);
134956
+ cloneEl.style.pointerEvents = "none";
134957
+ }
134958
+ }
134959
+ function _toPx(v) {
134960
+ if (!v || v === "auto") return null;
134961
+ const n = Number.parseFloat(v);
134962
+ return Number.isFinite(n) ? n : null;
134963
+ }
134964
+ function _pathOf(el, root) {
134965
+ const path = [];
134966
+ for (let cur = el; cur && cur !== root; ) {
134967
+ const p = cur.parentElement;
134968
+ if (!p) break;
134969
+ path.push(Array.prototype.indexOf.call(p.children, cur));
134970
+ cur = p;
134971
+ }
134972
+ return path.reverse();
134973
+ }
134974
+ function _findByPathIgnoringPlaceholders(root, path, phAttr) {
134975
+ let cur = root;
134976
+ for (let i = 0; i < path.length; i++) {
134977
+ const kids = _childrenWithoutPlaceholders(cur, phAttr);
134978
+ cur = /** @type {HTMLElement|undefined} */
134979
+ kids[path[i]];
134980
+ if (!cur) return null;
134981
+ }
134982
+ return cur instanceof HTMLElement ? cur : null;
134983
+ }
134984
+ function _childrenWithoutPlaceholders(el, phAttr) {
134985
+ const out = [];
134986
+ const ch = el.children;
134987
+ for (let i = 0; i < ch.length; i++) {
134988
+ const c = ch[i];
134989
+ if (!c.hasAttribute(phAttr)) out.push(c);
134990
+ }
134991
+ return out;
134992
+ }
134993
+
134994
+ // src/core/prepare.js
134995
+ async function prepareClone(element, options = {}) {
134996
+ const sessionCache = {
134997
+ styleMap: cache.session.styleMap,
134998
+ styleCache: cache.session.styleCache,
134999
+ nodeMap: cache.session.nodeMap
135000
+ };
135001
+ let clone;
135002
+ let classCSS = "";
135003
+ let shadowScopedCSS = "";
135004
+ stabilizeLayout(element);
135005
+ try {
135006
+ inlineExternalDefsAndSymbols(element);
135007
+ } catch (e) {
135008
+ console.warn("inlineExternal defs or symbol failed:", e);
135009
+ }
135010
+ try {
135011
+ clone = await deepClone(element, sessionCache, options, element);
135012
+ } catch (e) {
135013
+ console.warn("deepClone failed:", e);
135014
+ throw e;
135015
+ }
135016
+ try {
135017
+ await inlinePseudoElements(element, clone, sessionCache, options);
135018
+ } catch (e) {
135019
+ console.warn("inlinePseudoElements failed:", e);
135020
+ }
135021
+ await resolveBlobUrlsInTree(clone);
135022
+ try {
135023
+ const styleNodes = clone.querySelectorAll("style[data-sd]");
135024
+ for (const s of styleNodes) {
135025
+ shadowScopedCSS += s.textContent || "";
135026
+ s.remove();
135027
+ }
135028
+ } catch {
135029
+ }
135030
+ const keyToClass = generateCSSClasses(sessionCache.styleMap);
135031
+ classCSS = Array.from(keyToClass.entries()).map(([key, className]) => `.${className}{${key}}`).join("");
135032
+ classCSS = shadowScopedCSS + classCSS;
135033
+ for (const [node, key] of sessionCache.styleMap.entries()) {
135034
+ if (node.tagName === "STYLE") continue;
135035
+ if (node.getRootNode && node.getRootNode() instanceof ShadowRoot) {
135036
+ node.setAttribute("style", key.replace(/;/g, "; "));
135037
+ continue;
135038
+ }
135039
+ const className = keyToClass.get(key);
135040
+ if (className) node.classList.add(className);
135041
+ const bgImage = node.style?.backgroundImage;
135042
+ const hasIcon = node.dataset?.snapdomHasIcon;
135043
+ if (bgImage && bgImage !== "none") node.style.backgroundImage = bgImage;
135044
+ if (hasIcon) {
135045
+ node.style.verticalAlign = "middle";
135046
+ node.style.display = "inline";
135047
+ }
135048
+ }
135049
+ for (const [cloneNode, originalNode] of sessionCache.nodeMap.entries()) {
135050
+ const scrollX = originalNode.scrollLeft;
135051
+ const scrollY = originalNode.scrollTop;
135052
+ const hasScroll = scrollX || scrollY;
135053
+ if (hasScroll && cloneNode instanceof HTMLElement) {
135054
+ cloneNode.style.overflow = "hidden";
135055
+ cloneNode.style.scrollbarWidth = "none";
135056
+ cloneNode.style.msOverflowStyle = "none";
135057
+ const inner = document.createElement("div");
135058
+ inner.style.transform = `translate(${-scrollX}px, ${-scrollY}px)`;
135059
+ inner.style.willChange = "transform";
135060
+ inner.style.display = "inline-block";
135061
+ inner.style.width = "100%";
135062
+ while (cloneNode.firstChild) {
135063
+ inner.appendChild(cloneNode.firstChild);
135064
+ }
135065
+ cloneNode.appendChild(inner);
135066
+ }
135067
+ }
135068
+ const contentRoot = clone instanceof HTMLElement && clone.firstElementChild instanceof HTMLElement ? clone.firstElementChild : clone;
135069
+ freezeSticky(element, contentRoot);
135070
+ if (element === sessionCache.nodeMap.get(clone)) {
135071
+ const computed = sessionCache.styleCache.get(element) || window.getComputedStyle(element);
135072
+ sessionCache.styleCache.set(element, computed);
135073
+ const transform = stripTranslate(computed.transform);
135074
+ clone.style.margin = "0";
135075
+ clone.style.top = "auto";
135076
+ clone.style.left = "auto";
135077
+ clone.style.right = "auto";
135078
+ clone.style.bottom = "auto";
135079
+ clone.style.animation = "none";
135080
+ clone.style.transition = "none";
135081
+ clone.style.willChange = "auto";
135082
+ clone.style.float = "none";
135083
+ clone.style.clear = "none";
135084
+ clone.style.transform = transform || "";
135085
+ }
135086
+ for (const [cloneNode, originalNode] of sessionCache.nodeMap.entries()) {
135087
+ if (originalNode.tagName === "PRE") {
135088
+ cloneNode.style.marginTop = "0";
135089
+ cloneNode.style.marginBlockStart = "0";
135090
+ }
135091
+ }
135092
+ return { clone, classCSS, styleCache: sessionCache.styleCache };
135093
+ }
135094
+ function stabilizeLayout(element) {
135095
+ const style = getComputedStyle(element);
135096
+ const outlineStyle = style.outlineStyle;
135097
+ const outlineWidth = style.outlineWidth;
135098
+ const borderStyle = style.borderStyle;
135099
+ const borderWidth = style.borderWidth;
135100
+ const outlineVisible = outlineStyle !== "none" && parseFloat(outlineWidth) > 0;
135101
+ const borderAbsent = borderStyle === "none" || parseFloat(borderWidth) === 0;
135102
+ if (outlineVisible && borderAbsent) {
135103
+ element.style.border = `${outlineWidth} solid transparent`;
135104
+ }
135105
+ }
135106
+ var _blobToDataUrlCache = /* @__PURE__ */ new Map();
135107
+ async function blobUrlToDataUrl(blobUrl) {
135108
+ if (cache.resource?.has(blobUrl)) return cache.resource.get(blobUrl);
135109
+ if (_blobToDataUrlCache.has(blobUrl)) return _blobToDataUrlCache.get(blobUrl);
135110
+ const p = (async () => {
135111
+ const r = await snapFetch(blobUrl, { as: "dataURL", silent: true });
135112
+ if (!r.ok || typeof r.data !== "string") {
135113
+ throw new Error(`[snapDOM] Failed to read blob URL: ${blobUrl}`);
135114
+ }
135115
+ cache.resource?.set(blobUrl, r.data);
135116
+ return r.data;
135117
+ })();
135118
+ _blobToDataUrlCache.set(blobUrl, p);
135119
+ try {
135120
+ const data = await p;
135121
+ _blobToDataUrlCache.set(blobUrl, data);
135122
+ return data;
135123
+ } catch (e) {
135124
+ _blobToDataUrlCache.delete(blobUrl);
135125
+ throw e;
135126
+ }
135127
+ }
135128
+ var BLOB_URL_RE = /\bblob:[^)"'\s]+/g;
135129
+ async function replaceBlobUrlsInCssText(cssText) {
135130
+ if (!cssText || cssText.indexOf("blob:") === -1) return cssText;
135131
+ const uniques = Array.from(new Set(cssText.match(BLOB_URL_RE) || []));
135132
+ if (uniques.length === 0) return cssText;
135133
+ let out = cssText;
135134
+ for (const u of uniques) {
135135
+ try {
135136
+ const d = await blobUrlToDataUrl(u);
135137
+ out = out.split(u).join(d);
135138
+ } catch {
135139
+ }
135140
+ }
135141
+ return out;
135142
+ }
135143
+ function isBlobUrl(u) {
135144
+ return typeof u === "string" && u.startsWith("blob:");
135145
+ }
135146
+ function parseSrcset(srcset) {
135147
+ return (srcset || "").split(",").map((s) => s.trim()).filter(Boolean).map((item) => {
135148
+ const m = item.match(/^(\S+)(\s+.+)?$/);
135149
+ return m ? { url: m[1], desc: m[2] || "" } : null;
135150
+ }).filter(Boolean);
135151
+ }
135152
+ function stringifySrcset(parts) {
135153
+ return parts.map((p) => p.desc ? `${p.url} ${p.desc.trim()}` : p.url).join(", ");
135154
+ }
135155
+ async function resolveBlobUrlsInTree(root) {
135156
+ if (!root) return;
135157
+ const imgs = root.querySelectorAll ? root.querySelectorAll("img") : [];
135158
+ for (const img of imgs) {
135159
+ try {
135160
+ const srcAttr = img.getAttribute("src");
135161
+ const effective = srcAttr || img.currentSrc || "";
135162
+ if (isBlobUrl(effective)) {
135163
+ const data = await blobUrlToDataUrl(effective);
135164
+ img.setAttribute("src", data);
135165
+ }
135166
+ const srcset = img.getAttribute("srcset");
135167
+ if (srcset && srcset.includes("blob:")) {
135168
+ const parts = parseSrcset(srcset);
135169
+ let changed = false;
135170
+ for (const p of parts) {
135171
+ if (isBlobUrl(p.url)) {
135172
+ try {
135173
+ p.url = await blobUrlToDataUrl(p.url);
135174
+ changed = true;
135175
+ } catch {
135176
+ }
135177
+ }
135178
+ }
135179
+ if (changed) img.setAttribute("srcset", stringifySrcset(parts));
135180
+ }
135181
+ } catch {
135182
+ }
135183
+ }
135184
+ const svgImages = root.querySelectorAll ? root.querySelectorAll("image") : [];
135185
+ for (const node of svgImages) {
135186
+ try {
135187
+ const XLINK_NS = "http://www.w3.org/1999/xlink";
135188
+ const href = node.getAttribute("href") || node.getAttributeNS?.(XLINK_NS, "href");
135189
+ if (isBlobUrl(href)) {
135190
+ const d = await blobUrlToDataUrl(href);
135191
+ node.setAttribute("href", d);
135192
+ node.removeAttributeNS?.(XLINK_NS, "href");
135193
+ }
135194
+ } catch {
135195
+ }
135196
+ }
135197
+ const styled = root.querySelectorAll ? root.querySelectorAll("[style*='blob:']") : [];
135198
+ for (const el of styled) {
135199
+ try {
135200
+ const styleText = el.getAttribute("style");
135201
+ if (styleText && styleText.includes("blob:")) {
135202
+ const replaced = await replaceBlobUrlsInCssText(styleText);
135203
+ el.setAttribute("style", replaced);
135204
+ }
135205
+ } catch {
135206
+ }
135207
+ }
135208
+ const styleTags = root.querySelectorAll ? root.querySelectorAll("style") : [];
135209
+ for (const s of styleTags) {
135210
+ try {
135211
+ const css = s.textContent || "";
135212
+ if (css.includes("blob:")) {
135213
+ s.textContent = await replaceBlobUrlsInCssText(css);
135214
+ }
135215
+ } catch {
135216
+ }
135217
+ }
135218
+ const urlAttrs = ["poster"];
135219
+ for (const attr of urlAttrs) {
135220
+ const nodes = root.querySelectorAll ? root.querySelectorAll(`[${attr}^='blob:']`) : [];
135221
+ for (const n of nodes) {
135222
+ try {
135223
+ const u = n.getAttribute(attr);
135224
+ if (isBlobUrl(u)) {
135225
+ n.setAttribute(attr, await blobUrlToDataUrl(u));
135226
+ }
135227
+ } catch {
135228
+ }
135229
+ }
135230
+ }
135231
+ }
135232
+
135233
+ // src/modules/images.js
135234
+ async function inlineImages(clone, options = {}) {
135235
+ const imgs = Array.from(clone.querySelectorAll("img"));
135236
+ const processImg = async (img) => {
135237
+ if (!img.getAttribute("src")) {
135238
+ const eff = img.currentSrc || img.src || "";
135239
+ if (eff) img.setAttribute("src", eff);
135240
+ }
135241
+ img.removeAttribute("srcset");
135242
+ img.removeAttribute("sizes");
135243
+ const src = img.src || "";
135244
+ if (!src) return;
135245
+ const r = await snapFetch(src, { as: "dataURL", useProxy: options.useProxy });
135246
+ if (r.ok && typeof r.data === "string" && r.data.startsWith("data:")) {
135247
+ img.src = r.data;
135248
+ if (!img.width) img.width = img.naturalWidth || 100;
135249
+ if (!img.height) img.height = img.naturalHeight || 100;
135250
+ return;
135251
+ }
135252
+ const { fallbackURL } = options || {};
135253
+ if (fallbackURL) {
135254
+ try {
135255
+ const dsW = parseInt(img.dataset?.snapdomWidth || "", 10) || 0;
135256
+ const dsH = parseInt(img.dataset?.snapdomHeight || "", 10) || 0;
135257
+ const attrW = parseInt(img.getAttribute("width") || "", 10) || 0;
135258
+ const attrH = parseInt(img.getAttribute("height") || "", 10) || 0;
135259
+ const styleW = parseFloat(img.style?.width || "") || 0;
135260
+ const styleH = parseFloat(img.style?.height || "") || 0;
135261
+ const fbW = dsW || styleW || attrW || img.width || void 0;
135262
+ const fbH = dsH || styleH || attrH || img.height || void 0;
135263
+ const fallbackUrl = typeof fallbackURL === "function" ? await fallbackURL({ width: fbW, height: fbH, src, element: img }) : fallbackURL;
135264
+ if (fallbackUrl) {
135265
+ const fallbackData = await snapFetch(fallbackUrl, { as: "dataURL", useProxy: options.useProxy });
135266
+ img.src = fallbackData.data;
135267
+ if (!img.width && fbW) img.width = fbW;
135268
+ if (!img.height && fbH) img.height = fbH;
135269
+ if (!img.width) img.width = img.naturalWidth || 100;
135270
+ if (!img.height) img.height = img.naturalHeight || 100;
135271
+ return;
135272
+ }
135273
+ } catch {
135274
+ }
135275
+ }
135276
+ const w = img.width || img.naturalWidth || 100;
135277
+ const h = img.height || img.naturalHeight || 100;
135278
+ if (options.placeholders !== false) {
135279
+ const fallback = document.createElement("div");
135280
+ fallback.style.cssText = [
135281
+ `width:${w}px`,
135282
+ `height:${h}px`,
135283
+ "background:#ccc",
135284
+ "display:inline-block",
135285
+ "text-align:center",
135286
+ `line-height:${h}px`,
135287
+ "color:#666",
135288
+ "font-size:12px",
135289
+ "overflow:hidden"
135290
+ ].join(";");
135291
+ fallback.textContent = "img";
135292
+ img.replaceWith(fallback);
135293
+ } else {
135294
+ const spacer = document.createElement("div");
135295
+ spacer.style.cssText = `display:inline-block;width:${w}px;height:${h}px;visibility:hidden;`;
135296
+ img.replaceWith(spacer);
135297
+ }
135298
+ };
135299
+ for (let i = 0; i < imgs.length; i += 4) {
135300
+ const group = imgs.slice(i, i + 4).map(processImg);
135301
+ await Promise.allSettled(group);
135302
+ }
135303
+ }
135304
+
135305
+ // src/modules/background.js
135306
+ async function inlineBackgroundImages(source, clone, styleCache, options = {}) {
135307
+ const queue = [[source, clone]];
135308
+ const URL_PROPS = [
135309
+ "background-image",
135310
+ // Mask shorthands & images (both standard and WebKit)
135311
+ "mask",
135312
+ "mask-image",
135313
+ "-webkit-mask",
135314
+ "-webkit-mask-image",
135315
+ // Mask sources (rare, but keep)
135316
+ "mask-source",
135317
+ "mask-box-image-source",
135318
+ "mask-border-source",
135319
+ "-webkit-mask-box-image-source",
135320
+ // Border image
135321
+ "border-image",
135322
+ "border-image-source"
135323
+ ];
135324
+ const MASK_LAYOUT_PROPS = [
135325
+ "mask-position",
135326
+ "mask-size",
135327
+ "mask-repeat",
135328
+ // WebKit variants
135329
+ "-webkit-mask-position",
135330
+ "-webkit-mask-size",
135331
+ "-webkit-mask-repeat",
135332
+ // Extra (optional but helpful across engines)
135333
+ "mask-origin",
135334
+ "mask-clip",
135335
+ "-webkit-mask-origin",
135336
+ "-webkit-mask-clip",
135337
+ // Some engines expose X/Y position separately:
135338
+ "-webkit-mask-position-x",
135339
+ "-webkit-mask-position-y"
135340
+ ];
135341
+ const BORDER_AUX_PROPS = [
135342
+ "border-image-slice",
135343
+ "border-image-width",
135344
+ "border-image-outset",
135345
+ "border-image-repeat"
135346
+ ];
135347
+ while (queue.length) {
135348
+ const [srcNode, cloneNode] = queue.shift();
135349
+ const style = styleCache.get(srcNode) || getStyle(srcNode);
135350
+ if (!styleCache.has(srcNode)) styleCache.set(srcNode, style);
135351
+ const hasBorderImage = (() => {
135352
+ const bi = style.getPropertyValue("border-image");
135353
+ const bis = style.getPropertyValue("border-image-source");
135354
+ return bi && bi !== "none" || bis && bis !== "none";
135355
+ })();
135356
+ for (const prop of URL_PROPS) {
135357
+ const val = style.getPropertyValue(prop);
135358
+ if (!val || val === "none") continue;
135359
+ const splits = splitBackgroundImage(val);
135360
+ const inlined = await Promise.all(
135361
+ splits.map((entry) => inlineSingleBackgroundEntry(entry, options))
135362
+ );
135363
+ if (inlined.some((p) => p && p !== "none" && !/^url\(undefined/.test(p))) {
135364
+ cloneNode.style.setProperty(prop, inlined.join(", "));
135365
+ }
135366
+ }
135367
+ for (const prop of MASK_LAYOUT_PROPS) {
135368
+ const val = style.getPropertyValue(prop);
135369
+ if (!val || val === "initial") continue;
135370
+ cloneNode.style.setProperty(prop, val);
135371
+ }
135372
+ if (hasBorderImage) {
135373
+ for (const prop of BORDER_AUX_PROPS) {
135374
+ const val = style.getPropertyValue(prop);
135375
+ if (!val || val === "initial") continue;
135376
+ cloneNode.style.setProperty(prop, val);
135377
+ }
135378
+ }
135379
+ const sChildren = Array.from(srcNode.children);
135380
+ const cChildren = Array.from(cloneNode.children);
135381
+ for (let i = 0; i < Math.min(sChildren.length, cChildren.length); i++) {
135382
+ queue.push([sChildren[i], cChildren[i]]);
135383
+ }
135384
+ }
135385
+ }
135386
+
135387
+ // src/modules/lineClamp.js
135388
+ function lineClamp(el) {
135389
+ if (!el) return () => {
135390
+ };
135391
+ const lines = getClamp(el);
135392
+ if (lines <= 0) return () => {
135393
+ };
135394
+ if (!isPlainTextContainer(el)) return () => {
135395
+ };
135396
+ const cs = getComputedStyle(el);
135397
+ const targetH = Math.round(usedLineHeightPx(cs) * lines + vpad(cs));
135398
+ const original = el.textContent ?? "";
135399
+ const prevText = original;
135400
+ if (el.scrollHeight <= targetH + 0.5) {
135401
+ return () => {
135402
+ };
135403
+ }
135404
+ let lo = 0, hi = original.length, best = -1;
135405
+ while (lo <= hi) {
135406
+ const mid = lo + hi >> 1;
135407
+ el.textContent = original.slice(0, mid) + "\u2026";
135408
+ if (el.scrollHeight <= targetH + 0.5) {
135409
+ best = mid;
135410
+ lo = mid + 1;
135411
+ } else {
135412
+ hi = mid - 1;
135413
+ }
135414
+ }
135415
+ el.textContent = (best >= 0 ? original.slice(0, best) : "") + "\u2026";
135416
+ return () => {
135417
+ el.textContent = prevText;
135418
+ };
135419
+ }
135420
+ function getClamp(el) {
135421
+ const cs = getComputedStyle(el);
135422
+ let v = cs.getPropertyValue("-webkit-line-clamp") || cs.getPropertyValue("line-clamp");
135423
+ v = (v || "").trim();
135424
+ const n = parseInt(v, 10);
135425
+ return Number.isFinite(n) && n > 0 ? n : 0;
135426
+ }
135427
+ function usedLineHeightPx(cs) {
135428
+ const lh = (cs.lineHeight || "").trim();
135429
+ const fs = parseFloat(cs.fontSize) || 16;
135430
+ if (!lh || lh === "normal") return Math.round(fs * 1.2);
135431
+ if (lh.endsWith("px")) return parseFloat(lh);
135432
+ if (/^\d+(\.\d+)?$/.test(lh)) return Math.round(parseFloat(lh) * fs);
135433
+ if (lh.endsWith("%")) return Math.round(parseFloat(lh) / 100 * fs);
135434
+ return Math.round(fs * 1.2);
135435
+ }
135436
+ function vpad(cs) {
135437
+ return (parseFloat(cs.paddingTop) || 0) + (parseFloat(cs.paddingBottom) || 0);
135438
+ }
135439
+ function isPlainTextContainer(el) {
135440
+ if (el.childElementCount > 0) return false;
135441
+ return Array.from(el.childNodes).some((n) => n.nodeType === Node.TEXT_NODE);
135442
+ }
135443
+
135444
+ // src/core/capture.js
135445
+ function stripRootShadows(originalEl, cloneRoot) {
135446
+ if (!originalEl || !cloneRoot || !cloneRoot.style) return;
135447
+ const cs = getComputedStyle(originalEl);
135448
+ try {
135449
+ cloneRoot.style.boxShadow = "none";
135450
+ } catch {
135451
+ }
135452
+ try {
135453
+ cloneRoot.style.textShadow = "none";
135454
+ } catch {
135455
+ }
135456
+ try {
135457
+ cloneRoot.style.outline = "none";
135458
+ } catch {
135459
+ }
135460
+ const f = cs.filter || "";
135461
+ const cleaned = f.replace(/\bblur\([^()]*\)\s*/gi, "").replace(/\bdrop-shadow\([^()]*\)\s*/gi, "").trim().replace(/\s+/g, " ");
135462
+ try {
135463
+ cloneRoot.style.filter = cleaned.length ? cleaned : "none";
135464
+ } catch {
135465
+ }
135466
+ }
135467
+ async function captureDOM(element, options) {
135468
+ if (!element) throw new Error("Element cannot be null or undefined");
135469
+ applyCachePolicy(options.cache);
135470
+ const fast = options.fast;
135471
+ const straighten = !!options.straighten;
135472
+ const noShadows = !!options.noShadows;
135473
+ let clone, classCSS, styleCache;
135474
+ let fontsCSS = "";
135475
+ let baseCSS = "";
135476
+ let dataURL;
135477
+ let svgString;
135478
+ let rootTransform2D = null;
135479
+ const undoClamp = lineClamp(element);
135480
+ try {
135481
+ ({ clone, classCSS, styleCache } = await prepareClone(element, options));
135482
+ if (straighten && clone) {
135483
+ rootTransform2D = normalizeRootTransforms(element, clone);
135484
+ }
135485
+ if (noShadows && clone) {
135486
+ stripRootShadows(element, clone);
135487
+ }
135488
+ } finally {
135489
+ undoClamp();
135490
+ }
135491
+ await new Promise((resolve) => {
135492
+ idle(async () => {
135493
+ await inlineImages(clone, options);
135494
+ resolve();
135495
+ }, { fast });
135496
+ });
135497
+ await new Promise((resolve) => {
135498
+ idle(async () => {
135499
+ await inlineBackgroundImages(element, clone, styleCache, options);
135500
+ resolve();
135501
+ }, { fast });
135502
+ });
135503
+ if (options.embedFonts) {
135504
+ await new Promise((resolve) => {
135505
+ idle(async () => {
135506
+ const required = collectUsedFontVariants(element);
135507
+ const usedCodepoints = collectUsedCodepoints(element);
135508
+ if (isSafari()) {
135509
+ const families = new Set(
135510
+ Array.from(required).map((k) => String(k).split("__")[0]).filter(Boolean)
135511
+ );
135512
+ await ensureFontsReady(families, 1);
135513
+ }
135514
+ fontsCSS = await embedCustomFonts({
135515
+ required,
135516
+ usedCodepoints,
135517
+ exclude: options.excludeFonts,
135518
+ useProxy: options.useProxy
135519
+ });
135520
+ resolve();
135521
+ }, { fast });
135522
+ });
135523
+ }
135524
+ const usedTags = collectUsedTagNames(clone).sort();
135525
+ const tagKey = usedTags.join(",");
135526
+ if (cache.baseStyle.has(tagKey)) {
135527
+ baseCSS = cache.baseStyle.get(tagKey);
135528
+ } else {
135529
+ await new Promise((resolve) => {
135530
+ idle(() => {
135531
+ baseCSS = generateDedupedBaseCSS(usedTags);
135532
+ cache.baseStyle.set(tagKey, baseCSS);
135533
+ resolve();
135534
+ }, { fast });
135535
+ });
135536
+ }
135537
+ await new Promise((resolve) => {
135538
+ idle(() => {
135539
+ const csEl = getComputedStyle(element);
135540
+ function parseFilterDropShadows(cs) {
135541
+ const raw = `${cs.filter || ""} ${cs.webkitFilter || ""}`.trim();
135542
+ if (!raw || raw === "none") {
135543
+ return { bleed: { top: 0, right: 0, bottom: 0, left: 0 }, has: false };
135544
+ }
135545
+ const tokens = raw.match(/drop-shadow\((?:[^()]|\([^()]*\))*\)/gi) || [];
135546
+ let t = 0, r = 0, b = 0, l = 0;
135547
+ let found = false;
135548
+ for (const tok of tokens) {
135549
+ found = true;
135550
+ const nums = tok.match(/-?\d+(?:\.\d+)?px/gi)?.map((v) => parseFloat(v)) || [];
135551
+ const [ox = 0, oy = 0, blur = 0] = nums;
135552
+ const extX = Math.abs(ox) + blur;
135553
+ const extY = Math.abs(oy) + blur;
135554
+ r = Math.max(r, extX + Math.max(ox, 0));
135555
+ l = Math.max(l, extX + Math.max(-ox, 0));
135556
+ b = Math.max(b, extY + Math.max(oy, 0));
135557
+ t = Math.max(t, extY + Math.max(-oy, 0));
135558
+ }
135559
+ return { bleed: { top: Math.ceil(t), right: Math.ceil(r), bottom: Math.ceil(b), left: Math.ceil(l) }, has: found };
135560
+ }
135561
+ const rect = element.getBoundingClientRect();
135562
+ const w0 = Math.max(1, Math.ceil(element.offsetWidth || parseFloat(csEl.width) || rect.width || 1));
135563
+ const h0 = Math.max(1, Math.ceil(element.offsetHeight || parseFloat(csEl.height) || rect.height || 1));
135564
+ const coerceNum = (v, def = NaN) => {
135565
+ const n = typeof v === "string" ? parseFloat(v) : v;
135566
+ return Number.isFinite(n) ? n : def;
135567
+ };
135568
+ const optW = coerceNum(options.width);
135569
+ const optH = coerceNum(options.height);
135570
+ let w = w0, h = h0;
135571
+ const hasW = Number.isFinite(optW);
135572
+ const hasH = Number.isFinite(optH);
135573
+ const aspect0 = h0 > 0 ? w0 / h0 : 1;
135574
+ if (hasW && hasH) {
135575
+ w = Math.max(1, Math.ceil(optW));
135576
+ h = Math.max(1, Math.ceil(optH));
135577
+ } else if (hasW) {
135578
+ w = Math.max(1, Math.ceil(optW));
135579
+ h = Math.max(1, Math.ceil(w / (aspect0 || 1)));
135580
+ } else if (hasH) {
135581
+ h = Math.max(1, Math.ceil(optH));
135582
+ w = Math.max(1, Math.ceil(h * (aspect0 || 1)));
135583
+ } else {
135584
+ w = w0;
135585
+ h = h0;
135586
+ }
135587
+ let minX = 0, minY = 0, maxX = w0, maxY = h0;
135588
+ if (straighten && rootTransform2D && Number.isFinite(rootTransform2D.a)) {
135589
+ const M2 = { a: rootTransform2D.a, b: rootTransform2D.b || 0, c: rootTransform2D.c || 0, d: rootTransform2D.d || 1, e: 0, f: 0 };
135590
+ const bb2 = bboxWithOriginFull(w0, h0, M2, 0, 0);
135591
+ minX = bb2.minX;
135592
+ minY = bb2.minY;
135593
+ maxX = bb2.maxX;
135594
+ maxY = bb2.maxY;
135595
+ } else {
135596
+ const useTFBBox = !straighten && hasTFBBox(element);
135597
+ if (useTFBBox) {
135598
+ const baseTransform2 = csEl.transform && csEl.transform !== "none" ? csEl.transform : "";
135599
+ const ind2 = readIndividualTransforms(element);
135600
+ const TOTAL = readTotalTransformMatrix({
135601
+ baseTransform: baseTransform2,
135602
+ rotate: ind2.rotate || "0deg",
135603
+ scale: ind2.scale,
135604
+ translate: ind2.translate
135605
+ });
135606
+ const { ox: ox2, oy: oy2 } = parseTransformOriginPx(csEl, w0, h0);
135607
+ const M = TOTAL.is2D ? TOTAL : new DOMMatrix(TOTAL.toString());
135608
+ const bb = bboxWithOriginFull(w0, h0, M, ox2, oy2);
135609
+ minX = bb.minX;
135610
+ minY = bb.minY;
135611
+ maxX = bb.maxX;
135612
+ maxY = bb.maxY;
135613
+ }
135614
+ }
135615
+ const bleedShadow = parseBoxShadow(csEl);
135616
+ const bleedBlur = parseFilterBlur(csEl);
135617
+ const bleedOutline = parseOutline(csEl);
135618
+ const drop = parseFilterDropShadows(csEl);
135619
+ const bleed = noShadows ? { top: 0, right: 0, bottom: 0, left: 0 } : {
135620
+ top: bleedShadow.top + bleedBlur.top + bleedOutline.top + drop.bleed.top,
135621
+ right: bleedShadow.right + bleedBlur.right + bleedOutline.right + drop.bleed.right,
135622
+ bottom: bleedShadow.bottom + bleedBlur.bottom + bleedOutline.bottom + drop.bleed.bottom,
135623
+ left: bleedShadow.left + bleedBlur.left + bleedOutline.left + drop.bleed.left
135624
+ };
135625
+ minX -= bleed.left;
135626
+ minY -= bleed.top;
135627
+ maxX += bleed.right;
135628
+ maxY += bleed.bottom;
135629
+ const vbW0 = Math.max(1, Math.ceil(maxX - minX));
135630
+ const vbH0 = Math.max(1, Math.ceil(maxY - minY));
135631
+ const outW = Math.max(1, Math.round(vbW0 * (hasW || hasH ? w / w0 : 1)));
135632
+ const outH = Math.max(1, Math.round(vbH0 * (hasH || hasW ? h / h0 : 1)));
135633
+ const svgNS = "http://www.w3.org/2000/svg";
135634
+ const basePad = isSafari() ? 1 : 0;
135635
+ const extraPad = straighten ? 1 : 0;
135636
+ const pad = basePad + extraPad;
135637
+ const fo = document.createElementNS(svgNS, "foreignObject");
135638
+ const vbMinX = Math.floor(minX);
135639
+ const vbMinY = Math.floor(minY);
135640
+ fo.setAttribute("x", String(-(vbMinX - pad)));
135641
+ fo.setAttribute("y", String(-(vbMinY - pad)));
135642
+ fo.setAttribute("width", String(Math.ceil(w0 + pad * 2)));
135643
+ fo.setAttribute("height", String(Math.ceil(h0 + pad * 2)));
135644
+ fo.style.overflow = "visible";
135645
+ const styleTag = document.createElement("style");
135646
+ styleTag.textContent = baseCSS + fontsCSS + "svg{overflow:visible;} foreignObject{overflow:visible;}" + classCSS;
135647
+ fo.appendChild(styleTag);
135648
+ const container = document.createElement("div");
135649
+ container.setAttribute("xmlns", "http://www.w3.org/1999/xhtml");
135650
+ container.style.width = `${w0}px`;
135651
+ container.style.height = `${h0}px`;
135652
+ container.style.overflow = "visible";
135653
+ clone.setAttribute("xmlns", "http://www.w3.org/1999/xhtml");
135654
+ container.appendChild(clone);
135655
+ fo.appendChild(container);
135656
+ const serializer = new XMLSerializer();
135657
+ const foString = serializer.serializeToString(fo);
135658
+ const vbW = vbW0 + pad * 2;
135659
+ const vbH = vbH0 + pad * 2;
135660
+ const wantsSize = hasW || hasH;
135661
+ options.meta = { w0, h0, vbW, vbH, targetW: w, targetH: h };
135662
+ const svgOutW = isSafari() && wantsSize ? vbW : outW + pad * 2;
135663
+ const svgOutH = isSafari() && wantsSize ? vbH : outH + pad * 2;
135664
+ const svgHeader = `<svg xmlns="${svgNS}" width="${svgOutW}" height="${svgOutH}" viewBox="0 0 ${vbW} ${vbH}">`;
135665
+ const svgFooter = "</svg>";
135666
+ svgString = svgHeader + foString + svgFooter;
135667
+ dataURL = `data:image/svg+xml;charset=utf-8,${encodeURIComponent(svgString)}`;
135668
+ resolve();
135669
+ }, { fast });
135670
+ });
135671
+ const sandbox = document.getElementById("snapdom-sandbox");
135672
+ if (sandbox && sandbox.style.position === "absolute") sandbox.remove();
135673
+ return dataURL;
135674
+ }
135675
+ function normalizeRootTransforms(originalEl, cloneRoot) {
135676
+ if (!originalEl || !cloneRoot || !cloneRoot.style) return null;
135677
+ const cs = getComputedStyle(originalEl);
135678
+ try {
135679
+ cloneRoot.style.transformOrigin = "0 0";
135680
+ } catch {
135681
+ }
135682
+ try {
135683
+ if ("translate" in cloneRoot.style) cloneRoot.style.translate = "none";
135684
+ if ("rotate" in cloneRoot.style) cloneRoot.style.rotate = "none";
135685
+ } catch {
135686
+ }
135687
+ const tr = cs.transform || "none";
135688
+ if (tr === "none") {
135689
+ try {
135690
+ const M = matrixFromComputed(originalEl);
135691
+ if (M.a === 1 && M.b === 0 && M.c === 0 && M.d === 1) {
135692
+ cloneRoot.style.transform = "none";
135693
+ return { a: 1, b: 0, c: 0, d: 1 };
135694
+ }
135695
+ } catch {
135696
+ }
135697
+ }
135698
+ const m2d = tr.match(/^matrix\(\s*([^)]+)\)$/i);
135699
+ if (m2d) {
135700
+ const nums = m2d[1].split(",").map((v) => parseFloat(v.trim()));
135701
+ if (nums.length === 6 && nums.every(Number.isFinite)) {
135702
+ const [a, b, c, d] = nums;
135703
+ const scaleX = Math.sqrt(a * a + b * b) || 0;
135704
+ let a1 = 0, b1 = 0, shear = 0, c2 = 0, d2 = 0, scaleY = 0;
135705
+ if (scaleX > 0) {
135706
+ a1 = a / scaleX;
135707
+ b1 = b / scaleX;
135708
+ shear = a1 * c + b1 * d;
135709
+ c2 = c - a1 * shear;
135710
+ d2 = d - b1 * shear;
135711
+ scaleY = Math.sqrt(c2 * c2 + d2 * d2) || 0;
135712
+ if (scaleY > 0) shear = shear / scaleY;
135713
+ else shear = 0;
135714
+ }
135715
+ const aP = scaleX;
135716
+ const bP = 0;
135717
+ const cP = shear * scaleY;
135718
+ const dP = scaleY;
135719
+ try {
135720
+ cloneRoot.style.transform = `matrix(${aP}, ${bP}, ${cP}, ${dP}, 0, 0)`;
135721
+ } catch {
135722
+ }
135723
+ return { a: aP, b: bP, c: cP, d: dP };
135724
+ }
135725
+ }
135726
+ try {
135727
+ const legacy = String(tr).trim();
135728
+ cloneRoot.style.transform = legacy + " translate(0px, 0px) rotate(0deg)";
135729
+ return null;
135730
+ } catch {
135731
+ return null;
135732
+ }
135733
+ }
135734
+ function parseBoxShadow(cs) {
135735
+ const v = cs.boxShadow || "";
135736
+ if (!v || v === "none") return { top: 0, right: 0, bottom: 0, left: 0 };
135737
+ const parts = v.split(/\),(?=(?:[^()]*\([^()]*\))*[^()]*$)/).map((s) => s.trim());
135738
+ let t = 0, r = 0, b2 = 0, l = 0;
135739
+ for (const part of parts) {
135740
+ const nums = part.match(/-?\d+(\.\d+)?px/g)?.map((n) => parseFloat(n)) || [];
135741
+ if (nums.length < 2) continue;
135742
+ const [ox2, oy2, blur = 0, spread = 0] = nums;
135743
+ const extX = Math.abs(ox2) + blur + spread;
135744
+ const extY = Math.abs(oy2) + blur + spread;
135745
+ r = Math.max(r, extX + Math.max(ox2, 0));
135746
+ l = Math.max(l, extX + Math.max(-ox2, 0));
135747
+ b2 = Math.max(b2, extY + Math.max(oy2, 0));
135748
+ t = Math.max(t, extY + Math.max(-oy2, 0));
135749
+ }
135750
+ return { top: Math.ceil(t), right: Math.ceil(r), bottom: Math.ceil(b2), left: Math.ceil(l) };
135751
+ }
135752
+ function parseFilterBlur(cs) {
135753
+ const m = (cs.filter || "").match(/blur\(\s*([0-9.]+)px\s*\)/);
135754
+ const b2 = m ? Math.ceil(parseFloat(m[1]) || 0) : 0;
135755
+ return { top: b2, right: b2, bottom: b2, left: b2 };
135756
+ }
135757
+ function parseOutline(cs) {
135758
+ if ((cs.outlineStyle || "none") === "none") return { top: 0, right: 0, bottom: 0, left: 0 };
135759
+ const w2 = Math.ceil(parseFloat(cs.outlineWidth || "0") || 0);
135760
+ return { top: w2, right: w2, bottom: w2, left: w2 };
135761
+ }
135762
+ function bboxWithOriginFull(w2, h2, M, ox2, oy2) {
135763
+ const a2 = M.a, b2 = M.b, c2 = M.c, d2 = M.d, e2 = M.e || 0, f2 = M.f || 0;
135764
+ function pt(x, y) {
135765
+ let X = x - ox2, Y = y - oy2;
135766
+ let X2 = a2 * X + c2 * Y, Y2 = b2 * X + d2 * Y;
135767
+ X2 += ox2 + e2;
135768
+ Y2 += oy2 + f2;
135769
+ return [X2, Y2];
135770
+ }
135771
+ const P = [pt(0, 0), pt(w2, 0), pt(0, h2), pt(w2, h2)];
135772
+ let minX2 = Infinity, minY2 = Infinity, maxX2 = -Infinity, maxY2 = -Infinity;
135773
+ for (const [X, Y] of P) {
135774
+ if (X < minX2) minX2 = X;
135775
+ if (Y < minY2) minY2 = Y;
135776
+ if (X > maxX2) maxX2 = X;
135777
+ if (Y > maxY2) maxY2 = Y;
135778
+ }
135779
+ return { minX: minX2, minY: minY2, maxX: maxX2, maxY: maxY2, width: maxX2 - minX2, height: maxY2 - minY2 };
135780
+ }
135781
+ function hasTFBBox(el) {
135782
+ return hasBBoxAffectingTransform(el);
135783
+ }
135784
+ function matrixFromComputed(el) {
135785
+ const tr = getComputedStyle(el).transform;
135786
+ if (!tr || tr === "none") return new DOMMatrix();
135787
+ try {
135788
+ return new DOMMatrix(tr);
135789
+ } catch {
135790
+ return new WebKitCSSMatrix(tr);
135791
+ }
135792
+ }
135793
+ function readIndividualTransforms(el) {
135794
+ const out = { rotate: "0deg", scale: null, translate: null };
135795
+ const map = typeof el.computedStyleMap === "function" ? el.computedStyleMap() : null;
135796
+ if (map) {
135797
+ const safeGet = (prop) => {
135798
+ try {
135799
+ if (typeof map.has === "function" && !map.has(prop)) return null;
135800
+ if (typeof map.get !== "function") return null;
135801
+ return map.get(prop);
135802
+ } catch {
135803
+ return null;
135804
+ }
135805
+ };
135806
+ const rot = safeGet("rotate");
135807
+ if (rot) {
135808
+ if (rot.angle) {
135809
+ const ang = rot.angle;
135810
+ out.rotate = ang.unit === "rad" ? ang.value * 180 / Math.PI + "deg" : ang.value + ang.unit;
135811
+ } else if (rot.unit) {
135812
+ out.rotate = rot.unit === "rad" ? rot.value * 180 / Math.PI + "deg" : rot.value + rot.unit;
135813
+ } else {
135814
+ out.rotate = String(rot);
135815
+ }
135816
+ } else {
135817
+ const cs2 = getComputedStyle(el);
135818
+ out.rotate = cs2.rotate && cs2.rotate !== "none" ? cs2.rotate : "0deg";
135819
+ }
135820
+ const sc = safeGet("scale");
135821
+ if (sc) {
135822
+ const sx = "x" in sc && sc.x?.value != null ? sc.x.value : Array.isArray(sc) ? sc[0]?.value : Number(sc) || 1;
135823
+ const sy = "y" in sc && sc.y?.value != null ? sc.y.value : Array.isArray(sc) ? sc[1]?.value : sx;
135824
+ out.scale = `${sx} ${sy}`;
135825
+ } else {
135826
+ const cs2 = getComputedStyle(el);
135827
+ out.scale = cs2.scale && cs2.scale !== "none" ? cs2.scale : null;
135828
+ }
135829
+ const tr = safeGet("translate");
135830
+ if (tr) {
135831
+ const tx = "x" in tr && "value" in tr.x ? tr.x.value : Array.isArray(tr) ? tr[0]?.value : 0;
135832
+ const ty = "y" in tr && "value" in tr.y ? tr.y.value : Array.isArray(tr) ? tr[1]?.value : 0;
135833
+ const ux = "x" in tr && tr.x?.unit ? tr.x.unit : "px";
135834
+ const uy = "y" in tr && tr.y?.unit ? tr.y.unit : "px";
135835
+ out.translate = `${tx}${ux} ${ty}${uy}`;
135836
+ } else {
135837
+ const cs2 = getComputedStyle(el);
135838
+ out.translate = cs2.translate && cs2.translate !== "none" ? cs2.translate : null;
135839
+ }
135840
+ return out;
135841
+ }
135842
+ const cs = getComputedStyle(el);
135843
+ out.rotate = cs.rotate && cs.rotate !== "none" ? cs.rotate : "0deg";
135844
+ out.scale = cs.scale && cs.scale !== "none" ? cs.scale : null;
135845
+ out.translate = cs.translate && cs.translate !== "none" ? cs.translate : null;
135846
+ return out;
135847
+ }
135848
+ function hasBBoxAffectingTransform(el) {
135849
+ const cs = getComputedStyle(el);
135850
+ const t = cs.transform || "none";
135851
+ const hasMatrix = t !== "none" && !/^matrix\(\s*1\s*,\s*0\s*,\s*0\s*,\s*1\s*,\s*0\s*,\s*0\s*\)$/i.test(t);
135852
+ if (hasMatrix) return true;
135853
+ const r = cs.rotate && cs.rotate !== "none" && cs.rotate !== "0deg";
135854
+ const s = cs.scale && cs.scale !== "none" && cs.scale !== "1";
135855
+ const tr = cs.translate && cs.translate !== "none" && cs.translate !== "0px 0px";
135856
+ return Boolean(r || s || tr);
135857
+ }
135858
+ function parseTransformOriginPx(cs, w, h) {
135859
+ const raw = (cs.transformOrigin || "0 0").trim().split(/\s+/);
135860
+ const [oxRaw, oyRaw] = [raw[0] || "0", raw[1] || "0"];
135861
+ const toPx = (token, size) => {
135862
+ const t = token.toLowerCase();
135863
+ if (t === "left" || t === "top") return 0;
135864
+ if (t === "center") return size / 2;
135865
+ if (t === "right") return size;
135866
+ if (t === "bottom") return size;
135867
+ if (t.endsWith("px")) return parseFloat(t) || 0;
135868
+ if (t.endsWith("%")) return (parseFloat(t) || 0) * size / 100;
135869
+ if (/^-?\d+(\.\d+)?$/.test(t)) return parseFloat(t) || 0;
135870
+ return 0;
135871
+ };
135872
+ return {
135873
+ ox: toPx(oxRaw, w),
135874
+ oy: toPx(oyRaw, h)
135875
+ };
135876
+ }
135877
+ var __measureHost = null;
135878
+ function getMeasureHost() {
135879
+ if (__measureHost) return __measureHost;
135880
+ const n = document.createElement("div");
135881
+ n.id = "snapdom-measure-slot";
135882
+ n.setAttribute("aria-hidden", "true");
135883
+ Object.assign(n.style, {
135884
+ position: "absolute",
135885
+ left: "-99999px",
135886
+ top: "0px",
135887
+ width: "0px",
135888
+ height: "0px",
135889
+ overflow: "hidden",
135890
+ opacity: "0",
135891
+ pointerEvents: "none",
135892
+ contain: "size layout style"
135893
+ });
135894
+ document.documentElement.appendChild(n);
135895
+ __measureHost = n;
135896
+ return n;
135897
+ }
135898
+ function readTotalTransformMatrix(t) {
135899
+ const host = getMeasureHost();
135900
+ const tmp = document.createElement("div");
135901
+ tmp.style.transformOrigin = "0 0";
135902
+ if (t.baseTransform) tmp.style.transform = t.baseTransform;
135903
+ if (t.rotate) tmp.style.rotate = t.rotate;
135904
+ if (t.scale) tmp.style.scale = t.scale;
135905
+ if (t.translate) tmp.style.translate = t.translate;
135906
+ host.appendChild(tmp);
135907
+ const M = matrixFromComputed(tmp);
135908
+ host.removeChild(tmp);
135909
+ return M;
135910
+ }
135911
+
135912
+ // src/core/context.js
135913
+ function normalizeCachePolicy(v) {
135914
+ if (typeof v === "string") {
135915
+ const s = v.toLowerCase().trim();
135916
+ if (s === "disabled" || s === "full" || s === "auto" || s === "soft") return (
135917
+ /** @type {CachePolicy} */
135918
+ s
135919
+ );
135920
+ }
135921
+ return "soft";
135922
+ }
135923
+ function createContext(options = {}) {
135924
+ const resolvedFormat = options.format ?? "png";
135925
+ const cachePolicy = normalizeCachePolicy(options.cache);
135926
+ return {
135927
+ // Debug & perf
135928
+ debug: options.debug ?? false,
135929
+ fast: options.fast ?? true,
135930
+ scale: options.scale ?? 1,
135931
+ // DOM filters
135932
+ exclude: options.exclude ?? [],
135933
+ excludeMode: options.excludeMode ?? "hide",
135934
+ filter: options.filter ?? null,
135935
+ filterMode: options.filterMode ?? "hide",
135936
+ // Placeholders
135937
+ placeholders: options.placeholders !== false,
135938
+ // default true
135939
+ // Fonts
135940
+ embedFonts: options.embedFonts ?? false,
135941
+ iconFonts: Array.isArray(options.iconFonts) ? options.iconFonts : options.iconFonts ? [options.iconFonts] : [],
135942
+ localFonts: Array.isArray(options.localFonts) ? options.localFonts : [],
135943
+ excludeFonts: options.excludeFonts ?? void 0,
135944
+ fallbackURL: options.fallbackURL ?? void 0,
135945
+ /** @type {CachePolicy} */
135946
+ cache: cachePolicy,
135947
+ // Network
135948
+ useProxy: typeof options.useProxy === "string" ? options.useProxy : "",
135949
+ // Output
135950
+ width: options.width ?? null,
135951
+ height: options.height ?? null,
135952
+ format: resolvedFormat,
135953
+ type: options.type ?? "svg",
135954
+ quality: options.quality ?? 0.92,
135955
+ dpr: options.dpr ?? (window.devicePixelRatio || 1),
135956
+ backgroundColor: options.backgroundColor ?? (["jpg", "jpeg", "webp"].includes(resolvedFormat) ? "#ffffff" : null),
135957
+ filename: options.filename ?? "snapDOM",
135958
+ // NEW flags (user-friendly)
135959
+ straighten: options.straighten ?? false,
135960
+ noShadows: options.noShadows ?? false
135961
+ // Plugins (reservado)
135962
+ // plugins: normalizePlugins(...),
135963
+ };
135964
+ }
135965
+
135966
+ // src/exporters/toCanvas.js
135967
+ function isSvgDataURL(u) {
135968
+ return typeof u === "string" && /^data:image\/svg\+xml/i.test(u);
135969
+ }
135970
+ function decodeSvgFromDataURL(u) {
135971
+ const i = u.indexOf(",");
135972
+ return i >= 0 ? decodeURIComponent(u.slice(i + 1)) : "";
135973
+ }
135974
+ function encodeSvgToDataURL(svgText) {
135975
+ return `data:image/svg+xml;charset=utf-8,${encodeURIComponent(svgText)}`;
135976
+ }
135977
+ function splitDecls(s) {
135978
+ let parts = [], buf = "", depth = 0;
135979
+ for (let i = 0; i < s.length; i++) {
135980
+ const ch = s[i];
135981
+ if (ch === "(") depth++;
135982
+ if (ch === ")") depth = Math.max(0, depth - 1);
135983
+ if (ch === ";" && depth === 0) {
135984
+ parts.push(buf);
135985
+ buf = "";
135986
+ } else buf += ch;
135987
+ }
135988
+ if (buf.trim()) parts.push(buf);
135989
+ return parts.map((x) => x.trim()).filter(Boolean);
135990
+ }
135991
+ function boxShadowToDropShadow(value) {
135992
+ const layers = [];
135993
+ let buf = "", depth = 0;
135994
+ for (let i = 0; i < value.length; i++) {
135995
+ const ch = value[i];
135996
+ if (ch === "(") depth++;
135997
+ if (ch === ")") depth = Math.max(0, depth - 1);
135998
+ if (ch === "," && depth === 0) {
135999
+ layers.push(buf.trim());
136000
+ buf = "";
136001
+ } else buf += ch;
136002
+ }
136003
+ if (buf.trim()) layers.push(buf.trim());
136004
+ const fns = [];
136005
+ for (const layer of layers) {
136006
+ if (/\binset\b/i.test(layer)) continue;
136007
+ const nums = layer.match(/-?\d+(?:\.\d+)?px/gi) || [];
136008
+ const [ox = "0px", oy = "0px", blur = "0px"] = nums;
136009
+ let color = layer.replace(/-?\d+(?:\.\d+)?px/gi, "").replace(/\binset\b/ig, "").trim().replace(/\s{2,}/g, " ");
136010
+ const hasColor = !!color && color !== ",";
136011
+ fns.push(`drop-shadow(${ox} ${oy} ${blur}${hasColor ? ` ${color}` : ""})`);
136012
+ }
136013
+ return fns.join(" ");
136014
+ }
136015
+ function rewriteDeclList(list) {
136016
+ const decls = splitDecls(list);
136017
+ let filter = null, wfilter = null, box = null;
136018
+ const rest = [];
136019
+ for (const d of decls) {
136020
+ const idx = d.indexOf(":");
136021
+ if (idx < 0) continue;
136022
+ const prop = d.slice(0, idx).trim().toLowerCase();
136023
+ const val = d.slice(idx + 1).trim();
136024
+ if (prop === "box-shadow") box = val;
136025
+ else if (prop === "filter") filter = val;
136026
+ else if (prop === "-webkit-filter") wfilter = val;
136027
+ else rest.push([prop, val]);
136028
+ }
136029
+ if (box) {
136030
+ const ds = boxShadowToDropShadow(box);
136031
+ if (ds) {
136032
+ filter = filter ? `${filter} ${ds}` : ds;
136033
+ wfilter = wfilter ? `${wfilter} ${ds}` : ds;
136034
+ }
136035
+ }
136036
+ const out = [...rest];
136037
+ if (filter) out.push(["filter", filter]);
136038
+ if (wfilter) out.push(["-webkit-filter", wfilter]);
136039
+ return out.map(([k, v]) => `${k}:${v}`).join(";");
136040
+ }
136041
+ function rewriteCssBlock(css) {
136042
+ return css.replace(/([^{}]+)\{([^}]*)\}/g, (_m, sel, body) => `${sel}{${rewriteDeclList(body)}}`);
136043
+ }
136044
+ function rewriteSvgBoxShadowToDropShadow(svgText) {
136045
+ svgText = svgText.replace(
136046
+ /<style[^>]*>([\s\S]*?)<\/style>/gi,
136047
+ (m, css) => m.replace(css, rewriteCssBlock(css))
136048
+ );
136049
+ svgText = svgText.replace(
136050
+ /style=(['"])([\s\S]*?)\1/gi,
136051
+ (m, q, body) => `style=${q}${rewriteDeclList(body)}${q}`
136052
+ );
136053
+ return svgText;
136054
+ }
136055
+ function maybeConvertBoxShadowForSafari(url) {
136056
+ if (!isSafari() || !isSvgDataURL(url)) return url;
136057
+ try {
136058
+ const svg = decodeSvgFromDataURL(url);
136059
+ const fixed = rewriteSvgBoxShadowToDropShadow(svg);
136060
+ return encodeSvgToDataURL(fixed);
136061
+ } catch {
136062
+ return url;
136063
+ }
136064
+ }
136065
+ async function toCanvas(url, options) {
136066
+ let { width: optW, height: optH, scale = 1, dpr = 1, meta = {} } = options;
136067
+ url = maybeConvertBoxShadowForSafari(url);
136068
+ const img = new Image();
136069
+ img.loading = "eager";
136070
+ img.decoding = "sync";
136071
+ img.crossOrigin = "anonymous";
136072
+ img.src = url;
136073
+ await img.decode();
136074
+ const natW = img.naturalWidth;
136075
+ const natH = img.naturalHeight;
136076
+ const refW = Number.isFinite(meta.w0) ? meta.w0 : natW;
136077
+ const refH = Number.isFinite(meta.h0) ? meta.h0 : natH;
136078
+ let outW, outH;
136079
+ const hasW = Number.isFinite(optW);
136080
+ const hasH = Number.isFinite(optH);
136081
+ if (hasW && hasH) {
136082
+ outW = Math.max(1, optW);
136083
+ outH = Math.max(1, optH);
136084
+ } else if (hasW) {
136085
+ const k = optW / Math.max(1, refW);
136086
+ outW = optW;
136087
+ outH = Math.round(refH * k);
136088
+ } else if (hasH) {
136089
+ const k = optH / Math.max(1, refH);
136090
+ outH = optH;
136091
+ outW = Math.round(refW * k);
136092
+ } else {
136093
+ outW = natW;
136094
+ outH = natH;
136095
+ }
136096
+ outW = Math.round(outW * scale);
136097
+ outH = Math.round(outH * scale);
136098
+ const canvas = document.createElement("canvas");
136099
+ canvas.width = Math.ceil(outW * dpr);
136100
+ canvas.height = Math.ceil(outH * dpr);
136101
+ canvas.style.width = `${outW}px`;
136102
+ canvas.style.height = `${outH}px`;
136103
+ const ctx = canvas.getContext("2d");
136104
+ if (dpr !== 1) ctx.scale(dpr, dpr);
136105
+ ctx.drawImage(img, 0, 0, outW, outH);
136106
+ return canvas;
136107
+ }
136108
+
136109
+ // src/modules/rasterize.js
136110
+ async function rasterize(url, options) {
136111
+ const canvas = await toCanvas(url, options);
136112
+ const finalCanvas = options.backgroundColor ? createBackground(canvas, options.backgroundColor) : canvas;
136113
+ const img = new Image();
136114
+ img.src = finalCanvas.toDataURL(`image/${options.format}`, options.quality);
136115
+ await img.decode();
136116
+ img.style.width = `${finalCanvas.width / options.dpr}px`;
136117
+ img.style.height = `${finalCanvas.height / options.dpr}px`;
136118
+ return img;
136119
+ }
136120
+
136121
+ // src/exporters/toImg.js
136122
+ async function toImg(url, options) {
136123
+ const { scale = 1, width, height, meta = {} } = options;
136124
+ const hasW = Number.isFinite(width);
136125
+ const hasH = Number.isFinite(height);
136126
+ const wantsScale = Number.isFinite(scale) && scale !== 1 || hasW || hasH;
136127
+ if (isSafari() && wantsScale) {
136128
+ const pngUrl = await rasterize(url, { ...options, format: "png", quality: 1, meta });
136129
+ return pngUrl;
136130
+ }
136131
+ const img = new Image();
136132
+ img.decoding = "sync";
136133
+ img.loading = "eager";
136134
+ img.src = url;
136135
+ await img.decode();
136136
+ if (hasW && hasH) {
136137
+ img.style.width = `${width}px`;
136138
+ img.style.height = `${height}px`;
136139
+ } else if (hasW) {
136140
+ const refW = Number.isFinite(meta.w0) ? meta.w0 : img.naturalWidth;
136141
+ const refH = Number.isFinite(meta.h0) ? meta.h0 : img.naturalHeight;
136142
+ const k = width / Math.max(1, refW);
136143
+ img.style.width = `${width}px`;
136144
+ img.style.height = `${Math.round(refH * k)}px`;
136145
+ } else if (hasH) {
136146
+ const refW = Number.isFinite(meta.w0) ? meta.w0 : img.naturalWidth;
136147
+ const refH = Number.isFinite(meta.h0) ? meta.h0 : img.naturalHeight;
136148
+ const k = height / Math.max(1, refH);
136149
+ img.style.height = `${height}px`;
136150
+ img.style.width = `${Math.round(refW * k)}px`;
136151
+ } else {
136152
+ const cssW = Math.round(img.naturalWidth * scale);
136153
+ const cssH = Math.round(img.naturalHeight * scale);
136154
+ img.style.width = `${cssW}px`;
136155
+ img.style.height = `${cssH}px`;
136156
+ if (typeof url === "string" && url.startsWith("data:image/svg+xml")) {
136157
+ try {
136158
+ const decoded = decodeURIComponent(url.split(",")[1]);
136159
+ const patched = decoded.replace(/width="[^"]*"/, `width="${cssW}"`).replace(/height="[^"]*"/, `height="${cssH}"`);
136160
+ url = `data:image/svg+xml;charset=utf-8,${encodeURIComponent(patched)}`;
136161
+ img.src = url;
136162
+ } catch {
136163
+ }
136164
+ }
136165
+ }
136166
+ return img;
136167
+ }
136168
+
136169
+ // src/exporters/toBlob.js
136170
+ async function toBlob(url, options) {
136171
+ const type = options.type;
136172
+ if (type === "svg") {
136173
+ const svgText = decodeURIComponent(url.split(",")[1]);
136174
+ return new Blob([svgText], { type: "image/svg+xml" });
136175
+ }
136176
+ const canvas = await toCanvas(url, options);
136177
+ const finalCanvas = options.backgroundColor ? createBackground(canvas, options.backgroundColor) : canvas;
136178
+ return new Promise(
136179
+ (resolve) => finalCanvas.toBlob(
136180
+ (blob) => resolve(blob),
136181
+ `image/${type}`,
136182
+ options.quality
136183
+ )
136184
+ );
136185
+ }
136186
+
136187
+ // src/exporters/download.js
136188
+ async function download(url, options) {
136189
+ options.dpr = 1;
136190
+ if (options.format === "svg") {
136191
+ const blob = await toBlob(url, { ...options, type: "svg" });
136192
+ const objectURL = URL.createObjectURL(blob);
136193
+ const a2 = document.createElement("a");
136194
+ a2.href = objectURL;
136195
+ a2.download = options.filename;
136196
+ a2.click();
136197
+ URL.revokeObjectURL(objectURL);
136198
+ return;
136199
+ }
136200
+ const canvas = await toCanvas(url, options);
136201
+ const finalCanvas = options.backgroundColor ? createBackground(canvas, options.backgroundColor) : canvas;
136202
+ const a = document.createElement("a");
136203
+ a.href = finalCanvas.toDataURL(`image/${options.format}`, options.quality);
136204
+ a.download = options.filename;
136205
+ a.click();
136206
+ }
136207
+
136208
+ // src/api/snapdom.js
136209
+ var INTERNAL_TOKEN = Symbol("snapdom.internal");
136210
+ var _safariWarmup = false;
136211
+ async function snapdom(element, userOptions) {
136212
+ if (!element) throw new Error("Element cannot be null or undefined");
136213
+ const context = createContext(userOptions);
136214
+ if (isSafari() && (context.embedFonts === true || hasBackgroundOrMask(element))) {
136215
+ for (let i = 0; i < 3; i++) {
136216
+ try {
136217
+ await safariWarmup(element, userOptions);
136218
+ console.log("Iteraci\xF3n n\xFAmero:", i);
136219
+ _safariWarmup = false;
136220
+ } catch {
136221
+ }
136222
+ }
136223
+ }
136224
+ if (context.iconFonts && context.iconFonts.length > 0) extendIconFonts(context.iconFonts);
136225
+ if (!context.snap) {
136226
+ context.snap = {
136227
+ toPng: (el, opts) => snapdom.toPng(el, opts),
136228
+ toSvg: (el, opts) => snapdom.toSvg(el, opts)
136229
+ };
136230
+ }
136231
+ return snapdom.capture(element, context, INTERNAL_TOKEN);
136232
+ }
136233
+ snapdom.capture = async (el, context, _token) => {
136234
+ if (_token !== INTERNAL_TOKEN) throw new Error("[snapdom.capture] is internal. Use snapdom(...) instead.");
136235
+ const url = await captureDOM(el, context);
136236
+ const ensureContext = (opts) => ({ ...context, ...opts || {} });
136237
+ const withFormat = (format) => (opts) => {
136238
+ const next = ensureContext({ ...opts || {}, format });
136239
+ const wantsJpeg = format === "jpeg" || format === "jpg";
136240
+ const noBg = next.backgroundColor == null || next.backgroundColor === "transparent";
136241
+ if (wantsJpeg && noBg) {
136242
+ next.backgroundColor = "#ffffff";
136243
+ }
136244
+ return rasterize(url, next);
136245
+ };
136246
+ return {
136247
+ url,
136248
+ toRaw: () => url,
136249
+ toImg: (opts) => toImg(url, ensureContext(opts)),
136250
+ toSvg: (opts) => toImg(url, ensureContext(opts)),
136251
+ toCanvas: (opts) => toCanvas(url, ensureContext(opts)),
136252
+ toBlob: (opts) => toBlob(url, ensureContext(opts)),
136253
+ toPng: withFormat("png"),
136254
+ toJpg: withFormat("jpeg"),
136255
+ toWebp: withFormat("webp"),
136256
+ download: (opts) => download(url, ensureContext(opts))
136257
+ };
136258
+ };
136259
+ snapdom.toRaw = (el, options) => snapdom(el, options).then((result) => result.toRaw());
136260
+ snapdom.toImg = (el, options) => snapdom(el, options).then((result) => result.toImg());
136261
+ snapdom.toSvg = (el, options) => snapdom(el, options).then((result) => result.toSvg());
136262
+ snapdom.toCanvas = (el, options) => snapdom(el, options).then((result) => result.toCanvas());
136263
+ snapdom.toBlob = (el, options) => snapdom(el, options).then((result) => result.toBlob());
136264
+ snapdom.toPng = (el, options) => snapdom(el, { ...options, format: "png" }).then((result) => result.toPng());
136265
+ snapdom.toJpg = (el, options) => snapdom(el, { ...options, format: "jpeg" }).then((result) => result.toJpg());
136266
+ snapdom.toWebp = (el, options) => snapdom(el, { ...options, format: "webp" }).then((result) => result.toWebp());
136267
+ snapdom.download = (el, options) => snapdom(el, options).then((result) => result.download());
136268
+ async function safariWarmup(element, baseOptions) {
136269
+ if (_safariWarmup) return;
136270
+ const preflight = {
136271
+ ...baseOptions,
136272
+ fast: true,
136273
+ embedFonts: true,
136274
+ scale: 0.2
136275
+ };
136276
+ let url;
136277
+ try {
136278
+ url = await captureDOM(element, preflight);
136279
+ } catch {
136280
+ return;
136281
+ }
136282
+ await new Promise((resolve) => {
136283
+ const img = new Image();
136284
+ img.decoding = "sync";
136285
+ img.loading = "eager";
136286
+ img.style.position = "fixed";
136287
+ img.style.left = 0;
136288
+ img.style.top = 0;
136289
+ img.style.width = "10px";
136290
+ img.style.height = "10px";
136291
+ img.style.opacity = "0.01";
136292
+ img.style.transform = "translateZ(10px)";
136293
+ img.style.willChange = "transform,opacity;";
136294
+ img.src = url;
136295
+ const cleanup = async () => {
136296
+ await new Promise((r) => setTimeout(r, 100));
136297
+ if (img && img.parentNode) img.parentNode.removeChild(img);
136298
+ _safariWarmup = true;
136299
+ resolve();
136300
+ };
136301
+ document.body.appendChild(img);
136302
+ cleanup();
136303
+ });
136304
+ }
136305
+ function hasBackgroundOrMask(el) {
136306
+ const walker = document.createTreeWalker(el, NodeFilter.SHOW_ELEMENT);
136307
+ while (walker.nextNode()) {
136308
+ const node = (
136309
+ /** @type {Element} */
136310
+ walker.currentNode
136311
+ );
136312
+ const cs = getComputedStyle(node);
136313
+ const bg = cs.backgroundImage && cs.backgroundImage !== "none";
136314
+ const mask = cs.maskImage && cs.maskImage !== "none" || cs.webkitMaskImage && cs.webkitMaskImage !== "none";
136315
+ if (bg || mask) return true;
136316
+ }
136317
+ return false;
136318
+ }
136319
+
136320
+ // src/api/preCache.js
136321
+ async function preCache(root = document, options = {}) {
136322
+ const {
136323
+ embedFonts = true,
136324
+ useProxy = ""
136325
+ } = options;
136326
+ const cacheMode = options.cache ?? options.cacheOpt ?? "full";
136327
+ applyCachePolicy(cacheMode);
136328
+ try {
136329
+ await document.fonts?.ready;
136330
+ } catch {
136331
+ }
136332
+ try {
136333
+ precacheCommonTags();
136334
+ } catch {
136335
+ }
136336
+ cache.session = cache.session || {};
136337
+ if (!cache.session.styleCache) {
136338
+ cache.session.styleCache = /* @__PURE__ */ new WeakMap();
136339
+ }
136340
+ cache.image = cache.image || /* @__PURE__ */ new Map();
136341
+ try {
136342
+ await inlineBackgroundImages(
136343
+ root,
136344
+ /* mirror */
136345
+ void 0,
136346
+ cache.session.styleCache,
136347
+ { useProxy }
136348
+ );
136349
+ } catch {
136350
+ }
136351
+ let imgEls = [], allEls = [];
136352
+ try {
136353
+ if (root?.querySelectorAll) {
136354
+ imgEls = Array.from(root.querySelectorAll("img[src]"));
136355
+ allEls = Array.from(root.querySelectorAll("*"));
136356
+ }
136357
+ } catch {
136358
+ }
136359
+ const promises = [];
136360
+ for (const img of imgEls) {
136361
+ const src = img?.currentSrc || img?.src;
136362
+ if (!src) continue;
136363
+ if (!cache.image.has(src)) {
136364
+ const p = Promise.resolve().then(async () => {
136365
+ const res = await snapFetch(src, { as: "dataURL", useProxy });
136366
+ if (res?.ok && typeof res.data === "string") {
136367
+ cache.image.set(src, res.data);
136368
+ }
136369
+ }).catch(() => {
136370
+ });
136371
+ promises.push(p);
136372
+ }
136373
+ }
136374
+ for (const el of allEls) {
136375
+ let bg = "";
136376
+ try {
136377
+ bg = getStyle(el).backgroundImage;
136378
+ } catch {
136379
+ }
136380
+ if (bg && bg !== "none") {
136381
+ const parts = splitBackgroundImage(bg);
136382
+ for (const entry of parts) {
136383
+ if (entry.startsWith("url(")) {
136384
+ const p = Promise.resolve().then(() => inlineSingleBackgroundEntry(entry, { ...options, useProxy })).catch(() => {
136385
+ });
136386
+ promises.push(p);
136387
+ }
136388
+ }
136389
+ }
136390
+ }
136391
+ if (embedFonts) {
136392
+ try {
136393
+ const required = collectUsedFontVariants(root);
136394
+ const usedCodepoints = collectUsedCodepoints(root);
136395
+ const safari = typeof isSafari === "function" ? isSafari() : !!isSafari;
136396
+ if (safari) {
136397
+ const families = new Set(
136398
+ Array.from(required).map((k) => String(k).split("__")[0]).filter(Boolean)
136399
+ );
136400
+ await ensureFontsReady(families, 3);
136401
+ }
136402
+ await embedCustomFonts({
136403
+ required,
136404
+ usedCodepoints,
136405
+ exclude: options.excludeFonts,
136406
+ localFonts: options.localFonts,
136407
+ useProxy: options.useProxy ?? useProxy
136408
+ });
136409
+ } catch {
136410
+ }
136411
+ }
136412
+ await Promise.allSettled(promises);
136413
+ }
136414
+
136415
+ const snapdom$1 = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({
136416
+ __proto__: null,
136417
+ preCache,
136418
+ snapdom
136419
+ }, Symbol.toStringTag, { value: 'Module' }));
136420
+
132200
136421
  exports.ActionSheet = ActionSheet;
132201
136422
  exports.Affix = Affix;
132202
136423
  exports.Alert = Alert;
@@ -132231,7 +136452,6 @@
132231
136452
  exports.Form = Form;
132232
136453
  exports.FormItem = FormItem;
132233
136454
  exports.Fragment = Fragment;
132234
- exports.HTMLToImage = HTMLToImage;
132235
136455
  exports.Icon = Icon;
132236
136456
  exports.IconManager = IconManager;
132237
136457
  exports.Image = Image$1$1;
@@ -132276,7 +136496,6 @@
132276
136496
  exports.MForm = MForm;
132277
136497
  exports.MFormItem = MFormItem;
132278
136498
  exports.MFragment = MFragment;
132279
- exports.MHTMLToImage = MHTMLToImage;
132280
136499
  exports.MIcon = MIcon;
132281
136500
  exports.MImage = MImage;
132282
136501
  exports.MImageCrop = MImageCrop;
@@ -132310,6 +136529,7 @@
132310
136529
  exports.MScroller = MScroller;
132311
136530
  exports.MSelect = MSelect;
132312
136531
  exports.MSlider = MSlider;
136532
+ exports.MSnapshot = MSnapshot;
132313
136533
  exports.MSortList = MSortList;
132314
136534
  exports.MSpin = MSpin;
132315
136535
  exports.MSteps = MSteps;
@@ -132363,6 +136583,7 @@
132363
136583
  exports.ScrollerWheel = ScrollerWheel;
132364
136584
  exports.Select = Select;
132365
136585
  exports.Slider = Slider;
136586
+ exports.Snapshot = Snapshot;
132366
136587
  exports.SortList = SortList;
132367
136588
  exports.Spin = Spin;
132368
136589
  exports.Steps = Steps;