Open History to see the last commit
1// A project bound to a standalone tracker (Linear) in settings lists it beside its git host's.
2// References outside the project's canonical repository may be read on the same host,
3// but every write must pass through requireWritable.
4import * as Context from "effect/Context";
5import * as Effect from "effect/Effect";
6import * as Layer from "effect/Layer";
7import * as Option from "effect/Option";
8import {
9 IssueOperationError,
10 IssueTrackerKind,
11 IssueUnavailableError,
12 SourceControlProviderKind,
13 type IssueCandidates,
14 type IssueCommentInput,
15 type IssueCommentsPage,
16 type IssueCommentsPageInput,
17 type IssueCreateInput,
18 type IssueCreateResult,
19 type IssueDetail,
20 type IssueError,
21 type IssueListEntry,
22 type IssueListInput,
23 type IssueListProjectError,
24 type IssueListResult,
25 type IssueReactionInput,
26 type IssueRef,
27 type IssueScopeRef,
28 type IssueSetStateInput,
29 type IssueTemplateList,
30 type IssueTrackerSummary,
31 type IssueUpdateInput,
32 type OrchestrationProjectShell,
33 type ProjectId,
34} from "@t3tools/contracts";
35import * as SourceControlRateLimit from "@t3tools/source-control-core/server/SourceControlRateLimit";
36import {
37 IssueTrackerError,
38 isStandaloneIssueTracker,
39 type IssueInvolvementFilter,
40 type IssueTrackerApi,
41 type StandaloneIssueTrackerApi,
42 type TrackerIssueDetail,
43} from "@t3tools/source-control-core/server/IssueTracker";
44import { parseUrl } from "@t3tools/shared/url";
45
46import * as IssueTrackerBindings from "../persistence/IssueTrackerBindings.ts";
47import * as ProjectService from "../project/ProjectService.ts";
48import * as RepositoryIdentityResolver from "../project/RepositoryIdentityResolver.ts";
49import { sourceControlDefinitions } from "../sourceControl/sourceControlDefinitions.ts";
50import * as IssueTrackerRegistry from "./IssueTrackerRegistry.ts";
51
52const DEFAULT_LIST_LIMIT = 50;
53const SCOPE_CONCURRENCY = 4;
54
55const interactive =
56 <I, A>(call: (input: I) => Effect.Effect<A, IssueError>) =>
57 (input: I) =>
58 call(input).pipe(Effect.provideService(SourceControlRateLimit.Interactive, true));
59
60const traced =
61 <I, A>(operation: string, call: (input: I) => Effect.Effect<A, IssueError>) =>
62 (input: I) =>
63 call(input).pipe(Effect.withSpan(`IssueService.${operation}`));
64
65/** A tracker may fail with no detail; the wire errors carry a non-empty one. */
66export function trackerDetail(error: IssueTrackerError): string {
67 return error.detail.trim() || "The issue tracker request failed.";
68}
69
70/** One project's resolved tracker: which driver, where it is served from, and its container. */
71interface ProjectTrackerBinding {
72 readonly tracker: IssueTrackerKind;
73 readonly host: string;
74 readonly scope: string;
75}
76
77/** A project the registry has a tracker for, ready to serve reads and writes. */
78interface SupportedProject extends ProjectTrackerBinding {
79 readonly project: OrchestrationProjectShell;
80 readonly api: IssueTrackerApi;
81}
82
83/**
84 * The git-host path of resolution: the tracker is the host's own, named like the remote's
85 * provider kind. Null for a project with no remote or a kind no tracker claims.
86 */
87function resolveGitHostBinding(project: OrchestrationProjectShell): ProjectTrackerBinding | null {
88 const identity = project.repositoryIdentity;
89 const scope = sourceControlDefinitions.issueScope(identity);
90 const kind = identity?.provider;
91 if (!identity || kind === undefined || kind === "unknown" || scope === null) return null;
92 return {
93 tracker: IssueTrackerKind.make(kind),
94 host: sourceControlDefinitions.changeRequestHost(identity, kind),
95 scope,
96 };
97}
98
99function findStandaloneIssueUrl(trackers: ReadonlyArray<StandaloneIssueTrackerApi>, value: string) {
100 const url = parseUrl(value);
101 if (url === null) return null;
102 for (const api of trackers) {
103 const link = api.parseIssueUrl(url);
104 if (link !== null) return { api, tracker: api.kind, link };
105 }
106 return null;
107}
108
109/** Lower case, so a scope keeps its cursor whichever project's spelling of it is read. */
110function listCursorKey(host: string, scope: string): string {
111 return `${host} ${scope.toLowerCase()}`;
112}
113
114function isTrackerUnusable(error: IssueTrackerError): boolean {
115 return error.reason === "missing-tool" || error.reason === "unauthenticated";
116}
117
118function toIssueError(operation: string): (error: IssueTrackerError) => IssueError {
119 return (error) =>
120 isTrackerUnusable(error)
121 ? new IssueUnavailableError({
122 reason: error.reason === "missing-tool" ? "tool-missing" : "unauthenticated",
123 tracker: error.tracker,
124 cause: error,
125 })
126 : new IssueOperationError({
127 operation,
128 detail: trackerDetail(error),
129 ...(error.reason === "not-found" || error.reason === "rate-limited"
130 ? { reason: error.reason }
131 : {}),
132 ...(error.retryAt === undefined ? {} : { retryAt: error.retryAt }),
133 cause: error,
134 });
135}
136
137const readOnly = (operation: string) =>
138 new IssueOperationError({
139 operation,
140 reason: "read-only",
141 detail:
142 "This issue belongs to a repository outside the selected project and cannot be changed from here.",
143 });
144
145const unsupported = (operation: string, what: string) =>
146 new IssueOperationError({ operation, detail: `This tracker does not support ${what}.` });
147
148export class IssueService extends Context.Service<
149 IssueService,
150 {
151 readonly list: (input: IssueListInput) => Effect.Effect<IssueListResult, IssueError>;
152 readonly detail: (input: IssueRef) => Effect.Effect<IssueDetail, IssueError>;
153 readonly comments: (
154 input: IssueCommentsPageInput,
155 ) => Effect.Effect<IssueCommentsPage, IssueError>;
156 readonly templates: (input: IssueScopeRef) => Effect.Effect<IssueTemplateList, IssueError>;
157 readonly candidates: (input: IssueScopeRef) => Effect.Effect<IssueCandidates, IssueError>;
158 readonly create: (input: IssueCreateInput) => Effect.Effect<IssueCreateResult, IssueError>;
159 readonly comment: (input: IssueCommentInput) => Effect.Effect<void, IssueError>;
160 readonly update: (input: IssueUpdateInput) => Effect.Effect<void, IssueError>;
161 readonly setState: (input: IssueSetStateInput) => Effect.Effect<void, IssueError>;
162 readonly react: (input: IssueReactionInput) => Effect.Effect<void, IssueError>;
163 /** The tracker and container a project's own issues live in. */
164 readonly projectScope: (
165 projectId: ProjectId,
166 ) => Effect.Effect<IssueScopeRef & { readonly host: string }, IssueError>;
167 /**
168 * Resolve through a matching project, preferring `preferredProjectId`; other scopes are read-only.
169 * Standalone links must match the workspace in the issue's canonical URL from the connected
170 * tracker; that read comes back as `issue`, so callers need not read it again.
171 */
172 readonly resolveUrl: (
173 url: string,
174 preferredProjectId?: ProjectId,
175 ) => Effect.Effect<
176 IssueRef & {
177 readonly host: string;
178 readonly writable: boolean;
179 readonly issue?: IssueDetail;
180 },
181 IssueError
182 >;
183 }
184>()("t3/issue/IssueService") {}
185
186const make = Effect.gen(function* () {
187 const registry = yield* IssueTrackerRegistry.IssueTrackerRegistry;
188 const projects = yield* ProjectService.ProjectService;
189 const repositoryIdentities = yield* RepositoryIdentityResolver.RepositoryIdentityResolver;
190 const bindings = yield* IssueTrackerBindings.IssueTrackerBindingsRepository;
191
192 // Read per resolution so a binding saved in Settings applies without a restart.
193 const resolveStandaloneBinding = (
194 project: OrchestrationProjectShell,
195 ): Effect.Effect<ProjectTrackerBinding | null, IssueOperationError> =>
196 bindings.list.pipe(
197 Effect.map((bound) => {
198 const binding = bound.get(project.id);
199 const api = binding === undefined ? null : registry.get(binding.tracker);
200 if (binding === undefined || api === null || !isStandaloneIssueTracker(api)) return null;
201 return {
202 tracker: binding.tracker,
203 host: api.standalone.host,
204 scope: binding.scope,
205 };
206 }),
207 // A failed read is not an unbound project: that would list the git host's issues alone.
208 Effect.mapError(
209 (cause) =>
210 new IssueOperationError({
211 operation: "listProjects",
212 detail: "The project's issue tracker binding could not be read.",
213 cause,
214 }),
215 ),
216 );
217
218 /**
219 * Where a project's issues live: its bound standalone tracker, its git host's, or both. The
220 * tracker bound in Settings leads, as the one the user chose for the project.
221 */
222 const resolveProjectTracker = (
223 project: OrchestrationProjectShell,
224 ): Effect.Effect<ReadonlyArray<ProjectTrackerBinding>, IssueOperationError> =>
225 Effect.all([
226 resolveStandaloneBinding(project),
227 (project.repositoryIdentity != null
228 ? Effect.succeed(project.repositoryIdentity)
229 : repositoryIdentities.resolve(project.workspaceRoot)
230 ).pipe(
231 Effect.map((repositoryIdentity) =>
232 resolveGitHostBinding({ ...project, repositoryIdentity }),
233 ),
234 ),
235 ]).pipe(Effect.map((resolved) => resolved.filter((binding) => binding !== null)));
236
237 const listProjects = (filter: {
238 readonly projectId?: IssueListInput["projectId"];
239 readonly host?: string | undefined;
240 /** The link's `host:port`, for a host whose binding keeps its port. */
241 readonly authority?: string | undefined;
242 }) =>
243 (filter.projectId === undefined
244 ? projects.listShells()
245 : projects.getShell(filter.projectId).pipe(Effect.map(Option.toArray))
246 ).pipe(
247 Effect.mapError(
248 (cause) =>
249 new IssueOperationError({
250 operation: "listProjects",
251 detail: "The project list could not be read.",
252 cause,
253 }),
254 ),
255 Effect.flatMap((shells) =>
256 Effect.forEach(
257 shells,
258 (project) =>
259 resolveProjectTracker(project).pipe(
260 Effect.map((bindings) => bindings.map((binding) => ({ project, ...binding }))),
261 ),
262 { concurrency: SCOPE_CONCURRENCY },
263 ),
264 ),
265 Effect.map((bound) => {
266 const host = filter.host?.trim().toLowerCase();
267 const supported: SupportedProject[] = [];
268 const unimplemented = new Map<
269 string,
270 { tracker: IssueTrackerKind; projectCount: number }
271 >();
272 for (const candidate of bound.flat()) {
273 if (host !== undefined && candidate.host !== host && candidate.host !== filter.authority)
274 continue;
275 const api = registry.get(candidate.tracker);
276 if (api === null) {
277 const counted = unimplemented.get(candidate.host);
278 if (counted === undefined)
279 unimplemented.set(candidate.host, { tracker: candidate.tracker, projectCount: 1 });
280 else counted.projectCount += 1;
281 continue;
282 }
283 supported.push({ ...candidate, api });
284 }
285 return { supported, unimplemented };
286 }),
287 );
288
289 /**
290 * The project whose checkout and credentials serve a reference, and whether the reference is
291 * the project's own scope. A reference naming another scope on the same tracker and host is
292 * served by the project but marked read-only. A project with two trackers serves the one the
293 * reference names.
294 */
295 const requireProject = (
296 ref: IssueScopeRef,
297 ): Effect.Effect<SupportedProject & { readonly writable: boolean }, IssueError> =>
298 listProjects({ projectId: ref.projectId }).pipe(
299 Effect.flatMap(({ supported }) => {
300 const own = supported.find((candidate) => candidate.tracker === ref.tracker);
301 if (own === undefined) {
302 return Effect.fail(new IssueUnavailableError({ reason: "tracker-unsupported" }));
303 }
304 const host = ref.host?.trim().toLowerCase() ?? own.host;
305 if (host !== own.host) {
306 return Effect.fail(new IssueUnavailableError({ reason: "tracker-unsupported" }));
307 }
308 const scope = ref.scope.trim();
309 const writable = scope.toLowerCase() === own.scope.toLowerCase();
310 return Effect.succeed({ ...own, scope, writable });
311 }),
312 );
313
314 const requireWritable = (ref: IssueScopeRef, operation: string) =>
315 requireProject(ref).pipe(
316 Effect.filterOrFail(
317 (project) => project.writable,
318 () => readOnly(operation),
319 ),
320 );
321
322 const list: IssueService["Service"]["list"] = Effect.fn("IssueService.list")(function* (input) {
323 // Trackers name every host so a client narrowed to one can switch to another; only the
324 // narrowed host's scopes are read.
325 const { supported, unimplemented } = yield* listProjects({ projectId: input.projectId });
326 const host = input.host?.trim().toLowerCase();
327 const limit = input.limit ?? DEFAULT_LIST_LIMIT;
328 // Worktrees of one repository are separate projects, and every repository of an Azure
329 // DevOps project shares its work items; read each scope once.
330 const scopes = new Map<string, SupportedProject>();
331 for (const project of supported) {
332 if (host !== undefined && project.host !== host) continue;
333 const key = listCursorKey(project.host, project.scope);
334 if (!scopes.has(key)) scopes.set(key, project);
335 }
336 const continuing = input.cursors;
337 const viewers = new Map<string, string>();
338 const trackers = new Map<string, IssueTrackerSummary>();
339 const entries: IssueListEntry[] = [];
340 const errors: IssueListProjectError[] = [];
341 const nextCursors: Record<string, string> = {};
342
343 const involvement = input.involvement ?? "all";
344 // Only a narrowed listing compares against the signed-in account; `all` never reads it.
345 const viewerRequests = new Map<string, Effect.Effect<string, IssueTrackerError>>();
346 for (const project of involvement === "all" ? [] : scopes.values()) {
347 if (viewerRequests.has(project.host)) continue;
348 const request = yield* Effect.cached(
349 project.api
350 .getViewer({ cwd: project.project.workspaceRoot, host: project.host })
351 .pipe(Effect.tap((viewer) => Effect.sync(() => viewers.set(project.host, viewer)))),
352 );
353 viewerRequests.set(project.host, request);
354 }
355
356 // Every project counts, including worktrees of a scope read once below.
357 for (const project of supported) {
358 const existing = trackers.get(project.host);
359 trackers.set(
360 project.host,
361 existing === undefined
362 ? {
363 tracker: project.tracker,
364 host: project.host,
365 projectCount: 1,
366 capabilities: project.api.capabilities,
367 configured: true,
368 detail: null,
369 }
370 : { ...existing, projectCount: existing.projectCount + 1 },
371 );
372 }
373 const recordFailure = (project: SupportedProject, failure: IssueTrackerError) => {
374 const existing = trackers.get(project.host);
375 if (existing !== undefined && isTrackerUnusable(failure))
376 trackers.set(project.host, {
377 ...existing,
378 configured: false,
379 detail: trackerDetail(failure),
380 });
381 };
382
383 yield* Effect.forEach(
384 scopes.values(),
385 (project) =>
386 Effect.gen(function* () {
387 const key = listCursorKey(project.host, project.scope);
388 // A continuation names the scopes it wants; one not named has nothing to add.
389 if (continuing !== undefined && continuing[key] === undefined) return;
390 const cursor = continuing?.[key];
391 const filter: Effect.Effect<IssueInvolvementFilter, IssueTrackerError> =
392 involvement === "all"
393 ? Effect.succeed({ involvement })
394 : viewerRequests
395 .get(project.host)!
396 .pipe(Effect.map((viewer) => ({ involvement, viewer })));
397 const page = yield* filter.pipe(
398 Effect.flatMap((filter) =>
399 project.api.listIssues({
400 ...filter,
401 cwd: project.project.workspaceRoot,
402 host: project.host,
403 scope: project.scope,
404 state: input.state,
405 limit,
406 query: input.query,
407 labels: input.labels,
408 assignee: input.assignee,
409 sort: input.sort ?? "updated",
410 cursor,
411 }),
412 ),
413 Effect.result,
414 );
415 if (page._tag === "Failure") {
416 if (cursor !== undefined) nextCursors[key] = cursor;
417 recordFailure(project, page.failure);
418 errors.push({
419 projectId: project.project.id,
420 projectTitle: project.project.title,
421 message: trackerDetail(page.failure),
422 });
423 return;
424 }
425 for (const item of page.success.items) {
426 entries.push({
427 ...item,
428 tracker: project.tracker,
429 host: project.host,
430 scope: project.scope,
431 projectId: project.project.id,
432 projectTitle: project.project.title,
433 });
434 }
435 if (page.success.nextCursor !== null) nextCursors[key] = page.success.nextCursor;
436 }),
437 { concurrency: SCOPE_CONCURRENCY, discard: true },
438 );
439
440 for (const [host, { tracker, projectCount }] of unimplemented) {
441 trackers.set(host, {
442 tracker,
443 host,
444 projectCount,
445 capabilities: null,
446 configured: false,
447 detail: "Issues cannot be browsed for this host yet.",
448 });
449 }
450 entries.sort((a, b) => b.updatedAt.localeCompare(a.updatedAt));
451 return {
452 viewers: Object.fromEntries(viewers),
453 trackers: [...trackers.values()],
454 entries,
455 errors,
456 nextCursors,
457 scopes: [...scopes.values()].map((project) => ({
458 projectId: project.project.id,
459 tracker: project.tracker,
460 host: project.host,
461 scope: project.scope,
462 })),
463 };
464 });
465
466 const toDetail = (
467 project: SupportedProject & { readonly writable: boolean },
468 issue: TrackerIssueDetail,
469 ): IssueDetail => ({
470 ...issue,
471 tracker: project.tracker,
472 host: project.host,
473 scope: project.scope,
474 projectId: project.project.id,
475 projectTitle: project.project.title,
476 writable: project.writable,
477 capabilities: project.api.capabilities,
478 });
479
480 const detail: IssueService["Service"]["detail"] = (input) =>
481 requireProject(input).pipe(
482 Effect.flatMap((project) =>
483 project.api
484 .getIssue({
485 cwd: project.project.workspaceRoot,
486 host: project.host,
487 scope: project.scope,
488 key: input.key,
489 })
490 .pipe(
491 Effect.mapError(toIssueError("detail")),
492 Effect.map((issue) => toDetail(project, issue)),
493 ),
494 ),
495 );
496
497 const comments: IssueService["Service"]["comments"] = (input) =>
498 requireProject(input).pipe(
499 Effect.flatMap((project) =>
500 project.api
501 .getComments({
502 cwd: project.project.workspaceRoot,
503 host: project.host,
504 scope: project.scope,
505 key: input.key,
506 cursor: input.cursor,
507 })
508 .pipe(Effect.mapError(toIssueError("comments"))),
509 ),
510 );
511
512 const templates: IssueService["Service"]["templates"] = (input) =>
513 requireProject(input).pipe(
514 Effect.flatMap((project) =>
515 project.api.listTemplates === undefined || !project.api.capabilities.templates
516 ? Effect.fail(unsupported("templates", "issue templates"))
517 : project.api
518 .listTemplates({
519 cwd: project.project.workspaceRoot,
520 host: project.host,
521 scope: project.scope,
522 })
523 .pipe(Effect.mapError(toIssueError("templates"))),
524 ),
525 );
526
527 const candidates: IssueService["Service"]["candidates"] = (input) =>
528 requireProject(input).pipe(
529 Effect.flatMap((project) =>
530 project.api.listCandidates === undefined ||
531 !(project.api.capabilities.labels || project.api.capabilities.assignees)
532 ? Effect.fail(unsupported("candidates", "labels or assignees"))
533 : project.api
534 .listCandidates({
535 cwd: project.project.workspaceRoot,
536 host: project.host,
537 scope: project.scope,
538 })
539 .pipe(Effect.mapError(toIssueError("candidates"))),
540 ),
541 );
542
543 const create: IssueService["Service"]["create"] = (input) =>
544 requireWritable(input, "create").pipe(
545 Effect.flatMap((project) =>
546 project.api.create === undefined || !project.api.capabilities.create
547 ? Effect.fail(unsupported("create", "filing issues"))
548 : project.api
549 .create({
550 cwd: project.project.workspaceRoot,
551 host: project.host,
552 scope: project.scope,
553 title: input.title,
554 body: input.body,
555 labels: input.labels,
556 assignees: input.assignees,
557 })
558 .pipe(Effect.mapError(toIssueError("create"))),
559 ),
560 );
561
562 const comment: IssueService["Service"]["comment"] = (input) =>
563 requireWritable(input, "comment").pipe(
564 Effect.flatMap((project) => {
565 if (input.body.trim().length === 0) {
566 return Effect.fail(
567 new IssueOperationError({ operation: "comment", detail: "A comment needs some text." }),
568 );
569 }
570 return project.api.comment === undefined || !project.api.capabilities.comment
571 ? Effect.fail(unsupported("comment", "comments"))
572 : project.api
573 .comment({
574 cwd: project.project.workspaceRoot,
575 host: project.host,
576 scope: project.scope,
577 key: input.key,
578 body: input.body,
579 })
580 .pipe(Effect.mapError(toIssueError("comment")));
581 }),
582 );
583
584 const update: IssueService["Service"]["update"] = (input) =>
585 requireWritable(input, "update").pipe(
586 Effect.flatMap((project) => {
587 const { capabilities } = project.api;
588 const wantsWords = input.title !== undefined || input.body !== undefined;
589 if (!wantsWords && input.labels === undefined && input.assignees === undefined) {
590 return Effect.fail(
591 new IssueOperationError({ operation: "update", detail: "Nothing to change." }),
592 );
593 }
594 if (project.api.update === undefined) return Effect.fail(unsupported("update", "edits"));
595 if (wantsWords && !capabilities.edit)
596 return Effect.fail(unsupported("update", "editing the title or body"));
597 if (input.labels !== undefined && !capabilities.labels)
598 return Effect.fail(unsupported("update", "labels"));
599 if (input.assignees !== undefined && !capabilities.assignees)
600 return Effect.fail(unsupported("update", "assignees"));
601 return project.api
602 .update({
603 cwd: project.project.workspaceRoot,
604 host: project.host,
605 scope: project.scope,
606 key: input.key,
607 title: input.title,
608 body: input.body,
609 labels: input.labels,
610 assignees: input.assignees,
611 })
612 .pipe(Effect.mapError(toIssueError("update")));
613 }),
614 );
615
616 const setState: IssueService["Service"]["setState"] = (input) =>
617 requireWritable(input, "setState").pipe(
618 Effect.flatMap((project) => {
619 if (project.api.setState === undefined)
620 return Effect.fail(unsupported("setState", "changing an issue's state"));
621 return project.api
622 .setState({
623 cwd: project.project.workspaceRoot,
624 host: project.host,
625 scope: project.scope,
626 key: input.key,
627 state: input.state,
628 })
629 .pipe(Effect.mapError(toIssueError("setState")));
630 }),
631 );
632
633 const react: IssueService["Service"]["react"] = (input) =>
634 requireWritable(input, "react").pipe(
635 Effect.flatMap((project) =>
636 project.api.setReaction === undefined || !project.api.capabilities.reactions
637 ? Effect.fail(unsupported("react", "reactions"))
638 : project.api
639 .setReaction({
640 cwd: project.project.workspaceRoot,
641 host: project.host,
642 scope: project.scope,
643 key: input.key,
644 subjectId: input.subjectId,
645 content: input.content,
646 reacted: input.reacted,
647 })
648 .pipe(Effect.mapError(toIssueError("react"))),
649 ),
650 );
651
652 const projectScope: IssueService["Service"]["projectScope"] = Effect.fn(
653 "IssueService.projectScope",
654 )(function* (projectId) {
655 const { supported } = yield* listProjects({ projectId });
656 const [own] = supported;
657 if (own === undefined) {
658 return yield* new IssueUnavailableError({ reason: "tracker-unsupported" });
659 }
660 return { projectId, tracker: own.tracker, host: own.host, scope: own.scope };
661 });
662
663 /** A host whose hostname does not name it, such as GitHub Enterprise Server, is vouched for by a project on it. */
664 const parseOnProjectHost = (value: string) => {
665 const url = parseUrl(value);
666 if (url === null) return Effect.succeed(null);
667 return listProjects({ host: url.hostname, authority: url.host.toLowerCase() }).pipe(
668 Effect.map(({ supported }) => {
669 for (const project of supported) {
670 const parsed = sourceControlDefinitions.parseIssueUrl(
671 value,
672 SourceControlProviderKind.make(project.tracker),
673 );
674 if (parsed !== null) return parsed;
675 }
676 return null;
677 }),
678 );
679 };
680
681 const resolveUrl: IssueService["Service"]["resolveUrl"] = Effect.fn("IssueService.resolveUrl")(
682 function* (url, preferredProjectId) {
683 const recognized = sourceControlDefinitions.parseIssueUrl(url);
684 const standalone =
685 recognized === null ? findStandaloneIssueUrl(registry.standalone, url) : null;
686 const gitHost = recognized ?? (standalone === null ? yield* parseOnProjectHost(url) : null);
687 const parsed =
688 gitHost === null
689 ? standalone
690 : { tracker: IssueTrackerKind.make(gitHost.definition.kind), link: gitHost.link };
691 if (parsed === null) {
692 return yield* new IssueOperationError({
693 operation: "resolveUrl",
694 reason: "not-found",
695 detail: "This is not a recognised issue URL.",
696 });
697 }
698 const { tracker, link } = parsed;
699 // A link names its server's port; a binding does only when its remote or web URL did.
700 const authority = new URL(url).host.toLowerCase();
701 const { supported } = yield* listProjects({ host: link.host, authority });
702 const onHost = supported.filter((project) => project.tracker === tracker);
703 const onAuthority = onHost.filter((project) => project.host === authority);
704 const onTracker = onAuthority.length > 0 ? onAuthority : onHost;
705 const preferFirst = (projects: ReadonlyArray<SupportedProject>) =>
706 projects.find((project) => project.project.id === preferredProjectId) ?? projects[0];
707 const scope = link.scope.toLowerCase();
708 const own =
709 preferFirst(onTracker.filter((project) => project.scope.toLowerCase() === scope)) ??
710 preferFirst(
711 onTracker.filter((project) => project.scope.toLowerCase() === gitHost?.link.scopeAlias),
712 );
713 const lender = own ?? preferFirst(onTracker);
714 if (lender === undefined) {
715 return yield* new IssueUnavailableError({ reason: "tracker-unsupported" });
716 }
717 const served = {
718 ...lender,
719 scope: own === undefined ? link.scope : lender.scope,
720 writable: own !== undefined,
721 };
722 const resolved = {
723 projectId: lender.project.id,
724 tracker: lender.tracker,
725 host: lender.host,
726 scope: served.scope,
727 key: link.key,
728 writable: served.writable,
729 };
730 if (standalone === null) return resolved;
731 // Team keys repeat across workspaces; only the credential's canonical issue URL identifies one.
732 const issue = yield* lender.api
733 .getIssue({
734 cwd: lender.project.workspaceRoot,
735 host: lender.host,
736 scope: link.scope,
737 key: link.key,
738 })
739 .pipe(Effect.mapError(toIssueError("resolveUrl")));
740 const canonicalUrl = parseUrl(issue.url);
741 const canonical = canonicalUrl === null ? null : standalone.api.parseIssueUrl(canonicalUrl);
742 if (canonical === null || canonical.workspace !== standalone.link.workspace) {
743 return yield* new IssueOperationError({
744 operation: "resolveUrl",
745 reason: "not-found",
746 detail: "This issue URL does not belong to the connected workspace.",
747 });
748 }
749 return { ...resolved, issue: toDetail(served, issue) };
750 },
751 );
752
753 return IssueService.of({
754 list,
755 detail: traced("detail", detail),
756 comments: traced("comments", comments),
757 templates: traced("templates", templates),
758 candidates: interactive(traced("candidates", candidates)),
759 create: interactive(traced("create", create)),
760 comment: interactive(traced("comment", comment)),
761 update: interactive(traced("update", update)),
762 setState: interactive(traced("setState", setState)),
763 react: interactive(traced("react", react)),
764 projectScope,
765 resolveUrl,
766 });
767});
768
769export const layer = Layer.effect(IssueService, make);