-
-
Notifications
You must be signed in to change notification settings - Fork 54
Expand file tree
/
Copy pathgeneric.ts
More file actions
60 lines (48 loc) · 1.84 KB
/
Copy pathgeneric.ts
File metadata and controls
60 lines (48 loc) · 1.84 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
import type { Server, ServerHandler, ServerOptions } from "../types.ts";
import { wrapFetch } from "../_middleware.ts";
import { errorPlugin } from "../_plugins.ts";
import { createWaitUntil } from "../_utils.ts";
export const FastURL: typeof globalThis.URL = URL;
export const FastResponse: typeof globalThis.Response = Response;
export function serve(options: ServerOptions): Server {
return new GenericServer(options);
}
class GenericServer implements Server {
readonly runtime = "generic";
readonly options: Server["options"];
readonly fetch: ServerHandler;
readonly waitUntil: Server["waitUntil"];
#wait: ReturnType<typeof createWaitUntil>;
constructor(options: ServerOptions) {
this.options = { ...options, middleware: [...(options.middleware || [])] };
for (const plugin of options.plugins || []) plugin(this);
errorPlugin(this);
this.#wait = createWaitUntil();
this.waitUntil = this.#wait.waitUntil;
const fetchHandler = wrapFetch(this as unknown as Server);
this.fetch = (request: Request) => {
Object.defineProperties(request, {
waitUntil: { value: this.#wait.waitUntil },
runtime: { enumerable: true, value: { name: "generic" } },
ip: {
enumerable: true,
// The generic adapter has no native transport to read a peer address
// from, so `ip` is derived from `x-forwarded-for` when present.
// Configurable so a trustProxy setup can still override it.
configurable: true,
get() {
return request.headers.get("x-forwarded-for")?.split(",")[0]?.trim() || undefined;
},
},
});
return Promise.resolve(fetchHandler(request));
};
}
serve(): void {}
ready(): Promise<Server> {
return Promise.resolve(this);
}
async close(): Promise<void> {
await this.#wait.wait();
}
}