@mushi-mushi/web 1.37.0 → 1.38.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,653 @@
1
+ import { ALWAYS_REDACT_SELECTORS } from './chunk-ONXNS7MQ.js';
2
+
3
+ // src/capture/screenshot-dom.ts
4
+ async function captureDomScreenshot(privacy, fail) {
5
+ const canvas = document.createElement("canvas");
6
+ const ctx = canvas.getContext("2d", { willReadFrequently: true });
7
+ if (!ctx) {
8
+ fail("unsupported");
9
+ return null;
10
+ }
11
+ const width = window.innerWidth;
12
+ const height = window.innerHeight;
13
+ const dpr = Math.min(window.devicePixelRatio || 1, 2);
14
+ canvas.width = width * dpr;
15
+ canvas.height = height * dpr;
16
+ ctx.scale(dpr, dpr);
17
+ const safeDocument = await buildPrivacySafeDocument(privacy);
18
+ const markup = new XMLSerializer().serializeToString(safeDocument).replace(XML_INVALID_CHARS, "");
19
+ const svgData = `
20
+ <svg xmlns="http://www.w3.org/2000/svg" width="${width}" height="${height}">
21
+ <foreignObject width="100%" height="100%">
22
+ <div xmlns="http://www.w3.org/1999/xhtml">
23
+ ${markup}
24
+ </div>
25
+ </foreignObject>
26
+ </svg>
27
+ `;
28
+ const img = new Image();
29
+ const url = `data:image/svg+xml;charset=utf-8,${encodeURIComponent(svgData)}`;
30
+ let cspBlocked = false;
31
+ const onViolation = (e) => {
32
+ const v = e;
33
+ if (/^img-src|^default-src/.test(v.violatedDirective ?? "") && /^data/.test(v.blockedURI ?? "")) cspBlocked = true;
34
+ };
35
+ document.addEventListener("securitypolicyviolation", onViolation);
36
+ return new Promise((resolve) => {
37
+ let settled = false;
38
+ const settle = (value, reason) => {
39
+ if (settled) return;
40
+ settled = true;
41
+ clearTimeout(timer);
42
+ document.removeEventListener("securitypolicyviolation", onViolation);
43
+ if (reason) fail(reason);
44
+ resolve(value);
45
+ };
46
+ const timer = setTimeout(() => settle(null, "timeout"), 5e3);
47
+ img.onload = () => {
48
+ try {
49
+ ctx.drawImage(img, 0, 0, width, height);
50
+ if (isCanvasBlank(ctx, width, height)) {
51
+ settle(null, "unsupported");
52
+ return;
53
+ }
54
+ settle(canvas.toDataURL("image/jpeg", 0.7));
55
+ } catch {
56
+ settle(null, "taint");
57
+ }
58
+ };
59
+ img.onerror = () => setTimeout(() => settle(null, cspBlocked ? "csp" : "error"), 0);
60
+ img.src = url;
61
+ });
62
+ }
63
+ var XML_INVALID_CHARS = /[\u0000-\u0008\u000B\u000C\u000E-\u001F￾￿]/g;
64
+ var XML_ATTRIBUTE_NAME = /^[A-Za-z_][\w.:-]*$/;
65
+ var MAX_INLINED_MEDIA = 60;
66
+ var MAX_INLINED_BYTES = 12 * 1024 * 1024;
67
+ var MEDIA_SELECTOR = "img, video, canvas, iframe, object, embed";
68
+ async function buildPrivacySafeDocument(privacy) {
69
+ const live = document.documentElement;
70
+ const clone = live.cloneNode(true);
71
+ const liveLinks = live.querySelectorAll("link");
72
+ const cloneLinks = clone.querySelectorAll("link");
73
+ const linkSlots = /* @__PURE__ */ new Map();
74
+ if (liveLinks.length === cloneLinks.length) liveLinks.forEach((l, i) => linkSlots.set(l, cloneLinks[i]));
75
+ const { offscreen, pins, backgrounds } = replayLiveState(live, clone);
76
+ fillScriptedStyleElements(live, clone);
77
+ const hidden = [
78
+ ALWAYS_REDACT_SELECTORS,
79
+ ...privacy?.redactSelectors ?? DEFAULT_REDACT_SELECTORS,
80
+ ...privacy?.maskSelectors ?? [],
81
+ ...privacy?.blockSelectors ?? []
82
+ ];
83
+ inlineMedia(
84
+ Array.from(live.querySelectorAll(MEDIA_SELECTOR)),
85
+ Array.from(clone.querySelectorAll(MEDIA_SELECTOR)),
86
+ (el) => offscreen.has(el) || hidden.some((selector) => matchesOrInside(el, selector))
87
+ );
88
+ pinOffscreen(pins);
89
+ await inlineBackgrounds(backgrounds.filter((bg) => !hidden.some((selector) => matchesOrInside(bg.live, selector))));
90
+ clone.querySelector("#mushi-mushi-widget")?.remove();
91
+ await inlineDocumentStyles(clone, linkSlots);
92
+ stripTaintSources(clone);
93
+ makeXmlSafe(clone);
94
+ freezeMotion(clone);
95
+ fillViewport(clone);
96
+ const redactSelectors = [
97
+ ALWAYS_REDACT_SELECTORS,
98
+ ...privacy?.redactSelectors ?? DEFAULT_REDACT_SELECTORS
99
+ ];
100
+ for (const selector of redactSelectors) {
101
+ for (const el of safeQueryAll(clone, selector)) {
102
+ redactElement(el);
103
+ }
104
+ }
105
+ for (const selector of privacy?.blockSelectors ?? []) {
106
+ for (const el of safeQueryAll(clone, selector)) {
107
+ el.remove();
108
+ }
109
+ }
110
+ for (const selector of privacy?.maskSelectors ?? []) {
111
+ for (const el of safeQueryAll(clone, selector)) {
112
+ maskElement(el);
113
+ }
114
+ }
115
+ return clone;
116
+ }
117
+ var DEFAULT_REDACT_SELECTORS = ["[data-mushi-redact]"];
118
+ var ANIMATED_PROPERTIES = [
119
+ "transform",
120
+ "translate",
121
+ "scale",
122
+ "rotate",
123
+ "opacity",
124
+ "visibility",
125
+ "clip-path",
126
+ "object-position",
127
+ "background-position",
128
+ "left",
129
+ "top",
130
+ "width",
131
+ "height",
132
+ "color",
133
+ "background-color"
134
+ ];
135
+ function replayLiveState(live, clone) {
136
+ const offscreen = /* @__PURE__ */ new Set();
137
+ const pins = [];
138
+ const backgrounds = [];
139
+ const liveAll = [live, ...Array.from(live.querySelectorAll("*"))];
140
+ const cloneAll = [clone, ...Array.from(clone.querySelectorAll("*"))];
141
+ if (liveAll.length !== cloneAll.length) return { offscreen, pins, backgrounds };
142
+ const animated = animationTargets();
143
+ const styles = [];
144
+ const scroller = document.scrollingElement;
145
+ const pending = /* @__PURE__ */ new Map();
146
+ const set = (el, prop, value) => {
147
+ let decls = pending.get(el);
148
+ if (!decls) pending.set(el, decls = /* @__PURE__ */ new Map());
149
+ decls.set(prop, value);
150
+ };
151
+ const scrolled = [];
152
+ const withBackground = [];
153
+ let inBody = false;
154
+ for (let i = 0; i < liveAll.length; i++) {
155
+ const liveEl = liveAll[i];
156
+ const cloneEl = cloneAll[i];
157
+ const computed = getComputedStyle(liveEl);
158
+ styles.push(computed);
159
+ if (liveEl === document.body) inBody = true;
160
+ if (inBody) {
161
+ if (computed.display === "none") set(cloneEl, "display", "none");
162
+ else {
163
+ const parent = liveEl.parentElement;
164
+ if (computed.visibility !== "visible" && parent && getComputedStyle(parent).visibility === "visible") {
165
+ set(cloneEl, "visibility", computed.visibility);
166
+ }
167
+ if (computed.opacity === "0") set(cloneEl, "opacity", "0");
168
+ if (computed.backgroundImage.includes("url(")) withBackground.push(i);
169
+ }
170
+ }
171
+ if (animated.has(liveEl)) {
172
+ for (const p of ANIMATED_PROPERTIES) set(cloneEl, p, computed.getPropertyValue(p));
173
+ }
174
+ if (computed.position === "sticky" && liveEl instanceof HTMLElement) {
175
+ const offset = stickyOffset(liveEl);
176
+ if (offset) {
177
+ set(cloneEl, "position", "relative");
178
+ set(cloneEl, "top", `${offset.top}px`);
179
+ set(cloneEl, "left", `${offset.left}px`);
180
+ set(cloneEl, "bottom", "auto");
181
+ set(cloneEl, "right", "auto");
182
+ }
183
+ }
184
+ if (liveEl !== scroller && (liveEl.scrollTop > 0 || liveEl.scrollLeft > 0)) scrolled.push(i);
185
+ }
186
+ for (const i of scrolled) {
187
+ const liveEl = liveAll[i];
188
+ const liveKids = liveEl.children;
189
+ const cloneKids = cloneAll[i].children;
190
+ for (let j = 0; j < liveKids.length && j < cloneKids.length; j++) {
191
+ const kid = getComputedStyle(liveKids[j]);
192
+ if (kid.position === "fixed") continue;
193
+ const own = pending.get(cloneKids[j])?.get("transform") ?? kid.transform;
194
+ const shift = `translate(${-liveEl.scrollLeft}px, ${-liveEl.scrollTop}px)`;
195
+ set(cloneKids[j], "transform", own && own !== "none" ? `${shift} ${own}` : shift);
196
+ }
197
+ }
198
+ if (window.scrollX || window.scrollY) {
199
+ set(clone, "position", "relative");
200
+ set(clone, "top", `${-window.scrollY}px`);
201
+ set(clone, "left", `${-window.scrollX}px`);
202
+ }
203
+ for (const [el, decls] of pending) {
204
+ const held = Array.from(decls, ([p, v]) => `${p}:${v}!important`).join(";");
205
+ el.setAttribute("style", `${el.getAttribute("style") ?? ""};${held}`);
206
+ }
207
+ findOffscreen(liveAll, cloneAll, styles, offscreen, pins);
208
+ for (const i of withBackground) {
209
+ if (!offscreen.has(liveAll[i])) {
210
+ backgrounds.push({ live: liveAll[i], clone: cloneAll[i], value: styles[i].backgroundImage });
211
+ }
212
+ }
213
+ return { offscreen, pins, backgrounds };
214
+ }
215
+ var MAX_BACKGROUND_URLS = 40;
216
+ var MAX_BACKGROUND_BYTES = 6 * 1024 * 1024;
217
+ var MAX_BACKGROUND_IMAGE_BYTES = 2 * 1024 * 1024;
218
+ async function inlineBackgrounds(backgrounds) {
219
+ const urls = /* @__PURE__ */ new Map();
220
+ let bytes = 0;
221
+ const load = (url) => {
222
+ let pending = urls.get(url);
223
+ if (!pending) {
224
+ pending = urls.size >= MAX_BACKGROUND_URLS ? Promise.resolve(null) : readAsDataUrl(url).then((data) => {
225
+ if (!data || bytes + data.length > MAX_BACKGROUND_BYTES) return null;
226
+ bytes += data.length;
227
+ return data;
228
+ });
229
+ urls.set(url, pending);
230
+ }
231
+ return pending;
232
+ };
233
+ await Promise.all(
234
+ backgrounds.map(async (bg) => {
235
+ const refs = Array.from(bg.value.matchAll(CSS_URL), (m) => m[2].trim()).filter((u) => !u.startsWith("data:"));
236
+ if (refs.length === 0) return;
237
+ const data = await Promise.all(refs.map(load));
238
+ let value = bg.value;
239
+ refs.forEach((ref, k) => {
240
+ if (data[k]) value = value.split(ref).join(data[k]);
241
+ });
242
+ if (value !== bg.value) {
243
+ bg.clone.setAttribute("style", `${bg.clone.getAttribute("style") ?? ""};background-image:${value}!important`);
244
+ }
245
+ })
246
+ );
247
+ }
248
+ var CSS_URL = /url\(\s*(['"]?)([^)'"]+)\1\s*\)/gi;
249
+ async function readAsDataUrl(url) {
250
+ if (typeof fetch !== "function") return null;
251
+ const abort = typeof AbortController === "function" ? new AbortController() : null;
252
+ const timer = setTimeout(() => abort?.abort(), SHEET_FETCH_TIMEOUT_MS);
253
+ try {
254
+ const res = await fetch(url, { cache: "force-cache", signal: abort?.signal });
255
+ if (!res.ok) return null;
256
+ const blob = await res.blob();
257
+ if (blob.size > MAX_BACKGROUND_IMAGE_BYTES || !blob.type.startsWith("image/")) return null;
258
+ const bytes = new Uint8Array(await blob.arrayBuffer());
259
+ let binary = "";
260
+ for (let i = 0; i < bytes.length; i += 32768) {
261
+ binary += String.fromCharCode(...bytes.subarray(i, i + 32768));
262
+ }
263
+ return `data:${blob.type};base64,${btoa(binary)}`;
264
+ } catch {
265
+ return null;
266
+ } finally {
267
+ clearTimeout(timer);
268
+ }
269
+ }
270
+ var PINNABLE_DISPLAY = /^(block|flow-root|flex|grid|list-item|inline-block|inline-flex|inline-grid|table)$/;
271
+ var BLOCK_FLOW = /^(block|flow-root|list-item)$/;
272
+ function findOffscreen(liveAll, cloneAll, styles, offscreen, pins) {
273
+ const bodyIndex = document.body ? liveAll.indexOf(document.body) : -1;
274
+ if (bodyIndex < 0) return;
275
+ const vw = window.innerWidth;
276
+ const vh = window.innerHeight;
277
+ const index = /* @__PURE__ */ new Map();
278
+ const visible = new Array(liveAll.length).fill(false);
279
+ const outside = new Array(liveAll.length).fill(false);
280
+ for (let i = bodyIndex; i < liveAll.length; i++) index.set(liveAll[i], i);
281
+ visible[bodyIndex] = true;
282
+ for (let i = liveAll.length - 1; i > bodyIndex; i--) {
283
+ const el = liveAll[i];
284
+ const r = el.getBoundingClientRect();
285
+ if (r.width > 0 || r.height > 0) {
286
+ if (r.bottom > 0 && r.top < vh && r.right > 0 && r.left < vw) visible[i] = true;
287
+ else outside[i] = true;
288
+ }
289
+ if (styles[i].position === "fixed") visible[i] = true;
290
+ if (visible[i]) {
291
+ outside[i] = false;
292
+ const parent = el.parentElement ? index.get(el.parentElement) : void 0;
293
+ if (parent !== void 0) visible[parent] = true;
294
+ } else if (outside[i]) {
295
+ offscreen.add(el);
296
+ }
297
+ }
298
+ const covered = new Array(liveAll.length).fill(false);
299
+ for (let i = bodyIndex + 1; i < liveAll.length; i++) {
300
+ const el = liveAll[i];
301
+ const parentIndex = el.parentElement ? index.get(el.parentElement) : void 0;
302
+ if (parentIndex === void 0) continue;
303
+ if (covered[parentIndex]) {
304
+ covered[i] = true;
305
+ continue;
306
+ }
307
+ if (!outside[i] || !(el instanceof HTMLElement)) continue;
308
+ const s = styles[i];
309
+ if (!PINNABLE_DISPLAY.test(s.display)) continue;
310
+ covered[i] = true;
311
+ const inFlow = BLOCK_FLOW.test(styles[parentIndex].display) && s.float === "none" && (s.position === "static" || s.position === "relative");
312
+ pins.push({
313
+ clone: cloneAll[i],
314
+ width: el.offsetWidth,
315
+ height: el.offsetHeight,
316
+ marginTop: inFlow ? gapAbove(el) : null,
317
+ marginBottom: inFlow ? gapBelow(el) : null
318
+ });
319
+ }
320
+ }
321
+ function gapAbove(el) {
322
+ const prev = el.previousElementSibling;
323
+ if (!(prev instanceof HTMLElement) || prev.offsetParent !== el.offsetParent) return null;
324
+ return Math.max(0, el.offsetTop - (prev.offsetTop + prev.offsetHeight));
325
+ }
326
+ function gapBelow(el) {
327
+ const next = el.nextElementSibling;
328
+ if (!(next instanceof HTMLElement) || next.offsetParent !== el.offsetParent) return null;
329
+ return Math.max(0, next.offsetTop - (el.offsetTop + el.offsetHeight));
330
+ }
331
+ function pinOffscreen(pins) {
332
+ for (const pin of pins) {
333
+ pin.clone.replaceChildren();
334
+ let pinned = `width:${pin.width}px!important;height:${pin.height}px!important;box-sizing:border-box!important;min-width:0!important;min-height:0!important;max-width:none!important;max-height:none!important;content-visibility:visible!important;contain:none!important;`;
335
+ if (pin.marginTop !== null) pinned += `margin-top:${pin.marginTop}px!important;`;
336
+ if (pin.marginBottom !== null) pinned += `margin-bottom:${pin.marginBottom}px!important;`;
337
+ pin.clone.setAttribute("style", `${pin.clone.getAttribute("style") ?? ""};${pinned}`);
338
+ }
339
+ }
340
+ function animationTargets() {
341
+ try {
342
+ return new Set(
343
+ document.getAnimations().map((a) => a.effect?.target).filter((t) => t instanceof Element && !t.pseudoElement)
344
+ );
345
+ } catch {
346
+ return /* @__PURE__ */ new Set();
347
+ }
348
+ }
349
+ function stickyOffset(el) {
350
+ const stuck = el.getBoundingClientRect();
351
+ const value = el.style.getPropertyValue("position");
352
+ const priority = el.style.getPropertyPriority("position");
353
+ el.style.setProperty("position", "static", "important");
354
+ const flow = el.getBoundingClientRect();
355
+ el.style.removeProperty("position");
356
+ if (value) el.style.setProperty("position", value, priority);
357
+ const top = stuck.top - flow.top;
358
+ const left = stuck.left - flow.left;
359
+ return top || left ? { top, left } : null;
360
+ }
361
+ function inlineMedia(liveMedia, clonedMedia, isHidden) {
362
+ let count = 0;
363
+ let bytes = 0;
364
+ for (let i = 0; i < clonedMedia.length; i++) {
365
+ const cloned = clonedMedia[i];
366
+ const liveEl = liveMedia[i];
367
+ const rect = liveEl?.getBoundingClientRect();
368
+ const layout = liveEl instanceof HTMLElement && liveEl.offsetWidth > 0 ? { width: liveEl.offsetWidth, height: liveEl.offsetHeight } : rect && { width: rect.width, height: rect.height };
369
+ let pixels = null;
370
+ if (liveEl && layout && layout.width > 0 && layout.height > 0 && count < MAX_INLINED_MEDIA && bytes < MAX_INLINED_BYTES && !isHidden(liveEl)) {
371
+ pixels = readPixels(liveEl);
372
+ if (pixels) {
373
+ count++;
374
+ bytes += pixels.url.length;
375
+ }
376
+ }
377
+ replaceMedia(cloned, pixels, layout);
378
+ }
379
+ }
380
+ var MAX_IMAGE_SIDE = 2048;
381
+ function readPixels(el) {
382
+ try {
383
+ let source = null;
384
+ let width = 0;
385
+ let height = 0;
386
+ if (el instanceof HTMLCanvasElement) {
387
+ [source, width, height] = [el, el.width, el.height];
388
+ } else if (el instanceof HTMLImageElement && el.complete && el.naturalWidth > 0) {
389
+ [source, width, height] = [el, el.naturalWidth, el.naturalHeight];
390
+ } else if (el instanceof HTMLVideoElement && el.readyState >= 2) {
391
+ [source, width, height] = [el, el.videoWidth, el.videoHeight];
392
+ }
393
+ if (!source || width <= 0 || height <= 0) return null;
394
+ const scale = Math.min(1, MAX_IMAGE_SIDE / Math.max(width, height));
395
+ const canvas = document.createElement("canvas");
396
+ canvas.width = Math.max(1, Math.round(width * scale));
397
+ canvas.height = Math.max(1, Math.round(height * scale));
398
+ const ctx = canvas.getContext("2d");
399
+ if (!ctx) return null;
400
+ ctx.drawImage(source, 0, 0, canvas.width, canvas.height);
401
+ const url = canvas.toDataURL("image/webp", 0.85);
402
+ return url === "data:," ? null : { url, width, height };
403
+ } catch {
404
+ return null;
405
+ }
406
+ }
407
+ function matchesOrInside(el, selector) {
408
+ try {
409
+ return el.closest(selector) !== null;
410
+ } catch {
411
+ return false;
412
+ }
413
+ }
414
+ var SOURCE_ATTRIBUTES = /* @__PURE__ */ new Set(["src", "srcset", "sizes", "poster", "data", "loading", "decoding"]);
415
+ function replaceMedia(cloned, pixels, layout) {
416
+ const box = cloned.ownerDocument.createElement(pixels ? "img" : "div");
417
+ for (const name of cloned.getAttributeNames()) {
418
+ if (!SOURCE_ATTRIBUTES.has(name)) box.setAttribute(name, cloned.getAttribute(name) ?? "");
419
+ }
420
+ const size = layout ? `width:${layout.width}px;height:${layout.height}px;` : "";
421
+ if (pixels) {
422
+ box.setAttribute("src", pixels.url);
423
+ box.setAttribute("alt", "");
424
+ if (!box.hasAttribute("width")) box.setAttribute("width", String(pixels.width));
425
+ if (!box.hasAttribute("height")) box.setAttribute("height", String(pixels.height));
426
+ box.setAttribute("style", `${box.getAttribute("style") ?? ""};${size}`);
427
+ } else {
428
+ box.setAttribute(
429
+ "style",
430
+ `${box.getAttribute("style") ?? ""};${size}background:#d4d4d4!important;display:${cloned.tagName === "IMG" || cloned.tagName === "CANVAS" ? "inline-block" : "block"};`
431
+ );
432
+ }
433
+ const parent = cloned.parentElement;
434
+ const target = parent && parent.tagName === "PICTURE" ? parent : cloned;
435
+ target.replaceWith(box);
436
+ }
437
+ function makeXmlSafe(root) {
438
+ const doc = root.ownerDocument;
439
+ const walker = doc.createTreeWalker(root, NodeFilter.SHOW_COMMENT);
440
+ const comments = [];
441
+ for (let n = walker.nextNode(); n; n = walker.nextNode()) comments.push(n);
442
+ for (const c of comments) c.parentNode?.removeChild(c);
443
+ for (const el of [root, ...Array.from(root.querySelectorAll("*"))]) {
444
+ for (const name of el.getAttributeNames()) {
445
+ if (!XML_ATTRIBUTE_NAME.test(name)) el.removeAttribute(name);
446
+ }
447
+ }
448
+ }
449
+ function safeQueryAll(root, selector) {
450
+ try {
451
+ return Array.from(root.querySelectorAll(selector));
452
+ } catch {
453
+ return [];
454
+ }
455
+ }
456
+ function redactElement(el) {
457
+ if (el instanceof HTMLInputElement || el instanceof HTMLTextAreaElement) {
458
+ el.value = "";
459
+ el.setAttribute("value", "");
460
+ }
461
+ el.textContent = "";
462
+ el.setAttribute(
463
+ "style",
464
+ `${el.getAttribute("style") ?? ""};background:#000!important;color:#000!important;text-shadow:none!important;border-color:#000!important;`
465
+ );
466
+ el.setAttribute("data-mushi-redacted", "true");
467
+ while (el.firstChild) el.removeChild(el.firstChild);
468
+ }
469
+ function stripTaintSources(root) {
470
+ const pageOrigin = typeof location !== "undefined" ? location.origin : "";
471
+ for (const link of root.querySelectorAll('link[rel="stylesheet"], link[as="style"]')) {
472
+ link.remove();
473
+ }
474
+ for (const styleEl of root.querySelectorAll("style")) {
475
+ const cleaned = stripCssUrlRefs(styleEl.textContent ?? "", pageOrigin);
476
+ if (cleaned !== styleEl.textContent) styleEl.textContent = cleaned;
477
+ }
478
+ for (const el of root.querySelectorAll("[style]")) {
479
+ const s = el.getAttribute("style");
480
+ if (!s) continue;
481
+ const cleaned = stripCssUrlRefs(s, pageOrigin);
482
+ if (cleaned !== s) el.setAttribute("style", cleaned);
483
+ }
484
+ for (const script of root.querySelectorAll("script, noscript, template")) {
485
+ script.remove();
486
+ }
487
+ }
488
+ function stripCssUrlRefs(css, pageOrigin) {
489
+ return css.replace(/url\(\s*(['"]?)([^)'"]+)\1\s*\)/gi, (_match, _q, href) => {
490
+ const trimmed = href.trim();
491
+ if (!trimmed || trimmed.startsWith("data:") || trimmed.startsWith("#")) return _match;
492
+ if (isCrossOriginUrl(trimmed, pageOrigin)) return "none";
493
+ return _match;
494
+ });
495
+ }
496
+ async function inlineDocumentStyles(clone, linkSlots) {
497
+ const sheets = [
498
+ ...Array.from(document.styleSheets),
499
+ ...document.adoptedStyleSheets ?? []
500
+ ];
501
+ const texts = await Promise.all(
502
+ sheets.map(async (sheet) => {
503
+ const owner = sheet.ownerNode;
504
+ if (sheet.disabled || owner instanceof Element && owner.tagName === "STYLE") return "";
505
+ return withMedia(await sheetSource(sheet) ?? serializeSheet(sheet), sheet);
506
+ })
507
+ );
508
+ const head = clone.querySelector("head") ?? clone;
509
+ sheets.forEach((sheet, i) => {
510
+ if (!texts[i]) return;
511
+ const styleEl = document.createElement("style");
512
+ styleEl.textContent = texts[i];
513
+ const slot = sheet.ownerNode ? linkSlots.get(sheet.ownerNode) : void 0;
514
+ if (slot && clone.contains(slot)) slot.replaceWith(styleEl);
515
+ else head.appendChild(styleEl);
516
+ });
517
+ }
518
+ var SHEET_FETCH_TIMEOUT_MS = 2500;
519
+ async function sheetSource(sheet, depth = 0) {
520
+ const href = sheet.href;
521
+ if (!href || depth > 3 || typeof fetch !== "function") return null;
522
+ const abort = typeof AbortController === "function" ? new AbortController() : null;
523
+ const timer = setTimeout(() => abort?.abort(), SHEET_FETCH_TIMEOUT_MS);
524
+ try {
525
+ const res = await fetch(href, { cache: "force-cache", signal: abort?.signal });
526
+ if (!res.ok) return null;
527
+ let imported = "";
528
+ for (const rule of readableRules(sheet)) {
529
+ if (!(rule instanceof CSSImportRule) || !rule.styleSheet) continue;
530
+ const text = await sheetSource(rule.styleSheet, depth + 1) ?? serializeSheet(rule.styleSheet);
531
+ imported += wrapImport(text, rule);
532
+ }
533
+ const own = absolutizeCssUrls((await res.text()).replace(/@import\s[^;]*;/gi, ""), href);
534
+ return `${imported}
535
+ ${own}`;
536
+ } catch {
537
+ return null;
538
+ } finally {
539
+ clearTimeout(timer);
540
+ }
541
+ }
542
+ function readableRules(sheet) {
543
+ try {
544
+ return Array.from(sheet.cssRules);
545
+ } catch {
546
+ return [];
547
+ }
548
+ }
549
+ function wrapImport(text, rule) {
550
+ const layer = rule.layerName;
551
+ let out = layer == null ? text : `@layer ${layer}{${text}}`;
552
+ const media = rule.media?.mediaText;
553
+ if (media && media !== "all") out = `@media ${media}{${out}}`;
554
+ return `${out}
555
+ `;
556
+ }
557
+ function withMedia(text, sheet) {
558
+ const media = sheet.media?.mediaText;
559
+ return text && media && media !== "all" ? `@media ${media}{${text}}` : text;
560
+ }
561
+ function absolutizeCssUrls(css, base) {
562
+ return css.replace(/url\(\s*(['"]?)([^)'"]+)\1\s*\)/gi, (match, quote, ref) => {
563
+ const trimmed = ref.trim();
564
+ if (!trimmed || /^(data:|#|[a-z][a-z\d+.-]*:)/i.test(trimmed)) return match;
565
+ try {
566
+ return `url(${quote}${new URL(trimmed, base).href}${quote})`;
567
+ } catch {
568
+ return match;
569
+ }
570
+ });
571
+ }
572
+ function fillScriptedStyleElements(live, clone) {
573
+ const liveStyles = live.querySelectorAll("style");
574
+ const cloneStyles = clone.querySelectorAll("style");
575
+ if (liveStyles.length !== cloneStyles.length) return;
576
+ liveStyles.forEach((el, i) => {
577
+ if ((el.textContent ?? "").trim() || !el.sheet) return;
578
+ const text = serializeSheet(el.sheet);
579
+ if (text) cloneStyles[i].textContent = text;
580
+ });
581
+ }
582
+ var FREEZE_MOTION_CSS = "*,*::before,*::after{animation:none!important;transition:none!important}";
583
+ function fillViewport(clone) {
584
+ const clear = (c) => !c || c === "transparent" || /^rgba\(.*,\s*0\)$/.test(c);
585
+ let bg = getComputedStyle(document.documentElement).backgroundColor;
586
+ if (clear(bg) && document.body) bg = getComputedStyle(document.body).backgroundColor;
587
+ const root = clone;
588
+ root.style.setProperty("background-color", clear(bg) ? "Canvas" : bg);
589
+ root.style.setProperty("min-height", `${window.innerHeight}px`);
590
+ }
591
+ function freezeMotion(clone) {
592
+ const styleEl = document.createElement("style");
593
+ styleEl.textContent = FREEZE_MOTION_CSS;
594
+ (clone.querySelector("head") ?? clone).appendChild(styleEl);
595
+ }
596
+ function serializeSheet(sheet) {
597
+ let rules;
598
+ try {
599
+ rules = sheet.cssRules;
600
+ } catch {
601
+ return "";
602
+ }
603
+ let text = "";
604
+ for (const rule of Array.from(rules)) {
605
+ if (rule instanceof CSSImportRule) {
606
+ if (rule.styleSheet) text += serializeSheet(rule.styleSheet);
607
+ continue;
608
+ }
609
+ text += `${rule.cssText}
610
+ `;
611
+ }
612
+ return text;
613
+ }
614
+ function isCanvasBlank(ctx, width, height) {
615
+ try {
616
+ const stepX = Math.max(1, Math.floor(width / 8));
617
+ const stepY = Math.max(1, Math.floor(height / 8));
618
+ for (let y = 0; y < height; y += stepY) {
619
+ for (let x = 0; x < width; x += stepX) {
620
+ if (ctx.getImageData(x, y, 1, 1).data[3] !== 0) return false;
621
+ }
622
+ }
623
+ return true;
624
+ } catch {
625
+ return false;
626
+ }
627
+ }
628
+ function isCrossOriginUrl(raw, pageOrigin) {
629
+ if (!raw || raw.startsWith("data:") || raw.startsWith("blob:")) return false;
630
+ try {
631
+ const resolved = new URL(raw, typeof location !== "undefined" ? location.href : "http://localhost/");
632
+ return Boolean(pageOrigin) && resolved.origin !== pageOrigin;
633
+ } catch {
634
+ return true;
635
+ }
636
+ }
637
+ function maskElement(el) {
638
+ if (el instanceof HTMLInputElement || el instanceof HTMLTextAreaElement) {
639
+ el.value = "";
640
+ el.setAttribute("value", "");
641
+ el.setAttribute("placeholder", "\u2022\u2022\u2022\u2022");
642
+ }
643
+ el.textContent = el.children.length === 0 ? "\u2022\u2022\u2022\u2022" : el.textContent;
644
+ el.setAttribute(
645
+ "style",
646
+ `${el.getAttribute("style") ?? ""};background:#8f8f8f!important;color:transparent!important;text-shadow:none!important;`
647
+ );
648
+ el.setAttribute("data-mushi-masked", "true");
649
+ }
650
+
651
+ export { captureDomScreenshot };
652
+ //# sourceMappingURL=screenshot-dom-K3N2HPNN.js.map
653
+ //# sourceMappingURL=screenshot-dom-K3N2HPNN.js.map