-
Notifications
You must be signed in to change notification settings - Fork 0
/
_app.ts
427 lines (360 loc) · 9.66 KB
/
_app.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
import createRequest, { ServaRequest } from "./_request.ts";
import createRoute, { Route } from "./_route.ts";
import { fs, http, path, flags } from "./deps.ts";
export interface RouteCallback {
(request: ServaRequest): Promise<any> | any;
}
export interface ServaConfig {
port: number;
hostname?: string;
extension: string;
methods: string[];
}
const ROUTES_DIR = "routes";
const DEFAULT_CONFIG = Object.freeze({
port: 4500,
extension: ".ts",
methods: "get|post|put|delete|patch".split("|"),
});
type RouteEntry = [Route, RouteCallback];
type RoutesStruct = Map<string, RouteEntry[]>;
export default class App {
private readonly routes: RoutesStruct = new Map();
private readonly server?: http.Server;
public readonly appPath: string;
public readonly config: ServaConfig = Object.assign({}, DEFAULT_CONFIG);
/**
* Run main.
*
* @param {string[]} args
* @returns {void}
*/
public static main(args: string[]): App {
const { _: [command, dir = "."], port, hostname } = flags.parse(args);
if (command !== "start") {
throw new Error(`Unknown command: ${command}`);
}
const overwrites: Partial<ServaConfig> = {};
if (port) {
overwrites.port = port;
}
if (hostname) {
overwrites.hostname = hostname;
}
const app = new this(dir.toString(), overwrites);
app.start();
return app;
}
/**
* Creates a new App instance.
*
* @param {string} appPath Application root path.
*/
public constructor(
appPath: string,
public overwrites?: Partial<ServaConfig>,
) {
this.appPath = path.resolve(appPath);
}
/**
* Returns a path relative to the `appPath`. Or the absolute path if specified.
*
* @public
* @param {...string[]} path
* @returns {string}resolve
*/
public path(...paths: string[]): string {
if (paths.length === 0) {
return this.appPath;
}
if (paths.length === 1 && path.isAbsolute(paths[0])) {
return paths[0];
}
return path.join(this.appPath, ...paths);
}
/**
* Starts the application.
*
* @public
* @returns {Promise<void>}
*/
public async start() {
if (this.server) {
console.log("App already started.");
return;
}
await this.mount();
const options: http.HTTPOptions = {
port: this.config.port,
};
if (this.config.hostname) {
options.hostname = this.config.hostname;
}
// @ts-expect-error
this.server = http.serve(options);
console.log(
`App started, ${
options.hostname ? options.hostname : ""
}:${options.port}`,
);
for await (const request of this.server) {
this.handleRequest(request);
}
}
/**
* Stops the server if running.
*
* @public
* @returns {void}
*/
public stop() {
if (this.server) {
this.server.close();
}
}
/**
* Mounts the application to the `appPath`.
*
* @params {boolean} [remount] Fource app to remount.
* @returns {Promise<void>}
*/
async mount(remount: boolean = false): Promise<void> {
if (!remount && this.routes.size > 0) {
return;
}
const routesPath = this.path(ROUTES_DIR);
// /////////////////////////////////////////////////////////////////////////
// Config
try {
const configFilePath = this.path("serva.config.json");
const lstats = await Deno.lstat(configFilePath);
if (!lstats.isFile) {
throw new Error();
}
// @ts-expect-error
this.config = Object.assign({}, DEFAULT_CONFIG);
const config = await fs.readJson(configFilePath) as object;
[config, this.overwrites].forEach((object) => {
if (!object) {
return;
}
for (const [key, value] of Object.entries(object)) {
switch (key) {
case "port":
case "hostname":
case "extension":
case "methods":
// @ts-ignore
this.config[key] = value;
break;
default:
throw new Error(`Invalid config for: \`${key}\`.`);
}
}
});
} catch (err) {
if (err instanceof Deno.errors.NotFound) {
console.log("No serva.config.json found, using defaults.");
} else {
throw err;
}
}
// /////////////////////////////////////////////////////////////////////////
// Routes
// clear on remounts
this.routes.clear();
try {
const lstats = await Deno.lstat(routesPath);
if (!lstats.isDirectory) {
throw new Error();
}
} catch (err) {
throw new Error(`${routesPath} not found`);
}
const routes: [string, RouteEntry][] = [];
for await (const entry of fs.walk(routesPath)) {
// ignore directories and any non-typescript files
// todo: support for javascript
if (entry.isDirectory || !entry.name.endsWith(this.config.extension)) {
continue;
}
const relativeEntryPath = path.relative(routesPath, entry.path);
const method = routeMethod(relativeEntryPath, this.config);
const urlPath = routePath(relativeEntryPath, this.config); // route information
const route = createRoute(
method,
urlPath,
entry.path,
);
// register route
let callback: RouteCallback;
try {
let filePath = `file://${entry.path}`;
if (remount) {
filePath += "#" + Math.random();
}
({ default: callback } = await import(filePath));
if (typeof callback !== "function") {
throw new TypeError(
`${route.filePath} default export is not a callback.`,
);
}
} catch (err) {
console.log("Error in file:", entry.path, err);
continue;
}
routes.push(
[
route.method,
[route, callback!],
],
);
}
// sort and set routes
routes.sort(sortRoutes).forEach(([method, entry]) => {
const entries = this.routes.get(method) || [];
entries.push(entry);
if (entries.length === 1) {
this.routes.set(method, entries);
}
});
}
/**
* Handles an incoming request from the server.
*
* @private
* @param {ServerRequest} req
* @returns {<Promise<void>}
*/
private async handleRequest(req: http.ServerRequest): Promise<void> {
// find a matching route
let route: Route;
let callback: RouteCallback;
const { pathname } = new URL(req.url, "https://serva.land");
const possibleMethods = [req.method, "*"];
if (req.method === "HEAD") {
possibleMethods.splice(0, 1, "GET");
}
possibleMethods.some((m) => {
const entries = this.routes.get(m);
if (entries) {
return entries.some(([r, cb]) => {
if (r.regexp.test(pathname)) {
route = r;
callback = cb;
// route found
return true;
}
});
}
});
// not found
// @ts-ignore
if (!route) {
req.respond({
status: 404,
});
return;
}
const request = createRequest(req, route);
const body = await callback!(request);
// allow return values to set the body
if (body !== undefined) {
request.response.body = body;
}
// if nobody has responded, send the current request's response
if (request.httpRequest.w.usedBufferBytes === 0) {
req.respond(request.response);
}
}
}
/**
* Gets the route path from a file path.
*
* @example
* routePath("index.ts");
* // => "/"
*
* routePath("comments/[comment].get.ts");
* // => "/comments/[comment]"
*
* @param {string} filePath
* @param {ServaConfig} config
* @returns {string}
*/
function routePath(filePath: string, config: ServaConfig): string {
let name = path.basename(filePath, config.extension);
const matched = name.match(
new RegExp(`.*(?=\.(${config.methods.join("|")})$)`, "i"),
);
if (matched) {
[name] = matched;
}
if (name === "index") {
name = "";
}
let base = path.dirname(filePath);
if (base === ".") {
base = "";
}
return "/" + (base ? path.join(base, name) : name);
}
/**
* Returns the route method from a give route path.
*
* @example
* routeMethod("index.ts");
* // => "*"
*
* routeMethod("/comments/[comment].get.ts")
* // => "GET"
*
* @param {string} filePath
* @param {ServaConfig} config
* @returns {string}
*/
function routeMethod(filePath: string, config: ServaConfig): string {
const name = path.basename(filePath, config.extension);
const matched = name.match(
new RegExp(`.*(?=\.(${config.methods.join("|")})$)`, "i"),
);
let method = "*";
if (matched) {
[, method] = matched;
}
return method.toUpperCase();
}
/**
* Sort function for routes.
*
* @param {RouteEntry} a
* @param {RouteEntry} b
* @returns {number}
*/
function sortRoutes(a: [string, RouteEntry], b: [string, RouteEntry]): number {
const [methodA, [routeA]] = a;
const [methodB, [routeB]] = b;
// find params and insert placeholders
const pathA = routeA.path.replace(/\[.+\]/g, "\0");
const pathB = routeB.path.replace(/\[.+\]/g, "\0");
// compare each character of the urls
for (let i = 0, l = Math.min(pathA.length, pathB.length); i < l; ++i) {
const aChar = pathA.charAt(i);
const bChar = pathB.charAt(i);
if (aChar !== bChar) {
// param check
if (aChar === "\0") {
return 1;
} else if (bChar === "\0") {
return -1;
}
// order by least path segments
return pathA.split(path.sep).length - pathB.split(path.sep).length;
}
}
// compare methods
if (methodA === "*" || methodB === "*") {
return methodB.charCodeAt(0) - methodA.charCodeAt(0);
}
return 0;
}