| 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("client modules do not declare duplicate import bindings", () => |
| 30 | { |
| 31 | const offenders = []; |
| 32 | for (const file of listJsFiles(CLIENT_SRC)) |
| 33 | { |
| 34 | const source = readFileSync(file, "utf8"); |
| 35 | for (const name of duplicateImportBindings(source)) |
| 36 | { |
| 37 | offenders.push(`${relative(ROOT, file)}: duplicate import binding '${name}'`); |
| 38 | } |
| 39 | } |
| 40 | assert.deepEqual(offenders, []); |
| 41 | }); |
| 42 | |
| 43 | test("HTTP smoke: play, editor, and module graph resolve", async () => |
| 44 | { |
| 45 | const server = createHttpServer(ROOT); |
| 46 | await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve)); |
| 47 | const { port } = server.address(); |
| 48 | const base = `http://127.0.0.1:${port}`; |
| 49 | try |
| 50 | { |
| 51 | assert.equal((await fetch(`${base}/`)).status, 200); |
| 52 | assert.equal((await fetch(`${base}/editor`)).status, 200); |
| 53 | assert.equal((await fetch(`${base}/framework/framework.js`)).status, 200); |
| 54 | assert.equal((await fetch(`${base}/assets/catalog.json`)).status, 200); |
| 55 | |
| 56 | const playHtml = await (await fetch(`${base}/`)).text(); |
| 57 | assert.match(playHtml, /src="\/src\/play\/main\.js"/); |
| 58 | const editorHtml = await (await fetch(`${base}/editor`)).text(); |
| 59 | assert.match(editorHtml, /src="\/src\/editor\/main\.js"/); |
| 60 | |
| 61 | const seen = new Set(); |
| 62 | await crawlModuleGraph(base, PLAY_ENTRY, seen); |
| 63 | await crawlModuleGraph(base, EDITOR_ENTRY, seen); |
| 64 | assert.ok(seen.has(PLAY_ENTRY)); |
| 65 | assert.ok(seen.has(EDITOR_ENTRY)); |
| 66 | assert.ok(seen.size > 20, `expected a substantial module graph, got ${seen.size}`); |
| 67 | } |
| 68 | finally |
| 69 | { |
| 70 | await new Promise((resolve) => server.close(resolve)); |
| 71 | } |
| 72 | }); |
| 73 | |
| 74 | test("server process boots and serves play + editor", async () => |
| 75 | { |
| 76 | const dataDir = mkdtempSync(join(tmpdir(), "questward-smoke-")); |
| 77 | const port = await freePort(); |
| 78 | const child = spawn( |
| 79 | process.execPath, |
| 80 | ["--experimental-sqlite", join(ROOT, "server", "src", "index.js")], |
| 81 | { |
| 82 | cwd: ROOT, |
| 83 | env: { |
| 84 | ...process.env, |
| 85 | PORT: String(port), |
| 86 | QUESTWARD_DATA_DIR: dataDir, |
| 87 | QUESTWARD_DEPLOY_SCHEDULER: "0", |
| 88 | QUESTWARD_AUTH_STUB: "1", |
| 89 | SIMULATION_WORKERS: "1", |
| 90 | SIMULATION_WORKER_MODE: "inprocess" |
| 91 | }, |
| 92 | stdio: ["ignore", "pipe", "pipe"] |
| 93 | } |
| 94 | ); |
| 95 | |
| 96 | let stdout = ""; |
| 97 | let stderr = ""; |
| 98 | child.stdout.on("data", (chunk) => { stdout += chunk; }); |
| 99 | child.stderr.on("data", (chunk) => { stderr += chunk; }); |
| 100 | let exitCode = null; |
| 101 | child.on("exit", (code) => { exitCode = code; }); |
| 102 | |
| 103 | try |
| 104 | { |
| 105 | await waitFor( |
| 106 | () => /Questward listening/.test(stdout + stderr), |
| 107 | () => |
| 108 | { |
| 109 | if (exitCode != null) |
| 110 | { |
| 111 | throw new Error( |
| 112 | `Server exited early (${exitCode}). Output:\n${stdout}\n${stderr}` |
| 113 | ); |
| 114 | } |
| 115 | }, |
| 116 | 20_000 |
| 117 | ); |
| 118 | const base = `http://127.0.0.1:${port}`; |
| 119 | assert.equal((await fetch(`${base}/`)).status, 200); |
| 120 | assert.equal((await fetch(`${base}/editor`)).status, 200); |
| 121 | assert.equal((await fetch(`${base}${PLAY_ENTRY}`)).status, 200); |
| 122 | assert.equal((await fetch(`${base}${EDITOR_ENTRY}`)).status, 200); |
| 123 | } |
| 124 | finally |
| 125 | { |
| 126 | if (exitCode == null) |
| 127 | { |
| 128 | child.kill("SIGTERM"); |
| 129 | await new Promise((resolve) => |
| 130 | { |
| 131 | const timer = setTimeout(() => |
| 132 | { |
| 133 | child.kill("SIGKILL"); |
| 134 | resolve(); |
| 135 | }, 5_000); |
| 136 | child.on("exit", () => |
| 137 | { |
| 138 | clearTimeout(timer); |
| 139 | resolve(); |
| 140 | }); |
| 141 | }); |
| 142 | } |
| 143 | } |
| 144 | |
| 145 | assert.doesNotMatch(stderr, /SyntaxError|Export '.*' is not defined/); |
| 146 | assert.doesNotMatch(stdout, /SyntaxError|Export '.*' is not defined/); |
| 147 | }); |
| 148 | |
| 149 | async function crawlModuleGraph (base, urlPath, seen) |
| 150 | { |
| 151 | if (seen.has(urlPath)) |
| 152 | { return; } |
| 153 | seen.add(urlPath); |
| 154 | const res = await fetch(`${base}${urlPath}`); |
| 155 | assert.equal(res.status, 200, `missing module ${urlPath}`); |
| 156 | const type = res.headers.get("content-type") ?? ""; |
| 157 | assert.match(type, /javascript|ecmascript/, `${urlPath} content-type ${type}`); |
| 158 | const source = await res.text(); |
| 159 | for (const name of unboundReexportLocals(source)) |
| 160 | { |
| 161 | assert.fail(`${urlPath}: export { ${name} } is not defined in module`); |
| 162 | } |
| 163 | for (const name of duplicateImportBindings(source)) |
| 164 | { |
| 165 | assert.fail(`${urlPath}: duplicate import binding '${name}'`); |
| 166 | } |
| 167 | for (const spec of staticImportSpecifiers(source)) |
| 168 | { |
| 169 | const next = resolveBrowserSpecifier(urlPath, spec); |
| 170 | if (!next) |
| 171 | { continue; } |
| 172 | await crawlModuleGraph(base, next, seen); |
| 173 | } |
| 174 | } |
| 175 | |
| 176 | function resolveBrowserSpecifier (fromPath, spec) |
| 177 | { |
| 178 | if (spec.startsWith("/")) |
| 179 | { return spec.split("?")[0]; } |
| 180 | if (!spec.startsWith(".")) |
| 181 | { return null; } |
| 182 | const fromDir = dirname(fromPath); |
| 183 | const parts = [...fromDir.split("/").filter(Boolean)]; |
| 184 | for (const part of spec.split("/")) |
| 185 | { |
| 186 | if (part === "." || part === "") |
| 187 | { continue; } |
| 188 | if (part === "..") |
| 189 | { parts.pop(); } |
| 190 | else |
| 191 | { parts.push(part); } |
| 192 | } |
| 193 | return `/${parts.join("/")}`; |
| 194 | } |
| 195 | |
| 196 | function staticImportSpecifiers (source) |
| 197 | { |
| 198 | const specs = []; |
| 199 | const cleaned = stripComments(source); |
| 200 | for (const match of cleaned.matchAll(/\b(?:import|export)\s+(?:[^'";]*?\s+from\s+)?["']([^"']+)["']/g)) |
| 201 | { specs.push(match[1]); } |
| 202 | for (const match of cleaned.matchAll(/\bimport\s*\(\s*["']([^"']+)["']\s*\)/g)) |
| 203 | { specs.push(match[1]); } |
| 204 | return specs; |
| 205 | } |
| 206 | |
| 207 | function unboundReexportLocals (source) |
| 208 | { |
| 209 | const cleaned = stripComments(source); |
| 210 | const defined = new Set([ |
| 211 | ...importedBindings(cleaned), |
| 212 | ...localBindings(cleaned) |
| 213 | ]); |
| 214 | const missing = []; |
| 215 | for (const match of cleaned.matchAll(/\bexport\s*\{([^}]+)\}(\s*from\s*["'][^"']+["'])?/g)) |
| 216 | { |
| 217 | if (match[2]) |
| 218 | { continue; } |
| 219 | for (const part of match[1].split(",")) |
| 220 | { |
| 221 | const trimmed = part.trim(); |
| 222 | if (!trimmed) |
| 223 | { continue; } |
| 224 | const local = trimmed.split(/\s+as\s+/)[0].trim(); |
| 225 | if (!local || local === "default") |
| 226 | { continue; } |
| 227 | if (!defined.has(local)) |
| 228 | { missing.push(local); } |
| 229 | } |
| 230 | } |
| 231 | return missing; |
| 232 | } |
| 233 | |
| 234 | /** Local names imported more than once in the same module (SyntaxError in browsers). */ |
| 235 | function duplicateImportBindings (source) |
| 236 | { |
| 237 | const cleaned = stripComments(source); |
| 238 | const counts = new Map(); |
| 239 | const note = (name) => |
| 240 | { |
| 241 | if (!name || name === "default") |
| 242 | { return; } |
| 243 | counts.set(name, (counts.get(name) ?? 0) + 1); |
| 244 | }; |
| 245 | for (const match of cleaned.matchAll(/\bimport\s*\{([^}]+)\}\s*from\s*["']/g)) |
| 246 | { |
| 247 | for (const part of match[1].split(",")) |
| 248 | { |
| 249 | const trimmed = part.trim(); |
| 250 | if (!trimmed) |
| 251 | { continue; } |
| 252 | const bits = trimmed.split(/\s+as\s+/); |
| 253 | note(bits[bits.length - 1].trim()); |
| 254 | } |
| 255 | } |
| 256 | for (const match of cleaned.matchAll(/\bimport\s+([A-Za-z_$][\w$]*)\s*,\s*\{([^}]+)\}\s*from\s*["']/g)) |
| 257 | { |
| 258 | note(match[1]); |
| 259 | for (const part of match[2].split(",")) |
| 260 | { |
| 261 | const trimmed = part.trim(); |
| 262 | if (!trimmed) |
| 263 | { continue; } |
| 264 | const bits = trimmed.split(/\s+as\s+/); |
| 265 | note(bits[bits.length - 1].trim()); |
| 266 | } |
| 267 | } |
| 268 | for (const match of cleaned.matchAll(/\bimport\s+([A-Za-z_$][\w$]*)\s+from\s*["']/g)) |
| 269 | { note(match[1]); } |
| 270 | for (const match of cleaned.matchAll(/\bimport\s*\*\s*as\s+([A-Za-z_$][\w$]*)\s+from\s*["']/g)) |
| 271 | { note(match[1]); } |
| 272 | return [...counts.entries()] |
| 273 | .filter(([, count]) => count > 1) |
| 274 | .map(([name]) => name); |
| 275 | } |
| 276 | |
| 277 | function importedBindings (source) |
| 278 | { |
| 279 | const names = new Set(); |
| 280 | for (const match of source.matchAll(/\bimport\s*\{([^}]+)\}\s*from\s*["']/g)) |
| 281 | { |
| 282 | for (const part of match[1].split(",")) |
| 283 | { |
| 284 | const trimmed = part.trim(); |
| 285 | if (!trimmed) |
| 286 | { continue; } |
| 287 | const bits = trimmed.split(/\s+as\s+/); |
| 288 | names.add(bits[bits.length - 1].trim()); |
| 289 | } |
| 290 | } |
| 291 | for (const match of source.matchAll(/\bimport\s+([A-Za-z_$][\w$]*)\s*,\s*\{/g)) |
| 292 | { names.add(match[1]); } |
| 293 | for (const match of source.matchAll(/\bimport\s+([A-Za-z_$][\w$]*)\s+from\s*["']/g)) |
| 294 | { names.add(match[1]); } |
| 295 | for (const match of source.matchAll(/\bimport\s*\*\s*as\s+([A-Za-z_$][\w$]*)\s+from\s*["']/g)) |
| 296 | { names.add(match[1]); } |
| 297 | return names; |
| 298 | } |
| 299 | |
| 300 | function localBindings (source) |
| 301 | { |
| 302 | const names = new Set(); |
| 303 | for (const match of source.matchAll(/\b(?:async\s+)?function\s+([A-Za-z_$][\w$]*)/g)) |
| 304 | { names.add(match[1]); } |
| 305 | for (const match of source.matchAll(/\bclass\s+([A-Za-z_$][\w$]*)/g)) |
| 306 | { names.add(match[1]); } |
| 307 | for (const match of source.matchAll(/\b(?:const|let|var)\s+([A-Za-z_$][\w$]*)/g)) |
| 308 | { names.add(match[1]); } |
| 309 | return names; |
| 310 | } |
| 311 | |
| 312 | function stripComments (source) |
| 313 | { |
| 314 | return source |
| 315 | .replace(/\/\*[\s\S]*?\*\//g, "") |
| 316 | .replace(/(^|[^:])\/\/.*$/gm, "$1"); |
| 317 | } |
| 318 | |
| 319 | function listJsFiles (dir) |
| 320 | { |
| 321 | const out = []; |
| 322 | for (const entry of readdirSync(dir, { withFileTypes: true })) |
| 323 | { |
| 324 | const path = join(dir, entry.name); |
| 325 | if (entry.isDirectory()) |
| 326 | { out.push(...listJsFiles(path)); } |
| 327 | else if (extname(entry.name) === ".js") |
| 328 | { out.push(path); } |
| 329 | } |
| 330 | return out; |
| 331 | } |
| 332 | |
| 333 | function freePort () |
| 334 | { |
| 335 | return new Promise((resolve, reject) => |
| 336 | { |
| 337 | const server = createHttpServer(ROOT); |
| 338 | server.listen(0, "127.0.0.1", () => |
| 339 | { |
| 340 | const { port } = server.address(); |
| 341 | server.close((error) => (error ? reject(error) : resolve(port))); |
| 342 | }); |
| 343 | }); |
| 344 | } |
| 345 | |
| 346 | function waitFor (isReady, onTick, timeoutMs) |
| 347 | { |
| 348 | const started = Date.now(); |
| 349 | return new Promise((resolve, reject) => |
| 350 | { |
| 351 | const tick = () => |
| 352 | { |
| 353 | try |
| 354 | { onTick?.(); } |
| 355 | catch (error) |
| 356 | { |
| 357 | reject(error); |
| 358 | return; |
| 359 | } |
| 360 | if (isReady()) |
| 361 | { |
| 362 | resolve(); |
| 363 | return; |
| 364 | } |
| 365 | if (Date.now() - started > timeoutMs) |
| 366 | { |
| 367 | reject(new Error(`Timed out after ${timeoutMs}ms`)); |
| 368 | return; |
| 369 | } |
| 370 | setTimeout(tick, 50); |
| 371 | }; |
| 372 | tick(); |
| 373 | }); |
| 374 | } |