-
Notifications
You must be signed in to change notification settings - Fork 0
/
walk.ts
92 lines (78 loc) · 2.18 KB
/
walk.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
import type {
AdapterRequestContext,
HattipHandler,
} from "npm:@hattip/core@0.0.26/index.d.ts";
type DenoHandler = (
request: Request,
connInfo: ConnInfo
) => Response | Promise<Response>;
interface ConnInfo {
readonly localAddr: Deno.Addr;
readonly remoteAddr: Deno.Addr;
}
// deno-lint-ignore no-namespace
namespace Deno {
export type Addr = NetAddr | UnixAddr;
export interface NetAddr {
transport: "tcp" | "udp";
hostname: string;
port: number;
}
export interface UnixAddr {
transport: "unix" | "unixpacket";
path: string;
}
}
export interface StaticServeOptions {
staticDir: string;
walk(
root: string | URL,
options: { includeDirs: false }
): AsyncIterableIterator<{ path: string }>;
serveDir(request: Request, options: { fsRoot: string }): Promise<Response>;
}
export function createRequestHandler(
hattipHandler: HattipHandler,
options?: StaticServeOptions
): DenoHandler {
let staticFiles: Set<string> | undefined;
let pending: Promise<void> | undefined;
if (options) {
console.log("staticDir", options.staticDir);
pending = (async () => {
const walker = options.walk(options.staticDir, { includeDirs: false });
const files = new Set<string>();
for await (const entry of walker) {
files.add(
entry.path.slice(options.staticDir.length).replace(/\\/g, "/")
);
}
staticFiles = files;
})();
}
return async (request, connInfo) => {
const url = new URL(request.url);
const pathname = url.pathname;
if (options) {
if (!staticFiles) {
await pending;
}
if (staticFiles!.has(pathname)) {
return options.serveDir(request, { fsRoot: options.staticDir });
} else if (staticFiles!.has(pathname + "/index.html")) {
url.pathname = pathname + "/index.html";
return options.serveDir(new Request(url, request), {
fsRoot: options.staticDir,
});
}
}
const context: AdapterRequestContext = {
request,
ip: (connInfo.remoteAddr as Deno.NetAddr).hostname,
waitUntil() {},
passThrough() {},
platform: { connInfo },
};
return hattipHandler(context);
};
}