Skip to content

Commit

Permalink
Merge branch 'main' into feat/generic-page-plugin
Browse files Browse the repository at this point in the history
  • Loading branch information
natemoo-re authored Aug 2, 2022
2 parents ecc1736 + 9cc3a11 commit 7f09eee
Show file tree
Hide file tree
Showing 27 changed files with 477 additions and 62 deletions.
6 changes: 6 additions & 0 deletions .changeset/dull-radios-sparkle.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
'astro': patch
'@astrojs/mdx': patch
---

Fix MDX working with a ts config file
5 changes: 5 additions & 0 deletions .changeset/fifty-peas-admire.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@astrojs/mdx': minor
---

Add IDs to MDX headings and expose via getHeadings() export
5 changes: 5 additions & 0 deletions .changeset/seven-suits-sit.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"astro": patch
---

Do not send `body` with `HEAD` or `GET` requests when using `server` output.
5 changes: 5 additions & 0 deletions .changeset/weak-crabs-pump.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'astro': patch
---

Fix edge case with hoisted scripts and Tailwind during dev
2 changes: 1 addition & 1 deletion .gitpod.Dockerfile
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
FROM gitpod/workspace-node

# Install latest pnpm
RUN pnpm i -g pnpm
RUN curl -fsSL https://get.pnpm.io/install.sh | SHELL=`which bash` bash -

# Install deno in gitpod
RUN curl -fsSL https://deno.land/x/install/install.sh | sh
Expand Down
2 changes: 1 addition & 1 deletion .gitpod/gitpod-setup.sh
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ else
fi

# Wait for VSCode to be ready (port 23000)
gp await-port 23000 > /dev/null 2>&1
gp ports await 23000 > /dev/null 2>&1

echo "Loading example project:" $EXAMPLE_PROJECT

Expand Down
5 changes: 3 additions & 2 deletions packages/astro/src/core/app/node.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,11 @@ function createRequestFromNodeRequest(req: IncomingMessage, body?: Uint8Array):
let url = `http://${req.headers.host}${req.url}`;
let rawHeaders = req.headers as Record<string, any>;
const entries = Object.entries(rawHeaders);
const method = req.method || 'GET';
let request = new Request(url, {
method: req.method || 'GET',
method,
headers: new Headers(entries),
body,
body: ['HEAD', 'GET'].includes(method) ? null : body,
});
if (req.socket?.remoteAddress) {
Reflect.set(request, clientAddressSymbol, req.socket.remoteAddress);
Expand Down
85 changes: 55 additions & 30 deletions packages/astro/src/core/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import path from 'path';
import postcssrc from 'postcss-load-config';
import { BUNDLED_THEMES } from 'shiki';
import { fileURLToPath, pathToFileURL } from 'url';
import * as vite from 'vite';
import { mergeConfig as mergeViteConfig } from 'vite';
import { z } from 'zod';
import { LogOptions } from './logger/core.js';
Expand Down Expand Up @@ -413,6 +414,7 @@ export async function resolveConfigURL(
userConfigPath = /^\.*\//.test(flags.config) ? flags.config : `./${flags.config}`;
userConfigPath = fileURLToPath(new URL(userConfigPath, `file://${root}/`));
}

// Resolve config file path using Proload
// If `userConfigPath` is `undefined`, Proload will search for `astro.config.[cm]?[jt]s`
const configPath = await resolve('astro', {
Expand Down Expand Up @@ -447,21 +449,7 @@ export async function openConfig(configOptions: LoadConfigOptions): Promise<Open
);
}

// Automatically load config file using Proload
// If `userConfigPath` is `undefined`, Proload will search for `astro.config.[cm]?[jt]s`
let config;
try {
config = await load('astro', {
mustExist: !!userConfigPath,
cwd: root,
filePath: userConfigPath,
});
} catch (err) {
if (err instanceof ProloadError && flags.config) {
throw new Error(`Unable to resolve --config "${flags.config}"! Does the file exist?`);
}
throw err;
}
const config = await tryLoadConfig(configOptions, flags, userConfigPath, root);
if (config) {
userConfig = config.value;
userConfigPath = config.filePath;
Expand All @@ -483,6 +471,57 @@ export async function openConfig(configOptions: LoadConfigOptions): Promise<Open
};
}

interface TryLoadConfigResult {
value: Record<string, any>;
filePath?: string;
}

async function tryLoadConfig(
configOptions: LoadConfigOptions,
flags: CLIFlags,
userConfigPath: string | undefined,
root: string
): Promise<TryLoadConfigResult | undefined> {
try {
// Automatically load config file using Proload
// If `userConfigPath` is `undefined`, Proload will search for `astro.config.[cm]?[jt]s`
const config = await load('astro', {
mustExist: !!userConfigPath,
cwd: root,
filePath: userConfigPath,
});

return config as TryLoadConfigResult;
} catch (e) {
if (e instanceof ProloadError && flags.config) {
throw new Error(`Unable to resolve --config "${flags.config}"! Does the file exist?`);
}

const configURL = await resolveConfigURL(configOptions);
if (!configURL) {
throw e;
}

// Fallback to use Vite DevServer
const viteServer = await vite.createServer({
server: { middlewareMode: true, hmr: false },
appType: 'custom',
});
try {
const mod = await viteServer.ssrLoadModule(fileURLToPath(configURL));

if (mod?.default) {
return {
value: mod.default,
filePath: fileURLToPath(configURL),
};
}
} finally {
await viteServer.close();
}
}
}

/**
* Attempt to load an `astro.config.mjs` file
* @deprecated
Expand All @@ -500,21 +539,7 @@ export async function loadConfig(configOptions: LoadConfigOptions): Promise<Astr
);
}

// Automatically load config file using Proload
// If `userConfigPath` is `undefined`, Proload will search for `astro.config.[cm]?[jt]s`
let config;
try {
config = await load('astro', {
mustExist: !!userConfigPath,
cwd: root,
filePath: userConfigPath,
});
} catch (err) {
if (err instanceof ProloadError && flags.config) {
throw new Error(`Unable to resolve --config "${flags.config}"! Does the file exist?`);
}
throw err;
}
const config = await tryLoadConfig(configOptions, flags, userConfigPath, root);
if (config) {
userConfig = config.value;
}
Expand Down
9 changes: 9 additions & 0 deletions packages/astro/src/core/render/dev/vite.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import npath from 'path';
import vite from 'vite';
import { unwrapId } from '../../util.js';
import { STYLE_EXTENSIONS } from '../util.js';

/**
* List of file extensions signalling we can (and should) SSR ahead-of-time
Expand Down Expand Up @@ -36,13 +37,21 @@ export async function* crawlGraph(
}
if (id === entry.id) {
scanned.add(id);
const entryIsStyle = STYLE_EXTENSIONS.has(npath.extname(id));
for (const importedModule of entry.importedModules) {
// some dynamically imported modules are *not* server rendered in time
// to only SSR modules that we can safely transform, we check against
// a list of file extensions based on our built-in vite plugins
if (importedModule.id) {
// use URL to strip special query params like "?content"
const { pathname } = new URL(`file://${importedModule.id}`);
// If the entry is a style, skip any modules that are not also styles.
// Tools like Tailwind might add HMR dependencies as `importedModules`
// but we should skip them--they aren't really imported. Without this,
// every hoisted script in the project is added to every page!
if (entryIsStyle && !STYLE_EXTENSIONS.has(npath.extname(pathname))) {
continue;
}
if (fileExtensionsToSSR.has(npath.extname(pathname))) {
const mod = viteServer.moduleGraph.getModuleById(importedModule.id);
if (!mod?.ssrModule) {
Expand Down
2 changes: 1 addition & 1 deletion packages/integrations/cloudflare/README.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# @astrojs/cloudflare

An SSR adapter for use with Cloudflare Pages Functions targets. Write your code in Astro/Node and deploy to Cloudflare Pages.
An SSR adapter for use with Cloudflare Pages Functions targets. Write your code in Astro/Javascript and deploy to Cloudflare Pages.

In your `astro.config.mjs` use:

Expand Down
2 changes: 1 addition & 1 deletion packages/integrations/cloudflare/test/basics.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { loadFixture, runCLI } from './test-utils.js';
import { expect } from 'chai';
import * as cheerio from 'cheerio';

describe('Basic app', () => {
describe.skip('Basic app', () => {
/** @type {import('./test-utils').Fixture} */
let fixture;

Expand Down
37 changes: 35 additions & 2 deletions packages/integrations/mdx/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,24 @@ const posts = await Astro.glob('./*.mdx');
See [the official "how MDX works" guide](https://mdxjs.com/docs/using-mdx/#how-mdx-works) for more on MDX variables.
### Exported properties
Alongside your [MDX variable exports](#variables), we generate a few helpful exports as well. These are accessible when importing an MDX file via `import` statements or [`Astro.glob`](https://docs.astro.build/en/reference/api-reference/#astroglob).
#### `file`
The absolute path to the MDX file (e.g. `home/user/projects/.../file.md`).
#### `url`
The browser-ready URL for MDX files under `src/pages/`. For example, `src/pages/en/about.mdx` will provide a `url` of `/en/about/`. For MDX files outside of `src/pages`, `url` will be `undefined`.
#### `getHeadings()`
**Returns:** `{ depth: number; slug: string; text: string }[]`
A function that returns an array of all headings (i.e. `h1 -> h6` elements) in the MDX file. Each heading’s `slug` corresponds to the generated ID for a given heading and can be used for anchor links.
### Frontmatter
Astro also supports YAML-based frontmatter out-of-the-box using the [remark-mdx-frontmatter](https://github.com/remcohaszing/remark-mdx-frontmatter) plugin. By default, all variables declared in a frontmatter fence (`---`) will be accessible via the `frontmatter` export. See the `frontmatterOptions` configuration to customize this behavior.
Expand Down Expand Up @@ -279,11 +297,26 @@ export default {
<details>
<summary><strong>rehypePlugins</strong></summary>
**Default plugins:** none
**Default plugins:** [`collect-headings`](https://github.com/withastro/astro/blob/main/packages/integrations/mdx/src/rehype-collect-headings.ts)
[Rehype plugins](https://github.com/rehypejs/rehype/blob/main/doc/plugins.md) allow you to transform the HTML that your Markdown generates. We recommend checking the [Remark plugin](https://github.com/remarkjs/remark/blob/main/doc/plugins.md) catalog first _before_ considering rehype plugins, since most users want to transform their Markdown syntax instead. If HTML transforms are what you need, we encourage you to browse [awesome-rehype](https://github.com/rehypejs/awesome-rehype) for a full curated list of plugins!
To apply rehype plugins, use the `rehypePlugins` configuration option like so:
We apply our own [`collect-headings`](https://github.com/withastro/astro/blob/main/packages/integrations/mdx/src/rehype-collect-headings.ts) plugin by default. This applies IDs to all headings (i.e. `h1 -> h6`) in your MDX files to [link to headings via anchor tags](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/a#linking_to_an_element_on_the_same_page).
To apply rehype plugins _while preserving_ Astro's default plugins, use a nested `extends` object like so:
```js
// astro.config.mjs
import rehypeMinifyHtml from 'rehype-minify';
export default {
integrations: [mdx({
rehypePlugins: { extends: [rehypeMinifyHtml] },
})],
}
```
To apply plugins _without_ Astro's defaults, you can apply a plain array:
```js
// astro.config.mjs
Expand Down
5 changes: 5 additions & 0 deletions packages/integrations/mdx/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -33,8 +33,11 @@
"@astrojs/prism": "^0.6.1",
"@mdx-js/mdx": "^2.1.2",
"@mdx-js/rollup": "^2.1.1",
"acorn": "^8.8.0",
"es-module-lexer": "^0.10.5",
"github-slugger": "^1.4.0",
"gray-matter": "^4.0.3",
"mdast-util-mdx": "^2.0.0",
"prismjs": "^1.28.0",
"rehype-raw": "^6.1.1",
"remark-frontmatter": "^4.0.1",
Expand All @@ -53,7 +56,9 @@
"astro-scripts": "workspace:*",
"chai": "^4.3.6",
"linkedom": "^0.14.12",
"mdast-util-to-string": "^3.1.0",
"mocha": "^9.2.2",
"reading-time": "^1.5.0",
"remark-toc": "^8.0.1"
},
"engines": {
Expand Down
Loading

0 comments on commit 7f09eee

Please sign in to comment.