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
+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 {