@githits/mcp 0.6.3 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,1194 +0,0 @@
1
- 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}import{writeSync}from"node:fs";var ENABLED_VALUES=new Set(["1","true","yes","on"]);function isTelemetryEnabled(env=process.env){const raw=env.GITHITS_TELEMETRY?.trim().toLowerCase();if(!raw)return false;return ENABLED_VALUES.has(raw)}class TelemetryCollector{enabled;now;write;sessionStartMs;spans=[];activeSpans=new Map;nextId=1;flushed=false;constructor(options={}){this.enabled=isTelemetryEnabled(options.env);this.now=options.now??(()=>globalThis.performance.now());this.write=options.write??((text)=>writeSync(process.stderr.fd,text));this.sessionStartMs=this.now()}isEnabled(){return this.enabled}startSpan(name,attributes){if(!this.enabled)return;const span={id:this.nextId++,name,startMs:this.now(),attributes:sanitiseAttributes(attributes)};this.spans.push(span);this.activeSpans.set(span.id,span);return{id:span.id}}endSpan(handle,attributes){if(!this.enabled||!handle)return;const span=this.activeSpans.get(handle.id);if(!span||span.endMs!==undefined)return;span.endMs=this.now();span.attributes=mergeAttributes(span.attributes,attributes);this.activeSpans.delete(handle.id)}flush(exitCode=0){if(!this.enabled||this.flushed)return;const nowMs=this.now();for(const span of this.activeSpans.values()){if(span.endMs!==undefined)continue;span.endMs=nowMs;span.endedAtExit=true}this.activeSpans.clear();this.write(formatTelemetryReport(this.spans,this.sessionStartMs,nowMs,exitCode));this.flushed=true}}async function withTelemetrySpan(name,operation,attributes){const handle=telemetryCollector.startSpan(name,attributes);try{const result=await operation();telemetryCollector.endSpan(handle);return result}catch(error){telemetryCollector.endSpan(handle,{error:true});throw error}}function startTelemetrySpan(name,attributes){return telemetryCollector.startSpan(name,attributes)}function endTelemetrySpan(handle,attributes){telemetryCollector.endSpan(handle,attributes)}function flushTelemetry(exitCode=0){telemetryCollector.flush(exitCode)}var telemetryCollector=new TelemetryCollector;function sanitiseAttributes(attributes){if(!attributes)return;const entries=Object.entries(attributes).filter(([,value])=>value!==undefined);if(entries.length===0)return;return Object.fromEntries(entries)}function mergeAttributes(initial,extra){if(!initial&&!extra)return;return sanitiseAttributes({...initial??{},...extra??{}})}function formatTelemetryReport(spans,sessionStartMs,sessionEndMs,exitCode){const lines=["[githits telemetry]",`exit: ${exitCode}`,`total: ${formatMs(sessionEndMs-sessionStartMs)}`];const orderedSpans=[...spans].sort((left,right)=>{if(left.startMs!==right.startMs){return left.startMs-right.startMs}return left.id-right.id});for(const span of orderedSpans){const endMs=span.endMs??sessionEndMs;const details=[`start +${formatMs(span.startMs-sessionStartMs)}`];if(span.endedAtExit){details.push("ended-at-exit")}const attrs=formatAttributes(span.attributes);if(attrs){details.push(attrs)}lines.push(`- ${span.name}: ${formatMs(endMs-span.startMs)} (${details.join(", ")})`)}return`${lines.join(`
2
- `)}
3
- `}function formatAttributes(attributes){if(!attributes)return"";return Object.entries(attributes).map(([key,value])=>`${key}=${String(value)}`).join(" ")}function formatMs(value){return`${value.toFixed(1)}ms`}import{z}from"zod";var DEFAULT_FETCH_TIMEOUT_MS=120000;class FetchTimeoutError extends Error{timeoutMs;constructor(timeoutMs,options){super(`Request timed out after ${timeoutMs}ms.`,options);this.name="FetchTimeoutError";this.timeoutMs=timeoutMs}}async function fetchWithTimeout(input,init={},options={}){const timeoutMs=options.timeoutMs??DEFAULT_FETCH_TIMEOUT_MS;const timeoutSignal=AbortSignal.timeout(timeoutMs);const signal=init.signal?AbortSignal.any([init.signal,timeoutSignal]):timeoutSignal;const fetchFn=options.fetchFn??globalThis.fetch;let timeoutId;const timeout=new Promise((_,reject)=>{timeoutId=setTimeout(()=>{reject(new FetchTimeoutError(timeoutMs))},timeoutMs)});try{return await Promise.race([fetchFn(input,{...init,signal}),timeout])}catch(cause){if(cause instanceof FetchTimeoutError)throw cause;if(timeoutSignal.aborted&&!init.signal?.aborted){throw new FetchTimeoutError(timeoutMs,{cause})}throw cause}finally{if(timeoutId)clearTimeout(timeoutId)}}function isFetchTimeoutError(error){return error instanceof FetchTimeoutError}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)}var DEFAULT_EXAMPLE_REQUEST_TIMEOUT_MS=240000;var AUTHENTICATION_REQUIRED_MESSAGE="Authentication required.";var LOCAL_AUTHENTICATION_MISSING_MESSAGE="No local GitHits authentication token found.";var SERVER_AUTHENTICATION_REJECTED_MESSAGE="GitHits could not accept the authentication token.";class AuthenticationError extends Error{source;constructor(message=AUTHENTICATION_REQUIRED_MESSAGE,source="local"){super(message);this.name="AuthenticationError";this.source=source}}class ApiRateLimitError extends Error{status=429;retryAfterSeconds;constructor(message="Request rate limited.",retryAfterSeconds){super(message);this.name="ApiRateLimitError";this.retryAfterSeconds=retryAfterSeconds}}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){return withTelemetrySpan("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})},this.runtime.exampleRequestTimeoutMs??DEFAULT_EXAMPLE_REQUEST_TIMEOUT_MS);if(!response.ok){throw await this.createError(response)}return response.text()})}async getLanguages(){return withTelemetrySpan("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 withTelemetrySpan("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 withTelemetrySpan("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(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"]);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"}import{z as z2}from"zod";function debugLog(area,payload){if(!isAreaEnabled(area))return;const line={ts:new Date().toISOString(),area,...payload};let text;try{text=JSON.stringify(line)}catch{text=JSON.stringify({ts:line.ts,area,error:"debug-log payload not serialisable"})}process.stderr.write(`${text}
4
- `)}function isDebugAreaEnabled(area){return isAreaEnabled(area)}function isAreaEnabled(area){const raw=process.env.GITHITS_DEBUG;if(!raw||raw==="")return false;const scopes=raw.split(",").map((s)=>s.trim()).filter(Boolean);if(scopes.includes(area))return true;if(isExplicitOnlyArea(area))return false;return scopes.includes("*")}function isExplicitOnlyArea(area){return area==="code-nav-wire"}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){debugLog("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);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(!options.shouldRefresh(error)){throw error}const refreshedToken=await options.forceRefresh();if(!refreshedToken){throw error}return options.executeWithToken(refreshedToken)}}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;constructor(message,indexingRef,availableVersions,availableRefs,targetResolution=undefined,indexingEstimate=undefined){super(message);this.indexingRef=indexingRef;this.availableVersions=availableVersions;this.availableRefs=availableRefs;this.targetResolution=targetResolution;this.indexingEstimate=indexingEstimate;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 CodeNavigationTargetNotFoundError extends Error{availableVersions;repoUrl;requestedRef;constructor(message,availableVersions,repoUrl,requestedRef){super(message);this.availableVersions=availableVersions;this.repoUrl=repoUrl;this.requestedRef=requestedRef;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;constructor(message,packageName,requestedVersion,latestIndexed,availableVersions){super(message);this.packageName=packageName;this.requestedVersion=requestedVersion;this.latestIndexed=latestIndexed;this.availableVersions=availableVersions;this.name="CodeNavigationVersionNotFoundError"}}class CodeNavigationRefNotFoundError extends Error{repoUrl;requestedRef;availableRefs;suggestedRefs;constructor(message,repoUrl,requestedRef,availableRefs,suggestedRefs){super(message);this.repoUrl=repoUrl;this.requestedRef=requestedRef;this.availableRefs=availableRefs;this.suggestedRefs=suggestedRefs;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;constructor(message,status,graphqlCode,retryable){super(message);this.status=status;this.graphqlCode=graphqlCode;this.retryable=retryable;this.name="CodeNavigationBackendError"}}var TARGET_RESOLUTION_AVAILABLE_REFS_SELECTION=`
5
- availableRefs {
6
- version
7
- ref
8
- }`;var TARGET_RESOLUTION_SUGGESTED_REFS_SELECTION=`
9
- suggestedRefs {
10
- version
11
- ref
12
- }`;var DISCOVERY_TARGET_PROGRESS_SUGGESTED_REFS_SELECTION=`
13
- suggestedRefs {
14
- version
15
- ref
16
- }`;var TARGET_RESOLUTION_SELECTION=`
17
- targetResolution {
18
- requested {
19
- kind
20
- registry
21
- packageName
22
- version
23
- repoUrl
24
- gitRef
25
- commitSha
26
- }
27
- resolvedRequested {
28
- kind
29
- registry
30
- packageName
31
- version
32
- repoUrl
33
- gitRef
34
- commitSha
35
- }
36
- served {
37
- kind
38
- registry
39
- packageName
40
- version
41
- repoUrl
42
- gitRef
43
- commitSha
44
- }
45
- freshness
46
- freshnessReason
47
- indexingRef
48
- availableVersions {
49
- version
50
- ref
51
- }
52
- ${TARGET_RESOLUTION_AVAILABLE_REFS_SELECTION}
53
- ${TARGET_RESOLUTION_SUGGESTED_REFS_SELECTION}
54
- }`;var CODE_CONTEXT_AVAILABLE_VERSIONS_SELECTION=`
55
- availableVersions {
56
- version
57
- ref
58
- }`;var DISCOVERY_TARGET_PROGRESS_RETRY_SELECTION=`
59
- availableVersions {
60
- version
61
- ref
62
- }
63
- availableRefs {
64
- version
65
- ref
66
- }
67
- ${DISCOVERY_TARGET_PROGRESS_SUGGESTED_REFS_SELECTION}`;var INDEXING_DURATION_ESTIMATE_SELECTION=`
68
- indexingEstimate {
69
- lowerSeconds
70
- upperSeconds
71
- elapsedSeconds
72
- sampleCount
73
- source
74
- }`;var UNIFIED_SEARCH_QUERY=`
75
- query UnifiedSearch(
76
- $targets: [SearchPackageInput!]!
77
- $query: String!
78
- $sources: [DiscoverySearchSource!]
79
- $filters: DiscoverySearchFiltersInput
80
- $allowPartialResults: Boolean
81
- $limit: Int
82
- $offset: Int
83
- $waitTimeoutMs: Int
84
- ) {
85
- search(
86
- targets: $targets
87
- query: $query
88
- sources: $sources
89
- filters: $filters
90
- allowPartialResults: $allowPartialResults
91
- limit: $limit
92
- offset: $offset
93
- waitTimeoutMs: $waitTimeoutMs
94
- ) {
95
- completed
96
- searchRef
97
- result {
98
- query
99
- queryWarnings
100
- sources
101
- results {
102
- id
103
- resultType
104
- targetLabel
105
- requestedTargetLabel
106
- freshTargetLabel
107
- servedTargetLabel
108
- freshness
109
- title
110
- summary
111
- score
112
- highlights {
113
- title
114
- summary
115
- }
116
- locator {
117
- registry
118
- packageName
119
- version
120
- pageId
121
- sourceKind
122
- sourceUrl
123
- repoUrl
124
- gitRef
125
- requestedRef
126
- filePath
127
- startLine
128
- endLine
129
- fileContentHash
130
- symbolRef
131
- qualifiedPath
132
- kind
133
- category
134
- language
135
- }
136
- }
137
- page {
138
- offset
139
- limit
140
- returned
141
- hasMore
142
- }
143
- partialResults
144
- sourceStatus {
145
- source
146
- targetLabel
147
- requestedTargetLabel
148
- freshTargetLabel
149
- servedTargetLabel
150
- ${TARGET_RESOLUTION_SELECTION}
151
- indexingStatus
152
- codeIndexState
153
- resultCount
154
- appliedFilters
155
- ignoredFilters
156
- incompatibleFilters
157
- appliedQueryFeatures
158
- ignoredQueryFeatures
159
- incompatibleQueryFeatures
160
- note
161
- }
162
- }
163
- progress {
164
- searchRef
165
- status
166
- targetsTotal
167
- targetsReady
168
- elapsedMs
169
- query
170
- queryWarnings
171
- sources
172
- requestedSources
173
- targetMode
174
- requestedTargets {
175
- registry
176
- name
177
- version
178
- repoUrl
179
- gitRef
180
- }
181
- filters {
182
- fileIntent
183
- kind
184
- category
185
- publicOnly
186
- pathPrefix
187
- }
188
- limit
189
- offset
190
- targets {
191
- requested
192
- resolvedRequested
193
- served
194
- freshness
195
- indexingRef
196
- requestedRefKind
197
- ${TARGET_RESOLUTION_SELECTION}
198
- ${DISCOVERY_TARGET_PROGRESS_RETRY_SELECTION}
199
- }
200
- expiresAt
201
- }
202
- }
203
- }`;var UNIFIED_SEARCH_STATUS_QUERY=`
204
- query UnifiedSearchStatus($searchRef: String!, $includeResults: Boolean!) {
205
- discoverySearchProgress(searchRef: $searchRef, includeResults: $includeResults) {
206
- searchRef
207
- status
208
- targetsTotal
209
- targetsReady
210
- elapsedMs
211
- query
212
- queryWarnings
213
- sources
214
- requestedSources
215
- targetMode
216
- requestedTargets {
217
- registry
218
- name
219
- version
220
- repoUrl
221
- gitRef
222
- }
223
- filters {
224
- fileIntent
225
- kind
226
- category
227
- publicOnly
228
- pathPrefix
229
- }
230
- limit
231
- offset
232
- targets {
233
- requested
234
- resolvedRequested
235
- served
236
- freshness
237
- indexingRef
238
- requestedRefKind
239
- ${TARGET_RESOLUTION_SELECTION}
240
- ${DISCOVERY_TARGET_PROGRESS_RETRY_SELECTION}
241
- }
242
- expiresAt
243
- results {
244
- query
245
- queryWarnings
246
- sources
247
- results {
248
- id
249
- resultType
250
- targetLabel
251
- requestedTargetLabel
252
- freshTargetLabel
253
- servedTargetLabel
254
- freshness
255
- title
256
- summary
257
- score
258
- highlights {
259
- title
260
- summary
261
- }
262
- locator {
263
- registry
264
- packageName
265
- version
266
- pageId
267
- sourceKind
268
- sourceUrl
269
- repoUrl
270
- gitRef
271
- requestedRef
272
- filePath
273
- startLine
274
- endLine
275
- fileContentHash
276
- symbolRef
277
- qualifiedPath
278
- kind
279
- category
280
- language
281
- }
282
- }
283
- page {
284
- offset
285
- limit
286
- returned
287
- hasMore
288
- }
289
- partialResults
290
- sourceStatus {
291
- source
292
- targetLabel
293
- requestedTargetLabel
294
- freshTargetLabel
295
- servedTargetLabel
296
- ${TARGET_RESOLUTION_SELECTION}
297
- indexingStatus
298
- codeIndexState
299
- resultCount
300
- appliedFilters
301
- ignoredFilters
302
- incompatibleFilters
303
- appliedQueryFeatures
304
- ignoredQueryFeatures
305
- incompatibleQueryFeatures
306
- note
307
- }
308
- }
309
- }
310
- }`;function debugUnifiedSearchRequest(variables){if(!isDebugAreaEnabled("code-nav"))return;const serialised=serialiseForDebug(variables);const filters=asRecord(serialised.filters);debugLog("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){if(!isDebugAreaEnabled("code-nav-wire"))return;debugLog("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()}).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 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()),note:z2.string().nullable().optional()});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)});var unifiedSearchSessionStatusSchema=z2.enum(["PENDING","INDEXING","SEARCHING","COMPLETED","TIMEOUT","FAILED"]);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()});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()});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 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=`
311
- query ListRepoFiles(
312
- $registry: Registry
313
- $packageName: String
314
- $repoUrl: String
315
- $gitRef: String
316
- $version: String
317
- $pathPrefix: String
318
- $pathSelectors: [FilePathSelectorInput!]
319
- $extensions: [String!]
320
- $fileTypes: [String!]
321
- $languages: [String!]
322
- $fileIntent: FileIntent
323
- $fileIntents: [FileIntent!]
324
- $excludeFileIntents: [FileIntent!]
325
- $excludeDocFiles: Boolean
326
- $excludeTestFiles: Boolean
327
- $includeHidden: Boolean
328
- $limit: Int
329
- $waitTimeoutMs: Int
330
- ) {
331
- listRepoFiles(
332
- registry: $registry
333
- packageName: $packageName
334
- repoUrl: $repoUrl
335
- gitRef: $gitRef
336
- version: $version
337
- pathPrefix: $pathPrefix
338
- pathSelectors: $pathSelectors
339
- extensions: $extensions
340
- fileTypes: $fileTypes
341
- languages: $languages
342
- fileIntent: $fileIntent
343
- fileIntents: $fileIntents
344
- excludeFileIntents: $excludeFileIntents
345
- excludeDocFiles: $excludeDocFiles
346
- excludeTestFiles: $excludeTestFiles
347
- includeHidden: $includeHidden
348
- limit: $limit
349
- waitTimeoutMs: $waitTimeoutMs
350
- ) {
351
- files {
352
- path
353
- name
354
- language
355
- fileType
356
- byteSize
357
- }
358
- total
359
- hasMore
360
- indexedVersion
361
- resolution {
362
- requestedVersion
363
- requestedRef
364
- resolvedRef
365
- commitSha
366
- }
367
- ${TARGET_RESOLUTION_SELECTION}
368
- diagnostics {
369
- hint
370
- }
371
- codeIndexState
372
- indexingRef
373
- availableVersions {
374
- version
375
- ref
376
- }
377
- ${INDEXING_DURATION_ESTIMATE_SELECTION}
378
- }
379
- }`;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=`
380
- query FetchCodeContext(
381
- $registry: Registry
382
- $packageName: String
383
- $repoUrl: String
384
- $gitRef: String
385
- $version: String
386
- $filePath: String!
387
- $startLine: Int
388
- $endLine: Int
389
- $waitTimeoutMs: Int
390
- ) {
391
- fetchCodeContext(
392
- registry: $registry
393
- packageName: $packageName
394
- repoUrl: $repoUrl
395
- gitRef: $gitRef
396
- version: $version
397
- filePath: $filePath
398
- startLine: $startLine
399
- endLine: $endLine
400
- waitTimeoutMs: $waitTimeoutMs
401
- ) {
402
- content
403
- filePath
404
- language
405
- totalLines
406
- startLine
407
- endLine
408
- repoUrl
409
- gitRef
410
- isBinary
411
- codeIndexState
412
- indexingRef
413
- ${CODE_CONTEXT_AVAILABLE_VERSIONS_SELECTION}
414
- ${INDEXING_DURATION_ESTIMATE_SELECTION}
415
- ${TARGET_RESOLUTION_SELECTION}
416
- }
417
- }`;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(`
418
- `);const symbolBlock=symbolSelection.length>0?`
419
- symbol {
420
- ${symbolSelection}
421
- }`:"";return`
422
- query GrepRepo(
423
- $registry: Registry
424
- $packageName: String
425
- $repoUrl: String
426
- $gitRef: String
427
- $version: String
428
- $waitTimeoutMs: Int
429
- $pattern: String!
430
- $patternType: GrepPatternType
431
- $caseSensitive: Boolean
432
- $pathSelectors: [GrepPathSelectorInput!]
433
- $extensions: [String!]
434
- $excludeDocFiles: Boolean
435
- $excludeTestFiles: Boolean
436
- $allowUnscoped: Boolean
437
- $contextLinesBefore: Int
438
- $contextLinesAfter: Int
439
- $maxMatches: Int
440
- $maxMatchesPerFile: Int
441
- $cursor: String
442
- $symbolFields: [String!]
443
- ) {
444
- grepRepo(
445
- registry: $registry
446
- packageName: $packageName
447
- repoUrl: $repoUrl
448
- gitRef: $gitRef
449
- version: $version
450
- waitTimeoutMs: $waitTimeoutMs
451
- pattern: $pattern
452
- patternType: $patternType
453
- caseSensitive: $caseSensitive
454
- pathSelectors: $pathSelectors
455
- extensions: $extensions
456
- excludeDocFiles: $excludeDocFiles
457
- excludeTestFiles: $excludeTestFiles
458
- allowUnscoped: $allowUnscoped
459
- contextLinesBefore: $contextLinesBefore
460
- contextLinesAfter: $contextLinesAfter
461
- maxMatches: $maxMatches
462
- maxMatchesPerFile: $maxMatchesPerFile
463
- cursor: $cursor
464
- symbolFields: $symbolFields
465
- ) {
466
- matches {
467
- filePath
468
- line
469
- matchStartByte
470
- matchEndByte
471
- lineContent
472
- contextBefore
473
- contextAfter
474
- fileContentHash
475
- fileIntent
476
- symbolRowId${symbolBlock}
477
- }
478
- nextCursor
479
- totalMatches
480
- hasMore
481
- truncatedReason
482
- routeTaken
483
- filesScanned
484
- filesInScope
485
- binaryFilesSkipped
486
- filesTooLargeSkipped
487
- uniqueFilesMatched
488
- indexedVersion
489
- resolution {
490
- requestedVersion
491
- requestedRef
492
- resolvedRef
493
- commitSha
494
- }
495
- ${TARGET_RESOLUTION_SELECTION}
496
- codeIndexState
497
- indexingRef
498
- availableVersions {
499
- version
500
- ref
501
- }
502
- ${INDEXING_DURATION_ESTIMATE_SELECTION}
503
- }
504
- }`}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});if(response.status<200||response.status>=300)return response;if(!hasSchemaMismatchErrors(response.parsedBody))return response;for(const fallbackQuery of buildTargetResolutionFallbackQueries(input.query)){debugLog("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});if(!hasSchemaMismatchErrors(fallbackResponse.parsedBody)){return fallbackResponse}}return response}async search(params){return executeWithTokenRefresh({getToken:()=>this.tokenProvider.getToken(),forceRefresh:()=>this.tokenProvider.forceRefresh(),shouldRefresh:(error)=>error instanceof AuthenticationError,executeWithToken:(token)=>this.executeUnifiedSearch(token,params)})}async searchStatus(searchRef){return executeWithTokenRefresh({getToken:()=>this.tokenProvider.getToken(),forceRefresh:()=>this.tokenProvider.forceRefresh(),shouldRefresh:(error)=>error instanceof AuthenticationError,executeWithToken:(token)=>this.executeUnifiedSearchStatus(token,searchRef)})}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})),query:params.query,sources:params.sources,filters:params.filters,allowPartialResults:params.allowPartialResults??false,limit:params.limit,offset:params.offset,waitTimeoutMs:params.waitTimeoutMs};debugUnifiedSearchRequest(variables);debugGraphqlWireRequest("search",UNIFIED_SEARCH_QUERY,variables);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){let response;try{response=await this.postGraphqlWithTargetResolutionFallback({token,query:UNIFIED_SEARCH_STATUS_QUERY,variables:{searchRef,includeResults:true}})}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);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.";debugLog("code-nav",{event:"graphql-schema-mismatch",code:code??"omitted",message});return new CodeNavigationBackendError(isDebugAreaEnabled("code-nav-wire")?message:sanitized,undefined,code,retryable)}switch(code){case"PACKAGE_INDEXING":return new CodeNavigationIndexingError(this.createIndexingMessage(indexingRef,indexingEstimate,typeof extensions?.hint==="string"?extensions.hint:undefined),indexingRef,parseAvailableVersions(extensions),parseAvailableRefs(extensions),parseTargetResolution(extensions),indexingEstimate);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));case"REF_NOT_FOUND":return new CodeNavigationRefNotFoundError(message,parseGraphQLRepoUrl(extensions),parseGraphQLGitRef(extensions),parseAvailableRefs(extensions),parseSuggestedRefs(extensions));case"NOT_FOUND":case"PACKAGE_NOT_FOUND":case"NO_REPOSITORY_URL":return new CodeNavigationTargetNotFoundError(message);case"REPOSITORY_NOT_FOUND":return new CodeNavigationTargetNotFoundError(message,undefined,parseGraphQLRepoUrl(extensions),parseGraphQLGitRef(extensions));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"INTERNAL_ERROR":case"UNKNOWN_ERROR":return new CodeNavigationBackendError(message,undefined,code,retryable);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)}}return new CodeNavigationBackendError(message,undefined,code,retryable)}createIndexingMessage(indexingRef,estimate,backendHint){const retryGuidance="Retry, or wait until ready with CLI `--wait 60000` / MCP `wait_timeout_ms: 60000`.";const estimateMessage=formatIndexingDurationEstimate(estimate);const base=estimateMessage?`Target is indexing. ${estimateMessage} ${retryGuidance}`:backendHint?appendRetryGuidance(backendHint,retryGuidance):`Target is indexing. Usually completes within 30 seconds. ${retryGuidance}`;if(indexingRef){return`${base} Indexing ref: ${indexingRef}.`}return base}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,note:entry.note??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})),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)})),expiresAt:progress.expiresAt??undefined}}throwIfIndexing(data){if(data.codeIndexState==="INDEXING"){const targetResolution=normaliseTargetResolution(data.targetResolution);const indexingEstimate=normaliseIndexingDurationEstimate(data.indexingEstimate);throw new CodeNavigationIndexingError(this.createIndexingMessage(data.indexingRef??targetResolution?.indexingRef,indexingEstimate),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:(error)=>error instanceof AuthenticationError,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:(error)=>error instanceof AuthenticationError,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:(error)=>error instanceof AuthenticationError,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 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 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 formatIndexingDurationEstimate(estimate){if(!estimate)return;const parts=[];if(typeof estimate.elapsedSeconds==="number"){parts.push(`Running for ${formatSeconds(estimate.elapsedSeconds)}.`)}if(typeof estimate.lowerSeconds==="number"&&typeof estimate.upperSeconds==="number"){const duration=estimate.lowerSeconds===estimate.upperSeconds?formatSeconds(estimate.lowerSeconds):`${estimate.lowerSeconds} to ${formatSeconds(estimate.upperSeconds)}`;parts.push(`Similar refs usually index in ${duration}.`)}return parts.length>0?parts.join(" "):undefined}function formatSeconds(seconds){return`${seconds} ${seconds===1?"second":"seconds"}`}function appendRetryGuidance(hint,retryGuidance){if(hint.includes("--wait")||hint.includes("wait_timeout_ms"))return hint;return`${hint} ${retryGuidance}`}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 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;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"){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=`
505
- query PackageSummary(
506
- $registry: Registry!
507
- $name: String!
508
- $includeVerboseFields: Boolean! = true
509
- ) {
510
- packageSummary(registry: $registry, name: $name) {
511
- package {
512
- name
513
- registry
514
- description
515
- latestVersion
516
- latestVersionPublishedAt
517
- homepage
518
- repositoryUrl
519
- license
520
- downloadsLastMonth
521
- downloadsTotal
522
- githubRepository {
523
- stargazersCount
524
- forksCount
525
- openIssuesCount
526
- archived
527
- language @include(if: $includeVerboseFields)
528
- topics @include(if: $includeVerboseFields)
529
- pushedAt @include(if: $includeVerboseFields)
530
- }
531
- }
532
- security {
533
- vulnerabilityCount
534
- hasCurrentVulnerabilities
535
- recentVulnerabilities @include(if: $includeVerboseFields) {
536
- osvId
537
- summary
538
- severityScore
539
- publishedAt
540
- }
541
- }
542
- latestChangelogs(limit: 3) @include(if: $includeVerboseFields) {
543
- version
544
- publishedAt
545
- body
546
- }
547
- }
548
- }`;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=`
549
- query PackageVulnerabilities(
550
- $registry: Registry!
551
- $name: String!
552
- $version: String
553
- $minSeverity: Float
554
- $includeWithdrawn: Boolean
555
- $scope: VulnerabilityScope = AFFECTED
556
- $after: String
557
- ) {
558
- packageVulnerabilities(
559
- registry: $registry
560
- name: $name
561
- version: $version
562
- minSeverity: $minSeverity
563
- includeWithdrawn: $includeWithdrawn
564
- ) {
565
- package {
566
- name
567
- registry
568
- version
569
- }
570
- security {
571
- affectedVulnerabilityCount
572
- nonAffectingVulnerabilityCount
573
- allVulnerabilityCount
574
- currentVersionAffected
575
- upgradePaths
576
- advisories(scope: $scope, first: 100, after: $after) {
577
- entries {
578
- osvId
579
- summary
580
- severityScore
581
- severityType
582
- affectedVersionRanges
583
- affectedVersionRangesCount
584
- affectedVersionRangesTruncated
585
- fixedInVersions
586
- publishedAt
587
- modifiedAt
588
- withdrawnAt
589
- aliases
590
- isMalicious
591
- affectsInspectedVersion
592
- matchedAffectedVersionRanges
593
- duplicateIds
594
- }
595
- pageInfo {
596
- hasNextPage
597
- endCursor
598
- totalCount
599
- }
600
- }
601
- }
602
- }
603
- }`;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=`
604
- query PackageDependencies(
605
- $registry: Registry!
606
- $name: String!
607
- $version: String
608
- $includeTransitive: Boolean
609
- $includeTransitiveDetails: Boolean! = true
610
- $includeDependencyGraph: Boolean! = true
611
- $includeGroups: Boolean! = true
612
- $maxDepth: Int
613
- $lifecycle: [String!]
614
- ) {
615
- packageDependencies(
616
- registry: $registry
617
- name: $name
618
- version: $version
619
- includeTransitive: $includeTransitive
620
- maxDepth: $maxDepth
621
- lifecycle: $lifecycle
622
- ) {
623
- package {
624
- name
625
- registry
626
- version
627
- }
628
- dependencies {
629
- # Backend-side summary block intentionally not selected — our
630
- # envelope computes runtime.count client-side from direct[].length
631
- # so the invariant runtime.count === runtime.items.length always
632
- # holds regardless of backend-side drift.
633
- direct {
634
- name
635
- versionConstraint
636
- type
637
- }
638
- transitive {
639
- totalEdges @include(if: $includeTransitiveDetails)
640
- uniquePackagesCount @include(if: $includeTransitiveDetails)
641
- uniqueDependencies @include(if: $includeTransitiveDetails)
642
- dependencyConflicts @include(if: $includeTransitiveDetails) {
643
- packageName
644
- requiredVersions
645
- conflictingEdges {
646
- fromIndex
647
- toIndex
648
- versionConstraint
649
- dependencyType
650
- }
651
- }
652
- circularDependencyCycles @include(if: $includeTransitiveDetails) {
653
- cycleStart
654
- circularPath
655
- displayChain
656
- }
657
- dependencyGraph @include(if: $includeDependencyGraph) {
658
- formatVersion
659
- nodes {
660
- registry
661
- name
662
- version
663
- }
664
- edges {
665
- fromIndex
666
- toIndex
667
- constraint
668
- dependencyType
669
- }
670
- }
671
- }
672
- }
673
- dependencyGroups @include(if: $includeGroups) {
674
- primaryGroup
675
- environmentMarkers {
676
- type
677
- value
678
- raw
679
- }
680
- groups {
681
- name
682
- lifecycle
683
- conditionType
684
- conditionValue
685
- selectionMode
686
- exclusiveGroup
687
- fallbackPriority
688
- compatibleWith
689
- defaultEnabled
690
- dependencies {
691
- name
692
- constraint
693
- }
694
- }
695
- }
696
- }
697
- }`;var PACKAGE_UPGRADE_DEPENDENCY_PROBE_QUERY=`
698
- query PackageUpgradeDependencyProbe(
699
- $registry: Registry!
700
- $name: String!
701
- $version: String!
702
- $includeTransitiveRisk: Boolean!
703
- $includeTransitiveSecurity: Boolean!
704
- $includeDependencyIssues: Boolean!
705
- $includeDependencyChanges: Boolean!
706
- $includeGroups: Boolean!
707
- $lifecycle: [String!]
708
- $minSeverity: Float
709
- ) {
710
- packageDependencies(
711
- registry: $registry
712
- name: $name
713
- version: $version
714
- includeTransitive: $includeTransitiveRisk
715
- lifecycle: $lifecycle
716
- ) {
717
- package {
718
- name
719
- registry
720
- version
721
- publishedAt
722
- deprecated
723
- deprecationReason
724
- }
725
- dependencies {
726
- direct {
727
- name
728
- versionConstraint
729
- type
730
- }
731
- transitive @include(if: $includeTransitiveRisk) {
732
- dependencyGraph @include(if: $includeDependencyChanges) {
733
- formatVersion
734
- nodes {
735
- registry
736
- name
737
- version
738
- }
739
- edges {
740
- fromIndex
741
- toIndex
742
- constraint
743
- dependencyType
744
- }
745
- }
746
- vulnerabilitySummary(minSeverity: $minSeverity) @include(if: $includeTransitiveSecurity) {
747
- affected {
748
- totalVulnerabilities
749
- critical
750
- high
751
- medium
752
- low
753
- unknown
754
- }
755
- nonAffecting {
756
- totalVulnerabilities
757
- critical
758
- high
759
- medium
760
- low
761
- unknown
762
- }
763
- combined {
764
- totalVulnerabilities
765
- critical
766
- high
767
- medium
768
- low
769
- unknown
770
- }
771
- totalPackagesAnalyzed
772
- affectedPackageCount
773
- calculatedAt
774
- packages {
775
- registry
776
- name
777
- versions
778
- affectedCount
779
- nonAffectingCount
780
- totalCount
781
- maxSeverityScore
782
- maxSeverityLabel
783
- advisoryIds(scope: AFFECTED)
784
- mostCritical {
785
- osvId
786
- registry
787
- packageName
788
- summary
789
- severityScore
790
- severityType
791
- affectedVersionRanges
792
- fixedInVersions
793
- publishedAt
794
- modifiedAt
795
- withdrawnAt
796
- aliases
797
- isMalicious
798
- }
799
- advisoryOccurrences(scope: AFFECTED, minSeverity: $minSeverity, limit: 5) {
800
- version
801
- affectsResolvedVersion
802
- matchedAffectedVersionRanges
803
- fixVersionsAboveResolved
804
- nearestFixedVersion
805
- advisory {
806
- osvId
807
- registry
808
- packageName
809
- summary
810
- severityScore
811
- severityType
812
- affectedVersionRanges
813
- fixedInVersions
814
- publishedAt
815
- modifiedAt
816
- withdrawnAt
817
- aliases
818
- isMalicious
819
- }
820
- }
821
- }
822
- }
823
- dependencyIssues @include(if: $includeDependencyIssues) {
824
- totalCount
825
- deprecatedCount
826
- outdatedCount
827
- duplicateCount
828
- conflictCount
829
- deprecatedPackages {
830
- registry
831
- name
832
- versions
833
- reasons {
834
- version
835
- reason
836
- }
837
- }
838
- outdatedPackages {
839
- registry
840
- name
841
- latestVersion
842
- severity
843
- versions {
844
- version
845
- severity
846
- }
847
- repositoryUrl
848
- }
849
- duplicatePackages {
850
- registry
851
- name
852
- versions
853
- }
854
- conflicts {
855
- registry
856
- name
857
- versions
858
- requiredVersions
859
- conflictingEdges {
860
- fromIndex
861
- toIndex
862
- versionConstraint
863
- dependencyType
864
- }
865
- }
866
- }
867
- }
868
- }
869
- dependencyGroups @include(if: $includeGroups) {
870
- primaryGroup
871
- environmentMarkers {
872
- type
873
- value
874
- raw
875
- }
876
- groups {
877
- name
878
- lifecycle
879
- conditionType
880
- conditionValue
881
- selectionMode
882
- exclusiveGroup
883
- fallbackPriority
884
- compatibleWith
885
- defaultEnabled
886
- dependencies {
887
- name
888
- constraint
889
- }
890
- }
891
- }
892
- }
893
- }`;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=`
894
- query PackageUpgradeReview(
895
- $packages: [PackageUpgradeReviewPackageInput!]!
896
- $includeTransitiveSecurity: Boolean!
897
- $includeDependencyIssues: Boolean!
898
- $minSeverity: Float
899
- $changelogLimit: Int!
900
- ) {
901
- packageUpgradeReview(
902
- packages: $packages
903
- includeTransitiveSecurity: $includeTransitiveSecurity
904
- minSeverity: $minSeverity
905
- changelogLimit: $changelogLimit
906
- ) {
907
- summary {
908
- total
909
- withUnknowns
910
- withAddedAdvisories
911
- withBreakingSignals
912
- withDirectDependencyChanges
913
- withTransitiveVulnerabilityAdditions
914
- }
915
- reviews {
916
- registry
917
- name
918
- currentVersion
919
- targetVersion
920
- latestVersion
921
- versionDelta
922
- security {
923
- current {
924
- version
925
- publishedAt
926
- deprecated
927
- deprecationReason
928
- affectedCount
929
- nonAffectingCount
930
- allCount
931
- lastModifiedAt
932
- advisories {
933
- ...PackageUpgradeAdvisoryFields
934
- }
935
- }
936
- target {
937
- version
938
- publishedAt
939
- deprecated
940
- deprecationReason
941
- affectedCount
942
- nonAffectingCount
943
- allCount
944
- lastModifiedAt
945
- advisories {
946
- ...PackageUpgradeAdvisoryFields
947
- }
948
- }
949
- added {
950
- ...PackageUpgradeAdvisoryFields
951
- }
952
- removed {
953
- ...PackageUpgradeAdvisoryFields
954
- }
955
- notAddressed {
956
- ...PackageUpgradeAdvisoryFields
957
- }
958
- fixed {
959
- ...PackageUpgradeAdvisoryFields
960
- }
961
- introduced {
962
- ...PackageUpgradeAdvisoryFields
963
- }
964
- unchanged {
965
- ...PackageUpgradeAdvisoryFields
966
- }
967
- transitive @include(if: $includeTransitiveSecurity) {
968
- currentAffected
969
- targetAffected
970
- introducedPackages
971
- fixedPackages
972
- introducedPackageDetails(first: 50) {
973
- ...PackageUpgradeTransitivePackagePageFields
974
- }
975
- fixedPackageDetails(first: 50) {
976
- ...PackageUpgradeTransitivePackagePageFields
977
- }
978
- stillAffectedPackageDetails(first: 50) {
979
- ...PackageUpgradeTransitivePackagePageFields
980
- }
981
- }
982
- }
983
- changelog {
984
- source
985
- fallback
986
- entries {
987
- ...PackageUpgradeChangelogEntryFields
988
- }
989
- sampledEntries {
990
- ...PackageUpgradeChangelogEntryFields
991
- }
992
- keywordEntries {
993
- ...PackageUpgradeChangelogEntryFields
994
- }
995
- totalKeywordEntries
996
- totalEntries
997
- totalEntriesWithBodies
998
- truncated
999
- hasReleaseNoteBodies
1000
- breakingSignals
1001
- migrationSignals
1002
- }
1003
- compatibility {
1004
- peerDependencyChanges
1005
- notes
1006
- }
1007
- dependencyChanges {
1008
- direct {
1009
- ...PackageUpgradeDependencyChangeGroupFields
1010
- }
1011
- transitive {
1012
- ...PackageUpgradeDependencyChangeGroupFields
1013
- }
1014
- }
1015
- dependencyIssues @include(if: $includeDependencyIssues) {
1016
- currentTotal
1017
- targetTotal
1018
- introducedDeprecated
1019
- introducedDuplicates
1020
- introducedConflicts
1021
- introducedOutdated
1022
- }
1023
- unknowns
1024
- }
1025
- }
1026
- }
1027
-
1028
- fragment PackageUpgradeAdvisoryFields on PackageUpgradeAdvisorySummary {
1029
- id
1030
- aliases
1031
- summary
1032
- severity
1033
- severityLabel
1034
- fixedIn
1035
- isMalicious
1036
- }
1037
-
1038
- fragment PackageUpgradeTransitivePackagePageFields on PackageUpgradeTransitivePackagePage {
1039
- entries {
1040
- id
1041
- registry
1042
- name
1043
- versions
1044
- affectedCount
1045
- maxSeverityScore
1046
- maxSeverityLabel
1047
- advisoryIds
1048
- }
1049
- totalCount
1050
- truncated
1051
- }
1052
-
1053
- fragment PackageUpgradeChangelogEntryFields on PackageUpgradeChangelogEntry {
1054
- version
1055
- publishedAt
1056
- htmlUrl
1057
- body
1058
- bodyPreview
1059
- headline
1060
- signals
1061
- }
1062
-
1063
- fragment PackageUpgradeDependencyChangeGroupFields on PackageUpgradeDependencyChangeGroup {
1064
- added {
1065
- name
1066
- registry
1067
- version
1068
- fromVersions
1069
- toVersions
1070
- constraint
1071
- type
1072
- }
1073
- removed {
1074
- name
1075
- registry
1076
- version
1077
- fromVersions
1078
- toVersions
1079
- constraint
1080
- type
1081
- }
1082
- changed {
1083
- name
1084
- registry
1085
- version
1086
- fromVersions
1087
- toVersions
1088
- constraint
1089
- type
1090
- }
1091
- }`;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=`
1092
- query PackageChangelog(
1093
- $registry: Registry
1094
- $name: String
1095
- $repoUrl: String
1096
- $gitRef: String
1097
- $fromVersion: String
1098
- $toVersion: String
1099
- $limit: Int
1100
- $includeBodies: Boolean! = true
1101
- ) {
1102
- packageChangelog(
1103
- registry: $registry
1104
- name: $name
1105
- repoUrl: $repoUrl
1106
- gitRef: $gitRef
1107
- fromVersion: $fromVersion
1108
- toVersion: $toVersion
1109
- limit: $limit
1110
- ) {
1111
- package {
1112
- name
1113
- registry
1114
- repoUrl
1115
- fromVersion
1116
- toVersion
1117
- limit
1118
- }
1119
- source
1120
- entries {
1121
- version
1122
- normalizedVersion
1123
- body @include(if: $includeBodies)
1124
- htmlUrl
1125
- publishedAt
1126
- }
1127
- }
1128
- }`;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=`
1129
- query ListPackageDocs(
1130
- $registry: Registry!
1131
- $packageName: String!
1132
- $version: String
1133
- $limit: Int
1134
- $after: String
1135
- ) {
1136
- listPackageDocs(
1137
- registry: $registry
1138
- packageName: $packageName
1139
- version: $version
1140
- limit: $limit
1141
- after: $after
1142
- ) {
1143
- registry
1144
- packageName
1145
- version
1146
- stale
1147
- pages {
1148
- id
1149
- title
1150
- slug
1151
- order
1152
- linkName
1153
- lastUpdatedAt
1154
- sourceKind
1155
- sourceUrl
1156
- repoUrl
1157
- gitRef
1158
- requestedRef
1159
- filePath
1160
- }
1161
- pageInfo {
1162
- hasNextPage
1163
- endCursor
1164
- totalCount
1165
- }
1166
- }
1167
- }`;var READ_PACKAGE_DOC_QUERY=`
1168
- query ReadPackageDoc($pageId: String!) {
1169
- getDocPage(pageId: $pageId) {
1170
- registry
1171
- packageName
1172
- version
1173
- sourceKind
1174
- page {
1175
- id
1176
- title
1177
- content
1178
- contentFormat
1179
- breadcrumbs
1180
- linkName
1181
- lastUpdatedAt
1182
- sourceKind
1183
- source {
1184
- url
1185
- label
1186
- }
1187
- repoUrl
1188
- gitRef
1189
- requestedRef
1190
- filePath
1191
- baseUrl
1192
- }
1193
- }
1194
- }`;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 withTelemetrySpan("pkg-intel.summary.request",()=>executeWithTokenRefresh({getToken:()=>this.tokenProvider.getToken(),forceRefresh:()=>this.tokenProvider.forceRefresh(),shouldRefresh:(error)=>error instanceof AuthenticationError,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})}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){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)}createTransportError(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})}createGraphQLError(errors){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,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=pkg-graphql to inspect GraphQL details during local development.";debugLog("pkg-graphql",{event:"graphql-schema-mismatch",code:code??"omitted",message});return new PackageIntelligenceBackendError(isDebugAreaEnabled("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:break}return new PackageIntelligenceBackendError(message,undefined,code,retryable)}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 withTelemetrySpan("pkg-intel.vulnerabilities.request",()=>executeWithTokenRefresh({getToken:()=>this.tokenProvider.getToken(),forceRefresh:()=>this.tokenProvider.forceRefresh(),shouldRefresh:(error)=>error instanceof AuthenticationError,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})}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 withTelemetrySpan("pkg-intel.dependencies.request",()=>executeWithTokenRefresh({getToken:()=>this.tokenProvider.getToken(),forceRefresh:()=>this.tokenProvider.forceRefresh(),shouldRefresh:(error)=>error instanceof AuthenticationError,executeWithToken:(token)=>this.executePackageDependencies(token,params)}))}async packageUpgradeDependencyProbe(params){return withTelemetrySpan("pkg-intel.upgrade-dependency-probe.request",()=>executeWithTokenRefresh({getToken:()=>this.tokenProvider.getToken(),forceRefresh:()=>this.tokenProvider.forceRefresh(),shouldRefresh:(error)=>error instanceof AuthenticationError,executeWithToken:(token)=>this.executePackageUpgradeDependencyProbe(token,params)}))}async packageUpgradeReview(params){return withTelemetrySpan("pkg-intel.upgrade-review.request",()=>executeWithTokenRefresh({getToken:()=>this.tokenProvider.getToken(),forceRefresh:()=>this.tokenProvider.forceRefresh(),shouldRefresh:(error)=>error instanceof AuthenticationError,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})}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})}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})}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 withTelemetrySpan("pkg-intel.changelog.request",()=>executeWithTokenRefresh({getToken:()=>this.tokenProvider.getToken(),forceRefresh:()=>this.tokenProvider.forceRefresh(),shouldRefresh:(error)=>error instanceof AuthenticationError,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})}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 withTelemetrySpan("pkg-intel.docs.list",()=>executeWithTokenRefresh({getToken:()=>this.tokenProvider.getToken(),forceRefresh:()=>this.tokenProvider.forceRefresh(),shouldRefresh:(error)=>error instanceof AuthenticationError,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})}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 withTelemetrySpan("pkg-intel.docs.read",()=>executeWithTokenRefresh({getToken:()=>this.tokenProvider.getToken(),forceRefresh:()=>this.tokenProvider.forceRefresh(),shouldRefresh:(error)=>error instanceof AuthenticationError,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})}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 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){return this.withTokenRefresh((service)=>service.search(params))}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){return executeWithTokenRefresh({getToken:()=>this.tokenProvider.getToken(),forceRefresh:()=>this.tokenProvider.forceRefresh(),shouldRefresh:(error)=>error instanceof AuthenticationError,executeWithToken:async(token)=>{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}}}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_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 value in registryMap}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";export{CLIENT_UPDATE_REQUIRED_REASON,ClientUpdateRequiredError,debugLog,FetchTimeoutError,DEFAULT_MCP_URL,DEFAULT_API_URL,DEFAULT_CODE_NAV_URL,getMcpUrl,getApiUrl,getCodeNavigationUrl,getEnvApiToken,withTelemetrySpan,startTelemetrySpan,endTelemetrySpan,flushTelemetry,AuthenticationError,ApiRateLimitError,GitHitsServiceImpl,CodeNavigationAccessError,CodeNavigationGraphQLError,CodeNavigationIndexingError,CodeNavigationUnresolvableError,MalformedCodeNavigationResponseError,CodeNavigationTargetNotFoundError,CodeNavigationFileNotFoundError,CodeNavigationVersionNotFoundError,CodeNavigationRefNotFoundError,CodeNavigationValidationError,CodeNavigationFeatureFlagRequiredError,CodeNavigationNetworkError,CodeNavigationBackendError,CodeNavigationServiceImpl,PackageIntelligenceAccessError,PackageIntelligenceFeatureFlagRequiredError,PackageIntelligenceNetworkError,PackageIntelligenceBackendError,PackageIntelligenceGraphQLError,PackageIntelligenceTargetNotFoundError,PackageIntelligenceValidationError,PackageIntelligenceVersionNotFoundError,MalformedPackageIntelligenceResponseError,PackageIntelligenceChangelogSourceNotFoundError,PackageIntelligenceServiceImpl,RefreshingGitHitsService,createStaticTokenProvider,PKGSEER_REGISTRY_ARGS,PKGSEER_REGISTRY_LIST,toPkgseerRegistry,toPkgseerRegistryLowercase,isKnownPkgseerRegistryArg,createClientHeaderBuilder};