-
Notifications
You must be signed in to change notification settings - Fork 742
Expand file tree
/
Copy pathapp.ts
More file actions
458 lines (410 loc) · 12.6 KB
/
app.ts
File metadata and controls
458 lines (410 loc) · 12.6 KB
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
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
import { trace } from "@opentelemetry/api";
import { DENO_DEPLOYMENT_ID } from "./runtime/build_id.ts";
import * as colors from "@std/fmt/colors";
import {
type MaybeLazyMiddleware,
type MiddlewareFn,
runMiddlewares,
} from "./middlewares/mod.ts";
import { Context } from "./context.ts";
import { mergePath, type Method, UrlPatternRouter } from "./router.ts";
import type { FreshConfig, ResolvedFreshConfig } from "./config.ts";
import type { BuildCache } from "./build_cache.ts";
import { HttpError } from "./error.ts";
import type { LayoutConfig, MaybeLazy, Route, RouteConfig } from "./types.ts";
import type { RouteComponent } from "./segments.ts";
import {
applyCommands,
type Command,
CommandType,
DEFAULT_NOT_ALLOWED_METHOD,
DEFAULT_NOT_FOUND,
newAppCmd,
newErrorCmd,
newHandlerCmd,
newLayoutCmd,
newMiddlewareCmd,
newNotFoundCmd,
newRouteCmd,
} from "./commands.ts";
import { MockBuildCache } from "./test_utils.ts";
// TODO: Completed type clashes in older Deno versions
// deno-lint-ignore no-explicit-any
export const DEFAULT_CONN_INFO: any = {
localAddr: { transport: "tcp", hostname: "localhost", port: 8080 },
remoteAddr: { transport: "tcp", hostname: "localhost", port: 1234 },
};
const defaultOptionsHandler = (methods: string[]): () => Promise<Response> => {
return () =>
Promise.resolve(
new Response(null, {
status: 204,
headers: { Allow: methods.join(", ") },
}),
);
};
// deno-lint-ignore require-await
const DEFAULT_ERROR_HANDLER = async <State>(ctx: Context<State>) => {
const { error } = ctx;
if (error instanceof HttpError) {
if (error.status >= 500) {
// deno-lint-ignore no-console
console.error(error);
}
return new Response(error.message, { status: error.status });
}
// deno-lint-ignore no-console
console.error(error);
return new Response("Internal server error", { status: 500 });
};
export type ListenOptions =
& Partial<
Deno.ServeTcpOptions & Deno.TlsCertifiedKeyPem
>
& {
remoteAddress?: string;
};
function createOnListen(
basePath: string,
options: ListenOptions,
): (localAddr: Deno.NetAddr) => void {
return (params) => {
// Don't spam logs with this on live deployments
if (DENO_DEPLOYMENT_ID) return;
const pathname = basePath + "/";
const protocol = "key" in options && options.key && options.cert
? "https:"
: "http:";
let hostname = params.hostname;
// Windows being windows...
if (
Deno.build.os === "windows" &&
(hostname === "0.0.0.0" || hostname === "::")
) {
hostname = "localhost";
}
// Work around https://github.com/denoland/deno/issues/23650
hostname = hostname.startsWith("::") ? `[${hostname}]` : hostname;
// deno-lint-ignore no-console
console.log();
// deno-lint-ignore no-console
console.log(
colors.bgRgb8(colors.rgb8(" 🍋 Fresh ready ", 0), 121),
);
const sep = options.remoteAddress ? "" : "\n";
const space = options.remoteAddress ? " " : "";
const localLabel = colors.bold("Local:");
const address = colors.cyan(
`${protocol}//${hostname}:${params.port}${pathname}`,
);
const helper = hostname === "0.0.0.0" || hostname === "::"
? colors.cyan(` (${protocol}//localhost:${params.port}${pathname})`)
: "";
// deno-lint-ignore no-console
console.log(` ${localLabel} ${space}${address}${helper}${sep}`);
if (options.remoteAddress) {
const remoteLabel = colors.bold("Remote:");
const remoteAddress = colors.cyan(options.remoteAddress);
// deno-lint-ignore no-console
console.log(` ${remoteLabel} ${remoteAddress}\n`);
}
};
}
async function listenOnFreePort(
options: ListenOptions,
handler: (
request: Request,
info?: Deno.ServeHandlerInfo,
) => Promise<Response>,
) {
// No port specified, check for a free port. Instead of picking just
// any port we'll check if the next one is free for UX reasons.
// That way the user only needs to increment a number when running
// multiple apps vs having to remember completely different ports.
let firstError = null;
for (let port = 8000; port < 8020; port++) {
try {
return await Deno.serve({ ...options, port }, handler);
} catch (err) {
if (err instanceof Deno.errors.AddrInUse) {
// Throw first EADDRINUSE error if no port is free
if (!firstError) firstError = err;
continue;
}
throw err;
}
}
throw firstError;
}
export let getBuildCache: <State>(app: App<State>) => BuildCache<State> | null;
export let setBuildCache: <State>(
app: App<State>,
cache: BuildCache<State>,
) => void;
/**
* Create an application instance that passes the incoming `Request`
* instance through middlewares and routes.
*/
export class App<State> {
#getBuildCache: () => BuildCache<State> | null = () => null;
#commands: Command<State>[] = [];
static {
getBuildCache = (app) => app.#getBuildCache();
setBuildCache = (app, cache) => {
app.config.root = cache.root;
app.#getBuildCache = () => cache;
};
}
/**
* The final resolved Fresh configuration.
*/
config: ResolvedFreshConfig;
constructor(config: FreshConfig = {}) {
this.config = {
root: Deno.cwd(),
basePath: config.basePath ?? "",
mode: "production",
};
}
/**
* Add one or more middlewares at the top or the specified path.
*/
use(...middleware: MaybeLazyMiddleware<State>[]): this;
use(path: string, ...middleware: MaybeLazyMiddleware<State>[]): this;
use(
pathOrMiddleware: string | MaybeLazyMiddleware<State>,
...middlewares: MaybeLazyMiddleware<State>[]
): this {
let pattern: string;
let fns: MaybeLazyMiddleware<State>[];
if (typeof pathOrMiddleware === "string") {
pattern = pathOrMiddleware;
fns = middlewares!;
} else {
pattern = "*";
middlewares.unshift(pathOrMiddleware);
fns = middlewares;
}
this.#commands.push(newMiddlewareCmd(pattern, fns, true));
return this;
}
/**
* Set the app's 404 error handler. Can be a {@linkcode Route} or a {@linkcode MiddlewareFn}.
*/
notFound(routeOrMiddleware: Route<State> | MiddlewareFn<State>): this {
this.#commands.push(newNotFoundCmd(routeOrMiddleware));
return this;
}
onError(
path: string,
routeOrMiddleware: Route<State> | MiddlewareFn<State>,
): this {
this.#commands.push(newErrorCmd(path, routeOrMiddleware, true));
return this;
}
appWrapper(component: RouteComponent<State>): this {
this.#commands.push(newAppCmd(component));
return this;
}
layout(
path: string,
component: RouteComponent<State>,
config?: LayoutConfig,
): this {
this.#commands.push(newLayoutCmd(path, component, config, true));
return this;
}
route(
path: string,
route: MaybeLazy<Route<State>>,
config?: RouteConfig,
): this {
this.#commands.push(newRouteCmd(path, route, config, false));
return this;
}
/**
* Add middlewares for GET requests at the specified path.
*/
get(path: string, ...middlewares: MaybeLazy<MiddlewareFn<State>>[]): this {
this.#commands.push(newHandlerCmd("GET", path, middlewares, false));
return this;
}
/**
* Add middlewares for POST requests at the specified path.
*/
post(path: string, ...middlewares: MaybeLazy<MiddlewareFn<State>>[]): this {
this.#commands.push(newHandlerCmd("POST", path, middlewares, false));
return this;
}
/**
* Add middlewares for PATCH requests at the specified path.
*/
patch(path: string, ...middlewares: MaybeLazy<MiddlewareFn<State>>[]): this {
this.#commands.push(newHandlerCmd("PATCH", path, middlewares, false));
return this;
}
/**
* Add middlewares for PUT requests at the specified path.
*/
put(path: string, ...middlewares: MaybeLazy<MiddlewareFn<State>>[]): this {
this.#commands.push(newHandlerCmd("PUT", path, middlewares, false));
return this;
}
/**
* Add middlewares for DELETE requests at the specified path.
*/
delete(path: string, ...middlewares: MaybeLazy<MiddlewareFn<State>>[]): this {
this.#commands.push(newHandlerCmd("DELETE", path, middlewares, false));
return this;
}
/**
* Add middlewares for HEAD requests at the specified path.
*/
head(path: string, ...middlewares: MaybeLazy<MiddlewareFn<State>>[]): this {
this.#commands.push(newHandlerCmd("HEAD", path, middlewares, false));
return this;
}
/**
* Add middlewares for all HTTP verbs at the specified path.
*/
all(path: string, ...middlewares: MaybeLazy<MiddlewareFn<State>>[]): this {
this.#commands.push(newHandlerCmd("ALL", path, middlewares, false));
return this;
}
/**
* Insert file routes collected in {@linkcode Builder} at this point.
* @param pattern Append file routes at this pattern instead of the root
* @returns
*/
fsRoutes(pattern = "*"): this {
this.#commands.push({
type: CommandType.FsRoute,
pattern,
getItems: () => {
const buildCache = this.#getBuildCache();
if (buildCache === null) return [];
return buildCache.getFsRoutes();
},
includeLastSegment: false,
});
return this;
}
/**
* Merge another {@linkcode App} instance into this app at the
* specified path.
*/
mountApp(path: string, app: App<State>): this {
for (let i = 0; i < app.#commands.length; i++) {
const cmd = app.#commands[i];
if (cmd.type !== CommandType.App && cmd.type !== CommandType.NotFound) {
const clone = {
...cmd,
pattern: mergePath(path, cmd.pattern),
includeLastSegment: cmd.pattern === "/" || cmd.includeLastSegment,
};
this.#commands.push(clone);
continue;
}
this.#commands.push(cmd);
}
// deno-lint-ignore no-this-alias
const self = this;
app.#getBuildCache = () => self.#getBuildCache();
return this;
}
/**
* Create handler function for `Deno.serve` or to be used in
* testing.
*/
handler(): (
request: Request,
info?: Deno.ServeHandlerInfo,
) => Promise<Response> {
let buildCache = this.#getBuildCache();
if (buildCache === null) {
if (
this.config.mode === "production" &&
DENO_DEPLOYMENT_ID !== undefined
) {
throw new Error(
`Could not find _fresh directory. Maybe you forgot to run "deno task build"?`,
);
} else {
buildCache = new MockBuildCache([]);
}
}
const router = new UrlPatternRouter<MaybeLazyMiddleware<State>>();
const { rootMiddlewares } = applyCommands(
router,
this.#commands,
this.config.basePath,
);
return async (
req: Request,
conn: Deno.ServeHandlerInfo = DEFAULT_CONN_INFO,
) => {
const url = new URL(req.url);
// Prevent open redirect attacks
url.pathname = url.pathname.replace(/\/+/g, "/");
const method = req.method.toUpperCase() as Method;
const matched = router.match(method, url);
let { params, pattern, handlers, methodMatch } = matched;
const span = trace.getActiveSpan();
if (span && pattern) {
span.updateName(`${method} ${pattern}`);
span.setAttribute("http.route", pattern);
}
let next: () => Promise<Response>;
if (pattern === null || !methodMatch) {
handlers = rootMiddlewares;
}
if (matched.pattern !== null && !methodMatch) {
if (method === "OPTIONS") {
const allowed = router.getAllowedMethods(matched.pattern);
next = defaultOptionsHandler(allowed);
} else {
next = DEFAULT_NOT_ALLOWED_METHOD;
}
} else {
next = DEFAULT_NOT_FOUND;
}
const ctx = new Context<State>(
req,
url,
conn,
matched.pattern,
params,
this.config,
next,
buildCache!,
);
try {
if (handlers.length === 0) return await next();
const result = await runMiddlewares(handlers, ctx);
if (!(result instanceof Response)) {
throw new Error(
`Expected a "Response" instance to be returned, but got: ${result}`,
);
}
return result;
} catch (err) {
ctx.error = err;
return await DEFAULT_ERROR_HANDLER(ctx);
}
};
}
/**
* Spawn a server for this app.
*/
async listen(options: ListenOptions = {}): Promise<void> {
if (!options.onListen) {
options.onListen = createOnListen(this.config.basePath, options);
}
const handler = this.handler();
if (options.port) {
await Deno.serve(options, handler);
return;
}
await listenOnFreePort(options, handler);
}
}