-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathdev.ts
226 lines (204 loc) · 5.54 KB
/
dev.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
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
import * as path from "std/path/mod.ts";
import { debounce } from "std/async/debounce.ts";
import {
Application,
Router,
ServerSentEvent,
ServerSentEventTarget,
} from "x/oak/mod.ts";
import { getEnv, isTest } from "./env.ts";
const sessions = new Map<number, ServerSentEventTarget>();
let nextSessionId = 0;
function createDevApp(appPort = 9000) {
const app = new Application();
const router = new Router()
.get("/live-reload", (context) => {
const target = context.sendEvents({
headers: new Headers({
"Access-Control-Allow-Origin": `http://localhost:${appPort}`,
}),
keepAlive: true,
});
const sessionId = nextSessionId++;
target.addEventListener("close", () => {
sessions.delete(sessionId);
});
target.addEventListener("error", (event) => {
console.log("Live reload: Error", event);
});
sessions.set(sessionId, target);
target.dispatchMessage("Waiting");
})
.get("/listening", ({ response }) => {
response.status = 200;
if (reload) {
console.log("Server restarted");
reload = false;
queueMicrotask(() => {
for (const target of [...sessions.values()]) {
target.dispatchEvent(new ServerSentEvent("reload", null));
}
});
} else {
console.log("Server started");
}
});
app.use(router.routes(), router.allowedMethods());
app.addEventListener("error", ({ error }) => {
console.error("Uncaught app error", error);
});
app.addEventListener("listen", ({ hostname, port, secure }) => {
const origin = `${secure ? "https://" : "http://"}${hostname}`;
console.log(`Live reload listening on: ${origin}:${port}`);
});
return app;
}
let runProcess: Deno.Process | null = null;
function runDev() {
runProcess = Deno.run({
cmd: ["deno", "run", "-A", "./main.ts"],
env: {
APP_ENV: "development",
},
});
}
let building = false;
let buildAgain = false;
let restarting = false;
let restartAgain = false;
let reload = false;
async function buildDev() {
if (building) {
buildAgain = true;
} else {
buildAgain = false;
restartAgain = false;
reload = false;
building = true;
try {
await Deno.remove(buildDir, { recursive: true });
} catch {
// Ignore error
}
let status: Deno.ProcessStatus | null = null;
try {
const buildProcess = Deno.run({
cmd: ["deno", "task", "build"],
env: {
APP_ENV: "development",
},
stdin: "null",
});
status = await buildProcess.status();
} finally {
building = false;
if (buildAgain) {
await buildDev();
} else if (status?.success && runProcess) {
await restartApp();
}
}
}
}
async function restartApp() {
if (restarting) {
restartAgain = true;
} else if (runProcess) {
restartAgain = false;
reload = false;
restarting = true;
console.log("Restarting app");
queueMicrotask(() => {
try {
runProcess!.kill();
runProcess!.close();
} catch {
// Ignore error
}
});
try {
await runProcess.status();
} catch {
// Ignore error
}
queueMicrotask(async () => {
runDev();
restarting = false;
if (restartAgain) {
await restartApp();
} else if (!building) {
reload = true;
}
});
}
}
const cwd = Deno.cwd();
const buildDir = path.resolve(
cwd,
`./public/${isTest() ? "test-" : ""}build`,
);
const artifacts = new Set();
artifacts.add(path.resolve(cwd, "./routes/_main.tsx"));
artifacts.add(path.resolve(cwd, "./routes/_main.ts"));
function isBuildArtifact(pathname: string) {
return pathname.startsWith(buildDir) || artifacts.has(pathname);
}
export interface DevOptions {
/**
* Used to identify and ignore additional build artifacts created in your preBuild and postBuild functions.
*/
isCustomBuildArtifact?: (pathname: string) => boolean;
/** The port that the application uses. */
appPort?: number;
/** The port for the dev script's live reload server. */
devPort?: number;
}
/**
* Starts a file watcher for triggering new builds to be generated.
* When changes are made, the app will be re-built and the app will be restarted.
* Any active browser sessions will be reloaded once the new build is ready and the app has been restarted.
*/
export function startDev({
isCustomBuildArtifact,
appPort,
devPort,
}: DevOptions = {}) {
const shouldBuild = isCustomBuildArtifact
? ((pathname: string) =>
!isBuildArtifact(pathname) && !isCustomBuildArtifact(pathname))
: ((pathname: string) => !isBuildArtifact(pathname));
queueMicrotask(async () => {
await buildDev();
console.log("Starting app");
queueMicrotask(runDev);
});
async function watcher() {
console.log(`Watching ${cwd}`);
const build = debounce(
() => queueMicrotask(() => buildDev()),
20,
);
for await (const event of Deno.watchFs(Deno.cwd())) {
if (event.kind === "modify" && event.paths.find(shouldBuild)) {
build();
}
}
}
queueMicrotask(watcher);
queueMicrotask(() => {
const app = createDevApp(appPort);
app.listen({ port: devPort ?? 9002 });
});
}
if (import.meta.main) {
const options: DevOptions = {};
const appPort = +(getEnv("APP_PORT") ?? "");
if (appPort && !isNaN(appPort)) {
options.appPort = appPort;
}
const devPort = +(getEnv("DEV_PORT") ?? "");
if (devPort && !isNaN(devPort)) {
options.devPort = devPort;
}
startDev(options);
}