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

ForgejoCli.ts

758 lines27.5 KB

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