Skip to content
TypeScript

refactor(source-control): drivers build their own services and own host media (#23994)

Julius Marminge7368bd307bbf
diff --git a/apps/mobile/src/features/pull-requests/PullRequestMedia.tsx b/apps/mobile/src/features/pull-requests/PullRequestMedia.tsx
index 8c176059ec3..8f97b9c2289 100644
--- a/apps/mobile/src/features/pull-requests/PullRequestMedia.tsx
+++ b/apps/mobile/src/features/pull-requests/PullRequestMedia.tsx
@@ -1,8 +1,12 @@
import { createContext, useContext, useMemo, useState } from "react";
import { pullRequestMediaSource, pullRequestImageSource } from "./pullRequestMediaSource";
import { useFilePreviewGallery } from "../../components/FilePreviewGallery";
-import type { AssetResource, EnvironmentId } from "@t3tools/contracts";
-import { githubMediaFetchUrl } from "@t3tools/shared/githubMedia";
+import { sourceControlClients } from "@t3tools/client-runtime/source-control-clients";
+import {
+ SOURCE_CONTROL_MEDIA_ASSET,
+ type AssetResource,
+ type EnvironmentId,
+} from "@t3tools/contracts";
import { videoMimeType } from "@t3tools/shared/video";
import { Pressable, View } from "react-native";
import { Image } from "expo-image";
@@ -25,9 +29,12 @@ export const PullRequestMediaContext = createContext<{
export function usePullRequestMediaUrl(url: string) {
const context = useContext(PullRequestMediaContext);
- const fetchUrl = githubMediaFetchUrl(url);
+ const fetchUrl = sourceControlClients.mediaUrl(url)?.fetchUrl;
const resource = useMemo<AssetResource | null>(
- () => (context && fetchUrl ? { _tag: "github-media", cwd: context.cwd, url: fetchUrl } : null),
+ () =>
+ context && fetchUrl
+ ? { _tag: SOURCE_CONTROL_MEDIA_ASSET, cwd: context.cwd, url: fetchUrl }
+ : null,
[context, fetchUrl],
);
const asset = useAssetUrlState(context?.environmentId ?? null, resource);
diff --git a/apps/mobile/src/features/pull-requests/pullRequestMediaSource.ts b/apps/mobile/src/features/pull-requests/pullRequestMediaSource.ts
index e45cd548bcc..075eccfc38d 100644
--- a/apps/mobile/src/features/pull-requests/pullRequestMediaSource.ts
+++ b/apps/mobile/src/features/pull-requests/pullRequestMediaSource.ts
@@ -1,5 +1,5 @@
-import type { EnvironmentId } from "@t3tools/contracts";
-import { githubMediaFetchUrl } from "@t3tools/shared/githubMedia";
+import { sourceControlClients } from "@t3tools/client-runtime/source-control-clients";
+import { SOURCE_CONTROL_MEDIA_ASSET, type EnvironmentId } from "@t3tools/contracts";
import type { FilePreviewItem } from "../../components/FilePreviewModal.types";
export interface PullRequestMediaLocation {
@@ -9,11 +9,11 @@ export interface PullRequestMediaLocation {
/** Keep the original resource identity so previewers can resolve and renew its capability. */
export function pullRequestMediaSource(url: string, location: PullRequestMediaLocation | null) {
- const fetchUrl = githubMediaFetchUrl(url);
+ const fetchUrl = sourceControlClients.mediaUrl(url)?.fetchUrl;
return location && fetchUrl
? {
environmentId: location.environmentId,
- resource: { _tag: "github-media" as const, cwd: location.cwd, url: fetchUrl },
+ resource: { _tag: SOURCE_CONTROL_MEDIA_ASSET, cwd: location.cwd, url: fetchUrl },
}
: { uri: url };
}
diff --git a/apps/mobile/src/lib/videoPreviewSource.ts b/apps/mobile/src/lib/videoPreviewSource.ts
index dabc896e2de..837b4fbb0ae 100644
--- a/apps/mobile/src/lib/videoPreviewSource.ts
+++ b/apps/mobile/src/lib/videoPreviewSource.ts
@@ -1,4 +1,9 @@
-import type { AssetResource, ChatFileAttachment, EnvironmentId } from "@t3tools/contracts";
+import {
+ SOURCE_CONTROL_MEDIA_ASSET,
+ type AssetResource,
+ type ChatFileAttachment,
+ type EnvironmentId,
+} from "@t3tools/contracts";
import { videoMimeType } from "@t3tools/shared/video";
import type { DraftComposerFileAttachment } from "./composerImages";
@@ -17,7 +22,13 @@ export type MediaVideoPreviewSource = {
readonly environmentId: EnvironmentId;
readonly resource: Extract<
AssetResource,
- { readonly _tag: "attachment" | "media-file" | "draft-workspace-file" | "github-media" }
+ {
+ readonly _tag:
+ | "attachment"
+ | "media-file"
+ | "draft-workspace-file"
+ | typeof SOURCE_CONTROL_MEDIA_ASSET;
+ }
>;
}
);
@@ -45,10 +56,10 @@ export function mediaVideoThumbnailKey(source: MediaVideoPreviewSource): string
source.resource.path,
source.srcFragment ?? "",
]
- : source.resource._tag === "github-media"
+ : source.resource._tag === SOURCE_CONTROL_MEDIA_ASSET
? [
"media-video",
- "github-media",
+ SOURCE_CONTROL_MEDIA_ASSET,
source.environmentId,
source.resource.cwd,
source.resource.url,
diff --git a/apps/server/src/assets/AssetAccess.test.ts b/apps/server/src/assets/AssetAccess.test.ts
index 5b63d61d80c..0fb9f4eee5c 100644
--- a/apps/server/src/assets/AssetAccess.test.ts
+++ b/apps/server/src/assets/AssetAccess.test.ts
@@ -4,7 +4,9 @@ import * as NodeHttpPlatform from "@effect/platform-node/NodeHttpPlatform";
import * as NodeFSP from "node:fs/promises";
import {
AssetAccessError,
+ AssetCreateUrlInput,
AssetPreviewTypeValidationError,
+ SOURCE_CONTROL_MEDIA_ASSET,
ThreadId,
TurnItemId,
} from "@t3tools/contracts";
@@ -15,12 +17,11 @@ import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
-import * as Redacted from "effect/Redacted";
import * as Path from "effect/Path";
import * as PlatformError from "effect/PlatformError";
import * as Schema from "effect/Schema";
import * as TestClock from "effect/testing/TestClock";
-import { HttpClient, HttpClientResponse, HttpServerResponse } from "effect/http";
+import { HttpClientRequest, HttpClientResponse, HttpServerResponse } from "effect/http";
import { vi } from "vite-plus/test";
import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
@@ -33,8 +34,10 @@ import { assetFileResponse } from "../http.ts";
import { ASSET_ROUTE_PREFIX, issueAssetUrl, readMcpAppHtml, resolveAsset } from "./AssetAccess.ts";
import * as NativeAppIconResolver from "./NativeAppIconResolver.ts";
import { symlinksSupported } from "@t3tools/shared/testing/symlinks";
-import * as GitHubCredentials from "@t3tools/source-control-github/server/GitHubCredentials";
-import { githubMediaResponse } from "./GitHubMediaFetch.ts";
+import type { SourceControlDriverInstance } from "@t3tools/source-control-core/server/driver";
+import * as BuiltInDrivers from "../sourceControl/builtInDrivers.ts";
+import { sourceControlClients } from "../sourceControl/sourceControlClients.ts";
+import { sourceControlMediaResponse } from "./sourceControlMediaResponse.ts";
import * as HostProcess from "@t3tools/shared/HostProcess";
vi.mock("node:fs/promises", async (importOriginal) => {
@@ -178,53 +181,6 @@ describe("AssetAccess", () => {
);
});
- it.effect("loads private media immediately after login with the GitHub credential", () => {
- let lookups = 0;
- const authorizations: Array<string | undefined> = [];
- return Effect.gen(function* () {
- const asset = {
- url: "https://raw.githubusercontent.com/owner/repo/main/shot.png",
- cwd: "/repo",
- expiresAt: Number.MAX_SAFE_INTEGER,
- };
- expect((yield* githubMediaResponse(asset, {})).status).toBe(404);
- expect((yield* githubMediaResponse(asset, {})).status).toBe(200);
- expect((yield* githubMediaResponse(asset, {})).status).toBe(200);
- expect(lookups).toBe(3);
- expect(authorizations).toEqual([undefined, "Bearer signed-in", "Bearer signed-in"]);
- }).pipe(
- Effect.provide(
- Layer.mock(GitHubCredentials.GitHubCredentials)({
- get: (host) =>
- ++lookups === 1
- ? Effect.fail(new GitHubCredentials.GitHubNotSignedInError({ host }))
- : Effect.succeed({
- host,
- token: Redacted.make("signed-in"),
- source: "gh" as const,
- fingerprint: "fingerprint",
- }),
- }),
- ),
- Effect.provideService(
- HttpClient.HttpClient,
- HttpClient.make((request) => {
- authorizations.push(request.headers.authorization);
- return Effect.succeed(
- HttpClientResponse.fromWeb(
- request,
- new Response(null, {
- status: request.headers.authorization ? 200 : 404,
- headers: { "content-type": "image/png" },
- }),
- ),
- );
- }),
- ),
- Effect.scoped,
- );
- });
-
it.effect("serves an image a tool returned inline from the stored item", () =>
Effect.gen(function* () {
const resource = {
@@ -994,51 +950,66 @@ describe("AssetAccess", () => {
}).pipe(Effect.provide(layerTest)),
);
- it.effect("serves GitHub-hosted pull request media through the repository's credential", () =>
- Effect.gen(function* () {
- const resolve = (relativeUrl: string) => {
- const suffix = relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
- const separator = suffix.indexOf("/");
- return resolveAsset(suffix.slice(0, separator), suffix.slice(separator + 1));
- };
- const issue = (url: string) =>
- issueAssetUrl({ resource: { _tag: "github-media", cwd: "/repo", url } });
-
- const attachment = yield* issue(
- "https://github.com/user-attachments/assets/1a1842fb-6383-492f-873c-57aa0033fa6c",
- );
- expect(attachment.relativeUrl.endsWith("/1a1842fb-6383-492f-873c-57aa0033fa6c")).toBe(true);
- expect(yield* resolve(attachment.relativeUrl)).toEqual({
- kind: "github-media",
- url: "https://github.com/user-attachments/assets/1a1842fb-6383-492f-873c-57aa0033fa6c",
- cwd: "/repo",
- expiresAt: attachment.expiresAt,
+ it.effect("serves a host's credentialed media through that host's driver", () => {
+ const fetched: Array<{ url: string; headers: Readonly<Record<string, string>> }> = [];
+ const url = "https://github.com/owner/repo/blob/main/docs/shot.png";
+ const media = sourceControlClients.mediaUrl(url)!;
+ const layerDrivers = Layer.succeed(BuiltInDrivers.SourceControlDrivers, [
+ {
+ driver: { kind: media.definition.kind, definition: media.definition },
+ instance: {
+ sourceControl: {} as SourceControlDriverInstance["sourceControl"],
+ discovery: {} as SourceControlDriverInstance["discovery"],
+ pullRequests: null,
+ fetchMedia: (request) =>
+ Effect.sync(() => {
+ fetched.push(request);
+ return HttpClientResponse.fromWeb(
+ HttpClientRequest.get(request.url),
+ new Response("bytes", { status: 206, headers: { "content-length": "5" } }),
+ );
+ }),
+ },
+ },
+ ]);
+ return Effect.gen(function* () {
+ // Every client and server release spells the resource this way on the wire.
+ const { resource } = yield* Schema.decodeUnknownEffect(AssetCreateUrlInput)({
+ resource: { _tag: "github-media", cwd: "/repo", url },
});
-
- const committed = yield* issue("https://github.com/owner/repo/blob/main/docs/shot.png");
- expect(yield* resolve(committed.relativeUrl)).toMatchObject({
- url: "https://raw.githubusercontent.com/owner/repo/main/docs/shot.png",
+ const issued = yield* issueAssetUrl({ resource });
+ const suffix = issued.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
+ const separator = suffix.indexOf("/");
+ const asset = yield* resolveAsset(suffix.slice(0, separator), suffix.slice(separator + 1));
+ expect(asset).toEqual({
+ kind: "source-control-media",
+ url: media.fetchUrl,
+ cwd: "/repo",
+ expiresAt: issued.expiresAt,
});
+ if (asset?.kind !== "source-control-media") return;
- const legacy = yield* issue("https://github.com/owner/repo/assets/45952064/1a1842fb");
- expect(yield* resolve(legacy.relativeUrl)).toMatchObject({
- url: "https://github.com/owner/repo/assets/45952064/1a1842fb",
- });
- const lfs = yield* issue("https://media.githubusercontent.com/media/owner/repo/main/a.mp4");
- expect(yield* resolve(lfs.relativeUrl)).toMatchObject({
- url: "https://media.githubusercontent.com/media/owner/repo/main/a.mp4",
+ const response = yield* sourceControlMediaResponse(asset, {
+ range: "bytes=0-4",
+ cookie: "session",
});
- const awkward = yield* issue("https://raw.githubusercontent.com/o/r/main/100%.png");
- expect(awkward.relativeUrl.endsWith("/100%25.png")).toBe(true);
+ expect(fetched).toEqual([{ url: media.fetchUrl, headers: { range: "bytes=0-4" } }]);
+ expect(response.status).toBe(206);
+ // The upstream sent no type, so it comes from the file name the host gave the media.
+ expect(response.headers["content-type"]).toBe("image/png");
+ expect(response.headers["content-length"]).toBe("5");
+ }).pipe(Effect.provide(Layer.merge(layerTest, layerDrivers)), Effect.scoped);
+ });
+ it.effect("refuses media no host keeps behind a credential, without echoing the URL", () =>
+ Effect.gen(function* () {
for (const url of [
"https://example.com/shot.png",
"https://example.com/shot.png?token=private-media-token",
- "http://github.com/user-attachments/assets/1a1842fb",
- "https://github.com/owner/repo/pull/1",
- "https://github.com/owner/repo/blob/main/",
]) {
- const error = yield* issue(url).pipe(Effect.flip);
+ const error = yield* issueAssetUrl({
+ resource: { _tag: SOURCE_CONTROL_MEDIA_ASSET, cwd: "/repo", url },
+ }).pipe(Effect.flip);
expect(error._tag).toBe("AssetGitHubMediaUrlValidationError");
const encoded = yield* Schema.encodeEffect(Schema.fromJsonString(AssetAccessError))(error);
expect(encoded).not.toContain(url);
diff --git a/apps/server/src/assets/AssetAccess.ts b/apps/server/src/assets/AssetAccess.ts
index cc9621b962c..2d53da80392 100644
--- a/apps/server/src/assets/AssetAccess.ts
+++ b/apps/server/src/assets/AssetAccess.ts
@@ -1,7 +1,7 @@
import type { AssetResource } from "@t3tools/contracts";
import {
AssetAttachmentNotFoundError,
- AssetGitHubMediaUrlValidationError,
+ AssetSourceControlMediaUrlValidationError,
AssetPreviewTypeValidationError,
AssetProjectFaviconInspectionError,
AssetProjectFaviconNotFoundError,
@@ -13,6 +13,7 @@ import {
AssetWorkspacePathValidationError,
AssetWorkspaceResolutionError,
AssetWorkspaceRootNormalizationError,
+ SOURCE_CONTROL_MEDIA_ASSET,
ThreadId,
ToolActivityNativeAppReference,
TurnItemId,
@@ -30,7 +31,6 @@ import {
readImageDimensions,
type ImageDimensions,
} from "@t3tools/shared/imageDimensions";
-import { githubMediaFetchUrl, githubMediaFileName } from "@t3tools/shared/githubMedia";
import { MCP_APP_MAX_HTML_BYTES } from "@t3tools/shared/mcpApp";
import {
isProjectFaviconPath,
@@ -64,6 +64,7 @@ import * as ProjectFaviconResolver from "../project/ProjectFaviconResolver.ts";
import { isWithinRoot } from "../workspace/KnownWorkspaces.ts";
import * as WorkspacePaths from "../workspace/WorkspacePaths.ts";
import * as NativeAppIconResolver from "./NativeAppIconResolver.ts";
+import { sourceControlClients } from "../sourceControl/sourceControlClients.ts";
import { extractIcnsPng } from "./icns.ts";
import { openMediaFile, readMediaFileHeader, type OpenMediaFile } from "./MediaFile.ts";
import * as HostProcess from "@t3tools/shared/HostProcess";
@@ -160,8 +161,8 @@ const AssetClaimsSchema = Schema.Union([
}),
Schema.Struct({
version: Schema.Literal(1),
- kind: Schema.Literal("github-media"),
- /** Already narrowed to a GitHub media host at mint time; the signature is what keeps it there. */
+ kind: Schema.Literal(SOURCE_CONTROL_MEDIA_ASSET),
+ /** A host's `fetchUrl`, narrowed at mint time; the signature is what keeps it there. */
url: Schema.String,
cwd: Schema.String,
expiresAt: Schema.Number,
@@ -189,7 +190,7 @@ export type ResolvedAsset =
readonly mimeType: string;
}
| {
- readonly kind: "github-media";
+ readonly kind: "source-control-media";
readonly url: string;
readonly cwd: string;
readonly expiresAt: number;
@@ -803,19 +804,19 @@ export const issueAssetUrl = Effect.fn("AssetAccess.issueAssetUrl")(function* (i
fileName = "native-app-icon.png";
break;
}
- case "github-media": {
- const fetchUrl = githubMediaFetchUrl(input.resource.url);
- if (fetchUrl === null) {
- return yield* new AssetGitHubMediaUrlValidationError({});
+ case SOURCE_CONTROL_MEDIA_ASSET: {
+ const media = sourceControlClients.mediaUrl(input.resource.url);
+ if (media === null) {
+ return yield* new AssetSourceControlMediaUrlValidationError({});
}
claims = {
version: 1,
- kind: "github-media",
- url: fetchUrl,
+ kind: SOURCE_CONTROL_MEDIA_ASSET,
+ url: media.fetchUrl,
cwd: input.resource.cwd,
expiresAt,
};
- fileName = githubMediaFileName(fetchUrl);
+ fileName = media.fileName;
break;
}
}
@@ -926,9 +927,9 @@ export const resolveAsset = Effect.fn("AssetAccess.resolveAsset")(function* (
return faviconPath === claims.filePath ? yield* projectFaviconAsset(faviconPath) : null;
}
- if (claims.kind === "github-media") {
+ if (claims.kind === SOURCE_CONTROL_MEDIA_ASSET) {
return {
- kind: "github-media",
+ kind: "source-control-media",
url: claims.url,
cwd: claims.cwd,
expiresAt: claims.expiresAt,
diff --git a/apps/server/src/assets/GitHubMediaFetch.ts b/apps/server/src/assets/GitHubMediaFetch.ts
deleted file mode 100644
index 668f91b3d78..00000000000
--- a/apps/server/src/assets/GitHubMediaFetch.ts
+++ /dev/null
@@ -1,138 +0,0 @@
-import * as Mime from "effect/http/Mime";
-import { githubMediaFileName } from "@t3tools/shared/githubMedia";
-import * as Clock from "effect/Clock";
-import * as Effect from "effect/Effect";
-import * as Option from "effect/Option";
-import * as Redacted from "effect/Redacted";
-import {
- FetchHttpClient,
- HttpClient,
- HttpClientRequest,
- HttpServerResponse,
- type HttpClientResponse,
-} from "effect/http";
-
-import * as GitHubCredentials from "@t3tools/source-control-github/server/GitHubCredentials";
-
-/**
- * Everything a redirect leads to — the presigned object stores GitHub hands assets off to —
- * authorizes with its own signature, and some of them reject a request that also carries a
- * bearer token.
- */
-const CREDENTIALED_HOSTS = new Set([
- "github.com",
- "www.github.com",
- "raw.githubusercontent.com",
- "media.githubusercontent.com",
-]);
-const isCredentialedHost = (url: string) => {
- try {
- return CREDENTIALED_HOSTS.has(new URL(url).hostname.toLowerCase());
- } catch {
- return false;
- }
-};
-
-const MAX_REDIRECTS = 3;
-const MANUAL_REDIRECT: RequestInit = { redirect: "manual" };
-const FORWARDED_REQUEST_HEADERS = ["range", "if-range"] as const;
-const FORWARDED_RESPONSE_HEADERS = [
- "content-type",
- "content-length",
- "content-range",
- "accept-ranges",
- "etag",
- "last-modified",
-] as const;
-const MEDIA_CONTENT_TYPE_PATTERN = /^(?:image|video|audio)\/[\w!#$&^.+-]+$/i;
-const SVG_CONTENT_TYPE = "image/svg+xml";
-// An SVG is a document: same policy the asset route gives a workspace SVG, so one embedded in a
-// body cannot run script against this origin.
-const SVG_CONTENT_SECURITY_POLICY = "default-src 'none'; style-src 'unsafe-inline'; sandbox";
-
-const githubToken = GitHubCredentials.GitHubCredentials.pipe(
- Effect.flatMap((credentials) => credentials.get("github.com")),
- Effect.map((credential) => credential.token),
- Effect.orElseSucceed(() => null),
-);
-
-const fetchFollowingRedirects = Effect.fn("GitHubMediaFetch.fetchFollowingRedirects")(function* (
- url: string,
- headers: Record<string, string>,
- token: Redacted.Redacted | null,
-) {
- const httpClient = HttpClient.withScope(yield* HttpClient.HttpClient);
- let target = url;
- for (let hop = 0; ; hop += 1) {
- const authorization =
- token !== null && isCredentialedHost(target) ? `Bearer ${Redacted.value(token)}` : null;
- const response: HttpClientResponse.HttpClientResponse = yield* httpClient
- .execute(
- HttpClientRequest.get(target).pipe(
- HttpClientRequest.setHeaders({
- ...headers,
- // The bytes are streamed straight through, so never let an encoding layer in.
- "accept-encoding": "identity",
- ...(authorization === null ? {} : { authorization }),
- }),
- ),
- )
- .pipe(Effect.provideService(FetchHttpClient.RequestInit, MANUAL_REDIRECT));
- const location = response.headers.location;
- if (response.status < 300 || response.status >= 400) return response;
- if (!location || hop >= MAX_REDIRECTS) return null;
- const next = new URL(location, target);
- if (next.protocol !== "https:") return null;
- target = next.toString();
- }
-});
-
-export const githubMediaResponse = Effect.fn("GitHubMediaFetch.githubMediaResponse")(function* (
- asset: { readonly url: string; readonly cwd: string; readonly expiresAt: number },
- requestHeaders: Record<string, string | undefined>,
-) {
- // Both media hosts are served by github.com's account, which is the host `gh` stores it under.
- const token = yield* githubToken;
- const forwarded: Record<string, string> = {};
- for (const name of FORWARDED_REQUEST_HEADERS) {
- const value = requestHeaders[name];
- if (value !== undefined) forwarded[name] = value;
- }
- const response = yield* fetchFollowingRedirects(asset.url, forwarded, token);
- const remainingSeconds = Math.floor((asset.expiresAt - (yield* Clock.currentTimeMillis)) / 1000);
- const headers: Record<string, string> = {
- "cache-control":
- remainingSeconds > 0 ? `private, max-age=${remainingSeconds}` : "private, no-store",
- "x-content-type-options": "nosniff",
- };
- if (response === null) return HttpServerResponse.empty({ status: 502, headers });
- // It carries none of the upstream entity headers: a `content-length` with no body behind it
- // holds the connection open until the browser gives up on it.
- if (response.status >= 400) {
- return HttpServerResponse.empty({
- status: response.status >= 500 ? 502 : response.status,
- headers,
- });
- }
- const upstreamType =
- response.headers["content-type"]?.split(";", 1)[0]?.trim().toLowerCase() ?? "";
- const contentType = MEDIA_CONTENT_TYPE_PATTERN.test(upstreamType)
- ? upstreamType
- : Option.getOrElse(Mime.getType(githubMediaFileName(asset.url)), () => "").toLowerCase();
- if (!MEDIA_CONTENT_TYPE_PATTERN.test(contentType)) {
- return HttpServerResponse.empty({ status: 415, headers });
- }
- for (const name of FORWARDED_RESPONSE_HEADERS) {
- const value = response.headers[name];
- if (value !== undefined) headers[name] = value;
- }
- headers["content-type"] = contentType;
- if (contentType === SVG_CONTENT_TYPE) {
- headers["content-security-policy"] = SVG_CONTENT_SECURITY_POLICY;
- }
- return HttpServerResponse.stream(response.stream, {
- status: response.status,
- headers,
- contentType,
- });
-});
diff --git a/apps/server/src/assets/sourceControlMediaResponse.ts b/apps/server/src/assets/sourceControlMediaResponse.ts
new file mode 100644
index 00000000000..9c49420670f
--- /dev/null
+++ b/apps/server/src/assets/sourceControlMediaResponse.ts
@@ -0,0 +1,80 @@
+import * as Mime from "effect/http/Mime";
+import * as Clock from "effect/Clock";
+import * as Effect from "effect/Effect";
+import * as Option from "effect/Option";
+import { HttpServerResponse } from "effect/http";
+
+import * as BuiltInDrivers from "../sourceControl/builtInDrivers.ts";
+import { sourceControlClients } from "../sourceControl/sourceControlClients.ts";
+
+const FORWARDED_REQUEST_HEADERS = ["range", "if-range"] as const;
+const FORWARDED_RESPONSE_HEADERS = [
+ "content-type",
+ "content-length",
+ "content-range",
+ "accept-ranges",
+ "etag",
+ "last-modified",
+] as const;
+const MEDIA_CONTENT_TYPE_PATTERN = /^(?:image|video|audio)\/[\w!#$&^.+-]+$/i;
+const SVG_CONTENT_TYPE = "image/svg+xml";
+// An SVG is a document: same policy the asset route gives a workspace SVG, so one embedded in a
+// body cannot run script against this origin.
+const SVG_CONTENT_SECURITY_POLICY = "default-src 'none'; style-src 'unsafe-inline'; sandbox";
+
+export const sourceControlMediaResponse = Effect.fn(
+ "SourceControlMediaResponse.sourceControlMediaResponse",
+)(function* (
+ asset: { readonly url: string; readonly cwd: string; readonly expiresAt: number },
+ requestHeaders: Record<string, string | undefined>,
+) {
+ const remainingSeconds = Math.floor((asset.expiresAt - (yield* Clock.currentTimeMillis)) / 1000);
+ const headers: Record<string, string> = {
+ "cache-control":
+ remainingSeconds > 0 ? `private, max-age=${remainingSeconds}` : "private, no-store",
+ "x-content-type-options": "nosniff",
+ };
+ const media = sourceControlClients.mediaUrl(asset.url);
+ const drivers = yield* BuiltInDrivers.SourceControlDrivers;
+ const fetchMedia = drivers.find(({ driver }) => driver.kind === media?.definition.kind)?.instance
+ .fetchMedia;
+ if (media === null || fetchMedia === undefined) {
+ return HttpServerResponse.empty({ status: 404, headers });
+ }
+ const forwarded: Record<string, string> = {};
+ for (const name of FORWARDED_REQUEST_HEADERS) {
+ const value = requestHeaders[name];
+ if (value !== undefined) forwarded[name] = value;
+ }
+ const response = yield* fetchMedia({ url: asset.url, headers: forwarded });
+ if (response === null) return HttpServerResponse.empty({ status: 502, headers });
+ // It carries none of the upstream entity headers: a `content-length` with no body behind it
+ // holds the connection open until the browser gives up on it.
+ if (response.status >= 400) {
+ return HttpServerResponse.empty({
+ status: response.status >= 500 ? 502 : response.status,
+ headers,
+ });
+ }
+ const upstreamType =
+ response.headers["content-type"]?.split(";", 1)[0]?.trim().toLowerCase() ?? "";
+ const contentType = MEDIA_CONTENT_TYPE_PATTERN.test(upstreamType)
+ ? upstreamType
+ : Option.getOrElse(Mime.getType(media.fileName), () => "").toLowerCase();
+ if (!MEDIA_CONTENT_TYPE_PATTERN.test(contentType)) {
+ return HttpServerResponse.empty({ status: 415, headers });
+ }
+ for (const name of FORWARDED_RESPONSE_HEADERS) {
+ const value = response.headers[name];
+ if (value !== undefined) headers[name] = value;
+ }
+ headers["content-type"] = contentType;
+ if (contentType === SVG_CONTENT_TYPE) {
+ headers["content-security-policy"] = SVG_CONTENT_SECURITY_POLICY;
+ }
+ return HttpServerResponse.stream(response.stream, {
+ status: response.status,
+ headers,
+ contentType,
+ });
+});
diff --git a/apps/server/src/http.ts b/apps/server/src/http.ts
index 8871a5df345..b6c6833a87d 100644
--- a/apps/server/src/http.ts
+++ b/apps/server/src/http.ts
@@ -31,7 +31,7 @@ import { OtlpTracer, OtlpSerialization } from "effect/observability";
import * as ServerConfig from "./config.ts";
import { ASSET_ROUTE_PREFIX, readMcpAppHtml, resolveAsset } from "./assets/AssetAccess.ts";
-import { githubMediaResponse } from "./assets/GitHubMediaFetch.ts";
+import { sourceControlMediaResponse } from "./assets/sourceControlMediaResponse.ts";
import { statMediaFile, streamMediaFile, type OpenMediaFile } from "./assets/MediaFile.ts";
import {
ATTACHMENT_UPLOAD_ROUTE_PREFIX,
@@ -432,10 +432,15 @@ export const layerAssetRoute = HttpRouter.add(
headers: { "cache-control": "private, max-age=3600", "x-content-type-options": "nosniff" },
});
}
- if (asset.kind === "github-media") {
- return yield* githubMediaResponse(asset, request.headers).pipe(
+ if (asset.kind === "source-control-media") {
+ return yield* sourceControlMediaResponse(asset, request.headers).pipe(
Effect.tapError((cause) =>
- Effect.logWarning("Failed to fetch GitHub media.", { url: asset.url, cause }),
+ // The URL can carry a token in its query string, and the error keeps the request it
+ // failed on; the host and the failure kind are enough to diagnose.
+ Effect.logWarning("Failed to fetch source control media.", {
+ host: URL.canParse(asset.url) ? new URL(asset.url).host : undefined,
+ reason: cause.reason._tag,
+ }),
),
Effect.orElseSucceed(() =>
HttpServerResponse.empty({
diff --git a/apps/server/src/pullRequest/PullRequestProviderRegistry.ts b/apps/server/src/pullRequest/PullRequestProviderRegistry.ts
index 22a07e2a231..72cd314f5e2 100644
--- a/apps/server/src/pullRequest/PullRequestProviderRegistry.ts
+++ b/apps/server/src/pullRequest/PullRequestProviderRegistry.ts
@@ -28,12 +28,8 @@ export function fromProviders(
* @public Service construction is part of the canonical Effect module API.
*/
export const make = Effect.gen(function* () {
- const drivers = yield* Effect.forEach(BuiltInDrivers.BUILT_IN_SOURCE_CONTROL_DRIVERS, (driver) =>
- driver.make.pipe(Effect.map((instance) => instance.pullRequests)),
- );
- return fromProviders(
- drivers.filter((provider): provider is PullRequestProviderApi => provider !== null),
- );
+ const drivers = yield* BuiltInDrivers.SourceControlDrivers;
+ return fromProviders(drivers.flatMap(({ instance }) => instance.pullRequests ?? []));
});
export const layer = Layer.effect(PullRequestProviderRegistry, make).pipe(
diff --git a/apps/server/src/server.ts b/apps/server/src/server.ts
index ff0aca4126b..24ad96319c8 100644
--- a/apps/server/src/server.ts
+++ b/apps/server/src/server.ts
@@ -60,6 +60,7 @@ import * as AcpRegistrySupport from "@t3tools/provider-acp-registry/server/AcpRe
import * as CheckpointDiffQuery from "./checkpointing/CheckpointDiffQuery.ts";
import * as CheckpointStore from "./checkpointing/CheckpointStore.ts";
import * as SourceControlBuiltInDrivers from "./sourceControl/builtInDrivers.ts";
+import { BUILT_IN_SOURCE_CONTROL_DRIVER_LIST } from "./sourceControl/sourceControlClients.ts";
import * as TextGeneration from "./textGeneration/TextGeneration.ts";
import * as ProviderInstanceRegistryHydration from "./provider/ProviderInstanceRegistryHydration.ts";
import * as ProjectSettingsOverrideSweep from "./provider/ProjectSettingsOverrideSweep.ts";
@@ -332,9 +333,7 @@ const layerRepositoryIdentityResolver = Layer.effect(
const registry = yield* SourceControlProviderRegistry.SourceControlProviderRegistry;
return yield* RepositoryIdentityResolver.make({
refine: Effect.fn(function* (identity: RepositoryIdentity) {
- for (const kind of SourceControlBuiltInDrivers.BUILT_IN_SOURCE_CONTROL_DRIVERS.map(
- (driver) => driver.kind,
- )) {
+ for (const { kind } of BUILT_IN_SOURCE_CONTROL_DRIVER_LIST) {
const provider = yield* registry.get(kind);
if (provider.refineRepositoryIdentity === undefined) continue;
const refined = yield* provider.refineRepositoryIdentity({
diff --git a/apps/server/src/sourceControl/SourceControlDiscovery.test.ts b/apps/server/src/sourceControl/SourceControlDiscovery.test.ts
index 43f3a9ff868..8337ac730d3 100644
--- a/apps/server/src/sourceControl/SourceControlDiscovery.test.ts
+++ b/apps/server/src/sourceControl/SourceControlDiscovery.test.ts
@@ -23,6 +23,7 @@ import * as BitbucketPullRequestApi from "@t3tools/source-control-bitbucket/serv
import * as GitHubRest from "@t3tools/source-control-github/server/GitHubRest";
import * as GitHubRequestPolicy from "@t3tools/source-control-github/server/GitHubRequestPolicy";
import * as GitHubPullRequestApi from "@t3tools/source-control-github/server/GitHubPullRequestApi";
+import * as GitHubCredentials from "@t3tools/source-control-github/server/GitHubCredentials";
import * as GitLabCli from "@t3tools/source-control-gitlab/server/GitLabCli";
import * as GitLabPullRequestCli from "@t3tools/source-control-gitlab/server/GitLabPullRequestCli";
import * as ForgejoCli from "@t3tools/source-control-forgejo/server/ForgejoCli";
@@ -30,6 +31,7 @@ import * as GitCafeApi from "@t3tools/source-control-gitcafe/server/GitCafeApi";
import * as GitCafeCredentials from "@t3tools/source-control-gitcafe/server/GitCafeCredentials";
import * as ForgejoSourceControlProvider from "@t3tools/source-control-forgejo/server/ForgejoSourceControlProvider";
import * as SourceControlDiscovery from "./SourceControlDiscovery.ts";
+import * as BuiltInDriversTestkit from "./builtInDrivers.testkit.ts";
import * as SourceControlProviderRegistry from "./SourceControlProviderRegistry.ts";
import * as ServerSourceControlHost from "./ServerSourceControlHost.ts";
import * as SourceControlHost from "@t3tools/source-control-core/server/SourceControlHost";
@@ -39,6 +41,7 @@ const layerSourceControlProviderRegistryTest = (input: {
readonly process: Partial<VcsProcess.VcsProcess["Service"]>;
}) =>
SourceControlProviderRegistry.layer.pipe(
+ Layer.provide(BuiltInDriversTestkit.layerOverHostServices),
Layer.provide(
Layer.mergeAll(
ServerConfig.layerTest(process.cwd(), {
@@ -50,6 +53,7 @@ const layerSourceControlProviderRegistryTest = (input: {
Layer.mock(BitbucketPullRequestApi.BitbucketPullRequestApi)({}),
ServerSettings.ServerSettingsService.layerTest(),
Layer.mock(GitHubPullRequestApi.GitHubPullRequestApi)({}),
+ Layer.mock(GitHubCredentials.GitHubCredentials)({}),
Layer.mock(GitHubRest.GitHubRest)({}),
// The GitHub provider's GraphQL reads go through these; no test here makes one.
Layer.mock(GitHubRequestPolicy.GitHubRequestPolicy)({}),
diff --git a/apps/server/src/sourceControl/SourceControlProviderRegistry.test.ts b/apps/server/src/sourceControl/SourceControlProviderRegistry.test.ts
index 80738fcf38a..7d7c79990bd 100644
--- a/apps/server/src/sourceControl/SourceControlProviderRegistry.test.ts
+++ b/apps/server/src/sourceControl/SourceControlProviderRegistry.test.ts
@@ -39,6 +39,7 @@ import * as GitLabPullRequestCli from "@t3tools/source-control-gitlab/server/Git
import * as ForgejoCli from "@t3tools/source-control-forgejo/server/ForgejoCli";
import * as GitCafeApi from "@t3tools/source-control-gitcafe/server/GitCafeApi";
import * as GitCafeCredentials from "@t3tools/source-control-gitcafe/server/GitCafeCredentials";
+import * as BuiltInDriversTestkit from "./builtInDrivers.testkit.ts";
import * as SourceControlProviderRegistry from "./SourceControlProviderRegistry.ts";
import * as ServerSourceControlHost from "./ServerSourceControlHost.ts";
@@ -114,53 +115,59 @@ function makeRegistry(input: {
return SourceControlProviderRegistry.make.pipe(
Effect.provide(
- Layer.mergeAll(
- NodeServices.layer,
- layerRegistry,
- layerProcess,
- ServerSourceControlHost.layer.pipe(
- Layer.provide(
- Layer.mergeAll(
- layerProcess,
- layerRegistry,
- ServerSettings.ServerSettingsService.layerTest(),
- Layer.mock(GitVcsDriver.GitVcsDriver)({}),
+ BuiltInDriversTestkit.layerOverHostServices.pipe(
+ Layer.provideMerge(
+ Layer.mergeAll(
+ NodeServices.layer,
+ layerRegistry,
+ layerProcess,
+ ServerSourceControlHost.layer.pipe(
+ Layer.provide(
+ Layer.mergeAll(
+ layerProcess,
+ layerRegistry,
+ ServerSettings.ServerSettingsService.layerTest(),
+ Layer.mock(GitVcsDriver.GitVcsDriver)({}),
+ ),
+ ),
),
+ Layer.mock(AzureDevOpsCli.AzureDevOpsCli)({}),
+ Layer.mock(AzureDevOpsPullRequestCli.AzureDevOpsPullRequestCli)({}),
+ Layer.mock(BitbucketApi.BitbucketApi)({}),
+ Layer.mock(BitbucketPullRequestApi.BitbucketPullRequestApi)({}),
+ input.settings
+ ? Layer.mock(ServerSettings.ServerSettingsService)(input.settings)
+ : ServerSettings.ServerSettingsService.layerTest(),
+ Layer.mock(GitHubPullRequestApi.GitHubPullRequestApi)({}),
+ Layer.mock(GitHubCredentials.GitHubCredentials)({}),
+ // The GitHub provider's GraphQL reads go through these; no test here makes one.
+ Layer.mock(GitHubRequestPolicy.GitHubRequestPolicy)({}),
+ Layer.succeed(
+ HttpClient.HttpClient,
+ HttpClient.make(() => Effect.die(new Error("Unexpected GitHub GraphQL read"))),
+ ),
+ Layer.mock(GitHubRest.GitHubRest)({
+ // No GitHub credential unless a test supplies one, so custom hosts stay unclaimed.
+ credential: (host) =>
+ Effect.fail(new GitHubCredentials.GitHubNotSignedInError({ host })),
+ ...input.githubApi,
+ }),
+ Layer.mock(GitVcsDriver.GitVcsDriver)({}),
+ Layer.mock(GitLabCli.GitLabCli)(input.gitlab ?? {}),
+ Layer.mock(GitLabPullRequestCli.GitLabPullRequestCli)({}),
+ Layer.mock(ForgejoCli.ForgejoCli)({
+ listLogins: () => Effect.succeed([]),
+ ...input.forgejo,
+ }),
+ Layer.mock(GitCafeApi.GitCafeApi)({}),
+ Layer.mock(GitCafeCredentials.GitCafeCredentials)({
+ cliEnv: () => Effect.succeed({}),
+ }),
+ ServerConfig.layerTest(process.cwd(), {
+ prefix: "t3-source-control-registry-test-",
+ }).pipe(Layer.provide(NodeServices.layer)),
),
),
- Layer.mock(AzureDevOpsCli.AzureDevOpsCli)({}),
- Layer.mock(AzureDevOpsPullRequestCli.AzureDevOpsPullRequestCli)({}),
- Layer.mock(BitbucketApi.BitbucketApi)({}),
- Layer.mock(BitbucketPullRequestApi.BitbucketPullRequestApi)({}),
- input.settings
- ? Layer.mock(ServerSettings.ServerSettingsService)(input.settings)
- : ServerSettings.ServerSettingsService.layerTest(),
- Layer.mock(GitHubPullRequestApi.GitHubPullRequestApi)({}),
- // The GitHub provider's GraphQL reads go through these; no test here makes one.
- Layer.mock(GitHubRequestPolicy.GitHubRequestPolicy)({}),
- Layer.succeed(
- HttpClient.HttpClient,
- HttpClient.make(() => Effect.die(new Error("Unexpected GitHub GraphQL read"))),
- ),
- Layer.mock(GitHubRest.GitHubRest)({
- // No GitHub credential unless a test supplies one, so custom hosts stay unclaimed.
- credential: (host) => Effect.fail(new GitHubCredentials.GitHubNotSignedInError({ host })),
- ...input.githubApi,
- }),
- Layer.mock(GitVcsDriver.GitVcsDriver)({}),
- Layer.mock(GitLabCli.GitLabCli)(input.gitlab ?? {}),
- Layer.mock(GitLabPullRequestCli.GitLabPullRequestCli)({}),
- Layer.mock(ForgejoCli.ForgejoCli)({
- listLogins: () => Effect.succeed([]),
- ...input.forgejo,
- }),
- Layer.mock(GitCafeApi.GitCafeApi)({}),
- Layer.mock(GitCafeCredentials.GitCafeCredentials)({
- cliEnv: () => Effect.succeed({}),
- }),
- ServerConfig.layerTest(process.cwd(), {
- prefix: "t3-source-control-registry-test-",
- }).pipe(Layer.provide(NodeServices.layer)),
),
),
);
diff --git a/apps/server/src/sourceControl/SourceControlProviderRegistry.ts b/apps/server/src/sourceControl/SourceControlProviderRegistry.ts
index 5ea6c4037c9..e08b7a7e6fb 100644
--- a/apps/server/src/sourceControl/SourceControlProviderRegistry.ts
+++ b/apps/server/src/sourceControl/SourceControlProviderRegistry.ts
@@ -358,16 +358,14 @@ export const makeWithProviders = Effect.fn("makeSourceControlProviderRegistryWit
);
export const make = Effect.gen(function* () {
- const drivers = yield* Effect.forEach(BuiltInDrivers.BUILT_IN_SOURCE_CONTROL_DRIVERS, (driver) =>
- driver.make.pipe(
- Effect.map((instance): SourceControlProviderRegistration => ({
- kind: driver.kind,
- provider: instance.sourceControl,
- discovery: instance.discovery,
- })),
- ),
+ const drivers = yield* BuiltInDrivers.SourceControlDrivers;
+ return yield* makeWithProviders(
+ drivers.map(({ driver, instance }): SourceControlProviderRegistration => ({
+ kind: driver.kind,
+ provider: instance.sourceControl,
+ discovery: instance.discovery,
+ })),
);
- return yield* makeWithProviders(drivers);
});
export const layer = Layer.effect(SourceControlProviderRegistry, make);
diff --git a/apps/server/src/sourceControl/SourceControlRepositoryService.test.ts b/apps/server/src/sourceControl/SourceControlRepositoryService.test.ts
index 14615a39856..4a9105e9f5d 100644
--- a/apps/server/src/sourceControl/SourceControlRepositoryService.test.ts
+++ b/apps/server/src/sourceControl/SourceControlRepositoryService.test.ts
@@ -101,6 +101,51 @@ function layer(input: {
: layerService.pipe(Layer.provideMerge(NodeServices.layer));
}
+const lookupFailingWith = (cause: unknown, detail: string) =>
+ Effect.gen(function* () {
+ const service = yield* SourceControlRepositoryService.SourceControlRepositoryService;
+ return yield* service
+ .lookupRepository({ provider: SourceControlProviderKind.make("bitbucket"), repository: "x" })
+ .pipe(Effect.flip);
+ }).pipe(
+ Effect.provide(
+ layer({
+ provider: makeProvider({
+ getRepositoryCloneUrls: (input) =>
+ Effect.fail(
+ new SourceControlProviderError({
+ provider: SourceControlProviderKind.make("bitbucket"),
+ operation: "getRepositoryCloneUrls",
+ cwd: input.cwd,
+ detail,
+ cause,
+ }),
+ ),
+ }),
+ }),
+ ),
+ );
+
+it.effect("tells the user a host's fixed explanation of a failed repository lookup", () =>
+ Effect.gen(function* () {
+ const error = yield* lookupFailingWith(
+ { userFacingDetail: "Repositories are named workspace/repository." },
+ "Repositories are named workspace/repository.",
+ );
+ assert.strictEqual(error.detail, "Repositories are named workspace/repository.");
+ }),
+);
+
+it.effect("keeps a host's raw response text out of a failed repository lookup", () =>
+ Effect.gen(function* () {
+ const error = yield* lookupFailingWith(
+ new Error("upstream"),
+ "<html>internal token=abc</html>",
+ );
+ assert.strictEqual(error.detail, "The source control operation could not be completed.");
+ }),
+);
+
it.effect("clones a looked-up repository after creating missing parent directories", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
diff --git a/apps/server/src/sourceControl/SourceControlRepositoryService.ts b/apps/server/src/sourceControl/SourceControlRepositoryService.ts
index cba0df9d905..ceb9ec33288 100644
--- a/apps/server/src/sourceControl/SourceControlRepositoryService.ts
+++ b/apps/server/src/sourceControl/SourceControlRepositoryService.ts
@@ -30,14 +30,13 @@ import {
type GitCloneProgressLine,
} from "../project/gitCloneProgress.ts";
import * as GitVcsDriver from "../vcs/GitVcsDriver.ts";
-import * as BitbucketApi from "@t3tools/source-control-bitbucket/server/BitbucketApi";
+import * as SourceControlProvider from "@t3tools/source-control-core/server/SourceControlProvider";
import * as SourceControlProviderRegistry from "./SourceControlProviderRegistry.ts";
import * as HostProcess from "@t3tools/shared/HostProcess";
import { cloneUrlForProtocol, cloneUrlProtocol } from "@t3tools/shared/cloneUrl";
const isSourceControlRepositoryError = Schema.is(SourceControlRepositoryError);
const isSourceControlProviderError = Schema.is(SourceControlProviderError);
const isGitCommandError = Schema.is(GitCommandError);
-const isBitbucketRepositoryLocatorError = Schema.is(BitbucketApi.BitbucketRepositoryLocatorError);
export class SourceControlRepositoryService extends Context.Service<
SourceControlRepositoryService,
@@ -95,11 +94,9 @@ function mapRepositoryError(operation: string, provider: SourceControlProviderKi
operation,
provider,
detail:
- isSourceControlProviderError(cause) &&
- cause.provider === "bitbucket" &&
- isBitbucketRepositoryLocatorError(cause.cause)
- ? BitbucketApi.BitbucketRepositoryLocatorError.detail
- : "The source control operation could not be completed.",
+ (isSourceControlProviderError(cause)
+ ? SourceControlProvider.userFacingSourceControlDetail(cause.cause)
+ : undefined) ?? "The source control operation could not be completed.",
cause,
}),
);
diff --git a/apps/server/src/sourceControl/builtInDrivers.testkit.ts b/apps/server/src/sourceControl/builtInDrivers.testkit.ts
new file mode 100644
index 00000000000..e3d314336b0
--- /dev/null
+++ b/apps/server/src/sourceControl/builtInDrivers.testkit.ts
@@ -0,0 +1,40 @@
+import * as AzureDevOpsDriver from "@t3tools/source-control-azure-devops/server/driver";
+import * as BitbucketDriver from "@t3tools/source-control-bitbucket/server/driver";
+import * as ForgejoDriver from "@t3tools/source-control-forgejo/server/driver";
+import * as GitCafeDriver from "@t3tools/source-control-gitcafe/server/driver";
+import * as GitHubDriver from "@t3tools/source-control-github/server/driver";
+import * as GitLabDriver from "@t3tools/source-control-gitlab/server/driver";
+import type {
+ SourceControlDriver,
+ SourceControlDriverInstance,
+} from "@t3tools/source-control-core/server/driver";
+import * as Effect from "effect/Effect";
+import * as Layer from "effect/Layer";
+
+import * as BuiltInDrivers from "./builtInDrivers.ts";
+
+const entry = (
+ driver: SourceControlDriver,
+ instance: SourceControlDriverInstance,
+): BuiltInDrivers.SourceControlDriverEntry => ({ driver, instance });
+
+/** Every built-in driver over whatever stands in for its host's own services. */
+export const layerOverHostServices = Layer.effect(
+ BuiltInDrivers.SourceControlDrivers,
+ Effect.all([
+ GitHubDriver.makeInstance.pipe(Effect.map((instance) => entry(GitHubDriver.driver, instance))),
+ GitLabDriver.makeInstance.pipe(Effect.map((instance) => entry(GitLabDriver.driver, instance))),
+ GitCafeDriver.makeInstance.pipe(
+ Effect.map((instance) => entry(GitCafeDriver.driver, instance)),
+ ),
+ ForgejoDriver.makeInstance.pipe(
+ Effect.map((instance) => entry(ForgejoDriver.driver, instance)),
+ ),
+ BitbucketDriver.makeInstance.pipe(
+ Effect.map((instance) => entry(BitbucketDriver.driver, instance)),
+ ),
+ AzureDevOpsDriver.makeInstance.pipe(
+ Effect.map((instance) => entry(AzureDevOpsDriver.driver, instance)),
+ ),
+ ]),
+);
diff --git a/apps/server/src/sourceControl/builtInDrivers.ts b/apps/server/src/sourceControl/builtInDrivers.ts
index 7941c7f3ead..26bc4d4da21 100644
--- a/apps/server/src/sourceControl/builtInDrivers.ts
+++ b/apps/server/src/sourceControl/builtInDrivers.ts
@@ -1,37 +1,31 @@
-import * as AzureDevOpsCli from "@t3tools/source-control-azure-devops/server/AzureDevOpsCli";
-import * as AzureDevOpsPullRequestCli from "@t3tools/source-control-azure-devops/server/AzureDevOpsPullRequestCli";
-import * as BitbucketApi from "@t3tools/source-control-bitbucket/server/BitbucketApi";
-import * as BitbucketPullRequestApi from "@t3tools/source-control-bitbucket/server/BitbucketPullRequestApi";
-import * as ForgejoCli from "@t3tools/source-control-forgejo/server/ForgejoCli";
-import * as GitCafeApi from "@t3tools/source-control-gitcafe/server/GitCafeApi";
-import * as GitCafeCredentials from "@t3tools/source-control-gitcafe/server/GitCafeCredentials";
-import * as GitHubRest from "@t3tools/source-control-github/server/GitHubRest";
-import * as GitHubPullRequestApi from "@t3tools/source-control-github/server/GitHubPullRequestApi";
-import * as GitLabCli from "@t3tools/source-control-gitlab/server/GitLabCli";
-import * as GitLabPullRequestCli from "@t3tools/source-control-gitlab/server/GitLabPullRequestCli";
-import type { SourceControlDriver } from "@t3tools/source-control-core/server/driver";
+import type {
+ SourceControlDriver,
+ SourceControlDriverInstance,
+} from "@t3tools/source-control-core/server/driver";
import * as SourceControlRateLimit from "@t3tools/source-control-core/server/SourceControlRateLimit";
+import * as Context from "effect/Context";
+import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as ServerSourceControlHost from "./ServerSourceControlHost.ts";
-import { BUILT_IN_SOURCE_CONTROL_DRIVER_LIST as drivers } from "./sourceControlClients.ts";
+import { BUILT_IN_SOURCE_CONTROL_DRIVER_LIST } from "./sourceControlClients.ts";
-export type BuiltInSourceControlDriversEnv =
- (typeof drivers)[number] extends SourceControlDriver<infer R> ? R : never;
+export interface SourceControlDriverEntry {
+ readonly driver: Pick<SourceControlDriver, "kind" | "definition">;
+ readonly instance: SourceControlDriverInstance;
+}
-export const BUILT_IN_SOURCE_CONTROL_DRIVERS: ReadonlyArray<
- SourceControlDriver<BuiltInSourceControlDriversEnv>
-> = drivers;
+/** Every driver's instance, in registry order. Everything that reads a host reads it here. */
+export class SourceControlDrivers extends Context.Service<
+ SourceControlDrivers,
+ ReadonlyArray<SourceControlDriverEntry>
+>()("t3/sourceControl/builtInDrivers/SourceControlDrivers") {}
-export const layer = Layer.mergeAll(
- // `GitHubRest.layerWithDependencies` carries the quota reserve and rate-limit pause every GitHub
- // reader shares, so the server builds it once, here.
- GitHubPullRequestApi.layer.pipe(Layer.provideMerge(GitHubRest.layerWithDependencies)),
- AzureDevOpsPullRequestCli.layer.pipe(Layer.provideMerge(AzureDevOpsCli.layer)),
- BitbucketPullRequestApi.layer.pipe(
- Layer.provideMerge(BitbucketApi.layer.pipe(Layer.provide(SourceControlRateLimit.layer))),
- ),
- ForgejoCli.layer,
- GitCafeApi.layer.pipe(Layer.provideMerge(GitCafeCredentials.layer)),
- GitLabPullRequestCli.layer.pipe(Layer.provideMerge(GitLabCli.layer)),
-).pipe(Layer.provideMerge(ServerSourceControlHost.layer));
+const make = Effect.forEach(BUILT_IN_SOURCE_CONTROL_DRIVER_LIST, (driver) =>
+ driver.make.pipe(Effect.map((instance) => ({ driver, instance }))),
+);
+
+export const layer = Layer.effect(SourceControlDrivers, make).pipe(
+ Layer.provideMerge(ServerSourceControlHost.layer),
+ Layer.provideMerge(SourceControlRateLimit.layer),
+);
diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.ts
index 9a72a501f43..cc70767a8d3 100644
--- a/apps/server/src/ws.ts
+++ b/apps/server/src/ws.ts
@@ -85,6 +85,7 @@ import {
FilesystemBrowseError,
AssetWorkspaceContextNotFoundError,
AssetWorkspaceContextResolutionError,
+ SOURCE_CONTROL_MEDIA_ASSET,
ChatAttachmentId,
PersistChatAttachmentsError,
RpcClientId,
@@ -2772,7 +2773,7 @@ export const layerWsRpc = (
input.resource._tag === "attachment" ||
input.resource._tag === "native-app-icon" ||
input.resource._tag === "tool-output-image" ||
- input.resource._tag === "github-media" ||
+ input.resource._tag === SOURCE_CONTROL_MEDIA_ASSET ||
// A network path is served only from the thread's project, looked up below.
(input.resource._tag === "media-file" &&
path.isAbsolute(input.resource.path) &&
diff --git a/apps/web/src/components/ChatMarkdown.tsx b/apps/web/src/components/ChatMarkdown.tsx
index e46e3092d6b..2a3c7158342 100644
--- a/apps/web/src/components/ChatMarkdown.tsx
+++ b/apps/web/src/components/ChatMarkdown.tsx
@@ -8,7 +8,11 @@ import {
} from "@t3tools/shared/markdownLinks";
import { isHostPath, resolveWorkspaceFilePath } from "@t3tools/shared/path";
import { usePullRequestLinking } from "~/hooks/usePullRequestLinking";
-import { AuthFilesystemReadScope, AuthOrchestrationOperateScope } from "@t3tools/contracts";
+import {
+ AuthFilesystemReadScope,
+ AuthOrchestrationOperateScope,
+ SOURCE_CONTROL_MEDIA_ASSET,
+} from "@t3tools/contracts";
import {
CHAT_MARKDOWN_REMARK_PLUGINS,
CHAT_MARKDOWN_REMARK_PLUGINS_WITH_BREAKS,
@@ -45,7 +49,6 @@ import {
type ServerProviderSkill,
type ThreadPullRequestKey,
} from "@t3tools/contracts";
-import { githubMediaFetchUrl } from "@t3tools/shared/githubMedia";
import {
isAtomCommandInterrupted,
squashAtomCommandFailure,
@@ -234,9 +237,9 @@ interface ChatMarkdownProps {
onImageExpand?: ((preview: ExpandedImagePreview) => void) | undefined;
extraRemarkPlugins?: NonNullable<ReactMarkdownOptions["remarkPlugins"]>;
renderContextReference?: ((reference: ChatMarkdownContextReference) => ReactNode) | undefined;
- /** Loads GitHub-hosted media through `cwd`'s GitHub credential, which a private repository's
- uploads need; without it those images and videos load unauthenticated and 404. */
- githubMedia?: boolean | undefined;
+ /** Loads media a source control host keeps behind a credential through the server, which holds
+ `cwd`'s; without it a private repository's uploads load unauthenticated and 404. */
+ sourceControlMedia?: boolean | undefined;
headingLevelOffset?: number | undefined;
}
@@ -448,7 +451,7 @@ function useChatMarkdownState({
onImageExpand,
renderContextReference,
headingLevelOffset = 0,
- githubMedia = false,
+ sourceControlMedia = false,
}: ChatMarkdownProps) {
const resolvedTheme = useRenderedAppearance();
const markdownRef = useRef<HTMLElement>(null);
@@ -885,7 +888,7 @@ function useChatMarkdownState({
environmentId,
expandMedia,
fileLinkChip,
- githubMedia,
+ sourceControlMedia,
renderContextReference,
headingLevelOffset,
imageBaseDir,
@@ -1352,7 +1355,7 @@ const CHAT_MARKDOWN_COMPONENTS = {
expandMedia,
cwd,
environmentId,
- githubMedia,
+ sourceControlMedia,
imageBaseDir,
threadRef,
workspaceMutationId,
@@ -1384,19 +1387,22 @@ const CHAT_MARKDOWN_COMPONENTS = {
const imageSource = classifyMarkdownImageSource(classifiedSrc, imageBaseDir ?? cwd);
const kind = mediaKindFromPath(classifiedSrc) ?? "image";
const directUri = imageSource._tag === "Direct" ? imageSource.uri : null;
- const githubMediaUrl =
- directUri === null ? null : githubMediaFetchUrl(resolveProtocolRelativeMediaUrl(directUri));
+ const hostMediaUrl =
+ directUri === null
+ ? null
+ : (sourceControlClients.mediaUrl(resolveProtocolRelativeMediaUrl(directUri))?.fetchUrl ??
+ null);
if (
- githubMedia &&
+ sourceControlMedia &&
cwd !== undefined &&
environmentId !== null &&
directUri !== null &&
- githubMediaUrl !== null
+ hostMediaUrl !== null
) {
return (
<ChatMarkdownAssetImage
environmentId={environmentId}
- resource={{ _tag: "github-media", cwd, url: githubMediaUrl }}
+ resource={{ _tag: SOURCE_CONTROL_MEDIA_ASSET, cwd, url: hostMediaUrl }}
alt={altText}
kind={kind}
copyMarkdown={copyMarkdown}
@@ -1407,7 +1413,7 @@ const CHAT_MARKDOWN_COMPONENTS = {
srcFragment={markdownImageSourceFragment(classifiedSrc)}
originalUrl={resolveProtocolRelativeMediaUrl(directUri)}
framed={false}
- fallbackSrc={githubMediaUrl}
+ fallbackSrc={hostMediaUrl}
onImageExpand={imageExpand}
/>
);
diff --git a/apps/web/src/components/chat/ChatMarkdownMedia.tsx b/apps/web/src/components/chat/ChatMarkdownMedia.tsx
index f0601234628..d74746378d9 100644
--- a/apps/web/src/components/chat/ChatMarkdownMedia.tsx
+++ b/apps/web/src/components/chat/ChatMarkdownMedia.tsx
@@ -1,6 +1,6 @@
import { MISSING_FILE_ACCESS_MESSAGE } from "@t3tools/client-runtime/state/assets";
import { mediaFileReference, mediaUrlReference } from "@t3tools/client-runtime/media-reference";
-import type { AssetResource, EnvironmentId } from "@t3tools/contracts";
+import type { AssetResource, EnvironmentId, SOURCE_CONTROL_MEDIA_ASSET } from "@t3tools/contracts";
import { TriangleAlertIcon } from "lucide-react";
import {
createContext,
@@ -312,7 +312,7 @@ export const ChatMarkdownAssetImage = memo(function ChatMarkdownAssetImage(props
| "attachment"
| "workspace-file"
| "media-file"
- | "github-media"
+ | typeof SOURCE_CONTROL_MEDIA_ASSET
| "tool-output-image";
}
>;
diff --git a/apps/web/src/components/pullRequest/PullRequestMarkdown.tsx b/apps/web/src/components/pullRequest/PullRequestMarkdown.tsx
index 4d25c8011d1..91dec8acdac 100644
--- a/apps/web/src/components/pullRequest/PullRequestMarkdown.tsx
+++ b/apps/web/src/components/pullRequest/PullRequestMarkdown.tsx
@@ -1,7 +1,12 @@
import { ExternalLinkIcon, PaperclipIcon } from "lucide-react";
import { markdownImageSourceFragment } from "@t3tools/client-runtime/markdown-images";
-import { githubMediaFetchUrl } from "@t3tools/shared/githubMedia";
-import type { AssetResource, EnvironmentId, ScopedThreadRef } from "@t3tools/contracts";
+import { sourceControlClients } from "@t3tools/client-runtime/source-control-clients";
+import {
+ SOURCE_CONTROL_MEDIA_ASSET,
+ type AssetResource,
+ type EnvironmentId,
+ type ScopedThreadRef,
+} from "@t3tools/contracts";
import { createContext, useContext } from "react";
import type { Options as ReactMarkdownOptions } from "react-markdown";
@@ -18,7 +23,7 @@ export const PullRequestMarkdownContext = createContext<{
threadRef: ScopedThreadRef | null;
} | null>(null);
-function PullRequestGitHubVideo({
+function PullRequestHostVideo({
environmentId,
cwd,
url,
@@ -29,7 +34,7 @@ function PullRequestGitHubVideo({
url: string;
fetchUrl: string;
}) {
- const resource: AssetResource = { _tag: "github-media", cwd, url: fetchUrl };
+ const resource: AssetResource = { _tag: SOURCE_CONTROL_MEDIA_ASSET, cwd, url: fetchUrl };
const assetUrl = useAssetUrlState(environmentId, resource);
const refreshAssetUrl = useAssetUrlRefresh(environmentId, resource);
const src =
@@ -85,19 +90,19 @@ export function PullRequestMarkdown({
pullRequestPanelRef={resolvedThreadRef ?? PULL_REQUESTS_PANEL_REF}
environmentId={environmentId}
extraRemarkPlugins={extraRemarkPlugins}
- githubMedia
+ sourceControlMedia
/>
);
}
- const githubMediaUrl = segment.media === "video" ? githubMediaFetchUrl(segment.url) : null;
- if (githubMediaUrl !== null) {
+ const hostMedia = sourceControlClients.mediaUrl(segment.url);
+ if (segment.media === "video" && hostMedia !== null) {
return (
- <PullRequestGitHubVideo
+ <PullRequestHostVideo
key={`${segment.id}:${segment.url}`}
environmentId={environmentId}
cwd={cwd}
url={segment.url}
- fetchUrl={githubMediaUrl}
+ fetchUrl={hostMedia.fetchUrl}
/>
);
}
@@ -125,7 +130,9 @@ export function PullRequestMarkdown({
className="flex items-center gap-2 rounded-lg border border-border/60 bg-muted/30 px-3 py-2 text-sm hover:bg-muted/60"
>
<PaperclipIcon aria-hidden className="size-3.5 shrink-0 text-muted-foreground" />
- <span className="min-w-0 flex-1 truncate">Open attachment on GitHub</span>
+ <span className="min-w-0 flex-1 truncate">
+ Open attachment on {hostMedia?.definition.label ?? new URL(segment.url).hostname}
+ </span>
<ExternalLinkIcon aria-hidden className="size-3 shrink-0 text-muted-foreground" />
</a>
);
diff --git a/knip.jsonc b/knip.jsonc
index 13885f968c6..aba0742d242 100644
--- a/knip.jsonc
+++ b/knip.jsonc
@@ -44,7 +44,6 @@
"scripts/cli.ts",
"scripts/evaluate-thread-titles.ts",
"scripts/fetch-expo-schema.ts",
- "scripts/measure-pr-preview.ts",
"scripts/probe-claude-fork-local-rollback-replay.ts",
"scripts/update-test-shard-weights.ts",
"scripts/verify-background-live.ts",
@@ -135,7 +134,7 @@
},
"packages/source-control-github": {
// graphqlgen reads its config; the generated operations export every selection's class.
- "entry": ["graphql.config.ts"],
+ "entry": ["graphql.config.ts", "scripts/measure-pr-preview.ts"],
"ignoreIssues": { "**/*.graphql.ts": ["exports", "types", "namespaceMembers"] },
},
},
diff --git a/packages/client-runtime/src/pullRequestMarkdown.ts b/packages/client-runtime/src/pullRequestMarkdown.ts
index 67ac68e9261..8e342c425db 100644
--- a/packages/client-runtime/src/pullRequestMarkdown.ts
+++ b/packages/client-runtime/src/pullRequestMarkdown.ts
@@ -1,3 +1,5 @@
+import { sourceControlClients } from "./sourceControlClients.ts";
+
/** `id` is positional on purpose: the same attachment can be embedded twice in one body. */
export type PullRequestBodySegment =
| { readonly id: string; readonly kind: "markdown"; readonly text: string }
@@ -21,7 +23,6 @@ const IMAGE_EXTENSION_PATTERN = /\.(?:png|jpe?g|gif|webp|avif|heic|heif|svg)(?:$
const MARKDOWN_LINK_PATTERN = /^\[[^\]]*\]\((https?:\/\/[^\s)]+)\)$/u;
const VIDEO_EXTENSION_PATTERN = /\.(?:mp4|webm|mov|m4v|ogv)(?:$|[?#])/iu;
-const GITHUB_ASSET_PATTERN = /^https:\/\/github\.com\/user-attachments\/assets\/[\w-]+$/iu;
const VIDEO_TAG_SRC_PATTERN = /<(?:video|source)\b[^>]*\bsrc\s*=\s*["']([^"']+)["']/iu;
const STANDALONE_VIDEO_TAG_PATTERN = /^\s*<video\b/iu;
@@ -42,7 +43,7 @@ function attachmentFromLine(
const url =
BARE_URL_PATTERN.exec(line.trim())?.[1] ?? MARKDOWN_LINK_PATTERN.exec(line.trim())?.[1];
if (url === undefined || !isWebUrl(url)) return null;
- if (VIDEO_EXTENSION_PATTERN.test(url) || GITHUB_ASSET_PATTERN.test(url)) {
+ if (VIDEO_EXTENSION_PATTERN.test(url) || sourceControlClients.mediaUrl(url)?.kind === "video") {
return { url, media: "video" };
}
if (IMAGE_EXTENSION_PATTERN.test(url)) return { url, media: "image" };
diff --git a/packages/contracts/src/assets.ts b/packages/contracts/src/assets.ts
index 4726b4d7b92..172b06ac637 100644
--- a/packages/contracts/src/assets.ts
+++ b/packages/contracts/src/assets.ts
@@ -11,6 +11,12 @@ import { ToolActivityNativeAppReference } from "./providerRuntime.ts";
const ASSET_PATH_MAX_LENGTH = 1024;
+/**
+ * The wire tag of a source control host's credentialed media. It names GitHub because GitHub had
+ * it first, and servers and clients of different releases must keep understanding each other.
+ */
+export const SOURCE_CONTROL_MEDIA_ASSET = "github-media" as const;
+
export const AssetResource = Schema.Union([
Schema.TaggedStruct("workspace-file", {
threadId: ThreadId,
@@ -47,10 +53,10 @@ export const AssetResource = Schema.Union([
Schema.TaggedStruct("native-app-icon", {
app: ToolActivityNativeAppReference,
}),
- // An upload a pull request body points at on GitHub. A private repository serves these only
+ // Media a change request body points at on its host. A private repository serves these only
// to a request that carries a credential, which the client has none of, so the server fetches
- // them with the `gh` credential the repository at `cwd` authenticates with.
- Schema.TaggedStruct("github-media", {
+ // them with the credential the host's driver holds for the repository at `cwd`.
+ Schema.TaggedStruct(SOURCE_CONTROL_MEDIA_ASSET, {
cwd: TrimmedNonEmptyString.check(Schema.isMaxLength(ASSET_PATH_MAX_LENGTH)),
url: TrimmedNonEmptyString.check(Schema.isMaxLength(2048)),
}),
@@ -292,12 +298,13 @@ export class AssetSigningKeyLoadError extends Schema.TaggedError<AssetSigningKey
}
}
-export class AssetGitHubMediaUrlValidationError extends Schema.TaggedError<AssetGitHubMediaUrlValidationError>()(
+// The tag predates the rename and stays: clients on either side of an update decode it.
+export class AssetSourceControlMediaUrlValidationError extends Schema.TaggedError<AssetSourceControlMediaUrlValidationError>()(
"AssetGitHubMediaUrlValidationError",
{},
) {
override get message(): string {
- return "Only media hosted by GitHub can be fetched with a GitHub credential.";
+ return "Only media a source control host keeps behind a credential can be fetched with one.";
}
}
@@ -314,7 +321,7 @@ export const AssetAccessError = Schema.Union([
AssetProjectFaviconResolutionError,
AssetProjectFaviconInspectionError,
AssetProjectFaviconNotFoundError,
- AssetGitHubMediaUrlValidationError,
+ AssetSourceControlMediaUrlValidationError,
AssetSigningKeyLoadError,
]);
export type AssetAccessError = typeof AssetAccessError.Type;
diff --git a/packages/shared/package.json b/packages/shared/package.json
index 3fe44db4f34..0fcf52cc880 100644
--- a/packages/shared/package.json
+++ b/packages/shared/package.json
@@ -55,10 +55,6 @@
"types": "./src/git.ts",
"import": "./src/git.ts"
},
- "./githubMedia": {
- "types": "./src/githubMedia.ts",
- "import": "./src/githubMedia.ts"
- },
"./sourceControl": {
"types": "./src/sourceControl.ts",
"import": "./src/sourceControl.ts"
diff --git a/packages/source-control-azure-devops/src/server/driver.ts b/packages/source-control-azure-devops/src/server/driver.ts
index 1d218c30385..d1758ad8ba8 100644
--- a/packages/source-control-azure-devops/src/server/driver.ts
+++ b/packages/source-control-azure-devops/src/server/driver.ts
@@ -1,17 +1,28 @@
-import { defineSourceControlDriver } from "@t3tools/source-control-core/server/driver";
+import {
+ defineSourceControlDriver,
+ withOwnServices,
+} from "@t3tools/source-control-core/server/driver";
import * as Effect from "effect/Effect";
+import * as Layer from "effect/Layer";
import { definition } from "../client/definition.ts";
+import * as AzureDevOpsCli from "./AzureDevOpsCli.ts";
+import * as AzureDevOpsPullRequestCli from "./AzureDevOpsPullRequestCli.ts";
import * as AzureDevOpsPullRequestProvider from "./AzureDevOpsPullRequestProvider.ts";
import * as AzureDevOpsSourceControlProvider from "./AzureDevOpsSourceControlProvider.ts";
+const services = AzureDevOpsPullRequestCli.layer.pipe(Layer.provideMerge(AzureDevOpsCli.layer));
+
+/** Over this host's own services, which `driver` builds; tests stand in for them. */
+export const makeInstance = Effect.all({
+ sourceControl: AzureDevOpsSourceControlProvider.make,
+ discovery: Effect.succeed(AzureDevOpsSourceControlProvider.discovery),
+ pullRequests: AzureDevOpsPullRequestProvider.make,
+});
+
export const driver = defineSourceControlDriver({
kind: definition.kind,
definition,
- make: Effect.all({
- sourceControl: AzureDevOpsSourceControlProvider.make,
- discovery: Effect.succeed(AzureDevOpsSourceControlProvider.discovery),
- pullRequests: AzureDevOpsPullRequestProvider.make,
- }),
+ make: withOwnServices(makeInstance, services),
});
diff --git a/packages/source-control-bitbucket/src/server/BitbucketApi.ts b/packages/source-control-bitbucket/src/server/BitbucketApi.ts
index 07c7064b449..21aa02f34bb 100644
--- a/packages/source-control-bitbucket/src/server/BitbucketApi.ts
+++ b/packages/source-control-bitbucket/src/server/BitbucketApi.ts
@@ -77,6 +77,10 @@ export class BitbucketRepositoryLocatorError extends Schema.TaggedError<Bitbucke
return BitbucketRepositoryLocatorError.detail;
}
+ get userFacingDetail(): string {
+ return BitbucketRepositoryLocatorError.detail;
+ }
+
override get message(): string {
return `Bitbucket API failed: ${this.detail}`;
}
diff --git a/packages/source-control-bitbucket/src/server/BitbucketSourceControlProvider.ts b/packages/source-control-bitbucket/src/server/BitbucketSourceControlProvider.ts
index 976fa1231ba..6154d3e8e96 100644
--- a/packages/source-control-bitbucket/src/server/BitbucketSourceControlProvider.ts
+++ b/packages/source-control-bitbucket/src/server/BitbucketSourceControlProvider.ts
@@ -1,6 +1,7 @@
import { SourceControlProviderKind } from "@t3tools/contracts";
import * as Effect from "effect/Effect";
import * as Option from "effect/Option";
+import * as Schema from "effect/Schema";
import { SourceControlProviderError, type ChangeRequest } from "@t3tools/contracts";
import * as BitbucketApi from "./BitbucketApi.ts";
@@ -8,6 +9,12 @@ import type { NormalizedBitbucketPullRequestRecord } from "./bitbucketPullReques
import * as SourceControlProvider from "@t3tools/source-control-core/server/SourceControlProvider";
import type { SourceControlApiDiscoverySpec } from "@t3tools/source-control-core/server/discovery";
+const isRepositoryLocatorError = Schema.is(BitbucketApi.BitbucketRepositoryLocatorError);
+
+/** A repository named some other way than `workspace/repository` is the user's to fix. */
+const repositoryDetail = (error: BitbucketApi.BitbucketApiError, fallback: string) =>
+ isRepositoryLocatorError(error) ? error.detail : fallback;
+
function toChangeRequest(summary: NormalizedBitbucketPullRequestRecord): ChangeRequest {
return {
provider: SourceControlProviderKind.make("bitbucket"),
@@ -122,7 +129,7 @@ export const make = Effect.gen(function* () {
repository: SourceControlProvider.transportSafeSourceControlErrorValue(
input.repository,
),
- detail: "Failed to get repository clone URLs.",
+ detail: repositoryDetail(error, "Failed to get repository clone URLs."),
cause: error,
}),
),
@@ -138,7 +145,7 @@ export const make = Effect.gen(function* () {
repository: SourceControlProvider.transportSafeSourceControlErrorValue(
input.repository,
),
- detail: "Failed to create repository.",
+ detail: repositoryDetail(error, "Failed to create repository."),
cause: error,
}),
),
diff --git a/packages/source-control-bitbucket/src/server/driver.ts b/packages/source-control-bitbucket/src/server/driver.ts
index 19d35d82015..5cec134e8e7 100644
--- a/packages/source-control-bitbucket/src/server/driver.ts
+++ b/packages/source-control-bitbucket/src/server/driver.ts
@@ -1,17 +1,32 @@
-import { defineSourceControlDriver } from "@t3tools/source-control-core/server/driver";
+import {
+ defineSourceControlDriver,
+ withOwnServices,
+} from "@t3tools/source-control-core/server/driver";
import * as Effect from "effect/Effect";
+import * as Layer from "effect/Layer";
import { definition } from "../client/definition.ts";
+import * as BitbucketApi from "./BitbucketApi.ts";
+import * as BitbucketPullRequestApi from "./BitbucketPullRequestApi.ts";
import * as BitbucketPullRequestProvider from "./BitbucketPullRequestProvider.ts";
import * as BitbucketSourceControlProvider from "./BitbucketSourceControlProvider.ts";
+// Every setting the API reads from the environment is optional, so reading them cannot fail.
+const services = BitbucketPullRequestApi.layer.pipe(
+ Layer.provideMerge(BitbucketApi.layer),
+ Layer.orDie,
+);
+
+/** Over this host's own services, which `driver` builds; tests stand in for them. */
+export const makeInstance = Effect.all({
+ sourceControl: BitbucketSourceControlProvider.make,
+ discovery: BitbucketSourceControlProvider.makeDiscovery,
+ pullRequests: BitbucketPullRequestProvider.make,
+});
+
export const driver = defineSourceControlDriver({
kind: definition.kind,
definition,
- make: Effect.all({
- sourceControl: BitbucketSourceControlProvider.make,
- discovery: BitbucketSourceControlProvider.makeDiscovery,
- pullRequests: BitbucketPullRequestProvider.make,
- }),
+ make: withOwnServices(makeInstance, services),
});
diff --git a/packages/source-control-core/src/client/definition.ts b/packages/source-control-core/src/client/definition.ts
index 9a13dd20a4e..35cc5ddaeba 100644
--- a/packages/source-control-core/src/client/definition.ts
+++ b/packages/source-control-core/src/client/definition.ts
@@ -74,6 +74,16 @@ export interface ChangeRequestCheckoutInput {
readonly repositoryUrl?: string | null | undefined;
}
+/** Media a host serves only to a request carrying a credential, as `mediaUrl` reads it. */
+export interface SourceControlMediaUrl {
+ /** The canonical URL to fetch, the same for every spelling of one file. */
+ readonly fetchUrl: string;
+ /** A file name for the media, safe to put in a path or a download. */
+ readonly fileName: string;
+ /** Set when the URL alone says what the media is, as an extensionless upload can. */
+ readonly kind?: "image" | "video";
+}
+
export interface SourceControlClientDefinition {
readonly kind: SourceControlProviderKind;
readonly label: string;
@@ -141,6 +151,11 @@ export interface SourceControlClientDefinition {
* the provider rather than from the remote.
*/
readonly sshRemoteHidesWebHost?: boolean;
+ /**
+ * Null when `url` is not media this host keeps behind a credential. A client cannot load such
+ * media itself, so it asks the server, whose driver for this host fetches it.
+ */
+ readonly mediaUrl?: (url: URL) => SourceControlMediaUrl | null;
readonly settings?: SourceControlHostSettingsSchema;
}
@@ -342,6 +357,10 @@ export interface ParsedChangeRequest {
readonly link: ParsedChangeRequestUrl;
}
+export interface SourceControlMedia extends SourceControlMediaUrl {
+ readonly definition: SourceControlClientDefinition;
+}
+
export interface SourceControlClientRegistry {
readonly definitions: ReadonlyArray<SourceControlClientDefinition>;
readonly get: (kind: string | null | undefined) => SourceControlClientDefinition;
@@ -370,6 +389,8 @@ export interface SourceControlClientRegistry {
identity: ChangeRequestHostIdentity,
kind: Kind,
) => string | Kind;
+ /** The first host, in registry order, that keeps `url` behind a credential. */
+ readonly mediaUrl: (url: string) => SourceControlMedia | null;
}
function httpUrl(value: string): URL | null {
@@ -494,6 +515,15 @@ export function makeSourceControlClientRegistry(
changeRequestHost: (identity, kind) =>
(kind === undefined ? undefined : byKind.get(kind)?.changeRequestHost?.(identity)) ??
projectChangeRequestHost(identity, kind),
+ mediaUrl: (value) => {
+ const url = httpUrl(value);
+ if (url === null) return null;
+ for (const definition of definitions) {
+ const media = definition.mediaUrl?.(url);
+ if (media != null) return { ...media, definition };
+ }
+ return null;
+ },
};
}
diff --git a/packages/source-control-core/src/server/SourceControlProvider.ts b/packages/source-control-core/src/server/SourceControlProvider.ts
index e149fcd202a..23e26dcf0d7 100644
--- a/packages/source-control-core/src/server/SourceControlProvider.ts
+++ b/packages/source-control-core/src/server/SourceControlProvider.ts
@@ -38,6 +38,19 @@ export interface SourceControlRefSelector {
const MAX_ERROR_TRANSPORT_VALUE_LENGTH = 256;
+/**
+ * The fixed product text a provider failure carries for the user, if it has one. Any other
+ * detail may be upstream response text, so callers show a generic message instead.
+ */
+export function userFacingSourceControlDetail(cause: unknown): string | undefined {
+ return typeof cause === "object" &&
+ cause !== null &&
+ "userFacingDetail" in cause &&
+ typeof cause.userFacingDetail === "string"
+ ? cause.userFacingDetail
+ : undefined;
+}
+
export function transportSafeSourceControlErrorValue(value: string): string {
let printable = "";
for (const character of value) {
diff --git a/packages/source-control-core/src/server/driver.ts b/packages/source-control-core/src/server/driver.ts
index 360868770ab..9007dad84f0 100644
--- a/packages/source-control-core/src/server/driver.ts
+++ b/packages/source-control-core/src/server/driver.ts
@@ -1,25 +1,76 @@
import type { SourceControlProviderKind } from "@t3tools/contracts";
-import type * as Effect from "effect/Effect";
+import type * as Crypto from "effect/Crypto";
+import * as Effect from "effect/Effect";
+import type * as FileSystem from "effect/FileSystem";
+import type { HttpClient, HttpClientError, HttpClientResponse } from "effect/http";
+import * as Layer from "effect/Layer";
+import type * as Scope from "effect/Scope";
import type { SourceControlClientDefinition } from "../client/definition.ts";
import type { SourceControlProviderDiscoverySpec } from "./discovery.ts";
import type { PullRequestProviderApi } from "./PullRequestProvider.ts";
+import type * as SourceControlHost from "./SourceControlHost.ts";
import type * as SourceControlProvider from "./SourceControlProvider.ts";
+import type * as SourceControlRateLimit from "./SourceControlRateLimit.ts";
+
+export interface SourceControlMediaRequest {
+ /** A `fetchUrl` this host's definition returned from `mediaUrl`. */
+ readonly url: string;
+ /** Request headers to forward, such as `range`. */
+ readonly headers: Readonly<Record<string, string>>;
+}
export interface SourceControlDriverInstance {
readonly sourceControl: SourceControlProvider.SourceControlProvider["Service"];
readonly discovery: SourceControlProviderDiscoverySpec;
/** Null for a host whose pull requests this build cannot read. */
readonly pullRequests: PullRequestProviderApi | null;
+ /**
+ * Fetches media the definition's `mediaUrl` claimed, with the credential the host serves it
+ * to. Null when the fetch went nowhere a response could come from, such as a redirect loop.
+ */
+ readonly fetchMedia?: (
+ request: SourceControlMediaRequest,
+ ) => Effect.Effect<
+ HttpClientResponse.HttpClientResponse | null,
+ HttpClientError.HttpClientError,
+ Scope.Scope
+ >;
}
-export interface SourceControlDriver<R = never> {
+/** What the server gives every driver. A driver builds anything else it needs itself. */
+export type SourceControlDriverServices =
+ | SourceControlHost.SourceControlHost
+ | SourceControlRateLimit.SourceControlRateLimit
+ | HttpClient.HttpClient
+ | FileSystem.FileSystem
+ | Crypto.Crypto;
+
+export interface SourceControlDriver {
readonly kind: SourceControlProviderKind;
readonly definition: SourceControlClientDefinition;
- readonly make: Effect.Effect<SourceControlDriverInstance, never, R>;
+ /**
+ * Run once per server, in a scope that lasts as long as the server. State a host shares across
+ * everything that talks to it, such as GitHub's quota reserve and rate-limit pause, lives in
+ * what this builds, so building it twice would split that state.
+ */
+ readonly make: Effect.Effect<
+ SourceControlDriverInstance,
+ never,
+ SourceControlDriverServices | Scope.Scope
+ >;
}
-export const defineSourceControlDriver = <R>(
- driver: SourceControlDriver<R>,
-): SourceControlDriver<R> => driver;
+export const defineSourceControlDriver = (driver: SourceControlDriver): SourceControlDriver =>
+ driver;
+
+/**
+ * `make` over a host's own `services`, built into the caller's scope so they live as long as the
+ * instance that holds them.
+ */
+export const withOwnServices = <A, R, ROut, RIn>(
+ make: Effect.Effect<A, never, R>,
+ services: Layer.Layer<ROut, never, RIn>,
+): Effect.Effect<A, never, Exclude<R, ROut> | RIn | Scope.Scope> =>
+ Layer.build(services).pipe(Effect.flatMap((context) => make.pipe(Effect.provide(context))));
diff --git a/packages/source-control-forgejo/src/server/driver.ts b/packages/source-control-forgejo/src/server/driver.ts
index 7324741656c..b96b50a4f8a 100644
--- a/packages/source-control-forgejo/src/server/driver.ts
+++ b/packages/source-control-forgejo/src/server/driver.ts
@@ -1,17 +1,26 @@
-import { defineSourceControlDriver } from "@t3tools/source-control-core/server/driver";
+import {
+ defineSourceControlDriver,
+ withOwnServices,
+} from "@t3tools/source-control-core/server/driver";
import * as Effect from "effect/Effect";
import { definition } from "../client/definition.ts";
+import * as ForgejoCli from "./ForgejoCli.ts";
import * as ForgejoPullRequestProvider from "./ForgejoPullRequestProvider.ts";
import * as ForgejoSourceControlProvider from "./ForgejoSourceControlProvider.ts";
+const services = ForgejoCli.layer;
+
+/** Over this host's own services, which `driver` builds; tests stand in for them. */
+export const makeInstance = Effect.all({
+ sourceControl: ForgejoSourceControlProvider.make,
+ discovery: ForgejoSourceControlProvider.makeDiscovery,
+ pullRequests: ForgejoPullRequestProvider.make,
+});
+
export const driver = defineSourceControlDriver({
kind: definition.kind,
definition,
- make: Effect.all({
- sourceControl: ForgejoSourceControlProvider.make,
- discovery: ForgejoSourceControlProvider.makeDiscovery,
- pullRequests: ForgejoPullRequestProvider.make,
- }),
+ make: withOwnServices(makeInstance, services),
});
diff --git a/packages/source-control-gitcafe/src/server/driver.ts b/packages/source-control-gitcafe/src/server/driver.ts
index dca35f45b75..3fdc129ac40 100644
--- a/packages/source-control-gitcafe/src/server/driver.ts
+++ b/packages/source-control-gitcafe/src/server/driver.ts
@@ -1,17 +1,28 @@
-import { defineSourceControlDriver } from "@t3tools/source-control-core/server/driver";
+import {
+ defineSourceControlDriver,
+ withOwnServices,
+} from "@t3tools/source-control-core/server/driver";
import * as Effect from "effect/Effect";
+import * as Layer from "effect/Layer";
import { definition } from "../client/definition.ts";
+import * as GitCafeApi from "./GitCafeApi.ts";
+import * as GitCafeCredentials from "./GitCafeCredentials.ts";
import * as GitCafePullRequestProvider from "./GitCafePullRequestProvider.ts";
import * as GitCafeSourceControlProvider from "./GitCafeSourceControlProvider.ts";
+const services = GitCafeApi.layer.pipe(Layer.provideMerge(GitCafeCredentials.layer));
+
+/** Over this host's own services, which `driver` builds; tests stand in for them. */
+export const makeInstance = Effect.all({
+ sourceControl: GitCafeSourceControlProvider.make,
+ discovery: GitCafeSourceControlProvider.makeDiscovery,
+ pullRequests: GitCafePullRequestProvider.make,
+});
+
export const driver = defineSourceControlDriver({
kind: definition.kind,
definition,
- make: Effect.all({
- sourceControl: GitCafeSourceControlProvider.make,
- discovery: GitCafeSourceControlProvider.makeDiscovery,
- pullRequests: GitCafePullRequestProvider.make,
- }),
+ make: withOwnServices(makeInstance, services),
});
diff --git a/apps/server/scripts/measure-pr-preview.ts b/packages/source-control-github/scripts/measure-pr-preview.ts
similarity index 69%
rename from apps/server/scripts/measure-pr-preview.ts
rename to packages/source-control-github/scripts/measure-pr-preview.ts
index 5a37b685832..448984f5ce8 100644
--- a/apps/server/scripts/measure-pr-preview.ts
+++ b/packages/source-control-github/scripts/measure-pr-preview.ts
@@ -1,30 +1,29 @@
-// Run with: node apps/server/scripts/measure-pr-preview.ts owner/repo 123 456
+// Run with: node packages/source-control-github/scripts/measure-pr-preview.ts owner/repo 123 456
// Numbers form a session with shared repository-permission caches. Browser and
// service caches are excluded. Uses real GitHub reads, without a server or database.
// Requests are counted at the HTTP client. A GraphQL request's cost is how far it moved GitHub's
// `x-ratelimit-used` for the `graphql` resource, which is approximate when anything else spends
// the same token's quota while this runs.
import * as NodeServices from "@effect/platform-node/NodeServices";
+import * as SourceControlRateLimit from "@t3tools/source-control-core/server/SourceControlRateLimit";
+import * as TestSourceControlHost from "@t3tools/source-control-testing/TestSourceControlHost";
import * as Effect from "effect/Effect";
import * as Console from "effect/Console";
import * as Layer from "effect/Layer";
import * as Schema from "effect/Schema";
+import * as Stream from "effect/Stream";
import { FetchHttpClient, HttpClient } from "effect/http";
+import { ChildProcess, ChildProcessSpawner } from "effect/process";
-import * as GitHubPullRequestApi from "@t3tools/source-control-github/server/GitHubPullRequestApi";
-import * as GitHubPullRequestProvider from "@t3tools/source-control-github/server/GitHubPullRequestProvider";
-import * as GitHubRest from "@t3tools/source-control-github/server/GitHubRest";
-import * as ServerConfig from "../src/config.ts";
-import * as ServerSettings from "../src/serverSettings.ts";
-import * as ServerSourceControlHost from "../src/sourceControl/ServerSourceControlHost.ts";
-import * as GitVcsDriver from "../src/vcs/GitVcsDriver.ts";
-import * as VcsDriverRegistry from "../src/vcs/VcsDriverRegistry.ts";
-import * as VcsProcess from "../src/vcs/VcsProcess.ts";
-import * as VcsProjectConfig from "../src/vcs/VcsProjectConfig.ts";
+import * as GitHubPullRequestApi from "../src/server/GitHubPullRequestApi.ts";
+import * as GitHubPullRequestProvider from "../src/server/GitHubPullRequestProvider.ts";
+import * as GitHubRest from "../src/server/GitHubRest.ts";
const [repository, ...numbers] = process.argv.slice(2);
if (!repository || numbers.length === 0 || numbers.some((number) => !/^\d+$/.test(number))) {
- throw new Error("Usage: node apps/server/scripts/measure-pr-preview.ts owner/repo number...");
+ throw new Error(
+ "Usage: node packages/source-control-github/scripts/measure-pr-preview.ts owner/repo number...",
+ );
}
type Read = { graphqlRequests: number; restRequests: number; cost: number };
@@ -73,18 +72,42 @@ const measuredHttp = Layer.effect(
}),
).pipe(Layer.provide(FetchHttpClient.layer));
-// The server's host port over default settings: gh's own account choice, no saved token.
-const sourceControlHost = ServerSourceControlHost.layer.pipe(
- Layer.provide(VcsDriverRegistry.layer.pipe(Layer.provide(VcsProjectConfig.layer))),
- Layer.provide(GitVcsDriver.layer),
- Layer.provide(ServerSettings.layerTest()),
- Layer.provide(ServerConfig.layerTest(process.cwd(), { prefix: "t3-measure-pr-preview-" })),
- Layer.provideMerge(VcsProcess.layer),
- Layer.provideMerge(NodeServices.layer),
-);
+// Default settings, so `gh` picks the account and no saved token applies. Only the credential
+// lookup runs a process, and it needs no more than its output.
+const sourceControlHost = Layer.unwrap(
+ Effect.gen(function* () {
+ const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
+ return TestSourceControlHost.layer({
+ process: {
+ run: (input) =>
+ Effect.scoped(
+ Effect.gen(function* () {
+ const handle = yield* spawner.spawn(
+ ChildProcess.make(input.command, [...input.args], {
+ cwd: input.spawnCwd ?? input.cwd,
+ env: input.env,
+ extendEnv: true,
+ }),
+ );
+ const [stdout, stderr, exitCode] = yield* Effect.all(
+ [
+ Stream.mkString(Stream.decodeText(handle.stdout)),
+ Stream.mkString(Stream.decodeText(handle.stderr)),
+ handle.exitCode,
+ ],
+ { concurrency: "unbounded" },
+ );
+ return { exitCode, stdout, stderr, stdoutTruncated: false, stderrTruncated: false };
+ }),
+ ).pipe(Effect.orDie),
+ },
+ });
+ }),
+).pipe(Layer.provideMerge(NodeServices.layer));
const services = GitHubPullRequestApi.layer.pipe(
Layer.provideMerge(GitHubRest.layerWithDependencies),
+ Layer.provideMerge(SourceControlRateLimit.layer),
Layer.provideMerge(measuredHttp),
Layer.provideMerge(sourceControlHost),
);
diff --git a/packages/source-control-github/src/client/definition.test.ts b/packages/source-control-github/src/client/definition.test.ts
index c929be7167a..30fcf7ccc17 100644
--- a/packages/source-control-github/src/client/definition.test.ts
+++ b/packages/source-control-github/src/client/definition.test.ts
@@ -121,3 +121,41 @@ describe("GitHub remotes", () => {
expect(recognize("https://notgithub.example.com/owner/repo.git")).toBeNull();
});
});
+
+describe("GitHub media URLs", () => {
+ const media = (url: string) => definition.mediaUrl(new URL(url));
+
+ it("fetches every spelling of an upload or committed file from one canonical URL", () => {
+ expect(
+ media("https://github.com/user-attachments/assets/1a1842fb-6383-492f-873c-57aa0033fa6c"),
+ ).toEqual({
+ fetchUrl: "https://github.com/user-attachments/assets/1a1842fb-6383-492f-873c-57aa0033fa6c",
+ fileName: "1a1842fb-6383-492f-873c-57aa0033fa6c",
+ kind: "video",
+ });
+ expect(media("https://github.com/owner/repo/blob/main/docs/shot.png")).toEqual({
+ fetchUrl: "https://raw.githubusercontent.com/owner/repo/main/docs/shot.png",
+ fileName: "shot.png",
+ });
+ expect(media("https://github.com/owner/repo/assets/45952064/1a1842fb")?.fetchUrl).toBe(
+ "https://github.com/owner/repo/assets/45952064/1a1842fb",
+ );
+ expect(media("https://media.githubusercontent.com/media/owner/repo/main/a.mp4")).toEqual({
+ fetchUrl: "https://media.githubusercontent.com/media/owner/repo/main/a.mp4",
+ fileName: "a.mp4",
+ });
+ expect(media("https://raw.githubusercontent.com/o/r/main/100%.png")?.fileName).toBe("100%.png");
+ });
+
+ it("claims nothing a request without a credential loads just as well", () => {
+ for (const url of [
+ "https://example.com/shot.png",
+ "http://github.com/user-attachments/assets/1a1842fb",
+ "https://github.com/owner/repo/pull/1",
+ "https://github.com/owner/repo/blob/main/",
+ "https://objects.githubusercontent.com/github-production-user-asset/shot.png",
+ ]) {
+ expect(media(url), url).toBeNull();
+ }
+ });
+});
diff --git a/packages/source-control-github/src/client/definition.ts b/packages/source-control-github/src/client/definition.ts
index c022ed824b4..86268f29d40 100644
--- a/packages/source-control-github/src/client/definition.ts
+++ b/packages/source-control-github/src/client/definition.ts
@@ -18,6 +18,8 @@ import {
remoteWebOrigin,
} from "@t3tools/source-control-core/client/definition";
+import { gitHubMediaUrl } from "./gitHubMedia.ts";
+
const CHECKOUT_COMMAND = /^gh\s+pr\s+checkout\s+(.+)$/i;
const CHANGE_REQUEST_REFERENCE =
/^https:\/\/github\.com\/[^/\s]+\/[^/\s]+\/pull\/(\d+)(?:[/?#].*)?$/i;
@@ -134,5 +136,6 @@ export const definition = defineSourceControlClient({
isChangeRequestInProjectRepository(projectChangeRequestHost(identity, KIND), identity, link),
canReadChangeRequestOnHost: (identity, link) =>
isChangeRequestOnProjectHost(projectChangeRequestHost(identity, KIND), identity, link),
+ mediaUrl: gitHubMediaUrl,
settings,
});
diff --git a/packages/shared/src/githubMedia.ts b/packages/source-control-github/src/client/gitHubMedia.ts
similarity index 51%
rename from packages/shared/src/githubMedia.ts
rename to packages/source-control-github/src/client/gitHubMedia.ts
index 2d2797d09bc..51b9e0598fa 100644
--- a/packages/shared/src/githubMedia.ts
+++ b/packages/source-control-github/src/client/gitHubMedia.ts
@@ -1,44 +1,25 @@
+import type { SourceControlMediaUrl } from "@t3tools/source-control-core/client/definition";
+
/**
* Only hosts where a credential is what decides the answer belong here. `objects.githubusercontent.com`
* and the `private-user-images` links GitHub's own HTML carries are already signed and load on their
* own, and a token does nothing for them once that signature expires.
*/
-
+const WEB_HOSTS = new Set(["github.com", "www.github.com"]);
const RAW_HOST = "raw.githubusercontent.com";
const LFS_HOST = "media.githubusercontent.com";
+export const GITHUB_CREDENTIALED_MEDIA_HOSTS: ReadonlySet<string> = new Set([
+ ...WEB_HOSTS,
+ RAW_HOST,
+ LFS_HOST,
+]);
+
const ATTACHMENT_PATH_PATTERN = /^\/user-attachments\/assets\/[\w-]+$/u;
const LEGACY_ATTACHMENT_PATH_PATTERN = /^\/[^/]+\/[^/]+\/assets\/\d+\/[\w-]+$/u;
/** `blob` and `raw` both address file bytes; `raw` is the one the token is honoured on. */
const REPOSITORY_FILE_PATTERN = /^\/([^/]+)\/([^/]+)\/(?:raw|blob)\/(.*[^/])$/u;
-function canonicalUrl(host: string, url: URL): string {
- return `https://${host}${url.pathname}${url.search}`;
-}
-
-export function githubMediaFetchUrl(source: string): string | null {
- let url: URL;
- try {
- url = new URL(source);
- } catch {
- return null;
- }
- if (url.protocol !== "https:") return null;
- const host = url.hostname.toLowerCase();
- if (host === RAW_HOST || host === LFS_HOST) return canonicalUrl(host, url);
- if (host !== "github.com" && host !== "www.github.com") return null;
- if (
- ATTACHMENT_PATH_PATTERN.test(url.pathname) ||
- LEGACY_ATTACHMENT_PATH_PATTERN.test(url.pathname)
- ) {
- return `https://github.com${url.pathname}`;
- }
- const repositoryFile = REPOSITORY_FILE_PATTERN.exec(url.pathname);
- return repositoryFile
- ? `https://${RAW_HOST}/${repositoryFile[1]}/${repositoryFile[2]}/${repositoryFile[3]}`
- : null;
-}
-
-export function githubMediaFileName(fetchUrl: string): string {
+function fileName(fetchUrl: string): string {
const segment = new URL(fetchUrl).pathname.split("/").pop() ?? "";
let decoded: string;
try {
@@ -49,3 +30,27 @@ export function githubMediaFileName(fetchUrl: string): string {
const name = decoded.replace(/[\p{Cc}\\/]/gu, "");
return name.length > 0 ? name : "github-media";
}
+
+function media(fetchUrl: string, kind?: "video"): SourceControlMediaUrl {
+ return { fetchUrl, fileName: fileName(fetchUrl), ...(kind ? { kind } : {}) };
+}
+
+export function gitHubMediaUrl(url: URL): SourceControlMediaUrl | null {
+ if (url.protocol !== "https:") return null;
+ const host = url.hostname.toLowerCase();
+ if (host === RAW_HOST || host === LFS_HOST) {
+ return media(`https://${host}${url.pathname}${url.search}`);
+ }
+ if (!WEB_HOSTS.has(host)) return null;
+ // GitHub links an uploaded video bare, with no extension, and an image as markdown.
+ if (ATTACHMENT_PATH_PATTERN.test(url.pathname)) {
+ return media(`https://github.com${url.pathname}`, "video");
+ }
+ if (LEGACY_ATTACHMENT_PATH_PATTERN.test(url.pathname)) {
+ return media(`https://github.com${url.pathname}`);
+ }
+ const repositoryFile = REPOSITORY_FILE_PATTERN.exec(url.pathname);
+ return repositoryFile
+ ? media(`https://${RAW_HOST}/${repositoryFile[1]}/${repositoryFile[2]}/${repositoryFile[3]}`)
+ : null;
+}
diff --git a/packages/source-control-github/src/server/GitHubRest.ts b/packages/source-control-github/src/server/GitHubRest.ts
index 6ed65eebabf..a29505ecc7a 100644
--- a/packages/source-control-github/src/server/GitHubRest.ts
+++ b/packages/source-control-github/src/server/GitHubRest.ts
@@ -232,12 +232,11 @@ export const layer = Layer.effect(GitHubRest, make).pipe(
);
/**
- * REST and the request policy, with the credential, quota reserve and rate-limit pause the policy
- * reads through: everything both transports need. An application builds this once so every GitHub
- * reader shares one view of each quota per host.
+ * REST and the request policy, with the credential and quota reserve the policy reads through.
+ * Built once, so every GitHub reader shares one view of each quota per host. The rate-limit pause
+ * comes from the server, which every host's change request reads share.
*/
export const layerWithDependencies = layer.pipe(
Layer.provideMerge(GitHubCredentials.layer),
Layer.provideMerge(GitHubQuota.layer),
- Layer.provideMerge(SourceControlRateLimit.layer),
);
diff --git a/packages/source-control-github/src/server/driver.ts b/packages/source-control-github/src/server/driver.ts
index d5247732936..2afcd0898c0 100644
--- a/packages/source-control-github/src/server/driver.ts
+++ b/packages/source-control-github/src/server/driver.ts
@@ -1,17 +1,34 @@
-import { defineSourceControlDriver } from "@t3tools/source-control-core/server/driver";
+import {
+ defineSourceControlDriver,
+ withOwnServices,
+} from "@t3tools/source-control-core/server/driver";
import * as Effect from "effect/Effect";
+import * as Layer from "effect/Layer";
import { definition } from "../client/definition.ts";
+import * as GitHubMediaFetch from "./gitHubMediaFetch.ts";
+import * as GitHubPullRequestApi from "./GitHubPullRequestApi.ts";
import * as GitHubPullRequestProvider from "./GitHubPullRequestProvider.ts";
+import * as GitHubRest from "./GitHubRest.ts";
import * as GitHubSourceControlProvider from "./GitHubSourceControlProvider.ts";
+// `GitHubRest.layerWithDependencies` carries the quota reserve every GitHub reader shares, so it
+// must be built once; the driver is.
+const services = GitHubPullRequestApi.layer.pipe(
+ Layer.provideMerge(GitHubRest.layerWithDependencies),
+);
+
+/** Over this host's own services, which `driver` builds; tests stand in for them. */
+export const makeInstance = Effect.all({
+ sourceControl: GitHubSourceControlProvider.make,
+ discovery: GitHubSourceControlProvider.makeDiscovery,
+ pullRequests: GitHubPullRequestProvider.make,
+ fetchMedia: GitHubMediaFetch.make,
+});
+
export const driver = defineSourceControlDriver({
kind: definition.kind,
definition,
- make: Effect.all({
- sourceControl: GitHubSourceControlProvider.make,
- discovery: GitHubSourceControlProvider.makeDiscovery,
- pullRequests: GitHubPullRequestProvider.make,
- }),
+ make: withOwnServices(makeInstance, services),
});
diff --git a/packages/source-control-github/src/server/gitHubMediaFetch.test.ts b/packages/source-control-github/src/server/gitHubMediaFetch.test.ts
new file mode 100644
index 00000000000..07e2bbd8f72
--- /dev/null
+++ b/packages/source-control-github/src/server/gitHubMediaFetch.test.ts
@@ -0,0 +1,104 @@
+import { describe, expect, it } from "@effect/vitest";
+import * as Effect from "effect/Effect";
+import * as Layer from "effect/Layer";
+import * as Redacted from "effect/Redacted";
+import { HttpClient, HttpClientResponse } from "effect/http";
+
+import * as GitHubCredentials from "./GitHubCredentials.ts";
+import * as GitHubMediaFetch from "./gitHubMediaFetch.ts";
+
+describe("GitHubMediaFetch", () => {
+ it.effect("loads private media immediately after login with the GitHub credential", () => {
+ let lookups = 0;
+ const authorizations: Array<string | undefined> = [];
+ return Effect.gen(function* () {
+ const fetchMedia = yield* GitHubMediaFetch.make;
+ const request = {
+ url: "https://raw.githubusercontent.com/owner/repo/main/shot.png",
+ headers: {},
+ };
+ expect((yield* fetchMedia(request))?.status).toBe(404);
+ expect((yield* fetchMedia(request))?.status).toBe(200);
+ expect((yield* fetchMedia(request))?.status).toBe(200);
+ expect(lookups).toBe(3);
+ expect(authorizations).toEqual([undefined, "Bearer signed-in", "Bearer signed-in"]);
+ }).pipe(
+ Effect.provide(
+ Layer.mock(GitHubCredentials.GitHubCredentials)({
+ get: (host) =>
+ ++lookups === 1
+ ? Effect.fail(new GitHubCredentials.GitHubNotSignedInError({ host }))
+ : Effect.succeed({
+ host,
+ token: Redacted.make("signed-in"),
+ source: "gh" as const,
+ fingerprint: "fingerprint",
+ }),
+ }),
+ ),
+ Effect.provideService(
+ HttpClient.HttpClient,
+ HttpClient.make((request) => {
+ authorizations.push(request.headers.authorization);
+ return Effect.succeed(
+ HttpClientResponse.fromWeb(
+ request,
+ new Response(null, {
+ status: request.headers.authorization ? 200 : 404,
+ headers: { "content-type": "image/png" },
+ }),
+ ),
+ );
+ }),
+ ),
+ Effect.scoped,
+ );
+ });
+
+ it.effect("keeps the credential off the object store a redirect hands the media to", () => {
+ const authorizations: Array<[string, string | undefined]> = [];
+ return Effect.gen(function* () {
+ const fetchMedia = yield* GitHubMediaFetch.make;
+ const response = yield* fetchMedia({
+ url: "https://github.com/user-attachments/assets/1a1842fb",
+ headers: { range: "bytes=0-1" },
+ });
+ expect(response?.status).toBe(200);
+ expect(authorizations).toEqual([
+ ["github.com", "Bearer signed-in"],
+ ["objects.example.com", undefined],
+ ]);
+ }).pipe(
+ Effect.provide(
+ Layer.mock(GitHubCredentials.GitHubCredentials)({
+ get: (host) =>
+ Effect.succeed({
+ host,
+ token: Redacted.make("signed-in"),
+ source: "gh" as const,
+ fingerprint: "fingerprint",
+ }),
+ }),
+ ),
+ Effect.provideService(
+ HttpClient.HttpClient,
+ HttpClient.make((request) => {
+ const url = new URL(request.url);
+ authorizations.push([url.hostname, request.headers.authorization]);
+ return Effect.succeed(
+ HttpClientResponse.fromWeb(
+ request,
+ url.hostname === "github.com"
+ ? new Response(null, {
+ status: 302,
+ headers: { location: "https://objects.example.com/signed" },
+ })
+ : new Response(null, { status: 200 }),
+ ),
+ );
+ }),
+ ),
+ Effect.scoped,
+ );
+ });
+});
diff --git a/packages/source-control-github/src/server/gitHubMediaFetch.ts b/packages/source-control-github/src/server/gitHubMediaFetch.ts
new file mode 100644
index 00000000000..a360f873ae1
--- /dev/null
+++ b/packages/source-control-github/src/server/gitHubMediaFetch.ts
@@ -0,0 +1,68 @@
+import type { SourceControlMediaRequest } from "@t3tools/source-control-core/server/driver";
+import * as Effect from "effect/Effect";
+import * as Redacted from "effect/Redacted";
+import {
+ FetchHttpClient,
+ HttpClient,
+ HttpClientRequest,
+ type HttpClientResponse,
+} from "effect/http";
+
+import { GITHUB_CREDENTIALED_MEDIA_HOSTS } from "../client/gitHubMedia.ts";
+
+import * as GitHubCredentials from "./GitHubCredentials.ts";
+
+/**
+ * Everything a redirect leads to — the presigned object stores GitHub hands assets off to —
+ * authorizes with its own signature, and some of them reject a request that also carries a
+ * bearer token.
+ */
+const isCredentialedHost = (url: string) => {
+ try {
+ return GITHUB_CREDENTIALED_MEDIA_HOSTS.has(new URL(url).hostname.toLowerCase());
+ } catch {
+ return false;
+ }
+};
+
+const MAX_REDIRECTS = 3;
+const MANUAL_REDIRECT: RequestInit = { redirect: "manual" };
+
+export const make = Effect.gen(function* () {
+ const credentials = yield* GitHubCredentials.GitHubCredentials;
+ const httpClient = HttpClient.withScope(yield* HttpClient.HttpClient);
+
+ // Both media hosts are served by github.com's account, which is the host `gh` stores it under.
+ // Read on every fetch, so media loads as soon as the user signs in.
+ const token = Effect.suspend(() => credentials.get("github.com")).pipe(
+ Effect.map((credential) => credential.token),
+ Effect.orElseSucceed(() => null),
+ );
+
+ return Effect.fn("GitHubMediaFetch.fetchMedia")(function* (request: SourceControlMediaRequest) {
+ const bearer = yield* token;
+ let target = request.url;
+ for (let hop = 0; ; hop += 1) {
+ const authorization =
+ bearer !== null && isCredentialedHost(target) ? `Bearer ${Redacted.value(bearer)}` : null;
+ const response: HttpClientResponse.HttpClientResponse = yield* httpClient
+ .execute(
+ HttpClientRequest.get(target).pipe(
+ HttpClientRequest.setHeaders({
+ ...request.headers,
+ // The bytes are streamed straight through, so never let an encoding layer in.
+ "accept-encoding": "identity",
+ ...(authorization === null ? {} : { authorization }),
+ }),
+ ),
+ )
+ .pipe(Effect.provideService(FetchHttpClient.RequestInit, MANUAL_REDIRECT));
+ const location = response.headers.location;
+ if (response.status < 300 || response.status >= 400) return response;
+ if (!location || hop >= MAX_REDIRECTS) return null;
+ const next = new URL(location, target);
+ if (next.protocol !== "https:") return null;
+ target = next.toString();
+ }
+ });
+});
diff --git a/packages/source-control-github/tsconfig.json b/packages/source-control-github/tsconfig.json
index 374bac55202..154996e94d3 100644
--- a/packages/source-control-github/tsconfig.json
+++ b/packages/source-control-github/tsconfig.json
@@ -3,5 +3,5 @@
"compilerOptions": {
"types": ["node"]
},
- "include": ["src"]
+ "include": ["src", "scripts"]
}
diff --git a/packages/source-control-gitlab/src/server/driver.ts b/packages/source-control-gitlab/src/server/driver.ts
index 175efc16269..faf30e3406a 100644
--- a/packages/source-control-gitlab/src/server/driver.ts
+++ b/packages/source-control-gitlab/src/server/driver.ts
@@ -1,17 +1,28 @@
-import { defineSourceControlDriver } from "@t3tools/source-control-core/server/driver";
+import {
+ defineSourceControlDriver,
+ withOwnServices,
+} from "@t3tools/source-control-core/server/driver";
import * as Effect from "effect/Effect";
+import * as Layer from "effect/Layer";
import { definition } from "../client/definition.ts";
+import * as GitLabCli from "./GitLabCli.ts";
+import * as GitLabPullRequestCli from "./GitLabPullRequestCli.ts";
import * as GitLabPullRequestProvider from "./GitLabPullRequestProvider.ts";
import * as GitLabSourceControlProvider from "./GitLabSourceControlProvider.ts";
+const services = GitLabPullRequestCli.layer.pipe(Layer.provideMerge(GitLabCli.layer));
+
+/** Over this host's own services, which `driver` builds; tests stand in for them. */
+export const makeInstance = Effect.all({
+ sourceControl: GitLabSourceControlProvider.make,
+ discovery: Effect.succeed(GitLabSourceControlProvider.discovery),
+ pullRequests: GitLabPullRequestProvider.make,
+});
+
export const driver = defineSourceControlDriver({
kind: definition.kind,
definition,
- make: Effect.all({
- sourceControl: GitLabSourceControlProvider.make,
- discovery: Effect.succeed(GitLabSourceControlProvider.discovery),
- pullRequests: GitLabPullRequestProvider.make,
- }),
+ make: withOwnServices(makeInstance, services),
});