g1t/apps/web/app/routes/workspace/package.tsx

344 lines14,806 bytesCodeBlame
1import { BookOpen, Box, Lock, Package, Trash2 } from "lucide-react";
2import { Form, Link, data, redirect, useNavigation } from "react-router";
3
4import { ECOSYSTEMS, type Ecosystem, type PackageVersion } from "@g1t/contracts";
5
6import type { Route } from "./+types/package";
7import { Markdown } from "../../components/markdown";
8import { ConfirmDialog } from "../../components/repo-lifecycle";
9import { Button, CopyLine, ErrorText, TimeAgo } from "../../components/ui";
10import { Badge } from "../../components/ui/badge";
11import { page } from "../../lib/meta";
12import { ECOSYSTEM_LABEL, formatBytes, installCommands, shortDigest } from "../../lib/packages";
13import { packages } from "../../lib/services.server";
14import { assertSameOrigin, getViewer, requireUser } from "../../lib/session.server";
15
16function ecosystemOf(value: string | undefined): Ecosystem {
17 if (value && (ECOSYSTEMS as readonly string[]).includes(value)) return value as Ecosystem;
18 throw data(null, { status: 404 });
19}
20
21export function meta({ params, ...args }: Route.MetaArgs) {
22 return page(args, { title: `${params["*"]} · Packages · ${params.owner} · g1t` });
23}
24
25export async function loader({ params, context }: Route.LoaderArgs) {
26 const viewer = getViewer(context);
27 const ecosystem = ecosystemOf(params.ecosystem);
28 const name = params["*"] ?? "";
29 const found = await packages.get(params.owner, ecosystem, name, viewer);
30 // Not found and not allowed look the same.
31 if (!found.ok) throw data(null, { status: 404 });
32 return { detail: found.value, username: viewer?.username ?? "you" };
33}
34
35type Outcome = { error: string | null; message: string | null };
36
37export async function action({ request, params, context }: Route.ActionArgs): Promise<Outcome | Response> {
38 assertSameOrigin(request);
39 const user = requireUser(context, request);
40 const ecosystem = ecosystemOf(params.ecosystem);
41 const name = params["*"] ?? "";
42 const form = await request.formData();
43 const intent = String(form.get("intent") ?? "");
44 const fail = (message: string): Outcome => ({ error: message, message: null });
45 if (intent === "delete-version") {
46 const version = String(form.get("version") ?? "");
47 const done = await packages.deleteVersion(user, params.owner, ecosystem, name, version, "web");
48 return done.ok ? { error: null, message: `Deleted ${shortDigest(version)} and its tags.` } : fail(done.error.message);
49 }
50 if (intent === "delete-package") {
51 const done = await packages.deletePackage(user, params.owner, ecosystem, name, "web");
52 if (!done.ok) return fail(done.error.message);
53 return redirect(`/${params.owner}/-/packages`);
54 }
55 if (intent === "visibility") {
56 const visibility = form.get("visibility") === "public" ? "public" : "private";
57 const done = await packages.set(user, params.owner, ecosystem, name, { visibility }, "web");
58 return done.ok ? { error: null, message: `It is ${visibility} now.` } : fail(done.error.message);
59 }
60 if (intent === "link") {
61 const repo = String(form.get("repo") ?? "").trim();
62 const done = repo
63 ? await packages.set(user, params.owner, ecosystem, name, { link: repo }, "web")
64 : await packages.set(user, params.owner, ecosystem, name, { unlink: true }, "web");
65 return done.ok ? { error: null, message: repo ? `Linked to ${repo}.` : "Unlinked." } : fail(done.error.message);
66 }
67 return fail("That is not something this page does.");
68}
69
70export default function PackagePage({ loaderData, actionData }: Route.ComponentProps) {
71 const { detail, username } = loaderData;
72 const { package: pkg, versions, tags, permissions } = detail;
73 const outcome = actionData as Outcome | undefined;
74 const latest = tags.find((tag) => tag.tag === "latest")?.tag ?? tags[0]?.tag ?? null;
75 const commands = installCommands(pkg, latest, username);
76 // npm and Composer versions are numbers; images are digests and tags.
77 const npm = pkg.ecosystem !== "container";
78 // Composer's versions are the repository's tags and branches: they
79 // change in git, not here.
80 const fromGit = pkg.ecosystem === "composer";
81 // Signatures and attestations hang off the images they describe.
82 const images = versions.filter((version) => !version.subject);
83 const attached = (digest: string) => versions.filter((version) => version.subject === digest);
84 return (
85 <div className="space-y-8">
86 <header className="space-y-3">
87 <Link to={`/${pkg.workspace}/-/packages`} className="text-sm text-muted hover:text-fg">
88 Packages
89 </Link>
90 <div className="flex flex-wrap items-center gap-3">
91 <span className="text-faint">{pkg.visibility === "private" ? <Lock size={18} /> : <Package size={18} />}</span>
92 <h1 className="text-2xl font-semibold tracking-tight">{pkg.name}</h1>
93 <Badge>{ECOSYSTEM_LABEL[pkg.ecosystem]}</Badge>
94 <Badge>{pkg.visibility === "private" ? "Private" : "Public"}</Badge>
95 </div>
96 <p className="flex flex-wrap items-center gap-x-4 gap-y-1 text-sm text-muted tabular-nums">
97 {pkg.repo && (
98 <Link to={`/${pkg.repo.namespace}/${pkg.repo.name}`} className="inline-flex items-center gap-1 hover:text-fg">
99 <Box size={13} />
100 {pkg.repo.namespace}/{pkg.repo.name}
101 </Link>
102 )}
103 <span>{formatBytes(pkg.size)}</span>
104 <span>
105 {pkg.downloads.toLocaleString("en-US")}{" "}
106 {npm ? (pkg.downloads === 1 ? "download" : "downloads") : pkg.downloads === 1 ? "pull" : "pulls"}
107 </span>
108 <span>
109 Updated <TimeAgo at={pkg.updated_at} />
110 </span>
111 </p>
112 {pkg.description && <p className="max-w-2xl text-sm text-fg-soft">{pkg.description}</p>}
113 </header>
114
115 {outcome?.error && <ErrorText>{outcome.error}</ErrorText>}
116 {outcome?.message && <p className="text-sm text-accent">{outcome.message}</p>}
117
118 <section className="space-y-2">
119 <h2 className="text-sm font-semibold">{npm ? "Install it" : "Pull it"}</h2>
120 {commands.registry && <CopyLine prompt text={commands.registry} />}
121 {pkg.visibility === "private" && <CopyLine prompt text={commands.login} />}
122 <CopyLine prompt text={commands.install} />
123 {commands.registry && pkg.visibility === "private" && (
124 <p className="text-xs text-faint">
125 Put an{" "}
126 <Link to="/settings/tokens" className="text-muted hover:text-fg">
127 access token
128 </Link>{" "}
129 with <code className="font-mono">packages:read</code> in place of YOUR_TOKEN.
130 </p>
131 )}
132 </section>
133
134 {detail.readme && (
135 <section className="overflow-hidden rounded-xl border border-line">
136 <h2 className="flex items-center gap-2 border-b border-line bg-surface px-4 py-2.5 text-sm font-medium">
137 <BookOpen size={15} className="text-faint" />
138 README
139 </h2>
140 <div className="p-6">
141 <Markdown
142 source={detail.readme}
143 repo={pkg.repo ? { namespace: pkg.repo.namespace, name: pkg.repo.name } : undefined}
144 />
145 </div>
146 </section>
147 )}
148
149 <section className="space-y-3">
150 <h2 className="text-sm font-semibold">
151 Versions <span className="font-normal text-faint">{images.length}</span>
152 </h2>
153 {fromGit && (
154 <p className="text-xs text-faint">
155 Each tag of {pkg.repo ? `${pkg.repo.namespace}/${pkg.repo.name}` : "its repository"} that reads as a version, and each
156 branch as <code className="font-mono">dev-</code>, from its composer.json. Push a tag to publish one; delete it to take it away.
157 </p>
158 )}
159 {images.length === 0 ? (
160 <p className="text-sm text-muted">No versions are left.</p>
161 ) : (
162 <ul className="divide-y divide-line overflow-hidden rounded-xl border border-line bg-surface">
163 {images.map((version) => (
164 <VersionRow
165 key={version.id}
166 version={version}
167 attached={attached(version.digest)}
168 canDelete={permissions.delete && !fromGit}
169 npm={npm}
170 />
171 ))}
172 </ul>
173 )}
174 </section>
175
176 {permissions.admin && <Settings detail={detail} />}
177 </div>
178 );
179}
180
181function VersionRow({
182 version,
183 attached,
184 canDelete,
185 npm,
186}: {
187 version: PackageVersion;
188 attached: PackageVersion[];
189 canDelete: boolean;
190 npm: boolean;
191}) {
192 return (
193 <li className="flex flex-wrap items-start gap-x-4 gap-y-2 px-4 py-3">
194 <div className="min-w-0 grow space-y-1">
195 <div className="flex flex-wrap items-center gap-1.5">
196 {npm && <span className="font-mono text-sm font-medium">{version.version}</span>}
197 {npm ? (
198 version.tags.map((tag) => (
199 <Badge key={tag} tone={tag === "latest" ? "accent" : "neutral"} className="font-mono">
200 {tag}
201 </Badge>
202 ))
203 ) : version.tags.length > 0 ? (
204 version.tags.map((tag) => (
205 <Badge key={tag} tone={tag === "latest" ? "accent" : "neutral"} className="font-mono">
206 {tag}
207 </Badge>
208 ))
209 ) : (
210 <span className="text-xs text-faint">Untagged</span>
211 )}
212 {!npm && (
213 <code className="font-mono text-xs text-muted" title={version.digest}>
214 {shortDigest(version.digest)}
215 </code>
216 )}
217 {version.deprecated && (
218 <Badge tone="neutral" title={version.deprecated}>
219 Deprecated
220 </Badge>
221 )}
222 </div>
223 {version.deprecated && <p className="text-xs text-muted">{version.deprecated}</p>}
224 <p className="flex flex-wrap gap-x-3 text-xs text-faint tabular-nums">
225 <span>{formatBytes(version.size)}</span>
226 {version.platforms.length > 0 && <span>{version.platforms.join(", ")}</span>}
227 {attached.length > 0 && (
228 <span title={attached.map((a) => a.artifact_type ?? a.media_type ?? "artifact").join(", ")}>
229 {attached.length} attached ({attached.map((a) => artifactWord(a)).join(", ")})
230 </span>
231 )}
232 <span>
233 {version.published_by ? `${version.published_by} · ` : ""}
234 <TimeAgo at={version.published_at} />
235 </span>
236 </p>
237 </div>
238 {canDelete && (
239 <ConfirmDialog
240 intent="delete-version"
241 fields={{ version: npm ? version.version : version.digest }}
242 title={`Delete ${npm ? version.version : (version.tags[0] ?? shortDigest(version.digest))}?`}
243 description={
244 npm
245 ? "Anyone installing this version gets an error from then on."
246 : "Anyone pulling it by this tag or digest gets an error from then on."
247 }
248 submit="Delete version"
249 busy="Deleting…"
250 trigger={(open) => (
251 <button type="button" onClick={open} aria-label="Delete version" className="rounded-md p-1.5 text-faint hover:bg-raised hover:text-danger">
252 <Trash2 size={14} />
253 </button>
254 )}
255 >
256 <li>Its tags go with it.</li>
257 <li>Files no other version uses are removed within a day.</li>
258 </ConfirmDialog>
259 )}
260 </li>
261 );
262}
263
264/** "signature", "SBOM", "attestation", or what the artifact says it is. */
265function artifactWord(version: PackageVersion): string {
266 const type = version.artifact_type ?? version.media_type ?? "";
267 if (/signature|cosign|notary/i.test(type)) return "signature";
268 if (/spdx|cyclonedx|sbom/i.test(type)) return "SBOM";
269 if (/in-toto|attestation|provenance/i.test(type)) return "attestation";
270 return "artifact";
271}
272
273function Settings({ detail }: { detail: Route.ComponentProps["loaderData"]["detail"] }) {
274 const { package: pkg } = detail;
275 const busy = useNavigation().state !== "idle";
276 return (
277 <section className="space-y-4 rounded-xl border border-line bg-surface p-5">
278 <h2 className="text-sm font-semibold">Settings</h2>
279 {pkg.repo ? (
280 <p className="text-sm text-muted">
281 Linked to{" "}
282 <Link to={`/${pkg.repo.namespace}/${pkg.repo.name}`} className="text-fg-soft hover:text-fg">
283 {pkg.repo.namespace}/{pkg.repo.name}
284 </Link>
285 : it has the repository's visibility and roles.
286 </p>
287 ) : (
288 <Form method="post" className="flex flex-wrap items-center gap-2 text-sm">
289 <input type="hidden" name="intent" value="visibility" />
290 <span className="text-muted">Visibility</span>
291 <select
292 name="visibility"
293 defaultValue={pkg.visibility}
294 className="h-8 rounded-md border border-line bg-bg px-2 text-sm"
295 aria-label="Visibility"
296 >
297 <option value="private">Private: workspace members</option>
298 <option value="public">Public: anyone can pull</option>
299 </select>
300 <Button type="submit" variant="quiet" disabled={busy}>
301 Save
302 </Button>
303 </Form>
304 )}
305 <Form method="post" className="flex flex-wrap items-center gap-2 text-sm">
306 <input type="hidden" name="intent" value="link" />
307 <label className="text-muted" htmlFor="link-repo">
308 Repository
309 </label>
310 <input
311 id="link-repo"
312 name="repo"
313 defaultValue={pkg.repo?.name ?? ""}
314 placeholder="none"
315 className="h-8 w-56 rounded-md border border-line bg-bg px-2 font-mono text-sm placeholder:text-faint"
316 />
317 <Button type="submit" variant="quiet" disabled={busy}>
318 {pkg.repo ? "Change link" : "Link"}
319 </Button>
320 <span className="text-xs text-faint">Empty to unlink. A linked package takes the repository's access.</span>
321 </Form>
322 {detail.permissions.delete && (
323 <div className="border-t border-line pt-4">
324 <ConfirmDialog
325 intent="delete-package"
326 title={`Delete ${pkg.name}?`}
327 description="Every version and tag goes, and anyone pulling it gets an error."
328 confirm={pkg.name}
329 submit="Delete package"
330 busy="Deleting…"
331 trigger={(open) => (
332 <Button type="button" variant="danger" onClick={open}>
333 Delete package
334 </Button>
335 )}
336 >
337 <li>{detail.versions.length} versions and their tags.</li>
338 <li>The name can be pushed again afterwards.</li>
339 </ConfirmDialog>
340 </div>
341 )}
342 </section>
343 );
344}