@cappa/cli 0.18.0 → 0.20.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -36,9 +36,11 @@ node_path = __toESM(node_path);
36
36
  let zod = require("zod");
37
37
  let _cappa_client = require("@cappa/client");
38
38
  let _cappa_server = require("@cappa/server");
39
+ let node_http = require("node:http");
40
+ node_http = __toESM(node_http);
39
41
  let node_crypto = require("node:crypto");
40
42
  //#region package.json
41
- var version = "0.18.0";
43
+ var version = "0.20.0";
42
44
  //#endregion
43
45
  //#region src/utils/agentSkills.ts
44
46
  /**
@@ -656,6 +658,37 @@ const filterScreenshots = (screenshots, filters) => {
656
658
  });
657
659
  };
658
660
  //#endregion
661
+ //#region src/commands/browser.ts
662
+ /**
663
+ * The container CLI to use: `--cli`, else the config's
664
+ * `playwright({ container: { cli } })`, else `CAPPA_CONTAINER_CLI`, else
665
+ * docker. A config that fails to load must not block cleanup.
666
+ */
667
+ const resolveCli = async (cli) => {
668
+ if (cli) return cli;
669
+ let container;
670
+ try {
671
+ container = (await (0, _cappa_config.getConfig)()).browser?.provider?.options?.container;
672
+ } catch (error) {
673
+ (0, _cappa_logger.getLogger)().debug("Could not load the config:", error);
674
+ }
675
+ return (0, _cappa_core.resolveContainerOptions)(container && container !== true ? container : true)?.cli ?? "docker";
676
+ };
677
+ /** `cappa browser down` — remove every Playwright container cappa started. */
678
+ const browserDown = async (options = {}) => {
679
+ const logger = (0, _cappa_logger.getLogger)();
680
+ const cli = await resolveCli(options.cli);
681
+ const removed = await (0, _cappa_core.removePlaywrightContainers)({ cli });
682
+ if (removed.length === 0) {
683
+ logger.info("No Playwright containers to remove.");
684
+ return;
685
+ }
686
+ for (const name of removed) logger.success(`Removed ${name}`);
687
+ };
688
+ const registerBrowserCommand = (program) => {
689
+ program.command("browser").description("Manage the Playwright container (browser.provider container)").command("down").description("Remove every Playwright container cappa started").option("--cli <cli>", "container CLI to use (docker, podman, nerdctl)").action(browserDown);
690
+ };
691
+ //#endregion
659
692
  //#region src/utils/captureReport.ts
660
693
  const errorMessage = (error) => {
661
694
  if (typeof error === "string") return error;
@@ -820,7 +853,11 @@ const describeChanges = (screenshots, options = {}) => {
820
853
  const meta = screenshot.diffMeta;
821
854
  const parsed = interpretationSchema.safeParse(meta?.interpretation);
822
855
  const interpretation = parsed.success ? parsed.data : void 0;
856
+ const expectedRatio = screenshot.expectedPixelRatio ?? 1;
857
+ const actualRatio = screenshot.actualPixelRatio ?? 1;
858
+ const ratioChanged = expectedRatio !== actualRatio;
823
859
  const parts = [];
860
+ if (ratioChanged) parts.push(chalk.default.yellow(`${expectedRatio}× → ${actualRatio}×`));
824
861
  if (interpretation) parts.push(severityColor(interpretation.severity)(interpretation.severity.toUpperCase()));
825
862
  if (meta?.percentDifference !== void 0) parts.push(`${meta.percentDifference.toFixed(2)}%`);
826
863
  if (interpretation) {
@@ -829,6 +866,7 @@ const describeChanges = (screenshots, options = {}) => {
829
866
  }
830
867
  const suffix = parts.length > 0 ? ` ${chalk.default.dim("·")} ${parts.join(chalk.default.dim(" · "))}` : "";
831
868
  lines.push(`${chalk.default.bold(screenshot.name)}${suffix}`);
869
+ if (ratioChanged) lines.push(` ${chalk.default.yellow((0, _cappa_core.describePixelRatioMismatch)(expectedRatio, actualRatio))}`);
832
870
  if (interpretation?.summary) lines.push(` ${chalk.default.dim(interpretation.summary)}`);
833
871
  const regions = [...interpretation?.regions ?? []].sort((a, b) => b.percentage - a.percentage);
834
872
  if (maxRegions > 0 && regions.length > 0) {
@@ -900,6 +938,102 @@ async function connectToServer(options) {
900
938
  return engine;
901
939
  }
902
940
  //#endregion
941
+ //#region src/utils/loopback.ts
942
+ const IPV4_LOOPBACK = "127.0.0.1";
943
+ const IPV6_LOOPBACK = "::1";
944
+ /**
945
+ * Binds printed as `localhost`, and the loopback addresses each one leaves
946
+ * uncovered.
947
+ *
948
+ * `localhost` is not one address. Browsers try `::1` and `127.0.0.1` (RFC 6761,
949
+ * happy eyeballs), so a URL saying `localhost:3000` reaches whichever answers
950
+ * first — and if cappa holds only `127.0.0.1:3000` while a dev server holds
951
+ * `[::1]:3000`, the user's click lands in the dev server. The companions are
952
+ * the addresses cappa must also hold for the printed URL to mean cappa.
953
+ *
954
+ * `::` is dual-stack in Node (libuv clears `IPV6_V6ONLY`), so it covers both.
955
+ */
956
+ const LOCALHOST_BINDS = {
957
+ localhost: [IPV6_LOOPBACK],
958
+ [IPV4_LOOPBACK]: [IPV6_LOOPBACK],
959
+ [IPV6_LOOPBACK]: [IPV4_LOOPBACK],
960
+ "[::1]": [IPV4_LOOPBACK],
961
+ "0.0.0.0": [IPV6_LOOPBACK],
962
+ "::": [],
963
+ "[::]": []
964
+ };
965
+ /** Loopback addresses `localhost` may reach that binding `host` does not. */
966
+ const localhostCompanions = (host) => LOCALHOST_BINDS[host] ?? [];
967
+ /**
968
+ * The host to put in the URL a person is expected to click.
969
+ *
970
+ * `localhost` for every bind it reaches — loopback and wildcards, which no
971
+ * browser will open (`http://0.0.0.0:4801` locked users out of their own UI).
972
+ * Anything else is printed as given, with IPv6 literals bracketed. Note
973
+ * `127.0.0.2` is loopback but is *not* `localhost`, which resolves to
974
+ * `127.0.0.1` only.
975
+ */
976
+ const toDisplayHost = (host) => {
977
+ if (host in LOCALHOST_BINDS) return "localhost";
978
+ return host.includes(":") && !host.startsWith("[") ? `[${host}]` : host;
979
+ };
980
+ /**
981
+ * The address to hand to `listen`.
982
+ *
983
+ * `localhost` becomes `127.0.0.1`: Fastify binds every address `localhost`
984
+ * resolves to but silently drops the ones that fail, so a taken `[::1]:port`
985
+ * would go unnoticed — exactly the conflict the companions exist to catch.
986
+ * Brackets are URL syntax, not something `listen` resolves.
987
+ */
988
+ const toBindHost = (host) => {
989
+ if (host === "localhost") return IPV4_LOOPBACK;
990
+ return host.startsWith("[") && host.endsWith("]") ? host.slice(1, -1) : host;
991
+ };
992
+ /**
993
+ * The loopback family does not exist on this machine — IPv6 disabled, say —
994
+ * so nothing can be listening there and there is nothing to hold.
995
+ */
996
+ const FAMILY_UNAVAILABLE = /* @__PURE__ */ new Set(["EAFNOSUPPORT", "EADDRNOTAVAIL"]);
997
+ /**
998
+ * Listen on `host:port` and hand every request to `target`.
999
+ *
1000
+ * What Fastify does itself for its secondary `localhost` addresses, minus the
1001
+ * swallowed errors: `EADDRINUSE` is thrown so the caller can move to another
1002
+ * port. Resolves to `null` when the address family is unavailable.
1003
+ */
1004
+ async function bindCompanion(target, host, port) {
1005
+ const companion = node_http.default.createServer((req, res) => {
1006
+ target.emit("request", req, res);
1007
+ });
1008
+ companion.on("upgrade", (...args) => target.emit("upgrade", ...args));
1009
+ companion.timeout = target.timeout;
1010
+ companion.keepAliveTimeout = target.keepAliveTimeout;
1011
+ companion.requestTimeout = target.requestTimeout;
1012
+ companion.headersTimeout = target.headersTimeout;
1013
+ try {
1014
+ await new Promise((resolve, reject) => {
1015
+ companion.once("error", reject);
1016
+ companion.listen({
1017
+ host,
1018
+ port,
1019
+ ipv6Only: host.includes(":")
1020
+ }, () => {
1021
+ companion.off("error", reject);
1022
+ resolve();
1023
+ });
1024
+ });
1025
+ } catch (error) {
1026
+ if (FAMILY_UNAVAILABLE.has(error.code ?? "")) return null;
1027
+ throw error;
1028
+ }
1029
+ return companion;
1030
+ }
1031
+ /** Stop a companion and drop its open connections (SSE streams included). */
1032
+ const closeCompanion = (companion) => {
1033
+ companion.close(() => {});
1034
+ companion.closeAllConnections();
1035
+ };
1036
+ //#endregion
903
1037
  //#region src/utils/server.ts
904
1038
  const closeQuietly = async (name, closeable) => {
905
1039
  try {
@@ -946,22 +1080,100 @@ function registerShutdownHandlers(server, engine, exitFn = process.exit) {
946
1080
  * its process list, where anything on the box can read it.
947
1081
  */
948
1082
  const resolveToken = (token) => token ?? process.env.CAPPA_TOKEN ?? void 0;
949
- /** Wildcard binds: addresses to listen on, never addresses to open. */
950
- const WILDCARD_HOSTS = /* @__PURE__ */ new Set([
951
- "0.0.0.0",
952
- "::",
953
- "[::]"
954
- ]);
1083
+ /** No port in the range `listenWithFallback` tried was free. */
1084
+ var PortInUseError = class extends Error {
1085
+ constructor(message, options) {
1086
+ super(message, options);
1087
+ this.name = "PortInUseError";
1088
+ }
1089
+ };
1090
+ const isAddressInUse = (error) => error?.code === "EADDRINUSE";
1091
+ /** A bind that failed with `EADDRINUSE`, and where. */
1092
+ var AddressTaken = class extends Error {
1093
+ host;
1094
+ error;
1095
+ constructor(host, error) {
1096
+ super(`${host} is in use`);
1097
+ this.host = host;
1098
+ this.error = error;
1099
+ }
1100
+ };
955
1101
  /**
956
- * The host to put in the URL a person is expected to click.
1102
+ * Listen on `port`, or the next free port above it.
1103
+ *
1104
+ * Retries the real `listen` on `EADDRINUSE` rather than probing first (what
1105
+ * `get-port`/`detect-port` do): a probe frees the port again before the server
1106
+ * binds it, so two cappa processes started together can both "find" the same
1107
+ * port and one of them still crashes. Binding is the only atomic check.
1108
+ *
1109
+ * Companions are bound before the server, because a Fastify instance cannot
1110
+ * listen again once it has been closed: a companion that turns out to be taken
1111
+ * costs nothing to give back, a bound server does.
957
1112
  *
958
- * A wildcard bind is the common way to expose the UI, and printing it verbatim
959
- * produced `http://0.0.0.0:4801?token=…` — an address no browser will open,
960
- * handed to a user who then cannot reach their own review UI. `localhost` is
961
- * reachable on every interface the wildcard covers, so it is the right thing to
962
- * show; a specific host is printed as given, because that one is meaningful.
1113
+ * Only `EADDRINUSE` moves on. `EACCES` (a privileged port) or a bad host would
1114
+ * fail identically on every port, so they surface as-is.
1115
+ *
1116
+ * Returns the port actually bound, read back from the server so `port: 0`
1117
+ * (OS-assigned) reports the real number too.
963
1118
  */
964
- const toDisplayHost = (host) => (0, _cappa_server.isLoopbackHost)(host) || WILDCARD_HOSTS.has(host) ? "localhost" : host;
1119
+ async function listenWithFallback(server, options) {
1120
+ const { host, port, strictPort = false, companions } = options;
1121
+ const attempts = strictPort || port === 0 ? 1 : Math.min(options.maxAttempts ?? 20, 65536 - port);
1122
+ const companionHosts = companions?.hosts ?? [];
1123
+ const bind = async (address, candidate) => {
1124
+ if (!companions) return null;
1125
+ try {
1126
+ return await bindCompanion(companions.target, address, candidate);
1127
+ } catch (error) {
1128
+ throw isAddressInUse(error) ? new AddressTaken(address, error) : error;
1129
+ }
1130
+ };
1131
+ for (let i = 0; i < attempts; i++) {
1132
+ const candidate = port + i;
1133
+ const held = [];
1134
+ try {
1135
+ if (candidate !== 0) for (const address of companionHosts) {
1136
+ const companion = await bind(address, candidate);
1137
+ if (companion) held.push({
1138
+ host: address,
1139
+ server: companion
1140
+ });
1141
+ }
1142
+ try {
1143
+ await server.listen({
1144
+ port: candidate,
1145
+ host
1146
+ });
1147
+ } catch (error) {
1148
+ throw isAddressInUse(error) ? new AddressTaken(host, error) : error;
1149
+ }
1150
+ const bound = server.addresses?.()[0]?.port ?? candidate;
1151
+ if (candidate === 0) for (const address of companionHosts) {
1152
+ const companion = await bind(address, bound).catch(() => null);
1153
+ if (companion) held.push({
1154
+ host: address,
1155
+ server: companion
1156
+ });
1157
+ }
1158
+ if (companions && held.length > 0) companions.target.once("close", () => {
1159
+ for (const companion of held) closeCompanion(companion.server);
1160
+ });
1161
+ return {
1162
+ port: bound,
1163
+ companions: held.map((c) => c.host)
1164
+ };
1165
+ } catch (error) {
1166
+ for (const companion of held) closeCompanion(companion.server);
1167
+ if (!(error instanceof AddressTaken)) throw error;
1168
+ options.onPortInUse?.(candidate, error.host);
1169
+ if (i === attempts - 1) {
1170
+ const where = attempts === 1 ? error.host : host;
1171
+ throw new PortInUseError(`${attempts === 1 ? `Port ${port}` : `Ports ${port}–${candidate}`} on ${where} ${attempts === 1 ? "is" : "are all"} in use. ${strictPort ? "Drop --strict-port to use the next free one, or pass --port <port>." : "Pass --port <port> to pick another."}`, { cause: error.error });
1172
+ }
1173
+ }
1174
+ }
1175
+ throw new Error(`Could not listen on ${host}:${port}.`);
1176
+ }
965
1177
  /**
966
1178
  * Build an engine, wrap it in a server, and start listening.
967
1179
  *
@@ -976,7 +1188,7 @@ const toDisplayHost = (host) => (0, _cappa_server.isLoopbackHost)(host) || WILDC
976
1188
  */
977
1189
  async function startServer(options) {
978
1190
  const logger = (0, _cappa_logger.getLogger)();
979
- const { config, host, port, readOnly, token, ui } = options;
1191
+ const { config, host, port, readOnly, token, ui, strictPort } = options;
980
1192
  const engine = new _cappa_core.LocalEngine({
981
1193
  ...(0, _cappa_config.configToEngineOptions)(config),
982
1194
  browserIdleTimeoutMs: config.review.browserIdleTimeout
@@ -992,17 +1204,50 @@ async function startServer(options) {
992
1204
  token
993
1205
  });
994
1206
  const unregisterShutdownHandlers = registerShutdownHandlers(server, engine);
995
- await server.listen({
996
- port,
997
- host
998
- });
1207
+ let boundPort;
1208
+ try {
1209
+ ({port: boundPort} = await listenWithFallback(server, {
1210
+ host: toBindHost(host),
1211
+ port,
1212
+ strictPort,
1213
+ onPortInUse: (taken, on) => logger.debug(`Port ${taken} is in use on ${on}.`),
1214
+ companions: server.server && {
1215
+ hosts: localhostCompanions(host),
1216
+ target: server.server
1217
+ }
1218
+ }));
1219
+ } catch (error) {
1220
+ unregisterShutdownHandlers();
1221
+ await closeQuietly("server", server);
1222
+ await closeQuietly("engine", engine);
1223
+ throw error;
1224
+ }
1225
+ if (boundPort !== port && port !== 0) logger.warn(`Port ${port} is in use, using ${boundPort} instead.`);
1226
+ const displayHost = toDisplayHost(host);
1227
+ const query = token ? `?token=${token}` : "";
999
1228
  return {
1000
1229
  server,
1001
1230
  engine,
1002
- url: `http://${toDisplayHost(host)}:${port}${token ? `?token=${token}` : ""}`,
1231
+ port: boundPort,
1232
+ url: `http://${displayHost}:${boundPort}${query}`,
1003
1233
  unregisterShutdownHandlers
1004
1234
  };
1005
1235
  }
1236
+ /**
1237
+ * `startServer` for a CLI command: a taken port is a one-line error and exit
1238
+ * code 1, not a stack trace. Anything else is a bug and keeps its stack.
1239
+ */
1240
+ async function startServerOrExit(options, exitFn = process.exit) {
1241
+ try {
1242
+ return await startServer(options);
1243
+ } catch (error) {
1244
+ if (error instanceof PortInUseError) {
1245
+ (0, _cappa_logger.getLogger)().error(error.message);
1246
+ exitFn(1);
1247
+ }
1248
+ throw error;
1249
+ }
1250
+ }
1006
1251
  //#endregion
1007
1252
  //#region src/commands/capture.ts
1008
1253
  async function executeOnFailCallback(config, groupedScreenshots, { remote = false } = {}) {
@@ -1524,12 +1769,13 @@ const review = async (options = {}) => {
1524
1769
  tokenWasGenerated = true;
1525
1770
  logger.warn(`Binding to ${host} exposes capture control beyond this machine; requiring an access token.`);
1526
1771
  }
1527
- const { url } = await startServer({
1772
+ const { url } = await startServerOrExit({
1528
1773
  config,
1529
1774
  host,
1530
1775
  port,
1531
1776
  readOnly,
1532
1777
  token,
1778
+ strictPort: options.strictPort ?? false,
1533
1779
  ui: true
1534
1780
  });
1535
1781
  logger.success(`Review UI available at ${url}`);
@@ -1560,15 +1806,16 @@ const serve = async (options = {}) => {
1560
1806
  process.exit(1);
1561
1807
  return;
1562
1808
  }
1563
- const { url } = await startServer({
1809
+ const { url, port: boundPort } = await startServerOrExit({
1564
1810
  config,
1565
1811
  host,
1566
1812
  port,
1567
1813
  readOnly,
1568
1814
  token,
1815
+ strictPort: options.strictPort ?? false,
1569
1816
  ui
1570
1817
  });
1571
- logger.log(`cappa serve listening host=${host} port=${port} ui=${ui} read-only=${readOnly} token=${token ? "yes" : "no"}`);
1818
+ logger.log(`cappa serve listening host=${host} port=${boundPort} ui=${ui} read-only=${readOnly} token=${token ? "yes" : "no"}`);
1572
1819
  if (ui) logger.info(`Review UI available at ${url}`);
1573
1820
  if (readOnly) logger.info("Running read-only: capture and approval are disabled.");
1574
1821
  };
@@ -1602,11 +1849,12 @@ program.name("cappa").description("Cappa CLI").version(version).option("-l, --lo
1602
1849
  (0, _cappa_logger.initLogger)(logLevel)?.debug(`Log level set to: ${logLevel}`);
1603
1850
  });
1604
1851
  registerCaptureCommand(program);
1605
- program.command("review").description("Open the review and capture UI").option("-p, --port <port>", "port to listen on", (v) => Number.parseInt(v, 10)).option("--host <host>", "host to bind to (a non-loopback host requires an access token)").option("--read-only", "serve the UI without capture, approval or any other mutation").option("--token <token>", "require this access token on every API request (falls back to CAPPA_TOKEN)").action(review);
1606
- program.command("serve").description("Host a capture engine for a remote `cappa capture --server`").option("-p, --port <port>", "port to listen on", (v) => Number.parseInt(v, 10)).option("--host <host>", "host to bind to (a non-loopback host requires an access token)").option("--read-only", "serve without capture, approval or any other mutation").option("--token <token>", "require this access token on every API request (falls back to CAPPA_TOKEN)").option("--no-ui", "serve the API only, without the review UI").action(serve);
1852
+ program.command("review").description("Open the review and capture UI").option("-p, --port <port>", "port to listen on (the next free one if it is taken)", (v) => Number.parseInt(v, 10)).option("--strict-port", "exit if the port is taken instead of moving on").option("--host <host>", "host to bind to (a non-loopback host requires an access token)").option("--read-only", "serve the UI without capture, approval or any other mutation").option("--token <token>", "require this access token on every API request (falls back to CAPPA_TOKEN)").action(review);
1853
+ program.command("serve").description("Host a capture engine for a remote `cappa capture --server`").option("-p, --port <port>", "port to listen on (the next free one if it is taken)", (v) => Number.parseInt(v, 10)).option("--strict-port", "exit if the port is taken instead of moving on").option("--host <host>", "host to bind to (a non-loopback host requires an access token)").option("--read-only", "serve without capture, approval or any other mutation").option("--token <token>", "require this access token on every API request (falls back to CAPPA_TOKEN)").option("--no-ui", "serve the API only, without the review UI").action(serve);
1607
1854
  program.command("approve").description("Approve screenshots").option("-f, --filter <filter...>", "only approve screenshots whose name includes the provided filter value(s)").action(approve);
1608
1855
  program.command("status").description("Get status of screenshots").option("--max-regions <count>", "maximum number of interpreted diff regions listed per changed screenshot (0 to disable)", parseMaxRegions, 5).action(status);
1609
1856
  registerAgentCommand(program);
1857
+ registerBrowserCommand(program);
1610
1858
  program.command("init").description("Initialize Cappa in the current directory").action(init);
1611
1859
  async function run() {
1612
1860
  await program.parseAsync();