-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.ts
177 lines (162 loc) · 4.44 KB
/
main.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
164
165
166
167
168
169
170
171
172
173
174
175
176
177
import {
crypto,
toHashString,
} from "https://deno.land/[email protected]/crypto/mod.ts";
import { join } from "https://deno.land/[email protected]/path/mod.ts";
import { asChannel, Channel } from "./channel.ts";
import { denoDoc } from "./denodoc.ts";
export interface BeginDenoDocRequest {
importMap: string;
cwd: string;
}
export interface DocFileRequest {
path: string;
content: string;
hash: string;
}
export interface DocHttpRequest {
path: string;
}
const isDenoDocFileRequest = (v: DocRequest): v is DocFileRequest => {
return (v as DocFileRequest)?.content !== undefined;
};
export type DocRequest = DocFileRequest | DocHttpRequest;
export interface DocResponse {
path: string;
docNodes: string;
}
const isBeginDocRequest = (
v: unknown | BeginDenoDocRequest,
): v is BeginDenoDocRequest => {
return (v as BeginDenoDocRequest).cwd !== undefined;
};
const createIfNotExists = async (
req: BeginDenoDocRequest,
importMapDigest: string,
) => {
const folder = join("dist", importMapDigest);
const importMap = join(folder, "import_map.json");
try {
await Deno.stat(importMap);
return importMap;
} catch (e) {
if (e instanceof Deno.errors.NotFound) {
await Deno.mkdir(folder, {
recursive: true,
});
const parsed: { imports: Record<string, string> } = JSON.parse(
req.importMap,
);
for (const [key, value] of Object.entries(parsed?.imports ?? {})) {
if (value === "./") {
parsed.imports[key] = `http://localhost:8081/`;
}
}
await Deno.writeTextFile(
importMap,
JSON.stringify(parsed),
{ create: true },
);
return importMap;
}
throw e;
}
};
const creating: Record<string, Promise<string>> = {};
const fileContentChallenges: Record<string, string> = {};
// content addressable storage
const CAS: Record<string, Promise<string>> = {};
const httpModules: Record<string, Promise<string>> = {};
const useChannel = async (
c: Channel<
DocResponse,
DocRequest
>,
) => {
const firstMessage = await c.recv();
if (!isBeginDocRequest(firstMessage)) {
c.close();
return;
}
const hash = await crypto.subtle.digest(
"MD5",
new TextEncoder().encode(firstMessage.importMap),
);
const importMapHash = toHashString(hash);
creating[importMapHash] ??= createIfNotExists(firstMessage, importMapHash);
const importMap = await creating[importMapHash];
// http://localhost:8081/${deploymentId}/$file_path
while (true) {
const req = await Promise.race([c.closed.wait(), c.recv()]);
if (req === true) {
break;
}
if (!isDenoDocFileRequest(req)) {
httpModules[req.path] ??= denoDoc(req.path, importMap);
httpModules[req.path].then((docNodes) => {
if (c.closed.is_set()) {
console.log("CLOSE IS SET HTTP");
return;
}
c.send({ path: req.path, docNodes });
});
continue;
}
fileContentChallenges[req.hash] = req.content;
CAS[req.hash] ??= denoDoc(
`${
req.path.replace(
firstMessage.cwd,
`http://localhost:8081`,
)
}?hash=${req.hash}`,
importMap,
(str: string) =>
str.replaceAll(
`http://localhost:8081`,
firstMessage.cwd,
),
);
CAS[req.hash].then((docNodes) => {
if (c.closed.is_set()) {
console.log("CLOSE IS SET");
return;
}
c.send({ path: req.path, docNodes });
}).catch((err) => {
console.log(err, "denodoc err");
});
}
};
Deno.serve({ port: 8081 }, (req) => {
try {
const url = new URL(req.url);
if (url.pathname === "/ws") {
if (req.headers.get("upgrade") != "websocket") {
return new Response(null, { status: 501 });
}
const { socket, response } = Deno.upgradeWebSocket(req);
socket.binaryType = "arraybuffer";
asChannel<
DocResponse,
DocRequest
>(socket).then(useChannel).catch((e) => {
console.log(e);
}).finally(() => {
console.log("CLOSED CALLED");
socket.close();
});
return response;
}
console.log(url.toString());
// http://localhost:8081/$deployment_id/$file_path
const hash = url.searchParams.get("hash");
if (!hash) {
return new Response(null, { status: 400 });
}
return new Response(fileContentChallenges[hash], { status: 200 });
} catch (err) {
console.log(err);
return new Response(null, { status: 500 });
}
});