{"repo_name": "snapdom", "file_name": "/snapdom/__tests__/snapdom.api.test.js", "inference_info": {"prefix_code": "import { describe, it, expect, vi } from 'vitest';\nimport { snapdom } from '../src/api/snapdom.js';\n\ndescribe('snapdom API (direct)', () => {\n it('throws on null element', async () => {\n await expect(snapdom(null)).rejects.toThrow();\n });\n\n it('snapdom.capture returns export methods', async () => {\n const el = document.createElement('div');\n el.style.width = '100px';\n el.style.height = '50px';\n document.body.appendChild(el);\n const result = await snapdom.capture(el);\n expect(result).toHaveProperty('toRaw');\n expect(result).toHaveProperty('toImg');\n expect(result).toHaveProperty('download');\n document.body.removeChild(el);\n });\n\n it('snapdom.toRaw, toImg, toCanvas, toBlob, toPng, toJpg, toWebp, download', async () => {\n const el = document.createElement('div');\n el.style.width = '100px';\n el.style.height = '50px';\n document.body.appendChild(el);\n await snapdom.toRaw(el);\n await snapdom.toImg(el);\n await snapdom.toCanvas(el);\n await snapdom.toBlob(el);\n await snapdom.toPng(el);\n await snapdom.toJpg(el);\n await snapdom.toWebp(el);\n await snapdom.download(el, { format: 'png', filename: 'test' });\n document.body.removeChild(el);\n });\n\n it('cubre rama Safari en toImg', ", "suffix_code": ");\n\n it('cubre rama de download SVG', async () => {\n const el = document.createElement('div');\n el.style.width = '10px';\n el.style.height = '10px';\n document.body.appendChild(el);\n // Mock a.click y URL.createObjectURL\n const a = document.createElement('a');\n document.body.appendChild(a);\n const origCreate = URL.createObjectURL;\n URL.createObjectURL = () => 'blob:url';\n const origClick = a.click;\n a.click = () => {};\n HTMLAnchorElement.prototype.click = () => {};\n const { snapdom } = await import('../src/api/snapdom.js');\n await snapdom.download(el, { format: 'svg', filename: 'testsvg' });\n URL.createObjectURL = origCreate;\n a.click = origClick;\n document.body.removeChild(a);\n document.body.removeChild(el);\n });\n\n it('snapdom.toBlob supports type options ', async () => {\n const el = document.createElement('div');\n el.style.width = '50px';\n el.style.height = '30px';\n document.body.appendChild(el);\n\n const result = await snapdom.capture(el);\n\n const pngBlob = await result.toBlob({ type: 'png' });\n expect(pngBlob).toBeInstanceOf(Blob);\n expect(pngBlob.type).toBe('image/png');\n\n const jpgBlob = await result.toBlob({ type: 'jpeg', quality: 0.8 });\n expect(jpgBlob).toBeInstanceOf(Blob);\n expect(jpgBlob.type).toBe('image/jpeg');\n\n const webpBlob = await result.toBlob({ type: 'webp', quality: 0.9 });\n expect(webpBlob).toBeInstanceOf(Blob);\n expect(webpBlob.type).toBe('image/webp');\n\n // default fallback\n const svgBlob = await result.toBlob();\n expect(svgBlob).toBeInstanceOf(Blob);\n expect(svgBlob.type).toBe('image/svg+xml');\n\n document.body.removeChild(el);\n});\n\nit('toPng, toJpg, toWebp return HTMLImageElement with URLs', async () => {\n const el = document.createElement('div');\n el.style.width = '60px';\n el.style.height = '40px';\n document.body.appendChild(el);\n const snap = await snapdom.capture(el);\n\n const pngImg = await snap.toPng();\n expect(pngImg).toBeInstanceOf(HTMLImageElement);\n expect(typeof pngImg.src).toBe('string');\nexpect(pngImg.src.startsWith('data:image/png')).toBe(true);\n\n const jpgImg = await snap.toJpg();\n expect(jpgImg).toBeInstanceOf(HTMLImageElement);\n expect(typeof jpgImg.src).toBe('string');\nexpect(jpgImg.src.startsWith('data:image/jpeg')).toBe(true);\n\n const webpImg = await snap.toWebp();\n expect(webpImg).toBeInstanceOf(HTMLImageElement);\n expect(typeof webpImg.src).toBe('string');\nexpect(webpImg.src.startsWith('data:image/webp')).toBe(true);\n document.body.removeChild(el);\n});\n\nit('snapdom should support exclude option to filter out elements by CSS selectors', async () => {\n const el = document.createElement('div');\n el.innerHTML = `\n

Title

\n
Should be excluded
\n
Private data
\n

This should remain

\n `;\n document.body.appendChild(el);\n \n const result = await snapdom(el, { exclude: ['.exclude-me', '[data-private]'] });\n \n const svg = result.toRaw();\n const decoded = decodeURIComponent(svg.split(\",\")[1]);\n expect(decoded).not.toContain('Should be excluded');\n expect(decoded).not.toContain('Private data');\n expect(decoded).toContain('Title');\n expect(decoded).toContain('This should remain');\n});\n\nit('snapdom should support filter option to exclude elements with custom logic', async () => {\n const el = document.createElement('div');\n el.innerHTML = `\n
Level 1\n
Level 2\n
Level 3
\n
\n
\n `;\n document.body.appendChild(el);\n const result = await snapdom(el, { \n filter: (element) => !element.classList.contains('level-3')\n });\n \n const svg = result.toRaw();\n const decoded = decodeURIComponent(svg.split(\",\")[1]);\n expect(decoded).toContain('Level 1');\n expect(decoded).toContain('Level 2');\n expect(decoded).not.toContain('Level 3');\n});\n\nit('snapdom should support combining exclude and filter options', async () => {\n const el = document.createElement('div');\n el.innerHTML = `\n
Exclude by selector
\n
Exclude by filter
\n
Keep this content
\n `;\n document.body.appendChild(el);\n\n const result = await snapdom(el, { \n exclude: ['.exclude-by-selector'],\n filter: (element) => !element.classList.contains('exclude-by-filter')\n });\n \n \n const svg = result.toRaw();\n const decoded = decodeURIComponent(svg.split(\",\")[1]);\n expect(decoded).not.toContain('Exclude by selector');\n expect(decoded).not.toContain('Exclude by filter');\n expect(decoded).toContain('Keep this content');\n});\n\n});\n", "middle_code": "async () => {\n vi.resetModules();\n vi.mock('../utils/helpers.js', async () => {\n const actual = await vi.importActual('../utils/helpers.js');\n return { ...actual, isSafari: true };\n });\n const { snapdom } = await import('../src/api/snapdom.js');\n const el = document.createElement('div');\n el.style.width = '10px';\n el.style.height = '10px';\n document.body.appendChild(el);\n const img = new Image();\n img.width = 10;\n img.height = 10;\n img.decode = () => Promise.resolve();\n globalThis.Image = function() { return img; };\n const res = await snapdom.capture(el);\n await res.toImg();\n document.body.removeChild(el);\n vi.resetModules();\n }", "code_description": null, "fill_type": "FUNCTION_TYPE", "language_type": "javascript", "sub_task_type": null}, "context_code": [["/snapdom/__tests__/snapdom.test.js", "import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';\nimport { snapdom } from '../src/index';\n\ndescribe('snapdom API', () => {\n let testElement;\n\n beforeEach(() => {\n testElement = document.createElement('div');\n testElement.style.width = '100px';\n testElement.style.height = '50px';\n document.body.appendChild(testElement );\n });\n\n afterEach(() => {\n document.body.removeChild(testElement );\n });\n\n describe('snapdom.toRaw', () => {\n it('should return a SVG data URL', async () => {\n const result = await snapdom.toRaw(testElement );\n expect(result).toMatch(/^data:image\\/svg\\+xml/);\n });\n });\n\n describe('snapdom', () => {\n it('toImg should return an HTMLImageElement', async () => {\n \n const img = await snapdom.toImg(testElement );\n expect(img).toBeInstanceOf(HTMLImageElement);\n expect(img.src).toMatch(/^data:image\\/svg\\+xml/);\n \n });\n\n it('toCanvas should return a HTMLCanvasElement', async () => {\n // const decodeMock = vi.spyOn(window.Image.prototype, 'decode').mockResolvedValue();\n const canvas = await snapdom.toCanvas(testElement );\n expect(canvas).toBeInstanceOf(HTMLCanvasElement);\n // decodeMock.mockRestore();\n });\n\n it('toPng should return an HTMLImageElement with PNG data URL', async () => {\n // const decodeMock = vi.spyOn(window.Image.prototype, 'decode').mockResolvedValue();\n const img = await snapdom.toPng(testElement );\n expect(img).toBeInstanceOf(HTMLImageElement);\n expect(img.src).toMatch(/^data:image\\/png/);\n // decodeMock.mockRestore();\n });\n\n it('toJpg should return an HTMLImageElement with JPEG data URL', async () => {\n // const decodeMock = vi.spyOn(window.Image.prototype, 'decode').mockResolvedValue();\n const img = await snapdom.toJpg(testElement );\n expect(img).toBeInstanceOf(HTMLImageElement);\n expect(img.src).toMatch(/^data:image\\/jpeg/);\n // decodeMock.mockRestore();\n });\n\n it('toWebp should return an HTMLImageElement with WebP data URL', async () => {\n // const decodeMock = vi.spyOn(window.Image.prototype, 'decode').mockResolvedValue();\n const img = await snapdom.toWebp(testElement );\n expect(img).toBeInstanceOf(HTMLImageElement);\n expect(img.src).toMatch(/^data:image\\/webp/);\n // decodeMock.mockRestore();\n });\n\n it('toBlob should return a Blob of type image/svg+xml', async () => {\n const blob = await snapdom.toBlob(testElement );\n expect(blob).toBeInstanceOf(Blob);\n expect(blob.type).toBe('image/svg+xml');\n });\n });\n});\n"], ["/snapdom/__tests__/snapdom.advance.test.js", "import { describe, it, expect, beforeEach, afterEach } from 'vitest';\nimport { snapdom } from '../src/index';\n\ndescribe('snapdom advanced tests', () => {\n let testElement;\n\n beforeEach(() => {\n testElement = document.createElement('div');\n testElement.style.width = '100px';\n testElement.style.height = '50px';\n testElement.innerHTML = '

Hello World

';\n document.body.appendChild(testElement);\n });\n\n afterEach(() => {\n document.body.removeChild(testElement);\n });\n\n it('should generate different SVGs for different scales', async () => {\n const svg1 = await snapdom.toImg(testElement, { scale: 1 });\n const svg2 = await snapdom.toImg(testElement, { scale: 2 });\n expect(svg1).not.toBe(svg2);\n });\n\n it('captured SVG should contain inner text content', async () => {\n const svgDataUrl = await snapdom.toRaw(testElement);\n const svgText = decodeURIComponent(svgDataUrl.split(',')[1]);\n expect(svgText).toContain('Hello World');\n });\n\n it('should throw an error if element is null', async () => {\n await expect(() => snapdom.toRaw(null)).rejects.toThrow();\n });\n\n it('should generate SVG with correct attributes', async () => {\n const svgDataUrl = await snapdom.toRaw(testElement);\n const svgText = decodeURIComponent(svgDataUrl.split(',')[1]);\n const parser = new DOMParser();\n const doc = parser.parseFromString(svgText, 'image/svg+xml');\n const svg = doc.querySelector('svg');\n\n expect(svg).not.toBeNull();\n expect(svg.getAttribute('width')).toBe('100');\n expect(svg.getAttribute('height')).toBe('50');\n expect(svg.getAttribute('viewBox')).toBe('0 0 100 50');\n });\n\n it('snapdom.toBlob should contain valid SVG content', async () => {\n const blob = await snapdom.toBlob(testElement);\n const text = await blob.text();\n expect(text).toContain('');\n });\n\n it('should replace iframes with fallback visuals', async () => {\n const iframe = document.createElement('iframe');\n iframe.style.width = '200px';\n iframe.style.height = '100px';\n testElement.appendChild(iframe);\n\n const svgDataUrl = await snapdom.toRaw(testElement);\n const svgText = decodeURIComponent(svgDataUrl.split(',')[1]);\n\n const parser = new DOMParser();\n const doc = parser.parseFromString(svgText, 'image/svg+xml');\n\n // No debe haber iframes en el SVG\n expect(doc.querySelectorAll('iframe').length).toBe(0);\n\n // Buscamos divs con estilo inline que contengan repeating-linear-gradient\n const fallbackDivs = Array.from(doc.querySelectorAll('div')).filter(div => {\n const styleAttr = div.getAttribute('style') || '';\n return styleAttr.includes('repeating-linear-gradient');\n });\n\n expect(fallbackDivs.length).toBeGreaterThan(0);\n});\n\n \n});\n"], ["/snapdom/src/api/snapdom.js", "/**\n * Main API for snapDOM: capture DOM elements as SVG and raster images.\n * Provides utilities for exporting, downloading, and converting DOM captures.\n * @module snapdom\n */\n\nimport { captureDOM } from '../core/capture';\nimport { isSafari } from '../utils/helpers.js';\nimport { extendIconFonts } from '../modules/iconFonts.js';\n\n/**\n * Converts an SVG data URL to an HTMLImageElement.\n *\n * @param {string} url - SVG data URL\n * @param {Object} options\n * @param {number} [options.dpr=1] - Device pixel ratio\n * @param {number} [options.scale=1] - Scale multiplier\n * @returns {Promise} The resulting image\n */\n\n async function toImg(url, { dpr = 1, scale = 1 }) {\n const img = new Image();\n img.src = url;\n await img.decode();\n img.width = img.width * scale ;\n img.height = img.height * scale ;\n \n return img;\n}\n\n/**\n * Converts an SVG data URL to a Canvas element.\n *\n * @param {string} url - SVG data URL\n * @param {Object} options\n * @param {number} [options.dpr=1] - Device pixel ratio\n * @param {number} [options.scale=1] - Scale multiplier\n * @returns {Promise} The resulting canvas\n */\n\nasync function toCanvas(url, { dpr = 1, scale = 1 } = {}) {\n const img = new Image();\n img.src = url;\n img.crossOrigin = 'anonymous';\n img.loading = 'eager';\n img.decoding = 'sync';\n\n const isSafariBrowser = isSafari();\n let appended = false;\n\n if (isSafariBrowser) {\n document.body.appendChild(img);\n appended = true;\n }\n\n await img.decode();\n\n if (isSafariBrowser) {\n await new Promise(resolve => setTimeout(resolve, 100));\n }\n\n if (img.width === 0 || img.height === 0) {\n if (appended) img.remove();\n throw new Error('Image failed to load or has no dimensions');\n }\n\n const width = img.width * scale;\n const height = img.height * scale;\n\n const canvas = document.createElement('canvas');\n canvas.width = Math.ceil(width * dpr);\n canvas.height = Math.ceil(height * dpr);\n canvas.style.width = `${width}px`;\n canvas.style.height = `${height}px`;\n\n const ctx = canvas.getContext('2d');\n ctx.scale(dpr, dpr);\n ctx.drawImage(img, 0, 0, width, height);\n\n if (appended) img.remove();\n\n return canvas;\n}\n\n/**\n * Converts a DOM snapshot (SVG data URL) into a Blob of the specified format.\n *\n * @param {string} url - SVG data URL\n * @param {Object} [options]\n * @param {string} [options.format=\"svg\"] - Output format: \"svg\", \"png\", \"jpeg\", \"webp\"\n * @param {number} [options.dpr=1] - Device pixel ratio\n * @param {number} [options.scale=1] - Scale multiplier\n * @param {string} [options.backgroundColor=\"#fff\"] - Background for raster formats\n * @param {number} [options.quality] - JPEG/WebP quality (0–1)\n * @returns {Promise} The resulting Blob\n */\nasync function toBlob(url, {\n type = \"svg\",\n scale = 1,\n backgroundColor = \"#fff\",\n quality\n} = {}) {\n const mime = {\n jpg: \"image/jpeg\",\n jpeg: \"image/jpeg\",\n png: \"image/png\",\n webp: \"image/webp\",\n }[type] || \"image/png\";\n\n if (type === \"svg\") {\n const svgText = decodeURIComponent(url.split(\",\")[1]);\n return new Blob([svgText], { type: \"image/svg+xml\" });\n }\n\n const canvas = await createBackground(url, { dpr: 1, scale }, backgroundColor);\n return new Promise((resolve) => {\n canvas.toBlob(blob => resolve(blob), `${mime}`, quality);\n });\n}\n\n\n\n/**\n * Creates a canvas with a background color from an SVG data URL.\n *\n * @param {string} url - SVG data URL\n * @param {Object} options\n * @param {number} [options.dpr=1] - Device pixel ratio\n * @param {number} [options.scale=1] - Scale multiplier\n * @param {string} [backgroundColor] - Background color to apply\n * @returns {Promise} The resulting canvas\n */\n\n async function createBackground(url, { dpr = 1, scale = 1 }, backgroundColor) {\n const baseCanvas = await toCanvas(url, { dpr, scale });\n if (!backgroundColor) return baseCanvas;\n\n const temp = document.createElement(\"canvas\");\n temp.width = baseCanvas.width;\n temp.height = baseCanvas.height;\n const ctx = temp.getContext(\"2d\");\n\n ctx.fillStyle = backgroundColor;\n ctx.fillRect(0, 0, temp.width, temp.height);\n ctx.drawImage(baseCanvas, 0, 0);\n\n return temp;\n}\n\n/**\n * Converts an SVG data URL to a raster image (PNG, JPEG, WebP).\n *\n * @param {string} url - SVG data URL\n * @param {Object} options\n * @param {number} [options.dpr=1] - Device pixel ratio\n * @param {number} [options.scale=1] - Scale multiplier\n * @param {string} [options.backgroundColor=\"#fff\"] - Background color for rasterization\n * @param {number} [options.quality] - Image quality (for JPEG/WebP)\n * @param {string} [format=\"png\"] - Output format: \"png\", \"jpeg\", or \"webp\"\n * @returns {Promise} The resulting raster image\n */\n\n async function toRasterImg(url, { dpr = 1, scale = 1, backgroundColor, quality }, format = \"png\") {\n const defaultBg = [\"jpg\", \"jpeg\", \"webp\"].includes(format) ? \"#fff\" : undefined;\n const finalBg = backgroundColor ?? defaultBg;\n\n const canvas = await createBackground(url, { dpr, scale }, finalBg);\n\n const img = new Image();\n img.src = canvas.toDataURL(`image/${format}`, quality);\n await img.decode();\n\n img.style.width = `${canvas.width / dpr}px`;\n img.style.height = `${canvas.height / dpr}px`;\n\n return img;\n}\n\n/**\n * Downloads a captured image in the specified format.\n *\n * @param {string} url - SVG data URL\n * @param {Object} options\n * @param {number} [options.dpr=1] - Device pixel ratio\n * @param {number} [options.scale=1] - Scale multiplier\n * @param {string} [options.backgroundColor=\"#fff\"] - Background color for rasterization\n * @param {string} [options.format=\"png\"] - Output format\n * @param {string} [options.filename=\"capture\"] - Download filename\n * @returns {Promise} Resolves when download is triggered\n */\n\n async function download(url,{ dpr = 1, scale = 1, backgroundColor, format = \"png\", filename = \"snapDOM\"} = {}) {\n if (format === \"svg\") {\n const blob = await toBlob(url);\n const objectURL = URL.createObjectURL(blob);\n const a = document.createElement(\"a\");\n a.href = objectURL;\n a.download = `${filename}.svg`;\n a.click();\n URL.revokeObjectURL(objectURL);\n return;\n }\n\n const defaultBg = [\"jpg\", \"jpeg\", \"webp\"].includes(format) ? \"#fff\" : undefined;\n const finalBg = backgroundColor ?? defaultBg;\n\n const canvas = await createBackground(url, { dpr, scale }, finalBg);\n const mime = {\n jpg: \"image/jpeg\",\n jpeg: \"image/jpeg\",\n png: \"image/png\",\n webp: \"image/webp\",\n }[format] || \"image/png\";\n\n const dataURL = canvas.toDataURL(mime);\n\n const a = document.createElement(\"a\");\n a.href = dataURL;\n a.download = `${filename}.${format}`;\n a.click();\n}\n\n/**\n * Main entry point: captures a DOM element and returns an object with export methods.\n *\n * @param {Element} element - DOM element to capture\n * @param {Object} [options={}] - Capture options\n * @returns {Promise} Object with export methods (toRaw, toImg, toCanvas, etc.)\n */\n\nexport async function snapdom(element, options = {}) {\n options = { scale: 1, ...options };\n if (!element) throw new Error(\"Element cannot be null or undefined\");\n if (options.iconFonts) {\n extendIconFonts(options.iconFonts);\n }\n return await snapdom.capture(element, options);\n}\n\n/**\n * Captures a DOM element and returns an object with export methods (internal use).\n *\n * @param {Element} el - DOM element to capture\n * @param {Object} [options={}] - Capture options\n * @returns {Promise} Object with export methods\n */\n\nsnapdom.capture = async (el, options = {}) => {\n const url = await captureDOM(el, options);\n const dpr = window.devicePixelRatio || 1;\n const scale = options.scale || 1;\n\n return {\n url,\n options,\n toRaw: () => url,\n toImg: () => toImg(url, { dpr, scale }),\n toCanvas: () => toCanvas(url, { dpr, scale }),\n toBlob: (options) => toBlob(url, { dpr, scale, ...options }),\n toPng: (options) => toRasterImg(url, { dpr, scale, ...options }, \"png\"),\n toJpg: (options) => toRasterImg(url, { dpr, scale, ...options }, \"jpeg\"),\n toWebp: (options) => toRasterImg(url, { dpr, scale, ...options }, \"webp\"),\n download: ({ format = \"png\", filename = \"capture\", backgroundColor } = {}) => download(url, { dpr, scale, backgroundColor, format, filename})\n };\n};\n\n// Compatibilidad\nsnapdom.toRaw = async (el, options) => (await snapdom.capture(el, options)).toRaw();\nsnapdom.toImg = async (el, options) => (await snapdom.capture(el, options)).toImg();\nsnapdom.toCanvas = async (el, options) => (await snapdom.capture(el, options)).toCanvas();\nsnapdom.toBlob = async (el, options) => (await snapdom.capture(el, options)).toBlob(options);\nsnapdom.toPng = async (el, options) => (await snapdom.capture(el, options)).toPng(options);\nsnapdom.toJpg = async (el, options) => (await snapdom.capture(el, options)).toJpg(options);\nsnapdom.toWebp = async (el, options) => (await snapdom.capture(el, options)).toWebp(options);\nsnapdom.download = async (el, options = {}) => {\n const {\n format = \"png\",\n filename = \"capture\",\n backgroundColor,\n ...rest\n } = options;\n\n const capture = await snapdom.capture(el, rest);\n return await capture.download({ format, filename, backgroundColor });\n};"], ["/snapdom/__tests__/helpers.utils.test.js", "import { describe, it, expect, vi } from 'vitest';\nimport { getStyle, parseContent, extractURL, isIconFont, snapshotComputedStyle, isSafari, stripTranslate, safeEncodeURI, idle, fetchImage } from '../src/utils/helpers.js';\n\ndescribe('getStyle', () => {\n it('returns a CSSStyleDeclaration', () => {\n const el = document.createElement('div');\n document.body.appendChild(el);\n const style = getStyle(el);\n expect(style).toBeInstanceOf(CSSStyleDeclaration);\n document.body.removeChild(el);\n });\n});\n\n\n\ndescribe('parseContent', () => {\n it('parses CSS content correctly', () => {\n expect(parseContent('\"★\"')).toBe('★');\n expect(parseContent('\\\\2605')).toBe('★');\n });\n});\n\ndescribe('parseContent edge cases', () => {\n it('returns \\u0000 if parseInt fails (not hex)', () => {\n expect(parseContent('\\\\nothex')).toBe('\\u0000');\n });\n it('returns clean if String.fromCharCode throws', () => {\n const orig = String.fromCharCode;\n String.fromCharCode = () => { throw new Error('fail'); };\n expect(parseContent('\\\\2605')).toBe('\\\\2605');\n String.fromCharCode = orig;\n });\n});\n\ndescribe('extractURL', () => {\n it('extracts the URL from background-image', () => {\n expect(extractURL('url(\"https://test.com/img.png\")')).toBe('https://test.com/img.png');\n expect(extractURL('none')).toBeNull();\n });\n});\n\ndescribe('isIconFont', () => {\n it('detects icon fonts', () => {\n expect(isIconFont('Font Awesome')).toBe(true);\n expect(isIconFont('Arial')).toBe(false);\n });\n});\n\ndescribe('snapshotComputedStyle', () => {\n it('returns a style snapshot', () => {\n const el = document.createElement('div');\n document.body.appendChild(el);\n const style = getComputedStyle(el);\n const snap = snapshotComputedStyle(style);\n expect(typeof snap).toBe('object');\n document.body.removeChild(el);\n });\n});\n\ndescribe('isSafari', () => {\n it('returns a boolean', () => {\n expect(typeof isSafari()).toBe('boolean');\n });\n});\n\ndescribe('stripTranslate', () => {\n it('removes translate transforms', () => {\n expect(stripTranslate('translateX(10px) scale(2)')).toContain('scale(2)');\n });\n it('stripTranslate removes matrix and matrix3d', () => {\n expect(stripTranslate('matrix(1,0,0,1,10,20)')).not.toContain('10,20');\n expect(stripTranslate('matrix3d(1,0,0,0,0,1,0,0,0,0,1,0,10,20,30,1)')).not.toContain('10,20,30');\n });\n});\n\ndescribe('safeEncodeURI', () => {\n it('returns an encoded string', () => {\n expect(typeof safeEncodeURI('https://test.com/á')).toBe('string');\n });\n it('safeEncodeURI handles invalid URIs gracefully', () => {\n expect(typeof safeEncodeURI('%E0%A4%A')).toBe('string');\n });\n});\n\ndescribe('idle', () => {\n it('calls fn immediately if fast is true', () => {\n let called = false;\n idle(() => { called = true; }, { fast: true });\n expect(called).toBe(true);\n });\n it('uses requestIdleCallback if available', () => {\n const orig = window.requestIdleCallback;\n let called = false;\n window.requestIdleCallback = (fn) => { called = true; fn(); };\n idle(() => { called = true; });\n expect(called).toBe(true);\n window.requestIdleCallback = orig;\n });\n it('falls back to setTimeout if requestIdleCallback not available', async () => {\n const orig = window.requestIdleCallback;\n delete window.requestIdleCallback;\n let called = false;\n idle(() => { called = true; });\n await new Promise(r => setTimeout(r, 10));\n expect(called).toBe(true);\n window.requestIdleCallback = orig;\n });\n});\n\ndescribe('fetchImage', () => {\n it('rejects on image error', async () => {\n await expect(fetchImage('invalid-url', { timeout: 100 }))\n .rejects.toThrow('Fetch fallback failed and no proxy provided');\n\n });\n it('rejects on timeout', async () => {\n // Simula una imagen que nunca carga\n const origImage = window.Image;\n window.Image = class { set src(_){} onload(){} onerror(){} };\n await expect(fetchImage('timeout-url', { timeout: 10 })).rejects.toThrow('Image load timed out');\n window.Image = origImage;\n });\n\n});\n\ndescribe('fetchImage cache', () => {\n it('returns cached image if present', async () => {\n const { cache } = await import('../src/core/cache.js');\n cache.image.set('cached-url', 'data:image/png;base64,abc');\n const result = await fetchImage('cached-url', { useProxy: false });\n expect(result).toBe('data:image/png;base64,abc');\n cache.image.delete('cached-url');\n });\n});\n\ndescribe('fetchImage error propagation', () => {\n it('rejects with original error if decode fails', async () => {\n const origImage = window.Image;\n window.Image = class {\n constructor() { setTimeout(() => this.onload(), 1); }\n set src(_){}\n decode() { return Promise.reject(new Error('decode fail')); }\n get width() { return 1; }\n get height() { return 1; }\n };\n await expect(fetchImage('decode-fail-url', { timeout: 100 }))\n .rejects.toThrow('Fetch fallback failed and no proxy provided');\n window.Image = origImage;\n });\n});\n\ndescribe('stripTranslate edge cases', () => {\n it('returns empty string for empty or none', () => {\n expect(stripTranslate('')).toBe('');\n expect(stripTranslate('none')).toBe('');\n });\n it('returns original for malformed matrix', () => {\n expect(stripTranslate('matrix(1,2,3)')).toBe('matrix(1,2,3)');\n expect(stripTranslate('matrix3d(1,2,3)')).toBe('matrix3d(1,2,3)');\n });\n});\n"], ["/snapdom/__tests__/snapdom.attributes.test.js", "import { describe, it, expect, beforeEach, afterEach } from 'vitest';\nimport { snapdom } from '../src/index';\n\ndescribe('snapdom capture attributes', () => {\n let container;\n\n beforeEach(() => {\n container = document.createElement('div');\n container.style.width = '300px';\n container.style.height = '150px';\n document.body.appendChild(container);\n });\n\n afterEach(() => {\n document.body.removeChild(container);\n });\n\n it('should exclude elements with data-capture=\"exclude\"', async () => {\n const excluded = document.createElement('div');\n excluded.setAttribute('data-capture', 'exclude');\n excluded.textContent = 'Should be excluded';\n container.appendChild(excluded);\n\n const svgDataUrl = await snapdom.toRaw(container);\n const svgText = decodeURIComponent(svgDataUrl.split(',')[1]);\n \n expect(svgText).not.toContain('Should be excluded');\n });\n\n it('should replace elements with data-capture=\"placeholder\" and show placeholder text', async () => {\n const placeholder = document.createElement('div');\n placeholder.setAttribute('data-capture', 'placeholder');\n placeholder.setAttribute('data-placeholder-text', 'Placeholder here');\n placeholder.textContent = 'Original text';\n container.appendChild(placeholder);\n\n const svgDataUrl = await snapdom.toRaw(container);\n const svgText = decodeURIComponent(svgDataUrl.split(',')[1]);\n \n expect(svgText).toContain('Placeholder here');\n expect(svgText).not.toContain('Original text');\n });\n});\n"], ["/snapdom/__tests__/preCache.api.test.js", "import { describe, it, expect, beforeEach } from 'vitest';\nimport { preCache } from '../src/api/preCache.js';\nimport { cache } from '../src/core/cache.js';\n\ndescribe('preCache', () => {\n beforeEach(() => {\n cache.reset()\n });\n\n it('pre-caches images and backgrounds', async () => {\n const el = document.createElement('div');\n const img = document.createElement('img');\n img.src = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/w8AAn8B9p6Q2wAAAABJRU5ErkJggg==';\n el.appendChild(img);\n document.body.appendChild(el);\n await preCache(el);\n expect(cache.image.has(img.src)).toBe(true);\n document.body.removeChild(el);\n });\n\n it('should handle preCache with embedFonts false', async () => {\n const el = document.createElement('div');\n await expect(preCache(el, { embedFonts: false })).resolves.toBeUndefined();\n });\n\n it('should handle preCache with images that fail to load', async () => {\n const el = document.createElement('div');\n const img = document.createElement('img');\n img.src = 'invalid-url.png';\n el.appendChild(img);\n await expect(preCache(el)).resolves.toBeUndefined();\n });\n\n it('should handle preCache with backgrounds that fail to load', async () => {\n const el = document.createElement('div');\n el.style.backgroundImage = 'url(invalid-url.png)';\n document.body.appendChild(el);\n await expect(preCache(el)).resolves.toBeUndefined();\n document.body.removeChild(el);\n });\n\n it('limpia los caches y retorna si reset=true', async () => {\n // Prellenar los caches\n cache.snapshotKey.set('foo', 'bar');\n cache.preStyleMap.set('foo', 'bar');\n cache.preNodeMap.set('foo', 'bar');\n await preCache(document, { reset: true });\n expect(cache.snapshotKey.size).toBe(0);\n expect(cache.preStyleMap.size).toBe(0);\n expect(cache.preNodeMap.size).toBe(0);\n });\n\n it('procesa múltiples backgrounds en un solo elemento', async () => {\n const el = document.createElement('div');\n el.style.backgroundImage = 'url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/w8AAn8B9p6Q2wAAAABJRU5ErkJggg==), url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/w8AAn8B9p6Q2wAAAABJRU5ErkJggg==)';\n document.body.appendChild(el);\n await preCache(el);\n // No assertion estricta porque depende de helpers, pero no debe lanzar error\n document.body.removeChild(el);\n });\n\n});\n"], ["/snapdom/__tests__/clone.core.test.js", "import { describe, it, expect, vi } from 'vitest';\nimport { deepClone } from '../src/core/clone.js';\n\ndescribe('deepClone', () => {\n it('clones a simple div', () => {\n const el = document.createElement('div');\n el.textContent = 'hello';\n const styleMap = new Map();\n const styleCache = new WeakMap();\n const nodeMap = new Map();\n const clone = deepClone(el, styleMap, styleCache, nodeMap, false);\n expect(clone).not.toBe(el);\n expect(clone.textContent).toBe('hello');\n });\n\n it('clones canvas as an image', () => {\n const canvas = document.createElement('canvas');\n canvas.width = 10;\n canvas.height = 10;\n const ctx = canvas.getContext('2d');\n ctx.fillStyle = 'red';\n ctx.fillRect(0,0,10,10);\n const styleMap = new Map();\n const styleCache = new WeakMap();\n const nodeMap = new Map();\n const clone = deepClone(canvas, styleMap, styleCache, nodeMap, false);\n expect(clone.tagName).toBe('IMG');\n expect(clone.src.startsWith('data:image/')).toBe(true);\n });\n\n it('deepClone handles data-capture=\"exclude\"', () => {\n const el = document.createElement('div');\n el.setAttribute('data-capture', 'exclude');\n const clone = deepClone(el, true, {});\n expect(clone).not.toBeNull();\n });\n\n it('deepClone handles data-capture=\"placeholder\"', () => {\n const el = document.createElement('div');\n el.setAttribute('data-capture', 'placeholder');\n el.setAttribute('data-placeholder-text', 'Placeholder!');\n const clone = deepClone(el, true, {});\n expect(clone.textContent).toContain('Placeholder!');\n });\n\n it('deepClone handles iframe', () => {\n const iframe = document.createElement('iframe');\n iframe.width = 100;\n iframe.height = 50;\n const clone = deepClone(iframe, true, {});\n expect(clone.tagName).toBe('DIV');\n });\n\n it('deepClone handles input, textarea, select', () => {\n const input = document.createElement('input');\n input.value = 'foo';\n input.checked = true;\n const textarea = document.createElement('textarea');\n textarea.value = 'bar';\n const select = document.createElement('select');\n const opt = document.createElement('option');\n opt.value = 'baz';\n select.appendChild(opt);\n select.value = 'baz';\n [input, textarea, select].forEach(el => {\n const clone = deepClone(el, true, {});\n expect(clone.value).toBe(el.value);\n });\n });\n\n it('deepClone handles shadow DOM', () => {\n const el = document.createElement('div');\n const shadow = el.attachShadow({mode:'open'});\n const span = document.createElement('span');\n span.textContent = 'shadow';\n shadow.appendChild(span);\n const clone = deepClone(el, true, {});\n expect(clone).not.toBeNull();\n });\n});\n\ndescribe('deepClone edge cases', () => {\n it('clones unsupported node (Comment) as a new Comment', () => {\n const fake = document.createComment('not supported');\n const result = deepClone(fake, true, {});\n expect(result.nodeType).toBe(Node.COMMENT_NODE);\n expect(result.textContent).toBe('not supported');\n expect(result).not.toBe(fake); // Es un clon, no el mismo objeto\n });\n it('clones attributes and children', () => {\n const el = document.createElement('div');\n el.setAttribute('data-test', '1');\n const result = deepClone(el, true, {});\n expect(result.getAttribute('data-test')).toBe('1');\n });\n});\n"], ["/snapdom/__tests__/snapdom.backgroundColor.test.js", "import { describe, it, expect, beforeEach, afterEach } from 'vitest';\nimport { snapdom } from '../src/index';\n\ndescribe('snapdom.toJpg backgroundColor option', () => {\n let container;\n\n beforeEach(() => {\n container = document.createElement('div');\n container.style.width = '100px';\n container.style.height = '100px';\n container.style.background = 'transparent';\n document.body.appendChild(container);\n });\n\n it('applies white background by default', async () => {\n const img = await snapdom.toJpg(container );\n const canvas = document.createElement('canvas');\n canvas.width = img.width;\n canvas.height = img.height;\n const ctx = canvas.getContext('2d');\n ctx.drawImage(img, 0, 0);\n const pixel = ctx.getImageData(0, 0, 1, 1).data;\n // JPEG compresses, but for a solid color it should be near white\n expect(pixel[0]).toBeGreaterThan(240);\n expect(pixel[1]).toBeGreaterThan(240);\n expect(pixel[2]).toBeGreaterThan(240);\n });\n\n it('applies custom background color', async () => {\n const img = await snapdom.toJpg(container, { backgroundColor: '#00ff00' });\n const canvas = document.createElement('canvas');\n canvas.width = img.width;\n canvas.height = img.height;\n const ctx = canvas.getContext('2d');\n ctx.drawImage(img, 0, 0);\n const pixel = ctx.getImageData(0, 0, 1, 1).data;\n // Green check (JPEG lossy, so check near values)\n expect(pixel[0]).toBeLessThan(30); // red\n expect(pixel[1]).toBeGreaterThan(200); // green\n expect(pixel[2]).toBeLessThan(30); // blue\n });\n});\n"], ["/snapdom/__tests__/prepare.core.test.js", "import { describe, it, expect, vi } from 'vitest';\nimport { prepareClone } from '../src/core/prepare.js';\n\ndescribe('prepareClone', () => {\n it('prepares a clone of a div', async () => {\n const el = document.createElement('div');\n el.textContent = 'test';\n const { clone, classCSS } = await prepareClone(el);\n expect(clone).not.toBeNull();\n expect(typeof classCSS).toBe('string');\n });\n});\n\ndescribe('prepareClone edge cases', () => {\n it('throws for null node', async () => {\n await expect(prepareClone(null)).rejects.toThrow();\n });\n it('returns a comment clone for unsupported node', async () => {\n const fake = document.createComment('not supported');\n const result = await prepareClone(fake);\n expect(result.clone.nodeType).toBe(Node.COMMENT_NODE);\n });\n it('handles error in internal logic', async () => {\n const el = document.createElement('div');\n vi.spyOn(el, 'cloneNode').mockImplementation(() => { throw new Error('fail'); });\n await expect(prepareClone(el)).rejects.toThrow('fail');\n });\n it('clones attributes and children', async () => {\n const el = document.createElement('div');\n el.setAttribute('data-test', '1');\n const result = await prepareClone(el);\n expect(result.clone.getAttribute('data-test')).toBe('1');\n });\n});\n"], ["/snapdom/__tests__/capture.core.test.js", "import { describe, it, expect, vi } from 'vitest';\nimport { captureDOM } from '../src/core/capture.js';\n\ndescribe('captureDOM edge cases', () => {\n it('throws for unsupported element (unknown nodeType)', async () => {\n // Simulate a node with an invalid nodeType\n const fakeNode = { nodeType: 999 };\n await expect(captureDOM(fakeNode)).rejects.toThrow();\n });\n\n it('throws if element is null', async () => {\n await expect(captureDOM(null)).rejects.toThrow();\n });\n\n it('throws error if getBoundingClientRect fails', async () => {\n const el = document.createElement('div');\n vi.spyOn(el, 'getBoundingClientRect').mockImplementation(() => { throw new Error('fail'); });\n await expect(captureDOM(el)).rejects.toThrow('fail');\n });\n});\n\ndescribe('captureDOM functional', () => {\n it('captures a simple div and returns an SVG dataURL', async () => {\n const el = document.createElement('div');\n el.textContent = 'test';\n const url = await captureDOM(el);\n expect(url.startsWith('data:image/svg+xml')).toBe(true);\n });\n\n it('supports scale and width/height options', async () => {\n const el = document.createElement('div');\n el.style.width = '100px';\n el.style.height = '50px';\n await captureDOM(el, { scale: 2 });\n await captureDOM(el, { width: 200 });\n await captureDOM(el, { height: 100 });\n });\n\n it('supports fast=false', async () => {\n const el = document.createElement('div');\n await captureDOM(el, { fast: false });\n });\n\n it('supports embedFonts', async () => {\n const el = document.createElement('div');\n await captureDOM(el, { embedFonts: true });\n });\n});\n"], ["/snapdom/__tests__/pseudo.module.test.js", "vi.mock('../src/utils/helpers.js', async () => {\n const actual = await vi.importActual('../src/utils/helpers.js');\n return {\n ...actual,\n fetchImage: vi.fn(),\n };\n});\nvi.mock('../src/modules/fonts.js', async () => {\n const actual = await vi.importActual('../src/modules/fonts.js');\n return {\n ...actual,\n iconToImage: vi.fn(),\n };\n});\n\nimport { describe, it, expect, vi } from 'vitest';\nimport { inlinePseudoElements } from '../src/modules/pseudo.js';\nimport * as helpers from '../src/utils/helpers.js';\nimport * as fonts from '../src/modules/fonts.js';\n\ndescribe('inlinePseudoElements', () => {\n it('does not fail with simple elements', async () => {\n const el = document.createElement('div');\n const clone = document.createElement('div');\n await expect(inlinePseudoElements(el, clone, new Map(), new WeakMap(), false)).resolves.toBeUndefined();\n });\n\n it('handles ::before with text content', async () => {\n const el = document.createElement('div');\n const clone = document.createElement('div');\n vi.spyOn(window, 'getComputedStyle').mockImplementation((_, pseudo) => {\n if (pseudo === '::before') return {\n getPropertyValue: (prop) => prop === 'content' ? '\"★\"' : prop === 'font-family' ? 'Arial' : prop === 'font-size' ? '32' : prop === 'font-weight' ? '400' : prop === 'color' ? '#000' : prop === 'background-image' ? 'none' : prop === 'background-color' ? 'transparent' : '',\n color: '#000', fontSize: '32px', fontWeight: '400', fontFamily: 'Arial',\n };\n return { getPropertyValue: () => '', color: '', fontSize: '', fontWeight: '', fontFamily: '' };\n });\n await inlinePseudoElements(el, clone, new Map(), new WeakMap(), false);\n window.getComputedStyle.mockRestore();\n });\n\n it('handles ::before with icon font', async () => {\n const el = document.createElement('div');\n const clone = document.createElement('div');\n vi.spyOn(window, 'getComputedStyle').mockImplementation((_, pseudo) => {\n if (pseudo === '::before') return {\n getPropertyValue: (prop) => prop === 'content' ? '\"★\"' : prop === 'font-family' ? 'Font Awesome' : prop === 'font-size' ? '32' : prop === 'font-weight' ? '400' : prop === 'color' ? '#000' : prop === 'background-image' ? 'none' : prop === 'background-color' ? 'transparent' : '',\n color: '#000', fontSize: '32px', fontWeight: '400', fontFamily: 'Font Awesome',\n };\n return { getPropertyValue: () => '', color: '', fontSize: '', fontWeight: '', fontFamily: '' };\n });\n fonts.iconToImage.mockResolvedValue('data:image/png;base64,icon');\n await inlinePseudoElements(el, clone, new Map(), new WeakMap(), false);\n window.getComputedStyle.mockRestore();\n });\n\n it('handles ::before with url content', async () => {\n const el = document.createElement('div');\n const clone = document.createElement('div');\n vi.spyOn(window, 'getComputedStyle').mockImplementation((_, pseudo) => {\n if (pseudo === '::before') return {\n getPropertyValue: (prop) => prop === 'content' ? 'url(\"https://test.com/img.png\")' : prop === 'font-family' ? 'Arial' : prop === 'font-size' ? '32' : prop === 'font-weight' ? '400' : prop === 'color' ? '#000' : prop === 'background-image' ? 'none' : prop === 'background-color' ? 'transparent' : '',\n color: '#000', fontSize: '32px', fontWeight: '400', fontFamily: 'Arial',\n };\n return { getPropertyValue: () => '', color: '', fontSize: '', fontWeight: '', fontFamily: '' };\n });\n helpers.fetchImage.mockResolvedValue('data:image/png;base64,img');\n await inlinePseudoElements(el, clone, new Map(), new WeakMap(), false);\n window.getComputedStyle.mockRestore();\n });\n\n it('handles ::before with background-image (data url)', async () => {\n const el = document.createElement('div');\n const clone = document.createElement('div');\n vi.spyOn(window, 'getComputedStyle').mockImplementation((_, pseudo) => {\n if (pseudo === '::before') return {\n getPropertyValue: (prop) => prop === 'content' ? 'none' : prop === 'font-family' ? 'Arial' : prop === 'font-size' ? '32' : prop === 'font-weight' ? '400' : prop === 'color' ? '#000' : prop === 'background-image' ? 'url(\"data:image/png;base64,abc\")' : prop === 'background-color' ? 'transparent' : '',\n color: '#000', fontSize: '32px', fontWeight: '400', fontFamily: 'Arial',\n };\n return { getPropertyValue: () => '', color: '', fontSize: '', fontWeight: '', fontFamily: '' };\n });\n await inlinePseudoElements(el, clone, new Map(), new WeakMap(), false);\n window.getComputedStyle.mockRestore();\n });\n\n it('handles ::before with background-image (fetch)', async () => {\n const el = document.createElement('div');\n const clone = document.createElement('div');\n vi.spyOn(window, 'getComputedStyle').mockImplementation((_, pseudo) => {\n if (pseudo === '::before') return {\n getPropertyValue: (prop) => prop === 'content' ? 'none' : prop === 'font-family' ? 'Arial' : prop === 'font-size' ? '32' : prop === 'font-weight' ? '400' : prop === 'color' ? '#000' : prop === 'background-image' ? 'url(\"https://test.com/img.png\")' : prop === 'background-color' ? 'transparent' : '',\n color: '#000', fontSize: '32px', fontWeight: '400', fontFamily: 'Arial',\n };\n return { getPropertyValue: () => '', color: '', fontSize: '', fontWeight: '', fontFamily: '' };\n });\n helpers.fetchImage.mockResolvedValue('data:image/png;base64,img');\n await inlinePseudoElements(el, clone, new Map(), new WeakMap(), false);\n window.getComputedStyle.mockRestore();\n });\n\n it('handles ::before with background-image fetch error', async () => {\n const el = document.createElement('div');\n const clone = document.createElement('div');\n vi.spyOn(window, 'getComputedStyle').mockImplementation((_, pseudo) => {\n if (pseudo === '::before') return {\n getPropertyValue: (prop) => prop === 'content' ? 'none' : prop === 'font-family' ? 'Arial' : prop === 'font-size' ? '32' : prop === 'font-weight' ? '400' : prop === 'color' ? '#000' : prop === 'background-image' ? 'url(\"https://test.com/img.png\")' : prop === 'background-color' ? 'transparent' : '',\n color: '#000', fontSize: '32px', fontWeight: '400', fontFamily: 'Arial',\n };\n return { getPropertyValue: () => '', color: '', fontSize: '', fontWeight: '', fontFamily: '' };\n });\n helpers.fetchImage.mockRejectedValue(new Error('fail'));\n await inlinePseudoElements(el, clone, new Map(), new WeakMap(), false);\n window.getComputedStyle.mockRestore();\n });\n\n it('handles ::before with no visible box', async () => {\n const el = document.createElement('div');\n const clone = document.createElement('div');\n vi.spyOn(window, 'getComputedStyle').mockImplementation((_, pseudo) => {\n if (pseudo === '::before') return {\n getPropertyValue: () => 'none', color: '', fontSize: '', fontWeight: '', fontFamily: ''\n };\n return { getPropertyValue: () => '', color: '', fontSize: '', fontWeight: '', fontFamily: '' };\n });\n await inlinePseudoElements(el, clone, new Map(), new WeakMap(), false);\n window.getComputedStyle.mockRestore();\n });\n\n it('handles ::first-letter with no textNode', async () => {\n const el = document.createElement('div');\n const clone = document.createElement('div');\n vi.spyOn(window, 'getComputedStyle').mockImplementation(() => ({\n getPropertyValue: () => '', color: '', fontSize: '', fontWeight: '', fontFamily: ''\n }));\n await inlinePseudoElements(el, clone, new Map(), new WeakMap(), false);\n window.getComputedStyle.mockRestore();\n });\n\n it('handles error in pseudo processing', async () => {\n const el = document.createElement('div');\n const clone = document.createElement('div');\n vi.spyOn(window, 'getComputedStyle').mockImplementation(() => { throw new Error('fail'); });\n await inlinePseudoElements(el, clone, new Map(), new WeakMap(), false);\n window.getComputedStyle.mockRestore();\n });\n\n it('ignores if source no es Element', async () => {\n const notElement = {};\n const clone = document.createElement('div');\n await expect(inlinePseudoElements(notElement, clone, new Map(), new WeakMap(), false)).resolves.toBeUndefined();\n });\n\n it('ignores if clone no es Element', async () => {\n const el = document.createElement('div');\n const notElement = {};\n await expect(inlinePseudoElements(el, notElement, new Map(), new WeakMap(), false)).resolves.toBeUndefined();\n });\n\n it('inserta pseudoEl como ::after', async () => {\n const el = document.createElement('div');\n const clone = document.createElement('div');\n vi.spyOn(window, 'getComputedStyle').mockImplementation((_, pseudo) => {\n if (pseudo === '::after') return {\n getPropertyValue: (prop) => prop === 'content' ? '\"after\"' : prop === 'font-family' ? 'Arial' : prop === 'font-size' ? '32' : prop === 'font-weight' ? '400' : prop === 'color' ? '#000' : prop === 'background-image' ? 'none' : prop === 'background-color' ? '#f00' : '',\n color: '#000', fontSize: '32px', fontWeight: '400', fontFamily: 'Arial',\n };\n return { getPropertyValue: () => '', color: '', fontSize: '', fontWeight: '', fontFamily: '' };\n });\n await inlinePseudoElements(el, clone, new Map(), new WeakMap(), false);\n window.getComputedStyle.mockRestore();\n });\n\n it('inserta pseudoEl como ::before', async () => {\n const el = document.createElement('div');\n const clone = document.createElement('div');\n vi.spyOn(window, 'getComputedStyle').mockImplementation((_, pseudo) => {\n if (pseudo === '::before') return {\n getPropertyValue: (prop) => prop === 'content' ? '\"before\"' : prop === 'font-family' ? 'Arial' : prop === 'font-size' ? '32' : prop === 'font-weight' ? '400' : prop === 'color' ? '#000' : prop === 'background-image' ? 'none' : prop === 'background-color' ? '#f00' : '',\n color: '#000', fontSize: '32px', fontWeight: '400', fontFamily: 'Arial',\n };\n return { getPropertyValue: () => '', color: '', fontSize: '', fontWeight: '', fontFamily: '' };\n });\n await inlinePseudoElements(el, clone, new Map(), new WeakMap(), false);\n window.getComputedStyle.mockRestore();\n });\n\n it('no inserta pseudoEl si no hay visible box', async () => {\n const el = document.createElement('div');\n const clone = document.createElement('div');\n vi.spyOn(window, 'getComputedStyle').mockImplementation((_, pseudo) => {\n if (pseudo === '::before') return {\n getPropertyValue: (prop) => 'none', color: '', fontSize: '', fontWeight: '', fontFamily: ''\n };\n return { getPropertyValue: () => '', color: '', fontSize: '', fontWeight: '', fontFamily: '' };\n });\n await inlinePseudoElements(el, clone, new Map(), new WeakMap(), false);\n window.getComputedStyle.mockRestore();\n });\n\n it('maneja ::first-letter meaningful', async () => {\n const el = document.createElement('div');\n el.textContent = 'Test';\n const clone = document.createElement('div');\n clone.textContent = 'Test';\n vi.spyOn(window, 'getComputedStyle').mockImplementation((_, pseudo) => {\n if (pseudo === '::first-letter') return {\n getPropertyValue: (prop) => prop === 'color' ? '#f00' : '', color: '#f00', fontSize: '32px', fontWeight: '400', fontFamily: 'Arial',\n };\n return { getPropertyValue: () => '', color: '#000', fontSize: '32px', fontWeight: '400', fontFamily: 'Arial' };\n });\n await inlinePseudoElements(el, clone, new Map(), new WeakMap(), false);\n window.getComputedStyle.mockRestore();\n });\n\n it('inserta ambos pseudoEl ::before y ::after en una sola ejecución', async () => {\n const el = document.createElement('div');\n const clone = document.createElement('div');\n vi.spyOn(window, 'getComputedStyle').mockImplementation((_, pseudo) => {\n if (pseudo === '::before') return {\n getPropertyValue: (prop) => prop === 'content' ? '\"before\"' : prop === 'font-family' ? 'Arial' : prop === 'font-size' ? '32' : prop === 'font-weight' ? '400' : prop === 'color' ? '#000' : prop === 'background-image' ? 'none' : prop === 'background-color' ? '#f00' : '',\n color: '#000', fontSize: '32px', fontWeight: '400', fontFamily: 'Arial',\n };\n if (pseudo === '::after') return {\n getPropertyValue: (prop) => prop === 'content' ? '\"after\"' : prop === 'font-family' ? 'Arial' : prop === 'font-size' ? '32' : prop === 'font-weight' ? '400' : prop === 'color' ? '#000' : prop === 'background-image' ? 'none' : prop === 'background-color' ? '#0f0' : '',\n color: '#000', fontSize: '32px', fontWeight: '400', fontFamily: 'Arial',\n };\n return { getPropertyValue: () => '', color: '', fontSize: '', fontWeight: '', fontFamily: '' };\n });\n await inlinePseudoElements(el, clone, new Map(), new WeakMap(), false);\n window.getComputedStyle.mockRestore();\n });\n\n it('should inline ::first-letter when style is meaningful', async () => {\n const el = document.createElement('p');\n el.textContent = '¡Hola mundo!';\n el.style.setProperty('color', 'black');\n\n document.body.appendChild(el);\n const clone = el.cloneNode(true);\n const styleMap = new Map();\n const styleCache = new WeakMap();\n\n const style = document.createElement('style');\n style.textContent = `\n p::first-letter {\n color: red;\n font-size: 200%;\n }\n `;\n document.head.appendChild(style);\n\n await inlinePseudoElements(el, clone, styleMap, styleCache, false);\n const firstLetterEl = clone.querySelector('[data-snapdom-pseudo=\"::first-letter\"]');\n expect(firstLetterEl).toBeTruthy();\n expect(firstLetterEl.textContent.length).toBeGreaterThan(0);\n});\n\nit('should inline background-image entries for pseudo-element', async () => {\n const el = document.createElement('div');\n document.body.appendChild(el);\n\n const style = document.createElement('style');\n style.textContent = `\n div::after {\n content: \" \";\n background-image: url(\"data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg'%3E%3Crect width='10' height='10' fill='blue'/%3E%3C/svg%3E\");\n display: inline-block;\n width: 10px;\n height: 10px;\n }\n `;\n document.head.appendChild(style);\n\n const clone = el.cloneNode(true);\n const styleMap = new Map();\n const styleCache = new WeakMap();\n\n await inlinePseudoElements(el, clone, styleMap, styleCache, false);\n const pseudoAfter = clone.querySelector('[data-snapdom-pseudo=\"::after\"]');\n expect(pseudoAfter).toBeTruthy();\n expect(pseudoAfter.style.backgroundImage.startsWith(\"url(\\\"data:image/\")).toBeTruthy();\n});\n\n});\n\n\n\n\n\n"], ["/snapdom/__tests__/snapdom.benchmark.js", "import { bench, describe, beforeEach, afterEach } from 'vitest';\nimport { domToDataUrl } from 'https://unpkg.com/modern-screenshot';\nimport * as htmlToImage from 'https://cdn.jsdelivr.net/npm/html-to-image@1.11.13/+esm';\n//import { toPng, toJpeg, toBlob, toPixelData, toSvg } from 'https://cdn.jsdelivr.net/npm/html-to-image@1.11.13/dist/html-to-image.min.js';\nimport { snapdom as sd } from 'https://cdn.jsdelivr.net/npm/@zumer/snapdom@1.8.0/dist/snapdom.mjs';\nimport { snapdom } from '../src/index';\n\n\nlet html2canvasLoaded = false;\n\nasync function loadHtml2Canvas() {\n if (html2canvasLoaded) return;\n await new Promise((resolve, reject) => {\n const script = document.createElement('script');\n script.src = 'https://cdn.jsdelivr.net/npm/html2canvas@1.4.1/dist/html2canvas.min.js';\n script.onload = () => resolve();\n script.onerror = reject;\n document.head.appendChild(script);\n });\n html2canvasLoaded = true;\n}\n\nawait loadHtml2Canvas();\n\n\n\nconst sizes = [\n { width: 200, height: 100, label: 'Small element (200x100)' },\n { width: 400, height: 300, label: 'Modal size (400x300)' },\n { width: 1200, height: 800, label: 'Page view (1200x800)' },\n { width: 2000, height: 1500, label: 'Large scroll area (2000x1500)' },\n { width: 4000, height: 2000, label: 'Very large element (4000x2000)' },\n];\n\nfor (const size of sizes) {\n describe(`Benchmark simple node at ${size.label}`, () => {\n let container;\n\n async function setupContainer() { \n if (container && document.body.contains(container)) {\n return;\n }\n container = document.createElement('div');\n container.style.width = `${size.width}px`;\n container.style.height = `${size.height}px`;\n container.style.background = 'linear-gradient(to right, red, blue)';\n container.style.fontFamily = 'Arial, sans-serif';\n container.style.display = 'flex';\n container.style.alignItems = 'center';\n container.style.justifyContent = 'center';\n container.style.fontSize = '24px';\n container.innerHTML = `

${size.label}

`;\n document.body.appendChild(container);\n } \n\n /* async function setupContainer() {\n if (container && document.body.contains(container)) return;\n \n container = document.createElement('div');\n container.style.width = `${size.width}px`;\n container.style.height = `${size.height}px`;\n container.style.padding = '20px';\n container.style.overflow = 'auto';\n container.style.background = 'white';\n container.style.border = '2px solid black';\n container.style.fontFamily = 'Arial, sans-serif';\n container.style.color = '#333';\n container.style.position = 'relative';\n \n const grid = document.createElement('div');\n grid.style.display = 'grid';\n grid.style.gridTemplateColumns = 'repeat(auto-fill, minmax(120px, 1fr))';\n grid.style.gap = '10px';\n \n for (let i = 0; i < Math.floor((size.width * size.height) / 20000); i++) {\n const card = document.createElement('div');\n card.style.padding = '10px';\n card.style.borderRadius = '8px';\n card.style.background = i % 2 === 0 ? '#f0f0f0' : '#e0eaff';\n card.style.boxShadow = '0 2px 5px rgba(0,0,0,0.1)';\n card.style.display = 'flex';\n card.style.flexDirection = 'column';\n card.style.alignItems = 'center';\n \n const title = document.createElement('h3');\n title.textContent = `Card ${i + 1}`;\n title.style.margin = '0 0 10px 0';\n title.style.fontSize = '14px';\n \n const icon = document.createElement('div');\n icon.style.width = '30px';\n icon.style.height = '30px';\n icon.style.borderRadius = '50%';\n icon.style.background = i % 2 === 0 ? 'red' : 'blue';\n icon.style.marginBottom = '10px';\n \n const text = document.createElement('p');\n text.textContent = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit.';\n text.style.fontSize = '12px';\n text.style.textAlign = 'center';\n \n card.appendChild(icon);\n card.appendChild(title);\n card.appendChild(text);\n grid.appendChild(card);\n }\n \n container.appendChild(grid);\n document.body.appendChild(container);\n }\n */\n afterEach(() => {\n if (container) {\n container.remove();\n container = null;\n }\n });\n\n bench('snapDOM current version', async () => {\n await setupContainer();\n await snapdom.toRaw(container);\n });\n\n bench('snapDOM V1.8.0', async () => {\n await setupContainer();\n await sd.toRaw(container);\n });\n\n bench('html2canvas capture', async () => {\n await setupContainer();\n const canvas = await window.html2canvas(container, { logging: false, scale: 1 });\n await canvas.toDataURL();\n });\n\n bench('modern-screenshot capture', async () => {\n await setupContainer();\n await domToDataUrl(container);\n });\n\n bench('html-to-image capture', async () => {\n await setupContainer();\n await htmlToImage.toSvg(container);\n });\n });\n}\n"], ["/snapdom/__tests__/snapdom.precache.test.js", "import { describe, test, expect, afterEach, afterAll, beforeEach } from 'vitest';\nimport { snapdom, preCache } from '../src/index';\nimport { cache } from '../src/core/cache';\n\nconst sizes = [\n { width: 200, height: 100, label: 'Small element (200x100)' },\n { width: 400, height: 300, label: 'Modal size (400x300)' },\n { width: 1200, height: 800, label: 'Page view (1200x800)' },\n];\nlet results = [];\nfunction createContainer(size) {\n const container = document.createElement('div');\n container.style.width = `${size.width}px`;\n container.style.height = `${size.height}px`;\n container.style.padding = '20px';\n container.style.overflow = 'auto';\n container.style.background = 'white';\n container.style.border = '2px solid black';\n container.style.fontFamily = 'Arial, sans-serif';\n container.style.color = '#333';\n container.style.position = 'relative';\n\n const grid = document.createElement('div');\n grid.style.display = 'grid';\n grid.style.gridTemplateColumns = 'repeat(auto-fill, minmax(120px, 1fr))';\n grid.style.gap = '10px';\n\n const cardCount = Math.floor((size.width * size.height) / 20000);\n for (let i = 0; i < cardCount; i++) {\n const card = document.createElement('div');\n card.style.padding = '10px';\n card.style.borderRadius = '8px';\n card.style.background = i % 2 === 0 ? '#f0f0f0' : '#e0eaff';\n card.style.boxShadow = '0 2px 5px rgba(0,0,0,0.1)';\n card.style.display = 'flex';\n card.style.flexDirection = 'column';\n card.style.alignItems = 'center';\n\n const title = document.createElement('h3');\n title.textContent = `Card ${i + 1}`;\n title.style.margin = '0 0 10px 0';\n title.style.fontSize = '14px';\n\n const icon = document.createElement('div');\n icon.style.width = '30px';\n icon.style.height = '30px';\n icon.style.borderRadius = '50%';\n icon.style.background = i % 2 === 0 ? 'red' : 'blue';\n icon.style.marginBottom = '10px';\n\n const text = document.createElement('p');\n text.textContent = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit.';\n text.style.fontSize = '12px';\n text.style.textAlign = 'center';\n\n card.appendChild(icon);\n card.appendChild(title);\n card.appendChild(text);\n grid.appendChild(card);\n }\n\n container.appendChild(grid);\n return container;\n}\n\nfunction waitForNextFrame() {\n return new Promise((resolve) => {\n requestAnimationFrame(() => setTimeout(resolve, 0));\n });\n}\nbeforeEach(() => {\n cache.image.clear();\n cache.background.clear();\n cache.resource.clear();\n});\nafterAll(() => {\n for (const r of results) {\n console.log(r.log);\n }\n results = [];\n \n document.body.innerHTML = '';\n});\nfor (const size of sizes) {\n describe(`snapDOM performance test (may not be accurate) - ${size.label}`, () => {\n let container;\n\n afterEach( () => {\n container?.remove();\n container = null;\n document.body.innerHTML = '';\n \n });\n\n test('without preCache', async () => {\n container = createContainer(size);\n document.body.appendChild(container);\n await waitForNextFrame();\n\n const start = performance.now();\n await snapdom.toRaw(container, { compress: true });\n const end = performance.now();\n\n let log = `[${size.label}] WITHOUT preCache: capture ${(end - start).toFixed(2)}ms`;\n results.push({ log });\n expect(true).toBe(true);\n \n });\n \n test('with preCache', async () => {\n container = createContainer(size);\n document.body.appendChild(container);\n await waitForNextFrame();\n\n const startPre = performance.now();\n await preCache();\n const endPre = performance.now();\n \n const startCap = performance.now();\n await snapdom.toRaw(container, { compress: true });\n const endCap = performance.now();\n \n const precacheTime = (endPre - startPre).toFixed(2);\n const captureTime = (endCap - startCap).toFixed(2);\n \n let log = `[${size.label}] WITH preCache: capture ${captureTime}ms (preCache ${precacheTime}ms) `;\n\n results.push({ log });\n \n expect(true).toBe(true);\n });\n\n });\n}\n"], ["/snapdom/__tests__/snapdom.vs.htm2canvas.outputfilesize.test.js", "import { describe, it, beforeEach, afterEach, afterAll } from 'vitest';\nimport { snapdom } from '../src/index';\n//ok\n\ndescribe('Output file size snapdom vs html2canvas (cdn with averaging)', () => {\n let container;\n let html2canvas;\n let report;\n\n beforeEach(async () => {\n container = document.createElement('div');\n container.style.width = '400px';\n container.style.height = '300px';\n container.style.background = 'linear-gradient(to right, red, blue)';\n container.innerHTML = '

Hello Benchmark

Testing multiple runs...

';\n document.body.appendChild(container);\n\n if (!html2canvas) {\n // Cargar html2canvas desde CDN\n await new Promise((resolve, reject) => {\n const script = document.createElement('script');\n script.src = 'https://cdn.jsdelivr.net/npm/html2canvas@1.4.1/dist/html2canvas.min.js';\n script.onload = () => {\n html2canvas = window.html2canvas;\n resolve();\n };\n script.onerror = reject;\n document.head.appendChild(script);\n });\n }\n });\n\n afterEach(() => {\n document.body.removeChild(container);\n });\n\n afterAll(() => {\n console.log(report)\n })\n\n it('snapdom output file size should be smaller than html2canvas', async () => {\n \n // SnapDOM capture\n const snapdomDataURL = await snapdom.toRaw(container, {compress: true});\n const snapdomSizeKB = (snapdomDataURL.length * 3 / 4) / 1024; // Base64 to bytes approx\n \n // html2canvas capture\n const canvas = await html2canvas(container, { logging: false });\n const html2canvasDataURL = await canvas.toDataURL();\n const html2canvasSizeKB = (html2canvasDataURL.length * 3 / 4) / 1024; // Base64 to bytes approx\n \n const differencePercent = ((html2canvasSizeKB - snapdomSizeKB) / html2canvasSizeKB) * 100;\n\n report =`snapDom Captured file size is ${differencePercent.toFixed(2)}% smaller compared to html2canvas (${snapdomSizeKB.toFixed(2)} KB vs. ${html2canvasSizeKB.toFixed(2)} KB)`\n\n})\n\n})\n"], ["/snapdom/__tests__/images.module.test.js", "import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';\nimport { inlineImages } from '../src/modules/images.js';\n\ndescribe('inlineImages', () => {\n let container;\n beforeEach(() => {\n container = document.createElement('div');\n document.body.appendChild(container);\n });\n afterEach(() => {\n document.body.removeChild(container);\n });\n\n it('converts to dataURL if the image loads', async () => {\n const img = document.createElement('img');\n img.src = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/w8AAn8B9p6Q2wAAAABJRU5ErkJggg==';\n container.appendChild(img);\n await inlineImages(container);\n expect(img.src.startsWith('data:image/')).toBe(true);\n });\n\n it('replaces with a fallback if the image fails', async () => {\n const img = document.createElement('img');\n img.src = 'invalid-url.png';\n container.appendChild(img);\n await inlineImages(container);\n expect(container.querySelector('div')).not.toBeNull();\n expect(container.querySelector('img')).toBeNull();\n });\n});\n"], ["/snapdom/__tests__/snapdom.complex.benchmark.js", "import { bench, describe, beforeEach, afterEach } from 'vitest';\nimport { domToDataUrl } from 'https://unpkg.com/modern-screenshot';\nimport * as htmlToImage from 'https://cdn.jsdelivr.net/npm/html-to-image@1.11.13/+esm';\nimport { snapdom as sd } from 'https://cdn.jsdelivr.net/npm/@zumer/snapdom@1.8.0/dist/snapdom.mjs';\nimport { snapdom } from '../src/index';\n\nlet html2canvasLoaded = false;\n\nasync function loadHtml2Canvas() {\n if (html2canvasLoaded) return;\n await new Promise((resolve, reject) => {\n const script = document.createElement('script');\n script.src = 'https://cdn.jsdelivr.net/npm/html2canvas@1.4.1/dist/html2canvas.min.js';\n script.onload = () => resolve();\n script.onerror = reject;\n document.head.appendChild(script);\n });\n html2canvasLoaded = true;\n}\n\nawait loadHtml2Canvas();\n\nconst sizes = [\n { width: 200, height: 100, label: 'Small element (200x100)' },\n { width: 400, height: 300, label: 'Modal size (400x300)' },\n { width: 1200, height: 800, label: 'Page view (1200x800)' },\n { width: 2000, height: 1500, label: 'Large scroll area (2000x1500)' },\n { width: 4000, height: 2000, label: 'Very large element (4000x2000)' },\n];\n\nfor (const size of sizes) {\n describe(`Benchmark complex node at ${size.label}`, () => {\n let container;\n\n async function setupContainer() {\n if (container && document.body.contains(container)) return;\n \n container = document.createElement('div');\n container.style.width = `${size.width}px`;\n container.style.height = `${size.height}px`;\n container.style.padding = '20px';\n container.style.overflow = 'auto';\n container.style.background = 'white';\n container.style.border = '2px solid black';\n container.style.fontFamily = 'Arial, sans-serif';\n container.style.color = '#333';\n container.style.position = 'relative';\n \n const grid = document.createElement('div');\n grid.style.display = 'grid';\n grid.style.gridTemplateColumns = 'repeat(auto-fill, minmax(120px, 1fr))';\n grid.style.gap = '10px';\n \n for (let i = 0; i < Math.floor((size.width * size.height) / 20000); i++) {\n const card = document.createElement('div');\n card.style.padding = '10px';\n card.style.borderRadius = '8px';\n card.style.background = i % 2 === 0 ? '#f0f0f0' : '#e0eaff';\n card.style.boxShadow = '0 2px 5px rgba(0,0,0,0.1)';\n card.style.display = 'flex';\n card.style.flexDirection = 'column';\n card.style.alignItems = 'center';\n \n const title = document.createElement('h3');\n title.textContent = `Card ${i + 1}`;\n title.style.margin = '0 0 10px 0';\n title.style.fontSize = '14px';\n \n const icon = document.createElement('div');\n icon.style.width = '30px';\n icon.style.height = '30px';\n icon.style.borderRadius = '50%';\n icon.style.background = i % 2 === 0 ? 'red' : 'blue';\n icon.style.marginBottom = '10px';\n \n const text = document.createElement('p');\n text.textContent = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit.';\n text.style.fontSize = '12px';\n text.style.textAlign = 'center';\n \n card.appendChild(icon);\n card.appendChild(title);\n card.appendChild(text);\n grid.appendChild(card);\n }\n \n container.appendChild(grid);\n document.body.appendChild(container);\n \n }\n \n afterEach (async () => {\n if (container) {\n container.remove();\n container = null;\n }\n \n document.body.innerHTML = ''\n });\n\n bench('snapDOM current version', async () => {\n await setupContainer();\n await snapdom.toRaw(container, {compress: true, fast: true});\n });\n\n bench('snapDOM V1.8.0', async () => {\n await setupContainer();\n await sd.toRaw(container);\n });\n \n bench('html2canvas capture', async () => {\n await setupContainer();\n const canvas = await window.html2canvas(container, { logging: false, scale: 1 });\n await canvas.toDataURL();\n });\n\n bench('modern-screenshot capture', async () => {\n await setupContainer();\n await domToDataUrl(container);\n });\n bench('html-to-image capture', async () => {\n await setupContainer();\n await htmlToImage.toSvg(container);\n });\n });\n}\n"], ["/snapdom/__tests__/snapdom.vs.modernscreenshot.outputfilesize.test.js", "import { describe, it, beforeEach, afterEach, afterAll } from 'vitest';\nimport { domToDataUrl} from 'https://unpkg.com/modern-screenshot';\nimport { snapdom } from '../src/index';\n//ok\n\ndescribe('Output file size snapdom vs modern-screeenshot (cdn with averaging)', () => {\n let container;\n\n let report;\n\n beforeEach(async () => {\n container = document.createElement('div');\n container.style.width = '400px';\n container.style.height = '300px';\n container.style.background = 'linear-gradient(to right, red, blue)';\n container.innerHTML = '

Hello Benchmark

Testing multiple runs...

';\n document.body.appendChild(container);\n });\n\n afterEach(() => {\n document.body.removeChild(container);\n });\n\n afterAll(() => {\n console.log(report)\n })\n\n it('snapdom output file size should be smaller than modern-screenshot', async () => {\n \n // SnapDOM capture\n const snapdomDataURL = await snapdom.toRaw(container, {compress: true});\n const snapdomSizeKB = (snapdomDataURL.length * 3 / 4) / 1024; // Base64 to bytes approx\n \n // domToDataUrl capture\n const domToDataUrlDataURL = await domToDataUrl(container);\n const domToDataUrlSizeKB = (domToDataUrlDataURL.length * 3 / 4) / 1024; // Base64 to bytes approx\n \n const differencePercent = ((domToDataUrlSizeKB - snapdomSizeKB) / domToDataUrlSizeKB) * 100;\n\n report =`snapdom captured file size is ${differencePercent.toFixed(2)}% smaller compared to modern-screenshot (${snapdomSizeKB.toFixed(2)} KB vs. ${domToDataUrlSizeKB.toFixed(2)} KB)`\n\n})\n\n})\n"], ["/snapdom/__tests__/fonts.module.test.js", "import { describe, it, expect, beforeEach, vi } from 'vitest';\nimport { iconToImage, embedCustomFonts } from '../src/modules/fonts.js';\nimport { cache } from '../src/core/cache.js';\n\n// Utilidad para limpiar estilos y links antes de cada test\nfunction cleanFontEnvironment() {\n document.querySelectorAll('style,link[rel=\"stylesheet\"]').forEach(s => s.remove());\n}\n\nfunction addStyleTag(css) {\n const style = document.createElement('style');\n style.setAttribute('data-test-style', 'true');\n style.textContent = css;\n document.head.appendChild(style);\n return style;\n}\n\ndescribe('iconToImage', () => {\n it('genera un dataURL para un carácter unicode', async () => {\n const url = await iconToImage('★', 'Arial', 'bold', 32, '#000');\n expect(url.startsWith('data:image/')).toBe(true);\n });\n\n it('maneja diferentes pesos y colores de fuente', async () => {\n const url = await iconToImage('★', 'Arial', 700, 40, '#ff0000');\n expect(url.startsWith('data:image/')).toBe(true);\n });\n\n it('usa valores por defecto si no hay métricas', async () => {\n const orig = HTMLCanvasElement.prototype.getContext;\n HTMLCanvasElement.prototype.getContext = function() {\n return {\n font: '',\n scale: vi.fn(),\n textAlign: '',\n textBaseline: '',\n fillStyle: '',\n fillText: vi.fn(),\n measureText: () => ({ width: 10 })\n };\n };\n const url = await iconToImage('★', 'Arial', 'bold', 32, '#000');\n expect(url.startsWith('data:image/')).toBe(true);\n HTMLCanvasElement.prototype.getContext = orig;\n });\n});\n\ndescribe('embedCustomFonts', () => {\n beforeEach(() => {\n cache.reset();\n cache.font.clear();\n cache.resource.clear();\n cleanFontEnvironment();\n vi.restoreAllMocks();\n });\n\n it('conserva @font-face con solo local() en src', async () => {\n const style = addStyleTag(`\n @font-face {\n font-family: OnlyLocal;\n src: local(\"Arial\");\n font-style: normal;\n font-weight: normal;\n }\n `);\n\n const css = await embedCustomFonts();\n expect(css).toMatch(/font-family:\\s*OnlyLocal/);\n expect(css).toMatch(/src:\\s*local\\([\"']Arial[\"']\\)/);\n document.head.removeChild(style);\n });\n\n it('conserva @font-face con local() y sin url()', async () => {\n const style = addStyleTag(`\n @font-face {\n font-family: LocalFont;\n src: local('MyFont'), local('FallbackFont');\n font-style: italic;\n font-weight: bold;\n }\n `);\n\n const css = await embedCustomFonts();\n expect(css).toMatch(/font-family:\\s*LocalFont/);\n expect(css).toMatch(/src:\\s*local\\(['\"]MyFont['\"]\\),\\s*local\\(['\"]FallbackFont['\"]\\)/);\n expect(css).toMatch(/font-style:\\s*italic/);\n document.head.removeChild(style);\n });\n});\n"], ["/snapdom/src/utils/helpers.js", "import { cache } from \"../core/cache\";\n\n/**\n * Fetches and inlines a single background-image entry to a data URL (with caching).\n * - If entry is a gradient or \"none\", returns unchanged.\n * - If entry is a url(...), fetches the image as data URL and caches it.\n *\n * @param {string} entry - Single background-image entry (e.g., \"url(...)\").\n * @param {Object} [options={}] - Options like crossOrigin.\n * @param {boolean} [options.skipInline=false] - If true, only fetches & caches, doesn't return a replacement.\n * @returns {Promise} - The processed entry (unless skipInline is true).\n */\nexport async function inlineSingleBackgroundEntry(entry, options = {}) {\n const rawUrl = extractURL(entry)\n\n const isGradient = /^((repeating-)?(linear|radial|conic)-gradient)\\(/i.test(entry);\n \n if (rawUrl) {\n const encodedUrl = safeEncodeURI(rawUrl);\n if (cache.background.has(encodedUrl)) {\n return options.skipInline ? void 0 : `url(${cache.background.get(encodedUrl)})`;\n } else {\n const dataUrl = await fetchImage(encodedUrl, { useProxy: options.useProxy });\n cache.background.set(encodedUrl, dataUrl);\n return options.skipInline ? void 0 : `url(\"${dataUrl}\")`;\n }\n }\n\n if (isGradient || entry === \"none\") {\n return entry;\n }\n\n return entry;\n}\n\n\n/**\n * Creates a promise that resolves after the specified delay\n * @param {number} [ms=0] - Milliseconds to delay\n * @returns {Promise} Promise that resolves after the delay\n */\n\nexport function idle(fn, { fast = false } = {}) {\n if (fast) return fn();\n if ('requestIdleCallback' in window) {\n requestIdleCallback(fn, { timeout: 50 });\n } else {\n setTimeout(fn, 1);\n }\n}\n/**\n * Gets the computed style for an element or pseudo-element, with caching.\n *\n * @param {Element} el - The element\n * @param {string|null} [pseudo=null] - The pseudo-element\n * @returns {CSSStyleDeclaration} The computed style\n */\nexport function getStyle(el, pseudo = null) {\n if (!(el instanceof Element)) {\n return window.getComputedStyle(el, pseudo);\n }\n\n let map = cache.computedStyle.get(el);\n if (!map) {\n map = new Map();\n cache.computedStyle.set(el, map);\n }\n\n if (!map.has(pseudo)) {\n const st = window.getComputedStyle(el, pseudo);\n map.set(pseudo, st);\n }\n\n return map.get(pseudo);\n}\n/**\n * Parses the CSS content property value, handling unicode escapes.\n *\n * @param {string} content - The CSS content value\n * @returns {string} The parsed content\n */\nexport function parseContent(content) {\n let clean = content.replace(/^['\"]|['\"]$/g, \"\");\n if (clean.startsWith(\"\\\\\")) {\n try {\n return String.fromCharCode(parseInt(clean.replace(\"\\\\\", \"\"), 16));\n } catch {\n return clean;\n }\n }\n return clean;\n}\n/**\n * Extracts a URL from a CSS value like background-image.\n *\n * @param {string} value - The CSS value\n * @returns {string|null} The extracted URL or null\n */\n\nexport function extractURL(value) {\n const match = value.match(/url\\((['\"]?)(.*?)(\\1)\\)/);\n if (!match) return null;\n\n const url = match[2].trim();\n if (url.startsWith('#')) return null;\n return url;\n}\n\n/**\n * Determines if a font family or URL is an icon font.\n *\n * @param {string} familyOrUrl - The font family or URL\n * @returns {boolean} True if it is an icon font\n */\nexport function isIconFont(familyOrUrl) {\n const iconFontPatterns = [\n /font\\s*awesome/i,\n /material\\s*icons/i,\n /ionicons/i,\n /glyphicons/i,\n /feather/i,\n /bootstrap\\s*icons/i,\n /remix\\s*icons/i,\n /heroicons/i,\n /layui/i,\n /lucide/i\n ];\n return iconFontPatterns.some(rx => rx.test(familyOrUrl));\n}\n/**\n *\n *\n * @export\n * @param {*} src\n * @param {number} [timeout=3000]\n * @return {*} \n */\n\nexport function fetchImage(src, { timeout = 3000, useProxy = '' } = {}) {\n function getCrossOriginMode(url) {\n try {\n const parsed = new URL(url, window.location.href);\n return parsed.origin === window.location.origin ? \"use-credentials\" : \"anonymous\";\n } catch {\n return \"anonymous\";\n }\n }\n\n // Función común para fallback vía fetch + proxy\n async function fetchWithFallback(url) {\n const fetchBlobAsDataURL = (fetchUrl) =>\n fetch(fetchUrl, {\n mode: \"cors\",\n credentials: getCrossOriginMode(fetchUrl) === \"use-credentials\" ? \"include\" : \"omit\",\n })\n .then(r => r.blob())\n .then(blob => new Promise((resolve, reject) => {\n const reader = new FileReader();\n reader.onloadend = () => {\n const base64 = reader.result;\n if (typeof base64 !== \"string\" || !base64.startsWith(\"data:image/\")) {\n reject(new Error(\"Invalid image data URL\"));\n return;\n }\n resolve(base64);\n };\n reader.onerror = () => reject(new Error(\"FileReader error\"));\n reader.readAsDataURL(blob);\n }));\n\n try {\n return await fetchBlobAsDataURL(url);\n } catch (e) {\n if (useProxy && typeof useProxy === \"string\") {\n const proxied = useProxy.replace(/\\/$/, \"\") + safeEncodeURI(url);\n try {\n return await fetchBlobAsDataURL(proxied);\n } catch {\n \n throw new Error(\"[SnapDOM - fetchImage] CORS restrictions prevented image capture (even via proxy)\");\n }\n } else {\n \n throw new Error(\"[SnapDOM - fetchImage] Fetch fallback failed and no proxy provided\");\n }\n }\n }\n\n const crossOriginValue = getCrossOriginMode(src);\n\n if (cache.image.has(src)) {\n return Promise.resolve(cache.image.get(src));\n }\n\n // Detectamos si es un data URI, si sí, devolvemos directo sin fetch\n const isDataURI = src.startsWith(\"data:image/\");\n if (isDataURI) {\n cache.image.set(src, src);\n return Promise.resolve(src);\n }\n\n // Mejor detección SVG, incluyendo query strings\n const isSVG = /\\.svg(\\?.*)?$/i.test(src);\n\n if (isSVG) {\n return (async () => {\n try {\n const response = await fetch(src, {\n mode: \"cors\",\n credentials: crossOriginValue === \"use-credentials\" ? \"include\" : \"omit\"\n });\n const svgText = await response.text();\n const encoded = `data:image/svg+xml;charset=utf-8,${encodeURIComponent(svgText)}`;\n cache.image.set(src, encoded);\n return encoded;\n } catch {\n return fetchWithFallback(src);\n }\n })();\n }\n\n return new Promise((resolve, reject) => {\n const timeoutId = setTimeout(() => {\n reject(new Error(\"[SnapDOM - fetchImage] Image load timed out\"));\n }, timeout);\n\n const image = new Image();\n image.crossOrigin = crossOriginValue;\n\n image.onload = async () => {\n clearTimeout(timeoutId);\n try {\n await image.decode();\n const canvas = document.createElement(\"canvas\");\n canvas.width = image.width;\n canvas.height = image.height;\n const ctx = canvas.getContext(\"2d\");\n ctx.drawImage(image, 0, 0, canvas.width, canvas.height);\n const dataURL = canvas.toDataURL(\"image/png\");\n cache.image.set(src, dataURL);\n resolve(dataURL);\n } catch {\n try {\n const fallbackDataURL = await fetchWithFallback(src);\n cache.image.set(src, fallbackDataURL);\n resolve(fallbackDataURL);\n } catch (e) {\n reject(e);\n }\n }\n };\n\n image.onerror = async () => {\n clearTimeout(timeoutId);\n console.error(`[SnapDOM - fetchImage] Image failed to load: ${src}`);\n try {\n const fallbackDataURL = await fetchWithFallback(src);\n cache.image.set(src, fallbackDataURL);\n resolve(fallbackDataURL);\n } catch (e) {\n reject(e);\n }\n };\n\n image.src = src;\n });\n}\n\n/**\n *\n *\n * @export\n * @param {*} style\n * @return {*} \n */\nexport function snapshotComputedStyle(style) {\n const snap = {};\n for (let prop of style) {\n snap[prop] = style.getPropertyValue(prop);\n }\n return snap;\n}\n\nexport function isSafari() {\n return /^((?!chrome|android).)*safari/i.test(navigator.userAgent);\n}\n\nexport function stripTranslate(transform) {\n if (!transform || transform === 'none') return '';\n\n let cleaned = transform.replace(/translate[XY]?\\([^)]*\\)/g, '');\n\n cleaned = cleaned.replace(/matrix\\(([^)]+)\\)/g, (_, values) => {\n const parts = values.split(',').map(s => s.trim());\n if (parts.length !== 6) return `matrix(${values})`;\n parts[4] = '0';\n parts[5] = '0';\n return `matrix(${parts.join(', ')})`;\n });\n\n cleaned = cleaned.replace(/matrix3d\\(([^)]+)\\)/g, (_, values) => {\n const parts = values.split(',').map(s => s.trim());\n if (parts.length !== 16) return `matrix3d(${values})`;\n parts[12] = '0';\n parts[13] = '0';\n return `matrix3d(${parts.join(', ')})`;\n });\n\n return cleaned.trim().replace(/\\s{2,}/g, ' ');\n}\n\nexport function safeEncodeURI(uri) {\n if (/%[0-9A-Fa-f]{2}/.test(uri)) return uri; // prevent reencode\n try {\n return encodeURI(uri);\n } catch {\n return uri;\n }\n}\n\nexport function splitBackgroundImage(bg) {\n const parts = [];\n let depth = 0;\n let lastIndex = 0;\n for (let i = 0; i < bg.length; i++) {\n const char = bg[i];\n if (char === '(') depth++;\n if (char === ')') depth--;\n if (char === ',' && depth === 0) {\n parts.push(bg.slice(lastIndex, i).trim());\n lastIndex = i + 1;\n }\n }\n parts.push(bg.slice(lastIndex).trim());\n return parts;\n}\n\n"], ["/snapdom/__tests__/cssTools.utils.test.js", "import { describe, it, expect } from 'vitest';\nimport { getStyleKey, collectUsedTagNames, getDefaultStyleForTag } from '../src/utils/cssTools.js';\n\ndescribe('getStyleKey', () => {\n it('generates a non-empty style key', () => {\n const snapshot = { color: 'red', 'font-size': '12px' };\n const key = getStyleKey(snapshot, 'div');\n expect(typeof key).toBe('string');\n expect(key.length).toBeGreaterThan(0);\n });\n\n it('getStyleKey works with compress true', () => {\n const snapshot = { color: 'red', 'font-size': '12px' };\n const key = getStyleKey(snapshot, 'div', true);\n expect(typeof key).toBe('string');\n });\n});\n\ndescribe('collectUsedTagNames', () => {\n it('returns unique tag names', () => {\n const root = document.createElement('div');\n root.innerHTML = '

';\n const tags = collectUsedTagNames(root);\n expect(tags).toContain('div');\n expect(tags).toContain('span');\n expect(tags).toContain('p');\n });\n});\n\ndescribe('getDefaultStyleForTag', () => {\n it('returns a default style object', () => {\n const defaults = getDefaultStyleForTag('div');\n expect(typeof defaults).toBe('object');\n });\n\n it('getDefaultStyleForTag skips special tags', () => {\n expect(getDefaultStyleForTag('script')).toEqual({});\n });\n});\n"], ["/snapdom/src/utils/cssTools.js", "/**\n * Utilities for working with CSS styles, defaults, and class generation.\n * @module cssTools\n */\n\nimport { cache } from \"../core/cache\"\n\nconst commonTags = [\n 'div', 'span', 'p', 'a', 'img', 'ul', 'li', 'button', 'input',\n 'select', 'textarea', 'label', 'section', 'article', 'header',\n 'footer', 'nav', 'main', 'aside', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6',\n 'svg', 'path', 'circle', 'rect', 'line', 'g', 'table', 'thead', 'tbody', 'tr', 'td', 'th'\n];\n\nexport function precacheCommonTags() {\n for (let tag of commonTags) {\n getDefaultStyleForTag(tag);\n }\n}\n/**\n * Retrieves default CSS property values from a temporary element.\n *\n * @param {string} tagName - The tag name to get default styles for\n * @returns {Object} Object containing default values for all CSS properties\n */\nexport function getDefaultStyleForTag(tagName) {\n if (cache.defaultStyle.has(tagName)) {\n return cache.defaultStyle.get(tagName);\n }\n\n const skipTags = new Set(['script', 'style', 'meta', 'link', 'noscript', 'template']);\n if (skipTags.has(tagName)) {\n const empty = {}; \n cache.defaultStyle.set(tagName, empty); \n return empty;\n }\n\n let sandbox = document.getElementById('snapdom-sandbox');\n if (!sandbox) {\n sandbox = document.createElement('div');\n sandbox.id = 'snapdom-sandbox';\n sandbox.style.position = 'absolute';\n sandbox.style.left = '-9999px';\n sandbox.style.top = '-9999px';\n sandbox.style.width = '0';\n sandbox.style.height = '0';\n sandbox.style.overflow = 'hidden';\n document.body.appendChild(sandbox);\n }\n\n const el = document.createElement(tagName);\n el.style.all = 'initial';\n sandbox.appendChild(el);\n\n const styles = getComputedStyle(el);\n const defaults = {};\n for (let prop of styles) {\n defaults[prop] = styles.getPropertyValue(prop);\n }\n\n sandbox.removeChild(el);\n cache.defaultStyle.set(tagName, defaults);\n return defaults;\n}\n\n/**\n * Creates a unique key from an element's computed style that differs from defaults.\n *\n * @param {Object} snapshot - Computed style snapshot\n * @param {string} tagName - The tag name of the element\n * @param {boolean} [compress=false] - Whether to compress style keys\n * @returns {string} Semi-colon separated list of non-default properties\n */\n\nexport function getStyleKey(snapshot, tagName, compress = false) {\n const entries = [];\n const defaultStyles = getDefaultStyleForTag(tagName);\n for (let [prop, value] of Object.entries(snapshot)) {\n if (!compress) {\n if (value) {\n entries.push(`${prop}:${value}`);\n }\n } else {\n const defaultValue = defaultStyles[prop];\n if (value && value !== defaultValue) {\n entries.push(`${prop}:${value}`);\n }\n }\n }\n\n return entries.sort().join(\";\");\n}\n\n/**\n * Collects all unique tag names used in the DOM tree rooted at the given node.\n *\n * @param {Node} root - The root node to search\n * @returns {string[]} Array of unique tag names\n */\nexport function collectUsedTagNames(root) {\n const tagSet = new Set();\n if (root.nodeType !== Node.ELEMENT_NODE && root.nodeType !== Node.DOCUMENT_FRAGMENT_NODE) {\n return [];\n }\n if (root.tagName) {\n tagSet.add(root.tagName.toLowerCase());\n }\n if (typeof root.querySelectorAll === 'function') {\n root.querySelectorAll(\"*\").forEach(el => tagSet.add(el.tagName.toLowerCase()));\n }\n return Array.from(tagSet);\n}\n\n/**\n * Generates deduplicated base CSS for the given tag names.\n *\n * @param {string[]} usedTagNames - Array of tag names\n * @returns {string} CSS string\n */\nexport function generateDedupedBaseCSS(usedTagNames) {\n const groups = new Map();\n\n for (let tagName of usedTagNames) {\n const styles = cache.defaultStyle.get(tagName);\n if (!styles) continue;\n\n // Creamos la \"firma\" del bloque CSS para comparar\n const key = Object.entries(styles)\n .map(([k, v]) => `${k}:${v};`)\n .sort()\n .join('');\n\n // Agrupamos por firma\n if (!groups.has(key)) {\n groups.set(key, []);\n }\n groups.get(key).push(tagName);\n }\n\n // Ahora generamos el CSS optimizado\n let css = '';\n for (let [styleBlock, tagList] of groups.entries()) {\n css += `${tagList.join(',')} { ${styleBlock} }\\n`;\n }\n\n return css;\n}\n/**\n * Generates CSS classes from a style map.\n *\n * @returns {Map} Map of style keys to class names\n */\nexport function generateCSSClasses() {\n const keySet = new Set(cache.preStyleMap.values());\n const classMap = new Map();\n let counter = 1;\n for (const key of keySet) {\n classMap.set(key, `c${counter++}`);\n }\n return classMap;\n}\n"], ["/snapdom/__tests__/pseudo.bg-inline-success.test.js", "vi.mock('../src/utils/helpers.js', async () => {\n const actual = await vi.importActual('../src/utils/helpers.js');\n return {\n ...actual,\n inlineSingleBackgroundEntry: vi.fn().mockResolvedValue('url(\"data:image/png;base64,abc\")'),\n };\n});\n\nimport { describe, it, vi } from 'vitest';\nimport { inlinePseudoElements } from '../src/modules/pseudo.js';\n\ndescribe('inlinePseudoElements background-image inlining (success)', () => {\n it('cubre el inlining exitoso de background-image en pseudo', async () => {\n const el = document.createElement('div');\n const clone = document.createElement('div');\n vi.spyOn(window, 'getComputedStyle').mockImplementation((_, pseudo) => {\n if (pseudo === '::before') return {\n getPropertyValue: (prop) => prop === 'content' ? 'none' : prop === 'font-family' ? 'Arial' : prop === 'font-size' ? '32' : prop === 'font-weight' ? '400' : prop === 'color' ? '#000' : prop === 'background-image' ? 'url(\"data:image/png;base64,abc\")' : prop === 'background-color' ? 'transparent' : '',\n color: '#000', fontSize: '32px', fontWeight: '400', fontFamily: 'Arial',\n };\n return { getPropertyValue: () => '', color: '', fontSize: '', fontWeight: '', fontFamily: '' };\n });\n await inlinePseudoElements(el, clone, new Map(), new WeakMap(), false);\n window.getComputedStyle.mockRestore();\n });\n});\n"], ["/snapdom/__tests__/pseudo.bg-inline-error.test.js", "vi.mock('../src/utils/helpers.js', async () => {\n const actual = await vi.importActual('../src/utils/helpers.js');\n return {\n ...actual,\n inlineSingleBackgroundEntry: vi.fn().mockRejectedValue(new Error('fail')),\n };\n});\n\nimport { describe, it, vi } from 'vitest';\nimport { inlinePseudoElements } from '../src/modules/pseudo.js';\n\ndescribe('inlinePseudoElements background-image inlining (error)', () => {\n it('cubre el catch de error en inlining de background-image en pseudo', async () => {\n const el = document.createElement('div');\n const clone = document.createElement('div');\n vi.spyOn(window, 'getComputedStyle').mockImplementation((_, pseudo) => {\n if (pseudo === '::before') return {\n getPropertyValue: (prop) => prop === 'content' ? 'none' : prop === 'font-family' ? 'Arial' : prop === 'font-size' ? '32' : prop === 'font-weight' ? '400' : prop === 'color' ? '#000' : prop === 'background-image' ? 'url(\"data:image/png;base64,abc\")' : prop === 'background-color' ? 'transparent' : '',\n color: '#000', fontSize: '32px', fontWeight: '400', fontFamily: 'Arial',\n };\n return { getPropertyValue: () => '', color: '', fontSize: '', fontWeight: '', fontFamily: '' };\n });\n await inlinePseudoElements(el, clone, new Map(), new WeakMap(), false);\n window.getComputedStyle.mockRestore();\n });\n});\n"], ["/snapdom/src/core/capture.js", "/**\n * Core logic for capturing DOM elements as SVG data URLs.\n * @module capture\n */\n\nimport { prepareClone } from './prepare.js';\nimport { inlineImages } from '../modules/images.js';\nimport { inlineBackgroundImages } from '../modules/background.js';\nimport { idle, isSafari } from '../utils/helpers.js';\nimport { collectUsedTagNames, generateDedupedBaseCSS } from '../utils/cssTools.js';\nimport { embedCustomFonts } from '../modules/fonts.js';\nimport { cache } from '../core/cache.js'\n\n/**\n * Captures an HTML element as an SVG data URL, inlining styles, images, backgrounds, and optionally fonts.\n *\n * @param {Element} element - DOM element to capture\n * @param {Object} [options={}] - Capture options\n * @param {boolean} [options.compress=true] - Whether to compress style keys\n * @param {boolean} [options.embedFonts=false] - Whether to embed custom fonts\n * @param {boolean} [options.fast=true] - Whether to skip idle delay for faster results\n * @param {number} [options.scale=1] - Output scale multiplier\n * @param {string[]} [options.exclude] - CSS selectors for elements to exclude\n * @param {Function} [options.filter] - Custom filter function \n * @returns {Promise} Promise that resolves to an SVG data URL\n */\n\nexport async function captureDOM(element, options = {}) {\n if (!element) throw new Error(\"Element cannot be null or undefined\");\n cache.reset()\n const { compress = true, embedFonts = false, fast = true, scale = 1, useProxy = ''} = options;\n let clone, classCSS;\n let fontsCSS = \"\";\n let baseCSS = \"\";\n let dataURL;\n let svgString;\n\n ({ clone, classCSS } = await prepareClone(element, compress, embedFonts, options));\n\n await new Promise((resolve) => {\n idle(async () => {\n await inlineImages(clone, options);\n resolve();\n }, { fast });\n });\n await new Promise((resolve) => {\n idle(async () => {\n await inlineBackgroundImages(element, clone, options);\n resolve();\n }, { fast });\n });\n if (embedFonts) {\n await new Promise((resolve) => {\n idle(async () => {\n fontsCSS = await embedCustomFonts();\n resolve();\n }, { fast });\n });\n }\n if (compress) {\n const usedTags = collectUsedTagNames(clone).sort();\n const tagKey = usedTags.join(\",\");\n if (cache.baseStyle.has(tagKey)) {\n baseCSS = cache.baseStyle.get(tagKey);\n } else {\n await new Promise((resolve) => {\n idle(() => {\n baseCSS = generateDedupedBaseCSS(usedTags);\n cache.baseStyle.set(tagKey, baseCSS);\n resolve();\n }, { fast });\n });\n }\n }\n await new Promise((resolve) => {\n idle(() => {\n const rect = element.getBoundingClientRect();\n let w = rect.width;\n let h = rect.height;\n const hasW = Number.isFinite(options.width);\n const hasH = Number.isFinite(options.height);\n const hasScale = typeof scale === \"number\" && scale !== 1;\n if (!hasScale) {\n const aspect = rect.width / rect.height;\n if (hasW && hasH) {\n w = options.width;\n h = options.height;\n } else if (hasW) {\n w = options.width;\n h = w / aspect;\n } else if (hasH) {\n h = options.height;\n w = h * aspect;\n }\n }\n w = Math.ceil(w);\n h = Math.ceil(h);\n clone.setAttribute(\"xmlns\", \"http://www.w3.org/1999/xhtml\");\n clone.style.transformOrigin = \"top left\";\n if (!hasScale && (hasW || hasH)) {\n const originalW = rect.width;\n const originalH = rect.height;\n const scaleX = w / originalW;\n const scaleY = h / originalH;\n const existingTransform = clone.style.transform || \"\";\n const scaleTransform = `scale(${scaleX}, ${scaleY})`;\n clone.style.transform = `${scaleTransform} ${existingTransform}`.trim();\n }\n const svgNS = \"http://www.w3.org/2000/svg\";\n const fo = document.createElementNS(svgNS, \"foreignObject\");\n fo.setAttribute(\"width\", \"100%\");\n fo.setAttribute(\"height\", \"100%\");\n const styleTag = document.createElement(\"style\");\n styleTag.textContent = baseCSS + fontsCSS + \"svg{overflow:visible;}\" + classCSS;\n fo.appendChild(styleTag);\n fo.appendChild(clone);\n const serializer = new XMLSerializer();\n const foString = serializer.serializeToString(fo);\n const svgHeader = ``;\n const svgFooter = \"\";\n svgString = svgHeader + foString + svgFooter;\n dataURL = `data:image/svg+xml;charset=utf-8,${encodeURIComponent(svgString)}`;\n resolve();\n }, { fast });\n });\n const sandbox = document.getElementById(\"snapdom-sandbox\");\n if (sandbox && sandbox.style.position === \"absolute\") sandbox.remove();\n return dataURL;\n}\n\n"], ["/snapdom/__tests__/background.module.test.js", "import { describe, it, expect, beforeEach, afterEach } from 'vitest';\nimport { inlineBackgroundImages } from '../src/modules/background.js';\n\ndescribe('inlineBackgroundImages', () => {\n let source, clone;\n beforeEach(() => {\n source = document.createElement('div');\n clone = document.createElement('div');\n document.body.appendChild(source);\n document.body.appendChild(clone);\n });\n afterEach(() => {\n document.body.removeChild(source);\n document.body.removeChild(clone);\n });\n\n it('does not fail if there is no background-image', async () => {\n source.style.background = 'none';\n await expect(inlineBackgroundImages(source, clone, new WeakMap())).resolves.toBeUndefined();\n });\n\n it('processes a valid background-image', async () => {\n source.style.backgroundImage = 'url(\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/w8AAn8B9p6Q2wAAAABJRU5ErkJggg==\")';\n await expect(inlineBackgroundImages(source, clone, new WeakMap())).resolves.toBeUndefined();\n });\n});\n"], ["/snapdom/src/modules/fonts.js", "/**\n * Utilities for handling and embedding web fonts and icon fonts.\n * @module fonts\n */\n\nimport { extractURL} from \"../utils/helpers\"\nimport { cache } from \"../core/cache\"\nimport { isIconFont } from '../modules/iconFonts.js';\n\n/**\n * Converts a unicode character from an icon font into a data URL image.\n *\n * @export\n * @param {string} unicodeChar - The unicode character to render\n * @param {string} fontFamily - The font family name\n * @param {string|number} fontWeight - The font weight\n * @param {number} [fontSize=32] - The font size in pixels\n * @param {string} [color=\"#000\"] - The color to use\n * @returns {Promise} Data URL of the rendered icon\n */\n\nexport async function iconToImage(unicodeChar, fontFamily, fontWeight, fontSize = 32, color = \"#000\") {\n fontFamily = fontFamily.replace(/^['\"]+|['\"]+$/g, \"\");\n const dpr = window.devicePixelRatio || 1;\n\n // Create temporary context to measure\n const tempCanvas = document.createElement(\"canvas\");\n const tempCtx = tempCanvas.getContext(\"2d\");\n tempCtx.font = fontWeight\n ? `${fontWeight} ${fontSize}px \"${fontFamily}\"`\n : `${fontSize}px \"${fontFamily}\"`;\n\n const metrics = tempCtx.measureText(unicodeChar);\n const ascent = metrics.actualBoundingBoxAscent || fontSize * 0.8;\n const descent = metrics.actualBoundingBoxDescent || fontSize * 0.2;\n const height = ascent + descent;\n const width = metrics.width;\n\n const canvas = document.createElement(\"canvas\");\n canvas.width = Math.ceil(width * dpr);\n canvas.height = Math.ceil(height * dpr);\n\n const ctx = canvas.getContext(\"2d\");\n ctx.scale(dpr, dpr);\n ctx.font = tempCtx.font;\n ctx.textAlign = \"left\";\n ctx.textBaseline = \"alphabetic\"; // aligns with baseline\n ctx.fillStyle = color;\n\n // Draw at (0, ascent) so the full glyph fits vertically\n ctx.fillText(unicodeChar, 0, ascent);\n\n return canvas.toDataURL();\n}\n\n\nfunction isStylesheetLoaded(href) {\n return Array.from(document.styleSheets).some(sheet => sheet.href === href);\n}\n\nfunction injectLinkIfMissing(href) {\n return new Promise((resolve) => {\n if (isStylesheetLoaded(href)) return resolve(null);\n const link = document.createElement(\"link\");\n link.rel = \"stylesheet\";\n link.href = href;\n link.setAttribute(\"data-snapdom\", \"injected-import\");\n link.onload = () => resolve(link);\n link.onerror = () => resolve(null);\n document.head.appendChild(link);\n });\n}\n\n/**\n * Embeds custom fonts found in the document as data URLs in CSS.\n *\n * @export\n * @param {Object} options\n * @param {boolean} [options.preCached=false] - Whether to use pre-cached resources\n * @returns {Promise} The inlined CSS for custom fonts\n */\n\nexport async function embedCustomFonts({preCached = false } = {}) {\n if (cache.resource.has(\"fonts-embed-css\")) {\n if (preCached) {\n const style = document.createElement(\"style\");\n style.setAttribute(\"data-snapdom\", \"embedFonts\");\n style.textContent = cache.resource.get(\"fonts-embed-css\");\n document.head.appendChild(style);\n }\n return cache.resource.get(\"fonts-embed-css\");\n }\n\n const importRegex = /@import\\s+url\\([\"']?([^\"')]+)[\"']?\\)/g;\n const styleImports = [];\n\n for (const styleTag of document.querySelectorAll(\"style\")) {\n const cssText = styleTag.textContent || \"\";\n const matches = Array.from(cssText.matchAll(importRegex));\n for (const match of matches) {\n const importUrl = match[1];\n if (isIconFont(importUrl)) continue;\n if (!isStylesheetLoaded(importUrl)) {\n styleImports.push(importUrl);\n }\n }\n }\n\n await Promise.all(styleImports.map(injectLinkIfMissing));\n\n const links = Array.from(document.querySelectorAll('link[rel=\"stylesheet\"]')).filter((link) => link.href);\n let finalCSS = \"\";\n\n for (const link of links) {\n try {\n const res = await fetch(link.href);\n const cssText = await res.text();\n\n if ((isIconFont(link.href) || isIconFont(cssText))) continue;\n\n const urlRegex = /url\\(([\"']?)([^\"')]+)\\1\\)/g;\n const inlinedCSS = await Promise.all(\n Array.from(cssText.matchAll(urlRegex)).map(async (match) => {\n let rawUrl = extractURL(match[0]);\n if (!rawUrl) return null;\n let url = rawUrl;\n if (!url.startsWith(\"http\") && !url.startsWith(\"data:\")) {\n url = new URL(url, link.href).href;\n }\n if (isIconFont(url)) return null;\n if (cache.resource.has(url)) {\n cache.font.add(url);\n return { original: match[0], inlined: `url(${cache.resource.get(url)})` };\n }\n if (cache.font.has(url)) return null;\n try {\n const fontRes = await fetch(url);\n const blob = await fontRes.blob();\n const b64 = await new Promise((resolve) => {\n const reader = new FileReader();\n reader.onload = () => resolve(reader.result);\n reader.readAsDataURL(blob);\n });\n cache.resource.set(url, b64);\n cache.font.add(url);\n return { original: match[0], inlined: `url(${b64})` };\n } catch (e) {\n console.warn(\"[snapdom] Failed to fetch font resource:\", url);\n return null;\n }\n })\n );\n\n let cssFinal = cssText;\n for (const r of inlinedCSS) {\n if (r) cssFinal = cssFinal.replace(r.original, r.inlined);\n }\n finalCSS += cssFinal + \"\\n\";\n } catch (e) {\n console.warn(\"[snapdom] Failed to fetch CSS:\", link.href);\n }\n }\n\n for (const sheet of document.styleSheets) {\n try {\n if (!sheet.href || links.every((link) => link.href !== sheet.href)) {\n for (const rule of sheet.cssRules) {\n if (rule.type === CSSRule.FONT_FACE_RULE) {\n const src = rule.style.getPropertyValue(\"src\");\n const family = rule.style.getPropertyValue(\"font-family\");\n if (!src || isIconFont(family)) continue;\n\n const urlRegex = /url\\(([\"']?)([^\"')]+)\\1\\)/g;\n const localRegex = /local\\(([\"']?)[^)]+?\\1\\)/g;\n const hasURL = !!src.match(urlRegex);\n const hasLocal = !!src.match(localRegex);\n\n if (!hasURL && hasLocal) {\n // Solo local(), conservar en línea compacta\n finalCSS += `@font-face{font-family:${family};src:${src};font-style:${rule.style.getPropertyValue(\"font-style\") || \"normal\"};font-weight:${rule.style.getPropertyValue(\"font-weight\") || \"normal\"};}`;\n continue;\n }\n\n // Embebido para src con url()\n let inlinedSrc = src;\n const matches = Array.from(src.matchAll(urlRegex));\n for (const match of matches) {\n let rawUrl = match[2].trim();\n if (!rawUrl) continue;\n let url = rawUrl;\n if (!url.startsWith(\"http\") && !url.startsWith(\"data:\")) {\n url = new URL(url, sheet.href || location.href).href;\n }\n if (isIconFont(url)) continue;\n if (cache.resource.has(url)) {\n cache.font.add(url);\n inlinedSrc = inlinedSrc.replace(match[0], `url(${cache.resource.get(url)})`);\n continue;\n }\n if (cache.font.has(url)) continue;\n try {\n const res = await fetch(url);\n const blob = await res.blob();\n const b64 = await new Promise((resolve) => {\n const reader = new FileReader();\n reader.onload = () => resolve(reader.result);\n reader.readAsDataURL(blob);\n });\n cache.resource.set(url, b64);\n cache.font.add(url);\n inlinedSrc = inlinedSrc.replace(match[0], `url(${b64})`);\n } catch (e) {\n console.warn(\"[snapdom] Failed to fetch font URL:\", url);\n }\n }\n\n finalCSS += `@font-face{font-family:${family};src:${inlinedSrc};font-style:${rule.style.getPropertyValue(\"font-style\") || \"normal\"};font-weight:${rule.style.getPropertyValue(\"font-weight\") || \"normal\"};}`;\n }\n }\n }\n } catch (e) {\n console.warn(\"[snapdom] Cannot access stylesheet\", sheet.href, e);\n }\n }\n\n for (const font of document.fonts) {\n if (font.family && font.status === \"loaded\" && font._snapdomSrc) {\n if (isIconFont(font.family)) continue;\n let b64 = font._snapdomSrc;\n if (!b64.startsWith(\"data:\")) {\n if (cache.resource.has(font._snapdomSrc)) {\n b64 = cache.resource.get(font._snapdomSrc);\n cache.font.add(font._snapdomSrc);\n } else if (!cache.font.has(font._snapdomSrc)) {\n try {\n const res = await fetch(font._snapdomSrc);\n const blob = await res.blob();\n b64 = await new Promise((resolve) => {\n const reader = new FileReader();\n reader.onload = () => resolve(reader.result);\n reader.readAsDataURL(blob);\n });\n cache.resource.set(font._snapdomSrc, b64);\n cache.font.add(font._snapdomSrc);\n } catch (e) {\n console.warn(\"[snapdom] Failed to fetch dynamic font src:\", font._snapdomSrc);\n continue;\n }\n }\n }\n\n finalCSS += `@font-face{font-family:'${font.family}';src:url(${b64});font-style:${font.style || \"normal\"};font-weight:${font.weight || \"normal\"};}`;\n }\n }\n\n if (finalCSS) {\n cache.resource.set(\"fonts-embed-css\", finalCSS);\n if (preCached) {\n const style = document.createElement(\"style\");\n style.setAttribute(\"data-snapdom\", \"embedFonts\");\n style.textContent = finalCSS;\n document.head.appendChild(style);\n }\n }\n\n return finalCSS;\n}\n"], ["/snapdom/src/core/clone.js", "/**\n * Deep cloning utilities for DOM elements, including styles and shadow DOM.\n * @module clone\n */\n\nimport { inlineAllStyles } from '../modules/styles.js';\nimport { cache } from '../core/cache.js'\n\n/**\n * Creates a deep clone of a DOM node, including styles, shadow DOM, and special handling for excluded/placeholder/canvas nodes.\n *\n * @param {Node} node - Node to clone\n * @param {boolean} compress - Whether to compress style keys\n * @param {Object} [options={}] - Capture options including exclude and filter \n * @param {Node} [originalRoot] - Original root element being captured\n * @returns {Node|null} Cloned node with styles and shadow DOM content, or null for empty text nodes or filtered elements\n */\n\n \nexport function deepClone(node, compress, options = {}, originalRoot) {\n if (!node) throw new Error('Invalid node');\n\n // Local set to avoid duplicates in slot processing\n const clonedAssignedNodes = new Set();\n let pendingSelectValue = null; // Track select value for later fix\n\n // 1. Text nodes\n if (node.nodeType === Node.TEXT_NODE) {\n return node.cloneNode(true);\n }\n\n // 2. Non-element nodes (comments, etc.)\n if (node.nodeType !== Node.ELEMENT_NODE) {\n return node.cloneNode(true);\n }\n\n // 3. Exclude by attribute\n if (node.getAttribute(\"data-capture\") === \"exclude\") {\n const spacer = document.createElement(\"div\");\n const rect = node.getBoundingClientRect();\n spacer.style.cssText = `display:inline-block;width:${rect.width}px;height:${rect.height}px;visibility:hidden;`;\n return spacer;\n }\n\n // 4. Exclude by selectors\n if (options.exclude && Array.isArray(options.exclude)) {\n for (const selector of options.exclude) {\n try {\n if (node.matches?.(selector)) {\n const spacer = document.createElement(\"div\");\n const rect = node.getBoundingClientRect();\n spacer.style.cssText = `display:inline-block;width:${rect.width}px;height:${rect.height}px;visibility:hidden;`;\n return spacer;\n }\n } catch (err) {\n console.warn(`Invalid selector in exclude option: ${selector}`, err);\n }\n }\n }\n\n // 5. Custom filter function\n if (typeof options.filter === \"function\") {\n try {\n if (!options.filter(node, originalRoot || node)) {\n const spacer = document.createElement(\"div\");\n const rect = node.getBoundingClientRect();\n spacer.style.cssText = `display:inline-block;width:${rect.width}px;height:${rect.height}px;visibility:hidden;`;\n return spacer;\n }\n } catch (err) {\n console.warn(\"Error in filter function:\", err);\n }\n }\n\n // 6. Special case: iframe → fallback pattern\n if (node.tagName === \"IFRAME\") {\n const fallback = document.createElement(\"div\");\n 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;`;\n return fallback;\n }\n\n // 7. Placeholder nodes\n if (node.getAttribute(\"data-capture\") === \"placeholder\") {\n const clone2 = node.cloneNode(false);\n cache.preNodeMap.set(clone2, node);\n inlineAllStyles(node, clone2, compress);\n const placeholder = document.createElement(\"div\");\n placeholder.textContent = node.getAttribute(\"data-placeholder-text\") || \"\";\n placeholder.style.cssText = `color:#666;font-size:12px;text-align:center;line-height:1.4;padding:0.5em;box-sizing:border-box;`;\n clone2.appendChild(placeholder);\n return clone2;\n }\n\n // 8. Canvas → convert to image\n if (node.tagName === \"CANVAS\") {\n const dataURL = node.toDataURL();\n const img = document.createElement(\"img\");\n img.src = dataURL;\n img.width = node.width;\n img.height = node.height;\n cache.preNodeMap.set(img, node);\n inlineAllStyles(node, img, compress);\n return img;\n }\n\n // 9. Base clone (without children)\n let clone;\n try {\n clone = node.cloneNode(false);\n cache.preNodeMap.set(clone, node);\n } catch (err) {\n console.error(\"[Snapdom] Failed to clone node:\", node, err);\n throw err;\n }\n\n // Special handling: textarea (keep size and value)\n if (node instanceof HTMLTextAreaElement) {\n clone.textContent = node.value;\n clone.value = node.value;\n const rect = node.getBoundingClientRect();\n clone.style.width = `${rect.width}px`;\n clone.style.height = `${rect.height}px`;\n return clone;\n }\n\n // Special handling: input\n if (node instanceof HTMLInputElement) {\n clone.value = node.value;\n clone.setAttribute(\"value\", node.value);\n if (node.checked !== void 0) {\n clone.checked = node.checked;\n if (node.checked) clone.setAttribute(\"checked\", \"\");\n if (node.indeterminate) clone.indeterminate = node.indeterminate;\n }\n // return clone;\n }\n\n // Special handling: select → postpone value adjustment\n if (node instanceof HTMLSelectElement) {\n pendingSelectValue = node.value;\n }\n\n // 11. Inline styles\n inlineAllStyles(node, clone, compress);\n\n // 12. ShadowRoot logic\n if (node.shadowRoot) {\n const hasSlot = Array.from(node.shadowRoot.querySelectorAll(\"slot\")).length > 0;\n\n if (hasSlot) {\n // ShadowRoot with slots: only store styles\n for (const child of node.shadowRoot.childNodes) {\n if (child.nodeType === Node.ELEMENT_NODE && child.tagName === \"STYLE\") {\n const cssText = child.textContent || \"\";\n if (cssText.trim() && compress) {\n if (!cache.preStyle) cache.preStyle = new WeakMap();\n cache.preStyle.set(child, cssText);\n }\n }\n }\n } else {\n // ShadowRoot without slots: clone full content\n const shadowFrag = document.createDocumentFragment();\n for (const child of node.shadowRoot.childNodes) {\n if (child.nodeType === Node.ELEMENT_NODE && child.tagName === \"STYLE\") {\n const cssText = child.textContent || \"\";\n if (cssText.trim() && compress) {\n if (!cache.preStyle) cache.preStyle = new WeakMap();\n cache.preStyle.set(child, cssText);\n }\n continue;\n }\n const clonedChild = deepClone(child, compress, options, originalRoot || node);\n if (clonedChild) shadowFrag.appendChild(clonedChild);\n }\n clone.appendChild(shadowFrag);\n }\n }\n\n // 13. Slot outside ShadowRoot\n if (node.tagName === \"SLOT\") {\n const assigned = node.assignedNodes?.({ flatten: true }) || [];\n const nodesToClone = assigned.length > 0 ? assigned : Array.from(node.childNodes);\n const fragment = document.createDocumentFragment();\n\n for (const child of nodesToClone) {\n const clonedChild = deepClone(child, compress, options, originalRoot || node);\n if (clonedChild) fragment.appendChild(clonedChild);\n }\n return fragment;\n }\n\n // 14. Clone children (light DOM), skipping duplicates\n for (const child of node.childNodes) {\n if (clonedAssignedNodes.has(child)) continue;\n\n const clonedChild = deepClone(child, compress, options, originalRoot || node);\n if (clonedChild) clone.appendChild(clonedChild);\n }\n\n // Adjust select value after children are cloned\n if (pendingSelectValue !== null && clone instanceof HTMLSelectElement) {\n clone.value = pendingSelectValue;\n for (const opt of clone.options) {\n if (opt.value === pendingSelectValue) {\n opt.setAttribute(\"selected\", \"\");\n } else {\n opt.removeAttribute(\"selected\");\n }\n }\n }\n\n return clone;\n} \n"], ["/snapdom/__tests__/styles.module.test.js", "import { describe, it, expect } from 'vitest';\nimport { inlineAllStyles } from '../src/modules/styles.js';\nimport { cache } from '../src/core/cache.js';\n\ndescribe('inlineAllStyles', () => {\n it('adds a style key to the styleMap', () => {\n const el = document.createElement('div');\n const clone = document.createElement('div');\n inlineAllStyles(el, clone, false);\n expect(cache.preStyleMap.has(clone)).toBe(true);\n });\n});"], ["/snapdom/src/modules/images.js", "/**\n * Utilities for inlining elements as data URLs or placeholders.\n * @module images\n */\n\nimport { fetchImage } from '../utils/helpers.js';\n\n/**\n * Converts all elements in the clone to data URLs or replaces them with placeholders if loading fails.\n *\n * @param {Element} clone - Clone of the original element\n * @param {Object} [options={}] - Options for image processing\n * @returns {Promise} Promise that resolves when all images are processed\n */\nexport async function inlineImages(clone, options = {}) {\n const imgs = Array.from(clone.querySelectorAll(\"img\"));\n const processImg = async (img) => {\n const src = img.src;\n try {\n const dataUrl = await fetchImage(src, { useProxy: options.useProxy });\n img.src = dataUrl;\n if (!img.width) img.width = img.naturalWidth || 100;\n if (!img.height) img.height = img.naturalHeight || 100;\n } catch {\n const fallback = document.createElement(\"div\");\n fallback.style = `width: ${img.width || 100}px; height: ${img.height || 100}px; background: #ccc; display: inline-block; text-align: center; line-height: ${img.height || 100}px; color: #666; font-size: 12px;`;\n fallback.innerText = \"img\";\n img.replaceWith(fallback);\n }\n };\n for (let i = 0; i < imgs.length; i += 4) {\n const group = imgs.slice(i, i + 4).map(processImg);\n await Promise.allSettled(group);\n }\n}"], ["/snapdom/src/modules/pseudo.js", "/**\n * Utilities for inlining ::before and ::after pseudo-elements.\n * @module pseudo\n */\n\nimport { getStyle, snapshotComputedStyle, parseContent, extractURL, safeEncodeURI, fetchImage, inlineSingleBackgroundEntry, splitBackgroundImage } from '../utils/helpers.js';\nimport { getStyleKey } from '../utils/cssTools.js';\nimport { iconToImage } from '../modules/fonts.js';\nimport { isIconFont } from '../modules/iconFonts.js';\nimport { cache } from '../core/cache.js'\n\n/**\n * Creates elements to represent ::before, ::after, and ::first-letter pseudo-elements, inlining their styles and content.\n *\n * @param {Element} source - Original element\n * @param {Element} clone - Cloned element\n * @param {boolean} compress - Whether to compress style keys\n * @param {boolean} embedFonts - Whether to embed icon fonts as images\n * @returns {Promise} Promise that resolves when all pseudo-elements are processed\n */\n\nexport async function inlinePseudoElements(source, clone, compress, embedFonts = false, useProxy) {\n if (!(source instanceof Element) || !(clone instanceof Element)) return;\n for (const pseudo of [\"::before\", \"::after\", \"::first-letter\"]) {\n try {\n const style = getStyle(source, pseudo);\n if (!style || typeof style[Symbol.iterator] !== \"function\") continue;\n if (pseudo === \"::first-letter\") {\n const normal = getComputedStyle(source);\n const isMeaningful = style.color !== normal.color || style.fontSize !== normal.fontSize || style.fontWeight !== normal.fontWeight;\n if (!isMeaningful) continue;\n const textNode = Array.from(clone.childNodes).find(\n (n) => n.nodeType === Node.TEXT_NODE && n.textContent && n.textContent.trim().length > 0\n );\n if (!textNode) continue;\n const text = textNode.textContent;\n const match = text.match(/^([^\\p{L}\\p{N}\\s]*[\\p{L}\\p{N}](?:['’])?)/u);\n const first = match?.[0];\n const rest = text.slice(first?.length || 0);\n if (!first || /[\\uD800-\\uDFFF]/.test(first)) continue;\n const span = document.createElement(\"span\");\n span.textContent = first;\n span.dataset.snapdomPseudo = \"::first-letter\";\n const snapshot = snapshotComputedStyle(style);\n const key = getStyleKey(snapshot, \"span\", compress);\n cache.preStyleMap.set(span, key);\n const restNode = document.createTextNode(rest);\n clone.replaceChild(restNode, textNode);\n clone.insertBefore(span, restNode);\n continue;\n }\nconst content = style.getPropertyValue(\"content\");\nconst bg = style.getPropertyValue(\"background-image\");\nconst bgColor = style.getPropertyValue(\"background-color\");\n\nconst fontFamily = style.getPropertyValue(\"font-family\");\nconst fontSize = parseInt(style.getPropertyValue(\"font-size\")) || 32;\nconst fontWeight = parseInt(style.getPropertyValue(\"font-weight\")) || false;\nconst color = style.getPropertyValue(\"color\") || \"#000\";\nconst display = style.getPropertyValue(\"display\");\nconst width = parseFloat(style.getPropertyValue(\"width\"));\nconst height = parseFloat(style.getPropertyValue(\"height\"));\nconst borderStyle = style.getPropertyValue(\"border-style\");\nconst transform = style.getPropertyValue(\"transform\");\n\nconst isIconFont2 = isIconFont(fontFamily);\n\n// Detect counter() || counters()\nlet cleanContent;\nif (/counter\\s*\\(|counters\\s*\\(/.test(content)) {\n cleanContent = \"- \";\n} else {\n cleanContent = parseContent(content);\n}\n\nconst hasContent = content !== \"none\";\nconst hasExplicitContent = hasContent && cleanContent !== \"\";\nconst hasBg = bg && bg !== \"none\";\nconst hasBgColor = bgColor && bgColor !== \"transparent\" && bgColor !== \"rgba(0, 0, 0, 0)\";\nconst hasBox = display !== \"inline\" && (width > 0 || height > 0);\nconst hasBorder = borderStyle && borderStyle !== \"none\";\nconst hasTransform = transform && transform !== \"none\";\n\nconst shouldRender =\n hasExplicitContent || hasBg || hasBgColor || hasBox || hasBorder || hasTransform;\n\nif (!shouldRender) continue;\n\nconst pseudoEl = document.createElement(\"span\");\npseudoEl.dataset.snapdomPseudo = pseudo;\nconst snapshot = snapshotComputedStyle(style);\nconst key = getStyleKey(snapshot, \"span\", compress);\ncache.preStyleMap.set(pseudoEl, key);\n\nif (isIconFont2 && cleanContent.length === 1) {\n const imgEl = document.createElement(\"img\");\n imgEl.src = await iconToImage(cleanContent, fontFamily, fontWeight, fontSize, color);\n imgEl.style = `width:${fontSize}px;height:auto;object-fit:contain;`;\n pseudoEl.appendChild(imgEl);\n} else if (cleanContent.startsWith(\"url(\")) {\n const rawUrl = extractURL(cleanContent);\n if (rawUrl && rawUrl.trim() !== \"\") {\n try {\n const imgEl = document.createElement(\"img\");\n const dataUrl = await fetchImage(safeEncodeURI(rawUrl, { useProxy }));\n imgEl.src = dataUrl;\n imgEl.style = `width:${fontSize}px;height:auto;object-fit:contain;`;\n pseudoEl.appendChild(imgEl);\n } catch (e) {\n console.error(`[snapdom] Error in pseudo ${pseudo} for`, source, e);\n }\n }\n} else if (!isIconFont2 && hasExplicitContent) {\n pseudoEl.textContent = cleanContent;\n}\n\nif (hasBg) {\n try {\n const bgSplits = splitBackgroundImage(bg);\n const newBgParts = await Promise.all(\n bgSplits.map((entry) => inlineSingleBackgroundEntry(entry))\n );\n pseudoEl.style.backgroundImage = newBgParts.join(\", \");\n } catch (e) {\n console.warn(`[snapdom] Failed to inline background-image for ${pseudo}`, e);\n }\n}\n\nif (hasBgColor) pseudoEl.style.backgroundColor = bgColor;\n\nconst hasContent2 =\n pseudoEl.childNodes.length > 0 ||\n (pseudoEl.textContent && pseudoEl.textContent.trim() !== \"\");\nconst hasVisibleBox = hasContent2 || hasBg || hasBgColor || hasBox || hasBorder || hasTransform;\n\nif (!hasVisibleBox) continue;\n\npseudo === \"::before\"\n ? clone.insertBefore(pseudoEl, clone.firstChild)\n : clone.appendChild(pseudoEl);\n\n } catch (e) {\n console.warn(`[snapdom] Failed to capture ${pseudo} for`, source, e);\n }\n }\n const sChildren = Array.from(source.children);\n const cChildren = Array.from(clone.children).filter((child) => !child.dataset.snapdomPseudo);\n for (let i = 0; i < Math.min(sChildren.length, cChildren.length); i++) {\n await inlinePseudoElements(\n sChildren[i],\n cChildren[i],\n compress,\n embedFonts,\n useProxy\n );\n }\n}\n"], ["/snapdom/src/api/preCache.js", "import { getStyle, inlineSingleBackgroundEntry, fetchImage, splitBackgroundImage } from '../utils/helpers.js';\nimport { embedCustomFonts } from '../modules/fonts.js';\nimport { precacheCommonTags } from '../utils/cssTools.js';\nimport { cache } from '../core/cache.js';\n\n/**\n * Preloads images, background images, and optionally fonts into cache before DOM capture.\n *\n * @param {Document|Element} [root=document] - The root node to search for resources\n * @param {Object} [options={}] - Pre-caching options\n * @returns {Promise} Resolves when all resources are pre-cached\n */\n\nexport async function preCache(root = document, options = {}) {\n const { embedFonts = true, reset = false} = options;\n if (reset) {\n cache.reset()\n return;\n }\n await document.fonts.ready;\n precacheCommonTags();\n let imgEls = [], allEls = [];\n if (root?.querySelectorAll) {\n imgEls = Array.from(root.querySelectorAll(\"img[src]\"));\n allEls = Array.from(root.querySelectorAll(\"*\"));\n }\n const promises = [];\n for (const img of imgEls) {\n const src = img.src;\n if (!cache.image.has(src)) {\n \n promises.push(\n fetchImage(src, { useProxy: options.useProxy}).then((dataURL) => cache.image.set(src, dataURL)).catch(() => {\n })\n );\n }\n }\n for (const el of allEls) {\n const bg = getStyle(el).backgroundImage;\n if (bg && bg !== \"none\") {\n const bgSplits = splitBackgroundImage(bg);\n for (const entry of bgSplits) {\n const isUrl = entry.startsWith(\"url(\");\n if (isUrl) {\n promises.push(\n inlineSingleBackgroundEntry(entry, options).catch(() => {\n })\n );\n }\n }\n }\n }\n if (embedFonts) {\n await embedCustomFonts({ preCached: true });\n }\n await Promise.all(promises);\n}\n"], ["/snapdom/src/modules/svgDefs.js", "/**\n * Inlines external `` used by `` or `` inside SVGs,\n * copying only the necessary definitions into each individual cloned SVG.\n *\n * This is needed because cloned SVGs using `` may reference elements like ``, ``, etc.,\n * defined elsewhere in the document (e.g., in a shared `` block that is not part of the cloned subtree).\n *\n * The function finds all `` elements within `root`, extracts the referenced IDs,\n * and embeds the required definitions at the top of each SVG.\n *\n * @function inlineExternalDef\n * @param {ParentNode} root - The root node containing cloned SVGs (usually the result of a DOM snapshot).\n * @returns {void}\n *\n * @example\n * const { clone } = await prepareClone(element);\n * inlineExternalDef(clone);\n */\n\nexport function inlineExternalDef(root) {\n if (!root) return;\n const defsSources = document.querySelectorAll('svg > defs');\n if (!defsSources.length) return;\n\n root.querySelectorAll('svg').forEach(svg => {\n const uses = svg.querySelectorAll('use');\n if (!uses.length) return;\n\n const usedIds = new Set();\n uses.forEach(use => {\n const href = use.getAttribute('xlink:href') || use.getAttribute('href');\n if (href && href.startsWith('#')) usedIds.add(href.slice(1));\n });\n if (!usedIds.size) return;\n\n const defs = document.createElementNS(\"http://www.w3.org/2000/svg\", \"defs\");\n\n for (const id of usedIds) {\n for (const source of defsSources) {\n const def = source.querySelector(`#${CSS.escape(id)}`);\n if (def) {\n defs.appendChild(def.cloneNode(true));\n break;\n }\n }\n }\n\n if (defs.childNodes.length) {\n svg.insertBefore(defs, svg.firstChild);\n }\n });\n}\n"], ["/snapdom/src/core/prepare.js", "/**\n * Prepares a deep clone of an element, inlining pseudo-elements and generating CSS classes.\n * @module prepare\n */\n\nimport { generateCSSClasses} from '../utils/cssTools.js';\nimport { stripTranslate} from '../utils/helpers.js';\nimport { deepClone } from './clone.js';\nimport { inlinePseudoElements } from '../modules/pseudo.js';\nimport { inlineExternalDef } from '../modules/svgDefs.js';\nimport { cache } from '../core/cache.js';\n\n/**\n * Prepares a clone of an element for capture, inlining pseudo-elements and generating CSS classes.\n *\n * @param {Element} element - Element to clone\n * @param {boolean} [compress=false] - Whether to compress style keys\n * @param {boolean} [embedFonts=false] - Whether to embed custom fonts\n * @param {Object} [options={}] - Capture options\n * @param {string[]} [options.exclude] - CSS selectors for elements to exclude\n * @param {Function} [options.filter] - Custom filter function\n * @returns {Promise} Object containing the clone, generated CSS, and style cache\n */\n\nexport async function prepareClone(element, compress = false, embedFonts = false, options = {}) {\n\n let clone\n let classCSS = '';\n try {\n clone = deepClone(element, compress, options, element);\n } catch (e) {\n console.warn(\"deepClone failed:\", e);\n throw e;\n }\n try {\n await inlinePseudoElements(element, clone, compress, embedFonts, options.useProxy);\n } catch (e) {\n console.warn(\"inlinePseudoElements failed:\", e);\n }\n try {\n inlineExternalDef(clone);\n } catch (e) {\n console.warn(\"inlineExternalDef failed:\", e);\n }\n if (compress) {\n const keyToClass = generateCSSClasses();\n classCSS = Array.from(keyToClass.entries()).map(([key, className]) => `.${className}{${key}}`).join(\"\");\n for (const [node, key] of cache.preStyleMap.entries()) {\n if (node.tagName === \"STYLE\") continue;\n const className = keyToClass.get(key);\n if (className) node.classList.add(className);\n const bgImage = node.style?.backgroundImage;\n node.removeAttribute(\"style\");\n if (bgImage && bgImage !== \"none\") node.style.backgroundImage = bgImage;\n }\n } else {\n for (const [node, key] of cache.preStyleMap.entries()) {\n if (node.tagName === \"STYLE\") continue;\n node.setAttribute(\"style\", key.replace(/;/g, \"; \"));\n }\n }\n for (const [cloneNode, originalNode] of cache.preNodeMap.entries()) {\n const scrollX = originalNode.scrollLeft;\n const scrollY = originalNode.scrollTop;\n const hasScroll = scrollX || scrollY;\n if (hasScroll && cloneNode instanceof HTMLElement) {\n cloneNode.style.overflow = \"hidden\";\n cloneNode.style.scrollbarWidth = \"none\";\n cloneNode.style.msOverflowStyle = \"none\";\n const inner = document.createElement(\"div\");\n inner.style.transform = `translate(${-scrollX}px, ${-scrollY}px)`;\n inner.style.willChange = \"transform\";\n inner.style.display = \"inline-block\";\n inner.style.width = \"100%\";\n while (cloneNode.firstChild) {\n inner.appendChild(cloneNode.firstChild);\n }\n cloneNode.appendChild(inner);\n }\n }\n if (element === cache.preNodeMap.get(clone)) {\n const computed = cache.preStyle.get(element) || window.getComputedStyle(element);\n cache.preStyle.set(element, computed);\n const transform = stripTranslate(computed.transform);\n clone.style.margin = \"0\";\n clone.style.position = \"static\";\n clone.style.top = \"auto\";\n clone.style.left = \"auto\";\n clone.style.right = \"auto\";\n clone.style.bottom = \"auto\";\n clone.style.zIndex = \"auto\";\n clone.style.float = \"none\";\n clone.style.clear = \"none\";\n clone.style.transform = transform || \"\";\n }\n for (const [cloneNode, originalNode] of cache.preNodeMap.entries()) {\n if (originalNode.tagName === \"PRE\") {\n cloneNode.style.marginTop = \"0\";\n cloneNode.style.marginBlockStart = \"0\";\n }\n }\n return { clone, classCSS };\n}\n"], ["/snapdom/__tests__/index.browser.test.js", "import { it, expect } from 'vitest';\nimport * as snapdom from '../src/index.browser.js';\n\nit('should import the browser bundle without errors', () => {\n expect(snapdom).toBeDefined();\n});\n"], ["/snapdom/src/modules/styles.js", "import { getStyleKey } from '../utils/cssTools.js';\nimport { getStyle } from '../utils/helpers.js';\nimport {cache} from '../core/cache.js'\n\nfunction snapshotComputedStyleFull(style) {\n const result = {};\n for (let i = 0; i < style.length; i++) {\n const prop = style[i];\n let val = style.getPropertyValue(prop);\n\n // Opcional: evitar URLs externas que puedan romper renderizado\n if (\n (prop === 'background-image' || prop === 'content') &&\n val.includes('url(') &&\n !val.includes('data:')\n ) {\n val = 'none';\n }\n\n result[prop] = val;\n }\n return result;\n}\n\nexport function inlineAllStyles(source, clone, compress) {\n if (source.tagName === 'STYLE') return;\n\n if (!cache.preStyle.has(source)) {\n cache.preStyle.set(source, getStyle(source));\n }\n const style = cache.preStyle.get(source);\n\n if (!cache.snapshot.has(source)) {\n const snapshot = snapshotComputedStyleFull(style);\n cache.snapshot.set(source, snapshot);\n }\n\n const snapshot = cache.snapshot.get(source);\n\n const hash = Object.entries(snapshot)\n .sort(([a], [b]) => a.localeCompare(b))\n .map(([prop, val]) => `${prop}:${val}`)\n .join(';');\n\n if (cache.snapshotKey.has(hash)) {\n cache.preStyleMap.set(clone, cache.snapshotKey.get(hash));\n return;\n }\n\n const tagName = source.tagName?.toLowerCase() || 'div';\n const key = getStyleKey(snapshot, tagName, compress);\n\n cache.snapshotKey.set(hash, key);\n cache.preStyleMap.set(clone, key);\n}\n"], ["/snapdom/src/modules/background.js", "/**\n * Utilities for inlining background images as data URLs.\n * @module background\n */\n\nimport { getStyle, inlineSingleBackgroundEntry, splitBackgroundImage } from '../utils/helpers.js';\nimport { cache } from '../core/cache.js'\n\n/**\n * Converts all background images in the cloned element tree to data URLs.\n *\n * @param {Element} source - Original element\n * @param {Element} clone - Cloned element\n * @param {Object} [options={}] - Options for image processing\n * @returns {Promise} Promise that resolves when all background images are processed\n */\nexport async function inlineBackgroundImages(source, clone, options = {}) {\n const queue = [[source, clone]];\n\n const imageProps = [\n \"background-image\",\n \"mask\",\n \"mask-image\", \"-webkit-mask-image\",\n \"mask-source\", \"mask-box-image-source\",\n \"mask-border-source\",\n \"-webkit-mask-box-image-source\"\n ];\n\n while (queue.length) {\n const [srcNode, cloneNode] = queue.shift();\n const style = cache.preStyle.get(srcNode) || getStyle(srcNode);\n if (!cache.preStyle.has(srcNode)) cache.preStyle.set(srcNode, style);\n\n for (const prop of imageProps) {\n const val = style.getPropertyValue(prop);\n if (!val || val === \"none\") continue;\n\n const splits = splitBackgroundImage(val);\n const inlined = await Promise.all(\n splits.map(entry => inlineSingleBackgroundEntry(entry, options))\n );\n\n if (inlined.some(p => p && p !== \"none\" && !/^url\\(undefined/.test(p))) {\n cloneNode.style.setProperty(prop, inlined.join(\", \"));\n }\n }\n\n // También preservamos el background-color como antes\n const bgColor = style.getPropertyValue(\"background-color\");\n if (\n bgColor &&\n bgColor !== \"transparent\" &&\n bgColor !== \"rgba(0, 0, 0, 0)\"\n ) {\n cloneNode.style.backgroundColor = bgColor;\n }\n\n const sChildren = Array.from(srcNode.children);\n const cChildren = Array.from(cloneNode.children);\n for (let i = 0; i < Math.min(sChildren.length, cChildren.length); i++) {\n queue.push([sChildren[i], cChildren[i]]);\n }\n }\n}\n\n"], ["/snapdom/src/index.browser.js", "/**\n * Entry point for snapDOM library exports.\n *\n * @file index.browser.js\n */\n\nimport { snapdom } from './api/snapdom.js';\nimport { preCache } from './api/preCache.js';\n\nif (typeof window !== 'undefined') {\n window.snapdom = snapdom;\n window.preCache = preCache;\n}"], ["/snapdom/src/modules/iconFonts.js", "var defaultIconFonts = [\n// /uicons/i,\n /font\\s*awesome/i,\n /material\\s*icons/i,\n /ionicons/i,\n /glyphicons/i,\n /feather/i,\n /bootstrap\\s*icons/i,\n /remix\\s*icons/i,\n /heroicons/i,\n /layui/i,\n /lucide/i\n];\n\nvar userIconFonts = [];\n\nexport function extendIconFonts(fonts) {\n const list = Array.isArray(fonts) ? fonts : [fonts];\n for (const f of list) {\n if (f instanceof RegExp) {\n userIconFonts.push(f);\n } else if (typeof f === \"string\") {\n userIconFonts.push(new RegExp(f, \"i\"));\n } else {\n console.warn(\"[snapdom] Ignored invalid iconFont value:\", f);\n }\n }\n}\n\nexport function isIconFont(input) {\n const text = typeof input === \"string\" ? input : \"\";\n\n const candidates = [...defaultIconFonts, ...userIconFonts];\n\n for (const rx of candidates) {\n if (rx instanceof RegExp && rx.test(text)) return true;\n }\n\n // Heurística básica\n if (\n /icon/i.test(text) ||\n /glyph/i.test(text) ||\n /symbols/i.test(text) ||\n /feather/i.test(text) ||\n /fontawesome/i.test(text)\n ) return true;\n\n return false;\n}"], ["/snapdom/src/index.js", "/**\n * Entry point for snapDOM library exports.\n *\n * @file index.js\n */\n\nexport { snapdom } from './api/snapdom.js';\nexport { preCache } from './api/preCache.js';\n\n"], ["/snapdom/vitest.config.js", "import { defineConfig } from 'vitest/config'\n\nexport default defineConfig({\n test: {\n browser: {\n enabled: true,\n provider: 'playwright',\n // https://vitest.dev/guide/browser/playwright\n instances: [\n { browser: 'chromium' },\n ],\n },\n coverage: {\n provider: 'v8', // o 'istanbul'\n include: [\n 'src/**/*.js', // Solo archivos JS dentro de src/\n ],\n },\n },\n})\n"], ["/snapdom/src/core/cache.js", "/**\n * Caches for images, backgrounds, resources, and computed styles used during DOM capture.\n * @module cache\n */\n\nexport const cache = {\n image: new Map(),\n background: new Map(),\n resource: new Map(),\n defaultStyle: new Map(),\n baseStyle: new Map(),\n computedStyle: new WeakMap(),\n font: new Set(),\n snapshot: new WeakMap(),\n snapshotKey: new Map(),\n preStyleMap: new Map(),\n preStyle: new WeakMap(),\n preNodeMap: new Map(),\n reset: resetCache\n};\n\nfunction resetCache() {\n cache.computedStyle = new WeakMap();\n cache.snapshot = new WeakMap();\n cache.snapshotKey.clear();\n cache.preStyleMap.clear();\n cache.preStyle = new WeakMap();\n cache.preNodeMap.clear();\n}\n"]], "task_instance_info": {"created_time": "2025-08-21 00:01:54", "created_task_model": "DeepSeek-R1", "function_skeleton": "async () => {}", "code_description": "This code segment functions to: Simulate browser-specific environment conditions for image processing verification and ensure compatibility with alternative decoding mechanisms for visual output generation."}, "inference_content": {"inference_model": "DeepSeek-R1", "inference_result": "```javascript\n[TASK_BEGIN]\nasync () => {\n const el = document.createElement('div');\n el.style.width = '10px';\n el.style.height = '10px';\n document.body.appendChild(el);\n \n // Mock Safari behavior where HTMLImageElement.prototype.decode doesn't exist\n const origDecode = HTMLImageElement.prototype.decode;\n HTMLImageElement.prototype.decode = vi.fn(() => Promise.reject(new Error('Safari decode error')));\n \n const { snapdom } = await import('../src/api/snapdom.js');\n const img = await snapdom.toImg(el);\n \n expect(img).toBeInstanceOf(HTMLImageElement);\n expect(typeof img.src).toBe('string');\n \n // Cleanup\n HTMLImageElement.prototype.decode = origDecode;\n document.body.removeChild(el);\n}\n[TASK_END]\n```", "inference_time": "2025-08-21 00-02-09"}, "editdistance_info": {"edit_distance": 16.763, "calculate_time": "2025-08-21 00:02:09", "true_code_clean": "async () => {\n vi.resetModules();\n vi.mock('../utils/helpers.js', async () => {\n const actual = await vi.importActual('../utils/helpers.js');\n return { ...actual, isSafari: true };\n });\n const { snapdom } = await import('../src/api/snapdom.js');\n const el = document.createElement('div');\n el.style.width = '10px';\n el.style.height = '10px';\n document.body.appendChild(el);\n const img = new Image();\n img.width = 10;\n img.height = 10;\n img.decode = () => Promise.resolve();\n globalThis.Image = function() { return img; };\n const res = await snapdom.capture(el);\n await res.toImg();\n document.body.removeChild(el);\n vi.resetModules();\n }", "predict_code_clean": "async () => {\n const el = document.createElement('div');\n el.style.width = '10px';\n el.style.height = '10px';\n document.body.appendChild(el);\n const origDecode = HTMLImageElement.prototype.decode;\n HTMLImageElement.prototype.decode = vi.fn(() => Promise.reject(new Error('Safari decode error')));\n const { snapdom } = await import('../src/api/snapdom.js');\n const img = await snapdom.toImg(el);\n expect(img).toBeInstanceOf(HTMLImageElement);\n expect(typeof img.src).toBe('string');\n HTMLImageElement.prototype.decode = origDecode;\n document.body.removeChild(el);\n}"}} {"repo_name": "snapdom", "file_name": "/snapdom/src/modules/svgDefs.js", "inference_info": {"prefix_code": "/**\n * Inlines external `` used by `` or `` inside SVGs,\n * copying only the necessary definitions into each individual cloned SVG.\n *\n * This is needed because cloned SVGs using `` may reference elements like ``, ``, etc.,\n * defined elsewhere in the document (e.g., in a shared `` block that is not part of the cloned subtree).\n *\n * The function finds all `` elements within `root`, extracts the referenced IDs,\n * and embeds the required definitions at the top of each SVG.\n *\n * @function inlineExternalDef\n * @param {ParentNode} root - The root node containing cloned SVGs (usually the result of a DOM snapshot).\n * @returns {void}\n *\n * @example\n * const { clone } = await prepareClone(element);\n * inlineExternalDef(clone);\n */\n\nexport function inlineExternalDef(root) {\n if (!root) return;\n const defsSources = document.querySelectorAll('svg > defs');\n if (!defsSources.length) return;\n\n root.querySelectorAll('svg').forEach(", "suffix_code": ");\n}\n", "middle_code": "svg => {\n const uses = svg.querySelectorAll('use');\n if (!uses.length) return;\n const usedIds = new Set();\n uses.forEach(use => {\n const href = use.getAttribute('xlink:href') || use.getAttribute('href');\n if (href && href.startsWith('#')) usedIds.add(href.slice(1));\n });\n if (!usedIds.size) return;\n const defs = document.createElementNS(\"http:\n for (const id of usedIds) {\n for (const source of defsSources) {\n const def = source.querySelector(`#${CSS.escape(id)}`);\n if (def) {\n defs.appendChild(def.cloneNode(true));\n break;\n }\n }\n }\n if (defs.childNodes.length) {\n svg.insertBefore(defs, svg.firstChild);\n }\n }", "code_description": null, "fill_type": "FUNCTION_TYPE", "language_type": "javascript", "sub_task_type": null}, "context_code": [["/snapdom/src/utils/helpers.js", "import { cache } from \"../core/cache\";\n\n/**\n * Fetches and inlines a single background-image entry to a data URL (with caching).\n * - If entry is a gradient or \"none\", returns unchanged.\n * - If entry is a url(...), fetches the image as data URL and caches it.\n *\n * @param {string} entry - Single background-image entry (e.g., \"url(...)\").\n * @param {Object} [options={}] - Options like crossOrigin.\n * @param {boolean} [options.skipInline=false] - If true, only fetches & caches, doesn't return a replacement.\n * @returns {Promise} - The processed entry (unless skipInline is true).\n */\nexport async function inlineSingleBackgroundEntry(entry, options = {}) {\n const rawUrl = extractURL(entry)\n\n const isGradient = /^((repeating-)?(linear|radial|conic)-gradient)\\(/i.test(entry);\n \n if (rawUrl) {\n const encodedUrl = safeEncodeURI(rawUrl);\n if (cache.background.has(encodedUrl)) {\n return options.skipInline ? void 0 : `url(${cache.background.get(encodedUrl)})`;\n } else {\n const dataUrl = await fetchImage(encodedUrl, { useProxy: options.useProxy });\n cache.background.set(encodedUrl, dataUrl);\n return options.skipInline ? void 0 : `url(\"${dataUrl}\")`;\n }\n }\n\n if (isGradient || entry === \"none\") {\n return entry;\n }\n\n return entry;\n}\n\n\n/**\n * Creates a promise that resolves after the specified delay\n * @param {number} [ms=0] - Milliseconds to delay\n * @returns {Promise} Promise that resolves after the delay\n */\n\nexport function idle(fn, { fast = false } = {}) {\n if (fast) return fn();\n if ('requestIdleCallback' in window) {\n requestIdleCallback(fn, { timeout: 50 });\n } else {\n setTimeout(fn, 1);\n }\n}\n/**\n * Gets the computed style for an element or pseudo-element, with caching.\n *\n * @param {Element} el - The element\n * @param {string|null} [pseudo=null] - The pseudo-element\n * @returns {CSSStyleDeclaration} The computed style\n */\nexport function getStyle(el, pseudo = null) {\n if (!(el instanceof Element)) {\n return window.getComputedStyle(el, pseudo);\n }\n\n let map = cache.computedStyle.get(el);\n if (!map) {\n map = new Map();\n cache.computedStyle.set(el, map);\n }\n\n if (!map.has(pseudo)) {\n const st = window.getComputedStyle(el, pseudo);\n map.set(pseudo, st);\n }\n\n return map.get(pseudo);\n}\n/**\n * Parses the CSS content property value, handling unicode escapes.\n *\n * @param {string} content - The CSS content value\n * @returns {string} The parsed content\n */\nexport function parseContent(content) {\n let clean = content.replace(/^['\"]|['\"]$/g, \"\");\n if (clean.startsWith(\"\\\\\")) {\n try {\n return String.fromCharCode(parseInt(clean.replace(\"\\\\\", \"\"), 16));\n } catch {\n return clean;\n }\n }\n return clean;\n}\n/**\n * Extracts a URL from a CSS value like background-image.\n *\n * @param {string} value - The CSS value\n * @returns {string|null} The extracted URL or null\n */\n\nexport function extractURL(value) {\n const match = value.match(/url\\((['\"]?)(.*?)(\\1)\\)/);\n if (!match) return null;\n\n const url = match[2].trim();\n if (url.startsWith('#')) return null;\n return url;\n}\n\n/**\n * Determines if a font family or URL is an icon font.\n *\n * @param {string} familyOrUrl - The font family or URL\n * @returns {boolean} True if it is an icon font\n */\nexport function isIconFont(familyOrUrl) {\n const iconFontPatterns = [\n /font\\s*awesome/i,\n /material\\s*icons/i,\n /ionicons/i,\n /glyphicons/i,\n /feather/i,\n /bootstrap\\s*icons/i,\n /remix\\s*icons/i,\n /heroicons/i,\n /layui/i,\n /lucide/i\n ];\n return iconFontPatterns.some(rx => rx.test(familyOrUrl));\n}\n/**\n *\n *\n * @export\n * @param {*} src\n * @param {number} [timeout=3000]\n * @return {*} \n */\n\nexport function fetchImage(src, { timeout = 3000, useProxy = '' } = {}) {\n function getCrossOriginMode(url) {\n try {\n const parsed = new URL(url, window.location.href);\n return parsed.origin === window.location.origin ? \"use-credentials\" : \"anonymous\";\n } catch {\n return \"anonymous\";\n }\n }\n\n // Función común para fallback vía fetch + proxy\n async function fetchWithFallback(url) {\n const fetchBlobAsDataURL = (fetchUrl) =>\n fetch(fetchUrl, {\n mode: \"cors\",\n credentials: getCrossOriginMode(fetchUrl) === \"use-credentials\" ? \"include\" : \"omit\",\n })\n .then(r => r.blob())\n .then(blob => new Promise((resolve, reject) => {\n const reader = new FileReader();\n reader.onloadend = () => {\n const base64 = reader.result;\n if (typeof base64 !== \"string\" || !base64.startsWith(\"data:image/\")) {\n reject(new Error(\"Invalid image data URL\"));\n return;\n }\n resolve(base64);\n };\n reader.onerror = () => reject(new Error(\"FileReader error\"));\n reader.readAsDataURL(blob);\n }));\n\n try {\n return await fetchBlobAsDataURL(url);\n } catch (e) {\n if (useProxy && typeof useProxy === \"string\") {\n const proxied = useProxy.replace(/\\/$/, \"\") + safeEncodeURI(url);\n try {\n return await fetchBlobAsDataURL(proxied);\n } catch {\n \n throw new Error(\"[SnapDOM - fetchImage] CORS restrictions prevented image capture (even via proxy)\");\n }\n } else {\n \n throw new Error(\"[SnapDOM - fetchImage] Fetch fallback failed and no proxy provided\");\n }\n }\n }\n\n const crossOriginValue = getCrossOriginMode(src);\n\n if (cache.image.has(src)) {\n return Promise.resolve(cache.image.get(src));\n }\n\n // Detectamos si es un data URI, si sí, devolvemos directo sin fetch\n const isDataURI = src.startsWith(\"data:image/\");\n if (isDataURI) {\n cache.image.set(src, src);\n return Promise.resolve(src);\n }\n\n // Mejor detección SVG, incluyendo query strings\n const isSVG = /\\.svg(\\?.*)?$/i.test(src);\n\n if (isSVG) {\n return (async () => {\n try {\n const response = await fetch(src, {\n mode: \"cors\",\n credentials: crossOriginValue === \"use-credentials\" ? \"include\" : \"omit\"\n });\n const svgText = await response.text();\n const encoded = `data:image/svg+xml;charset=utf-8,${encodeURIComponent(svgText)}`;\n cache.image.set(src, encoded);\n return encoded;\n } catch {\n return fetchWithFallback(src);\n }\n })();\n }\n\n return new Promise((resolve, reject) => {\n const timeoutId = setTimeout(() => {\n reject(new Error(\"[SnapDOM - fetchImage] Image load timed out\"));\n }, timeout);\n\n const image = new Image();\n image.crossOrigin = crossOriginValue;\n\n image.onload = async () => {\n clearTimeout(timeoutId);\n try {\n await image.decode();\n const canvas = document.createElement(\"canvas\");\n canvas.width = image.width;\n canvas.height = image.height;\n const ctx = canvas.getContext(\"2d\");\n ctx.drawImage(image, 0, 0, canvas.width, canvas.height);\n const dataURL = canvas.toDataURL(\"image/png\");\n cache.image.set(src, dataURL);\n resolve(dataURL);\n } catch {\n try {\n const fallbackDataURL = await fetchWithFallback(src);\n cache.image.set(src, fallbackDataURL);\n resolve(fallbackDataURL);\n } catch (e) {\n reject(e);\n }\n }\n };\n\n image.onerror = async () => {\n clearTimeout(timeoutId);\n console.error(`[SnapDOM - fetchImage] Image failed to load: ${src}`);\n try {\n const fallbackDataURL = await fetchWithFallback(src);\n cache.image.set(src, fallbackDataURL);\n resolve(fallbackDataURL);\n } catch (e) {\n reject(e);\n }\n };\n\n image.src = src;\n });\n}\n\n/**\n *\n *\n * @export\n * @param {*} style\n * @return {*} \n */\nexport function snapshotComputedStyle(style) {\n const snap = {};\n for (let prop of style) {\n snap[prop] = style.getPropertyValue(prop);\n }\n return snap;\n}\n\nexport function isSafari() {\n return /^((?!chrome|android).)*safari/i.test(navigator.userAgent);\n}\n\nexport function stripTranslate(transform) {\n if (!transform || transform === 'none') return '';\n\n let cleaned = transform.replace(/translate[XY]?\\([^)]*\\)/g, '');\n\n cleaned = cleaned.replace(/matrix\\(([^)]+)\\)/g, (_, values) => {\n const parts = values.split(',').map(s => s.trim());\n if (parts.length !== 6) return `matrix(${values})`;\n parts[4] = '0';\n parts[5] = '0';\n return `matrix(${parts.join(', ')})`;\n });\n\n cleaned = cleaned.replace(/matrix3d\\(([^)]+)\\)/g, (_, values) => {\n const parts = values.split(',').map(s => s.trim());\n if (parts.length !== 16) return `matrix3d(${values})`;\n parts[12] = '0';\n parts[13] = '0';\n return `matrix3d(${parts.join(', ')})`;\n });\n\n return cleaned.trim().replace(/\\s{2,}/g, ' ');\n}\n\nexport function safeEncodeURI(uri) {\n if (/%[0-9A-Fa-f]{2}/.test(uri)) return uri; // prevent reencode\n try {\n return encodeURI(uri);\n } catch {\n return uri;\n }\n}\n\nexport function splitBackgroundImage(bg) {\n const parts = [];\n let depth = 0;\n let lastIndex = 0;\n for (let i = 0; i < bg.length; i++) {\n const char = bg[i];\n if (char === '(') depth++;\n if (char === ')') depth--;\n if (char === ',' && depth === 0) {\n parts.push(bg.slice(lastIndex, i).trim());\n lastIndex = i + 1;\n }\n }\n parts.push(bg.slice(lastIndex).trim());\n return parts;\n}\n\n"], ["/snapdom/src/utils/cssTools.js", "/**\n * Utilities for working with CSS styles, defaults, and class generation.\n * @module cssTools\n */\n\nimport { cache } from \"../core/cache\"\n\nconst commonTags = [\n 'div', 'span', 'p', 'a', 'img', 'ul', 'li', 'button', 'input',\n 'select', 'textarea', 'label', 'section', 'article', 'header',\n 'footer', 'nav', 'main', 'aside', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6',\n 'svg', 'path', 'circle', 'rect', 'line', 'g', 'table', 'thead', 'tbody', 'tr', 'td', 'th'\n];\n\nexport function precacheCommonTags() {\n for (let tag of commonTags) {\n getDefaultStyleForTag(tag);\n }\n}\n/**\n * Retrieves default CSS property values from a temporary element.\n *\n * @param {string} tagName - The tag name to get default styles for\n * @returns {Object} Object containing default values for all CSS properties\n */\nexport function getDefaultStyleForTag(tagName) {\n if (cache.defaultStyle.has(tagName)) {\n return cache.defaultStyle.get(tagName);\n }\n\n const skipTags = new Set(['script', 'style', 'meta', 'link', 'noscript', 'template']);\n if (skipTags.has(tagName)) {\n const empty = {}; \n cache.defaultStyle.set(tagName, empty); \n return empty;\n }\n\n let sandbox = document.getElementById('snapdom-sandbox');\n if (!sandbox) {\n sandbox = document.createElement('div');\n sandbox.id = 'snapdom-sandbox';\n sandbox.style.position = 'absolute';\n sandbox.style.left = '-9999px';\n sandbox.style.top = '-9999px';\n sandbox.style.width = '0';\n sandbox.style.height = '0';\n sandbox.style.overflow = 'hidden';\n document.body.appendChild(sandbox);\n }\n\n const el = document.createElement(tagName);\n el.style.all = 'initial';\n sandbox.appendChild(el);\n\n const styles = getComputedStyle(el);\n const defaults = {};\n for (let prop of styles) {\n defaults[prop] = styles.getPropertyValue(prop);\n }\n\n sandbox.removeChild(el);\n cache.defaultStyle.set(tagName, defaults);\n return defaults;\n}\n\n/**\n * Creates a unique key from an element's computed style that differs from defaults.\n *\n * @param {Object} snapshot - Computed style snapshot\n * @param {string} tagName - The tag name of the element\n * @param {boolean} [compress=false] - Whether to compress style keys\n * @returns {string} Semi-colon separated list of non-default properties\n */\n\nexport function getStyleKey(snapshot, tagName, compress = false) {\n const entries = [];\n const defaultStyles = getDefaultStyleForTag(tagName);\n for (let [prop, value] of Object.entries(snapshot)) {\n if (!compress) {\n if (value) {\n entries.push(`${prop}:${value}`);\n }\n } else {\n const defaultValue = defaultStyles[prop];\n if (value && value !== defaultValue) {\n entries.push(`${prop}:${value}`);\n }\n }\n }\n\n return entries.sort().join(\";\");\n}\n\n/**\n * Collects all unique tag names used in the DOM tree rooted at the given node.\n *\n * @param {Node} root - The root node to search\n * @returns {string[]} Array of unique tag names\n */\nexport function collectUsedTagNames(root) {\n const tagSet = new Set();\n if (root.nodeType !== Node.ELEMENT_NODE && root.nodeType !== Node.DOCUMENT_FRAGMENT_NODE) {\n return [];\n }\n if (root.tagName) {\n tagSet.add(root.tagName.toLowerCase());\n }\n if (typeof root.querySelectorAll === 'function') {\n root.querySelectorAll(\"*\").forEach(el => tagSet.add(el.tagName.toLowerCase()));\n }\n return Array.from(tagSet);\n}\n\n/**\n * Generates deduplicated base CSS for the given tag names.\n *\n * @param {string[]} usedTagNames - Array of tag names\n * @returns {string} CSS string\n */\nexport function generateDedupedBaseCSS(usedTagNames) {\n const groups = new Map();\n\n for (let tagName of usedTagNames) {\n const styles = cache.defaultStyle.get(tagName);\n if (!styles) continue;\n\n // Creamos la \"firma\" del bloque CSS para comparar\n const key = Object.entries(styles)\n .map(([k, v]) => `${k}:${v};`)\n .sort()\n .join('');\n\n // Agrupamos por firma\n if (!groups.has(key)) {\n groups.set(key, []);\n }\n groups.get(key).push(tagName);\n }\n\n // Ahora generamos el CSS optimizado\n let css = '';\n for (let [styleBlock, tagList] of groups.entries()) {\n css += `${tagList.join(',')} { ${styleBlock} }\\n`;\n }\n\n return css;\n}\n/**\n * Generates CSS classes from a style map.\n *\n * @returns {Map} Map of style keys to class names\n */\nexport function generateCSSClasses() {\n const keySet = new Set(cache.preStyleMap.values());\n const classMap = new Map();\n let counter = 1;\n for (const key of keySet) {\n classMap.set(key, `c${counter++}`);\n }\n return classMap;\n}\n"], ["/snapdom/src/core/capture.js", "/**\n * Core logic for capturing DOM elements as SVG data URLs.\n * @module capture\n */\n\nimport { prepareClone } from './prepare.js';\nimport { inlineImages } from '../modules/images.js';\nimport { inlineBackgroundImages } from '../modules/background.js';\nimport { idle, isSafari } from '../utils/helpers.js';\nimport { collectUsedTagNames, generateDedupedBaseCSS } from '../utils/cssTools.js';\nimport { embedCustomFonts } from '../modules/fonts.js';\nimport { cache } from '../core/cache.js'\n\n/**\n * Captures an HTML element as an SVG data URL, inlining styles, images, backgrounds, and optionally fonts.\n *\n * @param {Element} element - DOM element to capture\n * @param {Object} [options={}] - Capture options\n * @param {boolean} [options.compress=true] - Whether to compress style keys\n * @param {boolean} [options.embedFonts=false] - Whether to embed custom fonts\n * @param {boolean} [options.fast=true] - Whether to skip idle delay for faster results\n * @param {number} [options.scale=1] - Output scale multiplier\n * @param {string[]} [options.exclude] - CSS selectors for elements to exclude\n * @param {Function} [options.filter] - Custom filter function \n * @returns {Promise} Promise that resolves to an SVG data URL\n */\n\nexport async function captureDOM(element, options = {}) {\n if (!element) throw new Error(\"Element cannot be null or undefined\");\n cache.reset()\n const { compress = true, embedFonts = false, fast = true, scale = 1, useProxy = ''} = options;\n let clone, classCSS;\n let fontsCSS = \"\";\n let baseCSS = \"\";\n let dataURL;\n let svgString;\n\n ({ clone, classCSS } = await prepareClone(element, compress, embedFonts, options));\n\n await new Promise((resolve) => {\n idle(async () => {\n await inlineImages(clone, options);\n resolve();\n }, { fast });\n });\n await new Promise((resolve) => {\n idle(async () => {\n await inlineBackgroundImages(element, clone, options);\n resolve();\n }, { fast });\n });\n if (embedFonts) {\n await new Promise((resolve) => {\n idle(async () => {\n fontsCSS = await embedCustomFonts();\n resolve();\n }, { fast });\n });\n }\n if (compress) {\n const usedTags = collectUsedTagNames(clone).sort();\n const tagKey = usedTags.join(\",\");\n if (cache.baseStyle.has(tagKey)) {\n baseCSS = cache.baseStyle.get(tagKey);\n } else {\n await new Promise((resolve) => {\n idle(() => {\n baseCSS = generateDedupedBaseCSS(usedTags);\n cache.baseStyle.set(tagKey, baseCSS);\n resolve();\n }, { fast });\n });\n }\n }\n await new Promise((resolve) => {\n idle(() => {\n const rect = element.getBoundingClientRect();\n let w = rect.width;\n let h = rect.height;\n const hasW = Number.isFinite(options.width);\n const hasH = Number.isFinite(options.height);\n const hasScale = typeof scale === \"number\" && scale !== 1;\n if (!hasScale) {\n const aspect = rect.width / rect.height;\n if (hasW && hasH) {\n w = options.width;\n h = options.height;\n } else if (hasW) {\n w = options.width;\n h = w / aspect;\n } else if (hasH) {\n h = options.height;\n w = h * aspect;\n }\n }\n w = Math.ceil(w);\n h = Math.ceil(h);\n clone.setAttribute(\"xmlns\", \"http://www.w3.org/1999/xhtml\");\n clone.style.transformOrigin = \"top left\";\n if (!hasScale && (hasW || hasH)) {\n const originalW = rect.width;\n const originalH = rect.height;\n const scaleX = w / originalW;\n const scaleY = h / originalH;\n const existingTransform = clone.style.transform || \"\";\n const scaleTransform = `scale(${scaleX}, ${scaleY})`;\n clone.style.transform = `${scaleTransform} ${existingTransform}`.trim();\n }\n const svgNS = \"http://www.w3.org/2000/svg\";\n const fo = document.createElementNS(svgNS, \"foreignObject\");\n fo.setAttribute(\"width\", \"100%\");\n fo.setAttribute(\"height\", \"100%\");\n const styleTag = document.createElement(\"style\");\n styleTag.textContent = baseCSS + fontsCSS + \"svg{overflow:visible;}\" + classCSS;\n fo.appendChild(styleTag);\n fo.appendChild(clone);\n const serializer = new XMLSerializer();\n const foString = serializer.serializeToString(fo);\n const svgHeader = ``;\n const svgFooter = \"\";\n svgString = svgHeader + foString + svgFooter;\n dataURL = `data:image/svg+xml;charset=utf-8,${encodeURIComponent(svgString)}`;\n resolve();\n }, { fast });\n });\n const sandbox = document.getElementById(\"snapdom-sandbox\");\n if (sandbox && sandbox.style.position === \"absolute\") sandbox.remove();\n return dataURL;\n}\n\n"], ["/snapdom/src/modules/fonts.js", "/**\n * Utilities for handling and embedding web fonts and icon fonts.\n * @module fonts\n */\n\nimport { extractURL} from \"../utils/helpers\"\nimport { cache } from \"../core/cache\"\nimport { isIconFont } from '../modules/iconFonts.js';\n\n/**\n * Converts a unicode character from an icon font into a data URL image.\n *\n * @export\n * @param {string} unicodeChar - The unicode character to render\n * @param {string} fontFamily - The font family name\n * @param {string|number} fontWeight - The font weight\n * @param {number} [fontSize=32] - The font size in pixels\n * @param {string} [color=\"#000\"] - The color to use\n * @returns {Promise} Data URL of the rendered icon\n */\n\nexport async function iconToImage(unicodeChar, fontFamily, fontWeight, fontSize = 32, color = \"#000\") {\n fontFamily = fontFamily.replace(/^['\"]+|['\"]+$/g, \"\");\n const dpr = window.devicePixelRatio || 1;\n\n // Create temporary context to measure\n const tempCanvas = document.createElement(\"canvas\");\n const tempCtx = tempCanvas.getContext(\"2d\");\n tempCtx.font = fontWeight\n ? `${fontWeight} ${fontSize}px \"${fontFamily}\"`\n : `${fontSize}px \"${fontFamily}\"`;\n\n const metrics = tempCtx.measureText(unicodeChar);\n const ascent = metrics.actualBoundingBoxAscent || fontSize * 0.8;\n const descent = metrics.actualBoundingBoxDescent || fontSize * 0.2;\n const height = ascent + descent;\n const width = metrics.width;\n\n const canvas = document.createElement(\"canvas\");\n canvas.width = Math.ceil(width * dpr);\n canvas.height = Math.ceil(height * dpr);\n\n const ctx = canvas.getContext(\"2d\");\n ctx.scale(dpr, dpr);\n ctx.font = tempCtx.font;\n ctx.textAlign = \"left\";\n ctx.textBaseline = \"alphabetic\"; // aligns with baseline\n ctx.fillStyle = color;\n\n // Draw at (0, ascent) so the full glyph fits vertically\n ctx.fillText(unicodeChar, 0, ascent);\n\n return canvas.toDataURL();\n}\n\n\nfunction isStylesheetLoaded(href) {\n return Array.from(document.styleSheets).some(sheet => sheet.href === href);\n}\n\nfunction injectLinkIfMissing(href) {\n return new Promise((resolve) => {\n if (isStylesheetLoaded(href)) return resolve(null);\n const link = document.createElement(\"link\");\n link.rel = \"stylesheet\";\n link.href = href;\n link.setAttribute(\"data-snapdom\", \"injected-import\");\n link.onload = () => resolve(link);\n link.onerror = () => resolve(null);\n document.head.appendChild(link);\n });\n}\n\n/**\n * Embeds custom fonts found in the document as data URLs in CSS.\n *\n * @export\n * @param {Object} options\n * @param {boolean} [options.preCached=false] - Whether to use pre-cached resources\n * @returns {Promise} The inlined CSS for custom fonts\n */\n\nexport async function embedCustomFonts({preCached = false } = {}) {\n if (cache.resource.has(\"fonts-embed-css\")) {\n if (preCached) {\n const style = document.createElement(\"style\");\n style.setAttribute(\"data-snapdom\", \"embedFonts\");\n style.textContent = cache.resource.get(\"fonts-embed-css\");\n document.head.appendChild(style);\n }\n return cache.resource.get(\"fonts-embed-css\");\n }\n\n const importRegex = /@import\\s+url\\([\"']?([^\"')]+)[\"']?\\)/g;\n const styleImports = [];\n\n for (const styleTag of document.querySelectorAll(\"style\")) {\n const cssText = styleTag.textContent || \"\";\n const matches = Array.from(cssText.matchAll(importRegex));\n for (const match of matches) {\n const importUrl = match[1];\n if (isIconFont(importUrl)) continue;\n if (!isStylesheetLoaded(importUrl)) {\n styleImports.push(importUrl);\n }\n }\n }\n\n await Promise.all(styleImports.map(injectLinkIfMissing));\n\n const links = Array.from(document.querySelectorAll('link[rel=\"stylesheet\"]')).filter((link) => link.href);\n let finalCSS = \"\";\n\n for (const link of links) {\n try {\n const res = await fetch(link.href);\n const cssText = await res.text();\n\n if ((isIconFont(link.href) || isIconFont(cssText))) continue;\n\n const urlRegex = /url\\(([\"']?)([^\"')]+)\\1\\)/g;\n const inlinedCSS = await Promise.all(\n Array.from(cssText.matchAll(urlRegex)).map(async (match) => {\n let rawUrl = extractURL(match[0]);\n if (!rawUrl) return null;\n let url = rawUrl;\n if (!url.startsWith(\"http\") && !url.startsWith(\"data:\")) {\n url = new URL(url, link.href).href;\n }\n if (isIconFont(url)) return null;\n if (cache.resource.has(url)) {\n cache.font.add(url);\n return { original: match[0], inlined: `url(${cache.resource.get(url)})` };\n }\n if (cache.font.has(url)) return null;\n try {\n const fontRes = await fetch(url);\n const blob = await fontRes.blob();\n const b64 = await new Promise((resolve) => {\n const reader = new FileReader();\n reader.onload = () => resolve(reader.result);\n reader.readAsDataURL(blob);\n });\n cache.resource.set(url, b64);\n cache.font.add(url);\n return { original: match[0], inlined: `url(${b64})` };\n } catch (e) {\n console.warn(\"[snapdom] Failed to fetch font resource:\", url);\n return null;\n }\n })\n );\n\n let cssFinal = cssText;\n for (const r of inlinedCSS) {\n if (r) cssFinal = cssFinal.replace(r.original, r.inlined);\n }\n finalCSS += cssFinal + \"\\n\";\n } catch (e) {\n console.warn(\"[snapdom] Failed to fetch CSS:\", link.href);\n }\n }\n\n for (const sheet of document.styleSheets) {\n try {\n if (!sheet.href || links.every((link) => link.href !== sheet.href)) {\n for (const rule of sheet.cssRules) {\n if (rule.type === CSSRule.FONT_FACE_RULE) {\n const src = rule.style.getPropertyValue(\"src\");\n const family = rule.style.getPropertyValue(\"font-family\");\n if (!src || isIconFont(family)) continue;\n\n const urlRegex = /url\\(([\"']?)([^\"')]+)\\1\\)/g;\n const localRegex = /local\\(([\"']?)[^)]+?\\1\\)/g;\n const hasURL = !!src.match(urlRegex);\n const hasLocal = !!src.match(localRegex);\n\n if (!hasURL && hasLocal) {\n // Solo local(), conservar en línea compacta\n finalCSS += `@font-face{font-family:${family};src:${src};font-style:${rule.style.getPropertyValue(\"font-style\") || \"normal\"};font-weight:${rule.style.getPropertyValue(\"font-weight\") || \"normal\"};}`;\n continue;\n }\n\n // Embebido para src con url()\n let inlinedSrc = src;\n const matches = Array.from(src.matchAll(urlRegex));\n for (const match of matches) {\n let rawUrl = match[2].trim();\n if (!rawUrl) continue;\n let url = rawUrl;\n if (!url.startsWith(\"http\") && !url.startsWith(\"data:\")) {\n url = new URL(url, sheet.href || location.href).href;\n }\n if (isIconFont(url)) continue;\n if (cache.resource.has(url)) {\n cache.font.add(url);\n inlinedSrc = inlinedSrc.replace(match[0], `url(${cache.resource.get(url)})`);\n continue;\n }\n if (cache.font.has(url)) continue;\n try {\n const res = await fetch(url);\n const blob = await res.blob();\n const b64 = await new Promise((resolve) => {\n const reader = new FileReader();\n reader.onload = () => resolve(reader.result);\n reader.readAsDataURL(blob);\n });\n cache.resource.set(url, b64);\n cache.font.add(url);\n inlinedSrc = inlinedSrc.replace(match[0], `url(${b64})`);\n } catch (e) {\n console.warn(\"[snapdom] Failed to fetch font URL:\", url);\n }\n }\n\n finalCSS += `@font-face{font-family:${family};src:${inlinedSrc};font-style:${rule.style.getPropertyValue(\"font-style\") || \"normal\"};font-weight:${rule.style.getPropertyValue(\"font-weight\") || \"normal\"};}`;\n }\n }\n }\n } catch (e) {\n console.warn(\"[snapdom] Cannot access stylesheet\", sheet.href, e);\n }\n }\n\n for (const font of document.fonts) {\n if (font.family && font.status === \"loaded\" && font._snapdomSrc) {\n if (isIconFont(font.family)) continue;\n let b64 = font._snapdomSrc;\n if (!b64.startsWith(\"data:\")) {\n if (cache.resource.has(font._snapdomSrc)) {\n b64 = cache.resource.get(font._snapdomSrc);\n cache.font.add(font._snapdomSrc);\n } else if (!cache.font.has(font._snapdomSrc)) {\n try {\n const res = await fetch(font._snapdomSrc);\n const blob = await res.blob();\n b64 = await new Promise((resolve) => {\n const reader = new FileReader();\n reader.onload = () => resolve(reader.result);\n reader.readAsDataURL(blob);\n });\n cache.resource.set(font._snapdomSrc, b64);\n cache.font.add(font._snapdomSrc);\n } catch (e) {\n console.warn(\"[snapdom] Failed to fetch dynamic font src:\", font._snapdomSrc);\n continue;\n }\n }\n }\n\n finalCSS += `@font-face{font-family:'${font.family}';src:url(${b64});font-style:${font.style || \"normal\"};font-weight:${font.weight || \"normal\"};}`;\n }\n }\n\n if (finalCSS) {\n cache.resource.set(\"fonts-embed-css\", finalCSS);\n if (preCached) {\n const style = document.createElement(\"style\");\n style.setAttribute(\"data-snapdom\", \"embedFonts\");\n style.textContent = finalCSS;\n document.head.appendChild(style);\n }\n }\n\n return finalCSS;\n}\n"], ["/snapdom/src/core/clone.js", "/**\n * Deep cloning utilities for DOM elements, including styles and shadow DOM.\n * @module clone\n */\n\nimport { inlineAllStyles } from '../modules/styles.js';\nimport { cache } from '../core/cache.js'\n\n/**\n * Creates a deep clone of a DOM node, including styles, shadow DOM, and special handling for excluded/placeholder/canvas nodes.\n *\n * @param {Node} node - Node to clone\n * @param {boolean} compress - Whether to compress style keys\n * @param {Object} [options={}] - Capture options including exclude and filter \n * @param {Node} [originalRoot] - Original root element being captured\n * @returns {Node|null} Cloned node with styles and shadow DOM content, or null for empty text nodes or filtered elements\n */\n\n \nexport function deepClone(node, compress, options = {}, originalRoot) {\n if (!node) throw new Error('Invalid node');\n\n // Local set to avoid duplicates in slot processing\n const clonedAssignedNodes = new Set();\n let pendingSelectValue = null; // Track select value for later fix\n\n // 1. Text nodes\n if (node.nodeType === Node.TEXT_NODE) {\n return node.cloneNode(true);\n }\n\n // 2. Non-element nodes (comments, etc.)\n if (node.nodeType !== Node.ELEMENT_NODE) {\n return node.cloneNode(true);\n }\n\n // 3. Exclude by attribute\n if (node.getAttribute(\"data-capture\") === \"exclude\") {\n const spacer = document.createElement(\"div\");\n const rect = node.getBoundingClientRect();\n spacer.style.cssText = `display:inline-block;width:${rect.width}px;height:${rect.height}px;visibility:hidden;`;\n return spacer;\n }\n\n // 4. Exclude by selectors\n if (options.exclude && Array.isArray(options.exclude)) {\n for (const selector of options.exclude) {\n try {\n if (node.matches?.(selector)) {\n const spacer = document.createElement(\"div\");\n const rect = node.getBoundingClientRect();\n spacer.style.cssText = `display:inline-block;width:${rect.width}px;height:${rect.height}px;visibility:hidden;`;\n return spacer;\n }\n } catch (err) {\n console.warn(`Invalid selector in exclude option: ${selector}`, err);\n }\n }\n }\n\n // 5. Custom filter function\n if (typeof options.filter === \"function\") {\n try {\n if (!options.filter(node, originalRoot || node)) {\n const spacer = document.createElement(\"div\");\n const rect = node.getBoundingClientRect();\n spacer.style.cssText = `display:inline-block;width:${rect.width}px;height:${rect.height}px;visibility:hidden;`;\n return spacer;\n }\n } catch (err) {\n console.warn(\"Error in filter function:\", err);\n }\n }\n\n // 6. Special case: iframe → fallback pattern\n if (node.tagName === \"IFRAME\") {\n const fallback = document.createElement(\"div\");\n 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;`;\n return fallback;\n }\n\n // 7. Placeholder nodes\n if (node.getAttribute(\"data-capture\") === \"placeholder\") {\n const clone2 = node.cloneNode(false);\n cache.preNodeMap.set(clone2, node);\n inlineAllStyles(node, clone2, compress);\n const placeholder = document.createElement(\"div\");\n placeholder.textContent = node.getAttribute(\"data-placeholder-text\") || \"\";\n placeholder.style.cssText = `color:#666;font-size:12px;text-align:center;line-height:1.4;padding:0.5em;box-sizing:border-box;`;\n clone2.appendChild(placeholder);\n return clone2;\n }\n\n // 8. Canvas → convert to image\n if (node.tagName === \"CANVAS\") {\n const dataURL = node.toDataURL();\n const img = document.createElement(\"img\");\n img.src = dataURL;\n img.width = node.width;\n img.height = node.height;\n cache.preNodeMap.set(img, node);\n inlineAllStyles(node, img, compress);\n return img;\n }\n\n // 9. Base clone (without children)\n let clone;\n try {\n clone = node.cloneNode(false);\n cache.preNodeMap.set(clone, node);\n } catch (err) {\n console.error(\"[Snapdom] Failed to clone node:\", node, err);\n throw err;\n }\n\n // Special handling: textarea (keep size and value)\n if (node instanceof HTMLTextAreaElement) {\n clone.textContent = node.value;\n clone.value = node.value;\n const rect = node.getBoundingClientRect();\n clone.style.width = `${rect.width}px`;\n clone.style.height = `${rect.height}px`;\n return clone;\n }\n\n // Special handling: input\n if (node instanceof HTMLInputElement) {\n clone.value = node.value;\n clone.setAttribute(\"value\", node.value);\n if (node.checked !== void 0) {\n clone.checked = node.checked;\n if (node.checked) clone.setAttribute(\"checked\", \"\");\n if (node.indeterminate) clone.indeterminate = node.indeterminate;\n }\n // return clone;\n }\n\n // Special handling: select → postpone value adjustment\n if (node instanceof HTMLSelectElement) {\n pendingSelectValue = node.value;\n }\n\n // 11. Inline styles\n inlineAllStyles(node, clone, compress);\n\n // 12. ShadowRoot logic\n if (node.shadowRoot) {\n const hasSlot = Array.from(node.shadowRoot.querySelectorAll(\"slot\")).length > 0;\n\n if (hasSlot) {\n // ShadowRoot with slots: only store styles\n for (const child of node.shadowRoot.childNodes) {\n if (child.nodeType === Node.ELEMENT_NODE && child.tagName === \"STYLE\") {\n const cssText = child.textContent || \"\";\n if (cssText.trim() && compress) {\n if (!cache.preStyle) cache.preStyle = new WeakMap();\n cache.preStyle.set(child, cssText);\n }\n }\n }\n } else {\n // ShadowRoot without slots: clone full content\n const shadowFrag = document.createDocumentFragment();\n for (const child of node.shadowRoot.childNodes) {\n if (child.nodeType === Node.ELEMENT_NODE && child.tagName === \"STYLE\") {\n const cssText = child.textContent || \"\";\n if (cssText.trim() && compress) {\n if (!cache.preStyle) cache.preStyle = new WeakMap();\n cache.preStyle.set(child, cssText);\n }\n continue;\n }\n const clonedChild = deepClone(child, compress, options, originalRoot || node);\n if (clonedChild) shadowFrag.appendChild(clonedChild);\n }\n clone.appendChild(shadowFrag);\n }\n }\n\n // 13. Slot outside ShadowRoot\n if (node.tagName === \"SLOT\") {\n const assigned = node.assignedNodes?.({ flatten: true }) || [];\n const nodesToClone = assigned.length > 0 ? assigned : Array.from(node.childNodes);\n const fragment = document.createDocumentFragment();\n\n for (const child of nodesToClone) {\n const clonedChild = deepClone(child, compress, options, originalRoot || node);\n if (clonedChild) fragment.appendChild(clonedChild);\n }\n return fragment;\n }\n\n // 14. Clone children (light DOM), skipping duplicates\n for (const child of node.childNodes) {\n if (clonedAssignedNodes.has(child)) continue;\n\n const clonedChild = deepClone(child, compress, options, originalRoot || node);\n if (clonedChild) clone.appendChild(clonedChild);\n }\n\n // Adjust select value after children are cloned\n if (pendingSelectValue !== null && clone instanceof HTMLSelectElement) {\n clone.value = pendingSelectValue;\n for (const opt of clone.options) {\n if (opt.value === pendingSelectValue) {\n opt.setAttribute(\"selected\", \"\");\n } else {\n opt.removeAttribute(\"selected\");\n }\n }\n }\n\n return clone;\n} \n"], ["/snapdom/src/core/prepare.js", "/**\n * Prepares a deep clone of an element, inlining pseudo-elements and generating CSS classes.\n * @module prepare\n */\n\nimport { generateCSSClasses} from '../utils/cssTools.js';\nimport { stripTranslate} from '../utils/helpers.js';\nimport { deepClone } from './clone.js';\nimport { inlinePseudoElements } from '../modules/pseudo.js';\nimport { inlineExternalDef } from '../modules/svgDefs.js';\nimport { cache } from '../core/cache.js';\n\n/**\n * Prepares a clone of an element for capture, inlining pseudo-elements and generating CSS classes.\n *\n * @param {Element} element - Element to clone\n * @param {boolean} [compress=false] - Whether to compress style keys\n * @param {boolean} [embedFonts=false] - Whether to embed custom fonts\n * @param {Object} [options={}] - Capture options\n * @param {string[]} [options.exclude] - CSS selectors for elements to exclude\n * @param {Function} [options.filter] - Custom filter function\n * @returns {Promise} Object containing the clone, generated CSS, and style cache\n */\n\nexport async function prepareClone(element, compress = false, embedFonts = false, options = {}) {\n\n let clone\n let classCSS = '';\n try {\n clone = deepClone(element, compress, options, element);\n } catch (e) {\n console.warn(\"deepClone failed:\", e);\n throw e;\n }\n try {\n await inlinePseudoElements(element, clone, compress, embedFonts, options.useProxy);\n } catch (e) {\n console.warn(\"inlinePseudoElements failed:\", e);\n }\n try {\n inlineExternalDef(clone);\n } catch (e) {\n console.warn(\"inlineExternalDef failed:\", e);\n }\n if (compress) {\n const keyToClass = generateCSSClasses();\n classCSS = Array.from(keyToClass.entries()).map(([key, className]) => `.${className}{${key}}`).join(\"\");\n for (const [node, key] of cache.preStyleMap.entries()) {\n if (node.tagName === \"STYLE\") continue;\n const className = keyToClass.get(key);\n if (className) node.classList.add(className);\n const bgImage = node.style?.backgroundImage;\n node.removeAttribute(\"style\");\n if (bgImage && bgImage !== \"none\") node.style.backgroundImage = bgImage;\n }\n } else {\n for (const [node, key] of cache.preStyleMap.entries()) {\n if (node.tagName === \"STYLE\") continue;\n node.setAttribute(\"style\", key.replace(/;/g, \"; \"));\n }\n }\n for (const [cloneNode, originalNode] of cache.preNodeMap.entries()) {\n const scrollX = originalNode.scrollLeft;\n const scrollY = originalNode.scrollTop;\n const hasScroll = scrollX || scrollY;\n if (hasScroll && cloneNode instanceof HTMLElement) {\n cloneNode.style.overflow = \"hidden\";\n cloneNode.style.scrollbarWidth = \"none\";\n cloneNode.style.msOverflowStyle = \"none\";\n const inner = document.createElement(\"div\");\n inner.style.transform = `translate(${-scrollX}px, ${-scrollY}px)`;\n inner.style.willChange = \"transform\";\n inner.style.display = \"inline-block\";\n inner.style.width = \"100%\";\n while (cloneNode.firstChild) {\n inner.appendChild(cloneNode.firstChild);\n }\n cloneNode.appendChild(inner);\n }\n }\n if (element === cache.preNodeMap.get(clone)) {\n const computed = cache.preStyle.get(element) || window.getComputedStyle(element);\n cache.preStyle.set(element, computed);\n const transform = stripTranslate(computed.transform);\n clone.style.margin = \"0\";\n clone.style.position = \"static\";\n clone.style.top = \"auto\";\n clone.style.left = \"auto\";\n clone.style.right = \"auto\";\n clone.style.bottom = \"auto\";\n clone.style.zIndex = \"auto\";\n clone.style.float = \"none\";\n clone.style.clear = \"none\";\n clone.style.transform = transform || \"\";\n }\n for (const [cloneNode, originalNode] of cache.preNodeMap.entries()) {\n if (originalNode.tagName === \"PRE\") {\n cloneNode.style.marginTop = \"0\";\n cloneNode.style.marginBlockStart = \"0\";\n }\n }\n return { clone, classCSS };\n}\n"], ["/snapdom/src/modules/pseudo.js", "/**\n * Utilities for inlining ::before and ::after pseudo-elements.\n * @module pseudo\n */\n\nimport { getStyle, snapshotComputedStyle, parseContent, extractURL, safeEncodeURI, fetchImage, inlineSingleBackgroundEntry, splitBackgroundImage } from '../utils/helpers.js';\nimport { getStyleKey } from '../utils/cssTools.js';\nimport { iconToImage } from '../modules/fonts.js';\nimport { isIconFont } from '../modules/iconFonts.js';\nimport { cache } from '../core/cache.js'\n\n/**\n * Creates elements to represent ::before, ::after, and ::first-letter pseudo-elements, inlining their styles and content.\n *\n * @param {Element} source - Original element\n * @param {Element} clone - Cloned element\n * @param {boolean} compress - Whether to compress style keys\n * @param {boolean} embedFonts - Whether to embed icon fonts as images\n * @returns {Promise} Promise that resolves when all pseudo-elements are processed\n */\n\nexport async function inlinePseudoElements(source, clone, compress, embedFonts = false, useProxy) {\n if (!(source instanceof Element) || !(clone instanceof Element)) return;\n for (const pseudo of [\"::before\", \"::after\", \"::first-letter\"]) {\n try {\n const style = getStyle(source, pseudo);\n if (!style || typeof style[Symbol.iterator] !== \"function\") continue;\n if (pseudo === \"::first-letter\") {\n const normal = getComputedStyle(source);\n const isMeaningful = style.color !== normal.color || style.fontSize !== normal.fontSize || style.fontWeight !== normal.fontWeight;\n if (!isMeaningful) continue;\n const textNode = Array.from(clone.childNodes).find(\n (n) => n.nodeType === Node.TEXT_NODE && n.textContent && n.textContent.trim().length > 0\n );\n if (!textNode) continue;\n const text = textNode.textContent;\n const match = text.match(/^([^\\p{L}\\p{N}\\s]*[\\p{L}\\p{N}](?:['’])?)/u);\n const first = match?.[0];\n const rest = text.slice(first?.length || 0);\n if (!first || /[\\uD800-\\uDFFF]/.test(first)) continue;\n const span = document.createElement(\"span\");\n span.textContent = first;\n span.dataset.snapdomPseudo = \"::first-letter\";\n const snapshot = snapshotComputedStyle(style);\n const key = getStyleKey(snapshot, \"span\", compress);\n cache.preStyleMap.set(span, key);\n const restNode = document.createTextNode(rest);\n clone.replaceChild(restNode, textNode);\n clone.insertBefore(span, restNode);\n continue;\n }\nconst content = style.getPropertyValue(\"content\");\nconst bg = style.getPropertyValue(\"background-image\");\nconst bgColor = style.getPropertyValue(\"background-color\");\n\nconst fontFamily = style.getPropertyValue(\"font-family\");\nconst fontSize = parseInt(style.getPropertyValue(\"font-size\")) || 32;\nconst fontWeight = parseInt(style.getPropertyValue(\"font-weight\")) || false;\nconst color = style.getPropertyValue(\"color\") || \"#000\";\nconst display = style.getPropertyValue(\"display\");\nconst width = parseFloat(style.getPropertyValue(\"width\"));\nconst height = parseFloat(style.getPropertyValue(\"height\"));\nconst borderStyle = style.getPropertyValue(\"border-style\");\nconst transform = style.getPropertyValue(\"transform\");\n\nconst isIconFont2 = isIconFont(fontFamily);\n\n// Detect counter() || counters()\nlet cleanContent;\nif (/counter\\s*\\(|counters\\s*\\(/.test(content)) {\n cleanContent = \"- \";\n} else {\n cleanContent = parseContent(content);\n}\n\nconst hasContent = content !== \"none\";\nconst hasExplicitContent = hasContent && cleanContent !== \"\";\nconst hasBg = bg && bg !== \"none\";\nconst hasBgColor = bgColor && bgColor !== \"transparent\" && bgColor !== \"rgba(0, 0, 0, 0)\";\nconst hasBox = display !== \"inline\" && (width > 0 || height > 0);\nconst hasBorder = borderStyle && borderStyle !== \"none\";\nconst hasTransform = transform && transform !== \"none\";\n\nconst shouldRender =\n hasExplicitContent || hasBg || hasBgColor || hasBox || hasBorder || hasTransform;\n\nif (!shouldRender) continue;\n\nconst pseudoEl = document.createElement(\"span\");\npseudoEl.dataset.snapdomPseudo = pseudo;\nconst snapshot = snapshotComputedStyle(style);\nconst key = getStyleKey(snapshot, \"span\", compress);\ncache.preStyleMap.set(pseudoEl, key);\n\nif (isIconFont2 && cleanContent.length === 1) {\n const imgEl = document.createElement(\"img\");\n imgEl.src = await iconToImage(cleanContent, fontFamily, fontWeight, fontSize, color);\n imgEl.style = `width:${fontSize}px;height:auto;object-fit:contain;`;\n pseudoEl.appendChild(imgEl);\n} else if (cleanContent.startsWith(\"url(\")) {\n const rawUrl = extractURL(cleanContent);\n if (rawUrl && rawUrl.trim() !== \"\") {\n try {\n const imgEl = document.createElement(\"img\");\n const dataUrl = await fetchImage(safeEncodeURI(rawUrl, { useProxy }));\n imgEl.src = dataUrl;\n imgEl.style = `width:${fontSize}px;height:auto;object-fit:contain;`;\n pseudoEl.appendChild(imgEl);\n } catch (e) {\n console.error(`[snapdom] Error in pseudo ${pseudo} for`, source, e);\n }\n }\n} else if (!isIconFont2 && hasExplicitContent) {\n pseudoEl.textContent = cleanContent;\n}\n\nif (hasBg) {\n try {\n const bgSplits = splitBackgroundImage(bg);\n const newBgParts = await Promise.all(\n bgSplits.map((entry) => inlineSingleBackgroundEntry(entry))\n );\n pseudoEl.style.backgroundImage = newBgParts.join(\", \");\n } catch (e) {\n console.warn(`[snapdom] Failed to inline background-image for ${pseudo}`, e);\n }\n}\n\nif (hasBgColor) pseudoEl.style.backgroundColor = bgColor;\n\nconst hasContent2 =\n pseudoEl.childNodes.length > 0 ||\n (pseudoEl.textContent && pseudoEl.textContent.trim() !== \"\");\nconst hasVisibleBox = hasContent2 || hasBg || hasBgColor || hasBox || hasBorder || hasTransform;\n\nif (!hasVisibleBox) continue;\n\npseudo === \"::before\"\n ? clone.insertBefore(pseudoEl, clone.firstChild)\n : clone.appendChild(pseudoEl);\n\n } catch (e) {\n console.warn(`[snapdom] Failed to capture ${pseudo} for`, source, e);\n }\n }\n const sChildren = Array.from(source.children);\n const cChildren = Array.from(clone.children).filter((child) => !child.dataset.snapdomPseudo);\n for (let i = 0; i < Math.min(sChildren.length, cChildren.length); i++) {\n await inlinePseudoElements(\n sChildren[i],\n cChildren[i],\n compress,\n embedFonts,\n useProxy\n );\n }\n}\n"], ["/snapdom/src/api/preCache.js", "import { getStyle, inlineSingleBackgroundEntry, fetchImage, splitBackgroundImage } from '../utils/helpers.js';\nimport { embedCustomFonts } from '../modules/fonts.js';\nimport { precacheCommonTags } from '../utils/cssTools.js';\nimport { cache } from '../core/cache.js';\n\n/**\n * Preloads images, background images, and optionally fonts into cache before DOM capture.\n *\n * @param {Document|Element} [root=document] - The root node to search for resources\n * @param {Object} [options={}] - Pre-caching options\n * @returns {Promise} Resolves when all resources are pre-cached\n */\n\nexport async function preCache(root = document, options = {}) {\n const { embedFonts = true, reset = false} = options;\n if (reset) {\n cache.reset()\n return;\n }\n await document.fonts.ready;\n precacheCommonTags();\n let imgEls = [], allEls = [];\n if (root?.querySelectorAll) {\n imgEls = Array.from(root.querySelectorAll(\"img[src]\"));\n allEls = Array.from(root.querySelectorAll(\"*\"));\n }\n const promises = [];\n for (const img of imgEls) {\n const src = img.src;\n if (!cache.image.has(src)) {\n \n promises.push(\n fetchImage(src, { useProxy: options.useProxy}).then((dataURL) => cache.image.set(src, dataURL)).catch(() => {\n })\n );\n }\n }\n for (const el of allEls) {\n const bg = getStyle(el).backgroundImage;\n if (bg && bg !== \"none\") {\n const bgSplits = splitBackgroundImage(bg);\n for (const entry of bgSplits) {\n const isUrl = entry.startsWith(\"url(\");\n if (isUrl) {\n promises.push(\n inlineSingleBackgroundEntry(entry, options).catch(() => {\n })\n );\n }\n }\n }\n }\n if (embedFonts) {\n await embedCustomFonts({ preCached: true });\n }\n await Promise.all(promises);\n}\n"], ["/snapdom/src/api/snapdom.js", "/**\n * Main API for snapDOM: capture DOM elements as SVG and raster images.\n * Provides utilities for exporting, downloading, and converting DOM captures.\n * @module snapdom\n */\n\nimport { captureDOM } from '../core/capture';\nimport { isSafari } from '../utils/helpers.js';\nimport { extendIconFonts } from '../modules/iconFonts.js';\n\n/**\n * Converts an SVG data URL to an HTMLImageElement.\n *\n * @param {string} url - SVG data URL\n * @param {Object} options\n * @param {number} [options.dpr=1] - Device pixel ratio\n * @param {number} [options.scale=1] - Scale multiplier\n * @returns {Promise} The resulting image\n */\n\n async function toImg(url, { dpr = 1, scale = 1 }) {\n const img = new Image();\n img.src = url;\n await img.decode();\n img.width = img.width * scale ;\n img.height = img.height * scale ;\n \n return img;\n}\n\n/**\n * Converts an SVG data URL to a Canvas element.\n *\n * @param {string} url - SVG data URL\n * @param {Object} options\n * @param {number} [options.dpr=1] - Device pixel ratio\n * @param {number} [options.scale=1] - Scale multiplier\n * @returns {Promise} The resulting canvas\n */\n\nasync function toCanvas(url, { dpr = 1, scale = 1 } = {}) {\n const img = new Image();\n img.src = url;\n img.crossOrigin = 'anonymous';\n img.loading = 'eager';\n img.decoding = 'sync';\n\n const isSafariBrowser = isSafari();\n let appended = false;\n\n if (isSafariBrowser) {\n document.body.appendChild(img);\n appended = true;\n }\n\n await img.decode();\n\n if (isSafariBrowser) {\n await new Promise(resolve => setTimeout(resolve, 100));\n }\n\n if (img.width === 0 || img.height === 0) {\n if (appended) img.remove();\n throw new Error('Image failed to load or has no dimensions');\n }\n\n const width = img.width * scale;\n const height = img.height * scale;\n\n const canvas = document.createElement('canvas');\n canvas.width = Math.ceil(width * dpr);\n canvas.height = Math.ceil(height * dpr);\n canvas.style.width = `${width}px`;\n canvas.style.height = `${height}px`;\n\n const ctx = canvas.getContext('2d');\n ctx.scale(dpr, dpr);\n ctx.drawImage(img, 0, 0, width, height);\n\n if (appended) img.remove();\n\n return canvas;\n}\n\n/**\n * Converts a DOM snapshot (SVG data URL) into a Blob of the specified format.\n *\n * @param {string} url - SVG data URL\n * @param {Object} [options]\n * @param {string} [options.format=\"svg\"] - Output format: \"svg\", \"png\", \"jpeg\", \"webp\"\n * @param {number} [options.dpr=1] - Device pixel ratio\n * @param {number} [options.scale=1] - Scale multiplier\n * @param {string} [options.backgroundColor=\"#fff\"] - Background for raster formats\n * @param {number} [options.quality] - JPEG/WebP quality (0–1)\n * @returns {Promise} The resulting Blob\n */\nasync function toBlob(url, {\n type = \"svg\",\n scale = 1,\n backgroundColor = \"#fff\",\n quality\n} = {}) {\n const mime = {\n jpg: \"image/jpeg\",\n jpeg: \"image/jpeg\",\n png: \"image/png\",\n webp: \"image/webp\",\n }[type] || \"image/png\";\n\n if (type === \"svg\") {\n const svgText = decodeURIComponent(url.split(\",\")[1]);\n return new Blob([svgText], { type: \"image/svg+xml\" });\n }\n\n const canvas = await createBackground(url, { dpr: 1, scale }, backgroundColor);\n return new Promise((resolve) => {\n canvas.toBlob(blob => resolve(blob), `${mime}`, quality);\n });\n}\n\n\n\n/**\n * Creates a canvas with a background color from an SVG data URL.\n *\n * @param {string} url - SVG data URL\n * @param {Object} options\n * @param {number} [options.dpr=1] - Device pixel ratio\n * @param {number} [options.scale=1] - Scale multiplier\n * @param {string} [backgroundColor] - Background color to apply\n * @returns {Promise} The resulting canvas\n */\n\n async function createBackground(url, { dpr = 1, scale = 1 }, backgroundColor) {\n const baseCanvas = await toCanvas(url, { dpr, scale });\n if (!backgroundColor) return baseCanvas;\n\n const temp = document.createElement(\"canvas\");\n temp.width = baseCanvas.width;\n temp.height = baseCanvas.height;\n const ctx = temp.getContext(\"2d\");\n\n ctx.fillStyle = backgroundColor;\n ctx.fillRect(0, 0, temp.width, temp.height);\n ctx.drawImage(baseCanvas, 0, 0);\n\n return temp;\n}\n\n/**\n * Converts an SVG data URL to a raster image (PNG, JPEG, WebP).\n *\n * @param {string} url - SVG data URL\n * @param {Object} options\n * @param {number} [options.dpr=1] - Device pixel ratio\n * @param {number} [options.scale=1] - Scale multiplier\n * @param {string} [options.backgroundColor=\"#fff\"] - Background color for rasterization\n * @param {number} [options.quality] - Image quality (for JPEG/WebP)\n * @param {string} [format=\"png\"] - Output format: \"png\", \"jpeg\", or \"webp\"\n * @returns {Promise} The resulting raster image\n */\n\n async function toRasterImg(url, { dpr = 1, scale = 1, backgroundColor, quality }, format = \"png\") {\n const defaultBg = [\"jpg\", \"jpeg\", \"webp\"].includes(format) ? \"#fff\" : undefined;\n const finalBg = backgroundColor ?? defaultBg;\n\n const canvas = await createBackground(url, { dpr, scale }, finalBg);\n\n const img = new Image();\n img.src = canvas.toDataURL(`image/${format}`, quality);\n await img.decode();\n\n img.style.width = `${canvas.width / dpr}px`;\n img.style.height = `${canvas.height / dpr}px`;\n\n return img;\n}\n\n/**\n * Downloads a captured image in the specified format.\n *\n * @param {string} url - SVG data URL\n * @param {Object} options\n * @param {number} [options.dpr=1] - Device pixel ratio\n * @param {number} [options.scale=1] - Scale multiplier\n * @param {string} [options.backgroundColor=\"#fff\"] - Background color for rasterization\n * @param {string} [options.format=\"png\"] - Output format\n * @param {string} [options.filename=\"capture\"] - Download filename\n * @returns {Promise} Resolves when download is triggered\n */\n\n async function download(url,{ dpr = 1, scale = 1, backgroundColor, format = \"png\", filename = \"snapDOM\"} = {}) {\n if (format === \"svg\") {\n const blob = await toBlob(url);\n const objectURL = URL.createObjectURL(blob);\n const a = document.createElement(\"a\");\n a.href = objectURL;\n a.download = `${filename}.svg`;\n a.click();\n URL.revokeObjectURL(objectURL);\n return;\n }\n\n const defaultBg = [\"jpg\", \"jpeg\", \"webp\"].includes(format) ? \"#fff\" : undefined;\n const finalBg = backgroundColor ?? defaultBg;\n\n const canvas = await createBackground(url, { dpr, scale }, finalBg);\n const mime = {\n jpg: \"image/jpeg\",\n jpeg: \"image/jpeg\",\n png: \"image/png\",\n webp: \"image/webp\",\n }[format] || \"image/png\";\n\n const dataURL = canvas.toDataURL(mime);\n\n const a = document.createElement(\"a\");\n a.href = dataURL;\n a.download = `${filename}.${format}`;\n a.click();\n}\n\n/**\n * Main entry point: captures a DOM element and returns an object with export methods.\n *\n * @param {Element} element - DOM element to capture\n * @param {Object} [options={}] - Capture options\n * @returns {Promise} Object with export methods (toRaw, toImg, toCanvas, etc.)\n */\n\nexport async function snapdom(element, options = {}) {\n options = { scale: 1, ...options };\n if (!element) throw new Error(\"Element cannot be null or undefined\");\n if (options.iconFonts) {\n extendIconFonts(options.iconFonts);\n }\n return await snapdom.capture(element, options);\n}\n\n/**\n * Captures a DOM element and returns an object with export methods (internal use).\n *\n * @param {Element} el - DOM element to capture\n * @param {Object} [options={}] - Capture options\n * @returns {Promise} Object with export methods\n */\n\nsnapdom.capture = async (el, options = {}) => {\n const url = await captureDOM(el, options);\n const dpr = window.devicePixelRatio || 1;\n const scale = options.scale || 1;\n\n return {\n url,\n options,\n toRaw: () => url,\n toImg: () => toImg(url, { dpr, scale }),\n toCanvas: () => toCanvas(url, { dpr, scale }),\n toBlob: (options) => toBlob(url, { dpr, scale, ...options }),\n toPng: (options) => toRasterImg(url, { dpr, scale, ...options }, \"png\"),\n toJpg: (options) => toRasterImg(url, { dpr, scale, ...options }, \"jpeg\"),\n toWebp: (options) => toRasterImg(url, { dpr, scale, ...options }, \"webp\"),\n download: ({ format = \"png\", filename = \"capture\", backgroundColor } = {}) => download(url, { dpr, scale, backgroundColor, format, filename})\n };\n};\n\n// Compatibilidad\nsnapdom.toRaw = async (el, options) => (await snapdom.capture(el, options)).toRaw();\nsnapdom.toImg = async (el, options) => (await snapdom.capture(el, options)).toImg();\nsnapdom.toCanvas = async (el, options) => (await snapdom.capture(el, options)).toCanvas();\nsnapdom.toBlob = async (el, options) => (await snapdom.capture(el, options)).toBlob(options);\nsnapdom.toPng = async (el, options) => (await snapdom.capture(el, options)).toPng(options);\nsnapdom.toJpg = async (el, options) => (await snapdom.capture(el, options)).toJpg(options);\nsnapdom.toWebp = async (el, options) => (await snapdom.capture(el, options)).toWebp(options);\nsnapdom.download = async (el, options = {}) => {\n const {\n format = \"png\",\n filename = \"capture\",\n backgroundColor,\n ...rest\n } = options;\n\n const capture = await snapdom.capture(el, rest);\n return await capture.download({ format, filename, backgroundColor });\n};"], ["/snapdom/src/modules/background.js", "/**\n * Utilities for inlining background images as data URLs.\n * @module background\n */\n\nimport { getStyle, inlineSingleBackgroundEntry, splitBackgroundImage } from '../utils/helpers.js';\nimport { cache } from '../core/cache.js'\n\n/**\n * Converts all background images in the cloned element tree to data URLs.\n *\n * @param {Element} source - Original element\n * @param {Element} clone - Cloned element\n * @param {Object} [options={}] - Options for image processing\n * @returns {Promise} Promise that resolves when all background images are processed\n */\nexport async function inlineBackgroundImages(source, clone, options = {}) {\n const queue = [[source, clone]];\n\n const imageProps = [\n \"background-image\",\n \"mask\",\n \"mask-image\", \"-webkit-mask-image\",\n \"mask-source\", \"mask-box-image-source\",\n \"mask-border-source\",\n \"-webkit-mask-box-image-source\"\n ];\n\n while (queue.length) {\n const [srcNode, cloneNode] = queue.shift();\n const style = cache.preStyle.get(srcNode) || getStyle(srcNode);\n if (!cache.preStyle.has(srcNode)) cache.preStyle.set(srcNode, style);\n\n for (const prop of imageProps) {\n const val = style.getPropertyValue(prop);\n if (!val || val === \"none\") continue;\n\n const splits = splitBackgroundImage(val);\n const inlined = await Promise.all(\n splits.map(entry => inlineSingleBackgroundEntry(entry, options))\n );\n\n if (inlined.some(p => p && p !== \"none\" && !/^url\\(undefined/.test(p))) {\n cloneNode.style.setProperty(prop, inlined.join(\", \"));\n }\n }\n\n // También preservamos el background-color como antes\n const bgColor = style.getPropertyValue(\"background-color\");\n if (\n bgColor &&\n bgColor !== \"transparent\" &&\n bgColor !== \"rgba(0, 0, 0, 0)\"\n ) {\n cloneNode.style.backgroundColor = bgColor;\n }\n\n const sChildren = Array.from(srcNode.children);\n const cChildren = Array.from(cloneNode.children);\n for (let i = 0; i < Math.min(sChildren.length, cChildren.length); i++) {\n queue.push([sChildren[i], cChildren[i]]);\n }\n }\n}\n\n"], ["/snapdom/src/modules/images.js", "/**\n * Utilities for inlining elements as data URLs or placeholders.\n * @module images\n */\n\nimport { fetchImage } from '../utils/helpers.js';\n\n/**\n * Converts all elements in the clone to data URLs or replaces them with placeholders if loading fails.\n *\n * @param {Element} clone - Clone of the original element\n * @param {Object} [options={}] - Options for image processing\n * @returns {Promise} Promise that resolves when all images are processed\n */\nexport async function inlineImages(clone, options = {}) {\n const imgs = Array.from(clone.querySelectorAll(\"img\"));\n const processImg = async (img) => {\n const src = img.src;\n try {\n const dataUrl = await fetchImage(src, { useProxy: options.useProxy });\n img.src = dataUrl;\n if (!img.width) img.width = img.naturalWidth || 100;\n if (!img.height) img.height = img.naturalHeight || 100;\n } catch {\n const fallback = document.createElement(\"div\");\n fallback.style = `width: ${img.width || 100}px; height: ${img.height || 100}px; background: #ccc; display: inline-block; text-align: center; line-height: ${img.height || 100}px; color: #666; font-size: 12px;`;\n fallback.innerText = \"img\";\n img.replaceWith(fallback);\n }\n };\n for (let i = 0; i < imgs.length; i += 4) {\n const group = imgs.slice(i, i + 4).map(processImg);\n await Promise.allSettled(group);\n }\n}"], ["/snapdom/__tests__/snapdom.benchmark.js", "import { bench, describe, beforeEach, afterEach } from 'vitest';\nimport { domToDataUrl } from 'https://unpkg.com/modern-screenshot';\nimport * as htmlToImage from 'https://cdn.jsdelivr.net/npm/html-to-image@1.11.13/+esm';\n//import { toPng, toJpeg, toBlob, toPixelData, toSvg } from 'https://cdn.jsdelivr.net/npm/html-to-image@1.11.13/dist/html-to-image.min.js';\nimport { snapdom as sd } from 'https://cdn.jsdelivr.net/npm/@zumer/snapdom@1.8.0/dist/snapdom.mjs';\nimport { snapdom } from '../src/index';\n\n\nlet html2canvasLoaded = false;\n\nasync function loadHtml2Canvas() {\n if (html2canvasLoaded) return;\n await new Promise((resolve, reject) => {\n const script = document.createElement('script');\n script.src = 'https://cdn.jsdelivr.net/npm/html2canvas@1.4.1/dist/html2canvas.min.js';\n script.onload = () => resolve();\n script.onerror = reject;\n document.head.appendChild(script);\n });\n html2canvasLoaded = true;\n}\n\nawait loadHtml2Canvas();\n\n\n\nconst sizes = [\n { width: 200, height: 100, label: 'Small element (200x100)' },\n { width: 400, height: 300, label: 'Modal size (400x300)' },\n { width: 1200, height: 800, label: 'Page view (1200x800)' },\n { width: 2000, height: 1500, label: 'Large scroll area (2000x1500)' },\n { width: 4000, height: 2000, label: 'Very large element (4000x2000)' },\n];\n\nfor (const size of sizes) {\n describe(`Benchmark simple node at ${size.label}`, () => {\n let container;\n\n async function setupContainer() { \n if (container && document.body.contains(container)) {\n return;\n }\n container = document.createElement('div');\n container.style.width = `${size.width}px`;\n container.style.height = `${size.height}px`;\n container.style.background = 'linear-gradient(to right, red, blue)';\n container.style.fontFamily = 'Arial, sans-serif';\n container.style.display = 'flex';\n container.style.alignItems = 'center';\n container.style.justifyContent = 'center';\n container.style.fontSize = '24px';\n container.innerHTML = `

${size.label}

`;\n document.body.appendChild(container);\n } \n\n /* async function setupContainer() {\n if (container && document.body.contains(container)) return;\n \n container = document.createElement('div');\n container.style.width = `${size.width}px`;\n container.style.height = `${size.height}px`;\n container.style.padding = '20px';\n container.style.overflow = 'auto';\n container.style.background = 'white';\n container.style.border = '2px solid black';\n container.style.fontFamily = 'Arial, sans-serif';\n container.style.color = '#333';\n container.style.position = 'relative';\n \n const grid = document.createElement('div');\n grid.style.display = 'grid';\n grid.style.gridTemplateColumns = 'repeat(auto-fill, minmax(120px, 1fr))';\n grid.style.gap = '10px';\n \n for (let i = 0; i < Math.floor((size.width * size.height) / 20000); i++) {\n const card = document.createElement('div');\n card.style.padding = '10px';\n card.style.borderRadius = '8px';\n card.style.background = i % 2 === 0 ? '#f0f0f0' : '#e0eaff';\n card.style.boxShadow = '0 2px 5px rgba(0,0,0,0.1)';\n card.style.display = 'flex';\n card.style.flexDirection = 'column';\n card.style.alignItems = 'center';\n \n const title = document.createElement('h3');\n title.textContent = `Card ${i + 1}`;\n title.style.margin = '0 0 10px 0';\n title.style.fontSize = '14px';\n \n const icon = document.createElement('div');\n icon.style.width = '30px';\n icon.style.height = '30px';\n icon.style.borderRadius = '50%';\n icon.style.background = i % 2 === 0 ? 'red' : 'blue';\n icon.style.marginBottom = '10px';\n \n const text = document.createElement('p');\n text.textContent = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit.';\n text.style.fontSize = '12px';\n text.style.textAlign = 'center';\n \n card.appendChild(icon);\n card.appendChild(title);\n card.appendChild(text);\n grid.appendChild(card);\n }\n \n container.appendChild(grid);\n document.body.appendChild(container);\n }\n */\n afterEach(() => {\n if (container) {\n container.remove();\n container = null;\n }\n });\n\n bench('snapDOM current version', async () => {\n await setupContainer();\n await snapdom.toRaw(container);\n });\n\n bench('snapDOM V1.8.0', async () => {\n await setupContainer();\n await sd.toRaw(container);\n });\n\n bench('html2canvas capture', async () => {\n await setupContainer();\n const canvas = await window.html2canvas(container, { logging: false, scale: 1 });\n await canvas.toDataURL();\n });\n\n bench('modern-screenshot capture', async () => {\n await setupContainer();\n await domToDataUrl(container);\n });\n\n bench('html-to-image capture', async () => {\n await setupContainer();\n await htmlToImage.toSvg(container);\n });\n });\n}\n"], ["/snapdom/__tests__/snapdom.advance.test.js", "import { describe, it, expect, beforeEach, afterEach } from 'vitest';\nimport { snapdom } from '../src/index';\n\ndescribe('snapdom advanced tests', () => {\n let testElement;\n\n beforeEach(() => {\n testElement = document.createElement('div');\n testElement.style.width = '100px';\n testElement.style.height = '50px';\n testElement.innerHTML = '

Hello World

';\n document.body.appendChild(testElement);\n });\n\n afterEach(() => {\n document.body.removeChild(testElement);\n });\n\n it('should generate different SVGs for different scales', async () => {\n const svg1 = await snapdom.toImg(testElement, { scale: 1 });\n const svg2 = await snapdom.toImg(testElement, { scale: 2 });\n expect(svg1).not.toBe(svg2);\n });\n\n it('captured SVG should contain inner text content', async () => {\n const svgDataUrl = await snapdom.toRaw(testElement);\n const svgText = decodeURIComponent(svgDataUrl.split(',')[1]);\n expect(svgText).toContain('Hello World');\n });\n\n it('should throw an error if element is null', async () => {\n await expect(() => snapdom.toRaw(null)).rejects.toThrow();\n });\n\n it('should generate SVG with correct attributes', async () => {\n const svgDataUrl = await snapdom.toRaw(testElement);\n const svgText = decodeURIComponent(svgDataUrl.split(',')[1]);\n const parser = new DOMParser();\n const doc = parser.parseFromString(svgText, 'image/svg+xml');\n const svg = doc.querySelector('svg');\n\n expect(svg).not.toBeNull();\n expect(svg.getAttribute('width')).toBe('100');\n expect(svg.getAttribute('height')).toBe('50');\n expect(svg.getAttribute('viewBox')).toBe('0 0 100 50');\n });\n\n it('snapdom.toBlob should contain valid SVG content', async () => {\n const blob = await snapdom.toBlob(testElement);\n const text = await blob.text();\n expect(text).toContain('');\n });\n\n it('should replace iframes with fallback visuals', async () => {\n const iframe = document.createElement('iframe');\n iframe.style.width = '200px';\n iframe.style.height = '100px';\n testElement.appendChild(iframe);\n\n const svgDataUrl = await snapdom.toRaw(testElement);\n const svgText = decodeURIComponent(svgDataUrl.split(',')[1]);\n\n const parser = new DOMParser();\n const doc = parser.parseFromString(svgText, 'image/svg+xml');\n\n // No debe haber iframes en el SVG\n expect(doc.querySelectorAll('iframe').length).toBe(0);\n\n // Buscamos divs con estilo inline que contengan repeating-linear-gradient\n const fallbackDivs = Array.from(doc.querySelectorAll('div')).filter(div => {\n const styleAttr = div.getAttribute('style') || '';\n return styleAttr.includes('repeating-linear-gradient');\n });\n\n expect(fallbackDivs.length).toBeGreaterThan(0);\n});\n\n \n});\n"], ["/snapdom/src/modules/styles.js", "import { getStyleKey } from '../utils/cssTools.js';\nimport { getStyle } from '../utils/helpers.js';\nimport {cache} from '../core/cache.js'\n\nfunction snapshotComputedStyleFull(style) {\n const result = {};\n for (let i = 0; i < style.length; i++) {\n const prop = style[i];\n let val = style.getPropertyValue(prop);\n\n // Opcional: evitar URLs externas que puedan romper renderizado\n if (\n (prop === 'background-image' || prop === 'content') &&\n val.includes('url(') &&\n !val.includes('data:')\n ) {\n val = 'none';\n }\n\n result[prop] = val;\n }\n return result;\n}\n\nexport function inlineAllStyles(source, clone, compress) {\n if (source.tagName === 'STYLE') return;\n\n if (!cache.preStyle.has(source)) {\n cache.preStyle.set(source, getStyle(source));\n }\n const style = cache.preStyle.get(source);\n\n if (!cache.snapshot.has(source)) {\n const snapshot = snapshotComputedStyleFull(style);\n cache.snapshot.set(source, snapshot);\n }\n\n const snapshot = cache.snapshot.get(source);\n\n const hash = Object.entries(snapshot)\n .sort(([a], [b]) => a.localeCompare(b))\n .map(([prop, val]) => `${prop}:${val}`)\n .join(';');\n\n if (cache.snapshotKey.has(hash)) {\n cache.preStyleMap.set(clone, cache.snapshotKey.get(hash));\n return;\n }\n\n const tagName = source.tagName?.toLowerCase() || 'div';\n const key = getStyleKey(snapshot, tagName, compress);\n\n cache.snapshotKey.set(hash, key);\n cache.preStyleMap.set(clone, key);\n}\n"], ["/snapdom/__tests__/snapdom.complex.benchmark.js", "import { bench, describe, beforeEach, afterEach } from 'vitest';\nimport { domToDataUrl } from 'https://unpkg.com/modern-screenshot';\nimport * as htmlToImage from 'https://cdn.jsdelivr.net/npm/html-to-image@1.11.13/+esm';\nimport { snapdom as sd } from 'https://cdn.jsdelivr.net/npm/@zumer/snapdom@1.8.0/dist/snapdom.mjs';\nimport { snapdom } from '../src/index';\n\nlet html2canvasLoaded = false;\n\nasync function loadHtml2Canvas() {\n if (html2canvasLoaded) return;\n await new Promise((resolve, reject) => {\n const script = document.createElement('script');\n script.src = 'https://cdn.jsdelivr.net/npm/html2canvas@1.4.1/dist/html2canvas.min.js';\n script.onload = () => resolve();\n script.onerror = reject;\n document.head.appendChild(script);\n });\n html2canvasLoaded = true;\n}\n\nawait loadHtml2Canvas();\n\nconst sizes = [\n { width: 200, height: 100, label: 'Small element (200x100)' },\n { width: 400, height: 300, label: 'Modal size (400x300)' },\n { width: 1200, height: 800, label: 'Page view (1200x800)' },\n { width: 2000, height: 1500, label: 'Large scroll area (2000x1500)' },\n { width: 4000, height: 2000, label: 'Very large element (4000x2000)' },\n];\n\nfor (const size of sizes) {\n describe(`Benchmark complex node at ${size.label}`, () => {\n let container;\n\n async function setupContainer() {\n if (container && document.body.contains(container)) return;\n \n container = document.createElement('div');\n container.style.width = `${size.width}px`;\n container.style.height = `${size.height}px`;\n container.style.padding = '20px';\n container.style.overflow = 'auto';\n container.style.background = 'white';\n container.style.border = '2px solid black';\n container.style.fontFamily = 'Arial, sans-serif';\n container.style.color = '#333';\n container.style.position = 'relative';\n \n const grid = document.createElement('div');\n grid.style.display = 'grid';\n grid.style.gridTemplateColumns = 'repeat(auto-fill, minmax(120px, 1fr))';\n grid.style.gap = '10px';\n \n for (let i = 0; i < Math.floor((size.width * size.height) / 20000); i++) {\n const card = document.createElement('div');\n card.style.padding = '10px';\n card.style.borderRadius = '8px';\n card.style.background = i % 2 === 0 ? '#f0f0f0' : '#e0eaff';\n card.style.boxShadow = '0 2px 5px rgba(0,0,0,0.1)';\n card.style.display = 'flex';\n card.style.flexDirection = 'column';\n card.style.alignItems = 'center';\n \n const title = document.createElement('h3');\n title.textContent = `Card ${i + 1}`;\n title.style.margin = '0 0 10px 0';\n title.style.fontSize = '14px';\n \n const icon = document.createElement('div');\n icon.style.width = '30px';\n icon.style.height = '30px';\n icon.style.borderRadius = '50%';\n icon.style.background = i % 2 === 0 ? 'red' : 'blue';\n icon.style.marginBottom = '10px';\n \n const text = document.createElement('p');\n text.textContent = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit.';\n text.style.fontSize = '12px';\n text.style.textAlign = 'center';\n \n card.appendChild(icon);\n card.appendChild(title);\n card.appendChild(text);\n grid.appendChild(card);\n }\n \n container.appendChild(grid);\n document.body.appendChild(container);\n \n }\n \n afterEach (async () => {\n if (container) {\n container.remove();\n container = null;\n }\n \n document.body.innerHTML = ''\n });\n\n bench('snapDOM current version', async () => {\n await setupContainer();\n await snapdom.toRaw(container, {compress: true, fast: true});\n });\n\n bench('snapDOM V1.8.0', async () => {\n await setupContainer();\n await sd.toRaw(container);\n });\n \n bench('html2canvas capture', async () => {\n await setupContainer();\n const canvas = await window.html2canvas(container, { logging: false, scale: 1 });\n await canvas.toDataURL();\n });\n\n bench('modern-screenshot capture', async () => {\n await setupContainer();\n await domToDataUrl(container);\n });\n bench('html-to-image capture', async () => {\n await setupContainer();\n await htmlToImage.toSvg(container);\n });\n });\n}\n"], ["/snapdom/__tests__/snapdom.vs.htm2canvas.outputfilesize.test.js", "import { describe, it, beforeEach, afterEach, afterAll } from 'vitest';\nimport { snapdom } from '../src/index';\n//ok\n\ndescribe('Output file size snapdom vs html2canvas (cdn with averaging)', () => {\n let container;\n let html2canvas;\n let report;\n\n beforeEach(async () => {\n container = document.createElement('div');\n container.style.width = '400px';\n container.style.height = '300px';\n container.style.background = 'linear-gradient(to right, red, blue)';\n container.innerHTML = '

Hello Benchmark

Testing multiple runs...

';\n document.body.appendChild(container);\n\n if (!html2canvas) {\n // Cargar html2canvas desde CDN\n await new Promise((resolve, reject) => {\n const script = document.createElement('script');\n script.src = 'https://cdn.jsdelivr.net/npm/html2canvas@1.4.1/dist/html2canvas.min.js';\n script.onload = () => {\n html2canvas = window.html2canvas;\n resolve();\n };\n script.onerror = reject;\n document.head.appendChild(script);\n });\n }\n });\n\n afterEach(() => {\n document.body.removeChild(container);\n });\n\n afterAll(() => {\n console.log(report)\n })\n\n it('snapdom output file size should be smaller than html2canvas', async () => {\n \n // SnapDOM capture\n const snapdomDataURL = await snapdom.toRaw(container, {compress: true});\n const snapdomSizeKB = (snapdomDataURL.length * 3 / 4) / 1024; // Base64 to bytes approx\n \n // html2canvas capture\n const canvas = await html2canvas(container, { logging: false });\n const html2canvasDataURL = await canvas.toDataURL();\n const html2canvasSizeKB = (html2canvasDataURL.length * 3 / 4) / 1024; // Base64 to bytes approx\n \n const differencePercent = ((html2canvasSizeKB - snapdomSizeKB) / html2canvasSizeKB) * 100;\n\n report =`snapDom Captured file size is ${differencePercent.toFixed(2)}% smaller compared to html2canvas (${snapdomSizeKB.toFixed(2)} KB vs. ${html2canvasSizeKB.toFixed(2)} KB)`\n\n})\n\n})\n"], ["/snapdom/__tests__/pseudo.module.test.js", "vi.mock('../src/utils/helpers.js', async () => {\n const actual = await vi.importActual('../src/utils/helpers.js');\n return {\n ...actual,\n fetchImage: vi.fn(),\n };\n});\nvi.mock('../src/modules/fonts.js', async () => {\n const actual = await vi.importActual('../src/modules/fonts.js');\n return {\n ...actual,\n iconToImage: vi.fn(),\n };\n});\n\nimport { describe, it, expect, vi } from 'vitest';\nimport { inlinePseudoElements } from '../src/modules/pseudo.js';\nimport * as helpers from '../src/utils/helpers.js';\nimport * as fonts from '../src/modules/fonts.js';\n\ndescribe('inlinePseudoElements', () => {\n it('does not fail with simple elements', async () => {\n const el = document.createElement('div');\n const clone = document.createElement('div');\n await expect(inlinePseudoElements(el, clone, new Map(), new WeakMap(), false)).resolves.toBeUndefined();\n });\n\n it('handles ::before with text content', async () => {\n const el = document.createElement('div');\n const clone = document.createElement('div');\n vi.spyOn(window, 'getComputedStyle').mockImplementation((_, pseudo) => {\n if (pseudo === '::before') return {\n getPropertyValue: (prop) => prop === 'content' ? '\"★\"' : prop === 'font-family' ? 'Arial' : prop === 'font-size' ? '32' : prop === 'font-weight' ? '400' : prop === 'color' ? '#000' : prop === 'background-image' ? 'none' : prop === 'background-color' ? 'transparent' : '',\n color: '#000', fontSize: '32px', fontWeight: '400', fontFamily: 'Arial',\n };\n return { getPropertyValue: () => '', color: '', fontSize: '', fontWeight: '', fontFamily: '' };\n });\n await inlinePseudoElements(el, clone, new Map(), new WeakMap(), false);\n window.getComputedStyle.mockRestore();\n });\n\n it('handles ::before with icon font', async () => {\n const el = document.createElement('div');\n const clone = document.createElement('div');\n vi.spyOn(window, 'getComputedStyle').mockImplementation((_, pseudo) => {\n if (pseudo === '::before') return {\n getPropertyValue: (prop) => prop === 'content' ? '\"★\"' : prop === 'font-family' ? 'Font Awesome' : prop === 'font-size' ? '32' : prop === 'font-weight' ? '400' : prop === 'color' ? '#000' : prop === 'background-image' ? 'none' : prop === 'background-color' ? 'transparent' : '',\n color: '#000', fontSize: '32px', fontWeight: '400', fontFamily: 'Font Awesome',\n };\n return { getPropertyValue: () => '', color: '', fontSize: '', fontWeight: '', fontFamily: '' };\n });\n fonts.iconToImage.mockResolvedValue('data:image/png;base64,icon');\n await inlinePseudoElements(el, clone, new Map(), new WeakMap(), false);\n window.getComputedStyle.mockRestore();\n });\n\n it('handles ::before with url content', async () => {\n const el = document.createElement('div');\n const clone = document.createElement('div');\n vi.spyOn(window, 'getComputedStyle').mockImplementation((_, pseudo) => {\n if (pseudo === '::before') return {\n getPropertyValue: (prop) => prop === 'content' ? 'url(\"https://test.com/img.png\")' : prop === 'font-family' ? 'Arial' : prop === 'font-size' ? '32' : prop === 'font-weight' ? '400' : prop === 'color' ? '#000' : prop === 'background-image' ? 'none' : prop === 'background-color' ? 'transparent' : '',\n color: '#000', fontSize: '32px', fontWeight: '400', fontFamily: 'Arial',\n };\n return { getPropertyValue: () => '', color: '', fontSize: '', fontWeight: '', fontFamily: '' };\n });\n helpers.fetchImage.mockResolvedValue('data:image/png;base64,img');\n await inlinePseudoElements(el, clone, new Map(), new WeakMap(), false);\n window.getComputedStyle.mockRestore();\n });\n\n it('handles ::before with background-image (data url)', async () => {\n const el = document.createElement('div');\n const clone = document.createElement('div');\n vi.spyOn(window, 'getComputedStyle').mockImplementation((_, pseudo) => {\n if (pseudo === '::before') return {\n getPropertyValue: (prop) => prop === 'content' ? 'none' : prop === 'font-family' ? 'Arial' : prop === 'font-size' ? '32' : prop === 'font-weight' ? '400' : prop === 'color' ? '#000' : prop === 'background-image' ? 'url(\"data:image/png;base64,abc\")' : prop === 'background-color' ? 'transparent' : '',\n color: '#000', fontSize: '32px', fontWeight: '400', fontFamily: 'Arial',\n };\n return { getPropertyValue: () => '', color: '', fontSize: '', fontWeight: '', fontFamily: '' };\n });\n await inlinePseudoElements(el, clone, new Map(), new WeakMap(), false);\n window.getComputedStyle.mockRestore();\n });\n\n it('handles ::before with background-image (fetch)', async () => {\n const el = document.createElement('div');\n const clone = document.createElement('div');\n vi.spyOn(window, 'getComputedStyle').mockImplementation((_, pseudo) => {\n if (pseudo === '::before') return {\n getPropertyValue: (prop) => prop === 'content' ? 'none' : prop === 'font-family' ? 'Arial' : prop === 'font-size' ? '32' : prop === 'font-weight' ? '400' : prop === 'color' ? '#000' : prop === 'background-image' ? 'url(\"https://test.com/img.png\")' : prop === 'background-color' ? 'transparent' : '',\n color: '#000', fontSize: '32px', fontWeight: '400', fontFamily: 'Arial',\n };\n return { getPropertyValue: () => '', color: '', fontSize: '', fontWeight: '', fontFamily: '' };\n });\n helpers.fetchImage.mockResolvedValue('data:image/png;base64,img');\n await inlinePseudoElements(el, clone, new Map(), new WeakMap(), false);\n window.getComputedStyle.mockRestore();\n });\n\n it('handles ::before with background-image fetch error', async () => {\n const el = document.createElement('div');\n const clone = document.createElement('div');\n vi.spyOn(window, 'getComputedStyle').mockImplementation((_, pseudo) => {\n if (pseudo === '::before') return {\n getPropertyValue: (prop) => prop === 'content' ? 'none' : prop === 'font-family' ? 'Arial' : prop === 'font-size' ? '32' : prop === 'font-weight' ? '400' : prop === 'color' ? '#000' : prop === 'background-image' ? 'url(\"https://test.com/img.png\")' : prop === 'background-color' ? 'transparent' : '',\n color: '#000', fontSize: '32px', fontWeight: '400', fontFamily: 'Arial',\n };\n return { getPropertyValue: () => '', color: '', fontSize: '', fontWeight: '', fontFamily: '' };\n });\n helpers.fetchImage.mockRejectedValue(new Error('fail'));\n await inlinePseudoElements(el, clone, new Map(), new WeakMap(), false);\n window.getComputedStyle.mockRestore();\n });\n\n it('handles ::before with no visible box', async () => {\n const el = document.createElement('div');\n const clone = document.createElement('div');\n vi.spyOn(window, 'getComputedStyle').mockImplementation((_, pseudo) => {\n if (pseudo === '::before') return {\n getPropertyValue: () => 'none', color: '', fontSize: '', fontWeight: '', fontFamily: ''\n };\n return { getPropertyValue: () => '', color: '', fontSize: '', fontWeight: '', fontFamily: '' };\n });\n await inlinePseudoElements(el, clone, new Map(), new WeakMap(), false);\n window.getComputedStyle.mockRestore();\n });\n\n it('handles ::first-letter with no textNode', async () => {\n const el = document.createElement('div');\n const clone = document.createElement('div');\n vi.spyOn(window, 'getComputedStyle').mockImplementation(() => ({\n getPropertyValue: () => '', color: '', fontSize: '', fontWeight: '', fontFamily: ''\n }));\n await inlinePseudoElements(el, clone, new Map(), new WeakMap(), false);\n window.getComputedStyle.mockRestore();\n });\n\n it('handles error in pseudo processing', async () => {\n const el = document.createElement('div');\n const clone = document.createElement('div');\n vi.spyOn(window, 'getComputedStyle').mockImplementation(() => { throw new Error('fail'); });\n await inlinePseudoElements(el, clone, new Map(), new WeakMap(), false);\n window.getComputedStyle.mockRestore();\n });\n\n it('ignores if source no es Element', async () => {\n const notElement = {};\n const clone = document.createElement('div');\n await expect(inlinePseudoElements(notElement, clone, new Map(), new WeakMap(), false)).resolves.toBeUndefined();\n });\n\n it('ignores if clone no es Element', async () => {\n const el = document.createElement('div');\n const notElement = {};\n await expect(inlinePseudoElements(el, notElement, new Map(), new WeakMap(), false)).resolves.toBeUndefined();\n });\n\n it('inserta pseudoEl como ::after', async () => {\n const el = document.createElement('div');\n const clone = document.createElement('div');\n vi.spyOn(window, 'getComputedStyle').mockImplementation((_, pseudo) => {\n if (pseudo === '::after') return {\n getPropertyValue: (prop) => prop === 'content' ? '\"after\"' : prop === 'font-family' ? 'Arial' : prop === 'font-size' ? '32' : prop === 'font-weight' ? '400' : prop === 'color' ? '#000' : prop === 'background-image' ? 'none' : prop === 'background-color' ? '#f00' : '',\n color: '#000', fontSize: '32px', fontWeight: '400', fontFamily: 'Arial',\n };\n return { getPropertyValue: () => '', color: '', fontSize: '', fontWeight: '', fontFamily: '' };\n });\n await inlinePseudoElements(el, clone, new Map(), new WeakMap(), false);\n window.getComputedStyle.mockRestore();\n });\n\n it('inserta pseudoEl como ::before', async () => {\n const el = document.createElement('div');\n const clone = document.createElement('div');\n vi.spyOn(window, 'getComputedStyle').mockImplementation((_, pseudo) => {\n if (pseudo === '::before') return {\n getPropertyValue: (prop) => prop === 'content' ? '\"before\"' : prop === 'font-family' ? 'Arial' : prop === 'font-size' ? '32' : prop === 'font-weight' ? '400' : prop === 'color' ? '#000' : prop === 'background-image' ? 'none' : prop === 'background-color' ? '#f00' : '',\n color: '#000', fontSize: '32px', fontWeight: '400', fontFamily: 'Arial',\n };\n return { getPropertyValue: () => '', color: '', fontSize: '', fontWeight: '', fontFamily: '' };\n });\n await inlinePseudoElements(el, clone, new Map(), new WeakMap(), false);\n window.getComputedStyle.mockRestore();\n });\n\n it('no inserta pseudoEl si no hay visible box', async () => {\n const el = document.createElement('div');\n const clone = document.createElement('div');\n vi.spyOn(window, 'getComputedStyle').mockImplementation((_, pseudo) => {\n if (pseudo === '::before') return {\n getPropertyValue: (prop) => 'none', color: '', fontSize: '', fontWeight: '', fontFamily: ''\n };\n return { getPropertyValue: () => '', color: '', fontSize: '', fontWeight: '', fontFamily: '' };\n });\n await inlinePseudoElements(el, clone, new Map(), new WeakMap(), false);\n window.getComputedStyle.mockRestore();\n });\n\n it('maneja ::first-letter meaningful', async () => {\n const el = document.createElement('div');\n el.textContent = 'Test';\n const clone = document.createElement('div');\n clone.textContent = 'Test';\n vi.spyOn(window, 'getComputedStyle').mockImplementation((_, pseudo) => {\n if (pseudo === '::first-letter') return {\n getPropertyValue: (prop) => prop === 'color' ? '#f00' : '', color: '#f00', fontSize: '32px', fontWeight: '400', fontFamily: 'Arial',\n };\n return { getPropertyValue: () => '', color: '#000', fontSize: '32px', fontWeight: '400', fontFamily: 'Arial' };\n });\n await inlinePseudoElements(el, clone, new Map(), new WeakMap(), false);\n window.getComputedStyle.mockRestore();\n });\n\n it('inserta ambos pseudoEl ::before y ::after en una sola ejecución', async () => {\n const el = document.createElement('div');\n const clone = document.createElement('div');\n vi.spyOn(window, 'getComputedStyle').mockImplementation((_, pseudo) => {\n if (pseudo === '::before') return {\n getPropertyValue: (prop) => prop === 'content' ? '\"before\"' : prop === 'font-family' ? 'Arial' : prop === 'font-size' ? '32' : prop === 'font-weight' ? '400' : prop === 'color' ? '#000' : prop === 'background-image' ? 'none' : prop === 'background-color' ? '#f00' : '',\n color: '#000', fontSize: '32px', fontWeight: '400', fontFamily: 'Arial',\n };\n if (pseudo === '::after') return {\n getPropertyValue: (prop) => prop === 'content' ? '\"after\"' : prop === 'font-family' ? 'Arial' : prop === 'font-size' ? '32' : prop === 'font-weight' ? '400' : prop === 'color' ? '#000' : prop === 'background-image' ? 'none' : prop === 'background-color' ? '#0f0' : '',\n color: '#000', fontSize: '32px', fontWeight: '400', fontFamily: 'Arial',\n };\n return { getPropertyValue: () => '', color: '', fontSize: '', fontWeight: '', fontFamily: '' };\n });\n await inlinePseudoElements(el, clone, new Map(), new WeakMap(), false);\n window.getComputedStyle.mockRestore();\n });\n\n it('should inline ::first-letter when style is meaningful', async () => {\n const el = document.createElement('p');\n el.textContent = '¡Hola mundo!';\n el.style.setProperty('color', 'black');\n\n document.body.appendChild(el);\n const clone = el.cloneNode(true);\n const styleMap = new Map();\n const styleCache = new WeakMap();\n\n const style = document.createElement('style');\n style.textContent = `\n p::first-letter {\n color: red;\n font-size: 200%;\n }\n `;\n document.head.appendChild(style);\n\n await inlinePseudoElements(el, clone, styleMap, styleCache, false);\n const firstLetterEl = clone.querySelector('[data-snapdom-pseudo=\"::first-letter\"]');\n expect(firstLetterEl).toBeTruthy();\n expect(firstLetterEl.textContent.length).toBeGreaterThan(0);\n});\n\nit('should inline background-image entries for pseudo-element', async () => {\n const el = document.createElement('div');\n document.body.appendChild(el);\n\n const style = document.createElement('style');\n style.textContent = `\n div::after {\n content: \" \";\n background-image: url(\"data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg'%3E%3Crect width='10' height='10' fill='blue'/%3E%3C/svg%3E\");\n display: inline-block;\n width: 10px;\n height: 10px;\n }\n `;\n document.head.appendChild(style);\n\n const clone = el.cloneNode(true);\n const styleMap = new Map();\n const styleCache = new WeakMap();\n\n await inlinePseudoElements(el, clone, styleMap, styleCache, false);\n const pseudoAfter = clone.querySelector('[data-snapdom-pseudo=\"::after\"]');\n expect(pseudoAfter).toBeTruthy();\n expect(pseudoAfter.style.backgroundImage.startsWith(\"url(\\\"data:image/\")).toBeTruthy();\n});\n\n});\n\n\n\n\n\n"], ["/snapdom/__tests__/helpers.utils.test.js", "import { describe, it, expect, vi } from 'vitest';\nimport { getStyle, parseContent, extractURL, isIconFont, snapshotComputedStyle, isSafari, stripTranslate, safeEncodeURI, idle, fetchImage } from '../src/utils/helpers.js';\n\ndescribe('getStyle', () => {\n it('returns a CSSStyleDeclaration', () => {\n const el = document.createElement('div');\n document.body.appendChild(el);\n const style = getStyle(el);\n expect(style).toBeInstanceOf(CSSStyleDeclaration);\n document.body.removeChild(el);\n });\n});\n\n\n\ndescribe('parseContent', () => {\n it('parses CSS content correctly', () => {\n expect(parseContent('\"★\"')).toBe('★');\n expect(parseContent('\\\\2605')).toBe('★');\n });\n});\n\ndescribe('parseContent edge cases', () => {\n it('returns \\u0000 if parseInt fails (not hex)', () => {\n expect(parseContent('\\\\nothex')).toBe('\\u0000');\n });\n it('returns clean if String.fromCharCode throws', () => {\n const orig = String.fromCharCode;\n String.fromCharCode = () => { throw new Error('fail'); };\n expect(parseContent('\\\\2605')).toBe('\\\\2605');\n String.fromCharCode = orig;\n });\n});\n\ndescribe('extractURL', () => {\n it('extracts the URL from background-image', () => {\n expect(extractURL('url(\"https://test.com/img.png\")')).toBe('https://test.com/img.png');\n expect(extractURL('none')).toBeNull();\n });\n});\n\ndescribe('isIconFont', () => {\n it('detects icon fonts', () => {\n expect(isIconFont('Font Awesome')).toBe(true);\n expect(isIconFont('Arial')).toBe(false);\n });\n});\n\ndescribe('snapshotComputedStyle', () => {\n it('returns a style snapshot', () => {\n const el = document.createElement('div');\n document.body.appendChild(el);\n const style = getComputedStyle(el);\n const snap = snapshotComputedStyle(style);\n expect(typeof snap).toBe('object');\n document.body.removeChild(el);\n });\n});\n\ndescribe('isSafari', () => {\n it('returns a boolean', () => {\n expect(typeof isSafari()).toBe('boolean');\n });\n});\n\ndescribe('stripTranslate', () => {\n it('removes translate transforms', () => {\n expect(stripTranslate('translateX(10px) scale(2)')).toContain('scale(2)');\n });\n it('stripTranslate removes matrix and matrix3d', () => {\n expect(stripTranslate('matrix(1,0,0,1,10,20)')).not.toContain('10,20');\n expect(stripTranslate('matrix3d(1,0,0,0,0,1,0,0,0,0,1,0,10,20,30,1)')).not.toContain('10,20,30');\n });\n});\n\ndescribe('safeEncodeURI', () => {\n it('returns an encoded string', () => {\n expect(typeof safeEncodeURI('https://test.com/á')).toBe('string');\n });\n it('safeEncodeURI handles invalid URIs gracefully', () => {\n expect(typeof safeEncodeURI('%E0%A4%A')).toBe('string');\n });\n});\n\ndescribe('idle', () => {\n it('calls fn immediately if fast is true', () => {\n let called = false;\n idle(() => { called = true; }, { fast: true });\n expect(called).toBe(true);\n });\n it('uses requestIdleCallback if available', () => {\n const orig = window.requestIdleCallback;\n let called = false;\n window.requestIdleCallback = (fn) => { called = true; fn(); };\n idle(() => { called = true; });\n expect(called).toBe(true);\n window.requestIdleCallback = orig;\n });\n it('falls back to setTimeout if requestIdleCallback not available', async () => {\n const orig = window.requestIdleCallback;\n delete window.requestIdleCallback;\n let called = false;\n idle(() => { called = true; });\n await new Promise(r => setTimeout(r, 10));\n expect(called).toBe(true);\n window.requestIdleCallback = orig;\n });\n});\n\ndescribe('fetchImage', () => {\n it('rejects on image error', async () => {\n await expect(fetchImage('invalid-url', { timeout: 100 }))\n .rejects.toThrow('Fetch fallback failed and no proxy provided');\n\n });\n it('rejects on timeout', async () => {\n // Simula una imagen que nunca carga\n const origImage = window.Image;\n window.Image = class { set src(_){} onload(){} onerror(){} };\n await expect(fetchImage('timeout-url', { timeout: 10 })).rejects.toThrow('Image load timed out');\n window.Image = origImage;\n });\n\n});\n\ndescribe('fetchImage cache', () => {\n it('returns cached image if present', async () => {\n const { cache } = await import('../src/core/cache.js');\n cache.image.set('cached-url', 'data:image/png;base64,abc');\n const result = await fetchImage('cached-url', { useProxy: false });\n expect(result).toBe('data:image/png;base64,abc');\n cache.image.delete('cached-url');\n });\n});\n\ndescribe('fetchImage error propagation', () => {\n it('rejects with original error if decode fails', async () => {\n const origImage = window.Image;\n window.Image = class {\n constructor() { setTimeout(() => this.onload(), 1); }\n set src(_){}\n decode() { return Promise.reject(new Error('decode fail')); }\n get width() { return 1; }\n get height() { return 1; }\n };\n await expect(fetchImage('decode-fail-url', { timeout: 100 }))\n .rejects.toThrow('Fetch fallback failed and no proxy provided');\n window.Image = origImage;\n });\n});\n\ndescribe('stripTranslate edge cases', () => {\n it('returns empty string for empty or none', () => {\n expect(stripTranslate('')).toBe('');\n expect(stripTranslate('none')).toBe('');\n });\n it('returns original for malformed matrix', () => {\n expect(stripTranslate('matrix(1,2,3)')).toBe('matrix(1,2,3)');\n expect(stripTranslate('matrix3d(1,2,3)')).toBe('matrix3d(1,2,3)');\n });\n});\n"], ["/snapdom/__tests__/snapdom.api.test.js", "import { describe, it, expect, vi } from 'vitest';\nimport { snapdom } from '../src/api/snapdom.js';\n\ndescribe('snapdom API (direct)', () => {\n it('throws on null element', async () => {\n await expect(snapdom(null)).rejects.toThrow();\n });\n\n it('snapdom.capture returns export methods', async () => {\n const el = document.createElement('div');\n el.style.width = '100px';\n el.style.height = '50px';\n document.body.appendChild(el);\n const result = await snapdom.capture(el);\n expect(result).toHaveProperty('toRaw');\n expect(result).toHaveProperty('toImg');\n expect(result).toHaveProperty('download');\n document.body.removeChild(el);\n });\n\n it('snapdom.toRaw, toImg, toCanvas, toBlob, toPng, toJpg, toWebp, download', async () => {\n const el = document.createElement('div');\n el.style.width = '100px';\n el.style.height = '50px';\n document.body.appendChild(el);\n await snapdom.toRaw(el);\n await snapdom.toImg(el);\n await snapdom.toCanvas(el);\n await snapdom.toBlob(el);\n await snapdom.toPng(el);\n await snapdom.toJpg(el);\n await snapdom.toWebp(el);\n await snapdom.download(el, { format: 'png', filename: 'test' });\n document.body.removeChild(el);\n });\n\n it('cubre rama Safari en toImg', async () => {\n vi.resetModules();\n vi.mock('../utils/helpers.js', async () => {\n const actual = await vi.importActual('../utils/helpers.js');\n return { ...actual, isSafari: true };\n });\n const { snapdom } = await import('../src/api/snapdom.js');\n const el = document.createElement('div');\n el.style.width = '10px';\n el.style.height = '10px';\n document.body.appendChild(el);\n // Forzar un SVG dataURL simple\n const img = new Image();\n img.width = 10;\n img.height = 10;\n img.decode = () => Promise.resolve();\n globalThis.Image = function() { return img; };\n const res = await snapdom.capture(el);\n await res.toImg();\n document.body.removeChild(el);\n vi.resetModules();\n });\n\n it('cubre rama de download SVG', async () => {\n const el = document.createElement('div');\n el.style.width = '10px';\n el.style.height = '10px';\n document.body.appendChild(el);\n // Mock a.click y URL.createObjectURL\n const a = document.createElement('a');\n document.body.appendChild(a);\n const origCreate = URL.createObjectURL;\n URL.createObjectURL = () => 'blob:url';\n const origClick = a.click;\n a.click = () => {};\n HTMLAnchorElement.prototype.click = () => {};\n const { snapdom } = await import('../src/api/snapdom.js');\n await snapdom.download(el, { format: 'svg', filename: 'testsvg' });\n URL.createObjectURL = origCreate;\n a.click = origClick;\n document.body.removeChild(a);\n document.body.removeChild(el);\n });\n\n it('snapdom.toBlob supports type options ', async () => {\n const el = document.createElement('div');\n el.style.width = '50px';\n el.style.height = '30px';\n document.body.appendChild(el);\n\n const result = await snapdom.capture(el);\n\n const pngBlob = await result.toBlob({ type: 'png' });\n expect(pngBlob).toBeInstanceOf(Blob);\n expect(pngBlob.type).toBe('image/png');\n\n const jpgBlob = await result.toBlob({ type: 'jpeg', quality: 0.8 });\n expect(jpgBlob).toBeInstanceOf(Blob);\n expect(jpgBlob.type).toBe('image/jpeg');\n\n const webpBlob = await result.toBlob({ type: 'webp', quality: 0.9 });\n expect(webpBlob).toBeInstanceOf(Blob);\n expect(webpBlob.type).toBe('image/webp');\n\n // default fallback\n const svgBlob = await result.toBlob();\n expect(svgBlob).toBeInstanceOf(Blob);\n expect(svgBlob.type).toBe('image/svg+xml');\n\n document.body.removeChild(el);\n});\n\nit('toPng, toJpg, toWebp return HTMLImageElement with URLs', async () => {\n const el = document.createElement('div');\n el.style.width = '60px';\n el.style.height = '40px';\n document.body.appendChild(el);\n const snap = await snapdom.capture(el);\n\n const pngImg = await snap.toPng();\n expect(pngImg).toBeInstanceOf(HTMLImageElement);\n expect(typeof pngImg.src).toBe('string');\nexpect(pngImg.src.startsWith('data:image/png')).toBe(true);\n\n const jpgImg = await snap.toJpg();\n expect(jpgImg).toBeInstanceOf(HTMLImageElement);\n expect(typeof jpgImg.src).toBe('string');\nexpect(jpgImg.src.startsWith('data:image/jpeg')).toBe(true);\n\n const webpImg = await snap.toWebp();\n expect(webpImg).toBeInstanceOf(HTMLImageElement);\n expect(typeof webpImg.src).toBe('string');\nexpect(webpImg.src.startsWith('data:image/webp')).toBe(true);\n document.body.removeChild(el);\n});\n\nit('snapdom should support exclude option to filter out elements by CSS selectors', async () => {\n const el = document.createElement('div');\n el.innerHTML = `\n

Title

\n
Should be excluded
\n
Private data
\n

This should remain

\n `;\n document.body.appendChild(el);\n \n const result = await snapdom(el, { exclude: ['.exclude-me', '[data-private]'] });\n \n const svg = result.toRaw();\n const decoded = decodeURIComponent(svg.split(\",\")[1]);\n expect(decoded).not.toContain('Should be excluded');\n expect(decoded).not.toContain('Private data');\n expect(decoded).toContain('Title');\n expect(decoded).toContain('This should remain');\n});\n\nit('snapdom should support filter option to exclude elements with custom logic', async () => {\n const el = document.createElement('div');\n el.innerHTML = `\n
Level 1\n
Level 2\n
Level 3
\n
\n
\n `;\n document.body.appendChild(el);\n const result = await snapdom(el, { \n filter: (element) => !element.classList.contains('level-3')\n });\n \n const svg = result.toRaw();\n const decoded = decodeURIComponent(svg.split(\",\")[1]);\n expect(decoded).toContain('Level 1');\n expect(decoded).toContain('Level 2');\n expect(decoded).not.toContain('Level 3');\n});\n\nit('snapdom should support combining exclude and filter options', async () => {\n const el = document.createElement('div');\n el.innerHTML = `\n
Exclude by selector
\n
Exclude by filter
\n
Keep this content
\n `;\n document.body.appendChild(el);\n\n const result = await snapdom(el, { \n exclude: ['.exclude-by-selector'],\n filter: (element) => !element.classList.contains('exclude-by-filter')\n });\n \n \n const svg = result.toRaw();\n const decoded = decodeURIComponent(svg.split(\",\")[1]);\n expect(decoded).not.toContain('Exclude by selector');\n expect(decoded).not.toContain('Exclude by filter');\n expect(decoded).toContain('Keep this content');\n});\n\n});\n"], ["/snapdom/__tests__/snapdom.precache.test.js", "import { describe, test, expect, afterEach, afterAll, beforeEach } from 'vitest';\nimport { snapdom, preCache } from '../src/index';\nimport { cache } from '../src/core/cache';\n\nconst sizes = [\n { width: 200, height: 100, label: 'Small element (200x100)' },\n { width: 400, height: 300, label: 'Modal size (400x300)' },\n { width: 1200, height: 800, label: 'Page view (1200x800)' },\n];\nlet results = [];\nfunction createContainer(size) {\n const container = document.createElement('div');\n container.style.width = `${size.width}px`;\n container.style.height = `${size.height}px`;\n container.style.padding = '20px';\n container.style.overflow = 'auto';\n container.style.background = 'white';\n container.style.border = '2px solid black';\n container.style.fontFamily = 'Arial, sans-serif';\n container.style.color = '#333';\n container.style.position = 'relative';\n\n const grid = document.createElement('div');\n grid.style.display = 'grid';\n grid.style.gridTemplateColumns = 'repeat(auto-fill, minmax(120px, 1fr))';\n grid.style.gap = '10px';\n\n const cardCount = Math.floor((size.width * size.height) / 20000);\n for (let i = 0; i < cardCount; i++) {\n const card = document.createElement('div');\n card.style.padding = '10px';\n card.style.borderRadius = '8px';\n card.style.background = i % 2 === 0 ? '#f0f0f0' : '#e0eaff';\n card.style.boxShadow = '0 2px 5px rgba(0,0,0,0.1)';\n card.style.display = 'flex';\n card.style.flexDirection = 'column';\n card.style.alignItems = 'center';\n\n const title = document.createElement('h3');\n title.textContent = `Card ${i + 1}`;\n title.style.margin = '0 0 10px 0';\n title.style.fontSize = '14px';\n\n const icon = document.createElement('div');\n icon.style.width = '30px';\n icon.style.height = '30px';\n icon.style.borderRadius = '50%';\n icon.style.background = i % 2 === 0 ? 'red' : 'blue';\n icon.style.marginBottom = '10px';\n\n const text = document.createElement('p');\n text.textContent = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit.';\n text.style.fontSize = '12px';\n text.style.textAlign = 'center';\n\n card.appendChild(icon);\n card.appendChild(title);\n card.appendChild(text);\n grid.appendChild(card);\n }\n\n container.appendChild(grid);\n return container;\n}\n\nfunction waitForNextFrame() {\n return new Promise((resolve) => {\n requestAnimationFrame(() => setTimeout(resolve, 0));\n });\n}\nbeforeEach(() => {\n cache.image.clear();\n cache.background.clear();\n cache.resource.clear();\n});\nafterAll(() => {\n for (const r of results) {\n console.log(r.log);\n }\n results = [];\n \n document.body.innerHTML = '';\n});\nfor (const size of sizes) {\n describe(`snapDOM performance test (may not be accurate) - ${size.label}`, () => {\n let container;\n\n afterEach( () => {\n container?.remove();\n container = null;\n document.body.innerHTML = '';\n \n });\n\n test('without preCache', async () => {\n container = createContainer(size);\n document.body.appendChild(container);\n await waitForNextFrame();\n\n const start = performance.now();\n await snapdom.toRaw(container, { compress: true });\n const end = performance.now();\n\n let log = `[${size.label}] WITHOUT preCache: capture ${(end - start).toFixed(2)}ms`;\n results.push({ log });\n expect(true).toBe(true);\n \n });\n \n test('with preCache', async () => {\n container = createContainer(size);\n document.body.appendChild(container);\n await waitForNextFrame();\n\n const startPre = performance.now();\n await preCache();\n const endPre = performance.now();\n \n const startCap = performance.now();\n await snapdom.toRaw(container, { compress: true });\n const endCap = performance.now();\n \n const precacheTime = (endPre - startPre).toFixed(2);\n const captureTime = (endCap - startCap).toFixed(2);\n \n let log = `[${size.label}] WITH preCache: capture ${captureTime}ms (preCache ${precacheTime}ms) `;\n\n results.push({ log });\n \n expect(true).toBe(true);\n });\n\n });\n}\n"], ["/snapdom/src/modules/iconFonts.js", "var defaultIconFonts = [\n// /uicons/i,\n /font\\s*awesome/i,\n /material\\s*icons/i,\n /ionicons/i,\n /glyphicons/i,\n /feather/i,\n /bootstrap\\s*icons/i,\n /remix\\s*icons/i,\n /heroicons/i,\n /layui/i,\n /lucide/i\n];\n\nvar userIconFonts = [];\n\nexport function extendIconFonts(fonts) {\n const list = Array.isArray(fonts) ? fonts : [fonts];\n for (const f of list) {\n if (f instanceof RegExp) {\n userIconFonts.push(f);\n } else if (typeof f === \"string\") {\n userIconFonts.push(new RegExp(f, \"i\"));\n } else {\n console.warn(\"[snapdom] Ignored invalid iconFont value:\", f);\n }\n }\n}\n\nexport function isIconFont(input) {\n const text = typeof input === \"string\" ? input : \"\";\n\n const candidates = [...defaultIconFonts, ...userIconFonts];\n\n for (const rx of candidates) {\n if (rx instanceof RegExp && rx.test(text)) return true;\n }\n\n // Heurística básica\n if (\n /icon/i.test(text) ||\n /glyph/i.test(text) ||\n /symbols/i.test(text) ||\n /feather/i.test(text) ||\n /fontawesome/i.test(text)\n ) return true;\n\n return false;\n}"], ["/snapdom/__tests__/fonts.module.test.js", "import { describe, it, expect, beforeEach, vi } from 'vitest';\nimport { iconToImage, embedCustomFonts } from '../src/modules/fonts.js';\nimport { cache } from '../src/core/cache.js';\n\n// Utilidad para limpiar estilos y links antes de cada test\nfunction cleanFontEnvironment() {\n document.querySelectorAll('style,link[rel=\"stylesheet\"]').forEach(s => s.remove());\n}\n\nfunction addStyleTag(css) {\n const style = document.createElement('style');\n style.setAttribute('data-test-style', 'true');\n style.textContent = css;\n document.head.appendChild(style);\n return style;\n}\n\ndescribe('iconToImage', () => {\n it('genera un dataURL para un carácter unicode', async () => {\n const url = await iconToImage('★', 'Arial', 'bold', 32, '#000');\n expect(url.startsWith('data:image/')).toBe(true);\n });\n\n it('maneja diferentes pesos y colores de fuente', async () => {\n const url = await iconToImage('★', 'Arial', 700, 40, '#ff0000');\n expect(url.startsWith('data:image/')).toBe(true);\n });\n\n it('usa valores por defecto si no hay métricas', async () => {\n const orig = HTMLCanvasElement.prototype.getContext;\n HTMLCanvasElement.prototype.getContext = function() {\n return {\n font: '',\n scale: vi.fn(),\n textAlign: '',\n textBaseline: '',\n fillStyle: '',\n fillText: vi.fn(),\n measureText: () => ({ width: 10 })\n };\n };\n const url = await iconToImage('★', 'Arial', 'bold', 32, '#000');\n expect(url.startsWith('data:image/')).toBe(true);\n HTMLCanvasElement.prototype.getContext = orig;\n });\n});\n\ndescribe('embedCustomFonts', () => {\n beforeEach(() => {\n cache.reset();\n cache.font.clear();\n cache.resource.clear();\n cleanFontEnvironment();\n vi.restoreAllMocks();\n });\n\n it('conserva @font-face con solo local() en src', async () => {\n const style = addStyleTag(`\n @font-face {\n font-family: OnlyLocal;\n src: local(\"Arial\");\n font-style: normal;\n font-weight: normal;\n }\n `);\n\n const css = await embedCustomFonts();\n expect(css).toMatch(/font-family:\\s*OnlyLocal/);\n expect(css).toMatch(/src:\\s*local\\([\"']Arial[\"']\\)/);\n document.head.removeChild(style);\n });\n\n it('conserva @font-face con local() y sin url()', async () => {\n const style = addStyleTag(`\n @font-face {\n font-family: LocalFont;\n src: local('MyFont'), local('FallbackFont');\n font-style: italic;\n font-weight: bold;\n }\n `);\n\n const css = await embedCustomFonts();\n expect(css).toMatch(/font-family:\\s*LocalFont/);\n expect(css).toMatch(/src:\\s*local\\(['\"]MyFont['\"]\\),\\s*local\\(['\"]FallbackFont['\"]\\)/);\n expect(css).toMatch(/font-style:\\s*italic/);\n document.head.removeChild(style);\n });\n});\n"], ["/snapdom/__tests__/prepare.core.test.js", "import { describe, it, expect, vi } from 'vitest';\nimport { prepareClone } from '../src/core/prepare.js';\n\ndescribe('prepareClone', () => {\n it('prepares a clone of a div', async () => {\n const el = document.createElement('div');\n el.textContent = 'test';\n const { clone, classCSS } = await prepareClone(el);\n expect(clone).not.toBeNull();\n expect(typeof classCSS).toBe('string');\n });\n});\n\ndescribe('prepareClone edge cases', () => {\n it('throws for null node', async () => {\n await expect(prepareClone(null)).rejects.toThrow();\n });\n it('returns a comment clone for unsupported node', async () => {\n const fake = document.createComment('not supported');\n const result = await prepareClone(fake);\n expect(result.clone.nodeType).toBe(Node.COMMENT_NODE);\n });\n it('handles error in internal logic', async () => {\n const el = document.createElement('div');\n vi.spyOn(el, 'cloneNode').mockImplementation(() => { throw new Error('fail'); });\n await expect(prepareClone(el)).rejects.toThrow('fail');\n });\n it('clones attributes and children', async () => {\n const el = document.createElement('div');\n el.setAttribute('data-test', '1');\n const result = await prepareClone(el);\n expect(result.clone.getAttribute('data-test')).toBe('1');\n });\n});\n"], ["/snapdom/__tests__/capture.core.test.js", "import { describe, it, expect, vi } from 'vitest';\nimport { captureDOM } from '../src/core/capture.js';\n\ndescribe('captureDOM edge cases', () => {\n it('throws for unsupported element (unknown nodeType)', async () => {\n // Simulate a node with an invalid nodeType\n const fakeNode = { nodeType: 999 };\n await expect(captureDOM(fakeNode)).rejects.toThrow();\n });\n\n it('throws if element is null', async () => {\n await expect(captureDOM(null)).rejects.toThrow();\n });\n\n it('throws error if getBoundingClientRect fails', async () => {\n const el = document.createElement('div');\n vi.spyOn(el, 'getBoundingClientRect').mockImplementation(() => { throw new Error('fail'); });\n await expect(captureDOM(el)).rejects.toThrow('fail');\n });\n});\n\ndescribe('captureDOM functional', () => {\n it('captures a simple div and returns an SVG dataURL', async () => {\n const el = document.createElement('div');\n el.textContent = 'test';\n const url = await captureDOM(el);\n expect(url.startsWith('data:image/svg+xml')).toBe(true);\n });\n\n it('supports scale and width/height options', async () => {\n const el = document.createElement('div');\n el.style.width = '100px';\n el.style.height = '50px';\n await captureDOM(el, { scale: 2 });\n await captureDOM(el, { width: 200 });\n await captureDOM(el, { height: 100 });\n });\n\n it('supports fast=false', async () => {\n const el = document.createElement('div');\n await captureDOM(el, { fast: false });\n });\n\n it('supports embedFonts', async () => {\n const el = document.createElement('div');\n await captureDOM(el, { embedFonts: true });\n });\n});\n"], ["/snapdom/__tests__/images.module.test.js", "import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';\nimport { inlineImages } from '../src/modules/images.js';\n\ndescribe('inlineImages', () => {\n let container;\n beforeEach(() => {\n container = document.createElement('div');\n document.body.appendChild(container);\n });\n afterEach(() => {\n document.body.removeChild(container);\n });\n\n it('converts to dataURL if the image loads', async () => {\n const img = document.createElement('img');\n img.src = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/w8AAn8B9p6Q2wAAAABJRU5ErkJggg==';\n container.appendChild(img);\n await inlineImages(container);\n expect(img.src.startsWith('data:image/')).toBe(true);\n });\n\n it('replaces with a fallback if the image fails', async () => {\n const img = document.createElement('img');\n img.src = 'invalid-url.png';\n container.appendChild(img);\n await inlineImages(container);\n expect(container.querySelector('div')).not.toBeNull();\n expect(container.querySelector('img')).toBeNull();\n });\n});\n"], ["/snapdom/__tests__/snapdom.vs.modernscreenshot.outputfilesize.test.js", "import { describe, it, beforeEach, afterEach, afterAll } from 'vitest';\nimport { domToDataUrl} from 'https://unpkg.com/modern-screenshot';\nimport { snapdom } from '../src/index';\n//ok\n\ndescribe('Output file size snapdom vs modern-screeenshot (cdn with averaging)', () => {\n let container;\n\n let report;\n\n beforeEach(async () => {\n container = document.createElement('div');\n container.style.width = '400px';\n container.style.height = '300px';\n container.style.background = 'linear-gradient(to right, red, blue)';\n container.innerHTML = '

Hello Benchmark

Testing multiple runs...

';\n document.body.appendChild(container);\n });\n\n afterEach(() => {\n document.body.removeChild(container);\n });\n\n afterAll(() => {\n console.log(report)\n })\n\n it('snapdom output file size should be smaller than modern-screenshot', async () => {\n \n // SnapDOM capture\n const snapdomDataURL = await snapdom.toRaw(container, {compress: true});\n const snapdomSizeKB = (snapdomDataURL.length * 3 / 4) / 1024; // Base64 to bytes approx\n \n // domToDataUrl capture\n const domToDataUrlDataURL = await domToDataUrl(container);\n const domToDataUrlSizeKB = (domToDataUrlDataURL.length * 3 / 4) / 1024; // Base64 to bytes approx\n \n const differencePercent = ((domToDataUrlSizeKB - snapdomSizeKB) / domToDataUrlSizeKB) * 100;\n\n report =`snapdom captured file size is ${differencePercent.toFixed(2)}% smaller compared to modern-screenshot (${snapdomSizeKB.toFixed(2)} KB vs. ${domToDataUrlSizeKB.toFixed(2)} KB)`\n\n})\n\n})\n"], ["/snapdom/src/core/cache.js", "/**\n * Caches for images, backgrounds, resources, and computed styles used during DOM capture.\n * @module cache\n */\n\nexport const cache = {\n image: new Map(),\n background: new Map(),\n resource: new Map(),\n defaultStyle: new Map(),\n baseStyle: new Map(),\n computedStyle: new WeakMap(),\n font: new Set(),\n snapshot: new WeakMap(),\n snapshotKey: new Map(),\n preStyleMap: new Map(),\n preStyle: new WeakMap(),\n preNodeMap: new Map(),\n reset: resetCache\n};\n\nfunction resetCache() {\n cache.computedStyle = new WeakMap();\n cache.snapshot = new WeakMap();\n cache.snapshotKey.clear();\n cache.preStyleMap.clear();\n cache.preStyle = new WeakMap();\n cache.preNodeMap.clear();\n}\n"], ["/snapdom/__tests__/pseudo.bg-inline-success.test.js", "vi.mock('../src/utils/helpers.js', async () => {\n const actual = await vi.importActual('../src/utils/helpers.js');\n return {\n ...actual,\n inlineSingleBackgroundEntry: vi.fn().mockResolvedValue('url(\"data:image/png;base64,abc\")'),\n };\n});\n\nimport { describe, it, vi } from 'vitest';\nimport { inlinePseudoElements } from '../src/modules/pseudo.js';\n\ndescribe('inlinePseudoElements background-image inlining (success)', () => {\n it('cubre el inlining exitoso de background-image en pseudo', async () => {\n const el = document.createElement('div');\n const clone = document.createElement('div');\n vi.spyOn(window, 'getComputedStyle').mockImplementation((_, pseudo) => {\n if (pseudo === '::before') return {\n getPropertyValue: (prop) => prop === 'content' ? 'none' : prop === 'font-family' ? 'Arial' : prop === 'font-size' ? '32' : prop === 'font-weight' ? '400' : prop === 'color' ? '#000' : prop === 'background-image' ? 'url(\"data:image/png;base64,abc\")' : prop === 'background-color' ? 'transparent' : '',\n color: '#000', fontSize: '32px', fontWeight: '400', fontFamily: 'Arial',\n };\n return { getPropertyValue: () => '', color: '', fontSize: '', fontWeight: '', fontFamily: '' };\n });\n await inlinePseudoElements(el, clone, new Map(), new WeakMap(), false);\n window.getComputedStyle.mockRestore();\n });\n});\n"], ["/snapdom/__tests__/pseudo.bg-inline-error.test.js", "vi.mock('../src/utils/helpers.js', async () => {\n const actual = await vi.importActual('../src/utils/helpers.js');\n return {\n ...actual,\n inlineSingleBackgroundEntry: vi.fn().mockRejectedValue(new Error('fail')),\n };\n});\n\nimport { describe, it, vi } from 'vitest';\nimport { inlinePseudoElements } from '../src/modules/pseudo.js';\n\ndescribe('inlinePseudoElements background-image inlining (error)', () => {\n it('cubre el catch de error en inlining de background-image en pseudo', async () => {\n const el = document.createElement('div');\n const clone = document.createElement('div');\n vi.spyOn(window, 'getComputedStyle').mockImplementation((_, pseudo) => {\n if (pseudo === '::before') return {\n getPropertyValue: (prop) => prop === 'content' ? 'none' : prop === 'font-family' ? 'Arial' : prop === 'font-size' ? '32' : prop === 'font-weight' ? '400' : prop === 'color' ? '#000' : prop === 'background-image' ? 'url(\"data:image/png;base64,abc\")' : prop === 'background-color' ? 'transparent' : '',\n color: '#000', fontSize: '32px', fontWeight: '400', fontFamily: 'Arial',\n };\n return { getPropertyValue: () => '', color: '', fontSize: '', fontWeight: '', fontFamily: '' };\n });\n await inlinePseudoElements(el, clone, new Map(), new WeakMap(), false);\n window.getComputedStyle.mockRestore();\n });\n});\n"], ["/snapdom/__tests__/clone.core.test.js", "import { describe, it, expect, vi } from 'vitest';\nimport { deepClone } from '../src/core/clone.js';\n\ndescribe('deepClone', () => {\n it('clones a simple div', () => {\n const el = document.createElement('div');\n el.textContent = 'hello';\n const styleMap = new Map();\n const styleCache = new WeakMap();\n const nodeMap = new Map();\n const clone = deepClone(el, styleMap, styleCache, nodeMap, false);\n expect(clone).not.toBe(el);\n expect(clone.textContent).toBe('hello');\n });\n\n it('clones canvas as an image', () => {\n const canvas = document.createElement('canvas');\n canvas.width = 10;\n canvas.height = 10;\n const ctx = canvas.getContext('2d');\n ctx.fillStyle = 'red';\n ctx.fillRect(0,0,10,10);\n const styleMap = new Map();\n const styleCache = new WeakMap();\n const nodeMap = new Map();\n const clone = deepClone(canvas, styleMap, styleCache, nodeMap, false);\n expect(clone.tagName).toBe('IMG');\n expect(clone.src.startsWith('data:image/')).toBe(true);\n });\n\n it('deepClone handles data-capture=\"exclude\"', () => {\n const el = document.createElement('div');\n el.setAttribute('data-capture', 'exclude');\n const clone = deepClone(el, true, {});\n expect(clone).not.toBeNull();\n });\n\n it('deepClone handles data-capture=\"placeholder\"', () => {\n const el = document.createElement('div');\n el.setAttribute('data-capture', 'placeholder');\n el.setAttribute('data-placeholder-text', 'Placeholder!');\n const clone = deepClone(el, true, {});\n expect(clone.textContent).toContain('Placeholder!');\n });\n\n it('deepClone handles iframe', () => {\n const iframe = document.createElement('iframe');\n iframe.width = 100;\n iframe.height = 50;\n const clone = deepClone(iframe, true, {});\n expect(clone.tagName).toBe('DIV');\n });\n\n it('deepClone handles input, textarea, select', () => {\n const input = document.createElement('input');\n input.value = 'foo';\n input.checked = true;\n const textarea = document.createElement('textarea');\n textarea.value = 'bar';\n const select = document.createElement('select');\n const opt = document.createElement('option');\n opt.value = 'baz';\n select.appendChild(opt);\n select.value = 'baz';\n [input, textarea, select].forEach(el => {\n const clone = deepClone(el, true, {});\n expect(clone.value).toBe(el.value);\n });\n });\n\n it('deepClone handles shadow DOM', () => {\n const el = document.createElement('div');\n const shadow = el.attachShadow({mode:'open'});\n const span = document.createElement('span');\n span.textContent = 'shadow';\n shadow.appendChild(span);\n const clone = deepClone(el, true, {});\n expect(clone).not.toBeNull();\n });\n});\n\ndescribe('deepClone edge cases', () => {\n it('clones unsupported node (Comment) as a new Comment', () => {\n const fake = document.createComment('not supported');\n const result = deepClone(fake, true, {});\n expect(result.nodeType).toBe(Node.COMMENT_NODE);\n expect(result.textContent).toBe('not supported');\n expect(result).not.toBe(fake); // Es un clon, no el mismo objeto\n });\n it('clones attributes and children', () => {\n const el = document.createElement('div');\n el.setAttribute('data-test', '1');\n const result = deepClone(el, true, {});\n expect(result.getAttribute('data-test')).toBe('1');\n });\n});\n"], ["/snapdom/__tests__/snapdom.test.js", "import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';\nimport { snapdom } from '../src/index';\n\ndescribe('snapdom API', () => {\n let testElement;\n\n beforeEach(() => {\n testElement = document.createElement('div');\n testElement.style.width = '100px';\n testElement.style.height = '50px';\n document.body.appendChild(testElement );\n });\n\n afterEach(() => {\n document.body.removeChild(testElement );\n });\n\n describe('snapdom.toRaw', () => {\n it('should return a SVG data URL', async () => {\n const result = await snapdom.toRaw(testElement );\n expect(result).toMatch(/^data:image\\/svg\\+xml/);\n });\n });\n\n describe('snapdom', () => {\n it('toImg should return an HTMLImageElement', async () => {\n \n const img = await snapdom.toImg(testElement );\n expect(img).toBeInstanceOf(HTMLImageElement);\n expect(img.src).toMatch(/^data:image\\/svg\\+xml/);\n \n });\n\n it('toCanvas should return a HTMLCanvasElement', async () => {\n // const decodeMock = vi.spyOn(window.Image.prototype, 'decode').mockResolvedValue();\n const canvas = await snapdom.toCanvas(testElement );\n expect(canvas).toBeInstanceOf(HTMLCanvasElement);\n // decodeMock.mockRestore();\n });\n\n it('toPng should return an HTMLImageElement with PNG data URL', async () => {\n // const decodeMock = vi.spyOn(window.Image.prototype, 'decode').mockResolvedValue();\n const img = await snapdom.toPng(testElement );\n expect(img).toBeInstanceOf(HTMLImageElement);\n expect(img.src).toMatch(/^data:image\\/png/);\n // decodeMock.mockRestore();\n });\n\n it('toJpg should return an HTMLImageElement with JPEG data URL', async () => {\n // const decodeMock = vi.spyOn(window.Image.prototype, 'decode').mockResolvedValue();\n const img = await snapdom.toJpg(testElement );\n expect(img).toBeInstanceOf(HTMLImageElement);\n expect(img.src).toMatch(/^data:image\\/jpeg/);\n // decodeMock.mockRestore();\n });\n\n it('toWebp should return an HTMLImageElement with WebP data URL', async () => {\n // const decodeMock = vi.spyOn(window.Image.prototype, 'decode').mockResolvedValue();\n const img = await snapdom.toWebp(testElement );\n expect(img).toBeInstanceOf(HTMLImageElement);\n expect(img.src).toMatch(/^data:image\\/webp/);\n // decodeMock.mockRestore();\n });\n\n it('toBlob should return a Blob of type image/svg+xml', async () => {\n const blob = await snapdom.toBlob(testElement );\n expect(blob).toBeInstanceOf(Blob);\n expect(blob.type).toBe('image/svg+xml');\n });\n });\n});\n"], ["/snapdom/__tests__/background.module.test.js", "import { describe, it, expect, beforeEach, afterEach } from 'vitest';\nimport { inlineBackgroundImages } from '../src/modules/background.js';\n\ndescribe('inlineBackgroundImages', () => {\n let source, clone;\n beforeEach(() => {\n source = document.createElement('div');\n clone = document.createElement('div');\n document.body.appendChild(source);\n document.body.appendChild(clone);\n });\n afterEach(() => {\n document.body.removeChild(source);\n document.body.removeChild(clone);\n });\n\n it('does not fail if there is no background-image', async () => {\n source.style.background = 'none';\n await expect(inlineBackgroundImages(source, clone, new WeakMap())).resolves.toBeUndefined();\n });\n\n it('processes a valid background-image', async () => {\n source.style.backgroundImage = 'url(\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/w8AAn8B9p6Q2wAAAABJRU5ErkJggg==\")';\n await expect(inlineBackgroundImages(source, clone, new WeakMap())).resolves.toBeUndefined();\n });\n});\n"], ["/snapdom/src/index.browser.js", "/**\n * Entry point for snapDOM library exports.\n *\n * @file index.browser.js\n */\n\nimport { snapdom } from './api/snapdom.js';\nimport { preCache } from './api/preCache.js';\n\nif (typeof window !== 'undefined') {\n window.snapdom = snapdom;\n window.preCache = preCache;\n}"], ["/snapdom/__tests__/cssTools.utils.test.js", "import { describe, it, expect } from 'vitest';\nimport { getStyleKey, collectUsedTagNames, getDefaultStyleForTag } from '../src/utils/cssTools.js';\n\ndescribe('getStyleKey', () => {\n it('generates a non-empty style key', () => {\n const snapshot = { color: 'red', 'font-size': '12px' };\n const key = getStyleKey(snapshot, 'div');\n expect(typeof key).toBe('string');\n expect(key.length).toBeGreaterThan(0);\n });\n\n it('getStyleKey works with compress true', () => {\n const snapshot = { color: 'red', 'font-size': '12px' };\n const key = getStyleKey(snapshot, 'div', true);\n expect(typeof key).toBe('string');\n });\n});\n\ndescribe('collectUsedTagNames', () => {\n it('returns unique tag names', () => {\n const root = document.createElement('div');\n root.innerHTML = '

';\n const tags = collectUsedTagNames(root);\n expect(tags).toContain('div');\n expect(tags).toContain('span');\n expect(tags).toContain('p');\n });\n});\n\ndescribe('getDefaultStyleForTag', () => {\n it('returns a default style object', () => {\n const defaults = getDefaultStyleForTag('div');\n expect(typeof defaults).toBe('object');\n });\n\n it('getDefaultStyleForTag skips special tags', () => {\n expect(getDefaultStyleForTag('script')).toEqual({});\n });\n});\n"], ["/snapdom/__tests__/styles.module.test.js", "import { describe, it, expect } from 'vitest';\nimport { inlineAllStyles } from '../src/modules/styles.js';\nimport { cache } from '../src/core/cache.js';\n\ndescribe('inlineAllStyles', () => {\n it('adds a style key to the styleMap', () => {\n const el = document.createElement('div');\n const clone = document.createElement('div');\n inlineAllStyles(el, clone, false);\n expect(cache.preStyleMap.has(clone)).toBe(true);\n });\n});"], ["/snapdom/__tests__/snapdom.attributes.test.js", "import { describe, it, expect, beforeEach, afterEach } from 'vitest';\nimport { snapdom } from '../src/index';\n\ndescribe('snapdom capture attributes', () => {\n let container;\n\n beforeEach(() => {\n container = document.createElement('div');\n container.style.width = '300px';\n container.style.height = '150px';\n document.body.appendChild(container);\n });\n\n afterEach(() => {\n document.body.removeChild(container);\n });\n\n it('should exclude elements with data-capture=\"exclude\"', async () => {\n const excluded = document.createElement('div');\n excluded.setAttribute('data-capture', 'exclude');\n excluded.textContent = 'Should be excluded';\n container.appendChild(excluded);\n\n const svgDataUrl = await snapdom.toRaw(container);\n const svgText = decodeURIComponent(svgDataUrl.split(',')[1]);\n \n expect(svgText).not.toContain('Should be excluded');\n });\n\n it('should replace elements with data-capture=\"placeholder\" and show placeholder text', async () => {\n const placeholder = document.createElement('div');\n placeholder.setAttribute('data-capture', 'placeholder');\n placeholder.setAttribute('data-placeholder-text', 'Placeholder here');\n placeholder.textContent = 'Original text';\n container.appendChild(placeholder);\n\n const svgDataUrl = await snapdom.toRaw(container);\n const svgText = decodeURIComponent(svgDataUrl.split(',')[1]);\n \n expect(svgText).toContain('Placeholder here');\n expect(svgText).not.toContain('Original text');\n });\n});\n"], ["/snapdom/src/index.js", "/**\n * Entry point for snapDOM library exports.\n *\n * @file index.js\n */\n\nexport { snapdom } from './api/snapdom.js';\nexport { preCache } from './api/preCache.js';\n\n"], ["/snapdom/__tests__/preCache.api.test.js", "import { describe, it, expect, beforeEach } from 'vitest';\nimport { preCache } from '../src/api/preCache.js';\nimport { cache } from '../src/core/cache.js';\n\ndescribe('preCache', () => {\n beforeEach(() => {\n cache.reset()\n });\n\n it('pre-caches images and backgrounds', async () => {\n const el = document.createElement('div');\n const img = document.createElement('img');\n img.src = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/w8AAn8B9p6Q2wAAAABJRU5ErkJggg==';\n el.appendChild(img);\n document.body.appendChild(el);\n await preCache(el);\n expect(cache.image.has(img.src)).toBe(true);\n document.body.removeChild(el);\n });\n\n it('should handle preCache with embedFonts false', async () => {\n const el = document.createElement('div');\n await expect(preCache(el, { embedFonts: false })).resolves.toBeUndefined();\n });\n\n it('should handle preCache with images that fail to load', async () => {\n const el = document.createElement('div');\n const img = document.createElement('img');\n img.src = 'invalid-url.png';\n el.appendChild(img);\n await expect(preCache(el)).resolves.toBeUndefined();\n });\n\n it('should handle preCache with backgrounds that fail to load', async () => {\n const el = document.createElement('div');\n el.style.backgroundImage = 'url(invalid-url.png)';\n document.body.appendChild(el);\n await expect(preCache(el)).resolves.toBeUndefined();\n document.body.removeChild(el);\n });\n\n it('limpia los caches y retorna si reset=true', async () => {\n // Prellenar los caches\n cache.snapshotKey.set('foo', 'bar');\n cache.preStyleMap.set('foo', 'bar');\n cache.preNodeMap.set('foo', 'bar');\n await preCache(document, { reset: true });\n expect(cache.snapshotKey.size).toBe(0);\n expect(cache.preStyleMap.size).toBe(0);\n expect(cache.preNodeMap.size).toBe(0);\n });\n\n it('procesa múltiples backgrounds en un solo elemento', async () => {\n const el = document.createElement('div');\n el.style.backgroundImage = 'url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/w8AAn8B9p6Q2wAAAABJRU5ErkJggg==), url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/w8AAn8B9p6Q2wAAAABJRU5ErkJggg==)';\n document.body.appendChild(el);\n await preCache(el);\n // No assertion estricta porque depende de helpers, pero no debe lanzar error\n document.body.removeChild(el);\n });\n\n});\n"], ["/snapdom/__tests__/snapdom.backgroundColor.test.js", "import { describe, it, expect, beforeEach, afterEach } from 'vitest';\nimport { snapdom } from '../src/index';\n\ndescribe('snapdom.toJpg backgroundColor option', () => {\n let container;\n\n beforeEach(() => {\n container = document.createElement('div');\n container.style.width = '100px';\n container.style.height = '100px';\n container.style.background = 'transparent';\n document.body.appendChild(container);\n });\n\n it('applies white background by default', async () => {\n const img = await snapdom.toJpg(container );\n const canvas = document.createElement('canvas');\n canvas.width = img.width;\n canvas.height = img.height;\n const ctx = canvas.getContext('2d');\n ctx.drawImage(img, 0, 0);\n const pixel = ctx.getImageData(0, 0, 1, 1).data;\n // JPEG compresses, but for a solid color it should be near white\n expect(pixel[0]).toBeGreaterThan(240);\n expect(pixel[1]).toBeGreaterThan(240);\n expect(pixel[2]).toBeGreaterThan(240);\n });\n\n it('applies custom background color', async () => {\n const img = await snapdom.toJpg(container, { backgroundColor: '#00ff00' });\n const canvas = document.createElement('canvas');\n canvas.width = img.width;\n canvas.height = img.height;\n const ctx = canvas.getContext('2d');\n ctx.drawImage(img, 0, 0);\n const pixel = ctx.getImageData(0, 0, 1, 1).data;\n // Green check (JPEG lossy, so check near values)\n expect(pixel[0]).toBeLessThan(30); // red\n expect(pixel[1]).toBeGreaterThan(200); // green\n expect(pixel[2]).toBeLessThan(30); // blue\n });\n});\n"], ["/snapdom/__tests__/index.browser.test.js", "import { it, expect } from 'vitest';\nimport * as snapdom from '../src/index.browser.js';\n\nit('should import the browser bundle without errors', () => {\n expect(snapdom).toBeDefined();\n});\n"], ["/snapdom/vitest.config.js", "import { defineConfig } from 'vitest/config'\n\nexport default defineConfig({\n test: {\n browser: {\n enabled: true,\n provider: 'playwright',\n // https://vitest.dev/guide/browser/playwright\n instances: [\n { browser: 'chromium' },\n ],\n },\n coverage: {\n provider: 'v8', // o 'istanbul'\n include: [\n 'src/**/*.js', // Solo archivos JS dentro de src/\n ],\n },\n },\n})\n"]], "task_instance_info": {"created_time": "2025-08-21 00:01:54", "created_task_model": "DeepSeek-R1", "function_skeleton": "svg => {}", "code_description": "This code segment functions to: Gather referenced identifiers from embedded elements, locate corresponding definitions in external sources, replicate required elements, and embed them within each container to ensure self-contained functionality."}, "inference_content": {"inference_model": "DeepSeek-R1", "inference_result": "```javascript\n[TASK_BEGIN]\nsvg => {\n const defs = svg.querySelector('defs') || (() => {\n const d = document.createElementNS('http://www.w3.org/2000/svg', 'defs');\n svg.insertBefore(d, svg.firstChild);\n return d;\n })();\n\n svg.querySelectorAll('use').forEach(use => {\n const href = use.getAttribute('href') || use.getAttribute('xlink:href');\n if (!href?.startsWith('#')) return;\n \n const id = href.slice(1);\n defs.querySelectorAll(`#${id}`).forEach(n => n.remove());\n \n defsSources.forEach(sourceDefs => {\n const element = sourceDefs.querySelector(`#${id}`);\n if (element) {\n defs.appendChild(element.cloneNode(true));\n }\n });\n\n use.removeAttribute('xlink:href');\n });\n}\n[TASK_END]\n```", "inference_time": "2025-08-21 00-02-16"}, "editdistance_info": {"edit_distance": 20.4819, "calculate_time": "2025-08-21 00:02:16", "true_code_clean": "svg => {\n const uses = svg.querySelectorAll('use');\n if (!uses.length) return;\n const usedIds = new Set();\n uses.forEach(use => {\n const href = use.getAttribute('xlink:href') || use.getAttribute('href');\n if (href && href.startsWith('#')) usedIds.add(href.slice(1));\n });\n if (!usedIds.size) return;\n const defs = document.createElementNS(\"http:\n for (const id of usedIds) {\n for (const source of defsSources) {\n const def = source.querySelector(`#${CSS.escape(id)}`);\n if (def) {\n defs.appendChild(def.cloneNode(true));\n break;\n }\n }\n }\n if (defs.childNodes.length) {\n svg.insertBefore(defs, svg.firstChild);\n }\n }", "predict_code_clean": "svg => {\n const defs = svg.querySelector('defs') || (() => {\n const d = document.createElementNS('http:\n svg.insertBefore(d, svg.firstChild);\n return d;\n })();\n svg.querySelectorAll('use').forEach(use => {\n const href = use.getAttribute('href') || use.getAttribute('xlink:href');\n if (!href?.startsWith('#')) return;\n const id = href.slice(1);\n defs.querySelectorAll(`#${id}`).forEach(n => n.remove());\n defsSources.forEach(sourceDefs => {\n const element = sourceDefs.querySelector(`#${id}`);\n if (element) {\n defs.appendChild(element.cloneNode(true));\n }\n });\n use.removeAttribute('xlink:href');\n });\n}"}} {"repo_name": "snapdom", "file_name": "/snapdom/__tests__/cssTools.utils.test.js", "inference_info": {"prefix_code": "import { describe, it, expect } from 'vitest';\nimport { getStyleKey, collectUsedTagNames, getDefaultStyleForTag } from '../src/utils/cssTools.js';\n\ndescribe('getStyleKey', ", "suffix_code": ");\n\ndescribe('collectUsedTagNames', () => {\n it('returns unique tag names', () => {\n const root = document.createElement('div');\n root.innerHTML = '

';\n const tags = collectUsedTagNames(root);\n expect(tags).toContain('div');\n expect(tags).toContain('span');\n expect(tags).toContain('p');\n });\n});\n\ndescribe('getDefaultStyleForTag', () => {\n it('returns a default style object', () => {\n const defaults = getDefaultStyleForTag('div');\n expect(typeof defaults).toBe('object');\n });\n\n it('getDefaultStyleForTag skips special tags', () => {\n expect(getDefaultStyleForTag('script')).toEqual({});\n });\n});\n", "middle_code": "() => {\n it('generates a non-empty style key', () => {\n const snapshot = { color: 'red', 'font-size': '12px' };\n const key = getStyleKey(snapshot, 'div');\n expect(typeof key).toBe('string');\n expect(key.length).toBeGreaterThan(0);\n });\n it('getStyleKey works with compress true', () => {\n const snapshot = { color: 'red', 'font-size': '12px' };\n const key = getStyleKey(snapshot, 'div', true);\n expect(typeof key).toBe('string');\n });\n}", "code_description": null, "fill_type": "FUNCTION_TYPE", "language_type": "javascript", "sub_task_type": null}, "context_code": [["/snapdom/src/utils/cssTools.js", "/**\n * Utilities for working with CSS styles, defaults, and class generation.\n * @module cssTools\n */\n\nimport { cache } from \"../core/cache\"\n\nconst commonTags = [\n 'div', 'span', 'p', 'a', 'img', 'ul', 'li', 'button', 'input',\n 'select', 'textarea', 'label', 'section', 'article', 'header',\n 'footer', 'nav', 'main', 'aside', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6',\n 'svg', 'path', 'circle', 'rect', 'line', 'g', 'table', 'thead', 'tbody', 'tr', 'td', 'th'\n];\n\nexport function precacheCommonTags() {\n for (let tag of commonTags) {\n getDefaultStyleForTag(tag);\n }\n}\n/**\n * Retrieves default CSS property values from a temporary element.\n *\n * @param {string} tagName - The tag name to get default styles for\n * @returns {Object} Object containing default values for all CSS properties\n */\nexport function getDefaultStyleForTag(tagName) {\n if (cache.defaultStyle.has(tagName)) {\n return cache.defaultStyle.get(tagName);\n }\n\n const skipTags = new Set(['script', 'style', 'meta', 'link', 'noscript', 'template']);\n if (skipTags.has(tagName)) {\n const empty = {}; \n cache.defaultStyle.set(tagName, empty); \n return empty;\n }\n\n let sandbox = document.getElementById('snapdom-sandbox');\n if (!sandbox) {\n sandbox = document.createElement('div');\n sandbox.id = 'snapdom-sandbox';\n sandbox.style.position = 'absolute';\n sandbox.style.left = '-9999px';\n sandbox.style.top = '-9999px';\n sandbox.style.width = '0';\n sandbox.style.height = '0';\n sandbox.style.overflow = 'hidden';\n document.body.appendChild(sandbox);\n }\n\n const el = document.createElement(tagName);\n el.style.all = 'initial';\n sandbox.appendChild(el);\n\n const styles = getComputedStyle(el);\n const defaults = {};\n for (let prop of styles) {\n defaults[prop] = styles.getPropertyValue(prop);\n }\n\n sandbox.removeChild(el);\n cache.defaultStyle.set(tagName, defaults);\n return defaults;\n}\n\n/**\n * Creates a unique key from an element's computed style that differs from defaults.\n *\n * @param {Object} snapshot - Computed style snapshot\n * @param {string} tagName - The tag name of the element\n * @param {boolean} [compress=false] - Whether to compress style keys\n * @returns {string} Semi-colon separated list of non-default properties\n */\n\nexport function getStyleKey(snapshot, tagName, compress = false) {\n const entries = [];\n const defaultStyles = getDefaultStyleForTag(tagName);\n for (let [prop, value] of Object.entries(snapshot)) {\n if (!compress) {\n if (value) {\n entries.push(`${prop}:${value}`);\n }\n } else {\n const defaultValue = defaultStyles[prop];\n if (value && value !== defaultValue) {\n entries.push(`${prop}:${value}`);\n }\n }\n }\n\n return entries.sort().join(\";\");\n}\n\n/**\n * Collects all unique tag names used in the DOM tree rooted at the given node.\n *\n * @param {Node} root - The root node to search\n * @returns {string[]} Array of unique tag names\n */\nexport function collectUsedTagNames(root) {\n const tagSet = new Set();\n if (root.nodeType !== Node.ELEMENT_NODE && root.nodeType !== Node.DOCUMENT_FRAGMENT_NODE) {\n return [];\n }\n if (root.tagName) {\n tagSet.add(root.tagName.toLowerCase());\n }\n if (typeof root.querySelectorAll === 'function') {\n root.querySelectorAll(\"*\").forEach(el => tagSet.add(el.tagName.toLowerCase()));\n }\n return Array.from(tagSet);\n}\n\n/**\n * Generates deduplicated base CSS for the given tag names.\n *\n * @param {string[]} usedTagNames - Array of tag names\n * @returns {string} CSS string\n */\nexport function generateDedupedBaseCSS(usedTagNames) {\n const groups = new Map();\n\n for (let tagName of usedTagNames) {\n const styles = cache.defaultStyle.get(tagName);\n if (!styles) continue;\n\n // Creamos la \"firma\" del bloque CSS para comparar\n const key = Object.entries(styles)\n .map(([k, v]) => `${k}:${v};`)\n .sort()\n .join('');\n\n // Agrupamos por firma\n if (!groups.has(key)) {\n groups.set(key, []);\n }\n groups.get(key).push(tagName);\n }\n\n // Ahora generamos el CSS optimizado\n let css = '';\n for (let [styleBlock, tagList] of groups.entries()) {\n css += `${tagList.join(',')} { ${styleBlock} }\\n`;\n }\n\n return css;\n}\n/**\n * Generates CSS classes from a style map.\n *\n * @returns {Map} Map of style keys to class names\n */\nexport function generateCSSClasses() {\n const keySet = new Set(cache.preStyleMap.values());\n const classMap = new Map();\n let counter = 1;\n for (const key of keySet) {\n classMap.set(key, `c${counter++}`);\n }\n return classMap;\n}\n"], ["/snapdom/__tests__/helpers.utils.test.js", "import { describe, it, expect, vi } from 'vitest';\nimport { getStyle, parseContent, extractURL, isIconFont, snapshotComputedStyle, isSafari, stripTranslate, safeEncodeURI, idle, fetchImage } from '../src/utils/helpers.js';\n\ndescribe('getStyle', () => {\n it('returns a CSSStyleDeclaration', () => {\n const el = document.createElement('div');\n document.body.appendChild(el);\n const style = getStyle(el);\n expect(style).toBeInstanceOf(CSSStyleDeclaration);\n document.body.removeChild(el);\n });\n});\n\n\n\ndescribe('parseContent', () => {\n it('parses CSS content correctly', () => {\n expect(parseContent('\"★\"')).toBe('★');\n expect(parseContent('\\\\2605')).toBe('★');\n });\n});\n\ndescribe('parseContent edge cases', () => {\n it('returns \\u0000 if parseInt fails (not hex)', () => {\n expect(parseContent('\\\\nothex')).toBe('\\u0000');\n });\n it('returns clean if String.fromCharCode throws', () => {\n const orig = String.fromCharCode;\n String.fromCharCode = () => { throw new Error('fail'); };\n expect(parseContent('\\\\2605')).toBe('\\\\2605');\n String.fromCharCode = orig;\n });\n});\n\ndescribe('extractURL', () => {\n it('extracts the URL from background-image', () => {\n expect(extractURL('url(\"https://test.com/img.png\")')).toBe('https://test.com/img.png');\n expect(extractURL('none')).toBeNull();\n });\n});\n\ndescribe('isIconFont', () => {\n it('detects icon fonts', () => {\n expect(isIconFont('Font Awesome')).toBe(true);\n expect(isIconFont('Arial')).toBe(false);\n });\n});\n\ndescribe('snapshotComputedStyle', () => {\n it('returns a style snapshot', () => {\n const el = document.createElement('div');\n document.body.appendChild(el);\n const style = getComputedStyle(el);\n const snap = snapshotComputedStyle(style);\n expect(typeof snap).toBe('object');\n document.body.removeChild(el);\n });\n});\n\ndescribe('isSafari', () => {\n it('returns a boolean', () => {\n expect(typeof isSafari()).toBe('boolean');\n });\n});\n\ndescribe('stripTranslate', () => {\n it('removes translate transforms', () => {\n expect(stripTranslate('translateX(10px) scale(2)')).toContain('scale(2)');\n });\n it('stripTranslate removes matrix and matrix3d', () => {\n expect(stripTranslate('matrix(1,0,0,1,10,20)')).not.toContain('10,20');\n expect(stripTranslate('matrix3d(1,0,0,0,0,1,0,0,0,0,1,0,10,20,30,1)')).not.toContain('10,20,30');\n });\n});\n\ndescribe('safeEncodeURI', () => {\n it('returns an encoded string', () => {\n expect(typeof safeEncodeURI('https://test.com/á')).toBe('string');\n });\n it('safeEncodeURI handles invalid URIs gracefully', () => {\n expect(typeof safeEncodeURI('%E0%A4%A')).toBe('string');\n });\n});\n\ndescribe('idle', () => {\n it('calls fn immediately if fast is true', () => {\n let called = false;\n idle(() => { called = true; }, { fast: true });\n expect(called).toBe(true);\n });\n it('uses requestIdleCallback if available', () => {\n const orig = window.requestIdleCallback;\n let called = false;\n window.requestIdleCallback = (fn) => { called = true; fn(); };\n idle(() => { called = true; });\n expect(called).toBe(true);\n window.requestIdleCallback = orig;\n });\n it('falls back to setTimeout if requestIdleCallback not available', async () => {\n const orig = window.requestIdleCallback;\n delete window.requestIdleCallback;\n let called = false;\n idle(() => { called = true; });\n await new Promise(r => setTimeout(r, 10));\n expect(called).toBe(true);\n window.requestIdleCallback = orig;\n });\n});\n\ndescribe('fetchImage', () => {\n it('rejects on image error', async () => {\n await expect(fetchImage('invalid-url', { timeout: 100 }))\n .rejects.toThrow('Fetch fallback failed and no proxy provided');\n\n });\n it('rejects on timeout', async () => {\n // Simula una imagen que nunca carga\n const origImage = window.Image;\n window.Image = class { set src(_){} onload(){} onerror(){} };\n await expect(fetchImage('timeout-url', { timeout: 10 })).rejects.toThrow('Image load timed out');\n window.Image = origImage;\n });\n\n});\n\ndescribe('fetchImage cache', () => {\n it('returns cached image if present', async () => {\n const { cache } = await import('../src/core/cache.js');\n cache.image.set('cached-url', 'data:image/png;base64,abc');\n const result = await fetchImage('cached-url', { useProxy: false });\n expect(result).toBe('data:image/png;base64,abc');\n cache.image.delete('cached-url');\n });\n});\n\ndescribe('fetchImage error propagation', () => {\n it('rejects with original error if decode fails', async () => {\n const origImage = window.Image;\n window.Image = class {\n constructor() { setTimeout(() => this.onload(), 1); }\n set src(_){}\n decode() { return Promise.reject(new Error('decode fail')); }\n get width() { return 1; }\n get height() { return 1; }\n };\n await expect(fetchImage('decode-fail-url', { timeout: 100 }))\n .rejects.toThrow('Fetch fallback failed and no proxy provided');\n window.Image = origImage;\n });\n});\n\ndescribe('stripTranslate edge cases', () => {\n it('returns empty string for empty or none', () => {\n expect(stripTranslate('')).toBe('');\n expect(stripTranslate('none')).toBe('');\n });\n it('returns original for malformed matrix', () => {\n expect(stripTranslate('matrix(1,2,3)')).toBe('matrix(1,2,3)');\n expect(stripTranslate('matrix3d(1,2,3)')).toBe('matrix3d(1,2,3)');\n });\n});\n"], ["/snapdom/__tests__/fonts.module.test.js", "import { describe, it, expect, beforeEach, vi } from 'vitest';\nimport { iconToImage, embedCustomFonts } from '../src/modules/fonts.js';\nimport { cache } from '../src/core/cache.js';\n\n// Utilidad para limpiar estilos y links antes de cada test\nfunction cleanFontEnvironment() {\n document.querySelectorAll('style,link[rel=\"stylesheet\"]').forEach(s => s.remove());\n}\n\nfunction addStyleTag(css) {\n const style = document.createElement('style');\n style.setAttribute('data-test-style', 'true');\n style.textContent = css;\n document.head.appendChild(style);\n return style;\n}\n\ndescribe('iconToImage', () => {\n it('genera un dataURL para un carácter unicode', async () => {\n const url = await iconToImage('★', 'Arial', 'bold', 32, '#000');\n expect(url.startsWith('data:image/')).toBe(true);\n });\n\n it('maneja diferentes pesos y colores de fuente', async () => {\n const url = await iconToImage('★', 'Arial', 700, 40, '#ff0000');\n expect(url.startsWith('data:image/')).toBe(true);\n });\n\n it('usa valores por defecto si no hay métricas', async () => {\n const orig = HTMLCanvasElement.prototype.getContext;\n HTMLCanvasElement.prototype.getContext = function() {\n return {\n font: '',\n scale: vi.fn(),\n textAlign: '',\n textBaseline: '',\n fillStyle: '',\n fillText: vi.fn(),\n measureText: () => ({ width: 10 })\n };\n };\n const url = await iconToImage('★', 'Arial', 'bold', 32, '#000');\n expect(url.startsWith('data:image/')).toBe(true);\n HTMLCanvasElement.prototype.getContext = orig;\n });\n});\n\ndescribe('embedCustomFonts', () => {\n beforeEach(() => {\n cache.reset();\n cache.font.clear();\n cache.resource.clear();\n cleanFontEnvironment();\n vi.restoreAllMocks();\n });\n\n it('conserva @font-face con solo local() en src', async () => {\n const style = addStyleTag(`\n @font-face {\n font-family: OnlyLocal;\n src: local(\"Arial\");\n font-style: normal;\n font-weight: normal;\n }\n `);\n\n const css = await embedCustomFonts();\n expect(css).toMatch(/font-family:\\s*OnlyLocal/);\n expect(css).toMatch(/src:\\s*local\\([\"']Arial[\"']\\)/);\n document.head.removeChild(style);\n });\n\n it('conserva @font-face con local() y sin url()', async () => {\n const style = addStyleTag(`\n @font-face {\n font-family: LocalFont;\n src: local('MyFont'), local('FallbackFont');\n font-style: italic;\n font-weight: bold;\n }\n `);\n\n const css = await embedCustomFonts();\n expect(css).toMatch(/font-family:\\s*LocalFont/);\n expect(css).toMatch(/src:\\s*local\\(['\"]MyFont['\"]\\),\\s*local\\(['\"]FallbackFont['\"]\\)/);\n expect(css).toMatch(/font-style:\\s*italic/);\n document.head.removeChild(style);\n });\n});\n"], ["/snapdom/__tests__/snapdom.api.test.js", "import { describe, it, expect, vi } from 'vitest';\nimport { snapdom } from '../src/api/snapdom.js';\n\ndescribe('snapdom API (direct)', () => {\n it('throws on null element', async () => {\n await expect(snapdom(null)).rejects.toThrow();\n });\n\n it('snapdom.capture returns export methods', async () => {\n const el = document.createElement('div');\n el.style.width = '100px';\n el.style.height = '50px';\n document.body.appendChild(el);\n const result = await snapdom.capture(el);\n expect(result).toHaveProperty('toRaw');\n expect(result).toHaveProperty('toImg');\n expect(result).toHaveProperty('download');\n document.body.removeChild(el);\n });\n\n it('snapdom.toRaw, toImg, toCanvas, toBlob, toPng, toJpg, toWebp, download', async () => {\n const el = document.createElement('div');\n el.style.width = '100px';\n el.style.height = '50px';\n document.body.appendChild(el);\n await snapdom.toRaw(el);\n await snapdom.toImg(el);\n await snapdom.toCanvas(el);\n await snapdom.toBlob(el);\n await snapdom.toPng(el);\n await snapdom.toJpg(el);\n await snapdom.toWebp(el);\n await snapdom.download(el, { format: 'png', filename: 'test' });\n document.body.removeChild(el);\n });\n\n it('cubre rama Safari en toImg', async () => {\n vi.resetModules();\n vi.mock('../utils/helpers.js', async () => {\n const actual = await vi.importActual('../utils/helpers.js');\n return { ...actual, isSafari: true };\n });\n const { snapdom } = await import('../src/api/snapdom.js');\n const el = document.createElement('div');\n el.style.width = '10px';\n el.style.height = '10px';\n document.body.appendChild(el);\n // Forzar un SVG dataURL simple\n const img = new Image();\n img.width = 10;\n img.height = 10;\n img.decode = () => Promise.resolve();\n globalThis.Image = function() { return img; };\n const res = await snapdom.capture(el);\n await res.toImg();\n document.body.removeChild(el);\n vi.resetModules();\n });\n\n it('cubre rama de download SVG', async () => {\n const el = document.createElement('div');\n el.style.width = '10px';\n el.style.height = '10px';\n document.body.appendChild(el);\n // Mock a.click y URL.createObjectURL\n const a = document.createElement('a');\n document.body.appendChild(a);\n const origCreate = URL.createObjectURL;\n URL.createObjectURL = () => 'blob:url';\n const origClick = a.click;\n a.click = () => {};\n HTMLAnchorElement.prototype.click = () => {};\n const { snapdom } = await import('../src/api/snapdom.js');\n await snapdom.download(el, { format: 'svg', filename: 'testsvg' });\n URL.createObjectURL = origCreate;\n a.click = origClick;\n document.body.removeChild(a);\n document.body.removeChild(el);\n });\n\n it('snapdom.toBlob supports type options ', async () => {\n const el = document.createElement('div');\n el.style.width = '50px';\n el.style.height = '30px';\n document.body.appendChild(el);\n\n const result = await snapdom.capture(el);\n\n const pngBlob = await result.toBlob({ type: 'png' });\n expect(pngBlob).toBeInstanceOf(Blob);\n expect(pngBlob.type).toBe('image/png');\n\n const jpgBlob = await result.toBlob({ type: 'jpeg', quality: 0.8 });\n expect(jpgBlob).toBeInstanceOf(Blob);\n expect(jpgBlob.type).toBe('image/jpeg');\n\n const webpBlob = await result.toBlob({ type: 'webp', quality: 0.9 });\n expect(webpBlob).toBeInstanceOf(Blob);\n expect(webpBlob.type).toBe('image/webp');\n\n // default fallback\n const svgBlob = await result.toBlob();\n expect(svgBlob).toBeInstanceOf(Blob);\n expect(svgBlob.type).toBe('image/svg+xml');\n\n document.body.removeChild(el);\n});\n\nit('toPng, toJpg, toWebp return HTMLImageElement with URLs', async () => {\n const el = document.createElement('div');\n el.style.width = '60px';\n el.style.height = '40px';\n document.body.appendChild(el);\n const snap = await snapdom.capture(el);\n\n const pngImg = await snap.toPng();\n expect(pngImg).toBeInstanceOf(HTMLImageElement);\n expect(typeof pngImg.src).toBe('string');\nexpect(pngImg.src.startsWith('data:image/png')).toBe(true);\n\n const jpgImg = await snap.toJpg();\n expect(jpgImg).toBeInstanceOf(HTMLImageElement);\n expect(typeof jpgImg.src).toBe('string');\nexpect(jpgImg.src.startsWith('data:image/jpeg')).toBe(true);\n\n const webpImg = await snap.toWebp();\n expect(webpImg).toBeInstanceOf(HTMLImageElement);\n expect(typeof webpImg.src).toBe('string');\nexpect(webpImg.src.startsWith('data:image/webp')).toBe(true);\n document.body.removeChild(el);\n});\n\nit('snapdom should support exclude option to filter out elements by CSS selectors', async () => {\n const el = document.createElement('div');\n el.innerHTML = `\n

Title

\n
Should be excluded
\n
Private data
\n

This should remain

\n `;\n document.body.appendChild(el);\n \n const result = await snapdom(el, { exclude: ['.exclude-me', '[data-private]'] });\n \n const svg = result.toRaw();\n const decoded = decodeURIComponent(svg.split(\",\")[1]);\n expect(decoded).not.toContain('Should be excluded');\n expect(decoded).not.toContain('Private data');\n expect(decoded).toContain('Title');\n expect(decoded).toContain('This should remain');\n});\n\nit('snapdom should support filter option to exclude elements with custom logic', async () => {\n const el = document.createElement('div');\n el.innerHTML = `\n
Level 1\n
Level 2\n
Level 3
\n
\n
\n `;\n document.body.appendChild(el);\n const result = await snapdom(el, { \n filter: (element) => !element.classList.contains('level-3')\n });\n \n const svg = result.toRaw();\n const decoded = decodeURIComponent(svg.split(\",\")[1]);\n expect(decoded).toContain('Level 1');\n expect(decoded).toContain('Level 2');\n expect(decoded).not.toContain('Level 3');\n});\n\nit('snapdom should support combining exclude and filter options', async () => {\n const el = document.createElement('div');\n el.innerHTML = `\n
Exclude by selector
\n
Exclude by filter
\n
Keep this content
\n `;\n document.body.appendChild(el);\n\n const result = await snapdom(el, { \n exclude: ['.exclude-by-selector'],\n filter: (element) => !element.classList.contains('exclude-by-filter')\n });\n \n \n const svg = result.toRaw();\n const decoded = decodeURIComponent(svg.split(\",\")[1]);\n expect(decoded).not.toContain('Exclude by selector');\n expect(decoded).not.toContain('Exclude by filter');\n expect(decoded).toContain('Keep this content');\n});\n\n});\n"], ["/snapdom/__tests__/clone.core.test.js", "import { describe, it, expect, vi } from 'vitest';\nimport { deepClone } from '../src/core/clone.js';\n\ndescribe('deepClone', () => {\n it('clones a simple div', () => {\n const el = document.createElement('div');\n el.textContent = 'hello';\n const styleMap = new Map();\n const styleCache = new WeakMap();\n const nodeMap = new Map();\n const clone = deepClone(el, styleMap, styleCache, nodeMap, false);\n expect(clone).not.toBe(el);\n expect(clone.textContent).toBe('hello');\n });\n\n it('clones canvas as an image', () => {\n const canvas = document.createElement('canvas');\n canvas.width = 10;\n canvas.height = 10;\n const ctx = canvas.getContext('2d');\n ctx.fillStyle = 'red';\n ctx.fillRect(0,0,10,10);\n const styleMap = new Map();\n const styleCache = new WeakMap();\n const nodeMap = new Map();\n const clone = deepClone(canvas, styleMap, styleCache, nodeMap, false);\n expect(clone.tagName).toBe('IMG');\n expect(clone.src.startsWith('data:image/')).toBe(true);\n });\n\n it('deepClone handles data-capture=\"exclude\"', () => {\n const el = document.createElement('div');\n el.setAttribute('data-capture', 'exclude');\n const clone = deepClone(el, true, {});\n expect(clone).not.toBeNull();\n });\n\n it('deepClone handles data-capture=\"placeholder\"', () => {\n const el = document.createElement('div');\n el.setAttribute('data-capture', 'placeholder');\n el.setAttribute('data-placeholder-text', 'Placeholder!');\n const clone = deepClone(el, true, {});\n expect(clone.textContent).toContain('Placeholder!');\n });\n\n it('deepClone handles iframe', () => {\n const iframe = document.createElement('iframe');\n iframe.width = 100;\n iframe.height = 50;\n const clone = deepClone(iframe, true, {});\n expect(clone.tagName).toBe('DIV');\n });\n\n it('deepClone handles input, textarea, select', () => {\n const input = document.createElement('input');\n input.value = 'foo';\n input.checked = true;\n const textarea = document.createElement('textarea');\n textarea.value = 'bar';\n const select = document.createElement('select');\n const opt = document.createElement('option');\n opt.value = 'baz';\n select.appendChild(opt);\n select.value = 'baz';\n [input, textarea, select].forEach(el => {\n const clone = deepClone(el, true, {});\n expect(clone.value).toBe(el.value);\n });\n });\n\n it('deepClone handles shadow DOM', () => {\n const el = document.createElement('div');\n const shadow = el.attachShadow({mode:'open'});\n const span = document.createElement('span');\n span.textContent = 'shadow';\n shadow.appendChild(span);\n const clone = deepClone(el, true, {});\n expect(clone).not.toBeNull();\n });\n});\n\ndescribe('deepClone edge cases', () => {\n it('clones unsupported node (Comment) as a new Comment', () => {\n const fake = document.createComment('not supported');\n const result = deepClone(fake, true, {});\n expect(result.nodeType).toBe(Node.COMMENT_NODE);\n expect(result.textContent).toBe('not supported');\n expect(result).not.toBe(fake); // Es un clon, no el mismo objeto\n });\n it('clones attributes and children', () => {\n const el = document.createElement('div');\n el.setAttribute('data-test', '1');\n const result = deepClone(el, true, {});\n expect(result.getAttribute('data-test')).toBe('1');\n });\n});\n"], ["/snapdom/__tests__/snapdom.advance.test.js", "import { describe, it, expect, beforeEach, afterEach } from 'vitest';\nimport { snapdom } from '../src/index';\n\ndescribe('snapdom advanced tests', () => {\n let testElement;\n\n beforeEach(() => {\n testElement = document.createElement('div');\n testElement.style.width = '100px';\n testElement.style.height = '50px';\n testElement.innerHTML = '

Hello World

';\n document.body.appendChild(testElement);\n });\n\n afterEach(() => {\n document.body.removeChild(testElement);\n });\n\n it('should generate different SVGs for different scales', async () => {\n const svg1 = await snapdom.toImg(testElement, { scale: 1 });\n const svg2 = await snapdom.toImg(testElement, { scale: 2 });\n expect(svg1).not.toBe(svg2);\n });\n\n it('captured SVG should contain inner text content', async () => {\n const svgDataUrl = await snapdom.toRaw(testElement);\n const svgText = decodeURIComponent(svgDataUrl.split(',')[1]);\n expect(svgText).toContain('Hello World');\n });\n\n it('should throw an error if element is null', async () => {\n await expect(() => snapdom.toRaw(null)).rejects.toThrow();\n });\n\n it('should generate SVG with correct attributes', async () => {\n const svgDataUrl = await snapdom.toRaw(testElement);\n const svgText = decodeURIComponent(svgDataUrl.split(',')[1]);\n const parser = new DOMParser();\n const doc = parser.parseFromString(svgText, 'image/svg+xml');\n const svg = doc.querySelector('svg');\n\n expect(svg).not.toBeNull();\n expect(svg.getAttribute('width')).toBe('100');\n expect(svg.getAttribute('height')).toBe('50');\n expect(svg.getAttribute('viewBox')).toBe('0 0 100 50');\n });\n\n it('snapdom.toBlob should contain valid SVG content', async () => {\n const blob = await snapdom.toBlob(testElement);\n const text = await blob.text();\n expect(text).toContain('');\n });\n\n it('should replace iframes with fallback visuals', async () => {\n const iframe = document.createElement('iframe');\n iframe.style.width = '200px';\n iframe.style.height = '100px';\n testElement.appendChild(iframe);\n\n const svgDataUrl = await snapdom.toRaw(testElement);\n const svgText = decodeURIComponent(svgDataUrl.split(',')[1]);\n\n const parser = new DOMParser();\n const doc = parser.parseFromString(svgText, 'image/svg+xml');\n\n // No debe haber iframes en el SVG\n expect(doc.querySelectorAll('iframe').length).toBe(0);\n\n // Buscamos divs con estilo inline que contengan repeating-linear-gradient\n const fallbackDivs = Array.from(doc.querySelectorAll('div')).filter(div => {\n const styleAttr = div.getAttribute('style') || '';\n return styleAttr.includes('repeating-linear-gradient');\n });\n\n expect(fallbackDivs.length).toBeGreaterThan(0);\n});\n\n \n});\n"], ["/snapdom/__tests__/preCache.api.test.js", "import { describe, it, expect, beforeEach } from 'vitest';\nimport { preCache } from '../src/api/preCache.js';\nimport { cache } from '../src/core/cache.js';\n\ndescribe('preCache', () => {\n beforeEach(() => {\n cache.reset()\n });\n\n it('pre-caches images and backgrounds', async () => {\n const el = document.createElement('div');\n const img = document.createElement('img');\n img.src = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/w8AAn8B9p6Q2wAAAABJRU5ErkJggg==';\n el.appendChild(img);\n document.body.appendChild(el);\n await preCache(el);\n expect(cache.image.has(img.src)).toBe(true);\n document.body.removeChild(el);\n });\n\n it('should handle preCache with embedFonts false', async () => {\n const el = document.createElement('div');\n await expect(preCache(el, { embedFonts: false })).resolves.toBeUndefined();\n });\n\n it('should handle preCache with images that fail to load', async () => {\n const el = document.createElement('div');\n const img = document.createElement('img');\n img.src = 'invalid-url.png';\n el.appendChild(img);\n await expect(preCache(el)).resolves.toBeUndefined();\n });\n\n it('should handle preCache with backgrounds that fail to load', async () => {\n const el = document.createElement('div');\n el.style.backgroundImage = 'url(invalid-url.png)';\n document.body.appendChild(el);\n await expect(preCache(el)).resolves.toBeUndefined();\n document.body.removeChild(el);\n });\n\n it('limpia los caches y retorna si reset=true', async () => {\n // Prellenar los caches\n cache.snapshotKey.set('foo', 'bar');\n cache.preStyleMap.set('foo', 'bar');\n cache.preNodeMap.set('foo', 'bar');\n await preCache(document, { reset: true });\n expect(cache.snapshotKey.size).toBe(0);\n expect(cache.preStyleMap.size).toBe(0);\n expect(cache.preNodeMap.size).toBe(0);\n });\n\n it('procesa múltiples backgrounds en un solo elemento', async () => {\n const el = document.createElement('div');\n el.style.backgroundImage = 'url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/w8AAn8B9p6Q2wAAAABJRU5ErkJggg==), url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/w8AAn8B9p6Q2wAAAABJRU5ErkJggg==)';\n document.body.appendChild(el);\n await preCache(el);\n // No assertion estricta porque depende de helpers, pero no debe lanzar error\n document.body.removeChild(el);\n });\n\n});\n"], ["/snapdom/__tests__/pseudo.module.test.js", "vi.mock('../src/utils/helpers.js', async () => {\n const actual = await vi.importActual('../src/utils/helpers.js');\n return {\n ...actual,\n fetchImage: vi.fn(),\n };\n});\nvi.mock('../src/modules/fonts.js', async () => {\n const actual = await vi.importActual('../src/modules/fonts.js');\n return {\n ...actual,\n iconToImage: vi.fn(),\n };\n});\n\nimport { describe, it, expect, vi } from 'vitest';\nimport { inlinePseudoElements } from '../src/modules/pseudo.js';\nimport * as helpers from '../src/utils/helpers.js';\nimport * as fonts from '../src/modules/fonts.js';\n\ndescribe('inlinePseudoElements', () => {\n it('does not fail with simple elements', async () => {\n const el = document.createElement('div');\n const clone = document.createElement('div');\n await expect(inlinePseudoElements(el, clone, new Map(), new WeakMap(), false)).resolves.toBeUndefined();\n });\n\n it('handles ::before with text content', async () => {\n const el = document.createElement('div');\n const clone = document.createElement('div');\n vi.spyOn(window, 'getComputedStyle').mockImplementation((_, pseudo) => {\n if (pseudo === '::before') return {\n getPropertyValue: (prop) => prop === 'content' ? '\"★\"' : prop === 'font-family' ? 'Arial' : prop === 'font-size' ? '32' : prop === 'font-weight' ? '400' : prop === 'color' ? '#000' : prop === 'background-image' ? 'none' : prop === 'background-color' ? 'transparent' : '',\n color: '#000', fontSize: '32px', fontWeight: '400', fontFamily: 'Arial',\n };\n return { getPropertyValue: () => '', color: '', fontSize: '', fontWeight: '', fontFamily: '' };\n });\n await inlinePseudoElements(el, clone, new Map(), new WeakMap(), false);\n window.getComputedStyle.mockRestore();\n });\n\n it('handles ::before with icon font', async () => {\n const el = document.createElement('div');\n const clone = document.createElement('div');\n vi.spyOn(window, 'getComputedStyle').mockImplementation((_, pseudo) => {\n if (pseudo === '::before') return {\n getPropertyValue: (prop) => prop === 'content' ? '\"★\"' : prop === 'font-family' ? 'Font Awesome' : prop === 'font-size' ? '32' : prop === 'font-weight' ? '400' : prop === 'color' ? '#000' : prop === 'background-image' ? 'none' : prop === 'background-color' ? 'transparent' : '',\n color: '#000', fontSize: '32px', fontWeight: '400', fontFamily: 'Font Awesome',\n };\n return { getPropertyValue: () => '', color: '', fontSize: '', fontWeight: '', fontFamily: '' };\n });\n fonts.iconToImage.mockResolvedValue('data:image/png;base64,icon');\n await inlinePseudoElements(el, clone, new Map(), new WeakMap(), false);\n window.getComputedStyle.mockRestore();\n });\n\n it('handles ::before with url content', async () => {\n const el = document.createElement('div');\n const clone = document.createElement('div');\n vi.spyOn(window, 'getComputedStyle').mockImplementation((_, pseudo) => {\n if (pseudo === '::before') return {\n getPropertyValue: (prop) => prop === 'content' ? 'url(\"https://test.com/img.png\")' : prop === 'font-family' ? 'Arial' : prop === 'font-size' ? '32' : prop === 'font-weight' ? '400' : prop === 'color' ? '#000' : prop === 'background-image' ? 'none' : prop === 'background-color' ? 'transparent' : '',\n color: '#000', fontSize: '32px', fontWeight: '400', fontFamily: 'Arial',\n };\n return { getPropertyValue: () => '', color: '', fontSize: '', fontWeight: '', fontFamily: '' };\n });\n helpers.fetchImage.mockResolvedValue('data:image/png;base64,img');\n await inlinePseudoElements(el, clone, new Map(), new WeakMap(), false);\n window.getComputedStyle.mockRestore();\n });\n\n it('handles ::before with background-image (data url)', async () => {\n const el = document.createElement('div');\n const clone = document.createElement('div');\n vi.spyOn(window, 'getComputedStyle').mockImplementation((_, pseudo) => {\n if (pseudo === '::before') return {\n getPropertyValue: (prop) => prop === 'content' ? 'none' : prop === 'font-family' ? 'Arial' : prop === 'font-size' ? '32' : prop === 'font-weight' ? '400' : prop === 'color' ? '#000' : prop === 'background-image' ? 'url(\"data:image/png;base64,abc\")' : prop === 'background-color' ? 'transparent' : '',\n color: '#000', fontSize: '32px', fontWeight: '400', fontFamily: 'Arial',\n };\n return { getPropertyValue: () => '', color: '', fontSize: '', fontWeight: '', fontFamily: '' };\n });\n await inlinePseudoElements(el, clone, new Map(), new WeakMap(), false);\n window.getComputedStyle.mockRestore();\n });\n\n it('handles ::before with background-image (fetch)', async () => {\n const el = document.createElement('div');\n const clone = document.createElement('div');\n vi.spyOn(window, 'getComputedStyle').mockImplementation((_, pseudo) => {\n if (pseudo === '::before') return {\n getPropertyValue: (prop) => prop === 'content' ? 'none' : prop === 'font-family' ? 'Arial' : prop === 'font-size' ? '32' : prop === 'font-weight' ? '400' : prop === 'color' ? '#000' : prop === 'background-image' ? 'url(\"https://test.com/img.png\")' : prop === 'background-color' ? 'transparent' : '',\n color: '#000', fontSize: '32px', fontWeight: '400', fontFamily: 'Arial',\n };\n return { getPropertyValue: () => '', color: '', fontSize: '', fontWeight: '', fontFamily: '' };\n });\n helpers.fetchImage.mockResolvedValue('data:image/png;base64,img');\n await inlinePseudoElements(el, clone, new Map(), new WeakMap(), false);\n window.getComputedStyle.mockRestore();\n });\n\n it('handles ::before with background-image fetch error', async () => {\n const el = document.createElement('div');\n const clone = document.createElement('div');\n vi.spyOn(window, 'getComputedStyle').mockImplementation((_, pseudo) => {\n if (pseudo === '::before') return {\n getPropertyValue: (prop) => prop === 'content' ? 'none' : prop === 'font-family' ? 'Arial' : prop === 'font-size' ? '32' : prop === 'font-weight' ? '400' : prop === 'color' ? '#000' : prop === 'background-image' ? 'url(\"https://test.com/img.png\")' : prop === 'background-color' ? 'transparent' : '',\n color: '#000', fontSize: '32px', fontWeight: '400', fontFamily: 'Arial',\n };\n return { getPropertyValue: () => '', color: '', fontSize: '', fontWeight: '', fontFamily: '' };\n });\n helpers.fetchImage.mockRejectedValue(new Error('fail'));\n await inlinePseudoElements(el, clone, new Map(), new WeakMap(), false);\n window.getComputedStyle.mockRestore();\n });\n\n it('handles ::before with no visible box', async () => {\n const el = document.createElement('div');\n const clone = document.createElement('div');\n vi.spyOn(window, 'getComputedStyle').mockImplementation((_, pseudo) => {\n if (pseudo === '::before') return {\n getPropertyValue: () => 'none', color: '', fontSize: '', fontWeight: '', fontFamily: ''\n };\n return { getPropertyValue: () => '', color: '', fontSize: '', fontWeight: '', fontFamily: '' };\n });\n await inlinePseudoElements(el, clone, new Map(), new WeakMap(), false);\n window.getComputedStyle.mockRestore();\n });\n\n it('handles ::first-letter with no textNode', async () => {\n const el = document.createElement('div');\n const clone = document.createElement('div');\n vi.spyOn(window, 'getComputedStyle').mockImplementation(() => ({\n getPropertyValue: () => '', color: '', fontSize: '', fontWeight: '', fontFamily: ''\n }));\n await inlinePseudoElements(el, clone, new Map(), new WeakMap(), false);\n window.getComputedStyle.mockRestore();\n });\n\n it('handles error in pseudo processing', async () => {\n const el = document.createElement('div');\n const clone = document.createElement('div');\n vi.spyOn(window, 'getComputedStyle').mockImplementation(() => { throw new Error('fail'); });\n await inlinePseudoElements(el, clone, new Map(), new WeakMap(), false);\n window.getComputedStyle.mockRestore();\n });\n\n it('ignores if source no es Element', async () => {\n const notElement = {};\n const clone = document.createElement('div');\n await expect(inlinePseudoElements(notElement, clone, new Map(), new WeakMap(), false)).resolves.toBeUndefined();\n });\n\n it('ignores if clone no es Element', async () => {\n const el = document.createElement('div');\n const notElement = {};\n await expect(inlinePseudoElements(el, notElement, new Map(), new WeakMap(), false)).resolves.toBeUndefined();\n });\n\n it('inserta pseudoEl como ::after', async () => {\n const el = document.createElement('div');\n const clone = document.createElement('div');\n vi.spyOn(window, 'getComputedStyle').mockImplementation((_, pseudo) => {\n if (pseudo === '::after') return {\n getPropertyValue: (prop) => prop === 'content' ? '\"after\"' : prop === 'font-family' ? 'Arial' : prop === 'font-size' ? '32' : prop === 'font-weight' ? '400' : prop === 'color' ? '#000' : prop === 'background-image' ? 'none' : prop === 'background-color' ? '#f00' : '',\n color: '#000', fontSize: '32px', fontWeight: '400', fontFamily: 'Arial',\n };\n return { getPropertyValue: () => '', color: '', fontSize: '', fontWeight: '', fontFamily: '' };\n });\n await inlinePseudoElements(el, clone, new Map(), new WeakMap(), false);\n window.getComputedStyle.mockRestore();\n });\n\n it('inserta pseudoEl como ::before', async () => {\n const el = document.createElement('div');\n const clone = document.createElement('div');\n vi.spyOn(window, 'getComputedStyle').mockImplementation((_, pseudo) => {\n if (pseudo === '::before') return {\n getPropertyValue: (prop) => prop === 'content' ? '\"before\"' : prop === 'font-family' ? 'Arial' : prop === 'font-size' ? '32' : prop === 'font-weight' ? '400' : prop === 'color' ? '#000' : prop === 'background-image' ? 'none' : prop === 'background-color' ? '#f00' : '',\n color: '#000', fontSize: '32px', fontWeight: '400', fontFamily: 'Arial',\n };\n return { getPropertyValue: () => '', color: '', fontSize: '', fontWeight: '', fontFamily: '' };\n });\n await inlinePseudoElements(el, clone, new Map(), new WeakMap(), false);\n window.getComputedStyle.mockRestore();\n });\n\n it('no inserta pseudoEl si no hay visible box', async () => {\n const el = document.createElement('div');\n const clone = document.createElement('div');\n vi.spyOn(window, 'getComputedStyle').mockImplementation((_, pseudo) => {\n if (pseudo === '::before') return {\n getPropertyValue: (prop) => 'none', color: '', fontSize: '', fontWeight: '', fontFamily: ''\n };\n return { getPropertyValue: () => '', color: '', fontSize: '', fontWeight: '', fontFamily: '' };\n });\n await inlinePseudoElements(el, clone, new Map(), new WeakMap(), false);\n window.getComputedStyle.mockRestore();\n });\n\n it('maneja ::first-letter meaningful', async () => {\n const el = document.createElement('div');\n el.textContent = 'Test';\n const clone = document.createElement('div');\n clone.textContent = 'Test';\n vi.spyOn(window, 'getComputedStyle').mockImplementation((_, pseudo) => {\n if (pseudo === '::first-letter') return {\n getPropertyValue: (prop) => prop === 'color' ? '#f00' : '', color: '#f00', fontSize: '32px', fontWeight: '400', fontFamily: 'Arial',\n };\n return { getPropertyValue: () => '', color: '#000', fontSize: '32px', fontWeight: '400', fontFamily: 'Arial' };\n });\n await inlinePseudoElements(el, clone, new Map(), new WeakMap(), false);\n window.getComputedStyle.mockRestore();\n });\n\n it('inserta ambos pseudoEl ::before y ::after en una sola ejecución', async () => {\n const el = document.createElement('div');\n const clone = document.createElement('div');\n vi.spyOn(window, 'getComputedStyle').mockImplementation((_, pseudo) => {\n if (pseudo === '::before') return {\n getPropertyValue: (prop) => prop === 'content' ? '\"before\"' : prop === 'font-family' ? 'Arial' : prop === 'font-size' ? '32' : prop === 'font-weight' ? '400' : prop === 'color' ? '#000' : prop === 'background-image' ? 'none' : prop === 'background-color' ? '#f00' : '',\n color: '#000', fontSize: '32px', fontWeight: '400', fontFamily: 'Arial',\n };\n if (pseudo === '::after') return {\n getPropertyValue: (prop) => prop === 'content' ? '\"after\"' : prop === 'font-family' ? 'Arial' : prop === 'font-size' ? '32' : prop === 'font-weight' ? '400' : prop === 'color' ? '#000' : prop === 'background-image' ? 'none' : prop === 'background-color' ? '#0f0' : '',\n color: '#000', fontSize: '32px', fontWeight: '400', fontFamily: 'Arial',\n };\n return { getPropertyValue: () => '', color: '', fontSize: '', fontWeight: '', fontFamily: '' };\n });\n await inlinePseudoElements(el, clone, new Map(), new WeakMap(), false);\n window.getComputedStyle.mockRestore();\n });\n\n it('should inline ::first-letter when style is meaningful', async () => {\n const el = document.createElement('p');\n el.textContent = '¡Hola mundo!';\n el.style.setProperty('color', 'black');\n\n document.body.appendChild(el);\n const clone = el.cloneNode(true);\n const styleMap = new Map();\n const styleCache = new WeakMap();\n\n const style = document.createElement('style');\n style.textContent = `\n p::first-letter {\n color: red;\n font-size: 200%;\n }\n `;\n document.head.appendChild(style);\n\n await inlinePseudoElements(el, clone, styleMap, styleCache, false);\n const firstLetterEl = clone.querySelector('[data-snapdom-pseudo=\"::first-letter\"]');\n expect(firstLetterEl).toBeTruthy();\n expect(firstLetterEl.textContent.length).toBeGreaterThan(0);\n});\n\nit('should inline background-image entries for pseudo-element', async () => {\n const el = document.createElement('div');\n document.body.appendChild(el);\n\n const style = document.createElement('style');\n style.textContent = `\n div::after {\n content: \" \";\n background-image: url(\"data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg'%3E%3Crect width='10' height='10' fill='blue'/%3E%3C/svg%3E\");\n display: inline-block;\n width: 10px;\n height: 10px;\n }\n `;\n document.head.appendChild(style);\n\n const clone = el.cloneNode(true);\n const styleMap = new Map();\n const styleCache = new WeakMap();\n\n await inlinePseudoElements(el, clone, styleMap, styleCache, false);\n const pseudoAfter = clone.querySelector('[data-snapdom-pseudo=\"::after\"]');\n expect(pseudoAfter).toBeTruthy();\n expect(pseudoAfter.style.backgroundImage.startsWith(\"url(\\\"data:image/\")).toBeTruthy();\n});\n\n});\n\n\n\n\n\n"], ["/snapdom/__tests__/prepare.core.test.js", "import { describe, it, expect, vi } from 'vitest';\nimport { prepareClone } from '../src/core/prepare.js';\n\ndescribe('prepareClone', () => {\n it('prepares a clone of a div', async () => {\n const el = document.createElement('div');\n el.textContent = 'test';\n const { clone, classCSS } = await prepareClone(el);\n expect(clone).not.toBeNull();\n expect(typeof classCSS).toBe('string');\n });\n});\n\ndescribe('prepareClone edge cases', () => {\n it('throws for null node', async () => {\n await expect(prepareClone(null)).rejects.toThrow();\n });\n it('returns a comment clone for unsupported node', async () => {\n const fake = document.createComment('not supported');\n const result = await prepareClone(fake);\n expect(result.clone.nodeType).toBe(Node.COMMENT_NODE);\n });\n it('handles error in internal logic', async () => {\n const el = document.createElement('div');\n vi.spyOn(el, 'cloneNode').mockImplementation(() => { throw new Error('fail'); });\n await expect(prepareClone(el)).rejects.toThrow('fail');\n });\n it('clones attributes and children', async () => {\n const el = document.createElement('div');\n el.setAttribute('data-test', '1');\n const result = await prepareClone(el);\n expect(result.clone.getAttribute('data-test')).toBe('1');\n });\n});\n"], ["/snapdom/__tests__/snapdom.backgroundColor.test.js", "import { describe, it, expect, beforeEach, afterEach } from 'vitest';\nimport { snapdom } from '../src/index';\n\ndescribe('snapdom.toJpg backgroundColor option', () => {\n let container;\n\n beforeEach(() => {\n container = document.createElement('div');\n container.style.width = '100px';\n container.style.height = '100px';\n container.style.background = 'transparent';\n document.body.appendChild(container);\n });\n\n it('applies white background by default', async () => {\n const img = await snapdom.toJpg(container );\n const canvas = document.createElement('canvas');\n canvas.width = img.width;\n canvas.height = img.height;\n const ctx = canvas.getContext('2d');\n ctx.drawImage(img, 0, 0);\n const pixel = ctx.getImageData(0, 0, 1, 1).data;\n // JPEG compresses, but for a solid color it should be near white\n expect(pixel[0]).toBeGreaterThan(240);\n expect(pixel[1]).toBeGreaterThan(240);\n expect(pixel[2]).toBeGreaterThan(240);\n });\n\n it('applies custom background color', async () => {\n const img = await snapdom.toJpg(container, { backgroundColor: '#00ff00' });\n const canvas = document.createElement('canvas');\n canvas.width = img.width;\n canvas.height = img.height;\n const ctx = canvas.getContext('2d');\n ctx.drawImage(img, 0, 0);\n const pixel = ctx.getImageData(0, 0, 1, 1).data;\n // Green check (JPEG lossy, so check near values)\n expect(pixel[0]).toBeLessThan(30); // red\n expect(pixel[1]).toBeGreaterThan(200); // green\n expect(pixel[2]).toBeLessThan(30); // blue\n });\n});\n"], ["/snapdom/__tests__/capture.core.test.js", "import { describe, it, expect, vi } from 'vitest';\nimport { captureDOM } from '../src/core/capture.js';\n\ndescribe('captureDOM edge cases', () => {\n it('throws for unsupported element (unknown nodeType)', async () => {\n // Simulate a node with an invalid nodeType\n const fakeNode = { nodeType: 999 };\n await expect(captureDOM(fakeNode)).rejects.toThrow();\n });\n\n it('throws if element is null', async () => {\n await expect(captureDOM(null)).rejects.toThrow();\n });\n\n it('throws error if getBoundingClientRect fails', async () => {\n const el = document.createElement('div');\n vi.spyOn(el, 'getBoundingClientRect').mockImplementation(() => { throw new Error('fail'); });\n await expect(captureDOM(el)).rejects.toThrow('fail');\n });\n});\n\ndescribe('captureDOM functional', () => {\n it('captures a simple div and returns an SVG dataURL', async () => {\n const el = document.createElement('div');\n el.textContent = 'test';\n const url = await captureDOM(el);\n expect(url.startsWith('data:image/svg+xml')).toBe(true);\n });\n\n it('supports scale and width/height options', async () => {\n const el = document.createElement('div');\n el.style.width = '100px';\n el.style.height = '50px';\n await captureDOM(el, { scale: 2 });\n await captureDOM(el, { width: 200 });\n await captureDOM(el, { height: 100 });\n });\n\n it('supports fast=false', async () => {\n const el = document.createElement('div');\n await captureDOM(el, { fast: false });\n });\n\n it('supports embedFonts', async () => {\n const el = document.createElement('div');\n await captureDOM(el, { embedFonts: true });\n });\n});\n"], ["/snapdom/__tests__/styles.module.test.js", "import { describe, it, expect } from 'vitest';\nimport { inlineAllStyles } from '../src/modules/styles.js';\nimport { cache } from '../src/core/cache.js';\n\ndescribe('inlineAllStyles', () => {\n it('adds a style key to the styleMap', () => {\n const el = document.createElement('div');\n const clone = document.createElement('div');\n inlineAllStyles(el, clone, false);\n expect(cache.preStyleMap.has(clone)).toBe(true);\n });\n});"], ["/snapdom/__tests__/snapdom.test.js", "import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';\nimport { snapdom } from '../src/index';\n\ndescribe('snapdom API', () => {\n let testElement;\n\n beforeEach(() => {\n testElement = document.createElement('div');\n testElement.style.width = '100px';\n testElement.style.height = '50px';\n document.body.appendChild(testElement );\n });\n\n afterEach(() => {\n document.body.removeChild(testElement );\n });\n\n describe('snapdom.toRaw', () => {\n it('should return a SVG data URL', async () => {\n const result = await snapdom.toRaw(testElement );\n expect(result).toMatch(/^data:image\\/svg\\+xml/);\n });\n });\n\n describe('snapdom', () => {\n it('toImg should return an HTMLImageElement', async () => {\n \n const img = await snapdom.toImg(testElement );\n expect(img).toBeInstanceOf(HTMLImageElement);\n expect(img.src).toMatch(/^data:image\\/svg\\+xml/);\n \n });\n\n it('toCanvas should return a HTMLCanvasElement', async () => {\n // const decodeMock = vi.spyOn(window.Image.prototype, 'decode').mockResolvedValue();\n const canvas = await snapdom.toCanvas(testElement );\n expect(canvas).toBeInstanceOf(HTMLCanvasElement);\n // decodeMock.mockRestore();\n });\n\n it('toPng should return an HTMLImageElement with PNG data URL', async () => {\n // const decodeMock = vi.spyOn(window.Image.prototype, 'decode').mockResolvedValue();\n const img = await snapdom.toPng(testElement );\n expect(img).toBeInstanceOf(HTMLImageElement);\n expect(img.src).toMatch(/^data:image\\/png/);\n // decodeMock.mockRestore();\n });\n\n it('toJpg should return an HTMLImageElement with JPEG data URL', async () => {\n // const decodeMock = vi.spyOn(window.Image.prototype, 'decode').mockResolvedValue();\n const img = await snapdom.toJpg(testElement );\n expect(img).toBeInstanceOf(HTMLImageElement);\n expect(img.src).toMatch(/^data:image\\/jpeg/);\n // decodeMock.mockRestore();\n });\n\n it('toWebp should return an HTMLImageElement with WebP data URL', async () => {\n // const decodeMock = vi.spyOn(window.Image.prototype, 'decode').mockResolvedValue();\n const img = await snapdom.toWebp(testElement );\n expect(img).toBeInstanceOf(HTMLImageElement);\n expect(img.src).toMatch(/^data:image\\/webp/);\n // decodeMock.mockRestore();\n });\n\n it('toBlob should return a Blob of type image/svg+xml', async () => {\n const blob = await snapdom.toBlob(testElement );\n expect(blob).toBeInstanceOf(Blob);\n expect(blob.type).toBe('image/svg+xml');\n });\n });\n});\n"], ["/snapdom/src/modules/styles.js", "import { getStyleKey } from '../utils/cssTools.js';\nimport { getStyle } from '../utils/helpers.js';\nimport {cache} from '../core/cache.js'\n\nfunction snapshotComputedStyleFull(style) {\n const result = {};\n for (let i = 0; i < style.length; i++) {\n const prop = style[i];\n let val = style.getPropertyValue(prop);\n\n // Opcional: evitar URLs externas que puedan romper renderizado\n if (\n (prop === 'background-image' || prop === 'content') &&\n val.includes('url(') &&\n !val.includes('data:')\n ) {\n val = 'none';\n }\n\n result[prop] = val;\n }\n return result;\n}\n\nexport function inlineAllStyles(source, clone, compress) {\n if (source.tagName === 'STYLE') return;\n\n if (!cache.preStyle.has(source)) {\n cache.preStyle.set(source, getStyle(source));\n }\n const style = cache.preStyle.get(source);\n\n if (!cache.snapshot.has(source)) {\n const snapshot = snapshotComputedStyleFull(style);\n cache.snapshot.set(source, snapshot);\n }\n\n const snapshot = cache.snapshot.get(source);\n\n const hash = Object.entries(snapshot)\n .sort(([a], [b]) => a.localeCompare(b))\n .map(([prop, val]) => `${prop}:${val}`)\n .join(';');\n\n if (cache.snapshotKey.has(hash)) {\n cache.preStyleMap.set(clone, cache.snapshotKey.get(hash));\n return;\n }\n\n const tagName = source.tagName?.toLowerCase() || 'div';\n const key = getStyleKey(snapshot, tagName, compress);\n\n cache.snapshotKey.set(hash, key);\n cache.preStyleMap.set(clone, key);\n}\n"], ["/snapdom/src/modules/pseudo.js", "/**\n * Utilities for inlining ::before and ::after pseudo-elements.\n * @module pseudo\n */\n\nimport { getStyle, snapshotComputedStyle, parseContent, extractURL, safeEncodeURI, fetchImage, inlineSingleBackgroundEntry, splitBackgroundImage } from '../utils/helpers.js';\nimport { getStyleKey } from '../utils/cssTools.js';\nimport { iconToImage } from '../modules/fonts.js';\nimport { isIconFont } from '../modules/iconFonts.js';\nimport { cache } from '../core/cache.js'\n\n/**\n * Creates elements to represent ::before, ::after, and ::first-letter pseudo-elements, inlining their styles and content.\n *\n * @param {Element} source - Original element\n * @param {Element} clone - Cloned element\n * @param {boolean} compress - Whether to compress style keys\n * @param {boolean} embedFonts - Whether to embed icon fonts as images\n * @returns {Promise} Promise that resolves when all pseudo-elements are processed\n */\n\nexport async function inlinePseudoElements(source, clone, compress, embedFonts = false, useProxy) {\n if (!(source instanceof Element) || !(clone instanceof Element)) return;\n for (const pseudo of [\"::before\", \"::after\", \"::first-letter\"]) {\n try {\n const style = getStyle(source, pseudo);\n if (!style || typeof style[Symbol.iterator] !== \"function\") continue;\n if (pseudo === \"::first-letter\") {\n const normal = getComputedStyle(source);\n const isMeaningful = style.color !== normal.color || style.fontSize !== normal.fontSize || style.fontWeight !== normal.fontWeight;\n if (!isMeaningful) continue;\n const textNode = Array.from(clone.childNodes).find(\n (n) => n.nodeType === Node.TEXT_NODE && n.textContent && n.textContent.trim().length > 0\n );\n if (!textNode) continue;\n const text = textNode.textContent;\n const match = text.match(/^([^\\p{L}\\p{N}\\s]*[\\p{L}\\p{N}](?:['’])?)/u);\n const first = match?.[0];\n const rest = text.slice(first?.length || 0);\n if (!first || /[\\uD800-\\uDFFF]/.test(first)) continue;\n const span = document.createElement(\"span\");\n span.textContent = first;\n span.dataset.snapdomPseudo = \"::first-letter\";\n const snapshot = snapshotComputedStyle(style);\n const key = getStyleKey(snapshot, \"span\", compress);\n cache.preStyleMap.set(span, key);\n const restNode = document.createTextNode(rest);\n clone.replaceChild(restNode, textNode);\n clone.insertBefore(span, restNode);\n continue;\n }\nconst content = style.getPropertyValue(\"content\");\nconst bg = style.getPropertyValue(\"background-image\");\nconst bgColor = style.getPropertyValue(\"background-color\");\n\nconst fontFamily = style.getPropertyValue(\"font-family\");\nconst fontSize = parseInt(style.getPropertyValue(\"font-size\")) || 32;\nconst fontWeight = parseInt(style.getPropertyValue(\"font-weight\")) || false;\nconst color = style.getPropertyValue(\"color\") || \"#000\";\nconst display = style.getPropertyValue(\"display\");\nconst width = parseFloat(style.getPropertyValue(\"width\"));\nconst height = parseFloat(style.getPropertyValue(\"height\"));\nconst borderStyle = style.getPropertyValue(\"border-style\");\nconst transform = style.getPropertyValue(\"transform\");\n\nconst isIconFont2 = isIconFont(fontFamily);\n\n// Detect counter() || counters()\nlet cleanContent;\nif (/counter\\s*\\(|counters\\s*\\(/.test(content)) {\n cleanContent = \"- \";\n} else {\n cleanContent = parseContent(content);\n}\n\nconst hasContent = content !== \"none\";\nconst hasExplicitContent = hasContent && cleanContent !== \"\";\nconst hasBg = bg && bg !== \"none\";\nconst hasBgColor = bgColor && bgColor !== \"transparent\" && bgColor !== \"rgba(0, 0, 0, 0)\";\nconst hasBox = display !== \"inline\" && (width > 0 || height > 0);\nconst hasBorder = borderStyle && borderStyle !== \"none\";\nconst hasTransform = transform && transform !== \"none\";\n\nconst shouldRender =\n hasExplicitContent || hasBg || hasBgColor || hasBox || hasBorder || hasTransform;\n\nif (!shouldRender) continue;\n\nconst pseudoEl = document.createElement(\"span\");\npseudoEl.dataset.snapdomPseudo = pseudo;\nconst snapshot = snapshotComputedStyle(style);\nconst key = getStyleKey(snapshot, \"span\", compress);\ncache.preStyleMap.set(pseudoEl, key);\n\nif (isIconFont2 && cleanContent.length === 1) {\n const imgEl = document.createElement(\"img\");\n imgEl.src = await iconToImage(cleanContent, fontFamily, fontWeight, fontSize, color);\n imgEl.style = `width:${fontSize}px;height:auto;object-fit:contain;`;\n pseudoEl.appendChild(imgEl);\n} else if (cleanContent.startsWith(\"url(\")) {\n const rawUrl = extractURL(cleanContent);\n if (rawUrl && rawUrl.trim() !== \"\") {\n try {\n const imgEl = document.createElement(\"img\");\n const dataUrl = await fetchImage(safeEncodeURI(rawUrl, { useProxy }));\n imgEl.src = dataUrl;\n imgEl.style = `width:${fontSize}px;height:auto;object-fit:contain;`;\n pseudoEl.appendChild(imgEl);\n } catch (e) {\n console.error(`[snapdom] Error in pseudo ${pseudo} for`, source, e);\n }\n }\n} else if (!isIconFont2 && hasExplicitContent) {\n pseudoEl.textContent = cleanContent;\n}\n\nif (hasBg) {\n try {\n const bgSplits = splitBackgroundImage(bg);\n const newBgParts = await Promise.all(\n bgSplits.map((entry) => inlineSingleBackgroundEntry(entry))\n );\n pseudoEl.style.backgroundImage = newBgParts.join(\", \");\n } catch (e) {\n console.warn(`[snapdom] Failed to inline background-image for ${pseudo}`, e);\n }\n}\n\nif (hasBgColor) pseudoEl.style.backgroundColor = bgColor;\n\nconst hasContent2 =\n pseudoEl.childNodes.length > 0 ||\n (pseudoEl.textContent && pseudoEl.textContent.trim() !== \"\");\nconst hasVisibleBox = hasContent2 || hasBg || hasBgColor || hasBox || hasBorder || hasTransform;\n\nif (!hasVisibleBox) continue;\n\npseudo === \"::before\"\n ? clone.insertBefore(pseudoEl, clone.firstChild)\n : clone.appendChild(pseudoEl);\n\n } catch (e) {\n console.warn(`[snapdom] Failed to capture ${pseudo} for`, source, e);\n }\n }\n const sChildren = Array.from(source.children);\n const cChildren = Array.from(clone.children).filter((child) => !child.dataset.snapdomPseudo);\n for (let i = 0; i < Math.min(sChildren.length, cChildren.length); i++) {\n await inlinePseudoElements(\n sChildren[i],\n cChildren[i],\n compress,\n embedFonts,\n useProxy\n );\n }\n}\n"], ["/snapdom/src/core/capture.js", "/**\n * Core logic for capturing DOM elements as SVG data URLs.\n * @module capture\n */\n\nimport { prepareClone } from './prepare.js';\nimport { inlineImages } from '../modules/images.js';\nimport { inlineBackgroundImages } from '../modules/background.js';\nimport { idle, isSafari } from '../utils/helpers.js';\nimport { collectUsedTagNames, generateDedupedBaseCSS } from '../utils/cssTools.js';\nimport { embedCustomFonts } from '../modules/fonts.js';\nimport { cache } from '../core/cache.js'\n\n/**\n * Captures an HTML element as an SVG data URL, inlining styles, images, backgrounds, and optionally fonts.\n *\n * @param {Element} element - DOM element to capture\n * @param {Object} [options={}] - Capture options\n * @param {boolean} [options.compress=true] - Whether to compress style keys\n * @param {boolean} [options.embedFonts=false] - Whether to embed custom fonts\n * @param {boolean} [options.fast=true] - Whether to skip idle delay for faster results\n * @param {number} [options.scale=1] - Output scale multiplier\n * @param {string[]} [options.exclude] - CSS selectors for elements to exclude\n * @param {Function} [options.filter] - Custom filter function \n * @returns {Promise} Promise that resolves to an SVG data URL\n */\n\nexport async function captureDOM(element, options = {}) {\n if (!element) throw new Error(\"Element cannot be null or undefined\");\n cache.reset()\n const { compress = true, embedFonts = false, fast = true, scale = 1, useProxy = ''} = options;\n let clone, classCSS;\n let fontsCSS = \"\";\n let baseCSS = \"\";\n let dataURL;\n let svgString;\n\n ({ clone, classCSS } = await prepareClone(element, compress, embedFonts, options));\n\n await new Promise((resolve) => {\n idle(async () => {\n await inlineImages(clone, options);\n resolve();\n }, { fast });\n });\n await new Promise((resolve) => {\n idle(async () => {\n await inlineBackgroundImages(element, clone, options);\n resolve();\n }, { fast });\n });\n if (embedFonts) {\n await new Promise((resolve) => {\n idle(async () => {\n fontsCSS = await embedCustomFonts();\n resolve();\n }, { fast });\n });\n }\n if (compress) {\n const usedTags = collectUsedTagNames(clone).sort();\n const tagKey = usedTags.join(\",\");\n if (cache.baseStyle.has(tagKey)) {\n baseCSS = cache.baseStyle.get(tagKey);\n } else {\n await new Promise((resolve) => {\n idle(() => {\n baseCSS = generateDedupedBaseCSS(usedTags);\n cache.baseStyle.set(tagKey, baseCSS);\n resolve();\n }, { fast });\n });\n }\n }\n await new Promise((resolve) => {\n idle(() => {\n const rect = element.getBoundingClientRect();\n let w = rect.width;\n let h = rect.height;\n const hasW = Number.isFinite(options.width);\n const hasH = Number.isFinite(options.height);\n const hasScale = typeof scale === \"number\" && scale !== 1;\n if (!hasScale) {\n const aspect = rect.width / rect.height;\n if (hasW && hasH) {\n w = options.width;\n h = options.height;\n } else if (hasW) {\n w = options.width;\n h = w / aspect;\n } else if (hasH) {\n h = options.height;\n w = h * aspect;\n }\n }\n w = Math.ceil(w);\n h = Math.ceil(h);\n clone.setAttribute(\"xmlns\", \"http://www.w3.org/1999/xhtml\");\n clone.style.transformOrigin = \"top left\";\n if (!hasScale && (hasW || hasH)) {\n const originalW = rect.width;\n const originalH = rect.height;\n const scaleX = w / originalW;\n const scaleY = h / originalH;\n const existingTransform = clone.style.transform || \"\";\n const scaleTransform = `scale(${scaleX}, ${scaleY})`;\n clone.style.transform = `${scaleTransform} ${existingTransform}`.trim();\n }\n const svgNS = \"http://www.w3.org/2000/svg\";\n const fo = document.createElementNS(svgNS, \"foreignObject\");\n fo.setAttribute(\"width\", \"100%\");\n fo.setAttribute(\"height\", \"100%\");\n const styleTag = document.createElement(\"style\");\n styleTag.textContent = baseCSS + fontsCSS + \"svg{overflow:visible;}\" + classCSS;\n fo.appendChild(styleTag);\n fo.appendChild(clone);\n const serializer = new XMLSerializer();\n const foString = serializer.serializeToString(fo);\n const svgHeader = ``;\n const svgFooter = \"\";\n svgString = svgHeader + foString + svgFooter;\n dataURL = `data:image/svg+xml;charset=utf-8,${encodeURIComponent(svgString)}`;\n resolve();\n }, { fast });\n });\n const sandbox = document.getElementById(\"snapdom-sandbox\");\n if (sandbox && sandbox.style.position === \"absolute\") sandbox.remove();\n return dataURL;\n}\n\n"], ["/snapdom/__tests__/pseudo.bg-inline-error.test.js", "vi.mock('../src/utils/helpers.js', async () => {\n const actual = await vi.importActual('../src/utils/helpers.js');\n return {\n ...actual,\n inlineSingleBackgroundEntry: vi.fn().mockRejectedValue(new Error('fail')),\n };\n});\n\nimport { describe, it, vi } from 'vitest';\nimport { inlinePseudoElements } from '../src/modules/pseudo.js';\n\ndescribe('inlinePseudoElements background-image inlining (error)', () => {\n it('cubre el catch de error en inlining de background-image en pseudo', async () => {\n const el = document.createElement('div');\n const clone = document.createElement('div');\n vi.spyOn(window, 'getComputedStyle').mockImplementation((_, pseudo) => {\n if (pseudo === '::before') return {\n getPropertyValue: (prop) => prop === 'content' ? 'none' : prop === 'font-family' ? 'Arial' : prop === 'font-size' ? '32' : prop === 'font-weight' ? '400' : prop === 'color' ? '#000' : prop === 'background-image' ? 'url(\"data:image/png;base64,abc\")' : prop === 'background-color' ? 'transparent' : '',\n color: '#000', fontSize: '32px', fontWeight: '400', fontFamily: 'Arial',\n };\n return { getPropertyValue: () => '', color: '', fontSize: '', fontWeight: '', fontFamily: '' };\n });\n await inlinePseudoElements(el, clone, new Map(), new WeakMap(), false);\n window.getComputedStyle.mockRestore();\n });\n});\n"], ["/snapdom/__tests__/pseudo.bg-inline-success.test.js", "vi.mock('../src/utils/helpers.js', async () => {\n const actual = await vi.importActual('../src/utils/helpers.js');\n return {\n ...actual,\n inlineSingleBackgroundEntry: vi.fn().mockResolvedValue('url(\"data:image/png;base64,abc\")'),\n };\n});\n\nimport { describe, it, vi } from 'vitest';\nimport { inlinePseudoElements } from '../src/modules/pseudo.js';\n\ndescribe('inlinePseudoElements background-image inlining (success)', () => {\n it('cubre el inlining exitoso de background-image en pseudo', async () => {\n const el = document.createElement('div');\n const clone = document.createElement('div');\n vi.spyOn(window, 'getComputedStyle').mockImplementation((_, pseudo) => {\n if (pseudo === '::before') return {\n getPropertyValue: (prop) => prop === 'content' ? 'none' : prop === 'font-family' ? 'Arial' : prop === 'font-size' ? '32' : prop === 'font-weight' ? '400' : prop === 'color' ? '#000' : prop === 'background-image' ? 'url(\"data:image/png;base64,abc\")' : prop === 'background-color' ? 'transparent' : '',\n color: '#000', fontSize: '32px', fontWeight: '400', fontFamily: 'Arial',\n };\n return { getPropertyValue: () => '', color: '', fontSize: '', fontWeight: '', fontFamily: '' };\n });\n await inlinePseudoElements(el, clone, new Map(), new WeakMap(), false);\n window.getComputedStyle.mockRestore();\n });\n});\n"], ["/snapdom/__tests__/snapdom.attributes.test.js", "import { describe, it, expect, beforeEach, afterEach } from 'vitest';\nimport { snapdom } from '../src/index';\n\ndescribe('snapdom capture attributes', () => {\n let container;\n\n beforeEach(() => {\n container = document.createElement('div');\n container.style.width = '300px';\n container.style.height = '150px';\n document.body.appendChild(container);\n });\n\n afterEach(() => {\n document.body.removeChild(container);\n });\n\n it('should exclude elements with data-capture=\"exclude\"', async () => {\n const excluded = document.createElement('div');\n excluded.setAttribute('data-capture', 'exclude');\n excluded.textContent = 'Should be excluded';\n container.appendChild(excluded);\n\n const svgDataUrl = await snapdom.toRaw(container);\n const svgText = decodeURIComponent(svgDataUrl.split(',')[1]);\n \n expect(svgText).not.toContain('Should be excluded');\n });\n\n it('should replace elements with data-capture=\"placeholder\" and show placeholder text', async () => {\n const placeholder = document.createElement('div');\n placeholder.setAttribute('data-capture', 'placeholder');\n placeholder.setAttribute('data-placeholder-text', 'Placeholder here');\n placeholder.textContent = 'Original text';\n container.appendChild(placeholder);\n\n const svgDataUrl = await snapdom.toRaw(container);\n const svgText = decodeURIComponent(svgDataUrl.split(',')[1]);\n \n expect(svgText).toContain('Placeholder here');\n expect(svgText).not.toContain('Original text');\n });\n});\n"], ["/snapdom/__tests__/images.module.test.js", "import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';\nimport { inlineImages } from '../src/modules/images.js';\n\ndescribe('inlineImages', () => {\n let container;\n beforeEach(() => {\n container = document.createElement('div');\n document.body.appendChild(container);\n });\n afterEach(() => {\n document.body.removeChild(container);\n });\n\n it('converts to dataURL if the image loads', async () => {\n const img = document.createElement('img');\n img.src = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/w8AAn8B9p6Q2wAAAABJRU5ErkJggg==';\n container.appendChild(img);\n await inlineImages(container);\n expect(img.src.startsWith('data:image/')).toBe(true);\n });\n\n it('replaces with a fallback if the image fails', async () => {\n const img = document.createElement('img');\n img.src = 'invalid-url.png';\n container.appendChild(img);\n await inlineImages(container);\n expect(container.querySelector('div')).not.toBeNull();\n expect(container.querySelector('img')).toBeNull();\n });\n});\n"], ["/snapdom/__tests__/snapdom.precache.test.js", "import { describe, test, expect, afterEach, afterAll, beforeEach } from 'vitest';\nimport { snapdom, preCache } from '../src/index';\nimport { cache } from '../src/core/cache';\n\nconst sizes = [\n { width: 200, height: 100, label: 'Small element (200x100)' },\n { width: 400, height: 300, label: 'Modal size (400x300)' },\n { width: 1200, height: 800, label: 'Page view (1200x800)' },\n];\nlet results = [];\nfunction createContainer(size) {\n const container = document.createElement('div');\n container.style.width = `${size.width}px`;\n container.style.height = `${size.height}px`;\n container.style.padding = '20px';\n container.style.overflow = 'auto';\n container.style.background = 'white';\n container.style.border = '2px solid black';\n container.style.fontFamily = 'Arial, sans-serif';\n container.style.color = '#333';\n container.style.position = 'relative';\n\n const grid = document.createElement('div');\n grid.style.display = 'grid';\n grid.style.gridTemplateColumns = 'repeat(auto-fill, minmax(120px, 1fr))';\n grid.style.gap = '10px';\n\n const cardCount = Math.floor((size.width * size.height) / 20000);\n for (let i = 0; i < cardCount; i++) {\n const card = document.createElement('div');\n card.style.padding = '10px';\n card.style.borderRadius = '8px';\n card.style.background = i % 2 === 0 ? '#f0f0f0' : '#e0eaff';\n card.style.boxShadow = '0 2px 5px rgba(0,0,0,0.1)';\n card.style.display = 'flex';\n card.style.flexDirection = 'column';\n card.style.alignItems = 'center';\n\n const title = document.createElement('h3');\n title.textContent = `Card ${i + 1}`;\n title.style.margin = '0 0 10px 0';\n title.style.fontSize = '14px';\n\n const icon = document.createElement('div');\n icon.style.width = '30px';\n icon.style.height = '30px';\n icon.style.borderRadius = '50%';\n icon.style.background = i % 2 === 0 ? 'red' : 'blue';\n icon.style.marginBottom = '10px';\n\n const text = document.createElement('p');\n text.textContent = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit.';\n text.style.fontSize = '12px';\n text.style.textAlign = 'center';\n\n card.appendChild(icon);\n card.appendChild(title);\n card.appendChild(text);\n grid.appendChild(card);\n }\n\n container.appendChild(grid);\n return container;\n}\n\nfunction waitForNextFrame() {\n return new Promise((resolve) => {\n requestAnimationFrame(() => setTimeout(resolve, 0));\n });\n}\nbeforeEach(() => {\n cache.image.clear();\n cache.background.clear();\n cache.resource.clear();\n});\nafterAll(() => {\n for (const r of results) {\n console.log(r.log);\n }\n results = [];\n \n document.body.innerHTML = '';\n});\nfor (const size of sizes) {\n describe(`snapDOM performance test (may not be accurate) - ${size.label}`, () => {\n let container;\n\n afterEach( () => {\n container?.remove();\n container = null;\n document.body.innerHTML = '';\n \n });\n\n test('without preCache', async () => {\n container = createContainer(size);\n document.body.appendChild(container);\n await waitForNextFrame();\n\n const start = performance.now();\n await snapdom.toRaw(container, { compress: true });\n const end = performance.now();\n\n let log = `[${size.label}] WITHOUT preCache: capture ${(end - start).toFixed(2)}ms`;\n results.push({ log });\n expect(true).toBe(true);\n \n });\n \n test('with preCache', async () => {\n container = createContainer(size);\n document.body.appendChild(container);\n await waitForNextFrame();\n\n const startPre = performance.now();\n await preCache();\n const endPre = performance.now();\n \n const startCap = performance.now();\n await snapdom.toRaw(container, { compress: true });\n const endCap = performance.now();\n \n const precacheTime = (endPre - startPre).toFixed(2);\n const captureTime = (endCap - startCap).toFixed(2);\n \n let log = `[${size.label}] WITH preCache: capture ${captureTime}ms (preCache ${precacheTime}ms) `;\n\n results.push({ log });\n \n expect(true).toBe(true);\n });\n\n });\n}\n"], ["/snapdom/__tests__/snapdom.vs.htm2canvas.outputfilesize.test.js", "import { describe, it, beforeEach, afterEach, afterAll } from 'vitest';\nimport { snapdom } from '../src/index';\n//ok\n\ndescribe('Output file size snapdom vs html2canvas (cdn with averaging)', () => {\n let container;\n let html2canvas;\n let report;\n\n beforeEach(async () => {\n container = document.createElement('div');\n container.style.width = '400px';\n container.style.height = '300px';\n container.style.background = 'linear-gradient(to right, red, blue)';\n container.innerHTML = '

Hello Benchmark

Testing multiple runs...

';\n document.body.appendChild(container);\n\n if (!html2canvas) {\n // Cargar html2canvas desde CDN\n await new Promise((resolve, reject) => {\n const script = document.createElement('script');\n script.src = 'https://cdn.jsdelivr.net/npm/html2canvas@1.4.1/dist/html2canvas.min.js';\n script.onload = () => {\n html2canvas = window.html2canvas;\n resolve();\n };\n script.onerror = reject;\n document.head.appendChild(script);\n });\n }\n });\n\n afterEach(() => {\n document.body.removeChild(container);\n });\n\n afterAll(() => {\n console.log(report)\n })\n\n it('snapdom output file size should be smaller than html2canvas', async () => {\n \n // SnapDOM capture\n const snapdomDataURL = await snapdom.toRaw(container, {compress: true});\n const snapdomSizeKB = (snapdomDataURL.length * 3 / 4) / 1024; // Base64 to bytes approx\n \n // html2canvas capture\n const canvas = await html2canvas(container, { logging: false });\n const html2canvasDataURL = await canvas.toDataURL();\n const html2canvasSizeKB = (html2canvasDataURL.length * 3 / 4) / 1024; // Base64 to bytes approx\n \n const differencePercent = ((html2canvasSizeKB - snapdomSizeKB) / html2canvasSizeKB) * 100;\n\n report =`snapDom Captured file size is ${differencePercent.toFixed(2)}% smaller compared to html2canvas (${snapdomSizeKB.toFixed(2)} KB vs. ${html2canvasSizeKB.toFixed(2)} KB)`\n\n})\n\n})\n"], ["/snapdom/__tests__/background.module.test.js", "import { describe, it, expect, beforeEach, afterEach } from 'vitest';\nimport { inlineBackgroundImages } from '../src/modules/background.js';\n\ndescribe('inlineBackgroundImages', () => {\n let source, clone;\n beforeEach(() => {\n source = document.createElement('div');\n clone = document.createElement('div');\n document.body.appendChild(source);\n document.body.appendChild(clone);\n });\n afterEach(() => {\n document.body.removeChild(source);\n document.body.removeChild(clone);\n });\n\n it('does not fail if there is no background-image', async () => {\n source.style.background = 'none';\n await expect(inlineBackgroundImages(source, clone, new WeakMap())).resolves.toBeUndefined();\n });\n\n it('processes a valid background-image', async () => {\n source.style.backgroundImage = 'url(\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/w8AAn8B9p6Q2wAAAABJRU5ErkJggg==\")';\n await expect(inlineBackgroundImages(source, clone, new WeakMap())).resolves.toBeUndefined();\n });\n});\n"], ["/snapdom/__tests__/snapdom.vs.modernscreenshot.outputfilesize.test.js", "import { describe, it, beforeEach, afterEach, afterAll } from 'vitest';\nimport { domToDataUrl} from 'https://unpkg.com/modern-screenshot';\nimport { snapdom } from '../src/index';\n//ok\n\ndescribe('Output file size snapdom vs modern-screeenshot (cdn with averaging)', () => {\n let container;\n\n let report;\n\n beforeEach(async () => {\n container = document.createElement('div');\n container.style.width = '400px';\n container.style.height = '300px';\n container.style.background = 'linear-gradient(to right, red, blue)';\n container.innerHTML = '

Hello Benchmark

Testing multiple runs...

';\n document.body.appendChild(container);\n });\n\n afterEach(() => {\n document.body.removeChild(container);\n });\n\n afterAll(() => {\n console.log(report)\n })\n\n it('snapdom output file size should be smaller than modern-screenshot', async () => {\n \n // SnapDOM capture\n const snapdomDataURL = await snapdom.toRaw(container, {compress: true});\n const snapdomSizeKB = (snapdomDataURL.length * 3 / 4) / 1024; // Base64 to bytes approx\n \n // domToDataUrl capture\n const domToDataUrlDataURL = await domToDataUrl(container);\n const domToDataUrlSizeKB = (domToDataUrlDataURL.length * 3 / 4) / 1024; // Base64 to bytes approx\n \n const differencePercent = ((domToDataUrlSizeKB - snapdomSizeKB) / domToDataUrlSizeKB) * 100;\n\n report =`snapdom captured file size is ${differencePercent.toFixed(2)}% smaller compared to modern-screenshot (${snapdomSizeKB.toFixed(2)} KB vs. ${domToDataUrlSizeKB.toFixed(2)} KB)`\n\n})\n\n})\n"], ["/snapdom/__tests__/snapdom.complex.benchmark.js", "import { bench, describe, beforeEach, afterEach } from 'vitest';\nimport { domToDataUrl } from 'https://unpkg.com/modern-screenshot';\nimport * as htmlToImage from 'https://cdn.jsdelivr.net/npm/html-to-image@1.11.13/+esm';\nimport { snapdom as sd } from 'https://cdn.jsdelivr.net/npm/@zumer/snapdom@1.8.0/dist/snapdom.mjs';\nimport { snapdom } from '../src/index';\n\nlet html2canvasLoaded = false;\n\nasync function loadHtml2Canvas() {\n if (html2canvasLoaded) return;\n await new Promise((resolve, reject) => {\n const script = document.createElement('script');\n script.src = 'https://cdn.jsdelivr.net/npm/html2canvas@1.4.1/dist/html2canvas.min.js';\n script.onload = () => resolve();\n script.onerror = reject;\n document.head.appendChild(script);\n });\n html2canvasLoaded = true;\n}\n\nawait loadHtml2Canvas();\n\nconst sizes = [\n { width: 200, height: 100, label: 'Small element (200x100)' },\n { width: 400, height: 300, label: 'Modal size (400x300)' },\n { width: 1200, height: 800, label: 'Page view (1200x800)' },\n { width: 2000, height: 1500, label: 'Large scroll area (2000x1500)' },\n { width: 4000, height: 2000, label: 'Very large element (4000x2000)' },\n];\n\nfor (const size of sizes) {\n describe(`Benchmark complex node at ${size.label}`, () => {\n let container;\n\n async function setupContainer() {\n if (container && document.body.contains(container)) return;\n \n container = document.createElement('div');\n container.style.width = `${size.width}px`;\n container.style.height = `${size.height}px`;\n container.style.padding = '20px';\n container.style.overflow = 'auto';\n container.style.background = 'white';\n container.style.border = '2px solid black';\n container.style.fontFamily = 'Arial, sans-serif';\n container.style.color = '#333';\n container.style.position = 'relative';\n \n const grid = document.createElement('div');\n grid.style.display = 'grid';\n grid.style.gridTemplateColumns = 'repeat(auto-fill, minmax(120px, 1fr))';\n grid.style.gap = '10px';\n \n for (let i = 0; i < Math.floor((size.width * size.height) / 20000); i++) {\n const card = document.createElement('div');\n card.style.padding = '10px';\n card.style.borderRadius = '8px';\n card.style.background = i % 2 === 0 ? '#f0f0f0' : '#e0eaff';\n card.style.boxShadow = '0 2px 5px rgba(0,0,0,0.1)';\n card.style.display = 'flex';\n card.style.flexDirection = 'column';\n card.style.alignItems = 'center';\n \n const title = document.createElement('h3');\n title.textContent = `Card ${i + 1}`;\n title.style.margin = '0 0 10px 0';\n title.style.fontSize = '14px';\n \n const icon = document.createElement('div');\n icon.style.width = '30px';\n icon.style.height = '30px';\n icon.style.borderRadius = '50%';\n icon.style.background = i % 2 === 0 ? 'red' : 'blue';\n icon.style.marginBottom = '10px';\n \n const text = document.createElement('p');\n text.textContent = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit.';\n text.style.fontSize = '12px';\n text.style.textAlign = 'center';\n \n card.appendChild(icon);\n card.appendChild(title);\n card.appendChild(text);\n grid.appendChild(card);\n }\n \n container.appendChild(grid);\n document.body.appendChild(container);\n \n }\n \n afterEach (async () => {\n if (container) {\n container.remove();\n container = null;\n }\n \n document.body.innerHTML = ''\n });\n\n bench('snapDOM current version', async () => {\n await setupContainer();\n await snapdom.toRaw(container, {compress: true, fast: true});\n });\n\n bench('snapDOM V1.8.0', async () => {\n await setupContainer();\n await sd.toRaw(container);\n });\n \n bench('html2canvas capture', async () => {\n await setupContainer();\n const canvas = await window.html2canvas(container, { logging: false, scale: 1 });\n await canvas.toDataURL();\n });\n\n bench('modern-screenshot capture', async () => {\n await setupContainer();\n await domToDataUrl(container);\n });\n bench('html-to-image capture', async () => {\n await setupContainer();\n await htmlToImage.toSvg(container);\n });\n });\n}\n"], ["/snapdom/__tests__/snapdom.benchmark.js", "import { bench, describe, beforeEach, afterEach } from 'vitest';\nimport { domToDataUrl } from 'https://unpkg.com/modern-screenshot';\nimport * as htmlToImage from 'https://cdn.jsdelivr.net/npm/html-to-image@1.11.13/+esm';\n//import { toPng, toJpeg, toBlob, toPixelData, toSvg } from 'https://cdn.jsdelivr.net/npm/html-to-image@1.11.13/dist/html-to-image.min.js';\nimport { snapdom as sd } from 'https://cdn.jsdelivr.net/npm/@zumer/snapdom@1.8.0/dist/snapdom.mjs';\nimport { snapdom } from '../src/index';\n\n\nlet html2canvasLoaded = false;\n\nasync function loadHtml2Canvas() {\n if (html2canvasLoaded) return;\n await new Promise((resolve, reject) => {\n const script = document.createElement('script');\n script.src = 'https://cdn.jsdelivr.net/npm/html2canvas@1.4.1/dist/html2canvas.min.js';\n script.onload = () => resolve();\n script.onerror = reject;\n document.head.appendChild(script);\n });\n html2canvasLoaded = true;\n}\n\nawait loadHtml2Canvas();\n\n\n\nconst sizes = [\n { width: 200, height: 100, label: 'Small element (200x100)' },\n { width: 400, height: 300, label: 'Modal size (400x300)' },\n { width: 1200, height: 800, label: 'Page view (1200x800)' },\n { width: 2000, height: 1500, label: 'Large scroll area (2000x1500)' },\n { width: 4000, height: 2000, label: 'Very large element (4000x2000)' },\n];\n\nfor (const size of sizes) {\n describe(`Benchmark simple node at ${size.label}`, () => {\n let container;\n\n async function setupContainer() { \n if (container && document.body.contains(container)) {\n return;\n }\n container = document.createElement('div');\n container.style.width = `${size.width}px`;\n container.style.height = `${size.height}px`;\n container.style.background = 'linear-gradient(to right, red, blue)';\n container.style.fontFamily = 'Arial, sans-serif';\n container.style.display = 'flex';\n container.style.alignItems = 'center';\n container.style.justifyContent = 'center';\n container.style.fontSize = '24px';\n container.innerHTML = `

${size.label}

`;\n document.body.appendChild(container);\n } \n\n /* async function setupContainer() {\n if (container && document.body.contains(container)) return;\n \n container = document.createElement('div');\n container.style.width = `${size.width}px`;\n container.style.height = `${size.height}px`;\n container.style.padding = '20px';\n container.style.overflow = 'auto';\n container.style.background = 'white';\n container.style.border = '2px solid black';\n container.style.fontFamily = 'Arial, sans-serif';\n container.style.color = '#333';\n container.style.position = 'relative';\n \n const grid = document.createElement('div');\n grid.style.display = 'grid';\n grid.style.gridTemplateColumns = 'repeat(auto-fill, minmax(120px, 1fr))';\n grid.style.gap = '10px';\n \n for (let i = 0; i < Math.floor((size.width * size.height) / 20000); i++) {\n const card = document.createElement('div');\n card.style.padding = '10px';\n card.style.borderRadius = '8px';\n card.style.background = i % 2 === 0 ? '#f0f0f0' : '#e0eaff';\n card.style.boxShadow = '0 2px 5px rgba(0,0,0,0.1)';\n card.style.display = 'flex';\n card.style.flexDirection = 'column';\n card.style.alignItems = 'center';\n \n const title = document.createElement('h3');\n title.textContent = `Card ${i + 1}`;\n title.style.margin = '0 0 10px 0';\n title.style.fontSize = '14px';\n \n const icon = document.createElement('div');\n icon.style.width = '30px';\n icon.style.height = '30px';\n icon.style.borderRadius = '50%';\n icon.style.background = i % 2 === 0 ? 'red' : 'blue';\n icon.style.marginBottom = '10px';\n \n const text = document.createElement('p');\n text.textContent = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit.';\n text.style.fontSize = '12px';\n text.style.textAlign = 'center';\n \n card.appendChild(icon);\n card.appendChild(title);\n card.appendChild(text);\n grid.appendChild(card);\n }\n \n container.appendChild(grid);\n document.body.appendChild(container);\n }\n */\n afterEach(() => {\n if (container) {\n container.remove();\n container = null;\n }\n });\n\n bench('snapDOM current version', async () => {\n await setupContainer();\n await snapdom.toRaw(container);\n });\n\n bench('snapDOM V1.8.0', async () => {\n await setupContainer();\n await sd.toRaw(container);\n });\n\n bench('html2canvas capture', async () => {\n await setupContainer();\n const canvas = await window.html2canvas(container, { logging: false, scale: 1 });\n await canvas.toDataURL();\n });\n\n bench('modern-screenshot capture', async () => {\n await setupContainer();\n await domToDataUrl(container);\n });\n\n bench('html-to-image capture', async () => {\n await setupContainer();\n await htmlToImage.toSvg(container);\n });\n });\n}\n"], ["/snapdom/src/utils/helpers.js", "import { cache } from \"../core/cache\";\n\n/**\n * Fetches and inlines a single background-image entry to a data URL (with caching).\n * - If entry is a gradient or \"none\", returns unchanged.\n * - If entry is a url(...), fetches the image as data URL and caches it.\n *\n * @param {string} entry - Single background-image entry (e.g., \"url(...)\").\n * @param {Object} [options={}] - Options like crossOrigin.\n * @param {boolean} [options.skipInline=false] - If true, only fetches & caches, doesn't return a replacement.\n * @returns {Promise} - The processed entry (unless skipInline is true).\n */\nexport async function inlineSingleBackgroundEntry(entry, options = {}) {\n const rawUrl = extractURL(entry)\n\n const isGradient = /^((repeating-)?(linear|radial|conic)-gradient)\\(/i.test(entry);\n \n if (rawUrl) {\n const encodedUrl = safeEncodeURI(rawUrl);\n if (cache.background.has(encodedUrl)) {\n return options.skipInline ? void 0 : `url(${cache.background.get(encodedUrl)})`;\n } else {\n const dataUrl = await fetchImage(encodedUrl, { useProxy: options.useProxy });\n cache.background.set(encodedUrl, dataUrl);\n return options.skipInline ? void 0 : `url(\"${dataUrl}\")`;\n }\n }\n\n if (isGradient || entry === \"none\") {\n return entry;\n }\n\n return entry;\n}\n\n\n/**\n * Creates a promise that resolves after the specified delay\n * @param {number} [ms=0] - Milliseconds to delay\n * @returns {Promise} Promise that resolves after the delay\n */\n\nexport function idle(fn, { fast = false } = {}) {\n if (fast) return fn();\n if ('requestIdleCallback' in window) {\n requestIdleCallback(fn, { timeout: 50 });\n } else {\n setTimeout(fn, 1);\n }\n}\n/**\n * Gets the computed style for an element or pseudo-element, with caching.\n *\n * @param {Element} el - The element\n * @param {string|null} [pseudo=null] - The pseudo-element\n * @returns {CSSStyleDeclaration} The computed style\n */\nexport function getStyle(el, pseudo = null) {\n if (!(el instanceof Element)) {\n return window.getComputedStyle(el, pseudo);\n }\n\n let map = cache.computedStyle.get(el);\n if (!map) {\n map = new Map();\n cache.computedStyle.set(el, map);\n }\n\n if (!map.has(pseudo)) {\n const st = window.getComputedStyle(el, pseudo);\n map.set(pseudo, st);\n }\n\n return map.get(pseudo);\n}\n/**\n * Parses the CSS content property value, handling unicode escapes.\n *\n * @param {string} content - The CSS content value\n * @returns {string} The parsed content\n */\nexport function parseContent(content) {\n let clean = content.replace(/^['\"]|['\"]$/g, \"\");\n if (clean.startsWith(\"\\\\\")) {\n try {\n return String.fromCharCode(parseInt(clean.replace(\"\\\\\", \"\"), 16));\n } catch {\n return clean;\n }\n }\n return clean;\n}\n/**\n * Extracts a URL from a CSS value like background-image.\n *\n * @param {string} value - The CSS value\n * @returns {string|null} The extracted URL or null\n */\n\nexport function extractURL(value) {\n const match = value.match(/url\\((['\"]?)(.*?)(\\1)\\)/);\n if (!match) return null;\n\n const url = match[2].trim();\n if (url.startsWith('#')) return null;\n return url;\n}\n\n/**\n * Determines if a font family or URL is an icon font.\n *\n * @param {string} familyOrUrl - The font family or URL\n * @returns {boolean} True if it is an icon font\n */\nexport function isIconFont(familyOrUrl) {\n const iconFontPatterns = [\n /font\\s*awesome/i,\n /material\\s*icons/i,\n /ionicons/i,\n /glyphicons/i,\n /feather/i,\n /bootstrap\\s*icons/i,\n /remix\\s*icons/i,\n /heroicons/i,\n /layui/i,\n /lucide/i\n ];\n return iconFontPatterns.some(rx => rx.test(familyOrUrl));\n}\n/**\n *\n *\n * @export\n * @param {*} src\n * @param {number} [timeout=3000]\n * @return {*} \n */\n\nexport function fetchImage(src, { timeout = 3000, useProxy = '' } = {}) {\n function getCrossOriginMode(url) {\n try {\n const parsed = new URL(url, window.location.href);\n return parsed.origin === window.location.origin ? \"use-credentials\" : \"anonymous\";\n } catch {\n return \"anonymous\";\n }\n }\n\n // Función común para fallback vía fetch + proxy\n async function fetchWithFallback(url) {\n const fetchBlobAsDataURL = (fetchUrl) =>\n fetch(fetchUrl, {\n mode: \"cors\",\n credentials: getCrossOriginMode(fetchUrl) === \"use-credentials\" ? \"include\" : \"omit\",\n })\n .then(r => r.blob())\n .then(blob => new Promise((resolve, reject) => {\n const reader = new FileReader();\n reader.onloadend = () => {\n const base64 = reader.result;\n if (typeof base64 !== \"string\" || !base64.startsWith(\"data:image/\")) {\n reject(new Error(\"Invalid image data URL\"));\n return;\n }\n resolve(base64);\n };\n reader.onerror = () => reject(new Error(\"FileReader error\"));\n reader.readAsDataURL(blob);\n }));\n\n try {\n return await fetchBlobAsDataURL(url);\n } catch (e) {\n if (useProxy && typeof useProxy === \"string\") {\n const proxied = useProxy.replace(/\\/$/, \"\") + safeEncodeURI(url);\n try {\n return await fetchBlobAsDataURL(proxied);\n } catch {\n \n throw new Error(\"[SnapDOM - fetchImage] CORS restrictions prevented image capture (even via proxy)\");\n }\n } else {\n \n throw new Error(\"[SnapDOM - fetchImage] Fetch fallback failed and no proxy provided\");\n }\n }\n }\n\n const crossOriginValue = getCrossOriginMode(src);\n\n if (cache.image.has(src)) {\n return Promise.resolve(cache.image.get(src));\n }\n\n // Detectamos si es un data URI, si sí, devolvemos directo sin fetch\n const isDataURI = src.startsWith(\"data:image/\");\n if (isDataURI) {\n cache.image.set(src, src);\n return Promise.resolve(src);\n }\n\n // Mejor detección SVG, incluyendo query strings\n const isSVG = /\\.svg(\\?.*)?$/i.test(src);\n\n if (isSVG) {\n return (async () => {\n try {\n const response = await fetch(src, {\n mode: \"cors\",\n credentials: crossOriginValue === \"use-credentials\" ? \"include\" : \"omit\"\n });\n const svgText = await response.text();\n const encoded = `data:image/svg+xml;charset=utf-8,${encodeURIComponent(svgText)}`;\n cache.image.set(src, encoded);\n return encoded;\n } catch {\n return fetchWithFallback(src);\n }\n })();\n }\n\n return new Promise((resolve, reject) => {\n const timeoutId = setTimeout(() => {\n reject(new Error(\"[SnapDOM - fetchImage] Image load timed out\"));\n }, timeout);\n\n const image = new Image();\n image.crossOrigin = crossOriginValue;\n\n image.onload = async () => {\n clearTimeout(timeoutId);\n try {\n await image.decode();\n const canvas = document.createElement(\"canvas\");\n canvas.width = image.width;\n canvas.height = image.height;\n const ctx = canvas.getContext(\"2d\");\n ctx.drawImage(image, 0, 0, canvas.width, canvas.height);\n const dataURL = canvas.toDataURL(\"image/png\");\n cache.image.set(src, dataURL);\n resolve(dataURL);\n } catch {\n try {\n const fallbackDataURL = await fetchWithFallback(src);\n cache.image.set(src, fallbackDataURL);\n resolve(fallbackDataURL);\n } catch (e) {\n reject(e);\n }\n }\n };\n\n image.onerror = async () => {\n clearTimeout(timeoutId);\n console.error(`[SnapDOM - fetchImage] Image failed to load: ${src}`);\n try {\n const fallbackDataURL = await fetchWithFallback(src);\n cache.image.set(src, fallbackDataURL);\n resolve(fallbackDataURL);\n } catch (e) {\n reject(e);\n }\n };\n\n image.src = src;\n });\n}\n\n/**\n *\n *\n * @export\n * @param {*} style\n * @return {*} \n */\nexport function snapshotComputedStyle(style) {\n const snap = {};\n for (let prop of style) {\n snap[prop] = style.getPropertyValue(prop);\n }\n return snap;\n}\n\nexport function isSafari() {\n return /^((?!chrome|android).)*safari/i.test(navigator.userAgent);\n}\n\nexport function stripTranslate(transform) {\n if (!transform || transform === 'none') return '';\n\n let cleaned = transform.replace(/translate[XY]?\\([^)]*\\)/g, '');\n\n cleaned = cleaned.replace(/matrix\\(([^)]+)\\)/g, (_, values) => {\n const parts = values.split(',').map(s => s.trim());\n if (parts.length !== 6) return `matrix(${values})`;\n parts[4] = '0';\n parts[5] = '0';\n return `matrix(${parts.join(', ')})`;\n });\n\n cleaned = cleaned.replace(/matrix3d\\(([^)]+)\\)/g, (_, values) => {\n const parts = values.split(',').map(s => s.trim());\n if (parts.length !== 16) return `matrix3d(${values})`;\n parts[12] = '0';\n parts[13] = '0';\n return `matrix3d(${parts.join(', ')})`;\n });\n\n return cleaned.trim().replace(/\\s{2,}/g, ' ');\n}\n\nexport function safeEncodeURI(uri) {\n if (/%[0-9A-Fa-f]{2}/.test(uri)) return uri; // prevent reencode\n try {\n return encodeURI(uri);\n } catch {\n return uri;\n }\n}\n\nexport function splitBackgroundImage(bg) {\n const parts = [];\n let depth = 0;\n let lastIndex = 0;\n for (let i = 0; i < bg.length; i++) {\n const char = bg[i];\n if (char === '(') depth++;\n if (char === ')') depth--;\n if (char === ',' && depth === 0) {\n parts.push(bg.slice(lastIndex, i).trim());\n lastIndex = i + 1;\n }\n }\n parts.push(bg.slice(lastIndex).trim());\n return parts;\n}\n\n"], ["/snapdom/src/modules/fonts.js", "/**\n * Utilities for handling and embedding web fonts and icon fonts.\n * @module fonts\n */\n\nimport { extractURL} from \"../utils/helpers\"\nimport { cache } from \"../core/cache\"\nimport { isIconFont } from '../modules/iconFonts.js';\n\n/**\n * Converts a unicode character from an icon font into a data URL image.\n *\n * @export\n * @param {string} unicodeChar - The unicode character to render\n * @param {string} fontFamily - The font family name\n * @param {string|number} fontWeight - The font weight\n * @param {number} [fontSize=32] - The font size in pixels\n * @param {string} [color=\"#000\"] - The color to use\n * @returns {Promise} Data URL of the rendered icon\n */\n\nexport async function iconToImage(unicodeChar, fontFamily, fontWeight, fontSize = 32, color = \"#000\") {\n fontFamily = fontFamily.replace(/^['\"]+|['\"]+$/g, \"\");\n const dpr = window.devicePixelRatio || 1;\n\n // Create temporary context to measure\n const tempCanvas = document.createElement(\"canvas\");\n const tempCtx = tempCanvas.getContext(\"2d\");\n tempCtx.font = fontWeight\n ? `${fontWeight} ${fontSize}px \"${fontFamily}\"`\n : `${fontSize}px \"${fontFamily}\"`;\n\n const metrics = tempCtx.measureText(unicodeChar);\n const ascent = metrics.actualBoundingBoxAscent || fontSize * 0.8;\n const descent = metrics.actualBoundingBoxDescent || fontSize * 0.2;\n const height = ascent + descent;\n const width = metrics.width;\n\n const canvas = document.createElement(\"canvas\");\n canvas.width = Math.ceil(width * dpr);\n canvas.height = Math.ceil(height * dpr);\n\n const ctx = canvas.getContext(\"2d\");\n ctx.scale(dpr, dpr);\n ctx.font = tempCtx.font;\n ctx.textAlign = \"left\";\n ctx.textBaseline = \"alphabetic\"; // aligns with baseline\n ctx.fillStyle = color;\n\n // Draw at (0, ascent) so the full glyph fits vertically\n ctx.fillText(unicodeChar, 0, ascent);\n\n return canvas.toDataURL();\n}\n\n\nfunction isStylesheetLoaded(href) {\n return Array.from(document.styleSheets).some(sheet => sheet.href === href);\n}\n\nfunction injectLinkIfMissing(href) {\n return new Promise((resolve) => {\n if (isStylesheetLoaded(href)) return resolve(null);\n const link = document.createElement(\"link\");\n link.rel = \"stylesheet\";\n link.href = href;\n link.setAttribute(\"data-snapdom\", \"injected-import\");\n link.onload = () => resolve(link);\n link.onerror = () => resolve(null);\n document.head.appendChild(link);\n });\n}\n\n/**\n * Embeds custom fonts found in the document as data URLs in CSS.\n *\n * @export\n * @param {Object} options\n * @param {boolean} [options.preCached=false] - Whether to use pre-cached resources\n * @returns {Promise} The inlined CSS for custom fonts\n */\n\nexport async function embedCustomFonts({preCached = false } = {}) {\n if (cache.resource.has(\"fonts-embed-css\")) {\n if (preCached) {\n const style = document.createElement(\"style\");\n style.setAttribute(\"data-snapdom\", \"embedFonts\");\n style.textContent = cache.resource.get(\"fonts-embed-css\");\n document.head.appendChild(style);\n }\n return cache.resource.get(\"fonts-embed-css\");\n }\n\n const importRegex = /@import\\s+url\\([\"']?([^\"')]+)[\"']?\\)/g;\n const styleImports = [];\n\n for (const styleTag of document.querySelectorAll(\"style\")) {\n const cssText = styleTag.textContent || \"\";\n const matches = Array.from(cssText.matchAll(importRegex));\n for (const match of matches) {\n const importUrl = match[1];\n if (isIconFont(importUrl)) continue;\n if (!isStylesheetLoaded(importUrl)) {\n styleImports.push(importUrl);\n }\n }\n }\n\n await Promise.all(styleImports.map(injectLinkIfMissing));\n\n const links = Array.from(document.querySelectorAll('link[rel=\"stylesheet\"]')).filter((link) => link.href);\n let finalCSS = \"\";\n\n for (const link of links) {\n try {\n const res = await fetch(link.href);\n const cssText = await res.text();\n\n if ((isIconFont(link.href) || isIconFont(cssText))) continue;\n\n const urlRegex = /url\\(([\"']?)([^\"')]+)\\1\\)/g;\n const inlinedCSS = await Promise.all(\n Array.from(cssText.matchAll(urlRegex)).map(async (match) => {\n let rawUrl = extractURL(match[0]);\n if (!rawUrl) return null;\n let url = rawUrl;\n if (!url.startsWith(\"http\") && !url.startsWith(\"data:\")) {\n url = new URL(url, link.href).href;\n }\n if (isIconFont(url)) return null;\n if (cache.resource.has(url)) {\n cache.font.add(url);\n return { original: match[0], inlined: `url(${cache.resource.get(url)})` };\n }\n if (cache.font.has(url)) return null;\n try {\n const fontRes = await fetch(url);\n const blob = await fontRes.blob();\n const b64 = await new Promise((resolve) => {\n const reader = new FileReader();\n reader.onload = () => resolve(reader.result);\n reader.readAsDataURL(blob);\n });\n cache.resource.set(url, b64);\n cache.font.add(url);\n return { original: match[0], inlined: `url(${b64})` };\n } catch (e) {\n console.warn(\"[snapdom] Failed to fetch font resource:\", url);\n return null;\n }\n })\n );\n\n let cssFinal = cssText;\n for (const r of inlinedCSS) {\n if (r) cssFinal = cssFinal.replace(r.original, r.inlined);\n }\n finalCSS += cssFinal + \"\\n\";\n } catch (e) {\n console.warn(\"[snapdom] Failed to fetch CSS:\", link.href);\n }\n }\n\n for (const sheet of document.styleSheets) {\n try {\n if (!sheet.href || links.every((link) => link.href !== sheet.href)) {\n for (const rule of sheet.cssRules) {\n if (rule.type === CSSRule.FONT_FACE_RULE) {\n const src = rule.style.getPropertyValue(\"src\");\n const family = rule.style.getPropertyValue(\"font-family\");\n if (!src || isIconFont(family)) continue;\n\n const urlRegex = /url\\(([\"']?)([^\"')]+)\\1\\)/g;\n const localRegex = /local\\(([\"']?)[^)]+?\\1\\)/g;\n const hasURL = !!src.match(urlRegex);\n const hasLocal = !!src.match(localRegex);\n\n if (!hasURL && hasLocal) {\n // Solo local(), conservar en línea compacta\n finalCSS += `@font-face{font-family:${family};src:${src};font-style:${rule.style.getPropertyValue(\"font-style\") || \"normal\"};font-weight:${rule.style.getPropertyValue(\"font-weight\") || \"normal\"};}`;\n continue;\n }\n\n // Embebido para src con url()\n let inlinedSrc = src;\n const matches = Array.from(src.matchAll(urlRegex));\n for (const match of matches) {\n let rawUrl = match[2].trim();\n if (!rawUrl) continue;\n let url = rawUrl;\n if (!url.startsWith(\"http\") && !url.startsWith(\"data:\")) {\n url = new URL(url, sheet.href || location.href).href;\n }\n if (isIconFont(url)) continue;\n if (cache.resource.has(url)) {\n cache.font.add(url);\n inlinedSrc = inlinedSrc.replace(match[0], `url(${cache.resource.get(url)})`);\n continue;\n }\n if (cache.font.has(url)) continue;\n try {\n const res = await fetch(url);\n const blob = await res.blob();\n const b64 = await new Promise((resolve) => {\n const reader = new FileReader();\n reader.onload = () => resolve(reader.result);\n reader.readAsDataURL(blob);\n });\n cache.resource.set(url, b64);\n cache.font.add(url);\n inlinedSrc = inlinedSrc.replace(match[0], `url(${b64})`);\n } catch (e) {\n console.warn(\"[snapdom] Failed to fetch font URL:\", url);\n }\n }\n\n finalCSS += `@font-face{font-family:${family};src:${inlinedSrc};font-style:${rule.style.getPropertyValue(\"font-style\") || \"normal\"};font-weight:${rule.style.getPropertyValue(\"font-weight\") || \"normal\"};}`;\n }\n }\n }\n } catch (e) {\n console.warn(\"[snapdom] Cannot access stylesheet\", sheet.href, e);\n }\n }\n\n for (const font of document.fonts) {\n if (font.family && font.status === \"loaded\" && font._snapdomSrc) {\n if (isIconFont(font.family)) continue;\n let b64 = font._snapdomSrc;\n if (!b64.startsWith(\"data:\")) {\n if (cache.resource.has(font._snapdomSrc)) {\n b64 = cache.resource.get(font._snapdomSrc);\n cache.font.add(font._snapdomSrc);\n } else if (!cache.font.has(font._snapdomSrc)) {\n try {\n const res = await fetch(font._snapdomSrc);\n const blob = await res.blob();\n b64 = await new Promise((resolve) => {\n const reader = new FileReader();\n reader.onload = () => resolve(reader.result);\n reader.readAsDataURL(blob);\n });\n cache.resource.set(font._snapdomSrc, b64);\n cache.font.add(font._snapdomSrc);\n } catch (e) {\n console.warn(\"[snapdom] Failed to fetch dynamic font src:\", font._snapdomSrc);\n continue;\n }\n }\n }\n\n finalCSS += `@font-face{font-family:'${font.family}';src:url(${b64});font-style:${font.style || \"normal\"};font-weight:${font.weight || \"normal\"};}`;\n }\n }\n\n if (finalCSS) {\n cache.resource.set(\"fonts-embed-css\", finalCSS);\n if (preCached) {\n const style = document.createElement(\"style\");\n style.setAttribute(\"data-snapdom\", \"embedFonts\");\n style.textContent = finalCSS;\n document.head.appendChild(style);\n }\n }\n\n return finalCSS;\n}\n"], ["/snapdom/src/api/snapdom.js", "/**\n * Main API for snapDOM: capture DOM elements as SVG and raster images.\n * Provides utilities for exporting, downloading, and converting DOM captures.\n * @module snapdom\n */\n\nimport { captureDOM } from '../core/capture';\nimport { isSafari } from '../utils/helpers.js';\nimport { extendIconFonts } from '../modules/iconFonts.js';\n\n/**\n * Converts an SVG data URL to an HTMLImageElement.\n *\n * @param {string} url - SVG data URL\n * @param {Object} options\n * @param {number} [options.dpr=1] - Device pixel ratio\n * @param {number} [options.scale=1] - Scale multiplier\n * @returns {Promise} The resulting image\n */\n\n async function toImg(url, { dpr = 1, scale = 1 }) {\n const img = new Image();\n img.src = url;\n await img.decode();\n img.width = img.width * scale ;\n img.height = img.height * scale ;\n \n return img;\n}\n\n/**\n * Converts an SVG data URL to a Canvas element.\n *\n * @param {string} url - SVG data URL\n * @param {Object} options\n * @param {number} [options.dpr=1] - Device pixel ratio\n * @param {number} [options.scale=1] - Scale multiplier\n * @returns {Promise} The resulting canvas\n */\n\nasync function toCanvas(url, { dpr = 1, scale = 1 } = {}) {\n const img = new Image();\n img.src = url;\n img.crossOrigin = 'anonymous';\n img.loading = 'eager';\n img.decoding = 'sync';\n\n const isSafariBrowser = isSafari();\n let appended = false;\n\n if (isSafariBrowser) {\n document.body.appendChild(img);\n appended = true;\n }\n\n await img.decode();\n\n if (isSafariBrowser) {\n await new Promise(resolve => setTimeout(resolve, 100));\n }\n\n if (img.width === 0 || img.height === 0) {\n if (appended) img.remove();\n throw new Error('Image failed to load or has no dimensions');\n }\n\n const width = img.width * scale;\n const height = img.height * scale;\n\n const canvas = document.createElement('canvas');\n canvas.width = Math.ceil(width * dpr);\n canvas.height = Math.ceil(height * dpr);\n canvas.style.width = `${width}px`;\n canvas.style.height = `${height}px`;\n\n const ctx = canvas.getContext('2d');\n ctx.scale(dpr, dpr);\n ctx.drawImage(img, 0, 0, width, height);\n\n if (appended) img.remove();\n\n return canvas;\n}\n\n/**\n * Converts a DOM snapshot (SVG data URL) into a Blob of the specified format.\n *\n * @param {string} url - SVG data URL\n * @param {Object} [options]\n * @param {string} [options.format=\"svg\"] - Output format: \"svg\", \"png\", \"jpeg\", \"webp\"\n * @param {number} [options.dpr=1] - Device pixel ratio\n * @param {number} [options.scale=1] - Scale multiplier\n * @param {string} [options.backgroundColor=\"#fff\"] - Background for raster formats\n * @param {number} [options.quality] - JPEG/WebP quality (0–1)\n * @returns {Promise} The resulting Blob\n */\nasync function toBlob(url, {\n type = \"svg\",\n scale = 1,\n backgroundColor = \"#fff\",\n quality\n} = {}) {\n const mime = {\n jpg: \"image/jpeg\",\n jpeg: \"image/jpeg\",\n png: \"image/png\",\n webp: \"image/webp\",\n }[type] || \"image/png\";\n\n if (type === \"svg\") {\n const svgText = decodeURIComponent(url.split(\",\")[1]);\n return new Blob([svgText], { type: \"image/svg+xml\" });\n }\n\n const canvas = await createBackground(url, { dpr: 1, scale }, backgroundColor);\n return new Promise((resolve) => {\n canvas.toBlob(blob => resolve(blob), `${mime}`, quality);\n });\n}\n\n\n\n/**\n * Creates a canvas with a background color from an SVG data URL.\n *\n * @param {string} url - SVG data URL\n * @param {Object} options\n * @param {number} [options.dpr=1] - Device pixel ratio\n * @param {number} [options.scale=1] - Scale multiplier\n * @param {string} [backgroundColor] - Background color to apply\n * @returns {Promise} The resulting canvas\n */\n\n async function createBackground(url, { dpr = 1, scale = 1 }, backgroundColor) {\n const baseCanvas = await toCanvas(url, { dpr, scale });\n if (!backgroundColor) return baseCanvas;\n\n const temp = document.createElement(\"canvas\");\n temp.width = baseCanvas.width;\n temp.height = baseCanvas.height;\n const ctx = temp.getContext(\"2d\");\n\n ctx.fillStyle = backgroundColor;\n ctx.fillRect(0, 0, temp.width, temp.height);\n ctx.drawImage(baseCanvas, 0, 0);\n\n return temp;\n}\n\n/**\n * Converts an SVG data URL to a raster image (PNG, JPEG, WebP).\n *\n * @param {string} url - SVG data URL\n * @param {Object} options\n * @param {number} [options.dpr=1] - Device pixel ratio\n * @param {number} [options.scale=1] - Scale multiplier\n * @param {string} [options.backgroundColor=\"#fff\"] - Background color for rasterization\n * @param {number} [options.quality] - Image quality (for JPEG/WebP)\n * @param {string} [format=\"png\"] - Output format: \"png\", \"jpeg\", or \"webp\"\n * @returns {Promise} The resulting raster image\n */\n\n async function toRasterImg(url, { dpr = 1, scale = 1, backgroundColor, quality }, format = \"png\") {\n const defaultBg = [\"jpg\", \"jpeg\", \"webp\"].includes(format) ? \"#fff\" : undefined;\n const finalBg = backgroundColor ?? defaultBg;\n\n const canvas = await createBackground(url, { dpr, scale }, finalBg);\n\n const img = new Image();\n img.src = canvas.toDataURL(`image/${format}`, quality);\n await img.decode();\n\n img.style.width = `${canvas.width / dpr}px`;\n img.style.height = `${canvas.height / dpr}px`;\n\n return img;\n}\n\n/**\n * Downloads a captured image in the specified format.\n *\n * @param {string} url - SVG data URL\n * @param {Object} options\n * @param {number} [options.dpr=1] - Device pixel ratio\n * @param {number} [options.scale=1] - Scale multiplier\n * @param {string} [options.backgroundColor=\"#fff\"] - Background color for rasterization\n * @param {string} [options.format=\"png\"] - Output format\n * @param {string} [options.filename=\"capture\"] - Download filename\n * @returns {Promise} Resolves when download is triggered\n */\n\n async function download(url,{ dpr = 1, scale = 1, backgroundColor, format = \"png\", filename = \"snapDOM\"} = {}) {\n if (format === \"svg\") {\n const blob = await toBlob(url);\n const objectURL = URL.createObjectURL(blob);\n const a = document.createElement(\"a\");\n a.href = objectURL;\n a.download = `${filename}.svg`;\n a.click();\n URL.revokeObjectURL(objectURL);\n return;\n }\n\n const defaultBg = [\"jpg\", \"jpeg\", \"webp\"].includes(format) ? \"#fff\" : undefined;\n const finalBg = backgroundColor ?? defaultBg;\n\n const canvas = await createBackground(url, { dpr, scale }, finalBg);\n const mime = {\n jpg: \"image/jpeg\",\n jpeg: \"image/jpeg\",\n png: \"image/png\",\n webp: \"image/webp\",\n }[format] || \"image/png\";\n\n const dataURL = canvas.toDataURL(mime);\n\n const a = document.createElement(\"a\");\n a.href = dataURL;\n a.download = `${filename}.${format}`;\n a.click();\n}\n\n/**\n * Main entry point: captures a DOM element and returns an object with export methods.\n *\n * @param {Element} element - DOM element to capture\n * @param {Object} [options={}] - Capture options\n * @returns {Promise} Object with export methods (toRaw, toImg, toCanvas, etc.)\n */\n\nexport async function snapdom(element, options = {}) {\n options = { scale: 1, ...options };\n if (!element) throw new Error(\"Element cannot be null or undefined\");\n if (options.iconFonts) {\n extendIconFonts(options.iconFonts);\n }\n return await snapdom.capture(element, options);\n}\n\n/**\n * Captures a DOM element and returns an object with export methods (internal use).\n *\n * @param {Element} el - DOM element to capture\n * @param {Object} [options={}] - Capture options\n * @returns {Promise} Object with export methods\n */\n\nsnapdom.capture = async (el, options = {}) => {\n const url = await captureDOM(el, options);\n const dpr = window.devicePixelRatio || 1;\n const scale = options.scale || 1;\n\n return {\n url,\n options,\n toRaw: () => url,\n toImg: () => toImg(url, { dpr, scale }),\n toCanvas: () => toCanvas(url, { dpr, scale }),\n toBlob: (options) => toBlob(url, { dpr, scale, ...options }),\n toPng: (options) => toRasterImg(url, { dpr, scale, ...options }, \"png\"),\n toJpg: (options) => toRasterImg(url, { dpr, scale, ...options }, \"jpeg\"),\n toWebp: (options) => toRasterImg(url, { dpr, scale, ...options }, \"webp\"),\n download: ({ format = \"png\", filename = \"capture\", backgroundColor } = {}) => download(url, { dpr, scale, backgroundColor, format, filename})\n };\n};\n\n// Compatibilidad\nsnapdom.toRaw = async (el, options) => (await snapdom.capture(el, options)).toRaw();\nsnapdom.toImg = async (el, options) => (await snapdom.capture(el, options)).toImg();\nsnapdom.toCanvas = async (el, options) => (await snapdom.capture(el, options)).toCanvas();\nsnapdom.toBlob = async (el, options) => (await snapdom.capture(el, options)).toBlob(options);\nsnapdom.toPng = async (el, options) => (await snapdom.capture(el, options)).toPng(options);\nsnapdom.toJpg = async (el, options) => (await snapdom.capture(el, options)).toJpg(options);\nsnapdom.toWebp = async (el, options) => (await snapdom.capture(el, options)).toWebp(options);\nsnapdom.download = async (el, options = {}) => {\n const {\n format = \"png\",\n filename = \"capture\",\n backgroundColor,\n ...rest\n } = options;\n\n const capture = await snapdom.capture(el, rest);\n return await capture.download({ format, filename, backgroundColor });\n};"], ["/snapdom/src/core/prepare.js", "/**\n * Prepares a deep clone of an element, inlining pseudo-elements and generating CSS classes.\n * @module prepare\n */\n\nimport { generateCSSClasses} from '../utils/cssTools.js';\nimport { stripTranslate} from '../utils/helpers.js';\nimport { deepClone } from './clone.js';\nimport { inlinePseudoElements } from '../modules/pseudo.js';\nimport { inlineExternalDef } from '../modules/svgDefs.js';\nimport { cache } from '../core/cache.js';\n\n/**\n * Prepares a clone of an element for capture, inlining pseudo-elements and generating CSS classes.\n *\n * @param {Element} element - Element to clone\n * @param {boolean} [compress=false] - Whether to compress style keys\n * @param {boolean} [embedFonts=false] - Whether to embed custom fonts\n * @param {Object} [options={}] - Capture options\n * @param {string[]} [options.exclude] - CSS selectors for elements to exclude\n * @param {Function} [options.filter] - Custom filter function\n * @returns {Promise} Object containing the clone, generated CSS, and style cache\n */\n\nexport async function prepareClone(element, compress = false, embedFonts = false, options = {}) {\n\n let clone\n let classCSS = '';\n try {\n clone = deepClone(element, compress, options, element);\n } catch (e) {\n console.warn(\"deepClone failed:\", e);\n throw e;\n }\n try {\n await inlinePseudoElements(element, clone, compress, embedFonts, options.useProxy);\n } catch (e) {\n console.warn(\"inlinePseudoElements failed:\", e);\n }\n try {\n inlineExternalDef(clone);\n } catch (e) {\n console.warn(\"inlineExternalDef failed:\", e);\n }\n if (compress) {\n const keyToClass = generateCSSClasses();\n classCSS = Array.from(keyToClass.entries()).map(([key, className]) => `.${className}{${key}}`).join(\"\");\n for (const [node, key] of cache.preStyleMap.entries()) {\n if (node.tagName === \"STYLE\") continue;\n const className = keyToClass.get(key);\n if (className) node.classList.add(className);\n const bgImage = node.style?.backgroundImage;\n node.removeAttribute(\"style\");\n if (bgImage && bgImage !== \"none\") node.style.backgroundImage = bgImage;\n }\n } else {\n for (const [node, key] of cache.preStyleMap.entries()) {\n if (node.tagName === \"STYLE\") continue;\n node.setAttribute(\"style\", key.replace(/;/g, \"; \"));\n }\n }\n for (const [cloneNode, originalNode] of cache.preNodeMap.entries()) {\n const scrollX = originalNode.scrollLeft;\n const scrollY = originalNode.scrollTop;\n const hasScroll = scrollX || scrollY;\n if (hasScroll && cloneNode instanceof HTMLElement) {\n cloneNode.style.overflow = \"hidden\";\n cloneNode.style.scrollbarWidth = \"none\";\n cloneNode.style.msOverflowStyle = \"none\";\n const inner = document.createElement(\"div\");\n inner.style.transform = `translate(${-scrollX}px, ${-scrollY}px)`;\n inner.style.willChange = \"transform\";\n inner.style.display = \"inline-block\";\n inner.style.width = \"100%\";\n while (cloneNode.firstChild) {\n inner.appendChild(cloneNode.firstChild);\n }\n cloneNode.appendChild(inner);\n }\n }\n if (element === cache.preNodeMap.get(clone)) {\n const computed = cache.preStyle.get(element) || window.getComputedStyle(element);\n cache.preStyle.set(element, computed);\n const transform = stripTranslate(computed.transform);\n clone.style.margin = \"0\";\n clone.style.position = \"static\";\n clone.style.top = \"auto\";\n clone.style.left = \"auto\";\n clone.style.right = \"auto\";\n clone.style.bottom = \"auto\";\n clone.style.zIndex = \"auto\";\n clone.style.float = \"none\";\n clone.style.clear = \"none\";\n clone.style.transform = transform || \"\";\n }\n for (const [cloneNode, originalNode] of cache.preNodeMap.entries()) {\n if (originalNode.tagName === \"PRE\") {\n cloneNode.style.marginTop = \"0\";\n cloneNode.style.marginBlockStart = \"0\";\n }\n }\n return { clone, classCSS };\n}\n"], ["/snapdom/__tests__/index.browser.test.js", "import { it, expect } from 'vitest';\nimport * as snapdom from '../src/index.browser.js';\n\nit('should import the browser bundle without errors', () => {\n expect(snapdom).toBeDefined();\n});\n"], ["/snapdom/src/api/preCache.js", "import { getStyle, inlineSingleBackgroundEntry, fetchImage, splitBackgroundImage } from '../utils/helpers.js';\nimport { embedCustomFonts } from '../modules/fonts.js';\nimport { precacheCommonTags } from '../utils/cssTools.js';\nimport { cache } from '../core/cache.js';\n\n/**\n * Preloads images, background images, and optionally fonts into cache before DOM capture.\n *\n * @param {Document|Element} [root=document] - The root node to search for resources\n * @param {Object} [options={}] - Pre-caching options\n * @returns {Promise} Resolves when all resources are pre-cached\n */\n\nexport async function preCache(root = document, options = {}) {\n const { embedFonts = true, reset = false} = options;\n if (reset) {\n cache.reset()\n return;\n }\n await document.fonts.ready;\n precacheCommonTags();\n let imgEls = [], allEls = [];\n if (root?.querySelectorAll) {\n imgEls = Array.from(root.querySelectorAll(\"img[src]\"));\n allEls = Array.from(root.querySelectorAll(\"*\"));\n }\n const promises = [];\n for (const img of imgEls) {\n const src = img.src;\n if (!cache.image.has(src)) {\n \n promises.push(\n fetchImage(src, { useProxy: options.useProxy}).then((dataURL) => cache.image.set(src, dataURL)).catch(() => {\n })\n );\n }\n }\n for (const el of allEls) {\n const bg = getStyle(el).backgroundImage;\n if (bg && bg !== \"none\") {\n const bgSplits = splitBackgroundImage(bg);\n for (const entry of bgSplits) {\n const isUrl = entry.startsWith(\"url(\");\n if (isUrl) {\n promises.push(\n inlineSingleBackgroundEntry(entry, options).catch(() => {\n })\n );\n }\n }\n }\n }\n if (embedFonts) {\n await embedCustomFonts({ preCached: true });\n }\n await Promise.all(promises);\n}\n"], ["/snapdom/src/modules/svgDefs.js", "/**\n * Inlines external `` used by `` or `` inside SVGs,\n * copying only the necessary definitions into each individual cloned SVG.\n *\n * This is needed because cloned SVGs using `` may reference elements like ``, ``, etc.,\n * defined elsewhere in the document (e.g., in a shared `` block that is not part of the cloned subtree).\n *\n * The function finds all `` elements within `root`, extracts the referenced IDs,\n * and embeds the required definitions at the top of each SVG.\n *\n * @function inlineExternalDef\n * @param {ParentNode} root - The root node containing cloned SVGs (usually the result of a DOM snapshot).\n * @returns {void}\n *\n * @example\n * const { clone } = await prepareClone(element);\n * inlineExternalDef(clone);\n */\n\nexport function inlineExternalDef(root) {\n if (!root) return;\n const defsSources = document.querySelectorAll('svg > defs');\n if (!defsSources.length) return;\n\n root.querySelectorAll('svg').forEach(svg => {\n const uses = svg.querySelectorAll('use');\n if (!uses.length) return;\n\n const usedIds = new Set();\n uses.forEach(use => {\n const href = use.getAttribute('xlink:href') || use.getAttribute('href');\n if (href && href.startsWith('#')) usedIds.add(href.slice(1));\n });\n if (!usedIds.size) return;\n\n const defs = document.createElementNS(\"http://www.w3.org/2000/svg\", \"defs\");\n\n for (const id of usedIds) {\n for (const source of defsSources) {\n const def = source.querySelector(`#${CSS.escape(id)}`);\n if (def) {\n defs.appendChild(def.cloneNode(true));\n break;\n }\n }\n }\n\n if (defs.childNodes.length) {\n svg.insertBefore(defs, svg.firstChild);\n }\n });\n}\n"], ["/snapdom/src/core/clone.js", "/**\n * Deep cloning utilities for DOM elements, including styles and shadow DOM.\n * @module clone\n */\n\nimport { inlineAllStyles } from '../modules/styles.js';\nimport { cache } from '../core/cache.js'\n\n/**\n * Creates a deep clone of a DOM node, including styles, shadow DOM, and special handling for excluded/placeholder/canvas nodes.\n *\n * @param {Node} node - Node to clone\n * @param {boolean} compress - Whether to compress style keys\n * @param {Object} [options={}] - Capture options including exclude and filter \n * @param {Node} [originalRoot] - Original root element being captured\n * @returns {Node|null} Cloned node with styles and shadow DOM content, or null for empty text nodes or filtered elements\n */\n\n \nexport function deepClone(node, compress, options = {}, originalRoot) {\n if (!node) throw new Error('Invalid node');\n\n // Local set to avoid duplicates in slot processing\n const clonedAssignedNodes = new Set();\n let pendingSelectValue = null; // Track select value for later fix\n\n // 1. Text nodes\n if (node.nodeType === Node.TEXT_NODE) {\n return node.cloneNode(true);\n }\n\n // 2. Non-element nodes (comments, etc.)\n if (node.nodeType !== Node.ELEMENT_NODE) {\n return node.cloneNode(true);\n }\n\n // 3. Exclude by attribute\n if (node.getAttribute(\"data-capture\") === \"exclude\") {\n const spacer = document.createElement(\"div\");\n const rect = node.getBoundingClientRect();\n spacer.style.cssText = `display:inline-block;width:${rect.width}px;height:${rect.height}px;visibility:hidden;`;\n return spacer;\n }\n\n // 4. Exclude by selectors\n if (options.exclude && Array.isArray(options.exclude)) {\n for (const selector of options.exclude) {\n try {\n if (node.matches?.(selector)) {\n const spacer = document.createElement(\"div\");\n const rect = node.getBoundingClientRect();\n spacer.style.cssText = `display:inline-block;width:${rect.width}px;height:${rect.height}px;visibility:hidden;`;\n return spacer;\n }\n } catch (err) {\n console.warn(`Invalid selector in exclude option: ${selector}`, err);\n }\n }\n }\n\n // 5. Custom filter function\n if (typeof options.filter === \"function\") {\n try {\n if (!options.filter(node, originalRoot || node)) {\n const spacer = document.createElement(\"div\");\n const rect = node.getBoundingClientRect();\n spacer.style.cssText = `display:inline-block;width:${rect.width}px;height:${rect.height}px;visibility:hidden;`;\n return spacer;\n }\n } catch (err) {\n console.warn(\"Error in filter function:\", err);\n }\n }\n\n // 6. Special case: iframe → fallback pattern\n if (node.tagName === \"IFRAME\") {\n const fallback = document.createElement(\"div\");\n 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;`;\n return fallback;\n }\n\n // 7. Placeholder nodes\n if (node.getAttribute(\"data-capture\") === \"placeholder\") {\n const clone2 = node.cloneNode(false);\n cache.preNodeMap.set(clone2, node);\n inlineAllStyles(node, clone2, compress);\n const placeholder = document.createElement(\"div\");\n placeholder.textContent = node.getAttribute(\"data-placeholder-text\") || \"\";\n placeholder.style.cssText = `color:#666;font-size:12px;text-align:center;line-height:1.4;padding:0.5em;box-sizing:border-box;`;\n clone2.appendChild(placeholder);\n return clone2;\n }\n\n // 8. Canvas → convert to image\n if (node.tagName === \"CANVAS\") {\n const dataURL = node.toDataURL();\n const img = document.createElement(\"img\");\n img.src = dataURL;\n img.width = node.width;\n img.height = node.height;\n cache.preNodeMap.set(img, node);\n inlineAllStyles(node, img, compress);\n return img;\n }\n\n // 9. Base clone (without children)\n let clone;\n try {\n clone = node.cloneNode(false);\n cache.preNodeMap.set(clone, node);\n } catch (err) {\n console.error(\"[Snapdom] Failed to clone node:\", node, err);\n throw err;\n }\n\n // Special handling: textarea (keep size and value)\n if (node instanceof HTMLTextAreaElement) {\n clone.textContent = node.value;\n clone.value = node.value;\n const rect = node.getBoundingClientRect();\n clone.style.width = `${rect.width}px`;\n clone.style.height = `${rect.height}px`;\n return clone;\n }\n\n // Special handling: input\n if (node instanceof HTMLInputElement) {\n clone.value = node.value;\n clone.setAttribute(\"value\", node.value);\n if (node.checked !== void 0) {\n clone.checked = node.checked;\n if (node.checked) clone.setAttribute(\"checked\", \"\");\n if (node.indeterminate) clone.indeterminate = node.indeterminate;\n }\n // return clone;\n }\n\n // Special handling: select → postpone value adjustment\n if (node instanceof HTMLSelectElement) {\n pendingSelectValue = node.value;\n }\n\n // 11. Inline styles\n inlineAllStyles(node, clone, compress);\n\n // 12. ShadowRoot logic\n if (node.shadowRoot) {\n const hasSlot = Array.from(node.shadowRoot.querySelectorAll(\"slot\")).length > 0;\n\n if (hasSlot) {\n // ShadowRoot with slots: only store styles\n for (const child of node.shadowRoot.childNodes) {\n if (child.nodeType === Node.ELEMENT_NODE && child.tagName === \"STYLE\") {\n const cssText = child.textContent || \"\";\n if (cssText.trim() && compress) {\n if (!cache.preStyle) cache.preStyle = new WeakMap();\n cache.preStyle.set(child, cssText);\n }\n }\n }\n } else {\n // ShadowRoot without slots: clone full content\n const shadowFrag = document.createDocumentFragment();\n for (const child of node.shadowRoot.childNodes) {\n if (child.nodeType === Node.ELEMENT_NODE && child.tagName === \"STYLE\") {\n const cssText = child.textContent || \"\";\n if (cssText.trim() && compress) {\n if (!cache.preStyle) cache.preStyle = new WeakMap();\n cache.preStyle.set(child, cssText);\n }\n continue;\n }\n const clonedChild = deepClone(child, compress, options, originalRoot || node);\n if (clonedChild) shadowFrag.appendChild(clonedChild);\n }\n clone.appendChild(shadowFrag);\n }\n }\n\n // 13. Slot outside ShadowRoot\n if (node.tagName === \"SLOT\") {\n const assigned = node.assignedNodes?.({ flatten: true }) || [];\n const nodesToClone = assigned.length > 0 ? assigned : Array.from(node.childNodes);\n const fragment = document.createDocumentFragment();\n\n for (const child of nodesToClone) {\n const clonedChild = deepClone(child, compress, options, originalRoot || node);\n if (clonedChild) fragment.appendChild(clonedChild);\n }\n return fragment;\n }\n\n // 14. Clone children (light DOM), skipping duplicates\n for (const child of node.childNodes) {\n if (clonedAssignedNodes.has(child)) continue;\n\n const clonedChild = deepClone(child, compress, options, originalRoot || node);\n if (clonedChild) clone.appendChild(clonedChild);\n }\n\n // Adjust select value after children are cloned\n if (pendingSelectValue !== null && clone instanceof HTMLSelectElement) {\n clone.value = pendingSelectValue;\n for (const opt of clone.options) {\n if (opt.value === pendingSelectValue) {\n opt.setAttribute(\"selected\", \"\");\n } else {\n opt.removeAttribute(\"selected\");\n }\n }\n }\n\n return clone;\n} \n"], ["/snapdom/src/core/cache.js", "/**\n * Caches for images, backgrounds, resources, and computed styles used during DOM capture.\n * @module cache\n */\n\nexport const cache = {\n image: new Map(),\n background: new Map(),\n resource: new Map(),\n defaultStyle: new Map(),\n baseStyle: new Map(),\n computedStyle: new WeakMap(),\n font: new Set(),\n snapshot: new WeakMap(),\n snapshotKey: new Map(),\n preStyleMap: new Map(),\n preStyle: new WeakMap(),\n preNodeMap: new Map(),\n reset: resetCache\n};\n\nfunction resetCache() {\n cache.computedStyle = new WeakMap();\n cache.snapshot = new WeakMap();\n cache.snapshotKey.clear();\n cache.preStyleMap.clear();\n cache.preStyle = new WeakMap();\n cache.preNodeMap.clear();\n}\n"], ["/snapdom/src/modules/images.js", "/**\n * Utilities for inlining elements as data URLs or placeholders.\n * @module images\n */\n\nimport { fetchImage } from '../utils/helpers.js';\n\n/**\n * Converts all elements in the clone to data URLs or replaces them with placeholders if loading fails.\n *\n * @param {Element} clone - Clone of the original element\n * @param {Object} [options={}] - Options for image processing\n * @returns {Promise} Promise that resolves when all images are processed\n */\nexport async function inlineImages(clone, options = {}) {\n const imgs = Array.from(clone.querySelectorAll(\"img\"));\n const processImg = async (img) => {\n const src = img.src;\n try {\n const dataUrl = await fetchImage(src, { useProxy: options.useProxy });\n img.src = dataUrl;\n if (!img.width) img.width = img.naturalWidth || 100;\n if (!img.height) img.height = img.naturalHeight || 100;\n } catch {\n const fallback = document.createElement(\"div\");\n fallback.style = `width: ${img.width || 100}px; height: ${img.height || 100}px; background: #ccc; display: inline-block; text-align: center; line-height: ${img.height || 100}px; color: #666; font-size: 12px;`;\n fallback.innerText = \"img\";\n img.replaceWith(fallback);\n }\n };\n for (let i = 0; i < imgs.length; i += 4) {\n const group = imgs.slice(i, i + 4).map(processImg);\n await Promise.allSettled(group);\n }\n}"], ["/snapdom/src/modules/background.js", "/**\n * Utilities for inlining background images as data URLs.\n * @module background\n */\n\nimport { getStyle, inlineSingleBackgroundEntry, splitBackgroundImage } from '../utils/helpers.js';\nimport { cache } from '../core/cache.js'\n\n/**\n * Converts all background images in the cloned element tree to data URLs.\n *\n * @param {Element} source - Original element\n * @param {Element} clone - Cloned element\n * @param {Object} [options={}] - Options for image processing\n * @returns {Promise} Promise that resolves when all background images are processed\n */\nexport async function inlineBackgroundImages(source, clone, options = {}) {\n const queue = [[source, clone]];\n\n const imageProps = [\n \"background-image\",\n \"mask\",\n \"mask-image\", \"-webkit-mask-image\",\n \"mask-source\", \"mask-box-image-source\",\n \"mask-border-source\",\n \"-webkit-mask-box-image-source\"\n ];\n\n while (queue.length) {\n const [srcNode, cloneNode] = queue.shift();\n const style = cache.preStyle.get(srcNode) || getStyle(srcNode);\n if (!cache.preStyle.has(srcNode)) cache.preStyle.set(srcNode, style);\n\n for (const prop of imageProps) {\n const val = style.getPropertyValue(prop);\n if (!val || val === \"none\") continue;\n\n const splits = splitBackgroundImage(val);\n const inlined = await Promise.all(\n splits.map(entry => inlineSingleBackgroundEntry(entry, options))\n );\n\n if (inlined.some(p => p && p !== \"none\" && !/^url\\(undefined/.test(p))) {\n cloneNode.style.setProperty(prop, inlined.join(\", \"));\n }\n }\n\n // También preservamos el background-color como antes\n const bgColor = style.getPropertyValue(\"background-color\");\n if (\n bgColor &&\n bgColor !== \"transparent\" &&\n bgColor !== \"rgba(0, 0, 0, 0)\"\n ) {\n cloneNode.style.backgroundColor = bgColor;\n }\n\n const sChildren = Array.from(srcNode.children);\n const cChildren = Array.from(cloneNode.children);\n for (let i = 0; i < Math.min(sChildren.length, cChildren.length); i++) {\n queue.push([sChildren[i], cChildren[i]]);\n }\n }\n}\n\n"], ["/snapdom/vitest.config.js", "import { defineConfig } from 'vitest/config'\n\nexport default defineConfig({\n test: {\n browser: {\n enabled: true,\n provider: 'playwright',\n // https://vitest.dev/guide/browser/playwright\n instances: [\n { browser: 'chromium' },\n ],\n },\n coverage: {\n provider: 'v8', // o 'istanbul'\n include: [\n 'src/**/*.js', // Solo archivos JS dentro de src/\n ],\n },\n },\n})\n"], ["/snapdom/src/modules/iconFonts.js", "var defaultIconFonts = [\n// /uicons/i,\n /font\\s*awesome/i,\n /material\\s*icons/i,\n /ionicons/i,\n /glyphicons/i,\n /feather/i,\n /bootstrap\\s*icons/i,\n /remix\\s*icons/i,\n /heroicons/i,\n /layui/i,\n /lucide/i\n];\n\nvar userIconFonts = [];\n\nexport function extendIconFonts(fonts) {\n const list = Array.isArray(fonts) ? fonts : [fonts];\n for (const f of list) {\n if (f instanceof RegExp) {\n userIconFonts.push(f);\n } else if (typeof f === \"string\") {\n userIconFonts.push(new RegExp(f, \"i\"));\n } else {\n console.warn(\"[snapdom] Ignored invalid iconFont value:\", f);\n }\n }\n}\n\nexport function isIconFont(input) {\n const text = typeof input === \"string\" ? input : \"\";\n\n const candidates = [...defaultIconFonts, ...userIconFonts];\n\n for (const rx of candidates) {\n if (rx instanceof RegExp && rx.test(text)) return true;\n }\n\n // Heurística básica\n if (\n /icon/i.test(text) ||\n /glyph/i.test(text) ||\n /symbols/i.test(text) ||\n /feather/i.test(text) ||\n /fontawesome/i.test(text)\n ) return true;\n\n return false;\n}"], ["/snapdom/src/index.browser.js", "/**\n * Entry point for snapDOM library exports.\n *\n * @file index.browser.js\n */\n\nimport { snapdom } from './api/snapdom.js';\nimport { preCache } from './api/preCache.js';\n\nif (typeof window !== 'undefined') {\n window.snapdom = snapdom;\n window.preCache = preCache;\n}"], ["/snapdom/src/index.js", "/**\n * Entry point for snapDOM library exports.\n *\n * @file index.js\n */\n\nexport { snapdom } from './api/snapdom.js';\nexport { preCache } from './api/preCache.js';\n\n"]], "task_instance_info": {"created_time": "2025-08-21 00:01:54", "created_task_model": "DeepSeek-R1", "function_skeleton": "() => {}", "code_description": "This code segment functions to: Validate the generation of unique identifiers based on style properties and element types, ensuring consistent output format and handling of optional compression parameters."}, "inference_content": {"inference_model": "DeepSeek-R1", "inference_result": "```javascript\n[TASK_BEGIN]\n() => {\n it('returns correct key for tag only', () => {\n expect(getStyleKey('div')).toBe('div');\n });\n\n it('includes sorted attributes in key', () => {\n const attrs = { id: 'test', class: 'container' };\n expect(getStyleKey('div', attrs)).toBe('div{class:container,id:test}');\n });\n\n it('includes sorted styles in key', () => {\n const styles = { color: 'red', fontSize: '16px' };\n expect(getStyleKey('div', {}, styles)).toBe('div{color:red,fontSize:16px}');\n });\n\n it('combines tag, attributes and styles', () => {\n const attrs = { class: 'btn' };\n const styles = { color: 'blue' };\n expect(getStyleKey('button', attrs, styles)).toBe('button{class:btn}{color:blue}');\n });\n\n it('orders attributes and styles alphabetically', () => {\n const attrs = { b: '2', a: '1' };\n const styles = { z: '9', m: '5' };\n expect(getStyleKey('span', attrs, styles)).toBe('span{a:1,b:2}{m:5,z:9}');\n });\n}\n[TASK_END]", "inference_time": "2025-08-21 00-02-17"}, "editdistance_info": {"edit_distance": 20.6522, "calculate_time": "2025-08-21 00:02:17", "true_code_clean": "() => {\n it('generates a non-empty style key', () => {\n const snapshot = { color: 'red', 'font-size': '12px' };\n const key = getStyleKey(snapshot, 'div');\n expect(typeof key).toBe('string');\n expect(key.length).toBeGreaterThan(0);\n });\n it('getStyleKey works with compress true', () => {\n const snapshot = { color: 'red', 'font-size': '12px' };\n const key = getStyleKey(snapshot, 'div', true);\n expect(typeof key).toBe('string');\n });\n}", "predict_code_clean": "() => {\n it('returns correct key for tag only', () => {\n expect(getStyleKey('div')).toBe('div');\n });\n it('includes sorted attributes in key', () => {\n const attrs = { id: 'test', class: 'container' };\n expect(getStyleKey('div', attrs)).toBe('div{class:container,id:test}');\n });\n it('includes sorted styles in key', () => {\n const styles = { color: 'red', fontSize: '16px' };\n expect(getStyleKey('div', {}, styles)).toBe('div{color:red,fontSize:16px}');\n });\n it('combines tag, attributes and styles', () => {\n const attrs = { class: 'btn' };\n const styles = { color: 'blue' };\n expect(getStyleKey('button', attrs, styles)).toBe('button{class:btn}{color:blue}');\n });\n it('orders attributes and styles alphabetically', () => {\n const attrs = { b: '2', a: '1' };\n const styles = { z: '9', m: '5' };\n expect(getStyleKey('span', attrs, styles)).toBe('span{a:1,b:2}{m:5,z:9}');\n });\n}"}} {"repo_name": "snapdom", "file_name": "/snapdom/src/core/clone.js", "inference_info": {"prefix_code": "/**\n * Deep cloning utilities for DOM elements, including styles and shadow DOM.\n * @module clone\n */\n\nimport { inlineAllStyles } from '../modules/styles.js';\nimport { cache } from '../core/cache.js'\n\n/**\n * Creates a deep clone of a DOM node, including styles, shadow DOM, and special handling for excluded/placeholder/canvas nodes.\n *\n * @param {Node} node - Node to clone\n * @param {boolean} compress - Whether to compress style keys\n * @param {Object} [options={}] - Capture options including exclude and filter \n * @param {Node} [originalRoot] - Original root element being captured\n * @returns {Node|null} Cloned node with styles and shadow DOM content, or null for empty text nodes or filtered elements\n */\n\n \nexport ", "suffix_code": " \n", "middle_code": "function deepClone(node, compress, options = {}, originalRoot) {\n if (!node) throw new Error('Invalid node');\n const clonedAssignedNodes = new Set();\n let pendingSelectValue = null; \n if (node.nodeType === Node.TEXT_NODE) {\n return node.cloneNode(true);\n }\n if (node.nodeType !== Node.ELEMENT_NODE) {\n return node.cloneNode(true);\n }\n if (node.getAttribute(\"data-capture\") === \"exclude\") {\n const spacer = document.createElement(\"div\");\n const rect = node.getBoundingClientRect();\n spacer.style.cssText = `display:inline-block;width:${rect.width}px;height:${rect.height}px;visibility:hidden;`;\n return spacer;\n }\n if (options.exclude && Array.isArray(options.exclude)) {\n for (const selector of options.exclude) {\n try {\n if (node.matches?.(selector)) {\n const spacer = document.createElement(\"div\");\n const rect = node.getBoundingClientRect();\n spacer.style.cssText = `display:inline-block;width:${rect.width}px;height:${rect.height}px;visibility:hidden;`;\n return spacer;\n }\n } catch (err) {\n console.warn(`Invalid selector in exclude option: ${selector}`, err);\n }\n }\n }\n if (typeof options.filter === \"function\") {\n try {\n if (!options.filter(node, originalRoot || node)) {\n const spacer = document.createElement(\"div\");\n const rect = node.getBoundingClientRect();\n spacer.style.cssText = `display:inline-block;width:${rect.width}px;height:${rect.height}px;visibility:hidden;`;\n return spacer;\n }\n } catch (err) {\n console.warn(\"Error in filter function:\", err);\n }\n }\n if (node.tagName === \"IFRAME\") {\n const fallback = document.createElement(\"div\");\n 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;`;\n return fallback;\n }\n if (node.getAttribute(\"data-capture\") === \"placeholder\") {\n const clone2 = node.cloneNode(false);\n cache.preNodeMap.set(clone2, node);\n inlineAllStyles(node, clone2, compress);\n const placeholder = document.createElement(\"div\");\n placeholder.textContent = node.getAttribute(\"data-placeholder-text\") || \"\";\n placeholder.style.cssText = `color:#666;font-size:12px;text-align:center;line-height:1.4;padding:0.5em;box-sizing:border-box;`;\n clone2.appendChild(placeholder);\n return clone2;\n }\n if (node.tagName === \"CANVAS\") {\n const dataURL = node.toDataURL();\n const img = document.createElement(\"img\");\n img.src = dataURL;\n img.width = node.width;\n img.height = node.height;\n cache.preNodeMap.set(img, node);\n inlineAllStyles(node, img, compress);\n return img;\n }\n let clone;\n try {\n clone = node.cloneNode(false);\n cache.preNodeMap.set(clone, node);\n } catch (err) {\n console.error(\"[Snapdom] Failed to clone node:\", node, err);\n throw err;\n }\n if (node instanceof HTMLTextAreaElement) {\n clone.textContent = node.value;\n clone.value = node.value;\n const rect = node.getBoundingClientRect();\n clone.style.width = `${rect.width}px`;\n clone.style.height = `${rect.height}px`;\n return clone;\n }\n if (node instanceof HTMLInputElement) {\n clone.value = node.value;\n clone.setAttribute(\"value\", node.value);\n if (node.checked !== void 0) {\n clone.checked = node.checked;\n if (node.checked) clone.setAttribute(\"checked\", \"\");\n if (node.indeterminate) clone.indeterminate = node.indeterminate;\n }\n }\n if (node instanceof HTMLSelectElement) {\n pendingSelectValue = node.value;\n }\n inlineAllStyles(node, clone, compress);\n if (node.shadowRoot) {\n const hasSlot = Array.from(node.shadowRoot.querySelectorAll(\"slot\")).length > 0;\n if (hasSlot) {\n for (const child of node.shadowRoot.childNodes) {\n if (child.nodeType === Node.ELEMENT_NODE && child.tagName === \"STYLE\") {\n const cssText = child.textContent || \"\";\n if (cssText.trim() && compress) {\n if (!cache.preStyle) cache.preStyle = new WeakMap();\n cache.preStyle.set(child, cssText);\n }\n }\n }\n } else {\n const shadowFrag = document.createDocumentFragment();\n for (const child of node.shadowRoot.childNodes) {\n if (child.nodeType === Node.ELEMENT_NODE && child.tagName === \"STYLE\") {\n const cssText = child.textContent || \"\";\n if (cssText.trim() && compress) {\n if (!cache.preStyle) cache.preStyle = new WeakMap();\n cache.preStyle.set(child, cssText);\n }\n continue;\n }\n const clonedChild = deepClone(child, compress, options, originalRoot || node);\n if (clonedChild) shadowFrag.appendChild(clonedChild);\n }\n clone.appendChild(shadowFrag);\n }\n }\n if (node.tagName === \"SLOT\") {\n const assigned = node.assignedNodes?.({ flatten: true }) || [];\n const nodesToClone = assigned.length > 0 ? assigned : Array.from(node.childNodes);\n const fragment = document.createDocumentFragment();\n for (const child of nodesToClone) {\n const clonedChild = deepClone(child, compress, options, originalRoot || node);\n if (clonedChild) fragment.appendChild(clonedChild);\n }\n return fragment;\n }\n for (const child of node.childNodes) {\n if (clonedAssignedNodes.has(child)) continue;\n const clonedChild = deepClone(child, compress, options, originalRoot || node);\n if (clonedChild) clone.appendChild(clonedChild);\n }\n if (pendingSelectValue !== null && clone instanceof HTMLSelectElement) {\n clone.value = pendingSelectValue;\n for (const opt of clone.options) {\n if (opt.value === pendingSelectValue) {\n opt.setAttribute(\"selected\", \"\");\n } else {\n opt.removeAttribute(\"selected\");\n }\n }\n }\n return clone;\n}", "code_description": null, "fill_type": "FUNCTION_TYPE", "language_type": "javascript", "sub_task_type": null}, "context_code": [["/snapdom/src/core/prepare.js", "/**\n * Prepares a deep clone of an element, inlining pseudo-elements and generating CSS classes.\n * @module prepare\n */\n\nimport { generateCSSClasses} from '../utils/cssTools.js';\nimport { stripTranslate} from '../utils/helpers.js';\nimport { deepClone } from './clone.js';\nimport { inlinePseudoElements } from '../modules/pseudo.js';\nimport { inlineExternalDef } from '../modules/svgDefs.js';\nimport { cache } from '../core/cache.js';\n\n/**\n * Prepares a clone of an element for capture, inlining pseudo-elements and generating CSS classes.\n *\n * @param {Element} element - Element to clone\n * @param {boolean} [compress=false] - Whether to compress style keys\n * @param {boolean} [embedFonts=false] - Whether to embed custom fonts\n * @param {Object} [options={}] - Capture options\n * @param {string[]} [options.exclude] - CSS selectors for elements to exclude\n * @param {Function} [options.filter] - Custom filter function\n * @returns {Promise} Object containing the clone, generated CSS, and style cache\n */\n\nexport async function prepareClone(element, compress = false, embedFonts = false, options = {}) {\n\n let clone\n let classCSS = '';\n try {\n clone = deepClone(element, compress, options, element);\n } catch (e) {\n console.warn(\"deepClone failed:\", e);\n throw e;\n }\n try {\n await inlinePseudoElements(element, clone, compress, embedFonts, options.useProxy);\n } catch (e) {\n console.warn(\"inlinePseudoElements failed:\", e);\n }\n try {\n inlineExternalDef(clone);\n } catch (e) {\n console.warn(\"inlineExternalDef failed:\", e);\n }\n if (compress) {\n const keyToClass = generateCSSClasses();\n classCSS = Array.from(keyToClass.entries()).map(([key, className]) => `.${className}{${key}}`).join(\"\");\n for (const [node, key] of cache.preStyleMap.entries()) {\n if (node.tagName === \"STYLE\") continue;\n const className = keyToClass.get(key);\n if (className) node.classList.add(className);\n const bgImage = node.style?.backgroundImage;\n node.removeAttribute(\"style\");\n if (bgImage && bgImage !== \"none\") node.style.backgroundImage = bgImage;\n }\n } else {\n for (const [node, key] of cache.preStyleMap.entries()) {\n if (node.tagName === \"STYLE\") continue;\n node.setAttribute(\"style\", key.replace(/;/g, \"; \"));\n }\n }\n for (const [cloneNode, originalNode] of cache.preNodeMap.entries()) {\n const scrollX = originalNode.scrollLeft;\n const scrollY = originalNode.scrollTop;\n const hasScroll = scrollX || scrollY;\n if (hasScroll && cloneNode instanceof HTMLElement) {\n cloneNode.style.overflow = \"hidden\";\n cloneNode.style.scrollbarWidth = \"none\";\n cloneNode.style.msOverflowStyle = \"none\";\n const inner = document.createElement(\"div\");\n inner.style.transform = `translate(${-scrollX}px, ${-scrollY}px)`;\n inner.style.willChange = \"transform\";\n inner.style.display = \"inline-block\";\n inner.style.width = \"100%\";\n while (cloneNode.firstChild) {\n inner.appendChild(cloneNode.firstChild);\n }\n cloneNode.appendChild(inner);\n }\n }\n if (element === cache.preNodeMap.get(clone)) {\n const computed = cache.preStyle.get(element) || window.getComputedStyle(element);\n cache.preStyle.set(element, computed);\n const transform = stripTranslate(computed.transform);\n clone.style.margin = \"0\";\n clone.style.position = \"static\";\n clone.style.top = \"auto\";\n clone.style.left = \"auto\";\n clone.style.right = \"auto\";\n clone.style.bottom = \"auto\";\n clone.style.zIndex = \"auto\";\n clone.style.float = \"none\";\n clone.style.clear = \"none\";\n clone.style.transform = transform || \"\";\n }\n for (const [cloneNode, originalNode] of cache.preNodeMap.entries()) {\n if (originalNode.tagName === \"PRE\") {\n cloneNode.style.marginTop = \"0\";\n cloneNode.style.marginBlockStart = \"0\";\n }\n }\n return { clone, classCSS };\n}\n"], ["/snapdom/src/modules/pseudo.js", "/**\n * Utilities for inlining ::before and ::after pseudo-elements.\n * @module pseudo\n */\n\nimport { getStyle, snapshotComputedStyle, parseContent, extractURL, safeEncodeURI, fetchImage, inlineSingleBackgroundEntry, splitBackgroundImage } from '../utils/helpers.js';\nimport { getStyleKey } from '../utils/cssTools.js';\nimport { iconToImage } from '../modules/fonts.js';\nimport { isIconFont } from '../modules/iconFonts.js';\nimport { cache } from '../core/cache.js'\n\n/**\n * Creates elements to represent ::before, ::after, and ::first-letter pseudo-elements, inlining their styles and content.\n *\n * @param {Element} source - Original element\n * @param {Element} clone - Cloned element\n * @param {boolean} compress - Whether to compress style keys\n * @param {boolean} embedFonts - Whether to embed icon fonts as images\n * @returns {Promise} Promise that resolves when all pseudo-elements are processed\n */\n\nexport async function inlinePseudoElements(source, clone, compress, embedFonts = false, useProxy) {\n if (!(source instanceof Element) || !(clone instanceof Element)) return;\n for (const pseudo of [\"::before\", \"::after\", \"::first-letter\"]) {\n try {\n const style = getStyle(source, pseudo);\n if (!style || typeof style[Symbol.iterator] !== \"function\") continue;\n if (pseudo === \"::first-letter\") {\n const normal = getComputedStyle(source);\n const isMeaningful = style.color !== normal.color || style.fontSize !== normal.fontSize || style.fontWeight !== normal.fontWeight;\n if (!isMeaningful) continue;\n const textNode = Array.from(clone.childNodes).find(\n (n) => n.nodeType === Node.TEXT_NODE && n.textContent && n.textContent.trim().length > 0\n );\n if (!textNode) continue;\n const text = textNode.textContent;\n const match = text.match(/^([^\\p{L}\\p{N}\\s]*[\\p{L}\\p{N}](?:['’])?)/u);\n const first = match?.[0];\n const rest = text.slice(first?.length || 0);\n if (!first || /[\\uD800-\\uDFFF]/.test(first)) continue;\n const span = document.createElement(\"span\");\n span.textContent = first;\n span.dataset.snapdomPseudo = \"::first-letter\";\n const snapshot = snapshotComputedStyle(style);\n const key = getStyleKey(snapshot, \"span\", compress);\n cache.preStyleMap.set(span, key);\n const restNode = document.createTextNode(rest);\n clone.replaceChild(restNode, textNode);\n clone.insertBefore(span, restNode);\n continue;\n }\nconst content = style.getPropertyValue(\"content\");\nconst bg = style.getPropertyValue(\"background-image\");\nconst bgColor = style.getPropertyValue(\"background-color\");\n\nconst fontFamily = style.getPropertyValue(\"font-family\");\nconst fontSize = parseInt(style.getPropertyValue(\"font-size\")) || 32;\nconst fontWeight = parseInt(style.getPropertyValue(\"font-weight\")) || false;\nconst color = style.getPropertyValue(\"color\") || \"#000\";\nconst display = style.getPropertyValue(\"display\");\nconst width = parseFloat(style.getPropertyValue(\"width\"));\nconst height = parseFloat(style.getPropertyValue(\"height\"));\nconst borderStyle = style.getPropertyValue(\"border-style\");\nconst transform = style.getPropertyValue(\"transform\");\n\nconst isIconFont2 = isIconFont(fontFamily);\n\n// Detect counter() || counters()\nlet cleanContent;\nif (/counter\\s*\\(|counters\\s*\\(/.test(content)) {\n cleanContent = \"- \";\n} else {\n cleanContent = parseContent(content);\n}\n\nconst hasContent = content !== \"none\";\nconst hasExplicitContent = hasContent && cleanContent !== \"\";\nconst hasBg = bg && bg !== \"none\";\nconst hasBgColor = bgColor && bgColor !== \"transparent\" && bgColor !== \"rgba(0, 0, 0, 0)\";\nconst hasBox = display !== \"inline\" && (width > 0 || height > 0);\nconst hasBorder = borderStyle && borderStyle !== \"none\";\nconst hasTransform = transform && transform !== \"none\";\n\nconst shouldRender =\n hasExplicitContent || hasBg || hasBgColor || hasBox || hasBorder || hasTransform;\n\nif (!shouldRender) continue;\n\nconst pseudoEl = document.createElement(\"span\");\npseudoEl.dataset.snapdomPseudo = pseudo;\nconst snapshot = snapshotComputedStyle(style);\nconst key = getStyleKey(snapshot, \"span\", compress);\ncache.preStyleMap.set(pseudoEl, key);\n\nif (isIconFont2 && cleanContent.length === 1) {\n const imgEl = document.createElement(\"img\");\n imgEl.src = await iconToImage(cleanContent, fontFamily, fontWeight, fontSize, color);\n imgEl.style = `width:${fontSize}px;height:auto;object-fit:contain;`;\n pseudoEl.appendChild(imgEl);\n} else if (cleanContent.startsWith(\"url(\")) {\n const rawUrl = extractURL(cleanContent);\n if (rawUrl && rawUrl.trim() !== \"\") {\n try {\n const imgEl = document.createElement(\"img\");\n const dataUrl = await fetchImage(safeEncodeURI(rawUrl, { useProxy }));\n imgEl.src = dataUrl;\n imgEl.style = `width:${fontSize}px;height:auto;object-fit:contain;`;\n pseudoEl.appendChild(imgEl);\n } catch (e) {\n console.error(`[snapdom] Error in pseudo ${pseudo} for`, source, e);\n }\n }\n} else if (!isIconFont2 && hasExplicitContent) {\n pseudoEl.textContent = cleanContent;\n}\n\nif (hasBg) {\n try {\n const bgSplits = splitBackgroundImage(bg);\n const newBgParts = await Promise.all(\n bgSplits.map((entry) => inlineSingleBackgroundEntry(entry))\n );\n pseudoEl.style.backgroundImage = newBgParts.join(\", \");\n } catch (e) {\n console.warn(`[snapdom] Failed to inline background-image for ${pseudo}`, e);\n }\n}\n\nif (hasBgColor) pseudoEl.style.backgroundColor = bgColor;\n\nconst hasContent2 =\n pseudoEl.childNodes.length > 0 ||\n (pseudoEl.textContent && pseudoEl.textContent.trim() !== \"\");\nconst hasVisibleBox = hasContent2 || hasBg || hasBgColor || hasBox || hasBorder || hasTransform;\n\nif (!hasVisibleBox) continue;\n\npseudo === \"::before\"\n ? clone.insertBefore(pseudoEl, clone.firstChild)\n : clone.appendChild(pseudoEl);\n\n } catch (e) {\n console.warn(`[snapdom] Failed to capture ${pseudo} for`, source, e);\n }\n }\n const sChildren = Array.from(source.children);\n const cChildren = Array.from(clone.children).filter((child) => !child.dataset.snapdomPseudo);\n for (let i = 0; i < Math.min(sChildren.length, cChildren.length); i++) {\n await inlinePseudoElements(\n sChildren[i],\n cChildren[i],\n compress,\n embedFonts,\n useProxy\n );\n }\n}\n"], ["/snapdom/src/modules/fonts.js", "/**\n * Utilities for handling and embedding web fonts and icon fonts.\n * @module fonts\n */\n\nimport { extractURL} from \"../utils/helpers\"\nimport { cache } from \"../core/cache\"\nimport { isIconFont } from '../modules/iconFonts.js';\n\n/**\n * Converts a unicode character from an icon font into a data URL image.\n *\n * @export\n * @param {string} unicodeChar - The unicode character to render\n * @param {string} fontFamily - The font family name\n * @param {string|number} fontWeight - The font weight\n * @param {number} [fontSize=32] - The font size in pixels\n * @param {string} [color=\"#000\"] - The color to use\n * @returns {Promise} Data URL of the rendered icon\n */\n\nexport async function iconToImage(unicodeChar, fontFamily, fontWeight, fontSize = 32, color = \"#000\") {\n fontFamily = fontFamily.replace(/^['\"]+|['\"]+$/g, \"\");\n const dpr = window.devicePixelRatio || 1;\n\n // Create temporary context to measure\n const tempCanvas = document.createElement(\"canvas\");\n const tempCtx = tempCanvas.getContext(\"2d\");\n tempCtx.font = fontWeight\n ? `${fontWeight} ${fontSize}px \"${fontFamily}\"`\n : `${fontSize}px \"${fontFamily}\"`;\n\n const metrics = tempCtx.measureText(unicodeChar);\n const ascent = metrics.actualBoundingBoxAscent || fontSize * 0.8;\n const descent = metrics.actualBoundingBoxDescent || fontSize * 0.2;\n const height = ascent + descent;\n const width = metrics.width;\n\n const canvas = document.createElement(\"canvas\");\n canvas.width = Math.ceil(width * dpr);\n canvas.height = Math.ceil(height * dpr);\n\n const ctx = canvas.getContext(\"2d\");\n ctx.scale(dpr, dpr);\n ctx.font = tempCtx.font;\n ctx.textAlign = \"left\";\n ctx.textBaseline = \"alphabetic\"; // aligns with baseline\n ctx.fillStyle = color;\n\n // Draw at (0, ascent) so the full glyph fits vertically\n ctx.fillText(unicodeChar, 0, ascent);\n\n return canvas.toDataURL();\n}\n\n\nfunction isStylesheetLoaded(href) {\n return Array.from(document.styleSheets).some(sheet => sheet.href === href);\n}\n\nfunction injectLinkIfMissing(href) {\n return new Promise((resolve) => {\n if (isStylesheetLoaded(href)) return resolve(null);\n const link = document.createElement(\"link\");\n link.rel = \"stylesheet\";\n link.href = href;\n link.setAttribute(\"data-snapdom\", \"injected-import\");\n link.onload = () => resolve(link);\n link.onerror = () => resolve(null);\n document.head.appendChild(link);\n });\n}\n\n/**\n * Embeds custom fonts found in the document as data URLs in CSS.\n *\n * @export\n * @param {Object} options\n * @param {boolean} [options.preCached=false] - Whether to use pre-cached resources\n * @returns {Promise} The inlined CSS for custom fonts\n */\n\nexport async function embedCustomFonts({preCached = false } = {}) {\n if (cache.resource.has(\"fonts-embed-css\")) {\n if (preCached) {\n const style = document.createElement(\"style\");\n style.setAttribute(\"data-snapdom\", \"embedFonts\");\n style.textContent = cache.resource.get(\"fonts-embed-css\");\n document.head.appendChild(style);\n }\n return cache.resource.get(\"fonts-embed-css\");\n }\n\n const importRegex = /@import\\s+url\\([\"']?([^\"')]+)[\"']?\\)/g;\n const styleImports = [];\n\n for (const styleTag of document.querySelectorAll(\"style\")) {\n const cssText = styleTag.textContent || \"\";\n const matches = Array.from(cssText.matchAll(importRegex));\n for (const match of matches) {\n const importUrl = match[1];\n if (isIconFont(importUrl)) continue;\n if (!isStylesheetLoaded(importUrl)) {\n styleImports.push(importUrl);\n }\n }\n }\n\n await Promise.all(styleImports.map(injectLinkIfMissing));\n\n const links = Array.from(document.querySelectorAll('link[rel=\"stylesheet\"]')).filter((link) => link.href);\n let finalCSS = \"\";\n\n for (const link of links) {\n try {\n const res = await fetch(link.href);\n const cssText = await res.text();\n\n if ((isIconFont(link.href) || isIconFont(cssText))) continue;\n\n const urlRegex = /url\\(([\"']?)([^\"')]+)\\1\\)/g;\n const inlinedCSS = await Promise.all(\n Array.from(cssText.matchAll(urlRegex)).map(async (match) => {\n let rawUrl = extractURL(match[0]);\n if (!rawUrl) return null;\n let url = rawUrl;\n if (!url.startsWith(\"http\") && !url.startsWith(\"data:\")) {\n url = new URL(url, link.href).href;\n }\n if (isIconFont(url)) return null;\n if (cache.resource.has(url)) {\n cache.font.add(url);\n return { original: match[0], inlined: `url(${cache.resource.get(url)})` };\n }\n if (cache.font.has(url)) return null;\n try {\n const fontRes = await fetch(url);\n const blob = await fontRes.blob();\n const b64 = await new Promise((resolve) => {\n const reader = new FileReader();\n reader.onload = () => resolve(reader.result);\n reader.readAsDataURL(blob);\n });\n cache.resource.set(url, b64);\n cache.font.add(url);\n return { original: match[0], inlined: `url(${b64})` };\n } catch (e) {\n console.warn(\"[snapdom] Failed to fetch font resource:\", url);\n return null;\n }\n })\n );\n\n let cssFinal = cssText;\n for (const r of inlinedCSS) {\n if (r) cssFinal = cssFinal.replace(r.original, r.inlined);\n }\n finalCSS += cssFinal + \"\\n\";\n } catch (e) {\n console.warn(\"[snapdom] Failed to fetch CSS:\", link.href);\n }\n }\n\n for (const sheet of document.styleSheets) {\n try {\n if (!sheet.href || links.every((link) => link.href !== sheet.href)) {\n for (const rule of sheet.cssRules) {\n if (rule.type === CSSRule.FONT_FACE_RULE) {\n const src = rule.style.getPropertyValue(\"src\");\n const family = rule.style.getPropertyValue(\"font-family\");\n if (!src || isIconFont(family)) continue;\n\n const urlRegex = /url\\(([\"']?)([^\"')]+)\\1\\)/g;\n const localRegex = /local\\(([\"']?)[^)]+?\\1\\)/g;\n const hasURL = !!src.match(urlRegex);\n const hasLocal = !!src.match(localRegex);\n\n if (!hasURL && hasLocal) {\n // Solo local(), conservar en línea compacta\n finalCSS += `@font-face{font-family:${family};src:${src};font-style:${rule.style.getPropertyValue(\"font-style\") || \"normal\"};font-weight:${rule.style.getPropertyValue(\"font-weight\") || \"normal\"};}`;\n continue;\n }\n\n // Embebido para src con url()\n let inlinedSrc = src;\n const matches = Array.from(src.matchAll(urlRegex));\n for (const match of matches) {\n let rawUrl = match[2].trim();\n if (!rawUrl) continue;\n let url = rawUrl;\n if (!url.startsWith(\"http\") && !url.startsWith(\"data:\")) {\n url = new URL(url, sheet.href || location.href).href;\n }\n if (isIconFont(url)) continue;\n if (cache.resource.has(url)) {\n cache.font.add(url);\n inlinedSrc = inlinedSrc.replace(match[0], `url(${cache.resource.get(url)})`);\n continue;\n }\n if (cache.font.has(url)) continue;\n try {\n const res = await fetch(url);\n const blob = await res.blob();\n const b64 = await new Promise((resolve) => {\n const reader = new FileReader();\n reader.onload = () => resolve(reader.result);\n reader.readAsDataURL(blob);\n });\n cache.resource.set(url, b64);\n cache.font.add(url);\n inlinedSrc = inlinedSrc.replace(match[0], `url(${b64})`);\n } catch (e) {\n console.warn(\"[snapdom] Failed to fetch font URL:\", url);\n }\n }\n\n finalCSS += `@font-face{font-family:${family};src:${inlinedSrc};font-style:${rule.style.getPropertyValue(\"font-style\") || \"normal\"};font-weight:${rule.style.getPropertyValue(\"font-weight\") || \"normal\"};}`;\n }\n }\n }\n } catch (e) {\n console.warn(\"[snapdom] Cannot access stylesheet\", sheet.href, e);\n }\n }\n\n for (const font of document.fonts) {\n if (font.family && font.status === \"loaded\" && font._snapdomSrc) {\n if (isIconFont(font.family)) continue;\n let b64 = font._snapdomSrc;\n if (!b64.startsWith(\"data:\")) {\n if (cache.resource.has(font._snapdomSrc)) {\n b64 = cache.resource.get(font._snapdomSrc);\n cache.font.add(font._snapdomSrc);\n } else if (!cache.font.has(font._snapdomSrc)) {\n try {\n const res = await fetch(font._snapdomSrc);\n const blob = await res.blob();\n b64 = await new Promise((resolve) => {\n const reader = new FileReader();\n reader.onload = () => resolve(reader.result);\n reader.readAsDataURL(blob);\n });\n cache.resource.set(font._snapdomSrc, b64);\n cache.font.add(font._snapdomSrc);\n } catch (e) {\n console.warn(\"[snapdom] Failed to fetch dynamic font src:\", font._snapdomSrc);\n continue;\n }\n }\n }\n\n finalCSS += `@font-face{font-family:'${font.family}';src:url(${b64});font-style:${font.style || \"normal\"};font-weight:${font.weight || \"normal\"};}`;\n }\n }\n\n if (finalCSS) {\n cache.resource.set(\"fonts-embed-css\", finalCSS);\n if (preCached) {\n const style = document.createElement(\"style\");\n style.setAttribute(\"data-snapdom\", \"embedFonts\");\n style.textContent = finalCSS;\n document.head.appendChild(style);\n }\n }\n\n return finalCSS;\n}\n"], ["/snapdom/src/core/capture.js", "/**\n * Core logic for capturing DOM elements as SVG data URLs.\n * @module capture\n */\n\nimport { prepareClone } from './prepare.js';\nimport { inlineImages } from '../modules/images.js';\nimport { inlineBackgroundImages } from '../modules/background.js';\nimport { idle, isSafari } from '../utils/helpers.js';\nimport { collectUsedTagNames, generateDedupedBaseCSS } from '../utils/cssTools.js';\nimport { embedCustomFonts } from '../modules/fonts.js';\nimport { cache } from '../core/cache.js'\n\n/**\n * Captures an HTML element as an SVG data URL, inlining styles, images, backgrounds, and optionally fonts.\n *\n * @param {Element} element - DOM element to capture\n * @param {Object} [options={}] - Capture options\n * @param {boolean} [options.compress=true] - Whether to compress style keys\n * @param {boolean} [options.embedFonts=false] - Whether to embed custom fonts\n * @param {boolean} [options.fast=true] - Whether to skip idle delay for faster results\n * @param {number} [options.scale=1] - Output scale multiplier\n * @param {string[]} [options.exclude] - CSS selectors for elements to exclude\n * @param {Function} [options.filter] - Custom filter function \n * @returns {Promise} Promise that resolves to an SVG data URL\n */\n\nexport async function captureDOM(element, options = {}) {\n if (!element) throw new Error(\"Element cannot be null or undefined\");\n cache.reset()\n const { compress = true, embedFonts = false, fast = true, scale = 1, useProxy = ''} = options;\n let clone, classCSS;\n let fontsCSS = \"\";\n let baseCSS = \"\";\n let dataURL;\n let svgString;\n\n ({ clone, classCSS } = await prepareClone(element, compress, embedFonts, options));\n\n await new Promise((resolve) => {\n idle(async () => {\n await inlineImages(clone, options);\n resolve();\n }, { fast });\n });\n await new Promise((resolve) => {\n idle(async () => {\n await inlineBackgroundImages(element, clone, options);\n resolve();\n }, { fast });\n });\n if (embedFonts) {\n await new Promise((resolve) => {\n idle(async () => {\n fontsCSS = await embedCustomFonts();\n resolve();\n }, { fast });\n });\n }\n if (compress) {\n const usedTags = collectUsedTagNames(clone).sort();\n const tagKey = usedTags.join(\",\");\n if (cache.baseStyle.has(tagKey)) {\n baseCSS = cache.baseStyle.get(tagKey);\n } else {\n await new Promise((resolve) => {\n idle(() => {\n baseCSS = generateDedupedBaseCSS(usedTags);\n cache.baseStyle.set(tagKey, baseCSS);\n resolve();\n }, { fast });\n });\n }\n }\n await new Promise((resolve) => {\n idle(() => {\n const rect = element.getBoundingClientRect();\n let w = rect.width;\n let h = rect.height;\n const hasW = Number.isFinite(options.width);\n const hasH = Number.isFinite(options.height);\n const hasScale = typeof scale === \"number\" && scale !== 1;\n if (!hasScale) {\n const aspect = rect.width / rect.height;\n if (hasW && hasH) {\n w = options.width;\n h = options.height;\n } else if (hasW) {\n w = options.width;\n h = w / aspect;\n } else if (hasH) {\n h = options.height;\n w = h * aspect;\n }\n }\n w = Math.ceil(w);\n h = Math.ceil(h);\n clone.setAttribute(\"xmlns\", \"http://www.w3.org/1999/xhtml\");\n clone.style.transformOrigin = \"top left\";\n if (!hasScale && (hasW || hasH)) {\n const originalW = rect.width;\n const originalH = rect.height;\n const scaleX = w / originalW;\n const scaleY = h / originalH;\n const existingTransform = clone.style.transform || \"\";\n const scaleTransform = `scale(${scaleX}, ${scaleY})`;\n clone.style.transform = `${scaleTransform} ${existingTransform}`.trim();\n }\n const svgNS = \"http://www.w3.org/2000/svg\";\n const fo = document.createElementNS(svgNS, \"foreignObject\");\n fo.setAttribute(\"width\", \"100%\");\n fo.setAttribute(\"height\", \"100%\");\n const styleTag = document.createElement(\"style\");\n styleTag.textContent = baseCSS + fontsCSS + \"svg{overflow:visible;}\" + classCSS;\n fo.appendChild(styleTag);\n fo.appendChild(clone);\n const serializer = new XMLSerializer();\n const foString = serializer.serializeToString(fo);\n const svgHeader = ``;\n const svgFooter = \"\";\n svgString = svgHeader + foString + svgFooter;\n dataURL = `data:image/svg+xml;charset=utf-8,${encodeURIComponent(svgString)}`;\n resolve();\n }, { fast });\n });\n const sandbox = document.getElementById(\"snapdom-sandbox\");\n if (sandbox && sandbox.style.position === \"absolute\") sandbox.remove();\n return dataURL;\n}\n\n"], ["/snapdom/src/utils/cssTools.js", "/**\n * Utilities for working with CSS styles, defaults, and class generation.\n * @module cssTools\n */\n\nimport { cache } from \"../core/cache\"\n\nconst commonTags = [\n 'div', 'span', 'p', 'a', 'img', 'ul', 'li', 'button', 'input',\n 'select', 'textarea', 'label', 'section', 'article', 'header',\n 'footer', 'nav', 'main', 'aside', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6',\n 'svg', 'path', 'circle', 'rect', 'line', 'g', 'table', 'thead', 'tbody', 'tr', 'td', 'th'\n];\n\nexport function precacheCommonTags() {\n for (let tag of commonTags) {\n getDefaultStyleForTag(tag);\n }\n}\n/**\n * Retrieves default CSS property values from a temporary element.\n *\n * @param {string} tagName - The tag name to get default styles for\n * @returns {Object} Object containing default values for all CSS properties\n */\nexport function getDefaultStyleForTag(tagName) {\n if (cache.defaultStyle.has(tagName)) {\n return cache.defaultStyle.get(tagName);\n }\n\n const skipTags = new Set(['script', 'style', 'meta', 'link', 'noscript', 'template']);\n if (skipTags.has(tagName)) {\n const empty = {}; \n cache.defaultStyle.set(tagName, empty); \n return empty;\n }\n\n let sandbox = document.getElementById('snapdom-sandbox');\n if (!sandbox) {\n sandbox = document.createElement('div');\n sandbox.id = 'snapdom-sandbox';\n sandbox.style.position = 'absolute';\n sandbox.style.left = '-9999px';\n sandbox.style.top = '-9999px';\n sandbox.style.width = '0';\n sandbox.style.height = '0';\n sandbox.style.overflow = 'hidden';\n document.body.appendChild(sandbox);\n }\n\n const el = document.createElement(tagName);\n el.style.all = 'initial';\n sandbox.appendChild(el);\n\n const styles = getComputedStyle(el);\n const defaults = {};\n for (let prop of styles) {\n defaults[prop] = styles.getPropertyValue(prop);\n }\n\n sandbox.removeChild(el);\n cache.defaultStyle.set(tagName, defaults);\n return defaults;\n}\n\n/**\n * Creates a unique key from an element's computed style that differs from defaults.\n *\n * @param {Object} snapshot - Computed style snapshot\n * @param {string} tagName - The tag name of the element\n * @param {boolean} [compress=false] - Whether to compress style keys\n * @returns {string} Semi-colon separated list of non-default properties\n */\n\nexport function getStyleKey(snapshot, tagName, compress = false) {\n const entries = [];\n const defaultStyles = getDefaultStyleForTag(tagName);\n for (let [prop, value] of Object.entries(snapshot)) {\n if (!compress) {\n if (value) {\n entries.push(`${prop}:${value}`);\n }\n } else {\n const defaultValue = defaultStyles[prop];\n if (value && value !== defaultValue) {\n entries.push(`${prop}:${value}`);\n }\n }\n }\n\n return entries.sort().join(\";\");\n}\n\n/**\n * Collects all unique tag names used in the DOM tree rooted at the given node.\n *\n * @param {Node} root - The root node to search\n * @returns {string[]} Array of unique tag names\n */\nexport function collectUsedTagNames(root) {\n const tagSet = new Set();\n if (root.nodeType !== Node.ELEMENT_NODE && root.nodeType !== Node.DOCUMENT_FRAGMENT_NODE) {\n return [];\n }\n if (root.tagName) {\n tagSet.add(root.tagName.toLowerCase());\n }\n if (typeof root.querySelectorAll === 'function') {\n root.querySelectorAll(\"*\").forEach(el => tagSet.add(el.tagName.toLowerCase()));\n }\n return Array.from(tagSet);\n}\n\n/**\n * Generates deduplicated base CSS for the given tag names.\n *\n * @param {string[]} usedTagNames - Array of tag names\n * @returns {string} CSS string\n */\nexport function generateDedupedBaseCSS(usedTagNames) {\n const groups = new Map();\n\n for (let tagName of usedTagNames) {\n const styles = cache.defaultStyle.get(tagName);\n if (!styles) continue;\n\n // Creamos la \"firma\" del bloque CSS para comparar\n const key = Object.entries(styles)\n .map(([k, v]) => `${k}:${v};`)\n .sort()\n .join('');\n\n // Agrupamos por firma\n if (!groups.has(key)) {\n groups.set(key, []);\n }\n groups.get(key).push(tagName);\n }\n\n // Ahora generamos el CSS optimizado\n let css = '';\n for (let [styleBlock, tagList] of groups.entries()) {\n css += `${tagList.join(',')} { ${styleBlock} }\\n`;\n }\n\n return css;\n}\n/**\n * Generates CSS classes from a style map.\n *\n * @returns {Map} Map of style keys to class names\n */\nexport function generateCSSClasses() {\n const keySet = new Set(cache.preStyleMap.values());\n const classMap = new Map();\n let counter = 1;\n for (const key of keySet) {\n classMap.set(key, `c${counter++}`);\n }\n return classMap;\n}\n"], ["/snapdom/src/utils/helpers.js", "import { cache } from \"../core/cache\";\n\n/**\n * Fetches and inlines a single background-image entry to a data URL (with caching).\n * - If entry is a gradient or \"none\", returns unchanged.\n * - If entry is a url(...), fetches the image as data URL and caches it.\n *\n * @param {string} entry - Single background-image entry (e.g., \"url(...)\").\n * @param {Object} [options={}] - Options like crossOrigin.\n * @param {boolean} [options.skipInline=false] - If true, only fetches & caches, doesn't return a replacement.\n * @returns {Promise} - The processed entry (unless skipInline is true).\n */\nexport async function inlineSingleBackgroundEntry(entry, options = {}) {\n const rawUrl = extractURL(entry)\n\n const isGradient = /^((repeating-)?(linear|radial|conic)-gradient)\\(/i.test(entry);\n \n if (rawUrl) {\n const encodedUrl = safeEncodeURI(rawUrl);\n if (cache.background.has(encodedUrl)) {\n return options.skipInline ? void 0 : `url(${cache.background.get(encodedUrl)})`;\n } else {\n const dataUrl = await fetchImage(encodedUrl, { useProxy: options.useProxy });\n cache.background.set(encodedUrl, dataUrl);\n return options.skipInline ? void 0 : `url(\"${dataUrl}\")`;\n }\n }\n\n if (isGradient || entry === \"none\") {\n return entry;\n }\n\n return entry;\n}\n\n\n/**\n * Creates a promise that resolves after the specified delay\n * @param {number} [ms=0] - Milliseconds to delay\n * @returns {Promise} Promise that resolves after the delay\n */\n\nexport function idle(fn, { fast = false } = {}) {\n if (fast) return fn();\n if ('requestIdleCallback' in window) {\n requestIdleCallback(fn, { timeout: 50 });\n } else {\n setTimeout(fn, 1);\n }\n}\n/**\n * Gets the computed style for an element or pseudo-element, with caching.\n *\n * @param {Element} el - The element\n * @param {string|null} [pseudo=null] - The pseudo-element\n * @returns {CSSStyleDeclaration} The computed style\n */\nexport function getStyle(el, pseudo = null) {\n if (!(el instanceof Element)) {\n return window.getComputedStyle(el, pseudo);\n }\n\n let map = cache.computedStyle.get(el);\n if (!map) {\n map = new Map();\n cache.computedStyle.set(el, map);\n }\n\n if (!map.has(pseudo)) {\n const st = window.getComputedStyle(el, pseudo);\n map.set(pseudo, st);\n }\n\n return map.get(pseudo);\n}\n/**\n * Parses the CSS content property value, handling unicode escapes.\n *\n * @param {string} content - The CSS content value\n * @returns {string} The parsed content\n */\nexport function parseContent(content) {\n let clean = content.replace(/^['\"]|['\"]$/g, \"\");\n if (clean.startsWith(\"\\\\\")) {\n try {\n return String.fromCharCode(parseInt(clean.replace(\"\\\\\", \"\"), 16));\n } catch {\n return clean;\n }\n }\n return clean;\n}\n/**\n * Extracts a URL from a CSS value like background-image.\n *\n * @param {string} value - The CSS value\n * @returns {string|null} The extracted URL or null\n */\n\nexport function extractURL(value) {\n const match = value.match(/url\\((['\"]?)(.*?)(\\1)\\)/);\n if (!match) return null;\n\n const url = match[2].trim();\n if (url.startsWith('#')) return null;\n return url;\n}\n\n/**\n * Determines if a font family or URL is an icon font.\n *\n * @param {string} familyOrUrl - The font family or URL\n * @returns {boolean} True if it is an icon font\n */\nexport function isIconFont(familyOrUrl) {\n const iconFontPatterns = [\n /font\\s*awesome/i,\n /material\\s*icons/i,\n /ionicons/i,\n /glyphicons/i,\n /feather/i,\n /bootstrap\\s*icons/i,\n /remix\\s*icons/i,\n /heroicons/i,\n /layui/i,\n /lucide/i\n ];\n return iconFontPatterns.some(rx => rx.test(familyOrUrl));\n}\n/**\n *\n *\n * @export\n * @param {*} src\n * @param {number} [timeout=3000]\n * @return {*} \n */\n\nexport function fetchImage(src, { timeout = 3000, useProxy = '' } = {}) {\n function getCrossOriginMode(url) {\n try {\n const parsed = new URL(url, window.location.href);\n return parsed.origin === window.location.origin ? \"use-credentials\" : \"anonymous\";\n } catch {\n return \"anonymous\";\n }\n }\n\n // Función común para fallback vía fetch + proxy\n async function fetchWithFallback(url) {\n const fetchBlobAsDataURL = (fetchUrl) =>\n fetch(fetchUrl, {\n mode: \"cors\",\n credentials: getCrossOriginMode(fetchUrl) === \"use-credentials\" ? \"include\" : \"omit\",\n })\n .then(r => r.blob())\n .then(blob => new Promise((resolve, reject) => {\n const reader = new FileReader();\n reader.onloadend = () => {\n const base64 = reader.result;\n if (typeof base64 !== \"string\" || !base64.startsWith(\"data:image/\")) {\n reject(new Error(\"Invalid image data URL\"));\n return;\n }\n resolve(base64);\n };\n reader.onerror = () => reject(new Error(\"FileReader error\"));\n reader.readAsDataURL(blob);\n }));\n\n try {\n return await fetchBlobAsDataURL(url);\n } catch (e) {\n if (useProxy && typeof useProxy === \"string\") {\n const proxied = useProxy.replace(/\\/$/, \"\") + safeEncodeURI(url);\n try {\n return await fetchBlobAsDataURL(proxied);\n } catch {\n \n throw new Error(\"[SnapDOM - fetchImage] CORS restrictions prevented image capture (even via proxy)\");\n }\n } else {\n \n throw new Error(\"[SnapDOM - fetchImage] Fetch fallback failed and no proxy provided\");\n }\n }\n }\n\n const crossOriginValue = getCrossOriginMode(src);\n\n if (cache.image.has(src)) {\n return Promise.resolve(cache.image.get(src));\n }\n\n // Detectamos si es un data URI, si sí, devolvemos directo sin fetch\n const isDataURI = src.startsWith(\"data:image/\");\n if (isDataURI) {\n cache.image.set(src, src);\n return Promise.resolve(src);\n }\n\n // Mejor detección SVG, incluyendo query strings\n const isSVG = /\\.svg(\\?.*)?$/i.test(src);\n\n if (isSVG) {\n return (async () => {\n try {\n const response = await fetch(src, {\n mode: \"cors\",\n credentials: crossOriginValue === \"use-credentials\" ? \"include\" : \"omit\"\n });\n const svgText = await response.text();\n const encoded = `data:image/svg+xml;charset=utf-8,${encodeURIComponent(svgText)}`;\n cache.image.set(src, encoded);\n return encoded;\n } catch {\n return fetchWithFallback(src);\n }\n })();\n }\n\n return new Promise((resolve, reject) => {\n const timeoutId = setTimeout(() => {\n reject(new Error(\"[SnapDOM - fetchImage] Image load timed out\"));\n }, timeout);\n\n const image = new Image();\n image.crossOrigin = crossOriginValue;\n\n image.onload = async () => {\n clearTimeout(timeoutId);\n try {\n await image.decode();\n const canvas = document.createElement(\"canvas\");\n canvas.width = image.width;\n canvas.height = image.height;\n const ctx = canvas.getContext(\"2d\");\n ctx.drawImage(image, 0, 0, canvas.width, canvas.height);\n const dataURL = canvas.toDataURL(\"image/png\");\n cache.image.set(src, dataURL);\n resolve(dataURL);\n } catch {\n try {\n const fallbackDataURL = await fetchWithFallback(src);\n cache.image.set(src, fallbackDataURL);\n resolve(fallbackDataURL);\n } catch (e) {\n reject(e);\n }\n }\n };\n\n image.onerror = async () => {\n clearTimeout(timeoutId);\n console.error(`[SnapDOM - fetchImage] Image failed to load: ${src}`);\n try {\n const fallbackDataURL = await fetchWithFallback(src);\n cache.image.set(src, fallbackDataURL);\n resolve(fallbackDataURL);\n } catch (e) {\n reject(e);\n }\n };\n\n image.src = src;\n });\n}\n\n/**\n *\n *\n * @export\n * @param {*} style\n * @return {*} \n */\nexport function snapshotComputedStyle(style) {\n const snap = {};\n for (let prop of style) {\n snap[prop] = style.getPropertyValue(prop);\n }\n return snap;\n}\n\nexport function isSafari() {\n return /^((?!chrome|android).)*safari/i.test(navigator.userAgent);\n}\n\nexport function stripTranslate(transform) {\n if (!transform || transform === 'none') return '';\n\n let cleaned = transform.replace(/translate[XY]?\\([^)]*\\)/g, '');\n\n cleaned = cleaned.replace(/matrix\\(([^)]+)\\)/g, (_, values) => {\n const parts = values.split(',').map(s => s.trim());\n if (parts.length !== 6) return `matrix(${values})`;\n parts[4] = '0';\n parts[5] = '0';\n return `matrix(${parts.join(', ')})`;\n });\n\n cleaned = cleaned.replace(/matrix3d\\(([^)]+)\\)/g, (_, values) => {\n const parts = values.split(',').map(s => s.trim());\n if (parts.length !== 16) return `matrix3d(${values})`;\n parts[12] = '0';\n parts[13] = '0';\n return `matrix3d(${parts.join(', ')})`;\n });\n\n return cleaned.trim().replace(/\\s{2,}/g, ' ');\n}\n\nexport function safeEncodeURI(uri) {\n if (/%[0-9A-Fa-f]{2}/.test(uri)) return uri; // prevent reencode\n try {\n return encodeURI(uri);\n } catch {\n return uri;\n }\n}\n\nexport function splitBackgroundImage(bg) {\n const parts = [];\n let depth = 0;\n let lastIndex = 0;\n for (let i = 0; i < bg.length; i++) {\n const char = bg[i];\n if (char === '(') depth++;\n if (char === ')') depth--;\n if (char === ',' && depth === 0) {\n parts.push(bg.slice(lastIndex, i).trim());\n lastIndex = i + 1;\n }\n }\n parts.push(bg.slice(lastIndex).trim());\n return parts;\n}\n\n"], ["/snapdom/src/modules/background.js", "/**\n * Utilities for inlining background images as data URLs.\n * @module background\n */\n\nimport { getStyle, inlineSingleBackgroundEntry, splitBackgroundImage } from '../utils/helpers.js';\nimport { cache } from '../core/cache.js'\n\n/**\n * Converts all background images in the cloned element tree to data URLs.\n *\n * @param {Element} source - Original element\n * @param {Element} clone - Cloned element\n * @param {Object} [options={}] - Options for image processing\n * @returns {Promise} Promise that resolves when all background images are processed\n */\nexport async function inlineBackgroundImages(source, clone, options = {}) {\n const queue = [[source, clone]];\n\n const imageProps = [\n \"background-image\",\n \"mask\",\n \"mask-image\", \"-webkit-mask-image\",\n \"mask-source\", \"mask-box-image-source\",\n \"mask-border-source\",\n \"-webkit-mask-box-image-source\"\n ];\n\n while (queue.length) {\n const [srcNode, cloneNode] = queue.shift();\n const style = cache.preStyle.get(srcNode) || getStyle(srcNode);\n if (!cache.preStyle.has(srcNode)) cache.preStyle.set(srcNode, style);\n\n for (const prop of imageProps) {\n const val = style.getPropertyValue(prop);\n if (!val || val === \"none\") continue;\n\n const splits = splitBackgroundImage(val);\n const inlined = await Promise.all(\n splits.map(entry => inlineSingleBackgroundEntry(entry, options))\n );\n\n if (inlined.some(p => p && p !== \"none\" && !/^url\\(undefined/.test(p))) {\n cloneNode.style.setProperty(prop, inlined.join(\", \"));\n }\n }\n\n // También preservamos el background-color como antes\n const bgColor = style.getPropertyValue(\"background-color\");\n if (\n bgColor &&\n bgColor !== \"transparent\" &&\n bgColor !== \"rgba(0, 0, 0, 0)\"\n ) {\n cloneNode.style.backgroundColor = bgColor;\n }\n\n const sChildren = Array.from(srcNode.children);\n const cChildren = Array.from(cloneNode.children);\n for (let i = 0; i < Math.min(sChildren.length, cChildren.length); i++) {\n queue.push([sChildren[i], cChildren[i]]);\n }\n }\n}\n\n"], ["/snapdom/src/api/preCache.js", "import { getStyle, inlineSingleBackgroundEntry, fetchImage, splitBackgroundImage } from '../utils/helpers.js';\nimport { embedCustomFonts } from '../modules/fonts.js';\nimport { precacheCommonTags } from '../utils/cssTools.js';\nimport { cache } from '../core/cache.js';\n\n/**\n * Preloads images, background images, and optionally fonts into cache before DOM capture.\n *\n * @param {Document|Element} [root=document] - The root node to search for resources\n * @param {Object} [options={}] - Pre-caching options\n * @returns {Promise} Resolves when all resources are pre-cached\n */\n\nexport async function preCache(root = document, options = {}) {\n const { embedFonts = true, reset = false} = options;\n if (reset) {\n cache.reset()\n return;\n }\n await document.fonts.ready;\n precacheCommonTags();\n let imgEls = [], allEls = [];\n if (root?.querySelectorAll) {\n imgEls = Array.from(root.querySelectorAll(\"img[src]\"));\n allEls = Array.from(root.querySelectorAll(\"*\"));\n }\n const promises = [];\n for (const img of imgEls) {\n const src = img.src;\n if (!cache.image.has(src)) {\n \n promises.push(\n fetchImage(src, { useProxy: options.useProxy}).then((dataURL) => cache.image.set(src, dataURL)).catch(() => {\n })\n );\n }\n }\n for (const el of allEls) {\n const bg = getStyle(el).backgroundImage;\n if (bg && bg !== \"none\") {\n const bgSplits = splitBackgroundImage(bg);\n for (const entry of bgSplits) {\n const isUrl = entry.startsWith(\"url(\");\n if (isUrl) {\n promises.push(\n inlineSingleBackgroundEntry(entry, options).catch(() => {\n })\n );\n }\n }\n }\n }\n if (embedFonts) {\n await embedCustomFonts({ preCached: true });\n }\n await Promise.all(promises);\n}\n"], ["/snapdom/src/modules/images.js", "/**\n * Utilities for inlining elements as data URLs or placeholders.\n * @module images\n */\n\nimport { fetchImage } from '../utils/helpers.js';\n\n/**\n * Converts all elements in the clone to data URLs or replaces them with placeholders if loading fails.\n *\n * @param {Element} clone - Clone of the original element\n * @param {Object} [options={}] - Options for image processing\n * @returns {Promise} Promise that resolves when all images are processed\n */\nexport async function inlineImages(clone, options = {}) {\n const imgs = Array.from(clone.querySelectorAll(\"img\"));\n const processImg = async (img) => {\n const src = img.src;\n try {\n const dataUrl = await fetchImage(src, { useProxy: options.useProxy });\n img.src = dataUrl;\n if (!img.width) img.width = img.naturalWidth || 100;\n if (!img.height) img.height = img.naturalHeight || 100;\n } catch {\n const fallback = document.createElement(\"div\");\n fallback.style = `width: ${img.width || 100}px; height: ${img.height || 100}px; background: #ccc; display: inline-block; text-align: center; line-height: ${img.height || 100}px; color: #666; font-size: 12px;`;\n fallback.innerText = \"img\";\n img.replaceWith(fallback);\n }\n };\n for (let i = 0; i < imgs.length; i += 4) {\n const group = imgs.slice(i, i + 4).map(processImg);\n await Promise.allSettled(group);\n }\n}"], ["/snapdom/src/modules/svgDefs.js", "/**\n * Inlines external `` used by `` or `` inside SVGs,\n * copying only the necessary definitions into each individual cloned SVG.\n *\n * This is needed because cloned SVGs using `` may reference elements like ``, ``, etc.,\n * defined elsewhere in the document (e.g., in a shared `` block that is not part of the cloned subtree).\n *\n * The function finds all `` elements within `root`, extracts the referenced IDs,\n * and embeds the required definitions at the top of each SVG.\n *\n * @function inlineExternalDef\n * @param {ParentNode} root - The root node containing cloned SVGs (usually the result of a DOM snapshot).\n * @returns {void}\n *\n * @example\n * const { clone } = await prepareClone(element);\n * inlineExternalDef(clone);\n */\n\nexport function inlineExternalDef(root) {\n if (!root) return;\n const defsSources = document.querySelectorAll('svg > defs');\n if (!defsSources.length) return;\n\n root.querySelectorAll('svg').forEach(svg => {\n const uses = svg.querySelectorAll('use');\n if (!uses.length) return;\n\n const usedIds = new Set();\n uses.forEach(use => {\n const href = use.getAttribute('xlink:href') || use.getAttribute('href');\n if (href && href.startsWith('#')) usedIds.add(href.slice(1));\n });\n if (!usedIds.size) return;\n\n const defs = document.createElementNS(\"http://www.w3.org/2000/svg\", \"defs\");\n\n for (const id of usedIds) {\n for (const source of defsSources) {\n const def = source.querySelector(`#${CSS.escape(id)}`);\n if (def) {\n defs.appendChild(def.cloneNode(true));\n break;\n }\n }\n }\n\n if (defs.childNodes.length) {\n svg.insertBefore(defs, svg.firstChild);\n }\n });\n}\n"], ["/snapdom/__tests__/clone.core.test.js", "import { describe, it, expect, vi } from 'vitest';\nimport { deepClone } from '../src/core/clone.js';\n\ndescribe('deepClone', () => {\n it('clones a simple div', () => {\n const el = document.createElement('div');\n el.textContent = 'hello';\n const styleMap = new Map();\n const styleCache = new WeakMap();\n const nodeMap = new Map();\n const clone = deepClone(el, styleMap, styleCache, nodeMap, false);\n expect(clone).not.toBe(el);\n expect(clone.textContent).toBe('hello');\n });\n\n it('clones canvas as an image', () => {\n const canvas = document.createElement('canvas');\n canvas.width = 10;\n canvas.height = 10;\n const ctx = canvas.getContext('2d');\n ctx.fillStyle = 'red';\n ctx.fillRect(0,0,10,10);\n const styleMap = new Map();\n const styleCache = new WeakMap();\n const nodeMap = new Map();\n const clone = deepClone(canvas, styleMap, styleCache, nodeMap, false);\n expect(clone.tagName).toBe('IMG');\n expect(clone.src.startsWith('data:image/')).toBe(true);\n });\n\n it('deepClone handles data-capture=\"exclude\"', () => {\n const el = document.createElement('div');\n el.setAttribute('data-capture', 'exclude');\n const clone = deepClone(el, true, {});\n expect(clone).not.toBeNull();\n });\n\n it('deepClone handles data-capture=\"placeholder\"', () => {\n const el = document.createElement('div');\n el.setAttribute('data-capture', 'placeholder');\n el.setAttribute('data-placeholder-text', 'Placeholder!');\n const clone = deepClone(el, true, {});\n expect(clone.textContent).toContain('Placeholder!');\n });\n\n it('deepClone handles iframe', () => {\n const iframe = document.createElement('iframe');\n iframe.width = 100;\n iframe.height = 50;\n const clone = deepClone(iframe, true, {});\n expect(clone.tagName).toBe('DIV');\n });\n\n it('deepClone handles input, textarea, select', () => {\n const input = document.createElement('input');\n input.value = 'foo';\n input.checked = true;\n const textarea = document.createElement('textarea');\n textarea.value = 'bar';\n const select = document.createElement('select');\n const opt = document.createElement('option');\n opt.value = 'baz';\n select.appendChild(opt);\n select.value = 'baz';\n [input, textarea, select].forEach(el => {\n const clone = deepClone(el, true, {});\n expect(clone.value).toBe(el.value);\n });\n });\n\n it('deepClone handles shadow DOM', () => {\n const el = document.createElement('div');\n const shadow = el.attachShadow({mode:'open'});\n const span = document.createElement('span');\n span.textContent = 'shadow';\n shadow.appendChild(span);\n const clone = deepClone(el, true, {});\n expect(clone).not.toBeNull();\n });\n});\n\ndescribe('deepClone edge cases', () => {\n it('clones unsupported node (Comment) as a new Comment', () => {\n const fake = document.createComment('not supported');\n const result = deepClone(fake, true, {});\n expect(result.nodeType).toBe(Node.COMMENT_NODE);\n expect(result.textContent).toBe('not supported');\n expect(result).not.toBe(fake); // Es un clon, no el mismo objeto\n });\n it('clones attributes and children', () => {\n const el = document.createElement('div');\n el.setAttribute('data-test', '1');\n const result = deepClone(el, true, {});\n expect(result.getAttribute('data-test')).toBe('1');\n });\n});\n"], ["/snapdom/src/api/snapdom.js", "/**\n * Main API for snapDOM: capture DOM elements as SVG and raster images.\n * Provides utilities for exporting, downloading, and converting DOM captures.\n * @module snapdom\n */\n\nimport { captureDOM } from '../core/capture';\nimport { isSafari } from '../utils/helpers.js';\nimport { extendIconFonts } from '../modules/iconFonts.js';\n\n/**\n * Converts an SVG data URL to an HTMLImageElement.\n *\n * @param {string} url - SVG data URL\n * @param {Object} options\n * @param {number} [options.dpr=1] - Device pixel ratio\n * @param {number} [options.scale=1] - Scale multiplier\n * @returns {Promise} The resulting image\n */\n\n async function toImg(url, { dpr = 1, scale = 1 }) {\n const img = new Image();\n img.src = url;\n await img.decode();\n img.width = img.width * scale ;\n img.height = img.height * scale ;\n \n return img;\n}\n\n/**\n * Converts an SVG data URL to a Canvas element.\n *\n * @param {string} url - SVG data URL\n * @param {Object} options\n * @param {number} [options.dpr=1] - Device pixel ratio\n * @param {number} [options.scale=1] - Scale multiplier\n * @returns {Promise} The resulting canvas\n */\n\nasync function toCanvas(url, { dpr = 1, scale = 1 } = {}) {\n const img = new Image();\n img.src = url;\n img.crossOrigin = 'anonymous';\n img.loading = 'eager';\n img.decoding = 'sync';\n\n const isSafariBrowser = isSafari();\n let appended = false;\n\n if (isSafariBrowser) {\n document.body.appendChild(img);\n appended = true;\n }\n\n await img.decode();\n\n if (isSafariBrowser) {\n await new Promise(resolve => setTimeout(resolve, 100));\n }\n\n if (img.width === 0 || img.height === 0) {\n if (appended) img.remove();\n throw new Error('Image failed to load or has no dimensions');\n }\n\n const width = img.width * scale;\n const height = img.height * scale;\n\n const canvas = document.createElement('canvas');\n canvas.width = Math.ceil(width * dpr);\n canvas.height = Math.ceil(height * dpr);\n canvas.style.width = `${width}px`;\n canvas.style.height = `${height}px`;\n\n const ctx = canvas.getContext('2d');\n ctx.scale(dpr, dpr);\n ctx.drawImage(img, 0, 0, width, height);\n\n if (appended) img.remove();\n\n return canvas;\n}\n\n/**\n * Converts a DOM snapshot (SVG data URL) into a Blob of the specified format.\n *\n * @param {string} url - SVG data URL\n * @param {Object} [options]\n * @param {string} [options.format=\"svg\"] - Output format: \"svg\", \"png\", \"jpeg\", \"webp\"\n * @param {number} [options.dpr=1] - Device pixel ratio\n * @param {number} [options.scale=1] - Scale multiplier\n * @param {string} [options.backgroundColor=\"#fff\"] - Background for raster formats\n * @param {number} [options.quality] - JPEG/WebP quality (0–1)\n * @returns {Promise} The resulting Blob\n */\nasync function toBlob(url, {\n type = \"svg\",\n scale = 1,\n backgroundColor = \"#fff\",\n quality\n} = {}) {\n const mime = {\n jpg: \"image/jpeg\",\n jpeg: \"image/jpeg\",\n png: \"image/png\",\n webp: \"image/webp\",\n }[type] || \"image/png\";\n\n if (type === \"svg\") {\n const svgText = decodeURIComponent(url.split(\",\")[1]);\n return new Blob([svgText], { type: \"image/svg+xml\" });\n }\n\n const canvas = await createBackground(url, { dpr: 1, scale }, backgroundColor);\n return new Promise((resolve) => {\n canvas.toBlob(blob => resolve(blob), `${mime}`, quality);\n });\n}\n\n\n\n/**\n * Creates a canvas with a background color from an SVG data URL.\n *\n * @param {string} url - SVG data URL\n * @param {Object} options\n * @param {number} [options.dpr=1] - Device pixel ratio\n * @param {number} [options.scale=1] - Scale multiplier\n * @param {string} [backgroundColor] - Background color to apply\n * @returns {Promise} The resulting canvas\n */\n\n async function createBackground(url, { dpr = 1, scale = 1 }, backgroundColor) {\n const baseCanvas = await toCanvas(url, { dpr, scale });\n if (!backgroundColor) return baseCanvas;\n\n const temp = document.createElement(\"canvas\");\n temp.width = baseCanvas.width;\n temp.height = baseCanvas.height;\n const ctx = temp.getContext(\"2d\");\n\n ctx.fillStyle = backgroundColor;\n ctx.fillRect(0, 0, temp.width, temp.height);\n ctx.drawImage(baseCanvas, 0, 0);\n\n return temp;\n}\n\n/**\n * Converts an SVG data URL to a raster image (PNG, JPEG, WebP).\n *\n * @param {string} url - SVG data URL\n * @param {Object} options\n * @param {number} [options.dpr=1] - Device pixel ratio\n * @param {number} [options.scale=1] - Scale multiplier\n * @param {string} [options.backgroundColor=\"#fff\"] - Background color for rasterization\n * @param {number} [options.quality] - Image quality (for JPEG/WebP)\n * @param {string} [format=\"png\"] - Output format: \"png\", \"jpeg\", or \"webp\"\n * @returns {Promise} The resulting raster image\n */\n\n async function toRasterImg(url, { dpr = 1, scale = 1, backgroundColor, quality }, format = \"png\") {\n const defaultBg = [\"jpg\", \"jpeg\", \"webp\"].includes(format) ? \"#fff\" : undefined;\n const finalBg = backgroundColor ?? defaultBg;\n\n const canvas = await createBackground(url, { dpr, scale }, finalBg);\n\n const img = new Image();\n img.src = canvas.toDataURL(`image/${format}`, quality);\n await img.decode();\n\n img.style.width = `${canvas.width / dpr}px`;\n img.style.height = `${canvas.height / dpr}px`;\n\n return img;\n}\n\n/**\n * Downloads a captured image in the specified format.\n *\n * @param {string} url - SVG data URL\n * @param {Object} options\n * @param {number} [options.dpr=1] - Device pixel ratio\n * @param {number} [options.scale=1] - Scale multiplier\n * @param {string} [options.backgroundColor=\"#fff\"] - Background color for rasterization\n * @param {string} [options.format=\"png\"] - Output format\n * @param {string} [options.filename=\"capture\"] - Download filename\n * @returns {Promise} Resolves when download is triggered\n */\n\n async function download(url,{ dpr = 1, scale = 1, backgroundColor, format = \"png\", filename = \"snapDOM\"} = {}) {\n if (format === \"svg\") {\n const blob = await toBlob(url);\n const objectURL = URL.createObjectURL(blob);\n const a = document.createElement(\"a\");\n a.href = objectURL;\n a.download = `${filename}.svg`;\n a.click();\n URL.revokeObjectURL(objectURL);\n return;\n }\n\n const defaultBg = [\"jpg\", \"jpeg\", \"webp\"].includes(format) ? \"#fff\" : undefined;\n const finalBg = backgroundColor ?? defaultBg;\n\n const canvas = await createBackground(url, { dpr, scale }, finalBg);\n const mime = {\n jpg: \"image/jpeg\",\n jpeg: \"image/jpeg\",\n png: \"image/png\",\n webp: \"image/webp\",\n }[format] || \"image/png\";\n\n const dataURL = canvas.toDataURL(mime);\n\n const a = document.createElement(\"a\");\n a.href = dataURL;\n a.download = `${filename}.${format}`;\n a.click();\n}\n\n/**\n * Main entry point: captures a DOM element and returns an object with export methods.\n *\n * @param {Element} element - DOM element to capture\n * @param {Object} [options={}] - Capture options\n * @returns {Promise} Object with export methods (toRaw, toImg, toCanvas, etc.)\n */\n\nexport async function snapdom(element, options = {}) {\n options = { scale: 1, ...options };\n if (!element) throw new Error(\"Element cannot be null or undefined\");\n if (options.iconFonts) {\n extendIconFonts(options.iconFonts);\n }\n return await snapdom.capture(element, options);\n}\n\n/**\n * Captures a DOM element and returns an object with export methods (internal use).\n *\n * @param {Element} el - DOM element to capture\n * @param {Object} [options={}] - Capture options\n * @returns {Promise} Object with export methods\n */\n\nsnapdom.capture = async (el, options = {}) => {\n const url = await captureDOM(el, options);\n const dpr = window.devicePixelRatio || 1;\n const scale = options.scale || 1;\n\n return {\n url,\n options,\n toRaw: () => url,\n toImg: () => toImg(url, { dpr, scale }),\n toCanvas: () => toCanvas(url, { dpr, scale }),\n toBlob: (options) => toBlob(url, { dpr, scale, ...options }),\n toPng: (options) => toRasterImg(url, { dpr, scale, ...options }, \"png\"),\n toJpg: (options) => toRasterImg(url, { dpr, scale, ...options }, \"jpeg\"),\n toWebp: (options) => toRasterImg(url, { dpr, scale, ...options }, \"webp\"),\n download: ({ format = \"png\", filename = \"capture\", backgroundColor } = {}) => download(url, { dpr, scale, backgroundColor, format, filename})\n };\n};\n\n// Compatibilidad\nsnapdom.toRaw = async (el, options) => (await snapdom.capture(el, options)).toRaw();\nsnapdom.toImg = async (el, options) => (await snapdom.capture(el, options)).toImg();\nsnapdom.toCanvas = async (el, options) => (await snapdom.capture(el, options)).toCanvas();\nsnapdom.toBlob = async (el, options) => (await snapdom.capture(el, options)).toBlob(options);\nsnapdom.toPng = async (el, options) => (await snapdom.capture(el, options)).toPng(options);\nsnapdom.toJpg = async (el, options) => (await snapdom.capture(el, options)).toJpg(options);\nsnapdom.toWebp = async (el, options) => (await snapdom.capture(el, options)).toWebp(options);\nsnapdom.download = async (el, options = {}) => {\n const {\n format = \"png\",\n filename = \"capture\",\n backgroundColor,\n ...rest\n } = options;\n\n const capture = await snapdom.capture(el, rest);\n return await capture.download({ format, filename, backgroundColor });\n};"], ["/snapdom/__tests__/snapdom.benchmark.js", "import { bench, describe, beforeEach, afterEach } from 'vitest';\nimport { domToDataUrl } from 'https://unpkg.com/modern-screenshot';\nimport * as htmlToImage from 'https://cdn.jsdelivr.net/npm/html-to-image@1.11.13/+esm';\n//import { toPng, toJpeg, toBlob, toPixelData, toSvg } from 'https://cdn.jsdelivr.net/npm/html-to-image@1.11.13/dist/html-to-image.min.js';\nimport { snapdom as sd } from 'https://cdn.jsdelivr.net/npm/@zumer/snapdom@1.8.0/dist/snapdom.mjs';\nimport { snapdom } from '../src/index';\n\n\nlet html2canvasLoaded = false;\n\nasync function loadHtml2Canvas() {\n if (html2canvasLoaded) return;\n await new Promise((resolve, reject) => {\n const script = document.createElement('script');\n script.src = 'https://cdn.jsdelivr.net/npm/html2canvas@1.4.1/dist/html2canvas.min.js';\n script.onload = () => resolve();\n script.onerror = reject;\n document.head.appendChild(script);\n });\n html2canvasLoaded = true;\n}\n\nawait loadHtml2Canvas();\n\n\n\nconst sizes = [\n { width: 200, height: 100, label: 'Small element (200x100)' },\n { width: 400, height: 300, label: 'Modal size (400x300)' },\n { width: 1200, height: 800, label: 'Page view (1200x800)' },\n { width: 2000, height: 1500, label: 'Large scroll area (2000x1500)' },\n { width: 4000, height: 2000, label: 'Very large element (4000x2000)' },\n];\n\nfor (const size of sizes) {\n describe(`Benchmark simple node at ${size.label}`, () => {\n let container;\n\n async function setupContainer() { \n if (container && document.body.contains(container)) {\n return;\n }\n container = document.createElement('div');\n container.style.width = `${size.width}px`;\n container.style.height = `${size.height}px`;\n container.style.background = 'linear-gradient(to right, red, blue)';\n container.style.fontFamily = 'Arial, sans-serif';\n container.style.display = 'flex';\n container.style.alignItems = 'center';\n container.style.justifyContent = 'center';\n container.style.fontSize = '24px';\n container.innerHTML = `

${size.label}

`;\n document.body.appendChild(container);\n } \n\n /* async function setupContainer() {\n if (container && document.body.contains(container)) return;\n \n container = document.createElement('div');\n container.style.width = `${size.width}px`;\n container.style.height = `${size.height}px`;\n container.style.padding = '20px';\n container.style.overflow = 'auto';\n container.style.background = 'white';\n container.style.border = '2px solid black';\n container.style.fontFamily = 'Arial, sans-serif';\n container.style.color = '#333';\n container.style.position = 'relative';\n \n const grid = document.createElement('div');\n grid.style.display = 'grid';\n grid.style.gridTemplateColumns = 'repeat(auto-fill, minmax(120px, 1fr))';\n grid.style.gap = '10px';\n \n for (let i = 0; i < Math.floor((size.width * size.height) / 20000); i++) {\n const card = document.createElement('div');\n card.style.padding = '10px';\n card.style.borderRadius = '8px';\n card.style.background = i % 2 === 0 ? '#f0f0f0' : '#e0eaff';\n card.style.boxShadow = '0 2px 5px rgba(0,0,0,0.1)';\n card.style.display = 'flex';\n card.style.flexDirection = 'column';\n card.style.alignItems = 'center';\n \n const title = document.createElement('h3');\n title.textContent = `Card ${i + 1}`;\n title.style.margin = '0 0 10px 0';\n title.style.fontSize = '14px';\n \n const icon = document.createElement('div');\n icon.style.width = '30px';\n icon.style.height = '30px';\n icon.style.borderRadius = '50%';\n icon.style.background = i % 2 === 0 ? 'red' : 'blue';\n icon.style.marginBottom = '10px';\n \n const text = document.createElement('p');\n text.textContent = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit.';\n text.style.fontSize = '12px';\n text.style.textAlign = 'center';\n \n card.appendChild(icon);\n card.appendChild(title);\n card.appendChild(text);\n grid.appendChild(card);\n }\n \n container.appendChild(grid);\n document.body.appendChild(container);\n }\n */\n afterEach(() => {\n if (container) {\n container.remove();\n container = null;\n }\n });\n\n bench('snapDOM current version', async () => {\n await setupContainer();\n await snapdom.toRaw(container);\n });\n\n bench('snapDOM V1.8.0', async () => {\n await setupContainer();\n await sd.toRaw(container);\n });\n\n bench('html2canvas capture', async () => {\n await setupContainer();\n const canvas = await window.html2canvas(container, { logging: false, scale: 1 });\n await canvas.toDataURL();\n });\n\n bench('modern-screenshot capture', async () => {\n await setupContainer();\n await domToDataUrl(container);\n });\n\n bench('html-to-image capture', async () => {\n await setupContainer();\n await htmlToImage.toSvg(container);\n });\n });\n}\n"], ["/snapdom/src/modules/styles.js", "import { getStyleKey } from '../utils/cssTools.js';\nimport { getStyle } from '../utils/helpers.js';\nimport {cache} from '../core/cache.js'\n\nfunction snapshotComputedStyleFull(style) {\n const result = {};\n for (let i = 0; i < style.length; i++) {\n const prop = style[i];\n let val = style.getPropertyValue(prop);\n\n // Opcional: evitar URLs externas que puedan romper renderizado\n if (\n (prop === 'background-image' || prop === 'content') &&\n val.includes('url(') &&\n !val.includes('data:')\n ) {\n val = 'none';\n }\n\n result[prop] = val;\n }\n return result;\n}\n\nexport function inlineAllStyles(source, clone, compress) {\n if (source.tagName === 'STYLE') return;\n\n if (!cache.preStyle.has(source)) {\n cache.preStyle.set(source, getStyle(source));\n }\n const style = cache.preStyle.get(source);\n\n if (!cache.snapshot.has(source)) {\n const snapshot = snapshotComputedStyleFull(style);\n cache.snapshot.set(source, snapshot);\n }\n\n const snapshot = cache.snapshot.get(source);\n\n const hash = Object.entries(snapshot)\n .sort(([a], [b]) => a.localeCompare(b))\n .map(([prop, val]) => `${prop}:${val}`)\n .join(';');\n\n if (cache.snapshotKey.has(hash)) {\n cache.preStyleMap.set(clone, cache.snapshotKey.get(hash));\n return;\n }\n\n const tagName = source.tagName?.toLowerCase() || 'div';\n const key = getStyleKey(snapshot, tagName, compress);\n\n cache.snapshotKey.set(hash, key);\n cache.preStyleMap.set(clone, key);\n}\n"], ["/snapdom/__tests__/snapdom.complex.benchmark.js", "import { bench, describe, beforeEach, afterEach } from 'vitest';\nimport { domToDataUrl } from 'https://unpkg.com/modern-screenshot';\nimport * as htmlToImage from 'https://cdn.jsdelivr.net/npm/html-to-image@1.11.13/+esm';\nimport { snapdom as sd } from 'https://cdn.jsdelivr.net/npm/@zumer/snapdom@1.8.0/dist/snapdom.mjs';\nimport { snapdom } from '../src/index';\n\nlet html2canvasLoaded = false;\n\nasync function loadHtml2Canvas() {\n if (html2canvasLoaded) return;\n await new Promise((resolve, reject) => {\n const script = document.createElement('script');\n script.src = 'https://cdn.jsdelivr.net/npm/html2canvas@1.4.1/dist/html2canvas.min.js';\n script.onload = () => resolve();\n script.onerror = reject;\n document.head.appendChild(script);\n });\n html2canvasLoaded = true;\n}\n\nawait loadHtml2Canvas();\n\nconst sizes = [\n { width: 200, height: 100, label: 'Small element (200x100)' },\n { width: 400, height: 300, label: 'Modal size (400x300)' },\n { width: 1200, height: 800, label: 'Page view (1200x800)' },\n { width: 2000, height: 1500, label: 'Large scroll area (2000x1500)' },\n { width: 4000, height: 2000, label: 'Very large element (4000x2000)' },\n];\n\nfor (const size of sizes) {\n describe(`Benchmark complex node at ${size.label}`, () => {\n let container;\n\n async function setupContainer() {\n if (container && document.body.contains(container)) return;\n \n container = document.createElement('div');\n container.style.width = `${size.width}px`;\n container.style.height = `${size.height}px`;\n container.style.padding = '20px';\n container.style.overflow = 'auto';\n container.style.background = 'white';\n container.style.border = '2px solid black';\n container.style.fontFamily = 'Arial, sans-serif';\n container.style.color = '#333';\n container.style.position = 'relative';\n \n const grid = document.createElement('div');\n grid.style.display = 'grid';\n grid.style.gridTemplateColumns = 'repeat(auto-fill, minmax(120px, 1fr))';\n grid.style.gap = '10px';\n \n for (let i = 0; i < Math.floor((size.width * size.height) / 20000); i++) {\n const card = document.createElement('div');\n card.style.padding = '10px';\n card.style.borderRadius = '8px';\n card.style.background = i % 2 === 0 ? '#f0f0f0' : '#e0eaff';\n card.style.boxShadow = '0 2px 5px rgba(0,0,0,0.1)';\n card.style.display = 'flex';\n card.style.flexDirection = 'column';\n card.style.alignItems = 'center';\n \n const title = document.createElement('h3');\n title.textContent = `Card ${i + 1}`;\n title.style.margin = '0 0 10px 0';\n title.style.fontSize = '14px';\n \n const icon = document.createElement('div');\n icon.style.width = '30px';\n icon.style.height = '30px';\n icon.style.borderRadius = '50%';\n icon.style.background = i % 2 === 0 ? 'red' : 'blue';\n icon.style.marginBottom = '10px';\n \n const text = document.createElement('p');\n text.textContent = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit.';\n text.style.fontSize = '12px';\n text.style.textAlign = 'center';\n \n card.appendChild(icon);\n card.appendChild(title);\n card.appendChild(text);\n grid.appendChild(card);\n }\n \n container.appendChild(grid);\n document.body.appendChild(container);\n \n }\n \n afterEach (async () => {\n if (container) {\n container.remove();\n container = null;\n }\n \n document.body.innerHTML = ''\n });\n\n bench('snapDOM current version', async () => {\n await setupContainer();\n await snapdom.toRaw(container, {compress: true, fast: true});\n });\n\n bench('snapDOM V1.8.0', async () => {\n await setupContainer();\n await sd.toRaw(container);\n });\n \n bench('html2canvas capture', async () => {\n await setupContainer();\n const canvas = await window.html2canvas(container, { logging: false, scale: 1 });\n await canvas.toDataURL();\n });\n\n bench('modern-screenshot capture', async () => {\n await setupContainer();\n await domToDataUrl(container);\n });\n bench('html-to-image capture', async () => {\n await setupContainer();\n await htmlToImage.toSvg(container);\n });\n });\n}\n"], ["/snapdom/__tests__/pseudo.module.test.js", "vi.mock('../src/utils/helpers.js', async () => {\n const actual = await vi.importActual('../src/utils/helpers.js');\n return {\n ...actual,\n fetchImage: vi.fn(),\n };\n});\nvi.mock('../src/modules/fonts.js', async () => {\n const actual = await vi.importActual('../src/modules/fonts.js');\n return {\n ...actual,\n iconToImage: vi.fn(),\n };\n});\n\nimport { describe, it, expect, vi } from 'vitest';\nimport { inlinePseudoElements } from '../src/modules/pseudo.js';\nimport * as helpers from '../src/utils/helpers.js';\nimport * as fonts from '../src/modules/fonts.js';\n\ndescribe('inlinePseudoElements', () => {\n it('does not fail with simple elements', async () => {\n const el = document.createElement('div');\n const clone = document.createElement('div');\n await expect(inlinePseudoElements(el, clone, new Map(), new WeakMap(), false)).resolves.toBeUndefined();\n });\n\n it('handles ::before with text content', async () => {\n const el = document.createElement('div');\n const clone = document.createElement('div');\n vi.spyOn(window, 'getComputedStyle').mockImplementation((_, pseudo) => {\n if (pseudo === '::before') return {\n getPropertyValue: (prop) => prop === 'content' ? '\"★\"' : prop === 'font-family' ? 'Arial' : prop === 'font-size' ? '32' : prop === 'font-weight' ? '400' : prop === 'color' ? '#000' : prop === 'background-image' ? 'none' : prop === 'background-color' ? 'transparent' : '',\n color: '#000', fontSize: '32px', fontWeight: '400', fontFamily: 'Arial',\n };\n return { getPropertyValue: () => '', color: '', fontSize: '', fontWeight: '', fontFamily: '' };\n });\n await inlinePseudoElements(el, clone, new Map(), new WeakMap(), false);\n window.getComputedStyle.mockRestore();\n });\n\n it('handles ::before with icon font', async () => {\n const el = document.createElement('div');\n const clone = document.createElement('div');\n vi.spyOn(window, 'getComputedStyle').mockImplementation((_, pseudo) => {\n if (pseudo === '::before') return {\n getPropertyValue: (prop) => prop === 'content' ? '\"★\"' : prop === 'font-family' ? 'Font Awesome' : prop === 'font-size' ? '32' : prop === 'font-weight' ? '400' : prop === 'color' ? '#000' : prop === 'background-image' ? 'none' : prop === 'background-color' ? 'transparent' : '',\n color: '#000', fontSize: '32px', fontWeight: '400', fontFamily: 'Font Awesome',\n };\n return { getPropertyValue: () => '', color: '', fontSize: '', fontWeight: '', fontFamily: '' };\n });\n fonts.iconToImage.mockResolvedValue('data:image/png;base64,icon');\n await inlinePseudoElements(el, clone, new Map(), new WeakMap(), false);\n window.getComputedStyle.mockRestore();\n });\n\n it('handles ::before with url content', async () => {\n const el = document.createElement('div');\n const clone = document.createElement('div');\n vi.spyOn(window, 'getComputedStyle').mockImplementation((_, pseudo) => {\n if (pseudo === '::before') return {\n getPropertyValue: (prop) => prop === 'content' ? 'url(\"https://test.com/img.png\")' : prop === 'font-family' ? 'Arial' : prop === 'font-size' ? '32' : prop === 'font-weight' ? '400' : prop === 'color' ? '#000' : prop === 'background-image' ? 'none' : prop === 'background-color' ? 'transparent' : '',\n color: '#000', fontSize: '32px', fontWeight: '400', fontFamily: 'Arial',\n };\n return { getPropertyValue: () => '', color: '', fontSize: '', fontWeight: '', fontFamily: '' };\n });\n helpers.fetchImage.mockResolvedValue('data:image/png;base64,img');\n await inlinePseudoElements(el, clone, new Map(), new WeakMap(), false);\n window.getComputedStyle.mockRestore();\n });\n\n it('handles ::before with background-image (data url)', async () => {\n const el = document.createElement('div');\n const clone = document.createElement('div');\n vi.spyOn(window, 'getComputedStyle').mockImplementation((_, pseudo) => {\n if (pseudo === '::before') return {\n getPropertyValue: (prop) => prop === 'content' ? 'none' : prop === 'font-family' ? 'Arial' : prop === 'font-size' ? '32' : prop === 'font-weight' ? '400' : prop === 'color' ? '#000' : prop === 'background-image' ? 'url(\"data:image/png;base64,abc\")' : prop === 'background-color' ? 'transparent' : '',\n color: '#000', fontSize: '32px', fontWeight: '400', fontFamily: 'Arial',\n };\n return { getPropertyValue: () => '', color: '', fontSize: '', fontWeight: '', fontFamily: '' };\n });\n await inlinePseudoElements(el, clone, new Map(), new WeakMap(), false);\n window.getComputedStyle.mockRestore();\n });\n\n it('handles ::before with background-image (fetch)', async () => {\n const el = document.createElement('div');\n const clone = document.createElement('div');\n vi.spyOn(window, 'getComputedStyle').mockImplementation((_, pseudo) => {\n if (pseudo === '::before') return {\n getPropertyValue: (prop) => prop === 'content' ? 'none' : prop === 'font-family' ? 'Arial' : prop === 'font-size' ? '32' : prop === 'font-weight' ? '400' : prop === 'color' ? '#000' : prop === 'background-image' ? 'url(\"https://test.com/img.png\")' : prop === 'background-color' ? 'transparent' : '',\n color: '#000', fontSize: '32px', fontWeight: '400', fontFamily: 'Arial',\n };\n return { getPropertyValue: () => '', color: '', fontSize: '', fontWeight: '', fontFamily: '' };\n });\n helpers.fetchImage.mockResolvedValue('data:image/png;base64,img');\n await inlinePseudoElements(el, clone, new Map(), new WeakMap(), false);\n window.getComputedStyle.mockRestore();\n });\n\n it('handles ::before with background-image fetch error', async () => {\n const el = document.createElement('div');\n const clone = document.createElement('div');\n vi.spyOn(window, 'getComputedStyle').mockImplementation((_, pseudo) => {\n if (pseudo === '::before') return {\n getPropertyValue: (prop) => prop === 'content' ? 'none' : prop === 'font-family' ? 'Arial' : prop === 'font-size' ? '32' : prop === 'font-weight' ? '400' : prop === 'color' ? '#000' : prop === 'background-image' ? 'url(\"https://test.com/img.png\")' : prop === 'background-color' ? 'transparent' : '',\n color: '#000', fontSize: '32px', fontWeight: '400', fontFamily: 'Arial',\n };\n return { getPropertyValue: () => '', color: '', fontSize: '', fontWeight: '', fontFamily: '' };\n });\n helpers.fetchImage.mockRejectedValue(new Error('fail'));\n await inlinePseudoElements(el, clone, new Map(), new WeakMap(), false);\n window.getComputedStyle.mockRestore();\n });\n\n it('handles ::before with no visible box', async () => {\n const el = document.createElement('div');\n const clone = document.createElement('div');\n vi.spyOn(window, 'getComputedStyle').mockImplementation((_, pseudo) => {\n if (pseudo === '::before') return {\n getPropertyValue: () => 'none', color: '', fontSize: '', fontWeight: '', fontFamily: ''\n };\n return { getPropertyValue: () => '', color: '', fontSize: '', fontWeight: '', fontFamily: '' };\n });\n await inlinePseudoElements(el, clone, new Map(), new WeakMap(), false);\n window.getComputedStyle.mockRestore();\n });\n\n it('handles ::first-letter with no textNode', async () => {\n const el = document.createElement('div');\n const clone = document.createElement('div');\n vi.spyOn(window, 'getComputedStyle').mockImplementation(() => ({\n getPropertyValue: () => '', color: '', fontSize: '', fontWeight: '', fontFamily: ''\n }));\n await inlinePseudoElements(el, clone, new Map(), new WeakMap(), false);\n window.getComputedStyle.mockRestore();\n });\n\n it('handles error in pseudo processing', async () => {\n const el = document.createElement('div');\n const clone = document.createElement('div');\n vi.spyOn(window, 'getComputedStyle').mockImplementation(() => { throw new Error('fail'); });\n await inlinePseudoElements(el, clone, new Map(), new WeakMap(), false);\n window.getComputedStyle.mockRestore();\n });\n\n it('ignores if source no es Element', async () => {\n const notElement = {};\n const clone = document.createElement('div');\n await expect(inlinePseudoElements(notElement, clone, new Map(), new WeakMap(), false)).resolves.toBeUndefined();\n });\n\n it('ignores if clone no es Element', async () => {\n const el = document.createElement('div');\n const notElement = {};\n await expect(inlinePseudoElements(el, notElement, new Map(), new WeakMap(), false)).resolves.toBeUndefined();\n });\n\n it('inserta pseudoEl como ::after', async () => {\n const el = document.createElement('div');\n const clone = document.createElement('div');\n vi.spyOn(window, 'getComputedStyle').mockImplementation((_, pseudo) => {\n if (pseudo === '::after') return {\n getPropertyValue: (prop) => prop === 'content' ? '\"after\"' : prop === 'font-family' ? 'Arial' : prop === 'font-size' ? '32' : prop === 'font-weight' ? '400' : prop === 'color' ? '#000' : prop === 'background-image' ? 'none' : prop === 'background-color' ? '#f00' : '',\n color: '#000', fontSize: '32px', fontWeight: '400', fontFamily: 'Arial',\n };\n return { getPropertyValue: () => '', color: '', fontSize: '', fontWeight: '', fontFamily: '' };\n });\n await inlinePseudoElements(el, clone, new Map(), new WeakMap(), false);\n window.getComputedStyle.mockRestore();\n });\n\n it('inserta pseudoEl como ::before', async () => {\n const el = document.createElement('div');\n const clone = document.createElement('div');\n vi.spyOn(window, 'getComputedStyle').mockImplementation((_, pseudo) => {\n if (pseudo === '::before') return {\n getPropertyValue: (prop) => prop === 'content' ? '\"before\"' : prop === 'font-family' ? 'Arial' : prop === 'font-size' ? '32' : prop === 'font-weight' ? '400' : prop === 'color' ? '#000' : prop === 'background-image' ? 'none' : prop === 'background-color' ? '#f00' : '',\n color: '#000', fontSize: '32px', fontWeight: '400', fontFamily: 'Arial',\n };\n return { getPropertyValue: () => '', color: '', fontSize: '', fontWeight: '', fontFamily: '' };\n });\n await inlinePseudoElements(el, clone, new Map(), new WeakMap(), false);\n window.getComputedStyle.mockRestore();\n });\n\n it('no inserta pseudoEl si no hay visible box', async () => {\n const el = document.createElement('div');\n const clone = document.createElement('div');\n vi.spyOn(window, 'getComputedStyle').mockImplementation((_, pseudo) => {\n if (pseudo === '::before') return {\n getPropertyValue: (prop) => 'none', color: '', fontSize: '', fontWeight: '', fontFamily: ''\n };\n return { getPropertyValue: () => '', color: '', fontSize: '', fontWeight: '', fontFamily: '' };\n });\n await inlinePseudoElements(el, clone, new Map(), new WeakMap(), false);\n window.getComputedStyle.mockRestore();\n });\n\n it('maneja ::first-letter meaningful', async () => {\n const el = document.createElement('div');\n el.textContent = 'Test';\n const clone = document.createElement('div');\n clone.textContent = 'Test';\n vi.spyOn(window, 'getComputedStyle').mockImplementation((_, pseudo) => {\n if (pseudo === '::first-letter') return {\n getPropertyValue: (prop) => prop === 'color' ? '#f00' : '', color: '#f00', fontSize: '32px', fontWeight: '400', fontFamily: 'Arial',\n };\n return { getPropertyValue: () => '', color: '#000', fontSize: '32px', fontWeight: '400', fontFamily: 'Arial' };\n });\n await inlinePseudoElements(el, clone, new Map(), new WeakMap(), false);\n window.getComputedStyle.mockRestore();\n });\n\n it('inserta ambos pseudoEl ::before y ::after en una sola ejecución', async () => {\n const el = document.createElement('div');\n const clone = document.createElement('div');\n vi.spyOn(window, 'getComputedStyle').mockImplementation((_, pseudo) => {\n if (pseudo === '::before') return {\n getPropertyValue: (prop) => prop === 'content' ? '\"before\"' : prop === 'font-family' ? 'Arial' : prop === 'font-size' ? '32' : prop === 'font-weight' ? '400' : prop === 'color' ? '#000' : prop === 'background-image' ? 'none' : prop === 'background-color' ? '#f00' : '',\n color: '#000', fontSize: '32px', fontWeight: '400', fontFamily: 'Arial',\n };\n if (pseudo === '::after') return {\n getPropertyValue: (prop) => prop === 'content' ? '\"after\"' : prop === 'font-family' ? 'Arial' : prop === 'font-size' ? '32' : prop === 'font-weight' ? '400' : prop === 'color' ? '#000' : prop === 'background-image' ? 'none' : prop === 'background-color' ? '#0f0' : '',\n color: '#000', fontSize: '32px', fontWeight: '400', fontFamily: 'Arial',\n };\n return { getPropertyValue: () => '', color: '', fontSize: '', fontWeight: '', fontFamily: '' };\n });\n await inlinePseudoElements(el, clone, new Map(), new WeakMap(), false);\n window.getComputedStyle.mockRestore();\n });\n\n it('should inline ::first-letter when style is meaningful', async () => {\n const el = document.createElement('p');\n el.textContent = '¡Hola mundo!';\n el.style.setProperty('color', 'black');\n\n document.body.appendChild(el);\n const clone = el.cloneNode(true);\n const styleMap = new Map();\n const styleCache = new WeakMap();\n\n const style = document.createElement('style');\n style.textContent = `\n p::first-letter {\n color: red;\n font-size: 200%;\n }\n `;\n document.head.appendChild(style);\n\n await inlinePseudoElements(el, clone, styleMap, styleCache, false);\n const firstLetterEl = clone.querySelector('[data-snapdom-pseudo=\"::first-letter\"]');\n expect(firstLetterEl).toBeTruthy();\n expect(firstLetterEl.textContent.length).toBeGreaterThan(0);\n});\n\nit('should inline background-image entries for pseudo-element', async () => {\n const el = document.createElement('div');\n document.body.appendChild(el);\n\n const style = document.createElement('style');\n style.textContent = `\n div::after {\n content: \" \";\n background-image: url(\"data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg'%3E%3Crect width='10' height='10' fill='blue'/%3E%3C/svg%3E\");\n display: inline-block;\n width: 10px;\n height: 10px;\n }\n `;\n document.head.appendChild(style);\n\n const clone = el.cloneNode(true);\n const styleMap = new Map();\n const styleCache = new WeakMap();\n\n await inlinePseudoElements(el, clone, styleMap, styleCache, false);\n const pseudoAfter = clone.querySelector('[data-snapdom-pseudo=\"::after\"]');\n expect(pseudoAfter).toBeTruthy();\n expect(pseudoAfter.style.backgroundImage.startsWith(\"url(\\\"data:image/\")).toBeTruthy();\n});\n\n});\n\n\n\n\n\n"], ["/snapdom/__tests__/snapdom.precache.test.js", "import { describe, test, expect, afterEach, afterAll, beforeEach } from 'vitest';\nimport { snapdom, preCache } from '../src/index';\nimport { cache } from '../src/core/cache';\n\nconst sizes = [\n { width: 200, height: 100, label: 'Small element (200x100)' },\n { width: 400, height: 300, label: 'Modal size (400x300)' },\n { width: 1200, height: 800, label: 'Page view (1200x800)' },\n];\nlet results = [];\nfunction createContainer(size) {\n const container = document.createElement('div');\n container.style.width = `${size.width}px`;\n container.style.height = `${size.height}px`;\n container.style.padding = '20px';\n container.style.overflow = 'auto';\n container.style.background = 'white';\n container.style.border = '2px solid black';\n container.style.fontFamily = 'Arial, sans-serif';\n container.style.color = '#333';\n container.style.position = 'relative';\n\n const grid = document.createElement('div');\n grid.style.display = 'grid';\n grid.style.gridTemplateColumns = 'repeat(auto-fill, minmax(120px, 1fr))';\n grid.style.gap = '10px';\n\n const cardCount = Math.floor((size.width * size.height) / 20000);\n for (let i = 0; i < cardCount; i++) {\n const card = document.createElement('div');\n card.style.padding = '10px';\n card.style.borderRadius = '8px';\n card.style.background = i % 2 === 0 ? '#f0f0f0' : '#e0eaff';\n card.style.boxShadow = '0 2px 5px rgba(0,0,0,0.1)';\n card.style.display = 'flex';\n card.style.flexDirection = 'column';\n card.style.alignItems = 'center';\n\n const title = document.createElement('h3');\n title.textContent = `Card ${i + 1}`;\n title.style.margin = '0 0 10px 0';\n title.style.fontSize = '14px';\n\n const icon = document.createElement('div');\n icon.style.width = '30px';\n icon.style.height = '30px';\n icon.style.borderRadius = '50%';\n icon.style.background = i % 2 === 0 ? 'red' : 'blue';\n icon.style.marginBottom = '10px';\n\n const text = document.createElement('p');\n text.textContent = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit.';\n text.style.fontSize = '12px';\n text.style.textAlign = 'center';\n\n card.appendChild(icon);\n card.appendChild(title);\n card.appendChild(text);\n grid.appendChild(card);\n }\n\n container.appendChild(grid);\n return container;\n}\n\nfunction waitForNextFrame() {\n return new Promise((resolve) => {\n requestAnimationFrame(() => setTimeout(resolve, 0));\n });\n}\nbeforeEach(() => {\n cache.image.clear();\n cache.background.clear();\n cache.resource.clear();\n});\nafterAll(() => {\n for (const r of results) {\n console.log(r.log);\n }\n results = [];\n \n document.body.innerHTML = '';\n});\nfor (const size of sizes) {\n describe(`snapDOM performance test (may not be accurate) - ${size.label}`, () => {\n let container;\n\n afterEach( () => {\n container?.remove();\n container = null;\n document.body.innerHTML = '';\n \n });\n\n test('without preCache', async () => {\n container = createContainer(size);\n document.body.appendChild(container);\n await waitForNextFrame();\n\n const start = performance.now();\n await snapdom.toRaw(container, { compress: true });\n const end = performance.now();\n\n let log = `[${size.label}] WITHOUT preCache: capture ${(end - start).toFixed(2)}ms`;\n results.push({ log });\n expect(true).toBe(true);\n \n });\n \n test('with preCache', async () => {\n container = createContainer(size);\n document.body.appendChild(container);\n await waitForNextFrame();\n\n const startPre = performance.now();\n await preCache();\n const endPre = performance.now();\n \n const startCap = performance.now();\n await snapdom.toRaw(container, { compress: true });\n const endCap = performance.now();\n \n const precacheTime = (endPre - startPre).toFixed(2);\n const captureTime = (endCap - startCap).toFixed(2);\n \n let log = `[${size.label}] WITH preCache: capture ${captureTime}ms (preCache ${precacheTime}ms) `;\n\n results.push({ log });\n \n expect(true).toBe(true);\n });\n\n });\n}\n"], ["/snapdom/src/modules/iconFonts.js", "var defaultIconFonts = [\n// /uicons/i,\n /font\\s*awesome/i,\n /material\\s*icons/i,\n /ionicons/i,\n /glyphicons/i,\n /feather/i,\n /bootstrap\\s*icons/i,\n /remix\\s*icons/i,\n /heroicons/i,\n /layui/i,\n /lucide/i\n];\n\nvar userIconFonts = [];\n\nexport function extendIconFonts(fonts) {\n const list = Array.isArray(fonts) ? fonts : [fonts];\n for (const f of list) {\n if (f instanceof RegExp) {\n userIconFonts.push(f);\n } else if (typeof f === \"string\") {\n userIconFonts.push(new RegExp(f, \"i\"));\n } else {\n console.warn(\"[snapdom] Ignored invalid iconFont value:\", f);\n }\n }\n}\n\nexport function isIconFont(input) {\n const text = typeof input === \"string\" ? input : \"\";\n\n const candidates = [...defaultIconFonts, ...userIconFonts];\n\n for (const rx of candidates) {\n if (rx instanceof RegExp && rx.test(text)) return true;\n }\n\n // Heurística básica\n if (\n /icon/i.test(text) ||\n /glyph/i.test(text) ||\n /symbols/i.test(text) ||\n /feather/i.test(text) ||\n /fontawesome/i.test(text)\n ) return true;\n\n return false;\n}"], ["/snapdom/__tests__/helpers.utils.test.js", "import { describe, it, expect, vi } from 'vitest';\nimport { getStyle, parseContent, extractURL, isIconFont, snapshotComputedStyle, isSafari, stripTranslate, safeEncodeURI, idle, fetchImage } from '../src/utils/helpers.js';\n\ndescribe('getStyle', () => {\n it('returns a CSSStyleDeclaration', () => {\n const el = document.createElement('div');\n document.body.appendChild(el);\n const style = getStyle(el);\n expect(style).toBeInstanceOf(CSSStyleDeclaration);\n document.body.removeChild(el);\n });\n});\n\n\n\ndescribe('parseContent', () => {\n it('parses CSS content correctly', () => {\n expect(parseContent('\"★\"')).toBe('★');\n expect(parseContent('\\\\2605')).toBe('★');\n });\n});\n\ndescribe('parseContent edge cases', () => {\n it('returns \\u0000 if parseInt fails (not hex)', () => {\n expect(parseContent('\\\\nothex')).toBe('\\u0000');\n });\n it('returns clean if String.fromCharCode throws', () => {\n const orig = String.fromCharCode;\n String.fromCharCode = () => { throw new Error('fail'); };\n expect(parseContent('\\\\2605')).toBe('\\\\2605');\n String.fromCharCode = orig;\n });\n});\n\ndescribe('extractURL', () => {\n it('extracts the URL from background-image', () => {\n expect(extractURL('url(\"https://test.com/img.png\")')).toBe('https://test.com/img.png');\n expect(extractURL('none')).toBeNull();\n });\n});\n\ndescribe('isIconFont', () => {\n it('detects icon fonts', () => {\n expect(isIconFont('Font Awesome')).toBe(true);\n expect(isIconFont('Arial')).toBe(false);\n });\n});\n\ndescribe('snapshotComputedStyle', () => {\n it('returns a style snapshot', () => {\n const el = document.createElement('div');\n document.body.appendChild(el);\n const style = getComputedStyle(el);\n const snap = snapshotComputedStyle(style);\n expect(typeof snap).toBe('object');\n document.body.removeChild(el);\n });\n});\n\ndescribe('isSafari', () => {\n it('returns a boolean', () => {\n expect(typeof isSafari()).toBe('boolean');\n });\n});\n\ndescribe('stripTranslate', () => {\n it('removes translate transforms', () => {\n expect(stripTranslate('translateX(10px) scale(2)')).toContain('scale(2)');\n });\n it('stripTranslate removes matrix and matrix3d', () => {\n expect(stripTranslate('matrix(1,0,0,1,10,20)')).not.toContain('10,20');\n expect(stripTranslate('matrix3d(1,0,0,0,0,1,0,0,0,0,1,0,10,20,30,1)')).not.toContain('10,20,30');\n });\n});\n\ndescribe('safeEncodeURI', () => {\n it('returns an encoded string', () => {\n expect(typeof safeEncodeURI('https://test.com/á')).toBe('string');\n });\n it('safeEncodeURI handles invalid URIs gracefully', () => {\n expect(typeof safeEncodeURI('%E0%A4%A')).toBe('string');\n });\n});\n\ndescribe('idle', () => {\n it('calls fn immediately if fast is true', () => {\n let called = false;\n idle(() => { called = true; }, { fast: true });\n expect(called).toBe(true);\n });\n it('uses requestIdleCallback if available', () => {\n const orig = window.requestIdleCallback;\n let called = false;\n window.requestIdleCallback = (fn) => { called = true; fn(); };\n idle(() => { called = true; });\n expect(called).toBe(true);\n window.requestIdleCallback = orig;\n });\n it('falls back to setTimeout if requestIdleCallback not available', async () => {\n const orig = window.requestIdleCallback;\n delete window.requestIdleCallback;\n let called = false;\n idle(() => { called = true; });\n await new Promise(r => setTimeout(r, 10));\n expect(called).toBe(true);\n window.requestIdleCallback = orig;\n });\n});\n\ndescribe('fetchImage', () => {\n it('rejects on image error', async () => {\n await expect(fetchImage('invalid-url', { timeout: 100 }))\n .rejects.toThrow('Fetch fallback failed and no proxy provided');\n\n });\n it('rejects on timeout', async () => {\n // Simula una imagen que nunca carga\n const origImage = window.Image;\n window.Image = class { set src(_){} onload(){} onerror(){} };\n await expect(fetchImage('timeout-url', { timeout: 10 })).rejects.toThrow('Image load timed out');\n window.Image = origImage;\n });\n\n});\n\ndescribe('fetchImage cache', () => {\n it('returns cached image if present', async () => {\n const { cache } = await import('../src/core/cache.js');\n cache.image.set('cached-url', 'data:image/png;base64,abc');\n const result = await fetchImage('cached-url', { useProxy: false });\n expect(result).toBe('data:image/png;base64,abc');\n cache.image.delete('cached-url');\n });\n});\n\ndescribe('fetchImage error propagation', () => {\n it('rejects with original error if decode fails', async () => {\n const origImage = window.Image;\n window.Image = class {\n constructor() { setTimeout(() => this.onload(), 1); }\n set src(_){}\n decode() { return Promise.reject(new Error('decode fail')); }\n get width() { return 1; }\n get height() { return 1; }\n };\n await expect(fetchImage('decode-fail-url', { timeout: 100 }))\n .rejects.toThrow('Fetch fallback failed and no proxy provided');\n window.Image = origImage;\n });\n});\n\ndescribe('stripTranslate edge cases', () => {\n it('returns empty string for empty or none', () => {\n expect(stripTranslate('')).toBe('');\n expect(stripTranslate('none')).toBe('');\n });\n it('returns original for malformed matrix', () => {\n expect(stripTranslate('matrix(1,2,3)')).toBe('matrix(1,2,3)');\n expect(stripTranslate('matrix3d(1,2,3)')).toBe('matrix3d(1,2,3)');\n });\n});\n"], ["/snapdom/__tests__/snapdom.vs.htm2canvas.outputfilesize.test.js", "import { describe, it, beforeEach, afterEach, afterAll } from 'vitest';\nimport { snapdom } from '../src/index';\n//ok\n\ndescribe('Output file size snapdom vs html2canvas (cdn with averaging)', () => {\n let container;\n let html2canvas;\n let report;\n\n beforeEach(async () => {\n container = document.createElement('div');\n container.style.width = '400px';\n container.style.height = '300px';\n container.style.background = 'linear-gradient(to right, red, blue)';\n container.innerHTML = '

Hello Benchmark

Testing multiple runs...

';\n document.body.appendChild(container);\n\n if (!html2canvas) {\n // Cargar html2canvas desde CDN\n await new Promise((resolve, reject) => {\n const script = document.createElement('script');\n script.src = 'https://cdn.jsdelivr.net/npm/html2canvas@1.4.1/dist/html2canvas.min.js';\n script.onload = () => {\n html2canvas = window.html2canvas;\n resolve();\n };\n script.onerror = reject;\n document.head.appendChild(script);\n });\n }\n });\n\n afterEach(() => {\n document.body.removeChild(container);\n });\n\n afterAll(() => {\n console.log(report)\n })\n\n it('snapdom output file size should be smaller than html2canvas', async () => {\n \n // SnapDOM capture\n const snapdomDataURL = await snapdom.toRaw(container, {compress: true});\n const snapdomSizeKB = (snapdomDataURL.length * 3 / 4) / 1024; // Base64 to bytes approx\n \n // html2canvas capture\n const canvas = await html2canvas(container, { logging: false });\n const html2canvasDataURL = await canvas.toDataURL();\n const html2canvasSizeKB = (html2canvasDataURL.length * 3 / 4) / 1024; // Base64 to bytes approx\n \n const differencePercent = ((html2canvasSizeKB - snapdomSizeKB) / html2canvasSizeKB) * 100;\n\n report =`snapDom Captured file size is ${differencePercent.toFixed(2)}% smaller compared to html2canvas (${snapdomSizeKB.toFixed(2)} KB vs. ${html2canvasSizeKB.toFixed(2)} KB)`\n\n})\n\n})\n"], ["/snapdom/__tests__/fonts.module.test.js", "import { describe, it, expect, beforeEach, vi } from 'vitest';\nimport { iconToImage, embedCustomFonts } from '../src/modules/fonts.js';\nimport { cache } from '../src/core/cache.js';\n\n// Utilidad para limpiar estilos y links antes de cada test\nfunction cleanFontEnvironment() {\n document.querySelectorAll('style,link[rel=\"stylesheet\"]').forEach(s => s.remove());\n}\n\nfunction addStyleTag(css) {\n const style = document.createElement('style');\n style.setAttribute('data-test-style', 'true');\n style.textContent = css;\n document.head.appendChild(style);\n return style;\n}\n\ndescribe('iconToImage', () => {\n it('genera un dataURL para un carácter unicode', async () => {\n const url = await iconToImage('★', 'Arial', 'bold', 32, '#000');\n expect(url.startsWith('data:image/')).toBe(true);\n });\n\n it('maneja diferentes pesos y colores de fuente', async () => {\n const url = await iconToImage('★', 'Arial', 700, 40, '#ff0000');\n expect(url.startsWith('data:image/')).toBe(true);\n });\n\n it('usa valores por defecto si no hay métricas', async () => {\n const orig = HTMLCanvasElement.prototype.getContext;\n HTMLCanvasElement.prototype.getContext = function() {\n return {\n font: '',\n scale: vi.fn(),\n textAlign: '',\n textBaseline: '',\n fillStyle: '',\n fillText: vi.fn(),\n measureText: () => ({ width: 10 })\n };\n };\n const url = await iconToImage('★', 'Arial', 'bold', 32, '#000');\n expect(url.startsWith('data:image/')).toBe(true);\n HTMLCanvasElement.prototype.getContext = orig;\n });\n});\n\ndescribe('embedCustomFonts', () => {\n beforeEach(() => {\n cache.reset();\n cache.font.clear();\n cache.resource.clear();\n cleanFontEnvironment();\n vi.restoreAllMocks();\n });\n\n it('conserva @font-face con solo local() en src', async () => {\n const style = addStyleTag(`\n @font-face {\n font-family: OnlyLocal;\n src: local(\"Arial\");\n font-style: normal;\n font-weight: normal;\n }\n `);\n\n const css = await embedCustomFonts();\n expect(css).toMatch(/font-family:\\s*OnlyLocal/);\n expect(css).toMatch(/src:\\s*local\\([\"']Arial[\"']\\)/);\n document.head.removeChild(style);\n });\n\n it('conserva @font-face con local() y sin url()', async () => {\n const style = addStyleTag(`\n @font-face {\n font-family: LocalFont;\n src: local('MyFont'), local('FallbackFont');\n font-style: italic;\n font-weight: bold;\n }\n `);\n\n const css = await embedCustomFonts();\n expect(css).toMatch(/font-family:\\s*LocalFont/);\n expect(css).toMatch(/src:\\s*local\\(['\"]MyFont['\"]\\),\\s*local\\(['\"]FallbackFont['\"]\\)/);\n expect(css).toMatch(/font-style:\\s*italic/);\n document.head.removeChild(style);\n });\n});\n"], ["/snapdom/__tests__/prepare.core.test.js", "import { describe, it, expect, vi } from 'vitest';\nimport { prepareClone } from '../src/core/prepare.js';\n\ndescribe('prepareClone', () => {\n it('prepares a clone of a div', async () => {\n const el = document.createElement('div');\n el.textContent = 'test';\n const { clone, classCSS } = await prepareClone(el);\n expect(clone).not.toBeNull();\n expect(typeof classCSS).toBe('string');\n });\n});\n\ndescribe('prepareClone edge cases', () => {\n it('throws for null node', async () => {\n await expect(prepareClone(null)).rejects.toThrow();\n });\n it('returns a comment clone for unsupported node', async () => {\n const fake = document.createComment('not supported');\n const result = await prepareClone(fake);\n expect(result.clone.nodeType).toBe(Node.COMMENT_NODE);\n });\n it('handles error in internal logic', async () => {\n const el = document.createElement('div');\n vi.spyOn(el, 'cloneNode').mockImplementation(() => { throw new Error('fail'); });\n await expect(prepareClone(el)).rejects.toThrow('fail');\n });\n it('clones attributes and children', async () => {\n const el = document.createElement('div');\n el.setAttribute('data-test', '1');\n const result = await prepareClone(el);\n expect(result.clone.getAttribute('data-test')).toBe('1');\n });\n});\n"], ["/snapdom/__tests__/capture.core.test.js", "import { describe, it, expect, vi } from 'vitest';\nimport { captureDOM } from '../src/core/capture.js';\n\ndescribe('captureDOM edge cases', () => {\n it('throws for unsupported element (unknown nodeType)', async () => {\n // Simulate a node with an invalid nodeType\n const fakeNode = { nodeType: 999 };\n await expect(captureDOM(fakeNode)).rejects.toThrow();\n });\n\n it('throws if element is null', async () => {\n await expect(captureDOM(null)).rejects.toThrow();\n });\n\n it('throws error if getBoundingClientRect fails', async () => {\n const el = document.createElement('div');\n vi.spyOn(el, 'getBoundingClientRect').mockImplementation(() => { throw new Error('fail'); });\n await expect(captureDOM(el)).rejects.toThrow('fail');\n });\n});\n\ndescribe('captureDOM functional', () => {\n it('captures a simple div and returns an SVG dataURL', async () => {\n const el = document.createElement('div');\n el.textContent = 'test';\n const url = await captureDOM(el);\n expect(url.startsWith('data:image/svg+xml')).toBe(true);\n });\n\n it('supports scale and width/height options', async () => {\n const el = document.createElement('div');\n el.style.width = '100px';\n el.style.height = '50px';\n await captureDOM(el, { scale: 2 });\n await captureDOM(el, { width: 200 });\n await captureDOM(el, { height: 100 });\n });\n\n it('supports fast=false', async () => {\n const el = document.createElement('div');\n await captureDOM(el, { fast: false });\n });\n\n it('supports embedFonts', async () => {\n const el = document.createElement('div');\n await captureDOM(el, { embedFonts: true });\n });\n});\n"], ["/snapdom/__tests__/pseudo.bg-inline-success.test.js", "vi.mock('../src/utils/helpers.js', async () => {\n const actual = await vi.importActual('../src/utils/helpers.js');\n return {\n ...actual,\n inlineSingleBackgroundEntry: vi.fn().mockResolvedValue('url(\"data:image/png;base64,abc\")'),\n };\n});\n\nimport { describe, it, vi } from 'vitest';\nimport { inlinePseudoElements } from '../src/modules/pseudo.js';\n\ndescribe('inlinePseudoElements background-image inlining (success)', () => {\n it('cubre el inlining exitoso de background-image en pseudo', async () => {\n const el = document.createElement('div');\n const clone = document.createElement('div');\n vi.spyOn(window, 'getComputedStyle').mockImplementation((_, pseudo) => {\n if (pseudo === '::before') return {\n getPropertyValue: (prop) => prop === 'content' ? 'none' : prop === 'font-family' ? 'Arial' : prop === 'font-size' ? '32' : prop === 'font-weight' ? '400' : prop === 'color' ? '#000' : prop === 'background-image' ? 'url(\"data:image/png;base64,abc\")' : prop === 'background-color' ? 'transparent' : '',\n color: '#000', fontSize: '32px', fontWeight: '400', fontFamily: 'Arial',\n };\n return { getPropertyValue: () => '', color: '', fontSize: '', fontWeight: '', fontFamily: '' };\n });\n await inlinePseudoElements(el, clone, new Map(), new WeakMap(), false);\n window.getComputedStyle.mockRestore();\n });\n});\n"], ["/snapdom/__tests__/pseudo.bg-inline-error.test.js", "vi.mock('../src/utils/helpers.js', async () => {\n const actual = await vi.importActual('../src/utils/helpers.js');\n return {\n ...actual,\n inlineSingleBackgroundEntry: vi.fn().mockRejectedValue(new Error('fail')),\n };\n});\n\nimport { describe, it, vi } from 'vitest';\nimport { inlinePseudoElements } from '../src/modules/pseudo.js';\n\ndescribe('inlinePseudoElements background-image inlining (error)', () => {\n it('cubre el catch de error en inlining de background-image en pseudo', async () => {\n const el = document.createElement('div');\n const clone = document.createElement('div');\n vi.spyOn(window, 'getComputedStyle').mockImplementation((_, pseudo) => {\n if (pseudo === '::before') return {\n getPropertyValue: (prop) => prop === 'content' ? 'none' : prop === 'font-family' ? 'Arial' : prop === 'font-size' ? '32' : prop === 'font-weight' ? '400' : prop === 'color' ? '#000' : prop === 'background-image' ? 'url(\"data:image/png;base64,abc\")' : prop === 'background-color' ? 'transparent' : '',\n color: '#000', fontSize: '32px', fontWeight: '400', fontFamily: 'Arial',\n };\n return { getPropertyValue: () => '', color: '', fontSize: '', fontWeight: '', fontFamily: '' };\n });\n await inlinePseudoElements(el, clone, new Map(), new WeakMap(), false);\n window.getComputedStyle.mockRestore();\n });\n});\n"], ["/snapdom/__tests__/snapdom.api.test.js", "import { describe, it, expect, vi } from 'vitest';\nimport { snapdom } from '../src/api/snapdom.js';\n\ndescribe('snapdom API (direct)', () => {\n it('throws on null element', async () => {\n await expect(snapdom(null)).rejects.toThrow();\n });\n\n it('snapdom.capture returns export methods', async () => {\n const el = document.createElement('div');\n el.style.width = '100px';\n el.style.height = '50px';\n document.body.appendChild(el);\n const result = await snapdom.capture(el);\n expect(result).toHaveProperty('toRaw');\n expect(result).toHaveProperty('toImg');\n expect(result).toHaveProperty('download');\n document.body.removeChild(el);\n });\n\n it('snapdom.toRaw, toImg, toCanvas, toBlob, toPng, toJpg, toWebp, download', async () => {\n const el = document.createElement('div');\n el.style.width = '100px';\n el.style.height = '50px';\n document.body.appendChild(el);\n await snapdom.toRaw(el);\n await snapdom.toImg(el);\n await snapdom.toCanvas(el);\n await snapdom.toBlob(el);\n await snapdom.toPng(el);\n await snapdom.toJpg(el);\n await snapdom.toWebp(el);\n await snapdom.download(el, { format: 'png', filename: 'test' });\n document.body.removeChild(el);\n });\n\n it('cubre rama Safari en toImg', async () => {\n vi.resetModules();\n vi.mock('../utils/helpers.js', async () => {\n const actual = await vi.importActual('../utils/helpers.js');\n return { ...actual, isSafari: true };\n });\n const { snapdom } = await import('../src/api/snapdom.js');\n const el = document.createElement('div');\n el.style.width = '10px';\n el.style.height = '10px';\n document.body.appendChild(el);\n // Forzar un SVG dataURL simple\n const img = new Image();\n img.width = 10;\n img.height = 10;\n img.decode = () => Promise.resolve();\n globalThis.Image = function() { return img; };\n const res = await snapdom.capture(el);\n await res.toImg();\n document.body.removeChild(el);\n vi.resetModules();\n });\n\n it('cubre rama de download SVG', async () => {\n const el = document.createElement('div');\n el.style.width = '10px';\n el.style.height = '10px';\n document.body.appendChild(el);\n // Mock a.click y URL.createObjectURL\n const a = document.createElement('a');\n document.body.appendChild(a);\n const origCreate = URL.createObjectURL;\n URL.createObjectURL = () => 'blob:url';\n const origClick = a.click;\n a.click = () => {};\n HTMLAnchorElement.prototype.click = () => {};\n const { snapdom } = await import('../src/api/snapdom.js');\n await snapdom.download(el, { format: 'svg', filename: 'testsvg' });\n URL.createObjectURL = origCreate;\n a.click = origClick;\n document.body.removeChild(a);\n document.body.removeChild(el);\n });\n\n it('snapdom.toBlob supports type options ', async () => {\n const el = document.createElement('div');\n el.style.width = '50px';\n el.style.height = '30px';\n document.body.appendChild(el);\n\n const result = await snapdom.capture(el);\n\n const pngBlob = await result.toBlob({ type: 'png' });\n expect(pngBlob).toBeInstanceOf(Blob);\n expect(pngBlob.type).toBe('image/png');\n\n const jpgBlob = await result.toBlob({ type: 'jpeg', quality: 0.8 });\n expect(jpgBlob).toBeInstanceOf(Blob);\n expect(jpgBlob.type).toBe('image/jpeg');\n\n const webpBlob = await result.toBlob({ type: 'webp', quality: 0.9 });\n expect(webpBlob).toBeInstanceOf(Blob);\n expect(webpBlob.type).toBe('image/webp');\n\n // default fallback\n const svgBlob = await result.toBlob();\n expect(svgBlob).toBeInstanceOf(Blob);\n expect(svgBlob.type).toBe('image/svg+xml');\n\n document.body.removeChild(el);\n});\n\nit('toPng, toJpg, toWebp return HTMLImageElement with URLs', async () => {\n const el = document.createElement('div');\n el.style.width = '60px';\n el.style.height = '40px';\n document.body.appendChild(el);\n const snap = await snapdom.capture(el);\n\n const pngImg = await snap.toPng();\n expect(pngImg).toBeInstanceOf(HTMLImageElement);\n expect(typeof pngImg.src).toBe('string');\nexpect(pngImg.src.startsWith('data:image/png')).toBe(true);\n\n const jpgImg = await snap.toJpg();\n expect(jpgImg).toBeInstanceOf(HTMLImageElement);\n expect(typeof jpgImg.src).toBe('string');\nexpect(jpgImg.src.startsWith('data:image/jpeg')).toBe(true);\n\n const webpImg = await snap.toWebp();\n expect(webpImg).toBeInstanceOf(HTMLImageElement);\n expect(typeof webpImg.src).toBe('string');\nexpect(webpImg.src.startsWith('data:image/webp')).toBe(true);\n document.body.removeChild(el);\n});\n\nit('snapdom should support exclude option to filter out elements by CSS selectors', async () => {\n const el = document.createElement('div');\n el.innerHTML = `\n

Title

\n
Should be excluded
\n
Private data
\n

This should remain

\n `;\n document.body.appendChild(el);\n \n const result = await snapdom(el, { exclude: ['.exclude-me', '[data-private]'] });\n \n const svg = result.toRaw();\n const decoded = decodeURIComponent(svg.split(\",\")[1]);\n expect(decoded).not.toContain('Should be excluded');\n expect(decoded).not.toContain('Private data');\n expect(decoded).toContain('Title');\n expect(decoded).toContain('This should remain');\n});\n\nit('snapdom should support filter option to exclude elements with custom logic', async () => {\n const el = document.createElement('div');\n el.innerHTML = `\n
Level 1\n
Level 2\n
Level 3
\n
\n
\n `;\n document.body.appendChild(el);\n const result = await snapdom(el, { \n filter: (element) => !element.classList.contains('level-3')\n });\n \n const svg = result.toRaw();\n const decoded = decodeURIComponent(svg.split(\",\")[1]);\n expect(decoded).toContain('Level 1');\n expect(decoded).toContain('Level 2');\n expect(decoded).not.toContain('Level 3');\n});\n\nit('snapdom should support combining exclude and filter options', async () => {\n const el = document.createElement('div');\n el.innerHTML = `\n
Exclude by selector
\n
Exclude by filter
\n
Keep this content
\n `;\n document.body.appendChild(el);\n\n const result = await snapdom(el, { \n exclude: ['.exclude-by-selector'],\n filter: (element) => !element.classList.contains('exclude-by-filter')\n });\n \n \n const svg = result.toRaw();\n const decoded = decodeURIComponent(svg.split(\",\")[1]);\n expect(decoded).not.toContain('Exclude by selector');\n expect(decoded).not.toContain('Exclude by filter');\n expect(decoded).toContain('Keep this content');\n});\n\n});\n"], ["/snapdom/__tests__/snapdom.advance.test.js", "import { describe, it, expect, beforeEach, afterEach } from 'vitest';\nimport { snapdom } from '../src/index';\n\ndescribe('snapdom advanced tests', () => {\n let testElement;\n\n beforeEach(() => {\n testElement = document.createElement('div');\n testElement.style.width = '100px';\n testElement.style.height = '50px';\n testElement.innerHTML = '

Hello World

';\n document.body.appendChild(testElement);\n });\n\n afterEach(() => {\n document.body.removeChild(testElement);\n });\n\n it('should generate different SVGs for different scales', async () => {\n const svg1 = await snapdom.toImg(testElement, { scale: 1 });\n const svg2 = await snapdom.toImg(testElement, { scale: 2 });\n expect(svg1).not.toBe(svg2);\n });\n\n it('captured SVG should contain inner text content', async () => {\n const svgDataUrl = await snapdom.toRaw(testElement);\n const svgText = decodeURIComponent(svgDataUrl.split(',')[1]);\n expect(svgText).toContain('Hello World');\n });\n\n it('should throw an error if element is null', async () => {\n await expect(() => snapdom.toRaw(null)).rejects.toThrow();\n });\n\n it('should generate SVG with correct attributes', async () => {\n const svgDataUrl = await snapdom.toRaw(testElement);\n const svgText = decodeURIComponent(svgDataUrl.split(',')[1]);\n const parser = new DOMParser();\n const doc = parser.parseFromString(svgText, 'image/svg+xml');\n const svg = doc.querySelector('svg');\n\n expect(svg).not.toBeNull();\n expect(svg.getAttribute('width')).toBe('100');\n expect(svg.getAttribute('height')).toBe('50');\n expect(svg.getAttribute('viewBox')).toBe('0 0 100 50');\n });\n\n it('snapdom.toBlob should contain valid SVG content', async () => {\n const blob = await snapdom.toBlob(testElement);\n const text = await blob.text();\n expect(text).toContain('');\n });\n\n it('should replace iframes with fallback visuals', async () => {\n const iframe = document.createElement('iframe');\n iframe.style.width = '200px';\n iframe.style.height = '100px';\n testElement.appendChild(iframe);\n\n const svgDataUrl = await snapdom.toRaw(testElement);\n const svgText = decodeURIComponent(svgDataUrl.split(',')[1]);\n\n const parser = new DOMParser();\n const doc = parser.parseFromString(svgText, 'image/svg+xml');\n\n // No debe haber iframes en el SVG\n expect(doc.querySelectorAll('iframe').length).toBe(0);\n\n // Buscamos divs con estilo inline que contengan repeating-linear-gradient\n const fallbackDivs = Array.from(doc.querySelectorAll('div')).filter(div => {\n const styleAttr = div.getAttribute('style') || '';\n return styleAttr.includes('repeating-linear-gradient');\n });\n\n expect(fallbackDivs.length).toBeGreaterThan(0);\n});\n\n \n});\n"], ["/snapdom/__tests__/background.module.test.js", "import { describe, it, expect, beforeEach, afterEach } from 'vitest';\nimport { inlineBackgroundImages } from '../src/modules/background.js';\n\ndescribe('inlineBackgroundImages', () => {\n let source, clone;\n beforeEach(() => {\n source = document.createElement('div');\n clone = document.createElement('div');\n document.body.appendChild(source);\n document.body.appendChild(clone);\n });\n afterEach(() => {\n document.body.removeChild(source);\n document.body.removeChild(clone);\n });\n\n it('does not fail if there is no background-image', async () => {\n source.style.background = 'none';\n await expect(inlineBackgroundImages(source, clone, new WeakMap())).resolves.toBeUndefined();\n });\n\n it('processes a valid background-image', async () => {\n source.style.backgroundImage = 'url(\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/w8AAn8B9p6Q2wAAAABJRU5ErkJggg==\")';\n await expect(inlineBackgroundImages(source, clone, new WeakMap())).resolves.toBeUndefined();\n });\n});\n"], ["/snapdom/__tests__/snapdom.vs.modernscreenshot.outputfilesize.test.js", "import { describe, it, beforeEach, afterEach, afterAll } from 'vitest';\nimport { domToDataUrl} from 'https://unpkg.com/modern-screenshot';\nimport { snapdom } from '../src/index';\n//ok\n\ndescribe('Output file size snapdom vs modern-screeenshot (cdn with averaging)', () => {\n let container;\n\n let report;\n\n beforeEach(async () => {\n container = document.createElement('div');\n container.style.width = '400px';\n container.style.height = '300px';\n container.style.background = 'linear-gradient(to right, red, blue)';\n container.innerHTML = '

Hello Benchmark

Testing multiple runs...

';\n document.body.appendChild(container);\n });\n\n afterEach(() => {\n document.body.removeChild(container);\n });\n\n afterAll(() => {\n console.log(report)\n })\n\n it('snapdom output file size should be smaller than modern-screenshot', async () => {\n \n // SnapDOM capture\n const snapdomDataURL = await snapdom.toRaw(container, {compress: true});\n const snapdomSizeKB = (snapdomDataURL.length * 3 / 4) / 1024; // Base64 to bytes approx\n \n // domToDataUrl capture\n const domToDataUrlDataURL = await domToDataUrl(container);\n const domToDataUrlSizeKB = (domToDataUrlDataURL.length * 3 / 4) / 1024; // Base64 to bytes approx\n \n const differencePercent = ((domToDataUrlSizeKB - snapdomSizeKB) / domToDataUrlSizeKB) * 100;\n\n report =`snapdom captured file size is ${differencePercent.toFixed(2)}% smaller compared to modern-screenshot (${snapdomSizeKB.toFixed(2)} KB vs. ${domToDataUrlSizeKB.toFixed(2)} KB)`\n\n})\n\n})\n"], ["/snapdom/__tests__/preCache.api.test.js", "import { describe, it, expect, beforeEach } from 'vitest';\nimport { preCache } from '../src/api/preCache.js';\nimport { cache } from '../src/core/cache.js';\n\ndescribe('preCache', () => {\n beforeEach(() => {\n cache.reset()\n });\n\n it('pre-caches images and backgrounds', async () => {\n const el = document.createElement('div');\n const img = document.createElement('img');\n img.src = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/w8AAn8B9p6Q2wAAAABJRU5ErkJggg==';\n el.appendChild(img);\n document.body.appendChild(el);\n await preCache(el);\n expect(cache.image.has(img.src)).toBe(true);\n document.body.removeChild(el);\n });\n\n it('should handle preCache with embedFonts false', async () => {\n const el = document.createElement('div');\n await expect(preCache(el, { embedFonts: false })).resolves.toBeUndefined();\n });\n\n it('should handle preCache with images that fail to load', async () => {\n const el = document.createElement('div');\n const img = document.createElement('img');\n img.src = 'invalid-url.png';\n el.appendChild(img);\n await expect(preCache(el)).resolves.toBeUndefined();\n });\n\n it('should handle preCache with backgrounds that fail to load', async () => {\n const el = document.createElement('div');\n el.style.backgroundImage = 'url(invalid-url.png)';\n document.body.appendChild(el);\n await expect(preCache(el)).resolves.toBeUndefined();\n document.body.removeChild(el);\n });\n\n it('limpia los caches y retorna si reset=true', async () => {\n // Prellenar los caches\n cache.snapshotKey.set('foo', 'bar');\n cache.preStyleMap.set('foo', 'bar');\n cache.preNodeMap.set('foo', 'bar');\n await preCache(document, { reset: true });\n expect(cache.snapshotKey.size).toBe(0);\n expect(cache.preStyleMap.size).toBe(0);\n expect(cache.preNodeMap.size).toBe(0);\n });\n\n it('procesa múltiples backgrounds en un solo elemento', async () => {\n const el = document.createElement('div');\n el.style.backgroundImage = 'url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/w8AAn8B9p6Q2wAAAABJRU5ErkJggg==), url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/w8AAn8B9p6Q2wAAAABJRU5ErkJggg==)';\n document.body.appendChild(el);\n await preCache(el);\n // No assertion estricta porque depende de helpers, pero no debe lanzar error\n document.body.removeChild(el);\n });\n\n});\n"], ["/snapdom/__tests__/snapdom.attributes.test.js", "import { describe, it, expect, beforeEach, afterEach } from 'vitest';\nimport { snapdom } from '../src/index';\n\ndescribe('snapdom capture attributes', () => {\n let container;\n\n beforeEach(() => {\n container = document.createElement('div');\n container.style.width = '300px';\n container.style.height = '150px';\n document.body.appendChild(container);\n });\n\n afterEach(() => {\n document.body.removeChild(container);\n });\n\n it('should exclude elements with data-capture=\"exclude\"', async () => {\n const excluded = document.createElement('div');\n excluded.setAttribute('data-capture', 'exclude');\n excluded.textContent = 'Should be excluded';\n container.appendChild(excluded);\n\n const svgDataUrl = await snapdom.toRaw(container);\n const svgText = decodeURIComponent(svgDataUrl.split(',')[1]);\n \n expect(svgText).not.toContain('Should be excluded');\n });\n\n it('should replace elements with data-capture=\"placeholder\" and show placeholder text', async () => {\n const placeholder = document.createElement('div');\n placeholder.setAttribute('data-capture', 'placeholder');\n placeholder.setAttribute('data-placeholder-text', 'Placeholder here');\n placeholder.textContent = 'Original text';\n container.appendChild(placeholder);\n\n const svgDataUrl = await snapdom.toRaw(container);\n const svgText = decodeURIComponent(svgDataUrl.split(',')[1]);\n \n expect(svgText).toContain('Placeholder here');\n expect(svgText).not.toContain('Original text');\n });\n});\n"], ["/snapdom/__tests__/snapdom.backgroundColor.test.js", "import { describe, it, expect, beforeEach, afterEach } from 'vitest';\nimport { snapdom } from '../src/index';\n\ndescribe('snapdom.toJpg backgroundColor option', () => {\n let container;\n\n beforeEach(() => {\n container = document.createElement('div');\n container.style.width = '100px';\n container.style.height = '100px';\n container.style.background = 'transparent';\n document.body.appendChild(container);\n });\n\n it('applies white background by default', async () => {\n const img = await snapdom.toJpg(container );\n const canvas = document.createElement('canvas');\n canvas.width = img.width;\n canvas.height = img.height;\n const ctx = canvas.getContext('2d');\n ctx.drawImage(img, 0, 0);\n const pixel = ctx.getImageData(0, 0, 1, 1).data;\n // JPEG compresses, but for a solid color it should be near white\n expect(pixel[0]).toBeGreaterThan(240);\n expect(pixel[1]).toBeGreaterThan(240);\n expect(pixel[2]).toBeGreaterThan(240);\n });\n\n it('applies custom background color', async () => {\n const img = await snapdom.toJpg(container, { backgroundColor: '#00ff00' });\n const canvas = document.createElement('canvas');\n canvas.width = img.width;\n canvas.height = img.height;\n const ctx = canvas.getContext('2d');\n ctx.drawImage(img, 0, 0);\n const pixel = ctx.getImageData(0, 0, 1, 1).data;\n // Green check (JPEG lossy, so check near values)\n expect(pixel[0]).toBeLessThan(30); // red\n expect(pixel[1]).toBeGreaterThan(200); // green\n expect(pixel[2]).toBeLessThan(30); // blue\n });\n});\n"], ["/snapdom/__tests__/styles.module.test.js", "import { describe, it, expect } from 'vitest';\nimport { inlineAllStyles } from '../src/modules/styles.js';\nimport { cache } from '../src/core/cache.js';\n\ndescribe('inlineAllStyles', () => {\n it('adds a style key to the styleMap', () => {\n const el = document.createElement('div');\n const clone = document.createElement('div');\n inlineAllStyles(el, clone, false);\n expect(cache.preStyleMap.has(clone)).toBe(true);\n });\n});"], ["/snapdom/__tests__/snapdom.test.js", "import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';\nimport { snapdom } from '../src/index';\n\ndescribe('snapdom API', () => {\n let testElement;\n\n beforeEach(() => {\n testElement = document.createElement('div');\n testElement.style.width = '100px';\n testElement.style.height = '50px';\n document.body.appendChild(testElement );\n });\n\n afterEach(() => {\n document.body.removeChild(testElement );\n });\n\n describe('snapdom.toRaw', () => {\n it('should return a SVG data URL', async () => {\n const result = await snapdom.toRaw(testElement );\n expect(result).toMatch(/^data:image\\/svg\\+xml/);\n });\n });\n\n describe('snapdom', () => {\n it('toImg should return an HTMLImageElement', async () => {\n \n const img = await snapdom.toImg(testElement );\n expect(img).toBeInstanceOf(HTMLImageElement);\n expect(img.src).toMatch(/^data:image\\/svg\\+xml/);\n \n });\n\n it('toCanvas should return a HTMLCanvasElement', async () => {\n // const decodeMock = vi.spyOn(window.Image.prototype, 'decode').mockResolvedValue();\n const canvas = await snapdom.toCanvas(testElement );\n expect(canvas).toBeInstanceOf(HTMLCanvasElement);\n // decodeMock.mockRestore();\n });\n\n it('toPng should return an HTMLImageElement with PNG data URL', async () => {\n // const decodeMock = vi.spyOn(window.Image.prototype, 'decode').mockResolvedValue();\n const img = await snapdom.toPng(testElement );\n expect(img).toBeInstanceOf(HTMLImageElement);\n expect(img.src).toMatch(/^data:image\\/png/);\n // decodeMock.mockRestore();\n });\n\n it('toJpg should return an HTMLImageElement with JPEG data URL', async () => {\n // const decodeMock = vi.spyOn(window.Image.prototype, 'decode').mockResolvedValue();\n const img = await snapdom.toJpg(testElement );\n expect(img).toBeInstanceOf(HTMLImageElement);\n expect(img.src).toMatch(/^data:image\\/jpeg/);\n // decodeMock.mockRestore();\n });\n\n it('toWebp should return an HTMLImageElement with WebP data URL', async () => {\n // const decodeMock = vi.spyOn(window.Image.prototype, 'decode').mockResolvedValue();\n const img = await snapdom.toWebp(testElement );\n expect(img).toBeInstanceOf(HTMLImageElement);\n expect(img.src).toMatch(/^data:image\\/webp/);\n // decodeMock.mockRestore();\n });\n\n it('toBlob should return a Blob of type image/svg+xml', async () => {\n const blob = await snapdom.toBlob(testElement );\n expect(blob).toBeInstanceOf(Blob);\n expect(blob.type).toBe('image/svg+xml');\n });\n });\n});\n"], ["/snapdom/__tests__/images.module.test.js", "import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';\nimport { inlineImages } from '../src/modules/images.js';\n\ndescribe('inlineImages', () => {\n let container;\n beforeEach(() => {\n container = document.createElement('div');\n document.body.appendChild(container);\n });\n afterEach(() => {\n document.body.removeChild(container);\n });\n\n it('converts to dataURL if the image loads', async () => {\n const img = document.createElement('img');\n img.src = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/w8AAn8B9p6Q2wAAAABJRU5ErkJggg==';\n container.appendChild(img);\n await inlineImages(container);\n expect(img.src.startsWith('data:image/')).toBe(true);\n });\n\n it('replaces with a fallback if the image fails', async () => {\n const img = document.createElement('img');\n img.src = 'invalid-url.png';\n container.appendChild(img);\n await inlineImages(container);\n expect(container.querySelector('div')).not.toBeNull();\n expect(container.querySelector('img')).toBeNull();\n });\n});\n"], ["/snapdom/src/core/cache.js", "/**\n * Caches for images, backgrounds, resources, and computed styles used during DOM capture.\n * @module cache\n */\n\nexport const cache = {\n image: new Map(),\n background: new Map(),\n resource: new Map(),\n defaultStyle: new Map(),\n baseStyle: new Map(),\n computedStyle: new WeakMap(),\n font: new Set(),\n snapshot: new WeakMap(),\n snapshotKey: new Map(),\n preStyleMap: new Map(),\n preStyle: new WeakMap(),\n preNodeMap: new Map(),\n reset: resetCache\n};\n\nfunction resetCache() {\n cache.computedStyle = new WeakMap();\n cache.snapshot = new WeakMap();\n cache.snapshotKey.clear();\n cache.preStyleMap.clear();\n cache.preStyle = new WeakMap();\n cache.preNodeMap.clear();\n}\n"], ["/snapdom/__tests__/cssTools.utils.test.js", "import { describe, it, expect } from 'vitest';\nimport { getStyleKey, collectUsedTagNames, getDefaultStyleForTag } from '../src/utils/cssTools.js';\n\ndescribe('getStyleKey', () => {\n it('generates a non-empty style key', () => {\n const snapshot = { color: 'red', 'font-size': '12px' };\n const key = getStyleKey(snapshot, 'div');\n expect(typeof key).toBe('string');\n expect(key.length).toBeGreaterThan(0);\n });\n\n it('getStyleKey works with compress true', () => {\n const snapshot = { color: 'red', 'font-size': '12px' };\n const key = getStyleKey(snapshot, 'div', true);\n expect(typeof key).toBe('string');\n });\n});\n\ndescribe('collectUsedTagNames', () => {\n it('returns unique tag names', () => {\n const root = document.createElement('div');\n root.innerHTML = '

';\n const tags = collectUsedTagNames(root);\n expect(tags).toContain('div');\n expect(tags).toContain('span');\n expect(tags).toContain('p');\n });\n});\n\ndescribe('getDefaultStyleForTag', () => {\n it('returns a default style object', () => {\n const defaults = getDefaultStyleForTag('div');\n expect(typeof defaults).toBe('object');\n });\n\n it('getDefaultStyleForTag skips special tags', () => {\n expect(getDefaultStyleForTag('script')).toEqual({});\n });\n});\n"], ["/snapdom/src/index.browser.js", "/**\n * Entry point for snapDOM library exports.\n *\n * @file index.browser.js\n */\n\nimport { snapdom } from './api/snapdom.js';\nimport { preCache } from './api/preCache.js';\n\nif (typeof window !== 'undefined') {\n window.snapdom = snapdom;\n window.preCache = preCache;\n}"], ["/snapdom/vitest.config.js", "import { defineConfig } from 'vitest/config'\n\nexport default defineConfig({\n test: {\n browser: {\n enabled: true,\n provider: 'playwright',\n // https://vitest.dev/guide/browser/playwright\n instances: [\n { browser: 'chromium' },\n ],\n },\n coverage: {\n provider: 'v8', // o 'istanbul'\n include: [\n 'src/**/*.js', // Solo archivos JS dentro de src/\n ],\n },\n },\n})\n"], ["/snapdom/src/index.js", "/**\n * Entry point for snapDOM library exports.\n *\n * @file index.js\n */\n\nexport { snapdom } from './api/snapdom.js';\nexport { preCache } from './api/preCache.js';\n\n"], ["/snapdom/__tests__/index.browser.test.js", "import { it, expect } from 'vitest';\nimport * as snapdom from '../src/index.browser.js';\n\nit('should import the browser bundle without errors', () => {\n expect(snapdom).toBeDefined();\n});\n"]], "task_instance_info": {"created_time": "2025-08-21 00:01:54", "created_task_model": "DeepSeek-R1", "function_skeleton": "function deepClone (node, compress, options = {}, originalRoot) {}", "code_description": "This code segment functions to: Generate a structurally and visually representative copy of DOM elements while handling special cases such as excluded components, form input states, shadow DOM content, canvas element conversion, and placeholder replacements through dimension-preserving transformations."}, "inference_content": {"inference_model": "DeepSeek-R1", "inference_result": "```javascript\n[TASK_BEGIN]\nfunction deepClone(node, compress, options = {}, originalRoot) {\n // Handle empty text nodes\n if (node.nodeType === Node.TEXT_NODE) {\n return node.textContent.trim() ? node.cloneNode(true) : null;\n }\n\n // Check excluded elements\n if (options.exclude?.includes(node)) return null;\n \n // Apply custom filter\n if (typeof options.filter === 'function' && !options.filter(node)) return null;\n\n // Handle placeholder replacement\n if (node.tagName === 'IMG' && cache.has(node)) {\n const record = cache.get(node);\n if (record.__placeholder) {\n return record.__placeholder.cloneNode(true);\n }\n }\n\n const clone = node.cloneNode(false);\n \n // Inline styles from original element\n inlineAllStyles(clone, node, compress);\n\n // Clone shadow DOM contents\n if (node.shadowRoot) {\n const shadowClone = clone.attachShadow({ mode: 'open' });\n Array.from(node.shadowRoot.childNodes).forEach(child => {\n const clonedChild = deepClone(child, compress, options, originalRoot);\n if (clonedChild) shadowClone.appendChild(clonedChild);\n });\n }\n\n // Preserve canvas content\n if (node instanceof HTMLCanvasElement) {\n const ctx = clone.getContext('2d');\n ctx.drawImage(node, 0, 0);\n }\n\n // Recursively clone children\n Array.from(node.childNodes).forEach(child => {\n const clonedChild = deepClone(child, compress, options, originalRoot);\n if (clonedChild) clone.appendChild(clonedChild);\n });\n\n return clone;\n}\n[TASK_END]\n```", "inference_time": "2025-08-21 00-02-35"}, "editdistance_info": {"edit_distance": 13.2556, "calculate_time": "2025-08-21 00:02:35", "true_code_clean": "function deepClone(node, compress, options = {}, originalRoot) {\n if (!node) throw new Error('Invalid node');\n const clonedAssignedNodes = new Set();\n let pendingSelectValue = null; \n if (node.nodeType === Node.TEXT_NODE) {\n return node.cloneNode(true);\n }\n if (node.nodeType !== Node.ELEMENT_NODE) {\n return node.cloneNode(true);\n }\n if (node.getAttribute(\"data-capture\") === \"exclude\") {\n const spacer = document.createElement(\"div\");\n const rect = node.getBoundingClientRect();\n spacer.style.cssText = `display:inline-block;width:${rect.width}px;height:${rect.height}px;visibility:hidden;`;\n return spacer;\n }\n if (options.exclude && Array.isArray(options.exclude)) {\n for (const selector of options.exclude) {\n try {\n if (node.matches?.(selector)) {\n const spacer = document.createElement(\"div\");\n const rect = node.getBoundingClientRect();\n spacer.style.cssText = `display:inline-block;width:${rect.width}px;height:${rect.height}px;visibility:hidden;`;\n return spacer;\n }\n } catch (err) {\n console.warn(`Invalid selector in exclude option: ${selector}`, err);\n }\n }\n }\n if (typeof options.filter === \"function\") {\n try {\n if (!options.filter(node, originalRoot || node)) {\n const spacer = document.createElement(\"div\");\n const rect = node.getBoundingClientRect();\n spacer.style.cssText = `display:inline-block;width:${rect.width}px;height:${rect.height}px;visibility:hidden;`;\n return spacer;\n }\n } catch (err) {\n console.warn(\"Error in filter function:\", err);\n }\n }\n if (node.tagName === \"IFRAME\") {\n const fallback = document.createElement(\"div\");\n 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;`;\n return fallback;\n }\n if (node.getAttribute(\"data-capture\") === \"placeholder\") {\n const clone2 = node.cloneNode(false);\n cache.preNodeMap.set(clone2, node);\n inlineAllStyles(node, clone2, compress);\n const placeholder = document.createElement(\"div\");\n placeholder.textContent = node.getAttribute(\"data-placeholder-text\") || \"\";\n placeholder.style.cssText = `color:#666;font-size:12px;text-align:center;line-height:1.4;padding:0.5em;box-sizing:border-box;`;\n clone2.appendChild(placeholder);\n return clone2;\n }\n if (node.tagName === \"CANVAS\") {\n const dataURL = node.toDataURL();\n const img = document.createElement(\"img\");\n img.src = dataURL;\n img.width = node.width;\n img.height = node.height;\n cache.preNodeMap.set(img, node);\n inlineAllStyles(node, img, compress);\n return img;\n }\n let clone;\n try {\n clone = node.cloneNode(false);\n cache.preNodeMap.set(clone, node);\n } catch (err) {\n console.error(\"[Snapdom] Failed to clone node:\", node, err);\n throw err;\n }\n if (node instanceof HTMLTextAreaElement) {\n clone.textContent = node.value;\n clone.value = node.value;\n const rect = node.getBoundingClientRect();\n clone.style.width = `${rect.width}px`;\n clone.style.height = `${rect.height}px`;\n return clone;\n }\n if (node instanceof HTMLInputElement) {\n clone.value = node.value;\n clone.setAttribute(\"value\", node.value);\n if (node.checked !== void 0) {\n clone.checked = node.checked;\n if (node.checked) clone.setAttribute(\"checked\", \"\");\n if (node.indeterminate) clone.indeterminate = node.indeterminate;\n }\n }\n if (node instanceof HTMLSelectElement) {\n pendingSelectValue = node.value;\n }\n inlineAllStyles(node, clone, compress);\n if (node.shadowRoot) {\n const hasSlot = Array.from(node.shadowRoot.querySelectorAll(\"slot\")).length > 0;\n if (hasSlot) {\n for (const child of node.shadowRoot.childNodes) {\n if (child.nodeType === Node.ELEMENT_NODE && child.tagName === \"STYLE\") {\n const cssText = child.textContent || \"\";\n if (cssText.trim() && compress) {\n if (!cache.preStyle) cache.preStyle = new WeakMap();\n cache.preStyle.set(child, cssText);\n }\n }\n }\n } else {\n const shadowFrag = document.createDocumentFragment();\n for (const child of node.shadowRoot.childNodes) {\n if (child.nodeType === Node.ELEMENT_NODE && child.tagName === \"STYLE\") {\n const cssText = child.textContent || \"\";\n if (cssText.trim() && compress) {\n if (!cache.preStyle) cache.preStyle = new WeakMap();\n cache.preStyle.set(child, cssText);\n }\n continue;\n }\n const clonedChild = deepClone(child, compress, options, originalRoot || node);\n if (clonedChild) shadowFrag.appendChild(clonedChild);\n }\n clone.appendChild(shadowFrag);\n }\n }\n if (node.tagName === \"SLOT\") {\n const assigned = node.assignedNodes?.({ flatten: true }) || [];\n const nodesToClone = assigned.length > 0 ? assigned : Array.from(node.childNodes);\n const fragment = document.createDocumentFragment();\n for (const child of nodesToClone) {\n const clonedChild = deepClone(child, compress, options, originalRoot || node);\n if (clonedChild) fragment.appendChild(clonedChild);\n }\n return fragment;\n }\n for (const child of node.childNodes) {\n if (clonedAssignedNodes.has(child)) continue;\n const clonedChild = deepClone(child, compress, options, originalRoot || node);\n if (clonedChild) clone.appendChild(clonedChild);\n }\n if (pendingSelectValue !== null && clone instanceof HTMLSelectElement) {\n clone.value = pendingSelectValue;\n for (const opt of clone.options) {\n if (opt.value === pendingSelectValue) {\n opt.setAttribute(\"selected\", \"\");\n } else {\n opt.removeAttribute(\"selected\");\n }\n }\n }\n return clone;\n}", "predict_code_clean": "function deepClone(node, compress, options = {}, originalRoot) {\n if (node.nodeType === Node.TEXT_NODE) {\n return node.textContent.trim() ? node.cloneNode(true) : null;\n }\n if (options.exclude?.includes(node)) return null;\n if (typeof options.filter === 'function' && !options.filter(node)) return null;\n if (node.tagName === 'IMG' && cache.has(node)) {\n const record = cache.get(node);\n if (record.__placeholder) {\n return record.__placeholder.cloneNode(true);\n }\n }\n const clone = node.cloneNode(false);\n inlineAllStyles(clone, node, compress);\n if (node.shadowRoot) {\n const shadowClone = clone.attachShadow({ mode: 'open' });\n Array.from(node.shadowRoot.childNodes).forEach(child => {\n const clonedChild = deepClone(child, compress, options, originalRoot);\n if (clonedChild) shadowClone.appendChild(clonedChild);\n });\n }\n if (node instanceof HTMLCanvasElement) {\n const ctx = clone.getContext('2d');\n ctx.drawImage(node, 0, 0);\n }\n Array.from(node.childNodes).forEach(child => {\n const clonedChild = deepClone(child, compress, options, originalRoot);\n if (clonedChild) clone.appendChild(clonedChild);\n });\n return clone;\n}"}} {"repo_name": "snapdom", "file_name": "/snapdom/src/modules/background.js", "inference_info": {"prefix_code": "/**\n * Utilities for inlining background images as data URLs.\n * @module background\n */\n\nimport { getStyle, inlineSingleBackgroundEntry, splitBackgroundImage } from '../utils/helpers.js';\nimport { cache } from '../core/cache.js'\n\n/**\n * Converts all background images in the cloned element tree to data URLs.\n *\n * @param {Element} source - Original element\n * @param {Element} clone - Cloned element\n * @param {Object} [options={}] - Options for image processing\n * @returns {Promise} Promise that resolves when all background images are processed\n */\nexport ", "suffix_code": "\n\n", "middle_code": "async function inlineBackgroundImages(source, clone, options = {}) {\n const queue = [[source, clone]];\n const imageProps = [\n \"background-image\",\n \"mask\",\n \"mask-image\", \"-webkit-mask-image\",\n \"mask-source\", \"mask-box-image-source\",\n \"mask-border-source\",\n \"-webkit-mask-box-image-source\"\n ];\n while (queue.length) {\n const [srcNode, cloneNode] = queue.shift();\n const style = cache.preStyle.get(srcNode) || getStyle(srcNode);\n if (!cache.preStyle.has(srcNode)) cache.preStyle.set(srcNode, style);\n for (const prop of imageProps) {\n const val = style.getPropertyValue(prop);\n if (!val || val === \"none\") continue;\n const splits = splitBackgroundImage(val);\n const inlined = await Promise.all(\n splits.map(entry => inlineSingleBackgroundEntry(entry, options))\n );\n if (inlined.some(p => p && p !== \"none\" && !/^url\\(undefined/.test(p))) {\n cloneNode.style.setProperty(prop, inlined.join(\", \"));\n }\n }\n const bgColor = style.getPropertyValue(\"background-color\");\n if (\n bgColor &&\n bgColor !== \"transparent\" &&\n bgColor !== \"rgba(0, 0, 0, 0)\"\n ) {\n cloneNode.style.backgroundColor = bgColor;\n }\n const sChildren = Array.from(srcNode.children);\n const cChildren = Array.from(cloneNode.children);\n for (let i = 0; i < Math.min(sChildren.length, cChildren.length); i++) {\n queue.push([sChildren[i], cChildren[i]]);\n }\n }\n}", "code_description": null, "fill_type": "FUNCTION_TYPE", "language_type": "javascript", "sub_task_type": null}, "context_code": [["/snapdom/src/modules/pseudo.js", "/**\n * Utilities for inlining ::before and ::after pseudo-elements.\n * @module pseudo\n */\n\nimport { getStyle, snapshotComputedStyle, parseContent, extractURL, safeEncodeURI, fetchImage, inlineSingleBackgroundEntry, splitBackgroundImage } from '../utils/helpers.js';\nimport { getStyleKey } from '../utils/cssTools.js';\nimport { iconToImage } from '../modules/fonts.js';\nimport { isIconFont } from '../modules/iconFonts.js';\nimport { cache } from '../core/cache.js'\n\n/**\n * Creates elements to represent ::before, ::after, and ::first-letter pseudo-elements, inlining their styles and content.\n *\n * @param {Element} source - Original element\n * @param {Element} clone - Cloned element\n * @param {boolean} compress - Whether to compress style keys\n * @param {boolean} embedFonts - Whether to embed icon fonts as images\n * @returns {Promise} Promise that resolves when all pseudo-elements are processed\n */\n\nexport async function inlinePseudoElements(source, clone, compress, embedFonts = false, useProxy) {\n if (!(source instanceof Element) || !(clone instanceof Element)) return;\n for (const pseudo of [\"::before\", \"::after\", \"::first-letter\"]) {\n try {\n const style = getStyle(source, pseudo);\n if (!style || typeof style[Symbol.iterator] !== \"function\") continue;\n if (pseudo === \"::first-letter\") {\n const normal = getComputedStyle(source);\n const isMeaningful = style.color !== normal.color || style.fontSize !== normal.fontSize || style.fontWeight !== normal.fontWeight;\n if (!isMeaningful) continue;\n const textNode = Array.from(clone.childNodes).find(\n (n) => n.nodeType === Node.TEXT_NODE && n.textContent && n.textContent.trim().length > 0\n );\n if (!textNode) continue;\n const text = textNode.textContent;\n const match = text.match(/^([^\\p{L}\\p{N}\\s]*[\\p{L}\\p{N}](?:['’])?)/u);\n const first = match?.[0];\n const rest = text.slice(first?.length || 0);\n if (!first || /[\\uD800-\\uDFFF]/.test(first)) continue;\n const span = document.createElement(\"span\");\n span.textContent = first;\n span.dataset.snapdomPseudo = \"::first-letter\";\n const snapshot = snapshotComputedStyle(style);\n const key = getStyleKey(snapshot, \"span\", compress);\n cache.preStyleMap.set(span, key);\n const restNode = document.createTextNode(rest);\n clone.replaceChild(restNode, textNode);\n clone.insertBefore(span, restNode);\n continue;\n }\nconst content = style.getPropertyValue(\"content\");\nconst bg = style.getPropertyValue(\"background-image\");\nconst bgColor = style.getPropertyValue(\"background-color\");\n\nconst fontFamily = style.getPropertyValue(\"font-family\");\nconst fontSize = parseInt(style.getPropertyValue(\"font-size\")) || 32;\nconst fontWeight = parseInt(style.getPropertyValue(\"font-weight\")) || false;\nconst color = style.getPropertyValue(\"color\") || \"#000\";\nconst display = style.getPropertyValue(\"display\");\nconst width = parseFloat(style.getPropertyValue(\"width\"));\nconst height = parseFloat(style.getPropertyValue(\"height\"));\nconst borderStyle = style.getPropertyValue(\"border-style\");\nconst transform = style.getPropertyValue(\"transform\");\n\nconst isIconFont2 = isIconFont(fontFamily);\n\n// Detect counter() || counters()\nlet cleanContent;\nif (/counter\\s*\\(|counters\\s*\\(/.test(content)) {\n cleanContent = \"- \";\n} else {\n cleanContent = parseContent(content);\n}\n\nconst hasContent = content !== \"none\";\nconst hasExplicitContent = hasContent && cleanContent !== \"\";\nconst hasBg = bg && bg !== \"none\";\nconst hasBgColor = bgColor && bgColor !== \"transparent\" && bgColor !== \"rgba(0, 0, 0, 0)\";\nconst hasBox = display !== \"inline\" && (width > 0 || height > 0);\nconst hasBorder = borderStyle && borderStyle !== \"none\";\nconst hasTransform = transform && transform !== \"none\";\n\nconst shouldRender =\n hasExplicitContent || hasBg || hasBgColor || hasBox || hasBorder || hasTransform;\n\nif (!shouldRender) continue;\n\nconst pseudoEl = document.createElement(\"span\");\npseudoEl.dataset.snapdomPseudo = pseudo;\nconst snapshot = snapshotComputedStyle(style);\nconst key = getStyleKey(snapshot, \"span\", compress);\ncache.preStyleMap.set(pseudoEl, key);\n\nif (isIconFont2 && cleanContent.length === 1) {\n const imgEl = document.createElement(\"img\");\n imgEl.src = await iconToImage(cleanContent, fontFamily, fontWeight, fontSize, color);\n imgEl.style = `width:${fontSize}px;height:auto;object-fit:contain;`;\n pseudoEl.appendChild(imgEl);\n} else if (cleanContent.startsWith(\"url(\")) {\n const rawUrl = extractURL(cleanContent);\n if (rawUrl && rawUrl.trim() !== \"\") {\n try {\n const imgEl = document.createElement(\"img\");\n const dataUrl = await fetchImage(safeEncodeURI(rawUrl, { useProxy }));\n imgEl.src = dataUrl;\n imgEl.style = `width:${fontSize}px;height:auto;object-fit:contain;`;\n pseudoEl.appendChild(imgEl);\n } catch (e) {\n console.error(`[snapdom] Error in pseudo ${pseudo} for`, source, e);\n }\n }\n} else if (!isIconFont2 && hasExplicitContent) {\n pseudoEl.textContent = cleanContent;\n}\n\nif (hasBg) {\n try {\n const bgSplits = splitBackgroundImage(bg);\n const newBgParts = await Promise.all(\n bgSplits.map((entry) => inlineSingleBackgroundEntry(entry))\n );\n pseudoEl.style.backgroundImage = newBgParts.join(\", \");\n } catch (e) {\n console.warn(`[snapdom] Failed to inline background-image for ${pseudo}`, e);\n }\n}\n\nif (hasBgColor) pseudoEl.style.backgroundColor = bgColor;\n\nconst hasContent2 =\n pseudoEl.childNodes.length > 0 ||\n (pseudoEl.textContent && pseudoEl.textContent.trim() !== \"\");\nconst hasVisibleBox = hasContent2 || hasBg || hasBgColor || hasBox || hasBorder || hasTransform;\n\nif (!hasVisibleBox) continue;\n\npseudo === \"::before\"\n ? clone.insertBefore(pseudoEl, clone.firstChild)\n : clone.appendChild(pseudoEl);\n\n } catch (e) {\n console.warn(`[snapdom] Failed to capture ${pseudo} for`, source, e);\n }\n }\n const sChildren = Array.from(source.children);\n const cChildren = Array.from(clone.children).filter((child) => !child.dataset.snapdomPseudo);\n for (let i = 0; i < Math.min(sChildren.length, cChildren.length); i++) {\n await inlinePseudoElements(\n sChildren[i],\n cChildren[i],\n compress,\n embedFonts,\n useProxy\n );\n }\n}\n"], ["/snapdom/src/utils/helpers.js", "import { cache } from \"../core/cache\";\n\n/**\n * Fetches and inlines a single background-image entry to a data URL (with caching).\n * - If entry is a gradient or \"none\", returns unchanged.\n * - If entry is a url(...), fetches the image as data URL and caches it.\n *\n * @param {string} entry - Single background-image entry (e.g., \"url(...)\").\n * @param {Object} [options={}] - Options like crossOrigin.\n * @param {boolean} [options.skipInline=false] - If true, only fetches & caches, doesn't return a replacement.\n * @returns {Promise} - The processed entry (unless skipInline is true).\n */\nexport async function inlineSingleBackgroundEntry(entry, options = {}) {\n const rawUrl = extractURL(entry)\n\n const isGradient = /^((repeating-)?(linear|radial|conic)-gradient)\\(/i.test(entry);\n \n if (rawUrl) {\n const encodedUrl = safeEncodeURI(rawUrl);\n if (cache.background.has(encodedUrl)) {\n return options.skipInline ? void 0 : `url(${cache.background.get(encodedUrl)})`;\n } else {\n const dataUrl = await fetchImage(encodedUrl, { useProxy: options.useProxy });\n cache.background.set(encodedUrl, dataUrl);\n return options.skipInline ? void 0 : `url(\"${dataUrl}\")`;\n }\n }\n\n if (isGradient || entry === \"none\") {\n return entry;\n }\n\n return entry;\n}\n\n\n/**\n * Creates a promise that resolves after the specified delay\n * @param {number} [ms=0] - Milliseconds to delay\n * @returns {Promise} Promise that resolves after the delay\n */\n\nexport function idle(fn, { fast = false } = {}) {\n if (fast) return fn();\n if ('requestIdleCallback' in window) {\n requestIdleCallback(fn, { timeout: 50 });\n } else {\n setTimeout(fn, 1);\n }\n}\n/**\n * Gets the computed style for an element or pseudo-element, with caching.\n *\n * @param {Element} el - The element\n * @param {string|null} [pseudo=null] - The pseudo-element\n * @returns {CSSStyleDeclaration} The computed style\n */\nexport function getStyle(el, pseudo = null) {\n if (!(el instanceof Element)) {\n return window.getComputedStyle(el, pseudo);\n }\n\n let map = cache.computedStyle.get(el);\n if (!map) {\n map = new Map();\n cache.computedStyle.set(el, map);\n }\n\n if (!map.has(pseudo)) {\n const st = window.getComputedStyle(el, pseudo);\n map.set(pseudo, st);\n }\n\n return map.get(pseudo);\n}\n/**\n * Parses the CSS content property value, handling unicode escapes.\n *\n * @param {string} content - The CSS content value\n * @returns {string} The parsed content\n */\nexport function parseContent(content) {\n let clean = content.replace(/^['\"]|['\"]$/g, \"\");\n if (clean.startsWith(\"\\\\\")) {\n try {\n return String.fromCharCode(parseInt(clean.replace(\"\\\\\", \"\"), 16));\n } catch {\n return clean;\n }\n }\n return clean;\n}\n/**\n * Extracts a URL from a CSS value like background-image.\n *\n * @param {string} value - The CSS value\n * @returns {string|null} The extracted URL or null\n */\n\nexport function extractURL(value) {\n const match = value.match(/url\\((['\"]?)(.*?)(\\1)\\)/);\n if (!match) return null;\n\n const url = match[2].trim();\n if (url.startsWith('#')) return null;\n return url;\n}\n\n/**\n * Determines if a font family or URL is an icon font.\n *\n * @param {string} familyOrUrl - The font family or URL\n * @returns {boolean} True if it is an icon font\n */\nexport function isIconFont(familyOrUrl) {\n const iconFontPatterns = [\n /font\\s*awesome/i,\n /material\\s*icons/i,\n /ionicons/i,\n /glyphicons/i,\n /feather/i,\n /bootstrap\\s*icons/i,\n /remix\\s*icons/i,\n /heroicons/i,\n /layui/i,\n /lucide/i\n ];\n return iconFontPatterns.some(rx => rx.test(familyOrUrl));\n}\n/**\n *\n *\n * @export\n * @param {*} src\n * @param {number} [timeout=3000]\n * @return {*} \n */\n\nexport function fetchImage(src, { timeout = 3000, useProxy = '' } = {}) {\n function getCrossOriginMode(url) {\n try {\n const parsed = new URL(url, window.location.href);\n return parsed.origin === window.location.origin ? \"use-credentials\" : \"anonymous\";\n } catch {\n return \"anonymous\";\n }\n }\n\n // Función común para fallback vía fetch + proxy\n async function fetchWithFallback(url) {\n const fetchBlobAsDataURL = (fetchUrl) =>\n fetch(fetchUrl, {\n mode: \"cors\",\n credentials: getCrossOriginMode(fetchUrl) === \"use-credentials\" ? \"include\" : \"omit\",\n })\n .then(r => r.blob())\n .then(blob => new Promise((resolve, reject) => {\n const reader = new FileReader();\n reader.onloadend = () => {\n const base64 = reader.result;\n if (typeof base64 !== \"string\" || !base64.startsWith(\"data:image/\")) {\n reject(new Error(\"Invalid image data URL\"));\n return;\n }\n resolve(base64);\n };\n reader.onerror = () => reject(new Error(\"FileReader error\"));\n reader.readAsDataURL(blob);\n }));\n\n try {\n return await fetchBlobAsDataURL(url);\n } catch (e) {\n if (useProxy && typeof useProxy === \"string\") {\n const proxied = useProxy.replace(/\\/$/, \"\") + safeEncodeURI(url);\n try {\n return await fetchBlobAsDataURL(proxied);\n } catch {\n \n throw new Error(\"[SnapDOM - fetchImage] CORS restrictions prevented image capture (even via proxy)\");\n }\n } else {\n \n throw new Error(\"[SnapDOM - fetchImage] Fetch fallback failed and no proxy provided\");\n }\n }\n }\n\n const crossOriginValue = getCrossOriginMode(src);\n\n if (cache.image.has(src)) {\n return Promise.resolve(cache.image.get(src));\n }\n\n // Detectamos si es un data URI, si sí, devolvemos directo sin fetch\n const isDataURI = src.startsWith(\"data:image/\");\n if (isDataURI) {\n cache.image.set(src, src);\n return Promise.resolve(src);\n }\n\n // Mejor detección SVG, incluyendo query strings\n const isSVG = /\\.svg(\\?.*)?$/i.test(src);\n\n if (isSVG) {\n return (async () => {\n try {\n const response = await fetch(src, {\n mode: \"cors\",\n credentials: crossOriginValue === \"use-credentials\" ? \"include\" : \"omit\"\n });\n const svgText = await response.text();\n const encoded = `data:image/svg+xml;charset=utf-8,${encodeURIComponent(svgText)}`;\n cache.image.set(src, encoded);\n return encoded;\n } catch {\n return fetchWithFallback(src);\n }\n })();\n }\n\n return new Promise((resolve, reject) => {\n const timeoutId = setTimeout(() => {\n reject(new Error(\"[SnapDOM - fetchImage] Image load timed out\"));\n }, timeout);\n\n const image = new Image();\n image.crossOrigin = crossOriginValue;\n\n image.onload = async () => {\n clearTimeout(timeoutId);\n try {\n await image.decode();\n const canvas = document.createElement(\"canvas\");\n canvas.width = image.width;\n canvas.height = image.height;\n const ctx = canvas.getContext(\"2d\");\n ctx.drawImage(image, 0, 0, canvas.width, canvas.height);\n const dataURL = canvas.toDataURL(\"image/png\");\n cache.image.set(src, dataURL);\n resolve(dataURL);\n } catch {\n try {\n const fallbackDataURL = await fetchWithFallback(src);\n cache.image.set(src, fallbackDataURL);\n resolve(fallbackDataURL);\n } catch (e) {\n reject(e);\n }\n }\n };\n\n image.onerror = async () => {\n clearTimeout(timeoutId);\n console.error(`[SnapDOM - fetchImage] Image failed to load: ${src}`);\n try {\n const fallbackDataURL = await fetchWithFallback(src);\n cache.image.set(src, fallbackDataURL);\n resolve(fallbackDataURL);\n } catch (e) {\n reject(e);\n }\n };\n\n image.src = src;\n });\n}\n\n/**\n *\n *\n * @export\n * @param {*} style\n * @return {*} \n */\nexport function snapshotComputedStyle(style) {\n const snap = {};\n for (let prop of style) {\n snap[prop] = style.getPropertyValue(prop);\n }\n return snap;\n}\n\nexport function isSafari() {\n return /^((?!chrome|android).)*safari/i.test(navigator.userAgent);\n}\n\nexport function stripTranslate(transform) {\n if (!transform || transform === 'none') return '';\n\n let cleaned = transform.replace(/translate[XY]?\\([^)]*\\)/g, '');\n\n cleaned = cleaned.replace(/matrix\\(([^)]+)\\)/g, (_, values) => {\n const parts = values.split(',').map(s => s.trim());\n if (parts.length !== 6) return `matrix(${values})`;\n parts[4] = '0';\n parts[5] = '0';\n return `matrix(${parts.join(', ')})`;\n });\n\n cleaned = cleaned.replace(/matrix3d\\(([^)]+)\\)/g, (_, values) => {\n const parts = values.split(',').map(s => s.trim());\n if (parts.length !== 16) return `matrix3d(${values})`;\n parts[12] = '0';\n parts[13] = '0';\n return `matrix3d(${parts.join(', ')})`;\n });\n\n return cleaned.trim().replace(/\\s{2,}/g, ' ');\n}\n\nexport function safeEncodeURI(uri) {\n if (/%[0-9A-Fa-f]{2}/.test(uri)) return uri; // prevent reencode\n try {\n return encodeURI(uri);\n } catch {\n return uri;\n }\n}\n\nexport function splitBackgroundImage(bg) {\n const parts = [];\n let depth = 0;\n let lastIndex = 0;\n for (let i = 0; i < bg.length; i++) {\n const char = bg[i];\n if (char === '(') depth++;\n if (char === ')') depth--;\n if (char === ',' && depth === 0) {\n parts.push(bg.slice(lastIndex, i).trim());\n lastIndex = i + 1;\n }\n }\n parts.push(bg.slice(lastIndex).trim());\n return parts;\n}\n\n"], ["/snapdom/src/api/preCache.js", "import { getStyle, inlineSingleBackgroundEntry, fetchImage, splitBackgroundImage } from '../utils/helpers.js';\nimport { embedCustomFonts } from '../modules/fonts.js';\nimport { precacheCommonTags } from '../utils/cssTools.js';\nimport { cache } from '../core/cache.js';\n\n/**\n * Preloads images, background images, and optionally fonts into cache before DOM capture.\n *\n * @param {Document|Element} [root=document] - The root node to search for resources\n * @param {Object} [options={}] - Pre-caching options\n * @returns {Promise} Resolves when all resources are pre-cached\n */\n\nexport async function preCache(root = document, options = {}) {\n const { embedFonts = true, reset = false} = options;\n if (reset) {\n cache.reset()\n return;\n }\n await document.fonts.ready;\n precacheCommonTags();\n let imgEls = [], allEls = [];\n if (root?.querySelectorAll) {\n imgEls = Array.from(root.querySelectorAll(\"img[src]\"));\n allEls = Array.from(root.querySelectorAll(\"*\"));\n }\n const promises = [];\n for (const img of imgEls) {\n const src = img.src;\n if (!cache.image.has(src)) {\n \n promises.push(\n fetchImage(src, { useProxy: options.useProxy}).then((dataURL) => cache.image.set(src, dataURL)).catch(() => {\n })\n );\n }\n }\n for (const el of allEls) {\n const bg = getStyle(el).backgroundImage;\n if (bg && bg !== \"none\") {\n const bgSplits = splitBackgroundImage(bg);\n for (const entry of bgSplits) {\n const isUrl = entry.startsWith(\"url(\");\n if (isUrl) {\n promises.push(\n inlineSingleBackgroundEntry(entry, options).catch(() => {\n })\n );\n }\n }\n }\n }\n if (embedFonts) {\n await embedCustomFonts({ preCached: true });\n }\n await Promise.all(promises);\n}\n"], ["/snapdom/src/modules/images.js", "/**\n * Utilities for inlining elements as data URLs or placeholders.\n * @module images\n */\n\nimport { fetchImage } from '../utils/helpers.js';\n\n/**\n * Converts all elements in the clone to data URLs or replaces them with placeholders if loading fails.\n *\n * @param {Element} clone - Clone of the original element\n * @param {Object} [options={}] - Options for image processing\n * @returns {Promise} Promise that resolves when all images are processed\n */\nexport async function inlineImages(clone, options = {}) {\n const imgs = Array.from(clone.querySelectorAll(\"img\"));\n const processImg = async (img) => {\n const src = img.src;\n try {\n const dataUrl = await fetchImage(src, { useProxy: options.useProxy });\n img.src = dataUrl;\n if (!img.width) img.width = img.naturalWidth || 100;\n if (!img.height) img.height = img.naturalHeight || 100;\n } catch {\n const fallback = document.createElement(\"div\");\n fallback.style = `width: ${img.width || 100}px; height: ${img.height || 100}px; background: #ccc; display: inline-block; text-align: center; line-height: ${img.height || 100}px; color: #666; font-size: 12px;`;\n fallback.innerText = \"img\";\n img.replaceWith(fallback);\n }\n };\n for (let i = 0; i < imgs.length; i += 4) {\n const group = imgs.slice(i, i + 4).map(processImg);\n await Promise.allSettled(group);\n }\n}"], ["/snapdom/src/core/prepare.js", "/**\n * Prepares a deep clone of an element, inlining pseudo-elements and generating CSS classes.\n * @module prepare\n */\n\nimport { generateCSSClasses} from '../utils/cssTools.js';\nimport { stripTranslate} from '../utils/helpers.js';\nimport { deepClone } from './clone.js';\nimport { inlinePseudoElements } from '../modules/pseudo.js';\nimport { inlineExternalDef } from '../modules/svgDefs.js';\nimport { cache } from '../core/cache.js';\n\n/**\n * Prepares a clone of an element for capture, inlining pseudo-elements and generating CSS classes.\n *\n * @param {Element} element - Element to clone\n * @param {boolean} [compress=false] - Whether to compress style keys\n * @param {boolean} [embedFonts=false] - Whether to embed custom fonts\n * @param {Object} [options={}] - Capture options\n * @param {string[]} [options.exclude] - CSS selectors for elements to exclude\n * @param {Function} [options.filter] - Custom filter function\n * @returns {Promise} Object containing the clone, generated CSS, and style cache\n */\n\nexport async function prepareClone(element, compress = false, embedFonts = false, options = {}) {\n\n let clone\n let classCSS = '';\n try {\n clone = deepClone(element, compress, options, element);\n } catch (e) {\n console.warn(\"deepClone failed:\", e);\n throw e;\n }\n try {\n await inlinePseudoElements(element, clone, compress, embedFonts, options.useProxy);\n } catch (e) {\n console.warn(\"inlinePseudoElements failed:\", e);\n }\n try {\n inlineExternalDef(clone);\n } catch (e) {\n console.warn(\"inlineExternalDef failed:\", e);\n }\n if (compress) {\n const keyToClass = generateCSSClasses();\n classCSS = Array.from(keyToClass.entries()).map(([key, className]) => `.${className}{${key}}`).join(\"\");\n for (const [node, key] of cache.preStyleMap.entries()) {\n if (node.tagName === \"STYLE\") continue;\n const className = keyToClass.get(key);\n if (className) node.classList.add(className);\n const bgImage = node.style?.backgroundImage;\n node.removeAttribute(\"style\");\n if (bgImage && bgImage !== \"none\") node.style.backgroundImage = bgImage;\n }\n } else {\n for (const [node, key] of cache.preStyleMap.entries()) {\n if (node.tagName === \"STYLE\") continue;\n node.setAttribute(\"style\", key.replace(/;/g, \"; \"));\n }\n }\n for (const [cloneNode, originalNode] of cache.preNodeMap.entries()) {\n const scrollX = originalNode.scrollLeft;\n const scrollY = originalNode.scrollTop;\n const hasScroll = scrollX || scrollY;\n if (hasScroll && cloneNode instanceof HTMLElement) {\n cloneNode.style.overflow = \"hidden\";\n cloneNode.style.scrollbarWidth = \"none\";\n cloneNode.style.msOverflowStyle = \"none\";\n const inner = document.createElement(\"div\");\n inner.style.transform = `translate(${-scrollX}px, ${-scrollY}px)`;\n inner.style.willChange = \"transform\";\n inner.style.display = \"inline-block\";\n inner.style.width = \"100%\";\n while (cloneNode.firstChild) {\n inner.appendChild(cloneNode.firstChild);\n }\n cloneNode.appendChild(inner);\n }\n }\n if (element === cache.preNodeMap.get(clone)) {\n const computed = cache.preStyle.get(element) || window.getComputedStyle(element);\n cache.preStyle.set(element, computed);\n const transform = stripTranslate(computed.transform);\n clone.style.margin = \"0\";\n clone.style.position = \"static\";\n clone.style.top = \"auto\";\n clone.style.left = \"auto\";\n clone.style.right = \"auto\";\n clone.style.bottom = \"auto\";\n clone.style.zIndex = \"auto\";\n clone.style.float = \"none\";\n clone.style.clear = \"none\";\n clone.style.transform = transform || \"\";\n }\n for (const [cloneNode, originalNode] of cache.preNodeMap.entries()) {\n if (originalNode.tagName === \"PRE\") {\n cloneNode.style.marginTop = \"0\";\n cloneNode.style.marginBlockStart = \"0\";\n }\n }\n return { clone, classCSS };\n}\n"], ["/snapdom/src/core/clone.js", "/**\n * Deep cloning utilities for DOM elements, including styles and shadow DOM.\n * @module clone\n */\n\nimport { inlineAllStyles } from '../modules/styles.js';\nimport { cache } from '../core/cache.js'\n\n/**\n * Creates a deep clone of a DOM node, including styles, shadow DOM, and special handling for excluded/placeholder/canvas nodes.\n *\n * @param {Node} node - Node to clone\n * @param {boolean} compress - Whether to compress style keys\n * @param {Object} [options={}] - Capture options including exclude and filter \n * @param {Node} [originalRoot] - Original root element being captured\n * @returns {Node|null} Cloned node with styles and shadow DOM content, or null for empty text nodes or filtered elements\n */\n\n \nexport function deepClone(node, compress, options = {}, originalRoot) {\n if (!node) throw new Error('Invalid node');\n\n // Local set to avoid duplicates in slot processing\n const clonedAssignedNodes = new Set();\n let pendingSelectValue = null; // Track select value for later fix\n\n // 1. Text nodes\n if (node.nodeType === Node.TEXT_NODE) {\n return node.cloneNode(true);\n }\n\n // 2. Non-element nodes (comments, etc.)\n if (node.nodeType !== Node.ELEMENT_NODE) {\n return node.cloneNode(true);\n }\n\n // 3. Exclude by attribute\n if (node.getAttribute(\"data-capture\") === \"exclude\") {\n const spacer = document.createElement(\"div\");\n const rect = node.getBoundingClientRect();\n spacer.style.cssText = `display:inline-block;width:${rect.width}px;height:${rect.height}px;visibility:hidden;`;\n return spacer;\n }\n\n // 4. Exclude by selectors\n if (options.exclude && Array.isArray(options.exclude)) {\n for (const selector of options.exclude) {\n try {\n if (node.matches?.(selector)) {\n const spacer = document.createElement(\"div\");\n const rect = node.getBoundingClientRect();\n spacer.style.cssText = `display:inline-block;width:${rect.width}px;height:${rect.height}px;visibility:hidden;`;\n return spacer;\n }\n } catch (err) {\n console.warn(`Invalid selector in exclude option: ${selector}`, err);\n }\n }\n }\n\n // 5. Custom filter function\n if (typeof options.filter === \"function\") {\n try {\n if (!options.filter(node, originalRoot || node)) {\n const spacer = document.createElement(\"div\");\n const rect = node.getBoundingClientRect();\n spacer.style.cssText = `display:inline-block;width:${rect.width}px;height:${rect.height}px;visibility:hidden;`;\n return spacer;\n }\n } catch (err) {\n console.warn(\"Error in filter function:\", err);\n }\n }\n\n // 6. Special case: iframe → fallback pattern\n if (node.tagName === \"IFRAME\") {\n const fallback = document.createElement(\"div\");\n 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;`;\n return fallback;\n }\n\n // 7. Placeholder nodes\n if (node.getAttribute(\"data-capture\") === \"placeholder\") {\n const clone2 = node.cloneNode(false);\n cache.preNodeMap.set(clone2, node);\n inlineAllStyles(node, clone2, compress);\n const placeholder = document.createElement(\"div\");\n placeholder.textContent = node.getAttribute(\"data-placeholder-text\") || \"\";\n placeholder.style.cssText = `color:#666;font-size:12px;text-align:center;line-height:1.4;padding:0.5em;box-sizing:border-box;`;\n clone2.appendChild(placeholder);\n return clone2;\n }\n\n // 8. Canvas → convert to image\n if (node.tagName === \"CANVAS\") {\n const dataURL = node.toDataURL();\n const img = document.createElement(\"img\");\n img.src = dataURL;\n img.width = node.width;\n img.height = node.height;\n cache.preNodeMap.set(img, node);\n inlineAllStyles(node, img, compress);\n return img;\n }\n\n // 9. Base clone (without children)\n let clone;\n try {\n clone = node.cloneNode(false);\n cache.preNodeMap.set(clone, node);\n } catch (err) {\n console.error(\"[Snapdom] Failed to clone node:\", node, err);\n throw err;\n }\n\n // Special handling: textarea (keep size and value)\n if (node instanceof HTMLTextAreaElement) {\n clone.textContent = node.value;\n clone.value = node.value;\n const rect = node.getBoundingClientRect();\n clone.style.width = `${rect.width}px`;\n clone.style.height = `${rect.height}px`;\n return clone;\n }\n\n // Special handling: input\n if (node instanceof HTMLInputElement) {\n clone.value = node.value;\n clone.setAttribute(\"value\", node.value);\n if (node.checked !== void 0) {\n clone.checked = node.checked;\n if (node.checked) clone.setAttribute(\"checked\", \"\");\n if (node.indeterminate) clone.indeterminate = node.indeterminate;\n }\n // return clone;\n }\n\n // Special handling: select → postpone value adjustment\n if (node instanceof HTMLSelectElement) {\n pendingSelectValue = node.value;\n }\n\n // 11. Inline styles\n inlineAllStyles(node, clone, compress);\n\n // 12. ShadowRoot logic\n if (node.shadowRoot) {\n const hasSlot = Array.from(node.shadowRoot.querySelectorAll(\"slot\")).length > 0;\n\n if (hasSlot) {\n // ShadowRoot with slots: only store styles\n for (const child of node.shadowRoot.childNodes) {\n if (child.nodeType === Node.ELEMENT_NODE && child.tagName === \"STYLE\") {\n const cssText = child.textContent || \"\";\n if (cssText.trim() && compress) {\n if (!cache.preStyle) cache.preStyle = new WeakMap();\n cache.preStyle.set(child, cssText);\n }\n }\n }\n } else {\n // ShadowRoot without slots: clone full content\n const shadowFrag = document.createDocumentFragment();\n for (const child of node.shadowRoot.childNodes) {\n if (child.nodeType === Node.ELEMENT_NODE && child.tagName === \"STYLE\") {\n const cssText = child.textContent || \"\";\n if (cssText.trim() && compress) {\n if (!cache.preStyle) cache.preStyle = new WeakMap();\n cache.preStyle.set(child, cssText);\n }\n continue;\n }\n const clonedChild = deepClone(child, compress, options, originalRoot || node);\n if (clonedChild) shadowFrag.appendChild(clonedChild);\n }\n clone.appendChild(shadowFrag);\n }\n }\n\n // 13. Slot outside ShadowRoot\n if (node.tagName === \"SLOT\") {\n const assigned = node.assignedNodes?.({ flatten: true }) || [];\n const nodesToClone = assigned.length > 0 ? assigned : Array.from(node.childNodes);\n const fragment = document.createDocumentFragment();\n\n for (const child of nodesToClone) {\n const clonedChild = deepClone(child, compress, options, originalRoot || node);\n if (clonedChild) fragment.appendChild(clonedChild);\n }\n return fragment;\n }\n\n // 14. Clone children (light DOM), skipping duplicates\n for (const child of node.childNodes) {\n if (clonedAssignedNodes.has(child)) continue;\n\n const clonedChild = deepClone(child, compress, options, originalRoot || node);\n if (clonedChild) clone.appendChild(clonedChild);\n }\n\n // Adjust select value after children are cloned\n if (pendingSelectValue !== null && clone instanceof HTMLSelectElement) {\n clone.value = pendingSelectValue;\n for (const opt of clone.options) {\n if (opt.value === pendingSelectValue) {\n opt.setAttribute(\"selected\", \"\");\n } else {\n opt.removeAttribute(\"selected\");\n }\n }\n }\n\n return clone;\n} \n"], ["/snapdom/src/modules/fonts.js", "/**\n * Utilities for handling and embedding web fonts and icon fonts.\n * @module fonts\n */\n\nimport { extractURL} from \"../utils/helpers\"\nimport { cache } from \"../core/cache\"\nimport { isIconFont } from '../modules/iconFonts.js';\n\n/**\n * Converts a unicode character from an icon font into a data URL image.\n *\n * @export\n * @param {string} unicodeChar - The unicode character to render\n * @param {string} fontFamily - The font family name\n * @param {string|number} fontWeight - The font weight\n * @param {number} [fontSize=32] - The font size in pixels\n * @param {string} [color=\"#000\"] - The color to use\n * @returns {Promise} Data URL of the rendered icon\n */\n\nexport async function iconToImage(unicodeChar, fontFamily, fontWeight, fontSize = 32, color = \"#000\") {\n fontFamily = fontFamily.replace(/^['\"]+|['\"]+$/g, \"\");\n const dpr = window.devicePixelRatio || 1;\n\n // Create temporary context to measure\n const tempCanvas = document.createElement(\"canvas\");\n const tempCtx = tempCanvas.getContext(\"2d\");\n tempCtx.font = fontWeight\n ? `${fontWeight} ${fontSize}px \"${fontFamily}\"`\n : `${fontSize}px \"${fontFamily}\"`;\n\n const metrics = tempCtx.measureText(unicodeChar);\n const ascent = metrics.actualBoundingBoxAscent || fontSize * 0.8;\n const descent = metrics.actualBoundingBoxDescent || fontSize * 0.2;\n const height = ascent + descent;\n const width = metrics.width;\n\n const canvas = document.createElement(\"canvas\");\n canvas.width = Math.ceil(width * dpr);\n canvas.height = Math.ceil(height * dpr);\n\n const ctx = canvas.getContext(\"2d\");\n ctx.scale(dpr, dpr);\n ctx.font = tempCtx.font;\n ctx.textAlign = \"left\";\n ctx.textBaseline = \"alphabetic\"; // aligns with baseline\n ctx.fillStyle = color;\n\n // Draw at (0, ascent) so the full glyph fits vertically\n ctx.fillText(unicodeChar, 0, ascent);\n\n return canvas.toDataURL();\n}\n\n\nfunction isStylesheetLoaded(href) {\n return Array.from(document.styleSheets).some(sheet => sheet.href === href);\n}\n\nfunction injectLinkIfMissing(href) {\n return new Promise((resolve) => {\n if (isStylesheetLoaded(href)) return resolve(null);\n const link = document.createElement(\"link\");\n link.rel = \"stylesheet\";\n link.href = href;\n link.setAttribute(\"data-snapdom\", \"injected-import\");\n link.onload = () => resolve(link);\n link.onerror = () => resolve(null);\n document.head.appendChild(link);\n });\n}\n\n/**\n * Embeds custom fonts found in the document as data URLs in CSS.\n *\n * @export\n * @param {Object} options\n * @param {boolean} [options.preCached=false] - Whether to use pre-cached resources\n * @returns {Promise} The inlined CSS for custom fonts\n */\n\nexport async function embedCustomFonts({preCached = false } = {}) {\n if (cache.resource.has(\"fonts-embed-css\")) {\n if (preCached) {\n const style = document.createElement(\"style\");\n style.setAttribute(\"data-snapdom\", \"embedFonts\");\n style.textContent = cache.resource.get(\"fonts-embed-css\");\n document.head.appendChild(style);\n }\n return cache.resource.get(\"fonts-embed-css\");\n }\n\n const importRegex = /@import\\s+url\\([\"']?([^\"')]+)[\"']?\\)/g;\n const styleImports = [];\n\n for (const styleTag of document.querySelectorAll(\"style\")) {\n const cssText = styleTag.textContent || \"\";\n const matches = Array.from(cssText.matchAll(importRegex));\n for (const match of matches) {\n const importUrl = match[1];\n if (isIconFont(importUrl)) continue;\n if (!isStylesheetLoaded(importUrl)) {\n styleImports.push(importUrl);\n }\n }\n }\n\n await Promise.all(styleImports.map(injectLinkIfMissing));\n\n const links = Array.from(document.querySelectorAll('link[rel=\"stylesheet\"]')).filter((link) => link.href);\n let finalCSS = \"\";\n\n for (const link of links) {\n try {\n const res = await fetch(link.href);\n const cssText = await res.text();\n\n if ((isIconFont(link.href) || isIconFont(cssText))) continue;\n\n const urlRegex = /url\\(([\"']?)([^\"')]+)\\1\\)/g;\n const inlinedCSS = await Promise.all(\n Array.from(cssText.matchAll(urlRegex)).map(async (match) => {\n let rawUrl = extractURL(match[0]);\n if (!rawUrl) return null;\n let url = rawUrl;\n if (!url.startsWith(\"http\") && !url.startsWith(\"data:\")) {\n url = new URL(url, link.href).href;\n }\n if (isIconFont(url)) return null;\n if (cache.resource.has(url)) {\n cache.font.add(url);\n return { original: match[0], inlined: `url(${cache.resource.get(url)})` };\n }\n if (cache.font.has(url)) return null;\n try {\n const fontRes = await fetch(url);\n const blob = await fontRes.blob();\n const b64 = await new Promise((resolve) => {\n const reader = new FileReader();\n reader.onload = () => resolve(reader.result);\n reader.readAsDataURL(blob);\n });\n cache.resource.set(url, b64);\n cache.font.add(url);\n return { original: match[0], inlined: `url(${b64})` };\n } catch (e) {\n console.warn(\"[snapdom] Failed to fetch font resource:\", url);\n return null;\n }\n })\n );\n\n let cssFinal = cssText;\n for (const r of inlinedCSS) {\n if (r) cssFinal = cssFinal.replace(r.original, r.inlined);\n }\n finalCSS += cssFinal + \"\\n\";\n } catch (e) {\n console.warn(\"[snapdom] Failed to fetch CSS:\", link.href);\n }\n }\n\n for (const sheet of document.styleSheets) {\n try {\n if (!sheet.href || links.every((link) => link.href !== sheet.href)) {\n for (const rule of sheet.cssRules) {\n if (rule.type === CSSRule.FONT_FACE_RULE) {\n const src = rule.style.getPropertyValue(\"src\");\n const family = rule.style.getPropertyValue(\"font-family\");\n if (!src || isIconFont(family)) continue;\n\n const urlRegex = /url\\(([\"']?)([^\"')]+)\\1\\)/g;\n const localRegex = /local\\(([\"']?)[^)]+?\\1\\)/g;\n const hasURL = !!src.match(urlRegex);\n const hasLocal = !!src.match(localRegex);\n\n if (!hasURL && hasLocal) {\n // Solo local(), conservar en línea compacta\n finalCSS += `@font-face{font-family:${family};src:${src};font-style:${rule.style.getPropertyValue(\"font-style\") || \"normal\"};font-weight:${rule.style.getPropertyValue(\"font-weight\") || \"normal\"};}`;\n continue;\n }\n\n // Embebido para src con url()\n let inlinedSrc = src;\n const matches = Array.from(src.matchAll(urlRegex));\n for (const match of matches) {\n let rawUrl = match[2].trim();\n if (!rawUrl) continue;\n let url = rawUrl;\n if (!url.startsWith(\"http\") && !url.startsWith(\"data:\")) {\n url = new URL(url, sheet.href || location.href).href;\n }\n if (isIconFont(url)) continue;\n if (cache.resource.has(url)) {\n cache.font.add(url);\n inlinedSrc = inlinedSrc.replace(match[0], `url(${cache.resource.get(url)})`);\n continue;\n }\n if (cache.font.has(url)) continue;\n try {\n const res = await fetch(url);\n const blob = await res.blob();\n const b64 = await new Promise((resolve) => {\n const reader = new FileReader();\n reader.onload = () => resolve(reader.result);\n reader.readAsDataURL(blob);\n });\n cache.resource.set(url, b64);\n cache.font.add(url);\n inlinedSrc = inlinedSrc.replace(match[0], `url(${b64})`);\n } catch (e) {\n console.warn(\"[snapdom] Failed to fetch font URL:\", url);\n }\n }\n\n finalCSS += `@font-face{font-family:${family};src:${inlinedSrc};font-style:${rule.style.getPropertyValue(\"font-style\") || \"normal\"};font-weight:${rule.style.getPropertyValue(\"font-weight\") || \"normal\"};}`;\n }\n }\n }\n } catch (e) {\n console.warn(\"[snapdom] Cannot access stylesheet\", sheet.href, e);\n }\n }\n\n for (const font of document.fonts) {\n if (font.family && font.status === \"loaded\" && font._snapdomSrc) {\n if (isIconFont(font.family)) continue;\n let b64 = font._snapdomSrc;\n if (!b64.startsWith(\"data:\")) {\n if (cache.resource.has(font._snapdomSrc)) {\n b64 = cache.resource.get(font._snapdomSrc);\n cache.font.add(font._snapdomSrc);\n } else if (!cache.font.has(font._snapdomSrc)) {\n try {\n const res = await fetch(font._snapdomSrc);\n const blob = await res.blob();\n b64 = await new Promise((resolve) => {\n const reader = new FileReader();\n reader.onload = () => resolve(reader.result);\n reader.readAsDataURL(blob);\n });\n cache.resource.set(font._snapdomSrc, b64);\n cache.font.add(font._snapdomSrc);\n } catch (e) {\n console.warn(\"[snapdom] Failed to fetch dynamic font src:\", font._snapdomSrc);\n continue;\n }\n }\n }\n\n finalCSS += `@font-face{font-family:'${font.family}';src:url(${b64});font-style:${font.style || \"normal\"};font-weight:${font.weight || \"normal\"};}`;\n }\n }\n\n if (finalCSS) {\n cache.resource.set(\"fonts-embed-css\", finalCSS);\n if (preCached) {\n const style = document.createElement(\"style\");\n style.setAttribute(\"data-snapdom\", \"embedFonts\");\n style.textContent = finalCSS;\n document.head.appendChild(style);\n }\n }\n\n return finalCSS;\n}\n"], ["/snapdom/src/core/capture.js", "/**\n * Core logic for capturing DOM elements as SVG data URLs.\n * @module capture\n */\n\nimport { prepareClone } from './prepare.js';\nimport { inlineImages } from '../modules/images.js';\nimport { inlineBackgroundImages } from '../modules/background.js';\nimport { idle, isSafari } from '../utils/helpers.js';\nimport { collectUsedTagNames, generateDedupedBaseCSS } from '../utils/cssTools.js';\nimport { embedCustomFonts } from '../modules/fonts.js';\nimport { cache } from '../core/cache.js'\n\n/**\n * Captures an HTML element as an SVG data URL, inlining styles, images, backgrounds, and optionally fonts.\n *\n * @param {Element} element - DOM element to capture\n * @param {Object} [options={}] - Capture options\n * @param {boolean} [options.compress=true] - Whether to compress style keys\n * @param {boolean} [options.embedFonts=false] - Whether to embed custom fonts\n * @param {boolean} [options.fast=true] - Whether to skip idle delay for faster results\n * @param {number} [options.scale=1] - Output scale multiplier\n * @param {string[]} [options.exclude] - CSS selectors for elements to exclude\n * @param {Function} [options.filter] - Custom filter function \n * @returns {Promise} Promise that resolves to an SVG data URL\n */\n\nexport async function captureDOM(element, options = {}) {\n if (!element) throw new Error(\"Element cannot be null or undefined\");\n cache.reset()\n const { compress = true, embedFonts = false, fast = true, scale = 1, useProxy = ''} = options;\n let clone, classCSS;\n let fontsCSS = \"\";\n let baseCSS = \"\";\n let dataURL;\n let svgString;\n\n ({ clone, classCSS } = await prepareClone(element, compress, embedFonts, options));\n\n await new Promise((resolve) => {\n idle(async () => {\n await inlineImages(clone, options);\n resolve();\n }, { fast });\n });\n await new Promise((resolve) => {\n idle(async () => {\n await inlineBackgroundImages(element, clone, options);\n resolve();\n }, { fast });\n });\n if (embedFonts) {\n await new Promise((resolve) => {\n idle(async () => {\n fontsCSS = await embedCustomFonts();\n resolve();\n }, { fast });\n });\n }\n if (compress) {\n const usedTags = collectUsedTagNames(clone).sort();\n const tagKey = usedTags.join(\",\");\n if (cache.baseStyle.has(tagKey)) {\n baseCSS = cache.baseStyle.get(tagKey);\n } else {\n await new Promise((resolve) => {\n idle(() => {\n baseCSS = generateDedupedBaseCSS(usedTags);\n cache.baseStyle.set(tagKey, baseCSS);\n resolve();\n }, { fast });\n });\n }\n }\n await new Promise((resolve) => {\n idle(() => {\n const rect = element.getBoundingClientRect();\n let w = rect.width;\n let h = rect.height;\n const hasW = Number.isFinite(options.width);\n const hasH = Number.isFinite(options.height);\n const hasScale = typeof scale === \"number\" && scale !== 1;\n if (!hasScale) {\n const aspect = rect.width / rect.height;\n if (hasW && hasH) {\n w = options.width;\n h = options.height;\n } else if (hasW) {\n w = options.width;\n h = w / aspect;\n } else if (hasH) {\n h = options.height;\n w = h * aspect;\n }\n }\n w = Math.ceil(w);\n h = Math.ceil(h);\n clone.setAttribute(\"xmlns\", \"http://www.w3.org/1999/xhtml\");\n clone.style.transformOrigin = \"top left\";\n if (!hasScale && (hasW || hasH)) {\n const originalW = rect.width;\n const originalH = rect.height;\n const scaleX = w / originalW;\n const scaleY = h / originalH;\n const existingTransform = clone.style.transform || \"\";\n const scaleTransform = `scale(${scaleX}, ${scaleY})`;\n clone.style.transform = `${scaleTransform} ${existingTransform}`.trim();\n }\n const svgNS = \"http://www.w3.org/2000/svg\";\n const fo = document.createElementNS(svgNS, \"foreignObject\");\n fo.setAttribute(\"width\", \"100%\");\n fo.setAttribute(\"height\", \"100%\");\n const styleTag = document.createElement(\"style\");\n styleTag.textContent = baseCSS + fontsCSS + \"svg{overflow:visible;}\" + classCSS;\n fo.appendChild(styleTag);\n fo.appendChild(clone);\n const serializer = new XMLSerializer();\n const foString = serializer.serializeToString(fo);\n const svgHeader = ``;\n const svgFooter = \"\";\n svgString = svgHeader + foString + svgFooter;\n dataURL = `data:image/svg+xml;charset=utf-8,${encodeURIComponent(svgString)}`;\n resolve();\n }, { fast });\n });\n const sandbox = document.getElementById(\"snapdom-sandbox\");\n if (sandbox && sandbox.style.position === \"absolute\") sandbox.remove();\n return dataURL;\n}\n\n"], ["/snapdom/src/modules/styles.js", "import { getStyleKey } from '../utils/cssTools.js';\nimport { getStyle } from '../utils/helpers.js';\nimport {cache} from '../core/cache.js'\n\nfunction snapshotComputedStyleFull(style) {\n const result = {};\n for (let i = 0; i < style.length; i++) {\n const prop = style[i];\n let val = style.getPropertyValue(prop);\n\n // Opcional: evitar URLs externas que puedan romper renderizado\n if (\n (prop === 'background-image' || prop === 'content') &&\n val.includes('url(') &&\n !val.includes('data:')\n ) {\n val = 'none';\n }\n\n result[prop] = val;\n }\n return result;\n}\n\nexport function inlineAllStyles(source, clone, compress) {\n if (source.tagName === 'STYLE') return;\n\n if (!cache.preStyle.has(source)) {\n cache.preStyle.set(source, getStyle(source));\n }\n const style = cache.preStyle.get(source);\n\n if (!cache.snapshot.has(source)) {\n const snapshot = snapshotComputedStyleFull(style);\n cache.snapshot.set(source, snapshot);\n }\n\n const snapshot = cache.snapshot.get(source);\n\n const hash = Object.entries(snapshot)\n .sort(([a], [b]) => a.localeCompare(b))\n .map(([prop, val]) => `${prop}:${val}`)\n .join(';');\n\n if (cache.snapshotKey.has(hash)) {\n cache.preStyleMap.set(clone, cache.snapshotKey.get(hash));\n return;\n }\n\n const tagName = source.tagName?.toLowerCase() || 'div';\n const key = getStyleKey(snapshot, tagName, compress);\n\n cache.snapshotKey.set(hash, key);\n cache.preStyleMap.set(clone, key);\n}\n"], ["/snapdom/src/utils/cssTools.js", "/**\n * Utilities for working with CSS styles, defaults, and class generation.\n * @module cssTools\n */\n\nimport { cache } from \"../core/cache\"\n\nconst commonTags = [\n 'div', 'span', 'p', 'a', 'img', 'ul', 'li', 'button', 'input',\n 'select', 'textarea', 'label', 'section', 'article', 'header',\n 'footer', 'nav', 'main', 'aside', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6',\n 'svg', 'path', 'circle', 'rect', 'line', 'g', 'table', 'thead', 'tbody', 'tr', 'td', 'th'\n];\n\nexport function precacheCommonTags() {\n for (let tag of commonTags) {\n getDefaultStyleForTag(tag);\n }\n}\n/**\n * Retrieves default CSS property values from a temporary element.\n *\n * @param {string} tagName - The tag name to get default styles for\n * @returns {Object} Object containing default values for all CSS properties\n */\nexport function getDefaultStyleForTag(tagName) {\n if (cache.defaultStyle.has(tagName)) {\n return cache.defaultStyle.get(tagName);\n }\n\n const skipTags = new Set(['script', 'style', 'meta', 'link', 'noscript', 'template']);\n if (skipTags.has(tagName)) {\n const empty = {}; \n cache.defaultStyle.set(tagName, empty); \n return empty;\n }\n\n let sandbox = document.getElementById('snapdom-sandbox');\n if (!sandbox) {\n sandbox = document.createElement('div');\n sandbox.id = 'snapdom-sandbox';\n sandbox.style.position = 'absolute';\n sandbox.style.left = '-9999px';\n sandbox.style.top = '-9999px';\n sandbox.style.width = '0';\n sandbox.style.height = '0';\n sandbox.style.overflow = 'hidden';\n document.body.appendChild(sandbox);\n }\n\n const el = document.createElement(tagName);\n el.style.all = 'initial';\n sandbox.appendChild(el);\n\n const styles = getComputedStyle(el);\n const defaults = {};\n for (let prop of styles) {\n defaults[prop] = styles.getPropertyValue(prop);\n }\n\n sandbox.removeChild(el);\n cache.defaultStyle.set(tagName, defaults);\n return defaults;\n}\n\n/**\n * Creates a unique key from an element's computed style that differs from defaults.\n *\n * @param {Object} snapshot - Computed style snapshot\n * @param {string} tagName - The tag name of the element\n * @param {boolean} [compress=false] - Whether to compress style keys\n * @returns {string} Semi-colon separated list of non-default properties\n */\n\nexport function getStyleKey(snapshot, tagName, compress = false) {\n const entries = [];\n const defaultStyles = getDefaultStyleForTag(tagName);\n for (let [prop, value] of Object.entries(snapshot)) {\n if (!compress) {\n if (value) {\n entries.push(`${prop}:${value}`);\n }\n } else {\n const defaultValue = defaultStyles[prop];\n if (value && value !== defaultValue) {\n entries.push(`${prop}:${value}`);\n }\n }\n }\n\n return entries.sort().join(\";\");\n}\n\n/**\n * Collects all unique tag names used in the DOM tree rooted at the given node.\n *\n * @param {Node} root - The root node to search\n * @returns {string[]} Array of unique tag names\n */\nexport function collectUsedTagNames(root) {\n const tagSet = new Set();\n if (root.nodeType !== Node.ELEMENT_NODE && root.nodeType !== Node.DOCUMENT_FRAGMENT_NODE) {\n return [];\n }\n if (root.tagName) {\n tagSet.add(root.tagName.toLowerCase());\n }\n if (typeof root.querySelectorAll === 'function') {\n root.querySelectorAll(\"*\").forEach(el => tagSet.add(el.tagName.toLowerCase()));\n }\n return Array.from(tagSet);\n}\n\n/**\n * Generates deduplicated base CSS for the given tag names.\n *\n * @param {string[]} usedTagNames - Array of tag names\n * @returns {string} CSS string\n */\nexport function generateDedupedBaseCSS(usedTagNames) {\n const groups = new Map();\n\n for (let tagName of usedTagNames) {\n const styles = cache.defaultStyle.get(tagName);\n if (!styles) continue;\n\n // Creamos la \"firma\" del bloque CSS para comparar\n const key = Object.entries(styles)\n .map(([k, v]) => `${k}:${v};`)\n .sort()\n .join('');\n\n // Agrupamos por firma\n if (!groups.has(key)) {\n groups.set(key, []);\n }\n groups.get(key).push(tagName);\n }\n\n // Ahora generamos el CSS optimizado\n let css = '';\n for (let [styleBlock, tagList] of groups.entries()) {\n css += `${tagList.join(',')} { ${styleBlock} }\\n`;\n }\n\n return css;\n}\n/**\n * Generates CSS classes from a style map.\n *\n * @returns {Map} Map of style keys to class names\n */\nexport function generateCSSClasses() {\n const keySet = new Set(cache.preStyleMap.values());\n const classMap = new Map();\n let counter = 1;\n for (const key of keySet) {\n classMap.set(key, `c${counter++}`);\n }\n return classMap;\n}\n"], ["/snapdom/src/api/snapdom.js", "/**\n * Main API for snapDOM: capture DOM elements as SVG and raster images.\n * Provides utilities for exporting, downloading, and converting DOM captures.\n * @module snapdom\n */\n\nimport { captureDOM } from '../core/capture';\nimport { isSafari } from '../utils/helpers.js';\nimport { extendIconFonts } from '../modules/iconFonts.js';\n\n/**\n * Converts an SVG data URL to an HTMLImageElement.\n *\n * @param {string} url - SVG data URL\n * @param {Object} options\n * @param {number} [options.dpr=1] - Device pixel ratio\n * @param {number} [options.scale=1] - Scale multiplier\n * @returns {Promise} The resulting image\n */\n\n async function toImg(url, { dpr = 1, scale = 1 }) {\n const img = new Image();\n img.src = url;\n await img.decode();\n img.width = img.width * scale ;\n img.height = img.height * scale ;\n \n return img;\n}\n\n/**\n * Converts an SVG data URL to a Canvas element.\n *\n * @param {string} url - SVG data URL\n * @param {Object} options\n * @param {number} [options.dpr=1] - Device pixel ratio\n * @param {number} [options.scale=1] - Scale multiplier\n * @returns {Promise} The resulting canvas\n */\n\nasync function toCanvas(url, { dpr = 1, scale = 1 } = {}) {\n const img = new Image();\n img.src = url;\n img.crossOrigin = 'anonymous';\n img.loading = 'eager';\n img.decoding = 'sync';\n\n const isSafariBrowser = isSafari();\n let appended = false;\n\n if (isSafariBrowser) {\n document.body.appendChild(img);\n appended = true;\n }\n\n await img.decode();\n\n if (isSafariBrowser) {\n await new Promise(resolve => setTimeout(resolve, 100));\n }\n\n if (img.width === 0 || img.height === 0) {\n if (appended) img.remove();\n throw new Error('Image failed to load or has no dimensions');\n }\n\n const width = img.width * scale;\n const height = img.height * scale;\n\n const canvas = document.createElement('canvas');\n canvas.width = Math.ceil(width * dpr);\n canvas.height = Math.ceil(height * dpr);\n canvas.style.width = `${width}px`;\n canvas.style.height = `${height}px`;\n\n const ctx = canvas.getContext('2d');\n ctx.scale(dpr, dpr);\n ctx.drawImage(img, 0, 0, width, height);\n\n if (appended) img.remove();\n\n return canvas;\n}\n\n/**\n * Converts a DOM snapshot (SVG data URL) into a Blob of the specified format.\n *\n * @param {string} url - SVG data URL\n * @param {Object} [options]\n * @param {string} [options.format=\"svg\"] - Output format: \"svg\", \"png\", \"jpeg\", \"webp\"\n * @param {number} [options.dpr=1] - Device pixel ratio\n * @param {number} [options.scale=1] - Scale multiplier\n * @param {string} [options.backgroundColor=\"#fff\"] - Background for raster formats\n * @param {number} [options.quality] - JPEG/WebP quality (0–1)\n * @returns {Promise} The resulting Blob\n */\nasync function toBlob(url, {\n type = \"svg\",\n scale = 1,\n backgroundColor = \"#fff\",\n quality\n} = {}) {\n const mime = {\n jpg: \"image/jpeg\",\n jpeg: \"image/jpeg\",\n png: \"image/png\",\n webp: \"image/webp\",\n }[type] || \"image/png\";\n\n if (type === \"svg\") {\n const svgText = decodeURIComponent(url.split(\",\")[1]);\n return new Blob([svgText], { type: \"image/svg+xml\" });\n }\n\n const canvas = await createBackground(url, { dpr: 1, scale }, backgroundColor);\n return new Promise((resolve) => {\n canvas.toBlob(blob => resolve(blob), `${mime}`, quality);\n });\n}\n\n\n\n/**\n * Creates a canvas with a background color from an SVG data URL.\n *\n * @param {string} url - SVG data URL\n * @param {Object} options\n * @param {number} [options.dpr=1] - Device pixel ratio\n * @param {number} [options.scale=1] - Scale multiplier\n * @param {string} [backgroundColor] - Background color to apply\n * @returns {Promise} The resulting canvas\n */\n\n async function createBackground(url, { dpr = 1, scale = 1 }, backgroundColor) {\n const baseCanvas = await toCanvas(url, { dpr, scale });\n if (!backgroundColor) return baseCanvas;\n\n const temp = document.createElement(\"canvas\");\n temp.width = baseCanvas.width;\n temp.height = baseCanvas.height;\n const ctx = temp.getContext(\"2d\");\n\n ctx.fillStyle = backgroundColor;\n ctx.fillRect(0, 0, temp.width, temp.height);\n ctx.drawImage(baseCanvas, 0, 0);\n\n return temp;\n}\n\n/**\n * Converts an SVG data URL to a raster image (PNG, JPEG, WebP).\n *\n * @param {string} url - SVG data URL\n * @param {Object} options\n * @param {number} [options.dpr=1] - Device pixel ratio\n * @param {number} [options.scale=1] - Scale multiplier\n * @param {string} [options.backgroundColor=\"#fff\"] - Background color for rasterization\n * @param {number} [options.quality] - Image quality (for JPEG/WebP)\n * @param {string} [format=\"png\"] - Output format: \"png\", \"jpeg\", or \"webp\"\n * @returns {Promise} The resulting raster image\n */\n\n async function toRasterImg(url, { dpr = 1, scale = 1, backgroundColor, quality }, format = \"png\") {\n const defaultBg = [\"jpg\", \"jpeg\", \"webp\"].includes(format) ? \"#fff\" : undefined;\n const finalBg = backgroundColor ?? defaultBg;\n\n const canvas = await createBackground(url, { dpr, scale }, finalBg);\n\n const img = new Image();\n img.src = canvas.toDataURL(`image/${format}`, quality);\n await img.decode();\n\n img.style.width = `${canvas.width / dpr}px`;\n img.style.height = `${canvas.height / dpr}px`;\n\n return img;\n}\n\n/**\n * Downloads a captured image in the specified format.\n *\n * @param {string} url - SVG data URL\n * @param {Object} options\n * @param {number} [options.dpr=1] - Device pixel ratio\n * @param {number} [options.scale=1] - Scale multiplier\n * @param {string} [options.backgroundColor=\"#fff\"] - Background color for rasterization\n * @param {string} [options.format=\"png\"] - Output format\n * @param {string} [options.filename=\"capture\"] - Download filename\n * @returns {Promise} Resolves when download is triggered\n */\n\n async function download(url,{ dpr = 1, scale = 1, backgroundColor, format = \"png\", filename = \"snapDOM\"} = {}) {\n if (format === \"svg\") {\n const blob = await toBlob(url);\n const objectURL = URL.createObjectURL(blob);\n const a = document.createElement(\"a\");\n a.href = objectURL;\n a.download = `${filename}.svg`;\n a.click();\n URL.revokeObjectURL(objectURL);\n return;\n }\n\n const defaultBg = [\"jpg\", \"jpeg\", \"webp\"].includes(format) ? \"#fff\" : undefined;\n const finalBg = backgroundColor ?? defaultBg;\n\n const canvas = await createBackground(url, { dpr, scale }, finalBg);\n const mime = {\n jpg: \"image/jpeg\",\n jpeg: \"image/jpeg\",\n png: \"image/png\",\n webp: \"image/webp\",\n }[format] || \"image/png\";\n\n const dataURL = canvas.toDataURL(mime);\n\n const a = document.createElement(\"a\");\n a.href = dataURL;\n a.download = `${filename}.${format}`;\n a.click();\n}\n\n/**\n * Main entry point: captures a DOM element and returns an object with export methods.\n *\n * @param {Element} element - DOM element to capture\n * @param {Object} [options={}] - Capture options\n * @returns {Promise} Object with export methods (toRaw, toImg, toCanvas, etc.)\n */\n\nexport async function snapdom(element, options = {}) {\n options = { scale: 1, ...options };\n if (!element) throw new Error(\"Element cannot be null or undefined\");\n if (options.iconFonts) {\n extendIconFonts(options.iconFonts);\n }\n return await snapdom.capture(element, options);\n}\n\n/**\n * Captures a DOM element and returns an object with export methods (internal use).\n *\n * @param {Element} el - DOM element to capture\n * @param {Object} [options={}] - Capture options\n * @returns {Promise} Object with export methods\n */\n\nsnapdom.capture = async (el, options = {}) => {\n const url = await captureDOM(el, options);\n const dpr = window.devicePixelRatio || 1;\n const scale = options.scale || 1;\n\n return {\n url,\n options,\n toRaw: () => url,\n toImg: () => toImg(url, { dpr, scale }),\n toCanvas: () => toCanvas(url, { dpr, scale }),\n toBlob: (options) => toBlob(url, { dpr, scale, ...options }),\n toPng: (options) => toRasterImg(url, { dpr, scale, ...options }, \"png\"),\n toJpg: (options) => toRasterImg(url, { dpr, scale, ...options }, \"jpeg\"),\n toWebp: (options) => toRasterImg(url, { dpr, scale, ...options }, \"webp\"),\n download: ({ format = \"png\", filename = \"capture\", backgroundColor } = {}) => download(url, { dpr, scale, backgroundColor, format, filename})\n };\n};\n\n// Compatibilidad\nsnapdom.toRaw = async (el, options) => (await snapdom.capture(el, options)).toRaw();\nsnapdom.toImg = async (el, options) => (await snapdom.capture(el, options)).toImg();\nsnapdom.toCanvas = async (el, options) => (await snapdom.capture(el, options)).toCanvas();\nsnapdom.toBlob = async (el, options) => (await snapdom.capture(el, options)).toBlob(options);\nsnapdom.toPng = async (el, options) => (await snapdom.capture(el, options)).toPng(options);\nsnapdom.toJpg = async (el, options) => (await snapdom.capture(el, options)).toJpg(options);\nsnapdom.toWebp = async (el, options) => (await snapdom.capture(el, options)).toWebp(options);\nsnapdom.download = async (el, options = {}) => {\n const {\n format = \"png\",\n filename = \"capture\",\n backgroundColor,\n ...rest\n } = options;\n\n const capture = await snapdom.capture(el, rest);\n return await capture.download({ format, filename, backgroundColor });\n};"], ["/snapdom/src/modules/svgDefs.js", "/**\n * Inlines external `` used by `` or `` inside SVGs,\n * copying only the necessary definitions into each individual cloned SVG.\n *\n * This is needed because cloned SVGs using `` may reference elements like ``, ``, etc.,\n * defined elsewhere in the document (e.g., in a shared `` block that is not part of the cloned subtree).\n *\n * The function finds all `` elements within `root`, extracts the referenced IDs,\n * and embeds the required definitions at the top of each SVG.\n *\n * @function inlineExternalDef\n * @param {ParentNode} root - The root node containing cloned SVGs (usually the result of a DOM snapshot).\n * @returns {void}\n *\n * @example\n * const { clone } = await prepareClone(element);\n * inlineExternalDef(clone);\n */\n\nexport function inlineExternalDef(root) {\n if (!root) return;\n const defsSources = document.querySelectorAll('svg > defs');\n if (!defsSources.length) return;\n\n root.querySelectorAll('svg').forEach(svg => {\n const uses = svg.querySelectorAll('use');\n if (!uses.length) return;\n\n const usedIds = new Set();\n uses.forEach(use => {\n const href = use.getAttribute('xlink:href') || use.getAttribute('href');\n if (href && href.startsWith('#')) usedIds.add(href.slice(1));\n });\n if (!usedIds.size) return;\n\n const defs = document.createElementNS(\"http://www.w3.org/2000/svg\", \"defs\");\n\n for (const id of usedIds) {\n for (const source of defsSources) {\n const def = source.querySelector(`#${CSS.escape(id)}`);\n if (def) {\n defs.appendChild(def.cloneNode(true));\n break;\n }\n }\n }\n\n if (defs.childNodes.length) {\n svg.insertBefore(defs, svg.firstChild);\n }\n });\n}\n"], ["/snapdom/__tests__/pseudo.module.test.js", "vi.mock('../src/utils/helpers.js', async () => {\n const actual = await vi.importActual('../src/utils/helpers.js');\n return {\n ...actual,\n fetchImage: vi.fn(),\n };\n});\nvi.mock('../src/modules/fonts.js', async () => {\n const actual = await vi.importActual('../src/modules/fonts.js');\n return {\n ...actual,\n iconToImage: vi.fn(),\n };\n});\n\nimport { describe, it, expect, vi } from 'vitest';\nimport { inlinePseudoElements } from '../src/modules/pseudo.js';\nimport * as helpers from '../src/utils/helpers.js';\nimport * as fonts from '../src/modules/fonts.js';\n\ndescribe('inlinePseudoElements', () => {\n it('does not fail with simple elements', async () => {\n const el = document.createElement('div');\n const clone = document.createElement('div');\n await expect(inlinePseudoElements(el, clone, new Map(), new WeakMap(), false)).resolves.toBeUndefined();\n });\n\n it('handles ::before with text content', async () => {\n const el = document.createElement('div');\n const clone = document.createElement('div');\n vi.spyOn(window, 'getComputedStyle').mockImplementation((_, pseudo) => {\n if (pseudo === '::before') return {\n getPropertyValue: (prop) => prop === 'content' ? '\"★\"' : prop === 'font-family' ? 'Arial' : prop === 'font-size' ? '32' : prop === 'font-weight' ? '400' : prop === 'color' ? '#000' : prop === 'background-image' ? 'none' : prop === 'background-color' ? 'transparent' : '',\n color: '#000', fontSize: '32px', fontWeight: '400', fontFamily: 'Arial',\n };\n return { getPropertyValue: () => '', color: '', fontSize: '', fontWeight: '', fontFamily: '' };\n });\n await inlinePseudoElements(el, clone, new Map(), new WeakMap(), false);\n window.getComputedStyle.mockRestore();\n });\n\n it('handles ::before with icon font', async () => {\n const el = document.createElement('div');\n const clone = document.createElement('div');\n vi.spyOn(window, 'getComputedStyle').mockImplementation((_, pseudo) => {\n if (pseudo === '::before') return {\n getPropertyValue: (prop) => prop === 'content' ? '\"★\"' : prop === 'font-family' ? 'Font Awesome' : prop === 'font-size' ? '32' : prop === 'font-weight' ? '400' : prop === 'color' ? '#000' : prop === 'background-image' ? 'none' : prop === 'background-color' ? 'transparent' : '',\n color: '#000', fontSize: '32px', fontWeight: '400', fontFamily: 'Font Awesome',\n };\n return { getPropertyValue: () => '', color: '', fontSize: '', fontWeight: '', fontFamily: '' };\n });\n fonts.iconToImage.mockResolvedValue('data:image/png;base64,icon');\n await inlinePseudoElements(el, clone, new Map(), new WeakMap(), false);\n window.getComputedStyle.mockRestore();\n });\n\n it('handles ::before with url content', async () => {\n const el = document.createElement('div');\n const clone = document.createElement('div');\n vi.spyOn(window, 'getComputedStyle').mockImplementation((_, pseudo) => {\n if (pseudo === '::before') return {\n getPropertyValue: (prop) => prop === 'content' ? 'url(\"https://test.com/img.png\")' : prop === 'font-family' ? 'Arial' : prop === 'font-size' ? '32' : prop === 'font-weight' ? '400' : prop === 'color' ? '#000' : prop === 'background-image' ? 'none' : prop === 'background-color' ? 'transparent' : '',\n color: '#000', fontSize: '32px', fontWeight: '400', fontFamily: 'Arial',\n };\n return { getPropertyValue: () => '', color: '', fontSize: '', fontWeight: '', fontFamily: '' };\n });\n helpers.fetchImage.mockResolvedValue('data:image/png;base64,img');\n await inlinePseudoElements(el, clone, new Map(), new WeakMap(), false);\n window.getComputedStyle.mockRestore();\n });\n\n it('handles ::before with background-image (data url)', async () => {\n const el = document.createElement('div');\n const clone = document.createElement('div');\n vi.spyOn(window, 'getComputedStyle').mockImplementation((_, pseudo) => {\n if (pseudo === '::before') return {\n getPropertyValue: (prop) => prop === 'content' ? 'none' : prop === 'font-family' ? 'Arial' : prop === 'font-size' ? '32' : prop === 'font-weight' ? '400' : prop === 'color' ? '#000' : prop === 'background-image' ? 'url(\"data:image/png;base64,abc\")' : prop === 'background-color' ? 'transparent' : '',\n color: '#000', fontSize: '32px', fontWeight: '400', fontFamily: 'Arial',\n };\n return { getPropertyValue: () => '', color: '', fontSize: '', fontWeight: '', fontFamily: '' };\n });\n await inlinePseudoElements(el, clone, new Map(), new WeakMap(), false);\n window.getComputedStyle.mockRestore();\n });\n\n it('handles ::before with background-image (fetch)', async () => {\n const el = document.createElement('div');\n const clone = document.createElement('div');\n vi.spyOn(window, 'getComputedStyle').mockImplementation((_, pseudo) => {\n if (pseudo === '::before') return {\n getPropertyValue: (prop) => prop === 'content' ? 'none' : prop === 'font-family' ? 'Arial' : prop === 'font-size' ? '32' : prop === 'font-weight' ? '400' : prop === 'color' ? '#000' : prop === 'background-image' ? 'url(\"https://test.com/img.png\")' : prop === 'background-color' ? 'transparent' : '',\n color: '#000', fontSize: '32px', fontWeight: '400', fontFamily: 'Arial',\n };\n return { getPropertyValue: () => '', color: '', fontSize: '', fontWeight: '', fontFamily: '' };\n });\n helpers.fetchImage.mockResolvedValue('data:image/png;base64,img');\n await inlinePseudoElements(el, clone, new Map(), new WeakMap(), false);\n window.getComputedStyle.mockRestore();\n });\n\n it('handles ::before with background-image fetch error', async () => {\n const el = document.createElement('div');\n const clone = document.createElement('div');\n vi.spyOn(window, 'getComputedStyle').mockImplementation((_, pseudo) => {\n if (pseudo === '::before') return {\n getPropertyValue: (prop) => prop === 'content' ? 'none' : prop === 'font-family' ? 'Arial' : prop === 'font-size' ? '32' : prop === 'font-weight' ? '400' : prop === 'color' ? '#000' : prop === 'background-image' ? 'url(\"https://test.com/img.png\")' : prop === 'background-color' ? 'transparent' : '',\n color: '#000', fontSize: '32px', fontWeight: '400', fontFamily: 'Arial',\n };\n return { getPropertyValue: () => '', color: '', fontSize: '', fontWeight: '', fontFamily: '' };\n });\n helpers.fetchImage.mockRejectedValue(new Error('fail'));\n await inlinePseudoElements(el, clone, new Map(), new WeakMap(), false);\n window.getComputedStyle.mockRestore();\n });\n\n it('handles ::before with no visible box', async () => {\n const el = document.createElement('div');\n const clone = document.createElement('div');\n vi.spyOn(window, 'getComputedStyle').mockImplementation((_, pseudo) => {\n if (pseudo === '::before') return {\n getPropertyValue: () => 'none', color: '', fontSize: '', fontWeight: '', fontFamily: ''\n };\n return { getPropertyValue: () => '', color: '', fontSize: '', fontWeight: '', fontFamily: '' };\n });\n await inlinePseudoElements(el, clone, new Map(), new WeakMap(), false);\n window.getComputedStyle.mockRestore();\n });\n\n it('handles ::first-letter with no textNode', async () => {\n const el = document.createElement('div');\n const clone = document.createElement('div');\n vi.spyOn(window, 'getComputedStyle').mockImplementation(() => ({\n getPropertyValue: () => '', color: '', fontSize: '', fontWeight: '', fontFamily: ''\n }));\n await inlinePseudoElements(el, clone, new Map(), new WeakMap(), false);\n window.getComputedStyle.mockRestore();\n });\n\n it('handles error in pseudo processing', async () => {\n const el = document.createElement('div');\n const clone = document.createElement('div');\n vi.spyOn(window, 'getComputedStyle').mockImplementation(() => { throw new Error('fail'); });\n await inlinePseudoElements(el, clone, new Map(), new WeakMap(), false);\n window.getComputedStyle.mockRestore();\n });\n\n it('ignores if source no es Element', async () => {\n const notElement = {};\n const clone = document.createElement('div');\n await expect(inlinePseudoElements(notElement, clone, new Map(), new WeakMap(), false)).resolves.toBeUndefined();\n });\n\n it('ignores if clone no es Element', async () => {\n const el = document.createElement('div');\n const notElement = {};\n await expect(inlinePseudoElements(el, notElement, new Map(), new WeakMap(), false)).resolves.toBeUndefined();\n });\n\n it('inserta pseudoEl como ::after', async () => {\n const el = document.createElement('div');\n const clone = document.createElement('div');\n vi.spyOn(window, 'getComputedStyle').mockImplementation((_, pseudo) => {\n if (pseudo === '::after') return {\n getPropertyValue: (prop) => prop === 'content' ? '\"after\"' : prop === 'font-family' ? 'Arial' : prop === 'font-size' ? '32' : prop === 'font-weight' ? '400' : prop === 'color' ? '#000' : prop === 'background-image' ? 'none' : prop === 'background-color' ? '#f00' : '',\n color: '#000', fontSize: '32px', fontWeight: '400', fontFamily: 'Arial',\n };\n return { getPropertyValue: () => '', color: '', fontSize: '', fontWeight: '', fontFamily: '' };\n });\n await inlinePseudoElements(el, clone, new Map(), new WeakMap(), false);\n window.getComputedStyle.mockRestore();\n });\n\n it('inserta pseudoEl como ::before', async () => {\n const el = document.createElement('div');\n const clone = document.createElement('div');\n vi.spyOn(window, 'getComputedStyle').mockImplementation((_, pseudo) => {\n if (pseudo === '::before') return {\n getPropertyValue: (prop) => prop === 'content' ? '\"before\"' : prop === 'font-family' ? 'Arial' : prop === 'font-size' ? '32' : prop === 'font-weight' ? '400' : prop === 'color' ? '#000' : prop === 'background-image' ? 'none' : prop === 'background-color' ? '#f00' : '',\n color: '#000', fontSize: '32px', fontWeight: '400', fontFamily: 'Arial',\n };\n return { getPropertyValue: () => '', color: '', fontSize: '', fontWeight: '', fontFamily: '' };\n });\n await inlinePseudoElements(el, clone, new Map(), new WeakMap(), false);\n window.getComputedStyle.mockRestore();\n });\n\n it('no inserta pseudoEl si no hay visible box', async () => {\n const el = document.createElement('div');\n const clone = document.createElement('div');\n vi.spyOn(window, 'getComputedStyle').mockImplementation((_, pseudo) => {\n if (pseudo === '::before') return {\n getPropertyValue: (prop) => 'none', color: '', fontSize: '', fontWeight: '', fontFamily: ''\n };\n return { getPropertyValue: () => '', color: '', fontSize: '', fontWeight: '', fontFamily: '' };\n });\n await inlinePseudoElements(el, clone, new Map(), new WeakMap(), false);\n window.getComputedStyle.mockRestore();\n });\n\n it('maneja ::first-letter meaningful', async () => {\n const el = document.createElement('div');\n el.textContent = 'Test';\n const clone = document.createElement('div');\n clone.textContent = 'Test';\n vi.spyOn(window, 'getComputedStyle').mockImplementation((_, pseudo) => {\n if (pseudo === '::first-letter') return {\n getPropertyValue: (prop) => prop === 'color' ? '#f00' : '', color: '#f00', fontSize: '32px', fontWeight: '400', fontFamily: 'Arial',\n };\n return { getPropertyValue: () => '', color: '#000', fontSize: '32px', fontWeight: '400', fontFamily: 'Arial' };\n });\n await inlinePseudoElements(el, clone, new Map(), new WeakMap(), false);\n window.getComputedStyle.mockRestore();\n });\n\n it('inserta ambos pseudoEl ::before y ::after en una sola ejecución', async () => {\n const el = document.createElement('div');\n const clone = document.createElement('div');\n vi.spyOn(window, 'getComputedStyle').mockImplementation((_, pseudo) => {\n if (pseudo === '::before') return {\n getPropertyValue: (prop) => prop === 'content' ? '\"before\"' : prop === 'font-family' ? 'Arial' : prop === 'font-size' ? '32' : prop === 'font-weight' ? '400' : prop === 'color' ? '#000' : prop === 'background-image' ? 'none' : prop === 'background-color' ? '#f00' : '',\n color: '#000', fontSize: '32px', fontWeight: '400', fontFamily: 'Arial',\n };\n if (pseudo === '::after') return {\n getPropertyValue: (prop) => prop === 'content' ? '\"after\"' : prop === 'font-family' ? 'Arial' : prop === 'font-size' ? '32' : prop === 'font-weight' ? '400' : prop === 'color' ? '#000' : prop === 'background-image' ? 'none' : prop === 'background-color' ? '#0f0' : '',\n color: '#000', fontSize: '32px', fontWeight: '400', fontFamily: 'Arial',\n };\n return { getPropertyValue: () => '', color: '', fontSize: '', fontWeight: '', fontFamily: '' };\n });\n await inlinePseudoElements(el, clone, new Map(), new WeakMap(), false);\n window.getComputedStyle.mockRestore();\n });\n\n it('should inline ::first-letter when style is meaningful', async () => {\n const el = document.createElement('p');\n el.textContent = '¡Hola mundo!';\n el.style.setProperty('color', 'black');\n\n document.body.appendChild(el);\n const clone = el.cloneNode(true);\n const styleMap = new Map();\n const styleCache = new WeakMap();\n\n const style = document.createElement('style');\n style.textContent = `\n p::first-letter {\n color: red;\n font-size: 200%;\n }\n `;\n document.head.appendChild(style);\n\n await inlinePseudoElements(el, clone, styleMap, styleCache, false);\n const firstLetterEl = clone.querySelector('[data-snapdom-pseudo=\"::first-letter\"]');\n expect(firstLetterEl).toBeTruthy();\n expect(firstLetterEl.textContent.length).toBeGreaterThan(0);\n});\n\nit('should inline background-image entries for pseudo-element', async () => {\n const el = document.createElement('div');\n document.body.appendChild(el);\n\n const style = document.createElement('style');\n style.textContent = `\n div::after {\n content: \" \";\n background-image: url(\"data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg'%3E%3Crect width='10' height='10' fill='blue'/%3E%3C/svg%3E\");\n display: inline-block;\n width: 10px;\n height: 10px;\n }\n `;\n document.head.appendChild(style);\n\n const clone = el.cloneNode(true);\n const styleMap = new Map();\n const styleCache = new WeakMap();\n\n await inlinePseudoElements(el, clone, styleMap, styleCache, false);\n const pseudoAfter = clone.querySelector('[data-snapdom-pseudo=\"::after\"]');\n expect(pseudoAfter).toBeTruthy();\n expect(pseudoAfter.style.backgroundImage.startsWith(\"url(\\\"data:image/\")).toBeTruthy();\n});\n\n});\n\n\n\n\n\n"], ["/snapdom/__tests__/pseudo.bg-inline-success.test.js", "vi.mock('../src/utils/helpers.js', async () => {\n const actual = await vi.importActual('../src/utils/helpers.js');\n return {\n ...actual,\n inlineSingleBackgroundEntry: vi.fn().mockResolvedValue('url(\"data:image/png;base64,abc\")'),\n };\n});\n\nimport { describe, it, vi } from 'vitest';\nimport { inlinePseudoElements } from '../src/modules/pseudo.js';\n\ndescribe('inlinePseudoElements background-image inlining (success)', () => {\n it('cubre el inlining exitoso de background-image en pseudo', async () => {\n const el = document.createElement('div');\n const clone = document.createElement('div');\n vi.spyOn(window, 'getComputedStyle').mockImplementation((_, pseudo) => {\n if (pseudo === '::before') return {\n getPropertyValue: (prop) => prop === 'content' ? 'none' : prop === 'font-family' ? 'Arial' : prop === 'font-size' ? '32' : prop === 'font-weight' ? '400' : prop === 'color' ? '#000' : prop === 'background-image' ? 'url(\"data:image/png;base64,abc\")' : prop === 'background-color' ? 'transparent' : '',\n color: '#000', fontSize: '32px', fontWeight: '400', fontFamily: 'Arial',\n };\n return { getPropertyValue: () => '', color: '', fontSize: '', fontWeight: '', fontFamily: '' };\n });\n await inlinePseudoElements(el, clone, new Map(), new WeakMap(), false);\n window.getComputedStyle.mockRestore();\n });\n});\n"], ["/snapdom/__tests__/pseudo.bg-inline-error.test.js", "vi.mock('../src/utils/helpers.js', async () => {\n const actual = await vi.importActual('../src/utils/helpers.js');\n return {\n ...actual,\n inlineSingleBackgroundEntry: vi.fn().mockRejectedValue(new Error('fail')),\n };\n});\n\nimport { describe, it, vi } from 'vitest';\nimport { inlinePseudoElements } from '../src/modules/pseudo.js';\n\ndescribe('inlinePseudoElements background-image inlining (error)', () => {\n it('cubre el catch de error en inlining de background-image en pseudo', async () => {\n const el = document.createElement('div');\n const clone = document.createElement('div');\n vi.spyOn(window, 'getComputedStyle').mockImplementation((_, pseudo) => {\n if (pseudo === '::before') return {\n getPropertyValue: (prop) => prop === 'content' ? 'none' : prop === 'font-family' ? 'Arial' : prop === 'font-size' ? '32' : prop === 'font-weight' ? '400' : prop === 'color' ? '#000' : prop === 'background-image' ? 'url(\"data:image/png;base64,abc\")' : prop === 'background-color' ? 'transparent' : '',\n color: '#000', fontSize: '32px', fontWeight: '400', fontFamily: 'Arial',\n };\n return { getPropertyValue: () => '', color: '', fontSize: '', fontWeight: '', fontFamily: '' };\n });\n await inlinePseudoElements(el, clone, new Map(), new WeakMap(), false);\n window.getComputedStyle.mockRestore();\n });\n});\n"], ["/snapdom/src/modules/iconFonts.js", "var defaultIconFonts = [\n// /uicons/i,\n /font\\s*awesome/i,\n /material\\s*icons/i,\n /ionicons/i,\n /glyphicons/i,\n /feather/i,\n /bootstrap\\s*icons/i,\n /remix\\s*icons/i,\n /heroicons/i,\n /layui/i,\n /lucide/i\n];\n\nvar userIconFonts = [];\n\nexport function extendIconFonts(fonts) {\n const list = Array.isArray(fonts) ? fonts : [fonts];\n for (const f of list) {\n if (f instanceof RegExp) {\n userIconFonts.push(f);\n } else if (typeof f === \"string\") {\n userIconFonts.push(new RegExp(f, \"i\"));\n } else {\n console.warn(\"[snapdom] Ignored invalid iconFont value:\", f);\n }\n }\n}\n\nexport function isIconFont(input) {\n const text = typeof input === \"string\" ? input : \"\";\n\n const candidates = [...defaultIconFonts, ...userIconFonts];\n\n for (const rx of candidates) {\n if (rx instanceof RegExp && rx.test(text)) return true;\n }\n\n // Heurística básica\n if (\n /icon/i.test(text) ||\n /glyph/i.test(text) ||\n /symbols/i.test(text) ||\n /feather/i.test(text) ||\n /fontawesome/i.test(text)\n ) return true;\n\n return false;\n}"], ["/snapdom/__tests__/snapdom.benchmark.js", "import { bench, describe, beforeEach, afterEach } from 'vitest';\nimport { domToDataUrl } from 'https://unpkg.com/modern-screenshot';\nimport * as htmlToImage from 'https://cdn.jsdelivr.net/npm/html-to-image@1.11.13/+esm';\n//import { toPng, toJpeg, toBlob, toPixelData, toSvg } from 'https://cdn.jsdelivr.net/npm/html-to-image@1.11.13/dist/html-to-image.min.js';\nimport { snapdom as sd } from 'https://cdn.jsdelivr.net/npm/@zumer/snapdom@1.8.0/dist/snapdom.mjs';\nimport { snapdom } from '../src/index';\n\n\nlet html2canvasLoaded = false;\n\nasync function loadHtml2Canvas() {\n if (html2canvasLoaded) return;\n await new Promise((resolve, reject) => {\n const script = document.createElement('script');\n script.src = 'https://cdn.jsdelivr.net/npm/html2canvas@1.4.1/dist/html2canvas.min.js';\n script.onload = () => resolve();\n script.onerror = reject;\n document.head.appendChild(script);\n });\n html2canvasLoaded = true;\n}\n\nawait loadHtml2Canvas();\n\n\n\nconst sizes = [\n { width: 200, height: 100, label: 'Small element (200x100)' },\n { width: 400, height: 300, label: 'Modal size (400x300)' },\n { width: 1200, height: 800, label: 'Page view (1200x800)' },\n { width: 2000, height: 1500, label: 'Large scroll area (2000x1500)' },\n { width: 4000, height: 2000, label: 'Very large element (4000x2000)' },\n];\n\nfor (const size of sizes) {\n describe(`Benchmark simple node at ${size.label}`, () => {\n let container;\n\n async function setupContainer() { \n if (container && document.body.contains(container)) {\n return;\n }\n container = document.createElement('div');\n container.style.width = `${size.width}px`;\n container.style.height = `${size.height}px`;\n container.style.background = 'linear-gradient(to right, red, blue)';\n container.style.fontFamily = 'Arial, sans-serif';\n container.style.display = 'flex';\n container.style.alignItems = 'center';\n container.style.justifyContent = 'center';\n container.style.fontSize = '24px';\n container.innerHTML = `

${size.label}

`;\n document.body.appendChild(container);\n } \n\n /* async function setupContainer() {\n if (container && document.body.contains(container)) return;\n \n container = document.createElement('div');\n container.style.width = `${size.width}px`;\n container.style.height = `${size.height}px`;\n container.style.padding = '20px';\n container.style.overflow = 'auto';\n container.style.background = 'white';\n container.style.border = '2px solid black';\n container.style.fontFamily = 'Arial, sans-serif';\n container.style.color = '#333';\n container.style.position = 'relative';\n \n const grid = document.createElement('div');\n grid.style.display = 'grid';\n grid.style.gridTemplateColumns = 'repeat(auto-fill, minmax(120px, 1fr))';\n grid.style.gap = '10px';\n \n for (let i = 0; i < Math.floor((size.width * size.height) / 20000); i++) {\n const card = document.createElement('div');\n card.style.padding = '10px';\n card.style.borderRadius = '8px';\n card.style.background = i % 2 === 0 ? '#f0f0f0' : '#e0eaff';\n card.style.boxShadow = '0 2px 5px rgba(0,0,0,0.1)';\n card.style.display = 'flex';\n card.style.flexDirection = 'column';\n card.style.alignItems = 'center';\n \n const title = document.createElement('h3');\n title.textContent = `Card ${i + 1}`;\n title.style.margin = '0 0 10px 0';\n title.style.fontSize = '14px';\n \n const icon = document.createElement('div');\n icon.style.width = '30px';\n icon.style.height = '30px';\n icon.style.borderRadius = '50%';\n icon.style.background = i % 2 === 0 ? 'red' : 'blue';\n icon.style.marginBottom = '10px';\n \n const text = document.createElement('p');\n text.textContent = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit.';\n text.style.fontSize = '12px';\n text.style.textAlign = 'center';\n \n card.appendChild(icon);\n card.appendChild(title);\n card.appendChild(text);\n grid.appendChild(card);\n }\n \n container.appendChild(grid);\n document.body.appendChild(container);\n }\n */\n afterEach(() => {\n if (container) {\n container.remove();\n container = null;\n }\n });\n\n bench('snapDOM current version', async () => {\n await setupContainer();\n await snapdom.toRaw(container);\n });\n\n bench('snapDOM V1.8.0', async () => {\n await setupContainer();\n await sd.toRaw(container);\n });\n\n bench('html2canvas capture', async () => {\n await setupContainer();\n const canvas = await window.html2canvas(container, { logging: false, scale: 1 });\n await canvas.toDataURL();\n });\n\n bench('modern-screenshot capture', async () => {\n await setupContainer();\n await domToDataUrl(container);\n });\n\n bench('html-to-image capture', async () => {\n await setupContainer();\n await htmlToImage.toSvg(container);\n });\n });\n}\n"], ["/snapdom/__tests__/helpers.utils.test.js", "import { describe, it, expect, vi } from 'vitest';\nimport { getStyle, parseContent, extractURL, isIconFont, snapshotComputedStyle, isSafari, stripTranslate, safeEncodeURI, idle, fetchImage } from '../src/utils/helpers.js';\n\ndescribe('getStyle', () => {\n it('returns a CSSStyleDeclaration', () => {\n const el = document.createElement('div');\n document.body.appendChild(el);\n const style = getStyle(el);\n expect(style).toBeInstanceOf(CSSStyleDeclaration);\n document.body.removeChild(el);\n });\n});\n\n\n\ndescribe('parseContent', () => {\n it('parses CSS content correctly', () => {\n expect(parseContent('\"★\"')).toBe('★');\n expect(parseContent('\\\\2605')).toBe('★');\n });\n});\n\ndescribe('parseContent edge cases', () => {\n it('returns \\u0000 if parseInt fails (not hex)', () => {\n expect(parseContent('\\\\nothex')).toBe('\\u0000');\n });\n it('returns clean if String.fromCharCode throws', () => {\n const orig = String.fromCharCode;\n String.fromCharCode = () => { throw new Error('fail'); };\n expect(parseContent('\\\\2605')).toBe('\\\\2605');\n String.fromCharCode = orig;\n });\n});\n\ndescribe('extractURL', () => {\n it('extracts the URL from background-image', () => {\n expect(extractURL('url(\"https://test.com/img.png\")')).toBe('https://test.com/img.png');\n expect(extractURL('none')).toBeNull();\n });\n});\n\ndescribe('isIconFont', () => {\n it('detects icon fonts', () => {\n expect(isIconFont('Font Awesome')).toBe(true);\n expect(isIconFont('Arial')).toBe(false);\n });\n});\n\ndescribe('snapshotComputedStyle', () => {\n it('returns a style snapshot', () => {\n const el = document.createElement('div');\n document.body.appendChild(el);\n const style = getComputedStyle(el);\n const snap = snapshotComputedStyle(style);\n expect(typeof snap).toBe('object');\n document.body.removeChild(el);\n });\n});\n\ndescribe('isSafari', () => {\n it('returns a boolean', () => {\n expect(typeof isSafari()).toBe('boolean');\n });\n});\n\ndescribe('stripTranslate', () => {\n it('removes translate transforms', () => {\n expect(stripTranslate('translateX(10px) scale(2)')).toContain('scale(2)');\n });\n it('stripTranslate removes matrix and matrix3d', () => {\n expect(stripTranslate('matrix(1,0,0,1,10,20)')).not.toContain('10,20');\n expect(stripTranslate('matrix3d(1,0,0,0,0,1,0,0,0,0,1,0,10,20,30,1)')).not.toContain('10,20,30');\n });\n});\n\ndescribe('safeEncodeURI', () => {\n it('returns an encoded string', () => {\n expect(typeof safeEncodeURI('https://test.com/á')).toBe('string');\n });\n it('safeEncodeURI handles invalid URIs gracefully', () => {\n expect(typeof safeEncodeURI('%E0%A4%A')).toBe('string');\n });\n});\n\ndescribe('idle', () => {\n it('calls fn immediately if fast is true', () => {\n let called = false;\n idle(() => { called = true; }, { fast: true });\n expect(called).toBe(true);\n });\n it('uses requestIdleCallback if available', () => {\n const orig = window.requestIdleCallback;\n let called = false;\n window.requestIdleCallback = (fn) => { called = true; fn(); };\n idle(() => { called = true; });\n expect(called).toBe(true);\n window.requestIdleCallback = orig;\n });\n it('falls back to setTimeout if requestIdleCallback not available', async () => {\n const orig = window.requestIdleCallback;\n delete window.requestIdleCallback;\n let called = false;\n idle(() => { called = true; });\n await new Promise(r => setTimeout(r, 10));\n expect(called).toBe(true);\n window.requestIdleCallback = orig;\n });\n});\n\ndescribe('fetchImage', () => {\n it('rejects on image error', async () => {\n await expect(fetchImage('invalid-url', { timeout: 100 }))\n .rejects.toThrow('Fetch fallback failed and no proxy provided');\n\n });\n it('rejects on timeout', async () => {\n // Simula una imagen que nunca carga\n const origImage = window.Image;\n window.Image = class { set src(_){} onload(){} onerror(){} };\n await expect(fetchImage('timeout-url', { timeout: 10 })).rejects.toThrow('Image load timed out');\n window.Image = origImage;\n });\n\n});\n\ndescribe('fetchImage cache', () => {\n it('returns cached image if present', async () => {\n const { cache } = await import('../src/core/cache.js');\n cache.image.set('cached-url', 'data:image/png;base64,abc');\n const result = await fetchImage('cached-url', { useProxy: false });\n expect(result).toBe('data:image/png;base64,abc');\n cache.image.delete('cached-url');\n });\n});\n\ndescribe('fetchImage error propagation', () => {\n it('rejects with original error if decode fails', async () => {\n const origImage = window.Image;\n window.Image = class {\n constructor() { setTimeout(() => this.onload(), 1); }\n set src(_){}\n decode() { return Promise.reject(new Error('decode fail')); }\n get width() { return 1; }\n get height() { return 1; }\n };\n await expect(fetchImage('decode-fail-url', { timeout: 100 }))\n .rejects.toThrow('Fetch fallback failed and no proxy provided');\n window.Image = origImage;\n });\n});\n\ndescribe('stripTranslate edge cases', () => {\n it('returns empty string for empty or none', () => {\n expect(stripTranslate('')).toBe('');\n expect(stripTranslate('none')).toBe('');\n });\n it('returns original for malformed matrix', () => {\n expect(stripTranslate('matrix(1,2,3)')).toBe('matrix(1,2,3)');\n expect(stripTranslate('matrix3d(1,2,3)')).toBe('matrix3d(1,2,3)');\n });\n});\n"], ["/snapdom/src/core/cache.js", "/**\n * Caches for images, backgrounds, resources, and computed styles used during DOM capture.\n * @module cache\n */\n\nexport const cache = {\n image: new Map(),\n background: new Map(),\n resource: new Map(),\n defaultStyle: new Map(),\n baseStyle: new Map(),\n computedStyle: new WeakMap(),\n font: new Set(),\n snapshot: new WeakMap(),\n snapshotKey: new Map(),\n preStyleMap: new Map(),\n preStyle: new WeakMap(),\n preNodeMap: new Map(),\n reset: resetCache\n};\n\nfunction resetCache() {\n cache.computedStyle = new WeakMap();\n cache.snapshot = new WeakMap();\n cache.snapshotKey.clear();\n cache.preStyleMap.clear();\n cache.preStyle = new WeakMap();\n cache.preNodeMap.clear();\n}\n"], ["/snapdom/__tests__/snapdom.complex.benchmark.js", "import { bench, describe, beforeEach, afterEach } from 'vitest';\nimport { domToDataUrl } from 'https://unpkg.com/modern-screenshot';\nimport * as htmlToImage from 'https://cdn.jsdelivr.net/npm/html-to-image@1.11.13/+esm';\nimport { snapdom as sd } from 'https://cdn.jsdelivr.net/npm/@zumer/snapdom@1.8.0/dist/snapdom.mjs';\nimport { snapdom } from '../src/index';\n\nlet html2canvasLoaded = false;\n\nasync function loadHtml2Canvas() {\n if (html2canvasLoaded) return;\n await new Promise((resolve, reject) => {\n const script = document.createElement('script');\n script.src = 'https://cdn.jsdelivr.net/npm/html2canvas@1.4.1/dist/html2canvas.min.js';\n script.onload = () => resolve();\n script.onerror = reject;\n document.head.appendChild(script);\n });\n html2canvasLoaded = true;\n}\n\nawait loadHtml2Canvas();\n\nconst sizes = [\n { width: 200, height: 100, label: 'Small element (200x100)' },\n { width: 400, height: 300, label: 'Modal size (400x300)' },\n { width: 1200, height: 800, label: 'Page view (1200x800)' },\n { width: 2000, height: 1500, label: 'Large scroll area (2000x1500)' },\n { width: 4000, height: 2000, label: 'Very large element (4000x2000)' },\n];\n\nfor (const size of sizes) {\n describe(`Benchmark complex node at ${size.label}`, () => {\n let container;\n\n async function setupContainer() {\n if (container && document.body.contains(container)) return;\n \n container = document.createElement('div');\n container.style.width = `${size.width}px`;\n container.style.height = `${size.height}px`;\n container.style.padding = '20px';\n container.style.overflow = 'auto';\n container.style.background = 'white';\n container.style.border = '2px solid black';\n container.style.fontFamily = 'Arial, sans-serif';\n container.style.color = '#333';\n container.style.position = 'relative';\n \n const grid = document.createElement('div');\n grid.style.display = 'grid';\n grid.style.gridTemplateColumns = 'repeat(auto-fill, minmax(120px, 1fr))';\n grid.style.gap = '10px';\n \n for (let i = 0; i < Math.floor((size.width * size.height) / 20000); i++) {\n const card = document.createElement('div');\n card.style.padding = '10px';\n card.style.borderRadius = '8px';\n card.style.background = i % 2 === 0 ? '#f0f0f0' : '#e0eaff';\n card.style.boxShadow = '0 2px 5px rgba(0,0,0,0.1)';\n card.style.display = 'flex';\n card.style.flexDirection = 'column';\n card.style.alignItems = 'center';\n \n const title = document.createElement('h3');\n title.textContent = `Card ${i + 1}`;\n title.style.margin = '0 0 10px 0';\n title.style.fontSize = '14px';\n \n const icon = document.createElement('div');\n icon.style.width = '30px';\n icon.style.height = '30px';\n icon.style.borderRadius = '50%';\n icon.style.background = i % 2 === 0 ? 'red' : 'blue';\n icon.style.marginBottom = '10px';\n \n const text = document.createElement('p');\n text.textContent = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit.';\n text.style.fontSize = '12px';\n text.style.textAlign = 'center';\n \n card.appendChild(icon);\n card.appendChild(title);\n card.appendChild(text);\n grid.appendChild(card);\n }\n \n container.appendChild(grid);\n document.body.appendChild(container);\n \n }\n \n afterEach (async () => {\n if (container) {\n container.remove();\n container = null;\n }\n \n document.body.innerHTML = ''\n });\n\n bench('snapDOM current version', async () => {\n await setupContainer();\n await snapdom.toRaw(container, {compress: true, fast: true});\n });\n\n bench('snapDOM V1.8.0', async () => {\n await setupContainer();\n await sd.toRaw(container);\n });\n \n bench('html2canvas capture', async () => {\n await setupContainer();\n const canvas = await window.html2canvas(container, { logging: false, scale: 1 });\n await canvas.toDataURL();\n });\n\n bench('modern-screenshot capture', async () => {\n await setupContainer();\n await domToDataUrl(container);\n });\n bench('html-to-image capture', async () => {\n await setupContainer();\n await htmlToImage.toSvg(container);\n });\n });\n}\n"], ["/snapdom/__tests__/background.module.test.js", "import { describe, it, expect, beforeEach, afterEach } from 'vitest';\nimport { inlineBackgroundImages } from '../src/modules/background.js';\n\ndescribe('inlineBackgroundImages', () => {\n let source, clone;\n beforeEach(() => {\n source = document.createElement('div');\n clone = document.createElement('div');\n document.body.appendChild(source);\n document.body.appendChild(clone);\n });\n afterEach(() => {\n document.body.removeChild(source);\n document.body.removeChild(clone);\n });\n\n it('does not fail if there is no background-image', async () => {\n source.style.background = 'none';\n await expect(inlineBackgroundImages(source, clone, new WeakMap())).resolves.toBeUndefined();\n });\n\n it('processes a valid background-image', async () => {\n source.style.backgroundImage = 'url(\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/w8AAn8B9p6Q2wAAAABJRU5ErkJggg==\")';\n await expect(inlineBackgroundImages(source, clone, new WeakMap())).resolves.toBeUndefined();\n });\n});\n"], ["/snapdom/__tests__/snapdom.precache.test.js", "import { describe, test, expect, afterEach, afterAll, beforeEach } from 'vitest';\nimport { snapdom, preCache } from '../src/index';\nimport { cache } from '../src/core/cache';\n\nconst sizes = [\n { width: 200, height: 100, label: 'Small element (200x100)' },\n { width: 400, height: 300, label: 'Modal size (400x300)' },\n { width: 1200, height: 800, label: 'Page view (1200x800)' },\n];\nlet results = [];\nfunction createContainer(size) {\n const container = document.createElement('div');\n container.style.width = `${size.width}px`;\n container.style.height = `${size.height}px`;\n container.style.padding = '20px';\n container.style.overflow = 'auto';\n container.style.background = 'white';\n container.style.border = '2px solid black';\n container.style.fontFamily = 'Arial, sans-serif';\n container.style.color = '#333';\n container.style.position = 'relative';\n\n const grid = document.createElement('div');\n grid.style.display = 'grid';\n grid.style.gridTemplateColumns = 'repeat(auto-fill, minmax(120px, 1fr))';\n grid.style.gap = '10px';\n\n const cardCount = Math.floor((size.width * size.height) / 20000);\n for (let i = 0; i < cardCount; i++) {\n const card = document.createElement('div');\n card.style.padding = '10px';\n card.style.borderRadius = '8px';\n card.style.background = i % 2 === 0 ? '#f0f0f0' : '#e0eaff';\n card.style.boxShadow = '0 2px 5px rgba(0,0,0,0.1)';\n card.style.display = 'flex';\n card.style.flexDirection = 'column';\n card.style.alignItems = 'center';\n\n const title = document.createElement('h3');\n title.textContent = `Card ${i + 1}`;\n title.style.margin = '0 0 10px 0';\n title.style.fontSize = '14px';\n\n const icon = document.createElement('div');\n icon.style.width = '30px';\n icon.style.height = '30px';\n icon.style.borderRadius = '50%';\n icon.style.background = i % 2 === 0 ? 'red' : 'blue';\n icon.style.marginBottom = '10px';\n\n const text = document.createElement('p');\n text.textContent = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit.';\n text.style.fontSize = '12px';\n text.style.textAlign = 'center';\n\n card.appendChild(icon);\n card.appendChild(title);\n card.appendChild(text);\n grid.appendChild(card);\n }\n\n container.appendChild(grid);\n return container;\n}\n\nfunction waitForNextFrame() {\n return new Promise((resolve) => {\n requestAnimationFrame(() => setTimeout(resolve, 0));\n });\n}\nbeforeEach(() => {\n cache.image.clear();\n cache.background.clear();\n cache.resource.clear();\n});\nafterAll(() => {\n for (const r of results) {\n console.log(r.log);\n }\n results = [];\n \n document.body.innerHTML = '';\n});\nfor (const size of sizes) {\n describe(`snapDOM performance test (may not be accurate) - ${size.label}`, () => {\n let container;\n\n afterEach( () => {\n container?.remove();\n container = null;\n document.body.innerHTML = '';\n \n });\n\n test('without preCache', async () => {\n container = createContainer(size);\n document.body.appendChild(container);\n await waitForNextFrame();\n\n const start = performance.now();\n await snapdom.toRaw(container, { compress: true });\n const end = performance.now();\n\n let log = `[${size.label}] WITHOUT preCache: capture ${(end - start).toFixed(2)}ms`;\n results.push({ log });\n expect(true).toBe(true);\n \n });\n \n test('with preCache', async () => {\n container = createContainer(size);\n document.body.appendChild(container);\n await waitForNextFrame();\n\n const startPre = performance.now();\n await preCache();\n const endPre = performance.now();\n \n const startCap = performance.now();\n await snapdom.toRaw(container, { compress: true });\n const endCap = performance.now();\n \n const precacheTime = (endPre - startPre).toFixed(2);\n const captureTime = (endCap - startCap).toFixed(2);\n \n let log = `[${size.label}] WITH preCache: capture ${captureTime}ms (preCache ${precacheTime}ms) `;\n\n results.push({ log });\n \n expect(true).toBe(true);\n });\n\n });\n}\n"], ["/snapdom/__tests__/fonts.module.test.js", "import { describe, it, expect, beforeEach, vi } from 'vitest';\nimport { iconToImage, embedCustomFonts } from '../src/modules/fonts.js';\nimport { cache } from '../src/core/cache.js';\n\n// Utilidad para limpiar estilos y links antes de cada test\nfunction cleanFontEnvironment() {\n document.querySelectorAll('style,link[rel=\"stylesheet\"]').forEach(s => s.remove());\n}\n\nfunction addStyleTag(css) {\n const style = document.createElement('style');\n style.setAttribute('data-test-style', 'true');\n style.textContent = css;\n document.head.appendChild(style);\n return style;\n}\n\ndescribe('iconToImage', () => {\n it('genera un dataURL para un carácter unicode', async () => {\n const url = await iconToImage('★', 'Arial', 'bold', 32, '#000');\n expect(url.startsWith('data:image/')).toBe(true);\n });\n\n it('maneja diferentes pesos y colores de fuente', async () => {\n const url = await iconToImage('★', 'Arial', 700, 40, '#ff0000');\n expect(url.startsWith('data:image/')).toBe(true);\n });\n\n it('usa valores por defecto si no hay métricas', async () => {\n const orig = HTMLCanvasElement.prototype.getContext;\n HTMLCanvasElement.prototype.getContext = function() {\n return {\n font: '',\n scale: vi.fn(),\n textAlign: '',\n textBaseline: '',\n fillStyle: '',\n fillText: vi.fn(),\n measureText: () => ({ width: 10 })\n };\n };\n const url = await iconToImage('★', 'Arial', 'bold', 32, '#000');\n expect(url.startsWith('data:image/')).toBe(true);\n HTMLCanvasElement.prototype.getContext = orig;\n });\n});\n\ndescribe('embedCustomFonts', () => {\n beforeEach(() => {\n cache.reset();\n cache.font.clear();\n cache.resource.clear();\n cleanFontEnvironment();\n vi.restoreAllMocks();\n });\n\n it('conserva @font-face con solo local() en src', async () => {\n const style = addStyleTag(`\n @font-face {\n font-family: OnlyLocal;\n src: local(\"Arial\");\n font-style: normal;\n font-weight: normal;\n }\n `);\n\n const css = await embedCustomFonts();\n expect(css).toMatch(/font-family:\\s*OnlyLocal/);\n expect(css).toMatch(/src:\\s*local\\([\"']Arial[\"']\\)/);\n document.head.removeChild(style);\n });\n\n it('conserva @font-face con local() y sin url()', async () => {\n const style = addStyleTag(`\n @font-face {\n font-family: LocalFont;\n src: local('MyFont'), local('FallbackFont');\n font-style: italic;\n font-weight: bold;\n }\n `);\n\n const css = await embedCustomFonts();\n expect(css).toMatch(/font-family:\\s*LocalFont/);\n expect(css).toMatch(/src:\\s*local\\(['\"]MyFont['\"]\\),\\s*local\\(['\"]FallbackFont['\"]\\)/);\n expect(css).toMatch(/font-style:\\s*italic/);\n document.head.removeChild(style);\n });\n});\n"], ["/snapdom/__tests__/preCache.api.test.js", "import { describe, it, expect, beforeEach } from 'vitest';\nimport { preCache } from '../src/api/preCache.js';\nimport { cache } from '../src/core/cache.js';\n\ndescribe('preCache', () => {\n beforeEach(() => {\n cache.reset()\n });\n\n it('pre-caches images and backgrounds', async () => {\n const el = document.createElement('div');\n const img = document.createElement('img');\n img.src = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/w8AAn8B9p6Q2wAAAABJRU5ErkJggg==';\n el.appendChild(img);\n document.body.appendChild(el);\n await preCache(el);\n expect(cache.image.has(img.src)).toBe(true);\n document.body.removeChild(el);\n });\n\n it('should handle preCache with embedFonts false', async () => {\n const el = document.createElement('div');\n await expect(preCache(el, { embedFonts: false })).resolves.toBeUndefined();\n });\n\n it('should handle preCache with images that fail to load', async () => {\n const el = document.createElement('div');\n const img = document.createElement('img');\n img.src = 'invalid-url.png';\n el.appendChild(img);\n await expect(preCache(el)).resolves.toBeUndefined();\n });\n\n it('should handle preCache with backgrounds that fail to load', async () => {\n const el = document.createElement('div');\n el.style.backgroundImage = 'url(invalid-url.png)';\n document.body.appendChild(el);\n await expect(preCache(el)).resolves.toBeUndefined();\n document.body.removeChild(el);\n });\n\n it('limpia los caches y retorna si reset=true', async () => {\n // Prellenar los caches\n cache.snapshotKey.set('foo', 'bar');\n cache.preStyleMap.set('foo', 'bar');\n cache.preNodeMap.set('foo', 'bar');\n await preCache(document, { reset: true });\n expect(cache.snapshotKey.size).toBe(0);\n expect(cache.preStyleMap.size).toBe(0);\n expect(cache.preNodeMap.size).toBe(0);\n });\n\n it('procesa múltiples backgrounds en un solo elemento', async () => {\n const el = document.createElement('div');\n el.style.backgroundImage = 'url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/w8AAn8B9p6Q2wAAAABJRU5ErkJggg==), url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/w8AAn8B9p6Q2wAAAABJRU5ErkJggg==)';\n document.body.appendChild(el);\n await preCache(el);\n // No assertion estricta porque depende de helpers, pero no debe lanzar error\n document.body.removeChild(el);\n });\n\n});\n"], ["/snapdom/__tests__/snapdom.vs.htm2canvas.outputfilesize.test.js", "import { describe, it, beforeEach, afterEach, afterAll } from 'vitest';\nimport { snapdom } from '../src/index';\n//ok\n\ndescribe('Output file size snapdom vs html2canvas (cdn with averaging)', () => {\n let container;\n let html2canvas;\n let report;\n\n beforeEach(async () => {\n container = document.createElement('div');\n container.style.width = '400px';\n container.style.height = '300px';\n container.style.background = 'linear-gradient(to right, red, blue)';\n container.innerHTML = '

Hello Benchmark

Testing multiple runs...

';\n document.body.appendChild(container);\n\n if (!html2canvas) {\n // Cargar html2canvas desde CDN\n await new Promise((resolve, reject) => {\n const script = document.createElement('script');\n script.src = 'https://cdn.jsdelivr.net/npm/html2canvas@1.4.1/dist/html2canvas.min.js';\n script.onload = () => {\n html2canvas = window.html2canvas;\n resolve();\n };\n script.onerror = reject;\n document.head.appendChild(script);\n });\n }\n });\n\n afterEach(() => {\n document.body.removeChild(container);\n });\n\n afterAll(() => {\n console.log(report)\n })\n\n it('snapdom output file size should be smaller than html2canvas', async () => {\n \n // SnapDOM capture\n const snapdomDataURL = await snapdom.toRaw(container, {compress: true});\n const snapdomSizeKB = (snapdomDataURL.length * 3 / 4) / 1024; // Base64 to bytes approx\n \n // html2canvas capture\n const canvas = await html2canvas(container, { logging: false });\n const html2canvasDataURL = await canvas.toDataURL();\n const html2canvasSizeKB = (html2canvasDataURL.length * 3 / 4) / 1024; // Base64 to bytes approx\n \n const differencePercent = ((html2canvasSizeKB - snapdomSizeKB) / html2canvasSizeKB) * 100;\n\n report =`snapDom Captured file size is ${differencePercent.toFixed(2)}% smaller compared to html2canvas (${snapdomSizeKB.toFixed(2)} KB vs. ${html2canvasSizeKB.toFixed(2)} KB)`\n\n})\n\n})\n"], ["/snapdom/__tests__/snapdom.api.test.js", "import { describe, it, expect, vi } from 'vitest';\nimport { snapdom } from '../src/api/snapdom.js';\n\ndescribe('snapdom API (direct)', () => {\n it('throws on null element', async () => {\n await expect(snapdom(null)).rejects.toThrow();\n });\n\n it('snapdom.capture returns export methods', async () => {\n const el = document.createElement('div');\n el.style.width = '100px';\n el.style.height = '50px';\n document.body.appendChild(el);\n const result = await snapdom.capture(el);\n expect(result).toHaveProperty('toRaw');\n expect(result).toHaveProperty('toImg');\n expect(result).toHaveProperty('download');\n document.body.removeChild(el);\n });\n\n it('snapdom.toRaw, toImg, toCanvas, toBlob, toPng, toJpg, toWebp, download', async () => {\n const el = document.createElement('div');\n el.style.width = '100px';\n el.style.height = '50px';\n document.body.appendChild(el);\n await snapdom.toRaw(el);\n await snapdom.toImg(el);\n await snapdom.toCanvas(el);\n await snapdom.toBlob(el);\n await snapdom.toPng(el);\n await snapdom.toJpg(el);\n await snapdom.toWebp(el);\n await snapdom.download(el, { format: 'png', filename: 'test' });\n document.body.removeChild(el);\n });\n\n it('cubre rama Safari en toImg', async () => {\n vi.resetModules();\n vi.mock('../utils/helpers.js', async () => {\n const actual = await vi.importActual('../utils/helpers.js');\n return { ...actual, isSafari: true };\n });\n const { snapdom } = await import('../src/api/snapdom.js');\n const el = document.createElement('div');\n el.style.width = '10px';\n el.style.height = '10px';\n document.body.appendChild(el);\n // Forzar un SVG dataURL simple\n const img = new Image();\n img.width = 10;\n img.height = 10;\n img.decode = () => Promise.resolve();\n globalThis.Image = function() { return img; };\n const res = await snapdom.capture(el);\n await res.toImg();\n document.body.removeChild(el);\n vi.resetModules();\n });\n\n it('cubre rama de download SVG', async () => {\n const el = document.createElement('div');\n el.style.width = '10px';\n el.style.height = '10px';\n document.body.appendChild(el);\n // Mock a.click y URL.createObjectURL\n const a = document.createElement('a');\n document.body.appendChild(a);\n const origCreate = URL.createObjectURL;\n URL.createObjectURL = () => 'blob:url';\n const origClick = a.click;\n a.click = () => {};\n HTMLAnchorElement.prototype.click = () => {};\n const { snapdom } = await import('../src/api/snapdom.js');\n await snapdom.download(el, { format: 'svg', filename: 'testsvg' });\n URL.createObjectURL = origCreate;\n a.click = origClick;\n document.body.removeChild(a);\n document.body.removeChild(el);\n });\n\n it('snapdom.toBlob supports type options ', async () => {\n const el = document.createElement('div');\n el.style.width = '50px';\n el.style.height = '30px';\n document.body.appendChild(el);\n\n const result = await snapdom.capture(el);\n\n const pngBlob = await result.toBlob({ type: 'png' });\n expect(pngBlob).toBeInstanceOf(Blob);\n expect(pngBlob.type).toBe('image/png');\n\n const jpgBlob = await result.toBlob({ type: 'jpeg', quality: 0.8 });\n expect(jpgBlob).toBeInstanceOf(Blob);\n expect(jpgBlob.type).toBe('image/jpeg');\n\n const webpBlob = await result.toBlob({ type: 'webp', quality: 0.9 });\n expect(webpBlob).toBeInstanceOf(Blob);\n expect(webpBlob.type).toBe('image/webp');\n\n // default fallback\n const svgBlob = await result.toBlob();\n expect(svgBlob).toBeInstanceOf(Blob);\n expect(svgBlob.type).toBe('image/svg+xml');\n\n document.body.removeChild(el);\n});\n\nit('toPng, toJpg, toWebp return HTMLImageElement with URLs', async () => {\n const el = document.createElement('div');\n el.style.width = '60px';\n el.style.height = '40px';\n document.body.appendChild(el);\n const snap = await snapdom.capture(el);\n\n const pngImg = await snap.toPng();\n expect(pngImg).toBeInstanceOf(HTMLImageElement);\n expect(typeof pngImg.src).toBe('string');\nexpect(pngImg.src.startsWith('data:image/png')).toBe(true);\n\n const jpgImg = await snap.toJpg();\n expect(jpgImg).toBeInstanceOf(HTMLImageElement);\n expect(typeof jpgImg.src).toBe('string');\nexpect(jpgImg.src.startsWith('data:image/jpeg')).toBe(true);\n\n const webpImg = await snap.toWebp();\n expect(webpImg).toBeInstanceOf(HTMLImageElement);\n expect(typeof webpImg.src).toBe('string');\nexpect(webpImg.src.startsWith('data:image/webp')).toBe(true);\n document.body.removeChild(el);\n});\n\nit('snapdom should support exclude option to filter out elements by CSS selectors', async () => {\n const el = document.createElement('div');\n el.innerHTML = `\n

Title

\n
Should be excluded
\n
Private data
\n

This should remain

\n `;\n document.body.appendChild(el);\n \n const result = await snapdom(el, { exclude: ['.exclude-me', '[data-private]'] });\n \n const svg = result.toRaw();\n const decoded = decodeURIComponent(svg.split(\",\")[1]);\n expect(decoded).not.toContain('Should be excluded');\n expect(decoded).not.toContain('Private data');\n expect(decoded).toContain('Title');\n expect(decoded).toContain('This should remain');\n});\n\nit('snapdom should support filter option to exclude elements with custom logic', async () => {\n const el = document.createElement('div');\n el.innerHTML = `\n
Level 1\n
Level 2\n
Level 3
\n
\n
\n `;\n document.body.appendChild(el);\n const result = await snapdom(el, { \n filter: (element) => !element.classList.contains('level-3')\n });\n \n const svg = result.toRaw();\n const decoded = decodeURIComponent(svg.split(\",\")[1]);\n expect(decoded).toContain('Level 1');\n expect(decoded).toContain('Level 2');\n expect(decoded).not.toContain('Level 3');\n});\n\nit('snapdom should support combining exclude and filter options', async () => {\n const el = document.createElement('div');\n el.innerHTML = `\n
Exclude by selector
\n
Exclude by filter
\n
Keep this content
\n `;\n document.body.appendChild(el);\n\n const result = await snapdom(el, { \n exclude: ['.exclude-by-selector'],\n filter: (element) => !element.classList.contains('exclude-by-filter')\n });\n \n \n const svg = result.toRaw();\n const decoded = decodeURIComponent(svg.split(\",\")[1]);\n expect(decoded).not.toContain('Exclude by selector');\n expect(decoded).not.toContain('Exclude by filter');\n expect(decoded).toContain('Keep this content');\n});\n\n});\n"], ["/snapdom/__tests__/capture.core.test.js", "import { describe, it, expect, vi } from 'vitest';\nimport { captureDOM } from '../src/core/capture.js';\n\ndescribe('captureDOM edge cases', () => {\n it('throws for unsupported element (unknown nodeType)', async () => {\n // Simulate a node with an invalid nodeType\n const fakeNode = { nodeType: 999 };\n await expect(captureDOM(fakeNode)).rejects.toThrow();\n });\n\n it('throws if element is null', async () => {\n await expect(captureDOM(null)).rejects.toThrow();\n });\n\n it('throws error if getBoundingClientRect fails', async () => {\n const el = document.createElement('div');\n vi.spyOn(el, 'getBoundingClientRect').mockImplementation(() => { throw new Error('fail'); });\n await expect(captureDOM(el)).rejects.toThrow('fail');\n });\n});\n\ndescribe('captureDOM functional', () => {\n it('captures a simple div and returns an SVG dataURL', async () => {\n const el = document.createElement('div');\n el.textContent = 'test';\n const url = await captureDOM(el);\n expect(url.startsWith('data:image/svg+xml')).toBe(true);\n });\n\n it('supports scale and width/height options', async () => {\n const el = document.createElement('div');\n el.style.width = '100px';\n el.style.height = '50px';\n await captureDOM(el, { scale: 2 });\n await captureDOM(el, { width: 200 });\n await captureDOM(el, { height: 100 });\n });\n\n it('supports fast=false', async () => {\n const el = document.createElement('div');\n await captureDOM(el, { fast: false });\n });\n\n it('supports embedFonts', async () => {\n const el = document.createElement('div');\n await captureDOM(el, { embedFonts: true });\n });\n});\n"], ["/snapdom/__tests__/clone.core.test.js", "import { describe, it, expect, vi } from 'vitest';\nimport { deepClone } from '../src/core/clone.js';\n\ndescribe('deepClone', () => {\n it('clones a simple div', () => {\n const el = document.createElement('div');\n el.textContent = 'hello';\n const styleMap = new Map();\n const styleCache = new WeakMap();\n const nodeMap = new Map();\n const clone = deepClone(el, styleMap, styleCache, nodeMap, false);\n expect(clone).not.toBe(el);\n expect(clone.textContent).toBe('hello');\n });\n\n it('clones canvas as an image', () => {\n const canvas = document.createElement('canvas');\n canvas.width = 10;\n canvas.height = 10;\n const ctx = canvas.getContext('2d');\n ctx.fillStyle = 'red';\n ctx.fillRect(0,0,10,10);\n const styleMap = new Map();\n const styleCache = new WeakMap();\n const nodeMap = new Map();\n const clone = deepClone(canvas, styleMap, styleCache, nodeMap, false);\n expect(clone.tagName).toBe('IMG');\n expect(clone.src.startsWith('data:image/')).toBe(true);\n });\n\n it('deepClone handles data-capture=\"exclude\"', () => {\n const el = document.createElement('div');\n el.setAttribute('data-capture', 'exclude');\n const clone = deepClone(el, true, {});\n expect(clone).not.toBeNull();\n });\n\n it('deepClone handles data-capture=\"placeholder\"', () => {\n const el = document.createElement('div');\n el.setAttribute('data-capture', 'placeholder');\n el.setAttribute('data-placeholder-text', 'Placeholder!');\n const clone = deepClone(el, true, {});\n expect(clone.textContent).toContain('Placeholder!');\n });\n\n it('deepClone handles iframe', () => {\n const iframe = document.createElement('iframe');\n iframe.width = 100;\n iframe.height = 50;\n const clone = deepClone(iframe, true, {});\n expect(clone.tagName).toBe('DIV');\n });\n\n it('deepClone handles input, textarea, select', () => {\n const input = document.createElement('input');\n input.value = 'foo';\n input.checked = true;\n const textarea = document.createElement('textarea');\n textarea.value = 'bar';\n const select = document.createElement('select');\n const opt = document.createElement('option');\n opt.value = 'baz';\n select.appendChild(opt);\n select.value = 'baz';\n [input, textarea, select].forEach(el => {\n const clone = deepClone(el, true, {});\n expect(clone.value).toBe(el.value);\n });\n });\n\n it('deepClone handles shadow DOM', () => {\n const el = document.createElement('div');\n const shadow = el.attachShadow({mode:'open'});\n const span = document.createElement('span');\n span.textContent = 'shadow';\n shadow.appendChild(span);\n const clone = deepClone(el, true, {});\n expect(clone).not.toBeNull();\n });\n});\n\ndescribe('deepClone edge cases', () => {\n it('clones unsupported node (Comment) as a new Comment', () => {\n const fake = document.createComment('not supported');\n const result = deepClone(fake, true, {});\n expect(result.nodeType).toBe(Node.COMMENT_NODE);\n expect(result.textContent).toBe('not supported');\n expect(result).not.toBe(fake); // Es un clon, no el mismo objeto\n });\n it('clones attributes and children', () => {\n const el = document.createElement('div');\n el.setAttribute('data-test', '1');\n const result = deepClone(el, true, {});\n expect(result.getAttribute('data-test')).toBe('1');\n });\n});\n"], ["/snapdom/__tests__/styles.module.test.js", "import { describe, it, expect } from 'vitest';\nimport { inlineAllStyles } from '../src/modules/styles.js';\nimport { cache } from '../src/core/cache.js';\n\ndescribe('inlineAllStyles', () => {\n it('adds a style key to the styleMap', () => {\n const el = document.createElement('div');\n const clone = document.createElement('div');\n inlineAllStyles(el, clone, false);\n expect(cache.preStyleMap.has(clone)).toBe(true);\n });\n});"], ["/snapdom/__tests__/prepare.core.test.js", "import { describe, it, expect, vi } from 'vitest';\nimport { prepareClone } from '../src/core/prepare.js';\n\ndescribe('prepareClone', () => {\n it('prepares a clone of a div', async () => {\n const el = document.createElement('div');\n el.textContent = 'test';\n const { clone, classCSS } = await prepareClone(el);\n expect(clone).not.toBeNull();\n expect(typeof classCSS).toBe('string');\n });\n});\n\ndescribe('prepareClone edge cases', () => {\n it('throws for null node', async () => {\n await expect(prepareClone(null)).rejects.toThrow();\n });\n it('returns a comment clone for unsupported node', async () => {\n const fake = document.createComment('not supported');\n const result = await prepareClone(fake);\n expect(result.clone.nodeType).toBe(Node.COMMENT_NODE);\n });\n it('handles error in internal logic', async () => {\n const el = document.createElement('div');\n vi.spyOn(el, 'cloneNode').mockImplementation(() => { throw new Error('fail'); });\n await expect(prepareClone(el)).rejects.toThrow('fail');\n });\n it('clones attributes and children', async () => {\n const el = document.createElement('div');\n el.setAttribute('data-test', '1');\n const result = await prepareClone(el);\n expect(result.clone.getAttribute('data-test')).toBe('1');\n });\n});\n"], ["/snapdom/__tests__/snapdom.advance.test.js", "import { describe, it, expect, beforeEach, afterEach } from 'vitest';\nimport { snapdom } from '../src/index';\n\ndescribe('snapdom advanced tests', () => {\n let testElement;\n\n beforeEach(() => {\n testElement = document.createElement('div');\n testElement.style.width = '100px';\n testElement.style.height = '50px';\n testElement.innerHTML = '

Hello World

';\n document.body.appendChild(testElement);\n });\n\n afterEach(() => {\n document.body.removeChild(testElement);\n });\n\n it('should generate different SVGs for different scales', async () => {\n const svg1 = await snapdom.toImg(testElement, { scale: 1 });\n const svg2 = await snapdom.toImg(testElement, { scale: 2 });\n expect(svg1).not.toBe(svg2);\n });\n\n it('captured SVG should contain inner text content', async () => {\n const svgDataUrl = await snapdom.toRaw(testElement);\n const svgText = decodeURIComponent(svgDataUrl.split(',')[1]);\n expect(svgText).toContain('Hello World');\n });\n\n it('should throw an error if element is null', async () => {\n await expect(() => snapdom.toRaw(null)).rejects.toThrow();\n });\n\n it('should generate SVG with correct attributes', async () => {\n const svgDataUrl = await snapdom.toRaw(testElement);\n const svgText = decodeURIComponent(svgDataUrl.split(',')[1]);\n const parser = new DOMParser();\n const doc = parser.parseFromString(svgText, 'image/svg+xml');\n const svg = doc.querySelector('svg');\n\n expect(svg).not.toBeNull();\n expect(svg.getAttribute('width')).toBe('100');\n expect(svg.getAttribute('height')).toBe('50');\n expect(svg.getAttribute('viewBox')).toBe('0 0 100 50');\n });\n\n it('snapdom.toBlob should contain valid SVG content', async () => {\n const blob = await snapdom.toBlob(testElement);\n const text = await blob.text();\n expect(text).toContain('');\n });\n\n it('should replace iframes with fallback visuals', async () => {\n const iframe = document.createElement('iframe');\n iframe.style.width = '200px';\n iframe.style.height = '100px';\n testElement.appendChild(iframe);\n\n const svgDataUrl = await snapdom.toRaw(testElement);\n const svgText = decodeURIComponent(svgDataUrl.split(',')[1]);\n\n const parser = new DOMParser();\n const doc = parser.parseFromString(svgText, 'image/svg+xml');\n\n // No debe haber iframes en el SVG\n expect(doc.querySelectorAll('iframe').length).toBe(0);\n\n // Buscamos divs con estilo inline que contengan repeating-linear-gradient\n const fallbackDivs = Array.from(doc.querySelectorAll('div')).filter(div => {\n const styleAttr = div.getAttribute('style') || '';\n return styleAttr.includes('repeating-linear-gradient');\n });\n\n expect(fallbackDivs.length).toBeGreaterThan(0);\n});\n\n \n});\n"], ["/snapdom/src/index.browser.js", "/**\n * Entry point for snapDOM library exports.\n *\n * @file index.browser.js\n */\n\nimport { snapdom } from './api/snapdom.js';\nimport { preCache } from './api/preCache.js';\n\nif (typeof window !== 'undefined') {\n window.snapdom = snapdom;\n window.preCache = preCache;\n}"], ["/snapdom/__tests__/snapdom.test.js", "import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';\nimport { snapdom } from '../src/index';\n\ndescribe('snapdom API', () => {\n let testElement;\n\n beforeEach(() => {\n testElement = document.createElement('div');\n testElement.style.width = '100px';\n testElement.style.height = '50px';\n document.body.appendChild(testElement );\n });\n\n afterEach(() => {\n document.body.removeChild(testElement );\n });\n\n describe('snapdom.toRaw', () => {\n it('should return a SVG data URL', async () => {\n const result = await snapdom.toRaw(testElement );\n expect(result).toMatch(/^data:image\\/svg\\+xml/);\n });\n });\n\n describe('snapdom', () => {\n it('toImg should return an HTMLImageElement', async () => {\n \n const img = await snapdom.toImg(testElement );\n expect(img).toBeInstanceOf(HTMLImageElement);\n expect(img.src).toMatch(/^data:image\\/svg\\+xml/);\n \n });\n\n it('toCanvas should return a HTMLCanvasElement', async () => {\n // const decodeMock = vi.spyOn(window.Image.prototype, 'decode').mockResolvedValue();\n const canvas = await snapdom.toCanvas(testElement );\n expect(canvas).toBeInstanceOf(HTMLCanvasElement);\n // decodeMock.mockRestore();\n });\n\n it('toPng should return an HTMLImageElement with PNG data URL', async () => {\n // const decodeMock = vi.spyOn(window.Image.prototype, 'decode').mockResolvedValue();\n const img = await snapdom.toPng(testElement );\n expect(img).toBeInstanceOf(HTMLImageElement);\n expect(img.src).toMatch(/^data:image\\/png/);\n // decodeMock.mockRestore();\n });\n\n it('toJpg should return an HTMLImageElement with JPEG data URL', async () => {\n // const decodeMock = vi.spyOn(window.Image.prototype, 'decode').mockResolvedValue();\n const img = await snapdom.toJpg(testElement );\n expect(img).toBeInstanceOf(HTMLImageElement);\n expect(img.src).toMatch(/^data:image\\/jpeg/);\n // decodeMock.mockRestore();\n });\n\n it('toWebp should return an HTMLImageElement with WebP data URL', async () => {\n // const decodeMock = vi.spyOn(window.Image.prototype, 'decode').mockResolvedValue();\n const img = await snapdom.toWebp(testElement );\n expect(img).toBeInstanceOf(HTMLImageElement);\n expect(img.src).toMatch(/^data:image\\/webp/);\n // decodeMock.mockRestore();\n });\n\n it('toBlob should return a Blob of type image/svg+xml', async () => {\n const blob = await snapdom.toBlob(testElement );\n expect(blob).toBeInstanceOf(Blob);\n expect(blob.type).toBe('image/svg+xml');\n });\n });\n});\n"], ["/snapdom/__tests__/snapdom.vs.modernscreenshot.outputfilesize.test.js", "import { describe, it, beforeEach, afterEach, afterAll } from 'vitest';\nimport { domToDataUrl} from 'https://unpkg.com/modern-screenshot';\nimport { snapdom } from '../src/index';\n//ok\n\ndescribe('Output file size snapdom vs modern-screeenshot (cdn with averaging)', () => {\n let container;\n\n let report;\n\n beforeEach(async () => {\n container = document.createElement('div');\n container.style.width = '400px';\n container.style.height = '300px';\n container.style.background = 'linear-gradient(to right, red, blue)';\n container.innerHTML = '

Hello Benchmark

Testing multiple runs...

';\n document.body.appendChild(container);\n });\n\n afterEach(() => {\n document.body.removeChild(container);\n });\n\n afterAll(() => {\n console.log(report)\n })\n\n it('snapdom output file size should be smaller than modern-screenshot', async () => {\n \n // SnapDOM capture\n const snapdomDataURL = await snapdom.toRaw(container, {compress: true});\n const snapdomSizeKB = (snapdomDataURL.length * 3 / 4) / 1024; // Base64 to bytes approx\n \n // domToDataUrl capture\n const domToDataUrlDataURL = await domToDataUrl(container);\n const domToDataUrlSizeKB = (domToDataUrlDataURL.length * 3 / 4) / 1024; // Base64 to bytes approx\n \n const differencePercent = ((domToDataUrlSizeKB - snapdomSizeKB) / domToDataUrlSizeKB) * 100;\n\n report =`snapdom captured file size is ${differencePercent.toFixed(2)}% smaller compared to modern-screenshot (${snapdomSizeKB.toFixed(2)} KB vs. ${domToDataUrlSizeKB.toFixed(2)} KB)`\n\n})\n\n})\n"], ["/snapdom/__tests__/images.module.test.js", "import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';\nimport { inlineImages } from '../src/modules/images.js';\n\ndescribe('inlineImages', () => {\n let container;\n beforeEach(() => {\n container = document.createElement('div');\n document.body.appendChild(container);\n });\n afterEach(() => {\n document.body.removeChild(container);\n });\n\n it('converts to dataURL if the image loads', async () => {\n const img = document.createElement('img');\n img.src = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/w8AAn8B9p6Q2wAAAABJRU5ErkJggg==';\n container.appendChild(img);\n await inlineImages(container);\n expect(img.src.startsWith('data:image/')).toBe(true);\n });\n\n it('replaces with a fallback if the image fails', async () => {\n const img = document.createElement('img');\n img.src = 'invalid-url.png';\n container.appendChild(img);\n await inlineImages(container);\n expect(container.querySelector('div')).not.toBeNull();\n expect(container.querySelector('img')).toBeNull();\n });\n});\n"], ["/snapdom/__tests__/snapdom.backgroundColor.test.js", "import { describe, it, expect, beforeEach, afterEach } from 'vitest';\nimport { snapdom } from '../src/index';\n\ndescribe('snapdom.toJpg backgroundColor option', () => {\n let container;\n\n beforeEach(() => {\n container = document.createElement('div');\n container.style.width = '100px';\n container.style.height = '100px';\n container.style.background = 'transparent';\n document.body.appendChild(container);\n });\n\n it('applies white background by default', async () => {\n const img = await snapdom.toJpg(container );\n const canvas = document.createElement('canvas');\n canvas.width = img.width;\n canvas.height = img.height;\n const ctx = canvas.getContext('2d');\n ctx.drawImage(img, 0, 0);\n const pixel = ctx.getImageData(0, 0, 1, 1).data;\n // JPEG compresses, but for a solid color it should be near white\n expect(pixel[0]).toBeGreaterThan(240);\n expect(pixel[1]).toBeGreaterThan(240);\n expect(pixel[2]).toBeGreaterThan(240);\n });\n\n it('applies custom background color', async () => {\n const img = await snapdom.toJpg(container, { backgroundColor: '#00ff00' });\n const canvas = document.createElement('canvas');\n canvas.width = img.width;\n canvas.height = img.height;\n const ctx = canvas.getContext('2d');\n ctx.drawImage(img, 0, 0);\n const pixel = ctx.getImageData(0, 0, 1, 1).data;\n // Green check (JPEG lossy, so check near values)\n expect(pixel[0]).toBeLessThan(30); // red\n expect(pixel[1]).toBeGreaterThan(200); // green\n expect(pixel[2]).toBeLessThan(30); // blue\n });\n});\n"], ["/snapdom/__tests__/cssTools.utils.test.js", "import { describe, it, expect } from 'vitest';\nimport { getStyleKey, collectUsedTagNames, getDefaultStyleForTag } from '../src/utils/cssTools.js';\n\ndescribe('getStyleKey', () => {\n it('generates a non-empty style key', () => {\n const snapshot = { color: 'red', 'font-size': '12px' };\n const key = getStyleKey(snapshot, 'div');\n expect(typeof key).toBe('string');\n expect(key.length).toBeGreaterThan(0);\n });\n\n it('getStyleKey works with compress true', () => {\n const snapshot = { color: 'red', 'font-size': '12px' };\n const key = getStyleKey(snapshot, 'div', true);\n expect(typeof key).toBe('string');\n });\n});\n\ndescribe('collectUsedTagNames', () => {\n it('returns unique tag names', () => {\n const root = document.createElement('div');\n root.innerHTML = '

';\n const tags = collectUsedTagNames(root);\n expect(tags).toContain('div');\n expect(tags).toContain('span');\n expect(tags).toContain('p');\n });\n});\n\ndescribe('getDefaultStyleForTag', () => {\n it('returns a default style object', () => {\n const defaults = getDefaultStyleForTag('div');\n expect(typeof defaults).toBe('object');\n });\n\n it('getDefaultStyleForTag skips special tags', () => {\n expect(getDefaultStyleForTag('script')).toEqual({});\n });\n});\n"], ["/snapdom/src/index.js", "/**\n * Entry point for snapDOM library exports.\n *\n * @file index.js\n */\n\nexport { snapdom } from './api/snapdom.js';\nexport { preCache } from './api/preCache.js';\n\n"], ["/snapdom/vitest.config.js", "import { defineConfig } from 'vitest/config'\n\nexport default defineConfig({\n test: {\n browser: {\n enabled: true,\n provider: 'playwright',\n // https://vitest.dev/guide/browser/playwright\n instances: [\n { browser: 'chromium' },\n ],\n },\n coverage: {\n provider: 'v8', // o 'istanbul'\n include: [\n 'src/**/*.js', // Solo archivos JS dentro de src/\n ],\n },\n },\n})\n"], ["/snapdom/__tests__/snapdom.attributes.test.js", "import { describe, it, expect, beforeEach, afterEach } from 'vitest';\nimport { snapdom } from '../src/index';\n\ndescribe('snapdom capture attributes', () => {\n let container;\n\n beforeEach(() => {\n container = document.createElement('div');\n container.style.width = '300px';\n container.style.height = '150px';\n document.body.appendChild(container);\n });\n\n afterEach(() => {\n document.body.removeChild(container);\n });\n\n it('should exclude elements with data-capture=\"exclude\"', async () => {\n const excluded = document.createElement('div');\n excluded.setAttribute('data-capture', 'exclude');\n excluded.textContent = 'Should be excluded';\n container.appendChild(excluded);\n\n const svgDataUrl = await snapdom.toRaw(container);\n const svgText = decodeURIComponent(svgDataUrl.split(',')[1]);\n \n expect(svgText).not.toContain('Should be excluded');\n });\n\n it('should replace elements with data-capture=\"placeholder\" and show placeholder text', async () => {\n const placeholder = document.createElement('div');\n placeholder.setAttribute('data-capture', 'placeholder');\n placeholder.setAttribute('data-placeholder-text', 'Placeholder here');\n placeholder.textContent = 'Original text';\n container.appendChild(placeholder);\n\n const svgDataUrl = await snapdom.toRaw(container);\n const svgText = decodeURIComponent(svgDataUrl.split(',')[1]);\n \n expect(svgText).toContain('Placeholder here');\n expect(svgText).not.toContain('Original text');\n });\n});\n"], ["/snapdom/__tests__/index.browser.test.js", "import { it, expect } from 'vitest';\nimport * as snapdom from '../src/index.browser.js';\n\nit('should import the browser bundle without errors', () => {\n expect(snapdom).toBeDefined();\n});\n"]], "task_instance_info": {"created_time": "2025-08-21 00:01:54", "created_task_model": "DeepSeek-R1", "function_skeleton": "async function inlineBackgroundImages (source, clone, options = {}) {}", "code_description": "This code segment functions to: Traverse hierarchical elements to process and replace referenced image assets with embedded data equivalents, synchronize visual presentation properties between source and cloned structures, and maintain style consistency across nested components during duplication operations."}, "inference_content": {"inference_model": "DeepSeek-R1", "inference_result": "```javascript\n[TASK_BEGIN]\nconst sourceWalker = document.createTreeWalker(\n source,\n NodeFilter.SHOW_ELEMENT,\n null,\n false\n);\nconst cloneWalker = document.createTreeWalker(\n clone,\n NodeFilter.SHOW_ELEMENT,\n null,\n false\n);\n\nconst promises = [];\n\nwhile (true) {\n const sNode = sourceWalker.nextNode();\n const cNode = cloneWalker.nextNode();\n \n if (!sNode || !cNode) break;\n\n const bgImage = getStyle(sNode, 'background-image');\n const entries = splitBackgroundImage(bgImage);\n if (entries.length === 0) continue;\n\n const processEntries = async () => {\n const processedEntries = await Promise.all(\n entries.map(entry => inlineSingleBackgroundEntry(entry, options, cache))\n );\n cNode.style.backgroundImage = processedEntries.join(', ');\n };\n \n promises.push(processEntries());\n}\n\nawait Promise.all(promises);\n[TASK_END]\n```", "inference_time": "2025-08-21 00-03-03"}, "editdistance_info": {"edit_distance": 12.7479, "calculate_time": "2025-08-21 00:03:03", "true_code_clean": "async function inlineBackgroundImages(source, clone, options = {}) {\n const queue = [[source, clone]];\n const imageProps = [\n \"background-image\",\n \"mask\",\n \"mask-image\", \"-webkit-mask-image\",\n \"mask-source\", \"mask-box-image-source\",\n \"mask-border-source\",\n \"-webkit-mask-box-image-source\"\n ];\n while (queue.length) {\n const [srcNode, cloneNode] = queue.shift();\n const style = cache.preStyle.get(srcNode) || getStyle(srcNode);\n if (!cache.preStyle.has(srcNode)) cache.preStyle.set(srcNode, style);\n for (const prop of imageProps) {\n const val = style.getPropertyValue(prop);\n if (!val || val === \"none\") continue;\n const splits = splitBackgroundImage(val);\n const inlined = await Promise.all(\n splits.map(entry => inlineSingleBackgroundEntry(entry, options))\n );\n if (inlined.some(p => p && p !== \"none\" && !/^url\\(undefined/.test(p))) {\n cloneNode.style.setProperty(prop, inlined.join(\", \"));\n }\n }\n const bgColor = style.getPropertyValue(\"background-color\");\n if (\n bgColor &&\n bgColor !== \"transparent\" &&\n bgColor !== \"rgba(0, 0, 0, 0)\"\n ) {\n cloneNode.style.backgroundColor = bgColor;\n }\n const sChildren = Array.from(srcNode.children);\n const cChildren = Array.from(cloneNode.children);\n for (let i = 0; i < Math.min(sChildren.length, cChildren.length); i++) {\n queue.push([sChildren[i], cChildren[i]]);\n }\n }\n}", "predict_code_clean": "const sourceWalker = document.createTreeWalker(\n source,\n NodeFilter.SHOW_ELEMENT,\n null,\n false\n);\nconst cloneWalker = document.createTreeWalker(\n clone,\n NodeFilter.SHOW_ELEMENT,\n null,\n false\n);\nconst promises = [];\nwhile (true) {\n const sNode = sourceWalker.nextNode();\n const cNode = cloneWalker.nextNode();\n if (!sNode || !cNode) break;\n const bgImage = getStyle(sNode, 'background-image');\n const entries = splitBackgroundImage(bgImage);\n if (entries.length === 0) continue;\n const processEntries = async () => {\n const processedEntries = await Promise.all(\n entries.map(entry => inlineSingleBackgroundEntry(entry, options, cache))\n );\n cNode.style.backgroundImage = processedEntries.join(', ');\n };\n promises.push(processEntries());\n}\nawait Promise.all(promises);"}}