@deot/vc 1.0.51 → 1.0.53

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