forked from zhmushan/dev_server
-
Notifications
You must be signed in to change notification settings - Fork 0
/
mod.ts
156 lines (140 loc) · 3.93 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
import type { DirMetadata } from "./types.ts";
import { toFileUrl } from "https://deno.land/std@0.224.0/path/mod.ts";
import {
Application,
colors,
cors,
flags,
fs,
Header,
logger,
MIME,
NotFoundException,
path,
} from "./deps.ts";
import { transpile } from "jsr:@deno/emit";
const { readFile, cwd, stat, args, exit, writeTextFile } = Deno;
const { join } = path;
const { exists, ensureDir } = fs;
const { parse } = flags;
const { green } = colors;
const hasOwnProperty = Object.prototype.hasOwnProperty;
interface ServerArgs {
_: string[];
// -p --port
p: number;
port: number;
// --tsconfig
tsconfig: string;
// --template
template: string;
// -h --help
h: boolean;
help: boolean;
}
const serverArgs = parse(args) as ServerArgs;
if (serverArgs.h ?? serverArgs.help) {
console.log(`Dev Server
INSTALL:
deno install -A --unstable https://deno.land/x/dev_server/mod.ts
USAGE:
dev_server [path] [options]
OPTIONS:
-h, --help Prints help information
-p, --port <port> Set port
--tsconfig <path> Path to tsconfig.json
--template <name> Create app with template`);
exit();
}
const port = serverArgs.port ?? serverArgs.p ?? 8080;
const target = join(cwd(), serverArgs._[0] ?? ".");
const tsconfigPath = join(target, serverArgs.tsconfig ?? "tsconfig.json");
let compilerOptions: Deno.CompilerOptions = {};
if (typeof serverArgs.template === "string") {
const templateMetadata: DirMetadata = await fetch(
"https://deno.land/x/dev_server/template.json",
).then((resp) => resp.json());
const url = "https://deno.land/x/dev_server/template";
if (hasOwnProperty.call(templateMetadata, serverArgs.template)) {
const template = templateMetadata[serverArgs.template];
const processes: Promise<unknown>[] = [];
if (typeof template === "object") {
await createDirFromMetadata(
target,
`${url}/${serverArgs.template}`,
template,
);
}
await Promise.all(processes);
async function createDirFromMetadata(
localPath: string,
resourcePath: string,
metadata: DirMetadata,
) {
await ensureDir(localPath);
for (const k in metadata) {
const maybeMetadata = metadata[k];
const lp = join(localPath, k);
const rp = `${resourcePath}/${k}`;
if (typeof maybeMetadata === "object") {
await createDirFromMetadata(lp, rp, maybeMetadata);
} else {
const p = fetch(rp)
.then((resp) => resp.text())
.then((data) => writeTextFile(lp, data))
.then(() => console.log(`${green("Create")} ${lp}`));
processes.push(p);
}
}
}
}
}
if (await exists(tsconfigPath)) {
const tsconfig: { compilerOptions: Deno.CompilerOptions } = JSON.parse(
decode(await readFile(tsconfigPath)),
);
if (hasOwnProperty.call(tsconfig, "compilerOptions")) {
compilerOptions = { ...compilerOptions, ...tsconfig.compilerOptions };
}
}
const app = new Application();
app.start({ port, hostname: "0.0.0.0" });
console.log(`Server running at http://0.0.0.0:${port}/`);
app
.use(logger())
.use(cors())
.get("/", (c) => {
return c.redirect("/index.html");
})
.get("/*", async (c) => {
const p = join(target, c.path);
if (!(await exists(p)) || (await stat(p)).isDirectory) {
throw new NotFoundException();
}
const f = await readFile(p);
if (/\.[j|t]sx?$/.test(c.path)) {
c.response.headers.set(
Header.ContentType,
MIME.ApplicationJavaScriptCharsetUTF8,
);
return transform(p);
} else if (c.path === "/index.html") {
return c.htmlBlob(f);
}
c.blob(f);
});
async function transform(rootName: string) {
const url = toFileUrl(rootName)
const result = await transpile(
url,
{
bundle: "module",
check: true,
compilerOptions,
},
);
return result.get(url.href);
}
function decode(b: Uint8Array) {
return new TextDecoder().decode(b);
}