MCPcopy Create free account
hub / github.com/colbymchenry/codegraph / assertWellFormed

Function assertWellFormed

__tests__/ui-export-svg.test.ts:160–182  ·  view source on GitHub ↗

* Parse the SVG the way a consumer does. * * `DOMParser` is not in Node, so this is a hand-rolled well-formedness check: * every tag balanced, every attribute quoted, no stray `<` or `&` in text. That * is exactly the class of bug an un-escaped symbol name (`Map `, `a && b`) * would introdu

(svg: string)

Source from the content-addressed store, hash-verified

158 * would introduce, and it is the one that makes GitHub refuse the file.
159 */
160function assertWellFormed(svg: string): void {
161 const stack: string[] = [];
162 const tag = /<(\/?)([a-zA-Z:]+)((?:[^>"']|"[^"]*"|'[^']*')*?)(\/?)>/g;
163 let at = 0;
164 let match: RegExpExecArray | null;
165 while ((match = tag.exec(svg)) !== null) {
166 const between = svg.slice(at, match.index);
167 expect(between, `unescaped < or & in text: ${JSON.stringify(between)}`).not.toMatch(
168 /[<]|&(?!(amp|lt|gt|quot|apos|#\d+);)/
169 );
170 at = match.index + match[0].length;
171 const [, closing, name, attrs, selfClosing] = match;
172 // Every attribute is name="value" with a balanced pair of quotes.
173 const quotes = (attrs as string).split('"').length - 1;
174 expect(quotes % 2, `unbalanced quotes in <${name} ${attrs}>`).toBe(0);
175 if (closing === '/') {
176 expect(stack.pop(), 'closing tag with no opener').toBe(name);
177 } else if (selfClosing !== '/') {
178 stack.push(name as string);
179 }
180 }
181 expect(stack, 'unclosed tags').toEqual([]);
182}
183
184function viewBox(svg: string): { width: number; height: number } {
185 const box = /viewBox="0 0 (\d+(?:\.\d+)?) (\d+(?:\.\d+)?)"/.exec(svg);

Callers 1

Calls 2

pushMethod · 0.80
execMethod · 0.65

Tested by

no test coverage detected