Merge build/1411-web-import into main
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by oscabriel · committed by oscabriel · parents 7a90542, 81c99ad · Browse files · 22 files·+1774 added−33 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
22 files+1774 added−33 removed
- tests:+641 added−24 removed
- other:+1133 added−9 removed
Provenance
- Commit
059c75c- Tree
f0b5ae2- Author
oscabriel <oscarhernandeziv@gmail.com>- Committer
oscabriel <oscarhernandeziv@gmail.com>- Parent 1
7a90542- Parent 2
81c99ad
22 files changed+1774 added−33 removed
added:apps/web/e2e/import.e2e.ts+116 added
1+/**2+ * A web import, as a browser does it: signed in, `/import?url=<repo>`3+ * fills the form (owner and name from the URL), Import runs it, the page4+ * says "Importing…" while the platform clones, and lands on the project's5+ * page, which names where it was imported from. Saved as6+ * `e2e/out/import.png`.7+ *8+ * It runs only when `WEB_IMPORT_URL` names a tiny public repo to import9+ * (an HTTPS clone URL) and `WEB_URL` a web's origin, and is skipped10+ * otherwise. It signs in with `WEB_SESSION`, a session token for the11+ * stage, or, without one, through the dev world's own `/auth/dev` as12+ * `WEB_IMPORT_AS` (oscabriel unless given). `WEB_IMPORT_NAME` names the13+ * project instead of the URL's last segment, so a second run does not meet14+ * `ProjectExists`. It writes: each run makes a project.15+ */16+import { expect, test } from "@playwright/test";17+import { Config, Effect, Option, Redacted } from "effect";18+19+const settings = Effect.runSync(20+ Effect.gen(function* () {21+ return {22+ as: yield* Config.NonEmptyString("WEB_IMPORT_AS").pipe(23+ Config.withDefault("oscabriel")24+ ),25+ name: yield* Config.option(Config.NonEmptyString("WEB_IMPORT_NAME")),26+ repo: yield* Config.option(Config.NonEmptyString("WEB_IMPORT_URL")),27+ session: yield* Config.option(Config.Redacted("WEB_SESSION")),28+ web: Option.map(29+ yield* Config.option(Config.NonEmptyString("WEB_URL")),30+ (url) => url.replace(/\/+$/u, "")31+ ),32+ };33+ })34+);35+36+/** Where the screenshot goes: `e2e/out/import.png`. */37+const out = decodeURIComponent(new URL("out/", import.meta.url).pathname);38+39+/** An import clones the repo: up to half a minute, and some margin. */40+const IMPORTING = 90_000;41+42+test.describe("a web import", () => {43+ test.skip(44+ Option.isNone(settings.repo) || Option.isNone(settings.web),45+ "WEB_IMPORT_URL and WEB_URL are not both set: name a tiny public repo and a web's origin to run this check"46+ );47+48+ test.setTimeout(IMPORTING + 30_000);49+50+ test("imports a public repo from /import and lands on its project", ({51+ context,52+ page,53+ }) =>54+ Effect.runPromise(55+ Effect.gen(function* () {56+ const web = Option.getOrElse(settings.web, () => "");57+ const repo = Option.getOrElse(settings.repo, () => "");58+59+ yield* Option.match(settings.session, {60+ onNone: () =>61+ Effect.promise(() =>62+ page.goto(`${web}/auth/dev?handle=${settings.as}`)63+ ),64+ onSome: (token) =>65+ Effect.promise(() =>66+ context.addCookies([67+ {68+ name: "__Host-session",69+ secure: true,70+ url: web,71+ value: Redacted.value(token),72+ },73+ ])74+ ),75+ });76+77+ yield* Effect.promise(() =>78+ page.goto(`${web}/import?${new URLSearchParams({ url: repo })}`)79+ );80+81+ const form = page.getByRole("form", { name: "Import a repo" });82+83+ yield* Effect.promise(() =>84+ expect(form.getByLabel("Repo URL")).toHaveValue(repo)85+ );86+87+ const { name } = settings;88+89+ if (Option.isSome(name)) {90+ yield* Effect.promise(() => form.getByLabel("Name").fill(name.value));91+ }92+93+ yield* Effect.promise(() =>94+ form.getByRole("button", { name: "Import" }).click()95+ );96+97+ yield* Effect.promise(() =>98+ expect(form.getByRole("button", { name: "Importing…" })).toBeVisible()99+ );100+101+ yield* Effect.promise(() =>102+ page.waitForURL((url) => url.pathname !== "/import", {103+ timeout: IMPORTING,104+ })105+ );106+107+ yield* Effect.promise(() =>108+ expect(page.getByText(repo).first()).toBeVisible()109+ );110+111+ yield* Effect.promise(() =>112+ page.screenshot({ fullPage: true, path: `${out}import.png` })113+ );114+ })115+ ));116+});added:apps/web/src/client/import.ts+41 added
1234567891011121314151617181920212223242526272829303132333435363738394041/** * The import form's write. `importAtom` sends `initProject` with `import`: * the platform clones the public repo and makes the project, with the * caller as its decider, which takes up to half a minute. The list of * projects changes, and so does the project's own key, so both read again. */import type { InitProject } from "@repo/protocol/contracts";import type { ProjectName } from "@repo/protocol/ids";import { Effect, Option } from "effect";import { AsyncResult, Reactivity } from "effect/reactivity";
import { ContractsClient } from "../surfaces.ts";import { keys } from "./keys.ts";
/** * The project the last import made, once it answered. While a later * import is on its way, or after it was refused, the atom still holds an * earlier one's project, which names none here: the form never moves to it. */export const importMade = ( result: AsyncResult.AsyncResult< typeof InitProject.successSchema.Type, unknown >): Option.Option<ProjectName> => AsyncResult.isSuccess(result) && !result.waiting ? Option.some(result.value.project) : Option.none();
/** Import a public repo: `initProject`'s payload, answered with the project. */export const importAtom = ContractsClient.runtime.fn< typeof InitProject.payloadSchema.Type>()( Effect.fnUntraced(function* (input) { const client = yield* ContractsClient;
return yield* client("initProject", input).pipe( Reactivity.mutation([...keys.front(), ...keys.project(input.project)]) ); }));modified:apps/web/src/features/home/home-page.tsx+6 added-1 removed
29 unmodified lines30 answerPath,31 ASKS_PATH,32 askPath,33 HOME_PATH,34+ IMPORT_PATH,35 personPath,36 } from "../shared/paths.ts";37 import { UnreachableNotice } from "../shared/pending.tsx";38 import {297 unmodified lines336 <AskList asks={asks} />337 </RowGroup>338 );339 339-/** Who is signed in, and the way to their record. */340+/** Who is signed in, the way to their record, and the way to import a repo. */341 const Record = ({ handle }: { readonly handle: Handle }) => (342 <>343 Signed in as <HandleLink handle={handle} />.{" "}344 <AppLink className={LINK} to={personPath(handle)}>345 Your record346 </AppLink>347+ {" · "}348+ <AppLink className={LINK} to={IMPORT_PATH}>349+ Import a repo350+ </AppLink>351 </>352 );353 354 const SignedIn = ({52 unmodified linesadded:apps/web/src/features/import/client-owner.tsx+66 added
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566/** * The owner select, drawn in the browser only. The server renders its * stand-in: the trigger as it will look, holding the choice in sight and * in the form (a hidden input), never a native `<select>`; after * hydration the browser loads the kit's select over it * (`owner-select.tsx`), whose trigger takes the same `TRIGGER`. * `import.meta.env.SSR` is `true` in the Worker's build, so the dynamic * import below is dead code there and the Worker bundles none of it. */import type { Owner } from "@repo/protocol/ids";import { ClientOnly } from "@tanstack/react-router";import { ChevronDown } from "lucide-react";import { lazy, Suspense } from "react";
export interface OwnerSelectProps { /** The owners to choose from, the default first. */ readonly choices: readonly Owner[]; readonly labelledBy: string; readonly describedBy: string; readonly onChange: (value: Owner) => void; readonly value: Owner | undefined;}
/** The trigger's size, the kit's select and the stand-in alike. */export const TRIGGER = "tablet:text-ui tablet:h-9 h-11 w-full max-w-sm text-base";
const SelectLater = import.meta.env.SSR ? undefined : lazy(() => import("./owner-select.tsx"));
/** The select's place before it is drawn: its trigger, showing the choice. */const StandIn = ({ describedBy, labelledBy, value }: OwnerSelectProps) => ( <> <button aria-describedby={describedBy} aria-labelledby={labelledBy} className={`border-input flex items-center justify-between gap-1.5 border bg-transparent py-2 pr-2 pl-2.5 ${TRIGGER}`} data-slot="select-trigger" disabled type="button" > {value} <ChevronDown aria-hidden="true" className="text-muted-foreground size-4" strokeWidth={1.75} /> </button> <input name="owner" type="hidden" value={value ?? ""} /> </>);
export const ClientOwnerSelect = (props: OwnerSelectProps) => { const fallback = <StandIn {...props} />;
return SelectLater === undefined ? ( fallback ) : ( <ClientOnly fallback={fallback}> <Suspense fallback={fallback}> <SelectLater {...props} /> </Suspense> </ClientOnly> );};added:apps/web/src/features/import/import-form.tsx+436 added
1+/**2+ * The import form: a signed-in person pastes a public repo's HTTPS URL,3+ * may name a branch, picks the owner and the name, and presses Import. The4+ * owner and the name follow the URL until the person changes them: the5+ * URL's source namespace (`github.com/pallets`) when its host is one the6+ * platform knows, else their handle; the URL's last segment as the name.7+ * At a source namespace's address the owner is the address's, fixed.8+ * Signed out, it says what would be imported and links to sign-in, coming9+ * back to `here`. Props in, markup out: the route reads who is signed in,10+ * sends the payload, and goes to the project once it is made.11+ *12+ * Nothing is imported until Import is pressed; nothing here asks a host13+ * anything.14+ */15+import { Brand } from "@repo/brand";16+import type {17+ Handle,18+ Owner,19+ ShortName,20+ SourceNamespace,21+} from "@repo/protocol/ids";22+import { Option } from "effect";23+import { LogIn } from "lucide-react";24+import { useId, useState } from "react";25+import type { ReactNode } from "react";26+27+import { Button } from "../../components/ui/button.tsx";28+import { Input } from "../../components/ui/input.tsx";29+import { Spinner } from "../../components/ui/spinner.tsx";30+import { signInHref } from "../auth/session-slot.tsx";31+import { CommandLine } from "../shared/command.tsx";32+import { ClientOwnerSelect } from "./client-owner.tsx";33+import {34+ importPayload,35+ importSourceOf,36+ ownerChoices,37+ ownerOfNamespace,38+ prefillFrom,39+} from "./prefill.ts";40+import type { ImportPayload } from "./prefill.ts";41+42+/** What the form starts with: a URL, and the owner and name it gives. */43+export interface ImportPrefill {44+ readonly url: string;45+ readonly owner?: SourceNamespace | undefined;46+ readonly name?: ShortName | undefined;47+}48+49+/** Who is importing, and what became of the last press. */50+export interface Importer {51+ /** The handle signed in in this browser; none signed out. */52+ readonly handle: Option.Option<Handle>;53+ /** Whether the browser is still learning who is signed in. */54+ readonly checking?: boolean | undefined;55+ /** Whether an import is on its way: the button waits. */56+ readonly busy?: boolean | undefined;57+ /** Sends the payload; the route goes to the project once it is made. */58+ readonly onImport?: ((payload: ImportPayload) => void) | undefined;59+ /** What the last import came back with, when it was refused. */60+ readonly refusal?: ReactNode | undefined;61+}62+63+export interface ImportFormProps extends Importer {64+ readonly prefill?: ImportPrefill | undefined;65+ /** The owner the address fixes, at a source namespace's address. */66+ readonly fixedOwner?: SourceNamespace | undefined;67+ /** The page's own address, where sign-in comes back to. */68+ readonly here: string;69+}70+71+/** The import as a command, for a reader in a terminal. */72+export const importCommand = (project = "<owner>/<name>", url = "<url>") =>73+ `${Brand.cli} init --project ${project} --import ${url}`;74+75+const LINK = "decoration-rule font-medium underline hover:decoration-current";76+77+/** A field's label and the words under it. */78+const LABEL = "text-ui font-medium";79+80+const HINT = "text-label text-muted-foreground font-normal";81+82+/**83+ * A text field in mono: 16 px on a phone, so it does not zoom on focus, and84+ * without ligatures, as code shows what was typed (`://` stays three).85+ */86+const MONO_FIELD =87+ "tablet:h-9 tablet:text-mono h-11 font-mono text-base [font-feature-settings:'calt'_0,'liga'_0]";88+89+/** What Import says, by where the form stands: why it waits, or what it does. */90+const IMPORT_WORDS = {91+ busy: "Importing…",92+ noName: "Name the project",93+ noOwner: "No owner you may import under",94+ noUrl: "Paste a repo's URL first",95+ ready: "Import",96+} as const;97+98+type FormState = keyof typeof IMPORT_WORDS;99+100+/** Where the form stands: importing, waiting on a field, or ready. */101+const formState = ({102+ branch,103+ busy,104+ owner,105+ payload,106+ url,107+}: {108+ readonly busy: boolean;109+ readonly owner: Owner | undefined;110+ readonly payload: Option.Option<ImportPayload>;111+ readonly url: string;112+ readonly branch: string;113+}): FormState => {114+ if (busy) {115+ return "busy";116+ }117+118+ if (Option.isNone(importSourceOf({ branch, url }))) {119+ return "noUrl";120+ }121+122+ if (owner === undefined) {123+ return "noOwner";124+ }125+126+ return Option.isSome(payload) ? "ready" : "noName";127+};128+129+const SignInToImport = ({130+ fixedOwner,131+ here,132+ prefill,133+}: Pick<ImportFormProps, "fixedOwner" | "here" | "prefill">) => {134+ const name = prefill?.name;135+136+ const project =137+ fixedOwner === undefined || name === undefined138+ ? undefined139+ : `${fixedOwner}/${name}`;140+141+ return (142+ <section143+ aria-label="Sign in to import"144+ className="flex max-w-[70ch] flex-col items-start gap-4"145+ >146+ {prefill === undefined || prefill.url === "" ? null : (147+ <dl className="border-rule flex w-full flex-col border-y">148+ <div className="flex flex-col gap-0.5 py-2.5">149+ <dt className={HINT}>Repo URL</dt>150+ <dd className="text-mono font-mono [overflow-wrap:anywhere]">151+ <code>{prefill.url}</code>152+ </dd>153+ </div>154+ {project === undefined ? null : (155+ <div className="border-rule flex flex-col gap-0.5 border-t py-2.5">156+ <dt className={HINT}>Project</dt>157+ <dd className="text-mono font-mono [overflow-wrap:anywhere]">158+ <code>{project}</code>159+ </dd>160+ </div>161+ )}162+ </dl>163+ )}164+ <p className="text-ui flex items-start gap-2">165+ <LogIn166+ aria-hidden="true"167+ className="mt-0.5 size-4 shrink-0"168+ strokeWidth={1.75}169+ />170+ <span>171+ Importing is for signed-in people.{" "}172+ <a className={LINK} href={signInHref(here)}>173+ Sign in174+ </a>{" "}175+ to import it here, or import from a terminal:176+ </span>177+ </p>178+ <CommandLine179+ command={importCommand(180+ project,181+ prefill === undefined || prefill.url === "" ? undefined : prefill.url182+ )}183+ />184+ </section>185+ );186+};187+188+/** The owner, fixed by the address: in sight, and in the form. */189+const FixedOwner = ({190+ hintId,191+ owner,192+}: {193+ readonly hintId: string;194+ readonly owner: SourceNamespace;195+}) => (196+ <>197+ <p aria-describedby={hintId} className="text-want font-medium">198+ {owner}199+ </p>200+ <input name="owner" type="hidden" value={owner} />201+ </>202+);203+204+/** What the hint under Owner says, by what may be chosen. */205+const ownerHint = (fixed: boolean, choices: readonly Owner[]) => {206+ if (fixed) {207+ return "The address names it: the project keeps its source's account.";208+ }209+210+ return choices.length > 1211+ ? "The URL's own account, or your handle."212+ : "Your handle: this URL's host is not one a project may be owned by.";213+};214+215+/** Under Name: the project's address once the name is one, else what a name is. */216+const NameHint = ({217+ payload,218+}: {219+ readonly payload: Option.Option<ImportPayload>;220+}) =>221+ Option.match(payload, {222+ onNone: () =>223+ "Lowercase letters and digits, joined by single dots, dashes or underscores.",224+ onSome: ({ project }) => (225+ <>226+ The project's address:{" "}227+ <code className="text-mono text-foreground font-mono [overflow-wrap:anywhere]">228+ /{project}229+ </code>230+ </>231+ ),232+ });233+234+const Form = ({235+ busy = false,236+ fixedOwner,237+ handle,238+ onImport,239+ prefill,240+ refusal,241+}: Pick<242+ ImportFormProps,243+ "busy" | "fixedOwner" | "handle" | "onImport" | "prefill" | "refusal"244+>) => {245+ const id = useId();246+ const [url, setUrl] = useState(prefill?.url ?? "");247+ const [branch, setBranch] = useState("");248+ const [chosen, setChosen] = useState<string | undefined>(prefill?.owner);249+ const [typed, setTyped] = useState<string | undefined>(prefill?.name);250+251+ const choices =252+ fixedOwner === undefined253+ ? ownerChoices(handle, url)254+ : Option.toArray(ownerOfNamespace(fixedOwner));255+256+ const owner = choices.find((choice) => choice === chosen) ?? choices[0];257+258+ const name: string =259+ typed ?? Option.getOrElse(prefillFrom(url).name, () => "");260+261+ const payload =262+ owner === undefined263+ ? Option.none()264+ : importPayload({ branch, name, owner, url });265+266+ const state = formState({ branch, busy, owner, payload, url });267+268+ return (269+ <form270+ aria-label="Import a repo"271+ className="flex max-w-[70ch] flex-col gap-6"272+ data-import=""273+ onSubmit={(event) => {274+ event.preventDefault();275+276+ if (!busy && Option.isSome(payload)) {277+ onImport?.(payload.value);278+ }279+ }}280+ >281+ <div className="flex flex-col gap-1.5">282+ <label className={LABEL} htmlFor={`${id}-url`}>283+ Repo URL284+ </label>285+ <Input286+ aria-describedby={`${id}-url-hint`}287+ autoCapitalize="off"288+ autoComplete="off"289+ className={MONO_FIELD}290+ id={`${id}-url`}291+ inputMode="url"292+ name="url"293+ onChange={(event) => {294+ setUrl(event.target.value);295+ }}296+ placeholder="https://github.com/pallets/click"297+ // At a source namespace's address the URL is the address's own.298+ readOnly={busy || fixedOwner !== undefined}299+ required300+ spellCheck={false}301+ type="url"302+ value={url}303+ />304+ <p className={HINT} id={`${id}-url-hint`}>305+ {fixedOwner === undefined306+ ? "Any public repo over HTTPS: GitHub, GitLab, Codeberg, Bitbucket or another host."307+ : "Rebuilt from this page's address."}308+ </p>309+ </div>310+311+ <div className="flex flex-col gap-1.5">312+ <label className={LABEL} htmlFor={`${id}-branch`}>313+ Branch <span className={HINT}>(optional)</span>314+ </label>315+ <Input316+ aria-describedby={`${id}-branch-hint`}317+ autoCapitalize="off"318+ autoComplete="off"319+ className={`${MONO_FIELD} max-w-sm`}320+ id={`${id}-branch`}321+ name="branch"322+ onChange={(event) => {323+ setBranch(event.target.value);324+ }}325+ readOnly={busy}326+ spellCheck={false}327+ value={branch}328+ />329+ <p className={HINT} id={`${id}-branch-hint`}>330+ Left empty, the repo's default branch.331+ </p>332+ </div>333+334+ <div className="flex flex-col gap-1.5">335+ <span className={LABEL} id={`${id}-owner`}>336+ Owner337+ </span>338+ {fixedOwner === undefined ? (339+ <ClientOwnerSelect340+ choices={choices}341+ describedBy={`${id}-owner-hint`}342+ labelledBy={`${id}-owner`}343+ onChange={setChosen}344+ value={owner}345+ />346+ ) : (347+ <FixedOwner hintId={`${id}-owner-hint`} owner={fixedOwner} />348+ )}349+ <p className={HINT} id={`${id}-owner-hint`}>350+ {ownerHint(fixedOwner !== undefined, choices)}351+ </p>352+ </div>353+354+ <div className="flex flex-col gap-1.5">355+ <label className={LABEL} htmlFor={`${id}-name`}>356+ Name357+ </label>358+ <Input359+ aria-describedby={`${id}-name-hint`}360+ autoCapitalize="off"361+ autoComplete="off"362+ className={`${MONO_FIELD} max-w-sm`}363+ id={`${id}-name`}364+ name="name"365+ onChange={(event) => {366+ setTyped(event.target.value);367+ }}368+ readOnly={busy}369+ required370+ spellCheck={false}371+ value={name}372+ />373+ <p className={HINT} id={`${id}-name-hint`}>374+ <NameHint payload={payload} />375+ </p>376+ </div>377+378+ {refusal}379+380+ <div className="flex flex-col gap-2">381+ <Button382+ // Waiting for a URL or a name, it says so at full strength, dashed383+ // like any field still to fill, rather than sitting grey.384+ className={`tablet:h-9 tablet:w-fit h-11 w-full min-w-28 px-4 ${state === "ready" || state === "busy" ? "" : "text-muted-foreground border-dashed disabled:opacity-100"}`}385+ data-state={state}386+ disabled={state !== "ready"}387+ type="submit"388+ variant={389+ state === "ready" || state === "busy" ? "default" : "outline"390+ }391+ >392+ {busy ? <Spinner /> : null}393+ {IMPORT_WORDS[state]}394+ </Button>395+ <output aria-live="polite" className={HINT}>396+ {busy397+ ? "The platform is cloning the repo; an import takes up to half a minute. Stay on this page."398+ : null}399+ </output>400+ </div>401+ </form>402+ );403+};404+405+/** The form, the way to sign in, or the wait while the browser learns who is signed in. */406+export const ImportForm = ({407+ busy,408+ checking = false,409+ fixedOwner,410+ handle,411+ here,412+ onImport,413+ prefill,414+ refusal,415+}: ImportFormProps): ReactNode => {416+ if (checking) {417+ return (418+ <output className="text-ui text-muted-foreground block">419+ Checking who is signed in420+ </output>421+ );422+ }423+424+ return Option.isSome(handle) ? (425+ <Form426+ busy={busy}427+ fixedOwner={fixedOwner}428+ handle={handle}429+ onImport={onImport}430+ prefill={prefill}431+ refusal={refusal}432+ />433+ ) : (434+ <SignInToImport fixedOwner={fixedOwner} here={here} prefill={prefill} />435+ );436+};added:apps/web/src/features/import/import-offer.tsx+62 added
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162/** * The import a source namespace's address offers when nobody has made the * project (`/github.com/pallets/click`): the form prefilled with the URL * the address rebuilds (read-only), the owner fixed to the namespace, and * the name; signed out, the way to sign in. It never imports on its own. * The route draws it in place of the not-found when `offerFor` names the * address's project. Props in, markup out. */import { isSourceNamespace, ownerOf, ProjectName, shortNameOf,} from "@repo/protocol/ids";import { Option, Schema } from "effect";
import { Workspace } from "../shared/shell/workspace.tsx";import { ImportForm } from "./import-form.tsx";import type { Importer } from "./import-form.tsx";import { sourceUrlOf } from "./prefill.ts";
const decodeProject = Schema.decodeUnknownOption(ProjectName);
/** * The project an address that names none offers to import: its name, when * its owner is a source namespace; none for a person's address and for * one that names no possible project. */export const offerFor = (name: string): Option.Option<ProjectName> => Option.filter(decodeProject(name), (project) => isSourceNamespace(ownerOf(project)) );
export const ImportOffer = ({ importer, project,}: { readonly project: ProjectName; readonly importer: Importer;}) => { const owner = ownerOf(project); const fixedOwner = isSourceNamespace(owner) ? owner : undefined;
return ( <Workspace crumbs={[{ label: project }]} meta={`Nobody has imported ${project} yet. Import it, and you become its decider.`} title="Not imported yet" > <ImportForm {...importer} fixedOwner={fixedOwner} here={`/${project}`} prefill={{ name: shortNameOf(project), owner: fixedOwner, url: sourceUrlOf(project), }} /> </Workspace> );};added:apps/web/src/features/import/import-page.tsx+66 added
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566/** * `/import`: the import form under the page's head, and beside it what an * import does and the same import as a command. A URL in the address * (`?url=`) fills the form. Props in, markup out: the route reads who is * signed in, sends the payload and goes to the project once it is made. */import { CommandLine } from "../shared/command.tsx";import { FactBlock } from "../shared/facts.tsx";import { Workspace } from "../shared/shell/workspace.tsx";import { ImportForm, importCommand } from "./import-form.tsx";import type { Importer } from "./import-form.tsx";
/** What an import does, and the same import from a terminal. */export const ImportFacts = () => ( <> <FactBlock label="What an import does"> <ul className="text-ui flex list-disc flex-col gap-1.5 pl-4"> <li> The platform clones the repo once, over HTTPS. Later pushes to the source do not follow it. </li> <li>You become the project's decider.</li> <li> A repo with no config folder takes its checks from its CI and its test command. </li> </ul> </FactBlock> <FactBlock label="From a terminal"> <CommandLine command={importCommand()} numbered /> </FactBlock> </>);
export const ImportView = ({ url = "", here, ...importer}: Importer & { /** The URL the address carries, to fill the form with. */ readonly url?: string | undefined; /** The page's own address, where sign-in comes back to. */ readonly here: string;}) => ( // Below the shell's width the form comes first, and what an import does // follows it, rather than standing between the reader and the form. <div className="contents [&_[data-facts=inline]]:hidden"> <Workspace crumbs={[{ label: "Import a repo" }]} facts={<ImportFacts />} factsHeading="Importing" meta="Any public git repo becomes a project here, with its history." title="Import a repo" > <ImportForm {...importer} here={here} // The name follows the URL until the person types one. prefill={url === "" ? undefined : { url }} /> <div className="shell:hidden border-rule flex flex-col border-t pt-4"> <ImportFacts /> </div> </Workspace> </div>);added:apps/web/src/features/import/owner-select.tsx+56 added
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556/** * The owner an import is made under, chosen with the kit's select: the * URL's source namespace first when its host is one the platform knows, * then the person's handle. Drawn in the browser only (`client-owner.tsx`): * Base UI's select and its positioning are the browser's to run, and the * Worker bundles none of them. */import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue,} from "../../components/ui/select.tsx";import { TRIGGER } from "./client-owner.tsx";import type { OwnerSelectProps } from "./client-owner.tsx";
export const OwnerSelect = ({ choices, describedBy, labelledBy, onChange, value,}: OwnerSelectProps) => ( <Select items={choices.map((choice) => ({ label: choice, value: choice }))} name="owner" onValueChange={(chosen) => { // The select hands back one of its items' values: find it, an owner. const owner = choices.find((choice) => choice === chosen);
if (owner !== undefined) { onChange(owner); } }} value={value} > <SelectTrigger aria-describedby={describedBy} aria-labelledby={labelledBy} className={TRIGGER} > <SelectValue /> </SelectTrigger> <SelectContent> {choices.map((choice) => ( <SelectItem key={choice} value={choice}> {choice} </SelectItem> ))} </SelectContent> </Select>);
// `React.lazy` takes a module's default export.export default OwnerSelect;added:apps/web/src/features/import/prefill.ts+111 added
1+/**2+ * What the import form reads from a pasted URL, and what it sends. Pure:3+ * no view, no transport. The owner is the URL's source namespace4+ * (`github.com/pallets`) when its host is one the platform knows; the name5+ * is the URL's last segment, without `.git`, lowercased. Nothing here asks6+ * a host anything: the platform clones the URL when Import is pressed.7+ */8+import type { InitProject } from "@repo/protocol/contracts";9+import { ImportSource } from "@repo/protocol/domain/policy";10+import {11+ Owner,12+ projectNameOf,13+ ShortName,14+ sourceNamespaceOf,15+} from "@repo/protocol/ids";16+import type { Handle, ProjectName, SourceNamespace } from "@repo/protocol/ids";17+import { Array, Option, Schema } from "effect";18+19+/** What `initProject` takes, from its one schema. */20+export type ImportPayload = typeof InitProject.payloadSchema.Type;21+22+/** What a URL prefills: the owner its host gives, and the name it ends in. */23+export interface Prefill {24+ readonly owner: Option.Option<SourceNamespace>;25+ readonly name: Option.Option<ShortName>;26+}27+28+// `https://<host>/<path>`: the path's last non-empty segment is the repo's.29+const HTTPS_URL = /^https:\/\/[^/?#\s]+\/(?<path>[^?#\s]+)$/u;30+31+const decodeShortName = Schema.decodeUnknownOption(ShortName);32+33+const decodeOwner = Schema.decodeUnknownOption(Owner);34+35+const decodeSource = Schema.decodeUnknownOption(ImportSource);36+37+/** The name a URL ends in, without `.git` and lowercased; none when it is no name. */38+const nameIn = (url: string): Option.Option<ShortName> => {39+ const path = HTTPS_URL.exec(url.trim())?.groups?.path ?? "";40+ const last = path.split("/").findLast((segment) => segment !== "") ?? "";41+42+ return decodeShortName(last.replace(/\.git$/u, "").toLowerCase());43+};44+45+/** The owner and the name `url` prefills. */46+export const prefillFrom = (url: string): Prefill => ({47+ name: nameIn(url),48+ owner: sourceNamespaceOf(url.trim()),49+});50+51+/** A source namespace as an owner: every one is (a host is never a reserved word). */52+export const ownerOfNamespace = (53+ namespace: SourceNamespace54+): Option.Option<Owner> => decodeOwner(namespace);55+56+/** A handle as an owner, lowercased; none for one no owner can spell. */57+export const ownerOfHandle = (handle: Handle): Option.Option<Owner> =>58+ decodeOwner(handle.toLowerCase());59+60+/**61+ * The owners a person may import `url` under: the URL's source namespace62+ * first when its host is one the platform knows (the default then), and63+ * their own handle.64+ */65+export const ownerChoices = (66+ handle: Option.Option<Handle>,67+ url: string68+): readonly Owner[] =>69+ Array.dedupe([70+ ...Option.toArray(Option.flatMap(prefillFrom(url).owner, ownerOfNamespace)),71+ ...Option.toArray(Option.flatMap(handle, ownerOfHandle)),72+ ]);73+74+/**75+ * The URL a source namespace's project was imported from:76+ * `github.com/pallets/click` is `https://github.com/pallets/click`.77+ */78+export const sourceUrlOf = (project: ProjectName) => `https://${project}`;79+80+/**81+ * The source the form names, as `initProject` takes it: the URL and the82+ * branch trimmed, the branch only when named. None for a URL the contract83+ * would refuse (no public HTTPS URL).84+ */85+export const importSourceOf = (form: {86+ readonly url: string;87+ readonly branch: string;88+}): Option.Option<ImportSource> => {89+ const branch = form.branch.trim();90+ const url = form.url.trim();91+92+ return decodeSource(branch === "" ? { url } : { branch, url });93+};94+95+/**96+ * The form's fields as `initProject`'s payload: its source, and the97+ * project the owner and the name make. None when the contract would refuse98+ * the name or the URL before the platform ever read it.99+ */100+export const importPayload = (form: {101+ readonly url: string;102+ readonly branch: string;103+ readonly owner: Owner;104+ readonly name: string;105+}): Option.Option<ImportPayload> =>106+ Option.flatMap(importSourceOf(form), (source) =>107+ Option.map(decodeShortName(form.name.trim()), (short) => ({108+ import: source,109+ project: projectNameOf(form.owner, short),110+ }))111+ );added:apps/web/src/features/import/use-importer.tsx+81 added
1+/**2+ * The import form's wiring, for the two pages that draw it (`/import` and3+ * a source namespace's address nobody has made): who is signed in, read in4+ * the browser; `importAtom`, sent only when Import is pressed; the move to5+ * the project once it is made; and a refusal, drawn as the platform gave6+ * it, under the form.7+ */8+import { useAtom, useAtomValue } from "@effect/atom-react";9+import { ownerOf } from "@repo/protocol/ids";10+import type { ProjectName } from "@repo/protocol/ids";11+import { useLocation, useNavigate, useRouter } from "@tanstack/react-router";12+import { Option } from "effect";13+import { AsyncResult } from "effect/reactivity";14+import { useEffect, useState } from "react";15+16+import { importAtom, importMade } from "../../client/import.ts";17+import { hereOf } from "../auth/session-slot.tsx";18+import { whoAtom } from "../auth/who.ts";19+import { ProposalFailure } from "../proposal/failure.tsx";20+import type { Importer } from "./import-form.tsx";21+22+/**23+ * Where an import that made `made` goes from a page at `at`: nowhere when24+ * it is the project this address names (its page reads it again), else to25+ * the project's page.26+ */27+export const afterImport = (made: ProjectName, at?: ProjectName) =>28+ made === at29+ ? Option.none()30+ : Option.some({31+ params: { owner: ownerOf(made), project: made },32+ to: "/$owner/$project" as const,33+ });34+35+/**36+ * Who is importing and what became of the last press. `at` is the project37+ * this page's address names, if any: a project made there is read again38+ * where it stands; any other is gone to.39+ */40+export const useImporter = (at?: ProjectName): Importer => {41+ const navigate = useNavigate();42+ const router = useRouter();43+ const here = useLocation({ select: hereOf });44+ const who = useAtomValue(whoAtom);45+ const [imported, send] = useAtom(importAtom);46+ // Set once this page sends: a project the atom still holds from an47+ // earlier visit never moves the page.48+ const [sent, setSent] = useState(false);49+ const made = sent ? Option.getOrUndefined(importMade(imported)) : undefined;50+51+ useEffect(() => {52+ if (made === undefined) {53+ return;54+ }55+56+ Option.match(afterImport(made, at), {57+ // The loader read this address as no project: it reads it again.58+ onNone: () => {59+ void router.invalidate();60+ },61+ onSome: (to) => {62+ void navigate(to);63+ },64+ });65+ }, [at, made, navigate, router]);66+67+ return {68+ busy: imported.waiting,69+ checking: !AsyncResult.isSuccess(who),70+ handle: AsyncResult.isSuccess(who) ? who.value : Option.none(),71+ onImport: (payload) => {72+ setSent(true);73+ send(payload);74+ },75+ refusal: AsyncResult.isFailure(imported) ? (76+ <div aria-live="polite">77+ <ProposalFailure cause={imported.cause} doing="import it" here={here} />78+ </div>79+ ) : undefined,80+ };81+};modified:apps/web/src/features/landing/landing-page.tsx+5 added-1 removed
16 unmodified lines17 import { SkipLink } from "../shared/layout.tsx";18 import { AppLink } from "../shared/link.tsx";19 import {20 ASKS_PATH,21+ IMPORT_PATH,22 docsPath,23 HOME_PATH,24 projectPath,25 } from "../shared/paths.ts";346 unmodified lines372 Code, asks, credit and the ledger of what a project holds back are373 public to everyone.374 </p>375 <Projects projects={projects} />375- <p className="text-ui">376+ <p className="text-ui flex flex-wrap gap-x-4 gap-y-1">377 <AppLink className={LINK} to={ASKS_PATH}>378 All asks379 </AppLink>380+ <AppLink className={LINK} to={IMPORT_PATH}>381+ Import a repo382+ </AppLink>383 </p>384 </Part>385 </main>386 <footer className="border-rule text-ui flex flex-wrap gap-x-5 gap-y-2 border-t py-6">15 unmodified linesmodified:apps/web/src/features/shared/shell/overlays.tsx+12 added-2 removed
6 unmodified lines7 * overlay belongs to the address it opened on).8 */9 import { Brand } from "@repo/brand";10 import { useRouter } from "@tanstack/react-router";11-import { BookOpen, Bot, Keyboard } from "lucide-react";11+import { BookOpen, Bot, FolderInput, Keyboard } from "lucide-react";12 import { useRef } from "react";13 import type { RefObject } from "react";14 15 import {13 unmodified lines29 import { Sheet, SheetContent } from "../../../components/ui/sheet.tsx";30 import { SessionSlot } from "../../auth/session-slot.tsx";31 import { KeysHelp, useKeys } from "../keys.tsx";32 import { AppLink } from "../link.tsx";33-import { docsPath } from "../paths.ts";33+import { docsPath, IMPORT_PATH } from "../paths.ts";34 import { useCurrentProject, useProjectList, useShell } from "./context.ts";35 import type { Overlay } from "./context.ts";36 import {37 PostureMark,225 unmodified lines263 side={overlay === "projects" && atLeastTablet() ? "left" : "full"}264 title="Projects"265 >266 <ProjectSwitcher input={filter} onChosen={onClose} />267+ <div className="border-rule border-t p-1">268+ <AppLink className={RAIL_ROW} to={IMPORT_PATH}>269+ <FolderInput270+ aria-hidden="true"271+ className="text-muted-foreground size-4 shrink-0"272+ strokeWidth={1.75}273+ />274+ Import a repo275+ </AppLink>276+ </div>277 </SheetContent>278 </Sheet>279 <KeysDialog onClose={onClose} open={overlay === "keys"} />280 </>4 unmodified linesmodified:apps/web/src/features/shared/paths.ts+3 added
14 unmodified lines15 16 /** A signed-in reader's own page. */17 export const HOME_PATH = "/home";18 19+/** The import page: a public repo made a project. */20+export const IMPORT_PATH = "/import";21+22 /** The docs' index, or one of its pages. */23 export const docsPath = (page?: string) =>24 page === undefined ? "/docs" : `/docs/${page}`;25 37 unmodified linesmodified:apps/web/src/routes/$owner/$project/index.tsx+20 added-1 removed
31 unmodified lines32 markdownLink,33 } from "../../../features/front/markdown.ts";34 import { useStamps } from "../../../features/front/stamps.ts";35 import {36+ ImportOffer,37+ offerFor,38+} from "../../../features/import/import-offer.tsx";39+import { useImporter } from "../../../features/import/use-importer.tsx";40+import {41 ProjectView,42 heldBackOf,43 homeListing,44 } from "../../../features/project/project-page.tsx";248 unmodified lines293 </SeededAtoms>294 );295 };296 297+/** The import offer for `project`, wired. */298+const Offer = ({ project }: { readonly project: ProjectName }) => {299+ const importer = useImporter(project);300+301+ return <ImportOffer importer={importer} project={project} />;302+};303+304+/**305+ * No project at this address: at a source namespace's306+ * (`/github.com/pallets/click`) the import offer, else the not-found.307+ */308 const Unknown = () => {309 const { project } = Route.useParams();310 295- return <UnknownProjectView name={project} />;311+ return Option.match(offerFor(project), {312+ onNone: () => <UnknownProjectView name={project} />,313+ onSome: (offered) => <Offer project={offered} />,314+ });315 };316 317 export const Route = createFileRoute("/$owner/$project/")({318 // TanStack infers each option from the ones before it.19 unmodified linesadded:apps/web/src/routes/import.tsx+39 added
1+import { createFileRoute, useLocation } from "@tanstack/react-router";2+import { Predicate } from "effect";3+4+import { hereOf } from "../features/auth/session-slot.tsx";5+import { ImportView } from "../features/import/import-page.tsx";6+import { useImporter } from "../features/import/use-importer.tsx";7+import { pageHead } from "../features/shared/head.ts";8+import { personalPage } from "../server/cache-headers.ts";9+10+// `/import`: import a public repo as a project. Who is signed in is read11+// in the browser (the server paints the page while it checks); an import12+// made goes to the project's page, a refusal shows under the form.13+// `?url=<https URL>` fills the form; nothing is imported until Import is14+// pressed. A page about its reader, kept by no cache.15+16+/** A page about its reader, kept by no cache. */17+export const importHeaders = () => personalPage;18+19+const ImportPage = () => {20+ const { url } = Route.useSearch();21+ const here = useLocation({ select: hereOf });22+ const importer = useImporter();23+24+ return <ImportView {...importer} here={here} url={url} />;25+};26+27+/** The address's search: the URL to fill the form with, when it is text. */28+export const importSearch = ({29+ url,30+}: {31+ readonly url?: unknown;32+}): { readonly url?: string } => (Predicate.isString(url) ? { url } : {});33+34+export const Route = createFileRoute("/import")({35+ validateSearch: importSearch,36+ headers: importHeaders,37+ head: () => pageHead({ title: "Import a repo" }),38+ component: ImportPage,39+});modified:apps/web/src/server/addresses.ts+13 added-4 removed
9 unmodified lines10 * - `projectParams` gives the project's pages its full name as `project`11 * (`oscabriel/datekit`), the name every read takes, and splits it again12 * when the router prints a link.13 * - `canonicalAddress` answers, before any page, a key a project kept from14- * before owners (`/datekit/…`) and a name spelled in another case15- * (`/OscaBriel/datekit/…`) with a 301 to the name's address, the rest of14+ * before owners (`/datekit/…`), a name spelled in another case15+ * (`/OscaBriel/datekit/…`) and one ending in `.git` with a 301 to the name's address, the rest of16 * the path and the query kept.17 */18 import {19 ProjectName,102 unmodified lines122 status: 301,123 });124 125 /**126+ * A name as spelled without a trailing `.git` on its last segment: an127+ * address copied from a clone URL (`/github.com/pallets/click.git`) names128+ * the project.129+ */130+const withoutGit = (spelled: string) => spelled.replace(/\.git$/iu, "");131+132+/**133 * The 301 a request needs to reach its project's address, if any: a key a134 * project kept from before owners (`/datekit/tree/main?x=1` to135 * `/oscabriel/datekit/tree/main?x=1`) and a name in another case129- * (`/OscaBriel/datekit` to `/oscabriel/datekit`). None for the web's own136+ * (`/OscaBriel/datekit` to `/oscabriel/datekit`), and a name with a137+ * trailing `.git` (`/github.com/pallets/click.git` to138+ * `/github.com/pallets/click`). None for the web's own139 * pages and files, for an address already canonical, and for a name no140 * project could have, which its page says is unknown.141 */142 export const canonicalAddress = (request: Request): Option.Option<Response> => {9 unmodified lines152 return Option.none();153 }154 155 return Option.flatMap(projectAddressOf(segments), (address) =>147- Option.flatMap(decodeName(address.spelled), (name) =>156+ Option.flatMap(decodeName(withoutGit(address.spelled)), (name) =>157 name === address.spelled158 ? Option.none()159 : Option.some(160 movedTo(28 unmodified linesadded:apps/web/test/import.test.tsx+494 added
1+/**2+ * The import page, `/import`, rendered to HTML with `react-dom/server`: a3+ * signed-in person pastes a public repo's HTTPS URL, may name a branch,4+ * picks the owner (their handle, or the URL's source namespace when its5+ * host is one the platform knows, which is the default then) and the name,6+ * prefilled from the URL, and imports it through `initProject`. Signed out,7+ * the page links to sign-in, coming back to it. A refusal reads as the8+ * platform gave it. The page is about its reader, so no cache keeps it.9+ */10+import { RegistryContext } from "@effect/atom-react";11+import { describe, expect, it } from "@effect/vitest";12+import { Brand } from "@repo/brand";13+import { Contracts, InitProject } from "@repo/protocol/contracts";14+import { Handle, Owner, ProjectName } from "@repo/protocol/ids";15+import {16+ ImportFailed,17+ NotYourNamespace,18+ ProjectExists,19+} from "@repo/protocol/refusal";20+import { asPerson, unanswered } from "@repo/protocol/testing";21+import { Cause, Effect, Exit, Layer, Option, Schema } from "effect";22+import { Atom, AsyncResult, AtomRegistry, Reactivity } from "effect/reactivity";23+import { RpcTest } from "effect/rpc";24+25+import { importAtom, importMade } from "../src/client/import.ts";26+import type { Importer } from "../src/features/import/import-form.tsx";27+import { ImportView } from "../src/features/import/import-page.tsx";28+import {29+ importPayload,30+ ownerChoices,31+ prefillFrom,32+ sourceUrlOf,33+} from "../src/features/import/prefill.ts";34+import type { ImportPayload } from "../src/features/import/prefill.ts";35+import {36+ afterImport,37+ useImporter,38+} from "../src/features/import/use-importer.tsx";39+import { ProposalFailure } from "../src/features/proposal/failure.tsx";40+import { importHeaders, importSearch, Route } from "../src/routes/import.tsx";41+import { ContractsClient, webContracts } from "../src/surfaces.ts";42+import { markupOf, textIn } from "./markup.ts";43+import { renderAt, routerAt } from "./render.tsx";44+45+const CLICK = "https://github.com/pallets/click";46+47+const oscabriel = Option.some(Handle.make("oscabriel"));48+49+const signedIn = (url = CLICK) =>50+ markupOf(<ImportView handle={oscabriel} here="/import" url={url} />);51+52+/** An input's opening tag, by its `name`. */53+const inputNamed = (markup: string, name: string) =>54+ new RegExp(`<input[^>]*name="${name}"[^>]*>`, "u").exec(markup)?.[0] ?? "";55+56+/** Where a sign-in link in `markup` comes back to. */57+const returnOf = (markup: string) => {58+ const href = /href="(?<href>\/auth\/signin[^"]*)"/u59+ .exec(markup)60+ ?.groups?.href?.replaceAll("&", "&");61+62+ return new URL(href ?? "/", "https://web.test").searchParams.get("return");63+};64+65+describe("the import page", () => {66+ it("is kept by no cache: its response is private and never stored", () => {67+ expect(Route.options.headers).toBe(importHeaders);68+ expect(importHeaders()).toStrictEqual({69+ "Cache-Control": "private, no-store",70+ });71+ });72+73+ it("takes the URL to prefill from its address, and nothing else", () => {74+ expect(Route.options.validateSearch).toBe(importSearch);75+ expect(importSearch({ url: CLICK })).toStrictEqual({ url: CLICK });76+ expect(importSearch({ url: 3 })).toStrictEqual({});77+ });78+79+ it("signed out, shows no form and a sign-in link that comes back to /import", () => {80+ const markup = markupOf(81+ <ImportView handle={Option.none()} here="/import" />82+ );83+84+ expect(markup).not.toContain("<form");85+ expect(returnOf(markup)).toBe("/import");86+ expect(textIn(markup)).toContain(`${Brand.cli} init --project`);87+ });88+89+ it("says so while it learns who is signed in", () => {90+ const markup = markupOf(91+ <ImportView checking handle={Option.none()} here="/import" />92+ );93+94+ expect(markup).not.toContain("<form");95+ expect(textIn(markup)).toContain("Checking who is signed in");96+ });97+98+ it("signed in, offers the URL, the branch, the owner and the name, prefilled from the URL", () => {99+ const markup = signedIn();100+101+ expect(inputNamed(markup, "url")).toContain(`value="${CLICK}"`);102+ expect(inputNamed(markup, "branch")).toContain('value=""');103+ expect(inputNamed(markup, "owner")).toContain('value="github.com/pallets"');104+ expect(inputNamed(markup, "name")).toContain('value="click"');105+ expect(markup).toMatch(/<button[^>]*type="submit"[^>]*>Import<\/button>/u);106+ });107+108+ it("waits on Import until the URL is one to import, and says so", () => {109+ const markup = signedIn("");110+111+ expect(markup).toMatch(112+ /<button(?=[^>]*disabled="")(?=[^>]*type="submit")[^>]*>Paste a repo's URL first<\/button>/u113+ );114+ });115+116+ it("says what it is doing while the import runs", () => {117+ const markup = markupOf(118+ <ImportView busy handle={oscabriel} here="/import" url={CLICK} />119+ );120+121+ expect(textIn(markup)).toContain("Importing…");122+ expect(markup).toMatch(123+ /<button(?=[^>]*disabled="")(?=[^>]*type="submit")/u124+ );125+ });126+});127+128+describe(prefillFrom, () => {129+ it("reads the source namespace and the name from a known host's URL", () => {130+ expect(prefillFrom(CLICK)).toStrictEqual({131+ name: Option.some("click"),132+ owner: Option.some("github.com/pallets"),133+ });134+ });135+136+ it("strips .git, lowercases, and keeps a dot inside the name", () => {137+ expect(prefillFrom("https://github.com/TJ/Commander.js.git")).toStrictEqual(138+ { name: Option.some("commander.js"), owner: Option.some("github.com/tj") }139+ );140+ });141+142+ it("names no owner for a host the platform does not know, and still the name", () => {143+ expect(prefillFrom("https://git.sr.ht/~sircmpwn/hare/")).toStrictEqual({144+ name: Option.some("hare"),145+ owner: Option.none(),146+ });147+ });148+149+ it("prefills nothing from what is not an HTTPS URL", () => {150+ expect(prefillFrom("git@github.com:pallets/click.git")).toStrictEqual({151+ name: Option.none(),152+ owner: Option.none(),153+ });154+ expect(prefillFrom("")).toStrictEqual({155+ name: Option.none(),156+ owner: Option.none(),157+ });158+ });159+});160+161+describe(ownerChoices, () => {162+ it("puts the source namespace first when the host is on the list, then the handle", () => {163+ expect(ownerChoices(oscabriel, CLICK)).toStrictEqual([164+ "github.com/pallets",165+ "oscabriel",166+ ]);167+ });168+169+ it("offers the handle alone when the host is not on the list", () => {170+ expect(171+ ownerChoices(oscabriel, "https://git.sr.ht/~sircmpwn/hare")172+ ).toStrictEqual(["oscabriel"]);173+ });174+175+ it("offers a handle in lowercase, as an owner is spelled", () => {176+ expect(177+ ownerChoices(Option.some(Handle.make("OscaBriel")), "")178+ ).toStrictEqual(["oscabriel"]);179+ });180+});181+182+describe(importPayload, () => {183+ const isPayload = Schema.is(InitProject.payloadSchema);184+185+ it("is initProject's payload: the project and the import, the branch when named", () => {186+ const payload = importPayload({187+ branch: " stable ",188+ name: "click",189+ owner: Owner.make("github.com/pallets"),190+ url: ` ${CLICK} `,191+ });192+193+ expect(payload).toStrictEqual(194+ Option.some({195+ import: { branch: "stable", url: CLICK },196+ project: "github.com/pallets/click",197+ })198+ );199+ expect(Option.exists(payload, isPayload)).toBeTruthy();200+ });201+202+ it("carries no branch when none is named", () => {203+ expect(204+ importPayload({205+ branch: "",206+ name: "click",207+ owner: Owner.make("oscabriel"),208+ url: CLICK,209+ })210+ ).toStrictEqual(211+ Option.some({ import: { url: CLICK }, project: "oscabriel/click" })212+ );213+ });214+215+ it("is none for a name or a URL the contract would not take", () => {216+ expect(217+ importPayload({218+ branch: "",219+ name: "Bad Name",220+ owner: Owner.make("oscabriel"),221+ url: CLICK,222+ })223+ ).toStrictEqual(Option.none());224+ expect(225+ importPayload({226+ branch: "",227+ name: "click",228+ owner: Owner.make("oscabriel"),229+ url: "http://github.com/pallets/click",230+ })231+ ).toStrictEqual(Option.none());232+ });233+});234+235+describe(sourceUrlOf, () => {236+ it("rebuilds the URL a source namespace's project was imported from", () => {237+ expect(sourceUrlOf(ProjectName.make("github.com/pallets/click"))).toBe(238+ CLICK239+ );240+ });241+});242+243+/** `initProject`'s answer: the project made. */244+const made = (project: string) =>245+ Schema.decodeSync(InitProject.successSchema)({246+ project,247+ remote: `https://platform.test/${project}.git`,248+ });249+250+describe(importMade, () => {251+ it("names the project an import made, once it answered", () => {252+ expect(253+ importMade(AsyncResult.success(made("github.com/pallets/click")))254+ ).toStrictEqual(Option.some("github.com/pallets/click"));255+ });256+257+ it("names none while an import runs, or after it was refused", () => {258+ const earlier = AsyncResult.success(made("oscabriel/click"));259+260+ expect(importMade(AsyncResult.waiting(earlier))).toStrictEqual(261+ Option.none()262+ );263+ expect(264+ importMade(265+ AsyncResult.fail(266+ new ImportFailed({ next: "x", reason: "unreachable" }),267+ { previousSuccess: Option.some(earlier) }268+ )269+ )270+ ).toStrictEqual(Option.none());271+ });272+});273+274+describe("a refused import", () => {275+ const click = ProjectName.make("github.com/pallets/click");276+277+ it.each([278+ [279+ "ImportFailed",280+ new ImportFailed({281+ next: `${Brand.cli} init`,282+ reason: "the repo could not be read",283+ }),284+ ],285+ [286+ "ProjectExists",287+ new ProjectExists({ next: `${Brand.cli} asks`, project: click }),288+ ],289+ [290+ "NotYourNamespace",291+ NotYourNamespace.of(292+ ProjectName.make("github.com/someone/click"),293+ Handle.make("oscabriel")294+ ),295+ ],296+ ])("reads as the platform's %s, under the form", (tag, refusal) => {297+ const markup = markupOf(298+ <ImportView299+ handle={oscabriel}300+ here="/import"301+ refusal={302+ <ProposalFailure303+ cause={Cause.fail(refusal)}304+ doing="import it"305+ here="/import"306+ />307+ }308+ url={CLICK}309+ />310+ );311+312+ expect(markup).toContain(`data-refusal="${tag}"`);313+ expect(markup).toContain("<form");314+ });315+});316+317+/**318+ * The page as its route draws it, the hook's importer over `registry`,319+ * handing each render's importer to `seen`, as the press would reach it.320+ * A server's render always reads who is signed in as not yet known (the321+ * page's first paint, `whoAtom`), so this one says, as the browser would322+ * once it knows, that oscabriel is.323+ */324+const Page = ({325+ seen,326+}: {327+ readonly seen?: ((importer: Importer) => void) | undefined;328+}) => {329+ const importer = useImporter();330+331+ seen?.(importer);332+333+ return (334+ <ImportView335+ {...importer}336+ checking={false}337+ handle={oscabriel}338+ here="/import"339+ url={CLICK}340+ />341+ );342+};343+344+const PageOver = ({345+ registry,346+ seen,347+}: {348+ readonly registry: AtomRegistry.AtomRegistry;349+ readonly seen?: (importer: Importer) => void;350+}) => (351+ <RegistryContext.Provider value={registry}>352+ <Page seen={seen} />353+ </RegistryContext.Provider>354+);355+356+/**357+ * A browser signed in as oscabriel, over a platform whose `initProject`358+ * answers with `answer`, every payload it is sent kept in `sent`.359+ */360+const browserWith = (361+ sent: ImportPayload[],362+ answer: (363+ payload: ImportPayload364+ ) => Effect.Effect<365+ typeof InitProject.successSchema.Type,366+ typeof InitProject.errorSchema.Type367+ >368+) =>369+ AtomRegistry.make({370+ initialValues: [371+ Atom.initialValue(372+ ContractsClient.runtime.layer,373+ Layer.effect(374+ ContractsClient,375+ RpcTest.makeClient(webContracts, { flatten: true })376+ ).pipe(377+ Layer.provide([378+ Layer.mergeAll(379+ unanswered,380+ Contracts.toLayerHandler("initProject", (payload) => {381+ sent.push(payload);382+383+ return answer(payload);384+ })385+ ),386+ asPerson(Handle.make("oscabriel")),387+ ]),388+ Layer.provideMerge(Reactivity.layer)389+ )390+ ),391+ ],392+ });393+394+/** The form's fields as the page drew them: what pressing Import sends. */395+const fieldsIn = (markup: string) => {396+ const value = (name: string) =>397+ /value="(?<value>[^"]*)"/u398+ .exec(inputNamed(markup, name))399+ ?.groups?.value?.replaceAll("&", "&") ?? "";400+401+ return {402+ branch: value("branch"),403+ name: value("name"),404+ owner: Owner.make(value("owner")),405+ url: value("url"),406+ };407+};408+409+/** Presses Import on the page drawn over `registry`, and waits for the answer. */410+const pressImport = (registry: AtomRegistry.AtomRegistry) =>411+ Effect.gen(function* () {412+ const importers: Importer[] = [];413+414+ const markup = yield* renderAt(415+ `/import?url=${encodeURIComponent(CLICK)}`,416+ <PageOver417+ registry={registry}418+ seen={(importer) => {419+ importers.push(importer);420+ }}421+ />422+ );423+424+ const payload = yield* Effect.fromOption(importPayload(fieldsIn(markup)));425+426+ // A page in the browser keeps the atom mounted while it waits; a427+ // server's render keeps nothing.428+ registry.mount(importAtom);429+ importers.at(-1)?.onImport?.(payload);430+431+ return yield* Effect.exit(432+ AtomRegistry.getResult(registry, importAtom, { suspendOnWaiting: true })433+ );434+ });435+436+describe("pressing Import", () => {437+ it.live(438+ "sends initProject the project and the import, then goes to the project's address",439+ () =>440+ Effect.gen(function* () {441+ const sent: ImportPayload[] = [];442+443+ const registry = browserWith(sent, ({ project }) =>444+ Effect.succeed(made(project))445+ );446+447+ const answered = yield* pressImport(registry);448+449+ const to = yield* Effect.fromOption(450+ Exit.match(answered, {451+ onFailure: () => Option.none(),452+ onSuccess: ({ project }) => afterImport(project),453+ })454+ );455+456+ const router = routerAt("/import");457+458+ yield* Effect.tryPromise(() => router.load());459+460+ expect(sent).toStrictEqual([461+ { import: { url: CLICK }, project: "github.com/pallets/click" },462+ ]);463+ // Where the hook's `navigate` goes: a router with no window to464+ // move only builds the location, as `navigate` does first.465+ expect(router.buildLocation(to).publicHref).toBe(466+ "/github.com/pallets/click"467+ );468+ })469+ );470+471+ it.live("draws a refusal as the platform gave it, under the form", () =>472+ Effect.gen(function* () {473+ const registry = browserWith([], ({ project }) =>474+ Effect.fail(NotYourNamespace.of(project, Handle.make("oscabriel")))475+ );476+477+ yield* pressImport(registry);478+479+ const markup = yield* renderAt(480+ "/import",481+ <PageOver registry={registry} />482+ );483+484+ expect(markup).toContain('data-refusal="NotYourNamespace"');485+ expect(markup).toContain("<form");486+ })487+ );488+489+ it("stays where it is when the import made the project this address names", () => {490+ const click = ProjectName.make("github.com/pallets/click");491+492+ expect(afterImport(click, click)).toStrictEqual(Option.none());493+ });494+});modified:apps/web/test/legacy-redirect.test.ts+29 added
46 unmodified lines47 Option.some([301, "/github.com/pallets/click/tree/main"])48 );49 });50 51+ it("is a 301 from a name with a trailing .git to the name, the rest and the query kept", () => {52+ expect(movedTo("/github.com/pallets/click.git")).toStrictEqual(53+ Option.some([301, "/github.com/pallets/click"])54+ );55+ expect(movedTo("/oscabriel/datekit.git")).toStrictEqual(56+ Option.some([301, "/oscabriel/datekit"])57+ );58+ expect(59+ movedTo("/github.com/pallets/click.git/tree/main?x=1")60+ ).toStrictEqual(61+ Option.some([301, "/github.com/pallets/click/tree/main?x=1"])62+ );63+ expect(movedTo("/GitHub.com/Pallets/Click.GIT")).toStrictEqual(64+ Option.some([301, "/github.com/pallets/click"])65+ );66+ });67+68+ it("answers only a read with the .git 301", () => {69+ expect(70+ canonicalAddress(request("/github.com/pallets/click.git", "POST"))71+ ).toStrictEqual(Option.none());72+ expect(73+ Option.map(74+ canonicalAddress(request("/oscabriel/datekit.git", "HEAD")),75+ (response) => response.status76+ )77+ ).toStrictEqual(Option.some(301));78+ });79+80 it("is kept by the edge, as a page that reads as nobody", () => {81 const answered = Option.getOrThrow(82 canonicalAddress(request("/datekit/tree/main?x=1"))83 );44 unmodified linesmodified:apps/web/test/production-bundle.test.ts+6 added-4 removed
411 unmodified lines412 })413 );414 415 it.effect(416- "preloads on every page no grammar, nothing of the server's highlighting, and not the landing's view",416+ "preloads on every page no grammar, nothing of the server's highlighting, and neither the landing's view nor the import page's",417 () =>418 Effect.gen(function* () {419 const output = yield* Built;420 421- // Nor the landing's view: a route's head or loader that imported422- // it would carry the whole page into every page's preloads.421+ // Nor the landing's view, nor the import page's: a route's head or422+ // loader that imported one would carry the whole page into every423+ // page's preloads.424 expect(425 rootPreloads(output).flatMap((chunk) =>426 (output.holding.get(`client${chunk}`) ?? []).filter(427 (module) =>428 GRAMMAR.test(module) ||429 module.includes("prerender") ||429- module.endsWith("features/landing/landing-page.tsx")430+ module.endsWith("features/landing/landing-page.tsx") ||431+ module.includes("features/import/")432 )433 )434 ).toStrictEqual([]);435 60 unmodified linesmodified:apps/web/test/project.test.tsx+92 added-1 removed
28 unmodified lines29 } from "@repo/protocol/ids";30 import { UnknownRevision } from "@repo/protocol/refusal";31 import { asTester, unanswered } from "@repo/protocol/testing";32 import { isNotFound } from "@tanstack/react-router";33-import { DateTime, Duration, Effect, Layer, Ref, Schema, Stream } from "effect";33+import {34+ DateTime,35+ Duration,36+ Effect,37+ Layer,38+ Option,39+ Ref,40+ Schema,41+ Stream,42+} from "effect";43 import { FetchHttpClient } from "effect/http";44 import { RpcClient, RpcSerialization, RpcTest } from "effect/rpc";45 46 import { recentLandings } from "../src/client/events.ts";47 import type { DevWorldOptions } from "../src/dev/server.ts";48 import { devServer } from "../src/dev/server.ts";49 import { ledeOf } from "../src/features/front/head.ts";50 import { stampStep } from "../src/features/front/stamps.ts";51+import { ImportOffer, offerFor } from "../src/features/import/import-offer.tsx";52 import { recentShown } from "../src/features/project/landings.tsx";53 import { postureWord } from "../src/features/project/posture-label.ts";54 import {55 ProjectView,623 unmodified lines679 );680 681 const decodePage = Schema.decodeEffect(ProjectPageData);682 683+/** An input's opening tag, by its `name`. */684+const inputNamed = (markup: string, name: string) =>685+ new RegExp(`<input[^>]*name="${name}"[^>]*>`, "u").exec(markup)?.[0] ?? "";686+687 /** A fresh dev world seeds itself first, which a full test run can slow past 5 s. */688 const seededWorld = { timeout: 30_000 };689 690 /** The page as the route draws it from what its loader read. */244 unmodified lines935 expect(markup).toMatch(/<a\b[^>]*href="\/asks"[^>]*>Open asks<\/a>/u);936 })937 );938 939+ it.effect(940+ "keeps the one-sentence not-found, and no offer, for a person's address",941+ () =>942+ Effect.gen(function* () {943+ const markup = yield* renderAt(944+ "/oscabriel/no-such",945+ <UnknownProjectView name="oscabriel/no-such" />946+ );947+948+ expect(markup).toContain('data-refusal="UnknownProject"');949+ expect(markup).not.toContain("<form");950+ expect(offerFor("oscabriel/no-such")).toStrictEqual(Option.none());951+ })952+ );953+954 it("says in a sentence that an address naming no possible project names none", () => {955 const markup = markupOf(<UnknownProjectView name="Not_A_Project" />);956 957 expect(markup).not.toContain("data-refusal");2 unmodified lines960 );961 });962 });963 964+describe(ImportOffer, () => {965+ const click = ProjectName.make("github.com/pallets/click");966+967+ const offered = (handle: Option.Option<Handle>) =>968+ renderAt(969+ "/github.com/pallets/click",970+ <ImportOffer importer={{ handle }} project={click} />971+ );972+973+ it("is what a source namespace's address offers, and no other", () => {974+ expect(offerFor("github.com/pallets/click")).toStrictEqual(975+ Option.some(click)976+ );977+ expect(offerFor("oscabriel/no-such")).toStrictEqual(Option.none());978+ expect(offerFor("Not_A_Project")).toStrictEqual(Option.none());979+ });980+981+ it.effect(982+ "draws the form prefilled from the address, the owner fixed and no refusal",983+ () =>984+ Effect.gen(function* () {985+ const markup = yield* offered(Option.some(Handle.make("oscabriel")));986+987+ expect(inputNamed(markup, "url")).toContain(988+ 'value="https://github.com/pallets/click"'989+ );990+ expect(inputNamed(markup, "owner")).toMatch(991+ /type="hidden"[^>]*value="github\.com\/pallets"|value="github\.com\/pallets"[^>]*type="hidden"/u992+ );993+ expect(inputNamed(markup, "name")).toContain('value="click"');994+ expect(markup).not.toContain('data-slot="select-trigger"');995+ expect(markup).not.toContain("data-refusal");996+ })997+ );998+999+ it.effect(1000+ "keeps the URL the address rebuilds read-only, and the branch and the name editable",1001+ () =>1002+ Effect.gen(function* () {1003+ const markup = yield* offered(Option.some(Handle.make("oscabriel")));1004+1005+ expect(inputNamed(markup, "url")).toContain('readOnly=""');1006+ expect(inputNamed(markup, "branch")).not.toContain("readOnly");1007+ expect(inputNamed(markup, "name")).not.toContain("readOnly");1008+ })1009+ );1010+1011+ it.effect(1012+ "signed out, says what would be imported, with the sign-in link back to the address",1013+ () =>1014+ Effect.gen(function* () {1015+ const markup = yield* offered(Option.none());1016+1017+ expect(markup).not.toContain("<form");1018+ expect(markup).toContain(1019+ `href="/auth/signin?return=${encodeURIComponent("/github.com/pallets/click")}"`1020+ );1021+ expect(textIn(markup)).toContain("https://github.com/pallets/click");1022+ })1023+ );1024+});1025+1026 describe("the project's views", () => {1027 const sources: Readonly<Record<string, string>> = import.meta.glob(1028 "../src/features/project/**/*.{ts,tsx}",1029 { eager: true, import: "default", query: "?raw" }7 unmodified linesmodified:apps/web/test/render.tsx+18 added-6 removed
2 unmodified lines3 * draws the router's links (`AppLink`), reads the location or the route's4 * params needs around it, as the app's router gives it in the browser.5 *6 * The routes are the app's shape without its loaders: `/` (the landing,7- * outside the shell), `/asks`, `/home`, `/today`, `/docs`, `/docs/$page`,7+ * outside the shell), `/asks`, `/home`, `/import`, `/today`, `/docs`, `/docs/$page`,8 * `/agents`, `/people/$handle` and `/$owner/$project` with its pages under9 * it, read through the app's own rewrite and params, so the shell finds the10 * project in `/oscabriel/datekit/ledger` and11 * `/github.com/pallets/click/tree/main`, and none in `/agents`.43 unmodified lines55 staticData: { shell: "bare" },56 }),57 createRoute({ getParentRoute: () => root, path: "asks" }),58 createRoute({ getParentRoute: () => root, path: "home" }),59+ createRoute({ getParentRoute: () => root, path: "import" }),60 createRoute({ getParentRoute: () => root, path: "today" }),61 createRoute({ getParentRoute: () => root, path: "docs" }),62 createRoute({ getParentRoute: () => root, path: "docs/$page" }),63 createRoute({ getParentRoute: () => root, path: "agents" }),10 unmodified lines74 ]),75 ]);76 };77 77-/** `view`'s static markup inside a router whose location is `url`. */78-export const renderAt = (78+/**79+ * The app's router at `url`, in memory, drawing `view` whatever the80+ * address: what a test navigates as a page would, and reads where it went.81+ */82+export const routerAt = (83 url: string,80- view: ReactNode,84+ view: ReactNode = null,85 options: RenderOptions = {}82-): Effect.Effect<string, Cause.UnknownError> => {83- const router = createRouter({86+) =>87+ createRouter({88 history: createMemoryHistory({ initialEntries: [url] }),89 rewrite: addressRewrite,90 routeTree: routesFor(view, options),91 });92 93+/** `view`'s static markup inside a router whose location is `url`. */94+export const renderAt = (95+ url: string,96+ view: ReactNode,97+ options: RenderOptions = {}98+): Effect.Effect<string, Cause.UnknownError> => {99+ const router = routerAt(url, view, options);100+101 return Effect.tryPromise(() => router.load()).pipe(102 Effect.map(() => renderToStaticMarkup(<RouterProvider router={router} />))103 );104 };modified:apps/web/test/routes.test.ts+2 added-13 removed
37 unmodified lines38 ]39 .filter((segment) => !notSegments.has(segment) && !segment.startsWith("$"))40 .toSorted();41 42-/**43- * Words reserved before the web serves a page at them: `import` is the44- * import page's address, reserved before the page lands, so no owner takes45- * it in the meantime.46- */47-const RESERVED_BEFORE_THEIR_PAGE = ["import"];48-42 describe("the web's own paths", () => {43 it("are found: every page and file the web serves at its top", () => {44 expect(segments).toStrictEqual([45 ".well-known",6 unmodified lines52 "docs",53 "favicon.ico",54 "home",55 "icons",56+ "import",57 "install.sh",58 "llms-full.txt",59 "llms.txt",60 "people",11 unmodified lines72 });73 74 it("are the protocol's reserved names, where an owner could spell one", () => {75 expect(82- [83- ...segments.filter((segment) =>84- /^[a-z0-9]+(?:-[a-z0-9]+)*$/u.test(segment)85- ),86- ...RESERVED_BEFORE_THEIR_PAGE,87- ].toSorted()76+ segments.filter((segment) => /^[a-z0-9]+(?:-[a-z0-9]+)*$/u.test(segment))77 ).toStrictEqual([...reservedProjectNames]);78 });79 });