Skip to content

Commit da340da

Browse files
authored
BREAKING: move a bunch of types into server/ (#263)
Moved some server only types like `RouteConfig` into server/. They were previously in runtime/.
1 parent 3458e35 commit da340da

22 files changed

Lines changed: 230 additions & 216 deletions

File tree

docs/concepts/routes.md

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,7 @@ Now, let's render some HTML using the route component. Another example:
4242

4343
/** @jsx h */
4444
import { h } from "preact";
45-
import { PageProps } from "$fresh/runtime.ts";
45+
import { PageProps } from "$fresh/server.ts";
4646

4747
export default function Page(props: PageProps) {
4848
return <div>You are on the page '{props.url.href}'.</div>;
@@ -65,8 +65,7 @@ response after rendering the page component.
6565

6666
/** @jsx h */
6767
import { h } from "preact";
68-
import { PageProps } from "$fresh/runtime.ts";
69-
import { HandlerContext, Handlers } from "$fresh/server.ts";
68+
import { HandlerContext, Handlers, PageProps } from "$fresh/server.ts";
7069

7170
export const handler: Handlers = {
7271
async GET(ctx: HandlerContext) {

docs/getting-started/dynamic-routes.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,7 @@ as arguments in it's `props` object though.
2929

3030
/** @jsx h */
3131
import { h } from "preact";
32-
import { PageProps } from "$fresh/runtime.ts";
32+
import { PageProps } from "$fresh/server.ts";
3333

3434
export default function GreetPage(props: PageProps) {
3535
const { name } = props.params;

docs/getting-started/fetching-data.md

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -25,8 +25,7 @@ renders it in a page component.
2525

2626
/** @jsx h */
2727
import { h } from "preact";
28-
import { PageProps } from "$fresh/runtime.ts";
29-
import { Handlers } from "$fresh/server.ts";
28+
import { Handlers, PageProps } from "$fresh/server.ts";
3029

3130
interface User {
3231
login: string;

docs/getting-started/form-submissions.md

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -34,8 +34,7 @@ server side:
3434

3535
/** @jsx h */
3636
import { h } from "preact";
37-
import { PageProps } from "$fresh/runtime.ts";
38-
import { Handlers } from "$fresh/server.ts";
37+
import { Handlers, PageProps } from "$fresh/server.ts";
3938

4039
const NAMES = ["Alice", "Bob", "Charlie", "Dave", "Eve", "Frank"];
4140

init.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -166,7 +166,7 @@ await Deno.writeTextFile(
166166

167167
const ROUTES_GREET_TSX = `/** @jsx h */
168168
import { h } from "preact";
169-
import { PageProps } from "$fresh/runtime.ts";
169+
import { PageProps } from "$fresh/server.ts";
170170
171171
export default function Greet(props: PageProps) {
172172
return <div>Hello {props.params.name}</div>;

runtime.ts

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,3 @@
1-
export * from "./src/runtime/types.ts";
21
export * from "./src/runtime/utils.ts";
32
export * from "./src/runtime/head.ts";
43
export * from "./src/runtime/csp.ts";

src/runtime/types.ts

Lines changed: 0 additions & 70 deletions
This file was deleted.

src/server/context.ts

Lines changed: 44 additions & 41 deletions
Original file line numberDiff line numberDiff line change
@@ -23,17 +23,20 @@ import {
2323
Middleware,
2424
MiddlewareModule,
2525
MiddlewareRoute,
26-
Page,
27-
PageModule,
2826
RenderFunction,
29-
RouterState,
27+
Route,
28+
RouteModule,
3029
UnknownPage,
3130
UnknownPageModule,
3231
} from "./types.ts";
3332
import { render as internalRender } from "./render.tsx";
3433
import { ContentSecurityPolicyDirectives, SELF } from "../runtime/csp.ts";
3534
import { ASSET_CACHE_BUST_KEY, INTERNAL_PREFIX } from "../runtime/utils.ts";
3635

36+
interface RouterState {
37+
state: Record<string, unknown>;
38+
}
39+
3740
interface StaticFile {
3841
/** The URL to the static file on disk. */
3942
localUrl: URL;
@@ -49,7 +52,7 @@ interface StaticFile {
4952

5053
export class ServerContext {
5154
#dev: boolean;
52-
#pages: Page[];
55+
#routes: Route[];
5356
#islands: Island[];
5457
#staticFiles: StaticFile[];
5558
#bundler: Bundler;
@@ -60,7 +63,7 @@ export class ServerContext {
6063
#error: ErrorPage;
6164

6265
constructor(
63-
pages: Page[],
66+
routes: Route[],
6467
islands: Island[],
6568
staticFiles: StaticFile[],
6669
renderfn: RenderFunction,
@@ -70,7 +73,7 @@ export class ServerContext {
7073
error: ErrorPage,
7174
importMapURL: URL,
7275
) {
73-
this.#pages = pages;
76+
this.#routes = routes;
7477
this.#islands = islands;
7578
this.#staticFiles = staticFiles;
7679
this.#renderFn = renderfn;
@@ -94,7 +97,7 @@ export class ServerContext {
9497
const importMapURL = new URL("./import_map.json", manifest.baseUrl);
9598

9699
// Extract all routes, and prepare them into the `Page` structure.
97-
const pages: Page[] = [];
100+
const routes: Route[] = [];
98101
const islands: Island[] = [];
99102
const middlewares: MiddlewareRoute[] = [];
100103
let app: AppModule = DEFAULT_APP;
@@ -112,28 +115,28 @@ export class ServerContext {
112115
path.endsWith("/_middleware.ts") || path.endsWith("/_middleware.jsx") ||
113116
path.endsWith("/_middleware.js");
114117
if (!path.startsWith("/_") && !isMiddleware) {
115-
const { default: component, config } = (module as PageModule);
116-
let route = pathToRoute(baseRoute);
118+
const { default: component, config } = (module as RouteModule);
119+
let pattern = pathToPattern(baseRoute);
117120
if (config?.routeOverride) {
118-
route = String(config.routeOverride);
121+
pattern = String(config.routeOverride);
119122
}
120-
let { handler } = (module as PageModule);
123+
let { handler } = (module as RouteModule);
121124
handler ??= {};
122125
if (
123126
component &&
124127
typeof handler === "object" && handler.GET === undefined
125128
) {
126129
handler.GET = (_req, { render }) => render();
127130
}
128-
const page: Page = {
129-
route,
131+
const route: Route = {
132+
pattern,
130133
url,
131134
name,
132135
component,
133136
handler,
134137
csp: Boolean(config?.csp ?? false),
135138
};
136-
pages.push(page);
139+
routes.push(route);
137140
} else if (isMiddleware) {
138141
middlewares.push({
139142
...middlewarePathToPattern(baseRoute),
@@ -155,7 +158,7 @@ export class ServerContext {
155158
}
156159

157160
notFound = {
158-
route: pathToRoute(baseRoute),
161+
pattern: pathToPattern(baseRoute),
159162
url,
160163
name,
161164
component,
@@ -173,7 +176,7 @@ export class ServerContext {
173176
}
174177

175178
error = {
176-
route: pathToRoute(baseRoute),
179+
pattern: pathToPattern(baseRoute),
177180
url,
178181
name,
179182
component,
@@ -183,7 +186,7 @@ export class ServerContext {
183186
};
184187
}
185188
}
186-
sortRoutes(pages);
189+
sortRoutes(routes);
187190
sortRoutes(middlewares);
188191

189192
for (const [self, module] of Object.entries(manifest.islands)) {
@@ -249,7 +252,7 @@ export class ServerContext {
249252
}
250253

251254
return new ServerContext(
252-
pages,
255+
routes,
253256
islands,
254257
staticFiles,
255258
opts.render ?? DEFAULT_RENDER_FN,
@@ -266,7 +269,7 @@ export class ServerContext {
266269
* by fresh, including static files.
267270
*/
268271
handler(): RequestHandler {
269-
const inner = router.router<RouterState>(...this.#routes());
272+
const inner = router.router<RouterState>(...this.#handlers());
270273
const withMiddlewares = this.#composeMiddlewares(this.#middlewares);
271274
return function handler(req: Request, connInfo: ConnInfo) {
272275
// Redirect requests that end with a trailing slash
@@ -321,7 +324,7 @@ export class ServerContext {
321324
* This function returns all routes required by fresh as an extended
322325
* path-to-regex, to handler mapping.
323326
*/
324-
#routes(): [
327+
#handlers(): [
325328
router.Routes<RouterState>,
326329
router.Handler<RouterState>,
327330
router.ErrorHandler<RouterState>,
@@ -381,7 +384,7 @@ export class ServerContext {
381384
}
382385

383386
const genRender = <Data = undefined>(
384-
page: Page<Data> | UnknownPage | ErrorPage,
387+
route: Route<Data> | UnknownPage | ErrorPage,
385388
status: number,
386389
) => {
387390
const imports: string[] = [];
@@ -394,12 +397,12 @@ export class ServerContext {
394397
error?: unknown,
395398
) => {
396399
return async (data?: Data) => {
397-
if (page.component === undefined) {
400+
if (route.component === undefined) {
398401
throw new Error("This page does not have a component to render.");
399402
}
400403
const preloads: string[] = [];
401404
const resp = await internalRender({
402-
page,
405+
route,
403406
islands: this.#islands,
404407
app: this.#app,
405408
imports,
@@ -435,18 +438,18 @@ export class ServerContext {
435438
};
436439
};
437440

438-
for (const page of this.#pages) {
439-
const createRender = genRender(page, 200);
440-
if (typeof page.handler === "function") {
441-
routes[page.route] = (req, ctx, params) =>
442-
(page.handler as Handler)(req, {
441+
for (const route of this.#routes) {
442+
const createRender = genRender(route, 200);
443+
if (typeof route.handler === "function") {
444+
routes[route.pattern] = (req, ctx, params) =>
445+
(route.handler as Handler)(req, {
443446
...ctx,
444447
params,
445448
render: createRender(req, params),
446449
});
447450
} else {
448-
for (const [method, handler] of Object.entries(page.handler)) {
449-
routes[`${method}@${page.route}`] = (req, ctx, params) =>
451+
for (const [method, handler] of Object.entries(route.handler)) {
452+
routes[`${method}@${route.pattern}`] = (req, ctx, params) =>
450453
handler(req, {
451454
...ctx,
452455
params,
@@ -573,15 +576,15 @@ const DEFAULT_APP: AppModule = {
573576
};
574577

575578
const DEFAULT_NOT_FOUND: UnknownPage = {
576-
route: "",
579+
pattern: "",
577580
url: "",
578581
name: "_404",
579582
handler: (req) => router.defaultOtherHandler(req),
580583
csp: false,
581584
};
582585

583586
const DEFAULT_ERROR: ErrorPage = {
584-
route: "",
587+
pattern: "",
585588
url: "",
586589
name: "_500",
587590
component: DefaultErrorHandler,
@@ -598,8 +601,8 @@ export function selectMiddlewares(url: string, middlewares: MiddlewareRoute[]) {
598601
const selectedMws: Middleware[] = [];
599602
const reqURL = new URL(url);
600603

601-
for (const { pattern, handler } of middlewares) {
602-
const res = pattern.exec(reqURL);
604+
for (const { compiledPattern, handler } of middlewares) {
605+
const res = compiledPattern.exec(reqURL);
603606
if (res) {
604607
selectedMws.push({ handler });
605608
}
@@ -612,10 +615,10 @@ export function selectMiddlewares(url: string, middlewares: MiddlewareRoute[]) {
612615
* Sort pages by their relative routing priority, based on the parts in the
613616
* route matcher
614617
*/
615-
function sortRoutes<T extends { route: string }>(routes: T[]) {
618+
function sortRoutes<T extends { pattern: string }>(routes: T[]) {
616619
routes.sort((a, b) => {
617-
const partsA = a.route.split("/");
618-
const partsB = b.route.split("/");
620+
const partsA = a.pattern.split("/");
621+
const partsB = b.pattern.split("/");
619622
for (let i = 0; i < Math.max(partsA.length, partsB.length); i++) {
620623
const partA = partsA[i];
621624
const partB = partsB[i];
@@ -631,7 +634,7 @@ function sortRoutes<T extends { route: string }>(routes: T[]) {
631634
}
632635

633636
/** Transform a filesystem URL path to a `path-to-regex` style matcher. */
634-
function pathToRoute(path: string): string {
637+
function pathToPattern(path: string): string {
635638
const parts = path.split("/");
636639
if (parts[parts.length - 1] === "index") {
637640
parts.pop();
@@ -687,7 +690,7 @@ function serializeCSPDirectives(csp: ContentSecurityPolicyDirectives): string {
687690

688691
export function middlewarePathToPattern(baseRoute: string) {
689692
baseRoute = baseRoute.slice(0, -"_middleware".length);
690-
const regRoute = pathToRoute(baseRoute);
691-
const pattern = new URLPattern({ pathname: `${regRoute}*` });
692-
return { route: regRoute, pattern };
693+
const pattern = pathToPattern(baseRoute);
694+
const compiledPattern = new URLPattern({ pathname: `${pattern}*` });
695+
return { pattern, compiledPattern };
693696
}

0 commit comments

Comments
 (0)