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