Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

ForgejoCli.ts

722 lines26.2 KB

1import * as Context from "effect/Context";
2import * as Effect from "effect/Effect";
3import * as Layer from "effect/Layer";
4import * as Schema from "effect/Schema";
5import * as Result from "effect/Result";
6import * as Clock from "effect/Clock";
7import * as FileSystem from "effect/FileSystem";
8import * as Semaphore from "effect/Semaphore";
9// @effect-diagnostics-next-line nodeBuiltinImport:off - fj storage paths use explicit Windows and POSIX layouts, independently of this process's platform.
10import * as NodePath from "node:path";
11import { FetchHttpClient, HttpClient, HttpClientRequest } from "effect/http";
12import { ChildProcessSpawner } from "effect/process";
13import { decodeJsonResult } from "@t3tools/shared/schemaJson";
14import * as HostProcess from "@t3tools/shared/HostProcess";
15import * as SourceControlHost from "@t3tools/source-control-core/server/SourceControlHost";
16import { collectUint8StreamText } from "@t3tools/provider-core/server/collectStreamText";
17import type { SourceControlProviderContext } from "@t3tools/source-control-core/server/SourceControlProvider";
18​
19const encodeApiBody = Schema.encodeEffect(Schema.fromJsonString(Schema.Unknown));
20​
21export class ForgejoCliError extends Schema.TaggedError<ForgejoCliError>()("ForgejoCliError", {
22 command: Schema.Literals(["fj", "tea"]),
23 cwd: Schema.String,
24 detail: Schema.String,
25 reason: Schema.optional(
26 Schema.Literals([
27 "missing-cli",
28 "authentication",
29 "forbidden",
30 "not-found",
31 "rate-limit",
32 "invalid-response",
33 ]),
34 ),
35 httpStatus: Schema.optional(Schema.Int),
36 cause: Schema.optional(Schema.Defect()),
37}) {}
38​
39export const ForgejoLoginSchema = Schema.Struct({
40 name: Schema.String,
41 url: Schema.String,
42 ssh_host: Schema.optional(Schema.String),
43 valid: Schema.optional(Schema.String),
44 user: Schema.String,
45 default: Schema.String,
46});
47​
48export function parseForgejoLogins(raw: string) {
49 const decoded = decodeJsonResult(Schema.Array(ForgejoLoginSchema))(raw);
50 return Result.isSuccess(decoded) ? decoded.success : [];
52​
53export const ForgejoKeysSchema = Schema.Struct({
54 hosts: Schema.Record(
55 Schema.String,
56 Schema.Struct({
57 type: Schema.Literals(["Application", "OAuth"]),
58 token: Schema.String,
59 }),
60 ),
61 aliases: Schema.optional(Schema.Record(Schema.String, Schema.String)),
62});
63​
64const parseForgejoKeys = decodeJsonResult(ForgejoKeysSchema);
65​
66function forgejoKeysPaths(input: {
67 readonly platform: string;
68 readonly home: string;
69 readonly dataHome?: string;
70 readonly appData?: string;
71}) {
72 if (input.platform === "darwin")
73 return ["forgejo-cli", "Cyborus"].map((organization) =>
74 NodePath.join(
75 input.home,
76 "Library",
77 "Application Support",
78 `${organization}.forgejo-cli`,
79 "keys.json",
80 ),
81 );
82 if (input.platform === "win32")
83 return ["forgejo-cli", "Cyborus"].map((organization) =>
84 NodePath.win32.join(
85 input.appData || NodePath.win32.join(input.home, "AppData", "Roaming"),
86 organization,
87 "forgejo-cli",
88 "data",
89 "keys.json",
90 ),
91 );
92 return [
93 NodePath.join(
94 input.dataHome && NodePath.isAbsolute(input.dataHome)
95 ? input.dataHome
96 : NodePath.join(input.home, ".local", "share"),
97 "forgejo-cli",
98 "keys.json",
99 ),
100 ];
102​
103export interface ForgejoRepositoryInput {
104 readonly cwd: string;
105 readonly context?: SourceControlProviderContext;
106 readonly repository?: string;
107 readonly reference?: string;
108 readonly host?: string;
110​
111export interface ForgejoRepository {
112 readonly command?: "fj" | "tea";
113 readonly login: string;
114 readonly repository: string;
115 readonly baseUrl: string;
117​
118export interface ForgejoApiInput extends ForgejoRepositoryInput {
119 readonly path: string;
120 readonly method?: "GET" | "POST" | "PUT" | "PATCH" | "DELETE";
121 readonly body?: unknown;
123​
124export class ForgejoCli extends Context.Service<
125 ForgejoCli,
126 {
127 readonly execute: (input: {
128 readonly command?: "fj" | "tea";
129 readonly cwd: string;
130 readonly args: ReadonlyArray<string>;
131 readonly stdin?: string;
132 readonly timeoutMs?: number;
133 readonly maxOutputBytes?: number;
134 }) => Effect.Effect<SourceControlHost.SourceControlProcessOutput, ForgejoCliError>;
135 readonly listLogins?: (input: {
136 readonly cwd: string;
137 readonly command: "fj" | "tea";
138 readonly remoteUrl?: string;
139 }) => Effect.Effect<ReturnType<typeof parseForgejoLogins>, ForgejoCliError>;
140 readonly getAccount?: (input: {
141 readonly cwd: string;
142 readonly baseUrl: string;
143 }) => Effect.Effect<string, ForgejoCliError>;
144 readonly resolveRepository: (
145 input: ForgejoRepositoryInput,
146 ) => Effect.Effect<ForgejoRepository, ForgejoCliError>;
147 readonly api: (
148 input: ForgejoApiInput,
149 ) => Effect.Effect<SourceControlHost.SourceControlProcessOutput, ForgejoCliError>;
150 }
151>()("@t3tools/source-control-forgejo/server/ForgejoCli") {}
152​
153export function parseForgejoRemote(value: string) {
154 if (/^(?:https?|ssh):\/\//i.test(value)) {
155 try {
156 const url = new URL(value);
157 return {
158 host: url.host.toLowerCase(),
159 hostname: url.hostname.toLowerCase(),
160 ssh: url.protocol === "ssh:",
161 path: url.pathname.replace(/^\/+|\/+$/g, "").replace(/\.git$/, ""),
162 };
163 } catch {
164 return null;
165 }
166 }
167 // SCP remotes may omit the username; URL treats these as a custom scheme.
168 const ssh = /^(?:[^@/]+@)?([^:/]+):([^/].*)$/.exec(value);
169 return ssh?.[1] && ssh[2]
170 ? {
171 host: ssh[1].toLowerCase(),
172 hostname: ssh[1].toLowerCase(),
173 ssh: true,
174 path: ssh[2].replace(/\.git$/, ""),
175 }
176 : null;
178​
179export function matchForgejoLogin(
180 logins: ReturnType<typeof parseForgejoLogins>,
181 remote: NonNullable<ReturnType<typeof parseForgejoRemote>>,
182 requestedHost?: string,
183 hostOnly = false,
184) {
185 const matches = [
186 ...new Map(
187 logins
188 .filter((login) => {
189 const url = parseForgejoRemote(login.url);
190 if (!url) return false;
191 if (requestedHost !== undefined && url.host !== requestedHost.toLowerCase()) return false;
192 return remote.ssh
193 ? login.ssh_host?.toLowerCase() === remote.host ||
194 login.ssh_host?.toLowerCase() === remote.hostname ||
195 url.hostname === remote.hostname
196 : url.host === remote.host &&
197 ((hostOnly && !remote.path) ||
198 !url.path ||
199 remote.path === url.path ||
200 remote.path.startsWith(`${url.path}/`));
201 })
202 .map((login) => [login.name, login]),
203 ).values(),
204 ];
205 return matches.length === 1
206 ? matches[0]
207 : new Set(matches.map((login) => login.url)).size === 1
208 ? matches.find((login) => login.default === "true")
209 : undefined;
211​
212export const make = Effect.gen(function* () {
213 const { process } = yield* SourceControlHost.SourceControlHost;
214 const fileSystem = yield* FileSystem.FileSystem;
215 const httpClient = yield* HttpClient.HttpClient;
216 const authLock = yield* Semaphore.make(1);
217 const authenticated = new Map<string, { token: string; time: number }>();
218 const execute: ForgejoCli["Service"]["execute"] = (input) =>
219 process
220 .run({
221 ...input,
222 operation: "ForgejoCli.execute",
223 command: input.command ?? "tea",
224 timeoutMs: input.timeoutMs ?? 30_000,
225 })
226 .pipe(
227 Effect.mapError(
228 (cause) =>
229 new ForgejoCliError({
230 command: input.command ?? "tea",
231 cwd: input.cwd,
232 ...(input.command === "fj" ? {} : { cause }),
233 ...(cause._tag === "VcsProcessSpawnError"
234 ? { reason: "missing-cli" as const }
235 : cause._tag === "VcsProcessExitError" && cause.failureKind === "authentication"
236 ? { reason: "authentication" as const }
237 : {}),
238 detail:
239 cause._tag === "VcsProcessSpawnError"
240 ? "Install Forgejo CLI (`fj` 0.6 or later) or Gitea CLI (`tea` 0.16 or later) and retry."
241 : cause._tag === "VcsProcessExitError" && cause.failureKind === "authentication"
242 ? "Authenticate this server with `fj auth login`, `fj auth add-token`, or `tea login add`."
243 : "Forgejo CLI command failed.",
244 }),
245 ),
246 );
247​
248 const readKeys = Effect.fn("ForgejoCli.readKeys")(function* (cwd: string) {
249 for (const path of forgejoKeysPaths({
250 platform: yield* HostProcess.Platform,
251 home: yield* HostProcess.HomeDirectory,
252 ...(globalThis.process.env.XDG_DATA_HOME
253 ? { dataHome: globalThis.process.env.XDG_DATA_HOME }
254 : {}),
255 ...(globalThis.process.env.APPDATA ? { appData: globalThis.process.env.APPDATA } : {}),
256 })) {
257 const exists = yield* fileSystem.exists(path).pipe(
258 Effect.mapError(
259 () =>
260 new ForgejoCliError({
261 command: "fj",
262 cwd,
263 reason: "authentication",
264 detail: "Could not read fj authentication storage.",
265 }),
266 ),
267 );
268 if (!exists) continue;
269 const raw = yield* fileSystem.readFileString(path).pipe(
270 Effect.mapError(
271 () =>
272 new ForgejoCliError({
273 command: "fj",
274 cwd,
275 reason: "authentication",
276 detail: "Could not read fj authentication storage.",
277 }),
278 ),
279 );
280 const decoded = parseForgejoKeys(raw);
281 if (Result.isFailure(decoded))
282 return yield* new ForgejoCliError({
283 command: "fj",
284 cwd,
285 reason: "authentication",
286 detail: "fj authentication storage is invalid. Authenticate again with fj.",
287 });
288 return decoded.success;
289 }
290 const empty: typeof ForgejoKeysSchema.Type = { hosts: {}, aliases: {} };
291 return empty;
292 });
293​
294 const publicLogins = (
295 keys: typeof ForgejoKeysSchema.Type,
296 remoteUrl?: string,
297 ): ReturnType<typeof parseForgejoLogins> => {
298 const remote = remoteUrl ? parseForgejoRemote(remoteUrl) : null;
299 return Object.keys(keys.hosts).flatMap((host) => {
300 const url = parseForgejoRemote(`https://${host}`);
301 // fj 0.6 drops URL mounts during whoami and OAuth renewal; tea supports them.
302 if (!url || url.path) return [];
303 // fj omits the scheme in storage. Only an explicit matching HTTP remote opts into HTTP.
304 const scheme =
305 remote && !remote.ssh && remote.host === url.host && /^http:\/\//i.test(remoteUrl ?? "")
306 ? "http"
307 : "https";
308 const login = { name: host, url: `${scheme}://${host}`, user: "", default: "false" };
309 const aliases = Object.entries(keys.aliases ?? {})
310 .filter(([, target]) => target === host)
311 .map(([alias]) => ({ ...login, ssh_host: alias }));
312 return aliases.length ? aliases : [login];
313 });
314 };
315​
316 const listLogins: NonNullable<ForgejoCli["Service"]["listLogins"]> = Effect.fn(
317 "ForgejoCli.listLogins",
318 )(function* (input) {
319 if (input.command === "fj") {
320 const keys = yield* readKeys(input.cwd).pipe(Effect.result);
321 if (Result.isFailure(keys)) {
322 // Stale credentials from an uninstalled fj must not disable an available tea login.
323 const available = yield* execute({ command: "fj", cwd: input.cwd, args: ["version"] }).pipe(
324 Effect.result,
325 );
326 if (Result.isFailure(available) && available.failure.reason === "missing-cli") return [];
327 return yield* keys.failure;
328 }
329 return publicLogins(keys.success, input.remoteUrl);
330 }
331 return parseForgejoLogins(
332 (yield* execute({ cwd: input.cwd, args: ["login", "list", "--output", "json"] })).stdout,
333 );
334 });
335​
336 const requestFj = Effect.fn("ForgejoCli.requestFj")(
337 function* (input: {
338 readonly cwd: string;
339 readonly baseUrl: string;
340 readonly token: string;
341 readonly path: string;
342 readonly method?: ForgejoApiInput["method"];
343 readonly body?: string;
344 }) {
345 const base = new URL(`${input.baseUrl}/api/v1/`);
346 const url = new URL(input.path, base);
347 if (
348 url.origin !== base.origin ||
349 !url.pathname.startsWith(base.pathname) ||
350 url.username ||
351 url.password
352 )
353 return yield* new ForgejoCliError({
354 command: "fj",
355 cwd: input.cwd,
356 detail: "Invalid Forgejo API path.",
357 });
358 let request = HttpClientRequest.make(input.method ?? "GET")(url.toString()).pipe(
359 HttpClientRequest.setHeader("Authorization", `token ${input.token}`),
360 );
361 if (input.body !== undefined)
362 request = request.pipe(HttpClientRequest.bodyText(input.body, "application/json"));
363 const response = yield* httpClient
364 .execute(request)
365 .pipe(Effect.provideService(FetchHttpClient.RequestInit, { redirect: "manual" }));
366 const status = response.status;
367 const body =
368 status === 204 || status === 205
369 ? { text: "", truncated: false, invalidUtf8: false }
370 : yield* collectUint8StreamText({
371 stream: response.stream,
372 maxBytes: 8 * 1024 * 1024,
373 });
374 if (body.truncated || body.invalidUtf8)
375 return yield* new ForgejoCliError({
376 command: "fj",
377 cwd: input.cwd,
378 reason: "invalid-response",
379 detail: "Forgejo returned an oversized or invalid response.",
380 });
381 if (status < 200 || status >= 300) {
382 const detail =
383 status === 404
384 ? "Forgejo repository or pull request was not found."
385 : body.text
386 ? `Forgejo API request failed (HTTP ${status}): ${body.text}`
387 : `Forgejo API request failed (HTTP ${status}). Check this server's fj credentials and permissions.`;
388 return yield* new ForgejoCliError({
389 command: "fj",
390 cwd: input.cwd,
391 httpStatus: status,
392 ...(status === 401
393 ? { reason: "authentication" as const }
394 : status === 403
395 ? { reason: "forbidden" as const }
396 : status === 404
397 ? { reason: "not-found" as const }
398 : status === 429
399 ? { reason: "rate-limit" as const }
400 : {}),
401 detail,
402 });
403 }
404 return {
405 exitCode: ChildProcessSpawner.ExitCode(0),
406 stdout: body.text,
407 stderr: `HTTP/1.1 ${status}\n${response.headers.link ? `link: ${response.headers.link}\n` : ""}`,
408 stdoutTruncated: false,
409 stderrTruncated: false,
410 };
411 },
412 (effect, input) =>
413 effect.pipe(
414 Effect.timeout(30_000),
415 Effect.mapError((error) =>
416 error._tag === "ForgejoCliError"
417 ? error
418 : new ForgejoCliError({
419 command: "fj",
420 cwd: input.cwd,
421 detail: "Forgejo API request failed or timed out.",
422 }),
423 ),
424 ),
425 );
426​
427 const authenticateFj = Effect.fn("ForgejoCli.authenticateFj")(function* (
428 cwd: string,
429 login: typeof ForgejoLoginSchema.Type,
430 ) {
431 const keys = yield* readKeys(cwd);
432 const token = keys.hosts[login.name]?.token;
433 const now = yield* Clock.currentTimeMillis;
434 const cached = authenticated.get(login.url);
435 if (token && cached?.token === token && now - cached.time < 30_000) return token;
436 yield* execute({ command: "fj", cwd, args: ["--host", login.url, "whoami"] });
437 // fj owns OAuth renewal. Re-read the file after it has refreshed an expired token.
438 const refreshed = (yield* readKeys(cwd)).hosts[login.name]?.token;
439 if (!refreshed)
440 return yield* new ForgejoCliError({
441 command: "fj",
442 cwd,
443 reason: "authentication",
444 detail: "fj has no credentials for this server. Authenticate again with fj.",
445 });
446 authenticated.set(login.url, { token: refreshed, time: now });
447 return refreshed;
448 }, authLock.withPermits(1));
449​
450 const getAccount: NonNullable<ForgejoCli["Service"]["getAccount"]> = Effect.fn(
451 "ForgejoCli.getAccount",
452 )(function* (input) {
453 const logins = yield* listLogins({ cwd: input.cwd, command: "fj", remoteUrl: input.baseUrl });
454 const login = logins.find(
455 (item) => item.url.replace(/\/+$/, "") === input.baseUrl.replace(/\/+$/, ""),
456 );
457 if (!login)
458 return yield* new ForgejoCliError({
459 command: "fj",
460 cwd: input.cwd,
461 reason: "authentication",
462 detail: "fj has no credentials for this server.",
463 });
464 const token = yield* authenticateFj(input.cwd, login);
465 const currentUser = yield* requestFj({
466 cwd: input.cwd,
467 baseUrl: login.url.replace(/\/+$/, ""),
468 token,
469 path: "user",
470 });
471 const user = decodeJsonResult(Schema.Struct({ login: Schema.String }))(currentUser.stdout);
472 if (Result.isFailure(user) || !user.success.login.trim())
473 return yield* new ForgejoCliError({
474 command: "fj",
475 cwd: input.cwd,
476 reason: "invalid-response",
477 detail: "Forgejo returned an invalid account response.",
478 });
479 return user.success.login;
480 });
481​
482 const resolveTarget = Effect.fn("ForgejoCli.resolveTarget")(function* (
483 input: ForgejoRepositoryInput,
484 hostOnly = false,
485 ) {
486 const referenceRemote = input.reference ? parseForgejoRemote(input.reference) : null;
487 let remoteUrl = [input.reference, input.repository, input.context?.remoteUrl].find(
488 (value) => value && parseForgejoRemote(value),
489 );
490 let remote =
491 referenceRemote ??
492 (input.repository ? parseForgejoRemote(input.repository) : null) ??
493 (input.context ? parseForgejoRemote(input.context.remoteUrl) : null);
494 if (!remote && (!input.repository || input.host)) {
495 const result = yield* process
496 .run({
497 operation: "ForgejoCli.remote",
498 command: "git",
499 args: input.host ? ["remote", "-v"] : ["remote", "get-url", "origin"],
500 cwd: input.cwd,
501 allowNonZeroExit: true,
502 })
503 .pipe(
504 Effect.mapError(
505 (cause) =>
506 new ForgejoCliError({
507 command: "tea",
508 cwd: input.cwd,
509 detail: "Could not resolve the Forgejo repository remote.",
510 cause,
511 }),
512 ),
513 );
514 if (input.host) {
515 const matchingUrls = [
516 ...new Set(
517 result.stdout.split("\n").flatMap((line) => {
518 const url = /^\S+\s+(https?:\/\/\S+)\s+\(fetch\)$/.exec(line.trim())?.[1];
519 return url && parseForgejoRemote(url)?.host === input.host?.toLowerCase()
520 ? [url]
521 : [];
522 }),
523 ),
524 ];
525 const origins = [...new Set(matchingUrls.map((url) => new URL(url).origin))];
526 remoteUrl =
527 matchingUrls.length === 1
528 ? matchingUrls[0]
529 : origins.length === 1
530 ? origins[0]
531 : undefined;
532 } else {
533 remoteUrl = result.stdout.trim();
534 }
535 remote = remoteUrl ? parseForgejoRemote(remoteUrl) : null;
536 }
537 if (
538 input.host &&
539 !remote?.ssh &&
540 remote?.host !== input.host.toLowerCase() &&
541 remote?.hostname !== input.host.toLowerCase()
542 )
543 remote = {
544 host: input.host.toLowerCase(),
545 hostname: input.host.split(":")[0] ?? input.host,
546 ssh: false,
547 path: remote?.path ?? "",
548 };
549 const schemeRemoteUrl = remote?.ssh ? input.context?.provider.baseUrl : remoteUrl;
550 const fjLogins = yield* listLogins({
551 cwd: input.cwd,
552 command: "fj",
553 ...(schemeRemoteUrl ? { remoteUrl: schemeRemoteUrl } : {}),
554 });
555 const requestedHost = input.host ?? input.context?.requestedHost;
556 const matchHostOnly = hostOnly || (!!input.host && !remote?.path);
557 const selectLogin = (logins: ReturnType<typeof parseForgejoLogins>) =>
558 remote
559 ? matchForgejoLogin(logins, remote, remote.ssh ? requestedHost : undefined, matchHostOnly)
560 : (logins.find((item) => item.default === "true") ??
561 (new Set(logins.map((item) => item.name)).size === 1 ? logins[0] : undefined));
562 let login = selectLogin(fjLogins);
563 let command: "fj" | "tea" = "fj";
564 if (
565 !login &&
566 fjLogins.some(
567 (item) =>
568 !remote ||
569 matchForgejoLogin([item], remote, remote.ssh ? requestedHost : undefined, matchHostOnly),
570 )
571 ) {
572 const available = yield* execute({ command: "fj", cwd: input.cwd, args: ["version"] }).pipe(
573 Effect.result,
574 );
575 if (Result.isSuccess(available))
576 return yield* new ForgejoCliError({
577 command: "fj",
578 cwd: input.cwd,
579 reason: "authentication",
580 detail: "Multiple fj logins match this repository. Specify its full server URL.",
581 });
582 if (available.failure.reason !== "missing-cli") return yield* available.failure;
583 }
584 if (login) {
585 const auth = yield* authenticateFj(input.cwd, login).pipe(Effect.result);
586 if (Result.isFailure(auth)) {
587 if (auth.failure.reason === "missing-cli") login = undefined;
588 else return yield* auth.failure;
589 }
590 }
591 if (!login) {
592 command = "tea";
593 login = selectLogin(yield* listLogins({ cwd: input.cwd, command: "tea" }));
594 }
595 if (!login)
596 return yield* new ForgejoCliError({
597 command: "tea",
598 cwd: input.cwd,
599 reason: "authentication",
600 detail:
601 "No matching Forgejo login. Use `fj auth login`, `fj auth add-token`, or `tea login add` for this server; choose a default when multiple tea accounts match.",
602 });
603 if (hostOnly)
604 return { command, login: login.name, repository: "", baseUrl: login.url.replace(/\/+$/, "") };
605 const path =
606 referenceRemote?.path ??
607 (input.repository && !parseForgejoRemote(input.repository)
608 ? input.repository
609 : remote?.path) ??
610 "";
611 const basePath = new URL(login.url).pathname.replace(/^\/+|\/+$/g, "");
612 const relativePath =
613 basePath && path.split("/").length > 2 && path.startsWith(`${basePath}/`)
614 ? path.slice(basePath.length + 1)
615 : path;
616 const repositoryPath = relativePath.replace(/\/pulls\/\d+.*$/, "").replace(/\.git$/, "");
617 if (command === "fj" && !repositoryPath.includes("/")) {
618 login = { ...login, user: yield* getAccount({ cwd: input.cwd, baseUrl: login.url }) };
619 }
620 const repository = repositoryPath.includes("/")
621 ? repositoryPath
622 : `${login.user}/${repositoryPath}`;
623 if (!/^[^/\s]+\/[^/\s]+$/.test(repository))
624 return yield* new ForgejoCliError({
625 command,
626 cwd: input.cwd,
627 detail: "Specify a Forgejo repository as owner/repository or its full server URL.",
628 });
629 return { command, login: login.name, repository, baseUrl: login.url.replace(/\/+$/, "") };
630 });
631 const resolveRepository = (input: ForgejoRepositoryInput) => resolveTarget(input);
632 const api = Effect.fn("ForgejoCli.api")(function* (input: ForgejoApiInput) {
633 const repository = yield* resolveTarget(
634 input,
635 input.path.replace(/^\/+/, "") === "user" && (!input.method || input.method === "GET"),
636 );
637 const stdin =
638 input.body === undefined
639 ? undefined
640 : yield* encodeApiBody(input.body).pipe(
641 Effect.mapError(
642 (cause) =>
643 new ForgejoCliError({
644 command: "tea",
645 cwd: input.cwd,
646 detail: "Could not encode the Forgejo request body.",
647 cause,
648 }),
649 ),
650 );
651 let path = input.path.replace(/^\/+/, "");
652 if (input.repository && input.repository !== repository.repository) {
653 // Repository identities retain the server mount path; API routes do not.
654 const prefix = `repos/${input.repository.split("/").map(encodeURIComponent).join("/")}`;
655 if (path === prefix || path.startsWith(`${prefix}/`) || path.startsWith(`${prefix}?`)) {
656 path = `repos/${repository.repository.split("/").map(encodeURIComponent).join("/")}${path.slice(prefix.length)}`;
657 }
658 }
659 if (repository.command === "fj") {
660 const token = (yield* readKeys(input.cwd)).hosts[repository.login]?.token;
661 if (!token)
662 return yield* new ForgejoCliError({
663 command: "fj",
664 cwd: input.cwd,
665 reason: "authentication",
666 detail: "fj has no credentials for this server.",
667 });
668 return yield* requestFj({
669 cwd: input.cwd,
670 baseUrl: repository.baseUrl,
671 token,
672 path,
673 ...(input.method === undefined ? {} : { method: input.method }),
674 ...(stdin === undefined ? {} : { body: stdin }),
675 });
676 }
677 const result = yield* execute({
678 cwd: input.cwd,
679 args: [
680 "api",
681 "--include",
682 "--login",
683 repository.login,
684 ...(repository.repository ? ["--repo", repository.repository] : []),
685 "--method",
686 input.method ?? "GET",
687 ...(input.body === undefined ? [] : ["--data", "@-"]),
688 `${repository.baseUrl}/api/v1/${path}`,
689 ],
690 ...(stdin === undefined ? {} : { stdin }),
691 });
692 // tea reports HTTP failures with exit code zero; use its response status.
693 const status = Number(/^HTTP\/\S+ (\d{3})/m.exec(result.stderr)?.[1]);
694 if (!status || status >= 400)
695 return yield* new ForgejoCliError({
696 command: "tea",
697 cwd: input.cwd,
698 ...(status ? { httpStatus: status } : {}),
699 ...(status === 401
700 ? { reason: "authentication" as const }
701 : status === 403
702 ? { reason: "forbidden" as const }
703 : status === 404
704 ? { reason: "not-found" as const }
705 : status === 429
706 ? { reason: "rate-limit" as const }
707 : {}),
708 detail:
709 status === 401 || status === 403
710 ? "Forgejo denied access. Check this server's `tea login` credentials and permissions."
711 : status === 404
712 ? "Forgejo repository or pull request was not found."
713 : status === 429
714 ? "Forgejo API rate limit exceeded."
715 : `Forgejo API request failed${status ? ` (HTTP ${status})` : " without an HTTP status"}.`,
716 });
717 return result;
718 });
719 return ForgejoCli.of({ execute, listLogins, getAccount, resolveRepository, api });
720});
721​
722export const layer = Layer.effect(ForgejoCli, make);