From 20c7765be539365002defb14bfd6b22c076b8b73 Mon Sep 17 00:00:00 2001 From: Florian Lefebvre Date: Wed, 14 Aug 2024 14:59:04 +0200 Subject: [PATCH 01/29] chore: optimize check (#11704) --- packages/astro/src/core/dev/restart.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/astro/src/core/dev/restart.ts b/packages/astro/src/core/dev/restart.ts index 235454cb5a70..ee0ba995c446 100644 --- a/packages/astro/src/core/dev/restart.ts +++ b/packages/astro/src/core/dev/restart.ts @@ -51,7 +51,7 @@ function shouldRestartContainer( const settingsPath = vite.normalizePath( fileURLToPath(new URL('settings.json', settings.dotAstroDir)), ); - if (settingsPath.match(normalizedChangedFile)) { + if (settingsPath.endsWith(normalizedChangedFile)) { shouldRestart = settings.preferences.ignoreNextPreferenceReload ? false : true; settings.preferences.ignoreNextPreferenceReload = false; From df78c79ea0f4a76b5965c7175fd3656a5639dbf6 Mon Sep 17 00:00:00 2001 From: Florian Lefebvre Date: Wed, 14 Aug 2024 13:00:16 +0000 Subject: [PATCH 02/29] [ci] format --- packages/astro/src/@types/astro.ts | 6 +++--- packages/astro/src/content/data-store.ts | 2 +- packages/astro/src/content/types-generator.ts | 8 ++++---- packages/astro/src/core/sync/write-files.ts | 2 +- packages/astro/templates/content/types.d.ts | 2 -- 5 files changed, 9 insertions(+), 11 deletions(-) diff --git a/packages/astro/src/@types/astro.ts b/packages/astro/src/@types/astro.ts index 2cf4160609b1..850b1227b88e 100644 --- a/packages/astro/src/@types/astro.ts +++ b/packages/astro/src/@types/astro.ts @@ -1,3 +1,5 @@ +import type { OutgoingHttpHeaders } from 'node:http'; +import type { AddressInfo } from 'node:net'; import type { MarkdownHeading, MarkdownVFile, @@ -7,8 +9,6 @@ import type { ShikiConfig, } from '@astrojs/markdown-remark'; import type * as babel from '@babel/core'; -import type { OutgoingHttpHeaders } from 'node:http'; -import type { AddressInfo } from 'node:net'; import type * as rollup from 'rollup'; import type * as vite from 'vite'; import type { @@ -2261,7 +2261,7 @@ export interface AstroUserConfig { * updatedDate: z.coerce.date().optional(), * }) * }); - * + * * const dogs = defineCollection({ * // The path is relative to the project root, or an absolute path. * loader: file("src/data/dogs.json"), diff --git a/packages/astro/src/content/data-store.ts b/packages/astro/src/content/data-store.ts index f416082f9db0..e3b00f998924 100644 --- a/packages/astro/src/content/data-store.ts +++ b/packages/astro/src/content/data-store.ts @@ -1,6 +1,6 @@ +import { promises as fs, type PathLike, existsSync } from 'fs'; import type { MarkdownHeading } from '@astrojs/markdown-remark'; import * as devalue from 'devalue'; -import { existsSync, promises as fs, type PathLike } from 'fs'; import { imageSrcToImportId, importIdToSymbolName } from '../assets/utils/resolveImports.js'; import { AstroError, AstroErrorData } from '../core/errors/index.js'; import { CONTENT_MODULE_FLAG, DEFERRED_MODULE } from './consts.js'; diff --git a/packages/astro/src/content/types-generator.ts b/packages/astro/src/content/types-generator.ts index 6fa0db94beb2..973a892fa17f 100644 --- a/packages/astro/src/content/types-generator.ts +++ b/packages/astro/src/content/types-generator.ts @@ -1,10 +1,10 @@ -import glob from 'fast-glob'; -import { bold, cyan } from 'kleur/colors'; import type fsMod from 'node:fs'; import * as path from 'node:path'; import { fileURLToPath, pathToFileURL } from 'node:url'; +import glob from 'fast-glob'; +import { bold, cyan } from 'kleur/colors'; import { type ViteDevServer, normalizePath } from 'vite'; -import { z, type ZodSchema } from 'zod'; +import { type ZodSchema, z } from 'zod'; import { zodToJsonSchema } from 'zod-to-json-schema'; import { printNode, zodToTs } from 'zod-to-ts'; import type { AstroSettings, ContentEntryType } from '../@types/astro.js'; @@ -473,7 +473,7 @@ async function writeContentFiles({ collection.type === 'unknown' ? // Add empty / unknown collections to the data type map by default // This ensures `getCollection('empty-collection')` doesn't raise a type error - (collectionConfig?.type ?? 'data') + collectionConfig?.type ?? 'data' : collection.type; const collectionEntryKeys = Object.keys(collection.entries).sort(); diff --git a/packages/astro/src/core/sync/write-files.ts b/packages/astro/src/core/sync/write-files.ts index 56ab131f1be7..395bd54f2b12 100644 --- a/packages/astro/src/core/sync/write-files.ts +++ b/packages/astro/src/core/sync/write-files.ts @@ -4,9 +4,9 @@ import { fileURLToPath } from 'node:url'; import { bold } from 'kleur/colors'; import { normalizePath } from 'vite'; import type { AstroSettings } from '../../@types/astro.js'; +import { AstroError, AstroErrorData } from '../errors/index.js'; import type { Logger } from '../logger/core.js'; import { REFERENCE_FILE } from './constants.js'; -import { AstroError, AstroErrorData } from '../errors/index.js'; export async function writeFiles(settings: AstroSettings, fs: typeof fsMod, logger: Logger) { try { diff --git a/packages/astro/templates/content/types.d.ts b/packages/astro/templates/content/types.d.ts index 9f277576a4bf..f83f28177698 100644 --- a/packages/astro/templates/content/types.d.ts +++ b/packages/astro/templates/content/types.d.ts @@ -1,5 +1,4 @@ declare module 'astro:content' { - interface RenderResult { Content: import('astro/runtime/server/index.js').AstroComponentFactory; headings: import('astro').MarkdownHeading[]; @@ -9,7 +8,6 @@ declare module 'astro:content' { '.md': Promise; } - export interface RenderedContent { html: string; metadata?: { From 69a7a5f1325256aac7577c0120388472478733d7 Mon Sep 17 00:00:00 2001 From: Sarah Rainsberger Date: Wed, 14 Aug 2024 11:09:14 -0300 Subject: [PATCH 03/29] [docs] updates link in Content Layer API (#11706) --- packages/astro/src/@types/astro.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/astro/src/@types/astro.ts b/packages/astro/src/@types/astro.ts index 850b1227b88e..fcff6557cec3 100644 --- a/packages/astro/src/@types/astro.ts +++ b/packages/astro/src/@types/astro.ts @@ -2220,7 +2220,7 @@ export interface AstroUserConfig { * * The Content Layer API is a new way to handle content and data in Astro. It is similar to and builds upon [content collections](/en/guides/content-collections/), taking them beyond local files in `src/content/` and allowing you to fetch content from anywhere, including remote APIs, by adding a `loader` to your collection. * - * Your existing content collections can be [migrated to the Content Layer API](#migrating-a-content-collection-to-content-layer) with a few small changes. However, it is not necessary to update all your collections at once to add a new collection powered by the Content Layer API. You may have collections using both the existing and new APIs defined in `src/content/config.ts` at the same time. + * Your existing content collections can be [migrated to the Content Layer API](#migrating-an-existing-content-collection-to-use-the-content-layer-api) with a few small changes. However, it is not necessary to update all your collections at once to add a new collection powered by the Content Layer API. You may have collections using both the existing and new APIs defined in `src/content/config.ts` at the same time. * * The Content Layer API is designed to be more powerful and more performant, helping sites scale to thousands of pages. Data is cached between builds and updated incrementally. Markdown parsing is also 5-10 times faster, with similar scale reductions in memory, and MDX is 2-3 times faster. * From 3d8ae767fd4952af7332542b58fe98886eb2e99e Mon Sep 17 00:00:00 2001 From: Matthew Phillips Date: Wed, 14 Aug 2024 13:30:31 -0400 Subject: [PATCH 04/29] Prevent externalized adapters from breaking build (#11709) * Prevent externalized adapters from breaking build * Add a changeset * Implement in both types of build plugins * linting :( --- .changeset/new-boats-flash.md | 5 +++ .../src/core/build/plugins/plugin-ssr.ts | 44 ++++++++++++++++--- .../astro/test/ssr-split-manifest.test.js | 11 ++--- 3 files changed, 46 insertions(+), 14 deletions(-) create mode 100644 .changeset/new-boats-flash.md diff --git a/.changeset/new-boats-flash.md b/.changeset/new-boats-flash.md new file mode 100644 index 000000000000..4ef58bba4538 --- /dev/null +++ b/.changeset/new-boats-flash.md @@ -0,0 +1,5 @@ +--- +'astro': patch +--- + +Fix adapter causing Netlify to break diff --git a/packages/astro/src/core/build/plugins/plugin-ssr.ts b/packages/astro/src/core/build/plugins/plugin-ssr.ts index 70997e40ea67..b84d5050c492 100644 --- a/packages/astro/src/core/build/plugins/plugin-ssr.ts +++ b/packages/astro/src/core/build/plugins/plugin-ssr.ts @@ -19,6 +19,26 @@ import { getComponentFromVirtualModulePageName, getVirtualModulePageName } from export const SSR_VIRTUAL_MODULE_ID = '@astrojs-ssr-virtual-entry'; export const RESOLVED_SSR_VIRTUAL_MODULE_ID = '\0' + SSR_VIRTUAL_MODULE_ID; +const ADAPTER_VIRTUAL_MODULE_ID = '@astrojs-ssr-adapter'; +const RESOLVED_ADAPTER_VIRTUAL_MODULE_ID = '\0' + ADAPTER_VIRTUAL_MODULE_ID; + +function vitePluginAdapter(adapter: AstroAdapter): VitePlugin { + return { + name: '@astrojs/vite-plugin-astro-adapter', + enforce: 'post', + resolveId(id) { + if (id === ADAPTER_VIRTUAL_MODULE_ID) { + return RESOLVED_ADAPTER_VIRTUAL_MODULE_ID; + } + }, + async load(id) { + if(id === RESOLVED_ADAPTER_VIRTUAL_MODULE_ID) { + return `export * from '${adapter.serverEntrypoint}';`; + } + }, + }; +} + function vitePluginSSR( internals: BuildInternals, adapter: AstroAdapter, @@ -39,7 +59,7 @@ function vitePluginSSR( const adapterServerEntrypoint = options.settings.adapter?.serverEntrypoint; if (adapterServerEntrypoint) { - inputs.add(adapterServerEntrypoint); + inputs.add(ADAPTER_VIRTUAL_MODULE_ID); } inputs.add(SSR_VIRTUAL_MODULE_ID); @@ -119,14 +139,19 @@ export function pluginSSR( targets: ['server'], hooks: { 'build:before': () => { - let vitePlugin = + const adapter = options.settings.adapter!; + let ssrPlugin = ssr && functionPerRouteEnabled === false - ? vitePluginSSR(internals, options.settings.adapter!, options) + ? vitePluginSSR(internals, adapter, options) : undefined; + const vitePlugin = [vitePluginAdapter(adapter)]; + if(ssrPlugin) { + vitePlugin.unshift(ssrPlugin); + } return { enforce: 'after-user-plugins', - vitePlugin, + vitePlugin: vitePlugin, }; }, 'build:post': async () => { @@ -231,10 +256,15 @@ export function pluginSSRSplit( targets: ['server'], hooks: { 'build:before': () => { - let vitePlugin = + const adapter = options.settings.adapter!; + let ssrPlugin = ssr && functionPerRouteEnabled - ? vitePluginSSRSplit(internals, options.settings.adapter!, options) + ? vitePluginSSRSplit(internals, adapter, options) : undefined; + const vitePlugin = [vitePluginAdapter(adapter)]; + if(ssrPlugin) { + vitePlugin.unshift(ssrPlugin); + } return { enforce: 'after-user-plugins', @@ -251,7 +281,7 @@ function generateSSRCode(settings: AstroSettings, adapter: AstroAdapter, middlew const imports = [ `import { renderers } from '${RENDERERS_MODULE_ID}';`, - `import * as serverEntrypointModule from '${adapter.serverEntrypoint}';`, + `import * as serverEntrypointModule from '${ADAPTER_VIRTUAL_MODULE_ID}';`, `import { manifest as defaultManifest } from '${SSR_MANIFEST_VIRTUAL_MODULE_ID}';`, edgeMiddleware ? `` : `import { onRequest as middleware } from '${middlewareId}';`, settings.config.experimental.serverIslands diff --git a/packages/astro/test/ssr-split-manifest.test.js b/packages/astro/test/ssr-split-manifest.test.js index 06a6fe8c6a5c..fc55ce1ba821 100644 --- a/packages/astro/test/ssr-split-manifest.test.js +++ b/packages/astro/test/ssr-split-manifest.test.js @@ -1,6 +1,5 @@ import assert from 'node:assert/strict'; import { existsSync, readFileSync } from 'node:fs'; -import { resolve } from 'node:path'; import { before, describe, it } from 'node:test'; import { fileURLToPath } from 'node:url'; import * as cheerio from 'cheerio'; @@ -62,12 +61,10 @@ describe('astro:ssr-manifest, split', () => { }); it('should correctly emit the the pre render page', async () => { - const text = readFileSync( - resolve('./test/fixtures/ssr-split-manifest/dist/client/prerender/index.html'), - { - encoding: 'utf8', - }, - ); + const indexUrl = new URL('./fixtures/ssr-split-manifest/dist/client/prerender/index.html', import.meta.url); + const text = readFileSync(indexUrl, { + encoding: 'utf8', + }); assert.equal(text.includes('Pre render me'), true); }); From 3adb473cdf3cd2fc2ba90c7bb256fb677b442042 Mon Sep 17 00:00:00 2001 From: Matthew Phillips Date: Wed, 14 Aug 2024 17:31:27 +0000 Subject: [PATCH 05/29] [ci] format --- packages/astro/src/core/build/plugins/plugin-ssr.ts | 6 +++--- packages/astro/test/ssr-split-manifest.test.js | 5 ++++- 2 files changed, 7 insertions(+), 4 deletions(-) diff --git a/packages/astro/src/core/build/plugins/plugin-ssr.ts b/packages/astro/src/core/build/plugins/plugin-ssr.ts index b84d5050c492..e9eda1dc90c2 100644 --- a/packages/astro/src/core/build/plugins/plugin-ssr.ts +++ b/packages/astro/src/core/build/plugins/plugin-ssr.ts @@ -32,7 +32,7 @@ function vitePluginAdapter(adapter: AstroAdapter): VitePlugin { } }, async load(id) { - if(id === RESOLVED_ADAPTER_VIRTUAL_MODULE_ID) { + if (id === RESOLVED_ADAPTER_VIRTUAL_MODULE_ID) { return `export * from '${adapter.serverEntrypoint}';`; } }, @@ -145,7 +145,7 @@ export function pluginSSR( ? vitePluginSSR(internals, adapter, options) : undefined; const vitePlugin = [vitePluginAdapter(adapter)]; - if(ssrPlugin) { + if (ssrPlugin) { vitePlugin.unshift(ssrPlugin); } @@ -262,7 +262,7 @@ export function pluginSSRSplit( ? vitePluginSSRSplit(internals, adapter, options) : undefined; const vitePlugin = [vitePluginAdapter(adapter)]; - if(ssrPlugin) { + if (ssrPlugin) { vitePlugin.unshift(ssrPlugin); } diff --git a/packages/astro/test/ssr-split-manifest.test.js b/packages/astro/test/ssr-split-manifest.test.js index fc55ce1ba821..af0234c6a5cd 100644 --- a/packages/astro/test/ssr-split-manifest.test.js +++ b/packages/astro/test/ssr-split-manifest.test.js @@ -61,7 +61,10 @@ describe('astro:ssr-manifest, split', () => { }); it('should correctly emit the the pre render page', async () => { - const indexUrl = new URL('./fixtures/ssr-split-manifest/dist/client/prerender/index.html', import.meta.url); + const indexUrl = new URL( + './fixtures/ssr-split-manifest/dist/client/prerender/index.html', + import.meta.url, + ); const text = readFileSync(indexUrl, { encoding: 'utf8', }); From 057241f3a6cd55bf942d2a2f37723c5d2e1127d7 Mon Sep 17 00:00:00 2001 From: Yan <61414485+yanthomasdev@users.noreply.github.com> Date: Wed, 14 Aug 2024 17:47:39 -0300 Subject: [PATCH 06/29] Fix typos in 4.14 error references (#11711) --- packages/astro/src/core/errors/errors-data.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/astro/src/core/errors/errors-data.ts b/packages/astro/src/core/errors/errors-data.ts index aa19b6dc3b0e..24b9ad687aea 100644 --- a/packages/astro/src/core/errors/errors-data.ts +++ b/packages/astro/src/core/errors/errors-data.ts @@ -1294,11 +1294,11 @@ export const RewriteWithBodyUsed = { /** * @docs * @description - * An unknown error occured while reading or writing files to disk. It can be caused by many things, eg. missing permissions or a file not existing we attempt to read. + * An unknown error occurred while reading or writing files to disk. It can be caused by many things, eg. missing permissions or a file not existing we attempt to read. */ export const UnknownFilesystemError = { name: 'UnknownFilesystemError', - title: 'An unknown error occured while reading or writing files to disk.', + title: 'An unknown error occurred while reading or writing files to disk.', hint: 'It can be caused by many things, eg. missing permissions or a file not existing we attempt to read. Check the error cause for more details.', } satisfies ErrorData; From b860a9998ddad9f1f9f87a02b1a65d8907a99b38 Mon Sep 17 00:00:00 2001 From: Yan <61414485+yanthomasdev@users.noreply.github.com> Date: Wed, 14 Aug 2024 17:48:12 -0300 Subject: [PATCH 07/29] Small wording/nit improvements to 4.14 release types docs (#11710) Co-authored-by: Sarah Rainsberger --- packages/astro/src/@types/astro.ts | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/packages/astro/src/@types/astro.ts b/packages/astro/src/@types/astro.ts index fcff6557cec3..83c1392f412b 100644 --- a/packages/astro/src/@types/astro.ts +++ b/packages/astro/src/@types/astro.ts @@ -2237,7 +2237,7 @@ export interface AstroUserConfig { * * #### Fetching data with a `loader` * - * The Content Layer API allows you to fetch your content from outside of the `src/content/` folder (whether stored locally in your project or remotely), and uses a `loader` property to retrieve your data. + * The Content Layer API allows you to fetch your content from outside of the `src/content/` folder (whether stored locally in your project or remotely) and uses a `loader` property to retrieve your data. * * The `loader` is defined in the collection's schema and returns an array of entries. Astro provides two built-in loader functions (`glob()` and `file()`) for fetching your local content, as well as access to the API to [construct your own loader and fetch remote data](#creating-a-loader). * @@ -2292,10 +2292,10 @@ export interface AstroUserConfig { * const labradorData = await getEntry('dogs', 'labrador-retriever'); * ``` * - * Entries generated from Markdown, MDX or Markdoc can be rendered directly to a page using the `render()` function. + * Entries generated from Markdown, MDX, or Markdoc can be rendered directly to a page using the `render()` function. * * :::note - * The syntax for rendering collection entries is different from current content collections syntax. + * The syntax for rendering collection entries is different from the current content collections syntax. * ::: * * ```astro title="src/pages/[slug].astro" @@ -2336,7 +2336,7 @@ export interface AstroUserConfig { * export const collections = { countries }; * ``` * - * For more advanced loading logic, you can define an object loader. This allows incremental updates and conditional loading, and gives full access to the data store. See the API in [the Content Layer API RFC](https://github.com/withastro/roadmap/blob/content-layer/proposals/0047-content-layer.md#loaders). + * For more advanced loading logic, you can define an object loader. This allows incremental updates and conditional loading while also giving full access to the data store. See the API in [the Content Layer API RFC](https://github.com/withastro/roadmap/blob/content-layer/proposals/0047-content-layer.md#loaders). * * #### Migrating an existing content collection to use the Content Layer API * From 4a2cb3d1a97d7ff24491377fa9f730d8d544e59f Mon Sep 17 00:00:00 2001 From: Bjorn Lu Date: Thu, 15 Aug 2024 11:41:21 +0800 Subject: [PATCH 08/29] Upgrade to turbo v2 (#11705) --- package.json | 2 +- pnpm-lock.yaml | 60 +++++++++++++------------- turbo.json | 111 +++++++++++++++++++++++++++++-------------------- 3 files changed, 96 insertions(+), 77 deletions(-) diff --git a/package.json b/package.json index 5f2eb056c986..6958dee90d3e 100644 --- a/package.json +++ b/package.json @@ -65,7 +65,7 @@ "only-allow": "^1.2.1", "prettier": "^3.3.3", "prettier-plugin-astro": "^0.14.1", - "turbo": "^1.13.4", + "turbo": "^2.0.12", "typescript": "~5.5.4", "typescript-eslint": "^8.0.1" }, diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 01db0912ed26..6f548f03058b 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -52,8 +52,8 @@ importers: specifier: ^0.14.1 version: 0.14.1 turbo: - specifier: ^1.13.4 - version: 1.13.4 + specifier: ^2.0.12 + version: 2.0.12 typescript: specifier: ~5.5.4 version: 5.5.4 @@ -8281,7 +8281,7 @@ packages: resolution: {integrity: sha512-L3sHRo1pXXEqX8VU28kfgUY+YGsk09hPqZiZmLacNib6XNTCM8ubYeT7ryXQw8asB1sKgcU5lkB7ONug08aB8w==} concat-map@0.0.1: - resolution: {integrity: sha1-2Klr13/Wjfd5OnMDajug1UBdR3s=} + resolution: {integrity: sha512-/Srv4dswyQNBfohGpz9o6Yb3Gz3SrUDqBH5rTuhGR7ahtlbYKnVxw2bCFMRljaA7EXHaXZ8wsHdodFvbkhKmqg==} consola@3.2.3: resolution: {integrity: sha512-I5qxpzLv+sJhTVEoLYNcTW+bThDCPsit0vLNKShZx6rLtpilNpmmeTPaeqJb9ZE9dV3DGaeby6Vuhrw38WjeyQ==} @@ -11224,38 +11224,38 @@ packages: tslib@2.6.2: resolution: {integrity: sha512-AEYxH93jGFPn/a2iVAwW87VuUIkR1FVUKB77NwMF7nBTDkDrrT/Hpt/IrCJ0QXhW27jTBDcf5ZY7w6RiqTMw2Q==} - turbo-darwin-64@1.13.4: - resolution: {integrity: sha512-A0eKd73R7CGnRinTiS7txkMElg+R5rKFp9HV7baDiEL4xTG1FIg/56Vm7A5RVgg8UNgG2qNnrfatJtb+dRmNdw==} + turbo-darwin-64@2.0.12: + resolution: {integrity: sha512-NAgfgbXxX/JScWQmmQnGbPuFZq7LIswHfcMk5JwyBXQM/xmklNOxxac7MnGGIOf19Z2f6S3qHy17VIj0SeGfnA==} cpu: [x64] os: [darwin] - turbo-darwin-arm64@1.13.4: - resolution: {integrity: sha512-eG769Q0NF6/Vyjsr3mKCnkG/eW6dKMBZk6dxWOdrHfrg6QgfkBUk0WUUujzdtVPiUIvsh4l46vQrNVd9EOtbyA==} + turbo-darwin-arm64@2.0.12: + resolution: {integrity: sha512-cP02uer5KSJ+fXL+OfRRk5hnVjV0c60hxDgNcJxrZpfhun7HHoKDDR7w2xhQntiA45aC6ZZEXRqMKpj6GAmKbg==} cpu: [arm64] os: [darwin] - turbo-linux-64@1.13.4: - resolution: {integrity: sha512-Bq0JphDeNw3XEi+Xb/e4xoKhs1DHN7OoLVUbTIQz+gazYjigVZvtwCvgrZI7eW9Xo1eOXM2zw2u1DGLLUfmGkQ==} + turbo-linux-64@2.0.12: + resolution: {integrity: sha512-+mQgGfg1eq5qF+wenK/FKJaNMNAo5DQLC4htQy+8osW+fx6U+8+6UlPQPaycAWDEqwOI7NwuqkeHfkEQLQUTyQ==} cpu: [x64] os: [linux] - turbo-linux-arm64@1.13.4: - resolution: {integrity: sha512-BJcXw1DDiHO/okYbaNdcWN6szjXyHWx9d460v6fCHY65G8CyqGU3y2uUTPK89o8lq/b2C8NK0yZD+Vp0f9VoIg==} + turbo-linux-arm64@2.0.12: + resolution: {integrity: sha512-KFyEZDXfPU1DK4zimxdCcqAcK7IIttX4mfsgB7NsSEOmH0dhHOih/YFYiyEDC1lTRx0C2RlzQ0Kjjdz48AN5Eg==} cpu: [arm64] os: [linux] - turbo-windows-64@1.13.4: - resolution: {integrity: sha512-OFFhXHOFLN7A78vD/dlVuuSSVEB3s9ZBj18Tm1hk3aW1HTWTuAw0ReN6ZNlVObZUHvGy8d57OAGGxf2bT3etQw==} + turbo-windows-64@2.0.12: + resolution: {integrity: sha512-kJj4KCkZTkDTDCqsSw1m1dbO4WeoQq1mYUm/thXOH0OkeqYbSMt0EyoTcJOgKUDsrMnzZD2gPfYrlYHtV69lVA==} cpu: [x64] os: [win32] - turbo-windows-arm64@1.13.4: - resolution: {integrity: sha512-u5A+VOKHswJJmJ8o8rcilBfU5U3Y1TTAfP9wX8bFh8teYF1ghP0EhtMRLjhtp6RPa+XCxHHVA2CiC3gbh5eg5g==} + turbo-windows-arm64@2.0.12: + resolution: {integrity: sha512-TY3ROxguDilN2olCwcZMaePdW01Xhma0pZU7bNhsQEqca9RGAmsZBuzfGnTMcWPmv4tpnb/PlX1hrt1Hod/44Q==} cpu: [arm64] os: [win32] - turbo@1.13.4: - resolution: {integrity: sha512-1q7+9UJABuBAHrcC4Sxp5lOqYS5mvxRrwa33wpIyM18hlOCpRD/fTJNxZ0vhbMcJmz15o9kkVm743mPn7p6jpQ==} + turbo@2.0.12: + resolution: {integrity: sha512-8s2KwqjwQj7z8Z53SUZSKVkQOZ2/Sl4D2F440oaBY/k2lGju60dW6srEpnn8/RIDeICZmQn3pQHF79Jfnc5Skw==} hasBin: true type-check@0.4.0: @@ -17872,32 +17872,32 @@ snapshots: tslib@2.6.2: {} - turbo-darwin-64@1.13.4: + turbo-darwin-64@2.0.12: optional: true - turbo-darwin-arm64@1.13.4: + turbo-darwin-arm64@2.0.12: optional: true - turbo-linux-64@1.13.4: + turbo-linux-64@2.0.12: optional: true - turbo-linux-arm64@1.13.4: + turbo-linux-arm64@2.0.12: optional: true - turbo-windows-64@1.13.4: + turbo-windows-64@2.0.12: optional: true - turbo-windows-arm64@1.13.4: + turbo-windows-arm64@2.0.12: optional: true - turbo@1.13.4: + turbo@2.0.12: optionalDependencies: - turbo-darwin-64: 1.13.4 - turbo-darwin-arm64: 1.13.4 - turbo-linux-64: 1.13.4 - turbo-linux-arm64: 1.13.4 - turbo-windows-64: 1.13.4 - turbo-windows-arm64: 1.13.4 + turbo-darwin-64: 2.0.12 + turbo-darwin-arm64: 2.0.12 + turbo-linux-64: 2.0.12 + turbo-linux-arm64: 2.0.12 + turbo-windows-64: 2.0.12 + turbo-windows-arm64: 2.0.12 type-check@0.4.0: dependencies: diff --git a/turbo.json b/turbo.json index ffced482bb5d..c873e24c9495 100644 --- a/turbo.json +++ b/turbo.json @@ -1,48 +1,67 @@ { - "$schema": "https://turborepo.org/schema.json", - "pipeline": { - "build": { - "dependsOn": ["^build"], - "inputs": [ - "**/*", - "!test/**/*", - "!e2e/**/*", - "!performance/**/*", - "!.astro/**/*", - "!.cache/**/*", - "!mod.js", - "!mod.js.map" - ], - "outputs": ["dist/**/*", "!vendor/**", "mod.js", "mod.js.map"], - "outputMode": "new-only" - }, - "build:ci": { - "dependsOn": ["^build:ci"], - "inputs": [ - "**/*", - "!test/**/*", - "!e2e/**/*", - "!performance/**/*", - "!.astro/**/*", - "!.cache/**/*", - "!mod.js", - "!mod.js.map" - ], - "outputs": ["dist/**/*", "!vendor/**", "mod.js", "mod.js.map"], - "outputMode": "new-only" - }, - "dev": { - "cache": false, - "persistent": true - }, - "test": { - "dependsOn": ["^test"], - "env": ["RUNNER_OS", "NODE_VERSION"], - "outputMode": "new-only" - }, - "test:hosted": { - "outputMode": "new-only", - "cache": false - } - } + "$schema": "https://turborepo.org/schema.json", + "tasks": { + "build": { + "dependsOn": [ + "^build" + ], + "inputs": [ + "**/*", + "!test/**/*", + "!e2e/**/*", + "!performance/**/*", + "!.astro/**/*", + "!.cache/**/*", + "!mod.js", + "!mod.js.map" + ], + "outputs": [ + "dist/**/*", + "!vendor/**", + "mod.js", + "mod.js.map" + ], + "outputLogs": "new-only" + }, + "build:ci": { + "dependsOn": [ + "^build:ci" + ], + "inputs": [ + "**/*", + "!test/**/*", + "!e2e/**/*", + "!performance/**/*", + "!.astro/**/*", + "!.cache/**/*", + "!mod.js", + "!mod.js.map" + ], + "outputs": [ + "dist/**/*", + "!vendor/**", + "mod.js", + "mod.js.map" + ], + "outputLogs": "new-only" + }, + "dev": { + "cache": false, + "persistent": true + }, + "test": { + "dependsOn": [ + "^test" + ], + "env": [ + "RUNNER_OS", + "NODE_VERSION" + ], + "outputLogs": "new-only" + }, + "test:hosted": { + "cache": false, + "outputLogs": "new-only" + } + } } From 791d809cbc22ed30dda1195ca026daa46a54b551 Mon Sep 17 00:00:00 2001 From: Matthew Phillips Date: Thu, 15 Aug 2024 04:34:25 -0400 Subject: [PATCH 09/29] Server Islands - Handle base + trailingSlash ignore (#11712) * Server Islands - Handle base + trailingSlash ignore * Add a changeset --- .changeset/kind-bees-admire.md | 5 +++++ .../fixtures/server-islands/astro.config.mjs | 2 +- packages/astro/e2e/server-islands.test.js | 20 +++++++++++++++++++ .../runtime/server/render/server-islands.ts | 3 ++- 4 files changed, 28 insertions(+), 2 deletions(-) create mode 100644 .changeset/kind-bees-admire.md diff --git a/.changeset/kind-bees-admire.md b/.changeset/kind-bees-admire.md new file mode 100644 index 000000000000..7aa359f58bee --- /dev/null +++ b/.changeset/kind-bees-admire.md @@ -0,0 +1,5 @@ +--- +'astro': patch +--- + +Fix mixed use of base + trailingSlash in Server Islands diff --git a/packages/astro/e2e/fixtures/server-islands/astro.config.mjs b/packages/astro/e2e/fixtures/server-islands/astro.config.mjs index 4bec97b9e1ad..2175a1bf8fe9 100644 --- a/packages/astro/e2e/fixtures/server-islands/astro.config.mjs +++ b/packages/astro/e2e/fixtures/server-islands/astro.config.mjs @@ -9,7 +9,7 @@ export default defineConfig({ output: 'hybrid', adapter: nodejs({ mode: 'standalone' }), integrations: [react(), mdx()], - trailingSlash: 'always', + trailingSlash: process.env.TRAILING_SLASH ?? 'always', experimental: { serverIslands: true, } diff --git a/packages/astro/e2e/server-islands.test.js b/packages/astro/e2e/server-islands.test.js index b37495b28812..2e68937b98e1 100644 --- a/packages/astro/e2e/server-islands.test.js +++ b/packages/astro/e2e/server-islands.test.js @@ -52,6 +52,26 @@ test.describe('Server islands', () => { }); }); + test.describe('Development - trailingSlash: ignore', () => { + let devServer; + + test.beforeAll(async ({ astro }) => { + process.env.TRAILING_SLASH = 'ignore'; + devServer = await astro.startDevServer(); + }); + + test.afterAll(async () => { + await devServer.stop(); + }); + + test('Load content from the server', async ({ page, astro }) => { + await page.goto(astro.resolveUrl('/base/')); + let el = page.locator('#island'); + + await expect(el, 'element rendered').toBeVisible(); + await expect(el, 'should have content').toHaveText('I am an island'); + }); + }); test.describe('Production', () => { let previewServer; diff --git a/packages/astro/src/runtime/server/render/server-islands.ts b/packages/astro/src/runtime/server/render/server-islands.ts index 58cce4e14814..153c01c6563d 100644 --- a/packages/astro/src/runtime/server/render/server-islands.ts +++ b/packages/astro/src/runtime/server/render/server-islands.ts @@ -64,7 +64,8 @@ export function renderServerIsland( const propsEncrypted = await encryptString(key, JSON.stringify(props)); const hostId = crypto.randomUUID(); - const serverIslandUrl = `${result.base}_server-islands/${componentId}${result.trailingSlash === 'always' ? '/' : ''}`; + const slash = result.base.endsWith('/') ? '' : '/'; + const serverIslandUrl = `${result.base}${slash}_server-islands/${componentId}${result.trailingSlash === 'always' ? '/' : ''}`; destination.write(` + + diff --git a/packages/astro/e2e/server-islands.test.js b/packages/astro/e2e/server-islands.test.js index 2e68937b98e1..1c4e2a7e8051 100644 --- a/packages/astro/e2e/server-islands.test.js +++ b/packages/astro/e2e/server-islands.test.js @@ -50,6 +50,12 @@ test.describe('Server islands', () => { await expect(el).toHaveCount(2); }); + + test('Missing server island start comment doesn\'t cause browser to lock up', async ({ page, astro }) => { + await page.goto(astro.resolveUrl('/base/')); + let el = page.locator('#first'); + await expect(el).toHaveCount(1); + }); }); test.describe('Development - trailingSlash: ignore', () => { diff --git a/packages/astro/src/runtime/server/render/server-islands.ts b/packages/astro/src/runtime/server/render/server-islands.ts index 153c01c6563d..0a072113447b 100644 --- a/packages/astro/src/runtime/server/render/server-islands.ts +++ b/packages/astro/src/runtime/server/render/server-islands.ts @@ -86,9 +86,10 @@ if(response.status === 200 && response.headers.get('content-type') === 'text/htm let html = await response.text(); // Swap! - while(script.previousSibling?.nodeType !== 8 && - script.previousSibling?.data !== 'server-island-start') { - script.previousSibling?.remove(); + while(script.previousSibling && + script.previousSibling.nodeType !== 8 && + script.previousSibling.data !== 'server-island-start') { + script.previousSibling.remove(); } script.previousSibling?.remove(); From 934165e21b8b51868db70bbdbc7ffda63b77aefd Mon Sep 17 00:00:00 2001 From: Matthew Phillips Date: Thu, 15 Aug 2024 12:04:50 +0000 Subject: [PATCH 14/29] [ci] format --- packages/astro/e2e/server-islands.test.js | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/packages/astro/e2e/server-islands.test.js b/packages/astro/e2e/server-islands.test.js index 1c4e2a7e8051..496cf229cc50 100644 --- a/packages/astro/e2e/server-islands.test.js +++ b/packages/astro/e2e/server-islands.test.js @@ -51,7 +51,10 @@ test.describe('Server islands', () => { await expect(el).toHaveCount(2); }); - test('Missing server island start comment doesn\'t cause browser to lock up', async ({ page, astro }) => { + test("Missing server island start comment doesn't cause browser to lock up", async ({ + page, + astro, + }) => { await page.goto(astro.resolveUrl('/base/')); let el = page.locator('#first'); await expect(el).toHaveCount(1); From 88a6ccb8c63ab93f17e5733db85b2ab351393af1 Mon Sep 17 00:00:00 2001 From: Emanuele Stoppa Date: Thu, 15 Aug 2024 14:44:30 +0100 Subject: [PATCH 15/29] chore(readme): adds the netlify adapter (#11726) --- README.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 9b5e734aa852..0827fb9739d9 100644 --- a/README.md +++ b/README.md @@ -51,7 +51,7 @@ Join us on [Discord](https://astro.build/chat) to meet other maintainers. We'll ## Directory | Package | Release Notes | -| ------------------------------------------------------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +|--------------------------------------------------------------------------------------------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | [astro](packages/astro) | [![astro version](https://img.shields.io/npm/v/astro.svg?label=%20)](packages/astro/CHANGELOG.md) | | [create-astro](packages/create-astro) | [![create-astro version](https://img.shields.io/npm/v/create-astro.svg?label=%20)](packages/create-astro/CHANGELOG.md) | | [@astrojs/react](packages/integrations/react) | [![@astrojs/react version](https://img.shields.io/npm/v/@astrojs/react.svg?label=%20)](packages/integrations/react/CHANGELOG.md) | @@ -70,6 +70,7 @@ Join us on [Discord](https://astro.build/chat) to meet other maintainers. We'll | [@astrojs/mdx](packages/integrations/mdx) | [![@astrojs/mdx version](https://img.shields.io/npm/v/@astrojs/mdx.svg?label=%20)](packages/integrations/mdx/CHANGELOG.md) | | [@astrojs/db](packages/db) | [![@astrojs/db version](https://img.shields.io/npm/v/@astrojs/db.svg?label=%20)](packages/db/CHANGELOG.md) | | [@astrojs/rss](packages/astro-rss) | [![@astrojs/rss version](https://img.shields.io/npm/v/@astrojs/rss.svg?label=%20)](packages/astro-rss/CHANGELOG.md) | +| [@astrojs/netlify](https://github.com/withastro/adapters/blob/main/packages/netlify) | [![@astrojs/netlify version](https://img.shields.io/npm/v/@astrojs/netlify.svg?label=%20)](https://github.com/withastro/adapters/blob/main/packages/netlify/CHANGELOG.md) | [![CII Best Practices](https://bestpractices.coreinfrastructure.org/projects/6178/badge)](https://bestpractices.coreinfrastructure.org/projects/6178) From 4844e1b5fbe2216078e14e316996e06e3c899c93 Mon Sep 17 00:00:00 2001 From: Emanuele Stoppa Date: Thu, 15 Aug 2024 14:45:12 +0100 Subject: [PATCH 16/29] chore: updates the supported features of test adapter (#11724) --- packages/astro/test/test-adapter.js | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/packages/astro/test/test-adapter.js b/packages/astro/test/test-adapter.js index 8c4643367d20..fc5249561279 100644 --- a/packages/astro/test/test-adapter.js +++ b/packages/astro/test/test-adapter.js @@ -108,6 +108,10 @@ export default function ({ supportedAstroFeatures: { serverOutput: 'stable', envGetSecret: 'experimental', + staticOutput: 'stable', + hybridOutput: 'stable', + assets: 'stable', + i18nDomains: 'stable', }, ...extendAdapter, }); From 9bf9f5a7b0cf0f5d8edd25d562e292349c685303 Mon Sep 17 00:00:00 2001 From: Emanuele Stoppa Date: Thu, 15 Aug 2024 13:46:00 +0000 Subject: [PATCH 17/29] [ci] format --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 0827fb9739d9..62589bac80ce 100644 --- a/README.md +++ b/README.md @@ -51,7 +51,7 @@ Join us on [Discord](https://astro.build/chat) to meet other maintainers. We'll ## Directory | Package | Release Notes | -|--------------------------------------------------------------------------------------------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| ------------------------------------------------------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | [astro](packages/astro) | [![astro version](https://img.shields.io/npm/v/astro.svg?label=%20)](packages/astro/CHANGELOG.md) | | [create-astro](packages/create-astro) | [![create-astro version](https://img.shields.io/npm/v/create-astro.svg?label=%20)](packages/create-astro/CHANGELOG.md) | | [@astrojs/react](packages/integrations/react) | [![@astrojs/react version](https://img.shields.io/npm/v/@astrojs/react.svg?label=%20)](packages/integrations/react/CHANGELOG.md) | From 6c1560fb0d19ce659bc9f9090f8050254d5c03f3 Mon Sep 17 00:00:00 2001 From: Matt Kane Date: Thu, 15 Aug 2024 15:26:00 +0100 Subject: [PATCH 18/29] fix: separate data store into mutable and immutable versions (#11725) * fix: separate data store into mutable and immutable versions * Add jsdoc --- .changeset/fresh-tigers-cheat.md | 5 + packages/astro/src/content/content-layer.ts | 6 +- packages/astro/src/content/data-store.ts | 375 +----------------- packages/astro/src/content/loaders/types.ts | 2 +- .../astro/src/content/mutable-data-store.ts | 370 +++++++++++++++++ packages/astro/src/content/utils.ts | 8 + packages/astro/src/core/dev/dev.ts | 10 +- packages/astro/src/core/sync/index.ts | 10 +- 8 files changed, 410 insertions(+), 376 deletions(-) create mode 100644 .changeset/fresh-tigers-cheat.md create mode 100644 packages/astro/src/content/mutable-data-store.ts diff --git a/.changeset/fresh-tigers-cheat.md b/.changeset/fresh-tigers-cheat.md new file mode 100644 index 000000000000..32dbccebd1de --- /dev/null +++ b/.changeset/fresh-tigers-cheat.md @@ -0,0 +1,5 @@ +--- +'astro': patch +--- + +Prevents content layer importing node builtins in runtime diff --git a/packages/astro/src/content/content-layer.ts b/packages/astro/src/content/content-layer.ts index 9a6d4ed37542..4861f3f61aa1 100644 --- a/packages/astro/src/content/content-layer.ts +++ b/packages/astro/src/content/content-layer.ts @@ -12,12 +12,12 @@ import { DATA_STORE_FILE, MODULES_IMPORTS_FILE, } from './consts.js'; -import type { DataStore } from './data-store.js'; import type { LoaderContext } from './loaders/types.js'; +import type { MutableDataStore } from './mutable-data-store.js'; import { getEntryDataAndImages, globalContentConfigObserver, posixRelative } from './utils.js'; export interface ContentLayerOptions { - store: DataStore; + store: MutableDataStore; settings: AstroSettings; logger: Logger; watcher?: FSWatcher; @@ -25,7 +25,7 @@ export interface ContentLayerOptions { export class ContentLayer { #logger: Logger; - #store: DataStore; + #store: MutableDataStore; #settings: AstroSettings; #watcher?: FSWatcher; #lastConfigDigest?: string; diff --git a/packages/astro/src/content/data-store.ts b/packages/astro/src/content/data-store.ts index e3b00f998924..76cefc411a76 100644 --- a/packages/astro/src/content/data-store.ts +++ b/packages/astro/src/content/data-store.ts @@ -1,11 +1,5 @@ -import { promises as fs, type PathLike, existsSync } from 'fs'; import type { MarkdownHeading } from '@astrojs/markdown-remark'; import * as devalue from 'devalue'; -import { imageSrcToImportId, importIdToSymbolName } from '../assets/utils/resolveImports.js'; -import { AstroError, AstroErrorData } from '../core/errors/index.js'; -import { CONTENT_MODULE_FLAG, DEFERRED_MODULE } from './consts.js'; - -const SAVE_DEBOUNCE_MS = 500; export interface RenderedContent { /** Rendered HTML string. If present then `render(entry)` will return a component that renders this HTML. */ @@ -41,75 +35,39 @@ export interface DataEntry = Record>(); - - #file?: PathLike; - - #assetsFile?: PathLike; - #modulesFile?: PathLike; - - #saveTimeout: NodeJS.Timeout | undefined; - #assetsSaveTimeout: NodeJS.Timeout | undefined; - #modulesSaveTimeout: NodeJS.Timeout | undefined; - - #dirty = false; - #assetsDirty = false; - #modulesDirty = false; +/** + * A read-only data store for content collections. This is used to retrieve data from the content layer at runtime. + * To add or modify data, use {@link MutableDataStore} instead. + */ - #assetImports = new Set(); - #moduleImports = new Map(); +export class DataStore { + protected _collections = new Map>(); constructor() { - this.#collections = new Map(); + this._collections = new Map(); } get(collectionName: string, key: string): T | undefined { - return this.#collections.get(collectionName)?.get(String(key)); + return this._collections.get(collectionName)?.get(String(key)); } entries(collectionName: string): Array<[id: string, T]> { - const collection = this.#collections.get(collectionName) ?? new Map(); + const collection = this._collections.get(collectionName) ?? new Map(); return [...collection.entries()]; } values(collectionName: string): Array { - const collection = this.#collections.get(collectionName) ?? new Map(); + const collection = this._collections.get(collectionName) ?? new Map(); return [...collection.values()]; } keys(collectionName: string): Array { - const collection = this.#collections.get(collectionName) ?? new Map(); + const collection = this._collections.get(collectionName) ?? new Map(); return [...collection.keys()]; } - set(collectionName: string, key: string, value: unknown) { - const collection = this.#collections.get(collectionName) ?? new Map(); - collection.set(String(key), value); - this.#collections.set(collectionName, collection); - this.#saveToDiskDebounced(); - } - - delete(collectionName: string, key: string) { - const collection = this.#collections.get(collectionName); - if (collection) { - collection.delete(String(key)); - this.#saveToDiskDebounced(); - } - } - - clear(collectionName: string) { - this.#collections.delete(collectionName); - this.#saveToDiskDebounced(); - } - - clearAll() { - this.#collections.clear(); - this.#saveToDiskDebounced(); - } - has(collectionName: string, key: string) { - const collection = this.#collections.get(collectionName); + const collection = this._collections.get(collectionName); if (collection) { return collection.has(String(key)); } @@ -117,234 +75,11 @@ export class DataStore { } hasCollection(collectionName: string) { - return this.#collections.has(collectionName); + return this._collections.has(collectionName); } collections() { - return this.#collections; - } - - addAssetImport(assetImport: string, filePath: string) { - const id = imageSrcToImportId(assetImport, filePath); - if (id) { - this.#assetImports.add(id); - // We debounce the writes to disk because addAssetImport is called for every image in every file, - // and can be called many times in quick succession by a filesystem watcher. We only want to write - // the file once, after all the imports have been added. - this.#writeAssetsImportsDebounced(); - } - } - - addAssetImports(assets: Array, filePath: string) { - assets.forEach((asset) => this.addAssetImport(asset, filePath)); - } - - addModuleImport(fileName: string) { - const id = contentModuleToId(fileName); - if (id) { - this.#moduleImports.set(fileName, id); - // We debounce the writes to disk because addAssetImport is called for every image in every file, - // and can be called many times in quick succession by a filesystem watcher. We only want to write - // the file once, after all the imports have been added. - this.#writeModulesImportsDebounced(); - } - } - - async writeAssetImports(filePath: PathLike) { - this.#assetsFile = filePath; - - if (this.#assetImports.size === 0) { - try { - await fs.writeFile(filePath, 'export default new Map();'); - } catch (err) { - throw new AstroError(AstroErrorData.UnknownFilesystemError, { cause: err }); - } - } - - if (!this.#assetsDirty && existsSync(filePath)) { - return; - } - // Import the assets, with a symbol name that is unique to the import id. The import - // for each asset is an object with path, format and dimensions. - // We then export them all, mapped by the import id, so we can find them again in the build. - const imports: Array = []; - const exports: Array = []; - this.#assetImports.forEach((id) => { - const symbol = importIdToSymbolName(id); - imports.push(`import ${symbol} from '${id}';`); - exports.push(`[${JSON.stringify(id)}, ${symbol}]`); - }); - const code = /* js */ ` -${imports.join('\n')} -export default new Map([${exports.join(', ')}]); - `; - try { - await fs.writeFile(filePath, code); - } catch (err) { - throw new AstroError(AstroErrorData.UnknownFilesystemError, { cause: err }); - } - this.#assetsDirty = false; - } - - async writeModuleImports(filePath: PathLike) { - this.#modulesFile = filePath; - - if (this.#moduleImports.size === 0) { - try { - await fs.writeFile(filePath, 'export default new Map();'); - } catch (err) { - throw new AstroError(AstroErrorData.UnknownFilesystemError, { cause: err }); - } - } - - if (!this.#modulesDirty && existsSync(filePath)) { - return; - } - - // Import the assets, with a symbol name that is unique to the import id. The import - // for each asset is an object with path, format and dimensions. - // We then export them all, mapped by the import id, so we can find them again in the build. - const lines: Array = []; - for (const [fileName, specifier] of this.#moduleImports) { - lines.push(`['${fileName}', () => import('${specifier}')]`); - } - const code = ` -export default new Map([\n${lines.join(',\n')}]); - `; - try { - await fs.writeFile(filePath, code); - } catch (err) { - throw new AstroError(AstroErrorData.UnknownFilesystemError, { cause: err }); - } - this.#modulesDirty = false; - } - - #writeAssetsImportsDebounced() { - this.#assetsDirty = true; - if (this.#assetsFile) { - if (this.#assetsSaveTimeout) { - clearTimeout(this.#assetsSaveTimeout); - } - this.#assetsSaveTimeout = setTimeout(() => { - this.#assetsSaveTimeout = undefined; - this.writeAssetImports(this.#assetsFile!); - }, SAVE_DEBOUNCE_MS); - } - } - - #writeModulesImportsDebounced() { - this.#modulesDirty = true; - if (this.#modulesFile) { - if (this.#modulesSaveTimeout) { - clearTimeout(this.#modulesSaveTimeout); - } - this.#modulesSaveTimeout = setTimeout(() => { - this.#modulesSaveTimeout = undefined; - this.writeModuleImports(this.#modulesFile!); - }, SAVE_DEBOUNCE_MS); - } - } - - #saveToDiskDebounced() { - this.#dirty = true; - // Only save to disk if it has already been saved once - if (this.#file) { - if (this.#saveTimeout) { - clearTimeout(this.#saveTimeout); - } - this.#saveTimeout = setTimeout(() => { - this.#saveTimeout = undefined; - this.writeToDisk(this.#file!); - }, SAVE_DEBOUNCE_MS); - } - } - - scopedStore(collectionName: string): ScopedDataStore { - return { - get: = Record>(key: string) => - this.get>(collectionName, key), - entries: () => this.entries(collectionName), - values: () => this.values(collectionName), - keys: () => this.keys(collectionName), - set: ({ id: key, data, body, filePath, deferredRender, digest, rendered }) => { - if (!key) { - throw new Error(`ID must be a non-empty string`); - } - const id = String(key); - if (digest) { - const existing = this.get(collectionName, id); - if (existing && existing.digest === digest) { - return false; - } - } - const entry: DataEntry = { - id, - data, - }; - // We do it like this so we don't waste space stringifying - // the fields if they are not set - if (body) { - entry.body = body; - } - if (filePath) { - if (filePath.startsWith('/')) { - throw new Error(`File path must be relative to the site root. Got: ${filePath}`); - } - entry.filePath = filePath; - } - if (digest) { - entry.digest = digest; - } - if (rendered) { - entry.rendered = rendered; - } - if (deferredRender) { - entry.deferredRender = deferredRender; - if (filePath) { - this.addModuleImport(filePath); - } - } - this.set(collectionName, id, entry); - return true; - }, - delete: (key: string) => this.delete(collectionName, key), - clear: () => this.clear(collectionName), - has: (key: string) => this.has(collectionName, key), - addAssetImport: (assetImport: string, fileName: string) => - this.addAssetImport(assetImport, fileName), - addAssetImports: (assets: Array, fileName: string) => - this.addAssetImports(assets, fileName), - addModuleImport: (fileName: string) => this.addModuleImport(fileName), - }; - } - /** - * Returns a MetaStore for a given collection, or if no collection is provided, the default meta collection. - */ - metaStore(collectionName = ':meta'): MetaStore { - const collectionKey = `meta:${collectionName}`; - return { - get: (key: string) => this.get(collectionKey, key), - set: (key: string, data: string) => this.set(collectionKey, key, data), - delete: (key: string) => this.delete(collectionKey, key), - has: (key: string) => this.has(collectionKey, key), - }; - } - - toString() { - return devalue.stringify(this.#collections); - } - - async writeToDisk(filePath: PathLike) { - if (!this.#dirty) { - return; - } - try { - await fs.writeFile(filePath, this.toString()); - this.#file = filePath; - this.#dirty = false; - } catch (err) { - throw new AstroError(AstroErrorData.UnknownFilesystemError, { cause: err }); - } + return this._collections; } /** @@ -363,81 +98,9 @@ export default new Map([\n${lines.join(',\n')}]); static async fromMap(data: Map>) { const store = new DataStore(); - store.#collections = data; + store._collections = data; return store; } - - static async fromString(data: string) { - const map = devalue.parse(data); - return DataStore.fromMap(map); - } - - static async fromFile(filePath: string | URL) { - try { - if (existsSync(filePath)) { - const data = await fs.readFile(filePath, 'utf-8'); - return DataStore.fromString(data); - } - } catch {} - return new DataStore(); - } -} - -export interface ScopedDataStore { - get: = Record>( - key: string, - ) => DataEntry | undefined; - entries: () => Array<[id: string, DataEntry]>; - set: >(opts: { - /** The ID of the entry. Must be unique per collection. */ - id: string; - /** The data to store. */ - data: TData; - /** The raw body of the content, if applicable. */ - body?: string; - /** The file path of the content, if applicable. Relative to the site root. */ - filePath?: string; - /** A content digest, to check if the content has changed. */ - digest?: number | string; - /** The rendered content, if applicable. */ - rendered?: RenderedContent; - /** - * If an entry is a deferred, its rendering phase is delegated to a virtual module during the runtime phase. - */ - deferredRender?: boolean; - }) => boolean; - values: () => Array; - keys: () => Array; - delete: (key: string) => void; - clear: () => void; - has: (key: string) => boolean; - /** - * @internal Adds asset imports to the store. This is used to track image imports for the build. This API is subject to change. - */ - addAssetImports: (assets: Array, fileName: string) => void; - /** - * @internal Adds an asset import to the store. This is used to track image imports for the build. This API is subject to change. - */ - addAssetImport: (assetImport: string, fileName: string) => void; - /** - * Adds a single asset to the store. This asset will be transformed - * by Vite, and the URL will be available in the final build. - * @param fileName - * @param specifier - * @returns - */ - addModuleImport: (fileName: string) => void; -} - -/** - * A key-value store for metadata strings. Useful for storing things like sync tokens. - */ - -export interface MetaStore { - get: (key: string) => string | undefined; - set: (key: string, value: string) => void; - has: (key: string) => boolean; - delete: (key: string) => void; } function dataStoreSingleton() { @@ -455,13 +118,5 @@ function dataStoreSingleton() { }; } -// TODO: find a better place to put this image -export function contentModuleToId(fileName: string) { - const params = new URLSearchParams(DEFERRED_MODULE); - params.set('fileName', fileName); - params.set(CONTENT_MODULE_FLAG, 'true'); - return `${DEFERRED_MODULE}?${params.toString()}`; -} - /** @internal */ export const globalDataStore = dataStoreSingleton(); diff --git a/packages/astro/src/content/loaders/types.ts b/packages/astro/src/content/loaders/types.ts index f372967277b7..26be0495a281 100644 --- a/packages/astro/src/content/loaders/types.ts +++ b/packages/astro/src/content/loaders/types.ts @@ -1,7 +1,7 @@ import type { FSWatcher } from 'vite'; import type { ZodSchema } from 'zod'; import type { AstroIntegrationLogger, AstroSettings } from '../../@types/astro.js'; -import type { MetaStore, ScopedDataStore } from '../data-store.js'; +import type { MetaStore, ScopedDataStore } from '../mutable-data-store.js'; export interface ParseDataOptions> { /** The ID of the entry. Unique per collection */ diff --git a/packages/astro/src/content/mutable-data-store.ts b/packages/astro/src/content/mutable-data-store.ts new file mode 100644 index 000000000000..200951848046 --- /dev/null +++ b/packages/astro/src/content/mutable-data-store.ts @@ -0,0 +1,370 @@ +import { promises as fs, type PathLike, existsSync } from 'node:fs'; +import * as devalue from 'devalue'; +import { imageSrcToImportId, importIdToSymbolName } from '../assets/utils/resolveImports.js'; +import { AstroError, AstroErrorData } from '../core/errors/index.js'; +import { type DataEntry, DataStore, type RenderedContent } from './data-store.js'; +import { contentModuleToId } from './utils.js'; + +const SAVE_DEBOUNCE_MS = 500; + +/** + * Extends the DataStore with the ability to change entries and write them to disk. + * This is kept as a separate class to avoid needing node builtins at runtime, when read-only access is all that is needed. + */ +export class MutableDataStore extends DataStore { + #file?: PathLike; + + #assetsFile?: PathLike; + #modulesFile?: PathLike; + + #saveTimeout: NodeJS.Timeout | undefined; + #assetsSaveTimeout: NodeJS.Timeout | undefined; + #modulesSaveTimeout: NodeJS.Timeout | undefined; + + #dirty = false; + #assetsDirty = false; + #modulesDirty = false; + + #assetImports = new Set(); + #moduleImports = new Map(); + + set(collectionName: string, key: string, value: unknown) { + const collection = this._collections.get(collectionName) ?? new Map(); + collection.set(String(key), value); + this._collections.set(collectionName, collection); + this.#saveToDiskDebounced(); + } + + delete(collectionName: string, key: string) { + const collection = this._collections.get(collectionName); + if (collection) { + collection.delete(String(key)); + this.#saveToDiskDebounced(); + } + } + + clear(collectionName: string) { + this._collections.delete(collectionName); + this.#saveToDiskDebounced(); + } + + clearAll() { + this._collections.clear(); + this.#saveToDiskDebounced(); + } + + addAssetImport(assetImport: string, filePath: string) { + const id = imageSrcToImportId(assetImport, filePath); + if (id) { + this.#assetImports.add(id); + // We debounce the writes to disk because addAssetImport is called for every image in every file, + // and can be called many times in quick succession by a filesystem watcher. We only want to write + // the file once, after all the imports have been added. + this.#writeAssetsImportsDebounced(); + } + } + + addAssetImports(assets: Array, filePath: string) { + assets.forEach((asset) => this.addAssetImport(asset, filePath)); + } + + addModuleImport(fileName: string) { + const id = contentModuleToId(fileName); + if (id) { + this.#moduleImports.set(fileName, id); + // We debounce the writes to disk because addAssetImport is called for every image in every file, + // and can be called many times in quick succession by a filesystem watcher. We only want to write + // the file once, after all the imports have been added. + this.#writeModulesImportsDebounced(); + } + } + + async writeAssetImports(filePath: PathLike) { + this.#assetsFile = filePath; + + if (this.#assetImports.size === 0) { + try { + await fs.writeFile(filePath, 'export default new Map();'); + } catch (err) { + throw new AstroError(AstroErrorData.UnknownFilesystemError, { cause: err }); + } + } + + if (!this.#assetsDirty && existsSync(filePath)) { + return; + } + // Import the assets, with a symbol name that is unique to the import id. The import + // for each asset is an object with path, format and dimensions. + // We then export them all, mapped by the import id, so we can find them again in the build. + const imports: Array = []; + const exports: Array = []; + this.#assetImports.forEach((id) => { + const symbol = importIdToSymbolName(id); + imports.push(`import ${symbol} from '${id}';`); + exports.push(`[${JSON.stringify(id)}, ${symbol}]`); + }); + const code = /* js */ ` +${imports.join('\n')} +export default new Map([${exports.join(', ')}]); + `; + try { + await fs.writeFile(filePath, code); + } catch (err) { + throw new AstroError(AstroErrorData.UnknownFilesystemError, { cause: err }); + } + this.#assetsDirty = false; + } + + async writeModuleImports(filePath: PathLike) { + this.#modulesFile = filePath; + + if (this.#moduleImports.size === 0) { + try { + await fs.writeFile(filePath, 'export default new Map();'); + } catch (err) { + throw new AstroError(AstroErrorData.UnknownFilesystemError, { cause: err }); + } + } + + if (!this.#modulesDirty && existsSync(filePath)) { + return; + } + + // Import the assets, with a symbol name that is unique to the import id. The import + // for each asset is an object with path, format and dimensions. + // We then export them all, mapped by the import id, so we can find them again in the build. + const lines: Array = []; + for (const [fileName, specifier] of this.#moduleImports) { + lines.push(`['${fileName}', () => import('${specifier}')]`); + } + const code = ` +export default new Map([\n${lines.join(',\n')}]); + `; + try { + await fs.writeFile(filePath, code); + } catch (err) { + throw new AstroError(AstroErrorData.UnknownFilesystemError, { cause: err }); + } + this.#modulesDirty = false; + } + + #writeAssetsImportsDebounced() { + this.#assetsDirty = true; + if (this.#assetsFile) { + if (this.#assetsSaveTimeout) { + clearTimeout(this.#assetsSaveTimeout); + } + this.#assetsSaveTimeout = setTimeout(() => { + this.#assetsSaveTimeout = undefined; + this.writeAssetImports(this.#assetsFile!); + }, SAVE_DEBOUNCE_MS); + } + } + + #writeModulesImportsDebounced() { + this.#modulesDirty = true; + if (this.#modulesFile) { + if (this.#modulesSaveTimeout) { + clearTimeout(this.#modulesSaveTimeout); + } + this.#modulesSaveTimeout = setTimeout(() => { + this.#modulesSaveTimeout = undefined; + this.writeModuleImports(this.#modulesFile!); + }, SAVE_DEBOUNCE_MS); + } + } + + #saveToDiskDebounced() { + this.#dirty = true; + // Only save to disk if it has already been saved once + if (this.#file) { + if (this.#saveTimeout) { + clearTimeout(this.#saveTimeout); + } + this.#saveTimeout = setTimeout(() => { + this.#saveTimeout = undefined; + this.writeToDisk(this.#file!); + }, SAVE_DEBOUNCE_MS); + } + } + + scopedStore(collectionName: string): ScopedDataStore { + return { + get: = Record>(key: string) => + this.get>(collectionName, key), + entries: () => this.entries(collectionName), + values: () => this.values(collectionName), + keys: () => this.keys(collectionName), + set: ({ id: key, data, body, filePath, deferredRender, digest, rendered }) => { + if (!key) { + throw new Error(`ID must be a non-empty string`); + } + const id = String(key); + if (digest) { + const existing = this.get(collectionName, id); + if (existing && existing.digest === digest) { + return false; + } + } + const entry: DataEntry = { + id, + data, + }; + // We do it like this so we don't waste space stringifying + // the fields if they are not set + if (body) { + entry.body = body; + } + if (filePath) { + if (filePath.startsWith('/')) { + throw new Error(`File path must be relative to the site root. Got: ${filePath}`); + } + entry.filePath = filePath; + } + if (digest) { + entry.digest = digest; + } + if (rendered) { + entry.rendered = rendered; + } + if (deferredRender) { + entry.deferredRender = deferredRender; + if (filePath) { + this.addModuleImport(filePath); + } + } + this.set(collectionName, id, entry); + return true; + }, + delete: (key: string) => this.delete(collectionName, key), + clear: () => this.clear(collectionName), + has: (key: string) => this.has(collectionName, key), + addAssetImport: (assetImport: string, fileName: string) => + this.addAssetImport(assetImport, fileName), + addAssetImports: (assets: Array, fileName: string) => + this.addAssetImports(assets, fileName), + addModuleImport: (fileName: string) => this.addModuleImport(fileName), + }; + } + /** + * Returns a MetaStore for a given collection, or if no collection is provided, the default meta collection. + */ + metaStore(collectionName = ':meta'): MetaStore { + const collectionKey = `meta:${collectionName}`; + return { + get: (key: string) => this.get(collectionKey, key), + set: (key: string, data: string) => this.set(collectionKey, key, data), + delete: (key: string) => this.delete(collectionKey, key), + has: (key: string) => this.has(collectionKey, key), + }; + } + + toString() { + return devalue.stringify(this._collections); + } + + async writeToDisk(filePath: PathLike) { + if (!this.#dirty) { + return; + } + try { + await fs.writeFile(filePath, this.toString()); + this.#file = filePath; + this.#dirty = false; + } catch (err) { + throw new AstroError(AstroErrorData.UnknownFilesystemError, { cause: err }); + } + } + + /** + * Attempts to load a MutableDataStore from the virtual module. + * This only works in Vite. + */ + static async fromModule() { + try { + // @ts-expect-error - this is a virtual module + const data = await import('astro:data-layer-content'); + const map = devalue.unflatten(data.default); + return MutableDataStore.fromMap(map); + } catch {} + return new MutableDataStore(); + } + + static async fromMap(data: Map>) { + const store = new MutableDataStore(); + store._collections = data; + return store; + } + + static async fromString(data: string) { + const map = devalue.parse(data); + return MutableDataStore.fromMap(map); + } + + static async fromFile(filePath: string | URL) { + try { + if (existsSync(filePath)) { + const data = await fs.readFile(filePath, 'utf-8'); + return MutableDataStore.fromString(data); + } + } catch {} + return new MutableDataStore(); + } +} + +export interface ScopedDataStore { + get: = Record>( + key: string, + ) => DataEntry | undefined; + entries: () => Array<[id: string, DataEntry]>; + set: >(opts: { + /** The ID of the entry. Must be unique per collection. */ + id: string; + /** The data to store. */ + data: TData; + /** The raw body of the content, if applicable. */ + body?: string; + /** The file path of the content, if applicable. Relative to the site root. */ + filePath?: string; + /** A content digest, to check if the content has changed. */ + digest?: number | string; + /** The rendered content, if applicable. */ + rendered?: RenderedContent; + /** + * If an entry is a deferred, its rendering phase is delegated to a virtual module during the runtime phase. + */ + deferredRender?: boolean; + }) => boolean; + values: () => Array; + keys: () => Array; + delete: (key: string) => void; + clear: () => void; + has: (key: string) => boolean; + /** + * @internal Adds asset imports to the store. This is used to track image imports for the build. This API is subject to change. + */ + addAssetImports: (assets: Array, fileName: string) => void; + /** + * @internal Adds an asset import to the store. This is used to track image imports for the build. This API is subject to change. + */ + addAssetImport: (assetImport: string, fileName: string) => void; + /** + * Adds a single asset to the store. This asset will be transformed + * by Vite, and the URL will be available in the final build. + * @param fileName + * @param specifier + * @returns + */ + addModuleImport: (fileName: string) => void; +} + +/** + * A key-value store for metadata strings. Useful for storing things like sync tokens. + */ + +export interface MetaStore { + get: (key: string) => string | undefined; + set: (key: string, value: string) => void; + has: (key: string) => boolean; + delete: (key: string) => void; +} diff --git a/packages/astro/src/content/utils.ts b/packages/astro/src/content/utils.ts index 79a37a28d02f..6d06272470d0 100644 --- a/packages/astro/src/content/utils.ts +++ b/packages/astro/src/content/utils.ts @@ -20,6 +20,7 @@ import { CONTENT_FLAGS, CONTENT_LAYER_TYPE, CONTENT_MODULE_FLAG, + DEFERRED_MODULE, IMAGE_IMPORT_PREFIX, PROPAGATED_ASSET_FLAG, } from './consts.js'; @@ -670,3 +671,10 @@ export function posixifyPath(filePath: string) { export function posixRelative(from: string, to: string) { return posixifyPath(path.relative(from, to)); } + +export function contentModuleToId(fileName: string) { + const params = new URLSearchParams(DEFERRED_MODULE); + params.set('fileName', fileName); + params.set(CONTENT_MODULE_FLAG, 'true'); + return `${DEFERRED_MODULE}?${params.toString()}`; +} diff --git a/packages/astro/src/core/dev/dev.ts b/packages/astro/src/core/dev/dev.ts index 127f34b94989..8d19356b6950 100644 --- a/packages/astro/src/core/dev/dev.ts +++ b/packages/astro/src/core/dev/dev.ts @@ -8,8 +8,8 @@ import type * as vite from 'vite'; import type { AstroInlineConfig } from '../../@types/astro.js'; import { DATA_STORE_FILE } from '../../content/consts.js'; import { globalContentLayer } from '../../content/content-layer.js'; -import { DataStore, globalDataStore } from '../../content/data-store.js'; import { attachContentServerListeners } from '../../content/index.js'; +import { MutableDataStore } from '../../content/mutable-data-store.js'; import { globalContentConfigObserver } from '../../content/utils.js'; import { telemetry } from '../../events/index.js'; import * as msg from '../messages.js'; @@ -106,19 +106,17 @@ export default async function dev(inlineConfig: AstroInlineConfig): Promise Date: Thu, 15 Aug 2024 16:52:15 +0200 Subject: [PATCH 19/29] fix: content types sync in dev (#11727) Co-authored-by: Princesseuh <3019731+Princesseuh@users.noreply.github.com> --- .changeset/ten-buckets-matter.md | 5 +++++ packages/astro/src/content/types-generator.ts | 8 +++----- packages/astro/src/core/sync/index.ts | 3 ++- 3 files changed, 10 insertions(+), 6 deletions(-) create mode 100644 .changeset/ten-buckets-matter.md diff --git a/.changeset/ten-buckets-matter.md b/.changeset/ten-buckets-matter.md new file mode 100644 index 000000000000..b70a244a0591 --- /dev/null +++ b/.changeset/ten-buckets-matter.md @@ -0,0 +1,5 @@ +--- +'astro': patch +--- + +Fixes a type issue when using the Content Layer in dev diff --git a/packages/astro/src/content/types-generator.ts b/packages/astro/src/content/types-generator.ts index 973a892fa17f..faf02d95d915 100644 --- a/packages/astro/src/content/types-generator.ts +++ b/packages/astro/src/content/types-generator.ts @@ -590,11 +590,9 @@ async function writeContentFiles({ // If it's the first time, we inject types the usual way. sync() will handle creating files and references. If it's not the first time, we just override the dts content if (settings.injectedTypes.some((t) => t.filename === CONTENT_TYPES_FILE)) { - fs.promises.writeFile( - new URL(CONTENT_TYPES_FILE, settings.dotAstroDir), - typeTemplateContent, - 'utf-8', - ); + const filePath = fileURLToPath(new URL(CONTENT_TYPES_FILE, settings.dotAstroDir)); + await fs.promises.mkdir(path.dirname(filePath), { recursive: true }); + await fs.promises.writeFile(filePath, typeTemplateContent, 'utf-8'); } else { settings.injectedTypes.push({ filename: CONTENT_TYPES_FILE, diff --git a/packages/astro/src/core/sync/index.ts b/packages/astro/src/core/sync/index.ts index ce381537e2a5..aecf6c9c3d31 100644 --- a/packages/astro/src/core/sync/index.ts +++ b/packages/astro/src/core/sync/index.ts @@ -29,6 +29,7 @@ import type { Logger } from '../logger/core.js'; import { formatErrorMessage } from '../messages.js'; import { ensureProcessNodeEnv } from '../util.js'; import { writeFiles } from './write-files.js'; +import { fileURLToPath } from 'node:url'; export type SyncOptions = { /** @@ -122,7 +123,7 @@ export async function syncInternal({ }); await contentLayer.sync(); settings.timer.end('Sync content layer'); - } else if (fs.existsSync(getContentPaths(settings.config, fs).contentDir.href)) { + } else if (fs.existsSync(fileURLToPath(getContentPaths(settings.config, fs).contentDir))) { // Content is synced after writeFiles. That means references are not created // To work around it, we create a stub so the reference is created and content // sync will override the empty file From 70945dd9181e2dd021b92f3f82d66b0cd929def9 Mon Sep 17 00:00:00 2001 From: Florian Lefebvre Date: Thu, 15 Aug 2024 16:52:26 +0200 Subject: [PATCH 20/29] refactor: enforce node prefix (#11723) --- biome.json | 10 +++++++++- package.json | 2 +- packages/astro/src/assets/endpoint/node.ts | 2 +- packages/astro/src/core/dev/dev.ts | 2 +- packages/astro/src/core/logger/vite.ts | 2 +- .../astro/src/core/preview/static-preview-server.ts | 2 +- packages/astro/src/core/routing/manifest/create.ts | 2 +- .../astro/src/vite-plugin-astro-server/response.ts | 2 +- packages/astro/test/build-readonly-file.test.js | 2 +- packages/db/src/core/integration/index.ts | 8 ++++---- packages/db/test/local-prod.test.js | 4 ++-- packages/integrations/node/src/standalone.ts | 2 +- packages/integrations/partytown/src/index.ts | 2 +- packages/integrations/sitemap/src/write-sitemap.ts | 10 +++++----- 14 files changed, 30 insertions(+), 22 deletions(-) diff --git a/biome.json b/biome.json index 2928e8f4fe3d..67e2a4620e0f 100644 --- a/biome.json +++ b/biome.json @@ -26,7 +26,15 @@ "organizeImports": { "enabled": true }, - "linter": { "enabled": false }, + "linter": { + "enabled": true, + "rules": { + "recommended": false, + "style": { + "useNodejsImportProtocol": "error" + } + } + }, "javascript": { "formatter": { "trailingCommas": "all", diff --git a/package.json b/package.json index 6958dee90d3e..850816b5e115 100644 --- a/package.json +++ b/package.json @@ -35,7 +35,7 @@ "test:e2e:match": "cd packages/astro && pnpm playwright install chromium firefox && pnpm run test:e2e:match", "test:e2e:hosts": "turbo run test:hosted", "benchmark": "astro-benchmark", - "lint": "eslint . --report-unused-disable-directives", + "lint": "biome lint && eslint . --report-unused-disable-directives", "version": "changeset version && node ./scripts/deps/update-example-versions.js && pnpm install --no-frozen-lockfile && pnpm run format", "preinstall": "npx only-allow pnpm" }, diff --git a/packages/astro/src/assets/endpoint/node.ts b/packages/astro/src/assets/endpoint/node.ts index 4c50fe95fdb3..c1acc66efc15 100644 --- a/packages/astro/src/assets/endpoint/node.ts +++ b/packages/astro/src/assets/endpoint/node.ts @@ -5,7 +5,7 @@ import { fileURLToPath, pathToFileURL } from 'node:url'; // @ts-expect-error import { assetsDir, imageConfig, outDir } from 'astro:assets'; import { isRemotePath, removeQueryString } from '@astrojs/internal-helpers/path'; -import { readFile } from 'fs/promises'; +import { readFile } from 'node:fs/promises'; import * as mime from 'mrmime'; import type { APIRoute } from '../../@types/astro.js'; import { getConfiguredImageService } from '../internal.js'; diff --git a/packages/astro/src/core/dev/dev.ts b/packages/astro/src/core/dev/dev.ts index 8d19356b6950..ab1564d4e75f 100644 --- a/packages/astro/src/core/dev/dev.ts +++ b/packages/astro/src/core/dev/dev.ts @@ -2,7 +2,7 @@ import fs, { existsSync } from 'node:fs'; import type http from 'node:http'; import type { AddressInfo } from 'node:net'; import { green } from 'kleur/colors'; -import { performance } from 'perf_hooks'; +import { performance } from 'node:perf_hooks'; import { gt, major, minor, patch } from 'semver'; import type * as vite from 'vite'; import type { AstroInlineConfig } from '../../@types/astro.js'; diff --git a/packages/astro/src/core/logger/vite.ts b/packages/astro/src/core/logger/vite.ts index ed62adc8d047..f1ed49dce0d2 100644 --- a/packages/astro/src/core/logger/vite.ts +++ b/packages/astro/src/core/logger/vite.ts @@ -1,4 +1,4 @@ -import { fileURLToPath } from 'url'; +import { fileURLToPath } from 'node:url'; import stripAnsi from 'strip-ansi'; import type { LogLevel, Rollup, Logger as ViteLogger } from 'vite'; import { isAstroError } from '../errors/errors.js'; diff --git a/packages/astro/src/core/preview/static-preview-server.ts b/packages/astro/src/core/preview/static-preview-server.ts index 68ca3236b296..96afeb1b3781 100644 --- a/packages/astro/src/core/preview/static-preview-server.ts +++ b/packages/astro/src/core/preview/static-preview-server.ts @@ -1,6 +1,6 @@ import type http from 'node:http'; import { fileURLToPath } from 'node:url'; -import { performance } from 'perf_hooks'; +import { performance } from 'node:perf_hooks'; import { type PreviewServer as VitePreviewServer, preview } from 'vite'; import type { AstroSettings } from '../../@types/astro.js'; import type { Logger } from '../logger/core.js'; diff --git a/packages/astro/src/core/routing/manifest/create.ts b/packages/astro/src/core/routing/manifest/create.ts index f9c19b9ed0fd..d9a6c61b030e 100644 --- a/packages/astro/src/core/routing/manifest/create.ts +++ b/packages/astro/src/core/routing/manifest/create.ts @@ -8,7 +8,7 @@ import type { } from '../../../@types/astro.js'; import type { Logger } from '../../logger/core.js'; -import { createRequire } from 'module'; +import { createRequire } from 'node:module'; import nodeFs from 'node:fs'; import path from 'node:path'; import { fileURLToPath } from 'node:url'; diff --git a/packages/astro/src/vite-plugin-astro-server/response.ts b/packages/astro/src/vite-plugin-astro-server/response.ts index 2ccf1aade161..707a26e4091c 100644 --- a/packages/astro/src/vite-plugin-astro-server/response.ts +++ b/packages/astro/src/vite-plugin-astro-server/response.ts @@ -2,7 +2,7 @@ import type http from 'node:http'; import type { ErrorWithMetadata } from '../core/errors/index.js'; import type { ModuleLoader } from '../core/module-loader/index.js'; -import { Readable } from 'stream'; +import { Readable } from 'node:stream'; import { getSetCookiesFromResponse } from '../core/cookies/index.js'; import { getViteErrorPayload } from '../core/errors/dev/index.js'; import notFoundTemplate from '../template/4xx.js'; diff --git a/packages/astro/test/build-readonly-file.test.js b/packages/astro/test/build-readonly-file.test.js index bf6dd3fa4400..60b3f507be47 100644 --- a/packages/astro/test/build-readonly-file.test.js +++ b/packages/astro/test/build-readonly-file.test.js @@ -1,5 +1,5 @@ import { after, before, describe, it } from 'node:test'; -import { fileURLToPath } from 'url'; +import { fileURLToPath } from 'node:url'; import testAdapter from './test-adapter.js'; import { loadFixture } from './test-utils.js'; diff --git a/packages/db/src/core/integration/index.ts b/packages/db/src/core/integration/index.ts index 68439cfb9541..7be43c0daccb 100644 --- a/packages/db/src/core/integration/index.ts +++ b/packages/db/src/core/integration/index.ts @@ -1,11 +1,11 @@ -import { existsSync } from 'fs'; +import { existsSync } from 'node:fs'; import { parseArgs } from 'node:util'; -import { dirname } from 'path'; -import { fileURLToPath } from 'url'; +import { dirname } from 'node:path'; +import { fileURLToPath } from 'node:url'; import { type ManagedAppToken, getManagedAppTokenOrExit } from '@astrojs/studio'; import { LibsqlError } from '@libsql/client'; import type { AstroConfig, AstroIntegration } from 'astro'; -import { mkdir, writeFile } from 'fs/promises'; +import { mkdir, writeFile } from 'node:fs/promises'; import { blue, yellow } from 'kleur/colors'; import { type HMRPayload, diff --git a/packages/db/test/local-prod.test.js b/packages/db/test/local-prod.test.js index 134ee6b567bb..be67d179a3ea 100644 --- a/packages/db/test/local-prod.test.js +++ b/packages/db/test/local-prod.test.js @@ -1,7 +1,7 @@ import assert from 'node:assert/strict'; import { after, before, describe, it } from 'node:test'; -import { relative } from 'path'; -import { fileURLToPath } from 'url'; +import { relative } from 'node:path'; +import { fileURLToPath } from 'node:url'; import testAdapter from '../../astro/test/test-adapter.js'; import { loadFixture } from '../../astro/test/test-utils.js'; diff --git a/packages/integrations/node/src/standalone.ts b/packages/integrations/node/src/standalone.ts index 817ca70204fb..69db5ef2313b 100644 --- a/packages/integrations/node/src/standalone.ts +++ b/packages/integrations/node/src/standalone.ts @@ -1,4 +1,4 @@ -import https from 'https'; +import https from 'node:https'; import fs from 'node:fs'; import http from 'node:http'; import type { PreviewServer } from 'astro'; diff --git a/packages/integrations/partytown/src/index.ts b/packages/integrations/partytown/src/index.ts index bf8a6db1cbfa..9589e32a6cc1 100644 --- a/packages/integrations/partytown/src/index.ts +++ b/packages/integrations/partytown/src/index.ts @@ -1,4 +1,4 @@ -import { createRequire } from 'module'; +import { createRequire } from 'node:module'; import * as fs from 'node:fs'; import path from 'node:path'; import { fileURLToPath } from 'node:url'; diff --git a/packages/integrations/sitemap/src/write-sitemap.ts b/packages/integrations/sitemap/src/write-sitemap.ts index 8c86ae1669d2..b6a0c63c2f58 100644 --- a/packages/integrations/sitemap/src/write-sitemap.ts +++ b/packages/integrations/sitemap/src/write-sitemap.ts @@ -1,8 +1,8 @@ -import { type WriteStream, createWriteStream } from 'fs'; -import { normalize, resolve } from 'path'; -import { Readable, pipeline } from 'stream'; -import { promisify } from 'util'; -import { mkdir } from 'fs/promises'; +import { type WriteStream, createWriteStream } from 'node:fs'; +import { normalize, resolve } from 'node:path'; +import { Readable, pipeline } from 'node:stream'; +import { promisify } from 'node:util'; +import { mkdir } from 'node:fs/promises'; import replace from 'stream-replace-string'; import { SitemapAndIndexStream, SitemapStream } from 'sitemap'; From 87ce2381b6f1cc01b3532da8c09601f2118d4e43 Mon Sep 17 00:00:00 2001 From: Florian Lefebvre Date: Thu, 15 Aug 2024 14:53:15 +0000 Subject: [PATCH 21/29] [ci] format --- packages/astro/src/assets/endpoint/node.ts | 2 +- packages/astro/src/core/dev/dev.ts | 2 +- packages/astro/src/core/preview/static-preview-server.ts | 2 +- packages/astro/src/core/routing/manifest/create.ts | 2 +- packages/astro/src/core/sync/index.ts | 2 +- packages/db/src/core/integration/index.ts | 4 ++-- packages/db/test/local-prod.test.js | 2 +- packages/integrations/node/src/standalone.ts | 2 +- packages/integrations/partytown/src/index.ts | 2 +- packages/integrations/sitemap/src/write-sitemap.ts | 2 +- 10 files changed, 11 insertions(+), 11 deletions(-) diff --git a/packages/astro/src/assets/endpoint/node.ts b/packages/astro/src/assets/endpoint/node.ts index c1acc66efc15..cb3ae7806e91 100644 --- a/packages/astro/src/assets/endpoint/node.ts +++ b/packages/astro/src/assets/endpoint/node.ts @@ -1,3 +1,4 @@ +import { readFile } from 'node:fs/promises'; /* eslint-disable no-console */ import os from 'node:os'; import { isAbsolute } from 'node:path'; @@ -5,7 +6,6 @@ import { fileURLToPath, pathToFileURL } from 'node:url'; // @ts-expect-error import { assetsDir, imageConfig, outDir } from 'astro:assets'; import { isRemotePath, removeQueryString } from '@astrojs/internal-helpers/path'; -import { readFile } from 'node:fs/promises'; import * as mime from 'mrmime'; import type { APIRoute } from '../../@types/astro.js'; import { getConfiguredImageService } from '../internal.js'; diff --git a/packages/astro/src/core/dev/dev.ts b/packages/astro/src/core/dev/dev.ts index ab1564d4e75f..12b6d3b55aab 100644 --- a/packages/astro/src/core/dev/dev.ts +++ b/packages/astro/src/core/dev/dev.ts @@ -1,8 +1,8 @@ import fs, { existsSync } from 'node:fs'; import type http from 'node:http'; import type { AddressInfo } from 'node:net'; -import { green } from 'kleur/colors'; import { performance } from 'node:perf_hooks'; +import { green } from 'kleur/colors'; import { gt, major, minor, patch } from 'semver'; import type * as vite from 'vite'; import type { AstroInlineConfig } from '../../@types/astro.js'; diff --git a/packages/astro/src/core/preview/static-preview-server.ts b/packages/astro/src/core/preview/static-preview-server.ts index 96afeb1b3781..0afa34b6042e 100644 --- a/packages/astro/src/core/preview/static-preview-server.ts +++ b/packages/astro/src/core/preview/static-preview-server.ts @@ -1,6 +1,6 @@ import type http from 'node:http'; -import { fileURLToPath } from 'node:url'; import { performance } from 'node:perf_hooks'; +import { fileURLToPath } from 'node:url'; import { type PreviewServer as VitePreviewServer, preview } from 'vite'; import type { AstroSettings } from '../../@types/astro.js'; import type { Logger } from '../logger/core.js'; diff --git a/packages/astro/src/core/routing/manifest/create.ts b/packages/astro/src/core/routing/manifest/create.ts index d9a6c61b030e..df548ec8248d 100644 --- a/packages/astro/src/core/routing/manifest/create.ts +++ b/packages/astro/src/core/routing/manifest/create.ts @@ -8,8 +8,8 @@ import type { } from '../../../@types/astro.js'; import type { Logger } from '../../logger/core.js'; -import { createRequire } from 'node:module'; import nodeFs from 'node:fs'; +import { createRequire } from 'node:module'; import path from 'node:path'; import { fileURLToPath } from 'node:url'; import { bold } from 'kleur/colors'; diff --git a/packages/astro/src/core/sync/index.ts b/packages/astro/src/core/sync/index.ts index aecf6c9c3d31..92b3478e344d 100644 --- a/packages/astro/src/core/sync/index.ts +++ b/packages/astro/src/core/sync/index.ts @@ -1,5 +1,6 @@ import fsMod, { existsSync } from 'node:fs'; import { performance } from 'node:perf_hooks'; +import { fileURLToPath } from 'node:url'; import { dim } from 'kleur/colors'; import { type HMRPayload, createServer } from 'vite'; import type { AstroConfig, AstroInlineConfig, AstroSettings } from '../../@types/astro.js'; @@ -29,7 +30,6 @@ import type { Logger } from '../logger/core.js'; import { formatErrorMessage } from '../messages.js'; import { ensureProcessNodeEnv } from '../util.js'; import { writeFiles } from './write-files.js'; -import { fileURLToPath } from 'node:url'; export type SyncOptions = { /** diff --git a/packages/db/src/core/integration/index.ts b/packages/db/src/core/integration/index.ts index 7be43c0daccb..c096d08af82e 100644 --- a/packages/db/src/core/integration/index.ts +++ b/packages/db/src/core/integration/index.ts @@ -1,11 +1,11 @@ import { existsSync } from 'node:fs'; -import { parseArgs } from 'node:util'; +import { mkdir, writeFile } from 'node:fs/promises'; import { dirname } from 'node:path'; import { fileURLToPath } from 'node:url'; +import { parseArgs } from 'node:util'; import { type ManagedAppToken, getManagedAppTokenOrExit } from '@astrojs/studio'; import { LibsqlError } from '@libsql/client'; import type { AstroConfig, AstroIntegration } from 'astro'; -import { mkdir, writeFile } from 'node:fs/promises'; import { blue, yellow } from 'kleur/colors'; import { type HMRPayload, diff --git a/packages/db/test/local-prod.test.js b/packages/db/test/local-prod.test.js index be67d179a3ea..6513aeb08572 100644 --- a/packages/db/test/local-prod.test.js +++ b/packages/db/test/local-prod.test.js @@ -1,6 +1,6 @@ import assert from 'node:assert/strict'; -import { after, before, describe, it } from 'node:test'; import { relative } from 'node:path'; +import { after, before, describe, it } from 'node:test'; import { fileURLToPath } from 'node:url'; import testAdapter from '../../astro/test/test-adapter.js'; import { loadFixture } from '../../astro/test/test-utils.js'; diff --git a/packages/integrations/node/src/standalone.ts b/packages/integrations/node/src/standalone.ts index 69db5ef2313b..76e672d2fc36 100644 --- a/packages/integrations/node/src/standalone.ts +++ b/packages/integrations/node/src/standalone.ts @@ -1,6 +1,6 @@ -import https from 'node:https'; import fs from 'node:fs'; import http from 'node:http'; +import https from 'node:https'; import type { PreviewServer } from 'astro'; import type { NodeApp } from 'astro/app/node'; import enableDestroy from 'server-destroy'; diff --git a/packages/integrations/partytown/src/index.ts b/packages/integrations/partytown/src/index.ts index 9589e32a6cc1..739ff0e4b9b4 100644 --- a/packages/integrations/partytown/src/index.ts +++ b/packages/integrations/partytown/src/index.ts @@ -1,5 +1,5 @@ -import { createRequire } from 'node:module'; import * as fs from 'node:fs'; +import { createRequire } from 'node:module'; import path from 'node:path'; import { fileURLToPath } from 'node:url'; import type { PartytownConfig } from '@builder.io/partytown/integration'; diff --git a/packages/integrations/sitemap/src/write-sitemap.ts b/packages/integrations/sitemap/src/write-sitemap.ts index b6a0c63c2f58..4c189ee3c990 100644 --- a/packages/integrations/sitemap/src/write-sitemap.ts +++ b/packages/integrations/sitemap/src/write-sitemap.ts @@ -1,8 +1,8 @@ import { type WriteStream, createWriteStream } from 'node:fs'; +import { mkdir } from 'node:fs/promises'; import { normalize, resolve } from 'node:path'; import { Readable, pipeline } from 'node:stream'; import { promisify } from 'node:util'; -import { mkdir } from 'node:fs/promises'; import replace from 'stream-replace-string'; import { SitemapAndIndexStream, SitemapStream } from 'sitemap'; From 91d36fa36bc8c5ca3e27c72b85399d1eb150c872 Mon Sep 17 00:00:00 2001 From: "Houston (Bot)" <108291165+astrobot-houston@users.noreply.github.com> Date: Thu, 15 Aug 2024 08:06:43 -0700 Subject: [PATCH 22/29] [ci] release (#11719) Co-authored-by: github-actions[bot] --- .changeset/fresh-tigers-cheat.md | 5 -- .changeset/hot-dodos-whisper.md | 7 --- .changeset/ten-buckets-matter.md | 5 -- examples/basics/package.json | 2 +- examples/blog/package.json | 2 +- examples/component/package.json | 2 +- examples/container-with-vitest/package.json | 2 +- examples/framework-alpine/package.json | 2 +- examples/framework-lit/package.json | 2 +- examples/framework-multiple/package.json | 2 +- examples/framework-preact/package.json | 2 +- examples/framework-react/package.json | 2 +- examples/framework-solid/package.json | 2 +- examples/framework-svelte/package.json | 2 +- examples/framework-vue/package.json | 2 +- examples/hackernews/package.json | 2 +- examples/integration/package.json | 2 +- examples/middleware/package.json | 2 +- examples/minimal/package.json | 2 +- examples/non-html-pages/package.json | 2 +- examples/portfolio/package.json | 2 +- examples/server-islands/package.json | 2 +- examples/ssr/package.json | 2 +- examples/starlog/package.json | 2 +- examples/toolbar-app/package.json | 2 +- examples/view-transitions/package.json | 2 +- examples/with-markdoc/package.json | 2 +- examples/with-markdown-plugins/package.json | 2 +- examples/with-markdown-shiki/package.json | 2 +- examples/with-mdx/package.json | 2 +- examples/with-nanostores/package.json | 2 +- examples/with-tailwindcss/package.json | 2 +- examples/with-vitest/package.json | 2 +- packages/astro/CHANGELOG.md | 12 +++++ packages/astro/package.json | 2 +- pnpm-lock.yaml | 60 ++++++++++----------- 36 files changed, 73 insertions(+), 78 deletions(-) delete mode 100644 .changeset/fresh-tigers-cheat.md delete mode 100644 .changeset/hot-dodos-whisper.md delete mode 100644 .changeset/ten-buckets-matter.md diff --git a/.changeset/fresh-tigers-cheat.md b/.changeset/fresh-tigers-cheat.md deleted file mode 100644 index 32dbccebd1de..000000000000 --- a/.changeset/fresh-tigers-cheat.md +++ /dev/null @@ -1,5 +0,0 @@ ---- -'astro': patch ---- - -Prevents content layer importing node builtins in runtime diff --git a/.changeset/hot-dodos-whisper.md b/.changeset/hot-dodos-whisper.md deleted file mode 100644 index 07398058f292..000000000000 --- a/.changeset/hot-dodos-whisper.md +++ /dev/null @@ -1,7 +0,0 @@ ---- -'astro': patch ---- - -Prevent errant HTML from crashing server islands - -When an HTML minifier strips away the server island comment, the script can't correctly know where the end of the fallback content is. This makes it so that it simply doesn't remove any DOM in that scenario. This means the fallback isn't removed, but it also doesn't crash the browser. diff --git a/.changeset/ten-buckets-matter.md b/.changeset/ten-buckets-matter.md deleted file mode 100644 index b70a244a0591..000000000000 --- a/.changeset/ten-buckets-matter.md +++ /dev/null @@ -1,5 +0,0 @@ ---- -'astro': patch ---- - -Fixes a type issue when using the Content Layer in dev diff --git a/examples/basics/package.json b/examples/basics/package.json index ea1fe90c0839..08868cdadfba 100644 --- a/examples/basics/package.json +++ b/examples/basics/package.json @@ -11,6 +11,6 @@ "astro": "astro" }, "dependencies": { - "astro": "^4.14.0" + "astro": "^4.14.1" } } diff --git a/examples/blog/package.json b/examples/blog/package.json index 76f9b97fe0a6..1f8e5af6e151 100644 --- a/examples/blog/package.json +++ b/examples/blog/package.json @@ -14,6 +14,6 @@ "@astrojs/mdx": "^3.1.3", "@astrojs/rss": "^4.0.7", "@astrojs/sitemap": "^3.1.6", - "astro": "^4.14.0" + "astro": "^4.14.1" } } diff --git a/examples/component/package.json b/examples/component/package.json index 4e31293b2224..86ee213d7411 100644 --- a/examples/component/package.json +++ b/examples/component/package.json @@ -15,7 +15,7 @@ ], "scripts": {}, "devDependencies": { - "astro": "^4.14.0" + "astro": "^4.14.1" }, "peerDependencies": { "astro": "^4.0.0" diff --git a/examples/container-with-vitest/package.json b/examples/container-with-vitest/package.json index 0d7e206da76a..be5562e9b841 100644 --- a/examples/container-with-vitest/package.json +++ b/examples/container-with-vitest/package.json @@ -12,7 +12,7 @@ "test": "vitest run" }, "dependencies": { - "astro": "^4.14.0", + "astro": "^4.14.1", "@astrojs/react": "^3.6.2", "react": "^18.3.1", "react-dom": "^18.3.1", diff --git a/examples/framework-alpine/package.json b/examples/framework-alpine/package.json index 0a48c7eeb86c..97625ebbf3ff 100644 --- a/examples/framework-alpine/package.json +++ b/examples/framework-alpine/package.json @@ -14,6 +14,6 @@ "@astrojs/alpinejs": "^0.4.0", "@types/alpinejs": "^3.13.10", "alpinejs": "^3.14.1", - "astro": "^4.14.0" + "astro": "^4.14.1" } } diff --git a/examples/framework-lit/package.json b/examples/framework-lit/package.json index 9a9aee995dc7..592caf172d41 100644 --- a/examples/framework-lit/package.json +++ b/examples/framework-lit/package.json @@ -13,7 +13,7 @@ "dependencies": { "@astrojs/lit": "^4.3.0", "@webcomponents/template-shadowroot": "^0.2.1", - "astro": "^4.14.0", + "astro": "^4.14.1", "lit": "^3.2.0" } } diff --git a/examples/framework-multiple/package.json b/examples/framework-multiple/package.json index 7e71917c49de..ae2bb7d5439c 100644 --- a/examples/framework-multiple/package.json +++ b/examples/framework-multiple/package.json @@ -18,7 +18,7 @@ "@astrojs/vue": "^4.5.0", "@types/react": "^18.3.3", "@types/react-dom": "^18.3.0", - "astro": "^4.14.0", + "astro": "^4.14.1", "preact": "^10.23.1", "react": "^18.3.1", "react-dom": "^18.3.1", diff --git a/examples/framework-preact/package.json b/examples/framework-preact/package.json index 9d372fc0cfd6..2c962c87cb12 100644 --- a/examples/framework-preact/package.json +++ b/examples/framework-preact/package.json @@ -13,7 +13,7 @@ "dependencies": { "@astrojs/preact": "^3.5.1", "@preact/signals": "^1.3.0", - "astro": "^4.14.0", + "astro": "^4.14.1", "preact": "^10.23.1" } } diff --git a/examples/framework-react/package.json b/examples/framework-react/package.json index 85eebf19dcb5..eb74ea33a599 100644 --- a/examples/framework-react/package.json +++ b/examples/framework-react/package.json @@ -14,7 +14,7 @@ "@astrojs/react": "^3.6.2", "@types/react": "^18.3.3", "@types/react-dom": "^18.3.0", - "astro": "^4.14.0", + "astro": "^4.14.1", "react": "^18.3.1", "react-dom": "^18.3.1" } diff --git a/examples/framework-solid/package.json b/examples/framework-solid/package.json index e6ff05289e8d..57d5dced25d1 100644 --- a/examples/framework-solid/package.json +++ b/examples/framework-solid/package.json @@ -12,7 +12,7 @@ }, "dependencies": { "@astrojs/solid-js": "^4.4.1", - "astro": "^4.14.0", + "astro": "^4.14.1", "solid-js": "^1.8.20" } } diff --git a/examples/framework-svelte/package.json b/examples/framework-svelte/package.json index 8ba82634cd64..472078dac4e7 100644 --- a/examples/framework-svelte/package.json +++ b/examples/framework-svelte/package.json @@ -12,7 +12,7 @@ }, "dependencies": { "@astrojs/svelte": "^5.7.0", - "astro": "^4.14.0", + "astro": "^4.14.1", "svelte": "^4.2.18" } } diff --git a/examples/framework-vue/package.json b/examples/framework-vue/package.json index 47e1350f8b6c..b0109ba3985d 100644 --- a/examples/framework-vue/package.json +++ b/examples/framework-vue/package.json @@ -12,7 +12,7 @@ }, "dependencies": { "@astrojs/vue": "^4.5.0", - "astro": "^4.14.0", + "astro": "^4.14.1", "vue": "^3.4.37" } } diff --git a/examples/hackernews/package.json b/examples/hackernews/package.json index 3995d8cc108d..0769ac6b2977 100644 --- a/examples/hackernews/package.json +++ b/examples/hackernews/package.json @@ -12,6 +12,6 @@ }, "dependencies": { "@astrojs/node": "^8.3.3", - "astro": "^4.14.0" + "astro": "^4.14.1" } } diff --git a/examples/integration/package.json b/examples/integration/package.json index ee2571c17c5d..36b2da876cca 100644 --- a/examples/integration/package.json +++ b/examples/integration/package.json @@ -15,7 +15,7 @@ ], "scripts": {}, "devDependencies": { - "astro": "^4.14.0" + "astro": "^4.14.1" }, "peerDependencies": { "astro": "^4.0.0" diff --git a/examples/middleware/package.json b/examples/middleware/package.json index 990761c2f89f..7c028461316e 100644 --- a/examples/middleware/package.json +++ b/examples/middleware/package.json @@ -13,7 +13,7 @@ }, "dependencies": { "@astrojs/node": "^8.3.3", - "astro": "^4.14.0", + "astro": "^4.14.1", "html-minifier": "^4.0.0" }, "devDependencies": { diff --git a/examples/minimal/package.json b/examples/minimal/package.json index 27cf53e00a94..a40a78756134 100644 --- a/examples/minimal/package.json +++ b/examples/minimal/package.json @@ -11,6 +11,6 @@ "astro": "astro" }, "dependencies": { - "astro": "^4.14.0" + "astro": "^4.14.1" } } diff --git a/examples/non-html-pages/package.json b/examples/non-html-pages/package.json index 43813bbcda64..bf00519699b2 100644 --- a/examples/non-html-pages/package.json +++ b/examples/non-html-pages/package.json @@ -11,6 +11,6 @@ "astro": "astro" }, "dependencies": { - "astro": "^4.14.0" + "astro": "^4.14.1" } } diff --git a/examples/portfolio/package.json b/examples/portfolio/package.json index e16e5e93190f..9cff3186c2ac 100644 --- a/examples/portfolio/package.json +++ b/examples/portfolio/package.json @@ -11,6 +11,6 @@ "astro": "astro" }, "dependencies": { - "astro": "^4.14.0" + "astro": "^4.14.1" } } diff --git a/examples/server-islands/package.json b/examples/server-islands/package.json index b4e66b951a21..09c3a1d377ca 100644 --- a/examples/server-islands/package.json +++ b/examples/server-islands/package.json @@ -17,7 +17,7 @@ "@tailwindcss/forms": "^0.5.7", "@types/react": "^18.3.3", "@types/react-dom": "^18.3.0", - "astro": "^4.14.0", + "astro": "^4.14.1", "postcss": "^8.4.41", "react": "^18.3.1", "react-dom": "^18.3.1", diff --git a/examples/ssr/package.json b/examples/ssr/package.json index 5251c90c317b..a1f828779c30 100644 --- a/examples/ssr/package.json +++ b/examples/ssr/package.json @@ -14,7 +14,7 @@ "dependencies": { "@astrojs/node": "^8.3.3", "@astrojs/svelte": "^5.7.0", - "astro": "^4.14.0", + "astro": "^4.14.1", "svelte": "^4.2.18" } } diff --git a/examples/starlog/package.json b/examples/starlog/package.json index 2cff7650bdec..9d61795310c9 100644 --- a/examples/starlog/package.json +++ b/examples/starlog/package.json @@ -10,7 +10,7 @@ "astro": "astro" }, "dependencies": { - "astro": "^4.14.0", + "astro": "^4.14.1", "sass": "^1.77.8", "sharp": "^0.33.3" } diff --git a/examples/toolbar-app/package.json b/examples/toolbar-app/package.json index 73537e8ab8c8..bfb0f17ecde2 100644 --- a/examples/toolbar-app/package.json +++ b/examples/toolbar-app/package.json @@ -15,6 +15,6 @@ "./app": "./dist/app.js" }, "devDependencies": { - "astro": "^4.14.0" + "astro": "^4.14.1" } } diff --git a/examples/view-transitions/package.json b/examples/view-transitions/package.json index 0e05cd1420de..dfcdf86c296e 100644 --- a/examples/view-transitions/package.json +++ b/examples/view-transitions/package.json @@ -12,6 +12,6 @@ "devDependencies": { "@astrojs/tailwind": "^5.1.0", "@astrojs/node": "^8.3.3", - "astro": "^4.14.0" + "astro": "^4.14.1" } } diff --git a/examples/with-markdoc/package.json b/examples/with-markdoc/package.json index ddf843fae7d7..b0914c2b8610 100644 --- a/examples/with-markdoc/package.json +++ b/examples/with-markdoc/package.json @@ -12,6 +12,6 @@ }, "dependencies": { "@astrojs/markdoc": "^0.11.3", - "astro": "^4.14.0" + "astro": "^4.14.1" } } diff --git a/examples/with-markdown-plugins/package.json b/examples/with-markdown-plugins/package.json index 641a8cb8c18e..b84a26fd0ef2 100644 --- a/examples/with-markdown-plugins/package.json +++ b/examples/with-markdown-plugins/package.json @@ -12,7 +12,7 @@ }, "dependencies": { "@astrojs/markdown-remark": "^5.2.0", - "astro": "^4.14.0", + "astro": "^4.14.1", "hast-util-select": "^6.0.2", "rehype-autolink-headings": "^7.1.0", "rehype-slug": "^6.0.0", diff --git a/examples/with-markdown-shiki/package.json b/examples/with-markdown-shiki/package.json index 71eca6318cd8..0c49f34b2a39 100644 --- a/examples/with-markdown-shiki/package.json +++ b/examples/with-markdown-shiki/package.json @@ -11,6 +11,6 @@ "astro": "astro" }, "dependencies": { - "astro": "^4.14.0" + "astro": "^4.14.1" } } diff --git a/examples/with-mdx/package.json b/examples/with-mdx/package.json index 23a57015bdd9..80c142c438bb 100644 --- a/examples/with-mdx/package.json +++ b/examples/with-mdx/package.json @@ -13,7 +13,7 @@ "dependencies": { "@astrojs/mdx": "^3.1.3", "@astrojs/preact": "^3.5.1", - "astro": "^4.14.0", + "astro": "^4.14.1", "preact": "^10.23.1" } } diff --git a/examples/with-nanostores/package.json b/examples/with-nanostores/package.json index f700f300dcfc..4b7009566feb 100644 --- a/examples/with-nanostores/package.json +++ b/examples/with-nanostores/package.json @@ -13,7 +13,7 @@ "dependencies": { "@astrojs/preact": "^3.5.1", "@nanostores/preact": "^0.5.2", - "astro": "^4.14.0", + "astro": "^4.14.1", "nanostores": "^0.11.2", "preact": "^10.23.1" } diff --git a/examples/with-tailwindcss/package.json b/examples/with-tailwindcss/package.json index 5f8e023b121d..c744d8e05149 100644 --- a/examples/with-tailwindcss/package.json +++ b/examples/with-tailwindcss/package.json @@ -14,7 +14,7 @@ "@astrojs/mdx": "^3.1.3", "@astrojs/tailwind": "^5.1.0", "@types/canvas-confetti": "^1.6.4", - "astro": "^4.14.0", + "astro": "^4.14.1", "autoprefixer": "^10.4.20", "canvas-confetti": "^1.9.3", "postcss": "^8.4.41", diff --git a/examples/with-vitest/package.json b/examples/with-vitest/package.json index 15a3f58d02b8..eb0cf46cf1e8 100644 --- a/examples/with-vitest/package.json +++ b/examples/with-vitest/package.json @@ -12,7 +12,7 @@ "test": "vitest" }, "dependencies": { - "astro": "^4.14.0", + "astro": "^4.14.1", "vitest": "^2.0.5" } } diff --git a/packages/astro/CHANGELOG.md b/packages/astro/CHANGELOG.md index 8f6e75407232..e7417b655c8d 100644 --- a/packages/astro/CHANGELOG.md +++ b/packages/astro/CHANGELOG.md @@ -1,5 +1,17 @@ # astro +## 4.14.1 + +### Patch Changes + +- [#11725](https://github.com/withastro/astro/pull/11725) [`6c1560f`](https://github.com/withastro/astro/commit/6c1560fb0d19ce659bc9f9090f8050254d5c03f3) Thanks [@ascorbic](https://github.com/ascorbic)! - Prevents content layer importing node builtins in runtime + +- [#11692](https://github.com/withastro/astro/pull/11692) [`35af73a`](https://github.com/withastro/astro/commit/35af73aace97a7cc898b9aa5040db8bc2ac62687) Thanks [@matthewp](https://github.com/matthewp)! - Prevent errant HTML from crashing server islands + + When an HTML minifier strips away the server island comment, the script can't correctly know where the end of the fallback content is. This makes it so that it simply doesn't remove any DOM in that scenario. This means the fallback isn't removed, but it also doesn't crash the browser. + +- [#11727](https://github.com/withastro/astro/pull/11727) [`3c2f93b`](https://github.com/withastro/astro/commit/3c2f93b66c6b8e9d2ab58e2cbe941c14ffab89b5) Thanks [@florian-lefebvre](https://github.com/florian-lefebvre)! - Fixes a type issue when using the Content Layer in dev + ## 4.14.0 ### Minor Changes diff --git a/packages/astro/package.json b/packages/astro/package.json index e8f53ee8f25d..2e7657517032 100644 --- a/packages/astro/package.json +++ b/packages/astro/package.json @@ -1,6 +1,6 @@ { "name": "astro", - "version": "4.14.0", + "version": "4.14.1", "description": "Astro is a modern site builder with web best practices, performance, and DX front-of-mind.", "type": "module", "author": "withastro", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index c83e577de097..5c902e1084cd 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -116,7 +116,7 @@ importers: examples/basics: dependencies: astro: - specifier: ^4.14.0 + specifier: ^4.14.1 version: link:../../packages/astro examples/blog: @@ -131,13 +131,13 @@ importers: specifier: ^3.1.6 version: link:../../packages/integrations/sitemap astro: - specifier: ^4.14.0 + specifier: ^4.14.1 version: link:../../packages/astro examples/component: devDependencies: astro: - specifier: ^4.14.0 + specifier: ^4.14.1 version: link:../../packages/astro examples/container-with-vitest: @@ -146,7 +146,7 @@ importers: specifier: ^3.6.2 version: link:../../packages/integrations/react astro: - specifier: ^4.14.0 + specifier: ^4.14.1 version: link:../../packages/astro react: specifier: ^18.3.1 @@ -177,7 +177,7 @@ importers: specifier: ^3.14.1 version: 3.14.1 astro: - specifier: ^4.14.0 + specifier: ^4.14.1 version: link:../../packages/astro examples/framework-lit: @@ -189,7 +189,7 @@ importers: specifier: ^0.2.1 version: 0.2.1 astro: - specifier: ^4.14.0 + specifier: ^4.14.1 version: link:../../packages/astro lit: specifier: ^3.2.0 @@ -219,7 +219,7 @@ importers: specifier: ^18.3.0 version: 18.3.0 astro: - specifier: ^4.14.0 + specifier: ^4.14.1 version: link:../../packages/astro preact: specifier: ^10.23.1 @@ -249,7 +249,7 @@ importers: specifier: ^1.3.0 version: 1.3.0(preact@10.23.1) astro: - specifier: ^4.14.0 + specifier: ^4.14.1 version: link:../../packages/astro preact: specifier: ^10.23.1 @@ -267,7 +267,7 @@ importers: specifier: ^18.3.0 version: 18.3.0 astro: - specifier: ^4.14.0 + specifier: ^4.14.1 version: link:../../packages/astro react: specifier: ^18.3.1 @@ -282,7 +282,7 @@ importers: specifier: ^4.4.1 version: link:../../packages/integrations/solid astro: - specifier: ^4.14.0 + specifier: ^4.14.1 version: link:../../packages/astro solid-js: specifier: ^1.8.20 @@ -294,7 +294,7 @@ importers: specifier: ^5.7.0 version: link:../../packages/integrations/svelte astro: - specifier: ^4.14.0 + specifier: ^4.14.1 version: link:../../packages/astro svelte: specifier: ^4.2.18 @@ -306,7 +306,7 @@ importers: specifier: ^4.5.0 version: link:../../packages/integrations/vue astro: - specifier: ^4.14.0 + specifier: ^4.14.1 version: link:../../packages/astro vue: specifier: ^3.4.37 @@ -318,13 +318,13 @@ importers: specifier: ^8.3.3 version: link:../../packages/integrations/node astro: - specifier: ^4.14.0 + specifier: ^4.14.1 version: link:../../packages/astro examples/integration: devDependencies: astro: - specifier: ^4.14.0 + specifier: ^4.14.1 version: link:../../packages/astro examples/middleware: @@ -333,7 +333,7 @@ importers: specifier: ^8.3.3 version: link:../../packages/integrations/node astro: - specifier: ^4.14.0 + specifier: ^4.14.1 version: link:../../packages/astro html-minifier: specifier: ^4.0.0 @@ -346,19 +346,19 @@ importers: examples/minimal: dependencies: astro: - specifier: ^4.14.0 + specifier: ^4.14.1 version: link:../../packages/astro examples/non-html-pages: dependencies: astro: - specifier: ^4.14.0 + specifier: ^4.14.1 version: link:../../packages/astro examples/portfolio: dependencies: astro: - specifier: ^4.14.0 + specifier: ^4.14.1 version: link:../../packages/astro examples/server-islands: @@ -385,7 +385,7 @@ importers: specifier: ^18.3.0 version: 18.3.0 astro: - specifier: ^4.14.0 + specifier: ^4.14.1 version: link:../../packages/astro postcss: specifier: ^8.4.41 @@ -409,7 +409,7 @@ importers: specifier: ^5.7.0 version: link:../../packages/integrations/svelte astro: - specifier: ^4.14.0 + specifier: ^4.14.1 version: link:../../packages/astro svelte: specifier: ^4.2.18 @@ -418,7 +418,7 @@ importers: examples/starlog: dependencies: astro: - specifier: ^4.14.0 + specifier: ^4.14.1 version: link:../../packages/astro sass: specifier: ^1.77.8 @@ -430,7 +430,7 @@ importers: examples/toolbar-app: devDependencies: astro: - specifier: ^4.14.0 + specifier: ^4.14.1 version: link:../../packages/astro examples/view-transitions: @@ -442,7 +442,7 @@ importers: specifier: ^5.1.0 version: link:../../packages/integrations/tailwind astro: - specifier: ^4.14.0 + specifier: ^4.14.1 version: link:../../packages/astro examples/with-markdoc: @@ -451,7 +451,7 @@ importers: specifier: ^0.11.3 version: link:../../packages/integrations/markdoc astro: - specifier: ^4.14.0 + specifier: ^4.14.1 version: link:../../packages/astro examples/with-markdown-plugins: @@ -460,7 +460,7 @@ importers: specifier: ^5.2.0 version: link:../../packages/markdown/remark astro: - specifier: ^4.14.0 + specifier: ^4.14.1 version: link:../../packages/astro hast-util-select: specifier: ^6.0.2 @@ -481,7 +481,7 @@ importers: examples/with-markdown-shiki: dependencies: astro: - specifier: ^4.14.0 + specifier: ^4.14.1 version: link:../../packages/astro examples/with-mdx: @@ -493,7 +493,7 @@ importers: specifier: ^3.5.1 version: link:../../packages/integrations/preact astro: - specifier: ^4.14.0 + specifier: ^4.14.1 version: link:../../packages/astro preact: specifier: ^10.23.1 @@ -508,7 +508,7 @@ importers: specifier: ^0.5.2 version: 0.5.2(nanostores@0.11.2)(preact@10.23.1) astro: - specifier: ^4.14.0 + specifier: ^4.14.1 version: link:../../packages/astro nanostores: specifier: ^0.11.2 @@ -529,7 +529,7 @@ importers: specifier: ^1.6.4 version: 1.6.4 astro: - specifier: ^4.14.0 + specifier: ^4.14.1 version: link:../../packages/astro autoprefixer: specifier: ^10.4.20 @@ -547,7 +547,7 @@ importers: examples/with-vitest: dependencies: astro: - specifier: ^4.14.0 + specifier: ^4.14.1 version: link:../../packages/astro vitest: specifier: ^2.0.5 From 391324df969db71d1c7ca25c2ed14c9eb6eea5ee Mon Sep 17 00:00:00 2001 From: Bjorn Lu Date: Fri, 16 Aug 2024 00:27:08 +0800 Subject: [PATCH 23/29] Revert parseArgs change (#11733) --- .changeset/famous-dolls-grin.md | 6 ++ .changeset/wild-trainers-matter.md | 6 ++ packages/astro/package.json | 4 +- packages/astro/src/cli/check/index.ts | 2 +- packages/astro/src/cli/db/index.ts | 22 ++--- packages/astro/src/cli/flags.ts | 8 +- packages/astro/src/cli/index.ts | 37 +++----- packages/create-astro/src/actions/context.ts | 91 ++++++++----------- packages/db/package.json | 2 + .../db/src/core/cli/commands/execute/index.ts | 4 +- .../db/src/core/cli/commands/login/index.ts | 4 +- .../db/src/core/cli/commands/push/index.ts | 4 +- .../db/src/core/cli/commands/shell/index.ts | 4 +- .../db/src/core/cli/commands/verify/index.ts | 4 +- packages/db/src/core/cli/index.ts | 4 +- packages/db/src/core/cli/types.ts | 4 +- packages/db/src/core/integration/index.ts | 6 +- packages/upgrade/src/actions/context.ts | 28 +++--- packages/upgrade/test/context.test.js | 4 +- pnpm-lock.yaml | 19 ++++ 20 files changed, 131 insertions(+), 132 deletions(-) create mode 100644 .changeset/famous-dolls-grin.md create mode 100644 .changeset/wild-trainers-matter.md diff --git a/.changeset/famous-dolls-grin.md b/.changeset/famous-dolls-grin.md new file mode 100644 index 000000000000..0070ee43bfe7 --- /dev/null +++ b/.changeset/famous-dolls-grin.md @@ -0,0 +1,6 @@ +--- +'create-astro': patch +'@astrojs/db': patch +--- + +Reverts back to `arg` package for CLI argument parsing diff --git a/.changeset/wild-trainers-matter.md b/.changeset/wild-trainers-matter.md new file mode 100644 index 000000000000..daf3cd9e5323 --- /dev/null +++ b/.changeset/wild-trainers-matter.md @@ -0,0 +1,6 @@ +--- +'astro': patch +'@astrojs/db': patch +--- + +Reverts back to `yargs-parser` package for CLI argument parsing diff --git a/packages/astro/package.json b/packages/astro/package.json index 2e7657517032..6da1e12e7fe0 100644 --- a/packages/astro/package.json +++ b/packages/astro/package.json @@ -133,8 +133,8 @@ "@babel/plugin-transform-react-jsx": "^7.25.2", "@babel/traverse": "^7.25.3", "@babel/types": "^7.25.2", - "@rollup/pluginutils": "^5.1.0", "@oslojs/encoding": "^0.4.1", + "@rollup/pluginutils": "^5.1.0", "@types/babel__core": "^7.20.5", "@types/cookie": "^0.6.0", "acorn": "^8.12.1", @@ -186,6 +186,7 @@ "vitefu": "^0.2.5", "which-pm": "^3.0.0", "xxhash-wasm": "^1.0.2", + "yargs-parser": "^21.1.1", "zod": "^3.23.8", "zod-to-json-schema": "^3.23.2", "zod-to-ts": "^1.2.0" @@ -212,6 +213,7 @@ "@types/micromatch": "^4.0.9", "@types/prompts": "^2.4.9", "@types/semver": "^7.5.8", + "@types/yargs-parser": "^21.0.3", "astro-scripts": "workspace:*", "cheerio": "1.0.0", "eol": "^0.9.1", diff --git a/packages/astro/src/cli/check/index.ts b/packages/astro/src/cli/check/index.ts index 9a354c8e00a5..c93e3b2f4cff 100644 --- a/packages/astro/src/cli/check/index.ts +++ b/packages/astro/src/cli/check/index.ts @@ -8,7 +8,7 @@ export async function check(flags: Flags) { const logger = createLoggerFromFlags(flags); const getPackageOpts = { skipAsk: !!flags.yes || !!flags.y, - cwd: typeof flags.root == 'string' ? flags.root : undefined, + cwd: flags.root, }; const checkPackage = await getPackage( '@astrojs/check', diff --git a/packages/astro/src/cli/db/index.ts b/packages/astro/src/cli/db/index.ts index c6be7411bb2a..ae97e498f8c0 100644 --- a/packages/astro/src/cli/db/index.ts +++ b/packages/astro/src/cli/db/index.ts @@ -1,25 +1,20 @@ +import type { Arguments } from 'yargs-parser'; import type { AstroConfig } from '../../@types/astro.js'; import { resolveConfig } from '../../core/config/config.js'; import { apply as applyPolyfill } from '../../core/polyfill.js'; -import { type Flags, createLoggerFromFlags, flagsToAstroInlineConfig } from '../flags.js'; +import { createLoggerFromFlags, flagsToAstroInlineConfig } from '../flags.js'; import { getPackage } from '../install-package.js'; -interface YargsArguments { - _: Array; - '--'?: Array; - [argName: string]: any; -} - type DBPackage = { - cli: (args: { flags: YargsArguments; config: AstroConfig }) => unknown; + cli: (args: { flags: Arguments; config: AstroConfig }) => unknown; }; -export async function db({ positionals, flags }: { positionals: string[]; flags: Flags }) { +export async function db({ flags }: { flags: Arguments }) { applyPolyfill(); const logger = createLoggerFromFlags(flags); const getPackageOpts = { skipAsk: !!flags.yes || !!flags.y, - cwd: typeof flags.root == 'string' ? flags.root : undefined, + cwd: flags.root, }; const dbPackage = await getPackage('@astrojs/db', logger, getPackageOpts, []); @@ -35,10 +30,5 @@ export async function db({ positionals, flags }: { positionals: string[]; flags: const inlineConfig = flagsToAstroInlineConfig(flags); const { astroConfig } = await resolveConfig(inlineConfig, 'build'); - const yargsArgs: YargsArguments = { - _: positionals, - ...flags, - }; - - await cli({ flags: yargsArgs, config: astroConfig }); + await cli({ flags, config: astroConfig }); } diff --git a/packages/astro/src/cli/flags.ts b/packages/astro/src/cli/flags.ts index 59dfbf00a4bd..9d57c03166e3 100644 --- a/packages/astro/src/cli/flags.ts +++ b/packages/astro/src/cli/flags.ts @@ -1,10 +1,10 @@ -import type { parseArgs } from 'node:util'; +import type { Arguments } from 'yargs-parser'; import type { AstroInlineConfig } from '../@types/astro.js'; import { type LogOptions, Logger } from '../core/logger/core.js'; import { nodeLogDestination } from '../core/logger/node.js'; -export type ParsedArgsResult = ReturnType; -export type Flags = ParsedArgsResult['values']; +// Alias for now, but allows easier migration to node's `parseArgs` in the future. +export type Flags = Arguments; export function flagsToAstroInlineConfig(flags: Flags): AstroInlineConfig { return { @@ -20,7 +20,7 @@ export function flagsToAstroInlineConfig(flags: Flags): AstroInlineConfig { base: typeof flags.base === 'string' ? flags.base : undefined, outDir: typeof flags.outDir === 'string' ? flags.outDir : undefined, server: { - port: typeof flags.port === 'string' ? Number(flags.port) : undefined, + port: typeof flags.port === 'number' ? flags.port : undefined, host: typeof flags.host === 'string' || typeof flags.host === 'boolean' ? flags.host : undefined, open: diff --git a/packages/astro/src/cli/index.ts b/packages/astro/src/cli/index.ts index b3a819e586eb..c767569fde51 100644 --- a/packages/astro/src/cli/index.ts +++ b/packages/astro/src/cli/index.ts @@ -1,8 +1,7 @@ -import { parseArgs } from 'node:util'; /* eslint-disable no-console */ import * as colors from 'kleur/colors'; +import yargs from 'yargs-parser'; import { ASTRO_VERSION } from '../core/constants.js'; -import type { ParsedArgsResult } from './flags.js'; type CLICommand = | 'help' @@ -66,9 +65,9 @@ function printVersion() { } /** Determine which command the user requested */ -function resolveCommand(args: ParsedArgsResult): CLICommand { - const cmd = args.positionals[2] as string; - if (args.values.version) return 'version'; +function resolveCommand(flags: yargs.Arguments): CLICommand { + const cmd = flags._[2] as string; + if (flags.version) return 'version'; const supportedCommands = new Set([ 'add', @@ -98,9 +97,7 @@ function resolveCommand(args: ParsedArgsResult): CLICommand { * NOTE: This function provides no error handling, so be sure * to present user-friendly error output where the fn is called. **/ -async function runCommand(cmd: string, args: ParsedArgsResult) { - const flags = args.values; - +async function runCommand(cmd: string, flags: yargs.Arguments) { // These commands can run directly without parsing the user config. switch (cmd) { case 'help': @@ -123,7 +120,7 @@ async function runCommand(cmd: string, args: ParsedArgsResult) { // Do not track session start, since the user may be trying to enable, // disable, or modify telemetry settings. const { update } = await import('./telemetry/index.js'); - const subcommand = args.positionals[3]; + const subcommand = flags._[3]?.toString(); await update(subcommand, { flags }); return; } @@ -134,7 +131,7 @@ async function runCommand(cmd: string, args: ParsedArgsResult) { } case 'preferences': { const { preferences } = await import('./preferences/index.js'); - const [subcommand, key, value] = args.positionals.slice(3); + const [subcommand, key, value] = flags._.slice(3).map((v) => v.toString()); const exitCode = await preferences(subcommand, key, value, { flags }); return process.exit(exitCode); } @@ -154,7 +151,7 @@ async function runCommand(cmd: string, args: ParsedArgsResult) { switch (cmd) { case 'add': { const { add } = await import('./add/index.js'); - const packages = args.positionals.slice(3); + const packages = flags._.slice(3) as string[]; await add(packages, { flags }); return; } @@ -164,7 +161,7 @@ async function runCommand(cmd: string, args: ParsedArgsResult) { case 'link': case 'init': { const { db } = await import('./db/index.js'); - await db({ positionals: args.positionals, flags }); + await db({ flags }); return; } case 'dev': { @@ -205,20 +202,10 @@ async function runCommand(cmd: string, args: ParsedArgsResult) { /** The primary CLI action */ export async function cli(argv: string[]) { - const args = parseArgs({ - args: argv, - allowPositionals: true, - strict: false, - options: { - global: { type: 'boolean', short: 'g' }, - host: { type: 'string' }, // Can be boolean too, which is covered by `strict: false` - open: { type: 'string' }, // Can be boolean too, which is covered by `strict: false` - // TODO: Add more flags here - }, - }); - const cmd = resolveCommand(args); + const flags = yargs(argv, { boolean: ['global'], alias: { g: 'global' } }); + const cmd = resolveCommand(flags); try { - await runCommand(cmd, args); + await runCommand(cmd, flags); } catch (err) { const { throwAndExit } = await import('./throw-and-exit.js'); await throwAndExit(cmd, err); diff --git a/packages/create-astro/src/actions/context.ts b/packages/create-astro/src/actions/context.ts index bf1b522bd3bd..83a13eda7c94 100644 --- a/packages/create-astro/src/actions/context.ts +++ b/packages/create-astro/src/actions/context.ts @@ -1,7 +1,7 @@ import os from 'node:os'; -import { parseArgs } from 'node:util'; import { type Task, prompt } from '@astrojs/cli-kit'; import { random } from '@astrojs/cli-kit/utils'; +import arg from 'arg'; import getSeasonalData from '../data/seasonal.js'; import { getName, getVersion } from '../messages.js'; @@ -33,44 +33,47 @@ export interface Context { } export async function getContext(argv: string[]): Promise { - const args = parseArgs({ - args: argv, - allowPositionals: true, - strict: false, - options: { - template: { type: 'string' }, - ref: { type: 'string' }, - yes: { type: 'boolean', short: 'y' }, - no: { type: 'boolean', short: 'n' }, - install: { type: 'boolean' }, - 'no-install': { type: 'boolean' }, - git: { type: 'boolean' }, - 'no-git': { type: 'boolean' }, - typescript: { type: 'string' }, - 'skip-houston': { type: 'boolean' }, - 'dry-run': { type: 'boolean' }, - help: { type: 'boolean', short: 'h' }, - fancy: { type: 'boolean' }, + const flags = arg( + { + '--template': String, + '--ref': String, + '--yes': Boolean, + '--no': Boolean, + '--install': Boolean, + '--no-install': Boolean, + '--git': Boolean, + '--no-git': Boolean, + '--typescript': String, + '--skip-houston': Boolean, + '--dry-run': Boolean, + '--help': Boolean, + '--fancy': Boolean, + + '-y': '--yes', + '-n': '--no', + '-h': '--help', }, - }); + { argv, permissive: true }, + ); const packageManager = detectPackageManager() ?? 'npm'; - const projectName = args.positionals[0]; + let cwd = flags['_'][0]; let { - help, - template, - no, - yes, - install, - 'no-install': noInstall, - git, - 'no-git': noGit, - typescript, - fancy, - 'skip-houston': skipHouston, - 'dry-run': dryRun, - ref, - } = args.values; + '--help': help = false, + '--template': template, + '--no': no, + '--yes': yes, + '--install': install, + '--no-install': noInstall, + '--git': git, + '--no-git': noGit, + '--typescript': typescript, + '--fancy': fancy, + '--skip-houston': skipHouston, + '--dry-run': dryRun, + '--ref': ref, + } = flags; + let projectName = cwd; if (no) { yes = false; @@ -79,26 +82,10 @@ export async function getContext(argv: string[]): Promise { if (typescript == undefined) typescript = 'strict'; } - skipHouston = typeof skipHouston == 'boolean' ? skipHouston : undefined; skipHouston = ((os.platform() === 'win32' && !fancy) || skipHouston) ?? [yes, no, install, git, typescript].some((v) => v !== undefined); - // We use `strict: false` in `parseArgs` to allow unknown options, but Node also - // simply doesn't guarantee the types anymore, so we need to validate ourselves :( - help = !!help; - template = typeof template == 'string' ? template : undefined; - no = !!no; - yes = !!yes; - install = !!install; - noInstall = !!noInstall; - git = !!git; - noGit = !!noGit; - typescript = typeof typescript == 'string' ? typescript : undefined; - fancy = !!fancy; - dryRun = !!dryRun; - ref = typeof ref == 'string' ? ref : undefined; - const { messages, hats, ties } = getSeasonalData({ fancy }); const context: Context = { @@ -120,7 +107,7 @@ export async function getContext(argv: string[]): Promise { install: install ?? (noInstall ? false : undefined), git: git ?? (noGit ? false : undefined), typescript, - cwd: projectName, + cwd, exit(code) { process.exit(code); }, diff --git a/packages/db/package.json b/packages/db/package.json index b92e47fe6162..adc6fde648c1 100644 --- a/packages/db/package.json +++ b/packages/db/package.json @@ -81,11 +81,13 @@ "ora": "^8.0.1", "prompts": "^2.4.2", "strip-ansi": "^7.1.0", + "yargs-parser": "^21.1.1", "zod": "^3.23.8" }, "devDependencies": { "@types/deep-diff": "^1.0.5", "@types/prompts": "^2.4.9", + "@types/yargs-parser": "^21.0.3", "astro": "workspace:*", "astro-scripts": "workspace:*", "cheerio": "1.0.0", diff --git a/packages/db/src/core/cli/commands/execute/index.ts b/packages/db/src/core/cli/commands/execute/index.ts index 03b3d00adda2..c6c11cdbb6b9 100644 --- a/packages/db/src/core/cli/commands/execute/index.ts +++ b/packages/db/src/core/cli/commands/execute/index.ts @@ -3,6 +3,7 @@ import { getManagedAppTokenOrExit } from '@astrojs/studio'; import { LibsqlError } from '@libsql/client'; import type { AstroConfig } from 'astro'; import { green } from 'kleur/colors'; +import type { Arguments } from 'yargs-parser'; import { EXEC_DEFAULT_EXPORT_ERROR, EXEC_ERROR, @@ -15,7 +16,6 @@ import { } from '../../../integration/vite-plugin-db.js'; import { bundleFile, importBundledFile } from '../../../load-file.js'; import type { DBConfig } from '../../../types.js'; -import type { YargsArguments } from '../../types.js'; export async function cmd({ astroConfig, @@ -24,7 +24,7 @@ export async function cmd({ }: { astroConfig: AstroConfig; dbConfig: DBConfig; - flags: YargsArguments; + flags: Arguments; }) { const filePath = flags._[4]; if (typeof filePath !== 'string') { diff --git a/packages/db/src/core/cli/commands/login/index.ts b/packages/db/src/core/cli/commands/login/index.ts index 251d61e05433..61f7e0275b15 100644 --- a/packages/db/src/core/cli/commands/login/index.ts +++ b/packages/db/src/core/cli/commands/login/index.ts @@ -7,8 +7,8 @@ import { cyan } from 'kleur/colors'; import open from 'open'; import ora from 'ora'; import prompt from 'prompts'; +import type { Arguments } from 'yargs-parser'; import type { DBConfig } from '../../../types.js'; -import type { YargsArguments } from '../../types.js'; const isWebContainer = // Stackblitz heuristic @@ -21,7 +21,7 @@ export async function cmd({ }: { astroConfig: AstroConfig; dbConfig: DBConfig; - flags: YargsArguments; + flags: Arguments; }) { let session = flags.session; diff --git a/packages/db/src/core/cli/commands/push/index.ts b/packages/db/src/core/cli/commands/push/index.ts index 237f7f6ea29e..ecd101ecea79 100644 --- a/packages/db/src/core/cli/commands/push/index.ts +++ b/packages/db/src/core/cli/commands/push/index.ts @@ -1,6 +1,7 @@ import { getManagedAppTokenOrExit } from '@astrojs/studio'; import type { AstroConfig } from 'astro'; import prompts from 'prompts'; +import type { Arguments } from 'yargs-parser'; import { safeFetch } from '../../../../runtime/utils.js'; import { MIGRATION_VERSION } from '../../../consts.js'; import { type DBConfig, type DBSnapshot } from '../../../types.js'; @@ -12,7 +13,6 @@ import { getMigrationQueries, getProductionCurrentSnapshot, } from '../../migration-queries.js'; -import type { YargsArguments } from '../../types.js'; export async function cmd({ dbConfig, @@ -20,7 +20,7 @@ export async function cmd({ }: { astroConfig: AstroConfig; dbConfig: DBConfig; - flags: YargsArguments; + flags: Arguments; }) { const isDryRun = flags.dryRun; const isForceReset = flags.forceReset; diff --git a/packages/db/src/core/cli/commands/shell/index.ts b/packages/db/src/core/cli/commands/shell/index.ts index 5a6bcaa53d1b..e0a1a6086c4f 100644 --- a/packages/db/src/core/cli/commands/shell/index.ts +++ b/packages/db/src/core/cli/commands/shell/index.ts @@ -1,6 +1,7 @@ import { getManagedAppTokenOrExit } from '@astrojs/studio'; import type { AstroConfig } from 'astro'; import { sql } from 'drizzle-orm'; +import type { Arguments } from 'yargs-parser'; import { createLocalDatabaseClient, createRemoteDatabaseClient, @@ -10,7 +11,6 @@ import { DB_PATH } from '../../../consts.js'; import { SHELL_QUERY_MISSING_ERROR } from '../../../errors.js'; import type { DBConfigInput } from '../../../types.js'; import { getAstroEnv, getRemoteDatabaseUrl } from '../../../utils.js'; -import type { YargsArguments } from '../../types.js'; export async function cmd({ flags, @@ -18,7 +18,7 @@ export async function cmd({ }: { dbConfig: DBConfigInput; astroConfig: AstroConfig; - flags: YargsArguments; + flags: Arguments; }) { const query = flags.query; if (!query) { diff --git a/packages/db/src/core/cli/commands/verify/index.ts b/packages/db/src/core/cli/commands/verify/index.ts index 081c8ae3f8ec..950fb661567c 100644 --- a/packages/db/src/core/cli/commands/verify/index.ts +++ b/packages/db/src/core/cli/commands/verify/index.ts @@ -1,5 +1,6 @@ import { getManagedAppTokenOrExit } from '@astrojs/studio'; import type { AstroConfig } from 'astro'; +import type { Arguments } from 'yargs-parser'; import type { DBConfig } from '../../../types.js'; import { createCurrentSnapshot, @@ -8,7 +9,6 @@ import { getMigrationQueries, getProductionCurrentSnapshot, } from '../../migration-queries.js'; -import type { YargsArguments } from '../../types.js'; export async function cmd({ dbConfig, @@ -16,7 +16,7 @@ export async function cmd({ }: { astroConfig: AstroConfig; dbConfig: DBConfig; - flags: YargsArguments; + flags: Arguments; }) { const isJson = flags.json; const appToken = await getManagedAppTokenOrExit(flags.token); diff --git a/packages/db/src/core/cli/index.ts b/packages/db/src/core/cli/index.ts index 5d9aa10e97dd..531b016a6b77 100644 --- a/packages/db/src/core/cli/index.ts +++ b/packages/db/src/core/cli/index.ts @@ -1,13 +1,13 @@ import type { AstroConfig } from 'astro'; +import type { Arguments } from 'yargs-parser'; import { resolveDbConfig } from '../load-file.js'; import { printHelp } from './print-help.js'; -import type { YargsArguments } from './types.js'; export async function cli({ flags, config: astroConfig, }: { - flags: YargsArguments; + flags: Arguments; config: AstroConfig; }) { const args = flags._ as string[]; diff --git a/packages/db/src/core/cli/types.ts b/packages/db/src/core/cli/types.ts index 9d8aad56b78f..4294c3fb0289 100644 --- a/packages/db/src/core/cli/types.ts +++ b/packages/db/src/core/cli/types.ts @@ -1,6 +1,4 @@ -// Copy of `yargs-parser` `Arguments` type. We don't use `yargs-parser` -// in runtime anymore, but our exposed API still relies on this shape. -export interface YargsArguments { +export interface Arguments { _: Array; '--'?: Array; [argName: string]: any; diff --git a/packages/db/src/core/integration/index.ts b/packages/db/src/core/integration/index.ts index c096d08af82e..da03e71f27cb 100644 --- a/packages/db/src/core/integration/index.ts +++ b/packages/db/src/core/integration/index.ts @@ -2,7 +2,6 @@ import { existsSync } from 'node:fs'; import { mkdir, writeFile } from 'node:fs/promises'; import { dirname } from 'node:path'; import { fileURLToPath } from 'node:url'; -import { parseArgs } from 'node:util'; import { type ManagedAppToken, getManagedAppTokenOrExit } from '@astrojs/studio'; import { LibsqlError } from '@libsql/client'; import type { AstroConfig, AstroIntegration } from 'astro'; @@ -15,6 +14,7 @@ import { loadEnv, mergeConfig, } from 'vite'; +import parseArgs from 'yargs-parser'; import { AstroDbError } from '../../runtime/utils.js'; import { CONFIG_FILE_NAMES, DB_PATH } from '../consts.js'; import { EXEC_DEFAULT_EXPORT_ERROR, EXEC_ERROR } from '../errors.js'; @@ -71,8 +71,8 @@ function astroDBIntegration(): AstroIntegration { if (command === 'preview') return; let dbPlugin: VitePlugin | undefined = undefined; - const args = parseArgs({ strict: false }); - connectToStudio = !!process.env.ASTRO_INTERNAL_TEST_REMOTE || !!args.values.remote; + const args = parseArgs(process.argv.slice(3)); + connectToStudio = process.env.ASTRO_INTERNAL_TEST_REMOTE || args['remote']; if (connectToStudio) { appToken = await getManagedAppTokenOrExit(); diff --git a/packages/upgrade/src/actions/context.ts b/packages/upgrade/src/actions/context.ts index cd9028e85a54..2103a53277e2 100644 --- a/packages/upgrade/src/actions/context.ts +++ b/packages/upgrade/src/actions/context.ts @@ -1,13 +1,13 @@ import { pathToFileURL } from 'node:url'; -import { parseArgs } from 'node:util'; import { prompt } from '@astrojs/cli-kit'; +import arg from 'arg'; import detectPackageManager from 'preferred-pm'; export interface Context { help: boolean; prompt: typeof prompt; version: string; - dryRun: boolean; + dryRun?: boolean; cwd: URL; stdin?: typeof process.stdin; stdout?: typeof process.stdout; @@ -28,20 +28,22 @@ export interface PackageInfo { } export async function getContext(argv: string[]): Promise { - const args = parseArgs({ - args: argv, - allowPositionals: true, - strict: false, - options: { - 'dry-run': { type: 'boolean' }, - help: { type: 'boolean', short: 'h' }, + const flags = arg( + { + '--dry-run': Boolean, + '--help': Boolean, + + '-h': '--help', }, - }); + { argv, permissive: true }, + ); const packageManager = (await detectPackageManager(process.cwd()))?.name ?? 'npm'; - const version = args.positionals[0] ?? 'latest'; - const help = !!args.values.help; - const dryRun = !!args.values['dry-run']; + const { + _: [version = 'latest'] = [], + '--help': help = false, + '--dry-run': dryRun, + } = flags; return { help, diff --git a/packages/upgrade/test/context.test.js b/packages/upgrade/test/context.test.js index 5ba484740f89..bbc887c2ae3c 100644 --- a/packages/upgrade/test/context.test.js +++ b/packages/upgrade/test/context.test.js @@ -6,12 +6,12 @@ describe('context', () => { it('no arguments', async () => { const ctx = await getContext([]); assert.equal(ctx.version, 'latest'); - assert.equal(ctx.dryRun, false); + assert.equal(ctx.dryRun, undefined); }); it('tag', async () => { const ctx = await getContext(['beta']); assert.equal(ctx.version, 'beta'); - assert.equal(ctx.dryRun, false); + assert.equal(ctx.dryRun, undefined); }); it('dry run', async () => { const ctx = await getContext(['--dry-run']); diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 5c902e1084cd..48b1f14e6da1 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -744,6 +744,9 @@ importers: xxhash-wasm: specifier: ^1.0.2 version: 1.0.2 + yargs-parser: + specifier: ^21.1.1 + version: 21.1.1 zod: specifier: ^3.23.8 version: 3.23.8 @@ -812,6 +815,9 @@ importers: '@types/semver': specifier: ^7.5.8 version: 7.5.8 + '@types/yargs-parser': + specifier: ^21.0.3 + version: 21.0.3 astro-scripts: specifier: workspace:* version: link:../../scripts @@ -4306,6 +4312,9 @@ importers: strip-ansi: specifier: ^7.1.0 version: 7.1.0 + yargs-parser: + specifier: ^21.1.1 + version: 21.1.1 zod: specifier: ^3.23.8 version: 3.23.8 @@ -4316,6 +4325,9 @@ importers: '@types/prompts': specifier: ^2.4.9 version: 2.4.9 + '@types/yargs-parser': + specifier: ^21.0.3 + version: 21.0.3 astro: specifier: workspace:* version: link:../astro @@ -7598,6 +7610,9 @@ packages: '@types/xml2js@0.4.14': resolution: {integrity: sha512-4YnrRemBShWRO2QjvUin8ESA41rH+9nQGLUGZV/1IDhi3SL9OhdpNC/MrulTWuptXKwhx/aDxE7toV0f/ypIXQ==} + '@types/yargs-parser@21.0.3': + resolution: {integrity: sha512-I4q9QU9MQv4oEOz4tAHJtNz1cwuLxn2F3xcc2iV5WdqLPpUnj30aUuxt1mAxYTG+oe8CZMV/+6rU4S4gRDzqtQ==} + '@typescript-eslint/eslint-plugin@8.0.1': resolution: {integrity: sha512-5g3Y7GDFsJAnY4Yhvk8sZtFfV6YNF2caLzjrRPUBzewjPCaj0yokePB4LJSobyCzGMzjZZYFbwuzbfDHlimXbQ==} engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} @@ -9479,10 +9494,12 @@ packages: libsql@0.3.19: resolution: {integrity: sha512-Aj5cQ5uk/6fHdmeW0TiXK42FqUlwx7ytmMLPSaUQPin5HKKKuUPD62MAbN4OEweGBBI7q1BekoEN4gPUEL6MZA==} + cpu: [x64, arm64, wasm32] os: [darwin, linux, win32] libsql@0.4.1: resolution: {integrity: sha512-qZlR9Yu1zMBeLChzkE/cKfoKV3Esp9cn9Vx5Zirn4AVhDWPcjYhKwbtJcMuHehgk3mH+fJr9qW+3vesBWbQpBg==} + cpu: [x64, arm64, wasm32] os: [darwin, linux, win32] lilconfig@2.1.0: @@ -13557,6 +13574,8 @@ snapshots: dependencies: '@types/node': 18.19.31 + '@types/yargs-parser@21.0.3': {} + '@typescript-eslint/eslint-plugin@8.0.1(@typescript-eslint/parser@8.0.1(eslint@9.9.0(jiti@1.21.0))(typescript@5.5.4))(eslint@9.9.0(jiti@1.21.0))(typescript@5.5.4)': dependencies: '@eslint-community/regexpp': 4.11.0 From 7c6349beca2859d22ea6a1b4b9388ad43ad8bff1 Mon Sep 17 00:00:00 2001 From: Bjorn Lu Date: Fri, 16 Aug 2024 00:32:53 +0800 Subject: [PATCH 24/29] Fix astro upgrade changeset (#11735) --- .changeset/famous-dolls-grin.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.changeset/famous-dolls-grin.md b/.changeset/famous-dolls-grin.md index 0070ee43bfe7..dbbe8887fa07 100644 --- a/.changeset/famous-dolls-grin.md +++ b/.changeset/famous-dolls-grin.md @@ -1,6 +1,6 @@ --- 'create-astro': patch -'@astrojs/db': patch +'@astrojs/upgrade': patch --- Reverts back to `arg` package for CLI argument parsing From 0109690c3b4103c56bce40b3193a19cf05c5f4e2 Mon Sep 17 00:00:00 2001 From: "Houston (Bot)" <108291165+astrobot-houston@users.noreply.github.com> Date: Thu, 15 Aug 2024 09:34:37 -0700 Subject: [PATCH 25/29] [ci] release (#11734) Co-authored-by: github-actions[bot] --- .changeset/famous-dolls-grin.md | 6 -- .changeset/wild-trainers-matter.md | 6 -- examples/basics/package.json | 2 +- examples/blog/package.json | 2 +- examples/component/package.json | 2 +- examples/container-with-vitest/package.json | 2 +- examples/framework-alpine/package.json | 2 +- examples/framework-lit/package.json | 2 +- examples/framework-multiple/package.json | 2 +- examples/framework-preact/package.json | 2 +- examples/framework-react/package.json | 2 +- examples/framework-solid/package.json | 2 +- examples/framework-svelte/package.json | 2 +- examples/framework-vue/package.json | 2 +- examples/hackernews/package.json | 2 +- examples/integration/package.json | 2 +- examples/middleware/package.json | 2 +- examples/minimal/package.json | 2 +- examples/non-html-pages/package.json | 2 +- examples/portfolio/package.json | 2 +- examples/server-islands/package.json | 2 +- examples/ssr/package.json | 2 +- examples/starlog/package.json | 2 +- examples/toolbar-app/package.json | 2 +- examples/view-transitions/package.json | 2 +- examples/with-markdoc/package.json | 2 +- examples/with-markdown-plugins/package.json | 2 +- examples/with-markdown-shiki/package.json | 2 +- examples/with-mdx/package.json | 2 +- examples/with-nanostores/package.json | 2 +- examples/with-tailwindcss/package.json | 2 +- examples/with-vitest/package.json | 2 +- packages/astro/CHANGELOG.md | 6 ++ packages/astro/package.json | 2 +- packages/create-astro/CHANGELOG.md | 6 ++ packages/create-astro/package.json | 2 +- packages/db/CHANGELOG.md | 9 +++ packages/db/package.json | 2 +- packages/upgrade/CHANGELOG.md | 6 ++ packages/upgrade/package.json | 2 +- pnpm-lock.yaml | 62 ++++++++++----------- 41 files changed, 91 insertions(+), 78 deletions(-) delete mode 100644 .changeset/famous-dolls-grin.md delete mode 100644 .changeset/wild-trainers-matter.md diff --git a/.changeset/famous-dolls-grin.md b/.changeset/famous-dolls-grin.md deleted file mode 100644 index dbbe8887fa07..000000000000 --- a/.changeset/famous-dolls-grin.md +++ /dev/null @@ -1,6 +0,0 @@ ---- -'create-astro': patch -'@astrojs/upgrade': patch ---- - -Reverts back to `arg` package for CLI argument parsing diff --git a/.changeset/wild-trainers-matter.md b/.changeset/wild-trainers-matter.md deleted file mode 100644 index daf3cd9e5323..000000000000 --- a/.changeset/wild-trainers-matter.md +++ /dev/null @@ -1,6 +0,0 @@ ---- -'astro': patch -'@astrojs/db': patch ---- - -Reverts back to `yargs-parser` package for CLI argument parsing diff --git a/examples/basics/package.json b/examples/basics/package.json index 08868cdadfba..be4bf81ad1c6 100644 --- a/examples/basics/package.json +++ b/examples/basics/package.json @@ -11,6 +11,6 @@ "astro": "astro" }, "dependencies": { - "astro": "^4.14.1" + "astro": "^4.14.2" } } diff --git a/examples/blog/package.json b/examples/blog/package.json index 1f8e5af6e151..2b248d3a8d29 100644 --- a/examples/blog/package.json +++ b/examples/blog/package.json @@ -14,6 +14,6 @@ "@astrojs/mdx": "^3.1.3", "@astrojs/rss": "^4.0.7", "@astrojs/sitemap": "^3.1.6", - "astro": "^4.14.1" + "astro": "^4.14.2" } } diff --git a/examples/component/package.json b/examples/component/package.json index 86ee213d7411..3d2e2bead498 100644 --- a/examples/component/package.json +++ b/examples/component/package.json @@ -15,7 +15,7 @@ ], "scripts": {}, "devDependencies": { - "astro": "^4.14.1" + "astro": "^4.14.2" }, "peerDependencies": { "astro": "^4.0.0" diff --git a/examples/container-with-vitest/package.json b/examples/container-with-vitest/package.json index be5562e9b841..1c673234054c 100644 --- a/examples/container-with-vitest/package.json +++ b/examples/container-with-vitest/package.json @@ -12,7 +12,7 @@ "test": "vitest run" }, "dependencies": { - "astro": "^4.14.1", + "astro": "^4.14.2", "@astrojs/react": "^3.6.2", "react": "^18.3.1", "react-dom": "^18.3.1", diff --git a/examples/framework-alpine/package.json b/examples/framework-alpine/package.json index 97625ebbf3ff..03cfff656dbf 100644 --- a/examples/framework-alpine/package.json +++ b/examples/framework-alpine/package.json @@ -14,6 +14,6 @@ "@astrojs/alpinejs": "^0.4.0", "@types/alpinejs": "^3.13.10", "alpinejs": "^3.14.1", - "astro": "^4.14.1" + "astro": "^4.14.2" } } diff --git a/examples/framework-lit/package.json b/examples/framework-lit/package.json index 592caf172d41..cdb7d272a4e7 100644 --- a/examples/framework-lit/package.json +++ b/examples/framework-lit/package.json @@ -13,7 +13,7 @@ "dependencies": { "@astrojs/lit": "^4.3.0", "@webcomponents/template-shadowroot": "^0.2.1", - "astro": "^4.14.1", + "astro": "^4.14.2", "lit": "^3.2.0" } } diff --git a/examples/framework-multiple/package.json b/examples/framework-multiple/package.json index ae2bb7d5439c..626962d02e99 100644 --- a/examples/framework-multiple/package.json +++ b/examples/framework-multiple/package.json @@ -18,7 +18,7 @@ "@astrojs/vue": "^4.5.0", "@types/react": "^18.3.3", "@types/react-dom": "^18.3.0", - "astro": "^4.14.1", + "astro": "^4.14.2", "preact": "^10.23.1", "react": "^18.3.1", "react-dom": "^18.3.1", diff --git a/examples/framework-preact/package.json b/examples/framework-preact/package.json index 2c962c87cb12..d7169d6cc2e9 100644 --- a/examples/framework-preact/package.json +++ b/examples/framework-preact/package.json @@ -13,7 +13,7 @@ "dependencies": { "@astrojs/preact": "^3.5.1", "@preact/signals": "^1.3.0", - "astro": "^4.14.1", + "astro": "^4.14.2", "preact": "^10.23.1" } } diff --git a/examples/framework-react/package.json b/examples/framework-react/package.json index eb74ea33a599..4fbde09c6476 100644 --- a/examples/framework-react/package.json +++ b/examples/framework-react/package.json @@ -14,7 +14,7 @@ "@astrojs/react": "^3.6.2", "@types/react": "^18.3.3", "@types/react-dom": "^18.3.0", - "astro": "^4.14.1", + "astro": "^4.14.2", "react": "^18.3.1", "react-dom": "^18.3.1" } diff --git a/examples/framework-solid/package.json b/examples/framework-solid/package.json index 57d5dced25d1..cc583f052e6e 100644 --- a/examples/framework-solid/package.json +++ b/examples/framework-solid/package.json @@ -12,7 +12,7 @@ }, "dependencies": { "@astrojs/solid-js": "^4.4.1", - "astro": "^4.14.1", + "astro": "^4.14.2", "solid-js": "^1.8.20" } } diff --git a/examples/framework-svelte/package.json b/examples/framework-svelte/package.json index 472078dac4e7..42a99cd2473a 100644 --- a/examples/framework-svelte/package.json +++ b/examples/framework-svelte/package.json @@ -12,7 +12,7 @@ }, "dependencies": { "@astrojs/svelte": "^5.7.0", - "astro": "^4.14.1", + "astro": "^4.14.2", "svelte": "^4.2.18" } } diff --git a/examples/framework-vue/package.json b/examples/framework-vue/package.json index b0109ba3985d..1bff3df25d21 100644 --- a/examples/framework-vue/package.json +++ b/examples/framework-vue/package.json @@ -12,7 +12,7 @@ }, "dependencies": { "@astrojs/vue": "^4.5.0", - "astro": "^4.14.1", + "astro": "^4.14.2", "vue": "^3.4.37" } } diff --git a/examples/hackernews/package.json b/examples/hackernews/package.json index 0769ac6b2977..bc5ee46b2c2b 100644 --- a/examples/hackernews/package.json +++ b/examples/hackernews/package.json @@ -12,6 +12,6 @@ }, "dependencies": { "@astrojs/node": "^8.3.3", - "astro": "^4.14.1" + "astro": "^4.14.2" } } diff --git a/examples/integration/package.json b/examples/integration/package.json index 36b2da876cca..d8225462a805 100644 --- a/examples/integration/package.json +++ b/examples/integration/package.json @@ -15,7 +15,7 @@ ], "scripts": {}, "devDependencies": { - "astro": "^4.14.1" + "astro": "^4.14.2" }, "peerDependencies": { "astro": "^4.0.0" diff --git a/examples/middleware/package.json b/examples/middleware/package.json index 7c028461316e..db80ba2fe233 100644 --- a/examples/middleware/package.json +++ b/examples/middleware/package.json @@ -13,7 +13,7 @@ }, "dependencies": { "@astrojs/node": "^8.3.3", - "astro": "^4.14.1", + "astro": "^4.14.2", "html-minifier": "^4.0.0" }, "devDependencies": { diff --git a/examples/minimal/package.json b/examples/minimal/package.json index a40a78756134..129a0e1c68d6 100644 --- a/examples/minimal/package.json +++ b/examples/minimal/package.json @@ -11,6 +11,6 @@ "astro": "astro" }, "dependencies": { - "astro": "^4.14.1" + "astro": "^4.14.2" } } diff --git a/examples/non-html-pages/package.json b/examples/non-html-pages/package.json index bf00519699b2..14750d84118e 100644 --- a/examples/non-html-pages/package.json +++ b/examples/non-html-pages/package.json @@ -11,6 +11,6 @@ "astro": "astro" }, "dependencies": { - "astro": "^4.14.1" + "astro": "^4.14.2" } } diff --git a/examples/portfolio/package.json b/examples/portfolio/package.json index 9cff3186c2ac..22e75e1419ea 100644 --- a/examples/portfolio/package.json +++ b/examples/portfolio/package.json @@ -11,6 +11,6 @@ "astro": "astro" }, "dependencies": { - "astro": "^4.14.1" + "astro": "^4.14.2" } } diff --git a/examples/server-islands/package.json b/examples/server-islands/package.json index 09c3a1d377ca..a3bf732943f2 100644 --- a/examples/server-islands/package.json +++ b/examples/server-islands/package.json @@ -17,7 +17,7 @@ "@tailwindcss/forms": "^0.5.7", "@types/react": "^18.3.3", "@types/react-dom": "^18.3.0", - "astro": "^4.14.1", + "astro": "^4.14.2", "postcss": "^8.4.41", "react": "^18.3.1", "react-dom": "^18.3.1", diff --git a/examples/ssr/package.json b/examples/ssr/package.json index a1f828779c30..d35df0ec4c56 100644 --- a/examples/ssr/package.json +++ b/examples/ssr/package.json @@ -14,7 +14,7 @@ "dependencies": { "@astrojs/node": "^8.3.3", "@astrojs/svelte": "^5.7.0", - "astro": "^4.14.1", + "astro": "^4.14.2", "svelte": "^4.2.18" } } diff --git a/examples/starlog/package.json b/examples/starlog/package.json index 9d61795310c9..905df4a69dfe 100644 --- a/examples/starlog/package.json +++ b/examples/starlog/package.json @@ -10,7 +10,7 @@ "astro": "astro" }, "dependencies": { - "astro": "^4.14.1", + "astro": "^4.14.2", "sass": "^1.77.8", "sharp": "^0.33.3" } diff --git a/examples/toolbar-app/package.json b/examples/toolbar-app/package.json index bfb0f17ecde2..d08c29bca229 100644 --- a/examples/toolbar-app/package.json +++ b/examples/toolbar-app/package.json @@ -15,6 +15,6 @@ "./app": "./dist/app.js" }, "devDependencies": { - "astro": "^4.14.1" + "astro": "^4.14.2" } } diff --git a/examples/view-transitions/package.json b/examples/view-transitions/package.json index dfcdf86c296e..7448b9ec0a8f 100644 --- a/examples/view-transitions/package.json +++ b/examples/view-transitions/package.json @@ -12,6 +12,6 @@ "devDependencies": { "@astrojs/tailwind": "^5.1.0", "@astrojs/node": "^8.3.3", - "astro": "^4.14.1" + "astro": "^4.14.2" } } diff --git a/examples/with-markdoc/package.json b/examples/with-markdoc/package.json index b0914c2b8610..1af3bc63c152 100644 --- a/examples/with-markdoc/package.json +++ b/examples/with-markdoc/package.json @@ -12,6 +12,6 @@ }, "dependencies": { "@astrojs/markdoc": "^0.11.3", - "astro": "^4.14.1" + "astro": "^4.14.2" } } diff --git a/examples/with-markdown-plugins/package.json b/examples/with-markdown-plugins/package.json index b84a26fd0ef2..61f1253458f9 100644 --- a/examples/with-markdown-plugins/package.json +++ b/examples/with-markdown-plugins/package.json @@ -12,7 +12,7 @@ }, "dependencies": { "@astrojs/markdown-remark": "^5.2.0", - "astro": "^4.14.1", + "astro": "^4.14.2", "hast-util-select": "^6.0.2", "rehype-autolink-headings": "^7.1.0", "rehype-slug": "^6.0.0", diff --git a/examples/with-markdown-shiki/package.json b/examples/with-markdown-shiki/package.json index 0c49f34b2a39..e1486a376a88 100644 --- a/examples/with-markdown-shiki/package.json +++ b/examples/with-markdown-shiki/package.json @@ -11,6 +11,6 @@ "astro": "astro" }, "dependencies": { - "astro": "^4.14.1" + "astro": "^4.14.2" } } diff --git a/examples/with-mdx/package.json b/examples/with-mdx/package.json index 80c142c438bb..934959975cd8 100644 --- a/examples/with-mdx/package.json +++ b/examples/with-mdx/package.json @@ -13,7 +13,7 @@ "dependencies": { "@astrojs/mdx": "^3.1.3", "@astrojs/preact": "^3.5.1", - "astro": "^4.14.1", + "astro": "^4.14.2", "preact": "^10.23.1" } } diff --git a/examples/with-nanostores/package.json b/examples/with-nanostores/package.json index 4b7009566feb..b8db777b4225 100644 --- a/examples/with-nanostores/package.json +++ b/examples/with-nanostores/package.json @@ -13,7 +13,7 @@ "dependencies": { "@astrojs/preact": "^3.5.1", "@nanostores/preact": "^0.5.2", - "astro": "^4.14.1", + "astro": "^4.14.2", "nanostores": "^0.11.2", "preact": "^10.23.1" } diff --git a/examples/with-tailwindcss/package.json b/examples/with-tailwindcss/package.json index c744d8e05149..80ba691d86c0 100644 --- a/examples/with-tailwindcss/package.json +++ b/examples/with-tailwindcss/package.json @@ -14,7 +14,7 @@ "@astrojs/mdx": "^3.1.3", "@astrojs/tailwind": "^5.1.0", "@types/canvas-confetti": "^1.6.4", - "astro": "^4.14.1", + "astro": "^4.14.2", "autoprefixer": "^10.4.20", "canvas-confetti": "^1.9.3", "postcss": "^8.4.41", diff --git a/examples/with-vitest/package.json b/examples/with-vitest/package.json index eb0cf46cf1e8..88956a94eb43 100644 --- a/examples/with-vitest/package.json +++ b/examples/with-vitest/package.json @@ -12,7 +12,7 @@ "test": "vitest" }, "dependencies": { - "astro": "^4.14.1", + "astro": "^4.14.2", "vitest": "^2.0.5" } } diff --git a/packages/astro/CHANGELOG.md b/packages/astro/CHANGELOG.md index e7417b655c8d..5c93709a4b30 100644 --- a/packages/astro/CHANGELOG.md +++ b/packages/astro/CHANGELOG.md @@ -1,5 +1,11 @@ # astro +## 4.14.2 + +### Patch Changes + +- [#11733](https://github.com/withastro/astro/pull/11733) [`391324d`](https://github.com/withastro/astro/commit/391324df969db71d1c7ca25c2ed14c9eb6eea5ee) Thanks [@bluwy](https://github.com/bluwy)! - Reverts back to `yargs-parser` package for CLI argument parsing + ## 4.14.1 ### Patch Changes diff --git a/packages/astro/package.json b/packages/astro/package.json index 6da1e12e7fe0..9fac8c9b704a 100644 --- a/packages/astro/package.json +++ b/packages/astro/package.json @@ -1,6 +1,6 @@ { "name": "astro", - "version": "4.14.1", + "version": "4.14.2", "description": "Astro is a modern site builder with web best practices, performance, and DX front-of-mind.", "type": "module", "author": "withastro", diff --git a/packages/create-astro/CHANGELOG.md b/packages/create-astro/CHANGELOG.md index 600e9f8e63fd..19ae5f93f39c 100644 --- a/packages/create-astro/CHANGELOG.md +++ b/packages/create-astro/CHANGELOG.md @@ -1,5 +1,11 @@ # create-astro +## 4.8.3 + +### Patch Changes + +- [#11733](https://github.com/withastro/astro/pull/11733) [`391324d`](https://github.com/withastro/astro/commit/391324df969db71d1c7ca25c2ed14c9eb6eea5ee) Thanks [@bluwy](https://github.com/bluwy)! - Reverts back to `arg` package for CLI argument parsing + ## 4.8.2 ### Patch Changes diff --git a/packages/create-astro/package.json b/packages/create-astro/package.json index 79cea9ce9394..e22a738fae2a 100644 --- a/packages/create-astro/package.json +++ b/packages/create-astro/package.json @@ -1,6 +1,6 @@ { "name": "create-astro", - "version": "4.8.2", + "version": "4.8.3", "type": "module", "author": "withastro", "license": "MIT", diff --git a/packages/db/CHANGELOG.md b/packages/db/CHANGELOG.md index 046d3305ba4c..9fcc870d39ef 100644 --- a/packages/db/CHANGELOG.md +++ b/packages/db/CHANGELOG.md @@ -1,5 +1,14 @@ # @astrojs/db +## 0.13.1 + +### Patch Changes + +- [#11733](https://github.com/withastro/astro/pull/11733) [`391324d`](https://github.com/withastro/astro/commit/391324df969db71d1c7ca25c2ed14c9eb6eea5ee) Thanks [@bluwy](https://github.com/bluwy)! - Reverts back to `yargs-parser` package for CLI argument parsing + +- Updated dependencies []: + - @astrojs/studio@0.1.1 + ## 0.13.0 ### Minor Changes diff --git a/packages/db/package.json b/packages/db/package.json index adc6fde648c1..5f82fa910477 100644 --- a/packages/db/package.json +++ b/packages/db/package.json @@ -1,6 +1,6 @@ { "name": "@astrojs/db", - "version": "0.13.0", + "version": "0.13.1", "description": "Add libSQL and Astro Studio support to your Astro site", "license": "MIT", "repository": { diff --git a/packages/upgrade/CHANGELOG.md b/packages/upgrade/CHANGELOG.md index b0c80a869145..2156497a7909 100644 --- a/packages/upgrade/CHANGELOG.md +++ b/packages/upgrade/CHANGELOG.md @@ -1,5 +1,11 @@ # @astrojs/upgrade +## 0.3.3 + +### Patch Changes + +- [#11733](https://github.com/withastro/astro/pull/11733) [`391324d`](https://github.com/withastro/astro/commit/391324df969db71d1c7ca25c2ed14c9eb6eea5ee) Thanks [@bluwy](https://github.com/bluwy)! - Reverts back to `arg` package for CLI argument parsing + ## 0.3.2 ### Patch Changes diff --git a/packages/upgrade/package.json b/packages/upgrade/package.json index 3f005e1f8e3e..286a0be7813c 100644 --- a/packages/upgrade/package.json +++ b/packages/upgrade/package.json @@ -1,6 +1,6 @@ { "name": "@astrojs/upgrade", - "version": "0.3.2", + "version": "0.3.3", "type": "module", "author": "withastro", "license": "MIT", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 48b1f14e6da1..64c206e7e8f1 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -116,7 +116,7 @@ importers: examples/basics: dependencies: astro: - specifier: ^4.14.1 + specifier: ^4.14.2 version: link:../../packages/astro examples/blog: @@ -131,13 +131,13 @@ importers: specifier: ^3.1.6 version: link:../../packages/integrations/sitemap astro: - specifier: ^4.14.1 + specifier: ^4.14.2 version: link:../../packages/astro examples/component: devDependencies: astro: - specifier: ^4.14.1 + specifier: ^4.14.2 version: link:../../packages/astro examples/container-with-vitest: @@ -146,7 +146,7 @@ importers: specifier: ^3.6.2 version: link:../../packages/integrations/react astro: - specifier: ^4.14.1 + specifier: ^4.14.2 version: link:../../packages/astro react: specifier: ^18.3.1 @@ -177,7 +177,7 @@ importers: specifier: ^3.14.1 version: 3.14.1 astro: - specifier: ^4.14.1 + specifier: ^4.14.2 version: link:../../packages/astro examples/framework-lit: @@ -189,7 +189,7 @@ importers: specifier: ^0.2.1 version: 0.2.1 astro: - specifier: ^4.14.1 + specifier: ^4.14.2 version: link:../../packages/astro lit: specifier: ^3.2.0 @@ -219,7 +219,7 @@ importers: specifier: ^18.3.0 version: 18.3.0 astro: - specifier: ^4.14.1 + specifier: ^4.14.2 version: link:../../packages/astro preact: specifier: ^10.23.1 @@ -249,7 +249,7 @@ importers: specifier: ^1.3.0 version: 1.3.0(preact@10.23.1) astro: - specifier: ^4.14.1 + specifier: ^4.14.2 version: link:../../packages/astro preact: specifier: ^10.23.1 @@ -267,7 +267,7 @@ importers: specifier: ^18.3.0 version: 18.3.0 astro: - specifier: ^4.14.1 + specifier: ^4.14.2 version: link:../../packages/astro react: specifier: ^18.3.1 @@ -282,7 +282,7 @@ importers: specifier: ^4.4.1 version: link:../../packages/integrations/solid astro: - specifier: ^4.14.1 + specifier: ^4.14.2 version: link:../../packages/astro solid-js: specifier: ^1.8.20 @@ -294,7 +294,7 @@ importers: specifier: ^5.7.0 version: link:../../packages/integrations/svelte astro: - specifier: ^4.14.1 + specifier: ^4.14.2 version: link:../../packages/astro svelte: specifier: ^4.2.18 @@ -306,7 +306,7 @@ importers: specifier: ^4.5.0 version: link:../../packages/integrations/vue astro: - specifier: ^4.14.1 + specifier: ^4.14.2 version: link:../../packages/astro vue: specifier: ^3.4.37 @@ -318,13 +318,13 @@ importers: specifier: ^8.3.3 version: link:../../packages/integrations/node astro: - specifier: ^4.14.1 + specifier: ^4.14.2 version: link:../../packages/astro examples/integration: devDependencies: astro: - specifier: ^4.14.1 + specifier: ^4.14.2 version: link:../../packages/astro examples/middleware: @@ -333,7 +333,7 @@ importers: specifier: ^8.3.3 version: link:../../packages/integrations/node astro: - specifier: ^4.14.1 + specifier: ^4.14.2 version: link:../../packages/astro html-minifier: specifier: ^4.0.0 @@ -346,19 +346,19 @@ importers: examples/minimal: dependencies: astro: - specifier: ^4.14.1 + specifier: ^4.14.2 version: link:../../packages/astro examples/non-html-pages: dependencies: astro: - specifier: ^4.14.1 + specifier: ^4.14.2 version: link:../../packages/astro examples/portfolio: dependencies: astro: - specifier: ^4.14.1 + specifier: ^4.14.2 version: link:../../packages/astro examples/server-islands: @@ -385,7 +385,7 @@ importers: specifier: ^18.3.0 version: 18.3.0 astro: - specifier: ^4.14.1 + specifier: ^4.14.2 version: link:../../packages/astro postcss: specifier: ^8.4.41 @@ -409,7 +409,7 @@ importers: specifier: ^5.7.0 version: link:../../packages/integrations/svelte astro: - specifier: ^4.14.1 + specifier: ^4.14.2 version: link:../../packages/astro svelte: specifier: ^4.2.18 @@ -418,7 +418,7 @@ importers: examples/starlog: dependencies: astro: - specifier: ^4.14.1 + specifier: ^4.14.2 version: link:../../packages/astro sass: specifier: ^1.77.8 @@ -430,7 +430,7 @@ importers: examples/toolbar-app: devDependencies: astro: - specifier: ^4.14.1 + specifier: ^4.14.2 version: link:../../packages/astro examples/view-transitions: @@ -442,7 +442,7 @@ importers: specifier: ^5.1.0 version: link:../../packages/integrations/tailwind astro: - specifier: ^4.14.1 + specifier: ^4.14.2 version: link:../../packages/astro examples/with-markdoc: @@ -451,7 +451,7 @@ importers: specifier: ^0.11.3 version: link:../../packages/integrations/markdoc astro: - specifier: ^4.14.1 + specifier: ^4.14.2 version: link:../../packages/astro examples/with-markdown-plugins: @@ -460,7 +460,7 @@ importers: specifier: ^5.2.0 version: link:../../packages/markdown/remark astro: - specifier: ^4.14.1 + specifier: ^4.14.2 version: link:../../packages/astro hast-util-select: specifier: ^6.0.2 @@ -481,7 +481,7 @@ importers: examples/with-markdown-shiki: dependencies: astro: - specifier: ^4.14.1 + specifier: ^4.14.2 version: link:../../packages/astro examples/with-mdx: @@ -493,7 +493,7 @@ importers: specifier: ^3.5.1 version: link:../../packages/integrations/preact astro: - specifier: ^4.14.1 + specifier: ^4.14.2 version: link:../../packages/astro preact: specifier: ^10.23.1 @@ -508,7 +508,7 @@ importers: specifier: ^0.5.2 version: 0.5.2(nanostores@0.11.2)(preact@10.23.1) astro: - specifier: ^4.14.1 + specifier: ^4.14.2 version: link:../../packages/astro nanostores: specifier: ^0.11.2 @@ -529,7 +529,7 @@ importers: specifier: ^1.6.4 version: 1.6.4 astro: - specifier: ^4.14.1 + specifier: ^4.14.2 version: link:../../packages/astro autoprefixer: specifier: ^10.4.20 @@ -547,7 +547,7 @@ importers: examples/with-vitest: dependencies: astro: - specifier: ^4.14.1 + specifier: ^4.14.2 version: link:../../packages/astro vitest: specifier: ^2.0.5 @@ -9494,12 +9494,10 @@ packages: libsql@0.3.19: resolution: {integrity: sha512-Aj5cQ5uk/6fHdmeW0TiXK42FqUlwx7ytmMLPSaUQPin5HKKKuUPD62MAbN4OEweGBBI7q1BekoEN4gPUEL6MZA==} - cpu: [x64, arm64, wasm32] os: [darwin, linux, win32] libsql@0.4.1: resolution: {integrity: sha512-qZlR9Yu1zMBeLChzkE/cKfoKV3Esp9cn9Vx5Zirn4AVhDWPcjYhKwbtJcMuHehgk3mH+fJr9qW+3vesBWbQpBg==} - cpu: [x64, arm64, wasm32] os: [darwin, linux, win32] lilconfig@2.1.0: From 423614ebb6ddb76cc8d11f3e3b6ae111a4a82662 Mon Sep 17 00:00:00 2001 From: Bjorn Lu Date: Fri, 16 Aug 2024 12:09:20 +0800 Subject: [PATCH 26/29] Fix MDX stack trace location with frontmatter (#11717) --- .changeset/mighty-trees-teach.md | 5 +++++ packages/integrations/mdx/src/vite-plugin-mdx.ts | 5 +++-- 2 files changed, 8 insertions(+), 2 deletions(-) create mode 100644 .changeset/mighty-trees-teach.md diff --git a/.changeset/mighty-trees-teach.md b/.changeset/mighty-trees-teach.md new file mode 100644 index 000000000000..289a41816154 --- /dev/null +++ b/.changeset/mighty-trees-teach.md @@ -0,0 +1,5 @@ +--- +'@astrojs/mdx': patch +--- + +Fixes stack trace location when failed to parse an MDX file with frontmatter diff --git a/packages/integrations/mdx/src/vite-plugin-mdx.ts b/packages/integrations/mdx/src/vite-plugin-mdx.ts index b232d1c83fc8..7b37535d8e98 100644 --- a/packages/integrations/mdx/src/vite-plugin-mdx.ts +++ b/packages/integrations/mdx/src/vite-plugin-mdx.ts @@ -44,9 +44,10 @@ export function vitePluginMdx(mdxOptions: MdxOptions): Plugin { async transform(code, id) { if (!id.endsWith('.mdx')) return; - const { data: frontmatter, content: pageContent } = parseFrontmatter(code, id); + const { data: frontmatter, content: pageContent, matter } = parseFrontmatter(code, id); + const frontmatterLines = matter ? matter.match(/\n/g)?.join('') + '\n\n' : ''; - const vfile = new VFile({ value: pageContent, path: id }); + const vfile = new VFile({ value: frontmatterLines + pageContent, path: id }); // Ensure `data.astro` is available to all remark plugins setVfileFrontmatter(vfile, frontmatter); From 2df49a6fb4f6d92fe45f7429430abe63defeacd6 Mon Sep 17 00:00:00 2001 From: Florian Lefebvre Date: Fri, 16 Aug 2024 09:27:21 +0200 Subject: [PATCH 27/29] feat: simplifies sync paths (#11730) --- .changeset/spicy-houses-fry.md | 5 +++++ packages/astro/src/core/sync/write-files.ts | 12 +++++------- packages/astro/test/astro-sync.test.js | 4 +--- .../test/units/dev/collections-renderentry.test.js | 5 +---- 4 files changed, 12 insertions(+), 14 deletions(-) create mode 100644 .changeset/spicy-houses-fry.md diff --git a/.changeset/spicy-houses-fry.md b/.changeset/spicy-houses-fry.md new file mode 100644 index 000000000000..41f376a3546f --- /dev/null +++ b/.changeset/spicy-houses-fry.md @@ -0,0 +1,5 @@ +--- +'astro': patch +--- + +Simplifies path operations of `astro sync` diff --git a/packages/astro/src/core/sync/write-files.ts b/packages/astro/src/core/sync/write-files.ts index 395bd54f2b12..62f2ccb21f99 100644 --- a/packages/astro/src/core/sync/write-files.ts +++ b/packages/astro/src/core/sync/write-files.ts @@ -2,11 +2,11 @@ import type fsMod from 'node:fs'; import { dirname, relative } from 'node:path'; import { fileURLToPath } from 'node:url'; import { bold } from 'kleur/colors'; -import { normalizePath } from 'vite'; import type { AstroSettings } from '../../@types/astro.js'; import { AstroError, AstroErrorData } from '../errors/index.js'; import type { Logger } from '../logger/core.js'; import { REFERENCE_FILE } from './constants.js'; +import { normalizePath } from 'vite'; export async function writeFiles(settings: AstroSettings, fs: typeof fsMod, logger: Logger) { try { @@ -27,7 +27,7 @@ function writeInjectedTypes(settings: AstroSettings, fs: typeof fsMod) { const references: Array = []; for (const { filename, content } of settings.injectedTypes) { - const filepath = normalizePath(fileURLToPath(new URL(filename, settings.dotAstroDir))); + const filepath = fileURLToPath(new URL(filename, settings.dotAstroDir)); fs.mkdirSync(dirname(filepath), { recursive: true }); fs.writeFileSync(filepath, content, 'utf-8'); references.push(normalizePath(relative(fileURLToPath(settings.dotAstroDir), filepath))); @@ -38,17 +38,15 @@ function writeInjectedTypes(settings: AstroSettings, fs: typeof fsMod) { fs.mkdirSync(settings.dotAstroDir, { recursive: true }); } fs.writeFileSync( - normalizePath(fileURLToPath(new URL(REFERENCE_FILE, settings.dotAstroDir))), + fileURLToPath(new URL(REFERENCE_FILE, settings.dotAstroDir)), astroDtsContent, 'utf-8', ); } async function setUpEnvTs(settings: AstroSettings, fs: typeof fsMod, logger: Logger) { - const envTsPath = normalizePath(fileURLToPath(new URL('env.d.ts', settings.config.srcDir))); - const envTsPathRelativetoRoot = normalizePath( - relative(fileURLToPath(settings.config.root), envTsPath), - ); + const envTsPath = fileURLToPath(new URL('env.d.ts', settings.config.srcDir)); + const envTsPathRelativetoRoot = relative(fileURLToPath(settings.config.root), envTsPath); const relativePath = normalizePath( relative( fileURLToPath(settings.config.srcDir), diff --git a/packages/astro/test/astro-sync.test.js b/packages/astro/test/astro-sync.test.js index dfe4755d1102..bb044574fe32 100644 --- a/packages/astro/test/astro-sync.test.js +++ b/packages/astro/test/astro-sync.test.js @@ -4,7 +4,6 @@ import * as fs from 'node:fs'; import { beforeEach, describe, it } from 'node:test'; import { fileURLToPath } from 'node:url'; import ts from 'typescript'; -import { normalizePath } from 'vite'; import { loadFixture } from './test-utils.js'; const createFixture = () => { @@ -16,8 +15,7 @@ const createFixture = () => { /** * @param {string} path */ - const getExpectedPath = (path) => - normalizePath(fileURLToPath(new URL(path, astroFixture.config.root))); + const getExpectedPath = (path) => fileURLToPath(new URL(path, astroFixture.config.root)); return { /** @param {string} root */ diff --git a/packages/astro/test/units/dev/collections-renderentry.test.js b/packages/astro/test/units/dev/collections-renderentry.test.js index 9441129a7cd4..082cd6b2f78b 100644 --- a/packages/astro/test/units/dev/collections-renderentry.test.js +++ b/packages/astro/test/units/dev/collections-renderentry.test.js @@ -1,5 +1,4 @@ import * as assert from 'node:assert/strict'; -import os from 'node:os'; import { describe, it } from 'node:test'; import { fileURLToPath } from 'node:url'; import * as cheerio from 'cheerio'; @@ -9,8 +8,6 @@ import { createFsWithFallback, createRequestAndResponse, runInContainer } from ' const root = new URL('../../fixtures/content/', import.meta.url); -const _describe = os.platform() === 'win32' ? describe.skip : describe; - /** @type {typeof runInContainer} */ async function runInContainerWithContentListeners(params, callback) { return await runInContainer(params, async (container) => { @@ -19,7 +16,7 @@ async function runInContainerWithContentListeners(params, callback) { }); } -_describe('Content Collections - render()', () => { +describe('Content Collections - render()', () => { it('can be called in a page component', async () => { const fs = createFsWithFallback( { From 5f0b58fb6c656243b0f1456266f07af59834e781 Mon Sep 17 00:00:00 2001 From: Florian Lefebvre Date: Fri, 16 Aug 2024 07:28:10 +0000 Subject: [PATCH 28/29] [ci] format --- packages/astro/src/core/sync/write-files.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/astro/src/core/sync/write-files.ts b/packages/astro/src/core/sync/write-files.ts index 62f2ccb21f99..91084c36f965 100644 --- a/packages/astro/src/core/sync/write-files.ts +++ b/packages/astro/src/core/sync/write-files.ts @@ -2,11 +2,11 @@ import type fsMod from 'node:fs'; import { dirname, relative } from 'node:path'; import { fileURLToPath } from 'node:url'; import { bold } from 'kleur/colors'; +import { normalizePath } from 'vite'; import type { AstroSettings } from '../../@types/astro.js'; import { AstroError, AstroErrorData } from '../errors/index.js'; import type { Logger } from '../logger/core.js'; import { REFERENCE_FILE } from './constants.js'; -import { normalizePath } from 'vite'; export async function writeFiles(settings: AstroSettings, fs: typeof fsMod, logger: Logger) { try { From d74617cbd3278feba05909ec83db2d73d57a153e Mon Sep 17 00:00:00 2001 From: Erika <3019731+Princesseuh@users.noreply.github.com> Date: Fri, 16 Aug 2024 14:07:10 +0200 Subject: [PATCH 29/29] Refactor/types (#11715) * refactor: types * feat: refactor types * chore: organize imports * fix: remaining references * docs: types * refactor: small changes * chore: changeset --- .changeset/poor-frogs-dream.md | 7 + .github/labeler.yml | 2 +- .github/workflows/check.yml | 2 +- .github/workflows/ci.yml | 2 +- CONTRIBUTING.md | 2 +- packages/astro/astro-jsx.d.ts | 20 +- packages/astro/client.d.ts | 20 +- packages/astro/components/Picture.astro | 2 +- packages/astro/config.d.ts | 8 +- packages/astro/env.d.ts | 2 +- packages/astro/index.d.ts | 2 +- packages/astro/src/@types/README.md | 5 - packages/astro/src/@types/app.d.ts | 9 - packages/astro/src/actions/index.ts | 3 +- .../astro/src/actions/runtime/middleware.ts | 3 +- packages/astro/src/actions/runtime/route.ts | 2 +- packages/astro/src/actions/runtime/utils.ts | 2 +- packages/astro/src/actions/utils.ts | 4 +- packages/astro/src/assets/build/generate.ts | 2 +- packages/astro/src/assets/endpoint/config.ts | 2 +- packages/astro/src/assets/endpoint/generic.ts | 2 +- packages/astro/src/assets/endpoint/node.ts | 2 +- packages/astro/src/assets/internal.ts | 2 +- packages/astro/src/assets/services/service.ts | 2 +- .../astro/src/assets/utils/remotePattern.ts | 2 +- .../astro/src/assets/vite-plugin-assets.ts | 3 +- packages/astro/src/cli/db/index.ts | 2 +- packages/astro/src/cli/flags.ts | 2 +- packages/astro/src/cli/info/index.ts | 2 +- packages/astro/src/cli/preferences/index.ts | 2 +- packages/astro/src/config/index.ts | 2 +- .../src/config/vite-plugin-content-listen.ts | 2 +- packages/astro/src/container/index.ts | 43 +- packages/astro/src/container/pipeline.ts | 10 +- packages/astro/src/content/content-layer.ts | 2 +- packages/astro/src/content/loaders/glob.ts | 6 +- packages/astro/src/content/loaders/types.ts | 3 +- packages/astro/src/content/runtime.ts | 2 +- .../astro/src/content/server-listeners.ts | 2 +- packages/astro/src/content/types-generator.ts | 3 +- packages/astro/src/content/utils.ts | 9 +- .../src/content/vite-plugin-content-assets.ts | 3 +- .../content/vite-plugin-content-imports.ts | 16 +- .../vite-plugin-content-virtual-mod.ts | 2 +- packages/astro/src/core/app/index.ts | 3 +- packages/astro/src/core/app/middlewares.ts | 2 +- packages/astro/src/core/app/node.ts | 2 +- packages/astro/src/core/app/pipeline.ts | 11 +- packages/astro/src/core/app/types.ts | 12 +- packages/astro/src/core/base-pipeline.ts | 13 +- packages/astro/src/core/build/common.ts | 3 +- .../astro/src/core/build/css-asset-name.ts | 2 +- packages/astro/src/core/build/generate.ts | 23 +- packages/astro/src/core/build/index.ts | 9 +- packages/astro/src/core/build/internal.ts | 2 +- packages/astro/src/core/build/page-data.ts | 2 +- packages/astro/src/core/build/pipeline.ts | 10 +- .../src/core/build/plugins/plugin-content.ts | 2 +- .../build/plugins/plugin-hoisted-scripts.ts | 2 +- .../src/core/build/plugins/plugin-ssr.ts | 3 +- packages/astro/src/core/build/static-build.ts | 2 +- packages/astro/src/core/build/types.ts | 14 +- packages/astro/src/core/build/util.ts | 2 +- packages/astro/src/core/compile/compile.ts | 2 +- packages/astro/src/core/config/config.ts | 4 +- packages/astro/src/core/config/logging.ts | 2 +- packages/astro/src/core/config/schema.ts | 2 +- packages/astro/src/core/config/settings.ts | 3 +- packages/astro/src/core/config/validate.ts | 2 +- packages/astro/src/core/create-vite.ts | 4 +- packages/astro/src/core/dev/container.ts | 3 +- packages/astro/src/core/dev/dev.ts | 2 +- packages/astro/src/core/dev/restart.ts | 3 +- packages/astro/src/core/errors/dev/utils.ts | 2 +- packages/astro/src/core/errors/dev/vite.ts | 2 +- packages/astro/src/core/errors/errors-data.ts | 2 +- packages/astro/src/core/errors/utils.ts | 2 +- packages/astro/src/core/index.ts | 2 +- .../src/core/middleware/callMiddleware.ts | 4 +- packages/astro/src/core/middleware/index.ts | 3 +- .../astro/src/core/middleware/sequence.ts | 3 +- .../astro/src/core/middleware/vite-plugin.ts | 2 +- .../astro/src/core/module-loader/loader.ts | 2 +- packages/astro/src/core/preview/index.ts | 3 +- .../src/core/preview/static-preview-server.ts | 2 +- .../core/preview/vite-plugin-astro-preview.ts | 2 +- .../astro/src/core/redirects/component.ts | 2 +- packages/astro/src/core/redirects/helpers.ts | 6 +- packages/astro/src/core/render-context.ts | 15 +- packages/astro/src/core/render/index.ts | 3 +- packages/astro/src/core/render/paginate.ts | 4 +- .../astro/src/core/render/params-and-props.ts | 4 +- packages/astro/src/core/render/renderer.ts | 3 +- packages/astro/src/core/render/route-cache.ts | 8 +- packages/astro/src/core/render/slots.ts | 2 +- packages/astro/src/core/render/ssr-element.ts | 4 +- .../routing/astro-designed-error-pages.ts | 3 +- packages/astro/src/core/routing/default.ts | 3 +- .../astro/src/core/routing/manifest/create.ts | 12 +- .../src/core/routing/manifest/generator.ts | 4 +- .../src/core/routing/manifest/pattern.ts | 3 +- .../core/routing/manifest/serialization.ts | 4 +- packages/astro/src/core/routing/match.ts | 3 +- packages/astro/src/core/routing/params.ts | 3 +- packages/astro/src/core/routing/priority.ts | 2 +- packages/astro/src/core/routing/rewrite.ts | 4 +- packages/astro/src/core/routing/validation.ts | 4 +- .../astro/src/core/server-islands/endpoint.ts | 8 +- .../vite-plugin-server-islands.ts | 2 +- packages/astro/src/core/sync/index.ts | 3 +- packages/astro/src/core/sync/write-files.ts | 2 +- packages/astro/src/core/util.ts | 4 +- packages/astro/src/env/sync.ts | 2 +- packages/astro/src/env/vite-plugin-env.ts | 2 +- packages/astro/src/events/session.ts | 3 +- packages/astro/src/i18n/index.ts | 10 +- packages/astro/src/i18n/middleware.ts | 5 +- packages/astro/src/i18n/utils.ts | 2 +- packages/astro/src/i18n/vite-plugin-i18n.ts | 3 +- .../src/integrations/features-validation.ts | 16 +- packages/astro/src/integrations/hooks.ts | 27 +- packages/astro/src/jsx/renderer.ts | 5 +- packages/astro/src/jsx/server.ts | 2 +- packages/astro/src/jsx/transform-options.ts | 2 +- packages/astro/src/preferences/index.ts | 3 +- .../src/prefetch/vite-plugin-prefetch.ts | 2 +- packages/astro/src/prerender/routing.ts | 3 +- packages/astro/src/prerender/utils.ts | 2 +- .../runtime/client/dev-toolbar/apps/astro.ts | 2 +- .../client/dev-toolbar/apps/audit/index.ts | 2 +- .../dev-toolbar/apps/audit/ui/audit-ui.ts | 2 +- .../client/dev-toolbar/apps/settings.ts | 2 +- .../runtime/client/dev-toolbar/apps/xray.ts | 2 +- .../runtime/client/dev-toolbar/entrypoint.ts | 2 +- .../src/runtime/client/dev-toolbar/toolbar.ts | 2 +- packages/astro/src/runtime/client/idle.ts | 2 +- packages/astro/src/runtime/client/load.ts | 2 +- packages/astro/src/runtime/client/media.ts | 2 +- packages/astro/src/runtime/client/only.ts | 2 +- packages/astro/src/runtime/client/visible.ts | 3 +- .../src/runtime/server/astro-component.ts | 2 +- .../astro/src/runtime/server/astro-global.ts | 2 +- packages/astro/src/runtime/server/endpoint.ts | 7 +- .../astro/src/runtime/server/hydration.ts | 4 +- packages/astro/src/runtime/server/jsx.ts | 2 +- .../runtime/server/render/astro/factory.ts | 2 +- .../runtime/server/render/astro/instance.ts | 2 +- .../src/runtime/server/render/astro/render.ts | 2 +- .../astro/src/runtime/server/render/common.ts | 2 +- .../src/runtime/server/render/component.ts | 12 +- .../astro/src/runtime/server/render/dom.ts | 3 +- .../astro/src/runtime/server/render/head.ts | 3 +- .../astro/src/runtime/server/render/page.ts | 2 +- .../astro/src/runtime/server/render/script.ts | 2 +- .../runtime/server/render/server-islands.ts | 2 +- .../astro/src/runtime/server/render/slot.ts | 2 +- .../astro/src/runtime/server/render/tags.ts | 2 +- .../astro/src/runtime/server/render/util.ts | 2 +- packages/astro/src/runtime/server/scripts.ts | 2 +- .../astro/src/runtime/server/serialize.ts | 2 +- .../astro/src/runtime/server/transition.ts | 6 +- packages/astro/src/toolbar/index.ts | 2 +- .../src/toolbar/vite-plugin-dev-toolbar.ts | 2 +- packages/astro/src/transitions/index.ts | 6 +- .../transitions/vite-plugin-transitions.ts | 2 +- packages/astro/src/types/README.md | 5 + packages/astro/src/types/astro.ts | 93 + packages/astro/src/types/public/common.ts | 176 ++ .../astro.ts => types/public/config.ts} | 1713 +---------------- packages/astro/src/types/public/content.ts | 121 ++ packages/astro/src/types/public/context.ts | 501 +++++ packages/astro/src/types/public/elements.ts | 47 + .../astro/src/types/public/extendables.ts | 21 + packages/astro/src/types/public/index.ts | 44 + .../astro/src/types/public/integrations.ts | 258 +++ packages/astro/src/types/public/internal.ts | 202 ++ packages/astro/src/types/public/preview.ts | 28 + packages/astro/src/types/public/toolbar.ts | 96 + .../src/types/public/view-transitions.ts | 40 + .../src/{@types => types}/typed-emitter.ts | 0 .../astro/src/virtual-modules/container.ts | 3 +- packages/astro/src/virtual-modules/i18n.ts | 9 +- .../src/vite-plugin-astro-server/base.ts | 2 +- .../src/vite-plugin-astro-server/error.ts | 2 +- .../src/vite-plugin-astro-server/metadata.ts | 2 +- .../src/vite-plugin-astro-server/pipeline.ts | 20 +- .../src/vite-plugin-astro-server/plugin.ts | 4 +- .../src/vite-plugin-astro-server/request.ts | 2 +- .../src/vite-plugin-astro-server/route.ts | 3 +- .../src/vite-plugin-astro-server/scripts.ts | 2 +- .../astro/src/vite-plugin-astro/compile.ts | 2 +- packages/astro/src/vite-plugin-astro/index.ts | 3 +- packages/astro/src/vite-plugin-astro/types.ts | 2 +- .../src/vite-plugin-config-alias/index.ts | 2 +- packages/astro/src/vite-plugin-env/index.ts | 3 +- packages/astro/src/vite-plugin-head/index.ts | 2 +- .../index.ts | 3 +- .../content-entry-type.ts | 6 +- .../astro/src/vite-plugin-markdown/index.ts | 2 +- .../src/vite-plugin-mdx/transform-jsx.ts | 2 +- .../astro/src/vite-plugin-scanner/index.ts | 3 +- .../astro/src/vite-plugin-scanner/scan.ts | 2 +- .../astro/src/vite-plugin-scripts/index.ts | 3 +- .../astro/src/vite-plugin-scripts/page-ssr.ts | 2 +- packages/astro/src/vite-plugin-utils/index.ts | 2 +- packages/astro/templates/actions.mjs | 2 +- ...core-image-unconventional-settings.test.js | 2 +- .../fixtures/core-image-ssr/src/pages/api.ts | 2 +- .../deps/test-adapter/index.js | 4 +- packages/astro/test/test-adapter.js | 10 +- packages/astro/test/test-image-service.js | 2 +- packages/astro/test/test-utils.js | 4 +- packages/astro/test/types/call-action.ts | 2 +- packages/astro/test/units/test-utils.js | 6 +- packages/astro/types.d.ts | 2 +- .../integrations/node/test/api-route.test.js | 2 +- 216 files changed, 2079 insertions(+), 2102 deletions(-) create mode 100644 .changeset/poor-frogs-dream.md delete mode 100644 packages/astro/src/@types/README.md delete mode 100644 packages/astro/src/@types/app.d.ts create mode 100644 packages/astro/src/types/README.md create mode 100644 packages/astro/src/types/astro.ts create mode 100644 packages/astro/src/types/public/common.ts rename packages/astro/src/{@types/astro.ts => types/public/config.ts} (58%) create mode 100644 packages/astro/src/types/public/content.ts create mode 100644 packages/astro/src/types/public/context.ts create mode 100644 packages/astro/src/types/public/elements.ts create mode 100644 packages/astro/src/types/public/extendables.ts create mode 100644 packages/astro/src/types/public/index.ts create mode 100644 packages/astro/src/types/public/integrations.ts create mode 100644 packages/astro/src/types/public/internal.ts create mode 100644 packages/astro/src/types/public/preview.ts create mode 100644 packages/astro/src/types/public/toolbar.ts create mode 100644 packages/astro/src/types/public/view-transitions.ts rename packages/astro/src/{@types => types}/typed-emitter.ts (100%) diff --git a/.changeset/poor-frogs-dream.md b/.changeset/poor-frogs-dream.md new file mode 100644 index 000000000000..fdb3daa85284 --- /dev/null +++ b/.changeset/poor-frogs-dream.md @@ -0,0 +1,7 @@ +--- +'astro': major +--- + +Refactor the exported types from the `astro` module. There should normally be no breaking changes, but if you relied on some previously deprecated types, these might now have been fully removed. + +In most cases, updating your code to move away from previously deprecated APIs in previous versions of Astro should be enough to fix any issues. diff --git a/.github/labeler.yml b/.github/labeler.yml index c1025ad117d1..b0d27800ba97 100644 --- a/.github/labeler.yml +++ b/.github/labeler.yml @@ -40,5 +40,5 @@ - packages/integrations/vue/** 'docs pr': -- packages/astro/src/@types/astro.ts +- packages/astro/src/types/public/** - packages/astro/src/core/errors/errors-data.ts diff --git a/.github/workflows/check.yml b/.github/workflows/check.yml index c1b4919901ab..2ce9ac1dbd53 100644 --- a/.github/workflows/check.yml +++ b/.github/workflows/check.yml @@ -11,7 +11,7 @@ on: - "examples/**" - ".github/workflows/check.yml" - "scripts/smoke/check.js" - - "packages/astro/src/@types/astro.ts" + - "packages/astro/src/types/public/**" - "pnpm-lock.yaml" - "packages/astro/types.d.ts" diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 79962c07e1ce..d516ab47a93f 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -229,7 +229,7 @@ jobs: filters: | docs: - 'packages/integrations/*/README.md' - - 'packages/astro/src/@types/astro.ts' + - "packages/astro/src/types/public/**" - 'packages/astro/src/core/errors/errors-data.ts' - name: Build autogenerated docs pages from current astro branch diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index caaa9e726e10..6a657068d1df 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -289,7 +289,7 @@ Server-side rendering (SSR) can be complicated. The Astro package (`packages/ast - `components/`: Built-in components to use in your project (e.g. `import Code from 'astro/components/Code.astro'`) - `src/`: Astro source - - `@types/`: TypeScript types. These are centralized to cut down on circular dependencies + - `types/`: TypeScript types. These are centralized to cut down on circular dependencies - `cli/`: Code that powers the `astro` CLI command - `core/`: Code that executes **in the top-level scope** (in Node). Within, you’ll find code that powers the `astro build` and `astro dev` commands, as well as top-level SSR code. - `runtime/`: Code that executes **in different scopes** (i.e. not in a pure Node context). You’ll have to think about code differently here. diff --git a/packages/astro/astro-jsx.d.ts b/packages/astro/astro-jsx.d.ts index b26507d1db58..128709dfc528 100644 --- a/packages/astro/astro-jsx.d.ts +++ b/packages/astro/astro-jsx.d.ts @@ -17,23 +17,21 @@ declare namespace astroHTML.JSX { children: {}; } - interface IntrinsicAttributes - extends AstroBuiltinProps, - AstroBuiltinAttributes, - AstroClientDirectives { + interface IntrinsicAttributes extends AstroComponentDirectives, AstroBuiltinAttributes { slot?: string | undefined | null; children?: Children; } - type AstroBuiltinProps = import('./dist/@types/astro.js').AstroBuiltinProps; - type AstroClientDirectives = import('./dist/@types/astro.js').AstroClientDirectives; - type AstroBuiltinAttributes = import('./dist/@types/astro.js').AstroBuiltinAttributes; - type AstroDefineVarsAttribute = import('./dist/@types/astro.js').AstroDefineVarsAttribute; - type AstroScriptAttributes = import('./dist/@types/astro.js').AstroScriptAttributes & + type AstroComponentDirectives = + import('./dist/types/public/elements.js').AstroComponentDirectives; + type AstroBuiltinAttributes = import('./dist/types/public/elements.js').AstroBuiltinAttributes; + type AstroDefineVarsAttribute = + import('./dist/types/public/elements.js').AstroDefineVarsAttribute; + type AstroScriptAttributes = import('./dist/types/public/elements.js').AstroScriptAttributes & AstroDefineVarsAttribute; - type AstroStyleAttributes = import('./dist/@types/astro.js').AstroStyleAttributes & + type AstroStyleAttributes = import('./dist/types/public/elements.js').AstroStyleAttributes & AstroDefineVarsAttribute; - type AstroSlotAttributes = import('./dist/@types/astro.js').AstroSlotAttributes; + type AstroSlotAttributes = import('./dist/types/public/elements.js').AstroSlotAttributes; // This is an unfortunate use of `any`, but unfortunately we can't make a type that works for every framework // without importing every single framework's types (which comes with its own set of problems). diff --git a/packages/astro/client.d.ts b/packages/astro/client.d.ts index ed5c1b894d28..796bf3f33deb 100644 --- a/packages/astro/client.d.ts +++ b/packages/astro/client.d.ts @@ -2,12 +2,6 @@ /// /// -// eslint-disable-next-line @typescript-eslint/no-namespace -declare namespace App { - // eslint-disable-next-line @typescript-eslint/no-empty-interface - export interface Locals {} -} - interface ImportMetaEnv { /** * The prefix for Astro-generated asset links if the build.assetsPrefix config option is set. This can be used to create asset links not handled by Astro. @@ -52,7 +46,7 @@ declare module 'astro:assets' { getImage: ( options: import('./dist/assets/types.js').UnresolvedImageTransform, ) => Promise; - imageConfig: import('./dist/@types/astro.js').AstroConfig['image']; + imageConfig: import('./dist/types/public/config.js').AstroConfig['image']; getConfiguredImageService: typeof import('./dist/assets/index.js').getConfiguredImageService; inferRemoteSize: typeof import('./dist/assets/utils/index.js').inferRemoteSize; Image: typeof import('./components/Image.astro').default; @@ -172,7 +166,7 @@ declare module 'astro:components' { export * from 'astro/components'; } -type MD = import('./dist/@types/astro.js').MarkdownInstance>; +type MD = import('./dist/types/public/content.js').MarkdownInstance>; interface ExportedMarkdownModuleEntities { frontmatter: MD['frontmatter']; file: MD['file']; @@ -191,7 +185,6 @@ declare module '*.md' { file, url, getHeadings, - getHeaders, Content, rawContent, compiledContent, @@ -206,7 +199,6 @@ declare module '*.markdown' { file, url, getHeadings, - getHeaders, Content, rawContent, compiledContent, @@ -221,7 +213,6 @@ declare module '*.mkdn' { file, url, getHeadings, - getHeaders, Content, rawContent, compiledContent, @@ -236,7 +227,6 @@ declare module '*.mkd' { file, url, getHeadings, - getHeaders, Content, rawContent, compiledContent, @@ -251,7 +241,6 @@ declare module '*.mdwn' { file, url, getHeadings, - getHeaders, Content, rawContent, compiledContent, @@ -266,7 +255,6 @@ declare module '*.mdown' { file, url, getHeadings, - getHeaders, Content, rawContent, compiledContent, @@ -275,7 +263,7 @@ declare module '*.mdown' { } declare module '*.mdx' { - type MDX = import('./dist/@types/astro.js').MDXInstance>; + type MDX = import('./dist/types/public/content.js').MDXInstance>; export const frontmatter: MDX['frontmatter']; export const file: MDX['file']; @@ -288,7 +276,7 @@ declare module '*.mdx' { } declare module 'astro:ssr-manifest' { - export const manifest: import('./dist/@types/astro.js').SSRManifest; + export const manifest: import('./dist/types/public/internal.js').SSRManifest; } // Everything below are Vite's types (apart from image types, which are in `client.d.ts`) diff --git a/packages/astro/components/Picture.astro b/packages/astro/components/Picture.astro index c85548404d29..6686faf15bbe 100644 --- a/packages/astro/components/Picture.astro +++ b/packages/astro/components/Picture.astro @@ -1,7 +1,7 @@ --- import { type LocalImageProps, type RemoteImageProps, getImage } from 'astro:assets'; import * as mime from 'mrmime'; -import type { GetImageResult, ImageOutputFormat } from '../dist/@types/astro'; +import type { GetImageResult, ImageOutputFormat } from '../dist/types/public/index.js'; import { isESMImportedImage, resolveSrc } from '../dist/assets/utils/imageKind'; import { AstroError, AstroErrorData } from '../dist/core/errors/index.js'; import type { HTMLAttributes } from '../types'; diff --git a/packages/astro/config.d.ts b/packages/astro/config.d.ts index 9f4c6bfd112d..675c783a191d 100644 --- a/packages/astro/config.d.ts +++ b/packages/astro/config.d.ts @@ -1,8 +1,8 @@ type ViteUserConfig = import('vite').UserConfig; type ViteUserConfigFn = import('vite').UserConfigFn; -type AstroUserConfig = import('./dist/@types/astro.js').AstroUserConfig; -type AstroInlineConfig = import('./dist/@types/astro.js').AstroInlineConfig; -type ImageServiceConfig = import('./dist/@types/astro.js').ImageServiceConfig; +type AstroUserConfig = import('./dist/types/public/config.js').AstroUserConfig; +type AstroInlineConfig = import('./dist/types/public/config.js').AstroInlineConfig; +type ImageServiceConfig = import('./dist/types/public/config.js').ImageServiceConfig; type SharpImageServiceConfig = import('./dist/assets/services/sharp.js').SharpImageServiceConfig; type EnvField = typeof import('./dist/env/config.js').envField; @@ -42,4 +42,4 @@ export function passthroughImageService(): ImageServiceConfig; /** * Return a valid env field to use in this Astro config for `experimental.env.schema`. */ -export const envField: EnvField; +export declare const envField: EnvField; diff --git a/packages/astro/env.d.ts b/packages/astro/env.d.ts index 876a29c60f49..d2a788db3d3f 100644 --- a/packages/astro/env.d.ts +++ b/packages/astro/env.d.ts @@ -4,7 +4,7 @@ // As such, if the typings you're trying to add should be available inside ex: React components, they should instead // be inside `client.d.ts` -type Astro = import('./dist/@types/astro.js').AstroGlobal; +type Astro = import('./dist/types/public/context.js').AstroGlobal; // We have to duplicate the description here because editors won't show the JSDoc comment from the imported type // However, they will for its properties, ex: Astro.request will show the AstroGlobal.request description diff --git a/packages/astro/index.d.ts b/packages/astro/index.d.ts index a9e679be17d9..7b7a236e7970 100644 --- a/packages/astro/index.d.ts +++ b/packages/astro/index.d.ts @@ -1,2 +1,2 @@ -export type * from './dist/@types/astro.js'; +export type * from './dist/types/public/index.js'; export * from './dist/core/index.js'; diff --git a/packages/astro/src/@types/README.md b/packages/astro/src/@types/README.md deleted file mode 100644 index 397329eaf218..000000000000 --- a/packages/astro/src/@types/README.md +++ /dev/null @@ -1,5 +0,0 @@ -# `@types/` - -TypeScript definitions and types for untyped modules. - -[See CONTRIBUTING.md](../../../../CONTRIBUTING.md) for a code overview. diff --git a/packages/astro/src/@types/app.d.ts b/packages/astro/src/@types/app.d.ts deleted file mode 100644 index 1c0908bb8072..000000000000 --- a/packages/astro/src/@types/app.d.ts +++ /dev/null @@ -1,9 +0,0 @@ -/** - * Shared interfaces throughout the application that can be overridden by the user. - */ -declare namespace App { - /** - * Used by middlewares to store information, that can be read by the user via the global `Astro.locals` - */ - interface Locals {} -} diff --git a/packages/astro/src/actions/index.ts b/packages/astro/src/actions/index.ts index 2423b7017d43..61f5a00cc3ab 100644 --- a/packages/astro/src/actions/index.ts +++ b/packages/astro/src/actions/index.ts @@ -1,9 +1,10 @@ import fsMod from 'node:fs'; import type { Plugin as VitePlugin } from 'vite'; -import type { AstroIntegration, AstroSettings } from '../@types/astro.js'; import { ActionsWithoutServerOutputError } from '../core/errors/errors-data.js'; import { AstroError } from '../core/errors/errors.js'; import { isServerLikeOutput, viteID } from '../core/util.js'; +import type { AstroSettings } from '../types/astro.js'; +import type { AstroIntegration } from '../types/public/integrations.js'; import { ACTIONS_TYPES_FILE, NOOP_ACTIONS, diff --git a/packages/astro/src/actions/runtime/middleware.ts b/packages/astro/src/actions/runtime/middleware.ts index f3f01800a837..b6f3221b5700 100644 --- a/packages/astro/src/actions/runtime/middleware.ts +++ b/packages/astro/src/actions/runtime/middleware.ts @@ -1,8 +1,9 @@ import { yellow } from 'kleur/colors'; -import type { APIContext, MiddlewareNext } from '../../@types/astro.js'; import { ActionQueryStringInvalidError } from '../../core/errors/errors-data.js'; import { AstroError } from '../../core/errors/errors.js'; import { defineMiddleware } from '../../core/middleware/index.js'; +import type { MiddlewareNext } from '../../types/public/common.js'; +import type { APIContext } from '../../types/public/context.js'; import { ACTION_QUERY_PARAMS } from '../consts.js'; import { formContentTypes, hasContentType } from './utils.js'; import { getAction } from './virtual/get-action.js'; diff --git a/packages/astro/src/actions/runtime/route.ts b/packages/astro/src/actions/runtime/route.ts index e4e2ad1ce5b1..7279a093d07e 100644 --- a/packages/astro/src/actions/runtime/route.ts +++ b/packages/astro/src/actions/runtime/route.ts @@ -1,4 +1,4 @@ -import type { APIRoute } from '../../@types/astro.js'; +import type { APIRoute } from '../../types/public/common.js'; import { formContentTypes, hasContentType } from './utils.js'; import { getAction } from './virtual/get-action.js'; import { serializeActionResult } from './virtual/shared.js'; diff --git a/packages/astro/src/actions/runtime/utils.ts b/packages/astro/src/actions/runtime/utils.ts index 776171aa2ac5..199809d4e87c 100644 --- a/packages/astro/src/actions/runtime/utils.ts +++ b/packages/astro/src/actions/runtime/utils.ts @@ -1,4 +1,4 @@ -import type { APIContext } from '../../@types/astro.js'; +import type { APIContext } from '../../types/public/context.js'; export const formContentTypes = ['application/x-www-form-urlencoded', 'multipart/form-data']; diff --git a/packages/astro/src/actions/utils.ts b/packages/astro/src/actions/utils.ts index 5cf78626600f..f1cab8e430f2 100644 --- a/packages/astro/src/actions/utils.ts +++ b/packages/astro/src/actions/utils.ts @@ -1,6 +1,6 @@ -import type { APIContext } from '../@types/astro.js'; +import type { APIContext } from '../types/public/context.js'; import type { Locals } from './runtime/middleware.js'; -import { type ActionAPIContext } from './runtime/utils.js'; +import type { ActionAPIContext } from './runtime/utils.js'; import { deserializeActionResult, getActionQueryString } from './runtime/virtual/shared.js'; export function hasActionPayload(locals: APIContext['locals']): locals is Locals { diff --git a/packages/astro/src/assets/build/generate.ts b/packages/astro/src/assets/build/generate.ts index fcc19f4f53a9..1c4866592828 100644 --- a/packages/astro/src/assets/build/generate.ts +++ b/packages/astro/src/assets/build/generate.ts @@ -2,7 +2,6 @@ import fs, { readFileSync } from 'node:fs'; import { basename } from 'node:path/posix'; import { dim, green } from 'kleur/colors'; import type PQueue from 'p-queue'; -import type { AstroConfig } from '../../@types/astro.js'; import { getOutDirWithinCwd } from '../../core/build/common.js'; import type { BuildPipeline } from '../../core/build/pipeline.js'; import { getTimeStat } from '../../core/build/util.js'; @@ -12,6 +11,7 @@ import type { Logger } from '../../core/logger/core.js'; import { isRemotePath, removeLeadingForwardSlash } from '../../core/path.js'; import { isServerLikeOutput } from '../../core/util.js'; import type { MapValue } from '../../type-utils.js'; +import type { AstroConfig } from '../../types/public/config.js'; import { getConfiguredImageService } from '../internal.js'; import type { LocalImageService } from '../services/service.js'; import type { AssetsGlobalStaticImagesList, ImageMetadata, ImageTransform } from '../types.js'; diff --git a/packages/astro/src/assets/endpoint/config.ts b/packages/astro/src/assets/endpoint/config.ts index 07cfe8faecbb..ff9dcc79a807 100644 --- a/packages/astro/src/assets/endpoint/config.ts +++ b/packages/astro/src/assets/endpoint/config.ts @@ -1,4 +1,4 @@ -import type { AstroSettings } from '../../@types/astro.js'; +import type { AstroSettings } from '../../types/astro.js'; export function injectImageEndpoint(settings: AstroSettings, mode: 'dev' | 'build') { const endpointEntrypoint = diff --git a/packages/astro/src/assets/endpoint/generic.ts b/packages/astro/src/assets/endpoint/generic.ts index 5238f3721a4d..d453787fd87e 100644 --- a/packages/astro/src/assets/endpoint/generic.ts +++ b/packages/astro/src/assets/endpoint/generic.ts @@ -2,7 +2,7 @@ import { imageConfig } from 'astro:assets'; import { isRemotePath } from '@astrojs/internal-helpers/path'; import * as mime from 'mrmime'; -import type { APIRoute } from '../../@types/astro.js'; +import type { APIRoute } from '../../types/public/common.js'; import { getConfiguredImageService } from '../internal.js'; import { etag } from '../utils/etag.js'; import { isRemoteAllowed } from '../utils/remotePattern.js'; diff --git a/packages/astro/src/assets/endpoint/node.ts b/packages/astro/src/assets/endpoint/node.ts index cb3ae7806e91..04275652cde2 100644 --- a/packages/astro/src/assets/endpoint/node.ts +++ b/packages/astro/src/assets/endpoint/node.ts @@ -7,7 +7,7 @@ import { fileURLToPath, pathToFileURL } from 'node:url'; import { assetsDir, imageConfig, outDir } from 'astro:assets'; import { isRemotePath, removeQueryString } from '@astrojs/internal-helpers/path'; import * as mime from 'mrmime'; -import type { APIRoute } from '../../@types/astro.js'; +import type { APIRoute } from '../../types/public/common.js'; import { getConfiguredImageService } from '../internal.js'; import { etag } from '../utils/etag.js'; import { isRemoteAllowed } from '../utils/remotePattern.js'; diff --git a/packages/astro/src/assets/internal.ts b/packages/astro/src/assets/internal.ts index 38afbf19fc9b..9a5926e8d255 100644 --- a/packages/astro/src/assets/internal.ts +++ b/packages/astro/src/assets/internal.ts @@ -1,5 +1,5 @@ -import type { AstroConfig } from '../@types/astro.js'; import { AstroError, AstroErrorData } from '../core/errors/index.js'; +import type { AstroConfig } from '../types/public/config.js'; import { DEFAULT_HASH_PROPS } from './consts.js'; import { type ImageService, isLocalService } from './services/service.js'; import { diff --git a/packages/astro/src/assets/services/service.ts b/packages/astro/src/assets/services/service.ts index 9cd6d0ecba42..f798e1dfd142 100644 --- a/packages/astro/src/assets/services/service.ts +++ b/packages/astro/src/assets/services/service.ts @@ -1,6 +1,6 @@ -import type { AstroConfig } from '../../@types/astro.js'; import { AstroError, AstroErrorData } from '../../core/errors/index.js'; import { isRemotePath, joinPaths } from '../../core/path.js'; +import type { AstroConfig } from '../../types/public/config.js'; import { DEFAULT_HASH_PROPS, DEFAULT_OUTPUT_FORMAT, VALID_SUPPORTED_FORMATS } from '../consts.js'; import type { ImageOutputFormat, ImageTransform, UnresolvedSrcSetValue } from '../types.js'; import { isESMImportedImage } from '../utils/imageKind.js'; diff --git a/packages/astro/src/assets/utils/remotePattern.ts b/packages/astro/src/assets/utils/remotePattern.ts index 5feefb89fe73..d3e832573a7f 100644 --- a/packages/astro/src/assets/utils/remotePattern.ts +++ b/packages/astro/src/assets/utils/remotePattern.ts @@ -1,5 +1,5 @@ import { isRemotePath } from '@astrojs/internal-helpers/path'; -import type { AstroConfig } from '../../@types/astro.js'; +import type { AstroConfig } from '../../types/public/config.js'; export type RemotePattern = { hostname?: string; diff --git a/packages/astro/src/assets/vite-plugin-assets.ts b/packages/astro/src/assets/vite-plugin-assets.ts index 4c9314e85fad..57bbf847a4ff 100644 --- a/packages/astro/src/assets/vite-plugin-assets.ts +++ b/packages/astro/src/assets/vite-plugin-assets.ts @@ -2,7 +2,6 @@ import { extname } from 'node:path'; import MagicString from 'magic-string'; import type * as vite from 'vite'; import { normalizePath } from 'vite'; -import type { AstroPluginOptions, AstroSettings, ImageTransform } from '../@types/astro.js'; import { extendManualChunks } from '../core/build/plugins/util.js'; import { AstroError, AstroErrorData } from '../core/errors/index.js'; import { @@ -13,7 +12,9 @@ import { removeQueryString, } from '../core/path.js'; import { isServerLikeOutput } from '../core/util.js'; +import type { AstroPluginOptions, AstroSettings } from '../types/astro.js'; import { VALID_INPUT_FORMATS, VIRTUAL_MODULE_ID, VIRTUAL_SERVICE_ID } from './consts.js'; +import type { ImageTransform } from './types.js'; import { getAssetsPrefix } from './utils/getAssetsPrefix.js'; import { isESMImportedImage } from './utils/imageKind.js'; import { emitESMImage } from './utils/node/emitAsset.js'; diff --git a/packages/astro/src/cli/db/index.ts b/packages/astro/src/cli/db/index.ts index ae97e498f8c0..7aaea302c173 100644 --- a/packages/astro/src/cli/db/index.ts +++ b/packages/astro/src/cli/db/index.ts @@ -1,5 +1,5 @@ import type { Arguments } from 'yargs-parser'; -import type { AstroConfig } from '../../@types/astro.js'; +import type { AstroConfig } from '../../types/public/config.js'; import { resolveConfig } from '../../core/config/config.js'; import { apply as applyPolyfill } from '../../core/polyfill.js'; import { createLoggerFromFlags, flagsToAstroInlineConfig } from '../flags.js'; diff --git a/packages/astro/src/cli/flags.ts b/packages/astro/src/cli/flags.ts index 9d57c03166e3..e890b242cd08 100644 --- a/packages/astro/src/cli/flags.ts +++ b/packages/astro/src/cli/flags.ts @@ -1,7 +1,7 @@ import type { Arguments } from 'yargs-parser'; -import type { AstroInlineConfig } from '../@types/astro.js'; import { type LogOptions, Logger } from '../core/logger/core.js'; import { nodeLogDestination } from '../core/logger/node.js'; +import type { AstroInlineConfig } from '../types/public/config.js'; // Alias for now, but allows easier migration to node's `parseArgs` in the future. export type Flags = Arguments; diff --git a/packages/astro/src/cli/info/index.ts b/packages/astro/src/cli/info/index.ts index 3fa91802f26e..9f25a253516a 100644 --- a/packages/astro/src/cli/info/index.ts +++ b/packages/astro/src/cli/info/index.ts @@ -3,10 +3,10 @@ import { arch, platform } from 'node:os'; /* eslint-disable no-console */ import * as colors from 'kleur/colors'; import prompts from 'prompts'; -import type { AstroConfig, AstroUserConfig } from '../../@types/astro.js'; import { resolveConfig } from '../../core/config/index.js'; import { ASTRO_VERSION } from '../../core/constants.js'; import { apply as applyPolyfill } from '../../core/polyfill.js'; +import type { AstroConfig, AstroUserConfig } from '../../types/public/config.js'; import { type Flags, flagsToAstroInlineConfig } from '../flags.js'; interface InfoOptions { diff --git a/packages/astro/src/cli/preferences/index.ts b/packages/astro/src/cli/preferences/index.ts index 3811e7f48708..bd60343c22c5 100644 --- a/packages/astro/src/cli/preferences/index.ts +++ b/packages/astro/src/cli/preferences/index.ts @@ -1,5 +1,5 @@ /* eslint-disable no-console */ -import type { AstroSettings } from '../../@types/astro.js'; +import type { AstroSettings } from '../../types/astro.js'; import { fileURLToPath } from 'node:url'; import { bgGreen, black, bold, dim, yellow } from 'kleur/colors'; diff --git a/packages/astro/src/config/index.ts b/packages/astro/src/config/index.ts index 3c5faf2fa087..b31105ec7adc 100644 --- a/packages/astro/src/config/index.ts +++ b/packages/astro/src/config/index.ts @@ -1,6 +1,6 @@ import type { UserConfig as ViteUserConfig } from 'vite'; -import type { AstroInlineConfig, AstroUserConfig } from '../@types/astro.js'; import { Logger } from '../core/logger/core.js'; +import type { AstroInlineConfig, AstroUserConfig } from '../types/public/config.js'; export function defineConfig(config: AstroUserConfig) { return config; diff --git a/packages/astro/src/config/vite-plugin-content-listen.ts b/packages/astro/src/config/vite-plugin-content-listen.ts index 1b65c5bfbbb3..6c0408001954 100644 --- a/packages/astro/src/config/vite-plugin-content-listen.ts +++ b/packages/astro/src/config/vite-plugin-content-listen.ts @@ -1,8 +1,8 @@ import type fsMod from 'node:fs'; import type { Plugin, ViteDevServer } from 'vite'; -import type { AstroSettings } from '../@types/astro.js'; import { attachContentServerListeners } from '../content/server-listeners.js'; import type { Logger } from '../core/logger/core.js'; +import type { AstroSettings } from '../types/astro.js'; /** * Listen for Astro content directory changes and generate types. diff --git a/packages/astro/src/container/index.ts b/packages/astro/src/container/index.ts index f0c600a40623..8a8c83e07877 100644 --- a/packages/astro/src/container/index.ts +++ b/packages/astro/src/container/index.ts @@ -1,19 +1,4 @@ import { posix } from 'node:path'; -import type { - AstroConfig, - AstroUserConfig, - ComponentInstance, - ContainerImportRendererFn, - MiddlewareHandler, - NamedSSRLoadedRendererValue, - Props, - RouteData, - RouteType, - SSRLoadedRenderer, - SSRLoadedRendererValue, - SSRManifest, - SSRResult, -} from '../@types/astro.js'; import { getDefaultClientDirectives } from '../core/client-directive/index.js'; import { ASTRO_CONFIG_DEFAULTS } from '../core/config/schema.js'; import { validateConfig } from '../core/config/validate.js'; @@ -25,8 +10,32 @@ import { RenderContext } from '../core/render-context.js'; import { getParts, validateSegment } from '../core/routing/manifest/create.js'; import { getPattern } from '../core/routing/manifest/pattern.js'; import type { AstroComponentFactory } from '../runtime/server/index.js'; +import type { ComponentInstance } from '../types/astro.js'; +import type { MiddlewareHandler, Props } from '../types/public/common.js'; +import type { AstroConfig, AstroUserConfig } from '../types/public/config.js'; +import type { + NamedSSRLoadedRendererValue, + RouteData, + RouteType, + SSRLoadedRenderer, + SSRLoadedRendererValue, + SSRManifest, + SSRResult, +} from '../types/public/internal.js'; import { ContainerPipeline } from './pipeline.js'; +/** Public type, used for integrations to define a renderer for the container API */ +export type ContainerRenderer = { + /** + * The name of the renderer. + */ + name: string; + /** + * The entrypoint that is used to render a component on the server + */ + serverEntrypoint: string; +}; + /** * Options to be passed when rendering a route */ @@ -103,6 +112,10 @@ export type AddClientRenderer = { entrypoint: string; }; +type ContainerImportRendererFn = ( + containerRenderer: ContainerRenderer, +) => Promise; + function createManifest( manifest?: AstroContainerManifest, renderers?: SSRLoadedRenderer[], diff --git a/packages/astro/src/container/pipeline.ts b/packages/astro/src/container/pipeline.ts index ff2718b8fbc6..73caa4ecd9a4 100644 --- a/packages/astro/src/container/pipeline.ts +++ b/packages/astro/src/container/pipeline.ts @@ -1,10 +1,3 @@ -import type { - ComponentInstance, - RewritePayload, - RouteData, - SSRElement, - SSRResult, -} from '../@types/astro.js'; import { type HeadElements, Pipeline } from '../core/base-pipeline.js'; import type { SinglePageBuiltModule } from '../core/build/types.js'; import { @@ -12,6 +5,9 @@ import { createStylesheetElementSet, } from '../core/render/ssr-element.js'; import { findRouteToRewrite } from '../core/routing/rewrite.js'; +import type { ComponentInstance } from '../types/astro.js'; +import type { RewritePayload } from '../types/public/common.js'; +import type { RouteData, SSRElement, SSRResult } from '../types/public/internal.js'; export class ContainerPipeline extends Pipeline { /** diff --git a/packages/astro/src/content/content-layer.ts b/packages/astro/src/content/content-layer.ts index 4861f3f61aa1..c0ccf27c646e 100644 --- a/packages/astro/src/content/content-layer.ts +++ b/packages/astro/src/content/content-layer.ts @@ -3,9 +3,9 @@ import { isAbsolute } from 'node:path'; import { fileURLToPath } from 'node:url'; import type { FSWatcher } from 'vite'; import xxhash from 'xxhash-wasm'; -import type { AstroSettings } from '../@types/astro.js'; import { AstroUserError } from '../core/errors/errors.js'; import type { Logger } from '../core/logger/core.js'; +import type { AstroSettings } from '../types/astro.js'; import { ASSET_IMPORTS_FILE, CONTENT_LAYER_TYPE, diff --git a/packages/astro/src/content/loaders/glob.ts b/packages/astro/src/content/loaders/glob.ts index 4a4ecbcac8d3..27af34196ad0 100644 --- a/packages/astro/src/content/loaders/glob.ts +++ b/packages/astro/src/content/loaders/glob.ts @@ -4,7 +4,7 @@ import fastGlob from 'fast-glob'; import { bold, green } from 'kleur/colors'; import micromatch from 'micromatch'; import pLimit from 'p-limit'; -import type { ContentEntryRenderFuction, ContentEntryType } from '../../@types/astro.js'; +import type { ContentEntryRenderFunction, ContentEntryType } from '../../types/public/content.js'; import type { RenderedContent } from '../data-store.js'; import { getContentEntryIdAndSlug, getEntryConfigByExtMap, posixRelative } from '../utils.js'; import type { Loader } from './types.js'; @@ -69,7 +69,7 @@ export function glob(globOptions: GlobOptions): Loader { load: async ({ settings, logger, watcher, parseData, store, generateDigest }) => { const renderFunctionByContentType = new WeakMap< ContentEntryType, - ContentEntryRenderFuction + ContentEntryRenderFunction >(); const untouchedEntries = new Set(store.keys()); @@ -131,7 +131,7 @@ export function glob(globOptions: GlobOptions): Loader { if (entryType.getRenderFunction) { let render = renderFunctionByContentType.get(entryType); if (!render) { - render = await entryType.getRenderFunction(settings); + render = await entryType.getRenderFunction(settings.config); // Cache the render function for this content type, so it can re-use parsers and other expensive setup renderFunctionByContentType.set(entryType, render); } diff --git a/packages/astro/src/content/loaders/types.ts b/packages/astro/src/content/loaders/types.ts index 26be0495a281..5edfb5ef71fe 100644 --- a/packages/astro/src/content/loaders/types.ts +++ b/packages/astro/src/content/loaders/types.ts @@ -1,6 +1,7 @@ import type { FSWatcher } from 'vite'; import type { ZodSchema } from 'zod'; -import type { AstroIntegrationLogger, AstroSettings } from '../../@types/astro.js'; +import type { AstroIntegrationLogger } from '../../core/logger/core.js'; +import type { AstroSettings } from '../../types/astro.js'; import type { MetaStore, ScopedDataStore } from '../mutable-data-store.js'; export interface ParseDataOptions> { diff --git a/packages/astro/src/content/runtime.ts b/packages/astro/src/content/runtime.ts index b462e2e23a46..489625532950 100644 --- a/packages/astro/src/content/runtime.ts +++ b/packages/astro/src/content/runtime.ts @@ -2,7 +2,7 @@ import type { MarkdownHeading } from '@astrojs/markdown-remark'; import { Traverse } from 'neotraverse/modern'; import pLimit from 'p-limit'; import { ZodIssueCode, z } from 'zod'; -import type { GetImageResult, ImageMetadata } from '../@types/astro.js'; +import type { GetImageResult, ImageMetadata } from '../assets/types.js'; import { imageSrcToImportId } from '../assets/utils/resolveImports.js'; import { AstroError, AstroErrorData, AstroUserError } from '../core/errors/index.js'; import { prependForwardSlash } from '../core/path.js'; diff --git a/packages/astro/src/content/server-listeners.ts b/packages/astro/src/content/server-listeners.ts index 5d7868d58935..28f5b16a83e0 100644 --- a/packages/astro/src/content/server-listeners.ts +++ b/packages/astro/src/content/server-listeners.ts @@ -3,10 +3,10 @@ import path from 'node:path'; import { fileURLToPath, pathToFileURL } from 'node:url'; import { bold, cyan, underline } from 'kleur/colors'; import type { ViteDevServer } from 'vite'; -import type { AstroSettings } from '../@types/astro.js'; import { loadTSConfig } from '../core/config/tsconfig.js'; import type { Logger } from '../core/logger/core.js'; import { appendForwardSlash } from '../core/path.js'; +import type { AstroSettings } from '../types/astro.js'; import { createContentTypesGenerator } from './types-generator.js'; import { type ContentPaths, getContentPaths, globalContentConfigObserver } from './utils.js'; diff --git a/packages/astro/src/content/types-generator.ts b/packages/astro/src/content/types-generator.ts index faf02d95d915..9923a0c343d7 100644 --- a/packages/astro/src/content/types-generator.ts +++ b/packages/astro/src/content/types-generator.ts @@ -7,11 +7,12 @@ import { type ViteDevServer, normalizePath } from 'vite'; import { type ZodSchema, z } from 'zod'; import { zodToJsonSchema } from 'zod-to-json-schema'; import { printNode, zodToTs } from 'zod-to-ts'; -import type { AstroSettings, ContentEntryType } from '../@types/astro.js'; import { AstroError } from '../core/errors/errors.js'; import { AstroErrorData } from '../core/errors/index.js'; import type { Logger } from '../core/logger/core.js'; import { isRelativePath } from '../core/path.js'; +import type { AstroSettings } from '../types/astro.js'; +import type { ContentEntryType } from '../types/public/content.js'; import { CONTENT_LAYER_TYPE, CONTENT_TYPES_FILE, VIRTUAL_MODULE_ID } from './consts.js'; import { type CollectionConfig, diff --git a/packages/astro/src/content/utils.ts b/packages/astro/src/content/utils.ts index 6d06272470d0..27b0e1915f4a 100644 --- a/packages/astro/src/content/utils.ts +++ b/packages/astro/src/content/utils.ts @@ -7,15 +7,12 @@ import type { PluginContext } from 'rollup'; import { type ViteDevServer, normalizePath } from 'vite'; import xxhash from 'xxhash-wasm'; import { z } from 'zod'; -import type { - AstroConfig, - AstroSettings, - ContentEntryType, - DataEntryType, -} from '../@types/astro.js'; import { AstroError, AstroErrorData, MarkdownError, errorMap } from '../core/errors/index.js'; import { isYAMLException } from '../core/errors/utils.js'; import type { Logger } from '../core/logger/core.js'; +import type { AstroSettings } from '../types/astro.js'; +import type { AstroConfig } from '../types/public/config.js'; +import type { ContentEntryType, DataEntryType } from '../types/public/content.js'; import { CONTENT_FLAGS, CONTENT_LAYER_TYPE, diff --git a/packages/astro/src/content/vite-plugin-content-assets.ts b/packages/astro/src/content/vite-plugin-content-assets.ts index b810b8f71a4e..059cd92fa6af 100644 --- a/packages/astro/src/content/vite-plugin-content-assets.ts +++ b/packages/astro/src/content/vite-plugin-content-assets.ts @@ -1,7 +1,6 @@ import { extname } from 'node:path'; import { fileURLToPath, pathToFileURL } from 'node:url'; import type { Plugin } from 'vite'; -import type { AstroSettings, SSRElement } from '../@types/astro.js'; import { getAssetsPrefix } from '../assets/utils/getAssetsPrefix.js'; import type { BuildInternals } from '../core/build/internal.js'; import type { AstroBuildPlugin } from '../core/build/plugin.js'; @@ -9,6 +8,8 @@ import type { StaticBuildOptions } from '../core/build/types.js'; import type { ModuleLoader } from '../core/module-loader/loader.js'; import { createViteLoader } from '../core/module-loader/vite.js'; import { joinPaths, prependForwardSlash } from '../core/path.js'; +import type { AstroSettings } from '../types/astro.js'; +import type { SSRElement } from '../types/public/internal.js'; import { getStylesForURL } from '../vite-plugin-astro-server/css.js'; import { getScriptsForURL } from '../vite-plugin-astro-server/scripts.js'; import { diff --git a/packages/astro/src/content/vite-plugin-content-imports.ts b/packages/astro/src/content/vite-plugin-content-imports.ts index 5a944716c353..62f129052a8d 100644 --- a/packages/astro/src/content/vite-plugin-content-imports.ts +++ b/packages/astro/src/content/vite-plugin-content-imports.ts @@ -4,19 +4,19 @@ import { pathToFileURL } from 'node:url'; import * as devalue from 'devalue'; import type { PluginContext } from 'rollup'; import type { Plugin } from 'vite'; -import type { - AstroConfig, - AstroSettings, - ContentEntryModule, - ContentEntryType, - DataEntryModule, - DataEntryType, -} from '../@types/astro.js'; import { getProxyCode } from '../assets/utils/proxy.js'; import { AstroError } from '../core/errors/errors.js'; import { AstroErrorData } from '../core/errors/index.js'; import type { Logger } from '../core/logger/core.js'; import { isServerLikeOutput } from '../core/util.js'; +import type { AstroSettings } from '../types/astro.js'; +import type { AstroConfig } from '../types/public/config.js'; +import type { + ContentEntryModule, + ContentEntryType, + DataEntryModule, + DataEntryType, +} from '../types/public/content.js'; import { CONTENT_FLAG, DATA_FLAG } from './consts.js'; import { type ContentConfig, diff --git a/packages/astro/src/content/vite-plugin-content-virtual-mod.ts b/packages/astro/src/content/vite-plugin-content-virtual-mod.ts index 64e5d98ee410..832ca0b171ad 100644 --- a/packages/astro/src/content/vite-plugin-content-virtual-mod.ts +++ b/packages/astro/src/content/vite-plugin-content-virtual-mod.ts @@ -5,12 +5,12 @@ import { dataToEsm } from '@rollup/pluginutils'; import glob from 'fast-glob'; import pLimit from 'p-limit'; import type { Plugin } from 'vite'; -import type { AstroSettings } from '../@types/astro.js'; import { encodeName } from '../core/build/util.js'; import { AstroError, AstroErrorData } from '../core/errors/index.js'; import { appendForwardSlash, removeFileExtension } from '../core/path.js'; import { isServerLikeOutput } from '../core/util.js'; import { rootRelativePath } from '../core/viteUtils.js'; +import type { AstroSettings } from '../types/astro.js'; import type { AstroPluginMetadata } from '../vite-plugin-astro/index.js'; import { createDefaultAstroMetadata } from '../vite-plugin-astro/metadata.js'; import { diff --git a/packages/astro/src/core/app/index.ts b/packages/astro/src/core/app/index.ts index 8041dda3c6f7..3ffa5f144647 100644 --- a/packages/astro/src/core/app/index.ts +++ b/packages/astro/src/core/app/index.ts @@ -1,5 +1,6 @@ -import type { ManifestData, RouteData, SSRManifest } from '../../@types/astro.js'; import { normalizeTheLocale } from '../../i18n/index.js'; +import type { ManifestData } from '../../types/astro.js'; +import type { RouteData, SSRManifest } from '../../types/public/internal.js'; import { REROUTABLE_STATUS_CODES, REROUTE_DIRECTIVE_HEADER, diff --git a/packages/astro/src/core/app/middlewares.ts b/packages/astro/src/core/app/middlewares.ts index 095158b42ba3..a60b6baf4081 100644 --- a/packages/astro/src/core/app/middlewares.ts +++ b/packages/astro/src/core/app/middlewares.ts @@ -1,4 +1,4 @@ -import type { MiddlewareHandler } from '../../@types/astro.js'; +import type { MiddlewareHandler } from '../../types/public/common.js'; import { defineMiddleware } from '../middleware/index.js'; /** diff --git a/packages/astro/src/core/app/node.ts b/packages/astro/src/core/app/node.ts index f9afa6189d5a..86f0f5f65c46 100644 --- a/packages/astro/src/core/app/node.ts +++ b/packages/astro/src/core/app/node.ts @@ -1,6 +1,6 @@ import fs from 'node:fs'; import type { IncomingMessage, ServerResponse } from 'node:http'; -import type { RouteData } from '../../@types/astro.js'; +import type { RouteData } from '../../types/public/internal.js'; import { deserializeManifest } from './common.js'; import { createOutgoingHttpHeaders } from './createOutgoingHttpHeaders.js'; import { App } from './index.js'; diff --git a/packages/astro/src/core/app/pipeline.ts b/packages/astro/src/core/app/pipeline.ts index b784ba916464..d42472f50493 100644 --- a/packages/astro/src/core/app/pipeline.ts +++ b/packages/astro/src/core/app/pipeline.ts @@ -1,11 +1,6 @@ -import type { - ComponentInstance, - ManifestData, - RewritePayload, - RouteData, - SSRElement, - SSRResult, -} from '../../@types/astro.js'; +import type { ComponentInstance, ManifestData } from '../../types/astro.js'; +import type { RewritePayload } from '../../types/public/common.js'; +import type { RouteData, SSRElement, SSRResult } from '../../types/public/internal.js'; import { Pipeline } from '../base-pipeline.js'; import type { SinglePageBuiltModule } from '../build/types.js'; import { RedirectSinglePageBuiltModule } from '../redirects/component.js'; diff --git a/packages/astro/src/core/app/types.ts b/packages/astro/src/core/app/types.ts index 00e37dacd9ba..29cb00ed4d1f 100644 --- a/packages/astro/src/core/app/types.ts +++ b/packages/astro/src/core/app/types.ts @@ -1,14 +1,13 @@ +import type { RoutingStrategies } from '../../i18n/utils.js'; +import type { ComponentInstance, SerializedRouteData } from '../../types/astro.js'; +import type { MiddlewareHandler } from '../../types/public/common.js'; +import type { Locales } from '../../types/public/config.js'; import type { - ComponentInstance, - Locales, - MiddlewareHandler, RouteData, SSRComponentMetadata, SSRLoadedRenderer, SSRResult, - SerializedRouteData, -} from '../../@types/astro.js'; -import type { RoutingStrategies } from '../../i18n/utils.js'; +} from '../../types/public/internal.js'; import type { SinglePageBuiltModule } from '../build/types.js'; export type ComponentPath = string; @@ -82,6 +81,7 @@ export type SSRManifestI18n = { domainLookupTable: Record; }; +/** Public type exposed through the `astro:build:ssr` integration hook */ export type SerializedSSRManifest = Omit< SSRManifest, | 'middleware' diff --git a/packages/astro/src/core/base-pipeline.ts b/packages/astro/src/core/base-pipeline.ts index 01e18bfa0356..562b651744b1 100644 --- a/packages/astro/src/core/base-pipeline.ts +++ b/packages/astro/src/core/base-pipeline.ts @@ -1,15 +1,14 @@ +import { setGetEnv } from '../env/runtime.js'; +import { createI18nMiddleware } from '../i18n/middleware.js'; +import type { ComponentInstance } from '../types/astro.js'; +import type { MiddlewareHandler, RewritePayload } from '../types/public/common.js'; +import type { RuntimeMode } from '../types/public/config.js'; import type { - ComponentInstance, - MiddlewareHandler, - RewritePayload, RouteData, - RuntimeMode, SSRLoadedRenderer, SSRManifest, SSRResult, -} from '../@types/astro.js'; -import { setGetEnv } from '../env/runtime.js'; -import { createI18nMiddleware } from '../i18n/middleware.js'; +} from '../types/public/internal.js'; import { AstroError } from './errors/errors.js'; import { AstroErrorData } from './errors/index.js'; import type { Logger } from './logger/core.js'; diff --git a/packages/astro/src/core/build/common.ts b/packages/astro/src/core/build/common.ts index a479aed390dd..f9ed45836181 100644 --- a/packages/astro/src/core/build/common.ts +++ b/packages/astro/src/core/build/common.ts @@ -1,7 +1,8 @@ import npath from 'node:path'; import { fileURLToPath, pathToFileURL } from 'node:url'; -import type { AstroConfig, RouteData } from '../../@types/astro.js'; import { appendForwardSlash } from '../../core/path.js'; +import type { AstroConfig } from '../../types/public/config.js'; +import type { RouteData } from '../../types/public/internal.js'; const STATUS_CODE_PAGES = new Set(['/404', '/500']); const FALLBACK_OUT_DIR_NAME = './.astro/'; diff --git a/packages/astro/src/core/build/css-asset-name.ts b/packages/astro/src/core/build/css-asset-name.ts index fbee7f2e2008..57277c989c2a 100644 --- a/packages/astro/src/core/build/css-asset-name.ts +++ b/packages/astro/src/core/build/css-asset-name.ts @@ -4,7 +4,7 @@ import crypto from 'node:crypto'; import npath from 'node:path'; import { fileURLToPath } from 'node:url'; import { normalizePath } from 'vite'; -import type { AstroSettings } from '../../@types/astro.js'; +import type { AstroSettings } from '../../types/astro.js'; import { viteID } from '../util.js'; import { getTopLevelPageModuleInfos } from './graph.js'; diff --git a/packages/astro/src/core/build/generate.ts b/packages/astro/src/core/build/generate.ts index fae7896b9212..1f71f2d8a55d 100644 --- a/packages/astro/src/core/build/generate.ts +++ b/packages/astro/src/core/build/generate.ts @@ -2,18 +2,6 @@ import fs from 'node:fs'; import os from 'node:os'; import { bgGreen, black, blue, bold, dim, green, magenta, red } from 'kleur/colors'; import PQueue from 'p-queue'; -import type { - AstroConfig, - AstroSettings, - ComponentInstance, - GetStaticPathsItem, - MiddlewareHandler, - RouteData, - RouteType, - SSRError, - SSRLoadedRenderer, - SSRManifest, -} from '../../@types/astro.js'; import { generateImagesForPath, getStaticImageList, @@ -29,7 +17,16 @@ import { import { toRoutingStrategy } from '../../i18n/utils.js'; import { runHookBuildGenerated } from '../../integrations/hooks.js'; import { getOutputDirectory } from '../../prerender/utils.js'; -import type { SSRManifestI18n } from '../app/types.js'; +import type { AstroSettings, ComponentInstance } from '../../types/astro.js'; +import type { GetStaticPathsItem, MiddlewareHandler } from '../../types/public/common.js'; +import type { AstroConfig } from '../../types/public/config.js'; +import type { + RouteData, + RouteType, + SSRError, + SSRLoadedRenderer, +} from '../../types/public/internal.js'; +import type { SSRManifest, SSRManifestI18n } from '../app/types.js'; import { NoPrerenderedRoutesWithDomains } from '../errors/errors-data.js'; import { AstroError, AstroErrorData } from '../errors/index.js'; import { getRedirectLocationOrThrow, routeIsRedirect } from '../redirects/index.js'; diff --git a/packages/astro/src/core/build/index.ts b/packages/astro/src/core/build/index.ts index 72df05b89170..74a648304789 100644 --- a/packages/astro/src/core/build/index.ts +++ b/packages/astro/src/core/build/index.ts @@ -3,13 +3,6 @@ import { performance } from 'node:perf_hooks'; import { fileURLToPath } from 'node:url'; import { blue, bold, green } from 'kleur/colors'; import type * as vite from 'vite'; -import type { - AstroConfig, - AstroInlineConfig, - AstroSettings, - ManifestData, - RuntimeMode, -} from '../../@types/astro.js'; import { injectImageEndpoint } from '../../assets/endpoint/config.js'; import { telemetry } from '../../events/index.js'; import { eventCliSession } from '../../events/session.js'; @@ -19,6 +12,8 @@ import { runHookConfigDone, runHookConfigSetup, } from '../../integrations/hooks.js'; +import type { AstroSettings, ManifestData } from '../../types/astro.js'; +import type { AstroConfig, AstroInlineConfig, RuntimeMode } from '../../types/public/config.js'; import { resolveConfig } from '../config/config.js'; import { createNodeLogger } from '../config/logging.js'; import { createSettings } from '../config/settings.js'; diff --git a/packages/astro/src/core/build/internal.ts b/packages/astro/src/core/build/internal.ts index 5c28a4d40ed9..8c2d928244f2 100644 --- a/packages/astro/src/core/build/internal.ts +++ b/packages/astro/src/core/build/internal.ts @@ -1,5 +1,5 @@ import type { Rollup } from 'vite'; -import type { RouteData, SSRResult } from '../../@types/astro.js'; +import type { RouteData, SSRResult } from '../../types/public/internal.js'; import { prependForwardSlash, removeFileExtension } from '../path.js'; import { viteID } from '../util.js'; import { makePageDataKey } from './plugins/util.js'; diff --git a/packages/astro/src/core/build/page-data.ts b/packages/astro/src/core/build/page-data.ts index 210b31a0e56f..06ed629f2ce6 100644 --- a/packages/astro/src/core/build/page-data.ts +++ b/packages/astro/src/core/build/page-data.ts @@ -1,4 +1,4 @@ -import type { AstroSettings, ManifestData } from '../../@types/astro.js'; +import type { AstroSettings, ManifestData } from '../../types/astro.js'; import type { Logger } from '../logger/core.js'; import type { AllPagesData } from './types.js'; diff --git a/packages/astro/src/core/build/pipeline.ts b/packages/astro/src/core/build/pipeline.ts index 4e0d94c57ea6..18357e5ae62b 100644 --- a/packages/astro/src/core/build/pipeline.ts +++ b/packages/astro/src/core/build/pipeline.ts @@ -1,11 +1,7 @@ -import type { - ComponentInstance, - RewritePayload, - RouteData, - SSRLoadedRenderer, - SSRResult, -} from '../../@types/astro.js'; import { getOutputDirectory } from '../../prerender/utils.js'; +import type { ComponentInstance } from '../../types/astro.js'; +import type { RewritePayload } from '../../types/public/common.js'; +import type { RouteData, SSRLoadedRenderer, SSRResult } from '../../types/public/internal.js'; import { BEFORE_HYDRATION_SCRIPT_ID, PAGE_SCRIPT_ID } from '../../vite-plugin-scripts/index.js'; import type { SSRManifest } from '../app/types.js'; import { routeIsFallback, routeIsRedirect } from '../redirects/helpers.js'; diff --git a/packages/astro/src/core/build/plugins/plugin-content.ts b/packages/astro/src/core/build/plugins/plugin-content.ts index 9c6d5add0b8d..5fe0b6792036 100644 --- a/packages/astro/src/core/build/plugins/plugin-content.ts +++ b/packages/astro/src/core/build/plugins/plugin-content.ts @@ -4,13 +4,13 @@ import { fileURLToPath } from 'node:url'; import glob from 'fast-glob'; import pLimit from 'p-limit'; import { type Plugin as VitePlugin, normalizePath } from 'vite'; -import type { AstroConfig } from '../../../@types/astro.js'; import { CONTENT_RENDER_FLAG, PROPAGATED_ASSET_FLAG } from '../../../content/consts.js'; import { type ContentLookupMap, hasContentFlag } from '../../../content/utils.js'; import { generateContentEntryFile, generateLookupMap, } from '../../../content/vite-plugin-content-virtual-mod.js'; +import type { AstroConfig } from '../../../types/public/config.js'; import { configPaths } from '../../config/index.js'; import { emptyDir } from '../../fs/index.js'; import { diff --git a/packages/astro/src/core/build/plugins/plugin-hoisted-scripts.ts b/packages/astro/src/core/build/plugins/plugin-hoisted-scripts.ts index 7c378490938a..2992c0f2d91d 100644 --- a/packages/astro/src/core/build/plugins/plugin-hoisted-scripts.ts +++ b/packages/astro/src/core/build/plugins/plugin-hoisted-scripts.ts @@ -1,5 +1,5 @@ import type { BuildOptions, Rollup, Plugin as VitePlugin } from 'vite'; -import type { AstroSettings } from '../../../@types/astro.js'; +import type { AstroSettings } from '../../../types/astro.js'; import { viteID } from '../../util.js'; import type { BuildInternals } from '../internal.js'; import { getPageDataByViteID } from '../internal.js'; diff --git a/packages/astro/src/core/build/plugins/plugin-ssr.ts b/packages/astro/src/core/build/plugins/plugin-ssr.ts index e9eda1dc90c2..888a4d44b177 100644 --- a/packages/astro/src/core/build/plugins/plugin-ssr.ts +++ b/packages/astro/src/core/build/plugins/plugin-ssr.ts @@ -1,8 +1,9 @@ import { join } from 'node:path'; import { fileURLToPath, pathToFileURL } from 'node:url'; import type { Plugin as VitePlugin } from 'vite'; -import type { AstroAdapter, AstroSettings } from '../../../@types/astro.js'; import { isFunctionPerRouteEnabled } from '../../../integrations/hooks.js'; +import type { AstroSettings } from '../../../types/astro.js'; +import type { AstroAdapter } from '../../../types/public/integrations.js'; import { routeIsRedirect } from '../../redirects/index.js'; import { VIRTUAL_ISLAND_MAP_ID } from '../../server-islands/vite-plugin-server-islands.js'; import { isServerLikeOutput } from '../../util.js'; diff --git a/packages/astro/src/core/build/static-build.ts b/packages/astro/src/core/build/static-build.ts index 7e2272dde60e..96feb85420df 100644 --- a/packages/astro/src/core/build/static-build.ts +++ b/packages/astro/src/core/build/static-build.ts @@ -5,7 +5,6 @@ import { teardown } from '@astrojs/compiler'; import glob from 'fast-glob'; import { bgGreen, bgMagenta, black, green } from 'kleur/colors'; import * as vite from 'vite'; -import type { RouteData } from '../../@types/astro.js'; import { PROPAGATED_ASSET_FLAG } from '../../content/consts.js'; import { getSymlinkedContentCollections, @@ -22,6 +21,7 @@ import { appendForwardSlash, prependForwardSlash, removeFileExtension } from '.. import { isModeServerWithNoAdapter, isServerLikeOutput } from '../../core/util.js'; import { runHookBuildSetup } from '../../integrations/hooks.js'; import { getOutputDirectory } from '../../prerender/utils.js'; +import type { RouteData } from '../../types/public/internal.js'; import { PAGE_SCRIPT_ID } from '../../vite-plugin-scripts/index.js'; import { AstroError, AstroErrorData } from '../errors/index.js'; import type { Logger } from '../logger/core.js'; diff --git a/packages/astro/src/core/build/types.ts b/packages/astro/src/core/build/types.ts index 572140ef6669..f06f42501cf1 100644 --- a/packages/astro/src/core/build/types.ts +++ b/packages/astro/src/core/build/types.ts @@ -1,14 +1,9 @@ import type * as vite from 'vite'; import type { InlineConfig } from 'vite'; -import type { - AstroSettings, - ComponentInstance, - ManifestData, - MiddlewareHandler, - RouteData, - RuntimeMode, - SSRLoadedRenderer, -} from '../../@types/astro.js'; +import type { AstroSettings, ComponentInstance, ManifestData } from '../../types/astro.js'; +import type { MiddlewareHandler } from '../../types/public/common.js'; +import type { RuntimeMode } from '../../types/public/config.js'; +import type { RouteData, SSRLoadedRenderer } from '../../types/public/internal.js'; import type { Logger } from '../logger/core.js'; export type ComponentPath = string; @@ -20,6 +15,7 @@ export type StylesheetAsset = export type HoistedScriptAsset = { type: 'inline' | 'external'; value: string }; +/** Public type exposed through the `astro:build:setup` integration hook */ export interface PageBuildData { key: string; component: ComponentPath; diff --git a/packages/astro/src/core/build/util.ts b/packages/astro/src/core/build/util.ts index 9dc61f06fd8d..b6b313254379 100644 --- a/packages/astro/src/core/build/util.ts +++ b/packages/astro/src/core/build/util.ts @@ -1,5 +1,5 @@ import type { Rollup } from 'vite'; -import type { AstroConfig } from '../../@types/astro.js'; +import type { AstroConfig } from '../../types/public/config.js'; import type { ViteBuildReturn } from './types.js'; export function getTimeStat(timeStart: number, timeEnd: number) { diff --git a/packages/astro/src/core/compile/compile.ts b/packages/astro/src/core/compile/compile.ts index c3e6e4bb87a8..6e49f5850c63 100644 --- a/packages/astro/src/core/compile/compile.ts +++ b/packages/astro/src/core/compile/compile.ts @@ -1,11 +1,11 @@ import type { TransformResult } from '@astrojs/compiler'; import type { ResolvedConfig } from 'vite'; -import type { AstroConfig } from '../../@types/astro.js'; import { fileURLToPath } from 'node:url'; import { transform } from '@astrojs/compiler'; import { normalizePath } from 'vite'; import type { AstroPreferences } from '../../preferences/index.js'; +import type { AstroConfig } from '../../types/public/config.js'; import type { AstroError } from '../errors/errors.js'; import { AggregateError, CompilerError } from '../errors/errors.js'; import { AstroErrorData } from '../errors/index.js'; diff --git a/packages/astro/src/core/config/config.ts b/packages/astro/src/core/config/config.ts index c10066ce3273..3e19db8015f8 100644 --- a/packages/astro/src/core/config/config.ts +++ b/packages/astro/src/core/config/config.ts @@ -3,13 +3,13 @@ import path from 'node:path'; import { fileURLToPath } from 'node:url'; import * as colors from 'kleur/colors'; import { ZodError } from 'zod'; +import { eventConfigError, telemetry } from '../../events/index.js'; import type { AstroConfig, AstroInlineConfig, AstroInlineOnlyConfig, AstroUserConfig, -} from '../../@types/astro.js'; -import { eventConfigError, telemetry } from '../../events/index.js'; +} from '../../types/public/config.js'; import { trackAstroConfigZodError } from '../errors/errors.js'; import { AstroError, AstroErrorData } from '../errors/index.js'; import { formatConfigErrorMessage } from '../messages.js'; diff --git a/packages/astro/src/core/config/logging.ts b/packages/astro/src/core/config/logging.ts index 004283f85f0c..bd72f8b5e978 100644 --- a/packages/astro/src/core/config/logging.ts +++ b/packages/astro/src/core/config/logging.ts @@ -1,4 +1,4 @@ -import type { AstroInlineConfig } from '../../@types/astro.js'; +import type { AstroInlineConfig } from '../../types/public/config.js'; import { Logger } from '../logger/core.js'; import { nodeLogDestination } from '../logger/node.js'; diff --git a/packages/astro/src/core/config/schema.ts b/packages/astro/src/core/config/schema.ts index f49b4708e714..9db1117180b8 100644 --- a/packages/astro/src/core/config/schema.ts +++ b/packages/astro/src/core/config/schema.ts @@ -6,13 +6,13 @@ import type { } from '@astrojs/markdown-remark'; import { markdownConfigDefaults } from '@astrojs/markdown-remark'; import { type BuiltinTheme, bundledThemes } from 'shiki'; -import type { AstroUserConfig, ViteUserConfig } from '../../@types/astro.js'; import type { OutgoingHttpHeaders } from 'node:http'; import path from 'node:path'; import { pathToFileURL } from 'node:url'; import { z } from 'zod'; import { EnvSchema } from '../../env/schema.js'; +import type { AstroUserConfig, ViteUserConfig } from '../../types/public/config.js'; import { appendForwardSlash, prependForwardSlash, removeTrailingForwardSlash } from '../path.js'; // The below types are required boilerplate to workaround a Zod issue since v3.21.2. Since that version, diff --git a/packages/astro/src/core/config/settings.ts b/packages/astro/src/core/config/settings.ts index 6c878d7f3323..902ff7d03318 100644 --- a/packages/astro/src/core/config/settings.ts +++ b/packages/astro/src/core/config/settings.ts @@ -1,9 +1,10 @@ import path from 'node:path'; import { fileURLToPath, pathToFileURL } from 'node:url'; import yaml from 'js-yaml'; -import type { AstroConfig, AstroSettings } from '../../@types/astro.js'; import { getContentPaths } from '../../content/index.js'; import createPreferences from '../../preferences/index.js'; +import type { AstroSettings } from '../../types/astro.js'; +import type { AstroConfig } from '../../types/public/config.js'; import { markdownContentEntryType } from '../../vite-plugin-markdown/content-entry-type.js'; import { getDefaultClientDirectives } from '../client-directive/index.js'; import { AstroError, AstroErrorData } from '../errors/index.js'; diff --git a/packages/astro/src/core/config/validate.ts b/packages/astro/src/core/config/validate.ts index 4f4497b784d8..75a64f1f7d17 100644 --- a/packages/astro/src/core/config/validate.ts +++ b/packages/astro/src/core/config/validate.ts @@ -1,4 +1,4 @@ -import type { AstroConfig } from '../../@types/astro.js'; +import type { AstroConfig } from '../../types/public/config.js'; import { createRelativeSchema } from './schema.js'; /** Turn raw config values into normalized values */ diff --git a/packages/astro/src/core/create-vite.ts b/packages/astro/src/core/create-vite.ts index 23a4068a8bda..f2931523a6ed 100644 --- a/packages/astro/src/core/create-vite.ts +++ b/packages/astro/src/core/create-vite.ts @@ -3,7 +3,6 @@ import { fileURLToPath } from 'node:url'; import glob from 'fast-glob'; import * as vite from 'vite'; import { crawlFrameworkPkgs } from 'vitefu'; -import type { AstroSettings } from '../@types/astro.js'; import { getAssetsPrefix } from '../assets/utils/getAssetsPrefix.js'; import astroAssetsPlugin from '../assets/vite-plugin-assets.js'; import astroContainer from '../container/vite-plugin-container.js'; @@ -17,6 +16,7 @@ import astroInternationalization from '../i18n/vite-plugin-i18n.js'; import astroPrefetch from '../prefetch/vite-plugin-prefetch.js'; import astroDevToolbar from '../toolbar/vite-plugin-dev-toolbar.js'; import astroTransitions from '../transitions/vite-plugin-transitions.js'; +import type { AstroSettings } from '../types/astro.js'; import astroPostprocessVitePlugin from '../vite-plugin-astro-postprocess/index.js'; import { vitePluginAstroServer } from '../vite-plugin-astro-server/index.js'; import astroVitePlugin from '../vite-plugin-astro/index.js'; @@ -185,7 +185,7 @@ export async function createVite( { // Typings are imported from 'astro' (e.g. import { Type } from 'astro') find: /^astro$/, - replacement: fileURLToPath(new URL('../@types/astro.js', import.meta.url)), + replacement: fileURLToPath(new URL('../types/public/index.js', import.meta.url)), }, { find: 'astro:middleware', diff --git a/packages/astro/src/core/dev/container.ts b/packages/astro/src/core/dev/container.ts index 159d5e44769c..f89e331970c5 100644 --- a/packages/astro/src/core/dev/container.ts +++ b/packages/astro/src/core/dev/container.ts @@ -1,6 +1,6 @@ import type * as http from 'node:http'; import type { AddressInfo } from 'node:net'; -import type { AstroInlineConfig, AstroSettings } from '../../@types/astro.js'; +import type { AstroSettings } from '../../types/astro.js'; import nodeFs from 'node:fs'; import * as vite from 'vite'; @@ -11,6 +11,7 @@ import { runHookServerDone, runHookServerStart, } from '../../integrations/hooks.js'; +import type { AstroInlineConfig } from '../../types/public/config.js'; import { createVite } from '../create-vite.js'; import type { Logger } from '../logger/core.js'; import { apply as applyPolyfill } from '../polyfill.js'; diff --git a/packages/astro/src/core/dev/dev.ts b/packages/astro/src/core/dev/dev.ts index 12b6d3b55aab..73ec0fa713e2 100644 --- a/packages/astro/src/core/dev/dev.ts +++ b/packages/astro/src/core/dev/dev.ts @@ -5,13 +5,13 @@ import { performance } from 'node:perf_hooks'; import { green } from 'kleur/colors'; import { gt, major, minor, patch } from 'semver'; import type * as vite from 'vite'; -import type { AstroInlineConfig } from '../../@types/astro.js'; import { DATA_STORE_FILE } from '../../content/consts.js'; import { globalContentLayer } from '../../content/content-layer.js'; import { attachContentServerListeners } from '../../content/index.js'; import { MutableDataStore } from '../../content/mutable-data-store.js'; import { globalContentConfigObserver } from '../../content/utils.js'; import { telemetry } from '../../events/index.js'; +import type { AstroInlineConfig } from '../../types/public/config.js'; import * as msg from '../messages.js'; import { ensureProcessNodeEnv } from '../util.js'; import { startContainer } from './container.js'; diff --git a/packages/astro/src/core/dev/restart.ts b/packages/astro/src/core/dev/restart.ts index ee0ba995c446..8fb6e46a300c 100644 --- a/packages/astro/src/core/dev/restart.ts +++ b/packages/astro/src/core/dev/restart.ts @@ -1,9 +1,10 @@ import type nodeFs from 'node:fs'; import { fileURLToPath } from 'node:url'; import * as vite from 'vite'; -import type { AstroInlineConfig, AstroSettings } from '../../@types/astro.js'; import { globalContentLayer } from '../../content/content-layer.js'; import { eventCliSession, telemetry } from '../../events/index.js'; +import type { AstroSettings } from '../../types/astro.js'; +import type { AstroInlineConfig } from '../../types/public/config.js'; import { createNodeLogger, createSettings, resolveConfig } from '../config/index.js'; import { collectErrorMetadata } from '../errors/dev/utils.js'; import { isAstroConfigZodError } from '../errors/errors.js'; diff --git a/packages/astro/src/core/errors/dev/utils.ts b/packages/astro/src/core/errors/dev/utils.ts index 341c815a6762..c082a81937de 100644 --- a/packages/astro/src/core/errors/dev/utils.ts +++ b/packages/astro/src/core/errors/dev/utils.ts @@ -6,7 +6,7 @@ import { bold, underline } from 'kleur/colors'; import stripAnsi from 'strip-ansi'; import type { ESBuildTransformResult } from 'vite'; import { normalizePath } from 'vite'; -import type { SSRError } from '../../../@types/astro.js'; +import type { SSRError } from '../../../types/public/internal.js'; import { removeLeadingForwardSlashWindows } from '../../path.js'; import { AggregateError, type ErrorWithMetadata } from '../errors.js'; import { AstroErrorData } from '../index.js'; diff --git a/packages/astro/src/core/errors/dev/vite.ts b/packages/astro/src/core/errors/dev/vite.ts index 56688877a861..c944ad78d686 100644 --- a/packages/astro/src/core/errors/dev/vite.ts +++ b/packages/astro/src/core/errors/dev/vite.ts @@ -3,11 +3,11 @@ import { fileURLToPath } from 'node:url'; import { codeToHtml, createCssVariablesTheme } from 'shiki'; import type { ShikiTransformer } from 'shiki'; import type { ErrorPayload } from 'vite'; +import type { SSRLoadedRenderer } from '../../../types/public/internal.js'; import type { ModuleLoader } from '../../module-loader/index.js'; import { FailedToLoadModuleSSR, InvalidGlob, MdxIntegrationMissingError } from '../errors-data.js'; import { AstroError, type ErrorWithMetadata } from '../errors.js'; import { createSafeError } from '../utils.js'; -import type { SSRLoadedRenderer } from './../../../@types/astro.js'; import { getDocsForError, renderErrorMarkdown } from './utils.js'; export function enhanceViteSSRError({ diff --git a/packages/astro/src/core/errors/errors-data.ts b/packages/astro/src/core/errors/errors-data.ts index 24b9ad687aea..e083ba2f54ae 100644 --- a/packages/astro/src/core/errors/errors-data.ts +++ b/packages/astro/src/core/errors/errors-data.ts @@ -1,5 +1,5 @@ // BEFORE ADDING AN ERROR: Please look at the README.md in this folder for general guidelines on writing error messages -// Additionally, this code, much like `@types/astro.ts`, is used to generate documentation, so make sure to pass +// Additionally, this code, much like `types/public/config.ts`, is used to generate documentation, so make sure to pass // your changes by our wonderful docs team before merging! import type { ZodError } from 'zod'; diff --git a/packages/astro/src/core/errors/utils.ts b/packages/astro/src/core/errors/utils.ts index 05dd49071a48..6754656b9134 100644 --- a/packages/astro/src/core/errors/utils.ts +++ b/packages/astro/src/core/errors/utils.ts @@ -1,6 +1,6 @@ import type { YAMLException } from 'js-yaml'; import type { ErrorPayload as ViteErrorPayload } from 'vite'; -import type { SSRError } from '../../@types/astro.js'; +import type { SSRError } from '../../types/public/internal.js'; /** * Get the line and character based on the offset diff --git a/packages/astro/src/core/index.ts b/packages/astro/src/core/index.ts index bdd7c7f05939..14a8c2f99af0 100644 --- a/packages/astro/src/core/index.ts +++ b/packages/astro/src/core/index.ts @@ -1,6 +1,6 @@ // This is the main entrypoint when importing the `astro` package. -import type { AstroInlineConfig } from '../@types/astro.js'; +import type { AstroInlineConfig } from '../types/public/config.js'; import { default as _build } from './build/index.js'; import { default as _sync } from './sync/index.js'; diff --git a/packages/astro/src/core/middleware/callMiddleware.ts b/packages/astro/src/core/middleware/callMiddleware.ts index 3bdc6052da99..4cc7b6586685 100644 --- a/packages/astro/src/core/middleware/callMiddleware.ts +++ b/packages/astro/src/core/middleware/callMiddleware.ts @@ -1,9 +1,9 @@ import type { - APIContext, MiddlewareHandler, MiddlewareNext, RewritePayload, -} from '../../@types/astro.js'; +} from '../../types/public/common.js'; +import type { APIContext } from '../../types/public/context.js'; import { AstroError, AstroErrorData } from '../errors/index.js'; /** diff --git a/packages/astro/src/core/middleware/index.ts b/packages/astro/src/core/middleware/index.ts index 56ce0b76c364..31988ae02eac 100644 --- a/packages/astro/src/core/middleware/index.ts +++ b/packages/astro/src/core/middleware/index.ts @@ -1,10 +1,11 @@ -import type { APIContext, MiddlewareHandler, Params, RewritePayload } from '../../@types/astro.js'; import { createCallAction, createGetActionResult } from '../../actions/utils.js'; import { computeCurrentLocale, computePreferredLocale, computePreferredLocaleList, } from '../../i18n/utils.js'; +import type { MiddlewareHandler, Params, RewritePayload } from '../../types/public/common.js'; +import type { APIContext } from '../../types/public/context.js'; import { ASTRO_VERSION, clientAddressSymbol, clientLocalsSymbol } from '../constants.js'; import { AstroCookies } from '../cookies/index.js'; import { AstroError, AstroErrorData } from '../errors/index.js'; diff --git a/packages/astro/src/core/middleware/sequence.ts b/packages/astro/src/core/middleware/sequence.ts index ee08381e6fe4..aefa66a9205d 100644 --- a/packages/astro/src/core/middleware/sequence.ts +++ b/packages/astro/src/core/middleware/sequence.ts @@ -1,4 +1,5 @@ -import type { APIContext, MiddlewareHandler, RewritePayload } from '../../@types/astro.js'; +import type { MiddlewareHandler, RewritePayload } from '../../types/public/common.js'; +import type { APIContext } from '../../types/public/context.js'; import { AstroCookies } from '../cookies/cookies.js'; import { defineMiddleware } from './index.js'; diff --git a/packages/astro/src/core/middleware/vite-plugin.ts b/packages/astro/src/core/middleware/vite-plugin.ts index bb7b54e727d3..8a76bed921c9 100644 --- a/packages/astro/src/core/middleware/vite-plugin.ts +++ b/packages/astro/src/core/middleware/vite-plugin.ts @@ -1,7 +1,7 @@ import type { Plugin as VitePlugin } from 'vite'; import { normalizePath } from 'vite'; -import type { AstroSettings } from '../../@types/astro.js'; import { getOutputDirectory } from '../../prerender/utils.js'; +import type { AstroSettings } from '../../types/astro.js'; import { addRollupInput } from '../build/add-rollup-input.js'; import type { BuildInternals } from '../build/internal.js'; import type { StaticBuildOptions } from '../build/types.js'; diff --git a/packages/astro/src/core/module-loader/loader.ts b/packages/astro/src/core/module-loader/loader.ts index 976354448acc..9973ae6577e8 100644 --- a/packages/astro/src/core/module-loader/loader.ts +++ b/packages/astro/src/core/module-loader/loader.ts @@ -1,6 +1,6 @@ import { EventEmitter } from 'node:events'; import type * as fs from 'node:fs'; -import type { TypedEventEmitter } from '../../@types/typed-emitter.js'; +import type { TypedEventEmitter } from '../../types/typed-emitter.js'; // This is a generic interface for a module loader. In the astro cli this is // fulfilled by Vite, see vite.ts diff --git a/packages/astro/src/core/preview/index.ts b/packages/astro/src/core/preview/index.ts index b46cf1becc57..a8a533fe85b7 100644 --- a/packages/astro/src/core/preview/index.ts +++ b/packages/astro/src/core/preview/index.ts @@ -1,11 +1,12 @@ import fs from 'node:fs'; import { createRequire } from 'node:module'; import { fileURLToPath, pathToFileURL } from 'node:url'; -import type { AstroInlineConfig, PreviewModule, PreviewServer } from '../../@types/astro.js'; import { AstroIntegrationLogger } from '../../core/logger/core.js'; import { telemetry } from '../../events/index.js'; import { eventCliSession } from '../../events/session.js'; import { runHookConfigDone, runHookConfigSetup } from '../../integrations/hooks.js'; +import type { AstroInlineConfig } from '../../types/public/config.js'; +import type { PreviewModule, PreviewServer } from '../../types/public/preview.js'; import { resolveConfig } from '../config/config.js'; import { createNodeLogger } from '../config/logging.js'; import { createSettings } from '../config/settings.js'; diff --git a/packages/astro/src/core/preview/static-preview-server.ts b/packages/astro/src/core/preview/static-preview-server.ts index 0afa34b6042e..855506ef91ce 100644 --- a/packages/astro/src/core/preview/static-preview-server.ts +++ b/packages/astro/src/core/preview/static-preview-server.ts @@ -2,7 +2,7 @@ import type http from 'node:http'; import { performance } from 'node:perf_hooks'; import { fileURLToPath } from 'node:url'; import { type PreviewServer as VitePreviewServer, preview } from 'vite'; -import type { AstroSettings } from '../../@types/astro.js'; +import type { AstroSettings } from '../../types/astro.js'; import type { Logger } from '../logger/core.js'; import * as msg from '../messages.js'; import { getResolvedHostForHttpServer } from './util.js'; diff --git a/packages/astro/src/core/preview/vite-plugin-astro-preview.ts b/packages/astro/src/core/preview/vite-plugin-astro-preview.ts index a425807dccd2..fd9bbae66c57 100644 --- a/packages/astro/src/core/preview/vite-plugin-astro-preview.ts +++ b/packages/astro/src/core/preview/vite-plugin-astro-preview.ts @@ -2,8 +2,8 @@ import fs from 'node:fs'; import type { IncomingMessage, ServerResponse } from 'node:http'; import { fileURLToPath } from 'node:url'; import type { Connect, Plugin } from 'vite'; -import type { AstroSettings } from '../../@types/astro.js'; import { notFoundTemplate, subpathNotUsedTemplate } from '../../template/4xx.js'; +import type { AstroSettings } from '../../types/astro.js'; import { cleanUrl } from '../../vite-plugin-utils/index.js'; import { stripBase } from './util.js'; diff --git a/packages/astro/src/core/redirects/component.ts b/packages/astro/src/core/redirects/component.ts index 00b8d176c1d2..12b37ae0091b 100644 --- a/packages/astro/src/core/redirects/component.ts +++ b/packages/astro/src/core/redirects/component.ts @@ -1,4 +1,4 @@ -import type { ComponentInstance } from '../../@types/astro.js'; +import type { ComponentInstance } from '../../types/astro.js'; import type { SinglePageBuiltModule } from '../build/types.js'; // A stub of a component instance for a given route diff --git a/packages/astro/src/core/redirects/helpers.ts b/packages/astro/src/core/redirects/helpers.ts index 80f18ae0f123..a2dc42df96e5 100644 --- a/packages/astro/src/core/redirects/helpers.ts +++ b/packages/astro/src/core/redirects/helpers.ts @@ -1,4 +1,8 @@ -import type { RedirectRouteData, RouteData } from '../../@types/astro.js'; +import type { RouteData } from '../../types/public/internal.js'; + +type RedirectRouteData = RouteData & { + redirect: string; +}; export function routeIsRedirect(route: RouteData | undefined): route is RedirectRouteData { return route?.type === 'redirect'; diff --git a/packages/astro/src/core/render-context.ts b/packages/astro/src/core/render-context.ts index a19d11080a97..ab0554d0c03d 100644 --- a/packages/astro/src/core/render-context.ts +++ b/packages/astro/src/core/render-context.ts @@ -1,14 +1,3 @@ -import type { - APIContext, - AstroGlobal, - AstroGlobalPartial, - ComponentInstance, - MiddlewareHandler, - Props, - RewritePayload, - RouteData, - SSRResult, -} from '../@types/astro.js'; import type { ActionAPIContext } from '../actions/runtime/utils.js'; import { deserializeActionResult } from '../actions/runtime/virtual/shared.js'; import { createCallAction, createGetActionResult, hasActionPayload } from '../actions/utils.js'; @@ -19,6 +8,10 @@ import { } from '../i18n/utils.js'; import { renderEndpoint } from '../runtime/server/endpoint.js'; import { renderPage } from '../runtime/server/index.js'; +import type { ComponentInstance } from '../types/astro.js'; +import type { MiddlewareHandler, Props, RewritePayload } from '../types/public/common.js'; +import type { APIContext, AstroGlobal, AstroGlobalPartial } from '../types/public/context.js'; +import type { RouteData, SSRResult } from '../types/public/internal.js'; import { ASTRO_VERSION, REROUTE_DIRECTIVE_HEADER, diff --git a/packages/astro/src/core/render/index.ts b/packages/astro/src/core/render/index.ts index db14701b0fde..b56a2eaf2cc0 100644 --- a/packages/astro/src/core/render/index.ts +++ b/packages/astro/src/core/render/index.ts @@ -1,4 +1,5 @@ -import type { ComponentInstance, RouteData } from '../../@types/astro.js'; +import type { ComponentInstance } from '../../types/astro.js'; +import type { RouteData } from '../../types/public/internal.js'; import type { Pipeline } from '../base-pipeline.js'; export { Pipeline } from '../base-pipeline.js'; export { getParams, getProps } from './params-and-props.js'; diff --git a/packages/astro/src/core/render/paginate.ts b/packages/astro/src/core/render/paginate.ts index e962d98d31f4..c462cd4b8646 100644 --- a/packages/astro/src/core/render/paginate.ts +++ b/packages/astro/src/core/render/paginate.ts @@ -4,8 +4,8 @@ import type { PaginateOptions, Params, Props, - RouteData, -} from '../../@types/astro.js'; +} from '../../types/public/common.js'; +import type { RouteData } from '../../types/public/internal.js'; import { AstroError, AstroErrorData } from '../errors/index.js'; export function generatePaginateFunction( diff --git a/packages/astro/src/core/render/params-and-props.ts b/packages/astro/src/core/render/params-and-props.ts index cf7d02d48360..a45fb16a8084 100644 --- a/packages/astro/src/core/render/params-and-props.ts +++ b/packages/astro/src/core/render/params-and-props.ts @@ -1,4 +1,6 @@ -import type { ComponentInstance, Params, Props, RouteData } from '../../@types/astro.js'; +import type { ComponentInstance } from '../../types/astro.js'; +import type { Params, Props } from '../../types/public/common.js'; +import type { RouteData } from '../../types/public/internal.js'; import { DEFAULT_404_COMPONENT } from '../constants.js'; import { AstroError, AstroErrorData } from '../errors/index.js'; import type { Logger } from '../logger/core.js'; diff --git a/packages/astro/src/core/render/renderer.ts b/packages/astro/src/core/render/renderer.ts index 42cc8fd05d64..8daec8d53e5f 100644 --- a/packages/astro/src/core/render/renderer.ts +++ b/packages/astro/src/core/render/renderer.ts @@ -1,4 +1,5 @@ -import type { AstroRenderer, SSRLoadedRenderer } from '../../@types/astro.js'; +import type { AstroRenderer } from '../../types/public/integrations.js'; +import type { SSRLoadedRenderer } from '../../types/public/internal.js'; import type { ModuleLoader } from '../module-loader/index.js'; export async function loadRenderer( diff --git a/packages/astro/src/core/render/route-cache.ts b/packages/astro/src/core/render/route-cache.ts index 399795675e06..3329c42cd347 100644 --- a/packages/astro/src/core/render/route-cache.ts +++ b/packages/astro/src/core/render/route-cache.ts @@ -1,13 +1,13 @@ +import type { ComponentInstance } from '../../types/astro.js'; import type { - ComponentInstance, GetStaticPathsItem, GetStaticPathsResult, GetStaticPathsResultKeyed, PaginateFunction, Params, - RouteData, - RuntimeMode, -} from '../../@types/astro.js'; +} from '../../types/public/common.js'; +import type { RuntimeMode } from '../../types/public/config.js'; +import type { RouteData } from '../../types/public/internal.js'; import type { Logger } from '../logger/core.js'; import { stringifyParams } from '../routing/params.js'; diff --git a/packages/astro/src/core/render/slots.ts b/packages/astro/src/core/render/slots.ts index ab87204e465e..1c767083da71 100644 --- a/packages/astro/src/core/render/slots.ts +++ b/packages/astro/src/core/render/slots.ts @@ -1,8 +1,8 @@ -import type { SSRResult } from '../../@types/astro.js'; import { type ComponentSlots, renderSlotToString } from '../../runtime/server/index.js'; import { renderJSX } from '../../runtime/server/jsx.js'; import { chunkToString } from '../../runtime/server/render/index.js'; import { isRenderInstruction } from '../../runtime/server/render/instruction.js'; +import type { SSRResult } from '../../types/public/internal.js'; import { AstroError, AstroErrorData } from '../errors/index.js'; import type { Logger } from '../logger/core.js'; diff --git a/packages/astro/src/core/render/ssr-element.ts b/packages/astro/src/core/render/ssr-element.ts index 7c766ee20e4a..827c8fddf40d 100644 --- a/packages/astro/src/core/render/ssr-element.ts +++ b/packages/astro/src/core/render/ssr-element.ts @@ -1,7 +1,7 @@ -import type { AssetsPrefix, SSRElement } from '../../@types/astro.js'; import { getAssetsPrefix } from '../../assets/utils/getAssetsPrefix.js'; import { fileExtension, joinPaths, prependForwardSlash, slash } from '../../core/path.js'; -import type { StylesheetAsset } from '../app/types.js'; +import type { SSRElement } from '../../types/public/internal.js'; +import type { AssetsPrefix, StylesheetAsset } from '../app/types.js'; export function createAssetLink(href: string, base?: string, assetsPrefix?: AssetsPrefix): string { if (assetsPrefix) { diff --git a/packages/astro/src/core/routing/astro-designed-error-pages.ts b/packages/astro/src/core/routing/astro-designed-error-pages.ts index 4e4b41b70cf7..2c1c1f77c5a3 100644 --- a/packages/astro/src/core/routing/astro-designed-error-pages.ts +++ b/packages/astro/src/core/routing/astro-designed-error-pages.ts @@ -1,5 +1,6 @@ -import type { ComponentInstance, ManifestData, RouteData } from '../../@types/astro.js'; import notFoundTemplate from '../../template/4xx.js'; +import type { ComponentInstance, ManifestData } from '../../types/astro.js'; +import type { RouteData } from '../../types/public/internal.js'; import { DEFAULT_404_COMPONENT, DEFAULT_500_COMPONENT } from '../constants.js'; export const DEFAULT_404_ROUTE: RouteData = { diff --git a/packages/astro/src/core/routing/default.ts b/packages/astro/src/core/routing/default.ts index dd3c8cc538c1..8bcd473d0081 100644 --- a/packages/astro/src/core/routing/default.ts +++ b/packages/astro/src/core/routing/default.ts @@ -1,4 +1,5 @@ -import type { ComponentInstance, ManifestData, SSRManifest } from '../../@types/astro.js'; +import type { ComponentInstance, ManifestData } from '../../types/astro.js'; +import type { SSRManifest } from '../app/types.js'; import { DEFAULT_404_COMPONENT } from '../constants.js'; import { SERVER_ISLAND_COMPONENT, diff --git a/packages/astro/src/core/routing/manifest/create.ts b/packages/astro/src/core/routing/manifest/create.ts index df548ec8248d..14980f63e5ad 100644 --- a/packages/astro/src/core/routing/manifest/create.ts +++ b/packages/astro/src/core/routing/manifest/create.ts @@ -1,11 +1,4 @@ -import type { - AstroConfig, - AstroSettings, - ManifestData, - RouteData, - RoutePart, - RoutePriorityOverride, -} from '../../../@types/astro.js'; +import type { AstroSettings, ManifestData } from '../../../types/astro.js'; import type { Logger } from '../../logger/core.js'; import nodeFs from 'node:fs'; @@ -15,6 +8,9 @@ import { fileURLToPath } from 'node:url'; import { bold } from 'kleur/colors'; import { toRoutingStrategy } from '../../../i18n/utils.js'; import { getPrerenderDefault } from '../../../prerender/utils.js'; +import type { AstroConfig } from '../../../types/public/config.js'; +import type { RoutePriorityOverride } from '../../../types/public/integrations.js'; +import type { RouteData, RoutePart } from '../../../types/public/internal.js'; import { SUPPORTED_MARKDOWN_FILE_EXTENSIONS } from '../../constants.js'; import { MissingIndexForInternationalization } from '../../errors/errors-data.js'; import { AstroError } from '../../errors/index.js'; diff --git a/packages/astro/src/core/routing/manifest/generator.ts b/packages/astro/src/core/routing/manifest/generator.ts index 4ab635ec6608..e3565864d91d 100644 --- a/packages/astro/src/core/routing/manifest/generator.ts +++ b/packages/astro/src/core/routing/manifest/generator.ts @@ -1,6 +1,6 @@ -import type { AstroConfig, RoutePart } from '../../../@types/astro.js'; - import { compile } from 'path-to-regexp'; +import type { AstroConfig } from '../../../types/public/config.js'; +import type { RoutePart } from '../../../types/public/internal.js'; /** * Sanitizes the parameters object by normalizing string values and replacing certain characters with their URL-encoded equivalents. diff --git a/packages/astro/src/core/routing/manifest/pattern.ts b/packages/astro/src/core/routing/manifest/pattern.ts index 65f223aa0c20..8a9a9d27f9fc 100644 --- a/packages/astro/src/core/routing/manifest/pattern.ts +++ b/packages/astro/src/core/routing/manifest/pattern.ts @@ -1,4 +1,5 @@ -import type { AstroConfig, RoutePart } from '../../../@types/astro.js'; +import type { AstroConfig } from '../../../types/public/config.js'; +import type { RoutePart } from '../../../types/public/internal.js'; export function getPattern( segments: RoutePart[][], diff --git a/packages/astro/src/core/routing/manifest/serialization.ts b/packages/astro/src/core/routing/manifest/serialization.ts index 852aa703bf9d..c0cf600f0b79 100644 --- a/packages/astro/src/core/routing/manifest/serialization.ts +++ b/packages/astro/src/core/routing/manifest/serialization.ts @@ -1,4 +1,6 @@ -import type { AstroConfig, RouteData, SerializedRouteData } from '../../../@types/astro.js'; +import type { SerializedRouteData } from '../../../types/astro.js'; +import type { AstroConfig } from '../../../types/public/config.js'; +import type { RouteData } from '../../../types/public/internal.js'; import { getRouteGenerator } from './generator.js'; diff --git a/packages/astro/src/core/routing/match.ts b/packages/astro/src/core/routing/match.ts index 40a8b95fba29..403b3fb9535b 100644 --- a/packages/astro/src/core/routing/match.ts +++ b/packages/astro/src/core/routing/match.ts @@ -1,4 +1,5 @@ -import type { ManifestData, RouteData } from '../../@types/astro.js'; +import type { ManifestData } from '../../types/astro.js'; +import type { RouteData } from '../../types/public/internal.js'; /** Find matching route from pathname */ export function matchRoute(pathname: string, manifest: ManifestData): RouteData | undefined { diff --git a/packages/astro/src/core/routing/params.ts b/packages/astro/src/core/routing/params.ts index 43cd24cc13a7..802c39cc5043 100644 --- a/packages/astro/src/core/routing/params.ts +++ b/packages/astro/src/core/routing/params.ts @@ -1,4 +1,5 @@ -import type { GetStaticPathsItem, Params, RouteData } from '../../@types/astro.js'; +import type { GetStaticPathsItem, Params } from '../../types/public/common.js'; +import type { RouteData } from '../../types/public/internal.js'; import { trimSlashes } from '../path.js'; import { validateGetStaticPathsParameter } from './validation.js'; diff --git a/packages/astro/src/core/routing/priority.ts b/packages/astro/src/core/routing/priority.ts index 4082683970e5..dc1c665c6156 100644 --- a/packages/astro/src/core/routing/priority.ts +++ b/packages/astro/src/core/routing/priority.ts @@ -1,4 +1,4 @@ -import type { RouteData } from '../../@types/astro.js'; +import type { RouteData } from '../../types/public/internal.js'; /** * Comparator for sorting routes in resolution order. diff --git a/packages/astro/src/core/routing/rewrite.ts b/packages/astro/src/core/routing/rewrite.ts index f30caed08c7b..a6fce3354929 100644 --- a/packages/astro/src/core/routing/rewrite.ts +++ b/packages/astro/src/core/routing/rewrite.ts @@ -1,4 +1,6 @@ -import type { AstroConfig, RewritePayload, RouteData } from '../../@types/astro.js'; +import type { RewritePayload } from '../../types/public/common.js'; +import type { AstroConfig } from '../../types/public/config.js'; +import type { RouteData } from '../../types/public/internal.js'; import { shouldAppendForwardSlash } from '../build/util.js'; import { appendForwardSlash, removeTrailingForwardSlash } from '../path.js'; import { DEFAULT_404_ROUTE } from './astro-designed-error-pages.js'; diff --git a/packages/astro/src/core/routing/validation.ts b/packages/astro/src/core/routing/validation.ts index 1f11f55e6cd4..a2f9a25ba320 100644 --- a/packages/astro/src/core/routing/validation.ts +++ b/packages/astro/src/core/routing/validation.ts @@ -1,4 +1,6 @@ -import type { ComponentInstance, GetStaticPathsResult, RouteData } from '../../@types/astro.js'; +import type { ComponentInstance } from '../../types/astro.js'; +import type { GetStaticPathsResult } from '../../types/public/common.js'; +import type { RouteData } from '../../types/public/internal.js'; import { AstroError, AstroErrorData } from '../errors/index.js'; import type { Logger } from '../logger/core.js'; diff --git a/packages/astro/src/core/server-islands/endpoint.ts b/packages/astro/src/core/server-islands/endpoint.ts index 368a1b9b19ac..73ed5717704d 100644 --- a/packages/astro/src/core/server-islands/endpoint.ts +++ b/packages/astro/src/core/server-islands/endpoint.ts @@ -1,9 +1,3 @@ -import type { - ComponentInstance, - ManifestData, - RouteData, - SSRManifest, -} from '../../@types/astro.js'; import { type AstroComponentFactory, type ComponentSlots, @@ -11,6 +5,8 @@ import { renderTemplate, } from '../../runtime/server/index.js'; import { createSlotValueFromString } from '../../runtime/server/render/slot.js'; +import type { ComponentInstance, ManifestData } from '../../types/astro.js'; +import type { RouteData, SSRManifest } from '../../types/public/internal.js'; import { decryptString } from '../encryption.js'; import { getPattern } from '../routing/manifest/pattern.js'; diff --git a/packages/astro/src/core/server-islands/vite-plugin-server-islands.ts b/packages/astro/src/core/server-islands/vite-plugin-server-islands.ts index 573ae9cf9703..8bc79e087d56 100644 --- a/packages/astro/src/core/server-islands/vite-plugin-server-islands.ts +++ b/packages/astro/src/core/server-islands/vite-plugin-server-islands.ts @@ -1,5 +1,5 @@ import type { ConfigEnv, ViteDevServer, Plugin as VitePlugin } from 'vite'; -import type { AstroSettings } from '../../@types/astro.js'; +import type { AstroSettings } from '../../types/astro.js'; import type { AstroPluginMetadata } from '../../vite-plugin-astro/index.js'; export const VIRTUAL_ISLAND_MAP_ID = '@astro-server-islands'; diff --git a/packages/astro/src/core/sync/index.ts b/packages/astro/src/core/sync/index.ts index 92b3478e344d..02ab6bf9e137 100644 --- a/packages/astro/src/core/sync/index.ts +++ b/packages/astro/src/core/sync/index.ts @@ -3,7 +3,6 @@ import { performance } from 'node:perf_hooks'; import { fileURLToPath } from 'node:url'; import { dim } from 'kleur/colors'; import { type HMRPayload, createServer } from 'vite'; -import type { AstroConfig, AstroInlineConfig, AstroSettings } from '../../@types/astro.js'; import { CONTENT_TYPES_FILE, DATA_STORE_FILE } from '../../content/consts.js'; import { globalContentLayer } from '../../content/content-layer.js'; import { createContentTypesGenerator } from '../../content/index.js'; @@ -13,6 +12,8 @@ import { syncAstroEnv } from '../../env/sync.js'; import { telemetry } from '../../events/index.js'; import { eventCliSession } from '../../events/session.js'; import { runHookConfigDone, runHookConfigSetup } from '../../integrations/hooks.js'; +import type { AstroSettings } from '../../types/astro.js'; +import type { AstroConfig, AstroInlineConfig } from '../../types/public/config.js'; import { getTimeStat } from '../build/util.js'; import { resolveConfig } from '../config/config.js'; import { createNodeLogger } from '../config/logging.js'; diff --git a/packages/astro/src/core/sync/write-files.ts b/packages/astro/src/core/sync/write-files.ts index 91084c36f965..1f7d1d304608 100644 --- a/packages/astro/src/core/sync/write-files.ts +++ b/packages/astro/src/core/sync/write-files.ts @@ -3,7 +3,7 @@ import { dirname, relative } from 'node:path'; import { fileURLToPath } from 'node:url'; import { bold } from 'kleur/colors'; import { normalizePath } from 'vite'; -import type { AstroSettings } from '../../@types/astro.js'; +import type { AstroSettings } from '../../types/astro.js'; import { AstroError, AstroErrorData } from '../errors/index.js'; import type { Logger } from '../logger/core.js'; import { REFERENCE_FILE } from './constants.js'; diff --git a/packages/astro/src/core/util.ts b/packages/astro/src/core/util.ts index 654d1982994c..497d54610262 100644 --- a/packages/astro/src/core/util.ts +++ b/packages/astro/src/core/util.ts @@ -1,7 +1,9 @@ import fs from 'node:fs'; import path from 'node:path'; import { fileURLToPath } from 'node:url'; -import type { AstroConfig, AstroSettings, RouteType } from '../@types/astro.js'; +import type { AstroSettings } from '../types/astro.js'; +import type { AstroConfig } from '../types/public/config.js'; +import type { RouteType } from '../types/public/internal.js'; import { SUPPORTED_MARKDOWN_FILE_EXTENSIONS } from './constants.js'; import { removeTrailingForwardSlash, slash } from './path.js'; diff --git a/packages/astro/src/env/sync.ts b/packages/astro/src/env/sync.ts index 27436f967be7..90a29685dc28 100644 --- a/packages/astro/src/env/sync.ts +++ b/packages/astro/src/env/sync.ts @@ -1,5 +1,5 @@ import fsMod from 'node:fs'; -import type { AstroSettings } from '../@types/astro.js'; +import type { AstroSettings } from '../types/astro.js'; import { TYPES_TEMPLATE_URL } from './constants.js'; import { getEnvFieldType } from './validators.js'; diff --git a/packages/astro/src/env/vite-plugin-env.ts b/packages/astro/src/env/vite-plugin-env.ts index fdcd6ce4015d..934ba79ca2ab 100644 --- a/packages/astro/src/env/vite-plugin-env.ts +++ b/packages/astro/src/env/vite-plugin-env.ts @@ -1,8 +1,8 @@ import type fsMod from 'node:fs'; import { fileURLToPath } from 'node:url'; import { type Plugin, loadEnv } from 'vite'; -import type { AstroSettings } from '../@types/astro.js'; import { AstroError, AstroErrorData } from '../core/errors/index.js'; +import type { AstroSettings } from '../types/astro.js'; import { MODULE_TEMPLATE_URL, VIRTUAL_MODULES_IDS, diff --git a/packages/astro/src/events/session.ts b/packages/astro/src/events/session.ts index 18049ac04dd0..6e919f127bee 100644 --- a/packages/astro/src/events/session.ts +++ b/packages/astro/src/events/session.ts @@ -1,5 +1,6 @@ -import type { AstroIntegration, AstroUserConfig } from '../@types/astro.js'; import { AstroConfigSchema } from '../core/config/schema.js'; +import type { AstroUserConfig } from '../types/public/config.js'; +import type { AstroIntegration } from '../types/public/integrations.js'; const EVENT_SESSION = 'ASTRO_CLI_SESSION_STARTED'; diff --git a/packages/astro/src/i18n/index.ts b/packages/astro/src/i18n/index.ts index aa38b63bbe89..c7e676f75803 100644 --- a/packages/astro/src/i18n/index.ts +++ b/packages/astro/src/i18n/index.ts @@ -1,15 +1,11 @@ import { appendForwardSlash, joinPaths } from '@astrojs/internal-helpers/path'; -import type { - APIContext, - AstroConfig, - Locales, - SSRManifest, - ValidRedirectStatus, -} from '../@types/astro.js'; +import type { SSRManifest } from '../core/app/types.js'; import { shouldAppendForwardSlash } from '../core/build/util.js'; import { REROUTE_DIRECTIVE_HEADER } from '../core/constants.js'; import { MissingLocale, i18nNoLocaleFoundInPath } from '../core/errors/errors-data.js'; import { AstroError } from '../core/errors/index.js'; +import type { AstroConfig, Locales, ValidRedirectStatus } from '../types/public/config.js'; +import type { APIContext } from '../types/public/context.js'; import { createI18nMiddleware } from './middleware.js'; import type { RoutingStrategies } from './utils.js'; diff --git a/packages/astro/src/i18n/middleware.ts b/packages/astro/src/i18n/middleware.ts index 097332805759..7c2fc1406b2a 100644 --- a/packages/astro/src/i18n/middleware.ts +++ b/packages/astro/src/i18n/middleware.ts @@ -1,6 +1,7 @@ -import type { APIContext, MiddlewareHandler, SSRManifest } from '../@types/astro.js'; -import type { SSRManifestI18n } from '../core/app/types.js'; +import type { SSRManifest, SSRManifestI18n } from '../core/app/types.js'; import { ROUTE_TYPE_HEADER } from '../core/constants.js'; +import type { MiddlewareHandler } from '../types/public/common.js'; +import type { APIContext } from '../types/public/context.js'; import { type MiddlewarePayload, normalizeTheLocale, diff --git a/packages/astro/src/i18n/utils.ts b/packages/astro/src/i18n/utils.ts index 052fe01fce65..98a44a19ca5e 100644 --- a/packages/astro/src/i18n/utils.ts +++ b/packages/astro/src/i18n/utils.ts @@ -1,4 +1,4 @@ -import type { AstroConfig, Locales } from '../@types/astro.js'; +import type { AstroConfig, Locales } from '../types/public/config.js'; import { normalizeTheLocale, toCodes } from './index.js'; type BrowserLocale = { diff --git a/packages/astro/src/i18n/vite-plugin-i18n.ts b/packages/astro/src/i18n/vite-plugin-i18n.ts index 7aa4d327b223..5ee79a8836a8 100644 --- a/packages/astro/src/i18n/vite-plugin-i18n.ts +++ b/packages/astro/src/i18n/vite-plugin-i18n.ts @@ -1,7 +1,8 @@ import type * as vite from 'vite'; -import type { AstroConfig, AstroSettings } from '../@types/astro.js'; import { AstroError } from '../core/errors/errors.js'; import { AstroErrorData } from '../core/errors/index.js'; +import type { AstroSettings } from '../types/astro.js'; +import type { AstroConfig } from '../types/public/config.js'; const virtualModuleId = 'astro:i18n'; diff --git a/packages/astro/src/integrations/features-validation.ts b/packages/astro/src/integrations/features-validation.ts index 87de3592b726..f59a25b15c28 100644 --- a/packages/astro/src/integrations/features-validation.ts +++ b/packages/astro/src/integrations/features-validation.ts @@ -1,11 +1,11 @@ +import type { Logger } from '../core/logger/core.js'; +import type { AstroConfig } from '../types/public/config.js'; import type { + AdapterSupportsKind, + AstroAdapterFeatureMap, AstroAdapterFeatures, AstroAssetsFeature, - AstroConfig, - AstroFeatureMap, - SupportsKind, -} from '../@types/astro.js'; -import type { Logger } from '../core/logger/core.js'; +} from '../types/public/integrations.js'; const STABLE = 'stable'; const DEPRECATED = 'deprecated'; @@ -19,7 +19,7 @@ const UNSUPPORTED_ASSETS_FEATURE: AstroAssetsFeature = { }; type ValidationResult = { - [Property in keyof AstroFeatureMap]: boolean; + [Property in keyof AstroAdapterFeatureMap]: boolean; }; /** @@ -31,7 +31,7 @@ type ValidationResult = { */ export function validateSupportedFeatures( adapterName: string, - featureMap: AstroFeatureMap, + featureMap: AstroAdapterFeatureMap, config: AstroConfig, adapterFeatures: AstroAdapterFeatures | undefined, logger: Logger, @@ -101,7 +101,7 @@ export function validateSupportedFeatures( } function validateSupportKind( - supportKind: SupportsKind, + supportKind: AdapterSupportsKind, adapterName: string, logger: Logger, featureName: string, diff --git a/packages/astro/src/integrations/hooks.ts b/packages/astro/src/integrations/hooks.ts index c0b9604335b3..39d8ab69feb0 100644 --- a/packages/astro/src/integrations/hooks.ts +++ b/packages/astro/src/integrations/hooks.ts @@ -3,24 +3,23 @@ import type { AddressInfo } from 'node:net'; import { fileURLToPath } from 'node:url'; import { bold } from 'kleur/colors'; import type { InlineConfig, ViteDevServer } from 'vite'; -import type { - AstroAdapter, - AstroConfig, - AstroIntegration, - AstroRenderer, - AstroSettings, - ContentEntryType, - DataEntryType, - HookParameters, - RouteData, - RouteOptions, -} from '../@types/astro.js'; import type { SerializedSSRManifest } from '../core/app/types.js'; import type { PageBuildData } from '../core/build/types.js'; import { buildClientDirectiveEntrypoint } from '../core/client-directive/index.js'; import { mergeConfig } from '../core/config/index.js'; import type { AstroIntegrationLogger, Logger } from '../core/logger/core.js'; import { isServerLikeOutput } from '../core/util.js'; +import type { AstroSettings } from '../types/astro.js'; +import type { AstroConfig } from '../types/public/config.js'; +import type { ContentEntryType, DataEntryType } from '../types/public/content.js'; +import type { + AstroAdapter, + AstroIntegration, + AstroRenderer, + HookParameters, + RouteOptions, +} from '../types/public/integrations.js'; +import type { RouteData } from '../types/public/internal.js'; import { validateSupportedFeatures } from './features-validation.js'; async function withTakingALongTimeMsg({ @@ -198,10 +197,6 @@ export async function runHookConfigSetup({ addWatchFile: (path) => { updatedSettings.watchFiles.push(path instanceof URL ? fileURLToPath(path) : path); }, - addDevOverlayPlugin: (entrypoint) => { - // TODO add a deprecation warning in Astro 5. - hooks.addDevToolbarApp(entrypoint); - }, addDevToolbarApp: (entrypoint) => { updatedSettings.devToolbarApps.push(entrypoint); }, diff --git a/packages/astro/src/jsx/renderer.ts b/packages/astro/src/jsx/renderer.ts index 413257faab97..86f4d018743a 100644 --- a/packages/astro/src/jsx/renderer.ts +++ b/packages/astro/src/jsx/renderer.ts @@ -1,11 +1,8 @@ -import type { AstroRenderer } from '../@types/astro.js'; -import { jsxTransformOptions } from './transform-options.js'; +import type { AstroRenderer } from '../types/public/integrations.js'; const renderer: AstroRenderer = { name: 'astro:jsx', serverEntrypoint: 'astro/jsx/server.js', - jsxImportSource: 'astro', - jsxTransformOptions, }; export default renderer; diff --git a/packages/astro/src/jsx/server.ts b/packages/astro/src/jsx/server.ts index 73b584baeaf7..bb71231c5813 100644 --- a/packages/astro/src/jsx/server.ts +++ b/packages/astro/src/jsx/server.ts @@ -1,7 +1,7 @@ -import type { NamedSSRLoadedRendererValue } from '../@types/astro.js'; import { AstroError, AstroUserError } from '../core/errors/errors.js'; import { AstroJSX, jsx } from '../jsx-runtime/index.js'; import { renderJSX } from '../runtime/server/jsx.js'; +import type { NamedSSRLoadedRendererValue } from '../types/public/internal.js'; const slotName = (str: string) => str.trim().replace(/[-_]([a-z])/g, (_, w) => w.toUpperCase()); diff --git a/packages/astro/src/jsx/transform-options.ts b/packages/astro/src/jsx/transform-options.ts index ca1d50a6a131..e7405ddc0c2d 100644 --- a/packages/astro/src/jsx/transform-options.ts +++ b/packages/astro/src/jsx/transform-options.ts @@ -1,4 +1,4 @@ -import type { JSXTransformConfig } from '../@types/astro.js'; +import type { JSXTransformConfig } from '../types/astro.js'; /** * @deprecated This function is no longer used. Remove in Astro 5.0 diff --git a/packages/astro/src/preferences/index.ts b/packages/astro/src/preferences/index.ts index 2b92c5fb6cb5..7c8779b43f4e 100644 --- a/packages/astro/src/preferences/index.ts +++ b/packages/astro/src/preferences/index.ts @@ -1,11 +1,10 @@ -import type { AstroConfig } from '../@types/astro.js'; - import os from 'node:os'; import path from 'node:path'; import process from 'node:process'; import { fileURLToPath } from 'node:url'; import dget from 'dlv'; +import type { AstroConfig } from '../types/public/config.js'; import { DEFAULT_PREFERENCES, type Preferences, type PublicPreferences } from './defaults.js'; import { PreferenceStore } from './store.js'; diff --git a/packages/astro/src/prefetch/vite-plugin-prefetch.ts b/packages/astro/src/prefetch/vite-plugin-prefetch.ts index d64c6d5008b9..560895b15bfb 100644 --- a/packages/astro/src/prefetch/vite-plugin-prefetch.ts +++ b/packages/astro/src/prefetch/vite-plugin-prefetch.ts @@ -1,5 +1,5 @@ import type * as vite from 'vite'; -import type { AstroSettings } from '../@types/astro.js'; +import type { AstroSettings } from '../types/astro.js'; const virtualModuleId = 'astro:prefetch'; const resolvedVirtualModuleId = '\0' + virtualModuleId; diff --git a/packages/astro/src/prerender/routing.ts b/packages/astro/src/prerender/routing.ts index cbdddff5c8cb..888b012e0b9d 100644 --- a/packages/astro/src/prerender/routing.ts +++ b/packages/astro/src/prerender/routing.ts @@ -1,6 +1,7 @@ -import type { AstroSettings, ComponentInstance, RouteData } from '../@types/astro.js'; import { RedirectComponentInstance, routeIsRedirect } from '../core/redirects/index.js'; import { routeComparator } from '../core/routing/priority.js'; +import type { AstroSettings, ComponentInstance } from '../types/astro.js'; +import type { RouteData } from '../types/public/internal.js'; import type { DevPipeline } from '../vite-plugin-astro-server/pipeline.js'; import { getPrerenderStatus } from './metadata.js'; diff --git a/packages/astro/src/prerender/utils.ts b/packages/astro/src/prerender/utils.ts index 4097b66b1f6d..e34e0d5fd024 100644 --- a/packages/astro/src/prerender/utils.ts +++ b/packages/astro/src/prerender/utils.ts @@ -1,6 +1,6 @@ -import type { AstroConfig } from '../@types/astro.js'; import { getOutDirWithinCwd } from '../core/build/common.js'; import { isServerLikeOutput } from '../core/util.js'; +import type { AstroConfig } from '../types/public/config.js'; export function getPrerenderDefault(config: AstroConfig) { return config.output !== 'server'; diff --git a/packages/astro/src/runtime/client/dev-toolbar/apps/astro.ts b/packages/astro/src/runtime/client/dev-toolbar/apps/astro.ts index e63667a12d6f..12ab602a255e 100644 --- a/packages/astro/src/runtime/client/dev-toolbar/apps/astro.ts +++ b/packages/astro/src/runtime/client/dev-toolbar/apps/astro.ts @@ -1,4 +1,4 @@ -import type { DevToolbarApp, DevToolbarMetadata } from '../../../../@types/astro.js'; +import type { DevToolbarApp, DevToolbarMetadata } from '../../../../types/public/toolbar.js'; import { type Icon, isDefinedIcon } from '../ui-library/icons.js'; import { colorForIntegration, iconForIntegration } from './utils/icons.js'; import { diff --git a/packages/astro/src/runtime/client/dev-toolbar/apps/audit/index.ts b/packages/astro/src/runtime/client/dev-toolbar/apps/audit/index.ts index 6a6aba42d120..cc58411cf3c4 100644 --- a/packages/astro/src/runtime/client/dev-toolbar/apps/audit/index.ts +++ b/packages/astro/src/runtime/client/dev-toolbar/apps/audit/index.ts @@ -1,4 +1,4 @@ -import type { DevToolbarApp } from '../../../../../@types/astro.js'; +import type { DevToolbarApp } from '../../../../../types/public/toolbar.js'; import { settings } from '../../settings.js'; import type { DevToolbarHighlight } from '../../ui-library/highlight.js'; import { positionHighlight } from '../utils/highlight.js'; diff --git a/packages/astro/src/runtime/client/dev-toolbar/apps/audit/ui/audit-ui.ts b/packages/astro/src/runtime/client/dev-toolbar/apps/audit/ui/audit-ui.ts index 38559e0f9adf..34adf4f01282 100644 --- a/packages/astro/src/runtime/client/dev-toolbar/apps/audit/ui/audit-ui.ts +++ b/packages/astro/src/runtime/client/dev-toolbar/apps/audit/ui/audit-ui.ts @@ -1,5 +1,5 @@ import { escape as escapeHTML } from 'html-escaper'; -import type { DevToolbarMetadata } from '../../../../../../@types/astro.js'; +import type { DevToolbarMetadata } from '../../../../../../types/public/toolbar.js'; import { attachTooltipToHighlight, createHighlight, diff --git a/packages/astro/src/runtime/client/dev-toolbar/apps/settings.ts b/packages/astro/src/runtime/client/dev-toolbar/apps/settings.ts index 7ee42da84996..192e4509b504 100644 --- a/packages/astro/src/runtime/client/dev-toolbar/apps/settings.ts +++ b/packages/astro/src/runtime/client/dev-toolbar/apps/settings.ts @@ -1,4 +1,4 @@ -import type { DevToolbarApp } from '../../../../@types/astro.js'; +import type { DevToolbarApp } from '../../../../types/public/toolbar.js'; import { type Settings, settings } from '../settings.js'; import { isValidPlacement, placements } from '../ui-library/window.js'; import { diff --git a/packages/astro/src/runtime/client/dev-toolbar/apps/xray.ts b/packages/astro/src/runtime/client/dev-toolbar/apps/xray.ts index 2e56b0f244cf..fafc8e26d57e 100644 --- a/packages/astro/src/runtime/client/dev-toolbar/apps/xray.ts +++ b/packages/astro/src/runtime/client/dev-toolbar/apps/xray.ts @@ -1,5 +1,5 @@ import { escape as escapeHTML } from 'html-escaper'; -import type { DevToolbarApp, DevToolbarMetadata } from '../../../../@types/astro.js'; +import type { DevToolbarApp, DevToolbarMetadata } from '../../../../types/public/toolbar.js'; import type { DevToolbarHighlight } from '../ui-library/highlight.js'; import { attachTooltipToHighlight, diff --git a/packages/astro/src/runtime/client/dev-toolbar/entrypoint.ts b/packages/astro/src/runtime/client/dev-toolbar/entrypoint.ts index 9731f3597fbb..86c616becb3a 100644 --- a/packages/astro/src/runtime/client/dev-toolbar/entrypoint.ts +++ b/packages/astro/src/runtime/client/dev-toolbar/entrypoint.ts @@ -1,6 +1,6 @@ // @ts-expect-error - This module is private and untyped import { loadDevToolbarApps } from 'astro:toolbar:internal'; -import type { ResolvedDevToolbarApp as DevToolbarAppDefinition } from '../../../@types/astro.js'; +import type { ResolvedDevToolbarApp as DevToolbarAppDefinition } from '../../../types/public/toolbar.js'; import { ToolbarAppEventTarget } from './helpers.js'; import { settings } from './settings.js'; import type { AstroDevToolbar, DevToolbarApp } from './toolbar.js'; diff --git a/packages/astro/src/runtime/client/dev-toolbar/toolbar.ts b/packages/astro/src/runtime/client/dev-toolbar/toolbar.ts index 08ea61cace5c..e24698d4337b 100644 --- a/packages/astro/src/runtime/client/dev-toolbar/toolbar.ts +++ b/packages/astro/src/runtime/client/dev-toolbar/toolbar.ts @@ -1,5 +1,5 @@ /* eslint-disable no-console */ -import type { ResolvedDevToolbarApp as DevToolbarAppDefinition } from '../../../@types/astro.js'; +import type { ResolvedDevToolbarApp as DevToolbarAppDefinition } from '../../../types/public/toolbar.js'; import { type ToolbarAppEventTarget, serverHelpers } from './helpers.js'; import { settings } from './settings.js'; import { type Icon, getIconElement, isDefinedIcon } from './ui-library/icons.js'; diff --git a/packages/astro/src/runtime/client/idle.ts b/packages/astro/src/runtime/client/idle.ts index 990d5da6ef10..e32b1a42f698 100644 --- a/packages/astro/src/runtime/client/idle.ts +++ b/packages/astro/src/runtime/client/idle.ts @@ -1,4 +1,4 @@ -import type { ClientDirective } from '../../@types/astro.js'; +import type { ClientDirective } from '../../types/public/integrations.js'; const idleDirective: ClientDirective = (load) => { const cb = async () => { diff --git a/packages/astro/src/runtime/client/load.ts b/packages/astro/src/runtime/client/load.ts index b603eecb3b49..98521181c528 100644 --- a/packages/astro/src/runtime/client/load.ts +++ b/packages/astro/src/runtime/client/load.ts @@ -1,4 +1,4 @@ -import type { ClientDirective } from '../../@types/astro.js'; +import type { ClientDirective } from '../../types/public/integrations.js'; const loadDirective: ClientDirective = async (load) => { const hydrate = await load(); diff --git a/packages/astro/src/runtime/client/media.ts b/packages/astro/src/runtime/client/media.ts index f894af31112d..0c6e497e3302 100644 --- a/packages/astro/src/runtime/client/media.ts +++ b/packages/astro/src/runtime/client/media.ts @@ -1,4 +1,4 @@ -import type { ClientDirective } from '../../@types/astro.js'; +import type { ClientDirective } from '../../types/public/integrations.js'; /** * Hydrate this component when a matching media query is found diff --git a/packages/astro/src/runtime/client/only.ts b/packages/astro/src/runtime/client/only.ts index 8e072b7a3fc0..c5fc488d4bd8 100644 --- a/packages/astro/src/runtime/client/only.ts +++ b/packages/astro/src/runtime/client/only.ts @@ -1,4 +1,4 @@ -import type { ClientDirective } from '../../@types/astro.js'; +import type { ClientDirective } from '../../types/public/integrations.js'; /** * Hydrate this component only on the client diff --git a/packages/astro/src/runtime/client/visible.ts b/packages/astro/src/runtime/client/visible.ts index 9be4d9b318a7..c7d858ffb0b4 100644 --- a/packages/astro/src/runtime/client/visible.ts +++ b/packages/astro/src/runtime/client/visible.ts @@ -1,4 +1,5 @@ -import type { ClientDirective, ClientVisibleOptions } from '../../@types/astro.js'; +import type { ClientVisibleOptions } from '../../types/public/elements.js'; +import type { ClientDirective } from '../../types/public/integrations.js'; /** * Hydrate this component when one of it's children becomes visible diff --git a/packages/astro/src/runtime/server/astro-component.ts b/packages/astro/src/runtime/server/astro-component.ts index 928d23ad82a5..20649b64dcb4 100644 --- a/packages/astro/src/runtime/server/astro-component.ts +++ b/packages/astro/src/runtime/server/astro-component.ts @@ -1,5 +1,5 @@ -import type { PropagationHint } from '../../@types/astro.js'; import { AstroError, AstroErrorData } from '../../core/errors/index.js'; +import type { PropagationHint } from '../../types/public/internal.js'; import type { AstroComponentFactory } from './render/index.js'; function validateArgs(args: unknown[]): args is Parameters { diff --git a/packages/astro/src/runtime/server/astro-global.ts b/packages/astro/src/runtime/server/astro-global.ts index 5948c8ff3aff..74b32e331421 100644 --- a/packages/astro/src/runtime/server/astro-global.ts +++ b/packages/astro/src/runtime/server/astro-global.ts @@ -1,6 +1,6 @@ -import type { AstroGlobalPartial } from '../../@types/astro.js'; import { ASTRO_VERSION } from '../../core/constants.js'; import { AstroError, AstroErrorData } from '../../core/errors/index.js'; +import type { AstroGlobalPartial } from '../../types/public/context.js'; /** Create the Astro.glob() runtime function. */ function createAstroGlobFn() { diff --git a/packages/astro/src/runtime/server/endpoint.ts b/packages/astro/src/runtime/server/endpoint.ts index 900d604fd569..674d6209343f 100644 --- a/packages/astro/src/runtime/server/endpoint.ts +++ b/packages/astro/src/runtime/server/endpoint.ts @@ -1,13 +1,16 @@ import { bold } from 'kleur/colors'; -import type { APIContext, EndpointHandler } from '../../@types/astro.js'; import { REROUTABLE_STATUS_CODES, REROUTE_DIRECTIVE_HEADER } from '../../core/constants.js'; import { EndpointDidNotReturnAResponse } from '../../core/errors/errors-data.js'; import { AstroError } from '../../core/errors/errors.js'; import type { Logger } from '../../core/logger/core.js'; +import type { APIRoute } from '../../types/public/common.js'; +import type { APIContext } from '../../types/public/context.js'; /** Renders an endpoint request to completion, returning the body. */ export async function renderEndpoint( - mod: EndpointHandler, + mod: { + [method: string]: APIRoute; + }, context: APIContext, ssr: boolean, logger: Logger, diff --git a/packages/astro/src/runtime/server/hydration.ts b/packages/astro/src/runtime/server/hydration.ts index ab6396566b5e..982ff9977ecb 100644 --- a/packages/astro/src/runtime/server/hydration.ts +++ b/packages/astro/src/runtime/server/hydration.ts @@ -1,10 +1,10 @@ +import { AstroError, AstroErrorData } from '../../core/errors/index.js'; import type { AstroComponentMetadata, SSRElement, SSRLoadedRenderer, SSRResult, -} from '../../@types/astro.js'; -import { AstroError, AstroErrorData } from '../../core/errors/index.js'; +} from '../../types/public/internal.js'; import { escapeHTML } from './escape.js'; import { serializeProps } from './serialize.js'; diff --git a/packages/astro/src/runtime/server/jsx.ts b/packages/astro/src/runtime/server/jsx.ts index 2491ab58946e..7280e216c31c 100644 --- a/packages/astro/src/runtime/server/jsx.ts +++ b/packages/astro/src/runtime/server/jsx.ts @@ -1,5 +1,5 @@ -import type { SSRResult } from '../../@types/astro.js'; import { AstroJSX, type AstroVNode, isVNode } from '../../jsx-runtime/index.js'; +import type { SSRResult } from '../../types/public/internal.js'; import { HTMLString, escapeHTML, diff --git a/packages/astro/src/runtime/server/render/astro/factory.ts b/packages/astro/src/runtime/server/render/astro/factory.ts index db319eb1aadd..dab33a031991 100644 --- a/packages/astro/src/runtime/server/render/astro/factory.ts +++ b/packages/astro/src/runtime/server/render/astro/factory.ts @@ -1,4 +1,4 @@ -import type { PropagationHint, SSRResult } from '../../../../@types/astro.js'; +import type { PropagationHint, SSRResult } from '../../../../types/public/internal.js'; import type { HeadAndContent } from './head-and-content.js'; import type { RenderTemplateResult } from './render-template.js'; diff --git a/packages/astro/src/runtime/server/render/astro/instance.ts b/packages/astro/src/runtime/server/render/astro/instance.ts index 3246a7e1b294..029231a28d6d 100644 --- a/packages/astro/src/runtime/server/render/astro/instance.ts +++ b/packages/astro/src/runtime/server/render/astro/instance.ts @@ -1,7 +1,7 @@ -import type { SSRResult } from '../../../../@types/astro.js'; import type { ComponentSlots } from '../slot.js'; import type { AstroComponentFactory } from './factory.js'; +import type { SSRResult } from '../../../../types/public/internal.js'; import { isPromise } from '../../util.js'; import { renderChild } from '../any.js'; import type { RenderDestination } from '../common.js'; diff --git a/packages/astro/src/runtime/server/render/astro/render.ts b/packages/astro/src/runtime/server/render/astro/render.ts index 41845b7b9e16..adc335495da1 100644 --- a/packages/astro/src/runtime/server/render/astro/render.ts +++ b/packages/astro/src/runtime/server/render/astro/render.ts @@ -1,5 +1,5 @@ -import type { RouteData, SSRResult } from '../../../../@types/astro.js'; import { AstroError, AstroErrorData } from '../../../../core/errors/index.js'; +import type { RouteData, SSRResult } from '../../../../types/public/internal.js'; import { type RenderDestination, chunkToByteArray, chunkToString, encoder } from '../common.js'; import { promiseWithResolvers } from '../util.js'; import type { AstroComponentFactory } from './factory.js'; diff --git a/packages/astro/src/runtime/server/render/common.ts b/packages/astro/src/runtime/server/render/common.ts index 0845bdd65315..77f05dfccec6 100644 --- a/packages/astro/src/runtime/server/render/common.ts +++ b/packages/astro/src/runtime/server/render/common.ts @@ -1,6 +1,6 @@ -import type { SSRResult } from '../../../@types/astro.js'; import type { RenderInstruction } from './instruction.js'; +import type { SSRResult } from '../../../types/public/internal.js'; import type { HTMLBytes, HTMLString } from '../escape.js'; import { markHTMLString } from '../escape.js'; import { diff --git a/packages/astro/src/runtime/server/render/component.ts b/packages/astro/src/runtime/server/render/component.ts index 449f58fbcc7d..300911acdaca 100644 --- a/packages/astro/src/runtime/server/render/component.ts +++ b/packages/astro/src/runtime/server/render/component.ts @@ -1,9 +1,3 @@ -import type { - AstroComponentMetadata, - RouteData, - SSRLoadedRenderer, - SSRResult, -} from '../../../@types/astro.js'; import { createRenderInstruction } from './instruction.js'; import { clsx } from 'clsx'; @@ -17,6 +11,12 @@ import { type AstroComponentFactory, isAstroComponentFactory } from './astro/fac import { renderTemplate } from './astro/index.js'; import { createAstroComponentInstance } from './astro/instance.js'; +import type { + AstroComponentMetadata, + RouteData, + SSRLoadedRenderer, + SSRResult, +} from '../../../types/public/internal.js'; import { Fragment, type RenderDestination, diff --git a/packages/astro/src/runtime/server/render/dom.ts b/packages/astro/src/runtime/server/render/dom.ts index e2b194df3451..f92b4889a38f 100644 --- a/packages/astro/src/runtime/server/render/dom.ts +++ b/packages/astro/src/runtime/server/render/dom.ts @@ -1,5 +1,4 @@ -import type { SSRResult } from '../../../@types/astro.js'; - +import type { SSRResult } from '../../../types/public/internal.js'; import { markHTMLString } from '../escape.js'; import { renderSlotToString } from './slot.js'; import { toAttributeString } from './util.js'; diff --git a/packages/astro/src/runtime/server/render/head.ts b/packages/astro/src/runtime/server/render/head.ts index 49dd5abed14a..01f11f21e760 100644 --- a/packages/astro/src/runtime/server/render/head.ts +++ b/packages/astro/src/runtime/server/render/head.ts @@ -1,5 +1,4 @@ -import type { SSRResult } from '../../../@types/astro.js'; - +import type { SSRResult } from '../../../types/public/internal.js'; import { markHTMLString } from '../escape.js'; import type { MaybeRenderHeadInstruction, RenderHeadInstruction } from './instruction.js'; import { createRenderInstruction } from './instruction.js'; diff --git a/packages/astro/src/runtime/server/render/page.ts b/packages/astro/src/runtime/server/render/page.ts index 35a7ec789947..0e0bcf295ad8 100644 --- a/packages/astro/src/runtime/server/render/page.ts +++ b/packages/astro/src/runtime/server/render/page.ts @@ -1,7 +1,7 @@ -import type { RouteData, SSRResult } from '../../../@types/astro.js'; import { type NonAstroPageComponent, renderComponentToString } from './component.js'; import type { AstroComponentFactory } from './index.js'; +import type { RouteData, SSRResult } from '../../../types/public/internal.js'; import { isAstroComponentFactory } from './astro/index.js'; import { renderToAsyncIterable, renderToReadableStream, renderToString } from './astro/render.js'; import { encoder } from './common.js'; diff --git a/packages/astro/src/runtime/server/render/script.ts b/packages/astro/src/runtime/server/render/script.ts index 1b9c5ce1b37e..6d9283790a06 100644 --- a/packages/astro/src/runtime/server/render/script.ts +++ b/packages/astro/src/runtime/server/render/script.ts @@ -1,4 +1,4 @@ -import type { SSRResult } from '../../../@types/astro.js'; +import type { SSRResult } from '../../../types/public/internal.js'; import { markHTMLString } from '../escape.js'; /** diff --git a/packages/astro/src/runtime/server/render/server-islands.ts b/packages/astro/src/runtime/server/render/server-islands.ts index 0a072113447b..fce702364df9 100644 --- a/packages/astro/src/runtime/server/render/server-islands.ts +++ b/packages/astro/src/runtime/server/render/server-islands.ts @@ -1,5 +1,5 @@ -import type { SSRResult } from '../../../@types/astro.js'; import { encryptString } from '../../../core/encryption.js'; +import type { SSRResult } from '../../../types/public/internal.js'; import { renderChild } from './any.js'; import type { RenderInstance } from './common.js'; import { type ComponentSlots, renderSlotToString } from './slot.js'; diff --git a/packages/astro/src/runtime/server/render/slot.ts b/packages/astro/src/runtime/server/render/slot.ts index d02a32d82b5d..0df37440622c 100644 --- a/packages/astro/src/runtime/server/render/slot.ts +++ b/packages/astro/src/runtime/server/render/slot.ts @@ -1,7 +1,7 @@ -import type { SSRResult } from '../../../@types/astro.js'; import { renderTemplate } from './astro/render-template.js'; import type { RenderInstruction } from './instruction.js'; +import type { SSRResult } from '../../../types/public/internal.js'; import { HTMLString, markHTMLString, unescapeHTML } from '../escape.js'; import { renderChild } from './any.js'; import { type RenderDestination, type RenderInstance, chunkToString } from './common.js'; diff --git a/packages/astro/src/runtime/server/render/tags.ts b/packages/astro/src/runtime/server/render/tags.ts index 093c51a3c46e..baba11a5b0d1 100644 --- a/packages/astro/src/runtime/server/render/tags.ts +++ b/packages/astro/src/runtime/server/render/tags.ts @@ -1,5 +1,5 @@ -import type { SSRElement, SSRResult } from '../../../@types/astro.js'; import type { StylesheetAsset } from '../../../core/app/types.js'; +import type { SSRElement, SSRResult } from '../../../types/public/internal.js'; import { renderElement } from './util.js'; export function renderScriptElement({ props, children }: SSRElement) { diff --git a/packages/astro/src/runtime/server/render/util.ts b/packages/astro/src/runtime/server/render/util.ts index 019bf9a40828..19ac2f2b1928 100644 --- a/packages/astro/src/runtime/server/render/util.ts +++ b/packages/astro/src/runtime/server/render/util.ts @@ -1,7 +1,7 @@ -import type { SSRElement } from '../../../@types/astro.js'; import type { RenderDestination, RenderDestinationChunk, RenderFunction } from './common.js'; import { clsx } from 'clsx'; +import type { SSRElement } from '../../../types/public/internal.js'; import { HTMLString, markHTMLString } from '../escape.js'; export const voidElementNames = diff --git a/packages/astro/src/runtime/server/scripts.ts b/packages/astro/src/runtime/server/scripts.ts index 84f2dcd525d8..ca9cad1fb186 100644 --- a/packages/astro/src/runtime/server/scripts.ts +++ b/packages/astro/src/runtime/server/scripts.ts @@ -1,4 +1,4 @@ -import type { SSRResult } from '../../@types/astro.js'; +import type { SSRResult } from '../../types/public/internal.js'; import islandScriptDev from './astro-island.prebuilt-dev.js'; import islandScript from './astro-island.prebuilt.js'; diff --git a/packages/astro/src/runtime/server/serialize.ts b/packages/astro/src/runtime/server/serialize.ts index 522b05256601..6afe91917959 100644 --- a/packages/astro/src/runtime/server/serialize.ts +++ b/packages/astro/src/runtime/server/serialize.ts @@ -1,5 +1,5 @@ -import type { AstroComponentMetadata } from '../../@types/astro.js'; import type { ValueOf } from '../../type-utils.js'; +import type { AstroComponentMetadata } from '../../types/public/internal.js'; const PROP_TYPE = { Value: 0, diff --git a/packages/astro/src/runtime/server/transition.ts b/packages/astro/src/runtime/server/transition.ts index 8887d3dae4ed..4baae442afb6 100644 --- a/packages/astro/src/runtime/server/transition.ts +++ b/packages/astro/src/runtime/server/transition.ts @@ -1,12 +1,12 @@ import cssesc from 'cssesc'; +import { fade, slide } from '../../transitions/index.js'; +import type { SSRResult } from '../../types/public/internal.js'; import type { - SSRResult, TransitionAnimation, TransitionAnimationPair, TransitionAnimationValue, TransitionDirectionalAnimations, -} from '../../@types/astro.js'; -import { fade, slide } from '../../transitions/index.js'; +} from '../../types/public/view-transitions.js'; import { markHTMLString } from './escape.js'; const transitionNameMap = new WeakMap(); diff --git a/packages/astro/src/toolbar/index.ts b/packages/astro/src/toolbar/index.ts index bd05e4417447..78d7158b20af 100644 --- a/packages/astro/src/toolbar/index.ts +++ b/packages/astro/src/toolbar/index.ts @@ -1,4 +1,4 @@ -import type { DevToolbarApp } from '../@types/astro.js'; +import type { DevToolbarApp } from '../types/public/toolbar.js'; export function defineToolbarApp(app: DevToolbarApp) { return app; diff --git a/packages/astro/src/toolbar/vite-plugin-dev-toolbar.ts b/packages/astro/src/toolbar/vite-plugin-dev-toolbar.ts index 32c91752f30d..d4d0510e69ce 100644 --- a/packages/astro/src/toolbar/vite-plugin-dev-toolbar.ts +++ b/packages/astro/src/toolbar/vite-plugin-dev-toolbar.ts @@ -1,7 +1,7 @@ import type * as vite from 'vite'; -import type { AstroPluginOptions } from '../@types/astro.js'; import { telemetry } from '../events/index.js'; import { eventAppToggled } from '../events/toolbar.js'; +import type { AstroPluginOptions } from '../types/astro.js'; const PRIVATE_VIRTUAL_MODULE_ID = 'astro:toolbar:internal'; const resolvedPrivateVirtualModuleId = '\0' + PRIVATE_VIRTUAL_MODULE_ID; diff --git a/packages/astro/src/transitions/index.ts b/packages/astro/src/transitions/index.ts index d87052f2daf2..05bfb0972964 100644 --- a/packages/astro/src/transitions/index.ts +++ b/packages/astro/src/transitions/index.ts @@ -1,4 +1,8 @@ -import type { TransitionAnimationPair, TransitionDirectionalAnimations } from '../@types/astro.js'; +import type { + TransitionAnimationPair, + TransitionDirectionalAnimations, +} from '../types/public/view-transitions.js'; + export { createAnimationScope } from '../runtime/server/transition.js'; const EASE_IN_OUT_QUART = 'cubic-bezier(0.76, 0, 0.24, 1)'; diff --git a/packages/astro/src/transitions/vite-plugin-transitions.ts b/packages/astro/src/transitions/vite-plugin-transitions.ts index d88c96f8919f..56f086a06a36 100644 --- a/packages/astro/src/transitions/vite-plugin-transitions.ts +++ b/packages/astro/src/transitions/vite-plugin-transitions.ts @@ -1,5 +1,5 @@ import type * as vite from 'vite'; -import type { AstroSettings } from '../@types/astro.js'; +import type { AstroSettings } from '../types/astro.js'; const virtualModuleId = 'astro:transitions'; const resolvedVirtualModuleId = '\0' + virtualModuleId; diff --git a/packages/astro/src/types/README.md b/packages/astro/src/types/README.md new file mode 100644 index 000000000000..10331210628e --- /dev/null +++ b/packages/astro/src/types/README.md @@ -0,0 +1,5 @@ +# `types/` + +In this folder rest the types that are used throughout Astro. Typically folders for corresponding features will have a corresponding `types.ts` file in their folder. For example, the `src/assets/types.ts` contain the types for `astro:assets`. However this folder can be useful for types that are used across multiple features, or generally don't fit in any other folder. + +This folder additionally contain a `public` folder, which contains types that are exposed to users one way or another. Remember that these types are part of the public API, and as such follow the same semver contract as the rest of Astro. diff --git a/packages/astro/src/types/astro.ts b/packages/astro/src/types/astro.ts new file mode 100644 index 000000000000..6aa79a959c13 --- /dev/null +++ b/packages/astro/src/types/astro.ts @@ -0,0 +1,93 @@ +import type { SSRManifest } from '../core/app/types.js'; +import type { AstroTimer } from '../core/config/timer.js'; +import type { TSConfig } from '../core/config/tsconfig.js'; +import type { Logger } from '../core/logger/core.js'; +import type { AstroPreferences } from '../preferences/index.js'; +import type { AstroComponentFactory } from '../runtime/server/index.js'; +import type { GetStaticPathsOptions, GetStaticPathsResult } from './public/common.js'; +import type { AstroConfig } from './public/config.js'; +import type { ContentEntryType, DataEntryType } from './public/content.js'; +import type { + AstroAdapter, + AstroRenderer, + InjectedRoute, + InjectedScriptStage, + InjectedType, + ResolvedInjectedRoute, +} from './public/integrations.js'; +import type { RouteData } from './public/internal.js'; +import type { DevToolbarAppEntry } from './public/toolbar.js'; + +export type SerializedRouteData = Omit< + RouteData, + 'generate' | 'pattern' | 'redirectRoute' | 'fallbackRoutes' +> & { + generate: undefined; + pattern: string; + redirectRoute: SerializedRouteData | undefined; + fallbackRoutes: SerializedRouteData[]; + _meta: { + trailingSlash: AstroConfig['trailingSlash']; + }; +}; + +export interface AstroSettings { + config: AstroConfig; + adapter: AstroAdapter | undefined; + preferences: AstroPreferences; + injectedRoutes: InjectedRoute[]; + resolvedInjectedRoutes: ResolvedInjectedRoute[]; + pageExtensions: string[]; + contentEntryTypes: ContentEntryType[]; + dataEntryTypes: DataEntryType[]; + renderers: AstroRenderer[]; + scripts: { + stage: InjectedScriptStage; + content: string; + }[]; + /** + * Map of directive name (e.g. `load`) to the directive script code + */ + clientDirectives: Map; + devToolbarApps: (DevToolbarAppEntry | string)[]; + middlewares: { pre: string[]; post: string[] }; + tsConfig: TSConfig | undefined; + tsConfigPath: string | undefined; + watchFiles: string[]; + timer: AstroTimer; + dotAstroDir: URL; + /** + * Latest version of Astro, will be undefined if: + * - unable to check + * - the user has disabled the check + * - the check has not completed yet + * - the user is on the latest version already + */ + latestAstroVersion: string | undefined; + serverIslandMap: NonNullable; + serverIslandNameMap: NonNullable; + injectedTypes: Array; +} + +/** Generic interface for a component (Astro, Svelte, React, etc.) */ +export interface ComponentInstance { + default: AstroComponentFactory; + css?: string[]; + partial?: boolean; + prerender?: boolean; + getStaticPaths?: (options: GetStaticPathsOptions) => GetStaticPathsResult; +} + +export type JSXTransformConfig = Pick< + babel.TransformOptions, + 'presets' | 'plugins' | 'inputSourceMap' +>; + +export interface ManifestData { + routes: RouteData[]; +} + +export interface AstroPluginOptions { + settings: AstroSettings; + logger: Logger; +} diff --git a/packages/astro/src/types/public/common.ts b/packages/astro/src/types/public/common.ts new file mode 100644 index 000000000000..4bb94f5cad5a --- /dev/null +++ b/packages/astro/src/types/public/common.ts @@ -0,0 +1,176 @@ +import type { OmitIndexSignature, Simplify } from '../../type-utils.js'; +import type { APIContext } from './context.js'; + +/** + * getStaticPaths() options + * + * [Astro Reference](https://docs.astro.build/en/reference/api-reference/#getstaticpaths) + */ +export interface GetStaticPathsOptions { + paginate: PaginateFunction; +} + +export type GetStaticPathsItem = { + params: { [K in keyof Params]: Params[K] | number }; + props?: Props; +}; +export type GetStaticPathsResult = GetStaticPathsItem[]; +export type GetStaticPathsResultKeyed = GetStaticPathsResult & { + keyed: Map; +}; + +/** + * Return an array of pages to generate for a [dynamic route](https://docs.astro.build/en/guides/routing/#dynamic-routes). (**SSG Only**) + * + * [Astro Reference](https://docs.astro.build/en/reference/api-reference/#getstaticpaths) + */ +export type GetStaticPaths = ( + options: GetStaticPathsOptions, +) => Promise | GetStaticPathsResult; + +/** + * paginate() Options + * + * [Astro reference](https://docs.astro.build/en/reference/api-reference/#paginate) + */ +export interface PaginateOptions { + /** the number of items per-page (default: `10`) */ + pageSize?: number; + /** key: value object of page params (ex: `{ tag: 'javascript' }`) */ + params?: PaginateParams; + /** object of props to forward to `page` result */ + props?: PaginateProps; +} + +/** + * Represents a single page of data in a paginated collection + * + * [Astro reference](https://docs.astro.build/en/reference/api-reference/#the-pagination-page-prop) + */ +export interface Page { + /** result */ + data: T[]; + /** metadata */ + /** the count of the first item on the page, starting from 0 */ + start: number; + /** the count of the last item on the page, starting from 0 */ + end: number; + /** total number of results */ + total: number; + /** the current page number, starting from 1 */ + currentPage: number; + /** number of items per page (default: 10) */ + size: number; + /** number of last page */ + lastPage: number; + url: { + /** url of the current page */ + current: string; + /** url of the previous page (if there is one) */ + prev: string | undefined; + /** url of the next page (if there is one) */ + next: string | undefined; + /** url of the first page (if the current page is not the first page) */ + first: string | undefined; + /** url of the next page (if the current page in not the last page) */ + last: string | undefined; + }; +} + +export type PaginateFunction = < + PaginateData, + AdditionalPaginateProps extends Props, + AdditionalPaginateParams extends Params, +>( + data: PaginateData[], + args?: PaginateOptions, +) => { + params: Simplify< + { + page: string | undefined; + } & OmitIndexSignature + >; + props: Simplify< + { + page: Page; + } & OmitIndexSignature + >; +}[]; + +export type APIRoute< + Props extends Record = Record, + APIParams extends Record = Record, +> = (context: APIContext) => Response | Promise; + +export type RewritePayload = string | URL | Request; + +export type MiddlewareNext = (rewritePayload?: RewritePayload) => Promise; +export type MiddlewareHandler = ( + context: APIContext, + next: MiddlewareNext, +) => Promise | Response | Promise | void; + +/** + * Infers the shape of the `params` property returned by `getStaticPaths()`. + * + * @example + * ```ts + * import type { GetStaticPaths } from 'astro'; + * + * export const getStaticPaths = (() => { + * return results.map((entry) => ({ + * params: { slug: entry.slug }, + * })); + * }) satisfies GetStaticPaths; + * + * type Params = InferGetStaticParamsType; + * // ^? { slug: string; } + * + * const { slug } = Astro.params as Params; + * ``` + */ +export type InferGetStaticParamsType = T extends ( + opts?: GetStaticPathsOptions, +) => infer R | Promise + ? R extends Array + ? U extends { params: infer P } + ? P + : never + : never + : never; + +/** + * Infers the shape of the `props` property returned by `getStaticPaths()`. + * + * @example + * ```ts + * import type { GetStaticPaths } from 'astro'; + * + * export const getStaticPaths = (() => { + * return results.map((entry) => ({ + * params: { slug: entry.slug }, + * props: { + * propA: true, + * propB: 42 + * }, + * })); + * }) satisfies GetStaticPaths; + * + * type Props = InferGetStaticPropsType; + * // ^? { propA: boolean; propB: number; } + * + * const { propA, propB } = Astro.props; + * ``` + */ +export type InferGetStaticPropsType = T extends ( + opts: GetStaticPathsOptions, +) => infer R | Promise + ? R extends Array + ? U extends { props: infer P } + ? P + : never + : never + : never; + +export type Params = Record; +export type Props = Record; diff --git a/packages/astro/src/@types/astro.ts b/packages/astro/src/types/public/config.ts similarity index 58% rename from packages/astro/src/@types/astro.ts rename to packages/astro/src/types/public/config.ts index a10ad5126226..178b9edf7c96 100644 --- a/packages/astro/src/@types/astro.ts +++ b/packages/astro/src/types/public/config.ts @@ -1,408 +1,38 @@ -import type { OutgoingHttpHeaders } from 'node:http'; -import type { AddressInfo } from 'node:net'; import type { - MarkdownHeading, - MarkdownVFile, RehypePlugins, RemarkPlugins, RemarkRehype, ShikiConfig, } from '@astrojs/markdown-remark'; -import type * as babel from '@babel/core'; -import type * as rollup from 'rollup'; -import type * as vite from 'vite'; -import type { - ActionAccept, - ActionClient, - ActionInputSchema, - ActionReturnType, -} from '../actions/runtime/virtual/server.js'; -import type { RemotePattern } from '../assets/utils/remotePattern.js'; -import type { DataEntry, RenderedContent } from '../content/data-store.js'; -import type { AssetsPrefix, SSRManifest, SerializedSSRManifest } from '../core/app/types.js'; -import type { PageBuildData } from '../core/build/types.js'; -import type { AstroConfigType } from '../core/config/index.js'; -import type { AstroTimer } from '../core/config/timer.js'; -import type { TSConfig } from '../core/config/tsconfig.js'; -import type { AstroCookies } from '../core/cookies/index.js'; -import type { AstroIntegrationLogger, Logger, LoggerLevel } from '../core/logger/core.js'; -import type { EnvSchema } from '../env/schema.js'; -import type { getToolbarServerCommunicationHelpers } from '../integrations/hooks.js'; -import type { AstroPreferences } from '../preferences/index.js'; -import type { - ToolbarAppEventTarget, - ToolbarServerHelpers, -} from '../runtime/client/dev-toolbar/helpers.js'; -import type { AstroDevToolbar, DevToolbarCanvas } from '../runtime/client/dev-toolbar/toolbar.js'; -import type { Icon } from '../runtime/client/dev-toolbar/ui-library/icons.js'; -import type { - DevToolbarBadge, - DevToolbarButton, - DevToolbarCard, - DevToolbarHighlight, - DevToolbarIcon, - DevToolbarRadioCheckbox, - DevToolbarSelect, - DevToolbarToggle, - DevToolbarTooltip, - DevToolbarWindow, -} from '../runtime/client/dev-toolbar/ui-library/index.js'; -import type { AstroComponentFactory, AstroComponentInstance } from '../runtime/server/index.js'; -import type { - TransitionBeforePreparationEvent, - TransitionBeforeSwapEvent, -} from '../transitions/events.js'; -import type { DeepPartial, OmitIndexSignature, Simplify } from '../type-utils.js'; -import type { SUPPORTED_MARKDOWN_FILE_EXTENSIONS } from './../core/constants.js'; - -export type { AstroIntegrationLogger, ToolbarServerHelpers }; - -export type { - MarkdownHeading, - RehypePlugins, - RemarkPlugins, - ShikiConfig, -} from '@astrojs/markdown-remark'; -export type { - ExternalImageService, - ImageService, - LocalImageService, -} from '../assets/services/service.js'; -export type { - GetImageResult, - ImageInputFormat, - ImageMetadata, - ImageOutputFormat, - ImageQuality, - ImageQualityPreset, - ImageTransform, - UnresolvedImageTransform, -} from '../assets/types.js'; -export type { RemotePattern } from '../assets/utils/remotePattern.js'; -export type { AssetsPrefix, SSRManifest } from '../core/app/types.js'; -export type { - AstroCookieGetOptions, - AstroCookieSetOptions, - AstroCookies, -} from '../core/cookies/index.js'; - -export interface AstroBuiltinProps { - 'client:load'?: boolean; - 'client:idle'?: boolean; - 'client:media'?: string; - 'client:visible'?: ClientVisibleOptions | boolean; - 'client:only'?: boolean | string; - 'server:defer'?: boolean; -} - -export type ClientVisibleOptions = Pick; - -export interface TransitionAnimation { - name: string; // The name of the keyframe - delay?: number | string; - duration?: number | string; - easing?: string; - fillMode?: string; - direction?: string; -} - -export interface TransitionAnimationPair { - old: TransitionAnimation | TransitionAnimation[]; - new: TransitionAnimation | TransitionAnimation[]; -} - -export interface TransitionDirectionalAnimations { - forwards: TransitionAnimationPair; - backwards: TransitionAnimationPair; -} - -export type TransitionAnimationValue = - | 'initial' - | 'slide' - | 'fade' - | 'none' - | TransitionDirectionalAnimations; - -// Allow users to extend this for astro-jsx.d.ts - -// eslint-disable-next-line @typescript-eslint/no-empty-object-type -export interface AstroClientDirectives {} - -export interface AstroBuiltinAttributes { - 'class:list'?: - | Record - | Record - | Iterable - | Iterable - | string; - 'set:html'?: any; - 'set:text'?: any; - 'is:raw'?: boolean; - 'transition:animate'?: TransitionAnimationValue; - 'transition:name'?: string; - 'transition:persist'?: boolean | string; -} - -export interface AstroDefineVarsAttribute { - 'define:vars'?: any; -} - -export interface AstroStyleAttributes { - 'is:global'?: boolean; - 'is:inline'?: boolean; -} - -export interface AstroScriptAttributes { - 'is:inline'?: boolean; -} - -export interface AstroSlotAttributes { - 'is:inline'?: boolean; -} +import type { OutgoingHttpHeaders } from 'node:http'; +import type { UserConfig as OriginalViteUserConfig, SSROptions as ViteSSROptions } from 'vite'; +import type { RemotePattern } from '../../assets/utils/remotePattern.js'; +import type { AssetsPrefix } from '../../core/app/types.js'; +import type { AstroConfigType } from '../../core/config/schema.js'; +import type { Logger, LoggerLevel } from '../../core/logger/core.js'; +import type { EnvSchema } from '../../env/schema.js'; +import type { AstroIntegration, RoutePriorityOverride } from './integrations.js'; -export interface AstroComponentMetadata { - displayName: string; - hydrate?: 'load' | 'idle' | 'visible' | 'media' | 'only'; - hydrateArgs?: any; - componentUrl?: string; - componentExport?: { value: string; namespace?: boolean }; - astroStaticSlot: true; -} +export type Locales = (string | { codes: string[]; path: string })[]; -/** The flags supported by the Astro CLI */ -export interface CLIFlags { - root?: string; - site?: string; - base?: string; - host?: string | boolean; - port?: number; - config?: string; - open?: string | boolean; +export interface ImageServiceConfig = Record> { + entrypoint: 'astro/assets/services/sharp' | 'astro/assets/services/squoosh' | (string & {}); + config?: T; } -/** - * Astro global available in all contexts in .astro files - * - * [Astro reference](https://docs.astro.build/reference/api-reference/#astro-global) - */ -export interface AstroGlobal< - Props extends Record = Record, - Self = AstroComponentFactory, - Params extends Record = Record, -> extends AstroGlobalPartial, - AstroSharedContext { - /** - * A full URL object of the request URL. - * Equivalent to: `new URL(Astro.request.url)` - * - * [Astro reference](https://docs.astro.build/en/reference/api-reference/#url) - */ - url: AstroSharedContext['url']; - /** Parameters passed to a dynamic page generated using [getStaticPaths](https://docs.astro.build/en/reference/api-reference/#getstaticpaths) - * - * Example usage: - * ```astro - * --- - * export async function getStaticPaths() { - * return [ - * { params: { id: '1' } }, - * ]; - * } - * - * const { id } = Astro.params; - * --- - *

{id}

- * ``` - * - * [Astro reference](https://docs.astro.build/en/reference/api-reference/#astroparams) - */ - params: AstroSharedContext['params']; - /** List of props passed to this component - * - * A common way to get specific props is through [destructuring](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment), ex: - * ```typescript - * const { name } = Astro.props - * ``` - * - * [Astro reference](https://docs.astro.build/en/basics/astro-components/#component-props) - */ - props: AstroSharedContext['props']; - /** Information about the current request. This is a standard [Request](https://developer.mozilla.org/en-US/docs/Web/API/Request) object - * - * For example, to get a URL object of the current URL, you can use: - * ```typescript - * const url = new URL(Astro.request.url); - * ``` - * - * [Astro reference](https://docs.astro.build/en/reference/api-reference/#astrorequest) - */ - request: Request; - /** Information about the outgoing response. This is a standard [ResponseInit](https://developer.mozilla.org/en-US/docs/Web/API/Response/Response#init) object - * - * For example, to change the status code you can set a different status on this object: - * ```typescript - * Astro.response.status = 404; - * ``` - * - * [Astro reference](https://docs.astro.build/en/reference/api-reference/#astroresponse) - */ - response: ResponseInit & { - readonly headers: Headers; - }; - /** - * Get an action result on the server when using a form POST. - * Expects the action function as a parameter. - * Returns a type-safe result with the action data when - * a matching POST request is received - * and `undefined` otherwise. - * - * Example usage: - * - * ```typescript - * import { actions } from 'astro:actions'; - * - * const result = await Astro.getActionResult(actions.myAction); - * ``` - */ - getActionResult: AstroSharedContext['getActionResult']; - /** - * Call an Action directly from an Astro page or API endpoint. - * Expects the action function as the first parameter, - * and the type-safe action input as the second parameter. - * Returns a Promise with the action result. - * - * Example usage: - * - * ```typescript - * import { actions } from 'astro:actions'; - * - * const result = await Astro.callAction(actions.getPost, { postId: 'test' }); - * ``` - */ - callAction: AstroSharedContext['callAction']; - /** Redirect to another page - * - * Example usage: - * ```typescript - * if(!isLoggedIn) { - * return Astro.redirect('/login'); - * } - * ``` - * - * [Astro reference](https://docs.astro.build/en/reference/api-reference/#astroredirect) - */ - redirect: AstroSharedContext['redirect']; - /** - * It rewrites to another page. As opposed to redirects, the URL won't change, and Astro will render the HTML emitted - * by the rewritten URL passed as argument. - * - * ## Example - * - * ```js - * if (pageIsNotEnabled) { - * return Astro.rewrite('/fallback-page') - * } - * ``` - */ - rewrite: AstroSharedContext['rewrite']; - /** - * The element allows a component to reference itself recursively. - * - * [Astro reference](https://docs.astro.build/en/reference/api-reference/#astroself) - */ - self: Self; - /** Utility functions for modifying an Astro component’s slotted children - * - * [Astro reference](https://docs.astro.build/en/reference/api-reference/#astroslots) - */ - slots: Record & { - /** - * Check whether content for this slot name exists - * - * Example usage: - * ```typescript - * if (Astro.slots.has('default')) { - * // Do something... - * } - * ``` - * - * [Astro reference](https://docs.astro.build/en/reference/api-reference/#astroslots) - */ - has(slotName: string): boolean; - /** - * Asynchronously renders this slot and returns a string - * - * Example usage: - * ```astro - * --- - * let html: string = ''; - * if (Astro.slots.has('default')) { - * html = await Astro.slots.render('default') - * } - * --- - * - * ``` - * - * A second parameter can be used to pass arguments to a slotted callback - * - * Example usage: - * ```astro - * --- - * html = await Astro.slots.render('default', ["Hello", "World"]) - * --- - * ``` - * Each item in the array will be passed as an argument that you can use like so: - * ```astro - * - * {(hello, world) =>
{hello}, {world}!
} - *
- * ``` - * - * [Astro reference](https://docs.astro.build/en/reference/api-reference/#astroslots) - */ - render(slotName: string, args?: any[]): Promise; - }; -} +export type RuntimeMode = 'development' | 'production'; -/** Union type of supported markdown file extensions */ -type MarkdowFileExtension = (typeof SUPPORTED_MARKDOWN_FILE_EXTENSIONS)[number]; +export type ValidRedirectStatus = 300 | 301 | 302 | 303 | 304 | 307 | 308; -export interface AstroGlobalPartial { - /** - * Fetch local files into your static site setup - * - * Example usage: - * ```typescript - * const posts = await Astro.glob('../pages/post/*.md'); - * ``` - * - * [Astro reference](https://docs.astro.build/en/reference/api-reference/#astroglob) - */ - glob(globStr: `${any}.astro`): Promise; - glob>( - globStr: `${any}${MarkdowFileExtension}`, - ): Promise[]>; - glob>(globStr: `${any}.mdx`): Promise[]>; - glob>(globStr: string): Promise; - /** - * Returns a [URL](https://developer.mozilla.org/en-US/docs/Web/API/URL) object built from the [site](https://docs.astro.build/en/reference/configuration-reference/#site) config option - * - * [Astro reference](https://docs.astro.build/en/reference/api-reference/#astrosite) - */ - site: URL | undefined; - /** - * Returns a string with the current version of Astro. - * - * Useful for using `` or crediting Astro in a site footer. - * - * [HTML Specification for `generator`](https://html.spec.whatwg.org/multipage/semantics.html#meta-generator) - * - * [Astro reference](https://docs.astro.build/en/reference/api-reference/#astrogenerator) - */ - generator: string; -} +export type RedirectConfig = + | string + | { + status: ValidRedirectStatus; + destination: string; + priority?: RoutePriorityOverride; + }; -type ServerConfig = { +export type ServerConfig = { /** * @name server.host * @type {string | boolean} @@ -456,14 +86,17 @@ type ServerConfig = { open?: string | boolean; }; -export interface ViteUserConfig extends vite.UserConfig { - ssr?: vite.SSROptions; +export interface ViteUserConfig extends OriginalViteUserConfig { + ssr?: ViteSSROptions; } -export interface ImageServiceConfig = Record> { - entrypoint: 'astro/assets/services/sharp' | 'astro/assets/services/squoosh' | (string & {}); - config?: T; -} +// NOTE(fks): We choose to keep our hand-generated AstroUserConfig interface so that +// we can add JSDoc-style documentation and link to the definition file in our repo. +// However, Zod comes with the ability to auto-generate AstroConfig from the schema +// above. If we ever get to the point where we no longer need the dedicated type, +// consider replacing it with the following lines: +// export interface AstroUserConfig extends z.input { +// } /** * Astro User Config @@ -2407,58 +2040,6 @@ export interface AstroUserConfig { }; } -// NOTE(fks): We choose to keep our hand-generated AstroUserConfig interface so that -// we can add JSDoc-style documentation and link to the definition file in our repo. -// However, Zod comes with the ability to auto-generate AstroConfig from the schema -// above. If we ever get to the point where we no longer need the dedicated -// @types/config.ts file, consider replacing it with the following lines: -// -// export interface AstroUserConfig extends z.input { -// } - -/** - * IDs for different stages of JS script injection: - * - "before-hydration": Imported client-side, before the hydration script runs. Processed & resolved by Vite. - * - "head-inline": Injected into a script tag in the `` of every page. Not processed or resolved by Vite. - * - "page": Injected into the JavaScript bundle of every page. Processed & resolved by Vite. - * - "page-ssr": Injected into the frontmatter of every Astro page. Processed & resolved by Vite. - */ -export type InjectedScriptStage = 'before-hydration' | 'head-inline' | 'page' | 'page-ssr'; - -/** - * IDs for different priorities of injected routes and redirects: - * - "normal": Merge with discovered file-based project routes, behaving the same as if the route - * was defined as a file in the project. - * - "legacy": Use the old ordering of routes. Inject routes will override any file-based project route, - * and redirects will be overridden by any project route on conflict. - */ -export type RoutePriorityOverride = 'normal' | 'legacy'; - -export interface InjectedRoute { - pattern: string; - entrypoint: string; - prerender?: boolean; -} - -export interface ResolvedInjectedRoute extends InjectedRoute { - resolvedEntryPoint?: URL; -} - -export interface RouteOptions { - /** - * The path to this route relative to the project root. The slash is normalized as forward slash - * across all OS. - * @example "src/pages/blog/[...slug].astro" - */ - readonly component: string; - /** - * Whether this route should be prerendered. If the route has an explicit `prerender` export, - * the value will be passed here. Otherwise, it's undefined and will fallback to a prerender - * default depending on the `output` option. - */ - prerender?: boolean; -} - /** * Resolved Astro Config * Config with user settings along with all defaults filled in. @@ -2510,1230 +2091,10 @@ export interface AstroInlineOnlyConfig { logger?: Logger; } -export type ContentEntryModule = { - id: string; - collection: string; - slug: string; - body: string; - data: Record; - _internal: { - rawData: string; - filePath: string; - }; -}; - -export type DataEntryModule = { - id: string; - collection: string; - data: Record; - _internal: { - rawData: string; - filePath: string; - }; -}; - -export type ContentEntryRenderFuction = (entry: DataEntry) => Promise; - -export interface ContentEntryType { - extensions: string[]; - getEntryInfo(params: { - fileUrl: URL; - contents: string; - }): GetContentEntryInfoReturnType | Promise; - getRenderModule?( - this: rollup.PluginContext, - params: { - contents: string; - fileUrl: URL; - viteId: string; - }, - ): rollup.LoadResult | Promise; - contentModuleTypes?: string; - getRenderFunction?(settings: AstroSettings): Promise; - - /** - * Handle asset propagation for rendered content to avoid bleed. - * Ex. MDX content can import styles and scripts, so `handlePropagation` should be true. - * @default true - */ - handlePropagation?: boolean; -} - -type GetContentEntryInfoReturnType = { - data: Record; - /** - * Used for error hints to point to correct line and location - * Should be the untouched data as read from the file, - * including newlines - */ - rawData: string; - body: string; - slug: string; -}; - -export interface DataEntryType { - extensions: string[]; - getEntryInfo(params: { - fileUrl: URL; - contents: string; - }): GetDataEntryInfoReturnType | Promise; -} - -export type GetDataEntryInfoReturnType = { data: Record; rawData?: string }; - -export interface AstroAdapterFeatures { - /** - * Creates an edge function that will communiate with the Astro middleware - */ - edgeMiddleware: boolean; - /** - * SSR only. Each route becomes its own function/file. - */ - functionPerRoute: boolean; -} - -export interface InjectedType { - filename: string; - content: string; -} - -export interface AstroSettings { - config: AstroConfig; - adapter: AstroAdapter | undefined; - preferences: AstroPreferences; - injectedRoutes: InjectedRoute[]; - resolvedInjectedRoutes: ResolvedInjectedRoute[]; - pageExtensions: string[]; - contentEntryTypes: ContentEntryType[]; - dataEntryTypes: DataEntryType[]; - renderers: AstroRenderer[]; - scripts: { - stage: InjectedScriptStage; - content: string; - }[]; - /** - * Map of directive name (e.g. `load`) to the directive script code - */ - clientDirectives: Map; - devToolbarApps: (DevToolbarAppEntry | string)[]; - middlewares: { pre: string[]; post: string[] }; - tsConfig: TSConfig | undefined; - tsConfigPath: string | undefined; - watchFiles: string[]; - timer: AstroTimer; - dotAstroDir: URL; - /** - * Latest version of Astro, will be undefined if: - * - unable to check - * - the user has disabled the check - * - the check has not completed yet - * - the user is on the latest version already - */ - latestAstroVersion: string | undefined; - serverIslandMap: NonNullable; - serverIslandNameMap: NonNullable; - injectedTypes: Array; -} - -export type AsyncRendererComponentFn = ( - Component: any, - props: any, - slots: Record, - metadata?: AstroComponentMetadata, -) => Promise; - -/** Generic interface for a component (Astro, Svelte, React, etc.) */ -export interface ComponentInstance { - default: AstroComponentFactory; - css?: string[]; - partial?: boolean; - prerender?: boolean; - getStaticPaths?: (options: GetStaticPathsOptions) => GetStaticPathsResult; -} - -export interface AstroInstance { - file: string; - url: string | undefined; - default: AstroComponentFactory; -} - -export interface MarkdownInstance> { - frontmatter: T; - /** Absolute file path (e.g. `/home/user/projects/.../file.md`) */ - file: string; - /** Browser URL for files under `/src/pages` (e.g. `/en/guides/markdown-content`) */ - url: string | undefined; - /** Component to render content in `.astro` files. Usage: `` */ - Content: AstroComponentFactory; - /** raw Markdown file content, excluding layout HTML and YAML frontmatter */ - rawContent(): string; - /** Markdown file compiled to HTML, excluding layout HTML */ - compiledContent(): string; - /** List of headings (h1 -> h6) with associated metadata */ - getHeadings(): MarkdownHeading[]; - default: AstroComponentFactory; -} - -type MD = MarkdownInstance>; - -export type MDXInstance> = Omit< - MarkdownInstance, - 'rawContent' | 'compiledContent' ->; - -export interface MarkdownLayoutProps> { - frontmatter: { - file: MarkdownInstance['file']; - url: MarkdownInstance['url']; - } & T; - file: MarkdownInstance['file']; - url: MarkdownInstance['url']; - headings: MarkdownHeading[]; - rawContent: MarkdownInstance['rawContent']; - compiledContent: MarkdownInstance['compiledContent']; -} - -export type MDXLayoutProps> = Omit< - MarkdownLayoutProps, - 'rawContent' | 'compiledContent' ->; - -export type GetHydrateCallback = () => Promise<() => void | Promise>; - -/** - * getStaticPaths() options - * - * [Astro Reference](https://docs.astro.build/en/reference/api-reference/#getstaticpaths) - */ -export interface GetStaticPathsOptions { - paginate: PaginateFunction; -} - -export type GetStaticPathsItem = { - params: { [K in keyof Params]: Params[K] | number }; - props?: Props; -}; -export type GetStaticPathsResult = GetStaticPathsItem[]; -export type GetStaticPathsResultKeyed = GetStaticPathsResult & { - keyed: Map; -}; - -/** - * Return an array of pages to generate for a [dynamic route](https://docs.astro.build/en/guides/routing/#dynamic-routes). (**SSG Only**) - * - * [Astro Reference](https://docs.astro.build/en/reference/api-reference/#getstaticpaths) - */ -export type GetStaticPaths = ( - options: GetStaticPathsOptions, -) => Promise | GetStaticPathsResult; - -/** - * Infers the shape of the `params` property returned by `getStaticPaths()`. - * - * @example - * ```ts - * import type { GetStaticPaths } from 'astro'; - * - * export const getStaticPaths = (() => { - * return results.map((entry) => ({ - * params: { slug: entry.slug }, - * })); - * }) satisfies GetStaticPaths; - * - * type Params = InferGetStaticParamsType; - * // ^? { slug: string; } - * - * const { slug } = Astro.params as Params; - * ``` - */ -export type InferGetStaticParamsType = T extends ( - opts?: GetStaticPathsOptions, -) => infer R | Promise - ? R extends Array - ? U extends { params: infer P } - ? P - : never - : never - : never; - -/** - * Infers the shape of the `props` property returned by `getStaticPaths()`. - * - * @example - * ```ts - * import type { GetStaticPaths } from 'astro'; - * - * export const getStaticPaths = (() => { - * return results.map((entry) => ({ - * params: { slug: entry.slug }, - * props: { - * propA: true, - * propB: 42 - * }, - * })); - * }) satisfies GetStaticPaths; - * - * type Props = InferGetStaticPropsType; - * // ^? { propA: boolean; propB: number; } - * - * const { propA, propB } = Astro.props; - * ``` - */ -export type InferGetStaticPropsType = T extends ( - opts: GetStaticPathsOptions, -) => infer R | Promise - ? R extends Array - ? U extends { props: infer P } - ? P - : never - : never - : never; - -export interface HydrateOptions { - name: string; - value?: string; -} - -export type JSXTransformConfig = Pick< - babel.TransformOptions, - 'presets' | 'plugins' | 'inputSourceMap' ->; - -export type JSXTransformFn = (options: { - mode: string; - ssr: boolean; -}) => Promise; - -export interface ManifestData { - routes: RouteData[]; -} - -/** @deprecated Type is no longer used by exported APIs */ -export interface MarkdownMetadata { - headings: MarkdownHeading[]; - source: string; - html: string; -} - -/** @deprecated Type is no longer used by exported APIs */ -export interface MarkdownRenderingResult { - metadata: MarkdownMetadata; - vfile: MarkdownVFile; - code: string; -} - -/** @deprecated Type is no longer used by exported APIs */ -export interface MarkdownParserResponse extends MarkdownRenderingResult { - frontmatter: MD['frontmatter']; -} - -/** - * The `content` prop given to a Layout - * - * [Astro reference](https://docs.astro.build/en/guides/markdown-content/#markdown-layouts) - */ -export type MarkdownContent = Record> = T & { - astro: MarkdownMetadata; - url: string | undefined; - file: string; -}; - -/** - * paginate() Options - * - * [Astro reference](https://docs.astro.build/en/reference/api-reference/#paginate) - */ -export interface PaginateOptions { - /** the number of items per-page (default: `10`) */ - pageSize?: number; - /** key: value object of page params (ex: `{ tag: 'javascript' }`) */ - params?: PaginateParams; - /** object of props to forward to `page` result */ - props?: PaginateProps; -} - -/** - * Represents a single page of data in a paginated collection - * - * [Astro reference](https://docs.astro.build/en/reference/api-reference/#the-pagination-page-prop) - */ -export interface Page { - /** result */ - data: T[]; - /** metadata */ - /** the count of the first item on the page, starting from 0 */ - start: number; - /** the count of the last item on the page, starting from 0 */ - end: number; - /** total number of results */ - total: number; - /** the current page number, starting from 1 */ - currentPage: number; - /** number of items per page (default: 10) */ - size: number; - /** number of last page */ - lastPage: number; - url: { - /** url of the current page */ - current: string; - /** url of the previous page (if there is one) */ - prev: string | undefined; - /** url of the next page (if there is one) */ - next: string | undefined; - /** url of the first page (if the current page is not the first page) */ - first: string | undefined; - /** url of the next page (if the current page in not the last page) */ - last: string | undefined; - }; +// HACK! astro:db augment this type that is used in the config +declare global { + // eslint-disable-next-line @typescript-eslint/no-namespace + namespace Config { + type Database = Record; + } } - -export type PaginateFunction = < - PaginateData, - AdditionalPaginateProps extends Props, - AdditionalPaginateParams extends Params, ->( - data: PaginateData[], - args?: PaginateOptions, -) => { - params: Simplify< - { - page: string | undefined; - } & OmitIndexSignature - >; - props: Simplify< - { - page: Page; - } & OmitIndexSignature - >; -}[]; - -export type Params = Record; - -export type SupportsKind = 'unsupported' | 'stable' | 'experimental' | 'deprecated'; - -export type AstroFeatureMap = { - /** - * The adapter is able serve static pages - */ - staticOutput?: SupportsKind; - /** - * The adapter is able to serve pages that are static or rendered via server - */ - hybridOutput?: SupportsKind; - /** - * The adapter is able to serve SSR pages - */ - serverOutput?: SupportsKind; - /** - * The adapter can emit static assets - */ - assets?: AstroAssetsFeature; - - /** - * List of features that orbit around the i18n routing - */ - i18nDomains?: SupportsKind; - - /** - * The adapter is able to support `getSecret` exported from `astro:env/server` - */ - envGetSecret?: SupportsKind; -}; - -export interface AstroAssetsFeature { - supportKind?: SupportsKind; - /** - * Whether if this adapter deploys files in an environment that is compatible with the library `sharp` - */ - isSharpCompatible?: boolean; - /** - * Whether if this adapter deploys files in an environment that is compatible with the library `squoosh` - */ - isSquooshCompatible?: boolean; -} - -export interface AstroInternationalizationFeature { - /** - * The adapter should be able to create the proper redirects - */ - domains?: SupportsKind; -} - -export type Locales = (string | { codes: string[]; path: string })[]; - -export interface AstroAdapter { - name: string; - serverEntrypoint?: string; - previewEntrypoint?: string; - exports?: string[]; - args?: any; - adapterFeatures?: AstroAdapterFeatures; - /** - * List of features supported by an adapter. - * - * If the adapter is not able to handle certain configurations, Astro will throw an error. - */ - supportedAstroFeatures: AstroFeatureMap; -} - -export type ValidRedirectStatus = 300 | 301 | 302 | 303 | 304 | 307 | 308; - -// Shared types between `Astro` global and API context object -interface AstroSharedContext< - Props extends Record = Record, - RouteParams extends Record = Record, -> { - /** - * The address (usually IP address) of the user. - * - * Throws an error if used within a static site, or within a prerendered page. - */ - clientAddress: string; - /** - * Utility for getting and setting the values of cookies. - */ - cookies: AstroCookies; - /** - * Information about the current request. This is a standard [Request](https://developer.mozilla.org/en-US/docs/Web/API/Request) object - */ - request: Request; - /** - * A full URL object of the request URL. - */ - url: URL; - /** - * Get action result on the server when using a form POST. - */ - getActionResult: < - TAccept extends ActionAccept, - TInputSchema extends ActionInputSchema, - TAction extends ActionClient, - >( - action: TAction, - ) => ActionReturnType | undefined; - /** - * Call action handler from the server. - */ - callAction: < - TAccept extends ActionAccept, - TInputSchema extends ActionInputSchema, - TOutput, - TAction extends - | ActionClient - | ActionClient['orThrow'], - >( - action: TAction, - input: Parameters[0], - ) => Promise>; - /** - * Route parameters for this request if this is a dynamic route. - */ - params: RouteParams; - /** - * List of props returned for this path by `getStaticPaths` (**Static Only**). - */ - props: Props; - /** - * Redirect to another page (**SSR Only**). - */ - redirect(path: string, status?: ValidRedirectStatus): Response; - - /** - * It rewrites to another page. As opposed to redirects, the URL won't change, and Astro will render the HTML emitted - * by the rerouted URL passed as argument. - * - * ## Example - * - * ```js - * if (pageIsNotEnabled) { - * return Astro.rewrite('/fallback-page') - * } - * ``` - */ - rewrite(rewritePayload: RewritePayload): Promise; - - /** - * Object accessed via Astro middleware - */ - locals: App.Locals; - - /** - * The current locale that is computed from the `Accept-Language` header of the browser (**SSR Only**). - */ - preferredLocale: string | undefined; - - /** - * The list of locales computed from the `Accept-Language` header of the browser, sorted by quality value (**SSR Only**). - */ - - preferredLocaleList: string[] | undefined; - - /** - * The current locale computed from the URL of the request. It matches the locales in `i18n.locales`, and returns `undefined` otherwise. - */ - currentLocale: string | undefined; -} - -/** - * The `APIContext` is the object made available to endpoints and middleware. - * It is a subset of the `Astro` global object available in pages. - * - * [Reference](https://docs.astro.build/en/reference/api-reference/#endpoint-context) - */ -export interface APIContext< - Props extends Record = Record, - APIParams extends Record = Record, -> extends AstroSharedContext { - /** - * The site provided in the astro config, parsed as an instance of `URL`, without base. - * `undefined` if the site is not provided in the config. - */ - site: URL | undefined; - /** - * A human-readable string representing the Astro version used to create the project. - * For example, `"Astro v1.1.1"`. - */ - generator: string; - /** - * The url of the current request, parsed as an instance of `URL`. - * - * Equivalent to: - * ```ts - * new URL(context.request.url) - * ``` - */ - url: AstroSharedContext['url']; - /** - * Parameters matching the page’s dynamic route pattern. - * In static builds, this will be the `params` generated by `getStaticPaths`. - * In SSR builds, this can be any path segments matching the dynamic route pattern. - * - * Example usage: - * ```ts - * import type { APIContext } from "astro" - * - * export function getStaticPaths() { - * return [ - * { params: { id: '0' }, props: { name: 'Sarah' } }, - * { params: { id: '1' }, props: { name: 'Chris' } }, - * { params: { id: '2' }, props: { name: 'Fuzzy' } }, - * ]; - * } - * - * export async function GET({ params }: APIContext) { - * return new Response(`Hello user ${params.id}!`) - * } - * ``` - * - * [Reference](https://docs.astro.build/en/reference/api-reference/#contextparams) - */ - params: AstroSharedContext['params']; - /** - * List of props passed from `getStaticPaths`. Only available to static builds. - * - * Example usage: - * ```ts - * import type { APIContext } from "astro" - * - * export function getStaticPaths() { - * return [ - * { params: { id: '0' }, props: { name: 'Sarah' } }, - * { params: { id: '1' }, props: { name: 'Chris' } }, - * { params: { id: '2' }, props: { name: 'Fuzzy' } }, - * ]; - * } - * - * export function GET({ props }: APIContext): Response { - * return new Response(`Hello ${props.name}!`); - * } - * ``` - * - * [Reference](https://docs.astro.build/en/reference/api-reference/#contextprops) - */ - props: AstroSharedContext['props']; - /** - * Create a response that redirects to another page. - * - * Example usage: - * ```ts - * // src/pages/secret.ts - * export function GET({ redirect }) { - * return redirect('/login'); - * } - * ``` - * - * [Reference](https://docs.astro.build/en/guides/api-reference/#contextredirect) - */ - redirect: AstroSharedContext['redirect']; - - /** - * It reroutes to another page. As opposed to redirects, the URL won't change, and Astro will render the HTML emitted - * by the rerouted URL passed as argument. - * - * ## Example - * - * ```ts - * // src/pages/secret.ts - * export function GET(ctx) { - * return ctx.rewrite(new URL("../"), ctx.url); - * } - * ``` - */ - rewrite: AstroSharedContext['rewrite']; - - /** - * An object that middlewares can use to store extra information related to the request. - * - * It will be made available to pages as `Astro.locals`, and to endpoints as `context.locals`. - * - * Example usage: - * - * ```ts - * // src/middleware.ts - * import { defineMiddleware } from "astro:middleware"; - * - * export const onRequest = defineMiddleware((context, next) => { - * context.locals.greeting = "Hello!"; - * return next(); - * }); - * ``` - * Inside a `.astro` file: - * ```astro - * --- - * // src/pages/index.astro - * const greeting = Astro.locals.greeting; - * --- - *

{greeting}

- * ``` - * - * [Reference](https://docs.astro.build/en/reference/api-reference/#contextlocals) - */ - locals: App.Locals; - - /** - * Available only when `i18n` configured and in SSR. - * - * It represents the preferred locale of the user. It's computed by checking the supported locales in `i18n.locales` - * and locales supported by the users's browser via the header `Accept-Language` - * - * For example, given `i18n.locales` equals to `['fr', 'de']`, and the `Accept-Language` value equals to `en, de;q=0.2, fr;q=0.6`, the - * `Astro.preferredLanguage` will be `fr` because `en` is not supported, its [quality value] is the highest. - * - * [quality value]: https://developer.mozilla.org/en-US/docs/Glossary/Quality_values - */ - preferredLocale: string | undefined; - - /** - * Available only when `i18n` configured and in SSR. - * - * It represents the list of the preferred locales that are supported by the application. The list is sorted via [quality value]. - * - * For example, given `i18n.locales` equals to `['fr', 'pt', 'de']`, and the `Accept-Language` value equals to `en, de;q=0.2, fr;q=0.6`, the - * `Astro.preferredLocaleList` will be equal to `['fs', 'de']` because `en` isn't supported, and `pt` isn't part of the locales contained in the - * header. - * - * When the `Accept-Header` is `*`, the original `i18n.locales` are returned. The value `*` means no preferences, so Astro returns all the supported locales. - * - * [quality value]: https://developer.mozilla.org/en-US/docs/Glossary/Quality_values - */ - preferredLocaleList: string[] | undefined; - - /** - * The current locale computed from the URL of the request. It matches the locales in `i18n.locales`, and returns `undefined` otherwise. - */ - currentLocale: string | undefined; -} - -export type APIRoute< - Props extends Record = Record, - APIParams extends Record = Record, -> = (context: APIContext) => Response | Promise; - -export interface EndpointHandler { - [method: string]: APIRoute; -} - -export type Props = Record; - -export interface AstroRenderer { - /** Name of the renderer. */ - name: string; - /** Import entrypoint for the client/browser renderer. */ - clientEntrypoint?: string; - /** Import entrypoint for the server/build/ssr renderer. */ - serverEntrypoint: string; - /** @deprecated Vite plugins should transform the JSX instead */ - jsxImportSource?: string; - /** @deprecated Vite plugins should transform the JSX instead */ - jsxTransformOptions?: JSXTransformFn; -} - -export interface NamedSSRLoadedRendererValue extends SSRLoadedRendererValue { - name: string; -} - -export interface SSRLoadedRendererValue { - name?: string; - check: AsyncRendererComponentFn; - renderToStaticMarkup: AsyncRendererComponentFn<{ - html: string; - attrs?: Record; - }>; - supportsAstroStaticSlot?: boolean; - /** - * If provided, Astro will call this function and inject the returned - * script in the HTML before the first component handled by this renderer. - * - * This feature is needed by some renderers (in particular, by Solid). The - * Solid official hydration script sets up a page-level data structure. - * It is mainly used to transfer data between the server side render phase - * and the browser application state. Solid Components rendered later in - * the HTML may inject tiny scripts into the HTML that call into this - * page-level data structure. - */ - renderHydrationScript?: () => string; -} - -export interface SSRLoadedRenderer extends Pick { - ssr: SSRLoadedRendererValue; -} - -export type HookParameters< - Hook extends keyof AstroIntegration['hooks'], - Fn = AstroIntegration['hooks'][Hook], -> = Fn extends (...args: any) => any ? Parameters[0] : never; - -declare global { - // eslint-disable-next-line @typescript-eslint/no-namespace - namespace Astro { - export interface IntegrationHooks { - 'astro:config:setup': (options: { - config: AstroConfig; - command: 'dev' | 'build' | 'preview'; - isRestart: boolean; - updateConfig: (newConfig: DeepPartial) => AstroConfig; - addRenderer: (renderer: AstroRenderer) => void; - addWatchFile: (path: URL | string) => void; - injectScript: (stage: InjectedScriptStage, content: string) => void; - injectRoute: (injectRoute: InjectedRoute) => void; - addClientDirective: (directive: ClientDirectiveConfig) => void; - /** - * @deprecated Use `addDevToolbarApp` instead. - * TODO: Fully remove in Astro 5.0 - */ - addDevOverlayPlugin: (entrypoint: string) => void; - // TODO: Deprecate the `string` overload once a few apps have been migrated to the new API. - addDevToolbarApp: (entrypoint: DevToolbarAppEntry | string) => void; - addMiddleware: (mid: AstroIntegrationMiddleware) => void; - logger: AstroIntegrationLogger; - // TODO: Add support for `injectElement()` for full HTML element injection, not just scripts. - // This may require some refactoring of `scripts`, `styles`, and `links` into something - // more generalized. Consider the SSR use-case as well. - // injectElement: (stage: vite.HtmlTagDescriptor, element: string) => void; - }) => void | Promise; - 'astro:config:done': (options: { - config: AstroConfig; - setAdapter: (adapter: AstroAdapter) => void; - injectTypes: (injectedType: InjectedType) => URL; - logger: AstroIntegrationLogger; - }) => void | Promise; - 'astro:server:setup': (options: { - server: vite.ViteDevServer; - logger: AstroIntegrationLogger; - toolbar: ReturnType; - }) => void | Promise; - 'astro:server:start': (options: { - address: AddressInfo; - logger: AstroIntegrationLogger; - }) => void | Promise; - 'astro:server:done': (options: { logger: AstroIntegrationLogger }) => void | Promise; - 'astro:build:ssr': (options: { - manifest: SerializedSSRManifest; - /** - * This maps a {@link RouteData} to an {@link URL}, this URL represents - * the physical file you should import. - */ - entryPoints: Map; - /** - * File path of the emitted middleware - */ - middlewareEntryPoint: URL | undefined; - logger: AstroIntegrationLogger; - }) => void | Promise; - 'astro:build:start': (options: { logger: AstroIntegrationLogger }) => void | Promise; - 'astro:build:setup': (options: { - vite: vite.InlineConfig; - pages: Map; - target: 'client' | 'server'; - updateConfig: (newConfig: vite.InlineConfig) => void; - logger: AstroIntegrationLogger; - }) => void | Promise; - 'astro:build:generated': (options: { - dir: URL; - logger: AstroIntegrationLogger; - }) => void | Promise; - 'astro:build:done': (options: { - pages: { pathname: string }[]; - dir: URL; - routes: RouteData[]; - logger: AstroIntegrationLogger; - cacheManifest: boolean; - }) => void | Promise; - 'astro:route:setup': (options: { - route: RouteOptions; - logger: AstroIntegrationLogger; - }) => void | Promise; - } - } -} - -export interface AstroIntegration { - /** The name of the integration. */ - name: string; - /** The different hooks available to extend. */ - hooks: { - [K in keyof Astro.IntegrationHooks]?: Astro.IntegrationHooks[K]; - } & Partial>; -} - -export type RewritePayload = string | URL | Request; - -export type MiddlewareNext = (rewritePayload?: RewritePayload) => Promise; -export type MiddlewareHandler = ( - context: APIContext, - next: MiddlewareNext, -) => Promise | Response | Promise | void; - -// NOTE: when updating this file with other functions, -// remember to update `plugin-page.ts` too, to add that function as a no-op function. -export type AstroMiddlewareInstance = { - onRequest?: MiddlewareHandler; -}; - -export type AstroIntegrationMiddleware = { - order: 'pre' | 'post'; - entrypoint: string; -}; - -export interface AstroPluginOptions { - settings: AstroSettings; - logger: Logger; -} - -/** - * - page: a route that lives in the file system, usually an Astro component - * - endpoint: a route that lives in the file system, usually a JS file that exposes endpoints methods - * - redirect: a route points to another route that lives in the file system - * - fallback: a route that doesn't exist in the file system that needs to be handled with other means, usually the middleware - */ -export type RouteType = 'page' | 'endpoint' | 'redirect' | 'fallback'; - -export interface RoutePart { - content: string; - dynamic: boolean; - spread: boolean; -} - -type RedirectConfig = - | string - | { - status: ValidRedirectStatus; - destination: string; - priority?: RoutePriorityOverride; - }; - -export interface RouteData { - route: string; - component: string; - generate: (data?: any) => string; - params: string[]; - pathname?: string; - // expose the real path name on SSG - distURL?: URL; - pattern: RegExp; - segments: RoutePart[][]; - type: RouteType; - prerender: boolean; - redirect?: RedirectConfig; - redirectRoute?: RouteData; - fallbackRoutes: RouteData[]; - isIndex: boolean; -} - -export type RedirectRouteData = RouteData & { - redirect: string; -}; - -export type SerializedRouteData = Omit< - RouteData, - 'generate' | 'pattern' | 'redirectRoute' | 'fallbackRoutes' -> & { - generate: undefined; - pattern: string; - redirectRoute: SerializedRouteData | undefined; - fallbackRoutes: SerializedRouteData[]; - _meta: { - trailingSlash: AstroConfig['trailingSlash']; - }; -}; - -export type RuntimeMode = 'development' | 'production'; - -export type SSRError = Error & vite.ErrorPayload['err']; - -export interface SSRElement { - props: Record; - children: string; -} - -/** - * A hint on whether the Astro runtime needs to wait on a component to render head - * content. The meanings: - * - * - __none__ (default) The component does not propagation head content. - * - __self__ The component appends head content. - * - __in-tree__ Another component within this component's dependency tree appends head content. - * - * These are used within the runtime to know whether or not a component should be waited on. - */ -export type PropagationHint = 'none' | 'self' | 'in-tree'; - -export type SSRComponentMetadata = { - propagation: PropagationHint; - containsHead: boolean; -}; - -export interface SSRResult { - /** - * Whether the page has failed with a non-recoverable error, or the client disconnected. - */ - cancelled: boolean; - base: string; - styles: Set; - scripts: Set; - links: Set; - componentMetadata: Map; - inlinedScripts: Map; - createAstro( - Astro: AstroGlobalPartial, - props: Record, - slots: Record | null, - ): AstroGlobal; - params: Params; - resolve: (s: string) => Promise; - response: AstroGlobal['response']; - request: AstroGlobal['request']; - actionResult?: ReturnType; - renderers: SSRLoadedRenderer[]; - /** - * Map of directive name (e.g. `load`) to the directive script code - */ - clientDirectives: Map; - compressHTML: boolean; - partial: boolean; - /** - * Only used for logging - */ - pathname: string; - cookies: AstroCookies | undefined; - serverIslandNameMap: Map; - trailingSlash: AstroConfig['trailingSlash']; - key: Promise; - _metadata: SSRMetadata; -} - -/** - * Ephemeral and mutable state during rendering that doesn't rely - * on external configuration - */ -export interface SSRMetadata { - hasHydrationScript: boolean; - /** - * Names of renderers that have injected their hydration scripts - * into the current page. For example, Solid SSR needs a hydration - * script in the page HTML before the first Solid component. - */ - rendererSpecificHydrationScripts: Set; - /** - * Used by `renderScript` to track script ids that have been rendered, - * so we only render each once. - */ - renderedScripts: Set; - hasDirectives: Set; - hasRenderedHead: boolean; - headInTree: boolean; - extraHead: string[]; - propagators: Set; -} - -/* Preview server stuff */ -export interface PreviewServer { - host?: string; - port: number; - closed(): Promise; - stop(): Promise; -} - -export interface PreviewServerParams { - outDir: URL; - client: URL; - serverEntrypoint: URL; - host: string | undefined; - port: number; - base: string; - logger: AstroIntegrationLogger; - headers?: OutgoingHttpHeaders; -} - -export type CreatePreviewServer = ( - params: PreviewServerParams, -) => PreviewServer | Promise; - -export interface PreviewModule { - default: CreatePreviewServer; -} - -/* Client Directives */ -type DirectiveHydrate = () => Promise; -type DirectiveLoad = () => Promise; - -type DirectiveOptions = { - /** - * The component displayName - */ - name: string; - /** - * The attribute value provided - */ - value: string; -}; - -export type ClientDirective = ( - load: DirectiveLoad, - options: DirectiveOptions, - el: HTMLElement, -) => void; - -export interface ClientDirectiveConfig { - name: string; - entrypoint: string; -} - -type DevToolbarAppMeta = { - id: string; - name: string; - icon?: Icon; -}; - -// The param passed to `addDevToolbarApp` in the integration -export type DevToolbarAppEntry = DevToolbarAppMeta & { - entrypoint: string; -}; - -// Public API for the dev toolbar -export type DevToolbarApp = { - /** - * @deprecated The `id`, `name`, and `icon` properties should now be defined when using `addDevToolbarApp`. - * - * Ex: `addDevToolbarApp({ id: 'my-app', name: 'My App', icon: '🚀', entrypoint: '/path/to/app' })` - * - * In the future, putting these properties directly on the app object will be removed. - */ - id?: string; - /** - * @deprecated The `id`, `name`, and `icon` properties should now be defined when using `addDevToolbarApp`. - * - * Ex: `addDevToolbarApp({ id: 'my-app', name: 'My App', icon: '🚀', entrypoint: '/path/to/app' })` - * - * In the future, putting these properties directly on the app object will be removed. - */ - name?: string; - /** - * @deprecated The `id`, `name`, and `icon` properties should now be defined when using `addDevToolbarApp`. - * - * Ex: `addDevToolbarApp({ id: 'my-app', name: 'My App', icon: '🚀', entrypoint: '/path/to/app' })` - * - * In the future, putting these properties directly on the app object will be removed. - */ - icon?: Icon; - init?( - canvas: ShadowRoot, - app: ToolbarAppEventTarget, - server: ToolbarServerHelpers, - ): void | Promise; - beforeTogglingOff?(canvas: ShadowRoot): boolean | Promise; -}; - -// An app that has been loaded and as such contain all of its properties -export type ResolvedDevToolbarApp = DevToolbarAppMeta & Omit; - -// TODO: Remove in Astro 5.0 -export type DevOverlayPlugin = DevToolbarApp; - -export type DevToolbarMetadata = Window & - typeof globalThis & { - __astro_dev_toolbar__: { - root: string; - version: string; - latestAstroVersion: AstroSettings['latestAstroVersion']; - debugInfo: string; - }; - }; - -declare global { - interface HTMLElementTagNameMap { - 'astro-dev-toolbar': AstroDevToolbar; - 'astro-dev-toolbar-window': DevToolbarWindow; - 'astro-dev-toolbar-app-canvas': DevToolbarCanvas; - 'astro-dev-toolbar-tooltip': DevToolbarTooltip; - 'astro-dev-toolbar-highlight': DevToolbarHighlight; - 'astro-dev-toolbar-toggle': DevToolbarToggle; - 'astro-dev-toolbar-badge': DevToolbarBadge; - 'astro-dev-toolbar-button': DevToolbarButton; - 'astro-dev-toolbar-icon': DevToolbarIcon; - 'astro-dev-toolbar-card': DevToolbarCard; - 'astro-dev-toolbar-select': DevToolbarSelect; - 'astro-dev-toolbar-radio-checkbox': DevToolbarRadioCheckbox; - - // Deprecated names - // TODO: Remove in Astro 5.0 - 'astro-dev-overlay': AstroDevToolbar; - 'astro-dev-overlay-window': DevToolbarWindow; - 'astro-dev-overlay-plugin-canvas': DevToolbarCanvas; - 'astro-dev-overlay-tooltip': DevToolbarTooltip; - 'astro-dev-overlay-highlight': DevToolbarHighlight; - 'astro-dev-overlay-toggle': DevToolbarToggle; - 'astro-dev-overlay-badge': DevToolbarBadge; - 'astro-dev-overlay-button': DevToolbarButton; - 'astro-dev-overlay-icon': DevToolbarIcon; - 'astro-dev-overlay-card': DevToolbarCard; - } - // eslint-disable-next-line @typescript-eslint/no-namespace - namespace Config { - type Database = Record; - } - - interface DocumentEventMap { - 'astro:before-preparation': TransitionBeforePreparationEvent; - 'astro:after-preparation': Event; - 'astro:before-swap': TransitionBeforeSwapEvent; - 'astro:after-swap': Event; - 'astro:page-load': Event; - } -} - -// Container types -export type ContainerImportRendererFn = ( - containerRenderer: ContainerRenderer, -) => Promise; - -export type ContainerRenderer = { - /** - * The name of the renderer. - */ - name: string; - /** - * The entrypoint that is used to render a component on the server - */ - serverEntrypoint: string; -}; diff --git a/packages/astro/src/types/public/content.ts b/packages/astro/src/types/public/content.ts new file mode 100644 index 000000000000..ac58c918f48f --- /dev/null +++ b/packages/astro/src/types/public/content.ts @@ -0,0 +1,121 @@ +import type { MarkdownHeading } from '@astrojs/markdown-remark'; +import type * as rollup from 'rollup'; +import type { DataEntry, RenderedContent } from '../../content/data-store.js'; +import type { AstroComponentFactory } from '../../runtime/server/index.js'; +import type { AstroConfig } from './config.js'; + +export interface AstroInstance { + file: string; + url: string | undefined; + default: AstroComponentFactory; +} + +export interface MarkdownInstance> { + frontmatter: T; + /** Absolute file path (e.g. `/home/user/projects/.../file.md`) */ + file: string; + /** Browser URL for files under `/src/pages` (e.g. `/en/guides/markdown-content`) */ + url: string | undefined; + /** Component to render content in `.astro` files. Usage: `` */ + Content: AstroComponentFactory; + /** raw Markdown file content, excluding layout HTML and YAML frontmatter */ + rawContent(): string; + /** Markdown file compiled to HTML, excluding layout HTML */ + compiledContent(): string; + /** List of headings (h1 -> h6) with associated metadata */ + getHeadings(): MarkdownHeading[]; + default: AstroComponentFactory; +} + +export type MDXInstance> = Omit< + MarkdownInstance, + 'rawContent' | 'compiledContent' +>; + +export interface MarkdownLayoutProps> { + frontmatter: { + file: MarkdownInstance['file']; + url: MarkdownInstance['url']; + } & T; + file: MarkdownInstance['file']; + url: MarkdownInstance['url']; + headings: MarkdownHeading[]; + rawContent: MarkdownInstance['rawContent']; + compiledContent: MarkdownInstance['compiledContent']; +} + +export type MDXLayoutProps> = Omit< + MarkdownLayoutProps, + 'rawContent' | 'compiledContent' +>; + +export type ContentEntryModule = { + id: string; + collection: string; + slug: string; + body: string; + data: Record; + _internal: { + rawData: string; + filePath: string; + }; +}; + +export type DataEntryModule = { + id: string; + collection: string; + data: Record; + _internal: { + rawData: string; + filePath: string; + }; +}; + +export type ContentEntryRenderFunction = (entry: DataEntry) => Promise; + +export interface ContentEntryType { + extensions: string[]; + getEntryInfo(params: { + fileUrl: URL; + contents: string; + }): GetContentEntryInfoReturnType | Promise; + getRenderModule?( + this: rollup.PluginContext, + params: { + contents: string; + fileUrl: URL; + viteId: string; + }, + ): rollup.LoadResult | Promise; + contentModuleTypes?: string; + getRenderFunction?(config: AstroConfig): Promise; + + /** + * Handle asset propagation for rendered content to avoid bleed. + * Ex. MDX content can import styles and scripts, so `handlePropagation` should be true. + * @default true + */ + handlePropagation?: boolean; +} + +type GetContentEntryInfoReturnType = { + data: Record; + /** + * Used for error hints to point to correct line and location + * Should be the untouched data as read from the file, + * including newlines + */ + rawData: string; + body: string; + slug: string; +}; + +export interface DataEntryType { + extensions: string[]; + getEntryInfo(params: { + fileUrl: URL; + contents: string; + }): GetDataEntryInfoReturnType | Promise; +} + +export type GetDataEntryInfoReturnType = { data: Record; rawData?: string }; diff --git a/packages/astro/src/types/public/context.ts b/packages/astro/src/types/public/context.ts new file mode 100644 index 000000000000..5f05b7a66273 --- /dev/null +++ b/packages/astro/src/types/public/context.ts @@ -0,0 +1,501 @@ +import type { + ActionAccept, + ActionClient, + ActionInputSchema, + ActionReturnType, +} from '../../actions/runtime/virtual/server.js'; +import type { SUPPORTED_MARKDOWN_FILE_EXTENSIONS } from '../../core/constants.js'; +import type { AstroCookies } from '../../core/cookies/cookies.js'; +import type { AstroComponentFactory } from '../../runtime/server/index.js'; +import type { Params, RewritePayload } from './common.js'; +import type { ValidRedirectStatus } from './config.js'; +import type { AstroInstance, MDXInstance, MarkdownInstance } from './content.js'; + +/** + * Astro global available in all contexts in .astro files + * + * [Astro reference](https://docs.astro.build/reference/api-reference/#astro-global) + */ +export interface AstroGlobal< + Props extends Record = Record, + Self = AstroComponentFactory, + // eslint-disable-next-line @typescript-eslint/no-shadow + Params extends Record = Record, +> extends AstroGlobalPartial, + AstroSharedContext { + /** + * A full URL object of the request URL. + * Equivalent to: `new URL(Astro.request.url)` + * + * [Astro reference](https://docs.astro.build/en/reference/api-reference/#url) + */ + url: AstroSharedContext['url']; + /** Parameters passed to a dynamic page generated using [getStaticPaths](https://docs.astro.build/en/reference/api-reference/#getstaticpaths) + * + * Example usage: + * ```astro + * --- + * export async function getStaticPaths() { + * return [ + * { params: { id: '1' } }, + * ]; + * } + * + * const { id } = Astro.params; + * --- + *

{id}

+ * ``` + * + * [Astro reference](https://docs.astro.build/en/reference/api-reference/#astroparams) + */ + params: AstroSharedContext['params']; + /** List of props passed to this component + * + * A common way to get specific props is through [destructuring](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment), ex: + * ```typescript + * const { name } = Astro.props + * ``` + * + * [Astro reference](https://docs.astro.build/en/basics/astro-components/#component-props) + */ + props: AstroSharedContext['props']; + /** Information about the current request. This is a standard [Request](https://developer.mozilla.org/en-US/docs/Web/API/Request) object + * + * For example, to get a URL object of the current URL, you can use: + * ```typescript + * const url = new URL(Astro.request.url); + * ``` + * + * [Astro reference](https://docs.astro.build/en/reference/api-reference/#astrorequest) + */ + request: Request; + /** Information about the outgoing response. This is a standard [ResponseInit](https://developer.mozilla.org/en-US/docs/Web/API/Response/Response#init) object + * + * For example, to change the status code you can set a different status on this object: + * ```typescript + * Astro.response.status = 404; + * ``` + * + * [Astro reference](https://docs.astro.build/en/reference/api-reference/#astroresponse) + */ + response: ResponseInit & { + readonly headers: Headers; + }; + /** + * Get an action result on the server when using a form POST. + * Expects the action function as a parameter. + * Returns a type-safe result with the action data when + * a matching POST request is received + * and `undefined` otherwise. + * + * Example usage: + * + * ```typescript + * import { actions } from 'astro:actions'; + * + * const result = await Astro.getActionResult(actions.myAction); + * ``` + */ + getActionResult: AstroSharedContext['getActionResult']; + /** + * Call an Action directly from an Astro page or API endpoint. + * Expects the action function as the first parameter, + * and the type-safe action input as the second parameter. + * Returns a Promise with the action result. + * + * Example usage: + * + * ```typescript + * import { actions } from 'astro:actions'; + * + * const result = await Astro.callAction(actions.getPost, { postId: 'test' }); + * ``` + */ + callAction: AstroSharedContext['callAction']; + /** Redirect to another page + * + * Example usage: + * ```typescript + * if(!isLoggedIn) { + * return Astro.redirect('/login'); + * } + * ``` + * + * [Astro reference](https://docs.astro.build/en/reference/api-reference/#astroredirect) + */ + redirect: AstroSharedContext['redirect']; + /** + * It rewrites to another page. As opposed to redirects, the URL won't change, and Astro will render the HTML emitted + * by the rewritten URL passed as argument. + * + * ## Example + * + * ```js + * if (pageIsNotEnabled) { + * return Astro.rewrite('/fallback-page') + * } + * ``` + */ + rewrite: AstroSharedContext['rewrite']; + /** + * The element allows a component to reference itself recursively. + * + * [Astro reference](https://docs.astro.build/en/reference/api-reference/#astroself) + */ + self: Self; + /** Utility functions for modifying an Astro component’s slotted children + * + * [Astro reference](https://docs.astro.build/en/reference/api-reference/#astroslots) + */ + slots: Record & { + /** + * Check whether content for this slot name exists + * + * Example usage: + * ```typescript + * if (Astro.slots.has('default')) { + * // Do something... + * } + * ``` + * + * [Astro reference](https://docs.astro.build/en/reference/api-reference/#astroslots) + */ + has(slotName: string): boolean; + /** + * Asynchronously renders this slot and returns a string + * + * Example usage: + * ```astro + * --- + * let html: string = ''; + * if (Astro.slots.has('default')) { + * html = await Astro.slots.render('default') + * } + * --- + * + * ``` + * + * A second parameter can be used to pass arguments to a slotted callback + * + * Example usage: + * ```astro + * --- + * html = await Astro.slots.render('default', ["Hello", "World"]) + * --- + * ``` + * Each item in the array will be passed as an argument that you can use like so: + * ```astro + * + * {(hello, world) =>
{hello}, {world}!
} + *
+ * ``` + * + * [Astro reference](https://docs.astro.build/en/reference/api-reference/#astroslots) + */ + render(slotName: string, args?: any[]): Promise; + }; +} + +/** Union type of supported markdown file extensions */ +type MarkdownFileExtension = (typeof SUPPORTED_MARKDOWN_FILE_EXTENSIONS)[number]; + +export interface AstroGlobalPartial { + /** + * Fetch local files into your static site setup + * + * Example usage: + * ```typescript + * const posts = await Astro.glob('../pages/post/*.md'); + * ``` + * + * [Astro reference](https://docs.astro.build/en/reference/api-reference/#astroglob) + */ + glob(globStr: `${any}.astro`): Promise; + glob>( + globStr: `${any}${MarkdownFileExtension}`, + ): Promise[]>; + glob>(globStr: `${any}.mdx`): Promise[]>; + glob>(globStr: string): Promise; + /** + * Returns a [URL](https://developer.mozilla.org/en-US/docs/Web/API/URL) object built from the [site](https://docs.astro.build/en/reference/configuration-reference/#site) config option + * + * [Astro reference](https://docs.astro.build/en/reference/api-reference/#astrosite) + */ + site: URL | undefined; + /** + * Returns a string with the current version of Astro. + * + * Useful for using `` or crediting Astro in a site footer. + * + * [HTML Specification for `generator`](https://html.spec.whatwg.org/multipage/semantics.html#meta-generator) + * + * [Astro reference](https://docs.astro.build/en/reference/api-reference/#astrogenerator) + */ + generator: string; +} + +// Shared types between `Astro` global and API context object +interface AstroSharedContext< + Props extends Record = Record, + RouteParams extends Record = Record, +> { + /** + * The address (usually IP address) of the user. + * + * Throws an error if used within a static site, or within a prerendered page. + */ + clientAddress: string; + /** + * Utility for getting and setting the values of cookies. + */ + cookies: AstroCookies; + /** + * Information about the current request. This is a standard [Request](https://developer.mozilla.org/en-US/docs/Web/API/Request) object + */ + request: Request; + /** + * A full URL object of the request URL. + */ + url: URL; + /** + * Get action result on the server when using a form POST. + */ + getActionResult: < + TAccept extends ActionAccept, + TInputSchema extends ActionInputSchema, + TAction extends ActionClient, + >( + action: TAction, + ) => ActionReturnType | undefined; + /** + * Call action handler from the server. + */ + callAction: < + TAccept extends ActionAccept, + TInputSchema extends ActionInputSchema, + TOutput, + TAction extends + | ActionClient + | ActionClient['orThrow'], + >( + action: TAction, + input: Parameters[0], + ) => Promise>; + /** + * Route parameters for this request if this is a dynamic route. + */ + params: RouteParams; + /** + * List of props returned for this path by `getStaticPaths` (**Static Only**). + */ + props: Props; + /** + * Redirect to another page (**SSR Only**). + */ + redirect(path: string, status?: ValidRedirectStatus): Response; + + /** + * It rewrites to another page. As opposed to redirects, the URL won't change, and Astro will render the HTML emitted + * by the rerouted URL passed as argument. + * + * ## Example + * + * ```js + * if (pageIsNotEnabled) { + * return Astro.rewrite('/fallback-page') + * } + * ``` + */ + rewrite(rewritePayload: RewritePayload): Promise; + + /** + * Object accessed via Astro middleware + */ + locals: App.Locals; + + /** + * The current locale that is computed from the `Accept-Language` header of the browser (**SSR Only**). + */ + preferredLocale: string | undefined; + + /** + * The list of locales computed from the `Accept-Language` header of the browser, sorted by quality value (**SSR Only**). + */ + + preferredLocaleList: string[] | undefined; + + /** + * The current locale computed from the URL of the request. It matches the locales in `i18n.locales`, and returns `undefined` otherwise. + */ + currentLocale: string | undefined; +} + +/** + * The `APIContext` is the object made available to endpoints and middleware. + * It is a subset of the `Astro` global object available in pages. + * + * [Reference](https://docs.astro.build/en/reference/api-reference/#endpoint-context) + */ +export interface APIContext< + Props extends Record = Record, + APIParams extends Record = Record, +> extends AstroSharedContext { + /** + * The site provided in the astro config, parsed as an instance of `URL`, without base. + * `undefined` if the site is not provided in the config. + */ + site: URL | undefined; + /** + * A human-readable string representing the Astro version used to create the project. + * For example, `"Astro v1.1.1"`. + */ + generator: string; + /** + * The url of the current request, parsed as an instance of `URL`. + * + * Equivalent to: + * ```ts + * new URL(context.request.url) + * ``` + */ + url: AstroSharedContext['url']; + /** + * Parameters matching the page’s dynamic route pattern. + * In static builds, this will be the `params` generated by `getStaticPaths`. + * In SSR builds, this can be any path segments matching the dynamic route pattern. + * + * Example usage: + * ```ts + * import type { APIContext } from "astro" + * + * export function getStaticPaths() { + * return [ + * { params: { id: '0' }, props: { name: 'Sarah' } }, + * { params: { id: '1' }, props: { name: 'Chris' } }, + * { params: { id: '2' }, props: { name: 'Fuzzy' } }, + * ]; + * } + * + * export async function GET({ params }: APIContext) { + * return new Response(`Hello user ${params.id}!`) + * } + * ``` + * + * [Reference](https://docs.astro.build/en/reference/api-reference/#contextparams) + */ + params: AstroSharedContext['params']; + /** + * List of props passed from `getStaticPaths`. Only available to static builds. + * + * Example usage: + * ```ts + * import type { APIContext } from "astro" + * + * export function getStaticPaths() { + * return [ + * { params: { id: '0' }, props: { name: 'Sarah' } }, + * { params: { id: '1' }, props: { name: 'Chris' } }, + * { params: { id: '2' }, props: { name: 'Fuzzy' } }, + * ]; + * } + * + * export function GET({ props }: APIContext): Response { + * return new Response(`Hello ${props.name}!`); + * } + * ``` + * + * [Reference](https://docs.astro.build/en/reference/api-reference/#contextprops) + */ + props: AstroSharedContext['props']; + /** + * Create a response that redirects to another page. + * + * Example usage: + * ```ts + * // src/pages/secret.ts + * export function GET({ redirect }) { + * return redirect('/login'); + * } + * ``` + * + * [Reference](https://docs.astro.build/en/guides/api-reference/#contextredirect) + */ + redirect: AstroSharedContext['redirect']; + + /** + * It reroutes to another page. As opposed to redirects, the URL won't change, and Astro will render the HTML emitted + * by the rerouted URL passed as argument. + * + * ## Example + * + * ```ts + * // src/pages/secret.ts + * export function GET(ctx) { + * return ctx.rewrite(new URL("../"), ctx.url); + * } + * ``` + */ + rewrite: AstroSharedContext['rewrite']; + + /** + * An object that middlewares can use to store extra information related to the request. + * + * It will be made available to pages as `Astro.locals`, and to endpoints as `context.locals`. + * + * Example usage: + * + * ```ts + * // src/middleware.ts + * import { defineMiddleware } from "astro:middleware"; + * + * export const onRequest = defineMiddleware((context, next) => { + * context.locals.greeting = "Hello!"; + * return next(); + * }); + * ``` + * Inside a `.astro` file: + * ```astro + * --- + * // src/pages/index.astro + * const greeting = Astro.locals.greeting; + * --- + *

{greeting}

+ * ``` + * + * [Reference](https://docs.astro.build/en/reference/api-reference/#contextlocals) + */ + locals: App.Locals; + + /** + * Available only when `i18n` configured and in SSR. + * + * It represents the preferred locale of the user. It's computed by checking the supported locales in `i18n.locales` + * and locales supported by the users's browser via the header `Accept-Language` + * + * For example, given `i18n.locales` equals to `['fr', 'de']`, and the `Accept-Language` value equals to `en, de;q=0.2, fr;q=0.6`, the + * `Astro.preferredLanguage` will be `fr` because `en` is not supported, its [quality value] is the highest. + * + * [quality value]: https://developer.mozilla.org/en-US/docs/Glossary/Quality_values + */ + preferredLocale: string | undefined; + + /** + * Available only when `i18n` configured and in SSR. + * + * It represents the list of the preferred locales that are supported by the application. The list is sorted via [quality value]. + * + * For example, given `i18n.locales` equals to `['fr', 'pt', 'de']`, and the `Accept-Language` value equals to `en, de;q=0.2, fr;q=0.6`, the + * `Astro.preferredLocaleList` will be equal to `['fs', 'de']` because `en` isn't supported, and `pt` isn't part of the locales contained in the + * header. + * + * When the `Accept-Header` is `*`, the original `i18n.locales` are returned. The value `*` means no preferences, so Astro returns all the supported locales. + * + * [quality value]: https://developer.mozilla.org/en-US/docs/Glossary/Quality_values + */ + preferredLocaleList: string[] | undefined; + + /** + * The current locale computed from the URL of the request. It matches the locales in `i18n.locales`, and returns `undefined` otherwise. + */ + currentLocale: string | undefined; +} diff --git a/packages/astro/src/types/public/elements.ts b/packages/astro/src/types/public/elements.ts new file mode 100644 index 000000000000..83301f7b839a --- /dev/null +++ b/packages/astro/src/types/public/elements.ts @@ -0,0 +1,47 @@ +import type { TransitionAnimationValue } from './view-transitions.js'; + +export interface AstroComponentDirectives extends Astro.ClientDirectives { + 'server:defer'?: boolean; +} + +export interface AstroClientDirectives { + 'client:load'?: boolean; + 'client:idle'?: boolean; + 'client:media'?: string; + 'client:visible'?: ClientVisibleOptions | boolean; + 'client:only'?: boolean | string; +} + +export type ClientVisibleOptions = Pick; + +export interface AstroBuiltinAttributes { + 'class:list'?: + | Record + | Record + | Iterable + | Iterable + | string; + 'set:html'?: any; + 'set:text'?: any; + 'is:raw'?: boolean; + 'transition:animate'?: TransitionAnimationValue; + 'transition:name'?: string; + 'transition:persist'?: boolean | string; +} + +export interface AstroDefineVarsAttribute { + 'define:vars'?: any; +} + +export interface AstroStyleAttributes { + 'is:global'?: boolean; + 'is:inline'?: boolean; +} + +export interface AstroScriptAttributes { + 'is:inline'?: boolean; +} + +export interface AstroSlotAttributes { + 'is:inline'?: boolean; +} diff --git a/packages/astro/src/types/public/extendables.ts b/packages/astro/src/types/public/extendables.ts new file mode 100644 index 000000000000..1592eda190ad --- /dev/null +++ b/packages/astro/src/types/public/extendables.ts @@ -0,0 +1,21 @@ +/* eslint-disable @typescript-eslint/no-namespace */ +/* eslint-disable @typescript-eslint/no-empty-object-type */ +import type { AstroClientDirectives } from './elements.js'; +import type { BaseIntegrationHooks } from './integrations.js'; + +// The interfaces in this file can be extended by users +declare global { + namespace App { + /** + * Used by middlewares to store information, that can be read by the user via the global `Astro.locals` + */ + export interface Locals {} + } + + namespace Astro { + export interface IntegrationHooks extends BaseIntegrationHooks {} + export interface ClientDirectives extends AstroClientDirectives {} + } +} + +export {}; diff --git a/packages/astro/src/types/public/index.ts b/packages/astro/src/types/public/index.ts new file mode 100644 index 000000000000..5df509013678 --- /dev/null +++ b/packages/astro/src/types/public/index.ts @@ -0,0 +1,44 @@ +export type * from './config.js'; +export type * from './elements.js'; +export type * from './extendables.js'; +export type * from './toolbar.js'; +export type * from './view-transitions.js'; +export type * from './integrations.js'; +export type * from './internal.js'; +export type * from './context.js'; +export type * from './preview.js'; +export type * from './content.js'; +export type * from './common.js'; + +export type { AstroIntegrationLogger } from '../../core/logger/core.js'; +export type { ToolbarServerHelpers } from '../../runtime/client/dev-toolbar/helpers.js'; + +export type { + MarkdownHeading, + RehypePlugins, + RemarkPlugins, + ShikiConfig, +} from '@astrojs/markdown-remark'; +export type { + ExternalImageService, + ImageService, + LocalImageService, +} from '../../assets/services/service.js'; +export type { + GetImageResult, + ImageInputFormat, + ImageMetadata, + ImageOutputFormat, + ImageQuality, + ImageQualityPreset, + ImageTransform, + UnresolvedImageTransform, +} from '../../assets/types.js'; +export type { RemotePattern } from '../../assets/utils/remotePattern.js'; +export type { AssetsPrefix, SSRManifest } from '../../core/app/types.js'; +export type { + AstroCookieGetOptions, + AstroCookieSetOptions, + AstroCookies, +} from '../../core/cookies/index.js'; +export type { ContainerRenderer } from '../../container/index.js'; diff --git a/packages/astro/src/types/public/integrations.ts b/packages/astro/src/types/public/integrations.ts new file mode 100644 index 000000000000..d41abd8355e9 --- /dev/null +++ b/packages/astro/src/types/public/integrations.ts @@ -0,0 +1,258 @@ +import type { AddressInfo } from 'node:net'; +import type { ViteDevServer, InlineConfig as ViteInlineConfig } from 'vite'; +import type { SerializedSSRManifest } from '../../core/app/types.js'; +import type { PageBuildData } from '../../core/build/types.js'; +import type { AstroIntegrationLogger } from '../../core/logger/core.js'; +import type { getToolbarServerCommunicationHelpers } from '../../integrations/hooks.js'; +import type { DeepPartial } from '../../type-utils.js'; +import type { AstroConfig } from './config.js'; +import type { RouteData } from './internal.js'; +import type { DevToolbarAppEntry } from './toolbar.js'; + +export interface RouteOptions { + /** + * The path to this route relative to the project root. The slash is normalized as forward slash + * across all OS. + * @example "src/pages/blog/[...slug].astro" + */ + readonly component: string; + /** + * Whether this route should be prerendered. If the route has an explicit `prerender` export, + * the value will be passed here. Otherwise, it's undefined and will fallback to a prerender + * default depending on the `output` option. + */ + prerender?: boolean; +} + +/* Client Directives */ +type DirectiveHydrate = () => Promise; +type DirectiveLoad = () => Promise; + +type DirectiveOptions = { + /** + * The component displayName + */ + name: string; + /** + * The attribute value provided + */ + value: string; +}; + +export type ClientDirective = ( + load: DirectiveLoad, + options: DirectiveOptions, + el: HTMLElement, +) => void; + +export interface ClientDirectiveConfig { + name: string; + entrypoint: string; +} + +export interface AstroRenderer { + /** Name of the renderer. */ + name: string; + /** Import entrypoint for the client/browser renderer. */ + clientEntrypoint?: string; + /** Import entrypoint for the server/build/ssr renderer. */ + serverEntrypoint: string; +} + +export type AdapterSupportsKind = 'unsupported' | 'stable' | 'experimental' | 'deprecated'; + +export interface AstroAdapterFeatures { + /** + * Creates an edge function that will communiate with the Astro middleware + */ + edgeMiddleware: boolean; + /** + * SSR only. Each route becomes its own function/file. + */ + functionPerRoute: boolean; +} + +export interface AstroAdapter { + name: string; + serverEntrypoint?: string; + previewEntrypoint?: string; + exports?: string[]; + args?: any; + adapterFeatures?: AstroAdapterFeatures; + /** + * List of features supported by an adapter. + * + * If the adapter is not able to handle certain configurations, Astro will throw an error. + */ + supportedAstroFeatures: AstroAdapterFeatureMap; +} + +export type AstroAdapterFeatureMap = { + /** + * The adapter is able serve static pages + */ + staticOutput?: AdapterSupportsKind; + /** + * The adapter is able to serve pages that are static or rendered via server + */ + hybridOutput?: AdapterSupportsKind; + /** + * The adapter is able to serve SSR pages + */ + serverOutput?: AdapterSupportsKind; + /** + * The adapter can emit static assets + */ + assets?: AstroAssetsFeature; + + /** + * List of features that orbit around the i18n routing + */ + i18nDomains?: AdapterSupportsKind; + + /** + * The adapter is able to support `getSecret` exported from `astro:env/server` + */ + envGetSecret?: AdapterSupportsKind; +}; + +export interface AstroAssetsFeature { + supportKind?: AdapterSupportsKind; + /** + * Whether if this adapter deploys files in an environment that is compatible with the library `sharp` + */ + isSharpCompatible?: boolean; + /** + * Whether if this adapter deploys files in an environment that is compatible with the library `squoosh` + */ + isSquooshCompatible?: boolean; +} + +export interface AstroInternationalizationFeature { + /** + * The adapter should be able to create the proper redirects + */ + domains?: AdapterSupportsKind; +} + +/** + * IDs for different stages of JS script injection: + * - "before-hydration": Imported client-side, before the hydration script runs. Processed & resolved by Vite. + * - "head-inline": Injected into a script tag in the `` of every page. Not processed or resolved by Vite. + * - "page": Injected into the JavaScript bundle of every page. Processed & resolved by Vite. + * - "page-ssr": Injected into the frontmatter of every Astro page. Processed & resolved by Vite. + */ +export type InjectedScriptStage = 'before-hydration' | 'head-inline' | 'page' | 'page-ssr'; + +/** + * IDs for different priorities of injected routes and redirects: + * - "normal": Merge with discovered file-based project routes, behaving the same as if the route + * was defined as a file in the project. + * - "legacy": Use the old ordering of routes. Inject routes will override any file-based project route, + * and redirects will be overridden by any project route on conflict. + */ +export type RoutePriorityOverride = 'normal' | 'legacy'; + +export interface InjectedRoute { + pattern: string; + entrypoint: string; + prerender?: boolean; +} + +export interface ResolvedInjectedRoute extends InjectedRoute { + resolvedEntryPoint?: URL; +} + +export interface InjectedType { + filename: string; + content: string; +} + +export type AstroIntegrationMiddleware = { + order: 'pre' | 'post'; + entrypoint: string; +}; + +export type HookParameters< + Hook extends keyof AstroIntegration['hooks'], + Fn = AstroIntegration['hooks'][Hook], +> = Fn extends (...args: any) => any ? Parameters[0] : never; + +export interface BaseIntegrationHooks { + 'astro:config:setup': (options: { + config: AstroConfig; + command: 'dev' | 'build' | 'preview'; + isRestart: boolean; + updateConfig: (newConfig: DeepPartial) => AstroConfig; + addRenderer: (renderer: AstroRenderer) => void; + addWatchFile: (path: URL | string) => void; + injectScript: (stage: InjectedScriptStage, content: string) => void; + injectRoute: (injectRoute: InjectedRoute) => void; + addClientDirective: (directive: ClientDirectiveConfig) => void; + // TODO: Deprecate the `string` overload once a few apps have been migrated to the new API. + addDevToolbarApp: (entrypoint: DevToolbarAppEntry | string) => void; + addMiddleware: (mid: AstroIntegrationMiddleware) => void; + logger: AstroIntegrationLogger; + }) => void | Promise; + 'astro:config:done': (options: { + config: AstroConfig; + setAdapter: (adapter: AstroAdapter) => void; + injectTypes: (injectedType: InjectedType) => URL; + logger: AstroIntegrationLogger; + }) => void | Promise; + 'astro:server:setup': (options: { + server: ViteDevServer; + logger: AstroIntegrationLogger; + toolbar: ReturnType; + }) => void | Promise; + 'astro:server:start': (options: { + address: AddressInfo; + logger: AstroIntegrationLogger; + }) => void | Promise; + 'astro:server:done': (options: { logger: AstroIntegrationLogger }) => void | Promise; + 'astro:build:ssr': (options: { + manifest: SerializedSSRManifest; + /** + * This maps a {@link RouteData} to an {@link URL}, this URL represents + * the physical file you should import. + */ + entryPoints: Map; + /** + * File path of the emitted middleware + */ + middlewareEntryPoint: URL | undefined; + logger: AstroIntegrationLogger; + }) => void | Promise; + 'astro:build:start': (options: { logger: AstroIntegrationLogger }) => void | Promise; + 'astro:build:setup': (options: { + vite: ViteInlineConfig; + pages: Map; + target: 'client' | 'server'; + updateConfig: (newConfig: ViteInlineConfig) => void; + logger: AstroIntegrationLogger; + }) => void | Promise; + 'astro:build:generated': (options: { + dir: URL; + logger: AstroIntegrationLogger; + }) => void | Promise; + 'astro:build:done': (options: { + pages: { pathname: string }[]; + dir: URL; + routes: RouteData[]; + logger: AstroIntegrationLogger; + cacheManifest: boolean; + }) => void | Promise; + 'astro:route:setup': (options: { + route: RouteOptions; + logger: AstroIntegrationLogger; + }) => void | Promise; +} + +export interface AstroIntegration { + /** The name of the integration. */ + name: string; + /** The different hooks available to extend. */ + hooks: { + [K in keyof Astro.IntegrationHooks]?: Astro.IntegrationHooks[K]; + } & Partial>; +} diff --git a/packages/astro/src/types/public/internal.ts b/packages/astro/src/types/public/internal.ts new file mode 100644 index 000000000000..bee15c6f75c0 --- /dev/null +++ b/packages/astro/src/types/public/internal.ts @@ -0,0 +1,202 @@ +// TODO: Should the types here really be public? + +import type { ErrorPayload as ViteErrorPayload } from 'vite'; +import type { AstroCookies } from '../../core/cookies/cookies.js'; +import type { AstroComponentInstance } from '../../runtime/server/index.js'; +import type { Params } from './common.js'; +import type { AstroConfig, RedirectConfig } from './config.js'; +import type { AstroGlobal, AstroGlobalPartial } from './context.js'; +import type { AstroRenderer } from './integrations.js'; + +export type { SSRManifest } from '../../core/app/types.js'; + +export interface NamedSSRLoadedRendererValue extends SSRLoadedRendererValue { + name: string; +} + +export interface SSRLoadedRendererValue { + name?: string; + check: AsyncRendererComponentFn; + renderToStaticMarkup: AsyncRendererComponentFn<{ + html: string; + attrs?: Record; + }>; + supportsAstroStaticSlot?: boolean; + /** + * If provided, Astro will call this function and inject the returned + * script in the HTML before the first component handled by this renderer. + * + * This feature is needed by some renderers (in particular, by Solid). The + * Solid official hydration script sets up a page-level data structure. + * It is mainly used to transfer data between the server side render phase + * and the browser application state. Solid Components rendered later in + * the HTML may inject tiny scripts into the HTML that call into this + * page-level data structure. + */ + renderHydrationScript?: () => string; +} + +export interface RouteData { + route: string; + component: string; + generate: (data?: any) => string; + params: string[]; + pathname?: string; + // expose the real path name on SSG + distURL?: URL; + pattern: RegExp; + segments: RoutePart[][]; + type: RouteType; + prerender: boolean; + redirect?: RedirectConfig; + redirectRoute?: RouteData; + fallbackRoutes: RouteData[]; + isIndex: boolean; +} + +/** + * - page: a route that lives in the file system, usually an Astro component + * - endpoint: a route that lives in the file system, usually a JS file that exposes endpoints methods + * - redirect: a route points to another route that lives in the file system + * - fallback: a route that doesn't exist in the file system that needs to be handled with other means, usually the middleware + */ +export type RouteType = 'page' | 'endpoint' | 'redirect' | 'fallback'; + +export interface RoutePart { + content: string; + dynamic: boolean; + spread: boolean; +} + +export interface AstroComponentMetadata { + displayName: string; + hydrate?: 'load' | 'idle' | 'visible' | 'media' | 'only'; + hydrateArgs?: any; + componentUrl?: string; + componentExport?: { value: string; namespace?: boolean }; + astroStaticSlot: true; +} + +export type AsyncRendererComponentFn = ( + Component: any, + props: any, + slots: Record, + metadata?: AstroComponentMetadata, +) => Promise; + +export interface NamedSSRLoadedRendererValue extends SSRLoadedRendererValue { + name: string; +} + +export interface SSRLoadedRendererValue { + name?: string; + check: AsyncRendererComponentFn; + renderToStaticMarkup: AsyncRendererComponentFn<{ + html: string; + attrs?: Record; + }>; + supportsAstroStaticSlot?: boolean; + /** + * If provided, Astro will call this function and inject the returned + * script in the HTML before the first component handled by this renderer. + * + * This feature is needed by some renderers (in particular, by Solid). The + * Solid official hydration script sets up a page-level data structure. + * It is mainly used to transfer data between the server side render phase + * and the browser application state. Solid Components rendered later in + * the HTML may inject tiny scripts into the HTML that call into this + * page-level data structure. + */ + renderHydrationScript?: () => string; +} + +export interface SSRLoadedRenderer extends Pick { + ssr: SSRLoadedRendererValue; +} + +export interface SSRElement { + props: Record; + children: string; +} + +export interface SSRResult { + /** + * Whether the page has failed with a non-recoverable error, or the client disconnected. + */ + cancelled: boolean; + base: string; + styles: Set; + scripts: Set; + links: Set; + componentMetadata: Map; + inlinedScripts: Map; + createAstro( + Astro: AstroGlobalPartial, + props: Record, + slots: Record | null, + ): AstroGlobal; + params: Params; + resolve: (s: string) => Promise; + response: AstroGlobal['response']; + request: AstroGlobal['request']; + actionResult?: ReturnType; + renderers: SSRLoadedRenderer[]; + /** + * Map of directive name (e.g. `load`) to the directive script code + */ + clientDirectives: Map; + compressHTML: boolean; + partial: boolean; + /** + * Only used for logging + */ + pathname: string; + cookies: AstroCookies | undefined; + serverIslandNameMap: Map; + trailingSlash: AstroConfig['trailingSlash']; + key: Promise; + _metadata: SSRMetadata; +} + +/** + * A hint on whether the Astro runtime needs to wait on a component to render head + * content. The meanings: + * + * - __none__ (default) The component does not propagation head content. + * - __self__ The component appends head content. + * - __in-tree__ Another component within this component's dependency tree appends head content. + * + * These are used within the runtime to know whether or not a component should be waited on. + */ +export type PropagationHint = 'none' | 'self' | 'in-tree'; + +export type SSRComponentMetadata = { + propagation: PropagationHint; + containsHead: boolean; +}; + +/** + * Ephemeral and mutable state during rendering that doesn't rely + * on external configuration + */ +export interface SSRMetadata { + hasHydrationScript: boolean; + /** + * Names of renderers that have injected their hydration scripts + * into the current page. For example, Solid SSR needs a hydration + * script in the page HTML before the first Solid component. + */ + rendererSpecificHydrationScripts: Set; + /** + * Used by `renderScript` to track script ids that have been rendered, + * so we only render each once. + */ + renderedScripts: Set; + hasDirectives: Set; + hasRenderedHead: boolean; + headInTree: boolean; + extraHead: string[]; + propagators: Set; +} + +export type SSRError = Error & ViteErrorPayload['err']; diff --git a/packages/astro/src/types/public/preview.ts b/packages/astro/src/types/public/preview.ts new file mode 100644 index 000000000000..e2794303f39c --- /dev/null +++ b/packages/astro/src/types/public/preview.ts @@ -0,0 +1,28 @@ +import type { OutgoingHttpHeaders } from 'node:http'; +import type { AstroIntegrationLogger } from '../../core/logger/core.js'; + +export interface PreviewServer { + host?: string; + port: number; + closed(): Promise; + stop(): Promise; +} + +export interface PreviewServerParams { + outDir: URL; + client: URL; + serverEntrypoint: URL; + host: string | undefined; + port: number; + base: string; + logger: AstroIntegrationLogger; + headers?: OutgoingHttpHeaders; +} + +export type CreatePreviewServer = ( + params: PreviewServerParams, +) => PreviewServer | Promise; + +export interface PreviewModule { + default: CreatePreviewServer; +} diff --git a/packages/astro/src/types/public/toolbar.ts b/packages/astro/src/types/public/toolbar.ts new file mode 100644 index 000000000000..7beaab3bb84f --- /dev/null +++ b/packages/astro/src/types/public/toolbar.ts @@ -0,0 +1,96 @@ +import type { + ToolbarAppEventTarget, + ToolbarServerHelpers, +} from '../../runtime/client/dev-toolbar/helpers.js'; +import type { + AstroDevToolbar, + DevToolbarCanvas, +} from '../../runtime/client/dev-toolbar/toolbar.js'; +import type { Icon } from '../../runtime/client/dev-toolbar/ui-library/icons.js'; +import type { + DevToolbarBadge, + DevToolbarButton, + DevToolbarCard, + DevToolbarHighlight, + DevToolbarIcon, + DevToolbarRadioCheckbox, + DevToolbarSelect, + DevToolbarToggle, + DevToolbarTooltip, + DevToolbarWindow, +} from '../../runtime/client/dev-toolbar/ui-library/index.js'; + +declare global { + interface HTMLElementTagNameMap { + 'astro-dev-toolbar': AstroDevToolbar; + 'astro-dev-toolbar-window': DevToolbarWindow; + 'astro-dev-toolbar-app-canvas': DevToolbarCanvas; + 'astro-dev-toolbar-tooltip': DevToolbarTooltip; + 'astro-dev-toolbar-highlight': DevToolbarHighlight; + 'astro-dev-toolbar-toggle': DevToolbarToggle; + 'astro-dev-toolbar-badge': DevToolbarBadge; + 'astro-dev-toolbar-button': DevToolbarButton; + 'astro-dev-toolbar-icon': DevToolbarIcon; + 'astro-dev-toolbar-card': DevToolbarCard; + 'astro-dev-toolbar-select': DevToolbarSelect; + 'astro-dev-toolbar-radio-checkbox': DevToolbarRadioCheckbox; + } +} + +type DevToolbarAppMeta = { + id: string; + name: string; + icon?: Icon; +}; + +// The param passed to `addDevToolbarApp` in the integration +export type DevToolbarAppEntry = DevToolbarAppMeta & { + entrypoint: string; +}; + +// Public API for the dev toolbar +export type DevToolbarApp = { + /** + * @deprecated The `id`, `name`, and `icon` properties should now be defined when using `addDevToolbarApp`. + * + * Ex: `addDevToolbarApp({ id: 'my-app', name: 'My App', icon: '🚀', entrypoint: '/path/to/app' })` + * + * In the future, putting these properties directly on the app object will be removed. + */ + id?: string; + /** + * @deprecated The `id`, `name`, and `icon` properties should now be defined when using `addDevToolbarApp`. + * + * Ex: `addDevToolbarApp({ id: 'my-app', name: 'My App', icon: '🚀', entrypoint: '/path/to/app' })` + * + * In the future, putting these properties directly on the app object will be removed. + */ + name?: string; + /** + * @deprecated The `id`, `name`, and `icon` properties should now be defined when using `addDevToolbarApp`. + * + * Ex: `addDevToolbarApp({ id: 'my-app', name: 'My App', icon: '🚀', entrypoint: '/path/to/app' })` + * + * In the future, putting these properties directly on the app object will be removed. + */ + icon?: Icon; + init?( + canvas: ShadowRoot, + app: ToolbarAppEventTarget, + server: ToolbarServerHelpers, + ): void | Promise; + beforeTogglingOff?(canvas: ShadowRoot): boolean | Promise; +}; + +// An app that has been loaded and as such contain all of its properties +export type ResolvedDevToolbarApp = DevToolbarAppMeta & Omit; + +export type DevToolbarMetadata = Window & + typeof globalThis & { + __astro_dev_toolbar__: { + root: string; + version: string; + latestAstroVersion: string | undefined; + debugInfo: string; + }; + }; diff --git a/packages/astro/src/types/public/view-transitions.ts b/packages/astro/src/types/public/view-transitions.ts new file mode 100644 index 000000000000..1acd5003bff4 --- /dev/null +++ b/packages/astro/src/types/public/view-transitions.ts @@ -0,0 +1,40 @@ +import type { + TransitionBeforePreparationEvent, + TransitionBeforeSwapEvent, +} from '../../transitions/events.js'; + +export interface TransitionAnimation { + name: string; // The name of the keyframe + delay?: number | string; + duration?: number | string; + easing?: string; + fillMode?: string; + direction?: string; +} + +export interface TransitionAnimationPair { + old: TransitionAnimation | TransitionAnimation[]; + new: TransitionAnimation | TransitionAnimation[]; +} + +export interface TransitionDirectionalAnimations { + forwards: TransitionAnimationPair; + backwards: TransitionAnimationPair; +} + +export type TransitionAnimationValue = + | 'initial' + | 'slide' + | 'fade' + | 'none' + | TransitionDirectionalAnimations; + +declare global { + interface DocumentEventMap { + 'astro:before-preparation': TransitionBeforePreparationEvent; + 'astro:after-preparation': Event; + 'astro:before-swap': TransitionBeforeSwapEvent; + 'astro:after-swap': Event; + 'astro:page-load': Event; + } +} diff --git a/packages/astro/src/@types/typed-emitter.ts b/packages/astro/src/types/typed-emitter.ts similarity index 100% rename from packages/astro/src/@types/typed-emitter.ts rename to packages/astro/src/types/typed-emitter.ts diff --git a/packages/astro/src/virtual-modules/container.ts b/packages/astro/src/virtual-modules/container.ts index 420b3e3e2d94..3efc626d9f2c 100644 --- a/packages/astro/src/virtual-modules/container.ts +++ b/packages/astro/src/virtual-modules/container.ts @@ -1,4 +1,5 @@ -import type { AstroRenderer, SSRLoadedRenderer } from '../@types/astro.js'; +import type { AstroRenderer } from '../types/public/integrations.js'; +import type { SSRLoadedRenderer } from '../types/public/internal.js'; /** * Use this function to provide renderers to the `AstroContainer`: diff --git a/packages/astro/src/virtual-modules/i18n.ts b/packages/astro/src/virtual-modules/i18n.ts index aacdd80a96e1..927d479aab32 100644 --- a/packages/astro/src/virtual-modules/i18n.ts +++ b/packages/astro/src/virtual-modules/i18n.ts @@ -1,9 +1,3 @@ -import type { - APIContext, - AstroConfig, - MiddlewareHandler, - ValidRedirectStatus, -} from '../@types/astro.js'; import type { SSRManifest } from '../core/app/types.js'; import { IncorrectStrategyForI18n } from '../core/errors/errors-data.js'; import { AstroError } from '../core/errors/index.js'; @@ -11,6 +5,9 @@ import * as I18nInternals from '../i18n/index.js'; import type { RedirectToFallback } from '../i18n/index.js'; import { toRoutingStrategy } from '../i18n/utils.js'; import type { I18nInternalConfig } from '../i18n/vite-plugin-i18n.js'; +import type { MiddlewareHandler } from '../types/public/common.js'; +import type { AstroConfig, ValidRedirectStatus } from '../types/public/config.js'; +import type { APIContext } from '../types/public/context.js'; export { normalizeTheLocale, toCodes, toPaths } from '../i18n/index.js'; diff --git a/packages/astro/src/vite-plugin-astro-server/base.ts b/packages/astro/src/vite-plugin-astro-server/base.ts index bea642f6f8c7..562b89ba2204 100644 --- a/packages/astro/src/vite-plugin-astro-server/base.ts +++ b/packages/astro/src/vite-plugin-astro-server/base.ts @@ -1,5 +1,5 @@ import type * as vite from 'vite'; -import type { AstroSettings } from '../@types/astro.js'; +import type { AstroSettings } from '../types/astro.js'; import * as fs from 'node:fs'; import path from 'node:path'; diff --git a/packages/astro/src/vite-plugin-astro-server/error.ts b/packages/astro/src/vite-plugin-astro-server/error.ts index 24db9dc49b84..25a237cc278f 100644 --- a/packages/astro/src/vite-plugin-astro-server/error.ts +++ b/packages/astro/src/vite-plugin-astro-server/error.ts @@ -1,10 +1,10 @@ -import type { AstroConfig } from '../@types/astro.js'; import type { ModuleLoader } from '../core/module-loader/index.js'; import type { DevPipeline } from './pipeline.js'; import { collectErrorMetadata } from '../core/errors/dev/index.js'; import { createSafeError } from '../core/errors/index.js'; import { formatErrorMessage } from '../core/messages.js'; +import type { AstroConfig } from '../types/public/config.js'; export function recordServerError( loader: ModuleLoader, diff --git a/packages/astro/src/vite-plugin-astro-server/metadata.ts b/packages/astro/src/vite-plugin-astro-server/metadata.ts index 793ee5669312..7f358ade0c46 100644 --- a/packages/astro/src/vite-plugin-astro-server/metadata.ts +++ b/packages/astro/src/vite-plugin-astro-server/metadata.ts @@ -1,6 +1,6 @@ -import type { SSRComponentMetadata, SSRResult } from '../@types/astro.js'; import type { ModuleInfo, ModuleLoader } from '../core/module-loader/index.js'; import { viteID } from '../core/util.js'; +import type { SSRComponentMetadata, SSRResult } from '../types/public/internal.js'; import { getAstroMetadata } from '../vite-plugin-astro/index.js'; import { crawlGraph } from './vite.js'; diff --git a/packages/astro/src/vite-plugin-astro-server/pipeline.ts b/packages/astro/src/vite-plugin-astro-server/pipeline.ts index 4386eb154bda..5a672279ede8 100644 --- a/packages/astro/src/vite-plugin-astro-server/pipeline.ts +++ b/packages/astro/src/vite-plugin-astro-server/pipeline.ts @@ -1,15 +1,4 @@ import { fileURLToPath } from 'node:url'; -import type { - AstroSettings, - ComponentInstance, - DevToolbarMetadata, - ManifestData, - RewritePayload, - RouteData, - SSRElement, - SSRLoadedRenderer, - SSRManifest, -} from '../@types/astro.js'; import { getInfoOutput } from '../cli/info/index.js'; import { type HeadElements } from '../core/base-pipeline.js'; import { ASTRO_VERSION } from '../core/constants.js'; @@ -22,6 +11,15 @@ import { createDefaultRoutes } from '../core/routing/default.js'; import { findRouteToRewrite } from '../core/routing/rewrite.js'; import { isPage, isServerLikeOutput, viteID } from '../core/util.js'; import { resolveIdToUrl } from '../core/viteUtils.js'; +import type { AstroSettings, ComponentInstance, ManifestData } from '../types/astro.js'; +import type { RewritePayload } from '../types/public/common.js'; +import type { + RouteData, + SSRElement, + SSRLoadedRenderer, + SSRManifest, +} from '../types/public/internal.js'; +import type { DevToolbarMetadata } from '../types/public/toolbar.js'; import { PAGE_SCRIPT_ID } from '../vite-plugin-scripts/index.js'; import { getStylesForURL } from './css.js'; import { getComponentMetadata } from './metadata.js'; diff --git a/packages/astro/src/vite-plugin-astro-server/plugin.ts b/packages/astro/src/vite-plugin-astro-server/plugin.ts index 2458b5b8d360..3015f1003f82 100644 --- a/packages/astro/src/vite-plugin-astro-server/plugin.ts +++ b/packages/astro/src/vite-plugin-astro-server/plugin.ts @@ -2,8 +2,7 @@ import { AsyncLocalStorage } from 'node:async_hooks'; import type fs from 'node:fs'; import { IncomingMessage } from 'node:http'; import type * as vite from 'vite'; -import type { AstroSettings, ManifestData, SSRManifest } from '../@types/astro.js'; -import type { SSRManifestI18n } from '../core/app/types.js'; +import type { SSRManifest, SSRManifestI18n } from '../core/app/types.js'; import { createKey } from '../core/encryption.js'; import { getViteErrorPayload } from '../core/errors/dev/index.js'; import { AstroError, AstroErrorData } from '../core/errors/index.js'; @@ -13,6 +12,7 @@ import { createViteLoader } from '../core/module-loader/index.js'; import { injectDefaultRoutes } from '../core/routing/default.js'; import { createRouteManifest } from '../core/routing/index.js'; import { toRoutingStrategy } from '../i18n/utils.js'; +import type { AstroSettings, ManifestData } from '../types/astro.js'; import { baseMiddleware } from './base.js'; import { createController } from './controller.js'; import { recordServerError } from './error.js'; diff --git a/packages/astro/src/vite-plugin-astro-server/request.ts b/packages/astro/src/vite-plugin-astro-server/request.ts index b231bfde35c6..98cf2b5022dd 100644 --- a/packages/astro/src/vite-plugin-astro-server/request.ts +++ b/packages/astro/src/vite-plugin-astro-server/request.ts @@ -1,6 +1,6 @@ import type http from 'node:http'; -import type { ManifestData } from '../@types/astro.js'; import { removeTrailingForwardSlash } from '../core/path.js'; +import type { ManifestData } from '../types/astro.js'; import type { DevServerController } from './controller.js'; import { runWithErrorHandling } from './controller.js'; import { recordServerError } from './error.js'; diff --git a/packages/astro/src/vite-plugin-astro-server/route.ts b/packages/astro/src/vite-plugin-astro-server/route.ts index aa70d5324582..c59af5c80c7a 100644 --- a/packages/astro/src/vite-plugin-astro-server/route.ts +++ b/packages/astro/src/vite-plugin-astro-server/route.ts @@ -1,5 +1,4 @@ import type http from 'node:http'; -import type { ComponentInstance, ManifestData, RouteData } from '../@types/astro.js'; import { REROUTE_DIRECTIVE_HEADER, REWRITE_DIRECTIVE_HEADER_KEY, @@ -13,6 +12,8 @@ import { type SSROptions, getProps } from '../core/render/index.js'; import { createRequest } from '../core/request.js'; import { matchAllRoutes } from '../core/routing/index.js'; import { getSortedPreloadedMatches } from '../prerender/routing.js'; +import type { ComponentInstance, ManifestData } from '../types/astro.js'; +import type { RouteData } from '../types/public/internal.js'; import type { DevPipeline } from './pipeline.js'; import { writeSSRResult, writeWebResponse } from './response.js'; diff --git a/packages/astro/src/vite-plugin-astro-server/scripts.ts b/packages/astro/src/vite-plugin-astro-server/scripts.ts index e21d44116324..95763ab34ae8 100644 --- a/packages/astro/src/vite-plugin-astro-server/scripts.ts +++ b/packages/astro/src/vite-plugin-astro-server/scripts.ts @@ -1,8 +1,8 @@ -import type { SSRElement } from '../@types/astro.js'; import type { ModuleInfo, ModuleLoader } from '../core/module-loader/index.js'; import { createModuleScriptElementWithSrc } from '../core/render/ssr-element.js'; import { viteID } from '../core/util.js'; import { rootRelativePath } from '../core/viteUtils.js'; +import type { SSRElement } from '../types/public/internal.js'; import type { PluginMetadata as AstroPluginMetadata } from '../vite-plugin-astro/types.js'; import { crawlGraph } from './vite.js'; diff --git a/packages/astro/src/vite-plugin-astro/compile.ts b/packages/astro/src/vite-plugin-astro/compile.ts index 8dfb68a16fd1..78d6c416f0ff 100644 --- a/packages/astro/src/vite-plugin-astro/compile.ts +++ b/packages/astro/src/vite-plugin-astro/compile.ts @@ -1,7 +1,7 @@ import { type ESBuildTransformResult, transformWithEsbuild } from 'vite'; -import type { AstroConfig } from '../@types/astro.js'; import { type CompileProps, type CompileResult, compile } from '../core/compile/index.js'; import type { Logger } from '../core/logger/core.js'; +import type { AstroConfig } from '../types/public/config.js'; import { getFileInfo } from '../vite-plugin-utils/index.js'; import type { CompileMetadata } from './types.js'; import { frontmatterRE } from './utils.js'; diff --git a/packages/astro/src/vite-plugin-astro/index.ts b/packages/astro/src/vite-plugin-astro/index.ts index d5968a905953..b7dd0a2b6d6d 100644 --- a/packages/astro/src/vite-plugin-astro/index.ts +++ b/packages/astro/src/vite-plugin-astro/index.ts @@ -1,7 +1,7 @@ import type { SourceDescription } from 'rollup'; import type * as vite from 'vite'; -import type { AstroConfig, AstroSettings } from '../@types/astro.js'; import type { Logger } from '../core/logger/core.js'; +import type { AstroSettings } from '../types/astro.js'; import type { PluginCssMetadata as AstroPluginCssMetadata, PluginMetadata as AstroPluginMetadata, @@ -9,6 +9,7 @@ import type { } from './types.js'; import { normalizePath } from 'vite'; +import type { AstroConfig } from '../types/public/config.js'; import { hasSpecialQueries, normalizeFilename } from '../vite-plugin-utils/index.js'; import { type CompileAstroResult, compileAstro } from './compile.js'; import { handleHotUpdate } from './hmr.js'; diff --git a/packages/astro/src/vite-plugin-astro/types.ts b/packages/astro/src/vite-plugin-astro/types.ts index ee5003941526..195745443e06 100644 --- a/packages/astro/src/vite-plugin-astro/types.ts +++ b/packages/astro/src/vite-plugin-astro/types.ts @@ -1,6 +1,6 @@ import type { HoistedScript, TransformResult } from '@astrojs/compiler'; -import type { PropagationHint } from '../@types/astro.js'; import type { CompileCssResult } from '../core/compile/types.js'; +import type { PropagationHint } from '../types/public/internal.js'; export interface PageOptions { prerender?: boolean; diff --git a/packages/astro/src/vite-plugin-config-alias/index.ts b/packages/astro/src/vite-plugin-config-alias/index.ts index cb9bdc48c186..9b102c5648cb 100644 --- a/packages/astro/src/vite-plugin-config-alias/index.ts +++ b/packages/astro/src/vite-plugin-config-alias/index.ts @@ -1,7 +1,7 @@ import path from 'node:path'; import type { CompilerOptions } from 'typescript'; import { type ResolvedConfig, type Plugin as VitePlugin, normalizePath } from 'vite'; -import type { AstroSettings } from '../@types/astro.js'; +import type { AstroSettings } from '../types/astro.js'; type Alias = { find: RegExp; diff --git a/packages/astro/src/vite-plugin-env/index.ts b/packages/astro/src/vite-plugin-env/index.ts index 350a29b7ffe1..127575f3918a 100644 --- a/packages/astro/src/vite-plugin-env/index.ts +++ b/packages/astro/src/vite-plugin-env/index.ts @@ -4,8 +4,9 @@ import { bold } from 'kleur/colors'; import MagicString from 'magic-string'; import type * as vite from 'vite'; import { loadEnv } from 'vite'; -import type { AstroConfig, AstroSettings } from '../@types/astro.js'; import type { Logger } from '../core/logger/core.js'; +import type { AstroSettings } from '../types/astro.js'; +import type { AstroConfig } from '../types/public/config.js'; interface EnvPluginOptions { settings: AstroSettings; diff --git a/packages/astro/src/vite-plugin-head/index.ts b/packages/astro/src/vite-plugin-head/index.ts index a7e35dedb119..c9ec2460dcb6 100644 --- a/packages/astro/src/vite-plugin-head/index.ts +++ b/packages/astro/src/vite-plugin-head/index.ts @@ -1,11 +1,11 @@ import type { ModuleInfo } from 'rollup'; import type * as vite from 'vite'; -import type { SSRComponentMetadata, SSRResult } from '../@types/astro.js'; import type { AstroBuildPlugin } from '../core/build/plugin.js'; import type { PluginMetadata } from '../vite-plugin-astro/types.js'; import { getParentModuleInfos, getTopLevelPageModuleInfos } from '../core/build/graph.js'; import type { BuildInternals } from '../core/build/internal.js'; +import type { SSRComponentMetadata, SSRResult } from '../types/public/internal.js'; import { getAstroMetadata } from '../vite-plugin-astro/index.js'; // Detect this in comments, both in .astro components and in js/ts files. diff --git a/packages/astro/src/vite-plugin-integrations-container/index.ts b/packages/astro/src/vite-plugin-integrations-container/index.ts index 49122b24fd84..22623284ec45 100644 --- a/packages/astro/src/vite-plugin-integrations-container/index.ts +++ b/packages/astro/src/vite-plugin-integrations-container/index.ts @@ -1,10 +1,11 @@ import type { PluginContext } from 'rollup'; import type { Plugin as VitePlugin } from 'vite'; -import type { AstroSettings, InjectedRoute, ResolvedInjectedRoute } from '../@types/astro.js'; import type { Logger } from '../core/logger/core.js'; +import type { AstroSettings } from '../types/astro.js'; import { normalizePath } from 'vite'; import { runHookServerSetup } from '../integrations/hooks.js'; +import type { InjectedRoute, ResolvedInjectedRoute } from '../types/public/integrations.js'; /** Connect Astro integrations into Vite, as needed. */ export default function astroIntegrationsContainerPlugin({ diff --git a/packages/astro/src/vite-plugin-markdown/content-entry-type.ts b/packages/astro/src/vite-plugin-markdown/content-entry-type.ts index 9b78d8f35149..48a45294ef3a 100644 --- a/packages/astro/src/vite-plugin-markdown/content-entry-type.ts +++ b/packages/astro/src/vite-plugin-markdown/content-entry-type.ts @@ -1,7 +1,7 @@ import { fileURLToPath, pathToFileURL } from 'node:url'; import { createMarkdownProcessor } from '@astrojs/markdown-remark'; -import type { ContentEntryType } from '../@types/astro.js'; import { safeParseFrontmatter } from '../content/utils.js'; +import type { ContentEntryType } from '../types/public/content.js'; export const markdownContentEntryType: ContentEntryType = { extensions: ['.md'], @@ -17,8 +17,8 @@ export const markdownContentEntryType: ContentEntryType = { // We need to handle propagation for Markdown because they support layouts which will bring in styles. handlePropagation: true, - async getRenderFunction(settings) { - const processor = await createMarkdownProcessor(settings.config.markdown); + async getRenderFunction(config) { + const processor = await createMarkdownProcessor(config.markdown); return async function renderToString(entry) { if (!entry.body) { return { diff --git a/packages/astro/src/vite-plugin-markdown/index.ts b/packages/astro/src/vite-plugin-markdown/index.ts index 37af2dc50c53..694b96448fb5 100644 --- a/packages/astro/src/vite-plugin-markdown/index.ts +++ b/packages/astro/src/vite-plugin-markdown/index.ts @@ -7,12 +7,12 @@ import { } from '@astrojs/markdown-remark'; import type { Plugin } from 'vite'; import { normalizePath } from 'vite'; -import type { AstroSettings } from '../@types/astro.js'; import { safeParseFrontmatter } from '../content/utils.js'; import { AstroError, AstroErrorData } from '../core/errors/index.js'; import type { Logger } from '../core/logger/core.js'; import { isMarkdownFile } from '../core/util.js'; import { shorthash } from '../runtime/server/shorthash.js'; +import type { AstroSettings } from '../types/astro.js'; import { createDefaultAstroMetadata } from '../vite-plugin-astro/metadata.js'; import { getFileInfo } from '../vite-plugin-utils/index.js'; import { type MarkdownImagePath, getMarkdownCodeForImages } from './images.js'; diff --git a/packages/astro/src/vite-plugin-mdx/transform-jsx.ts b/packages/astro/src/vite-plugin-mdx/transform-jsx.ts index c3bb8ed76214..31db2793124f 100644 --- a/packages/astro/src/vite-plugin-mdx/transform-jsx.ts +++ b/packages/astro/src/vite-plugin-mdx/transform-jsx.ts @@ -1,7 +1,7 @@ import babel from '@babel/core'; import type { TransformResult } from 'rollup'; -import type { JSXTransformConfig } from '../@types/astro.js'; import { jsxTransformOptions } from '../jsx/transform-options.js'; +import type { JSXTransformConfig } from '../types/astro.js'; import type { PluginMetadata } from '../vite-plugin-astro/types.js'; import { tagExportsPlugin } from './tag.js'; diff --git a/packages/astro/src/vite-plugin-scanner/index.ts b/packages/astro/src/vite-plugin-scanner/index.ts index 842857777a87..2633743ae554 100644 --- a/packages/astro/src/vite-plugin-scanner/index.ts +++ b/packages/astro/src/vite-plugin-scanner/index.ts @@ -2,12 +2,13 @@ import { extname } from 'node:path'; import { bold } from 'kleur/colors'; import type { Plugin as VitePlugin } from 'vite'; import { normalizePath } from 'vite'; -import type { AstroSettings, RouteOptions } from '../@types/astro.js'; import { type Logger } from '../core/logger/core.js'; import { isEndpoint, isPage, isServerLikeOutput } from '../core/util.js'; import { rootRelativePath } from '../core/viteUtils.js'; import { runHookRouteSetup } from '../integrations/hooks.js'; import { getPrerenderDefault } from '../prerender/utils.js'; +import type { AstroSettings } from '../types/astro.js'; +import type { RouteOptions } from '../types/public/integrations.js'; import type { PageOptions } from '../vite-plugin-astro/types.js'; import { scan } from './scan.js'; diff --git a/packages/astro/src/vite-plugin-scanner/scan.ts b/packages/astro/src/vite-plugin-scanner/scan.ts index 52b2d6bd8289..35e3de20a84f 100644 --- a/packages/astro/src/vite-plugin-scanner/scan.ts +++ b/packages/astro/src/vite-plugin-scanner/scan.ts @@ -1,4 +1,4 @@ -import type { AstroSettings } from '../@types/astro.js'; +import type { AstroSettings } from '../types/astro.js'; import type { PageOptions } from '../vite-plugin-astro/types.js'; import * as eslexer from 'es-module-lexer'; diff --git a/packages/astro/src/vite-plugin-scripts/index.ts b/packages/astro/src/vite-plugin-scripts/index.ts index 9b2848923752..f87f6a381cc8 100644 --- a/packages/astro/src/vite-plugin-scripts/index.ts +++ b/packages/astro/src/vite-plugin-scripts/index.ts @@ -1,5 +1,6 @@ import type { ConfigEnv, Plugin as VitePlugin } from 'vite'; -import type { AstroSettings, InjectedScriptStage } from '../@types/astro.js'; +import type { AstroSettings } from '../types/astro.js'; +import type { InjectedScriptStage } from '../types/public/integrations.js'; // NOTE: We can't use the virtual "\0" ID convention because we need to // inject these as ESM imports into actual code, where they would not diff --git a/packages/astro/src/vite-plugin-scripts/page-ssr.ts b/packages/astro/src/vite-plugin-scripts/page-ssr.ts index 00e907b03cc6..05d8be18dacd 100644 --- a/packages/astro/src/vite-plugin-scripts/page-ssr.ts +++ b/packages/astro/src/vite-plugin-scripts/page-ssr.ts @@ -1,7 +1,7 @@ import MagicString from 'magic-string'; import { type Plugin as VitePlugin, normalizePath } from 'vite'; -import type { AstroSettings } from '../@types/astro.js'; import { isPage } from '../core/util.js'; +import type { AstroSettings } from '../types/astro.js'; import { PAGE_SSR_SCRIPT_ID } from './index.js'; export default function astroScriptsPostPlugin({ diff --git a/packages/astro/src/vite-plugin-utils/index.ts b/packages/astro/src/vite-plugin-utils/index.ts index a0133104cbda..2e7948bdd6ea 100644 --- a/packages/astro/src/vite-plugin-utils/index.ts +++ b/packages/astro/src/vite-plugin-utils/index.ts @@ -1,12 +1,12 @@ import { fileURLToPath } from 'node:url'; import ancestor from 'common-ancestor-path'; -import type { AstroConfig } from '../@types/astro.js'; import { appendExtension, appendForwardSlash, removeLeadingForwardSlashWindows, } from '../core/path.js'; import { viteID } from '../core/util.js'; +import type { AstroConfig } from '../types/public/config.js'; export function getFileInfo(id: string, config: AstroConfig) { const sitePathname = appendForwardSlash( diff --git a/packages/astro/templates/actions.mjs b/packages/astro/templates/actions.mjs index 587f6ed9b7c1..823699e15e65 100644 --- a/packages/astro/templates/actions.mjs +++ b/packages/astro/templates/actions.mjs @@ -55,7 +55,7 @@ function toActionProxy(actionCallback = {}, aggregatedPath = '') { /** * @param {*} param argument passed to the action when called server or client-side. * @param {string} path Built path to call action by path name. - * @param {import('../dist/@types/astro.d.ts').APIContext | undefined} context Injected API context when calling actions from the server. + * @param {import('../dist/types/public/context.js').APIContext | undefined} context Injected API context when calling actions from the server. * Usage: `actions.[name](param)`. * @returns {Promise>} */ diff --git a/packages/astro/test/core-image-unconventional-settings.test.js b/packages/astro/test/core-image-unconventional-settings.test.js index edbfab6f6343..b5d5fc6640de 100644 --- a/packages/astro/test/core-image-unconventional-settings.test.js +++ b/packages/astro/test/core-image-unconventional-settings.test.js @@ -6,7 +6,7 @@ import { testImageService } from './test-image-service.js'; import { loadFixture } from './test-utils.js'; /** - ** @typedef {import('../src/@types/astro').AstroInlineConfig & { root?: string | URL }} AstroInlineConfig + ** @typedef {import('../src/types/public/config.js').AstroInlineConfig & { root?: string | URL }} AstroInlineConfig */ /** @type {AstroInlineConfig} */ diff --git a/packages/astro/test/fixtures/core-image-ssr/src/pages/api.ts b/packages/astro/test/fixtures/core-image-ssr/src/pages/api.ts index 261fb6bb7dc7..25777dce8adb 100644 --- a/packages/astro/test/fixtures/core-image-ssr/src/pages/api.ts +++ b/packages/astro/test/fixtures/core-image-ssr/src/pages/api.ts @@ -1,4 +1,4 @@ -import type { APIRoute } from "../../../../../src/@types/astro"; +import type { APIRoute } from "astro" export const GET = (async ({ params, request }) => { const url = new URL(request.url); diff --git a/packages/astro/test/fixtures/ssr-prerender-chunks/deps/test-adapter/index.js b/packages/astro/test/fixtures/ssr-prerender-chunks/deps/test-adapter/index.js index 82b7b64b1fc9..06eb02e2c6ce 100644 --- a/packages/astro/test/fixtures/ssr-prerender-chunks/deps/test-adapter/index.js +++ b/packages/astro/test/fixtures/ssr-prerender-chunks/deps/test-adapter/index.js @@ -1,6 +1,6 @@ /** * - * @returns {import('../src/@types/astro').AstroIntegration} + * @returns {import('../../../../../src/types/public/integrations.js').AstroIntegration} */ export default function () { return { @@ -82,4 +82,4 @@ export default function () { }, }, }; -} \ No newline at end of file +} diff --git a/packages/astro/test/test-adapter.js b/packages/astro/test/test-adapter.js index fc5249561279..4a2ac65d0047 100644 --- a/packages/astro/test/test-adapter.js +++ b/packages/astro/test/test-adapter.js @@ -1,11 +1,11 @@ import { viteID } from '../dist/core/util.js'; /** - * @typedef {import('../src/@types/astro.js').AstroAdapter} AstroAdapter - * @typedef {import('../src/@types/astro.js').AstroIntegration} AstroIntegration - * @typedef {import('../src/@types/astro.js').HookParameters<"astro:build:ssr">['entryPoints']} EntryPoints - * @typedef {import('../src/@types/astro.js').HookParameters<"astro:build:ssr">['middlewareEntryPoint']} MiddlewareEntryPoint - * @typedef {import('../src/@types/astro.js').HookParameters<"astro:build:done">['routes']} Routes + * @typedef {import('../src/types/public/integrations.js').AstroAdapter} AstroAdapter + * @typedef {import('../src/types/public/integrations.js').AstroIntegration} AstroIntegration + * @typedef {import('../src/types/public/integrations.js').HookParameters<"astro:build:ssr">['entryPoints']} EntryPoints + * @typedef {import('../src/types/public/integrations.js').HookParameters<"astro:build:ssr">['middlewareEntryPoint']} MiddlewareEntryPoint + * @typedef {import('../src/types/public/integrations.js').HookParameters<"astro:build:done">['routes']} Routes */ /** diff --git a/packages/astro/test/test-image-service.js b/packages/astro/test/test-image-service.js index 35a5fa2c8625..de076425cd9a 100644 --- a/packages/astro/test/test-image-service.js +++ b/packages/astro/test/test-image-service.js @@ -12,7 +12,7 @@ export function testImageService(config = {}) { }; } -/** @type {import("../dist/@types/astro").LocalImageService} */ +/** @type {import("../dist/types/public/index.js").LocalImageService} */ export default { ...baseService, propertiesToHash: [...baseService.propertiesToHash, 'data-custom'], diff --git a/packages/astro/test/test-utils.js b/packages/astro/test/test-utils.js index 95edeebd2673..115f3c2d5f2e 100644 --- a/packages/astro/test/test-utils.js +++ b/packages/astro/test/test-utils.js @@ -23,8 +23,8 @@ process.env.ASTRO_TELEMETRY_DISABLED = true; /** * @typedef {import('../src/core/dev/dev').DevServer} DevServer - * @typedef {import('../src/@types/astro').AstroInlineConfig & { root?: string | URL }} AstroInlineConfig - * @typedef {import('../src/@types/astro').AstroConfig} AstroConfig + * @typedef {import('../src/types/public/config.js').AstroInlineConfig & { root?: string | URL }} AstroInlineConfig + * @typedef {import('../src/types/public/config.js').AstroConfig} AstroConfig * @typedef {import('../src/core/preview/index').PreviewServer} PreviewServer * @typedef {import('../src/core/app/index').App} App * @typedef {import('../src/cli/check/index').AstroChecker} AstroChecker diff --git a/packages/astro/test/types/call-action.ts b/packages/astro/test/types/call-action.ts index 91610558586f..8cadd1fb06e6 100644 --- a/packages/astro/test/types/call-action.ts +++ b/packages/astro/test/types/call-action.ts @@ -1,6 +1,6 @@ import { describe, it } from 'node:test'; import { expectTypeOf } from 'expect-type'; -import type { APIContext } from '../../dist/@types/astro.js'; +import type { APIContext } from '../../dist/types/public/context.js'; import { type ActionReturnType, defineAction } from '../../dist/actions/runtime/virtual/server.js'; import { z } from '../../zod.mjs'; diff --git a/packages/astro/test/units/test-utils.js b/packages/astro/test/units/test-utils.js index bab850b68530..a104ef2a40a2 100644 --- a/packages/astro/test/units/test-utils.js +++ b/packages/astro/test/units/test-utils.js @@ -211,8 +211,8 @@ export function createBasicPipeline(options = {}) { } /** - * @param {import('../../src/@types/astro.js').AstroInlineConfig} inlineConfig - * @returns {Promise} + * @param {import('../../src/types/public/config.js').AstroInlineConfig} inlineConfig + * @returns {Promise} */ export async function createBasicSettings(inlineConfig = {}) { if (!inlineConfig.root) { @@ -225,7 +225,7 @@ export async function createBasicSettings(inlineConfig = {}) { /** * @typedef {{ * fs?: typeof realFS, - * inlineConfig?: import('../../src/@types/astro.js').AstroInlineConfig, + * inlineConfig?: import('../../src/types/public/config.js').AstroInlineConfig, * logging?: import('../../src/core/logger/core').LogOptions, * }} RunInContainerOptions */ diff --git a/packages/astro/types.d.ts b/packages/astro/types.d.ts index b04f062fdba8..cc0f1c3d2371 100644 --- a/packages/astro/types.d.ts +++ b/packages/astro/types.d.ts @@ -1,6 +1,6 @@ import './astro-jsx'; -import type { AstroBuiltinAttributes } from './dist/@types/astro.js'; import type { OmitIndexSignature, Simplify } from './dist/type-utils.js'; +import type { AstroBuiltinAttributes } from './dist/types/public/elements.js'; /** Any supported HTML or SVG element name, as defined by the HTML specification */ export type HTMLTag = keyof astroHTML.JSX.DefinedIntrinsicElements; diff --git a/packages/integrations/node/test/api-route.test.js b/packages/integrations/node/test/api-route.test.js index 804a5ccf4797..9743ce42d51c 100644 --- a/packages/integrations/node/test/api-route.test.js +++ b/packages/integrations/node/test/api-route.test.js @@ -7,7 +7,7 @@ import { createRequestAndResponse, loadFixture } from './test-utils.js'; describe('API routes', () => { /** @type {import('./test-utils').Fixture} */ let fixture; - /** @type {import('astro/src/@types/astro.js').PreviewServer} */ + /** @type {import('../../../astro/src/types/public/preview.js').PreviewServer} */ let previewServer; /** @type {URL} */ let baseUri;