Commit Graph
578 Commits
Author SHA1 Message Date
Marvin Hagemeister 85c17fac72 fix: nested index route not working in prod builds (#3132)
This was due to a mismatch in the disk snapshot compared to in memory.
2025-07-24 21:27:16 +02:00
Marvin Hagemeister 41b11de470 docs: update fs route (#3125) 2025-07-24 15:34:51 +02:00
Marvin Hagemeister 118242eaa6 major: build islands + scan routeDir without importing user code (#3122)
This fixes a bunch of long standing issues in our tracker where a build
wouldn't finish because of importing user code. It's common for backend
apps to spawn some open ended tasks like subscribing to Deno KV or other
things. This addresses another problem of having to set up ENV vars just
for the build, even though they are technically not required to build
islands.

This also gives a roughly ~30% performance boost on cold starts (at
least on `deno.com`). Unfortunately, this does require some breaking
changes. But I believe the performance improvements + removing the
footgun of loading user code during build is well worth it. This work is
also a precursor in case we want to exploring moving to vite at some
point in the future.

## Breaking changes

1. Build options have moved to the builder.
```diff
  // main.ts
- const app = new App({ build: { outDir: "dist/" } })
+ const app = new App()

  // dev.ts
- const builder = new Builder();
+ const builder = new Builder({ outDir: "dist/" });
```

2. Another breaking change is how file based routes are loaded. Since
they're prepared and loaded by the builder the API changed.

```diff
  // main.ts
  const app = new App()
    .use(staticFiles())
  
- await fsRoutes(app, {
-   loadIsland: (path) => import(`./islands/${path}`),
-   loadRoute: (path) => import(`./routes/${path}`),
- }); 
+ app.fsRoutes()
```
You can optionally change the `islandDir` or `routeDir` by passing that
to the `Builder`:

```ts
// dev.ts
const builder = new Builder({
  islandDir: "/path/to/islands", 
  routeDir: "/path/to/routes"
});
```

3. Import `app` lazily in `dev.ts`. Passing `app` to `builder.build()`
is not necessary anymore.

```diff
- import { app } from "./main.ts";

  const builder = new Builder({ target: "safari12" });
  
  if (Deno.args.includes("build")) {
-    await builder.build(app);
+    await builder.build();
  } else {
-   await builder.listen(app);
+   await builder.listen(() => import("./main.ts"));
  }
```

4. The production run command has changed. It's now using `deno serve`
```diff
  // deno.json
  {
    "tasks": {
      "dev": "deno run -A --watch=static/,routes/ dev.ts",
      "dev": "deno run -A dev.ts build",
-     "start": "deno run -A main.ts",
+     "start": "deno serve -A _fresh/server.js",
    }
  }
```
Remove this bit in `main.ts`:

```diff
  // main.ts
  
- if (import.meta.main) {
-   await app.listen()
- }
```

Fixes https://github.com/denoland/fresh/issues/2240
Fixes https://github.com/denoland/fresh/issues/2640
Fixes https://github.com/denoland/fresh/issues/2592
Fixes https://github.com/denoland/fresh/issues/1843
2025-07-24 15:04:05 +02:00
Marvin Hagemeister cd7c3479a4 fix: basePath not applied to app.route() (#3116)
Fixes https://github.com/denoland/fresh/issues/3115
2025-07-19 12:29:45 +02:00
Marvin Hagemeister 39737b4530 fix: write matched pattern into ctx.route (#3113)
Fixes https://github.com/denoland/fresh/issues/3112
2025-07-18 22:38:56 +02:00
Asher GomezandMarvin Hagemeister 83da608504 BREAKING(core): remove FreshBuilder interface (#2935)
Once can just use `Builder` for typing.

---------

Co-authored-by: Marvin Hagemeister <marvin@deno.com>
2025-07-18 19:15:14 +02:00
Marvin Hagemeister a703e79181 docs: update canary docs for Fresh 2 (#3108)
There are still some rough edges here and there, but it's in a much
better shape than what we have today.
2025-07-18 15:18:38 +02:00
Marvin Hagemeister 226e250386 fix: middleware regressions (#3106)
Fixes some regressions found after merging
https://github.com/denoland/fresh/pull/3086

- Missing 404 middlewares when mounting sub-apps
- revert more staticFiles logic to always require the middleware like
before
2025-07-17 15:23:27 +02:00
Marvin Hagemeister c279efa345 fix: incorrect middleware ordering (#3102)
This is a regression introduced in
https://github.com/denoland/fresh/pull/3086
2025-07-16 16:43:46 +02:00
Marvin Hagemeister 599973bb5c fix: support non-fallthrough static files like before (#3099) 2025-07-16 14:34:39 +02:00
Luca Casonato b7384037f9 fix: find nearest deno config with compiler options (#3096)
Previously it would only consult the compiler options in the workspace
root deno.json, now it also considers relevant workspace members.
2025-07-16 11:36:21 +00:00
Marvin Hagemeister c11cf7b41a feat: expose layouts and pages on App (#3086)
This PR extracts the functionality from the `fs_routes` plugin and
exposes it onto `App`. These are the new APIs:

- `app.layout(pattern, route)`
- `app.onError(pattern, route)`
- `app.notFound(pattern, route)`
- `app.route(pattern, route)`

This also removes the need for `.use(staticFiles())`. This line can be
safely removed.

Fixes https://github.com/denoland/fresh/issues/3040
Fixes https://github.com/denoland/fresh/issues/3033
Fixes https://github.com/denoland/fresh/issues/2591
Fixes https://github.com/denoland/fresh/issues/950
Fixes https://github.com/denoland/fresh/issues/1918
2025-07-14 19:27:48 +02:00
Marvin Hagemeister 6eeb20c7a3 Revert "feat: support overwriting default 404 handler (#3081)" (#3093)
This reverts commit 0b3546f201.

Reverting this because it will be superseded by
https://github.com/denoland/fresh/pull/3086
2025-07-14 18:11:20 +02:00
Marvin Hagemeister e2699923b0 chore: rename tests FreshApp -> App (#3087) 2025-07-10 10:24:39 +02:00
Marvin Hagemeister a941dd33c5 chore: ignore test tmp delete failures on windows (#3088) 2025-07-10 10:21:22 +02:00
zhizheng cfc9a9a601 chore: ensures more stable CI runs on Windows environments. (#3070)
This pull request includes a small but important change to the
`withTmpDir` function in `src/test_utils.ts`. The change adds error
handling to ensure that a `PermissionDenied` error during directory
removal does not interrupt the execution.
2025-07-10 10:09:16 +02:00
Marvin Hagemeister 31434a2cf9 fix: wrong fresh domain used in hash (#3085) 2025-07-09 23:39:39 +02:00
Marvin Hagemeister f7174d0df0 chore: cleanup cors middleware (#3083)
- Remove some indirections
- Make tests self contained
- Switch tests to `Deno.test` as the LSP doesn't yet recognise
`describe/it`
2025-07-09 21:44:57 +02:00
Chris d072dc2fc0 fix: avoid reload for user-code history changes (#3045) (#3048)
The Fresh partials popstate handler causes page reloads when user code
makes use of navigation history state. This can lead to a loss of user
data in a browsing context.
To fix this behavior, FreshHistoryState now has a flag which validates
partials functionality/explicitly opts-in to any partial related
location management.
2025-07-09 20:59:32 +02:00
Coty ee46263053 feat: Add localhost help text to server address output (#3077)
When binding to `0.0.0.0` or `::`, show localhost equivalent URL for
convenience

Closes #3076

output from fresh www

```
deno task start
Task start deno run -A --watch=static/,routes/,../src,../docs dev.ts
Watcher Process started.

 🍋 Fresh ready
    Local:  http://0.0.0.0:8000/ (http://localhost:8000/)

GA4_MEASUREMENT_ID environment variable not set. Google Analytics reporting disabled.
```
2025-07-09 00:58:04 +02:00
Marvin Hagemeister 0b3546f201 feat: support overwriting default 404 handler (#3081)
Fixes https://github.com/denoland/fresh/issues/1918
2025-07-09 00:40:12 +02:00
Marvin Hagemeister 8416078b6a fix(core): improve island props serialization (#3071) 2025-06-30 16:31:58 +02:00
Asher Gomez 8f813fad90 fix(core): use PageProps instead of FreshContext in define*() compat functions (#3064)
In Fresh 1, define apps used `RouteContext`, which align with
`PageProps` in Fresh 2, rather than `FreshContext`. E.g. before this PR,
one would get a type error if they tried to use `ctx.Component` within
`defineApp()` and now they shouldn't.
2025-06-27 09:54:53 +02:00
Asher Gomez 682368ba30 refactor(src): remove redundant coloring from createCodeFrame() (#3049)
`src/runtime/server/preact_hooks.tsx` is the only place that
`createCodeFrame()` is used which stripped the ANSI codes anyway.
2025-06-18 10:43:56 +02:00
Marvin Hagemeister 85d22e0bb0 fix(core): move to new esbuild deno plugin (#3034)
Move to the new esbuild plugin that leverages `@deno/loader` under the
hood. This is based on the exact same rust crates that Deno itself uses
to do resolution, instead of doing it's own resolution.
2025-06-18 10:42:47 +02:00
75897de196 chore: add tests for fresh/compat imports (#3036)
- `fresh/compat - defineFn mixed return types` - Tests all supported
return types (Response, VNode, null) with both sync and async handlers,
including FreshContext parameter usage

- `fresh/compat - multiple compat imports` - Tests importing multiple
compat functions simultaneously

close #3025 

--patch-1
try to use deno/std Api to replace

--patch-2
make it simple and clean

--patch-3
Convert update_test.ts to .tsx for JSX support
Use static imports instead of dynamic imports for better performance
Switch from @std/assert to @std/expect for consistency
Use ReturnType<> for automatic type inference instead of manual type
definitions

Sincerely grateful to @iuioiua for the guidance and patience.

---------

Co-authored-by: 李嘉图·M·路 <146103794+Ricardo-M-Zheng@users.noreply.github.com>
Co-authored-by: Asher Gomez <ashersaupingomez@gmail.com>
2025-06-17 13:06:21 +02:00
Asher Gomez c3c79352b0 fix(core): refine HttpError.status property type (#2890)
As this is property only ever has an error HTTP status code (>400).
2025-06-16 17:57:49 +02:00
Asher Gomez 71b7de4581 fix(core): align defineFn() with previous definition (#3043)
https://github.com/denoland/fresh/blob/990357629e50ef123e5b5ee2b80c250be867534f/src/server/defines.ts#L13-L16

Closes #3042
2025-06-16 11:04:18 +02:00
Asher Gomez e868a924fa fix(update): correct return and argument types for defineFn() (#3023)
Previously, the return union type of the inner function and the function
itself contained a `Request` instead of a `Response`.
2025-06-12 13:25:36 +02:00
Octo8080XandMarvin Hagemeister 1213aad90d feat: add CORS middleware (#3013)
## Why was this PR initiated?

I opened an issue and held discussions about officially providing
middleware in Fresh by porting middleware from Hono.

https://github.com/denoland/fresh/issues/3011

## What does this PR do? 

I introduced the CORS middleware bundled with Fresh by porting the CORS
middleware from Hono.


I appreciate your review.

---------

Co-authored-by: Marvin Hagemeister <marvin@deno.com>
2025-06-11 17:34:00 +02:00
Christian Svensson b4c3ff8e98 feat: add flag to FreshContext for partial requests (#2993)
Addresses a gap between [Fresh
v1](https://github.com/denoland/fresh/blob/1.x/src/server/types.ts#L192)
and Fresh v2, by adding `ctx.isPartial` to `FreshContext`.

The same route (e.g. `GET /api/autocomplete`) can be called from both an
Island or a Partial. Returning JSON or HTML depending on the destination
of the code.

Or is the intent that endpoints returning partials and data should be
separated, and this pattern is not to be encouraged in Fresh v2? My use
case in Fresh v1 was an `/routes/api/cart.tsx`, which can either just
toggle a product from the cart (via cookie), but also update UI elements
(e.g. cart icon) based on if called from partial or not.


![image](https://github.com/user-attachments/assets/a1cbcfb1-2446-4d6d-bce5-4c3d6acf9bfd)
2025-05-26 14:15:36 +02:00
Marvin Hagemeister 750ab35499 fix: add back LayoutConfig (#2982)
~~Makes it easier to upgrade from 1.x .~~

Initially, I assumed it would be just an alias to `RouteConfig`, but
upon closer inspection that has some additional properties that make no
sense for a layout.
2025-05-21 13:44:09 +02:00
Christian Svensson 17257dd1c2 test: use disposable tmp dirs (#2983)
Replaces the patterns below with consistent `AsyncDisposable` and `await
using` resource management for automatic cleanup.

- `await withTmpDir(async (dir) => { ... })` with `finally`
  - Makes code a bit flatter, and reduces callback-hell a bit
- `await Deno.makeTempDir()` + `Deno.remove()`
- `await Deno.makeTempDir()`

Helps be more consistent in removing temporary folders. Among others,
ensures temp folders are removed in the tests below:

- `src/build_cache_test.ts`
- `src/dev/builder_test.ts`
- `src/dev/dev_build_cache_test.ts`

## TODO's

The `Deno.makeTempDir()` method is still used by `buildProd` as well,
but this method is used in the top module scope, where it does not work
correctly with `Deno.test` (it runs before the test methods). I removed
this part from the PR and leave this for later to avoid making the PR
too big.

-
https://github.com/csvn/fresh/blob/test%2Fdisposable-tmp-dirs/tests/test_utils.tsx/#L64
-
https://github.com/csvn/fresh/blob/test%2Fdisposable-tmp-dirs/www/main_test.ts/#L7
2025-05-21 11:13:02 +02:00
Christian Svensson db142115ec feat: support automatic workspace detection in Dev (#2985)
Adds support for [Automatic Workspace
Detection](https://chromium.googlesource.com/devtools/devtools-frontend/+/main/docs/ecosystem/automatic_workspace_folders.md).

- Avoids 404's or middleware logging when this feature is active (e.g.
Chrome/Edge with DevTools open)
- Generates the same UUID based on root folder path (without writing
anything to disk)
- The middleware is lazy and does nothing until the path is opened for
`com.chrome.devtools.json`
2025-05-21 11:09:43 +02:00
Christian Svensson bc8cdb9c7b fix: convert island filePath to valid variable name (#2984)
I only added a unit test, but maybe it's testing internals too much?
Should I add a more E2E test in `tests/` with real files?


Closes #2971
2025-05-21 11:06:16 +02:00
Asher Gomez 144ed2e75c refactor(core): minor fresh/compat cleanups (#2880) 2025-05-19 12:05:22 +02:00
Marvin Hagemeister e996b5e2fe feat(core): support exclude option for transformers (#2960)
This PR adds general support for an `exclude` option to file
transformers. This allows plugin to skip processing excluded files. The
exclude array can be a `string`, a `RegExp` or a glob pattern.

Fixes https://github.com/denoland/fresh/issues/2937
2025-05-16 15:17:43 +02:00
Marvin Hagemeister 63cb208f8b fix(core): support method handler on _error, _404 and _500 routes (#2955)
This PR adds support for using method handlers in `_error`, `_404` and
`_500` files.

Fixes https://github.com/denoland/fresh/issues/2953
2025-05-15 17:15:30 +02:00
Christian Svensson b852fe7deb fix: log warning on invalid route configurations (#2954)
Related to #2953.

I found it confusing that there were unsupported route configurations,
that fails silently without any errors or wanings. Though I think it is
a good idea to not throw for this, as that would be worse DX. But
logging a warning if the developer is migrating from Fresh v1, or if the
developer is using code that will not work (e.g. copy pasting a handler
from a route to `_middleware`), I think it's helpful where reasonable to
help guide a bit more.

Does a small refactor first to hopefully improve typing to be more
correct for `InternalRoute.handlers`, then adds warnings for the
following:

- `_middleware` using Object form (`GET`, `POST` handlers) of the
handler format
  - Helps find issues when moving handler from route to middleware
- `_layout` using `handlers`
  - E.g. if developer moves a route to a layout
- ~~`_404`, `_500` or `_error` using Object handler form (`GET`, `POST`
handlers), which is not yet supported (See #2953)~~
  - No longer necessary as it is fixed by #2955
2025-05-15 17:09:53 +02:00
Asher Gomez 20162f6896 chore: use lint tags (#2952) 2025-05-15 09:34:46 +02:00
Marvin Hagemeister 36442d0ded fix(core): silence esbuild jsx comment warning (#2944)
JSR is a bit over-eager with inserting JSX comments and inserts both
`@jsx classic` and `@jsxImportSource` which are ignored in combination

Fixes https://github.com/denoland/fresh/issues/2942
2025-05-14 22:45:04 +02:00
Christian Svensson e2d0624512 fix: do not skip app-wrapper for sibling routes (#2911)
This PR adds a unit test for the issue in #2910. I have not found a
solution yet, since I'm not very familiar with the `fsRoutes` code, and
what it is doing. But a thought a unit test with the failing code could
help to find a bug fix.

**Edit:** I managed to fix the failing test by removing a couple of
lines, but I'm not too familiar with the code so I'm not sure if it's
correct. It seems to pass all the tests still...

Closes #2910
2025-05-13 18:03:13 +02:00
Christian Svensson f15f225576 fix: make static folders with dot such as .well-known allowed (#2929)
This PR intends to address an error logged when opening a DevTools in a
Chromium based browser while using Fresh in dev mode.

<details>

<summary><strong>See error</strong></summary>

```
Error: Processed file resolved outside of static dir C:\Users\<name>\fresh-site\src\static\.well-known\appspecific\com.chrome.devtools.json
    at MemoryBuildCache.readFile (https://jsr.io/@fresh/core/2.0.0-alpha.29/src/dev/dev_build_cache.ts:81:13)
    at eventLoopTick (ext:core/01_core.js:178:7)
    at async freshStaticFiles (https://jsr.io/@fresh/core/2.0.0-alpha.29/src/middlewares/static_files.ts:30:18)
    at async FreshReqContext.fn (https://jsr.io/@fresh/core/2.0.0-alpha.29/src/middlewares/mod.ts:99:18)
    at async https://jsr.io/@fresh/core/2.0.0-alpha.29/src/dev/middlewares/error_overlay/middleware.tsx:15:14
    at async FreshReqContext.fn (https://jsr.io/@fresh/core/2.0.0-alpha.29/src/middlewares/mod.ts:99:18)
    at async fn (https://jsr.io/@fresh/core/2.0.0-alpha.29/src/middlewares/mod.ts:99:18)
    at async https://jsr.io/@fresh/core/2.0.0-alpha.29/src/app.ts:232:16
    at async mapped (ext:deno_http/00_serve.ts:407:18)
```

</details>

DevTools tries to load a
`<root>/static/.well-known/appspecific/com.chrome.devtools.json` file,
which incorrectly is flagged as "outside" the static directory, and thus
generates errors instead of 404.

Maybe hidden folders (starting with `.`) in `/static` should be opt-in
though? I'm not sure if anyone puts folders with `.` prefix inside
`static/` without intending them to be accessible?

- `..` throws errors (outside staticDir)
- `.` returns "missing file" (unless `config.allowHiddenFolders` is
true)

## Automatic workspace folders

I think a follow-up PR could be for the Dev `Builder` to also implement
support for [Automatic workspace
folders](https://chromium.googlesource.com/devtools/devtools-frontend/+/main/docs/ecosystem/automatic_workspace_folders.md),
by returning JSON content automatically at
`.well-known/appspecific/com.chrome.devtools.json`.

I think a good first step is to allow `.<folder-name>`, especially since
`.well-known/` has [many valid
use-cases](https://en.wikipedia.org/wiki/Well-known_URI), and as such is
not unreasonable to want to add static files in.
2025-05-13 10:03:05 +02:00
Marvin Hagemeister fcd94809c8 fix(esbuild): disable spammy warning for monaco editor (#2928)
It's a super spammy warning message when you're using the monaco editor.
They have code like that as the result of minifcation.

Fixes https://github.com/denoland/fresh/issues/2775
2025-05-13 00:13:21 +02:00
Marvin Hagemeister d2da471d67 fix(partial): form dialog method not supported (#2927)
The `<form>` method value `dialog` does no network request, so we should
ignore it for partials.

Fixes https://github.com/denoland/fresh/issues/2885
2025-05-12 21:19:19 +02:00
Marvin Hagemeister 24ad244a79 fix: error when no Response instance is returned (#2924)
Fixes https://github.com/denoland/fresh/issues/1494
2025-05-12 20:30:45 +02:00
Marvin Hagemeister 09705b9b7f fix: bigint key values erroring (#2923)
Fixes https://github.com/denoland/fresh/issues/2802
2025-05-12 19:49:13 +02:00
Tim Reichen 1cfb4bc876 refactor: make App.prototype.handler() sync (#2906) 2025-05-12 10:12:50 +02:00
Tim Reichen 9605cd81b5 refactor: move mergePaths() to utils.ts (#2905) 2025-05-12 09:59:37 +02:00
Tim Reichen c6d4c47e00 refactor: App.prototype.listen() (#2907) 2025-05-12 09:58:37 +02:00