Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

IssueService.ts

770 lines29.2 KB

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.";
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;
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;
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 };
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;
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()}`;
113​
114function isTrackerUnusable(error: IssueTrackerError): boolean {
115 return error.reason === "missing-tool" || error.reason === "unauthenticated";
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 });
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 refresh: input.refresh,
412 }),
413 ),
414 Effect.result,
415 );
416 if (page._tag === "Failure") {
417 if (cursor !== undefined) nextCursors[key] = cursor;
418 recordFailure(project, page.failure);
419 errors.push({
420 projectId: project.project.id,
421 projectTitle: project.project.title,
422 message: trackerDetail(page.failure),
423 });
424 return;
425 }
426 for (const item of page.success.items) {
427 entries.push({
428 ...item,
429 tracker: project.tracker,
430 host: project.host,
431 scope: project.scope,
432 projectId: project.project.id,
433 projectTitle: project.project.title,
434 });
435 }
436 if (page.success.nextCursor !== null) nextCursors[key] = page.success.nextCursor;
437 }),
438 { concurrency: SCOPE_CONCURRENCY, discard: true },
439 );
440​
441 for (const [host, { tracker, projectCount }] of unimplemented) {
442 trackers.set(host, {
443 tracker,
444 host,
445 projectCount,
446 capabilities: null,
447 configured: false,
448 detail: "Issues cannot be browsed for this host yet.",
449 });
450 }
451 entries.sort((a, b) => b.updatedAt.localeCompare(a.updatedAt));
452 return {
453 viewers: Object.fromEntries(viewers),
454 trackers: [...trackers.values()],
455 entries,
456 errors,
457 nextCursors,
458 scopes: [...scopes.values()].map((project) => ({
459 projectId: project.project.id,
460 tracker: project.tracker,
461 host: project.host,
462 scope: project.scope,
463 })),
464 };
465 });
466​
467 const toDetail = (
468 project: SupportedProject & { readonly writable: boolean },
469 issue: TrackerIssueDetail,
470 ): IssueDetail => ({
471 ...issue,
472 tracker: project.tracker,
473 host: project.host,
474 scope: project.scope,
475 projectId: project.project.id,
476 projectTitle: project.project.title,
477 writable: project.writable,
478 capabilities: project.api.capabilities,
479 });
480​
481 const detail: IssueService["Service"]["detail"] = (input) =>
482 requireProject(input).pipe(
483 Effect.flatMap((project) =>
484 project.api
485 .getIssue({
486 cwd: project.project.workspaceRoot,
487 host: project.host,
488 scope: project.scope,
489 key: input.key,
490 })
491 .pipe(
492 Effect.mapError(toIssueError("detail")),
493 Effect.map((issue) => toDetail(project, issue)),
494 ),
495 ),
496 );
497​
498 const comments: IssueService["Service"]["comments"] = (input) =>
499 requireProject(input).pipe(
500 Effect.flatMap((project) =>
501 project.api
502 .getComments({
503 cwd: project.project.workspaceRoot,
504 host: project.host,
505 scope: project.scope,
506 key: input.key,
507 cursor: input.cursor,
508 })
509 .pipe(Effect.mapError(toIssueError("comments"))),
510 ),
511 );
512​
513 const templates: IssueService["Service"]["templates"] = (input) =>
514 requireProject(input).pipe(
515 Effect.flatMap((project) =>
516 project.api.listTemplates === undefined || !project.api.capabilities.templates
517 ? Effect.fail(unsupported("templates", "issue templates"))
518 : project.api
519 .listTemplates({
520 cwd: project.project.workspaceRoot,
521 host: project.host,
522 scope: project.scope,
523 })
524 .pipe(Effect.mapError(toIssueError("templates"))),
525 ),
526 );
527​
528 const candidates: IssueService["Service"]["candidates"] = (input) =>
529 requireProject(input).pipe(
530 Effect.flatMap((project) =>
531 project.api.listCandidates === undefined ||
532 !(project.api.capabilities.labels || project.api.capabilities.assignees)
533 ? Effect.fail(unsupported("candidates", "labels or assignees"))
534 : project.api
535 .listCandidates({
536 cwd: project.project.workspaceRoot,
537 host: project.host,
538 scope: project.scope,
539 })
540 .pipe(Effect.mapError(toIssueError("candidates"))),
541 ),
542 );
543​
544 const create: IssueService["Service"]["create"] = (input) =>
545 requireWritable(input, "create").pipe(
546 Effect.flatMap((project) =>
547 project.api.create === undefined || !project.api.capabilities.create
548 ? Effect.fail(unsupported("create", "filing issues"))
549 : project.api
550 .create({
551 cwd: project.project.workspaceRoot,
552 host: project.host,
553 scope: project.scope,
554 title: input.title,
555 body: input.body,
556 labels: input.labels,
557 assignees: input.assignees,
558 })
559 .pipe(Effect.mapError(toIssueError("create"))),
560 ),
561 );
562​
563 const comment: IssueService["Service"]["comment"] = (input) =>
564 requireWritable(input, "comment").pipe(
565 Effect.flatMap((project) => {
566 if (input.body.trim().length === 0) {
567 return Effect.fail(
568 new IssueOperationError({ operation: "comment", detail: "A comment needs some text." }),
569 );
570 }
571 return project.api.comment === undefined || !project.api.capabilities.comment
572 ? Effect.fail(unsupported("comment", "comments"))
573 : project.api
574 .comment({
575 cwd: project.project.workspaceRoot,
576 host: project.host,
577 scope: project.scope,
578 key: input.key,
579 body: input.body,
580 })
581 .pipe(Effect.mapError(toIssueError("comment")));
582 }),
583 );
584​
585 const update: IssueService["Service"]["update"] = (input) =>
586 requireWritable(input, "update").pipe(
587 Effect.flatMap((project) => {
588 const { capabilities } = project.api;
589 const wantsWords = input.title !== undefined || input.body !== undefined;
590 if (!wantsWords && input.labels === undefined && input.assignees === undefined) {
591 return Effect.fail(
592 new IssueOperationError({ operation: "update", detail: "Nothing to change." }),
593 );
594 }
595 if (project.api.update === undefined) return Effect.fail(unsupported("update", "edits"));
596 if (wantsWords && !capabilities.edit)
597 return Effect.fail(unsupported("update", "editing the title or body"));
598 if (input.labels !== undefined && !capabilities.labels)
599 return Effect.fail(unsupported("update", "labels"));
600 if (input.assignees !== undefined && !capabilities.assignees)
601 return Effect.fail(unsupported("update", "assignees"));
602 return project.api
603 .update({
604 cwd: project.project.workspaceRoot,
605 host: project.host,
606 scope: project.scope,
607 key: input.key,
608 title: input.title,
609 body: input.body,
610 labels: input.labels,
611 assignees: input.assignees,
612 })
613 .pipe(Effect.mapError(toIssueError("update")));
614 }),
615 );
616​
617 const setState: IssueService["Service"]["setState"] = (input) =>
618 requireWritable(input, "setState").pipe(
619 Effect.flatMap((project) => {
620 if (project.api.setState === undefined)
621 return Effect.fail(unsupported("setState", "changing an issue's state"));
622 return project.api
623 .setState({
624 cwd: project.project.workspaceRoot,
625 host: project.host,
626 scope: project.scope,
627 key: input.key,
628 state: input.state,
629 })
630 .pipe(Effect.mapError(toIssueError("setState")));
631 }),
632 );
633​
634 const react: IssueService["Service"]["react"] = (input) =>
635 requireWritable(input, "react").pipe(
636 Effect.flatMap((project) =>
637 project.api.setReaction === undefined || !project.api.capabilities.reactions
638 ? Effect.fail(unsupported("react", "reactions"))
639 : project.api
640 .setReaction({
641 cwd: project.project.workspaceRoot,
642 host: project.host,
643 scope: project.scope,
644 key: input.key,
645 subjectId: input.subjectId,
646 content: input.content,
647 reacted: input.reacted,
648 })
649 .pipe(Effect.mapError(toIssueError("react"))),
650 ),
651 );
652​
653 const projectScope: IssueService["Service"]["projectScope"] = Effect.fn(
654 "IssueService.projectScope",
655 )(function* (projectId) {
656 const { supported } = yield* listProjects({ projectId });
657 const [own] = supported;
658 if (own === undefined) {
659 return yield* new IssueUnavailableError({ reason: "tracker-unsupported" });
660 }
661 return { projectId, tracker: own.tracker, host: own.host, scope: own.scope };
662 });
663​
664 /** A host whose hostname does not name it, such as GitHub Enterprise Server, is vouched for by a project on it. */
665 const parseOnProjectHost = (value: string) => {
666 const url = parseUrl(value);
667 if (url === null) return Effect.succeed(null);
668 return listProjects({ host: url.hostname, authority: url.host.toLowerCase() }).pipe(
669 Effect.map(({ supported }) => {
670 for (const project of supported) {
671 const parsed = sourceControlDefinitions.parseIssueUrl(
672 value,
673 SourceControlProviderKind.make(project.tracker),
674 );
675 if (parsed !== null) return parsed;
676 }
677 return null;
678 }),
679 );
680 };
681​
682 const resolveUrl: IssueService["Service"]["resolveUrl"] = Effect.fn("IssueService.resolveUrl")(
683 function* (url, preferredProjectId) {
684 const recognized = sourceControlDefinitions.parseIssueUrl(url);
685 const standalone =
686 recognized === null ? findStandaloneIssueUrl(registry.standalone, url) : null;
687 const gitHost = recognized ?? (standalone === null ? yield* parseOnProjectHost(url) : null);
688 const parsed =
689 gitHost === null
690 ? standalone
691 : { tracker: IssueTrackerKind.make(gitHost.definition.kind), link: gitHost.link };
692 if (parsed === null) {
693 return yield* new IssueOperationError({
694 operation: "resolveUrl",
695 reason: "not-found",
696 detail: "This is not a recognised issue URL.",
697 });
698 }
699 const { tracker, link } = parsed;
700 // A link names its server's port; a binding does only when its remote or web URL did.
701 const authority = new URL(url).host.toLowerCase();
702 const { supported } = yield* listProjects({ host: link.host, authority });
703 const onHost = supported.filter((project) => project.tracker === tracker);
704 const onAuthority = onHost.filter((project) => project.host === authority);
705 const onTracker = onAuthority.length > 0 ? onAuthority : onHost;
706 const preferFirst = (projects: ReadonlyArray<SupportedProject>) =>
707 projects.find((project) => project.project.id === preferredProjectId) ?? projects[0];
708 const scope = link.scope.toLowerCase();
709 const own =
710 preferFirst(onTracker.filter((project) => project.scope.toLowerCase() === scope)) ??
711 preferFirst(
712 onTracker.filter((project) => project.scope.toLowerCase() === gitHost?.link.scopeAlias),
713 );
714 const lender = own ?? preferFirst(onTracker);
715 if (lender === undefined) {
716 return yield* new IssueUnavailableError({ reason: "tracker-unsupported" });
717 }
718 const served = {
719 ...lender,
720 scope: own === undefined ? link.scope : lender.scope,
721 writable: own !== undefined,
722 };
723 const resolved = {
724 projectId: lender.project.id,
725 tracker: lender.tracker,
726 host: lender.host,
727 scope: served.scope,
728 key: link.key,
729 writable: served.writable,
730 };
731 if (standalone === null) return resolved;
732 // Team keys repeat across workspaces; only the credential's canonical issue URL identifies one.
733 const issue = yield* lender.api
734 .getIssue({
735 cwd: lender.project.workspaceRoot,
736 host: lender.host,
737 scope: link.scope,
738 key: link.key,
739 })
740 .pipe(Effect.mapError(toIssueError("resolveUrl")));
741 const canonicalUrl = parseUrl(issue.url);
742 const canonical = canonicalUrl === null ? null : standalone.api.parseIssueUrl(canonicalUrl);
743 if (canonical === null || canonical.workspace !== standalone.link.workspace) {
744 return yield* new IssueOperationError({
745 operation: "resolveUrl",
746 reason: "not-found",
747 detail: "This issue URL does not belong to the connected workspace.",
748 });
749 }
750 return { ...resolved, issue: toDetail(served, issue) };
751 },
752 );
753​
754 return IssueService.of({
755 list,
756 detail: traced("detail", detail),
757 comments: traced("comments", comments),
758 templates: traced("templates", templates),
759 candidates: interactive(traced("candidates", candidates)),
760 create: interactive(traced("create", create)),
761 comment: interactive(traced("comment", comment)),
762 update: interactive(traced("update", update)),
763 setState: interactive(traced("setState", setState)),
764 react: interactive(traced("react", react)),
765 projectScope,
766 resolveUrl,
767 });
768});
769​
770export const layer = Layer.effect(IssueService, make);