Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
55 changes: 44 additions & 11 deletions src/presets/vercel/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,12 @@ import fsp from "node:fs/promises";
import { defu } from "defu";
import mime from "mime";
import { writeFile } from "nitropack/kit";
import type { Nitro, NitroRouteRules, PrerenderRoute } from "nitropack/types";
import type {
Nitro,
NitroRouteRules,
PrerenderRoute,
PublicAssetDir,
} from "nitropack/types";
import { dirname, relative, resolve } from "pathe";
import {
joinURL,
Expand Down Expand Up @@ -177,6 +182,10 @@ function generateBuildConfig(nitro: Nitro, o11Routes?: ObservabilityRoute[]) {
const routeSrc = (route: string, requireCatchAll?: boolean) =>
`^${routeToVercelSrc(route, { baseURL: nitro.options.baseURL, requireCatchAll })}$`;

const publicAssetRoutes = getPublicAssetRoutes(nitro.options.publicAssets, {
baseURL: nitro.options.baseURL,
});

const config = defu(nitro.options.vercel?.config, <VercelBuildConfigV3>{
version: 3,
framework: {
Expand Down Expand Up @@ -241,17 +250,22 @@ function generateBuildConfig(nitro: Nitro, o11Routes?: ObservabilityRoute[]) {
]
: []),
// Public asset rules
...nitro.options.publicAssets
.filter((asset) => !asset.fallthrough)
.map((asset) => joinURL(nitro.options.baseURL, asset.baseURL || "/"))
.map((baseURL) => ({
src: `^${escapeRegExp(withTrailingSlash(baseURL))}(.*)$`,
headers: {
"cache-control": "public,max-age=31536000,immutable",
},
continue: true,
})),
...publicAssetRoutes.map(({ src }) => ({
src,
headers: {
"cache-control": "public,max-age=31536000,immutable",
},
continue: true,
})),
{ handle: "filesystem" },
...publicAssetRoutes.map(({ src }) => ({
src,
status: 404,
headers: {
"cache-control": "no-store",
},
continue: false,
})),
],
});

Expand Down Expand Up @@ -315,6 +329,25 @@ function generateBuildConfig(nitro: Nitro, o11Routes?: ObservabilityRoute[]) {
return config;
}

/**
* Routes matching each public asset directory that Vercel serves only from the
* filesystem. Directories that fall through to the server and the root base
* are excluded.
*/
export function getPublicAssetRoutes(
publicAssets: PublicAssetDir[],
opts: { baseURL: string }
): { src: string }[] {
return publicAssets.flatMap((asset) => {
const assetBase = asset.baseURL || "/";
if (asset.fallthrough || assetBase === "/") {
return [];
}
const base = withTrailingSlash(joinURL(opts.baseURL, assetBase));
return [{ src: `^${escapeRegExp(base)}(.*)$` }];
});
}

/**
* Map prerendered files to the route and content type they should be served with.
*
Expand Down
33 changes: 33 additions & 0 deletions test/presets/vercel.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -213,6 +213,14 @@ describe("nitro:preset:vercel", async () => {
{
"handle": "filesystem",
},
{
"continue": false,
"headers": {
"cache-control": "no-store",
},
"src": "^/build/(.*)$",
"status": 404,
},
{
"dest": "/rules/_/noncached/cached-isr?__isr_route=$__isr_route",
"src": "^(?<__isr_route>/rules/_/noncached/cached/?)$",
Expand Down Expand Up @@ -535,6 +543,31 @@ describe("nitro:preset:vercel", async () => {
`);
});

it("should not cache missing immutable public assets", () => {
const filesystemIndex = ownBuildConfig.routes.findIndex(
(route: { handle?: string }) => route.handle === "filesystem"
);
const missingAssetRoute = (src: string) => ({
src,
status: 404,
headers: {
"cache-control": "no-store",
},
continue: false,
});

expect(
ownBuildConfig.routes.slice(filesystemIndex + 1, filesystemIndex + 3)
).toEqual(
expect.arrayContaining([
missingAssetRoute("^/build/(.*)$"),
missingAssetRoute(
`^/_vercel/immutable/${TEST_HASH_SALT}/nitro/(.*)$`
),
])
);
});

it("should apply immutable buildAssetsDir and write manifest", async () => {
// `vercel.immutableStaticFiles` relocates build assets under the
// reserved `_vercel/immutable` base (namespaced by the optional
Expand Down
60 changes: 60 additions & 0 deletions test/unit/vercel-public-asset-routes.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
import { describe, expect, it } from "vitest";
import type { PublicAssetDir } from "nitropack/types";
import { getPublicAssetRoutes } from "../../src/presets/vercel/utils";

const asset = (dir: Partial<PublicAssetDir>): PublicAssetDir =>
({ dir: "public", maxAge: 0, ...dir }) as PublicAssetDir;

describe("getPublicAssetRoutes", () => {
it("returns no routes without public assets", () => {
expect(getPublicAssetRoutes([], { baseURL: "/" })).toEqual([]);
});

it("skips assets that fall through to the server", () => {
expect(
getPublicAssetRoutes([asset({ baseURL: "/build", fallthrough: true })], {
baseURL: "/",
})
).toEqual([]);
});

it.each(["/", "/base/"])("skips the root base (baseURL: %s)", (baseURL) => {
expect(
getPublicAssetRoutes(
[
asset({ baseURL: "/", fallthrough: false }),
asset({ fallthrough: false }),
],
{ baseURL }
)
).toEqual([]);
});

it("matches the base as a path prefix", () => {
const routes = getPublicAssetRoutes(
[asset({ baseURL: "/build", fallthrough: false })],
{ baseURL: "/" }
);
expect(routes).toEqual([{ src: "^/build/(.*)$" }]);
const src = new RegExp(routes[0].src);
expect(src.test("/build/a.js")).toBe(true);
expect(src.test("/build")).toBe(false);
expect(src.test("/buildings")).toBe(false);
});

it("prefixes sources with the app base URL", () => {
expect(
getPublicAssetRoutes([asset({ baseURL: "/build", fallthrough: false })], {
baseURL: "/base/",
})
).toEqual([{ src: "^/base/build/(.*)$" }]);
});

it("escapes regular expression characters in the base", () => {
expect(
getPublicAssetRoutes([asset({ baseURL: "/a.b+c", fallthrough: false })], {
baseURL: "/",
})
).toEqual([{ src: String.raw`^/a\.b\+c/(.*)$` }]);
});
});
Loading