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