-
Notifications
You must be signed in to change notification settings - Fork 3.7k
Expand file tree
/
Copy pathazure-devops.ts
More file actions
1714 lines (1581 loc) · 57.9 KB
/
Copy pathazure-devops.ts
File metadata and controls
1714 lines (1581 loc) · 57.9 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 { createLogger } from '@sim/logger'
import { getErrorMessage, toError } from '@sim/utils/errors'
import { fetchWithRetry, VALIDATE_RETRY_OPTIONS } from '@/lib/knowledge/documents/utils'
import { azureDevopsConnectorMeta } from '@/connectors/azure-devops/meta'
import type { ConnectorConfig, ExternalDocument, ExternalDocumentList } from '@/connectors/types'
import {
CONNECTOR_MAX_FILE_BYTES,
htmlToPlainText,
joinTagArray,
markSkipped,
parseTagDate,
readBodyWithLimit,
sizeLimitSkipReason,
} from '@/connectors/utils'
const logger = createLogger('AzureDevOpsConnector')
const ADO_BASE_URL = 'https://dev.azure.com'
const WIKI_API_VERSION = '7.1'
const WIKIS_LIST_API_VERSION = '7.1'
const WIQL_API_VERSION = '7.1'
const WORKITEMS_API_VERSION = '7.1'
const PROJECT_API_VERSION = '7.1'
const GIT_API_VERSION = '7.1'
/** Page size for the wiki `pagesbatch` endpoint. */
const WIKI_PAGE_BATCH_SIZE = 100
/** Page size for the WIQL → workitemsbatch listing pipeline. ADO caps a batch at 200 ids. */
const WORK_ITEM_BATCH_SIZE = 200
/** Concurrency for per-page wiki ETag lookups during listing. */
const WIKI_ETAG_CONCURRENCY = 5
/** Page size for paginating repository-file stubs out of the in-memory tree. */
const FILE_BATCH_SIZE = 100
/**
* Max repository file size to index. The Items list API does not return file
* size, so this cap is enforced at content-fetch time in getDocument: the raw
* octet-stream body is read through `readBodyWithLimit`, which streams the bytes
* and aborts (returning null) the moment the cap is exceeded. Larger files are
* skipped without being fully buffered.
*/
const MAX_FILE_SIZE = CONNECTOR_MAX_FILE_BYTES
/** Bytes sniffed for a NUL byte when detecting binary files (matches git's heuristic). */
const BINARY_SNIFF_BYTES = 8000
/**
* WIQL returns at most 20,000 work item references. We cap `$top` at this bound
* so the connector never silently relies on truncated results; users who need
* more should narrow the query via the work-item filters.
*/
const WIQL_MAX_RESULTS = 20000
/**
* externalId discriminators. Wiki pages are addressed by `wiki:{wikiId}:{path}`,
* work items by `wi:{id}`, and repository files by `file:{repoId}:{path}`.
*/
const FILE_PREFIX = 'file:'
type ContentType = 'wiki' | 'workitems' | 'files' | 'both' | 'all'
/** Listing phases, walked in order: wiki ➜ work items ➜ repository files. */
type SyncPhase = 'wiki' | 'workitems' | 'file'
/**
* Returns the ordered list of active sync phases for a content-type choice.
* Phase order is fixed (wiki ➜ workitems ➜ file) so the phase-encoded cursor and
* the maxItems phase-boundary guard compose deterministically.
*/
function activePhases(contentType: ContentType): SyncPhase[] {
const phases: SyncPhase[] = []
if (contentType === 'wiki' || contentType === 'both' || contentType === 'all') phases.push('wiki')
if (contentType === 'workitems' || contentType === 'both' || contentType === 'all') {
phases.push('workitems')
}
if (contentType === 'files' || contentType === 'all') phases.push('file')
return phases
}
/**
* Returns the phase following `current` for a content type, or undefined when
* `current` is the last active phase.
*/
function nextPhase(current: SyncPhase, contentType: ContentType): SyncPhase | undefined {
const phases = activePhases(contentType)
const idx = phases.indexOf(current)
return idx >= 0 && idx + 1 < phases.length ? phases[idx + 1] : undefined
}
/**
* Builds the Azure DevOps PAT auth header. ADO PATs authenticate via HTTP Basic
* with an empty username and the token as the password.
*/
function patAuthHeader(accessToken: string): string {
return `Basic ${Buffer.from(`:${accessToken}`).toString('base64')}`
}
/**
* Normalizes the configured content type, defaulting to wiki pages.
*/
function parseContentType(value: unknown): ContentType {
if (value === 'workitems' || value === 'files' || value === 'both' || value === 'all') {
return value
}
return 'wiki'
}
/**
* Heuristic binary detection: a NUL byte in the first 8 KB marks the file as
* binary, matching `git diff` / `git grep` semantics.
*/
function isBinaryBuffer(buf: Buffer): boolean {
const len = Math.min(buf.length, BINARY_SNIFF_BYTES)
for (let i = 0; i < len; i++) {
if (buf[i] === 0) return true
}
return false
}
/**
* Parses a comma-separated extension filter into a normalized set (leading dot,
* lowercased). Returns null when no filter is configured (accept all files).
*/
function parseExtensions(raw: unknown): Set<string> | null {
const trimmed = typeof raw === 'string' ? raw.trim() : ''
if (!trimmed) return null
const exts = trimmed
.split(',')
.map((e) => e.trim().toLowerCase())
.filter(Boolean)
.map((e) => (e.startsWith('.') ? e : `.${e}`))
return exts.length > 0 ? new Set(exts) : null
}
/**
* Returns true when the file path matches the extension filter (or no filter set).
*/
function matchesExtension(filePath: string, extSet: Set<string> | null): boolean {
if (!extSet) return true
const lastDot = filePath.lastIndexOf('.')
if (lastDot === -1) return false
return extSet.has(filePath.slice(lastDot).toLowerCase())
}
/**
* Strips the `refs/heads/` prefix from a default-branch ref so it can be used as
* a `versionDescriptor.version` branch name.
*/
function stripRefsHeads(ref: string): string {
return ref.replace(/^refs\/heads\//, '')
}
/**
* Reads a trimmed string config value, returning '' when absent.
*/
function readString(value: unknown): string {
return typeof value === 'string' ? value.trim() : ''
}
/**
* Escapes a value for safe interpolation into a single-quoted WIQL string literal.
* WIQL escapes an embedded single quote by doubling it.
*/
function escapeWiql(value: string): string {
return value.replace(/'/g, "''")
}
/**
* Encodes an external ID that combines a discriminator with its identifier,
* e.g. `wiki:{wikiId}:{pagePath}` or `wi:{id}`.
*/
function workItemExternalId(id: number): string {
return `wi:${id}`
}
function wikiPageExternalId(wikiId: string, pagePath: string): string {
return `wiki:${wikiId}:${pagePath}`
}
/**
* Parses a wiki external ID back into its wiki ID and page path.
*/
function parseWikiExternalId(externalId: string): { wikiId: string; pagePath: string } | null {
if (!externalId.startsWith('wiki:')) return null
const rest = externalId.slice('wiki:'.length)
const sep = rest.indexOf(':')
if (sep === -1) return null
return { wikiId: rest.slice(0, sep), pagePath: rest.slice(sep + 1) }
}
/**
* Builds the externalId for a repository file: `file:{repoId}:{path}`. The path
* retains its leading slash as returned by the Items API.
*/
function fileExternalId(repoId: string, path: string): string {
return `${FILE_PREFIX}${repoId}:${path}`
}
/**
* Parses a file externalId back into its repository ID and path. Returns null
* when the externalId is not a file ID.
*/
function parseFileExternalId(externalId: string): { repoId: string; path: string } | null {
if (!externalId.startsWith(FILE_PREFIX)) return null
const rest = externalId.slice(FILE_PREFIX.length)
const sep = rest.indexOf(':')
if (sep === -1) return null
return { repoId: rest.slice(0, sep), path: rest.slice(sep + 1) }
}
/**
* Builds the change-detection hash for a repository file. The git blob objectId
* is content-addressable, so it changes exactly when the file content changes,
* and it is reported both by the tree listing (`objectId`) and the per-file
* metadata fetch (`objectId`) — so the listing stub and the hydrated document
* normally hash identically without a content fetch during listing.
*
* Hydration in getFileDocument is a two-step fetch against the same branch ref:
* a JSON metadata call yields the objectId used for this hash, then a raw
* octet-stream call yields the content. Both pin to the branch *name*, not a
* commit SHA, so if the branch advances between the two calls the stored hash
* (metadata call's objectId) and the stored content (content call's bytes) can
* be one commit apart. This window is bounded and self-heals: the next listing
* reports the branch's current objectId, which differs from the stored
* one-commit-old hash, queuing an update that re-fetches and re-converges
* content and hash. (A revert to identical bytes yields the identical objectId
* by content-addressing, so the stored content is already correct in that case.)
*/
function buildFileContentHash(repoId: string, objectId: string): string {
return `ado:file:${repoId}:${objectId}`
}
interface WikiV2 {
id: string
name: string
remoteUrl?: string
type?: string
}
interface GitRepository {
id: string
name: string
defaultBranch?: string
isDisabled?: boolean
remoteUrl?: string
webUrl?: string
size?: number
}
interface GitItem {
objectId: string
gitObjectType?: string
path: string
isFolder?: boolean
content?: string
contentMetadata?: {
isBinary?: boolean
fileName?: string
encoding?: number
}
}
/**
* A repository file flattened across all in-scope repositories, carrying enough
* context to build its stub and source URL during offset-based pagination.
*/
interface RepoFileEntry {
repoId: string
repoName: string
repoWebUrl?: string
branch: string
item: GitItem
}
interface WikiPageDetail {
id: number
path: string
}
interface WorkItemRef {
id: number
}
interface RawWorkItem {
id: number
rev?: number
url?: string
fields?: Record<string, unknown>
}
/**
* Resolves the change-detection revision for a work item. ADO returns the
* revision as the top-level `rev` property on each batch item; `System.Rev` is
* not guaranteed to be echoed in the requested `fields`, so `rev` is the
* authoritative source. Falls back to the in-fields rev, then `System.ChangedDate`.
*/
function resolveWorkItemRev(raw: RawWorkItem, fields: Record<string, unknown>): string {
if (typeof raw.rev === 'number') return String(raw.rev)
const fieldRev = fields['System.Rev']
if (typeof fieldRev === 'number') return String(fieldRev)
const changed = fields['System.ChangedDate']
if (typeof changed === 'string' && changed) return changed
return '0'
}
/**
* Fetches the list of wikis in the configured project. Returns an empty list on
* 401/403/404 so a missing or inaccessible wiki feature degrades gracefully
* rather than aborting the sync.
*/
async function listWikis(
accessToken: string,
organization: string,
project: string,
retryOptions?: Parameters<typeof fetchWithRetry>[2],
syncContext?: Record<string, unknown>
): Promise<WikiV2[]> {
const url = `${ADO_BASE_URL}/${encodeURIComponent(organization)}/${encodeURIComponent(project)}/_apis/wiki/wikis?api-version=${WIKIS_LIST_API_VERSION}`
const response = await fetchWithRetry(
url,
{
method: 'GET',
headers: { Accept: 'application/json', Authorization: patAuthHeader(accessToken) },
},
retryOptions
)
if (!response.ok) {
if (response.status === 401 || response.status === 403 || response.status === 404) {
/**
* 401/403 mean the wikis still exist but this PAT cannot read them right
* now — flag the listing as incomplete so reconciliation does not delete
* previously synced wiki pages. A 404 means the wiki feature/content is
* genuinely absent, so reconciliation stays enabled.
*/
if ((response.status === 401 || response.status === 403) && syncContext) {
syncContext.listingCapped = true
}
logger.warn('Azure DevOps wikis unavailable; skipping wiki listing', {
organization,
project,
status: response.status,
})
return []
}
const errorText = await response.text().catch(() => '')
logger.error('Failed to list Azure DevOps wikis', { status: response.status, error: errorText })
throw new Error(`Failed to list wikis: ${response.status}`)
}
const data = await response.json()
return (data.value as WikiV2[] | undefined) ?? []
}
/**
* Resolves the wikis for the project, caching them on the sync context so a
* single sync (and its deferred getDocument calls) reuse one listing.
*/
async function resolveWikis(
accessToken: string,
organization: string,
project: string,
syncContext?: Record<string, unknown>
): Promise<WikiV2[]> {
const cached = syncContext?.wikis as WikiV2[] | undefined
if (cached) return cached
const wikis = await listWikis(accessToken, organization, project, undefined, syncContext)
if (syncContext) syncContext.wikis = wikis
return wikis
}
/**
* Returns true when the wiki should be included given an optional wiki filter
* (matched case-insensitively against the wiki id or name).
*/
function wikiMatchesFilter(wiki: WikiV2, filter: string): boolean {
if (!filter) return true
const needle = filter.toLowerCase()
return wiki.id.toLowerCase() === needle || (wiki.name ?? '').toLowerCase() === needle
}
/**
* Fetches the ETag for a single wiki page without downloading its content.
* The ETag changes whenever the page is edited, making it a reliable
* metadata-only change-detection hash for the deferred-content pattern.
*/
async function fetchWikiPageETag(
accessToken: string,
organization: string,
project: string,
wikiId: string,
pagePath: string
): Promise<string | null> {
const url = `${ADO_BASE_URL}/${encodeURIComponent(organization)}/${encodeURIComponent(project)}/_apis/wiki/wikis/${encodeURIComponent(wikiId)}/pages?path=${encodeURIComponent(pagePath)}&api-version=${WIKI_API_VERSION}`
const response = await fetchWithRetry(url, {
method: 'GET',
headers: { Accept: 'application/json', Authorization: patAuthHeader(accessToken) },
})
if (!response.ok) {
if (response.status === 404) return null
logger.warn('Failed to fetch wiki page ETag', { pagePath, status: response.status })
return null
}
const etag = response.headers.get('etag')
return etag ? etag.replace(/"/g, '') : null
}
/**
* Builds a wiki page stub. The contentHash is derived from the page ETag
* (falls back to the page id when no ETag is available), guaranteeing the
* hash is identical between listing and content fetch.
*/
function wikiPageToStub(
organization: string,
project: string,
wiki: WikiV2,
page: WikiPageDetail,
etag: string | null
): ExternalDocument {
const title = page.path.split('/').filter(Boolean).pop() || page.path || 'Untitled'
const sourceUrl = wiki.remoteUrl
? `${wiki.remoteUrl}?pagePath=${encodeURIComponent(page.path)}`
: undefined
return {
externalId: wikiPageExternalId(wiki.id, page.path),
title,
content: '',
contentDeferred: true,
mimeType: 'text/plain',
sourceUrl,
contentHash: `ado:wiki:${wiki.id}:${page.path}:${etag ?? page.id}`,
metadata: {
kind: 'wiki',
organization,
project,
wikiId: wiki.id,
wikiName: wiki.name,
pageId: page.id,
pagePath: page.path,
},
}
}
/**
* Builds a work item document. Work items are returned inline (not deferred)
* because the batch fetch already includes all field content. The contentHash
* uses the work item revision, which increments on every change. HTML-bearing
* fields (description, repro steps, acceptance criteria) are stripped to text.
*/
function workItemToDocument(
organization: string,
project: string,
raw: RawWorkItem
): ExternalDocument {
const fields = raw.fields ?? {}
const title = (fields['System.Title'] as string | undefined) ?? `Work Item ${raw.id}`
const workItemType = (fields['System.WorkItemType'] as string | undefined) ?? ''
const state = (fields['System.State'] as string | undefined) ?? ''
const rev = resolveWorkItemRev(raw, fields)
const changedDate = (fields['System.ChangedDate'] as string | undefined) ?? ''
const areaPath = (fields['System.AreaPath'] as string | undefined) ?? ''
const iterationPath = (fields['System.IterationPath'] as string | undefined) ?? ''
const rawTags = (fields['System.Tags'] as string | undefined) ?? ''
const tags = rawTags
.split(';')
.map((t) => t.trim())
.filter(Boolean)
const description = htmlToPlainText((fields['System.Description'] as string | undefined) ?? '')
const reproSteps = htmlToPlainText(
(fields['Microsoft.VSTS.TCM.ReproSteps'] as string | undefined) ?? ''
)
const acceptanceCriteria = htmlToPlainText(
(fields['Microsoft.VSTS.Common.AcceptanceCriteria'] as string | undefined) ?? ''
)
const contentParts: string[] = [`Title: ${title}`, `Type: ${workItemType}`, `State: ${state}`]
if (tags.length > 0) contentParts.push(`Tags: ${tags.join(', ')}`)
if (description) contentParts.push('', 'Description:', description)
if (reproSteps) contentParts.push('', 'Repro Steps:', reproSteps)
if (acceptanceCriteria) contentParts.push('', 'Acceptance Criteria:', acceptanceCriteria)
return {
externalId: workItemExternalId(raw.id),
title: `#${raw.id}: ${title}`,
content: contentParts.join('\n'),
contentDeferred: false,
mimeType: 'text/plain',
sourceUrl: `${ADO_BASE_URL}/${encodeURIComponent(organization)}/${encodeURIComponent(project)}/_workitems/edit/${raw.id}`,
contentHash: `ado:wi:${raw.id}:${rev}`,
metadata: {
kind: 'workitem',
organization,
project,
workItemId: raw.id,
workItemType,
state,
areaPath,
iterationPath,
tags,
changedDate,
rev,
},
}
}
/**
* Reads the work-item filter configuration from sourceConfig.
*/
interface WorkItemFilters {
workItemType: string
state: string
areaPath: string
tags: string[]
customWiql: string
}
function readWorkItemFilters(sourceConfig: Record<string, unknown>): WorkItemFilters {
const tagsRaw = readString(sourceConfig.workItemTags)
const tags = tagsRaw
? tagsRaw
.split(',')
.map((t) => t.trim())
.filter(Boolean)
: []
return {
workItemType: readString(sourceConfig.workItemType),
state: readString(sourceConfig.state),
areaPath: readString(sourceConfig.areaPath),
tags,
customWiql: readString(sourceConfig.customWiql),
}
}
/**
* Builds the WIQL query for the configured work-item filters. User-supplied
* values are escaped against WIQL string-literal injection. `lastSyncAt`
* narrows results to items changed since the previous sync, and `idAfter`
* restricts to items with a greater id (used to probe past the 20,000-item
* WIQL cap).
*
* A custom WIQL query is used verbatim: neither the incremental changed-date
* filter nor the probe condition can be injected into arbitrary user WIQL
* safely, so custom queries always run as full listings on every sync. Change
* detection still short-circuits unchanged items via the content hash.
*/
function buildWiql(filters: WorkItemFilters, lastSyncAt?: Date, idAfter?: number): string {
if (filters.customWiql) return filters.customWiql
const clauses: string[] = ['[System.TeamProject] = @project']
if (filters.workItemType) {
clauses.push(`[System.WorkItemType] = '${escapeWiql(filters.workItemType)}'`)
}
if (filters.state) {
clauses.push(`[System.State] = '${escapeWiql(filters.state)}'`)
}
if (filters.areaPath) {
clauses.push(`[System.AreaPath] UNDER '${escapeWiql(filters.areaPath)}'`)
}
for (const tag of filters.tags) {
clauses.push(`[System.Tags] CONTAINS '${escapeWiql(tag)}'`)
}
if (lastSyncAt) {
clauses.push(`[System.ChangedDate] >= '${lastSyncAt.toISOString()}'`)
}
if (idAfter !== undefined) {
clauses.push(`[System.Id] > ${idAfter}`)
}
return `SELECT [System.Id] FROM workitems WHERE ${clauses.join(' AND ')} ORDER BY [System.ChangedDate] DESC`
}
/**
* Runs a WIQL query for work items in the project and returns their IDs.
* WIQL itself is not paginated and returns at most 20,000 ids; pagination
* happens over the resulting ID list via the workitemsbatch endpoint.
*/
async function queryWorkItemIds(
accessToken: string,
organization: string,
project: string,
wiql: string,
top: number = WIQL_MAX_RESULTS
): Promise<number[]> {
const url = `${ADO_BASE_URL}/${encodeURIComponent(organization)}/${encodeURIComponent(project)}/_apis/wit/wiql?$top=${top}&api-version=${WIQL_API_VERSION}`
const response = await fetchWithRetry(url, {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
Authorization: patAuthHeader(accessToken),
},
body: JSON.stringify({ query: wiql }),
})
if (!response.ok) {
const errorText = await response.text().catch(() => '')
logger.error('Failed to query Azure DevOps work items', {
status: response.status,
error: errorText,
})
throw new Error(`Failed to query work items: ${response.status}`)
}
const data = await response.json()
const refs = (data.workItems as WorkItemRef[] | undefined) ?? []
if (refs.length >= WIQL_MAX_RESULTS) {
logger.warn('WIQL result hit the 20,000-item cap; narrow work-item filters to sync all items', {
organization,
project,
})
}
return refs.map((ref) => ref.id)
}
/**
* Fetches full field details for a batch of work item IDs (max 200 per call).
* `errorPolicy: 'Omit'` keeps the batch resilient: a single inaccessible or
* deleted id is dropped from the response rather than failing the whole call.
*/
async function fetchWorkItemsBatch(
accessToken: string,
organization: string,
project: string,
ids: number[]
): Promise<RawWorkItem[]> {
if (ids.length === 0) return []
const url = `${ADO_BASE_URL}/${encodeURIComponent(organization)}/${encodeURIComponent(project)}/_apis/wit/workitemsbatch?api-version=${WORKITEMS_API_VERSION}`
const response = await fetchWithRetry(url, {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
Authorization: patAuthHeader(accessToken),
},
body: JSON.stringify({
ids,
errorPolicy: 'Omit',
fields: [
'System.Id',
'System.Title',
'System.WorkItemType',
'System.State',
'System.AreaPath',
'System.IterationPath',
'System.ChangedDate',
'System.Tags',
'System.Description',
'Microsoft.VSTS.TCM.ReproSteps',
'Microsoft.VSTS.Common.AcceptanceCriteria',
],
}),
})
if (!response.ok) {
const errorText = await response.text().catch(() => '')
logger.error('Failed to fetch Azure DevOps work items batch', {
status: response.status,
error: errorText,
})
throw new Error(`Failed to fetch work items batch: ${response.status}`)
}
const data = await response.json()
return (data.value as RawWorkItem[] | undefined) ?? []
}
/**
* Reads the repository-file filter configuration from sourceConfig.
*/
interface FileFilters {
repositoryName: string
branch: string
pathPrefix: string
extensions: Set<string> | null
}
function readFileFilters(sourceConfig: Record<string, unknown>): FileFilters {
const rawPrefix = readString(sourceConfig.pathPrefix)
return {
repositoryName: readString(sourceConfig.repositoryName),
branch: readString(sourceConfig.branch),
pathPrefix: rawPrefix,
extensions: parseExtensions(sourceConfig.fileExtensions),
}
}
/**
* Lists the project's git repositories. Returns an empty list on 401/403/404 so
* a project without Git or without repo access degrades gracefully instead of
* aborting the sync.
*/
async function listRepositories(
accessToken: string,
organization: string,
project: string,
retryOptions?: Parameters<typeof fetchWithRetry>[2],
syncContext?: Record<string, unknown>
): Promise<GitRepository[]> {
const url = `${ADO_BASE_URL}/${encodeURIComponent(organization)}/${encodeURIComponent(project)}/_apis/git/repositories?api-version=${GIT_API_VERSION}`
const response = await fetchWithRetry(
url,
{
method: 'GET',
headers: { Accept: 'application/json', Authorization: patAuthHeader(accessToken) },
},
retryOptions
)
if (!response.ok) {
if (response.status === 401 || response.status === 403 || response.status === 404) {
/**
* 401/403 mean repositories still exist but this PAT cannot read them
* right now — flag the listing as incomplete so reconciliation does not
* delete previously synced repository files. A 404 means the Git feature
* is genuinely absent, so reconciliation stays enabled.
*/
if ((response.status === 401 || response.status === 403) && syncContext) {
syncContext.listingCapped = true
}
logger.warn('Azure DevOps repositories unavailable; skipping file listing', {
organization,
project,
status: response.status,
})
return []
}
const errorText = await response.text().catch(() => '')
logger.error('Failed to list Azure DevOps repositories', {
status: response.status,
error: errorText,
})
throw new Error(`Failed to list repositories: ${response.status}`)
}
const data = await response.json()
return (data.value as GitRepository[] | undefined) ?? []
}
/**
* Resolves the in-scope repositories for the project, caching them on the sync
* context so a single sync reuses one listing. Disabled repositories and, when a
* filter is set, non-matching repositories are excluded.
*/
async function resolveRepositories(
accessToken: string,
organization: string,
project: string,
repositoryFilter: string,
syncContext?: Record<string, unknown>
): Promise<GitRepository[]> {
const cached = syncContext?.repositories as GitRepository[] | undefined
const all =
cached ?? (await listRepositories(accessToken, organization, project, undefined, syncContext))
if (syncContext && !cached) syncContext.repositories = all
const needle = repositoryFilter.toLowerCase()
return all.filter((repo) => {
if (repo.isDisabled) return false
if (!needle) return true
return repo.id.toLowerCase() === needle || (repo.name ?? '').toLowerCase() === needle
})
}
/**
* Lists every blob in a repository at the given branch via the non-paginated
* Items list API (recursionLevel=Full). Returns an empty list on 401/403/404 so
* a single inaccessible or empty repo does not abort the sync.
*/
async function listRepositoryBlobs(
accessToken: string,
organization: string,
project: string,
repoId: string,
branch: string,
syncContext?: Record<string, unknown>
): Promise<GitItem[]> {
const params = new URLSearchParams({
recursionLevel: 'Full',
'versionDescriptor.version': branch,
'versionDescriptor.versionType': 'Branch',
'api-version': GIT_API_VERSION,
})
const url = `${ADO_BASE_URL}/${encodeURIComponent(organization)}/${encodeURIComponent(project)}/_apis/git/repositories/${encodeURIComponent(repoId)}/items?${params.toString()}`
const response = await fetchWithRetry(url, {
method: 'GET',
headers: { Accept: 'application/json', Authorization: patAuthHeader(accessToken) },
})
if (!response.ok) {
if (response.status === 401 || response.status === 403 || response.status === 404) {
/**
* 401/403 mean the repository's files still exist but this PAT cannot
* read them right now — flag the listing as incomplete so reconciliation
* does not delete previously synced files. A 404 means the branch/repo
* content is genuinely absent (empty repo, deleted branch), so
* reconciliation stays enabled.
*/
if ((response.status === 401 || response.status === 403) && syncContext) {
syncContext.listingCapped = true
}
logger.warn('Azure DevOps repository items unavailable; skipping repository', {
repoId,
branch,
status: response.status,
})
return []
}
const errorText = await response.text().catch(() => '')
logger.error('Failed to list Azure DevOps repository items', {
repoId,
branch,
status: response.status,
error: errorText,
})
throw new Error(`Failed to list repository items: ${response.status}`)
}
/**
* The Items list API documents no pagination, but very large trees may emit
* an `x-ms-continuationtoken` response header. No request parameter exists
* to follow it, so when it appears the tree is treated as incomplete: the
* listing is flagged so deletion reconciliation cannot remove files that
* were never returned.
*/
if (response.headers.get('x-ms-continuationtoken')) {
if (syncContext) syncContext.listingCapped = true
logger.warn(
'Azure DevOps repository tree listing returned a continuation token; partial tree',
{
repoId,
branch,
}
)
}
const data = await response.json()
const items = (data.value as GitItem[] | undefined) ?? []
return items.filter((item) => item.gitObjectType === 'blob' && !item.isFolder && item.path)
}
/**
* Builds the web UI URL for a repository file at a given branch. Azure DevOps
* file links use `{repoWebUrl}?path={path}&version=GB{branch}` (GB = Git Branch).
*/
function buildFileSourceUrl(
repoWebUrl: string | undefined,
branch: string,
path: string
): string | undefined {
if (!repoWebUrl) return undefined
return `${repoWebUrl}?path=${encodeURIComponent(path)}&version=GB${encodeURIComponent(branch)}`
}
/**
* Builds a deferred stub for a repository file. Content is empty and fetched
* lazily via getDocument for new/changed files only. The contentHash is the git
* blob objectId, identical between the stub and the hydrated document.
*/
function fileToStub(organization: string, project: string, entry: RepoFileEntry): ExternalDocument {
const path = entry.item.path
const title = path.split('/').filter(Boolean).pop() || path
return {
externalId: fileExternalId(entry.repoId, path),
title,
content: '',
contentDeferred: true,
mimeType: 'text/plain',
sourceUrl: buildFileSourceUrl(entry.repoWebUrl, entry.branch, path),
contentHash: buildFileContentHash(entry.repoId, entry.item.objectId),
metadata: {
kind: 'file',
organization,
project,
repository: entry.repoName,
repositoryId: entry.repoId,
branch: entry.branch,
path,
},
}
}
/**
* Resolves the flattened, filtered list of repository files for the configured
* scope. Repositories are listed once, each is walked via the recursive Items
* API, and blobs are filtered by path prefix and extension. The result is cached
* on syncContext so offset-based pagination and the maxItems cap apply over a
* stable list across pages.
*/
async function resolveRepoFiles(
accessToken: string,
organization: string,
project: string,
filters: FileFilters,
syncContext?: Record<string, unknown>
): Promise<RepoFileEntry[]> {
const cached = syncContext?.repoFiles as RepoFileEntry[] | undefined
if (cached) return cached
const repositories = await resolveRepositories(
accessToken,
organization,
project,
filters.repositoryName,
syncContext
)
const normalizedPrefix =
filters.pathPrefix && !filters.pathPrefix.startsWith('/')
? `/${filters.pathPrefix}`
: filters.pathPrefix
const entries: RepoFileEntry[] = []
for (const repo of repositories) {
const branch = filters.branch || stripRefsHeads(repo.defaultBranch ?? '')
if (!branch) {
/**
* No branch override and no resolvable default branch. An empty
* repository (size 0) has nothing to list and nothing previously synced,
* so it is skipped without flagging — flagging here would permanently
* suppress deletion reconciliation for any project containing an empty
* repo. A non-empty repository reaching this branch means content exists
* but its default branch ref is missing/unreadable, so the listing is
* flagged incomplete to protect previously synced files from
* reconciliation deletion.
*/
if ((repo.size ?? 0) > 0 && syncContext) {
syncContext.listingCapped = true
}
logger.warn('Skipping Azure DevOps repository with no default branch', {
repoId: repo.id,
repoName: repo.name,
size: repo.size ?? 0,
})
continue
}
const blobs = await listRepositoryBlobs(
accessToken,
organization,
project,
repo.id,
branch,
syncContext
)
for (const item of blobs) {
if (normalizedPrefix && !item.path.startsWith(normalizedPrefix)) continue
if (!matchesExtension(item.path, filters.extensions)) continue
entries.push({
repoId: repo.id,
repoName: repo.name,
repoWebUrl: repo.webUrl,
branch,
item,
})
}
}
if (syncContext) syncContext.repoFiles = entries
return entries
}
/**
* Lists a single batch of repository-file stubs. The full filtered file list is
* resolved once and cached on syncContext; the cursor is an offset into that
* list, of the form `file|{offset}`.
*/
async function listRepoFiles(
accessToken: string,
organization: string,
project: string,
filters: FileFilters,
maxItems: number,
cursor: string | undefined,
syncContext: Record<string, unknown> | undefined
): Promise<ExternalDocumentList> {
const entries = await resolveRepoFiles(accessToken, organization, project, filters, syncContext)
if (entries.length === 0) {
return { documents: [], hasMore: false }
}
let offset = 0
if (cursor) {
const parts = cursor.split('|')
offset = Number(parts[1]) || 0
}
const chunk = entries.slice(offset, offset + FILE_BATCH_SIZE)
const documents = chunk.map((entry) => fileToStub(organization, project, entry))
const nextOffset = offset + FILE_BATCH_SIZE
const { documents: capped, capped: hitLimit } = applyMaxItemsCap(
documents,
maxItems,
syncContext,
nextOffset < entries.length
)
const hasMore = !hitLimit && nextOffset < entries.length
return {
documents: capped,
nextCursor: hasMore ? `file|${nextOffset}` : undefined,
hasMore,
}
}
/**
* Resolves the branch to fetch a single repository file from in getDocument. Uses
* the configured branch override when set, otherwise the repository's default
* branch (resolved from the cached or freshly-listed repository record).
*/
async function resolveFileBranch(
accessToken: string,
organization: string,