diff --git a/docs/concepts/static-files.md b/docs/concepts/static-files.md index 86e8c7f4..43e0d4a2 100644 --- a/docs/concepts/static-files.md +++ b/docs/concepts/static-files.md @@ -1 +1,48 @@ -> TODO(lucacasonato): this page still needs to be written +> TODO(lucacasonato): this page still needs to be completed + +Fresh automatically serves static assets placed in a `static/` directory in the +project root. These assets are served at the root of the webserver, with a +higher priority than routes. This means that if a given request matches a file +in the `static/` folder, it is always served, even if there is a route that +would also match the request. + +Static asset responses automatically get a `content-type` header assigned based +on the file extension of the file on disk. Assets are also automatically +streamed from disk to the client to improve performance and efficiency for both +user and server. + +Fresh also adds an `etag` header to assets automatically, and handles the +`If-None-Match` header for incoming requests. + +### Caching + +By default, no caching headers are added to assets. This can be disadvantageous +in many scenarios, so fresh makes it easy to serve assets with long cache +lifetimes too. + +The first approach to do this is manual. The client runtime exports an `asset` +function that takes an absolute path to the static asset, and returns a "locked" +version of this path that contains a build ID for cache busting. When the asset +is requested at this "locked" path, it will be served with a cache lifetime of +one year. + +```jsx +import { asset, h } from "../deps.ts"; + +export default function Page() { + return ( +

+ View brochure +

+ ); +} +``` + +Fresh also does this automatically for `src` and `srcset` attributes in `` +and `` HTML tags. These will automatically use "locked" paths if fresh +deems it safe to do so. You can always opt out of this behaviour per tag, by +adding the `data-fresh-disable-lock` attribute. + +```jsx +; +``` diff --git a/src/runtime/main.ts b/src/runtime/main.ts index b77def6d..7d46a618 100644 --- a/src/runtime/main.ts +++ b/src/runtime/main.ts @@ -1,4 +1,5 @@ -import { ComponentType, h, render } from "./deps.ts"; +import { ComponentType, h, options, render } from "./deps.ts"; +import { assetHashingHook } from "./utils.ts"; function createRootFragment( parent: Element, @@ -61,3 +62,9 @@ export function revive(islands: Record) { } walk(document.body); } + +const originalHook = options.vnode; +options.vnode = (vnode) => { + assetHashingHook(vnode); + if (originalHook) originalHook(vnode); +}; diff --git a/src/runtime/utils.ts b/src/runtime/utils.ts index d8c5ea49..6373e6e6 100644 --- a/src/runtime/utils.ts +++ b/src/runtime/utils.ts @@ -1,3 +1,5 @@ +import { VNode } from "./deps.ts"; + export const INTERNAL_PREFIX = "/_frsh"; export const ASSET_CACHE_BUST_KEY = "__frsh_c"; @@ -28,3 +30,41 @@ export function asset(path: string) { return path; } } + +/** Apply the `asset` function to urls in a `srcset` attribute. */ +export function assetSrcSet(srcset: string): string { + if (srcset.includes("(")) return srcset; // Bail if the srcset contains complicated syntax. + const parts = srcset.split(","); + const constructed = []; + for (const part of parts) { + const trimmed = part.trimStart(); + const leadingWhitespace = part.length - trimmed.length; + if (trimmed === "") return srcset; // Bail if the srcset is malformed. + let urlEnd = trimmed.indexOf(" "); + if (urlEnd === -1) urlEnd = trimmed.length; + const leading = part.substring(0, leadingWhitespace); + const url = trimmed.substring(0, urlEnd); + const trailing = trimmed.substring(urlEnd); + constructed.push(leading + asset(url) + trailing); + } + return constructed.join(","); +} + +export function assetHashingHook( + vnode: VNode<{ + src?: string; + srcset?: string; + ["data-fresh-disable-lock"]?: boolean; + }>, +) { + if (vnode.type === "img" || vnode.type === "source") { + const { props } = vnode; + if (props["data-fresh-disable-lock"]) return; + if (typeof props.src === "string") { + props.src = asset(props.src); + } + if (typeof props.srcset === "string") { + props.srcset = assetSrcSet(props.srcset); + } + } +} diff --git a/src/runtime/utils_test.ts b/src/runtime/utils_test.ts index fc11bb90..c1e8cb4f 100644 --- a/src/runtime/utils_test.ts +++ b/src/runtime/utils_test.ts @@ -1,5 +1,5 @@ import { assertEquals } from "../../tests/deps.ts"; -import { asset } from "./utils.ts"; +import { asset, assetSrcSet } from "./utils.ts"; globalThis.__FRSH_BUILD_ID = "ID123"; @@ -17,3 +17,44 @@ Deno.test("asset", () => { "https://example.com/logo.png", ); }); + +Deno.test("assetSrcSet", () => { + assertEquals(assetSrcSet("/img.png"), "/img.png?__frsh_c=ID123"); + assertEquals( + assetSrcSet("/img.png, /img.png 2x"), + "/img.png?__frsh_c=ID123, /img.png?__frsh_c=ID123 2x", + ); + assertEquals(assetSrcSet("/img.png 1x"), "/img.png?__frsh_c=ID123 1x"); + assertEquals( + assetSrcSet("/img.png 1x, /img.png 2x"), + "/img.png?__frsh_c=ID123 1x, /img.png?__frsh_c=ID123 2x", + ); + assertEquals( + assetSrcSet("/img.png 1.5x, /img.png 3x"), + "/img.png?__frsh_c=ID123 1.5x, /img.png?__frsh_c=ID123 3x", + ); + + //test with queries + assertEquals( + assetSrcSet("/img.png?w=140, /img.png?w=200 2x"), + "/img.png?w=140&__frsh_c=ID123, /img.png?w=200&__frsh_c=ID123 2x", + ); + + // test with extra spaces + assertEquals( + assetSrcSet("/img-s.png 300w, /img-l.png 600w , /img-xl.png 900w"), + "/img-s.png?__frsh_c=ID123 300w, /img-l.png?__frsh_c=ID123 600w , /img-xl.png?__frsh_c=ID123 900w", + ); + + // test with ( syntax + assertEquals( + assetSrcSet("/img.png ( 140,0w)"), + "/img.png ( 140,0w)", + ); + + // test with invalid parts + assertEquals( + assetSrcSet("/img.png,, /img-s.png 300w"), + "/img.png,, /img-s.png 300w", + ); +}); diff --git a/src/server/render.tsx b/src/server/render.tsx index 9bce290d..196b24ab 100644 --- a/src/server/render.tsx +++ b/src/server/render.tsx @@ -18,6 +18,7 @@ import { HEAD_CONTEXT } from "../runtime/head.ts"; import { CSP_CONTEXT, nonce, NONE, UNSAFE_INLINE } from "../runtime/csp.ts"; import { ContentSecurityPolicy } from "../runtime/csp.ts"; import { bundleAssetUrl } from "./constants.ts"; +import { assetHashingHook } from "../runtime/utils.ts"; export interface RenderOptions { page: Page | UnknownPage | ErrorPage; @@ -296,6 +297,7 @@ let ISLAND_PROPS: unknown[] = []; const originalHook = options.vnode; let ignoreNext = false; options.vnode = (vnode) => { + assetHashingHook(vnode); const originalType = vnode.type as ComponentType; if (typeof vnode.type === "function") { const island = ISLANDS.find((island) => island.component === originalType); diff --git a/tests/fixture/fresh.gen.ts b/tests/fixture/fresh.gen.ts index ff718cc3..ce1372d8 100644 --- a/tests/fixture/fresh.gen.ts +++ b/tests/fixture/fresh.gen.ts @@ -9,23 +9,24 @@ import * as $3 from "./routes/_app.tsx"; import * as $4 from "./routes/_middleware.ts"; import * as $5 from "./routes/_render.ts"; import * as $6 from "./routes/api/get_only.ts"; -import * as $7 from "./routes/books/[id].tsx"; -import * as $8 from "./routes/connInfo.ts"; -import * as $9 from "./routes/failure.ts"; -import * as $10 from "./routes/index.tsx"; -import * as $11 from "./routes/intercept.tsx"; -import * as $12 from "./routes/intercept_args.tsx"; -import * as $13 from "./routes/layeredMdw/_middleware.ts"; -import * as $14 from "./routes/layeredMdw/layer2-no-mw/without_mw.ts"; -import * as $15 from "./routes/layeredMdw/layer2/_middleware.ts"; -import * as $16 from "./routes/layeredMdw/layer2/abc.ts"; -import * as $17 from "./routes/layeredMdw/layer2/layer3/[id].ts"; -import * as $18 from "./routes/layeredMdw/layer2/layer3/_middleware.ts"; -import * as $19 from "./routes/middleware_root.ts"; -import * as $20 from "./routes/params.tsx"; -import * as $21 from "./routes/props/[id].tsx"; -import * as $22 from "./routes/static.tsx"; -import * as $23 from "./routes/wildcard.tsx"; +import * as $7 from "./routes/assetsCaching/index.tsx"; +import * as $8 from "./routes/books/[id].tsx"; +import * as $9 from "./routes/connInfo.ts"; +import * as $10 from "./routes/failure.ts"; +import * as $11 from "./routes/index.tsx"; +import * as $12 from "./routes/intercept.tsx"; +import * as $13 from "./routes/intercept_args.tsx"; +import * as $14 from "./routes/layeredMdw/_middleware.ts"; +import * as $15 from "./routes/layeredMdw/layer2-no-mw/without_mw.ts"; +import * as $16 from "./routes/layeredMdw/layer2/_middleware.ts"; +import * as $17 from "./routes/layeredMdw/layer2/abc.ts"; +import * as $18 from "./routes/layeredMdw/layer2/layer3/[id].ts"; +import * as $19 from "./routes/layeredMdw/layer2/layer3/_middleware.ts"; +import * as $20 from "./routes/middleware_root.ts"; +import * as $21 from "./routes/params.tsx"; +import * as $22 from "./routes/props/[id].tsx"; +import * as $23 from "./routes/static.tsx"; +import * as $24 from "./routes/wildcard.tsx"; import * as $$0 from "./islands/Test.tsx"; const manifest = { @@ -37,23 +38,24 @@ const manifest = { "./routes/_middleware.ts": $4, "./routes/_render.ts": $5, "./routes/api/get_only.ts": $6, - "./routes/books/[id].tsx": $7, - "./routes/connInfo.ts": $8, - "./routes/failure.ts": $9, - "./routes/index.tsx": $10, - "./routes/intercept.tsx": $11, - "./routes/intercept_args.tsx": $12, - "./routes/layeredMdw/_middleware.ts": $13, - "./routes/layeredMdw/layer2-no-mw/without_mw.ts": $14, - "./routes/layeredMdw/layer2/_middleware.ts": $15, - "./routes/layeredMdw/layer2/abc.ts": $16, - "./routes/layeredMdw/layer2/layer3/[id].ts": $17, - "./routes/layeredMdw/layer2/layer3/_middleware.ts": $18, - "./routes/middleware_root.ts": $19, - "./routes/params.tsx": $20, - "./routes/props/[id].tsx": $21, - "./routes/static.tsx": $22, - "./routes/wildcard.tsx": $23, + "./routes/assetsCaching/index.tsx": $7, + "./routes/books/[id].tsx": $8, + "./routes/connInfo.ts": $9, + "./routes/failure.ts": $10, + "./routes/index.tsx": $11, + "./routes/intercept.tsx": $12, + "./routes/intercept_args.tsx": $13, + "./routes/layeredMdw/_middleware.ts": $14, + "./routes/layeredMdw/layer2-no-mw/without_mw.ts": $15, + "./routes/layeredMdw/layer2/_middleware.ts": $16, + "./routes/layeredMdw/layer2/abc.ts": $17, + "./routes/layeredMdw/layer2/layer3/[id].ts": $18, + "./routes/layeredMdw/layer2/layer3/_middleware.ts": $19, + "./routes/middleware_root.ts": $20, + "./routes/params.tsx": $21, + "./routes/props/[id].tsx": $22, + "./routes/static.tsx": $23, + "./routes/wildcard.tsx": $24, }, islands: { "./islands/Test.tsx": $$0, diff --git a/tests/fixture/islands/Test.tsx b/tests/fixture/islands/Test.tsx index 9baedbe4..5af0a1a1 100644 --- a/tests/fixture/islands/Test.tsx +++ b/tests/fixture/islands/Test.tsx @@ -1,12 +1,17 @@ /** @jsx h */ -import { asset, h } from "../client_deps.ts"; +import { h } from "../client_deps.ts"; export default function Test(props: { message: string }) { return (

{props.message}

- +
); } diff --git a/tests/fixture/routes/assetsCaching/index.tsx b/tests/fixture/routes/assetsCaching/index.tsx new file mode 100644 index 00000000..0dc6c72b --- /dev/null +++ b/tests/fixture/routes/assetsCaching/index.tsx @@ -0,0 +1,30 @@ +/** @jsx h */ + +import { asset, h } from "../../client_deps.ts"; +import Test from "../../islands/Test.tsx"; + +export default function Home() { + return ( +
+
img-with-hashing
+ + +
img-without-hashing
+ + + + +
img-external
+ +
+ ); +} diff --git a/tests/main_test.ts b/tests/main_test.ts index 8ed781ce..a807a26e 100644 --- a/tests/main_test.ts +++ b/tests/main_test.ts @@ -219,9 +219,11 @@ Deno.test("static file - by file path", async () => { Deno.test("static file - by 'hashed' path", async () => { // Check that the file path have the BUILD_ID - const resp = await router(new Request("https://fresh.deno.dev/")); + const resp = await router( + new Request("https://fresh.deno.dev/assetsCaching"), + ); const body = await resp.text(); - const imgFilePath = body.match(/img src="(.*?)"/)?.[1]; + const imgFilePath = body.match(/img id="img-with-hashing" src="(.*?)"/)?.[1]; assert(imgFilePath); assert(imgFilePath.includes(`?__frsh_c=${globalThis.__FRSH_BUILD_ID}`)); @@ -244,6 +246,38 @@ Deno.test("static file - by 'hashed' path", async () => { }), ); assertEquals(resp3.status, 304); + + // ensure asset hook is not applied on file explicitly excluded with attribute + const imgFilePathWithNoCache = body.match( + /img id="img-without-hashing" src="(.*?)"/, + )?.[1]; + assert(imgFilePathWithNoCache); + assert( + !imgFilePathWithNoCache.includes(globalThis.__FRSH_BUILD_ID), + "img-without-hashing", + ); + + // ensure asset hook is applied on img within an island + const imgInIsland = body.match(/img id="img-in-island" src="(.*?)"/)?.[1]; + assert(imgInIsland); + assert(imgInIsland.includes(globalThis.__FRSH_BUILD_ID), "img-in-island"); + + // verify that the asset hook is applied to the srcset + const imgInIslandSrcSet = body.match(/srcset="(.*?)"/)?.[1]; + assert(imgInIslandSrcSet); + console.log(imgInIslandSrcSet); + assert( + imgInIslandSrcSet.includes(globalThis.__FRSH_BUILD_ID), + "img-in-island-srcset", + ); + + // verify that the asset hook is not applied to img outside reference out of the static folder + const imgMissing = body.match(/img id="img-missing" src="(.*?)"/)?.[1]; + assert(imgMissing); + assert( + !imgMissing.includes(globalThis.__FRSH_BUILD_ID), + "Applying hash on unknown asset", + ); }); Deno.test("/params/:path*", async () => { diff --git a/www/routes/docs/[...slug].tsx b/www/routes/docs/[...slug].tsx index 35bc2b7c..d0912816 100644 --- a/www/routes/docs/[...slug].tsx +++ b/www/routes/docs/[...slug].tsx @@ -83,7 +83,7 @@ function Logo() { return ( Fresh logo