@githits/mcp 0.10.1 → 0.11.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1314 @@
1
+ import{ApiRateLimitError,AuthenticationError,DEFAULT_FETCH_TIMEOUT_MS,FetchTimeoutError,LOCAL_AUTHENTICATION_MISSING_MESSAGE,SERVER_AUTHENTICATION_REJECTED_MESSAGE,TermsAcceptanceRequiredError,fetchWithTimeout,isFetchTimeoutError,throwIfTermsAcceptanceRequired}from"./chunk-51x6tx02.js";var DEFAULT_MCP_URL="https://mcp.githits.com";var DEFAULT_API_URL="https://api.githits.com";var DEFAULT_CODE_NAV_URL="https://pkgseer.dev";class ServiceUrlConfigError extends Error{constructor(message){super(message);this.name="ServiceUrlConfigError"}}function getMcpUrl(){return resolveServiceUrl("GITHITS_MCP_URL",DEFAULT_MCP_URL)}function getApiUrl(){return resolveServiceUrl("GITHITS_API_URL",DEFAULT_API_URL)}function getCodeNavigationUrl(){if(process.env.GITHITS_CODE_NAV_URL!==undefined){return validateServiceUrl(process.env.GITHITS_CODE_NAV_URL,"GITHITS_CODE_NAV_URL")}if(process.env.PKGSEER_URL!==undefined){return validateServiceUrl(process.env.PKGSEER_URL,"PKGSEER_URL")}return DEFAULT_CODE_NAV_URL}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){const override=process.env[envName];return override===undefined?defaultUrl:validateServiceUrl(override,envName)}function getEnvApiToken(){return process.env.GITHITS_API_TOKEN}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_LIST=PKGSEER_REGISTRY_ARGS.join(", ");function toPkgseerRegistry(registry){return registryMap[registry]}function toPkgseerRegistryLowercase(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}from"zod";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 AuthenticationError||error instanceof TermsAcceptanceRequiredError}function parseRetryAfterSeconds(value,nowMs){const normalized=value?.trim();if(!normalized)return;if(/^\d+$/.test(normalized)){const delaySeconds2=Number(normalized);return Number.isSafeInteger(delaySeconds2)?delaySeconds2: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}var LANGUAGE_SCHEMA=z.object({id:z.string(),name:z.string(),display_name:z.string(),aliases:z.array(z.string()),search_priority:z.number().optional()});var LANGUAGES_SCHEMA=z.array(LANGUAGE_SCHEMA);class GitHitsServiceImpl{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()})}async getLanguages(){return withServiceDiagnostics(this.runtime.diagnostics,"githits.languages.request",async()=>{const response=await this.request("/languages",{headers:this.headers()});if(!response.ok){throw await this.createError(response)}return this.parseLanguages(response)})}async searchLanguages(query,limit=5){return withServiceDiagnostics(this.runtime.diagnostics,"githits.languages.search.request",async()=>{const params=new URLSearchParams({query,limit:String(limit)});const response=await this.request(`/languages?${params.toString()}`,{headers:this.headers()});if(!response.ok){throw await this.createError(response)}return this.parseLanguages(response)})}async submitFeedback(params){return withServiceDiagnostics(this.runtime.diagnostics,"githits.feedback.request",async()=>{const response=await this.request("/feedbacks",{method:"POST",headers:this.headers(),body:JSON.stringify({...params.exampleId!==undefined&&{example_id:params.exampleId},...params.solutionId!==undefined&&{solution_id:params.solutionId},accepted:params.accepted,feedback_text:params.feedbackText??null,...params.toolName!==undefined&&{tool_name:params.toolName}})});if(!response.ok){throw await this.createError(response)}return{success:true,message:"Feedback submitted successfully"}})}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 parseLanguages(response){let data;try{data=await response.json()}catch(cause){throw new Error("GitHits returned an invalid languages response.",{cause})}const parsed=LANGUAGES_SCHEMA.safeParse(data);if(!parsed.success){throw new Error("GitHits returned an invalid languages response.",{cause:parsed.error})}return parsed.data}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 AuthenticationError(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 ApiRateLimitError(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 FetchTimeoutError{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)))}import{z as z2}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");let response;try{response=await fetchWithTimeout(`${baseUrl(endpointUrl)}/api/graphql`,{method:"POST",headers:{...request.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){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(()=>"");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 AuthenticationError(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)}}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 CodeDiffError 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_SELECTION=`
85
+ indexingEstimate {
86
+ lowerSeconds
87
+ upperSeconds
88
+ elapsedSeconds
89
+ sampleCount
90
+ source
91
+ }`;var UNIFIED_SEARCH_QUERY=`
92
+ query UnifiedSearch(
93
+ $targets: [SearchPackageInput!]!
94
+ $query: String!
95
+ $sources: [DiscoverySearchSource!]
96
+ $filters: DiscoverySearchFiltersInput
97
+ $allowPartialResults: Boolean
98
+ $limit: Int
99
+ $offset: Int
100
+ $waitTimeoutMs: Int
101
+ ) {
102
+ search(
103
+ targets: $targets
104
+ query: $query
105
+ sources: $sources
106
+ filters: $filters
107
+ allowPartialResults: $allowPartialResults
108
+ limit: $limit
109
+ offset: $offset
110
+ waitTimeoutMs: $waitTimeoutMs
111
+ ) {
112
+ completed
113
+ searchRef
114
+ result {
115
+ query
116
+ queryWarnings
117
+ sources
118
+ results {
119
+ id
120
+ resultType
121
+ targetLabel
122
+ requestedTargetLabel
123
+ freshTargetLabel
124
+ servedTargetLabel
125
+ freshness
126
+ title
127
+ summary
128
+ score
129
+ highlights {
130
+ title
131
+ summary
132
+ }
133
+ locator {
134
+ registry
135
+ packageName
136
+ version
137
+ pageId
138
+ sourceKind
139
+ sourceUrl
140
+ repoUrl
141
+ gitRef
142
+ requestedRef
143
+ filePath
144
+ startLine
145
+ endLine
146
+ fileContentHash
147
+ symbolRef
148
+ qualifiedPath
149
+ kind
150
+ category
151
+ language
152
+ }
153
+ }
154
+ page {
155
+ offset
156
+ limit
157
+ returned
158
+ hasMore
159
+ }
160
+ partialResults
161
+ evidenceNotice
162
+ sourceStatus {
163
+ source
164
+ targetLabel
165
+ requestedTargetLabel
166
+ freshTargetLabel
167
+ servedTargetLabel
168
+ ${TARGET_RESOLUTION_SELECTION}
169
+ indexingStatus
170
+ codeIndexState
171
+ resultCount
172
+ appliedFilters
173
+ ignoredFilters
174
+ incompatibleFilters
175
+ appliedQueryFeatures
176
+ ignoredQueryFeatures
177
+ incompatibleQueryFeatures
178
+ suggestedSiteTargets
179
+ suggestedSiteTargetsTruncated
180
+ note
181
+ ${DOC_COVERAGE_SELECTION}
182
+ ${DOCUMENTATION_CONTRIBUTORS_SELECTION}
183
+ }
184
+ }
185
+ progress {
186
+ searchRef
187
+ status
188
+ targetsTotal
189
+ targetsReady
190
+ elapsedMs
191
+ query
192
+ queryWarnings
193
+ sources
194
+ requestedSources
195
+ targetMode
196
+ requestedTargets {
197
+ registry
198
+ name
199
+ version
200
+ repoUrl
201
+ gitRef
202
+ site
203
+ }
204
+ filters {
205
+ fileIntent
206
+ kind
207
+ category
208
+ publicOnly
209
+ pathPrefix
210
+ }
211
+ limit
212
+ offset
213
+ targets {
214
+ requested
215
+ resolvedRequested
216
+ served
217
+ freshness
218
+ indexingRef
219
+ requestedRefKind
220
+ ${TARGET_RESOLUTION_SELECTION}
221
+ ${DISCOVERY_TARGET_PROGRESS_RETRY_SELECTION}
222
+ ${DOC_COVERAGE_SELECTION}
223
+ }
224
+ expiresAt
225
+ }
226
+ }
227
+ }`;var UNIFIED_SEARCH_STATUS_QUERY=`
228
+ query UnifiedSearchStatus($searchRef: String!, $includeResults: Boolean!, $waitTimeoutMs: Int) {
229
+ discoverySearchProgress(searchRef: $searchRef, includeResults: $includeResults, waitTimeoutMs: $waitTimeoutMs) {
230
+ searchRef
231
+ status
232
+ targetsTotal
233
+ targetsReady
234
+ elapsedMs
235
+ query
236
+ queryWarnings
237
+ sources
238
+ requestedSources
239
+ targetMode
240
+ requestedTargets {
241
+ registry
242
+ name
243
+ version
244
+ repoUrl
245
+ gitRef
246
+ site
247
+ }
248
+ filters {
249
+ fileIntent
250
+ kind
251
+ category
252
+ publicOnly
253
+ pathPrefix
254
+ }
255
+ limit
256
+ offset
257
+ targets {
258
+ requested
259
+ resolvedRequested
260
+ served
261
+ freshness
262
+ indexingRef
263
+ requestedRefKind
264
+ ${TARGET_RESOLUTION_SELECTION}
265
+ ${DISCOVERY_TARGET_PROGRESS_RETRY_SELECTION}
266
+ ${DOC_COVERAGE_SELECTION}
267
+ }
268
+ expiresAt
269
+ results {
270
+ query
271
+ queryWarnings
272
+ sources
273
+ results {
274
+ id
275
+ resultType
276
+ targetLabel
277
+ requestedTargetLabel
278
+ freshTargetLabel
279
+ servedTargetLabel
280
+ freshness
281
+ title
282
+ summary
283
+ score
284
+ highlights {
285
+ title
286
+ summary
287
+ }
288
+ locator {
289
+ registry
290
+ packageName
291
+ version
292
+ pageId
293
+ sourceKind
294
+ sourceUrl
295
+ repoUrl
296
+ gitRef
297
+ requestedRef
298
+ filePath
299
+ startLine
300
+ endLine
301
+ fileContentHash
302
+ symbolRef
303
+ qualifiedPath
304
+ kind
305
+ category
306
+ language
307
+ }
308
+ }
309
+ page {
310
+ offset
311
+ limit
312
+ returned
313
+ hasMore
314
+ }
315
+ partialResults
316
+ evidenceNotice
317
+ sourceStatus {
318
+ source
319
+ targetLabel
320
+ requestedTargetLabel
321
+ freshTargetLabel
322
+ servedTargetLabel
323
+ ${TARGET_RESOLUTION_SELECTION}
324
+ indexingStatus
325
+ codeIndexState
326
+ resultCount
327
+ appliedFilters
328
+ ignoredFilters
329
+ incompatibleFilters
330
+ appliedQueryFeatures
331
+ ignoredQueryFeatures
332
+ incompatibleQueryFeatures
333
+ suggestedSiteTargets
334
+ suggestedSiteTargetsTruncated
335
+ note
336
+ ${DOC_COVERAGE_SELECTION}
337
+ ${DOCUMENTATION_CONTRIBUTORS_SELECTION}
338
+ }
339
+ }
340
+ }
341
+ }`;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=z2.object({version:z2.string().nullable().optional(),ref:z2.string()});var indexingDurationEstimateSchema=z2.object({lowerSeconds:z2.number().int().nullable().optional(),upperSeconds:z2.number().int().nullable().optional(),elapsedSeconds:z2.number().int().nullable().optional(),sampleCount:z2.number().int().nullable().optional(),source:z2.string().nullable().optional()}).nullable().optional();var targetResolutionIdentitySchema=z2.object({kind:z2.string().nullable().optional(),registry:z2.string().nullable().optional(),packageName:z2.string().nullable().optional(),version:z2.string().nullable().optional(),repoUrl:z2.string().nullable().optional(),gitRef:z2.string().nullable().optional(),commitSha:z2.string().nullable().optional(),site:z2.string().nullable().optional()}).nullable().optional();var targetResolutionSchema=z2.object({requested:targetResolutionIdentitySchema,resolvedRequested:targetResolutionIdentitySchema,served:targetResolutionIdentitySchema,freshness:z2.string().nullable().optional(),freshnessReason:z2.string().nullable().optional(),indexingRef:z2.string().nullable().optional(),availableVersions:z2.array(availableVersionSchema).nullable().optional(),availableRefs:z2.array(availableVersionSchema).nullable().optional(),suggestedRefs:z2.array(availableVersionSchema).nullable().optional()}).nullable().optional();var unifiedSearchSourceSchema=z2.enum(["AUTO","DOCS","CODE","SYMBOL"]);var unifiedSearchResultTypeSchema=z2.enum(["DOCUMENTATION_PAGE","REPOSITORY_SYMBOL","REPOSITORY_CODE","REPOSITORY_DOC"]);var unifiedSearchLocatorSchema=z2.object({registry:z2.string().nullable().optional(),packageName:z2.string().nullable().optional(),version:z2.string().nullable().optional(),pageId:z2.string().nullable().optional(),sourceKind:z2.string().nullable().optional(),sourceUrl:z2.string().nullable().optional(),repoUrl:z2.string().nullable().optional(),gitRef:z2.string().nullable().optional(),requestedRef:z2.string().nullable().optional(),filePath:z2.string().nullable().optional(),startLine:z2.number().int().nullable().optional(),endLine:z2.number().int().nullable().optional(),fileContentHash:z2.string().nullable().optional(),symbolRef:z2.string().nullable().optional(),qualifiedPath:z2.string().nullable().optional(),kind:z2.string().nullable().optional(),category:z2.string().nullable().optional(),language:z2.string().nullable().optional()});var unifiedSearchHitSchema=z2.object({id:z2.string(),resultType:unifiedSearchResultTypeSchema,targetLabel:z2.string(),requestedTargetLabel:z2.string().nullable().optional(),freshTargetLabel:z2.string().nullable().optional(),servedTargetLabel:z2.string().nullable().optional(),freshness:z2.string().nullable().optional(),title:z2.string().nullable().optional(),summary:z2.string().nullable().optional(),score:z2.number().nullable().optional(),highlights:z2.object({title:z2.array(z2.tuple([z2.number().int(),z2.number().int()])).nullable().optional(),summary:z2.array(z2.tuple([z2.number().int(),z2.number().int()])).nullable().optional()}).nullable().optional(),locator:unifiedSearchLocatorSchema});var unifiedSearchPageInfoSchema=z2.object({offset:z2.number().int(),limit:z2.number().int(),returned:z2.number().int(),hasMore:z2.boolean()});var docCoverageSchema=z2.object({coverageState:z2.string(),coverageReason:z2.string().nullable().optional(),pagesCrawled:z2.number().int().nullable().optional(),frontierRemaining:z2.number().int().nullable().optional(),artifactOverflowPageCount:z2.number().int().nullable().optional(),estimatedTotalPages:z2.number().int().nullable().optional(),note:z2.string().nullable().optional()}).nullable().optional();var unifiedSearchDocumentationContributorSchema=z2.object({kind:z2.enum(["REPOSITORY_DOCS","DOCPACK"]),state:z2.enum(["SEARCHED","READY","PENDING","UNAVAILABLE"]),freshness:z2.enum(["CURRENT","PROVISIONAL","STALE"]).nullable().optional(),resultCount:z2.number().int().nonnegative(),repositoryUrl:z2.string().nullable().optional(),commitSha:z2.string().nullable().optional(),siteKey:z2.string().nullable().optional(),siteUrl:z2.string().nullable().optional(),coverage:docCoverageSchema});var unifiedSearchSourceStatusSchema=z2.object({source:unifiedSearchSourceSchema,targetLabel:z2.string(),requestedTargetLabel:z2.string().nullable().optional(),freshTargetLabel:z2.string().nullable().optional(),servedTargetLabel:z2.string().nullable().optional(),targetResolution:targetResolutionSchema,indexingStatus:z2.string().nullable().optional(),codeIndexState:z2.string().nullable().optional(),resultCount:z2.number().int().nullable().optional(),appliedFilters:z2.array(z2.string()),ignoredFilters:z2.array(z2.string()),incompatibleFilters:z2.array(z2.string()),appliedQueryFeatures:z2.array(z2.string()),ignoredQueryFeatures:z2.array(z2.string()),incompatibleQueryFeatures:z2.array(z2.string()),suggestedSiteTargets:z2.array(z2.string()),suggestedSiteTargetsTruncated:z2.boolean(),note:z2.string().nullable().optional(),coverage:docCoverageSchema,contributors:z2.array(unifiedSearchDocumentationContributorSchema)});var unifiedSearchResultSchema=z2.object({query:z2.string(),queryWarnings:z2.array(z2.string()),sources:z2.array(unifiedSearchSourceSchema),results:z2.array(unifiedSearchHitSchema),page:unifiedSearchPageInfoSchema,partialResults:z2.boolean(),sourceStatus:z2.array(unifiedSearchSourceStatusSchema),evidenceNotice:z2.string().nullable().optional()});var unifiedSearchSessionStatusSchema=z2.string().min(1);var unifiedSearchFiltersSchema=z2.object({fileIntent:z2.string().nullable().optional(),kind:z2.string().nullable().optional(),category:z2.string().nullable().optional(),publicOnly:z2.boolean().nullable().optional(),pathPrefix:z2.string().nullable().optional()}).nullable().optional();var unifiedSearchProgressTargetSchema=z2.object({requested:z2.string().nullable().optional(),resolvedRequested:z2.string().nullable().optional(),served:z2.string().nullable().optional(),freshness:z2.string().nullable().optional(),indexingRef:z2.string().nullable().optional(),requestedRefKind:z2.string().nullable().optional(),targetResolution:targetResolutionSchema,availableVersions:z2.array(availableVersionSchema).nullable().optional(),availableRefs:z2.array(availableVersionSchema).nullable().optional(),suggestedRefs:z2.array(availableVersionSchema).nullable().optional(),coverage:docCoverageSchema});var unifiedSearchRequestedTargetSchema=z2.object({registry:z2.string().nullable().optional(),name:z2.string().nullable().optional(),version:z2.string().nullable().optional(),repoUrl:z2.string().nullable().optional(),gitRef:z2.string().nullable().optional(),site:z2.string().nullable().optional()});var unifiedSearchProgressSchema=z2.object({searchRef:z2.string(),status:unifiedSearchSessionStatusSchema,targetsTotal:z2.number().int(),targetsReady:z2.number().int(),elapsedMs:z2.number().int(),query:z2.string(),queryWarnings:z2.array(z2.string()),sources:z2.array(unifiedSearchSourceSchema),requestedSources:z2.array(unifiedSearchSourceSchema).nullable().optional(),targetMode:z2.string().nullable().optional(),requestedTargets:z2.array(unifiedSearchRequestedTargetSchema).nullable().optional(),filters:unifiedSearchFiltersSchema,limit:z2.number().int().nullable().optional(),offset:z2.number().int().nullable().optional(),targets:z2.array(unifiedSearchProgressTargetSchema).nullable().optional(),expiresAt:z2.string().nullable().optional(),results:unifiedSearchResultSchema.nullable().optional()});var asyncUnifiedSearchResultSchema=z2.object({completed:z2.boolean(),searchRef:z2.string().nullable().optional(),result:unifiedSearchResultSchema.nullable().optional(),progress:unifiedSearchProgressSchema.nullable().optional()});var graphQLErrorSchema=z2.object({message:z2.string(),extensions:z2.record(z2.string(),z2.unknown()).optional()});var codeDiffGraphQLErrorSchema=z2.object({message:z2.string(),path:z2.array(z2.union([z2.string(),z2.number().int()])).nullable().optional(),extensions:z2.record(z2.string(),z2.unknown()).optional()});var codeDiffRegistrySchema=z2.enum(PKGSEER_REGISTRY_VALUES);var codeDiffPackageInfoSchema=z2.object({registry:codeDiffRegistrySchema,name:z2.string(),repoUrl:z2.string()});var codeDiffRefResolutionSchema=z2.object({requested:z2.string(),resolvedVersion:z2.string().nullable().optional(),ref:z2.string(),commitSha:z2.string(),refKind:z2.enum(["SHA","TAG","BRANCH","HEAD","UNKNOWN"]),versionSource:z2.enum(["REGISTRY","GIT_HEAD","TAG","RELEASE"]).nullable().optional()});var rawCodeDiffSummarySchema=z2.object({filesChanged:z2.number().int(),added:z2.number().int(),deleted:z2.number().int(),modified:z2.number().int(),modeChanged:z2.number().int(),typeChanged:z2.number().int(),inventoryComplete:z2.boolean(),unprojectableFiles:z2.number().int()});var rawCodeDiffScopeSchema=z2.object({status:z2.enum(["PACKAGE","REPOSITORY","UNKNOWN"]),fromSubpath:z2.string().nullable().optional(),toSubpath:z2.string().nullable().optional(),pathPrefix:z2.string().nullable().optional(),pathGlob:z2.string().nullable().optional()});var rawCodeDiffContentFailureSchema=z2.object({code:z2.string(),retryable:z2.boolean(),retryAfterMs:z2.number().int().nullable().optional(),stage:z2.string().nullable().optional(),limitKind:z2.string().nullable().optional()});var contentSafetySchema=z2.object({filtered:z2.boolean(),modifications:z2.array(z2.enum(["INVISIBLE_CONTROLS_STRIPPED","HTML_COMMENTS_STRIPPED","IMAGES_REPLACED","UNSAFE_LINKS_NEUTRALIZED"]))});var rawCodeDiffFileSchema=z2.object({path:z2.string(),pathEncoding:z2.enum(["UTF8","BYTE_ESCAPED"]),status:z2.enum(["ADDED","DELETED","MODIFIED"]),modeChanged:z2.boolean(),typeChanged:z2.boolean(),additions:z2.number().int().nullable().optional(),deletions:z2.number().int().nullable().optional(),patch:z2.string().nullable().optional(),contentStatus:z2.enum(["NOT_REQUESTED","STATS","PATCH","BINARY","METADATA_ONLY","OMITTED","UNAVAILABLE"]),contentOmissionReason:z2.string().nullable().optional(),contentSafety:contentSafetySchema});var rawCodeDiffSchema=z2.object({summary:rawCodeDiffSummarySchema,scope:rawCodeDiffScopeSchema,contentCoverage:z2.enum(["NOT_REQUESTED","COMPLETE","PARTIAL","FAILED"]),contentFailure:rawCodeDiffContentFailureSchema.nullable().optional(),files:z2.array(rawCodeDiffFileSchema),hasMoreFiles:z2.boolean()});var codeDiffResultSchema=z2.object({package:codeDiffPackageInfoSchema.nullable().optional(),fromResolution:codeDiffRefResolutionSchema,toResolution:codeDiffRefResolutionSchema,raw:rawCodeDiffSchema.nullable().optional()});var codeDiffGraphQLResponseSchema=z2.object({data:z2.object({codeDiff:codeDiffResultSchema.nullable().optional()}).nullable().optional(),errors:z2.array(codeDiffGraphQLErrorSchema).optional()});var CODE_DIFF_OPTION_KEYS=new Set(["maxFiles","maxPatchBytes","pathPrefix","pathGlob"]);var CODE_DIFF_COMMON_SELECTION=` package {
342
+ registry
343
+ name
344
+ repoUrl
345
+ }
346
+ fromResolution {
347
+ requested
348
+ resolvedVersion
349
+ ref
350
+ commitSha
351
+ refKind
352
+ versionSource
353
+ }
354
+ toResolution {
355
+ requested
356
+ resolvedVersion
357
+ ref
358
+ commitSha
359
+ refKind
360
+ versionSource
361
+ }
362
+ raw {
363
+ summary {
364
+ filesChanged
365
+ added
366
+ deleted
367
+ modified
368
+ modeChanged
369
+ typeChanged
370
+ inventoryComplete
371
+ unprojectableFiles
372
+ }
373
+ scope {
374
+ status
375
+ fromSubpath
376
+ toSubpath
377
+ pathPrefix
378
+ pathGlob
379
+ }
380
+ contentCoverage
381
+ contentFailure {
382
+ code
383
+ retryable
384
+ retryAfterMs
385
+ stage
386
+ limitKind
387
+ }
388
+ files {
389
+ path
390
+ pathEncoding
391
+ status
392
+ modeChanged
393
+ typeChanged
394
+ contentStatus
395
+ contentSafety {
396
+ filtered
397
+ modifications
398
+ }`;function buildCodeDiffQuery(mode){const contentFields=mode==="inventory"?"":mode==="stats"?`
399
+ additions
400
+ deletions`:`
401
+ additions
402
+ deletions
403
+ patch
404
+ contentOmissionReason`;return`
405
+ query CodeDiff(
406
+ $registry: Registry
407
+ $name: String
408
+ $fromVersion: String
409
+ $toVersion: String
410
+ $repoUrl: String
411
+ $fromRef: String
412
+ $toRef: String
413
+ $rawOptions: RawCodeDiffOptions
414
+ ) {
415
+ codeDiff(
416
+ registry: $registry
417
+ name: $name
418
+ fromVersion: $fromVersion
419
+ toVersion: $toVersion
420
+ repoUrl: $repoUrl
421
+ fromRef: $fromRef
422
+ toRef: $toRef
423
+ rawOptions: $rawOptions
424
+ ) {
425
+ ${CODE_DIFF_COMMON_SELECTION}${contentFields}
426
+ }
427
+ hasMoreFiles
428
+ }
429
+ }
430
+ }`}var navigationResolutionSchema=z2.object({requestedVersion:z2.string().nullable().optional(),requestedRef:z2.string().nullable().optional(),resolvedRef:z2.string().nullable().optional(),commitSha:z2.string().nullable().optional()}).nullable().optional();var navigationDiagnosticsSchema=z2.object({hint:z2.string().nullable().optional()}).nullable().optional();var repoFileEntrySchema=z2.object({path:z2.string(),name:z2.string().nullable().optional(),language:z2.string().nullable().optional(),fileType:z2.string().nullable().optional(),byteSize:z2.number().int().nullable().optional()});var listRepoFilesResponseSchema=z2.object({files:z2.array(repoFileEntrySchema),total:z2.number().int(),hasMore:z2.boolean(),indexedVersion:z2.string().nullable().optional(),resolution:navigationResolutionSchema,targetResolution:targetResolutionSchema,diagnostics:navigationDiagnosticsSchema,codeIndexState:z2.string(),indexingRef:z2.string().nullable().optional(),availableVersions:z2.array(availableVersionSchema).nullable().optional(),indexingEstimate:indexingDurationEstimateSchema});var listRepoFilesGraphQLResponseSchema=z2.object({data:z2.object({listRepoFiles:listRepoFilesResponseSchema.nullable().optional()}).nullable().optional(),errors:z2.array(graphQLErrorSchema).optional()});var LIST_REPO_FILES_QUERY=`
431
+ query ListRepoFiles(
432
+ $registry: Registry
433
+ $packageName: String
434
+ $repoUrl: String
435
+ $gitRef: String
436
+ $version: String
437
+ $pathPrefix: String
438
+ $pathSelectors: [FilePathSelectorInput!]
439
+ $extensions: [String!]
440
+ $fileTypes: [String!]
441
+ $languages: [String!]
442
+ $fileIntent: FileIntent
443
+ $fileIntents: [FileIntent!]
444
+ $excludeFileIntents: [FileIntent!]
445
+ $excludeDocFiles: Boolean
446
+ $excludeTestFiles: Boolean
447
+ $includeHidden: Boolean
448
+ $limit: Int
449
+ $waitTimeoutMs: Int
450
+ ) {
451
+ listRepoFiles(
452
+ registry: $registry
453
+ packageName: $packageName
454
+ repoUrl: $repoUrl
455
+ gitRef: $gitRef
456
+ version: $version
457
+ pathPrefix: $pathPrefix
458
+ pathSelectors: $pathSelectors
459
+ extensions: $extensions
460
+ fileTypes: $fileTypes
461
+ languages: $languages
462
+ fileIntent: $fileIntent
463
+ fileIntents: $fileIntents
464
+ excludeFileIntents: $excludeFileIntents
465
+ excludeDocFiles: $excludeDocFiles
466
+ excludeTestFiles: $excludeTestFiles
467
+ includeHidden: $includeHidden
468
+ limit: $limit
469
+ waitTimeoutMs: $waitTimeoutMs
470
+ ) {
471
+ files {
472
+ path
473
+ name
474
+ language
475
+ fileType
476
+ byteSize
477
+ }
478
+ total
479
+ hasMore
480
+ indexedVersion
481
+ resolution {
482
+ requestedVersion
483
+ requestedRef
484
+ resolvedRef
485
+ commitSha
486
+ }
487
+ ${TARGET_RESOLUTION_SELECTION}
488
+ diagnostics {
489
+ hint
490
+ }
491
+ codeIndexState
492
+ indexingRef
493
+ availableVersions {
494
+ version
495
+ ref
496
+ }
497
+ ${INDEXING_DURATION_ESTIMATE_SELECTION}
498
+ }
499
+ }`;var codeContextResponseSchema=z2.object({content:z2.string().nullable().optional(),filePath:z2.string().nullable().optional(),language:z2.string().nullable().optional(),totalLines:z2.number().int().nullable().optional(),startLine:z2.number().int().nullable().optional(),endLine:z2.number().int().nullable().optional(),repoUrl:z2.string().nullable().optional(),gitRef:z2.string().nullable().optional(),isBinary:z2.boolean().nullable().optional(),codeIndexState:z2.string(),indexingRef:z2.string().nullable().optional(),availableVersions:z2.array(availableVersionSchema).nullable().optional(),indexingEstimate:indexingDurationEstimateSchema,targetResolution:targetResolutionSchema});var fetchCodeContextGraphQLResponseSchema=z2.object({data:z2.object({fetchCodeContext:codeContextResponseSchema.nullable().optional()}).nullable().optional(),errors:z2.array(graphQLErrorSchema).optional()});var FETCH_CODE_CONTEXT_QUERY=`
500
+ query FetchCodeContext(
501
+ $registry: Registry
502
+ $packageName: String
503
+ $repoUrl: String
504
+ $gitRef: String
505
+ $version: String
506
+ $filePath: String!
507
+ $startLine: Int
508
+ $endLine: Int
509
+ $waitTimeoutMs: Int
510
+ ) {
511
+ fetchCodeContext(
512
+ registry: $registry
513
+ packageName: $packageName
514
+ repoUrl: $repoUrl
515
+ gitRef: $gitRef
516
+ version: $version
517
+ filePath: $filePath
518
+ startLine: $startLine
519
+ endLine: $endLine
520
+ waitTimeoutMs: $waitTimeoutMs
521
+ ) {
522
+ content
523
+ filePath
524
+ language
525
+ totalLines
526
+ startLine
527
+ endLine
528
+ repoUrl
529
+ gitRef
530
+ isBinary
531
+ codeIndexState
532
+ indexingRef
533
+ ${CODE_CONTEXT_AVAILABLE_VERSIONS_SELECTION}
534
+ ${INDEXING_DURATION_ESTIMATE_SELECTION}
535
+ ${TARGET_RESOLUTION_SELECTION}
536
+ }
537
+ }`;var grepRepoMatchSchema=z2.object({filePath:z2.string(),line:z2.number().int(),matchStartByte:z2.number().int(),matchEndByte:z2.number().int(),lineContent:z2.string(),contextBefore:z2.array(z2.string()).nullable().optional(),contextAfter:z2.array(z2.string()).nullable().optional(),fileContentHash:z2.string().nullable().optional(),fileIntent:z2.string().nullable().optional(),symbolRowId:z2.string().nullable().optional(),symbol:z2.object({symbolRef:z2.string().optional(),name:z2.string().optional(),qualifiedPath:z2.string().nullable().optional(),kind:z2.string().nullable().optional(),category:z2.string().nullable().optional(),arity:z2.number().int().nullable().optional(),isPublic:z2.boolean().nullable().optional(),filePath:z2.string().nullable().optional(),startLine:z2.number().int().nullable().optional(),endLine:z2.number().int().nullable().optional(),code:z2.string().nullable().optional(),callerCount:z2.number().int().nullable().optional(),contentHash:z2.string().nullable().optional(),parentSymbolRef:z2.string().nullable().optional(),parentPath:z2.string().nullable().optional()}).nullable().optional()});var grepRepoResponseSchema=z2.object({matches:z2.array(grepRepoMatchSchema),nextCursor:z2.string().nullable().optional(),hasMore:z2.boolean(),truncatedReason:z2.enum(["NONE","MAX_MATCHES","MAX_MATCHES_PER_FILE","DEADLINE"]),routeTaken:z2.enum(["SINGLE_FILE","CONTENT_INDEX"]).nullable().optional(),filesScanned:z2.number().int(),filesInScope:z2.number().int(),binaryFilesSkipped:z2.number().int(),filesTooLargeSkipped:z2.number().int(),totalMatches:z2.number().int(),uniqueFilesMatched:z2.number().int(),indexedVersion:z2.string().nullable().optional(),resolution:navigationResolutionSchema,targetResolution:targetResolutionSchema,codeIndexState:z2.string(),indexingRef:z2.string().nullable().optional(),availableVersions:z2.array(availableVersionSchema).nullable().optional(),indexingEstimate:indexingDurationEstimateSchema});var grepRepoGraphQLResponseSchema=z2.object({data:z2.object({grepRepo:grepRepoResponseSchema.nullable().optional()}).nullable().optional(),errors:z2.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",code:"code",caller_count:"callerCount",content_hash:"contentHash",parent_symbol_ref:"parentSymbolRef",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(`
538
+ `);const symbolBlock=symbolSelection.length>0?`
539
+ symbol {
540
+ ${symbolSelection}
541
+ }`:"";return`
542
+ query GrepRepo(
543
+ $registry: Registry
544
+ $packageName: String
545
+ $repoUrl: String
546
+ $gitRef: String
547
+ $version: String
548
+ $waitTimeoutMs: Int
549
+ $pattern: String!
550
+ $patternType: GrepPatternType
551
+ $caseSensitive: Boolean
552
+ $pathSelectors: [GrepPathSelectorInput!]
553
+ $extensions: [String!]
554
+ $excludeDocFiles: Boolean
555
+ $excludeTestFiles: Boolean
556
+ $allowUnscoped: Boolean
557
+ $contextLinesBefore: Int
558
+ $contextLinesAfter: Int
559
+ $maxMatches: Int
560
+ $maxMatchesPerFile: Int
561
+ $cursor: String
562
+ $symbolFields: [String!]
563
+ ) {
564
+ grepRepo(
565
+ registry: $registry
566
+ packageName: $packageName
567
+ repoUrl: $repoUrl
568
+ gitRef: $gitRef
569
+ version: $version
570
+ waitTimeoutMs: $waitTimeoutMs
571
+ pattern: $pattern
572
+ patternType: $patternType
573
+ caseSensitive: $caseSensitive
574
+ pathSelectors: $pathSelectors
575
+ extensions: $extensions
576
+ excludeDocFiles: $excludeDocFiles
577
+ excludeTestFiles: $excludeTestFiles
578
+ allowUnscoped: $allowUnscoped
579
+ contextLinesBefore: $contextLinesBefore
580
+ contextLinesAfter: $contextLinesAfter
581
+ maxMatches: $maxMatches
582
+ maxMatchesPerFile: $maxMatchesPerFile
583
+ cursor: $cursor
584
+ symbolFields: $symbolFields
585
+ ) {
586
+ matches {
587
+ filePath
588
+ line
589
+ matchStartByte
590
+ matchEndByte
591
+ lineContent
592
+ contextBefore
593
+ contextAfter
594
+ fileContentHash
595
+ fileIntent
596
+ symbolRowId${symbolBlock}
597
+ }
598
+ nextCursor
599
+ totalMatches
600
+ hasMore
601
+ truncatedReason
602
+ routeTaken
603
+ filesScanned
604
+ filesInScope
605
+ binaryFilesSkipped
606
+ filesTooLargeSkipped
607
+ uniqueFilesMatched
608
+ indexedVersion
609
+ resolution {
610
+ requestedVersion
611
+ requestedRef
612
+ resolvedRef
613
+ commitSha
614
+ }
615
+ ${TARGET_RESOLUTION_SELECTION}
616
+ codeIndexState
617
+ indexingRef
618
+ availableVersions {
619
+ version
620
+ ref
621
+ }
622
+ ${INDEXING_DURATION_ESTIMATE_SELECTION}
623
+ }
624
+ }`}var unifiedSearchGraphQLResponseSchema=z2.object({data:z2.object({search:asyncUnifiedSearchResultSchema.nullable().optional()}).nullable().optional(),errors:z2.array(graphQLErrorSchema).optional()});var unifiedSearchStatusGraphQLResponseSchema=z2.object({data:z2.object({discoverySearchProgress:unifiedSearchProgressSchema.nullable().optional()}).nullable().optional(),errors:z2.array(graphQLErrorSchema).optional()});class CodeNavigationServiceImpl{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,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,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){return executeWithTokenRefresh({getToken:()=>this.tokenProvider.getToken(),forceRefresh:()=>this.tokenProvider.forceRefresh(),shouldRefresh:isTokenRefreshableError,executeWithToken:(token)=>this.executeUnifiedSearch(token,params)})}async searchStatus(searchRef,waitTimeoutMs=0){return executeWithTokenRefresh({getToken:()=>this.tokenProvider.getToken(),forceRefresh:()=>this.tokenProvider.forceRefresh(),shouldRefresh:isTokenRefreshableError,executeWithToken:(token)=>this.executeUnifiedSearchStatus(token,searchRef,waitTimeoutMs)})}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 CodeDiffError(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:message2,extensions:extensions2})=>({message:message2,extensions:extensions2}));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 AuthenticationError(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 CodeDiffError(message,parseCodeDiffErrorDetails(errors))}async executeUnifiedSearch(token,params){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})}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){let response;try{response=await this.postGraphqlWithTargetResolutionFallback({token,query:UNIFIED_SEARCH_STATUS_QUERY,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){const status=response.status;const detail=parseDetail(response.responseBody);if(status===401){return new AuthenticationError(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)}createTransportError(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})}createGraphQLError(errors){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,this.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(this.runtime.diagnostics?.isEnabled("code-nav")){this.runtime.diagnostics.debug("code-nav",{event:"graphql-schema-mismatch",code:code??"omitted",message})}return new CodeNavigationBackendError(this.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"UNAUTHORIZED":return new AuthenticationError(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)}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)=>({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,summary:entry.summary??undefined,score:entry.score??undefined,highlights:entry.highlights?{title:entry.highlights.title??undefined,summary:entry.highlights.summary??undefined}:undefined,locator:{registry:entry.locator.registry??undefined,packageName:entry.locator.packageName??undefined,version:entry.locator.version??undefined,pageId:entry.locator.pageId??undefined,sourceKind:entry.locator.sourceKind??undefined,sourceUrl:entry.locator.sourceUrl??undefined,repoUrl:entry.locator.repoUrl??undefined,gitRef:entry.locator.gitRef??undefined,requestedRef:entry.locator.requestedRef??undefined,filePath:entry.locator.filePath??undefined,startLine:entry.locator.startLine??undefined,endLine:entry.locator.endLine??undefined,fileContentHash:entry.locator.fileContentHash??undefined,symbolRef:entry.locator.symbolRef??undefined,qualifiedPath:entry.locator.qualifiedPath??undefined,kind:entry.locator.kind??undefined,category:entry.locator.category??undefined,language:entry.locator.language??undefined}})),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)})),expiresAt:progress.expiresAt??undefined}}throwIfIndexing(data){if(data.codeIndexState==="INDEXING"){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)}}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{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)}}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,code:entry.symbol.code??undefined,callerCount:entry.symbol.callerCount??undefined,contentHash:entry.symbol.contentHash??undefined,parentSymbolRef:entry.symbol.parentSymbolRef??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 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}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 parseDetail(body){if(!body)return;try{const parsed=JSON.parse(body);if(typeof parsed.detail==="string")return parsed.detail;if(typeof parsed.error==="string")return parsed.error}catch{return body}return}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 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 z3}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 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"}}class PackageIntelligenceChangelogSourceNotFoundError extends Error{constructor(message){super(message);this.name="PackageIntelligenceChangelogSourceNotFoundError"}}var githubRepositorySchema=z3.object({stargazersCount:z3.number().int().nullable().optional(),forksCount:z3.number().int().nullable().optional(),openIssuesCount:z3.number().int().nullable().optional(),archived:z3.boolean().nullable().optional(),language:z3.string().nullable().optional(),topics:z3.array(z3.string()).nullable().optional(),pushedAt:z3.string().nullable().optional()}).nullable().optional();var packageIdentitySchema=z3.object({name:z3.string().nullable().optional(),registry:z3.string().nullable().optional(),description:z3.string().nullable().optional(),latestVersion:z3.string().nullable().optional(),latestVersionPublishedAt:z3.string().nullable().optional(),homepage:z3.string().nullable().optional(),repositoryUrl:z3.string().nullable().optional(),license:z3.string().nullable().optional(),downloadsLastMonth:z3.number().int().nullable().optional(),downloadsTotal:z3.number().int().nullable().optional(),githubRepository:githubRepositorySchema});var vulnerabilityOverviewSchema=z3.object({osvId:z3.string().nullable().optional(),summary:z3.string().nullable().optional(),severityScore:z3.number().nullable().optional(),publishedAt:z3.string().nullable().optional()});var packageSecurityOverviewSchema=z3.object({vulnerabilityCount:z3.number().int().nullable().optional(),hasCurrentVulnerabilities:z3.boolean().nullable().optional(),recentVulnerabilities:z3.array(vulnerabilityOverviewSchema).nullable().optional()}).nullable().optional();var changelogEntrySchema=z3.object({version:z3.string().nullable().optional(),publishedAt:z3.string().nullable().optional(),body:z3.string().nullable().optional()});var packageSummaryResponseSchema=z3.object({package:packageIdentitySchema.nullable().optional(),security:packageSecurityOverviewSchema,latestChangelogs:z3.array(changelogEntrySchema).nullable().optional()});var graphQLErrorSchema2=z3.object({message:z3.string(),extensions:z3.record(z3.string(),z3.unknown()).optional()});var graphQLResponseSchema=z3.object({data:z3.object({packageSummary:packageSummaryResponseSchema.nullable().optional()}).nullable().optional(),errors:z3.array(graphQLErrorSchema2).optional()});var PACKAGE_SUMMARY_QUERY=`
625
+ query PackageSummary(
626
+ $registry: Registry!
627
+ $name: String!
628
+ $includeVerboseFields: Boolean! = true
629
+ ) {
630
+ packageSummary(registry: $registry, name: $name) {
631
+ package {
632
+ name
633
+ registry
634
+ description
635
+ latestVersion
636
+ latestVersionPublishedAt
637
+ homepage
638
+ repositoryUrl
639
+ license
640
+ downloadsLastMonth
641
+ downloadsTotal
642
+ githubRepository {
643
+ stargazersCount
644
+ forksCount
645
+ openIssuesCount
646
+ archived
647
+ language @include(if: $includeVerboseFields)
648
+ topics @include(if: $includeVerboseFields)
649
+ pushedAt @include(if: $includeVerboseFields)
650
+ }
651
+ }
652
+ security {
653
+ vulnerabilityCount
654
+ hasCurrentVulnerabilities
655
+ recentVulnerabilities @include(if: $includeVerboseFields) {
656
+ osvId
657
+ summary
658
+ severityScore
659
+ publishedAt
660
+ }
661
+ }
662
+ latestChangelogs(limit: 3) @include(if: $includeVerboseFields) {
663
+ version
664
+ publishedAt
665
+ body
666
+ }
667
+ }
668
+ }`;var packageVersionIdentitySchema=z3.object({name:z3.string().nullable().optional(),registry:z3.string().nullable().optional(),version:z3.string().nullable().optional(),publishedAt:z3.string().nullable().optional(),deprecated:z3.boolean().nullable().optional(),deprecationReason:z3.string().nullable().optional()});var vulnerabilityDetailSchema=z3.object({osvId:z3.string().nullable().optional(),summary:z3.string().nullable().optional(),severityScore:z3.number().nullable().optional(),severityType:z3.string().nullable().optional(),affectedVersionRanges:z3.array(z3.string()).nullable().optional(),affectedVersionRangesCount:z3.number().int(),affectedVersionRangesTruncated:z3.boolean(),fixedInVersions:z3.array(z3.string()).nullable().optional(),publishedAt:z3.string().nullable().optional(),modifiedAt:z3.string().nullable().optional(),withdrawnAt:z3.string().nullable().optional(),aliases:z3.array(z3.string()).nullable().optional(),isMalicious:z3.boolean().nullable().optional(),affectsInspectedVersion:z3.boolean(),matchedAffectedVersionRanges:z3.array(z3.string()),duplicateIds:z3.array(z3.string())});var pageInfoSchema=z3.object({hasNextPage:z3.boolean(),endCursor:z3.string().nullable().optional(),totalCount:z3.number().int()});var vulnerabilityAdvisoryPageSchema=z3.object({entries:z3.array(vulnerabilityDetailSchema),pageInfo:pageInfoSchema});var vulnerabilitySecurityDetailsSchema=z3.object({affectedVulnerabilityCount:z3.number().int(),nonAffectingVulnerabilityCount:z3.number().int(),allVulnerabilityCount:z3.number().int(),currentVersionAffected:z3.boolean().nullable().optional(),advisories:vulnerabilityAdvisoryPageSchema,upgradePaths:z3.array(z3.string()).nullable().optional()}).nullable().optional();var vulnerabilityReportResponseSchema=z3.object({package:packageVersionIdentitySchema.nullable().optional(),security:vulnerabilitySecurityDetailsSchema});var vulnerabilitiesGraphQLResponseSchema=z3.object({data:z3.object({packageVulnerabilities:vulnerabilityReportResponseSchema.nullable().optional()}).nullable().optional(),errors:z3.array(graphQLErrorSchema2).optional()});var PACKAGE_VULNERABILITIES_QUERY=`
669
+ query PackageVulnerabilities(
670
+ $registry: Registry!
671
+ $name: String!
672
+ $version: String
673
+ $minSeverity: Float
674
+ $includeWithdrawn: Boolean
675
+ $scope: VulnerabilityScope = AFFECTED
676
+ $after: String
677
+ ) {
678
+ packageVulnerabilities(
679
+ registry: $registry
680
+ name: $name
681
+ version: $version
682
+ minSeverity: $minSeverity
683
+ includeWithdrawn: $includeWithdrawn
684
+ ) {
685
+ package {
686
+ name
687
+ registry
688
+ version
689
+ }
690
+ security {
691
+ affectedVulnerabilityCount
692
+ nonAffectingVulnerabilityCount
693
+ allVulnerabilityCount
694
+ currentVersionAffected
695
+ upgradePaths
696
+ advisories(scope: $scope, first: 100, after: $after) {
697
+ entries {
698
+ osvId
699
+ summary
700
+ severityScore
701
+ severityType
702
+ affectedVersionRanges
703
+ affectedVersionRangesCount
704
+ affectedVersionRangesTruncated
705
+ fixedInVersions
706
+ publishedAt
707
+ modifiedAt
708
+ withdrawnAt
709
+ aliases
710
+ isMalicious
711
+ affectsInspectedVersion
712
+ matchedAffectedVersionRanges
713
+ duplicateIds
714
+ }
715
+ pageInfo {
716
+ hasNextPage
717
+ endCursor
718
+ totalCount
719
+ }
720
+ }
721
+ }
722
+ }
723
+ }`;var directDependencySchema=z3.object({name:z3.string().nullable().optional(),versionConstraint:z3.string().nullable().optional(),type:z3.string().nullable().optional()});var dependencyGraphNodeSchema=z3.object({registry:z3.string(),name:z3.string(),version:z3.string().nullable().optional()});var dependencyGraphEdgeSchema=z3.object({fromIndex:z3.number().int().nullable().optional(),toIndex:z3.number().int(),constraint:z3.string().nullable().optional(),dependencyType:z3.string().nullable().optional()});var dependencyGraphSchema=z3.object({formatVersion:z3.number().int(),nodes:z3.array(dependencyGraphNodeSchema),edges:z3.array(dependencyGraphEdgeSchema)});var vulnerabilityCountSummarySchema=z3.object({totalVulnerabilities:z3.number().int(),critical:z3.number().int(),high:z3.number().int(),medium:z3.number().int(),low:z3.number().int(),unknown:z3.number().int()});var vulnerabilitySummaryDetailSchema=z3.object({osvId:z3.string().nullable().optional(),registry:z3.string().nullable().optional(),packageName:z3.string().nullable().optional(),summary:z3.string().nullable().optional(),severityScore:z3.number().nullable().optional(),severityType:z3.string().nullable().optional(),affectedVersionRanges:z3.array(z3.string()).nullable().optional(),fixedInVersions:z3.array(z3.string()).nullable().optional(),publishedAt:z3.string().nullable().optional(),modifiedAt:z3.string().nullable().optional(),withdrawnAt:z3.string().nullable().optional(),aliases:z3.array(z3.string()).nullable().optional(),isMalicious:z3.boolean().nullable().optional()});var transitiveDependencyVulnerabilitySchema=z3.object({version:z3.string(),affectsResolvedVersion:z3.boolean(),matchedAffectedVersionRanges:z3.array(z3.string()),fixVersionsAboveResolved:z3.array(z3.string()),nearestFixedVersion:z3.string().nullable().optional(),advisory:vulnerabilitySummaryDetailSchema});var transitiveVulnerablePackageSchema=z3.object({registry:z3.string(),name:z3.string(),versions:z3.array(z3.string()),affectedCount:z3.number().int(),nonAffectingCount:z3.number().int(),totalCount:z3.number().int(),maxSeverityScore:z3.number().nullable().optional(),maxSeverityLabel:z3.string().nullable().optional(),advisoryIds:z3.array(z3.string()),mostCritical:vulnerabilitySummaryDetailSchema.nullable().optional(),advisoryOccurrences:z3.array(transitiveDependencyVulnerabilitySchema).nullable().optional()});var transitiveVulnerabilitySummarySchema=z3.object({affected:vulnerabilityCountSummarySchema,nonAffecting:vulnerabilityCountSummarySchema,combined:vulnerabilityCountSummarySchema,totalPackagesAnalyzed:z3.number().int(),affectedPackageCount:z3.number().int(),packages:z3.array(transitiveVulnerablePackageSchema),calculatedAt:z3.string().nullable().optional()}).nullable().optional();var dependencyDeprecationReasonSchema=z3.object({version:z3.string(),reason:z3.string().nullable().optional()});var deprecatedDependencySchema=z3.object({registry:z3.string(),name:z3.string(),versions:z3.array(z3.string()),reasons:z3.array(dependencyDeprecationReasonSchema)});var outdatedDependencyVersionSchema=z3.object({version:z3.string(),severity:z3.string()});var outdatedDependencySchema=z3.object({registry:z3.string(),name:z3.string(),latestVersion:z3.string().nullable().optional(),severity:z3.string(),versions:z3.array(outdatedDependencyVersionSchema),repositoryUrl:z3.string().nullable().optional()});var duplicateDependencySchema=z3.object({registry:z3.string().nullable().optional(),name:z3.string(),versions:z3.array(z3.string())});var dependencyConflictEdgeSchema=z3.object({fromIndex:z3.number().int().nullable().optional(),toIndex:z3.number().int(),versionConstraint:z3.string(),dependencyType:z3.string()});var dependencyConflictSchema=z3.object({packageName:z3.string(),requiredVersions:z3.array(z3.string()),conflictingEdges:z3.array(dependencyConflictEdgeSchema)});var dependencyIssueConflictSchema=z3.object({registry:z3.string().nullable().optional(),name:z3.string(),versions:z3.array(z3.string()),requiredVersions:z3.array(z3.string()),conflictingEdges:z3.array(dependencyConflictEdgeSchema)});var dependencyIssuesSummarySchema=z3.object({totalCount:z3.number().int(),deprecatedCount:z3.number().int(),outdatedCount:z3.number().int(),duplicateCount:z3.number().int(),conflictCount:z3.number().int(),deprecatedPackages:z3.array(deprecatedDependencySchema),outdatedPackages:z3.array(outdatedDependencySchema),duplicatePackages:z3.array(duplicateDependencySchema),conflicts:z3.array(dependencyIssueConflictSchema)}).nullable().optional();var circularDependencyCycleSchema=z3.object({cycleStart:z3.string(),circularPath:z3.array(z3.string()),displayChain:z3.string()});var environmentMarkerSchema=z3.object({type:z3.string().nullable().optional(),value:z3.string().nullable().optional(),raw:z3.string().nullable().optional()});var transitiveDependencySchema=z3.object({totalEdges:z3.number().int().nullable().optional(),uniquePackagesCount:z3.number().int().nullable().optional(),uniqueDependencies:z3.array(z3.string()).nullable().optional(),dependencyConflicts:z3.array(dependencyConflictSchema).nullable().optional(),circularDependencyCycles:z3.array(circularDependencyCycleSchema).nullable().optional(),dependencyGraph:dependencyGraphSchema.nullable().optional(),vulnerabilitySummary:transitiveVulnerabilitySummarySchema,dependencyIssues:dependencyIssuesSummarySchema}).nullable().optional();var dependencyBundleSchema=z3.object({direct:z3.array(directDependencySchema).nullable().optional(),transitive:transitiveDependencySchema}).nullable().optional();var groupDependencySchema=z3.object({name:z3.string(),constraint:z3.string().nullable().optional()});var dependencyGroupSchema=z3.object({name:z3.string(),lifecycle:z3.string(),conditionType:z3.string(),conditionValue:z3.string().nullable().optional(),selectionMode:z3.string(),exclusiveGroup:z3.string().nullable().optional(),fallbackPriority:z3.number().int().nullable().optional(),compatibleWith:z3.array(z3.string()).nullable().optional(),defaultEnabled:z3.boolean().nullable().optional(),dependencies:z3.array(groupDependencySchema)});var dependencyGroupsInfoSchema=z3.object({primaryGroup:z3.string().nullable().optional(),environmentMarkers:z3.array(environmentMarkerSchema).nullable().optional(),groups:z3.array(dependencyGroupSchema)}).nullable().optional();var dependencyReportResponseSchema=z3.object({package:packageVersionIdentitySchema.nullable().optional(),dependencies:dependencyBundleSchema,dependencyGroups:dependencyGroupsInfoSchema});var dependenciesGraphQLResponseSchema=z3.object({data:z3.object({packageDependencies:dependencyReportResponseSchema.nullable().optional()}).nullable().optional(),errors:z3.array(graphQLErrorSchema2).optional()});var PACKAGE_DEPENDENCIES_QUERY=`
724
+ query PackageDependencies(
725
+ $registry: Registry!
726
+ $name: String!
727
+ $version: String
728
+ $includeTransitive: Boolean
729
+ $includeTransitiveDetails: Boolean! = true
730
+ $includeDependencyGraph: Boolean! = true
731
+ $includeGroups: Boolean! = true
732
+ $maxDepth: Int
733
+ $lifecycle: [String!]
734
+ ) {
735
+ packageDependencies(
736
+ registry: $registry
737
+ name: $name
738
+ version: $version
739
+ includeTransitive: $includeTransitive
740
+ maxDepth: $maxDepth
741
+ lifecycle: $lifecycle
742
+ ) {
743
+ package {
744
+ name
745
+ registry
746
+ version
747
+ }
748
+ dependencies {
749
+ # Backend-side summary block intentionally not selected — our
750
+ # envelope computes runtime.count client-side from direct[].length
751
+ # so the invariant runtime.count === runtime.items.length always
752
+ # holds regardless of backend-side drift.
753
+ direct {
754
+ name
755
+ versionConstraint
756
+ type
757
+ }
758
+ transitive {
759
+ totalEdges @include(if: $includeTransitiveDetails)
760
+ uniquePackagesCount @include(if: $includeTransitiveDetails)
761
+ uniqueDependencies @include(if: $includeTransitiveDetails)
762
+ dependencyConflicts @include(if: $includeTransitiveDetails) {
763
+ packageName
764
+ requiredVersions
765
+ conflictingEdges {
766
+ fromIndex
767
+ toIndex
768
+ versionConstraint
769
+ dependencyType
770
+ }
771
+ }
772
+ circularDependencyCycles @include(if: $includeTransitiveDetails) {
773
+ cycleStart
774
+ circularPath
775
+ displayChain
776
+ }
777
+ dependencyGraph @include(if: $includeDependencyGraph) {
778
+ formatVersion
779
+ nodes {
780
+ registry
781
+ name
782
+ version
783
+ }
784
+ edges {
785
+ fromIndex
786
+ toIndex
787
+ constraint
788
+ dependencyType
789
+ }
790
+ }
791
+ }
792
+ }
793
+ dependencyGroups @include(if: $includeGroups) {
794
+ primaryGroup
795
+ environmentMarkers {
796
+ type
797
+ value
798
+ raw
799
+ }
800
+ groups {
801
+ name
802
+ lifecycle
803
+ conditionType
804
+ conditionValue
805
+ selectionMode
806
+ exclusiveGroup
807
+ fallbackPriority
808
+ compatibleWith
809
+ defaultEnabled
810
+ dependencies {
811
+ name
812
+ constraint
813
+ }
814
+ }
815
+ }
816
+ }
817
+ }`;var PACKAGE_UPGRADE_DEPENDENCY_PROBE_QUERY=`
818
+ query PackageUpgradeDependencyProbe(
819
+ $registry: Registry!
820
+ $name: String!
821
+ $version: String!
822
+ $includeTransitiveRisk: Boolean!
823
+ $includeTransitiveSecurity: Boolean!
824
+ $includeDependencyIssues: Boolean!
825
+ $includeDependencyChanges: Boolean!
826
+ $includeGroups: Boolean!
827
+ $lifecycle: [String!]
828
+ $minSeverity: Float
829
+ ) {
830
+ packageDependencies(
831
+ registry: $registry
832
+ name: $name
833
+ version: $version
834
+ includeTransitive: $includeTransitiveRisk
835
+ lifecycle: $lifecycle
836
+ ) {
837
+ package {
838
+ name
839
+ registry
840
+ version
841
+ publishedAt
842
+ deprecated
843
+ deprecationReason
844
+ }
845
+ dependencies {
846
+ direct {
847
+ name
848
+ versionConstraint
849
+ type
850
+ }
851
+ transitive @include(if: $includeTransitiveRisk) {
852
+ dependencyGraph @include(if: $includeDependencyChanges) {
853
+ formatVersion
854
+ nodes {
855
+ registry
856
+ name
857
+ version
858
+ }
859
+ edges {
860
+ fromIndex
861
+ toIndex
862
+ constraint
863
+ dependencyType
864
+ }
865
+ }
866
+ vulnerabilitySummary(minSeverity: $minSeverity) @include(if: $includeTransitiveSecurity) {
867
+ affected {
868
+ totalVulnerabilities
869
+ critical
870
+ high
871
+ medium
872
+ low
873
+ unknown
874
+ }
875
+ nonAffecting {
876
+ totalVulnerabilities
877
+ critical
878
+ high
879
+ medium
880
+ low
881
+ unknown
882
+ }
883
+ combined {
884
+ totalVulnerabilities
885
+ critical
886
+ high
887
+ medium
888
+ low
889
+ unknown
890
+ }
891
+ totalPackagesAnalyzed
892
+ affectedPackageCount
893
+ calculatedAt
894
+ packages {
895
+ registry
896
+ name
897
+ versions
898
+ affectedCount
899
+ nonAffectingCount
900
+ totalCount
901
+ maxSeverityScore
902
+ maxSeverityLabel
903
+ advisoryIds(scope: AFFECTED)
904
+ mostCritical {
905
+ osvId
906
+ registry
907
+ packageName
908
+ summary
909
+ severityScore
910
+ severityType
911
+ affectedVersionRanges
912
+ fixedInVersions
913
+ publishedAt
914
+ modifiedAt
915
+ withdrawnAt
916
+ aliases
917
+ isMalicious
918
+ }
919
+ advisoryOccurrences(scope: AFFECTED, minSeverity: $minSeverity, limit: 5) {
920
+ version
921
+ affectsResolvedVersion
922
+ matchedAffectedVersionRanges
923
+ fixVersionsAboveResolved
924
+ nearestFixedVersion
925
+ advisory {
926
+ osvId
927
+ registry
928
+ packageName
929
+ summary
930
+ severityScore
931
+ severityType
932
+ affectedVersionRanges
933
+ fixedInVersions
934
+ publishedAt
935
+ modifiedAt
936
+ withdrawnAt
937
+ aliases
938
+ isMalicious
939
+ }
940
+ }
941
+ }
942
+ }
943
+ dependencyIssues @include(if: $includeDependencyIssues) {
944
+ totalCount
945
+ deprecatedCount
946
+ outdatedCount
947
+ duplicateCount
948
+ conflictCount
949
+ deprecatedPackages {
950
+ registry
951
+ name
952
+ versions
953
+ reasons {
954
+ version
955
+ reason
956
+ }
957
+ }
958
+ outdatedPackages {
959
+ registry
960
+ name
961
+ latestVersion
962
+ severity
963
+ versions {
964
+ version
965
+ severity
966
+ }
967
+ repositoryUrl
968
+ }
969
+ duplicatePackages {
970
+ registry
971
+ name
972
+ versions
973
+ }
974
+ conflicts {
975
+ registry
976
+ name
977
+ versions
978
+ requiredVersions
979
+ conflictingEdges {
980
+ fromIndex
981
+ toIndex
982
+ versionConstraint
983
+ dependencyType
984
+ }
985
+ }
986
+ }
987
+ }
988
+ }
989
+ dependencyGroups @include(if: $includeGroups) {
990
+ primaryGroup
991
+ environmentMarkers {
992
+ type
993
+ value
994
+ raw
995
+ }
996
+ groups {
997
+ name
998
+ lifecycle
999
+ conditionType
1000
+ conditionValue
1001
+ selectionMode
1002
+ exclusiveGroup
1003
+ fallbackPriority
1004
+ compatibleWith
1005
+ defaultEnabled
1006
+ dependencies {
1007
+ name
1008
+ constraint
1009
+ }
1010
+ }
1011
+ }
1012
+ }
1013
+ }`;var packageUpgradeAdvisorySchema=z3.object({id:z3.string().nullable().optional(),aliases:z3.array(z3.string()),summary:z3.string().nullable().optional(),severity:z3.number().nullable().optional(),severityLabel:z3.string().nullable().optional(),fixedIn:z3.array(z3.string()),isMalicious:z3.boolean().nullable().optional()});var packageUpgradeVersionVulnerabilitySummarySchema=z3.object({version:z3.string(),publishedAt:z3.string().nullable().optional(),deprecated:z3.boolean().nullable().optional(),deprecationReason:z3.string().nullable().optional(),affectedCount:z3.number().int(),nonAffectingCount:z3.number().int(),allCount:z3.number().int(),lastModifiedAt:z3.string().nullable().optional(),advisories:z3.array(packageUpgradeAdvisorySchema)}).nullable().optional();var packageUpgradeTransitivePackagePageSchema=z3.object({entries:z3.array(z3.object({id:z3.string(),registry:z3.string(),name:z3.string(),versions:z3.array(z3.string()),affectedCount:z3.number().int(),maxSeverityScore:z3.number().nullable().optional(),maxSeverityLabel:z3.string().nullable().optional(),advisoryIds:z3.array(z3.string())})),totalCount:z3.number().int(),truncated:z3.boolean()});var packageUpgradeTransitiveSecuritySchema=z3.object({currentAffected:z3.number().int(),targetAffected:z3.number().int(),introducedPackages:z3.array(z3.string()),fixedPackages:z3.array(z3.string()),introducedPackageDetails:packageUpgradeTransitivePackagePageSchema,fixedPackageDetails:packageUpgradeTransitivePackagePageSchema,stillAffectedPackageDetails:packageUpgradeTransitivePackagePageSchema}).nullable().optional();var packageUpgradeSecuritySchema=z3.object({current:packageUpgradeVersionVulnerabilitySummarySchema,target:packageUpgradeVersionVulnerabilitySummarySchema,added:z3.array(packageUpgradeAdvisorySchema),removed:z3.array(packageUpgradeAdvisorySchema),notAddressed:z3.array(packageUpgradeAdvisorySchema),fixed:z3.array(packageUpgradeAdvisorySchema),introduced:z3.array(packageUpgradeAdvisorySchema),unchanged:z3.array(packageUpgradeAdvisorySchema),transitive:packageUpgradeTransitiveSecuritySchema});var packageUpgradeChangelogEntrySchema=z3.object({version:z3.string().nullable().optional(),publishedAt:z3.string().nullable().optional(),htmlUrl:z3.string().nullable().optional(),body:z3.string().nullable().optional(),bodyPreview:z3.string().nullable().optional(),headline:z3.string().nullable().optional(),signals:z3.array(z3.string())});var packageUpgradeChangelogSchema=z3.object({source:z3.string().nullable().optional(),fallback:z3.string().nullable().optional(),entries:z3.array(packageUpgradeChangelogEntrySchema),sampledEntries:z3.array(packageUpgradeChangelogEntrySchema),keywordEntries:z3.array(packageUpgradeChangelogEntrySchema),totalKeywordEntries:z3.number().int(),totalEntries:z3.number().int(),totalEntriesWithBodies:z3.number().int(),truncated:z3.boolean(),hasReleaseNoteBodies:z3.boolean(),breakingSignals:z3.array(z3.string()),migrationSignals:z3.array(z3.string())});var packageUpgradeCompatibilitySchema=z3.object({peerDependencyChanges:z3.array(z3.string()),notes:z3.array(z3.string())}).nullable().optional();var packageUpgradeDependencyChangeItemSchema=z3.object({name:z3.string(),registry:z3.string().nullable().optional(),version:z3.string().nullable().optional(),fromVersions:z3.array(z3.string()),toVersions:z3.array(z3.string()),constraint:z3.string().nullable().optional(),type:z3.string().nullable().optional()});var packageUpgradeDependencyChangeGroupSchema=z3.object({added:z3.array(packageUpgradeDependencyChangeItemSchema),removed:z3.array(packageUpgradeDependencyChangeItemSchema),changed:z3.array(packageUpgradeDependencyChangeItemSchema)});var packageUpgradeDependencyChangesSchema=z3.object({direct:packageUpgradeDependencyChangeGroupSchema,transitive:packageUpgradeDependencyChangeGroupSchema}).nullable().optional();var packageUpgradeDependencyIssuesSchema=z3.object({currentTotal:z3.number().int(),targetTotal:z3.number().int(),introducedDeprecated:z3.array(z3.string()),introducedDuplicates:z3.array(z3.string()),introducedConflicts:z3.array(z3.string()),introducedOutdated:z3.array(z3.string())}).nullable().optional();var packageUpgradeReviewSchema=z3.object({registry:z3.string(),name:z3.string(),currentVersion:z3.string(),targetVersion:z3.string(),latestVersion:z3.string().nullable().optional(),versionDelta:z3.string(),security:packageUpgradeSecuritySchema,changelog:packageUpgradeChangelogSchema,compatibility:packageUpgradeCompatibilitySchema,dependencyChanges:packageUpgradeDependencyChangesSchema,dependencyIssues:packageUpgradeDependencyIssuesSchema,unknowns:z3.array(z3.string())});var packageUpgradeReviewResponseSchema=z3.object({summary:z3.object({total:z3.number().int(),withUnknowns:z3.number().int(),withAddedAdvisories:z3.number().int(),withBreakingSignals:z3.number().int(),withDirectDependencyChanges:z3.number().int(),withTransitiveVulnerabilityAdditions:z3.number().int()}),reviews:z3.array(packageUpgradeReviewSchema)});var packageUpgradeReviewGraphQLResponseSchema=z3.object({data:z3.object({packageUpgradeReview:packageUpgradeReviewResponseSchema.nullable().optional()}).nullable().optional(),errors:z3.array(graphQLErrorSchema2).optional()});var PACKAGE_UPGRADE_REVIEW_QUERY=`
1014
+ query PackageUpgradeReview(
1015
+ $packages: [PackageUpgradeReviewPackageInput!]!
1016
+ $includeTransitiveSecurity: Boolean!
1017
+ $includeDependencyIssues: Boolean!
1018
+ $minSeverity: Float
1019
+ $changelogLimit: Int!
1020
+ ) {
1021
+ packageUpgradeReview(
1022
+ packages: $packages
1023
+ includeTransitiveSecurity: $includeTransitiveSecurity
1024
+ minSeverity: $minSeverity
1025
+ changelogLimit: $changelogLimit
1026
+ ) {
1027
+ summary {
1028
+ total
1029
+ withUnknowns
1030
+ withAddedAdvisories
1031
+ withBreakingSignals
1032
+ withDirectDependencyChanges
1033
+ withTransitiveVulnerabilityAdditions
1034
+ }
1035
+ reviews {
1036
+ registry
1037
+ name
1038
+ currentVersion
1039
+ targetVersion
1040
+ latestVersion
1041
+ versionDelta
1042
+ security {
1043
+ current {
1044
+ version
1045
+ publishedAt
1046
+ deprecated
1047
+ deprecationReason
1048
+ affectedCount
1049
+ nonAffectingCount
1050
+ allCount
1051
+ lastModifiedAt
1052
+ advisories {
1053
+ ...PackageUpgradeAdvisoryFields
1054
+ }
1055
+ }
1056
+ target {
1057
+ version
1058
+ publishedAt
1059
+ deprecated
1060
+ deprecationReason
1061
+ affectedCount
1062
+ nonAffectingCount
1063
+ allCount
1064
+ lastModifiedAt
1065
+ advisories {
1066
+ ...PackageUpgradeAdvisoryFields
1067
+ }
1068
+ }
1069
+ added {
1070
+ ...PackageUpgradeAdvisoryFields
1071
+ }
1072
+ removed {
1073
+ ...PackageUpgradeAdvisoryFields
1074
+ }
1075
+ notAddressed {
1076
+ ...PackageUpgradeAdvisoryFields
1077
+ }
1078
+ fixed {
1079
+ ...PackageUpgradeAdvisoryFields
1080
+ }
1081
+ introduced {
1082
+ ...PackageUpgradeAdvisoryFields
1083
+ }
1084
+ unchanged {
1085
+ ...PackageUpgradeAdvisoryFields
1086
+ }
1087
+ transitive @include(if: $includeTransitiveSecurity) {
1088
+ currentAffected
1089
+ targetAffected
1090
+ introducedPackages
1091
+ fixedPackages
1092
+ introducedPackageDetails(first: 50) {
1093
+ ...PackageUpgradeTransitivePackagePageFields
1094
+ }
1095
+ fixedPackageDetails(first: 50) {
1096
+ ...PackageUpgradeTransitivePackagePageFields
1097
+ }
1098
+ stillAffectedPackageDetails(first: 50) {
1099
+ ...PackageUpgradeTransitivePackagePageFields
1100
+ }
1101
+ }
1102
+ }
1103
+ changelog {
1104
+ source
1105
+ fallback
1106
+ entries {
1107
+ ...PackageUpgradeChangelogEntryFields
1108
+ }
1109
+ sampledEntries {
1110
+ ...PackageUpgradeChangelogEntryFields
1111
+ }
1112
+ keywordEntries {
1113
+ ...PackageUpgradeChangelogEntryFields
1114
+ }
1115
+ totalKeywordEntries
1116
+ totalEntries
1117
+ totalEntriesWithBodies
1118
+ truncated
1119
+ hasReleaseNoteBodies
1120
+ breakingSignals
1121
+ migrationSignals
1122
+ }
1123
+ compatibility {
1124
+ peerDependencyChanges
1125
+ notes
1126
+ }
1127
+ dependencyChanges {
1128
+ direct {
1129
+ ...PackageUpgradeDependencyChangeGroupFields
1130
+ }
1131
+ transitive {
1132
+ ...PackageUpgradeDependencyChangeGroupFields
1133
+ }
1134
+ }
1135
+ dependencyIssues @include(if: $includeDependencyIssues) {
1136
+ currentTotal
1137
+ targetTotal
1138
+ introducedDeprecated
1139
+ introducedDuplicates
1140
+ introducedConflicts
1141
+ introducedOutdated
1142
+ }
1143
+ unknowns
1144
+ }
1145
+ }
1146
+ }
1147
+
1148
+ fragment PackageUpgradeAdvisoryFields on PackageUpgradeAdvisorySummary {
1149
+ id
1150
+ aliases
1151
+ summary
1152
+ severity
1153
+ severityLabel
1154
+ fixedIn
1155
+ isMalicious
1156
+ }
1157
+
1158
+ fragment PackageUpgradeTransitivePackagePageFields on PackageUpgradeTransitivePackagePage {
1159
+ entries {
1160
+ id
1161
+ registry
1162
+ name
1163
+ versions
1164
+ affectedCount
1165
+ maxSeverityScore
1166
+ maxSeverityLabel
1167
+ advisoryIds
1168
+ }
1169
+ totalCount
1170
+ truncated
1171
+ }
1172
+
1173
+ fragment PackageUpgradeChangelogEntryFields on PackageUpgradeChangelogEntry {
1174
+ version
1175
+ publishedAt
1176
+ htmlUrl
1177
+ body
1178
+ bodyPreview
1179
+ headline
1180
+ signals
1181
+ }
1182
+
1183
+ fragment PackageUpgradeDependencyChangeGroupFields on PackageUpgradeDependencyChangeGroup {
1184
+ added {
1185
+ name
1186
+ registry
1187
+ version
1188
+ fromVersions
1189
+ toVersions
1190
+ constraint
1191
+ type
1192
+ }
1193
+ removed {
1194
+ name
1195
+ registry
1196
+ version
1197
+ fromVersions
1198
+ toVersions
1199
+ constraint
1200
+ type
1201
+ }
1202
+ changed {
1203
+ name
1204
+ registry
1205
+ version
1206
+ fromVersions
1207
+ toVersions
1208
+ constraint
1209
+ type
1210
+ }
1211
+ }`;var changelogPackageInfoSchema=z3.object({name:z3.string().nullable().optional(),registry:z3.string().nullable().optional(),repoUrl:z3.string().nullable().optional(),fromVersion:z3.string().nullable().optional(),toVersion:z3.string().nullable().optional(),limit:z3.number().int().nullable().optional()}).nullable().optional();var changelogEntryDetailSchema=z3.object({version:z3.string().nullable().optional(),normalizedVersion:z3.string().nullable().optional(),body:z3.string().nullable().optional(),htmlUrl:z3.string().nullable().optional(),publishedAt:z3.string().nullable().optional()});var changelogReportResponseSchema=z3.object({package:changelogPackageInfoSchema,source:z3.string().nullable().optional(),entries:z3.array(changelogEntryDetailSchema).nullable().optional()});var changelogGraphQLResponseSchema=z3.object({data:z3.object({packageChangelog:changelogReportResponseSchema.nullable().optional()}).nullable().optional(),errors:z3.array(graphQLErrorSchema2).optional()});var PACKAGE_CHANGELOG_QUERY=`
1212
+ query PackageChangelog(
1213
+ $registry: Registry
1214
+ $name: String
1215
+ $repoUrl: String
1216
+ $gitRef: String
1217
+ $fromVersion: String
1218
+ $toVersion: String
1219
+ $limit: Int
1220
+ $includeBodies: Boolean! = true
1221
+ ) {
1222
+ packageChangelog(
1223
+ registry: $registry
1224
+ name: $name
1225
+ repoUrl: $repoUrl
1226
+ gitRef: $gitRef
1227
+ fromVersion: $fromVersion
1228
+ toVersion: $toVersion
1229
+ limit: $limit
1230
+ ) {
1231
+ package {
1232
+ name
1233
+ registry
1234
+ repoUrl
1235
+ fromVersion
1236
+ toVersion
1237
+ limit
1238
+ }
1239
+ source
1240
+ entries {
1241
+ version
1242
+ normalizedVersion
1243
+ body @include(if: $includeBodies)
1244
+ htmlUrl
1245
+ publishedAt
1246
+ }
1247
+ }
1248
+ }`;var packageDocSourceKindSchema=z3.enum(["CRAWLED","REPOSITORY"]);var packageDocPageSummarySchema=z3.object({id:z3.string().nullable().optional(),title:z3.string().nullable().optional(),slug:z3.string().nullable().optional(),order:z3.number().int().nullable().optional(),linkName:z3.string().nullable().optional(),lastUpdatedAt:z3.string().nullable().optional(),sourceKind:packageDocSourceKindSchema.nullable().optional(),sourceUrl:z3.string().nullable().optional(),repoUrl:z3.string().nullable().optional(),gitRef:z3.string().nullable().optional(),requestedRef:z3.string().nullable().optional(),filePath:z3.string().nullable().optional()});var packageDocsPageInfoSchema=z3.object({hasNextPage:z3.boolean(),endCursor:z3.string().nullable().optional(),totalCount:z3.number().int().nullable().optional()}).nullable().optional();var packageDocsListResponseSchema=z3.object({registry:z3.string().nullable().optional(),packageName:z3.string().nullable().optional(),version:z3.string().nullable().optional(),stale:z3.boolean().nullable().optional(),pages:z3.array(packageDocPageSummarySchema).nullable().optional(),pageInfo:packageDocsPageInfoSchema});var packageDocSourceSchema=z3.object({url:z3.string().nullable().optional(),label:z3.string().nullable().optional()}).nullable().optional();var packageDocPageSchema=z3.object({id:z3.string().nullable().optional(),title:z3.string().nullable().optional(),content:z3.string().nullable().optional(),contentFormat:z3.string().nullable().optional(),breadcrumbs:z3.array(z3.string()).nullable().optional(),linkName:z3.string().nullable().optional(),lastUpdatedAt:z3.string().nullable().optional(),sourceKind:packageDocSourceKindSchema.nullable().optional(),source:packageDocSourceSchema,repoUrl:z3.string().nullable().optional(),gitRef:z3.string().nullable().optional(),requestedRef:z3.string().nullable().optional(),filePath:z3.string().nullable().optional(),baseUrl:z3.string().nullable().optional()}).nullable().optional();var packageDocResultResponseSchema=z3.object({registry:z3.string().nullable().optional(),packageName:z3.string().nullable().optional(),version:z3.string().nullable().optional(),sourceKind:packageDocSourceKindSchema.nullable().optional(),page:packageDocPageSchema});var packageDocsListGraphQLResponseSchema=z3.object({data:z3.object({listPackageDocs:packageDocsListResponseSchema.nullable().optional()}).nullable().optional(),errors:z3.array(graphQLErrorSchema2).optional()});var packageDocReadGraphQLResponseSchema=z3.object({data:z3.object({getDocPage:packageDocResultResponseSchema.nullable().optional()}).nullable().optional(),errors:z3.array(graphQLErrorSchema2).optional()});var LIST_PACKAGE_DOCS_QUERY=`
1249
+ query ListPackageDocs(
1250
+ $registry: Registry!
1251
+ $packageName: String!
1252
+ $version: String
1253
+ $limit: Int
1254
+ $after: String
1255
+ ) {
1256
+ listPackageDocs(
1257
+ registry: $registry
1258
+ packageName: $packageName
1259
+ version: $version
1260
+ limit: $limit
1261
+ after: $after
1262
+ ) {
1263
+ registry
1264
+ packageName
1265
+ version
1266
+ stale
1267
+ pages {
1268
+ id
1269
+ title
1270
+ slug
1271
+ order
1272
+ linkName
1273
+ lastUpdatedAt
1274
+ sourceKind
1275
+ sourceUrl
1276
+ repoUrl
1277
+ gitRef
1278
+ requestedRef
1279
+ filePath
1280
+ }
1281
+ pageInfo {
1282
+ hasNextPage
1283
+ endCursor
1284
+ totalCount
1285
+ }
1286
+ }
1287
+ }`;var READ_PACKAGE_DOC_QUERY=`
1288
+ query ReadPackageDoc($pageId: String!) {
1289
+ getDocPage(pageId: $pageId) {
1290
+ registry
1291
+ packageName
1292
+ version
1293
+ sourceKind
1294
+ page {
1295
+ id
1296
+ title
1297
+ content
1298
+ contentFormat
1299
+ breadcrumbs
1300
+ linkName
1301
+ lastUpdatedAt
1302
+ sourceKind
1303
+ source {
1304
+ url
1305
+ label
1306
+ }
1307
+ repoUrl
1308
+ gitRef
1309
+ requestedRef
1310
+ filePath
1311
+ baseUrl
1312
+ }
1313
+ }
1314
+ }`;class PackageIntelligenceServiceImpl{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,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,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;return this.normaliseVulnerabilityReport(data)}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 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.includeTransitive,includeTransitiveDetails:params.includeTransitiveDetails!==false,includeDependencyGraph:params.includeTransitive===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.")}return this.normaliseDependencyReport(data)}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}}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){let response;try{response=await postPkgseerGraphql({endpointUrl:this.endpointUrl,token,query:PACKAGE_CHANGELOG_QUERY,variables:{registry:params.registry,name:params.packageName,repoUrl:params.repoUrl,gitRef:params.gitRef,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.normaliseChangelogReport(data,params)}normaliseChangelogReport(data,params){const source=data.source?.trim()?data.source:undefined;const rawEntries=data.entries??[];if(!source&&rawEntries.length===0){const target=params.repoUrl??(params.registry&&params.packageName?`${params.registry.toLowerCase()}:${params.packageName}`:"package");throw new PackageIntelligenceChangelogSourceNotFoundError(`No changelog source available for ${target} (tried GitHub Releases, CHANGELOG.md, and HexDocs).`)}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,repoUrl:data.package.repoUrl??undefined,fromVersion:data.package.fromVersion??undefined,toVersion:data.package.toVersion??undefined,limit:data.package.limit??undefined}:undefined;return{package:packageInfo,source,entries}}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,pages:data.pages?.map((page)=>({id:page.id??undefined,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},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 this.normalisePackageDocResult(data)}normalisePackageDocResult(data){return{registry:data.registry??undefined,packageName:data.packageName??undefined,version:data.version??undefined,sourceKind:data.sourceKind??undefined,page:data.page?{id:data.page.id??undefined,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 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=parseDetail2(response.responseBody);if(status===401){return new AuthenticationError(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"FEATURE_FLAG_REQUIRED":return new PackageIntelligenceFeatureFlagRequiredError(message);case"UNAUTHORIZED":return new AuthenticationError(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 parseDetail2(body){if(!body)return;try{const parsed=JSON.parse(body);if(typeof parsed.detail==="string")return parsed.detail;if(typeof parsed.error==="string")return parsed.error}catch{return body}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}class RefreshingGitHitsService{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 getLanguages(){return this.withTokenRefresh((service)=>service.getLanguages())}async searchLanguages(query,limit){return this.withTokenRefresh((service)=>service.searchLanguages(query,limit))}async submitFeedback(params){return this.withTokenRefresh((service)=>service.submitFeedback(params))}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 GitHitsServiceImpl(this.apiUrl,token,undefined,undefined,this.runtime);return operation(service)}})}}function createStaticTokenProvider(token){return{getToken:async()=>token,forceRefresh:async()=>{return}}}import{createHash,randomUUID}from"node:crypto";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;function resolveRawSessionId(env=process.env,ppid=process.ppid){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){if(cachedSessionId!==undefined&&env===undefined&&ppid===undefined){return cachedSessionId}const raw=resolveRawSessionId(env,ppid);const hashed=hashValue(raw);if(env===undefined&&ppid===undefined){cachedSessionId=hashed}return hashed}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 createClientHeaderBuilder(options){return()=>buildClientHeadersWithContext({clientName:options.clientName,clientVersion:options.clientVersion,agentProvider:options.agentProvider,env:options.env,ppid:options.ppid})}function buildClientHeadersWithContext(context){try{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}}const sessionId=sanitizeHeaderValue(getSessionId(context.env,context.ppid));if(sessionId){headers["x-githits-session-id"]=sessionId}return headers}catch{return{}}}import{createHash as createHash2,randomBytes}from"node:crypto";import{z as z4}from"zod";var latestVersionMaliciousEvidenceSchema=z4.object({advisories:z4.array(z4.object({osvId:z4.string(),classificationReasons:z4.array(z4.string())})).max(5),totalCount:z4.number().int().nonnegative(),truncated:z4.boolean()}).nullable();var listCandidateSchema=z4.object({kind:z4.string(),canonicalKey:z4.string(),confidence:z4.string(),latestVersionMaliciousStatus:z4.string(),latestVersionMaliciousEvidence:latestVersionMaliciousEvidenceSchema,description:z4.string().nullable().optional(),repositoryUrl:z4.string().nullable().optional(),stars:z4.number().int().nullable().optional(),downloadsLastMonth:z4.number().int().nullable().optional(),downloadsTotal:z4.number().int().nullable().optional(),docsAvailable:z4.boolean(),codeAvailable:z4.boolean()});var targetReferenceSchema=listCandidateSchema.pick({kind:true,canonicalKey:true,confidence:true});var detailedCandidateSchema=listCandidateSchema.extend({displayName:z4.string(),registry:z4.string().nullable().optional(),packageName:z4.string().nullable().optional(),latestVersion:z4.string().nullable().optional(),repositoryOwner:z4.string().nullable().optional(),repositoryName:z4.string().nullable().optional(),documentationUrl:z4.string().nullable().optional(),matchedAliases:z4.array(z4.string()),matchTier:z4.number().int(),score:z4.number(),reason:z4.string().nullable().optional()});var graphQLErrorSchema3=z4.object({message:z4.string(),extensions:z4.record(z4.string(),z4.unknown()).optional()});export{CLIENT_UPDATE_REQUIRED_REASON,ClientUpdateRequiredError,DEFAULT_MCP_URL,DEFAULT_API_URL,DEFAULT_CODE_NAV_URL,getMcpUrl,getApiUrl,getCodeNavigationUrl,getEnvApiToken,PKGSEER_REGISTRY_ARGS,PKGSEER_REGISTRY_LIST,toPkgseerRegistry,toPkgseerRegistryLowercase,isKnownPkgseerRegistryArg,GitHitsServiceImpl,CodeNavigationAccessError,CodeNavigationGraphQLError,CodeNavigationIndexingError,CodeNavigationUnresolvableError,MalformedCodeNavigationResponseError,CodeDiffError,CodeNavigationTargetNotFoundError,CodeNavigationFileNotFoundError,CodeNavigationVersionNotFoundError,CodeNavigationRefNotFoundError,CodeNavigationValidationError,CodeNavigationFeatureFlagRequiredError,CodeNavigationNetworkError,CodeNavigationBackendError,CodeNavigationServiceImpl,PackageIntelligenceAccessError,PackageIntelligenceFeatureFlagRequiredError,PackageIntelligenceNetworkError,PackageIntelligenceBackendError,PackageIntelligenceGraphQLError,PackageIntelligenceTargetNotFoundError,PackageIntelligenceValidationError,PackageIntelligenceVersionNotFoundError,MalformedPackageIntelligenceResponseError,PackageIntelligenceChangelogSourceNotFoundError,PackageIntelligenceServiceImpl,RefreshingGitHitsService,createStaticTokenProvider,createClientHeaderBuilder};