-
Notifications
You must be signed in to change notification settings - Fork 1
/
dev.ts
238 lines (214 loc) · 6.23 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
227
228
229
230
231
232
233
234
235
236
237
238
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) => {
context.response.headers.set(
"Access-Control-Allow-Origin",
`http://localhost:${appPort}`,
);
const target = context.sendEvents({ 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", { data: 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.ChildProcess | null = null;
function runDev(entryPoint: string) {
const runCommand = new Deno.Command(Deno.execPath(), {
args: ["run", "-A", entryPoint],
stdin: "null",
});
runProcess = runCommand.spawn();
}
let building = false;
let buildAgain = false;
let buildAgainFor = "";
let restarting = false;
let restartAgain = false;
let reload = false;
const buildDevCommand = new Deno.Command(Deno.execPath(), {
args: ["task", "build"],
stdin: "null",
});
async function buildDev(entryPoint: string, changedPath?: string) {
if (building) {
buildAgain = true;
buildAgainFor = changedPath ?? "";
} else {
buildAgain = false;
buildAgainFor = "";
restartAgain = false;
reload = false;
building = true;
if (changedPath) {
console.log(`Detected change: ${changedPath}`);
}
try {
await Deno.remove(buildDir, { recursive: true });
} catch {
// Ignore error
}
let success = false;
try {
const buildProcess = buildDevCommand.spawn();
success = (await buildProcess.status).success;
} finally {
building = false;
if (buildAgain) {
await buildDev(entryPoint, buildAgainFor);
} else if (success && runProcess) {
await restartApp(entryPoint);
}
}
}
}
async function restartApp(entryPoint: string) {
if (restarting) {
restartAgain = true;
} else if (runProcess) {
restartAgain = false;
reload = false;
restarting = true;
console.log("Restarting app");
queueMicrotask(() => {
try {
runProcess!.kill();
} catch {
// Ignore error
}
});
try {
await runProcess.status;
} catch {
// Ignore error
}
queueMicrotask(async () => {
runDev(entryPoint);
restarting = false;
if (restartAgain) {
await restartApp(entryPoint);
} 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. Defaults to APP_PORT environment variable or 9000. */
appPort?: number;
/** The port for the dev script's live reload server. Defaults to DEV_PORT environment variable or 9001. */
devPort?: number;
/** The entry point for the application server. Defaults to getEnv("APP_ENTRY_POINT") or "./main.ts". */
entryPoint?: string;
}
/**
* 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,
entryPoint,
}: DevOptions = {}) {
if (!appPort) {
const APP_PORT = +(getEnv("APP_PORT") ?? "");
if (APP_PORT && !isNaN(APP_PORT)) {
appPort = APP_PORT;
}
}
if (!devPort) {
const DEV_PORT = +(getEnv("DEV_PORT") ?? "");
if (DEV_PORT && !isNaN(DEV_PORT)) {
devPort = DEV_PORT;
}
}
entryPoint ??= getEnv("APP_ENTRY_POINT") ?? "./main.ts";
const shouldBuild = isCustomBuildArtifact
? ((pathname: string) =>
!isBuildArtifact(pathname) && !isCustomBuildArtifact(pathname))
: ((pathname: string) => !isBuildArtifact(pathname));
queueMicrotask(async () => {
await buildDev(entryPoint!);
console.log("Starting app");
queueMicrotask(() => runDev(entryPoint!));
});
async function watcher() {
console.log(`Watching ${cwd}`);
const build = debounce(
(changedPath: string) =>
queueMicrotask(() => buildDev(entryPoint!, changedPath)),
20,
);
for await (const event of Deno.watchFs(Deno.cwd())) {
if (event.kind === "modify") {
const path = event.paths.find(shouldBuild);
if (path) build(path);
}
}
}
queueMicrotask(watcher);
queueMicrotask(() => {
const app = createDevApp(appPort);
app.listen({ port: devPort ?? 9002 });
});
}
if (import.meta.main) {
startDev();
}