@glass-cannon/router 0.0.2 → 0.0.4

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.
@@ -0,0 +1,48 @@
1
+ import type { Handler, Request, Response } from '@glass-cannon/server';
2
+ import { type Middleware } from './middleware/index.js';
3
+ type StringWithSuggestions<T> = T | (string & {});
4
+ export type RouteHandler<Context> = (request: RouteContext & Context) => Promise<Response> | Response;
5
+ export type RouteContext = Request & {
6
+ params: Record<string, string>;
7
+ route: Route<any>;
8
+ };
9
+ export interface Route<Context> {
10
+ method?: string;
11
+ path: string;
12
+ handler: RouteHandler<Context>;
13
+ }
14
+ export interface RouterGroup<Context> {
15
+ route(options: RouteOptions<Context>): void;
16
+ group<NewContext>(options: GroupOptions<NewContext>): RouterGroup<Context & NewContext>;
17
+ }
18
+ export interface RouterOptions<Context = unknown> {
19
+ fallback?: Handler;
20
+ middleware?: Middleware<Context>;
21
+ }
22
+ export interface RouteOptions<Context> {
23
+ method?: StringWithSuggestions<'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH' | 'OPTIONS'>;
24
+ path: string;
25
+ handler: RouteHandler<Context>;
26
+ }
27
+ export interface GroupOptions<Context> {
28
+ prefix?: string;
29
+ middleware: Middleware<Context>;
30
+ }
31
+ export declare class Router<Context = unknown> implements RouterGroup<Context> {
32
+ private readonly fallback;
33
+ private readonly middleware;
34
+ private routes;
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 matchingGeneralRouteWithMetadata;
42
+ private computeMetadata;
43
+ private computeScore;
44
+ private pathToRegex;
45
+ private pathToCapturingRegex;
46
+ private compileRegex;
47
+ }
48
+ export {};
package/dist/index.js ADDED
@@ -0,0 +1,125 @@
1
+ import { pipe } from './middleware/index.js';
2
+ const ALL_METHODS = '*';
3
+ export class Router {
4
+ fallback;
5
+ middleware;
6
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
7
+ routes = Object.create(null);
8
+ constructor(options) {
9
+ this.fallback = options?.fallback ?? (() => ({ status: 404 }));
10
+ this.middleware = options?.middleware ?? ((x) => x);
11
+ }
12
+ matchingRoute(request) {
13
+ return this.matchingRouteWithMetadata(request)?.route;
14
+ }
15
+ handle = async (request) => {
16
+ const routeWithMetadata = this.matchingRouteWithMetadata(request);
17
+ if (!routeWithMetadata)
18
+ return await this.fallback(request);
19
+ const { route, capturingRegex } = routeWithMetadata;
20
+ const params = { ...capturingRegex.exec(request.path).groups };
21
+ const context = { ...request, params, route };
22
+ return await this.middleware(route.handler, context);
23
+ };
24
+ route(route) {
25
+ const metadata = this.computeMetadata(route);
26
+ const method = route.method ?? ALL_METHODS;
27
+ this.routes[method] ??= [[], undefined];
28
+ binaryInsert(this.routes[method][0], metadata, (route) => route.score);
29
+ this.routes[method][1] = undefined;
30
+ }
31
+ group(options) {
32
+ return {
33
+ route: (route) => {
34
+ const path = options.prefix ? `${options.prefix}${route.path}` : route.path;
35
+ const handler = async (context) =>
36
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-argument
37
+ options.middleware(route.handler, context);
38
+ this.route({ ...route, path, handler });
39
+ },
40
+ group: (group) => {
41
+ const prefix = options.prefix ? `${options.prefix}${group.prefix}` : group.prefix;
42
+ const middleware = pipe(options.middleware, group.middleware);
43
+ return this.group({ prefix, middleware });
44
+ },
45
+ };
46
+ }
47
+ matchingRouteWithMetadata(request) {
48
+ const routes = this.routes[request.method];
49
+ if (!routes)
50
+ return this.matchingGeneralRouteWithMetadata(request);
51
+ routes[1] ??= this.compileRegex(request.method);
52
+ const match = routes[1].exec(request.path);
53
+ if (!match)
54
+ return this.matchingGeneralRouteWithMetadata(request);
55
+ const matchIndex = match.findLastIndex(Boolean) - 1;
56
+ return routes[0][matchIndex];
57
+ }
58
+ matchingGeneralRouteWithMetadata(request) {
59
+ const routes = this.routes[ALL_METHODS];
60
+ if (!routes)
61
+ return;
62
+ routes[1] ??= this.compileRegex(request.method);
63
+ const match = routes[1].exec(request.path);
64
+ if (!match)
65
+ return;
66
+ const matchIndex = match.findLastIndex(Boolean) - 1;
67
+ return routes[0][matchIndex];
68
+ }
69
+ computeMetadata(route) {
70
+ const score = this.computeScore(route.path);
71
+ const regex = this.pathToRegex(route.path);
72
+ const capturingRegex = new RegExp(this.pathToCapturingRegex(route.path));
73
+ return { route, regex, score, capturingRegex };
74
+ }
75
+ computeScore(path) {
76
+ let score = 0;
77
+ for (const c of path) {
78
+ if (c === ':') {
79
+ score += 1;
80
+ }
81
+ else if (c === '/') {
82
+ score += 2;
83
+ }
84
+ }
85
+ return score;
86
+ }
87
+ pathToRegex(path) {
88
+ return ('^(' +
89
+ path
90
+ .replace(/([.+?^=!:${}()[\]|/\\])/g, '\\$1')
91
+ .replace(/\\:([a-zA-Z0-9_]+)\*/g, '(?:.*)')
92
+ .replace(/\\\*/g, '(?:.*)')
93
+ .replace(/\\:([a-zA-Z0-9_]+)/g, '(?:[^/]+)') +
94
+ ')$');
95
+ }
96
+ pathToCapturingRegex(path) {
97
+ return ('^' +
98
+ path
99
+ .replace(/([.+?^=!:${}()[\]|/\\])/g, '\\$1')
100
+ .replace(/\\:([a-zA-Z0-9_]+)\*/g, '(?<$1>.*)')
101
+ .replace(/\\\*/g, '(?:.*)')
102
+ .replace(/\\:([a-zA-Z0-9_]+)/g, '(?<$1>[^/]+)') +
103
+ '$');
104
+ }
105
+ compileRegex(method) {
106
+ const regex = this.routes[method][0].map((route) => route.regex).join('|');
107
+ return new RegExp(regex);
108
+ }
109
+ }
110
+ function binaryInsert(array, value, score) {
111
+ let low = 0;
112
+ let high = array.length;
113
+ while (low < high) {
114
+ const mid = Math.floor((low + high) / 2);
115
+ if (score(value) < score(array[mid])) {
116
+ low = mid + 1;
117
+ }
118
+ else {
119
+ high = mid;
120
+ }
121
+ }
122
+ array.splice(low, 0, value);
123
+ return low;
124
+ }
125
+ //# 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;AAErD,MAAM,WAAW,GAAG,GAAG,CAAC;AA8CxB,MAAM,OAAO,MAAM;IACA,QAAQ,CAAU;IAClB,UAAU,CAAsB;IAEjD,mEAAmE;IAC3D,MAAM,GACZ,MAAM,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC;IAEtB,YAAY,OAAgC;QAC1C,IAAI,CAAC,QAAQ,GAAG,OAAO,EAAE,QAAQ,IAAI,CAAC,GAAG,EAAE,CAAC,CAAC,EAAE,MAAM,EAAE,GAAG,EAAE,CAAC,CAAC,CAAC;QAC/D,IAAI,CAAC,UAAU,GAAG,OAAO,EAAE,UAAU,IAAI,CAAC,CAAC,CAAC,EAAO,EAAE,CAAC,CAAC,CAAC,CAAC;IAC3D,CAAC;IAED,aAAa,CAAC,OAAyC;QACrD,OAAO,IAAI,CAAC,yBAAyB,CAAC,OAAO,CAAC,EAAE,KAAK,CAAC;IACxD,CAAC;IAED,MAAM,GAAY,KAAK,EAAE,OAAO,EAAE,EAAE;QAClC,MAAM,iBAAiB,GAAG,IAAI,CAAC,yBAAyB,CAAC,OAAO,CAAC,CAAC;QAElE,IAAI,CAAC,iBAAiB;YAAE,OAAO,MAAM,IAAI,CAAC,QAAQ,CAAC,OAAO,CAAC,CAAC;QAE5D,MAAM,EAAE,KAAK,EAAE,cAAc,EAAE,GAAG,iBAAiB,CAAC;QAEpD,MAAM,MAAM,GAAG,EAAE,GAAG,cAAc,CAAC,IAAI,CAAC,OAAO,CAAC,IAAI,CAAE,CAAC,MAAM,EAAE,CAAC;QAChE,MAAM,OAAO,GAAG,EAAE,GAAG,OAAO,EAAE,MAAM,EAAE,KAAK,EAAE,CAA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AAC,uBAAuB,EAAE,WAAW,CAAC;iBAC7C,OAAO,CAAC,OAAO,EAAE,QAAQ,CAAC;iBAC1B,OAAO,CAAC,qBAAqB,EAAE,cAAc,CAAC;YACjD,GAAG,CACJ,CAAC;IACJ,CAAC;IAEO,YAAY,CAAC,MAAc;QACjC,MAAM,KAAK,GAAG,IAAI,CAAC,MAAM,CAAC,MAAM,CAAE,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;QAC5E,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,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AE,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.2",
4
+ "version": "0.0.4",
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
- }
@@ -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
- };
package/tsconfig.json DELETED
@@ -1,7 +0,0 @@
1
- {
2
- "extends": "../../tsconfig.json",
3
- "compilerOptions": {
4
- "outDir": "dist"
5
- },
6
- "include": ["src"]
7
- }