Files
sweet/src/render.ts
T
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

154 lines
3.9 KiB
TypeScript

import {
type AnyComponent,
type FunctionComponent,
h,
type RenderableProps,
type VNode,
} from "preact";
import {
FreshScripts,
type RenderState,
setRenderState,
} from "./runtime/server/preact_hooks.tsx";
import type { Context } from "./context.ts";
import { recordSpanError, tracer } from "./otel.ts";
import { DEV_ERROR_OVERLAY_URL } from "./constants.ts";
import { renderToString } from "preact-render-to-string";
import { BUILD_ID } from "./runtime/build_id.ts";
export type AsyncAnyComponent<P> = {
(
props: RenderableProps<P>,
// deno-lint-ignore no-explicit-any
context?: any,
// deno-lint-ignore no-explicit-any
): Promise<VNode<any> | Response | null>;
displayName?: string;
defaultProps?: Partial<P> | undefined;
};
// deno-lint-ignore no-explicit-any
export function isAsyncAnyComponent(fn: any): fn is AsyncAnyComponent<any> {
return typeof fn === "function" && fn.constructor.name === "AsyncFunction";
}
export async function renderAsyncAnyComponent<Props>(
fn: AsyncAnyComponent<Props>,
props: RenderableProps<Props>,
) {
return await tracer.startActiveSpan(
"invoke async component",
async (span) => {
span.setAttribute("fresh.span_type", "fs_routes/async_component");
try {
const result = (await fn(props)) as VNode | Response;
span.setAttribute(
"fresh.component_response",
result instanceof Response ? "http" : "jsx",
);
return result;
} catch (err) {
recordSpanError(span, err);
throw err;
} finally {
span.end();
}
},
);
}
export function preactRender<State, Data>(
vnode: VNode,
ctx: PageProps<Data, State>,
state: RenderState,
headers: Headers,
) {
try {
let res = renderToString(vnode);
// We require a the full outer DOM structure so that browser put
// comment markers in the right place in the DOM.
if (!state.renderedHtmlBody) {
let scripts = "";
if (ctx.url.pathname !== ctx.config.basePath + DEV_ERROR_OVERLAY_URL) {
scripts = renderToString(h(FreshScripts, null));
}
res = `<body>${res}${scripts}</body>`;
}
if (!state.renderedHtmlHead) {
res = `<head><meta charset="utf-8"></head>${res}`;
}
if (!state.renderedHtmlTag) {
res = `<html>${res}</html>`;
}
return `<!DOCTYPE html>${res}`;
} finally {
// Add preload headers
const basePath = ctx.config.basePath;
const runtimeUrl = `${basePath}/_fresh/js/${BUILD_ID}/fresh-runtime.js`;
let link = `<${encodeURI(runtimeUrl)}>; rel="modulepreload"; as="script"`;
state.islands.forEach((island) => {
link += `, <${
encodeURI(`${basePath}${island.file}`)
}>; rel="modulepreload"; as="script"`;
});
if (link !== "") {
headers.append("Link", link);
}
state.clear();
setRenderState(null);
}
}
export type PageProps<Data = unknown, T = unknown> =
& Pick<
Context<T>,
| "config"
| "url"
| "req"
| "params"
| "info"
| "state"
| "isPartial"
| "Component"
| "error"
>
& { data: Data };
export interface ComponentDef<Data, State> {
props: PageProps<Data, State> | null;
component: AnyComponent<PageProps<Data, State>>;
}
export async function renderRouteComponent<State>(
ctx: Context<State>,
def: ComponentDef<unknown, State>,
child: FunctionComponent,
): Promise<VNode | Response> {
const vnodeProps: PageProps<unknown, State> = {
Component: child,
config: ctx.config,
data: def.props,
error: ctx.error,
info: ctx.info,
isPartial: ctx.isPartial,
params: ctx.params,
req: ctx.req,
state: ctx.state,
url: ctx.url,
};
if (isAsyncAnyComponent(def.component)) {
const result = await renderAsyncAnyComponent(def.component, vnodeProps);
if (result instanceof Response) {
return result;
}
return result;
}
return h(def.component, vnodeProps) as VNode;
}