runServe

tcmts.cli.run.runServe · #ifquuob7 · term · runs on the server

uses node:path

Runs tcm serve.

import { routeServe } from "#codebase/tcmts/cli/commands";
import { execute } from "#codebase/tcmts/cli/main";
import type { Context } from "#codebase/tcmts/cli/run";
import { newToken, serve, tlsMaterial } from "#codebase/tcmts/cli/sync";
import { UsageError } from "#codebase/tcmts/cli/ui";
import { parse } from "@bomb.sh/router";
import fs from "node:fs";
import path_1 from "node:path";

export function runServe({ cb, cmd, rest, cwd }: Context): number {
  const { model } = execute(cmd, parse(routeServe(), { argv: rest }));
  const given = model.token ?? process.env.TCM_TOKEN;
  const token = given ?? newToken();
  const tls =
    model.tls || model["tls-cert"]
      ? tlsMaterial(cb, model["tls-cert"], model["tls-key"])
      : undefined;
  // --insecure acknowledges clear-text tokens beyond localhost
  const site = model.site ? path_1.resolve(cwd, model.site) : undefined;
  if (site && !fs.existsSync(path_1.join(site, "index.html")))
    throw new UsageError(`--site ${model.site}: there's no index.html there`);
  const moved = model.moved?.replace(/\/+$/, "");
  if (moved !== undefined && (!site || !moved.startsWith("/")))
    throw new UsageError(
      `--moved ${model.moved}: a path of the --site its pages moved under, as /docs`,
    );
  const proxies = (model.proxy ?? []).map((p) => {
    const [at, to] = p.split("=");
    const servers = (to ?? "").split("|");
    if (!at?.startsWith("/") || !servers.every((s) => /^https?:\/\/\S+$/.test(s)))
      throw new UsageError(
        `--proxy ${p}: a path and the server its requests go to (or several, |-separated), as /examples/notes=http://127.0.0.1:7801`,
      );
    return { path: at.replace(/\/+$/, ""), to: servers };
  });
  serve(
    cb,
    {
      host: model.host,
      port: model.port,
      token,
      allowRun: model.run,
      public: model.public,
      tls,
      showToken: !given,
      ...(site ? { site } : {}),
      ...(moved ? { moved } : {}),
      ...(proxies.length ? { proxies } : {}),
    },
    model.insecure,
  );
  return -1; // keep running
}

uses

used by