-
Notifications
You must be signed in to change notification settings - Fork 71
Expand file tree
/
Copy pathlinear.ts
More file actions
1166 lines (1074 loc) · 28.3 KB
/
linear.ts
File metadata and controls
1166 lines (1074 loc) · 28.3 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
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { gql } from "../__codegen__/gql.ts"
import type {
GetAllTeamsQuery,
GetAllTeamsQueryVariables as _GetAllTeamsQueryVariables,
GetIssuesForStateQuery,
GetTeamMembersQuery,
IssueFilter,
IssueSortInput,
LookupUsersForIssueResolutionQuery,
LookupUsersForIssueResolutionQueryVariables,
} from "../__codegen__/graphql.ts"
import { LookupUsersForIssueResolutionDocument } from "../__codegen__/graphql.ts"
import { Select } from "@cliffy/prompt"
import { getOption } from "../config.ts"
import { getGraphQLClient } from "./graphql.ts"
import { getCurrentIssueFromVcs } from "./vcs.ts"
import { NotFoundError, ValidationError } from "./errors.ts"
function isValidLinearIdentifier(id: string): boolean {
return /^[a-zA-Z0-9]+-[1-9][0-9]*$/i.test(id)
}
export function formatIssueIdentifier(providedId: string): string {
return providedId.toUpperCase()
}
export function getTeamKey(): string | undefined {
const teamId = getOption("team_id")
if (teamId) {
return teamId.toUpperCase()
}
return undefined
}
/**
* based on loose inputs, returns a linear issue identifier like ABC-123
*
* formats the provided identifier, adds the team id prefix, or finds one from VCS state
*/
export async function getIssueIdentifier(
providedId?: string,
): Promise<string | undefined> {
if (providedId && isValidLinearIdentifier(providedId)) {
return formatIssueIdentifier(providedId)
}
if (providedId && /^[1-9][0-9]*$/.test(providedId)) {
const teamId = getTeamKey()
if (teamId) {
const fullId = `${teamId}-${providedId}`
if (isValidLinearIdentifier(fullId)) {
return formatIssueIdentifier(fullId)
}
} else {
throw new Error(
"an integer id was provided, but no team is set. run `linear configure`",
)
}
}
if (providedId === undefined) {
const issueId = await getCurrentIssueFromVcs()
return issueId || undefined
}
}
export async function getIssueId(
identifier: string,
): Promise<string | undefined> {
const query = gql(/* GraphQL */ `
query GetIssueId($id: String!) {
issue(id: $id) {
id
}
}
`)
const client = getGraphQLClient()
const data = await client.request(query, { id: identifier })
return data.issue?.id
}
export async function getWorkflowStates(
teamKey: string,
) {
const query = gql(/* GraphQL */ `
query GetWorkflowStates($teamKey: String!) {
team(id: $teamKey) {
states {
nodes {
id
name
type
position
}
}
}
}
`)
const client = getGraphQLClient()
const result = await client.request(query, { teamKey })
return result.team.states.nodes.sort(
(a: { position: number }, b: { position: number }) =>
a.position - b.position,
)
}
export type WorkflowState = Awaited<
ReturnType<typeof getWorkflowStates>
>[number]
export async function getStartedState(
teamKey: string,
): Promise<{ id: string; name: string }> {
const states = await getWorkflowStates(teamKey)
const startedStates = states.filter((s) => s.type === "started")
if (!startedStates.length) {
throw new Error("No 'started' state found in workflow")
}
return { id: startedStates[0].id, name: startedStates[0].name }
}
export async function getWorkflowStateByNameOrType(
teamKey: string,
nameOrType: string,
): Promise<{ id: string; name: string } | undefined> {
const states = await getWorkflowStates(teamKey)
const nameMatch = states.find(
(s) => s.name.toLowerCase() === nameOrType.toLowerCase(),
)
if (nameMatch) {
return { id: nameMatch.id, name: nameMatch.name }
}
const typeMatch = states.find((s) => s.type === nameOrType.toLowerCase())
if (typeMatch) {
return { id: typeMatch.id, name: typeMatch.name }
}
return undefined
}
export async function updateIssueState(
issueId: string,
stateId: string,
): Promise<void> {
const mutation = gql(/* GraphQL */ `
mutation UpdateIssueState($issueId: String!, $stateId: String!) {
issueUpdate(id: $issueId, input: { stateId: $stateId }) {
success
}
}
`)
const client = getGraphQLClient()
await client.request(mutation, { issueId, stateId })
}
export async function fetchIssueDetails(
issueId: string,
_showSpinner = false,
includeComments = false,
): Promise<{
identifier: string
title: string
description?: string | null | undefined
url: string
branchName: string
state: { name: string; color: string }
project?: { name: string } | null
projectMilestone?: { name: string } | null
cycle?: { name?: string | null; number: number } | null
parent?: {
identifier: string
title: string
state: { name: string; color: string }
} | null
children?: Array<{
identifier: string
title: string
state: { name: string; color: string }
}>
comments?: Array<{
id: string
body: string
createdAt: string
user?: { name: string; displayName: string } | null
externalUser?: { name: string; displayName: string } | null
parent?: { id: string } | null
}>
attachments?: Array<{
id: string
title: string
url: string
subtitle?: string | null
sourceType?: string | null
metadata: Record<string, unknown>
createdAt: string
}>
}> {
const { Spinner } = await import("@std/cli/unstable-spinner")
const { shouldShowSpinner } = await import("./hyperlink.ts")
const spinner = shouldShowSpinner() ? new Spinner() : null
spinner?.start()
try {
const queryWithComments = gql(/* GraphQL */ `
query GetIssueDetailsWithComments($id: String!) {
issue(id: $id) {
identifier
title
description
url
branchName
state {
name
color
}
project {
name
}
projectMilestone {
name
}
cycle {
name
number
}
parent {
identifier
title
state {
name
color
}
}
children(first: 250) {
nodes {
identifier
title
state {
name
color
}
}
}
comments(first: 50, orderBy: createdAt) {
nodes {
id
body
createdAt
user {
name
displayName
}
externalUser {
name
displayName
}
parent {
id
}
}
}
attachments(first: 50) {
nodes {
id
title
url
subtitle
sourceType
metadata
createdAt
}
}
}
}
`)
const queryWithoutComments = gql(/* GraphQL */ `
query GetIssueDetails($id: String!) {
issue(id: $id) {
identifier
title
description
url
branchName
state {
name
color
}
project {
name
}
projectMilestone {
name
}
cycle {
name
number
}
parent {
identifier
title
state {
name
color
}
}
children(first: 250) {
nodes {
identifier
title
state {
name
color
}
}
}
attachments(first: 50) {
nodes {
id
title
url
subtitle
sourceType
metadata
createdAt
}
}
}
}
`)
const client = getGraphQLClient()
if (includeComments) {
const data = await client.request(queryWithComments, { id: issueId })
spinner?.stop()
return {
...data.issue,
children: data.issue.children?.nodes || [],
comments: data.issue.comments?.nodes || [],
attachments: data.issue.attachments?.nodes || [],
}
} else {
const data = await client.request(queryWithoutComments, { id: issueId })
spinner?.stop()
return {
...data.issue,
children: data.issue.children?.nodes || [],
attachments: data.issue.attachments?.nodes || [],
}
}
} catch (error) {
spinner?.stop()
// Re-throw to let caller handle with proper context
throw error
}
}
export async function fetchParentIssueTitle(
parentId: string,
): Promise<string | null> {
try {
const query = gql(/* GraphQL */ `
query GetParentIssueTitle($id: String!) {
issue(id: $id) {
title
identifier
}
}
`)
const client = getGraphQLClient()
const data = await client.request(query, { id: parentId })
return `${data.issue.identifier}: ${data.issue.title}`
} catch {
// Silently fail for optional parent lookup - caller handles display
return null
}
}
export async function fetchParentIssueData(parentId: string): Promise<
{
title: string
identifier: string
projectId: string | null
} | null
> {
try {
const query = gql(/* GraphQL */ `
query GetParentIssueData($id: String!) {
issue(id: $id) {
title
identifier
project {
id
}
}
}
`)
const client = getGraphQLClient()
const data = await client.request(query, { id: parentId })
return {
title: data.issue.title,
identifier: data.issue.identifier,
projectId: data.issue.project?.id || null,
}
} catch {
// Silently fail for optional parent lookup - caller handles display
return null
}
}
export async function fetchIssuesForState(
teamKey: string,
state: string[] | undefined,
assignee?: string,
unassigned = false,
allAssignees = false,
limit?: number,
projectId?: string,
sortParam?: "manual" | "priority",
cycleId?: string,
milestoneId?: string,
) {
const sort = sortParam ??
getOption("issue_sort") as "manual" | "priority" | undefined
if (!sort) {
throw new ValidationError(
"Sort must be provided",
{
suggestion:
"Use --sort parameter, set in configuration file, or set LINEAR_ISSUE_SORT environment variable",
},
)
}
const filter: IssueFilter = {
team: { key: { eq: teamKey } },
}
if (state) {
filter.state = { type: { in: state } }
}
if (unassigned) {
filter.assignee = { null: true }
} else if (allAssignees) {
// No assignee filter means all assignees
} else if (assignee) {
const userId = await lookupUserId(assignee)
if (!userId) {
throw new NotFoundError("User", assignee)
}
filter.assignee = { id: { eq: userId } }
} else {
filter.assignee = { isMe: { eq: true } }
}
if (projectId) {
filter.project = { id: { eq: projectId } }
}
if (cycleId) {
filter.cycle = { id: { eq: cycleId } }
}
if (milestoneId) {
filter.projectMilestone = { id: { eq: milestoneId } }
}
const query = gql(/* GraphQL */ `
query GetIssuesForState($sort: [IssueSortInput!], $filter: IssueFilter!, $first: Int, $after: String) {
issues(filter: $filter, sort: $sort, first: $first, after: $after) {
nodes {
id
identifier
title
priority
estimate
assignee {
initials
}
state {
id
name
color
}
labels {
nodes {
id
name
color
}
}
updatedAt
}
pageInfo {
hasNextPage
endCursor
}
}
}
`)
let sortPayload: Array<IssueSortInput>
switch (sort) {
case "manual":
sortPayload = [
{ workflowState: { order: "Descending" } },
{ manual: { nulls: "last" as const, order: "Ascending" as const } },
]
break
case "priority":
sortPayload = [
{ workflowState: { order: "Descending" } },
{ priority: { nulls: "last" as const, order: "Descending" as const } },
{ manual: { nulls: "last" as const, order: "Ascending" as const } },
]
break
default:
throw new ValidationError(`Unknown sort type: ${sort}`, {
suggestion: "Use 'manual' or 'priority'",
})
}
const client = getGraphQLClient()
const pageSize = limit !== undefined ? Math.min(limit, 100) : 50
const fetchAll = limit === undefined || limit === 0
const allIssues = []
let hasNextPage = true
let after: string | null | undefined = undefined
while (hasNextPage) {
const result: GetIssuesForStateQuery = await client.request(query, {
sort: sortPayload,
filter,
first: pageSize,
after,
})
const issues = result.issues?.nodes || []
allIssues.push(...issues)
if (!fetchAll && allIssues.length >= limit!) {
break
}
hasNextPage = result.issues?.pageInfo?.hasNextPage || false
after = result.issues?.pageInfo?.endCursor
}
return {
issues: {
nodes: allIssues.slice(0, limit),
},
}
}
export async function getProjectIdByName(
name: string,
): Promise<string | undefined> {
const client = getGraphQLClient()
const query = gql(/* GraphQL */ `
query GetProjectIdByName($name: String!) {
projects(filter: { name: { eq: $name } }) {
nodes {
id
}
}
}
`)
const data = await client.request(query, { name })
const projectId = data.projects?.nodes[0]?.id
if (projectId) return projectId
// Fall back to matching by slugId (the 12-char hex string visible in
// `project list` output and Linear URLs). This provides a reliable
// alternative when project names contain special characters that the
// exact-match name filter doesn't handle well.
const slugQuery = gql(/* GraphQL */ `
query GetProjectIdBySlugId($slugId: String!) {
projects(filter: { slugId: { eq: $slugId } }) {
nodes {
id
}
}
}
`)
const slugData = await client.request(slugQuery, { slugId: name })
return slugData.projects?.nodes[0]?.id
}
export async function resolveProjectId(
projectIdOrSlug: string,
): Promise<string> {
// If it looks like a full UUID, try to use it directly
if (
/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(
projectIdOrSlug,
)
) {
return projectIdOrSlug
}
// Otherwise, treat it as a slug and look it up
const client = getGraphQLClient()
const query = gql(/* GraphQL */ `
query GetProjectBySlug($slugId: String!) {
projects(filter: { slugId: { eq: $slugId } }) {
nodes {
id
slugId
}
}
}
`)
const data = await client.request(query, { slugId: projectIdOrSlug })
const projectId = data.projects?.nodes[0]?.id
if (!projectId) {
throw new NotFoundError("Project", projectIdOrSlug)
}
return projectId
}
export async function getProjectOptionsByName(
name: string,
): Promise<Record<string, string>> {
const client = getGraphQLClient()
const query = gql(/* GraphQL */ `
query GetProjectIdOptionsByName($name: String!) {
projects(filter: { name: { containsIgnoreCase: $name } }) {
nodes {
id
name
}
}
}
`)
const data = await client.request(query, { name })
const qResults = data.projects?.nodes || []
return Object.fromEntries(qResults.map((t) => [t.id, t.name]))
}
export async function getTeamIdByKey(
team: string,
): Promise<string | undefined> {
const client = getGraphQLClient()
const query = gql(/* GraphQL */ `
query GetTeamIdByKey($team: String!) {
teams(filter: { key: { eq: $team } }) {
nodes {
id
}
}
}
`)
const data = await client.request(query, { team })
return data.teams?.nodes[0]?.id
}
export async function searchTeamsByKeySubstring(
keySubstring: string,
): Promise<Record<string, string>> {
const client = getGraphQLClient()
const query = gql(/* GraphQL */ `
query GetTeamIdOptionsByKey($team: String!) {
teams(filter: { key: { containsIgnoreCase: $team } }) {
nodes {
id
key
name
}
}
}
`)
const data = await client.request(query, { team: keySubstring })
const qResults = data.teams?.nodes || []
const sortedResults = qResults.sort((a, b) =>
a.key.toLowerCase().localeCompare(b.key.toLowerCase())
)
return Object.fromEntries(
sortedResults.map((t) => [
t.id,
`${(t as { id: string; key: string; name: string }).name} (${t.key})`,
]),
)
}
export async function lookupUser(
/**
* email, username, display name, 'self', or '@me' for viewer
*/
input: "self" | "@me" | string,
): Promise<
| {
id: string
email?: string | null
displayName?: string | null
name: string
app: boolean
}
| undefined
> {
if (input === "@me" || input === "self") {
const client = getGraphQLClient()
const query = gql(/* GraphQL */ `
query GetViewerId {
viewer {
id
email
displayName
name
app
}
}
`)
const data = await client.request(query, {})
return data.viewer
} else {
const client = getGraphQLClient()
const query = gql(/* GraphQL */ `
query LookupUser($input: String!) {
users(
filter: {
or: [
{ email: { eqIgnoreCase: $input } }
{ displayName: { eqIgnoreCase: $input } }
{ name: { containsIgnoreCaseAndAccent: $input } }
]
}
) {
nodes {
id
email
displayName
name
app
}
}
}
`)
const data = await client.request(query, { input })
if (!data.users?.nodes?.length) {
return undefined
}
for (const user of data.users.nodes) {
if (user.email?.toLowerCase() === input.toLowerCase()) {
return user
}
}
for (const user of data.users.nodes) {
if (user.displayName?.toLowerCase() === input.toLowerCase()) {
return user
}
}
return data.users.nodes[0]
}
}
type LookupUserResult =
| { kind: "match"; user: NonNullable<Awaited<ReturnType<typeof lookupUser>>> }
| {
kind: "wrong_type"
user: NonNullable<Awaited<ReturnType<typeof lookupUser>>>
}
| { kind: "ambiguous" }
| { kind: "not_found" }
function selectTypedUserMatch(
users: Array<NonNullable<Awaited<ReturnType<typeof lookupUser>>>>,
expectedApp: boolean,
): LookupUserResult | null {
if (users.length === 0) {
return null
}
const expectedType = users.filter((user) => user.app === expectedApp)
if (expectedType.length === 1) {
return { kind: "match", user: expectedType[0] }
}
if (expectedType.length > 1) {
return { kind: "ambiguous" }
}
const oppositeType = users.filter((user) => user.app !== expectedApp)
if (oppositeType.length === 1) {
return { kind: "wrong_type", user: oppositeType[0] }
}
return { kind: "ambiguous" }
}
export async function resolveIssueUser(
input: "self" | "@me" | string,
expectedApp: boolean,
): Promise<LookupUserResult> {
const exactSelf = input === "@me" || input === "self"
? await lookupUser(input)
: undefined
if (exactSelf) {
return exactSelf.app === expectedApp
? { kind: "match", user: exactSelf }
: { kind: "wrong_type", user: exactSelf }
}
const client = getGraphQLClient()
const data: LookupUsersForIssueResolutionQuery = await client.request(
LookupUsersForIssueResolutionDocument,
{ input } satisfies LookupUsersForIssueResolutionQueryVariables,
)
const users = data.users?.nodes ?? []
if (users.length === 0) {
return { kind: "not_found" }
}
const normalizedInput = input.toLowerCase()
const exactEmail = users.filter((user) =>
user.email?.toLowerCase() === normalizedInput
)
const exactDisplayName = users.filter((user) =>
user.displayName?.toLowerCase() === normalizedInput
)
const exactName = users.filter((user) =>
user.name.toLowerCase() === normalizedInput
)
return selectTypedUserMatch(exactEmail, expectedApp) ??
selectTypedUserMatch(exactDisplayName, expectedApp) ??
selectTypedUserMatch(exactName, expectedApp) ??
selectTypedUserMatch(users, expectedApp) ??
{ kind: "not_found" }
}
export async function lookupUserId(
/**
* email, username, display name, 'self', or '@me' for viewer
*/
input: "self" | "@me" | string,
): Promise<string | undefined> {
const user = await lookupUser(input)
return user?.id
}
export async function getIssueLabelIdByNameForTeam(
name: string,
teamKey: string,
): Promise<string | undefined> {
const client = getGraphQLClient()
const query = gql(/* GraphQL */ `
query GetIssueLabelIdByNameForTeam($name: String!, $teamKey: String!) {
issueLabels(
filter: {
name: { eqIgnoreCase: $name }
or: [{ team: { key: { eq: $teamKey } } }, { team: { null: true } }]
}
) {
nodes {
id
name
}
}
}
`)
const data = await client.request(query, { name, teamKey })
return data.issueLabels?.nodes[0]?.id
}
export async function getIssueLabelOptionsByNameForTeam(
name: string,
teamKey: string,
): Promise<Record<string, string>> {
const client = getGraphQLClient()
const query = gql(/* GraphQL */ `
query GetIssueLabelIdOptionsByNameForTeam(
$name: String!
$teamKey: String!
) {
issueLabels(
filter: {
name: { containsIgnoreCase: $name }
or: [{ team: { key: { eq: $teamKey } } }, { team: { null: true } }]
}
) {
nodes {
id
name
}
}
}
`)
const data = await client.request(query, { name, teamKey })
const qResults = data.issueLabels?.nodes || []
const sortedResults = qResults.sort((a, b) =>
a.name.toLowerCase().localeCompare(b.name.toLowerCase())
)
return Object.fromEntries(sortedResults.map((t) => [t.id, t.name]))
}
export async function getAllTeams(): Promise<
Array<{ id: string; key: string; name: string }>
> {
const client = getGraphQLClient()
const query = gql(/* GraphQL */ `
query GetAllTeams($first: Int, $after: String) {
teams(first: $first, after: $after) {
nodes {
id
key
name
}
pageInfo {
hasNextPage
endCursor
}
}
}
`)
const allTeams = []
let hasNextPage = true
let after: string | null | undefined = undefined
while (hasNextPage) {
const result: GetAllTeamsQuery = await client.request(query, {
first: 100, // Fetch 100 teams per page
after,
})
const teams = result.teams.nodes
allTeams.push(...teams)
hasNextPage = result.teams.pageInfo.hasNextPage
after = result.teams.pageInfo.endCursor
}
return allTeams.sort((a, b) =>
a.name.toLowerCase().localeCompare(b.name.toLowerCase())
)
}
export async function getLabelsForTeam(
teamKey: string,
): Promise<Array<{ id: string; name: string; color: string }>> {
const client = getGraphQLClient()
const query = gql(/* GraphQL */ `
query GetLabelsForTeam($teamKey: String!) {
team(id: $teamKey) {
labels {
nodes {
id
name
color
}
}
}
}
`)
const result = await client.request(query, { teamKey })
const labels = result.team?.labels?.nodes || []
return labels.sort((a, b) =>
a.name.toLowerCase().localeCompare(b.name.toLowerCase())
)
}
export async function getTeamMembers(teamKey: string) {
const client = getGraphQLClient()
const query = gql(/* GraphQL */ `
query GetTeamMembers($teamKey: String!, $first: Int, $after: String) {
team(id: $teamKey) {
members(first: $first, after: $after) {
nodes {
id
name
displayName
email
active
initials
description
timezone
lastSeen
statusEmoji
statusLabel
guest