Open History to see the last commit
1import type { SourceControlMediaRequest } from "@t3tools/source-control-core/server/driver";
2import * as Effect from "effect/Effect";
3import * as Redacted from "effect/Redacted";
4import {
5 FetchHttpClient,
6 HttpClient,
7 HttpClientRequest,
8 type HttpClientResponse,
9} from "effect/http";
10
11import * as Credentials from "./TanStackSourceCredentials.ts";
12import * as Hosts from "./tanStackSourceHosts.ts";
13
14const MAX_REDIRECTS = 3;
15const MANUAL_REDIRECT: RequestInit = { redirect: "manual" };
16
17/** The token only goes to Source itself, never to a host a redirect names. */
18const sourceHost = (url: URL) =>
19 url.protocol === "https:" && url.port === "" ? Hosts.tanStackSourceHost(url.hostname) : null;
20
21export const make = Effect.gen(function* () {
22 const credentials = yield* Credentials.TanStackSourceCredentials;
23 const httpClient = HttpClient.withScope(yield* HttpClient.HttpClient);
24
25 return Effect.fn("TanStackSourceMediaFetch.fetchMedia")(function* (
26 request: SourceControlMediaRequest,
27 ) {
28 let target = URL.parse(request.url);
29 for (let hop = 0; target !== null && !target.username && !target.password; hop += 1) {
30 const host = sourceHost(target);
31 // Signed out still loads public assets.
32 const credential =
33 host === null ? null : yield* credentials.get(host).pipe(Effect.orElseSucceed(() => null));
34 const response: HttpClientResponse.HttpClientResponse = yield* httpClient
35 .execute(
36 HttpClientRequest.get(target.toString()).pipe(
37 HttpClientRequest.setHeaders({
38 ...request.headers,
39 // The bytes are streamed straight through, so never let an encoding layer in.
40 "accept-encoding": "identity",
41 "user-agent": "t3code",
42 }),
43 credential === null
44 ? (built) => built
45 : HttpClientRequest.bearerToken(Redacted.value(credential.token)),
46 ),
47 )
48 .pipe(
49 Effect.provideService(FetchHttpClient.RequestInit, MANUAL_REDIRECT),
50 Effect.provideService(HttpClient.TracerDisabledWhen, () => true),
51 );
52 // The source may hold a newer token than the one that was refused.
53 if (response.status === 401 && host !== null) yield* credentials.invalidate(host);
54 if (response.status < 300 || response.status >= 400) return response;
55 const location = response.headers.location;
56 if (!location || hop >= MAX_REDIRECTS) return null;
57 target = URL.parse(location, target.href);
58 if (target?.protocol !== "https:") return null;
59 }
60 return null;
61 });
62});