Router cleanup (#2099)
This commit is contained in:
+32
-58
@@ -2,10 +2,8 @@ import { SEP } from "./deps.ts";
|
|||||||
import { ErrorHandler, FinalHandler, RouteResult } from "./router.ts";
|
import { ErrorHandler, FinalHandler, RouteResult } from "./router.ts";
|
||||||
import {
|
import {
|
||||||
BaseRoute,
|
BaseRoute,
|
||||||
MiddlewareHandlerContext,
|
FreshContext,
|
||||||
MiddlewareRoute,
|
MiddlewareRoute,
|
||||||
RouterState,
|
|
||||||
ServeHandlerInfo,
|
|
||||||
UnknownRenderFunction,
|
UnknownRenderFunction,
|
||||||
} from "./types.ts";
|
} from "./types.ts";
|
||||||
|
|
||||||
@@ -56,20 +54,20 @@ export function selectSharedRoutes<T extends { baseRoute: BaseRoute }>(
|
|||||||
*/
|
*/
|
||||||
export function composeMiddlewares(
|
export function composeMiddlewares(
|
||||||
middlewares: MiddlewareRoute[],
|
middlewares: MiddlewareRoute[],
|
||||||
errorHandler: ErrorHandler<RouterState>,
|
errorHandler: ErrorHandler,
|
||||||
paramsAndRoute: (
|
paramsAndRoute: (
|
||||||
url: string,
|
url: string,
|
||||||
) => RouteResult<RouterState>,
|
) => RouteResult,
|
||||||
renderNotFound: UnknownRenderFunction,
|
renderNotFound: UnknownRenderFunction,
|
||||||
basePath: string,
|
|
||||||
) {
|
) {
|
||||||
return (
|
return (
|
||||||
req: Request,
|
req: Request,
|
||||||
connInfo: ServeHandlerInfo,
|
ctx: FreshContext,
|
||||||
inner: FinalHandler<RouterState>,
|
inner: FinalHandler,
|
||||||
) => {
|
) => {
|
||||||
const handlers: (() => Response | Promise<Response>)[] = [];
|
const handlers: (() => Response | Promise<Response>)[] = [];
|
||||||
const paramsAndRouteResult = paramsAndRoute(req.url);
|
const paramsAndRouteResult = paramsAndRoute(req.url);
|
||||||
|
ctx.params = paramsAndRouteResult.params;
|
||||||
|
|
||||||
// identify middlewares to apply, if any.
|
// identify middlewares to apply, if any.
|
||||||
// middlewares should be already sorted from deepest to shallow layer
|
// middlewares should be already sorted from deepest to shallow layer
|
||||||
@@ -78,73 +76,49 @@ export function composeMiddlewares(
|
|||||||
middlewares,
|
middlewares,
|
||||||
);
|
);
|
||||||
|
|
||||||
let state: Record<string, unknown> = {};
|
if (paramsAndRouteResult.route) {
|
||||||
const middlewareCtx: MiddlewareHandlerContext = {
|
ctx.route = paramsAndRouteResult.route.originalPattern;
|
||||||
next() {
|
}
|
||||||
const handler = handlers.shift()!;
|
|
||||||
try {
|
ctx.next = () => {
|
||||||
// As the `handler` can be either sync or async, depending on the user's code,
|
const handler = handlers.shift()!;
|
||||||
// the current shape of our wrapper, that is `() => handler(req, middlewareCtx)`,
|
try {
|
||||||
// doesn't guarantee that all possible errors will be captured.
|
// As the `handler` can be either sync or async, depending on the user's code,
|
||||||
// `Promise.resolve` accept the value that should be returned to the promise
|
// the current shape of our wrapper, that is `() => handler(req, middlewareCtx)`,
|
||||||
// chain, however, if that value is produced by the external function call,
|
// doesn't guarantee that all possible errors will be captured.
|
||||||
// the possible `Error`, will *not* be caught by any `.catch()` attached to that chain.
|
// `Promise.resolve` accept the value that should be returned to the promise
|
||||||
// Because of that, we need to make sure that the produced value is pushed
|
// chain, however, if that value is produced by the external function call,
|
||||||
// through the pipeline only if function was called successfully, and handle
|
// the possible `Error`, will *not* be caught by any `.catch()` attached to that chain.
|
||||||
// the error case manually, by returning the `Error` as rejected promise.
|
// Because of that, we need to make sure that the produced value is pushed
|
||||||
return Promise.resolve(handler());
|
// through the pipeline only if function was called successfully, and handle
|
||||||
} catch (e) {
|
// the error case manually, by returning the `Error` as rejected promise.
|
||||||
if (e instanceof Deno.errors.NotFound) {
|
return Promise.resolve(handler());
|
||||||
return renderNotFound(req, paramsAndRouteResult.params, ctx);
|
} catch (e) {
|
||||||
}
|
if (e instanceof Deno.errors.NotFound) {
|
||||||
return Promise.reject(e);
|
return renderNotFound(req, ctx);
|
||||||
}
|
}
|
||||||
},
|
return Promise.reject(e);
|
||||||
...connInfo,
|
}
|
||||||
get state() {
|
|
||||||
return state;
|
|
||||||
},
|
|
||||||
set state(v) {
|
|
||||||
state = v;
|
|
||||||
},
|
|
||||||
destination: "route",
|
|
||||||
params: paramsAndRouteResult.params,
|
|
||||||
renderNotFound: async () => {
|
|
||||||
return await renderNotFound(req, paramsAndRouteResult.params, ctx);
|
|
||||||
},
|
|
||||||
isPartial: paramsAndRouteResult.isPartial,
|
|
||||||
basePath,
|
|
||||||
};
|
};
|
||||||
|
|
||||||
for (const { module } of mws) {
|
for (const { module } of mws) {
|
||||||
if (module.handler instanceof Array) {
|
if (module.handler instanceof Array) {
|
||||||
for (const handler of module.handler) {
|
for (const handler of module.handler) {
|
||||||
handlers.push(() => handler(req, middlewareCtx));
|
handlers.push(() => handler(req, ctx));
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
const handler = module.handler;
|
const handler = module.handler;
|
||||||
handlers.push(() => handler(req, middlewareCtx));
|
handlers.push(() => handler(req, ctx));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const ctx = {
|
|
||||||
...connInfo,
|
|
||||||
get state() {
|
|
||||||
return state;
|
|
||||||
},
|
|
||||||
set state(v) {
|
|
||||||
state = v;
|
|
||||||
},
|
|
||||||
isPartial: paramsAndRouteResult.isPartial,
|
|
||||||
};
|
|
||||||
const { destination, handler } = inner(
|
const { destination, handler } = inner(
|
||||||
req,
|
req,
|
||||||
ctx,
|
ctx,
|
||||||
paramsAndRouteResult.params,
|
|
||||||
paramsAndRouteResult.route,
|
paramsAndRouteResult.route,
|
||||||
);
|
);
|
||||||
handlers.push(handler);
|
handlers.push(handler);
|
||||||
middlewareCtx.destination = destination;
|
ctx.destination = destination;
|
||||||
return middlewareCtx.next().catch((e) => errorHandler(req, ctx, e));
|
return ctx.next().catch((e) => errorHandler(req, ctx, e));
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|||||||
+84
-124
@@ -1,6 +1,6 @@
|
|||||||
import { contentType, extname, SEP, STATUS_CODE } from "./deps.ts";
|
import { contentType, extname, SEP, STATUS_CODE } from "./deps.ts";
|
||||||
import * as router from "./router.ts";
|
import * as router from "./router.ts";
|
||||||
import { FreshConfig, Manifest, UnknownHandlerContext } from "./mod.ts";
|
import { FreshConfig, FreshContext, Manifest } from "./mod.ts";
|
||||||
import {
|
import {
|
||||||
ALIVE_URL,
|
ALIVE_URL,
|
||||||
DEV_CLIENT_URL,
|
DEV_CLIENT_URL,
|
||||||
@@ -18,7 +18,6 @@ import {
|
|||||||
RenderFunction,
|
RenderFunction,
|
||||||
RenderOptions,
|
RenderOptions,
|
||||||
Route,
|
Route,
|
||||||
RouterState,
|
|
||||||
ServeHandlerInfo,
|
ServeHandlerInfo,
|
||||||
UnknownPage,
|
UnknownPage,
|
||||||
UnknownRenderFunction,
|
UnknownRenderFunction,
|
||||||
@@ -44,12 +43,17 @@ import { extractRoutes, FsExtractResult } from "./fs_extract.ts";
|
|||||||
import { loadAotSnapshot } from "../build/aot_snapshot.ts";
|
import { loadAotSnapshot } from "../build/aot_snapshot.ts";
|
||||||
import { ErrorOverlay } from "./error_overlay.tsx";
|
import { ErrorOverlay } from "./error_overlay.tsx";
|
||||||
import { withBase } from "./router.ts";
|
import { withBase } from "./router.ts";
|
||||||
|
import { PARTIAL_SEARCH_PARAM } from "../constants.ts";
|
||||||
|
|
||||||
const DEFAULT_CONN_INFO: ServeHandlerInfo = {
|
const DEFAULT_CONN_INFO: ServeHandlerInfo = {
|
||||||
localAddr: { transport: "tcp", hostname: "localhost", port: 8080 },
|
localAddr: { transport: "tcp", hostname: "localhost", port: 8080 },
|
||||||
remoteAddr: { transport: "tcp", hostname: "localhost", port: 1234 },
|
remoteAddr: { transport: "tcp", hostname: "localhost", port: 1234 },
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// deno-lint-ignore no-explicit-any
|
||||||
|
const NOOP_COMPONENT = () => null as any;
|
||||||
|
const NOOP_NEXT = () => Promise.resolve(new Response(null, { status: 500 }));
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @deprecated Use {@linkcode FromManifestConfig} instead
|
* @deprecated Use {@linkcode FromManifestConfig} instead
|
||||||
*/
|
*/
|
||||||
@@ -154,20 +158,17 @@ export class ServerContext {
|
|||||||
this.#plugins,
|
this.#plugins,
|
||||||
this.#renderFn,
|
this.#renderFn,
|
||||||
this.#maybeBuildSnapshot(),
|
this.#maybeBuildSnapshot(),
|
||||||
basePath,
|
|
||||||
);
|
);
|
||||||
const handlers = this.#handlers(renderNotFound);
|
const handlers = this.#handlers(renderNotFound);
|
||||||
const inner = router.router<RouterState>(handlers);
|
const inner = router.router(handlers);
|
||||||
const withMiddlewares = composeMiddlewares(
|
const withMiddlewares = composeMiddlewares(
|
||||||
this.#extractResult.middlewares,
|
this.#extractResult.middlewares,
|
||||||
handlers.errorHandler,
|
handlers.errorHandler,
|
||||||
router.getParamsAndRoute<RouterState>(handlers),
|
router.getParamsAndRoute(handlers),
|
||||||
renderNotFound,
|
renderNotFound,
|
||||||
basePath,
|
|
||||||
);
|
);
|
||||||
const trailingSlashEnabled = this.#state.config.router?.trailingSlash;
|
const trailingSlashEnabled = this.#state.config.router?.trailingSlash;
|
||||||
const isDev = this.#dev;
|
const isDev = this.#dev;
|
||||||
const bundleAssetRoute = this.#bundleAssetRoute();
|
|
||||||
|
|
||||||
if (this.#dev) {
|
if (this.#dev) {
|
||||||
this.#revision = Date.now();
|
this.#revision = Date.now();
|
||||||
@@ -215,9 +216,8 @@ export class ServerContext {
|
|||||||
const bundlePath = (url.pathname.endsWith(".map"))
|
const bundlePath = (url.pathname.endsWith(".map"))
|
||||||
? "fresh_dev_client.js.map"
|
? "fresh_dev_client.js.map"
|
||||||
: "fresh_dev_client.js";
|
: "fresh_dev_client.js";
|
||||||
return bundleAssetRoute(req, { ...connInfo, isPartial: false }, {
|
|
||||||
path: bundlePath,
|
return _self.#bundleAssetRoute(bundlePath);
|
||||||
});
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -254,7 +254,28 @@ export class ServerContext {
|
|||||||
return Response.redirect(to, 302);
|
return Response.redirect(to, 302);
|
||||||
}
|
}
|
||||||
|
|
||||||
return await withMiddlewares(req, connInfo, inner);
|
const ctx: FreshContext = {
|
||||||
|
url,
|
||||||
|
params: {},
|
||||||
|
basePath: _self.#state.config.basePath,
|
||||||
|
localAddr: connInfo.localAddr,
|
||||||
|
remoteAddr: connInfo.remoteAddr,
|
||||||
|
state: {},
|
||||||
|
isPartial: url.searchParams.has(PARTIAL_SEARCH_PARAM),
|
||||||
|
destination: "route",
|
||||||
|
error: undefined,
|
||||||
|
Component: NOOP_COMPONENT,
|
||||||
|
next: NOOP_NEXT,
|
||||||
|
render: NOOP_NEXT,
|
||||||
|
renderNotFound: async (data) => {
|
||||||
|
ctx.data = data;
|
||||||
|
return await renderNotFound(req, ctx);
|
||||||
|
},
|
||||||
|
route: "",
|
||||||
|
data: undefined,
|
||||||
|
};
|
||||||
|
|
||||||
|
return await withMiddlewares(req, ctx, inner);
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -287,16 +308,16 @@ export class ServerContext {
|
|||||||
#handlers(
|
#handlers(
|
||||||
renderNotFound: UnknownRenderFunction,
|
renderNotFound: UnknownRenderFunction,
|
||||||
): {
|
): {
|
||||||
internalRoutes: router.Routes<RouterState>;
|
internalRoutes: router.Routes;
|
||||||
staticRoutes: router.Routes<RouterState>;
|
staticRoutes: router.Routes;
|
||||||
routes: router.Routes<RouterState>;
|
routes: router.Routes;
|
||||||
|
|
||||||
otherHandler: router.Handler<RouterState>;
|
otherHandler: router.Handler;
|
||||||
errorHandler: router.ErrorHandler<RouterState>;
|
errorHandler: router.ErrorHandler;
|
||||||
} {
|
} {
|
||||||
const internalRoutes: router.Routes<RouterState> = {};
|
const internalRoutes: router.Routes = {};
|
||||||
const staticRoutes: router.Routes<RouterState> = {};
|
const staticRoutes: router.Routes = {};
|
||||||
const routes: router.Routes<RouterState> = {};
|
const routes: router.Routes = {};
|
||||||
|
|
||||||
const assetRoute = withBase(
|
const assetRoute = withBase(
|
||||||
`${INTERNAL_PREFIX}${JS_PREFIX}/${BUILD_ID}/:path*`,
|
`${INTERNAL_PREFIX}${JS_PREFIX}/${BUILD_ID}/:path*`,
|
||||||
@@ -305,7 +326,7 @@ export class ServerContext {
|
|||||||
internalRoutes[assetRoute] = {
|
internalRoutes[assetRoute] = {
|
||||||
baseRoute: toBaseRoute(assetRoute),
|
baseRoute: toBaseRoute(assetRoute),
|
||||||
methods: {
|
methods: {
|
||||||
default: this.#bundleAssetRoute(),
|
default: (_req, ctx) => this.#bundleAssetRoute(ctx.params.path),
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -352,9 +373,7 @@ export class ServerContext {
|
|||||||
if (this.#dev) imports.push(this.#state.config.basePath + DEV_CLIENT_URL);
|
if (this.#dev) imports.push(this.#state.config.basePath + DEV_CLIENT_URL);
|
||||||
return (
|
return (
|
||||||
req: Request,
|
req: Request,
|
||||||
params: Record<string, string>,
|
ctx: FreshContext,
|
||||||
// deno-lint-ignore no-explicit-any
|
|
||||||
ctx?: any,
|
|
||||||
error?: unknown,
|
error?: unknown,
|
||||||
codeFrame?: string,
|
codeFrame?: string,
|
||||||
) => {
|
) => {
|
||||||
@@ -367,14 +386,11 @@ export class ServerContext {
|
|||||||
this.#extractResult.layouts,
|
this.#extractResult.layouts,
|
||||||
);
|
);
|
||||||
|
|
||||||
|
ctx.error = error;
|
||||||
|
ctx.data = data;
|
||||||
const resp = await internalRender({
|
const resp = await internalRender({
|
||||||
request: req,
|
request: req,
|
||||||
context: {
|
context: ctx,
|
||||||
...ctx,
|
|
||||||
async renderNotFound() {
|
|
||||||
return await renderNotFound(req, params, ctx, data, error);
|
|
||||||
},
|
|
||||||
},
|
|
||||||
route,
|
route,
|
||||||
plugins: this.#plugins,
|
plugins: this.#plugins,
|
||||||
app: this.#extractResult.app,
|
app: this.#extractResult.app,
|
||||||
@@ -382,13 +398,7 @@ export class ServerContext {
|
|||||||
imports,
|
imports,
|
||||||
dependenciesFn,
|
dependenciesFn,
|
||||||
renderFn: this.#renderFn,
|
renderFn: this.#renderFn,
|
||||||
url: new URL(req.url),
|
|
||||||
params,
|
|
||||||
data,
|
|
||||||
state: ctx?.state,
|
|
||||||
error,
|
|
||||||
codeFrame,
|
codeFrame,
|
||||||
basePath: this.#state.config.basePath,
|
|
||||||
});
|
});
|
||||||
|
|
||||||
if (resp instanceof Response) {
|
if (resp instanceof Response) {
|
||||||
@@ -416,16 +426,10 @@ export class ServerContext {
|
|||||||
routes[route.pattern] = {
|
routes[route.pattern] = {
|
||||||
baseRoute: route.baseRoute,
|
baseRoute: route.baseRoute,
|
||||||
methods: {
|
methods: {
|
||||||
default: (req, ctx, params) =>
|
default: (req, ctx) => {
|
||||||
(route.handler as Handler)(req, {
|
ctx.render = createRender(req, ctx);
|
||||||
...ctx,
|
return (route.handler as Handler)(req, ctx);
|
||||||
params,
|
},
|
||||||
render: createRender(req, params, ctx),
|
|
||||||
async renderNotFound<Data = undefined>(data: Data) {
|
|
||||||
return await renderNotFound(req, params, ctx, data);
|
|
||||||
},
|
|
||||||
basePath: this.#state.config.basePath,
|
|
||||||
}),
|
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
} else {
|
} else {
|
||||||
@@ -437,40 +441,27 @@ export class ServerContext {
|
|||||||
routes[route.pattern].methods[method as router.KnownMethod] = (
|
routes[route.pattern].methods[method as router.KnownMethod] = (
|
||||||
req,
|
req,
|
||||||
ctx,
|
ctx,
|
||||||
params,
|
) => {
|
||||||
) =>
|
ctx.render = createRender(req, ctx);
|
||||||
handler(req, {
|
return handler(req, ctx);
|
||||||
...ctx,
|
};
|
||||||
params,
|
|
||||||
render: createRender(req, params, ctx),
|
|
||||||
async renderNotFound<Data = undefined>(data: Data) {
|
|
||||||
return await renderNotFound(req, params, ctx, data);
|
|
||||||
},
|
|
||||||
basePath: this.#state.config.basePath,
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const otherHandler: router.Handler<RouterState> = (
|
const otherHandler: router.Handler = (req, ctx) => {
|
||||||
req,
|
ctx.render = (data) => {
|
||||||
ctx,
|
ctx.data = data;
|
||||||
) =>
|
return renderNotFound(req, ctx);
|
||||||
this.#extractResult.notFound.handler(
|
};
|
||||||
req,
|
return this.#extractResult.notFound.handler(req, ctx);
|
||||||
{
|
};
|
||||||
...ctx,
|
|
||||||
render() {
|
|
||||||
return renderNotFound(req, {}, ctx);
|
|
||||||
},
|
|
||||||
},
|
|
||||||
);
|
|
||||||
|
|
||||||
const errorHandlerRender = genRender(
|
const errorHandlerRender = genRender(
|
||||||
this.#extractResult.error,
|
this.#extractResult.error,
|
||||||
STATUS_CODE.InternalServerError,
|
STATUS_CODE.InternalServerError,
|
||||||
);
|
);
|
||||||
const errorHandler: router.ErrorHandler<RouterState> = async (
|
const errorHandler: router.ErrorHandler = async (
|
||||||
req,
|
req,
|
||||||
ctx,
|
ctx,
|
||||||
error,
|
error,
|
||||||
@@ -490,14 +481,9 @@ export class ServerContext {
|
|||||||
}
|
}
|
||||||
console.error(error);
|
console.error(error);
|
||||||
|
|
||||||
return this.#extractResult.error.handler(
|
ctx.error = error;
|
||||||
req,
|
ctx.render = errorHandlerRender(req, ctx, error, codeFrame);
|
||||||
{
|
return this.#extractResult.error.handler(req, ctx);
|
||||||
...ctx,
|
|
||||||
error,
|
|
||||||
render: errorHandlerRender(req, {}, ctx, error, codeFrame),
|
|
||||||
},
|
|
||||||
);
|
|
||||||
};
|
};
|
||||||
|
|
||||||
if (this.#dev) {
|
if (this.#dev) {
|
||||||
@@ -520,8 +506,7 @@ export class ServerContext {
|
|||||||
csp: false,
|
csp: false,
|
||||||
url: req.url,
|
url: req.url,
|
||||||
name: "error overlay route",
|
name: "error overlay route",
|
||||||
handler: (_req: Request, ctx: UnknownHandlerContext) =>
|
handler: (_req: Request, ctx: FreshContext) => ctx.render(),
|
||||||
ctx.render(),
|
|
||||||
baseRoute,
|
baseRoute,
|
||||||
pattern: baseRoute,
|
pattern: baseRoute,
|
||||||
},
|
},
|
||||||
@@ -531,16 +516,7 @@ export class ServerContext {
|
|||||||
imports: [],
|
imports: [],
|
||||||
dependenciesFn: () => [],
|
dependenciesFn: () => [],
|
||||||
renderFn: this.#renderFn,
|
renderFn: this.#renderFn,
|
||||||
url: new URL(req.url),
|
|
||||||
params: {},
|
|
||||||
data: undefined,
|
|
||||||
state: {
|
|
||||||
...ctx?.state,
|
|
||||||
error: null,
|
|
||||||
},
|
|
||||||
error: null,
|
|
||||||
codeFrame: undefined,
|
codeFrame: undefined,
|
||||||
basePath: this.#state.config.basePath,
|
|
||||||
});
|
});
|
||||||
|
|
||||||
if (resp instanceof Response) {
|
if (resp instanceof Response) {
|
||||||
@@ -602,31 +578,25 @@ export class ServerContext {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
async #bundleAssetRoute(filePath: string) {
|
||||||
* Returns a router that contains all Fresh routes. Should be mounted at
|
const snapshot = await this.buildSnapshot();
|
||||||
* constants.INTERNAL_PREFIX
|
const contents = await snapshot.read(filePath);
|
||||||
*/
|
if (!contents) return new Response(null, { status: 404 });
|
||||||
#bundleAssetRoute = (): router.MatchHandler => {
|
|
||||||
return async (_req, _ctx, params) => {
|
|
||||||
const snapshot = await this.buildSnapshot();
|
|
||||||
const contents = await snapshot.read(params.path);
|
|
||||||
if (!contents) return new Response(null, { status: 404 });
|
|
||||||
|
|
||||||
const headers: Record<string, string> = {
|
const headers: Record<string, string> = {
|
||||||
"Cache-Control": this.#dev
|
"Cache-Control": this.#dev
|
||||||
? "no-cache, no-store, max-age=0, must-revalidate"
|
? "no-cache, no-store, max-age=0, must-revalidate"
|
||||||
: "public, max-age=604800, immutable",
|
: "public, max-age=604800, immutable",
|
||||||
};
|
|
||||||
|
|
||||||
const type = contentType(extname(params.path));
|
|
||||||
if (type) headers["Content-Type"] = type;
|
|
||||||
|
|
||||||
return new Response(contents, {
|
|
||||||
status: 200,
|
|
||||||
headers,
|
|
||||||
});
|
|
||||||
};
|
};
|
||||||
};
|
|
||||||
|
const type = contentType(extname(filePath));
|
||||||
|
if (type) headers["Content-Type"] = type;
|
||||||
|
|
||||||
|
return new Response(contents, {
|
||||||
|
status: 200,
|
||||||
|
headers,
|
||||||
|
});
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const createRenderNotFound = (
|
const createRenderNotFound = (
|
||||||
@@ -635,17 +605,13 @@ const createRenderNotFound = (
|
|||||||
plugins: Plugin<Record<string, unknown>>[],
|
plugins: Plugin<Record<string, unknown>>[],
|
||||||
renderFunction: RenderFunction,
|
renderFunction: RenderFunction,
|
||||||
buildSnapshot: BuildSnapshot | null,
|
buildSnapshot: BuildSnapshot | null,
|
||||||
basePath: string,
|
): UnknownRenderFunction => {
|
||||||
) => {
|
|
||||||
const dependenciesFn = (path: string) => {
|
const dependenciesFn = (path: string) => {
|
||||||
const snapshot = buildSnapshot;
|
const snapshot = buildSnapshot;
|
||||||
return snapshot?.dependencies(path) ?? [];
|
return snapshot?.dependencies(path) ?? [];
|
||||||
};
|
};
|
||||||
|
|
||||||
return async (
|
return async (req, ctx) => {
|
||||||
...args: Parameters<UnknownRenderFunction>
|
|
||||||
) => {
|
|
||||||
const [req, params, ctx, data, error] = args;
|
|
||||||
const notFound = extractResult.notFound;
|
const notFound = extractResult.notFound;
|
||||||
if (!notFound.component) {
|
if (!notFound.component) {
|
||||||
return sendResponse(["Not found.", undefined], {
|
return sendResponse(["Not found.", undefined], {
|
||||||
@@ -672,12 +638,6 @@ const createRenderNotFound = (
|
|||||||
imports,
|
imports,
|
||||||
dependenciesFn,
|
dependenciesFn,
|
||||||
renderFn: renderFunction,
|
renderFn: renderFunction,
|
||||||
url: new URL(req.url),
|
|
||||||
params,
|
|
||||||
data,
|
|
||||||
state: ctx?.state,
|
|
||||||
error,
|
|
||||||
basePath,
|
|
||||||
});
|
});
|
||||||
|
|
||||||
if (resp instanceof Response) {
|
if (resp instanceof Response) {
|
||||||
|
|||||||
+3
-10
@@ -1,12 +1,5 @@
|
|||||||
import { ComponentChildren } from "preact";
|
import { ComponentChildren } from "preact";
|
||||||
import {
|
import { AsyncLayout, AsyncRoute, FreshConfig, RouteContext } from "./types.ts";
|
||||||
AppContext,
|
|
||||||
AsyncLayout,
|
|
||||||
AsyncRoute,
|
|
||||||
FreshConfig,
|
|
||||||
LayoutContext,
|
|
||||||
RouteContext,
|
|
||||||
} from "./types.ts";
|
|
||||||
import { checkAsyncComponent } from "./render.ts";
|
import { checkAsyncComponent } from "./render.ts";
|
||||||
|
|
||||||
export function defineConfig(config: FreshConfig): FreshConfig {
|
export function defineConfig(config: FreshConfig): FreshConfig {
|
||||||
@@ -32,7 +25,7 @@ export function defineRoute<
|
|||||||
export function defineLayout<T>(
|
export function defineLayout<T>(
|
||||||
fn: (
|
fn: (
|
||||||
req: Request,
|
req: Request,
|
||||||
ctx: LayoutContext<void, T>,
|
ctx: RouteContext<void, T>,
|
||||||
) => ComponentChildren | Response | Promise<ComponentChildren | Response>,
|
) => ComponentChildren | Response | Promise<ComponentChildren | Response>,
|
||||||
): AsyncLayout<void, T> {
|
): AsyncLayout<void, T> {
|
||||||
// deno-lint-ignore no-explicit-any
|
// deno-lint-ignore no-explicit-any
|
||||||
@@ -45,7 +38,7 @@ export function defineLayout<T>(
|
|||||||
export function defineApp<T>(
|
export function defineApp<T>(
|
||||||
fn: (
|
fn: (
|
||||||
req: Request,
|
req: Request,
|
||||||
ctx: AppContext<void, T>,
|
ctx: RouteContext<void, T>,
|
||||||
) => ComponentChildren | Response | Promise<ComponentChildren | Response>,
|
) => ComponentChildren | Response | Promise<ComponentChildren | Response>,
|
||||||
): AsyncLayout<void, T> {
|
): AsyncLayout<void, T> {
|
||||||
// deno-lint-ignore no-explicit-any
|
// deno-lint-ignore no-explicit-any
|
||||||
|
|||||||
@@ -28,6 +28,7 @@ export type {
|
|||||||
ErrorHandlerContext,
|
ErrorHandlerContext,
|
||||||
ErrorPageProps,
|
ErrorPageProps,
|
||||||
FreshConfig,
|
FreshConfig,
|
||||||
|
FreshContext,
|
||||||
FreshOptions,
|
FreshOptions,
|
||||||
Handler,
|
Handler,
|
||||||
HandlerContext,
|
HandlerContext,
|
||||||
|
|||||||
+25
-40
@@ -4,13 +4,13 @@ import {
|
|||||||
AsyncLayout,
|
AsyncLayout,
|
||||||
AsyncRoute,
|
AsyncRoute,
|
||||||
ErrorPage,
|
ErrorPage,
|
||||||
|
FreshContext,
|
||||||
LayoutRoute,
|
LayoutRoute,
|
||||||
Plugin,
|
Plugin,
|
||||||
PluginRenderFunctionResult,
|
PluginRenderFunctionResult,
|
||||||
PluginRenderResult,
|
PluginRenderResult,
|
||||||
RenderFunction,
|
RenderFunction,
|
||||||
Route,
|
Route,
|
||||||
RouteContext,
|
|
||||||
UnknownPage,
|
UnknownPage,
|
||||||
} from "./types.ts";
|
} from "./types.ts";
|
||||||
import { NONE, UNSAFE_INLINE } from "../runtime/csp.ts";
|
import { NONE, UNSAFE_INLINE } from "../runtime/csp.ts";
|
||||||
@@ -28,23 +28,16 @@ export const DEFAULT_RENDER_FN: RenderFunction = (_ctx, render) => {
|
|||||||
|
|
||||||
export interface RenderOptions<Data> {
|
export interface RenderOptions<Data> {
|
||||||
request: Request;
|
request: Request;
|
||||||
// deno-lint-ignore no-explicit-any
|
context: FreshContext;
|
||||||
context: any;
|
|
||||||
route: Route<Data> | UnknownPage | ErrorPage;
|
route: Route<Data> | UnknownPage | ErrorPage;
|
||||||
plugins: Plugin[];
|
plugins: Plugin[];
|
||||||
app: AppModule;
|
app: AppModule;
|
||||||
layouts: LayoutRoute[];
|
layouts: LayoutRoute[];
|
||||||
imports: string[];
|
imports: string[];
|
||||||
dependenciesFn: (path: string) => string[];
|
dependenciesFn: (path: string) => string[];
|
||||||
url: URL;
|
|
||||||
params: Record<string, string | string[]>;
|
|
||||||
renderFn: RenderFunction;
|
renderFn: RenderFunction;
|
||||||
data?: Data;
|
|
||||||
state?: Record<string, unknown>;
|
|
||||||
error?: unknown;
|
|
||||||
codeFrame?: string;
|
codeFrame?: string;
|
||||||
lang?: string;
|
lang?: string;
|
||||||
basePath: string;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export type InnerRenderFunction = () => string;
|
export type InnerRenderFunction = () => string;
|
||||||
@@ -148,15 +141,17 @@ export async function render<Data>(
|
|||||||
layouts = [];
|
layouts = [];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const { params, data, state, error, url, basePath } = opts.context;
|
||||||
|
|
||||||
const props: Record<string, unknown> = {
|
const props: Record<string, unknown> = {
|
||||||
params: opts.params,
|
params,
|
||||||
url: opts.url,
|
url,
|
||||||
route: opts.route.pattern,
|
route: opts.route.pattern,
|
||||||
data: opts.data,
|
data,
|
||||||
state: opts.state,
|
state,
|
||||||
};
|
};
|
||||||
if (opts.error) {
|
if (error) {
|
||||||
props.error = opts.error;
|
props.error = error;
|
||||||
}
|
}
|
||||||
if (opts.codeFrame) {
|
if (opts.codeFrame) {
|
||||||
props.codeFrame = opts.codeFrame;
|
props.codeFrame = opts.codeFrame;
|
||||||
@@ -174,22 +169,12 @@ export async function render<Data>(
|
|||||||
|
|
||||||
const ctx = new RenderContext(
|
const ctx = new RenderContext(
|
||||||
crypto.randomUUID(),
|
crypto.randomUUID(),
|
||||||
opts.url,
|
url,
|
||||||
opts.route.pattern,
|
opts.route.pattern,
|
||||||
opts.lang ?? "en",
|
opts.lang ?? "en",
|
||||||
);
|
);
|
||||||
|
|
||||||
const context: RouteContext = {
|
const context = opts.context;
|
||||||
localAddr: opts.context.localAddr,
|
|
||||||
remoteAddr: opts.context.remoteAddr,
|
|
||||||
renderNotFound: opts.context.renderNotFound,
|
|
||||||
url: opts.url,
|
|
||||||
route: opts.route.pattern,
|
|
||||||
params: opts.params as Record<string, string>,
|
|
||||||
state: opts.state ?? {},
|
|
||||||
data: opts.data,
|
|
||||||
isPartial: opts.context.isPartial,
|
|
||||||
};
|
|
||||||
|
|
||||||
// Prepare render order
|
// Prepare render order
|
||||||
// deno-lint-ignore no-explicit-any
|
// deno-lint-ignore no-explicit-any
|
||||||
@@ -253,16 +238,16 @@ export async function render<Data>(
|
|||||||
// data.
|
// data.
|
||||||
const renderState = new RenderState(
|
const renderState = new RenderState(
|
||||||
{
|
{
|
||||||
url: opts.url,
|
url,
|
||||||
route: opts.route.pattern,
|
route: opts.route.pattern,
|
||||||
data: opts.data,
|
data,
|
||||||
state: opts.state,
|
state,
|
||||||
params: opts.params,
|
params,
|
||||||
basePath: opts.basePath,
|
basePath,
|
||||||
},
|
},
|
||||||
componentStack,
|
componentStack,
|
||||||
csp,
|
csp,
|
||||||
opts.error,
|
error,
|
||||||
);
|
);
|
||||||
|
|
||||||
let bodyHtml: string | null = null;
|
let bodyHtml: string | null = null;
|
||||||
@@ -370,20 +355,20 @@ export async function render<Data>(
|
|||||||
});
|
});
|
||||||
|
|
||||||
// Append error overlay
|
// Append error overlay
|
||||||
const devErrorUrl = withBase(DEV_ERROR_OVERLAY_URL, opts.basePath);
|
const devErrorUrl = withBase(DEV_ERROR_OVERLAY_URL, basePath);
|
||||||
if (opts.error !== undefined && opts.url.pathname !== devErrorUrl) {
|
if (error !== undefined && url.pathname !== devErrorUrl) {
|
||||||
const url = new URL(devErrorUrl, "https://localhost/");
|
const url = new URL(devErrorUrl, "https://localhost/");
|
||||||
if (opts.error instanceof Error) {
|
if (error instanceof Error) {
|
||||||
let message = opts.error.message;
|
let message = error.message;
|
||||||
const idx = message.indexOf("\n");
|
const idx = message.indexOf("\n");
|
||||||
if (idx > -1) message = message.slice(0, idx);
|
if (idx > -1) message = message.slice(0, idx);
|
||||||
url.searchParams.append("message", message);
|
url.searchParams.append("message", message);
|
||||||
if (opts.error.stack) {
|
if (error.stack) {
|
||||||
const stack = colors.stripAnsiCode(opts.error.stack);
|
const stack = colors.stripAnsiCode(error.stack);
|
||||||
url.searchParams.append("stack", stack);
|
url.searchParams.append("stack", stack);
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
url.searchParams.append("message", String(opts.error));
|
url.searchParams.append("message", String(error));
|
||||||
}
|
}
|
||||||
if (opts.codeFrame) {
|
if (opts.codeFrame) {
|
||||||
const codeFrame = colors.stripAnsiCode(opts.codeFrame);
|
const codeFrame = colors.stripAnsiCode(opts.codeFrame);
|
||||||
|
|||||||
+48
-45
@@ -1,72 +1,74 @@
|
|||||||
import { PARTIAL_SEARCH_PARAM } from "../constants.ts";
|
import { PARTIAL_SEARCH_PARAM } from "../constants.ts";
|
||||||
import { BaseRoute, ErrorHandlerContext, ServeHandlerInfo } from "./types.ts";
|
import {
|
||||||
|
BaseRoute,
|
||||||
|
ErrorHandlerContext,
|
||||||
|
FreshContext,
|
||||||
|
ServeHandlerInfo,
|
||||||
|
} from "./types.ts";
|
||||||
import { isIdentifierChar, isIdentifierStart } from "./init_safe_deps.ts";
|
import { isIdentifierChar, isIdentifierStart } from "./init_safe_deps.ts";
|
||||||
|
|
||||||
type HandlerContext<T = unknown> = T & ServeHandlerInfo & {
|
type HandlerContext<T = unknown> = T & ServeHandlerInfo & {
|
||||||
isPartial: boolean;
|
isPartial: boolean;
|
||||||
};
|
};
|
||||||
|
|
||||||
export type Handler<T = unknown> = (
|
export type Handler<T = Record<string, unknown>> = (
|
||||||
req: Request,
|
req: Request,
|
||||||
ctx: HandlerContext<T>,
|
ctx: FreshContext<T>,
|
||||||
) => Response | Promise<Response>;
|
) => Response | Promise<Response>;
|
||||||
|
|
||||||
export type FinalHandler<T = unknown> = (
|
export type FinalHandler = (
|
||||||
req: Request,
|
req: Request,
|
||||||
ctx: HandlerContext<T>,
|
ctx: FreshContext,
|
||||||
params: Record<string, string>,
|
route?: InternalRoute,
|
||||||
route?: InternalRoute<T>,
|
|
||||||
) => {
|
) => {
|
||||||
destination: DestinationKind;
|
destination: DestinationKind;
|
||||||
handler: () => Response | Promise<Response>;
|
handler: () => Response | Promise<Response>;
|
||||||
};
|
};
|
||||||
|
|
||||||
export type ErrorHandler<T = unknown> = (
|
export type ErrorHandler<T = Record<string, unknown>> = (
|
||||||
req: Request,
|
req: Request,
|
||||||
ctx: HandlerContext<T>,
|
ctx: FreshContext<T>,
|
||||||
err: unknown,
|
err: unknown,
|
||||||
) => Response | Promise<Response>;
|
) => Response | Promise<Response>;
|
||||||
|
|
||||||
type UnknownMethodHandler<T = unknown> = (
|
type UnknownMethodHandler = (
|
||||||
req: Request,
|
req: Request,
|
||||||
ctx: HandlerContext<T>,
|
ctx: FreshContext,
|
||||||
knownMethods: KnownMethod[],
|
knownMethods: KnownMethod[],
|
||||||
) => Response | Promise<Response>;
|
) => Response | Promise<Response>;
|
||||||
|
|
||||||
export type MatchHandler<T = unknown> = (
|
export type MatchHandler = (
|
||||||
req: Request,
|
req: Request,
|
||||||
ctx: HandlerContext<T>,
|
ctx: FreshContext,
|
||||||
match: Record<string, string>,
|
|
||||||
) => Response | Promise<Response>;
|
) => Response | Promise<Response>;
|
||||||
|
|
||||||
// deno-lint-ignore ban-types
|
export interface Routes {
|
||||||
export interface Routes<T = {}> {
|
|
||||||
[key: string]: {
|
[key: string]: {
|
||||||
baseRoute: BaseRoute;
|
baseRoute: BaseRoute;
|
||||||
methods: {
|
methods: {
|
||||||
[K in KnownMethod | "default"]?: MatchHandler<T>;
|
[K in KnownMethod | "default"]?: MatchHandler;
|
||||||
};
|
};
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
export type DestinationKind = "internal" | "static" | "route" | "notFound";
|
export type DestinationKind = "internal" | "static" | "route" | "notFound";
|
||||||
|
|
||||||
// deno-lint-ignore ban-types
|
export type InternalRoute = {
|
||||||
export type InternalRoute<T = {}> = {
|
|
||||||
baseRoute: BaseRoute;
|
baseRoute: BaseRoute;
|
||||||
|
originalPattern: string;
|
||||||
pattern: RegExp | string;
|
pattern: RegExp | string;
|
||||||
methods: { [K in KnownMethod]?: MatchHandler<T> };
|
methods: { [K in KnownMethod]?: MatchHandler };
|
||||||
default?: MatchHandler<T>;
|
default?: MatchHandler;
|
||||||
destination: DestinationKind;
|
destination: DestinationKind;
|
||||||
};
|
};
|
||||||
|
|
||||||
export interface RouterOptions<T> {
|
export interface RouterOptions {
|
||||||
internalRoutes: Routes<T>;
|
internalRoutes: Routes;
|
||||||
staticRoutes: Routes<T>;
|
staticRoutes: Routes;
|
||||||
routes: Routes<T>;
|
routes: Routes;
|
||||||
otherHandler: Handler<T>;
|
otherHandler: Handler;
|
||||||
errorHandler: ErrorHandler<T>;
|
errorHandler: ErrorHandler;
|
||||||
unknownMethodHandler?: UnknownMethodHandler<T>;
|
unknownMethodHandler?: UnknownMethodHandler;
|
||||||
}
|
}
|
||||||
|
|
||||||
export type KnownMethod = typeof knownMethods[number];
|
export type KnownMethod = typeof knownMethods[number];
|
||||||
@@ -214,9 +216,9 @@ export function patternToRegExp(input: string): RegExp {
|
|||||||
|
|
||||||
export const IS_PATTERN = /[*:{}+?()]/;
|
export const IS_PATTERN = /[*:{}+?()]/;
|
||||||
|
|
||||||
function processRoutes<T>(
|
function processRoutes(
|
||||||
processedRoutes: Array<InternalRoute<T> | null>,
|
processedRoutes: Array<InternalRoute | null>,
|
||||||
routes: Routes<T>,
|
routes: Routes,
|
||||||
destination: DestinationKind,
|
destination: DestinationKind,
|
||||||
) {
|
) {
|
||||||
for (const [path, def] of Object.entries(routes)) {
|
for (const [path, def] of Object.entries(routes)) {
|
||||||
@@ -224,9 +226,10 @@ function processRoutes<T>(
|
|||||||
? path
|
? path
|
||||||
: patternToRegExp(path);
|
: patternToRegExp(path);
|
||||||
|
|
||||||
const entry: InternalRoute<T> = {
|
const entry: InternalRoute = {
|
||||||
baseRoute: def.baseRoute,
|
baseRoute: def.baseRoute,
|
||||||
pattern,
|
pattern,
|
||||||
|
originalPattern: path,
|
||||||
methods: {},
|
methods: {},
|
||||||
default: undefined,
|
default: undefined,
|
||||||
destination,
|
destination,
|
||||||
@@ -244,27 +247,27 @@ function processRoutes<T>(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface RouteResult<T> {
|
export interface RouteResult {
|
||||||
route: InternalRoute<T> | undefined;
|
route: InternalRoute | undefined;
|
||||||
params: Record<string, string>;
|
params: Record<string, string>;
|
||||||
isPartial: boolean;
|
isPartial: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function getParamsAndRoute<T>(
|
export function getParamsAndRoute(
|
||||||
{
|
{
|
||||||
internalRoutes,
|
internalRoutes,
|
||||||
staticRoutes,
|
staticRoutes,
|
||||||
routes,
|
routes,
|
||||||
}: RouterOptions<T>,
|
}: RouterOptions,
|
||||||
): (
|
): (
|
||||||
url: string,
|
url: string,
|
||||||
) => RouteResult<T> {
|
) => RouteResult {
|
||||||
const processedRoutes: Array<InternalRoute<T> | null> = [];
|
const processedRoutes: Array<InternalRoute | null> = [];
|
||||||
processRoutes(processedRoutes, internalRoutes, "internal");
|
processRoutes(processedRoutes, internalRoutes, "internal");
|
||||||
processRoutes(processedRoutes, staticRoutes, "static");
|
processRoutes(processedRoutes, staticRoutes, "static");
|
||||||
processRoutes(processedRoutes, routes, "route");
|
processRoutes(processedRoutes, routes, "route");
|
||||||
|
|
||||||
const statics = new Map<string, RouteResult<T>>();
|
const statics = new Map<string, RouteResult>();
|
||||||
|
|
||||||
return (url: string) => {
|
return (url: string) => {
|
||||||
const urlObject = new URL(url);
|
const urlObject = new URL(url);
|
||||||
@@ -323,15 +326,15 @@ export function getParamsAndRoute<T>(
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
export function router<T = unknown>(
|
export function router(
|
||||||
{
|
{
|
||||||
otherHandler,
|
otherHandler,
|
||||||
unknownMethodHandler,
|
unknownMethodHandler,
|
||||||
}: RouterOptions<T>,
|
}: RouterOptions,
|
||||||
): FinalHandler<T> {
|
): FinalHandler {
|
||||||
unknownMethodHandler ??= defaultUnknownMethodHandler;
|
unknownMethodHandler ??= defaultUnknownMethodHandler;
|
||||||
|
|
||||||
return (req, ctx, groups, route) => {
|
return (req, ctx, route) => {
|
||||||
if (route) {
|
if (route) {
|
||||||
// If not overridden, HEAD requests should be handled as GET requests but without the body.
|
// If not overridden, HEAD requests should be handled as GET requests but without the body.
|
||||||
if (req.method === "HEAD" && !route.methods["HEAD"]) {
|
if (req.method === "HEAD" && !route.methods["HEAD"]) {
|
||||||
@@ -342,7 +345,7 @@ export function router<T = unknown>(
|
|||||||
if (req.method === method) {
|
if (req.method === method) {
|
||||||
return {
|
return {
|
||||||
destination: route.destination,
|
destination: route.destination,
|
||||||
handler: () => handler(req, ctx, groups),
|
handler: () => handler(req, ctx),
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -350,7 +353,7 @@ export function router<T = unknown>(
|
|||||||
if (route.default) {
|
if (route.default) {
|
||||||
return {
|
return {
|
||||||
destination: route.destination,
|
destination: route.destination,
|
||||||
handler: () => route.default!(req, ctx, groups),
|
handler: () => route.default!(req, ctx),
|
||||||
};
|
};
|
||||||
} else {
|
} else {
|
||||||
return {
|
return {
|
||||||
|
|||||||
+106
-96
@@ -22,17 +22,6 @@ export interface DenoConfig {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// --- APPLICATION CONFIGURATION ---
|
// --- APPLICATION CONFIGURATION ---
|
||||||
|
|
||||||
/**
|
|
||||||
* @deprecated Use {@linkcode FreshConfig} instead
|
|
||||||
*/
|
|
||||||
export type StartOptions = FreshConfig;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @deprecated Use {@linkcode FreshConfig} interface instead.
|
|
||||||
*/
|
|
||||||
export type FreshOptions = FreshConfig;
|
|
||||||
|
|
||||||
export interface FreshConfig {
|
export interface FreshConfig {
|
||||||
build?: {
|
build?: {
|
||||||
/**
|
/**
|
||||||
@@ -201,22 +190,46 @@ export interface StaticFile {
|
|||||||
etag: string;
|
etag: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export interface FreshContext<
|
||||||
|
State = Record<string, unknown>,
|
||||||
|
// deno-lint-ignore no-explicit-any
|
||||||
|
Data = any,
|
||||||
|
NotFoundData = Data,
|
||||||
|
> {
|
||||||
|
/** @types deprecated */
|
||||||
|
localAddr?: Deno.NetAddr;
|
||||||
|
remoteAddr: Deno.NetAddr;
|
||||||
|
url: URL;
|
||||||
|
basePath: string;
|
||||||
|
route: string;
|
||||||
|
destination: router.DestinationKind;
|
||||||
|
params: Record<string, string>;
|
||||||
|
isPartial: boolean;
|
||||||
|
state: State;
|
||||||
|
/** @deprecated Pass values to state instead */
|
||||||
|
data: Data;
|
||||||
|
error?: unknown;
|
||||||
|
|
||||||
|
// These properties may be different
|
||||||
|
renderNotFound: (data?: NotFoundData) => Response | Promise<Response>;
|
||||||
|
render: (
|
||||||
|
data?: Data,
|
||||||
|
options?: RenderOptions,
|
||||||
|
) => Response | Promise<Response>;
|
||||||
|
Component: () => VNode;
|
||||||
|
next: () => Promise<Response>;
|
||||||
|
}
|
||||||
/**
|
/**
|
||||||
* Context passed to async route components.
|
* Context passed to async route components.
|
||||||
*/
|
*/
|
||||||
// deno-lint-ignore no-explicit-any
|
// deno-lint-ignore no-explicit-any
|
||||||
export type RouteContext<T = any, S = Record<string, unknown>> = {
|
export type RouteContext<T = any, S = Record<string, unknown>> = Omit<
|
||||||
/** @types deprecated */
|
FreshContext<
|
||||||
localAddr?: Deno.NetAddr;
|
S,
|
||||||
remoteAddr: Deno.NetAddr;
|
T
|
||||||
renderNotFound: (data?: T) => Response | Promise<Response>;
|
>,
|
||||||
url: URL;
|
"next" | "render"
|
||||||
route: string;
|
>;
|
||||||
params: Record<string, string>;
|
|
||||||
state: S;
|
|
||||||
data: T;
|
|
||||||
isPartial: boolean;
|
|
||||||
};
|
|
||||||
|
|
||||||
export interface RouteConfig {
|
export interface RouteConfig {
|
||||||
/**
|
/**
|
||||||
@@ -265,26 +278,10 @@ export type ServeHandler = (
|
|||||||
info: ServeHandlerInfo,
|
info: ServeHandlerInfo,
|
||||||
) => Response | Promise<Response>;
|
) => Response | Promise<Response>;
|
||||||
|
|
||||||
export interface HandlerContext<
|
|
||||||
Data = unknown,
|
|
||||||
State = Record<string, unknown>,
|
|
||||||
NotFoundData = Data,
|
|
||||||
> extends ServeHandlerInfo {
|
|
||||||
params: Record<string, string>;
|
|
||||||
basePath: string;
|
|
||||||
render: (
|
|
||||||
data?: Data,
|
|
||||||
options?: RenderOptions,
|
|
||||||
) => Response | Promise<Response>;
|
|
||||||
renderNotFound: (data?: NotFoundData) => Response | Promise<Response>;
|
|
||||||
state: State;
|
|
||||||
isPartial: boolean;
|
|
||||||
}
|
|
||||||
|
|
||||||
// deno-lint-ignore no-explicit-any
|
// deno-lint-ignore no-explicit-any
|
||||||
export type Handler<T = any, State = Record<string, unknown>> = (
|
export type Handler<T = any, State = Record<string, unknown>> = (
|
||||||
req: Request,
|
req: Request,
|
||||||
ctx: HandlerContext<T, State>,
|
ctx: FreshContext<State, T>,
|
||||||
) => Response | Promise<Response>;
|
) => Response | Promise<Response>;
|
||||||
|
|
||||||
// deno-lint-ignore no-explicit-any
|
// deno-lint-ignore no-explicit-any
|
||||||
@@ -292,11 +289,6 @@ export type Handlers<T = any, State = Record<string, unknown>> = {
|
|||||||
[K in router.KnownMethod]?: Handler<T, State>;
|
[K in router.KnownMethod]?: Handler<T, State>;
|
||||||
};
|
};
|
||||||
|
|
||||||
/**
|
|
||||||
* @deprecated This type was a short-lived alternative to `Handlers`. Please use `Handlers` instead.
|
|
||||||
*/
|
|
||||||
export type MultiHandler<T> = Handlers<T>;
|
|
||||||
|
|
||||||
export interface RouteModule {
|
export interface RouteModule {
|
||||||
default?: PageComponent<PageProps>;
|
default?: PageComponent<PageProps>;
|
||||||
// deno-lint-ignore no-explicit-any
|
// deno-lint-ignore no-explicit-any
|
||||||
@@ -307,7 +299,7 @@ export interface RouteModule {
|
|||||||
// deno-lint-ignore no-explicit-any
|
// deno-lint-ignore no-explicit-any
|
||||||
export type AsyncRoute<T = any, S = Record<string, unknown>> = (
|
export type AsyncRoute<T = any, S = Record<string, unknown>> = (
|
||||||
req: Request,
|
req: Request,
|
||||||
ctx: RouteContext<T, S>,
|
ctx: FreshContext<S, T>,
|
||||||
) => Promise<ComponentChildren | Response>;
|
) => Promise<ComponentChildren | Response>;
|
||||||
// deno-lint-ignore no-explicit-any
|
// deno-lint-ignore no-explicit-any
|
||||||
export type PageComponent<T = any, S = Record<string, unknown>> =
|
export type PageComponent<T = any, S = Record<string, unknown>> =
|
||||||
@@ -329,10 +321,6 @@ export interface Route<Data = any> {
|
|||||||
inheritLayouts: boolean;
|
inheritLayouts: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface RouterState {
|
|
||||||
state: Record<string, unknown>;
|
|
||||||
}
|
|
||||||
|
|
||||||
// --- APP ---
|
// --- APP ---
|
||||||
|
|
||||||
// deno-lint-ignore no-explicit-any
|
// deno-lint-ignore no-explicit-any
|
||||||
@@ -342,18 +330,6 @@ export interface AppModule {
|
|||||||
default: ComponentType<AppProps> | AsyncLayout;
|
default: ComponentType<AppProps> | AsyncLayout;
|
||||||
}
|
}
|
||||||
|
|
||||||
// deno-lint-ignore no-explicit-any
|
|
||||||
export type AppContext<T = any, S = Record<string, unknown>> =
|
|
||||||
& RouteContext<T, S>
|
|
||||||
& {
|
|
||||||
Component: () => VNode;
|
|
||||||
};
|
|
||||||
// deno-lint-ignore no-explicit-any
|
|
||||||
export type LayoutContext<T = any, S = Record<string, unknown>> = AppContext<
|
|
||||||
T,
|
|
||||||
S
|
|
||||||
>;
|
|
||||||
|
|
||||||
// deno-lint-ignore no-explicit-any
|
// deno-lint-ignore no-explicit-any
|
||||||
export interface LayoutProps<T = any, S = Record<string, unknown>>
|
export interface LayoutProps<T = any, S = Record<string, unknown>>
|
||||||
extends PageProps<T, S> {
|
extends PageProps<T, S> {
|
||||||
@@ -362,7 +338,7 @@ export interface LayoutProps<T = any, S = Record<string, unknown>>
|
|||||||
// deno-lint-ignore no-explicit-any
|
// deno-lint-ignore no-explicit-any
|
||||||
export type AsyncLayout<T = any, S = Record<string, unknown>> = (
|
export type AsyncLayout<T = any, S = Record<string, unknown>> = (
|
||||||
req: Request,
|
req: Request,
|
||||||
ctx: LayoutContext<T, S>,
|
ctx: FreshContext<S, T>,
|
||||||
) => Promise<ComponentChildren | Response>;
|
) => Promise<ComponentChildren | Response>;
|
||||||
|
|
||||||
export interface LayoutConfig {
|
export interface LayoutConfig {
|
||||||
@@ -413,15 +389,9 @@ export interface UnknownPageProps<T = any, S = Record<string, unknown>> {
|
|||||||
state: S;
|
state: S;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface UnknownHandlerContext<State = Record<string, unknown>>
|
|
||||||
extends ServeHandlerInfo {
|
|
||||||
render: () => Response | Promise<Response>;
|
|
||||||
state: State;
|
|
||||||
}
|
|
||||||
|
|
||||||
export type UnknownHandler = (
|
export type UnknownHandler = (
|
||||||
req: Request,
|
req: Request,
|
||||||
ctx: UnknownHandlerContext,
|
ctx: FreshContext,
|
||||||
) => Response | Promise<Response>;
|
) => Response | Promise<Response>;
|
||||||
|
|
||||||
export interface UnknownPageModule {
|
export interface UnknownPageModule {
|
||||||
@@ -444,11 +414,7 @@ export interface UnknownPage {
|
|||||||
|
|
||||||
export type UnknownRenderFunction = (
|
export type UnknownRenderFunction = (
|
||||||
req: Request,
|
req: Request,
|
||||||
params: Record<string, string>,
|
ctx: FreshContext,
|
||||||
// deno-lint-ignore no-explicit-any
|
|
||||||
ctx?: any,
|
|
||||||
data?: unknown,
|
|
||||||
error?: unknown,
|
|
||||||
) => Promise<Response>;
|
) => Promise<Response>;
|
||||||
|
|
||||||
// --- ERROR PAGE ---
|
// --- ERROR PAGE ---
|
||||||
@@ -468,19 +434,12 @@ export interface ErrorPageProps {
|
|||||||
codeFrame?: string;
|
codeFrame?: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface ErrorHandlerContext<State = Record<string, unknown>>
|
|
||||||
extends ServeHandlerInfo {
|
|
||||||
error: unknown;
|
|
||||||
render: () => Response | Promise<Response>;
|
|
||||||
state: State;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Nominal/Branded type. Ensures that the string has the expected format
|
// Nominal/Branded type. Ensures that the string has the expected format
|
||||||
export type BaseRoute = string & { readonly __brand: unique symbol };
|
export type BaseRoute = string & { readonly __brand: unique symbol };
|
||||||
|
|
||||||
export type ErrorHandler = (
|
export type ErrorHandler = (
|
||||||
req: Request,
|
req: Request,
|
||||||
ctx: ErrorHandlerContext,
|
ctx: FreshContext,
|
||||||
) => Response | Promise<Response>;
|
) => Response | Promise<Response>;
|
||||||
|
|
||||||
export interface ErrorPageModule {
|
export interface ErrorPageModule {
|
||||||
@@ -502,18 +461,6 @@ export interface ErrorPage {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// --- MIDDLEWARES ---
|
// --- MIDDLEWARES ---
|
||||||
|
|
||||||
export interface MiddlewareHandlerContext<State = Record<string, unknown>>
|
|
||||||
extends ServeHandlerInfo {
|
|
||||||
next: () => Promise<Response>;
|
|
||||||
renderNotFound: (state?: State) => Response | Promise<Response>;
|
|
||||||
state: State;
|
|
||||||
destination: router.DestinationKind;
|
|
||||||
params: Record<string, string>;
|
|
||||||
isPartial: boolean;
|
|
||||||
basePath: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface MiddlewareRoute {
|
export interface MiddlewareRoute {
|
||||||
baseRoute: BaseRoute;
|
baseRoute: BaseRoute;
|
||||||
module: Middleware;
|
module: Middleware;
|
||||||
@@ -521,7 +468,7 @@ export interface MiddlewareRoute {
|
|||||||
|
|
||||||
export type MiddlewareHandler<State = Record<string, unknown>> = (
|
export type MiddlewareHandler<State = Record<string, unknown>> = (
|
||||||
req: Request,
|
req: Request,
|
||||||
ctx: MiddlewareHandlerContext<State>,
|
ctx: FreshContext<State>,
|
||||||
) => Response | Promise<Response>;
|
) => Response | Promise<Response>;
|
||||||
|
|
||||||
// deno-lint-ignore no-explicit-any
|
// deno-lint-ignore no-explicit-any
|
||||||
@@ -688,3 +635,66 @@ export interface PluginIslands {
|
|||||||
baseLocation: string;
|
baseLocation: string;
|
||||||
paths: string[];
|
paths: string[];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// --- Deprecated types ---
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @deprecated This type was a short-lived alternative to `Handlers`. Please use `Handlers` instead.
|
||||||
|
*/
|
||||||
|
export type MultiHandler<T> = Handlers<T>;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @deprecated Use {@linkcode FreshConfig} instead
|
||||||
|
*/
|
||||||
|
export type StartOptions = FreshConfig;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @deprecated Use {@linkcode FreshConfig} interface instead.
|
||||||
|
*/
|
||||||
|
export type FreshOptions = FreshConfig;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @deprecated Use {@linkcode FreshContext} interface instead
|
||||||
|
*/
|
||||||
|
export type HandlerContext<
|
||||||
|
Data = unknown,
|
||||||
|
State = Record<string, unknown>,
|
||||||
|
NotFoundData = Data,
|
||||||
|
> = FreshContext<State, Data, NotFoundData>;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @deprecated Use {@linkcode FreshContext} interface instead
|
||||||
|
*/
|
||||||
|
// deno-lint-ignore no-explicit-any
|
||||||
|
export type AppContext<T = any, S = Record<string, unknown>> = FreshContext<
|
||||||
|
S,
|
||||||
|
T
|
||||||
|
>;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @deprecated Use {@linkcode FreshContext} interface instead
|
||||||
|
*/
|
||||||
|
// deno-lint-ignore no-explicit-any
|
||||||
|
export type LayoutContext<T = any, S = Record<string, unknown>> = FreshContext<
|
||||||
|
S,
|
||||||
|
T
|
||||||
|
>;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @deprecated Use {@linkcode FreshContext} interface instead
|
||||||
|
*/
|
||||||
|
export type UnknownHandlerContext<State = Record<string, unknown>> =
|
||||||
|
FreshContext<State>;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @deprecated Use {@linkcode FreshContext} interface instead
|
||||||
|
*/
|
||||||
|
export type ErrorHandlerContext<State = Record<string, unknown>> = FreshContext<
|
||||||
|
State
|
||||||
|
>;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @deprecated Use {@linkcode FreshContext} interface instead
|
||||||
|
*/
|
||||||
|
export type MiddlewareHandlerContext<State = Record<string, unknown>> =
|
||||||
|
FreshContext<State>;
|
||||||
|
|||||||
@@ -36,17 +36,14 @@ Deno.test("dev_command config: shows codeframe", async () => {
|
|||||||
);
|
);
|
||||||
});
|
});
|
||||||
|
|
||||||
Deno.test({
|
Deno.test("dev_command legacy", async () => {
|
||||||
name: "dev_command legacy",
|
await withPageName(
|
||||||
async fn() {
|
"./tests/fixture_dev_legacy/main.ts",
|
||||||
await withPageName(
|
async (page, address) => {
|
||||||
"./tests/fixture_dev_legacy/main.ts",
|
await page.goto(`${address}`);
|
||||||
async (page, address) => {
|
await waitForStyle(page, "h1", "color", "rgb(220, 38, 38)");
|
||||||
await page.goto(`${address}`);
|
},
|
||||||
await waitForStyle(page, "h1", "color", "rgb(220, 38, 38)");
|
);
|
||||||
},
|
|
||||||
);
|
|
||||||
},
|
|
||||||
});
|
});
|
||||||
|
|
||||||
Deno.test("dev_command legacy: shows codeframe", async () => {
|
Deno.test("dev_command legacy: shows codeframe", async () => {
|
||||||
|
|||||||
+31
-35
@@ -79,22 +79,22 @@ import * as $static from "./routes/static.tsx";
|
|||||||
import * as $status_overwrite from "./routes/status_overwrite.tsx";
|
import * as $status_overwrite from "./routes/status_overwrite.tsx";
|
||||||
import * as $umlaut_äöüß from "./routes/umlaut-äöüß.tsx";
|
import * as $umlaut_äöüß from "./routes/umlaut-äöüß.tsx";
|
||||||
import * as $wildcard from "./routes/wildcard.tsx";
|
import * as $wildcard from "./routes/wildcard.tsx";
|
||||||
import * as $$Counter from "./islands/Counter.tsx";
|
import * as $Counter from "./islands/Counter.tsx";
|
||||||
import * as $$FormIsland from "./islands/FormIsland.tsx";
|
import * as $FormIsland from "./islands/FormIsland.tsx";
|
||||||
import * as $$Greeter from "./islands/Greeter.tsx";
|
import * as $Greeter from "./islands/Greeter.tsx";
|
||||||
import * as $$HookIsland from "./islands/HookIsland.tsx";
|
import * as $HookIsland from "./islands/HookIsland.tsx";
|
||||||
import * as $$MultipleCounters from "./islands/MultipleCounters.tsx";
|
import * as $MultipleCounters from "./islands/MultipleCounters.tsx";
|
||||||
import * as $$ReturningNull from "./islands/ReturningNull.tsx";
|
import * as $ReturningNull from "./islands/ReturningNull.tsx";
|
||||||
import * as $$RootFragment from "./islands/RootFragment.tsx";
|
import * as $RootFragment from "./islands/RootFragment.tsx";
|
||||||
import * as $$RootFragmentWithConditionalFirst from "./islands/RootFragmentWithConditionalFirst.tsx";
|
import * as $RootFragmentWithConditionalFirst from "./islands/RootFragmentWithConditionalFirst.tsx";
|
||||||
import * as $$StringEventIsland from "./islands/StringEventIsland.tsx";
|
import * as $StringEventIsland from "./islands/StringEventIsland.tsx";
|
||||||
import * as $$Test from "./islands/Test.tsx";
|
import * as $Test from "./islands/Test.tsx";
|
||||||
import * as $$folder_Counter from "./islands/folder/Counter.tsx";
|
import * as $folder_Counter from "./islands/folder/Counter.tsx";
|
||||||
import * as $$folder_subfolder_Counter from "./islands/folder/subfolder/Counter.tsx";
|
import * as $folder_subfolder_Counter from "./islands/folder/subfolder/Counter.tsx";
|
||||||
import * as $$kebab_case_counter_test from "./islands/kebab-case-counter-test.tsx";
|
import * as $kebab_case_counter_test from "./islands/kebab-case-counter-test.tsx";
|
||||||
import * as $$route_groups_islands_islands_Counter from "./routes/route-groups-islands/(_islands)/Counter.tsx";
|
import * as $route_groups_islands_islands_Counter from "./routes/route-groups-islands/(_islands)/Counter.tsx";
|
||||||
import * as $$route_groups_islands_islands_invalid from "./routes/route-groups-islands/(_islands)/invalid.tsx";
|
import * as $route_groups_islands_islands_invalid from "./routes/route-groups-islands/(_islands)/invalid.tsx";
|
||||||
import { Manifest } from "$fresh/server.ts";
|
import { type Manifest } from "$fresh/server.ts";
|
||||||
|
|
||||||
const manifest = {
|
const manifest = {
|
||||||
routes: {
|
routes: {
|
||||||
@@ -195,28 +195,24 @@ const manifest = {
|
|||||||
"./routes/wildcard.tsx": $wildcard,
|
"./routes/wildcard.tsx": $wildcard,
|
||||||
},
|
},
|
||||||
islands: {
|
islands: {
|
||||||
"./islands/Counter.tsx": $$Counter,
|
"./islands/Counter.tsx": $Counter,
|
||||||
"./islands/FormIsland.tsx": $$FormIsland,
|
"./islands/FormIsland.tsx": $FormIsland,
|
||||||
"./islands/Greeter.tsx": $$Greeter,
|
"./islands/Greeter.tsx": $Greeter,
|
||||||
"./islands/HookIsland.tsx": $$HookIsland,
|
"./islands/HookIsland.tsx": $HookIsland,
|
||||||
"./islands/MultipleCounters.tsx": {
|
"./islands/MultipleCounters.tsx": $MultipleCounters,
|
||||||
CounterOne: $$MultipleCounters.CounterOne,
|
"./islands/ReturningNull.tsx": $ReturningNull,
|
||||||
CounterTwo: $$MultipleCounters.CounterTwo,
|
"./islands/RootFragment.tsx": $RootFragment,
|
||||||
default: $$MultipleCounters.default,
|
|
||||||
},
|
|
||||||
"./islands/ReturningNull.tsx": $$ReturningNull,
|
|
||||||
"./islands/RootFragment.tsx": $$RootFragment,
|
|
||||||
"./islands/RootFragmentWithConditionalFirst.tsx":
|
"./islands/RootFragmentWithConditionalFirst.tsx":
|
||||||
$$RootFragmentWithConditionalFirst,
|
$RootFragmentWithConditionalFirst,
|
||||||
"./islands/StringEventIsland.tsx": $$StringEventIsland,
|
"./islands/StringEventIsland.tsx": $StringEventIsland,
|
||||||
"./islands/Test.tsx": $$Test,
|
"./islands/Test.tsx": $Test,
|
||||||
"./islands/folder/Counter.tsx": $$folder_Counter,
|
"./islands/folder/Counter.tsx": $folder_Counter,
|
||||||
"./islands/folder/subfolder/Counter.tsx": $$folder_subfolder_Counter,
|
"./islands/folder/subfolder/Counter.tsx": $folder_subfolder_Counter,
|
||||||
"./islands/kebab-case-counter-test.tsx": $$kebab_case_counter_test,
|
"./islands/kebab-case-counter-test.tsx": $kebab_case_counter_test,
|
||||||
"./routes/route-groups-islands/(_islands)/Counter.tsx":
|
"./routes/route-groups-islands/(_islands)/Counter.tsx":
|
||||||
$$route_groups_islands_islands_Counter,
|
$route_groups_islands_islands_Counter,
|
||||||
"./routes/route-groups-islands/(_islands)/invalid.tsx":
|
"./routes/route-groups-islands/(_islands)/invalid.tsx":
|
||||||
$$route_groups_islands_islands_invalid,
|
$route_groups_islands_islands_invalid,
|
||||||
},
|
},
|
||||||
baseUrl: import.meta.url,
|
baseUrl: import.meta.url,
|
||||||
} satisfies Manifest;
|
} satisfies Manifest;
|
||||||
|
|||||||
@@ -1,8 +1,5 @@
|
|||||||
import { MiddlewareHandlerContext } from "$fresh/server.ts";
|
import { FreshContext } from "$fresh/server.ts";
|
||||||
|
|
||||||
export async function handler(
|
export async function handler(_req: Request, ctx: FreshContext) {
|
||||||
_req: Request,
|
|
||||||
ctx: MiddlewareHandlerContext,
|
|
||||||
) {
|
|
||||||
return await ctx.renderNotFound();
|
return await ctx.renderNotFound();
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,10 +1,7 @@
|
|||||||
import { MiddlewareHandler, MiddlewareHandlerContext } from "$fresh/server.ts";
|
import { FreshContext, MiddlewareHandler } from "$fresh/server.ts";
|
||||||
|
|
||||||
// cors middleware
|
// cors middleware
|
||||||
async function corsHandler(
|
async function corsHandler(_req: Request, ctx: FreshContext) {
|
||||||
_req: Request,
|
|
||||||
ctx: MiddlewareHandlerContext,
|
|
||||||
) {
|
|
||||||
if (_req.method == "OPTIONS") {
|
if (_req.method == "OPTIONS") {
|
||||||
return new Response(null, {
|
return new Response(null, {
|
||||||
status: 204,
|
status: 204,
|
||||||
@@ -29,10 +26,7 @@ async function corsHandler(
|
|||||||
}
|
}
|
||||||
|
|
||||||
// log middleware
|
// log middleware
|
||||||
async function logHandler(
|
async function logHandler(_req: Request, ctx: FreshContext) {
|
||||||
_req: Request,
|
|
||||||
ctx: MiddlewareHandlerContext,
|
|
||||||
) {
|
|
||||||
const since = new Date();
|
const since = new Date();
|
||||||
const resp = await ctx.next();
|
const resp = await ctx.next();
|
||||||
const latency = (+new Date()) - (+since);
|
const latency = (+new Date()) - (+since);
|
||||||
@@ -40,20 +34,14 @@ async function logHandler(
|
|||||||
return resp;
|
return resp;
|
||||||
}
|
}
|
||||||
|
|
||||||
async function rootHandler(
|
async function rootHandler(_req: Request, ctx: FreshContext) {
|
||||||
_req: Request,
|
|
||||||
ctx: MiddlewareHandlerContext,
|
|
||||||
) {
|
|
||||||
ctx.state.root = "root_mw";
|
ctx.state.root = "root_mw";
|
||||||
const resp = await ctx.next();
|
const resp = await ctx.next();
|
||||||
resp.headers.set("server", "fresh test server");
|
resp.headers.set("server", "fresh test server");
|
||||||
return resp;
|
return resp;
|
||||||
}
|
}
|
||||||
|
|
||||||
async function kindHandler(
|
async function kindHandler(_req: Request, ctx: FreshContext) {
|
||||||
_req: Request,
|
|
||||||
ctx: MiddlewareHandlerContext,
|
|
||||||
) {
|
|
||||||
const resp = await ctx.next();
|
const resp = await ctx.next();
|
||||||
resp.headers.set("destination", ctx.destination);
|
resp.headers.set("destination", ctx.destination);
|
||||||
return resp;
|
return resp;
|
||||||
|
|||||||
@@ -9,8 +9,8 @@ import * as $index from "./routes/index.tsx";
|
|||||||
import * as $island from "./routes/island.tsx";
|
import * as $island from "./routes/island.tsx";
|
||||||
import * as $response from "./routes/response.tsx";
|
import * as $response from "./routes/response.tsx";
|
||||||
import * as $twind from "./routes/twind.tsx";
|
import * as $twind from "./routes/twind.tsx";
|
||||||
import * as $$FooIsland from "./islands/FooIsland.tsx";
|
import * as $FooIsland from "./islands/FooIsland.tsx";
|
||||||
import { Manifest } from "$fresh/server.ts";
|
import { type Manifest } from "$fresh/server.ts";
|
||||||
|
|
||||||
const manifest = {
|
const manifest = {
|
||||||
routes: {
|
routes: {
|
||||||
@@ -23,7 +23,7 @@ const manifest = {
|
|||||||
"./routes/twind.tsx": $twind,
|
"./routes/twind.tsx": $twind,
|
||||||
},
|
},
|
||||||
islands: {
|
islands: {
|
||||||
"./islands/FooIsland.tsx": $$FooIsland,
|
"./islands/FooIsland.tsx": $FooIsland,
|
||||||
},
|
},
|
||||||
baseUrl: import.meta.url,
|
baseUrl: import.meta.url,
|
||||||
} satisfies Manifest;
|
} satisfies Manifest;
|
||||||
|
|||||||
+8
-11
@@ -671,17 +671,14 @@ Deno.test({
|
|||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
Deno.test({
|
Deno.test("/not_found", async () => {
|
||||||
name: "/not_found",
|
const resp = await handler(new Request("https://fresh.deno.dev/not_found"));
|
||||||
fn: async () => {
|
assert(resp);
|
||||||
const resp = await handler(new Request("https://fresh.deno.dev/not_found"));
|
assertEquals(resp.status, 404);
|
||||||
assert(resp);
|
const body = await resp.text();
|
||||||
assertEquals(resp.status, 404);
|
assertStringIncludes(body, "404 not found: /not_found");
|
||||||
const body = await resp.text();
|
assertStringIncludes(body, "Hello Dino");
|
||||||
assertStringIncludes(body, "404 not found: /not_found");
|
assertStringIncludes(body, "State root: root_mw");
|
||||||
assertStringIncludes(body, "Hello Dino");
|
|
||||||
assertStringIncludes(body, "State root: root_mw");
|
|
||||||
},
|
|
||||||
});
|
});
|
||||||
|
|
||||||
Deno.test("middleware destination", async (t) => {
|
Deno.test("middleware destination", async (t) => {
|
||||||
|
|||||||
@@ -58,47 +58,48 @@ Deno.test({
|
|||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
Deno.test({
|
Deno.test("passes context to server component", async () => {
|
||||||
name: "passes context to server component",
|
await withFresh(
|
||||||
|
"./tests/fixture_server_components/main.ts",
|
||||||
|
async (address) => {
|
||||||
|
const res = await fetch(`${address}/context/foo`);
|
||||||
|
const json = await res.json();
|
||||||
|
|
||||||
async fn() {
|
assertEquals(typeof json.localAddr, "object");
|
||||||
await withFresh(
|
assertEquals(typeof json.remoteAddr, "object");
|
||||||
"./tests/fixture_server_components/main.ts",
|
json.localAddr.port = 8000;
|
||||||
async (address) => {
|
json.remoteAddr.port = 8000;
|
||||||
const res = await fetch(`${address}/context/foo`);
|
|
||||||
const json = await res.json();
|
|
||||||
|
|
||||||
assertEquals(typeof json.localAddr, "object");
|
assertEquals(
|
||||||
assertEquals(typeof json.remoteAddr, "object");
|
json,
|
||||||
json.localAddr.port = 8000;
|
{
|
||||||
json.remoteAddr.port = 8000;
|
localAddr: {
|
||||||
|
hostname: "localhost",
|
||||||
assertEquals(
|
port: 8000,
|
||||||
json,
|
transport: "tcp",
|
||||||
{
|
|
||||||
localAddr: {
|
|
||||||
hostname: "localhost",
|
|
||||||
port: 8000,
|
|
||||||
transport: "tcp",
|
|
||||||
},
|
|
||||||
remoteAddr: {
|
|
||||||
hostname: "127.0.0.1",
|
|
||||||
port: 8000,
|
|
||||||
transport: "tcp",
|
|
||||||
},
|
|
||||||
renderNotFound: "AsyncFunction",
|
|
||||||
url: `${address}/context/foo`,
|
|
||||||
route: "/context/:id",
|
|
||||||
params: {
|
|
||||||
id: "foo",
|
|
||||||
},
|
|
||||||
state: {},
|
|
||||||
isPartial: false,
|
|
||||||
},
|
},
|
||||||
);
|
remoteAddr: {
|
||||||
},
|
hostname: "127.0.0.1",
|
||||||
);
|
port: 8000,
|
||||||
},
|
transport: "tcp",
|
||||||
|
},
|
||||||
|
render: "AsyncFunction",
|
||||||
|
Component: "Function",
|
||||||
|
destination: "route",
|
||||||
|
next: "Function",
|
||||||
|
basePath: "",
|
||||||
|
renderNotFound: "AsyncFunction",
|
||||||
|
url: `${address}/context/foo`,
|
||||||
|
route: "/context/:id",
|
||||||
|
params: {
|
||||||
|
id: "foo",
|
||||||
|
},
|
||||||
|
state: {},
|
||||||
|
isPartial: false,
|
||||||
|
},
|
||||||
|
);
|
||||||
|
},
|
||||||
|
);
|
||||||
});
|
});
|
||||||
|
|
||||||
Deno.test({
|
Deno.test({
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import { MiddlewareHandlerContext } from "$fresh/server.ts";
|
import { type FreshContext } from "$fresh/server.ts";
|
||||||
import type { Event } from "$ga4";
|
import type { Event } from "$ga4";
|
||||||
import { GA4Report, isDocument, isServerError } from "$ga4";
|
import { GA4Report, isDocument, isServerError } from "$ga4";
|
||||||
|
|
||||||
@@ -8,7 +8,7 @@ let showedMissingEnvWarning = false;
|
|||||||
|
|
||||||
function ga4(
|
function ga4(
|
||||||
request: Request,
|
request: Request,
|
||||||
conn: MiddlewareHandlerContext,
|
conn: FreshContext,
|
||||||
response: Response,
|
response: Response,
|
||||||
_start: number,
|
_start: number,
|
||||||
error?: unknown,
|
error?: unknown,
|
||||||
@@ -80,7 +80,7 @@ function ga4(
|
|||||||
|
|
||||||
export async function handler(
|
export async function handler(
|
||||||
req: Request,
|
req: Request,
|
||||||
ctx: MiddlewareHandlerContext,
|
ctx: FreshContext,
|
||||||
): Promise<Response> {
|
): Promise<Response> {
|
||||||
let err;
|
let err;
|
||||||
let res: Response;
|
let res: Response;
|
||||||
|
|||||||
Reference in New Issue
Block a user