MCPcopy
hub / github.com/freshframework/fresh / staticFiles

Function staticFiles

packages/fresh/src/middlewares/static_files.ts:22–133  ·  view source on GitHub ↗
()

Source from the content-addressed store, hash-verified

20 * ```
21 */
22export function staticFiles<T>(): Middleware<T> {
23 return async function freshServeStaticFiles(ctx) {
24 const { req, url, config } = ctx;
25
26 const buildCache = getBuildCache(ctx);
27 if (buildCache === null) return await ctx.next();
28
29 let pathname = url.pathname;
30 if (config.basePath) {
31 pathname = pathname !== config.basePath
32 ? pathname.slice(config.basePath.length)
33 : "/";
34 }
35
36 try {
37 pathname = normalizePathname(decodeURIComponent(pathname));
38 } catch (_e: unknown) {
39 if (!(_e instanceof URIError)) throw _e;
40 return await ctx.next();
41 }
42
43 // Fast path bail out
44 const startTime = performance.now() + performance.timeOrigin;
45 const file = await buildCache.readFile(pathname);
46 if (pathname === "/" || file === null) {
47 // Optimization: Prevent long responses for favicon.ico requests
48 if (pathname === "/favicon.ico") {
49 return new Response(null, { status: 404 });
50 }
51 return await ctx.next();
52 }
53
54 if (req.method !== "GET" && req.method !== "HEAD") {
55 file.close();
56 return new Response("Method Not Allowed", { status: 405 });
57 }
58
59 const span = tracer.startSpan("static file", {
60 attributes: { "fresh.span_type": "static_file" },
61 startTime,
62 });
63
64 try {
65 const cacheKey = url.searchParams.get(ASSET_CACHE_BUST_KEY);
66 if (cacheKey !== null && BUILD_ID !== cacheKey) {
67 url.searchParams.delete(ASSET_CACHE_BUST_KEY);
68 const location = url.pathname + url.search;
69 file.close();
70 span.setAttribute("fresh.cache", "invalid_bust_key");
71 span.setAttribute("fresh.cache_key", cacheKey);
72 return new Response(null, {
73 status: 307,
74 headers: {
75 location,
76 },
77 });
78 }
79

Callers 15

main.tsFile · 0.90
builder_test.tsFile · 0.90
testAppFunction · 0.90
testAppFunction · 0.90
testGroupAppFunction · 0.90
testAppFunction · 0.90
head_test.tsxFile · 0.90
main.tsFile · 0.90
main.tsFile · 0.85
main.tsFile · 0.85
main.tsFile · 0.85

Calls 5

normalizePathnameFunction · 0.85
readFileMethod · 0.65
closeMethod · 0.65
getMethod · 0.45
deleteMethod · 0.45

Tested by

no test coverage detected