-
-
Notifications
You must be signed in to change notification settings - Fork 815
Expand file tree
/
Copy pathapp.ts
More file actions
175 lines (161 loc) · 5.5 KB
/
app.ts
File metadata and controls
175 lines (161 loc) · 5.5 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
import type { Nitro } from "nitro/types";
import type { H3Event, HTTPHandler } from "h3";
import { createProxyServer, type ProxyServerOptions } from "httpxy";
import type { IncomingMessage, ServerResponse } from "node:http";
import { H3, toEventHandler, serveStatic, fromNodeHandler, HTTPError } from "h3";
import { joinURL } from "ufo";
import mime from "mime";
import { join, resolve, extname } from "pathe";
import { stat } from "node:fs/promises";
import { createReadStream } from "node:fs";
import { createGzip, createBrotliCompress } from "node:zlib";
import { createVFSHandler } from "./vfs.ts";
import type { CompressOptions } from "../types/config.ts";
import devErrorHandler, {
defaultHandler as devErrorHandlerInternal,
loadStackTrace,
} from "../runtime/internal/error/dev.ts";
export class NitroDevApp {
nitro: Nitro;
fetch: (req: Request) => Response | Promise<Response>;
constructor(nitro: Nitro, catchAllHandler?: HTTPHandler) {
this.nitro = nitro;
const app = this.#createApp(catchAllHandler);
this.fetch = app.fetch.bind(app);
}
#createApp(catchAllHandler?: HTTPHandler) {
// Init h3 app
const app = new H3({
debug: true,
onError: async (error, event) => {
const errorHandler = this.nitro.options.devErrorHandler || devErrorHandler;
await loadStackTrace(error).catch(() => {});
return errorHandler(error, event, {
defaultHandler: devErrorHandlerInternal,
});
},
});
// Dev-only handlers
for (const h of this.nitro.options.devHandlers) {
const handler = toEventHandler(h.handler);
if (!handler) {
this.nitro.logger.warn("Invalid dev handler:", h);
continue;
}
if (h.middleware || !h.route) {
// Middleware
if (h.route) {
app.use(h.route, handler, { method: h.method });
} else {
app.use(handler, { method: h.method });
}
} else {
// Route
app.on(h.method || "", h.route, handler, { meta: h.meta as any });
}
}
// Debugging endpoint to view vfs
app.get("/_vfs/**", createVFSHandler(this.nitro));
// Serve asset dirs
for (const asset of this.nitro.options.publicAssets) {
const assetBase = joinURL(this.nitro.options.baseURL, asset.baseURL || "/");
app.use(joinURL(assetBase, "**"), (event) =>
serveStaticDir(event, {
dir: asset.dir,
base: assetBase,
fallthrough: asset.fallthrough,
compress: this.nitro.options.compressPublicAssets,
})
);
}
// User defined dev proxy
const routes = Object.keys(this.nitro.options.devProxy).sort().reverse();
for (const route of routes) {
let opts = this.nitro.options.devProxy[route];
if (typeof opts === "string") {
opts = { target: opts };
}
const proxy = createHTTPProxy(opts);
app.all(route, proxy.handleEvent);
}
// Main handler
if (catchAllHandler) {
app.all("/**", catchAllHandler);
}
return app;
}
}
// TODO: upstream to h3/node
function serveStaticDir(
event: H3Event,
opts: { dir: string; base: string; fallthrough?: boolean; compress?: boolean | CompressOptions }
) {
const dir = resolve(opts.dir) + "/";
const r = (id: string) => {
if (!id.startsWith(opts.base) || !extname(id)) return;
const resolved = join(dir, id.slice(opts.base.length));
if (resolved.startsWith(dir)) {
return resolved;
}
};
// Determine compression settings
const compressOpts =
opts.compress === true
? { gzip: true, brotli: true, zstd: false }
: opts.compress === false
? { gzip: false, brotli: false, zstd: false }
: opts.compress || { gzip: false, brotli: false, zstd: false };
return serveStatic(event, {
fallthrough: opts.fallthrough,
getMeta: async (id) => {
const path = r(id);
if (!path) return;
const s = await stat(path).catch(() => null);
if (!s?.isFile()) return;
const ext = extname(path);
return {
size: s.size,
mtime: s.mtime,
type: mime.getType(ext) || "application/octet-stream",
};
},
getContents(id) {
const path = r(id);
if (!path) return;
const stream = createReadStream(path);
const acceptEncoding = event.req.headers.get("accept-encoding") || "";
if (compressOpts.brotli && acceptEncoding.includes("br")) {
event.res.headers.set("Content-Encoding", "br");
event.res.headers.delete("Content-Length");
event.res.headers.set("Vary", "Accept-Encoding");
return stream.pipe(createBrotliCompress());
} else if (compressOpts.gzip && acceptEncoding.includes("gzip")) {
event.res.headers.set("Content-Encoding", "gzip");
event.res.headers.delete("Content-Length");
event.res.headers.set("Vary", "Accept-Encoding");
return stream.pipe(createGzip());
}
return stream as any;
},
});
}
function createHTTPProxy(defaults: ProxyServerOptions = {}) {
const proxy = createProxyServer({ xfwd: true, ...defaults });
return {
proxy,
async handleEvent(event: H3Event, opts?: ProxyServerOptions) {
try {
return await fromNodeHandler((req, res) => {
return proxy.web(req as IncomingMessage, res as ServerResponse, opts);
})(event);
} catch (error: any) {
event.res.headers.set("refresh", "3");
throw new HTTPError({
status: 503,
message: "Dev server is unavailable.",
cause: error,
});
}
},
};
}