Skip to content

Commit

Permalink
fix: correctly emit middleware file name (#7427)
Browse files Browse the repository at this point in the history
  • Loading branch information
ematipico authored Jun 20, 2023
1 parent 008af95 commit e314a04
Show file tree
Hide file tree
Showing 10 changed files with 47 additions and 28 deletions.
5 changes: 5 additions & 0 deletions .changeset/great-crabs-march.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'astro': patch
---

Correctly emit the middleware code during the build phase. The file emitted is now `dist/middleware.mjs`
7 changes: 3 additions & 4 deletions packages/astro/src/core/app/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -236,12 +236,11 @@ export class App {
site: this.#env.site,
adapterName: this.#env.adapterName,
});
const onRequest = page.middleware?.onRequest;
let response;
if (onRequest) {
if (page.onRequest) {
response = await callMiddleware<Response>(
this.#env.logging,
onRequest as MiddlewareResponseHandler,
page.onRequest as MiddlewareResponseHandler,
apiContext,
() => {
return renderPage({ mod, renderContext, env: this.#env, apiContext });
Expand Down Expand Up @@ -287,7 +286,7 @@ export class App {
mod: handler as any,
});

const result = await callEndpoint(handler, this.#env, ctx, this.#logging, page.middleware);
const result = await callEndpoint(handler, this.#env, ctx, this.#logging, page.onRequest);

if (result.type === 'response') {
if (result.response.headers.get('X-Astro-Response') === 'Not-Found') {
Expand Down
10 changes: 5 additions & 5 deletions packages/astro/src/core/build/generate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import type {
EndpointOutput,
GetStaticPathsItem,
ImageTransform,
MiddlewareHandler,
MiddlewareResponseHandler,
RouteData,
RouteType,
Expand Down Expand Up @@ -229,7 +230,7 @@ async function generatePage(
.reduce(mergeInlineCss, []);

const pageModulePromise = ssrEntry.page;
const middleware = ssrEntry.middleware;
const onRequest = ssrEntry.onRequest;

if (!pageModulePromise) {
throw new Error(
Expand Down Expand Up @@ -264,7 +265,7 @@ async function generatePage(

for (let i = 0; i < paths.length; i++) {
const path = paths[i];
await generatePath(path, opts, generationOptions, middleware);
await generatePath(path, opts, generationOptions, onRequest);
const timeEnd = performance.now();
const timeChange = getTimeStat(timeStart, timeEnd);
const timeIncrease = `(+${timeChange})`;
Expand Down Expand Up @@ -448,7 +449,7 @@ async function generatePath(
pathname: string,
opts: StaticBuildOptions,
gopts: GeneratePathOptions,
middleware?: AstroMiddlewareInstance<unknown>
onRequest?: MiddlewareHandler<unknown>
) {
const { settings, logging, origin, routeCache } = opts;
const {
Expand Down Expand Up @@ -569,7 +570,7 @@ async function generatePath(
env,
renderContext,
logging,
middleware as AstroMiddlewareInstance<Response | EndpointOutput>
onRequest as MiddlewareHandler<Response | EndpointOutput>
);

if (result.type === 'response') {
Expand All @@ -593,7 +594,6 @@ async function generatePath(
adapterName: env.adapterName,
});

const onRequest = middleware?.onRequest;
if (onRequest) {
response = await callMiddleware<Response>(
env.logging,
Expand Down
18 changes: 18 additions & 0 deletions packages/astro/src/core/build/plugins/plugin-middleware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,25 +3,43 @@ import { MIDDLEWARE_PATH_SEGMENT_NAME } from '../../constants.js';
import type { BuildInternals } from '../internal.js';
import type { AstroBuildPlugin } from '../plugin';
import type { StaticBuildOptions } from '../types';
import { addRollupInput } from '../add-rollup-input.js';

export const MIDDLEWARE_MODULE_ID = '@astro-middleware';

const EMPTY_MIDDLEWARE = '\0empty-middleware';

export function vitePluginMiddleware(
opts: StaticBuildOptions,
_internals: BuildInternals
): VitePlugin {
return {
name: '@astro/plugin-middleware',

options(options) {
return addRollupInput(options, [MIDDLEWARE_MODULE_ID]);
},

async resolveId(id) {
if (id === MIDDLEWARE_MODULE_ID) {
const middlewareId = await this.resolve(
`${opts.settings.config.srcDir.pathname}/${MIDDLEWARE_PATH_SEGMENT_NAME}`
);
if (middlewareId) {
return middlewareId.id;
} else {
return EMPTY_MIDDLEWARE;
}
}
if (id === EMPTY_MIDDLEWARE) {
return EMPTY_MIDDLEWARE;
}
},

load(id) {
if (id === EMPTY_MIDDLEWARE) {
return 'export const onRequest = undefined';
}
},
};
}
Expand Down
4 changes: 2 additions & 2 deletions packages/astro/src/core/build/plugins/plugin-pages.ts
Original file line number Diff line number Diff line change
Expand Up @@ -82,8 +82,8 @@ function vitePluginPages(opts: StaticBuildOptions, internals: BuildInternals): V

const middlewareModule = await this.resolve(MIDDLEWARE_MODULE_ID);
if (middlewareModule) {
imports.push(`import * as middleware from "${middlewareModule.id}";`);
exports.push(`export { middleware };`);
imports.push(`import { onRequest } from "${middlewareModule.id}";`);
exports.push(`export { onRequest };`);
}

return `${imports.join('\n')}${exports.join('\n')}`;
Expand Down
8 changes: 2 additions & 6 deletions packages/astro/src/core/build/static-build.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ import { RESOLVED_RENDERERS_MODULE_ID } from './plugins/plugin-renderers.js';
import { SSR_VIRTUAL_MODULE_ID } from './plugins/plugin-ssr.js';
import type { AllPagesData, PageBuildData, StaticBuildOptions } from './types';
import { getTimeStat } from './util.js';
import { MIDDLEWARE_MODULE_ID } from './plugins/plugin-middleware.js';

export async function viteBuild(opts: StaticBuildOptions) {
const { allPages, settings } = opts;
Expand Down Expand Up @@ -176,12 +177,7 @@ async function ssrBuild(
entryFileNames(chunkInfo) {
if (chunkInfo.facadeModuleId?.startsWith(ASTRO_PAGE_RESOLVED_MODULE_ID)) {
return makeAstroPageEntryPointFileName(chunkInfo.facadeModuleId, allPages);
} else if (
// checks if the path of the module we have middleware, e.g. middleware.js / middleware/index.js
chunkInfo.moduleIds.find((m) => m.includes('middleware')) !== undefined &&
// checks if the file actually export the `onRequest` function
chunkInfo.exports.includes('_middleware')
) {
} else if (chunkInfo.facadeModuleId === MIDDLEWARE_MODULE_ID) {
return 'middleware.mjs';
} else if (chunkInfo.facadeModuleId === SSR_VIRTUAL_MODULE_ID) {
return opts.settings.config.build.serverEntry;
Expand Down
6 changes: 5 additions & 1 deletion packages/astro/src/core/build/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import type {
BuildConfig,
ComponentInstance,
ManifestData,
MiddlewareHandler,
RouteData,
RuntimeMode,
SSRLoadedRenderer,
Expand Down Expand Up @@ -51,7 +52,10 @@ type ImportComponentInstance = () => Promise<ComponentInstance>;

export interface SinglePageBuiltModule {
page: ImportComponentInstance;
middleware: AstroMiddlewareInstance<unknown>;
/**
* The `onRequest` hook exported by the middleware
*/
onRequest?: MiddlewareHandler<unknown>;
renderers: SSRLoadedRenderer[];
}

Expand Down
2 changes: 1 addition & 1 deletion packages/astro/src/core/endpoint/dev/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,5 +21,5 @@ export async function call(options: SSROptions, logging: LogOptions) {
mod: endpointHandler as any,
});

return await callEndpoint(endpointHandler, env, ctx, logging, middleware);
return await callEndpoint(endpointHandler, env, ctx, logging, middleware?.onRequest);
}
8 changes: 4 additions & 4 deletions packages/astro/src/core/endpoint/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import type {
EndpointHandler,
EndpointOutput,
MiddlewareEndpointHandler,
MiddlewareHandler,
Params,
} from '../../@types/astro';
import type { Environment, RenderContext } from '../render/index';
Expand Down Expand Up @@ -97,7 +98,7 @@ export async function callEndpoint<MiddlewareResult = Response | EndpointOutput>
env: Environment,
ctx: RenderContext,
logging: LogOptions,
middleware?: AstroMiddlewareInstance<MiddlewareResult> | undefined
onRequest?: MiddlewareHandler<MiddlewareResult> | undefined
): Promise<EndpointCallResult> {
const context = createAPIContext({
request: ctx.request,
Expand All @@ -108,11 +109,10 @@ export async function callEndpoint<MiddlewareResult = Response | EndpointOutput>
});

let response;
if (middleware && middleware.onRequest) {
const onRequest = middleware.onRequest as MiddlewareEndpointHandler;
if (onRequest) {
response = await callMiddleware<Response | EndpointOutput>(
env.logging,
onRequest,
onRequest as MiddlewareEndpointHandler,
context,
async () => {
return await renderEndpoint(mod, context, env.ssr);
Expand Down
7 changes: 2 additions & 5 deletions packages/astro/src/core/redirects/component.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import type { AstroMiddlewareInstance, ComponentInstance } from '../../@types/astro';
import type { SinglePageBuiltModule } from '../build/types';
import type { MiddlewareHandler } from '../../@types/astro';

// A stub of a component instance for a given route
export const RedirectComponentInstance: ComponentInstance = {
Expand All @@ -10,12 +11,8 @@ export const RedirectComponentInstance: ComponentInstance = {
},
};

const StaticMiddlewareInstance: AstroMiddlewareInstance<unknown> = {
onRequest: (ctx, next) => next(),
};

export const RedirectSinglePageBuiltModule: SinglePageBuiltModule = {
page: () => Promise.resolve(RedirectComponentInstance),
middleware: StaticMiddlewareInstance,
onRequest: (ctx, next) => next(),
renderers: [],
};

0 comments on commit e314a04

Please sign in to comment.