-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdev-server.js
More file actions
176 lines (152 loc) · 4.71 KB
/
dev-server.js
File metadata and controls
176 lines (152 loc) · 4.71 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
176
import { listenAndServe } from "https://deno.land/std@0.113.0/http/server.ts";
import { serveFile } from "https://deno.land/std@0.113.0/http/file_server.ts";
import {
common,
parse,
extname,
toFileUrl,
} from "https://deno.land/std@0.113.0/path/mod.ts";
import { ensureDir } from "https://deno.land/std@0.113.0/fs/mod.ts";
import { MEDIA_TYPES } from "./media-type.js";
const staticAssets = {
"/": "./dev.html",
"/dev.html": "./dev.html",
"/css/style.css": "./css/style.css",
"/js/dev.js": "./js/dev.js"
};
/**
* @param {string} path
* @returns {string}
*/
function removeLeadingSlash(path) {
if (path.startsWith("/")) {
return path.slice(1);
}
return path;
}
/**
* @param {string} path
* @returns {string}
*/
function removeTrailingSlash(path) {
if (path.endsWith("/")) {
return path.slice(0, -1);
}
return path;
}
/**
* @param {string} path
* @returns {string}
*/
function removeSlashes(path) {
return removeTrailingSlash(removeLeadingSlash(path));
}
/**
* @param {Request} request
* @returns {Promise<Response>}
*/
async function requestHandler(request) {
const mode = request.headers.get('sec-fetch-mode');
const dest = request.headers.get('sec-fetch-dest');
const site = request.headers.get('sec-fetch-site');
const { pathname } = new URL(request.url);
if (globalThis.sessionStorage) {
const storedFileKey = removeSlashes(pathname);
const storedFile = globalThis.sessionStorage.getItem(storedFileKey);
if (storedFile) {
return new Response(storedFile, {
// @ts-ignore
headers: {
// @ts-ignore
"content-type": MEDIA_TYPES[extname(storedFileKey)],
"x-cache-hit": true
}
});
}
}
// @ts-ignore
const staticFile = staticAssets[pathname];
// Check if the request is for static file.
if (staticFile) {
try {
if (mode === 'navigate' || dest === 'document') {
const content = await Deno.readTextFile(staticFile);
const { main } = await import('./js/importmap-generator.js');
const importMap = await main();
const [beforeImportmap, afterImportmap] = content.split("//__importmap");
const html = `${beforeImportmap}${importMap}${afterImportmap}`;
return new Response(html, {
headers: {
"content-type": MEDIA_TYPES['.html'],
}
});
}
return serveFile(request, staticFile);
} catch (error) {
return new Response(error.message || error.toString(), { status: 500 })
}
}
if (dest === 'script' && mode === 'cors' && site === 'same-origin' && pathname.endsWith(".jsx.js")) {
try {
const { files, diagnostics } = await Deno.emit(`.${pathname}`.slice(0, -3));
if (diagnostics.length) {
// there is something that impacted the emit
console.warn(Deno.formatDiagnostics(diagnostics));
}
// @ts-ignore
const [, content] = Object.entries(files).find(([fileName]) => {
const cwd = toFileUrl(Deno.cwd()).href;
const commonPath = common([
cwd,
fileName,
]);
const shortFileName = fileName.replace(commonPath, `/`);
return shortFileName === pathname;
});
return new Response(content);
} catch (error) {
return new Response(error.message || error.toString(), { status: 500 })
}
}
if (extname(pathname) === ".jsx") {
try {
const { files, diagnostics } = await Deno.emit(`.${pathname}`);
if (diagnostics.length) {
// there is something that impacted the emit
console.warn(Deno.formatDiagnostics(diagnostics));
}
for (const [fileName, text] of Object.entries(files)) {
const cwd = toFileUrl(Deno.cwd()).href;
const commonPath = common([
cwd,
fileName,
]);
const shortFileName = fileName.replace(commonPath, ``);
sessionStorage.setItem(shortFileName, text);
const outputFileName = `./dist/${shortFileName}`;
const { dir } = parse(outputFileName);
await ensureDir(dir);
await Deno.writeTextFile(outputFileName, text);
}
return new Response(pathname, {
status: 303,
headers: {
"location": `${request.url}.js`,
},
});
} catch (error) {
return new Response(error.message || error.toString(), { status: 500 })
}
}
return new Response(null, {
status: 404,
});
}
if (import.meta.main) {
const PORT = Deno.env.get("PORT") || 1729;
const timestamp = Date.now();
const humanReadableDateTime = new Date(timestamp).toLocaleString();
console.log('Current Date: ', humanReadableDateTime)
console.info(`Server Listening on http://localhost:${PORT}`);
listenAndServe(`:${PORT}`, requestHandler);
}