Compare commits

...

2 commits

Author SHA1 Message Date
Fred K. Schott
59728dd64a wip 2021-07-11 22:55:41 -04:00
Fred K. Schott
653b23082f move Astro.fetchContent to runtime API 2021-07-10 01:55:42 -04:00
28 changed files with 120 additions and 505 deletions

View file

@ -0,0 +1,17 @@
---
'astro': minor
---
[BREAKING CHANGE] change Astro.fetchContent() to a runtime API. This makes two breaking changes to the existing Astro.fetchContent() API:
1. The method is now async. Previously, it was synchronous.
2. The method now takes in an `import.meta.glob()` argument. Previous, it took a string.
Example change to make to your code:
```diff
- let allPosts = Astro.fetchContent('../pages/posts/*.md');
+ let allPosts = await Astro.fetchContent(import.meta.glob('../pages/posts/*.md'));
```
An error will throw if you use the deprecated syntax.

View file

@ -40,7 +40,7 @@ const { collection } = Astro.props;
// Define a `createCollection` function. // Define a `createCollection` function.
export async function createCollection() { export async function createCollection() {
const allPosts = Astro.fetchContent('../posts/*.md'); // fetch local posts. const allPosts = await Astro.fetchContent(import.meta.glob('../posts/*.md')); // fetch local posts.
allPosts.sort((a, b) => a.title.localeCompare(b.title)); // sort by title. allPosts.sort((a, b) => a.title.localeCompare(b.title)); // sort by title.
return { return {
// Because you are not doing anything more than simple pagination, // Because you are not doing anything more than simple pagination,

View file

@ -9,12 +9,16 @@ The `Astro` global is available in all contexts in `.astro` files. It has the fo
### `Astro.fetchContent()` ### `Astro.fetchContent()`
`Astro.fetchContent()` is a way to load local `*.md` files into your static site setup. You can either use this on its own, or within [Astro Collections][docs-collections]. `Astro.fetchContent()` is a way to load local Markdown files in Astro. You can use this to generate pages based on your site content, for things like [paginated collections][docs-collections] or a single page that lists all posts on your site.
This leverages `import.meta.glob` in Snowpack to fetch the local files.
```jsx ```jsx
// ./src/components/my-component.astro
--- ---
const data = Astro.fetchContent('../pages/post/*.md'); // returns an array of posts that live at ./src/pages/post/*.md // Example: ./src/components/my-component.astro
// - `import.meta.glob('../pages/post/*.md')` returns references to all markdown posts.
// - `Astro.fetchContent()` loads the referenced markdown files, and returns the result.
const posts = await Astro.fetchContent(import.meta.glob('../pages/post/*.md'));
--- ---
<div> <div>
@ -28,24 +32,25 @@ const data = Astro.fetchContent('../pages/post/*.md'); // returns an array of po
</div> </div>
``` ```
`.fetchContent()` only takes one parameter: a relative URL glob of which local files youd like to import. Currently only `*.md` files are supported. Its synchronous, and returns an array of items of type: Any non-markdown posts will be ignored. A successful call returns a Promise, which resolves to array of items of the following type:
```js ```js
{ {
/** frontmatter from the post.. example frontmatter: /** Markdown file frontmatter: */
title: '', title: '',
tag: '', tag: '',
date: '', date: '',
image: '', image: '',
author: '', author: '',
description: '', description: '',
**/ /** astro metadata: **/
astro: { astro: {
headers: [], // an array of h1...h6 elements in the markdown file headers: [], // an array of h1...h6 elements in the markdown file
source: '' // raw source of the markdown file source: '' // raw source of the markdown file
html: '' // rendered HTML of the markdown file html: '' // rendered HTML of the markdown file
}, },
url: '' // the rendered path /** the file's web URL (if it is a page) */
url: ''
}[] }[]
``` ```

View file

@ -15,7 +15,7 @@ import authorData from '../data/authors.json';
let { collection } = Astro.props; let { collection } = Astro.props;
export async function createCollection() { export async function createCollection() {
/** Load posts */ /** Load posts */
let allPosts = Astro.fetchContent('./post/*.md'); let allPosts = await Astro.fetchContent(import.meta.glob('./post/*.md'));
let allAuthors = new Set(); let allAuthors = new Set();
/** Loop through all posts, gather all authors */ /** Loop through all posts, gather all authors */

View file

@ -16,7 +16,7 @@ export async function createCollection() {
return { return {
/** Load posts, sort newest -> oldest */ /** Load posts, sort newest -> oldest */
async data() { async data() {
let allPosts = Astro.fetchContent('./post/*.md'); let allPosts = await Astro.fetchContent(import.meta.glob('./post/*.md'));
allPosts.sort((a, b) => new Date(b.date) - new Date(a.date)); allPosts.sort((a, b) => new Date(b.date) - new Date(a.date));
return allPosts; return allPosts;
}, },

View file

@ -14,7 +14,7 @@ let title = 'Dons Blog';
let description = 'An example blog on Astro'; let description = 'An example blog on Astro';
// Data Fetching: List all Markdown posts in the repo. // Data Fetching: List all Markdown posts in the repo.
let allPosts = Astro.fetchContent('./post/*.md'); let allPosts = await Astro.fetchContent(import.meta.glob('./post/*.md'));
allPosts.sort((a, b) => new Date(b.date) - new Date(a.date)); allPosts.sort((a, b) => new Date(b.date) - new Date(a.date));
// Full Astro Component Syntax: // Full Astro Component Syntax:

View file

@ -13,7 +13,8 @@ let description = 'The perfect starter for your perfect blog.';
let permalink = 'https://example.com/'; let permalink = 'https://example.com/';
// Data Fetching: List all Markdown posts in the repo. // Data Fetching: List all Markdown posts in the repo.
let allPosts = Astro.fetchContent('./posts/*.md'); let allPosts = await Astro.fetchContent(import.meta.glob('../pages/posts/*.md'));
console.log(allPosts)
allPosts = allPosts.sort((a, b) => new Date(b.publishDate) - new Date(a.publishDate)); allPosts = allPosts.sort((a, b) => new Date(b.publishDate) - new Date(a.publishDate));
// Full Astro Component Syntax: // Full Astro Component Syntax:

View file

@ -1,9 +1,16 @@
--- ---
const { title = 'Jeanine White: Personal Site' } = Astro.props; export interface Props {
--- title: string;
description?: string[];
}
export function __state({props}: {props: Props}) {
return {description: props.description || 'This is the default site descrition.'};
}
---
<meta charset="UTF-8"> <meta charset="UTF-8">
<title>{title}</title> <title>{$props.title}</title>
<meta name="description" content={$state.description}>
<link rel="stylesheet" type="text/css" href="/global.css"> <link rel="stylesheet" type="text/css" href="/global.css">
<link rel="preconnect" href="https://fonts.gstatic.com"> <link rel="preconnect" href="https://fonts.gstatic.com">
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@200;400;700;900&display=swap" rel="stylesheet"> <link href="https://fonts.googleapis.com/css2?family=Inter:wght@200;400;700;900&display=swap" rel="stylesheet">

View file

@ -3,12 +3,10 @@ import MainHead from '../components/MainHead.astro';
import Button from '../components/Button/index.jsx'; import Button from '../components/Button/index.jsx';
import Footer from '../components/Footer/index.jsx'; import Footer from '../components/Footer/index.jsx';
import Nav from '../components/Nav/index.jsx'; import Nav from '../components/Nav/index.jsx';
const { content } = Astro.props;
--- ---
<html> <html>
<head> <head>
<MainHead title={content.title} /> <MainHead title={$props.content.title} />
<style lang="scss"> <style lang="scss">
.hero { .hero {
padding: 8rem; padding: 8rem;

View file

@ -8,7 +8,7 @@ let { collection } = Astro.props;
export async function createCollection() { export async function createCollection() {
return { return {
async data() { async data() {
const projects = Astro.fetchContent('./project/*.md'); const projects = await Astro.fetchContent(import.meta.glob('./project/*.md'));
projects.sort((a, b) => new Date(b.published_at) - new Date(a.published_at)); projects.sort((a, b) => new Date(b.published_at) - new Date(a.published_at));
return projects.filter(({ published_at }) => !!published_at); return projects.filter(({ published_at }) => !!published_at);
} }

View file

@ -1,245 +1,12 @@
--- ---
// Component Imports // Component Imports
import MainHead from '../components/MainHead.astro'; import MainHead from '../components/MainHead.astro';
import Button from '../components/Button/index.jsx';
import Nav from '../components/Nav/index.jsx';
import Footer from '../components/Footer/index.jsx';
import PorfolioPreview from '../components/PortfolioPreview/index.jsx';
// Data Fetching: List all Markdown posts in the repo.
const projects = Astro.fetchContent('./project/**/*.md');
const featuredProject = projects[0];
// Full Astro Component Syntax:
// https://github.com/snowpackjs/astro/blob/main/docs/core-concepts/astro-components.md
--- ---
<html> <html>
<head> <head>
<MainHead title="Jeanine White: Personal Site" /> <MainHead title="Jeanine White: Personal Site" />
<style lang="scss">
$w-s: 750px;
.hero {
position: relative;
overflow: hidden;
@media (min-width: $w-s) {
height: 45vw;
}
}
.img {
display: block;
width: 100%;
height: auto;
}
.gradient,
.gradient2 {
background-image: url('/assets/mesh-gradient.jpg');
pointer-events: none;
mix-blend-mode: screen;
width: 100%;
height: 100%;
position: absolute;
top: 0;
left: 0;
z-index: 2;
}
.gradient2 {
mix-blend-mode: multiply;
}
.overlay {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
z-index: 10;
display: flex;
flex-direction: column;
align-items: flex-start;
justify-content: center;
padding-left: 2rem;
@media (min-width: $w-s) {
padding-left: 4rem;
}
}
.title {
font-weight: 900;
font-size: var(--f-u8);
margin-bottom: 0.5rem;
margin-top: 0;
@media (min-width: $w-s) {
font-size: var(--f-u12);
}
}
.grid {
display: grid;
grid-gap: 2rem;
@media (min-width: 1200px) {
grid-template-columns: 2fr 1fr;
}
}
.sectionTitle {
font-weight: 700;
font-size: var(--f-u8);
margin-top: 4rem;
margin-bottom: 2rem;
}
.role {
position: relative;
display: inline-block;
font-weight: 900;
color: var(--t-bg);
background-color: var(--t-fg);
padding: 0.25em 0.5em;
z-index: 2;
@media (min-width: $w-s) {
font-size: var(--f-u3);
}
+ .role {
margin-left: 1em;
}
&:nth-of-type(1) {
.invert {
background-color: var(--c-pink);
}
}
&:nth-of-type(2) {
.invert {
background-color: var(--c-blue);
}
}
&:nth-of-type(3) {
.invert {
background-color: var(--c-green);
}
}
&:hover {
.invert {
clip-path: polygon(0% 0%, 100% 0%, 100% 100%, 0% 100%);
}
}
}
.invert {
position: absolute;
color: var(--t-fg);
display: flex;
align-items: center;
justify-content: center;
width: 100%;
height: 100%;
top: 0;
left: 0;
pointer-events: none;
clip-path: polygon(0% 100%, 100% 100%, 100% 200%, 0% 200%);
transition: clip-path cubic-bezier(0.4, 0, 0.5, 1) 150ms;
}
.desc {
font-size: var(--f-u2);
margin-top: 1.5rem;
margin-bottom: 0;
}
.subtitle {
display: block;
font-weight: 400;
font-size: var(--f-d6);
letter-spacing: -0.0625em;
}
.bio {
line-height: 2;
margin-bottom: 2rem;
> span:first-of-type {
line-height: 1;
margin-bottom: 0.5em;
display: block;
font-weight: 700;
font-size: var(--f-u4);
}
}
</style>
</head> </head>
<body> <body>
<Nav /> Test
<header class="hero">
<img
width="1600"
height="1131"
class="img"
src="https://images.unsplash.com/photo-1469854523086-cc02fe5d8800?w=1200&q=75"
srcSet="https://images.unsplash.com/photo-1469854523086-cc02fe5d8800?w=1200&q=75 800w,
https://images.unsplash.com/photo-1469854523086-cc02fe5d8800?w=1200&q=75 1200w,
https://images.unsplash.com/photo-1469854523086-cc02fe5d8800?w=1600&q=75 1600w,
https://images.unsplash.com/photo-1469854523086-cc02fe5d8800?w=2400&q=75 2400w,"
sizes="(max-width: 800px) 800px, (max-width: 1200px) 1200px, (max-width: 1600px) 1600px, (max-width: 2400px) 2400px, 1200px"
/>
<div class="gradient" />
<div class="gradient2" />
<div class="overlay">
<h1 class="title">
<small class="subtitle">The personal site of </small>Jeanine White
</h1>
<div>
<span class="role">
👩‍💻 Developer <span class="invert">👩‍💻 Developer</span>
</span>&nbsp;
<span class="role">
🎤 Speaker <span class="invert">🎤 Speaker</span>
</span>&nbsp;
<span class="role">
✏️ Writer <span class="invert">✏️ Writer</span>
</span>
</div>
<p class="desc">Lover of dogs, roadtrips, and poetry.</p>
</div>
</header>
<main class="wrapper mt4 mb4">
<div class="grid">
<div class="section">
<h3 class="sectionTitle">Selected Work</h3>
<PorfolioPreview project={featuredProject} />
<div class="tac mt4">
<a href="/projects">
<Button>View All</Button>
</a>
</div>
</div>
<div class="section">
<h3 class="sectionTitle">About me</h3>
<p class="bio">
<span>Hello!</span> Im Jeanine, and this is my website. It was made using{' '}
<a href="https://github.com/snowpackjs/astro" target="_blank" rel="nofollow">
Astro
</a>
, a new way to build static sites. This is just an example template for you to modify.
</p>
<p>
<a href="/about">Read more</a>
</p>
</div>
</div>
</main>
<Footer />
</body> </body>
</html> </html>

View file

@ -12,7 +12,7 @@
"build": "yarn build:core", "build": "yarn build:core",
"build:all": "lerna run build", "build:all": "lerna run build",
"build:one": "lerna run build --scope", "build:one": "lerna run build --scope",
"build:core": "lerna run build --scope astro --scope @astrojs/parser --scope @astrojs/markdown-support --scope create-astro", "build:core": "lerna run build --scope astro --scope @astrojs/parser --scope @astrojs/markdown-support",
"build:vscode": "lerna run build --scope astro-languageserver --scope astro-vscode --scope @astrojs/parser", "build:vscode": "lerna run build --scope astro-languageserver --scope astro-vscode --scope @astrojs/parser",
"dev:vscode": "lerna run dev --scope astro-languageserver --scope astro-vscode --scope @astrojs/parser --parallel --stream", "dev:vscode": "lerna run dev --scope astro-languageserver --scope astro-vscode --scope @astrojs/parser --parallel --stream",
"format": "prettier -w \"**/*.{js,jsx,ts,tsx,md,json}\"", "format": "prettier -w \"**/*.{js,jsx,ts,tsx,md,json}\"",

View file

@ -170,7 +170,7 @@ For fetching from a remote API, use a native JavaScript `fetch()` ([docs][fetch-
const remoteData = await fetch('https://api.mysite.com/v1/people').then((res) => res.json()); const remoteData = await fetch('https://api.mysite.com/v1/people').then((res) => res.json());
// Example 2: load local markdown files // Example 2: load local markdown files
const localData = Astro.fetchContent('../post/*.md'); const localData = await Astro.fetchContent(import.meta.glob('../post/*.md'));
--- ---
``` ```

View file

@ -51,7 +51,6 @@
"@babel/code-frame": "^7.12.13", "@babel/code-frame": "^7.12.13",
"@babel/generator": "^7.13.9", "@babel/generator": "^7.13.9",
"@babel/parser": "^7.13.15", "@babel/parser": "^7.13.15",
"@babel/traverse": "^7.13.15",
"@snowpack/plugin-postcss": "^1.4.3", "@snowpack/plugin-postcss": "^1.4.3",
"@snowpack/plugin-sass": "^1.4.0", "@snowpack/plugin-sass": "^1.4.0",
"acorn": "^7.4.0", "acorn": "^7.4.0",

View file

@ -1,58 +0,0 @@
import path from 'path';
import glob from 'tiny-glob/sync.js';
import slash from 'slash';
/**
* Handling for import.meta.glob and import.meta.globEager
*/
interface GlobOptions {
namespace: string;
filename: string;
}
interface GlobResult {
/** Array of import statements to inject */
imports: Set<string>;
/** Replace original code with */
code: string;
}
/** General glob handling */
function globSearch(spec: string, { filename }: { filename: string }): string[] {
try {
const cwd = path.dirname(filename);
let found = glob(spec, { cwd, filesOnly: true });
if (!found.length) {
throw new Error(`No files matched "${spec}" from ${filename}`);
}
return found.map((f) => slash(f[0] === '.' ? f : `./${f}`));
} catch (err) {
throw new Error(`No files matched "${spec}" from ${filename}`);
}
}
/** Astro.fetchContent() */
export function fetchContent(spec: string, { namespace, filename }: GlobOptions): GlobResult {
let code = '';
const imports = new Set<string>();
const importPaths = globSearch(spec, { filename });
// gather imports
importPaths.forEach((importPath, j) => {
const id = `${namespace}_${j}`;
imports.add(`import { __content as ${id} } from '${importPath}';`);
// add URL if this appears within the /pages/ directory (probably can be improved)
const fullPath = path.resolve(path.dirname(filename), importPath);
if (fullPath.includes(`${path.sep}pages${path.sep}`)) {
const url = importPath.replace(/^\./, '').replace(/\.md$/, '');
imports.add(`${id}.url = '${url}';`);
}
});
// generate replacement code
code += `${namespace} = [${importPaths.map((_, j) => `${namespace}_${j}`).join(',')}];\n`;
return { imports, code };
}

View file

@ -12,10 +12,7 @@ import { walk, asyncWalk } from 'estree-walker';
import _babelGenerator from '@babel/generator'; import _babelGenerator from '@babel/generator';
import babelParser from '@babel/parser'; import babelParser from '@babel/parser';
import { codeFrameColumns } from '@babel/code-frame'; import { codeFrameColumns } from '@babel/code-frame';
import * as babelTraverse from '@babel/traverse';
import { error, warn, parseError } from '../../logger.js'; import { error, warn, parseError } from '../../logger.js';
import { fetchContent } from './content.js';
import { isFetchContent } from './utils.js';
import { yellow } from 'kleur/colors'; import { yellow } from 'kleur/colors';
import { isComponentTag, isCustomElementTag, positionAt } from '../utils.js'; import { isComponentTag, isCustomElementTag, positionAt } from '../utils.js';
import { renderMarkdown } from '@astrojs/markdown-support'; import { renderMarkdown } from '@astrojs/markdown-support';
@ -26,8 +23,6 @@ import { nodeBuiltinsSet } from '../../node_builtins.js';
import { readFileSync } from 'fs'; import { readFileSync } from 'fs';
import { pathToFileURL } from 'url'; import { pathToFileURL } from 'url';
const traverse: typeof babelTraverse.default = (babelTraverse.default as any).default;
// @ts-ignore // @ts-ignore
const babelGenerator: typeof _babelGenerator = _babelGenerator.default; const babelGenerator: typeof _babelGenerator = _babelGenerator.default;
const { transformSync } = esbuild; const { transformSync } = esbuild;
@ -322,11 +317,9 @@ function compileModule(ast: Ast, module: Script, state: CodegenState, compileOpt
const componentImports: ImportDeclaration[] = []; const componentImports: ImportDeclaration[] = [];
const componentProps: VariableDeclarator[] = []; const componentProps: VariableDeclarator[] = [];
const componentExports: ExportNamedDeclaration[] = []; const componentExports: ExportNamedDeclaration[] = [];
const contentImports = new Map<string, { spec: string; declarator: string }>();
let script = ''; let script = '';
let propsStatement = ''; let propsStatement = '';
let contentCode = ''; // code for handling Astro.fetchContent(), if any;
let createCollection = ''; // function for executing collection let createCollection = ''; // function for executing collection
if (module) { if (module) {
@ -387,37 +380,11 @@ function compileModule(ast: Ast, module: Script, state: CodegenState, compileOpt
break; break;
} }
case 'VariableDeclaration': { case 'VariableDeclaration': {
// Support frontmatter-defined components
for (const declaration of node.declarations) { for (const declaration of node.declarations) {
// only select Astro.fetchContent() calls for more processing,
// otherwise just push name to declarations
if (!isFetchContent(declaration)) {
if (declaration.id.type === 'Identifier') { if (declaration.id.type === 'Identifier') {
state.declarations.add(declaration.id.name); state.declarations.add(declaration.id.name);
} }
continue;
}
// remove node
body.splice(i, 1);
// a bit of munging
let { id, init } = declaration;
if (!id || !init || id.type !== 'Identifier') continue;
if (init.type === 'AwaitExpression') {
init = init.argument;
const shortname = path.posix.relative(compileOptions.astroConfig.projectRoot.pathname, state.filename);
warn(compileOptions.logging, shortname, yellow('awaiting Astro.fetchContent() not necessary'));
}
if (init.type !== 'CallExpression') continue;
// gather data
const namespace = id.name;
if ((init as any).arguments[0].type !== 'StringLiteral') {
throw new Error(`[Astro.fetchContent] Only string literals allowed, ex: \`Astro.fetchContent('./post/*.md')\`\n ${state.filename}`);
}
const spec = (init as any).arguments[0].value;
if (typeof spec === 'string') contentImports.set(namespace, { spec, declarator: node.kind });
} }
break; break;
} }
@ -466,64 +433,7 @@ const { ${props.join(', ')} } = Astro.props;\n`)
); );
} }
// handle createCollection, if any script = propsStatement + babelGenerator(program).code;
if (createCollection) {
const ast = babelParser.parse(createCollection, {
sourceType: 'module',
});
traverse(ast, {
enter({ node }) {
switch (node.type) {
case 'VariableDeclaration': {
for (const declaration of node.declarations) {
// only select Astro.fetchContent() calls here. this utility filters those out for us.
if (!isFetchContent(declaration)) continue;
// a bit of munging
let { id, init } = declaration;
if (!id || !init || id.type !== 'Identifier') continue;
if (init.type === 'AwaitExpression') {
init = init.argument;
const shortname = path.relative(compileOptions.astroConfig.projectRoot.pathname, state.filename);
warn(compileOptions.logging, shortname, yellow('awaiting Astro.fetchContent() not necessary'));
}
if (init.type !== 'CallExpression') continue;
// gather data
const namespace = id.name;
if ((init as any).arguments[0].type !== 'StringLiteral') {
throw new Error(`[Astro.fetchContent] Only string literals allowed, ex: \`Astro.fetchContent('./post/*.md')\`\n ${state.filename}`);
}
const spec = (init as any).arguments[0].value;
if (typeof spec !== 'string') break;
const globResult = fetchContent(spec, { namespace, filename: state.filename });
let imports = '';
for (const importStatement of globResult.imports) {
imports += importStatement + '\n';
}
createCollection = imports + createCollection.substring(0, declaration.start || 0) + globResult.code + createCollection.substring(declaration.end || 0);
}
break;
}
}
},
});
}
// Astro.fetchContent()
for (const [namespace, { spec }] of contentImports.entries()) {
const globResult = fetchContent(spec, { namespace, filename: state.filename });
for (const importStatement of globResult.imports) {
state.importStatements.add(importStatement);
}
contentCode += globResult.code;
}
script = propsStatement + contentCode + babelGenerator(program).code;
const location = { start: module.start, end: module.end }; const location = { start: module.start, end: module.end };
let transpiledScript = transpileExpressionSafe(script, { state, compileOptions, location }); let transpiledScript = transpileExpressionSafe(script, { state, compileOptions, location });
if (transpiledScript === null) throw new Error(`Unable to compile script`); if (transpiledScript === null) throw new Error(`Unable to compile script`);

View file

@ -2,7 +2,7 @@
* Codegen utils * Codegen utils
*/ */
import type { VariableDeclarator } from '@babel/types'; import type { VariableDeclarator, CallExpression } from '@babel/types';
/** Is this an import.meta.* built-in? You can pass an optional 2nd param to see if the name matches as well. */ /** Is this an import.meta.* built-in? You can pass an optional 2nd param to see if the name matches as well. */
export function isImportMetaDeclaration(declaration: VariableDeclarator, metaName?: string): boolean { export function isImportMetaDeclaration(declaration: VariableDeclarator, metaName?: string): boolean {
@ -18,22 +18,3 @@ export function isImportMetaDeclaration(declaration: VariableDeclarator, metaNam
if (metaName && (init.callee.property.type !== 'Identifier' || init.callee.property.name !== metaName)) return false; if (metaName && (init.callee.property.type !== 'Identifier' || init.callee.property.name !== metaName)) return false;
return true; return true;
} }
/** Is this an Astro.fetchContent() call? */
export function isFetchContent(declaration: VariableDeclarator): boolean {
let { init } = declaration;
if (!init) return false; // definitely not import.meta
// this could be `await import.meta`; if so, evaluate that:
if (init.type === 'AwaitExpression') {
init = init.argument;
}
// continue evaluating
if (
init.type !== 'CallExpression' ||
init.callee.type !== 'MemberExpression' ||
(init.callee.object as any).name !== 'Astro' ||
(init.callee.property as any).name !== 'fetchContent'
)
return false;
return true;
}

View file

@ -114,8 +114,21 @@ export async function compileComponent(source: string, { compileOptions, filenam
let moduleJavaScript = ` let moduleJavaScript = `
import fetch from 'node-fetch'; import fetch from 'node-fetch';
// <script astro></script> ${/* Global Astro Namespace (shadowed & extended by the scoped namespace inside of __render()) */''}
const Astro = {
site: new URL('/', ${JSON.stringify(site)}),
async fetchContent(importMetaGlobResult) {
const {fetchContent: fetchContentInternal} = await import('astro/dist/internal/fetch-content.js');
return fetchContentInternal(importMetaGlobResult, import.meta.url);
},
};
const __Astro = Astro;
// Frontmatter Script
${result.imports.join('\n')} ${result.imports.join('\n')}
${result.script}
${ ${
result.hasCustomElements result.hasCustomElements
? ` ? `
@ -131,19 +144,24 @@ const __astro_element_registry = new AstroElementRegistry({
// \`__render()\`: Render the contents of the Astro module. // \`__render()\`: Render the contents of the Astro module.
import { h, Fragment } from 'astro/dist/internal/h.js'; import { h, Fragment } from 'astro/dist/internal/h.js';
const __astroInternal = Symbol('astro.internal'); const __astroInternal = Symbol('astro.internal');
async function __render(props, ...children) { async function __render($props, ...children) {
const Astro = { const Astro = {
props, ...__Astro,
site: new URL('/', ${JSON.stringify(site)}), // props,
css: props[__astroInternal]?.css || [], css: $props[__astroInternal]?.css || [],
request: props[__astroInternal]?.request || {}, request: $props[__astroInternal]?.request || {},
isPage: props[__astroInternal]?.isPage || false isPage: $props[__astroInternal]?.isPage || false,
}; };
${result.script} const $state = typeof __state !== 'undefined' ? __state({props: $props}) : {};
console.log('$state', $state);
return h(Fragment, null, ${result.html}); return h(Fragment, null, ${result.html});
} }
export default { isAstroComponent: true, __render }; export default {
isAstroComponent: true,
__render
};
${result.createCollection || ''} ${result.createCollection || ''}
@ -181,10 +199,9 @@ export async function __renderPage({request, children, props, css}) {
return childBodyResult; return childBodyResult;
}; };
${result.exports.join('\n')}
`; `;
console.log(moduleJavaScript);
return { return {
result, result,
contents: moduleJavaScript, contents: moduleJavaScript,

View file

@ -0,0 +1,22 @@
export async function fetchContent(importMetaGlobResult: Record<string, () => Promise<any>>, url: string) {
if (typeof importMetaGlobResult === 'string') {
throw new Error(`[deprecated] "Astro.fetchContent(str)" is now "await Astro.fetchContent(import[dot]meta[dot]glob(str))"`);
}
const allImporters = [...Object.entries(importMetaGlobResult)];
const allImports = await Promise.all(allImporters.map(([spec, imp]) => {
return imp().then(mod => {
if (!mod.__content) {
return;
}
const urlSpec = new URL(spec, url).pathname.replace(/[\\/\\\\]/, '/');
if (!urlSpec.includes('/pages/')) {
return mod.__content;
}
return {
...mod.__content,
url: urlSpec.replace(/^.*\/pages\//, '/').replace(/\.md$/, ''),
};
});
}));
return allImports.filter(Boolean);
}

View file

@ -2,7 +2,7 @@
const { collection } = Astro.props; const { collection } = Astro.props;
export async function createCollection() { export async function createCollection() {
const allPosts = Astro.fetchContent('./post/**/*.md'); const allPosts = await Astro.fetchContent(import.meta.glob('./post/**/*.md'));
const allAuthors = allPosts.map(p => p.author); const allAuthors = allPosts.map(p => p.author);
const uniqueAuthors = [...new Set(allAuthors)]; const uniqueAuthors = [...new Set(allAuthors)];

View file

@ -2,7 +2,7 @@
const { collection } = Astro.props; const { collection } = Astro.props;
export async function createCollection() { export async function createCollection() {
const allPosts = Astro.fetchContent('./post/*.md'); const allPosts = await Astro.fetchContent(import.meta.glob('./post/*.md'));
return { return {
routes: allPosts.map((post, i) => { routes: allPosts.map((post, i) => {

View file

@ -4,7 +4,7 @@ const { collection } = Astro.props;
export async function createCollection() { export async function createCollection() {
return { return {
async data() { async data() {
let data = Astro.fetchContent('./post/**/*.md'); let data = await Astro.fetchContent(import.meta.glob('./post/**/*.md'));
data.sort((a, b) => new Date(b.date) - new Date(a.date)); data.sort((a, b) => new Date(b.date) - new Date(a.date));
return data; return data;
}, },

View file

@ -4,7 +4,7 @@ const { collection } = Astro.props;
export async function createCollection() { export async function createCollection() {
return { return {
async data() { async data() {
let data = Astro.fetchContent('./post/**/*.md'); let data = await Astro.fetchContent(import.meta.glob('./post/**/*.md'));
data.sort((a, b) => new Date(b.date) - new Date(a.date)); data.sort((a, b) => new Date(b.date) - new Date(a.date));
return data; return data;
} }

View file

@ -4,7 +4,7 @@ const { collection } = Astro.props;
export async function createCollection() { export async function createCollection() {
return { return {
async data() { async data() {
let data = Astro.fetchContent('./post/**/*.md'); let data = await Astro.fetchContent(import.meta.glob('./post/**/*.md'));
data.sort((a, b) => new Date(b.date) - new Date(a.date)); data.sort((a, b) => new Date(b.date) - new Date(a.date));
return data; return data;
}, },

View file

@ -4,7 +4,7 @@ const { collection } = Astro.props;
export async function createCollection() { export async function createCollection() {
return { return {
async data() { async data() {
let data = Astro.fetchContent('./post/*.md'); let data = await Astro.fetchContent(import.meta.glob('./post/*.md'));
data.sort((a, b) => new Date(b.date) - new Date(a.date)); data.sort((a, b) => new Date(b.date) - new Date(a.date));
return data; return data;
}, },

View file

@ -4,7 +4,7 @@ const { collection } = Astro.props;
export function createCollection() { export function createCollection() {
return { return {
async data() { async data() {
const data = Astro.fetchContent('./post/*.md'); const data = await Astro.fetchContent(import.meta.glob('./post/*.md'));
return data; return data;
}, },
pageSize: 1, pageSize: 1,

View file

@ -4,7 +4,7 @@ const { collection } = Astro.props;
export async function createCollection() { export async function createCollection() {
return { return {
async data() { async data() {
const episodes = Astro.fetchContent('./episode/*.md'); const episodes = await Astro.fetchContent(import.meta.glob('./episode/*.md'));
episodes.sort((a, b) => new Date(b.pubDate) - new Date(a.pubDate)); episodes.sort((a, b) => new Date(b.pubDate) - new Date(a.pubDate));
return episodes; return episodes;
}, },

View file

@ -76,7 +76,7 @@
dependencies: dependencies:
"@babel/highlight" "^7.12.13" "@babel/highlight" "^7.12.13"
"@babel/generator@^7.13.9", "@babel/generator@^7.14.2": "@babel/generator@^7.13.9":
version "7.14.3" version "7.14.3"
resolved "https://registry.npmjs.org/@babel/generator/-/generator-7.14.3.tgz" resolved "https://registry.npmjs.org/@babel/generator/-/generator-7.14.3.tgz"
integrity sha512-bn0S6flG/j0xtQdz3hsjJ624h3W0r3llttBMfyHX3YrZ/KtLYr15bjA0FXkgW7FpvrDuTuElXeVjiKlYRpnOFA== integrity sha512-bn0S6flG/j0xtQdz3hsjJ624h3W0r3llttBMfyHX3YrZ/KtLYr15bjA0FXkgW7FpvrDuTuElXeVjiKlYRpnOFA==
@ -85,29 +85,6 @@
jsesc "^2.5.1" jsesc "^2.5.1"
source-map "^0.5.0" source-map "^0.5.0"
"@babel/helper-function-name@^7.14.2":
version "7.14.2"
resolved "https://registry.npmjs.org/@babel/helper-function-name/-/helper-function-name-7.14.2.tgz"
integrity sha512-NYZlkZRydxw+YT56IlhIcS8PAhb+FEUiOzuhFTfqDyPmzAhRge6ua0dQYT/Uh0t/EDHq05/i+e5M2d4XvjgarQ==
dependencies:
"@babel/helper-get-function-arity" "^7.12.13"
"@babel/template" "^7.12.13"
"@babel/types" "^7.14.2"
"@babel/helper-get-function-arity@^7.12.13":
version "7.12.13"
resolved "https://registry.npmjs.org/@babel/helper-get-function-arity/-/helper-get-function-arity-7.12.13.tgz"
integrity sha512-DjEVzQNz5LICkzN0REdpD5prGoidvbdYk1BVgRUOINaWJP2t6avB27X1guXK1kXNrX0WMfsrm1A/ZBthYuIMQg==
dependencies:
"@babel/types" "^7.12.13"
"@babel/helper-split-export-declaration@^7.12.13":
version "7.12.13"
resolved "https://registry.npmjs.org/@babel/helper-split-export-declaration/-/helper-split-export-declaration-7.12.13.tgz"
integrity sha512-tCJDltF83htUtXx5NLcaDqRmknv652ZWCHyoTETf1CXYJdPC7nohZohjUgieXhv0hTJdRf2FjDueFehdNucpzg==
dependencies:
"@babel/types" "^7.12.13"
"@babel/helper-validator-identifier@^7.14.0": "@babel/helper-validator-identifier@^7.14.0":
version "7.14.0" version "7.14.0"
resolved "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.14.0.tgz" resolved "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.14.0.tgz"
@ -122,7 +99,7 @@
chalk "^2.0.0" chalk "^2.0.0"
js-tokens "^4.0.0" js-tokens "^4.0.0"
"@babel/parser@*", "@babel/parser@^7.12.0", "@babel/parser@^7.12.13", "@babel/parser@^7.13.15", "@babel/parser@^7.13.9", "@babel/parser@^7.14.2": "@babel/parser@*", "@babel/parser@^7.12.0", "@babel/parser@^7.13.15", "@babel/parser@^7.13.9":
version "7.14.3" version "7.14.3"
resolved "https://registry.npmjs.org/@babel/parser/-/parser-7.14.3.tgz" resolved "https://registry.npmjs.org/@babel/parser/-/parser-7.14.3.tgz"
integrity sha512-7MpZDIfI7sUC5zWo2+foJ50CSI5lcqDehZ0lVgIhSi4bFEk94fLAKlF3Q0nzSQQ+ca0lm+O6G9ztKVBeu8PMRQ== integrity sha512-7MpZDIfI7sUC5zWo2+foJ50CSI5lcqDehZ0lVgIhSi4bFEk94fLAKlF3Q0nzSQQ+ca0lm+O6G9ztKVBeu8PMRQ==
@ -134,30 +111,7 @@
dependencies: dependencies:
regenerator-runtime "^0.13.4" regenerator-runtime "^0.13.4"
"@babel/template@^7.12.13": "@babel/types@^7.0.0", "@babel/types@^7.12.0", "@babel/types@^7.13.0", "@babel/types@^7.14.0", "@babel/types@^7.14.2", "@babel/types@^7.3.0":
version "7.12.13"
resolved "https://registry.npmjs.org/@babel/template/-/template-7.12.13.tgz"
integrity sha512-/7xxiGA57xMo/P2GVvdEumr8ONhFOhfgq2ihK3h1e6THqzTAkHbkXgB0xI9yeTfIUoH3+oAeHhqm/I43OTbbjA==
dependencies:
"@babel/code-frame" "^7.12.13"
"@babel/parser" "^7.12.13"
"@babel/types" "^7.12.13"
"@babel/traverse@^7.13.15":
version "7.14.2"
resolved "https://registry.npmjs.org/@babel/traverse/-/traverse-7.14.2.tgz"
integrity sha512-TsdRgvBFHMyHOOzcP9S6QU0QQtjxlRpEYOy3mcCO5RgmC305ki42aSAmfZEMSSYBla2oZ9BMqYlncBaKmD/7iA==
dependencies:
"@babel/code-frame" "^7.12.13"
"@babel/generator" "^7.14.2"
"@babel/helper-function-name" "^7.14.2"
"@babel/helper-split-export-declaration" "^7.12.13"
"@babel/parser" "^7.14.2"
"@babel/types" "^7.14.2"
debug "^4.1.0"
globals "^11.1.0"
"@babel/types@^7.0.0", "@babel/types@^7.12.0", "@babel/types@^7.12.13", "@babel/types@^7.13.0", "@babel/types@^7.14.0", "@babel/types@^7.14.2", "@babel/types@^7.3.0":
version "7.14.2" version "7.14.2"
resolved "https://registry.npmjs.org/@babel/types/-/types-7.14.2.tgz" resolved "https://registry.npmjs.org/@babel/types/-/types-7.14.2.tgz"
integrity sha512-SdjAG/3DikRHpUOjxZgnkbR11xUlyDMUFJdvnIgZEE16mqmY0BINMmc4//JMJglEmn6i7sq6p+mGrFWyZ98EEw== integrity sha512-SdjAG/3DikRHpUOjxZgnkbR11xUlyDMUFJdvnIgZEE16mqmY0BINMmc4//JMJglEmn6i7sq6p+mGrFWyZ98EEw==
@ -4546,11 +4500,6 @@ global@^4.3.2:
min-document "^2.19.0" min-document "^2.19.0"
process "^0.11.10" process "^0.11.10"
globals@^11.1.0:
version "11.12.0"
resolved "https://registry.npmjs.org/globals/-/globals-11.12.0.tgz"
integrity sha512-WOBp/EEGUiIsJSp7wcv/y6MO+lV9UoncWqxuFfm8eBwzWNgyfBd6Gz+IeKQ9jCmyhoH99g15M3T+QaVHFjizVA==
globals@^12.1.0: globals@^12.1.0:
version "12.4.0" version "12.4.0"
resolved "https://registry.npmjs.org/globals/-/globals-12.4.0.tgz" resolved "https://registry.npmjs.org/globals/-/globals-12.4.0.tgz"