refactor: use MarkdocError on render errors
This commit is contained in:
parent
041f606343
commit
6217b7a1a1
1 changed files with 26 additions and 22 deletions
|
@ -1,7 +1,8 @@
|
||||||
import type { AstroInstance } from 'astro';
|
import type { AstroInstance } from 'astro';
|
||||||
import type { RenderableTreeNode } from '@markdoc/markdoc';
|
import type { RenderableTreeNode } from '@markdoc/markdoc';
|
||||||
import Markdoc from '@markdoc/markdoc';
|
import Markdoc from '@markdoc/markdoc';
|
||||||
import z from 'zod';
|
import { MarkdocError } from '../dist/utils.js';
|
||||||
|
import z, { ZodError } from 'zod';
|
||||||
|
|
||||||
export type AstroNode =
|
export type AstroNode =
|
||||||
| string
|
| string
|
||||||
|
@ -55,28 +56,31 @@ export function createAstroNode(
|
||||||
}
|
}
|
||||||
|
|
||||||
function validateComponents(components: Record<string, AstroInstance['default']>) {
|
function validateComponents(components: Record<string, AstroInstance['default']>) {
|
||||||
return z
|
try {
|
||||||
.record(
|
return z
|
||||||
z
|
.record(
|
||||||
.string()
|
z
|
||||||
.min(1, toComponentsKeyErrorMsg('Component name cannot be empty.'))
|
.string()
|
||||||
.refine(
|
.min(1, 'Invalid `components` prop. Component names cannot be empty!')
|
||||||
(value) => isCapitalized(value),
|
.refine(
|
||||||
(value) => ({
|
(value) => isCapitalized(value),
|
||||||
message: toComponentsKeyErrorMsg(
|
(value) => ({
|
||||||
`Component name must be capitalized (received ${JSON.stringify(
|
message: `Invalid \`components\` prop: ${JSON.stringify(
|
||||||
value
|
value
|
||||||
)}). If you want to render HTML elements as components, try using a Markdoc node [TODO: DOCS LINK]`
|
)}. Component name must be capitalized. If you want to render HTML elements as components, try using a Markdoc node [TODO: DOCS LINK]`,
|
||||||
),
|
})
|
||||||
})
|
),
|
||||||
),
|
z.any()
|
||||||
z.any()
|
)
|
||||||
)
|
.parse(components);
|
||||||
.parse(components);
|
} catch (e) {
|
||||||
}
|
throw new MarkdocError({
|
||||||
|
message:
|
||||||
function toComponentsKeyErrorMsg(msg: string) {
|
e instanceof ZodError
|
||||||
return '[Markdoc] Invalid "components" prop: ' + msg;
|
? e.issues[0].message
|
||||||
|
: 'Invalid `components` prop. Ensure you are passing an object of components to <Content />',
|
||||||
|
});
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function isCapitalized(str: string) {
|
function isCapitalized(str: string) {
|
||||||
|
|
Loading…
Add table
Reference in a new issue