Skip to content

Commit

Permalink
fix: --experimental-ssr fixes (withastro#2937)
Browse files Browse the repository at this point in the history
* Replaced `--experimental-ssr` with `isBuildingToSSR`

* changest

* Improved `isBuildingToSSR` a bit

* Added `isBuildingToSSR` to more places!!1!

* Added `@deprecated` tag

* Replaced missing experimentalSsr

* Added failing test

* Removed test

* Re-added experimental ssr flag

* Fixed typo

Co-authored-by: Matthew Phillips <matthew@skypack.dev>

* Fixed deno tests

Co-authored-by: Matthew Phillips <matthew@skypack.dev>
  • Loading branch information
JuanM04 and matthewp authored Mar 31, 2022
1 parent af0568a commit 89b4644
Show file tree
Hide file tree
Showing 13 changed files with 44 additions and 28 deletions.
3 changes: 2 additions & 1 deletion src/@types/astro.ts
Original file line number Diff line number Diff line change
Expand Up @@ -345,7 +345,8 @@ export interface AstroUserConfig {
*/
experimentalStaticBuild?: boolean;
/**
* Enable a build for SSR support.
* Enable SSR support for 3rd-party adapters.
* Not required when using a built-in adapter.
* Default: false
*/
experimentalSsr?: boolean;
Expand Down
2 changes: 1 addition & 1 deletion src/cli/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ function printAstroHelp() {
['--project-root <path>', 'Specify the path to the project root folder.'],
['--no-sitemap', 'Disable sitemap generation (build only).'],
['--legacy-build', 'Use the build strategy prior to 0.24.0'],
['--experimental-ssr', 'Enable SSR compilation.'],
['--experimental-ssr', 'Enable SSR compilation fot 3rd-party adapters.'],
['--drafts', 'Include markdown draft pages in the build.'],
['--verbose', 'Enable verbose logging'],
['--silent', 'Disable logging'],
Expand Down
6 changes: 3 additions & 3 deletions src/core/build/generate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import { BEFORE_HYDRATION_SCRIPT_ID } from '../../vite-plugin-scripts/index.js';
import { call as callEndpoint } from '../endpoint/index.js';
import { render } from '../render/core.js';
import { createLinkStylesheetElementSet, createModuleScriptElementWithSrcSet } from '../render/ssr-element.js';
import { getOutputFilename } from '../util.js';
import { getOutputFilename, isBuildingToSSR } from '../util.js';
import { getOutFile, getOutFolder } from './common.js';
import { eachPageData, getPageDataByComponent } from './internal.js';
import type { PageBuildData, SingleFileBuiltModule, StaticBuildOptions } from './types';
Expand Down Expand Up @@ -71,7 +71,7 @@ export async function generatePages(result: RollupOutput, opts: StaticBuildOptio
const timer = performance.now();
info(opts.logging, null, `\n${bgGreen(black(' generating static routes '))}`);

const ssr = !!opts.astroConfig._ctx.adapter?.serverEntrypoint;
const ssr = isBuildingToSSR(opts.astroConfig);
const serverEntry = opts.buildConfig.serverEntry;
const outFolder = ssr ? opts.buildConfig.server : opts.astroConfig.dist;
const ssrEntryURL = new URL('./' + serverEntry + `?time=${Date.now()}`, outFolder);
Expand Down Expand Up @@ -197,7 +197,7 @@ async function generatePath(pathname: string, opts: StaticBuildOptions, gopts: G
route: pageData.route,
routeCache,
site: astroConfig.buildOptions.site,
ssr: opts.astroConfig.buildOptions.experimentalSsr,
ssr: isBuildingToSSR(opts.astroConfig),
};

let body: string;
Expand Down
6 changes: 3 additions & 3 deletions src/core/build/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ import { staticBuild } from './static-build.js';
import { RouteCache } from '../render/route-cache.js';
import { runHookBuildDone, runHookBuildStart, runHookConfigDone, runHookConfigSetup } from '../../integrations/index.js';
import { getTimeStat } from './util.js';
import { createSafeError } from '../util.js';
import { createSafeError, isBuildingToSSR } from '../util.js';
import { fixViteErrorMessage } from '../errors.js';

export interface BuildOptions {
Expand Down Expand Up @@ -101,7 +101,7 @@ class AstroBuilder {
origin,
routeCache: this.routeCache,
viteServer,
ssr: this.config.buildOptions.experimentalSsr,
ssr: isBuildingToSSR(this.config),
});

// Filter pages by using conditions based on their frontmatter.
Expand Down Expand Up @@ -182,7 +182,7 @@ class AstroBuilder {
await runHookBuildDone({ config: this.config, pages: pageNames, routes: Object.values(allPages).map((pd) => pd.route) });

if (this.logging.level && levels[this.logging.level] <= levels['info']) {
const buildMode = this.config.buildOptions.experimentalSsr ? 'ssr' : 'static';
const buildMode = isBuildingToSSR(this.config) ? 'ssr' : 'static';
await this.printStats({ logging: this.logging, timeStart: this.timer.init, pageCount: pageNames.length, buildMode });
}
}
Expand Down
3 changes: 2 additions & 1 deletion src/core/build/page-data.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import { debug } from '../logger/core.js';
import { preload as ssrPreload } from '../render/dev/index.js';
import { generateRssFunction } from '../render/rss.js';
import { callGetStaticPaths, RouteCache, RouteCacheEntry } from '../render/route-cache.js';
import { isBuildingToSSR } from '../util.js';

export interface CollectPagesDataOptions {
astroConfig: AstroConfig;
Expand All @@ -33,7 +34,7 @@ export async function collectPagesData(opts: CollectPagesDataOptions): Promise<C
const assets: Record<string, string> = {};
const allPages: AllPagesData = {};

const buildMode = astroConfig.buildOptions.experimentalSsr ? 'ssr' : 'static';
const buildMode = isBuildingToSSR(astroConfig) ? 'ssr' : 'static';

const dataCollectionLogTimeout = setInterval(() => {
info(opts.logging, 'build', 'The data collection step may take longer for larger projects...');
Expand Down
2 changes: 1 addition & 1 deletion src/core/build/static-build.ts
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,7 @@ export async function staticBuild(opts: StaticBuildOptions) {

async function ssrBuild(opts: StaticBuildOptions, internals: BuildInternals, input: Set<string>) {
const { astroConfig, viteConfig } = opts;
const ssr = astroConfig.buildOptions.experimentalSsr;
const ssr = isBuildingToSSR(astroConfig);
const out = ssr ? opts.buildConfig.server : astroConfig.dist;

const viteBuildConfig = {
Expand Down
7 changes: 1 addition & 6 deletions src/core/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -261,12 +261,7 @@ function mergeCLIFlags(astroConfig: AstroUserConfig, flags: CLIFlags) {
if (typeof flags.host === 'string' || typeof flags.host === 'boolean') astroConfig.devOptions.host = flags.host;
if (typeof flags.hostname === 'string') astroConfig.devOptions.hostname = flags.hostname;
if (typeof flags.legacyBuild === 'boolean') astroConfig.buildOptions.legacyBuild = flags.legacyBuild;
if (typeof flags.experimentalSsr === 'boolean') {
astroConfig.buildOptions.experimentalSsr = flags.experimentalSsr;
if (flags.experimentalSsr) {
astroConfig.buildOptions.legacyBuild = false;
}
}
if (typeof flags.experimentalSsr === 'boolean') astroConfig.buildOptions.experimentalSsr = flags.experimentalSsr;
if (typeof flags.experimentalIntegrations === 'boolean') astroConfig.experimentalIntegrations = flags.experimentalIntegrations;
if (typeof flags.drafts === 'boolean') astroConfig.buildOptions.drafts = flags.drafts;
return astroConfig;
Expand Down
3 changes: 2 additions & 1 deletion src/core/endpoint/dev/index.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
import type { EndpointHandler } from '../../../@types/astro';
import type { SSROptions } from '../../render/dev';
import { preload } from '../../render/dev/index.js';
import { isBuildingToSSR } from '../../util.js';
import { call as callEndpoint } from '../index.js';

export async function call(ssrOpts: SSROptions) {
const [, mod] = await preload(ssrOpts);
return await callEndpoint(mod as unknown as EndpointHandler, {
...ssrOpts,
ssr: ssrOpts.astroConfig.buildOptions.experimentalSsr,
ssr: isBuildingToSSR(ssrOpts.astroConfig),
});
}
4 changes: 3 additions & 1 deletion src/core/render/dev/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ import { createModuleScriptElementWithSrcSet } from '../ssr-element.js';
import { getStylesForURL } from './css.js';
import { getHmrScript } from './hmr.js';
import { injectTags } from './html.js';
import { isBuildingToSSR } from '../../util.js';

export interface SSROptions {
/** an instance of the AstroConfig */
astroConfig: AstroConfig;
Expand Down Expand Up @@ -146,7 +148,7 @@ export async function render(renderers: SSRLoadedRenderer[], mod: ComponentInsta
route,
routeCache,
site: astroConfig.buildOptions.site,
ssr: astroConfig.buildOptions.experimentalSsr,
ssr: isBuildingToSSR(astroConfig),
});

if (route?.type === 'endpoint' || content.type === 'response') {
Expand Down
22 changes: 21 additions & 1 deletion src/core/util.ts
Original file line number Diff line number Diff line change
Expand Up @@ -139,7 +139,27 @@ export function emptyDir(_dir: URL, skip?: Set<string>): void {
}

export function isBuildingToSSR(config: AstroConfig): boolean {
return !!config._ctx.adapter?.serverEntrypoint;
const adapter = config._ctx.adapter;
if (!adapter) return false;

if (typeof adapter.serverEntrypoint === 'string') {
if (!adapter.name.startsWith('@astrojs/') && !config.buildOptions.experimentalSsr) {
throw new Error(
[
`Server-side rendering (SSR) is still experimental.`,
``,
`Only official "@astrojs/*" adapters are currently supported.`,
`To enable SSR for 3rd-party adapters, use the "--experimental-ssr" flag.`,
`Breaking changes may occur in this API before Astro v1.0 is released.`,
``,
].join('\n')
);
} else {
return true;
}
} else {
return false;
}
}

export function emoji(char: string, fallback: string) {
Expand Down
6 changes: 3 additions & 3 deletions src/vite-plugin-astro-server/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import { debug, info, warn, error, LogOptions } from '../core/logger/core.js';
import { getParamsAndProps, GetParamsAndPropsError } from '../core/render/core.js';
import { createRouteManifest, matchRoute } from '../core/routing/index.js';
import stripAnsi from 'strip-ansi';
import { createSafeError } from '../core/util.js';
import { createSafeError, isBuildingToSSR } from '../core/util.js';
import { ssr, preload } from '../core/render/dev/index.js';
import { call as callEndpoint } from '../core/endpoint/dev/index.js';
import * as msg from '../core/messages.js';
Expand Down Expand Up @@ -123,7 +123,7 @@ async function handleRequest(
const site = config.buildOptions.site ? new URL(config.buildOptions.site) : undefined;
const devRoot = site ? site.pathname : '/';
const origin = `${viteServer.config.server.https ? 'https' : 'http'}://${req.headers.host}`;
const buildingToSSR = !!config._ctx.adapter?.serverEntrypoint;
const buildingToSSR = isBuildingToSSR(config);
const url = new URL(origin + req.url);
const pathname = decodeURI(url.pathname);
const rootRelativeUrl = pathname.substring(devRoot.length - 1);
Expand Down Expand Up @@ -185,7 +185,7 @@ async function handleRequest(
routeCache,
pathname: rootRelativeUrl,
logging,
ssr: config.buildOptions.experimentalSsr,
ssr: isBuildingToSSR(config),
});
if (paramsAndPropsRes === GetParamsAndPropsError.NoMatchingStaticPath) {
warn(logging, 'getStaticPaths', `Route pattern matched, but no matching static path found. (${pathname})`);
Expand Down
4 changes: 1 addition & 3 deletions test/ssr-api-route.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,7 @@ describe('API routes in SSR', () => {
before(async () => {
fixture = await loadFixture({
projectRoot: './fixtures/ssr-api-route/',
buildOptions: {
experimentalSsr: true,
},
buildOptions: { experimentalSsr: true },
adapter: testAdapter(),
});
await fixture.build();
Expand Down
4 changes: 1 addition & 3 deletions test/ssr-dynamic.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,7 @@ describe('Dynamic pages in SSR', () => {
before(async () => {
fixture = await loadFixture({
projectRoot: './fixtures/ssr-dynamic/',
buildOptions: {
experimentalSsr: true,
},
buildOptions: { experimentalSsr: true },
adapter: testAdapter(),
});
await fixture.build();
Expand Down

0 comments on commit 89b4644

Please sign in to comment.