Skip to content

Commit

Permalink
Handle invalid snippets
Browse files Browse the repository at this point in the history
  • Loading branch information
sergeche committed Sep 23, 2024
1 parent 949f080 commit 5f77c35
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 1 deletion.
5 changes: 5 additions & 0 deletions src/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,11 @@ interface ResolvedConfig extends BaseConfig {
* new object.
*/
cache?: Cache;

/**
* A callback for internal warnings or errors (for example, when parsing invalid abbreviation)
*/
warn?: (message: string, err?: Error) => void
}

export type Config = ResolvedConfig & { options: Options };
Expand Down
11 changes: 10 additions & 1 deletion src/markup/snippets.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import type { Config } from '../config.js';
export default function resolveSnippets(abbr: Abbreviation, config: Config): Abbreviation {
const stack: string[] = [];
const reversed = config.options['output.reverseAttributes'];
const { warn } = config;

const resolve = (child: AbbreviationNode): Abbreviation | null => {
const snippet = child.name && config.snippets[child.name];
Expand All @@ -26,7 +27,15 @@ export default function resolveSnippets(abbr: Abbreviation, config: Config): Abb
return null;
}

const snippetAbbr = parse(snippet, config);
let snippetAbbr: Abbreviation;
try {
// User may add invlid snippet. In this case, silently bail out
snippetAbbr = parse(snippet, config);
} catch (err) {
warn?.(`Unable to parse "${snippet}" snippet`, err);
return null;
}

stack.push(snippet);
walkResolve(snippetAbbr, resolve, config);
stack.pop();
Expand Down
10 changes: 10 additions & 0 deletions test/snippets.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,4 +14,14 @@ describe('Snippets', () => {
it('XSL', () => {
Object.keys(xsl).forEach(k => ok(markup(xsl[k]), k));
});

it('Invalid snippets', () => {
const snippets = {
invalid: 'invalid snippet',
valid: 'button'
}

const result = expand('invalid+valid', { snippets })
equal(result, '<invalid></invalid>\n<button></button>')
});
});

0 comments on commit 5f77c35

Please sign in to comment.