@githits/mcp 0.9.0 → 0.9.2

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,1209 +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 TERMS_ACCEPTANCE_REQUIRED_CODE="TERMS_ACCEPTANCE_REQUIRED";var TERMS_URL="https://githits.com/legal/terms-of-service/";var TERMS_ACCEPTANCE_URL="https://app.githits.com/settings/privacy";class TermsAcceptanceRequiredError extends Error{code=TERMS_ACCEPTANCE_REQUIRED_CODE;termsUrl;acceptanceUrl;constructor(remediation={}){super("Terms acceptance required. Run `githits settings terms accept`, then retry.");this.name="TermsAcceptanceRequiredError";this.termsUrl=remediation.termsUrl??TERMS_URL;this.acceptanceUrl=remediation.acceptanceUrl??TERMS_ACCEPTANCE_URL}}function createTermsAcceptanceError(payload){const record=parseErrorRecord(payload);if(!record)return;const contract=record.code===TERMS_ACCEPTANCE_REQUIRED_CODE?record:firstGraphQLErrorExtensions(record);if(contract?.code!==TERMS_ACCEPTANCE_REQUIRED_CODE)return;return new TermsAcceptanceRequiredError({termsUrl:stringField(contract,"terms_url"),acceptanceUrl:stringField(contract,"acceptance_url")})}function throwIfTermsAcceptanceRequired(payload){const error=createTermsAcceptanceError(payload);if(error)throw error}function parseErrorRecord(payload){if(typeof payload==="string"){try{return parseErrorRecord(JSON.parse(payload))}catch{return}}return payload&&typeof payload==="object"?payload:undefined}function firstGraphQLErrorExtensions(record){const firstError=Array.isArray(record.errors)?record.errors[0]:undefined;if(!firstError||typeof firstError!=="object")return;const extensions=firstError.extensions;return extensions&&typeof extensions==="object"?extensions:undefined}function stringField(record,field){return typeof record[field]==="string"?record[field]:undefined}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}}function isTokenRefreshableError(error){return error instanceof AuthenticationError||error instanceof TermsAcceptanceRequiredError}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"]);throwIfTermsAcceptanceRequired(body);switch(status){case 401:return new AuthenticationError(SERVER_AUTHENTICATION_REJECTED_MESSAGE,"server");case 403:return new Error("Access denied.");case 404:return new Error(detail||"Resource not found.");case 429:return new ApiRateLimitError(undefined,parseRetryAfterSeconds(response.headers.get("Retry-After"),Date.now()));default:{if(status>=500){return new Error(`Server error (${status}). Try again shortly.${detail?` ${detail}`:""}`)}return new Error(`Request failed with status ${status}.${detail?` ${detail}`:""}`)}}}}class GitHitsRequestTimeoutError extends FetchTimeoutError{constructor(timeoutMs,cause){super(timeoutMs,{cause});this.name="GitHitsRequestTimeoutError";this.message="Request to GitHits timed out. Try again."}}function isAbortError(error){return error instanceof Error&&error.name==="AbortError"}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);throwIfTermsAcceptanceRequired(parsedBody);return{status:response.status,responseBody,parsedBody}}function parseJsonOrNull(body){if(!body)return null;try{return JSON.parse(body)}catch{return null}}var CLIENT_UPDATE_REQUIRED_REASON="Backend protocol changed";class ClientUpdateRequiredError extends Error{reason;currentVersion;constructor(message=`Update required: ${CLIENT_UPDATE_REQUIRED_REASON}`,reason=CLIENT_UPDATE_REQUIRED_REASON,currentVersion=undefined){super(message);this.reason=reason;this.currentVersion=currentVersion;this.name="ClientUpdateRequiredError"}}function isClientUpdateRequiredGraphQLError(input){return input.code==="CLIENT_UPDATE_REQUIRED"}function isGraphQLSchemaMismatchError(input){if(!isGraphQLSchemaMismatchMessage(input.message))return false;return!input.code||input.code==="GRAPHQL_VALIDATION_FAILED"||input.code==="BAD_USER_INPUT"}function isGraphQLSchemaMismatchMessage(message){return/Cannot query field|Field .* does not exist|Unknown argument|Unknown type|Unknown field/i.test(message)}async function executeWithTokenRefresh(options){const token=await options.getToken();if(!token){throw new AuthenticationError(LOCAL_AUTHENTICATION_MISSING_MESSAGE,"local")}try{return await options.executeWithToken(token)}catch(error){if(token.startsWith("ghi-")||!options.shouldRefresh(error)){throw error}const refreshedToken=await options.forceRefresh();if(!refreshedToken){throw error}return options.executeWithToken(refreshedToken)}}var INDEXING_WAIT_HINT="Wait until ready with CLI `--wait 60000` or MCP `wait_timeout_ms: 60000`.";class CodeNavigationAccessError extends Error{constructor(message){super(message);this.name="CodeNavigationAccessError"}}class CodeNavigationGraphQLError extends Error{code;constructor(message,code){super(message);this.code=code;this.name="CodeNavigationGraphQLError"}}class CodeNavigationIndexingError extends Error{indexingRef;availableVersions;availableRefs;targetResolution;indexingEstimate;hint;constructor(message,indexingRef,availableVersions,availableRefs,targetResolution=undefined,indexingEstimate=undefined,hint=undefined){super(message);this.indexingRef=indexingRef;this.availableVersions=availableVersions;this.availableRefs=availableRefs;this.targetResolution=targetResolution;this.indexingEstimate=indexingEstimate;this.hint=hint;this.name="CodeNavigationIndexingError"}}class CodeNavigationUnresolvableError extends Error{constructor(message){super(message);this.name="CodeNavigationUnresolvableError"}}class MalformedCodeNavigationResponseError extends Error{constructor(message){super(message);this.name="MalformedCodeNavigationResponseError"}}class CodeNavigationTargetNotFoundError extends Error{availableVersions;repoUrl;requestedRef;metadata;constructor(message,availableVersions,repoUrl,requestedRef,metadata=undefined){super(message);this.availableVersions=availableVersions;this.repoUrl=repoUrl;this.requestedRef=requestedRef;this.metadata=metadata;this.name="CodeNavigationTargetNotFoundError"}}class CodeNavigationFileNotFoundError extends Error{filePath;constructor(message,filePath){super(message);this.filePath=filePath;this.name="CodeNavigationFileNotFoundError"}}class CodeNavigationVersionNotFoundError extends Error{packageName;requestedVersion;latestIndexed;availableVersions;metadata;constructor(message,packageName,requestedVersion,latestIndexed,availableVersions,metadata=undefined){super(message);this.packageName=packageName;this.requestedVersion=requestedVersion;this.latestIndexed=latestIndexed;this.availableVersions=availableVersions;this.metadata=metadata;this.name="CodeNavigationVersionNotFoundError"}}class CodeNavigationRefNotFoundError extends Error{repoUrl;requestedRef;availableRefs;suggestedRefs;metadata;constructor(message,repoUrl,requestedRef,availableRefs,suggestedRefs,metadata=undefined){super(message);this.repoUrl=repoUrl;this.requestedRef=requestedRef;this.availableRefs=availableRefs;this.suggestedRefs=suggestedRefs;this.metadata=metadata;this.name="CodeNavigationRefNotFoundError"}}class CodeNavigationValidationError extends Error{constructor(message){super(message);this.name="CodeNavigationValidationError"}}class CodeNavigationFeatureFlagRequiredError extends Error{constructor(message){super(message);this.name="CodeNavigationFeatureFlagRequiredError"}}class CodeNavigationNetworkError extends Error{constructor(message,options){super(message,options);this.name="CodeNavigationNetworkError"}}class CodeNavigationBackendError extends Error{status;graphqlCode;retryable;metadata;constructor(message,status,graphqlCode,retryable,metadata=undefined){super(message);this.status=status;this.graphqlCode=graphqlCode;this.retryable=retryable;this.metadata=metadata;this.name="CodeNavigationBackendError"}}var TARGET_RESOLUTION_AVAILABLE_REFS_SELECTION=`
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 DOC_COVERAGE_SELECTION=`
17
- coverage {
18
- coverageState
19
- coverageReason
20
- pagesCrawled
21
- frontierRemaining
22
- artifactOverflowPageCount
23
- estimatedTotalPages
24
- note
25
- }`;var TARGET_RESOLUTION_SELECTION=`
26
- targetResolution {
27
- requested {
28
- kind
29
- registry
30
- packageName
31
- version
32
- repoUrl
33
- gitRef
34
- commitSha
35
- }
36
- resolvedRequested {
37
- kind
38
- registry
39
- packageName
40
- version
41
- repoUrl
42
- gitRef
43
- commitSha
44
- }
45
- served {
46
- kind
47
- registry
48
- packageName
49
- version
50
- repoUrl
51
- gitRef
52
- commitSha
53
- }
54
- freshness
55
- freshnessReason
56
- indexingRef
57
- availableVersions {
58
- version
59
- ref
60
- }
61
- ${TARGET_RESOLUTION_AVAILABLE_REFS_SELECTION}
62
- ${TARGET_RESOLUTION_SUGGESTED_REFS_SELECTION}
63
- }`;var CODE_CONTEXT_AVAILABLE_VERSIONS_SELECTION=`
64
- availableVersions {
65
- version
66
- ref
67
- }`;var DISCOVERY_TARGET_PROGRESS_RETRY_SELECTION=`
68
- availableVersions {
69
- version
70
- ref
71
- }
72
- availableRefs {
73
- version
74
- ref
75
- }
76
- ${DISCOVERY_TARGET_PROGRESS_SUGGESTED_REFS_SELECTION}`;var INDEXING_DURATION_ESTIMATE_SELECTION=`
77
- indexingEstimate {
78
- lowerSeconds
79
- upperSeconds
80
- elapsedSeconds
81
- sampleCount
82
- source
83
- }`;var UNIFIED_SEARCH_QUERY=`
84
- query UnifiedSearch(
85
- $targets: [SearchPackageInput!]!
86
- $query: String!
87
- $sources: [DiscoverySearchSource!]
88
- $filters: DiscoverySearchFiltersInput
89
- $allowPartialResults: Boolean
90
- $limit: Int
91
- $offset: Int
92
- $waitTimeoutMs: Int
93
- ) {
94
- search(
95
- targets: $targets
96
- query: $query
97
- sources: $sources
98
- filters: $filters
99
- allowPartialResults: $allowPartialResults
100
- limit: $limit
101
- offset: $offset
102
- waitTimeoutMs: $waitTimeoutMs
103
- ) {
104
- completed
105
- searchRef
106
- result {
107
- query
108
- queryWarnings
109
- sources
110
- results {
111
- id
112
- resultType
113
- targetLabel
114
- requestedTargetLabel
115
- freshTargetLabel
116
- servedTargetLabel
117
- freshness
118
- title
119
- summary
120
- score
121
- highlights {
122
- title
123
- summary
124
- }
125
- locator {
126
- registry
127
- packageName
128
- version
129
- pageId
130
- sourceKind
131
- sourceUrl
132
- repoUrl
133
- gitRef
134
- requestedRef
135
- filePath
136
- startLine
137
- endLine
138
- fileContentHash
139
- symbolRef
140
- qualifiedPath
141
- kind
142
- category
143
- language
144
- }
145
- }
146
- page {
147
- offset
148
- limit
149
- returned
150
- hasMore
151
- }
152
- partialResults
153
- sourceStatus {
154
- source
155
- targetLabel
156
- requestedTargetLabel
157
- freshTargetLabel
158
- servedTargetLabel
159
- ${TARGET_RESOLUTION_SELECTION}
160
- indexingStatus
161
- codeIndexState
162
- resultCount
163
- appliedFilters
164
- ignoredFilters
165
- incompatibleFilters
166
- appliedQueryFeatures
167
- ignoredQueryFeatures
168
- incompatibleQueryFeatures
169
- note
170
- ${DOC_COVERAGE_SELECTION}
171
- }
172
- }
173
- progress {
174
- searchRef
175
- status
176
- targetsTotal
177
- targetsReady
178
- elapsedMs
179
- query
180
- queryWarnings
181
- sources
182
- requestedSources
183
- targetMode
184
- requestedTargets {
185
- registry
186
- name
187
- version
188
- repoUrl
189
- gitRef
190
- site
191
- }
192
- filters {
193
- fileIntent
194
- kind
195
- category
196
- publicOnly
197
- pathPrefix
198
- }
199
- limit
200
- offset
201
- targets {
202
- requested
203
- resolvedRequested
204
- served
205
- freshness
206
- indexingRef
207
- requestedRefKind
208
- ${TARGET_RESOLUTION_SELECTION}
209
- ${DISCOVERY_TARGET_PROGRESS_RETRY_SELECTION}
210
- ${DOC_COVERAGE_SELECTION}
211
- }
212
- expiresAt
213
- }
214
- }
215
- }`;var UNIFIED_SEARCH_STATUS_QUERY=`
216
- query UnifiedSearchStatus($searchRef: String!, $includeResults: Boolean!, $waitTimeoutMs: Int) {
217
- discoverySearchProgress(searchRef: $searchRef, includeResults: $includeResults, waitTimeoutMs: $waitTimeoutMs) {
218
- searchRef
219
- status
220
- targetsTotal
221
- targetsReady
222
- elapsedMs
223
- query
224
- queryWarnings
225
- sources
226
- requestedSources
227
- targetMode
228
- requestedTargets {
229
- registry
230
- name
231
- version
232
- repoUrl
233
- gitRef
234
- site
235
- }
236
- filters {
237
- fileIntent
238
- kind
239
- category
240
- publicOnly
241
- pathPrefix
242
- }
243
- limit
244
- offset
245
- targets {
246
- requested
247
- resolvedRequested
248
- served
249
- freshness
250
- indexingRef
251
- requestedRefKind
252
- ${TARGET_RESOLUTION_SELECTION}
253
- ${DISCOVERY_TARGET_PROGRESS_RETRY_SELECTION}
254
- ${DOC_COVERAGE_SELECTION}
255
- }
256
- expiresAt
257
- results {
258
- query
259
- queryWarnings
260
- sources
261
- results {
262
- id
263
- resultType
264
- targetLabel
265
- requestedTargetLabel
266
- freshTargetLabel
267
- servedTargetLabel
268
- freshness
269
- title
270
- summary
271
- score
272
- highlights {
273
- title
274
- summary
275
- }
276
- locator {
277
- registry
278
- packageName
279
- version
280
- pageId
281
- sourceKind
282
- sourceUrl
283
- repoUrl
284
- gitRef
285
- requestedRef
286
- filePath
287
- startLine
288
- endLine
289
- fileContentHash
290
- symbolRef
291
- qualifiedPath
292
- kind
293
- category
294
- language
295
- }
296
- }
297
- page {
298
- offset
299
- limit
300
- returned
301
- hasMore
302
- }
303
- partialResults
304
- sourceStatus {
305
- source
306
- targetLabel
307
- requestedTargetLabel
308
- freshTargetLabel
309
- servedTargetLabel
310
- ${TARGET_RESOLUTION_SELECTION}
311
- indexingStatus
312
- codeIndexState
313
- resultCount
314
- appliedFilters
315
- ignoredFilters
316
- incompatibleFilters
317
- appliedQueryFeatures
318
- ignoredQueryFeatures
319
- incompatibleQueryFeatures
320
- note
321
- ${DOC_COVERAGE_SELECTION}
322
- }
323
- }
324
- }
325
- }`;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(),site:z2.string().nullable().optional()}).nullable().optional();var targetResolutionSchema=z2.object({requested:targetResolutionIdentitySchema,resolvedRequested:targetResolutionIdentitySchema,served:targetResolutionIdentitySchema,freshness:z2.string().nullable().optional(),freshnessReason:z2.string().nullable().optional(),indexingRef:z2.string().nullable().optional(),availableVersions:z2.array(availableVersionSchema).nullable().optional(),availableRefs:z2.array(availableVersionSchema).nullable().optional(),suggestedRefs:z2.array(availableVersionSchema).nullable().optional()}).nullable().optional();var unifiedSearchSourceSchema=z2.enum(["AUTO","DOCS","CODE","SYMBOL"]);var unifiedSearchResultTypeSchema=z2.enum(["DOCUMENTATION_PAGE","REPOSITORY_SYMBOL","REPOSITORY_CODE","REPOSITORY_DOC"]);var unifiedSearchLocatorSchema=z2.object({registry:z2.string().nullable().optional(),packageName:z2.string().nullable().optional(),version:z2.string().nullable().optional(),pageId:z2.string().nullable().optional(),sourceKind:z2.string().nullable().optional(),sourceUrl:z2.string().nullable().optional(),repoUrl:z2.string().nullable().optional(),gitRef:z2.string().nullable().optional(),requestedRef:z2.string().nullable().optional(),filePath:z2.string().nullable().optional(),startLine:z2.number().int().nullable().optional(),endLine:z2.number().int().nullable().optional(),fileContentHash:z2.string().nullable().optional(),symbolRef:z2.string().nullable().optional(),qualifiedPath:z2.string().nullable().optional(),kind:z2.string().nullable().optional(),category:z2.string().nullable().optional(),language:z2.string().nullable().optional()});var unifiedSearchHitSchema=z2.object({id:z2.string(),resultType:unifiedSearchResultTypeSchema,targetLabel:z2.string(),requestedTargetLabel:z2.string().nullable().optional(),freshTargetLabel:z2.string().nullable().optional(),servedTargetLabel:z2.string().nullable().optional(),freshness:z2.string().nullable().optional(),title:z2.string().nullable().optional(),summary:z2.string().nullable().optional(),score:z2.number().nullable().optional(),highlights:z2.object({title:z2.array(z2.tuple([z2.number().int(),z2.number().int()])).nullable().optional(),summary:z2.array(z2.tuple([z2.number().int(),z2.number().int()])).nullable().optional()}).nullable().optional(),locator:unifiedSearchLocatorSchema});var unifiedSearchPageInfoSchema=z2.object({offset:z2.number().int(),limit:z2.number().int(),returned:z2.number().int(),hasMore:z2.boolean()});var docCoverageSchema=z2.object({coverageState:z2.string(),coverageReason:z2.string().nullable().optional(),pagesCrawled:z2.number().int().nullable().optional(),frontierRemaining:z2.number().int().nullable().optional(),artifactOverflowPageCount:z2.number().int().nullable().optional(),estimatedTotalPages:z2.number().int().nullable().optional(),note:z2.string().nullable().optional()}).nullable().optional();var 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(),coverage:docCoverageSchema});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(),coverage:docCoverageSchema});var unifiedSearchRequestedTargetSchema=z2.object({registry:z2.string().nullable().optional(),name:z2.string().nullable().optional(),version:z2.string().nullable().optional(),repoUrl:z2.string().nullable().optional(),gitRef:z2.string().nullable().optional(),site:z2.string().nullable().optional()});var unifiedSearchProgressSchema=z2.object({searchRef:z2.string(),status:unifiedSearchSessionStatusSchema,targetsTotal:z2.number().int(),targetsReady:z2.number().int(),elapsedMs:z2.number().int(),query:z2.string(),queryWarnings:z2.array(z2.string()),sources:z2.array(unifiedSearchSourceSchema),requestedSources:z2.array(unifiedSearchSourceSchema).nullable().optional(),targetMode:z2.string().nullable().optional(),requestedTargets:z2.array(unifiedSearchRequestedTargetSchema).nullable().optional(),filters:unifiedSearchFiltersSchema,limit:z2.number().int().nullable().optional(),offset:z2.number().int().nullable().optional(),targets:z2.array(unifiedSearchProgressTargetSchema).nullable().optional(),expiresAt:z2.string().nullable().optional(),results:unifiedSearchResultSchema.nullable().optional()});var asyncUnifiedSearchResultSchema=z2.object({completed:z2.boolean(),searchRef:z2.string().nullable().optional(),result:unifiedSearchResultSchema.nullable().optional(),progress:unifiedSearchProgressSchema.nullable().optional()});var graphQLErrorSchema=z2.object({message:z2.string(),extensions:z2.record(z2.string(),z2.unknown()).optional()});var 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=`
326
- query ListRepoFiles(
327
- $registry: Registry
328
- $packageName: String
329
- $repoUrl: String
330
- $gitRef: String
331
- $version: String
332
- $pathPrefix: String
333
- $pathSelectors: [FilePathSelectorInput!]
334
- $extensions: [String!]
335
- $fileTypes: [String!]
336
- $languages: [String!]
337
- $fileIntent: FileIntent
338
- $fileIntents: [FileIntent!]
339
- $excludeFileIntents: [FileIntent!]
340
- $excludeDocFiles: Boolean
341
- $excludeTestFiles: Boolean
342
- $includeHidden: Boolean
343
- $limit: Int
344
- $waitTimeoutMs: Int
345
- ) {
346
- listRepoFiles(
347
- registry: $registry
348
- packageName: $packageName
349
- repoUrl: $repoUrl
350
- gitRef: $gitRef
351
- version: $version
352
- pathPrefix: $pathPrefix
353
- pathSelectors: $pathSelectors
354
- extensions: $extensions
355
- fileTypes: $fileTypes
356
- languages: $languages
357
- fileIntent: $fileIntent
358
- fileIntents: $fileIntents
359
- excludeFileIntents: $excludeFileIntents
360
- excludeDocFiles: $excludeDocFiles
361
- excludeTestFiles: $excludeTestFiles
362
- includeHidden: $includeHidden
363
- limit: $limit
364
- waitTimeoutMs: $waitTimeoutMs
365
- ) {
366
- files {
367
- path
368
- name
369
- language
370
- fileType
371
- byteSize
372
- }
373
- total
374
- hasMore
375
- indexedVersion
376
- resolution {
377
- requestedVersion
378
- requestedRef
379
- resolvedRef
380
- commitSha
381
- }
382
- ${TARGET_RESOLUTION_SELECTION}
383
- diagnostics {
384
- hint
385
- }
386
- codeIndexState
387
- indexingRef
388
- availableVersions {
389
- version
390
- ref
391
- }
392
- ${INDEXING_DURATION_ESTIMATE_SELECTION}
393
- }
394
- }`;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=`
395
- query FetchCodeContext(
396
- $registry: Registry
397
- $packageName: String
398
- $repoUrl: String
399
- $gitRef: String
400
- $version: String
401
- $filePath: String!
402
- $startLine: Int
403
- $endLine: Int
404
- $waitTimeoutMs: Int
405
- ) {
406
- fetchCodeContext(
407
- registry: $registry
408
- packageName: $packageName
409
- repoUrl: $repoUrl
410
- gitRef: $gitRef
411
- version: $version
412
- filePath: $filePath
413
- startLine: $startLine
414
- endLine: $endLine
415
- waitTimeoutMs: $waitTimeoutMs
416
- ) {
417
- content
418
- filePath
419
- language
420
- totalLines
421
- startLine
422
- endLine
423
- repoUrl
424
- gitRef
425
- isBinary
426
- codeIndexState
427
- indexingRef
428
- ${CODE_CONTEXT_AVAILABLE_VERSIONS_SELECTION}
429
- ${INDEXING_DURATION_ESTIMATE_SELECTION}
430
- ${TARGET_RESOLUTION_SELECTION}
431
- }
432
- }`;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(`
433
- `);const symbolBlock=symbolSelection.length>0?`
434
- symbol {
435
- ${symbolSelection}
436
- }`:"";return`
437
- query GrepRepo(
438
- $registry: Registry
439
- $packageName: String
440
- $repoUrl: String
441
- $gitRef: String
442
- $version: String
443
- $waitTimeoutMs: Int
444
- $pattern: String!
445
- $patternType: GrepPatternType
446
- $caseSensitive: Boolean
447
- $pathSelectors: [GrepPathSelectorInput!]
448
- $extensions: [String!]
449
- $excludeDocFiles: Boolean
450
- $excludeTestFiles: Boolean
451
- $allowUnscoped: Boolean
452
- $contextLinesBefore: Int
453
- $contextLinesAfter: Int
454
- $maxMatches: Int
455
- $maxMatchesPerFile: Int
456
- $cursor: String
457
- $symbolFields: [String!]
458
- ) {
459
- grepRepo(
460
- registry: $registry
461
- packageName: $packageName
462
- repoUrl: $repoUrl
463
- gitRef: $gitRef
464
- version: $version
465
- waitTimeoutMs: $waitTimeoutMs
466
- pattern: $pattern
467
- patternType: $patternType
468
- caseSensitive: $caseSensitive
469
- pathSelectors: $pathSelectors
470
- extensions: $extensions
471
- excludeDocFiles: $excludeDocFiles
472
- excludeTestFiles: $excludeTestFiles
473
- allowUnscoped: $allowUnscoped
474
- contextLinesBefore: $contextLinesBefore
475
- contextLinesAfter: $contextLinesAfter
476
- maxMatches: $maxMatches
477
- maxMatchesPerFile: $maxMatchesPerFile
478
- cursor: $cursor
479
- symbolFields: $symbolFields
480
- ) {
481
- matches {
482
- filePath
483
- line
484
- matchStartByte
485
- matchEndByte
486
- lineContent
487
- contextBefore
488
- contextAfter
489
- fileContentHash
490
- fileIntent
491
- symbolRowId${symbolBlock}
492
- }
493
- nextCursor
494
- totalMatches
495
- hasMore
496
- truncatedReason
497
- routeTaken
498
- filesScanned
499
- filesInScope
500
- binaryFilesSkipped
501
- filesTooLargeSkipped
502
- uniqueFilesMatched
503
- indexedVersion
504
- resolution {
505
- requestedVersion
506
- requestedRef
507
- resolvedRef
508
- commitSha
509
- }
510
- ${TARGET_RESOLUTION_SELECTION}
511
- codeIndexState
512
- indexingRef
513
- availableVersions {
514
- version
515
- ref
516
- }
517
- ${INDEXING_DURATION_ESTIMATE_SELECTION}
518
- }
519
- }`}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:isTokenRefreshableError,executeWithToken:(token)=>this.executeUnifiedSearch(token,params)})}async searchStatus(searchRef,waitTimeoutMs=0){return executeWithTokenRefresh({getToken:()=>this.tokenProvider.getToken(),forceRefresh:()=>this.tokenProvider.forceRefresh(),shouldRefresh:isTokenRefreshableError,executeWithToken:(token)=>this.executeUnifiedSearchStatus(token,searchRef,waitTimeoutMs)})}async executeUnifiedSearch(token,params){if(params.targets.length===0){throw new CodeNavigationValidationError("At least one search target is required.")}let response;const variables={targets:params.targets.map((target)=>({registry:target.registry,name:target.packageName,version:target.version,repoUrl:target.repoUrl,gitRef:target.gitRef,site:target.site})),query:params.query,sources:params.sources,filters:params.filters,allowPartialResults:params.allowPartialResults??false,limit:params.limit,offset:params.offset,waitTimeoutMs:params.waitTimeoutMs};debugUnifiedSearchRequest(variables);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,waitTimeoutMs){let response;try{response=await this.postGraphqlWithTargetResolutionFallback({token,query:UNIFIED_SEARCH_STATUS_QUERY,variables:{searchRef,includeResults:true,waitTimeoutMs}})}catch(cause){if(cause instanceof PkgseerTransportError){throw this.createTransportError(cause)}throw cause}if(response.status<200||response.status>=300){throw this.createHttpError(response)}const parsed=unifiedSearchStatusGraphQLResponseSchema.safeParse(response.parsedBody);if(!parsed.success){throw new MalformedCodeNavigationResponseError("Malformed response from code navigation service.")}if(parsed.data.errors&&parsed.data.errors.length>0){throw this.createGraphQLError(parsed.data.errors)}const data=parsed.data.data?.discoverySearchProgress;if(!data){throw new MalformedCodeNavigationResponseError("Malformed response from code navigation service.")}const progress=this.normaliseUnifiedSearchProgress(data);const result=data.results?this.normaliseUnifiedSearchResult(data.results):undefined;if(result&&progress.status==="COMPLETED"){return{state:"completed",completed:true,searchRef:progress.searchRef,result,progress}}return{state:"incomplete",completed:false,searchRef:progress.searchRef,result,progress}}createHttpError(response){const status=response.status;const detail=parseDetail(response.responseBody);if(status===401){return new AuthenticationError(SERVER_AUTHENTICATION_REJECTED_MESSAGE,"server")}if(status===403){return new CodeNavigationAccessError(detail??"Code navigation access denied.")}if(status>=500){return new CodeNavigationBackendError(detail?`Server error (${status}): ${detail}`:`Server error (${status})`,status)}return new CodeNavigationBackendError(detail??`Request failed with status ${status}`,status)}createTransportError(error){if(isFetchTimeoutError(error.cause)){return new CodeNavigationBackendError("Code navigation request timed out.",undefined,"TIMEOUT",true)}return new CodeNavigationNetworkError("Could not reach the code navigation service. Check your connection or set GITHITS_CODE_NAV_URL.",{cause:error})}createGraphQLError(errors){const message=errors.map((error)=>error.message).join(", ");const extensions=getPrimaryExtensions(errors);const code=typeof extensions?.code==="string"?extensions.code:undefined;const retryable=typeof extensions?.retryable==="boolean"?extensions.retryable:undefined;const indexingRef=getGraphQLIndexingRef(errors);const indexingEstimate=parseIndexingDurationEstimate(extensions);const errorMetadata=parseGraphQLErrorMetadata(extensions,indexingEstimate);if(isClientUpdateRequiredGraphQLError({message,code})){return new ClientUpdateRequiredError(undefined,undefined,this.runtime.clientVersion)}if(isGraphQLSchemaMismatchError({message,code})){const sanitized="Backend protocol mismatch. Your CLI may be newer than the server, or the server may require a newer CLI. Run `githits update-check` to verify your installed version. Set GITHITS_DEBUG=code-nav-wire to inspect GraphQL details during local development.";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(message,indexingRef,parseAvailableVersions(extensions),parseAvailableRefs(extensions),parseTargetResolution(extensions),indexingEstimate,appendIndexingWaitHint(message,typeof extensions?.hint==="string"?extensions.hint:undefined));case"GREP_PATTERN_TOO_SHORT":case"GREP_PATTERN_TOO_LONG":case"GREP_PATTERN_INVALID":case"GREP_INVALID_REGEX":case"GREP_UNSUPPORTED_PATTERN":case"GREP_PATTERN_TOO_UNSELECTIVE":case"GREP_SCOPE_REQUIRED":case"GREP_SELECTOR_INVALID":case"GREP_CURSOR_INVALID":case"GREP_CONTEXT_TOO_LARGE":case"GREP_CONTEXT_NEGATIVE":case"GREP_MAX_MATCHES_TOO_LARGE":case"GREP_MAX_MATCHES_INVALID":return new CodeNavigationValidationError(message);case"VERSION_NOT_FOUND":return new CodeNavigationVersionNotFoundError(message,typeof extensions?.package==="string"?extensions.package:undefined,typeof extensions?.requested_version==="string"?extensions.requested_version:undefined,typeof extensions?.latest_indexed==="string"?extensions.latest_indexed:undefined,parseAvailableVersions(extensions),errorMetadata);case"REF_NOT_FOUND":return new CodeNavigationRefNotFoundError(message,parseGraphQLRepoUrl(extensions),parseGraphQLGitRef(extensions),parseAvailableRefs(extensions),parseSuggestedRefs(extensions),errorMetadata);case"NOT_FOUND":case"PACKAGE_NOT_FOUND":case"NO_REPOSITORY_URL":return new CodeNavigationTargetNotFoundError(message,parseAvailableVersions(extensions),parseGraphQLRepoUrl(extensions),parseGraphQLGitRef(extensions),errorMetadata);case"REPOSITORY_NOT_FOUND":return new CodeNavigationTargetNotFoundError(message,undefined,parseGraphQLRepoUrl(extensions),parseGraphQLGitRef(extensions),errorMetadata);case"FILE_NOT_FOUND":return new CodeNavigationFileNotFoundError(message,typeof extensions?.file_path==="string"?extensions.file_path:typeof extensions?.filePath==="string"?extensions.filePath:undefined);case"UNSUPPORTED_REGISTRY":case"VALIDATION_ERROR":return new CodeNavigationValidationError(message);case"FEATURE_FLAG_REQUIRED":return new CodeNavigationFeatureFlagRequiredError(message);case"UNAUTHORIZED":return new AuthenticationError(SERVER_AUTHENTICATION_REJECTED_MESSAGE,"server");case"FORBIDDEN":return new CodeNavigationAccessError("Code navigation access denied. This feature may not be enabled for your account.");case"UPSTREAM_ERROR":case"TIMEOUT":case"RATE_LIMITED":case"GREP_FILE_TOO_LARGE":case"GREP_TIMEOUT":case"GREP_SERVICE_UNAVAILABLE":case"GREP_FAILED":case"GREP_INDEX_NOT_AVAILABLE":case"INTERNAL_ERROR":case"UNKNOWN_ERROR":return new CodeNavigationBackendError(message,undefined,code,retryable,errorMetadata);default:break}if(code===undefined){if(isAuthMessage(message)){return new CodeNavigationAccessError("Code navigation access denied. This feature may not be enabled for your account.")}if(isUnresolvableMessage(message)){return new CodeNavigationUnresolvableError(message)}if(isTargetNotFoundMessage(message)){return new CodeNavigationTargetNotFoundError(message,parseAvailableVersions(extensions),parseGraphQLRepoUrl(extensions),parseGraphQLGitRef(extensions),errorMetadata)}}return new CodeNavigationBackendError(message,undefined,code,retryable,errorMetadata)}normaliseUnifiedSearchOutcome(data){const progress=data.progress?this.normaliseUnifiedSearchProgress(data.progress):undefined;if(data.completed){if(!data.result){throw new MalformedCodeNavigationResponseError("Completed unified search response missing result payload.")}return{state:"completed",completed:true,searchRef:data.searchRef??undefined,result:this.normaliseUnifiedSearchResult(data.result),progress}}const searchRef=data.searchRef??progress?.searchRef;if(!searchRef){throw new MalformedCodeNavigationResponseError("Incomplete unified search response missing search reference.")}const result=data.result?this.normaliseUnifiedSearchResult(data.result):undefined;return{state:"incomplete",completed:false,searchRef,result,progress}}normaliseUnifiedSearchResult(result){return{query:result.query,queryWarnings:result.queryWarnings,sources:result.sources,results:result.results.map((entry)=>({id:entry.id,resultType:entry.resultType,targetLabel:entry.targetLabel,requestedTargetLabel:entry.requestedTargetLabel??undefined,freshTargetLabel:entry.freshTargetLabel??undefined,servedTargetLabel:entry.servedTargetLabel??undefined,freshness:entry.freshness??undefined,title:entry.title??undefined,summary:entry.summary??undefined,score:entry.score??undefined,highlights:entry.highlights?{title:entry.highlights.title??undefined,summary:entry.highlights.summary??undefined}:undefined,locator:{registry:entry.locator.registry??undefined,packageName:entry.locator.packageName??undefined,version:entry.locator.version??undefined,pageId:entry.locator.pageId??undefined,sourceKind:entry.locator.sourceKind??undefined,sourceUrl:entry.locator.sourceUrl??undefined,repoUrl:entry.locator.repoUrl??undefined,gitRef:entry.locator.gitRef??undefined,requestedRef:entry.locator.requestedRef??undefined,filePath:entry.locator.filePath??undefined,startLine:entry.locator.startLine??undefined,endLine:entry.locator.endLine??undefined,fileContentHash:entry.locator.fileContentHash??undefined,symbolRef:entry.locator.symbolRef??undefined,qualifiedPath:entry.locator.qualifiedPath??undefined,kind:entry.locator.kind??undefined,category:entry.locator.category??undefined,language:entry.locator.language??undefined}})),page:{offset:result.page.offset,limit:result.page.limit,returned:result.page.returned,hasMore:result.page.hasMore},partialResults:result.partialResults,sourceStatus:result.sourceStatus.map((entry)=>({source:entry.source,targetLabel:entry.targetLabel,requestedTargetLabel:entry.requestedTargetLabel??undefined,freshTargetLabel:entry.freshTargetLabel??undefined,servedTargetLabel:entry.servedTargetLabel??undefined,targetResolution:normaliseTargetResolution(entry.targetResolution),indexingStatus:entry.indexingStatus??undefined,codeIndexState:entry.codeIndexState??undefined,resultCount:entry.resultCount??undefined,appliedFilters:entry.appliedFilters,ignoredFilters:entry.ignoredFilters,incompatibleFilters:entry.incompatibleFilters,appliedQueryFeatures:entry.appliedQueryFeatures,ignoredQueryFeatures:entry.ignoredQueryFeatures,incompatibleQueryFeatures:entry.incompatibleQueryFeatures,note:entry.note??undefined,coverage:normaliseDocCoverage(entry.coverage)}))}}normaliseUnifiedSearchProgress(progress){return{searchRef:progress.searchRef,status:progress.status,targetsTotal:progress.targetsTotal,targetsReady:progress.targetsReady,elapsedMs:progress.elapsedMs,query:progress.query,queryWarnings:progress.queryWarnings,sources:progress.sources,requestedSources:progress.requestedSources??undefined,targetMode:normaliseTargetMode(progress.targetMode),requestedTargets:progress.requestedTargets?.map((target)=>({registry:target.registry?target.registry:undefined,name:target.name??undefined,version:target.version??undefined,repoUrl:target.repoUrl??undefined,gitRef:target.gitRef??undefined,site:target.site??undefined})),filters:normaliseProgressFilters(progress.filters),limit:progress.limit??undefined,offset:progress.offset??undefined,targets:progress.targets?.map((target)=>({requested:target.requested??undefined,resolvedRequested:target.resolvedRequested??undefined,served:target.served??undefined,freshness:target.freshness??undefined,indexingRef:target.indexingRef??undefined,requestedRefKind:normaliseRequestedRefKind(target.requestedRefKind),targetResolution:normaliseTargetResolution(target.targetResolution),availableVersions:normaliseAvailableVersions(target.availableVersions),availableRefs:normaliseAvailableVersions(target.availableRefs),suggestedRefs:normaliseAvailableVersions(target.suggestedRefs),coverage:normaliseDocCoverage(target.coverage)})),expiresAt:progress.expiresAt??undefined}}throwIfIndexing(data){if(data.codeIndexState==="INDEXING"){const targetResolution=normaliseTargetResolution(data.targetResolution);const indexingEstimate=normaliseIndexingDurationEstimate(data.indexingEstimate);throw new CodeNavigationIndexingError(`Target is indexing. ${INDEXING_WAIT_HINT}`,data.indexingRef??targetResolution?.indexingRef,normaliseAvailableVersions(data.availableVersions)??targetResolution?.availableVersions,targetResolution?.availableRefs,targetResolution,indexingEstimate)}}async listFiles(params){return executeWithTokenRefresh({getToken:()=>this.tokenProvider.getToken(),forceRefresh:()=>this.tokenProvider.forceRefresh(),shouldRefresh:isTokenRefreshableError,executeWithToken:(token)=>this.executeListFiles(token,params)})}async executeListFiles(token,params){let response;try{response=await this.postGraphqlWithTargetResolutionFallback({token,query:LIST_REPO_FILES_QUERY,variables:{registry:params.target.registry,packageName:params.target.packageName,repoUrl:params.target.repoUrl,gitRef:params.target.gitRef,version:params.target.version,pathPrefix:params.pathPrefix,pathSelectors:params.pathSelectors?.map((entry)=>({kind:entry.kind,value:entry.value})),extensions:params.extensions,fileTypes:params.fileTypes,languages:params.languages,fileIntent:params.fileIntent,fileIntents:params.fileIntents,excludeFileIntents:params.excludeFileIntents,excludeDocFiles:params.excludeDocFiles,excludeTestFiles:params.excludeTestFiles,includeHidden:params.includeHidden,limit:params.limit,waitTimeoutMs:params.waitTimeoutMs}})}catch(cause){if(cause instanceof PkgseerTransportError){throw this.createTransportError(cause)}throw cause}if(response.status<200||response.status>=300){throw this.createHttpError(response)}const parsed=listRepoFilesGraphQLResponseSchema.safeParse(response.parsedBody);if(!parsed.success){throw new MalformedCodeNavigationResponseError("Malformed response from code navigation service.")}if(parsed.data.errors&&parsed.data.errors.length>0){throw this.createGraphQLError(parsed.data.errors)}const data=parsed.data.data?.listRepoFiles;if(!data){throw new MalformedCodeNavigationResponseError("Malformed response from code navigation service.")}this.throwIfIndexing(data);return{files:data.files.map((entry)=>({path:entry.path,name:entry.name??undefined,language:entry.language??undefined,fileType:entry.fileType??undefined,byteSize:entry.byteSize??undefined})),total:data.total,hasMore:data.hasMore,indexedVersion:data.indexedVersion??undefined,resolution:data.resolution?{requestedVersion:data.resolution.requestedVersion??undefined,requestedRef:data.resolution.requestedRef??undefined,resolvedRef:data.resolution.resolvedRef??undefined,commitSha:data.resolution.commitSha??undefined}:undefined,targetResolution:normaliseTargetResolution(data.targetResolution),hint:data.diagnostics?.hint??undefined}}async readFile(params){return executeWithTokenRefresh({getToken:()=>this.tokenProvider.getToken(),forceRefresh:()=>this.tokenProvider.forceRefresh(),shouldRefresh:isTokenRefreshableError,executeWithToken:(token)=>this.executeReadFile(token,params)})}async executeReadFile(token,params){let response;try{response=await this.postGraphqlWithTargetResolutionFallback({token,query:FETCH_CODE_CONTEXT_QUERY,variables:{registry:params.target.registry,packageName:params.target.packageName,repoUrl:params.target.repoUrl,gitRef:params.target.gitRef,version:params.target.version,filePath:params.filePath,startLine:params.startLine,endLine:params.endLine,waitTimeoutMs:params.waitTimeoutMs}})}catch(cause){if(cause instanceof PkgseerTransportError){throw this.createTransportError(cause)}throw cause}if(response.status<200||response.status>=300){throw this.createHttpError(response)}const parsed=fetchCodeContextGraphQLResponseSchema.safeParse(response.parsedBody);if(!parsed.success){throw new MalformedCodeNavigationResponseError("Malformed response from code navigation service.")}if(parsed.data.errors&&parsed.data.errors.length>0){throw this.createGraphQLError(parsed.data.errors)}const data=parsed.data.data?.fetchCodeContext;if(!data){throw new MalformedCodeNavigationResponseError("Malformed response from code navigation service.")}this.throwIfIndexing(data);return{filePath:data.filePath??undefined,language:data.language??undefined,totalLines:data.totalLines??undefined,startLine:data.startLine??undefined,endLine:data.endLine??undefined,content:data.content??undefined,isBinary:data.isBinary??undefined,targetResolution:normaliseTargetResolution(data.targetResolution),availableVersions:normaliseAvailableVersions(data.availableVersions)}}async grepRepo(params){return executeWithTokenRefresh({getToken:()=>this.tokenProvider.getToken(),forceRefresh:()=>this.tokenProvider.forceRefresh(),shouldRefresh:isTokenRefreshableError,executeWithToken:(token)=>this.executeGrepRepo(token,params)})}async executeGrepRepo(token,params){let response;try{response=await this.postGraphqlWithTargetResolutionFallback({token,query:buildGrepRepoQuery(params.symbolFields),variables:{registry:params.target.registry,packageName:params.target.packageName,repoUrl:params.target.repoUrl,gitRef:params.target.gitRef,version:params.target.version,waitTimeoutMs:params.waitTimeoutMs,pattern:params.pattern,patternType:params.patternType,caseSensitive:params.caseSensitive,pathSelectors:params.pathSelectors?.map((entry)=>({kind:entry.kind,value:entry.value})),extensions:params.extensions,excludeDocFiles:params.excludeDocFiles,excludeTestFiles:params.excludeTestFiles,allowUnscoped:params.allowUnscoped,contextLinesBefore:params.contextLinesBefore,contextLinesAfter:params.contextLinesAfter,maxMatches:params.maxMatches,maxMatchesPerFile:params.maxMatchesPerFile,cursor:params.cursor,symbolFields:params.symbolFields}})}catch(cause){if(cause instanceof PkgseerTransportError){throw this.createTransportError(cause)}throw cause}if(response.status<200||response.status>=300){throw this.createHttpError(response)}const parsed=grepRepoGraphQLResponseSchema.safeParse(response.parsedBody);if(!parsed.success){throw new MalformedCodeNavigationResponseError("Malformed response from code navigation service.")}if(parsed.data.errors&&parsed.data.errors.length>0){throw this.createGraphQLError(parsed.data.errors)}const data=parsed.data.data?.grepRepo;if(!data){throw new MalformedCodeNavigationResponseError("Malformed response from code navigation service.")}this.throwIfIndexing(data);return{matches:data.matches.map((entry)=>({filePath:entry.filePath,line:entry.line,matchStartByte:entry.matchStartByte,matchEndByte:entry.matchEndByte,lineContent:entry.lineContent,contextBefore:entry.contextBefore??undefined,contextAfter:entry.contextAfter??undefined,fileContentHash:entry.fileContentHash??undefined,fileIntent:entry.fileIntent??undefined,symbolRowId:entry.symbolRowId??undefined,symbol:entry.symbol?{symbolRef:entry.symbol.symbolRef,name:entry.symbol.name,qualifiedPath:entry.symbol.qualifiedPath??undefined,kind:entry.symbol.kind??undefined,category:entry.symbol.category??undefined,arity:entry.symbol.arity??undefined,isPublic:entry.symbol.isPublic??undefined,filePath:entry.symbol.filePath??undefined,startLine:entry.symbol.startLine??undefined,endLine:entry.symbol.endLine??undefined,code:entry.symbol.code??undefined,callerCount:entry.symbol.callerCount??undefined,contentHash:entry.symbol.contentHash??undefined,parentSymbolRef:entry.symbol.parentSymbolRef??undefined,parentPath:entry.symbol.parentPath??undefined}:undefined})),nextCursor:data.nextCursor??undefined,hasMore:data.hasMore,truncatedReason:data.truncatedReason,routeTaken:data.routeTaken??undefined,filesScanned:data.filesScanned,filesInScope:data.filesInScope,binaryFilesSkipped:data.binaryFilesSkipped,filesTooLargeSkipped:data.filesTooLargeSkipped,totalMatches:data.totalMatches,uniqueFilesMatched:data.uniqueFilesMatched,indexedVersion:data.indexedVersion??undefined,resolution:data.resolution?{requestedVersion:data.resolution.requestedVersion??undefined,requestedRef:data.resolution.requestedRef??undefined,resolvedRef:data.resolution.resolvedRef??undefined,commitSha:data.resolution.commitSha??undefined}:undefined,targetResolution:normaliseTargetResolution(data.targetResolution)}}}function parseDetail(body){if(!body)return;try{const parsed=JSON.parse(body);if(typeof parsed.detail==="string")return parsed.detail;if(typeof parsed.error==="string")return parsed.error}catch{return body}return}function buildTargetResolutionFallbackQueries(query){const withoutSuggestedRefs=query.replaceAll(TARGET_RESOLUTION_SUGGESTED_REFS_SELECTION,"").replaceAll(DISCOVERY_TARGET_PROGRESS_SUGGESTED_REFS_SELECTION,"");const candidates=[withoutSuggestedRefs,withoutSuggestedRefs.replaceAll(TARGET_RESOLUTION_AVAILABLE_REFS_SELECTION,""),withoutSuggestedRefs.replaceAll(DISCOVERY_TARGET_PROGRESS_RETRY_SELECTION,""),withoutSuggestedRefs.replaceAll(CODE_CONTEXT_AVAILABLE_VERSIONS_SELECTION,""),withoutSuggestedRefs.replaceAll(TARGET_RESOLUTION_SELECTION,"").replaceAll(DISCOVERY_TARGET_PROGRESS_RETRY_SELECTION,"").replaceAll(CODE_CONTEXT_AVAILABLE_VERSIONS_SELECTION,"")];return candidates.filter((candidate,index,all)=>candidate!==query&&all.indexOf(candidate)===index)}function hasSchemaMismatchErrors(parsedBody){if(!parsedBody||typeof parsedBody!=="object")return false;const errors=parsedBody.errors;if(!Array.isArray(errors))return false;return errors.some((entry)=>{if(!entry||typeof entry!=="object")return false;const error=entry;if(typeof error.message!=="string")return false;const code=typeof error.extensions?.code==="string"?error.extensions.code:undefined;return isGraphQLSchemaMismatchError({message:error.message,code})})}function getPrimaryExtensions(errors){for(const error of errors){if(error.extensions&&Object.keys(error.extensions).length>0){return error.extensions}}return}function getGraphQLIndexingRef(errors){for(const error of errors){const indexingRef=error.extensions?.indexing_ref??error.extensions?.indexingRef;if(typeof indexingRef==="string")return indexingRef}return}function parseAvailableVersions(extensions){const raw=extensions?.available_versions??extensions?.availableVersions;return parseAvailableArtifacts(raw)}function parseAvailableRefs(extensions){const raw=extensions?.available_refs??extensions?.availableRefs;return parseAvailableArtifacts(raw)}function parseSuggestedRefs(extensions){const raw=extensions?.suggested_refs??extensions?.suggestedRefs;return parseAvailableArtifacts(raw)}function parseGraphQLErrorMetadata(extensions,indexingEstimate){const metadata={};if(typeof extensions?.hint==="string")metadata.hint=extensions.hint;const availableVersions=parseAvailableVersions(extensions);if(availableVersions?.length)metadata.availableVersions=availableVersions;const availableRefs=parseAvailableRefs(extensions);if(availableRefs?.length)metadata.availableRefs=availableRefs;const suggestedRefs=parseSuggestedRefs(extensions);if(suggestedRefs?.length)metadata.suggestedRefs=suggestedRefs;const targetResolution=parseTargetResolution(extensions);if(targetResolution)metadata.targetResolution=targetResolution;if(indexingEstimate)metadata.indexingEstimate=indexingEstimate;return Object.keys(metadata).length>0?metadata:undefined}function parseGraphQLRepoUrl(extensions){return typeof extensions?.repo_url==="string"?extensions.repo_url:typeof extensions?.repoUrl==="string"?extensions.repoUrl:undefined}function parseGraphQLGitRef(extensions){return typeof extensions?.git_ref==="string"?extensions.git_ref:typeof extensions?.gitRef==="string"?extensions.gitRef:undefined}function parseTargetResolution(extensions){const raw=extensions?.target_resolution??extensions?.targetResolution;const parsed=targetResolutionSchema.safeParse(raw);if(!parsed.success)return;return normaliseTargetResolution(parsed.data)}function parseIndexingDurationEstimate(extensions){const raw=extensions?.estimated_indexing_duration??extensions?.estimatedIndexingDuration??extensions?.indexing_estimate??extensions?.indexingEstimate;const parsed=indexingDurationEstimateSchema.safeParse(normaliseRawIndexingDurationEstimate(raw));if(!parsed.success)return;return normaliseIndexingDurationEstimate(parsed.data)}function normaliseRawIndexingDurationEstimate(raw){if(!raw||typeof raw!=="object"||Array.isArray(raw))return raw;const record=raw;return{lowerSeconds:record.lowerSeconds??record.lower_seconds,upperSeconds:record.upperSeconds??record.upper_seconds,elapsedSeconds:record.elapsedSeconds??record.elapsed_seconds,sampleCount:record.sampleCount??record.sample_count,source:record.source}}function normaliseIndexingDurationEstimate(estimate){if(!estimate)return;const out={};if(typeof estimate.lowerSeconds==="number"){out.lowerSeconds=estimate.lowerSeconds}if(typeof estimate.upperSeconds==="number"){out.upperSeconds=estimate.upperSeconds}if(typeof estimate.elapsedSeconds==="number"){out.elapsedSeconds=estimate.elapsedSeconds}if(typeof estimate.sampleCount==="number"){out.sampleCount=estimate.sampleCount}if(typeof estimate.source==="string")out.source=estimate.source;return Object.keys(out).length>0?out:undefined}function appendIndexingWaitHint(message,backendHint){const hintAlreadyInMessage=Boolean(backendHint&&message.includes(backendHint));const existingGuidance=`${message} ${backendHint??""}`;if(/(?:--wait\b|wait_timeout_ms|waitTimeoutMs)/i.test(existingGuidance)){return hintAlreadyInMessage?undefined:backendHint}return backendHint&&!hintAlreadyInMessage?`${backendHint} ${INDEXING_WAIT_HINT}`:INDEXING_WAIT_HINT}function parseAvailableArtifacts(raw){if(!Array.isArray(raw))return;const parsed=[];for(const item of raw){if(item&&typeof item==="object"&&"ref"in item){const entry=item;if(typeof entry.ref==="string"){parsed.push({ref:entry.ref,version:typeof entry.version==="string"?entry.version:undefined})}}}return parsed.length>0?parsed:undefined}function normaliseAvailableVersions(entries){if(!entries||entries.length===0)return;return entries.map((entry)=>({version:entry.version??undefined,ref:entry.ref}))}function normaliseTargetResolution(resolution){if(!resolution)return;return{requested:normaliseTargetResolutionIdentity(resolution.requested),resolvedRequested:normaliseTargetResolutionIdentity(resolution.resolvedRequested),served:normaliseTargetResolutionIdentity(resolution.served),freshness:resolution.freshness??undefined,freshnessReason:resolution.freshnessReason??undefined,indexingRef:resolution.indexingRef??undefined,availableVersions:normaliseAvailableVersions(resolution.availableVersions)??[],availableRefs:normaliseAvailableVersions(resolution.availableRefs)??[],suggestedRefs:normaliseAvailableVersions(resolution.suggestedRefs)??[]}}function normaliseDocCoverage(coverage){if(!coverage)return;if(coverage.coverageState==="NONE")return;const out={coverageState:coverage.coverageState};if(coverage.coverageReason)out.coverageReason=coverage.coverageReason;if(typeof coverage.pagesCrawled==="number"){out.pagesCrawled=coverage.pagesCrawled}if(typeof coverage.frontierRemaining==="number"){out.frontierRemaining=coverage.frontierRemaining}if(typeof coverage.artifactOverflowPageCount==="number"){out.artifactOverflowPageCount=coverage.artifactOverflowPageCount}if(typeof coverage.estimatedTotalPages==="number"){out.estimatedTotalPages=coverage.estimatedTotalPages}if(coverage.note)out.note=coverage.note;return out}function normaliseTargetResolutionIdentity(identity){if(!identity)return;const out={};if(identity.kind)out.kind=identity.kind;if(identity.registry)out.registry=identity.registry;if(identity.packageName)out.packageName=identity.packageName;if(identity.version)out.version=identity.version;if(identity.repoUrl)out.repoUrl=identity.repoUrl;if(identity.gitRef)out.gitRef=identity.gitRef;if(identity.commitSha)out.commitSha=identity.commitSha;if(identity.site)out.site=identity.site;return Object.keys(out).length>0?out:undefined}function isAuthMessage(message){const lower=message.toLowerCase();return lower.includes("unauthorized")||lower.includes("forbidden")||lower.includes("permission")||lower.includes("authentication")}function normaliseTargetMode(value){if(value==="PACKAGES"||value==="REPO"||value==="MIXED"||value==="SITES"||value==="SITE"){return value}return}function normaliseRequestedRefKind(value){switch(value){case"OMITTED_VERSION":case"LATEST_VERSION":case"EXACT_VERSION":case"DEFAULT_BRANCH":case"HEAD":case"BRANCH":case"SHA":return value;default:return}}function normaliseProgressFilters(filters){if(!filters)return;const out={};if(filters.fileIntent)out.fileIntent=filters.fileIntent;if(filters.kind)out.kind=filters.kind;if(filters.category)out.category=filters.category;if(typeof filters.publicOnly==="boolean"){out.publicOnly=filters.publicOnly}if(filters.pathPrefix)out.pathPrefix=filters.pathPrefix;return Object.keys(out).length>0?out:undefined}function isTargetNotFoundMessage(message){const lower=message.toLowerCase();return lower.includes("not found")||lower.includes("unknown package")||lower.includes("no such package")||lower.includes("does not exist")}function isUnresolvableMessage(message){const lower=message.toLowerCase();return lower.includes("could not resolve")||lower.includes("cannot resolve")}import{z as z3}from"zod";function promoteGenericVersionNotFound(error,params){if(!(error instanceof PackageIntelligenceBackendError))return error;if(error.graphqlCode!==undefined)return error;const requestedVersion=pickRequestedVersion(params);if(!requestedVersion)return error;if(!/no matching version/i.test(error.message))return error;const qualifiedName=synthesizeQualifiedName(params);return new PackageIntelligenceVersionNotFoundError(error.message,qualifiedName,requestedVersion,undefined)}function pickRequestedVersion(params){if(params.version)return params.version;if(params.fromVersion)return params.fromVersion;if(params.toVersion)return params.toVersion;return}function synthesizeQualifiedName(params){if(!params.registry||!params.packageName)return;return`${params.registry.toLowerCase()}:${params.packageName}`}class PackageIntelligenceAccessError extends Error{constructor(message){super(message);this.name="PackageIntelligenceAccessError"}}class PackageIntelligenceFeatureFlagRequiredError extends Error{constructor(message){super(message);this.name="PackageIntelligenceFeatureFlagRequiredError"}}class PackageIntelligenceNetworkError extends Error{constructor(message,options){super(message,options);this.name="PackageIntelligenceNetworkError"}}class PackageIntelligenceBackendError extends Error{status;graphqlCode;retryable;constructor(message,status,graphqlCode,retryable){super(message);this.status=status;this.graphqlCode=graphqlCode;this.retryable=retryable;this.name="PackageIntelligenceBackendError"}}class PackageIntelligenceGraphQLError extends Error{code;constructor(message,code){super(message);this.code=code;this.name="PackageIntelligenceGraphQLError"}}class PackageIntelligenceTargetNotFoundError extends Error{constructor(message){super(message);this.name="PackageIntelligenceTargetNotFoundError"}}class PackageIntelligenceValidationError extends Error{constructor(message){super(message);this.name="PackageIntelligenceValidationError"}}class PackageIntelligenceVersionNotFoundError extends Error{packageName;requestedVersion;availableVersions;constructor(message,packageName,requestedVersion,availableVersions){super(message);this.packageName=packageName;this.requestedVersion=requestedVersion;this.availableVersions=availableVersions;this.name="PackageIntelligenceVersionNotFoundError"}}class MalformedPackageIntelligenceResponseError extends Error{constructor(message){super(message);this.name="MalformedPackageIntelligenceResponseError"}}class PackageIntelligenceChangelogSourceNotFoundError extends Error{constructor(message){super(message);this.name="PackageIntelligenceChangelogSourceNotFoundError"}}var githubRepositorySchema=z3.object({stargazersCount:z3.number().int().nullable().optional(),forksCount:z3.number().int().nullable().optional(),openIssuesCount:z3.number().int().nullable().optional(),archived:z3.boolean().nullable().optional(),language:z3.string().nullable().optional(),topics:z3.array(z3.string()).nullable().optional(),pushedAt:z3.string().nullable().optional()}).nullable().optional();var packageIdentitySchema=z3.object({name:z3.string().nullable().optional(),registry:z3.string().nullable().optional(),description:z3.string().nullable().optional(),latestVersion:z3.string().nullable().optional(),latestVersionPublishedAt:z3.string().nullable().optional(),homepage:z3.string().nullable().optional(),repositoryUrl:z3.string().nullable().optional(),license:z3.string().nullable().optional(),downloadsLastMonth:z3.number().int().nullable().optional(),downloadsTotal:z3.number().int().nullable().optional(),githubRepository:githubRepositorySchema});var vulnerabilityOverviewSchema=z3.object({osvId:z3.string().nullable().optional(),summary:z3.string().nullable().optional(),severityScore:z3.number().nullable().optional(),publishedAt:z3.string().nullable().optional()});var packageSecurityOverviewSchema=z3.object({vulnerabilityCount:z3.number().int().nullable().optional(),hasCurrentVulnerabilities:z3.boolean().nullable().optional(),recentVulnerabilities:z3.array(vulnerabilityOverviewSchema).nullable().optional()}).nullable().optional();var changelogEntrySchema=z3.object({version:z3.string().nullable().optional(),publishedAt:z3.string().nullable().optional(),body:z3.string().nullable().optional()});var packageSummaryResponseSchema=z3.object({package:packageIdentitySchema.nullable().optional(),security:packageSecurityOverviewSchema,latestChangelogs:z3.array(changelogEntrySchema).nullable().optional()});var graphQLErrorSchema2=z3.object({message:z3.string(),extensions:z3.record(z3.string(),z3.unknown()).optional()});var graphQLResponseSchema=z3.object({data:z3.object({packageSummary:packageSummaryResponseSchema.nullable().optional()}).nullable().optional(),errors:z3.array(graphQLErrorSchema2).optional()});var PACKAGE_SUMMARY_QUERY=`
520
- query PackageSummary(
521
- $registry: Registry!
522
- $name: String!
523
- $includeVerboseFields: Boolean! = true
524
- ) {
525
- packageSummary(registry: $registry, name: $name) {
526
- package {
527
- name
528
- registry
529
- description
530
- latestVersion
531
- latestVersionPublishedAt
532
- homepage
533
- repositoryUrl
534
- license
535
- downloadsLastMonth
536
- downloadsTotal
537
- githubRepository {
538
- stargazersCount
539
- forksCount
540
- openIssuesCount
541
- archived
542
- language @include(if: $includeVerboseFields)
543
- topics @include(if: $includeVerboseFields)
544
- pushedAt @include(if: $includeVerboseFields)
545
- }
546
- }
547
- security {
548
- vulnerabilityCount
549
- hasCurrentVulnerabilities
550
- recentVulnerabilities @include(if: $includeVerboseFields) {
551
- osvId
552
- summary
553
- severityScore
554
- publishedAt
555
- }
556
- }
557
- latestChangelogs(limit: 3) @include(if: $includeVerboseFields) {
558
- version
559
- publishedAt
560
- body
561
- }
562
- }
563
- }`;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=`
564
- query PackageVulnerabilities(
565
- $registry: Registry!
566
- $name: String!
567
- $version: String
568
- $minSeverity: Float
569
- $includeWithdrawn: Boolean
570
- $scope: VulnerabilityScope = AFFECTED
571
- $after: String
572
- ) {
573
- packageVulnerabilities(
574
- registry: $registry
575
- name: $name
576
- version: $version
577
- minSeverity: $minSeverity
578
- includeWithdrawn: $includeWithdrawn
579
- ) {
580
- package {
581
- name
582
- registry
583
- version
584
- }
585
- security {
586
- affectedVulnerabilityCount
587
- nonAffectingVulnerabilityCount
588
- allVulnerabilityCount
589
- currentVersionAffected
590
- upgradePaths
591
- advisories(scope: $scope, first: 100, after: $after) {
592
- entries {
593
- osvId
594
- summary
595
- severityScore
596
- severityType
597
- affectedVersionRanges
598
- affectedVersionRangesCount
599
- affectedVersionRangesTruncated
600
- fixedInVersions
601
- publishedAt
602
- modifiedAt
603
- withdrawnAt
604
- aliases
605
- isMalicious
606
- affectsInspectedVersion
607
- matchedAffectedVersionRanges
608
- duplicateIds
609
- }
610
- pageInfo {
611
- hasNextPage
612
- endCursor
613
- totalCount
614
- }
615
- }
616
- }
617
- }
618
- }`;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=`
619
- query PackageDependencies(
620
- $registry: Registry!
621
- $name: String!
622
- $version: String
623
- $includeTransitive: Boolean
624
- $includeTransitiveDetails: Boolean! = true
625
- $includeDependencyGraph: Boolean! = true
626
- $includeGroups: Boolean! = true
627
- $maxDepth: Int
628
- $lifecycle: [String!]
629
- ) {
630
- packageDependencies(
631
- registry: $registry
632
- name: $name
633
- version: $version
634
- includeTransitive: $includeTransitive
635
- maxDepth: $maxDepth
636
- lifecycle: $lifecycle
637
- ) {
638
- package {
639
- name
640
- registry
641
- version
642
- }
643
- dependencies {
644
- # Backend-side summary block intentionally not selected — our
645
- # envelope computes runtime.count client-side from direct[].length
646
- # so the invariant runtime.count === runtime.items.length always
647
- # holds regardless of backend-side drift.
648
- direct {
649
- name
650
- versionConstraint
651
- type
652
- }
653
- transitive {
654
- totalEdges @include(if: $includeTransitiveDetails)
655
- uniquePackagesCount @include(if: $includeTransitiveDetails)
656
- uniqueDependencies @include(if: $includeTransitiveDetails)
657
- dependencyConflicts @include(if: $includeTransitiveDetails) {
658
- packageName
659
- requiredVersions
660
- conflictingEdges {
661
- fromIndex
662
- toIndex
663
- versionConstraint
664
- dependencyType
665
- }
666
- }
667
- circularDependencyCycles @include(if: $includeTransitiveDetails) {
668
- cycleStart
669
- circularPath
670
- displayChain
671
- }
672
- dependencyGraph @include(if: $includeDependencyGraph) {
673
- formatVersion
674
- nodes {
675
- registry
676
- name
677
- version
678
- }
679
- edges {
680
- fromIndex
681
- toIndex
682
- constraint
683
- dependencyType
684
- }
685
- }
686
- }
687
- }
688
- dependencyGroups @include(if: $includeGroups) {
689
- primaryGroup
690
- environmentMarkers {
691
- type
692
- value
693
- raw
694
- }
695
- groups {
696
- name
697
- lifecycle
698
- conditionType
699
- conditionValue
700
- selectionMode
701
- exclusiveGroup
702
- fallbackPriority
703
- compatibleWith
704
- defaultEnabled
705
- dependencies {
706
- name
707
- constraint
708
- }
709
- }
710
- }
711
- }
712
- }`;var PACKAGE_UPGRADE_DEPENDENCY_PROBE_QUERY=`
713
- query PackageUpgradeDependencyProbe(
714
- $registry: Registry!
715
- $name: String!
716
- $version: String!
717
- $includeTransitiveRisk: Boolean!
718
- $includeTransitiveSecurity: Boolean!
719
- $includeDependencyIssues: Boolean!
720
- $includeDependencyChanges: Boolean!
721
- $includeGroups: Boolean!
722
- $lifecycle: [String!]
723
- $minSeverity: Float
724
- ) {
725
- packageDependencies(
726
- registry: $registry
727
- name: $name
728
- version: $version
729
- includeTransitive: $includeTransitiveRisk
730
- lifecycle: $lifecycle
731
- ) {
732
- package {
733
- name
734
- registry
735
- version
736
- publishedAt
737
- deprecated
738
- deprecationReason
739
- }
740
- dependencies {
741
- direct {
742
- name
743
- versionConstraint
744
- type
745
- }
746
- transitive @include(if: $includeTransitiveRisk) {
747
- dependencyGraph @include(if: $includeDependencyChanges) {
748
- formatVersion
749
- nodes {
750
- registry
751
- name
752
- version
753
- }
754
- edges {
755
- fromIndex
756
- toIndex
757
- constraint
758
- dependencyType
759
- }
760
- }
761
- vulnerabilitySummary(minSeverity: $minSeverity) @include(if: $includeTransitiveSecurity) {
762
- affected {
763
- totalVulnerabilities
764
- critical
765
- high
766
- medium
767
- low
768
- unknown
769
- }
770
- nonAffecting {
771
- totalVulnerabilities
772
- critical
773
- high
774
- medium
775
- low
776
- unknown
777
- }
778
- combined {
779
- totalVulnerabilities
780
- critical
781
- high
782
- medium
783
- low
784
- unknown
785
- }
786
- totalPackagesAnalyzed
787
- affectedPackageCount
788
- calculatedAt
789
- packages {
790
- registry
791
- name
792
- versions
793
- affectedCount
794
- nonAffectingCount
795
- totalCount
796
- maxSeverityScore
797
- maxSeverityLabel
798
- advisoryIds(scope: AFFECTED)
799
- mostCritical {
800
- osvId
801
- registry
802
- packageName
803
- summary
804
- severityScore
805
- severityType
806
- affectedVersionRanges
807
- fixedInVersions
808
- publishedAt
809
- modifiedAt
810
- withdrawnAt
811
- aliases
812
- isMalicious
813
- }
814
- advisoryOccurrences(scope: AFFECTED, minSeverity: $minSeverity, limit: 5) {
815
- version
816
- affectsResolvedVersion
817
- matchedAffectedVersionRanges
818
- fixVersionsAboveResolved
819
- nearestFixedVersion
820
- advisory {
821
- osvId
822
- registry
823
- packageName
824
- summary
825
- severityScore
826
- severityType
827
- affectedVersionRanges
828
- fixedInVersions
829
- publishedAt
830
- modifiedAt
831
- withdrawnAt
832
- aliases
833
- isMalicious
834
- }
835
- }
836
- }
837
- }
838
- dependencyIssues @include(if: $includeDependencyIssues) {
839
- totalCount
840
- deprecatedCount
841
- outdatedCount
842
- duplicateCount
843
- conflictCount
844
- deprecatedPackages {
845
- registry
846
- name
847
- versions
848
- reasons {
849
- version
850
- reason
851
- }
852
- }
853
- outdatedPackages {
854
- registry
855
- name
856
- latestVersion
857
- severity
858
- versions {
859
- version
860
- severity
861
- }
862
- repositoryUrl
863
- }
864
- duplicatePackages {
865
- registry
866
- name
867
- versions
868
- }
869
- conflicts {
870
- registry
871
- name
872
- versions
873
- requiredVersions
874
- conflictingEdges {
875
- fromIndex
876
- toIndex
877
- versionConstraint
878
- dependencyType
879
- }
880
- }
881
- }
882
- }
883
- }
884
- dependencyGroups @include(if: $includeGroups) {
885
- primaryGroup
886
- environmentMarkers {
887
- type
888
- value
889
- raw
890
- }
891
- groups {
892
- name
893
- lifecycle
894
- conditionType
895
- conditionValue
896
- selectionMode
897
- exclusiveGroup
898
- fallbackPriority
899
- compatibleWith
900
- defaultEnabled
901
- dependencies {
902
- name
903
- constraint
904
- }
905
- }
906
- }
907
- }
908
- }`;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=`
909
- query PackageUpgradeReview(
910
- $packages: [PackageUpgradeReviewPackageInput!]!
911
- $includeTransitiveSecurity: Boolean!
912
- $includeDependencyIssues: Boolean!
913
- $minSeverity: Float
914
- $changelogLimit: Int!
915
- ) {
916
- packageUpgradeReview(
917
- packages: $packages
918
- includeTransitiveSecurity: $includeTransitiveSecurity
919
- minSeverity: $minSeverity
920
- changelogLimit: $changelogLimit
921
- ) {
922
- summary {
923
- total
924
- withUnknowns
925
- withAddedAdvisories
926
- withBreakingSignals
927
- withDirectDependencyChanges
928
- withTransitiveVulnerabilityAdditions
929
- }
930
- reviews {
931
- registry
932
- name
933
- currentVersion
934
- targetVersion
935
- latestVersion
936
- versionDelta
937
- security {
938
- current {
939
- version
940
- publishedAt
941
- deprecated
942
- deprecationReason
943
- affectedCount
944
- nonAffectingCount
945
- allCount
946
- lastModifiedAt
947
- advisories {
948
- ...PackageUpgradeAdvisoryFields
949
- }
950
- }
951
- target {
952
- version
953
- publishedAt
954
- deprecated
955
- deprecationReason
956
- affectedCount
957
- nonAffectingCount
958
- allCount
959
- lastModifiedAt
960
- advisories {
961
- ...PackageUpgradeAdvisoryFields
962
- }
963
- }
964
- added {
965
- ...PackageUpgradeAdvisoryFields
966
- }
967
- removed {
968
- ...PackageUpgradeAdvisoryFields
969
- }
970
- notAddressed {
971
- ...PackageUpgradeAdvisoryFields
972
- }
973
- fixed {
974
- ...PackageUpgradeAdvisoryFields
975
- }
976
- introduced {
977
- ...PackageUpgradeAdvisoryFields
978
- }
979
- unchanged {
980
- ...PackageUpgradeAdvisoryFields
981
- }
982
- transitive @include(if: $includeTransitiveSecurity) {
983
- currentAffected
984
- targetAffected
985
- introducedPackages
986
- fixedPackages
987
- introducedPackageDetails(first: 50) {
988
- ...PackageUpgradeTransitivePackagePageFields
989
- }
990
- fixedPackageDetails(first: 50) {
991
- ...PackageUpgradeTransitivePackagePageFields
992
- }
993
- stillAffectedPackageDetails(first: 50) {
994
- ...PackageUpgradeTransitivePackagePageFields
995
- }
996
- }
997
- }
998
- changelog {
999
- source
1000
- fallback
1001
- entries {
1002
- ...PackageUpgradeChangelogEntryFields
1003
- }
1004
- sampledEntries {
1005
- ...PackageUpgradeChangelogEntryFields
1006
- }
1007
- keywordEntries {
1008
- ...PackageUpgradeChangelogEntryFields
1009
- }
1010
- totalKeywordEntries
1011
- totalEntries
1012
- totalEntriesWithBodies
1013
- truncated
1014
- hasReleaseNoteBodies
1015
- breakingSignals
1016
- migrationSignals
1017
- }
1018
- compatibility {
1019
- peerDependencyChanges
1020
- notes
1021
- }
1022
- dependencyChanges {
1023
- direct {
1024
- ...PackageUpgradeDependencyChangeGroupFields
1025
- }
1026
- transitive {
1027
- ...PackageUpgradeDependencyChangeGroupFields
1028
- }
1029
- }
1030
- dependencyIssues @include(if: $includeDependencyIssues) {
1031
- currentTotal
1032
- targetTotal
1033
- introducedDeprecated
1034
- introducedDuplicates
1035
- introducedConflicts
1036
- introducedOutdated
1037
- }
1038
- unknowns
1039
- }
1040
- }
1041
- }
1042
-
1043
- fragment PackageUpgradeAdvisoryFields on PackageUpgradeAdvisorySummary {
1044
- id
1045
- aliases
1046
- summary
1047
- severity
1048
- severityLabel
1049
- fixedIn
1050
- isMalicious
1051
- }
1052
-
1053
- fragment PackageUpgradeTransitivePackagePageFields on PackageUpgradeTransitivePackagePage {
1054
- entries {
1055
- id
1056
- registry
1057
- name
1058
- versions
1059
- affectedCount
1060
- maxSeverityScore
1061
- maxSeverityLabel
1062
- advisoryIds
1063
- }
1064
- totalCount
1065
- truncated
1066
- }
1067
-
1068
- fragment PackageUpgradeChangelogEntryFields on PackageUpgradeChangelogEntry {
1069
- version
1070
- publishedAt
1071
- htmlUrl
1072
- body
1073
- bodyPreview
1074
- headline
1075
- signals
1076
- }
1077
-
1078
- fragment PackageUpgradeDependencyChangeGroupFields on PackageUpgradeDependencyChangeGroup {
1079
- added {
1080
- name
1081
- registry
1082
- version
1083
- fromVersions
1084
- toVersions
1085
- constraint
1086
- type
1087
- }
1088
- removed {
1089
- name
1090
- registry
1091
- version
1092
- fromVersions
1093
- toVersions
1094
- constraint
1095
- type
1096
- }
1097
- changed {
1098
- name
1099
- registry
1100
- version
1101
- fromVersions
1102
- toVersions
1103
- constraint
1104
- type
1105
- }
1106
- }`;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=`
1107
- query PackageChangelog(
1108
- $registry: Registry
1109
- $name: String
1110
- $repoUrl: String
1111
- $gitRef: String
1112
- $fromVersion: String
1113
- $toVersion: String
1114
- $limit: Int
1115
- $includeBodies: Boolean! = true
1116
- ) {
1117
- packageChangelog(
1118
- registry: $registry
1119
- name: $name
1120
- repoUrl: $repoUrl
1121
- gitRef: $gitRef
1122
- fromVersion: $fromVersion
1123
- toVersion: $toVersion
1124
- limit: $limit
1125
- ) {
1126
- package {
1127
- name
1128
- registry
1129
- repoUrl
1130
- fromVersion
1131
- toVersion
1132
- limit
1133
- }
1134
- source
1135
- entries {
1136
- version
1137
- normalizedVersion
1138
- body @include(if: $includeBodies)
1139
- htmlUrl
1140
- publishedAt
1141
- }
1142
- }
1143
- }`;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=`
1144
- query ListPackageDocs(
1145
- $registry: Registry!
1146
- $packageName: String!
1147
- $version: String
1148
- $limit: Int
1149
- $after: String
1150
- ) {
1151
- listPackageDocs(
1152
- registry: $registry
1153
- packageName: $packageName
1154
- version: $version
1155
- limit: $limit
1156
- after: $after
1157
- ) {
1158
- registry
1159
- packageName
1160
- version
1161
- stale
1162
- pages {
1163
- id
1164
- title
1165
- slug
1166
- order
1167
- linkName
1168
- lastUpdatedAt
1169
- sourceKind
1170
- sourceUrl
1171
- repoUrl
1172
- gitRef
1173
- requestedRef
1174
- filePath
1175
- }
1176
- pageInfo {
1177
- hasNextPage
1178
- endCursor
1179
- totalCount
1180
- }
1181
- }
1182
- }`;var READ_PACKAGE_DOC_QUERY=`
1183
- query ReadPackageDoc($pageId: String!) {
1184
- getDocPage(pageId: $pageId) {
1185
- registry
1186
- packageName
1187
- version
1188
- sourceKind
1189
- page {
1190
- id
1191
- title
1192
- content
1193
- contentFormat
1194
- breadcrumbs
1195
- linkName
1196
- lastUpdatedAt
1197
- sourceKind
1198
- source {
1199
- url
1200
- label
1201
- }
1202
- repoUrl
1203
- gitRef
1204
- requestedRef
1205
- filePath
1206
- baseUrl
1207
- }
1208
- }
1209
- }`;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:isTokenRefreshableError,executeWithToken:(token)=>this.executePackageSummary(token,params)}))}async executePackageSummary(token,params){let response;try{response=await postPkgseerGraphql({endpointUrl:this.endpointUrl,token,query:PACKAGE_SUMMARY_QUERY,variables:{registry:params.registry,name:params.packageName,includeVerboseFields:params.includeVerboseFields!==false},fetchFn:this.fetchFn,clientHeaders:this.runtime.clientHeaders,userAgent:this.runtime.userAgent})}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:isTokenRefreshableError,executeWithToken:(token)=>this.executePackageVulnerabilities(token,params)}))}async executePackageVulnerabilities(token,params){let after=null;let firstPage;const entries=[];const seenCursors=new Set;do{const page=await this.fetchPackageVulnerabilitiesPage(token,params,after);if(!firstPage)firstPage=page;const advisoryPage=page.security?.advisories;if(!advisoryPage){after=null;break}entries.push(...advisoryPage.entries);if(advisoryPage.pageInfo.hasNextPage){const nextCursor=advisoryPage.pageInfo.endCursor;if(!nextCursor){throw new MalformedPackageIntelligenceResponseError("Vulnerability response pagination omitted next cursor.")}if(seenCursors.has(nextCursor)){throw new MalformedPackageIntelligenceResponseError("Vulnerability response pagination repeated a cursor.")}seenCursors.add(nextCursor);after=nextCursor}else{after=null}}while(after!==null);if(!firstPage){throw new MalformedPackageIntelligenceResponseError("Empty response from the package-intelligence service.")}if(firstPage.security){const expectedCount=firstPage.security.advisories.pageInfo.totalCount;if(entries.length!==expectedCount){throw new MalformedPackageIntelligenceResponseError("Vulnerability response pagination returned an incomplete advisory set.")}}const data=firstPage.security?{...firstPage,security:{...firstPage.security,advisories:{...firstPage.security.advisories,entries}}}:firstPage;return this.normaliseVulnerabilityReport(data)}async fetchPackageVulnerabilitiesPage(token,params,after){let response;try{response=await postPkgseerGraphql({endpointUrl:this.endpointUrl,token,query:PACKAGE_VULNERABILITIES_QUERY,variables:{registry:params.registry,name:params.packageName,version:params.version,minSeverity:params.minSeverity,includeWithdrawn:params.includeWithdrawn,scope:params.advisoryScope,after},fetchFn:this.fetchFn,clientHeaders:this.runtime.clientHeaders,userAgent:this.runtime.userAgent})}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:isTokenRefreshableError,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:isTokenRefreshableError,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:isTokenRefreshableError,executeWithToken:(token)=>this.executePackageUpgradeReview(token,params)}))}async executePackageUpgradeReview(token,params){let response;try{response=await postPkgseerGraphql({endpointUrl:this.endpointUrl,token,query:PACKAGE_UPGRADE_REVIEW_QUERY,variables:{packages:params.packages,includeTransitiveSecurity:params.includeTransitiveSecurity,includeDependencyIssues:params.includeDependencyIssues,minSeverity:params.minSeverity,changelogLimit:params.changelogLimit},fetchFn:this.fetchFn,clientHeaders:this.runtime.clientHeaders,userAgent:this.runtime.userAgent})}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:isTokenRefreshableError,executeWithToken:(token)=>this.executePackageChangelog(token,params)}))}async executePackageChangelog(token,params){let response;try{response=await postPkgseerGraphql({endpointUrl:this.endpointUrl,token,query:PACKAGE_CHANGELOG_QUERY,variables:{registry:params.registry,name:params.packageName,repoUrl:params.repoUrl,gitRef:params.gitRef,fromVersion:params.fromVersion,toVersion:params.toVersion,limit:params.limit,includeBodies:params.includeBodies!==false},fetchFn:this.fetchFn,clientHeaders:this.runtime.clientHeaders,userAgent:this.runtime.userAgent})}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:isTokenRefreshableError,executeWithToken:(token)=>this.executeListPackageDocs(token,params)}))}async executeListPackageDocs(token,params){let response;try{response=await postPkgseerGraphql({endpointUrl:this.endpointUrl,token,query:LIST_PACKAGE_DOCS_QUERY,variables:{registry:params.registry,packageName:params.packageName,version:params.version,limit:params.limit,after:params.after},fetchFn:this.fetchFn,clientHeaders:this.runtime.clientHeaders,userAgent:this.runtime.userAgent})}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:isTokenRefreshableError,executeWithToken:(token)=>this.executeReadPackageDoc(token,params)}))}async executeReadPackageDoc(token,params){let response;try{response=await postPkgseerGraphql({endpointUrl:this.endpointUrl,token,query:READ_PACKAGE_DOC_QUERY,variables:{pageId:params.pageId},fetchFn:this.fetchFn,clientHeaders:this.runtime.clientHeaders,userAgent:this.runtime.userAgent})}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:isTokenRefreshableError,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,TermsAcceptanceRequiredError,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};