BlueGit

timfa questward

Fix AutorunMode re-export and add boot smoke tests.

The settings module exported AutorunMode without importing it, which broke the play client. Smoke coverage now checks unbound re-exports, the HTTP module graph, and a real server boot of play + editor.

timfa Tim Falken · pushed by timfa

Authored 2026-08-30 · 2 months ago

Hash
b5f715908acbc5100e63dd3bfb9475995f00c300
Parent
0c5ad783
4 files changed +318 −1
client/src/play/graphicsSettings.js +1 −0
@@ -2,6 +2,7 @@ import {
2 2 ViewDistance,
3 3 LightingMode,
4 4 BloomMode,
5 AutorunMode,
5 6 loadGraphicsSettings,
6 7 saveGraphicsSettings,
7 8 normalizeGraphicsSettings
@@ -2,6 +2,7 @@ import {
2 ViewDistance,
2 ViewDistance,
3 LightingMode,
3 LightingMode,
4 BloomMode,
4 BloomMode,
5 AutorunMode,
5 loadGraphicsSettings,
6 loadGraphicsSettings,
6 saveGraphicsSettings,
7 saveGraphicsSettings,
7 normalizeGraphicsSettings
8 normalizeGraphicsSettings
package.json +1 −0
@@ -8,6 +8,7 @@
8 8 "scripts": {
9 9 "start": "node --experimental-sqlite server/src/index.js",
10 10 "test": "node --experimental-sqlite --test server/tests/**/*.test.js client/tests/**/*.test.js",
11 "test:smoke": "node --experimental-sqlite --test server/tests/smoke-boot.test.js",
11 12 "build:client": "node client/scripts/build-framework.mjs"
12 13 },
13 14 "dependencies": {
@@ -8,6 +8,7 @@
8 "scripts": {
8 "scripts": {
9 "start": "node --experimental-sqlite server/src/index.js",
9 "start": "node --experimental-sqlite server/src/index.js",
10 "test": "node --experimental-sqlite --test server/tests/**/*.test.js client/tests/**/*.test.js",
10 "test": "node --experimental-sqlite --test server/tests/**/*.test.js client/tests/**/*.test.js",
11 "test:smoke": "node --experimental-sqlite --test server/tests/smoke-boot.test.js",
11 "build:client": "node client/scripts/build-framework.mjs"
12 "build:client": "node client/scripts/build-framework.mjs"
12 },
13 },
13 "dependencies": {
14 "dependencies": {
server/src/index.js +3 −1
@@ -15,7 +15,9 @@ import { hookConsoleCapture } from "./logging/consoleCapture.js";
15 15 hookConsoleCapture();
16 16
17 17 const rootDir = repoRootFrom(import.meta.url);
18 const dataDir = join(rootDir, "server", "data");
18 const dataDir = process.env.QUESTWARD_DATA_DIR
19 ? join(process.env.QUESTWARD_DATA_DIR)
20 : join(rootDir, "server", "data");
19 21 const port = Number(process.env.PORT ?? 8080);
20 22
21 23 const worldDb = new WorldDatabase(join(dataDir, "world.sqlite"));
@@ -15,7 +15,9 @@ import { hookConsoleCapture } from "./logging/consoleCapture.js";
15hookConsoleCapture();
15hookConsoleCapture();
16
16
17const rootDir = repoRootFrom(import.meta.url);
17const rootDir = repoRootFrom(import.meta.url);
18const dataDir = join(rootDir, "server", "data");
18const dataDir = process.env.QUESTWARD_DATA_DIR
19 ? join(process.env.QUESTWARD_DATA_DIR)
20 : join(rootDir, "server", "data");
19const port = Number(process.env.PORT ?? 8080);
21const port = Number(process.env.PORT ?? 8080);
20
22
21const worldDb = new WorldDatabase(join(dataDir, "world.sqlite"));
23const worldDb = new WorldDatabase(join(dataDir, "world.sqlite"));
server/tests/smoke-boot.test.js added +313 −0
@@ -0,0 +1,313 @@
1 import test from "node:test";
2 import assert from "node:assert/strict";
3 import { spawn } from "node:child_process";
4 import { mkdtempSync, readdirSync, readFileSync } from "node:fs";
5 import { tmpdir } from "node:os";
6 import { dirname, extname, join, relative } from "node:path";
7 import { createHttpServer, repoRootFrom } from "../src/gateway/http.js";
8
9 const ROOT = repoRootFrom(import.meta.url);
10 const CLIENT_SRC = join(ROOT, "client", "src");
11
12 const PLAY_ENTRY = "/src/play/main.js";
13 const EDITOR_ENTRY = "/src/editor/main.js";
14
15 test("client modules do not re-export unbound names", () =>
16 {
17 const offenders = [];
18 for (const file of listJsFiles(CLIENT_SRC))
19 {
20 const source = readFileSync(file, "utf8");
21 for (const name of unboundReexportLocals(source))
22 {
23 offenders.push(`${relative(ROOT, file)}: export { ${name} } is not defined in module`);
24 }
25 }
26 assert.deepEqual(offenders, []);
27 });
28
29 test("HTTP smoke: play, editor, and module graph resolve", async () =>
30 {
31 const server = createHttpServer(ROOT);
32 await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve));
33 const { port } = server.address();
34 const base = `http://127.0.0.1:${port}`;
35 try
36 {
37 assert.equal((await fetch(`${base}/`)).status, 200);
38 assert.equal((await fetch(`${base}/editor`)).status, 200);
39 assert.equal((await fetch(`${base}/framework/framework.js`)).status, 200);
40 assert.equal((await fetch(`${base}/assets/catalog.json`)).status, 200);
41
42 const playHtml = await (await fetch(`${base}/`)).text();
43 assert.match(playHtml, /src="\/src\/play\/main\.js"/);
44 const editorHtml = await (await fetch(`${base}/editor`)).text();
45 assert.match(editorHtml, /src="\/src\/editor\/main\.js"/);
46
47 const seen = new Set();
48 await crawlModuleGraph(base, PLAY_ENTRY, seen);
49 await crawlModuleGraph(base, EDITOR_ENTRY, seen);
50 assert.ok(seen.has(PLAY_ENTRY));
51 assert.ok(seen.has(EDITOR_ENTRY));
52 assert.ok(seen.size > 20, `expected a substantial module graph, got ${seen.size}`);
53 }
54 finally
55 {
56 await new Promise((resolve) => server.close(resolve));
57 }
58 });
59
60 test("server process boots and serves play + editor", async () =>
61 {
62 const dataDir = mkdtempSync(join(tmpdir(), "questward-smoke-"));
63 const port = await freePort();
64 const child = spawn(
65 process.execPath,
66 ["--experimental-sqlite", join(ROOT, "server", "src", "index.js")],
67 {
68 cwd: ROOT,
69 env: {
70 ...process.env,
71 PORT: String(port),
72 QUESTWARD_DATA_DIR: dataDir,
73 QUESTWARD_DEPLOY_SCHEDULER: "0",
74 QUESTWARD_AUTH_STUB: "1",
75 SIMULATION_WORKERS: "1",
76 SIMULATION_WORKER_MODE: "inprocess"
77 },
78 stdio: ["ignore", "pipe", "pipe"]
79 }
80 );
81
82 let stdout = "";
83 let stderr = "";
84 child.stdout.on("data", (chunk) => { stdout += chunk; });
85 child.stderr.on("data", (chunk) => { stderr += chunk; });
86 let exitCode = null;
87 child.on("exit", (code) => { exitCode = code; });
88
89 try
90 {
91 await waitFor(
92 () => /Questward listening/.test(stdout + stderr),
93 () =>
94 {
95 if (exitCode != null)
96 {
97 throw new Error(
98 `Server exited early (${exitCode}). Output:\n${stdout}\n${stderr}`
99 );
100 }
101 },
102 20_000
103 );
104 const base = `http://127.0.0.1:${port}`;
105 assert.equal((await fetch(`${base}/`)).status, 200);
106 assert.equal((await fetch(`${base}/editor`)).status, 200);
107 assert.equal((await fetch(`${base}${PLAY_ENTRY}`)).status, 200);
108 assert.equal((await fetch(`${base}${EDITOR_ENTRY}`)).status, 200);
109 }
110 finally
111 {
112 if (exitCode == null)
113 {
114 child.kill("SIGTERM");
115 await new Promise((resolve) =>
116 {
117 const timer = setTimeout(() =>
118 {
119 child.kill("SIGKILL");
120 resolve();
121 }, 5_000);
122 child.on("exit", () =>
123 {
124 clearTimeout(timer);
125 resolve();
126 });
127 });
128 }
129 }
130
131 assert.doesNotMatch(stderr, /SyntaxError|Export '.*' is not defined/);
132 assert.doesNotMatch(stdout, /SyntaxError|Export '.*' is not defined/);
133 });
134
135 async function crawlModuleGraph (base, urlPath, seen)
136 {
137 if (seen.has(urlPath))
138 { return; }
139 seen.add(urlPath);
140 const res = await fetch(`${base}${urlPath}`);
141 assert.equal(res.status, 200, `missing module ${urlPath}`);
142 const type = res.headers.get("content-type") ?? "";
143 assert.match(type, /javascript|ecmascript/, `${urlPath} content-type ${type}`);
144 const source = await res.text();
145 for (const name of unboundReexportLocals(source))
146 {
147 assert.fail(`${urlPath}: export { ${name} } is not defined in module`);
148 }
149 for (const spec of staticImportSpecifiers(source))
150 {
151 const next = resolveBrowserSpecifier(urlPath, spec);
152 if (!next)
153 { continue; }
154 await crawlModuleGraph(base, next, seen);
155 }
156 }
157
158 function resolveBrowserSpecifier (fromPath, spec)
159 {
160 if (spec.startsWith("/"))
161 { return spec.split("?")[0]; }
162 if (!spec.startsWith("."))
163 { return null; }
164 const fromDir = dirname(fromPath);
165 const parts = [...fromDir.split("/").filter(Boolean)];
166 for (const part of spec.split("/"))
167 {
168 if (part === "." || part === "")
169 { continue; }
170 if (part === "..")
171 { parts.pop(); }
172 else
173 { parts.push(part); }
174 }
175 return `/${parts.join("/")}`;
176 }
177
178 function staticImportSpecifiers (source)
179 {
180 const specs = [];
181 const cleaned = stripComments(source);
182 for (const match of cleaned.matchAll(/\b(?:import|export)\s+(?:[^'";]*?\s+from\s+)?["']([^"']+)["']/g))
183 { specs.push(match[1]); }
184 for (const match of cleaned.matchAll(/\bimport\s*\(\s*["']([^"']+)["']\s*\)/g))
185 { specs.push(match[1]); }
186 return specs;
187 }
188
189 function unboundReexportLocals (source)
190 {
191 const cleaned = stripComments(source);
192 const defined = new Set([
193 ...importedBindings(cleaned),
194 ...localBindings(cleaned)
195 ]);
196 const missing = [];
197 for (const match of cleaned.matchAll(/\bexport\s*\{([^}]+)\}(\s*from\s*["'][^"']+["'])?/g))
198 {
199 if (match[2])
200 { continue; }
201 for (const part of match[1].split(","))
202 {
203 const trimmed = part.trim();
204 if (!trimmed)
205 { continue; }
206 const local = trimmed.split(/\s+as\s+/)[0].trim();
207 if (!local || local === "default")
208 { continue; }
209 if (!defined.has(local))
210 { missing.push(local); }
211 }
212 }
213 return missing;
214 }
215
216 function importedBindings (source)
217 {
218 const names = new Set();
219 for (const match of source.matchAll(/\bimport\s*\{([^}]+)\}\s*from\s*["']/g))
220 {
221 for (const part of match[1].split(","))
222 {
223 const trimmed = part.trim();
224 if (!trimmed)
225 { continue; }
226 const bits = trimmed.split(/\s+as\s+/);
227 names.add(bits[bits.length - 1].trim());
228 }
229 }
230 for (const match of source.matchAll(/\bimport\s+([A-Za-z_$][\w$]*)\s*,\s*\{/g))
231 { names.add(match[1]); }
232 for (const match of source.matchAll(/\bimport\s+([A-Za-z_$][\w$]*)\s+from\s*["']/g))
233 { names.add(match[1]); }
234 for (const match of source.matchAll(/\bimport\s*\*\s*as\s+([A-Za-z_$][\w$]*)\s+from\s*["']/g))
235 { names.add(match[1]); }
236 return names;
237 }
238
239 function localBindings (source)
240 {
241 const names = new Set();
242 for (const match of source.matchAll(/\b(?:async\s+)?function\s+([A-Za-z_$][\w$]*)/g))
243 { names.add(match[1]); }
244 for (const match of source.matchAll(/\bclass\s+([A-Za-z_$][\w$]*)/g))
245 { names.add(match[1]); }
246 for (const match of source.matchAll(/\b(?:const|let|var)\s+([A-Za-z_$][\w$]*)/g))
247 { names.add(match[1]); }
248 return names;
249 }
250
251 function stripComments (source)
252 {
253 return source
254 .replace(/\/\*[\s\S]*?\*\//g, "")
255 .replace(/(^|[^:])\/\/.*$/gm, "$1");
256 }
257
258 function listJsFiles (dir)
259 {
260 const out = [];
261 for (const entry of readdirSync(dir, { withFileTypes: true }))
262 {
263 const path = join(dir, entry.name);
264 if (entry.isDirectory())
265 { out.push(...listJsFiles(path)); }
266 else if (extname(entry.name) === ".js")
267 { out.push(path); }
268 }
269 return out;
270 }
271
272 function freePort ()
273 {
274 return new Promise((resolve, reject) =>
275 {
276 const server = createHttpServer(ROOT);
277 server.listen(0, "127.0.0.1", () =>
278 {
279 const { port } = server.address();
280 server.close((error) => (error ? reject(error) : resolve(port)));
281 });
282 });
283 }
284
285 function waitFor (isReady, onTick, timeoutMs)
286 {
287 const started = Date.now();
288 return new Promise((resolve, reject) =>
289 {
290 const tick = () =>
291 {
292 try
293 { onTick?.(); }
294 catch (error)
295 {
296 reject(error);
297 return;
298 }
299 if (isReady())
300 {
301 resolve();
302 return;
303 }
304 if (Date.now() - started > timeoutMs)
305 {
306 reject(new Error(`Timed out after ${timeoutMs}ms`));
307 return;
308 }
309 setTimeout(tick, 50);
310 };
311 tick();
312 });
313 }
@@ -0,0 +1,313 @@
1import test from "node:test";
2import assert from "node:assert/strict";
3import { spawn } from "node:child_process";
4import { mkdtempSync, readdirSync, readFileSync } from "node:fs";
5import { tmpdir } from "node:os";
6import { dirname, extname, join, relative } from "node:path";
7import { createHttpServer, repoRootFrom } from "../src/gateway/http.js";
8
9const ROOT = repoRootFrom(import.meta.url);
10const CLIENT_SRC = join(ROOT, "client", "src");
11
12const PLAY_ENTRY = "/src/play/main.js";
13const EDITOR_ENTRY = "/src/editor/main.js";
14
15test("client modules do not re-export unbound names", () =>
16{
17 const offenders = [];
18 for (const file of listJsFiles(CLIENT_SRC))
19 {
20 const source = readFileSync(file, "utf8");
21 for (const name of unboundReexportLocals(source))
22 {
23 offenders.push(`${relative(ROOT, file)}: export { ${name} } is not defined in module`);
24 }
25 }
26 assert.deepEqual(offenders, []);
27});
28
29test("HTTP smoke: play, editor, and module graph resolve", async () =>
30{
31 const server = createHttpServer(ROOT);
32 await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve));
33 const { port } = server.address();
34 const base = `http://127.0.0.1:${port}`;
35 try
36 {
37 assert.equal((await fetch(`${base}/`)).status, 200);
38 assert.equal((await fetch(`${base}/editor`)).status, 200);
39 assert.equal((await fetch(`${base}/framework/framework.js`)).status, 200);
40 assert.equal((await fetch(`${base}/assets/catalog.json`)).status, 200);
41
42 const playHtml = await (await fetch(`${base}/`)).text();
43 assert.match(playHtml, /src="\/src\/play\/main\.js"/);
44 const editorHtml = await (await fetch(`${base}/editor`)).text();
45 assert.match(editorHtml, /src="\/src\/editor\/main\.js"/);
46
47 const seen = new Set();
48 await crawlModuleGraph(base, PLAY_ENTRY, seen);
49 await crawlModuleGraph(base, EDITOR_ENTRY, seen);
50 assert.ok(seen.has(PLAY_ENTRY));
51 assert.ok(seen.has(EDITOR_ENTRY));
52 assert.ok(seen.size > 20, `expected a substantial module graph, got ${seen.size}`);
53 }
54 finally
55 {
56 await new Promise((resolve) => server.close(resolve));
57 }
58});
59
60test("server process boots and serves play + editor", async () =>
61{
62 const dataDir = mkdtempSync(join(tmpdir(), "questward-smoke-"));
63 const port = await freePort();
64 const child = spawn(
65 process.execPath,
66 ["--experimental-sqlite", join(ROOT, "server", "src", "index.js")],
67 {
68 cwd: ROOT,
69 env: {
70 ...process.env,
71 PORT: String(port),
72 QUESTWARD_DATA_DIR: dataDir,
73 QUESTWARD_DEPLOY_SCHEDULER: "0",
74 QUESTWARD_AUTH_STUB: "1",
75 SIMULATION_WORKERS: "1",
76 SIMULATION_WORKER_MODE: "inprocess"
77 },
78 stdio: ["ignore", "pipe", "pipe"]
79 }
80 );
81
82 let stdout = "";
83 let stderr = "";
84 child.stdout.on("data", (chunk) => { stdout += chunk; });
85 child.stderr.on("data", (chunk) => { stderr += chunk; });
86 let exitCode = null;
87 child.on("exit", (code) => { exitCode = code; });
88
89 try
90 {
91 await waitFor(
92 () => /Questward listening/.test(stdout + stderr),
93 () =>
94 {
95 if (exitCode != null)
96 {
97 throw new Error(
98 `Server exited early (${exitCode}). Output:\n${stdout}\n${stderr}`
99 );
100 }
101 },
102 20_000
103 );
104 const base = `http://127.0.0.1:${port}`;
105 assert.equal((await fetch(`${base}/`)).status, 200);
106 assert.equal((await fetch(`${base}/editor`)).status, 200);
107 assert.equal((await fetch(`${base}${PLAY_ENTRY}`)).status, 200);
108 assert.equal((await fetch(`${base}${EDITOR_ENTRY}`)).status, 200);
109 }
110 finally
111 {
112 if (exitCode == null)
113 {
114 child.kill("SIGTERM");
115 await new Promise((resolve) =>
116 {
117 const timer = setTimeout(() =>
118 {
119 child.kill("SIGKILL");
120 resolve();
121 }, 5_000);
122 child.on("exit", () =>
123 {
124 clearTimeout(timer);
125 resolve();
126 });
127 });
128 }
129 }
130
131 assert.doesNotMatch(stderr, /SyntaxError|Export '.*' is not defined/);
132 assert.doesNotMatch(stdout, /SyntaxError|Export '.*' is not defined/);
133});
134
135async function crawlModuleGraph (base, urlPath, seen)
136{
137 if (seen.has(urlPath))
138 { return; }
139 seen.add(urlPath);
140 const res = await fetch(`${base}${urlPath}`);
141 assert.equal(res.status, 200, `missing module ${urlPath}`);
142 const type = res.headers.get("content-type") ?? "";
143 assert.match(type, /javascript|ecmascript/, `${urlPath} content-type ${type}`);
144 const source = await res.text();
145 for (const name of unboundReexportLocals(source))
146 {
147 assert.fail(`${urlPath}: export { ${name} } is not defined in module`);
148 }
149 for (const spec of staticImportSpecifiers(source))
150 {
151 const next = resolveBrowserSpecifier(urlPath, spec);
152 if (!next)
153 { continue; }
154 await crawlModuleGraph(base, next, seen);
155 }
156}
157
158function resolveBrowserSpecifier (fromPath, spec)
159{
160 if (spec.startsWith("/"))
161 { return spec.split("?")[0]; }
162 if (!spec.startsWith("."))
163 { return null; }
164 const fromDir = dirname(fromPath);
165 const parts = [...fromDir.split("/").filter(Boolean)];
166 for (const part of spec.split("/"))
167 {
168 if (part === "." || part === "")
169 { continue; }
170 if (part === "..")
171 { parts.pop(); }
172 else
173 { parts.push(part); }
174 }
175 return `/${parts.join("/")}`;
176}
177
178function staticImportSpecifiers (source)
179{
180 const specs = [];
181 const cleaned = stripComments(source);
182 for (const match of cleaned.matchAll(/\b(?:import|export)\s+(?:[^'";]*?\s+from\s+)?["']([^"']+)["']/g))
183 { specs.push(match[1]); }
184 for (const match of cleaned.matchAll(/\bimport\s*\(\s*["']([^"']+)["']\s*\)/g))
185 { specs.push(match[1]); }
186 return specs;
187}
188
189function unboundReexportLocals (source)
190{
191 const cleaned = stripComments(source);
192 const defined = new Set([
193 ...importedBindings(cleaned),
194 ...localBindings(cleaned)
195 ]);
196 const missing = [];
197 for (const match of cleaned.matchAll(/\bexport\s*\{([^}]+)\}(\s*from\s*["'][^"']+["'])?/g))
198 {
199 if (match[2])
200 { continue; }
201 for (const part of match[1].split(","))
202 {
203 const trimmed = part.trim();
204 if (!trimmed)
205 { continue; }
206 const local = trimmed.split(/\s+as\s+/)[0].trim();
207 if (!local || local === "default")
208 { continue; }
209 if (!defined.has(local))
210 { missing.push(local); }
211 }
212 }
213 return missing;
214}
215
216function importedBindings (source)
217{
218 const names = new Set();
219 for (const match of source.matchAll(/\bimport\s*\{([^}]+)\}\s*from\s*["']/g))
220 {
221 for (const part of match[1].split(","))
222 {
223 const trimmed = part.trim();
224 if (!trimmed)
225 { continue; }
226 const bits = trimmed.split(/\s+as\s+/);
227 names.add(bits[bits.length - 1].trim());
228 }
229 }
230 for (const match of source.matchAll(/\bimport\s+([A-Za-z_$][\w$]*)\s*,\s*\{/g))
231 { names.add(match[1]); }
232 for (const match of source.matchAll(/\bimport\s+([A-Za-z_$][\w$]*)\s+from\s*["']/g))
233 { names.add(match[1]); }
234 for (const match of source.matchAll(/\bimport\s*\*\s*as\s+([A-Za-z_$][\w$]*)\s+from\s*["']/g))
235 { names.add(match[1]); }
236 return names;
237}
238
239function localBindings (source)
240{
241 const names = new Set();
242 for (const match of source.matchAll(/\b(?:async\s+)?function\s+([A-Za-z_$][\w$]*)/g))
243 { names.add(match[1]); }
244 for (const match of source.matchAll(/\bclass\s+([A-Za-z_$][\w$]*)/g))
245 { names.add(match[1]); }
246 for (const match of source.matchAll(/\b(?:const|let|var)\s+([A-Za-z_$][\w$]*)/g))
247 { names.add(match[1]); }
248 return names;
249}
250
251function stripComments (source)
252{
253 return source
254 .replace(/\/\*[\s\S]*?\*\//g, "")
255 .replace(/(^|[^:])\/\/.*$/gm, "$1");
256}
257
258function listJsFiles (dir)
259{
260 const out = [];
261 for (const entry of readdirSync(dir, { withFileTypes: true }))
262 {
263 const path = join(dir, entry.name);
264 if (entry.isDirectory())
265 { out.push(...listJsFiles(path)); }
266 else if (extname(entry.name) === ".js")
267 { out.push(path); }
268 }
269 return out;
270}
271
272function freePort ()
273{
274 return new Promise((resolve, reject) =>
275 {
276 const server = createHttpServer(ROOT);
277 server.listen(0, "127.0.0.1", () =>
278 {
279 const { port } = server.address();
280 server.close((error) => (error ? reject(error) : resolve(port)));
281 });
282 });
283}
284
285function waitFor (isReady, onTick, timeoutMs)
286{
287 const started = Date.now();
288 return new Promise((resolve, reject) =>
289 {
290 const tick = () =>
291 {
292 try
293 { onTick?.(); }
294 catch (error)
295 {
296 reject(error);
297 return;
298 }
299 if (isReady())
300 {
301 resolve();
302 return;
303 }
304 if (Date.now() - started > timeoutMs)
305 {
306 reject(new Error(`Timed out after ${timeoutMs}ms`));
307 return;
308 }
309 setTimeout(tick, 50);
310 };
311 tick();
312 });
313}