-
-
Notifications
You must be signed in to change notification settings - Fork 18
Expand file tree
/
Copy pathlinear-service.ts
More file actions
917 lines (820 loc) · 26 KB
/
linear-service.ts
File metadata and controls
917 lines (820 loc) · 26 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
import { LinearClient } from "@linear/sdk";
import { CommandOptions, getApiToken } from "./auth.js";
import {
CreateCommentArgs,
LinearComment,
LinearInitiative,
LinearIssue,
LinearLabel,
LinearProject,
} from "./linear-types.js";
import { isUuid } from "./uuid.js";
import { parseIssueIdentifier } from "./identifier-parser.js";
import { multipleMatchesError, notFoundError } from "./error-messages.js";
// Default pagination limit for Linear SDK queries to avoid complexity errors
const DEFAULT_CYCLE_PAGINATION_LIMIT = 250;
/**
* Generic ID resolver that handles UUID validation and passthrough
*
* @param input - Input string that may be a UUID or identifier
* @returns UUID as-is, or original string for non-UUID inputs
*/
function resolveId(input: string): string {
if (isUuid(input)) {
return input;
}
// Return as-is for non-UUID inputs that need further resolution
return input;
}
/**
* Build common GraphQL filter for name/key equality searches
*
* @param field - GraphQL field name
* @param value - Value to match exactly
* @returns GraphQL filter object
*/
function buildEqualityFilter(field: string, value: string): any {
return {
[field]: { eq: value },
};
}
/**
* Execute a Linear client query and handle "not found" errors consistently
*
* @param queryFn - Function that returns a promise with nodes array
* @param entityName - Human-readable entity name for error messages
* @param identifier - The identifier used in the query
* @returns The first node from the result
* @throws Error if no nodes are found
*/
async function executeLinearQuery<T>(
queryFn: () => Promise<{ nodes: T[] }>,
entityName: string,
identifier: string,
): Promise<T> {
const result = await queryFn();
if (result.nodes.length === 0) {
throw new Error(`${entityName} "${identifier}" not found`);
}
return result.nodes[0];
}
/**
* Linear SDK service with smart ID resolution and optimized operations
*
* Provides fallback operations and comprehensive ID resolution for Linear entities.
* This service handles human-friendly identifiers (TEAM-123, project names, etc.)
* and resolves them to Linear UUIDs for API operations.
*
* Features:
* - Smart ID resolution for teams, projects, labels, and issues
* - Fallback operations when GraphQL optimizations aren't available
* - Consistent error handling and messaging
* - Batch operations where possible
*/
export class LinearService {
private client: LinearClient;
/**
* Initialize Linear service with authentication
*
* @param apiToken - Linear API token for authentication
*/
constructor(apiToken: string) {
this.client = new LinearClient({ apiKey: apiToken });
}
/**
* Resolve issue identifier to UUID (lightweight version for ID-only resolution)
*
* @param issueId - Either a UUID string or TEAM-123 format identifier
* @returns The resolved UUID string
* @throws Error if the issue identifier format is invalid or issue not found
*
* @example
* ```typescript
* // Using UUID
* const uuid1 = await resolveIssueId("123e4567-e89b-12d3-a456-426614174000");
*
* // Using TEAM-123 format
* const uuid2 = await resolveIssueId("ABC-123");
* ```
*/
async resolveIssueId(issueId: string): Promise<string> {
// Return UUID as-is
if (isUuid(issueId)) {
return issueId;
}
// Parse identifier (ABC-123 format) and resolve to UUID
const { teamKey, issueNumber } = parseIssueIdentifier(issueId);
const issues = await this.client.issues({
filter: {
number: { eq: issueNumber },
team: { key: { eq: teamKey } },
},
first: 1,
});
if (issues.nodes.length === 0) {
throw new Error(`Issue with identifier "${issueId}" not found`);
}
return issues.nodes[0].id;
}
/**
* Get all teams in the workspace
*
* @returns Array of teams with id, key, name, and description
*/
async getTeams(): Promise<any[]> {
const teamsConnection = await this.client.teams({
first: 100,
});
// Sort by name client-side since Linear API doesn't support orderBy: "name"
const teams = teamsConnection.nodes.map((team) => ({
id: team.id,
key: team.key,
name: team.name,
description: team.description || null,
}));
return teams.sort((a, b) => a.name.localeCompare(b.name));
}
/**
* Get all users in the workspace
*
* @param activeOnly - If true, return only active users
* @returns Array of users with id, name, displayName, email, and active status
*/
async getUsers(activeOnly?: boolean): Promise<any[]> {
const filter: any = {};
if (activeOnly) {
filter.active = { eq: true };
}
const usersConnection = await this.client.users({
filter: Object.keys(filter).length > 0 ? filter : undefined,
first: 100,
});
// Sort by name client-side since Linear API doesn't support orderBy: "name"
const users = usersConnection.nodes.map((user) => ({
id: user.id,
name: user.name,
displayName: user.displayName,
email: user.email,
active: user.active,
}));
return users.sort((a, b) => a.name.localeCompare(b.name));
}
/**
* Get all projects
*/
async getProjects(): Promise<LinearProject[]> {
const projects = await this.client.projects({
first: 100,
orderBy: "updatedAt" as any,
includeArchived: false,
});
// Fetch all relationships in parallel for all projects
const projectsWithData = await Promise.all(
projects.nodes.map(async (project) => {
const [teams, lead] = await Promise.all([
project.teams(),
project.lead,
]);
return { project, teams, lead };
}),
);
return projectsWithData.map(({ project, teams, lead }) => ({
id: project.id,
name: project.name,
description: project.description || undefined,
state: project.state,
progress: project.progress,
teams: teams.nodes.map((team: any) => ({
id: team.id,
key: team.key,
name: team.name,
})),
lead: lead
? {
id: lead.id,
name: lead.name,
}
: undefined,
// Convert date objects to ISO 8601 strings for JSON serialization
targetDate: project.targetDate
? new Date(project.targetDate).toISOString()
: undefined,
createdAt: project.createdAt
? new Date(project.createdAt).toISOString()
: new Date().toISOString(),
updatedAt: project.updatedAt
? new Date(project.updatedAt).toISOString()
: new Date().toISOString(),
}));
}
/**
* Resolve team key or name to team ID
*/
async resolveTeamId(teamKeyOrNameOrId: string): Promise<string> {
// Use generic ID resolver
const resolved = resolveId(teamKeyOrNameOrId);
if (resolved === teamKeyOrNameOrId && isUuid(teamKeyOrNameOrId)) {
return teamKeyOrNameOrId;
}
// Try to find by key first (like "ABC"), then by name
try {
const team = await executeLinearQuery(
() =>
this.client.teams({
filter: buildEqualityFilter("key", teamKeyOrNameOrId),
first: 1,
}),
"Team",
teamKeyOrNameOrId,
);
return team.id;
} catch {
// If not found by key, try by name
const team = await executeLinearQuery(
() =>
this.client.teams({
filter: buildEqualityFilter("name", teamKeyOrNameOrId),
first: 1,
}),
"Team",
teamKeyOrNameOrId,
);
return team.id;
}
}
/**
* Resolve status name to status ID for a specific team
*/
async resolveStatusId(statusName: string, teamId?: string): Promise<string> {
// Return UUID as-is
if (isUuid(statusName)) {
return statusName;
}
// Build filter for workflow states
const filter: any = {
name: { eqIgnoreCase: statusName },
};
// If teamId is provided, filter by team
if (teamId) {
filter.team = { id: { eq: teamId } };
}
const statuses = await this.client.workflowStates({
filter,
first: 1,
});
if (statuses.nodes.length === 0) {
const context = teamId ? ` for team ${teamId}` : "";
throw new Error(`Status "${statusName}"${context} not found`);
}
return statuses.nodes[0].id;
}
/**
* Get all labels (workspace and team-specific)
*/
async getLabels(teamFilter?: string): Promise<{ labels: LinearLabel[] }> {
const labels: LinearLabel[] = [];
if (teamFilter) {
// Get labels for specific team only
const teamId = await this.resolveTeamId(teamFilter);
const team = await this.client.team(teamId);
const teamLabels = await this.client.issueLabels({
filter: { team: { id: { eq: teamId } } },
first: 100,
});
for (const label of teamLabels.nodes) {
// Skip group labels (isGroup: true) as they're containers, not actual labels
if (label.isGroup) {
continue;
}
const parent = await label.parent;
const labelData: LinearLabel = {
id: label.id,
name: label.name,
color: label.color,
scope: "team",
team: {
id: team.id,
name: team.name,
},
};
// Add group info if this label has a parent group
if (parent) {
// Fetch the parent label details to get the name
const parentLabel = await this.client.issueLabel(parent.id);
labelData.group = {
id: parent.id,
name: parentLabel.name,
};
}
labels.push(labelData);
}
} else {
// Get all labels (workspace + team labels)
const allLabels = await this.client.issueLabels({
first: 100,
});
for (const label of allLabels.nodes) {
// Skip group labels (isGroup: true) as they're containers, not actual labels
if (label.isGroup) {
continue;
}
const [team, parent] = await Promise.all([
label.team,
label.parent,
]);
const labelData: LinearLabel = {
id: label.id,
name: label.name,
color: label.color,
scope: team ? "team" : "workspace",
};
// Add team info if this is a team-specific label
if (team) {
labelData.team = {
id: team.id,
name: team.name,
};
}
// Add group info if this label has a parent group
if (parent) {
// Fetch the parent label details to get the name
const parentLabel = await this.client.issueLabel(parent.id);
labelData.group = {
id: parent.id,
name: parentLabel.name,
};
}
labels.push(labelData);
}
}
return { labels };
}
/**
* Create comment on issue
*/
async createComment(args: CreateCommentArgs): Promise<LinearComment> {
const payload = await this.client.createComment({
issueId: args.issueId,
body: args.body,
});
if (!payload.success) {
throw new Error("Failed to create comment");
}
// Fetch the created comment to return full data
const comment = await payload.comment;
if (!comment) {
throw new Error("Failed to retrieve created comment");
}
const user = await comment.user;
if (!user) {
throw new Error("Failed to retrieve comment user information");
}
return {
id: comment.id,
body: comment.body,
user: {
id: user.id,
name: user.name,
},
createdAt: comment.createdAt.toISOString(),
updatedAt: comment.updatedAt.toISOString(),
};
}
/**
* Get all cycles with automatic pagination
*
* @param teamFilter - Optional team key, name, or ID to filter cycles
* @param activeOnly - If true, return only active cycles
* @returns Array of cycles with team information
*
* @remarks
* Uses Linear SDK automatic pagination with 250 cycles per request.
* This method will make multiple API calls if necessary to fetch all
* matching cycles.
*
* For workspaces with hundreds of cycles, consider using team filtering
* to reduce result set size and improve performance.
*/
async getCycles(teamFilter?: string, activeOnly?: boolean): Promise<any[]> {
const filter: any = {};
if (teamFilter) {
const teamId = await this.resolveTeamId(teamFilter);
filter.team = { id: { eq: teamId } };
}
if (activeOnly) {
filter.isActive = { eq: true };
}
const cyclesConnection = await this.client.cycles({
filter: Object.keys(filter).length > 0 ? filter : undefined,
orderBy: "createdAt" as any,
first: DEFAULT_CYCLE_PAGINATION_LIMIT,
});
// Fetch all relationships in parallel for all cycles
// Note: Uses Promise.all - entire operation fails if any team fetch fails.
// This ensures data consistency (all cycles have team data or none do).
// If partial failures are acceptable, use Promise.allSettled instead.
const cyclesWithData = await Promise.all(
cyclesConnection.nodes.map(async (cycle) => {
const team = await cycle.team;
return {
id: cycle.id,
name: cycle.name,
number: cycle.number,
// Convert date objects to ISO 8601 strings for JSON serialization
startsAt: cycle.startsAt
? new Date(cycle.startsAt).toISOString()
: undefined,
endsAt: cycle.endsAt
? new Date(cycle.endsAt).toISOString()
: undefined,
isActive: cycle.isActive,
isPrevious: cycle.isPrevious,
isNext: cycle.isNext,
progress: cycle.progress,
issueCountHistory: cycle.issueCountHistory,
team: team
? {
id: team.id,
key: team.key,
name: team.name,
}
: undefined,
};
}),
);
return cyclesWithData;
}
/**
* Get single cycle by ID with issues
*
* @param cycleId - Cycle UUID
* @param issuesLimit - Maximum issues to fetch (default 50)
* @returns Cycle with issues
*
* @remarks
* This method does not paginate issues. If a cycle has more issues than
* the limit, only the first N will be returned sorted by creation date.
*
* Linear API limits single requests to 250 items. Values above 250 may
* result in errors or truncation.
*
* To get all issues in a large cycle, either:
* 1. Increase the limit (up to 250)
* 2. Fetch issues separately using the issues API with pagination
* 3. Make multiple requests with cursor-based pagination
*/
async getCycleById(cycleId: string, issuesLimit: number = 50): Promise<any> {
const cycle = await this.client.cycle(cycleId);
const [team, issuesConnection] = await Promise.all([
cycle.team,
cycle.issues({ first: issuesLimit }),
]);
const issues = [];
for (const issue of issuesConnection.nodes) {
const [state, assignee, issueTeam, project, labels] = await Promise.all([
issue.state,
issue.assignee,
issue.team,
issue.project,
issue.labels(),
]);
issues.push({
id: issue.id,
identifier: issue.identifier,
title: issue.title,
description: issue.description || undefined,
priority: issue.priority,
estimate: issue.estimate || undefined,
state: state ? { id: state.id, name: state.name } : undefined,
assignee: assignee
? { id: assignee.id, name: assignee.name }
: undefined,
team: issueTeam
? { id: issueTeam.id, key: issueTeam.key, name: issueTeam.name }
: undefined,
project: project ? { id: project.id, name: project.name } : undefined,
labels: labels.nodes.map((label: any) => ({
id: label.id,
name: label.name,
})),
createdAt: issue.createdAt
? new Date(issue.createdAt).toISOString()
: new Date().toISOString(),
updatedAt: issue.updatedAt
? new Date(issue.updatedAt).toISOString()
: new Date().toISOString(),
});
}
return {
id: cycle.id,
name: cycle.name,
number: cycle.number,
// Convert date objects to ISO 8601 strings for JSON serialization
startsAt: cycle.startsAt
? new Date(cycle.startsAt).toISOString()
: undefined,
endsAt: cycle.endsAt ? new Date(cycle.endsAt).toISOString() : undefined,
isActive: cycle.isActive,
progress: cycle.progress,
issueCountHistory: cycle.issueCountHistory,
team: team
? {
id: team.id,
key: team.key,
name: team.name,
}
: undefined,
issues,
};
}
/**
* Resolve cycle by name or ID
*/
async resolveCycleId(
cycleNameOrId: string,
teamFilter?: string,
): Promise<string> {
// Return UUID as-is
if (isUuid(cycleNameOrId)) {
return cycleNameOrId;
}
// Build filter for name-based lookup
const filter: any = {
name: { eq: cycleNameOrId },
};
// If teamId is provided, filter by team
if (teamFilter) {
const teamId = await this.resolveTeamId(teamFilter);
filter.team = { id: { eq: teamId } };
}
const cyclesConnection = await this.client.cycles({
filter,
first: 10,
});
const cyclesData = cyclesConnection.nodes;
const nodes = [];
for (const cycle of cyclesData) {
const team = await cycle.team;
nodes.push({
id: cycle.id,
name: cycle.name,
number: cycle.number,
startsAt: cycle.startsAt
? new Date(cycle.startsAt).toISOString()
: undefined,
isActive: cycle.isActive,
isNext: cycle.isNext,
isPrevious: cycle.isPrevious,
team: team
? { id: team.id, key: team.key, name: team.name }
: undefined,
});
}
if (nodes.length === 0) {
throw notFoundError(
"Cycle",
cycleNameOrId,
teamFilter ? `for team ${teamFilter}` : undefined,
);
}
// Disambiguate: prefer active, then next, then previous
let chosen = nodes.find((n: any) => n.isActive);
if (!chosen) chosen = nodes.find((n: any) => n.isNext);
if (!chosen) chosen = nodes.find((n: any) => n.isPrevious);
if (!chosen && nodes.length === 1) chosen = nodes[0];
if (!chosen) {
const matches = nodes.map((n: any) =>
`${n.id} (${n.team?.key || "?"} / #${n.number} / ${n.startsAt})`
);
throw multipleMatchesError(
"cycle",
cycleNameOrId,
matches,
"use an ID or scope with --team",
);
}
return chosen.id;
}
/**
* Resolve project identifier to UUID
*
* @param projectNameOrId - Project name or UUID
* @returns Project UUID
* @throws Error if project not found
*/
async resolveProjectId(projectNameOrId: string): Promise<string> {
if (isUuid(projectNameOrId)) {
return projectNameOrId;
}
// Use case-insensitive matching for better UX
const filter = { name: { eqIgnoreCase: projectNameOrId } };
const projectsConnection = await this.client.projects({ filter, first: 1 });
if (projectsConnection.nodes.length === 0) {
throw new Error(`Project "${projectNameOrId}" not found`);
}
return projectsConnection.nodes[0].id;
}
/**
* Get all initiatives
*
* @param statusFilter - Optional status filter (Planned/Active/Completed)
* @param ownerFilter - Optional owner ID filter
* @param limit - Maximum initiatives to fetch (default 50)
* @returns Array of initiatives with owner information
*/
async getInitiatives(
statusFilter?: string,
ownerFilter?: string,
limit: number = 50,
): Promise<LinearInitiative[]> {
const filter: any = {};
if (statusFilter) {
filter.status = { eq: statusFilter };
}
if (ownerFilter) {
filter.owner = { id: { eq: ownerFilter } };
}
const initiativesConnection = await this.client.initiatives({
filter: Object.keys(filter).length > 0 ? filter : undefined,
first: limit,
});
// Fetch owner relationship in parallel for all initiatives
const initiativesWithData = await Promise.all(
initiativesConnection.nodes.map(async (initiative) => {
const owner = await initiative.owner;
return {
id: initiative.id,
name: initiative.name,
description: initiative.description || undefined,
content: initiative.content || undefined,
status: initiative.status as "Planned" | "Active" | "Completed",
health: initiative.health as
| "onTrack"
| "atRisk"
| "offTrack"
| undefined,
targetDate: initiative.targetDate
? new Date(initiative.targetDate).toISOString()
: undefined,
owner: owner
? {
id: owner.id,
name: owner.name,
}
: undefined,
createdAt: initiative.createdAt
? new Date(initiative.createdAt).toISOString()
: new Date().toISOString(),
updatedAt: initiative.updatedAt
? new Date(initiative.updatedAt).toISOString()
: new Date().toISOString(),
};
}),
);
return initiativesWithData;
}
/**
* Get single initiative by ID with projects and sub-initiatives
*
* @param initiativeId - Initiative UUID
* @param projectsLimit - Maximum projects to fetch (default 50)
* @returns Initiative with projects and sub-initiatives
*/
async getInitiativeById(
initiativeId: string,
projectsLimit: number = 50,
): Promise<LinearInitiative> {
const initiative = await this.client.initiative(initiativeId);
const [
owner,
projectsConnection,
parentInitiative,
subInitiativesConnection,
] = await Promise.all([
initiative.owner,
initiative.projects({ first: projectsLimit }),
initiative.parentInitiative,
initiative.subInitiatives({ first: 50 }),
]);
// Map projects with basic info
const projects = projectsConnection.nodes.map((project) => ({
id: project.id,
name: project.name,
state: project.state,
progress: project.progress,
}));
// Map sub-initiatives
const subInitiatives = subInitiativesConnection.nodes.map((sub) => ({
id: sub.id,
name: sub.name,
status: sub.status as "Planned" | "Active" | "Completed",
}));
return {
id: initiative.id,
name: initiative.name,
description: initiative.description || undefined,
content: initiative.content || undefined,
status: initiative.status as "Planned" | "Active" | "Completed",
health: initiative.health as
| "onTrack"
| "atRisk"
| "offTrack"
| undefined,
targetDate: initiative.targetDate
? new Date(initiative.targetDate).toISOString()
: undefined,
owner: owner
? {
id: owner.id,
name: owner.name,
}
: undefined,
createdAt: initiative.createdAt
? new Date(initiative.createdAt).toISOString()
: new Date().toISOString(),
updatedAt: initiative.updatedAt
? new Date(initiative.updatedAt).toISOString()
: new Date().toISOString(),
projects: projects.length > 0 ? projects : undefined,
parentInitiative: parentInitiative
? {
id: parentInitiative.id,
name: parentInitiative.name,
}
: undefined,
subInitiatives: subInitiatives.length > 0 ? subInitiatives : undefined,
};
}
/**
* Resolve initiative by name or ID
*
* @param initiativeNameOrId - Initiative name or UUID
* @returns Initiative UUID
* @throws Error if initiative not found or multiple matches
*/
async resolveInitiativeId(initiativeNameOrId: string): Promise<string> {
// Return UUID as-is
if (isUuid(initiativeNameOrId)) {
return initiativeNameOrId;
}
// Search by name (case-insensitive)
const initiativesConnection = await this.client.initiatives({
filter: { name: { eqIgnoreCase: initiativeNameOrId } },
first: 10,
});
const nodes = initiativesConnection.nodes;
if (nodes.length === 0) {
throw notFoundError("Initiative", initiativeNameOrId);
}
if (nodes.length === 1) {
return nodes[0].id;
}
// Multiple matches - prefer Active, then Planned
let chosen = nodes.find((n) => n.status === "Active");
if (!chosen) chosen = nodes.find((n) => n.status === "Planned");
if (!chosen) chosen = nodes[0];
return chosen.id;
}
/**
* Update an initiative
*
* @param initiativeId - Initiative UUID
* @param updates - Fields to update
* @returns Updated initiative
*/
async updateInitiative(
initiativeId: string,
updates: {
name?: string;
description?: string;
content?: string;
status?: "Planned" | "Active" | "Completed";
ownerId?: string;
targetDate?: string;
},
): Promise<LinearInitiative> {
// Build update input with only provided fields
const input: Record<string, any> = {};
if (updates.name !== undefined) input.name = updates.name;
if (updates.description !== undefined) input.description = updates.description;
if (updates.content !== undefined) input.content = updates.content;
if (updates.status !== undefined) input.status = updates.status;
if (updates.ownerId !== undefined) input.ownerId = updates.ownerId;
if (updates.targetDate !== undefined) input.targetDate = updates.targetDate;
const payload = await this.client.updateInitiative(initiativeId, input);
if (!payload.success) {
throw new Error("Failed to update initiative");
}
// Re-fetch to get complete data
return this.getInitiativeById(initiativeId);
}
}
/**
* Create LinearService instance with authentication
*/
export async function createLinearService(
options: CommandOptions,
): Promise<LinearService> {
const apiToken = await getApiToken(options);
return new LinearService(apiToken);
}