@githits/mcp 0.25.1 → 0.27.0

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.
@@ -1,1778 +0,0 @@
1
- import{LOCAL_AUTHENTICATION_MISSING_MESSAGE,SERVER_AUTHENTICATION_REJECTED_MESSAGE,AuthenticationError2,ApiRateLimitError2,DEFAULT_FETCH_TIMEOUT_MS,FetchTimeoutError2,fetchWithTimeout,isFetchTimeoutError,TermsAcceptanceRequiredError2,throwIfTermsAcceptanceRequired}from"./chunk-q07qg1z9.js";import{z}from"zod";var DEFAULT_MCP_URL2="https://mcp.githits.com";var DEFAULT_API_URL2="https://api.githits.com";var DEFAULT_CODE_NAV_URL2="https://oss.githits.dev";var ENVIRONMENT_SCHEMA=z.enum(["prod","dev"]);var SERVICE_URL_DEFAULTS={prod:{mcpUrl:DEFAULT_MCP_URL2,apiUrl:DEFAULT_API_URL2,codeNavigationUrl:DEFAULT_CODE_NAV_URL2},dev:{mcpUrl:"https://mcp-dev.githits.com",apiUrl:"https://api-dev.githits.com",codeNavigationUrl:"https://oss-dev.githits.dev"}};class ServiceUrlConfigError extends Error{constructor(message){super(message);this.name="ServiceUrlConfigError"}}function getGitHitsEnvironment(env=process.env){const value=env.GITHITS_ENV;const parsed=ENVIRONMENT_SCHEMA.safeParse(value===undefined||value.trim()===""?"prod":value);if(!parsed.success){throw new ServiceUrlConfigError("Invalid GITHITS_ENV: use prod or dev.")}return parsed.data}function getServiceUrlDefaults(environment){return SERVICE_URL_DEFAULTS[environment]}function getMcpUrl2(env=process.env){const defaults=getServiceUrlDefaults(getGitHitsEnvironment(env));return resolveServiceUrl("GITHITS_MCP_URL",defaults.mcpUrl,env)}function getApiUrl2(env=process.env){const defaults=getServiceUrlDefaults(getGitHitsEnvironment(env));return resolveServiceUrl("GITHITS_API_URL",defaults.apiUrl,env)}function getCodeNavigationUrl2(env=process.env){const defaults=getServiceUrlDefaults(getGitHitsEnvironment(env));return resolveServiceUrl("GITHITS_CODE_NAV_URL",defaults.codeNavigationUrl,env)}function validateServiceUrl(value,source){let parsed;try{parsed=new URL(value)}catch{throw new ServiceUrlConfigError(`Invalid ${source}: expected an HTTPS URL or an HTTP loopback URL.`)}if(parsed.protocol==="https:")return value;const hostname=parsed.hostname.replace(/^\[|\]$/g,"");const isLoopback=hostname==="localhost"||hostname==="127.0.0.1"||hostname==="::1";if(parsed.protocol==="http:"&&isLoopback)return value;throw new ServiceUrlConfigError(`Invalid ${source}: use HTTPS. Plain HTTP is allowed only for localhost, 127.0.0.1, or [::1].`)}function resolveServiceUrl(envName,defaultUrl,env){const override=env[envName];return override===undefined?defaultUrl:validateServiceUrl(override,envName)}function getEnvApiToken2(){return process.env.GITHITS_API_TOKEN}var MAX_ERROR_DETAIL_LENGTH=500;function parseHttpErrorDetail(body,fields){if(!body)return;let parsed;try{parsed=JSON.parse(body)}catch{return}if(!isRecord(parsed))return;for(const field of fields){const value=parsed[field];if(typeof value!=="string")continue;const normalized=normalizeSingleLineText(value);if(!normalized)continue;if(normalized.length<=MAX_ERROR_DETAIL_LENGTH)return normalized;return`${normalized.slice(0,MAX_ERROR_DETAIL_LENGTH-3)}...`}return}function normalizeSingleLineText(value){const withoutControlCharacters=Array.from(value,(character)=>{const codePoint=character.codePointAt(0)??0;return codePoint<=31||codePoint===127?" ":character}).join("");return withoutControlCharacters.replace(/\s+/g," ").trim()}function isRecord(value){return value!==null&&typeof value==="object"&&!Array.isArray(value)}function withServiceDiagnostics(diagnostics,name,operation){return diagnostics?diagnostics.withOperation(name,operation):operation()}var DEFAULT_EXAMPLE_REQUEST_TIMEOUT_MS=240000;function isTokenRefreshableError(error){return error instanceof AuthenticationError2||error instanceof TermsAcceptanceRequiredError2}function parseRetryAfterSeconds(value,nowMs){const normalized=value?.trim();if(!normalized)return;if(/^\d+$/.test(normalized)){const delaySeconds=Number(normalized);return Number.isSafeInteger(delaySeconds)?delaySeconds:undefined}if(/^[+-]?\d+(?:\.\d+)?$/.test(normalized))return;const isHttpDate=/^[A-Z][a-z]{2}, \d{2} [A-Z][a-z]{2} \d{4} \d{2}:\d{2}:\d{2} GMT$/.test(normalized)||/^[A-Z][a-z]+, \d{2}-[A-Z][a-z]{2}-\d{2} \d{2}:\d{2}:\d{2} GMT$/.test(normalized)||/^[A-Z][a-z]{2} [A-Z][a-z]{2} [ \d]\d \d{2}:\d{2}:\d{2} \d{4}$/.test(normalized);if(!isHttpDate)return;const retryAtMs=Date.parse(normalized);if(!Number.isFinite(retryAtMs))return;const delayMs=retryAtMs-nowMs;if(delayMs<0)return;const delaySeconds=Math.ceil(delayMs/1000);return Number.isSafeInteger(delaySeconds)?delaySeconds:undefined}class GitHitsServiceImpl2{apiUrl;token;fetchFn;fetchTimeoutMs;runtime;constructor(apiUrl,token,fetchFn,fetchTimeoutMs=undefined,runtime={}){this.apiUrl=apiUrl;this.token=token;this.fetchFn=fetchFn;this.fetchTimeoutMs=fetchTimeoutMs;this.runtime=runtime}async search(params,options){options?.signal?.throwIfAborted();return withServiceDiagnostics(this.runtime.diagnostics,"githits.search.request",async()=>{const response=await this.request("/search",{method:"POST",headers:this.headers(),body:JSON.stringify({query:params.query,language:params.language,license_mode:params.licenseMode??"strict",include_explanation:params.includeExplanation??false}),...options?.signal?{signal:options.signal}:{}},this.runtime.exampleRequestTimeoutMs??DEFAULT_EXAMPLE_REQUEST_TIMEOUT_MS);if(!response.ok){throw await this.createError(response)}return response.text()})}headers(){return{...this.runtime.clientHeaders?.(),Authorization:`Bearer ${this.token}`,"Content-Type":"application/json","User-Agent":this.runtime.userAgent??"githits-cli"}}fetchOptions(defaultTimeoutMs=DEFAULT_FETCH_TIMEOUT_MS){return{fetchFn:this.fetchFn,timeoutMs:this.fetchTimeoutMs??defaultTimeoutMs}}async request(path,init,defaultTimeoutMs=DEFAULT_FETCH_TIMEOUT_MS){const apiUrl=validateServiceUrl(this.apiUrl,"GITHITS_API_URL");const fetchOptions=this.fetchOptions(defaultTimeoutMs);try{return await fetchWithTimeout(`${apiUrl.replace(/\/+$/,"")}${path}`,init,fetchOptions)}catch(cause){if(isCallerAbort(cause,init.signal))throw cause;if(isFetchTimeoutError(cause)||isAbortError(cause)){throw new GitHitsRequestTimeoutError(fetchOptions.timeoutMs,cause)}if(cause instanceof TypeError){throw new Error("Could not connect to GitHits. Check your connection and GITHITS_API_URL, then try again.",{cause})}throw cause}}async createError(response){const status=response.status;const body=await response.text().catch(()=>"");const detail=parseHttpErrorDetail(body,["detail"]);throwIfTermsAcceptanceRequired(body);switch(status){case 401:return new AuthenticationError2(SERVER_AUTHENTICATION_REJECTED_MESSAGE,"server");case 403:return new Error("Access denied.");case 404:return new Error(detail||"Resource not found.");case 429:return new ApiRateLimitError2(undefined,parseRetryAfterSeconds(response.headers.get("Retry-After"),Date.now()));default:{if(status>=500){return new Error(`Server error (${status}). Try again shortly.${detail?` ${detail}`:""}`)}return new Error(`Request failed with status ${status}.${detail?` ${detail}`:""}`)}}}}class GitHitsRequestTimeoutError extends FetchTimeoutError2{constructor(timeoutMs,cause){super(timeoutMs,{cause});this.name="GitHitsRequestTimeoutError";this.message="Request to GitHits timed out. Try again."}}function isAbortError(error){return error instanceof Error&&error.name==="AbortError"}function isCallerAbort(error,signal){return Boolean(signal?.aborted&&(error===signal.reason||isAbortError(error)))}var PKGSEER_REGISTRY_ARGS=["npm","pypi","hex","crates","nuget","maven","zig","vcpkg","packagist","rubygems","go","swift"];var registryMap={npm:"NPM",pypi:"PYPI",hex:"HEX",crates:"CRATES",nuget:"NUGET",maven:"MAVEN",zig:"ZIG",vcpkg:"VCPKG",packagist:"PACKAGIST",rubygems:"RUBYGEMS",go:"GO",swift:"SWIFT"};var PKGSEER_REGISTRY_VALUES=Object.values(registryMap);var PKGSEER_REGISTRY_LIST2=PKGSEER_REGISTRY_ARGS.join(", ");function toPkgseerRegistry2(registry){return registryMap[registry]}function toPkgseerRegistryLowercase2(registry){for(const[lower,upper]of Object.entries(registryMap)){if(upper===registry)return lower}throw new Error(`Unknown registry value: ${String(registry)} (schema drift?)`)}function isKnownPkgseerRegistryArg(value){return Object.hasOwn(registryMap,value)}import{z as z3}from"zod";class PkgseerTransportError extends Error{constructor(message,options){super(message,options);this.name="PkgseerTransportError"}}function baseUrl(endpointUrl){return endpointUrl.replace(/\/+$/,"")}async function postPkgseerGraphql(request){const userAgent=request.userAgent??"githits-cli";const timeoutMs=request.timeoutMs??DEFAULT_FETCH_TIMEOUT_MS;const endpointUrl=validateServiceUrl(request.endpointUrl,"package/source service URL");const clientHeaders=request.clientHeaders?.();let response;try{response=await fetchWithTimeout(`${baseUrl(endpointUrl)}/api/graphql`,{method:"POST",signal:request.signal,headers:{...clientHeaders,Authorization:`Bearer ${request.token}`,"Content-Type":"application/json","User-Agent":userAgent},body:JSON.stringify({query:request.query,variables:request.variables})},{fetchFn:request.fetchFn,timeoutMs})}catch(cause){request.signal?.throwIfAborted();if(request.diagnostics?.isEnabled("pkg-graphql")){request.diagnostics.debug("pkg-graphql",{event:"transport-error",errorName:cause instanceof Error?cause.name:typeof cause,hasCause:true})}throw new PkgseerTransportError("Network request failed before a response was received. Caller should re-wrap with a domain-specific message.",{cause})}const responseBody=await response.text().catch(()=>"");request.signal?.throwIfAborted();const parsedBody=parseJsonOrNull(responseBody);throwIfTermsAcceptanceRequired(parsedBody);return{status:response.status,responseBody,parsedBody}}function parseJsonOrNull(body){if(!body)return null;try{return JSON.parse(body)}catch{return null}}var CLIENT_UPDATE_REQUIRED_REASON="Backend protocol changed";class ClientUpdateRequiredError extends Error{reason;currentVersion;constructor(message=`Update required: ${CLIENT_UPDATE_REQUIRED_REASON}`,reason=CLIENT_UPDATE_REQUIRED_REASON,currentVersion=undefined){super(message);this.reason=reason;this.currentVersion=currentVersion;this.name="ClientUpdateRequiredError"}}function isClientUpdateRequiredGraphQLError(input){return input.code==="CLIENT_UPDATE_REQUIRED"}function isGraphQLSchemaMismatchError(input){if(!isGraphQLSchemaMismatchMessage(input.message))return false;return!input.code||input.code==="GRAPHQL_VALIDATION_FAILED"||input.code==="BAD_USER_INPUT"}function isGraphQLSchemaMismatchMessage(message){return/Cannot query field|Field .* does not exist|Unknown argument|Unknown type|Unknown field/i.test(message)}async function executeWithTokenRefresh(options){const token=await options.getToken();if(!token){throw new AuthenticationError2(LOCAL_AUTHENTICATION_MISSING_MESSAGE,"local")}try{return await options.executeWithToken(token)}catch(error){if(token.startsWith("ghi-")||!options.shouldRefresh(error)){throw error}const refreshedToken=await options.forceRefresh();if(!refreshedToken){throw error}return options.executeWithToken(refreshedToken)}}import{z as z2}from"zod";var READ_TARGET_SELECTION="target path selector startLine endLine";var positiveLineSchema=z2.number().int().positive();var readTargetInputSchema=z2.object({target:z2.string().min(1),path:z2.string().nullable().optional(),selector:z2.string().nullable().optional(),startLine:positiveLineSchema.nullable().optional(),endLine:positiveLineSchema.nullable().optional()}).superRefine((value,context)=>{if(value.startLine!=null&&value.endLine!=null&&value.endLine<value.startLine){context.addIssue({code:z2.ZodIssueCode.custom,path:["endLine"],message:"endLine must be greater than or equal to startLine"})}});function normaliseReadTarget(value){return{target:value.target,...value.path==null?{}:{path:value.path},...value.selector==null?{}:{selector:value.selector},...value.startLine==null?{}:{startLine:value.startLine},...value.endLine==null?{}:{endLine:value.endLine}}}var readTargetSchema=readTargetInputSchema.transform(normaliseReadTarget);var selectedReadTargetSchema=readTargetInputSchema.safeExtend({path:z2.string().nullable(),selector:z2.string().nullable(),startLine:positiveLineSchema.nullable(),endLine:positiveLineSchema.nullable()}).transform(normaliseReadTarget);var INDEXING_WAIT_HINT="Wait until ready with CLI `--wait 60000` or MCP `wait_timeout_ms: 60000`.";class CodeNavigationAccessError extends Error{constructor(message){super(message);this.name="CodeNavigationAccessError"}}class CodeNavigationGraphQLError extends Error{code;constructor(message,code){super(message);this.code=code;this.name="CodeNavigationGraphQLError"}}class CodeNavigationIndexingError extends Error{indexingRef;availableVersions;availableRefs;targetResolution;indexingEstimate;hint;constructor(message,indexingRef,availableVersions,availableRefs,targetResolution=undefined,indexingEstimate=undefined,hint=undefined){super(message);this.indexingRef=indexingRef;this.availableVersions=availableVersions;this.availableRefs=availableRefs;this.targetResolution=targetResolution;this.indexingEstimate=indexingEstimate;this.hint=hint;this.name="CodeNavigationIndexingError"}}class CodeNavigationUnresolvableError extends Error{constructor(message){super(message);this.name="CodeNavigationUnresolvableError"}}class MalformedCodeNavigationResponseError extends Error{constructor(message){super(message);this.name="MalformedCodeNavigationResponseError"}}class CodeDiffError2 extends Error{details;partial;constructor(message,details=undefined,partial=undefined){super(message);this.details=details;this.partial=partial;this.name="CodeDiffError"}}class CodeNavigationTargetNotFoundError extends Error{availableVersions;repoUrl;requestedRef;metadata;constructor(message,availableVersions,repoUrl,requestedRef,metadata=undefined){super(message);this.availableVersions=availableVersions;this.repoUrl=repoUrl;this.requestedRef=requestedRef;this.metadata=metadata;this.name="CodeNavigationTargetNotFoundError"}}class CodeNavigationFileNotFoundError extends Error{filePath;constructor(message,filePath){super(message);this.filePath=filePath;this.name="CodeNavigationFileNotFoundError"}}class CodeNavigationVersionNotFoundError extends Error{packageName;requestedVersion;latestIndexed;availableVersions;metadata;constructor(message,packageName,requestedVersion,latestIndexed,availableVersions,metadata=undefined){super(message);this.packageName=packageName;this.requestedVersion=requestedVersion;this.latestIndexed=latestIndexed;this.availableVersions=availableVersions;this.metadata=metadata;this.name="CodeNavigationVersionNotFoundError"}}class CodeNavigationRefNotFoundError extends Error{repoUrl;requestedRef;availableRefs;suggestedRefs;metadata;constructor(message,repoUrl,requestedRef,availableRefs,suggestedRefs,metadata=undefined){super(message);this.repoUrl=repoUrl;this.requestedRef=requestedRef;this.availableRefs=availableRefs;this.suggestedRefs=suggestedRefs;this.metadata=metadata;this.name="CodeNavigationRefNotFoundError"}}class CodeNavigationValidationError extends Error{constructor(message){super(message);this.name="CodeNavigationValidationError"}}class CodeNavigationFeatureFlagRequiredError extends Error{constructor(message){super(message);this.name="CodeNavigationFeatureFlagRequiredError"}}class CodeNavigationNetworkError extends Error{constructor(message,options){super(message,options);this.name="CodeNavigationNetworkError"}}class CodeNavigationBackendError extends Error{status;graphqlCode;retryable;metadata;constructor(message,status,graphqlCode,retryable,metadata=undefined){super(message);this.status=status;this.graphqlCode=graphqlCode;this.retryable=retryable;this.metadata=metadata;this.name="CodeNavigationBackendError"}}var TARGET_RESOLUTION_AVAILABLE_REFS_SELECTION=`
2
- availableRefs {
3
- version
4
- ref
5
- }`;var TARGET_RESOLUTION_SUGGESTED_REFS_SELECTION=`
6
- suggestedRefs {
7
- version
8
- ref
9
- }`;var DISCOVERY_TARGET_PROGRESS_SUGGESTED_REFS_SELECTION=`
10
- suggestedRefs {
11
- version
12
- ref
13
- }`;var DOC_COVERAGE_SELECTION=`
14
- coverage {
15
- coverageState
16
- coverageReason
17
- pagesCrawled
18
- frontierRemaining
19
- artifactOverflowPageCount
20
- estimatedTotalPages
21
- note
22
- }`;var DOCUMENTATION_CONTRIBUTORS_SELECTION=`
23
- contributors {
24
- kind
25
- state
26
- freshness
27
- resultCount
28
- repositoryUrl
29
- commitSha
30
- siteKey
31
- siteUrl
32
- ${DOC_COVERAGE_SELECTION}
33
- }`;var TARGET_RESOLUTION_SELECTION=`
34
- targetResolution {
35
- requested {
36
- kind
37
- registry
38
- packageName
39
- version
40
- repoUrl
41
- gitRef
42
- commitSha
43
- }
44
- resolvedRequested {
45
- kind
46
- registry
47
- packageName
48
- version
49
- repoUrl
50
- gitRef
51
- commitSha
52
- }
53
- served {
54
- kind
55
- registry
56
- packageName
57
- version
58
- repoUrl
59
- gitRef
60
- commitSha
61
- }
62
- freshness
63
- freshnessReason
64
- indexingRef
65
- availableVersions {
66
- version
67
- ref
68
- }
69
- ${TARGET_RESOLUTION_AVAILABLE_REFS_SELECTION}
70
- ${TARGET_RESOLUTION_SUGGESTED_REFS_SELECTION}
71
- }`;var CODE_CONTEXT_AVAILABLE_VERSIONS_SELECTION=`
72
- availableVersions {
73
- version
74
- ref
75
- }`;var DISCOVERY_TARGET_PROGRESS_RETRY_SELECTION=`
76
- availableVersions {
77
- version
78
- ref
79
- }
80
- availableRefs {
81
- version
82
- ref
83
- }
84
- ${DISCOVERY_TARGET_PROGRESS_SUGGESTED_REFS_SELECTION}`;var INDEXING_DURATION_ESTIMATE_FIELDS=`
85
- lowerSeconds
86
- upperSeconds
87
- elapsedSeconds
88
- sampleCount
89
- source`;var INDEXING_DURATION_ESTIMATE_SELECTION=`
90
- indexingEstimate {
91
- ${INDEXING_DURATION_ESTIMATE_FIELDS}
92
- }`;var DISCOVERY_INDEXING_ESTIMATES_SELECTION=`
93
- indexingEstimates {
94
- kind
95
- targets
96
- repositoryUrl
97
- commitSha
98
- estimate {
99
- ${INDEXING_DURATION_ESTIMATE_FIELDS}
100
- }
101
- unavailableReason
102
- }`;var UNIFIED_SEARCH_LOCATOR_SELECTION=`
103
- registry
104
- packageName
105
- version
106
- pageId
107
- docsReadTarget
108
- sourceKind
109
- sourceUrl
110
- repoUrl
111
- gitRef
112
- commitSha
113
- requestedRef
114
- filePath
115
- repositoryFilePath
116
- startLine
117
- endLine
118
- evidenceRange {
119
- startLine
120
- endLine
121
- matchLine
122
- rangeKind
123
- matchSpansTruncated
124
- }
125
- indexedRange {
126
- startLine
127
- endLine
128
- }
129
- symbolContext {
130
- name
131
- qualifiedPath
132
- kind
133
- relation
134
- definitionRange {
135
- filePath
136
- repositoryFilePath
137
- startLine
138
- endLine
139
- }
140
- }
141
- fileContentHash
142
- symbolRef
143
- qualifiedPath
144
- kind
145
- category
146
- language`;var UNIFIED_SEARCH_REPOSITORY_EVIDENCE_SELECTION=`
147
- repositoryEvidence {
148
- bm25MatchFields
149
- semanticContext {
150
- scopes {
151
- name
152
- qualifiedPath
153
- kind
154
- parentQualifiedPath
155
- declarationStartLine
156
- declarationEndLine
157
- parameterNames
158
- returnType
159
- symbolRef
160
- }
161
- scopeChainTruncated
162
- preferredRead {
163
- targetLabel
164
- registry
165
- packageName
166
- version
167
- repoUrl
168
- gitRef
169
- commitSha
170
- requestedRef
171
- filePath
172
- repositoryFilePath
173
- startLine
174
- endLine
175
- }
176
- }
177
- matchedSource {
178
- startLine
179
- endLine
180
- matchLine
181
- rangeKind
182
- matchSpansTruncated
183
- linesOmittedBefore
184
- linesOmittedAfter
185
- lines {
186
- lineNumber
187
- text
188
- highlights
189
- prefixTruncated
190
- suffixTruncated
191
- }
192
- }
193
- }`;var UNIFIED_SEARCH_QUERY=`
194
- query UnifiedSearch(
195
- $targets: [SearchPackageInput!]!
196
- $query: String!
197
- $sources: [DiscoverySearchSource!]
198
- $filters: DiscoverySearchFiltersInput
199
- $allowPartialResults: Boolean
200
- $limit: Int
201
- $offset: Int
202
- $waitTimeoutMs: Int
203
- ) {
204
- search(
205
- targets: $targets
206
- query: $query
207
- sources: $sources
208
- filters: $filters
209
- allowPartialResults: $allowPartialResults
210
- limit: $limit
211
- offset: $offset
212
- waitTimeoutMs: $waitTimeoutMs
213
- ) {
214
- completed
215
- searchRef
216
- result {
217
- query
218
- queryWarnings
219
- sources
220
- results {
221
- readTarget { ${READ_TARGET_SELECTION} }
222
- id
223
- resultType
224
- targetLabel
225
- requestedTargetLabel
226
- freshTargetLabel
227
- servedTargetLabel
228
- freshness
229
- title
230
- score
231
- highlights {
232
- title
233
- }
234
- documentationPreview {
235
- text
236
- highlights
237
- }
238
- ${UNIFIED_SEARCH_REPOSITORY_EVIDENCE_SELECTION}
239
- locator {
240
- ${UNIFIED_SEARCH_LOCATOR_SELECTION}
241
- }
242
- }
243
- page {
244
- offset
245
- limit
246
- returned
247
- hasMore
248
- }
249
- partialResults
250
- evidenceNotice
251
- sourceStatus {
252
- source
253
- targetLabel
254
- requestedTargetLabel
255
- freshTargetLabel
256
- servedTargetLabel
257
- ${TARGET_RESOLUTION_SELECTION}
258
- indexingStatus
259
- codeIndexState
260
- resultCount
261
- appliedFilters
262
- ignoredFilters
263
- incompatibleFilters
264
- appliedQueryFeatures
265
- ignoredQueryFeatures
266
- incompatibleQueryFeatures
267
- suggestedSiteTargets
268
- suggestedSiteTargetsTruncated
269
- note
270
- ${DOC_COVERAGE_SELECTION}
271
- ${DOCUMENTATION_CONTRIBUTORS_SELECTION}
272
- }
273
- }
274
- progress {
275
- searchRef
276
- status
277
- targetsTotal
278
- targetsReady
279
- elapsedMs
280
- ${DISCOVERY_INDEXING_ESTIMATES_SELECTION}
281
- query
282
- queryWarnings
283
- sources
284
- requestedSources
285
- targetMode
286
- requestedTargets {
287
- registry
288
- name
289
- version
290
- repoUrl
291
- gitRef
292
- site
293
- }
294
- filters {
295
- fileIntent
296
- kind
297
- category
298
- publicOnly
299
- pathPrefix
300
- }
301
- limit
302
- offset
303
- targets {
304
- requested
305
- resolvedRequested
306
- served
307
- freshness
308
- indexingRef
309
- requestedRefKind
310
- ${TARGET_RESOLUTION_SELECTION}
311
- ${DISCOVERY_TARGET_PROGRESS_RETRY_SELECTION}
312
- ${DOC_COVERAGE_SELECTION}
313
- }
314
- expiresAt
315
- }
316
- }
317
- }`;var UNIFIED_SEARCH_STATUS_QUERY=`
318
- query UnifiedSearchStatus($searchRef: String!, $includeResults: Boolean!, $waitTimeoutMs: Int) {
319
- discoverySearchProgress(searchRef: $searchRef, includeResults: $includeResults, waitTimeoutMs: $waitTimeoutMs) {
320
- searchRef
321
- status
322
- targetsTotal
323
- targetsReady
324
- elapsedMs
325
- ${DISCOVERY_INDEXING_ESTIMATES_SELECTION}
326
- query
327
- queryWarnings
328
- sources
329
- requestedSources
330
- targetMode
331
- requestedTargets {
332
- registry
333
- name
334
- version
335
- repoUrl
336
- gitRef
337
- site
338
- }
339
- filters {
340
- fileIntent
341
- kind
342
- category
343
- publicOnly
344
- pathPrefix
345
- }
346
- limit
347
- offset
348
- targets {
349
- requested
350
- resolvedRequested
351
- served
352
- freshness
353
- indexingRef
354
- requestedRefKind
355
- ${TARGET_RESOLUTION_SELECTION}
356
- ${DISCOVERY_TARGET_PROGRESS_RETRY_SELECTION}
357
- ${DOC_COVERAGE_SELECTION}
358
- }
359
- expiresAt
360
- results {
361
- query
362
- queryWarnings
363
- sources
364
- results {
365
- readTarget { ${READ_TARGET_SELECTION} }
366
- id
367
- resultType
368
- targetLabel
369
- requestedTargetLabel
370
- freshTargetLabel
371
- servedTargetLabel
372
- freshness
373
- title
374
- score
375
- highlights {
376
- title
377
- }
378
- documentationPreview {
379
- text
380
- highlights
381
- }
382
- ${UNIFIED_SEARCH_REPOSITORY_EVIDENCE_SELECTION}
383
- locator {
384
- ${UNIFIED_SEARCH_LOCATOR_SELECTION}
385
- }
386
- }
387
- page {
388
- offset
389
- limit
390
- returned
391
- hasMore
392
- }
393
- partialResults
394
- evidenceNotice
395
- sourceStatus {
396
- source
397
- targetLabel
398
- requestedTargetLabel
399
- freshTargetLabel
400
- servedTargetLabel
401
- ${TARGET_RESOLUTION_SELECTION}
402
- indexingStatus
403
- codeIndexState
404
- resultCount
405
- appliedFilters
406
- ignoredFilters
407
- incompatibleFilters
408
- appliedQueryFeatures
409
- ignoredQueryFeatures
410
- incompatibleQueryFeatures
411
- suggestedSiteTargets
412
- suggestedSiteTargetsTruncated
413
- note
414
- ${DOC_COVERAGE_SELECTION}
415
- ${DOCUMENTATION_CONTRIBUTORS_SELECTION}
416
- }
417
- }
418
- }
419
- }`;function debugUnifiedSearchRequest(variables,diagnostics){if(!diagnostics?.isEnabled("code-nav"))return;const serialised=serialiseForDebug(variables);const filters=asRecord(serialised.filters);diagnostics.debug("code-nav",{event:"request",operation:"search",targetCount:Array.isArray(serialised.targets)?serialised.targets.length:0,sources:Array.isArray(serialised.sources)?serialised.sources:[],hasFilters:filters!==undefined,filterKeys:filters?Object.keys(filters).sort():[],fileIntent:filters&&typeof filters.fileIntent==="string"?filters.fileIntent:"omitted",allowPartialResults:serialised.allowPartialResults===true,presentVariableKeys:Object.keys(serialised).sort(),hasLimit:typeof serialised.limit==="number",hasOffset:typeof serialised.offset==="number",waitTimeoutMs:typeof serialised.waitTimeoutMs==="number"?serialised.waitTimeoutMs:undefined})}function debugGraphqlWireRequest(operation,graphqlQuery,variables,diagnostics){if(!diagnostics?.isEnabled("code-nav-wire"))return;diagnostics.debug("code-nav-wire",{event:"wire-request",operation,graphqlQuery,variables:serialiseForDebug(variables)})}function serialiseForDebug(value){try{const text=JSON.stringify(value);if(!text)return{};const parsed=JSON.parse(text);return asRecord(parsed)??{}}catch{return{}}}function asRecord(value){if(value&&typeof value==="object"&&!Array.isArray(value)){return value}return}var availableVersionSchema=z3.object({version:z3.string().nullable().optional(),ref:z3.string()});var indexingDurationEstimateSchema=z3.object({lowerSeconds:z3.number().int().nullable().optional(),upperSeconds:z3.number().int().nullable().optional(),elapsedSeconds:z3.number().int().nullable().optional(),sampleCount:z3.number().int().nullable().optional(),source:z3.string().nullable().optional()}).nullable().optional();var targetResolutionIdentitySchema=z3.object({kind:z3.string().nullable().optional(),registry:z3.string().nullable().optional(),packageName:z3.string().nullable().optional(),version:z3.string().nullable().optional(),repoUrl:z3.string().nullable().optional(),gitRef:z3.string().nullable().optional(),commitSha:z3.string().nullable().optional(),site:z3.string().nullable().optional()}).nullable().optional();var targetResolutionSchema=z3.object({requested:targetResolutionIdentitySchema,resolvedRequested:targetResolutionIdentitySchema,served:targetResolutionIdentitySchema,freshness:z3.string().nullable().optional(),freshnessReason:z3.string().nullable().optional(),indexingRef:z3.string().nullable().optional(),availableVersions:z3.array(availableVersionSchema).nullable().optional(),availableRefs:z3.array(availableVersionSchema).nullable().optional(),suggestedRefs:z3.array(availableVersionSchema).nullable().optional()}).nullable().optional();var unifiedSearchSourceSchema=z3.enum(["AUTO","DOCS","CODE","SYMBOL"]);var unifiedSearchResultTypeSchema=z3.enum(["DOCUMENTATION_PAGE","REPOSITORY_SYMBOL","REPOSITORY_CODE","REPOSITORY_DOC"]);var unifiedSearchLineRangeSchema=z3.object({startLine:z3.number().int().positive(),endLine:z3.number().int().positive()}).refine((range)=>range.startLine<=range.endLine,{message:"startLine must be less than or equal to endLine"});var unifiedSearchEvidenceRangeSchema=unifiedSearchLineRangeSchema.extend({matchLine:z3.number().int().positive().nullable().optional(),rangeKind:z3.string().nullable().optional(),matchSpansTruncated:z3.boolean()});var unifiedSearchDefinitionRangeSchema=unifiedSearchLineRangeSchema.extend({filePath:z3.string(),repositoryFilePath:z3.string()});var unifiedSearchSymbolContextBaseSchema=z3.object({name:z3.string(),qualifiedPath:z3.string().nullable().optional(),kind:z3.string().nullable().optional()});var unifiedSearchSymbolContextSchema=z3.discriminatedUnion("relation",[unifiedSearchSymbolContextBaseSchema.extend({relation:z3.literal("ENCLOSES_MATCH"),definitionRange:unifiedSearchDefinitionRangeSchema}),unifiedSearchSymbolContextBaseSchema.extend({relation:z3.literal("ASSOCIATED_WITH_INDEXED_CHUNK"),definitionRange:unifiedSearchDefinitionRangeSchema.nullable().optional()})]);var unifiedSearchLocatorSchema=z3.object({registry:z3.string().nullable().optional(),packageName:z3.string().nullable().optional(),version:z3.string().nullable().optional(),pageId:z3.string().nullable().optional(),docsReadTarget:z3.string().nullable().optional(),sourceKind:z3.string().nullable().optional(),sourceUrl:z3.string().nullable().optional(),repoUrl:z3.string().nullable().optional(),gitRef:z3.string().nullable().optional(),commitSha:z3.string().nullable().optional(),requestedRef:z3.string().nullable().optional(),filePath:z3.string().nullable().optional(),repositoryFilePath:z3.string().nullable().optional(),startLine:z3.number().int().nullable().optional(),endLine:z3.number().int().nullable().optional(),evidenceRange:unifiedSearchEvidenceRangeSchema.nullable().optional(),indexedRange:unifiedSearchLineRangeSchema.nullable().optional(),symbolContext:unifiedSearchSymbolContextSchema.nullable().optional(),fileContentHash:z3.string().nullable().optional(),symbolRef:z3.string().nullable().optional(),qualifiedPath:z3.string().nullable().optional(),kind:z3.string().nullable().optional(),category:z3.string().nullable().optional(),language:z3.string().nullable().optional()});var unifiedSearchSemanticPreferredReadSchema=z3.object({targetLabel:z3.string(),registry:z3.string().nullable(),packageName:z3.string().nullable(),version:z3.string().nullable(),repoUrl:z3.string(),gitRef:z3.string(),commitSha:z3.string(),requestedRef:z3.string().nullable(),filePath:z3.string(),repositoryFilePath:z3.string(),startLine:unifiedSearchLineRangeSchema.shape.startLine,endLine:unifiedSearchLineRangeSchema.shape.endLine}).refine((range)=>range.startLine<=range.endLine,{message:"startLine must be less than or equal to endLine"});var unifiedSearchSemanticScopeSchema=z3.object({name:z3.string(),qualifiedPath:z3.string(),kind:z3.string(),parentQualifiedPath:z3.string().nullable(),declarationStartLine:z3.number().int().positive(),declarationEndLine:z3.number().int().positive(),parameterNames:z3.array(z3.string()),returnType:z3.string().nullable(),symbolRef:z3.string()}).refine((range)=>range.declarationStartLine<=range.declarationEndLine,{message:"declarationStartLine must be less than or equal to declarationEndLine"});var unifiedSearchSemanticContextSchema=z3.object({scopes:z3.array(unifiedSearchSemanticScopeSchema),scopeChainTruncated:z3.boolean(),preferredRead:unifiedSearchSemanticPreferredReadSchema});var unifiedSearchHighlightSchema=z3.tuple([z3.number().int().nonnegative(),z3.number().int().nonnegative()]).refine(([start,end])=>start<=end,{message:"highlight start must be less than or equal to end"});var unifiedSearchFocusedSourceLineSchema=z3.object({lineNumber:z3.number().int().positive(),text:z3.string(),highlights:z3.array(unifiedSearchHighlightSchema),prefixTruncated:z3.boolean(),suffixTruncated:z3.boolean()});var unifiedSearchBm25MatchFieldSchema=z3.enum(["SYMBOL_NAME","FILE_PATH","DOCUMENTATION","SOURCE_IDENTIFIER"]);var unifiedSearchMatchedSourceSchema=unifiedSearchLineRangeSchema.extend({matchLine:z3.number().int().positive().nullable(),rangeKind:z3.string(),matchSpansTruncated:z3.boolean(),lines:z3.array(unifiedSearchFocusedSourceLineSchema),linesOmittedBefore:z3.boolean(),linesOmittedAfter:z3.boolean()});var unifiedSearchDocumentationPreviewSchema=z3.object({text:z3.string().min(1),highlights:z3.array(unifiedSearchHighlightSchema)});var unifiedSearchRepositoryEvidenceSchema=z3.object({semanticContext:unifiedSearchSemanticContextSchema.nullable(),bm25MatchFields:z3.array(unifiedSearchBm25MatchFieldSchema).min(1).nullable().optional(),matchedSource:unifiedSearchMatchedSourceSchema.nullable().optional()});var contentSafetySchema=z3.object({filtered:z3.boolean(),modifications:z3.array(z3.enum(["INVISIBLE_CONTROLS_STRIPPED","HTML_COMMENTS_STRIPPED","IMAGES_REPLACED","UNSAFE_LINKS_NEUTRALIZED"]))});var unifiedSearchHitSchema=z3.object({readTarget:selectedReadTargetSchema.nullable(),id:z3.string(),resultType:unifiedSearchResultTypeSchema,targetLabel:z3.string(),requestedTargetLabel:z3.string().nullable().optional(),freshTargetLabel:z3.string().nullable().optional(),servedTargetLabel:z3.string().nullable().optional(),freshness:z3.string().nullable().optional(),title:z3.string().nullable().optional(),score:z3.number().nullable().optional(),highlights:z3.object({title:z3.array(z3.tuple([z3.number().int(),z3.number().int()])).nullable().optional()}).nullable().optional(),repositoryEvidence:unifiedSearchRepositoryEvidenceSchema.nullable().optional(),documentationPreview:unifiedSearchDocumentationPreviewSchema.nullable().optional(),locator:unifiedSearchLocatorSchema});var unifiedSearchPageInfoSchema=z3.object({offset:z3.number().int(),limit:z3.number().int(),returned:z3.number().int(),hasMore:z3.boolean()});var docCoverageSchema=z3.object({coverageState:z3.string(),coverageReason:z3.string().nullable().optional(),pagesCrawled:z3.number().int().nullable().optional(),frontierRemaining:z3.number().int().nullable().optional(),artifactOverflowPageCount:z3.number().int().nullable().optional(),estimatedTotalPages:z3.number().int().nullable().optional(),note:z3.string().nullable().optional()}).nullable().optional();var unifiedSearchDocumentationContributorSchema=z3.object({kind:z3.enum(["REPOSITORY_DOCS","DOCPACK"]),state:z3.enum(["SEARCHED","READY","PENDING","UNAVAILABLE"]),freshness:z3.enum(["CURRENT","PROVISIONAL","STALE"]).nullable().optional(),resultCount:z3.number().int().nonnegative(),repositoryUrl:z3.string().nullable().optional(),commitSha:z3.string().nullable().optional(),siteKey:z3.string().nullable().optional(),siteUrl:z3.string().nullable().optional(),coverage:docCoverageSchema});var unifiedSearchSourceStatusSchema=z3.object({source:unifiedSearchSourceSchema,targetLabel:z3.string(),requestedTargetLabel:z3.string().nullable().optional(),freshTargetLabel:z3.string().nullable().optional(),servedTargetLabel:z3.string().nullable().optional(),targetResolution:targetResolutionSchema,indexingStatus:z3.string().nullable().optional(),codeIndexState:z3.string().nullable().optional(),resultCount:z3.number().int().nullable().optional(),appliedFilters:z3.array(z3.string()),ignoredFilters:z3.array(z3.string()),incompatibleFilters:z3.array(z3.string()),appliedQueryFeatures:z3.array(z3.string()),ignoredQueryFeatures:z3.array(z3.string()),incompatibleQueryFeatures:z3.array(z3.string()),suggestedSiteTargets:z3.array(z3.string()),suggestedSiteTargetsTruncated:z3.boolean(),note:z3.string().nullable().optional(),coverage:docCoverageSchema,contributors:z3.array(unifiedSearchDocumentationContributorSchema)});var unifiedSearchResultSchema=z3.object({query:z3.string(),queryWarnings:z3.array(z3.string()),sources:z3.array(unifiedSearchSourceSchema),results:z3.array(unifiedSearchHitSchema),page:unifiedSearchPageInfoSchema,partialResults:z3.boolean(),sourceStatus:z3.array(unifiedSearchSourceStatusSchema),evidenceNotice:z3.string().nullable().optional()});var unifiedSearchSessionStatusSchema=z3.string().min(1);var unifiedSearchFiltersSchema=z3.object({fileIntent:z3.string().nullable().optional(),kind:z3.string().nullable().optional(),category:z3.string().nullable().optional(),publicOnly:z3.boolean().nullable().optional(),pathPrefix:z3.string().nullable().optional()}).nullable().optional();var unifiedSearchProgressTargetSchema=z3.object({requested:z3.string().nullable().optional(),resolvedRequested:z3.string().nullable().optional(),served:z3.string().nullable().optional(),freshness:z3.string().nullable().optional(),indexingRef:z3.string().nullable().optional(),requestedRefKind:z3.string().nullable().optional(),targetResolution:targetResolutionSchema,availableVersions:z3.array(availableVersionSchema).nullable().optional(),availableRefs:z3.array(availableVersionSchema).nullable().optional(),suggestedRefs:z3.array(availableVersionSchema).nullable().optional(),coverage:docCoverageSchema});var unifiedSearchRequestedTargetSchema=z3.object({registry:z3.string().nullable().optional(),name:z3.string().nullable().optional(),version:z3.string().nullable().optional(),repoUrl:z3.string().nullable().optional(),gitRef:z3.string().nullable().optional(),site:z3.string().nullable().optional()});var discoveryIndexingEstimateSchema=z3.object({kind:z3.enum(["REPOSITORY","DOCUMENTATION"]),targets:z3.array(z3.string()),repositoryUrl:z3.string().nullable(),commitSha:z3.string().nullable(),estimate:indexingDurationEstimateSchema,unavailableReason:z3.enum(["NO_HISTORY","UNSUPPORTED_WORK"]).nullable()});var unifiedSearchProgressSchema=z3.object({searchRef:z3.string(),status:unifiedSearchSessionStatusSchema,targetsTotal:z3.number().int(),targetsReady:z3.number().int(),elapsedMs:z3.number().int(),query:z3.string(),queryWarnings:z3.array(z3.string()),sources:z3.array(unifiedSearchSourceSchema),requestedSources:z3.array(unifiedSearchSourceSchema).nullable().optional(),targetMode:z3.string().nullable().optional(),requestedTargets:z3.array(unifiedSearchRequestedTargetSchema).nullable().optional(),filters:unifiedSearchFiltersSchema,limit:z3.number().int().nullable().optional(),offset:z3.number().int().nullable().optional(),targets:z3.array(unifiedSearchProgressTargetSchema).nullable().optional(),indexingEstimates:z3.array(discoveryIndexingEstimateSchema),expiresAt:z3.string().nullable().optional(),results:unifiedSearchResultSchema.nullable().optional()});var asyncUnifiedSearchResultSchema=z3.object({completed:z3.boolean(),searchRef:z3.string().nullable().optional(),result:unifiedSearchResultSchema.nullable().optional(),progress:unifiedSearchProgressSchema.nullable().optional()});var graphQLErrorSchema=z3.object({message:z3.string(),extensions:z3.record(z3.string(),z3.unknown()).optional()});var codeDiffGraphQLErrorSchema=z3.object({message:z3.string(),path:z3.array(z3.union([z3.string(),z3.number().int()])).nullable().optional(),extensions:z3.record(z3.string(),z3.unknown()).optional()});var codeDiffRegistrySchema=z3.enum(PKGSEER_REGISTRY_VALUES);var codeDiffPackageInfoSchema=z3.object({registry:codeDiffRegistrySchema,name:z3.string(),repoUrl:z3.string()});var codeDiffRefResolutionSchema=z3.object({requested:z3.string(),resolvedVersion:z3.string().nullable().optional(),ref:z3.string(),commitSha:z3.string(),refKind:z3.enum(["SHA","TAG","BRANCH","HEAD","UNKNOWN"]),versionSource:z3.enum(["REGISTRY","GIT_HEAD","TAG","RELEASE"]).nullable().optional()});var rawCodeDiffSummarySchema=z3.object({filesChanged:z3.number().int(),added:z3.number().int(),deleted:z3.number().int(),modified:z3.number().int(),modeChanged:z3.number().int(),typeChanged:z3.number().int(),inventoryComplete:z3.boolean(),unprojectableFiles:z3.number().int()});var rawCodeDiffScopeSchema=z3.object({status:z3.enum(["PACKAGE","REPOSITORY","UNKNOWN"]),fromSubpath:z3.string().nullable().optional(),toSubpath:z3.string().nullable().optional(),pathPrefix:z3.string().nullable().optional(),pathGlob:z3.string().nullable().optional()});var rawCodeDiffContentFailureSchema=z3.object({code:z3.string(),retryable:z3.boolean(),retryAfterMs:z3.number().int().nullable().optional(),stage:z3.string().nullable().optional(),limitKind:z3.string().nullable().optional()});var rawCodeDiffFileSchema=z3.object({path:z3.string(),pathEncoding:z3.enum(["UTF8","BYTE_ESCAPED"]),status:z3.enum(["ADDED","DELETED","MODIFIED"]),modeChanged:z3.boolean(),typeChanged:z3.boolean(),additions:z3.number().int().nullable().optional(),deletions:z3.number().int().nullable().optional(),patch:z3.string().nullable().optional(),contentStatus:z3.enum(["NOT_REQUESTED","STATS","PATCH","BINARY","METADATA_ONLY","OMITTED","UNAVAILABLE"]),contentOmissionReason:z3.string().nullable().optional(),contentSafety:contentSafetySchema});var rawCodeDiffSchema=z3.object({summary:rawCodeDiffSummarySchema,scope:rawCodeDiffScopeSchema,contentCoverage:z3.enum(["NOT_REQUESTED","COMPLETE","PARTIAL","FAILED"]),contentFailure:rawCodeDiffContentFailureSchema.nullable().optional(),files:z3.array(rawCodeDiffFileSchema),hasMoreFiles:z3.boolean()});var codeDiffResultSchema=z3.object({package:codeDiffPackageInfoSchema.nullable().optional(),fromResolution:codeDiffRefResolutionSchema,toResolution:codeDiffRefResolutionSchema,raw:rawCodeDiffSchema.nullable().optional()});var codeDiffGraphQLResponseSchema=z3.object({data:z3.object({codeDiff:codeDiffResultSchema.nullable().optional()}).nullable().optional(),errors:z3.array(codeDiffGraphQLErrorSchema).optional()});var CODE_DIFF_OPTION_KEYS=new Set(["maxFiles","maxPatchBytes","pathPrefix","pathGlob"]);var CODE_DIFF_COMMON_SELECTION=` package {
420
- registry
421
- name
422
- repoUrl
423
- }
424
- fromResolution {
425
- requested
426
- resolvedVersion
427
- ref
428
- commitSha
429
- refKind
430
- versionSource
431
- }
432
- toResolution {
433
- requested
434
- resolvedVersion
435
- ref
436
- commitSha
437
- refKind
438
- versionSource
439
- }
440
- raw {
441
- summary {
442
- filesChanged
443
- added
444
- deleted
445
- modified
446
- modeChanged
447
- typeChanged
448
- inventoryComplete
449
- unprojectableFiles
450
- }
451
- scope {
452
- status
453
- fromSubpath
454
- toSubpath
455
- pathPrefix
456
- pathGlob
457
- }
458
- contentCoverage
459
- contentFailure {
460
- code
461
- retryable
462
- retryAfterMs
463
- stage
464
- limitKind
465
- }
466
- files {
467
- path
468
- pathEncoding
469
- status
470
- modeChanged
471
- typeChanged
472
- contentStatus
473
- contentSafety {
474
- filtered
475
- modifications
476
- }`;function buildCodeDiffQuery(mode){const contentFields=mode==="inventory"?"":mode==="stats"?`
477
- additions
478
- deletions`:`
479
- additions
480
- deletions
481
- patch
482
- contentOmissionReason`;return`
483
- query CodeDiff(
484
- $registry: Registry
485
- $name: String
486
- $fromVersion: String
487
- $toVersion: String
488
- $repoUrl: String
489
- $fromRef: String
490
- $toRef: String
491
- $rawOptions: RawCodeDiffOptions
492
- ) {
493
- codeDiff(
494
- registry: $registry
495
- name: $name
496
- fromVersion: $fromVersion
497
- toVersion: $toVersion
498
- repoUrl: $repoUrl
499
- fromRef: $fromRef
500
- toRef: $toRef
501
- rawOptions: $rawOptions
502
- ) {
503
- ${CODE_DIFF_COMMON_SELECTION}${contentFields}
504
- }
505
- hasMoreFiles
506
- }
507
- }
508
- }`}var navigationResolutionSchema=z3.object({requestedVersion:z3.string().nullable().optional(),requestedRef:z3.string().nullable().optional(),resolvedRef:z3.string().nullable().optional(),commitSha:z3.string().nullable().optional()}).nullable().optional();var navigationDiagnosticsSchema=z3.object({hint:z3.string().nullable().optional()}).nullable().optional();var repoFileEntrySchema=z3.object({path:z3.string(),name:z3.string().nullable().optional(),language:z3.string().nullable().optional(),fileType:z3.string().nullable().optional(),byteSize:z3.number().int().nullable().optional()});var listRepoFilesResponseSchema=z3.object({files:z3.array(repoFileEntrySchema),total:z3.number().int(),hasMore:z3.boolean(),indexedVersion:z3.string().nullable().optional(),resolution:navigationResolutionSchema,targetResolution:targetResolutionSchema,diagnostics:navigationDiagnosticsSchema,codeIndexState:z3.string(),indexingRef:z3.string().nullable().optional(),availableVersions:z3.array(availableVersionSchema).nullable().optional(),indexingEstimate:indexingDurationEstimateSchema});var listRepoFilesGraphQLResponseSchema=z3.object({data:z3.object({listRepoFiles:listRepoFilesResponseSchema.nullable().optional()}).nullable().optional(),errors:z3.array(graphQLErrorSchema).optional()});var LIST_REPO_FILES_QUERY=`
509
- query ListRepoFiles(
510
- $registry: Registry
511
- $packageName: String
512
- $repoUrl: String
513
- $gitRef: String
514
- $version: String
515
- $pathPrefix: String
516
- $pathSelectors: [FilePathSelectorInput!]
517
- $extensions: [String!]
518
- $fileTypes: [String!]
519
- $languages: [String!]
520
- $fileIntent: FileIntent
521
- $fileIntents: [FileIntent!]
522
- $excludeFileIntents: [FileIntent!]
523
- $excludeDocFiles: Boolean
524
- $excludeTestFiles: Boolean
525
- $includeHidden: Boolean
526
- $limit: Int
527
- $waitTimeoutMs: Int
528
- ) {
529
- listRepoFiles(
530
- registry: $registry
531
- packageName: $packageName
532
- repoUrl: $repoUrl
533
- gitRef: $gitRef
534
- version: $version
535
- pathPrefix: $pathPrefix
536
- pathSelectors: $pathSelectors
537
- extensions: $extensions
538
- fileTypes: $fileTypes
539
- languages: $languages
540
- fileIntent: $fileIntent
541
- fileIntents: $fileIntents
542
- excludeFileIntents: $excludeFileIntents
543
- excludeDocFiles: $excludeDocFiles
544
- excludeTestFiles: $excludeTestFiles
545
- includeHidden: $includeHidden
546
- limit: $limit
547
- waitTimeoutMs: $waitTimeoutMs
548
- ) {
549
- files {
550
- path
551
- name
552
- language
553
- fileType
554
- byteSize
555
- }
556
- total
557
- hasMore
558
- indexedVersion
559
- resolution {
560
- requestedVersion
561
- requestedRef
562
- resolvedRef
563
- commitSha
564
- }
565
- ${TARGET_RESOLUTION_SELECTION}
566
- diagnostics {
567
- hint
568
- }
569
- codeIndexState
570
- indexingRef
571
- availableVersions {
572
- version
573
- ref
574
- }
575
- ${INDEXING_DURATION_ESTIMATE_SELECTION}
576
- }
577
- }`;var codeContextResponseSchema=z3.object({content:z3.string().nullable().optional(),filePath:z3.string().nullable().optional(),language:z3.string().nullable().optional(),totalLines:z3.number().int().nullable().optional(),startLine:z3.number().int().nullable().optional(),endLine:z3.number().int().nullable().optional(),repoUrl:z3.string().nullable().optional(),gitRef:z3.string().nullable().optional(),isBinary:z3.boolean().nullable().optional(),codeIndexState:z3.string(),indexingRef:z3.string().nullable().optional(),availableVersions:z3.array(availableVersionSchema).nullable().optional(),indexingEstimate:indexingDurationEstimateSchema,targetResolution:targetResolutionSchema});var fetchCodeContextGraphQLResponseSchema=z3.object({data:z3.object({fetchCodeContext:codeContextResponseSchema.nullable().optional()}).nullable().optional(),errors:z3.array(graphQLErrorSchema).optional()});var FETCH_CODE_CONTEXT_QUERY=`
578
- query FetchCodeContext(
579
- $registry: Registry
580
- $packageName: String
581
- $repoUrl: String
582
- $gitRef: String
583
- $version: String
584
- $filePath: String!
585
- $startLine: Int
586
- $endLine: Int
587
- $waitTimeoutMs: Int
588
- ) {
589
- fetchCodeContext(
590
- registry: $registry
591
- packageName: $packageName
592
- repoUrl: $repoUrl
593
- gitRef: $gitRef
594
- version: $version
595
- filePath: $filePath
596
- startLine: $startLine
597
- endLine: $endLine
598
- waitTimeoutMs: $waitTimeoutMs
599
- ) {
600
- content
601
- filePath
602
- language
603
- totalLines
604
- startLine
605
- endLine
606
- repoUrl
607
- gitRef
608
- isBinary
609
- codeIndexState
610
- indexingRef
611
- ${CODE_CONTEXT_AVAILABLE_VERSIONS_SELECTION}
612
- ${INDEXING_DURATION_ESTIMATE_SELECTION}
613
- ${TARGET_RESOLUTION_SELECTION}
614
- }
615
- }`;var grepRepoMatchSchema=z3.object({filePath:z3.string(),line:z3.number().int(),matchStartByte:z3.number().int(),matchEndByte:z3.number().int(),lineContent:z3.string(),contextBefore:z3.array(z3.string()).nullable().optional(),contextAfter:z3.array(z3.string()).nullable().optional(),fileContentHash:z3.string().nullable().optional(),fileIntent:z3.string().nullable().optional(),symbolRowId:z3.string().nullable().optional(),symbol:z3.object({symbolRef:z3.string().optional(),name:z3.string().optional(),qualifiedPath:z3.string().nullable().optional(),kind:z3.string().nullable().optional(),category:z3.string().nullable().optional(),arity:z3.number().int().nullable().optional(),isPublic:z3.boolean().nullable().optional(),filePath:z3.string().nullable().optional(),startLine:z3.number().int().nullable().optional(),endLine:z3.number().int().nullable().optional(),contentHash:z3.string().nullable().optional(),parentPath:z3.string().nullable().optional()}).nullable().optional()});var grepRepoResponseSchema=z3.object({matches:z3.array(grepRepoMatchSchema),nextCursor:z3.string().nullable().optional(),hasMore:z3.boolean(),truncatedReason:z3.enum(["NONE","MAX_MATCHES","MAX_MATCHES_PER_FILE","DEADLINE"]),routeTaken:z3.enum(["SINGLE_FILE","CONTENT_INDEX"]).nullable().optional(),filesScanned:z3.number().int(),filesInScope:z3.number().int(),binaryFilesSkipped:z3.number().int(),filesTooLargeSkipped:z3.number().int(),totalMatches:z3.number().int(),uniqueFilesMatched:z3.number().int(),indexedVersion:z3.string().nullable().optional(),resolution:navigationResolutionSchema,targetResolution:targetResolutionSchema,codeIndexState:z3.string(),indexingRef:z3.string().nullable().optional(),availableVersions:z3.array(availableVersionSchema).nullable().optional(),indexingEstimate:indexingDurationEstimateSchema});var grepRepoGraphQLResponseSchema=z3.object({data:z3.object({grepRepo:grepRepoResponseSchema.nullable().optional()}).nullable().optional(),errors:z3.array(graphQLErrorSchema).optional()});var GREP_REPO_SYMBOL_SELECTIONS={symbol_ref:"symbolRef",name:"name",qualified_path:"qualifiedPath",kind:"kind",category:"category",arity:"arity",is_public:"isPublic",file_path:"filePath",start_line:"startLine",end_line:"endLine",content_hash:"contentHash",parent_path:"parentPath"};function buildGrepRepoQuery(symbolFields){const symbolSelection=(symbolFields??[]).map((field)=>GREP_REPO_SYMBOL_SELECTIONS[field]).filter((field)=>Boolean(field)).filter((field,index,fields)=>fields.indexOf(field)===index).join(`
616
- `);const symbolBlock=symbolSelection.length>0?`
617
- symbol {
618
- ${symbolSelection}
619
- }`:"";return`
620
- query GrepRepo(
621
- $registry: Registry
622
- $packageName: String
623
- $repoUrl: String
624
- $gitRef: String
625
- $version: String
626
- $waitTimeoutMs: Int
627
- $pattern: String!
628
- $patternType: GrepPatternType
629
- $caseSensitive: Boolean
630
- $pathSelectors: [GrepPathSelectorInput!]
631
- $extensions: [String!]
632
- $excludeDocFiles: Boolean
633
- $excludeTestFiles: Boolean
634
- $allowUnscoped: Boolean
635
- $contextLinesBefore: Int
636
- $contextLinesAfter: Int
637
- $maxMatches: Int
638
- $maxMatchesPerFile: Int
639
- $cursor: String
640
- $symbolFields: [String!]
641
- ) {
642
- grepRepo(
643
- registry: $registry
644
- packageName: $packageName
645
- repoUrl: $repoUrl
646
- gitRef: $gitRef
647
- version: $version
648
- waitTimeoutMs: $waitTimeoutMs
649
- pattern: $pattern
650
- patternType: $patternType
651
- caseSensitive: $caseSensitive
652
- pathSelectors: $pathSelectors
653
- extensions: $extensions
654
- excludeDocFiles: $excludeDocFiles
655
- excludeTestFiles: $excludeTestFiles
656
- allowUnscoped: $allowUnscoped
657
- contextLinesBefore: $contextLinesBefore
658
- contextLinesAfter: $contextLinesAfter
659
- maxMatches: $maxMatches
660
- maxMatchesPerFile: $maxMatchesPerFile
661
- cursor: $cursor
662
- symbolFields: $symbolFields
663
- ) {
664
- matches {
665
- filePath
666
- line
667
- matchStartByte
668
- matchEndByte
669
- lineContent
670
- contextBefore
671
- contextAfter
672
- fileContentHash
673
- fileIntent
674
- symbolRowId${symbolBlock}
675
- }
676
- nextCursor
677
- totalMatches
678
- hasMore
679
- truncatedReason
680
- routeTaken
681
- filesScanned
682
- filesInScope
683
- binaryFilesSkipped
684
- filesTooLargeSkipped
685
- uniqueFilesMatched
686
- indexedVersion
687
- resolution {
688
- requestedVersion
689
- requestedRef
690
- resolvedRef
691
- commitSha
692
- }
693
- ${TARGET_RESOLUTION_SELECTION}
694
- codeIndexState
695
- indexingRef
696
- availableVersions {
697
- version
698
- ref
699
- }
700
- ${INDEXING_DURATION_ESTIMATE_SELECTION}
701
- }
702
- }`}var unifiedSearchGraphQLResponseSchema=z3.object({data:z3.object({search:asyncUnifiedSearchResultSchema.nullable().optional()}).nullable().optional(),errors:z3.array(graphQLErrorSchema).optional()});var unifiedSearchStatusGraphQLResponseSchema=z3.object({data:z3.object({discoverySearchProgress:unifiedSearchProgressSchema.nullable().optional()}).nullable().optional(),errors:z3.array(graphQLErrorSchema).optional()});class CodeNavigationServiceImpl2{codeNavigationUrl;tokenProvider;fetchFn;runtime;constructor(codeNavigationUrl,tokenProvider,fetchFn=globalThis.fetch,runtime={}){this.codeNavigationUrl=codeNavigationUrl;this.tokenProvider=tokenProvider;this.fetchFn=fetchFn;this.runtime=runtime}async postGraphqlWithTargetResolutionFallback(input){const response=await postPkgseerGraphql({endpointUrl:this.codeNavigationUrl,token:input.token,query:input.query,variables:input.variables,timeoutMs:input.timeoutMs,signal:input.signal,fetchFn:this.fetchFn,clientHeaders:this.runtime.clientHeaders,userAgent:this.runtime.userAgent,diagnostics:this.runtime.diagnostics});if(response.status<200||response.status>=300)return response;if(!hasSchemaMismatchErrors(response.parsedBody))return response;for(const fallbackQuery of buildTargetResolutionFallbackQueries(input.query)){if(this.runtime.diagnostics?.isEnabled("code-nav")){this.runtime.diagnostics.debug("code-nav",{event:"target-resolution-query-fallback"})}const fallbackResponse=await postPkgseerGraphql({endpointUrl:this.codeNavigationUrl,token:input.token,query:fallbackQuery,variables:input.variables,timeoutMs:input.timeoutMs,signal:input.signal,fetchFn:this.fetchFn,clientHeaders:this.runtime.clientHeaders,userAgent:this.runtime.userAgent,diagnostics:this.runtime.diagnostics});if(!hasSchemaMismatchErrors(fallbackResponse.parsedBody)){return fallbackResponse}}return response}async search(params,options){return executeWithTokenRefresh({getToken:()=>this.tokenProvider.getToken(),forceRefresh:()=>this.tokenProvider.forceRefresh(),shouldRefresh:isTokenRefreshableError,executeWithToken:(token)=>this.executeUnifiedSearch(token,params,options)})}async searchStatus(searchRef,waitTimeoutMs=0,options){return executeWithTokenRefresh({getToken:()=>this.tokenProvider.getToken(),forceRefresh:()=>this.tokenProvider.forceRefresh(),shouldRefresh:isTokenRefreshableError,executeWithToken:(token)=>this.executeUnifiedSearchStatus(token,searchRef,waitTimeoutMs,options)})}async codeDiff(params){validateCodeDiffParams(params);return executeWithTokenRefresh({getToken:()=>this.tokenProvider.getToken(),forceRefresh:()=>this.tokenProvider.forceRefresh(),shouldRefresh:isTokenRefreshableError,executeWithToken:(token)=>this.executeCodeDiff(token,params)})}async executeCodeDiff(token,params){const query=buildCodeDiffQuery(params.mode);const variables=buildCodeDiffVariables(params);debugGraphqlWireRequest("codeDiff",query,variables,this.runtime.diagnostics);let response;try{response=await this.postGraphqlWithTargetResolutionFallback({token,query,variables})}catch(cause){if(cause instanceof PkgseerTransportError){throw this.createTransportError(cause)}throw cause}if(response.status<200||response.status>=300){throw this.createHttpError(response)}const parsed=codeDiffGraphQLResponseSchema.safeParse(response.parsedBody);if(!parsed.success){throw new MalformedCodeNavigationResponseError("Malformed response from code navigation service.")}const data=parsed.data.data?.codeDiff;const errors=parsed.data.errors??[];if(errors.length>0){const rawErrors=errors.filter(isCodeDiffRawError);if(rawErrors.length>0){throw new CodeDiffError2(rawErrors.map((error)=>error.message).join(", "),parseCodeDiffErrorDetails(rawErrors),data?normaliseCodeDiffPartial(data):undefined)}throw this.createCodeDiffRootError(errors)}if(!data?.raw){throw new MalformedCodeNavigationResponseError("CodeDiff response missing non-null raw result.")}return normaliseCodeDiffResult(data)}createCodeDiffRootError(errors){const graphQLErrors=errors.map(({message,extensions})=>({message,extensions}));const message=errors.map((error)=>error.message).join(", ");const extensions=getPrimaryExtensions(errors);const code=typeof extensions?.code==="string"?extensions.code:undefined;if(code==="AUTHENTICATION_REQUIRED"){return new AuthenticationError2(SERVER_AUTHENTICATION_REJECTED_MESSAGE,"server")}if(code==="UNAUTHORIZED"||code==="FORBIDDEN"||code==="FEATURE_FLAG_REQUIRED"||isClientUpdateRequiredGraphQLError({message,code})||isGraphQLSchemaMismatchError({message,code})||code===undefined&&isAuthMessage(message)){return this.createGraphQLError(graphQLErrors)}return new CodeDiffError2(message,parseCodeDiffErrorDetails(errors))}async executeUnifiedSearch(token,params,options){if(params.targets.length===0){throw new CodeNavigationValidationError("At least one search target is required.")}let response;const variables={targets:params.targets.map((target)=>({registry:target.registry,name:target.packageName,version:target.version,repoUrl:target.repoUrl,gitRef:target.gitRef,site:target.site})),query:params.query,sources:params.sources,filters:params.filters,allowPartialResults:params.allowPartialResults??false,limit:params.limit,offset:params.offset,waitTimeoutMs:params.waitTimeoutMs};debugUnifiedSearchRequest(variables,this.runtime.diagnostics);debugGraphqlWireRequest("search",UNIFIED_SEARCH_QUERY,variables,this.runtime.diagnostics);try{response=await this.postGraphqlWithTargetResolutionFallback({token,query:UNIFIED_SEARCH_QUERY,variables,timeoutMs:Math.max(DEFAULT_FETCH_TIMEOUT_MS,(params.waitTimeoutMs??0)+30000),signal:options?.signal})}catch(cause){if(cause instanceof PkgseerTransportError){throw this.createTransportError(cause)}throw cause}if(response.status<200||response.status>=300){throw this.createHttpError(response)}const parsed=unifiedSearchGraphQLResponseSchema.safeParse(response.parsedBody);if(!parsed.success){throw new MalformedCodeNavigationResponseError("Malformed response from code navigation service.")}if(parsed.data.errors&&parsed.data.errors.length>0){throw this.createGraphQLError(parsed.data.errors)}const data=parsed.data.data?.search;if(!data){throw new MalformedCodeNavigationResponseError("Malformed response from code navigation service.")}return this.normaliseUnifiedSearchOutcome(data)}async executeUnifiedSearchStatus(token,searchRef,waitTimeoutMs,options){let response;try{response=await this.postGraphqlWithTargetResolutionFallback({token,query:UNIFIED_SEARCH_STATUS_QUERY,timeoutMs:Math.max(DEFAULT_FETCH_TIMEOUT_MS,waitTimeoutMs+30000),signal:options?.signal,variables:{searchRef,includeResults:true,waitTimeoutMs}})}catch(cause){if(cause instanceof PkgseerTransportError){throw this.createTransportError(cause)}throw cause}if(response.status<200||response.status>=300){throw this.createHttpError(response)}const parsed=unifiedSearchStatusGraphQLResponseSchema.safeParse(response.parsedBody);if(!parsed.success){throw new MalformedCodeNavigationResponseError("Malformed response from code navigation service.")}if(parsed.data.errors&&parsed.data.errors.length>0){throw this.createGraphQLError(parsed.data.errors)}const data=parsed.data.data?.discoverySearchProgress;if(!data){throw new MalformedCodeNavigationResponseError("Malformed response from code navigation service.")}const progress=this.normaliseUnifiedSearchProgress(data);const result=data.results?this.normaliseUnifiedSearchResult(data.results):undefined;if(result&&progress.status==="COMPLETED"){return{state:"completed",completed:true,searchRef:progress.searchRef,result,progress}}return{state:"incomplete",completed:false,searchRef:progress.searchRef,result,progress}}createHttpError(response){return createCodeNavigationHttpError(response)}createTransportError(error){return createCodeNavigationTransportError(error)}createGraphQLError(errors){return createCodeNavigationGraphQLError(errors,this.runtime)}normaliseUnifiedSearchOutcome(data){const progress=data.progress?this.normaliseUnifiedSearchProgress(data.progress):undefined;if(data.completed){if(!data.result){throw new MalformedCodeNavigationResponseError("Completed unified search response missing result payload.")}return{state:"completed",completed:true,searchRef:data.searchRef??undefined,result:this.normaliseUnifiedSearchResult(data.result),progress}}const searchRef=data.searchRef??progress?.searchRef;if(!searchRef){throw new MalformedCodeNavigationResponseError("Incomplete unified search response missing search reference.")}const result=data.result?this.normaliseUnifiedSearchResult(data.result):undefined;return{state:"incomplete",completed:false,searchRef,result,progress}}normaliseUnifiedSearchResult(result){return{query:result.query,queryWarnings:result.queryWarnings,sources:result.sources,results:result.results.map((entry)=>({readTarget:entry.readTarget,id:entry.id,resultType:entry.resultType,targetLabel:entry.targetLabel,requestedTargetLabel:entry.requestedTargetLabel??undefined,freshTargetLabel:entry.freshTargetLabel??undefined,servedTargetLabel:entry.servedTargetLabel??undefined,freshness:entry.freshness??undefined,title:entry.title??undefined,score:entry.score??undefined,highlights:entry.highlights?{title:entry.highlights.title??undefined}:undefined,repositoryEvidence:entry.repositoryEvidence,documentationPreview:entry.documentationPreview,locator:normaliseUnifiedSearchLocator(entry.locator)})),page:{offset:result.page.offset,limit:result.page.limit,returned:result.page.returned,hasMore:result.page.hasMore},partialResults:result.partialResults,sourceStatus:result.sourceStatus.map((entry)=>({source:entry.source,targetLabel:entry.targetLabel,requestedTargetLabel:entry.requestedTargetLabel??undefined,freshTargetLabel:entry.freshTargetLabel??undefined,servedTargetLabel:entry.servedTargetLabel??undefined,targetResolution:normaliseTargetResolution(entry.targetResolution),indexingStatus:entry.indexingStatus??undefined,codeIndexState:entry.codeIndexState??undefined,resultCount:entry.resultCount??undefined,appliedFilters:entry.appliedFilters,ignoredFilters:entry.ignoredFilters,incompatibleFilters:entry.incompatibleFilters,appliedQueryFeatures:entry.appliedQueryFeatures,ignoredQueryFeatures:entry.ignoredQueryFeatures,incompatibleQueryFeatures:entry.incompatibleQueryFeatures,suggestedSiteTargets:entry.suggestedSiteTargets,suggestedSiteTargetsTruncated:entry.suggestedSiteTargetsTruncated,note:entry.note??undefined,coverage:normaliseDocCoverage(entry.coverage),contributors:entry.contributors.map((contributor)=>({kind:contributor.kind,state:contributor.state,freshness:contributor.freshness??undefined,resultCount:contributor.resultCount,repositoryUrl:contributor.repositoryUrl??undefined,commitSha:contributor.commitSha??undefined,siteKey:contributor.siteKey??undefined,siteUrl:contributor.siteUrl??undefined,coverage:normaliseDocCoverage(contributor.coverage,{preserveNone:true})}))})),evidenceNotice:result.evidenceNotice??undefined}}normaliseUnifiedSearchProgress(progress){return{searchRef:progress.searchRef,status:progress.status,targetsTotal:progress.targetsTotal,targetsReady:progress.targetsReady,elapsedMs:progress.elapsedMs,query:progress.query,queryWarnings:progress.queryWarnings,sources:progress.sources,requestedSources:progress.requestedSources??undefined,targetMode:normaliseTargetMode(progress.targetMode),requestedTargets:progress.requestedTargets?.map((target)=>({registry:target.registry?target.registry:undefined,name:target.name??undefined,version:target.version??undefined,repoUrl:target.repoUrl??undefined,gitRef:target.gitRef??undefined,site:target.site??undefined})),filters:normaliseProgressFilters(progress.filters),limit:progress.limit??undefined,offset:progress.offset??undefined,targets:progress.targets?.map((target)=>({requested:target.requested??undefined,resolvedRequested:target.resolvedRequested??undefined,served:target.served??undefined,freshness:target.freshness??undefined,indexingRef:target.indexingRef??undefined,requestedRefKind:normaliseRequestedRefKind(target.requestedRefKind),targetResolution:normaliseTargetResolution(target.targetResolution),availableVersions:normaliseAvailableVersions(target.availableVersions),availableRefs:normaliseAvailableVersions(target.availableRefs),suggestedRefs:normaliseAvailableVersions(target.suggestedRefs),coverage:normaliseDocCoverage(target.coverage)})),indexingEstimates:progress.indexingEstimates.map((entry)=>({kind:entry.kind,targets:entry.targets,repositoryUrl:entry.repositoryUrl??undefined,commitSha:entry.commitSha??undefined,estimate:normaliseIndexingDurationEstimate(entry.estimate),unavailableReason:entry.unavailableReason??undefined})),expiresAt:progress.expiresAt??undefined}}throwIfIndexing(data){throwIfCodeContextIndexing(data)}async listFiles(params){return executeWithTokenRefresh({getToken:()=>this.tokenProvider.getToken(),forceRefresh:()=>this.tokenProvider.forceRefresh(),shouldRefresh:isTokenRefreshableError,executeWithToken:(token)=>this.executeListFiles(token,params)})}async executeListFiles(token,params){let response;try{response=await this.postGraphqlWithTargetResolutionFallback({token,query:LIST_REPO_FILES_QUERY,variables:{registry:params.target.registry,packageName:params.target.packageName,repoUrl:params.target.repoUrl,gitRef:params.target.gitRef,version:params.target.version,pathPrefix:params.pathPrefix,pathSelectors:params.pathSelectors?.map((entry)=>({kind:entry.kind,value:entry.value})),extensions:params.extensions,fileTypes:params.fileTypes,languages:params.languages,fileIntent:params.fileIntent,fileIntents:params.fileIntents,excludeFileIntents:params.excludeFileIntents,excludeDocFiles:params.excludeDocFiles,excludeTestFiles:params.excludeTestFiles,includeHidden:params.includeHidden,limit:params.limit,waitTimeoutMs:params.waitTimeoutMs}})}catch(cause){if(cause instanceof PkgseerTransportError){throw this.createTransportError(cause)}throw cause}if(response.status<200||response.status>=300){throw this.createHttpError(response)}const parsed=listRepoFilesGraphQLResponseSchema.safeParse(response.parsedBody);if(!parsed.success){throw new MalformedCodeNavigationResponseError("Malformed response from code navigation service.")}if(parsed.data.errors&&parsed.data.errors.length>0){throw this.createGraphQLError(parsed.data.errors)}const data=parsed.data.data?.listRepoFiles;if(!data){throw new MalformedCodeNavigationResponseError("Malformed response from code navigation service.")}this.throwIfIndexing(data);return{files:data.files.map((entry)=>({path:entry.path,name:entry.name??undefined,language:entry.language??undefined,fileType:entry.fileType??undefined,byteSize:entry.byteSize??undefined})),total:data.total,hasMore:data.hasMore,indexedVersion:data.indexedVersion??undefined,resolution:data.resolution?{requestedVersion:data.resolution.requestedVersion??undefined,requestedRef:data.resolution.requestedRef??undefined,resolvedRef:data.resolution.resolvedRef??undefined,commitSha:data.resolution.commitSha??undefined}:undefined,targetResolution:normaliseTargetResolution(data.targetResolution),hint:data.diagnostics?.hint??undefined}}async readFile(params){return executeWithTokenRefresh({getToken:()=>this.tokenProvider.getToken(),forceRefresh:()=>this.tokenProvider.forceRefresh(),shouldRefresh:isTokenRefreshableError,executeWithToken:(token)=>this.executeReadFile(token,params)})}async executeReadFile(token,params){let response;try{response=await this.postGraphqlWithTargetResolutionFallback({token,query:FETCH_CODE_CONTEXT_QUERY,variables:{registry:params.target.registry,packageName:params.target.packageName,repoUrl:params.target.repoUrl,gitRef:params.target.gitRef,version:params.target.version,filePath:params.filePath,startLine:params.startLine,endLine:params.endLine,waitTimeoutMs:params.waitTimeoutMs}})}catch(cause){if(cause instanceof PkgseerTransportError){throw this.createTransportError(cause)}throw cause}if(response.status<200||response.status>=300){throw this.createHttpError(response)}const parsed=fetchCodeContextGraphQLResponseSchema.safeParse(response.parsedBody);if(!parsed.success){throw new MalformedCodeNavigationResponseError("Malformed response from code navigation service.")}if(parsed.data.errors&&parsed.data.errors.length>0){throw this.createGraphQLError(parsed.data.errors)}const data=parsed.data.data?.fetchCodeContext;if(!data){throw new MalformedCodeNavigationResponseError("Malformed response from code navigation service.")}this.throwIfIndexing(data);return normaliseCodeContextResult(data)}async grepRepo(params){return executeWithTokenRefresh({getToken:()=>this.tokenProvider.getToken(),forceRefresh:()=>this.tokenProvider.forceRefresh(),shouldRefresh:isTokenRefreshableError,executeWithToken:(token)=>this.executeGrepRepo(token,params)})}async executeGrepRepo(token,params){let response;try{response=await this.postGraphqlWithTargetResolutionFallback({token,query:buildGrepRepoQuery(params.symbolFields),variables:{registry:params.target.registry,packageName:params.target.packageName,repoUrl:params.target.repoUrl,gitRef:params.target.gitRef,version:params.target.version,waitTimeoutMs:params.waitTimeoutMs,pattern:params.pattern,patternType:params.patternType,caseSensitive:params.caseSensitive,pathSelectors:params.pathSelectors?.map((entry)=>({kind:entry.kind,value:entry.value})),extensions:params.extensions,excludeDocFiles:params.excludeDocFiles,excludeTestFiles:params.excludeTestFiles,allowUnscoped:params.allowUnscoped,contextLinesBefore:params.contextLinesBefore,contextLinesAfter:params.contextLinesAfter,maxMatches:params.maxMatches,maxMatchesPerFile:params.maxMatchesPerFile,cursor:params.cursor,symbolFields:params.symbolFields}})}catch(cause){if(cause instanceof PkgseerTransportError){throw this.createTransportError(cause)}throw cause}if(response.status<200||response.status>=300){throw this.createHttpError(response)}const parsed=grepRepoGraphQLResponseSchema.safeParse(response.parsedBody);if(!parsed.success){throw new MalformedCodeNavigationResponseError("Malformed response from code navigation service.")}if(parsed.data.errors&&parsed.data.errors.length>0){throw this.createGraphQLError(parsed.data.errors)}const data=parsed.data.data?.grepRepo;if(!data){throw new MalformedCodeNavigationResponseError("Malformed response from code navigation service.")}this.throwIfIndexing(data);return{matches:data.matches.map((entry)=>({filePath:entry.filePath,line:entry.line,matchStartByte:entry.matchStartByte,matchEndByte:entry.matchEndByte,lineContent:entry.lineContent,contextBefore:entry.contextBefore??undefined,contextAfter:entry.contextAfter??undefined,fileContentHash:entry.fileContentHash??undefined,fileIntent:entry.fileIntent??undefined,symbolRowId:entry.symbolRowId??undefined,symbol:entry.symbol?{symbolRef:entry.symbol.symbolRef,name:entry.symbol.name,qualifiedPath:entry.symbol.qualifiedPath??undefined,kind:entry.symbol.kind??undefined,category:entry.symbol.category??undefined,arity:entry.symbol.arity??undefined,isPublic:entry.symbol.isPublic??undefined,filePath:entry.symbol.filePath??undefined,startLine:entry.symbol.startLine??undefined,endLine:entry.symbol.endLine??undefined,contentHash:entry.symbol.contentHash??undefined,parentPath:entry.symbol.parentPath??undefined}:undefined})),nextCursor:data.nextCursor??undefined,hasMore:data.hasMore,truncatedReason:data.truncatedReason,routeTaken:data.routeTaken??undefined,filesScanned:data.filesScanned,filesInScope:data.filesInScope,binaryFilesSkipped:data.binaryFilesSkipped,filesTooLargeSkipped:data.filesTooLargeSkipped,totalMatches:data.totalMatches,uniqueFilesMatched:data.uniqueFilesMatched,indexedVersion:data.indexedVersion??undefined,resolution:data.resolution?{requestedVersion:data.resolution.requestedVersion??undefined,requestedRef:data.resolution.requestedRef??undefined,resolvedRef:data.resolution.resolvedRef??undefined,commitSha:data.resolution.commitSha??undefined}:undefined,targetResolution:normaliseTargetResolution(data.targetResolution)}}}function normaliseUnifiedSearchLocator(value){return{registry:value.registry??undefined,packageName:value.packageName??undefined,version:value.version??undefined,pageId:value.pageId??undefined,docsReadTarget:value.docsReadTarget??undefined,sourceKind:value.sourceKind??undefined,sourceUrl:value.sourceUrl??undefined,repoUrl:value.repoUrl??undefined,gitRef:value.gitRef??undefined,commitSha:value.commitSha??undefined,requestedRef:value.requestedRef??undefined,filePath:value.filePath??undefined,repositoryFilePath:value.repositoryFilePath??undefined,startLine:value.startLine??undefined,endLine:value.endLine??undefined,evidenceRange:value.evidenceRange?{startLine:value.evidenceRange.startLine,endLine:value.evidenceRange.endLine,matchLine:value.evidenceRange.matchLine??undefined,rangeKind:value.evidenceRange.rangeKind??undefined,matchSpansTruncated:value.evidenceRange.matchSpansTruncated}:undefined,indexedRange:value.indexedRange?{startLine:value.indexedRange.startLine,endLine:value.indexedRange.endLine}:undefined,symbolContext:value.symbolContext?normaliseUnifiedSearchSymbolContext(value.symbolContext):undefined,fileContentHash:value.fileContentHash??undefined,symbolRef:value.symbolRef??undefined,qualifiedPath:value.qualifiedPath??undefined,kind:value.kind??undefined,category:value.category??undefined,language:value.language??undefined}}function normaliseUnifiedSearchSymbolContext(value){const identity={name:value.name,qualifiedPath:value.qualifiedPath??undefined,kind:value.kind??undefined};if(value.relation==="ENCLOSES_MATCH"){return{...identity,relation:"encloses_match",definitionRange:normaliseUnifiedSearchDefinitionRange(value.definitionRange)}}return{...identity,relation:"associated_with_indexed_chunk",definitionRange:value.definitionRange?normaliseUnifiedSearchDefinitionRange(value.definitionRange):undefined}}function normaliseUnifiedSearchDefinitionRange(value){return{filePath:value.filePath,repositoryFilePath:value.repositoryFilePath,startLine:value.startLine,endLine:value.endLine}}function validateCodeDiffParams(params){const paramsRecord=asRecord(params);if(!paramsRecord){throw new CodeNavigationValidationError("CodeDiff params must be an object.")}if(paramsRecord.mode!=="inventory"&&paramsRecord.mode!=="stats"&&paramsRecord.mode!=="patches"){throw new CodeNavigationValidationError("CodeDiff mode must be inventory, stats, or patches.")}if(typeof paramsRecord.from!=="string"||paramsRecord.from.length===0){throw new CodeNavigationValidationError("CodeDiff from ref or version must not be empty.")}if(typeof paramsRecord.to!=="string"||paramsRecord.to.length===0){throw new CodeNavigationValidationError("CodeDiff to ref or version must not be empty.")}const target=asRecord(paramsRecord.target);if(!target){throw new CodeNavigationValidationError("CodeDiff target must be a package or repository target.")}if(Object.hasOwn(target,"registry")&&Object.hasOwn(target,"packageName")&&!Object.hasOwn(target,"repoUrl")){if(!codeDiffRegistrySchema.safeParse(target.registry).success){throw new CodeNavigationValidationError("CodeDiff package target has an unsupported registry.")}if(typeof target.packageName!=="string"||target.packageName.length===0){throw new CodeNavigationValidationError("CodeDiff package target name must not be empty.")}}else if(Object.hasOwn(target,"repoUrl")&&!Object.hasOwn(target,"registry")&&!Object.hasOwn(target,"packageName")){if(typeof target.repoUrl!=="string"||target.repoUrl.length===0){throw new CodeNavigationValidationError("CodeDiff repository target URL must not be empty.")}}else if((Object.hasOwn(target,"registry")||Object.hasOwn(target,"packageName"))&&Object.hasOwn(target,"repoUrl")){const conflictingKeys=["registry","packageName","repoUrl"].filter((key)=>Object.hasOwn(target,key)).join(", ");throw new CodeNavigationValidationError(`CodeDiff target has conflicting present keys: ${conflictingKeys}. Target shape is determined by key presence, even when a value is undefined.`)}else{throw new CodeNavigationValidationError("CodeDiff target must be a package or repository target.")}const optionsValue=paramsRecord.options;if(optionsValue===undefined)return;const options=asRecord(optionsValue);if(!options){throw new CodeNavigationValidationError("CodeDiff options must be an object when supplied.")}for(const key of Object.keys(options)){if(!CODE_DIFF_OPTION_KEYS.has(key)){throw new CodeNavigationValidationError(`CodeDiff options contains unknown key '${key}'.`)}}validateCodeDiffIntegerOption(options.maxFiles,"maxFiles",1,300);validateCodeDiffIntegerOption(options.maxPatchBytes,"maxPatchBytes",1024,2097152);validateCodeDiffPathOption(options.pathPrefix,"pathPrefix");validateCodeDiffPathOption(options.pathGlob,"pathGlob")}function validateCodeDiffIntegerOption(value,name,minimum,maximum){if(value===undefined)return;if(typeof value!=="number"||!Number.isInteger(value)||value<minimum||value>maximum){throw new CodeNavigationValidationError(`CodeDiff ${name} must be an integer from ${minimum} through ${maximum}.`)}}function validateCodeDiffPathOption(value,name){if(value===undefined)return;if(typeof value!=="string"){throw new CodeNavigationValidationError(`CodeDiff ${name} must be a string when supplied.`)}if(value.length===0){throw new CodeNavigationValidationError(`CodeDiff ${name} must not be empty when supplied.`)}if(new TextEncoder().encode(value).byteLength>1024){throw new CodeNavigationValidationError(`CodeDiff ${name} must be at most 1024 bytes.`)}}function buildCodeDiffVariables(params){const target=params.target;const variables={};if("registry"in target){variables.registry=target.registry;variables.name=target.packageName;variables.fromVersion=params.from;variables.toVersion=params.to}else{variables.repoUrl=target.repoUrl;variables.fromRef=params.from;variables.toRef=params.to}const rawOptions=Object.fromEntries(Object.entries(params.options??{}).filter(([,value])=>value!==undefined));if(Object.keys(rawOptions).length>0)variables.rawOptions=rawOptions;return variables}function isCodeDiffRawError(error){return error.path?.some((part)=>part==="raw")??false}function normaliseCodeDiffResult(result){if(!result.raw){throw new MalformedCodeNavigationResponseError("CodeDiff response missing non-null raw result.")}return{package:normaliseCodeDiffPackage(result.package),fromResolution:normaliseCodeDiffResolution(result.fromResolution),toResolution:normaliseCodeDiffResolution(result.toResolution),raw:normaliseRawCodeDiff(result.raw)}}function normaliseCodeDiffPartial(result){return{package:normaliseCodeDiffPackage(result.package),fromResolution:normaliseCodeDiffResolution(result.fromResolution),toResolution:normaliseCodeDiffResolution(result.toResolution),raw:result.raw?normaliseRawCodeDiff(result.raw):undefined}}function normaliseCodeDiffPackage(value){if(!value)return;return{registry:value.registry,name:value.name,repoUrl:value.repoUrl}}function normaliseCodeDiffResolution(value){return{requested:value.requested,resolvedVersion:value.resolvedVersion??undefined,ref:value.ref,commitSha:value.commitSha,refKind:value.refKind,versionSource:value.versionSource??undefined}}function normaliseRawCodeDiff(value){return{summary:value.summary,scope:{status:value.scope.status,fromSubpath:value.scope.fromSubpath??undefined,toSubpath:value.scope.toSubpath??undefined,pathPrefix:value.scope.pathPrefix??undefined,pathGlob:value.scope.pathGlob??undefined},contentCoverage:value.contentCoverage,contentFailure:value.contentFailure?{code:value.contentFailure.code,retryable:value.contentFailure.retryable,retryAfterMs:value.contentFailure.retryAfterMs??undefined,stage:value.contentFailure.stage??undefined,limitKind:value.contentFailure.limitKind??undefined}:undefined,files:value.files.map((file)=>({path:file.path,pathEncoding:file.pathEncoding,status:file.status,modeChanged:file.modeChanged,typeChanged:file.typeChanged,additions:file.additions??undefined,deletions:file.deletions??undefined,patch:file.patch??undefined,contentStatus:file.contentStatus,contentOmissionReason:file.contentOmissionReason??undefined,contentSafety:{filtered:file.contentSafety.filtered,modifications:file.contentSafety.modifications}})),hasMoreFiles:value.hasMoreFiles}}function parseCodeDiffErrorDetails(errors){const extensions=getPrimaryExtensions(errors);if(!extensions)return;const details={};if(typeof extensions.code==="string")details.code=extensions.code;if(typeof extensions.retryable==="boolean"){details.retryable=extensions.retryable}if(extensions.side==="from"||extensions.side==="to"){details.side=extensions.side}const publishedVersions=parseCodeDiffStringArray(extensions.published_versions);if(publishedVersions)details.publishedVersions=publishedVersions;if(typeof extensions.published_versions_truncated==="boolean"){details.publishedVersionsTruncated=extensions.published_versions_truncated}const availableVersions=parseCodeDiffErrorRefs(extensions.available_versions);if(availableVersions)details.availableVersions=availableVersions;if(typeof extensions.registry==="string"){details.registry=extensions.registry}if(typeof extensions.retry_after_ms==="number"&&Number.isInteger(extensions.retry_after_ms)&&extensions.retry_after_ms>=0){details.retryAfterMs=extensions.retry_after_ms}if(typeof extensions.stage==="string")details.stage=extensions.stage;if(typeof extensions.limit_kind==="string"){details.limitKind=extensions.limit_kind}if(typeof extensions.repo_url==="string"){details.repoUrl=extensions.repo_url}if(typeof extensions.git_ref==="string")details.gitRef=extensions.git_ref;const availableRefs=parseCodeDiffErrorRefs(extensions.available_refs);if(availableRefs)details.availableRefs=availableRefs;const suggestedRefs=parseCodeDiffErrorRefs(extensions.suggested_refs);if(suggestedRefs)details.suggestedRefs=suggestedRefs;const refKinds=parseCodeDiffStringArray(extensions.ref_kinds);if(refKinds)details.refKinds=refKinds;return Object.keys(details).length>0?details:undefined}function parseCodeDiffStringArray(value){if(!Array.isArray(value))return;if(value.some((entry)=>typeof entry!=="string"))return;return value}function parseCodeDiffErrorRefs(value){if(!Array.isArray(value))return;const refs=[];for(const entry of value){if(!entry||typeof entry!=="object"||Array.isArray(entry)){return}const record=entry;if(typeof record.ref!=="string"||record.version!==undefined&&record.version!==null&&typeof record.version!=="string"){return}refs.push({ref:record.ref,version:typeof record.version==="string"?record.version:undefined})}return refs}function createCodeNavigationHttpError(response){const status=response.status;const detail=parseHttpErrorDetail(response.responseBody,["detail","error"]);if(status===401){return new AuthenticationError2(SERVER_AUTHENTICATION_REJECTED_MESSAGE,"server")}if(status===403){return new CodeNavigationAccessError(detail??"Code navigation access denied.")}if(status>=500){return new CodeNavigationBackendError(detail?`Server error (${status}): ${detail}`:`Server error (${status})`,status)}return new CodeNavigationBackendError(detail??`Request failed with status ${status}`,status)}function createCodeNavigationTransportError(error){if(isFetchTimeoutError(error.cause)){return new CodeNavigationBackendError("Code navigation request timed out.",undefined,"TIMEOUT",true)}return new CodeNavigationNetworkError("Could not reach the code navigation service. Check your connection or set GITHITS_CODE_NAV_URL.",{cause:error})}function createCodeNavigationGraphQLError(errors,runtime={}){const message=errors.map((error)=>error.message).join(", ");const extensions=getPrimaryExtensions(errors);const code=typeof extensions?.code==="string"?extensions.code:undefined;const retryable=typeof extensions?.retryable==="boolean"?extensions.retryable:undefined;const indexingRef=getGraphQLIndexingRef(errors);const indexingEstimate=parseIndexingDurationEstimate(extensions);const errorMetadata=parseGraphQLErrorMetadata(extensions,indexingEstimate);if(isClientUpdateRequiredGraphQLError({message,code})){return new ClientUpdateRequiredError(undefined,undefined,runtime.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.";if(runtime.diagnostics?.isEnabled("code-nav")){runtime.diagnostics.debug("code-nav",{event:"graphql-schema-mismatch",code:code??"omitted",message})}return new CodeNavigationBackendError(runtime.diagnostics?.isEnabled("code-nav-wire")?message:sanitized,undefined,code,retryable)}switch(code){case"PACKAGE_INDEXING":return new CodeNavigationIndexingError(message,indexingRef,parseAvailableVersions(extensions),parseAvailableRefs(extensions),parseTargetResolution(extensions),indexingEstimate,appendIndexingWaitHint(message,typeof extensions?.hint==="string"?extensions.hint:undefined));case"GREP_PATTERN_TOO_SHORT":case"GREP_PATTERN_TOO_LONG":case"GREP_PATTERN_INVALID":case"GREP_INVALID_REGEX":case"GREP_UNSUPPORTED_PATTERN":case"GREP_PATTERN_TOO_UNSELECTIVE":case"GREP_SCOPE_REQUIRED":case"GREP_SELECTOR_INVALID":case"GREP_CURSOR_INVALID":case"GREP_CONTEXT_TOO_LARGE":case"GREP_CONTEXT_NEGATIVE":case"GREP_MAX_MATCHES_TOO_LARGE":case"GREP_MAX_MATCHES_INVALID":return new CodeNavigationValidationError(message);case"VERSION_NOT_FOUND":return new CodeNavigationVersionNotFoundError(message,typeof extensions?.package==="string"?extensions.package:undefined,typeof extensions?.requested_version==="string"?extensions.requested_version:undefined,typeof extensions?.latest_indexed==="string"?extensions.latest_indexed:undefined,parseAvailableVersions(extensions),errorMetadata);case"REF_NOT_FOUND":return new CodeNavigationRefNotFoundError(message,parseGraphQLRepoUrl(extensions),parseGraphQLGitRef(extensions),parseAvailableRefs(extensions),parseSuggestedRefs(extensions),errorMetadata);case"NOT_FOUND":case"PACKAGE_NOT_FOUND":case"NO_REPOSITORY_URL":return new CodeNavigationTargetNotFoundError(message,parseAvailableVersions(extensions),parseGraphQLRepoUrl(extensions),parseGraphQLGitRef(extensions),errorMetadata);case"REPOSITORY_NOT_FOUND":return new CodeNavigationTargetNotFoundError(message,undefined,parseGraphQLRepoUrl(extensions),parseGraphQLGitRef(extensions),errorMetadata);case"FILE_NOT_FOUND":return new CodeNavigationFileNotFoundError(message,typeof extensions?.file_path==="string"?extensions.file_path:typeof extensions?.filePath==="string"?extensions.filePath:undefined);case"UNSUPPORTED_REGISTRY":case"VALIDATION_ERROR":return new CodeNavigationValidationError(message);case"FEATURE_FLAG_REQUIRED":return new CodeNavigationFeatureFlagRequiredError(message);case"AUTHENTICATION_REQUIRED":case"UNAUTHORIZED":return new AuthenticationError2(SERVER_AUTHENTICATION_REJECTED_MESSAGE,"server");case"FORBIDDEN":return new CodeNavigationAccessError("Code navigation access denied. This feature may not be enabled for your account.");case"UPSTREAM_ERROR":case"TIMEOUT":case"RATE_LIMITED":case"GREP_FILE_TOO_LARGE":case"GREP_TIMEOUT":case"GREP_SERVICE_UNAVAILABLE":case"GREP_FAILED":case"GREP_INDEX_NOT_AVAILABLE":case"FILE_PATH_EXCLUDED":case"SOURCE_FILE_INVENTORY_UNKNOWN":case"INTERNAL_ERROR":case"UNKNOWN_ERROR":return new CodeNavigationBackendError(message,undefined,code,retryable,errorMetadata);default:break}if(code===undefined){if(isAuthMessage(message)){return new CodeNavigationAccessError("Code navigation access denied. This feature may not be enabled for your account.")}if(isUnresolvableMessage(message)){return new CodeNavigationUnresolvableError(message)}if(isTargetNotFoundMessage(message)){return new CodeNavigationTargetNotFoundError(message,parseAvailableVersions(extensions),parseGraphQLRepoUrl(extensions),parseGraphQLGitRef(extensions),errorMetadata)}}return new CodeNavigationBackendError(message,undefined,code,retryable,errorMetadata)}function buildTargetResolutionFallbackQueries(query){const withoutSuggestedRefs=query.replaceAll(TARGET_RESOLUTION_SUGGESTED_REFS_SELECTION,"").replaceAll(DISCOVERY_TARGET_PROGRESS_SUGGESTED_REFS_SELECTION,"");const candidates=[withoutSuggestedRefs,withoutSuggestedRefs.replaceAll(TARGET_RESOLUTION_AVAILABLE_REFS_SELECTION,""),withoutSuggestedRefs.replaceAll(DISCOVERY_TARGET_PROGRESS_RETRY_SELECTION,""),withoutSuggestedRefs.replaceAll(CODE_CONTEXT_AVAILABLE_VERSIONS_SELECTION,""),withoutSuggestedRefs.replaceAll(TARGET_RESOLUTION_SELECTION,"").replaceAll(DISCOVERY_TARGET_PROGRESS_RETRY_SELECTION,"").replaceAll(CODE_CONTEXT_AVAILABLE_VERSIONS_SELECTION,"")];return candidates.filter((candidate,index,all)=>candidate!==query&&all.indexOf(candidate)===index)}function hasSchemaMismatchErrors(parsedBody){if(!parsedBody||typeof parsedBody!=="object")return false;const errors=parsedBody.errors;if(!Array.isArray(errors))return false;return errors.some((entry)=>{if(!entry||typeof entry!=="object")return false;const error=entry;if(typeof error.message!=="string")return false;const code=typeof error.extensions?.code==="string"?error.extensions.code:undefined;return isGraphQLSchemaMismatchError({message:error.message,code})})}function getPrimaryExtensions(errors){for(const error of errors){if(error.extensions&&Object.keys(error.extensions).length>0){return error.extensions}}return}function getGraphQLIndexingRef(errors){for(const error of errors){const indexingRef=error.extensions?.indexing_ref??error.extensions?.indexingRef;if(typeof indexingRef==="string")return indexingRef}return}function parseAvailableVersions(extensions){const raw=extensions?.available_versions??extensions?.availableVersions;return parseAvailableArtifacts(raw)}function parseAvailableRefs(extensions){const raw=extensions?.available_refs??extensions?.availableRefs;return parseAvailableArtifacts(raw)}function parseSuggestedRefs(extensions){const raw=extensions?.suggested_refs??extensions?.suggestedRefs;return parseAvailableArtifacts(raw)}function parseGraphQLErrorMetadata(extensions,indexingEstimate){const metadata={};if(typeof extensions?.hint==="string")metadata.hint=extensions.hint;const filePath=extensions?.file_path??extensions?.filePath;if(typeof filePath==="string")metadata.filePath=filePath;const exclusionReason=extensions?.exclusion_reason??extensions?.exclusionReason;if(typeof exclusionReason==="string"){metadata.exclusionReason=exclusionReason}const availableVersions=parseAvailableVersions(extensions);if(availableVersions?.length)metadata.availableVersions=availableVersions;const availableRefs=parseAvailableRefs(extensions);if(availableRefs?.length)metadata.availableRefs=availableRefs;const suggestedRefs=parseSuggestedRefs(extensions);if(suggestedRefs?.length)metadata.suggestedRefs=suggestedRefs;const targetResolution=parseTargetResolution(extensions);if(targetResolution)metadata.targetResolution=targetResolution;if(indexingEstimate)metadata.indexingEstimate=indexingEstimate;return Object.keys(metadata).length>0?metadata:undefined}function parseGraphQLRepoUrl(extensions){return typeof extensions?.repo_url==="string"?extensions.repo_url:typeof extensions?.repoUrl==="string"?extensions.repoUrl:undefined}function parseGraphQLGitRef(extensions){return typeof extensions?.git_ref==="string"?extensions.git_ref:typeof extensions?.gitRef==="string"?extensions.gitRef:undefined}function parseTargetResolution(extensions){const raw=extensions?.target_resolution??extensions?.targetResolution;const parsed=targetResolutionSchema.safeParse(raw);if(!parsed.success)return;return normaliseTargetResolution(parsed.data)}function parseIndexingDurationEstimate(extensions){const raw=extensions?.estimated_indexing_duration??extensions?.estimatedIndexingDuration??extensions?.indexing_estimate??extensions?.indexingEstimate;const parsed=indexingDurationEstimateSchema.safeParse(normaliseRawIndexingDurationEstimate(raw));if(!parsed.success)return;return normaliseIndexingDurationEstimate(parsed.data)}function normaliseRawIndexingDurationEstimate(raw){if(!raw||typeof raw!=="object"||Array.isArray(raw))return raw;const record=raw;return{lowerSeconds:record.lowerSeconds??record.lower_seconds,upperSeconds:record.upperSeconds??record.upper_seconds,elapsedSeconds:record.elapsedSeconds??record.elapsed_seconds,sampleCount:record.sampleCount??record.sample_count,source:record.source}}function normaliseCodeContextResult(data){return{filePath:data.filePath??undefined,language:data.language??undefined,totalLines:data.totalLines??undefined,startLine:data.startLine??undefined,endLine:data.endLine??undefined,content:data.content??undefined,isBinary:data.isBinary??undefined,targetResolution:normaliseTargetResolution(data.targetResolution),availableVersions:normaliseAvailableVersions(data.availableVersions)}}function throwIfCodeContextIndexing(data){if(data.codeIndexState!=="INDEXING")return;const targetResolution=normaliseTargetResolution(data.targetResolution);const indexingEstimate=normaliseIndexingDurationEstimate(data.indexingEstimate);throw new CodeNavigationIndexingError(`Target is indexing. ${INDEXING_WAIT_HINT}`,data.indexingRef??targetResolution?.indexingRef,normaliseAvailableVersions(data.availableVersions)??targetResolution?.availableVersions,targetResolution?.availableRefs,targetResolution,indexingEstimate)}function parseCodeContextResult(data){const parsed=codeContextResponseSchema.safeParse(data);if(!parsed.success){throw new MalformedCodeNavigationResponseError("Malformed response from code navigation service.")}throwIfCodeContextIndexing(parsed.data);return normaliseCodeContextResult(parsed.data)}function normaliseIndexingDurationEstimate(estimate){if(!estimate)return;const out={};if(typeof estimate.lowerSeconds==="number"){out.lowerSeconds=estimate.lowerSeconds}if(typeof estimate.upperSeconds==="number"){out.upperSeconds=estimate.upperSeconds}if(typeof estimate.elapsedSeconds==="number"){out.elapsedSeconds=estimate.elapsedSeconds}if(typeof estimate.sampleCount==="number"){out.sampleCount=estimate.sampleCount}if(typeof estimate.source==="string")out.source=estimate.source;return Object.keys(out).length>0?out:undefined}function appendIndexingWaitHint(message,backendHint){const hintAlreadyInMessage=Boolean(backendHint&&message.includes(backendHint));const existingGuidance=`${message} ${backendHint??""}`;if(/(?:--wait\b|wait_timeout_ms|waitTimeoutMs)/i.test(existingGuidance)){return hintAlreadyInMessage?undefined:backendHint}return backendHint&&!hintAlreadyInMessage?`${backendHint} ${INDEXING_WAIT_HINT}`:INDEXING_WAIT_HINT}function parseAvailableArtifacts(raw){if(!Array.isArray(raw))return;const parsed=[];for(const item of raw){if(item&&typeof item==="object"&&"ref"in item){const entry=item;if(typeof entry.ref==="string"){parsed.push({ref:entry.ref,version:typeof entry.version==="string"?entry.version:undefined})}}}return parsed.length>0?parsed:undefined}function normaliseAvailableVersions(entries){if(!entries||entries.length===0)return;return entries.map((entry)=>({version:entry.version??undefined,ref:entry.ref}))}function normaliseTargetResolution(resolution){if(!resolution)return;return{requested:normaliseTargetResolutionIdentity(resolution.requested),resolvedRequested:normaliseTargetResolutionIdentity(resolution.resolvedRequested),served:normaliseTargetResolutionIdentity(resolution.served),freshness:resolution.freshness??undefined,freshnessReason:resolution.freshnessReason??undefined,indexingRef:resolution.indexingRef??undefined,availableVersions:normaliseAvailableVersions(resolution.availableVersions)??[],availableRefs:normaliseAvailableVersions(resolution.availableRefs)??[],suggestedRefs:normaliseAvailableVersions(resolution.suggestedRefs)??[]}}function normaliseDocCoverage(coverage,options={}){if(!coverage)return;if(coverage.coverageState==="NONE"&&!options.preserveNone){return}const out={coverageState:coverage.coverageState};if(coverage.coverageReason)out.coverageReason=coverage.coverageReason;if(typeof coverage.pagesCrawled==="number"){out.pagesCrawled=coverage.pagesCrawled}if(typeof coverage.frontierRemaining==="number"||coverage.frontierRemaining===null){out.frontierRemaining=coverage.frontierRemaining}if(typeof coverage.artifactOverflowPageCount==="number"){out.artifactOverflowPageCount=coverage.artifactOverflowPageCount}if(typeof coverage.estimatedTotalPages==="number"){out.estimatedTotalPages=coverage.estimatedTotalPages}if(coverage.note)out.note=coverage.note;return out}function normaliseTargetResolutionIdentity(identity){if(!identity)return;const out={};if(identity.kind)out.kind=identity.kind;if(identity.registry)out.registry=identity.registry;if(identity.packageName)out.packageName=identity.packageName;if(identity.version)out.version=identity.version;if(identity.repoUrl)out.repoUrl=identity.repoUrl;if(identity.gitRef)out.gitRef=identity.gitRef;if(identity.commitSha)out.commitSha=identity.commitSha;if(identity.site)out.site=identity.site;return Object.keys(out).length>0?out:undefined}function isAuthMessage(message){const lower=message.toLowerCase();return lower.includes("unauthorized")||lower.includes("forbidden")||lower.includes("permission")||lower.includes("authentication")}function normaliseTargetMode(value){if(value==="PACKAGES"||value==="REPO"||value==="MIXED"||value==="SITES"||value==="SITE"){return value}return}function normaliseRequestedRefKind(value){switch(value){case"OMITTED_VERSION":case"LATEST_VERSION":case"EXACT_VERSION":case"DEFAULT_BRANCH":case"HEAD":case"BRANCH":case"SHA":return value;default:return}}function normaliseProgressFilters(filters){if(!filters)return;const out={};if(filters.fileIntent)out.fileIntent=filters.fileIntent;if(filters.kind)out.kind=filters.kind;if(filters.category)out.category=filters.category;if(typeof filters.publicOnly==="boolean"){out.publicOnly=filters.publicOnly}if(filters.pathPrefix)out.pathPrefix=filters.pathPrefix;return Object.keys(out).length>0?out:undefined}function isTargetNotFoundMessage(message){const lower=message.toLowerCase();return lower.includes("not found")||lower.includes("unknown package")||lower.includes("no such package")||lower.includes("does not exist")}function isUnresolvableMessage(message){const lower=message.toLowerCase();return lower.includes("could not resolve")||lower.includes("cannot resolve")}import{z as z4}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=z4.enum(["COMPLETE","RESUMABLE_LIMIT","NON_RESUMABLE_PARTIAL","FAILED","CURSOR_EXPIRED"]);var corpus=z4.enum(["SOURCE","DOCUMENTATION","ALL"]);var nonnegativeInt=z4.number().int().nonnegative();var nullableString=z4.string().nullable();var lineSlice=z4.object({content:z4.string(),startByte:nonnegativeInt,endByte:nonnegativeInt,originalLineBytes:nonnegativeInt});var readAction=z4.object({target:z4.string(),path:nullableString,startLine:z4.number().int().positive(),endLine:z4.number().int().positive()});var modifications=z4.array(z4.enum(["INVISIBLE_CONTROLS_STRIPPED","HTML_COMMENTS_STRIPPED","IMAGES_REPLACED","UNSAFE_LINKS_NEUTRALIZED"]));function resultSchema(detailed){const selected=(schema)=>detailed?schema:schema.optional();const safety=z4.object({filtered:z4.boolean(),modifications:selected(modifications)});const common={targetIndex:nonnegativeInt,line:z4.number().int().positive(),lineSlice,contextBeforeSlices:z4.array(lineSlice),contextAfterSlices:z4.array(lineSlice),read:readAction,contentSafety:safety,lineContent:selected(z4.string()),matchStartByte:nonnegativeInt,matchEndByte:nonnegativeInt,sourceMatchStartByte:selected(nonnegativeInt),sourceMatchEndByte:selected(nonnegativeInt)};return z4.object({hits:z4.array(z4.discriminatedUnion("__typename",[z4.object({...common,__typename:z4.literal("GrepRepositoryHit"),read:readAction.extend({path:z4.string()}),filePath:z4.string(),repoUrl:selected(z4.string()),commitSha:selected(z4.string()),repositoryFilePath:selected(z4.string())}),z4.object({...common,__typename:z4.literal("GrepSiteHit"),read:readAction.extend({path:z4.null()}),pageUrl:z4.string()})])),targets:z4.array(z4.object({targetIndex:nonnegativeInt,requestedInputIndices:z4.array(nonnegativeInt),kind:z4.enum(["REPOSITORY","SITE"]),target:z4.string(),traversal,readiness:z4.enum(["UNSPECIFIED","CURRENT","STALE","NOT_AVAILABLE","MISSING_REF","READER_OPEN_FAILED","INCOMPLETE","RESOURCE_LIMIT","VERSION_UNSUPPORTED","READ_FAILED"]),errorCode:nullableString,retryable:z4.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:z4.array(z4.object({filePath:z4.string(),contentSafety:safety,code:z4.string(),line:nonnegativeInt,lineBytes:selected(nonnegativeInt),matchStartByte:selected(nonnegativeInt.nullable()),matchEndByte:selected(nonnegativeInt.nullable())})).nullable(),repoUrl:nullableString,canonicalSite:nullableString,urlPrefixes:selected(z4.array(z4.string()))})),unavailableTargets:z4.array(z4.object({inputIndex:nonnegativeInt,target:z4.string(),reason:z4.string(),retryable:z4.boolean(),progressRef:nullableString,suggestedSiteTargets:z4.array(z4.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(
703
- $targets: [GrepTargetInput!]!, $pattern: String!, $patternType: GrepPatternType,
704
- $caseSensitive: Boolean, $contextLinesBefore: Int, $contextLinesAfter: Int,
705
- $maxMatches: Int, $cursor: String, $waitTimeoutMs: Int, $includeDetailedFields: Boolean!
706
- ) {
707
- grep(targets: $targets, pattern: $pattern, patternType: $patternType,
708
- caseSensitive: $caseSensitive, contextLinesBefore: $contextLinesBefore,
709
- contextLinesAfter: $contextLinesAfter, maxMatches: $maxMatches,
710
- cursor: $cursor, waitTimeoutMs: $waitTimeoutMs) {
711
- traversal nextCursor totalMatches
712
- hits {
713
- __typename
714
- ... on GrepRepositoryHit {
715
- filePath
716
- repoUrl @include(if: $includeDetailedFields)
717
- commitSha @include(if: $includeDetailedFields)
718
- repositoryFilePath @include(if: $includeDetailedFields)
719
- ...RepositoryMatch
720
- }
721
- ... on GrepSiteHit { pageUrl ...SiteMatch }
722
- }
723
- targets {
724
- targetIndex requestedInputIndices kind target traversal readiness errorCode retryable publicMessage
725
- requestedRef commitSha corpus filesScanned filesInScope binaryFilesSkipped filesTooLargeSkipped fileIssuesOmitted
726
- repoUrl canonicalSite
727
- urlPrefixes @include(if: $includeDetailedFields)
728
- fileIssues {
729
- filePath code line contentSafety { filtered modifications @include(if: $includeDetailedFields) }
730
- lineBytes @include(if: $includeDetailedFields)
731
- matchStartByte @include(if: $includeDetailedFields)
732
- matchEndByte @include(if: $includeDetailedFields)
733
- }
734
- }
735
- unavailableTargets { inputIndex target reason retryable progressRef suggestedSiteTargets }
736
- }
737
- }
738
- fragment RepositoryMatch on GrepRepositoryHit {
739
- targetIndex line lineSlice { ...LineSlice } contextBeforeSlices { ...LineSlice } contextAfterSlices { ...LineSlice }
740
- read: readTarget { target path startLine endLine } contentSafety { filtered modifications @include(if: $includeDetailedFields) }
741
- lineContent @include(if: $includeDetailedFields)
742
- matchStartByte matchEndByte
743
- sourceMatchStartByte @include(if: $includeDetailedFields) sourceMatchEndByte @include(if: $includeDetailedFields)
744
- }
745
- fragment SiteMatch on GrepSiteHit {
746
- targetIndex line lineSlice { ...LineSlice } contextBeforeSlices { ...LineSlice } contextAfterSlices { ...LineSlice }
747
- read: readTarget { target path startLine endLine } contentSafety { filtered modifications @include(if: $includeDetailedFields) }
748
- lineContent @include(if: $includeDetailedFields)
749
- matchStartByte matchEndByte
750
- sourceMatchStartByte @include(if: $includeDetailedFields) sourceMatchEndByte @include(if: $includeDetailedFields)
751
- }
752
- fragment LineSlice on GrepRepoLineSlice { content startByte endByte originalLineBytes }`;var graphQLResponse=z4.object({data:z4.object({grep:z4.unknown().optional()}).nullable().optional(),errors:z4.array(z4.object({message:z4.string(),extensions:z4.record(z4.string(),z4.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 z5}from"zod";class ListAccessError2 extends Error{constructor(message){super(message);this.name="ListAccessError"}}class ListGraphQLError2 extends Error{code;retryable;repoUrl;commitSha;indexingRef;hint;constructor(message,code,retryable,repoUrl,commitSha,indexingRef,hint){super(message);this.code=code;this.retryable=retryable;this.repoUrl=repoUrl;this.commitSha=commitSha;this.indexingRef=indexingRef;this.hint=hint;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=z5.string().nullable();var optionalNullableString=nullableString2.optional();var nullableInt=z5.number().int().nullable();var optionalNullableInt=nullableInt.optional();var listReadActionSchema=z5.object({target:z5.string().min(1),path:nullableString2}).nullable();var listBrowseActionSchema=z5.object({target:z5.string(),paths:z5.array(z5.string()).nullable()}).nullable();var listEntrySchema=z5.object({kind:z5.enum(["FILE","PAGE","DIRECTORY"]),path:z5.string(),title:optionalNullableString,language:optionalNullableString,fileType:optionalNullableString,intent:optionalNullableString,byteSize:optionalNullableInt,lineCount:optionalNullableInt,contentHash:optionalNullableString,read:listReadActionSchema.optional(),browse:listBrowseActionSchema.optional()});var availableVersionSchema2=z5.object({version:nullableString2,ref:z5.string()});var resolutionSchema=z5.object({requestedVersion:nullableString2,requestedRef:nullableString2,resolvedRef:nullableString2,commitSha:nullableString2});var targetIdentitySchema=z5.object({kind:nullableString2,registry:nullableString2,packageName:nullableString2,version:nullableString2,repoUrl:nullableString2,gitRef:nullableString2,commitSha:nullableString2});var targetResolutionSchema2=z5.object({requested:targetIdentitySchema.nullable(),resolvedRequested:targetIdentitySchema.nullable(),served:targetIdentitySchema.nullable(),freshness:nullableString2,freshnessReason:nullableString2,indexingRef:nullableString2,availableVersions:z5.array(availableVersionSchema2).nullable(),availableRefs:z5.array(availableVersionSchema2).nullable(),suggestedRefs:z5.array(availableVersionSchema2).nullable()});var indexingEstimateSchema=z5.object({lowerSeconds:nullableInt,upperSeconds:nullableInt,elapsedSeconds:nullableInt,sampleCount:nullableInt,source:nullableString2});var sitePreparationSchema=z5.object({selected:z5.number().int(),enqueued:z5.number().int(),activeJobs:z5.array(z5.object({mode:nullableString2,state:z5.string()})),awaited:z5.array(z5.object({mode:nullableString2,outcome:z5.enum(["COMPLETED","DISCARDED","CANCELLED","TIMEOUT"])}))}).nullable();var listResultSchema=z5.object({inventoryKind:z5.enum(["SOURCE","SITE"]),requestedTarget:z5.string(),canonicalTarget:nullableString2,entries:z5.array(listEntrySchema),hasMore:z5.boolean(),nextCursor:nullableString2,indexedVersion:nullableString2,resolution:resolutionSchema.nullable().optional(),targetResolution:targetResolutionSchema2.nullable().optional(),codeIndexState:nullableString2,indexingStatus:nullableString2,indexingRef:nullableString2,availableVersions:z5.array(availableVersionSchema2).nullable().optional(),indexingEstimate:indexingEstimateSchema.nullable().optional(),inventoryState:z5.enum(["AVAILABLE","EMPTY"]).nullable(),crawlStatus:z5.enum(["IDLE","RUNNING","COMPLETE","FAILED"]).nullable(),coverageState:z5.enum(["NONE","PARTIAL","CAPPED","COMPLETE"]).nullable(),coverageReason:nullableString2,preparation:sitePreparationSchema});var graphQLErrorSchema2=z5.object({message:z5.string(),extensions:z5.record(z5.string(),z5.unknown()).optional()});var listGraphQLResponseSchema=z5.object({data:z5.object({list:z5.unknown().nullable().optional()}).nullable().optional(),errors:z5.array(graphQLErrorSchema2).optional()});var LIST_QUERY=`
753
- query List(
754
- $target: String!
755
- $paths: [String!]
756
- $recursive: Boolean
757
- $fileTypes: [String!]
758
- $languages: [String!]
759
- $intents: [FileIntent!]
760
- $limit: Int
761
- $after: String
762
- $waitTimeoutMs: Int
763
- $includeDetailedFields: Boolean!
764
- $includeReadActions: Boolean!
765
- ) {
766
- list(
767
- target: $target
768
- paths: $paths
769
- recursive: $recursive
770
- fileTypes: $fileTypes
771
- languages: $languages
772
- intents: $intents
773
- limit: $limit
774
- after: $after
775
- waitTimeoutMs: $waitTimeoutMs
776
- ) {
777
- inventoryKind
778
- requestedTarget
779
- canonicalTarget
780
- entries {
781
- kind
782
- path
783
- title @include(if: $includeDetailedFields)
784
- language @include(if: $includeDetailedFields)
785
- fileType @include(if: $includeDetailedFields)
786
- intent @include(if: $includeDetailedFields)
787
- byteSize @include(if: $includeDetailedFields)
788
- lineCount @include(if: $includeDetailedFields)
789
- contentHash @include(if: $includeDetailedFields)
790
- read: readTarget @include(if: $includeReadActions) {
791
- target
792
- path
793
- }
794
- browse @include(if: $includeDetailedFields) {
795
- target
796
- paths
797
- }
798
- }
799
- hasMore
800
- nextCursor
801
- indexedVersion
802
- resolution @include(if: $includeDetailedFields) {
803
- requestedVersion
804
- requestedRef
805
- resolvedRef
806
- commitSha
807
- }
808
- targetResolution @include(if: $includeDetailedFields) {
809
- requested {
810
- kind
811
- registry
812
- packageName
813
- version
814
- repoUrl
815
- gitRef
816
- commitSha
817
- }
818
- resolvedRequested {
819
- kind
820
- registry
821
- packageName
822
- version
823
- repoUrl
824
- gitRef
825
- commitSha
826
- }
827
- served {
828
- kind
829
- registry
830
- packageName
831
- version
832
- repoUrl
833
- gitRef
834
- commitSha
835
- }
836
- freshness
837
- freshnessReason
838
- indexingRef
839
- availableVersions {
840
- version
841
- ref
842
- }
843
- availableRefs {
844
- version
845
- ref
846
- }
847
- suggestedRefs {
848
- version
849
- ref
850
- }
851
- }
852
- codeIndexState
853
- indexingStatus
854
- indexingRef
855
- availableVersions @include(if: $includeDetailedFields) {
856
- version
857
- ref
858
- }
859
- indexingEstimate @include(if: $includeDetailedFields) {
860
- lowerSeconds
861
- upperSeconds
862
- elapsedSeconds
863
- sampleCount
864
- source
865
- }
866
- inventoryState
867
- crawlStatus
868
- coverageState
869
- coverageReason
870
- preparation {
871
- selected
872
- enqueued
873
- activeJobs {
874
- mode
875
- state
876
- }
877
- awaited {
878
- mode
879
- outcome
880
- }
881
- }
882
- }
883
- }`;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,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)}import{z as z6}from"zod";function promoteGenericVersionNotFound(error,params){if(!(error instanceof PackageIntelligenceBackendError))return error;if(error.graphqlCode!==undefined)return error;const requestedVersion=pickRequestedVersion(params);if(!requestedVersion)return error;if(!/no matching version/i.test(error.message))return error;const qualifiedName=synthesizeQualifiedName(params);return new PackageIntelligenceVersionNotFoundError(error.message,qualifiedName,requestedVersion,undefined)}function pickRequestedVersion(params){if(params.version)return params.version;if(params.fromVersion)return params.fromVersion;if(params.toVersion)return params.toVersion;return}function synthesizeQualifiedName(params){if(!params.registry||!params.packageName)return;return`${params.registry.toLowerCase()}:${params.packageName}`}class PackageIntelligenceAccessError extends Error{constructor(message){super(message);this.name="PackageIntelligenceAccessError"}}class PackageIntelligenceFeatureFlagRequiredError extends Error{constructor(message){super(message);this.name="PackageIntelligenceFeatureFlagRequiredError"}}class PackageIntelligenceNetworkError extends Error{constructor(message,options){super(message,options);this.name="PackageIntelligenceNetworkError"}}class PackageIntelligenceBackendError extends Error{status;graphqlCode;retryable;constructor(message,status,graphqlCode,retryable){super(message);this.status=status;this.graphqlCode=graphqlCode;this.retryable=retryable;this.name="PackageIntelligenceBackendError"}}class PackageIntelligenceGraphQLError extends Error{code;constructor(message,code){super(message);this.code=code;this.name="PackageIntelligenceGraphQLError"}}class PackageIntelligenceTargetNotFoundError extends Error{constructor(message){super(message);this.name="PackageIntelligenceTargetNotFoundError"}}class PackageIntelligenceValidationError extends Error{constructor(message){super(message);this.name="PackageIntelligenceValidationError"}}class PackageIntelligenceDocumentationSectionUnresolvedError extends Error{reason;constructor(message,reason){super(message);this.reason=reason;this.name="PackageIntelligenceDocumentationSectionUnresolvedError"}}class PackageIntelligenceVersionNotFoundError extends Error{packageName;requestedVersion;availableVersions;constructor(message,packageName,requestedVersion,availableVersions){super(message);this.packageName=packageName;this.requestedVersion=requestedVersion;this.availableVersions=availableVersions;this.name="PackageIntelligenceVersionNotFoundError"}}class MalformedPackageIntelligenceResponseError extends Error{constructor(message){super(message);this.name="MalformedPackageIntelligenceResponseError"}}var githubRepositorySchema=z6.object({stargazersCount:z6.number().int().nullable().optional(),forksCount:z6.number().int().nullable().optional(),openIssuesCount:z6.number().int().nullable().optional(),archived:z6.boolean().nullable().optional(),language:z6.string().nullable().optional(),topics:z6.array(z6.string()).nullable().optional(),pushedAt:z6.string().nullable().optional()}).nullable().optional();var packageIdentitySchema=z6.object({name:z6.string().nullable().optional(),registry:z6.string().nullable().optional(),description:z6.string().nullable().optional(),latestVersion:z6.string().nullable().optional(),latestVersionPublishedAt:z6.string().nullable().optional(),versionCount:z6.number().int().nullable().optional(),downloadsRefreshedAt:z6.string().nullable().optional(),homepage:z6.string().nullable().optional(),repositoryUrl:z6.string().nullable().optional(),license:z6.string().nullable().optional(),downloadsLastMonth:z6.number().int().nullable().optional(),downloadsTotal:z6.number().int().nullable().optional(),githubRepository:githubRepositorySchema});var vulnerabilityOverviewSchema=z6.object({osvId:z6.string().nullable().optional(),summary:z6.string().nullable().optional(),severityScore:z6.number().nullable().optional(),publishedAt:z6.string().nullable().optional()});var packageSecurityOverviewSchema=z6.object({vulnerabilityCount:z6.number().int().nullable().optional(),allVulnerabilityCount:z6.number().int(),hasCurrentVulnerabilities:z6.boolean().nullable().optional(),recentVulnerabilities:z6.array(vulnerabilityOverviewSchema).nullable().optional()}).nullable().optional();var changelogEntrySchema=z6.object({version:z6.string().nullable().optional(),publishedAt:z6.string().nullable().optional(),body:z6.string().nullable().optional()});var packageSummaryResponseSchema=z6.object({package:packageIdentitySchema.nullable().optional(),security:packageSecurityOverviewSchema,latestChangelogs:z6.array(changelogEntrySchema).nullable().optional()});var graphQLErrorSchema3=z6.object({message:z6.string(),extensions:z6.record(z6.string(),z6.unknown()).optional()});var graphQLResponseSchema=z6.object({data:z6.object({packageSummary:packageSummaryResponseSchema.nullable().optional()}).nullable().optional(),errors:z6.array(graphQLErrorSchema3).optional()});var PACKAGE_SUMMARY_QUERY=`
884
- query PackageSummary(
885
- $registry: Registry!
886
- $name: String!
887
- $includeVerboseFields: Boolean! = true
888
- ) {
889
- packageSummary(registry: $registry, name: $name) {
890
- package {
891
- name
892
- registry
893
- description
894
- latestVersion
895
- latestVersionPublishedAt
896
- homepage
897
- repositoryUrl
898
- license
899
- downloadsLastMonth
900
- downloadsTotal
901
- versionCount @include(if: $includeVerboseFields)
902
- downloadsRefreshedAt @include(if: $includeVerboseFields)
903
- githubRepository {
904
- stargazersCount
905
- forksCount
906
- openIssuesCount
907
- archived
908
- language @include(if: $includeVerboseFields)
909
- topics @include(if: $includeVerboseFields)
910
- pushedAt @include(if: $includeVerboseFields)
911
- }
912
- }
913
- security {
914
- vulnerabilityCount
915
- allVulnerabilityCount
916
- hasCurrentVulnerabilities
917
- recentVulnerabilities @include(if: $includeVerboseFields) {
918
- osvId
919
- summary
920
- severityScore
921
- publishedAt
922
- }
923
- }
924
- latestChangelogs(limit: 3) @include(if: $includeVerboseFields) {
925
- version
926
- publishedAt
927
- body
928
- }
929
- }
930
- }`;var packageVersionIdentitySchema=z6.object({name:z6.string().nullable().optional(),registry:z6.string().nullable().optional(),version:z6.string().nullable().optional(),publishedAt:z6.string().nullable().optional(),deprecated:z6.boolean().nullable().optional(),deprecationReason:z6.string().nullable().optional()});var vulnerabilityDetailSchema=z6.object({osvId:z6.string().nullable().optional(),summary:z6.string().nullable().optional(),severityScore:z6.number().nullable().optional(),severityType:z6.string().nullable().optional(),affectedVersionRanges:z6.array(z6.string()).nullable().optional(),affectedVersionRangesCount:z6.number().int(),affectedVersionRangesTruncated:z6.boolean(),fixedInVersions:z6.array(z6.string()).nullable().optional(),publishedAt:z6.string().nullable().optional(),modifiedAt:z6.string().nullable().optional(),withdrawnAt:z6.string().nullable().optional(),aliases:z6.array(z6.string()).nullable().optional(),isMalicious:z6.boolean().nullable().optional(),affectsInspectedVersion:z6.boolean(),matchedAffectedVersionRanges:z6.array(z6.string()),duplicateIds:z6.array(z6.string())});var pageInfoSchema=z6.object({hasNextPage:z6.boolean(),endCursor:z6.string().nullable().optional(),totalCount:z6.number().int()});var vulnerabilityAdvisoryPageSchema=z6.object({entries:z6.array(vulnerabilityDetailSchema),pageInfo:pageInfoSchema});var vulnerabilitySecurityDetailsSchema=z6.object({affectedVulnerabilityCount:z6.number().int(),nonAffectingVulnerabilityCount:z6.number().int(),allVulnerabilityCount:z6.number().int(),currentVersionAffected:z6.boolean().nullable().optional(),advisories:vulnerabilityAdvisoryPageSchema,upgradePaths:z6.array(z6.string()).nullable().optional()}).nullable().optional();var vulnerabilityReportResponseSchema=z6.object({package:packageVersionIdentitySchema.nullable().optional(),security:vulnerabilitySecurityDetailsSchema});var vulnerabilitiesGraphQLResponseSchema=z6.object({data:z6.object({packageVulnerabilities:vulnerabilityReportResponseSchema.nullable().optional()}).nullable().optional(),errors:z6.array(graphQLErrorSchema3).optional()});var transitiveAuditAdvisorySchema=z6.object({osvId:z6.string().nullable().optional(),summary:z6.string().nullable().optional(),severityScore:z6.number().nullable().optional(),affectedVersionRanges:z6.array(z6.string()).nullable().optional(),fixedInVersions:z6.array(z6.string()).nullable().optional(),publishedAt:z6.string().nullable().optional(),modifiedAt:z6.string().nullable().optional(),aliases:z6.array(z6.string()).nullable().optional(),isMalicious:z6.boolean().nullable().optional()});var transitiveAuditOccurrenceSchema=z6.object({version:z6.string(),affectsResolvedVersion:z6.boolean(),matchedAffectedVersionRanges:z6.array(z6.string()),fixVersionsAboveResolved:z6.array(z6.string()),nearestFixedVersion:z6.string().nullable().optional(),advisory:transitiveAuditAdvisorySchema});var transitiveAuditPackageSchema=z6.object({registry:z6.string(),name:z6.string(),selectedCount:z6.number().int().nonnegative(),advisoryOccurrences:z6.array(transitiveAuditOccurrenceSchema).nullable().optional()});var transitiveAuditSummarySchema=z6.object({selected:z6.object({totalVulnerabilities:z6.number().int().nonnegative()}),totalPackagesAnalyzed:z6.number().int().nonnegative(),packages:z6.array(transitiveAuditPackageSchema),calculatedAt:z6.string().nullable().optional()});var transitiveAuditResponseSchema=z6.object({package:packageVersionIdentitySchema.nullable().optional(),dependencies:z6.object({transitive:z6.object({vulnerabilitySummary:transitiveAuditSummarySchema.nullable().optional()}).nullable().optional()}).nullable().optional()});var transitiveAuditGraphQLResponseSchema=z6.object({data:z6.object({packageDependencies:transitiveAuditResponseSchema.nullable().optional()}).nullable().optional(),errors:z6.array(graphQLErrorSchema3).optional()});var PACKAGE_VULNERABILITIES_QUERY=`
931
- query PackageVulnerabilities(
932
- $registry: Registry!
933
- $name: String!
934
- $version: String
935
- $minSeverity: Float
936
- $includeWithdrawn: Boolean
937
- $scope: VulnerabilityScope = AFFECTED
938
- $after: String
939
- ) {
940
- packageVulnerabilities(
941
- registry: $registry
942
- name: $name
943
- version: $version
944
- minSeverity: $minSeverity
945
- includeWithdrawn: $includeWithdrawn
946
- ) {
947
- package {
948
- name
949
- registry
950
- version
951
- }
952
- security {
953
- affectedVulnerabilityCount
954
- nonAffectingVulnerabilityCount
955
- allVulnerabilityCount
956
- currentVersionAffected
957
- upgradePaths
958
- advisories(scope: $scope, first: 100, after: $after) {
959
- entries {
960
- osvId
961
- summary
962
- severityScore
963
- severityType
964
- affectedVersionRanges
965
- affectedVersionRangesCount
966
- affectedVersionRangesTruncated
967
- fixedInVersions
968
- publishedAt
969
- modifiedAt
970
- withdrawnAt
971
- aliases
972
- isMalicious
973
- affectsInspectedVersion
974
- matchedAffectedVersionRanges
975
- duplicateIds
976
- }
977
- pageInfo {
978
- hasNextPage
979
- endCursor
980
- totalCount
981
- }
982
- }
983
- }
984
- }
985
- }`;var TRANSITIVE_AUDIT_SCOPE_FIELDS={AFFECTED:{summary:"affected",packageCount:"affectedCount"},NON_AFFECTING:{summary:"nonAffecting",packageCount:"nonAffectingCount"},ALL:{summary:"combined",packageCount:"totalCount"}};function buildPackageTransitiveVulnerabilityAuditQuery(scope){const fields=TRANSITIVE_AUDIT_SCOPE_FIELDS[scope];return`
986
- query PackageTransitiveVulnerabilityAudit(
987
- $registry: Registry!
988
- $name: String!
989
- $version: String!
990
- $minSeverity: Float
991
- $scope: VulnerabilityScope!
992
- $includeTransitiveAdvisoryDetails: Boolean! = false
993
- ) {
994
- packageDependencies(
995
- registry: $registry
996
- name: $name
997
- version: $version
998
- includeTransitive: true
999
- ) {
1000
- package {
1001
- name
1002
- registry
1003
- version
1004
- }
1005
- dependencies {
1006
- transitive {
1007
- vulnerabilitySummary(minSeverity: $minSeverity) {
1008
- selected: ${fields.summary} {
1009
- totalVulnerabilities
1010
- }
1011
- totalPackagesAnalyzed
1012
- calculatedAt
1013
- packages {
1014
- registry
1015
- name
1016
- selectedCount: ${fields.packageCount}
1017
- advisoryOccurrences(scope: $scope, minSeverity: $minSeverity) {
1018
- version
1019
- affectsResolvedVersion
1020
- matchedAffectedVersionRanges
1021
- fixVersionsAboveResolved
1022
- nearestFixedVersion
1023
- advisory {
1024
- osvId
1025
- summary
1026
- severityScore
1027
- affectedVersionRanges @include(if: $includeTransitiveAdvisoryDetails)
1028
- fixedInVersions @include(if: $includeTransitiveAdvisoryDetails)
1029
- publishedAt
1030
- modifiedAt
1031
- aliases
1032
- isMalicious
1033
- }
1034
- }
1035
- }
1036
- }
1037
- }
1038
- }
1039
- }
1040
- }`}var directDependencySchema=z6.object({name:z6.string().nullable().optional(),versionConstraint:z6.string().nullable().optional(),type:z6.string().nullable().optional()});var dependencyGraphNodeSchema=z6.object({registry:z6.string(),name:z6.string(),version:z6.string().nullable().optional()});var dependencyGraphEdgeSchema=z6.object({fromIndex:z6.number().int().nullable().optional(),toIndex:z6.number().int(),constraint:z6.string().nullable().optional(),dependencyType:z6.string().nullable().optional()});var dependencyGraphSchema=z6.object({formatVersion:z6.number().int(),nodes:z6.array(dependencyGraphNodeSchema),edges:z6.array(dependencyGraphEdgeSchema)});var vulnerabilityCountSummarySchema=z6.object({totalVulnerabilities:z6.number().int(),critical:z6.number().int(),high:z6.number().int(),medium:z6.number().int(),low:z6.number().int(),unknown:z6.number().int()});var vulnerabilitySummaryDetailSchema=z6.object({osvId:z6.string().nullable().optional(),registry:z6.string().nullable().optional(),packageName:z6.string().nullable().optional(),summary:z6.string().nullable().optional(),severityScore:z6.number().nullable().optional(),severityType:z6.string().nullable().optional(),affectedVersionRanges:z6.array(z6.string()).nullable().optional(),fixedInVersions:z6.array(z6.string()).nullable().optional(),publishedAt:z6.string().nullable().optional(),modifiedAt:z6.string().nullable().optional(),withdrawnAt:z6.string().nullable().optional(),aliases:z6.array(z6.string()).nullable().optional(),isMalicious:z6.boolean().nullable().optional()});var transitiveDependencyVulnerabilitySchema=z6.object({version:z6.string(),affectsResolvedVersion:z6.boolean(),matchedAffectedVersionRanges:z6.array(z6.string()),fixVersionsAboveResolved:z6.array(z6.string()),nearestFixedVersion:z6.string().nullable().optional(),advisory:vulnerabilitySummaryDetailSchema});var transitiveVulnerablePackageSchema=z6.object({registry:z6.string(),name:z6.string(),versions:z6.array(z6.string()),affectedCount:z6.number().int(),nonAffectingCount:z6.number().int(),totalCount:z6.number().int(),maxSeverityScore:z6.number().nullable().optional(),maxSeverityLabel:z6.string().nullable().optional(),advisoryIds:z6.array(z6.string()),mostCritical:vulnerabilitySummaryDetailSchema.nullable().optional(),advisoryOccurrences:z6.array(transitiveDependencyVulnerabilitySchema).nullable().optional()});var transitiveVulnerabilitySummarySchema=z6.object({affected:vulnerabilityCountSummarySchema,nonAffecting:vulnerabilityCountSummarySchema,combined:vulnerabilityCountSummarySchema,totalPackagesAnalyzed:z6.number().int(),affectedPackageCount:z6.number().int(),packages:z6.array(transitiveVulnerablePackageSchema),calculatedAt:z6.string().nullable().optional()}).nullable().optional();var dependencyDeprecationReasonSchema=z6.object({version:z6.string(),reason:z6.string().nullable().optional()});var deprecatedDependencySchema=z6.object({registry:z6.string(),name:z6.string(),versions:z6.array(z6.string()),reasons:z6.array(dependencyDeprecationReasonSchema)});var outdatedDependencyVersionSchema=z6.object({version:z6.string(),severity:z6.string()});var outdatedDependencySchema=z6.object({registry:z6.string(),name:z6.string(),latestVersion:z6.string().nullable().optional(),severity:z6.string(),versions:z6.array(outdatedDependencyVersionSchema),repositoryUrl:z6.string().nullable().optional()});var duplicateDependencySchema=z6.object({registry:z6.string().nullable().optional(),name:z6.string(),versions:z6.array(z6.string())});var dependencyConflictEdgeSchema=z6.object({fromIndex:z6.number().int().nullable().optional(),toIndex:z6.number().int(),versionConstraint:z6.string(),dependencyType:z6.string()});var dependencyConflictSchema=z6.object({packageName:z6.string(),requiredVersions:z6.array(z6.string()),conflictingEdges:z6.array(dependencyConflictEdgeSchema)});var dependencyIssueConflictSchema=z6.object({registry:z6.string().nullable().optional(),name:z6.string(),versions:z6.array(z6.string()),requiredVersions:z6.array(z6.string()),conflictingEdges:z6.array(dependencyConflictEdgeSchema)});var dependencyIssuesSummarySchema=z6.object({totalCount:z6.number().int(),deprecatedCount:z6.number().int(),outdatedCount:z6.number().int(),duplicateCount:z6.number().int(),conflictCount:z6.number().int(),deprecatedPackages:z6.array(deprecatedDependencySchema),outdatedPackages:z6.array(outdatedDependencySchema),duplicatePackages:z6.array(duplicateDependencySchema),conflicts:z6.array(dependencyIssueConflictSchema)}).nullable().optional();var circularDependencyCycleSchema=z6.object({cycleStart:z6.string(),circularPath:z6.array(z6.string()),displayChain:z6.string()});var environmentMarkerSchema=z6.object({type:z6.string().nullable().optional(),value:z6.string().nullable().optional(),raw:z6.string().nullable().optional()});var transitiveDependencySchema=z6.object({totalEdges:z6.number().int().nullable().optional(),uniquePackagesCount:z6.number().int().nullable().optional(),uniqueDependencies:z6.array(z6.string()).nullable().optional(),dependencyConflicts:z6.array(dependencyConflictSchema).nullable().optional(),circularDependencyCycles:z6.array(circularDependencyCycleSchema).nullable().optional(),dependencyGraph:dependencyGraphSchema.nullable().optional(),vulnerabilitySummary:transitiveVulnerabilitySummarySchema,dependencyIssues:dependencyIssuesSummarySchema}).nullable().optional();var dependencyBundleSchema=z6.object({direct:z6.array(directDependencySchema).nullable().optional(),transitive:transitiveDependencySchema}).nullable().optional();var groupDependencySchema=z6.object({name:z6.string(),constraint:z6.string().nullable().optional()});var dependencyGroupSchema=z6.object({name:z6.string(),lifecycle:z6.string(),conditionType:z6.string(),conditionValue:z6.string().nullable().optional(),selectionMode:z6.string(),exclusiveGroup:z6.string().nullable().optional(),fallbackPriority:z6.number().int().nullable().optional(),compatibleWith:z6.array(z6.string()).nullable().optional(),defaultEnabled:z6.boolean().nullable().optional(),dependencies:z6.array(groupDependencySchema)});var dependencyGroupsInfoSchema=z6.object({primaryGroup:z6.string().nullable().optional(),environmentMarkers:z6.array(environmentMarkerSchema).nullable().optional(),groups:z6.array(dependencyGroupSchema)}).nullable().optional();var dependencyReportResponseSchema=z6.object({package:packageVersionIdentitySchema.nullable().optional(),dependencies:dependencyBundleSchema,dependencyGroups:dependencyGroupsInfoSchema});var dependenciesGraphQLResponseSchema=z6.object({data:z6.object({packageDependencies:dependencyReportResponseSchema.nullable().optional()}).nullable().optional(),errors:z6.array(graphQLErrorSchema3).optional()});var PACKAGE_DEPENDENCIES_QUERY=`
1041
- query PackageDependencies(
1042
- $registry: Registry!
1043
- $name: String!
1044
- $version: String
1045
- $includeTransitive: Boolean
1046
- $includeTransitiveDetails: Boolean! = true
1047
- $includeDependencyGraph: Boolean! = true
1048
- $includeGroups: Boolean! = true
1049
- $includeDependencyIssues: Boolean! = false
1050
- $maxDepth: Int
1051
- $lifecycle: [String!]
1052
- ) {
1053
- packageDependencies(
1054
- registry: $registry
1055
- name: $name
1056
- version: $version
1057
- includeTransitive: $includeTransitive
1058
- maxDepth: $maxDepth
1059
- lifecycle: $lifecycle
1060
- ) {
1061
- package {
1062
- name
1063
- registry
1064
- version
1065
- }
1066
- dependencies {
1067
- # Backend-side summary block intentionally not selected — our
1068
- # envelope computes runtime.count client-side from direct[].length
1069
- # so the invariant runtime.count === runtime.items.length always
1070
- # holds regardless of backend-side drift.
1071
- direct {
1072
- name
1073
- versionConstraint
1074
- type
1075
- }
1076
- transitive {
1077
- totalEdges @include(if: $includeTransitiveDetails)
1078
- uniquePackagesCount @include(if: $includeTransitiveDetails)
1079
- uniqueDependencies @include(if: $includeTransitiveDetails)
1080
- dependencyConflicts @include(if: $includeTransitiveDetails) {
1081
- packageName
1082
- requiredVersions
1083
- conflictingEdges {
1084
- fromIndex
1085
- toIndex
1086
- versionConstraint
1087
- dependencyType
1088
- }
1089
- }
1090
- circularDependencyCycles @include(if: $includeTransitiveDetails) {
1091
- cycleStart
1092
- circularPath
1093
- displayChain
1094
- }
1095
- dependencyGraph @include(if: $includeDependencyGraph) {
1096
- formatVersion
1097
- nodes {
1098
- registry
1099
- name
1100
- version
1101
- }
1102
- edges {
1103
- fromIndex
1104
- toIndex
1105
- constraint
1106
- dependencyType
1107
- }
1108
- }
1109
- dependencyIssues @include(if: $includeDependencyIssues) {
1110
- totalCount
1111
- deprecatedCount
1112
- outdatedCount
1113
- duplicateCount
1114
- conflictCount
1115
- deprecatedPackages {
1116
- registry
1117
- name
1118
- versions
1119
- reasons {
1120
- version
1121
- reason
1122
- }
1123
- }
1124
- outdatedPackages {
1125
- registry
1126
- name
1127
- latestVersion
1128
- severity
1129
- versions {
1130
- version
1131
- severity
1132
- }
1133
- repositoryUrl
1134
- }
1135
- duplicatePackages {
1136
- registry
1137
- name
1138
- versions
1139
- }
1140
- conflicts {
1141
- registry
1142
- name
1143
- versions
1144
- requiredVersions
1145
- conflictingEdges {
1146
- fromIndex
1147
- toIndex
1148
- versionConstraint
1149
- dependencyType
1150
- }
1151
- }
1152
- }
1153
- }
1154
- }
1155
- dependencyGroups @include(if: $includeGroups) {
1156
- primaryGroup
1157
- environmentMarkers {
1158
- type
1159
- value
1160
- raw
1161
- }
1162
- groups {
1163
- name
1164
- lifecycle
1165
- conditionType
1166
- conditionValue
1167
- selectionMode
1168
- exclusiveGroup
1169
- fallbackPriority
1170
- compatibleWith
1171
- defaultEnabled
1172
- dependencies {
1173
- name
1174
- constraint
1175
- }
1176
- }
1177
- }
1178
- }
1179
- }`;var PACKAGE_UPGRADE_DEPENDENCY_PROBE_QUERY=`
1180
- query PackageUpgradeDependencyProbe(
1181
- $registry: Registry!
1182
- $name: String!
1183
- $version: String!
1184
- $includeTransitiveRisk: Boolean!
1185
- $includeTransitiveSecurity: Boolean!
1186
- $includeDependencyIssues: Boolean!
1187
- $includeDependencyChanges: Boolean!
1188
- $includeGroups: Boolean!
1189
- $lifecycle: [String!]
1190
- $minSeverity: Float
1191
- ) {
1192
- packageDependencies(
1193
- registry: $registry
1194
- name: $name
1195
- version: $version
1196
- includeTransitive: $includeTransitiveRisk
1197
- lifecycle: $lifecycle
1198
- ) {
1199
- package {
1200
- name
1201
- registry
1202
- version
1203
- publishedAt
1204
- deprecated
1205
- deprecationReason
1206
- }
1207
- dependencies {
1208
- direct {
1209
- name
1210
- versionConstraint
1211
- type
1212
- }
1213
- transitive @include(if: $includeTransitiveRisk) {
1214
- dependencyGraph @include(if: $includeDependencyChanges) {
1215
- formatVersion
1216
- nodes {
1217
- registry
1218
- name
1219
- version
1220
- }
1221
- edges {
1222
- fromIndex
1223
- toIndex
1224
- constraint
1225
- dependencyType
1226
- }
1227
- }
1228
- vulnerabilitySummary(minSeverity: $minSeverity) @include(if: $includeTransitiveSecurity) {
1229
- affected {
1230
- totalVulnerabilities
1231
- critical
1232
- high
1233
- medium
1234
- low
1235
- unknown
1236
- }
1237
- nonAffecting {
1238
- totalVulnerabilities
1239
- critical
1240
- high
1241
- medium
1242
- low
1243
- unknown
1244
- }
1245
- combined {
1246
- totalVulnerabilities
1247
- critical
1248
- high
1249
- medium
1250
- low
1251
- unknown
1252
- }
1253
- totalPackagesAnalyzed
1254
- affectedPackageCount
1255
- calculatedAt
1256
- packages {
1257
- registry
1258
- name
1259
- versions
1260
- affectedCount
1261
- nonAffectingCount
1262
- totalCount
1263
- maxSeverityScore
1264
- maxSeverityLabel
1265
- advisoryIds(scope: AFFECTED)
1266
- mostCritical {
1267
- osvId
1268
- registry
1269
- packageName
1270
- summary
1271
- severityScore
1272
- severityType
1273
- affectedVersionRanges
1274
- fixedInVersions
1275
- publishedAt
1276
- modifiedAt
1277
- withdrawnAt
1278
- aliases
1279
- isMalicious
1280
- }
1281
- advisoryOccurrences(scope: AFFECTED, minSeverity: $minSeverity, limit: 5) {
1282
- version
1283
- affectsResolvedVersion
1284
- matchedAffectedVersionRanges
1285
- fixVersionsAboveResolved
1286
- nearestFixedVersion
1287
- advisory {
1288
- osvId
1289
- registry
1290
- packageName
1291
- summary
1292
- severityScore
1293
- severityType
1294
- affectedVersionRanges
1295
- fixedInVersions
1296
- publishedAt
1297
- modifiedAt
1298
- withdrawnAt
1299
- aliases
1300
- isMalicious
1301
- }
1302
- }
1303
- }
1304
- }
1305
- dependencyIssues @include(if: $includeDependencyIssues) {
1306
- totalCount
1307
- deprecatedCount
1308
- outdatedCount
1309
- duplicateCount
1310
- conflictCount
1311
- deprecatedPackages {
1312
- registry
1313
- name
1314
- versions
1315
- reasons {
1316
- version
1317
- reason
1318
- }
1319
- }
1320
- outdatedPackages {
1321
- registry
1322
- name
1323
- latestVersion
1324
- severity
1325
- versions {
1326
- version
1327
- severity
1328
- }
1329
- repositoryUrl
1330
- }
1331
- duplicatePackages {
1332
- registry
1333
- name
1334
- versions
1335
- }
1336
- conflicts {
1337
- registry
1338
- name
1339
- versions
1340
- requiredVersions
1341
- conflictingEdges {
1342
- fromIndex
1343
- toIndex
1344
- versionConstraint
1345
- dependencyType
1346
- }
1347
- }
1348
- }
1349
- }
1350
- }
1351
- dependencyGroups @include(if: $includeGroups) {
1352
- primaryGroup
1353
- environmentMarkers {
1354
- type
1355
- value
1356
- raw
1357
- }
1358
- groups {
1359
- name
1360
- lifecycle
1361
- conditionType
1362
- conditionValue
1363
- selectionMode
1364
- exclusiveGroup
1365
- fallbackPriority
1366
- compatibleWith
1367
- defaultEnabled
1368
- dependencies {
1369
- name
1370
- constraint
1371
- }
1372
- }
1373
- }
1374
- }
1375
- }`;var packageUpgradeAdvisorySchema=z6.object({id:z6.string().nullable().optional(),aliases:z6.array(z6.string()),summary:z6.string().nullable().optional(),severity:z6.number().nullable().optional(),severityLabel:z6.string().nullable().optional(),fixedIn:z6.array(z6.string()),isMalicious:z6.boolean().nullable().optional()});var packageUpgradeVersionVulnerabilitySummarySchema=z6.object({version:z6.string(),publishedAt:z6.string().nullable().optional(),deprecated:z6.boolean().nullable().optional(),deprecationReason:z6.string().nullable().optional(),affectedCount:z6.number().int(),nonAffectingCount:z6.number().int(),allCount:z6.number().int(),lastModifiedAt:z6.string().nullable().optional(),advisories:z6.array(packageUpgradeAdvisorySchema)}).nullable().optional();var packageUpgradeTransitivePackagePageSchema=z6.object({entries:z6.array(z6.object({id:z6.string(),registry:z6.string(),name:z6.string(),versions:z6.array(z6.string()),affectedCount:z6.number().int(),maxSeverityScore:z6.number().nullable().optional(),maxSeverityLabel:z6.string().nullable().optional(),advisoryIds:z6.array(z6.string())})),totalCount:z6.number().int(),truncated:z6.boolean()});var packageUpgradeTransitiveSecuritySchema=z6.object({currentAffected:z6.number().int(),targetAffected:z6.number().int(),introducedPackages:z6.array(z6.string()),fixedPackages:z6.array(z6.string()),introducedPackageDetails:packageUpgradeTransitivePackagePageSchema,fixedPackageDetails:packageUpgradeTransitivePackagePageSchema,stillAffectedPackageDetails:packageUpgradeTransitivePackagePageSchema}).nullable().optional();var packageUpgradeSecuritySchema=z6.object({current:packageUpgradeVersionVulnerabilitySummarySchema,target:packageUpgradeVersionVulnerabilitySummarySchema,added:z6.array(packageUpgradeAdvisorySchema),removed:z6.array(packageUpgradeAdvisorySchema),notAddressed:z6.array(packageUpgradeAdvisorySchema),fixed:z6.array(packageUpgradeAdvisorySchema),introduced:z6.array(packageUpgradeAdvisorySchema),unchanged:z6.array(packageUpgradeAdvisorySchema),transitive:packageUpgradeTransitiveSecuritySchema});var packageUpgradeChangelogEntrySchema=z6.object({version:z6.string().nullable().optional(),publishedAt:z6.string().nullable().optional(),htmlUrl:z6.string().nullable().optional(),body:z6.string().nullable().optional(),bodyPreview:z6.string().nullable().optional(),headline:z6.string().nullable().optional(),signals:z6.array(z6.string())});var packageUpgradeChangelogSchema=z6.object({source:z6.string().nullable().optional(),fallback:z6.string().nullable().optional(),entries:z6.array(packageUpgradeChangelogEntrySchema),sampledEntries:z6.array(packageUpgradeChangelogEntrySchema),keywordEntries:z6.array(packageUpgradeChangelogEntrySchema),totalKeywordEntries:z6.number().int(),totalEntries:z6.number().int(),totalEntriesWithBodies:z6.number().int(),truncated:z6.boolean(),hasReleaseNoteBodies:z6.boolean(),breakingSignals:z6.array(z6.string()),migrationSignals:z6.array(z6.string())});var packageUpgradeCompatibilitySchema=z6.object({peerDependencyChanges:z6.array(z6.string()),notes:z6.array(z6.string())}).nullable().optional();var packageUpgradeDependencyChangeItemSchema=z6.object({name:z6.string(),registry:z6.string().nullable().optional(),version:z6.string().nullable().optional(),fromVersions:z6.array(z6.string()),toVersions:z6.array(z6.string()),constraint:z6.string().nullable().optional(),type:z6.string().nullable().optional()});var packageUpgradeDependencyChangeGroupSchema=z6.object({added:z6.array(packageUpgradeDependencyChangeItemSchema),removed:z6.array(packageUpgradeDependencyChangeItemSchema),changed:z6.array(packageUpgradeDependencyChangeItemSchema)});var packageUpgradeDependencyChangesSchema=z6.object({direct:packageUpgradeDependencyChangeGroupSchema,transitive:packageUpgradeDependencyChangeGroupSchema}).nullable().optional();var packageUpgradeDependencyIssuesSchema=z6.object({currentTotal:z6.number().int(),targetTotal:z6.number().int(),introducedDeprecated:z6.array(z6.string()),introducedDuplicates:z6.array(z6.string()),introducedConflicts:z6.array(z6.string()),introducedOutdated:z6.array(z6.string())}).nullable().optional();var packageUpgradeReviewSchema=z6.object({registry:z6.string(),name:z6.string(),currentVersion:z6.string(),targetVersion:z6.string(),latestVersion:z6.string().nullable().optional(),versionDelta:z6.string(),security:packageUpgradeSecuritySchema,changelog:packageUpgradeChangelogSchema,compatibility:packageUpgradeCompatibilitySchema,dependencyChanges:packageUpgradeDependencyChangesSchema,dependencyIssues:packageUpgradeDependencyIssuesSchema,unknowns:z6.array(z6.string())});var packageUpgradeReviewResponseSchema=z6.object({summary:z6.object({total:z6.number().int(),withUnknowns:z6.number().int(),withAddedAdvisories:z6.number().int(),withBreakingSignals:z6.number().int(),withDirectDependencyChanges:z6.number().int(),withTransitiveVulnerabilityAdditions:z6.number().int()}),reviews:z6.array(packageUpgradeReviewSchema)});var packageUpgradeReviewGraphQLResponseSchema=z6.object({data:z6.object({packageUpgradeReview:packageUpgradeReviewResponseSchema.nullable().optional()}).nullable().optional(),errors:z6.array(graphQLErrorSchema3).optional()});var PACKAGE_UPGRADE_REVIEW_QUERY=`
1376
- query PackageUpgradeReview(
1377
- $packages: [PackageUpgradeReviewPackageInput!]!
1378
- $includeTransitiveSecurity: Boolean!
1379
- $includeDependencyIssues: Boolean!
1380
- $minSeverity: Float
1381
- $changelogLimit: Int!
1382
- ) {
1383
- packageUpgradeReview(
1384
- packages: $packages
1385
- includeTransitiveSecurity: $includeTransitiveSecurity
1386
- minSeverity: $minSeverity
1387
- changelogLimit: $changelogLimit
1388
- ) {
1389
- summary {
1390
- total
1391
- withUnknowns
1392
- withAddedAdvisories
1393
- withBreakingSignals
1394
- withDirectDependencyChanges
1395
- withTransitiveVulnerabilityAdditions
1396
- }
1397
- reviews {
1398
- registry
1399
- name
1400
- currentVersion
1401
- targetVersion
1402
- latestVersion
1403
- versionDelta
1404
- security {
1405
- current {
1406
- version
1407
- publishedAt
1408
- deprecated
1409
- deprecationReason
1410
- affectedCount
1411
- nonAffectingCount
1412
- allCount
1413
- lastModifiedAt
1414
- advisories {
1415
- ...PackageUpgradeAdvisoryFields
1416
- }
1417
- }
1418
- target {
1419
- version
1420
- publishedAt
1421
- deprecated
1422
- deprecationReason
1423
- affectedCount
1424
- nonAffectingCount
1425
- allCount
1426
- lastModifiedAt
1427
- advisories {
1428
- ...PackageUpgradeAdvisoryFields
1429
- }
1430
- }
1431
- added {
1432
- ...PackageUpgradeAdvisoryFields
1433
- }
1434
- removed {
1435
- ...PackageUpgradeAdvisoryFields
1436
- }
1437
- notAddressed {
1438
- ...PackageUpgradeAdvisoryFields
1439
- }
1440
- fixed {
1441
- ...PackageUpgradeAdvisoryFields
1442
- }
1443
- introduced {
1444
- ...PackageUpgradeAdvisoryFields
1445
- }
1446
- unchanged {
1447
- ...PackageUpgradeAdvisoryFields
1448
- }
1449
- transitive @include(if: $includeTransitiveSecurity) {
1450
- currentAffected
1451
- targetAffected
1452
- introducedPackages
1453
- fixedPackages
1454
- introducedPackageDetails(first: 50) {
1455
- ...PackageUpgradeTransitivePackagePageFields
1456
- }
1457
- fixedPackageDetails(first: 50) {
1458
- ...PackageUpgradeTransitivePackagePageFields
1459
- }
1460
- stillAffectedPackageDetails(first: 50) {
1461
- ...PackageUpgradeTransitivePackagePageFields
1462
- }
1463
- }
1464
- }
1465
- changelog {
1466
- source
1467
- fallback
1468
- entries {
1469
- ...PackageUpgradeChangelogEntryFields
1470
- }
1471
- sampledEntries {
1472
- ...PackageUpgradeChangelogEntryFields
1473
- }
1474
- keywordEntries {
1475
- ...PackageUpgradeChangelogEntryFields
1476
- }
1477
- totalKeywordEntries
1478
- totalEntries
1479
- totalEntriesWithBodies
1480
- truncated
1481
- hasReleaseNoteBodies
1482
- breakingSignals
1483
- migrationSignals
1484
- }
1485
- compatibility {
1486
- peerDependencyChanges
1487
- notes
1488
- }
1489
- dependencyChanges {
1490
- direct {
1491
- ...PackageUpgradeDependencyChangeGroupFields
1492
- }
1493
- transitive {
1494
- ...PackageUpgradeDependencyChangeGroupFields
1495
- }
1496
- }
1497
- dependencyIssues @include(if: $includeDependencyIssues) {
1498
- currentTotal
1499
- targetTotal
1500
- introducedDeprecated
1501
- introducedDuplicates
1502
- introducedConflicts
1503
- introducedOutdated
1504
- }
1505
- unknowns
1506
- }
1507
- }
1508
- }
1509
-
1510
- fragment PackageUpgradeAdvisoryFields on PackageUpgradeAdvisorySummary {
1511
- id
1512
- aliases
1513
- summary
1514
- severity
1515
- severityLabel
1516
- fixedIn
1517
- isMalicious
1518
- }
1519
-
1520
- fragment PackageUpgradeTransitivePackagePageFields on PackageUpgradeTransitivePackagePage {
1521
- entries {
1522
- id
1523
- registry
1524
- name
1525
- versions
1526
- affectedCount
1527
- maxSeverityScore
1528
- maxSeverityLabel
1529
- advisoryIds
1530
- }
1531
- totalCount
1532
- truncated
1533
- }
1534
-
1535
- fragment PackageUpgradeChangelogEntryFields on PackageUpgradeChangelogEntry {
1536
- version
1537
- publishedAt
1538
- htmlUrl
1539
- body
1540
- bodyPreview
1541
- headline
1542
- signals
1543
- }
1544
-
1545
- fragment PackageUpgradeDependencyChangeGroupFields on PackageUpgradeDependencyChangeGroup {
1546
- added {
1547
- name
1548
- registry
1549
- version
1550
- fromVersions
1551
- toVersions
1552
- constraint
1553
- type
1554
- }
1555
- removed {
1556
- name
1557
- registry
1558
- version
1559
- fromVersions
1560
- toVersions
1561
- constraint
1562
- type
1563
- }
1564
- changed {
1565
- name
1566
- registry
1567
- version
1568
- fromVersions
1569
- toVersions
1570
- constraint
1571
- type
1572
- }
1573
- }`;var changelogPackageInfoSchema=z6.object({name:z6.string().nullable().optional(),registry:z6.string().nullable().optional(),fromVersion:z6.string().nullable().optional(),toVersion:z6.string().nullable().optional(),limit:z6.number().int().nullable().optional()}).nullable().optional();var changelogEntryDetailSchema=z6.object({version:z6.string().nullable().optional(),normalizedVersion:z6.string().nullable().optional(),body:z6.string().nullable().optional(),htmlUrl:z6.string().nullable().optional(),publishedAt:z6.string().nullable().optional()});var changelogReportResponseSchema=z6.object({package:changelogPackageInfoSchema,source:z6.string().nullable().optional(),entries:z6.array(changelogEntryDetailSchema).nullable().optional()});var changelogGraphQLResponseSchema=z6.object({data:z6.object({packageChangelog:changelogReportResponseSchema.nullable().optional()}).nullable().optional(),errors:z6.array(graphQLErrorSchema3).optional()});var exactChangelogDetailSchema=z6.object({detailSource:z6.string().nullable().optional(),hasChangelog:z6.boolean(),entry:changelogEntryDetailSchema.nullable().optional()});var exactChangelogGraphQLResponseSchema=z6.object({data:z6.object({packageInfo:z6.object({selectedVersion:z6.object({resolvedVersion:z6.string(),changelog:exactChangelogDetailSchema.nullable().optional()}).nullable().optional()}).nullable().optional()}).nullable().optional(),errors:z6.array(graphQLErrorSchema3).optional()});var PACKAGE_CHANGELOG_QUERY=`
1574
- query PackageChangelog(
1575
- $registry: Registry!
1576
- $name: String!
1577
- $fromVersion: String
1578
- $toVersion: String
1579
- $limit: Int
1580
- $includeBodies: Boolean! = true
1581
- ) {
1582
- packageChangelog(
1583
- registry: $registry
1584
- name: $name
1585
- fromVersion: $fromVersion
1586
- toVersion: $toVersion
1587
- limit: $limit
1588
- ) {
1589
- package {
1590
- name
1591
- registry
1592
- fromVersion
1593
- toVersion
1594
- limit
1595
- }
1596
- source
1597
- entries {
1598
- version
1599
- normalizedVersion
1600
- body @include(if: $includeBodies)
1601
- htmlUrl
1602
- publishedAt
1603
- }
1604
- }
1605
- }`;var PACKAGE_CHANGELOG_EXACT_QUERY=`
1606
- query PackageChangelogExact(
1607
- $registry: Registry!
1608
- $name: String!
1609
- $version: String
1610
- $includeBodies: Boolean! = true
1611
- ) {
1612
- packageInfo(registry: $registry, name: $name, version: $version) {
1613
- selectedVersion {
1614
- resolvedVersion
1615
- changelog {
1616
- detailSource
1617
- hasChangelog
1618
- entry {
1619
- normalizedVersion
1620
- body @include(if: $includeBodies)
1621
- htmlUrl
1622
- publishedAt
1623
- }
1624
- }
1625
- }
1626
- }
1627
- }`;function normaliseChangelogSource(raw){const trimmed=raw?.trim();if(!trimmed)return;return trimmed.toLowerCase()}var packageDocSourceKindSchema=z6.enum(["CRAWLED","REPOSITORY"]);var packageDocPageSummarySchema=z6.object({id:z6.string().nullable().optional(),readTarget:readTargetSchema,title:z6.string().nullable().optional(),slug:z6.string().nullable().optional(),order:z6.number().int().nullable().optional(),linkName:z6.string().nullable().optional(),lastUpdatedAt:z6.string().nullable().optional(),sourceKind:packageDocSourceKindSchema.nullable().optional(),sourceUrl:z6.string().nullable().optional(),repoUrl:z6.string().nullable().optional(),gitRef:z6.string().nullable().optional(),requestedRef:z6.string().nullable().optional(),filePath:z6.string().nullable().optional()});var packageDocsPageInfoSchema=z6.object({hasNextPage:z6.boolean(),endCursor:z6.string().nullable().optional(),totalCount:z6.number().int().nullable().optional()}).nullable().optional();var packageDocsListResponseSchema=z6.object({registry:z6.string().nullable().optional(),packageName:z6.string().nullable().optional(),version:z6.string().nullable().optional(),stale:z6.boolean().nullable().optional(),codeIndexState:z6.string().nullable().optional(),pages:z6.array(packageDocPageSummarySchema).nullable().optional(),pageInfo:packageDocsPageInfoSchema});var packageDocSourceSchema=z6.object({url:z6.string().nullable().optional(),label:z6.string().nullable().optional()}).nullable().optional();var packageDocPageSchema=z6.object({id:z6.string().nullable().optional(),docsReadTarget:z6.string(),title:z6.string().nullable().optional(),content:z6.string().nullable().optional(),contentFormat:z6.string().nullable().optional(),breadcrumbs:z6.array(z6.string()).nullable().optional(),linkName:z6.string().nullable().optional(),lastUpdatedAt:z6.string().nullable().optional(),sourceKind:packageDocSourceKindSchema.nullable().optional(),source:packageDocSourceSchema,repoUrl:z6.string().nullable().optional(),gitRef:z6.string().nullable().optional(),requestedRef:z6.string().nullable().optional(),filePath:z6.string().nullable().optional(),baseUrl:z6.string().nullable().optional()}).nullable().optional();var packageDocResultResponseSchema=z6.object({registry:z6.string().nullable().optional(),packageName:z6.string().nullable().optional(),version:z6.string().nullable().optional(),sourceKind:packageDocSourceKindSchema.nullable().optional(),contentRange:z6.object({startLine:z6.number().int().positive().nullable(),endLine:z6.number().int().positive().nullable(),totalLines:z6.number().int().nonnegative(),anchor:z6.string().nullable()}).superRefine((range,context)=>{const empty=range.totalLines===0;if(empty&&(range.startLine!==null||range.endLine!==null)){context.addIssue({code:"custom",message:"Empty documentation must have null range bounds."})}if(!empty&&(range.startLine===null||range.endLine===null)){context.addIssue({code:"custom",message:"Non-empty documentation must have range bounds."})}if(range.startLine!==null&&range.endLine!==null&&(range.startLine>range.endLine||range.endLine>range.totalLines)){context.addIssue({code:"custom",message:"Documentation range must fit within the complete page."})}}),page:packageDocPageSchema});var packageDocsListGraphQLResponseSchema=z6.object({data:z6.object({listPackageDocs:packageDocsListResponseSchema.nullable().optional()}).nullable().optional(),errors:z6.array(graphQLErrorSchema3).optional()});var packageDocReadGraphQLResponseSchema=z6.object({data:z6.object({getDocPage:packageDocResultResponseSchema.nullable().optional()}).nullable().optional(),errors:z6.array(graphQLErrorSchema3).optional()});var LIST_PACKAGE_DOCS_QUERY=`
1628
- query ListPackageDocs(
1629
- $registry: Registry!
1630
- $packageName: String!
1631
- $version: String
1632
- $limit: Int
1633
- $after: String
1634
- ) {
1635
- listPackageDocs(
1636
- registry: $registry
1637
- packageName: $packageName
1638
- version: $version
1639
- limit: $limit
1640
- after: $after
1641
- ) {
1642
- registry
1643
- packageName
1644
- version
1645
- stale
1646
- codeIndexState
1647
- pages {
1648
- id
1649
- readTarget { target }
1650
- title
1651
- slug
1652
- order
1653
- linkName
1654
- lastUpdatedAt
1655
- sourceKind
1656
- sourceUrl
1657
- repoUrl
1658
- gitRef
1659
- requestedRef
1660
- filePath
1661
- }
1662
- pageInfo {
1663
- hasNextPage
1664
- endCursor
1665
- totalCount
1666
- }
1667
- }
1668
- }`;var READ_PACKAGE_DOC_QUERY=`
1669
- query ReadPackageDoc($pageId: String!, $startLine: Int, $endLine: Int) {
1670
- getDocPage(pageId: $pageId, startLine: $startLine, endLine: $endLine) {
1671
- registry
1672
- packageName
1673
- version
1674
- sourceKind
1675
- contentRange {
1676
- startLine
1677
- endLine
1678
- totalLines
1679
- anchor
1680
- }
1681
- page {
1682
- id
1683
- docsReadTarget
1684
- title
1685
- content
1686
- contentFormat
1687
- breadcrumbs
1688
- linkName
1689
- lastUpdatedAt
1690
- sourceKind
1691
- source {
1692
- url
1693
- label
1694
- }
1695
- repoUrl
1696
- gitRef
1697
- requestedRef
1698
- filePath
1699
- baseUrl
1700
- }
1701
- }
1702
- }`;class PackageIntelligenceServiceImpl2{endpointUrl;tokenProvider;fetchFn;runtime;constructor(endpointUrl,tokenProvider,fetchFn=globalThis.fetch,runtime={}){this.endpointUrl=endpointUrl;this.tokenProvider=tokenProvider;this.fetchFn=fetchFn;this.runtime=runtime}async packageSummary(params){return withServiceDiagnostics(this.runtime.diagnostics,"pkg-intel.summary.request",()=>executeWithTokenRefresh({getToken:()=>this.tokenProvider.getToken(),forceRefresh:()=>this.tokenProvider.forceRefresh(),shouldRefresh:isTokenRefreshableError,executeWithToken:(token)=>this.executePackageSummary(token,params)}))}async executePackageSummary(token,params){let response;try{response=await postPkgseerGraphql({endpointUrl:this.endpointUrl,token,query:PACKAGE_SUMMARY_QUERY,variables:{registry:params.registry,name:params.packageName,includeVerboseFields:params.includeVerboseFields!==false},fetchFn:this.fetchFn,clientHeaders:this.runtime.clientHeaders,userAgent:this.runtime.userAgent,diagnostics:this.runtime.diagnostics})}catch(cause){if(cause instanceof PkgseerTransportError){throw this.createTransportError(cause)}throw cause}if(response.status<200||response.status>=300){throw this.createHttpError(response)}const parsed=graphQLResponseSchema.safeParse(response.parsedBody);if(!parsed.success){throw new MalformedPackageIntelligenceResponseError("Malformed response from the package-intelligence service.")}if(parsed.data.errors&&parsed.data.errors.length>0){throw this.createGraphQLError(parsed.data.errors)}const data=parsed.data.data?.packageSummary;if(!data){throw new MalformedPackageIntelligenceResponseError("Empty response from the package-intelligence service.")}return this.normalise(data)}createHttpError(response){return createPackageIntelligenceHttpError(response)}createTransportError(error){return createPackageIntelligenceTransportError(error)}createGraphQLError(errors){return createPackageIntelligenceGraphQLError(errors,this.runtime.clientVersion,this.runtime.diagnostics)}normalise(data){const name=data.package?.name??undefined;const latestVersion=data.package?.latestVersion??undefined;if(!name||!latestVersion){throw new MalformedPackageIntelligenceResponseError("Package summary response missing required name/latestVersion.")}const pkg=data.package;const github=pkg?.githubRepository;const identity={name,latestVersion,registry:pkg?.registry??undefined,description:pkg?.description??undefined,latestVersionPublishedAt:pkg?.latestVersionPublishedAt??undefined,homepage:pkg?.homepage??undefined,repositoryUrl:pkg?.repositoryUrl??undefined,license:pkg?.license??undefined,downloadsLastMonth:pkg?.downloadsLastMonth??undefined,downloadsTotal:pkg?.downloadsTotal??undefined,versionCount:pkg?.versionCount??undefined,downloadsRefreshedAt:pkg?.downloadsRefreshedAt??undefined,githubRepository:github?{stargazersCount:github.stargazersCount??undefined,forksCount:github.forksCount??undefined,openIssuesCount:github.openIssuesCount??undefined,archived:github.archived??undefined,language:github.language??undefined,topics:github.topics??undefined,pushedAt:github.pushedAt??undefined}:undefined};const security=data.security?{vulnerabilityCount:data.security.vulnerabilityCount??undefined,allVulnerabilityCount:data.security.allVulnerabilityCount,hasCurrentVulnerabilities:data.security.hasCurrentVulnerabilities??undefined,recentVulnerabilities:data.security.recentVulnerabilities?.map((vuln)=>({osvId:vuln.osvId??undefined,summary:vuln.summary??undefined,severityScore:vuln.severityScore??undefined,publishedAt:vuln.publishedAt??undefined}))??undefined}:undefined;const latestChangelogs=data.latestChangelogs?.map((entry)=>({version:entry.version??undefined,publishedAt:entry.publishedAt??undefined,body:entry.body??undefined}))??undefined;return{package:identity,security,latestChangelogs}}async packageVulnerabilities(params){return withServiceDiagnostics(this.runtime.diagnostics,"pkg-intel.vulnerabilities.request",()=>executeWithTokenRefresh({getToken:()=>this.tokenProvider.getToken(),forceRefresh:()=>this.tokenProvider.forceRefresh(),shouldRefresh:isTokenRefreshableError,executeWithToken:(token)=>this.executePackageVulnerabilities(token,params)}))}async executePackageVulnerabilities(token,params){let after=null;let firstPage;const entries=[];const seenCursors=new Set;do{const page=await this.fetchPackageVulnerabilitiesPage(token,params,after);if(!firstPage)firstPage=page;const advisoryPage=page.security?.advisories;if(!advisoryPage){after=null;break}entries.push(...advisoryPage.entries);if(advisoryPage.pageInfo.hasNextPage){const nextCursor=advisoryPage.pageInfo.endCursor;if(!nextCursor){throw new MalformedPackageIntelligenceResponseError("Vulnerability response pagination omitted next cursor.")}if(seenCursors.has(nextCursor)){throw new MalformedPackageIntelligenceResponseError("Vulnerability response pagination repeated a cursor.")}seenCursors.add(nextCursor);after=nextCursor}else{after=null}}while(after!==null);if(!firstPage){throw new MalformedPackageIntelligenceResponseError("Empty response from the package-intelligence service.")}if(firstPage.security){const expectedCount=firstPage.security.advisories.pageInfo.totalCount;if(entries.length!==expectedCount){throw new MalformedPackageIntelligenceResponseError("Vulnerability response pagination returned an incomplete advisory set.")}}const data=firstPage.security?{...firstPage,security:{...firstPage.security,advisories:{...firstPage.security.advisories,entries}}}:firstPage;const report=this.normaliseVulnerabilityReport(data);if(params.includeTransitive===true){report.transitive=await this.fetchTransitiveVulnerabilityAudit(token,report.package,params.minSeverity,params.advisoryScope??"AFFECTED",params)}return report}async fetchPackageVulnerabilitiesPage(token,params,after){let response;try{response=await postPkgseerGraphql({endpointUrl:this.endpointUrl,token,query:PACKAGE_VULNERABILITIES_QUERY,variables:{registry:params.registry,name:params.packageName,version:params.version,minSeverity:params.minSeverity,includeWithdrawn:params.includeWithdrawn,scope:params.advisoryScope,after},fetchFn:this.fetchFn,clientHeaders:this.runtime.clientHeaders,userAgent:this.runtime.userAgent,diagnostics:this.runtime.diagnostics})}catch(cause){if(cause instanceof PkgseerTransportError){throw this.createTransportError(cause)}throw cause}if(response.status<200||response.status>=300){throw this.createHttpError(response)}const parsed=vulnerabilitiesGraphQLResponseSchema.safeParse(response.parsedBody);if(!parsed.success){throw new MalformedPackageIntelligenceResponseError("Malformed response from the package-intelligence service.")}if(parsed.data.errors&&parsed.data.errors.length>0){throw promoteGenericVersionNotFound(this.createGraphQLError(parsed.data.errors),params)}const data=parsed.data.data?.packageVulnerabilities;if(!data){throw new MalformedPackageIntelligenceResponseError("Empty response from the package-intelligence service.")}return data}normaliseVulnerabilityReport(data){const name=data.package?.name??undefined;const version=data.package?.version??undefined;if(!name||!version){throw new MalformedPackageIntelligenceResponseError("Vulnerability report response missing required name/version.")}const identity={name,version,registry:data.package?.registry??undefined,publishedAt:data.package?.publishedAt??undefined,deprecated:data.package?.deprecated??undefined,deprecationReason:data.package?.deprecationReason??undefined};const security=data.security?{affectedVulnerabilityCount:data.security.affectedVulnerabilityCount,nonAffectingVulnerabilityCount:data.security.nonAffectingVulnerabilityCount,allVulnerabilityCount:data.security.allVulnerabilityCount,currentVersionAffected:data.security.currentVersionAffected??undefined,vulnerabilities:data.security.advisories.entries.map((vuln)=>({osvId:vuln.osvId??undefined,summary:vuln.summary??undefined,severityScore:vuln.severityScore??undefined,severityType:vuln.severityType??undefined,affectedVersionRanges:vuln.affectedVersionRanges??undefined,affectedVersionRangesCount:vuln.affectedVersionRangesCount,affectedVersionRangesTruncated:vuln.affectedVersionRangesTruncated,fixedInVersions:vuln.fixedInVersions??undefined,publishedAt:vuln.publishedAt??undefined,modifiedAt:vuln.modifiedAt??undefined,withdrawnAt:vuln.withdrawnAt??undefined,aliases:vuln.aliases??undefined,isMalicious:vuln.isMalicious??undefined,affectsInspectedVersion:vuln.affectsInspectedVersion,matchedAffectedVersionRanges:vuln.matchedAffectedVersionRanges,duplicateIds:vuln.duplicateIds})),upgradePaths:data.security.upgradePaths??undefined}:undefined;return{package:identity,security}}async fetchTransitiveVulnerabilityAudit(token,directIdentity,minSeverity,advisoryScope,params){if(!directIdentity.registry){throw new MalformedPackageIntelligenceResponseError("Vulnerability report response missing registry for transitive audit.")}let response;try{response=await postPkgseerGraphql({endpointUrl:this.endpointUrl,token,query:buildPackageTransitiveVulnerabilityAuditQuery(advisoryScope),variables:{registry:params.registry,name:directIdentity.name,version:directIdentity.version,minSeverity,scope:advisoryScope,includeTransitiveAdvisoryDetails:params.includeTransitiveAdvisoryDetails===true},fetchFn:this.fetchFn,clientHeaders:this.runtime.clientHeaders,userAgent:this.runtime.userAgent,diagnostics:this.runtime.diagnostics})}catch(cause){if(cause instanceof PkgseerTransportError){throw this.createTransportError(cause)}throw cause}if(response.status<200||response.status>=300){throw this.createHttpError(response)}const parsed=transitiveAuditGraphQLResponseSchema.safeParse(response.parsedBody);if(!parsed.success){throw new MalformedPackageIntelligenceResponseError("Malformed response from the package-intelligence service.")}if(parsed.data.errors&&parsed.data.errors.length>0){throw promoteGenericVersionNotFound(this.createGraphQLError(parsed.data.errors),{registry:params.registry,packageName:directIdentity.name,version:directIdentity.version})}const data=parsed.data.data?.packageDependencies;if(!data){throw new MalformedPackageIntelligenceResponseError("Empty response from the package-intelligence service.")}const packageIdentity=data.package;if(packageIdentity?.name!==directIdentity.name||packageIdentity.registry!==directIdentity.registry||packageIdentity.version!==directIdentity.version){throw new MalformedPackageIntelligenceResponseError("Transitive vulnerability audit response package identity differs from the direct report.")}const summary=data.dependencies?.transitive?.vulnerabilitySummary;if(!summary){throw new MalformedPackageIntelligenceResponseError("Transitive vulnerability audit response missing vulnerability summary.")}return this.normaliseTransitiveVulnerabilityAudit(summary,advisoryScope)}normaliseTransitiveVulnerabilityAudit(summary,advisoryScope){const packages=summary.packages.filter((pkg)=>pkg.selectedCount>0).map((pkg)=>{const occurrences=pkg.advisoryOccurrences??[];if(occurrences.length!==pkg.selectedCount){throw new MalformedPackageIntelligenceResponseError("Transitive vulnerability audit package occurrence count differs from selected count.")}return{registry:pkg.registry,name:pkg.name,occurrenceCount:pkg.selectedCount,occurrences:occurrences.map((occurrence)=>{const isAffected=occurrence.affectsResolvedVersion;if(advisoryScope==="AFFECTED"&&!isAffected||advisoryScope==="NON_AFFECTING"&&isAffected){throw new MalformedPackageIntelligenceResponseError("Transitive vulnerability audit occurrence differs from the requested scope.")}const hasMatchedAffectedRange=occurrence.matchedAffectedVersionRanges.length>0;if(isAffected!==hasMatchedAffectedRange){throw new MalformedPackageIntelligenceResponseError("Transitive vulnerability audit occurrence has inconsistent affectedness proof.")}const hasHigherFixes=occurrence.fixVersionsAboveResolved.length>0;const nearestFixedVersion=occurrence.nearestFixedVersion??undefined;const hasNearestFix=nearestFixedVersion!==undefined;if(!isAffected&&(hasHigherFixes||hasNearestFix)||hasHigherFixes!==hasNearestFix||hasNearestFix&&!occurrence.fixVersionsAboveResolved.includes(nearestFixedVersion)){throw new MalformedPackageIntelligenceResponseError("Transitive vulnerability audit fix metadata is inconsistent.")}return{version:occurrence.version,affectsResolvedVersion:occurrence.affectsResolvedVersion,matchedAffectedVersionRanges:occurrence.matchedAffectedVersionRanges,fixVersionsAboveResolved:occurrence.fixVersionsAboveResolved,nearestFixedVersion,advisory:this.normaliseTransitiveAuditAdvisory(occurrence.advisory)}})}});const normalisedOccurrenceCount=packages.reduce((total,pkg)=>total+pkg.occurrences.length,0);const occurrenceCount=summary.selected.totalVulnerabilities;if(normalisedOccurrenceCount!==occurrenceCount){throw new MalformedPackageIntelligenceResponseError("Transitive vulnerability audit occurrence count differs from selected total.")}return{advisoryScope,totalPackagesAnalyzed:summary.totalPackagesAnalyzed,packageCount:packages.length,occurrenceCount,calculatedAt:summary.calculatedAt??undefined,packages}}async packageDependencies(params){return withServiceDiagnostics(this.runtime.diagnostics,"pkg-intel.dependencies.request",()=>executeWithTokenRefresh({getToken:()=>this.tokenProvider.getToken(),forceRefresh:()=>this.tokenProvider.forceRefresh(),shouldRefresh:isTokenRefreshableError,executeWithToken:(token)=>this.executePackageDependencies(token,params)}))}async packageUpgradeDependencyProbe(params){return withServiceDiagnostics(this.runtime.diagnostics,"pkg-intel.upgrade-dependency-probe.request",()=>executeWithTokenRefresh({getToken:()=>this.tokenProvider.getToken(),forceRefresh:()=>this.tokenProvider.forceRefresh(),shouldRefresh:isTokenRefreshableError,executeWithToken:(token)=>this.executePackageUpgradeDependencyProbe(token,params)}))}async packageUpgradeReview(params){return withServiceDiagnostics(this.runtime.diagnostics,"pkg-intel.upgrade-review.request",()=>executeWithTokenRefresh({getToken:()=>this.tokenProvider.getToken(),forceRefresh:()=>this.tokenProvider.forceRefresh(),shouldRefresh:isTokenRefreshableError,executeWithToken:(token)=>this.executePackageUpgradeReview(token,params)}))}async executePackageUpgradeReview(token,params){let response;try{response=await postPkgseerGraphql({endpointUrl:this.endpointUrl,token,query:PACKAGE_UPGRADE_REVIEW_QUERY,variables:{packages:params.packages,includeTransitiveSecurity:params.includeTransitiveSecurity,includeDependencyIssues:params.includeDependencyIssues,minSeverity:params.minSeverity,changelogLimit:params.changelogLimit},fetchFn:this.fetchFn,clientHeaders:this.runtime.clientHeaders,userAgent:this.runtime.userAgent,diagnostics:this.runtime.diagnostics})}catch(cause){if(cause instanceof PkgseerTransportError){throw this.createTransportError(cause)}throw cause}if(response.status<200||response.status>=300){throw this.createHttpError(response)}const parsed=packageUpgradeReviewGraphQLResponseSchema.safeParse(response.parsedBody);if(!parsed.success){throw new MalformedPackageIntelligenceResponseError("Malformed response from the package-intelligence service.")}if(parsed.data.errors&&parsed.data.errors.length>0){throw this.createGraphQLError(parsed.data.errors)}const data=parsed.data.data?.packageUpgradeReview;if(!data){throw new MalformedPackageIntelligenceResponseError("Empty response from the package-intelligence service.")}return stripNullProperties(data)}async executePackageUpgradeDependencyProbe(token,params){const includeTransitiveRisk=params.includeTransitiveSecurity===true||params.includeDependencyIssues===true||params.includeDependencyChanges===true;let response;try{response=await postPkgseerGraphql({endpointUrl:this.endpointUrl,token,query:PACKAGE_UPGRADE_DEPENDENCY_PROBE_QUERY,variables:{registry:params.registry,name:params.packageName,version:params.version,includeTransitiveRisk,includeTransitiveSecurity:params.includeTransitiveSecurity===true,includeDependencyIssues:params.includeDependencyIssues===true,includeDependencyChanges:params.includeDependencyChanges===true,includeGroups:params.includeGroups===true,lifecycle:params.includeGroups===true?["peer"]:undefined,minSeverity:params.minSeverity},fetchFn:this.fetchFn,clientHeaders:this.runtime.clientHeaders,userAgent:this.runtime.userAgent,diagnostics:this.runtime.diagnostics})}catch(cause){if(cause instanceof PkgseerTransportError){throw this.createTransportError(cause)}throw cause}if(response.status<200||response.status>=300){throw this.createHttpError(response)}const parsed=dependenciesGraphQLResponseSchema.safeParse(response.parsedBody);if(!parsed.success){throw new MalformedPackageIntelligenceResponseError("Malformed response from the package-intelligence service.")}if(parsed.data.errors&&parsed.data.errors.length>0){throw promoteGenericVersionNotFound(this.createGraphQLError(parsed.data.errors),params)}const data=parsed.data.data?.packageDependencies;if(!data){throw new MalformedPackageIntelligenceResponseError("Empty response from the package-intelligence service.")}return this.normaliseDependencyReport(data)}async executePackageDependencies(token,params){let response;try{response=await postPkgseerGraphql({endpointUrl:this.endpointUrl,token,query:PACKAGE_DEPENDENCIES_QUERY,variables:{registry:params.registry,name:params.packageName,version:params.version,includeTransitive:params.includeDependencyIssues===true?true:params.includeTransitive,includeTransitiveDetails:params.includeTransitiveDetails!==false,includeDependencyGraph:params.includeTransitive===true||params.includeDependencyIssues===true,includeDependencyIssues:params.includeDependencyIssues===true,includeGroups:params.includeGroups!==false,maxDepth:params.maxDepth,lifecycle:params.lifecycle&&params.lifecycle.length>0?params.lifecycle:undefined},fetchFn:this.fetchFn,clientHeaders:this.runtime.clientHeaders,userAgent:this.runtime.userAgent,diagnostics:this.runtime.diagnostics})}catch(cause){if(cause instanceof PkgseerTransportError){throw this.createTransportError(cause)}throw cause}if(response.status<200||response.status>=300){throw this.createHttpError(response)}const parsed=dependenciesGraphQLResponseSchema.safeParse(response.parsedBody);if(!parsed.success){throw new MalformedPackageIntelligenceResponseError("Malformed response from the package-intelligence service.")}if(parsed.data.errors&&parsed.data.errors.length>0){throw promoteGenericVersionNotFound(this.createGraphQLError(parsed.data.errors),params)}const data=parsed.data.data?.packageDependencies;if(!data){throw new MalformedPackageIntelligenceResponseError("Empty response from the package-intelligence service.")}const report=this.normaliseDependencyReport(data);if(params.includeDependencyIssues===true){const transitive=report.dependencies?.transitive;if(!transitive?.dependencyIssues){throw new MalformedPackageIntelligenceResponseError("Dependency issue analysis response missing dependency issues.")}if(!transitive.dependencyGraph){throw new MalformedPackageIntelligenceResponseError("Dependency issue analysis response missing dependency graph.")}}if(params.includeTransitive===true){const transitive=report.dependencies?.transitive;const hasConflictEdges=transitive?.dependencyConflicts?.some((conflict)=>conflict.conflictingEdges.length>0);if(hasConflictEdges&&!transitive?.dependencyGraph){throw new MalformedPackageIntelligenceResponseError("Transitive dependency conflict edges response missing dependency graph.")}}return report}normaliseDependencyReport(data){const name=data.package?.name??undefined;const version=data.package?.version??undefined;if(!name||!version){throw new MalformedPackageIntelligenceResponseError("Package dependencies response missing required name/version.")}const identity={name,version,registry:data.package?.registry??undefined,publishedAt:data.package?.publishedAt??undefined,deprecated:data.package?.deprecated??undefined,deprecationReason:data.package?.deprecationReason??undefined};const bundle=data.dependencies;const dependencies=bundle?{direct:bundle.direct?.map((entry)=>{if(!entry.name){throw new MalformedPackageIntelligenceResponseError("Dependency entry missing required name.")}return{name:entry.name,versionConstraint:entry.versionConstraint??undefined,type:entry.type??undefined}})??undefined,transitive:bundle.transitive?{totalEdges:bundle.transitive.totalEdges??undefined,uniquePackagesCount:bundle.transitive.uniquePackagesCount??undefined,uniqueDependencies:bundle.transitive.uniqueDependencies??undefined,dependencyConflicts:bundle.transitive.dependencyConflicts?.map((c)=>({packageName:c.packageName,requiredVersions:c.requiredVersions,conflictingEdges:c.conflictingEdges.map((edge)=>({fromIndex:edge.fromIndex??undefined,toIndex:edge.toIndex,versionConstraint:edge.versionConstraint,dependencyType:edge.dependencyType}))}))??undefined,circularDependencyCycles:bundle.transitive.circularDependencyCycles?.map((cycle)=>({cycleStart:cycle.cycleStart,circularPath:cycle.circularPath,displayChain:cycle.displayChain}))??undefined,dependencyGraph:bundle.transitive.dependencyGraph?{formatVersion:bundle.transitive.dependencyGraph.formatVersion,nodes:bundle.transitive.dependencyGraph.nodes.map((n)=>({registry:n.registry,name:n.name,version:n.version??undefined})),edges:bundle.transitive.dependencyGraph.edges.map((e)=>({fromIndex:e.fromIndex??undefined,toIndex:e.toIndex,constraint:e.constraint??undefined,dependencyType:e.dependencyType??undefined}))}:undefined,vulnerabilitySummary:this.normaliseTransitiveVulnerabilitySummary(bundle.transitive.vulnerabilitySummary),dependencyIssues:this.normaliseDependencyIssuesSummary(bundle.transitive.dependencyIssues)}:undefined}:undefined;const dependencyGroups=data.dependencyGroups?{primaryGroup:data.dependencyGroups.primaryGroup??undefined,environmentMarkers:data.dependencyGroups.environmentMarkers?.map((m)=>({type:m.type??undefined,value:m.value??undefined,raw:m.raw??undefined}))??undefined,groups:data.dependencyGroups.groups.map((group)=>({name:group.name,lifecycle:group.lifecycle,conditionType:group.conditionType,conditionValue:group.conditionValue??undefined,selectionMode:group.selectionMode,exclusiveGroup:group.exclusiveGroup??undefined,fallbackPriority:group.fallbackPriority??undefined,compatibleWith:group.compatibleWith??undefined,defaultEnabled:group.defaultEnabled??undefined,dependencies:group.dependencies.map((entry)=>({name:entry.name,constraint:entry.constraint??undefined}))}))}:undefined;return{package:identity,dependencies,dependencyGroups}}normaliseTransitiveVulnerabilitySummary(summary){if(!summary)return;return{affected:summary.affected,nonAffecting:summary.nonAffecting,combined:summary.combined,totalPackagesAnalyzed:summary.totalPackagesAnalyzed,affectedPackageCount:summary.affectedPackageCount,calculatedAt:summary.calculatedAt??undefined,packages:summary.packages.map((pkg)=>({registry:pkg.registry,name:pkg.name,versions:pkg.versions,affectedCount:pkg.affectedCount,nonAffectingCount:pkg.nonAffectingCount,totalCount:pkg.totalCount,maxSeverityScore:pkg.maxSeverityScore??undefined,maxSeverityLabel:pkg.maxSeverityLabel??undefined,advisoryIds:pkg.advisoryIds,mostCritical:pkg.mostCritical?this.normaliseVulnerabilitySummaryDetail(pkg.mostCritical):undefined,advisoryOccurrences:pkg.advisoryOccurrences?.map((occurrence)=>({version:occurrence.version,affectsResolvedVersion:occurrence.affectsResolvedVersion,matchedAffectedVersionRanges:occurrence.matchedAffectedVersionRanges,fixVersionsAboveResolved:occurrence.fixVersionsAboveResolved,nearestFixedVersion:occurrence.nearestFixedVersion??undefined,advisory:this.normaliseVulnerabilitySummaryDetail(occurrence.advisory)}))??undefined}))}}normaliseVulnerabilitySummaryDetail(advisory){return{osvId:advisory.osvId??undefined,registry:advisory.registry??undefined,packageName:advisory.packageName??undefined,summary:advisory.summary??undefined,severityScore:advisory.severityScore??undefined,severityType:advisory.severityType??undefined,affectedVersionRanges:advisory.affectedVersionRanges??undefined,fixedInVersions:advisory.fixedInVersions??undefined,publishedAt:advisory.publishedAt??undefined,modifiedAt:advisory.modifiedAt??undefined,withdrawnAt:advisory.withdrawnAt??undefined,aliases:advisory.aliases??undefined,isMalicious:advisory.isMalicious??undefined}}normaliseTransitiveAuditAdvisory(advisory){return{osvId:advisory.osvId??undefined,summary:advisory.summary??undefined,severityScore:advisory.severityScore??undefined,affectedVersionRanges:advisory.affectedVersionRanges?.length?advisory.affectedVersionRanges:undefined,fixedInVersions:advisory.fixedInVersions?.length?advisory.fixedInVersions:undefined,publishedAt:advisory.publishedAt??undefined,modifiedAt:advisory.modifiedAt??undefined,aliases:advisory.aliases??undefined,isMalicious:advisory.isMalicious??undefined}}normaliseDependencyIssuesSummary(issues){if(!issues)return;return{totalCount:issues.totalCount,deprecatedCount:issues.deprecatedCount,outdatedCount:issues.outdatedCount,duplicateCount:issues.duplicateCount,conflictCount:issues.conflictCount,deprecatedPackages:issues.deprecatedPackages.map((pkg)=>({registry:pkg.registry,name:pkg.name,versions:pkg.versions,reasons:pkg.reasons.map((reason)=>({version:reason.version,reason:reason.reason??undefined}))})),outdatedPackages:issues.outdatedPackages.map((pkg)=>({registry:pkg.registry,name:pkg.name,latestVersion:pkg.latestVersion??undefined,severity:pkg.severity,versions:pkg.versions.map((version)=>({version:version.version,severity:version.severity})),repositoryUrl:pkg.repositoryUrl??undefined})),duplicatePackages:issues.duplicatePackages.map((pkg)=>({registry:pkg.registry??undefined,name:pkg.name,versions:pkg.versions})),conflicts:issues.conflicts.map((conflict)=>({registry:conflict.registry??undefined,name:conflict.name,versions:conflict.versions,requiredVersions:conflict.requiredVersions,conflictingEdges:conflict.conflictingEdges.map((edge)=>({fromIndex:edge.fromIndex??undefined,toIndex:edge.toIndex,versionConstraint:edge.versionConstraint,dependencyType:edge.dependencyType}))}))}}async packageChangelog(params){return withServiceDiagnostics(this.runtime.diagnostics,"pkg-intel.changelog.request",()=>executeWithTokenRefresh({getToken:()=>this.tokenProvider.getToken(),forceRefresh:()=>this.tokenProvider.forceRefresh(),shouldRefresh:isTokenRefreshableError,executeWithToken:(token)=>this.executePackageChangelog(token,params)}))}async executePackageChangelog(token,params){if(params.version!==undefined){return this.executeExactPackageChangelog(token,params)}return this.executeTimelinePackageChangelog(token,params)}async executeTimelinePackageChangelog(token,params){let response;try{response=await postPkgseerGraphql({endpointUrl:this.endpointUrl,token,query:PACKAGE_CHANGELOG_QUERY,variables:{registry:params.registry,name:params.packageName,fromVersion:params.fromVersion,toVersion:params.toVersion,limit:params.limit,includeBodies:params.includeBodies!==false},fetchFn:this.fetchFn,clientHeaders:this.runtime.clientHeaders,userAgent:this.runtime.userAgent,diagnostics:this.runtime.diagnostics})}catch(cause){if(cause instanceof PkgseerTransportError){throw this.createTransportError(cause)}throw cause}if(response.status<200||response.status>=300){throw this.createHttpError(response)}const parsed=changelogGraphQLResponseSchema.safeParse(response.parsedBody);if(!parsed.success){throw new MalformedPackageIntelligenceResponseError("Malformed response from the package-intelligence service.")}if(parsed.data.errors&&parsed.data.errors.length>0){throw promoteGenericVersionNotFound(this.createGraphQLError(parsed.data.errors),params)}const data=parsed.data.data?.packageChangelog;if(!data){throw new MalformedPackageIntelligenceResponseError("Empty response from the package-intelligence service.")}return this.normaliseTimelineChangelogReport(data)}async executeExactPackageChangelog(token,params){let response;try{response=await postPkgseerGraphql({endpointUrl:this.endpointUrl,token,query:PACKAGE_CHANGELOG_EXACT_QUERY,variables:{registry:params.registry,name:params.packageName,version:params.version,includeBodies:params.includeBodies!==false},fetchFn:this.fetchFn,clientHeaders:this.runtime.clientHeaders,userAgent:this.runtime.userAgent,diagnostics:this.runtime.diagnostics})}catch(cause){if(cause instanceof PkgseerTransportError){throw this.createTransportError(cause)}throw cause}if(response.status<200||response.status>=300){throw this.createHttpError(response)}const parsed=exactChangelogGraphQLResponseSchema.safeParse(response.parsedBody);if(!parsed.success){throw new MalformedPackageIntelligenceResponseError("Malformed response from the package-intelligence service.")}if(parsed.data.errors&&parsed.data.errors.length>0){throw promoteGenericVersionNotFound(this.createGraphQLError(parsed.data.errors),params)}const selected=parsed.data.data?.packageInfo?.selectedVersion;if(!selected){throw new MalformedPackageIntelligenceResponseError("Empty response from the package-intelligence service.")}return this.normaliseExactChangelogReport(selected,params)}normaliseTimelineChangelogReport(data){const source=normaliseChangelogSource(data.source);const rawEntries=data.entries??[];const entries=rawEntries.map((entry)=>({version:entry.version??undefined,normalizedVersion:entry.normalizedVersion??undefined,body:entry.body??undefined,htmlUrl:entry.htmlUrl??undefined,publishedAt:entry.publishedAt??undefined}));const packageInfo=data.package?{name:data.package.name??undefined,registry:data.package.registry??undefined,fromVersion:data.package.fromVersion??undefined,toVersion:data.package.toVersion??undefined,limit:data.package.limit??undefined}:undefined;return{package:packageInfo,source,entries}}normaliseExactChangelogReport(selected,params){const changelog=selected.changelog??undefined;const entry=changelog?.entry??undefined;const hasChangelog=changelog?.hasChangelog??false;return{package:{name:params.packageName,registry:toPkgseerRegistryLowercase2(params.registry)},source:normaliseChangelogSource(changelog?.detailSource),entries:[{version:selected.resolvedVersion,normalizedVersion:entry?.normalizedVersion??undefined,body:entry?.body??undefined,htmlUrl:entry?.htmlUrl??undefined,publishedAt:entry?.publishedAt??undefined,hasChangelog}]}}async listPackageDocs(params){return withServiceDiagnostics(this.runtime.diagnostics,"pkg-intel.docs.list",()=>executeWithTokenRefresh({getToken:()=>this.tokenProvider.getToken(),forceRefresh:()=>this.tokenProvider.forceRefresh(),shouldRefresh:isTokenRefreshableError,executeWithToken:(token)=>this.executeListPackageDocs(token,params)}))}async executeListPackageDocs(token,params){let response;try{response=await postPkgseerGraphql({endpointUrl:this.endpointUrl,token,query:LIST_PACKAGE_DOCS_QUERY,variables:{registry:params.registry,packageName:params.packageName,version:params.version,limit:params.limit,after:params.after},fetchFn:this.fetchFn,clientHeaders:this.runtime.clientHeaders,userAgent:this.runtime.userAgent,diagnostics:this.runtime.diagnostics})}catch(cause){if(cause instanceof PkgseerTransportError){throw this.createTransportError(cause)}throw cause}if(response.status<200||response.status>=300){throw this.createHttpError(response)}const parsed=packageDocsListGraphQLResponseSchema.safeParse(response.parsedBody);if(!parsed.success){throw new MalformedPackageIntelligenceResponseError("Malformed response from the package-intelligence service.")}if(parsed.data.errors&&parsed.data.errors.length>0){throw promoteGenericVersionNotFound(this.createGraphQLError(parsed.data.errors),params)}const data=parsed.data.data?.listPackageDocs;if(!data){throw new MalformedPackageIntelligenceResponseError("Empty response from the package-intelligence service.")}return this.normalisePackageDocsList(data)}normalisePackageDocsList(data){return{registry:data.registry??undefined,packageName:data.packageName??undefined,version:data.version??undefined,stale:data.stale??undefined,codeIndexState:data.codeIndexState??undefined,pages:data.pages?.map((page)=>({id:page.id??undefined,docsReadTarget:page.readTarget.target,title:page.title??undefined,slug:page.slug??undefined,order:page.order??undefined,linkName:page.linkName??undefined,lastUpdatedAt:page.lastUpdatedAt??undefined,sourceKind:page.sourceKind??undefined,sourceUrl:page.sourceUrl??undefined,repoUrl:page.repoUrl??undefined,gitRef:page.gitRef??undefined,requestedRef:page.requestedRef??undefined,filePath:page.filePath??undefined}))??[],pageInfo:data.pageInfo?{hasNextPage:data.pageInfo.hasNextPage,endCursor:data.pageInfo.endCursor??undefined,totalCount:data.pageInfo.totalCount??undefined}:undefined}}async readPackageDoc(params){return withServiceDiagnostics(this.runtime.diagnostics,"pkg-intel.docs.read",()=>executeWithTokenRefresh({getToken:()=>this.tokenProvider.getToken(),forceRefresh:()=>this.tokenProvider.forceRefresh(),shouldRefresh:isTokenRefreshableError,executeWithToken:(token)=>this.executeReadPackageDoc(token,params)}))}async executeReadPackageDoc(token,params){let response;try{response=await postPkgseerGraphql({endpointUrl:this.endpointUrl,token,query:READ_PACKAGE_DOC_QUERY,variables:{pageId:params.pageId,...params.startLine!==undefined?{startLine:params.startLine}:{},...params.endLine!==undefined?{endLine:params.endLine}:{}},fetchFn:this.fetchFn,clientHeaders:this.runtime.clientHeaders,userAgent:this.runtime.userAgent,diagnostics:this.runtime.diagnostics})}catch(cause){if(cause instanceof PkgseerTransportError){throw this.createTransportError(cause)}throw cause}if(response.status<200||response.status>=300){throw this.createHttpError(response)}const parsed=packageDocReadGraphQLResponseSchema.safeParse(response.parsedBody);if(!parsed.success){throw new MalformedPackageIntelligenceResponseError("Malformed response from the package-intelligence service.")}if(parsed.data.errors&&parsed.data.errors.length>0){throw this.createGraphQLError(parsed.data.errors)}const data=parsed.data.data?.getDocPage;if(!data){throw new MalformedPackageIntelligenceResponseError("Empty response from the package-intelligence service.")}return normalisePackageDocResult(data)}}function normalisePackageDocResult(data){return{registry:data.registry??undefined,packageName:data.packageName??undefined,version:data.version??undefined,sourceKind:data.sourceKind??undefined,contentRange:{startLine:data.contentRange.startLine??undefined,endLine:data.contentRange.endLine??undefined,totalLines:data.contentRange.totalLines,anchor:data.contentRange.anchor??undefined},page:data.page?{id:data.page.id??undefined,docsReadTarget:data.page.docsReadTarget,title:data.page.title??undefined,content:data.page.content??undefined,contentFormat:data.page.contentFormat??undefined,breadcrumbs:data.page.breadcrumbs??undefined,linkName:data.page.linkName??undefined,lastUpdatedAt:data.page.lastUpdatedAt??undefined,sourceKind:data.page.sourceKind??undefined,source:data.page.source?{url:data.page.source.url??undefined,label:data.page.source.label??undefined}:undefined,repoUrl:data.page.repoUrl??undefined,gitRef:data.page.gitRef??undefined,requestedRef:data.page.requestedRef??undefined,filePath:data.page.filePath??undefined,baseUrl:data.page.baseUrl??undefined}:undefined}}function parsePackageDocResult(data){const parsed=packageDocResultResponseSchema.safeParse(data);if(!parsed.success){throw new MalformedPackageIntelligenceResponseError("Malformed response from the package-intelligence service.")}return normalisePackageDocResult(parsed.data)}function stripNullProperties(value){if(Array.isArray(value))return value.map(stripNullProperties);if(!value||typeof value!=="object")return value;const result={};for(const[key,child]of Object.entries(value)){if(child!==null)result[key]=stripNullProperties(child)}return result}function createPackageIntelligenceHttpError(response){const status=response.status;const detail=parseHttpErrorDetail(response.responseBody,["detail","error"]);if(status===401){return new AuthenticationError2(SERVER_AUTHENTICATION_REJECTED_MESSAGE,"server")}if(status===403){return new PackageIntelligenceAccessError(detail??"Access denied.")}if(status>=500){return new PackageIntelligenceBackendError(detail?`Server error (${status}): ${detail}`:`Server error (${status})`,status)}return new PackageIntelligenceBackendError(detail??`Request failed with status ${status}`,status)}function createPackageIntelligenceTransportError(error){if(isFetchTimeoutError(error.cause)){return new PackageIntelligenceBackendError("Package intelligence request timed out.",undefined,"TIMEOUT",true)}return new PackageIntelligenceNetworkError("Could not reach the package intelligence service. Check your connection or set GITHITS_CODE_NAV_URL.",{cause:error})}function createPackageIntelligenceGraphQLError(errors,clientVersion,diagnostics){const message=errors.map((error)=>error.message).join(", ");const extensions=getPrimaryExtensions2(errors);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=pkg-graphql to inspect GraphQL details during local development.";if(diagnostics?.isEnabled("pkg-graphql")){diagnostics.debug("pkg-graphql",{event:"graphql-schema-mismatch",code:code??"omitted",message})}return new PackageIntelligenceBackendError(diagnostics?.isEnabled("pkg-graphql")?message:sanitized,undefined,code,retryable)}switch(code){case"NOT_FOUND":case"PACKAGE_NOT_FOUND":return new PackageIntelligenceTargetNotFoundError(message);case"VERSION_NOT_FOUND":return new PackageIntelligenceVersionNotFoundError(message,typeof extensions?.package==="string"?extensions.package:undefined,typeof extensions?.requested_version==="string"?extensions.requested_version:undefined,parseVersionList(extensions?.available_versions??extensions?.availableVersions));case"UNSUPPORTED_REGISTRY":case"VALIDATION_ERROR":return new PackageIntelligenceValidationError(message);case"DOCUMENTATION_SECTION_UNRESOLVED":return new PackageIntelligenceDocumentationSectionUnresolvedError(message,parseDocumentationSectionUnresolvedReason(extensions?.reason));case"FEATURE_FLAG_REQUIRED":return new PackageIntelligenceFeatureFlagRequiredError(message);case"AUTHENTICATION_REQUIRED":case"UNAUTHORIZED":return new AuthenticationError2(SERVER_AUTHENTICATION_REJECTED_MESSAGE,"server");case"FORBIDDEN":return new PackageIntelligenceAccessError("Access denied. This feature may not be enabled for your account.");case"UPSTREAM_ERROR":case"TIMEOUT":case"RATE_LIMITED":case"INTERNAL_ERROR":case"UNKNOWN_ERROR":return new PackageIntelligenceBackendError(message,undefined,code,retryable);default:return new PackageIntelligenceBackendError(message,undefined,code,retryable)}}function parseDocumentationSectionUnresolvedReason(value){switch(value){case"not_found":case"ambiguous":case"inexact_range":case"unsupported_format":return value;default:return}}function getPrimaryExtensions2(errors){for(const error of errors){if(error.extensions&&Object.keys(error.extensions).length>0){return error.extensions}}return}function parseVersionList(raw){if(!Array.isArray(raw))return;const versions=[];for(const item of raw){if(typeof item==="string"&&item.length>0){versions.push(item)}}return versions.length>0?versions:undefined}import{z as z7}from"zod";var readResultTypeSchema=z7.object({__typename:z7.enum(["CodeContextResult","GetDocPageResult","CodeSymbolResolutionResult"])});var symbolResolutionSchema=z7.object({__typename:z7.literal("CodeSymbolResolutionResult"),status:z7.enum(["AMBIGUOUS","NOT_FOUND","SNAPSHOT_UNSUPPORTED"]),candidates:z7.array(z7.object({name:z7.string().nullable(),qualifiedPath:z7.string().nullable(),kind:z7.string().nullable(),arity:z7.number().int().nullable(),filePath:z7.string().nullable(),startLine:z7.number().int().nullable(),endLine:z7.number().int().nullable()})).max(10),suggestions:z7.array(z7.object({name:z7.string(),qualifiedPath:z7.string().nullable(),localId:z7.string().nullable(),arity:z7.number().int().nullable(),filePath:z7.string().nullable(),reason:z7.string().nullable()})).max(10),hasMore:z7.boolean(),repoUrl:z7.string(),gitRef:z7.string(),message:z7.string().nullable(),codeIndexState:z7.string()});var readGraphQLErrorSchema=z7.object({message:z7.string(),extensions:z7.record(z7.string(),z7.unknown()).optional()});var readGraphQLResponseSchema=z7.object({data:z7.object({read:z7.unknown().nullable().optional()}).nullable().optional(),errors:z7.array(readGraphQLErrorSchema).optional()});var READ_QUERY=`
1703
- query Read(
1704
- $target: String!
1705
- $path: String
1706
- $selector: String
1707
- $startLine: Int
1708
- $endLine: Int
1709
- $waitTimeoutMs: Int
1710
- ) {
1711
- read(
1712
- target: $target
1713
- path: $path
1714
- selector: $selector
1715
- startLine: $startLine
1716
- endLine: $endLine
1717
- waitTimeoutMs: $waitTimeoutMs
1718
- ) {
1719
- __typename
1720
- ... on CodeContextResult {
1721
- codeAction: readTarget { ${READ_TARGET_SELECTION} }
1722
- content
1723
- filePath
1724
- language
1725
- totalLines
1726
- startLine
1727
- endLine
1728
- isBinary
1729
- codeIndexState
1730
- indexingRef
1731
- ${CODE_CONTEXT_AVAILABLE_VERSIONS_SELECTION}
1732
- ${INDEXING_DURATION_ESTIMATE_SELECTION}
1733
- ${TARGET_RESOLUTION_SELECTION}
1734
- }
1735
- ... on GetDocPageResult {
1736
- docAction: readTarget { ${READ_TARGET_SELECTION} }
1737
- registry
1738
- packageName
1739
- version
1740
- sourceKind
1741
- contentRange {
1742
- startLine
1743
- endLine
1744
- totalLines
1745
- anchor
1746
- }
1747
- page {
1748
- id
1749
- docsReadTarget
1750
- title
1751
- content
1752
- contentFormat
1753
- breadcrumbs
1754
- lastUpdatedAt
1755
- sourceKind
1756
- source {
1757
- url
1758
- label
1759
- }
1760
- repoUrl
1761
- gitRef
1762
- requestedRef
1763
- filePath
1764
- baseUrl
1765
- }
1766
- }
1767
- ... on CodeSymbolResolutionResult {
1768
- status
1769
- candidates { name qualifiedPath kind arity filePath startLine endLine }
1770
- suggestions { name qualifiedPath localId arity filePath reason }
1771
- hasMore
1772
- repoUrl
1773
- gitRef
1774
- message
1775
- codeIndexState
1776
- }
1777
- }
1778
- }`;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=z7.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=z7.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)}})}}function createStaticTokenProvider2(token){return{getToken:async()=>token,forceRefresh:async()=>{return}}}import{createHash,randomUUID}from"node:crypto";import{z as z8}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=z8.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;import{z as z9}from"zod";var latestVersionMaliciousEvidenceSchema=z9.object({advisories:z9.array(z9.object({osvId:z9.string(),classificationReasons:z9.array(z9.string())})).max(5),totalCount:z9.number().int().nonnegative(),truncated:z9.boolean()}).nullable();var compactMatchSchema=z9.object({confidence:z9.string()});var candidateEvidenceSchema=z9.object({canonicalKey:z9.string(),nameSimilarity:z9.number().nullable()});var detailedMatchSchema=compactMatchSchema.extend({matchedAliases:z9.array(z9.string()),matchTier:z9.number().int(),score:z9.number()});var listTargetSchema=z9.object({kind:z9.string(),canonicalKey:z9.string(),latestVersionMaliciousStatus:z9.string(),latestVersionMaliciousEvidence:latestVersionMaliciousEvidenceSchema,description:z9.string().nullable().optional(),repositoryUrl:z9.string().nullable().optional(),stars:z9.number().int().nullable().optional(),downloadsLastMonth:z9.number().int().nullable().optional(),downloadsTotal:z9.number().int().nullable().optional(),docsAvailable:z9.boolean(),codeAvailable:z9.boolean(),groupKey:z9.string().nullable(),match:compactMatchSchema.nullable(),docsPageCount:z9.number().int().nullable(),codeFileCount:z9.number().int().nullable(),license:z9.string().nullable()});var targetReferenceSchema=z9.object({kind:z9.string(),canonicalKey:z9.string(),confidence:z9.string()});var detailedTargetSchema=listTargetSchema.omit({match:true}).extend({match:detailedMatchSchema.nullable(),displayName:z9.string(),registry:z9.string().nullable().optional(),packageName:z9.string().nullable().optional(),latestVersion:z9.string().nullable().optional(),repositoryOwner:z9.string().nullable().optional(),repositoryName:z9.string().nullable().optional(),documentationUrl:z9.string().nullable().optional()});var graphQLErrorSchema4=z9.object({message:z9.string(),extensions:z9.record(z9.string(),z9.unknown()).optional()});export{DEFAULT_MCP_URL2,DEFAULT_API_URL2,DEFAULT_CODE_NAV_URL2,getMcpUrl2,getApiUrl2,getCodeNavigationUrl2,getEnvApiToken2,GitHitsServiceImpl2,CLIENT_UPDATE_REQUIRED_REASON,ClientUpdateRequiredError,PKGSEER_REGISTRY_ARGS,PKGSEER_REGISTRY_LIST2,toPkgseerRegistry2,toPkgseerRegistryLowercase2,isKnownPkgseerRegistryArg,CodeNavigationAccessError,CodeNavigationGraphQLError,CodeNavigationIndexingError,CodeNavigationUnresolvableError,MalformedCodeNavigationResponseError,CodeDiffError2,CodeNavigationTargetNotFoundError,CodeNavigationFileNotFoundError,CodeNavigationVersionNotFoundError,CodeNavigationRefNotFoundError,CodeNavigationValidationError,CodeNavigationFeatureFlagRequiredError,CodeNavigationNetworkError,CodeNavigationBackendError,CodeNavigationServiceImpl2,GrepGraphQLError2,GrepBackendError2,GrepAccessError2,GrepNetworkError2,MalformedGrepResponseError2,parseGrepResult,GrepServiceImpl2,ListAccessError2,ListGraphQLError2,ListBackendError2,ListNetworkError2,MalformedListResponseError2,ListServiceImpl2,PackageIntelligenceAccessError,PackageIntelligenceFeatureFlagRequiredError,PackageIntelligenceNetworkError,PackageIntelligenceBackendError,PackageIntelligenceGraphQLError,PackageIntelligenceTargetNotFoundError,PackageIntelligenceValidationError,PackageIntelligenceDocumentationSectionUnresolvedError,PackageIntelligenceVersionNotFoundError,MalformedPackageIntelligenceResponseError,PackageIntelligenceServiceImpl2,ReadServiceImpl2,RefreshingGitHitsService2,createStaticTokenProvider2,SessionIdConfigError2,getEnvSessionId2,createClientHeaderBuilder2};