|
1 | 1 | 'use strict';
|
2 |
| -const htmlCommentRegex = require('html-comment-regex'); |
| 2 | +const parser = require('fast-xml-parser'); |
3 | 3 |
|
4 |
| -const isBinary = buffer => { |
5 |
| - const isBuffer = Buffer.isBuffer(buffer); |
| 4 | +const isSvg = input => { |
| 5 | + if (input === undefined || input === null) { |
| 6 | + return false; |
| 7 | + } |
6 | 8 |
|
7 |
| - for (let i = 0; i < 24; i++) { |
8 |
| - const characterCode = isBuffer ? buffer[i] : buffer.charCodeAt(i); |
| 9 | + input = input.toString().trim(); |
9 | 10 |
|
10 |
| - if (characterCode === 65533 || characterCode <= 8) { |
11 |
| - return true; |
12 |
| - } |
| 11 | + if (input.length === 0) { |
| 12 | + return false; |
13 | 13 | }
|
14 | 14 |
|
15 |
| - return false; |
16 |
| -}; |
17 |
| - |
18 |
| -const cleanEntities = svg => { |
19 |
| - const entityRegex = /\s*<!Entity\s+\S*\s*(?:"|')[^"]+(?:"|')\s*>/img; |
20 |
| - // Remove entities |
21 |
| - return svg.replace(entityRegex, ''); |
22 |
| -}; |
| 15 | + // Has to be `!==` as it can also return an object with error info. |
| 16 | + console.log('a', parser.validate(input)); |
| 17 | + if (parser.validate(input) !== true) { |
| 18 | + return false; |
| 19 | + } |
23 | 20 |
|
24 |
| -const removeDtdMarkupDeclarations = svg => svg.replace(/\[?(?:\s*<![A-Z]+[^>]*>\s*)*\]?/g, ''); |
| 21 | + let jsonObject; |
| 22 | + try { |
| 23 | + jsonObject = parser.parse(input); |
| 24 | + } catch (_) { |
| 25 | + return false; |
| 26 | + } |
25 | 27 |
|
26 |
| -const clean = svg => { |
27 |
| - svg = cleanEntities(svg); |
28 |
| - svg = removeDtdMarkupDeclarations(svg); |
29 |
| - return svg; |
30 |
| -}; |
| 28 | + if (!jsonObject) { |
| 29 | + return false; |
| 30 | + } |
31 | 31 |
|
32 |
| -const regex = /^\s*(?:<\?xml[^>]*>\s*)?(?:<!doctype svg[^>]*>\s*)?(?:<svg[^>]*>[^]*<\/svg>|<svg[^/>]*\/\s*>)\s*$/i; |
| 32 | + if (!('svg' in jsonObject)) { |
| 33 | + return false; |
| 34 | + } |
33 | 35 |
|
34 |
| -const isSvg = input => Boolean(input) && !isBinary(input) && regex.test(clean(input.toString()).replace(htmlCommentRegex, '')); |
| 36 | + return true; |
| 37 | +}; |
35 | 38 |
|
36 | 39 | module.exports = isSvg;
|
37 | 40 | // TODO: Remove this for the next major release
|
|
0 commit comments