-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmod.ts
163 lines (153 loc) · 3.92 KB
/
mod.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
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
import { getMediaType } from "./media_types.ts";
type Server = {
close(): void;
addr: Deno.Addr;
};
type ServeOptions = {
port?: number;
onError?: (e: Error) => void;
debugPagePath?: string;
};
/**
* @private
*/
export type Cache = Record<string, File>;
/**
* Serves the items from the async iterable of the files matching by its file name.
*
* ex.
* If file.name === "foo.txt", it's served at url "http://localhost:3000/foo.txt".
* If file.name === "foo/bar.html", it's served at url "http://localhost:3000/foo/bar.html".
*/
export function serve(
src: AsyncIterable<File>,
{ port = 3000, onError = console.error, debugPagePath = "/__debug__" }:
ServeOptions = {},
): Server {
const listener = Deno.listen({ port });
const cache = {} as Cache;
accumulate(src, cache).catch(onError);
const closer = serveFromCache(listener, cache, { onError, debugPagePath });
return {
addr: listener.addr,
close() {
closer();
listener.close();
},
};
}
/**
* @private
* Accumulates the files from the async iterable into the cache record.
*/
export async function accumulate(
src: AsyncIterable<File>,
cache: Cache,
): Promise<void> {
for await (const file of src) {
const { pathname } = new URL(file.name, "file:///");
cache[pathname] = file;
}
}
/**
* @private
* Serves the items from the cache record of files.
*/
export function serveFromCache(
listener: Deno.Listener,
cache: Cache,
{ onError, debugPagePath }: ServeOptions,
): () => void {
const httpConns = [] as Deno.HttpConn[];
const closer = () => {
for (const conn of httpConns) {
conn.close();
}
};
if (!debugPagePath) {
throw new Error("debugPagePath option is not given");
}
if (!debugPagePath.startsWith("/")) {
throw new Error("debugPagePath option doesn't start with '/'");
}
(async () => {
for await (const conn of listener) {
(async () => {
const httpConn = Deno.serveHttp(conn);
httpConns.push(httpConn);
for await (const { request, respondWith } of httpConn) {
const { pathname } = new URL(request.url);
if (pathname === debugPagePath) {
respondWith(responseDebugPage(cache));
continue;
}
let resp = cache[pathname];
if (resp) {
respondWith(
new Response(resp, {
headers: {
"content-type": getMediaType(
pathname.match(/\.[a-zA-Z0-9]+$/)?.[0],
),
},
}),
);
continue;
}
if (pathname.endsWith("/")) {
resp = cache[pathname + "index.html"];
if (resp) {
respondWith(
new Response(resp, {
headers: {
"content-type": "text/html",
},
}),
);
continue;
}
}
// If there's a file at the path /404, it works as the custom 404 page.
resp = cache["/404"];
if (resp) {
respondWith(new Response(resp));
continue;
}
respondWith(responseNotFound(debugPagePath));
}
})().catch(onError);
}
})().catch(onError);
return closer;
}
/**
* Returns a response for the debug page.
*/
function responseDebugPage(cache: Cache): Response {
return new Response(
`
<pre>
debug page
${Object.keys(cache).map((path) => `<a href="${path}">${path}</a>`).join("\n")}
</pre>
`,
{
status: 200,
headers: {
"content-type": "text/html",
},
},
);
}
/**
* Returns a response for the 404 page.
*/
function responseNotFound(debugPagePath: string): Response {
return new Response(
`
<h1>404 Not Found</h1>
<p><a href="${debugPagePath}">Go to debug page</a></p>
`,
{ status: 404, headers: { "content-type": "text/html" } },
);
}