feat(server): Add basePath config to host from a directory (#2092)

Co-authored-by: Marvin Hagemeister <marvin@deno.com>
This commit is contained in:
Reed von Redwitz
2023-11-29 16:44:25 +00:00
committed by GitHub
co-authored by Marvin Hagemeister
parent fe792455ab
commit 9ab8651018
40 changed files with 810 additions and 28 deletions
@@ -0,0 +1,212 @@
---
description: |
The ability to configure the core Fresh server leads to its flexibility.
---
In this page we discuss how the server can be configured during startup.
The signature of the primary method looks like this:
```ts main.ts
export async function start(manifest: Manifest, config: FreshConfig = {});
```
## Configuration
`Manifest` comes from `fresh.gen.ts`, so nothing to do there. `config` is where
things get interesting.
[`FreshConfig`](https://deno.land/x/fresh/server.ts?s=FreshConfig) looks like
this:
```ts
export interface FreshConfig {
build?: {
/**
* The directory to write generated files to when `dev.ts build` is run.
* This can be an absolute path, a file URL or a relative path.
*/
outDir?: string;
/**
* This sets the target environment for the generated code. Newer
* language constructs will be transformed to match the specified
* support range. See https://esbuild.github.io/api/#target
* @default {"es2022"}
*/
target?: string | string[];
};
render?: RenderFunction;
plugins?: Plugin[];
staticDir?: string;
router?: RouterOptions;
server?: Partial<Deno.ServeTlsOptions>;
}
```
And for completeness here are the remaining two types:
```ts
export type RenderFunction = (
ctx: RenderContext,
render: InnerRenderFunction,
) => void | Promise<void>;
export interface RouterOptions {
/**
* Controls whether Fresh will append a trailing slash to the URL.
* @default {false}
*/
trailingSlash?: boolean;
/**
* Configures the pattern of files to ignore in islands and routes.
*
* By default Fresh will ignore test files,
* for example files with a `.test.ts` or a `_test.ts` suffix.
*
* @default {/(?:[^/]*_|[^/]*\.|)test\.(?:ts|tsx|mts|js|mjs|jsx|)\/*$/}
*/
ignoreFilePattern?: RegExp;
/**
* Serve fresh from a base path instead of from the root.
* "/foo/bar" -> http://localhost:8000/foo/bar
* @default {undefined}
*/
basePath?: string;
}
```
## Build
### outDir
As the comment suggests, this can be used to configure where generated files are
written:
```tsx
await dev(import.meta.url, "./main.ts", {
build: {
outDir: Deno.env.get("FRESH_TEST_OUTDIR") ?? undefined,
},
});
```
### target
This should be a valid ES Build target.
```tsx
await dev(import.meta.url, "./main.ts", {
build: {
target: "es2015",
},
});
```
## Plugins
See the [docs](/docs/concepts/plugins) on this topic for more detail. But as a
quick example, you can do something like this to load plugins:
```ts main.ts
await start(manifest, { plugins: [twindPlugin(twindConfig)] });
```
## StaticDir
This allows you to specify the location where your site's static assets are
stored. Here's an example:
```ts main.ts
await start(manifest, { staticDir: "./custom_static" });
```
## Render
This is by far the most complicated option currently available. It allows you to
configure how your components get rendered.
## RouterOptions
### TrailingSlash
By default Fresh uses URLs like `https://www.example.com/about`. If you'd like,
you can configure this to `https://www.example.com/about/` by using the
`trailingSlash` setting.
```ts main.ts
await start(manifest, { router: { trailingSlash: true } });
```
### ignoreFilePattern
By default Fresh ignores test files which are co-located next routes and
islands. If you want, you can change the pattern Fresh uses ignore these files
### basePath
This setting allows you to serve a Fresh app from sub-path of a domain. A value
of `/foo/bar` would serve the app from `http://localhost:8000/foo/bar` instead
of `http://localhost:8000/` for example.
The `basePath` will be automatically applied to absolute links in your app. For
example, when the `basePath` is `/foo/bar`, linking to `/about` will
automatically become `/foo/bar/about`.
```jsx
<a href="/about">About</a>;
```
Rendered HTML:
```html
<a href="/foo/bar/about">About</a>
```
The `basePath` is also applied to the `src` and `srcset` attribute of
`<img>`-tags, the `href` attribute of `<link>` and the `src` attribute of
`<script>` tags.
## Server
Now that Deno has stabilized [Deno.serve](https://deno.land/api?s=Deno.serve)
and Fresh has switched to using this API, all server configuration options are
embedded in `server` inside the `FreshConfig`. The fully expanded set of
parameters looks like this:
```ts
server: {
/** Server private key in PEM format */
cert: string;
/** Cert chain in PEM format */
key: string;
/** The port to listen on.
*
* @default {8000} */
port?: number;
/** A literal IP address or host name that can be resolved to an IP address.
*
* __Note about `0.0.0.0`__ While listening `0.0.0.0` works on all platforms,
* the browsers on Windows don't work with the address `0.0.0.0`.
* You should show the message like `server running on localhost:8080` instead of
* `server running on 0.0.0.0:8080` if your program supports Windows.
*
* @default {"0.0.0.0"} */
hostname?: string;
/** An {@linkcode AbortSignal} to close the server and all connections. */
signal?: AbortSignal;
/** Sets `SO_REUSEPORT` on POSIX systems. */
reusePort?: boolean;
/** The handler to invoke when route handlers throw an error. */
onError?: (error: unknown) => Response | Promise<Response>;
/** The callback which is called when the server starts listening. */
onListen?: (params: { hostname: string; port: number }) => void;
}
```
Use these to configure your server as you see fit.
+1 -1
View File
@@ -61,7 +61,7 @@ const toc: RawTableOfContents = {
["deployment", "Deployment", "link:latest"],
["plugins", "Plugins", "link:canary"],
["updating", "Updating Fresh", "link:latest"],
["server-configuration", "Server configuration", "link:latest"],
["server-configuration", "Server configuration", "link:canary"],
],
},
integrations: {
+28
View File
@@ -20,6 +20,7 @@ export interface EsbuildBuilderOptions {
jsxImportSource?: string;
target: string | string[];
absoluteWorkingDir: string;
basePath?: string;
}
export class EsbuildBuilder implements Builder {
@@ -94,6 +95,7 @@ export class EsbuildBuilder implements Builder {
metafile: true,
plugins: [
devClientUrlPlugin(opts.basePath),
buildIdPlugin(opts.buildID),
...denoPlugins({ configPath: opts.configPath }),
],
@@ -128,6 +130,32 @@ export class EsbuildBuilder implements Builder {
}
}
function devClientUrlPlugin(basePath?: string): Plugin {
return {
name: "dev-client-url",
setup(build) {
build.onLoad(
{ filter: /client\.ts$/, namespace: "file" },
async (args) => {
// Load the original script
const contents = await Deno.readTextFile(args.path);
// Replace the URL
const modifiedContents = contents.replace(
"/_frsh/alive",
`${basePath}/_frsh/alive`,
);
return {
contents: modifiedContents,
loader: "ts",
};
},
);
},
};
}
function buildIdPlugin(buildId: string): Plugin {
const file = import.meta.resolve("../runtime/build_id.ts");
const url = new URL(file);
+4 -1
View File
@@ -55,7 +55,10 @@ export async function dev(
state.config.dev = true;
state.loadSnapshot = false;
const ctx = await getServerContext(state);
await startServer(ctx.handler(), state.config.server);
await startServer(ctx.handler(), {
...state.config.server,
basePath: state.config.basePath,
});
} else {
// Legacy entry point: Back then `dev.ts` would call `main.ts` but
// this causes duplicate plugin instantiation if both `dev.ts` and
+3 -2
View File
@@ -3,7 +3,7 @@ import { ServeHandler } from "./types.ts";
export async function startServer(
handler: Deno.ServeHandler,
opts: Partial<Deno.ServeTlsOptions>,
opts: Partial<Deno.ServeTlsOptions> & { basePath: string },
) {
if (!opts.onListen) {
opts.onListen = (params) => {
@@ -12,7 +12,8 @@ export async function startServer(
colors.bgRgb8(colors.rgb8(" 🍋 Fresh ready ", 0), 121),
);
const address = colors.cyan(`http://localhost:${params.port}/`);
const pathname = opts.basePath + "/";
const address = colors.cyan(`http://localhost:${params.port}${pathname}`);
const localLabel = colors.bold("Local:");
console.log(` ${localLabel} ${address}\n`);
};
+5
View File
@@ -1,3 +1,4 @@
import { SEP } from "./deps.ts";
import { ErrorHandler, FinalHandler, RouteResult } from "./router.ts";
import {
BaseRoute,
@@ -11,6 +12,8 @@ import {
export const ROOT_BASE_ROUTE = toBaseRoute("/");
export function toBaseRoute(input: string): BaseRoute {
input = input.replaceAll(SEP, "/");
if (input.endsWith("_layout")) {
input = input.slice(0, -"_layout".length);
} else if (input.endsWith("_middleware")) {
@@ -58,6 +61,7 @@ export function composeMiddlewares(
url: string,
) => RouteResult<RouterState>,
renderNotFound: UnknownRenderFunction,
basePath: string,
) {
return (
req: Request,
@@ -109,6 +113,7 @@ export function composeMiddlewares(
return await renderNotFound(req, paramsAndRouteResult.params, ctx);
},
isPartial: paramsAndRouteResult.isPartial,
basePath,
};
for (const { module } of mws) {
+22
View File
@@ -57,6 +57,27 @@ export async function getInternalFreshState(
const isLegacyDev = Deno.env.get("__FRSH_LEGACY_DEV") === "true";
/**
* assume a basePath is declared like this:
* basePath: "/foo/bar"
* it must start with a slash, and not have a trailing slash
*/
let basePath = "";
if (config.router?.basePath) {
basePath = config.router?.basePath;
if (!basePath.startsWith("/")) {
throw new TypeError(
`"basePath" option must start with "/". Received: "${basePath}"`,
);
}
if (basePath.endsWith("/")) {
throw new TypeError(
`"basePath" option must not end with "/". Received: "${basePath}"`,
);
}
}
const internalConfig: ResolvedFreshConfig = {
dev: isLegacyDev || Boolean(config.dev),
build: {
@@ -72,6 +93,7 @@ export async function getInternalFreshState(
render: config.render ?? DEFAULT_RENDER_FN,
router: config.router,
server: config.server ?? {},
basePath,
};
if (config.cert) {
+43 -13
View File
@@ -1,7 +1,12 @@
import { contentType, extname, STATUS_CODE } from "./deps.ts";
import { contentType, extname, SEP, STATUS_CODE } from "./deps.ts";
import * as router from "./router.ts";
import { FreshConfig, Manifest, UnknownHandlerContext } from "./mod.ts";
import { ALIVE_URL, DEV_CLIENT_URL, JS_PREFIX } from "./constants.ts";
import {
ALIVE_URL,
DEV_CLIENT_URL,
DEV_ERROR_OVERLAY_URL,
JS_PREFIX,
} from "./constants.ts";
import { BUILD_ID } from "./build_id.ts";
import {
@@ -38,6 +43,7 @@ import {
import { extractRoutes, FsExtractResult } from "./fs_extract.ts";
import { loadAotSnapshot } from "../build/aot_snapshot.ts";
import { ErrorOverlay } from "./error_overlay.tsx";
import { withBase } from "./router.ts";
const DEFAULT_CONN_INFO: ServeHandlerInfo = {
localAddr: { transport: "tcp", hostname: "localhost", port: 8080 },
@@ -90,6 +96,7 @@ export async function getServerContext(state: InternalFreshState) {
jsxImportSource: denoJson.compilerOptions?.jsxImportSource,
target: state.config.build.target,
absoluteWorkingDir: Deno.cwd(),
basePath: state.config.basePath,
});
return new ServerContext(
@@ -140,12 +147,14 @@ export class ServerContext {
* by Fresh, including static files.
*/
handler(): (req: Request, connInfo?: ServeHandlerInfo) => Promise<Response> {
const basePath = this.#state.config.basePath;
const renderNotFound = createRenderNotFound(
this.#extractResult,
this.#dev,
this.#plugins,
this.#renderFn,
this.#maybeBuildSnapshot(),
basePath,
);
const handlers = this.#handlers(renderNotFound);
const inner = router.router<RouterState>(handlers);
@@ -154,6 +163,7 @@ export class ServerContext {
handlers.errorHandler,
router.getParamsAndRoute<RouterState>(handlers),
renderNotFound,
basePath,
);
const trailingSlashEnabled = this.#state.config.router?.trailingSlash;
const isDev = this.#dev;
@@ -172,9 +182,11 @@ export class ServerContext {
) {
const url = new URL(req.url);
const aliveUrl = basePath + ALIVE_URL;
if (isDev) {
// Live reload: Send updates to browser
if (url.pathname === ALIVE_URL) {
if (url.pathname === aliveUrl) {
if (req.headers.get("upgrade") !== "websocket") {
return new Response(null, { status: 501 });
}
@@ -197,8 +209,8 @@ export class ServerContext {
return response;
} else if (
url.pathname === DEV_CLIENT_URL ||
url.pathname === `${DEV_CLIENT_URL}.map`
url.pathname === withBase(DEV_CLIENT_URL, basePath) ||
url.pathname === withBase(`${DEV_CLIENT_URL}.map`, basePath)
) {
const bundlePath = (url.pathname.endsWith(".map"))
? "fresh_dev_client.js.map"
@@ -236,6 +248,12 @@ export class ServerContext {
}
}
// Redirect to base path if not present in url
if (basePath && !url.pathname.startsWith(basePath)) {
const to = new URL(basePath + url.pathname, url.origin);
return Response.redirect(to, 302);
}
return await withMiddlewares(req, connInfo, inner);
};
}
@@ -280,10 +298,12 @@ export class ServerContext {
const staticRoutes: router.Routes<RouterState> = {};
const routes: router.Routes<RouterState> = {};
internalRoutes[`${INTERNAL_PREFIX}${JS_PREFIX}/${BUILD_ID}/:path*`] = {
baseRoute: toBaseRoute(
`${INTERNAL_PREFIX}${JS_PREFIX}/${BUILD_ID}/:path*`,
),
const assetRoute = withBase(
`${INTERNAL_PREFIX}${JS_PREFIX}/${BUILD_ID}/:path*`,
this.#state.config.basePath,
);
internalRoutes[assetRoute] = {
baseRoute: toBaseRoute(assetRoute),
methods: {
default: this.#bundleAssetRoute(),
},
@@ -297,7 +317,7 @@ export class ServerContext {
const { localUrl, path, size, contentType, etag } of this.#extractResult
.staticFiles
) {
staticRoutes[path] = {
staticRoutes[path.replaceAll(SEP, "/")] = {
baseRoute: toBaseRoute(path),
methods: {
"HEAD": this.#staticFileHandler(
@@ -329,7 +349,7 @@ export class ServerContext {
status: number,
) => {
const imports: string[] = [];
if (this.#dev) imports.push(DEV_CLIENT_URL);
if (this.#dev) imports.push(this.#state.config.basePath + DEV_CLIENT_URL);
return (
req: Request,
params: Record<string, string>,
@@ -368,6 +388,7 @@ export class ServerContext {
state: ctx?.state,
error,
codeFrame,
basePath: this.#state.config.basePath,
});
if (resp instanceof Response) {
@@ -403,6 +424,7 @@ export class ServerContext {
async renderNotFound<Data = undefined>(data: Data) {
return await renderNotFound(req, params, ctx, data);
},
basePath: this.#state.config.basePath,
}),
},
};
@@ -424,6 +446,7 @@ export class ServerContext {
async renderNotFound<Data = undefined>(data: Data) {
return await renderNotFound(req, params, ctx, data);
},
basePath: this.#state.config.basePath,
});
}
}
@@ -478,8 +501,12 @@ export class ServerContext {
};
if (this.#dev) {
const baseRoute = toBaseRoute("/_frsh/error_overlay");
internalRoutes["/_frsh/error_overlay"] = {
const devErrorUrl = withBase(
DEV_ERROR_OVERLAY_URL,
this.#state.config.basePath,
);
const baseRoute = toBaseRoute(devErrorUrl);
internalRoutes[devErrorUrl] = {
baseRoute,
methods: {
default: async (req, ctx) => {
@@ -513,6 +540,7 @@ export class ServerContext {
},
error: null,
codeFrame: undefined,
basePath: this.#state.config.basePath,
});
if (resp instanceof Response) {
@@ -607,6 +635,7 @@ const createRenderNotFound = (
plugins: Plugin<Record<string, unknown>>[],
renderFunction: RenderFunction,
buildSnapshot: BuildSnapshot | null,
basePath: string,
) => {
const dependenciesFn = (path: string) => {
const snapshot = buildSnapshot;
@@ -648,6 +677,7 @@ const createRenderNotFound = (
data,
state: ctx?.state,
error,
basePath,
});
if (resp instanceof Response) {
+6
View File
@@ -6,6 +6,7 @@ export {
fromFileUrl,
isAbsolute,
join,
SEP,
toFileUrl,
} from "https://deno.land/std@0.208.0/path/mod.ts";
export { walk } from "https://deno.land/std@0.208.0/fs/walk.ts";
@@ -26,4 +27,9 @@ export {
assertEquals,
assertThrows,
} from "https://deno.land/std@0.208.0/assert/mod.ts";
export {
isIdentifierChar,
isIdentifierStart,
} from "https://esm.sh/@babel/helper-validator-identifier@7.22.20";
export { normalize } from "https://deno.land/std@0.208.0/path/posix/mod.ts";
export { assertSnapshot } from "https://deno.land/std@0.208.0/testing/snapshot.ts";
+8 -3
View File
@@ -26,6 +26,7 @@ import {
dirname,
extname,
join,
SEP,
toFileUrl,
walk,
} from "./deps.ts";
@@ -107,8 +108,12 @@ export async function extractRoutes(
throw new TypeError("Page is not a child of the basepath.");
}
const path = url.substring(baseUrl.length + "routes".length);
const baseRoute = path.substring(1, path.length - extname(path).length);
const name = baseRoute.replace("/", "-");
let baseRoute = path.substring(1, path.length - extname(path).length);
baseRoute = join(state.config.basePath.slice(1), baseRoute).replaceAll(
SEP,
"/",
);
const name = baseRoute.replace(/\//g, "-");
const isLayout = path.endsWith("/_layout.tsx") ||
path.endsWith("/_layout.ts") || path.endsWith("/_layout.jsx") ||
path.endsWith("/_layout.js");
@@ -328,7 +333,7 @@ export async function extractRoutes(
);
const staticFile: StaticFile = {
localUrl,
path,
path: join(state.config.basePath, path),
size: stat.size,
contentType: type,
etag,
+5 -1
View File
@@ -110,5 +110,9 @@ export async function start(manifest: Manifest, config: FreshConfig = {}) {
...config,
dev: false,
});
await startServer(ctx.handler(), config.server ?? config);
const realConfig = config.server ?? config;
await startServer(ctx.handler(), {
...realConfig,
basePath: config?.router?.basePath ?? "",
});
}
+6 -2
View File
@@ -20,6 +20,7 @@ import { renderHtml, renderOuterDocument } from "./rendering/template.tsx";
import { renderFreshTags } from "./rendering/fresh_tags.tsx";
import { DEV_ERROR_OVERLAY_URL } from "./constants.ts";
import { colors } from "./deps.ts";
import { withBase } from "./router.ts";
export const DEFAULT_RENDER_FN: RenderFunction = (_ctx, render) => {
render();
@@ -43,6 +44,7 @@ export interface RenderOptions<Data> {
error?: unknown;
codeFrame?: string;
lang?: string;
basePath: string;
}
export type InnerRenderFunction = () => string;
@@ -256,6 +258,7 @@ export async function render<Data>(
data: opts.data,
state: opts.state,
params: opts.params,
basePath: opts.basePath,
},
componentStack,
csp,
@@ -367,8 +370,9 @@ export async function render<Data>(
});
// Append error overlay
if (opts.error !== undefined && opts.url.pathname !== DEV_ERROR_OVERLAY_URL) {
const url = new URL(DEV_ERROR_OVERLAY_URL, "https://localhost/");
const devErrorUrl = withBase(DEV_ERROR_OVERLAY_URL, opts.basePath);
if (opts.error !== undefined && opts.url.pathname !== devErrorUrl) {
const url = new URL(devErrorUrl, "https://localhost/");
if (opts.error instanceof Error) {
let message = opts.error.message;
const idx = message.indexOf("\n");
+42 -1
View File
@@ -11,7 +11,7 @@ import {
} from "preact";
import { assetHashingHook } from "../../runtime/utils.ts";
import { Partial, PartialProps } from "../../runtime/Partial.tsx";
import { renderToString } from "../deps.ts";
import { join, renderToString, SEP } from "../deps.ts";
import { RenderState } from "./state.ts";
import { Island } from "../types.ts";
import {
@@ -21,6 +21,7 @@ import {
PartialMode,
} from "../../constants.ts";
import { setActiveUrl } from "../../runtime/active_url.ts";
import { withBase } from "../router.ts";
// See: https://github.com/preactjs/preact/blob/7748dcb83cedd02e37b3713634e35b97b26028fd/src/internal.d.ts#L3C1-L16
enum HookType {
@@ -207,6 +208,46 @@ options.vnode = (vnode) => {
if (typeof props[CLIENT_NAV_ATTR] === "boolean") {
props[CLIENT_NAV_ATTR] = props[CLIENT_NAV_ATTR] ? "true" : "false";
}
if (typeof props.href === "string") {
props.href = withBase(props.href, current?.basePath);
}
if (typeof props.src === "string") {
props.src = withBase(props.src, current?.basePath);
}
srcsetRewrite:
if (typeof props.srcset === "string") {
// Bail out on complex syntax that's too complicated for now
if (props.srcset.includes("(")) break srcsetRewrite;
const parts = props.srcset.split(",");
const out: string[] = [];
for (const part of parts) {
const trimmed = part.trimStart();
if (trimmed === "") break srcsetRewrite;
let urlEnd = trimmed.indexOf(" ");
if (urlEnd === -1) urlEnd = trimmed.length;
const leadingWhitespace = part.length - trimmed.length;
const leading = part.substring(0, leadingWhitespace);
const url = trimmed.substring(0, urlEnd);
const trailing = trimmed.substring(urlEnd);
if (url.startsWith("/") && current?.basePath) {
const joinedPath = join("/", current.basePath, url).replaceAll(
SEP,
"/",
);
out.push(leading + joinedPath + trailing);
} else {
out.push(part);
}
}
props.srcset = out.join(",");
}
} else if (
current && typeof vnode.type === "function" && vnode.type !== Fragment &&
ownerStack.length > 0
+3
View File
@@ -12,6 +12,7 @@ export interface RenderStateRouteOptions {
state?: any;
error?: unknown;
params: Record<string, string | string[]>;
basePath: string;
}
export class RenderState {
@@ -44,6 +45,7 @@ export class RenderState {
partialDepth = 0;
islandDepth = 0;
url: URL;
basePath: string;
constructor(
routeOptions: RenderStateRouteOptions,
@@ -57,6 +59,7 @@ export class RenderState {
this.componentStack = componentStack;
this.url = routeOptions.url;
this.isPartial = routeOptions.url.searchParams.has(PARTIAL_SEARCH_PARAM);
this.basePath = routeOptions.basePath;
if (error) this.routeOptions.error = error;
}
+7 -2
View File
@@ -11,6 +11,7 @@ import {
} from "preact";
import { HEAD_CONTEXT } from "../../runtime/head.ts";
import { CSP_CONTEXT } from "../../runtime/csp.ts";
import { withBase } from "$fresh/src/server/router.ts";
export function renderHtml(state: RenderState) {
setRenderState(state);
@@ -121,10 +122,14 @@ export function renderOuterDocument(
docTitle,
docHeadNodes.map((node) => h(node.type, node.props)),
opts.preloads.map((src) =>
h("link", { rel: "modulepreload", href: src })
h("link", { rel: "modulepreload", href: withBase(src, state.basePath) })
),
opts.moduleScripts.map(([src, nonce]) =>
h("script", { src: src, nonce, type: "module" })
h("script", {
src: withBase(src, state.basePath),
nonce,
type: "module",
})
),
filteredHeadNodes,
),
+7
View File
@@ -371,3 +371,10 @@ export function router<T = unknown>(
};
};
}
export function withBase(src: string, base?: string) {
if (base !== undefined && src.startsWith("/") && !src.startsWith(base)) {
return base + src;
}
return src;
}
+9
View File
@@ -128,6 +128,7 @@ export interface ResolvedFreshConfig {
staticDir: string;
router?: RouterOptions;
server: Partial<Deno.ServeTlsOptions>;
basePath: string;
}
export interface RouterOptions {
@@ -145,6 +146,12 @@ export interface RouterOptions {
* @default {/(?:[^/]*_|[^/]*\.|)test\.(?:ts|tsx|mts|js|mjs|jsx|)\/*$/}
*/
ignoreFilePattern?: RegExp;
/**
* Serve fresh from a base path instead of from the root.
* "/foo/bar" -> http://localhost:8000/foo/bar
* @default {undefined}
*/
basePath?: string;
}
export type RenderFunction = (
@@ -264,6 +271,7 @@ export interface HandlerContext<
NotFoundData = Data,
> extends ServeHandlerInfo {
params: Record<string, string>;
basePath: string;
render: (
data?: Data,
options?: RenderOptions,
@@ -503,6 +511,7 @@ export interface MiddlewareHandlerContext<State = Record<string, unknown>>
destination: router.DestinationKind;
params: Record<string, string>;
isPartial: boolean;
basePath: string;
}
export interface MiddlewareRoute {
+170
View File
@@ -0,0 +1,170 @@
import {
assert,
assertEquals,
assertMatch,
delay,
puppeteer,
STATUS_CODE,
} from "./deps.ts";
import {
clickWhenListenerReady,
getErrorOverlay,
waitForText,
withFakeServe,
withFresh,
withPageName,
} from "./test_utils.ts";
Deno.test("redirects on incomplete base path in url", async () => {
await withFresh("./tests/fixture_base_path/main.ts", async (address) => {
await delay(100);
const url = new URL(address);
const res = await fetch(url.origin);
assert(
res.url.endsWith("/foo/bar"),
`didn't redirect to base path: "${res.url}"`,
);
assert(res.redirected, "did not redirect");
assertEquals(res.status, STATUS_CODE.OK);
await res.body?.cancel();
});
});
Deno.test("shows full address with base path in cli", async () => {
// deno-lint-ignore require-await
await withFresh("./tests/fixture_base_path/main.ts", async (address) => {
assertMatch(address, /^http:\/\/localhost:\d+\/foo\/bar$/);
});
});
Deno.test("rewrites middleware request", async () => {
await withFresh("./tests/fixture_base_path/main.ts", async (address) => {
const res = await fetch(`${address}/api`);
const body = await res.text();
assertEquals(body, "it works");
});
});
Deno.test("rewrites root relative middleware redirects", async () => {
await withFresh("./tests/fixture_base_path/main.ts", async (address) => {
const res = await fetch(`${address}/api/rewrite`);
assertEquals(res.status, STATUS_CODE.OK);
assertEquals(res.url, address);
await res.body?.cancel();
});
});
Deno.test("passes basePath to route handlers", async () => {
await withFresh("./tests/fixture_base_path/main.ts", async (address) => {
const res = await fetch(`${address}/api/base-handler`);
assertEquals(res.status, STATUS_CODE.OK);
assertEquals(await res.text(), "/foo/bar");
});
});
Deno.test("works with relative urls", async () => {
await withFresh("./tests/fixture_base_path/main.ts", async (address) => {
const browser = await puppeteer.launch({ args: ["--no-sandbox"] });
const page = await browser.newPage();
await page.goto(`${address}/a/b/relative`);
await Promise.all([
page.waitForNavigation(),
page.click("a"),
]);
const html = await page.content();
assertMatch(html, /it works/);
await browser.close();
});
});
Deno.test("rewrites root relative URLs in HTML", async () => {
await withFresh("./tests/fixture_base_path/main.ts", async (address) => {
const browser = await puppeteer.launch({ args: ["--no-sandbox"] });
const page = await browser.newPage();
await page.goto(`${address}/html`);
const script = await page.$eval("#script-output", (el) => el.textContent);
assertEquals(script, "it works");
const img = await page.$eval("img", (el) => ({
src: el.src,
}));
assertMatch(img.src, /\/foo\/bar\/img\.png/);
const img2 = await page.$eval(".img-srcset", (el) => ({
src: el.src,
srcset: el.srcset,
}));
assertMatch(img2.src, /\/foo\/bar\/img\.png/);
assertMatch(
img2.srcset,
/\/foo\/bar\/img\.png.* 480w,.*\/foo\/bar\/img\.png.* 800w/,
);
const source = await page.$eval("picture source", (el) => ({
srcset: el.srcset,
}));
assertMatch(
source.srcset,
/\/foo\/bar\/img\.png/,
);
const style = await page.$eval(
".foo",
(el) => window.getComputedStyle(el).color,
);
assertMatch(
style,
/rgb\(255,\s+0,\s+0\)/,
);
await browser.close();
});
});
Deno.test("island tests", async (t) => {
await withPageName(
"./tests/fixture_base_path/main.ts",
async (page, address) => {
async function counterTest(counterId: string, originalValue: number) {
const pElem = await page.waitForSelector(`#${counterId} > p`);
const value = await pElem?.evaluate((el) => el.textContent);
assert(value === `${originalValue}`, `${counterId} first value`);
await clickWhenListenerReady(page, `#b-${counterId}`);
await waitForText(page, `#${counterId} > p`, String(originalValue + 1));
}
await page.goto(`${address}/islands`);
await t.step("Ensure 1 islands on 1 page are revived", async () => {
await counterTest("counter1", 3);
});
},
);
});
Deno.test("renders error boundary", async () => {
await withPageName(
"./tests/fixture_base_path/main.ts",
async (page, address) => {
await page.goto(`${address}/error_boundary`);
const text = await page.$eval("p", (el) => el.textContent);
assertEquals(text, "it works");
},
);
});
Deno.test("dev_command config: shows codeframe", async () => {
await withFakeServe(
"./tests/fixture_base_path/dev.ts",
async (server) => {
const { codeFrame } = await getErrorOverlay(server, "/codeframe");
assert(codeFrame);
},
);
});
+2
View File
@@ -44,3 +44,5 @@ export {
} from "https://deno.land/std@0.208.0/path/mod.ts";
export * as JSONC from "https://deno.land/std@0.208.0/jsonc/mod.ts";
export * as colors from "https://deno.land/std@0.208.0/fmt/colors.ts";
export { STATUS_CODE } from "https://deno.land/std@0.208.0/http/status.ts";
export { stripAnsiCode } from "https://deno.land/std@0.208.0/fmt/colors.ts";
+18
View File
@@ -0,0 +1,18 @@
{
"lock": false,
"tasks": {
"start": "deno run -A --watch=static/,routes/ dev.ts"
},
"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.2.2",
"@preact/signals-core": "https://esm.sh/@preact/signals-core@1.5.0",
"preact-render-to-string": "https://esm.sh/*preact-render-to-string@6.1.0"
},
"compilerOptions": {
"jsx": "react-jsx",
"jsxImportSource": "preact"
}
}
+5
View File
@@ -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");
+41
View File
@@ -0,0 +1,41 @@
// 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 $_middleware from "./routes/_middleware.ts";
import * as $a_b_b from "./routes/a/b/b.tsx";
import * as $a_b_relative_index from "./routes/a/b/relative/index.tsx";
import * as $api_base_handler from "./routes/api/base-handler.ts";
import * as $api_index from "./routes/api/index.ts";
import * as $api_rewrite from "./routes/api/rewrite.ts";
import * as $baz_slug_ from "./routes/baz/[...slug].tsx";
import * as $codeframe from "./routes/codeframe.tsx";
import * as $error_boundary from "./routes/error_boundary.tsx";
import * as $html from "./routes/html.tsx";
import * as $index from "./routes/index.tsx";
import * as $islands from "./routes/islands.tsx";
import * as $$Counter from "./islands/Counter.tsx";
import { Manifest } from "$fresh/server.ts";
const manifest = {
routes: {
"./routes/_middleware.ts": $_middleware,
"./routes/a/b/b.tsx": $a_b_b,
"./routes/a/b/relative/index.tsx": $a_b_relative_index,
"./routes/api/base-handler.ts": $api_base_handler,
"./routes/api/index.ts": $api_index,
"./routes/api/rewrite.ts": $api_rewrite,
"./routes/baz/[...slug].tsx": $baz_slug_,
"./routes/codeframe.tsx": $codeframe,
"./routes/error_boundary.tsx": $error_boundary,
"./routes/html.tsx": $html,
"./routes/index.tsx": $index,
"./routes/islands.tsx": $islands,
},
islands: {
"./islands/Counter.tsx": $$Counter,
},
baseUrl: import.meta.url,
} satisfies Manifest;
export default manifest;
@@ -0,0 +1,22 @@
import type { Signal } from "@preact/signals";
import { IS_BROWSER } from "$fresh/runtime.ts";
interface CounterProps {
count: Signal<number>;
id: string;
}
export default function Counter(props: CounterProps) {
return (
<div id={props.id}>
<p>{props.count}</p>
<button
id={`b-${props.id}`}
onClick={() => props.count.value += 1}
disabled={!IS_BROWSER}
>
+1
</button>
</div>
);
}
+10
View File
@@ -0,0 +1,10 @@
/// <reference no-default-lib="true" />
/// <reference lib="dom" />
/// <reference lib="dom.iterable" />
/// <reference lib="dom.asynciterable" />
/// <reference lib="deno.ns" />
import { start } from "$fresh/server.ts";
import manifest from "./fresh.gen.ts";
await start(manifest, { router: { basePath: "/foo/bar" } });
@@ -0,0 +1,11 @@
import { MiddlewareHandlerContext } from "$fresh/server.ts";
export async function handler(
_req: Request,
ctx: MiddlewareHandlerContext<{ data: string }>,
) {
ctx.state.data = "it works";
const resp = await ctx.next();
resp.headers.set("server", "fresh server");
return resp;
}
+3
View File
@@ -0,0 +1,3 @@
export default function B() {
return <h1>it works</h1>;
}
@@ -0,0 +1,7 @@
export default function Relative() {
return (
<div>
<a href="b">baz/foo</a>
</div>
);
}
@@ -0,0 +1,9 @@
import { Handlers } from "$fresh/server.ts";
export const handler: Handlers<unknown, { data: string }> = {
GET(_req, ctx) {
return new Response(ctx.basePath, {
status: 200,
});
},
};
@@ -0,0 +1,7 @@
import { Handlers } from "$fresh/server.ts";
export const handler: Handlers<unknown, { data: string }> = {
GET(_req, ctx) {
return new Response(ctx.state.data);
},
};
@@ -0,0 +1,13 @@
import { Handlers } from "$fresh/server.ts";
export const handler: Handlers<unknown, { data: string }> = {
GET(req) {
const url = new URL(req.url);
return new Response(null, {
status: 302,
headers: {
"Location": url.origin,
},
});
},
};
@@ -0,0 +1,3 @@
export default function Other() {
return <h1>it works</h1>;
}
@@ -0,0 +1,4 @@
// deno-lint-ignore no-explicit-any
export default function Page(): any {
throw new Error("fail!!!");
}
@@ -0,0 +1,27 @@
import { Component } from "preact";
class ErrorBoundary extends Component {
state = { error: null } as { error: Error | null };
static getDerivedStateFromError(error: Error) {
return { error };
}
render() {
return this.state.error
? <p>{this.state.error.message}</p>
: <>{this.props.children}</>;
}
}
function Thrower(): preact.JSX.Element {
throw new Error("it works");
}
export default function ErrorBoundaryPage() {
return (
<ErrorBoundary>
<Thrower />
</ErrorBoundary>
);
}
+27
View File
@@ -0,0 +1,27 @@
import { Head } from "$fresh/runtime.ts";
export default function Page() {
return (
<>
<Head>
<link rel="stylesheet" href="/style.css" />
</Head>
<div>
<div id="script-output" />
<script src="/script.js"></script>
<img class="img" src="/img.png" alt="" />
<img
class="img-srcset"
src="/img.png"
srcset="/img.png 480w, /img.png 800w"
alt=""
/>
<picture>
<source srcset="/img.png" media="(min-width: 600px)" />
<img src="/img.png" alt="MDN" />
</picture>
<p class="foo">css style</p>
</div>
</>
);
}
+3
View File
@@ -0,0 +1,3 @@
export default function Home() {
return <h1>it works</h1>;
}
@@ -0,0 +1,10 @@
import { useSignal } from "@preact/signals";
import Counter from "../islands/Counter.tsx";
export default function Home() {
return (
<div>
<Counter id="counter1" count={useSignal(3)} />
</div>
);
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 4.4 KiB

+1
View File
@@ -0,0 +1 @@
document.querySelector("#script-output").textContent = "it works";
+3
View File
@@ -0,0 +1,3 @@
.foo {
color: red;
}
+3 -2
View File
@@ -235,7 +235,6 @@ export async function withPageName(
}
} finally {
serverProcess.kill("SIGTERM");
// Wait until the process exits
await serverProcess.status;
@@ -483,7 +482,9 @@ async function spawnServer(
// @ts-ignore yes it does
for await (const line of lines.values({ preventCancel: true })) {
output.push(line);
const match = line.match(/https?:\/\/localhost:\d+/g);
const match = line.match(
/https?:\/\/localhost:\d+(\/\w+[-\w]*)*/g,
);
if (match) {
address = match[0];
break;