forked from freshframework/fresh
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.ts
More file actions
334 lines (295 loc) · 10.1 KB
/
app.ts
File metadata and controls
334 lines (295 loc) · 10.1 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
import * as path from "@std/path";
import { type ComponentType, h } from "preact";
import { renderToString } from "preact-render-to-string";
import { trace } from "@opentelemetry/api";
import { DENO_DEPLOYMENT_ID } from "./runtime/build_id.ts";
import * as colors from "@std/fmt/colors";
import { type MiddlewareFn, runMiddlewares } from "./middlewares/mod.ts";
import { FreshReqContext } from "./context.ts";
import { type Method, type Router, UrlPatternRouter } from "./router.ts";
import {
type FreshConfig,
normalizeConfig,
type ResolvedFreshConfig,
} from "./config.ts";
import { type BuildCache, ProdBuildCache } from "./build_cache.ts";
import type { ServerIslandRegistry } from "./context.ts";
import { FinishSetup, ForgotBuild } from "./finish_setup.tsx";
import { HttpError } from "./error.ts";
import { mergePaths } from "./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 DEFAULT_NOT_FOUND = () => {
throw new HttpError(404);
};
const DEFAULT_NOT_ALLOWED_METHOD = () => {
throw new HttpError(405);
};
export type ListenOptions =
& Partial<
Deno.ServeTcpOptions & Deno.TlsCertifiedKeyPem
>
& {
remoteAddress?: string;
};
Deno.serve;
export let getRouter: <State>(app: App<State>) => Router<MiddlewareFn<State>>;
// deno-lint-ignore no-explicit-any
export let getIslandRegistry: (app: App<any>) => ServerIslandRegistry;
// deno-lint-ignore no-explicit-any
export let getBuildCache: (app: App<any>) => BuildCache | null;
// deno-lint-ignore no-explicit-any
export let setBuildCache: (app: App<any>, cache: BuildCache | null) => void;
export class App<State> {
#router: Router<MiddlewareFn<State>> = new UrlPatternRouter<
MiddlewareFn<State>
>();
#islandRegistry: ServerIslandRegistry = new Map();
#buildCache: BuildCache | null = null;
#islandNames = new Set<string>();
static {
getRouter = (app) => app.#router;
getIslandRegistry = (app) => app.#islandRegistry;
getBuildCache = (app) => app.#buildCache;
setBuildCache = (app, cache) => app.#buildCache = cache;
}
/**
* The final resolved Fresh configuration.
*/
config: ResolvedFreshConfig;
constructor(config: FreshConfig = {}) {
this.config = normalizeConfig(config);
}
island(
filePathOrUrl: string | URL,
exportName: string,
// deno-lint-ignore no-explicit-any
fn: ComponentType<any>,
): this {
const filePath = filePathOrUrl instanceof URL
? filePathOrUrl.href
: filePathOrUrl;
// Create unique island name
let name = exportName === "default"
? path.basename(filePath, path.extname(filePath))
: exportName;
if (this.#islandNames.has(name)) {
let i = 0;
while (this.#islandNames.has(`${name}_${i}`)) {
i++;
}
name = `${name}_${i}`;
}
this.#islandRegistry.set(fn, { fn, exportName, name, file: filePathOrUrl });
return this;
}
use(middleware: MiddlewareFn<State>): this {
this.#router.addMiddleware(middleware);
return this;
}
get(path: string, ...middlewares: MiddlewareFn<State>[]): this {
return this.#addRoutes("GET", path, middlewares);
}
post(path: string, ...middlewares: MiddlewareFn<State>[]): this {
return this.#addRoutes("POST", path, middlewares);
}
patch(path: string, ...middlewares: MiddlewareFn<State>[]): this {
return this.#addRoutes("PATCH", path, middlewares);
}
put(path: string, ...middlewares: MiddlewareFn<State>[]): this {
return this.#addRoutes("PUT", path, middlewares);
}
delete(path: string, ...middlewares: MiddlewareFn<State>[]): this {
return this.#addRoutes("DELETE", path, middlewares);
}
head(path: string, ...middlewares: MiddlewareFn<State>[]): this {
return this.#addRoutes("HEAD", path, middlewares);
}
all(path: string, ...middlewares: MiddlewareFn<State>[]): this {
return this.#addRoutes("ALL", path, middlewares);
}
mountApp(path: string, app: App<State>): this {
const routes = app.#router._routes;
app.#islandRegistry.forEach((value, key) => {
this.#islandRegistry.set(key, value);
});
const middlewares = app.#router._middlewares;
// Special case when user calls one of these:
// - `app.mountApp("/", otherApp)`
// - `app.mountApp("/*", otherApp)`
const isSelf = path === "/*" || path === "/";
if (isSelf && middlewares.length > 0) {
this.#router._middlewares.push(...middlewares);
}
for (let i = 0; i < routes.length; i++) {
const route = routes[i];
const merged = typeof route.path === "string"
? mergePaths(path, route.path)
: route.path;
const combined = isSelf
? route.handlers
: middlewares.concat(route.handlers);
this.#router.add(route.method, merged, combined);
}
return this;
}
#addRoutes(
method: Method | "ALL",
pathname: string | URLPattern,
middlewares: MiddlewareFn<State>[],
): this {
const merged = typeof pathname === "string"
? mergePaths(this.config.basePath, pathname)
: pathname;
this.#router.add(method, merged, middlewares);
return this;
}
async handler(): Promise<
(request: Request, info?: Deno.ServeHandlerInfo) => Promise<Response>
> {
if (this.#buildCache === null) {
this.#buildCache = await ProdBuildCache.fromSnapshot(
this.config,
this.#islandRegistry.size,
);
}
if (
!this.#buildCache.hasSnapshot && this.config.mode === "production" &&
DENO_DEPLOYMENT_ID !== undefined
) {
return missingBuildHandler;
}
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 = this.#router.match(method, url);
const next = matched.patternMatch && !matched.methodMatch
? DEFAULT_NOT_ALLOWED_METHOD
: DEFAULT_NOT_FOUND;
const { params, handlers, pattern } = matched;
const ctx = new FreshReqContext<State>(
req,
url,
conn,
params,
this.config,
next,
this.#islandRegistry,
this.#buildCache!,
);
const span = trace.getActiveSpan();
if (span && pattern) {
span.updateName(`${method} ${pattern}`);
span.setAttribute("http.route", pattern);
}
try {
if (handlers.length === 1 && handlers[0].length === 1) {
return handlers[0][0](ctx);
}
return await runMiddlewares(handlers, ctx);
} catch (err) {
if (err instanceof HttpError) {
if (err.status >= 500) {
// deno-lint-ignore no-console
console.error(err);
}
return new Response(err.message, { status: err.status });
}
// deno-lint-ignore no-console
console.error(err);
return new Response("Internal server error", { status: 500 });
}
};
}
async listen(options: ListenOptions = {}): Promise<void> {
if (!options.onListen) {
options.onListen = (params) => {
const pathname = (this.config.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;
const address = colors.cyan(
`${protocol}//${hostname}:${params.port}${pathname}`,
);
const localLabel = colors.bold("Local:");
// Don't spam logs with this on live deployments
if (!DENO_DEPLOYMENT_ID) {
// 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 ? " " : "";
// deno-lint-ignore no-console
console.log(` ${localLabel} ${space}${address}${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`);
}
}
};
}
const handler = await this.handler();
if (options.port) {
await Deno.serve(options, handler);
} else {
// 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;
for (let port = 8000; port < 8020; port++) {
try {
await Deno.serve({ ...options, port }, handler);
firstError = undefined;
break;
} catch (err) {
if (err instanceof Deno.errors.AddrInUse) {
// Throw first EADDRINUSE error
// if no port is free
if (!firstError) {
firstError = err;
}
continue;
}
throw err;
}
}
if (firstError) {
throw firstError;
}
}
}
}
// deno-lint-ignore require-await
const missingBuildHandler = async (): Promise<Response> => {
const headers = new Headers();
headers.set("Content-Type", "text/html; charset=utf-8");
const html = DENO_DEPLOYMENT_ID
? renderToString(h(FinishSetup, null))
: renderToString(h(ForgotBuild, null));
return new Response(html, { headers, status: 500 });
};