From d34859d75008812fcd101e197ce835bcc1ee2017 Mon Sep 17 00:00:00 2001 From: Nate Moore Date: Thu, 19 May 2022 10:49:14 -0500 Subject: [PATCH] Expose `file` and `url` for Astro files (#3385) * feat: update test * feat: return `file` and `url` for astro files * chore: add changeset * fix: use private names $$file and $$url * test: update markdown test * chore: update fileId logic to strip query params --- .changeset/quiet-pumpkins-hunt.md | 5 +++++ packages/astro/src/@types/astro.ts | 8 +++++++- packages/astro/src/vite-plugin-astro/index.ts | 3 +++ .../astro/src/vite-plugin-markdown/index.ts | 15 +++------------ packages/astro/src/vite-plugin-utils/index.ts | 17 +++++++++++++++++ packages/astro/test/astro-global.test.js | 9 ++++++++- .../fixtures/astro-global/src/pages/glob.astro | 17 +++++++++++++++++ .../astro-global/src/pages/post/post-3.astro | 1 + 8 files changed, 61 insertions(+), 14 deletions(-) create mode 100644 .changeset/quiet-pumpkins-hunt.md create mode 100644 packages/astro/src/vite-plugin-utils/index.ts create mode 100644 packages/astro/test/fixtures/astro-global/src/pages/glob.astro create mode 100644 packages/astro/test/fixtures/astro-global/src/pages/post/post-3.astro diff --git a/.changeset/quiet-pumpkins-hunt.md b/.changeset/quiet-pumpkins-hunt.md new file mode 100644 index 000000000..17cd703c2 --- /dev/null +++ b/.changeset/quiet-pumpkins-hunt.md @@ -0,0 +1,5 @@ +--- +'astro': patch +--- + +Expose `file` and `url` properties when fetching `.astro` files with `Astro.glob()` diff --git a/packages/astro/src/@types/astro.ts b/packages/astro/src/@types/astro.ts index 85e3d26c5..642fe9ffb 100644 --- a/packages/astro/src/@types/astro.ts +++ b/packages/astro/src/@types/astro.ts @@ -216,7 +216,7 @@ export interface AstroGlobalPartial { * * [Astro reference](https://docs.astro.build/en/reference/api-reference/#astroglob) */ - glob(globStr: `${any}.astro`): Promise; + glob(globStr: `${any}.astro`): Promise; glob>(globStr: `${any}.md`): Promise[]>; glob>(globStr: string): Promise; /** @@ -752,6 +752,12 @@ export interface ComponentInstance { getStaticPaths?: (options: GetStaticPathsOptions) => GetStaticPathsResult; } +export interface AstroInstance { + file: string; + url: string | undefined; + default: AstroComponentFactory; +} + export interface MarkdownInstance> { frontmatter: T; file: string; diff --git a/packages/astro/src/vite-plugin-astro/index.ts b/packages/astro/src/vite-plugin-astro/index.ts index b13b85494..4589adce5 100644 --- a/packages/astro/src/vite-plugin-astro/index.ts +++ b/packages/astro/src/vite-plugin-astro/index.ts @@ -14,6 +14,7 @@ import ancestor from 'common-ancestor-path'; import { trackCSSDependencies, handleHotUpdate } from './hmr.js'; import { isRelativePath, startsWithForwardSlash } from '../core/path.js'; import { PAGE_SCRIPT_ID, PAGE_SSR_SCRIPT_ID } from '../vite-plugin-scripts/index.js'; +import { getFileInfo } from '../vite-plugin-utils/index.js'; import { resolvePages } from '../core/util.js'; const FRONTMATTER_PARSE_REGEXP = /^\-\-\-(.*)^\-\-\-/ms; @@ -168,6 +169,7 @@ export default function astro({ config, logging }: AstroPluginOptions): vite.Plu try { const transformResult = await cachedCompilation(compileProps); + const { fileId: file, fileUrl: url } = getFileInfo(id, config); // Compile all TypeScript to JavaScript. // Also, catches invalid JS/TS in the compiled output before returning. @@ -180,6 +182,7 @@ export default function astro({ config, logging }: AstroPluginOptions): vite.Plu }); let SUFFIX = ''; + SUFFIX += `\nconst $$file = ${JSON.stringify(file)};\nconst $$url = ${JSON.stringify(url)};export { $$file as file, $$url as url };\n`; // Add HMR handling in dev mode. if (!resolvedConfig.isProduction) { // HACK: extract dependencies from metadata until compiler static extraction handles them diff --git a/packages/astro/src/vite-plugin-markdown/index.ts b/packages/astro/src/vite-plugin-markdown/index.ts index 8e702054d..9c7577fc3 100644 --- a/packages/astro/src/vite-plugin-markdown/index.ts +++ b/packages/astro/src/vite-plugin-markdown/index.ts @@ -9,8 +9,9 @@ import type { Plugin } from 'vite'; import type { AstroConfig } from '../@types/astro'; import { PAGE_SSR_SCRIPT_ID } from '../vite-plugin-scripts/index.js'; import { pagesVirtualModuleId } from '../core/app/index.js'; -import { appendForwardSlash, prependForwardSlash } from '../core/path.js'; +import { prependForwardSlash } from '../core/path.js'; import { resolvePages, viteID } from '../core/util.js'; +import { getFileInfo } from '../vite-plugin-utils/index.js'; interface AstroPluginOptions { config: AstroConfig; @@ -78,17 +79,7 @@ export default function markdown({ config }: AstroPluginOptions): Plugin { // Return the file's JS representation, including all Markdown // frontmatter and a deferred `import() of the compiled markdown content. if (id.endsWith(`.md${MARKDOWN_IMPORT_FLAG}`)) { - const sitePathname = appendForwardSlash( - config.site ? new URL(config.base, config.site).pathname : config.base - ); - - const fileId = id.replace(MARKDOWN_IMPORT_FLAG, ''); - let fileUrl = fileId.includes('/pages/') - ? fileId.replace(/^.*?\/pages\//, sitePathname).replace(/(\/index)?\.md$/, '') - : undefined; - if (fileUrl && config.trailingSlash === 'always') { - fileUrl = appendForwardSlash(fileUrl); - } + const { fileId, fileUrl } = getFileInfo(id, config); const source = await fs.promises.readFile(fileId, 'utf8'); const { data: frontmatter } = matter(source); diff --git a/packages/astro/src/vite-plugin-utils/index.ts b/packages/astro/src/vite-plugin-utils/index.ts new file mode 100644 index 000000000..d6ccd58b0 --- /dev/null +++ b/packages/astro/src/vite-plugin-utils/index.ts @@ -0,0 +1,17 @@ +import type { AstroConfig } from '../@types/astro'; +import { appendForwardSlash } from '../core/path.js'; + +export function getFileInfo(id: string, config: AstroConfig) { + const sitePathname = appendForwardSlash( + config.site ? new URL(config.base, config.site).pathname : config.base + ); + + const fileId = id.split('?')[0]; + let fileUrl = fileId.includes('/pages/') + ? fileId.replace(/^.*?\/pages\//, sitePathname).replace(/(\/index)?\.(md|astro)$/, '') + : undefined; + if (fileUrl && config.trailingSlash === 'always') { + fileUrl = appendForwardSlash(fileUrl); + } + return { fileId, fileUrl }; +} diff --git a/packages/astro/test/astro-global.test.js b/packages/astro/test/astro-global.test.js index 17520dacf..799f89071 100644 --- a/packages/astro/test/astro-global.test.js +++ b/packages/astro/test/astro-global.test.js @@ -2,7 +2,7 @@ import { expect } from 'chai'; import * as cheerio from 'cheerio'; import { loadFixture } from './test-utils.js'; -describe('Astro.*', () => { +describe('Astro Global', () => { let fixture; before(async () => { @@ -76,5 +76,12 @@ describe('Astro.*', () => { const $ = cheerio.load(html); expect($('.post-url').attr('href')).to.equal('/blog/post/post-2'); }); + + it('Astro.glob() correctly returns meta info for MD and Astro files', async () => { + const html = await fixture.readFile('/glob/index.html'); + const $ = cheerio.load(html); + expect($('[data-file]').length).to.equal(3); + expect($('.post-url[href]').length).to.equal(3); + }); }); }); diff --git a/packages/astro/test/fixtures/astro-global/src/pages/glob.astro b/packages/astro/test/fixtures/astro-global/src/pages/glob.astro new file mode 100644 index 000000000..cf237581a --- /dev/null +++ b/packages/astro/test/fixtures/astro-global/src/pages/glob.astro @@ -0,0 +1,17 @@ +--- +const data = await Astro.glob('./post/**/*'); +--- + + + + All Posts + + + {data.map((page: any) => ( +
+

Title

+ Read +
+ ))} + + diff --git a/packages/astro/test/fixtures/astro-global/src/pages/post/post-3.astro b/packages/astro/test/fixtures/astro-global/src/pages/post/post-3.astro new file mode 100644 index 000000000..31826b62d --- /dev/null +++ b/packages/astro/test/fixtures/astro-global/src/pages/post/post-3.astro @@ -0,0 +1 @@ +

Post 3