@githits/mcp 0.26.0 → 0.27.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +16 -0
- package/dist/client.d.ts +136 -28
- package/dist/client.js +1 -1
- package/dist/index.d.ts +117 -28
- package/dist/index.js +38 -35
- package/dist/shared/chunk-4gcqyg9g.js +1528 -0
- package/dist/shared/chunk-54c4zdmn.js +352 -0
- package/dist/shared/chunk-78y1gbky.js +24 -0
- package/dist/smoke-test.d.ts +5 -2
- package/dist/smoke-test.js +5 -4
- package/dist/tools.d.ts +110 -5
- package/dist/tools.js +1 -1
- package/package.json +1 -1
- package/dist/shared/chunk-fy8ypkev.js +0 -16
- package/dist/shared/chunk-vhhae3y9.js +0 -2
- package/dist/shared/chunk-yxxmv1b1.js +0 -1778
|
@@ -0,0 +1,352 @@
|
|
|
1
|
+
import{ClientUpdateRequiredError,isClientUpdateRequiredGraphQLError,isGraphQLSchemaMismatchError,parseAvailableArtifacts,DEFAULT_FETCH_TIMEOUT_MS,isFetchTimeoutError,parseHttpErrorDetail,PkgseerTransportError,postPkgseerGraphql,SERVER_AUTHENTICATION_REJECTED_MESSAGE,AuthenticationError2,withServiceDiagnostics,isTokenRefreshableError,GitHitsServiceImpl2,executeWithTokenRefresh,INDEXING_DURATION_ESTIMATE_SELECTION,INDEXING_ESTIMATES_SELECTION,indexingEstimatesSchema,parseIndexingDurationEstimate,READ_TARGET_SELECTION,selectedReadTargetSchema,CodeNavigationAccessError,MalformedCodeNavigationResponseError,CodeNavigationNetworkError,CodeNavigationBackendError,TARGET_RESOLUTION_SELECTION,CODE_CONTEXT_AVAILABLE_VERSIONS_SELECTION,createCodeNavigationHttpError,createCodeNavigationGraphQLError,parseCodeContextResult,MalformedPackageIntelligenceResponseError,parsePackageDocResult,createPackageIntelligenceHttpError,createPackageIntelligenceTransportError,createPackageIntelligenceGraphQLError}from"./chunk-4gcqyg9g.js";import{z}from"zod";class GrepGraphQLError2 extends Error{extensions;constructor(message,extensions={}){super(message);this.extensions=extensions;this.name="GrepGraphQLError"}}class GrepBackendError2 extends Error{status;graphqlCode;retryable;constructor(message,status,graphqlCode,retryable){super(message);this.status=status;this.graphqlCode=graphqlCode;this.retryable=retryable;this.name="GrepBackendError"}}class GrepAccessError2 extends Error{constructor(message){super(message);this.name="GrepAccessError"}}class GrepNetworkError2 extends Error{constructor(message,options){super(message,options);this.name="GrepNetworkError"}}class MalformedGrepResponseError2 extends Error{constructor(){super("Malformed response from the grep service.");this.name="MalformedGrepResponseError"}}var traversal=z.enum(["COMPLETE","RESUMABLE_LIMIT","NON_RESUMABLE_PARTIAL","FAILED","CURSOR_EXPIRED"]);var corpus=z.enum(["SOURCE","DOCUMENTATION","ALL"]);var nonnegativeInt=z.number().int().nonnegative();var nullableString=z.string().nullable();var lineSlice=z.object({content:z.string(),startByte:nonnegativeInt,endByte:nonnegativeInt,originalLineBytes:nonnegativeInt});var readAction=z.object({target:z.string(),path:nullableString,startLine:z.number().int().positive(),endLine:z.number().int().positive()});var modifications=z.array(z.enum(["INVISIBLE_CONTROLS_STRIPPED","HTML_COMMENTS_STRIPPED","IMAGES_REPLACED","UNSAFE_LINKS_NEUTRALIZED"]));function resultSchema(detailed){const selected=(schema)=>detailed?schema:schema.optional();const safety=z.object({filtered:z.boolean(),modifications:selected(modifications)});const common={targetIndex:nonnegativeInt,line:z.number().int().positive(),lineSlice,contextBeforeSlices:z.array(lineSlice),contextAfterSlices:z.array(lineSlice),read:readAction,contentSafety:safety,lineContent:selected(z.string()),matchStartByte:nonnegativeInt,matchEndByte:nonnegativeInt,sourceMatchStartByte:selected(nonnegativeInt),sourceMatchEndByte:selected(nonnegativeInt)};return z.object({indexingEstimates:indexingEstimatesSchema,hits:z.array(z.discriminatedUnion("__typename",[z.object({...common,__typename:z.literal("GrepRepositoryHit"),read:readAction.extend({path:z.string()}),filePath:z.string(),repoUrl:selected(z.string()),commitSha:selected(z.string()),repositoryFilePath:selected(z.string())}),z.object({...common,__typename:z.literal("GrepSiteHit"),read:readAction.extend({path:z.null()}),pageUrl:z.string()})])),targets:z.array(z.object({targetIndex:nonnegativeInt,requestedInputIndices:z.array(nonnegativeInt),kind:z.enum(["REPOSITORY","SITE"]),target:z.string(),traversal,readiness:z.enum(["UNSPECIFIED","CURRENT","STALE","NOT_AVAILABLE","MISSING_REF","READER_OPEN_FAILED","INCOMPLETE","RESOURCE_LIMIT","VERSION_UNSUPPORTED","READ_FAILED"]),errorCode:nullableString,retryable:z.boolean(),publicMessage:nullableString,requestedRef:nullableString,commitSha:nullableString,corpus:corpus.nullable(),filesScanned:nonnegativeInt.nullable(),filesInScope:nonnegativeInt.nullable(),binaryFilesSkipped:nonnegativeInt.nullable(),filesTooLargeSkipped:nonnegativeInt.nullable(),fileIssuesOmitted:nonnegativeInt.nullable(),fileIssues:z.array(z.object({filePath:z.string(),contentSafety:safety,code:z.string(),line:nonnegativeInt,lineBytes:selected(nonnegativeInt),matchStartByte:selected(nonnegativeInt.nullable()),matchEndByte:selected(nonnegativeInt.nullable())})).nullable(),repoUrl:nullableString,canonicalSite:nullableString,urlPrefixes:selected(z.array(z.string()))})),unavailableTargets:z.array(z.object({inputIndex:nonnegativeInt,target:z.string(),reason:z.string(),retryable:z.boolean(),progressRef:nullableString,suggestedSiteTargets:z.array(z.string()).nullable()})),traversal,nextCursor:nullableString,totalMatches:nonnegativeInt})}function parseGrepResult(value,detailed=false){const parsed=resultSchema(detailed).safeParse(value);if(!parsed.success)throw new MalformedGrepResponseError2;const result=parsed.data;const indices=new Set(result.targets.map((target)=>target.targetIndex));if(indices.size!==result.targets.length||result.hits.some((hit)=>!indices.has(hit.targetIndex)||!validMatchCoordinates(hit))||result.traversal==="RESUMABLE_LIMIT"&&!result.nextCursor)throw new MalformedGrepResponseError2;return result}function validMatchCoordinates(hit){const bytes=new TextEncoder().encode(hit.lineSlice.content);const{matchStartByte:start,matchEndByte:end}=hit;const boundary=(offset)=>offset===bytes.length||((bytes[offset]??0)&192)!==128;return start<=end&&end<=bytes.length&&boundary(start)&&boundary(end)}var GRAPHQL_QUERY=`query Grep(
|
|
2
|
+
$targets: [GrepTargetInput!]!, $pattern: String!, $patternType: GrepPatternType,
|
|
3
|
+
$caseSensitive: Boolean, $contextLinesBefore: Int, $contextLinesAfter: Int,
|
|
4
|
+
$maxMatches: Int, $cursor: String, $waitTimeoutMs: Int, $includeDetailedFields: Boolean!
|
|
5
|
+
) {
|
|
6
|
+
grep(targets: $targets, pattern: $pattern, patternType: $patternType,
|
|
7
|
+
caseSensitive: $caseSensitive, contextLinesBefore: $contextLinesBefore,
|
|
8
|
+
contextLinesAfter: $contextLinesAfter, maxMatches: $maxMatches,
|
|
9
|
+
cursor: $cursor, waitTimeoutMs: $waitTimeoutMs) {
|
|
10
|
+
traversal nextCursor totalMatches
|
|
11
|
+
${INDEXING_ESTIMATES_SELECTION}
|
|
12
|
+
hits {
|
|
13
|
+
__typename
|
|
14
|
+
... on GrepRepositoryHit {
|
|
15
|
+
filePath
|
|
16
|
+
repoUrl @include(if: $includeDetailedFields)
|
|
17
|
+
commitSha @include(if: $includeDetailedFields)
|
|
18
|
+
repositoryFilePath @include(if: $includeDetailedFields)
|
|
19
|
+
...RepositoryMatch
|
|
20
|
+
}
|
|
21
|
+
... on GrepSiteHit { pageUrl ...SiteMatch }
|
|
22
|
+
}
|
|
23
|
+
targets {
|
|
24
|
+
targetIndex requestedInputIndices kind target traversal readiness errorCode retryable publicMessage
|
|
25
|
+
requestedRef commitSha corpus filesScanned filesInScope binaryFilesSkipped filesTooLargeSkipped fileIssuesOmitted
|
|
26
|
+
repoUrl canonicalSite
|
|
27
|
+
urlPrefixes @include(if: $includeDetailedFields)
|
|
28
|
+
fileIssues {
|
|
29
|
+
filePath code line contentSafety { filtered modifications @include(if: $includeDetailedFields) }
|
|
30
|
+
lineBytes @include(if: $includeDetailedFields)
|
|
31
|
+
matchStartByte @include(if: $includeDetailedFields)
|
|
32
|
+
matchEndByte @include(if: $includeDetailedFields)
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
unavailableTargets { inputIndex target reason retryable progressRef suggestedSiteTargets }
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
fragment RepositoryMatch on GrepRepositoryHit {
|
|
39
|
+
targetIndex line lineSlice { ...LineSlice } contextBeforeSlices { ...LineSlice } contextAfterSlices { ...LineSlice }
|
|
40
|
+
read: readTarget { target path startLine endLine } contentSafety { filtered modifications @include(if: $includeDetailedFields) }
|
|
41
|
+
lineContent @include(if: $includeDetailedFields)
|
|
42
|
+
matchStartByte matchEndByte
|
|
43
|
+
sourceMatchStartByte @include(if: $includeDetailedFields) sourceMatchEndByte @include(if: $includeDetailedFields)
|
|
44
|
+
}
|
|
45
|
+
fragment SiteMatch on GrepSiteHit {
|
|
46
|
+
targetIndex line lineSlice { ...LineSlice } contextBeforeSlices { ...LineSlice } contextAfterSlices { ...LineSlice }
|
|
47
|
+
read: readTarget { target path startLine endLine } contentSafety { filtered modifications @include(if: $includeDetailedFields) }
|
|
48
|
+
lineContent @include(if: $includeDetailedFields)
|
|
49
|
+
matchStartByte matchEndByte
|
|
50
|
+
sourceMatchStartByte @include(if: $includeDetailedFields) sourceMatchEndByte @include(if: $includeDetailedFields)
|
|
51
|
+
}
|
|
52
|
+
fragment LineSlice on GrepRepoLineSlice { content startByte endByte originalLineBytes }`;var graphQLResponse=z.object({data:z.object({grep:z.unknown().optional()}).nullable().optional(),errors:z.array(z.object({message:z.string(),extensions:z.record(z.string(),z.unknown()).optional()})).optional()});class GrepServiceImpl2{endpointUrl;tokenProvider;fetchFn;runtime;constructor(endpointUrl,tokenProvider,fetchFn=globalThis.fetch,runtime={}){this.endpointUrl=endpointUrl;this.tokenProvider=tokenProvider;this.fetchFn=fetchFn;this.runtime=runtime}async grep(params){return withServiceDiagnostics(this.runtime.diagnostics,"grep.request",()=>executeWithTokenRefresh({getToken:()=>this.tokenProvider.getToken(),forceRefresh:()=>this.tokenProvider.forceRefresh(),shouldRefresh:isTokenRefreshableError,executeWithToken:(token)=>this.executeGrep(token,params)}))}async executeGrep(token,params){let response;const{includeDetailedFields,...controls}=params;try{response=await postPkgseerGraphql({endpointUrl:this.endpointUrl,token,query:GRAPHQL_QUERY,variables:{...controls,includeDetailedFields},timeoutMs:Math.max(DEFAULT_FETCH_TIMEOUT_MS,(params.waitTimeoutMs??0)+30000),fetchFn:this.fetchFn,clientHeaders:this.runtime.clientHeaders,userAgent:this.runtime.userAgent,diagnostics:this.runtime.diagnostics})}catch(cause){if(!(cause instanceof PkgseerTransportError))throw cause;if(isFetchTimeoutError(cause.cause))throw new GrepBackendError2("Grep request timed out.",undefined,"TIMEOUT",true);throw new GrepNetworkError2("Could not reach the package and documentation service. Check your connection.",{cause})}if(response.status<200||response.status>=300)throw httpError(response);const envelope=graphQLResponse.safeParse(response.parsedBody);if(!envelope.success)throw new MalformedGrepResponseError2;const errors=envelope.data.errors;if(errors?.length){const message=errors.map((error)=>error.message).join(", ");const extensions=errors.find((error)=>error.extensions?.code)?.extensions??{};const code=typeof extensions.code==="string"?extensions.code:undefined;if(isClientUpdateRequiredGraphQLError({message,code}))throw new ClientUpdateRequiredError(undefined,undefined,this.runtime.clientVersion);if(isGraphQLSchemaMismatchError({message,code}))throw new GrepBackendError2("Backend protocol mismatch: the endpoint must support unified grep. Run `githits update-check` to check your client version.",undefined,code,false);if(code==="AUTHENTICATION_REQUIRED"||code==="UNAUTHORIZED")throw new AuthenticationError2(SERVER_AUTHENTICATION_REJECTED_MESSAGE,"server");if(code==="FORBIDDEN"||code==="ACCESS_DENIED")throw new GrepAccessError2(message);throw new GrepGraphQLError2(message,extensions)}return parseGrepResult(envelope.data.data?.grep,includeDetailedFields)}}function httpError(response){const detail=parseHttpErrorDetail(response.responseBody,["message","error","detail"]);if(response.status===401)return new AuthenticationError2(SERVER_AUTHENTICATION_REJECTED_MESSAGE,"server");if(response.status===403)return new GrepAccessError2(detail??"Grep access denied.");return new GrepBackendError2(detail??`Request failed with status ${response.status}`,response.status)}import{z as z2}from"zod";class ListAccessError2 extends Error{constructor(message){super(message);this.name="ListAccessError"}}class ListGraphQLError2 extends Error{code;retryable;repoUrl;commitSha;indexingRef;hint;indexingMetadata;constructor(message,code,retryable,repoUrl,commitSha,indexingRef,hint,indexingMetadata=undefined){super(message);this.code=code;this.retryable=retryable;this.repoUrl=repoUrl;this.commitSha=commitSha;this.indexingRef=indexingRef;this.hint=hint;this.indexingMetadata=indexingMetadata;this.name="ListGraphQLError"}}class ListBackendError2 extends Error{status;graphqlCode;retryable;constructor(message,status,graphqlCode,retryable){super(message);this.status=status;this.graphqlCode=graphqlCode;this.retryable=retryable;this.name="ListBackendError"}}class ListNetworkError2 extends Error{constructor(message,options){super(message,options);this.name="ListNetworkError"}}class MalformedListResponseError2 extends Error{constructor(message="Malformed response from the list service."){super(message);this.name="MalformedListResponseError"}}var nullableString2=z2.string().nullable();var optionalNullableString=nullableString2.optional();var nullableInt=z2.number().int().nullable();var optionalNullableInt=nullableInt.optional();var listReadActionSchema=z2.object({target:z2.string().min(1),path:nullableString2}).nullable();var listBrowseActionSchema=z2.object({target:z2.string(),paths:z2.array(z2.string()).nullable()}).nullable();var listEntrySchema=z2.object({kind:z2.enum(["FILE","PAGE","DIRECTORY"]),path:z2.string(),title:optionalNullableString,language:optionalNullableString,fileType:optionalNullableString,intent:optionalNullableString,byteSize:optionalNullableInt,lineCount:optionalNullableInt,contentHash:optionalNullableString,read:listReadActionSchema.optional(),browse:listBrowseActionSchema.optional()});var availableVersionSchema=z2.object({version:nullableString2,ref:z2.string()});var resolutionSchema=z2.object({requestedVersion:nullableString2,requestedRef:nullableString2,resolvedRef:nullableString2,commitSha:nullableString2});var targetIdentitySchema=z2.object({kind:optionalNullableString,registry:optionalNullableString,packageName:optionalNullableString,version:optionalNullableString,repoUrl:optionalNullableString,gitRef:nullableString2,commitSha:optionalNullableString,committedAt:optionalNullableString});var targetResolutionSchema=z2.object({requested:targetIdentitySchema.nullable(),resolvedRequested:targetIdentitySchema.nullable(),served:targetIdentitySchema.nullable(),freshness:nullableString2,freshnessReason:nullableString2,indexingRef:optionalNullableString,availableVersions:z2.array(availableVersionSchema).nullable().optional(),availableRefs:z2.array(availableVersionSchema).nullable().optional(),suggestedRefs:z2.array(availableVersionSchema).nullable().optional()});var indexingEstimateSchema=z2.object({lowerSeconds:nullableInt,upperSeconds:nullableInt,elapsedSeconds:nullableInt,sampleCount:nullableInt,source:nullableString2});var sitePreparationSchema=z2.object({selected:z2.number().int(),enqueued:z2.number().int(),activeJobs:z2.array(z2.object({mode:nullableString2,state:z2.string()})),awaited:z2.array(z2.object({mode:nullableString2,outcome:z2.enum(["COMPLETED","DISCARDED","CANCELLED","TIMEOUT","FAILED","SUPERSEDED"])}))}).nullable();var listResultSchema=z2.object({indexingEstimates:indexingEstimatesSchema,inventoryKind:z2.enum(["SOURCE","SITE"]),requestedTarget:z2.string(),canonicalTarget:nullableString2,entries:z2.array(listEntrySchema),hasMore:z2.boolean(),nextCursor:nullableString2,indexedVersion:nullableString2,resolution:resolutionSchema.nullable().optional(),targetResolution:targetResolutionSchema.nullable().optional(),codeIndexState:nullableString2,indexingStatus:nullableString2,indexingRef:nullableString2,availableVersions:z2.array(availableVersionSchema).nullable().optional(),indexingEstimate:indexingEstimateSchema.nullable().optional(),inventoryState:z2.enum(["AVAILABLE","EMPTY"]).nullable(),crawlStatus:z2.enum(["IDLE","RUNNING","COMPLETE","FAILED"]).nullable(),coverageState:z2.enum(["NONE","PARTIAL","CAPPED","COMPLETE"]).nullable(),coverageReason:nullableString2,preparation:sitePreparationSchema});var graphQLErrorSchema=z2.object({message:z2.string(),extensions:z2.record(z2.string(),z2.unknown()).optional()});var listGraphQLResponseSchema=z2.object({data:z2.object({list:z2.unknown().nullable().optional()}).nullable().optional(),errors:z2.array(graphQLErrorSchema).optional()});var LIST_QUERY=`
|
|
53
|
+
query List(
|
|
54
|
+
$target: String!
|
|
55
|
+
$paths: [String!]
|
|
56
|
+
$recursive: Boolean
|
|
57
|
+
$fileTypes: [String!]
|
|
58
|
+
$languages: [String!]
|
|
59
|
+
$intents: [FileIntent!]
|
|
60
|
+
$limit: Int
|
|
61
|
+
$after: String
|
|
62
|
+
$waitTimeoutMs: Int
|
|
63
|
+
$includeDetailedFields: Boolean!
|
|
64
|
+
$includeTargetProvenance: Boolean!
|
|
65
|
+
$includeReadActions: Boolean!
|
|
66
|
+
) {
|
|
67
|
+
list(
|
|
68
|
+
target: $target
|
|
69
|
+
paths: $paths
|
|
70
|
+
recursive: $recursive
|
|
71
|
+
fileTypes: $fileTypes
|
|
72
|
+
languages: $languages
|
|
73
|
+
intents: $intents
|
|
74
|
+
limit: $limit
|
|
75
|
+
after: $after
|
|
76
|
+
waitTimeoutMs: $waitTimeoutMs
|
|
77
|
+
) {
|
|
78
|
+
inventoryKind
|
|
79
|
+
${INDEXING_ESTIMATES_SELECTION}
|
|
80
|
+
requestedTarget
|
|
81
|
+
canonicalTarget
|
|
82
|
+
entries {
|
|
83
|
+
kind
|
|
84
|
+
path
|
|
85
|
+
title @include(if: $includeDetailedFields)
|
|
86
|
+
language @include(if: $includeDetailedFields)
|
|
87
|
+
fileType @include(if: $includeDetailedFields)
|
|
88
|
+
intent @include(if: $includeDetailedFields)
|
|
89
|
+
byteSize @include(if: $includeDetailedFields)
|
|
90
|
+
lineCount @include(if: $includeDetailedFields)
|
|
91
|
+
contentHash @include(if: $includeDetailedFields)
|
|
92
|
+
read: readTarget @include(if: $includeReadActions) {
|
|
93
|
+
target
|
|
94
|
+
path
|
|
95
|
+
}
|
|
96
|
+
browse @include(if: $includeDetailedFields) {
|
|
97
|
+
target
|
|
98
|
+
paths
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
hasMore
|
|
102
|
+
nextCursor
|
|
103
|
+
indexedVersion
|
|
104
|
+
resolution @include(if: $includeDetailedFields) {
|
|
105
|
+
requestedVersion
|
|
106
|
+
requestedRef
|
|
107
|
+
resolvedRef
|
|
108
|
+
commitSha
|
|
109
|
+
}
|
|
110
|
+
targetResolution @include(if: $includeTargetProvenance) {
|
|
111
|
+
requested {
|
|
112
|
+
kind
|
|
113
|
+
gitRef
|
|
114
|
+
registry
|
|
115
|
+
packageName
|
|
116
|
+
version
|
|
117
|
+
repoUrl
|
|
118
|
+
commitSha @include(if: $includeDetailedFields)
|
|
119
|
+
}
|
|
120
|
+
resolvedRequested {
|
|
121
|
+
repoUrl
|
|
122
|
+
gitRef
|
|
123
|
+
commitSha
|
|
124
|
+
committedAt
|
|
125
|
+
kind @include(if: $includeDetailedFields)
|
|
126
|
+
registry @include(if: $includeDetailedFields)
|
|
127
|
+
packageName @include(if: $includeDetailedFields)
|
|
128
|
+
version @include(if: $includeDetailedFields)
|
|
129
|
+
}
|
|
130
|
+
served {
|
|
131
|
+
repoUrl
|
|
132
|
+
gitRef
|
|
133
|
+
commitSha
|
|
134
|
+
committedAt
|
|
135
|
+
kind @include(if: $includeDetailedFields)
|
|
136
|
+
registry @include(if: $includeDetailedFields)
|
|
137
|
+
packageName @include(if: $includeDetailedFields)
|
|
138
|
+
version @include(if: $includeDetailedFields)
|
|
139
|
+
}
|
|
140
|
+
freshness
|
|
141
|
+
freshnessReason
|
|
142
|
+
indexingRef @include(if: $includeDetailedFields)
|
|
143
|
+
availableVersions @include(if: $includeDetailedFields) {
|
|
144
|
+
version
|
|
145
|
+
ref
|
|
146
|
+
}
|
|
147
|
+
availableRefs @include(if: $includeDetailedFields) {
|
|
148
|
+
version
|
|
149
|
+
ref
|
|
150
|
+
}
|
|
151
|
+
suggestedRefs @include(if: $includeDetailedFields) {
|
|
152
|
+
version
|
|
153
|
+
ref
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
codeIndexState
|
|
157
|
+
indexingStatus
|
|
158
|
+
indexingRef
|
|
159
|
+
availableVersions @include(if: $includeDetailedFields) {
|
|
160
|
+
version
|
|
161
|
+
ref
|
|
162
|
+
}
|
|
163
|
+
indexingEstimate @include(if: $includeDetailedFields) {
|
|
164
|
+
lowerSeconds
|
|
165
|
+
upperSeconds
|
|
166
|
+
elapsedSeconds
|
|
167
|
+
sampleCount
|
|
168
|
+
source
|
|
169
|
+
}
|
|
170
|
+
inventoryState
|
|
171
|
+
crawlStatus
|
|
172
|
+
coverageState
|
|
173
|
+
coverageReason
|
|
174
|
+
preparation {
|
|
175
|
+
selected
|
|
176
|
+
enqueued
|
|
177
|
+
activeJobs {
|
|
178
|
+
mode
|
|
179
|
+
state
|
|
180
|
+
}
|
|
181
|
+
awaited {
|
|
182
|
+
mode
|
|
183
|
+
outcome: status
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
}`;class ListServiceImpl2{endpointUrl;tokenProvider;fetchFn;runtime;constructor(endpointUrl,tokenProvider,fetchFn=globalThis.fetch,runtime={}){this.endpointUrl=endpointUrl;this.tokenProvider=tokenProvider;this.fetchFn=fetchFn;this.runtime=runtime}async list(params){return withServiceDiagnostics(this.runtime.diagnostics,"list.request",()=>executeWithTokenRefresh({getToken:()=>this.tokenProvider.getToken(),forceRefresh:()=>this.tokenProvider.forceRefresh(),shouldRefresh:isTokenRefreshableError,executeWithToken:(token)=>this.executeList(token,params)}))}async executeList(token,params){let response;try{response=await postPkgseerGraphql({endpointUrl:this.endpointUrl,token,query:LIST_QUERY,variables:buildListVariables(params),fetchFn:this.fetchFn,clientHeaders:this.runtime.clientHeaders,userAgent:this.runtime.userAgent,diagnostics:this.runtime.diagnostics})}catch(cause){if(cause instanceof PkgseerTransportError){throw createListTransportError(cause)}throw cause}if(response.status<200||response.status>=300){throw createListHttpError(response)}const parsed=listGraphQLResponseSchema.safeParse(response.parsedBody);if(!parsed.success)throw new MalformedListResponseError2;if(parsed.data.errors&&parsed.data.errors.length>0){throw createListGraphQLError(parsed.data.errors,this.runtime.clientVersion,this.runtime.diagnostics)}const resultParsed=listResultSchema.safeParse(parsed.data.data?.list);if(!resultParsed.success)throw new MalformedListResponseError2;const result=resultParsed.data;if((params.includeDetailedFields||params.includeReadActions===true)&&result.entries.some((entry)=>entry.read===undefined)){throw new MalformedListResponseError2}if(result.hasMore&&!result.nextCursor){throw new MalformedListResponseError2("Malformed response from the list service: a continuation cursor is missing.")}return result}}function buildListVariables(params){return{target:params.target,...params.paths!==undefined?{paths:params.paths}:{},...params.recursive!==undefined?{recursive:params.recursive}:{},...params.fileTypes!==undefined?{fileTypes:params.fileTypes}:{},...params.languages!==undefined?{languages:params.languages}:{},...params.intents!==undefined?{intents:params.intents}:{},...params.limit!==undefined?{limit:params.limit}:{},...params.after!==undefined?{after:params.after}:{},...params.waitTimeoutMs!==undefined?{waitTimeoutMs:params.waitTimeoutMs}:{},includeDetailedFields:params.includeDetailedFields,includeTargetProvenance:params.includeDetailedFields||params.includeTargetProvenance===true,includeReadActions:params.includeDetailedFields||params.includeReadActions===true}}function createListHttpError(response){const detail=parseHttpErrorDetail(response.responseBody,["message","error","detail"]);if(response.status===401){return new AuthenticationError2(SERVER_AUTHENTICATION_REJECTED_MESSAGE,"server")}if(response.status===403){return new ListAccessError2(detail??"List access denied.")}if(response.status>=500){return new ListBackendError2(detail?`Server error (${response.status}): ${detail}`:`Server error (${response.status})`,response.status)}return new ListBackendError2(detail??`Request failed with status ${response.status}`,response.status)}function createListTransportError(error){if(isFetchTimeoutError(error.cause)){return new ListBackendError2("List request timed out.",undefined,"TIMEOUT",true)}return new ListNetworkError2("Could not reach the package and documentation service. Check your connection.",{cause:error})}function createListGraphQLError(errors,clientVersion,diagnostics){const message=errors.map((error)=>error.message).join(", ");const extensions=errors.find((error)=>error.extensions&&Object.keys(error.extensions).length>0)?.extensions;const code=typeof extensions?.code==="string"?extensions.code:undefined;const retryable=typeof extensions?.retryable==="boolean"?extensions.retryable:undefined;if(isClientUpdateRequiredGraphQLError({message,code})){return new ClientUpdateRequiredError(undefined,undefined,clientVersion)}if(isGraphQLSchemaMismatchError({message,code})){const sanitized="Backend protocol mismatch. Your CLI may be newer than the server, or the server may require a newer CLI. Run `githits update-check` to verify your installed version. Set GITHITS_DEBUG=code-nav-wire to inspect GraphQL details during local development.";return new ListBackendError2(diagnostics?.isEnabled("code-nav-wire")?message:sanitized,undefined,code,retryable)}if(code==="AUTHENTICATION_REQUIRED"||code==="UNAUTHORIZED"){return new AuthenticationError2(SERVER_AUTHENTICATION_REJECTED_MESSAGE,"server")}if(code==="FORBIDDEN"||code==="ACCESS_DENIED"){return new ListAccessError2(message)}return new ListGraphQLError2(message,code,retryable,typeof extensions?.repo_url==="string"?extensions.repo_url:undefined,typeof extensions?.commit_sha==="string"?extensions.commit_sha:undefined,typeof extensions?.indexing_ref==="string"?extensions.indexing_ref:undefined,typeof extensions?.hint==="string"?extensions.hint:undefined,{indexingEstimate:parseIndexingDurationEstimate(extensions),availableVersions:parseAvailableArtifacts(extensions?.available_versions??extensions?.availableVersions),package:typeof extensions?.package==="string"?extensions.package:undefined})}import{z as z3}from"zod";var readResultTypeSchema=z3.object({__typename:z3.enum(["CodeContextResult","GetDocPageResult","CodeSymbolResolutionResult"])});var symbolResolutionSchema=z3.object({__typename:z3.literal("CodeSymbolResolutionResult"),status:z3.enum(["AMBIGUOUS","NOT_FOUND","SNAPSHOT_UNSUPPORTED"]),candidates:z3.array(z3.object({name:z3.string().nullable(),qualifiedPath:z3.string().nullable(),kind:z3.string().nullable(),arity:z3.number().int().nullable(),filePath:z3.string().nullable(),startLine:z3.number().int().nullable(),endLine:z3.number().int().nullable()})).max(10),suggestions:z3.array(z3.object({name:z3.string(),qualifiedPath:z3.string().nullable(),localId:z3.string().nullable(),arity:z3.number().int().nullable(),filePath:z3.string().nullable(),reason:z3.string().nullable()})).max(10),hasMore:z3.boolean(),repoUrl:z3.string(),gitRef:z3.string(),message:z3.string().nullable(),codeIndexState:z3.string()});var readGraphQLErrorSchema=z3.object({message:z3.string(),extensions:z3.record(z3.string(),z3.unknown()).optional()});var readGraphQLResponseSchema=z3.object({data:z3.object({read:z3.unknown().nullable().optional()}).nullable().optional(),errors:z3.array(readGraphQLErrorSchema).optional()});var READ_QUERY=`
|
|
188
|
+
query Read(
|
|
189
|
+
$target: String!
|
|
190
|
+
$path: String
|
|
191
|
+
$selector: String
|
|
192
|
+
$startLine: Int
|
|
193
|
+
$endLine: Int
|
|
194
|
+
$waitTimeoutMs: Int
|
|
195
|
+
) {
|
|
196
|
+
read(
|
|
197
|
+
target: $target
|
|
198
|
+
path: $path
|
|
199
|
+
selector: $selector
|
|
200
|
+
startLine: $startLine
|
|
201
|
+
endLine: $endLine
|
|
202
|
+
waitTimeoutMs: $waitTimeoutMs
|
|
203
|
+
) {
|
|
204
|
+
__typename
|
|
205
|
+
... on CodeContextResult {
|
|
206
|
+
codeAction: readTarget { ${READ_TARGET_SELECTION} }
|
|
207
|
+
content
|
|
208
|
+
filePath
|
|
209
|
+
language
|
|
210
|
+
totalLines
|
|
211
|
+
startLine
|
|
212
|
+
endLine
|
|
213
|
+
isBinary
|
|
214
|
+
codeIndexState
|
|
215
|
+
indexingRef
|
|
216
|
+
${CODE_CONTEXT_AVAILABLE_VERSIONS_SELECTION}
|
|
217
|
+
${INDEXING_DURATION_ESTIMATE_SELECTION}
|
|
218
|
+
${INDEXING_ESTIMATES_SELECTION}
|
|
219
|
+
${TARGET_RESOLUTION_SELECTION}
|
|
220
|
+
}
|
|
221
|
+
... on GetDocPageResult {
|
|
222
|
+
docAction: readTarget { ${READ_TARGET_SELECTION} }
|
|
223
|
+
registry
|
|
224
|
+
packageName
|
|
225
|
+
version
|
|
226
|
+
sourceKind
|
|
227
|
+
contentRange {
|
|
228
|
+
startLine
|
|
229
|
+
endLine
|
|
230
|
+
totalLines
|
|
231
|
+
anchor
|
|
232
|
+
}
|
|
233
|
+
page {
|
|
234
|
+
id
|
|
235
|
+
docsReadTarget
|
|
236
|
+
title
|
|
237
|
+
content
|
|
238
|
+
contentFormat
|
|
239
|
+
breadcrumbs
|
|
240
|
+
lastUpdatedAt
|
|
241
|
+
sourceKind
|
|
242
|
+
source {
|
|
243
|
+
url
|
|
244
|
+
label
|
|
245
|
+
}
|
|
246
|
+
repoUrl
|
|
247
|
+
gitRef
|
|
248
|
+
requestedRef
|
|
249
|
+
filePath
|
|
250
|
+
baseUrl
|
|
251
|
+
}
|
|
252
|
+
}
|
|
253
|
+
... on CodeSymbolResolutionResult {
|
|
254
|
+
status
|
|
255
|
+
candidates { name qualifiedPath kind arity filePath startLine endLine }
|
|
256
|
+
suggestions { name qualifiedPath localId arity filePath reason }
|
|
257
|
+
hasMore
|
|
258
|
+
repoUrl
|
|
259
|
+
gitRef
|
|
260
|
+
message
|
|
261
|
+
codeIndexState
|
|
262
|
+
}
|
|
263
|
+
}
|
|
264
|
+
}`;class ReadServiceImpl2{endpointUrl;tokenProvider;fetchFn;runtime;constructor(endpointUrl,tokenProvider,fetchFn=globalThis.fetch,runtime={}){this.endpointUrl=endpointUrl;this.tokenProvider=tokenProvider;this.fetchFn=fetchFn;this.runtime=runtime}async read(params){const request=normaliseReadRequest(params);return withServiceDiagnostics(this.runtime.diagnostics,"read.request",()=>executeWithTokenRefresh({getToken:()=>this.tokenProvider.getToken(),forceRefresh:()=>this.tokenProvider.forceRefresh(),shouldRefresh:isTokenRefreshableError,executeWithToken:(token)=>this.executeRead(token,request)}))}async executeRead(token,request){let response;try{response=await postPkgseerGraphql({endpointUrl:this.endpointUrl,token,query:READ_QUERY,variables:buildReadVariables(request),fetchFn:this.fetchFn,clientHeaders:this.runtime.clientHeaders,userAgent:this.runtime.userAgent,diagnostics:this.runtime.diagnostics})}catch(cause){if(cause instanceof PkgseerTransportError){if(isFetchTimeoutError(cause.cause)){throw new CodeNavigationBackendError("Read request timed out.",undefined,"TIMEOUT",true)}throw new CodeNavigationNetworkError("Could not reach the read service. Check your connection or set GITHITS_CODE_NAV_URL.",{cause})}throw cause}if(response.status<200||response.status>=300){const error=createCodeNavigationHttpError(response);if(error instanceof CodeNavigationAccessError&&error.message==="Code navigation access denied."){throw new CodeNavigationAccessError("Read access denied.")}throw error}const parsed=readGraphQLResponseSchema.safeParse(response.parsedBody);if(!parsed.success)throw malformedReadResponse();if(parsed.data.errors&&parsed.data.errors.length>0){const backendCode=parsed.data.errors[0]?.extensions?.code;if(backendCode==="DOCUMENTATION_SECTION_UNRESOLVED"){throw createPackageIntelligenceGraphQLError(parsed.data.errors,this.runtime.clientVersion,this.runtime.diagnostics)}if(backendCode==="FORBIDDEN"){throw new CodeNavigationAccessError("Read access denied.")}throw createCodeNavigationGraphQLError(parsed.data.errors,this.runtime)}const data=parsed.data.data?.read;if(!data)throw malformedReadResponse();const resultType=readResultTypeSchema.safeParse(data);if(!resultType.success)throw malformedReadResponse();if(resultType.data.__typename==="CodeSymbolResolutionResult"){const resolution=symbolResolutionSchema.safeParse(data);if(!resolution.success)throw malformedReadResponse();return{source:"symbol_resolution",result:resolution.data}}if(resultType.data.__typename==="CodeContextResult"){const action=z3.object({codeAction:selectedReadTargetSchema.nullable()}).safeParse(data);if(!action.success)throw malformedReadResponse();return{source:"code",result:{...parseReadBranch(parseCodeContextResult,data),readTarget:action.data.codeAction}}}if(resultType.data.__typename==="GetDocPageResult"){const action=z3.object({docAction:selectedReadTargetSchema}).safeParse(data);if(!action.success)throw malformedReadResponse();return{source:"docs",result:{...parseReadBranch(parsePackageDocResult,data),readTarget:action.data.docAction}}}throw malformedReadResponse()}}function normaliseReadRequest(params){const path=params.path?.trim()||undefined;return{...params,path}}function buildReadVariables(request){return{target:request.target,...request.path!==undefined?{path:request.path}:{},...request.selector!==undefined?{selector:request.selector}:{},...request.startLine!==undefined?{startLine:request.startLine}:{},...request.endLine!==undefined?{endLine:request.endLine}:{},...request.waitTimeoutMs!==undefined?{waitTimeoutMs:request.waitTimeoutMs}:{}}}function malformedReadResponse(){return new MalformedCodeNavigationResponseError("Malformed response from read service.")}function parseReadBranch(parse,data){try{return parse(data)}catch(error){if(error instanceof MalformedCodeNavigationResponseError||error instanceof MalformedPackageIntelligenceResponseError){throw malformedReadResponse()}throw error}}class RefreshingGitHitsService2{apiUrl;tokenProvider;serviceFactory;runtime;constructor(apiUrl,tokenProvider,serviceFactory=undefined,runtime={}){this.apiUrl=apiUrl;this.tokenProvider=tokenProvider;this.serviceFactory=serviceFactory;this.runtime=runtime}async search(params,options){return this.withTokenRefresh(options?(service)=>service.search(params,options):(service)=>service.search(params),options)}async withTokenRefresh(operation,options){return executeWithTokenRefresh({getToken:()=>{options?.signal?.throwIfAborted();return this.tokenProvider.getToken()},forceRefresh:()=>{options?.signal?.throwIfAborted();return this.tokenProvider.forceRefresh()},shouldRefresh:isTokenRefreshableError,executeWithToken:async(token)=>{options?.signal?.throwIfAborted();const service=this.serviceFactory?this.serviceFactory(this.apiUrl,token):new GitHitsServiceImpl2(this.apiUrl,token,undefined,undefined,this.runtime);return operation(service)}})}}import{z as z4}from"zod";var latestVersionMaliciousEvidenceSchema=z4.object({advisories:z4.array(z4.object({osvId:z4.string(),classificationReasons:z4.array(z4.string())})).max(5),totalCount:z4.number().int().nonnegative(),truncated:z4.boolean()}).nullable();var compactMatchSchema=z4.object({confidence:z4.string()});var candidateEvidenceSchema=z4.object({canonicalKey:z4.string(),nameSimilarity:z4.number().nullable()});var detailedMatchSchema=compactMatchSchema.extend({matchedAliases:z4.array(z4.string()),matchTier:z4.number().int(),score:z4.number()});var listTargetSchema=z4.object({kind:z4.string(),canonicalKey:z4.string(),latestVersionMaliciousStatus:z4.string(),latestVersionMaliciousEvidence:latestVersionMaliciousEvidenceSchema,description:z4.string().nullable().optional(),repositoryUrl:z4.string().nullable().optional(),stars:z4.number().int().nullable().optional(),downloadsLastMonth:z4.number().int().nullable().optional(),downloadsTotal:z4.number().int().nullable().optional(),docsAvailable:z4.boolean(),codeAvailable:z4.boolean(),groupKey:z4.string().nullable(),match:compactMatchSchema.nullable(),docsPageCount:z4.number().int().nullable(),codeFileCount:z4.number().int().nullable(),license:z4.string().nullable()});var targetReferenceSchema=z4.object({kind:z4.string(),canonicalKey:z4.string(),confidence:z4.string()});var detailedTargetSchema=listTargetSchema.omit({match:true}).extend({match:detailedMatchSchema.nullable(),displayName:z4.string(),registry:z4.string().nullable().optional(),packageName:z4.string().nullable().optional(),latestVersion:z4.string().nullable().optional(),repositoryOwner:z4.string().nullable().optional(),repositoryName:z4.string().nullable().optional(),documentationUrl:z4.string().nullable().optional()});var graphQLErrorSchema2=z4.object({message:z4.string(),extensions:z4.record(z4.string(),z4.unknown()).optional()});function responseSchema(targetSchema,includeNameSimilarity){const resultSchema=z4.object({best:targetReferenceSchema.nullable(),protectedMatches:z4.array(targetReferenceSchema),candidates:includeNameSimilarity?z4.array(candidateEvidenceSchema):z4.array(candidateEvidenceSchema).optional(),targets:z4.array(targetSchema),targetsTruncated:z4.boolean(),ambiguous:z4.boolean(),ambiguousReason:z4.string()});return z4.object({data:z4.object({resolveTarget:resultSchema.nullable()}).nullable().optional(),errors:z4.array(graphQLErrorSchema2).optional()})}var RESOLVE_TARGET_QUERY=`
|
|
265
|
+
query ResolveTarget(
|
|
266
|
+
$name: String!
|
|
267
|
+
$query: String
|
|
268
|
+
$registries: [Registry!]
|
|
269
|
+
$preferredKinds: [TargetResolutionKind!]
|
|
270
|
+
$intentHints: [String!]
|
|
271
|
+
$limit: Int!
|
|
272
|
+
$includeDetailedFields: Boolean!
|
|
273
|
+
$includeNameSimilarity: Boolean!
|
|
274
|
+
) {
|
|
275
|
+
resolveTarget(
|
|
276
|
+
name: $name
|
|
277
|
+
query: $query
|
|
278
|
+
registries: $registries
|
|
279
|
+
preferredKinds: $preferredKinds
|
|
280
|
+
intentHints: $intentHints
|
|
281
|
+
limit: $limit
|
|
282
|
+
) {
|
|
283
|
+
best {
|
|
284
|
+
...ResolveTargetReferenceFields
|
|
285
|
+
}
|
|
286
|
+
protectedMatches {
|
|
287
|
+
...ResolveTargetReferenceFields
|
|
288
|
+
}
|
|
289
|
+
candidates @include(if: $includeNameSimilarity) {
|
|
290
|
+
canonicalKey
|
|
291
|
+
nameSimilarity
|
|
292
|
+
}
|
|
293
|
+
targetsTruncated
|
|
294
|
+
targets {
|
|
295
|
+
...ResolveTargetListFields
|
|
296
|
+
...ResolveTargetJsonFields @include(if: $includeDetailedFields)
|
|
297
|
+
match {
|
|
298
|
+
confidence
|
|
299
|
+
...ResolveTargetMatchJsonFields @include(if: $includeDetailedFields)
|
|
300
|
+
}
|
|
301
|
+
}
|
|
302
|
+
ambiguous
|
|
303
|
+
ambiguousReason
|
|
304
|
+
}
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
fragment ResolveTargetReferenceFields on TargetResolutionCandidate {
|
|
308
|
+
kind
|
|
309
|
+
canonicalKey
|
|
310
|
+
confidence
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
fragment ResolveTargetListFields on TargetResolutionTarget {
|
|
314
|
+
kind
|
|
315
|
+
canonicalKey
|
|
316
|
+
latestVersionMaliciousStatus
|
|
317
|
+
latestVersionMaliciousEvidence {
|
|
318
|
+
advisories {
|
|
319
|
+
osvId
|
|
320
|
+
classificationReasons
|
|
321
|
+
}
|
|
322
|
+
totalCount
|
|
323
|
+
truncated
|
|
324
|
+
}
|
|
325
|
+
description
|
|
326
|
+
repositoryUrl
|
|
327
|
+
stars
|
|
328
|
+
downloadsLastMonth
|
|
329
|
+
downloadsTotal
|
|
330
|
+
docsAvailable
|
|
331
|
+
codeAvailable
|
|
332
|
+
groupKey
|
|
333
|
+
docsPageCount
|
|
334
|
+
codeFileCount
|
|
335
|
+
license
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
fragment ResolveTargetJsonFields on TargetResolutionTarget {
|
|
339
|
+
displayName
|
|
340
|
+
registry
|
|
341
|
+
packageName
|
|
342
|
+
latestVersion
|
|
343
|
+
repositoryOwner
|
|
344
|
+
repositoryName
|
|
345
|
+
documentationUrl
|
|
346
|
+
}
|
|
347
|
+
|
|
348
|
+
fragment ResolveTargetMatchJsonFields on TargetResolutionMatch {
|
|
349
|
+
matchedAliases
|
|
350
|
+
matchTier
|
|
351
|
+
score
|
|
352
|
+
}`;class ResolveTargetServiceImpl2{endpointUrl;tokenProvider;fetchFn;runtime;constructor(endpointUrl,tokenProvider,fetchFn=globalThis.fetch,runtime={}){this.endpointUrl=endpointUrl;this.tokenProvider=tokenProvider;this.fetchFn=fetchFn;this.runtime=runtime}async resolveTarget(params){return withServiceDiagnostics(this.runtime.diagnostics,"resolve-target.request",()=>executeWithTokenRefresh({getToken:()=>this.tokenProvider.getToken(),forceRefresh:()=>this.tokenProvider.forceRefresh(),shouldRefresh:(error)=>error instanceof AuthenticationError2,executeWithToken:(token)=>this.executeResolveTarget(token,params)}))}async executeResolveTarget(token,params){let response;try{response=await postPkgseerGraphql({endpointUrl:this.endpointUrl,token,query:RESOLVE_TARGET_QUERY,variables:buildVariables(params),fetchFn:this.fetchFn,clientHeaders:this.runtime.clientHeaders,userAgent:this.runtime.userAgent,diagnostics:this.runtime.diagnostics})}catch(cause){if(cause instanceof PkgseerTransportError){throw createPackageIntelligenceTransportError(cause)}throw cause}if(response.status<200||response.status>=300){throw createPackageIntelligenceHttpError(response)}const parsed=(params.includeDetailedFields?responseSchema(detailedTargetSchema,params.includeNameSimilarity):responseSchema(listTargetSchema,params.includeNameSimilarity)).safeParse(response.parsedBody);if(!parsed.success){throw new MalformedPackageIntelligenceResponseError("Malformed response from the target-resolution service.")}if(parsed.data.errors&&parsed.data.errors.length>0){throw createPackageIntelligenceGraphQLError(parsed.data.errors,this.runtime.clientVersion,this.runtime.diagnostics)}const result=parsed.data.data?.resolveTarget;if(!result){throw new MalformedPackageIntelligenceResponseError("Empty response from the target-resolution service.")}const nameSimilarityByCanonicalKey=new Map((result.candidates??[]).map((candidate)=>[candidate.canonicalKey,candidate.nameSimilarity]));return{best:result.best?normaliseReference(result.best):undefined,protectedMatches:result.protectedMatches.map(normaliseReference),targets:result.targets.map((target)=>normaliseTarget(target,nameSimilarityByCanonicalKey.get(target.canonicalKey))),targetsTruncated:result.targetsTruncated,ambiguous:result.ambiguous,ambiguousReason:result.ambiguousReason}}}function normaliseReference(target){return{kind:target.kind,canonicalKey:target.canonicalKey,confidence:target.confidence}}function buildVariables(params){const variables={name:params.name,limit:params.limit,includeDetailedFields:params.includeDetailedFields,includeNameSimilarity:params.includeNameSimilarity};if(params.query!==undefined)variables.query=params.query;if(params.registries!==undefined)variables.registries=params.registries;if(params.preferredKinds!==undefined){variables.preferredKinds=params.preferredKinds}if(params.intentHints!==undefined)variables.intentHints=params.intentHints;return variables}function normaliseTarget(target,nameSimilarity){const result={kind:target.kind,canonicalKey:target.canonicalKey,latestVersionMaliciousStatus:target.latestVersionMaliciousStatus,docsAvailable:target.docsAvailable,codeAvailable:target.codeAvailable};assignDefined(result,"description",target.description);assignDefined(result,"latestVersionMaliciousEvidence",target.latestVersionMaliciousEvidence);assignDefined(result,"repositoryUrl",target.repositoryUrl);assignDefined(result,"stars",target.stars);assignDefined(result,"downloadsLastMonth",target.downloadsLastMonth);assignDefined(result,"downloadsTotal",target.downloadsTotal);assignDefined(result,"groupKey",target.groupKey);assignDefined(result,"docsPageCount",target.docsPageCount);assignDefined(result,"codeFileCount",target.codeFileCount);assignDefined(result,"license",target.license);if(target.match){const match={confidence:target.match.confidence};assignDefined(match,"nameSimilarity",nameSimilarity);if("matchedAliases"in target.match){assignDefined(match,"matchedAliases",target.match.matchedAliases);assignDefined(match,"matchTier",target.match.matchTier);assignDefined(match,"score",target.match.score)}result.match=match}if("displayName"in target){assignDefined(result,"displayName",target.displayName);assignDefined(result,"registry",target.registry);assignDefined(result,"packageName",target.packageName);assignDefined(result,"latestVersion",target.latestVersion);assignDefined(result,"repositoryOwner",target.repositoryOwner);assignDefined(result,"repositoryName",target.repositoryName);assignDefined(result,"documentationUrl",target.documentationUrl)}return result}function assignDefined(target,key,value){if(value!==null&&value!==undefined)target[key]=value}function createStaticTokenProvider2(token){return{getToken:async()=>token,forceRefresh:async()=>{return}}}import{createHash,randomUUID}from"node:crypto";import{z as z5}from"zod";var MAX_HEADER_BYTES=256;var SESSION_ENV_VARS=["TERM_SESSION_ID","ITERM_SESSION_ID","WEZTERM_PANE","KITTY_PID","ALACRITTY_SOCKET","WT_SESSION","VSCODE_PID","SUPERSET_PANE_ID","SUPERSET_WORKSPACE_ID","STARSHIP_SESSION_KEY","SSH_CONNECTION"];var cachedSessionId;var SESSION_ID_SCHEMA=z5.string().regex(/^[A-Za-z0-9_-]{1,64}$/);class SessionIdConfigError2 extends Error{constructor(){super("Invalid GITHITS_SESSION_ID: expected [A-Za-z0-9_-]{1,64}.");this.name="SessionIdConfigError"}}function getEnvSessionId2(env=process.env){const value=env.GITHITS_SESSION_ID;if(value===undefined)return;const parsed=SESSION_ID_SCHEMA.safeParse(value);if(!parsed.success)throw new SessionIdConfigError2;return parsed.data}function resolveRawSessionId(env=process.env,ppid=process.ppid){const explicit=getEnvSessionId2(env);if(explicit!==undefined)return explicit;for(const key of SESSION_ENV_VARS){const value=env[key];if(value&&value.trim().length>0){return value.trim()}}if(typeof ppid==="number"&&!Number.isNaN(ppid)&&ppid>0){return String(ppid)}return randomUUID()}function getSessionId(env,ppid){const explicit=getEnvSessionId2(env);if(cachedSessionId!==undefined&&env===undefined&&ppid===undefined){return cachedSessionId}const sessionId=explicit??hashValue(resolveRawSessionId(env,ppid));if(env===undefined&&ppid===undefined){cachedSessionId=sessionId}return sessionId}function hashValue(input){return createHash("sha256").update(input).digest("hex").slice(0,16)}var AGENT_PROBES=[{envVar:"OPENCODE",name:"opencode"},{envVar:"CLAUDECODE",name:"claude-code"},{envVar:"CURSOR_TRACE_ID",name:"cursor"},{envVar:"WINDSURF_CONFIG_DIR",name:"windsurf"},{envVar:"ZED_TERM",name:"zed"},{envVar:"VSCODE_PID",name:"vscode"}];function parseAgentString(raw){const trimmed=raw.trim();if(trimmed.length===0)return;const slashIndex=trimmed.indexOf("/");if(slashIndex===-1)return{name:trimmed};const name=trimmed.slice(0,slashIndex);const ver=trimmed.slice(slashIndex+1);if(name.length===0)return;return{name,version:ver||undefined}}function formatAgentInfo(info){return info.version?`${info.name}/${info.version}`:info.name}function resolveAgentInfo(env=process.env){const explicit=env.GITHITS_AGENT;if(explicit&&explicit.trim().length>0){return parseAgentString(explicit)}for(const probe of AGENT_PROBES){const value=env[probe.envVar];if(value&&value.trim().length>0){return{name:probe.name}}}return}var CONTROL_CHARS=/[\x00-\x1f\x7f-\x9f]/g;function sanitizeHeaderValue(value){if(value===undefined||value===null||typeof value!=="string"){return}const cleaned=value.replace(CONTROL_CHARS,"").trim();if(cleaned.length===0)return;if(Buffer.byteLength(cleaned,"utf8")>MAX_HEADER_BYTES)return;return cleaned}function createClientHeaderBuilder2(options){return()=>buildClientHeadersWithContext({clientName:options.clientName,clientVersion:options.clientVersion,agentProvider:options.agentProvider,env:options.env,ppid:options.ppid})}function buildClientHeadersWithContext(context){try{const sessionId=getSessionId(context.env,context.ppid);const headers={};const name=sanitizeHeaderValue(context.clientName);if(name){headers["x-githits-client-name"]=name}const safeClientVersion=sanitizeHeaderValue(context.clientVersion);if(safeClientVersion){headers["x-githits-client-version"]=safeClientVersion}const agentInfo=context.agentProvider?.()??resolveAgentInfo(context.env);if(agentInfo){const agentValue=sanitizeHeaderValue(formatAgentInfo(agentInfo));if(agentValue){headers["x-githits-agent"]=agentValue}}headers["x-githits-session-id"]=sessionId;return headers}catch(error){if(error instanceof SessionIdConfigError2)throw error;return{}}}import{createHash as createHash2,randomBytes}from"node:crypto";var AGENTIC_ASK_MAX_RESPONSE_BYTES=4*1024*1024;export{GrepGraphQLError2,GrepBackendError2,GrepAccessError2,GrepNetworkError2,MalformedGrepResponseError2,parseGrepResult,GrepServiceImpl2,ListAccessError2,ListGraphQLError2,ListBackendError2,ListNetworkError2,MalformedListResponseError2,ListServiceImpl2,ReadServiceImpl2,RefreshingGitHitsService2,ResolveTargetServiceImpl2,createStaticTokenProvider2,SessionIdConfigError2,getEnvSessionId2,createClientHeaderBuilder2};
|