From 1acbcaba9e05ef376ba8f2e550a0ab5bbad35efe Mon Sep 17 00:00:00 2001 From: FredKSchott Date: Tue, 10 May 2022 12:02:57 +0000 Subject: [PATCH 01/22] [ci] collect stats --- scripts/stats/stats.csv | 1 + 1 file changed, 1 insertion(+) diff --git a/scripts/stats/stats.csv b/scripts/stats/stats.csv index a00a485c8b31..bd8b913fb017 100644 --- a/scripts/stats/stats.csv +++ b/scripts/stats/stats.csv @@ -1,4 +1,5 @@ Date,Commits (24hr),Issues (24hr),Issues:BUG (24hr),Issues:RFC (24hr),Issues:DOC (24hr),PRs (24hr),Open PRs,Open Issues,Bugs: Needs Triage,Bugs: Accepted,RFC: In Progress,RFC: Accepted,Date (ISO) +"Tuesday, May 10, 2022",0,2,2,0,0,0,16,136,96,35,0,0,"2022-05-10T12:02:52.912Z" "Monday, May 9, 2022",0,1,1,0,0,0,16,134,94,35,0,0,"2022-05-09T12:02:22.292Z" "Sunday, May 8, 2022",1,1,1,0,0,2,16,133,93,35,0,0,"2022-05-08T12:01:57.320Z" "Saturday, May 7, 2022",6,2,2,0,0,2,14,133,93,35,0,0,"2022-05-07T12:01:57.661Z" From d04928e8f20435cf69d1c171523aa152601cfe21 Mon Sep 17 00:00:00 2001 From: "Fred K. Schott" Date: Tue, 10 May 2022 14:54:01 -0600 Subject: [PATCH 02/22] rename dts to ts file (#3332) * rename dts to ts file * Create new-carrots-cough.md * add back missing types --- .changeset/new-carrots-cough.md | 5 +++++ packages/astro/src/core/build/{types.d.ts => types.ts} | 6 +++--- 2 files changed, 8 insertions(+), 3 deletions(-) create mode 100644 .changeset/new-carrots-cough.md rename packages/astro/src/core/build/{types.d.ts => types.ts} (85%) diff --git a/.changeset/new-carrots-cough.md b/.changeset/new-carrots-cough.md new file mode 100644 index 000000000000..3855009e9c8c --- /dev/null +++ b/.changeset/new-carrots-cough.md @@ -0,0 +1,5 @@ +--- +"astro": patch +--- + +Fix an `import from '../core/build/types';` error diff --git a/packages/astro/src/core/build/types.d.ts b/packages/astro/src/core/build/types.ts similarity index 85% rename from packages/astro/src/core/build/types.d.ts rename to packages/astro/src/core/build/types.ts index 30ea53901589..0d89c6c3052d 100644 --- a/packages/astro/src/core/build/types.d.ts +++ b/packages/astro/src/core/build/types.ts @@ -7,9 +7,9 @@ import type { ComponentInstance, SSRLoadedRenderer, } from '../../@types/astro'; -import type { ViteConfigWithSSR } from '../../create-vite'; -import type { LogOptions } from '../../logger'; -import type { RouteCache } from '../../render/route-cache.js'; +import type { LogOptions } from '../logger/core'; +import type { RouteCache } from '../render/route-cache'; +import type { ViteConfigWithSSR } from '../create-vite'; export type ComponentPath = string; export type ViteID = string; From e22f7364ceb3e4b057d89bbb32111bcffb7ae967 Mon Sep 17 00:00:00 2001 From: Tony Sullivan Date: Tue, 10 May 2022 21:05:30 +0000 Subject: [PATCH 03/22] Fixes custom 404 pages in astro dev (#3331) * Fixing pathname matching for custom 404 pages * fixes custom 404 routes in dev * refactor: removing node path dependency * refactor: using core's path utils --- .changeset/healthy-oranges-approve.md | 5 +++ .../src/vite-plugin-astro-server/index.ts | 3 +- packages/astro/test/custom-404.test.js | 41 +++++++++++++++++++ .../test/fixtures/custom-404/astro.config.mjs | 4 ++ .../test/fixtures/custom-404/package.json | 8 ++++ .../fixtures/custom-404/src/pages/404.astro | 12 ++++++ .../fixtures/custom-404/src/pages/index.astro | 11 +++++ pnpm-lock.yaml | 6 +++ 8 files changed, 89 insertions(+), 1 deletion(-) create mode 100644 .changeset/healthy-oranges-approve.md create mode 100644 packages/astro/test/custom-404.test.js create mode 100644 packages/astro/test/fixtures/custom-404/astro.config.mjs create mode 100644 packages/astro/test/fixtures/custom-404/package.json create mode 100644 packages/astro/test/fixtures/custom-404/src/pages/404.astro create mode 100644 packages/astro/test/fixtures/custom-404/src/pages/index.astro diff --git a/.changeset/healthy-oranges-approve.md b/.changeset/healthy-oranges-approve.md new file mode 100644 index 000000000000..69dc4a4508ea --- /dev/null +++ b/.changeset/healthy-oranges-approve.md @@ -0,0 +1,5 @@ +--- +'astro': patch +--- + +Fixes an issue preventing custom 404 pages in dev diff --git a/packages/astro/src/vite-plugin-astro-server/index.ts b/packages/astro/src/vite-plugin-astro-server/index.ts index 5c8cafd77cf9..bcbbfd35f139 100644 --- a/packages/astro/src/vite-plugin-astro-server/index.ts +++ b/packages/astro/src/vite-plugin-astro-server/index.ts @@ -3,6 +3,7 @@ import type http from 'http'; import type { AstroConfig, ManifestData } from '../@types/astro'; import type { RenderResponse, SSROptions } from '../core/render/dev/index'; import { debug, info, warn, error, LogOptions } from '../core/logger/core.js'; +import { appendForwardSlash } from '../core/path.js'; import { getParamsAndProps, GetParamsAndPropsError } from '../core/render/core.js'; import { createRouteManifest, matchRoute } from '../core/routing/index.js'; import stripAnsi from 'strip-ansi'; @@ -166,7 +167,7 @@ async function handle500Response( function getCustom404Route(config: AstroConfig, manifest: ManifestData) { const relPages = resolvePages(config).href.replace(config.root.href, ''); - return manifest.routes.find((r) => r.component === relPages + '404.astro'); + return manifest.routes.find((r) => r.component === appendForwardSlash(relPages) + '404.astro'); } function log404(logging: LogOptions, pathname: string) { diff --git a/packages/astro/test/custom-404.test.js b/packages/astro/test/custom-404.test.js new file mode 100644 index 000000000000..4651d7f20ee8 --- /dev/null +++ b/packages/astro/test/custom-404.test.js @@ -0,0 +1,41 @@ +import { expect } from 'chai'; +import * as cheerio from 'cheerio'; +import { loadFixture } from './test-utils.js'; + +describe('Custom 404', () => { + let fixture; + + before(async () => { + fixture = await loadFixture({ + root: './fixtures/custom-404/', + }); + }); + + describe('dev', () => { + let devServer; + let $; + + before(async () => { + devServer = await fixture.startDevServer(); + }); + + after(async () => { + await devServer.stop(); + }); + + it('renders /', async () => { + const html = await fixture.fetch('/').then((res) => res.text()); + $ = cheerio.load(html); + + expect($('h1').text()).to.equal('Home'); + }); + + it('renders 404 for /a', async () => { + const html = await fixture.fetch('/a').then((res) => res.text()); + $ = cheerio.load(html); + + expect($('h1').text()).to.equal('Page not found'); + expect($('p').text()).to.equal('/a/'); + }) + }); +}); diff --git a/packages/astro/test/fixtures/custom-404/astro.config.mjs b/packages/astro/test/fixtures/custom-404/astro.config.mjs new file mode 100644 index 000000000000..882e6515a67e --- /dev/null +++ b/packages/astro/test/fixtures/custom-404/astro.config.mjs @@ -0,0 +1,4 @@ +import { defineConfig } from 'astro/config'; + +// https://astro.build/config +export default defineConfig({}); diff --git a/packages/astro/test/fixtures/custom-404/package.json b/packages/astro/test/fixtures/custom-404/package.json new file mode 100644 index 000000000000..73ef4171b3a9 --- /dev/null +++ b/packages/astro/test/fixtures/custom-404/package.json @@ -0,0 +1,8 @@ +{ + "name": "@test/custom-404", + "version": "0.0.0", + "private": true, + "dependencies": { + "astro": "workspace:*" + } +} diff --git a/packages/astro/test/fixtures/custom-404/src/pages/404.astro b/packages/astro/test/fixtures/custom-404/src/pages/404.astro new file mode 100644 index 000000000000..85b800bc973f --- /dev/null +++ b/packages/astro/test/fixtures/custom-404/src/pages/404.astro @@ -0,0 +1,12 @@ +--- +--- + + + + Not Found - Custom 404 + + +

Page not found

+

{Astro.canonicalURL.pathname}

+ + diff --git a/packages/astro/test/fixtures/custom-404/src/pages/index.astro b/packages/astro/test/fixtures/custom-404/src/pages/index.astro new file mode 100644 index 000000000000..cf5ef9b586c6 --- /dev/null +++ b/packages/astro/test/fixtures/custom-404/src/pages/index.astro @@ -0,0 +1,11 @@ +--- +--- + + + + Custom 404 + + +

Home

+ + diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 436a7bf9b1c4..ef182ea3bcee 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -961,6 +961,12 @@ importers: dependencies: astro: link:../../.. + packages/astro/test/fixtures/custom-404: + specifiers: + astro: workspace:* + dependencies: + astro: link:../../.. + packages/astro/test/fixtures/custom-elements: specifiers: '@test/custom-element-renderer': workspace:* From 0913afb255522b6175c376f3b5398a1b76e9dd4a Mon Sep 17 00:00:00 2001 From: tony-sull Date: Tue, 10 May 2022 21:06:25 +0000 Subject: [PATCH 04/22] [ci] format --- packages/astro/test/custom-404.test.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/astro/test/custom-404.test.js b/packages/astro/test/custom-404.test.js index 4651d7f20ee8..099fa5aad87e 100644 --- a/packages/astro/test/custom-404.test.js +++ b/packages/astro/test/custom-404.test.js @@ -36,6 +36,6 @@ describe('Custom 404', () => { expect($('h1').text()).to.equal('Page not found'); expect($('p').text()).to.equal('/a/'); - }) + }); }); }); From be899fdd1a5408e41e63a5f7c8be7753a8fafda8 Mon Sep 17 00:00:00 2001 From: Tony Sullivan Date: Tue, 10 May 2022 21:59:56 +0000 Subject: [PATCH 05/22] Fixing mobile header for docs example (#3335) --- examples/docs/src/components/Header/Header.astro | 11 +++++++---- examples/docs/src/config.ts | 2 +- 2 files changed, 8 insertions(+), 5 deletions(-) diff --git a/examples/docs/src/components/Header/Header.astro b/examples/docs/src/components/Header/Header.astro index 7dcbb987d23f..ca787dc637e9 100644 --- a/examples/docs/src/components/Header/Header.astro +++ b/examples/docs/src/components/Header/Header.astro @@ -18,8 +18,8 @@ const lang = currentPage && getLanguageFromURL(currentPage); @@ -48,6 +48,7 @@ const lang = currentPage && getLanguageFromURL(currentPage); } .logo { + flex: 1; display: flex; overflow: hidden; width: 30px; @@ -61,6 +62,7 @@ const lang = currentPage && getLanguageFromURL(currentPage); } .logo a { + display: flex; padding: 0.5em 0.25em; margin: -0.5em -0.25em; text-decoration: none; @@ -78,6 +80,7 @@ const lang = currentPage && getLanguageFromURL(currentPage); } .logo h1 { + display: none; font: inherit; color: inherit; margin: 0; @@ -103,12 +106,12 @@ const lang = currentPage && getLanguageFromURL(currentPage); margin: 0; z-index: 0; } + .logo h1 { + display: initial; + } .menu-toggle { display: none; } - .logo { - width: auto; - } } /** Style Algolia */ diff --git a/examples/docs/src/config.ts b/examples/docs/src/config.ts index 537723f439e1..b81bf9b4fd6a 100644 --- a/examples/docs/src/config.ts +++ b/examples/docs/src/config.ts @@ -1,5 +1,5 @@ export const SITE = { - title: 'Your Documentation Website', + title: 'Documentation', description: 'Your website description.', defaultLanguage: 'en_US', }; From d67096ac0f989c9d988f6c05444ab89db1598580 Mon Sep 17 00:00:00 2001 From: "Fred K. Schott" Date: Tue, 10 May 2022 16:44:41 -0600 Subject: [PATCH 06/22] [ci] update github labeler --- .github/labeler.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/labeler.yml b/.github/labeler.yml index e6ec99206025..f3896ce670be 100644 --- a/.github/labeler.yml +++ b/.github/labeler.yml @@ -18,7 +18,7 @@ create-astro: markdown: - packages/markdown/** -renderer: +integration: - packages/integrations/** framework-lit: From 9ef92e0a3d604c479bb325eab073e7d3c896d388 Mon Sep 17 00:00:00 2001 From: "Fred K. Schott" Date: Tue, 10 May 2022 16:48:45 -0600 Subject: [PATCH 07/22] [ci] update github labeler --- .github/labeler.yml | 3 --- 1 file changed, 3 deletions(-) diff --git a/.github/labeler.yml b/.github/labeler.yml index f3896ce670be..185c6dd3ee4d 100644 --- a/.github/labeler.yml +++ b/.github/labeler.yml @@ -6,9 +6,6 @@ example: '🚨 action': - .github/workflows/** -test: -- packages/**/*.test.js - core: - packages/astro/** From 71f852cad908fe03d85112456df49f01b6709ba6 Mon Sep 17 00:00:00 2001 From: FredKSchott Date: Wed, 11 May 2022 12:04:20 +0000 Subject: [PATCH 08/22] [ci] collect stats --- scripts/stats/stats.csv | 1 + 1 file changed, 1 insertion(+) diff --git a/scripts/stats/stats.csv b/scripts/stats/stats.csv index bd8b913fb017..aa01e38eb74d 100644 --- a/scripts/stats/stats.csv +++ b/scripts/stats/stats.csv @@ -1,4 +1,5 @@ Date,Commits (24hr),Issues (24hr),Issues:BUG (24hr),Issues:RFC (24hr),Issues:DOC (24hr),PRs (24hr),Open PRs,Open Issues,Bugs: Needs Triage,Bugs: Accepted,RFC: In Progress,RFC: Accepted,Date (ISO) +"Wednesday, May 11, 2022",6,7,7,0,0,12,23,75,39,27,0,0,"2022-05-11T12:04:15.277Z" "Tuesday, May 10, 2022",0,2,2,0,0,0,16,136,96,35,0,0,"2022-05-10T12:02:52.912Z" "Monday, May 9, 2022",0,1,1,0,0,0,16,134,94,35,0,0,"2022-05-09T12:02:22.292Z" "Sunday, May 8, 2022",1,1,1,0,0,2,16,133,93,35,0,0,"2022-05-08T12:01:57.320Z" From 3dc68e148e05a36694cb5759f44cc5349bd66294 Mon Sep 17 00:00:00 2001 From: Pascal Schilp Date: Wed, 11 May 2022 16:53:53 +0200 Subject: [PATCH 09/22] fix: inject script for ssr mode (#3339) * fix: inject script for ssr mode * chore: changeset --- .changeset/heavy-adults-obey.md | 5 +++++ packages/astro/src/core/app/index.ts | 14 +++++++++++++- packages/astro/src/core/app/types.ts | 2 +- packages/astro/src/core/build/vite-plugin-ssr.ts | 2 +- 4 files changed, 20 insertions(+), 3 deletions(-) create mode 100644 .changeset/heavy-adults-obey.md diff --git a/.changeset/heavy-adults-obey.md b/.changeset/heavy-adults-obey.md new file mode 100644 index 000000000000..af35b58259bf --- /dev/null +++ b/.changeset/heavy-adults-obey.md @@ -0,0 +1,5 @@ +--- +'astro': patch +--- + +fixes injectscript in ssr mode diff --git a/packages/astro/src/core/app/index.ts b/packages/astro/src/core/app/index.ts index 261d8f385636..b963b5794450 100644 --- a/packages/astro/src/core/app/index.ts +++ b/packages/astro/src/core/app/index.ts @@ -78,7 +78,19 @@ export class App { const renderers = manifest.renderers; const info = this.#routeDataToRouteInfo.get(routeData!)!; const links = createLinkStylesheetElementSet(info.links, manifest.site); - const scripts = createModuleScriptElementWithSrcSet(info.scripts, manifest.site); + + const filteredScripts = info.scripts.filter(script => typeof script !== 'string' && script?.stage !== 'head-inline') as string[]; + const scripts = createModuleScriptElementWithSrcSet(filteredScripts, manifest.site); + + // Add all injected scripts to the page. + for (const script of info.scripts) { + if (typeof script !== 'string' && script.stage === 'head-inline') { + scripts.add({ + props: {}, + children: script.children, + }); + } + } const result = await render({ links, diff --git a/packages/astro/src/core/app/types.ts b/packages/astro/src/core/app/types.ts index aa44811416da..6a5b55760a5b 100644 --- a/packages/astro/src/core/app/types.ts +++ b/packages/astro/src/core/app/types.ts @@ -12,7 +12,7 @@ export interface RouteInfo { routeData: RouteData; file: string; links: string[]; - scripts: string[]; + scripts: Array; } export type SerializedRouteInfo = Omit & { diff --git a/packages/astro/src/core/build/vite-plugin-ssr.ts b/packages/astro/src/core/build/vite-plugin-ssr.ts index faf6a94d8189..38b30b3df611 100644 --- a/packages/astro/src/core/build/vite-plugin-ssr.ts +++ b/packages/astro/src/core/build/vite-plugin-ssr.ts @@ -109,7 +109,7 @@ function buildManifest( routes.push({ file: '', links: Array.from(pageData.css), - scripts, + scripts: [...scripts, ...astroConfig._ctx.scripts.filter(script => script.stage === 'head-inline').map(({stage, content}) => ({stage, children: content}))], routeData: serializeRouteData(pageData.route), }); } From 9c98ba81e1cde14a3772cbc9ee020956dae996e8 Mon Sep 17 00:00:00 2001 From: matthewp Date: Wed, 11 May 2022 14:54:52 +0000 Subject: [PATCH 10/22] [ci] format --- packages/astro/src/core/app/index.ts | 6 ++++-- packages/astro/src/core/app/types.ts | 2 +- packages/astro/src/core/build/vite-plugin-ssr.ts | 7 ++++++- 3 files changed, 11 insertions(+), 4 deletions(-) diff --git a/packages/astro/src/core/app/index.ts b/packages/astro/src/core/app/index.ts index b963b5794450..a53c1c06239a 100644 --- a/packages/astro/src/core/app/index.ts +++ b/packages/astro/src/core/app/index.ts @@ -78,8 +78,10 @@ export class App { const renderers = manifest.renderers; const info = this.#routeDataToRouteInfo.get(routeData!)!; const links = createLinkStylesheetElementSet(info.links, manifest.site); - - const filteredScripts = info.scripts.filter(script => typeof script !== 'string' && script?.stage !== 'head-inline') as string[]; + + const filteredScripts = info.scripts.filter( + (script) => typeof script !== 'string' && script?.stage !== 'head-inline' + ) as string[]; const scripts = createModuleScriptElementWithSrcSet(filteredScripts, manifest.site); // Add all injected scripts to the page. diff --git a/packages/astro/src/core/app/types.ts b/packages/astro/src/core/app/types.ts index 6a5b55760a5b..063f33b7fc3c 100644 --- a/packages/astro/src/core/app/types.ts +++ b/packages/astro/src/core/app/types.ts @@ -12,7 +12,7 @@ export interface RouteInfo { routeData: RouteData; file: string; links: string[]; - scripts: Array; + scripts: Array; } export type SerializedRouteInfo = Omit & { diff --git a/packages/astro/src/core/build/vite-plugin-ssr.ts b/packages/astro/src/core/build/vite-plugin-ssr.ts index 38b30b3df611..1a4a0d2911eb 100644 --- a/packages/astro/src/core/build/vite-plugin-ssr.ts +++ b/packages/astro/src/core/build/vite-plugin-ssr.ts @@ -109,7 +109,12 @@ function buildManifest( routes.push({ file: '', links: Array.from(pageData.css), - scripts: [...scripts, ...astroConfig._ctx.scripts.filter(script => script.stage === 'head-inline').map(({stage, content}) => ({stage, children: content}))], + scripts: [ + ...scripts, + ...astroConfig._ctx.scripts + .filter((script) => script.stage === 'head-inline') + .map(({ stage, content }) => ({ stage, children: content })), + ], routeData: serializeRouteData(pageData.route), }); } From 352fc3166fe3b3d3da3feff621394b20eacb9cc3 Mon Sep 17 00:00:00 2001 From: Pascal Schilp Date: Wed, 11 May 2022 17:13:23 +0200 Subject: [PATCH 11/22] Fix/netlify edge redirects (#3342) * fix: create redirects file for netlify edge adapter * chore: changeset * chore: distinguish between edge/regular --- .changeset/eighty-keys-explode.md | 5 +++ .../netlify/src/integration-edge-functions.ts | 2 ++ .../netlify/src/integration-functions.ts | 23 ++------------ packages/integrations/netlify/src/shared.ts | 31 +++++++++++++++++++ 4 files changed, 40 insertions(+), 21 deletions(-) create mode 100644 .changeset/eighty-keys-explode.md create mode 100644 packages/integrations/netlify/src/shared.ts diff --git a/.changeset/eighty-keys-explode.md b/.changeset/eighty-keys-explode.md new file mode 100644 index 000000000000..abd3707f6e8c --- /dev/null +++ b/.changeset/eighty-keys-explode.md @@ -0,0 +1,5 @@ +--- +'@astrojs/netlify': patch +--- + +create redirects file for netlify edge adapter diff --git a/packages/integrations/netlify/src/integration-edge-functions.ts b/packages/integrations/netlify/src/integration-edge-functions.ts index 08835bd261a5..0f28aeab5975 100644 --- a/packages/integrations/netlify/src/integration-edge-functions.ts +++ b/packages/integrations/netlify/src/integration-edge-functions.ts @@ -1,4 +1,5 @@ import type { AstroAdapter, AstroIntegration, AstroConfig, RouteData } from 'astro'; +import { createRedirects } from './shared.js'; import * as fs from 'fs'; export function getAdapter(): AstroAdapter { @@ -97,6 +98,7 @@ export function netlifyEdgeFunctions({ dist }: NetlifyEdgeFunctionsOptions = {}) }, 'astro:build:done': async ({ routes, dir }) => { await createEdgeManifest(routes, entryFile, _config.root); + await createRedirects(routes, dir, entryFile, true); }, }, }; diff --git a/packages/integrations/netlify/src/integration-functions.ts b/packages/integrations/netlify/src/integration-functions.ts index 2720eb591167..81cb7e9fd5ad 100644 --- a/packages/integrations/netlify/src/integration-functions.ts +++ b/packages/integrations/netlify/src/integration-functions.ts @@ -1,5 +1,5 @@ import type { AstroAdapter, AstroIntegration, AstroConfig } from 'astro'; -import fs from 'fs'; +import { createRedirects } from './shared.js'; export function getAdapter(): AstroAdapter { return { @@ -37,26 +37,7 @@ function netlifyFunctions({ dist }: NetlifyFunctionsOptions = {}): AstroIntegrat buildConfig.server = new URL('./functions/', _config.outDir); }, 'astro:build:done': async ({ routes, dir }) => { - const _redirectsURL = new URL('./_redirects', dir); - - // Create the redirects file that is used for routing. - let _redirects = ''; - for (const route of routes) { - if (route.pathname) { - _redirects += ` -${route.pathname} /.netlify/functions/${entryFile} 200`; - } else { - const pattern = - '/' + route.segments.map(([part]) => (part.dynamic ? '*' : part.content)).join('/'); - _redirects += ` -${pattern} /.netlify/functions/${entryFile} 200`; - } - } - - // Always use appendFile() because the redirects file could already exist, - // e.g. due to a `/public/_redirects` file that got copied to the output dir. - // If the file does not exist yet, appendFile() automatically creates it. - await fs.promises.appendFile(_redirectsURL, _redirects, 'utf-8'); + await createRedirects(routes, dir, entryFile, false); }, }, }; diff --git a/packages/integrations/netlify/src/shared.ts b/packages/integrations/netlify/src/shared.ts new file mode 100644 index 000000000000..3df667f4d55c --- /dev/null +++ b/packages/integrations/netlify/src/shared.ts @@ -0,0 +1,31 @@ +import type { RouteData } from 'astro'; +import fs from 'fs'; + +export async function createRedirects( + routes: RouteData[], + dir: URL, + entryFile: string, + edge: boolean + ) { + const _redirectsURL = new URL('./_redirects', dir); + const kind = edge ? 'edge-functions' : 'functions' + + // Create the redirects file that is used for routing. + let _redirects = ''; + for (const route of routes) { + if (route.pathname) { + _redirects += ` + ${route.pathname} /.netlify/${kind}/${entryFile} 200`; + } else { + const pattern = + '/' + route.segments.map(([part]) => (part.dynamic ? '*' : part.content)).join('/'); + _redirects += ` + ${pattern} /.netlify/${kind}/${entryFile} 200`; + } + } + + // Always use appendFile() because the redirects file could already exist, + // e.g. due to a `/public/_redirects` file that got copied to the output dir. + // If the file does not exist yet, appendFile() automatically creates it. + await fs.promises.appendFile(_redirectsURL, _redirects, 'utf-8'); +} \ No newline at end of file From efe4f1a3ef1679bfa2828bd5b63a494354864bc5 Mon Sep 17 00:00:00 2001 From: Yuji Sugiura Date: Thu, 12 May 2022 00:13:47 +0900 Subject: [PATCH 12/22] Fix GetStaticPathsOptions types (#3341) --- packages/astro/src/@types/astro.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/astro/src/@types/astro.ts b/packages/astro/src/@types/astro.ts index 8a04f21e94cf..117a1e257a7a 100644 --- a/packages/astro/src/@types/astro.ts +++ b/packages/astro/src/@types/astro.ts @@ -770,8 +770,8 @@ export type GetHydrateCallback = () => Promise< * getStaticPaths() options * Docs: https://docs.astro.build/reference/api-reference/#getstaticpaths */ export interface GetStaticPathsOptions { - paginate?: PaginateFunction; - rss?: (...args: any[]) => any; + paginate: PaginateFunction; + rss: (...args: any[]) => any; } export type GetStaticPathsItem = { params: Params; props?: Props }; From 3bb07a01e07d818b626c4adbd0a3ad41f1eba44b Mon Sep 17 00:00:00 2001 From: matthewp Date: Wed, 11 May 2022 15:14:43 +0000 Subject: [PATCH 13/22] [ci] format --- .../netlify/src/integration-functions.ts | 2 +- packages/integrations/netlify/src/shared.ts | 46 +++++++++---------- 2 files changed, 24 insertions(+), 24 deletions(-) diff --git a/packages/integrations/netlify/src/integration-functions.ts b/packages/integrations/netlify/src/integration-functions.ts index 81cb7e9fd5ad..b353220ced86 100644 --- a/packages/integrations/netlify/src/integration-functions.ts +++ b/packages/integrations/netlify/src/integration-functions.ts @@ -37,7 +37,7 @@ function netlifyFunctions({ dist }: NetlifyFunctionsOptions = {}): AstroIntegrat buildConfig.server = new URL('./functions/', _config.outDir); }, 'astro:build:done': async ({ routes, dir }) => { - await createRedirects(routes, dir, entryFile, false); + await createRedirects(routes, dir, entryFile, false); }, }, }; diff --git a/packages/integrations/netlify/src/shared.ts b/packages/integrations/netlify/src/shared.ts index 3df667f4d55c..90bd5333bbe9 100644 --- a/packages/integrations/netlify/src/shared.ts +++ b/packages/integrations/netlify/src/shared.ts @@ -2,30 +2,30 @@ import type { RouteData } from 'astro'; import fs from 'fs'; export async function createRedirects( - routes: RouteData[], - dir: URL, - entryFile: string, - edge: boolean - ) { - const _redirectsURL = new URL('./_redirects', dir); - const kind = edge ? 'edge-functions' : 'functions' + routes: RouteData[], + dir: URL, + entryFile: string, + edge: boolean +) { + const _redirectsURL = new URL('./_redirects', dir); + const kind = edge ? 'edge-functions' : 'functions'; - // Create the redirects file that is used for routing. - let _redirects = ''; - for (const route of routes) { - if (route.pathname) { - _redirects += ` + // Create the redirects file that is used for routing. + let _redirects = ''; + for (const route of routes) { + if (route.pathname) { + _redirects += ` ${route.pathname} /.netlify/${kind}/${entryFile} 200`; - } else { - const pattern = - '/' + route.segments.map(([part]) => (part.dynamic ? '*' : part.content)).join('/'); - _redirects += ` + } else { + const pattern = + '/' + route.segments.map(([part]) => (part.dynamic ? '*' : part.content)).join('/'); + _redirects += ` ${pattern} /.netlify/${kind}/${entryFile} 200`; - } - } + } + } - // Always use appendFile() because the redirects file could already exist, - // e.g. due to a `/public/_redirects` file that got copied to the output dir. - // If the file does not exist yet, appendFile() automatically creates it. - await fs.promises.appendFile(_redirectsURL, _redirects, 'utf-8'); -} \ No newline at end of file + // Always use appendFile() because the redirects file could already exist, + // e.g. due to a `/public/_redirects` file that got copied to the output dir. + // If the file does not exist yet, appendFile() automatically creates it. + await fs.promises.appendFile(_redirectsURL, _redirects, 'utf-8'); +} From ccea6a0a1ae55ab057d94f60014e2183013b5f60 Mon Sep 17 00:00:00 2001 From: Matthew Phillips Date: Wed, 11 May 2022 09:23:11 -0600 Subject: [PATCH 14/22] HMR hoisted scripts (#3336) * HMR hoisted scripts * Add to the dep graph * Remove example change * Adds changeset * Fix markdown test --- .changeset/happy-wasps-check.md | 5 +++ examples/minimal/src/pages/index.astro | 2 +- packages/astro/src/vite-plugin-astro/hmr.ts | 10 ++++++ packages/astro/src/vite-plugin-astro/index.ts | 31 ++++++++++++++----- .../astro/test/astro-markdown-css.test.js | 3 +- 5 files changed, 42 insertions(+), 9 deletions(-) create mode 100644 .changeset/happy-wasps-check.md diff --git a/.changeset/happy-wasps-check.md b/.changeset/happy-wasps-check.md new file mode 100644 index 000000000000..6fb90627b5a9 --- /dev/null +++ b/.changeset/happy-wasps-check.md @@ -0,0 +1,5 @@ +--- +'astro': patch +--- + +Fixes HMR of hoisted script tags diff --git a/examples/minimal/src/pages/index.astro b/examples/minimal/src/pages/index.astro index 25f796bf177b..346e155c4004 100644 --- a/examples/minimal/src/pages/index.astro +++ b/examples/minimal/src/pages/index.astro @@ -10,4 +10,4 @@

Astro

- \ No newline at end of file + diff --git a/packages/astro/src/vite-plugin-astro/hmr.ts b/packages/astro/src/vite-plugin-astro/hmr.ts index 4e194993e72b..2b11585ca484 100644 --- a/packages/astro/src/vite-plugin-astro/hmr.ts +++ b/packages/astro/src/vite-plugin-astro/hmr.ts @@ -68,6 +68,7 @@ export async function handleHotUpdate(ctx: HmrContext, config: AstroConfig, logg filtered.add(mod); files.add(mod.file); } + for (const imp of mod.importers) { if (imp.file && isCached(config, imp.file)) { filtered.add(imp); @@ -85,6 +86,15 @@ export async function handleHotUpdate(ctx: HmrContext, config: AstroConfig, logg // Bugfix: sometimes style URLs get normalized and end with `lang.css=` // These will cause full reloads, so filter them out here const mods = ctx.modules.filter((m) => !m.url.endsWith('=')); + + // Add hoisted scripts so these get invalidated + for(const mod of mods) { + for(const imp of mod.importedModules) { + if(imp.id?.includes('?astro&type=script')) { + mods.push(imp); + } + } + } const isSelfAccepting = mods.every((m) => m.isSelfAccepting || m.url.endsWith('.svelte')); const file = ctx.file.replace(config.root.pathname, '/'); diff --git a/packages/astro/src/vite-plugin-astro/index.ts b/packages/astro/src/vite-plugin-astro/index.ts index ea6f17dcdfe8..47ecfee1efbe 100644 --- a/packages/astro/src/vite-plugin-astro/index.ts +++ b/packages/astro/src/vite-plugin-astro/index.ts @@ -126,6 +126,12 @@ export default function astro({ config, logging }: AstroPluginOptions): vite.Plu if (typeof query.index === 'undefined') { throw new Error(`Requests for hoisted scripts must include an index`); } + // HMR hoisted script only exists to make them appear in the module graph. + if(opts?.ssr) { + return { + code: `/* client hoisted script, empty in SSR: ${id} */` + }; + } const transformResult = await cachedCompilation(config, filename, source, viteTransform, { ssr: Boolean(opts?.ssr), @@ -182,17 +188,28 @@ export default function astro({ config, logging }: AstroPluginOptions): vite.Plu while ((match = pattern.exec(metadata)?.[1])) { deps.add(match); } - // // import.meta.hot.accept(["${id}", "${Array.from(deps).join('","')}"], (...mods) => mods); - // We need to be self-accepting, AND - // we need an explicity array of deps to track changes for SSR-only components - SUFFIX += `\nif (import.meta.hot) { - import.meta.hot.accept(mod => mod); - }`; + + let i = 0; + while(i < transformResult.scripts.length) { + deps.add(`${id}?astro&type=script&index=${i}`); + SUFFIX += `import "${id}?astro&type=script&index=${i}";`; + i++; + } + + // We only need to define deps if there are any + if(deps.size > 1) { + SUFFIX += `\nif(import.meta.hot) import.meta.hot.accept(["${id}", "${Array.from(deps).join('","')}"], (...mods) => mods);` + } else { + SUFFIX += `\nif (import.meta.hot) { + import.meta.hot.accept(mod => mod); + }`; + } } // Add handling to inject scripts into each page JS bundle, if needed. if (isPage) { SUFFIX += `\nimport "${PAGE_SSR_SCRIPT_ID}";`; } + return { code: `${code}${SUFFIX}`, map, @@ -260,7 +277,7 @@ export default function astro({ config, logging }: AstroPluginOptions): vite.Plu }, async handleHotUpdate(context) { if (context.server.config.isProduction) return; - return handleHotUpdate(context, config, logging); + return handleHotUpdate.call(this, context, config, logging); }, }; } diff --git a/packages/astro/test/astro-markdown-css.test.js b/packages/astro/test/astro-markdown-css.test.js index 40710ce8528b..fcb1408f091a 100644 --- a/packages/astro/test/astro-markdown-css.test.js +++ b/packages/astro/test/astro-markdown-css.test.js @@ -34,11 +34,12 @@ describe('Imported markdown CSS', function () { }); describe('dev', () => { let devServer; + let html; let $; before(async () => { devServer = await fixture.startDevServer(); - const html = await fixture.fetch('/').then((res) => res.text()); + html = await fixture.fetch('/').then((res) => res.text()); $ = cheerio.load(html); }); From ce6d79828250e9a3631778a37d43068cae04bb4f Mon Sep 17 00:00:00 2001 From: "Fred K. Schott" Date: Wed, 11 May 2022 09:23:32 -0600 Subject: [PATCH 15/22] Fix peer deps issue in svelte and vue plugins (#3333) * fix peer deps issue * add changeset * rebuild lockfile --- .changeset/violet-bees-camp.md | 6 ++++ packages/integrations/svelte/package.json | 3 +- packages/integrations/vue/package.json | 3 +- pnpm-lock.yaml | 40 ++++++++++++++++++++--- 4 files changed, 46 insertions(+), 6 deletions(-) create mode 100644 .changeset/violet-bees-camp.md diff --git a/.changeset/violet-bees-camp.md b/.changeset/violet-bees-camp.md new file mode 100644 index 000000000000..07a08f19ae64 --- /dev/null +++ b/.changeset/violet-bees-camp.md @@ -0,0 +1,6 @@ +--- +'@astrojs/svelte': patch +'@astrojs/vue': patch +--- + +Fix a vite peer dependency bug diff --git a/packages/integrations/svelte/package.json b/packages/integrations/svelte/package.json index 1e3d56934488..932021e5d170 100644 --- a/packages/integrations/svelte/package.json +++ b/packages/integrations/svelte/package.json @@ -33,7 +33,8 @@ "dependencies": { "@sveltejs/vite-plugin-svelte": "^1.0.0-next.41", "postcss-load-config": "^3.1.4", - "svelte-preprocess": "^4.10.6" + "svelte-preprocess": "^4.10.6", + "vite": "^2.9.5" }, "devDependencies": { "astro": "workspace:*", diff --git a/packages/integrations/vue/package.json b/packages/integrations/vue/package.json index 4d23797d96d2..2daca2ee4245 100644 --- a/packages/integrations/vue/package.json +++ b/packages/integrations/vue/package.json @@ -31,7 +31,8 @@ "dev": "astro-scripts dev \"src/**/*.ts\"" }, "dependencies": { - "@vitejs/plugin-vue": "^2.3.1" + "@vitejs/plugin-vue": "^2.3.1", + "vite": "^2.9.5" }, "devDependencies": { "astro": "workspace:*", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index ef182ea3bcee..8cc31f697d13 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -1432,10 +1432,12 @@ importers: postcss-load-config: ^3.1.4 svelte: ^3.47.0 svelte-preprocess: ^4.10.6 + vite: ^2.9.5 dependencies: - '@sveltejs/vite-plugin-svelte': 1.0.0-next.41_svelte@3.47.0 + '@sveltejs/vite-plugin-svelte': 1.0.0-next.41_svelte@3.47.0+vite@2.9.5 postcss-load-config: 3.1.4 svelte-preprocess: 4.10.6_ouvyccvykwltmjwugnola6eovq + vite: 2.9.5 devDependencies: astro: link:../../astro astro-scripts: link:../../../scripts @@ -1489,9 +1491,11 @@ importers: '@vitejs/plugin-vue': ^2.3.1 astro: workspace:* astro-scripts: workspace:* + vite: ^2.9.5 vue: ^3.2.33 dependencies: - '@vitejs/plugin-vue': 2.3.1_vue@3.2.33 + '@vitejs/plugin-vue': 2.3.1_vite@2.9.5+vue@3.2.33 + vite: 2.9.5 devDependencies: astro: link:../../astro astro-scripts: link:../../../scripts @@ -2109,6 +2113,8 @@ packages: resolution: {integrity: sha512-vqUSBLP8dQHFPdPi9bc5GK9vRkYHJ49fsZdtoJ8EQ8ibpwk5rPKfvNIwChB0KVXcIjcepEBBd2VHC5r9Gy8ueg==} engines: {node: '>=6.0.0'} hasBin: true + dependencies: + '@babel/types': 7.17.0 /@babel/plugin-bugfix-safari-id-destructuring-collision-in-function-expression/7.16.7_@babel+core@7.17.9: resolution: {integrity: sha512-anv/DObl7waiGEnC24O9zqL0pSuI9hljihqiDuFHC8d7/bjr/4RLGPWuc8rYOff/QPzbEPSkzG8wGG9aDuhHRg==} @@ -3849,7 +3855,7 @@ packages: string.prototype.matchall: 4.0.7 dev: true - /@sveltejs/vite-plugin-svelte/1.0.0-next.41_svelte@3.47.0: + /@sveltejs/vite-plugin-svelte/1.0.0-next.41_svelte@3.47.0+vite@2.9.5: resolution: {integrity: sha512-2kZ49mpi/YW1PIPvKaJNSSwIFgmw9QUf1+yaNa4U8yJD6AsfSHXAU3goscWbi1jfWnSg2PhvwAf+bvLCdp2F9g==} engines: {node: ^14.13.1 || >= 16} peerDependencies: @@ -3868,6 +3874,7 @@ packages: magic-string: 0.26.1 svelte: 3.47.0 svelte-hmr: 0.14.11_svelte@3.47.0 + vite: 2.9.5 transitivePeerDependencies: - supports-color dev: false @@ -4392,7 +4399,7 @@ packages: '@unocss/scope': 0.15.6 dev: true - /@vitejs/plugin-vue/2.3.1_vue@3.2.33: + /@vitejs/plugin-vue/2.3.1_vite@2.9.5+vue@3.2.33: resolution: {integrity: sha512-YNzBt8+jt6bSwpt7LP890U1UcTOIZZxfpE5WOJ638PNxSEKOqAi0+FSKS0nVeukfdZ0Ai/H7AFd6k3hayfGZqQ==} engines: {node: '>=12.0.0'} peerDependencies: @@ -4402,6 +4409,7 @@ packages: vite: optional: true dependencies: + vite: 2.9.5 vue: 3.2.33 dev: false @@ -10463,6 +10471,30 @@ packages: - supports-color dev: true + /vite/2.9.5: + resolution: {integrity: sha512-dvMN64X2YEQgSXF1lYabKXw3BbN6e+BL67+P3Vy4MacnY+UzT1AfkHiioFSi9+uiDUiaDy7Ax/LQqivk6orilg==} + engines: {node: '>=12.2.0'} + hasBin: true + peerDependencies: + less: '*' + sass: '*' + stylus: '*' + peerDependenciesMeta: + less: + optional: true + sass: + optional: true + stylus: + optional: true + dependencies: + esbuild: 0.14.38 + postcss: 8.4.12 + resolve: 1.22.0 + rollup: 2.70.2 + optionalDependencies: + fsevents: 2.3.2 + dev: false + /vite/2.9.5_sass@1.50.1: resolution: {integrity: sha512-dvMN64X2YEQgSXF1lYabKXw3BbN6e+BL67+P3Vy4MacnY+UzT1AfkHiioFSi9+uiDUiaDy7Ax/LQqivk6orilg==} engines: {node: '>=12.2.0'} From ca4e3aa048288ba9d28bfdfb3aaeab080765cac5 Mon Sep 17 00:00:00 2001 From: Nate Moore Date: Wed, 11 May 2022 10:23:55 -0500 Subject: [PATCH 16/22] fix: allow Astro to pass `process.env` variables to `import.meta.env` (#3327) --- packages/astro/src/vite-plugin-env/index.ts | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/packages/astro/src/vite-plugin-env/index.ts b/packages/astro/src/vite-plugin-env/index.ts index 7a716019e6f1..bc3447214a3c 100644 --- a/packages/astro/src/vite-plugin-env/index.ts +++ b/packages/astro/src/vite-plugin-env/index.ts @@ -22,9 +22,6 @@ function getPrivateEnv(viteConfig: vite.ResolvedConfig, astroConfig: AstroConfig '' ); const privateKeys = Object.keys(fullEnv).filter((key) => { - // don't expose any variables also on `process.env` - // note: this filters out `CLI_ARGS=1` passed to node! - if (typeof process.env[key] !== 'undefined') return false; // don't inject `PUBLIC_` variables, Vite handles that for us for (const envPrefix of envPrefixes) { @@ -37,7 +34,10 @@ function getPrivateEnv(viteConfig: vite.ResolvedConfig, astroConfig: AstroConfig if (privateKeys.length === 0) { return null; } - return Object.fromEntries(privateKeys.map((key) => [key, JSON.stringify(fullEnv[key])])); + return Object.fromEntries(privateKeys.map((key) => { + if (typeof process.env[key] !== 'undefined') return [key, `process.env.${key}`]; + return [key, JSON.stringify(fullEnv[key])] + })); } function getReferencedPrivateKeys(source: string, privateEnv: Record): Set { From 74510a96078a2bce0cc797a39070469444164394 Mon Sep 17 00:00:00 2001 From: Sarah Rainsberger Date: Wed, 11 May 2022 12:24:26 -0300 Subject: [PATCH 17/22] Update markdown.remark/rehypePlugins defaults for docs (#3321) Updating defaults used in the documentation --- packages/astro/src/@types/astro.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/astro/src/@types/astro.ts b/packages/astro/src/@types/astro.ts index 117a1e257a7a..e57126180b98 100644 --- a/packages/astro/src/@types/astro.ts +++ b/packages/astro/src/@types/astro.ts @@ -563,7 +563,7 @@ export interface AstroUserConfig { * { * markdown: { * // Example: The default set of remark plugins used by Astro - * remarkPlugins: ['remark-code-titles', ['rehype-autolink-headings', { behavior: 'prepend' }]], + * remarkPlugins: ['remark-gfm', 'remark-smartypants'], * }, * }; * ``` @@ -582,7 +582,7 @@ export interface AstroUserConfig { * { * markdown: { * // Example: The default set of rehype plugins used by Astro - * rehypePlugins: ['rehype-slug', ['rehype-toc', { headings: ['h2', 'h3'] }], [addClasses, { 'h1,h2,h3': 'title' }]], + * rehypePlugins: [], * }, * }; * ``` From 380acd23de6c0ccd1237d5a99a0af8641d17f4fa Mon Sep 17 00:00:00 2001 From: matthewp Date: Wed, 11 May 2022 15:25:30 +0000 Subject: [PATCH 18/22] [ci] format --- packages/astro/src/vite-plugin-astro/hmr.ts | 8 ++++---- packages/astro/src/vite-plugin-astro/index.ts | 14 ++++++++------ packages/astro/src/vite-plugin-env/index.ts | 11 ++++++----- 3 files changed, 18 insertions(+), 15 deletions(-) diff --git a/packages/astro/src/vite-plugin-astro/hmr.ts b/packages/astro/src/vite-plugin-astro/hmr.ts index 2b11585ca484..9bb1ff371668 100644 --- a/packages/astro/src/vite-plugin-astro/hmr.ts +++ b/packages/astro/src/vite-plugin-astro/hmr.ts @@ -68,7 +68,7 @@ export async function handleHotUpdate(ctx: HmrContext, config: AstroConfig, logg filtered.add(mod); files.add(mod.file); } - + for (const imp of mod.importers) { if (imp.file && isCached(config, imp.file)) { filtered.add(imp); @@ -88,9 +88,9 @@ export async function handleHotUpdate(ctx: HmrContext, config: AstroConfig, logg const mods = ctx.modules.filter((m) => !m.url.endsWith('=')); // Add hoisted scripts so these get invalidated - for(const mod of mods) { - for(const imp of mod.importedModules) { - if(imp.id?.includes('?astro&type=script')) { + for (const mod of mods) { + for (const imp of mod.importedModules) { + if (imp.id?.includes('?astro&type=script')) { mods.push(imp); } } diff --git a/packages/astro/src/vite-plugin-astro/index.ts b/packages/astro/src/vite-plugin-astro/index.ts index 47ecfee1efbe..9ed6f983b3bc 100644 --- a/packages/astro/src/vite-plugin-astro/index.ts +++ b/packages/astro/src/vite-plugin-astro/index.ts @@ -127,9 +127,9 @@ export default function astro({ config, logging }: AstroPluginOptions): vite.Plu throw new Error(`Requests for hoisted scripts must include an index`); } // HMR hoisted script only exists to make them appear in the module graph. - if(opts?.ssr) { + if (opts?.ssr) { return { - code: `/* client hoisted script, empty in SSR: ${id} */` + code: `/* client hoisted script, empty in SSR: ${id} */`, }; } @@ -190,15 +190,17 @@ export default function astro({ config, logging }: AstroPluginOptions): vite.Plu } let i = 0; - while(i < transformResult.scripts.length) { + while (i < transformResult.scripts.length) { deps.add(`${id}?astro&type=script&index=${i}`); SUFFIX += `import "${id}?astro&type=script&index=${i}";`; i++; } // We only need to define deps if there are any - if(deps.size > 1) { - SUFFIX += `\nif(import.meta.hot) import.meta.hot.accept(["${id}", "${Array.from(deps).join('","')}"], (...mods) => mods);` + if (deps.size > 1) { + SUFFIX += `\nif(import.meta.hot) import.meta.hot.accept(["${id}", "${Array.from( + deps + ).join('","')}"], (...mods) => mods);`; } else { SUFFIX += `\nif (import.meta.hot) { import.meta.hot.accept(mod => mod); @@ -209,7 +211,7 @@ export default function astro({ config, logging }: AstroPluginOptions): vite.Plu if (isPage) { SUFFIX += `\nimport "${PAGE_SSR_SCRIPT_ID}";`; } - + return { code: `${code}${SUFFIX}`, map, diff --git a/packages/astro/src/vite-plugin-env/index.ts b/packages/astro/src/vite-plugin-env/index.ts index bc3447214a3c..a510f2eee8ca 100644 --- a/packages/astro/src/vite-plugin-env/index.ts +++ b/packages/astro/src/vite-plugin-env/index.ts @@ -22,7 +22,6 @@ function getPrivateEnv(viteConfig: vite.ResolvedConfig, astroConfig: AstroConfig '' ); const privateKeys = Object.keys(fullEnv).filter((key) => { - // don't inject `PUBLIC_` variables, Vite handles that for us for (const envPrefix of envPrefixes) { if (key.startsWith(envPrefix)) return false; @@ -34,10 +33,12 @@ function getPrivateEnv(viteConfig: vite.ResolvedConfig, astroConfig: AstroConfig if (privateKeys.length === 0) { return null; } - return Object.fromEntries(privateKeys.map((key) => { - if (typeof process.env[key] !== 'undefined') return [key, `process.env.${key}`]; - return [key, JSON.stringify(fullEnv[key])] - })); + return Object.fromEntries( + privateKeys.map((key) => { + if (typeof process.env[key] !== 'undefined') return [key, `process.env.${key}`]; + return [key, JSON.stringify(fullEnv[key])]; + }) + ); } function getReferencedPrivateKeys(source: string, privateEnv: Record): Set { From abc5b219bb58c22b680da0486bc2b779e6661dd8 Mon Sep 17 00:00:00 2001 From: Jonas Luebbers Date: Wed, 11 May 2022 12:23:34 -0400 Subject: [PATCH 19/22] Remove try/catch from solid component check (#3282) * Remove try/catch from solid component check * Move try/catch to renderComponent * Add solid to integrations-playground example --- .../integrations-playground/astro.config.mjs | 7 ++++--- examples/integrations-playground/package.json | 5 +++-- .../src/components/Link.jsx | 3 +++ .../src/components/SolidCounter.jsx | 18 ++++++++++++++++++ .../src/pages/index.astro | 12 ++++++------ packages/astro/src/runtime/server/index.ts | 15 ++++++++++++--- packages/integrations/solid/server.js | 8 ++------ pnpm-lock.yaml | 6 ++++-- 8 files changed, 52 insertions(+), 22 deletions(-) create mode 100644 examples/integrations-playground/src/components/SolidCounter.jsx diff --git a/examples/integrations-playground/astro.config.mjs b/examples/integrations-playground/astro.config.mjs index a1f21fe0b677..2859263ad27e 100644 --- a/examples/integrations-playground/astro.config.mjs +++ b/examples/integrations-playground/astro.config.mjs @@ -1,12 +1,13 @@ import { defineConfig } from 'astro/config'; - import lit from '@astrojs/lit'; import react from '@astrojs/react'; import tailwind from '@astrojs/tailwind'; import turbolinks from '@astrojs/turbolinks'; import sitemap from '@astrojs/sitemap'; import partytown from '@astrojs/partytown'; +import solid from "@astrojs/solid-js"; +// https://astro.build/config export default defineConfig({ - integrations: [lit(), react(), tailwind(), turbolinks(), partytown(), sitemap()], -}); + integrations: [lit(), react(), tailwind(), turbolinks(), partytown(), sitemap(), solid()] +}); \ No newline at end of file diff --git a/examples/integrations-playground/package.json b/examples/integrations-playground/package.json index 023ae1c07c22..af39d140ee59 100644 --- a/examples/integrations-playground/package.json +++ b/examples/integrations-playground/package.json @@ -13,9 +13,11 @@ "@astrojs/partytown": "^0.1.2", "@astrojs/react": "^0.1.1", "@astrojs/sitemap": "^0.1.0", + "@astrojs/solid-js": "0.1.2", "@astrojs/tailwind": "^0.2.1", "@astrojs/turbolinks": "^0.1.2", - "astro": "^1.0.0-beta.27" + "astro": "^1.0.0-beta.27", + "solid-js": "^1.3.6" }, "dependencies": { "@webcomponents/template-shadowroot": "^0.1.0", @@ -23,7 +25,6 @@ "preact": "^10.7.1", "react": "^18.0.0", "react-dom": "^18.0.0", - "solid-js": "^1.3.16", "svelte": "^3.47.0", "vue": "^3.2.33" } diff --git a/examples/integrations-playground/src/components/Link.jsx b/examples/integrations-playground/src/components/Link.jsx index 2758df130d96..040d112c3ec3 100644 --- a/examples/integrations-playground/src/components/Link.jsx +++ b/examples/integrations-playground/src/components/Link.jsx @@ -1,3 +1,6 @@ +/* jsxImportSource: react */ +import React from 'react'; + export default function Link({ to, text }) { return {text}; } diff --git a/examples/integrations-playground/src/components/SolidCounter.jsx b/examples/integrations-playground/src/components/SolidCounter.jsx new file mode 100644 index 000000000000..4453b881c6c8 --- /dev/null +++ b/examples/integrations-playground/src/components/SolidCounter.jsx @@ -0,0 +1,18 @@ +import { createSignal } from 'solid-js'; + +export default function Counter(props) { + const [count, setCount] = createSignal(0); + const add = () => setCount(count() + 1); + const subtract = () => setCount(count() - 1); + + return ( + <> +
+ +
{count()}
+ +
+
{props.children}
+ + ); +} diff --git a/examples/integrations-playground/src/pages/index.astro b/examples/integrations-playground/src/pages/index.astro index 2ee717d6a9c4..06c9aa3d870b 100644 --- a/examples/integrations-playground/src/pages/index.astro +++ b/examples/integrations-playground/src/pages/index.astro @@ -1,8 +1,9 @@ --- import Lorem from '../components/Lorem.astro'; import Link from '../components/Link.jsx'; +import SolidCounter from '../components/SolidCounter.jsx'; import '../components/Test.js'; -import '../components/Counter.js'; +import '../components/Counter.js'; --- @@ -14,20 +15,19 @@ import '../components/Counter.js';

Test app

- Party Mode! + Party Mode! Colors changing = partytown is enabled

+ - - diff --git a/packages/astro/src/runtime/server/index.ts b/packages/astro/src/runtime/server/index.ts index 73c13c1392c1..13d408f9785e 100644 --- a/packages/astro/src/runtime/server/index.ts +++ b/packages/astro/src/runtime/server/index.ts @@ -201,13 +201,22 @@ Did you mean to add ${formatList(probableRendererNames.map((r) => '`' + r + '`') // Call the renderers `check` hook to see if any claim this component. let renderer: SSRLoadedRenderer | undefined; if (metadata.hydrate !== 'only') { + let error; for (const r of renderers) { - if (await r.ssr.check(Component, props, children)) { - renderer = r; - break; + try { + if (await r.ssr.check(Component, props, children)) { + renderer = r; + break; + } + } catch (e) { + error ??= e; } } + if (error) { + throw error; + } + if (!renderer && typeof HTMLElement === 'function' && componentIsHTMLElement(Component)) { const output = renderHTMLElement(result, Component as typeof HTMLElement, _props, slots); diff --git a/packages/integrations/solid/server.js b/packages/integrations/solid/server.js index 636fa50f6bc6..dc4f88227eee 100644 --- a/packages/integrations/solid/server.js +++ b/packages/integrations/solid/server.js @@ -2,12 +2,8 @@ import { renderToString, ssr, createComponent } from 'solid-js/web'; function check(Component, props, children) { if (typeof Component !== 'function') return false; - try { - const { html } = renderToStaticMarkup(Component, props, children); - return typeof html === 'string'; - } catch (err) { - return false; - } + const { html } = renderToStaticMarkup(Component, props, children); + return typeof html === 'string'; } function renderToStaticMarkup(Component, props, children) { diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 8cc31f697d13..29b9251f04b6 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -245,6 +245,7 @@ importers: '@astrojs/partytown': ^0.1.2 '@astrojs/react': ^0.1.1 '@astrojs/sitemap': ^0.1.0 + '@astrojs/solid-js': 0.1.2 '@astrojs/tailwind': ^0.2.1 '@astrojs/turbolinks': ^0.1.2 '@webcomponents/template-shadowroot': ^0.1.0 @@ -253,7 +254,7 @@ importers: preact: ^10.7.1 react: ^18.0.0 react-dom: ^18.0.0 - solid-js: ^1.3.16 + solid-js: ^1.3.6 svelte: ^3.47.0 vue: ^3.2.33 dependencies: @@ -262,7 +263,6 @@ importers: preact: 10.7.1 react: 18.0.0 react-dom: 18.0.0_react@18.0.0 - solid-js: 1.3.16 svelte: 3.47.0 vue: 3.2.33 devDependencies: @@ -270,9 +270,11 @@ importers: '@astrojs/partytown': link:../../packages/integrations/partytown '@astrojs/react': link:../../packages/integrations/react '@astrojs/sitemap': link:../../packages/integrations/sitemap + '@astrojs/solid-js': link:../../packages/integrations/solid '@astrojs/tailwind': link:../../packages/integrations/tailwind '@astrojs/turbolinks': link:../../packages/integrations/turbolinks astro: link:../../packages/astro + solid-js: 1.3.16 examples/minimal: specifiers: From 461d1bb4c33cb50ee29e1ec08a8dbf35f2b00baf Mon Sep 17 00:00:00 2001 From: matthewp Date: Wed, 11 May 2022 16:24:45 +0000 Subject: [PATCH 20/22] [ci] format --- examples/integrations-playground/astro.config.mjs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/examples/integrations-playground/astro.config.mjs b/examples/integrations-playground/astro.config.mjs index 2859263ad27e..a7c3d4a0b7a2 100644 --- a/examples/integrations-playground/astro.config.mjs +++ b/examples/integrations-playground/astro.config.mjs @@ -5,9 +5,9 @@ import tailwind from '@astrojs/tailwind'; import turbolinks from '@astrojs/turbolinks'; import sitemap from '@astrojs/sitemap'; import partytown from '@astrojs/partytown'; -import solid from "@astrojs/solid-js"; +import solid from '@astrojs/solid-js'; // https://astro.build/config export default defineConfig({ - integrations: [lit(), react(), tailwind(), turbolinks(), partytown(), sitemap(), solid()] -}); \ No newline at end of file + integrations: [lit(), react(), tailwind(), turbolinks(), partytown(), sitemap(), solid()], +}); From f40705d906951a2ac16a89290bcadd597fe4cbeb Mon Sep 17 00:00:00 2001 From: Matthew Phillips Date: Wed, 11 May 2022 10:25:12 -0600 Subject: [PATCH 21/22] Adding a changeset for solidjs error swallowing fix --- .changeset/olive-grapes-relate.md | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 .changeset/olive-grapes-relate.md diff --git a/.changeset/olive-grapes-relate.md b/.changeset/olive-grapes-relate.md new file mode 100644 index 000000000000..8524f87ef0a7 --- /dev/null +++ b/.changeset/olive-grapes-relate.md @@ -0,0 +1,5 @@ +--- +'astro': patch +--- + +Fix for swallowed SolidJS errors From 1a5335ed9abaef397ee9543a3b4ad7a3fddcf024 Mon Sep 17 00:00:00 2001 From: Ben Holmes Date: Wed, 11 May 2022 10:38:42 -0600 Subject: [PATCH 22/22] =?UTF-8?q?[create-astro]=20Finalize=20developer=20e?= =?UTF-8?q?xperience...=20with=20gradients=20=F0=9F=9A=80=20(#3313)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * wip: port gradient helpers from sandbox ideas * feat: wire up rocket gradient 🚀 * feat: wire up rocket gradient on install step * refactor: update "next steps" wording * deps: add chalk (for rendering gradient) * chore: changeset * chore: clean up sstray template string --- .changeset/strong-students-tie.md | 5 ++ packages/create-astro/package.json | 1 + packages/create-astro/src/gradient.ts | 91 +++++++++++++++++++++++++++ packages/create-astro/src/index.ts | 47 +++++++------- pnpm-lock.yaml | 2 + 5 files changed, 123 insertions(+), 23 deletions(-) create mode 100644 .changeset/strong-students-tie.md create mode 100644 packages/create-astro/src/gradient.ts diff --git a/.changeset/strong-students-tie.md b/.changeset/strong-students-tie.md new file mode 100644 index 000000000000..9ac0be8f761b --- /dev/null +++ b/.changeset/strong-students-tie.md @@ -0,0 +1,5 @@ +--- +'create-astro': patch +--- + +Update "next steps" with more informative text on each CLI command. Oh, and gradients. A lot more gradients. diff --git a/packages/create-astro/package.json b/packages/create-astro/package.json index 5a1e2af99c53..de3c1a35b45c 100644 --- a/packages/create-astro/package.json +++ b/packages/create-astro/package.json @@ -30,6 +30,7 @@ "dependencies": { "@types/degit": "^2.8.3", "@types/prompts": "^2.0.14", + "chalk": "^5.0.1", "degit": "^2.8.4", "execa": "^6.1.0", "kleur": "^4.1.4", diff --git a/packages/create-astro/src/gradient.ts b/packages/create-astro/src/gradient.ts new file mode 100644 index 000000000000..2d4c48d81858 --- /dev/null +++ b/packages/create-astro/src/gradient.ts @@ -0,0 +1,91 @@ +import chalk from 'chalk'; +import ora from 'ora'; +import type { Ora } from 'ora'; + +const gradientColors = [ + `#ff5e00`, + `#ff4c29`, + `#ff383f`, + `#ff2453`, + `#ff0565`, + `#ff007b`, + `#f5008b`, + `#e6149c`, + `#d629ae`, + `#c238bd`, +]; + +export const rocketAscii = '■■▶'; + +// get a reference to scroll through while loading +// visual representation of what this generates: +// gradientColors: "..xxXX" +// referenceGradient: "..xxXXXXxx....xxXX" +const referenceGradient = [ + ...gradientColors, + // draw the reverse of the gradient without + // accidentally mutating the gradient (ugh, reverse()) + ...[...gradientColors].reverse(), + ...gradientColors, +]; + +// async-friendly setTimeout +const sleep = (time: number) => + new Promise((resolve) => { + setTimeout(resolve, time); + }); + +function getGradientAnimFrames() { + const frames = []; + for (let start = 0; start < gradientColors.length * 2; start++) { + const end = start + gradientColors.length - 1; + frames.push( + referenceGradient + .slice(start, end) + .map((g) => chalk.bgHex(g)(' ')) + .join('') + ); + } + return frames; +} + +function getIntroAnimFrames() { + const frames = []; + for (let end = 1; end <= gradientColors.length; end++) { + const leadingSpacesArr = Array.from( + new Array(Math.abs(gradientColors.length - end - 1)), + () => ' ' + ); + const gradientArr = gradientColors.slice(0, end).map((g) => chalk.bgHex(g)(' ')); + frames.push([...leadingSpacesArr, ...gradientArr].join('')); + } + return frames; +} + +/** + * Generate loading spinner with rocket flames! + * @param text display text next to rocket + * @returns Ora spinner for running .stop() + */ +export async function loadWithRocketGradient(text: string): Promise { + const frames = getIntroAnimFrames(); + const intro = ora({ + spinner: { + interval: 30, + frames, + }, + text: `${rocketAscii} ${text}`, + }); + intro.start(); + await sleep((frames.length - 1) * intro.interval); + intro.stop(); + const spinner = ora({ + spinner: { + interval: 80, + frames: getGradientAnimFrames(), + }, + text: `${rocketAscii} ${text}`, + }).start(); + + return spinner; +} diff --git a/packages/create-astro/src/index.ts b/packages/create-astro/src/index.ts index dab8e7a3b9a4..0546bd7512e9 100644 --- a/packages/create-astro/src/index.ts +++ b/packages/create-astro/src/index.ts @@ -8,6 +8,7 @@ import ora from 'ora'; import { TEMPLATES } from './templates.js'; import { logger, defaultLogLevel } from './logger.js'; import { execa, execaCommand } from 'execa'; +import { loadWithRocketGradient, rocketAscii } from './gradient.js'; // NOTE: In the v7.x version of npm, the default behavior of `npm init` was changed // to no longer require `--` to pass args and instead pass `--` directly to us. This @@ -42,10 +43,6 @@ export async function main() { logger.debug('Verbose logging turned on'); console.log(`\n${bold('Welcome to Astro!')} ${gray(`(create-astro v${version})`)}`); - let spinner = ora({ color: 'green', text: 'Prepare for liftoff.' }); - - spinner.succeed(); - let cwd = args['_'][2] as string; if (cwd && isEmpty(cwd)) { @@ -95,6 +92,8 @@ export async function main() { process.exit(1); } + const templateSpinner = await loadWithRocketGradient('Copying project files...'); + const hash = args.commit ? `#${args.commit}` : ''; const templateTarget = `withastro/astro/examples/${options.template}#latest`; @@ -111,8 +110,6 @@ export async function main() { verbose: defaultLogLevel === 'debug' ? true : false, }); - spinner = ora({ color: 'green', text: 'Copying project files...' }).start(); - // Copy if (!args.dryrun) { try { @@ -152,7 +149,7 @@ export async function main() { ) ); } - spinner.fail(); + templateSpinner.fail(); process.exit(1); } @@ -167,8 +164,8 @@ export async function main() { ); } - spinner.succeed(); - console.log(bold(green('✔') + ' Done!')); + templateSpinner.text = green('Template copied!'); + templateSpinner.succeed(); const installResponse = await prompts({ type: 'confirm', @@ -184,15 +181,18 @@ export async function main() { if (installResponse.install && !args.dryrun) { const installExec = execa(pkgManager, ['install'], { cwd }); const installingPackagesMsg = `Installing packages${emojiWithFallback(' 📦', '...')}`; - spinner = ora({ color: 'green', text: installingPackagesMsg }).start(); + const installSpinner = await loadWithRocketGradient(installingPackagesMsg); await new Promise((resolve, reject) => { installExec.stdout?.on('data', function (data) { - spinner.text = `${installingPackagesMsg}\n${bold(`[${pkgManager}]`)} ${data}`; + installSpinner.text = `${rocketAscii} ${installingPackagesMsg}\n${bold( + `[${pkgManager}]` + )} ${data}`; }); installExec.on('error', (error) => reject(error)); installExec.on('close', () => resolve()); }); - spinner.succeed(); + installSpinner.text = green('Packages installed!'); + installSpinner.succeed(); } const astroAddCommand = installResponse.install @@ -240,21 +240,22 @@ export async function main() { await execaCommand('git init', { cwd }); } + ora({ text: green('Done. Ready for liftoff!') }).succeed(); console.log(`\n${bgCyan(black(' Next steps '))}\n`); - const relative = path.relative(process.cwd(), cwd); - const startCommand = []; - if (relative !== '') { - startCommand.push(bold(cyan(`cd ${relative}`))); - } + const projectDir = path.relative(process.cwd(), cwd); + const devCmd = pkgManager === 'npm' ? 'npm run dev' : `${pkgManager} dev`; + + console.log( + `You can now ${bold(cyan('cd'))} into the ${bold(cyan(projectDir))} project directory.` + ); + console.log( + `Run ${bold(cyan(devCmd))} to start the Astro dev server. ${bold(cyan('CTRL-C'))} to close.` + ); if (!installResponse.install) { - startCommand.push(bold(cyan(`${pkgManager} install`))); + console.log(yellow(`Remember to install dependencies first!`)); } - startCommand.push(bold(cyan(pkgManager === 'npm' ? 'npm run dev' : `${pkgManager} dev`))); - console.log(startCommand.join(' && ')); - - console.log(`\nTo close the dev server, hit ${bold(cyan('Ctrl-C'))}`); - console.log(`Stuck? Visit us at ${cyan('https://astro.build/chat')}\n`); + console.log(`\nStuck? Come join us at ${bold(cyan('https://astro.build/chat'))}`); } function emojiWithFallback(char: string, fallback: string) { diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 29b9251f04b6..be8f0175ef84 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -1256,6 +1256,7 @@ importers: '@types/yargs-parser': ^21.0.0 astro-scripts: workspace:* chai: ^4.3.6 + chalk: ^5.0.1 degit: ^2.8.4 execa: ^6.1.0 kleur: ^4.1.4 @@ -1267,6 +1268,7 @@ importers: dependencies: '@types/degit': 2.8.3 '@types/prompts': 2.0.14 + chalk: 5.0.1 degit: 2.8.4 execa: 6.1.0 kleur: 4.1.4