From 8d950297aeccd9a166fe9e0e24096f38f771ce4d Mon Sep 17 00:00:00 2001 From: Bryan Kendall Date: Fri, 4 Dec 2026 10:19:38 -0800 Subject: [PATCH 1/2] chore(deps): bump commander to 15.1.0 and add CLI tests --- package-lock.json | 13 +- package.json | 4 +- src/cli/index.ts | 124 ++++++++++------- test/unit/cli.spec.ts | 315 ++++++++++++++++++++++++++++++++++++++++++ 4 files changed, 400 insertions(+), 56 deletions(-) create mode 100644 test/unit/cli.spec.ts diff --git a/package-lock.json b/package-lock.json index d0b1998a..1f48e4ec 100644 --- a/package-lock.json +++ b/package-lock.json @@ -11,7 +11,7 @@ "dependencies": { "@types/connect": "^3.4.35", "basic-auth-connect": "^1.1.0", - "commander": "^10.0.0", + "commander": "^15.1.0", "compression": "^1.7.0", "connect": "^3.7.0", "destroy": "^1.0.4", @@ -69,7 +69,7 @@ "typescript-eslint": "^8.63.0" }, "engines": { - "node": "22 || 24 || 26" + "node": "^22.12.0 || 24 || 26" }, "optionalDependencies": { "re2": "^1.26.1" @@ -2096,11 +2096,12 @@ } }, "node_modules/commander": { - "version": "10.0.1", - "resolved": "https://registry.npmjs.org/commander/-/commander-10.0.1.tgz", - "integrity": "sha512-y4Mg2tXshplEbSGzx7amzPwKKOCGuoSRP/CjEdwwk0FOGlUbq6lKuoyDZTNZkmxHdJtp54hdfY/JUrdL7Xfdug==", + "version": "15.1.0", + "resolved": "https://registry.npmjs.org/commander/-/commander-15.1.0.tgz", + "integrity": "sha512-cgnQ88TRrWcC7pVq46RzJVRMktu3W2RcbnoidnfBsl1bmDCBwJS/udcIZpKoCrbAYYaCqsz1yZCVIgbIaU3ddQ==", + "license": "MIT", "engines": { - "node": ">=14" + "node": ">=22.12.0" } }, "node_modules/comment-parser": { diff --git a/package.json b/package.json index 261839ea..6a540a41 100644 --- a/package.json +++ b/package.json @@ -30,7 +30,7 @@ "templates" ], "engines": { - "node": "22 || 24 || 26" + "node": "^22.12.0 || 24 || 26" }, "repository": { "type": "git", @@ -55,7 +55,7 @@ "dependencies": { "@types/connect": "^3.4.35", "basic-auth-connect": "^1.1.0", - "commander": "^10.0.0", + "commander": "^15.1.0", "compression": "^1.7.0", "connect": "^3.7.0", "destroy": "^1.0.4", diff --git a/src/cli/index.ts b/src/cli/index.ts index cae0ac5b..af0b60cb 100644 --- a/src/cli/index.ts +++ b/src/cli/index.ts @@ -35,6 +35,15 @@ interface ServeOptions { debug?: boolean; } +/** + * Optional dependency overrides for constructing the CLI command. + */ +export interface CreateCliOptions { + serverFactory?: typeof server; + cwd?: string; + env?: Record; +} + const PORT = "3474"; const HOSTNAME = "localhost"; const CONFIG_FILENAME = ["superstatic.json", "firebase.json"]; @@ -48,62 +57,81 @@ const pkgVersion = ? rawPkg.version : "0.0.0"; -let env: Record | undefined = undefined; -try { - const parsedEnv: unknown = JSON.parse( - fs.readFileSync(path.resolve(ENV_FILENAME), "utf8"), - ); - if (isPlainObject(parsedEnv)) { - const stringEnv: Record = {}; - for (const [key, value] of Object.entries(parsedEnv)) { - if ( - typeof value === "string" || - typeof value === "number" || - typeof value === "boolean" - ) { - stringEnv[key] = String(value); +function loadEnv(cwd?: string): Record | undefined { + try { + const envPath = cwd + ? path.resolve(cwd, ENV_FILENAME) + : path.resolve(ENV_FILENAME); + const parsedEnv: unknown = JSON.parse(fs.readFileSync(envPath, "utf8")); + if (isPlainObject(parsedEnv)) { + const stringEnv: Record = {}; + for (const [key, value] of Object.entries(parsedEnv)) { + if ( + typeof value === "string" || + typeof value === "number" || + typeof value === "boolean" + ) { + stringEnv[key] = String(value); + } } + return stringEnv; } - env = stringEnv; + } catch { + // do nothing } -} catch { - // do nothing + return undefined; } -const cli = new Command(); +/** + * Creates a configured Superstatic CLI Commander instance. + * @param cliOptions optional overrides for testing. + * @returns configured Commander program. + */ +export function createCli(cliOptions: CreateCliOptions = {}): Command { + const serverFactory = cliOptions.serverFactory ?? server; + const env = "env" in cliOptions ? cliOptions.env : loadEnv(cliOptions.cwd); + + const program = new Command(); -cli.name("superstatic").version(pkgVersion, "-v, --version"); + program.name("superstatic").version(pkgVersion, "-v, --version"); -cli - .command("serve", { isDefault: true }) - .argument("[folder]") - .option("-p, --port ", "Port", PORT) - .option("--host, --hostname ", "Hostname", HOSTNAME) - .option("-c, --config ", "Filename of config", CONFIG_FILENAME) - .option("--debug") - .option("--gzip") - .option("--compression") - .description("start server") - .action((folder: string | undefined, options: ServeOptions) => { - return new Promise((resolve) => { - const parsedPort = - options.port !== undefined ? Number(options.port) : undefined; - const isValidPort = parsedPort !== undefined && !Number.isNaN(parsedPort); - const app = server({ - cwd: path.join(process.cwd(), folder ?? ""), - config: options.config, - port: isValidPort ? parsedPort : Number(PORT), - hostname: options.hostname, - compression: options.compression, - gzip: options.gzip, - debug: options.debug, - env: env, + program + .command("serve", { isDefault: true }) + .argument("[folder]") + .option("-p, --port ", "Port", PORT) + .option("--host, --hostname ", "Hostname", HOSTNAME) + .option("-c, --config ", "Filename of config", CONFIG_FILENAME) + .option("--debug") + .option("--gzip") + .option("--compression") + .description("start server") + .action((folder: string | undefined, options: ServeOptions) => { + return new Promise((resolve) => { + const parsedPort = + options.port !== undefined ? Number(options.port) : undefined; + const isValidPort = + parsedPort !== undefined && !Number.isNaN(parsedPort); + const baseCwd = cliOptions.cwd ?? process.cwd(); + const app = serverFactory({ + cwd: path.join(baseCwd, folder ?? ""), + config: options.config, + port: isValidPort ? parsedPort : Number(PORT), + hostname: options.hostname, + compression: options.compression, + gzip: options.gzip, + debug: options.debug, + env: env, + }); + app.listen(() => resolve()); + console.log( + `Superstatic started.\nVisit http://${options.hostname ?? HOSTNAME}:${isValidPort ? parsedPort : PORT} to view your app.`, + ); }); - app.listen(() => resolve()); - console.log( - `Superstatic started.\nVisit http://${options.hostname ?? HOSTNAME}:${isValidPort ? parsedPort : PORT} to view your app.`, - ); }); - }); + + return program; +} + +const cli = createCli(); export default cli; diff --git a/test/unit/cli.spec.ts b/test/unit/cli.spec.ts new file mode 100644 index 00000000..2c953863 --- /dev/null +++ b/test/unit/cli.spec.ts @@ -0,0 +1,315 @@ +/** + * Copyright (c) 2026 Google LLC + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * this software and associated documentation files (the "Software"), to deal in + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS + * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR + * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER + * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +import { expect } from "chai"; +import { CommanderError } from "commander"; +import * as fs from "node:fs"; +import * as http from "node:http"; +import * as os from "node:os"; +import * as path from "node:path"; +import * as sinon from "sinon"; + +import cli, { createCli } from "../../src/cli"; +import { ServerOptions } from "../../src/options"; +import server from "../../src/server"; + +const pkg = JSON.parse( + fs.readFileSync(path.resolve(__dirname, "../../package.json"), "utf8"), +) as { version: string }; + +describe("cli", () => { + let logStub: sinon.SinonStub; + + beforeEach(() => { + logStub = sinon.stub(console, "log"); + }); + + afterEach(() => { + sinon.restore(); + }); + + function createStubServerFactory() { + const calls: ServerOptions[] = []; + const listenStub = sinon.stub().callsFake((done?: () => void) => { + done?.(); + return {} as http.Server; + }); + const serverFactory: typeof server = (spec = {}) => { + calls.push(spec); + return { listen: listenStub } as unknown as server.SuperstaticServer; + }; + return { calls, listenStub, serverFactory }; + } + + describe("default export", () => { + it("loads commander and configures program metadata", () => { + expect(cli.name()).to.equal("superstatic"); + expect(cli.version()).to.equal(pkg.version); + expect(cli.commands.map((cmd) => cmd.name())).to.deep.equal(["serve"]); + }); + }); + + describe("option and argument parsing", () => { + it("starts the default serve command with default options", async () => { + const { calls, listenStub, serverFactory } = createStubServerFactory(); + const cwd = "/tmp/superstatic-cli-default"; + const program = createCli({ serverFactory, cwd, env: undefined }); + + await program.parseAsync(["node", "superstatic"]); + + expect(listenStub.calledOnce).to.equal(true); + expect(calls).to.have.lengthOf(1); + expect(calls[0]).to.deep.equal({ + cwd: path.join(cwd, ""), + config: ["superstatic.json", "firebase.json"], + port: 3474, + hostname: "localhost", + compression: undefined, + gzip: undefined, + debug: undefined, + env: undefined, + }); + expect( + logStub.calledWith( + "Superstatic started.\nVisit http://localhost:3474 to view your app.", + ), + ).to.equal(true); + }); + + it("parses positional folder and all CLI flags", async () => { + const { calls, serverFactory } = createStubServerFactory(); + const cwd = "/tmp/superstatic-cli-flags"; + const program = createCli({ serverFactory, cwd, env: { FOO: "bar" } }); + + await program.parseAsync([ + "node", + "superstatic", + "serve", + "public", + "-p", + "8080", + "--hostname", + "127.0.0.1", + "-c", + "custom.json", + "--debug", + "--gzip", + "--compression", + ]); + + expect(calls).to.have.lengthOf(1); + expect(calls[0]).to.deep.equal({ + cwd: path.join(cwd, "public"), + config: "custom.json", + port: 8080, + hostname: "127.0.0.1", + compression: true, + gzip: true, + debug: true, + env: { FOO: "bar" }, + }); + expect( + logStub.calledWith( + "Superstatic started.\nVisit http://127.0.0.1:8080 to view your app.", + ), + ).to.equal(true); + }); + + it("supports the --host alias for --hostname", async () => { + const { calls, serverFactory } = createStubServerFactory(); + const program = createCli({ + serverFactory, + cwd: "/tmp/superstatic-cli-host", + env: undefined, + }); + + await program.parseAsync([ + "node", + "superstatic", + "--host", + "0.0.0.0", + "dist", + ]); + + expect(calls).to.have.lengthOf(1); + expect(calls[0].hostname).to.equal("0.0.0.0"); + expect(calls[0].cwd).to.equal( + path.join("/tmp/superstatic-cli-host", "dist"), + ); + }); + + it("falls back to default port when --port is not a number", async () => { + const { calls, serverFactory } = createStubServerFactory(); + const program = createCli({ + serverFactory, + cwd: "/tmp/superstatic-cli-port", + env: undefined, + }); + + await program.parseAsync(["node", "superstatic", "--port", "not-a-port"]); + + expect(calls).to.have.lengthOf(1); + expect(calls[0].port).to.equal(3474); + expect( + logStub.calledWith( + "Superstatic started.\nVisit http://localhost:3474 to view your app.", + ), + ).to.equal(true); + }); + + it("outputs package version with --version", () => { + let stdout = ""; + const program = createCli({ env: undefined }); + program.exitOverride().configureOutput({ + writeOut: (str) => { + stdout += str; + }, + }); + + let caught: unknown; + try { + program.parse(["node", "superstatic", "--version"]); + } catch (err) { + caught = err; + } + + expect(caught).to.be.instanceOf(CommanderError); + expect((caught as CommanderError).code).to.equal("commander.version"); + expect(stdout.trim()).to.equal(pkg.version); + }); + + it("rejects excess positional arguments", () => { + let stderr = ""; + const program = createCli({ env: undefined }); + for (const cmd of [program, ...program.commands]) { + cmd.exitOverride().configureOutput({ + writeErr: (str) => { + stderr += str; + }, + }); + } + + let caught: unknown; + try { + program.parse(["node", "superstatic", "dir1", "extra"]); + } catch (err) { + caught = err; + } + + expect(caught).to.be.instanceOf(CommanderError); + expect((caught as CommanderError).code).to.equal( + "commander.excessArguments", + ); + expect(stderr).to.include("too many arguments"); + }); + + it("loads primitive values from .env.json in cwd", async () => { + const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "superstatic-cli-")); + try { + fs.writeFileSync( + path.join(tmpDir, ".env.json"), + JSON.stringify({ + STR: "hello", + NUM: 42, + BOOL: true, + NESTED: { ignored: true }, + ARR: [1, 2], + NIL: null, + }), + ); + + const { calls, serverFactory } = createStubServerFactory(); + const program = createCli({ serverFactory, cwd: tmpDir }); + await program.parseAsync(["node", "superstatic"]); + + expect(calls).to.have.lengthOf(1); + expect(calls[0].env).to.deep.equal({ + STR: "hello", + NUM: "42", + BOOL: "true", + }); + } finally { + fs.rmSync(tmpDir, { recursive: true, force: true }); + } + }); + }); + + describe("smoke test", () => { + it("starts and serves a file via the real server", async () => { + let httpServer: http.Server | undefined; + const wrappedServer: typeof server = (spec) => { + const app = server(spec); + const origListen = app.listen.bind(app); + app.listen = (done?: () => void) => { + httpServer = origListen(done); + return httpServer; + }; + return app; + }; + + const program = createCli({ + serverFactory: wrappedServer, + cwd: path.resolve(__dirname, "../fixtures"), + env: undefined, + }); + + try { + await program.parseAsync([ + "node", + "superstatic", + "a", + "-p", + "0", + "--host", + "127.0.0.1", + ]); + + expect(httpServer).to.not.equal(undefined); + const address = httpServer!.address(); + expect(address).to.be.an("object"); + const port = (address as { port: number }).port; + + const body = await new Promise((resolve, reject) => { + http + .get(`http://127.0.0.1:${port}/`, { agent: false }, (res) => { + let data = ""; + res.setEncoding("utf8"); + res.on("data", (chunk: string) => { + data += chunk; + }); + res.on("end", () => resolve(data)); + }) + .on("error", reject); + }); + + expect(body).to.include("A"); + } finally { + if (httpServer) { + const serverToClose = httpServer; + await new Promise((resolve, reject) => { + serverToClose.close((err) => (err ? reject(err) : resolve())); + serverToClose.closeAllConnections(); + }); + } + } + }); + }); +}); From 75749f924e52fb2df51250864f22b688e39adbf7 Mon Sep 17 00:00:00 2001 From: Bryan Kendall Date: Fri, 4 Dec 2026 10:51:49 -0800 Subject: [PATCH 2/2] fix(cli): validate port range and log actual bound port on listen --- src/cli/index.ts | 30 ++++++++++++++----- test/unit/cli.spec.ts | 69 ++++++++++++++++++++++++++++++++++++++----- 2 files changed, 85 insertions(+), 14 deletions(-) diff --git a/src/cli/index.ts b/src/cli/index.ts index af0b60cb..1d98c757 100644 --- a/src/cli/index.ts +++ b/src/cli/index.ts @@ -107,25 +107,41 @@ export function createCli(cliOptions: CreateCliOptions = {}): Command { .description("start server") .action((folder: string | undefined, options: ServeOptions) => { return new Promise((resolve) => { + const trimmedPort = options.port?.trim(); const parsedPort = - options.port !== undefined ? Number(options.port) : undefined; + trimmedPort !== undefined && trimmedPort !== "" + ? Number(trimmedPort) + : undefined; const isValidPort = - parsedPort !== undefined && !Number.isNaN(parsedPort); + parsedPort !== undefined && + Number.isInteger(parsedPort) && + parsedPort >= 0 && + parsedPort <= 65535; + const port = isValidPort ? parsedPort : Number(PORT); const baseCwd = cliOptions.cwd ?? process.cwd(); const app = serverFactory({ cwd: path.join(baseCwd, folder ?? ""), config: options.config, - port: isValidPort ? parsedPort : Number(PORT), + port, hostname: options.hostname, compression: options.compression, gzip: options.gzip, debug: options.debug, env: env, }); - app.listen(() => resolve()); - console.log( - `Superstatic started.\nVisit http://${options.hostname ?? HOSTNAME}:${isValidPort ? parsedPort : PORT} to view your app.`, - ); + let httpServer: ReturnType | undefined = undefined; + httpServer = app.listen(() => { + const address = + typeof httpServer?.address === "function" + ? httpServer.address() + : null; + const actualPort = + address && typeof address === "object" ? address.port : port; + console.log( + `Superstatic started.\nVisit http://${options.hostname ?? HOSTNAME}:${actualPort} to view your app.`, + ); + resolve(); + }); }); }); diff --git a/test/unit/cli.spec.ts b/test/unit/cli.spec.ts index 2c953863..8a36ce05 100644 --- a/test/unit/cli.spec.ts +++ b/test/unit/cli.spec.ts @@ -156,21 +156,70 @@ describe("cli", () => { ); }); - it("falls back to default port when --port is not a number", async () => { - const { calls, serverFactory } = createStubServerFactory(); + it("falls back to default port for invalid --port values", async () => { + for (const invalidPort of ["not-a-port", "-1", "70000", "3.14", ""]) { + logStub.resetHistory(); + const { calls, serverFactory } = createStubServerFactory(); + const program = createCli({ + serverFactory, + cwd: "/tmp/superstatic-cli-port", + env: undefined, + }); + + await program.parseAsync([ + "node", + "superstatic", + "--port", + invalidPort, + ]); + + expect(calls).to.have.lengthOf(1); + expect(calls[0].port, `port "${invalidPort}"`).to.equal(3474); + expect( + logStub.calledWith( + "Superstatic started.\nVisit http://localhost:3474 to view your app.", + ), + ).to.equal(true); + } + }); + + it("logs startup message only after the server begins listening", async () => { + let listenCallback: (() => void) | undefined; + const serverFactory: typeof server = () => { + return { + listen: (done?: () => void) => { + listenCallback = done; + return { + address: () => ({ + port: 4321, + address: "127.0.0.1", + family: "IPv4", + }), + } as unknown as http.Server; + }, + } as unknown as server.SuperstaticServer; + }; const program = createCli({ serverFactory, - cwd: "/tmp/superstatic-cli-port", + cwd: "/tmp/superstatic-cli-listen", env: undefined, }); - await program.parseAsync(["node", "superstatic", "--port", "not-a-port"]); + const parsePromise = program.parseAsync([ + "node", + "superstatic", + "-p", + "0", + ]); + expect(logStub.called).to.equal(false); + expect(listenCallback).to.be.a("function"); + + listenCallback!(); + await parsePromise; - expect(calls).to.have.lengthOf(1); - expect(calls[0].port).to.equal(3474); expect( logStub.calledWith( - "Superstatic started.\nVisit http://localhost:3474 to view your app.", + "Superstatic started.\nVisit http://localhost:4321 to view your app.", ), ).to.equal(true); }); @@ -286,6 +335,12 @@ describe("cli", () => { const address = httpServer!.address(); expect(address).to.be.an("object"); const port = (address as { port: number }).port; + expect(port).to.be.greaterThan(0); + expect( + logStub.calledWith( + `Superstatic started.\nVisit http://127.0.0.1:${port} to view your app.`, + ), + ).to.equal(true); const body = await new Promise((resolve, reject) => { http