@kvbox/cli 0.5.39 → 0.5.40

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/kvbox.js CHANGED
@@ -149,7 +149,7 @@ async function spin(message, work, opts = {}) {
149
149
  }
150
150
 
151
151
  // src/program.ts
152
- import { Command as Command76 } from "commander";
152
+ import { Command as Command77 } from "commander";
153
153
 
154
154
  // ../shared/src/version.ts
155
155
  import { createRequire } from "module";
@@ -164,7 +164,7 @@ function versionOf(srcFileUrl, injected) {
164
164
  }
165
165
 
166
166
  // src/version.ts
167
- var VERSION = versionOf(import.meta.url, true ? "0.5.39" : void 0);
167
+ var VERSION = versionOf(import.meta.url, true ? "0.5.40" : void 0);
168
168
 
169
169
  // src/commands/vm/index.ts
170
170
  import { Command as Command37 } from "commander";
@@ -919,8 +919,11 @@ var VolumeEventsResponseSchema = z2.object({
919
919
  events: z2.array(VolumeEventRowSchema),
920
920
  next: z2.number().int()
921
921
  });
922
+ var API_ERROR_CODES = ["account-inactive", "org-inactive", "out-of-credit"];
923
+ var ApiErrorCodeSchema = z2.enum(API_ERROR_CODES);
922
924
  var ApiErrorSchema = z2.object({
923
- error: z2.string()
925
+ error: z2.string(),
926
+ code: ApiErrorCodeSchema.optional()
924
927
  });
925
928
  var DEFAULT_CLOUD_URL = "https://api.kvbox.sh";
926
929
  var ACTIVATED_BY = ["card", "admin"];
@@ -1332,24 +1335,25 @@ var ServerClient = class {
1332
1335
  removeBoxHook(name, id) {
1333
1336
  return this.call("DELETE", `/machines/${encodeURIComponent(name)}/hooks/${encodeURIComponent(id)}`, WakeHookSchema);
1334
1337
  }
1335
- /** HTTPS names (#31), the control plane's only: the box's subdomain, claimed for its default port. */
1338
+ /** HTTPS names (#31), the control plane's only: claim another subdomain for the box (up to MAX_BOX_SUBDOMAINS). */
1336
1339
  claimSubdomain(name, req) {
1337
1340
  return this.call("PUT", `/machines/${encodeURIComponent(name)}/subdomain`, SubdomainSchema, req);
1338
1341
  }
1339
- setSubdomainPort(name, req) {
1340
- return this.call("POST", `/machines/${encodeURIComponent(name)}/subdomain/port`, SubdomainSchema, req);
1342
+ /** `sub` names which of the box's subdomains; left out, the box's only one (several: an error). */
1343
+ setSubdomainPort(name, req, sub) {
1344
+ return this.call("POST", subdomainPath(name, "/port", sub), SubdomainSchema, req);
1341
1345
  }
1342
- releaseSubdomain(name) {
1343
- return this.call("DELETE", `/machines/${encodeURIComponent(name)}/subdomain`, SubdomainSchema);
1346
+ releaseSubdomain(name, sub) {
1347
+ return this.call("DELETE", subdomainPath(name, "", sub), SubdomainSchema);
1344
1348
  }
1345
- /** `<route>.<sub>`: a named port under the box's subdomain. */
1346
- addSubdomainRoute(name, req) {
1347
- return this.call("POST", `/machines/${encodeURIComponent(name)}/subdomain/routes`, SubdomainSchema, req);
1349
+ /** `<route>.<sub>`: a named port under one of the box's subdomains. */
1350
+ addSubdomainRoute(name, req, sub) {
1351
+ return this.call("POST", subdomainPath(name, "/routes", sub), SubdomainSchema, req);
1348
1352
  }
1349
- removeSubdomainRoute(name, route) {
1350
- return this.call("DELETE", `/machines/${encodeURIComponent(name)}/subdomain/routes/${encodeURIComponent(route)}`, SubdomainSchema);
1353
+ removeSubdomainRoute(name, route, sub) {
1354
+ return this.call("DELETE", subdomainPath(name, `/routes/${encodeURIComponent(route)}`, sub), SubdomainSchema);
1351
1355
  }
1352
- /** Every readable box's subdomain. */
1356
+ /** Every readable box's subdomains, one entry each. */
1353
1357
  listSubdomains() {
1354
1358
  return this.call("GET", "/subdomains", z3.array(SubdomainSchema));
1355
1359
  }
@@ -1635,6 +1639,9 @@ async function serving(p, timeoutMs, check) {
1635
1639
  }
1636
1640
  throw new KvboxError(`kvbox-server did not start within ${timeoutMs / 1e3}s; see ${p.serverLog}`);
1637
1641
  }
1642
+ function subdomainPath(box, path, sub) {
1643
+ return `/machines/${encodeURIComponent(box)}/subdomain${path}${sub !== void 0 ? `?sub=${encodeURIComponent(sub)}` : ""}`;
1644
+ }
1638
1645
 
1639
1646
  // src/prompt.ts
1640
1647
  import { createInterface } from "readline/promises";
@@ -2246,28 +2253,28 @@ var getCommand = new Command6("get").description("show one box in full: status,
2246
2253
  try {
2247
2254
  const user = me(client);
2248
2255
  const box = await findBox(client, name);
2249
- const sub = client.target.kind === "cloud" ? await subdomainOf(client, box) : void 0;
2256
+ const subs = client.target.kind === "cloud" ? await subdomainsOf(client, box) : [];
2250
2257
  if (opts.json) {
2251
- json({ ...box, ...sub ? { subdomain: subdomainJson(sub, user) } : {} });
2258
+ json({ ...box, ...subs.length > 0 ? { subdomains: subs.map((s) => subdomainJson(s, user)) } : {} });
2252
2259
  return;
2253
2260
  }
2254
- const rows2 = getRows(box, sub, user);
2261
+ const rows2 = getRows(box, subs, user);
2255
2262
  const width2 = Math.max(...rows2.map(([k]) => k.length));
2256
2263
  for (const [k, v] of rows2) info(`${color.dim(k.padStart(width2))} ${v}`);
2257
2264
  } finally {
2258
2265
  await client.close();
2259
2266
  }
2260
2267
  });
2261
- async function subdomainOf(client, box) {
2268
+ async function subdomainsOf(client, box) {
2262
2269
  try {
2263
2270
  const slug = slugOf(box.owner);
2264
- return (await client.listSubdomains()).find((s) => s.box === box.name && s.owner === slug);
2271
+ return (await client.listSubdomains()).filter((s) => s.box === box.name && s.owner === slug);
2265
2272
  } catch (err) {
2266
2273
  warn(`HTTPS name not shown: ${err.message}`);
2267
- return void 0;
2274
+ return [];
2268
2275
  }
2269
2276
  }
2270
- function getRows(box, sub, user) {
2277
+ function getRows(box, subs, user) {
2271
2278
  const rows2 = [
2272
2279
  ["name", color.bold(displayName(box, user))],
2273
2280
  ["status", status(box.status)]
@@ -2279,7 +2286,8 @@ function getRows(box, sub, user) {
2279
2286
  rows2.push(["ssh", box.ssh ? `ssh -p ${box.ssh.port} ${box.ssh.user}@${box.ssh.host}` : `kvbox connect ${displayName(box, user)}`]);
2280
2287
  }
2281
2288
  if (box.url !== void 0) rows2.push(["connect", `${box.url} ${color.dim("(password shown once, at new)")}`]);
2282
- rows2.push(["url", sub ? [`${sub.url} ${color.dim(`(port ${sub.port})`)}`, ...sub.routes.map((r) => `${r.url} ${color.dim(`(port ${r.port})`)}`)].join(", ") : "-"]);
2289
+ const urls = subs.flatMap((sub) => [`${sub.url} ${color.dim(`(port ${sub.port})`)}`, ...sub.routes.map((r) => `${r.url} ${color.dim(`(port ${r.port})`)}`)]);
2290
+ rows2.push(["url", urls.length === 0 ? "-" : urls.join(", ")]);
2283
2291
  const ports = rowsOf(box, user).map((r) => `${r.guestPort}/${r.proto} \u2192 ${reaches(r, true)}`);
2284
2292
  rows2.push(["ports", ports.length === 0 ? "-" : ports.join(", ")]);
2285
2293
  rows2.push(["volumes", box.volumes?.length ? box.volumes.map((v) => `${v.name} ${color.dim(`(${v.sizeGib} GB at ${v.mountPath})`)}`).join(", ") : "-"]);
@@ -2387,6 +2395,7 @@ import { Command as Command11 } from "commander";
2387
2395
  // ../shared/src/names.ts
2388
2396
  import { createHmac } from "crypto";
2389
2397
  var DEFAULT_PROXY_DOMAIN = "kvbox.app";
2398
+ var MAX_BOX_SUBDOMAINS = 5;
2390
2399
  var LABEL_RE = /^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/;
2391
2400
  var RESERVED_SUBDOMAINS = /* @__PURE__ */ new Set([
2392
2401
  "admin",
@@ -2452,7 +2461,7 @@ function assertDomain(text2, proxyDomain) {
2452
2461
  }
2453
2462
 
2454
2463
  // src/commands/vm/proxy/claim.ts
2455
- var claimCommand = new Command11("claim").description("give a box its HTTPS address, https://<subdomain>.kvbox.app, serving one of its ports").argument("[box]", "box name (picked from a list when left out)").argument("[subdomain]", "3-63 lowercase letters, digits and '-'; must be free (asked for when left out)").option("--port <port>", "the box port the address serves (asked for when left out)").option("--json", "print the subdomain as JSON").action(async (nameArg, subArg, opts, cmd) => {
2464
+ var claimCommand = new Command11("claim").description(`give a box an HTTPS address, https://<subdomain>.kvbox.app, serving one of its ports (up to ${MAX_BOX_SUBDOMAINS} per box)`).argument("[box]", "box name (picked from a list when left out)").argument("[subdomain]", "3-63 lowercase letters, digits and '-'; must be free (asked for when left out)").option("--port <port>", "the box port the address serves (asked for when left out)").option("--json", "print the subdomain as JSON").action(async (nameArg, subArg, opts, cmd) => {
2456
2465
  if (nameArg === void 0 || subArg === void 0 || opts.port === void 0) askOrUsage("give the box, the subdomain and the port: kvbox vm proxy claim <box> <subdomain> --port <port>");
2457
2466
  if (subArg !== void 0) assertSubdomain(subArg);
2458
2467
  if (opts.port !== void 0) parsePorts([opts.port]);
@@ -2473,6 +2482,7 @@ var claimCommand = new Command11("claim").description("give a box its HTTPS addr
2473
2482
  }
2474
2483
  info(`${color.green("\u2713")} ${color.bold(sub.url)} \u2192 box ${color.bold(box)} port ${sub.port}`);
2475
2484
  info(` more ports under it: kvbox vm proxy add ${box} <port> --name <name> \u2192 https://<name>.${sub.url.replace(/^https:\/\//, "")}`);
2485
+ info(` another address for this box: kvbox vm proxy claim ${box} <subdomain> --port <port>`);
2476
2486
  if (found.status !== "running") info(` box ${box} is ${found.status}: the address answers once it runs`);
2477
2487
  } finally {
2478
2488
  await client.close();
@@ -2484,12 +2494,14 @@ import { Command as Command17 } from "commander";
2484
2494
 
2485
2495
  // src/commands/vm/proxy/add.ts
2486
2496
  import { Command as Command12 } from "commander";
2487
- var addCommand = new Command12("add").description("publish box ports on the internet; each gets a random public port, or an HTTPS name with --name").argument("<box>", "box name").argument("<port...>", "ports inside the box, e.g. 3000 8080").option("--udp", "UDP instead of TCP").option("--name <name>", "serve the port at https://<name>.<subdomain>.kvbox.app (one port; needs kvbox vm proxy claim first)").option("--json", "print the new forwards as JSON").action(async (name, portTexts, opts, cmd) => {
2497
+ var addCommand = new Command12("add").description("publish box ports on the internet; each gets a random public port, or an HTTPS name with --name").argument("<box>", "box name").argument("<port...>", "ports inside the box, e.g. 3000 8080").option("--udp", "UDP instead of TCP").option("--name <name>", "serve the port at https://<name>.<subdomain>.kvbox.app (one port; needs kvbox vm proxy claim first)").option("--sub <subdomain>", "with --name: which of the box's subdomains it goes under (needed when it has more than one)").option("--json", "print the new forwards as JSON").action(async (name, portTexts, opts, cmd) => {
2488
2498
  const guestPorts = parsePorts(portTexts);
2489
2499
  if (opts.name !== void 0) {
2490
2500
  assertRouteName(opts.name);
2491
2501
  if (guestPorts.length !== 1) throw new KvboxError("--name publishes one port: kvbox vm proxy add <box> <port> --name <name>");
2492
2502
  if (opts.udp) throw new KvboxError("--name serves HTTPS, which is TCP: drop --udp");
2503
+ } else if (opts.sub !== void 0) {
2504
+ throw new KvboxError("--sub goes with --name: kvbox vm proxy add <box> <port> --name <name> --sub <subdomain>");
2493
2505
  }
2494
2506
  const proto = opts.udp ? "udp" : "tcp";
2495
2507
  const client = await clientFor(cmd.optsWithGlobals());
@@ -2500,7 +2512,7 @@ var addCommand = new Command12("add").description("publish box ports on the inte
2500
2512
  const box = displayName(found, user);
2501
2513
  if (opts.name !== void 0) {
2502
2514
  const route = opts.name;
2503
- const sub = await spin(`publishing ${guestPorts[0]} on ${name} as ${route}\u2026`, client.addSubdomainRoute(box, { name: route, port: guestPorts[0] }));
2515
+ const sub = await spin(`publishing ${guestPorts[0]} on ${name} as ${route}\u2026`, client.addSubdomainRoute(box, { name: route, port: guestPorts[0] }, opts.sub));
2504
2516
  const url = sub.routes.find((r) => r.name === route).url;
2505
2517
  if (opts.json) {
2506
2518
  json({ box, guestPort: guestPorts[0], proto: "https", url, name: route });
@@ -2526,7 +2538,7 @@ var addCommand = new Command12("add").description("publish box ports on the inte
2526
2538
 
2527
2539
  // src/commands/vm/proxy/ls.ts
2528
2540
  import { Command as Command13 } from "commander";
2529
- async function subdomainsOf(client) {
2541
+ async function subdomainsOf2(client) {
2530
2542
  try {
2531
2543
  return await client.listSubdomains();
2532
2544
  } catch (err) {
@@ -2540,7 +2552,7 @@ var lsCommand2 = new Command13("ls").description("list the box ports published o
2540
2552
  const user = me(client);
2541
2553
  const [boxes, subs] = await Promise.all([
2542
2554
  name === void 0 ? client.listMachines() : findBox(client, name).then((b) => [b]),
2543
- client.target.kind === "cloud" ? subdomainsOf(client) : []
2555
+ client.target.kind === "cloud" ? subdomainsOf2(client) : []
2544
2556
  ]);
2545
2557
  const shown = new Set(boxes.map((b) => displayName(b, user)));
2546
2558
  const https = subs.flatMap((s) => httpsRowsOf(s, user)).filter((r) => shown.has(r.box));
@@ -2561,17 +2573,17 @@ var lsCommand2 = new Command13("ls").description("list the box ports published o
2561
2573
 
2562
2574
  // src/commands/vm/proxy/release.ts
2563
2575
  import { Command as Command14 } from "commander";
2564
- var releaseCommand = new Command14("release").description("give up a box's HTTPS address and every name under it").argument("<box>", "box name").option("-y, --yes", "do not ask for confirmation").action(async (name, opts, cmd) => {
2576
+ var releaseCommand = new Command14("release").description("give up one of a box's HTTPS addresses and every name under it").argument("<box>", "box name").option("--sub <subdomain>", "which of the box's subdomains (needed when it has more than one)").option("-y, --yes", "do not ask for confirmation").action(async (name, opts, cmd) => {
2565
2577
  const client = await clientFor(cmd.optsWithGlobals());
2566
2578
  try {
2567
2579
  requireCloud(client);
2568
2580
  const box = displayName(await findBox(client, name), me(client));
2569
- if (!await confirm(`Give up box ${box}'s HTTPS address and every name under it? Anyone may claim it after.`, opts.yes ?? false)) {
2581
+ if (!await confirm(`Give up ${opts.sub !== void 0 ? `${opts.sub}, one of box ${box}'s HTTPS addresses,` : `box ${box}'s HTTPS address`} and every name under it? Anyone may claim it after.`, opts.yes ?? false)) {
2570
2582
  info("cancelled");
2571
2583
  process.exitCode = 1;
2572
2584
  return;
2573
2585
  }
2574
- const sub = await spin(`releasing ${name}'s address\u2026`, client.releaseSubdomain(box));
2586
+ const sub = await spin(`releasing ${name}'s address\u2026`, client.releaseSubdomain(box, opts.sub));
2575
2587
  const names2 = sub.routes.length === 0 ? "" : ` and ${sub.routes.length} name${sub.routes.length > 1 ? "s" : ""} under it`;
2576
2588
  info(`${color.green("\u2713")} ${sub.url.replace(/^https:\/\//, "")}${names2} no longer reach box ${color.bold(box)}`);
2577
2589
  } finally {
@@ -2581,10 +2593,12 @@ var releaseCommand = new Command14("release").description("give up a box's HTTPS
2581
2593
 
2582
2594
  // src/commands/vm/proxy/rm.ts
2583
2595
  import { Command as Command15 } from "commander";
2584
- var rmCommand = new Command15("rm").description("stop publishing box ports, or an HTTPS name with --name").argument("<box>", "box name").argument("[port...]", "ports inside the box, as given to add").option("--udp", "the UDP forwards of those ports").option("--name <name>", "the HTTPS name to free (kvbox vm proxy release frees the whole subdomain)").option("-y, --yes", "do not ask for confirmation").action(async (name, portTexts, opts, cmd) => {
2596
+ var rmCommand = new Command15("rm").description("stop publishing box ports, or an HTTPS name with --name").argument("<box>", "box name").argument("[port...]", "ports inside the box, as given to add").option("--udp", "the UDP forwards of those ports").option("--name <name>", "the HTTPS name to free (kvbox vm proxy release frees the whole subdomain)").option("--sub <subdomain>", "with --name: which of the box's subdomains the name is under (needed when it has more than one)").option("-y, --yes", "do not ask for confirmation").action(async (name, portTexts, opts, cmd) => {
2585
2597
  if (opts.name !== void 0) {
2586
2598
  assertRouteName(opts.name);
2587
2599
  if (portTexts.length > 0) throw new KvboxError("--name frees a name, not ports: kvbox vm proxy rm <box> --name <name>");
2600
+ } else if (opts.sub !== void 0) {
2601
+ throw new KvboxError("--sub goes with --name: kvbox vm proxy rm <box> --name <name> --sub <subdomain>");
2588
2602
  } else if (portTexts.length === 0) {
2589
2603
  throw new KvboxError("which ports? kvbox vm proxy rm <box> <port...>, or --name <name> for an HTTPS name");
2590
2604
  }
@@ -2601,7 +2615,7 @@ var rmCommand = new Command15("rm").description("stop publishing box ports, or a
2601
2615
  return;
2602
2616
  }
2603
2617
  if (opts.name !== void 0) {
2604
- const sub = await spin(`freeing ${opts.name} on ${name}\u2026`, client.removeSubdomainRoute(box, opts.name));
2618
+ const sub = await spin(`freeing ${opts.name} on ${name}\u2026`, client.removeSubdomainRoute(box, opts.name, opts.sub));
2605
2619
  info(`${color.green("\u2713")} ${opts.name}.${sub.url.replace(/^https:\/\//, "")} no longer reaches box ${color.bold(box)}`);
2606
2620
  return;
2607
2621
  }
@@ -2614,13 +2628,13 @@ var rmCommand = new Command15("rm").description("stop publishing box ports, or a
2614
2628
 
2615
2629
  // src/commands/vm/proxy/set-port.ts
2616
2630
  import { Command as Command16 } from "commander";
2617
- var setPortCommand = new Command16("set-port").description("point a box's HTTPS address at another of its ports").argument("<box>", "box name").argument("<port>", "the box port https://<subdomain>.kvbox.app serves from now on").option("--json", "print the subdomain as JSON").action(async (name, portText, opts, cmd) => {
2631
+ var setPortCommand = new Command16("set-port").description("point a box's HTTPS address at another of its ports").argument("<box>", "box name").argument("<port>", "the box port https://<subdomain>.kvbox.app serves from now on").option("--sub <subdomain>", "which of the box's subdomains (needed when it has more than one)").option("--json", "print the subdomain as JSON").action(async (name, portText, opts, cmd) => {
2618
2632
  const [port] = parsePorts([portText]);
2619
2633
  const client = await clientFor(cmd.optsWithGlobals());
2620
2634
  try {
2621
2635
  requireCloud(client);
2622
2636
  const box = displayName(await findBox(client, name), me(client));
2623
- const sub = await spin(`pointing ${name} at port ${port}\u2026`, client.setSubdomainPort(box, { port }));
2637
+ const sub = await spin(`pointing ${name} at port ${port}\u2026`, client.setSubdomainPort(box, { port }, opts.sub));
2624
2638
  if (opts.json) {
2625
2639
  json(subdomainJson(sub, me(client)));
2626
2640
  return;
@@ -3824,6 +3838,7 @@ var PricingSchema = z4.object({
3824
3838
  volumeGibHour: z4.number().nonnegative().default(0),
3825
3839
  diskIncludedGib: z4.number().int().nonnegative().default(0)
3826
3840
  });
3841
+ var PriceListSchema = PricingSchema.extend({ welcomeCredit: z4.number().nonnegative() });
3827
3842
  var round = (n, places) => Math.round(n * 10 ** places) / 10 ** places;
3828
3843
  function costOf(t, pricing) {
3829
3844
  return t.vcpuHours * pricing.vcpuHour + t.ramGibHours * pricing.ramGibHour + t.diskGibHours * pricing.diskGibHour;
@@ -4024,13 +4039,13 @@ function creditRow(b, me2) {
4024
4039
  }
4025
4040
 
4026
4041
  // src/commands/deploy/index.ts
4027
- import { readFile as readFile7 } from "fs/promises";
4042
+ import { access as access4, readFile as readFile7 } from "fs/promises";
4028
4043
  import { basename, resolve as resolve2 } from "path";
4029
4044
  import { Command as Command61, InvalidArgumentError as InvalidArgumentError2, Option as Option5 } from "commander";
4030
4045
 
4031
4046
  // src/commands/deploy/config.ts
4032
4047
  import { readFile as readFile6, writeFile as writeFile4 } from "fs/promises";
4033
- import { join as join4 } from "path";
4048
+ import { join as join5 } from "path";
4034
4049
  import { z as z5 } from "zod";
4035
4050
 
4036
4051
  // src/commands/deploy/templates/pm.ts
@@ -4212,40 +4227,62 @@ var reactTemplate = {
4212
4227
  `the build left no ${candidates.join(" or ")}/index.html. The React template ships a directory of static files; set "dist" in kvbox.json to the build output directory, or pick the right template with --template`
4213
4228
  );
4214
4229
  },
4215
- /**
4216
- * The archive lands in a staging directory, which then becomes /srv/app/dist in one move; the
4217
- * old site is kept beside it until the new one is in place, so a failed step never leaves nginx
4218
- * without a root and a visitor never sees a half-copied site. Files get read permission for
4219
- * nginx's user, whatever umask the build ran under. /srv/app is the kvbox user's (image v0.8.0+);
4220
- * the missing site file means an older image.
4221
- */
4222
- remote() {
4223
- return [
4224
- "set -e",
4225
- "test -e /etc/nginx/sites-enabled/kvbox-app || exit 3",
4226
- "rm -rf /srv/app/.incoming /srv/app/.old",
4227
- "mkdir -p /srv/app/.incoming",
4228
- "tar -xf - -C /srv/app/.incoming",
4229
- "chmod -R a+rX /srv/app/.incoming",
4230
- "if [ -e /srv/app/dist ]; then mv /srv/app/dist /srv/app/.old; fi",
4231
- "mv /srv/app/.incoming /srv/app/dist",
4232
- "rm -rf /srv/app/.old",
4233
- "sudo -n systemctl enable --now --quiet nginx",
4234
- "sudo -n systemctl reload nginx"
4235
- ].join("\n");
4236
- }
4230
+ remote: nginxRemote
4231
+ };
4232
+ function nginxRemote() {
4233
+ return [
4234
+ "set -e",
4235
+ "test -e /etc/nginx/sites-enabled/kvbox-app || exit 3",
4236
+ "rm -rf /srv/app/.incoming /srv/app/.old",
4237
+ "mkdir -p /srv/app/.incoming",
4238
+ "tar -xf - -C /srv/app/.incoming",
4239
+ "chmod -R a+rX /srv/app/.incoming",
4240
+ "if [ -e /srv/app/dist ]; then mv /srv/app/dist /srv/app/.old; fi",
4241
+ "mv /srv/app/.incoming /srv/app/dist",
4242
+ "rm -rf /srv/app/.old",
4243
+ "sudo -n systemctl enable --now --quiet nginx",
4244
+ "sudo -n systemctl reload nginx"
4245
+ ].join("\n");
4246
+ }
4247
+
4248
+ // src/commands/deploy/templates/static.ts
4249
+ import { access as access3 } from "fs/promises";
4250
+ import { join as join4 } from "path";
4251
+ var EXCLUDE = ["node_modules", ".git", "kvbox.json"];
4252
+ var staticTemplate = {
4253
+ id: "static",
4254
+ label: "Static site",
4255
+ hint: "plain HTML, CSS and JS: shipped as is, served by nginx in the box",
4256
+ size: "xs",
4257
+ port: 80,
4258
+ /** An index.html at the top and nothing to build; a project with a `build` script is one of the others, or says --template static. */
4259
+ detect(pkg, dir) {
4260
+ return dir.indexHtml && typeof pkg?.scripts?.["build"] !== "string";
4261
+ },
4262
+ async build(ctx) {
4263
+ const dist = ctx.dist;
4264
+ const outDir = dist !== void 0 ? join4(ctx.dir, dist) : ctx.dir;
4265
+ if (!await access3(join4(outDir, "index.html")).then(() => true, () => false)) {
4266
+ throw new KvboxError(
4267
+ `${outDir} has no index.html. The static template ships a directory of files as it is; set "dist" in kvbox.json to the folder that holds the site, or pick another template with --template`
4268
+ );
4269
+ }
4270
+ const pm = ctx.pkg !== void 0 ? await packageManager(ctx.dir) : "npm";
4271
+ return { outDir, ...dist !== void 0 ? { dist } : {}, exclude: EXCLUDE, pm, what: dist !== void 0 ? `${dist}/` : "the directory" };
4272
+ },
4273
+ remote: nginxRemote
4237
4274
  };
4238
4275
 
4239
4276
  // src/commands/deploy/templates/index.ts
4240
- var TEMPLATES = [reactTemplate, nextjsTemplate, nodeTemplate];
4277
+ var TEMPLATES = [reactTemplate, nextjsTemplate, nodeTemplate, staticTemplate];
4241
4278
  var TEMPLATE_IDS = TEMPLATES.map((t) => t.id);
4242
4279
  function templateById(id) {
4243
4280
  const t = TEMPLATES.find((x) => x.id === id);
4244
4281
  if (!t) throw new Error(`no template ${id}`);
4245
4282
  return t;
4246
4283
  }
4247
- function detectTemplate(pkg) {
4248
- return TEMPLATES.find((t) => t.detect(pkg));
4284
+ function detectTemplate(pkg, dir = { indexHtml: false }) {
4285
+ return TEMPLATES.find((t) => t.detect(pkg, dir));
4249
4286
  }
4250
4287
 
4251
4288
  // src/commands/deploy/config.ts
@@ -4269,7 +4306,7 @@ var DeployConfigSchema = z5.object({
4269
4306
  port: z5.number().int().min(1).max(65535).optional()
4270
4307
  });
4271
4308
  async function readConfig(dir) {
4272
- const path = join4(dir, CONFIG_FILE);
4309
+ const path = join5(dir, CONFIG_FILE);
4273
4310
  let raw;
4274
4311
  try {
4275
4312
  raw = await readFile6(path, "utf8");
@@ -4291,7 +4328,7 @@ async function readConfig(dir) {
4291
4328
  return parsed.data;
4292
4329
  }
4293
4330
  async function writeConfig(dir, config) {
4294
- await writeFile4(join4(dir, CONFIG_FILE), JSON.stringify(config, null, 2) + "\n");
4331
+ await writeFile4(join5(dir, CONFIG_FILE), JSON.stringify(config, null, 2) + "\n");
4295
4332
  }
4296
4333
  function nameFromDir(dirName) {
4297
4334
  const slug = dirName.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 12).replace(/-+$/, "");
@@ -4304,7 +4341,7 @@ function subdomainFor(name) {
4304
4341
  // src/commands/deploy/ship.ts
4305
4342
  import { spawn as spawn6 } from "child_process";
4306
4343
  import { readdir, stat as stat2 } from "fs/promises";
4307
- import { join as join5 } from "path";
4344
+ import { join as join6 } from "path";
4308
4345
  var IMAGE_TOO_OLD = 3;
4309
4346
  var SSH_FAILED3 = 255;
4310
4347
  async function measure(dir, exclude = []) {
@@ -4312,7 +4349,7 @@ async function measure(dir, exclude = []) {
4312
4349
  const walk = async (d) => {
4313
4350
  for (const entry of await readdir(d, { withFileTypes: true })) {
4314
4351
  if (exclude.includes(entry.name)) continue;
4315
- const path = join5(d, entry.name);
4352
+ const path = join6(d, entry.name);
4316
4353
  if (entry.isDirectory()) await walk(path);
4317
4354
  else if (entry.isFile()) {
4318
4355
  total.files += 1;
@@ -4355,9 +4392,10 @@ async function ship(ep, dir, remote, exclude = []) {
4355
4392
  var shipping = { ship, measure, waitForSsh };
4356
4393
 
4357
4394
  // src/commands/deploy/index.ts
4358
- var deployCommand = new Command61("deploy").description("put the app in this directory (React, Next.js or a Node server) on a box with its own HTTPS address; redeploy by running it again").argument("[dir]", "the app's directory (default: the current one)").addOption(new Option5("-t, --template <template>", "what kind of app it is (detected from package.json when not given)").choices(TEMPLATE_IDS)).option("-n, --name <name>", "the box's name (default: the directory's name)").option("--sub <subdomain>", "its HTTPS name, https://<subdomain>.kvbox.app (default: the box's name)").addOption(new Option5("-s, --size <size>", "size of the box when it has to be made").choices(SIZE_NAMES)).option("--port <port>", "the port a Next.js app or Node server listens on (default 3000; saved to kvbox.json)", parsePort).option("-y, --yes", "ask nothing: take the defaults for whatever the flags and kvbox.json leave open").option("--json", "print the result as JSON").option("--org <slug>", "deploy into this org's boxes (saved to kvbox.json)").action(async (dirArg, opts, cmd) => {
4395
+ var deployCommand = new Command61("deploy").description("put the app in this directory (React, Next.js, a Node server or a static site) on a box with its own HTTPS address; redeploy by running it again").argument("[dir]", "the app's directory (default: the current one)").addOption(new Option5("-t, --template <template>", "what kind of app it is (detected from package.json and the directory when not given)").choices(TEMPLATE_IDS)).option("-n, --name <name>", "the box's name (default: the directory's name)").option("--sub <subdomain>", "its HTTPS name, https://<subdomain>.kvbox.app (default: the box's name)").addOption(new Option5("-s, --size <size>", "size of the box when it has to be made").choices(SIZE_NAMES)).option("--port <port>", "the port a Next.js app or Node server listens on (default 3000; saved to kvbox.json)", parsePort).option("-y, --yes", "ask nothing: take the defaults for whatever the flags and kvbox.json leave open").option("--json", "print the result as JSON").option("--org <slug>", "deploy into this org's boxes (saved to kvbox.json)").action(async (dirArg, opts, cmd) => {
4359
4396
  const dir = resolve2(dirArg ?? ".");
4360
4397
  const pkg = await readPackageJson(dir);
4398
+ const facts = { indexHtml: await access4(resolve2(dir, "index.html")).then(() => true, () => false) };
4361
4399
  const saved = await readConfig(dir);
4362
4400
  const globals = cmd.optsWithGlobals();
4363
4401
  const orgFlag = orgOption(globals);
@@ -4366,7 +4404,7 @@ var deployCommand = new Command61("deploy").description("put the app in this dir
4366
4404
  try {
4367
4405
  const cloud = client.target.kind === "cloud";
4368
4406
  if (!cloud && org !== void 0) throw new KvboxError("--org needs a control plane: kvbox login, or drop --org");
4369
- const { config, template, fresh } = await settle(dir, pkg, saved, opts, orgFlag, cloud);
4407
+ const { config, template, fresh } = await settle(dir, pkg, facts, saved, opts, orgFlag, cloud);
4370
4408
  if (cloud && config.subdomain !== void 0) await refuseOtherAddress(client, config);
4371
4409
  await writeConfig(dir, config);
4372
4410
  if (fresh) info(` ${color.dim(`saved to ${CONFIG_FILE}; next time kvbox deploy asks nothing`)}
@@ -4443,8 +4481,8 @@ async function readPackageJson(dir) {
4443
4481
  throw new KvboxError(`${resolve2(dir, "package.json")}: ${err.message}`);
4444
4482
  }
4445
4483
  }
4446
- async function settle(dir, pkg, saved, opts, orgFlag, cloud) {
4447
- const detected = detectTemplate(pkg);
4484
+ async function settle(dir, pkg, facts, saved, opts, orgFlag, cloud) {
4485
+ const detected = detectTemplate(pkg, facts);
4448
4486
  if (opts.name !== void 0 && !BOX_NAME_RE.test(opts.name)) throw new KvboxError(`--name ${opts.name}: ${NAME_RULE}`);
4449
4487
  if (opts.sub !== void 0) assertSubdomain(opts.sub);
4450
4488
  const renamed = saved !== void 0 && (opts.name !== void 0 && opts.name !== saved.name || orgFlag !== void 0 && orgFlag !== saved.org);
@@ -4478,7 +4516,7 @@ async function settle(dir, pkg, saved, opts, orgFlag, cloud) {
4478
4516
  const initial = detected ? TEMPLATES.indexOf(detected) : 0;
4479
4517
  templateId = await select("Template", TEMPLATES.map((t) => ({ value: t.id, label: t.label, hint: t === detected ? `${t.hint} \xB7 detected` : t.hint })), initial);
4480
4518
  }
4481
- if (templateId === void 0) throw new KvboxError(`could not tell what kind of app ${dir} is (no package.json of a Vite, Create React App or Next.js project, or of a server on Express, Fastify, Koa, Hono or NestJS): say it with --template ${TEMPLATE_IDS.join("|")}`);
4519
+ if (templateId === void 0) throw new KvboxError(`could not tell what kind of app ${dir} is (no package.json of a Vite, Create React App or Next.js project, or of a server on Express, Fastify, Koa, Hono or NestJS, and no index.html): say it with --template ${TEMPLATE_IDS.join("|")}`);
4482
4520
  const template = templateById(templateId);
4483
4521
  let name = defaults.name;
4484
4522
  if (open.name && ask) name = await text("Box name", { default: defaults.name, validate: (a) => BOX_NAME_RE.test(a) ? void 0 : NAME_RULE });
@@ -4529,22 +4567,23 @@ async function findOrCreate(client, config) {
4529
4567
  }
4530
4568
  return { box, ref: displayName(box, user), created };
4531
4569
  }
4532
- async function existingAddress(client, config) {
4570
+ async function existingAddresses(client, config) {
4533
4571
  const slug = config.org ?? me(client);
4534
- return (await client.listSubdomains()).find((s) => s.box === config.name && s.owner === slug);
4572
+ return (await client.listSubdomains()).filter((s) => s.box === config.name && s.owner === slug);
4535
4573
  }
4536
4574
  async function refuseOtherAddress(client, config) {
4537
- const have = await existingAddress(client, config);
4538
- if (!have || have.subdomain === config.subdomain) return;
4575
+ const have = await existingAddresses(client, config);
4576
+ if (have.length < MAX_BOX_SUBDOMAINS || have.some((s) => s.subdomain === config.subdomain)) return;
4539
4577
  const ref = config.org !== void 0 ? `${config.org}/${config.name}` : config.name;
4540
4578
  throw new KvboxError(
4541
- `box ${ref} already answers at ${have.url}, not ${config.subdomain}. To keep the address: kvbox deploy --sub ${have.subdomain}. To move it: kvbox vm proxy release ${ref}, then deploy again`
4579
+ `box ${ref} already has ${MAX_BOX_SUBDOMAINS} addresses (${have.map((s) => s.subdomain).join(", ")}), none of them ${config.subdomain}. Deploy to one: kvbox deploy --sub <name>. Or free one: kvbox vm proxy release ${ref} --sub <name>`
4542
4580
  );
4543
4581
  }
4544
4582
  async function address(client, box, ref, config, port) {
4545
- const have = (await client.listSubdomains()).find((s) => s.box === box.name && s.owner === slugOf(box.owner));
4583
+ const subs = (await client.listSubdomains()).filter((s) => s.box === box.name && s.owner === slugOf(box.owner));
4584
+ const have = config.subdomain !== void 0 ? subs.find((s) => s.subdomain === config.subdomain) : subs[0];
4546
4585
  if (have) {
4547
- if (have.port !== port) await client.setSubdomainPort(ref, { port });
4586
+ if (have.port !== port) await client.setSubdomainPort(ref, { port }, have.subdomain);
4548
4587
  return { url: have.url, subdomain: have.subdomain };
4549
4588
  }
4550
4589
  const wanted = config.subdomain ?? subdomainFor(config.name);
@@ -4977,25 +5016,12 @@ var rmCommand9 = new Command74("rm").alias("remove").description("stop serving a
4977
5016
  var domainCommand = new Command75("domain").alias("domains").description("serve a box at a domain of your own").addCommand(addCommand3).addCommand(lsCommand10).addCommand(rmCommand9);
4978
5017
  for (const cmd of domainCommand.commands) cmd.option("--org <slug>", "act in this org (- for your personal boxes)");
4979
5018
 
4980
- // src/program.ts
4981
- function buildProgram() {
4982
- const program = new Command76("kvbox").description("self-hosted Firecracker microVMs with Docker-like ergonomics").version(VERSION, "-v, --version").option("--local", "use this machine's kvbox-server over its socket, ignoring kvbox login").option("--org <slug>", "the org: where kvbox new creates, and which box a name means when it is not one of yours; before the command here, or after it").showHelpAfterError().enablePositionalOptions();
4983
- program.addCommand(vmCommand);
4984
- program.addCommand(snapshotsCommand);
4985
- program.addCommand(volumeCommand);
4986
- program.addCommand(envCommand);
4987
- program.addCommand(domainCommand);
4988
- program.addCommand(serverCommand);
4989
- program.addCommand(loginCommand);
4990
- program.addCommand(logoutCommand);
4991
- program.addCommand(whoamiCommand);
4992
- program.addCommand(orgCommand);
4993
- program.addCommand(usageCommand2);
4994
- program.addCommand(creditCommand);
4995
- program.addCommand(deployCommand);
4996
- for (const cmd of vmAliases) program.addCommand(cmd);
4997
- return program;
4998
- }
5019
+ // src/commands/update.ts
5020
+ import { spawn as spawn7 } from "child_process";
5021
+ import { mkdtempSync, rmSync, writeFileSync as writeFileSync2 } from "fs";
5022
+ import { tmpdir } from "os";
5023
+ import { join as join7 } from "path";
5024
+ import { Command as Command76 } from "commander";
4999
5025
 
5000
5026
  // src/update.ts
5001
5027
  import { mkdirSync, readFileSync as readFileSync3, writeFileSync } from "fs";
@@ -5003,7 +5029,11 @@ import { dirname } from "path";
5003
5029
  var REGISTRY_URL = "https://registry.npmjs.org/@kvbox/cli/latest";
5004
5030
  var CHECK_EVERY_MS = 24 * 60 * 60 * 1e3;
5005
5031
  var FETCH_TIMEOUT_MS = 1500;
5006
- var UPDATE_COMMAND = "npm install -g @kvbox/cli";
5032
+ var UPDATE_COMMAND = "kvbox update";
5033
+ var suppressed = false;
5034
+ function suppressUpdateNotice() {
5035
+ suppressed = true;
5036
+ }
5007
5037
  function isNewer(a, b) {
5008
5038
  const pa = parse(a);
5009
5039
  const pb = parse(b);
@@ -5069,6 +5099,7 @@ function enabled() {
5069
5099
  function startUpdateCheck() {
5070
5100
  if (!enabled()) return Promise.resolve();
5071
5101
  process.on("exit", () => {
5102
+ if (suppressed) return;
5072
5103
  const state = readUpdateState();
5073
5104
  const notice = state ? updateNotice(state.latest) : null;
5074
5105
  if (notice) process.stderr.write(notice);
@@ -5076,6 +5107,80 @@ function startUpdateCheck() {
5076
5107
  return refreshUpdateState();
5077
5108
  }
5078
5109
 
5110
+ // src/commands/update.ts
5111
+ var INSTALL_BASE = "https://kvbox.sh";
5112
+ function installerFor(platform, base = INSTALL_BASE) {
5113
+ const root = base.replace(/\/+$/, "");
5114
+ if (platform === "win32") {
5115
+ const url = `${root}/install.ps1`;
5116
+ return {
5117
+ url,
5118
+ cmd: "powershell.exe",
5119
+ args: ["-NoProfile", "-ExecutionPolicy", "Bypass", "-Command", `irm ${url} | iex`]
5120
+ };
5121
+ }
5122
+ return { url: `${root}/install.sh`, cmd: "bash", args: ["{script}"] };
5123
+ }
5124
+ async function download(url) {
5125
+ let res;
5126
+ try {
5127
+ res = await fetch(url, { signal: AbortSignal.timeout(3e4) });
5128
+ } catch (err) {
5129
+ throw new KvboxError(`could not download ${url}: ${err.message}`);
5130
+ }
5131
+ if (!res.ok) throw new KvboxError(`could not download ${url}: HTTP ${res.status}`);
5132
+ const body = await res.text();
5133
+ if (!body.startsWith("#!")) throw new KvboxError(`${url} did not return a shell script`);
5134
+ return body;
5135
+ }
5136
+ function run(cmd, args) {
5137
+ return new Promise((resolve3, reject) => {
5138
+ const child = spawn7(cmd, args, { stdio: "inherit" });
5139
+ child.on("error", (err) => reject(new KvboxError(`could not run ${cmd}: ${err.message}`)));
5140
+ child.on("exit", (code, signal) => resolve3(code ?? (signal ? 1 : 0)));
5141
+ });
5142
+ }
5143
+ var selfUpdateCommand = new Command76("update").description("update kvbox to the latest version (reruns the installer from kvbox.sh, agent skill included)").action(async () => {
5144
+ suppressUpdateNotice();
5145
+ const inst = installerFor(process.platform, process.env["KVBOX_INSTALL_URL"] || INSTALL_BASE);
5146
+ let code;
5147
+ if (process.platform === "win32") {
5148
+ code = await run(inst.cmd, inst.args);
5149
+ } else {
5150
+ const script = await download(inst.url);
5151
+ const dir = mkdtempSync(join7(tmpdir(), "kvbox-update-"));
5152
+ const file = join7(dir, "install.sh");
5153
+ try {
5154
+ writeFileSync2(file, script, { mode: 448 });
5155
+ code = await run(inst.cmd, inst.args.map((a) => a === "{script}" ? file : a));
5156
+ } finally {
5157
+ rmSync(dir, { recursive: true, force: true });
5158
+ }
5159
+ }
5160
+ if (code !== 0) throw new KvboxError(`the installer failed (exit ${code})`, code);
5161
+ });
5162
+
5163
+ // src/program.ts
5164
+ function buildProgram() {
5165
+ const program = new Command77("kvbox").description("self-hosted Firecracker microVMs with Docker-like ergonomics").version(VERSION, "-v, --version").option("--local", "use this machine's kvbox-server over its socket, ignoring kvbox login").option("--org <slug>", "the org: where kvbox new creates, and which box a name means when it is not one of yours; before the command here, or after it").showHelpAfterError().enablePositionalOptions();
5166
+ program.addCommand(vmCommand);
5167
+ program.addCommand(snapshotsCommand);
5168
+ program.addCommand(volumeCommand);
5169
+ program.addCommand(envCommand);
5170
+ program.addCommand(domainCommand);
5171
+ program.addCommand(serverCommand);
5172
+ program.addCommand(loginCommand);
5173
+ program.addCommand(logoutCommand);
5174
+ program.addCommand(whoamiCommand);
5175
+ program.addCommand(orgCommand);
5176
+ program.addCommand(usageCommand2);
5177
+ program.addCommand(creditCommand);
5178
+ program.addCommand(deployCommand);
5179
+ program.addCommand(selfUpdateCommand);
5180
+ for (const cmd of vmAliases) program.addCommand(cmd);
5181
+ return program;
5182
+ }
5183
+
5079
5184
  // src/index.ts
5080
5185
  var updateCheck = startUpdateCheck();
5081
5186
  try {