Skip to content

Commit

Permalink
feat: keep meta for public assets
Browse files Browse the repository at this point in the history
  • Loading branch information
pi0 committed Feb 8, 2023
1 parent 45e6dbe commit 5867851
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 9 deletions.
17 changes: 13 additions & 4 deletions src/rollup/plugins/public-assets.ts
Original file line number Diff line number Diff line change
Expand Up @@ -84,9 +84,11 @@ export function readAsset (id) {
},
// #internal/nitro/virtual/public-assets
"#internal/nitro/virtual/public-assets": () => {
const publicAssetBases = nitro.options.publicAssets
.filter((dir) => !dir.fallthrough && dir.baseURL !== "/")
.map((dir) => dir.baseURL);
const publicAssetBases = Object.fromEntries(
nitro.options.publicAssets
.filter((dir) => !dir.fallthrough && dir.baseURL !== "/")
.map((dir) => [dir.baseURL, { maxAge: dir.maxAge }])
);

return `
import assets from '#internal/nitro/virtual/public-assets-data'
Expand All @@ -104,12 +106,19 @@ export function isPublicAssetURL(id = '') {
if (assets[id]) {
return true
}
for (const base of publicAssetBases) {
for (const base in publicAssetBases) {
if (id.startsWith(base)) { return true }
}
return false
}
export function getPublicAssetMeta(id = '') {
for (const base in publicAssetBases) {
if (id.startsWith(base)) { return publicAssetBases[base] }
}
return {}
}
export function getAsset (id) {
return assets[id]
}
Expand Down
10 changes: 5 additions & 5 deletions src/runtime/entries/cloudflare.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import { withoutBase } from "ufo";
import { requestHasBody } from "../utils";
import { nitroApp } from "#internal/nitro/app";
import { useRuntimeConfig } from "#internal/nitro";
import { isPublicAssetURL } from "#internal/nitro/virtual/public-assets";
import { getPublicAssetMeta } from "#internal/nitro/virtual/public-assets";

addEventListener("fetch", (event: any) => {
event.respondWith(handleEvent(event));
Expand Down Expand Up @@ -50,11 +50,11 @@ async function handleEvent(event: FetchEvent) {

function assetsCacheControl(_request) {
const url = new URL(_request.url);

if (isPublicAssetURL(url.pathname)) {
const meta = getPublicAssetMeta(url.pathname);
if (meta.maxAge) {
return {
browserTTL: 31_536_000,
edgeTTL: 31_536_000,
browserTTL: meta.maxAge,
edgeTTL: meta.maxAge,
};
}
return {};
Expand Down
1 change: 1 addition & 0 deletions src/runtime/virtual/public-assets.d.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
export const publicAssetBases: string[];
export const isPublicAssetURL: (id: string) => boolean;
export const getPublicAssetMeta: (id: string) => { maxAge?: number };
export const readAsset: (id: string) => Promise<Buffer>;
export const getAsset: (id: string) => any;

0 comments on commit 5867851

Please sign in to comment.