@glass-cannon/router 0.0.2 → 0.0.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.ts +46 -0
- package/dist/index.js +109 -0
- package/dist/index.js.map +1 -0
- package/dist/middleware/contentType.d.ts +13 -0
- package/dist/middleware/contentType.js +42 -0
- package/dist/middleware/contentType.js.map +1 -0
- package/dist/middleware/index.d.ts +11 -0
- package/dist/middleware/index.js +17 -0
- package/dist/middleware/index.js.map +1 -0
- package/package.json +2 -1
- package/src/index.ts +0 -177
- package/src/middleware/contentType.ts +0 -50
- package/src/middleware/index.ts +0 -39
- package/tsconfig.json +0 -7
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import type { Handler, Request, Response } from '@glass-cannon/server';
|
|
2
|
+
import { type Middleware } from './middleware/index.js';
|
|
3
|
+
export type RouteHandler<Context> = (request: RouteContext & Context) => Promise<Response> | Response;
|
|
4
|
+
export type RouteContext = Request & {
|
|
5
|
+
params: Record<string, string>;
|
|
6
|
+
route: Route<any>;
|
|
7
|
+
};
|
|
8
|
+
export interface Route<Context> {
|
|
9
|
+
method?: string;
|
|
10
|
+
path: string;
|
|
11
|
+
handler: RouteHandler<Context>;
|
|
12
|
+
}
|
|
13
|
+
export interface RouterGroup<Context> {
|
|
14
|
+
route(options: RouteOptions<Context>): void;
|
|
15
|
+
group<NewContext>(options: GroupOptions<NewContext>): RouterGroup<Context & NewContext>;
|
|
16
|
+
}
|
|
17
|
+
export interface RouterOptions<Context = unknown> {
|
|
18
|
+
fallback?: Handler;
|
|
19
|
+
middleware?: Middleware<Context>;
|
|
20
|
+
}
|
|
21
|
+
export interface RouteOptions<Context> {
|
|
22
|
+
method?: string;
|
|
23
|
+
path: string;
|
|
24
|
+
handler: RouteHandler<Context>;
|
|
25
|
+
}
|
|
26
|
+
export interface GroupOptions<Context> {
|
|
27
|
+
prefix?: string;
|
|
28
|
+
middleware: Middleware<Context>;
|
|
29
|
+
}
|
|
30
|
+
export declare class Router<Context = unknown> implements RouterGroup<Context> {
|
|
31
|
+
private readonly fallback;
|
|
32
|
+
private readonly middleware;
|
|
33
|
+
private routes;
|
|
34
|
+
private regex;
|
|
35
|
+
constructor(options?: RouterOptions<Context>);
|
|
36
|
+
matchingRoute(request: Pick<Request, 'method' | 'path'>): Route<Context> | undefined;
|
|
37
|
+
handle: Handler;
|
|
38
|
+
route(route: RouteOptions<Context>): void;
|
|
39
|
+
group<NewContext>(options: GroupOptions<NewContext>): RouterGroup<Context & NewContext>;
|
|
40
|
+
private matchingRouteWithMetadata;
|
|
41
|
+
private computeMetadata;
|
|
42
|
+
private computeScore;
|
|
43
|
+
private pathToRegex;
|
|
44
|
+
private pathToCapturingRegex;
|
|
45
|
+
private compileRegex;
|
|
46
|
+
}
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
import { pipe } from './middleware/index.js';
|
|
2
|
+
export class Router {
|
|
3
|
+
fallback;
|
|
4
|
+
middleware;
|
|
5
|
+
routes = [];
|
|
6
|
+
regex;
|
|
7
|
+
constructor(options) {
|
|
8
|
+
this.fallback = options?.fallback ?? (() => ({ status: 404 }));
|
|
9
|
+
this.middleware = options?.middleware ?? ((x) => x);
|
|
10
|
+
}
|
|
11
|
+
matchingRoute(request) {
|
|
12
|
+
return this.matchingRouteWithMetadata(request)?.route;
|
|
13
|
+
}
|
|
14
|
+
handle = async (request) => {
|
|
15
|
+
const routeWithMetadata = this.matchingRouteWithMetadata(request);
|
|
16
|
+
if (!routeWithMetadata)
|
|
17
|
+
return await this.fallback(request);
|
|
18
|
+
const { route, capturingRegex } = routeWithMetadata;
|
|
19
|
+
const params = { ...capturingRegex.exec(request.path).groups };
|
|
20
|
+
const context = { ...request, params, route };
|
|
21
|
+
return await this.middleware(route.handler, context);
|
|
22
|
+
};
|
|
23
|
+
route(route) {
|
|
24
|
+
const metadata = this.computeMetadata(route);
|
|
25
|
+
binaryInsert(this.routes, metadata, (route) => route.score);
|
|
26
|
+
}
|
|
27
|
+
group(options) {
|
|
28
|
+
return {
|
|
29
|
+
route: (route) => {
|
|
30
|
+
const path = options.prefix ? `${options.prefix}${route.path}` : route.path;
|
|
31
|
+
const handler = async (context) =>
|
|
32
|
+
// eslint-disable-next-line @typescript-eslint/no-unsafe-argument
|
|
33
|
+
options.middleware(route.handler, context);
|
|
34
|
+
this.route({ ...route, path, handler });
|
|
35
|
+
},
|
|
36
|
+
group: (group) => {
|
|
37
|
+
const prefix = options.prefix ? `${options.prefix}${group.prefix}` : group.prefix;
|
|
38
|
+
const middleware = pipe(options.middleware, group.middleware);
|
|
39
|
+
return this.group({ prefix, middleware });
|
|
40
|
+
},
|
|
41
|
+
};
|
|
42
|
+
}
|
|
43
|
+
matchingRouteWithMetadata(request) {
|
|
44
|
+
this.regex ??= this.compileRegex();
|
|
45
|
+
const match = this.regex.exec(request.path);
|
|
46
|
+
if (!match)
|
|
47
|
+
return;
|
|
48
|
+
const matchIndex = match.findLastIndex(Boolean) - 1;
|
|
49
|
+
return this.routes[matchIndex];
|
|
50
|
+
}
|
|
51
|
+
computeMetadata(route) {
|
|
52
|
+
const score = this.computeScore(route.path);
|
|
53
|
+
const regex = this.pathToRegex(route.path);
|
|
54
|
+
const capturingRegex = new RegExp(this.pathToCapturingRegex(route.path));
|
|
55
|
+
return { route, regex, score, capturingRegex };
|
|
56
|
+
}
|
|
57
|
+
computeScore(path) {
|
|
58
|
+
let score = 0;
|
|
59
|
+
for (const c of path) {
|
|
60
|
+
if (c === ':') {
|
|
61
|
+
score += 1;
|
|
62
|
+
}
|
|
63
|
+
else if (c === '/') {
|
|
64
|
+
score += 2;
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
return score;
|
|
68
|
+
}
|
|
69
|
+
pathToRegex(path) {
|
|
70
|
+
return ('^(' +
|
|
71
|
+
path
|
|
72
|
+
.replace(/([.+?^=!:${}()[\]|/\\])/g, '\\$1')
|
|
73
|
+
.replace(/\\:([a-zA-Z0-9_]+)\*/g, '(?:.*)')
|
|
74
|
+
.replace(/\\\*/g, '(?:.*)')
|
|
75
|
+
.replace(/\\:([a-zA-Z0-9_]+)/g, '(?:[^/]+)') +
|
|
76
|
+
')$');
|
|
77
|
+
}
|
|
78
|
+
pathToCapturingRegex(path) {
|
|
79
|
+
return ('^' +
|
|
80
|
+
path
|
|
81
|
+
.replace(/([.+?^=!:${}()[\]|/\\])/g, '\\$1')
|
|
82
|
+
.replace(/\\:([a-zA-Z0-9_]+)\*/g, '(?<$1>.*)')
|
|
83
|
+
.replace(/\\\*/g, '(?:.*)')
|
|
84
|
+
.replace(/\\:([a-zA-Z0-9_]+)/g, '(?<$1>[^/]+)') +
|
|
85
|
+
'$');
|
|
86
|
+
}
|
|
87
|
+
compileRegex() {
|
|
88
|
+
if (this.routes.length === 0)
|
|
89
|
+
return new RegExp('$^');
|
|
90
|
+
const regex = this.routes.map((route) => route.regex).join('|');
|
|
91
|
+
return new RegExp(regex);
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
function binaryInsert(array, value, score) {
|
|
95
|
+
let low = 0;
|
|
96
|
+
let high = array.length;
|
|
97
|
+
while (low < high) {
|
|
98
|
+
const mid = Math.floor((low + high) / 2);
|
|
99
|
+
if (score(value) < score(array[mid])) {
|
|
100
|
+
low = mid + 1;
|
|
101
|
+
}
|
|
102
|
+
else {
|
|
103
|
+
high = mid;
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
array.splice(low, 0, value);
|
|
107
|
+
return low;
|
|
108
|
+
}
|
|
109
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,IAAI,EAAmB,MAAM,cAAc,CAAC;AA6CrD,MAAM,OAAO,MAAM;IACA,QAAQ,CAAU;IAClB,UAAU,CAAsB;IAEzC,MAAM,GAA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CAAC;IACJ,CAAC;IAEO,YAAY;QAClB,IAAI,IAAI,CAAC,MAAM,CAAC,MAAM,KAAK,CAAC;YAAE,OAAO,IAAI,MAAM,CAAC,IAAI,CAAC,CAAC;QACtD,MAAM,KAAK,GAAG,IAAI,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;QAChE,OAAO,IAAI,MAAM,CAAC,KAAK,CAAC,CAAC;IAC3B,CAAC;CACF;AAED,SAAS,YAAY,CAAI,KAAU,EAAE,KAAQ,EAAE,KAA2B;IACxE,IAAI,GAAG,GAAG,CAAC,CAAC;IACZ,IAAI,IAAI,GAAG,KAAK,CAAC,MAAM,CAAC;IAExB,OAAO,GAAG,GAAG,IAAI,EAAE,CAAC;QAClB,MAAM,GAAG,GAAG,IAAI,CAAC,KAAK,CAAC,CAAC,GAAG,GAAG,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC;QAEzC,IAAI,KAAK,CAAC,KAAK,CAAC,GAAG,KAAK,CAAC,KAAK,CAAC,GAAG,CAAE,CAAC,EAAE,CAAC;YACtC,GAAG,GAAG,GAAG,GAAG,CAAC,CAAC;QAChB,CAAC;aAAM,CAAC;YACN,IAAI,GAAG,GAAG,CAAC;QACb,CAAC;IACH,CAAC;IAED,KAAK,CAAC,MAAM,CAAC,GAAG,EAAE,CAAC,EAAE,KAAK,CAAC,CAAC;IAC5B,OAAO,GAAG,CAAC;AACb,CAAC"}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import { type Response } from '@glass-cannon/server';
|
|
2
|
+
import type { Middleware } from './index.js';
|
|
3
|
+
import type { RouteContext } from '../index.js';
|
|
4
|
+
export interface ContentTypeOptions {
|
|
5
|
+
allowNoConent?: boolean;
|
|
6
|
+
onInvalidContentType?: (context: RouteContext) => Promise<Response> | Response;
|
|
7
|
+
}
|
|
8
|
+
export declare function text(options?: ContentTypeOptions): Middleware<{
|
|
9
|
+
text: string;
|
|
10
|
+
}>;
|
|
11
|
+
export declare function json(options?: ContentTypeOptions): Middleware<{
|
|
12
|
+
json: unknown;
|
|
13
|
+
}>;
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import { readJson, readText } from '@glass-cannon/server';
|
|
2
|
+
export function text(options) {
|
|
3
|
+
const allowNoContent = options?.allowNoConent ?? true;
|
|
4
|
+
const onInvalidContentType = options?.onInvalidContentType ?? (() => ({ status: 415 }));
|
|
5
|
+
return async (handler, context) => {
|
|
6
|
+
const contentType = context.headers.get('Content-Type');
|
|
7
|
+
if (!contentType) {
|
|
8
|
+
if (allowNoContent) {
|
|
9
|
+
return await handler({ ...context, text: '' });
|
|
10
|
+
}
|
|
11
|
+
else {
|
|
12
|
+
return await onInvalidContentType(context);
|
|
13
|
+
}
|
|
14
|
+
}
|
|
15
|
+
if (!contentType.startsWith('text/plain'))
|
|
16
|
+
return await onInvalidContentType(context);
|
|
17
|
+
const charsetMatch = /charset=([^;]*)/i.exec(contentType);
|
|
18
|
+
const encoding = (charsetMatch?.[1]?.trim().toLowerCase() ?? 'utf-8');
|
|
19
|
+
const text = await readText(context.body, encoding);
|
|
20
|
+
return await handler({ ...context, text });
|
|
21
|
+
};
|
|
22
|
+
}
|
|
23
|
+
export function json(options) {
|
|
24
|
+
const allowNoContent = options?.allowNoConent ?? true;
|
|
25
|
+
const onInvalidContentType = options?.onInvalidContentType ?? (() => ({ status: 415 }));
|
|
26
|
+
return async (handler, context) => {
|
|
27
|
+
const contentType = context.headers.get('Content-Type');
|
|
28
|
+
if (!contentType) {
|
|
29
|
+
if (allowNoContent) {
|
|
30
|
+
return await handler({ ...context, json: undefined });
|
|
31
|
+
}
|
|
32
|
+
else {
|
|
33
|
+
return await onInvalidContentType(context);
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
if (!contentType.startsWith('application/json'))
|
|
37
|
+
return await onInvalidContentType(context);
|
|
38
|
+
const json = await readJson(context.body, 'utf-8');
|
|
39
|
+
return await handler({ ...context, json });
|
|
40
|
+
};
|
|
41
|
+
}
|
|
42
|
+
//# sourceMappingURL=contentType.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"contentType.js","sourceRoot":"","sources":["../../src/middleware/contentType.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,QAAQ,EAAiB,MAAM,sBAAsB,CAAC;AASzE,MAAM,UAAU,IAAI,CAAC,OAA4B;IAC/C,MAAM,cAAc,GAAG,OAAO,EAAE,aAAa,IAAI,IAAI,CAAC;IACtD,MAAM,oBAAoB,GAAG,OAAO,EAAE,oBAAoB,IAAI,CAAC,GAAG,EAAE,CAAC,CAAC,EAAE,MAAM,EAAE,GAAG,EAAE,CAAC,CAAC,CAAC;IAExF,OAAO,KAAK,EAAE,OAAO,EAAE,OAAO,EAAE,EAAE;QAChC,MAAM,WAAW,GAAG,OAAO,CAAC,OAAO,CAAC,GAAG,CAAC,cAAc,CAAC,CAAC;QACxD,IAAI,CAAC,WAAW,EAAE,CAAC;YACjB,IAAI,cAAc,EAAE,CAAC;gBACnB,OAAO,MAAM,OAAO,CAAC,EAAE,GAAG,OAAO,EAAE,IAAI,EAAE,EAAE,EAAE,CAAC,CAAC;YACjD,CAAC;iBAAM,CAAC;gBACN,OAAO,MAAM,oBAAoB,CAAC,OAAO,CAAC,CAAC;YAC7C,CAAC;QACH,CAAC;QAED,IAAI,CAAC,WAAW,CAAC,UAAU,CAAC,YAAY,CAAC;YAAE,OAAO,MAAM,oBAAoB,CAAC,OAAO,CAAC,CAAC;QACtF,MAAM,YAAY,GAAG,kBAAkB,CAAC,IAAI,CAAC,WAAW,CAAC,CAAC;QAC1D,MAAM,QAAQ,GAAG,CAAC,YAAY,EAAE,CAAC,CAAC,CAAC,EAAE,IAAI,EAAE,CAAC,WAAW,EAAE,IAAI,OAAO,CAAmB,CAAC;QACxF,MAAM,IAAI,GAAG,MAAM,QAAQ,CAAC,OAAO,CAAC,IAAI,EAAE,QAAQ,CAAC,CAAC;QACpD,OAAO,MAAM,OAAO,CAAC,EAAE,GAAG,OAAO,EAAE,IAAI,EAAE,CAAC,CAAC;IAC7C,CAAC,CAAC;AACJ,CAAC;AAED,MAAM,UAAU,IAAI,CAAC,OAA4B;IAC/C,MAAM,cAAc,GAAG,OAAO,EAAE,aAAa,IAAI,IAAI,CAAC;IACtD,MAAM,oBAAoB,GAAG,OAAO,EAAE,oBAAoB,IAAI,CAAC,GAAG,EAAE,CAAC,CAAC,EAAE,MAAM,EAAE,GAAG,EAAE,CAAC,CAAC,CAAC;IAExF,OAAO,KAAK,EAAE,OAAO,EAAE,OAAO,EAAE,EAAE;QAChC,MAAM,WAAW,GAAG,OAAO,CAAC,OAAO,CAAC,GAAG,CAAC,cAAc,CAAC,CAAC;QACxD,IAAI,CAAC,WAAW,EAAE,CAAC;YACjB,IAAI,cAAc,EAAE,CAAC;gBACnB,OAAO,MAAM,OAAO,CAAC,EAAE,GAAG,OAAO,EAAE,IAAI,EAAE,SAAS,EAAE,CAAC,CAAC;YACxD,CAAC;iBAAM,CAAC;gBACN,OAAO,MAAM,oBAAoB,CAAC,OAAO,CAAC,CAAC;YAC7C,CAAC;QACH,CAAC;QAED,IAAI,CAAC,WAAW,CAAC,UAAU,CAAC,kBAAkB,CAAC;YAAE,OAAO,MAAM,oBAAoB,CAAC,OAAO,CAAC,CAAC;QAC5F,MAAM,IAAI,GAAG,MAAM,QAAQ,CAAC,OAAO,CAAC,IAAI,EAAE,OAAO,CAAC,CAAC;QACnD,OAAO,MAAM,OAAO,CAAC,EAAE,GAAG,OAAO,EAAE,IAAI,EAAE,CAAC,CAAC;IAC7C,CAAC,CAAC;AACJ,CAAC"}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import type { Response } from '@glass-cannon/server';
|
|
2
|
+
import type { RouteContext, RouteHandler } from '../index.js';
|
|
3
|
+
export type Middleware<T = unknown> = (handler: RouteHandler<T>, request: RouteContext) => Promise<Response> | Response;
|
|
4
|
+
export type PipeMiddlewares<Middlewares extends Middleware[]> = Middlewares extends [
|
|
5
|
+
infer First,
|
|
6
|
+
...infer Rest
|
|
7
|
+
] ? First extends Middleware<infer FirstContext> ? Rest extends Middleware[] ? PipeMiddlewares<Rest> extends Middleware<infer RestContext> ? Middleware<FirstContext & RestContext> : never : never : never : Middleware;
|
|
8
|
+
export declare function pipe<Middlewares extends Middleware[]>(...middlewares: Middlewares): PipeMiddlewares<Middlewares>;
|
|
9
|
+
export declare const authenticated: Middleware<{
|
|
10
|
+
accessToken: string;
|
|
11
|
+
}>;
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
export function pipe(...middlewares) {
|
|
2
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
3
|
+
return ((handler, request) => {
|
|
4
|
+
// eslint-disable-next-line @typescript-eslint/no-unsafe-return
|
|
5
|
+
return middlewares.reduceRight((acc, middleware) => {
|
|
6
|
+
// eslint-disable-next-line @typescript-eslint/no-unsafe-argument
|
|
7
|
+
return middleware(acc, request);
|
|
8
|
+
}, handler);
|
|
9
|
+
});
|
|
10
|
+
}
|
|
11
|
+
export const authenticated = async (handler, request) => {
|
|
12
|
+
const accessToken = request.headers.get('Authorization')?.split(' ')[1];
|
|
13
|
+
if (!accessToken)
|
|
14
|
+
throw new Error('Unauthorized');
|
|
15
|
+
return await handler({ ...request, accessToken });
|
|
16
|
+
};
|
|
17
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/middleware/index.ts"],"names":[],"mappings":"AAqBA,MAAM,UAAU,IAAI,CAClB,GAAG,WAAwB;IAE3B,8DAA8D;IAC9D,OAAO,CAAC,CAAC,OAAY,EAAE,OAAY,EAAE,EAAE;QACrC,+DAA+D;QAC/D,OAAO,WAAW,CAAC,WAAW,CAAC,CAAC,GAAG,EAAE,UAAU,EAAE,EAAE;YACjD,iEAAiE;YACjE,OAAO,UAAU,CAAC,GAAG,EAAE,OAAO,CAAC,CAAC;QAClC,CAAC,EAAE,OAAO,CAAC,CAAC;IACd,CAAC,CAA4C,CAAC;AAChD,CAAC;AAED,MAAM,CAAC,MAAM,aAAa,GAAwC,KAAK,EAAE,OAAO,EAAE,OAAO,EAAE,EAAE;IAC3F,MAAM,WAAW,GAAG,OAAO,CAAC,OAAO,CAAC,GAAG,CAAC,eAAe,CAAC,EAAE,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC;IACxE,IAAI,CAAC,WAAW;QAAE,MAAM,IAAI,KAAK,CAAC,cAAc,CAAC,CAAC;IAClD,OAAO,MAAM,OAAO,CAAC,EAAE,GAAG,OAAO,EAAE,WAAW,EAAE,CAAC,CAAC;AACpD,CAAC,CAAC"}
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@glass-cannon/router",
|
|
3
3
|
"type": "module",
|
|
4
|
-
"version": "0.0.
|
|
4
|
+
"version": "0.0.3",
|
|
5
5
|
"exports": {
|
|
6
6
|
".": {
|
|
7
7
|
"import": "./dist/index.js",
|
|
@@ -16,6 +16,7 @@
|
|
|
16
16
|
"types": "./dist/middleware/contentType.d.ts"
|
|
17
17
|
}
|
|
18
18
|
},
|
|
19
|
+
"files": ["dist"],
|
|
19
20
|
"dependencies": {
|
|
20
21
|
"@glass-cannon/server": "^0.0.1"
|
|
21
22
|
},
|
package/src/index.ts
DELETED
|
@@ -1,177 +0,0 @@
|
|
|
1
|
-
/* eslint-disable @typescript-eslint/no-explicit-any */
|
|
2
|
-
import type { Handler, Request, Response } from '@glass-cannon/server';
|
|
3
|
-
import { pipe, type Middleware } from './middleware';
|
|
4
|
-
|
|
5
|
-
export type RouteHandler<Context> = (
|
|
6
|
-
request: RouteContext & Context
|
|
7
|
-
) => Promise<Response> | Response;
|
|
8
|
-
|
|
9
|
-
export type RouteContext = Request & {
|
|
10
|
-
params: Record<string, string>;
|
|
11
|
-
route: Route<any>;
|
|
12
|
-
};
|
|
13
|
-
|
|
14
|
-
export interface Route<Context> {
|
|
15
|
-
method?: string;
|
|
16
|
-
path: string;
|
|
17
|
-
handler: RouteHandler<Context>;
|
|
18
|
-
}
|
|
19
|
-
|
|
20
|
-
export interface RouterGroup<Context> {
|
|
21
|
-
route(options: RouteOptions<Context>): void;
|
|
22
|
-
group<NewContext>(options: GroupOptions<NewContext>): RouterGroup<Context & NewContext>;
|
|
23
|
-
}
|
|
24
|
-
|
|
25
|
-
export interface RouterOptions<Context = unknown> {
|
|
26
|
-
fallback?: Handler;
|
|
27
|
-
middleware?: Middleware<Context>;
|
|
28
|
-
}
|
|
29
|
-
|
|
30
|
-
export interface RouteOptions<Context> {
|
|
31
|
-
method?: string;
|
|
32
|
-
path: string;
|
|
33
|
-
handler: RouteHandler<Context>;
|
|
34
|
-
}
|
|
35
|
-
|
|
36
|
-
export interface GroupOptions<Context> {
|
|
37
|
-
prefix?: string;
|
|
38
|
-
middleware: Middleware<Context>;
|
|
39
|
-
}
|
|
40
|
-
|
|
41
|
-
interface RouteWithMetadata<Context> {
|
|
42
|
-
route: Route<Context>;
|
|
43
|
-
regex: string;
|
|
44
|
-
score: number;
|
|
45
|
-
capturingRegex: RegExp;
|
|
46
|
-
}
|
|
47
|
-
|
|
48
|
-
export class Router<Context = unknown> implements RouterGroup<Context> {
|
|
49
|
-
private readonly fallback: Handler;
|
|
50
|
-
private readonly middleware: Middleware<Context>;
|
|
51
|
-
|
|
52
|
-
private routes: RouteWithMetadata<Context>[] = [];
|
|
53
|
-
private regex: RegExp | undefined;
|
|
54
|
-
|
|
55
|
-
constructor(options?: RouterOptions<Context>) {
|
|
56
|
-
this.fallback = options?.fallback ?? (() => ({ status: 404 }));
|
|
57
|
-
this.middleware = options?.middleware ?? ((x): any => x);
|
|
58
|
-
}
|
|
59
|
-
|
|
60
|
-
matchingRoute(request: Pick<Request, 'method' | 'path'>): Route<Context> | undefined {
|
|
61
|
-
return this.matchingRouteWithMetadata(request)?.route;
|
|
62
|
-
}
|
|
63
|
-
|
|
64
|
-
handle: Handler = async (request) => {
|
|
65
|
-
const routeWithMetadata = this.matchingRouteWithMetadata(request);
|
|
66
|
-
|
|
67
|
-
if (!routeWithMetadata) return await this.fallback(request);
|
|
68
|
-
|
|
69
|
-
const { route, capturingRegex } = routeWithMetadata;
|
|
70
|
-
|
|
71
|
-
const params = { ...capturingRegex.exec(request.path)!.groups };
|
|
72
|
-
const context = { ...request, params, route };
|
|
73
|
-
return await this.middleware(route.handler, context);
|
|
74
|
-
};
|
|
75
|
-
|
|
76
|
-
route(route: RouteOptions<Context>): void {
|
|
77
|
-
const metadata = this.computeMetadata(route);
|
|
78
|
-
binaryInsert(this.routes, metadata, (route) => route.score);
|
|
79
|
-
}
|
|
80
|
-
|
|
81
|
-
group<NewContext>(options: GroupOptions<NewContext>): RouterGroup<Context & NewContext> {
|
|
82
|
-
return {
|
|
83
|
-
route: (route) => {
|
|
84
|
-
const path = options.prefix ? `${options.prefix}${route.path}` : route.path;
|
|
85
|
-
const handler: RouteHandler<Context> = async (context) =>
|
|
86
|
-
// eslint-disable-next-line @typescript-eslint/no-unsafe-argument
|
|
87
|
-
options.middleware(route.handler as any, context);
|
|
88
|
-
this.route({ ...route, path, handler });
|
|
89
|
-
},
|
|
90
|
-
group: (group) => {
|
|
91
|
-
const prefix = options.prefix ? `${options.prefix}${group.prefix}` : group.prefix;
|
|
92
|
-
const middleware = pipe(options.middleware, group.middleware);
|
|
93
|
-
return this.group({ prefix, middleware });
|
|
94
|
-
},
|
|
95
|
-
};
|
|
96
|
-
}
|
|
97
|
-
|
|
98
|
-
private matchingRouteWithMetadata(
|
|
99
|
-
request: Pick<Request, 'method' | 'path'>
|
|
100
|
-
): RouteWithMetadata<Context> | undefined {
|
|
101
|
-
this.regex ??= this.compileRegex();
|
|
102
|
-
const match = this.regex.exec(request.path);
|
|
103
|
-
|
|
104
|
-
if (!match) return;
|
|
105
|
-
|
|
106
|
-
const matchIndex = match.findLastIndex(Boolean) - 1;
|
|
107
|
-
return this.routes[matchIndex];
|
|
108
|
-
}
|
|
109
|
-
|
|
110
|
-
private computeMetadata(route: Route<Context>): RouteWithMetadata<Context> {
|
|
111
|
-
const score = this.computeScore(route.path);
|
|
112
|
-
const regex = this.pathToRegex(route.path);
|
|
113
|
-
const capturingRegex = new RegExp(this.pathToCapturingRegex(route.path));
|
|
114
|
-
|
|
115
|
-
return { route, regex, score, capturingRegex };
|
|
116
|
-
}
|
|
117
|
-
|
|
118
|
-
private computeScore(path: string): number {
|
|
119
|
-
let score = 0;
|
|
120
|
-
for (const c of path) {
|
|
121
|
-
if (c === ':') {
|
|
122
|
-
score += 1;
|
|
123
|
-
} else if (c === '/') {
|
|
124
|
-
score += 2;
|
|
125
|
-
}
|
|
126
|
-
}
|
|
127
|
-
return score;
|
|
128
|
-
}
|
|
129
|
-
|
|
130
|
-
private pathToRegex(path: string): string {
|
|
131
|
-
return (
|
|
132
|
-
'^(' +
|
|
133
|
-
path
|
|
134
|
-
.replace(/([.+?^=!:${}()[\]|/\\])/g, '\\$1')
|
|
135
|
-
.replace(/\\:([a-zA-Z0-9_]+)\*/g, '(?:.*)')
|
|
136
|
-
.replace(/\\\*/g, '(?:.*)')
|
|
137
|
-
.replace(/\\:([a-zA-Z0-9_]+)/g, '(?:[^/]+)') +
|
|
138
|
-
')$'
|
|
139
|
-
);
|
|
140
|
-
}
|
|
141
|
-
|
|
142
|
-
private pathToCapturingRegex(path: string): string {
|
|
143
|
-
return (
|
|
144
|
-
'^' +
|
|
145
|
-
path
|
|
146
|
-
.replace(/([.+?^=!:${}()[\]|/\\])/g, '\\$1')
|
|
147
|
-
.replace(/\\:([a-zA-Z0-9_]+)\*/g, '(?<$1>.*)')
|
|
148
|
-
.replace(/\\\*/g, '(?:.*)')
|
|
149
|
-
.replace(/\\:([a-zA-Z0-9_]+)/g, '(?<$1>[^/]+)') +
|
|
150
|
-
'$'
|
|
151
|
-
);
|
|
152
|
-
}
|
|
153
|
-
|
|
154
|
-
private compileRegex(): RegExp {
|
|
155
|
-
if (this.routes.length === 0) return new RegExp('$^');
|
|
156
|
-
const regex = this.routes.map((route) => route.regex).join('|');
|
|
157
|
-
return new RegExp(regex);
|
|
158
|
-
}
|
|
159
|
-
}
|
|
160
|
-
|
|
161
|
-
function binaryInsert<T>(array: T[], value: T, score: (route: T) => number): number {
|
|
162
|
-
let low = 0;
|
|
163
|
-
let high = array.length;
|
|
164
|
-
|
|
165
|
-
while (low < high) {
|
|
166
|
-
const mid = Math.floor((low + high) / 2);
|
|
167
|
-
|
|
168
|
-
if (score(value) < score(array[mid]!)) {
|
|
169
|
-
low = mid + 1;
|
|
170
|
-
} else {
|
|
171
|
-
high = mid;
|
|
172
|
-
}
|
|
173
|
-
}
|
|
174
|
-
|
|
175
|
-
array.splice(low, 0, value);
|
|
176
|
-
return low;
|
|
177
|
-
}
|
|
@@ -1,50 +0,0 @@
|
|
|
1
|
-
import { readJson, readText, type Response } from '@glass-cannon/server';
|
|
2
|
-
import type { Middleware } from '.';
|
|
3
|
-
import type { RouteContext } from '..';
|
|
4
|
-
|
|
5
|
-
export interface ContentTypeOptions {
|
|
6
|
-
allowNoConent?: boolean;
|
|
7
|
-
onInvalidContentType?: (context: RouteContext) => Promise<Response> | Response;
|
|
8
|
-
}
|
|
9
|
-
|
|
10
|
-
export function text(options?: ContentTypeOptions): Middleware<{ text: string }> {
|
|
11
|
-
const allowNoContent = options?.allowNoConent ?? true;
|
|
12
|
-
const onInvalidContentType = options?.onInvalidContentType ?? (() => ({ status: 415 }));
|
|
13
|
-
|
|
14
|
-
return async (handler, context) => {
|
|
15
|
-
const contentType = context.headers.get('Content-Type');
|
|
16
|
-
if (!contentType) {
|
|
17
|
-
if (allowNoContent) {
|
|
18
|
-
return await handler({ ...context, text: '' });
|
|
19
|
-
} else {
|
|
20
|
-
return await onInvalidContentType(context);
|
|
21
|
-
}
|
|
22
|
-
}
|
|
23
|
-
|
|
24
|
-
if (!contentType.startsWith('text/plain')) return await onInvalidContentType(context);
|
|
25
|
-
const charsetMatch = /charset=([^;]*)/i.exec(contentType);
|
|
26
|
-
const encoding = (charsetMatch?.[1]?.trim().toLowerCase() ?? 'utf-8') as BufferEncoding;
|
|
27
|
-
const text = await readText(context.body, encoding);
|
|
28
|
-
return await handler({ ...context, text });
|
|
29
|
-
};
|
|
30
|
-
}
|
|
31
|
-
|
|
32
|
-
export function json(options?: ContentTypeOptions): Middleware<{ json: unknown }> {
|
|
33
|
-
const allowNoContent = options?.allowNoConent ?? true;
|
|
34
|
-
const onInvalidContentType = options?.onInvalidContentType ?? (() => ({ status: 415 }));
|
|
35
|
-
|
|
36
|
-
return async (handler, context) => {
|
|
37
|
-
const contentType = context.headers.get('Content-Type');
|
|
38
|
-
if (!contentType) {
|
|
39
|
-
if (allowNoContent) {
|
|
40
|
-
return await handler({ ...context, json: undefined });
|
|
41
|
-
} else {
|
|
42
|
-
return await onInvalidContentType(context);
|
|
43
|
-
}
|
|
44
|
-
}
|
|
45
|
-
|
|
46
|
-
if (!contentType.startsWith('application/json')) return await onInvalidContentType(context);
|
|
47
|
-
const json = await readJson(context.body, 'utf-8');
|
|
48
|
-
return await handler({ ...context, json });
|
|
49
|
-
};
|
|
50
|
-
}
|
package/src/middleware/index.ts
DELETED
|
@@ -1,39 +0,0 @@
|
|
|
1
|
-
import type { Response } from '@glass-cannon/server';
|
|
2
|
-
import type { RouteContext, RouteHandler } from '..';
|
|
3
|
-
|
|
4
|
-
export type Middleware<T = unknown> = (
|
|
5
|
-
handler: RouteHandler<T>,
|
|
6
|
-
request: RouteContext
|
|
7
|
-
) => Promise<Response> | Response;
|
|
8
|
-
|
|
9
|
-
export type PipeMiddlewares<Middlewares extends Middleware[]> = Middlewares extends [
|
|
10
|
-
infer First,
|
|
11
|
-
...infer Rest,
|
|
12
|
-
]
|
|
13
|
-
? First extends Middleware<infer FirstContext>
|
|
14
|
-
? Rest extends Middleware[]
|
|
15
|
-
? PipeMiddlewares<Rest> extends Middleware<infer RestContext>
|
|
16
|
-
? Middleware<FirstContext & RestContext>
|
|
17
|
-
: never
|
|
18
|
-
: never
|
|
19
|
-
: never
|
|
20
|
-
: Middleware;
|
|
21
|
-
|
|
22
|
-
export function pipe<Middlewares extends Middleware[]>(
|
|
23
|
-
...middlewares: Middlewares
|
|
24
|
-
): PipeMiddlewares<Middlewares> {
|
|
25
|
-
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
26
|
-
return ((handler: any, request: any) => {
|
|
27
|
-
// eslint-disable-next-line @typescript-eslint/no-unsafe-return
|
|
28
|
-
return middlewares.reduceRight((acc, middleware) => {
|
|
29
|
-
// eslint-disable-next-line @typescript-eslint/no-unsafe-argument
|
|
30
|
-
return middleware(acc, request);
|
|
31
|
-
}, handler);
|
|
32
|
-
}) as unknown as PipeMiddlewares<Middlewares>;
|
|
33
|
-
}
|
|
34
|
-
|
|
35
|
-
export const authenticated: Middleware<{ accessToken: string }> = async (handler, request) => {
|
|
36
|
-
const accessToken = request.headers.get('Authorization')?.split(' ')[1];
|
|
37
|
-
if (!accessToken) throw new Error('Unauthorized');
|
|
38
|
-
return await handler({ ...request, accessToken });
|
|
39
|
-
};
|