Skip to content

Commit

Permalink
Remove deprecated APIs (#5707)
Browse files Browse the repository at this point in the history
* Remove deprecated Astro globals

* Remove deprecated hook param

* Fix test

* Add changeset

* Add TODO
  • Loading branch information
bluwy committed Jan 3, 2023
1 parent 8fb2864 commit 5eba34f
Show file tree
Hide file tree
Showing 18 changed files with 87 additions and 217 deletions.
10 changes: 10 additions & 0 deletions .changeset/selfish-tigers-do.md
@@ -0,0 +1,10 @@
---
'@astrojs/cloudflare': major
'@astrojs/deno': major
'@astrojs/image': minor
'@astrojs/netlify': major
'@astrojs/node': major
'@astrojs/vercel': major
---

Remove `astro:build:start` backwards compatibility code
36 changes: 36 additions & 0 deletions .changeset/tricky-rabbits-count.md
@@ -0,0 +1,36 @@
---
'astro': major
---

Remove deprecated `Astro` global APIs, including `Astro.resolve`, `Astro.fetchContent`, and `Astro.canonicalURL`.

#### `Astro.resolve`

You can resolve asset paths using `import` instead. For example:

```astro
---
import 'style.css'
import imageUrl from './image.png'
---
<img src={imageUrl} />
```

See the [v0.25 migration guide](https://docs.astro.build/en/migrate/#deprecated-astroresolve) for more information.

#### `Astro.fetchContent`

Use `Astro.glob` instead to fetch markdown files, or migrate to the [Content Collections](https://docs.astro.build/en/guides/content-collections/) feature.

```js
let allPosts = await Astro.glob('./posts/*.md');
```

#### `Astro.canonicalURL`

Use `Astro.url` instead to construct the canonical URL.

```js
const canonicalURL = new URL(Astro.url.pathname, Astro.site);
```
24 changes: 24 additions & 0 deletions .changeset/two-geese-eat.md
@@ -0,0 +1,24 @@
---
'astro': major
---

Remove `buildConfig` option parameter from integration `astro:build:start` hook in favour of the `build.config` option in the `astro:config:setup` hook.

```js
export default function myIntegration() {
return {
name: 'my-integration',
hooks: {
'astro:config:setup': ({ updateConfig }) => {
updateConfig({
build: {
client: '...',
server: '...',
serverEntry: '...',
},
});
},
},
};
}
```
2 changes: 1 addition & 1 deletion examples/integration/index.ts
Expand Up @@ -10,7 +10,7 @@ export default function createIntegration(): AstroIntegration {
// See the @astrojs/react integration for an example
// https://github.com/withastro/astro/blob/main/packages/integrations/react/src/index.ts
},
'astro:build:start': ({ buildConfig }) => {
'astro:build:setup': ({ config, updateConfig }) => {
// See the @astrojs/netlify integration for an example
// https://github.com/withastro/astro/blob/main/packages/integrations/netlify/src/integration-functions.ts
},
Expand Down
20 changes: 1 addition & 19 deletions packages/astro/src/@types/astro.ts
Expand Up @@ -109,18 +109,6 @@ export interface BuildConfig {
export interface AstroGlobal<Props extends Record<string, any> = Record<string, any>>
extends AstroGlobalPartial,
AstroSharedContext<Props> {
/**
* Canonical URL of the current page.
* @deprecated Use `Astro.url` instead.
*
* Example:
* ```astro
* ---
* const canonicalURL = new URL(Astro.url.pathname, Astro.site);
* ---
* ```
*/
canonicalURL: URL;
/**
* A full URL object of the request URL.
* Equivalent to: `new URL(Astro.request.url)`
Expand Down Expand Up @@ -254,12 +242,6 @@ export interface AstroGlobal<Props extends Record<string, any> = Record<string,
type MarkdowFileExtension = typeof SUPPORTED_MARKDOWN_FILE_EXTENSIONS[number];

export interface AstroGlobalPartial {
/**
* @deprecated since version 0.24. See the {@link https://astro.build/deprecated/resolve upgrade guide} for more details.
*/
resolve(path: string): string;
/** @deprecated since version 0.26. Use [Astro.glob()](https://docs.astro.build/en/reference/api-reference/#astroglob) instead. */
fetchContent(globStr: string): Promise<any[]>;
/**
* Fetch local files into your static site setup
*
Expand Down Expand Up @@ -1390,7 +1372,7 @@ export interface AstroIntegration {
'astro:server:start'?: (options: { address: AddressInfo }) => void | Promise<void>;
'astro:server:done'?: () => void | Promise<void>;
'astro:build:ssr'?: (options: { manifest: SerializedSSRManifest }) => void | Promise<void>;
'astro:build:start'?: (options: { buildConfig: BuildConfig }) => void | Promise<void>;
'astro:build:start'?: () => void | Promise<void>;
'astro:build:setup'?: (options: {
vite: vite.InlineConfig;
pages: Map<string, PageBuildData>;
Expand Down
2 changes: 1 addition & 1 deletion packages/astro/src/core/build/index.ts
Expand Up @@ -90,7 +90,7 @@ class AstroBuilder {
server: this.settings.config.build.server,
serverEntry: this.settings.config.build.serverEntry,
};
await runHookBuildStart({ config: this.settings.config, buildConfig, logging: this.logging });
await runHookBuildStart({ config: this.settings.config, logging: this.logging });
this.validateConfig();

info(this.logging, 'build', `output target: ${colors.green(this.settings.config.output)}`);
Expand Down
51 changes: 1 addition & 50 deletions packages/astro/src/core/render/result.ts
Expand Up @@ -183,7 +183,7 @@ export function createResult(args: CreateResultArgs): SSRResult {
}
}

return Reflect.get(request, clientAddressSymbol);
return Reflect.get(request, clientAddressSymbol) as string;
},
get cookies() {
if (cookies) {
Expand All @@ -207,59 +207,10 @@ export function createResult(args: CreateResultArgs): SSRResult {
});
}
: onlyAvailableInSSR('Astro.redirect'),
resolve(path: string) {
let extra = `This can be replaced with a dynamic import like so: await import("${path}")`;
if (isCSSRequest(path)) {
extra = `It looks like you are resolving styles. If you are adding a link tag, replace with this:
---
import "${path}";
---
`;
} else if (isScriptRequest(path)) {
extra = `It looks like you are resolving scripts. If you are adding a script tag, replace with this:
<script type="module" src={(await import("${path}?url")).default}></script>
or consider make it a module like so:
<script>
import MyModule from "${path}";
</script>
`;
}

warn(
args.logging,
`deprecation`,
`${bold(
'Astro.resolve()'
)} is deprecated. We see that you are trying to resolve ${path}.
${extra}`
);
// Intentionally return an empty string so that it is not relied upon.
return '';
},
response: response as AstroGlobal['response'],
slots: astroSlots as unknown as AstroGlobal['slots'],
};

Object.defineProperty(Astro, 'canonicalURL', {
get: function () {
warn(
args.logging,
'deprecation',
`${bold('Astro.canonicalURL')} is deprecated! Use \`Astro.url\` instead.
Example:
---
const canonicalURL = new URL(Astro.url.pathname, Astro.site);
---
`
);
return new URL(this.request.url.pathname, this.site);
},
});

Object.defineProperty(Astro, '__renderMarkdown', {
// Ensure this API is not exposed to users
enumerable: false,
Expand Down
39 changes: 1 addition & 38 deletions packages/astro/src/integrations/index.ts
Expand Up @@ -206,55 +206,18 @@ export async function runHookServerDone({

export async function runHookBuildStart({
config,
buildConfig,
logging,
}: {
config: AstroConfig;
buildConfig: BuildConfig;
logging: LogOptions;
}) {
function warnDeprecated(
integration: AstroIntegration,
prop: 'server' | 'client' | 'serverEntry'
) {
let value: any = Reflect.get(buildConfig, prop);
Object.defineProperty(buildConfig, prop, {
enumerable: true,
get() {
return value;
},
set(newValue) {
value = newValue;
warn(
logging,
'astro:build:start',
`Your adapter ${bold(integration.name)} is using a deprecated API, buildConfig. ${bold(
prop
)} config should be set via config.build.${prop} instead.`
);
},
});
return () => {
Object.defineProperty(buildConfig, prop, {
enumerable: true,
value,
});
};
}

for (const integration of config.integrations) {
if (integration?.hooks?.['astro:build:start']) {
const undoClientWarning = warnDeprecated(integration, 'client');
const undoServerWarning = warnDeprecated(integration, 'server');
const undoServerEntryWarning = warnDeprecated(integration, 'serverEntry');
await withTakingALongTimeMsg({
name: integration.name,
hookResult: integration.hooks['astro:build:start']({ buildConfig }),
hookResult: integration.hooks['astro:build:start'](),
logging,
});
undoClientWarning();
undoServerEntryWarning();
undoServerWarning();
}
}
}
Expand Down
31 changes: 5 additions & 26 deletions packages/astro/src/runtime/server/astro-global.ts
@@ -1,13 +1,6 @@
import type { AstroGlobalPartial } from '../../@types/astro';
import { ASTRO_VERSION } from '../../core/constants.js';

/** Create the Astro.fetchContent() runtime function. */
function createDeprecatedFetchContentFn() {
return () => {
throw new Error('Deprecated: Astro.fetchContent() has been replaced with Astro.glob().');
};
}

/** Create the Astro.glob() runtime function. */
function createAstroGlobFn() {
const globHandler = (importMetaGlobResult: Record<string, any>, globValue: () => any) => {
Expand All @@ -25,29 +18,15 @@ function createAstroGlobFn() {

// This is used to create the top-level Astro global; the one that you can use
// Inside of getStaticPaths.
// TODO: remove `_filePathname` and `_projectRootStr` from the compiler
export function createAstro(
filePathname: string,
_site: string | undefined,
projectRootStr: string
_filePathname: string,
site: string | undefined,
_projectRootStr: string
): AstroGlobalPartial {
const site = _site ? new URL(_site) : undefined;
const referenceURL = new URL(filePathname, `http://localhost`);
const projectRoot = new URL(projectRootStr);
return {
site,
site: site ? new URL(site) : undefined,
generator: `Astro v${ASTRO_VERSION}`,
fetchContent: createDeprecatedFetchContentFn(),
glob: createAstroGlobFn(),
// INVESTIGATE is there a use-case for multi args?
// TODO remove in 2.0
resolve(...segments: string[]) {
let resolved = segments.reduce((u, segment) => new URL(segment, u), referenceURL).pathname;
// When inside of project root, remove the leading path so you are
// left with only `/src/images/tower.png`
if (resolved.startsWith(projectRoot.pathname)) {
resolved = '/' + resolved.slice(projectRoot.pathname.length);
}
return resolved;
},
};
}
15 changes: 6 additions & 9 deletions packages/astro/test/ssr-adapter-build-config.test.js
@@ -1,5 +1,4 @@
import { expect } from 'chai';
import { load as cheerioLoad } from 'cheerio';
import { loadFixture } from './test-utils.js';
import { viteID } from '../dist/core/util.js';

Expand All @@ -8,15 +7,18 @@ describe('Integration buildConfig hook', () => {
let fixture;

before(async () => {
let _config;
fixture = await loadFixture({
root: './fixtures/ssr-request/',
output: 'server',
adapter: {
name: 'my-ssr-adapter',
hooks: {
'astro:config:setup': ({ updateConfig }) => {
'astro:config:setup': ({ config, updateConfig }) => {
updateConfig({
build: {
server: new URL('./dist/.root/server/', config.root),
client: new URL('./dist/.root/client/', config.root),
},
vite: {
plugins: [
{
Expand All @@ -40,12 +42,7 @@ describe('Integration buildConfig hook', () => {
},
});
},
'astro:build:start': ({ buildConfig }) => {
buildConfig.server = new URL('./dist/.root/server/', _config.root);
buildConfig.client = new URL('./dist/.root/client/', _config.root);
},
'astro:config:done': ({ config, setAdapter }) => {
_config = config;
'astro:config:done': ({ setAdapter }) => {
setAdapter({
name: 'my-ssr-adapter',
serverEntrypoint: '@my-ssr',
Expand Down
10 changes: 0 additions & 10 deletions packages/integrations/cloudflare/src/index.ts
Expand Up @@ -39,14 +39,12 @@ const SERVER_BUILD_FOLDER = '/$server_build/';
export default function createIntegration(args?: Options): AstroIntegration {
let _config: AstroConfig;
let _buildConfig: BuildConfig;
let needsBuildConfig = false;
const isModeDirectory = args?.mode === 'directory';

return {
name: '@astrojs/cloudflare',
hooks: {
'astro:config:setup': ({ config, updateConfig }) => {
needsBuildConfig = !config.build.client;
updateConfig({
build: {
client: new URL(`.${config.base}`, config.outDir),
Expand Down Expand Up @@ -90,14 +88,6 @@ export default function createIntegration(args?: Options): AstroIntegration {
vite.ssr.target = vite.ssr.target || 'webworker';
}
},
'astro:build:start': ({ buildConfig }) => {
// Backwards compat
if (needsBuildConfig) {
buildConfig.client = new URL(`.${_config.base}`, _config.outDir);
buildConfig.server = new URL(`.${SERVER_BUILD_FOLDER}`, _config.outDir);
buildConfig.serverEntry = '_worker.js';
}
},
'astro:build:done': async () => {
const entryPath = fileURLToPath(new URL(_buildConfig.serverEntry, _buildConfig.server)),
entryUrl = new URL(_buildConfig.serverEntry, _config.outDir),
Expand Down

0 comments on commit 5eba34f

Please sign in to comment.