0
Fork 0
mirror of https://github.com/withastro/astro.git synced 2024-12-16 21:46:22 -05:00

[ci] yarn format

This commit is contained in:
natemoo-re 2021-05-17 14:30:21 +00:00 committed by GitHub Actions
parent b3886c206f
commit a2ae7018ca
20 changed files with 103 additions and 100 deletions

View file

@ -17,6 +17,7 @@ Astro treats any `.md` files inside of the `/src/pages` directory as pages. Thes
The only special Frontmatter key is `layout`, which defines the relative path to a `.astro` component which should wrap your Markdown content.
`src/pages/index.md`
```md
---
layout: ../layouts/main.astro
@ -30,6 +31,7 @@ Layout files are normal `.astro` components. Any Frontmatter defined in your `.m
The rendered Markdown content is placed into the default `<slot />` element.
`src/layouts/main.astro`
```jsx
---
export let content;
@ -52,7 +54,7 @@ Similar to tools like [MDX](https://mdxjs.com/) or [MDsveX](https://github.com/p
Astro exposes a special `Markdown` component for `.astro` files which enables markdown syntax for its children **recursively**. Within the `Markdown` component you may also use plain HTML or any other type of component that is supported by Astro.
```jsx
````jsx
---
// For now, this import _must_ be named "Markdown" and _must not_ be wrapped with a custom component
// We're working on easing these restrictions!
@ -91,7 +93,7 @@ const expressions = 'Lorem ipsum';
</MyFancyCodePreview:visible>
</Markdown>
</Layout>
```
````
### Remote Markdown
@ -111,7 +113,7 @@ const content = await fetch('https://raw.githubusercontent.com/snowpackjs/snowpa
### Security FAQs
**Aren't there security concerns to rendering remote markdown directly to HTML?**
**Aren't there security concerns to rendering remote markdown directly to HTML?**
Yes! Just like with regular HTML, improper use the `<Markdown>` component can open you up to a [cross-site scripting (XSS)](https://en.wikipedia.org/wiki/Cross-site_scripting) attack. If you are rendering untrusted content, be sure to _santize your content **before** rendering it_.

View file

@ -1,5 +1,10 @@
import { h, Fragment } from 'preact';
export default function Yell({ children }) {
return children.filter(v => typeof v === 'string').join('').toUpperCase() + '!'
return (
children
.filter((v) => typeof v === 'string')
.join('')
.toUpperCase() + '!'
);
}

View file

@ -23,7 +23,7 @@ export default function codefence(parser: Parser) {
type: 'CodeFence',
raw: `${raw}` + trailingWhitespace,
metadata,
data
data,
};
parser.current().children.push(node);

View file

@ -18,7 +18,10 @@ export default function codespan(parser: Parser) {
end: parser.index,
type: 'CodeSpan',
raw,
data: raw?.slice(open?.length, open?.length * -1).replace(/^ /, '').replace(/ $/, '')
data: raw
?.slice(open?.length, open?.length * -1)
.replace(/^ /, '')
.replace(/ $/, ''),
};
parser.current().children.push(node);

View file

@ -306,7 +306,7 @@ interface CodegenState {
components: Components;
css: string[];
markers: {
insideMarkdown: boolean|string;
insideMarkdown: boolean | string;
};
importExportStatements: Set<string>;
dynamicImports: DynamicImportMap;
@ -583,41 +583,41 @@ function compileHtml(enterNode: TemplateNode, state: CodegenState, compileOption
try {
const attributes = getAttributes(node.attributes);
outSource += outSource === '' ? '' : ',';
if (node.type === 'Slot') {
outSource += `(children`;
return;
}
const COMPONENT_NAME_SCANNER = /^[A-Z]/;
if (!COMPONENT_NAME_SCANNER.test(name)) {
outSource += `h("${name}", ${attributes ? generateAttributes(attributes) : 'null'}`;
if (state.markers.insideMarkdown) {
outSource += `,h(__astroMarkdownRender, null`
}
return;
}
const [componentName, componentKind] = name.split(':');
const componentImportData = components[componentName];
if (!componentImportData) {
throw new Error(`Unknown Component: ${componentName}`);
}
if (componentImportData.type === '.astro') {
if (componentName === 'Markdown') {
const attributeStr = attributes ? generateAttributes(attributes) : 'null';
state.markers.insideMarkdown = attributeStr;
outSource += `h(__astroMarkdownRender, ${attributeStr}`
outSource += outSource === '' ? '' : ',';
if (node.type === 'Slot') {
outSource += `(children`;
return;
}
}
const { wrapper, wrapperImport } = getComponentWrapper(name, components[componentName], { astroConfig, dynamicImports, filename });
if (wrapperImport) {
importExportStatements.add(wrapperImport);
}
const COMPONENT_NAME_SCANNER = /^[A-Z]/;
if (!COMPONENT_NAME_SCANNER.test(name)) {
outSource += `h("${name}", ${attributes ? generateAttributes(attributes) : 'null'}`;
if (state.markers.insideMarkdown) {
outSource += `,h(__astroMarkdownRender, null`;
}
return;
}
const [componentName, componentKind] = name.split(':');
const componentImportData = components[componentName];
if (!componentImportData) {
throw new Error(`Unknown Component: ${componentName}`);
}
if (componentImportData.type === '.astro') {
if (componentName === 'Markdown') {
const attributeStr = attributes ? generateAttributes(attributes) : 'null';
state.markers.insideMarkdown = attributeStr;
outSource += `h(__astroMarkdownRender, ${attributeStr}`;
return;
}
}
const { wrapper, wrapperImport } = getComponentWrapper(name, components[componentName], { astroConfig, dynamicImports, filename });
if (wrapperImport) {
importExportStatements.add(wrapperImport);
}
outSource += `h(${wrapper}, ${attributes ? generateAttributes(attributes) : 'null'}`;
if (state.markers.insideMarkdown) {
const attributeStr = state.markers.insideMarkdown;
outSource += `,h(__astroMarkdownRender, ${attributeStr}`
outSource += `,h(__astroMarkdownRender, ${attributeStr}`;
}
} catch (err) {
// handle errors in scope with filename
@ -710,10 +710,10 @@ export async function codegen(ast: Ast, { compileOptions, filename }: CodeGenOpt
components: {},
css: [],
markers: {
insideMarkdown: false
insideMarkdown: false,
},
importExportStatements: new Set(),
dynamicImports: new Map()
dynamicImports: new Map(),
};
const { script, componentPlugins, createCollection } = compileModule(ast.module, state, compileOptions);

View file

@ -48,13 +48,17 @@ async function convertAstroToJsx(template: string, opts: ConvertAstroOptions): P
* .md -> .astro source
*/
export async function convertMdToAstroSource(contents: string, { filename }: { filename: string }): Promise<string> {
const { content, frontmatter: { layout, ...frontmatter }, ...data } = await renderMarkdownWithFrontmatter(contents);
const {
content,
frontmatter: { layout, ...frontmatter },
...data
} = await renderMarkdownWithFrontmatter(contents);
if (frontmatter['astro'] !== undefined) {
throw new Error(`"astro" is a reserved word but was used as a frontmatter value!\n\tat ${filename}`);
}
const contentData: any = {
...frontmatter,
...data
...data,
};
// </script> can't be anywhere inside of a JS string, otherwise the HTML parser fails.
// Break it up here so that the HTML parser won't detect it.
@ -75,7 +79,7 @@ async function convertMdToJsx(
contents: string,
{ compileOptions, filename, fileID }: { compileOptions: CompileOptions; filename: string; fileID: string }
): Promise<TransformResult> {
const raw = await convertMdToAstroSource(contents, { filename });
const raw = await convertMdToAstroSource(contents, { filename });
const convertOptions = { compileOptions, filename, fileID };
return await convertAstroToJsx(raw, convertOptions);
}
@ -105,7 +109,7 @@ export async function compileComponent(
): Promise<CompileResult> {
const result = await transformFromSource(source, { compileOptions, filename, projectRoot });
const site = compileOptions.astroConfig.buildOptions.site || `http://localhost:${compileOptions.astroConfig.devOptions.port}`;
const usesMarkdown = !!result.imports.find(spec => spec.indexOf('Markdown') > -1);
const usesMarkdown = !!result.imports.find((spec) => spec.indexOf('Markdown') > -1);
// return template
let modJsx = `

View file

@ -1,11 +1,11 @@
declare module '@silvenon/remark-smartypants' {
declare module '@silvenon/remark-smartypants' {
export default function (): any;
}
declare module 'mdast-util-mdx/from-markdown.js' {
declare module 'mdast-util-mdx/from-markdown.js' {
export default function (): any;
}
declare module 'mdast-util-mdx/to-markdown.js' {
declare module 'mdast-util-mdx/to-markdown.js' {
export default function (): any;
}

View file

@ -7,16 +7,16 @@ export default function createCollectHeaders() {
const visitor = (node: any) => {
if (node.type !== 'element') return;
const { tagName, children } = node
const { tagName, children } = node;
if (tagName[0] !== 'h') return;
let [_, depth] = tagName.match(/h([0-6])/) ?? [];
if (!depth) return;
depth = Number.parseInt(depth);
let text = '';
visit(node, 'text', (child) => {
text += child.value;
})
});
let slug = slugger.slug(text);
node.properties = node.properties || {};
@ -24,7 +24,7 @@ export default function createCollectHeaders() {
headers.push({ depth, slug, text });
return node;
}
};
return { headers, rehypeCollectHeaders: () => (tree: any) => visit(tree, visitor) }
return { headers, rehypeCollectHeaders: () => (tree: any) => visit(tree, visitor) };
}

View file

@ -2,24 +2,24 @@ import fromMarkdown from 'mdast-util-mdx/from-markdown.js';
import toMarkdown from 'mdast-util-mdx/to-markdown.js';
/** See https://github.com/micromark/micromark-extension-mdx-md */
const syntax = { disable: {null: ['autolink', 'codeIndented']} };
const syntax = { disable: { null: ['autolink', 'codeIndented'] } };
/**
/**
* Lite version of https://github.com/mdx-js/mdx/tree/main/packages/remark-mdx
* We don't need all the features MDX does because all components are precompiled
* to HTML. We just want to disable a few MD features that cause issues.
*/
function mdxLite (this: any) {
let data = this.data()
function mdxLite(this: any) {
let data = this.data();
add('micromarkExtensions', syntax);
add('fromMarkdownExtensions', fromMarkdown)
add('toMarkdownExtensions', toMarkdown)
add('fromMarkdownExtensions', fromMarkdown);
add('toMarkdownExtensions', toMarkdown);
/** Adds remark plugin */
function add(field: string, value: any) {
if (data[field]) data[field].push(value)
else data[field] = [value]
if (data[field]) data[field].push(value);
else data[field] = [value];
}
}

View file

@ -6,13 +6,13 @@ export default function scopedStyles(className: string) {
const visitor = (node: any) => {
if (noVisit.has(node.type)) return;
const {data} = node
const { data } = node;
const currentClassName = data?.hProperties?.class ?? '';
node.data = node.data || {};
node.data.hProperties = node.data.hProperties || {};
node.data.hProperties.className = `${className} ${currentClassName}`.trim();
return node;
}
};
return () => (tree: any) => visit(tree, visitor);
}

View file

@ -214,7 +214,7 @@ export default function transformStyles({ compileOptions, filename, fileID }: Tr
enter(node) {
if (node.name !== 'Markdown') return;
injectScopedClassAttribute(node, scopedClass, '$scope');
}
},
},
Element: {
enter(node) {

View file

@ -18,13 +18,10 @@ export interface MarkdownRenderingOptions {
}
/** Internal utility for rendering a full markdown file and extracting Frontmatter data */
export async function renderMarkdownWithFrontmatter(contents: string, opts?: MarkdownRenderingOptions|null) {
export async function renderMarkdownWithFrontmatter(contents: string, opts?: MarkdownRenderingOptions | null) {
// Dynamic import to ensure that "gray-matter" isn't built by Snowpack
const { default: matter } = await import('gray-matter');
const {
data: frontmatter,
content,
} = matter(contents);
const { data: frontmatter, content } = matter(contents);
const value = await renderMarkdown(content, opts);
return { ...value, frontmatter };
}
@ -41,12 +38,12 @@ export async function renderMarkdown(content: string, opts?: MarkdownRenderingOp
}
if (useGfm) {
const {default:gfm} = await import('remark-gfm');
const { default: gfm } = await import('remark-gfm');
parser = parser.use(gfm);
}
if (useFootnotes) {
const {default:footnotes} = await import('remark-footnotes');
const { default: footnotes } = await import('remark-footnotes');
parser = parser.use(footnotes);
}

View file

@ -1,14 +1,14 @@
import { renderMarkdown } from '../compiler/utils.js';
/**
* Functional component which uses Astro's built-in Markdown rendering
* to render out its children.
*
* Note: the children have already been properly escaped/rendered
* by the parser and Astro, so at this point we're just rendering
* out plain markdown, no need for JSX support
*/
export default async function Markdown(props: { $scope: string|null }, ...children: string[]): Promise<string> {
/**
* Functional component which uses Astro's built-in Markdown rendering
* to render out its children.
*
* Note: the children have already been properly escaped/rendered
* by the parser and Astro, so at this point we're just rendering
* out plain markdown, no need for JSX support
*/
export default async function Markdown(props: { $scope: string | null }, ...children: string[]): Promise<string> {
const { $scope = null } = props ?? {};
const text = dedent(children.join('').trimEnd());
let { content } = await renderMarkdown(text, { $: { scopedClassName: $scope } });
@ -21,6 +21,6 @@ export default async function Markdown(props: { $scope: string|null }, ...childr
/** Remove leading indentation based on first line */
function dedent(str: string) {
let arr = str.match(/^[ \t]*(?=\S)/gm);
let first = !!arr && arr.find(x => x.length > 0)?.length;
return (!arr || !first) ? str : str.replace(new RegExp(`^[ \\t]{0,${first}}`, 'gm'), '');
let first = !!arr && arr.find((x) => x.length > 0)?.length;
return !arr || !first ? str : str.replace(new RegExp(`^[ \\t]{0,${first}}`, 'gm'), '');
}

View file

@ -39,11 +39,11 @@ export function createRenderer(renderer: SupportedComponentRenderer) {
const script = `${typeof wrapperStart === 'function' ? wrapperStart(innerContext) : wrapperStart}
${_imports(renderContext)}
${renderer.render({
...innerContext,
props: serializeProps(props),
children: `[${childrenToH(renderer, children) ?? ''}]`,
childrenAsString: `\`${children}\``,
})}
...innerContext,
props: serializeProps(props),
children: `[${childrenToH(renderer, children) ?? ''}]`,
childrenAsString: `\`${children}\``,
})}
${typeof wrapperEnd === 'function' ? wrapperEnd(innerContext) : wrapperEnd}`;
return [value, `<script type="module">${script.trim()}</script>`].join('\n');

View file

@ -42,7 +42,7 @@ export const childrenToH = moize.deep(function childrenToH(renderer: ComponentRe
const simpleTypes = new Set(['number', 'boolean']);
const serializeChild = (child: unknown) => {
if (typeof child === 'string') return JSON.stringify(child).replace(/<\/script>/gmi, '</script" + ">');
if (typeof child === 'string') return JSON.stringify(child).replace(/<\/script>/gim, '</script" + ">');
if (simpleTypes.has(typeof child)) return JSON.stringify(child);
if (child === null) return `null`;
if ((child as any).__SERIALIZED) return (child as any).__SERIALIZED;

View file

@ -314,11 +314,7 @@ async function createSnowpack(astroConfig: AstroConfig, options: CreateSnowpackO
},
packageOptions: {
knownEntrypoints: ['preact-render-to-string'],
external: [
'@vue/server-renderer',
'node-fetch',
'prismjs/components/index.js'
],
external: ['@vue/server-renderer', 'node-fetch', 'prismjs/components/index.js'],
},
});

View file

@ -45,7 +45,7 @@ export function searchForPage(url: URL, astroRoot: URL): SearchResult {
// Try to find index.astro/md paths
if (reqPath.endsWith('/')) {
const candidates = [`${base}index.astro`, `${base}index.md`,];
const candidates = [`${base}index.astro`, `${base}index.md`];
const location = findAnyPage(candidates, astroRoot);
if (location) {
return {

View file

@ -8,7 +8,6 @@ const Markdown = suite('Astro Markdown tests');
setup(Markdown, './fixtures/astro-markdown');
setupBuild(Markdown, './fixtures/astro-markdown');
Markdown('Can load markdown pages with Astro', async ({ runtime }) => {
const result = await runtime.load('/post');
if (result.error) throw new Error(result.error);

View file

@ -34,5 +34,4 @@ Markdown('Builds markdown pages for prod', async (context) => {
await context.build();
});
Markdown.run();

View file

@ -16,13 +16,11 @@
{ "open": "'", "close": "'" },
{ "open": "\"", "close": "\"" },
{
"open": "<",
"close": ">",
"notIn": [
"string"
]
},
{ "open": "<!--", "close": "-->", "notIn": ["comment", "string"] },
"open": "<",
"close": ">",
"notIn": ["string"]
},
{ "open": "<!--", "close": "-->", "notIn": ["comment", "string"] }
],
"autoCloseBefore": ";:.,=}])>` \n\t",
"surroundingPairs": [