From c8c251fabd690ed82a4a43322a8f5257be0d09c5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C5=ABdolfs=20O=C5=A1i=C5=86=C5=A1?= Date: Mon, 27 Feb 2023 14:52:07 +0100 Subject: [PATCH] Add httpd-client api library MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Rūdolfs Ošiņš --- .../workflows/check-httpd-api-unit-test.yml | 25 + httpd-client/index.ts | 136 +++++ httpd-client/lib/fetcher.ts | 159 ++++++ httpd-client/lib/project.ts | 474 ++++++++++++++++++ httpd-client/lib/project/comment.ts | 31 ++ httpd-client/lib/project/commit.ts | 169 +++++++ httpd-client/lib/project/issue.ts | 60 +++ httpd-client/lib/project/patch.ts | 151 ++++++ httpd-client/lib/session.ts | 76 +++ httpd-client/lib/shared.ts | 11 + httpd-client/tests/client.test.ts | 22 + httpd-client/tests/project.test.ts | 100 ++++ httpd-client/tests/session.test.ts | 7 + httpd-client/vite.config.ts | 17 + package-lock.json | 11 +- package.json | 6 +- scripts/run-httpd-with-fixtures | 11 +- src/App.svelte | 2 +- src/App/Header/Search.svelte | 17 +- src/App/Header/SearchResultsModal.svelte | 21 +- src/App/Hotkeys.svelte | 2 +- src/components/Authorship.svelte | 10 +- src/components/Comment.svelte | 8 +- src/components/DiffStatBadge.svelte | 9 +- src/components/Dropdown.svelte | 6 +- src/components/Thread.svelte | 14 +- src/config.json | 36 +- src/lib/api.ts | 127 ----- src/lib/cobs.ts | 32 -- src/lib/commit.ts | 66 +-- src/lib/config.ts | 6 +- src/lib/diff.ts | 104 ---- src/lib/issue.ts | 213 -------- src/lib/patch.ts | 171 ------- src/lib/project.ts | 351 ------------- src/lib/router.ts | 56 +-- src/lib/router/definitions.ts | 4 +- src/lib/search.ts | 61 ++- src/lib/seed.ts | 86 ---- src/lib/session.ts | 54 +- src/lib/utils.ts | 66 ++- src/views/home/Index.svelte | 36 +- src/views/projects/Blob.svelte | 10 +- src/views/projects/BranchSelector.svelte | 26 +- src/views/projects/Browser.svelte | 44 +- src/views/projects/CloneButton.svelte | 8 +- src/views/projects/Cob/CobStateButton.svelte | 17 +- src/views/projects/Commit.svelte | 10 +- .../projects/Commit/CommitAuthorship.svelte | 2 +- src/views/projects/Commit/CommitTeaser.svelte | 20 +- src/views/projects/Header.svelte | 56 ++- src/views/projects/History.svelte | 31 +- src/views/projects/Issue.svelte | 106 ++-- src/views/projects/Issue/IssueTeaser.svelte | 21 +- src/views/projects/Issue/New.svelte | 51 +- src/views/projects/Issues.svelte | 32 +- src/views/projects/Patch.svelte | 121 ++--- src/views/projects/Patch/PatchTeaser.svelte | 29 +- src/views/projects/Patches.svelte | 45 +- src/views/projects/PeerSelector.svelte | 14 +- src/views/projects/ProjectMeta.svelte | 2 +- .../projects/SourceBrowser/Changeset.svelte | 14 +- .../projects/SourceBrowser/FileDiff.svelte | 54 +- src/views/projects/Tree.svelte | 4 +- src/views/projects/Tree/Folder.svelte | 9 +- src/views/projects/View.svelte | 155 ++++-- src/views/projects/Widget.svelte | 19 +- src/views/seeds/View.svelte | 65 ++- src/views/seeds/View/Projects.svelte | 33 +- src/views/seeds/View/SeedAddress.svelte | 38 -- src/views/session/Index.svelte | 9 +- tests/e2e/hotkeys.spec.ts | 2 +- tests/e2e/search.spec.ts | 4 +- tests/e2e/seed.spec.ts | 3 +- tests/support/fixtures.ts | 43 +- tests/unit/cobs.test.ts | 26 - tests/unit/router.test.ts | 16 +- tests/unit/utils.test.ts | 24 + tsconfig.json | 4 +- vite.config.ts | 1 + 80 files changed, 2391 insertions(+), 1801 deletions(-) create mode 100644 .github/workflows/check-httpd-api-unit-test.yml create mode 100644 httpd-client/index.ts create mode 100644 httpd-client/lib/fetcher.ts create mode 100644 httpd-client/lib/project.ts create mode 100644 httpd-client/lib/project/comment.ts create mode 100644 httpd-client/lib/project/commit.ts create mode 100644 httpd-client/lib/project/issue.ts create mode 100644 httpd-client/lib/project/patch.ts create mode 100644 httpd-client/lib/session.ts create mode 100644 httpd-client/lib/shared.ts create mode 100644 httpd-client/tests/client.test.ts create mode 100644 httpd-client/tests/project.test.ts create mode 100644 httpd-client/tests/session.test.ts create mode 100644 httpd-client/vite.config.ts delete mode 100644 src/lib/api.ts delete mode 100644 src/lib/diff.ts delete mode 100644 src/lib/issue.ts delete mode 100644 src/lib/patch.ts delete mode 100644 src/lib/project.ts delete mode 100644 src/lib/seed.ts delete mode 100644 src/views/seeds/View/SeedAddress.svelte delete mode 100644 tests/unit/cobs.test.ts diff --git a/.github/workflows/check-httpd-api-unit-test.yml b/.github/workflows/check-httpd-api-unit-test.yml new file mode 100644 index 000000000..2dbabc328 --- /dev/null +++ b/.github/workflows/check-httpd-api-unit-test.yml @@ -0,0 +1,25 @@ +name: check-httpd-api-unit-test +on: + push: + branches: + - master + pull_request: + branches: + - master + +jobs: + check-httpd-api-unit-test: + runs-on: ubuntu-latest + steps: + - name: Setup Node + uses: actions/setup-node@v3 + with: + node-version: "18.15.0" + - name: Checkout + uses: actions/checkout@v3 + - run: npm ci + - name: Start http-api test server + run: | + mkdir -p tests/artifacts; + ./scripts/run-httpd-with-fixtures --non-interactive --download 2>&1 | tee tests/artifacts/httpd-api.log & + - run: npm run test:httpd-api:unit diff --git a/httpd-client/index.ts b/httpd-client/index.ts new file mode 100644 index 000000000..b1bd7e86a --- /dev/null +++ b/httpd-client/index.ts @@ -0,0 +1,136 @@ +import type { BaseUrl } from "./lib/fetcher.js"; +import type { Blob, Project, Remote, Tree } from "./lib/project.js"; +import type { Comment } from "./lib/project/comment.js"; +import type { + Commit, + CommitHeader, + Diff, + DiffAddedDeletedModifiedChangeset, + HunkLine, +} from "./lib/project/commit.js"; +import type { Issue, IssueState } from "./lib/project/issue.js"; +import type { Merge, Patch, PatchState, Review } from "./lib/project/patch.js"; +import type { RequestOptions, Method } from "./lib/fetcher.js"; +import type { ZodSchema } from "zod"; + +import { array, literal, number, strictObject, string, union } from "zod"; + +import * as project from "./lib/project.js"; +import * as session from "./lib/session.js"; +import { Fetcher } from "./lib/fetcher.js"; + +export type { + BaseUrl, + Blob, + Comment, + Commit, + CommitHeader, + Diff, + DiffAddedDeletedModifiedChangeset, + HunkLine, + Issue, + IssueState, + Merge, + Patch, + PatchState, + Project, + Remote, + Review, + Tree, +}; + +export interface Node { + id: string; +} + +const nodeSchema = strictObject({ + id: string(), +}) satisfies ZodSchema; + +export interface Root { + message: string; + service: string; + version: string; + node: Node; + path: string; + links: { href: string; rel: string; type: Method }[]; +} + +const rootSchema = strictObject({ + message: string(), + service: string(), + version: string(), + node: nodeSchema, + path: string(), + links: array( + strictObject({ + href: string(), + rel: string(), + type: union([ + literal("GET"), + literal("POST"), + literal("PUT"), + literal("DELETE"), + ]), + }), + ), +}) satisfies ZodSchema; + +export interface NodeStats { + projects: { count: number }; + users: { count: number }; +} + +const nodeStatsSchema = strictObject({ + projects: strictObject({ count: number() }), + users: strictObject({ count: number() }), +}) satisfies ZodSchema; + +export class HttpdClient { + #fetcher: Fetcher; + #baseUrl: BaseUrl; + + public project: project.Client; + public session: session.Client; + + public constructor(baseUrl: BaseUrl) { + this.#baseUrl = baseUrl; + this.#fetcher = new Fetcher(this.#baseUrl); + + this.project = new project.Client(this.#fetcher); + this.session = new session.Client(this.#fetcher); + } + + public async getRoot(options?: RequestOptions): Promise { + return this.#fetcher.fetchOk( + { + method: "GET", + path: "", + options, + }, + rootSchema, + ); + } + + public async getStats(options?: RequestOptions): Promise { + return this.#fetcher.fetchOk( + { + method: "GET", + path: "stats", + options, + }, + nodeStatsSchema, + ); + } + + public async getNode(options?: RequestOptions): Promise { + return this.#fetcher.fetchOk( + { + method: "GET", + path: "node", + options, + }, + nodeSchema, + ); + } +} diff --git a/httpd-client/lib/fetcher.ts b/httpd-client/lib/fetcher.ts new file mode 100644 index 000000000..acc4d6d05 --- /dev/null +++ b/httpd-client/lib/fetcher.ts @@ -0,0 +1,159 @@ +// This module provides low-level capabilities to interact with a typed +// JSON HTTP API. + +import type { ZodIssue, ZodType, TypeOf } from "zod"; + +export interface BaseUrl { + hostname: string; + port: number; + scheme: string; +} + +// Error that is thrown by `Fetcher` methods. +export class ResponseError extends Error { + public method: string; + public url: string; + public status: number; + public body: unknown; + + public constructor(method: string, response: Response, body_: unknown) { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const body: any = body_; + if ( + typeof body === "object" && + body !== null && + typeof body.message === "string" + ) { + super(body.message); + } else { + super("Response error"); + } + + this.method = method; + this.body = body_; + this.status = response.status; + this.url = response.url; + } +} + +// Error that is thrown by `Fetcher` methods when parsing the response +// body fails. +export class ResponseParseError extends Error { + public method: string; + public path: string; + public body: unknown; + public zodIssues: ZodIssue[]; + + public constructor( + method: string, + path: string, + body: unknown, + zodIssues: ZodIssue[], + ) { + super("Failed to parse response body"); + this.method = method; + this.path = path; + this.body = body; + this.zodIssues = zodIssues; + } +} + +export interface RequestOptions { + abort?: AbortSignal; +} + +export interface FetchParams { + method: Method; + // Path to append to the `Fetcher`s base URL to get the final URL. + path: string; + // Object that is serialized into JSON and sent as the data. + body?: unknown; + // Query parameters to be serialized with URLSearchParams. + query?: Record; + options?: RequestOptions; + headers?: Record; +} + +export type Method = "DELETE" | "GET" | "PATCH" | "POST" | "PUT"; + +export class Fetcher { + #baseUrl: BaseUrl; + + public constructor(baseUrl: BaseUrl) { + this.#baseUrl = baseUrl; + } + + // Execute a fetch and parse the result with the provided schema. + // Return the parsed payload. + // + // Throws `ResponseError` if the response status code is not `200`. + // eslint-disable-next-line @typescript-eslint/no-explicit-any + public async fetchOk>( + params: FetchParams, + schema: T, + ): Promise> { + const response = await this.fetch(params); + + const responseBody = await response.json(); + + if (!response.ok) { + throw new ResponseError(params.method, response, responseBody); + } + + const result = schema.safeParse(responseBody); + if (result.success) { + return result.data; + } else { + throw new ResponseParseError( + params.method, + params.path, + responseBody, + result.error.errors, + ); + } + } + + // Execute a fetch and ignore the response body. + // + // Throws `ResponseError` if the response status code is not `200`. + public async fetchOkNoContent(params: FetchParams): Promise { + const response = await this.fetch(params); + + if (!response.ok) { + let responseBody = await response.text(); + try { + responseBody = JSON.parse(responseBody); + } catch (_e: unknown) { + // We keep the original text response body. + } + throw new ResponseError(params.method, response, responseBody); + } + } + + private async fetch({ + method, + path, + body, + options = {}, + query, + headers = {}, + }: FetchParams): Promise { + if (body !== undefined && headers["content-type"] === undefined) { + headers["content-type"] = "application/json"; + } + + let url = `${this.#baseUrl.scheme}://${this.#baseUrl.hostname}:${ + this.#baseUrl.port + }/api/v1/${path}`; + if (query) { + const searchparams = new URLSearchParams(query as Record); + url = `${url}?${searchparams.toString()}`; + } + return globalThis.fetch(url, { + method, + headers, + body: body === undefined ? undefined : JSON.stringify(body), + signal: options.abort, + }); + } +} diff --git a/httpd-client/lib/project.ts b/httpd-client/lib/project.ts new file mode 100644 index 000000000..17f72f62d --- /dev/null +++ b/httpd-client/lib/project.ts @@ -0,0 +1,474 @@ +import type { Commit, CommitHeader, Commits, Diff } from "./project/commit.js"; +import type { Fetcher, RequestOptions } from "./fetcher.js"; +import type { + Issue, + IssueCreated, + IssueUpdateAction, +} from "./project/issue.js"; +import type { Patch, PatchUpdateAction } from "./project/patch.js"; +import type { SuccessResponse } from "./shared.js"; +import type { ZodSchema } from "zod"; + +import { successResponseSchema } from "./shared.js"; +import { + array, + boolean, + literal, + number, + optional, + record, + strictObject, + string, + union, +} from "zod"; + +import { + commitHeaderSchema, + commitSchema, + commitsSchema, + diffSchema, +} from "./project/commit.js"; + +import { + issueCreatedSchema, + issueSchema, + issuesSchema, +} from "./project/issue.js"; + +import { patchSchema, patchesSchema } from "./project/patch.js"; + +export interface Project { + id: string; + name: string; + description: string; + defaultBranch: string; + delegates: string[]; + head: string; + patches: { + open: number; + draft: number; + archived: number; + merged: number; + }; + issues: { + open: number; + closed: number; + }; +} + +const projectSchema = strictObject({ + id: string(), + name: string(), + description: string(), + defaultBranch: string(), + delegates: array(string()), + head: string(), + patches: strictObject({ + open: number(), + draft: number(), + archived: number(), + merged: number(), + }), + issues: strictObject({ + open: number(), + closed: number(), + }), +}) satisfies ZodSchema; + +const projectsSchema = array(projectSchema) satisfies ZodSchema; + +export interface Activity { + activity: number[]; +} + +const activitySchema = strictObject({ + activity: array(number()), +}) satisfies ZodSchema; + +export interface Blob { + binary: boolean; + content?: string; + name: string; + path: string; + lastCommit: CommitHeader; +} + +const blobSchema = strictObject({ + binary: boolean(), + content: optional(string()), + name: string(), + path: string(), + lastCommit: commitHeaderSchema, +}) satisfies ZodSchema; + +interface TreeEntry { + path: string; + name: string; + kind: "tree" | "blob"; +} + +const treeEntrySchema = strictObject({ + path: string(), + name: string(), + kind: union([literal("blob"), literal("tree")]), +}) satisfies ZodSchema; + +export interface TreeStats { + commits: number; + branches: number; + contributors: number; +} + +export interface Tree { + entries: TreeEntry[]; + lastCommit: CommitHeader; + name: string; + path: string; + stats: TreeStats; +} + +const treeSchema = strictObject({ + entries: array(treeEntrySchema), + lastCommit: commitHeaderSchema, + name: string(), + path: string(), + stats: strictObject({ + commits: number(), + branches: number(), + contributors: number(), + }), +}) satisfies ZodSchema; + +export interface Remote { + id: string; + heads: Record; + delegate: boolean; +} + +const remoteSchema = strictObject({ + id: string(), + heads: record(string(), string()), + delegate: boolean(), +}) satisfies ZodSchema; + +const remotesSchema = array(remoteSchema) satisfies ZodSchema; + +interface DiffResponse { + commits: CommitHeader[]; + diff: Diff; +} + +const diffResponseSchema = strictObject({ + commits: array(commitHeaderSchema), + diff: diffSchema, +}) satisfies ZodSchema; + +export class Client { + #fetcher: Fetcher; + + public constructor(fetcher: Fetcher) { + this.#fetcher = fetcher; + } + + public async getByDelegate( + delegateId: string, + options?: RequestOptions, + ): Promise { + return this.#fetcher.fetchOk( + { + method: "GET", + path: `delegates/${delegateId}/projects`, + options, + }, + projectsSchema, + ); + } + + public async getById(id: string, options?: RequestOptions): Promise { + return this.#fetcher.fetchOk( + { + method: "GET", + path: `projects/${id}`, + options, + }, + projectSchema, + ); + } + + public async getAll( + query?: { page?: number; perPage?: number }, + options?: RequestOptions, + ): Promise { + return this.#fetcher.fetchOk( + { + method: "GET", + path: "projects", + query, + options, + }, + projectsSchema, + ); + } + + public async getActivity( + id: string, + options?: RequestOptions, + ): Promise { + return this.#fetcher.fetchOk( + { + method: "GET", + path: `projects/${id}/activity`, + options, + }, + activitySchema, + ); + } + + public async getReadme( + id: string, + sha: string, + options?: RequestOptions, + ): Promise { + return this.#fetcher.fetchOk( + { + method: "GET", + path: `projects/${id}/readme/${sha}`, + options, + }, + blobSchema, + ); + } + + public async getBlob( + id: string, + sha: string, + path: string, + options?: RequestOptions, + ): Promise { + return this.#fetcher.fetchOk( + { + method: "GET", + path: `projects/${id}/blob/${sha}/${path}`, + options, + }, + blobSchema, + ); + } + + public async getTree( + id: string, + sha: string, + path?: string, + options?: RequestOptions, + ): Promise { + return this.#fetcher.fetchOk( + { + method: "GET", + path: `projects/${id}/tree/${sha}/${path ?? ""}`, + options, + }, + treeSchema, + ); + } + + public async getAllRemotes( + id: string, + options?: RequestOptions, + ): Promise { + return this.#fetcher.fetchOk( + { + method: "GET", + path: `projects/${id}/remotes`, + options, + }, + remotesSchema, + ); + } + + public async getRemoteByPeer( + id: string, + peer: string, + options?: RequestOptions, + ): Promise { + return this.#fetcher.fetchOk( + { + method: "GET", + path: `projects/${id}/remotes/${peer}`, + options, + }, + remoteSchema, + ); + } + + public async getAllCommits( + id: string, + query?: { + parent?: string; + since?: number; + until?: number; + page?: number; + perPage?: number; + }, + options?: RequestOptions, + ): Promise { + return this.#fetcher.fetchOk( + { + method: "GET", + path: `projects/${id}/commits`, + query, + options, + }, + commitsSchema, + ); + } + + public async getCommitBySha( + id: string, + sha: string, + options?: RequestOptions, + ): Promise { + return this.#fetcher.fetchOk( + { + method: "GET", + path: `projects/${id}/commits/${sha}`, + options, + }, + commitSchema, + ); + } + + public async getDiff( + id: string, + revisionBase: string, + revisionOid: string, + options?: RequestOptions, + ): Promise { + return this.#fetcher.fetchOk( + { + method: "GET", + path: `projects/${id}/diff/${revisionBase}/${revisionOid}`, + options, + }, + diffResponseSchema, + ); + } + + public async getIssueById( + id: string, + issueId: string, + options?: RequestOptions, + ): Promise { + return this.#fetcher.fetchOk( + { + method: "GET", + path: `projects/${id}/issues/${issueId}`, + options, + }, + issueSchema, + ); + } + + public async getAllIssues( + id: string, + options?: RequestOptions, + ): Promise { + return this.#fetcher.fetchOk( + { + method: "GET", + path: `projects/${id}/issues`, + options, + }, + issuesSchema, + ); + } + + public async createIssue( + id: string, + body: { + title: string; + description: string; + assignees: string[]; + tags: string[]; + }, + authToken: string, + options?: RequestOptions, + ): Promise { + return this.#fetcher.fetchOk( + { + method: "POST", + path: `projects/${id}/issues`, + headers: { Authorization: `Bearer ${authToken}` }, + body, + options, + }, + issueCreatedSchema, + ); + } + + public async updateIssue( + id: string, + issueId: string, + body: IssueUpdateAction, + authToken: string, + options?: RequestOptions, + ): Promise { + return this.#fetcher.fetchOk( + { + method: "PATCH", + path: `projects/${id}/issues/${issueId}`, + headers: { Authorization: `Bearer ${authToken}` }, + body, + options, + }, + successResponseSchema, + ); + } + + public async getPatchById( + id: string, + patchId: string, + options?: RequestOptions, + ): Promise { + return this.#fetcher.fetchOk( + { + method: "GET", + path: `projects/${id}/patches/${patchId}`, + options, + }, + patchSchema, + ); + } + + public async getAllPatches( + id: string, + options?: RequestOptions, + ): Promise { + return this.#fetcher.fetchOk( + { + method: "GET", + path: `projects/${id}/patches`, + options, + }, + patchesSchema, + ); + } + + public async updatePatch( + id: string, + patchId: string, + body: PatchUpdateAction, + authToken: string, + options?: RequestOptions, + ): Promise { + return this.#fetcher.fetchOk( + { + method: "PATCH", + path: `projects/${id}/patches/${patchId}`, + headers: { Authorization: `Bearer ${authToken}` }, + body, + options, + }, + successResponseSchema, + ); + } +} diff --git a/httpd-client/lib/project/comment.ts b/httpd-client/lib/project/comment.ts new file mode 100644 index 000000000..6bcbae19f --- /dev/null +++ b/httpd-client/lib/project/comment.ts @@ -0,0 +1,31 @@ +import type { ZodSchema } from "zod"; +import { array, number, record, strictObject, string } from "zod"; + +export type ThreadUpdateAction = + | { type: "comment"; body: string; replyTo?: string } + | { type: "edit"; id: string; body: string } + | { type: "redact"; id: string } + | { + type: "react"; + to: string; + reaction: { emoji: string }; + active: boolean; + }; + +export interface Comment { + id: string; + author: { id: string }; + body: string; + reactions: Record[]; + timestamp: number; + replyTo: string | null; +} + +export const commentSchema = strictObject({ + id: string(), + author: strictObject({ id: string() }), + body: string(), + reactions: array(record(string(), number())), + timestamp: number(), + replyTo: string().nullable(), +}) satisfies ZodSchema; diff --git a/httpd-client/lib/project/commit.ts b/httpd-client/lib/project/commit.ts new file mode 100644 index 000000000..42f4c1166 --- /dev/null +++ b/httpd-client/lib/project/commit.ts @@ -0,0 +1,169 @@ +import type { ZodSchema } from "zod"; +import { array, literal, number, strictObject, string, union } from "zod"; + +interface GitPerson { + name: string; + email: string; +} + +const gitPersonSchema = strictObject({ + name: string(), + email: string(), +}) satisfies ZodSchema; + +export interface CommitHeader { + id: string; + author: GitPerson; + summary: string; + description: string; + committer: GitPerson & { time: number }; +} + +export const commitHeaderSchema = strictObject({ + id: string(), + author: gitPersonSchema, + summary: string(), + description: string(), + committer: gitPersonSchema.merge(strictObject({ time: number() })), +}) satisfies ZodSchema; + +interface AdditionHunkLine { + line: string; + lineNo: number; + type: "addition"; +} + +const additionHunkLineSchema = strictObject({ + line: string(), + lineNo: number(), + type: literal("addition"), +}) satisfies ZodSchema; + +interface DeletionHunkLine { + line: string; + lineNo: number; + type: "deletion"; +} + +const deletionHunkLineSchema = strictObject({ + line: string(), + lineNo: number(), + type: literal("deletion"), +}) satisfies ZodSchema; + +interface ContextHunkLine { + line: string; + lineNoNew: number; + lineNoOld: number; + type: "context"; +} + +const contextHunkLineSchema = strictObject({ + line: string(), + lineNoNew: number(), + lineNoOld: number(), + type: literal("context"), +}) satisfies ZodSchema; + +export type HunkLine = AdditionHunkLine | DeletionHunkLine | ContextHunkLine; + +const hunkLineSchema = union([ + additionHunkLineSchema, + deletionHunkLineSchema, + contextHunkLineSchema, +]) satisfies ZodSchema; + +interface ChangesetHunk { + header: string; + lines: HunkLine[]; +} + +const changesetHunkSchema = strictObject({ + header: string(), + lines: array(hunkLineSchema), +}) satisfies ZodSchema; + +export interface DiffAddedDeletedModifiedChangeset { + path: string; + diff: { + type: "plain" | "binary" | "empty"; + hunks: ChangesetHunk[]; + eof: "noneMissing" | "oldMissing" | "newMissing" | "bothMissing"; + }; +} + +const diffAddedDeletedModifiedChangesetSchema = strictObject({ + path: string(), + diff: strictObject({ + type: union([literal("plain"), literal("binary"), literal("empty")]), + hunks: array(changesetHunkSchema), + eof: union([ + literal("noneMissing"), + literal("oldMissing"), + literal("newMissing"), + literal("bothMissing"), + ]), + }), +}) satisfies ZodSchema; + +interface DiffCopiedMovedChangeset { + newPath: string; + oldPath: string; +} + +const diffCopiedMovedChangesetSchema = strictObject({ + newPath: string(), + oldPath: string(), +}) satisfies ZodSchema; + +export interface Diff { + added: DiffAddedDeletedModifiedChangeset[]; + deleted: DiffAddedDeletedModifiedChangeset[]; + moved: DiffCopiedMovedChangeset[]; + copied: DiffCopiedMovedChangeset[]; + modified: DiffAddedDeletedModifiedChangeset[]; + stats: { + filesChanged: number; + insertions: number; + deletions: number; + }; +} + +export const diffSchema = strictObject({ + added: array(diffAddedDeletedModifiedChangesetSchema), + deleted: array(diffAddedDeletedModifiedChangesetSchema), + moved: array(diffCopiedMovedChangesetSchema), + copied: array(diffCopiedMovedChangesetSchema), + modified: array(diffAddedDeletedModifiedChangesetSchema), + stats: strictObject({ + filesChanged: number(), + insertions: number(), + deletions: number(), + }), +}) satisfies ZodSchema; + +export interface Commit { + commit: CommitHeader; + diff: Diff; + branches: string[]; +} + +export const commitSchema = strictObject({ + commit: commitHeaderSchema, + diff: diffSchema, + branches: array(string()), +}) satisfies ZodSchema; + +export interface Commits { + commits: Commit[]; + stats: { commits: number; branches: number; contributors: number }; +} + +export const commitsSchema = strictObject({ + commits: array(commitSchema), + stats: strictObject({ + commits: number(), + branches: number(), + contributors: number(), + }), +}) satisfies ZodSchema; diff --git a/httpd-client/lib/project/issue.ts b/httpd-client/lib/project/issue.ts new file mode 100644 index 000000000..28dcb376f --- /dev/null +++ b/httpd-client/lib/project/issue.ts @@ -0,0 +1,60 @@ +import type { Comment, ThreadUpdateAction } from "./comment.js"; +import type { ZodSchema } from "zod"; +import { array, boolean, literal, strictObject, string, union } from "zod"; + +import { commentSchema } from "./comment.js"; + +export type IssueState = + | { status: "open" } + | { status: "closed"; reason: "other" | "solved" }; + +const issueStateSchema = union([ + strictObject({ status: literal("open") }), + strictObject({ + status: literal("closed"), + reason: union([literal("other"), literal("solved")]), + }), +]) satisfies ZodSchema; + +export interface Issue { + id: string; + author: { id: string }; + title: string; + state: IssueState; + discussion: Comment[]; + tags: string[]; + assignees: string[]; +} + +export const issueSchema = strictObject({ + id: string(), + author: strictObject({ id: string() }), + title: string(), + state: issueStateSchema, + discussion: array(commentSchema), + tags: array(string()), + assignees: array(string()), +}) satisfies ZodSchema; + +export interface IssueCreated { + success: boolean; + id: string; +} + +export const issueCreatedSchema = strictObject({ + success: boolean(), + id: string(), +}) satisfies ZodSchema; + +export const issuesSchema = array(issueSchema) satisfies ZodSchema; + +export type IssueUpdateAction = + | { + type: "assign"; + add: string[]; + remove: string[]; + } + | { type: "edit"; title: string } + | { type: "lifecycle"; state: IssueState } + | { type: "tag"; add: string[]; remove: string[] } + | { type: "thread"; action: ThreadUpdateAction }; diff --git a/httpd-client/lib/project/patch.ts b/httpd-client/lib/project/patch.ts new file mode 100644 index 000000000..9fca90c80 --- /dev/null +++ b/httpd-client/lib/project/patch.ts @@ -0,0 +1,151 @@ +import type { Comment, ThreadUpdateAction } from "./comment.js"; +import type { ZodSchema } from "zod"; + +import { commentSchema } from "./comment.js"; + +import { + array, + literal, + number, + optional, + strictObject, + string, + tuple, + union, +} from "zod"; + +export type PatchState = + | { status: "draft" } + | { status: "open" } + | { status: "archived" } + | { status: "merged" }; + +const patchStateSchema = union([ + strictObject({ status: literal("draft") }), + strictObject({ status: literal("open") }), + strictObject({ status: literal("archived") }), + strictObject({ status: literal("merged") }), +]) satisfies ZodSchema; + +export interface Merge { + node: string; + commit: string; + timestamp: number; +} + +const mergeSchema = strictObject({ + node: string(), + commit: string(), + timestamp: number(), +}) satisfies ZodSchema; + +interface CodeLocation { + path: string; + commit: string; + lines: { + start: number; + end: number; + }; +} + +const codeLocationSchema = strictObject({ + path: string(), + commit: string(), + lines: strictObject({ + start: number(), + end: number(), + }), +}) satisfies ZodSchema; + +interface CodeComment { + location: CodeLocation; + comment: string; + timestamp: number; +} + +const codeCommentSchema = strictObject({ + location: codeLocationSchema, + comment: string(), + timestamp: number(), +}) satisfies ZodSchema; + +type Verdict = "accept" | "reject"; + +export interface Review { + verdict?: Verdict; + comment?: string; + inline: CodeComment[]; + timestamp: number; +} + +const reviewSchema = strictObject({ + verdict: optional(union([literal("accept"), literal("reject")])), + comment: optional(string()), + inline: array(codeCommentSchema), + timestamp: number(), +}) satisfies ZodSchema; + +interface Revision { + id: string; + description: string; + base: string; + oid: string; + refs: string[]; + discussions: Comment[]; + reviews: [string, Review][]; + merges: Merge[]; + timestamp: number; +} + +const revisionSchema = strictObject({ + id: string(), + description: string(), + base: string(), + oid: string(), + refs: array(string()), + discussions: array(commentSchema), + reviews: array(tuple([string(), reviewSchema])), + merges: array(mergeSchema), + timestamp: number(), +}) satisfies ZodSchema; + +export interface Patch { + id: string; + author: { id: string }; + title: string; + description: string; + state: PatchState; + target: string; + tags: string[]; + revisions: Revision[]; +} + +export const patchSchema = strictObject({ + id: string(), + author: strictObject({ id: string() }), + title: string(), + description: string(), + state: patchStateSchema, + target: string(), + tags: array(string()), + revisions: array(revisionSchema), +}) satisfies ZodSchema; + +export const patchesSchema = array(patchSchema) satisfies ZodSchema; + +export type PatchUpdateAction = + | { type: "edit"; title: string; description: string; target: string } + | { type: "editRevision"; revision: string; description: string } + | { type: "tag"; add: string[]; remove: string[] } + | { type: "revision"; description: string; base: string; oid: string } + | { type: "lifecycle"; state: PatchState } + | { type: "redact"; revision: string } + | { + type: "review"; + revision: string; + verdict?: Verdict; + comment?: string; + inline: CodeComment; + } + | { type: "merge"; revision: string; commit: string } + | { type: "thread"; revision: string; action: ThreadUpdateAction }; diff --git a/httpd-client/lib/session.ts b/httpd-client/lib/session.ts new file mode 100644 index 000000000..354311e6c --- /dev/null +++ b/httpd-client/lib/session.ts @@ -0,0 +1,76 @@ +import type { Fetcher, RequestOptions } from "./fetcher.js"; +import type { SuccessResponse } from "./shared.js"; +import type { ZodSchema } from "zod"; + +import { number, strictObject, string } from "zod"; + +import { successResponseSchema } from "./shared.js"; + +interface Session { + sessionId: string; + status: string; + publicKey: string; + issuedAt: number; + expiresAt: number; +} + +const sessionSchema = strictObject({ + sessionId: string(), + status: string(), + publicKey: string(), + issuedAt: number(), + expiresAt: number(), +}) satisfies ZodSchema; + +export class Client { + #fetcher: Fetcher; + + public constructor(fetcher: Fetcher) { + this.#fetcher = fetcher; + } + + public async getById(id: string, options?: RequestOptions): Promise { + return this.#fetcher.fetchOk( + { + method: "GET", + path: `sessions/${id}`, + options, + }, + sessionSchema, + ); + } + + public async update( + id: string, + body: { + sig: string; + pk: string; + }, + options?: RequestOptions, + ): Promise { + return this.#fetcher.fetchOk( + { + method: "PUT", + path: `sessions/${id}`, + body, + options, + }, + successResponseSchema, + ); + } + + public async delete( + id: string, + options?: RequestOptions, + ): Promise { + return this.#fetcher.fetchOk( + { + method: "DELETE", + path: `sessions/${id}`, + headers: { Authorization: `Bearer ${id}` }, + options, + }, + successResponseSchema, + ); + } +} diff --git a/httpd-client/lib/shared.ts b/httpd-client/lib/shared.ts new file mode 100644 index 000000000..5ddf1fcba --- /dev/null +++ b/httpd-client/lib/shared.ts @@ -0,0 +1,11 @@ +import type { ZodSchema } from "zod"; + +import { literal, strictObject } from "zod"; + +export interface SuccessResponse { + success: true; +} + +export const successResponseSchema = strictObject({ + success: literal(true), +}) satisfies ZodSchema; diff --git a/httpd-client/tests/client.test.ts b/httpd-client/tests/client.test.ts new file mode 100644 index 000000000..92071ba9a --- /dev/null +++ b/httpd-client/tests/client.test.ts @@ -0,0 +1,22 @@ +import { describe, test } from "vitest"; +import { HttpdClient } from "../index"; + +const api = new HttpdClient({ + hostname: "127.0.0.1", + port: 8080, + scheme: "http", +}); + +describe("client", () => { + test("#getRoot()", async () => { + await api.getRoot(); + }); + + test("#getStats()", async () => { + await api.getStats(); + }); + + test("#getNode()", async () => { + await api.getNode(); + }); +}); diff --git a/httpd-client/tests/project.test.ts b/httpd-client/tests/project.test.ts new file mode 100644 index 000000000..d36e7920e --- /dev/null +++ b/httpd-client/tests/project.test.ts @@ -0,0 +1,100 @@ +import { describe, test } from "vitest"; +import { HttpdClient } from "../index"; + +const api = new HttpdClient({ + hostname: "127.0.0.1", + port: 8080, + scheme: "http", +}); + +describe("project", () => { + test("#getByDelegate(delegateId)", async () => { + await api.project.getByDelegate( + "did:key:z6MknSLrJoTcukLrE435hVNQT4JUhbvWLX4kUzqkEStBU8Vi", + ); + }); + + test("#getAll()", async () => { + await api.project.getAll(); + }); + + test("#getById(id)", async () => { + await api.project.getById("rad:zKtT7DmF9H34KkvcKj9PHW19WzjT"); + }); + + test("#getActivity(id)", async () => { + await api.project.getActivity("rad:zKtT7DmF9H34KkvcKj9PHW19WzjT"); + }); + + test("#getReadme(id, sha)", async () => { + await api.project.getReadme( + "rad:zKtT7DmF9H34KkvcKj9PHW19WzjT", + "fcc929424b82984b7cbff9c01d2e20d9b1249842", + ); + }); + + test("#getBlob(id, sha, path)", async () => { + await api.project.getBlob( + "rad:zKtT7DmF9H34KkvcKj9PHW19WzjT", + "dd068e9aff9a569e597f6abaf84f120dd0cbbd70", + "src/true.c", + ); + }); + + test("#getTree(id, sha)", async () => { + await api.project.getTree( + "rad:zKtT7DmF9H34KkvcKj9PHW19WzjT", + "dd068e9aff9a569e597f6abaf84f120dd0cbbd70", + ); + }); + + test("#getTree(id, sha, path)", async () => { + await api.project.getTree( + "rad:zKtT7DmF9H34KkvcKj9PHW19WzjT", + "dd068e9aff9a569e597f6abaf84f120dd0cbbd70", + "src", + ); + }); + + test("#getAllRemotes(id)", async () => { + await api.project.getAllRemotes("rad:zKtT7DmF9H34KkvcKj9PHW19WzjT"); + }); + + test("#getRemoteByPeer(id, peer)", async () => { + await api.project.getRemoteByPeer( + "rad:zKtT7DmF9H34KkvcKj9PHW19WzjT", + "z6MknSLrJoTcukLrE435hVNQT4JUhbvWLX4kUzqkEStBU8Vi", + ); + }); + + test("#getAllCommits(id)", async () => { + await api.project.getAllCommits("rad:zKtT7DmF9H34KkvcKj9PHW19WzjT"); + }); + + // TODO: test since/until properly. + test("#getAllCommits(id, {parent, since, until, page, perPage})", async () => { + await api.project.getAllCommits("rad:zKtT7DmF9H34KkvcKj9PHW19WzjT", { + parent: "f0b8db68847b01f0964380507a9db6800e5b5342", + since: 1679065819581, + until: 1679065819590, + page: 1, + perPage: 2, + }); + }); + + test("#getCommitBySha(id, sha)", async () => { + await api.project.getCommitBySha( + "rad:zKtT7DmF9H34KkvcKj9PHW19WzjT", + "fcc929424b82984b7cbff9c01d2e20d9b1249842", + ); + }); + + test.todo("#getDiff(id, revisionBase, revisionOid)"); + test.todo("#getIssueById(id, issueId)"); + test.todo("#getAllIssues(id)"); + test.todo("#createIssue(id, { title, description, assignees, tags })"); + test.todo("#updateIssue(id, issueId, issueUpdateAction, authToken)"); + test.todo("#getPatchById(id, patchId)"); + test.todo("#getAllPatches(id)"); + test.todo("#updatePatch(id, patchId, patchUpdateAction, authToken)"); +}); diff --git a/httpd-client/tests/session.test.ts b/httpd-client/tests/session.test.ts new file mode 100644 index 000000000..a129391b4 --- /dev/null +++ b/httpd-client/tests/session.test.ts @@ -0,0 +1,7 @@ +import { describe, test } from "vitest"; + +describe("session", () => { + test.todo("#getById(id)"); + test.todo("#update(id, {sig, pk})"); + test.todo("#delete(id)"); +}); diff --git a/httpd-client/vite.config.ts b/httpd-client/vite.config.ts new file mode 100644 index 000000000..3e2cdd370 --- /dev/null +++ b/httpd-client/vite.config.ts @@ -0,0 +1,17 @@ +/// +import { defineConfig } from "vite"; +import path from "node:path"; + +export default defineConfig({ + test: { + environment: "node", + include: ["httpd-client/tests/*.test.ts"], + reporters: "verbose", + globalSetup: "./tests/support/globalSetup", + }, + resolve: { + alias: { + "@tests": path.resolve("./tests"), + }, + }, +}); diff --git a/package-lock.json b/package-lock.json index bd72aaa05..762889f05 100644 --- a/package-lock.json +++ b/package-lock.json @@ -21,7 +21,8 @@ "md5": "^2.3.0", "plausible-tracker": "^0.3.8", "svelte": "^3.57.0", - "twemoji": "^14.0.2" + "twemoji": "^14.0.2", + "zod": "^3.21.2" }, "devDependencies": { "@playwright/test": "^1.32.1", @@ -4191,6 +4192,14 @@ "url": "https://github.com/sponsors/sindresorhus" } }, + "node_modules/zod": { + "version": "3.21.4", + "resolved": "https://registry.npmjs.org/zod/-/zod-3.21.4.tgz", + "integrity": "sha512-m46AKbrzKVzOzs/DZgVnG5H55N1sv1M8qZU3A8RIKbs3mrACDNeIOeilDymVb2HdmP8uwshOCF4uJ8uM9rCqJw==", + "funding": { + "url": "https://github.com/sponsors/colinhacks" + } + }, "node_modules/zwitch": { "version": "2.0.4", "resolved": "https://registry.npmjs.org/zwitch/-/zwitch-2.0.4.tgz", diff --git a/package.json b/package.json index 1d7f38923..7c4f4e6fb 100644 --- a/package.json +++ b/package.json @@ -11,7 +11,8 @@ "format": "npx prettier '**/*.@(ts|js|svelte|json|css|html|yml)' --ignore-path .gitignore --write", "test:unit": "TZ='UTC' vitest run", "test:e2e": "TZ='UTC' playwright test", - "test:e2e:ipfs": "TZ='UTC' playwright test ./tests/e2e/hashRouter.spec.ts --config playwright.ipfs.config.ts" + "test:e2e:ipfs": "TZ='UTC' playwright test ./tests/e2e/hashRouter.spec.ts --config playwright.ipfs.config.ts", + "test:httpd-api:unit": "TZ='UTC' vitest run --config httpd-client/vite.config.ts --reporter verbose --threads false" }, "type": "module", "engines": { @@ -55,6 +56,7 @@ "md5": "^2.3.0", "plausible-tracker": "^0.3.8", "svelte": "^3.57.0", - "twemoji": "^14.0.2" + "twemoji": "^14.0.2", + "zod": "^3.21.2" } } diff --git a/scripts/run-httpd-with-fixtures b/scripts/run-httpd-with-fixtures index d3982f2b9..2da66cab7 100755 --- a/scripts/run-httpd-with-fixtures +++ b/scripts/run-httpd-with-fixtures @@ -1,7 +1,7 @@ #!/bin/bash set -e -REV=646376828d0520035246ccbbfcb82127160cd184 +REV=414477a31676d5e75efa7f3e8dc6624bcf2b2e52 REPO_ROOT=$(git rev-parse --show-toplevel) FIXTURE=$REPO_ROOT/tests/fixtures/seeds/palm.tar.bz2 @@ -75,10 +75,13 @@ if [ "$DOWNLOAD" = true ]; then CACHED_BINARY_NAME="$BINARY_NAME-${REV:0:7}" if ! [ -x "$(command -v $BINARY_PATH/$CACHED_BINARY_NAME)" ]; then - echo "Downloading $BINARY_NAME" case "$OS" in - Darwin) curl --fail -s "https://files.radicle.xyz/aarch64-apple-darwin/$REV/$BINARY_NAME" --output "$BINARY_PATH/$CACHED_BINARY_NAME" ;; - Linux) curl --fail -s "https://files.radicle.xyz/x86_64-unknown-linux-musl/$REV/$BINARY_NAME" --output "$BINARY_PATH/$CACHED_BINARY_NAME" ;; + Darwin) + echo Downloading $BINARY_NAME from https://files.radicle.xyz/$REV/aarch64-apple-darwin/$BINARY_NAME + curl --fail -s "https://files.radicle.xyz/$REV/aarch64-apple-darwin/$BINARY_NAME" --output "$BINARY_PATH/$CACHED_BINARY_NAME" || (echo "Download failed" && exit 1);; + Linux) + echo Downloading $BINARY_NAME from https://files.radicle.xyz/$REV/x86_64-unknown-linux-musl/$BINARY_NAME + curl --fail -s "https://files.radicle.xyz/$REV/x86_64-unknown-linux-musl/$BINARY_NAME" --output "$BINARY_PATH/$CACHED_BINARY_NAME" || (echo "Download failed" && exit 1);; *) echo "There are no precompiled binaries for your OS: $OS, compile $BINARY_NAME manually and make sure it's in PATH." && exit 1 ;; esac diff --git a/src/App.svelte b/src/App.svelte index c5bfbb268..e43a000c1 100644 --- a/src/App.svelte +++ b/src/App.svelte @@ -60,7 +60,7 @@ {#if $activeRouteStore.resource === "home"} {:else if $activeRouteStore.resource === "seeds"} - + {:else if $activeRouteStore.resource === "session"} {:else if $activeRouteStore.resource === "projects"} diff --git a/src/App/Header/Search.svelte b/src/App/Header/Search.svelte index cf93c9ead..167abfcbf 100644 --- a/src/App/Header/Search.svelte +++ b/src/App/Header/Search.svelte @@ -42,18 +42,17 @@ if (searchResult.type === "nothing") { shake(); } else if (searchResult.type === "error") { - // TODO: show some kind of notification to the user. shake(); } else if (searchResult.type === "projects") { input = ""; - if (searchResult.projects.length === 1) { + if (searchResult.results.length === 1) { router.push({ resource: "projects", params: { view: { resource: "tree" }, - id: searchResult.projects[0].info.id, + id: searchResult.results[0].project.id, peer: undefined, - seed: searchResult.projects[0].seed.host, + hostnamePort: searchResult.results[0].baseUrl.hostname, hash: undefined, search: undefined, }, @@ -62,7 +61,7 @@ modal.show({ component: SearchResultsModal, props: { - results: searchResult.projects, + results: searchResult.results, query, }, }); @@ -104,14 +103,14 @@ } .search { transition: all 0.2s; - width: 13rem; + width: 11rem; } .expanded { - width: 20rem; + width: 25.5rem; } @media (max-width: 720px) { .expanded { - width: 13rem; + width: 11rem; } } @@ -132,7 +131,7 @@ } }} on:submit={search} - placeholder="Search a name…"> + placeholder="Search a RID…"> diff --git a/src/App/Header/SearchResultsModal.svelte b/src/App/Header/SearchResultsModal.svelte index 7d4b822fa..c9da6d06a 100644 --- a/src/App/Header/SearchResultsModal.svelte +++ b/src/App/Header/SearchResultsModal.svelte @@ -1,13 +1,14 @@ - {#each replies as reply}
-
diff --git a/src/config.json b/src/config.json index 2f0f811c2..fb241b728 100644 --- a/src/config.json +++ b/src/config.json @@ -6,7 +6,11 @@ "defaultNodePort": 8776, "pinned": [ { - "host": "seed.radicle.xyz" + "baseUrl": { + "hostname": "seed.radicle.xyz", + "port": 443, + "scheme": "https" + } } ] }, @@ -15,27 +19,47 @@ { "name": "radicle-interface", "id": "rad:z4V1sjrXqjvFdnCUbxPFqd5p4DtH5", - "seed": "seed.radicle.xyz" + "baseUrl": { + "hostname": "seed.radicle.xyz", + "port": 443, + "scheme": "https" + } }, { "name": "heartwood", "id": "rad:z3gqcJUoA1n9HaHKufZs5FCSGazv5", - "seed": "seed.radicle.xyz" + "baseUrl": { + "hostname": "seed.radicle.xyz", + "port": 443, + "scheme": "https" + } }, { "name": "rips", "id": "rad:z3trNYnLWS11cJWC6BbxDs5niGo82", - "seed": "seed.radicle.xyz" + "baseUrl": { + "hostname": "seed.radicle.xyz", + "port": 443, + "scheme": "https" + } }, { "name": "radicle-git", "id": "rad:zMKWcgFLjUSVBBVmxbcMzzokRxub", - "seed": "seed.radicle.xyz" + "baseUrl": { + "hostname": "seed.radicle.xyz", + "port": 443, + "scheme": "https" + } }, { "name": "radicle-team", "id": "rad:z2Jk1mNqyX7AjT4K83jJW9vQoHn4f", - "seed": "seed.radicle.xyz" + "baseUrl": { + "hostname": "seed.radicle.xyz", + "port": 443, + "scheme": "https" + } } ] } diff --git a/src/lib/api.ts b/src/lib/api.ts deleted file mode 100644 index 5337d9fb8..000000000 --- a/src/lib/api.ts +++ /dev/null @@ -1,127 +0,0 @@ -export interface Host { - host: string; - port: number; - scheme: string; -} - -export class Request { - path: string; - base: string; - port: number; - - constructor(path: string, api: Host) { - this.port = api.port; - this.base = `${api.scheme}://${api.host}/api/v1`; - this.path = path.startsWith("/") ? path.slice(1) : path; - } - - async get( - params: Record = {}, - headers: Record = {}, - ): Promise { - const query = this.formatParams(params); - const search = new URLSearchParams(query).toString(); - const urlString = this.createUrl(search); - - return await Request.exec(urlString, { - method: "GET", - headers: { ...headers, Accept: "application/json" }, - }); - } - - async post( - params: Record = {}, - headers: Record = {}, - ): Promise { - const body = this.formatParams(params); - const urlString = this.createUrl(); - - return await Request.exec(urlString, { - method: "POST", - body: JSON.stringify(body), - headers: { ...headers, "Content-Type": "application/json" }, - }); - } - - async patch( - params: Record = {}, - headers: Record = {}, - ): Promise { - const body = this.formatParams(params); - const urlString = this.createUrl(); - - return await Request.exec(urlString, { - method: "PATCH", - body: JSON.stringify(body), - headers: { ...headers, "Content-Type": "application/json" }, - }); - } - - async put( - params: Record = {}, - headers: Record = {}, - ): Promise { - const body = this.formatParams(params); - const urlString = this.createUrl(); - - return await Request.exec(urlString, { - method: "PUT", - body: JSON.stringify(body), - headers: { ...headers, "Content-Type": "application/json" }, - }); - } - - // Executes a request and returns the response. - static async exec( - urlString: string, - props: Record, - ): Promise { - let response = null; - try { - response = await fetch(urlString, props); - } catch (err) { - throw new ApiError("API request failed", urlString); - } - - if (!response.ok) { - throw new ApiError(response.statusText, urlString); - } - return response.json(); - } - - // Filters out undefined and null values. - private formatParams(params: Record): Record { - const query: Record = {}; - for (const [key, val] of Object.entries(params)) { - if (val !== undefined && val !== null) { - query[key] = val; - } - } - - return query; - } - - // Creates a URL with an eventual query string and port. - private createUrl(search?: string): string { - const baseUrl = this.path ? `${this.base}/${this.path}` : this.base; - - const url = new URL(search ? `${baseUrl}?${search}` : baseUrl); - url.port = String(this.port); - return String(url); - } -} - -export class ApiError extends Error { - url?: string; - - constructor(message: string, url?: string) { - super(message); - - if (Error.captureStackTrace) { - Error.captureStackTrace(this, ApiError); - } - - this.name = "ApiError"; - this.url = url; - } -} diff --git a/src/lib/cobs.ts b/src/lib/cobs.ts index b985ac848..23519c615 100644 --- a/src/lib/cobs.ts +++ b/src/lib/cobs.ts @@ -1,35 +1,5 @@ -import type { IssueState } from "@app/lib/issue"; -import type { PatchState } from "@app/lib/patch"; - import { parseNodeId } from "@app/lib/utils"; -export interface Comment { - id: string; - author: Author; - body: string; - reactions: Record; - timestamp: number; - replyTo: string | null; -} - -export interface Author { - id: string; -} - -export interface Thread { - root: Comment; - replies: Comment[]; -} - -export interface PeerIdentity { - id: string; -} -export interface PeerInfo { - id: string; - person?: PeerIdentity; - delegate: boolean; -} - // Formats COBs Object Ids export function formatObjectId(id: string): string { return id.substring(0, 11); @@ -39,8 +9,6 @@ export function stripDidPrefix(array: string[]): string[] { return array.map(id => id.replace("did:key:", "")); } -export type State = IssueState | PatchState; - export function validateTag( value: string, items: string[], diff --git a/src/lib/commit.ts b/src/lib/commit.ts index 7522f0996..c0563d8d6 100644 --- a/src/lib/commit.ts +++ b/src/lib/commit.ts @@ -1,47 +1,12 @@ -import type { Stats } from "@app/lib/project"; -import type { Diff, DiffStats } from "@app/lib/diff"; -import { ApiError } from "@app/lib/api"; +import type { CommitHeader } from "@httpd-client"; + import { getDaysPassed } from "@app/lib/utils"; -export interface CommitsHistory { - commits: CommitMetadata[]; - stats: Stats; -} - -export interface CommitMetadata { - commit: CommitHeader; -} - -export interface Author { - email: string; - name: string; - time: number; -} - -export interface CommitStats { - branches: number; - commits: number; - contributors: number; -} - -export interface GroupedCommitsHistory { - commits: CommitGroup[]; - stats: Stats; -} - -export interface CommitHeader { - author: Author; - committer: Author; - description: string; - id: string; - summary: string; -} - // A set of commits grouped by time. -export interface CommitGroup { +interface CommitGroup { date: string; time: number; - commits: CommitMetadata[]; + commits: CommitHeader[]; week: number; } @@ -52,14 +17,7 @@ export interface WeeklyActivity { week: number; } -export interface Commit { - commit: CommitHeader; - stats: DiffStats; - diff: Diff; - branches: string[]; -} - -export function formatGroupTime(timestamp: number): string { +function formatGroupTime(timestamp: number): string { return new Date(timestamp).toLocaleDateString("en-US", { day: "numeric", weekday: "long", @@ -68,24 +26,22 @@ export function formatGroupTime(timestamp: number): string { }); } -export function groupCommits( - commits: { commit: CommitHeader }[], -): CommitGroup[] { +export function groupCommits(commits: CommitHeader[]): CommitGroup[] { const groupedCommits: CommitGroup[] = []; let groupDate: Date | undefined = undefined; try { commits = commits.sort((a, b) => { - if (a.commit.committer.time > b.commit.committer.time) { + if (a.committer.time > b.committer.time) { return -1; - } else if (a.commit.committer.time < b.commit.committer.time) { + } else if (a.committer.time < b.committer.time) { return 1; } return 0; }); - for (const { commit } of commits) { + for (const commit of commits) { const time = commit.committer.time * 1000; const date = new Date(time); const isNewDay = @@ -104,11 +60,11 @@ export function groupCommits( }); groupDate = date; } - groupedCommits[groupedCommits.length - 1].commits.push({ commit }); + groupedCommits[groupedCommits.length - 1].commits.push(commit); } return groupedCommits; } catch (err) { - throw new ApiError( + throw new Error( "Not able to create commit history, please consider updating seed HTTP API.", ); } diff --git a/src/lib/config.ts b/src/lib/config.ts index dc7f8e3a3..e5b5ec829 100644 --- a/src/lib/config.ts +++ b/src/lib/config.ts @@ -1,3 +1,5 @@ +import type { BaseUrl } from "@httpd-client"; + import configJson from "@app/config.json"; export interface Config { @@ -6,13 +8,13 @@ export interface Config { defaultHttpdPort: number; defaultNodePort: number; defaultHttpdScheme: string; - pinned: { host: string }[]; + pinned: { baseUrl: BaseUrl }[]; }; projects: { pinned: { name: string; id: string; - seed: string; + baseUrl: BaseUrl; }[]; }; } diff --git a/src/lib/diff.ts b/src/lib/diff.ts deleted file mode 100644 index a2321f2ba..000000000 --- a/src/lib/diff.ts +++ /dev/null @@ -1,104 +0,0 @@ -export const lineNumberR = (line: LineDiff): string | number => { - switch (line.type) { - case LineDiffType.Addition: { - return line.lineNo; - } - case LineDiffType.Context: { - return line.lineNoNew; - } - case LineDiffType.Deletion: { - return " "; - } - } -}; - -export const lineNumberL = (line: LineDiff): string | number => { - switch (line.type) { - case LineDiffType.Addition: { - return " "; - } - case LineDiffType.Context: { - return line.lineNoOld; - } - case LineDiffType.Deletion: { - return line.lineNo; - } - } -}; - -export const lineSign = (line: LineDiff): string => { - switch (line.type) { - case LineDiffType.Addition: { - return "+"; - } - case LineDiffType.Context: { - return " "; - } - case LineDiffType.Deletion: { - return "-"; - } - } -}; - -export enum LineDiffType { - Addition = "addition", - Context = "context", - Deletion = "deletion", -} - -export interface Addition { - type: LineDiffType.Addition; - line: string; - lineNo: number; -} - -export interface Context { - type: LineDiffType.Context; - line: string; - lineNoNew: number; - lineNoOld: number; -} - -export interface Deletion { - type: LineDiffType.Deletion; - line: string; - lineNo: number; -} - -export type LineDiff = Addition | Deletion | Context; - -export interface FileDiff { - path: string; - diff: Changeset; - eof: EofNewLine | null; -} - -export interface Changeset { - type: string; - hunks: Hunk[]; -} - -export interface Hunk { - header: string; - lines: LineDiff[]; -} - -export interface Diff { - added: FileDiff[]; - deleted: FileDiff[]; - moved: string[]; - copied: string[]; - modified: FileDiff[]; - stats: DiffStats; -} - -export interface DiffStats { - insertions: number; - deletions: number; -} - -export enum EofNewLine { - OldMissing = "oldMissing", - NewMissing = "newMissing", - BothMissing = "bothMissing", -} diff --git a/src/lib/issue.ts b/src/lib/issue.ts deleted file mode 100644 index 0835a4629..000000000 --- a/src/lib/issue.ts +++ /dev/null @@ -1,213 +0,0 @@ -import type { Author, Comment, State } from "@app/lib/cobs"; -import type { Host } from "@app/lib/api"; - -import { stripDidPrefix } from "@app/lib/cobs"; -import { Request } from "@app/lib/api"; - -export interface IIssue { - id: string; - author: Author; - title: string; - state: IssueState; - discussion: Comment[]; - tags: string[]; - assignees: string[]; - timestamp: number; -} - -export type IssueState = - | { status: "open" } - | { status: "closed"; reason: "other" | "solved" }; - -export function groupIssues(issues: Issue[]): { - open: Issue[]; - closed: Issue[]; -} { - return issues.reduce( - (acc, issue) => { - acc[issue.state.status].push(issue); - return acc; - }, - { open: [] as Issue[], closed: [] as Issue[] }, - ); -} - -export function createAddRemoveArrays( - currentArray: string[], - newArray: string[], -): { add: string[]; remove: string[] } { - return { - add: newArray.filter(item => !currentArray.includes(item)), - remove: currentArray.filter(item => !newArray.includes(item)), - }; -} - -export class Issue { - id: string; - author: Author; - title: string; - state: IssueState; - discussion: Comment[]; - tags: string[]; - assignees: string[]; - timestamp: number; - - constructor(issue: IIssue) { - this.id = issue.id; - this.author = issue.author; - this.title = issue.title; - this.state = issue.state; - this.discussion = issue.discussion; - this.tags = issue.tags; - this.assignees = issue.assignees; - this.timestamp = issue.discussion[0].timestamp; - } - - // Counts the amount of comments in a discussion, excluding the initial description - countComments(): number { - return this.discussion.reduce((acc, curr, index) => { - if (index !== 0) { - return acc + 1; - } - return acc; - }, 0); - } - - static async createIssue( - project: string, - title: string, - description: string, - assignees: string[], - tags: string[], - host: Host, - authToken: string, - ): Promise<{ success: true; id: string }> { - return await new Request(`projects/${project}/issues`, host).post( - { - title, - description, - assignees, - tags, - }, - { Authorization: `Bearer ${authToken}` }, - ); - } - - async editTitle( - project: string, - title: string, - host: Host, - session: string, - ): Promise { - await new Request(`projects/${project}/issues/${this.id}`, host).patch( - { - type: "edit", - title, - }, - { Authorization: `Bearer ${session}` }, - ); - } - - async editTags( - project: string, - add: string[], - remove: string[], - host: Host, - session: string, - ): Promise { - await new Request(`projects/${project}/issues/${this.id}`, host).patch( - { - type: "tag", - add, - remove, - }, - { Authorization: `Bearer ${session}` }, - ); - } - - async editAssignees( - project: string, - add: string[], - remove: string[], - host: Host, - session: string, - ): Promise { - await new Request(`projects/${project}/issues/${this.id}`, host).patch( - { - type: "assign", - add: stripDidPrefix(add), - remove: stripDidPrefix(remove), - }, - { Authorization: `Bearer ${session}` }, - ); - } - - async createComment( - project: string, - body: string, - host: Host, - session: string, - ): Promise { - await new Request(`projects/${project}/issues/${this.id}`, host).patch( - { - type: "thread", - action: { - type: "comment", - body, - }, - }, - { Authorization: `Bearer ${session}` }, - ); - } - - async replyComment( - project: string, - body: string, - replyTo: string, - host: Host, - session: string, - ): Promise { - await new Request(`projects/${project}/issues/${this.id}`, host).patch( - { - type: "thread", - action: { - type: "comment", - body, - replyTo, - }, - }, - { Authorization: `Bearer ${session}` }, - ); - } - - async changeState( - project: string, - state: State, - host: Host, - session: string, - ): Promise { - await new Request(`projects/${project}/issues/${this.id}`, host).patch( - { - type: "lifecycle", - state, - }, - { Authorization: `Bearer ${session}` }, - ); - } - - static async getIssues(id: string, host: Host): Promise { - const response: IIssue[] = await new Request( - `projects/${id}/issues`, - host, - ).get(); - return response.map(issue => new Issue(issue)); - } - - static async getIssue(id: string, issue: string, host: Host): Promise { - const response: IIssue = await new Request( - `projects/${id}/issues/${issue}`, - host, - ).get(); - return new Issue(response); - } -} diff --git a/src/lib/patch.ts b/src/lib/patch.ts deleted file mode 100644 index 7cab63478..000000000 --- a/src/lib/patch.ts +++ /dev/null @@ -1,171 +0,0 @@ -import type { Author, Comment } from "@app/lib/cobs"; -import type { CommitHeader } from "@app/lib/commit"; -import type { Diff } from "@app/lib/diff"; -import type { Host } from "@app/lib/api"; - -import { Request } from "@app/lib/api"; - -interface IPatch { - id: string; - author: Author; - title: string; - description: string; - state: PatchState; - target: string; - tags: string[]; - revisions: Revision[]; -} - -export interface Revision { - id: string; - description: string; - base: string; - oid: string; - refs: string[]; - discussions: Comment[]; - reviews: [string, Review][]; - merges: Merge[]; - timestamp: number; -} - -export interface Review { - verdict?: "accept" | "reject"; - comment?: string; - inline: CodeComment[]; - timestamp: number; -} - -export interface CodeComment { - location: CodeLocation; - comment: string; - timestamp: number; -} - -interface CodeLocation { - path: string; - commit: string; - lines: { - start: number; - end: number; - }; -} - -export interface Merge { - node: string; - commit: string; - timestamp: number; -} - -export type PatchState = - | { status: "draft" } - | { status: "open" } - | { status: "archived" } - | { status: "merged" }; - -export function groupPatches(patches: Patch[]): { - open: Patch[]; - draft: Patch[]; - archived: Patch[]; - merged: Patch[]; -} { - return patches.reduce( - (acc, patch) => { - acc[patch.state.status].push(patch); - return acc; - }, - { - open: [] as Patch[], - draft: [] as Patch[], - archived: [] as Patch[], - merged: [] as Patch[], - }, - ); -} - -export class Patch { - id: string; - author: Author; - title: string; - description: string; - state: PatchState; - target: string; - tags: string[]; - revisions: Revision[]; - - constructor(patch: IPatch) { - this.id = patch.id; - this.author = patch.author; - this.title = patch.title; - this.description = patch.description; - this.state = patch.state; - this.target = patch.target; - this.tags = patch.tags; - this.revisions = patch.revisions; - } - - async editTags( - project: string, - add: string[], - remove: string[], - host: Host, - session: string, - ): Promise { - await new Request(`projects/${project}/patches/${this.id}`, host).patch( - { - type: "tag", - add, - remove, - }, - { Authorization: `Bearer ${session}` }, - ); - } - - static async getPatches(id: string, host: Host): Promise { - const response: IPatch[] = await new Request( - `projects/${id}/patches`, - host, - ).get(); - return response.map(patch => new Patch(patch)); - } - - async replyComment( - project: string, - revision: string, - body: string, - replyTo: string, - host: Host, - session: string, - ): Promise { - await new Request(`projects/${project}/patches/${this.id}`, host).patch( - { - type: "thread", - revision, - action: { - type: "comment", - body, - replyTo, - }, - }, - { Authorization: `Bearer ${session}` }, - ); - } - - async getPatchDiff( - project: string, - revision: Revision, - host: Host, - ): Promise<{ commits: CommitHeader[]; diff: Diff }> { - return await new Request( - `projects/${project}/diff/${revision.base}/${revision.oid}`, - host, - ).get(); - } - - static async getPatch(id: string, patch: string, host: Host): Promise { - const response: IPatch = await new Request( - `projects/${id}/patches/${patch}`, - host, - ).get(); - return new Patch(response); - } -} diff --git a/src/lib/project.ts b/src/lib/project.ts deleted file mode 100644 index c83b9466a..000000000 --- a/src/lib/project.ts +++ /dev/null @@ -1,351 +0,0 @@ -import type { Commit, CommitHeader, CommitsHistory } from "@app/lib/commit"; -import type { Host } from "@app/lib/api"; -import type { ProjectResult } from "@app/lib/search"; - -import * as utils from "@app/lib/utils"; -import { Request } from "@app/lib/api"; -import { Seed } from "@app/lib/seed"; -import { isFulfilled, isOid, isRepositoryId } from "@app/lib/utils"; - -export type Branches = { [key: string]: string }; -export type MaybeBlob = Blob | undefined; -export type MaybeTree = Tree | undefined; - -// Enumerates the space below the Header component in the projects View component -export enum ProjectContent { - Tree, - History, - Commit, - Issues, - Issue, -} - -export interface ProjectInfo { - head: string; - id: string; - name: string; - description: string; - defaultBranch: string; - delegates: string[]; - patches: { - open: number; - draft: number; - archived: number; - merged?: number; - }; - issues: { - open: number; - closed: number; - }; -} - -export interface Tree { - path: string; - entries: Array; - stats: Stats; - name: string; - lastCommit: CommitHeader; -} - -type Kind = "tree" | "blob"; - -export interface Stats { - commits: number; - contributors: number; -} - -export interface Entry { - path: string; - name: string; - kind: Kind; -} - -export interface Blob { - binary: boolean; - content?: string; - path: string; - name: string; - lastCommit: CommitHeader; -} - -export interface Remote { - heads: Branches; -} - -export interface Person { - name: string; -} - -export interface Peer { - id: string; - heads: Branches; - delegate: boolean; -} - -// We need a SHA1 commit in some places, so we return early if the revision is a SHA and else we look into branches. -export function getOid(revision: string, branches?: Branches): string | null { - if (isOid(revision)) return revision; - - if (branches) { - const oid = branches[revision]; - - if (oid) { - return oid; - } - } - return null; -} - -// Parses the path consisting of a revision (eg. branch or commit) and file path into a tuple [revision, file-path] -export function parseRoute( - input: string, - branches: Branches, -): { path?: string; revision?: string } { - const branch = Object.entries(branches).find(([branchName]) => - input.startsWith(branchName), - ); - const commitPath = [input.slice(0, 40), input.slice(41)]; - const parsed: { path?: string; revision?: string } = {}; - - if (branch) { - const [rev, path] = [ - input.slice(0, branch[0].length), - input.slice(branch[0].length + 1), - ]; - - parsed.revision = rev; - parsed.path = path ? path : "/"; - } else if (isOid(commitPath[0])) { - parsed.revision = commitPath[0]; - parsed.path = commitPath[1] ? commitPath[1] : "/"; - } else { - parsed.path = input; - } - return parsed; -} - -export class Project implements ProjectInfo { - id: string; - head: string; - name: string; - description: string; - defaultBranch: string; - delegates: string[]; - seed: Seed; - peers: Peer[]; - branches: Branches; - patches: { - open: number; - draft: number; - archived: number; - merged?: number; - }; - issues: { - open: number; - closed: number; - }; - - constructor( - id: string, - info: ProjectInfo, - seed: Seed, - peers: Peer[], - branches: Branches, - ) { - this.id = id; - this.head = info.head; - this.name = info.name; - this.description = info.description; - this.defaultBranch = info.defaultBranch; - this.delegates = info.delegates; - this.seed = seed; - this.peers = peers; - this.branches = branches; - this.patches = info.patches; - this.issues = info.issues; - } - - async getRoot( - revision: string | null, - ): Promise<{ tree: Tree; commit: string }> { - const head = this.branches[this.defaultBranch]; - const commit = revision ? getOid(revision, this.branches) : head; - - if (!commit) { - throw new Error(`Revision ${revision} not found`); - } - const tree = await this.getTree(commit, "/"); - - return { tree, commit }; - } - - static async getInfo(nameOrId: string, host: Host): Promise { - return await new Request(`projects/${nameOrId}`, host).get(); - } - - static async getProjects( - host: Host, - opts?: { - perPage?: number; - page?: number; - }, - ): Promise { - const params: Record = { - "per-page": opts?.perPage, - page: opts?.page, - }; - return await new Request("projects", host).get(params); - } - - static async getDelegateProjects( - delegate: string, - host: Host, - opts?: { - perPage?: number; - page?: number; - }, - ): Promise { - const params: Record = { - "per-page": opts?.perPage, - page: opts?.page, - }; - return new Request(`delegates/${delegate}/projects`, host).get(params); - } - - static async getRemote( - id: string, - peer: string, - host: Host, - ): Promise { - return new Request(`projects/${id}/remotes/${peer}`, host).get(); - } - - static async getRemotes(id: string, host: Host): Promise { - return new Request(`projects/${id}/remotes`, host).get(); - } - - static async getCommits( - id: string, - host: Host, - opts?: { - parent?: string | null; - since?: string; - until?: string; - perPage?: number; - page?: number; - verified?: boolean; - }, - ): Promise { - const params: Record = { - parent: opts?.parent, - since: opts?.since, - until: opts?.until, - "per-page": opts?.perPage, - page: opts?.page, - verified: opts?.verified, - }; - const result = await new Request(`projects/${id}/commits`, host).get( - params, - ); - return result; - } - - static async getActivity( - id: string, - host: Host, - ): Promise<{ activity: number[] }> { - return new Request(`projects/${id}/activity`, host).get(); - } - - async getCommit(commit: string): Promise { - const result = await new Request( - `projects/${this.id}/commits/${commit}`, - this.seed.addr, - ).get(); - - return result; - } - - async getTree(commit: string, path: string): Promise { - if (path === "/") path = ""; - const result = await new Request( - `projects/${this.id}/tree/${commit}/${path}`, - this.seed.addr, - ).get(); - return result; - } - - async getBlob(commit: string, path: string): Promise { - const result = await new Request( - `projects/${this.id}/blob/${commit}/${path}`, - this.seed.addr, - ).get(); - return result; - } - - async getReadme(commit: string): Promise { - const result = await new Request( - `projects/${this.id}/readme/${commit}`, - this.seed.addr, - ).get(); - return result; - } - - getRawPath(commit?: string): string { - return `${this.seed.addr.scheme}://${this.seed.addr.host}:${ - this.seed.addr.port - }/raw/${this.id}/${commit ?? this.head}`; - } - - static async get( - id: string, - seedHost: string, - peer?: string, - ): Promise { - let seed: Seed | undefined = undefined; - - try { - seed = await Seed.lookup(utils.extractHost(seedHost)); - } catch (error) { - throw new Error(`Couldn't load project: ${error}`); - } - - const info = await Project.getInfo(id, seed.addr); - id = isRepositoryId(id) ? id : info.id; - - let peers: Peer[] = []; - - peers = await Project.getRemotes(id, seed.addr); - - let remote: Remote = { - heads: info.head ? { [info.defaultBranch]: info.head } : {}, - }; - - if (peer) { - try { - remote = await Project.getRemote(id, peer, seed.addr); - } catch { - remote.heads = {}; - } - } - - return new Project(id, info, seed, peers, remote.heads); - } - - static async getMulti( - projs: { nameOrId: string; seed: Host }[], - ): Promise { - const promises = []; - - for (const proj of projs) { - promises.push( - Project.getInfo(proj.nameOrId, proj.seed).then(info => { - return { info, seed: proj.seed }; - }), - ); - } - const results = await Promise.allSettled(promises); - - return results.filter(isFulfilled).map(r => r.value); - } -} diff --git a/src/lib/router.ts b/src/lib/router.ts index c25b02222..3f712ccad 100644 --- a/src/lib/router.ts +++ b/src/lib/router.ts @@ -149,8 +149,8 @@ function pathToRoute(path: string): Route | null { const resource = segments.shift(); switch (resource) { case "seeds": { - const host = segments.shift(); - if (host) { + const hostnamePort = segments.shift(); + if (hostnamePort) { const id = segments.shift(); if (id) { // Allows project paths with or without trailing slash @@ -164,24 +164,24 @@ function pathToRoute(path: string): Route | null { view: { resource: "tree" }, id, peer: undefined, - seed: host, + hostnamePort, }, }; } - const params = resolveProjectRoute(url, host, id, segments); + const params = resolveProjectRoute(url, hostnamePort, id, segments); if (params) { return { resource: "projects", params: { ...params, - seed: host, + hostnamePort, id, }, }; } return null; } - return { resource: "seeds", params: { host } }; + return { resource: "seeds", params: { hostnamePort } }; } return null; } @@ -214,9 +214,9 @@ export function routeToPath(route: Route) { } else if (route.resource === "session") { return `/session?id=${route.params.id}&sig=${route.params.signature}&pk=${route.params.publicKey}`; } else if (route.resource === "seeds") { - return `/seeds/${route.params.host}`; + return `/seeds/${route.params.hostnamePort}`; } else if (route.resource === "projects") { - const hostPrefix = `/seeds/${route.params.seed}`; + const hostnamePortPrefix = `/seeds/${route.params.hostnamePort}`; const content = `/${route.params.view.resource}`; let peer = ""; @@ -252,31 +252,31 @@ export function routeToPath(route: Route) { if (route.params.view.resource === "tree") { if (suffix) { - return `${hostPrefix}/${route.params.id}${peer}/tree${suffix}`; + return `${hostnamePortPrefix}/${route.params.id}${peer}/tree${suffix}`; } - return `${hostPrefix}/${route.params.id}${peer}`; + return `${hostnamePortPrefix}/${route.params.id}${peer}`; } else if (route.params.view.resource === "commits") { - return `${hostPrefix}/${route.params.id}${peer}/commits${suffix}`; + return `${hostnamePortPrefix}/${route.params.id}${peer}/commits${suffix}`; } else if (route.params.view.resource === "history") { - return `${hostPrefix}/${route.params.id}${peer}/history${suffix}`; + return `${hostnamePortPrefix}/${route.params.id}${peer}/history${suffix}`; } else if ( route.params.view.resource === "issues" && route.params.view.params?.view.resource === "new" ) { - return `${hostPrefix}/${route.params.id}${peer}/issues/new${suffix}`; + return `${hostnamePortPrefix}/${route.params.id}${peer}/issues/new${suffix}`; } else if (route.params.view.resource === "issues") { - return `${hostPrefix}/${route.params.id}${peer}/issues${suffix}`; + return `${hostnamePortPrefix}/${route.params.id}${peer}/issues${suffix}`; } else if (route.params.view.resource === "issue") { - return `${hostPrefix}/${route.params.id}${peer}/issues/${route.params.view.params.issue}`; + return `${hostnamePortPrefix}/${route.params.id}${peer}/issues/${route.params.view.params.issue}`; } else if (route.params.view.resource === "patches") { - return `${hostPrefix}/${route.params.id}${peer}/patches${suffix}`; + return `${hostnamePortPrefix}/${route.params.id}${peer}/patches${suffix}`; } else if (route.params.view.resource === "patch") { if (route.params.view.params.revision) { - return `${hostPrefix}/${route.params.id}${peer}/patches/${route.params.view.params.patch}/${route.params.view.params.revision}${suffix}`; + return `${hostnamePortPrefix}/${route.params.id}${peer}/patches/${route.params.view.params.patch}/${route.params.view.params.revision}${suffix}`; } - return `${hostPrefix}/${route.params.id}${peer}/patches/${route.params.view.params.patch}${suffix}`; + return `${hostnamePortPrefix}/${route.params.id}${peer}/patches/${route.params.view.params.patch}${suffix}`; } else { - return `${hostPrefix}/${route.params.id}${peer}${content}`; + return `${hostnamePortPrefix}/${route.params.id}${peer}${content}`; } } else if (route.resource === "404") { return route.params.url; @@ -287,7 +287,7 @@ export function routeToPath(route: Route) { function resolveProjectRoute( url: URL, - seed: string, + hostnamePort: string, id: string, segments: string[], ): ProjectsParams | null { @@ -304,7 +304,7 @@ function resolveProjectRoute( return { view: { resource: "tree" }, id, - seed, + hostnamePort, peer, path: undefined, revision: undefined, @@ -317,7 +317,7 @@ function resolveProjectRoute( return { view: { resource: "history" }, id, - seed, + hostnamePort, peer, path: undefined, revision: undefined, @@ -328,7 +328,7 @@ function resolveProjectRoute( return { view: { resource: "commits" }, id, - seed, + hostnamePort, peer, path: undefined, revision: undefined, @@ -341,7 +341,7 @@ function resolveProjectRoute( return { view: { resource: "issues", params: { view: { resource: "new" } } }, id, - seed, + hostnamePort, peer, search: sanitizeQueryString(url.search), path: undefined, @@ -351,7 +351,7 @@ function resolveProjectRoute( return { view: { resource: "issue", params: { issue: issueOrAction } }, id, - seed, + hostnamePort, peer, path: undefined, revision: undefined, @@ -361,7 +361,7 @@ function resolveProjectRoute( return { view: { resource: "issues" }, id, - seed, + hostnamePort, peer, search: sanitizeQueryString(url.search), path: undefined, @@ -375,7 +375,7 @@ function resolveProjectRoute( return { view: { resource: "patch", params: { patch, revision } }, id, - seed, + hostnamePort, peer, path: undefined, revision: undefined, @@ -385,7 +385,7 @@ function resolveProjectRoute( return { view: { resource: "patches" }, id, - seed, + hostnamePort, peer, search: sanitizeQueryString(url.search), path: undefined, diff --git a/src/lib/router/definitions.ts b/src/lib/router/definitions.ts index e3f7f6368..c44fb800e 100644 --- a/src/lib/router/definitions.ts +++ b/src/lib/router/definitions.ts @@ -6,7 +6,7 @@ export type Route = params: { id: string; signature: string; publicKey: string }; } | { resource: "404"; params: { url: string } } - | { resource: "seeds"; params: { host: string } }; + | { resource: "seeds"; params: { hostnamePort: string } }; export interface ProjectsParams { id: string; @@ -28,7 +28,7 @@ export interface ProjectsParams { }; } | { resource: "patch"; params: { patch: string; revision?: string } }; - seed: string; + hostnamePort: string; hash?: string; line?: string; path?: string; diff --git a/src/lib/search.ts b/src/lib/search.ts index ffc358f6a..e4b089402 100644 --- a/src/lib/search.ts +++ b/src/lib/search.ts @@ -1,61 +1,42 @@ -import type { Host } from "@app/lib/api"; -import type { ProjectInfo } from "@app/lib/project"; +import type { BaseUrl, Project } from "@httpd-client"; import * as utils from "@app/lib/utils"; -import { Project } from "@app/lib/project"; +import { HttpdClient } from "@httpd-client"; import { config } from "@app/lib/config"; +import { isFulfilled } from "@app/lib/utils"; -export interface ProjectResult { - info: ProjectInfo; - seed: Host; +export interface ProjectAndSeed { + project: Project; + baseUrl: BaseUrl; } type SearchResult = | { type: "nothing" } | { type: "error"; message: string } - | { type: "projects"; projects: ProjectResult[] }; + | { type: "projects"; results: ProjectAndSeed[] }; export async function searchProjectsAndProfiles( query: string, ): Promise { try { - const projectOnSeeds = config.seeds.pinned.map(seed => ({ - nameOrId: query, - seed: { - host: seed.host, - port: config.seeds.defaultHttpdPort, - scheme: config.seeds.defaultHttpdScheme, - }, + const pinned = config.seeds.pinned.map(seed => ({ + id: query, + baseUrl: seed.baseUrl, })); - // The query is a radicle project ID. if (utils.isRepositoryId(query)) { - const projects = await Project.getMulti(projectOnSeeds); + const results = await getProjectsFromSeeds(pinned); - if (projects.length === 0) { + if (results.length === 0) { return { type: "nothing" }; } else { return { type: "projects", - projects, + results, }; } } - let projects: ProjectResult[] = []; - try { - projects = await Project.getMulti(projectOnSeeds); - } catch { - // TODO: collect errors and forward to user. - } - - if (projects.length > 0) { - return { - type: "projects", - projects, - }; - } - return { type: "nothing" }; } catch (error) { let message = "An unknown error occoured while searching."; @@ -67,3 +48,19 @@ export async function searchProjectsAndProfiles( return { type: "error", message }; } } + +export async function getProjectsFromSeeds( + params: { id: string; baseUrl: BaseUrl }[], +): Promise { + const projectPromises = params.map(async param => { + const api = new HttpdClient(param.baseUrl); + const project = await api.project.getById(param.id); + return { + project, + baseUrl: param.baseUrl, + }; + }); + + const results = await Promise.allSettled(projectPromises); + return results.filter(isFulfilled).map(r => r.value); +} diff --git a/src/lib/seed.ts b/src/lib/seed.ts deleted file mode 100644 index ba8c35308..000000000 --- a/src/lib/seed.ts +++ /dev/null @@ -1,86 +0,0 @@ -import type { Host } from "@app/lib/api"; - -import * as proj from "@app/lib/project"; -import { Request } from "@app/lib/api"; -import { assert } from "@app/lib/error"; -import { config } from "@app/lib/config"; - -export interface Stats { - projects: { count: number }; - users: { count: number }; -} - -export class Seed { - addr: Host; - node: Host & { id: string }; - - version?: string; - - constructor(seed: { host: Host; id: string; version?: string }) { - assert(/^[a-zA-Z0-9]+$/.test(seed.id), `invalid seed id ${seed.id}`); - - this.addr = seed.host; - this.node = { - host: seed.host.host, - id: seed.id, - port: config.seeds.defaultNodePort, - scheme: seed.host.scheme, - }; - - if (seed.version) { - this.version = seed.version; - } - } - - get id(): string { - return this.node.id; - } - - get host(): string { - return this.addr.host; - } - - async getNode(): Promise<{ id: string }> { - return Seed.getNode(this.addr); - } - - async getProject(id: string): Promise { - return proj.Project.getInfo(id, this.addr); - } - - async getProjects(perPage: number, id?: string): Promise { - const result = id - ? await proj.Project.getDelegateProjects(id, this.addr, { perPage }) - : await proj.Project.getProjects(this.addr, { perPage }); - - return result; - } - - async getStats(): Promise<{ - projects: { count: number }; - users: { count: number }; - }> { - return new Request("/stats", this.addr).get(); - } - - static async getNode(host: Host): Promise<{ id: string }> { - return new Request("/node", host).get(); - } - - static async getInfo(host: Host): Promise<{ version: string }> { - return new Request("/", host).get(); - } - - static async lookup(host: Host): Promise { - const [info, node] = await Promise.all([ - Seed.getInfo(host), - Seed.getNode(host), - ]); - - return new Seed({ - id: node.id, - version: info.version, - host, - }); - } -} diff --git a/src/lib/session.ts b/src/lib/session.ts index d867840f6..2830f8f3c 100644 --- a/src/lib/session.ts +++ b/src/lib/session.ts @@ -1,40 +1,37 @@ import { derived, get, writable } from "svelte/store"; -export interface Session { +import { HttpdClient } from "@httpd-client"; + +export interface StoredSession { id: string; publicKey: string; } -interface SessionResponse { - sessionId: string; - status: string; - publicKey: string; - issuedAt: number; - expiresAt: number; -} - -const store = writable(undefined); +const store = writable(undefined); export const sessionStore = derived(store, s => s); -const endpoint = "http://localhost:8080/api/v1/sessions"; +const api = new HttpdClient({ + hostname: "127.0.0.1", + port: 8080, + scheme: "http", +}); export async function authenticate(params: { id: string; signature: string; publicKey: string; -}): Promise<"success" | "failure"> { - disconnect(); +}): Promise { + await disconnect(); - const request = await fetch(`${endpoint}/${params.id}`, { - method: "PUT", - headers: { "Content-Type": "application/json" }, - body: JSON.stringify({ sig: params.signature, pk: params.publicKey }), - }); - if (request.ok) { + try { + await api.session.update(params.id, { + sig: params.signature, + pk: params.publicKey, + }); save(params.id, params.publicKey); - return "success"; - } else { - return "failure"; + return true; + } catch { + return false; } } @@ -52,11 +49,8 @@ function pollSession() { } try { - const resp = await fetch(`${endpoint}/${session.id}`, { - method: "GET", - }); + const sess = await api.session.getById(session.id); - const sess: SessionResponse = await resp.json(); const unixTimeInSeconds = Math.floor(Date.now() / 1000); if ( sess.status === "unauthorized" || @@ -76,13 +70,7 @@ export async function disconnect() { return "success"; } - await fetch(`${endpoint}/${session.id}`, { - method: "DELETE", - headers: { - "Content-Type": "application/json", - Authorization: `Bearer ${session.id}`, - }, - }); + await api.session.delete(session.id); clear(); } diff --git a/src/lib/utils.ts b/src/lib/utils.ts index b34d5c55a..34b26ee19 100644 --- a/src/lib/utils.ts +++ b/src/lib/utils.ts @@ -1,4 +1,4 @@ -import type { Host } from "@app/lib/api"; +import type { BaseUrl } from "@httpd-client"; import md5 from "md5"; import bs58 from "bs58"; @@ -23,20 +23,30 @@ export function setOpenGraphMetaTag( }); } -export function formatSeedAddress( +export function getRawBasePath( id: string, - host: string, - port: number, + baseUrl: BaseUrl, + commit: string, ): string { - return `${id}@${host}:${port}`; + return `${baseUrl.scheme}://${baseUrl.hostname}:${baseUrl.port}/raw/${id}/${commit}`; } -export function formatSeedHost(host: string): string { - if (isLocal(host)) { - return "radicle.local"; - } else { - return host; +// We need a SHA1 commit in some places, so we return early if the revision is +// a SHA and else we look into branches. +export function getOid( + revision: string, + branches?: Record, +): string | null { + if (isOid(revision)) return revision; + + if (branches) { + const oid = branches[revision]; + + if (oid) { + return oid; + } } + return null; } export function formatLocationHash(hash: string | null): number | null { @@ -231,7 +241,7 @@ export function isDomain(input: string): boolean { ); } -// Check whether the given address is a local host address. +// Check whether the given address is a localhost address. export function isLocal(addr: string): boolean { return ( addr.startsWith("127.0.0.1") || @@ -269,27 +279,37 @@ export function twemoji( }); } -export function extractHost(origin: string): Host { +export function extractBaseUrl(hostnamePort: string): BaseUrl { if ( - origin === "radicle.local" || - origin === "radicle.local:8080" || - origin === "0.0.0.0" || - origin === "0.0.0.0:8080" || - origin === "127.0.0.1" || - origin === "127.0.0.1:8080" + hostnamePort === "radicle.local" || + hostnamePort === "radicle.local:8080" || + hostnamePort === "0.0.0.0" || + hostnamePort === "0.0.0.0:8080" || + hostnamePort === "127.0.0.1" || + hostnamePort === "127.0.0.1:8080" ) { - return { host: "127.0.0.1", port: 8080, scheme: "http" }; - } else if (origin.includes(":")) { + return { hostname: "127.0.0.1", port: 8080, scheme: "http" }; + } else if (hostnamePort.includes(":")) { return { - host: origin.split(":")[0], - port: Number(origin.split(":")[1]), + hostname: hostnamePort.split(":")[0], + port: Number(hostnamePort.split(":")[1]), scheme: config.seeds.defaultHttpdScheme, }; } else { return { - host: origin, + hostname: hostnamePort, port: config.seeds.defaultHttpdPort, scheme: config.seeds.defaultHttpdScheme, }; } } + +export function createAddRemoveArrays( + currentArray: string[], + newArray: string[], +): { add: string[]; remove: string[] } { + return { + add: newArray.filter(item => !currentArray.includes(item)), + remove: currentArray.filter(item => !newArray.includes(item)), + }; +} diff --git a/src/views/home/Index.svelte b/src/views/home/Index.svelte index e295b077c..8e7f66f75 100644 --- a/src/views/home/Index.svelte +++ b/src/views/home/Index.svelte @@ -1,14 +1,14 @@ diff --git a/src/views/projects/Cob/CobStateButton.svelte b/src/views/projects/Cob/CobStateButton.svelte index b93aac51d..09c217ea9 100644 --- a/src/views/projects/Cob/CobStateButton.svelte +++ b/src/views/projects/Cob/CobStateButton.svelte @@ -1,6 +1,7 @@ - @@ -95,25 +100,22 @@ {/if} updateRevision(event.detail)} /> - {#if seed.addr.host} - - {/if} + - {#if seed.addr.host} - - {seed.addr.host} - - {/if} + + {baseUrl.hostname} + toggleContent("issues", false)}> - {project.issues.open ?? 0} + {project.issues.open} {pluralize("issue", project.issues.open)} toggleContent("patches", false)}> - {project.patches.open ?? 0} + {project.patches.open} {pluralize("patch", project.patches.open)} diff --git a/src/views/projects/History.svelte b/src/views/projects/History.svelte index c30a637a5..e650dfefb 100644 --- a/src/views/projects/History.svelte +++ b/src/views/projects/History.svelte @@ -1,24 +1,27 @@ - -
-
- {truncateId(seed.id)}@{seed.host} - {#if port !== config.seeds.defaultNodePort} - :{port} - {/if} -
- -
diff --git a/src/views/session/Index.svelte b/src/views/session/Index.svelte index 7ba4fc6f8..b3b949e58 100644 --- a/src/views/session/Index.svelte +++ b/src/views/session/Index.svelte @@ -14,11 +14,14 @@ export let activeRoute: Extract; onMount(async () => { - const status = await session.authenticate(activeRoute.params); + const isAuthenticated = await session.authenticate(activeRoute.params); - if (status === "success") { + if (isAuthenticated) { modal.show({ component: AuthenticatedModal, props: {} }); - router.push({ resource: "seeds", params: { host: "radicle.local" } }); + router.push({ + resource: "seeds", + params: { hostnamePort: "radicle.local" }, + }); } else { modal.show({ component: AuthenticationErrorModal, diff --git a/tests/e2e/hotkeys.spec.ts b/tests/e2e/hotkeys.spec.ts index 1d3d5374c..942f51a4d 100644 --- a/tests/e2e/hotkeys.spec.ts +++ b/tests/e2e/hotkeys.spec.ts @@ -1,6 +1,6 @@ import { test, expect } from "@tests/support/fixtures.js"; -const searchPlaceholder = "Search a name…"; +const searchPlaceholder = "Search a RID…"; test("global hotkeys", async ({ page }) => { await page.goto("/"); diff --git a/tests/e2e/search.spec.ts b/tests/e2e/search.spec.ts index d99b3f440..f07981043 100644 --- a/tests/e2e/search.spec.ts +++ b/tests/e2e/search.spec.ts @@ -7,7 +7,7 @@ import { test("navigate to existing project", async ({ page }) => { await page.goto("/"); - const searchInput = page.getByPlaceholder("Search a name…"); + const searchInput = page.getByPlaceholder("Search a RID…"); await searchInput.click(); await searchInput.fill(`${rid}`); await searchInput.press("Enter"); @@ -18,7 +18,7 @@ test("navigate to existing project", async ({ page }) => { test("navigate to a project that does not exist", async ({ page }) => { await page.goto("/"); - const searchInput = page.getByPlaceholder("Search a name…"); + const searchInput = page.getByPlaceholder("Search a RID…"); await searchInput.click(); const nonExistantId = "rad:zAAAAAAAAAAAAAAAAAAAAAAAAAAA"; diff --git a/tests/e2e/seed.spec.ts b/tests/e2e/seed.spec.ts index 2b1c498e9..7817920bd 100644 --- a/tests/e2e/seed.spec.ts +++ b/tests/e2e/seed.spec.ts @@ -3,7 +3,6 @@ import { expect, rid, seedRemote, - seedVersion, test, } from "@tests/support/fixtures.js"; @@ -15,7 +14,7 @@ test("seed metadata", async ({ page }) => { await expect( page.locator(`text=${seedRemote.substring(0, 6)}…${seedRemote.slice(-6)}`), ).toBeVisible(); - await expect(page.locator(`text=${seedVersion}`)).toBeVisible(); + await expect(page.locator(`text=0.1.0-`)).toBeVisible(); }); test("seed projects", async ({ page }) => { diff --git a/tests/support/fixtures.ts b/tests/support/fixtures.ts index 04c630fe9..cad767f5f 100644 --- a/tests/support/fixtures.ts +++ b/tests/support/fixtures.ts @@ -52,7 +52,15 @@ export const test = base.extend<{ defaultHttpdPort: 8080, defaultHttpdScheme: "http", defaultNodePort: 8776, - pinned: [{ host: "127.0.0.1" }], + pinned: [ + { + baseUrl: { + hostname: "127.0.0.1", + port: 8080, + scheme: "http", + }, + }, + ], }, projects: { pinned: [] }, }; @@ -134,14 +142,26 @@ export function configFixture() { defaultHttpdPort: 8080, defaultHttpdScheme: "http", defaultNodePort: 8776, - pinned: [{ host: "127.0.0.1" }], + pinned: [ + { + baseUrl: { + hostname: "127.0.0.1", + port: 8080, + scheme: "http", + }, + }, + ], }, projects: { pinned: [ { name: "source-browsing", id: "rad:git:hnrkdi8be7n4hhqoz9rpzrgd68u9dr3zsxgmy", - seed: "127.0.0.1", + baseUrl: { + hostname: "127.0.0.1", + port: 8080, + scheme: "http", + }, }, ], }, @@ -155,14 +175,26 @@ export function appConfigWithFixture() { defaultHttpdPort: 8080, defaultHttpdScheme: "http", defaultNodePort: 8776, - pinned: [{ host: "127.0.0.1" }], + pinned: [ + { + baseUrl: { + hostname: "127.0.0.1", + port: 8080, + scheme: "http", + }, + }, + ], }, projects: { pinned: [ { name: "source-browsing", id: "rad:zKtT7DmF9H34KkvcKj9PHW19WzjT", - seed: "127.0.0.1", + baseUrl: { + hostname: "127.0.0.1", + port: 8080, + scheme: "http", + }, }, ], }, @@ -177,5 +209,4 @@ export const bobRemote = export const rid = "rad:zKtT7DmF9H34KkvcKj9PHW19WzjT"; export const projectFixtureUrl = `/seeds/127.0.0.1/${rid}`; export const seedPort = 8080; -export const seedVersion = "0.1.0-6463768"; export const seedRemote = "z6Mkk7oqY4pPxhMmGEotDYsFo97vhCj85BLY1H256HrJmjN8"; diff --git a/tests/unit/cobs.test.ts b/tests/unit/cobs.test.ts deleted file mode 100644 index 813965800..000000000 --- a/tests/unit/cobs.test.ts +++ /dev/null @@ -1,26 +0,0 @@ -import { describe, expect, test } from "vitest"; -import * as issue from "@app/lib/issue"; - -describe("Issues", () => { - test.each([ - { - currentArray: ["a", "b"], - newArray: ["a", "b", "c"], - expected: { add: ["c"], remove: [] }, - }, - { - currentArray: ["a", "b"], - newArray: ["c"], - expected: { add: ["c"], remove: ["a", "b"] }, - }, - { currentArray: [], newArray: ["c"], expected: { add: ["c"], remove: [] } }, - { currentArray: ["a"], newArray: ["a"], expected: { add: [], remove: [] } }, - ])( - "createAssigneeArrays $hash => $expected", - ({ currentArray, newArray, expected }) => { - expect(issue.createAddRemoveArrays(currentArray, newArray)).toEqual( - expected, - ); - }, - ); -}); diff --git a/tests/unit/router.test.ts b/tests/unit/router.test.ts index c94874b85..0500a86a4 100644 --- a/tests/unit/router.test.ts +++ b/tests/unit/router.test.ts @@ -9,7 +9,10 @@ describe("routeToPath", () => { test.each([ { input: { resource: "home" }, output: "/", description: "Home Route" }, { - input: { resource: "seeds", params: { host: "willow.radicle.garden" } }, + input: { + resource: "seeds", + params: { hostnamePort: "willow.radicle.garden" }, + }, output: "/seeds/willow.radicle.garden", description: "Seed View Route", }, @@ -18,7 +21,7 @@ describe("routeToPath", () => { resource: "projects", params: { view: { resource: "tree" }, - seed: "willow.radicle.garden", + hostnamePort: "willow.radicle.garden", id: "rad:zKtT7DmF9H34KkvcKj9PHW19WzjT", }, }, @@ -41,7 +44,10 @@ describe("pathToRoute", () => { { input: "/", output: { resource: "home" }, description: "Home Route" }, { input: "/seeds/willow.radicle.garden", - output: { resource: "seeds", params: { host: "willow.radicle.garden" } }, + output: { + resource: "seeds", + params: { hostnamePort: "willow.radicle.garden" }, + }, description: "Seed View Route", }, { @@ -50,7 +56,7 @@ describe("pathToRoute", () => { resource: "projects", params: { view: { resource: "tree" }, - seed: "willow.radicle.garden", + hostnamePort: "willow.radicle.garden", profile: undefined, peer: undefined, id: "rad:zKtT7DmF9H34KkvcKj9PHW19WzjT", @@ -70,7 +76,7 @@ describe("pathToRoute", () => { resource: "projects", params: { view: { resource: "tree" }, - seed: "willow.radicle.garden", + hostnamePort: "willow.radicle.garden", profile: undefined, peer: undefined, id: "rad:zKtT7DmF9H34KkvcKj9PHW19WzjT", diff --git a/tests/unit/utils.test.ts b/tests/unit/utils.test.ts index 4afd9d28a..4d44e15db 100644 --- a/tests/unit/utils.test.ts +++ b/tests/unit/utils.test.ts @@ -272,3 +272,27 @@ describe("Date Manipulation", () => { ); }); }); + +describe("createAddRemoveArrays", () => { + test.each([ + { + currentArray: ["a", "b"], + newArray: ["a", "b", "c"], + expected: { add: ["c"], remove: [] }, + }, + { + currentArray: ["a", "b"], + newArray: ["c"], + expected: { add: ["c"], remove: ["a", "b"] }, + }, + { currentArray: [], newArray: ["c"], expected: { add: ["c"], remove: [] } }, + { currentArray: ["a"], newArray: ["a"], expected: { add: [], remove: [] } }, + ])( + "createAssigneeArrays $hash => $expected", + ({ currentArray, newArray, expected }) => { + expect(utils.createAddRemoveArrays(currentArray, newArray)).toEqual( + expected, + ); + }, + ); +}); diff --git a/tsconfig.json b/tsconfig.json index 68d913e32..998fcbbe9 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -1,6 +1,6 @@ { "extends": "@tsconfig/svelte/tsconfig.json", - "include": ["src", "tests"], + "include": ["src", "tests", "httpd-client"], "exclude": ["node_modules/*"], "compilerOptions": { "target": "es2020", @@ -17,6 +17,8 @@ "skipLibCheck": true, "paths": { "@app/*": ["./src/*"], + "@httpd-client": ["./httpd-client/index.ts"], + "@httpd-client/*": ["./httpd-client/*"], "@public/*": ["./public/*"], "@tests/*": ["./tests/*"] } diff --git a/vite.config.ts b/vite.config.ts index 411bc7b05..60a5846b8 100644 --- a/vite.config.ts +++ b/vite.config.ts @@ -32,6 +32,7 @@ export default defineConfig({ alias: { "@app": path.resolve("./src"), "@public": path.resolve("./public"), + "@httpd-client": path.resolve("./httpd-client"), }, }, build: {