import type { State } from "./application.ts";import type { Context } from "./context.ts";import { assert, compile, Key, ParseOptions, pathParse, pathToRegexp, Status, TokensToRegexpOptions,} from "./deps.ts";import { httpErrors } from "./httpError.ts";import { compose, Middleware } from "./middleware.ts";import type { HTTPMethods, RedirectStatus } from "./types.d.ts";import { decodeComponent } from "./util.ts";
interface Matches { path: Layer[]; pathAndMethod: Layer[]; route: boolean;}
export interface RouterAllowedMethodsOptions { methodNotAllowed?(): any;
notImplemented?(): any;
throw?: boolean;}
export interface Route< P extends RouteParams = RouteParams, S extends State = Record<string, any>,> { methods: HTTPMethods[];
middleware: RouterMiddleware<P, S>[];
name?: string;
options: LayerOptions;
paramNames: (keyof P)[];
path: string;
regexp: RegExp;}
export interface RouterContext< P extends RouteParams = RouteParams, S extends State = Record<string, any>,> extends Context<S> { captures: string[];
matched?: Layer<P, S>[];
params: P;
router: Router;
routeName?: string;
routerPath?: string;}
export interface RouterMiddleware< P extends RouteParams = RouteParams, S extends State = Record<string, any>,> { (context: RouterContext<P, S>, next: () => Promise<void>): | Promise<void> | void; param?: keyof P;}
export interface RouterOptions { methods?: HTTPMethods[];
prefix?: string;
routerPath?: string;
sensitive?: boolean;
strict?: boolean;}
export interface RouterParamMiddleware< P extends RouteParams = RouteParams, S extends State = Record<string, any>,> { ( param: string, context: RouterContext<P, S>, next: () => Promise<void>, ): Promise<void> | void;}
export type RouteParams = Record<string | number, string | undefined>;
type LayerOptions = TokensToRegexpOptions & ParseOptions & { ignoreCaptures?: boolean; name?: string;};
type UrlOptions = TokensToRegexpOptions & ParseOptions & { query?: URLSearchParams | Record<string, string> | string;};
function toUrl(url: string, params: RouteParams = {}, options?: UrlOptions) { const tokens = pathParse(url); let replace: RouteParams = {};
if (tokens.some((token) => typeof token === "object")) { replace = params; } else { options = params; }
const toPath = compile(url, options); let replaced = toPath(replace);
if (options && options.query) { const url = new URL(replaced, "http://oak"); if (typeof options.query === "string") { url.search = options.query; } else { url.search = String( options.query instanceof URLSearchParams ? options.query : new URLSearchParams(options.query), ); } return `${url.pathname}${url.search}${url.hash}`; } return replaced;}
class Layer< P extends RouteParams = RouteParams, S extends State = Record<string, any>,> { #opts: LayerOptions; #paramNames: Key[] = []; #regexp: RegExp;
methods: HTTPMethods[]; name?: string; path: string; stack: RouterMiddleware<P, S>[];
constructor( path: string, methods: HTTPMethods[], middleware: RouterMiddleware<P, S> | RouterMiddleware<P, S>[], { name, ...opts }: LayerOptions = {}, ) { this.#opts = opts; this.name = name; this.methods = [...methods]; if (this.methods.includes("GET")) { this.methods.unshift("HEAD"); } this.stack = Array.isArray(middleware) ? middleware : [middleware]; this.path = path; this.#regexp = pathToRegexp(path, this.#paramNames, this.#opts); }
match(path: string): boolean { return this.#regexp.test(path); }
params( captures: string[], existingParams: RouteParams = {}, ): RouteParams { const params = existingParams; for (let i = 0; i < captures.length; i++) { if (this.#paramNames[i]) { const c = captures[i]; params[this.#paramNames[i].name] = c ? decodeComponent(c) : c; } } return params; }
captures(path: string): string[] { if (this.#opts.ignoreCaptures) { return []; } return path.match(this.#regexp)?.slice(1) ?? []; }
url( params: RouteParams = {}, options?: UrlOptions, ): string { const url = this.path.replace(/\(\.\*\)/g, ""); return toUrl(url, params, options); }
param( param: string, fn: RouterParamMiddleware<any, any>, ) { const stack = this.stack; const params = this.#paramNames; const middleware: RouterMiddleware = function ( this: Router, ctx, next, ): Promise<void> | void { const p = ctx.params[param]; assert(p); return fn.call(this, p, ctx, next); }; middleware.param = param;
const names = params.map((p) => p.name);
const x = names.indexOf(param); if (x >= 0) { for (let i = 0; i < stack.length; i++) { const fn = stack[i]; if (!fn.param || names.indexOf(fn.param as (string | number)) > x) { stack.splice(i, 0, middleware); break; } } } return this; }
setPrefix(prefix: string): this { if (this.path) { this.path = this.path !== "/" || this.#opts.strict === true ? `${prefix}${this.path}` : prefix; this.#paramNames = []; this.#regexp = pathToRegexp(this.path, this.#paramNames, this.#opts); } return this; }
toJSON(): Route<any, any> { return { methods: [...this.methods], middleware: [...this.stack], paramNames: this.#paramNames.map((key) => key.name), path: this.path, regexp: this.#regexp, options: { ...this.#opts }, }; }}
export class Router< RP extends RouteParams = RouteParams, RS extends State = Record<string, any>,> { #opts: RouterOptions; #methods: HTTPMethods[]; #params: Record<string, RouterParamMiddleware<any, any>> = {}; #stack: Layer[] = [];
#match = (path: string, method: HTTPMethods): Matches => { const matches: Matches = { path: [], pathAndMethod: [], route: false, };
for (const route of this.#stack) { if (route.match(path)) { matches.path.push(route); if (route.methods.length === 0 || route.methods.includes(method)) { matches.pathAndMethod.push(route); if (route.methods.length) { matches.route = true; } } } }
return matches; };
#register = ( path: string | string[], middleware: RouterMiddleware[], methods: HTTPMethods[], options: LayerOptions = {}, ): void => { if (Array.isArray(path)) { for (const p of path) { this.#register(p, middleware, methods, options); } return; }
const { end, name, sensitive, strict, ignoreCaptures } = options; const route = new Layer(path, methods, middleware, { end: end === false ? end : true, name, sensitive: sensitive ?? this.#opts.sensitive ?? false, strict: strict ?? this.#opts.strict ?? false, ignoreCaptures, });
if (this.#opts.prefix) { route.setPrefix(this.#opts.prefix); }
for (const [param, mw] of Object.entries(this.#params)) { route.param(param, mw); }
this.#stack.push(route); };
#route = (name: string): Layer | undefined => { for (const route of this.#stack) { if (route.name === name) { return route; } } };
#useVerb = ( nameOrPath: string, pathOrMiddleware: string | RouterMiddleware, middleware: RouterMiddleware[], methods: HTTPMethods[], ): void => { let name: string | undefined = undefined; let path: string; if (typeof pathOrMiddleware === "string") { name = nameOrPath; path = pathOrMiddleware; } else { path = nameOrPath; middleware.unshift(pathOrMiddleware); }
this.#register(path, middleware, methods, { name }); };
constructor(opts: RouterOptions = {}) { this.#opts = opts; this.#methods = opts.methods ?? [ "DELETE", "GET", "HEAD", "OPTIONS", "PATCH", "POST", "PUT", ]; }
all<P extends RouteParams = RP, S extends State = RS>( name: string, path: string, ...middleware: RouterMiddleware<P, S>[] ): Router<P extends RP ? P : (P & RP), S extends RS ? S : (S & RS)>; all<P extends RouteParams = RP, S extends State = RS>( path: string, ...middleware: RouterMiddleware<P, S>[] ): Router<P extends RP ? P : (P & RP), S extends RS ? S : (S & RS)>; all<P extends RouteParams = RP, S extends State = RS>( nameOrPath: string, pathOrMiddleware: string | RouterMiddleware<P, S>, ...middleware: RouterMiddleware<P, S>[] ): Router<P extends RP ? P : (P & RP), S extends RS ? S : (S & RS)> { this.#useVerb( nameOrPath, pathOrMiddleware as (string | RouterMiddleware), middleware as RouterMiddleware[], ["DELETE", "GET", "POST", "PUT"], ); return this as Router<any, any>; }
allowedMethods( options: RouterAllowedMethodsOptions = {}, ): Middleware { const implemented = this.#methods;
const allowedMethods: Middleware = async (context, next) => { const ctx = context as RouterContext; await next(); if (!ctx.response.status || ctx.response.status === Status.NotFound) { assert(ctx.matched); const allowed = new Set<HTTPMethods>(); for (const route of ctx.matched) { for (const method of route.methods) { allowed.add(method); } }
const allowedStr = [...allowed].join(", "); if (!implemented.includes(ctx.request.method)) { if (options.throw) { throw options.notImplemented ? options.notImplemented() : new httpErrors.NotImplemented(); } else { ctx.response.status = Status.NotImplemented; ctx.response.headers.set("Allowed", allowedStr); } } else if (allowed.size) { if (ctx.request.method === "OPTIONS") { ctx.response.status = Status.OK; ctx.response.headers.set("Allowed", allowedStr); } else if (!allowed.has(ctx.request.method)) { if (options.throw) { throw options.methodNotAllowed ? options.methodNotAllowed() : new httpErrors.MethodNotAllowed(); } else { ctx.response.status = Status.MethodNotAllowed; ctx.response.headers.set("Allowed", allowedStr); } } } } };
return allowedMethods; }
delete<P extends RouteParams = RP, S extends State = RS>( name: string, path: string, ...middleware: RouterMiddleware<P, S>[] ): Router<P extends RP ? P : (P & RP), S extends RS ? S : (S & RS)>; delete<P extends RouteParams = RP, S extends State = RS>( path: string, ...middleware: RouterMiddleware<P, S>[] ): Router<P extends RP ? P : (P & RP), S extends RS ? S : (S & RS)>; delete<P extends RouteParams = RP, S extends State = RS>( nameOrPath: string, pathOrMiddleware: string | RouterMiddleware<P, S>, ...middleware: RouterMiddleware<P, S>[] ): Router<P extends RP ? P : (P & RP), S extends RS ? S : (S & RS)> { this.#useVerb( nameOrPath, pathOrMiddleware as (string | RouterMiddleware), middleware as RouterMiddleware[], ["DELETE"], ); return this as Router<any, any>; }
*entries(): IterableIterator<[Route, Route]> { for (const route of this.#stack) { const value = route.toJSON(); yield [value, value]; } }
forEach( callback: (value1: Route, value2: Route, router: this) => void, thisArg: any = null, ): void { for (const route of this.#stack) { const value = route.toJSON(); callback.call(thisArg, value, value, this); } }
get<P extends RouteParams = RP, S extends State = RS>( name: string, path: string, ...middleware: RouterMiddleware<P, S>[] ): Router<P extends RP ? P : (P & RP), S extends RS ? S : (S & RS)>; get<P extends RouteParams = RP, S extends State = RS>( path: string, ...middleware: RouterMiddleware<P, S>[] ): Router<P extends RP ? P : (P & RP), S extends RS ? S : (S & RS)>; get<P extends RouteParams = RP, S extends State = RS>( nameOrPath: string, pathOrMiddleware: string | RouterMiddleware<P, S>, ...middleware: RouterMiddleware<P, S>[] ): Router<P extends RP ? P : (P & RP), S extends RS ? S : (S & RS)> { this.#useVerb( nameOrPath, pathOrMiddleware as (string | RouterMiddleware), middleware as RouterMiddleware[], ["GET"], ); return this as Router<any, any>; }
head<P extends RouteParams = RP, S extends State = RS>( name: string, path: string, ...middleware: RouterMiddleware<P, S>[] ): Router<P extends RP ? P : (P & RP), S extends RS ? S : (S & RS)>; head<P extends RouteParams = RP, S extends State = RS>( path: string, ...middleware: RouterMiddleware<P, S>[] ): Router<P extends RP ? P : (P & RP), S extends RS ? S : (S & RS)>; head<P extends RouteParams = RP, S extends State = RS>( nameOrPath: string, pathOrMiddleware: string | RouterMiddleware<P, S>, ...middleware: RouterMiddleware<P, S>[] ): Router<P extends RP ? P : (P & RP), S extends RS ? S : (S & RS)> { this.#useVerb( nameOrPath, pathOrMiddleware as (string | RouterMiddleware), middleware as RouterMiddleware[], ["HEAD"], ); return this as Router<any, any>; }
*keys(): IterableIterator<Route> { for (const route of this.#stack) { yield route.toJSON(); } }
options<P extends RouteParams = RP, S extends State = RS>( name: string, path: string, ...middleware: RouterMiddleware<P, S>[] ): Router<P extends RP ? P : (P & RP), S extends RS ? S : (S & RS)>; options<P extends RouteParams = RP, S extends State = RS>( path: string, ...middleware: RouterMiddleware<P, S>[] ): Router<P extends RP ? P : (P & RP), S extends RS ? S : (S & RS)>; options<P extends RouteParams = RP, S extends State = RS>( nameOrPath: string, pathOrMiddleware: string | RouterMiddleware<P, S>, ...middleware: RouterMiddleware<P, S>[] ): Router<P extends RP ? P : (P & RP), S extends RS ? S : (S & RS)> { this.#useVerb( nameOrPath, pathOrMiddleware as (string | RouterMiddleware), middleware as RouterMiddleware[], ["OPTIONS"], ); return this as Router<any, any>; }
param<S extends State = RS>( param: keyof RP, middleware: RouterParamMiddleware<RP, S>, ): Router<RP, S> { this.#params[param as string] = middleware; for (const route of this.#stack) { route.param(param as string, middleware); } return this; }
patch<P extends RouteParams = RP, S extends State = RS>( name: string, path: string, ...middleware: RouterMiddleware<P, S>[] ): Router<P extends RP ? P : (P & RP), S extends RS ? S : (S & RS)>; patch<P extends RouteParams = RP, S extends State = RS>( path: string, ...middleware: RouterMiddleware<P, S>[] ): Router<P extends RP ? P : (P & RP), S extends RS ? S : (S & RS)>; patch<P extends RouteParams = RP, S extends State = RS>( nameOrPath: string, pathOrMiddleware: string | RouterMiddleware<P, S>, ...middleware: RouterMiddleware<P, S>[] ): Router<P extends RP ? P : (P & RP), S extends RS ? S : (S & RS)> { this.#useVerb( nameOrPath, pathOrMiddleware as (string | RouterMiddleware), middleware as RouterMiddleware[], ["PATCH"], ); return this as Router<any, any>; }
post<P extends RouteParams = RP, S extends State = RS>( name: string, path: string, ...middleware: RouterMiddleware<P, S>[] ): Router<P extends RP ? P : (P & RP), S extends RS ? S : (S & RS)>; post<P extends RouteParams = RP, S extends State = RS>( path: string, ...middleware: RouterMiddleware<P, S>[] ): Router<P extends RP ? P : (P & RP), S extends RS ? S : (S & RS)>; post<P extends RouteParams = RP, S extends State = RS>( nameOrPath: string, pathOrMiddleware: string | RouterMiddleware<P, S>, ...middleware: RouterMiddleware<P, S>[] ): Router<P extends RP ? P : (P & RP), S extends RS ? S : (S & RS)> { this.#useVerb( nameOrPath, pathOrMiddleware as (string | RouterMiddleware), middleware as RouterMiddleware[], ["POST"], ); return this as Router<any, any>; }
prefix(prefix: string): this { prefix = prefix.replace(/\/$/, ""); this.#opts.prefix = prefix; for (const route of this.#stack) { route.setPrefix(prefix); } return this; }
put<P extends RouteParams = RP, S extends State = RS>( name: string, path: string, ...middleware: RouterMiddleware<P, S>[] ): Router<P extends RP ? P : (P & RP), S extends RS ? S : (S & RS)>; put<P extends RouteParams = RP, S extends State = RS>( path: string, ...middleware: RouterMiddleware<P, S>[] ): Router<P extends RP ? P : (P & RP), S extends RS ? S : (S & RS)>; put<P extends RouteParams = RP, S extends State = RS>( nameOrPath: string, pathOrMiddleware: string | RouterMiddleware<P, S>, ...middleware: RouterMiddleware<P, S>[] ): Router<P extends RP ? P : (P & RP), S extends RS ? S : (S & RS)> { this.#useVerb( nameOrPath, pathOrMiddleware as (string | RouterMiddleware), middleware as RouterMiddleware[], ["PUT"], ); return this as Router<any, any>; }
redirect( source: string, destination: string, status: RedirectStatus = Status.Found, ): this { if (source[0] !== "/") { const s = this.url(source); if (!s) { throw new RangeError(`Could not resolve named route: "${source}"`); } source = s; } if (destination[0] !== "/") { const d = this.url(destination); if (!d) { throw new RangeError(`Could not resolve named route: "${source}"`); } destination = d; }
this.all(source, (ctx) => { ctx.response.redirect(destination); ctx.response.status = status; }); return this; }
routes(): Middleware { const dispatch = ( context: Context, next: () => Promise<void>, ): Promise<void> => { const ctx = context as RouterContext; const { url: { pathname }, method } = ctx.request; const path = this.#opts.routerPath ?? ctx.routerPath ?? decodeURIComponent(pathname); const matches = this.#match(path, method);
if (ctx.matched) { ctx.matched.push(...matches.path); } else { ctx.matched = [...matches.path]; }
ctx.router = this as Router<any, any>;
if (!matches.route) return next();
const { pathAndMethod: matchedRoutes } = matches;
const chain = matchedRoutes.reduce( (prev, route) => [ ...prev, (ctx: RouterContext, next: () => Promise<void>): Promise<void> => { ctx.captures = route.captures(path); ctx.params = route.params(ctx.captures, ctx.params); ctx.routeName = route.name; return next(); }, ...route.stack, ], [] as RouterMiddleware[], ); return compose(chain)(ctx, next); }; dispatch.router = this; return dispatch; }
url<P extends RouteParams = RP>( name: string, params?: P, options?: UrlOptions, ): string | undefined { const route = this.#route(name);
if (route) { return route.url(params, options); } }
use<P extends RouteParams = RP, S extends State = RS>( ...middleware: RouterMiddleware<P, S>[] ): Router<P extends RP ? P : (P & RP), S extends RS ? S : (S & RS)>; use<P extends RouteParams = RP, S extends State = RS>( path: string | string[], ...middleware: RouterMiddleware<P, S>[] ): Router<P extends RP ? P : (P & RP), S extends RS ? S : (S & RS)>; use<P extends RouteParams = RP, S extends State = RS>( pathOrMiddleware: string | string[] | RouterMiddleware<P, S>, ...middleware: RouterMiddleware<P, S>[] ): Router<P extends RP ? P : (P & RP), S extends RS ? S : (S & RS)> { let path: string | string[] | undefined; if ( typeof pathOrMiddleware === "string" || Array.isArray(pathOrMiddleware) ) { path = pathOrMiddleware; } else { middleware.unshift(pathOrMiddleware); }
this.#register( path ?? "(.*)", middleware as RouterMiddleware[], [], { end: false, ignoreCaptures: !path }, );
return this as Router<any, any>; }
*values(): IterableIterator<Route<RP, RS>> { for (const route of this.#stack) { yield route.toJSON(); } }
*[Symbol.iterator](): IterableIterator<Route<RP, RS>> { for (const route of this.#stack) { yield route.toJSON(); } }
static url( path: string, params?: RouteParams, options?: UrlOptions, ): string { return toUrl(path, params, options); }}