LibraryPage

tcmts.registry.pages.LibraryPage · #cvumbfga · term · runs on the server

is an async component

A library: its newest version, or the one asked for, with its README, code, versions, dependents and what tcm checked; beside them, how to add it, where it runs, what it reaches, where it's fetched from and the libraries it holds.

import { libraryName } from "#codebase/tcmts/cli/libraries";
import { shellWord } from "#codebase/tcmts/cli/ui";
import { shortHash } from "#codebase/tcmts/core/hash";
import { compareVersions } from "#codebase/tcmts/core/semver";
import { STAR_COLLECTION, starKey } from "#codebase/tcmts/records";
import {
  addLine, changesHref, everyone, latestRelease, libraries, libraryHref, libraryKey, ownNames, registryShare,
  releaseOfNamespace, releases, said, shownAttestations, starCounts, stars, usersByNamespace, uses, visitor, whoHref,
  whoIs, yanksOf,
} from "#codebase/tcmts/registry";
import {
  Initial, Legend, Level, LinkSelect, NotHere, PlaceBar, Reaches, RegistryFrame, StarButton,
} from "#codebase/tcmts/registry/pages";
import {
  ago, at, codeHref, CopyButton, DefRow, Html, leafOf, markdownHtml, NavTabs, shareNow, Trail,
} from "#codebase/tcmts/share";
import { Meter } from "react-aria-components";

export async function LibraryPage({ who: asked, pkg, version, tab }: { who: string; pkg: string; version?: string; tab: string }) {
  registryShare();
  const who = await whoIs(asked);
  if (!who) return <NotHere what={`The registry doesn't know @${asked}.`} />;
  const all = (await releases.find({ did: who.did, package: pkg })).map((r) => r.value);
  all.sort((a, b) => compareVersions(b.version, a.version));
  const shown = all.filter((r) => r.state !== "failed");
  // (its versions its author yanked: not the latest, nor in its picker, unless it's the one asked for)
  const everySaid = await shownAttestations();
  const yanks = yanksOf(shown, everySaid);
  const latest = shown.length ? latestRelease(shown, yanks) : undefined;
  const r = version ? all.find((x) => x.version === version) : latest;
  if (!r) return <NotHere what={`${said(who)} hasn't announced ${pkg}${version ? `@${version}` : ""}.`} />;
  const s = shareNow();
  const cb = s.cb;
  const lib = (await libraries({ yanked: true })).find((l) => libraryKey(l) === libraryKey(r));
  const users = await usersByNamespace(shown.length ? (await releases.find({ state: "mirrored" })).map((x) => x.value) : []);
  const people = await everyone();
  const mounted = r.state !== "failed" && r.state !== "pending" && r.mount;
  const own = mounted ? ownNames(cb, r.mount!) : [];
  const readme = own.find((n) => n.path === `${r.mount}.README` && n.kind === "file");
  const held = mounted ? (await uses.find({ uri: r.uri })).map((u) => u.value) : [];
  const heldAs = await Promise.all(held.map(async (u) => ({ u, r: await releaseOfNamespace(u.namespace) })));
  // what people say of this version (yanks only from its author), checked against their repositories
  const said_ = everySaid.filter((a) => a.namespace === r.namespace);
  const yank = yanks.get(r.uri);
  // (the latest to point to from a yanked or withdrawn version: one that's neither)
  const instead = latest && latest !== r && latest.state === "mirrored" && !yanks.has(latest.uri) ? latest : undefined;
  const dependents = shown.flatMap((v) => (users.get(v.namespace) ?? []).filter((d) => libraryKey(d) !== libraryKey(r)).map((d) => ({ v, d })));
  const tabs = [
    { id: "", label: "README", href: libraryHref(who, pkg, version) },
    { id: "code", label: "Code", href: libraryHref(who, pkg, version, "code"), count: own.length },
    { id: "versions", label: "Versions", href: libraryHref(who, pkg, version, "versions"), count: shown.length },
    { id: "dependents", label: "Dependents", href: libraryHref(who, pkg, version, "dependents"), count: lib?.dependents ?? 0 },
    {
      id: "trust",
      label: "Trust",
      href: libraryHref(who, pkg, version, "trust"),
      count: said_.filter((a) => a.kind !== "yank").length,
    },
  ];
  // (its stars, across versions, and whether the visitor's is one)
  const me = await visitor();
  const starCount = (await starCounts()).get(libraryKey({ did: who.did, package: pkg })) ?? 0;
  const mine = me ? await stars.findOne({ uri: `at://${me.did}/${STAR_COLLECTION}/${starKey(who.did, pkg)}` }) : undefined;
  const p = r.facts?.places;
  const add = addLine(who, pkg, r.version);
  const byHash =
    r.sources[0] &&
    `tcm lib add ${shellWord(r.sources[0])} ${shellWord(`#${r.namespace}`)} --as ${shellWord(libraryName(pkg))}`;
  const host = (u: string) => {
    try {
      return new URL(u).host;
    } catch {
      return u;
    }
  };
  // (how many of what the registry has use each version, for the bars)
  const perVersion = shown
    .map((v) => ({ v, n: dependents.filter((d) => d.v === v).length }))
    .filter((x) => x.n);
  const most = Math.max(1, ...perVersion.map((x) => x.n));
  return (
    <RegistryFrame tab="libraries" title={`${said(who)}/${pkg}`}>
      <div className="page cols-2">
        <div>
          <div className="crumbs">
            <Trail
              items={[
                { label: "Libraries", href: at("/libraries") },
                { label: said(who), href: whoHref(who) },
                { label: pkg },
              ]}
            />
          </div>
          <div className="libhead">
            <h1 className="title mono">{pkg}</h1>
            <LinkSelect
              label={`${pkg}'s versions`}
              selected={r.version}
              options={shown
                .filter((v) => !yanks.has(v.uri) || v === r)
                .map((v) => ({
                  id: v.version,
                  label: `${v.version}${v === latest && !yanks.has(v.uri) ? " · latest" : ""}${v.state === "withdrawn" ? " · withdrawn" : ""}${yanks.has(v.uri) ? " · yanked" : ""}`,
                  href: libraryHref(who, pkg, v === latest ? undefined : v.version, tab || undefined),
                }))}
            />
            {r.verifiedAt && r.state !== "failed" && <span className="signed">✓ signed by {said(who)}</span>}
          </div>
          {r.facts?.description && <p className="lede">{r.facts.description}</p>}
          <div className="facts">
            <span className="hash">{shortHash(r.namespace)}</span>
            {r.facts?.license && <span>{r.facts.license}</span>}
            <span>released {ago(Date.parse(r.createdAt))}</span>
            {mounted && <span>{own.length} definitions</span>}
            <span>used by {lib?.dependents ?? 0}</span>
            <StarButton author={who.did} pkg={pkg} count={starCount} starred={mine?.value.state === "verified"} />
          </div>
          {r.state === "pending" && (
            <div className="notice">⋯ Mirroring: fetching it from its sources and checking every hash; its code appears when that's done.</div>
          )}
          {r.state === "failed" && (
            <div className="notice bad">
              ⚠ Authorship not verified: {r.reason}. It isn't shown as {said(who)}'s; only who released it is in doubt, not what its hash names.
            </div>
          )}
          {yank && (
            <div className="notice bad">
              ↩ Yanked by {said(who)}: {yank.body.split("\n")[0]}
              {/[.!?]$/.test(yank.body.split("\n")[0]!) ? "" : "."} It's left out of the registry's lists; its code stays,
              by hash, for what still uses it.
              {instead && (
                <>
                  {" "}
                  The latest is <a href={libraryHref(who, pkg, instead.version)}>{instead.version}</a>.
                </>
              )}
            </div>
          )}
          {said_
            .filter((a) => a.kind === "advisory")
            .map((a) => (
              <div className="notice bad" key={a.uri}>
                ⚠ Advisory ({a.severity}) from {said(people.get(a.did) ?? { did: a.did })}: {a.body.split("\n")[0]}
                {a.fixedIn ? ` Fixed in ${a.fixedIn}.` : ""}
              </div>
            ))}
          {r.state === "withdrawn" && (
            <div className="notice">
              ↩ Withdrawn by {said(who)}. Its code stays, by hash, for what still uses it.
              {instead && (
                <>
                  {" "}
                  The latest is <a href={libraryHref(who, pkg, instead.version)}>{instead.version}</a>.
                </>
              )}
            </div>
          )}
          <div className="subtabs">
            <NavTabs label="Library" selected={tab || "readme"} tabs={tabs.map((t) => ({ ...t, id: t.id || "readme" }))} />
          </div>
          {!tab &&
            (readme ? (
              <div className="box">
                <Html className="boxbody md" html={markdownHtml(cb, cb.store.getDef(readme.hash)?.sourceText ?? "")} />
              </div>
            ) : (
              <div className="empty">{r.facts?.description ?? `${pkg} has no README.`}</div>
            ))}
          {tab === "code" && (
            <div className="box">
              {own.slice(0, 300).map((n) => (
                <DefRow key={n.path} row={{ ...n, path: n.path }} />
              ))}
              {!own.length && <div className="empty">Its code isn't here yet.</div>}
            </div>
          )}
          {tab === "versions" && (
            <div className="box">
              {shown.map((v) => (
                <div className="vrow" key={v.version}>
                  <a className="mono" href={libraryHref(who, pkg, v.version)}>
                    <b>{v.version}</b>
                  </a>
                  <span>
                    <Level level={v.facts?.level} />
                  </span>
                  <span className={yanks.has(v.uri) ? "bad" : v.state === "withdrawn" ? "muted" : ""}>
                    {yanks.has(v.uri)
                      ? `yanked: ${yanks.get(v.uri)!.body.split("\n")[0]}`
                      : v.state === "withdrawn"
                        ? "withdrawn"
                        : (v.facts?.change ?? (v.facts?.after ? "" : "first release"))}
                  </span>
                  <span className="muted">
                    {v.facts?.after && <a href={changesHref(who, pkg, v.facts.after, v.version)}>what changed</a>}{" "}
                    {v.createdAt.slice(0, 10)}
                  </span>
                </div>
              ))}
            </div>
          )}
          {tab === "dependents" && (
            <>
              <div className="box">
                <div className="boxhead">
                  <b>Who uses which version</b>
                  <span className="muted">exactly, by the hashes their releases hold</span>
                </div>
                {perVersion.length > 0 && (
                  <div className="boxbody bars">
                    {perVersion.map(({ v, n }) => (
                      <div key={v.version}>
                        <span className="mono">{v.version}</span>
                        <Meter
                          className="meter"
                          value={n}
                          maxValue={most}
                          aria-label={`Using ${v.version}`}
                          valueLabel={`${n}`}
                        >
                          <span className="fill" style={{ width: `${(100 * n) / most}%` }} />
                        </Meter>
                        <span>{n}</span>
                      </div>
                    ))}
                  </div>
                )}
                {dependents.map(({ v, d }) => {
                  const w = people.get(d.did) ?? { did: d.did };
                  return (
                    <div className="lib" key={d.uri}>
                      <div>
                        <a className="name mono" href={libraryHref(w, d.package, d.version)}>
                          {said(w)}/{d.package}
                        </a>{" "}
                        <span className="muted">
                          {d.version} uses {v.version}
                        </span>
                      </div>
                    </div>
                  );
                })}
                {!dependents.length && <div className="empty">Nothing the registry has uses it yet.</div>}
              </div>
            </>
          )}
          {tab === "trust" && (
            <>
              <div className="box">
              <div className="boxhead">
                <b>What tcm checked</b>
                <span className="muted">from the code, not from what anyone says</span>
              </div>
              <div className="boxbody checks">
                {r.state === "mirrored" || r.state === "withdrawn" ? (
                  <>
                    <div>✓ Every definition's hash checked as it arrived{r.from ? `, from ${r.from}` : ""}.</div>
                    <div>
                      ✓ Released by {said(who)}: it matches a record signed in their repository
                      {r.verifiedAt ? `, checked ${ago(r.verifiedAt.getTime())}` : ""}.
                    </div>
                    {r.facts && <div>✓ It {r.facts.reaches.replace(/^reaches/, "reaches")}.</div>}
                  </>
                ) : (
                  <div>{r.state === "pending" ? "Not checked yet: it's being mirrored." : `✗ ${r.reason}`}</div>
                )}
              </div>
              <div className="boxhead topline">
                <b>What others say</b>
              </div>
              {said_.filter((a) => a.kind !== "yank").length ? (
                said_
                  .filter((a) => a.kind !== "yank")
                  .map((a) => {
                    const w = people.get(a.did) ?? { did: a.did };
                    return (
                      <div className="lib" key={a.uri}>
                        <div className="who">
                          <Initial who={w} size="sm" />
                          <a href={whoHref(w)}>{said(w)}</a>{" "}
                          <span className="muted">{a.kind === "review" ? "reviewed it" : `an advisory (${a.severity})`}</span>
                        </div>
                        <div className="stat">{ago(Date.parse(a.createdAt))}</div>
                        <div className="desc">{a.body}</div>
                      </div>
                    );
                  })
              ) : (
                <div className="empty">No reviews yet: <code>tcm lib attest {`@${who.handle ?? who.did}/${pkg}@${r.version}`} review -m …</code> writes one.</div>
              )}
              </div>
            </>
          )}
        </div>
        <div className="side">
          <div className="sect">
            <h4>Add it</h4>
            <div className="copy">
              <code>{add}</code>
              <CopyButton text={add} label="Copy" />
            </div>
            {byHash && (
              <>
                <div className="muted copynote">or by hash, from any source:</div>
                <div className="copy">
                  <code title={byHash}>{byHash}</code>
                  <CopyButton text={byHash} label="Copy" />
                </div>
              </>
            )}
          </div>
          {p && (
            <div className="sect">
              <h4>Where it runs</h4>
              <PlaceBar places={p} />
              <div className="legendrow">
                <Legend places={p} />
              </div>
            </div>
          )}
          {r.facts && (
            <div className="sect">
              <h4>What it reaches</h4>
              <div className="says">
                <Reaches facts={r.facts} />.
              </div>
            </div>
          )}
          <div className="sect">
            <h4>Sources</h4>
            {r.sources.map((src, i) => (
              <div className="row" key={src}>
                <span
                  className={src === r.from ? "ok" : "muted"}
                  title={src === r.from ? "the registry fetched it from here" : "not asked: another answered first"}
                >
                  ●
                </span>
                <span className="mono">{host(src)}</span>
                <span className="muted right">{i === 0 ? "author" : "mirror"}</span>
              </div>
            ))}
          </div>
          {heldAs.length > 0 && (
            <div className="sect">
              <h4>Its libraries</h4>
              {heldAs.map(({ u, r: x }) => {
                const w = x && (people.get(x.did) ?? { did: x.did });
                return (
                  <div className="row" key={u.at}>
                    {x && w ? (
                      <>
                        <a className="mono" href={libraryHref(w, x.package, x.version)}>
                          {said(w)}/{x.package}
                        </a>
                        <span className="mono muted">{x.version}</span>
                      </>
                    ) : (
                      <>
                        <a className="mono" href={codeHref(`${r.mount}.${u.at}`)}>
                          {leafOf(u.at)}
                        </a>
                        <span className="muted">by hash</span>
                      </>
                    )}
                  </div>
                );
              })}
            </div>
          )}
        </div>
      </div>
    </RegistryFrame>
  );
}

uses

used by