-
Notifications
You must be signed in to change notification settings - Fork 0
/
serverless.js
155 lines (137 loc) · 4.06 KB
/
serverless.js
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
import { listenAndServe } from "https://deno.land/std@0.115.1/http/server.ts";
import { serveFile } from "https://deno.land/std@0.115.1/http/file_server.ts";
import {
common,
extname,
toFileUrl,
} from "https://deno.land/std@0.115.1/path/mod.ts";
import { MEDIA_TYPES } from "./media-type.js";
import { main as generateImportmap } from './importmap-generator.js';
const staticAssets = {
"/": "./index.html",
"/index.html": "./index.html",
"/css/style.css": "./css/style.css",
"/js/main.js": "./js/main.js",
"/data/initial-data.js": "./data/initial-data.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'
}
});
}
}
// @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 importMap = await generateImportmap();
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, {
headers: {
"content-type": MEDIA_TYPES['.js'],
}
});
} catch (error) {
return new Response(error.message || error.toString(), { status: 500 })
}
}
if (extname(pathname) === ".jsx") {
try {
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);
}