Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support error fallback #14

Merged
merged 2 commits into from
Dec 5, 2022
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,15 @@ console.log(value);

### Options

#### `errorFallback`

Create a fallback node if processing of a mermaid diagram fails. If nothing is returned, the code
block is removed. The function receives the following arguments:

- `node`: The mdast `code` node that couldn’t be rendered.
- `error`: The error message that was thrown.
- `file`: The file on which the error occurred.

#### `launchOptions`

These options are passed to
Expand Down
56 changes: 35 additions & 21 deletions browser.ts
Original file line number Diff line number Diff line change
@@ -1,39 +1,53 @@
import { fromDom } from 'hast-util-from-dom';
import { type Code, type Parent, type Root } from 'mdast';
import { type Code, type Parent } from 'mdast';
import mermaid from 'mermaid';
import { type Plugin } from 'unified';
import type { RemarkMermaid } from 'remark-mermaidjs';
import { visit } from 'unist-util-visit';

// eslint-disable-next-line jsdoc/require-jsdoc
function transformer(ast: Root): void {
const instances: [string, number, Parent][] = [];
const remarkMermaid: RemarkMermaid = (options) => (ast, file) => {
const instances: [Code, number, Parent][] = [];

visit(ast, { type: 'code', lang: 'mermaid' }, (node: Code, index, parent: Parent) => {
instances.push([node.value, index, parent]);
instances.push([node, index, parent]);
});

// Nothing to do. No need to start puppeteer in this case.
if (!instances.length) {
return;
}

const results = instances.map(([code], index) =>
// @ts-expect-error The mermaid types are wrong.
mermaid.render(`remark-mermaid-${index}`, code),
);
const results: string[] = [];
const errors: string[] = [];
for (const [index, [node]] of instances.entries()) {
try {
// @ts-expect-error The mermaid types are wrong.
results[index] = mermaid.render(`remark-mermaid-${index}`, node.value);
} catch (error) {
errors[index] = error instanceof Error ? error.message : String(error);
}
}

const wrapper = document.createElement('div');
for (const [i, [, index, parent]] of instances.entries()) {
const value = results[i];
wrapper.innerHTML = value;
parent.children.splice(index, 1, {
type: 'paragraph',
children: [{ type: 'html', value }],
data: { hChildren: [fromDom(wrapper.firstChild!)] },
});
for (const [i, [node, index, parent]] of instances.entries()) {
if (i in results) {
const value = results[i];
wrapper.innerHTML = value;
parent.children.splice(index, 1, {
type: 'paragraph',
children: [{ type: 'html', value }],
data: { hChildren: [fromDom(wrapper.firstChild!)] },
});
} else if (options?.errorFallback) {
const fallback = options.errorFallback(node, errors[i], file);
if (fallback) {
parent.children[index] = fallback;
} else {
parent.children.splice(index, 1);
}
} else {
file.fail(errors[i], node, 'remark-mermaidjs:remark-mermaidjs');
}
}
}

const remarkMermaid: Plugin<[], Root> = () => transformer;
};

export default remarkMermaid;
99 changes: 81 additions & 18 deletions index.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,14 @@
import { createRequire } from 'node:module';

import { fromParse5 } from 'hast-util-from-parse5';
import { type Code, type Parent, type Root } from 'mdast';
import { type BlockContent, type Code, type Parent, type Root } from 'mdast';
import { type MermaidConfig } from 'mermaid';
import { parseFragment } from 'parse5';
import puppeteer, { type Browser, type Page, type PuppeteerLaunchOptions } from 'puppeteer-core';
import { type Config, optimize } from 'svgo';
import { type Plugin } from 'unified';
import { visit } from 'unist-util-visit';
import { type VFile } from 'vfile';

const mermaidScript = {
path: createRequire(import.meta.url).resolve('mermaid/dist/mermaid.min.js'),
Expand All @@ -16,6 +17,30 @@ const mermaidScript = {
// eslint-disable-next-line @typescript-eslint/consistent-type-imports
declare const mermaid: typeof import('mermaid').default;

interface SuccessResult {
/**
* This indicates diagram was rendered succesfully.
*/
success: true;

/**
* The resulting SVG code.
*/
svg: string;
}

interface ErrorResult {
/**
* This indicates diagram wasn’t rendered succesfully.
*/
success: false;

/**
* The error message.
*/
error: string;
}

export interface RemarkMermaidOptions {
/**
* Launch options to pass to puppeteer.
Expand All @@ -42,26 +67,40 @@ export interface RemarkMermaidOptions {
* you use this in a browser, call `mermaid.initialize()` manually.
*/
mermaidOptions?: MermaidConfig;

/**
* Create a fallback node if processing of a mermaid diagram fails.
*
* @param node The mdast `code` node that couldn’t be rendered.
* @param error The error message that was thrown.
* @param file The file on which the error occurred.
* @returns A fallback node to render instead of the invalid diagram. If nothing is returned, the
* code block is removed
*/
// eslint-disable-next-line @typescript-eslint/no-invalid-void-type
errorFallback?: (node: Code, error: string, file: VFile) => BlockContent | undefined | void;
}

export type RemarkMermaid = Plugin<[RemarkMermaidOptions?], Root>;

/**
* @param options Options that may be used to tweak the output.
*/
const remarkMermaid: Plugin<[RemarkMermaidOptions?], Root> = (options) => {
const remarkMermaid: RemarkMermaid = (options) => {
if (!options?.launchOptions?.executablePath) {
throw new Error('The option `launchOptions.executablePath` is required when using Node.js');
}

const { launchOptions, mermaidOptions, svgo } = options;
const { errorFallback, launchOptions, mermaidOptions, svgo } = options;

let browserPromise: Promise<Browser> | undefined;
let count = 0;

return async function transformer(ast) {
const instances: [string, number, Parent][] = [];
return async function transformer(ast, file) {
const instances: [Code, number, Parent][] = [];

visit(ast, { type: 'code', lang: 'mermaid' }, (node: Code, index, parent: Parent) => {
instances.push([node.value, index, parent]);
instances.push([node, index, parent]);
});

// Nothing to do. No need to start puppeteer in this case.
Expand All @@ -76,7 +115,7 @@ const remarkMermaid: Plugin<[RemarkMermaidOptions?], Root> = (options) => {
});
const browser = await browserPromise;
let page: Page | undefined;
let results: string[];
let results: (ErrorResult | SuccessResult)[];
try {
page = await browser.newPage();
await page.goto(String(new URL('index.html', import.meta.url)));
Expand All @@ -90,27 +129,51 @@ const remarkMermaid: Plugin<[RemarkMermaidOptions?], Root> = (options) => {
if (initOptions) {
mermaid.initialize(initOptions);
}
return codes.map((code, index) => mermaid.render(`remark-mermaid-${index}`, code));
return codes.map((code, index) => {
try {
return {
success: true,
svg: mermaid.render(`remark-mermaid-${index}`, code),
} as const;
} catch (error) {
return {
success: false,
error: error instanceof Error ? error.message : String(error),
} as const;
}
});
},
/* C8 ignore stop */
instances.map((instance) => instance[0]),
instances.map((instance) => instance[0].value),
mermaidOptions,
);
} finally {
count -= 1;
await page?.close();
}

for (const [i, [, index, parent]] of instances.entries()) {
let value = results[i];
if (svgo !== false) {
value = optimize(value, svgo).data;
for (const [i, [node, index, parent]] of instances.entries()) {
const result = results[i];
if (result.success) {
let value = result.svg;
if (svgo !== false) {
value = optimize(value, svgo).data;
}
parent.children[index] = {
type: 'paragraph',
children: [{ type: 'html', value }],
data: { hChildren: [fromParse5(parseFragment(value))] },
};
} else if (errorFallback) {
const fallback = errorFallback(node, result.error, file);
if (fallback) {
parent.children[index] = fallback;
} else {
parent.children.splice(index, 1);
}
} else {
file.fail(result.error, node, 'remark-mermaidjs:remark-mermaidjs');
remcohaszing marked this conversation as resolved.
Show resolved Hide resolved
}
parent.children.splice(index, 1, {
type: 'paragraph',
children: [{ type: 'html', value }],
data: { hChildren: [fromParse5(parseFragment(value))] },
});
}
if (!count) {
browserPromise = undefined;
Expand Down
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,8 @@
"puppeteer-core": "^19.0.0",
"svgo": "^3.0.0",
"unified": "^10.0.0",
"unist-util-visit": "^4.0.0"
"unist-util-visit": "^4.0.0",
"vfile": "^5.0.0"
},
"devDependencies": {
"@playwright/test": "^1.0.0",
Expand Down
9 changes: 9 additions & 0 deletions test/fixtures/error/input.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
# Error

This is an invalid diagram

```mermaid
invalid
```

More content
10 changes: 10 additions & 0 deletions test/fixtures/error/options.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import type { RemarkMermaidOptions } from 'remark-mermaidjs';

export const options: RemarkMermaidOptions = {
errorFallback(node, error, vfile) {
return {
type: 'code',
value: `${vfile.basename}\n\n${error}\n\n${JSON.stringify(node, undefined, 2)}`,
};
},
};
9 changes: 9 additions & 0 deletions test/fixtures/errorEmpty/input.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
# Error

This is an invalid diagram

```mermaid
invalid
```

More content
6 changes: 6 additions & 0 deletions test/fixtures/errorEmpty/options.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
import type { RemarkMermaidOptions } from 'remark-mermaidjs';

export const options: RemarkMermaidOptions = {
// eslint-disable-next-line @typescript-eslint/no-empty-function
errorFallback() {},
};
17 changes: 12 additions & 5 deletions test/runInBrowser.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,13 @@
import rehypeStringify from 'rehype-stringify';
import { remark } from 'remark';
import { type RemarkMermaidOptions } from 'remark-mermaidjs';
import remarkRehype from 'remark-rehype';

import remarkMermaid from '../browser.js';
import { options as error } from './fixtures/error/options.js';
import { options as errorEmpty } from './fixtures/errorEmpty/options.js';

const options: Record<string, RemarkMermaidOptions> = { error, errorEmpty };

/**
* Process a fixture using remark and remark-mermaidjs.
Expand All @@ -13,10 +18,12 @@ import remarkMermaid from '../browser.js';
* @returns A tuple of the file processed to both markdown and HTML.
*/
export async function processFixture(name: string): Promise<[string, string]> {
const response = await fetch(`fixtures/${name}/input.md`);
const original = await response.text();
const processor = remark().use(remarkMermaid);
const asMarkdown = processor.processSync(original);
const asHTML = processor().use(remarkRehype).use(rehypeStringify).processSync(original);
const testOptions = name in options ? options[name] : undefined;
const path = `fixtures/${name}/input.md`;
const response = await fetch(path);
const value = await response.text();
const processor = remark().use(remarkMermaid, testOptions);
const asMarkdown = processor.processSync({ path, value });
const asHTML = processor().use(remarkRehype).use(rehypeStringify).processSync({ path, value });
return [asMarkdown.value as string, asHTML.value as string];
}
27 changes: 24 additions & 3 deletions test/test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import rehypeStringify from 'rehype-stringify';
import { remark } from 'remark';
import remarkRehype from 'remark-rehype';
import sinon from 'sinon';
import { VFile } from 'vfile';

import remarkMermaid, { type RemarkMermaidOptions } from '../index.js';

Expand Down Expand Up @@ -45,7 +46,7 @@ test.describe.parallel('node', () => {
test(name, async ({}, testInfo) => {
testInfo.snapshotSuffix = 'node';
const fixture = new URL(`${name}/`, fixtures);
const original = await readFile(new URL('input.md', fixture));
const value = await readFile(new URL('input.md', fixture));
let options: RemarkMermaidOptions = {
launchOptions,
};
Expand All @@ -56,8 +57,11 @@ test.describe.parallel('node', () => {
// This test case uses default options.
}
const processor = remark().use(remarkMermaid, options);
const asMarkdown = await processor.process(original);
const asHTML = await processor().use(remarkRehype).use(rehypeStringify).process(original);
const asMarkdown = await processor.process({ path: `${name}/input.md`, value });
const asHTML = await processor()
.use(remarkRehype)
.use(rehypeStringify)
.process({ path: `${name}/input.md`, value });
expect(asMarkdown.value).toMatchSnapshot({ name: `${name}.md` });
expect(asHTML.value).toMatchSnapshot({ name: `${name}.html` });
});
Expand Down Expand Up @@ -104,4 +108,21 @@ test.describe.serial('node', () => {
'The option `launchOptions.executablePath` is required when using Node.js',
);
});

test('it should throw a vfile error if a diagram is invalid without error fallback', async () => {
const processor = remark().use(remarkMermaid, { launchOptions });
const file = new VFile('```mermaid\ninvalid\n```\n');
await expect(() => processor.process(file)).rejects.toThrowError(
'No diagram type detected for text: invalid',
);
expect(file.messages).toHaveLength(1);
expect(file.messages[0].message).toBe('No diagram type detected for text: invalid');
expect(file.messages[0].source).toBe('remark-mermaidjs');
expect(file.messages[0].ruleId).toBe('remark-mermaidjs');
expect(file.messages[0].fatal).toBe(true);
expect(file.messages[0].position).toStrictEqual({
start: { offset: 0, line: 1, column: 1 },
end: { offset: 22, line: 3, column: 4 },
});
});
});
Loading