diff --git a/docs/canary/concepts/ahead-of-time-builds.md b/docs/canary/concepts/ahead-of-time-builds.md new file mode 100644 index 00000000..233498b6 --- /dev/null +++ b/docs/canary/concepts/ahead-of-time-builds.md @@ -0,0 +1,142 @@ +--- +description: | + Fresh optimize assets ahead of time, which makes pages load way quicker. +--- + +Fresh enables you to pre-optimize frontend assets before the code is deployed. +During that process the code for Islands will be compressed and optimized, so +that Fresh can send as little code as possible to the browser. Depending on the +amount of code an island needs, this process can take several seconds if done on +the fly serverside. + +Doing those optimizations ahead-of-time and deploying the already optimized +assets alongside with your code, allows Fresh to treat them as like any other +static file and can serve it immediately without any further processing. On +pages with islands, having to do no processing greatly speeds up page load +times. + +Plugins can build static assets during ahead-of-time builds. This can be used to +preprocess or generate CSS files, for example. + +## Creating an optimized build + +To have Fresh optimize all the assets, run one of the following commands: + +```sh +# As a task in newer Fresh projects +deno task build +# or invoke it manually +deno run -A dev.ts build +``` + +This will create a `_fresh` folder in the project directory. That folder +contains the optimized assets and a `snapshot.json` file which includes some +metadata for Fresh. + +Any other static files generated by plugins will be stored in the +`_fresh/static` subfolder. They will be served the same as other +[static files](/docs/concepts/static-files.md). + +> [info]: The `_fresh` folder should not be committed to the repository. Add an +> entry in the `.gitignore` file to ensure that it is not committed. Create that +> file at the root of your git repository if not present. +> +> ```gitignore .gitignore +> # Ignore fresh build directory +> _fresh/ +> ``` + +## Running Fresh with optimized assets + +When Fresh is started in non-development mode (usually via `main.ts`), Fresh +will automatically pick up optimized assets when a `_fresh` folder exists. If +found, Fresh will print the following message to the terminal: + +```sh Terminal output +Using snapshot found at /path/to/project/_fresh +``` + +## Deploying an optimized Fresh project + +To generate optimized assets whenever you push changes to the `main` branch of +your project, copy the following GitHub action and add it under +`.github/workflows/deploy.yml` in your project. + +```yml .github/workflows/deploy.yml +name: Deploy +on: + push: + branches: [main] + pull_request: + branches: main + +jobs: + deploy: + name: Deploy + runs-on: ubuntu-latest + + permissions: + id-token: write # Needed for auth with Deno Deploy + contents: read # Needed to clone the repository + + steps: + - name: Clone repository + uses: actions/checkout@v3 + + - name: Install Deno + uses: denoland/setup-deno@v1 + with: + deno-version: v1.x + + - name: Build step + run: "deno task build" # đ Update the build command(s) if necessary + + - name: Upload to Deno Deploy + uses: denoland/deployctl@v1 + with: + project: "example-project" # đ Update the deploy project name if necessary + entrypoint: "./main.ts" # đ Update the entrypoint if necessary +``` + +> âšī¸ **Important:** The project name here must match the project name you've +> picked in Deno Deploy. + +On the Deno Deploy side change the GitHub integration mode to GitHub Actions. +You need to unlink first, if you have an existing project that's linked with the +"Automatic" mode. + + + +Once this is set up you're ready for your next deployment. Whenever a new PR is +merged into the `main` branch on GitHub the deploy action will be executed and +deploy the optimized assets to Deno Deploy. + +## Migrating existing projects with Plugins + +If you're using Fresh plugins, extract them into a `fresh.config.ts` file, so +that both the `dev.ts` and `main.ts` script have access to them. + +```ts fresh.config.ts +import { defineConfig } from "$fresh/server.ts"; +import twindPlugin from "$fresh/plugins/twind.ts"; +import twindConfig from "./twind.config.ts"; + +export default defineConfig({ + plugins: [twindPlugin(twindConfig)], +}); +``` + +```ts main.ts +import { start } from "$fresh/server.ts"; +import manifest from "./fresh.gen.ts"; +import config from "./fresh.config.ts"; + +await start(manifest, config); +``` + +```ts dev.ts +import dev from "$fresh/dev.ts"; +import config from "./fresh.config.ts"; + +await dev(import.meta.url, "./main.ts", config); +``` diff --git a/docs/canary/concepts/plugins.md b/docs/canary/concepts/plugins.md new file mode 100644 index 00000000..4d6ddce0 --- /dev/null +++ b/docs/canary/concepts/plugins.md @@ -0,0 +1,160 @@ +--- +description: Plugins can add new functionality to Fresh without requiring significant complexity. +--- + +Plugins can dynamically add new functionality to Fresh without exposing +significant complexity to the user. Users can add plugins by importing and +initializing them in their `main.ts` file: + +```ts main.ts +import { start } from "$fresh/server.ts"; +import manifest from "./fresh.gen.ts"; + +import twindPlugin from "$fresh/plugins/twind.ts"; +import twindConfig from "./twind.config.js"; + +await start(manifest, { + plugins: [ + // This line configures Fresh to use the first-party twind plugin. + twindPlugin(twindConfig), + ], +}); +``` + +Currently, the only available first-party plugin is the Twind plugin. +Third-party plugins are also supported - they can be imported from any HTTP +server, like any other Deno module. + +Plugin hooks are executed in the order that the plugins are defined in the +`plugins` array. This means that the first plugin in the array will be executed +first, and the last plugin in the array will be executed last. For many plugins, +this does not matter, but for some plugins it may. + +## Creating a plugin + +Fresh plugins are in essence a collection of hooks that allow the plugin to hook +into various systems inside of Fresh. Currently only a `render` hook is +available (explained below). + +A Fresh plugin is just a JavaScript object that conforms to the +[Plugin](https://deno.land/x/fresh/server.ts?s=Plugin) interface. The only +required property of a plugin is its name. Names must only contain the +characters `a`-`z`, and `_`. + +```ts +import { Plugin } from "$fresh/server.ts"; + +const plugin: Plugin = { + name: "my_plugin", +}; +``` + +A plugin containing only a name is technically valid, but not very useful. To be +able to do anything with a plugin, it must register some hooks, middlewares, or +routes. + +### Hook: `render` + +The render hook allows plugins to: + +- Control timing of the synchronous render of a page. +- Inject additional CSS and JS into the rendered page. + +This is commonly used to set thread local variables for the duration of the +render (for example preact global context, preact option hooks, or for style +libraries like Twind). After render is complete, the plugin can inject inline +CSS and JS modules (with attached state) into the page. + +The render hook is called with the +[`PluginRenderContext`](https://deno.land/x/fresh/server.ts?s=PluginRenderContext) +object, which contains a `render()` method. This method must be invoked during +the render hook to actually render the page. It is a terminal error to not call +the `render()` method during the render hook. + +The `render()` method returns a +[`PluginRenderFunctionResult`](https://deno.land/x/fresh/server.ts?s=PluginRenderFunctionResult) +object which contains the HTML text of the rendered page, as well as a boolean +indicating whether the page contains any islands that will be hydrated on the +client. + +The `render` hook needs to synchronously return a +[`PluginRenderResult`](https://deno.land/x/fresh/server.ts?s=PluginRenderResult) +object. Additional CSS and JS modules can be added to be injected into the page +by adding them to `styles` and `scripts` arrays in this object. + +`styles` are injected into the `
` of the page as inline CSS. Each entry +can define the CSS text to inject, as well as an optional `id` for the style +tag, and an optional `media` attribute for the style tag. + +`scripts` define JavaScript/TypeScript modules to be injected into the page. The +possibly loaded modules need to be defined up front in the `Plugin#entrypoints` +property. Each defined module must be a JavaScript/TypeScript module that has a +default export of a function that takes one (arbitrary) argument, and returns +nothing (or a promise resolving to nothing). Fresh will call this function with +the state defined in the `scripts` entry. The state can be any arbitrary JSON +serializable JavaScript value. + +For an example of a plugin that uses the `render` hook, see the first-party +[Twind plugin](https://github.com/denoland/fresh/blob/main/plugins/twind.ts). + +### Hook: `renderAsync` + +This hook is largely the same as the `render` hook, with a couple of key +differences to make asynchronous style and script generation possible. It must +asynchronously return its +[`PluginRenderResult`](https://deno.land/x/fresh/server.ts?s=PluginRenderResult), +either from an `async/await` function or wrapped within a promise. + +The render hook is called with the +[`PluginAsyncRenderContext`](https://deno.land/x/fresh/server.ts?s=PluginAsyncRenderContext) +object, which contains a `renderAsync()` method. This method must be invoked +during the render hook to actually render the page. It is a terminal error to +not call the `renderAsync()` method during the render hook. + +This is useful for when plugins are generating styles and scripts with +asynchronous dependencies based on the `htmlText`. Unlike the synchronous render +hook, async render hooks for multiple pages can be running at the same time. +This means that unlike the synchronous render hook, you can not use global +variables to propagate state between the render hook and the renderer. + +The `renderAsync` hooks start before any page rendering occurs, and finish after +all rendering is complete -- they wrap around the underlying JSX->string +rendering, plugin `render` hooks, and the +[`RenderFunction`](https://deno.land/x/fresh/server.ts?s=RenderFunction) that +may be provided to Fresh's `start` entrypoint in the `main.ts` file. + +### Hook: `buildStart` + +This hook is run at the start of the Fresh +[ahead-of-time build task](/docs/concepts/ahead-of-time-builds). It may be +synchronous or asynchronous. + +The build start hook is called with the +[`ResolvedFreshConfig`](https://deno.land/x/fresh/src/server/types.ts?s=ResolvedFreshConfig) +object, which contains the full Fresh configuration. + +This hook may be used to generate precompiled static assets. Any files saved to +the `static` subfolder of `config.build.outDir` (typically `_fresh`) will be +served the same as other [static files](/docs/concepts/static-files). + +### Hook: `buildEnd` + +This hook is run at the end of the Fresh +[ahead-of-time build task](/docs/concepts/ahead-of-time-builds). It may be +synchronous or asynchronous. + +### Routes and Middlewares + +You can create routes and middlewares that get loaded and rendered like the +normal [routes](/docs/concepts/routes) and +[middlewares](/docs/concepts/middleware). + +The plugin routes and middlewares need a defined path in the format of a file +name without a filetype inside the routes directory(E.g. `blog/index`, +`blog/[slug]`). + +For more examples see the [Concepts: Routing](/docs/concepts/routing) page. + +To create a middleware you need to create a `MiddlewareHandler` function. + +And to create a route you can create both a Handler and/or component. diff --git a/docs/toc.ts b/docs/toc.ts index 13f1470e..57a5d0a6 100644 --- a/docs/toc.ts +++ b/docs/toc.ts @@ -57,9 +57,9 @@ const toc: RawTableOfContents = { ["error-pages", "Error pages", "link:canary"], ["partials", "Partials", "link:latest"], ["data-fetching", "Data fetching", "link:latest"], - ["ahead-of-time-builds", "Ahead-of-time Builds", "link:latest"], + ["ahead-of-time-builds", "Ahead-of-time Builds", "link:canary"], ["deployment", "Deployment", "link:latest"], - ["plugins", "Plugins", "link:latest"], + ["plugins", "Plugins", "link:canary"], ["updating", "Updating Fresh", "link:latest"], ["server-configuration", "Server configuration", "link:latest"], ], diff --git a/src/dev/build.ts b/src/dev/build.ts index 55b13726..264e79da 100644 --- a/src/dev/build.ts +++ b/src/dev/build.ts @@ -14,6 +14,9 @@ export async function build( // Ensure that build dir is empty await emptyDir(outDir); + // Create a directory for static assets produced during the build + await Deno.mkdir(join(outDir, "static")); + await Promise.all(plugins.map((plugin) => plugin.buildStart?.(state.config))); // Bundle assets diff --git a/src/server/fs_extract.ts b/src/server/fs_extract.ts index 3003c82a..636f60e3 100644 --- a/src/server/fs_extract.ts +++ b/src/server/fs_extract.ts @@ -19,7 +19,7 @@ import { } from "./types.ts"; import * as router from "./router.ts"; import DefaultErrorHandler from "./default_error_page.tsx"; -import { extname, toFileUrl, typeByExtension, walk } from "./deps.ts"; +import { extname, join, toFileUrl, typeByExtension, walk } from "./deps.ts"; import { BUILD_ID } from "./build_id.ts"; import { toBaseRoute } from "./compose.ts"; @@ -262,35 +262,38 @@ export async function extractRoutes( const staticFiles: StaticFile[] = []; try { - const staticDirUrl = toFileUrl(config.staticDir); - const entries = walk(config.staticDir, { - includeFiles: true, - includeDirs: false, - followSymlinks: false, - }); - const encoder = new TextEncoder(); - for await (const entry of entries) { - const localUrl = toFileUrl(entry.path); - const path = localUrl.href.substring(staticDirUrl.href.length); - const stat = await Deno.stat(localUrl); - const contentType = typeByExtension(extname(path)) ?? - "application/octet-stream"; - const etag = await crypto.subtle.digest( - "SHA-1", - encoder.encode(BUILD_ID + path), - ).then((hash) => - Array.from(new Uint8Array(hash)) - .map((byte) => byte.toString(16).padStart(2, "0")) - .join("") - ); - const staticFile: StaticFile = { - localUrl, - path, - size: stat.size, - contentType, - etag, - }; - staticFiles.push(staticFile); + const outDirStatic = join(config.build.outDir, "static"); + for (const staticDir of [config.staticDir, outDirStatic]) { + const staticDirUrl = toFileUrl(staticDir); + const entries = walk(staticDir, { + includeFiles: true, + includeDirs: false, + followSymlinks: false, + }); + const encoder = new TextEncoder(); + for await (const entry of entries) { + const localUrl = toFileUrl(entry.path); + const path = localUrl.href.substring(staticDirUrl.href.length); + const stat = await Deno.stat(localUrl); + const contentType = typeByExtension(extname(path)) ?? + "application/octet-stream"; + const etag = await crypto.subtle.digest( + "SHA-1", + encoder.encode(BUILD_ID + path), + ).then((hash) => + Array.from(new Uint8Array(hash)) + .map((byte) => byte.toString(16).padStart(2, "0")) + .join("") + ); + const staticFile: StaticFile = { + localUrl, + path, + size: stat.size, + contentType, + etag, + }; + staticFiles.push(staticFile); + } } } catch (err) { if (err.cause instanceof Deno.errors.NotFound) { diff --git a/tests/build_test.ts b/tests/build_test.ts index c283e842..c657d403 100644 --- a/tests/build_test.ts +++ b/tests/build_test.ts @@ -1,14 +1,17 @@ import * as path from "$std/path/mod.ts"; import { assert, + assertEquals, assertNotMatch, assertStringIncludes, puppeteer, } from "./deps.ts"; import { getStdOutput, + recreateFolder, startFreshServer, waitForText, + withFakeServe, } from "$fresh/tests/test_utils.ts"; import { BuildSnapshotJson } from "$fresh/src/build/mod.ts"; @@ -258,3 +261,47 @@ Deno.test("pass target options", async () => { `Asset contained ?? despite target es2015\n\n${stdout}\n${stderr}`, ); }); + +Deno.test("serve static files from build dir", async () => { + const filePath = path.join( + path.dirname(path.fromFileUrl(import.meta.url)), + "fixture_build_static", + "_fresh", + "static", + "foo.txt", + ); + + await recreateFolder(path.dirname(filePath)); + await Deno.writeTextFile(filePath, `it works`); + + await withFakeServe( + "./tests/fixture_build_static/main.ts", + async (server) => { + const res = await server.get("/foo.txt"); + const text = await res.text(); + assertEquals(text, "it works"); + }, + ); +}); + +Deno.test("prefer static files from build dir", async () => { + const filePath = path.join( + path.dirname(path.fromFileUrl(import.meta.url)), + "fixture_build_static", + "_fresh", + "static", + "duplicate.txt", + ); + + await recreateFolder(path.dirname(filePath)); + await Deno.writeTextFile(filePath, "it works"); + + await withFakeServe( + "./tests/fixture_build_static/main.ts", + async (server) => { + const res = await server.get("/duplicate.txt"); + const text = await res.text(); + assertEquals(text, "it works"); + }, + ); +}); diff --git a/tests/fixture_build_static/deno.json b/tests/fixture_build_static/deno.json new file mode 100644 index 00000000..fe6caa19 --- /dev/null +++ b/tests/fixture_build_static/deno.json @@ -0,0 +1,14 @@ +{ + "lock": false, + "imports": { + "$fresh/": "../../", + "preact": "https://esm.sh/preact@10.15.1", + "preact/": "https://esm.sh/preact@10.15.1/", + "@preact/signals": "https://esm.sh/*@preact/signals@1.1.3", + "@preact/signals-core": "https://esm.sh/@preact/signals-core@1.2.3" + }, + "compilerOptions": { + "jsx": "react-jsx", + "jsxImportSource": "preact" + } +} diff --git a/tests/fixture_build_static/dev.ts b/tests/fixture_build_static/dev.ts new file mode 100755 index 00000000..2d85d6c1 --- /dev/null +++ b/tests/fixture_build_static/dev.ts @@ -0,0 +1,5 @@ +#!/usr/bin/env -S deno run -A --watch=static/,routes/ + +import dev from "$fresh/dev.ts"; + +await dev(import.meta.url, "./main.ts"); diff --git a/tests/fixture_build_static/fresh.gen.ts b/tests/fixture_build_static/fresh.gen.ts new file mode 100644 index 00000000..b321c0e0 --- /dev/null +++ b/tests/fixture_build_static/fresh.gen.ts @@ -0,0 +1,15 @@ +// DO NOT EDIT. This file is generated by Fresh. +// This file SHOULD be checked into source version control. +// This file is automatically updated during development when running `dev.ts`. + +import * as $0 from "./routes/index.tsx"; + +const manifest = { + routes: { + "./routes/index.tsx": $0, + }, + islands: {}, + baseUrl: import.meta.url, +}; + +export default manifest; diff --git a/tests/fixture_build_static/main.ts b/tests/fixture_build_static/main.ts new file mode 100644 index 00000000..dedce9cb --- /dev/null +++ b/tests/fixture_build_static/main.ts @@ -0,0 +1,10 @@ +///