Skip to content
Myr

import.test.tsx

This file

Path

apps/web/test/import.test.tsx

470 lines · 13.5 KiB · TypeScript

Last changed by

Merge build/comments-web-rest into mainoscabrielbefore adoption0eb1248

History of this file

Take it

1import { RegistryContext } from "@effect/atom-react";2import { describe, expect, it } from "@effect/vitest";3import { Brand } from "@repo/brand";4import { Contracts, InitProject } from "@repo/protocol/contracts";5import { Handle, Owner, ProjectName } from "@repo/protocol/ids";6import {7  ImportFailed,8  NotYourNamespace,9  ProjectExists,10} from "@repo/protocol/refusal";11import { asPerson, unanswered } from "@repo/protocol/testing";12import { Cause, Effect, Exit, Layer, Option, Schema } from "effect";13import { Atom, AsyncResult, AtomRegistry, Reactivity } from "effect/reactivity";14import { RpcTest } from "effect/rpc";1516import { importAtom, importMade } from "../src/client/import.ts";17import type { Importer } from "../src/features/import/import-form.tsx";18import { ImportView } from "../src/features/import/import-page.tsx";19import {20  importPayload,21  ownerChoices,22  prefillFrom,23  sourceUrlOf,24} from "../src/features/import/prefill.ts";25import type { ImportPayload } from "../src/features/import/prefill.ts";26import {27  afterImport,28  useImporter,29} from "../src/features/import/use-importer.tsx";30import { ProposalFailure } from "../src/features/proposal/failure.tsx";31import { importHeaders, importSearch, Route } from "../src/routes/import.tsx";32import { ContractsClient, webContracts } from "../src/surfaces.ts";33import { markupOf, textIn } from "./markup.ts";34import { renderAt, routerAt } from "./render.tsx";3536const CLICK = "https://github.com/pallets/click";3738const oscabriel = Option.some(Handle.make("oscabriel"));3940const signedIn = (url = CLICK) =>41  markupOf(<ImportView handle={oscabriel} here="/import" url={url} />);4243const inputNamed = (markup: string, name: string) =>44  new RegExp(`<input[^>]*name="${name}"[^>]*>`, "u").exec(markup)?.[0] ?? "";4546const returnOf = (markup: string) => {47  const href = /href="(?<href>\/auth\/signin[^"]*)"/u48    .exec(markup)49    ?.groups?.href?.replaceAll("&amp;", "&");5051  return new URL(href ?? "/", "https://web.test").searchParams.get("return");52};5354describe("the import page", () => {55  it("is kept by no cache: its response is private and never stored", () => {56    expect(Route.options.headers).toBe(importHeaders);57    expect(importHeaders()).toStrictEqual({58      "Cache-Control": "private, no-store",59    });60  });6162  it("takes the URL to prefill from its address, and nothing else", () => {63    expect(Route.options.validateSearch).toBe(importSearch);64    expect(importSearch({ url: CLICK })).toStrictEqual({ url: CLICK });65    expect(importSearch({ url: 3 })).toStrictEqual({});66  });6768  it("signed out, shows no form and a sign-in link that comes back to /import", () => {69    const markup = markupOf(70      <ImportView handle={Option.none()} here="/import" />71    );7273    expect(markup).not.toContain("<form");74    expect(returnOf(markup)).toBe("/import");75    expect(textIn(markup)).toContain(`${Brand.cli} init --project`);76  });7778  it("says so while it learns who is signed in", () => {79    const markup = markupOf(80      <ImportView checking handle={Option.none()} here="/import" />81    );8283    expect(markup).not.toContain("<form");84    expect(textIn(markup)).toContain("Checking who is signed in");85  });8687  it("signed in, offers the URL, the branch, the owner and the name, prefilled from the URL", () => {88    const markup = signedIn();8990    expect(inputNamed(markup, "url")).toContain(`value="${CLICK}"`);91    expect(inputNamed(markup, "branch")).toContain('value=""');92    expect(inputNamed(markup, "owner")).toContain('value="github.com/pallets"');93    expect(inputNamed(markup, "name")).toContain('value="click"');94    expect(markup).toMatch(/<button[^>]*type="submit"[^>]*>Import<\/button>/u);95  });9697  it("waits on Import until the URL is one to import, and says so", () => {98    const markup = signedIn("");99100    expect(markup).toMatch(101      /<button(?=[^>]*disabled="")(?=[^>]*type="submit")[^>]*>Paste a repo&#x27;s URL first<\/button>/u102    );103  });104105  it("says what it is doing while the import runs", () => {106    const markup = markupOf(107      <ImportView busy handle={oscabriel} here="/import" url={CLICK} />108    );109110    expect(textIn(markup)).toContain("Importing…");111    expect(markup).toMatch(112      /<button(?=[^>]*disabled="")(?=[^>]*type="submit")/u113    );114  });115});116117describe(prefillFrom, () => {118  it("reads the source namespace and the name from a known host's URL", () => {119    expect(prefillFrom(CLICK)).toStrictEqual({120      name: Option.some("click"),121      owner: Option.some("github.com/pallets"),122    });123  });124125  it("strips .git, lowercases, and keeps a dot inside the name", () => {126    expect(prefillFrom("https://github.com/TJ/Commander.js.git")).toStrictEqual(127      { name: Option.some("commander.js"), owner: Option.some("github.com/tj") }128    );129  });130131  it("names no owner for a host the platform does not know, and still the name", () => {132    expect(prefillFrom("https://git.sr.ht/~sircmpwn/hare/")).toStrictEqual({133      name: Option.some("hare"),134      owner: Option.none(),135    });136  });137138  it("prefills nothing from what is not an HTTPS URL", () => {139    expect(prefillFrom("git@github.com:pallets/click.git")).toStrictEqual({140      name: Option.none(),141      owner: Option.none(),142    });143    expect(prefillFrom("")).toStrictEqual({144      name: Option.none(),145      owner: Option.none(),146    });147  });148});149150describe(ownerChoices, () => {151  it("puts the source namespace first when the host is on the list, then the handle", () => {152    expect(ownerChoices(oscabriel, CLICK)).toStrictEqual([153      "github.com/pallets",154      "oscabriel",155    ]);156  });157158  it("offers the handle alone when the host is not on the list", () => {159    expect(160      ownerChoices(oscabriel, "https://git.sr.ht/~sircmpwn/hare")161    ).toStrictEqual(["oscabriel"]);162  });163164  it("offers a handle in lowercase, as an owner is spelled", () => {165    expect(166      ownerChoices(Option.some(Handle.make("OscaBriel")), "")167    ).toStrictEqual(["oscabriel"]);168  });169});170171describe(importPayload, () => {172  const isPayload = Schema.is(InitProject.payloadSchema);173174  it("is initProject's payload: the project and the import, the branch when named", () => {175    const payload = importPayload({176      branch: " stable ",177      name: "click",178      owner: Owner.make("github.com/pallets"),179      url: ` ${CLICK} `,180    });181182    expect(payload).toStrictEqual(183      Option.some({184        import: { branch: "stable", url: CLICK },185        project: "github.com/pallets/click",186      })187    );188    expect(Option.exists(payload, isPayload)).toBeTruthy();189  });190191  it("carries no branch when none is named", () => {192    expect(193      importPayload({194        branch: "",195        name: "click",196        owner: Owner.make("oscabriel"),197        url: CLICK,198      })199    ).toStrictEqual(200      Option.some({ import: { url: CLICK }, project: "oscabriel/click" })201    );202  });203204  it("is none for a name or a URL the contract would not take", () => {205    expect(206      importPayload({207        branch: "",208        name: "Bad Name",209        owner: Owner.make("oscabriel"),210        url: CLICK,211      })212    ).toStrictEqual(Option.none());213    expect(214      importPayload({215        branch: "",216        name: "click",217        owner: Owner.make("oscabriel"),218        url: "http://github.com/pallets/click",219      })220    ).toStrictEqual(Option.none());221  });222});223224describe(sourceUrlOf, () => {225  it("rebuilds the URL a source namespace's project was imported from", () => {226    expect(sourceUrlOf(ProjectName.make("github.com/pallets/click"))).toBe(227      CLICK228    );229  });230});231232const made = (project: string) =>233  Schema.decodeSync(InitProject.successSchema)({234    project,235    remote: `https://platform.test/${project}.git`,236  });237238describe(importMade, () => {239  it("names the project an import made, once it answered", () => {240    expect(241      importMade(AsyncResult.success(made("github.com/pallets/click")))242    ).toStrictEqual(Option.some("github.com/pallets/click"));243  });244245  it("names none while an import runs, or after it was refused", () => {246    const earlier = AsyncResult.success(made("oscabriel/click"));247248    expect(importMade(AsyncResult.waiting(earlier))).toStrictEqual(249      Option.none()250    );251    expect(252      importMade(253        AsyncResult.fail(254          new ImportFailed({ next: "x", reason: "unreachable" }),255          { previousSuccess: Option.some(earlier) }256        )257      )258    ).toStrictEqual(Option.none());259  });260});261262describe("a refused import", () => {263  const click = ProjectName.make("github.com/pallets/click");264265  it.each([266    [267      "ImportFailed",268      new ImportFailed({269        next: `${Brand.cli} init`,270        reason: "the repo could not be read",271      }),272    ],273    [274      "ProjectExists",275      new ProjectExists({ next: `${Brand.cli} asks`, project: click }),276    ],277    [278      "NotYourNamespace",279      NotYourNamespace.of(280        ProjectName.make("github.com/someone/click"),281        Handle.make("oscabriel")282      ),283    ],284  ])("reads as the platform's %s, under the form", (tag, refusal) => {285    const markup = markupOf(286      <ImportView287        handle={oscabriel}288        here="/import"289        refusal={290          <ProposalFailure291            cause={Cause.fail(refusal)}292            doing="import it"293            here="/import"294          />295        }296        url={CLICK}297      />298    );299300    expect(markup).toContain(`data-refusal="${tag}"`);301    expect(markup).toContain("<form");302  });303});304305// A server's render always reads who is signed in as not yet known, so this one says, as the browser would, that oscabriel is.306const Page = ({307  seen,308}: {309  readonly seen?: ((importer: Importer) => void) | undefined;310}) => {311  const importer = useImporter();312313  seen?.(importer);314315  return (316    <ImportView317      {...importer}318      checking={false}319      handle={oscabriel}320      here="/import"321      url={CLICK}322    />323  );324};325326const PageOver = ({327  registry,328  seen,329}: {330  readonly registry: AtomRegistry.AtomRegistry;331  readonly seen?: (importer: Importer) => void;332}) => (333  <RegistryContext.Provider value={registry}>334    <Page seen={seen} />335  </RegistryContext.Provider>336);337338const browserWith = (339  sent: ImportPayload[],340  answer: (341    payload: ImportPayload342  ) => Effect.Effect<343    typeof InitProject.successSchema.Type,344    typeof InitProject.errorSchema.Type345  >346) =>347  AtomRegistry.make({348    initialValues: [349      Atom.initialValue(350        ContractsClient.runtime.layer,351        Layer.effect(352          ContractsClient,353          RpcTest.makeClient(webContracts, { flatten: true })354        ).pipe(355          Layer.provide([356            Layer.mergeAll(357              unanswered,358              Contracts.toLayerHandler("initProject", (payload) => {359                sent.push(payload);360361                return answer(payload);362              })363            ),364            asPerson(Handle.make("oscabriel")),365          ]),366          Layer.provideMerge(Reactivity.layer)367        )368      ),369    ],370  });371372const fieldsIn = (markup: string) => {373  const value = (name: string) =>374    /value="(?<value>[^"]*)"/u375      .exec(inputNamed(markup, name))376      ?.groups?.value?.replaceAll("&amp;", "&") ?? "";377378  return {379    branch: value("branch"),380    name: value("name"),381    owner: Owner.make(value("owner")),382    url: value("url"),383  };384};385386const pressImport = (registry: AtomRegistry.AtomRegistry) =>387  Effect.gen(function* () {388    const importers: Importer[] = [];389390    const markup = yield* renderAt(391      `/import?url=${encodeURIComponent(CLICK)}`,392      <PageOver393        registry={registry}394        seen={(importer) => {395          importers.push(importer);396        }}397      />398    );399400    const payload = yield* Effect.fromOption(importPayload(fieldsIn(markup)));401402    // A page in the browser keeps the atom mounted while it waits; a403    // server's render keeps nothing.404    registry.mount(importAtom);405    importers.at(-1)?.onImport?.(payload);406407    return yield* Effect.exit(408      AtomRegistry.getResult(registry, importAtom, { suspendOnWaiting: true })409    );410  });411412describe("pressing Import", () => {413  it.live(414    "sends initProject the project and the import, then goes to the project's address",415    () =>416      Effect.gen(function* () {417        const sent: ImportPayload[] = [];418419        const registry = browserWith(sent, ({ project }) =>420          Effect.succeed(made(project))421        );422423        const answered = yield* pressImport(registry);424425        const to = yield* Effect.fromOption(426          Exit.match(answered, {427            onFailure: () => Option.none(),428            onSuccess: ({ project }) => afterImport(project),429          })430        );431432        const router = routerAt("/import");433434        yield* Effect.tryPromise(() => router.load());435436        expect(sent).toStrictEqual([437          { import: { url: CLICK }, project: "github.com/pallets/click" },438        ]);439        // Where the hook's `navigate` goes: a router with no window to440        // move only builds the location, as `navigate` does first.441        expect(router.buildLocation(to).publicHref).toBe(442          "/github.com/pallets/click"443        );444      })445  );446447  it.live("draws a refusal as the platform gave it, under the form", () =>448    Effect.gen(function* () {449      const registry = browserWith([], ({ project }) =>450        Effect.fail(NotYourNamespace.of(project, Handle.make("oscabriel")))451      );452453      yield* pressImport(registry);454455      const markup = yield* renderAt(456        "/import",457        <PageOver registry={registry} />458      );459460      expect(markup).toContain('data-refusal="NotYourNamespace"');461      expect(markup).toContain("<form");462    })463  );464465  it("stays where it is when the import made the project this address names", () => {466    const click = ProjectName.make("github.com/pallets/click");467468    expect(afterImport(click, click)).toStrictEqual(Option.none());469  });470});