| 589 | |
| 590 | // Inspired by https://github.com/iconify/iconify/blob/main/packages/utils/src/svg/url.ts |
| 591 | function svgToDataURL(content: Buffer): string { |
| 592 | const stringContent = content.toString() |
| 593 | // If the SVG contains some text or HTML, any transformation is unsafe, and given that double quotes would then |
| 594 | // need to be escaped, the gain to use a data URI would be ridiculous if not negative |
| 595 | if ( |
| 596 | stringContent.includes('<text') || |
| 597 | stringContent.includes('<foreignObject') || |
| 598 | nestedQuotesRE.test(stringContent) |
| 599 | ) { |
| 600 | return `data:image/svg+xml;base64,${content.toString('base64')}` |
| 601 | } else { |
| 602 | return ( |
| 603 | 'data:image/svg+xml,' + |
| 604 | stringContent |
| 605 | .trim() |
| 606 | .replaceAll(/>\s+</g, '><') |
| 607 | .replaceAll('"', "'") |
| 608 | .replaceAll('%', '%25') |
| 609 | .replaceAll('#', '%23') |
| 610 | .replaceAll('<', '%3c') |
| 611 | .replaceAll('>', '%3e') |
| 612 | // Spaces are not valid in srcset it has some use cases |
| 613 | // it can make the uncompressed URI slightly higher than base64, but will compress way better |
| 614 | // https://github.com/vitejs/vite/pull/14643#issuecomment-1766288673 |
| 615 | .replaceAll(/\s+/g, '%20') |
| 616 | ) |
| 617 | } |
| 618 | } |