@githits/mcp 0.11.2 → 0.11.3

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.
@@ -621,7 +621,7 @@ query GrepRepo(
621
621
  }
622
622
  ${INDEXING_DURATION_ESTIMATE_SELECTION}
623
623
  }
624
- }`}var unifiedSearchGraphQLResponseSchema=z2.object({data:z2.object({search:asyncUnifiedSearchResultSchema.nullable().optional()}).nullable().optional(),errors:z2.array(graphQLErrorSchema).optional()});var unifiedSearchStatusGraphQLResponseSchema=z2.object({data:z2.object({discoverySearchProgress:unifiedSearchProgressSchema.nullable().optional()}).nullable().optional(),errors:z2.array(graphQLErrorSchema).optional()});class CodeNavigationServiceImpl{codeNavigationUrl;tokenProvider;fetchFn;runtime;constructor(codeNavigationUrl,tokenProvider,fetchFn=globalThis.fetch,runtime={}){this.codeNavigationUrl=codeNavigationUrl;this.tokenProvider=tokenProvider;this.fetchFn=fetchFn;this.runtime=runtime}async postGraphqlWithTargetResolutionFallback(input){const response=await postPkgseerGraphql({endpointUrl:this.codeNavigationUrl,token:input.token,query:input.query,variables:input.variables,fetchFn:this.fetchFn,clientHeaders:this.runtime.clientHeaders,userAgent:this.runtime.userAgent,diagnostics:this.runtime.diagnostics});if(response.status<200||response.status>=300)return response;if(!hasSchemaMismatchErrors(response.parsedBody))return response;for(const fallbackQuery of buildTargetResolutionFallbackQueries(input.query)){if(this.runtime.diagnostics?.isEnabled("code-nav")){this.runtime.diagnostics.debug("code-nav",{event:"target-resolution-query-fallback"})}const fallbackResponse=await postPkgseerGraphql({endpointUrl:this.codeNavigationUrl,token:input.token,query:fallbackQuery,variables:input.variables,fetchFn:this.fetchFn,clientHeaders:this.runtime.clientHeaders,userAgent:this.runtime.userAgent,diagnostics:this.runtime.diagnostics});if(!hasSchemaMismatchErrors(fallbackResponse.parsedBody)){return fallbackResponse}}return response}async search(params){return executeWithTokenRefresh({getToken:()=>this.tokenProvider.getToken(),forceRefresh:()=>this.tokenProvider.forceRefresh(),shouldRefresh:isTokenRefreshableError,executeWithToken:(token)=>this.executeUnifiedSearch(token,params)})}async searchStatus(searchRef,waitTimeoutMs=0){return executeWithTokenRefresh({getToken:()=>this.tokenProvider.getToken(),forceRefresh:()=>this.tokenProvider.forceRefresh(),shouldRefresh:isTokenRefreshableError,executeWithToken:(token)=>this.executeUnifiedSearchStatus(token,searchRef,waitTimeoutMs)})}async codeDiff(params){validateCodeDiffParams(params);return executeWithTokenRefresh({getToken:()=>this.tokenProvider.getToken(),forceRefresh:()=>this.tokenProvider.forceRefresh(),shouldRefresh:isTokenRefreshableError,executeWithToken:(token)=>this.executeCodeDiff(token,params)})}async executeCodeDiff(token,params){const query=buildCodeDiffQuery(params.mode);const variables=buildCodeDiffVariables(params);debugGraphqlWireRequest("codeDiff",query,variables,this.runtime.diagnostics);let response;try{response=await this.postGraphqlWithTargetResolutionFallback({token,query,variables})}catch(cause){if(cause instanceof PkgseerTransportError){throw this.createTransportError(cause)}throw cause}if(response.status<200||response.status>=300){throw this.createHttpError(response)}const parsed=codeDiffGraphQLResponseSchema.safeParse(response.parsedBody);if(!parsed.success){throw new MalformedCodeNavigationResponseError("Malformed response from code navigation service.")}const data=parsed.data.data?.codeDiff;const errors=parsed.data.errors??[];if(errors.length>0){const rawErrors=errors.filter(isCodeDiffRawError);if(rawErrors.length>0){throw new CodeDiffError(rawErrors.map((error)=>error.message).join(", "),parseCodeDiffErrorDetails(rawErrors),data?normaliseCodeDiffPartial(data):undefined)}throw this.createCodeDiffRootError(errors)}if(!data?.raw){throw new MalformedCodeNavigationResponseError("CodeDiff response missing non-null raw result.")}return normaliseCodeDiffResult(data)}createCodeDiffRootError(errors){const graphQLErrors=errors.map(({message:message2,extensions:extensions2})=>({message:message2,extensions:extensions2}));const message=errors.map((error)=>error.message).join(", ");const extensions=getPrimaryExtensions(errors);const code=typeof extensions?.code==="string"?extensions.code:undefined;if(code==="AUTHENTICATION_REQUIRED"){return new AuthenticationError(SERVER_AUTHENTICATION_REJECTED_MESSAGE,"server")}if(code==="UNAUTHORIZED"||code==="FORBIDDEN"||code==="FEATURE_FLAG_REQUIRED"||isClientUpdateRequiredGraphQLError({message,code})||isGraphQLSchemaMismatchError({message,code})||code===undefined&&isAuthMessage(message)){return this.createGraphQLError(graphQLErrors)}return new CodeDiffError(message,parseCodeDiffErrorDetails(errors))}async executeUnifiedSearch(token,params){if(params.targets.length===0){throw new CodeNavigationValidationError("At least one search target is required.")}let response;const variables={targets:params.targets.map((target)=>({registry:target.registry,name:target.packageName,version:target.version,repoUrl:target.repoUrl,gitRef:target.gitRef,site:target.site})),query:params.query,sources:params.sources,filters:params.filters,allowPartialResults:params.allowPartialResults??false,limit:params.limit,offset:params.offset,waitTimeoutMs:params.waitTimeoutMs};debugUnifiedSearchRequest(variables,this.runtime.diagnostics);debugGraphqlWireRequest("search",UNIFIED_SEARCH_QUERY,variables,this.runtime.diagnostics);try{response=await this.postGraphqlWithTargetResolutionFallback({token,query:UNIFIED_SEARCH_QUERY,variables})}catch(cause){if(cause instanceof PkgseerTransportError){throw this.createTransportError(cause)}throw cause}if(response.status<200||response.status>=300){throw this.createHttpError(response)}const parsed=unifiedSearchGraphQLResponseSchema.safeParse(response.parsedBody);if(!parsed.success){throw new MalformedCodeNavigationResponseError("Malformed response from code navigation service.")}if(parsed.data.errors&&parsed.data.errors.length>0){throw this.createGraphQLError(parsed.data.errors)}const data=parsed.data.data?.search;if(!data){throw new MalformedCodeNavigationResponseError("Malformed response from code navigation service.")}return this.normaliseUnifiedSearchOutcome(data)}async executeUnifiedSearchStatus(token,searchRef,waitTimeoutMs){let response;try{response=await this.postGraphqlWithTargetResolutionFallback({token,query:UNIFIED_SEARCH_STATUS_QUERY,variables:{searchRef,includeResults:true,waitTimeoutMs}})}catch(cause){if(cause instanceof PkgseerTransportError){throw this.createTransportError(cause)}throw cause}if(response.status<200||response.status>=300){throw this.createHttpError(response)}const parsed=unifiedSearchStatusGraphQLResponseSchema.safeParse(response.parsedBody);if(!parsed.success){throw new MalformedCodeNavigationResponseError("Malformed response from code navigation service.")}if(parsed.data.errors&&parsed.data.errors.length>0){throw this.createGraphQLError(parsed.data.errors)}const data=parsed.data.data?.discoverySearchProgress;if(!data){throw new MalformedCodeNavigationResponseError("Malformed response from code navigation service.")}const progress=this.normaliseUnifiedSearchProgress(data);const result=data.results?this.normaliseUnifiedSearchResult(data.results):undefined;if(result&&progress.status==="COMPLETED"){return{state:"completed",completed:true,searchRef:progress.searchRef,result,progress}}return{state:"incomplete",completed:false,searchRef:progress.searchRef,result,progress}}createHttpError(response){const status=response.status;const detail=parseDetail(response.responseBody);if(status===401){return new AuthenticationError(SERVER_AUTHENTICATION_REJECTED_MESSAGE,"server")}if(status===403){return new CodeNavigationAccessError(detail??"Code navigation access denied.")}if(status>=500){return new CodeNavigationBackendError(detail?`Server error (${status}): ${detail}`:`Server error (${status})`,status)}return new CodeNavigationBackendError(detail??`Request failed with status ${status}`,status)}createTransportError(error){if(isFetchTimeoutError(error.cause)){return new CodeNavigationBackendError("Code navigation request timed out.",undefined,"TIMEOUT",true)}return new CodeNavigationNetworkError("Could not reach the code navigation service. Check your connection or set GITHITS_CODE_NAV_URL.",{cause:error})}createGraphQLError(errors){const message=errors.map((error)=>error.message).join(", ");const extensions=getPrimaryExtensions(errors);const code=typeof extensions?.code==="string"?extensions.code:undefined;const retryable=typeof extensions?.retryable==="boolean"?extensions.retryable:undefined;const indexingRef=getGraphQLIndexingRef(errors);const indexingEstimate=parseIndexingDurationEstimate(extensions);const errorMetadata=parseGraphQLErrorMetadata(extensions,indexingEstimate);if(isClientUpdateRequiredGraphQLError({message,code})){return new ClientUpdateRequiredError(undefined,undefined,this.runtime.clientVersion)}if(isGraphQLSchemaMismatchError({message,code})){const sanitized="Backend protocol mismatch. Your CLI may be newer than the server, or the server may require a newer CLI. Run `githits update-check` to verify your installed version. Set GITHITS_DEBUG=code-nav-wire to inspect GraphQL details during local development.";if(this.runtime.diagnostics?.isEnabled("code-nav")){this.runtime.diagnostics.debug("code-nav",{event:"graphql-schema-mismatch",code:code??"omitted",message})}return new CodeNavigationBackendError(this.runtime.diagnostics?.isEnabled("code-nav-wire")?message:sanitized,undefined,code,retryable)}switch(code){case"PACKAGE_INDEXING":return new CodeNavigationIndexingError(message,indexingRef,parseAvailableVersions(extensions),parseAvailableRefs(extensions),parseTargetResolution(extensions),indexingEstimate,appendIndexingWaitHint(message,typeof extensions?.hint==="string"?extensions.hint:undefined));case"GREP_PATTERN_TOO_SHORT":case"GREP_PATTERN_TOO_LONG":case"GREP_PATTERN_INVALID":case"GREP_INVALID_REGEX":case"GREP_UNSUPPORTED_PATTERN":case"GREP_PATTERN_TOO_UNSELECTIVE":case"GREP_SCOPE_REQUIRED":case"GREP_SELECTOR_INVALID":case"GREP_CURSOR_INVALID":case"GREP_CONTEXT_TOO_LARGE":case"GREP_CONTEXT_NEGATIVE":case"GREP_MAX_MATCHES_TOO_LARGE":case"GREP_MAX_MATCHES_INVALID":return new CodeNavigationValidationError(message);case"VERSION_NOT_FOUND":return new CodeNavigationVersionNotFoundError(message,typeof extensions?.package==="string"?extensions.package:undefined,typeof extensions?.requested_version==="string"?extensions.requested_version:undefined,typeof extensions?.latest_indexed==="string"?extensions.latest_indexed:undefined,parseAvailableVersions(extensions),errorMetadata);case"REF_NOT_FOUND":return new CodeNavigationRefNotFoundError(message,parseGraphQLRepoUrl(extensions),parseGraphQLGitRef(extensions),parseAvailableRefs(extensions),parseSuggestedRefs(extensions),errorMetadata);case"NOT_FOUND":case"PACKAGE_NOT_FOUND":case"NO_REPOSITORY_URL":return new CodeNavigationTargetNotFoundError(message,parseAvailableVersions(extensions),parseGraphQLRepoUrl(extensions),parseGraphQLGitRef(extensions),errorMetadata);case"REPOSITORY_NOT_FOUND":return new CodeNavigationTargetNotFoundError(message,undefined,parseGraphQLRepoUrl(extensions),parseGraphQLGitRef(extensions),errorMetadata);case"FILE_NOT_FOUND":return new CodeNavigationFileNotFoundError(message,typeof extensions?.file_path==="string"?extensions.file_path:typeof extensions?.filePath==="string"?extensions.filePath:undefined);case"UNSUPPORTED_REGISTRY":case"VALIDATION_ERROR":return new CodeNavigationValidationError(message);case"FEATURE_FLAG_REQUIRED":return new CodeNavigationFeatureFlagRequiredError(message);case"UNAUTHORIZED":return new AuthenticationError(SERVER_AUTHENTICATION_REJECTED_MESSAGE,"server");case"FORBIDDEN":return new CodeNavigationAccessError("Code navigation access denied. This feature may not be enabled for your account.");case"UPSTREAM_ERROR":case"TIMEOUT":case"RATE_LIMITED":case"GREP_FILE_TOO_LARGE":case"GREP_TIMEOUT":case"GREP_SERVICE_UNAVAILABLE":case"GREP_FAILED":case"GREP_INDEX_NOT_AVAILABLE":case"FILE_PATH_EXCLUDED":case"SOURCE_FILE_INVENTORY_UNKNOWN":case"INTERNAL_ERROR":case"UNKNOWN_ERROR":return new CodeNavigationBackendError(message,undefined,code,retryable,errorMetadata);default:break}if(code===undefined){if(isAuthMessage(message)){return new CodeNavigationAccessError("Code navigation access denied. This feature may not be enabled for your account.")}if(isUnresolvableMessage(message)){return new CodeNavigationUnresolvableError(message)}if(isTargetNotFoundMessage(message)){return new CodeNavigationTargetNotFoundError(message,parseAvailableVersions(extensions),parseGraphQLRepoUrl(extensions),parseGraphQLGitRef(extensions),errorMetadata)}}return new CodeNavigationBackendError(message,undefined,code,retryable,errorMetadata)}normaliseUnifiedSearchOutcome(data){const progress=data.progress?this.normaliseUnifiedSearchProgress(data.progress):undefined;if(data.completed){if(!data.result){throw new MalformedCodeNavigationResponseError("Completed unified search response missing result payload.")}return{state:"completed",completed:true,searchRef:data.searchRef??undefined,result:this.normaliseUnifiedSearchResult(data.result),progress}}const searchRef=data.searchRef??progress?.searchRef;if(!searchRef){throw new MalformedCodeNavigationResponseError("Incomplete unified search response missing search reference.")}const result=data.result?this.normaliseUnifiedSearchResult(data.result):undefined;return{state:"incomplete",completed:false,searchRef,result,progress}}normaliseUnifiedSearchResult(result){return{query:result.query,queryWarnings:result.queryWarnings,sources:result.sources,results:result.results.map((entry)=>({id:entry.id,resultType:entry.resultType,targetLabel:entry.targetLabel,requestedTargetLabel:entry.requestedTargetLabel??undefined,freshTargetLabel:entry.freshTargetLabel??undefined,servedTargetLabel:entry.servedTargetLabel??undefined,freshness:entry.freshness??undefined,title:entry.title??undefined,summary:entry.summary??undefined,score:entry.score??undefined,highlights:entry.highlights?{title:entry.highlights.title??undefined,summary:entry.highlights.summary??undefined}:undefined,locator:{registry:entry.locator.registry??undefined,packageName:entry.locator.packageName??undefined,version:entry.locator.version??undefined,pageId:entry.locator.pageId??undefined,sourceKind:entry.locator.sourceKind??undefined,sourceUrl:entry.locator.sourceUrl??undefined,repoUrl:entry.locator.repoUrl??undefined,gitRef:entry.locator.gitRef??undefined,requestedRef:entry.locator.requestedRef??undefined,filePath:entry.locator.filePath??undefined,startLine:entry.locator.startLine??undefined,endLine:entry.locator.endLine??undefined,fileContentHash:entry.locator.fileContentHash??undefined,symbolRef:entry.locator.symbolRef??undefined,qualifiedPath:entry.locator.qualifiedPath??undefined,kind:entry.locator.kind??undefined,category:entry.locator.category??undefined,language:entry.locator.language??undefined}})),page:{offset:result.page.offset,limit:result.page.limit,returned:result.page.returned,hasMore:result.page.hasMore},partialResults:result.partialResults,sourceStatus:result.sourceStatus.map((entry)=>({source:entry.source,targetLabel:entry.targetLabel,requestedTargetLabel:entry.requestedTargetLabel??undefined,freshTargetLabel:entry.freshTargetLabel??undefined,servedTargetLabel:entry.servedTargetLabel??undefined,targetResolution:normaliseTargetResolution(entry.targetResolution),indexingStatus:entry.indexingStatus??undefined,codeIndexState:entry.codeIndexState??undefined,resultCount:entry.resultCount??undefined,appliedFilters:entry.appliedFilters,ignoredFilters:entry.ignoredFilters,incompatibleFilters:entry.incompatibleFilters,appliedQueryFeatures:entry.appliedQueryFeatures,ignoredQueryFeatures:entry.ignoredQueryFeatures,incompatibleQueryFeatures:entry.incompatibleQueryFeatures,suggestedSiteTargets:entry.suggestedSiteTargets,suggestedSiteTargetsTruncated:entry.suggestedSiteTargetsTruncated,note:entry.note??undefined,coverage:normaliseDocCoverage(entry.coverage),contributors:entry.contributors.map((contributor)=>({kind:contributor.kind,state:contributor.state,freshness:contributor.freshness??undefined,resultCount:contributor.resultCount,repositoryUrl:contributor.repositoryUrl??undefined,commitSha:contributor.commitSha??undefined,siteKey:contributor.siteKey??undefined,siteUrl:contributor.siteUrl??undefined,coverage:normaliseDocCoverage(contributor.coverage,{preserveNone:true})}))})),evidenceNotice:result.evidenceNotice??undefined}}normaliseUnifiedSearchProgress(progress){return{searchRef:progress.searchRef,status:progress.status,targetsTotal:progress.targetsTotal,targetsReady:progress.targetsReady,elapsedMs:progress.elapsedMs,query:progress.query,queryWarnings:progress.queryWarnings,sources:progress.sources,requestedSources:progress.requestedSources??undefined,targetMode:normaliseTargetMode(progress.targetMode),requestedTargets:progress.requestedTargets?.map((target)=>({registry:target.registry?target.registry:undefined,name:target.name??undefined,version:target.version??undefined,repoUrl:target.repoUrl??undefined,gitRef:target.gitRef??undefined,site:target.site??undefined})),filters:normaliseProgressFilters(progress.filters),limit:progress.limit??undefined,offset:progress.offset??undefined,targets:progress.targets?.map((target)=>({requested:target.requested??undefined,resolvedRequested:target.resolvedRequested??undefined,served:target.served??undefined,freshness:target.freshness??undefined,indexingRef:target.indexingRef??undefined,requestedRefKind:normaliseRequestedRefKind(target.requestedRefKind),targetResolution:normaliseTargetResolution(target.targetResolution),availableVersions:normaliseAvailableVersions(target.availableVersions),availableRefs:normaliseAvailableVersions(target.availableRefs),suggestedRefs:normaliseAvailableVersions(target.suggestedRefs),coverage:normaliseDocCoverage(target.coverage)})),expiresAt:progress.expiresAt??undefined}}throwIfIndexing(data){if(data.codeIndexState==="INDEXING"){const targetResolution=normaliseTargetResolution(data.targetResolution);const indexingEstimate=normaliseIndexingDurationEstimate(data.indexingEstimate);throw new CodeNavigationIndexingError(`Target is indexing. ${INDEXING_WAIT_HINT}`,data.indexingRef??targetResolution?.indexingRef,normaliseAvailableVersions(data.availableVersions)??targetResolution?.availableVersions,targetResolution?.availableRefs,targetResolution,indexingEstimate)}}async listFiles(params){return executeWithTokenRefresh({getToken:()=>this.tokenProvider.getToken(),forceRefresh:()=>this.tokenProvider.forceRefresh(),shouldRefresh:isTokenRefreshableError,executeWithToken:(token)=>this.executeListFiles(token,params)})}async executeListFiles(token,params){let response;try{response=await this.postGraphqlWithTargetResolutionFallback({token,query:LIST_REPO_FILES_QUERY,variables:{registry:params.target.registry,packageName:params.target.packageName,repoUrl:params.target.repoUrl,gitRef:params.target.gitRef,version:params.target.version,pathPrefix:params.pathPrefix,pathSelectors:params.pathSelectors?.map((entry)=>({kind:entry.kind,value:entry.value})),extensions:params.extensions,fileTypes:params.fileTypes,languages:params.languages,fileIntent:params.fileIntent,fileIntents:params.fileIntents,excludeFileIntents:params.excludeFileIntents,excludeDocFiles:params.excludeDocFiles,excludeTestFiles:params.excludeTestFiles,includeHidden:params.includeHidden,limit:params.limit,waitTimeoutMs:params.waitTimeoutMs}})}catch(cause){if(cause instanceof PkgseerTransportError){throw this.createTransportError(cause)}throw cause}if(response.status<200||response.status>=300){throw this.createHttpError(response)}const parsed=listRepoFilesGraphQLResponseSchema.safeParse(response.parsedBody);if(!parsed.success){throw new MalformedCodeNavigationResponseError("Malformed response from code navigation service.")}if(parsed.data.errors&&parsed.data.errors.length>0){throw this.createGraphQLError(parsed.data.errors)}const data=parsed.data.data?.listRepoFiles;if(!data){throw new MalformedCodeNavigationResponseError("Malformed response from code navigation service.")}this.throwIfIndexing(data);return{files:data.files.map((entry)=>({path:entry.path,name:entry.name??undefined,language:entry.language??undefined,fileType:entry.fileType??undefined,byteSize:entry.byteSize??undefined})),total:data.total,hasMore:data.hasMore,indexedVersion:data.indexedVersion??undefined,resolution:data.resolution?{requestedVersion:data.resolution.requestedVersion??undefined,requestedRef:data.resolution.requestedRef??undefined,resolvedRef:data.resolution.resolvedRef??undefined,commitSha:data.resolution.commitSha??undefined}:undefined,targetResolution:normaliseTargetResolution(data.targetResolution),hint:data.diagnostics?.hint??undefined}}async readFile(params){return executeWithTokenRefresh({getToken:()=>this.tokenProvider.getToken(),forceRefresh:()=>this.tokenProvider.forceRefresh(),shouldRefresh:isTokenRefreshableError,executeWithToken:(token)=>this.executeReadFile(token,params)})}async executeReadFile(token,params){let response;try{response=await this.postGraphqlWithTargetResolutionFallback({token,query:FETCH_CODE_CONTEXT_QUERY,variables:{registry:params.target.registry,packageName:params.target.packageName,repoUrl:params.target.repoUrl,gitRef:params.target.gitRef,version:params.target.version,filePath:params.filePath,startLine:params.startLine,endLine:params.endLine,waitTimeoutMs:params.waitTimeoutMs}})}catch(cause){if(cause instanceof PkgseerTransportError){throw this.createTransportError(cause)}throw cause}if(response.status<200||response.status>=300){throw this.createHttpError(response)}const parsed=fetchCodeContextGraphQLResponseSchema.safeParse(response.parsedBody);if(!parsed.success){throw new MalformedCodeNavigationResponseError("Malformed response from code navigation service.")}if(parsed.data.errors&&parsed.data.errors.length>0){throw this.createGraphQLError(parsed.data.errors)}const data=parsed.data.data?.fetchCodeContext;if(!data){throw new MalformedCodeNavigationResponseError("Malformed response from code navigation service.")}this.throwIfIndexing(data);return{filePath:data.filePath??undefined,language:data.language??undefined,totalLines:data.totalLines??undefined,startLine:data.startLine??undefined,endLine:data.endLine??undefined,content:data.content??undefined,isBinary:data.isBinary??undefined,targetResolution:normaliseTargetResolution(data.targetResolution),availableVersions:normaliseAvailableVersions(data.availableVersions)}}async grepRepo(params){return executeWithTokenRefresh({getToken:()=>this.tokenProvider.getToken(),forceRefresh:()=>this.tokenProvider.forceRefresh(),shouldRefresh:isTokenRefreshableError,executeWithToken:(token)=>this.executeGrepRepo(token,params)})}async executeGrepRepo(token,params){let response;try{response=await this.postGraphqlWithTargetResolutionFallback({token,query:buildGrepRepoQuery(params.symbolFields),variables:{registry:params.target.registry,packageName:params.target.packageName,repoUrl:params.target.repoUrl,gitRef:params.target.gitRef,version:params.target.version,waitTimeoutMs:params.waitTimeoutMs,pattern:params.pattern,patternType:params.patternType,caseSensitive:params.caseSensitive,pathSelectors:params.pathSelectors?.map((entry)=>({kind:entry.kind,value:entry.value})),extensions:params.extensions,excludeDocFiles:params.excludeDocFiles,excludeTestFiles:params.excludeTestFiles,allowUnscoped:params.allowUnscoped,contextLinesBefore:params.contextLinesBefore,contextLinesAfter:params.contextLinesAfter,maxMatches:params.maxMatches,maxMatchesPerFile:params.maxMatchesPerFile,cursor:params.cursor,symbolFields:params.symbolFields}})}catch(cause){if(cause instanceof PkgseerTransportError){throw this.createTransportError(cause)}throw cause}if(response.status<200||response.status>=300){throw this.createHttpError(response)}const parsed=grepRepoGraphQLResponseSchema.safeParse(response.parsedBody);if(!parsed.success){throw new MalformedCodeNavigationResponseError("Malformed response from code navigation service.")}if(parsed.data.errors&&parsed.data.errors.length>0){throw this.createGraphQLError(parsed.data.errors)}const data=parsed.data.data?.grepRepo;if(!data){throw new MalformedCodeNavigationResponseError("Malformed response from code navigation service.")}this.throwIfIndexing(data);return{matches:data.matches.map((entry)=>({filePath:entry.filePath,line:entry.line,matchStartByte:entry.matchStartByte,matchEndByte:entry.matchEndByte,lineContent:entry.lineContent,contextBefore:entry.contextBefore??undefined,contextAfter:entry.contextAfter??undefined,fileContentHash:entry.fileContentHash??undefined,fileIntent:entry.fileIntent??undefined,symbolRowId:entry.symbolRowId??undefined,symbol:entry.symbol?{symbolRef:entry.symbol.symbolRef,name:entry.symbol.name,qualifiedPath:entry.symbol.qualifiedPath??undefined,kind:entry.symbol.kind??undefined,category:entry.symbol.category??undefined,arity:entry.symbol.arity??undefined,isPublic:entry.symbol.isPublic??undefined,filePath:entry.symbol.filePath??undefined,startLine:entry.symbol.startLine??undefined,endLine:entry.symbol.endLine??undefined,code:entry.symbol.code??undefined,callerCount:entry.symbol.callerCount??undefined,contentHash:entry.symbol.contentHash??undefined,parentSymbolRef:entry.symbol.parentSymbolRef??undefined,parentPath:entry.symbol.parentPath??undefined}:undefined})),nextCursor:data.nextCursor??undefined,hasMore:data.hasMore,truncatedReason:data.truncatedReason,routeTaken:data.routeTaken??undefined,filesScanned:data.filesScanned,filesInScope:data.filesInScope,binaryFilesSkipped:data.binaryFilesSkipped,filesTooLargeSkipped:data.filesTooLargeSkipped,totalMatches:data.totalMatches,uniqueFilesMatched:data.uniqueFilesMatched,indexedVersion:data.indexedVersion??undefined,resolution:data.resolution?{requestedVersion:data.resolution.requestedVersion??undefined,requestedRef:data.resolution.requestedRef??undefined,resolvedRef:data.resolution.resolvedRef??undefined,commitSha:data.resolution.commitSha??undefined}:undefined,targetResolution:normaliseTargetResolution(data.targetResolution)}}}function validateCodeDiffParams(params){const paramsRecord=asRecord(params);if(!paramsRecord){throw new CodeNavigationValidationError("CodeDiff params must be an object.")}if(paramsRecord.mode!=="inventory"&&paramsRecord.mode!=="stats"&&paramsRecord.mode!=="patches"){throw new CodeNavigationValidationError("CodeDiff mode must be inventory, stats, or patches.")}if(typeof paramsRecord.from!=="string"||paramsRecord.from.length===0){throw new CodeNavigationValidationError("CodeDiff from ref or version must not be empty.")}if(typeof paramsRecord.to!=="string"||paramsRecord.to.length===0){throw new CodeNavigationValidationError("CodeDiff to ref or version must not be empty.")}const target=asRecord(paramsRecord.target);if(!target){throw new CodeNavigationValidationError("CodeDiff target must be a package or repository target.")}if(Object.hasOwn(target,"registry")&&Object.hasOwn(target,"packageName")&&!Object.hasOwn(target,"repoUrl")){if(!codeDiffRegistrySchema.safeParse(target.registry).success){throw new CodeNavigationValidationError("CodeDiff package target has an unsupported registry.")}if(typeof target.packageName!=="string"||target.packageName.length===0){throw new CodeNavigationValidationError("CodeDiff package target name must not be empty.")}}else if(Object.hasOwn(target,"repoUrl")&&!Object.hasOwn(target,"registry")&&!Object.hasOwn(target,"packageName")){if(typeof target.repoUrl!=="string"||target.repoUrl.length===0){throw new CodeNavigationValidationError("CodeDiff repository target URL must not be empty.")}}else if((Object.hasOwn(target,"registry")||Object.hasOwn(target,"packageName"))&&Object.hasOwn(target,"repoUrl")){const conflictingKeys=["registry","packageName","repoUrl"].filter((key)=>Object.hasOwn(target,key)).join(", ");throw new CodeNavigationValidationError(`CodeDiff target has conflicting present keys: ${conflictingKeys}. Target shape is determined by key presence, even when a value is undefined.`)}else{throw new CodeNavigationValidationError("CodeDiff target must be a package or repository target.")}const optionsValue=paramsRecord.options;if(optionsValue===undefined)return;const options=asRecord(optionsValue);if(!options){throw new CodeNavigationValidationError("CodeDiff options must be an object when supplied.")}for(const key of Object.keys(options)){if(!CODE_DIFF_OPTION_KEYS.has(key)){throw new CodeNavigationValidationError(`CodeDiff options contains unknown key '${key}'.`)}}validateCodeDiffIntegerOption(options.maxFiles,"maxFiles",1,300);validateCodeDiffIntegerOption(options.maxPatchBytes,"maxPatchBytes",1024,2097152);validateCodeDiffPathOption(options.pathPrefix,"pathPrefix");validateCodeDiffPathOption(options.pathGlob,"pathGlob")}function validateCodeDiffIntegerOption(value,name,minimum,maximum){if(value===undefined)return;if(typeof value!=="number"||!Number.isInteger(value)||value<minimum||value>maximum){throw new CodeNavigationValidationError(`CodeDiff ${name} must be an integer from ${minimum} through ${maximum}.`)}}function validateCodeDiffPathOption(value,name){if(value===undefined)return;if(typeof value!=="string"){throw new CodeNavigationValidationError(`CodeDiff ${name} must be a string when supplied.`)}if(value.length===0){throw new CodeNavigationValidationError(`CodeDiff ${name} must not be empty when supplied.`)}if(new TextEncoder().encode(value).byteLength>1024){throw new CodeNavigationValidationError(`CodeDiff ${name} must be at most 1024 bytes.`)}}function buildCodeDiffVariables(params){const target=params.target;const variables={};if("registry"in target){variables.registry=target.registry;variables.name=target.packageName;variables.fromVersion=params.from;variables.toVersion=params.to}else{variables.repoUrl=target.repoUrl;variables.fromRef=params.from;variables.toRef=params.to}const rawOptions=Object.fromEntries(Object.entries(params.options??{}).filter(([,value])=>value!==undefined));if(Object.keys(rawOptions).length>0)variables.rawOptions=rawOptions;return variables}function isCodeDiffRawError(error){return error.path?.some((part)=>part==="raw")??false}function normaliseCodeDiffResult(result){if(!result.raw){throw new MalformedCodeNavigationResponseError("CodeDiff response missing non-null raw result.")}return{package:normaliseCodeDiffPackage(result.package),fromResolution:normaliseCodeDiffResolution(result.fromResolution),toResolution:normaliseCodeDiffResolution(result.toResolution),raw:normaliseRawCodeDiff(result.raw)}}function normaliseCodeDiffPartial(result){return{package:normaliseCodeDiffPackage(result.package),fromResolution:normaliseCodeDiffResolution(result.fromResolution),toResolution:normaliseCodeDiffResolution(result.toResolution),raw:result.raw?normaliseRawCodeDiff(result.raw):undefined}}function normaliseCodeDiffPackage(value){if(!value)return;return{registry:value.registry,name:value.name,repoUrl:value.repoUrl}}function normaliseCodeDiffResolution(value){return{requested:value.requested,resolvedVersion:value.resolvedVersion??undefined,ref:value.ref,commitSha:value.commitSha,refKind:value.refKind,versionSource:value.versionSource??undefined}}function normaliseRawCodeDiff(value){return{summary:value.summary,scope:{status:value.scope.status,fromSubpath:value.scope.fromSubpath??undefined,toSubpath:value.scope.toSubpath??undefined,pathPrefix:value.scope.pathPrefix??undefined,pathGlob:value.scope.pathGlob??undefined},contentCoverage:value.contentCoverage,contentFailure:value.contentFailure?{code:value.contentFailure.code,retryable:value.contentFailure.retryable,retryAfterMs:value.contentFailure.retryAfterMs??undefined,stage:value.contentFailure.stage??undefined,limitKind:value.contentFailure.limitKind??undefined}:undefined,files:value.files.map((file)=>({path:file.path,pathEncoding:file.pathEncoding,status:file.status,modeChanged:file.modeChanged,typeChanged:file.typeChanged,additions:file.additions??undefined,deletions:file.deletions??undefined,patch:file.patch??undefined,contentStatus:file.contentStatus,contentOmissionReason:file.contentOmissionReason??undefined,contentSafety:{filtered:file.contentSafety.filtered,modifications:file.contentSafety.modifications}})),hasMoreFiles:value.hasMoreFiles}}function parseCodeDiffErrorDetails(errors){const extensions=getPrimaryExtensions(errors);if(!extensions)return;const details={};if(typeof extensions.code==="string")details.code=extensions.code;if(typeof extensions.retryable==="boolean"){details.retryable=extensions.retryable}if(extensions.side==="from"||extensions.side==="to"){details.side=extensions.side}const publishedVersions=parseCodeDiffStringArray(extensions.published_versions);if(publishedVersions)details.publishedVersions=publishedVersions;if(typeof extensions.published_versions_truncated==="boolean"){details.publishedVersionsTruncated=extensions.published_versions_truncated}if(typeof extensions.registry==="string"){details.registry=extensions.registry}if(typeof extensions.retry_after_ms==="number"&&Number.isInteger(extensions.retry_after_ms)&&extensions.retry_after_ms>=0){details.retryAfterMs=extensions.retry_after_ms}if(typeof extensions.stage==="string")details.stage=extensions.stage;if(typeof extensions.limit_kind==="string"){details.limitKind=extensions.limit_kind}if(typeof extensions.repo_url==="string"){details.repoUrl=extensions.repo_url}if(typeof extensions.git_ref==="string")details.gitRef=extensions.git_ref;const availableRefs=parseCodeDiffErrorRefs(extensions.available_refs);if(availableRefs)details.availableRefs=availableRefs;const suggestedRefs=parseCodeDiffErrorRefs(extensions.suggested_refs);if(suggestedRefs)details.suggestedRefs=suggestedRefs;const refKinds=parseCodeDiffStringArray(extensions.ref_kinds);if(refKinds)details.refKinds=refKinds;return Object.keys(details).length>0?details:undefined}function parseCodeDiffStringArray(value){if(!Array.isArray(value))return;if(value.some((entry)=>typeof entry!=="string"))return;return value}function parseCodeDiffErrorRefs(value){if(!Array.isArray(value))return;const refs=[];for(const entry of value){if(!entry||typeof entry!=="object"||Array.isArray(entry)){return}const record=entry;if(typeof record.ref!=="string"||record.version!==undefined&&record.version!==null&&typeof record.version!=="string"){return}refs.push({ref:record.ref,version:typeof record.version==="string"?record.version:undefined})}return refs}function parseDetail(body){if(!body)return;try{const parsed=JSON.parse(body);if(typeof parsed.detail==="string")return parsed.detail;if(typeof parsed.error==="string")return parsed.error}catch{return body}return}function buildTargetResolutionFallbackQueries(query){const withoutSuggestedRefs=query.replaceAll(TARGET_RESOLUTION_SUGGESTED_REFS_SELECTION,"").replaceAll(DISCOVERY_TARGET_PROGRESS_SUGGESTED_REFS_SELECTION,"");const candidates=[withoutSuggestedRefs,withoutSuggestedRefs.replaceAll(TARGET_RESOLUTION_AVAILABLE_REFS_SELECTION,""),withoutSuggestedRefs.replaceAll(DISCOVERY_TARGET_PROGRESS_RETRY_SELECTION,""),withoutSuggestedRefs.replaceAll(CODE_CONTEXT_AVAILABLE_VERSIONS_SELECTION,""),withoutSuggestedRefs.replaceAll(TARGET_RESOLUTION_SELECTION,"").replaceAll(DISCOVERY_TARGET_PROGRESS_RETRY_SELECTION,"").replaceAll(CODE_CONTEXT_AVAILABLE_VERSIONS_SELECTION,"")];return candidates.filter((candidate,index,all)=>candidate!==query&&all.indexOf(candidate)===index)}function hasSchemaMismatchErrors(parsedBody){if(!parsedBody||typeof parsedBody!=="object")return false;const errors=parsedBody.errors;if(!Array.isArray(errors))return false;return errors.some((entry)=>{if(!entry||typeof entry!=="object")return false;const error=entry;if(typeof error.message!=="string")return false;const code=typeof error.extensions?.code==="string"?error.extensions.code:undefined;return isGraphQLSchemaMismatchError({message:error.message,code})})}function getPrimaryExtensions(errors){for(const error of errors){if(error.extensions&&Object.keys(error.extensions).length>0){return error.extensions}}return}function getGraphQLIndexingRef(errors){for(const error of errors){const indexingRef=error.extensions?.indexing_ref??error.extensions?.indexingRef;if(typeof indexingRef==="string")return indexingRef}return}function parseAvailableVersions(extensions){const raw=extensions?.available_versions??extensions?.availableVersions;return parseAvailableArtifacts(raw)}function parseAvailableRefs(extensions){const raw=extensions?.available_refs??extensions?.availableRefs;return parseAvailableArtifacts(raw)}function parseSuggestedRefs(extensions){const raw=extensions?.suggested_refs??extensions?.suggestedRefs;return parseAvailableArtifacts(raw)}function parseGraphQLErrorMetadata(extensions,indexingEstimate){const metadata={};if(typeof extensions?.hint==="string")metadata.hint=extensions.hint;const filePath=extensions?.file_path??extensions?.filePath;if(typeof filePath==="string")metadata.filePath=filePath;const exclusionReason=extensions?.exclusion_reason??extensions?.exclusionReason;if(typeof exclusionReason==="string"){metadata.exclusionReason=exclusionReason}const availableVersions=parseAvailableVersions(extensions);if(availableVersions?.length)metadata.availableVersions=availableVersions;const availableRefs=parseAvailableRefs(extensions);if(availableRefs?.length)metadata.availableRefs=availableRefs;const suggestedRefs=parseSuggestedRefs(extensions);if(suggestedRefs?.length)metadata.suggestedRefs=suggestedRefs;const targetResolution=parseTargetResolution(extensions);if(targetResolution)metadata.targetResolution=targetResolution;if(indexingEstimate)metadata.indexingEstimate=indexingEstimate;return Object.keys(metadata).length>0?metadata:undefined}function parseGraphQLRepoUrl(extensions){return typeof extensions?.repo_url==="string"?extensions.repo_url:typeof extensions?.repoUrl==="string"?extensions.repoUrl:undefined}function parseGraphQLGitRef(extensions){return typeof extensions?.git_ref==="string"?extensions.git_ref:typeof extensions?.gitRef==="string"?extensions.gitRef:undefined}function parseTargetResolution(extensions){const raw=extensions?.target_resolution??extensions?.targetResolution;const parsed=targetResolutionSchema.safeParse(raw);if(!parsed.success)return;return normaliseTargetResolution(parsed.data)}function parseIndexingDurationEstimate(extensions){const raw=extensions?.estimated_indexing_duration??extensions?.estimatedIndexingDuration??extensions?.indexing_estimate??extensions?.indexingEstimate;const parsed=indexingDurationEstimateSchema.safeParse(normaliseRawIndexingDurationEstimate(raw));if(!parsed.success)return;return normaliseIndexingDurationEstimate(parsed.data)}function normaliseRawIndexingDurationEstimate(raw){if(!raw||typeof raw!=="object"||Array.isArray(raw))return raw;const record=raw;return{lowerSeconds:record.lowerSeconds??record.lower_seconds,upperSeconds:record.upperSeconds??record.upper_seconds,elapsedSeconds:record.elapsedSeconds??record.elapsed_seconds,sampleCount:record.sampleCount??record.sample_count,source:record.source}}function normaliseIndexingDurationEstimate(estimate){if(!estimate)return;const out={};if(typeof estimate.lowerSeconds==="number"){out.lowerSeconds=estimate.lowerSeconds}if(typeof estimate.upperSeconds==="number"){out.upperSeconds=estimate.upperSeconds}if(typeof estimate.elapsedSeconds==="number"){out.elapsedSeconds=estimate.elapsedSeconds}if(typeof estimate.sampleCount==="number"){out.sampleCount=estimate.sampleCount}if(typeof estimate.source==="string")out.source=estimate.source;return Object.keys(out).length>0?out:undefined}function appendIndexingWaitHint(message,backendHint){const hintAlreadyInMessage=Boolean(backendHint&&message.includes(backendHint));const existingGuidance=`${message} ${backendHint??""}`;if(/(?:--wait\b|wait_timeout_ms|waitTimeoutMs)/i.test(existingGuidance)){return hintAlreadyInMessage?undefined:backendHint}return backendHint&&!hintAlreadyInMessage?`${backendHint} ${INDEXING_WAIT_HINT}`:INDEXING_WAIT_HINT}function parseAvailableArtifacts(raw){if(!Array.isArray(raw))return;const parsed=[];for(const item of raw){if(item&&typeof item==="object"&&"ref"in item){const entry=item;if(typeof entry.ref==="string"){parsed.push({ref:entry.ref,version:typeof entry.version==="string"?entry.version:undefined})}}}return parsed.length>0?parsed:undefined}function normaliseAvailableVersions(entries){if(!entries||entries.length===0)return;return entries.map((entry)=>({version:entry.version??undefined,ref:entry.ref}))}function normaliseTargetResolution(resolution){if(!resolution)return;return{requested:normaliseTargetResolutionIdentity(resolution.requested),resolvedRequested:normaliseTargetResolutionIdentity(resolution.resolvedRequested),served:normaliseTargetResolutionIdentity(resolution.served),freshness:resolution.freshness??undefined,freshnessReason:resolution.freshnessReason??undefined,indexingRef:resolution.indexingRef??undefined,availableVersions:normaliseAvailableVersions(resolution.availableVersions)??[],availableRefs:normaliseAvailableVersions(resolution.availableRefs)??[],suggestedRefs:normaliseAvailableVersions(resolution.suggestedRefs)??[]}}function normaliseDocCoverage(coverage,options={}){if(!coverage)return;if(coverage.coverageState==="NONE"&&!options.preserveNone){return}const out={coverageState:coverage.coverageState};if(coverage.coverageReason)out.coverageReason=coverage.coverageReason;if(typeof coverage.pagesCrawled==="number"){out.pagesCrawled=coverage.pagesCrawled}if(typeof coverage.frontierRemaining==="number"||coverage.frontierRemaining===null){out.frontierRemaining=coverage.frontierRemaining}if(typeof coverage.artifactOverflowPageCount==="number"){out.artifactOverflowPageCount=coverage.artifactOverflowPageCount}if(typeof coverage.estimatedTotalPages==="number"){out.estimatedTotalPages=coverage.estimatedTotalPages}if(coverage.note)out.note=coverage.note;return out}function normaliseTargetResolutionIdentity(identity){if(!identity)return;const out={};if(identity.kind)out.kind=identity.kind;if(identity.registry)out.registry=identity.registry;if(identity.packageName)out.packageName=identity.packageName;if(identity.version)out.version=identity.version;if(identity.repoUrl)out.repoUrl=identity.repoUrl;if(identity.gitRef)out.gitRef=identity.gitRef;if(identity.commitSha)out.commitSha=identity.commitSha;if(identity.site)out.site=identity.site;return Object.keys(out).length>0?out:undefined}function isAuthMessage(message){const lower=message.toLowerCase();return lower.includes("unauthorized")||lower.includes("forbidden")||lower.includes("permission")||lower.includes("authentication")}function normaliseTargetMode(value){if(value==="PACKAGES"||value==="REPO"||value==="MIXED"||value==="SITES"||value==="SITE"){return value}return}function normaliseRequestedRefKind(value){switch(value){case"OMITTED_VERSION":case"LATEST_VERSION":case"EXACT_VERSION":case"DEFAULT_BRANCH":case"HEAD":case"BRANCH":case"SHA":return value;default:return}}function normaliseProgressFilters(filters){if(!filters)return;const out={};if(filters.fileIntent)out.fileIntent=filters.fileIntent;if(filters.kind)out.kind=filters.kind;if(filters.category)out.category=filters.category;if(typeof filters.publicOnly==="boolean"){out.publicOnly=filters.publicOnly}if(filters.pathPrefix)out.pathPrefix=filters.pathPrefix;return Object.keys(out).length>0?out:undefined}function isTargetNotFoundMessage(message){const lower=message.toLowerCase();return lower.includes("not found")||lower.includes("unknown package")||lower.includes("no such package")||lower.includes("does not exist")}function isUnresolvableMessage(message){const lower=message.toLowerCase();return lower.includes("could not resolve")||lower.includes("cannot resolve")}import{z as z3}from"zod";function promoteGenericVersionNotFound(error,params){if(!(error instanceof PackageIntelligenceBackendError))return error;if(error.graphqlCode!==undefined)return error;const requestedVersion=pickRequestedVersion(params);if(!requestedVersion)return error;if(!/no matching version/i.test(error.message))return error;const qualifiedName=synthesizeQualifiedName(params);return new PackageIntelligenceVersionNotFoundError(error.message,qualifiedName,requestedVersion,undefined)}function pickRequestedVersion(params){if(params.version)return params.version;if(params.fromVersion)return params.fromVersion;if(params.toVersion)return params.toVersion;return}function synthesizeQualifiedName(params){if(!params.registry||!params.packageName)return;return`${params.registry.toLowerCase()}:${params.packageName}`}class PackageIntelligenceAccessError extends Error{constructor(message){super(message);this.name="PackageIntelligenceAccessError"}}class PackageIntelligenceFeatureFlagRequiredError extends Error{constructor(message){super(message);this.name="PackageIntelligenceFeatureFlagRequiredError"}}class PackageIntelligenceNetworkError extends Error{constructor(message,options){super(message,options);this.name="PackageIntelligenceNetworkError"}}class PackageIntelligenceBackendError extends Error{status;graphqlCode;retryable;constructor(message,status,graphqlCode,retryable){super(message);this.status=status;this.graphqlCode=graphqlCode;this.retryable=retryable;this.name="PackageIntelligenceBackendError"}}class PackageIntelligenceGraphQLError extends Error{code;constructor(message,code){super(message);this.code=code;this.name="PackageIntelligenceGraphQLError"}}class PackageIntelligenceTargetNotFoundError extends Error{constructor(message){super(message);this.name="PackageIntelligenceTargetNotFoundError"}}class PackageIntelligenceValidationError extends Error{constructor(message){super(message);this.name="PackageIntelligenceValidationError"}}class PackageIntelligenceVersionNotFoundError extends Error{packageName;requestedVersion;availableVersions;constructor(message,packageName,requestedVersion,availableVersions){super(message);this.packageName=packageName;this.requestedVersion=requestedVersion;this.availableVersions=availableVersions;this.name="PackageIntelligenceVersionNotFoundError"}}class MalformedPackageIntelligenceResponseError extends Error{constructor(message){super(message);this.name="MalformedPackageIntelligenceResponseError"}}class PackageIntelligenceChangelogSourceNotFoundError extends Error{constructor(message){super(message);this.name="PackageIntelligenceChangelogSourceNotFoundError"}}var githubRepositorySchema=z3.object({stargazersCount:z3.number().int().nullable().optional(),forksCount:z3.number().int().nullable().optional(),openIssuesCount:z3.number().int().nullable().optional(),archived:z3.boolean().nullable().optional(),language:z3.string().nullable().optional(),topics:z3.array(z3.string()).nullable().optional(),pushedAt:z3.string().nullable().optional()}).nullable().optional();var packageIdentitySchema=z3.object({name:z3.string().nullable().optional(),registry:z3.string().nullable().optional(),description:z3.string().nullable().optional(),latestVersion:z3.string().nullable().optional(),latestVersionPublishedAt:z3.string().nullable().optional(),homepage:z3.string().nullable().optional(),repositoryUrl:z3.string().nullable().optional(),license:z3.string().nullable().optional(),downloadsLastMonth:z3.number().int().nullable().optional(),downloadsTotal:z3.number().int().nullable().optional(),githubRepository:githubRepositorySchema});var vulnerabilityOverviewSchema=z3.object({osvId:z3.string().nullable().optional(),summary:z3.string().nullable().optional(),severityScore:z3.number().nullable().optional(),publishedAt:z3.string().nullable().optional()});var packageSecurityOverviewSchema=z3.object({vulnerabilityCount:z3.number().int().nullable().optional(),hasCurrentVulnerabilities:z3.boolean().nullable().optional(),recentVulnerabilities:z3.array(vulnerabilityOverviewSchema).nullable().optional()}).nullable().optional();var changelogEntrySchema=z3.object({version:z3.string().nullable().optional(),publishedAt:z3.string().nullable().optional(),body:z3.string().nullable().optional()});var packageSummaryResponseSchema=z3.object({package:packageIdentitySchema.nullable().optional(),security:packageSecurityOverviewSchema,latestChangelogs:z3.array(changelogEntrySchema).nullable().optional()});var graphQLErrorSchema2=z3.object({message:z3.string(),extensions:z3.record(z3.string(),z3.unknown()).optional()});var graphQLResponseSchema=z3.object({data:z3.object({packageSummary:packageSummaryResponseSchema.nullable().optional()}).nullable().optional(),errors:z3.array(graphQLErrorSchema2).optional()});var PACKAGE_SUMMARY_QUERY=`
624
+ }`}var unifiedSearchGraphQLResponseSchema=z2.object({data:z2.object({search:asyncUnifiedSearchResultSchema.nullable().optional()}).nullable().optional(),errors:z2.array(graphQLErrorSchema).optional()});var unifiedSearchStatusGraphQLResponseSchema=z2.object({data:z2.object({discoverySearchProgress:unifiedSearchProgressSchema.nullable().optional()}).nullable().optional(),errors:z2.array(graphQLErrorSchema).optional()});class CodeNavigationServiceImpl{codeNavigationUrl;tokenProvider;fetchFn;runtime;constructor(codeNavigationUrl,tokenProvider,fetchFn=globalThis.fetch,runtime={}){this.codeNavigationUrl=codeNavigationUrl;this.tokenProvider=tokenProvider;this.fetchFn=fetchFn;this.runtime=runtime}async postGraphqlWithTargetResolutionFallback(input){const response=await postPkgseerGraphql({endpointUrl:this.codeNavigationUrl,token:input.token,query:input.query,variables:input.variables,fetchFn:this.fetchFn,clientHeaders:this.runtime.clientHeaders,userAgent:this.runtime.userAgent,diagnostics:this.runtime.diagnostics});if(response.status<200||response.status>=300)return response;if(!hasSchemaMismatchErrors(response.parsedBody))return response;for(const fallbackQuery of buildTargetResolutionFallbackQueries(input.query)){if(this.runtime.diagnostics?.isEnabled("code-nav")){this.runtime.diagnostics.debug("code-nav",{event:"target-resolution-query-fallback"})}const fallbackResponse=await postPkgseerGraphql({endpointUrl:this.codeNavigationUrl,token:input.token,query:fallbackQuery,variables:input.variables,fetchFn:this.fetchFn,clientHeaders:this.runtime.clientHeaders,userAgent:this.runtime.userAgent,diagnostics:this.runtime.diagnostics});if(!hasSchemaMismatchErrors(fallbackResponse.parsedBody)){return fallbackResponse}}return response}async search(params){return executeWithTokenRefresh({getToken:()=>this.tokenProvider.getToken(),forceRefresh:()=>this.tokenProvider.forceRefresh(),shouldRefresh:isTokenRefreshableError,executeWithToken:(token)=>this.executeUnifiedSearch(token,params)})}async searchStatus(searchRef,waitTimeoutMs=0){return executeWithTokenRefresh({getToken:()=>this.tokenProvider.getToken(),forceRefresh:()=>this.tokenProvider.forceRefresh(),shouldRefresh:isTokenRefreshableError,executeWithToken:(token)=>this.executeUnifiedSearchStatus(token,searchRef,waitTimeoutMs)})}async codeDiff(params){validateCodeDiffParams(params);return executeWithTokenRefresh({getToken:()=>this.tokenProvider.getToken(),forceRefresh:()=>this.tokenProvider.forceRefresh(),shouldRefresh:isTokenRefreshableError,executeWithToken:(token)=>this.executeCodeDiff(token,params)})}async executeCodeDiff(token,params){const query=buildCodeDiffQuery(params.mode);const variables=buildCodeDiffVariables(params);debugGraphqlWireRequest("codeDiff",query,variables,this.runtime.diagnostics);let response;try{response=await this.postGraphqlWithTargetResolutionFallback({token,query,variables})}catch(cause){if(cause instanceof PkgseerTransportError){throw this.createTransportError(cause)}throw cause}if(response.status<200||response.status>=300){throw this.createHttpError(response)}const parsed=codeDiffGraphQLResponseSchema.safeParse(response.parsedBody);if(!parsed.success){throw new MalformedCodeNavigationResponseError("Malformed response from code navigation service.")}const data=parsed.data.data?.codeDiff;const errors=parsed.data.errors??[];if(errors.length>0){const rawErrors=errors.filter(isCodeDiffRawError);if(rawErrors.length>0){throw new CodeDiffError(rawErrors.map((error)=>error.message).join(", "),parseCodeDiffErrorDetails(rawErrors),data?normaliseCodeDiffPartial(data):undefined)}throw this.createCodeDiffRootError(errors)}if(!data?.raw){throw new MalformedCodeNavigationResponseError("CodeDiff response missing non-null raw result.")}return normaliseCodeDiffResult(data)}createCodeDiffRootError(errors){const graphQLErrors=errors.map(({message:message2,extensions:extensions2})=>({message:message2,extensions:extensions2}));const message=errors.map((error)=>error.message).join(", ");const extensions=getPrimaryExtensions(errors);const code=typeof extensions?.code==="string"?extensions.code:undefined;if(code==="AUTHENTICATION_REQUIRED"){return new AuthenticationError(SERVER_AUTHENTICATION_REJECTED_MESSAGE,"server")}if(code==="UNAUTHORIZED"||code==="FORBIDDEN"||code==="FEATURE_FLAG_REQUIRED"||isClientUpdateRequiredGraphQLError({message,code})||isGraphQLSchemaMismatchError({message,code})||code===undefined&&isAuthMessage(message)){return this.createGraphQLError(graphQLErrors)}return new CodeDiffError(message,parseCodeDiffErrorDetails(errors))}async executeUnifiedSearch(token,params){if(params.targets.length===0){throw new CodeNavigationValidationError("At least one search target is required.")}let response;const variables={targets:params.targets.map((target)=>({registry:target.registry,name:target.packageName,version:target.version,repoUrl:target.repoUrl,gitRef:target.gitRef,site:target.site})),query:params.query,sources:params.sources,filters:params.filters,allowPartialResults:params.allowPartialResults??false,limit:params.limit,offset:params.offset,waitTimeoutMs:params.waitTimeoutMs};debugUnifiedSearchRequest(variables,this.runtime.diagnostics);debugGraphqlWireRequest("search",UNIFIED_SEARCH_QUERY,variables,this.runtime.diagnostics);try{response=await this.postGraphqlWithTargetResolutionFallback({token,query:UNIFIED_SEARCH_QUERY,variables})}catch(cause){if(cause instanceof PkgseerTransportError){throw this.createTransportError(cause)}throw cause}if(response.status<200||response.status>=300){throw this.createHttpError(response)}const parsed=unifiedSearchGraphQLResponseSchema.safeParse(response.parsedBody);if(!parsed.success){throw new MalformedCodeNavigationResponseError("Malformed response from code navigation service.")}if(parsed.data.errors&&parsed.data.errors.length>0){throw this.createGraphQLError(parsed.data.errors)}const data=parsed.data.data?.search;if(!data){throw new MalformedCodeNavigationResponseError("Malformed response from code navigation service.")}return this.normaliseUnifiedSearchOutcome(data)}async executeUnifiedSearchStatus(token,searchRef,waitTimeoutMs){let response;try{response=await this.postGraphqlWithTargetResolutionFallback({token,query:UNIFIED_SEARCH_STATUS_QUERY,variables:{searchRef,includeResults:true,waitTimeoutMs}})}catch(cause){if(cause instanceof PkgseerTransportError){throw this.createTransportError(cause)}throw cause}if(response.status<200||response.status>=300){throw this.createHttpError(response)}const parsed=unifiedSearchStatusGraphQLResponseSchema.safeParse(response.parsedBody);if(!parsed.success){throw new MalformedCodeNavigationResponseError("Malformed response from code navigation service.")}if(parsed.data.errors&&parsed.data.errors.length>0){throw this.createGraphQLError(parsed.data.errors)}const data=parsed.data.data?.discoverySearchProgress;if(!data){throw new MalformedCodeNavigationResponseError("Malformed response from code navigation service.")}const progress=this.normaliseUnifiedSearchProgress(data);const result=data.results?this.normaliseUnifiedSearchResult(data.results):undefined;if(result&&progress.status==="COMPLETED"){return{state:"completed",completed:true,searchRef:progress.searchRef,result,progress}}return{state:"incomplete",completed:false,searchRef:progress.searchRef,result,progress}}createHttpError(response){const status=response.status;const detail=parseDetail(response.responseBody);if(status===401){return new AuthenticationError(SERVER_AUTHENTICATION_REJECTED_MESSAGE,"server")}if(status===403){return new CodeNavigationAccessError(detail??"Code navigation access denied.")}if(status>=500){return new CodeNavigationBackendError(detail?`Server error (${status}): ${detail}`:`Server error (${status})`,status)}return new CodeNavigationBackendError(detail??`Request failed with status ${status}`,status)}createTransportError(error){if(isFetchTimeoutError(error.cause)){return new CodeNavigationBackendError("Code navigation request timed out.",undefined,"TIMEOUT",true)}return new CodeNavigationNetworkError("Could not reach the code navigation service. Check your connection or set GITHITS_CODE_NAV_URL.",{cause:error})}createGraphQLError(errors){const message=errors.map((error)=>error.message).join(", ");const extensions=getPrimaryExtensions(errors);const code=typeof extensions?.code==="string"?extensions.code:undefined;const retryable=typeof extensions?.retryable==="boolean"?extensions.retryable:undefined;const indexingRef=getGraphQLIndexingRef(errors);const indexingEstimate=parseIndexingDurationEstimate(extensions);const errorMetadata=parseGraphQLErrorMetadata(extensions,indexingEstimate);if(isClientUpdateRequiredGraphQLError({message,code})){return new ClientUpdateRequiredError(undefined,undefined,this.runtime.clientVersion)}if(isGraphQLSchemaMismatchError({message,code})){const sanitized="Backend protocol mismatch. Your CLI may be newer than the server, or the server may require a newer CLI. Run `githits update-check` to verify your installed version. Set GITHITS_DEBUG=code-nav-wire to inspect GraphQL details during local development.";if(this.runtime.diagnostics?.isEnabled("code-nav")){this.runtime.diagnostics.debug("code-nav",{event:"graphql-schema-mismatch",code:code??"omitted",message})}return new CodeNavigationBackendError(this.runtime.diagnostics?.isEnabled("code-nav-wire")?message:sanitized,undefined,code,retryable)}switch(code){case"PACKAGE_INDEXING":return new CodeNavigationIndexingError(message,indexingRef,parseAvailableVersions(extensions),parseAvailableRefs(extensions),parseTargetResolution(extensions),indexingEstimate,appendIndexingWaitHint(message,typeof extensions?.hint==="string"?extensions.hint:undefined));case"GREP_PATTERN_TOO_SHORT":case"GREP_PATTERN_TOO_LONG":case"GREP_PATTERN_INVALID":case"GREP_INVALID_REGEX":case"GREP_UNSUPPORTED_PATTERN":case"GREP_PATTERN_TOO_UNSELECTIVE":case"GREP_SCOPE_REQUIRED":case"GREP_SELECTOR_INVALID":case"GREP_CURSOR_INVALID":case"GREP_CONTEXT_TOO_LARGE":case"GREP_CONTEXT_NEGATIVE":case"GREP_MAX_MATCHES_TOO_LARGE":case"GREP_MAX_MATCHES_INVALID":return new CodeNavigationValidationError(message);case"VERSION_NOT_FOUND":return new CodeNavigationVersionNotFoundError(message,typeof extensions?.package==="string"?extensions.package:undefined,typeof extensions?.requested_version==="string"?extensions.requested_version:undefined,typeof extensions?.latest_indexed==="string"?extensions.latest_indexed:undefined,parseAvailableVersions(extensions),errorMetadata);case"REF_NOT_FOUND":return new CodeNavigationRefNotFoundError(message,parseGraphQLRepoUrl(extensions),parseGraphQLGitRef(extensions),parseAvailableRefs(extensions),parseSuggestedRefs(extensions),errorMetadata);case"NOT_FOUND":case"PACKAGE_NOT_FOUND":case"NO_REPOSITORY_URL":return new CodeNavigationTargetNotFoundError(message,parseAvailableVersions(extensions),parseGraphQLRepoUrl(extensions),parseGraphQLGitRef(extensions),errorMetadata);case"REPOSITORY_NOT_FOUND":return new CodeNavigationTargetNotFoundError(message,undefined,parseGraphQLRepoUrl(extensions),parseGraphQLGitRef(extensions),errorMetadata);case"FILE_NOT_FOUND":return new CodeNavigationFileNotFoundError(message,typeof extensions?.file_path==="string"?extensions.file_path:typeof extensions?.filePath==="string"?extensions.filePath:undefined);case"UNSUPPORTED_REGISTRY":case"VALIDATION_ERROR":return new CodeNavigationValidationError(message);case"FEATURE_FLAG_REQUIRED":return new CodeNavigationFeatureFlagRequiredError(message);case"UNAUTHORIZED":return new AuthenticationError(SERVER_AUTHENTICATION_REJECTED_MESSAGE,"server");case"FORBIDDEN":return new CodeNavigationAccessError("Code navigation access denied. This feature may not be enabled for your account.");case"UPSTREAM_ERROR":case"TIMEOUT":case"RATE_LIMITED":case"GREP_FILE_TOO_LARGE":case"GREP_TIMEOUT":case"GREP_SERVICE_UNAVAILABLE":case"GREP_FAILED":case"GREP_INDEX_NOT_AVAILABLE":case"FILE_PATH_EXCLUDED":case"SOURCE_FILE_INVENTORY_UNKNOWN":case"INTERNAL_ERROR":case"UNKNOWN_ERROR":return new CodeNavigationBackendError(message,undefined,code,retryable,errorMetadata);default:break}if(code===undefined){if(isAuthMessage(message)){return new CodeNavigationAccessError("Code navigation access denied. This feature may not be enabled for your account.")}if(isUnresolvableMessage(message)){return new CodeNavigationUnresolvableError(message)}if(isTargetNotFoundMessage(message)){return new CodeNavigationTargetNotFoundError(message,parseAvailableVersions(extensions),parseGraphQLRepoUrl(extensions),parseGraphQLGitRef(extensions),errorMetadata)}}return new CodeNavigationBackendError(message,undefined,code,retryable,errorMetadata)}normaliseUnifiedSearchOutcome(data){const progress=data.progress?this.normaliseUnifiedSearchProgress(data.progress):undefined;if(data.completed){if(!data.result){throw new MalformedCodeNavigationResponseError("Completed unified search response missing result payload.")}return{state:"completed",completed:true,searchRef:data.searchRef??undefined,result:this.normaliseUnifiedSearchResult(data.result),progress}}const searchRef=data.searchRef??progress?.searchRef;if(!searchRef){throw new MalformedCodeNavigationResponseError("Incomplete unified search response missing search reference.")}const result=data.result?this.normaliseUnifiedSearchResult(data.result):undefined;return{state:"incomplete",completed:false,searchRef,result,progress}}normaliseUnifiedSearchResult(result){return{query:result.query,queryWarnings:result.queryWarnings,sources:result.sources,results:result.results.map((entry)=>({id:entry.id,resultType:entry.resultType,targetLabel:entry.targetLabel,requestedTargetLabel:entry.requestedTargetLabel??undefined,freshTargetLabel:entry.freshTargetLabel??undefined,servedTargetLabel:entry.servedTargetLabel??undefined,freshness:entry.freshness??undefined,title:entry.title??undefined,summary:entry.summary??undefined,score:entry.score??undefined,highlights:entry.highlights?{title:entry.highlights.title??undefined,summary:entry.highlights.summary??undefined}:undefined,locator:{registry:entry.locator.registry??undefined,packageName:entry.locator.packageName??undefined,version:entry.locator.version??undefined,pageId:entry.locator.pageId??undefined,sourceKind:entry.locator.sourceKind??undefined,sourceUrl:entry.locator.sourceUrl??undefined,repoUrl:entry.locator.repoUrl??undefined,gitRef:entry.locator.gitRef??undefined,requestedRef:entry.locator.requestedRef??undefined,filePath:entry.locator.filePath??undefined,startLine:entry.locator.startLine??undefined,endLine:entry.locator.endLine??undefined,fileContentHash:entry.locator.fileContentHash??undefined,symbolRef:entry.locator.symbolRef??undefined,qualifiedPath:entry.locator.qualifiedPath??undefined,kind:entry.locator.kind??undefined,category:entry.locator.category??undefined,language:entry.locator.language??undefined}})),page:{offset:result.page.offset,limit:result.page.limit,returned:result.page.returned,hasMore:result.page.hasMore},partialResults:result.partialResults,sourceStatus:result.sourceStatus.map((entry)=>({source:entry.source,targetLabel:entry.targetLabel,requestedTargetLabel:entry.requestedTargetLabel??undefined,freshTargetLabel:entry.freshTargetLabel??undefined,servedTargetLabel:entry.servedTargetLabel??undefined,targetResolution:normaliseTargetResolution(entry.targetResolution),indexingStatus:entry.indexingStatus??undefined,codeIndexState:entry.codeIndexState??undefined,resultCount:entry.resultCount??undefined,appliedFilters:entry.appliedFilters,ignoredFilters:entry.ignoredFilters,incompatibleFilters:entry.incompatibleFilters,appliedQueryFeatures:entry.appliedQueryFeatures,ignoredQueryFeatures:entry.ignoredQueryFeatures,incompatibleQueryFeatures:entry.incompatibleQueryFeatures,suggestedSiteTargets:entry.suggestedSiteTargets,suggestedSiteTargetsTruncated:entry.suggestedSiteTargetsTruncated,note:entry.note??undefined,coverage:normaliseDocCoverage(entry.coverage),contributors:entry.contributors.map((contributor)=>({kind:contributor.kind,state:contributor.state,freshness:contributor.freshness??undefined,resultCount:contributor.resultCount,repositoryUrl:contributor.repositoryUrl??undefined,commitSha:contributor.commitSha??undefined,siteKey:contributor.siteKey??undefined,siteUrl:contributor.siteUrl??undefined,coverage:normaliseDocCoverage(contributor.coverage,{preserveNone:true})}))})),evidenceNotice:result.evidenceNotice??undefined}}normaliseUnifiedSearchProgress(progress){return{searchRef:progress.searchRef,status:progress.status,targetsTotal:progress.targetsTotal,targetsReady:progress.targetsReady,elapsedMs:progress.elapsedMs,query:progress.query,queryWarnings:progress.queryWarnings,sources:progress.sources,requestedSources:progress.requestedSources??undefined,targetMode:normaliseTargetMode(progress.targetMode),requestedTargets:progress.requestedTargets?.map((target)=>({registry:target.registry?target.registry:undefined,name:target.name??undefined,version:target.version??undefined,repoUrl:target.repoUrl??undefined,gitRef:target.gitRef??undefined,site:target.site??undefined})),filters:normaliseProgressFilters(progress.filters),limit:progress.limit??undefined,offset:progress.offset??undefined,targets:progress.targets?.map((target)=>({requested:target.requested??undefined,resolvedRequested:target.resolvedRequested??undefined,served:target.served??undefined,freshness:target.freshness??undefined,indexingRef:target.indexingRef??undefined,requestedRefKind:normaliseRequestedRefKind(target.requestedRefKind),targetResolution:normaliseTargetResolution(target.targetResolution),availableVersions:normaliseAvailableVersions(target.availableVersions),availableRefs:normaliseAvailableVersions(target.availableRefs),suggestedRefs:normaliseAvailableVersions(target.suggestedRefs),coverage:normaliseDocCoverage(target.coverage)})),expiresAt:progress.expiresAt??undefined}}throwIfIndexing(data){if(data.codeIndexState==="INDEXING"){const targetResolution=normaliseTargetResolution(data.targetResolution);const indexingEstimate=normaliseIndexingDurationEstimate(data.indexingEstimate);throw new CodeNavigationIndexingError(`Target is indexing. ${INDEXING_WAIT_HINT}`,data.indexingRef??targetResolution?.indexingRef,normaliseAvailableVersions(data.availableVersions)??targetResolution?.availableVersions,targetResolution?.availableRefs,targetResolution,indexingEstimate)}}async listFiles(params){return executeWithTokenRefresh({getToken:()=>this.tokenProvider.getToken(),forceRefresh:()=>this.tokenProvider.forceRefresh(),shouldRefresh:isTokenRefreshableError,executeWithToken:(token)=>this.executeListFiles(token,params)})}async executeListFiles(token,params){let response;try{response=await this.postGraphqlWithTargetResolutionFallback({token,query:LIST_REPO_FILES_QUERY,variables:{registry:params.target.registry,packageName:params.target.packageName,repoUrl:params.target.repoUrl,gitRef:params.target.gitRef,version:params.target.version,pathPrefix:params.pathPrefix,pathSelectors:params.pathSelectors?.map((entry)=>({kind:entry.kind,value:entry.value})),extensions:params.extensions,fileTypes:params.fileTypes,languages:params.languages,fileIntent:params.fileIntent,fileIntents:params.fileIntents,excludeFileIntents:params.excludeFileIntents,excludeDocFiles:params.excludeDocFiles,excludeTestFiles:params.excludeTestFiles,includeHidden:params.includeHidden,limit:params.limit,waitTimeoutMs:params.waitTimeoutMs}})}catch(cause){if(cause instanceof PkgseerTransportError){throw this.createTransportError(cause)}throw cause}if(response.status<200||response.status>=300){throw this.createHttpError(response)}const parsed=listRepoFilesGraphQLResponseSchema.safeParse(response.parsedBody);if(!parsed.success){throw new MalformedCodeNavigationResponseError("Malformed response from code navigation service.")}if(parsed.data.errors&&parsed.data.errors.length>0){throw this.createGraphQLError(parsed.data.errors)}const data=parsed.data.data?.listRepoFiles;if(!data){throw new MalformedCodeNavigationResponseError("Malformed response from code navigation service.")}this.throwIfIndexing(data);return{files:data.files.map((entry)=>({path:entry.path,name:entry.name??undefined,language:entry.language??undefined,fileType:entry.fileType??undefined,byteSize:entry.byteSize??undefined})),total:data.total,hasMore:data.hasMore,indexedVersion:data.indexedVersion??undefined,resolution:data.resolution?{requestedVersion:data.resolution.requestedVersion??undefined,requestedRef:data.resolution.requestedRef??undefined,resolvedRef:data.resolution.resolvedRef??undefined,commitSha:data.resolution.commitSha??undefined}:undefined,targetResolution:normaliseTargetResolution(data.targetResolution),hint:data.diagnostics?.hint??undefined}}async readFile(params){return executeWithTokenRefresh({getToken:()=>this.tokenProvider.getToken(),forceRefresh:()=>this.tokenProvider.forceRefresh(),shouldRefresh:isTokenRefreshableError,executeWithToken:(token)=>this.executeReadFile(token,params)})}async executeReadFile(token,params){let response;try{response=await this.postGraphqlWithTargetResolutionFallback({token,query:FETCH_CODE_CONTEXT_QUERY,variables:{registry:params.target.registry,packageName:params.target.packageName,repoUrl:params.target.repoUrl,gitRef:params.target.gitRef,version:params.target.version,filePath:params.filePath,startLine:params.startLine,endLine:params.endLine,waitTimeoutMs:params.waitTimeoutMs}})}catch(cause){if(cause instanceof PkgseerTransportError){throw this.createTransportError(cause)}throw cause}if(response.status<200||response.status>=300){throw this.createHttpError(response)}const parsed=fetchCodeContextGraphQLResponseSchema.safeParse(response.parsedBody);if(!parsed.success){throw new MalformedCodeNavigationResponseError("Malformed response from code navigation service.")}if(parsed.data.errors&&parsed.data.errors.length>0){throw this.createGraphQLError(parsed.data.errors)}const data=parsed.data.data?.fetchCodeContext;if(!data){throw new MalformedCodeNavigationResponseError("Malformed response from code navigation service.")}this.throwIfIndexing(data);return{filePath:data.filePath??undefined,language:data.language??undefined,totalLines:data.totalLines??undefined,startLine:data.startLine??undefined,endLine:data.endLine??undefined,content:data.content??undefined,isBinary:data.isBinary??undefined,targetResolution:normaliseTargetResolution(data.targetResolution),availableVersions:normaliseAvailableVersions(data.availableVersions)}}async grepRepo(params){return executeWithTokenRefresh({getToken:()=>this.tokenProvider.getToken(),forceRefresh:()=>this.tokenProvider.forceRefresh(),shouldRefresh:isTokenRefreshableError,executeWithToken:(token)=>this.executeGrepRepo(token,params)})}async executeGrepRepo(token,params){let response;try{response=await this.postGraphqlWithTargetResolutionFallback({token,query:buildGrepRepoQuery(params.symbolFields),variables:{registry:params.target.registry,packageName:params.target.packageName,repoUrl:params.target.repoUrl,gitRef:params.target.gitRef,version:params.target.version,waitTimeoutMs:params.waitTimeoutMs,pattern:params.pattern,patternType:params.patternType,caseSensitive:params.caseSensitive,pathSelectors:params.pathSelectors?.map((entry)=>({kind:entry.kind,value:entry.value})),extensions:params.extensions,excludeDocFiles:params.excludeDocFiles,excludeTestFiles:params.excludeTestFiles,allowUnscoped:params.allowUnscoped,contextLinesBefore:params.contextLinesBefore,contextLinesAfter:params.contextLinesAfter,maxMatches:params.maxMatches,maxMatchesPerFile:params.maxMatchesPerFile,cursor:params.cursor,symbolFields:params.symbolFields}})}catch(cause){if(cause instanceof PkgseerTransportError){throw this.createTransportError(cause)}throw cause}if(response.status<200||response.status>=300){throw this.createHttpError(response)}const parsed=grepRepoGraphQLResponseSchema.safeParse(response.parsedBody);if(!parsed.success){throw new MalformedCodeNavigationResponseError("Malformed response from code navigation service.")}if(parsed.data.errors&&parsed.data.errors.length>0){throw this.createGraphQLError(parsed.data.errors)}const data=parsed.data.data?.grepRepo;if(!data){throw new MalformedCodeNavigationResponseError("Malformed response from code navigation service.")}this.throwIfIndexing(data);return{matches:data.matches.map((entry)=>({filePath:entry.filePath,line:entry.line,matchStartByte:entry.matchStartByte,matchEndByte:entry.matchEndByte,lineContent:entry.lineContent,contextBefore:entry.contextBefore??undefined,contextAfter:entry.contextAfter??undefined,fileContentHash:entry.fileContentHash??undefined,fileIntent:entry.fileIntent??undefined,symbolRowId:entry.symbolRowId??undefined,symbol:entry.symbol?{symbolRef:entry.symbol.symbolRef,name:entry.symbol.name,qualifiedPath:entry.symbol.qualifiedPath??undefined,kind:entry.symbol.kind??undefined,category:entry.symbol.category??undefined,arity:entry.symbol.arity??undefined,isPublic:entry.symbol.isPublic??undefined,filePath:entry.symbol.filePath??undefined,startLine:entry.symbol.startLine??undefined,endLine:entry.symbol.endLine??undefined,code:entry.symbol.code??undefined,callerCount:entry.symbol.callerCount??undefined,contentHash:entry.symbol.contentHash??undefined,parentSymbolRef:entry.symbol.parentSymbolRef??undefined,parentPath:entry.symbol.parentPath??undefined}:undefined})),nextCursor:data.nextCursor??undefined,hasMore:data.hasMore,truncatedReason:data.truncatedReason,routeTaken:data.routeTaken??undefined,filesScanned:data.filesScanned,filesInScope:data.filesInScope,binaryFilesSkipped:data.binaryFilesSkipped,filesTooLargeSkipped:data.filesTooLargeSkipped,totalMatches:data.totalMatches,uniqueFilesMatched:data.uniqueFilesMatched,indexedVersion:data.indexedVersion??undefined,resolution:data.resolution?{requestedVersion:data.resolution.requestedVersion??undefined,requestedRef:data.resolution.requestedRef??undefined,resolvedRef:data.resolution.resolvedRef??undefined,commitSha:data.resolution.commitSha??undefined}:undefined,targetResolution:normaliseTargetResolution(data.targetResolution)}}}function validateCodeDiffParams(params){const paramsRecord=asRecord(params);if(!paramsRecord){throw new CodeNavigationValidationError("CodeDiff params must be an object.")}if(paramsRecord.mode!=="inventory"&&paramsRecord.mode!=="stats"&&paramsRecord.mode!=="patches"){throw new CodeNavigationValidationError("CodeDiff mode must be inventory, stats, or patches.")}if(typeof paramsRecord.from!=="string"||paramsRecord.from.length===0){throw new CodeNavigationValidationError("CodeDiff from ref or version must not be empty.")}if(typeof paramsRecord.to!=="string"||paramsRecord.to.length===0){throw new CodeNavigationValidationError("CodeDiff to ref or version must not be empty.")}const target=asRecord(paramsRecord.target);if(!target){throw new CodeNavigationValidationError("CodeDiff target must be a package or repository target.")}if(Object.hasOwn(target,"registry")&&Object.hasOwn(target,"packageName")&&!Object.hasOwn(target,"repoUrl")){if(!codeDiffRegistrySchema.safeParse(target.registry).success){throw new CodeNavigationValidationError("CodeDiff package target has an unsupported registry.")}if(typeof target.packageName!=="string"||target.packageName.length===0){throw new CodeNavigationValidationError("CodeDiff package target name must not be empty.")}}else if(Object.hasOwn(target,"repoUrl")&&!Object.hasOwn(target,"registry")&&!Object.hasOwn(target,"packageName")){if(typeof target.repoUrl!=="string"||target.repoUrl.length===0){throw new CodeNavigationValidationError("CodeDiff repository target URL must not be empty.")}}else if((Object.hasOwn(target,"registry")||Object.hasOwn(target,"packageName"))&&Object.hasOwn(target,"repoUrl")){const conflictingKeys=["registry","packageName","repoUrl"].filter((key)=>Object.hasOwn(target,key)).join(", ");throw new CodeNavigationValidationError(`CodeDiff target has conflicting present keys: ${conflictingKeys}. Target shape is determined by key presence, even when a value is undefined.`)}else{throw new CodeNavigationValidationError("CodeDiff target must be a package or repository target.")}const optionsValue=paramsRecord.options;if(optionsValue===undefined)return;const options=asRecord(optionsValue);if(!options){throw new CodeNavigationValidationError("CodeDiff options must be an object when supplied.")}for(const key of Object.keys(options)){if(!CODE_DIFF_OPTION_KEYS.has(key)){throw new CodeNavigationValidationError(`CodeDiff options contains unknown key '${key}'.`)}}validateCodeDiffIntegerOption(options.maxFiles,"maxFiles",1,300);validateCodeDiffIntegerOption(options.maxPatchBytes,"maxPatchBytes",1024,2097152);validateCodeDiffPathOption(options.pathPrefix,"pathPrefix");validateCodeDiffPathOption(options.pathGlob,"pathGlob")}function validateCodeDiffIntegerOption(value,name,minimum,maximum){if(value===undefined)return;if(typeof value!=="number"||!Number.isInteger(value)||value<minimum||value>maximum){throw new CodeNavigationValidationError(`CodeDiff ${name} must be an integer from ${minimum} through ${maximum}.`)}}function validateCodeDiffPathOption(value,name){if(value===undefined)return;if(typeof value!=="string"){throw new CodeNavigationValidationError(`CodeDiff ${name} must be a string when supplied.`)}if(value.length===0){throw new CodeNavigationValidationError(`CodeDiff ${name} must not be empty when supplied.`)}if(new TextEncoder().encode(value).byteLength>1024){throw new CodeNavigationValidationError(`CodeDiff ${name} must be at most 1024 bytes.`)}}function buildCodeDiffVariables(params){const target=params.target;const variables={};if("registry"in target){variables.registry=target.registry;variables.name=target.packageName;variables.fromVersion=params.from;variables.toVersion=params.to}else{variables.repoUrl=target.repoUrl;variables.fromRef=params.from;variables.toRef=params.to}const rawOptions=Object.fromEntries(Object.entries(params.options??{}).filter(([,value])=>value!==undefined));if(Object.keys(rawOptions).length>0)variables.rawOptions=rawOptions;return variables}function isCodeDiffRawError(error){return error.path?.some((part)=>part==="raw")??false}function normaliseCodeDiffResult(result){if(!result.raw){throw new MalformedCodeNavigationResponseError("CodeDiff response missing non-null raw result.")}return{package:normaliseCodeDiffPackage(result.package),fromResolution:normaliseCodeDiffResolution(result.fromResolution),toResolution:normaliseCodeDiffResolution(result.toResolution),raw:normaliseRawCodeDiff(result.raw)}}function normaliseCodeDiffPartial(result){return{package:normaliseCodeDiffPackage(result.package),fromResolution:normaliseCodeDiffResolution(result.fromResolution),toResolution:normaliseCodeDiffResolution(result.toResolution),raw:result.raw?normaliseRawCodeDiff(result.raw):undefined}}function normaliseCodeDiffPackage(value){if(!value)return;return{registry:value.registry,name:value.name,repoUrl:value.repoUrl}}function normaliseCodeDiffResolution(value){return{requested:value.requested,resolvedVersion:value.resolvedVersion??undefined,ref:value.ref,commitSha:value.commitSha,refKind:value.refKind,versionSource:value.versionSource??undefined}}function normaliseRawCodeDiff(value){return{summary:value.summary,scope:{status:value.scope.status,fromSubpath:value.scope.fromSubpath??undefined,toSubpath:value.scope.toSubpath??undefined,pathPrefix:value.scope.pathPrefix??undefined,pathGlob:value.scope.pathGlob??undefined},contentCoverage:value.contentCoverage,contentFailure:value.contentFailure?{code:value.contentFailure.code,retryable:value.contentFailure.retryable,retryAfterMs:value.contentFailure.retryAfterMs??undefined,stage:value.contentFailure.stage??undefined,limitKind:value.contentFailure.limitKind??undefined}:undefined,files:value.files.map((file)=>({path:file.path,pathEncoding:file.pathEncoding,status:file.status,modeChanged:file.modeChanged,typeChanged:file.typeChanged,additions:file.additions??undefined,deletions:file.deletions??undefined,patch:file.patch??undefined,contentStatus:file.contentStatus,contentOmissionReason:file.contentOmissionReason??undefined,contentSafety:{filtered:file.contentSafety.filtered,modifications:file.contentSafety.modifications}})),hasMoreFiles:value.hasMoreFiles}}function parseCodeDiffErrorDetails(errors){const extensions=getPrimaryExtensions(errors);if(!extensions)return;const details={};if(typeof extensions.code==="string")details.code=extensions.code;if(typeof extensions.retryable==="boolean"){details.retryable=extensions.retryable}if(extensions.side==="from"||extensions.side==="to"){details.side=extensions.side}const publishedVersions=parseCodeDiffStringArray(extensions.published_versions);if(publishedVersions)details.publishedVersions=publishedVersions;if(typeof extensions.published_versions_truncated==="boolean"){details.publishedVersionsTruncated=extensions.published_versions_truncated}const availableVersions=parseCodeDiffErrorRefs(extensions.available_versions);if(availableVersions)details.availableVersions=availableVersions;if(typeof extensions.registry==="string"){details.registry=extensions.registry}if(typeof extensions.retry_after_ms==="number"&&Number.isInteger(extensions.retry_after_ms)&&extensions.retry_after_ms>=0){details.retryAfterMs=extensions.retry_after_ms}if(typeof extensions.stage==="string")details.stage=extensions.stage;if(typeof extensions.limit_kind==="string"){details.limitKind=extensions.limit_kind}if(typeof extensions.repo_url==="string"){details.repoUrl=extensions.repo_url}if(typeof extensions.git_ref==="string")details.gitRef=extensions.git_ref;const availableRefs=parseCodeDiffErrorRefs(extensions.available_refs);if(availableRefs)details.availableRefs=availableRefs;const suggestedRefs=parseCodeDiffErrorRefs(extensions.suggested_refs);if(suggestedRefs)details.suggestedRefs=suggestedRefs;const refKinds=parseCodeDiffStringArray(extensions.ref_kinds);if(refKinds)details.refKinds=refKinds;return Object.keys(details).length>0?details:undefined}function parseCodeDiffStringArray(value){if(!Array.isArray(value))return;if(value.some((entry)=>typeof entry!=="string"))return;return value}function parseCodeDiffErrorRefs(value){if(!Array.isArray(value))return;const refs=[];for(const entry of value){if(!entry||typeof entry!=="object"||Array.isArray(entry)){return}const record=entry;if(typeof record.ref!=="string"||record.version!==undefined&&record.version!==null&&typeof record.version!=="string"){return}refs.push({ref:record.ref,version:typeof record.version==="string"?record.version:undefined})}return refs}function parseDetail(body){if(!body)return;try{const parsed=JSON.parse(body);if(typeof parsed.detail==="string")return parsed.detail;if(typeof parsed.error==="string")return parsed.error}catch{return body}return}function buildTargetResolutionFallbackQueries(query){const withoutSuggestedRefs=query.replaceAll(TARGET_RESOLUTION_SUGGESTED_REFS_SELECTION,"").replaceAll(DISCOVERY_TARGET_PROGRESS_SUGGESTED_REFS_SELECTION,"");const candidates=[withoutSuggestedRefs,withoutSuggestedRefs.replaceAll(TARGET_RESOLUTION_AVAILABLE_REFS_SELECTION,""),withoutSuggestedRefs.replaceAll(DISCOVERY_TARGET_PROGRESS_RETRY_SELECTION,""),withoutSuggestedRefs.replaceAll(CODE_CONTEXT_AVAILABLE_VERSIONS_SELECTION,""),withoutSuggestedRefs.replaceAll(TARGET_RESOLUTION_SELECTION,"").replaceAll(DISCOVERY_TARGET_PROGRESS_RETRY_SELECTION,"").replaceAll(CODE_CONTEXT_AVAILABLE_VERSIONS_SELECTION,"")];return candidates.filter((candidate,index,all)=>candidate!==query&&all.indexOf(candidate)===index)}function hasSchemaMismatchErrors(parsedBody){if(!parsedBody||typeof parsedBody!=="object")return false;const errors=parsedBody.errors;if(!Array.isArray(errors))return false;return errors.some((entry)=>{if(!entry||typeof entry!=="object")return false;const error=entry;if(typeof error.message!=="string")return false;const code=typeof error.extensions?.code==="string"?error.extensions.code:undefined;return isGraphQLSchemaMismatchError({message:error.message,code})})}function getPrimaryExtensions(errors){for(const error of errors){if(error.extensions&&Object.keys(error.extensions).length>0){return error.extensions}}return}function getGraphQLIndexingRef(errors){for(const error of errors){const indexingRef=error.extensions?.indexing_ref??error.extensions?.indexingRef;if(typeof indexingRef==="string")return indexingRef}return}function parseAvailableVersions(extensions){const raw=extensions?.available_versions??extensions?.availableVersions;return parseAvailableArtifacts(raw)}function parseAvailableRefs(extensions){const raw=extensions?.available_refs??extensions?.availableRefs;return parseAvailableArtifacts(raw)}function parseSuggestedRefs(extensions){const raw=extensions?.suggested_refs??extensions?.suggestedRefs;return parseAvailableArtifacts(raw)}function parseGraphQLErrorMetadata(extensions,indexingEstimate){const metadata={};if(typeof extensions?.hint==="string")metadata.hint=extensions.hint;const filePath=extensions?.file_path??extensions?.filePath;if(typeof filePath==="string")metadata.filePath=filePath;const exclusionReason=extensions?.exclusion_reason??extensions?.exclusionReason;if(typeof exclusionReason==="string"){metadata.exclusionReason=exclusionReason}const availableVersions=parseAvailableVersions(extensions);if(availableVersions?.length)metadata.availableVersions=availableVersions;const availableRefs=parseAvailableRefs(extensions);if(availableRefs?.length)metadata.availableRefs=availableRefs;const suggestedRefs=parseSuggestedRefs(extensions);if(suggestedRefs?.length)metadata.suggestedRefs=suggestedRefs;const targetResolution=parseTargetResolution(extensions);if(targetResolution)metadata.targetResolution=targetResolution;if(indexingEstimate)metadata.indexingEstimate=indexingEstimate;return Object.keys(metadata).length>0?metadata:undefined}function parseGraphQLRepoUrl(extensions){return typeof extensions?.repo_url==="string"?extensions.repo_url:typeof extensions?.repoUrl==="string"?extensions.repoUrl:undefined}function parseGraphQLGitRef(extensions){return typeof extensions?.git_ref==="string"?extensions.git_ref:typeof extensions?.gitRef==="string"?extensions.gitRef:undefined}function parseTargetResolution(extensions){const raw=extensions?.target_resolution??extensions?.targetResolution;const parsed=targetResolutionSchema.safeParse(raw);if(!parsed.success)return;return normaliseTargetResolution(parsed.data)}function parseIndexingDurationEstimate(extensions){const raw=extensions?.estimated_indexing_duration??extensions?.estimatedIndexingDuration??extensions?.indexing_estimate??extensions?.indexingEstimate;const parsed=indexingDurationEstimateSchema.safeParse(normaliseRawIndexingDurationEstimate(raw));if(!parsed.success)return;return normaliseIndexingDurationEstimate(parsed.data)}function normaliseRawIndexingDurationEstimate(raw){if(!raw||typeof raw!=="object"||Array.isArray(raw))return raw;const record=raw;return{lowerSeconds:record.lowerSeconds??record.lower_seconds,upperSeconds:record.upperSeconds??record.upper_seconds,elapsedSeconds:record.elapsedSeconds??record.elapsed_seconds,sampleCount:record.sampleCount??record.sample_count,source:record.source}}function normaliseIndexingDurationEstimate(estimate){if(!estimate)return;const out={};if(typeof estimate.lowerSeconds==="number"){out.lowerSeconds=estimate.lowerSeconds}if(typeof estimate.upperSeconds==="number"){out.upperSeconds=estimate.upperSeconds}if(typeof estimate.elapsedSeconds==="number"){out.elapsedSeconds=estimate.elapsedSeconds}if(typeof estimate.sampleCount==="number"){out.sampleCount=estimate.sampleCount}if(typeof estimate.source==="string")out.source=estimate.source;return Object.keys(out).length>0?out:undefined}function appendIndexingWaitHint(message,backendHint){const hintAlreadyInMessage=Boolean(backendHint&&message.includes(backendHint));const existingGuidance=`${message} ${backendHint??""}`;if(/(?:--wait\b|wait_timeout_ms|waitTimeoutMs)/i.test(existingGuidance)){return hintAlreadyInMessage?undefined:backendHint}return backendHint&&!hintAlreadyInMessage?`${backendHint} ${INDEXING_WAIT_HINT}`:INDEXING_WAIT_HINT}function parseAvailableArtifacts(raw){if(!Array.isArray(raw))return;const parsed=[];for(const item of raw){if(item&&typeof item==="object"&&"ref"in item){const entry=item;if(typeof entry.ref==="string"){parsed.push({ref:entry.ref,version:typeof entry.version==="string"?entry.version:undefined})}}}return parsed.length>0?parsed:undefined}function normaliseAvailableVersions(entries){if(!entries||entries.length===0)return;return entries.map((entry)=>({version:entry.version??undefined,ref:entry.ref}))}function normaliseTargetResolution(resolution){if(!resolution)return;return{requested:normaliseTargetResolutionIdentity(resolution.requested),resolvedRequested:normaliseTargetResolutionIdentity(resolution.resolvedRequested),served:normaliseTargetResolutionIdentity(resolution.served),freshness:resolution.freshness??undefined,freshnessReason:resolution.freshnessReason??undefined,indexingRef:resolution.indexingRef??undefined,availableVersions:normaliseAvailableVersions(resolution.availableVersions)??[],availableRefs:normaliseAvailableVersions(resolution.availableRefs)??[],suggestedRefs:normaliseAvailableVersions(resolution.suggestedRefs)??[]}}function normaliseDocCoverage(coverage,options={}){if(!coverage)return;if(coverage.coverageState==="NONE"&&!options.preserveNone){return}const out={coverageState:coverage.coverageState};if(coverage.coverageReason)out.coverageReason=coverage.coverageReason;if(typeof coverage.pagesCrawled==="number"){out.pagesCrawled=coverage.pagesCrawled}if(typeof coverage.frontierRemaining==="number"||coverage.frontierRemaining===null){out.frontierRemaining=coverage.frontierRemaining}if(typeof coverage.artifactOverflowPageCount==="number"){out.artifactOverflowPageCount=coverage.artifactOverflowPageCount}if(typeof coverage.estimatedTotalPages==="number"){out.estimatedTotalPages=coverage.estimatedTotalPages}if(coverage.note)out.note=coverage.note;return out}function normaliseTargetResolutionIdentity(identity){if(!identity)return;const out={};if(identity.kind)out.kind=identity.kind;if(identity.registry)out.registry=identity.registry;if(identity.packageName)out.packageName=identity.packageName;if(identity.version)out.version=identity.version;if(identity.repoUrl)out.repoUrl=identity.repoUrl;if(identity.gitRef)out.gitRef=identity.gitRef;if(identity.commitSha)out.commitSha=identity.commitSha;if(identity.site)out.site=identity.site;return Object.keys(out).length>0?out:undefined}function isAuthMessage(message){const lower=message.toLowerCase();return lower.includes("unauthorized")||lower.includes("forbidden")||lower.includes("permission")||lower.includes("authentication")}function normaliseTargetMode(value){if(value==="PACKAGES"||value==="REPO"||value==="MIXED"||value==="SITES"||value==="SITE"){return value}return}function normaliseRequestedRefKind(value){switch(value){case"OMITTED_VERSION":case"LATEST_VERSION":case"EXACT_VERSION":case"DEFAULT_BRANCH":case"HEAD":case"BRANCH":case"SHA":return value;default:return}}function normaliseProgressFilters(filters){if(!filters)return;const out={};if(filters.fileIntent)out.fileIntent=filters.fileIntent;if(filters.kind)out.kind=filters.kind;if(filters.category)out.category=filters.category;if(typeof filters.publicOnly==="boolean"){out.publicOnly=filters.publicOnly}if(filters.pathPrefix)out.pathPrefix=filters.pathPrefix;return Object.keys(out).length>0?out:undefined}function isTargetNotFoundMessage(message){const lower=message.toLowerCase();return lower.includes("not found")||lower.includes("unknown package")||lower.includes("no such package")||lower.includes("does not exist")}function isUnresolvableMessage(message){const lower=message.toLowerCase();return lower.includes("could not resolve")||lower.includes("cannot resolve")}import{z as z3}from"zod";function promoteGenericVersionNotFound(error,params){if(!(error instanceof PackageIntelligenceBackendError))return error;if(error.graphqlCode!==undefined)return error;const requestedVersion=pickRequestedVersion(params);if(!requestedVersion)return error;if(!/no matching version/i.test(error.message))return error;const qualifiedName=synthesizeQualifiedName(params);return new PackageIntelligenceVersionNotFoundError(error.message,qualifiedName,requestedVersion,undefined)}function pickRequestedVersion(params){if(params.version)return params.version;if(params.fromVersion)return params.fromVersion;if(params.toVersion)return params.toVersion;return}function synthesizeQualifiedName(params){if(!params.registry||!params.packageName)return;return`${params.registry.toLowerCase()}:${params.packageName}`}class PackageIntelligenceAccessError extends Error{constructor(message){super(message);this.name="PackageIntelligenceAccessError"}}class PackageIntelligenceFeatureFlagRequiredError extends Error{constructor(message){super(message);this.name="PackageIntelligenceFeatureFlagRequiredError"}}class PackageIntelligenceNetworkError extends Error{constructor(message,options){super(message,options);this.name="PackageIntelligenceNetworkError"}}class PackageIntelligenceBackendError extends Error{status;graphqlCode;retryable;constructor(message,status,graphqlCode,retryable){super(message);this.status=status;this.graphqlCode=graphqlCode;this.retryable=retryable;this.name="PackageIntelligenceBackendError"}}class PackageIntelligenceGraphQLError extends Error{code;constructor(message,code){super(message);this.code=code;this.name="PackageIntelligenceGraphQLError"}}class PackageIntelligenceTargetNotFoundError extends Error{constructor(message){super(message);this.name="PackageIntelligenceTargetNotFoundError"}}class PackageIntelligenceValidationError extends Error{constructor(message){super(message);this.name="PackageIntelligenceValidationError"}}class PackageIntelligenceVersionNotFoundError extends Error{packageName;requestedVersion;availableVersions;constructor(message,packageName,requestedVersion,availableVersions){super(message);this.packageName=packageName;this.requestedVersion=requestedVersion;this.availableVersions=availableVersions;this.name="PackageIntelligenceVersionNotFoundError"}}class MalformedPackageIntelligenceResponseError extends Error{constructor(message){super(message);this.name="MalformedPackageIntelligenceResponseError"}}class PackageIntelligenceChangelogSourceNotFoundError extends Error{constructor(message){super(message);this.name="PackageIntelligenceChangelogSourceNotFoundError"}}var githubRepositorySchema=z3.object({stargazersCount:z3.number().int().nullable().optional(),forksCount:z3.number().int().nullable().optional(),openIssuesCount:z3.number().int().nullable().optional(),archived:z3.boolean().nullable().optional(),language:z3.string().nullable().optional(),topics:z3.array(z3.string()).nullable().optional(),pushedAt:z3.string().nullable().optional()}).nullable().optional();var packageIdentitySchema=z3.object({name:z3.string().nullable().optional(),registry:z3.string().nullable().optional(),description:z3.string().nullable().optional(),latestVersion:z3.string().nullable().optional(),latestVersionPublishedAt:z3.string().nullable().optional(),homepage:z3.string().nullable().optional(),repositoryUrl:z3.string().nullable().optional(),license:z3.string().nullable().optional(),downloadsLastMonth:z3.number().int().nullable().optional(),downloadsTotal:z3.number().int().nullable().optional(),githubRepository:githubRepositorySchema});var vulnerabilityOverviewSchema=z3.object({osvId:z3.string().nullable().optional(),summary:z3.string().nullable().optional(),severityScore:z3.number().nullable().optional(),publishedAt:z3.string().nullable().optional()});var packageSecurityOverviewSchema=z3.object({vulnerabilityCount:z3.number().int().nullable().optional(),hasCurrentVulnerabilities:z3.boolean().nullable().optional(),recentVulnerabilities:z3.array(vulnerabilityOverviewSchema).nullable().optional()}).nullable().optional();var changelogEntrySchema=z3.object({version:z3.string().nullable().optional(),publishedAt:z3.string().nullable().optional(),body:z3.string().nullable().optional()});var packageSummaryResponseSchema=z3.object({package:packageIdentitySchema.nullable().optional(),security:packageSecurityOverviewSchema,latestChangelogs:z3.array(changelogEntrySchema).nullable().optional()});var graphQLErrorSchema2=z3.object({message:z3.string(),extensions:z3.record(z3.string(),z3.unknown()).optional()});var graphQLResponseSchema=z3.object({data:z3.object({packageSummary:packageSummaryResponseSchema.nullable().optional()}).nullable().optional(),errors:z3.array(graphQLErrorSchema2).optional()});var PACKAGE_SUMMARY_QUERY=`
625
625
  query PackageSummary(
626
626
  $registry: Registry!
627
627
  $name: String!
@@ -1311,4 +1311,4 @@ query ReadPackageDoc($pageId: String!) {
1311
1311
  baseUrl
1312
1312
  }
1313
1313
  }
1314
- }`;class PackageIntelligenceServiceImpl{endpointUrl;tokenProvider;fetchFn;runtime;constructor(endpointUrl,tokenProvider,fetchFn=globalThis.fetch,runtime={}){this.endpointUrl=endpointUrl;this.tokenProvider=tokenProvider;this.fetchFn=fetchFn;this.runtime=runtime}async packageSummary(params){return withServiceDiagnostics(this.runtime.diagnostics,"pkg-intel.summary.request",()=>executeWithTokenRefresh({getToken:()=>this.tokenProvider.getToken(),forceRefresh:()=>this.tokenProvider.forceRefresh(),shouldRefresh:isTokenRefreshableError,executeWithToken:(token)=>this.executePackageSummary(token,params)}))}async executePackageSummary(token,params){let response;try{response=await postPkgseerGraphql({endpointUrl:this.endpointUrl,token,query:PACKAGE_SUMMARY_QUERY,variables:{registry:params.registry,name:params.packageName,includeVerboseFields:params.includeVerboseFields!==false},fetchFn:this.fetchFn,clientHeaders:this.runtime.clientHeaders,userAgent:this.runtime.userAgent,diagnostics:this.runtime.diagnostics})}catch(cause){if(cause instanceof PkgseerTransportError){throw this.createTransportError(cause)}throw cause}if(response.status<200||response.status>=300){throw this.createHttpError(response)}const parsed=graphQLResponseSchema.safeParse(response.parsedBody);if(!parsed.success){throw new MalformedPackageIntelligenceResponseError("Malformed response from the package-intelligence service.")}if(parsed.data.errors&&parsed.data.errors.length>0){throw this.createGraphQLError(parsed.data.errors)}const data=parsed.data.data?.packageSummary;if(!data){throw new MalformedPackageIntelligenceResponseError("Empty response from the package-intelligence service.")}return this.normalise(data)}createHttpError(response){return createPackageIntelligenceHttpError(response)}createTransportError(error){return createPackageIntelligenceTransportError(error)}createGraphQLError(errors){return createPackageIntelligenceGraphQLError(errors,this.runtime.clientVersion,this.runtime.diagnostics)}normalise(data){const name=data.package?.name??undefined;const latestVersion=data.package?.latestVersion??undefined;if(!name||!latestVersion){throw new MalformedPackageIntelligenceResponseError("Package summary response missing required name/latestVersion.")}const pkg=data.package;const github=pkg?.githubRepository;const identity={name,latestVersion,registry:pkg?.registry??undefined,description:pkg?.description??undefined,latestVersionPublishedAt:pkg?.latestVersionPublishedAt??undefined,homepage:pkg?.homepage??undefined,repositoryUrl:pkg?.repositoryUrl??undefined,license:pkg?.license??undefined,downloadsLastMonth:pkg?.downloadsLastMonth??undefined,downloadsTotal:pkg?.downloadsTotal??undefined,githubRepository:github?{stargazersCount:github.stargazersCount??undefined,forksCount:github.forksCount??undefined,openIssuesCount:github.openIssuesCount??undefined,archived:github.archived??undefined,language:github.language??undefined,topics:github.topics??undefined,pushedAt:github.pushedAt??undefined}:undefined};const security=data.security?{vulnerabilityCount:data.security.vulnerabilityCount??undefined,hasCurrentVulnerabilities:data.security.hasCurrentVulnerabilities??undefined,recentVulnerabilities:data.security.recentVulnerabilities?.map((vuln)=>({osvId:vuln.osvId??undefined,summary:vuln.summary??undefined,severityScore:vuln.severityScore??undefined,publishedAt:vuln.publishedAt??undefined}))??undefined}:undefined;const latestChangelogs=data.latestChangelogs?.map((entry)=>({version:entry.version??undefined,publishedAt:entry.publishedAt??undefined,body:entry.body??undefined}))??undefined;return{package:identity,security,latestChangelogs}}async packageVulnerabilities(params){return withServiceDiagnostics(this.runtime.diagnostics,"pkg-intel.vulnerabilities.request",()=>executeWithTokenRefresh({getToken:()=>this.tokenProvider.getToken(),forceRefresh:()=>this.tokenProvider.forceRefresh(),shouldRefresh:isTokenRefreshableError,executeWithToken:(token)=>this.executePackageVulnerabilities(token,params)}))}async executePackageVulnerabilities(token,params){let after=null;let firstPage;const entries=[];const seenCursors=new Set;do{const page=await this.fetchPackageVulnerabilitiesPage(token,params,after);if(!firstPage)firstPage=page;const advisoryPage=page.security?.advisories;if(!advisoryPage){after=null;break}entries.push(...advisoryPage.entries);if(advisoryPage.pageInfo.hasNextPage){const nextCursor=advisoryPage.pageInfo.endCursor;if(!nextCursor){throw new MalformedPackageIntelligenceResponseError("Vulnerability response pagination omitted next cursor.")}if(seenCursors.has(nextCursor)){throw new MalformedPackageIntelligenceResponseError("Vulnerability response pagination repeated a cursor.")}seenCursors.add(nextCursor);after=nextCursor}else{after=null}}while(after!==null);if(!firstPage){throw new MalformedPackageIntelligenceResponseError("Empty response from the package-intelligence service.")}if(firstPage.security){const expectedCount=firstPage.security.advisories.pageInfo.totalCount;if(entries.length!==expectedCount){throw new MalformedPackageIntelligenceResponseError("Vulnerability response pagination returned an incomplete advisory set.")}}const data=firstPage.security?{...firstPage,security:{...firstPage.security,advisories:{...firstPage.security.advisories,entries}}}:firstPage;return this.normaliseVulnerabilityReport(data)}async fetchPackageVulnerabilitiesPage(token,params,after){let response;try{response=await postPkgseerGraphql({endpointUrl:this.endpointUrl,token,query:PACKAGE_VULNERABILITIES_QUERY,variables:{registry:params.registry,name:params.packageName,version:params.version,minSeverity:params.minSeverity,includeWithdrawn:params.includeWithdrawn,scope:params.advisoryScope,after},fetchFn:this.fetchFn,clientHeaders:this.runtime.clientHeaders,userAgent:this.runtime.userAgent,diagnostics:this.runtime.diagnostics})}catch(cause){if(cause instanceof PkgseerTransportError){throw this.createTransportError(cause)}throw cause}if(response.status<200||response.status>=300){throw this.createHttpError(response)}const parsed=vulnerabilitiesGraphQLResponseSchema.safeParse(response.parsedBody);if(!parsed.success){throw new MalformedPackageIntelligenceResponseError("Malformed response from the package-intelligence service.")}if(parsed.data.errors&&parsed.data.errors.length>0){throw promoteGenericVersionNotFound(this.createGraphQLError(parsed.data.errors),params)}const data=parsed.data.data?.packageVulnerabilities;if(!data){throw new MalformedPackageIntelligenceResponseError("Empty response from the package-intelligence service.")}return data}normaliseVulnerabilityReport(data){const name=data.package?.name??undefined;const version=data.package?.version??undefined;if(!name||!version){throw new MalformedPackageIntelligenceResponseError("Vulnerability report response missing required name/version.")}const identity={name,version,registry:data.package?.registry??undefined,publishedAt:data.package?.publishedAt??undefined,deprecated:data.package?.deprecated??undefined,deprecationReason:data.package?.deprecationReason??undefined};const security=data.security?{affectedVulnerabilityCount:data.security.affectedVulnerabilityCount,nonAffectingVulnerabilityCount:data.security.nonAffectingVulnerabilityCount,allVulnerabilityCount:data.security.allVulnerabilityCount,currentVersionAffected:data.security.currentVersionAffected??undefined,vulnerabilities:data.security.advisories.entries.map((vuln)=>({osvId:vuln.osvId??undefined,summary:vuln.summary??undefined,severityScore:vuln.severityScore??undefined,severityType:vuln.severityType??undefined,affectedVersionRanges:vuln.affectedVersionRanges??undefined,affectedVersionRangesCount:vuln.affectedVersionRangesCount,affectedVersionRangesTruncated:vuln.affectedVersionRangesTruncated,fixedInVersions:vuln.fixedInVersions??undefined,publishedAt:vuln.publishedAt??undefined,modifiedAt:vuln.modifiedAt??undefined,withdrawnAt:vuln.withdrawnAt??undefined,aliases:vuln.aliases??undefined,isMalicious:vuln.isMalicious??undefined,affectsInspectedVersion:vuln.affectsInspectedVersion,matchedAffectedVersionRanges:vuln.matchedAffectedVersionRanges,duplicateIds:vuln.duplicateIds})),upgradePaths:data.security.upgradePaths??undefined}:undefined;return{package:identity,security}}async packageDependencies(params){return withServiceDiagnostics(this.runtime.diagnostics,"pkg-intel.dependencies.request",()=>executeWithTokenRefresh({getToken:()=>this.tokenProvider.getToken(),forceRefresh:()=>this.tokenProvider.forceRefresh(),shouldRefresh:isTokenRefreshableError,executeWithToken:(token)=>this.executePackageDependencies(token,params)}))}async packageUpgradeDependencyProbe(params){return withServiceDiagnostics(this.runtime.diagnostics,"pkg-intel.upgrade-dependency-probe.request",()=>executeWithTokenRefresh({getToken:()=>this.tokenProvider.getToken(),forceRefresh:()=>this.tokenProvider.forceRefresh(),shouldRefresh:isTokenRefreshableError,executeWithToken:(token)=>this.executePackageUpgradeDependencyProbe(token,params)}))}async packageUpgradeReview(params){return withServiceDiagnostics(this.runtime.diagnostics,"pkg-intel.upgrade-review.request",()=>executeWithTokenRefresh({getToken:()=>this.tokenProvider.getToken(),forceRefresh:()=>this.tokenProvider.forceRefresh(),shouldRefresh:isTokenRefreshableError,executeWithToken:(token)=>this.executePackageUpgradeReview(token,params)}))}async executePackageUpgradeReview(token,params){let response;try{response=await postPkgseerGraphql({endpointUrl:this.endpointUrl,token,query:PACKAGE_UPGRADE_REVIEW_QUERY,variables:{packages:params.packages,includeTransitiveSecurity:params.includeTransitiveSecurity,includeDependencyIssues:params.includeDependencyIssues,minSeverity:params.minSeverity,changelogLimit:params.changelogLimit},fetchFn:this.fetchFn,clientHeaders:this.runtime.clientHeaders,userAgent:this.runtime.userAgent,diagnostics:this.runtime.diagnostics})}catch(cause){if(cause instanceof PkgseerTransportError){throw this.createTransportError(cause)}throw cause}if(response.status<200||response.status>=300){throw this.createHttpError(response)}const parsed=packageUpgradeReviewGraphQLResponseSchema.safeParse(response.parsedBody);if(!parsed.success){throw new MalformedPackageIntelligenceResponseError("Malformed response from the package-intelligence service.")}if(parsed.data.errors&&parsed.data.errors.length>0){throw this.createGraphQLError(parsed.data.errors)}const data=parsed.data.data?.packageUpgradeReview;if(!data){throw new MalformedPackageIntelligenceResponseError("Empty response from the package-intelligence service.")}return stripNullProperties(data)}async executePackageUpgradeDependencyProbe(token,params){const includeTransitiveRisk=params.includeTransitiveSecurity===true||params.includeDependencyIssues===true||params.includeDependencyChanges===true;let response;try{response=await postPkgseerGraphql({endpointUrl:this.endpointUrl,token,query:PACKAGE_UPGRADE_DEPENDENCY_PROBE_QUERY,variables:{registry:params.registry,name:params.packageName,version:params.version,includeTransitiveRisk,includeTransitiveSecurity:params.includeTransitiveSecurity===true,includeDependencyIssues:params.includeDependencyIssues===true,includeDependencyChanges:params.includeDependencyChanges===true,includeGroups:params.includeGroups===true,lifecycle:params.includeGroups===true?["peer"]:undefined,minSeverity:params.minSeverity},fetchFn:this.fetchFn,clientHeaders:this.runtime.clientHeaders,userAgent:this.runtime.userAgent,diagnostics:this.runtime.diagnostics})}catch(cause){if(cause instanceof PkgseerTransportError){throw this.createTransportError(cause)}throw cause}if(response.status<200||response.status>=300){throw this.createHttpError(response)}const parsed=dependenciesGraphQLResponseSchema.safeParse(response.parsedBody);if(!parsed.success){throw new MalformedPackageIntelligenceResponseError("Malformed response from the package-intelligence service.")}if(parsed.data.errors&&parsed.data.errors.length>0){throw promoteGenericVersionNotFound(this.createGraphQLError(parsed.data.errors),params)}const data=parsed.data.data?.packageDependencies;if(!data){throw new MalformedPackageIntelligenceResponseError("Empty response from the package-intelligence service.")}return this.normaliseDependencyReport(data)}async executePackageDependencies(token,params){let response;try{response=await postPkgseerGraphql({endpointUrl:this.endpointUrl,token,query:PACKAGE_DEPENDENCIES_QUERY,variables:{registry:params.registry,name:params.packageName,version:params.version,includeTransitive:params.includeTransitive,includeTransitiveDetails:params.includeTransitiveDetails!==false,includeDependencyGraph:params.includeTransitive===true,includeGroups:params.includeGroups!==false,maxDepth:params.maxDepth,lifecycle:params.lifecycle&&params.lifecycle.length>0?params.lifecycle:undefined},fetchFn:this.fetchFn,clientHeaders:this.runtime.clientHeaders,userAgent:this.runtime.userAgent,diagnostics:this.runtime.diagnostics})}catch(cause){if(cause instanceof PkgseerTransportError){throw this.createTransportError(cause)}throw cause}if(response.status<200||response.status>=300){throw this.createHttpError(response)}const parsed=dependenciesGraphQLResponseSchema.safeParse(response.parsedBody);if(!parsed.success){throw new MalformedPackageIntelligenceResponseError("Malformed response from the package-intelligence service.")}if(parsed.data.errors&&parsed.data.errors.length>0){throw promoteGenericVersionNotFound(this.createGraphQLError(parsed.data.errors),params)}const data=parsed.data.data?.packageDependencies;if(!data){throw new MalformedPackageIntelligenceResponseError("Empty response from the package-intelligence service.")}return this.normaliseDependencyReport(data)}normaliseDependencyReport(data){const name=data.package?.name??undefined;const version=data.package?.version??undefined;if(!name||!version){throw new MalformedPackageIntelligenceResponseError("Package dependencies response missing required name/version.")}const identity={name,version,registry:data.package?.registry??undefined,publishedAt:data.package?.publishedAt??undefined,deprecated:data.package?.deprecated??undefined,deprecationReason:data.package?.deprecationReason??undefined};const bundle=data.dependencies;const dependencies=bundle?{direct:bundle.direct?.map((entry)=>{if(!entry.name){throw new MalformedPackageIntelligenceResponseError("Dependency entry missing required name.")}return{name:entry.name,versionConstraint:entry.versionConstraint??undefined,type:entry.type??undefined}})??undefined,transitive:bundle.transitive?{totalEdges:bundle.transitive.totalEdges??undefined,uniquePackagesCount:bundle.transitive.uniquePackagesCount??undefined,uniqueDependencies:bundle.transitive.uniqueDependencies??undefined,dependencyConflicts:bundle.transitive.dependencyConflicts?.map((c)=>({packageName:c.packageName,requiredVersions:c.requiredVersions,conflictingEdges:c.conflictingEdges.map((edge)=>({fromIndex:edge.fromIndex??undefined,toIndex:edge.toIndex,versionConstraint:edge.versionConstraint,dependencyType:edge.dependencyType}))}))??undefined,circularDependencyCycles:bundle.transitive.circularDependencyCycles?.map((cycle)=>({cycleStart:cycle.cycleStart,circularPath:cycle.circularPath,displayChain:cycle.displayChain}))??undefined,dependencyGraph:bundle.transitive.dependencyGraph?{formatVersion:bundle.transitive.dependencyGraph.formatVersion,nodes:bundle.transitive.dependencyGraph.nodes.map((n)=>({registry:n.registry,name:n.name,version:n.version??undefined})),edges:bundle.transitive.dependencyGraph.edges.map((e)=>({fromIndex:e.fromIndex??undefined,toIndex:e.toIndex,constraint:e.constraint??undefined,dependencyType:e.dependencyType??undefined}))}:undefined,vulnerabilitySummary:this.normaliseTransitiveVulnerabilitySummary(bundle.transitive.vulnerabilitySummary),dependencyIssues:this.normaliseDependencyIssuesSummary(bundle.transitive.dependencyIssues)}:undefined}:undefined;const dependencyGroups=data.dependencyGroups?{primaryGroup:data.dependencyGroups.primaryGroup??undefined,environmentMarkers:data.dependencyGroups.environmentMarkers?.map((m)=>({type:m.type??undefined,value:m.value??undefined,raw:m.raw??undefined}))??undefined,groups:data.dependencyGroups.groups.map((group)=>({name:group.name,lifecycle:group.lifecycle,conditionType:group.conditionType,conditionValue:group.conditionValue??undefined,selectionMode:group.selectionMode,exclusiveGroup:group.exclusiveGroup??undefined,fallbackPriority:group.fallbackPriority??undefined,compatibleWith:group.compatibleWith??undefined,defaultEnabled:group.defaultEnabled??undefined,dependencies:group.dependencies.map((entry)=>({name:entry.name,constraint:entry.constraint??undefined}))}))}:undefined;return{package:identity,dependencies,dependencyGroups}}normaliseTransitiveVulnerabilitySummary(summary){if(!summary)return;return{affected:summary.affected,nonAffecting:summary.nonAffecting,combined:summary.combined,totalPackagesAnalyzed:summary.totalPackagesAnalyzed,affectedPackageCount:summary.affectedPackageCount,calculatedAt:summary.calculatedAt??undefined,packages:summary.packages.map((pkg)=>({registry:pkg.registry,name:pkg.name,versions:pkg.versions,affectedCount:pkg.affectedCount,nonAffectingCount:pkg.nonAffectingCount,totalCount:pkg.totalCount,maxSeverityScore:pkg.maxSeverityScore??undefined,maxSeverityLabel:pkg.maxSeverityLabel??undefined,advisoryIds:pkg.advisoryIds,mostCritical:pkg.mostCritical?this.normaliseVulnerabilitySummaryDetail(pkg.mostCritical):undefined,advisoryOccurrences:pkg.advisoryOccurrences?.map((occurrence)=>({version:occurrence.version,affectsResolvedVersion:occurrence.affectsResolvedVersion,matchedAffectedVersionRanges:occurrence.matchedAffectedVersionRanges,fixVersionsAboveResolved:occurrence.fixVersionsAboveResolved,nearestFixedVersion:occurrence.nearestFixedVersion??undefined,advisory:this.normaliseVulnerabilitySummaryDetail(occurrence.advisory)}))??undefined}))}}normaliseVulnerabilitySummaryDetail(advisory){return{osvId:advisory.osvId??undefined,registry:advisory.registry??undefined,packageName:advisory.packageName??undefined,summary:advisory.summary??undefined,severityScore:advisory.severityScore??undefined,severityType:advisory.severityType??undefined,affectedVersionRanges:advisory.affectedVersionRanges??undefined,fixedInVersions:advisory.fixedInVersions??undefined,publishedAt:advisory.publishedAt??undefined,modifiedAt:advisory.modifiedAt??undefined,withdrawnAt:advisory.withdrawnAt??undefined,aliases:advisory.aliases??undefined,isMalicious:advisory.isMalicious??undefined}}normaliseDependencyIssuesSummary(issues){if(!issues)return;return{totalCount:issues.totalCount,deprecatedCount:issues.deprecatedCount,outdatedCount:issues.outdatedCount,duplicateCount:issues.duplicateCount,conflictCount:issues.conflictCount,deprecatedPackages:issues.deprecatedPackages.map((pkg)=>({registry:pkg.registry,name:pkg.name,versions:pkg.versions,reasons:pkg.reasons.map((reason)=>({version:reason.version,reason:reason.reason??undefined}))})),outdatedPackages:issues.outdatedPackages.map((pkg)=>({registry:pkg.registry,name:pkg.name,latestVersion:pkg.latestVersion??undefined,severity:pkg.severity,versions:pkg.versions.map((version)=>({version:version.version,severity:version.severity})),repositoryUrl:pkg.repositoryUrl??undefined})),duplicatePackages:issues.duplicatePackages.map((pkg)=>({registry:pkg.registry??undefined,name:pkg.name,versions:pkg.versions})),conflicts:issues.conflicts.map((conflict)=>({registry:conflict.registry??undefined,name:conflict.name,versions:conflict.versions,requiredVersions:conflict.requiredVersions,conflictingEdges:conflict.conflictingEdges.map((edge)=>({fromIndex:edge.fromIndex??undefined,toIndex:edge.toIndex,versionConstraint:edge.versionConstraint,dependencyType:edge.dependencyType}))}))}}async packageChangelog(params){return withServiceDiagnostics(this.runtime.diagnostics,"pkg-intel.changelog.request",()=>executeWithTokenRefresh({getToken:()=>this.tokenProvider.getToken(),forceRefresh:()=>this.tokenProvider.forceRefresh(),shouldRefresh:isTokenRefreshableError,executeWithToken:(token)=>this.executePackageChangelog(token,params)}))}async executePackageChangelog(token,params){let response;try{response=await postPkgseerGraphql({endpointUrl:this.endpointUrl,token,query:PACKAGE_CHANGELOG_QUERY,variables:{registry:params.registry,name:params.packageName,repoUrl:params.repoUrl,gitRef:params.gitRef,fromVersion:params.fromVersion,toVersion:params.toVersion,limit:params.limit,includeBodies:params.includeBodies!==false},fetchFn:this.fetchFn,clientHeaders:this.runtime.clientHeaders,userAgent:this.runtime.userAgent,diagnostics:this.runtime.diagnostics})}catch(cause){if(cause instanceof PkgseerTransportError){throw this.createTransportError(cause)}throw cause}if(response.status<200||response.status>=300){throw this.createHttpError(response)}const parsed=changelogGraphQLResponseSchema.safeParse(response.parsedBody);if(!parsed.success){throw new MalformedPackageIntelligenceResponseError("Malformed response from the package-intelligence service.")}if(parsed.data.errors&&parsed.data.errors.length>0){throw promoteGenericVersionNotFound(this.createGraphQLError(parsed.data.errors),params)}const data=parsed.data.data?.packageChangelog;if(!data){throw new MalformedPackageIntelligenceResponseError("Empty response from the package-intelligence service.")}return this.normaliseChangelogReport(data,params)}normaliseChangelogReport(data,params){const source=data.source?.trim()?data.source:undefined;const rawEntries=data.entries??[];if(!source&&rawEntries.length===0){const target=params.repoUrl??(params.registry&&params.packageName?`${params.registry.toLowerCase()}:${params.packageName}`:"package");throw new PackageIntelligenceChangelogSourceNotFoundError(`No changelog source available for ${target} (tried GitHub Releases, CHANGELOG.md, and HexDocs).`)}const entries=rawEntries.map((entry)=>({version:entry.version??undefined,normalizedVersion:entry.normalizedVersion??undefined,body:entry.body??undefined,htmlUrl:entry.htmlUrl??undefined,publishedAt:entry.publishedAt??undefined}));const packageInfo=data.package?{name:data.package.name??undefined,registry:data.package.registry??undefined,repoUrl:data.package.repoUrl??undefined,fromVersion:data.package.fromVersion??undefined,toVersion:data.package.toVersion??undefined,limit:data.package.limit??undefined}:undefined;return{package:packageInfo,source,entries}}async listPackageDocs(params){return withServiceDiagnostics(this.runtime.diagnostics,"pkg-intel.docs.list",()=>executeWithTokenRefresh({getToken:()=>this.tokenProvider.getToken(),forceRefresh:()=>this.tokenProvider.forceRefresh(),shouldRefresh:isTokenRefreshableError,executeWithToken:(token)=>this.executeListPackageDocs(token,params)}))}async executeListPackageDocs(token,params){let response;try{response=await postPkgseerGraphql({endpointUrl:this.endpointUrl,token,query:LIST_PACKAGE_DOCS_QUERY,variables:{registry:params.registry,packageName:params.packageName,version:params.version,limit:params.limit,after:params.after},fetchFn:this.fetchFn,clientHeaders:this.runtime.clientHeaders,userAgent:this.runtime.userAgent,diagnostics:this.runtime.diagnostics})}catch(cause){if(cause instanceof PkgseerTransportError){throw this.createTransportError(cause)}throw cause}if(response.status<200||response.status>=300){throw this.createHttpError(response)}const parsed=packageDocsListGraphQLResponseSchema.safeParse(response.parsedBody);if(!parsed.success){throw new MalformedPackageIntelligenceResponseError("Malformed response from the package-intelligence service.")}if(parsed.data.errors&&parsed.data.errors.length>0){throw promoteGenericVersionNotFound(this.createGraphQLError(parsed.data.errors),params)}const data=parsed.data.data?.listPackageDocs;if(!data){throw new MalformedPackageIntelligenceResponseError("Empty response from the package-intelligence service.")}return this.normalisePackageDocsList(data)}normalisePackageDocsList(data){return{registry:data.registry??undefined,packageName:data.packageName??undefined,version:data.version??undefined,stale:data.stale??undefined,pages:data.pages?.map((page)=>({id:page.id??undefined,title:page.title??undefined,slug:page.slug??undefined,order:page.order??undefined,linkName:page.linkName??undefined,lastUpdatedAt:page.lastUpdatedAt??undefined,sourceKind:page.sourceKind??undefined,sourceUrl:page.sourceUrl??undefined,repoUrl:page.repoUrl??undefined,gitRef:page.gitRef??undefined,requestedRef:page.requestedRef??undefined,filePath:page.filePath??undefined}))??[],pageInfo:data.pageInfo?{hasNextPage:data.pageInfo.hasNextPage,endCursor:data.pageInfo.endCursor??undefined,totalCount:data.pageInfo.totalCount??undefined}:undefined}}async readPackageDoc(params){return withServiceDiagnostics(this.runtime.diagnostics,"pkg-intel.docs.read",()=>executeWithTokenRefresh({getToken:()=>this.tokenProvider.getToken(),forceRefresh:()=>this.tokenProvider.forceRefresh(),shouldRefresh:isTokenRefreshableError,executeWithToken:(token)=>this.executeReadPackageDoc(token,params)}))}async executeReadPackageDoc(token,params){let response;try{response=await postPkgseerGraphql({endpointUrl:this.endpointUrl,token,query:READ_PACKAGE_DOC_QUERY,variables:{pageId:params.pageId},fetchFn:this.fetchFn,clientHeaders:this.runtime.clientHeaders,userAgent:this.runtime.userAgent,diagnostics:this.runtime.diagnostics})}catch(cause){if(cause instanceof PkgseerTransportError){throw this.createTransportError(cause)}throw cause}if(response.status<200||response.status>=300){throw this.createHttpError(response)}const parsed=packageDocReadGraphQLResponseSchema.safeParse(response.parsedBody);if(!parsed.success){throw new MalformedPackageIntelligenceResponseError("Malformed response from the package-intelligence service.")}if(parsed.data.errors&&parsed.data.errors.length>0){throw this.createGraphQLError(parsed.data.errors)}const data=parsed.data.data?.getDocPage;if(!data){throw new MalformedPackageIntelligenceResponseError("Empty response from the package-intelligence service.")}return this.normalisePackageDocResult(data)}normalisePackageDocResult(data){return{registry:data.registry??undefined,packageName:data.packageName??undefined,version:data.version??undefined,sourceKind:data.sourceKind??undefined,page:data.page?{id:data.page.id??undefined,title:data.page.title??undefined,content:data.page.content??undefined,contentFormat:data.page.contentFormat??undefined,breadcrumbs:data.page.breadcrumbs??undefined,linkName:data.page.linkName??undefined,lastUpdatedAt:data.page.lastUpdatedAt??undefined,sourceKind:data.page.sourceKind??undefined,source:data.page.source?{url:data.page.source.url??undefined,label:data.page.source.label??undefined}:undefined,repoUrl:data.page.repoUrl??undefined,gitRef:data.page.gitRef??undefined,requestedRef:data.page.requestedRef??undefined,filePath:data.page.filePath??undefined,baseUrl:data.page.baseUrl??undefined}:undefined}}}function stripNullProperties(value){if(Array.isArray(value))return value.map(stripNullProperties);if(!value||typeof value!=="object")return value;const result={};for(const[key,child]of Object.entries(value)){if(child!==null)result[key]=stripNullProperties(child)}return result}function createPackageIntelligenceHttpError(response){const status=response.status;const detail=parseDetail2(response.responseBody);if(status===401){return new AuthenticationError(SERVER_AUTHENTICATION_REJECTED_MESSAGE,"server")}if(status===403){return new PackageIntelligenceAccessError(detail??"Access denied.")}if(status>=500){return new PackageIntelligenceBackendError(detail?`Server error (${status}): ${detail}`:`Server error (${status})`,status)}return new PackageIntelligenceBackendError(detail??`Request failed with status ${status}`,status)}function createPackageIntelligenceTransportError(error){if(isFetchTimeoutError(error.cause)){return new PackageIntelligenceBackendError("Package intelligence request timed out.",undefined,"TIMEOUT",true)}return new PackageIntelligenceNetworkError("Could not reach the package intelligence service. Check your connection or set GITHITS_CODE_NAV_URL.",{cause:error})}function createPackageIntelligenceGraphQLError(errors,clientVersion,diagnostics){const message=errors.map((error)=>error.message).join(", ");const extensions=getPrimaryExtensions2(errors);const code=typeof extensions?.code==="string"?extensions.code:undefined;const retryable=typeof extensions?.retryable==="boolean"?extensions.retryable:undefined;if(isClientUpdateRequiredGraphQLError({message,code})){return new ClientUpdateRequiredError(undefined,undefined,clientVersion)}if(isGraphQLSchemaMismatchError({message,code})){const sanitized="Backend protocol mismatch. Your CLI may be newer than the server, or the server may require a newer CLI. Run `githits update-check` to verify your installed version. Set GITHITS_DEBUG=pkg-graphql to inspect GraphQL details during local development.";if(diagnostics?.isEnabled("pkg-graphql")){diagnostics.debug("pkg-graphql",{event:"graphql-schema-mismatch",code:code??"omitted",message})}return new PackageIntelligenceBackendError(diagnostics?.isEnabled("pkg-graphql")?message:sanitized,undefined,code,retryable)}switch(code){case"NOT_FOUND":case"PACKAGE_NOT_FOUND":return new PackageIntelligenceTargetNotFoundError(message);case"VERSION_NOT_FOUND":return new PackageIntelligenceVersionNotFoundError(message,typeof extensions?.package==="string"?extensions.package:undefined,typeof extensions?.requested_version==="string"?extensions.requested_version:undefined,parseVersionList(extensions?.available_versions??extensions?.availableVersions));case"UNSUPPORTED_REGISTRY":case"VALIDATION_ERROR":return new PackageIntelligenceValidationError(message);case"FEATURE_FLAG_REQUIRED":return new PackageIntelligenceFeatureFlagRequiredError(message);case"UNAUTHORIZED":return new AuthenticationError(SERVER_AUTHENTICATION_REJECTED_MESSAGE,"server");case"FORBIDDEN":return new PackageIntelligenceAccessError("Access denied. This feature may not be enabled for your account.");case"UPSTREAM_ERROR":case"TIMEOUT":case"RATE_LIMITED":case"INTERNAL_ERROR":case"UNKNOWN_ERROR":return new PackageIntelligenceBackendError(message,undefined,code,retryable);default:return new PackageIntelligenceBackendError(message,undefined,code,retryable)}}function parseDetail2(body){if(!body)return;try{const parsed=JSON.parse(body);if(typeof parsed.detail==="string")return parsed.detail;if(typeof parsed.error==="string")return parsed.error}catch{return body}return}function getPrimaryExtensions2(errors){for(const error of errors){if(error.extensions&&Object.keys(error.extensions).length>0){return error.extensions}}return}function parseVersionList(raw){if(!Array.isArray(raw))return;const versions=[];for(const item of raw){if(typeof item==="string"&&item.length>0){versions.push(item)}}return versions.length>0?versions:undefined}class RefreshingGitHitsService{apiUrl;tokenProvider;serviceFactory;runtime;constructor(apiUrl,tokenProvider,serviceFactory=undefined,runtime={}){this.apiUrl=apiUrl;this.tokenProvider=tokenProvider;this.serviceFactory=serviceFactory;this.runtime=runtime}async search(params,options){return this.withTokenRefresh(options?(service)=>service.search(params,options):(service)=>service.search(params),options)}async getLanguages(){return this.withTokenRefresh((service)=>service.getLanguages())}async searchLanguages(query,limit){return this.withTokenRefresh((service)=>service.searchLanguages(query,limit))}async submitFeedback(params){return this.withTokenRefresh((service)=>service.submitFeedback(params))}async withTokenRefresh(operation,options){return executeWithTokenRefresh({getToken:()=>{options?.signal?.throwIfAborted();return this.tokenProvider.getToken()},forceRefresh:()=>{options?.signal?.throwIfAborted();return this.tokenProvider.forceRefresh()},shouldRefresh:isTokenRefreshableError,executeWithToken:async(token)=>{options?.signal?.throwIfAborted();const service=this.serviceFactory?this.serviceFactory(this.apiUrl,token):new GitHitsServiceImpl(this.apiUrl,token,undefined,undefined,this.runtime);return operation(service)}})}}function createStaticTokenProvider(token){return{getToken:async()=>token,forceRefresh:async()=>{return}}}import{createHash,randomUUID}from"node:crypto";var MAX_HEADER_BYTES=256;var SESSION_ENV_VARS=["TERM_SESSION_ID","ITERM_SESSION_ID","WEZTERM_PANE","KITTY_PID","ALACRITTY_SOCKET","WT_SESSION","VSCODE_PID","SUPERSET_PANE_ID","SUPERSET_WORKSPACE_ID","STARSHIP_SESSION_KEY","SSH_CONNECTION"];var cachedSessionId;function resolveRawSessionId(env=process.env,ppid=process.ppid){for(const key of SESSION_ENV_VARS){const value=env[key];if(value&&value.trim().length>0){return value.trim()}}if(typeof ppid==="number"&&!Number.isNaN(ppid)&&ppid>0){return String(ppid)}return randomUUID()}function getSessionId(env,ppid){if(cachedSessionId!==undefined&&env===undefined&&ppid===undefined){return cachedSessionId}const raw=resolveRawSessionId(env,ppid);const hashed=hashValue(raw);if(env===undefined&&ppid===undefined){cachedSessionId=hashed}return hashed}function hashValue(input){return createHash("sha256").update(input).digest("hex").slice(0,16)}var AGENT_PROBES=[{envVar:"OPENCODE",name:"opencode"},{envVar:"CLAUDECODE",name:"claude-code"},{envVar:"CURSOR_TRACE_ID",name:"cursor"},{envVar:"WINDSURF_CONFIG_DIR",name:"windsurf"},{envVar:"ZED_TERM",name:"zed"},{envVar:"VSCODE_PID",name:"vscode"}];function parseAgentString(raw){const trimmed=raw.trim();if(trimmed.length===0)return;const slashIndex=trimmed.indexOf("/");if(slashIndex===-1)return{name:trimmed};const name=trimmed.slice(0,slashIndex);const ver=trimmed.slice(slashIndex+1);if(name.length===0)return;return{name,version:ver||undefined}}function formatAgentInfo(info){return info.version?`${info.name}/${info.version}`:info.name}function resolveAgentInfo(env=process.env){const explicit=env.GITHITS_AGENT;if(explicit&&explicit.trim().length>0){return parseAgentString(explicit)}for(const probe of AGENT_PROBES){const value=env[probe.envVar];if(value&&value.trim().length>0){return{name:probe.name}}}return}var CONTROL_CHARS=/[\x00-\x1f\x7f-\x9f]/g;function sanitizeHeaderValue(value){if(value===undefined||value===null||typeof value!=="string"){return}const cleaned=value.replace(CONTROL_CHARS,"").trim();if(cleaned.length===0)return;if(Buffer.byteLength(cleaned,"utf8")>MAX_HEADER_BYTES)return;return cleaned}function createClientHeaderBuilder(options){return()=>buildClientHeadersWithContext({clientName:options.clientName,clientVersion:options.clientVersion,agentProvider:options.agentProvider,env:options.env,ppid:options.ppid})}function buildClientHeadersWithContext(context){try{const headers={};const name=sanitizeHeaderValue(context.clientName);if(name){headers["x-githits-client-name"]=name}const safeClientVersion=sanitizeHeaderValue(context.clientVersion);if(safeClientVersion){headers["x-githits-client-version"]=safeClientVersion}const agentInfo=context.agentProvider?.()??resolveAgentInfo(context.env);if(agentInfo){const agentValue=sanitizeHeaderValue(formatAgentInfo(agentInfo));if(agentValue){headers["x-githits-agent"]=agentValue}}const sessionId=sanitizeHeaderValue(getSessionId(context.env,context.ppid));if(sessionId){headers["x-githits-session-id"]=sessionId}return headers}catch{return{}}}import{createHash as createHash2,randomBytes}from"node:crypto";import{z as z4}from"zod";var latestVersionMaliciousEvidenceSchema=z4.object({advisories:z4.array(z4.object({osvId:z4.string(),classificationReasons:z4.array(z4.string())})).max(5),totalCount:z4.number().int().nonnegative(),truncated:z4.boolean()}).nullable();var listCandidateSchema=z4.object({kind:z4.string(),canonicalKey:z4.string(),confidence:z4.string(),latestVersionMaliciousStatus:z4.string(),latestVersionMaliciousEvidence:latestVersionMaliciousEvidenceSchema,description:z4.string().nullable().optional(),repositoryUrl:z4.string().nullable().optional(),stars:z4.number().int().nullable().optional(),downloadsLastMonth:z4.number().int().nullable().optional(),downloadsTotal:z4.number().int().nullable().optional(),docsAvailable:z4.boolean(),codeAvailable:z4.boolean()});var targetReferenceSchema=listCandidateSchema.pick({kind:true,canonicalKey:true,confidence:true});var detailedCandidateSchema=listCandidateSchema.extend({displayName:z4.string(),registry:z4.string().nullable().optional(),packageName:z4.string().nullable().optional(),latestVersion:z4.string().nullable().optional(),repositoryOwner:z4.string().nullable().optional(),repositoryName:z4.string().nullable().optional(),documentationUrl:z4.string().nullable().optional(),matchedAliases:z4.array(z4.string()),matchTier:z4.number().int(),score:z4.number(),reason:z4.string().nullable().optional()});var graphQLErrorSchema3=z4.object({message:z4.string(),extensions:z4.record(z4.string(),z4.unknown()).optional()});export{CLIENT_UPDATE_REQUIRED_REASON,ClientUpdateRequiredError,DEFAULT_MCP_URL,DEFAULT_API_URL,DEFAULT_CODE_NAV_URL,getMcpUrl,getApiUrl,getCodeNavigationUrl,getEnvApiToken,PKGSEER_REGISTRY_ARGS,PKGSEER_REGISTRY_LIST,toPkgseerRegistry,toPkgseerRegistryLowercase,isKnownPkgseerRegistryArg,GitHitsServiceImpl,CodeNavigationAccessError,CodeNavigationGraphQLError,CodeNavigationIndexingError,CodeNavigationUnresolvableError,MalformedCodeNavigationResponseError,CodeDiffError,CodeNavigationTargetNotFoundError,CodeNavigationFileNotFoundError,CodeNavigationVersionNotFoundError,CodeNavigationRefNotFoundError,CodeNavigationValidationError,CodeNavigationFeatureFlagRequiredError,CodeNavigationNetworkError,CodeNavigationBackendError,CodeNavigationServiceImpl,PackageIntelligenceAccessError,PackageIntelligenceFeatureFlagRequiredError,PackageIntelligenceNetworkError,PackageIntelligenceBackendError,PackageIntelligenceGraphQLError,PackageIntelligenceTargetNotFoundError,PackageIntelligenceValidationError,PackageIntelligenceVersionNotFoundError,MalformedPackageIntelligenceResponseError,PackageIntelligenceChangelogSourceNotFoundError,PackageIntelligenceServiceImpl,RefreshingGitHitsService,createStaticTokenProvider,createClientHeaderBuilder};
1314
+ }`;class PackageIntelligenceServiceImpl{endpointUrl;tokenProvider;fetchFn;runtime;constructor(endpointUrl,tokenProvider,fetchFn=globalThis.fetch,runtime={}){this.endpointUrl=endpointUrl;this.tokenProvider=tokenProvider;this.fetchFn=fetchFn;this.runtime=runtime}async packageSummary(params){return withServiceDiagnostics(this.runtime.diagnostics,"pkg-intel.summary.request",()=>executeWithTokenRefresh({getToken:()=>this.tokenProvider.getToken(),forceRefresh:()=>this.tokenProvider.forceRefresh(),shouldRefresh:isTokenRefreshableError,executeWithToken:(token)=>this.executePackageSummary(token,params)}))}async executePackageSummary(token,params){let response;try{response=await postPkgseerGraphql({endpointUrl:this.endpointUrl,token,query:PACKAGE_SUMMARY_QUERY,variables:{registry:params.registry,name:params.packageName,includeVerboseFields:params.includeVerboseFields!==false},fetchFn:this.fetchFn,clientHeaders:this.runtime.clientHeaders,userAgent:this.runtime.userAgent,diagnostics:this.runtime.diagnostics})}catch(cause){if(cause instanceof PkgseerTransportError){throw this.createTransportError(cause)}throw cause}if(response.status<200||response.status>=300){throw this.createHttpError(response)}const parsed=graphQLResponseSchema.safeParse(response.parsedBody);if(!parsed.success){throw new MalformedPackageIntelligenceResponseError("Malformed response from the package-intelligence service.")}if(parsed.data.errors&&parsed.data.errors.length>0){throw this.createGraphQLError(parsed.data.errors)}const data=parsed.data.data?.packageSummary;if(!data){throw new MalformedPackageIntelligenceResponseError("Empty response from the package-intelligence service.")}return this.normalise(data)}createHttpError(response){return createPackageIntelligenceHttpError(response)}createTransportError(error){return createPackageIntelligenceTransportError(error)}createGraphQLError(errors){return createPackageIntelligenceGraphQLError(errors,this.runtime.clientVersion,this.runtime.diagnostics)}normalise(data){const name=data.package?.name??undefined;const latestVersion=data.package?.latestVersion??undefined;if(!name||!latestVersion){throw new MalformedPackageIntelligenceResponseError("Package summary response missing required name/latestVersion.")}const pkg=data.package;const github=pkg?.githubRepository;const identity={name,latestVersion,registry:pkg?.registry??undefined,description:pkg?.description??undefined,latestVersionPublishedAt:pkg?.latestVersionPublishedAt??undefined,homepage:pkg?.homepage??undefined,repositoryUrl:pkg?.repositoryUrl??undefined,license:pkg?.license??undefined,downloadsLastMonth:pkg?.downloadsLastMonth??undefined,downloadsTotal:pkg?.downloadsTotal??undefined,githubRepository:github?{stargazersCount:github.stargazersCount??undefined,forksCount:github.forksCount??undefined,openIssuesCount:github.openIssuesCount??undefined,archived:github.archived??undefined,language:github.language??undefined,topics:github.topics??undefined,pushedAt:github.pushedAt??undefined}:undefined};const security=data.security?{vulnerabilityCount:data.security.vulnerabilityCount??undefined,hasCurrentVulnerabilities:data.security.hasCurrentVulnerabilities??undefined,recentVulnerabilities:data.security.recentVulnerabilities?.map((vuln)=>({osvId:vuln.osvId??undefined,summary:vuln.summary??undefined,severityScore:vuln.severityScore??undefined,publishedAt:vuln.publishedAt??undefined}))??undefined}:undefined;const latestChangelogs=data.latestChangelogs?.map((entry)=>({version:entry.version??undefined,publishedAt:entry.publishedAt??undefined,body:entry.body??undefined}))??undefined;return{package:identity,security,latestChangelogs}}async packageVulnerabilities(params){return withServiceDiagnostics(this.runtime.diagnostics,"pkg-intel.vulnerabilities.request",()=>executeWithTokenRefresh({getToken:()=>this.tokenProvider.getToken(),forceRefresh:()=>this.tokenProvider.forceRefresh(),shouldRefresh:isTokenRefreshableError,executeWithToken:(token)=>this.executePackageVulnerabilities(token,params)}))}async executePackageVulnerabilities(token,params){let after=null;let firstPage;const entries=[];const seenCursors=new Set;do{const page=await this.fetchPackageVulnerabilitiesPage(token,params,after);if(!firstPage)firstPage=page;const advisoryPage=page.security?.advisories;if(!advisoryPage){after=null;break}entries.push(...advisoryPage.entries);if(advisoryPage.pageInfo.hasNextPage){const nextCursor=advisoryPage.pageInfo.endCursor;if(!nextCursor){throw new MalformedPackageIntelligenceResponseError("Vulnerability response pagination omitted next cursor.")}if(seenCursors.has(nextCursor)){throw new MalformedPackageIntelligenceResponseError("Vulnerability response pagination repeated a cursor.")}seenCursors.add(nextCursor);after=nextCursor}else{after=null}}while(after!==null);if(!firstPage){throw new MalformedPackageIntelligenceResponseError("Empty response from the package-intelligence service.")}if(firstPage.security){const expectedCount=firstPage.security.advisories.pageInfo.totalCount;if(entries.length!==expectedCount){throw new MalformedPackageIntelligenceResponseError("Vulnerability response pagination returned an incomplete advisory set.")}}const data=firstPage.security?{...firstPage,security:{...firstPage.security,advisories:{...firstPage.security.advisories,entries}}}:firstPage;return this.normaliseVulnerabilityReport(data)}async fetchPackageVulnerabilitiesPage(token,params,after){let response;try{response=await postPkgseerGraphql({endpointUrl:this.endpointUrl,token,query:PACKAGE_VULNERABILITIES_QUERY,variables:{registry:params.registry,name:params.packageName,version:params.version,minSeverity:params.minSeverity,includeWithdrawn:params.includeWithdrawn,scope:params.advisoryScope,after},fetchFn:this.fetchFn,clientHeaders:this.runtime.clientHeaders,userAgent:this.runtime.userAgent,diagnostics:this.runtime.diagnostics})}catch(cause){if(cause instanceof PkgseerTransportError){throw this.createTransportError(cause)}throw cause}if(response.status<200||response.status>=300){throw this.createHttpError(response)}const parsed=vulnerabilitiesGraphQLResponseSchema.safeParse(response.parsedBody);if(!parsed.success){throw new MalformedPackageIntelligenceResponseError("Malformed response from the package-intelligence service.")}if(parsed.data.errors&&parsed.data.errors.length>0){throw promoteGenericVersionNotFound(this.createGraphQLError(parsed.data.errors),params)}const data=parsed.data.data?.packageVulnerabilities;if(!data){throw new MalformedPackageIntelligenceResponseError("Empty response from the package-intelligence service.")}return data}normaliseVulnerabilityReport(data){const name=data.package?.name??undefined;const version=data.package?.version??undefined;if(!name||!version){throw new MalformedPackageIntelligenceResponseError("Vulnerability report response missing required name/version.")}const identity={name,version,registry:data.package?.registry??undefined,publishedAt:data.package?.publishedAt??undefined,deprecated:data.package?.deprecated??undefined,deprecationReason:data.package?.deprecationReason??undefined};const security=data.security?{affectedVulnerabilityCount:data.security.affectedVulnerabilityCount,nonAffectingVulnerabilityCount:data.security.nonAffectingVulnerabilityCount,allVulnerabilityCount:data.security.allVulnerabilityCount,currentVersionAffected:data.security.currentVersionAffected??undefined,vulnerabilities:data.security.advisories.entries.map((vuln)=>({osvId:vuln.osvId??undefined,summary:vuln.summary??undefined,severityScore:vuln.severityScore??undefined,severityType:vuln.severityType??undefined,affectedVersionRanges:vuln.affectedVersionRanges??undefined,affectedVersionRangesCount:vuln.affectedVersionRangesCount,affectedVersionRangesTruncated:vuln.affectedVersionRangesTruncated,fixedInVersions:vuln.fixedInVersions??undefined,publishedAt:vuln.publishedAt??undefined,modifiedAt:vuln.modifiedAt??undefined,withdrawnAt:vuln.withdrawnAt??undefined,aliases:vuln.aliases??undefined,isMalicious:vuln.isMalicious??undefined,affectsInspectedVersion:vuln.affectsInspectedVersion,matchedAffectedVersionRanges:vuln.matchedAffectedVersionRanges,duplicateIds:vuln.duplicateIds})),upgradePaths:data.security.upgradePaths??undefined}:undefined;return{package:identity,security}}async packageDependencies(params){return withServiceDiagnostics(this.runtime.diagnostics,"pkg-intel.dependencies.request",()=>executeWithTokenRefresh({getToken:()=>this.tokenProvider.getToken(),forceRefresh:()=>this.tokenProvider.forceRefresh(),shouldRefresh:isTokenRefreshableError,executeWithToken:(token)=>this.executePackageDependencies(token,params)}))}async packageUpgradeDependencyProbe(params){return withServiceDiagnostics(this.runtime.diagnostics,"pkg-intel.upgrade-dependency-probe.request",()=>executeWithTokenRefresh({getToken:()=>this.tokenProvider.getToken(),forceRefresh:()=>this.tokenProvider.forceRefresh(),shouldRefresh:isTokenRefreshableError,executeWithToken:(token)=>this.executePackageUpgradeDependencyProbe(token,params)}))}async packageUpgradeReview(params){return withServiceDiagnostics(this.runtime.diagnostics,"pkg-intel.upgrade-review.request",()=>executeWithTokenRefresh({getToken:()=>this.tokenProvider.getToken(),forceRefresh:()=>this.tokenProvider.forceRefresh(),shouldRefresh:isTokenRefreshableError,executeWithToken:(token)=>this.executePackageUpgradeReview(token,params)}))}async executePackageUpgradeReview(token,params){let response;try{response=await postPkgseerGraphql({endpointUrl:this.endpointUrl,token,query:PACKAGE_UPGRADE_REVIEW_QUERY,variables:{packages:params.packages,includeTransitiveSecurity:params.includeTransitiveSecurity,includeDependencyIssues:params.includeDependencyIssues,minSeverity:params.minSeverity,changelogLimit:params.changelogLimit},fetchFn:this.fetchFn,clientHeaders:this.runtime.clientHeaders,userAgent:this.runtime.userAgent,diagnostics:this.runtime.diagnostics})}catch(cause){if(cause instanceof PkgseerTransportError){throw this.createTransportError(cause)}throw cause}if(response.status<200||response.status>=300){throw this.createHttpError(response)}const parsed=packageUpgradeReviewGraphQLResponseSchema.safeParse(response.parsedBody);if(!parsed.success){throw new MalformedPackageIntelligenceResponseError("Malformed response from the package-intelligence service.")}if(parsed.data.errors&&parsed.data.errors.length>0){throw this.createGraphQLError(parsed.data.errors)}const data=parsed.data.data?.packageUpgradeReview;if(!data){throw new MalformedPackageIntelligenceResponseError("Empty response from the package-intelligence service.")}return stripNullProperties(data)}async executePackageUpgradeDependencyProbe(token,params){const includeTransitiveRisk=params.includeTransitiveSecurity===true||params.includeDependencyIssues===true||params.includeDependencyChanges===true;let response;try{response=await postPkgseerGraphql({endpointUrl:this.endpointUrl,token,query:PACKAGE_UPGRADE_DEPENDENCY_PROBE_QUERY,variables:{registry:params.registry,name:params.packageName,version:params.version,includeTransitiveRisk,includeTransitiveSecurity:params.includeTransitiveSecurity===true,includeDependencyIssues:params.includeDependencyIssues===true,includeDependencyChanges:params.includeDependencyChanges===true,includeGroups:params.includeGroups===true,lifecycle:params.includeGroups===true?["peer"]:undefined,minSeverity:params.minSeverity},fetchFn:this.fetchFn,clientHeaders:this.runtime.clientHeaders,userAgent:this.runtime.userAgent,diagnostics:this.runtime.diagnostics})}catch(cause){if(cause instanceof PkgseerTransportError){throw this.createTransportError(cause)}throw cause}if(response.status<200||response.status>=300){throw this.createHttpError(response)}const parsed=dependenciesGraphQLResponseSchema.safeParse(response.parsedBody);if(!parsed.success){throw new MalformedPackageIntelligenceResponseError("Malformed response from the package-intelligence service.")}if(parsed.data.errors&&parsed.data.errors.length>0){throw promoteGenericVersionNotFound(this.createGraphQLError(parsed.data.errors),params)}const data=parsed.data.data?.packageDependencies;if(!data){throw new MalformedPackageIntelligenceResponseError("Empty response from the package-intelligence service.")}return this.normaliseDependencyReport(data)}async executePackageDependencies(token,params){let response;try{response=await postPkgseerGraphql({endpointUrl:this.endpointUrl,token,query:PACKAGE_DEPENDENCIES_QUERY,variables:{registry:params.registry,name:params.packageName,version:params.version,includeTransitive:params.includeTransitive,includeTransitiveDetails:params.includeTransitiveDetails!==false,includeDependencyGraph:params.includeTransitive===true,includeGroups:params.includeGroups!==false,maxDepth:params.maxDepth,lifecycle:params.lifecycle&&params.lifecycle.length>0?params.lifecycle:undefined},fetchFn:this.fetchFn,clientHeaders:this.runtime.clientHeaders,userAgent:this.runtime.userAgent,diagnostics:this.runtime.diagnostics})}catch(cause){if(cause instanceof PkgseerTransportError){throw this.createTransportError(cause)}throw cause}if(response.status<200||response.status>=300){throw this.createHttpError(response)}const parsed=dependenciesGraphQLResponseSchema.safeParse(response.parsedBody);if(!parsed.success){throw new MalformedPackageIntelligenceResponseError("Malformed response from the package-intelligence service.")}if(parsed.data.errors&&parsed.data.errors.length>0){throw promoteGenericVersionNotFound(this.createGraphQLError(parsed.data.errors),params)}const data=parsed.data.data?.packageDependencies;if(!data){throw new MalformedPackageIntelligenceResponseError("Empty response from the package-intelligence service.")}return this.normaliseDependencyReport(data)}normaliseDependencyReport(data){const name=data.package?.name??undefined;const version=data.package?.version??undefined;if(!name||!version){throw new MalformedPackageIntelligenceResponseError("Package dependencies response missing required name/version.")}const identity={name,version,registry:data.package?.registry??undefined,publishedAt:data.package?.publishedAt??undefined,deprecated:data.package?.deprecated??undefined,deprecationReason:data.package?.deprecationReason??undefined};const bundle=data.dependencies;const dependencies=bundle?{direct:bundle.direct?.map((entry)=>{if(!entry.name){throw new MalformedPackageIntelligenceResponseError("Dependency entry missing required name.")}return{name:entry.name,versionConstraint:entry.versionConstraint??undefined,type:entry.type??undefined}})??undefined,transitive:bundle.transitive?{totalEdges:bundle.transitive.totalEdges??undefined,uniquePackagesCount:bundle.transitive.uniquePackagesCount??undefined,uniqueDependencies:bundle.transitive.uniqueDependencies??undefined,dependencyConflicts:bundle.transitive.dependencyConflicts?.map((c)=>({packageName:c.packageName,requiredVersions:c.requiredVersions,conflictingEdges:c.conflictingEdges.map((edge)=>({fromIndex:edge.fromIndex??undefined,toIndex:edge.toIndex,versionConstraint:edge.versionConstraint,dependencyType:edge.dependencyType}))}))??undefined,circularDependencyCycles:bundle.transitive.circularDependencyCycles?.map((cycle)=>({cycleStart:cycle.cycleStart,circularPath:cycle.circularPath,displayChain:cycle.displayChain}))??undefined,dependencyGraph:bundle.transitive.dependencyGraph?{formatVersion:bundle.transitive.dependencyGraph.formatVersion,nodes:bundle.transitive.dependencyGraph.nodes.map((n)=>({registry:n.registry,name:n.name,version:n.version??undefined})),edges:bundle.transitive.dependencyGraph.edges.map((e)=>({fromIndex:e.fromIndex??undefined,toIndex:e.toIndex,constraint:e.constraint??undefined,dependencyType:e.dependencyType??undefined}))}:undefined,vulnerabilitySummary:this.normaliseTransitiveVulnerabilitySummary(bundle.transitive.vulnerabilitySummary),dependencyIssues:this.normaliseDependencyIssuesSummary(bundle.transitive.dependencyIssues)}:undefined}:undefined;const dependencyGroups=data.dependencyGroups?{primaryGroup:data.dependencyGroups.primaryGroup??undefined,environmentMarkers:data.dependencyGroups.environmentMarkers?.map((m)=>({type:m.type??undefined,value:m.value??undefined,raw:m.raw??undefined}))??undefined,groups:data.dependencyGroups.groups.map((group)=>({name:group.name,lifecycle:group.lifecycle,conditionType:group.conditionType,conditionValue:group.conditionValue??undefined,selectionMode:group.selectionMode,exclusiveGroup:group.exclusiveGroup??undefined,fallbackPriority:group.fallbackPriority??undefined,compatibleWith:group.compatibleWith??undefined,defaultEnabled:group.defaultEnabled??undefined,dependencies:group.dependencies.map((entry)=>({name:entry.name,constraint:entry.constraint??undefined}))}))}:undefined;return{package:identity,dependencies,dependencyGroups}}normaliseTransitiveVulnerabilitySummary(summary){if(!summary)return;return{affected:summary.affected,nonAffecting:summary.nonAffecting,combined:summary.combined,totalPackagesAnalyzed:summary.totalPackagesAnalyzed,affectedPackageCount:summary.affectedPackageCount,calculatedAt:summary.calculatedAt??undefined,packages:summary.packages.map((pkg)=>({registry:pkg.registry,name:pkg.name,versions:pkg.versions,affectedCount:pkg.affectedCount,nonAffectingCount:pkg.nonAffectingCount,totalCount:pkg.totalCount,maxSeverityScore:pkg.maxSeverityScore??undefined,maxSeverityLabel:pkg.maxSeverityLabel??undefined,advisoryIds:pkg.advisoryIds,mostCritical:pkg.mostCritical?this.normaliseVulnerabilitySummaryDetail(pkg.mostCritical):undefined,advisoryOccurrences:pkg.advisoryOccurrences?.map((occurrence)=>({version:occurrence.version,affectsResolvedVersion:occurrence.affectsResolvedVersion,matchedAffectedVersionRanges:occurrence.matchedAffectedVersionRanges,fixVersionsAboveResolved:occurrence.fixVersionsAboveResolved,nearestFixedVersion:occurrence.nearestFixedVersion??undefined,advisory:this.normaliseVulnerabilitySummaryDetail(occurrence.advisory)}))??undefined}))}}normaliseVulnerabilitySummaryDetail(advisory){return{osvId:advisory.osvId??undefined,registry:advisory.registry??undefined,packageName:advisory.packageName??undefined,summary:advisory.summary??undefined,severityScore:advisory.severityScore??undefined,severityType:advisory.severityType??undefined,affectedVersionRanges:advisory.affectedVersionRanges??undefined,fixedInVersions:advisory.fixedInVersions??undefined,publishedAt:advisory.publishedAt??undefined,modifiedAt:advisory.modifiedAt??undefined,withdrawnAt:advisory.withdrawnAt??undefined,aliases:advisory.aliases??undefined,isMalicious:advisory.isMalicious??undefined}}normaliseDependencyIssuesSummary(issues){if(!issues)return;return{totalCount:issues.totalCount,deprecatedCount:issues.deprecatedCount,outdatedCount:issues.outdatedCount,duplicateCount:issues.duplicateCount,conflictCount:issues.conflictCount,deprecatedPackages:issues.deprecatedPackages.map((pkg)=>({registry:pkg.registry,name:pkg.name,versions:pkg.versions,reasons:pkg.reasons.map((reason)=>({version:reason.version,reason:reason.reason??undefined}))})),outdatedPackages:issues.outdatedPackages.map((pkg)=>({registry:pkg.registry,name:pkg.name,latestVersion:pkg.latestVersion??undefined,severity:pkg.severity,versions:pkg.versions.map((version)=>({version:version.version,severity:version.severity})),repositoryUrl:pkg.repositoryUrl??undefined})),duplicatePackages:issues.duplicatePackages.map((pkg)=>({registry:pkg.registry??undefined,name:pkg.name,versions:pkg.versions})),conflicts:issues.conflicts.map((conflict)=>({registry:conflict.registry??undefined,name:conflict.name,versions:conflict.versions,requiredVersions:conflict.requiredVersions,conflictingEdges:conflict.conflictingEdges.map((edge)=>({fromIndex:edge.fromIndex??undefined,toIndex:edge.toIndex,versionConstraint:edge.versionConstraint,dependencyType:edge.dependencyType}))}))}}async packageChangelog(params){return withServiceDiagnostics(this.runtime.diagnostics,"pkg-intel.changelog.request",()=>executeWithTokenRefresh({getToken:()=>this.tokenProvider.getToken(),forceRefresh:()=>this.tokenProvider.forceRefresh(),shouldRefresh:isTokenRefreshableError,executeWithToken:(token)=>this.executePackageChangelog(token,params)}))}async executePackageChangelog(token,params){let response;try{response=await postPkgseerGraphql({endpointUrl:this.endpointUrl,token,query:PACKAGE_CHANGELOG_QUERY,variables:{registry:params.registry,name:params.packageName,repoUrl:params.repoUrl,gitRef:params.gitRef,fromVersion:params.fromVersion,toVersion:params.toVersion,limit:params.limit,includeBodies:params.includeBodies!==false},fetchFn:this.fetchFn,clientHeaders:this.runtime.clientHeaders,userAgent:this.runtime.userAgent,diagnostics:this.runtime.diagnostics})}catch(cause){if(cause instanceof PkgseerTransportError){throw this.createTransportError(cause)}throw cause}if(response.status<200||response.status>=300){throw this.createHttpError(response)}const parsed=changelogGraphQLResponseSchema.safeParse(response.parsedBody);if(!parsed.success){throw new MalformedPackageIntelligenceResponseError("Malformed response from the package-intelligence service.")}if(parsed.data.errors&&parsed.data.errors.length>0){throw promoteGenericVersionNotFound(this.createGraphQLError(parsed.data.errors),params)}const data=parsed.data.data?.packageChangelog;if(!data){throw new MalformedPackageIntelligenceResponseError("Empty response from the package-intelligence service.")}return this.normaliseChangelogReport(data,params)}normaliseChangelogReport(data,params){const source=data.source?.trim()?data.source:undefined;const rawEntries=data.entries??[];if(!source&&rawEntries.length===0){const target=params.repoUrl??(params.registry&&params.packageName?`${params.registry.toLowerCase()}:${params.packageName}`:"package");throw new PackageIntelligenceChangelogSourceNotFoundError(`No changelog source available for ${target} (tried GitHub Releases, CHANGELOG.md, and HexDocs).`)}const entries=rawEntries.map((entry)=>({version:entry.version??undefined,normalizedVersion:entry.normalizedVersion??undefined,body:entry.body??undefined,htmlUrl:entry.htmlUrl??undefined,publishedAt:entry.publishedAt??undefined}));const packageInfo=data.package?{name:data.package.name??undefined,registry:data.package.registry??undefined,repoUrl:data.package.repoUrl??undefined,fromVersion:data.package.fromVersion??undefined,toVersion:data.package.toVersion??undefined,limit:data.package.limit??undefined}:undefined;return{package:packageInfo,source,entries}}async listPackageDocs(params){return withServiceDiagnostics(this.runtime.diagnostics,"pkg-intel.docs.list",()=>executeWithTokenRefresh({getToken:()=>this.tokenProvider.getToken(),forceRefresh:()=>this.tokenProvider.forceRefresh(),shouldRefresh:isTokenRefreshableError,executeWithToken:(token)=>this.executeListPackageDocs(token,params)}))}async executeListPackageDocs(token,params){let response;try{response=await postPkgseerGraphql({endpointUrl:this.endpointUrl,token,query:LIST_PACKAGE_DOCS_QUERY,variables:{registry:params.registry,packageName:params.packageName,version:params.version,limit:params.limit,after:params.after},fetchFn:this.fetchFn,clientHeaders:this.runtime.clientHeaders,userAgent:this.runtime.userAgent,diagnostics:this.runtime.diagnostics})}catch(cause){if(cause instanceof PkgseerTransportError){throw this.createTransportError(cause)}throw cause}if(response.status<200||response.status>=300){throw this.createHttpError(response)}const parsed=packageDocsListGraphQLResponseSchema.safeParse(response.parsedBody);if(!parsed.success){throw new MalformedPackageIntelligenceResponseError("Malformed response from the package-intelligence service.")}if(parsed.data.errors&&parsed.data.errors.length>0){throw promoteGenericVersionNotFound(this.createGraphQLError(parsed.data.errors),params)}const data=parsed.data.data?.listPackageDocs;if(!data){throw new MalformedPackageIntelligenceResponseError("Empty response from the package-intelligence service.")}return this.normalisePackageDocsList(data)}normalisePackageDocsList(data){return{registry:data.registry??undefined,packageName:data.packageName??undefined,version:data.version??undefined,stale:data.stale??undefined,pages:data.pages?.map((page)=>({id:page.id??undefined,title:page.title??undefined,slug:page.slug??undefined,order:page.order??undefined,linkName:page.linkName??undefined,lastUpdatedAt:page.lastUpdatedAt??undefined,sourceKind:page.sourceKind??undefined,sourceUrl:page.sourceUrl??undefined,repoUrl:page.repoUrl??undefined,gitRef:page.gitRef??undefined,requestedRef:page.requestedRef??undefined,filePath:page.filePath??undefined}))??[],pageInfo:data.pageInfo?{hasNextPage:data.pageInfo.hasNextPage,endCursor:data.pageInfo.endCursor??undefined,totalCount:data.pageInfo.totalCount??undefined}:undefined}}async readPackageDoc(params){return withServiceDiagnostics(this.runtime.diagnostics,"pkg-intel.docs.read",()=>executeWithTokenRefresh({getToken:()=>this.tokenProvider.getToken(),forceRefresh:()=>this.tokenProvider.forceRefresh(),shouldRefresh:isTokenRefreshableError,executeWithToken:(token)=>this.executeReadPackageDoc(token,params)}))}async executeReadPackageDoc(token,params){let response;try{response=await postPkgseerGraphql({endpointUrl:this.endpointUrl,token,query:READ_PACKAGE_DOC_QUERY,variables:{pageId:params.pageId},fetchFn:this.fetchFn,clientHeaders:this.runtime.clientHeaders,userAgent:this.runtime.userAgent,diagnostics:this.runtime.diagnostics})}catch(cause){if(cause instanceof PkgseerTransportError){throw this.createTransportError(cause)}throw cause}if(response.status<200||response.status>=300){throw this.createHttpError(response)}const parsed=packageDocReadGraphQLResponseSchema.safeParse(response.parsedBody);if(!parsed.success){throw new MalformedPackageIntelligenceResponseError("Malformed response from the package-intelligence service.")}if(parsed.data.errors&&parsed.data.errors.length>0){throw this.createGraphQLError(parsed.data.errors)}const data=parsed.data.data?.getDocPage;if(!data){throw new MalformedPackageIntelligenceResponseError("Empty response from the package-intelligence service.")}return this.normalisePackageDocResult(data)}normalisePackageDocResult(data){return{registry:data.registry??undefined,packageName:data.packageName??undefined,version:data.version??undefined,sourceKind:data.sourceKind??undefined,page:data.page?{id:data.page.id??undefined,title:data.page.title??undefined,content:data.page.content??undefined,contentFormat:data.page.contentFormat??undefined,breadcrumbs:data.page.breadcrumbs??undefined,linkName:data.page.linkName??undefined,lastUpdatedAt:data.page.lastUpdatedAt??undefined,sourceKind:data.page.sourceKind??undefined,source:data.page.source?{url:data.page.source.url??undefined,label:data.page.source.label??undefined}:undefined,repoUrl:data.page.repoUrl??undefined,gitRef:data.page.gitRef??undefined,requestedRef:data.page.requestedRef??undefined,filePath:data.page.filePath??undefined,baseUrl:data.page.baseUrl??undefined}:undefined}}}function stripNullProperties(value){if(Array.isArray(value))return value.map(stripNullProperties);if(!value||typeof value!=="object")return value;const result={};for(const[key,child]of Object.entries(value)){if(child!==null)result[key]=stripNullProperties(child)}return result}function createPackageIntelligenceHttpError(response){const status=response.status;const detail=parseDetail2(response.responseBody);if(status===401){return new AuthenticationError(SERVER_AUTHENTICATION_REJECTED_MESSAGE,"server")}if(status===403){return new PackageIntelligenceAccessError(detail??"Access denied.")}if(status>=500){return new PackageIntelligenceBackendError(detail?`Server error (${status}): ${detail}`:`Server error (${status})`,status)}return new PackageIntelligenceBackendError(detail??`Request failed with status ${status}`,status)}function createPackageIntelligenceTransportError(error){if(isFetchTimeoutError(error.cause)){return new PackageIntelligenceBackendError("Package intelligence request timed out.",undefined,"TIMEOUT",true)}return new PackageIntelligenceNetworkError("Could not reach the package intelligence service. Check your connection or set GITHITS_CODE_NAV_URL.",{cause:error})}function createPackageIntelligenceGraphQLError(errors,clientVersion,diagnostics){const message=errors.map((error)=>error.message).join(", ");const extensions=getPrimaryExtensions2(errors);const code=typeof extensions?.code==="string"?extensions.code:undefined;const retryable=typeof extensions?.retryable==="boolean"?extensions.retryable:undefined;if(isClientUpdateRequiredGraphQLError({message,code})){return new ClientUpdateRequiredError(undefined,undefined,clientVersion)}if(isGraphQLSchemaMismatchError({message,code})){const sanitized="Backend protocol mismatch. Your CLI may be newer than the server, or the server may require a newer CLI. Run `githits update-check` to verify your installed version. Set GITHITS_DEBUG=pkg-graphql to inspect GraphQL details during local development.";if(diagnostics?.isEnabled("pkg-graphql")){diagnostics.debug("pkg-graphql",{event:"graphql-schema-mismatch",code:code??"omitted",message})}return new PackageIntelligenceBackendError(diagnostics?.isEnabled("pkg-graphql")?message:sanitized,undefined,code,retryable)}switch(code){case"NOT_FOUND":case"PACKAGE_NOT_FOUND":return new PackageIntelligenceTargetNotFoundError(message);case"VERSION_NOT_FOUND":return new PackageIntelligenceVersionNotFoundError(message,typeof extensions?.package==="string"?extensions.package:undefined,typeof extensions?.requested_version==="string"?extensions.requested_version:undefined,parseVersionList(extensions?.available_versions??extensions?.availableVersions));case"UNSUPPORTED_REGISTRY":case"VALIDATION_ERROR":return new PackageIntelligenceValidationError(message);case"FEATURE_FLAG_REQUIRED":return new PackageIntelligenceFeatureFlagRequiredError(message);case"AUTHENTICATION_REQUIRED":case"UNAUTHORIZED":return new AuthenticationError(SERVER_AUTHENTICATION_REJECTED_MESSAGE,"server");case"FORBIDDEN":return new PackageIntelligenceAccessError("Access denied. This feature may not be enabled for your account.");case"UPSTREAM_ERROR":case"TIMEOUT":case"RATE_LIMITED":case"INTERNAL_ERROR":case"UNKNOWN_ERROR":return new PackageIntelligenceBackendError(message,undefined,code,retryable);default:return new PackageIntelligenceBackendError(message,undefined,code,retryable)}}function parseDetail2(body){if(!body)return;try{const parsed=JSON.parse(body);if(typeof parsed.detail==="string")return parsed.detail;if(typeof parsed.error==="string")return parsed.error}catch{return body}return}function getPrimaryExtensions2(errors){for(const error of errors){if(error.extensions&&Object.keys(error.extensions).length>0){return error.extensions}}return}function parseVersionList(raw){if(!Array.isArray(raw))return;const versions=[];for(const item of raw){if(typeof item==="string"&&item.length>0){versions.push(item)}}return versions.length>0?versions:undefined}class RefreshingGitHitsService{apiUrl;tokenProvider;serviceFactory;runtime;constructor(apiUrl,tokenProvider,serviceFactory=undefined,runtime={}){this.apiUrl=apiUrl;this.tokenProvider=tokenProvider;this.serviceFactory=serviceFactory;this.runtime=runtime}async search(params,options){return this.withTokenRefresh(options?(service)=>service.search(params,options):(service)=>service.search(params),options)}async getLanguages(){return this.withTokenRefresh((service)=>service.getLanguages())}async searchLanguages(query,limit){return this.withTokenRefresh((service)=>service.searchLanguages(query,limit))}async submitFeedback(params){return this.withTokenRefresh((service)=>service.submitFeedback(params))}async withTokenRefresh(operation,options){return executeWithTokenRefresh({getToken:()=>{options?.signal?.throwIfAborted();return this.tokenProvider.getToken()},forceRefresh:()=>{options?.signal?.throwIfAborted();return this.tokenProvider.forceRefresh()},shouldRefresh:isTokenRefreshableError,executeWithToken:async(token)=>{options?.signal?.throwIfAborted();const service=this.serviceFactory?this.serviceFactory(this.apiUrl,token):new GitHitsServiceImpl(this.apiUrl,token,undefined,undefined,this.runtime);return operation(service)}})}}function createStaticTokenProvider(token){return{getToken:async()=>token,forceRefresh:async()=>{return}}}import{createHash,randomUUID}from"node:crypto";var MAX_HEADER_BYTES=256;var SESSION_ENV_VARS=["TERM_SESSION_ID","ITERM_SESSION_ID","WEZTERM_PANE","KITTY_PID","ALACRITTY_SOCKET","WT_SESSION","VSCODE_PID","SUPERSET_PANE_ID","SUPERSET_WORKSPACE_ID","STARSHIP_SESSION_KEY","SSH_CONNECTION"];var cachedSessionId;function resolveRawSessionId(env=process.env,ppid=process.ppid){for(const key of SESSION_ENV_VARS){const value=env[key];if(value&&value.trim().length>0){return value.trim()}}if(typeof ppid==="number"&&!Number.isNaN(ppid)&&ppid>0){return String(ppid)}return randomUUID()}function getSessionId(env,ppid){if(cachedSessionId!==undefined&&env===undefined&&ppid===undefined){return cachedSessionId}const raw=resolveRawSessionId(env,ppid);const hashed=hashValue(raw);if(env===undefined&&ppid===undefined){cachedSessionId=hashed}return hashed}function hashValue(input){return createHash("sha256").update(input).digest("hex").slice(0,16)}var AGENT_PROBES=[{envVar:"OPENCODE",name:"opencode"},{envVar:"CLAUDECODE",name:"claude-code"},{envVar:"CURSOR_TRACE_ID",name:"cursor"},{envVar:"WINDSURF_CONFIG_DIR",name:"windsurf"},{envVar:"ZED_TERM",name:"zed"},{envVar:"VSCODE_PID",name:"vscode"}];function parseAgentString(raw){const trimmed=raw.trim();if(trimmed.length===0)return;const slashIndex=trimmed.indexOf("/");if(slashIndex===-1)return{name:trimmed};const name=trimmed.slice(0,slashIndex);const ver=trimmed.slice(slashIndex+1);if(name.length===0)return;return{name,version:ver||undefined}}function formatAgentInfo(info){return info.version?`${info.name}/${info.version}`:info.name}function resolveAgentInfo(env=process.env){const explicit=env.GITHITS_AGENT;if(explicit&&explicit.trim().length>0){return parseAgentString(explicit)}for(const probe of AGENT_PROBES){const value=env[probe.envVar];if(value&&value.trim().length>0){return{name:probe.name}}}return}var CONTROL_CHARS=/[\x00-\x1f\x7f-\x9f]/g;function sanitizeHeaderValue(value){if(value===undefined||value===null||typeof value!=="string"){return}const cleaned=value.replace(CONTROL_CHARS,"").trim();if(cleaned.length===0)return;if(Buffer.byteLength(cleaned,"utf8")>MAX_HEADER_BYTES)return;return cleaned}function createClientHeaderBuilder(options){return()=>buildClientHeadersWithContext({clientName:options.clientName,clientVersion:options.clientVersion,agentProvider:options.agentProvider,env:options.env,ppid:options.ppid})}function buildClientHeadersWithContext(context){try{const headers={};const name=sanitizeHeaderValue(context.clientName);if(name){headers["x-githits-client-name"]=name}const safeClientVersion=sanitizeHeaderValue(context.clientVersion);if(safeClientVersion){headers["x-githits-client-version"]=safeClientVersion}const agentInfo=context.agentProvider?.()??resolveAgentInfo(context.env);if(agentInfo){const agentValue=sanitizeHeaderValue(formatAgentInfo(agentInfo));if(agentValue){headers["x-githits-agent"]=agentValue}}const sessionId=sanitizeHeaderValue(getSessionId(context.env,context.ppid));if(sessionId){headers["x-githits-session-id"]=sessionId}return headers}catch{return{}}}import{createHash as createHash2,randomBytes}from"node:crypto";import{z as z4}from"zod";var latestVersionMaliciousEvidenceSchema=z4.object({advisories:z4.array(z4.object({osvId:z4.string(),classificationReasons:z4.array(z4.string())})).max(5),totalCount:z4.number().int().nonnegative(),truncated:z4.boolean()}).nullable();var compactMatchSchema=z4.object({confidence:z4.string()});var candidateEvidenceSchema=z4.object({canonicalKey:z4.string(),nameSimilarity:z4.number().nullable()});var detailedMatchSchema=compactMatchSchema.extend({matchedAliases:z4.array(z4.string()),matchTier:z4.number().int(),score:z4.number()});var listTargetSchema=z4.object({kind:z4.string(),canonicalKey:z4.string(),latestVersionMaliciousStatus:z4.string(),latestVersionMaliciousEvidence:latestVersionMaliciousEvidenceSchema,description:z4.string().nullable().optional(),repositoryUrl:z4.string().nullable().optional(),stars:z4.number().int().nullable().optional(),downloadsLastMonth:z4.number().int().nullable().optional(),downloadsTotal:z4.number().int().nullable().optional(),docsAvailable:z4.boolean(),codeAvailable:z4.boolean(),groupKey:z4.string().nullable(),match:compactMatchSchema.nullable(),docsPageCount:z4.number().int().nullable(),codeFileCount:z4.number().int().nullable(),license:z4.string().nullable()});var targetReferenceSchema=z4.object({kind:z4.string(),canonicalKey:z4.string(),confidence:z4.string()});var detailedTargetSchema=listTargetSchema.omit({match:true}).extend({match:detailedMatchSchema.nullable(),displayName:z4.string(),registry:z4.string().nullable().optional(),packageName:z4.string().nullable().optional(),latestVersion:z4.string().nullable().optional(),repositoryOwner:z4.string().nullable().optional(),repositoryName:z4.string().nullable().optional(),documentationUrl:z4.string().nullable().optional()});var graphQLErrorSchema3=z4.object({message:z4.string(),extensions:z4.record(z4.string(),z4.unknown()).optional()});export{CLIENT_UPDATE_REQUIRED_REASON,ClientUpdateRequiredError,DEFAULT_MCP_URL,DEFAULT_API_URL,DEFAULT_CODE_NAV_URL,getMcpUrl,getApiUrl,getCodeNavigationUrl,getEnvApiToken,PKGSEER_REGISTRY_ARGS,PKGSEER_REGISTRY_LIST,toPkgseerRegistry,toPkgseerRegistryLowercase,isKnownPkgseerRegistryArg,GitHitsServiceImpl,CodeNavigationAccessError,CodeNavigationGraphQLError,CodeNavigationIndexingError,CodeNavigationUnresolvableError,MalformedCodeNavigationResponseError,CodeDiffError,CodeNavigationTargetNotFoundError,CodeNavigationFileNotFoundError,CodeNavigationVersionNotFoundError,CodeNavigationRefNotFoundError,CodeNavigationValidationError,CodeNavigationFeatureFlagRequiredError,CodeNavigationNetworkError,CodeNavigationBackendError,CodeNavigationServiceImpl,PackageIntelligenceAccessError,PackageIntelligenceFeatureFlagRequiredError,PackageIntelligenceNetworkError,PackageIntelligenceBackendError,PackageIntelligenceGraphQLError,PackageIntelligenceTargetNotFoundError,PackageIntelligenceValidationError,PackageIntelligenceVersionNotFoundError,MalformedPackageIntelligenceResponseError,PackageIntelligenceChangelogSourceNotFoundError,PackageIntelligenceServiceImpl,RefreshingGitHitsService,createStaticTokenProvider,createClientHeaderBuilder};
@@ -1,3 +1,8 @@
1
- var EXPECTED_MCP_TOOLS=["quick_start","get_example","search_language","pkg_info","pkg_deps","pkg_vulns","pkg_changelog","pkg_upgrade_review","docs_list","docs_read","code_files","code_read","code_grep","search","search_status","feedback"];var DEFAULT_TEXT_LIMIT=12000;var SMOKE_PACKAGE_VERSION="5.2.1";var SMOKE_PACKAGE_TARGET={registry:"npm",package_name:"express",version:SMOKE_PACKAGE_VERSION};function assert(condition,message){if(!condition){throw new Error(message)}}function parseJson(text,context){try{return JSON.parse(text)}catch(error){const message=error instanceof Error?error.message:"unknown error";throw new Error(`${context}: expected parseable JSON (${message})`)}}function assertNotJson(text,context){try{JSON.parse(text)}catch{return}throw new Error(`${context}: default response unexpectedly parsed as JSON`)}function assertRecord(value,context){assert(value!==null&&typeof value==="object"&&!Array.isArray(value),`${context}: expected object`)}function headerValue(headers,name){if(!headers)return null;if("get"in headers&&typeof headers.get==="function"){return headers.get(name)}const lowerName=name.toLowerCase();for(const[key,value]of Object.entries(headers)){if(key.toLowerCase()===lowerName)return value??null}return null}function resultText(result,context){assert(Array.isArray(result.content),`${context}: expected content array`);const first=result.content[0];assert(first?.type==="text",`${context}: expected text content`);assert(typeof first.text==="string",`${context}: expected text string`);return first.text}function assertCleanErrorEnvelope(result,context){assert(result.isError===true,`${context}: expected MCP error result`);const payload=parseJson(resultText(result,context),context);assertRecord(payload,context);assert(typeof payload.error==="string"&&payload.error.length>0,`${context}: missing error`);assert(typeof payload.code==="string"&&payload.code.length>0,`${context}: missing code`);assert(typeof payload.retryable==="boolean",`${context}: missing retryable`);return payload}function assertHttpUnauthorizedChallenge(metadata,context="unauthenticated HTTP challenge"){assert(metadata.status===401,`${context}: expected HTTP 401`);const challenge=headerValue(metadata.headers,"www-authenticate");assert(typeof challenge==="string"&&challenge.length>0,`${context}: missing WWW-Authenticate header`);assert(/^Bearer\b/i.test(challenge),`${context}: expected Bearer challenge, got ${challenge}`)}function assertDefaultText(result,context){assert(result.isError!==true,`${context}: expected success`);const text=resultText(result,context);assert(text.length>0,`${context}: expected non-empty text`);assert(text.length<DEFAULT_TEXT_LIMIT,`${context}: default text too large (${text.length} chars)`);assertNotJson(text,context);assert(!text.includes("--lifecycle"),`${context}: leaked CLI lifecycle flag`);assert(!text.includes("--verbose"),`${context}: leaked CLI verbose flag`);return text}function assertSearchDefaultText(text,context){const lines=text.split(`
1
+ var EXPECTED_MCP_TOOLS=["quick_start","get_example","search_language","pkg_info","pkg_deps","pkg_vulns","pkg_changelog","pkg_upgrade_review","docs_list","docs_read","code_files","code_read","code_grep","search","search_status","feedback"];var DEFAULT_TEXT_LIMIT=12000;var TARGET_DETAIL_STATE_PATTERN=/^ {2}(?:(?:indexing|searched|available|unavailable|using):|(?:ready|pending|provisional|older snapshot)$|(?:not found|unresolved|version unavailable|repository ref unresolved|(?:package|repository|site|target) (?:not found|unresolved)):)/;var SMOKE_PACKAGE_VERSION="5.2.1";var SMOKE_PACKAGE_TARGET={registry:"npm",package_name:"express",version:SMOKE_PACKAGE_VERSION};function assert(condition,message){if(!condition){throw new Error(message)}}function parseJson(text,context){try{return JSON.parse(text)}catch(error){const message=error instanceof Error?error.message:"unknown error";throw new Error(`${context}: expected parseable JSON (${message})`)}}function assertNotJson(text,context){try{JSON.parse(text)}catch{return}throw new Error(`${context}: default response unexpectedly parsed as JSON`)}function assertRecord(value,context){assert(value!==null&&typeof value==="object"&&!Array.isArray(value),`${context}: expected object`)}function headerValue(headers,name){if(!headers)return null;if("get"in headers&&typeof headers.get==="function"){return headers.get(name)}const lowerName=name.toLowerCase();for(const[key,value]of Object.entries(headers)){if(key.toLowerCase()===lowerName)return value??null}return null}function resultText(result,context){assert(Array.isArray(result.content),`${context}: expected content array`);const first=result.content[0];assert(first?.type==="text",`${context}: expected text content`);assert(typeof first.text==="string",`${context}: expected text string`);return first.text}function assertCleanErrorEnvelope(result,context){assert(result.isError===true,`${context}: expected MCP error result`);const payload=parseJson(resultText(result,context),context);assertRecord(payload,context);assert(typeof payload.error==="string"&&payload.error.length>0,`${context}: missing error`);assert(typeof payload.code==="string"&&payload.code.length>0,`${context}: missing code`);assert(typeof payload.retryable==="boolean",`${context}: missing retryable`);return payload}function assertHttpUnauthorizedChallenge(metadata,context="unauthenticated HTTP challenge"){assert(metadata.status===401,`${context}: expected HTTP 401`);const challenge=headerValue(metadata.headers,"www-authenticate");assert(typeof challenge==="string"&&challenge.length>0,`${context}: missing WWW-Authenticate header`);assert(/^Bearer\b/i.test(challenge),`${context}: expected Bearer challenge, got ${challenge}`)}function assertDefaultText(result,context){assert(result.isError!==true,`${context}: expected success`);const text=resultText(result,context);assert(text.length>0,`${context}: expected non-empty text`);assert(text.length<DEFAULT_TEXT_LIMIT,`${context}: default text too large (${text.length} chars)`);assertNotJson(text,context);assert(!text.includes("--lifecycle"),`${context}: leaked CLI lifecycle flag`);assert(!text.includes("--verbose"),`${context}: leaked CLI verbose flag`);return text}function assertSearchDefaultText(text,context){const lines=text.split(`
2
2
  `);const formatterLines=searchFormatterLines(lines);const formatterText=formatterLines.join(`
3
- `);const firstLine=lines[0]?.trim()??"";assert(firstLine.length>0,`${context}: missing outcome first line`);assert(/^(?:Preparing|Indexing|Searching)\b|^No results returned\b|^\d+ results?\b|^[A-Z_]+ - /.test(firstLine),`${context}: missing outcome headline`);assert(!firstLine.startsWith("search |")&&!firstLine.startsWith("search_status |"),`${context}: legacy header precedes outcome`);assert(!formatterLines.some((line)=>/^status\s*:/i.test(line.trim())),`${context}: duplicated lifecycle status line`);const lifecycleOutcomeLines=lines.filter((line)=>/^(?:Preparing|Indexing|Searching)\b/.test(line));assert(lifecycleOutcomeLines.length<=1,`${context}: duplicate lifecycle outcome lines`);assert(!formatterText.includes("searchRef="),`${context}: leaked searchRef=`);assert(!formatterText.includes("indexingRef"),`${context}: leaked indexingRef`);const forbiddenSections=["Ready:","Waiting:","Available but not searched:","Indexed alternatives:"];for(const section of forbiddenSections){assert(!lines.some((line)=>line.startsWith(section)),`${context}: legacy flat section ${section}`)}assert(!lines.some((line)=>line==="Evidence may change."),`${context}: vague evidence policy prose`);assert(!lines.some((line)=>line.startsWith("Do not repeat")),`${context}: repeat policy prose`);assert(!lines.some((line)=>line.startsWith("Do not poll")),`${context}: poll policy prose`);const hasReadinessText=formatterLines.some((line)=>/^ {2}(?! {2}).*(?:Indexing|Searched|Available now|Unavailable|Using|Status):/.test(line));if(hasReadinessText){assert(formatterLines.some((line)=>/^-\s+\S/.test(line)),`${context}: readiness details must be grouped under a target`)}const nextLines=lines.filter((line)=>line.startsWith("Next:"));assert(nextLines.length<=1,`${context}: multiple Next actions are not allowed`);const searchRefOccurrences=formatterText.match(/search_ref=/g)?.length??0;assert(searchRefOccurrences<=1,`${context}: search_ref= must appear at most once`);if(searchRefOccurrences===1){const refLine=formatterLines.find((line)=>line.includes("search_ref="));assert(refLine?.trimStart().startsWith("Next:"),`${context}: search_ref= must appear only on a Next line`);assert(refLine?.startsWith("Next: search_status "),`${context}: search_ref= must use the MCP search_status action`);assert(refLine!==undefined,`${context}: search_ref= must appear only on a Next line`);const match=refLine.match(/search_ref=(?:"([^"]+)"|(\S+))/);const searchRef=match?.[1]??match?.[2];const summaryLines=lines.filter((line)=>/^Search\s+\S+\s+\|/.test(line));assert(summaryLines.length===1,`${context}: expected one Search <ref> session summary`);assert(searchRef!==undefined&&summaryLines[0]?.startsWith(`Search ${searchRef} |`),`${context}: session summary does not match search_ref action`)}assert(!formatterText.includes("githits search-status ")&&!formatterText.includes("githits code read ")&&!formatterText.includes("githits docs read ")&&!formatterText.includes(" --wait ")&&!formatterText.includes(" --offset "),`${context}: CLI command syntax leaked into MCP output`);assert(hasHumanSearchHitLocator(lines)||lines.some((line)=>line.startsWith("Next:")),`${context}: missing usable result locator or status follow-up`)}function hasHumanSearchHitLocator(lines){return lines.some((line,index)=>{const docsMatch=/^\[\d+\]\s+(\S+)\s+\[docs page\]\s+(.+)$/.exec(line);if(docsMatch){const pageId=docsMatch[1];const docsDetails=docsMatch[2];if(!pageId||pageId==="page ID unavailable"||!docsDetails){return false}const firstDivider=docsDetails.indexOf(" - ");if(firstDivider<=0)return false;const sourceAndTitle=docsDetails.slice(firstDivider+3);const secondDivider=sourceAndTitle.indexOf(" - ");if(secondDivider>0){const source2=sourceAndTitle.slice(0,secondDivider).trim();const title=sourceAndTitle.slice(secondDivider+3).trim();return source2.length>0&&(title.length>0||hasWrappedHitTitle(lines,index))}if(!sourceAndTitle.endsWith(" -"))return false;const source=sourceAndTitle.slice(0,-2).trim();return source.length>0&&hasWrappedHitTitle(lines,index)}const match=/^\[\d+\]\s+(.+?)\s+\[(repo doc|repo code|repo symbol)\](?: -(?: (.*))?)?$/.exec(line);if(!match)return false;const locatorText=match[1];if(!locatorText)return false;const locator=locatorText.trim().split(/\s+/);if(locator.length>=2&&!locatorText.trim().endsWith("location unavailable")&&locator.every((part)=>part.length>0)){const title=match[3];return title===undefined?!line.endsWith(" -")||hasWrappedHitTitle(lines,index):title.trim().length>0||hasWrappedHitTitle(lines,index)}return false})}function hasWrappedHitTitle(lines,index){const titleLine=lines[index+1];return titleLine?.startsWith(" ")===true&&titleLine.trim().length>0}function searchFormatterLines(lines){let inHit=false;return lines.filter((line)=>{if(/^\[\d+\]\s/.test(line)){inHit=true;return true}if(inHit&&line.length>0&&!line.startsWith(" "))inHit=false;return!inHit})}function assertJsonResult(result,context){assert(result.isError!==true,`${context}: expected success`);return parseJson(resultText(result,context),context)}function assertErrorCode(result,context,code){const envelope=assertCleanErrorEnvelope(result,context);assert(envelope.code===code,`${context}: expected ${code}, got ${envelope.code}`)}async function callTool(caller,name,args){return await caller.callTool(name,args)}async function callToolText(caller,name,args){const result=await caller.callTool(name,args);const text=resultText(result,name);if(result.isError===true){throw new Error(text)}return text}async function assertLiveOrAuthRequired(caller,logger){const result=await callTool(caller,"search_language",{query:"python"});if(result.isError===true){const envelope=assertCleanErrorEnvelope(result,"search_language auth probe");assert(envelope.code==="AUTH_REQUIRED",`auth probe returned unexpected code ${envelope.code}`);logger.log("AUTH_REQUIRED: live smoke skipped");return false}const text=assertDefaultText(result,"search_language default");assert(text.includes("python (Python)"),"search_language default missing Python display name");assert(text.includes("aliases:"),"search_language default missing aliases");return true}async function runLiveSmoke(caller){const languageJson=assertJsonResult(await callTool(caller,"search_language",{query:"python",format:"json"}),"search_language json");assert(Array.isArray(languageJson),"search_language json: expected array");const exampleText=assertDefaultText(await callTool(caller,"get_example",{query:"express hello world",language:"javascript"}),"get_example default");assert(exampleText.includes("solution_id:"),"get_example default missing solution_id hint");const exampleJson=assertJsonResult(await callTool(caller,"get_example",{query:"express hello world",language:"javascript",format:"json"}),"get_example json");assertRecord(exampleJson,"get_example json");assert(typeof exampleJson.result==="string","get_example json missing result");const pkgInfoText=assertDefaultText(await callTool(caller,"pkg_info",{registry:"npm",package_name:"express"}),"pkg_info default");assert(pkgInfoText.includes("express"),"pkg_info default missing package name");assert(pkgInfoText.includes("Repository")&&pkgInfoText.includes("stars"),"pkg_info default missing repository popularity");assert(pkgInfoText.includes("Vulnerabilities"),"pkg_info default missing vulnerability status");assert(!pkgInfoText.includes("Install")&&!pkgInfoText.includes("Usage"),"pkg_info default should not include quickstart fields");const pkgInfoJson=assertJsonResult(await callTool(caller,"pkg_info",{registry:"npm",package_name:"express",format:"json"}),"pkg_info json");assertRecord(pkgInfoJson,"pkg_info json");assert(pkgInfoJson.registry==="npm","pkg_info json registry mismatch");assert(pkgInfoJson.name==="express","pkg_info json name mismatch");assert(typeof pkgInfoJson.version==="string","pkg_info json missing version");assert(!("install"in pkgInfoJson)&&!("usage"in pkgInfoJson),"pkg_info json should not include quickstart fields");const depsText=assertDefaultText(await callTool(caller,"pkg_deps",{registry:"npm",package_name:"express"}),"pkg_deps default");assert(depsText.includes("Runtime dependencies:"),"pkg_deps default missing runtime heading");assert(depsText.includes('pass lifecycle="all"'),"pkg_deps default missing MCP-native lifecycle hint");const depsAllText=assertDefaultText(await callTool(caller,"pkg_deps",{registry:"npm",package_name:"express",lifecycle:"all"}),"pkg_deps lifecycle all");assert(depsAllText.includes("Dependency groups:"),"pkg_deps lifecycle all missing groups heading");assert(!depsAllText.includes("Hidden groups:"),"pkg_deps lifecycle all still hides groups");const depsJson=assertJsonResult(await callTool(caller,"pkg_deps",{registry:"npm",package_name:"express",format:"json"}),"pkg_deps json");assertRecord(depsJson,"pkg_deps json");assertRecord(depsJson.runtime,"pkg_deps json runtime");const vulnsText=assertDefaultText(await callTool(caller,"pkg_vulns",{registry:"npm",package_name:"express"}),"pkg_vulns default");assert(vulnsText.includes("express")||vulnsText.includes("vulnerab"),"pkg_vulns default missing context");assert(!vulnsText.includes("use -v"),"pkg_vulns leaked CLI -v hint");const filteredVulnsText=assertDefaultText(await callTool(caller,"pkg_vulns",{registry:"npm",package_name:"lodash",version:"4.17.20",min_severity:"high"}),"pkg_vulns filtered default");assert(filteredVulnsText.includes("Filter severity >= high"),"pkg_vulns filtered default missing filter echo");assert(!filteredVulnsText.includes("use -v"),"pkg_vulns filtered default leaked CLI -v hint");const vulnsJson=assertJsonResult(await callTool(caller,"pkg_vulns",{registry:"npm",package_name:"express",format:"json"}),"pkg_vulns json");assertRecord(vulnsJson,"pkg_vulns json");assert("summary"in vulnsJson||"advisories"in vulnsJson,"pkg_vulns json missing vulnerability data");const filteredVulnsJson=assertJsonResult(await callTool(caller,"pkg_vulns",{registry:"npm",package_name:"lodash",version:"4.17.20",min_severity:"high",format:"json"}),"pkg_vulns filtered json");assertRecord(filteredVulnsJson,"pkg_vulns filtered json");assertRecord(filteredVulnsJson.filter,"pkg_vulns filtered json filter");assert(filteredVulnsJson.filter.minSeverity==="high","pkg_vulns filtered json missing severity filter echo");const scopedVulnsText=assertDefaultText(await callTool(caller,"pkg_vulns",{registry:"npm",package_name:"express",advisory_scope:"non_affecting"}),"pkg_vulns scoped default");assert(scopedVulnsText.includes("Scope historical advisories only"),"pkg_vulns scoped default missing scope echo");assert(scopedVulnsText.includes("No active vulnerabilities affect this version"),"pkg_vulns scoped default missing current-risk statement");assert(!scopedVulnsText.includes("use -v"),"pkg_vulns scoped default leaked CLI -v hint");const scopedVulnsJson=assertJsonResult(await callTool(caller,"pkg_vulns",{registry:"npm",package_name:"express",advisory_scope:"non_affecting",format:"json"}),"pkg_vulns scoped json");assertRecord(scopedVulnsJson,"pkg_vulns scoped json");assertRecord(scopedVulnsJson.filter,"pkg_vulns scoped json filter");assert(scopedVulnsJson.filter.advisoryScope==="non_affecting","pkg_vulns scoped json missing advisory scope echo");const changelogText=assertDefaultText(await callTool(caller,"pkg_changelog",{registry:"npm",package_name:"express",limit:1}),"pkg_changelog default");assert(!changelogText.includes("--verbose"),"pkg_changelog default leaked CLI verbose flag");if(changelogText.includes("truncated")||changelogText.includes("full bodies")){assert(changelogText.includes('pass verbose=true, body_lines=<n>, or format="json"'),"pkg_changelog truncation hint is not MCP-native")}const changelogBodyLinesText=assertDefaultText(await callTool(caller,"pkg_changelog",{registry:"npm",package_name:"express",limit:2,body_lines:3}),"pkg_changelog body_lines");assert(changelogBodyLinesText.includes('pass verbose=true, body_lines=<n>, or format="json"'),"pkg_changelog body_lines missing MCP-native truncation hint");assert(!changelogBodyLinesText.includes("--verbose"),"pkg_changelog body_lines leaked CLI verbose flag");const changelogJson=assertJsonResult(await callTool(caller,"pkg_changelog",{registry:"npm",package_name:"express",limit:1,format:"json"}),"pkg_changelog json");assertRecord(changelogJson,"pkg_changelog json");assertRecord(changelogJson.entries,"pkg_changelog json entries");const changelogTimeline=assertDefaultText(await callTool(caller,"pkg_changelog",{registry:"npm",package_name:"express",limit:2,omit_bodies:true}),"pkg_changelog timeline");assert(!changelogTimeline.includes("What's Changed"),"pkg_changelog omit_bodies=true still emitted bodies");const upgradeReviewText=assertDefaultText(await callTool(caller,"pkg_upgrade_review",{registry:"npm",package_name:"express",current_version:"5.0.0",target_version:"5.2.1",skip_transitive_security:true}),"pkg_upgrade_review default");assert(upgradeReviewText.includes("pkg_upgrade_review")&&upgradeReviewText.includes("vulnerabilities")&&upgradeReviewText.includes("changes"),"pkg_upgrade_review default missing evidence sections");assert(!upgradeReviewText.includes("recommendation")&&!upgradeReviewText.includes("risk level"),"pkg_upgrade_review default leaked assessment language");const upgradeReviewJson=assertJsonResult(await callTool(caller,"pkg_upgrade_review",{registry:"npm",package_name:"express",current_version:"5.0.0",target_version:"5.2.1",skip_transitive_security:true,format:"json"}),"pkg_upgrade_review json");assertRecord(upgradeReviewJson,"pkg_upgrade_review json");assertRecord(upgradeReviewJson.summary,"pkg_upgrade_review json summary");assert(Array.isArray(upgradeReviewJson.reviews),"pkg_upgrade_review json missing reviews array");const firstUpgradeReview=upgradeReviewJson.reviews[0];assert(firstUpgradeReview,"pkg_upgrade_review json missing first review");for(const forbidden of["risk","riskLevel","recommendation","findings","verification"]){assert(!(forbidden in firstUpgradeReview),`pkg_upgrade_review json leaked judgment field ${forbidden}`)}const docsText=assertDefaultText(await callTool(caller,"docs_list",{...SMOKE_PACKAGE_TARGET,limit:2}),"docs_list default");assert(docsText.includes("docs_read page_id="),"docs_list default missing docs_read follow-up");const docsJson=assertJsonResult(await callTool(caller,"docs_list",{...SMOKE_PACKAGE_TARGET,limit:2,format:"json"}),"docs_list json");assertRecord(docsJson,"docs_list json");assert(Array.isArray(docsJson.pages),"docs_list json missing pages array");const firstPage=docsJson.pages[0];assert(firstPage&&typeof firstPage.pageId==="string","docs_list json missing readable page id");const docReadText=assertDefaultText(await callTool(caller,"docs_read",{page_id:firstPage.pageId,start_line:1,end_line:5}),"docs_read default");assert(docReadText.length>0,"docs_read default missing content");const docReadJson=assertJsonResult(await callTool(caller,"docs_read",{page_id:firstPage.pageId,start_line:1,end_line:5,format:"json"}),"docs_read json");assertRecord(docReadJson,"docs_read json");assert(typeof docReadJson.content==="string","docs_read json missing content");const codeFilesText=assertDefaultText(await callTool(caller,"code_files",{target:SMOKE_PACKAGE_TARGET,path_prefix:"package.json",limit:1}),"code_files default");assert(codeFilesText.includes("package.json"),"code_files default missing package.json");const codeFilesJson=assertJsonResult(await callTool(caller,"code_files",{target:SMOKE_PACKAGE_TARGET,path_prefix:"package.json",limit:1,format:"json"}),"code_files json");assertRecord(codeFilesJson,"code_files json");assert(Array.isArray(codeFilesJson.files),"code_files json missing files array");const codeReadText=assertDefaultText(await callTool(caller,"code_read",{target:SMOKE_PACKAGE_TARGET,path:"package.json",start_line:1,end_line:5}),"code_read default");assert(/^1\s+/m.test(codeReadText),"code_read default missing line numbers");const codeReadJson=assertJsonResult(await callTool(caller,"code_read",{target:SMOKE_PACKAGE_TARGET,path:"package.json",start_line:1,end_line:5,format:"json"}),"code_read json");assertRecord(codeReadJson,"code_read json");assert(codeReadJson.path==="package.json","code_read json path mismatch");const codeGrepText=assertDefaultText(await callTool(caller,"code_grep",{target:SMOKE_PACKAGE_TARGET,pattern:"express",path:"package.json",max_matches:1}),"code_grep default");assert(codeGrepText.includes("package.json"),"code_grep default missing package.json");const codeGrepJson=assertJsonResult(await callTool(caller,"code_grep",{target:SMOKE_PACKAGE_TARGET,pattern:"express",path:"package.json",max_matches:1,format:"json"}),"code_grep json");assertRecord(codeGrepJson,"code_grep json");assert("matches"in codeGrepJson||"totalMatches"in codeGrepJson,"code_grep json missing matches");const searchText=assertDefaultText(await callTool(caller,"search",{target:SMOKE_PACKAGE_TARGET,query:"router",limit:1}),"search default");assertSearchDefaultText(searchText,"search default");const searchJson=assertJsonResult(await callTool(caller,"search",{target:SMOKE_PACKAGE_TARGET,query:"router",limit:1,format:"json"}),"search json");assertRecord(searchJson,"search json");const searchRef=typeof searchJson.searchRef==="string"?searchJson.searchRef:undefined;if(searchRef){const statusJson=assertJsonResult(await callTool(caller,"search_status",{search_ref:searchRef,wait_timeout_ms:0,format:"json"}),"search_status json");assertRecord(statusJson,"search_status json");assert("completed"in statusJson||"progress"in statusJson,"search_status json missing status data")}else{assertErrorCode(await callTool(caller,"search_status",{search_ref:"smoke-invalid-search-ref",wait_timeout_ms:0}),"search_status invalid ref","NOT_FOUND")}const feedbackValidation=await callTool(caller,"feedback",{solution_id:"",accepted:true});assert(feedbackValidation.isError===true,"feedback validation should fail before submitting");assert(resultText(feedbackValidation,"feedback validation").includes("MCP error"),"feedback validation missing protocol error text")}async function runMcpSmoke(caller,options={}){const logger=options.logger??console;const includeLiveTools=options.includeLiveTools??true;const toolsResponse=await caller.listTools();const toolNames=new Set(toolsResponse.tools.map((tool)=>tool.name));for(const expected of EXPECTED_MCP_TOOLS){assert(toolNames.has(expected),`listTools missing ${expected}`)}const quickStart=assertDefaultText(await callTool(caller,"quick_start",{}),"quick_start default");for(const expected of["GitHits provides","`search`","`code_grep`"]){assert(quickStart.includes(expected),`quick_start default missing ${expected}`)}if(!includeLiveTools)return;if(await assertLiveOrAuthRequired(caller,logger)){await runLiveSmoke(caller);logger.log("MCP smoke passed")}}export{EXPECTED_MCP_TOOLS,assertCleanErrorEnvelope,assertDefaultText,assertHttpUnauthorizedChallenge,assertJsonResult,callToolText,resultText,runMcpSmoke};
3
+ `);const firstLine=lines[0]?.trim()??"";assert(firstLine.length>0,`${context}: missing outcome first line`);assert(/^(?:No result snapshot yet|No results yet|No result snapshot|No results)\b|^\d+ (?:partial |interim )?results?\b/.test(firstLine),`${context}: missing outcome headline`);assert(!firstLine.startsWith("search |")&&!firstLine.startsWith("search_status |"),`${context}: legacy header precedes outcome`);assert(!formatterLines.some((line)=>/^status\s*:/i.test(line.trim())),`${context}: duplicated lifecycle status line`);assert(!formatterLines.some((line)=>/^Search\s+\S+\s+\|/.test(line)),`${context}: separate Search <ref> session summary`);const lifecycleOutcomeLines=lines.filter((line)=>/\|\s+(?:preparing|indexing|searching)(?:\s*\||$)/.test(line));assert(lifecycleOutcomeLines.length<=1,`${context}: duplicate lifecycle outcome lines`);assert(!formatterText.includes("searchRef="),`${context}: leaked searchRef=`);assert(!formatterText.includes("indexingRef"),`${context}: leaked indexingRef`);const forbiddenSections=["Ready:","Waiting:","Available but not searched:","Indexed alternatives:"];for(const section of forbiddenSections){assert(!lines.some((line)=>line.startsWith(section)),`${context}: legacy flat section ${section}`)}assert(!lines.some((line)=>line==="Evidence may change."),`${context}: vague evidence policy prose`);assert(!lines.some((line)=>line.startsWith("Do not repeat")),`${context}: repeat policy prose`);assert(!lines.some((line)=>line.startsWith("Do not poll")),`${context}: poll policy prose`);const hasReadinessText=formatterLines.some((line)=>TARGET_DETAIL_STATE_PATTERN.test(line));if(hasReadinessText){assert(formatterLines.some((line)=>/^-\s+\S/.test(line)),`${context}: readiness details must be grouped under a target`)}const nextLines=lines.filter((line)=>line.startsWith("Next:"));assert(nextLines.length<=1,`${context}: multiple Next actions are not allowed`);const searchRefOccurrences=formatterText.match(/search_ref=/g)?.length??0;assert(searchRefOccurrences<=1,`${context}: search_ref= must appear at most once`);if(searchRefOccurrences===1){const refLine=formatterLines.find((line)=>line.includes("search_ref="));assert(refLine?.trimStart().startsWith("Next:"),`${context}: search_ref= must appear only on a Next line`);assert(refLine?.startsWith("Next: search_status "),`${context}: search_ref= must use the MCP search_status action`);assert(refLine!==undefined,`${context}: search_ref= must appear only on a Next line`);const match=refLine.match(/search_ref=(?:"([^"]+)"|(\S+))/);const searchRef=match?.[1]??match?.[2];assert(searchRef!==undefined,`${context}: missing search_ref value`)}assert(!formatterText.includes("githits search-status ")&&!formatterText.includes("githits code read ")&&!formatterText.includes("githits docs read ")&&!formatterText.includes(" --wait ")&&!formatterText.includes(" --offset "),`${context}: CLI command syntax leaked into MCP output`);assert(hasHumanSearchHitLocator(lines)||hasTargetRecovery(formatterLines)||lines.some((line)=>line.startsWith("Next:")),`${context}: missing usable result locator or status follow-up`)}function hasTargetRecovery(lines){return lines.some((line,index)=>{if(!/^ {2}(?:Fix|Try):\s+\S/.test(line))return false;for(let previousIndex=index-1;previousIndex>=0;previousIndex-=1){const previous=lines[previousIndex];if(!previous||previous.trim()==="")continue;if(/^-\s+\S/.test(previous))return true;if(previous.startsWith(" "))continue;return false}return false})}function hasHumanSearchHitLocator(lines){return lines.some((line,index)=>{const docsMatch=/^\[\d+\]\s+(\S+)\s+\[docs page\]\s+(.+)$/.exec(line);if(docsMatch){const pageId=docsMatch[1];const docsDetails=docsMatch[2];if(!pageId||pageId==="page ID unavailable"||!docsDetails){return false}const firstDivider=docsDetails.indexOf(" - ");if(firstDivider<=0)return false;const sourceAndTitle=docsDetails.slice(firstDivider+3);const secondDivider=sourceAndTitle.indexOf(" - ");if(secondDivider>0){const source2=sourceAndTitle.slice(0,secondDivider).trim();const title=sourceAndTitle.slice(secondDivider+3).trim();return source2.length>0&&(title.length>0||hasWrappedHitTitle(lines,index))}if(!sourceAndTitle.endsWith(" -"))return false;const source=sourceAndTitle.slice(0,-2).trim();return source.length>0&&hasWrappedHitTitle(lines,index)}const match=/^\[\d+\]\s+(.+?)\s+\[(repo doc|repo code|repo symbol)\](?: -(?: (.*))?)?$/.exec(line);if(!match)return false;const locatorText=match[1];if(!locatorText)return false;const locator=locatorText.trim().split(/\s+/);if(locator.length>=2&&!locatorText.trim().endsWith("location unavailable")&&locator.every((part)=>part.length>0)){const title=match[3];return title===undefined?!line.endsWith(" -")||hasWrappedHitTitle(lines,index):title.trim().length>0||hasWrappedHitTitle(lines,index)}return false})}function hasWrappedHitTitle(lines,index){const titleLine=lines[index+1];return titleLine?.startsWith(" ")===true&&titleLine.trim().length>0}function searchFormatterLines(lines){let inHit=false;return lines.filter((line)=>{if(/^\[\d+\]\s/.test(line)){inHit=true;return true}if(inHit&&line.length>0&&!line.startsWith(" "))inHit=false;return!inHit})}function assertJsonResult(result,context){assert(result.isError!==true,`${context}: expected success`);return parseJson(resultText(result,context),context)}function assertErrorCode(result,context,code){const envelope=assertCleanErrorEnvelope(result,context);assert(envelope.code===code,`${context}: expected ${code}, got ${envelope.code}`)}async function callTool(caller,name,args){return await caller.callTool(name,args)}async function callToolText(caller,name,args){const result=await caller.callTool(name,args);const text=resultText(result,name);if(result.isError===true){throw new Error(text)}return text}async function assertLiveOrAuthRequired(caller,logger){const result=await callTool(caller,"search_language",{query:"python"});if(result.isError===true){const envelope=assertCleanErrorEnvelope(result,"search_language auth probe");assert(envelope.code==="AUTH_REQUIRED",`auth probe returned unexpected code ${envelope.code}`);logger.log("AUTH_REQUIRED: live smoke skipped");return false}const text=assertDefaultText(result,"search_language default");assert(text.includes("python (Python)"),"search_language default missing Python display name");assert(text.includes("aliases:"),"search_language default missing aliases");const packageResult=await callTool(caller,"pkg_info",{registry:"npm",package_name:"express"});if(packageResult.isError===true){const envelope=assertCleanErrorEnvelope(packageResult,"pkg_info auth probe");assert(envelope.code==="AUTH_REQUIRED",`pkg_info auth probe returned unexpected code ${envelope.code}`);logger.log("AUTH_REQUIRED: live smoke skipped");return false}return true}async function runLiveSmoke(caller){const languageJson=assertJsonResult(await callTool(caller,"search_language",{query:"python",format:"json"}),"search_language json");assert(Array.isArray(languageJson),"search_language json: expected array");const exampleText=assertDefaultText(await callTool(caller,"get_example",{query:"express hello world",language:"javascript"}),"get_example default");assert(exampleText.includes("solution_id:"),"get_example default missing solution_id hint");const exampleJson=assertJsonResult(await callTool(caller,"get_example",{query:"express hello world",language:"javascript",format:"json"}),"get_example json");assertRecord(exampleJson,"get_example json");assert(typeof exampleJson.result==="string","get_example json missing result");const pkgInfoText=assertDefaultText(await callTool(caller,"pkg_info",{registry:"npm",package_name:"express"}),"pkg_info default");assert(pkgInfoText.includes("express"),"pkg_info default missing package name");assert(pkgInfoText.includes("Repository")&&pkgInfoText.includes("stars"),"pkg_info default missing repository popularity");assert(pkgInfoText.includes("Vulnerabilities"),"pkg_info default missing vulnerability status");assert(!pkgInfoText.includes("Install")&&!pkgInfoText.includes("Usage"),"pkg_info default should not include quickstart fields");const pkgInfoJson=assertJsonResult(await callTool(caller,"pkg_info",{registry:"npm",package_name:"express",format:"json"}),"pkg_info json");assertRecord(pkgInfoJson,"pkg_info json");assert(pkgInfoJson.registry==="npm","pkg_info json registry mismatch");assert(pkgInfoJson.name==="express","pkg_info json name mismatch");assert(typeof pkgInfoJson.version==="string","pkg_info json missing version");assert(!("install"in pkgInfoJson)&&!("usage"in pkgInfoJson),"pkg_info json should not include quickstart fields");const depsText=assertDefaultText(await callTool(caller,"pkg_deps",{registry:"npm",package_name:"express"}),"pkg_deps default");assert(depsText.includes("Runtime dependencies:"),"pkg_deps default missing runtime heading");assert(depsText.includes('pass lifecycle="all"'),"pkg_deps default missing MCP-native lifecycle hint");const depsAllText=assertDefaultText(await callTool(caller,"pkg_deps",{registry:"npm",package_name:"express",lifecycle:"all"}),"pkg_deps lifecycle all");assert(depsAllText.includes("Dependency groups:"),"pkg_deps lifecycle all missing groups heading");assert(!depsAllText.includes("Hidden groups:"),"pkg_deps lifecycle all still hides groups");const depsJson=assertJsonResult(await callTool(caller,"pkg_deps",{registry:"npm",package_name:"express",format:"json"}),"pkg_deps json");assertRecord(depsJson,"pkg_deps json");assertRecord(depsJson.runtime,"pkg_deps json runtime");const vulnsText=assertDefaultText(await callTool(caller,"pkg_vulns",{registry:"npm",package_name:"express"}),"pkg_vulns default");assert(vulnsText.includes("express")||vulnsText.includes("vulnerab"),"pkg_vulns default missing context");assert(!vulnsText.includes("use -v"),"pkg_vulns leaked CLI -v hint");const filteredVulnsText=assertDefaultText(await callTool(caller,"pkg_vulns",{registry:"npm",package_name:"lodash",version:"4.17.20",min_severity:"high"}),"pkg_vulns filtered default");assert(filteredVulnsText.includes("Filter severity >= high"),"pkg_vulns filtered default missing filter echo");assert(!filteredVulnsText.includes("use -v"),"pkg_vulns filtered default leaked CLI -v hint");const vulnsJson=assertJsonResult(await callTool(caller,"pkg_vulns",{registry:"npm",package_name:"express",format:"json"}),"pkg_vulns json");assertRecord(vulnsJson,"pkg_vulns json");assert("summary"in vulnsJson||"advisories"in vulnsJson,"pkg_vulns json missing vulnerability data");const filteredVulnsJson=assertJsonResult(await callTool(caller,"pkg_vulns",{registry:"npm",package_name:"lodash",version:"4.17.20",min_severity:"high",format:"json"}),"pkg_vulns filtered json");assertRecord(filteredVulnsJson,"pkg_vulns filtered json");assertRecord(filteredVulnsJson.filter,"pkg_vulns filtered json filter");assert(filteredVulnsJson.filter.minSeverity==="high","pkg_vulns filtered json missing severity filter echo");const scopedVulnsText=assertDefaultText(await callTool(caller,"pkg_vulns",{registry:"npm",package_name:"express",advisory_scope:"non_affecting"}),"pkg_vulns scoped default");assert(scopedVulnsText.includes("Scope historical advisories only"),"pkg_vulns scoped default missing scope echo");assert(scopedVulnsText.includes("No active vulnerabilities affect this version"),"pkg_vulns scoped default missing current-risk statement");assert(!scopedVulnsText.includes("use -v"),"pkg_vulns scoped default leaked CLI -v hint");const scopedVulnsJson=assertJsonResult(await callTool(caller,"pkg_vulns",{registry:"npm",package_name:"express",advisory_scope:"non_affecting",format:"json"}),"pkg_vulns scoped json");assertRecord(scopedVulnsJson,"pkg_vulns scoped json");assertRecord(scopedVulnsJson.filter,"pkg_vulns scoped json filter");assert(scopedVulnsJson.filter.advisoryScope==="non_affecting","pkg_vulns scoped json missing advisory scope echo");const changelogText=assertDefaultText(await callTool(caller,"pkg_changelog",{registry:"npm",package_name:"express",limit:1}),"pkg_changelog default");assert(!changelogText.includes("--verbose"),"pkg_changelog default leaked CLI verbose flag");if(changelogText.includes("truncated")||changelogText.includes("full bodies")){assert(changelogText.includes('pass verbose=true, body_lines=<n>, or format="json"'),"pkg_changelog truncation hint is not MCP-native")}const changelogBodyLinesText=assertDefaultText(await callTool(caller,"pkg_changelog",{registry:"npm",package_name:"express",limit:2,body_lines:3}),"pkg_changelog body_lines");assert(changelogBodyLinesText.includes('pass verbose=true, body_lines=<n>, or format="json"'),"pkg_changelog body_lines missing MCP-native truncation hint");assert(!changelogBodyLinesText.includes("--verbose"),"pkg_changelog body_lines leaked CLI verbose flag");const changelogJson=assertJsonResult(await callTool(caller,"pkg_changelog",{registry:"npm",package_name:"express",limit:1,format:"json"}),"pkg_changelog json");assertRecord(changelogJson,"pkg_changelog json");assertRecord(changelogJson.entries,"pkg_changelog json entries");const changelogTimeline=assertDefaultText(await callTool(caller,"pkg_changelog",{registry:"npm",package_name:"express",limit:2,omit_bodies:true}),"pkg_changelog timeline");assert(!changelogTimeline.includes("What's Changed"),"pkg_changelog omit_bodies=true still emitted bodies");const upgradeReviewText=assertDefaultText(await callTool(caller,"pkg_upgrade_review",{registry:"npm",package_name:"express",current_version:"5.0.0",target_version:"5.2.1",skip_transitive_security:true}),"pkg_upgrade_review default");const upgradeReviewFirstLine=upgradeReviewText.split(`
4
+ `)[0]?.trim();assert(upgradeReviewFirstLine==="Upgrade review - 1 package","pkg_upgrade_review default missing outcome headline");assert(upgradeReviewText.includes("npm:express 5.0.0 -> 5.2.1")&&upgradeReviewText.includes(`
5
+ Security
6
+ `)&&upgradeReviewText.includes(`
7
+ Changes
8
+ `),"pkg_upgrade_review default missing grouped evidence");assert(!upgradeReviewText.includes("pkg_upgrade_review")&&!/\b(?:recommendation|risk level|assessment)\b/i.test(upgradeReviewText),"pkg_upgrade_review default leaked assessment language");const upgradeReviewJson=assertJsonResult(await callTool(caller,"pkg_upgrade_review",{registry:"npm",package_name:"express",current_version:"5.0.0",target_version:"5.2.1",skip_transitive_security:true,format:"json"}),"pkg_upgrade_review json");assertRecord(upgradeReviewJson,"pkg_upgrade_review json");assertRecord(upgradeReviewJson.summary,"pkg_upgrade_review json summary");assert(Array.isArray(upgradeReviewJson.reviews),"pkg_upgrade_review json missing reviews array");const firstUpgradeReview=upgradeReviewJson.reviews[0];assert(firstUpgradeReview,"pkg_upgrade_review json missing first review");for(const forbidden of["risk","riskLevel","recommendation","findings","verification"]){assert(!(forbidden in firstUpgradeReview),`pkg_upgrade_review json leaked judgment field ${forbidden}`)}const docsText=assertDefaultText(await callTool(caller,"docs_list",{...SMOKE_PACKAGE_TARGET,limit:2}),"docs_list default");assert(docsText.includes("docs_read page_id="),"docs_list default missing docs_read follow-up");const docsJson=assertJsonResult(await callTool(caller,"docs_list",{...SMOKE_PACKAGE_TARGET,limit:2,format:"json"}),"docs_list json");assertRecord(docsJson,"docs_list json");assert(Array.isArray(docsJson.pages),"docs_list json missing pages array");const firstPage=docsJson.pages[0];assert(firstPage&&typeof firstPage.pageId==="string","docs_list json missing readable page id");const docReadText=assertDefaultText(await callTool(caller,"docs_read",{page_id:firstPage.pageId,start_line:1,end_line:5}),"docs_read default");assert(docReadText.length>0,"docs_read default missing content");const docReadJson=assertJsonResult(await callTool(caller,"docs_read",{page_id:firstPage.pageId,start_line:1,end_line:5,format:"json"}),"docs_read json");assertRecord(docReadJson,"docs_read json");assert(typeof docReadJson.content==="string","docs_read json missing content");const codeFilesText=assertDefaultText(await callTool(caller,"code_files",{target:SMOKE_PACKAGE_TARGET,path_prefix:"package.json",limit:1}),"code_files default");assert(codeFilesText.includes("package.json"),"code_files default missing package.json");const codeFilesJson=assertJsonResult(await callTool(caller,"code_files",{target:SMOKE_PACKAGE_TARGET,path_prefix:"package.json",limit:1,format:"json"}),"code_files json");assertRecord(codeFilesJson,"code_files json");assert(Array.isArray(codeFilesJson.files),"code_files json missing files array");const codeReadText=assertDefaultText(await callTool(caller,"code_read",{target:SMOKE_PACKAGE_TARGET,path:"package.json",start_line:1,end_line:5}),"code_read default");assert(/^1\s+/m.test(codeReadText),"code_read default missing line numbers");const codeReadJson=assertJsonResult(await callTool(caller,"code_read",{target:SMOKE_PACKAGE_TARGET,path:"package.json",start_line:1,end_line:5,format:"json"}),"code_read json");assertRecord(codeReadJson,"code_read json");assert(codeReadJson.path==="package.json","code_read json path mismatch");const codeGrepText=assertDefaultText(await callTool(caller,"code_grep",{target:SMOKE_PACKAGE_TARGET,pattern:"express",path:"package.json",max_matches:1}),"code_grep default");assert(codeGrepText.includes("package.json"),"code_grep default missing package.json");const codeGrepJson=assertJsonResult(await callTool(caller,"code_grep",{target:SMOKE_PACKAGE_TARGET,pattern:"express",path:"package.json",max_matches:1,format:"json"}),"code_grep json");assertRecord(codeGrepJson,"code_grep json");assert("matches"in codeGrepJson||"totalMatches"in codeGrepJson,"code_grep json missing matches");const searchText=assertDefaultText(await callTool(caller,"search",{target:SMOKE_PACKAGE_TARGET,query:"router",limit:1}),"search default");assertSearchDefaultText(searchText,"search default");const searchJson=assertJsonResult(await callTool(caller,"search",{target:SMOKE_PACKAGE_TARGET,query:"router",limit:1,format:"json"}),"search json");assertRecord(searchJson,"search json");const searchRef=typeof searchJson.searchRef==="string"?searchJson.searchRef:undefined;if(searchRef){const statusJson=assertJsonResult(await callTool(caller,"search_status",{search_ref:searchRef,wait_timeout_ms:0,format:"json"}),"search_status json");assertRecord(statusJson,"search_status json");assert("completed"in statusJson||"progress"in statusJson,"search_status json missing status data")}else{assertErrorCode(await callTool(caller,"search_status",{search_ref:"smoke-invalid-search-ref",wait_timeout_ms:0}),"search_status invalid ref","NOT_FOUND")}const feedbackValidation=await callTool(caller,"feedback",{solution_id:"",accepted:true});assert(feedbackValidation.isError===true,"feedback validation should fail before submitting");assert(resultText(feedbackValidation,"feedback validation").includes("MCP error"),"feedback validation missing protocol error text")}async function runMcpSmoke(caller,options={}){const logger=options.logger??console;const includeLiveTools=options.includeLiveTools??true;const toolsResponse=await caller.listTools();const toolNames=new Set(toolsResponse.tools.map((tool)=>tool.name));for(const expected of EXPECTED_MCP_TOOLS){assert(toolNames.has(expected),`listTools missing ${expected}`)}const quickStart=assertDefaultText(await callTool(caller,"quick_start",{}),"quick_start default");for(const expected of["GitHits provides","`search`","`code_grep`"]){assert(quickStart.includes(expected),`quick_start default missing ${expected}`)}if(!includeLiveTools)return;if(await assertLiveOrAuthRequired(caller,logger)){await runLiveSmoke(caller);logger.log("MCP smoke passed")}}export{EXPECTED_MCP_TOOLS,assertCleanErrorEnvelope,assertDefaultText,assertHttpUnauthorizedChallenge,assertJsonResult,callToolText,resultText,runMcpSmoke};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@githits/mcp",
3
- "version": "0.11.2",
3
+ "version": "0.11.3",
4
4
  "description": "Reusable MCP server APIs and tools for GitHits",
5
5
  "type": "module",
6
6
  "files": [