Open History to see the last commit
1import * as NodeUtil from "node:util";
2import type {
3 SourceControlProviderAuth,
4 SourceControlProviderDiscoveryItem,
5 SourceControlProviderInfo,
6 SourceControlProviderKind,
7} from "@t3tools/contracts";
8import * as Effect from "effect/Effect";
9import * as Option from "effect/Option";
10
11import type * as SourceControlProvider from "./SourceControlProvider.ts";
12import type * as VcsProcess from "../vcs/VcsProcess.ts";
13
14export interface SourceControlAuthProbeInput {
15 readonly stdout: string;
16 readonly stderr: string;
17 readonly exitCode: VcsProcess.VcsProcessOutput["exitCode"];
18}
19
20export interface SourceControlUnknownRemoteRefinementInput {
21 readonly cwd: string;
22 readonly context: SourceControlProvider.SourceControlProviderContext;
23 readonly auth: SourceControlAuthProbeInput;
24}
25
26interface SourceControlDiscoverySpecBase {
27 readonly kind: SourceControlProviderKind;
28 readonly label: string;
29 readonly installHint: string;
30}
31
32export type SourceControlCliDiscoverySpec = SourceControlDiscoverySpecBase & {
33 readonly type: "cli";
34 readonly executable: string;
35 readonly versionArgs: ReadonlyArray<string>;
36 readonly authArgs: ReadonlyArray<string>;
37 readonly remoteRefinementArgs?: ReadonlyArray<string>;
38 readonly probeTimeoutMs?: number;
39 readonly parseAuth: (input: SourceControlAuthProbeInput) => SourceControlProviderAuth;
40 readonly refineUnknownRemote?: (
41 input: SourceControlUnknownRemoteRefinementInput,
42 ) => SourceControlProviderInfo | null;
43};
44
45export type SourceControlApiDiscoverySpec = SourceControlDiscoverySpecBase & {
46 readonly type: "api";
47 readonly probeAuth: Effect.Effect<SourceControlProviderAuth, never>;
48};
49
50export type SourceControlManagedCliDiscoverySpec = SourceControlDiscoverySpecBase & {
51 readonly type: "managed-cli";
52 readonly probe: (cwd: string) => Effect.Effect<SourceControlProviderDiscoveryItem>;
53 readonly refineUnknownRemote: (input: {
54 readonly cwd: string;
55 readonly context: SourceControlProvider.SourceControlProviderContext;
56 }) => Effect.Effect<SourceControlProviderInfo | null>;
57};
58
59export type SourceControlProviderDiscoverySpec =
60 | SourceControlCliDiscoverySpec
61 | SourceControlManagedCliDiscoverySpec
62 | SourceControlApiDiscoverySpec;
63
64type SourceControlCliRemoteRefinementSpec = SourceControlCliDiscoverySpec & {
65 readonly refineUnknownRemote: NonNullable<SourceControlCliDiscoverySpec["refineUnknownRemote"]>;
66};
67
68// Most provider CLIs answer `--version` in well under a second, so a short budget keeps
69// discovery snappy. Specs whose CLI is known to be slower can raise it via probeTimeoutMs.
70const DEFAULT_PROBE_TIMEOUT_MS = 5_000;
71
72function probeTimeoutMs(spec: SourceControlCliDiscoverySpec): number {
73 return spec.probeTimeoutMs ?? DEFAULT_PROBE_TIMEOUT_MS;
74}
75
76interface DiscoveryProbeResult {
77 readonly kind: SourceControlProviderKind;
78 readonly label: string;
79 readonly executable: string;
80 readonly status: "available" | "missing";
81 readonly version: Option.Option<string>;
82 readonly installHint: string;
83 readonly detail: Option.Option<string>;
84}
85
86export function firstNonEmptyLine(text: string): Option.Option<string> {
87 const line = NodeUtil.stripVTControlCharacters(text)
88 .split(/\r?\n/)
89 .map((entry) => entry.trim())
90 .find((entry) => entry.length > 0);
91 return line === undefined ? Option.none() : Option.some(line);
92}
93
94export function detailFromCause(cause: unknown): Option.Option<string> {
95 if (cause instanceof Error && cause.message.trim().length > 0) {
96 return Option.some(cause.message.trim());
97 }
98 return Option.none();
99}
100
101function authAccount(account: string | undefined): Option.Option<string> {
102 const trimmed = account?.trim();
103 return trimmed === undefined || trimmed.length === 0 ? Option.none() : Option.some(trimmed);
104}
105
106function authHost(host: string | undefined): Option.Option<string> {
107 const trimmed = host?.trim();
108 return trimmed === undefined || trimmed.length === 0 ? Option.none() : Option.some(trimmed);
109}
110
111function authDetail(detail: string | undefined): Option.Option<string> {
112 const trimmed = detail?.trim();
113 return trimmed === undefined || trimmed.length === 0 ? Option.none() : Option.some(trimmed);
114}
115
116export function providerAuth(input: {
117 readonly status: SourceControlProviderAuth["status"];
118 readonly account?: string | undefined;
119 readonly host?: string | undefined;
120 readonly detail?: string | undefined;
121}): SourceControlProviderAuth {
122 return {
123 status: input.status,
124 account: authAccount(input.account),
125 host: authHost(input.host),
126 detail: authDetail(input.detail),
127 };
128}
129
130function unknownAuth(detail?: string): SourceControlProviderAuth {
131 return providerAuth({ status: "unknown", detail });
132}
133
134export function combinedAuthOutput(input: SourceControlAuthProbeInput): string {
135 const parts: string[] = [];
136 for (const entry of [input.stdout, input.stderr]) {
137 if (entry.trim().length > 0) {
138 parts.push(entry);
139 }
140 }
141 return parts.join("\n");
142}
143
144function sanitizedAuthLines(text: string): ReadonlyArray<string> {
145 const lines: string[] = [];
146 for (const entry of text.split(/\r?\n/)) {
147 const line = entry.trim();
148 if (line.length === 0) continue;
149 if (/^[-\s]*token(?:\s+scopes?)?:/iu.test(line)) continue;
150 lines.push(line);
151 }
152 return lines;
153}
154
155export function firstSafeAuthLine(text: string): string | undefined {
156 return sanitizedAuthLines(text)[0];
157}
158
159export function parseCliHost(text: string): string | undefined {
160 return sanitizedAuthLines(text)
161 .map((line) => line.replace(/^[^a-z0-9]+/iu, ""))
162 .find((line) => /^[a-z0-9][a-z0-9.-]*(?::\d+)?$/iu.test(line));
163}
164
165export function matchFirst(text: string, patterns: ReadonlyArray<RegExp>): string | undefined {
166 for (const pattern of patterns) {
167 const match = pattern.exec(text);
168 const value = match?.[1]?.trim();
169 if (value && value.length > 0) return value;
170 }
171 return undefined;
172}
173
174function isCliRemoteRefinementSpec(
175 spec: SourceControlProviderDiscoverySpec,
176): spec is SourceControlCliRemoteRefinementSpec {
177 return spec.type === "cli" && spec.refineUnknownRemote !== undefined;
178}
179
180function probeCli(input: {
181 readonly spec: SourceControlCliDiscoverySpec;
182 readonly process: VcsProcess.VcsProcess["Service"];
183 readonly cwd: string;
184}): Effect.Effect<DiscoveryProbeResult> {
185 return input.process
186 .run({
187 operation: "source-control.discovery.probe",
188 command: input.spec.executable,
189 args: input.spec.versionArgs,
190 cwd: input.cwd,
191 timeoutMs: probeTimeoutMs(input.spec),
192 maxOutputBytes: 8_000,
193 appendTruncationMarker: true,
194 })
195 .pipe(
196 Effect.map(
197 (result) =>
198 ({
199 kind: input.spec.kind,
200 label: input.spec.label,
201 executable: input.spec.executable,
202 status: "available" as const,
203 version: Option.orElse(firstNonEmptyLine(result.stdout), () =>
204 firstNonEmptyLine(result.stderr),
205 ),
206 installHint: input.spec.installHint,
207 detail: Option.none<string>(),
208 }) satisfies DiscoveryProbeResult,
209 ),
210 Effect.catch((cause) =>
211 Effect.succeed({
212 kind: input.spec.kind,
213 label: input.spec.label,
214 executable: input.spec.executable,
215 status: "missing" as const,
216 version: Option.none<string>(),
217 installHint: input.spec.installHint,
218 detail: detailFromCause(cause),
219 } satisfies DiscoveryProbeResult),
220 ),
221 );
222}
223
224export function probeSourceControlProvider(input: {
225 readonly spec: SourceControlProviderDiscoverySpec;
226 readonly process: VcsProcess.VcsProcess["Service"];
227 readonly cwd: string;
228}): Effect.Effect<SourceControlProviderDiscoveryItem> {
229 if (input.spec.type === "managed-cli") return input.spec.probe(input.cwd);
230 if (input.spec.type === "api") {
231 return input.spec.probeAuth.pipe(
232 Effect.map(
233 (auth) =>
234 ({
235 kind: input.spec.kind,
236 label: input.spec.label,
237 status: "available" as const,
238 version: Option.none<string>(),
239 installHint: input.spec.installHint,
240 detail: Option.none<string>(),
241 auth,
242 }) satisfies SourceControlProviderDiscoveryItem,
243 ),
244 );
245 }
246
247 const spec = input.spec;
248
249 return probeCli({
250 spec,
251 process: input.process,
252 cwd: input.cwd,
253 }).pipe(
254 Effect.flatMap((item) => {
255 if (item.status !== "available") {
256 return Effect.succeed({
257 ...item,
258 auth: unknownAuth("Hosting integration command was not found on the server PATH."),
259 } satisfies SourceControlProviderDiscoveryItem);
260 }
261
262 return input.process
263 .run({
264 operation: "source-control.discovery.auth",
265 command: spec.executable,
266 args: spec.authArgs,
267 cwd: input.cwd,
268 allowNonZeroExit: true,
269 timeoutMs: probeTimeoutMs(spec),
270 maxOutputBytes: 8_000,
271 appendTruncationMarker: true,
272 })
273 .pipe(
274 Effect.map(
275 (result) =>
276 ({
277 ...item,
278 auth: spec.parseAuth(result),
279 }) satisfies SourceControlProviderDiscoveryItem,
280 ),
281 Effect.catch((cause) =>
282 Effect.succeed({
283 ...item,
284 auth: unknownAuth(Option.getOrUndefined(detailFromCause(cause))),
285 } satisfies SourceControlProviderDiscoveryItem),
286 ),
287 );
288 }),
289 );
290}
291
292export const refineUnknownRemoteProvider = Effect.fn("refineUnknownRemoteProvider")(
293 function* (input: {
294 readonly specs: ReadonlyArray<SourceControlProviderDiscoverySpec>;
295 readonly process: VcsProcess.VcsProcess["Service"];
296 readonly cwd: string;
297 readonly context: SourceControlProvider.SourceControlProviderContext | null;
298 }): Effect.fn.Return<SourceControlProvider.SourceControlProviderContext | null> {
299 if (input.context === null || input.context.provider.kind !== "unknown") {
300 return input.context;
301 }
302 const context = input.context;
303
304 const providers = yield* Effect.forEach(input.specs, (spec) => {
305 if (spec.type === "managed-cli") {
306 return spec.refineUnknownRemote({ cwd: input.cwd, context });
307 }
308 if (!isCliRemoteRefinementSpec(spec)) return Effect.succeed(null);
309 return input.process
310 .run({
311 operation: "source-control.discovery.refine-unknown-remote",
312 command: spec.executable,
313 args: spec.remoteRefinementArgs ?? spec.authArgs,
314 cwd: input.cwd,
315 allowNonZeroExit: true,
316 timeoutMs: probeTimeoutMs(spec),
317 maxOutputBytes: 8_000,
318 appendTruncationMarker: true,
319 })
320 .pipe(
321 Effect.map((auth) =>
322 spec.refineUnknownRemote({
323 cwd: input.cwd,
324 context,
325 auth,
326 }),
327 ),
328 Effect.orElseSucceed(() => null),
329 );
330 });
331 const provider = providers.find((candidate) => candidate !== null);
332
333 return provider ? { ...context, provider } : context;
334 },
335);