@prairielearn/express-list-endpoints 1.0.0

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/src/index.ts ADDED
@@ -0,0 +1,219 @@
1
+ import type { Express, Router } from 'express';
2
+
3
+ interface Route {
4
+ methods: object;
5
+ path: string | string[];
6
+ stack: any[];
7
+ }
8
+
9
+ export interface Endpoint {
10
+ path: string;
11
+ methods: string[];
12
+ middlewares: string[];
13
+ }
14
+
15
+ const regExpToParseExpressPathRegExp =
16
+ /^\/\^\\?\/?(?:(:?[\w\\.-]*(?:\\\/:?[\w\\.-]*)*)|(\(\?:\\?\/?\([^)]+\)\)))\\\/.*/;
17
+ const regExpToReplaceExpressPathRegExpParams = /\(\?:\\?\/?\([^)]+\)\)/;
18
+ const regexpExpressParamRegexp = /\(\?:\\?\\?\/?\([^)]+\)\)/g;
19
+ const regexpExpressPathParamRegexp = /(:[^)]+)\([^)]+\)/g;
20
+
21
+ const EXPRESS_ROOT_PATH_REGEXP_VALUE = '/^\\/?(?=\\/|$)/i';
22
+ const STACK_ITEM_VALID_NAMES = ['router', 'bound dispatch', 'mounted_app'];
23
+
24
+ /**
25
+ * Returns all the verbs detected for the passed route
26
+ */
27
+ function getRouteMethods(route: Route) {
28
+ let methods = Object.keys(route.methods);
29
+
30
+ methods = methods.filter((method) => method !== '_all');
31
+ methods = methods.map((method) => method.toUpperCase());
32
+
33
+ return methods;
34
+ }
35
+
36
+ /**
37
+ * Returns the names (or anonymous) of all the middlewares attached to the
38
+ * passed route.
39
+ */
40
+ function getRouteMiddlewares(route: Route): string[] {
41
+ return route.stack.map((item) => {
42
+ return item.handle.name || 'anonymous';
43
+ });
44
+ }
45
+
46
+ /**
47
+ * Returns true if found regexp related with express params.
48
+ */
49
+ function hasParams(expressPathRegExp: string): boolean {
50
+ return regexpExpressParamRegexp.test(expressPathRegExp);
51
+ }
52
+
53
+ /**
54
+ * @param route Express route object to be parsed
55
+ * @param basePath The basePath the route is on
56
+ * @return Endpoints info
57
+ */
58
+ function parseExpressRoute(route: Route, basePath: string): Endpoint[] {
59
+ const paths = [];
60
+
61
+ if (Array.isArray(route.path)) {
62
+ paths.push(...route.path);
63
+ } else {
64
+ paths.push(route.path);
65
+ }
66
+
67
+ const endpoints: Endpoint[] = paths.map((path) => {
68
+ const completePath = basePath && path === '/' ? basePath : `${basePath}${path}`;
69
+
70
+ const endpoint: Endpoint = {
71
+ path: completePath.replace(regexpExpressPathParamRegexp, '$1'),
72
+ methods: getRouteMethods(route),
73
+ middlewares: getRouteMiddlewares(route),
74
+ };
75
+
76
+ return endpoint;
77
+ });
78
+
79
+ return endpoints;
80
+ }
81
+
82
+ function parseExpressPath(expressPathRegExp: RegExp, params: any[]): string {
83
+ let parsedRegExp = expressPathRegExp.toString();
84
+ let expressPathRegExpExec = regExpToParseExpressPathRegExp.exec(parsedRegExp);
85
+ let paramIndex = 0;
86
+
87
+ while (hasParams(parsedRegExp)) {
88
+ const paramName = params[paramIndex].name;
89
+ const paramId = `:${paramName}`;
90
+
91
+ parsedRegExp = parsedRegExp.replace(regExpToReplaceExpressPathRegExpParams, (str) => {
92
+ // Express >= 4.20.0 uses a different RegExp for parameters: it
93
+ // captures the slash as part of the parameter. We need to check
94
+ // for this case and add the slash to the value that will replace
95
+ // the parameter in the path.
96
+ if (str.startsWith('(?:\\/')) {
97
+ return `\\/${paramId}`;
98
+ }
99
+
100
+ return paramId;
101
+ });
102
+
103
+ paramIndex++;
104
+ }
105
+
106
+ if (parsedRegExp !== expressPathRegExp.toString()) {
107
+ expressPathRegExpExec = regExpToParseExpressPathRegExp.exec(parsedRegExp);
108
+ }
109
+
110
+ // TODO: can we do better than this?
111
+ if (!expressPathRegExpExec) {
112
+ throw new Error('Error parsing express path');
113
+ }
114
+
115
+ const parsedPath = expressPathRegExpExec[1].replace(/\\\//g, '/');
116
+
117
+ return parsedPath;
118
+ }
119
+
120
+ function parseEndpoints(
121
+ app: Express | Router | any,
122
+ basePath?: string,
123
+ endpoints?: Endpoint[],
124
+ ): Endpoint[] {
125
+ const stack = app.stack || (app._router && app._router.stack);
126
+
127
+ endpoints = endpoints || [];
128
+ basePath = basePath || '';
129
+
130
+ if (!stack) {
131
+ if (endpoints.length) {
132
+ endpoints = addEndpoints(endpoints, [
133
+ {
134
+ path: basePath,
135
+ methods: [],
136
+ middlewares: [],
137
+ },
138
+ ]);
139
+ }
140
+ } else {
141
+ endpoints = parseStack(stack, basePath, endpoints);
142
+ }
143
+
144
+ return endpoints;
145
+ }
146
+
147
+ /**
148
+ * Ensures the path of the new endpoints isn't yet in the array.
149
+ * If the path is already in the array merges the endpoints with the existing
150
+ * one, if not, it adds them to the array.
151
+ *
152
+ * @param currentEndpoints Array of current endpoints
153
+ * @param endpointsToAdd New endpoints to be added to the array
154
+ * @returns Updated endpoints array
155
+ */
156
+ function addEndpoints(currentEndpoints: Endpoint[], endpointsToAdd: Endpoint[]): Endpoint[] {
157
+ endpointsToAdd.forEach((newEndpoint) => {
158
+ const existingEndpoint = currentEndpoints.find(
159
+ (endpoint) => endpoint.path === newEndpoint.path,
160
+ );
161
+
162
+ if (existingEndpoint !== undefined) {
163
+ const newMethods = newEndpoint.methods.filter(
164
+ (method) => !existingEndpoint.methods.includes(method),
165
+ );
166
+
167
+ existingEndpoint.methods = existingEndpoint.methods.concat(newMethods);
168
+ } else {
169
+ currentEndpoints.push(newEndpoint);
170
+ }
171
+ });
172
+
173
+ return currentEndpoints;
174
+ }
175
+
176
+ function parseStack(stack: any[], basePath: string, endpoints: Endpoint[]): Endpoint[] {
177
+ stack.forEach((stackItem) => {
178
+ if (stackItem.route) {
179
+ const newEndpoints = parseExpressRoute(stackItem.route, basePath);
180
+
181
+ endpoints = addEndpoints(endpoints, newEndpoints);
182
+ } else if (STACK_ITEM_VALID_NAMES.includes(stackItem.name)) {
183
+ const isExpressPathRegexp = regExpToParseExpressPathRegExp.test(stackItem.regexp);
184
+
185
+ let newBasePath = basePath;
186
+
187
+ if (isExpressPathRegexp) {
188
+ const parsedPath = parseExpressPath(stackItem.regexp, stackItem.keys);
189
+
190
+ newBasePath += `/${parsedPath}`;
191
+ } else if (
192
+ !stackItem.path &&
193
+ stackItem.regexp &&
194
+ stackItem.regexp.toString() !== EXPRESS_ROOT_PATH_REGEXP_VALUE
195
+ ) {
196
+ const regExpPath = ` RegExp(${stackItem.regexp}) `;
197
+
198
+ newBasePath += `/${regExpPath}`;
199
+ }
200
+
201
+ endpoints = parseEndpoints(stackItem.handle, newBasePath, endpoints);
202
+ }
203
+ });
204
+
205
+ return endpoints;
206
+ }
207
+
208
+ /**
209
+ * Returns an array of strings with all the detected endpoints
210
+ * @param app The express/router instance to get the endpoints from
211
+ * @returns The array of endpoints
212
+ */
213
+ function expressListEndpoints(app: Express | Router | any): Endpoint[] {
214
+ const endpoints = parseEndpoints(app);
215
+
216
+ return endpoints;
217
+ }
218
+
219
+ export default expressListEndpoints;
package/tsconfig.json ADDED
@@ -0,0 +1,8 @@
1
+ {
2
+ "extends": "@prairielearn/tsconfig/tsconfig.package.json",
3
+ "compilerOptions": {
4
+ "outDir": "./dist",
5
+ "rootDir": "./src",
6
+ "types": ["mocha", "node"]
7
+ }
8
+ }