githits 0.13.0 → 0.14.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,4 @@
1
- import{version2}from"./chunk-pxb26at5.js";import{createHash,randomBytes}from"node:crypto";function generateCodeVerifier(){return randomBytes(32).toString("base64url")}function generateCodeChallenge(verifier){return createHash("sha256").update(verifier).digest("base64url")}function generateState(){return randomBytes(32).toString("hex")}import{z as z2}from"zod";var TERMS_ACCEPTANCE_REQUIRED_CODE="TERMS_ACCEPTANCE_REQUIRED";var TERMS_URL="https://githits.com/legal/terms-of-service/";var TERMS_ACCEPTANCE_URL="https://app.githits.com/settings/privacy";class TermsAcceptanceRequiredError extends Error{code=TERMS_ACCEPTANCE_REQUIRED_CODE;termsUrl;acceptanceUrl;constructor(remediation={}){super("Terms acceptance required.");this.name="TermsAcceptanceRequiredError";this.termsUrl=remediation.termsUrl??TERMS_URL;this.acceptanceUrl=remediation.acceptanceUrl??TERMS_ACCEPTANCE_URL}}function createTermsAcceptanceError(payload){const record=parseErrorRecord(payload);if(!record)return;const contract=record.code===TERMS_ACCEPTANCE_REQUIRED_CODE?record:firstGraphQLErrorExtensions(record);if(contract?.code!==TERMS_ACCEPTANCE_REQUIRED_CODE)return;return new TermsAcceptanceRequiredError({termsUrl:stringField(contract,"terms_url"),acceptanceUrl:stringField(contract,"acceptance_url")})}function throwIfTermsAcceptanceRequired(payload){const error=createTermsAcceptanceError(payload);if(error)throw error}function parseErrorRecord(payload){if(typeof payload==="string"){try{return parseErrorRecord(JSON.parse(payload))}catch{return}}return payload&&typeof payload==="object"?payload:undefined}function firstGraphQLErrorExtensions(record){const firstError=Array.isArray(record.errors)?record.errors[0]:undefined;if(!firstError||typeof firstError!=="object")return;const extensions=firstError.extensions;return extensions&&typeof extensions==="object"?extensions:undefined}function stringField(record,field){return typeof record[field]==="string"?record[field]:undefined}var DEFAULT_MCP_URL="https://mcp.githits.com";var DEFAULT_API_URL="https://api.githits.com";var DEFAULT_CODE_NAV_URL="https://pkgseer.dev";class ServiceUrlConfigError extends Error{constructor(message){super(message);this.name="ServiceUrlConfigError"}}function getMcpUrl(){return resolveServiceUrl("GITHITS_MCP_URL",DEFAULT_MCP_URL)}function getMcpStorageKeyUrl(){return process.env.GITHITS_MCP_URL??DEFAULT_MCP_URL}function getApiUrl(){return resolveServiceUrl("GITHITS_API_URL",DEFAULT_API_URL)}function getCodeNavigationUrl(){if(process.env.GITHITS_CODE_NAV_URL!==undefined){return validateServiceUrl(process.env.GITHITS_CODE_NAV_URL,"GITHITS_CODE_NAV_URL")}if(process.env.PKGSEER_URL!==undefined){return validateServiceUrl(process.env.PKGSEER_URL,"PKGSEER_URL")}return DEFAULT_CODE_NAV_URL}function validateServiceUrl(value,source){let parsed;try{parsed=new URL(value)}catch{throw new ServiceUrlConfigError(`Invalid ${source}: expected an HTTPS URL or an HTTP loopback URL.`)}if(parsed.protocol==="https:")return value;const hostname=parsed.hostname.replace(/^\[|\]$/g,"");const isLoopback=hostname==="localhost"||hostname==="127.0.0.1"||hostname==="::1";if(parsed.protocol==="http:"&&isLoopback)return value;throw new ServiceUrlConfigError(`Invalid ${source}: use HTTPS. Plain HTTP is allowed only for localhost, 127.0.0.1, or [::1].`)}function resolveServiceUrl(envName,defaultUrl){const override=process.env[envName];return override===undefined?defaultUrl:validateServiceUrl(override,envName)}function getEnvApiToken(){return process.env.GITHITS_API_TOKEN}import{z}from"zod";var DEFAULT_FETCH_TIMEOUT_MS=120000;class FetchTimeoutError extends Error{timeoutMs;constructor(timeoutMs,options){super(`Request timed out after ${timeoutMs}ms.`,options);this.name="FetchTimeoutError";this.timeoutMs=timeoutMs}}async function fetchWithTimeout(input,init={},options={}){const timeoutMs=options.timeoutMs??DEFAULT_FETCH_TIMEOUT_MS;const timeoutSignal=AbortSignal.timeout(timeoutMs);const signal=init.signal?AbortSignal.any([init.signal,timeoutSignal]):timeoutSignal;const fetchFn=options.fetchFn??globalThis.fetch;let timeoutId;const timeout=new Promise((_,reject)=>{timeoutId=setTimeout(()=>{reject(new FetchTimeoutError(timeoutMs))},timeoutMs)});try{return await Promise.race([fetchFn(input,{...init,signal}),timeout])}catch(cause){if(cause instanceof FetchTimeoutError)throw cause;if(timeoutSignal.aborted&&!init.signal?.aborted){throw new FetchTimeoutError(timeoutMs,{cause})}throw cause}finally{if(timeoutId)clearTimeout(timeoutId)}}function isFetchTimeoutError(error){return error instanceof FetchTimeoutError}var MAX_ERROR_DETAIL_LENGTH=500;function parseHttpErrorDetail(body,fields){if(!body)return;let parsed;try{parsed=JSON.parse(body)}catch{return}if(!isRecord(parsed))return;for(const field of fields){const value=parsed[field];if(typeof value!=="string")continue;const normalized=normalizeSingleLineText(value);if(!normalized)continue;if(normalized.length<=MAX_ERROR_DETAIL_LENGTH)return normalized;return`${normalized.slice(0,MAX_ERROR_DETAIL_LENGTH-3)}...`}return}function normalizeSingleLineText(value){const withoutControlCharacters=Array.from(value,(character)=>{const codePoint=character.codePointAt(0)??0;return codePoint<=31||codePoint===127?" ":character}).join("");return withoutControlCharacters.replace(/\s+/g," ").trim()}function isRecord(value){return value!==null&&typeof value==="object"&&!Array.isArray(value)}var AUTHENTICATION_REQUIRED_MESSAGE="Authentication required.";var LOCAL_AUTHENTICATION_MISSING_MESSAGE="No local GitHits authentication token found.";var SERVER_AUTHENTICATION_REJECTED_MESSAGE="GitHits could not accept the authentication token.";class AuthenticationError extends Error{source;constructor(message=AUTHENTICATION_REQUIRED_MESSAGE,source="local"){super(message);this.name="AuthenticationError";this.source=source}}class ApiRateLimitError extends Error{status=429;retryAfterSeconds;constructor(message="Request rate limited.",retryAfterSeconds){super(message);this.name="ApiRateLimitError";this.retryAfterSeconds=retryAfterSeconds}}function withServiceDiagnostics(diagnostics,name,operation){return diagnostics?diagnostics.withOperation(name,operation):operation()}var DEFAULT_EXAMPLE_REQUEST_TIMEOUT_MS=240000;function isTokenRefreshableError(error){return error instanceof AuthenticationError||error instanceof TermsAcceptanceRequiredError}function parseRetryAfterSeconds(value,nowMs){const normalized=value?.trim();if(!normalized)return;if(/^\d+$/.test(normalized)){const delaySeconds=Number(normalized);return Number.isSafeInteger(delaySeconds)?delaySeconds:undefined}if(/^[+-]?\d+(?:\.\d+)?$/.test(normalized))return;const isHttpDate=/^[A-Z][a-z]{2}, \d{2} [A-Z][a-z]{2} \d{4} \d{2}:\d{2}:\d{2} GMT$/.test(normalized)||/^[A-Z][a-z]+, \d{2}-[A-Z][a-z]{2}-\d{2} \d{2}:\d{2}:\d{2} GMT$/.test(normalized)||/^[A-Z][a-z]{2} [A-Z][a-z]{2} [ \d]\d \d{2}:\d{2}:\d{2} \d{4}$/.test(normalized);if(!isHttpDate)return;const retryAtMs=Date.parse(normalized);if(!Number.isFinite(retryAtMs))return;const delayMs=retryAtMs-nowMs;if(delayMs<0)return;const delaySeconds=Math.ceil(delayMs/1000);return Number.isSafeInteger(delaySeconds)?delaySeconds:undefined}var LANGUAGE_SCHEMA=z.object({id:z.string(),name:z.string(),display_name:z.string(),aliases:z.array(z.string()),search_priority:z.number().optional()});var LANGUAGES_SCHEMA=z.array(LANGUAGE_SCHEMA);class GitHitsServiceImpl{apiUrl;token;fetchFn;fetchTimeoutMs;runtime;constructor(apiUrl,token,fetchFn,fetchTimeoutMs=undefined,runtime={}){this.apiUrl=apiUrl;this.token=token;this.fetchFn=fetchFn;this.fetchTimeoutMs=fetchTimeoutMs;this.runtime=runtime}async search(params,options){options?.signal?.throwIfAborted();return withServiceDiagnostics(this.runtime.diagnostics,"githits.search.request",async()=>{const response=await this.request("/search",{method:"POST",headers:this.headers(),body:JSON.stringify({query:params.query,language:params.language,license_mode:params.licenseMode??"strict",include_explanation:params.includeExplanation??false}),...options?.signal?{signal:options.signal}:{}},this.runtime.exampleRequestTimeoutMs??DEFAULT_EXAMPLE_REQUEST_TIMEOUT_MS);if(!response.ok){throw await this.createError(response)}return response.text()})}async getLanguages(){return withServiceDiagnostics(this.runtime.diagnostics,"githits.languages.request",async()=>{const response=await this.request("/languages",{headers:this.headers()});if(!response.ok){throw await this.createError(response)}return this.parseLanguages(response)})}async searchLanguages(query,limit=5){return withServiceDiagnostics(this.runtime.diagnostics,"githits.languages.search.request",async()=>{const params=new URLSearchParams({query,limit:String(limit)});const response=await this.request(`/languages?${params.toString()}`,{headers:this.headers()});if(!response.ok){throw await this.createError(response)}return this.parseLanguages(response)})}async submitFeedback(params){return withServiceDiagnostics(this.runtime.diagnostics,"githits.feedback.request",async()=>{const response=await this.request("/feedbacks",{method:"POST",headers:this.headers(),body:JSON.stringify({...params.exampleId!==undefined&&{example_id:params.exampleId},...params.solutionId!==undefined&&{solution_id:params.solutionId},accepted:params.accepted,feedback_text:params.feedbackText??null,...params.toolName!==undefined&&{tool_name:params.toolName}})});if(!response.ok){throw await this.createError(response)}return{success:true,message:"Feedback submitted successfully"}})}headers(){return{...this.runtime.clientHeaders?.(),Authorization:`Bearer ${this.token}`,"Content-Type":"application/json","User-Agent":this.runtime.userAgent??"githits-cli"}}fetchOptions(defaultTimeoutMs=DEFAULT_FETCH_TIMEOUT_MS){return{fetchFn:this.fetchFn,timeoutMs:this.fetchTimeoutMs??defaultTimeoutMs}}async request(path,init,defaultTimeoutMs=DEFAULT_FETCH_TIMEOUT_MS){const apiUrl=validateServiceUrl(this.apiUrl,"GITHITS_API_URL");const fetchOptions=this.fetchOptions(defaultTimeoutMs);try{return await fetchWithTimeout(`${apiUrl.replace(/\/+$/,"")}${path}`,init,fetchOptions)}catch(cause){if(isCallerAbort(cause,init.signal))throw cause;if(isFetchTimeoutError(cause)||isAbortError(cause)){throw new GitHitsRequestTimeoutError(fetchOptions.timeoutMs,cause)}if(cause instanceof TypeError){throw new Error("Could not connect to GitHits. Check your connection and GITHITS_API_URL, then try again.",{cause})}throw cause}}async parseLanguages(response){let data;try{data=await response.json()}catch(cause){throw new Error("GitHits returned an invalid languages response.",{cause})}const parsed=LANGUAGES_SCHEMA.safeParse(data);if(!parsed.success){throw new Error("GitHits returned an invalid languages response.",{cause:parsed.error})}return parsed.data}async createError(response){const status=response.status;const body=await response.text().catch(()=>"");const detail=parseHttpErrorDetail(body,["detail"]);throwIfTermsAcceptanceRequired(body);switch(status){case 401:return new AuthenticationError(SERVER_AUTHENTICATION_REJECTED_MESSAGE,"server");case 403:return new Error("Access denied.");case 404:return new Error(detail||"Resource not found.");case 429:return new ApiRateLimitError(undefined,parseRetryAfterSeconds(response.headers.get("Retry-After"),Date.now()));default:{if(status>=500){return new Error(`Server error (${status}). Try again shortly.${detail?` ${detail}`:""}`)}return new Error(`Request failed with status ${status}.${detail?` ${detail}`:""}`)}}}}class GitHitsRequestTimeoutError extends FetchTimeoutError{constructor(timeoutMs,cause){super(timeoutMs,{cause});this.name="GitHitsRequestTimeoutError";this.message="Request to GitHits timed out. Try again."}}function isAbortError(error){return error instanceof Error&&error.name==="AbortError"}function isCallerAbort(error,signal){return Boolean(signal?.aborted&&(error===signal.reason||isAbortError(error)))}async function executeWithTokenRefresh(options){const token=await options.getToken();if(!token){throw new AuthenticationError(LOCAL_AUTHENTICATION_MISSING_MESSAGE,"local")}try{return await options.executeWithToken(token)}catch(error){if(token.startsWith("ghi-")||!options.shouldRefresh(error)){throw error}const refreshedToken=await options.forceRefresh();if(!refreshedToken){throw error}return options.executeWithToken(refreshedToken)}}var AGENTIC_ASK_REQUEST_TIMEOUT_MS=210000;var AGENTIC_ASK_MAX_RESPONSE_BYTES=4*1024*1024;var UUID_V7_PATTERN=/^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;var sourceLineRangeSchema=z2.string().regex(/^\d+-\d+$/);var cliSourceArgumentsSchema=z2.union([z2.tuple([z2.literal("githits@latest"),z2.literal("code"),z2.literal("read"),z2.literal("--lines"),sourceLineRangeSchema,z2.literal("--"),z2.string().min(1),z2.string().min(1)]),z2.tuple([z2.literal("githits@latest"),z2.literal("docs"),z2.literal("read"),z2.literal("--lines"),sourceLineRangeSchema,z2.literal("--"),z2.string().min(1)])]);var cliSourceCallSchema=z2.object({command:z2.literal("npx"),arguments:cliSourceArgumentsSchema});var cliResponseSchema=z2.object({source_format:z2.literal("cli"),tool_call_id:z2.string().regex(UUID_V7_PATTERN),thread_id:z2.string().regex(UUID_V7_PATTERN),answer_markdown:z2.string().min(1),sources:z2.array(cliSourceCallSchema)});var mcpCodeReadSourceCallSchema=z2.object({name:z2.literal("code_read"),arguments:z2.object({target:z2.string().min(1),path:z2.string().min(1),start_line:z2.number().int().min(1),end_line:z2.number().int().min(1)})});var mcpDocumentationReadSourceCallSchema=z2.object({name:z2.literal("docs_read"),arguments:z2.object({page_id:z2.string().min(1),start_line:z2.number().int().min(1),end_line:z2.number().int().min(1)})});var mcpResponseSchema=z2.object({source_format:z2.literal("mcp"),tool_call_id:z2.string().regex(UUID_V7_PATTERN),thread_id:z2.string().regex(UUID_V7_PATTERN),answer_markdown:z2.string().min(1),sources:z2.array(z2.discriminatedUnion("name",[mcpCodeReadSourceCallSchema,mcpDocumentationReadSourceCallSchema]))});var upstreamUrlSchema=z2.string().refine((value)=>value===value.trim()&&!hasControlCharacters(value)).pipe(z2.string().url()).refine((value)=>{if(!URL.canParse(value))return false;const protocol=new URL(value).protocol;return protocol==="http:"||protocol==="https:"});var urlResponseSchema=z2.object({source_format:z2.literal("url"),tool_call_id:z2.string().regex(UUID_V7_PATTERN),thread_id:z2.string().regex(UUID_V7_PATTERN),answer_markdown:z2.string().min(1),sources:z2.array(z2.object({url:upstreamUrlSchema}))});class AgenticAskHttpError extends Error{code;status;toolCallId;retryAfterSeconds;threadId;retryable;constructor(code,message,status,toolCallId,retryAfterSeconds,retryable=false,threadId){super(message);this.code=code;this.status=status;this.toolCallId=toolCallId;this.retryAfterSeconds=retryAfterSeconds;this.threadId=threadId;this.name="AgenticAskHttpError";this.retryable=retryable}}class AgenticAskRequestTimeoutError extends Error{timeoutMs;constructor(timeoutMs){super("Agentic Ask timed out. Try again.");this.timeoutMs=timeoutMs;this.name="AgenticAskRequestTimeoutError"}}class AgenticAskConnectionError extends Error{constructor(options){super("Could not connect to GitHits. Check your connection and try again.",{cause:options?.cause});this.name="AgenticAskConnectionError"}}class MalformedAgenticAskResponseError extends Error{constructor(options){super("GitHits returned an invalid Agentic Ask response.",{cause:options?.cause});this.name="MalformedAgenticAskResponseError"}}class AgenticAskResponseTooLargeError extends Error{maxBytes;constructor(maxBytes=AGENTIC_ASK_MAX_RESPONSE_BYTES){super("GitHits returned an Agentic Ask response that was too large.");this.maxBytes=maxBytes;this.name="AgenticAskResponseTooLargeError"}}class AgenticAskServiceImpl{apiUrl;tokenProvider;fetchFn;runtime;constructor(apiUrl,tokenProvider,fetchFn=globalThis.fetch,runtime={}){this.apiUrl=apiUrl;this.tokenProvider=tokenProvider;this.fetchFn=fetchFn;this.runtime=runtime}async ask(request,options){return this.askRequest(request,options)}async askRequest(request,options={}){return withServiceDiagnostics(this.runtime.diagnostics,"agentic-ask.request",()=>withRequestDeadline((signal)=>executeWithTokenRefresh({getToken:()=>this.tokenProvider.getToken(),forceRefresh:()=>this.tokenProvider.forceRefresh(),shouldRefresh:(error)=>error instanceof AgenticAskHttpError&&error.code==="AUTH_REQUIRED"||isTokenRefreshableError(error),executeWithToken:(token)=>this.executeAsk(token,request,signal)}),options.signal,this.runtime.timeoutMs??AGENTIC_ASK_REQUEST_TIMEOUT_MS))}async executeAsk(token,request,signal){const apiUrl=validateServiceUrl(this.apiUrl,"GITHITS_API_URL");let response;try{response=await this.fetchFn(`${apiUrl.replace(/\/+$/,"")}/ask`,{method:"POST",headers:{...this.runtime.clientHeaders?.(),Authorization:`Bearer ${token}`,"Content-Type":"application/json","User-Agent":this.runtime.userAgent??"githits-cli"},body:JSON.stringify({...request.target!==undefined?{target:request.target}:{thread_id:request.threadId},question:request.question,source_format:request.sourceFormat??"cli"}),signal})}catch(cause){if(signal.aborted||isAbortError2(cause))throw cause;if(cause instanceof TypeError){throw new AgenticAskConnectionError({cause})}throw cause}const toolCallId=parseAgenticAskToolCallId(response.headers.get("X-GitHits-Tool-Call-Id"));const threadId=normalizeAgenticAskThreadId(response.headers.get("X-GitHits-Thread-Id"));if(!response.ok){if(response.status===403){let body="";try{body=await readBoundedResponseBody(response)}catch(cause){if(signal.aborted)throw signal.reason??cause}throwIfTermsAcceptanceRequired(body)}else{await response.body?.cancel().catch(()=>{return})}throw createHttpError(response,toolCallId,threadId)}let body;try{body=await readBoundedResponseBody(response)}catch(cause){if(signal.aborted||cause instanceof AgenticAskResponseTooLargeError){throw cause}throw new AgenticAskConnectionError({cause})}let raw;try{raw=JSON.parse(body)}catch(cause){throw new MalformedAgenticAskResponseError({cause})}const responseSchema=request.sourceFormat==="mcp"?mcpResponseSchema:request.sourceFormat==="url"?urlResponseSchema:cliResponseSchema;const parsed=responseSchema.safeParse(raw);if(!parsed.success){throw new MalformedAgenticAskResponseError({cause:parsed.error})}return parsed.data}}function parseAgenticAskToolCallId(value){return normalizeUuidV7(value)}function normalizeAgenticAskThreadId(value){return normalizeUuidV7(value)}function normalizeUuidV7(value){if(!value||value!==value.trim())return;if(value.includes(",")||hasControlCharacters(value))return;return UUID_V7_PATTERN.test(value)?value.toLowerCase():undefined}async function readBoundedResponseBody(response){const declaredLength=response.headers.get("Content-Length");if(isDeclaredBodyTooLarge(declaredLength)){await response.body?.cancel().catch(()=>{return});throw new AgenticAskResponseTooLargeError}if(!response.body)return"";const reader=response.body.getReader();const decoder=new TextDecoder;let totalBytes=0;let text="";try{while(true){const{done,value}=await reader.read();if(done)break;totalBytes+=value.byteLength;if(totalBytes>AGENTIC_ASK_MAX_RESPONSE_BYTES){await reader.cancel().catch(()=>{return});throw new AgenticAskResponseTooLargeError}text+=decoder.decode(value,{stream:true})}return text+decoder.decode()}finally{reader.releaseLock()}}function isDeclaredBodyTooLarge(value){if(!value||!/^\d+$/.test(value))return false;try{return BigInt(value)>BigInt(AGENTIC_ASK_MAX_RESPONSE_BYTES)}catch{return false}}function createHttpError(response,toolCallId,threadId){const status=response.status;switch(status){case 400:return new AgenticAskHttpError("INVALID_TARGET","GitHits rejected the Agentic Ask target.",status,toolCallId,undefined,false,threadId);case 401:return new AgenticAskHttpError("AUTH_REQUIRED","GitHits could not accept the authentication token.",status,toolCallId,undefined,false,threadId);case 403:return new AgenticAskHttpError("ACCESS_DENIED","Access to Agentic Ask is denied.",status,toolCallId,undefined,false,threadId);case 404:return new AgenticAskHttpError("THREAD_NOT_FOUND","Agentic Ask thread was not found.",status,toolCallId,undefined,false,threadId);case 409:return new AgenticAskHttpError("INVALID_REQUEST","This Agentic Ask thread cannot accept another follow-up.",status,toolCallId,undefined,false,threadId);case 422:return new AgenticAskHttpError("INVALID_REQUEST","GitHits rejected the Agentic Ask request.",status,toolCallId,undefined,false,threadId);case 429:return new AgenticAskHttpError("RATE_LIMITED","Agentic Ask is rate limited.",status,toolCallId,parseRetryAfterSeconds(response.headers.get("Retry-After"),Date.now()),true,threadId);case 500:return new AgenticAskHttpError("EXECUTION_FAILED","Agentic Ask failed.",status,toolCallId,undefined,false,threadId);case 503:return new AgenticAskHttpError("SERVICE_UNAVAILABLE","Agentic Ask is temporarily unavailable.",status,toolCallId,undefined,true,threadId);case 504:return new AgenticAskHttpError("TIMEOUT","Agentic Ask timed out.",status,toolCallId,undefined,true,threadId);default:return new AgenticAskHttpError("HTTP_ERROR",`Agentic Ask request failed with status ${status}.`,status,toolCallId,undefined,status>=500,threadId)}}async function withRequestDeadline(operation,callerSignal,timeoutMs){callerSignal?.throwIfAborted();const timeoutController=new AbortController;const timeoutError=new AgenticAskRequestTimeoutError(timeoutMs);const signal=callerSignal?AbortSignal.any([callerSignal,timeoutController.signal]):timeoutController.signal;let timeoutId;const timeout=new Promise((_,reject)=>{timeoutId=setTimeout(()=>{timeoutController.abort(timeoutError);reject(timeoutError)},timeoutMs)});try{return await Promise.race([operation(signal),timeout])}catch(cause){if(callerSignal?.aborted){throw callerSignal.reason??cause}if(timeoutController.signal.aborted)throw timeoutError;throw cause}finally{if(timeoutId)clearTimeout(timeoutId)}}function hasControlCharacters(value){return Array.from(value).some((character)=>{const codePoint=character.codePointAt(0)??0;return codePoint<=31||codePoint>=127&&codePoint<=159})}function isAbortError2(error){return error instanceof Error&&error.name==="AbortError"}var CLIENT_UPDATE_REQUIRED_REASON="Backend protocol changed";class ClientUpdateRequiredError extends Error{reason;currentVersion;constructor(message=`Update required: ${CLIENT_UPDATE_REQUIRED_REASON}`,reason=CLIENT_UPDATE_REQUIRED_REASON,currentVersion=undefined){super(message);this.reason=reason;this.currentVersion=currentVersion;this.name="ClientUpdateRequiredError"}}function isClientUpdateRequiredGraphQLError(input){return input.code==="CLIENT_UPDATE_REQUIRED"}function isGraphQLSchemaMismatchError(input){if(!isGraphQLSchemaMismatchMessage(input.message))return false;return!input.code||input.code==="GRAPHQL_VALIDATION_FAILED"||input.code==="BAD_USER_INPUT"}function isGraphQLSchemaMismatchMessage(message){return/Cannot query field|Field .* does not exist|Unknown argument|Unknown type|Unknown field/i.test(message)}import{z as z3}from"zod";class PkgseerTransportError extends Error{constructor(message,options){super(message,options);this.name="PkgseerTransportError"}}function baseUrl(endpointUrl){return endpointUrl.replace(/\/+$/,"")}async function postPkgseerGraphql(request){const userAgent=request.userAgent??"githits-cli";const timeoutMs=request.timeoutMs??DEFAULT_FETCH_TIMEOUT_MS;const endpointUrl=validateServiceUrl(request.endpointUrl,"package/source service URL");let response;try{response=await fetchWithTimeout(`${baseUrl(endpointUrl)}/api/graphql`,{method:"POST",headers:{...request.clientHeaders?.(),Authorization:`Bearer ${request.token}`,"Content-Type":"application/json","User-Agent":userAgent},body:JSON.stringify({query:request.query,variables:request.variables})},{fetchFn:request.fetchFn,timeoutMs})}catch(cause){if(request.diagnostics?.isEnabled("pkg-graphql")){request.diagnostics.debug("pkg-graphql",{event:"transport-error",errorName:cause instanceof Error?cause.name:typeof cause,hasCause:true})}throw new PkgseerTransportError("Network request failed before a response was received. Caller should re-wrap with a domain-specific message.",{cause})}const responseBody=await response.text().catch(()=>"");const parsedBody=parseJsonOrNull(responseBody);throwIfTermsAcceptanceRequired(parsedBody);return{status:response.status,responseBody,parsedBody}}function parseJsonOrNull(body){if(!body)return null;try{return JSON.parse(body)}catch{return null}}var PKGSEER_REGISTRY_ARGS=["npm","pypi","hex","crates","nuget","maven","zig","vcpkg","packagist","rubygems","go","swift"];var registryMap={npm:"NPM",pypi:"PYPI",hex:"HEX",crates:"CRATES",nuget:"NUGET",maven:"MAVEN",zig:"ZIG",vcpkg:"VCPKG",packagist:"PACKAGIST",rubygems:"RUBYGEMS",go:"GO",swift:"SWIFT"};var PKGSEER_REGISTRY_VALUES=Object.values(registryMap);var PKGSEER_REGISTRY_LIST=PKGSEER_REGISTRY_ARGS.join(", ");function toPkgseerRegistry(registry){return registryMap[registry]}function toPkgseerRegistryLowercase(registry){for(const[lower,upper]of Object.entries(registryMap)){if(upper===registry)return lower}throw new Error(`Unknown registry value: ${String(registry)} (schema drift?)`)}function isKnownPkgseerRegistryArg(value){return Object.hasOwn(registryMap,value)}var INDEXING_WAIT_HINT="Wait until ready with CLI `--wait 60000` or MCP `wait_timeout_ms: 60000`.";var GREP_REPO_SYMBOL_FIELDS=["symbol_ref","name","qualified_path","kind","category","arity","is_public","file_path","start_line","end_line","content_hash","parent_path"];class CodeNavigationAccessError extends Error{constructor(message){super(message);this.name="CodeNavigationAccessError"}}class CodeNavigationGraphQLError extends Error{code;constructor(message,code){super(message);this.code=code;this.name="CodeNavigationGraphQLError"}}class CodeNavigationIndexingError extends Error{indexingRef;availableVersions;availableRefs;targetResolution;indexingEstimate;hint;constructor(message,indexingRef,availableVersions,availableRefs,targetResolution=undefined,indexingEstimate=undefined,hint=undefined){super(message);this.indexingRef=indexingRef;this.availableVersions=availableVersions;this.availableRefs=availableRefs;this.targetResolution=targetResolution;this.indexingEstimate=indexingEstimate;this.hint=hint;this.name="CodeNavigationIndexingError"}}class CodeNavigationUnresolvableError extends Error{constructor(message){super(message);this.name="CodeNavigationUnresolvableError"}}class MalformedCodeNavigationResponseError extends Error{constructor(message){super(message);this.name="MalformedCodeNavigationResponseError"}}class CodeDiffError extends Error{details;partial;constructor(message,details=undefined,partial=undefined){super(message);this.details=details;this.partial=partial;this.name="CodeDiffError"}}class CodeNavigationTargetNotFoundError extends Error{availableVersions;repoUrl;requestedRef;metadata;constructor(message,availableVersions,repoUrl,requestedRef,metadata=undefined){super(message);this.availableVersions=availableVersions;this.repoUrl=repoUrl;this.requestedRef=requestedRef;this.metadata=metadata;this.name="CodeNavigationTargetNotFoundError"}}class CodeNavigationFileNotFoundError extends Error{filePath;constructor(message,filePath){super(message);this.filePath=filePath;this.name="CodeNavigationFileNotFoundError"}}class CodeNavigationVersionNotFoundError extends Error{packageName;requestedVersion;latestIndexed;availableVersions;metadata;constructor(message,packageName,requestedVersion,latestIndexed,availableVersions,metadata=undefined){super(message);this.packageName=packageName;this.requestedVersion=requestedVersion;this.latestIndexed=latestIndexed;this.availableVersions=availableVersions;this.metadata=metadata;this.name="CodeNavigationVersionNotFoundError"}}class CodeNavigationRefNotFoundError extends Error{repoUrl;requestedRef;availableRefs;suggestedRefs;metadata;constructor(message,repoUrl,requestedRef,availableRefs,suggestedRefs,metadata=undefined){super(message);this.repoUrl=repoUrl;this.requestedRef=requestedRef;this.availableRefs=availableRefs;this.suggestedRefs=suggestedRefs;this.metadata=metadata;this.name="CodeNavigationRefNotFoundError"}}class CodeNavigationValidationError extends Error{constructor(message){super(message);this.name="CodeNavigationValidationError"}}class CodeNavigationFeatureFlagRequiredError extends Error{constructor(message){super(message);this.name="CodeNavigationFeatureFlagRequiredError"}}class CodeNavigationNetworkError extends Error{constructor(message,options){super(message,options);this.name="CodeNavigationNetworkError"}}class CodeNavigationBackendError extends Error{status;graphqlCode;retryable;metadata;constructor(message,status,graphqlCode,retryable,metadata=undefined){super(message);this.status=status;this.graphqlCode=graphqlCode;this.retryable=retryable;this.metadata=metadata;this.name="CodeNavigationBackendError"}}var TARGET_RESOLUTION_AVAILABLE_REFS_SELECTION=`
1
+ import{version2}from"./chunk-p501y1h6.js";import{createHash,randomBytes}from"node:crypto";function generateCodeVerifier(){return randomBytes(32).toString("base64url")}function generateCodeChallenge(verifier){return createHash("sha256").update(verifier).digest("base64url")}function generateState(){return randomBytes(32).toString("hex")}import{z as z2}from"zod";var TERMS_ACCEPTANCE_REQUIRED_CODE="TERMS_ACCEPTANCE_REQUIRED";var TERMS_URL="https://githits.com/legal/terms-of-service/";var TERMS_ACCEPTANCE_URL="https://app.githits.com/settings/privacy";class TermsAcceptanceRequiredError extends Error{code=TERMS_ACCEPTANCE_REQUIRED_CODE;termsUrl;acceptanceUrl;constructor(remediation={}){super("Terms acceptance required.");this.name="TermsAcceptanceRequiredError";this.termsUrl=remediation.termsUrl??TERMS_URL;this.acceptanceUrl=remediation.acceptanceUrl??TERMS_ACCEPTANCE_URL}}function createTermsAcceptanceError(payload){const record=parseErrorRecord(payload);if(!record)return;const contract=record.code===TERMS_ACCEPTANCE_REQUIRED_CODE?record:firstGraphQLErrorExtensions(record);if(contract?.code!==TERMS_ACCEPTANCE_REQUIRED_CODE)return;return new TermsAcceptanceRequiredError({termsUrl:stringField(contract,"terms_url"),acceptanceUrl:stringField(contract,"acceptance_url")})}function throwIfTermsAcceptanceRequired(payload){const error=createTermsAcceptanceError(payload);if(error)throw error}function parseErrorRecord(payload){if(typeof payload==="string"){try{return parseErrorRecord(JSON.parse(payload))}catch{return}}return payload&&typeof payload==="object"?payload:undefined}function firstGraphQLErrorExtensions(record){const firstError=Array.isArray(record.errors)?record.errors[0]:undefined;if(!firstError||typeof firstError!=="object")return;const extensions=firstError.extensions;return extensions&&typeof extensions==="object"?extensions:undefined}function stringField(record,field){return typeof record[field]==="string"?record[field]:undefined}var DEFAULT_MCP_URL="https://mcp.githits.com";var DEFAULT_API_URL="https://api.githits.com";var DEFAULT_CODE_NAV_URL="https://pkgseer.dev";class ServiceUrlConfigError extends Error{constructor(message){super(message);this.name="ServiceUrlConfigError"}}function getMcpUrl(){return resolveServiceUrl("GITHITS_MCP_URL",DEFAULT_MCP_URL)}function getMcpStorageKeyUrl(){return process.env.GITHITS_MCP_URL??DEFAULT_MCP_URL}function getApiUrl(){return resolveServiceUrl("GITHITS_API_URL",DEFAULT_API_URL)}function getCodeNavigationUrl(){if(process.env.GITHITS_CODE_NAV_URL!==undefined){return validateServiceUrl(process.env.GITHITS_CODE_NAV_URL,"GITHITS_CODE_NAV_URL")}if(process.env.PKGSEER_URL!==undefined){return validateServiceUrl(process.env.PKGSEER_URL,"PKGSEER_URL")}return DEFAULT_CODE_NAV_URL}function validateServiceUrl(value,source){let parsed;try{parsed=new URL(value)}catch{throw new ServiceUrlConfigError(`Invalid ${source}: expected an HTTPS URL or an HTTP loopback URL.`)}if(parsed.protocol==="https:")return value;const hostname=parsed.hostname.replace(/^\[|\]$/g,"");const isLoopback=hostname==="localhost"||hostname==="127.0.0.1"||hostname==="::1";if(parsed.protocol==="http:"&&isLoopback)return value;throw new ServiceUrlConfigError(`Invalid ${source}: use HTTPS. Plain HTTP is allowed only for localhost, 127.0.0.1, or [::1].`)}function resolveServiceUrl(envName,defaultUrl){const override=process.env[envName];return override===undefined?defaultUrl:validateServiceUrl(override,envName)}function getEnvApiToken(){return process.env.GITHITS_API_TOKEN}import{z}from"zod";var DEFAULT_FETCH_TIMEOUT_MS=120000;class FetchTimeoutError extends Error{timeoutMs;constructor(timeoutMs,options){super(`Request timed out after ${timeoutMs}ms.`,options);this.name="FetchTimeoutError";this.timeoutMs=timeoutMs}}async function fetchWithTimeout(input,init={},options={}){const timeoutMs=options.timeoutMs??DEFAULT_FETCH_TIMEOUT_MS;const timeoutSignal=AbortSignal.timeout(timeoutMs);const signal=init.signal?AbortSignal.any([init.signal,timeoutSignal]):timeoutSignal;const fetchFn=options.fetchFn??globalThis.fetch;let timeoutId;const timeout=new Promise((_,reject)=>{timeoutId=setTimeout(()=>{reject(new FetchTimeoutError(timeoutMs))},timeoutMs)});try{return await Promise.race([fetchFn(input,{...init,signal}),timeout])}catch(cause){if(cause instanceof FetchTimeoutError)throw cause;if(timeoutSignal.aborted&&!init.signal?.aborted){throw new FetchTimeoutError(timeoutMs,{cause})}throw cause}finally{if(timeoutId)clearTimeout(timeoutId)}}function isFetchTimeoutError(error){return error instanceof FetchTimeoutError}var MAX_ERROR_DETAIL_LENGTH=500;function parseHttpErrorDetail(body,fields){if(!body)return;let parsed;try{parsed=JSON.parse(body)}catch{return}if(!isRecord(parsed))return;for(const field of fields){const value=parsed[field];if(typeof value!=="string")continue;const normalized=normalizeSingleLineText(value);if(!normalized)continue;if(normalized.length<=MAX_ERROR_DETAIL_LENGTH)return normalized;return`${normalized.slice(0,MAX_ERROR_DETAIL_LENGTH-3)}...`}return}function normalizeSingleLineText(value){const withoutControlCharacters=Array.from(value,(character)=>{const codePoint=character.codePointAt(0)??0;return codePoint<=31||codePoint===127?" ":character}).join("");return withoutControlCharacters.replace(/\s+/g," ").trim()}function isRecord(value){return value!==null&&typeof value==="object"&&!Array.isArray(value)}var AUTHENTICATION_REQUIRED_MESSAGE="Authentication required.";var LOCAL_AUTHENTICATION_MISSING_MESSAGE="No local GitHits authentication token found.";var SERVER_AUTHENTICATION_REJECTED_MESSAGE="GitHits could not accept the authentication token.";class AuthenticationError extends Error{source;constructor(message=AUTHENTICATION_REQUIRED_MESSAGE,source="local"){super(message);this.name="AuthenticationError";this.source=source}}class ApiRateLimitError extends Error{status=429;retryAfterSeconds;constructor(message="Request rate limited.",retryAfterSeconds){super(message);this.name="ApiRateLimitError";this.retryAfterSeconds=retryAfterSeconds}}function withServiceDiagnostics(diagnostics,name,operation){return diagnostics?diagnostics.withOperation(name,operation):operation()}var DEFAULT_EXAMPLE_REQUEST_TIMEOUT_MS=240000;function isTokenRefreshableError(error){return error instanceof AuthenticationError||error instanceof TermsAcceptanceRequiredError}function parseRetryAfterSeconds(value,nowMs){const normalized=value?.trim();if(!normalized)return;if(/^\d+$/.test(normalized)){const delaySeconds=Number(normalized);return Number.isSafeInteger(delaySeconds)?delaySeconds:undefined}if(/^[+-]?\d+(?:\.\d+)?$/.test(normalized))return;const isHttpDate=/^[A-Z][a-z]{2}, \d{2} [A-Z][a-z]{2} \d{4} \d{2}:\d{2}:\d{2} GMT$/.test(normalized)||/^[A-Z][a-z]+, \d{2}-[A-Z][a-z]{2}-\d{2} \d{2}:\d{2}:\d{2} GMT$/.test(normalized)||/^[A-Z][a-z]{2} [A-Z][a-z]{2} [ \d]\d \d{2}:\d{2}:\d{2} \d{4}$/.test(normalized);if(!isHttpDate)return;const retryAtMs=Date.parse(normalized);if(!Number.isFinite(retryAtMs))return;const delayMs=retryAtMs-nowMs;if(delayMs<0)return;const delaySeconds=Math.ceil(delayMs/1000);return Number.isSafeInteger(delaySeconds)?delaySeconds:undefined}var LANGUAGE_SCHEMA=z.object({id:z.string(),name:z.string(),display_name:z.string(),aliases:z.array(z.string()),search_priority:z.number().optional()});var LANGUAGES_SCHEMA=z.array(LANGUAGE_SCHEMA);class GitHitsServiceImpl{apiUrl;token;fetchFn;fetchTimeoutMs;runtime;constructor(apiUrl,token,fetchFn,fetchTimeoutMs=undefined,runtime={}){this.apiUrl=apiUrl;this.token=token;this.fetchFn=fetchFn;this.fetchTimeoutMs=fetchTimeoutMs;this.runtime=runtime}async search(params,options){options?.signal?.throwIfAborted();return withServiceDiagnostics(this.runtime.diagnostics,"githits.search.request",async()=>{const response=await this.request("/search",{method:"POST",headers:this.headers(),body:JSON.stringify({query:params.query,language:params.language,license_mode:params.licenseMode??"strict",include_explanation:params.includeExplanation??false}),...options?.signal?{signal:options.signal}:{}},this.runtime.exampleRequestTimeoutMs??DEFAULT_EXAMPLE_REQUEST_TIMEOUT_MS);if(!response.ok){throw await this.createError(response)}return response.text()})}async getLanguages(){return withServiceDiagnostics(this.runtime.diagnostics,"githits.languages.request",async()=>{const response=await this.request("/languages",{headers:this.headers()});if(!response.ok){throw await this.createError(response)}return this.parseLanguages(response)})}async searchLanguages(query,limit=5){return withServiceDiagnostics(this.runtime.diagnostics,"githits.languages.search.request",async()=>{const params=new URLSearchParams({query,limit:String(limit)});const response=await this.request(`/languages?${params.toString()}`,{headers:this.headers()});if(!response.ok){throw await this.createError(response)}return this.parseLanguages(response)})}async submitFeedback(params){return withServiceDiagnostics(this.runtime.diagnostics,"githits.feedback.request",async()=>{const response=await this.request("/feedbacks",{method:"POST",headers:this.headers(),body:JSON.stringify({...params.exampleId!==undefined&&{example_id:params.exampleId},...params.solutionId!==undefined&&{solution_id:params.solutionId},accepted:params.accepted,feedback_text:params.feedbackText??null,...params.toolName!==undefined&&{tool_name:params.toolName}})});if(!response.ok){throw await this.createError(response)}return{success:true,message:"Feedback submitted successfully"}})}headers(){return{...this.runtime.clientHeaders?.(),Authorization:`Bearer ${this.token}`,"Content-Type":"application/json","User-Agent":this.runtime.userAgent??"githits-cli"}}fetchOptions(defaultTimeoutMs=DEFAULT_FETCH_TIMEOUT_MS){return{fetchFn:this.fetchFn,timeoutMs:this.fetchTimeoutMs??defaultTimeoutMs}}async request(path,init,defaultTimeoutMs=DEFAULT_FETCH_TIMEOUT_MS){const apiUrl=validateServiceUrl(this.apiUrl,"GITHITS_API_URL");const fetchOptions=this.fetchOptions(defaultTimeoutMs);try{return await fetchWithTimeout(`${apiUrl.replace(/\/+$/,"")}${path}`,init,fetchOptions)}catch(cause){if(isCallerAbort(cause,init.signal))throw cause;if(isFetchTimeoutError(cause)||isAbortError(cause)){throw new GitHitsRequestTimeoutError(fetchOptions.timeoutMs,cause)}if(cause instanceof TypeError){throw new Error("Could not connect to GitHits. Check your connection and GITHITS_API_URL, then try again.",{cause})}throw cause}}async parseLanguages(response){let data;try{data=await response.json()}catch(cause){throw new Error("GitHits returned an invalid languages response.",{cause})}const parsed=LANGUAGES_SCHEMA.safeParse(data);if(!parsed.success){throw new Error("GitHits returned an invalid languages response.",{cause:parsed.error})}return parsed.data}async createError(response){const status=response.status;const body=await response.text().catch(()=>"");const detail=parseHttpErrorDetail(body,["detail"]);throwIfTermsAcceptanceRequired(body);switch(status){case 401:return new AuthenticationError(SERVER_AUTHENTICATION_REJECTED_MESSAGE,"server");case 403:return new Error("Access denied.");case 404:return new Error(detail||"Resource not found.");case 429:return new ApiRateLimitError(undefined,parseRetryAfterSeconds(response.headers.get("Retry-After"),Date.now()));default:{if(status>=500){return new Error(`Server error (${status}). Try again shortly.${detail?` ${detail}`:""}`)}return new Error(`Request failed with status ${status}.${detail?` ${detail}`:""}`)}}}}class GitHitsRequestTimeoutError extends FetchTimeoutError{constructor(timeoutMs,cause){super(timeoutMs,{cause});this.name="GitHitsRequestTimeoutError";this.message="Request to GitHits timed out. Try again."}}function isAbortError(error){return error instanceof Error&&error.name==="AbortError"}function isCallerAbort(error,signal){return Boolean(signal?.aborted&&(error===signal.reason||isAbortError(error)))}async function executeWithTokenRefresh(options){const token=await options.getToken();if(!token){throw new AuthenticationError(LOCAL_AUTHENTICATION_MISSING_MESSAGE,"local")}try{return await options.executeWithToken(token)}catch(error){if(token.startsWith("ghi-")||!options.shouldRefresh(error)){throw error}const refreshedToken=await options.forceRefresh();if(!refreshedToken){throw error}return options.executeWithToken(refreshedToken)}}var AGENTIC_ASK_REQUEST_TIMEOUT_MS=210000;var AGENTIC_ASK_MAX_RESPONSE_BYTES=4*1024*1024;var UUID_V7_PATTERN=/^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;var sourceLineRangeSchema=z2.string().regex(/^\d+-\d+$/);var cliSourceArgumentsSchema=z2.union([z2.tuple([z2.literal("githits@latest"),z2.literal("code"),z2.literal("read"),z2.literal("--lines"),sourceLineRangeSchema,z2.literal("--"),z2.string().min(1),z2.string().min(1)]),z2.tuple([z2.literal("githits@latest"),z2.literal("docs"),z2.literal("read"),z2.literal("--lines"),sourceLineRangeSchema,z2.literal("--"),z2.string().min(1)])]);var cliSourceCallSchema=z2.object({command:z2.literal("npx"),arguments:cliSourceArgumentsSchema});var cliResponseSchema=z2.object({source_format:z2.literal("cli"),tool_call_id:z2.string().regex(UUID_V7_PATTERN),thread_id:z2.string().regex(UUID_V7_PATTERN),answer_markdown:z2.string().min(1),sources:z2.array(cliSourceCallSchema)});var mcpCodeReadSourceCallSchema=z2.object({name:z2.literal("code_read"),arguments:z2.object({target:z2.string().min(1),path:z2.string().min(1),start_line:z2.number().int().min(1),end_line:z2.number().int().min(1)})});var mcpDocumentationReadSourceCallSchema=z2.object({name:z2.literal("docs_read"),arguments:z2.object({page_id:z2.string().min(1),start_line:z2.number().int().min(1),end_line:z2.number().int().min(1)})});var mcpResponseSchema=z2.object({source_format:z2.literal("mcp"),tool_call_id:z2.string().regex(UUID_V7_PATTERN),thread_id:z2.string().regex(UUID_V7_PATTERN),answer_markdown:z2.string().min(1),sources:z2.array(z2.discriminatedUnion("name",[mcpCodeReadSourceCallSchema,mcpDocumentationReadSourceCallSchema]))});var upstreamUrlSchema=z2.string().refine((value)=>value===value.trim()&&!hasControlCharacters(value)).pipe(z2.string().url()).refine((value)=>{if(!URL.canParse(value))return false;const protocol=new URL(value).protocol;return protocol==="http:"||protocol==="https:"});var urlResponseSchema=z2.object({source_format:z2.literal("url"),tool_call_id:z2.string().regex(UUID_V7_PATTERN),thread_id:z2.string().regex(UUID_V7_PATTERN),answer_markdown:z2.string().min(1),sources:z2.array(z2.object({url:upstreamUrlSchema}))});class AgenticAskHttpError extends Error{code;status;toolCallId;retryAfterSeconds;threadId;retryable;constructor(code,message,status,toolCallId,retryAfterSeconds,retryable=false,threadId){super(message);this.code=code;this.status=status;this.toolCallId=toolCallId;this.retryAfterSeconds=retryAfterSeconds;this.threadId=threadId;this.name="AgenticAskHttpError";this.retryable=retryable}}class AgenticAskRequestTimeoutError extends Error{timeoutMs;constructor(timeoutMs){super("Agentic Ask timed out. Try again.");this.timeoutMs=timeoutMs;this.name="AgenticAskRequestTimeoutError"}}class AgenticAskConnectionError extends Error{constructor(options){super("Could not connect to GitHits. Check your connection and try again.",{cause:options?.cause});this.name="AgenticAskConnectionError"}}class MalformedAgenticAskResponseError extends Error{constructor(options){super("GitHits returned an invalid Agentic Ask response.",{cause:options?.cause});this.name="MalformedAgenticAskResponseError"}}class AgenticAskResponseTooLargeError extends Error{maxBytes;constructor(maxBytes=AGENTIC_ASK_MAX_RESPONSE_BYTES){super("GitHits returned an Agentic Ask response that was too large.");this.maxBytes=maxBytes;this.name="AgenticAskResponseTooLargeError"}}class AgenticAskServiceImpl{apiUrl;tokenProvider;fetchFn;runtime;constructor(apiUrl,tokenProvider,fetchFn=globalThis.fetch,runtime={}){this.apiUrl=apiUrl;this.tokenProvider=tokenProvider;this.fetchFn=fetchFn;this.runtime=runtime}async ask(request,options){return this.askRequest(request,options)}async askRequest(request,options={}){return withServiceDiagnostics(this.runtime.diagnostics,"agentic-ask.request",()=>withRequestDeadline((signal)=>executeWithTokenRefresh({getToken:()=>this.tokenProvider.getToken(),forceRefresh:()=>this.tokenProvider.forceRefresh(),shouldRefresh:(error)=>error instanceof AgenticAskHttpError&&error.code==="AUTH_REQUIRED"||isTokenRefreshableError(error),executeWithToken:(token)=>this.executeAsk(token,request,signal)}),options.signal,this.runtime.timeoutMs??AGENTIC_ASK_REQUEST_TIMEOUT_MS))}async executeAsk(token,request,signal){const apiUrl=validateServiceUrl(this.apiUrl,"GITHITS_API_URL");let response;try{response=await this.fetchFn(`${apiUrl.replace(/\/+$/,"")}/ask`,{method:"POST",headers:{...this.runtime.clientHeaders?.(),Authorization:`Bearer ${token}`,"Content-Type":"application/json","User-Agent":this.runtime.userAgent??"githits-cli"},body:JSON.stringify({...request.target!==undefined?{target:request.target}:{thread_id:request.threadId},question:request.question,source_format:request.sourceFormat??"cli"}),signal})}catch(cause){if(signal.aborted||isAbortError2(cause))throw cause;if(cause instanceof TypeError){throw new AgenticAskConnectionError({cause})}throw cause}const toolCallId=parseAgenticAskToolCallId(response.headers.get("X-GitHits-Tool-Call-Id"));const threadId=normalizeAgenticAskThreadId(response.headers.get("X-GitHits-Thread-Id"));if(!response.ok){if(response.status===403){let body="";try{body=await readBoundedResponseBody(response)}catch(cause){if(signal.aborted)throw signal.reason??cause}throwIfTermsAcceptanceRequired(body)}else{await response.body?.cancel().catch(()=>{return})}throw createHttpError(response,toolCallId,threadId)}let body;try{body=await readBoundedResponseBody(response)}catch(cause){if(signal.aborted||cause instanceof AgenticAskResponseTooLargeError){throw cause}throw new AgenticAskConnectionError({cause})}let raw;try{raw=JSON.parse(body)}catch(cause){throw new MalformedAgenticAskResponseError({cause})}const responseSchema=request.sourceFormat==="mcp"?mcpResponseSchema:request.sourceFormat==="url"?urlResponseSchema:cliResponseSchema;const parsed=responseSchema.safeParse(raw);if(!parsed.success){throw new MalformedAgenticAskResponseError({cause:parsed.error})}return parsed.data}}function parseAgenticAskToolCallId(value){return normalizeUuidV7(value)}function normalizeAgenticAskThreadId(value){return normalizeUuidV7(value)}function normalizeUuidV7(value){if(!value||value!==value.trim())return;if(value.includes(",")||hasControlCharacters(value))return;return UUID_V7_PATTERN.test(value)?value.toLowerCase():undefined}async function readBoundedResponseBody(response){const declaredLength=response.headers.get("Content-Length");if(isDeclaredBodyTooLarge(declaredLength)){await response.body?.cancel().catch(()=>{return});throw new AgenticAskResponseTooLargeError}if(!response.body)return"";const reader=response.body.getReader();const decoder=new TextDecoder;let totalBytes=0;let text="";try{while(true){const{done,value}=await reader.read();if(done)break;totalBytes+=value.byteLength;if(totalBytes>AGENTIC_ASK_MAX_RESPONSE_BYTES){await reader.cancel().catch(()=>{return});throw new AgenticAskResponseTooLargeError}text+=decoder.decode(value,{stream:true})}return text+decoder.decode()}finally{reader.releaseLock()}}function isDeclaredBodyTooLarge(value){if(!value||!/^\d+$/.test(value))return false;try{return BigInt(value)>BigInt(AGENTIC_ASK_MAX_RESPONSE_BYTES)}catch{return false}}function createHttpError(response,toolCallId,threadId){const status=response.status;switch(status){case 400:return new AgenticAskHttpError("INVALID_TARGET","GitHits rejected the Agentic Ask target.",status,toolCallId,undefined,false,threadId);case 401:return new AgenticAskHttpError("AUTH_REQUIRED","GitHits could not accept the authentication token.",status,toolCallId,undefined,false,threadId);case 403:return new AgenticAskHttpError("ACCESS_DENIED","Access to Agentic Ask is denied.",status,toolCallId,undefined,false,threadId);case 404:return new AgenticAskHttpError("THREAD_NOT_FOUND","Agentic Ask thread was not found.",status,toolCallId,undefined,false,threadId);case 409:return new AgenticAskHttpError("INVALID_REQUEST","This Agentic Ask thread cannot accept another follow-up.",status,toolCallId,undefined,false,threadId);case 422:return new AgenticAskHttpError("INVALID_REQUEST","GitHits rejected the Agentic Ask request.",status,toolCallId,undefined,false,threadId);case 429:return new AgenticAskHttpError("RATE_LIMITED","Agentic Ask is rate limited.",status,toolCallId,parseRetryAfterSeconds(response.headers.get("Retry-After"),Date.now()),true,threadId);case 500:return new AgenticAskHttpError("EXECUTION_FAILED","Agentic Ask failed.",status,toolCallId,undefined,false,threadId);case 503:return new AgenticAskHttpError("SERVICE_UNAVAILABLE","Agentic Ask is temporarily unavailable.",status,toolCallId,undefined,true,threadId);case 504:return new AgenticAskHttpError("TIMEOUT","Agentic Ask timed out.",status,toolCallId,undefined,true,threadId);default:return new AgenticAskHttpError("HTTP_ERROR",`Agentic Ask request failed with status ${status}.`,status,toolCallId,undefined,status>=500,threadId)}}async function withRequestDeadline(operation,callerSignal,timeoutMs){callerSignal?.throwIfAborted();const timeoutController=new AbortController;const timeoutError=new AgenticAskRequestTimeoutError(timeoutMs);const signal=callerSignal?AbortSignal.any([callerSignal,timeoutController.signal]):timeoutController.signal;let timeoutId;const timeout=new Promise((_,reject)=>{timeoutId=setTimeout(()=>{timeoutController.abort(timeoutError);reject(timeoutError)},timeoutMs)});try{return await Promise.race([operation(signal),timeout])}catch(cause){if(callerSignal?.aborted){throw callerSignal.reason??cause}if(timeoutController.signal.aborted)throw timeoutError;throw cause}finally{if(timeoutId)clearTimeout(timeoutId)}}function hasControlCharacters(value){return Array.from(value).some((character)=>{const codePoint=character.codePointAt(0)??0;return codePoint<=31||codePoint>=127&&codePoint<=159})}function isAbortError2(error){return error instanceof Error&&error.name==="AbortError"}var CLIENT_UPDATE_REQUIRED_REASON="Backend protocol changed";class ClientUpdateRequiredError extends Error{reason;currentVersion;constructor(message=`Update required: ${CLIENT_UPDATE_REQUIRED_REASON}`,reason=CLIENT_UPDATE_REQUIRED_REASON,currentVersion=undefined){super(message);this.reason=reason;this.currentVersion=currentVersion;this.name="ClientUpdateRequiredError"}}function isClientUpdateRequiredGraphQLError(input){return input.code==="CLIENT_UPDATE_REQUIRED"}function isGraphQLSchemaMismatchError(input){if(!isGraphQLSchemaMismatchMessage(input.message))return false;return!input.code||input.code==="GRAPHQL_VALIDATION_FAILED"||input.code==="BAD_USER_INPUT"}function isGraphQLSchemaMismatchMessage(message){return/Cannot query field|Field .* does not exist|Unknown argument|Unknown type|Unknown field/i.test(message)}import{z as z3}from"zod";class PkgseerTransportError extends Error{constructor(message,options){super(message,options);this.name="PkgseerTransportError"}}function baseUrl(endpointUrl){return endpointUrl.replace(/\/+$/,"")}async function postPkgseerGraphql(request){const userAgent=request.userAgent??"githits-cli";const timeoutMs=request.timeoutMs??DEFAULT_FETCH_TIMEOUT_MS;const endpointUrl=validateServiceUrl(request.endpointUrl,"package/source service URL");let response;try{response=await fetchWithTimeout(`${baseUrl(endpointUrl)}/api/graphql`,{method:"POST",headers:{...request.clientHeaders?.(),Authorization:`Bearer ${request.token}`,"Content-Type":"application/json","User-Agent":userAgent},body:JSON.stringify({query:request.query,variables:request.variables})},{fetchFn:request.fetchFn,timeoutMs})}catch(cause){if(request.diagnostics?.isEnabled("pkg-graphql")){request.diagnostics.debug("pkg-graphql",{event:"transport-error",errorName:cause instanceof Error?cause.name:typeof cause,hasCause:true})}throw new PkgseerTransportError("Network request failed before a response was received. Caller should re-wrap with a domain-specific message.",{cause})}const responseBody=await response.text().catch(()=>"");const parsedBody=parseJsonOrNull(responseBody);throwIfTermsAcceptanceRequired(parsedBody);return{status:response.status,responseBody,parsedBody}}function parseJsonOrNull(body){if(!body)return null;try{return JSON.parse(body)}catch{return null}}var PKGSEER_REGISTRY_ARGS=["npm","pypi","hex","crates","nuget","maven","zig","vcpkg","packagist","rubygems","go","swift"];var registryMap={npm:"NPM",pypi:"PYPI",hex:"HEX",crates:"CRATES",nuget:"NUGET",maven:"MAVEN",zig:"ZIG",vcpkg:"VCPKG",packagist:"PACKAGIST",rubygems:"RUBYGEMS",go:"GO",swift:"SWIFT"};var PKGSEER_REGISTRY_VALUES=Object.values(registryMap);var PKGSEER_REGISTRY_LIST=PKGSEER_REGISTRY_ARGS.join(", ");function toPkgseerRegistry(registry){return registryMap[registry]}function toPkgseerRegistryLowercase(registry){for(const[lower,upper]of Object.entries(registryMap)){if(upper===registry)return lower}throw new Error(`Unknown registry value: ${String(registry)} (schema drift?)`)}function isKnownPkgseerRegistryArg(value){return Object.hasOwn(registryMap,value)}var INDEXING_WAIT_HINT="Wait until ready with CLI `--wait 60000` or MCP `wait_timeout_ms: 60000`.";var GREP_REPO_SYMBOL_FIELDS=["symbol_ref","name","qualified_path","kind","category","arity","is_public","file_path","start_line","end_line","content_hash","parent_path"];class CodeNavigationAccessError extends Error{constructor(message){super(message);this.name="CodeNavigationAccessError"}}class CodeNavigationGraphQLError extends Error{code;constructor(message,code){super(message);this.code=code;this.name="CodeNavigationGraphQLError"}}class CodeNavigationIndexingError extends Error{indexingRef;availableVersions;availableRefs;targetResolution;indexingEstimate;hint;constructor(message,indexingRef,availableVersions,availableRefs,targetResolution=undefined,indexingEstimate=undefined,hint=undefined){super(message);this.indexingRef=indexingRef;this.availableVersions=availableVersions;this.availableRefs=availableRefs;this.targetResolution=targetResolution;this.indexingEstimate=indexingEstimate;this.hint=hint;this.name="CodeNavigationIndexingError"}}class CodeNavigationUnresolvableError extends Error{constructor(message){super(message);this.name="CodeNavigationUnresolvableError"}}class MalformedCodeNavigationResponseError extends Error{constructor(message){super(message);this.name="MalformedCodeNavigationResponseError"}}class CodeDiffError extends Error{details;partial;constructor(message,details=undefined,partial=undefined){super(message);this.details=details;this.partial=partial;this.name="CodeDiffError"}}class CodeNavigationTargetNotFoundError extends Error{availableVersions;repoUrl;requestedRef;metadata;constructor(message,availableVersions,repoUrl,requestedRef,metadata=undefined){super(message);this.availableVersions=availableVersions;this.repoUrl=repoUrl;this.requestedRef=requestedRef;this.metadata=metadata;this.name="CodeNavigationTargetNotFoundError"}}class CodeNavigationFileNotFoundError extends Error{filePath;constructor(message,filePath){super(message);this.filePath=filePath;this.name="CodeNavigationFileNotFoundError"}}class CodeNavigationVersionNotFoundError extends Error{packageName;requestedVersion;latestIndexed;availableVersions;metadata;constructor(message,packageName,requestedVersion,latestIndexed,availableVersions,metadata=undefined){super(message);this.packageName=packageName;this.requestedVersion=requestedVersion;this.latestIndexed=latestIndexed;this.availableVersions=availableVersions;this.metadata=metadata;this.name="CodeNavigationVersionNotFoundError"}}class CodeNavigationRefNotFoundError extends Error{repoUrl;requestedRef;availableRefs;suggestedRefs;metadata;constructor(message,repoUrl,requestedRef,availableRefs,suggestedRefs,metadata=undefined){super(message);this.repoUrl=repoUrl;this.requestedRef=requestedRef;this.availableRefs=availableRefs;this.suggestedRefs=suggestedRefs;this.metadata=metadata;this.name="CodeNavigationRefNotFoundError"}}class CodeNavigationValidationError extends Error{constructor(message){super(message);this.name="CodeNavigationValidationError"}}class CodeNavigationFeatureFlagRequiredError extends Error{constructor(message){super(message);this.name="CodeNavigationFeatureFlagRequiredError"}}class CodeNavigationNetworkError extends Error{constructor(message,options){super(message,options);this.name="CodeNavigationNetworkError"}}class CodeNavigationBackendError extends Error{status;graphqlCode;retryable;metadata;constructor(message,status,graphqlCode,retryable,metadata=undefined){super(message);this.status=status;this.graphqlCode=graphqlCode;this.retryable=retryable;this.metadata=metadata;this.name="CodeNavigationBackendError"}}var TARGET_RESOLUTION_AVAILABLE_REFS_SELECTION=`
2
2
  availableRefs {
3
3
  version
4
4
  ref
@@ -134,6 +134,7 @@ kind
134
134
  category
135
135
  language`;var UNIFIED_SEARCH_REPOSITORY_EVIDENCE_SELECTION=`
136
136
  repositoryEvidence {
137
+ bm25MatchFields
137
138
  semanticContext {
138
139
  scopes {
139
140
  name
@@ -162,7 +163,23 @@ repositoryEvidence {
162
163
  endLine
163
164
  }
164
165
  }
165
- focusedSource {
166
+ focusedSource @include(if: $includeFocusedSource) {
167
+ startLine
168
+ endLine
169
+ matchLine
170
+ rangeKind
171
+ matchSpansTruncated
172
+ linesOmittedBefore
173
+ linesOmittedAfter
174
+ lines {
175
+ lineNumber
176
+ text
177
+ highlights
178
+ prefixTruncated
179
+ suffixTruncated
180
+ }
181
+ }
182
+ matchedSource {
166
183
  startLine
167
184
  endLine
168
185
  matchLine
@@ -192,6 +209,7 @@ query UnifiedSearch(
192
209
  $limit: Int
193
210
  $offset: Int
194
211
  $waitTimeoutMs: Int
212
+ $includeFocusedSource: Boolean!
195
213
  ) {
196
214
  search(
197
215
  targets: $targets
@@ -224,6 +242,10 @@ query UnifiedSearch(
224
242
  title
225
243
  summary
226
244
  }
245
+ documentationPreview {
246
+ text
247
+ highlights
248
+ }
227
249
  ${UNIFIED_SEARCH_REPOSITORY_EVIDENCE_SELECTION}
228
250
  locator {
229
251
  ${UNIFIED_SEARCH_LOCATOR_SELECTION}
@@ -303,7 +325,7 @@ query UnifiedSearch(
303
325
  }
304
326
  }
305
327
  }`;var UNIFIED_SEARCH_STATUS_QUERY=`
306
- query UnifiedSearchStatus($searchRef: String!, $includeResults: Boolean!, $waitTimeoutMs: Int) {
328
+ query UnifiedSearchStatus($searchRef: String!, $includeResults: Boolean!, $waitTimeoutMs: Int, $includeFocusedSource: Boolean!) {
307
329
  discoverySearchProgress(searchRef: $searchRef, includeResults: $includeResults, waitTimeoutMs: $waitTimeoutMs) {
308
330
  searchRef
309
331
  status
@@ -363,6 +385,10 @@ query UnifiedSearchStatus($searchRef: String!, $includeResults: Boolean!, $waitT
363
385
  title
364
386
  summary
365
387
  }
388
+ documentationPreview {
389
+ text
390
+ highlights
391
+ }
366
392
  ${UNIFIED_SEARCH_REPOSITORY_EVIDENCE_SELECTION}
367
393
  locator {
368
394
  ${UNIFIED_SEARCH_LOCATOR_SELECTION}
@@ -400,7 +426,7 @@ query UnifiedSearchStatus($searchRef: String!, $includeResults: Boolean!, $waitT
400
426
  }
401
427
  }
402
428
  }
403
- }`;function debugUnifiedSearchRequest(variables,diagnostics){if(!diagnostics?.isEnabled("code-nav"))return;const serialised=serialiseForDebug(variables);const filters=asRecord(serialised.filters);diagnostics.debug("code-nav",{event:"request",operation:"search",targetCount:Array.isArray(serialised.targets)?serialised.targets.length:0,sources:Array.isArray(serialised.sources)?serialised.sources:[],hasFilters:filters!==undefined,filterKeys:filters?Object.keys(filters).sort():[],fileIntent:filters&&typeof filters.fileIntent==="string"?filters.fileIntent:"omitted",allowPartialResults:serialised.allowPartialResults===true,presentVariableKeys:Object.keys(serialised).sort(),hasLimit:typeof serialised.limit==="number",hasOffset:typeof serialised.offset==="number",waitTimeoutMs:typeof serialised.waitTimeoutMs==="number"?serialised.waitTimeoutMs:undefined})}function debugGraphqlWireRequest(operation,graphqlQuery,variables,diagnostics){if(!diagnostics?.isEnabled("code-nav-wire"))return;diagnostics.debug("code-nav-wire",{event:"wire-request",operation,graphqlQuery,variables:serialiseForDebug(variables)})}function serialiseForDebug(value){try{const text=JSON.stringify(value);if(!text)return{};const parsed=JSON.parse(text);return asRecord(parsed)??{}}catch{return{}}}function asRecord(value){if(value&&typeof value==="object"&&!Array.isArray(value)){return value}return}var availableVersionSchema=z3.object({version:z3.string().nullable().optional(),ref:z3.string()});var indexingDurationEstimateSchema=z3.object({lowerSeconds:z3.number().int().nullable().optional(),upperSeconds:z3.number().int().nullable().optional(),elapsedSeconds:z3.number().int().nullable().optional(),sampleCount:z3.number().int().nullable().optional(),source:z3.string().nullable().optional()}).nullable().optional();var targetResolutionIdentitySchema=z3.object({kind:z3.string().nullable().optional(),registry:z3.string().nullable().optional(),packageName:z3.string().nullable().optional(),version:z3.string().nullable().optional(),repoUrl:z3.string().nullable().optional(),gitRef:z3.string().nullable().optional(),commitSha:z3.string().nullable().optional(),site:z3.string().nullable().optional()}).nullable().optional();var targetResolutionSchema=z3.object({requested:targetResolutionIdentitySchema,resolvedRequested:targetResolutionIdentitySchema,served:targetResolutionIdentitySchema,freshness:z3.string().nullable().optional(),freshnessReason:z3.string().nullable().optional(),indexingRef:z3.string().nullable().optional(),availableVersions:z3.array(availableVersionSchema).nullable().optional(),availableRefs:z3.array(availableVersionSchema).nullable().optional(),suggestedRefs:z3.array(availableVersionSchema).nullable().optional()}).nullable().optional();var unifiedSearchSourceSchema=z3.enum(["AUTO","DOCS","CODE","SYMBOL"]);var unifiedSearchResultTypeSchema=z3.enum(["DOCUMENTATION_PAGE","REPOSITORY_SYMBOL","REPOSITORY_CODE","REPOSITORY_DOC"]);var unifiedSearchLineRangeSchema=z3.object({startLine:z3.number().int().positive(),endLine:z3.number().int().positive()}).refine((range)=>range.startLine<=range.endLine,{message:"startLine must be less than or equal to endLine"});var unifiedSearchEvidenceRangeSchema=unifiedSearchLineRangeSchema.extend({matchLine:z3.number().int().positive().nullable().optional(),rangeKind:z3.string().nullable().optional(),matchSpansTruncated:z3.boolean()});var unifiedSearchDefinitionRangeSchema=unifiedSearchLineRangeSchema.extend({filePath:z3.string(),repositoryFilePath:z3.string()});var unifiedSearchSymbolContextBaseSchema=z3.object({name:z3.string(),qualifiedPath:z3.string().nullable().optional(),kind:z3.string().nullable().optional()});var unifiedSearchSymbolContextSchema=z3.discriminatedUnion("relation",[unifiedSearchSymbolContextBaseSchema.extend({relation:z3.literal("ENCLOSES_MATCH"),definitionRange:unifiedSearchDefinitionRangeSchema}),unifiedSearchSymbolContextBaseSchema.extend({relation:z3.literal("ASSOCIATED_WITH_INDEXED_CHUNK"),definitionRange:unifiedSearchDefinitionRangeSchema.nullable().optional()})]);var unifiedSearchLocatorSchema=z3.object({registry:z3.string().nullable().optional(),packageName:z3.string().nullable().optional(),version:z3.string().nullable().optional(),pageId:z3.string().nullable().optional(),docsReadTarget:z3.string().nullable().optional(),sourceKind:z3.string().nullable().optional(),sourceUrl:z3.string().nullable().optional(),repoUrl:z3.string().nullable().optional(),gitRef:z3.string().nullable().optional(),commitSha:z3.string().nullable().optional(),requestedRef:z3.string().nullable().optional(),filePath:z3.string().nullable().optional(),repositoryFilePath:z3.string().nullable().optional(),startLine:z3.number().int().nullable().optional(),endLine:z3.number().int().nullable().optional(),evidenceRange:unifiedSearchEvidenceRangeSchema.nullable().optional(),indexedRange:unifiedSearchLineRangeSchema.nullable().optional(),symbolContext:unifiedSearchSymbolContextSchema.nullable().optional(),fileContentHash:z3.string().nullable().optional(),symbolRef:z3.string().nullable().optional(),qualifiedPath:z3.string().nullable().optional(),kind:z3.string().nullable().optional(),category:z3.string().nullable().optional(),language:z3.string().nullable().optional()});var unifiedSearchSemanticPreferredReadSchema=z3.object({targetLabel:z3.string(),registry:z3.string().nullable(),packageName:z3.string().nullable(),version:z3.string().nullable(),repoUrl:z3.string(),gitRef:z3.string(),commitSha:z3.string(),requestedRef:z3.string().nullable(),filePath:z3.string(),repositoryFilePath:z3.string(),startLine:unifiedSearchLineRangeSchema.shape.startLine,endLine:unifiedSearchLineRangeSchema.shape.endLine}).refine((range)=>range.startLine<=range.endLine,{message:"startLine must be less than or equal to endLine"});var unifiedSearchSemanticScopeSchema=z3.object({name:z3.string(),qualifiedPath:z3.string(),kind:z3.string(),parentQualifiedPath:z3.string().nullable(),declarationStartLine:z3.number().int().positive(),declarationEndLine:z3.number().int().positive(),parameterNames:z3.array(z3.string()),returnType:z3.string().nullable(),symbolRef:z3.string()}).refine((range)=>range.declarationStartLine<=range.declarationEndLine,{message:"declarationStartLine must be less than or equal to declarationEndLine"});var unifiedSearchSemanticContextSchema=z3.object({scopes:z3.array(unifiedSearchSemanticScopeSchema),scopeChainTruncated:z3.boolean(),preferredRead:unifiedSearchSemanticPreferredReadSchema});var unifiedSearchHighlightSchema=z3.tuple([z3.number().int().nonnegative(),z3.number().int().nonnegative()]).refine(([start,end])=>start<=end,{message:"highlight start must be less than or equal to end"});var unifiedSearchFocusedSourceLineSchema=z3.object({lineNumber:z3.number().int().positive(),text:z3.string(),highlights:z3.array(unifiedSearchHighlightSchema),prefixTruncated:z3.boolean(),suffixTruncated:z3.boolean()});var unifiedSearchFocusedSourceSchema=z3.object({startLine:z3.number().int().positive(),endLine:z3.number().int().positive(),matchLine:z3.number().int().positive().nullable(),rangeKind:z3.string().nullable(),matchSpansTruncated:z3.boolean(),lines:z3.array(unifiedSearchFocusedSourceLineSchema),linesOmittedBefore:z3.boolean(),linesOmittedAfter:z3.boolean()}).refine((range)=>range.startLine<=range.endLine,{message:"startLine must be less than or equal to endLine"});var unifiedSearchRepositoryEvidenceSchema=z3.object({focusedSource:unifiedSearchFocusedSourceSchema.nullable(),semanticContext:unifiedSearchSemanticContextSchema.nullable()});var contentSafetySchema=z3.object({filtered:z3.boolean(),modifications:z3.array(z3.enum(["INVISIBLE_CONTROLS_STRIPPED","HTML_COMMENTS_STRIPPED","IMAGES_REPLACED","UNSAFE_LINKS_NEUTRALIZED"]))});var unifiedSearchHitSchema=z3.object({id:z3.string(),resultType:unifiedSearchResultTypeSchema,targetLabel:z3.string(),requestedTargetLabel:z3.string().nullable().optional(),freshTargetLabel:z3.string().nullable().optional(),servedTargetLabel:z3.string().nullable().optional(),freshness:z3.string().nullable().optional(),title:z3.string().nullable().optional(),summary:z3.string().nullable().optional(),score:z3.number().nullable().optional(),highlights:z3.object({title:z3.array(z3.tuple([z3.number().int(),z3.number().int()])).nullable().optional(),summary:z3.array(z3.tuple([z3.number().int(),z3.number().int()])).nullable().optional()}).nullable().optional(),repositoryEvidence:unifiedSearchRepositoryEvidenceSchema.nullable().optional(),contentSafety:contentSafetySchema.optional(),locator:unifiedSearchLocatorSchema});var unifiedSearchPageInfoSchema=z3.object({offset:z3.number().int(),limit:z3.number().int(),returned:z3.number().int(),hasMore:z3.boolean()});var docCoverageSchema=z3.object({coverageState:z3.string(),coverageReason:z3.string().nullable().optional(),pagesCrawled:z3.number().int().nullable().optional(),frontierRemaining:z3.number().int().nullable().optional(),artifactOverflowPageCount:z3.number().int().nullable().optional(),estimatedTotalPages:z3.number().int().nullable().optional(),note:z3.string().nullable().optional()}).nullable().optional();var unifiedSearchDocumentationContributorSchema=z3.object({kind:z3.enum(["REPOSITORY_DOCS","DOCPACK"]),state:z3.enum(["SEARCHED","READY","PENDING","UNAVAILABLE"]),freshness:z3.enum(["CURRENT","PROVISIONAL","STALE"]).nullable().optional(),resultCount:z3.number().int().nonnegative(),repositoryUrl:z3.string().nullable().optional(),commitSha:z3.string().nullable().optional(),siteKey:z3.string().nullable().optional(),siteUrl:z3.string().nullable().optional(),coverage:docCoverageSchema});var unifiedSearchSourceStatusSchema=z3.object({source:unifiedSearchSourceSchema,targetLabel:z3.string(),requestedTargetLabel:z3.string().nullable().optional(),freshTargetLabel:z3.string().nullable().optional(),servedTargetLabel:z3.string().nullable().optional(),targetResolution:targetResolutionSchema,indexingStatus:z3.string().nullable().optional(),codeIndexState:z3.string().nullable().optional(),resultCount:z3.number().int().nullable().optional(),appliedFilters:z3.array(z3.string()),ignoredFilters:z3.array(z3.string()),incompatibleFilters:z3.array(z3.string()),appliedQueryFeatures:z3.array(z3.string()),ignoredQueryFeatures:z3.array(z3.string()),incompatibleQueryFeatures:z3.array(z3.string()),suggestedSiteTargets:z3.array(z3.string()),suggestedSiteTargetsTruncated:z3.boolean(),note:z3.string().nullable().optional(),coverage:docCoverageSchema,contributors:z3.array(unifiedSearchDocumentationContributorSchema)});var unifiedSearchResultSchema=z3.object({query:z3.string(),queryWarnings:z3.array(z3.string()),sources:z3.array(unifiedSearchSourceSchema),results:z3.array(unifiedSearchHitSchema),page:unifiedSearchPageInfoSchema,partialResults:z3.boolean(),sourceStatus:z3.array(unifiedSearchSourceStatusSchema),evidenceNotice:z3.string().nullable().optional()});var unifiedSearchSessionStatusSchema=z3.string().min(1);var unifiedSearchFiltersSchema=z3.object({fileIntent:z3.string().nullable().optional(),kind:z3.string().nullable().optional(),category:z3.string().nullable().optional(),publicOnly:z3.boolean().nullable().optional(),pathPrefix:z3.string().nullable().optional()}).nullable().optional();var unifiedSearchProgressTargetSchema=z3.object({requested:z3.string().nullable().optional(),resolvedRequested:z3.string().nullable().optional(),served:z3.string().nullable().optional(),freshness:z3.string().nullable().optional(),indexingRef:z3.string().nullable().optional(),requestedRefKind:z3.string().nullable().optional(),targetResolution:targetResolutionSchema,availableVersions:z3.array(availableVersionSchema).nullable().optional(),availableRefs:z3.array(availableVersionSchema).nullable().optional(),suggestedRefs:z3.array(availableVersionSchema).nullable().optional(),coverage:docCoverageSchema});var unifiedSearchRequestedTargetSchema=z3.object({registry:z3.string().nullable().optional(),name:z3.string().nullable().optional(),version:z3.string().nullable().optional(),repoUrl:z3.string().nullable().optional(),gitRef:z3.string().nullable().optional(),site:z3.string().nullable().optional()});var unifiedSearchProgressSchema=z3.object({searchRef:z3.string(),status:unifiedSearchSessionStatusSchema,targetsTotal:z3.number().int(),targetsReady:z3.number().int(),elapsedMs:z3.number().int(),query:z3.string(),queryWarnings:z3.array(z3.string()),sources:z3.array(unifiedSearchSourceSchema),requestedSources:z3.array(unifiedSearchSourceSchema).nullable().optional(),targetMode:z3.string().nullable().optional(),requestedTargets:z3.array(unifiedSearchRequestedTargetSchema).nullable().optional(),filters:unifiedSearchFiltersSchema,limit:z3.number().int().nullable().optional(),offset:z3.number().int().nullable().optional(),targets:z3.array(unifiedSearchProgressTargetSchema).nullable().optional(),expiresAt:z3.string().nullable().optional(),results:unifiedSearchResultSchema.nullable().optional()});var asyncUnifiedSearchResultSchema=z3.object({completed:z3.boolean(),searchRef:z3.string().nullable().optional(),result:unifiedSearchResultSchema.nullable().optional(),progress:unifiedSearchProgressSchema.nullable().optional()});var graphQLErrorSchema=z3.object({message:z3.string(),extensions:z3.record(z3.string(),z3.unknown()).optional()});var codeDiffGraphQLErrorSchema=z3.object({message:z3.string(),path:z3.array(z3.union([z3.string(),z3.number().int()])).nullable().optional(),extensions:z3.record(z3.string(),z3.unknown()).optional()});var codeDiffRegistrySchema=z3.enum(PKGSEER_REGISTRY_VALUES);var codeDiffPackageInfoSchema=z3.object({registry:codeDiffRegistrySchema,name:z3.string(),repoUrl:z3.string()});var codeDiffRefResolutionSchema=z3.object({requested:z3.string(),resolvedVersion:z3.string().nullable().optional(),ref:z3.string(),commitSha:z3.string(),refKind:z3.enum(["SHA","TAG","BRANCH","HEAD","UNKNOWN"]),versionSource:z3.enum(["REGISTRY","GIT_HEAD","TAG","RELEASE"]).nullable().optional()});var rawCodeDiffSummarySchema=z3.object({filesChanged:z3.number().int(),added:z3.number().int(),deleted:z3.number().int(),modified:z3.number().int(),modeChanged:z3.number().int(),typeChanged:z3.number().int(),inventoryComplete:z3.boolean(),unprojectableFiles:z3.number().int()});var rawCodeDiffScopeSchema=z3.object({status:z3.enum(["PACKAGE","REPOSITORY","UNKNOWN"]),fromSubpath:z3.string().nullable().optional(),toSubpath:z3.string().nullable().optional(),pathPrefix:z3.string().nullable().optional(),pathGlob:z3.string().nullable().optional()});var rawCodeDiffContentFailureSchema=z3.object({code:z3.string(),retryable:z3.boolean(),retryAfterMs:z3.number().int().nullable().optional(),stage:z3.string().nullable().optional(),limitKind:z3.string().nullable().optional()});var rawCodeDiffFileSchema=z3.object({path:z3.string(),pathEncoding:z3.enum(["UTF8","BYTE_ESCAPED"]),status:z3.enum(["ADDED","DELETED","MODIFIED"]),modeChanged:z3.boolean(),typeChanged:z3.boolean(),additions:z3.number().int().nullable().optional(),deletions:z3.number().int().nullable().optional(),patch:z3.string().nullable().optional(),contentStatus:z3.enum(["NOT_REQUESTED","STATS","PATCH","BINARY","METADATA_ONLY","OMITTED","UNAVAILABLE"]),contentOmissionReason:z3.string().nullable().optional(),contentSafety:contentSafetySchema});var rawCodeDiffSchema=z3.object({summary:rawCodeDiffSummarySchema,scope:rawCodeDiffScopeSchema,contentCoverage:z3.enum(["NOT_REQUESTED","COMPLETE","PARTIAL","FAILED"]),contentFailure:rawCodeDiffContentFailureSchema.nullable().optional(),files:z3.array(rawCodeDiffFileSchema),hasMoreFiles:z3.boolean()});var codeDiffResultSchema=z3.object({package:codeDiffPackageInfoSchema.nullable().optional(),fromResolution:codeDiffRefResolutionSchema,toResolution:codeDiffRefResolutionSchema,raw:rawCodeDiffSchema.nullable().optional()});var codeDiffGraphQLResponseSchema=z3.object({data:z3.object({codeDiff:codeDiffResultSchema.nullable().optional()}).nullable().optional(),errors:z3.array(codeDiffGraphQLErrorSchema).optional()});var CODE_DIFF_OPTION_KEYS=new Set(["maxFiles","maxPatchBytes","pathPrefix","pathGlob"]);var CODE_DIFF_COMMON_SELECTION=` package {
429
+ }`;function debugUnifiedSearchRequest(variables,diagnostics){if(!diagnostics?.isEnabled("code-nav"))return;const serialised=serialiseForDebug(variables);const filters=asRecord(serialised.filters);diagnostics.debug("code-nav",{event:"request",operation:"search",targetCount:Array.isArray(serialised.targets)?serialised.targets.length:0,sources:Array.isArray(serialised.sources)?serialised.sources:[],hasFilters:filters!==undefined,filterKeys:filters?Object.keys(filters).sort():[],fileIntent:filters&&typeof filters.fileIntent==="string"?filters.fileIntent:"omitted",allowPartialResults:serialised.allowPartialResults===true,presentVariableKeys:Object.keys(serialised).sort(),hasLimit:typeof serialised.limit==="number",hasOffset:typeof serialised.offset==="number",waitTimeoutMs:typeof serialised.waitTimeoutMs==="number"?serialised.waitTimeoutMs:undefined})}function debugGraphqlWireRequest(operation,graphqlQuery,variables,diagnostics){if(!diagnostics?.isEnabled("code-nav-wire"))return;diagnostics.debug("code-nav-wire",{event:"wire-request",operation,graphqlQuery,variables:serialiseForDebug(variables)})}function serialiseForDebug(value){try{const text=JSON.stringify(value);if(!text)return{};const parsed=JSON.parse(text);return asRecord(parsed)??{}}catch{return{}}}function asRecord(value){if(value&&typeof value==="object"&&!Array.isArray(value)){return value}return}var availableVersionSchema=z3.object({version:z3.string().nullable().optional(),ref:z3.string()});var indexingDurationEstimateSchema=z3.object({lowerSeconds:z3.number().int().nullable().optional(),upperSeconds:z3.number().int().nullable().optional(),elapsedSeconds:z3.number().int().nullable().optional(),sampleCount:z3.number().int().nullable().optional(),source:z3.string().nullable().optional()}).nullable().optional();var targetResolutionIdentitySchema=z3.object({kind:z3.string().nullable().optional(),registry:z3.string().nullable().optional(),packageName:z3.string().nullable().optional(),version:z3.string().nullable().optional(),repoUrl:z3.string().nullable().optional(),gitRef:z3.string().nullable().optional(),commitSha:z3.string().nullable().optional(),site:z3.string().nullable().optional()}).nullable().optional();var targetResolutionSchema=z3.object({requested:targetResolutionIdentitySchema,resolvedRequested:targetResolutionIdentitySchema,served:targetResolutionIdentitySchema,freshness:z3.string().nullable().optional(),freshnessReason:z3.string().nullable().optional(),indexingRef:z3.string().nullable().optional(),availableVersions:z3.array(availableVersionSchema).nullable().optional(),availableRefs:z3.array(availableVersionSchema).nullable().optional(),suggestedRefs:z3.array(availableVersionSchema).nullable().optional()}).nullable().optional();var unifiedSearchSourceSchema=z3.enum(["AUTO","DOCS","CODE","SYMBOL"]);var unifiedSearchResultTypeSchema=z3.enum(["DOCUMENTATION_PAGE","REPOSITORY_SYMBOL","REPOSITORY_CODE","REPOSITORY_DOC"]);var unifiedSearchLineRangeSchema=z3.object({startLine:z3.number().int().positive(),endLine:z3.number().int().positive()}).refine((range)=>range.startLine<=range.endLine,{message:"startLine must be less than or equal to endLine"});var unifiedSearchEvidenceRangeSchema=unifiedSearchLineRangeSchema.extend({matchLine:z3.number().int().positive().nullable().optional(),rangeKind:z3.string().nullable().optional(),matchSpansTruncated:z3.boolean()});var unifiedSearchDefinitionRangeSchema=unifiedSearchLineRangeSchema.extend({filePath:z3.string(),repositoryFilePath:z3.string()});var unifiedSearchSymbolContextBaseSchema=z3.object({name:z3.string(),qualifiedPath:z3.string().nullable().optional(),kind:z3.string().nullable().optional()});var unifiedSearchSymbolContextSchema=z3.discriminatedUnion("relation",[unifiedSearchSymbolContextBaseSchema.extend({relation:z3.literal("ENCLOSES_MATCH"),definitionRange:unifiedSearchDefinitionRangeSchema}),unifiedSearchSymbolContextBaseSchema.extend({relation:z3.literal("ASSOCIATED_WITH_INDEXED_CHUNK"),definitionRange:unifiedSearchDefinitionRangeSchema.nullable().optional()})]);var unifiedSearchLocatorSchema=z3.object({registry:z3.string().nullable().optional(),packageName:z3.string().nullable().optional(),version:z3.string().nullable().optional(),pageId:z3.string().nullable().optional(),docsReadTarget:z3.string().nullable().optional(),sourceKind:z3.string().nullable().optional(),sourceUrl:z3.string().nullable().optional(),repoUrl:z3.string().nullable().optional(),gitRef:z3.string().nullable().optional(),commitSha:z3.string().nullable().optional(),requestedRef:z3.string().nullable().optional(),filePath:z3.string().nullable().optional(),repositoryFilePath:z3.string().nullable().optional(),startLine:z3.number().int().nullable().optional(),endLine:z3.number().int().nullable().optional(),evidenceRange:unifiedSearchEvidenceRangeSchema.nullable().optional(),indexedRange:unifiedSearchLineRangeSchema.nullable().optional(),symbolContext:unifiedSearchSymbolContextSchema.nullable().optional(),fileContentHash:z3.string().nullable().optional(),symbolRef:z3.string().nullable().optional(),qualifiedPath:z3.string().nullable().optional(),kind:z3.string().nullable().optional(),category:z3.string().nullable().optional(),language:z3.string().nullable().optional()});var unifiedSearchSemanticPreferredReadSchema=z3.object({targetLabel:z3.string(),registry:z3.string().nullable(),packageName:z3.string().nullable(),version:z3.string().nullable(),repoUrl:z3.string(),gitRef:z3.string(),commitSha:z3.string(),requestedRef:z3.string().nullable(),filePath:z3.string(),repositoryFilePath:z3.string(),startLine:unifiedSearchLineRangeSchema.shape.startLine,endLine:unifiedSearchLineRangeSchema.shape.endLine}).refine((range)=>range.startLine<=range.endLine,{message:"startLine must be less than or equal to endLine"});var unifiedSearchSemanticScopeSchema=z3.object({name:z3.string(),qualifiedPath:z3.string(),kind:z3.string(),parentQualifiedPath:z3.string().nullable(),declarationStartLine:z3.number().int().positive(),declarationEndLine:z3.number().int().positive(),parameterNames:z3.array(z3.string()),returnType:z3.string().nullable(),symbolRef:z3.string()}).refine((range)=>range.declarationStartLine<=range.declarationEndLine,{message:"declarationStartLine must be less than or equal to declarationEndLine"});var unifiedSearchSemanticContextSchema=z3.object({scopes:z3.array(unifiedSearchSemanticScopeSchema),scopeChainTruncated:z3.boolean(),preferredRead:unifiedSearchSemanticPreferredReadSchema});var unifiedSearchHighlightSchema=z3.tuple([z3.number().int().nonnegative(),z3.number().int().nonnegative()]).refine(([start,end])=>start<=end,{message:"highlight start must be less than or equal to end"});var unifiedSearchFocusedSourceLineSchema=z3.object({lineNumber:z3.number().int().positive(),text:z3.string(),highlights:z3.array(unifiedSearchHighlightSchema),prefixTruncated:z3.boolean(),suffixTruncated:z3.boolean()});var unifiedSearchFocusedSourceSchema=z3.object({startLine:z3.number().int().positive(),endLine:z3.number().int().positive(),matchLine:z3.number().int().positive().nullable(),rangeKind:z3.string().nullable(),matchSpansTruncated:z3.boolean(),lines:z3.array(unifiedSearchFocusedSourceLineSchema),linesOmittedBefore:z3.boolean(),linesOmittedAfter:z3.boolean()}).refine((range)=>range.startLine<=range.endLine,{message:"startLine must be less than or equal to endLine"});var unifiedSearchBm25MatchFieldSchema=z3.enum(["SYMBOL_NAME","FILE_PATH","DOCUMENTATION","SOURCE_IDENTIFIER"]);var unifiedSearchMatchedSourceSchema=unifiedSearchLineRangeSchema.extend({matchLine:z3.number().int().positive().nullable(),rangeKind:z3.string(),matchSpansTruncated:z3.boolean(),lines:z3.array(unifiedSearchFocusedSourceLineSchema),linesOmittedBefore:z3.boolean(),linesOmittedAfter:z3.boolean()});var unifiedSearchDocumentationPreviewSchema=z3.object({text:z3.string().min(1),highlights:z3.array(unifiedSearchHighlightSchema)});var unifiedSearchRepositoryEvidenceSchema=z3.object({focusedSource:unifiedSearchFocusedSourceSchema.nullable().optional(),semanticContext:unifiedSearchSemanticContextSchema.nullable(),bm25MatchFields:z3.array(unifiedSearchBm25MatchFieldSchema).min(1).nullable().optional(),matchedSource:unifiedSearchMatchedSourceSchema.nullable().optional()});var contentSafetySchema=z3.object({filtered:z3.boolean(),modifications:z3.array(z3.enum(["INVISIBLE_CONTROLS_STRIPPED","HTML_COMMENTS_STRIPPED","IMAGES_REPLACED","UNSAFE_LINKS_NEUTRALIZED"]))});var unifiedSearchHitSchema=z3.object({id:z3.string(),resultType:unifiedSearchResultTypeSchema,targetLabel:z3.string(),requestedTargetLabel:z3.string().nullable().optional(),freshTargetLabel:z3.string().nullable().optional(),servedTargetLabel:z3.string().nullable().optional(),freshness:z3.string().nullable().optional(),title:z3.string().nullable().optional(),summary:z3.string().nullable().optional(),score:z3.number().nullable().optional(),highlights:z3.object({title:z3.array(z3.tuple([z3.number().int(),z3.number().int()])).nullable().optional(),summary:z3.array(z3.tuple([z3.number().int(),z3.number().int()])).nullable().optional()}).nullable().optional(),repositoryEvidence:unifiedSearchRepositoryEvidenceSchema.nullable().optional(),documentationPreview:unifiedSearchDocumentationPreviewSchema.nullable().optional(),contentSafety:contentSafetySchema.optional(),locator:unifiedSearchLocatorSchema});var unifiedSearchPageInfoSchema=z3.object({offset:z3.number().int(),limit:z3.number().int(),returned:z3.number().int(),hasMore:z3.boolean()});var docCoverageSchema=z3.object({coverageState:z3.string(),coverageReason:z3.string().nullable().optional(),pagesCrawled:z3.number().int().nullable().optional(),frontierRemaining:z3.number().int().nullable().optional(),artifactOverflowPageCount:z3.number().int().nullable().optional(),estimatedTotalPages:z3.number().int().nullable().optional(),note:z3.string().nullable().optional()}).nullable().optional();var unifiedSearchDocumentationContributorSchema=z3.object({kind:z3.enum(["REPOSITORY_DOCS","DOCPACK"]),state:z3.enum(["SEARCHED","READY","PENDING","UNAVAILABLE"]),freshness:z3.enum(["CURRENT","PROVISIONAL","STALE"]).nullable().optional(),resultCount:z3.number().int().nonnegative(),repositoryUrl:z3.string().nullable().optional(),commitSha:z3.string().nullable().optional(),siteKey:z3.string().nullable().optional(),siteUrl:z3.string().nullable().optional(),coverage:docCoverageSchema});var unifiedSearchSourceStatusSchema=z3.object({source:unifiedSearchSourceSchema,targetLabel:z3.string(),requestedTargetLabel:z3.string().nullable().optional(),freshTargetLabel:z3.string().nullable().optional(),servedTargetLabel:z3.string().nullable().optional(),targetResolution:targetResolutionSchema,indexingStatus:z3.string().nullable().optional(),codeIndexState:z3.string().nullable().optional(),resultCount:z3.number().int().nullable().optional(),appliedFilters:z3.array(z3.string()),ignoredFilters:z3.array(z3.string()),incompatibleFilters:z3.array(z3.string()),appliedQueryFeatures:z3.array(z3.string()),ignoredQueryFeatures:z3.array(z3.string()),incompatibleQueryFeatures:z3.array(z3.string()),suggestedSiteTargets:z3.array(z3.string()),suggestedSiteTargetsTruncated:z3.boolean(),note:z3.string().nullable().optional(),coverage:docCoverageSchema,contributors:z3.array(unifiedSearchDocumentationContributorSchema)});var unifiedSearchResultSchema=z3.object({query:z3.string(),queryWarnings:z3.array(z3.string()),sources:z3.array(unifiedSearchSourceSchema),results:z3.array(unifiedSearchHitSchema),page:unifiedSearchPageInfoSchema,partialResults:z3.boolean(),sourceStatus:z3.array(unifiedSearchSourceStatusSchema),evidenceNotice:z3.string().nullable().optional()});var unifiedSearchSessionStatusSchema=z3.string().min(1);var unifiedSearchFiltersSchema=z3.object({fileIntent:z3.string().nullable().optional(),kind:z3.string().nullable().optional(),category:z3.string().nullable().optional(),publicOnly:z3.boolean().nullable().optional(),pathPrefix:z3.string().nullable().optional()}).nullable().optional();var unifiedSearchProgressTargetSchema=z3.object({requested:z3.string().nullable().optional(),resolvedRequested:z3.string().nullable().optional(),served:z3.string().nullable().optional(),freshness:z3.string().nullable().optional(),indexingRef:z3.string().nullable().optional(),requestedRefKind:z3.string().nullable().optional(),targetResolution:targetResolutionSchema,availableVersions:z3.array(availableVersionSchema).nullable().optional(),availableRefs:z3.array(availableVersionSchema).nullable().optional(),suggestedRefs:z3.array(availableVersionSchema).nullable().optional(),coverage:docCoverageSchema});var unifiedSearchRequestedTargetSchema=z3.object({registry:z3.string().nullable().optional(),name:z3.string().nullable().optional(),version:z3.string().nullable().optional(),repoUrl:z3.string().nullable().optional(),gitRef:z3.string().nullable().optional(),site:z3.string().nullable().optional()});var unifiedSearchProgressSchema=z3.object({searchRef:z3.string(),status:unifiedSearchSessionStatusSchema,targetsTotal:z3.number().int(),targetsReady:z3.number().int(),elapsedMs:z3.number().int(),query:z3.string(),queryWarnings:z3.array(z3.string()),sources:z3.array(unifiedSearchSourceSchema),requestedSources:z3.array(unifiedSearchSourceSchema).nullable().optional(),targetMode:z3.string().nullable().optional(),requestedTargets:z3.array(unifiedSearchRequestedTargetSchema).nullable().optional(),filters:unifiedSearchFiltersSchema,limit:z3.number().int().nullable().optional(),offset:z3.number().int().nullable().optional(),targets:z3.array(unifiedSearchProgressTargetSchema).nullable().optional(),expiresAt:z3.string().nullable().optional(),results:unifiedSearchResultSchema.nullable().optional()});var asyncUnifiedSearchResultSchema=z3.object({completed:z3.boolean(),searchRef:z3.string().nullable().optional(),result:unifiedSearchResultSchema.nullable().optional(),progress:unifiedSearchProgressSchema.nullable().optional()});var graphQLErrorSchema=z3.object({message:z3.string(),extensions:z3.record(z3.string(),z3.unknown()).optional()});var codeDiffGraphQLErrorSchema=z3.object({message:z3.string(),path:z3.array(z3.union([z3.string(),z3.number().int()])).nullable().optional(),extensions:z3.record(z3.string(),z3.unknown()).optional()});var codeDiffRegistrySchema=z3.enum(PKGSEER_REGISTRY_VALUES);var codeDiffPackageInfoSchema=z3.object({registry:codeDiffRegistrySchema,name:z3.string(),repoUrl:z3.string()});var codeDiffRefResolutionSchema=z3.object({requested:z3.string(),resolvedVersion:z3.string().nullable().optional(),ref:z3.string(),commitSha:z3.string(),refKind:z3.enum(["SHA","TAG","BRANCH","HEAD","UNKNOWN"]),versionSource:z3.enum(["REGISTRY","GIT_HEAD","TAG","RELEASE"]).nullable().optional()});var rawCodeDiffSummarySchema=z3.object({filesChanged:z3.number().int(),added:z3.number().int(),deleted:z3.number().int(),modified:z3.number().int(),modeChanged:z3.number().int(),typeChanged:z3.number().int(),inventoryComplete:z3.boolean(),unprojectableFiles:z3.number().int()});var rawCodeDiffScopeSchema=z3.object({status:z3.enum(["PACKAGE","REPOSITORY","UNKNOWN"]),fromSubpath:z3.string().nullable().optional(),toSubpath:z3.string().nullable().optional(),pathPrefix:z3.string().nullable().optional(),pathGlob:z3.string().nullable().optional()});var rawCodeDiffContentFailureSchema=z3.object({code:z3.string(),retryable:z3.boolean(),retryAfterMs:z3.number().int().nullable().optional(),stage:z3.string().nullable().optional(),limitKind:z3.string().nullable().optional()});var rawCodeDiffFileSchema=z3.object({path:z3.string(),pathEncoding:z3.enum(["UTF8","BYTE_ESCAPED"]),status:z3.enum(["ADDED","DELETED","MODIFIED"]),modeChanged:z3.boolean(),typeChanged:z3.boolean(),additions:z3.number().int().nullable().optional(),deletions:z3.number().int().nullable().optional(),patch:z3.string().nullable().optional(),contentStatus:z3.enum(["NOT_REQUESTED","STATS","PATCH","BINARY","METADATA_ONLY","OMITTED","UNAVAILABLE"]),contentOmissionReason:z3.string().nullable().optional(),contentSafety:contentSafetySchema});var rawCodeDiffSchema=z3.object({summary:rawCodeDiffSummarySchema,scope:rawCodeDiffScopeSchema,contentCoverage:z3.enum(["NOT_REQUESTED","COMPLETE","PARTIAL","FAILED"]),contentFailure:rawCodeDiffContentFailureSchema.nullable().optional(),files:z3.array(rawCodeDiffFileSchema),hasMoreFiles:z3.boolean()});var codeDiffResultSchema=z3.object({package:codeDiffPackageInfoSchema.nullable().optional(),fromResolution:codeDiffRefResolutionSchema,toResolution:codeDiffRefResolutionSchema,raw:rawCodeDiffSchema.nullable().optional()});var codeDiffGraphQLResponseSchema=z3.object({data:z3.object({codeDiff:codeDiffResultSchema.nullable().optional()}).nullable().optional(),errors:z3.array(codeDiffGraphQLErrorSchema).optional()});var CODE_DIFF_OPTION_KEYS=new Set(["maxFiles","maxPatchBytes","pathPrefix","pathGlob"]);var CODE_DIFF_COMMON_SELECTION=` package {
404
430
  registry
405
431
  name
406
432
  repoUrl
@@ -683,7 +709,7 @@ query GrepRepo(
683
709
  }
684
710
  ${INDEXING_DURATION_ESTIMATE_SELECTION}
685
711
  }
686
- }`}var unifiedSearchGraphQLResponseSchema=z3.object({data:z3.object({search:asyncUnifiedSearchResultSchema.nullable().optional()}).nullable().optional(),errors:z3.array(graphQLErrorSchema).optional()});var unifiedSearchStatusGraphQLResponseSchema=z3.object({data:z3.object({discoverySearchProgress:unifiedSearchProgressSchema.nullable().optional()}).nullable().optional(),errors:z3.array(graphQLErrorSchema).optional()});class 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,extensions})=>({message,extensions}));const message=errors.map((error)=>error.message).join(", ");const extensions=getPrimaryExtensions(errors);const code=typeof extensions?.code==="string"?extensions.code:undefined;if(code==="AUTHENTICATION_REQUIRED"){return new 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,repositoryEvidence:entry.repositoryEvidence,contentSafety:entry.contentSafety,locator:normaliseUnifiedSearchLocator(entry.locator)})),page:{offset:result.page.offset,limit:result.page.limit,returned:result.page.returned,hasMore:result.page.hasMore},partialResults:result.partialResults,sourceStatus:result.sourceStatus.map((entry)=>({source:entry.source,targetLabel:entry.targetLabel,requestedTargetLabel:entry.requestedTargetLabel??undefined,freshTargetLabel:entry.freshTargetLabel??undefined,servedTargetLabel:entry.servedTargetLabel??undefined,targetResolution:normaliseTargetResolution(entry.targetResolution),indexingStatus:entry.indexingStatus??undefined,codeIndexState:entry.codeIndexState??undefined,resultCount:entry.resultCount??undefined,appliedFilters:entry.appliedFilters,ignoredFilters:entry.ignoredFilters,incompatibleFilters:entry.incompatibleFilters,appliedQueryFeatures:entry.appliedQueryFeatures,ignoredQueryFeatures:entry.ignoredQueryFeatures,incompatibleQueryFeatures:entry.incompatibleQueryFeatures,suggestedSiteTargets:entry.suggestedSiteTargets,suggestedSiteTargetsTruncated:entry.suggestedSiteTargetsTruncated,note:entry.note??undefined,coverage:normaliseDocCoverage(entry.coverage),contributors:entry.contributors.map((contributor)=>({kind:contributor.kind,state:contributor.state,freshness:contributor.freshness??undefined,resultCount:contributor.resultCount,repositoryUrl:contributor.repositoryUrl??undefined,commitSha:contributor.commitSha??undefined,siteKey:contributor.siteKey??undefined,siteUrl:contributor.siteUrl??undefined,coverage:normaliseDocCoverage(contributor.coverage,{preserveNone:true})}))})),evidenceNotice:result.evidenceNotice??undefined}}normaliseUnifiedSearchProgress(progress){return{searchRef:progress.searchRef,status:progress.status,targetsTotal:progress.targetsTotal,targetsReady:progress.targetsReady,elapsedMs:progress.elapsedMs,query:progress.query,queryWarnings:progress.queryWarnings,sources:progress.sources,requestedSources:progress.requestedSources??undefined,targetMode:normaliseTargetMode(progress.targetMode),requestedTargets:progress.requestedTargets?.map((target)=>({registry:target.registry?target.registry:undefined,name:target.name??undefined,version:target.version??undefined,repoUrl:target.repoUrl??undefined,gitRef:target.gitRef??undefined,site:target.site??undefined})),filters:normaliseProgressFilters(progress.filters),limit:progress.limit??undefined,offset:progress.offset??undefined,targets:progress.targets?.map((target)=>({requested:target.requested??undefined,resolvedRequested:target.resolvedRequested??undefined,served:target.served??undefined,freshness:target.freshness??undefined,indexingRef:target.indexingRef??undefined,requestedRefKind:normaliseRequestedRefKind(target.requestedRefKind),targetResolution:normaliseTargetResolution(target.targetResolution),availableVersions:normaliseAvailableVersions(target.availableVersions),availableRefs:normaliseAvailableVersions(target.availableRefs),suggestedRefs:normaliseAvailableVersions(target.suggestedRefs),coverage:normaliseDocCoverage(target.coverage)})),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,contentHash:entry.symbol.contentHash??undefined,parentPath:entry.symbol.parentPath??undefined}:undefined})),nextCursor:data.nextCursor??undefined,hasMore:data.hasMore,truncatedReason:data.truncatedReason,routeTaken:data.routeTaken??undefined,filesScanned:data.filesScanned,filesInScope:data.filesInScope,binaryFilesSkipped:data.binaryFilesSkipped,filesTooLargeSkipped:data.filesTooLargeSkipped,totalMatches:data.totalMatches,uniqueFilesMatched:data.uniqueFilesMatched,indexedVersion:data.indexedVersion??undefined,resolution:data.resolution?{requestedVersion:data.resolution.requestedVersion??undefined,requestedRef:data.resolution.requestedRef??undefined,resolvedRef:data.resolution.resolvedRef??undefined,commitSha:data.resolution.commitSha??undefined}:undefined,targetResolution:normaliseTargetResolution(data.targetResolution)}}}function normaliseUnifiedSearchLocator(value){return{registry:value.registry??undefined,packageName:value.packageName??undefined,version:value.version??undefined,pageId:value.pageId??undefined,docsReadTarget:value.docsReadTarget??undefined,sourceKind:value.sourceKind??undefined,sourceUrl:value.sourceUrl??undefined,repoUrl:value.repoUrl??undefined,gitRef:value.gitRef??undefined,commitSha:value.commitSha??undefined,requestedRef:value.requestedRef??undefined,filePath:value.filePath??undefined,repositoryFilePath:value.repositoryFilePath??undefined,startLine:value.startLine??undefined,endLine:value.endLine??undefined,evidenceRange:value.evidenceRange?{startLine:value.evidenceRange.startLine,endLine:value.evidenceRange.endLine,matchLine:value.evidenceRange.matchLine??undefined,rangeKind:value.evidenceRange.rangeKind??undefined,matchSpansTruncated:value.evidenceRange.matchSpansTruncated}:undefined,indexedRange:value.indexedRange?{startLine:value.indexedRange.startLine,endLine:value.indexedRange.endLine}:undefined,symbolContext:value.symbolContext?normaliseUnifiedSearchSymbolContext(value.symbolContext):undefined,fileContentHash:value.fileContentHash??undefined,symbolRef:value.symbolRef??undefined,qualifiedPath:value.qualifiedPath??undefined,kind:value.kind??undefined,category:value.category??undefined,language:value.language??undefined}}function normaliseUnifiedSearchSymbolContext(value){const identity={name:value.name,qualifiedPath:value.qualifiedPath??undefined,kind:value.kind??undefined};if(value.relation==="ENCLOSES_MATCH"){return{...identity,relation:"encloses_match",definitionRange:normaliseUnifiedSearchDefinitionRange(value.definitionRange)}}return{...identity,relation:"associated_with_indexed_chunk",definitionRange:value.definitionRange?normaliseUnifiedSearchDefinitionRange(value.definitionRange):undefined}}function normaliseUnifiedSearchDefinitionRange(value){return{filePath:value.filePath,repositoryFilePath:value.repositoryFilePath,startLine:value.startLine,endLine:value.endLine}}function validateCodeDiffParams(params){const paramsRecord=asRecord(params);if(!paramsRecord){throw new CodeNavigationValidationError("CodeDiff params must be an object.")}if(paramsRecord.mode!=="inventory"&&paramsRecord.mode!=="stats"&&paramsRecord.mode!=="patches"){throw new CodeNavigationValidationError("CodeDiff mode must be inventory, stats, or patches.")}if(typeof paramsRecord.from!=="string"||paramsRecord.from.length===0){throw new CodeNavigationValidationError("CodeDiff from ref or version must not be empty.")}if(typeof paramsRecord.to!=="string"||paramsRecord.to.length===0){throw new CodeNavigationValidationError("CodeDiff to ref or version must not be empty.")}const target=asRecord(paramsRecord.target);if(!target){throw new CodeNavigationValidationError("CodeDiff target must be a package or repository target.")}if(Object.hasOwn(target,"registry")&&Object.hasOwn(target,"packageName")&&!Object.hasOwn(target,"repoUrl")){if(!codeDiffRegistrySchema.safeParse(target.registry).success){throw new CodeNavigationValidationError("CodeDiff package target has an unsupported registry.")}if(typeof target.packageName!=="string"||target.packageName.length===0){throw new CodeNavigationValidationError("CodeDiff package target name must not be empty.")}}else if(Object.hasOwn(target,"repoUrl")&&!Object.hasOwn(target,"registry")&&!Object.hasOwn(target,"packageName")){if(typeof target.repoUrl!=="string"||target.repoUrl.length===0){throw new CodeNavigationValidationError("CodeDiff repository target URL must not be empty.")}}else if((Object.hasOwn(target,"registry")||Object.hasOwn(target,"packageName"))&&Object.hasOwn(target,"repoUrl")){const conflictingKeys=["registry","packageName","repoUrl"].filter((key)=>Object.hasOwn(target,key)).join(", ");throw new CodeNavigationValidationError(`CodeDiff target has conflicting present keys: ${conflictingKeys}. Target shape is determined by key presence, even when a value is undefined.`)}else{throw new CodeNavigationValidationError("CodeDiff target must be a package or repository target.")}const optionsValue=paramsRecord.options;if(optionsValue===undefined)return;const options=asRecord(optionsValue);if(!options){throw new CodeNavigationValidationError("CodeDiff options must be an object when supplied.")}for(const key of Object.keys(options)){if(!CODE_DIFF_OPTION_KEYS.has(key)){throw new CodeNavigationValidationError(`CodeDiff options contains unknown key '${key}'.`)}}validateCodeDiffIntegerOption(options.maxFiles,"maxFiles",1,300);validateCodeDiffIntegerOption(options.maxPatchBytes,"maxPatchBytes",1024,2097152);validateCodeDiffPathOption(options.pathPrefix,"pathPrefix");validateCodeDiffPathOption(options.pathGlob,"pathGlob")}function validateCodeDiffIntegerOption(value,name,minimum,maximum){if(value===undefined)return;if(typeof value!=="number"||!Number.isInteger(value)||value<minimum||value>maximum){throw new CodeNavigationValidationError(`CodeDiff ${name} must be an integer from ${minimum} through ${maximum}.`)}}function validateCodeDiffPathOption(value,name){if(value===undefined)return;if(typeof value!=="string"){throw new CodeNavigationValidationError(`CodeDiff ${name} must be a string when supplied.`)}if(value.length===0){throw new CodeNavigationValidationError(`CodeDiff ${name} must not be empty when supplied.`)}if(new TextEncoder().encode(value).byteLength>1024){throw new CodeNavigationValidationError(`CodeDiff ${name} must be at most 1024 bytes.`)}}function buildCodeDiffVariables(params){const target=params.target;const variables={};if("registry"in target){variables.registry=target.registry;variables.name=target.packageName;variables.fromVersion=params.from;variables.toVersion=params.to}else{variables.repoUrl=target.repoUrl;variables.fromRef=params.from;variables.toRef=params.to}const rawOptions=Object.fromEntries(Object.entries(params.options??{}).filter(([,value])=>value!==undefined));if(Object.keys(rawOptions).length>0)variables.rawOptions=rawOptions;return variables}function isCodeDiffRawError(error){return error.path?.some((part)=>part==="raw")??false}function normaliseCodeDiffResult(result){if(!result.raw){throw new MalformedCodeNavigationResponseError("CodeDiff response missing non-null raw result.")}return{package:normaliseCodeDiffPackage(result.package),fromResolution:normaliseCodeDiffResolution(result.fromResolution),toResolution:normaliseCodeDiffResolution(result.toResolution),raw:normaliseRawCodeDiff(result.raw)}}function normaliseCodeDiffPartial(result){return{package:normaliseCodeDiffPackage(result.package),fromResolution:normaliseCodeDiffResolution(result.fromResolution),toResolution:normaliseCodeDiffResolution(result.toResolution),raw:result.raw?normaliseRawCodeDiff(result.raw):undefined}}function normaliseCodeDiffPackage(value){if(!value)return;return{registry:value.registry,name:value.name,repoUrl:value.repoUrl}}function normaliseCodeDiffResolution(value){return{requested:value.requested,resolvedVersion:value.resolvedVersion??undefined,ref:value.ref,commitSha:value.commitSha,refKind:value.refKind,versionSource:value.versionSource??undefined}}function normaliseRawCodeDiff(value){return{summary:value.summary,scope:{status:value.scope.status,fromSubpath:value.scope.fromSubpath??undefined,toSubpath:value.scope.toSubpath??undefined,pathPrefix:value.scope.pathPrefix??undefined,pathGlob:value.scope.pathGlob??undefined},contentCoverage:value.contentCoverage,contentFailure:value.contentFailure?{code:value.contentFailure.code,retryable:value.contentFailure.retryable,retryAfterMs:value.contentFailure.retryAfterMs??undefined,stage:value.contentFailure.stage??undefined,limitKind:value.contentFailure.limitKind??undefined}:undefined,files:value.files.map((file)=>({path:file.path,pathEncoding:file.pathEncoding,status:file.status,modeChanged:file.modeChanged,typeChanged:file.typeChanged,additions:file.additions??undefined,deletions:file.deletions??undefined,patch:file.patch??undefined,contentStatus:file.contentStatus,contentOmissionReason:file.contentOmissionReason??undefined,contentSafety:{filtered:file.contentSafety.filtered,modifications:file.contentSafety.modifications}})),hasMoreFiles:value.hasMoreFiles}}function parseCodeDiffErrorDetails(errors){const extensions=getPrimaryExtensions(errors);if(!extensions)return;const details={};if(typeof extensions.code==="string")details.code=extensions.code;if(typeof extensions.retryable==="boolean"){details.retryable=extensions.retryable}if(extensions.side==="from"||extensions.side==="to"){details.side=extensions.side}const publishedVersions=parseCodeDiffStringArray(extensions.published_versions);if(publishedVersions)details.publishedVersions=publishedVersions;if(typeof extensions.published_versions_truncated==="boolean"){details.publishedVersionsTruncated=extensions.published_versions_truncated}const availableVersions=parseCodeDiffErrorRefs(extensions.available_versions);if(availableVersions)details.availableVersions=availableVersions;if(typeof extensions.registry==="string"){details.registry=extensions.registry}if(typeof extensions.retry_after_ms==="number"&&Number.isInteger(extensions.retry_after_ms)&&extensions.retry_after_ms>=0){details.retryAfterMs=extensions.retry_after_ms}if(typeof extensions.stage==="string")details.stage=extensions.stage;if(typeof extensions.limit_kind==="string"){details.limitKind=extensions.limit_kind}if(typeof extensions.repo_url==="string"){details.repoUrl=extensions.repo_url}if(typeof extensions.git_ref==="string")details.gitRef=extensions.git_ref;const availableRefs=parseCodeDiffErrorRefs(extensions.available_refs);if(availableRefs)details.availableRefs=availableRefs;const suggestedRefs=parseCodeDiffErrorRefs(extensions.suggested_refs);if(suggestedRefs)details.suggestedRefs=suggestedRefs;const refKinds=parseCodeDiffStringArray(extensions.ref_kinds);if(refKinds)details.refKinds=refKinds;return Object.keys(details).length>0?details:undefined}function parseCodeDiffStringArray(value){if(!Array.isArray(value))return;if(value.some((entry)=>typeof entry!=="string"))return;return value}function parseCodeDiffErrorRefs(value){if(!Array.isArray(value))return;const refs=[];for(const entry of value){if(!entry||typeof entry!=="object"||Array.isArray(entry)){return}const record=entry;if(typeof record.ref!=="string"||record.version!==undefined&&record.version!==null&&typeof record.version!=="string"){return}refs.push({ref:record.ref,version:typeof record.version==="string"?record.version:undefined})}return refs}function 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 z4}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=z4.object({stargazersCount:z4.number().int().nullable().optional(),forksCount:z4.number().int().nullable().optional(),openIssuesCount:z4.number().int().nullable().optional(),archived:z4.boolean().nullable().optional(),language:z4.string().nullable().optional(),topics:z4.array(z4.string()).nullable().optional(),pushedAt:z4.string().nullable().optional()}).nullable().optional();var packageIdentitySchema=z4.object({name:z4.string().nullable().optional(),registry:z4.string().nullable().optional(),description:z4.string().nullable().optional(),latestVersion:z4.string().nullable().optional(),latestVersionPublishedAt:z4.string().nullable().optional(),versionCount:z4.number().int().nullable().optional(),downloadsRefreshedAt:z4.string().nullable().optional(),homepage:z4.string().nullable().optional(),repositoryUrl:z4.string().nullable().optional(),license:z4.string().nullable().optional(),downloadsLastMonth:z4.number().int().nullable().optional(),downloadsTotal:z4.number().int().nullable().optional(),githubRepository:githubRepositorySchema});var vulnerabilityOverviewSchema=z4.object({osvId:z4.string().nullable().optional(),summary:z4.string().nullable().optional(),severityScore:z4.number().nullable().optional(),publishedAt:z4.string().nullable().optional()});var packageSecurityOverviewSchema=z4.object({vulnerabilityCount:z4.number().int().nullable().optional(),allVulnerabilityCount:z4.number().int(),hasCurrentVulnerabilities:z4.boolean().nullable().optional(),recentVulnerabilities:z4.array(vulnerabilityOverviewSchema).nullable().optional()}).nullable().optional();var changelogEntrySchema=z4.object({version:z4.string().nullable().optional(),publishedAt:z4.string().nullable().optional(),body:z4.string().nullable().optional()});var packageSummaryResponseSchema=z4.object({package:packageIdentitySchema.nullable().optional(),security:packageSecurityOverviewSchema,latestChangelogs:z4.array(changelogEntrySchema).nullable().optional()});var graphQLErrorSchema2=z4.object({message:z4.string(),extensions:z4.record(z4.string(),z4.unknown()).optional()});var graphQLResponseSchema=z4.object({data:z4.object({packageSummary:packageSummaryResponseSchema.nullable().optional()}).nullable().optional(),errors:z4.array(graphQLErrorSchema2).optional()});var PACKAGE_SUMMARY_QUERY=`
712
+ }`}var unifiedSearchGraphQLResponseSchema=z3.object({data:z3.object({search:asyncUnifiedSearchResultSchema.nullable().optional()}).nullable().optional(),errors:z3.array(graphQLErrorSchema).optional()});var unifiedSearchStatusGraphQLResponseSchema=z3.object({data:z3.object({discoverySearchProgress:unifiedSearchProgressSchema.nullable().optional()}).nullable().optional(),errors:z3.array(graphQLErrorSchema).optional()});class 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,options){return executeWithTokenRefresh({getToken:()=>this.tokenProvider.getToken(),forceRefresh:()=>this.tokenProvider.forceRefresh(),shouldRefresh:isTokenRefreshableError,executeWithToken:(token)=>this.executeUnifiedSearch(token,params,options)})}async searchStatus(searchRef,waitTimeoutMs=0,options){return executeWithTokenRefresh({getToken:()=>this.tokenProvider.getToken(),forceRefresh:()=>this.tokenProvider.forceRefresh(),shouldRefresh:isTokenRefreshableError,executeWithToken:(token)=>this.executeUnifiedSearchStatus(token,searchRef,waitTimeoutMs,options)})}async codeDiff(params){validateCodeDiffParams(params);return executeWithTokenRefresh({getToken:()=>this.tokenProvider.getToken(),forceRefresh:()=>this.tokenProvider.forceRefresh(),shouldRefresh:isTokenRefreshableError,executeWithToken:(token)=>this.executeCodeDiff(token,params)})}async executeCodeDiff(token,params){const query=buildCodeDiffQuery(params.mode);const variables=buildCodeDiffVariables(params);debugGraphqlWireRequest("codeDiff",query,variables,this.runtime.diagnostics);let response;try{response=await this.postGraphqlWithTargetResolutionFallback({token,query,variables})}catch(cause){if(cause instanceof PkgseerTransportError){throw this.createTransportError(cause)}throw cause}if(response.status<200||response.status>=300){throw this.createHttpError(response)}const parsed=codeDiffGraphQLResponseSchema.safeParse(response.parsedBody);if(!parsed.success){throw new MalformedCodeNavigationResponseError("Malformed response from code navigation service.")}const data=parsed.data.data?.codeDiff;const errors=parsed.data.errors??[];if(errors.length>0){const rawErrors=errors.filter(isCodeDiffRawError);if(rawErrors.length>0){throw new 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,extensions})=>({message,extensions}));const message=errors.map((error)=>error.message).join(", ");const extensions=getPrimaryExtensions(errors);const code=typeof extensions?.code==="string"?extensions.code:undefined;if(code==="AUTHENTICATION_REQUIRED"){return new 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,options){if(params.targets.length===0){throw new CodeNavigationValidationError("At least one search target is required.")}let response;const variables={targets:params.targets.map((target)=>({registry:target.registry,name:target.packageName,version:target.version,repoUrl:target.repoUrl,gitRef:target.gitRef,site:target.site})),query:params.query,sources:params.sources,filters:params.filters,allowPartialResults:params.allowPartialResults??false,limit:params.limit,offset:params.offset,waitTimeoutMs:params.waitTimeoutMs,includeFocusedSource:options?.omitFocusedSource!==true};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,options){let response;try{response=await this.postGraphqlWithTargetResolutionFallback({token,query:UNIFIED_SEARCH_STATUS_QUERY,variables:{searchRef,includeResults:true,waitTimeoutMs,includeFocusedSource:options?.omitFocusedSource!==true}})}catch(cause){if(cause instanceof PkgseerTransportError){throw this.createTransportError(cause)}throw cause}if(response.status<200||response.status>=300){throw this.createHttpError(response)}const parsed=unifiedSearchStatusGraphQLResponseSchema.safeParse(response.parsedBody);if(!parsed.success){throw new MalformedCodeNavigationResponseError("Malformed response from code navigation service.")}if(parsed.data.errors&&parsed.data.errors.length>0){throw this.createGraphQLError(parsed.data.errors)}const data=parsed.data.data?.discoverySearchProgress;if(!data){throw new MalformedCodeNavigationResponseError("Malformed response from code navigation service.")}const progress=this.normaliseUnifiedSearchProgress(data);const result=data.results?this.normaliseUnifiedSearchResult(data.results):undefined;if(result&&progress.status==="COMPLETED"){return{state:"completed",completed:true,searchRef:progress.searchRef,result,progress}}return{state:"incomplete",completed:false,searchRef:progress.searchRef,result,progress}}createHttpError(response){const status=response.status;const detail=parseDetail(response.responseBody);if(status===401){return new AuthenticationError(SERVER_AUTHENTICATION_REJECTED_MESSAGE,"server")}if(status===403){return new CodeNavigationAccessError(detail??"Code navigation access denied.")}if(status>=500){return new CodeNavigationBackendError(detail?`Server error (${status}): ${detail}`:`Server error (${status})`,status)}return new CodeNavigationBackendError(detail??`Request failed with status ${status}`,status)}createTransportError(error){if(isFetchTimeoutError(error.cause)){return new CodeNavigationBackendError("Code navigation request timed out.",undefined,"TIMEOUT",true)}return new CodeNavigationNetworkError("Could not reach the code navigation service. Check your connection or set GITHITS_CODE_NAV_URL.",{cause:error})}createGraphQLError(errors){const message=errors.map((error)=>error.message).join(", ");const extensions=getPrimaryExtensions(errors);const code=typeof extensions?.code==="string"?extensions.code:undefined;const retryable=typeof extensions?.retryable==="boolean"?extensions.retryable:undefined;const indexingRef=getGraphQLIndexingRef(errors);const indexingEstimate=parseIndexingDurationEstimate(extensions);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,repositoryEvidence:entry.repositoryEvidence,documentationPreview:entry.documentationPreview,contentSafety:entry.contentSafety,locator:normaliseUnifiedSearchLocator(entry.locator)})),page:{offset:result.page.offset,limit:result.page.limit,returned:result.page.returned,hasMore:result.page.hasMore},partialResults:result.partialResults,sourceStatus:result.sourceStatus.map((entry)=>({source:entry.source,targetLabel:entry.targetLabel,requestedTargetLabel:entry.requestedTargetLabel??undefined,freshTargetLabel:entry.freshTargetLabel??undefined,servedTargetLabel:entry.servedTargetLabel??undefined,targetResolution:normaliseTargetResolution(entry.targetResolution),indexingStatus:entry.indexingStatus??undefined,codeIndexState:entry.codeIndexState??undefined,resultCount:entry.resultCount??undefined,appliedFilters:entry.appliedFilters,ignoredFilters:entry.ignoredFilters,incompatibleFilters:entry.incompatibleFilters,appliedQueryFeatures:entry.appliedQueryFeatures,ignoredQueryFeatures:entry.ignoredQueryFeatures,incompatibleQueryFeatures:entry.incompatibleQueryFeatures,suggestedSiteTargets:entry.suggestedSiteTargets,suggestedSiteTargetsTruncated:entry.suggestedSiteTargetsTruncated,note:entry.note??undefined,coverage:normaliseDocCoverage(entry.coverage),contributors:entry.contributors.map((contributor)=>({kind:contributor.kind,state:contributor.state,freshness:contributor.freshness??undefined,resultCount:contributor.resultCount,repositoryUrl:contributor.repositoryUrl??undefined,commitSha:contributor.commitSha??undefined,siteKey:contributor.siteKey??undefined,siteUrl:contributor.siteUrl??undefined,coverage:normaliseDocCoverage(contributor.coverage,{preserveNone:true})}))})),evidenceNotice:result.evidenceNotice??undefined}}normaliseUnifiedSearchProgress(progress){return{searchRef:progress.searchRef,status:progress.status,targetsTotal:progress.targetsTotal,targetsReady:progress.targetsReady,elapsedMs:progress.elapsedMs,query:progress.query,queryWarnings:progress.queryWarnings,sources:progress.sources,requestedSources:progress.requestedSources??undefined,targetMode:normaliseTargetMode(progress.targetMode),requestedTargets:progress.requestedTargets?.map((target)=>({registry:target.registry?target.registry:undefined,name:target.name??undefined,version:target.version??undefined,repoUrl:target.repoUrl??undefined,gitRef:target.gitRef??undefined,site:target.site??undefined})),filters:normaliseProgressFilters(progress.filters),limit:progress.limit??undefined,offset:progress.offset??undefined,targets:progress.targets?.map((target)=>({requested:target.requested??undefined,resolvedRequested:target.resolvedRequested??undefined,served:target.served??undefined,freshness:target.freshness??undefined,indexingRef:target.indexingRef??undefined,requestedRefKind:normaliseRequestedRefKind(target.requestedRefKind),targetResolution:normaliseTargetResolution(target.targetResolution),availableVersions:normaliseAvailableVersions(target.availableVersions),availableRefs:normaliseAvailableVersions(target.availableRefs),suggestedRefs:normaliseAvailableVersions(target.suggestedRefs),coverage:normaliseDocCoverage(target.coverage)})),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,contentHash:entry.symbol.contentHash??undefined,parentPath:entry.symbol.parentPath??undefined}:undefined})),nextCursor:data.nextCursor??undefined,hasMore:data.hasMore,truncatedReason:data.truncatedReason,routeTaken:data.routeTaken??undefined,filesScanned:data.filesScanned,filesInScope:data.filesInScope,binaryFilesSkipped:data.binaryFilesSkipped,filesTooLargeSkipped:data.filesTooLargeSkipped,totalMatches:data.totalMatches,uniqueFilesMatched:data.uniqueFilesMatched,indexedVersion:data.indexedVersion??undefined,resolution:data.resolution?{requestedVersion:data.resolution.requestedVersion??undefined,requestedRef:data.resolution.requestedRef??undefined,resolvedRef:data.resolution.resolvedRef??undefined,commitSha:data.resolution.commitSha??undefined}:undefined,targetResolution:normaliseTargetResolution(data.targetResolution)}}}function normaliseUnifiedSearchLocator(value){return{registry:value.registry??undefined,packageName:value.packageName??undefined,version:value.version??undefined,pageId:value.pageId??undefined,docsReadTarget:value.docsReadTarget??undefined,sourceKind:value.sourceKind??undefined,sourceUrl:value.sourceUrl??undefined,repoUrl:value.repoUrl??undefined,gitRef:value.gitRef??undefined,commitSha:value.commitSha??undefined,requestedRef:value.requestedRef??undefined,filePath:value.filePath??undefined,repositoryFilePath:value.repositoryFilePath??undefined,startLine:value.startLine??undefined,endLine:value.endLine??undefined,evidenceRange:value.evidenceRange?{startLine:value.evidenceRange.startLine,endLine:value.evidenceRange.endLine,matchLine:value.evidenceRange.matchLine??undefined,rangeKind:value.evidenceRange.rangeKind??undefined,matchSpansTruncated:value.evidenceRange.matchSpansTruncated}:undefined,indexedRange:value.indexedRange?{startLine:value.indexedRange.startLine,endLine:value.indexedRange.endLine}:undefined,symbolContext:value.symbolContext?normaliseUnifiedSearchSymbolContext(value.symbolContext):undefined,fileContentHash:value.fileContentHash??undefined,symbolRef:value.symbolRef??undefined,qualifiedPath:value.qualifiedPath??undefined,kind:value.kind??undefined,category:value.category??undefined,language:value.language??undefined}}function normaliseUnifiedSearchSymbolContext(value){const identity={name:value.name,qualifiedPath:value.qualifiedPath??undefined,kind:value.kind??undefined};if(value.relation==="ENCLOSES_MATCH"){return{...identity,relation:"encloses_match",definitionRange:normaliseUnifiedSearchDefinitionRange(value.definitionRange)}}return{...identity,relation:"associated_with_indexed_chunk",definitionRange:value.definitionRange?normaliseUnifiedSearchDefinitionRange(value.definitionRange):undefined}}function normaliseUnifiedSearchDefinitionRange(value){return{filePath:value.filePath,repositoryFilePath:value.repositoryFilePath,startLine:value.startLine,endLine:value.endLine}}function validateCodeDiffParams(params){const paramsRecord=asRecord(params);if(!paramsRecord){throw new CodeNavigationValidationError("CodeDiff params must be an object.")}if(paramsRecord.mode!=="inventory"&&paramsRecord.mode!=="stats"&&paramsRecord.mode!=="patches"){throw new CodeNavigationValidationError("CodeDiff mode must be inventory, stats, or patches.")}if(typeof paramsRecord.from!=="string"||paramsRecord.from.length===0){throw new CodeNavigationValidationError("CodeDiff from ref or version must not be empty.")}if(typeof paramsRecord.to!=="string"||paramsRecord.to.length===0){throw new CodeNavigationValidationError("CodeDiff to ref or version must not be empty.")}const target=asRecord(paramsRecord.target);if(!target){throw new CodeNavigationValidationError("CodeDiff target must be a package or repository target.")}if(Object.hasOwn(target,"registry")&&Object.hasOwn(target,"packageName")&&!Object.hasOwn(target,"repoUrl")){if(!codeDiffRegistrySchema.safeParse(target.registry).success){throw new CodeNavigationValidationError("CodeDiff package target has an unsupported registry.")}if(typeof target.packageName!=="string"||target.packageName.length===0){throw new CodeNavigationValidationError("CodeDiff package target name must not be empty.")}}else if(Object.hasOwn(target,"repoUrl")&&!Object.hasOwn(target,"registry")&&!Object.hasOwn(target,"packageName")){if(typeof target.repoUrl!=="string"||target.repoUrl.length===0){throw new CodeNavigationValidationError("CodeDiff repository target URL must not be empty.")}}else if((Object.hasOwn(target,"registry")||Object.hasOwn(target,"packageName"))&&Object.hasOwn(target,"repoUrl")){const conflictingKeys=["registry","packageName","repoUrl"].filter((key)=>Object.hasOwn(target,key)).join(", ");throw new CodeNavigationValidationError(`CodeDiff target has conflicting present keys: ${conflictingKeys}. Target shape is determined by key presence, even when a value is undefined.`)}else{throw new CodeNavigationValidationError("CodeDiff target must be a package or repository target.")}const optionsValue=paramsRecord.options;if(optionsValue===undefined)return;const options=asRecord(optionsValue);if(!options){throw new CodeNavigationValidationError("CodeDiff options must be an object when supplied.")}for(const key of Object.keys(options)){if(!CODE_DIFF_OPTION_KEYS.has(key)){throw new CodeNavigationValidationError(`CodeDiff options contains unknown key '${key}'.`)}}validateCodeDiffIntegerOption(options.maxFiles,"maxFiles",1,300);validateCodeDiffIntegerOption(options.maxPatchBytes,"maxPatchBytes",1024,2097152);validateCodeDiffPathOption(options.pathPrefix,"pathPrefix");validateCodeDiffPathOption(options.pathGlob,"pathGlob")}function validateCodeDiffIntegerOption(value,name,minimum,maximum){if(value===undefined)return;if(typeof value!=="number"||!Number.isInteger(value)||value<minimum||value>maximum){throw new CodeNavigationValidationError(`CodeDiff ${name} must be an integer from ${minimum} through ${maximum}.`)}}function validateCodeDiffPathOption(value,name){if(value===undefined)return;if(typeof value!=="string"){throw new CodeNavigationValidationError(`CodeDiff ${name} must be a string when supplied.`)}if(value.length===0){throw new CodeNavigationValidationError(`CodeDiff ${name} must not be empty when supplied.`)}if(new TextEncoder().encode(value).byteLength>1024){throw new CodeNavigationValidationError(`CodeDiff ${name} must be at most 1024 bytes.`)}}function buildCodeDiffVariables(params){const target=params.target;const variables={};if("registry"in target){variables.registry=target.registry;variables.name=target.packageName;variables.fromVersion=params.from;variables.toVersion=params.to}else{variables.repoUrl=target.repoUrl;variables.fromRef=params.from;variables.toRef=params.to}const rawOptions=Object.fromEntries(Object.entries(params.options??{}).filter(([,value])=>value!==undefined));if(Object.keys(rawOptions).length>0)variables.rawOptions=rawOptions;return variables}function isCodeDiffRawError(error){return error.path?.some((part)=>part==="raw")??false}function normaliseCodeDiffResult(result){if(!result.raw){throw new MalformedCodeNavigationResponseError("CodeDiff response missing non-null raw result.")}return{package:normaliseCodeDiffPackage(result.package),fromResolution:normaliseCodeDiffResolution(result.fromResolution),toResolution:normaliseCodeDiffResolution(result.toResolution),raw:normaliseRawCodeDiff(result.raw)}}function normaliseCodeDiffPartial(result){return{package:normaliseCodeDiffPackage(result.package),fromResolution:normaliseCodeDiffResolution(result.fromResolution),toResolution:normaliseCodeDiffResolution(result.toResolution),raw:result.raw?normaliseRawCodeDiff(result.raw):undefined}}function normaliseCodeDiffPackage(value){if(!value)return;return{registry:value.registry,name:value.name,repoUrl:value.repoUrl}}function normaliseCodeDiffResolution(value){return{requested:value.requested,resolvedVersion:value.resolvedVersion??undefined,ref:value.ref,commitSha:value.commitSha,refKind:value.refKind,versionSource:value.versionSource??undefined}}function normaliseRawCodeDiff(value){return{summary:value.summary,scope:{status:value.scope.status,fromSubpath:value.scope.fromSubpath??undefined,toSubpath:value.scope.toSubpath??undefined,pathPrefix:value.scope.pathPrefix??undefined,pathGlob:value.scope.pathGlob??undefined},contentCoverage:value.contentCoverage,contentFailure:value.contentFailure?{code:value.contentFailure.code,retryable:value.contentFailure.retryable,retryAfterMs:value.contentFailure.retryAfterMs??undefined,stage:value.contentFailure.stage??undefined,limitKind:value.contentFailure.limitKind??undefined}:undefined,files:value.files.map((file)=>({path:file.path,pathEncoding:file.pathEncoding,status:file.status,modeChanged:file.modeChanged,typeChanged:file.typeChanged,additions:file.additions??undefined,deletions:file.deletions??undefined,patch:file.patch??undefined,contentStatus:file.contentStatus,contentOmissionReason:file.contentOmissionReason??undefined,contentSafety:{filtered:file.contentSafety.filtered,modifications:file.contentSafety.modifications}})),hasMoreFiles:value.hasMoreFiles}}function parseCodeDiffErrorDetails(errors){const extensions=getPrimaryExtensions(errors);if(!extensions)return;const details={};if(typeof extensions.code==="string")details.code=extensions.code;if(typeof extensions.retryable==="boolean"){details.retryable=extensions.retryable}if(extensions.side==="from"||extensions.side==="to"){details.side=extensions.side}const publishedVersions=parseCodeDiffStringArray(extensions.published_versions);if(publishedVersions)details.publishedVersions=publishedVersions;if(typeof extensions.published_versions_truncated==="boolean"){details.publishedVersionsTruncated=extensions.published_versions_truncated}const availableVersions=parseCodeDiffErrorRefs(extensions.available_versions);if(availableVersions)details.availableVersions=availableVersions;if(typeof extensions.registry==="string"){details.registry=extensions.registry}if(typeof extensions.retry_after_ms==="number"&&Number.isInteger(extensions.retry_after_ms)&&extensions.retry_after_ms>=0){details.retryAfterMs=extensions.retry_after_ms}if(typeof extensions.stage==="string")details.stage=extensions.stage;if(typeof extensions.limit_kind==="string"){details.limitKind=extensions.limit_kind}if(typeof extensions.repo_url==="string"){details.repoUrl=extensions.repo_url}if(typeof extensions.git_ref==="string")details.gitRef=extensions.git_ref;const availableRefs=parseCodeDiffErrorRefs(extensions.available_refs);if(availableRefs)details.availableRefs=availableRefs;const suggestedRefs=parseCodeDiffErrorRefs(extensions.suggested_refs);if(suggestedRefs)details.suggestedRefs=suggestedRefs;const refKinds=parseCodeDiffStringArray(extensions.ref_kinds);if(refKinds)details.refKinds=refKinds;return Object.keys(details).length>0?details:undefined}function parseCodeDiffStringArray(value){if(!Array.isArray(value))return;if(value.some((entry)=>typeof entry!=="string"))return;return value}function parseCodeDiffErrorRefs(value){if(!Array.isArray(value))return;const refs=[];for(const entry of value){if(!entry||typeof entry!=="object"||Array.isArray(entry)){return}const record=entry;if(typeof record.ref!=="string"||record.version!==undefined&&record.version!==null&&typeof record.version!=="string"){return}refs.push({ref:record.ref,version:typeof record.version==="string"?record.version:undefined})}return refs}function 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 z4}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=z4.object({stargazersCount:z4.number().int().nullable().optional(),forksCount:z4.number().int().nullable().optional(),openIssuesCount:z4.number().int().nullable().optional(),archived:z4.boolean().nullable().optional(),language:z4.string().nullable().optional(),topics:z4.array(z4.string()).nullable().optional(),pushedAt:z4.string().nullable().optional()}).nullable().optional();var packageIdentitySchema=z4.object({name:z4.string().nullable().optional(),registry:z4.string().nullable().optional(),description:z4.string().nullable().optional(),latestVersion:z4.string().nullable().optional(),latestVersionPublishedAt:z4.string().nullable().optional(),versionCount:z4.number().int().nullable().optional(),downloadsRefreshedAt:z4.string().nullable().optional(),homepage:z4.string().nullable().optional(),repositoryUrl:z4.string().nullable().optional(),license:z4.string().nullable().optional(),downloadsLastMonth:z4.number().int().nullable().optional(),downloadsTotal:z4.number().int().nullable().optional(),githubRepository:githubRepositorySchema});var vulnerabilityOverviewSchema=z4.object({osvId:z4.string().nullable().optional(),summary:z4.string().nullable().optional(),severityScore:z4.number().nullable().optional(),publishedAt:z4.string().nullable().optional()});var packageSecurityOverviewSchema=z4.object({vulnerabilityCount:z4.number().int().nullable().optional(),allVulnerabilityCount:z4.number().int(),hasCurrentVulnerabilities:z4.boolean().nullable().optional(),recentVulnerabilities:z4.array(vulnerabilityOverviewSchema).nullable().optional()}).nullable().optional();var changelogEntrySchema=z4.object({version:z4.string().nullable().optional(),publishedAt:z4.string().nullable().optional(),body:z4.string().nullable().optional()});var packageSummaryResponseSchema=z4.object({package:packageIdentitySchema.nullable().optional(),security:packageSecurityOverviewSchema,latestChangelogs:z4.array(changelogEntrySchema).nullable().optional()});var graphQLErrorSchema2=z4.object({message:z4.string(),extensions:z4.record(z4.string(),z4.unknown()).optional()});var graphQLResponseSchema=z4.object({data:z4.object({packageSummary:packageSummaryResponseSchema.nullable().optional()}).nullable().optional(),errors:z4.array(graphQLErrorSchema2).optional()});var PACKAGE_SUMMARY_QUERY=`
687
713
  query PackageSummary(
688
714
  $registry: Registry!
689
715
  $name: String!
@@ -730,7 +756,7 @@ query PackageSummary(
730
756
  body
731
757
  }
732
758
  }
733
- }`;var packageVersionIdentitySchema=z4.object({name:z4.string().nullable().optional(),registry:z4.string().nullable().optional(),version:z4.string().nullable().optional(),publishedAt:z4.string().nullable().optional(),deprecated:z4.boolean().nullable().optional(),deprecationReason:z4.string().nullable().optional()});var vulnerabilityDetailSchema=z4.object({osvId:z4.string().nullable().optional(),summary:z4.string().nullable().optional(),severityScore:z4.number().nullable().optional(),severityType:z4.string().nullable().optional(),affectedVersionRanges:z4.array(z4.string()).nullable().optional(),affectedVersionRangesCount:z4.number().int(),affectedVersionRangesTruncated:z4.boolean(),fixedInVersions:z4.array(z4.string()).nullable().optional(),publishedAt:z4.string().nullable().optional(),modifiedAt:z4.string().nullable().optional(),withdrawnAt:z4.string().nullable().optional(),aliases:z4.array(z4.string()).nullable().optional(),isMalicious:z4.boolean().nullable().optional(),affectsInspectedVersion:z4.boolean(),matchedAffectedVersionRanges:z4.array(z4.string()),duplicateIds:z4.array(z4.string())});var pageInfoSchema=z4.object({hasNextPage:z4.boolean(),endCursor:z4.string().nullable().optional(),totalCount:z4.number().int()});var vulnerabilityAdvisoryPageSchema=z4.object({entries:z4.array(vulnerabilityDetailSchema),pageInfo:pageInfoSchema});var vulnerabilitySecurityDetailsSchema=z4.object({affectedVulnerabilityCount:z4.number().int(),nonAffectingVulnerabilityCount:z4.number().int(),allVulnerabilityCount:z4.number().int(),currentVersionAffected:z4.boolean().nullable().optional(),advisories:vulnerabilityAdvisoryPageSchema,upgradePaths:z4.array(z4.string()).nullable().optional()}).nullable().optional();var vulnerabilityReportResponseSchema=z4.object({package:packageVersionIdentitySchema.nullable().optional(),security:vulnerabilitySecurityDetailsSchema});var vulnerabilitiesGraphQLResponseSchema=z4.object({data:z4.object({packageVulnerabilities:vulnerabilityReportResponseSchema.nullable().optional()}).nullable().optional(),errors:z4.array(graphQLErrorSchema2).optional()});var PACKAGE_VULNERABILITIES_QUERY=`
759
+ }`;var packageVersionIdentitySchema=z4.object({name:z4.string().nullable().optional(),registry:z4.string().nullable().optional(),version:z4.string().nullable().optional(),publishedAt:z4.string().nullable().optional(),deprecated:z4.boolean().nullable().optional(),deprecationReason:z4.string().nullable().optional()});var vulnerabilityDetailSchema=z4.object({osvId:z4.string().nullable().optional(),summary:z4.string().nullable().optional(),severityScore:z4.number().nullable().optional(),severityType:z4.string().nullable().optional(),affectedVersionRanges:z4.array(z4.string()).nullable().optional(),affectedVersionRangesCount:z4.number().int(),affectedVersionRangesTruncated:z4.boolean(),fixedInVersions:z4.array(z4.string()).nullable().optional(),publishedAt:z4.string().nullable().optional(),modifiedAt:z4.string().nullable().optional(),withdrawnAt:z4.string().nullable().optional(),aliases:z4.array(z4.string()).nullable().optional(),isMalicious:z4.boolean().nullable().optional(),affectsInspectedVersion:z4.boolean(),matchedAffectedVersionRanges:z4.array(z4.string()),duplicateIds:z4.array(z4.string())});var pageInfoSchema=z4.object({hasNextPage:z4.boolean(),endCursor:z4.string().nullable().optional(),totalCount:z4.number().int()});var vulnerabilityAdvisoryPageSchema=z4.object({entries:z4.array(vulnerabilityDetailSchema),pageInfo:pageInfoSchema});var vulnerabilitySecurityDetailsSchema=z4.object({affectedVulnerabilityCount:z4.number().int(),nonAffectingVulnerabilityCount:z4.number().int(),allVulnerabilityCount:z4.number().int(),currentVersionAffected:z4.boolean().nullable().optional(),advisories:vulnerabilityAdvisoryPageSchema,upgradePaths:z4.array(z4.string()).nullable().optional()}).nullable().optional();var vulnerabilityReportResponseSchema=z4.object({package:packageVersionIdentitySchema.nullable().optional(),security:vulnerabilitySecurityDetailsSchema});var vulnerabilitiesGraphQLResponseSchema=z4.object({data:z4.object({packageVulnerabilities:vulnerabilityReportResponseSchema.nullable().optional()}).nullable().optional(),errors:z4.array(graphQLErrorSchema2).optional()});var transitiveAuditAdvisorySchema=z4.object({osvId:z4.string().nullable().optional(),summary:z4.string().nullable().optional(),severityScore:z4.number().nullable().optional(),affectedVersionRanges:z4.array(z4.string()).nullable().optional(),fixedInVersions:z4.array(z4.string()).nullable().optional(),publishedAt:z4.string().nullable().optional(),modifiedAt:z4.string().nullable().optional(),aliases:z4.array(z4.string()).nullable().optional(),isMalicious:z4.boolean().nullable().optional()});var transitiveAuditOccurrenceSchema=z4.object({version:z4.string(),affectsResolvedVersion:z4.boolean(),matchedAffectedVersionRanges:z4.array(z4.string()),fixVersionsAboveResolved:z4.array(z4.string()),nearestFixedVersion:z4.string().nullable().optional(),advisory:transitiveAuditAdvisorySchema});var transitiveAuditPackageSchema=z4.object({registry:z4.string(),name:z4.string(),selectedCount:z4.number().int().nonnegative(),advisoryOccurrences:z4.array(transitiveAuditOccurrenceSchema).nullable().optional()});var transitiveAuditSummarySchema=z4.object({selected:z4.object({totalVulnerabilities:z4.number().int().nonnegative()}),totalPackagesAnalyzed:z4.number().int().nonnegative(),packages:z4.array(transitiveAuditPackageSchema),calculatedAt:z4.string().nullable().optional()});var transitiveAuditResponseSchema=z4.object({package:packageVersionIdentitySchema.nullable().optional(),dependencies:z4.object({transitive:z4.object({vulnerabilitySummary:transitiveAuditSummarySchema.nullable().optional()}).nullable().optional()}).nullable().optional()});var transitiveAuditGraphQLResponseSchema=z4.object({data:z4.object({packageDependencies:transitiveAuditResponseSchema.nullable().optional()}).nullable().optional(),errors:z4.array(graphQLErrorSchema2).optional()});var PACKAGE_VULNERABILITIES_QUERY=`
734
760
  query PackageVulnerabilities(
735
761
  $registry: Registry!
736
762
  $name: String!
@@ -785,7 +811,62 @@ query PackageVulnerabilities(
785
811
  }
786
812
  }
787
813
  }
788
- }`;var directDependencySchema=z4.object({name:z4.string().nullable().optional(),versionConstraint:z4.string().nullable().optional(),type:z4.string().nullable().optional()});var dependencyGraphNodeSchema=z4.object({registry:z4.string(),name:z4.string(),version:z4.string().nullable().optional()});var dependencyGraphEdgeSchema=z4.object({fromIndex:z4.number().int().nullable().optional(),toIndex:z4.number().int(),constraint:z4.string().nullable().optional(),dependencyType:z4.string().nullable().optional()});var dependencyGraphSchema=z4.object({formatVersion:z4.number().int(),nodes:z4.array(dependencyGraphNodeSchema),edges:z4.array(dependencyGraphEdgeSchema)});var vulnerabilityCountSummarySchema=z4.object({totalVulnerabilities:z4.number().int(),critical:z4.number().int(),high:z4.number().int(),medium:z4.number().int(),low:z4.number().int(),unknown:z4.number().int()});var vulnerabilitySummaryDetailSchema=z4.object({osvId:z4.string().nullable().optional(),registry:z4.string().nullable().optional(),packageName:z4.string().nullable().optional(),summary:z4.string().nullable().optional(),severityScore:z4.number().nullable().optional(),severityType:z4.string().nullable().optional(),affectedVersionRanges:z4.array(z4.string()).nullable().optional(),fixedInVersions:z4.array(z4.string()).nullable().optional(),publishedAt:z4.string().nullable().optional(),modifiedAt:z4.string().nullable().optional(),withdrawnAt:z4.string().nullable().optional(),aliases:z4.array(z4.string()).nullable().optional(),isMalicious:z4.boolean().nullable().optional()});var transitiveDependencyVulnerabilitySchema=z4.object({version:z4.string(),affectsResolvedVersion:z4.boolean(),matchedAffectedVersionRanges:z4.array(z4.string()),fixVersionsAboveResolved:z4.array(z4.string()),nearestFixedVersion:z4.string().nullable().optional(),advisory:vulnerabilitySummaryDetailSchema});var transitiveVulnerablePackageSchema=z4.object({registry:z4.string(),name:z4.string(),versions:z4.array(z4.string()),affectedCount:z4.number().int(),nonAffectingCount:z4.number().int(),totalCount:z4.number().int(),maxSeverityScore:z4.number().nullable().optional(),maxSeverityLabel:z4.string().nullable().optional(),advisoryIds:z4.array(z4.string()),mostCritical:vulnerabilitySummaryDetailSchema.nullable().optional(),advisoryOccurrences:z4.array(transitiveDependencyVulnerabilitySchema).nullable().optional()});var transitiveVulnerabilitySummarySchema=z4.object({affected:vulnerabilityCountSummarySchema,nonAffecting:vulnerabilityCountSummarySchema,combined:vulnerabilityCountSummarySchema,totalPackagesAnalyzed:z4.number().int(),affectedPackageCount:z4.number().int(),packages:z4.array(transitiveVulnerablePackageSchema),calculatedAt:z4.string().nullable().optional()}).nullable().optional();var dependencyDeprecationReasonSchema=z4.object({version:z4.string(),reason:z4.string().nullable().optional()});var deprecatedDependencySchema=z4.object({registry:z4.string(),name:z4.string(),versions:z4.array(z4.string()),reasons:z4.array(dependencyDeprecationReasonSchema)});var outdatedDependencyVersionSchema=z4.object({version:z4.string(),severity:z4.string()});var outdatedDependencySchema=z4.object({registry:z4.string(),name:z4.string(),latestVersion:z4.string().nullable().optional(),severity:z4.string(),versions:z4.array(outdatedDependencyVersionSchema),repositoryUrl:z4.string().nullable().optional()});var duplicateDependencySchema=z4.object({registry:z4.string().nullable().optional(),name:z4.string(),versions:z4.array(z4.string())});var dependencyConflictEdgeSchema=z4.object({fromIndex:z4.number().int().nullable().optional(),toIndex:z4.number().int(),versionConstraint:z4.string(),dependencyType:z4.string()});var dependencyConflictSchema=z4.object({packageName:z4.string(),requiredVersions:z4.array(z4.string()),conflictingEdges:z4.array(dependencyConflictEdgeSchema)});var dependencyIssueConflictSchema=z4.object({registry:z4.string().nullable().optional(),name:z4.string(),versions:z4.array(z4.string()),requiredVersions:z4.array(z4.string()),conflictingEdges:z4.array(dependencyConflictEdgeSchema)});var dependencyIssuesSummarySchema=z4.object({totalCount:z4.number().int(),deprecatedCount:z4.number().int(),outdatedCount:z4.number().int(),duplicateCount:z4.number().int(),conflictCount:z4.number().int(),deprecatedPackages:z4.array(deprecatedDependencySchema),outdatedPackages:z4.array(outdatedDependencySchema),duplicatePackages:z4.array(duplicateDependencySchema),conflicts:z4.array(dependencyIssueConflictSchema)}).nullable().optional();var circularDependencyCycleSchema=z4.object({cycleStart:z4.string(),circularPath:z4.array(z4.string()),displayChain:z4.string()});var environmentMarkerSchema=z4.object({type:z4.string().nullable().optional(),value:z4.string().nullable().optional(),raw:z4.string().nullable().optional()});var transitiveDependencySchema=z4.object({totalEdges:z4.number().int().nullable().optional(),uniquePackagesCount:z4.number().int().nullable().optional(),uniqueDependencies:z4.array(z4.string()).nullable().optional(),dependencyConflicts:z4.array(dependencyConflictSchema).nullable().optional(),circularDependencyCycles:z4.array(circularDependencyCycleSchema).nullable().optional(),dependencyGraph:dependencyGraphSchema.nullable().optional(),vulnerabilitySummary:transitiveVulnerabilitySummarySchema,dependencyIssues:dependencyIssuesSummarySchema}).nullable().optional();var dependencyBundleSchema=z4.object({direct:z4.array(directDependencySchema).nullable().optional(),transitive:transitiveDependencySchema}).nullable().optional();var groupDependencySchema=z4.object({name:z4.string(),constraint:z4.string().nullable().optional()});var dependencyGroupSchema=z4.object({name:z4.string(),lifecycle:z4.string(),conditionType:z4.string(),conditionValue:z4.string().nullable().optional(),selectionMode:z4.string(),exclusiveGroup:z4.string().nullable().optional(),fallbackPriority:z4.number().int().nullable().optional(),compatibleWith:z4.array(z4.string()).nullable().optional(),defaultEnabled:z4.boolean().nullable().optional(),dependencies:z4.array(groupDependencySchema)});var dependencyGroupsInfoSchema=z4.object({primaryGroup:z4.string().nullable().optional(),environmentMarkers:z4.array(environmentMarkerSchema).nullable().optional(),groups:z4.array(dependencyGroupSchema)}).nullable().optional();var dependencyReportResponseSchema=z4.object({package:packageVersionIdentitySchema.nullable().optional(),dependencies:dependencyBundleSchema,dependencyGroups:dependencyGroupsInfoSchema});var dependenciesGraphQLResponseSchema=z4.object({data:z4.object({packageDependencies:dependencyReportResponseSchema.nullable().optional()}).nullable().optional(),errors:z4.array(graphQLErrorSchema2).optional()});var PACKAGE_DEPENDENCIES_QUERY=`
814
+ }`;var TRANSITIVE_AUDIT_SCOPE_FIELDS={AFFECTED:{summary:"affected",packageCount:"affectedCount"},NON_AFFECTING:{summary:"nonAffecting",packageCount:"nonAffectingCount"},ALL:{summary:"combined",packageCount:"totalCount"}};function buildPackageTransitiveVulnerabilityAuditQuery(scope){const fields=TRANSITIVE_AUDIT_SCOPE_FIELDS[scope];return`
815
+ query PackageTransitiveVulnerabilityAudit(
816
+ $registry: Registry!
817
+ $name: String!
818
+ $version: String!
819
+ $minSeverity: Float
820
+ $scope: VulnerabilityScope!
821
+ $includeTransitiveAdvisoryDetails: Boolean! = false
822
+ ) {
823
+ packageDependencies(
824
+ registry: $registry
825
+ name: $name
826
+ version: $version
827
+ includeTransitive: true
828
+ ) {
829
+ package {
830
+ name
831
+ registry
832
+ version
833
+ }
834
+ dependencies {
835
+ transitive {
836
+ vulnerabilitySummary(minSeverity: $minSeverity) {
837
+ selected: ${fields.summary} {
838
+ totalVulnerabilities
839
+ }
840
+ totalPackagesAnalyzed
841
+ calculatedAt
842
+ packages {
843
+ registry
844
+ name
845
+ selectedCount: ${fields.packageCount}
846
+ advisoryOccurrences(scope: $scope, minSeverity: $minSeverity) {
847
+ version
848
+ affectsResolvedVersion
849
+ matchedAffectedVersionRanges
850
+ fixVersionsAboveResolved
851
+ nearestFixedVersion
852
+ advisory {
853
+ osvId
854
+ summary
855
+ severityScore
856
+ affectedVersionRanges @include(if: $includeTransitiveAdvisoryDetails)
857
+ fixedInVersions @include(if: $includeTransitiveAdvisoryDetails)
858
+ publishedAt
859
+ modifiedAt
860
+ aliases
861
+ isMalicious
862
+ }
863
+ }
864
+ }
865
+ }
866
+ }
867
+ }
868
+ }
869
+ }`}var directDependencySchema=z4.object({name:z4.string().nullable().optional(),versionConstraint:z4.string().nullable().optional(),type:z4.string().nullable().optional()});var dependencyGraphNodeSchema=z4.object({registry:z4.string(),name:z4.string(),version:z4.string().nullable().optional()});var dependencyGraphEdgeSchema=z4.object({fromIndex:z4.number().int().nullable().optional(),toIndex:z4.number().int(),constraint:z4.string().nullable().optional(),dependencyType:z4.string().nullable().optional()});var dependencyGraphSchema=z4.object({formatVersion:z4.number().int(),nodes:z4.array(dependencyGraphNodeSchema),edges:z4.array(dependencyGraphEdgeSchema)});var vulnerabilityCountSummarySchema=z4.object({totalVulnerabilities:z4.number().int(),critical:z4.number().int(),high:z4.number().int(),medium:z4.number().int(),low:z4.number().int(),unknown:z4.number().int()});var vulnerabilitySummaryDetailSchema=z4.object({osvId:z4.string().nullable().optional(),registry:z4.string().nullable().optional(),packageName:z4.string().nullable().optional(),summary:z4.string().nullable().optional(),severityScore:z4.number().nullable().optional(),severityType:z4.string().nullable().optional(),affectedVersionRanges:z4.array(z4.string()).nullable().optional(),fixedInVersions:z4.array(z4.string()).nullable().optional(),publishedAt:z4.string().nullable().optional(),modifiedAt:z4.string().nullable().optional(),withdrawnAt:z4.string().nullable().optional(),aliases:z4.array(z4.string()).nullable().optional(),isMalicious:z4.boolean().nullable().optional()});var transitiveDependencyVulnerabilitySchema=z4.object({version:z4.string(),affectsResolvedVersion:z4.boolean(),matchedAffectedVersionRanges:z4.array(z4.string()),fixVersionsAboveResolved:z4.array(z4.string()),nearestFixedVersion:z4.string().nullable().optional(),advisory:vulnerabilitySummaryDetailSchema});var transitiveVulnerablePackageSchema=z4.object({registry:z4.string(),name:z4.string(),versions:z4.array(z4.string()),affectedCount:z4.number().int(),nonAffectingCount:z4.number().int(),totalCount:z4.number().int(),maxSeverityScore:z4.number().nullable().optional(),maxSeverityLabel:z4.string().nullable().optional(),advisoryIds:z4.array(z4.string()),mostCritical:vulnerabilitySummaryDetailSchema.nullable().optional(),advisoryOccurrences:z4.array(transitiveDependencyVulnerabilitySchema).nullable().optional()});var transitiveVulnerabilitySummarySchema=z4.object({affected:vulnerabilityCountSummarySchema,nonAffecting:vulnerabilityCountSummarySchema,combined:vulnerabilityCountSummarySchema,totalPackagesAnalyzed:z4.number().int(),affectedPackageCount:z4.number().int(),packages:z4.array(transitiveVulnerablePackageSchema),calculatedAt:z4.string().nullable().optional()}).nullable().optional();var dependencyDeprecationReasonSchema=z4.object({version:z4.string(),reason:z4.string().nullable().optional()});var deprecatedDependencySchema=z4.object({registry:z4.string(),name:z4.string(),versions:z4.array(z4.string()),reasons:z4.array(dependencyDeprecationReasonSchema)});var outdatedDependencyVersionSchema=z4.object({version:z4.string(),severity:z4.string()});var outdatedDependencySchema=z4.object({registry:z4.string(),name:z4.string(),latestVersion:z4.string().nullable().optional(),severity:z4.string(),versions:z4.array(outdatedDependencyVersionSchema),repositoryUrl:z4.string().nullable().optional()});var duplicateDependencySchema=z4.object({registry:z4.string().nullable().optional(),name:z4.string(),versions:z4.array(z4.string())});var dependencyConflictEdgeSchema=z4.object({fromIndex:z4.number().int().nullable().optional(),toIndex:z4.number().int(),versionConstraint:z4.string(),dependencyType:z4.string()});var dependencyConflictSchema=z4.object({packageName:z4.string(),requiredVersions:z4.array(z4.string()),conflictingEdges:z4.array(dependencyConflictEdgeSchema)});var dependencyIssueConflictSchema=z4.object({registry:z4.string().nullable().optional(),name:z4.string(),versions:z4.array(z4.string()),requiredVersions:z4.array(z4.string()),conflictingEdges:z4.array(dependencyConflictEdgeSchema)});var dependencyIssuesSummarySchema=z4.object({totalCount:z4.number().int(),deprecatedCount:z4.number().int(),outdatedCount:z4.number().int(),duplicateCount:z4.number().int(),conflictCount:z4.number().int(),deprecatedPackages:z4.array(deprecatedDependencySchema),outdatedPackages:z4.array(outdatedDependencySchema),duplicatePackages:z4.array(duplicateDependencySchema),conflicts:z4.array(dependencyIssueConflictSchema)}).nullable().optional();var circularDependencyCycleSchema=z4.object({cycleStart:z4.string(),circularPath:z4.array(z4.string()),displayChain:z4.string()});var environmentMarkerSchema=z4.object({type:z4.string().nullable().optional(),value:z4.string().nullable().optional(),raw:z4.string().nullable().optional()});var transitiveDependencySchema=z4.object({totalEdges:z4.number().int().nullable().optional(),uniquePackagesCount:z4.number().int().nullable().optional(),uniqueDependencies:z4.array(z4.string()).nullable().optional(),dependencyConflicts:z4.array(dependencyConflictSchema).nullable().optional(),circularDependencyCycles:z4.array(circularDependencyCycleSchema).nullable().optional(),dependencyGraph:dependencyGraphSchema.nullable().optional(),vulnerabilitySummary:transitiveVulnerabilitySummarySchema,dependencyIssues:dependencyIssuesSummarySchema}).nullable().optional();var dependencyBundleSchema=z4.object({direct:z4.array(directDependencySchema).nullable().optional(),transitive:transitiveDependencySchema}).nullable().optional();var groupDependencySchema=z4.object({name:z4.string(),constraint:z4.string().nullable().optional()});var dependencyGroupSchema=z4.object({name:z4.string(),lifecycle:z4.string(),conditionType:z4.string(),conditionValue:z4.string().nullable().optional(),selectionMode:z4.string(),exclusiveGroup:z4.string().nullable().optional(),fallbackPriority:z4.number().int().nullable().optional(),compatibleWith:z4.array(z4.string()).nullable().optional(),defaultEnabled:z4.boolean().nullable().optional(),dependencies:z4.array(groupDependencySchema)});var dependencyGroupsInfoSchema=z4.object({primaryGroup:z4.string().nullable().optional(),environmentMarkers:z4.array(environmentMarkerSchema).nullable().optional(),groups:z4.array(dependencyGroupSchema)}).nullable().optional();var dependencyReportResponseSchema=z4.object({package:packageVersionIdentitySchema.nullable().optional(),dependencies:dependencyBundleSchema,dependencyGroups:dependencyGroupsInfoSchema});var dependenciesGraphQLResponseSchema=z4.object({data:z4.object({packageDependencies:dependencyReportResponseSchema.nullable().optional()}).nullable().optional(),errors:z4.array(graphQLErrorSchema2).optional()});var PACKAGE_DEPENDENCIES_QUERY=`
789
870
  query PackageDependencies(
790
871
  $registry: Registry!
791
872
  $name: String!
@@ -1423,7 +1504,7 @@ query ReadPackageDoc($pageId: String!) {
1423
1504
  baseUrl
1424
1505
  }
1425
1506
  }
1426
- }`;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,versionCount:pkg?.versionCount??undefined,downloadsRefreshedAt:pkg?.downloadsRefreshedAt??undefined,githubRepository:github?{stargazersCount:github.stargazersCount??undefined,forksCount:github.forksCount??undefined,openIssuesCount:github.openIssuesCount??undefined,archived:github.archived??undefined,language:github.language??undefined,topics:github.topics??undefined,pushedAt:github.pushedAt??undefined}:undefined};const security=data.security?{vulnerabilityCount:data.security.vulnerabilityCount??undefined,allVulnerabilityCount:data.security.allVulnerabilityCount,hasCurrentVulnerabilities:data.security.hasCurrentVulnerabilities??undefined,recentVulnerabilities:data.security.recentVulnerabilities?.map((vuln)=>({osvId:vuln.osvId??undefined,summary:vuln.summary??undefined,severityScore:vuln.severityScore??undefined,publishedAt:vuln.publishedAt??undefined}))??undefined}:undefined;const latestChangelogs=data.latestChangelogs?.map((entry)=>({version:entry.version??undefined,publishedAt:entry.publishedAt??undefined,body:entry.body??undefined}))??undefined;return{package:identity,security,latestChangelogs}}async packageVulnerabilities(params){return withServiceDiagnostics(this.runtime.diagnostics,"pkg-intel.vulnerabilities.request",()=>executeWithTokenRefresh({getToken:()=>this.tokenProvider.getToken(),forceRefresh:()=>this.tokenProvider.forceRefresh(),shouldRefresh:isTokenRefreshableError,executeWithToken:(token)=>this.executePackageVulnerabilities(token,params)}))}async executePackageVulnerabilities(token,params){let after=null;let firstPage;const entries=[];const seenCursors=new Set;do{const page=await this.fetchPackageVulnerabilitiesPage(token,params,after);if(!firstPage)firstPage=page;const advisoryPage=page.security?.advisories;if(!advisoryPage){after=null;break}entries.push(...advisoryPage.entries);if(advisoryPage.pageInfo.hasNextPage){const nextCursor=advisoryPage.pageInfo.endCursor;if(!nextCursor){throw new MalformedPackageIntelligenceResponseError("Vulnerability response pagination omitted next cursor.")}if(seenCursors.has(nextCursor)){throw new MalformedPackageIntelligenceResponseError("Vulnerability response pagination repeated a cursor.")}seenCursors.add(nextCursor);after=nextCursor}else{after=null}}while(after!==null);if(!firstPage){throw new MalformedPackageIntelligenceResponseError("Empty response from the package-intelligence service.")}if(firstPage.security){const expectedCount=firstPage.security.advisories.pageInfo.totalCount;if(entries.length!==expectedCount){throw new MalformedPackageIntelligenceResponseError("Vulnerability response pagination returned an incomplete advisory set.")}}const data=firstPage.security?{...firstPage,security:{...firstPage.security,advisories:{...firstPage.security.advisories,entries}}}:firstPage;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.includeDependencyIssues===true?true:params.includeTransitive,includeTransitiveDetails:params.includeTransitiveDetails!==false,includeDependencyGraph:params.includeTransitive===true||params.includeDependencyIssues===true,includeDependencyIssues:params.includeDependencyIssues===true,includeGroups:params.includeGroups!==false,maxDepth:params.maxDepth,lifecycle:params.lifecycle&&params.lifecycle.length>0?params.lifecycle:undefined},fetchFn:this.fetchFn,clientHeaders:this.runtime.clientHeaders,userAgent:this.runtime.userAgent,diagnostics:this.runtime.diagnostics})}catch(cause){if(cause instanceof PkgseerTransportError){throw this.createTransportError(cause)}throw cause}if(response.status<200||response.status>=300){throw this.createHttpError(response)}const parsed=dependenciesGraphQLResponseSchema.safeParse(response.parsedBody);if(!parsed.success){throw new MalformedPackageIntelligenceResponseError("Malformed response from the package-intelligence service.")}if(parsed.data.errors&&parsed.data.errors.length>0){throw promoteGenericVersionNotFound(this.createGraphQLError(parsed.data.errors),params)}const data=parsed.data.data?.packageDependencies;if(!data){throw new MalformedPackageIntelligenceResponseError("Empty response from the package-intelligence service.")}const report=this.normaliseDependencyReport(data);if(params.includeDependencyIssues===true){const transitive=report.dependencies?.transitive;if(!transitive?.dependencyIssues){throw new MalformedPackageIntelligenceResponseError("Dependency issue analysis response missing dependency issues.")}if(!transitive.dependencyGraph){throw new MalformedPackageIntelligenceResponseError("Dependency issue analysis response missing dependency graph.")}}if(params.includeTransitive===true){const transitive=report.dependencies?.transitive;const hasConflictEdges=transitive?.dependencyConflicts?.some((conflict)=>conflict.conflictingEdges.length>0);if(hasConflictEdges&&!transitive?.dependencyGraph){throw new MalformedPackageIntelligenceResponseError("Transitive dependency conflict edges response missing dependency graph.")}}return report}normaliseDependencyReport(data){const name=data.package?.name??undefined;const version=data.package?.version??undefined;if(!name||!version){throw new MalformedPackageIntelligenceResponseError("Package dependencies response missing required name/version.")}const identity={name,version,registry:data.package?.registry??undefined,publishedAt:data.package?.publishedAt??undefined,deprecated:data.package?.deprecated??undefined,deprecationReason:data.package?.deprecationReason??undefined};const bundle=data.dependencies;const dependencies=bundle?{direct:bundle.direct?.map((entry)=>{if(!entry.name){throw new MalformedPackageIntelligenceResponseError("Dependency entry missing required name.")}return{name:entry.name,versionConstraint:entry.versionConstraint??undefined,type:entry.type??undefined}})??undefined,transitive:bundle.transitive?{totalEdges:bundle.transitive.totalEdges??undefined,uniquePackagesCount:bundle.transitive.uniquePackagesCount??undefined,uniqueDependencies:bundle.transitive.uniqueDependencies??undefined,dependencyConflicts:bundle.transitive.dependencyConflicts?.map((c)=>({packageName:c.packageName,requiredVersions:c.requiredVersions,conflictingEdges:c.conflictingEdges.map((edge)=>({fromIndex:edge.fromIndex??undefined,toIndex:edge.toIndex,versionConstraint:edge.versionConstraint,dependencyType:edge.dependencyType}))}))??undefined,circularDependencyCycles:bundle.transitive.circularDependencyCycles?.map((cycle)=>({cycleStart:cycle.cycleStart,circularPath:cycle.circularPath,displayChain:cycle.displayChain}))??undefined,dependencyGraph:bundle.transitive.dependencyGraph?{formatVersion:bundle.transitive.dependencyGraph.formatVersion,nodes:bundle.transitive.dependencyGraph.nodes.map((n)=>({registry:n.registry,name:n.name,version:n.version??undefined})),edges:bundle.transitive.dependencyGraph.edges.map((e)=>({fromIndex:e.fromIndex??undefined,toIndex:e.toIndex,constraint:e.constraint??undefined,dependencyType:e.dependencyType??undefined}))}:undefined,vulnerabilitySummary:this.normaliseTransitiveVulnerabilitySummary(bundle.transitive.vulnerabilitySummary),dependencyIssues:this.normaliseDependencyIssuesSummary(bundle.transitive.dependencyIssues)}:undefined}:undefined;const dependencyGroups=data.dependencyGroups?{primaryGroup:data.dependencyGroups.primaryGroup??undefined,environmentMarkers:data.dependencyGroups.environmentMarkers?.map((m)=>({type:m.type??undefined,value:m.value??undefined,raw:m.raw??undefined}))??undefined,groups:data.dependencyGroups.groups.map((group)=>({name:group.name,lifecycle:group.lifecycle,conditionType:group.conditionType,conditionValue:group.conditionValue??undefined,selectionMode:group.selectionMode,exclusiveGroup:group.exclusiveGroup??undefined,fallbackPriority:group.fallbackPriority??undefined,compatibleWith:group.compatibleWith??undefined,defaultEnabled:group.defaultEnabled??undefined,dependencies:group.dependencies.map((entry)=>({name:entry.name,constraint:entry.constraint??undefined}))}))}:undefined;return{package:identity,dependencies,dependencyGroups}}normaliseTransitiveVulnerabilitySummary(summary){if(!summary)return;return{affected:summary.affected,nonAffecting:summary.nonAffecting,combined:summary.combined,totalPackagesAnalyzed:summary.totalPackagesAnalyzed,affectedPackageCount:summary.affectedPackageCount,calculatedAt:summary.calculatedAt??undefined,packages:summary.packages.map((pkg)=>({registry:pkg.registry,name:pkg.name,versions:pkg.versions,affectedCount:pkg.affectedCount,nonAffectingCount:pkg.nonAffectingCount,totalCount:pkg.totalCount,maxSeverityScore:pkg.maxSeverityScore??undefined,maxSeverityLabel:pkg.maxSeverityLabel??undefined,advisoryIds:pkg.advisoryIds,mostCritical:pkg.mostCritical?this.normaliseVulnerabilitySummaryDetail(pkg.mostCritical):undefined,advisoryOccurrences:pkg.advisoryOccurrences?.map((occurrence)=>({version:occurrence.version,affectsResolvedVersion:occurrence.affectsResolvedVersion,matchedAffectedVersionRanges:occurrence.matchedAffectedVersionRanges,fixVersionsAboveResolved:occurrence.fixVersionsAboveResolved,nearestFixedVersion:occurrence.nearestFixedVersion??undefined,advisory:this.normaliseVulnerabilitySummaryDetail(occurrence.advisory)}))??undefined}))}}normaliseVulnerabilitySummaryDetail(advisory){return{osvId:advisory.osvId??undefined,registry:advisory.registry??undefined,packageName:advisory.packageName??undefined,summary:advisory.summary??undefined,severityScore:advisory.severityScore??undefined,severityType:advisory.severityType??undefined,affectedVersionRanges:advisory.affectedVersionRanges??undefined,fixedInVersions:advisory.fixedInVersions??undefined,publishedAt:advisory.publishedAt??undefined,modifiedAt:advisory.modifiedAt??undefined,withdrawnAt:advisory.withdrawnAt??undefined,aliases:advisory.aliases??undefined,isMalicious:advisory.isMalicious??undefined}}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,docsReadTarget:page.docsReadTarget,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,docsReadTarget:data.page.docsReadTarget,title:data.page.title??undefined,content:data.page.content??undefined,contentFormat:data.page.contentFormat??undefined,breadcrumbs:data.page.breadcrumbs??undefined,linkName:data.page.linkName??undefined,lastUpdatedAt:data.page.lastUpdatedAt??undefined,sourceKind:data.page.sourceKind??undefined,source:data.page.source?{url:data.page.source.url??undefined,label:data.page.source.label??undefined}:undefined,repoUrl:data.page.repoUrl??undefined,gitRef:data.page.gitRef??undefined,requestedRef:data.page.requestedRef??undefined,filePath:data.page.filePath??undefined,baseUrl:data.page.baseUrl??undefined}:undefined}}}function 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)}})}}import{z as z5}from"zod";var latestVersionMaliciousEvidenceSchema=z5.object({advisories:z5.array(z5.object({osvId:z5.string(),classificationReasons:z5.array(z5.string())})).max(5),totalCount:z5.number().int().nonnegative(),truncated:z5.boolean()}).nullable();var compactMatchSchema=z5.object({confidence:z5.string()});var candidateEvidenceSchema=z5.object({canonicalKey:z5.string(),nameSimilarity:z5.number().nullable()});var detailedMatchSchema=compactMatchSchema.extend({matchedAliases:z5.array(z5.string()),matchTier:z5.number().int(),score:z5.number()});var listTargetSchema=z5.object({kind:z5.string(),canonicalKey:z5.string(),latestVersionMaliciousStatus:z5.string(),latestVersionMaliciousEvidence:latestVersionMaliciousEvidenceSchema,description:z5.string().nullable().optional(),repositoryUrl:z5.string().nullable().optional(),stars:z5.number().int().nullable().optional(),downloadsLastMonth:z5.number().int().nullable().optional(),downloadsTotal:z5.number().int().nullable().optional(),docsAvailable:z5.boolean(),codeAvailable:z5.boolean(),groupKey:z5.string().nullable(),match:compactMatchSchema.nullable(),docsPageCount:z5.number().int().nullable(),codeFileCount:z5.number().int().nullable(),license:z5.string().nullable()});var targetReferenceSchema=z5.object({kind:z5.string(),canonicalKey:z5.string(),confidence:z5.string()});var detailedTargetSchema=listTargetSchema.omit({match:true}).extend({match:detailedMatchSchema.nullable(),displayName:z5.string(),registry:z5.string().nullable().optional(),packageName:z5.string().nullable().optional(),latestVersion:z5.string().nullable().optional(),repositoryOwner:z5.string().nullable().optional(),repositoryName:z5.string().nullable().optional(),documentationUrl:z5.string().nullable().optional()});var graphQLErrorSchema3=z5.object({message:z5.string(),extensions:z5.record(z5.string(),z5.unknown()).optional()});function responseSchema(targetSchema,includeNameSimilarity){const resultSchema=z5.object({best:targetReferenceSchema.nullable(),protectedMatches:z5.array(targetReferenceSchema),candidates:includeNameSimilarity?z5.array(candidateEvidenceSchema):z5.array(candidateEvidenceSchema).optional(),targets:z5.array(targetSchema),targetsTruncated:z5.boolean(),ambiguous:z5.boolean(),ambiguousReason:z5.string()});return z5.object({data:z5.object({resolveTarget:resultSchema.nullable()}).nullable().optional(),errors:z5.array(graphQLErrorSchema3).optional()})}var RESOLVE_TARGET_QUERY=`
1507
+ }`;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,versionCount:pkg?.versionCount??undefined,downloadsRefreshedAt:pkg?.downloadsRefreshedAt??undefined,githubRepository:github?{stargazersCount:github.stargazersCount??undefined,forksCount:github.forksCount??undefined,openIssuesCount:github.openIssuesCount??undefined,archived:github.archived??undefined,language:github.language??undefined,topics:github.topics??undefined,pushedAt:github.pushedAt??undefined}:undefined};const security=data.security?{vulnerabilityCount:data.security.vulnerabilityCount??undefined,allVulnerabilityCount:data.security.allVulnerabilityCount,hasCurrentVulnerabilities:data.security.hasCurrentVulnerabilities??undefined,recentVulnerabilities:data.security.recentVulnerabilities?.map((vuln)=>({osvId:vuln.osvId??undefined,summary:vuln.summary??undefined,severityScore:vuln.severityScore??undefined,publishedAt:vuln.publishedAt??undefined}))??undefined}:undefined;const latestChangelogs=data.latestChangelogs?.map((entry)=>({version:entry.version??undefined,publishedAt:entry.publishedAt??undefined,body:entry.body??undefined}))??undefined;return{package:identity,security,latestChangelogs}}async packageVulnerabilities(params){return withServiceDiagnostics(this.runtime.diagnostics,"pkg-intel.vulnerabilities.request",()=>executeWithTokenRefresh({getToken:()=>this.tokenProvider.getToken(),forceRefresh:()=>this.tokenProvider.forceRefresh(),shouldRefresh:isTokenRefreshableError,executeWithToken:(token)=>this.executePackageVulnerabilities(token,params)}))}async executePackageVulnerabilities(token,params){let after=null;let firstPage;const entries=[];const seenCursors=new Set;do{const page=await this.fetchPackageVulnerabilitiesPage(token,params,after);if(!firstPage)firstPage=page;const advisoryPage=page.security?.advisories;if(!advisoryPage){after=null;break}entries.push(...advisoryPage.entries);if(advisoryPage.pageInfo.hasNextPage){const nextCursor=advisoryPage.pageInfo.endCursor;if(!nextCursor){throw new MalformedPackageIntelligenceResponseError("Vulnerability response pagination omitted next cursor.")}if(seenCursors.has(nextCursor)){throw new MalformedPackageIntelligenceResponseError("Vulnerability response pagination repeated a cursor.")}seenCursors.add(nextCursor);after=nextCursor}else{after=null}}while(after!==null);if(!firstPage){throw new MalformedPackageIntelligenceResponseError("Empty response from the package-intelligence service.")}if(firstPage.security){const expectedCount=firstPage.security.advisories.pageInfo.totalCount;if(entries.length!==expectedCount){throw new MalformedPackageIntelligenceResponseError("Vulnerability response pagination returned an incomplete advisory set.")}}const data=firstPage.security?{...firstPage,security:{...firstPage.security,advisories:{...firstPage.security.advisories,entries}}}:firstPage;const report=this.normaliseVulnerabilityReport(data);if(params.includeTransitive===true){report.transitive=await this.fetchTransitiveVulnerabilityAudit(token,report.package,params.minSeverity,params.advisoryScope??"AFFECTED",params)}return report}async fetchPackageVulnerabilitiesPage(token,params,after){let response;try{response=await postPkgseerGraphql({endpointUrl:this.endpointUrl,token,query:PACKAGE_VULNERABILITIES_QUERY,variables:{registry:params.registry,name:params.packageName,version:params.version,minSeverity:params.minSeverity,includeWithdrawn:params.includeWithdrawn,scope:params.advisoryScope,after},fetchFn:this.fetchFn,clientHeaders:this.runtime.clientHeaders,userAgent:this.runtime.userAgent,diagnostics:this.runtime.diagnostics})}catch(cause){if(cause instanceof PkgseerTransportError){throw this.createTransportError(cause)}throw cause}if(response.status<200||response.status>=300){throw this.createHttpError(response)}const parsed=vulnerabilitiesGraphQLResponseSchema.safeParse(response.parsedBody);if(!parsed.success){throw new MalformedPackageIntelligenceResponseError("Malformed response from the package-intelligence service.")}if(parsed.data.errors&&parsed.data.errors.length>0){throw promoteGenericVersionNotFound(this.createGraphQLError(parsed.data.errors),params)}const data=parsed.data.data?.packageVulnerabilities;if(!data){throw new MalformedPackageIntelligenceResponseError("Empty response from the package-intelligence service.")}return data}normaliseVulnerabilityReport(data){const name=data.package?.name??undefined;const version=data.package?.version??undefined;if(!name||!version){throw new MalformedPackageIntelligenceResponseError("Vulnerability report response missing required name/version.")}const identity={name,version,registry:data.package?.registry??undefined,publishedAt:data.package?.publishedAt??undefined,deprecated:data.package?.deprecated??undefined,deprecationReason:data.package?.deprecationReason??undefined};const security=data.security?{affectedVulnerabilityCount:data.security.affectedVulnerabilityCount,nonAffectingVulnerabilityCount:data.security.nonAffectingVulnerabilityCount,allVulnerabilityCount:data.security.allVulnerabilityCount,currentVersionAffected:data.security.currentVersionAffected??undefined,vulnerabilities:data.security.advisories.entries.map((vuln)=>({osvId:vuln.osvId??undefined,summary:vuln.summary??undefined,severityScore:vuln.severityScore??undefined,severityType:vuln.severityType??undefined,affectedVersionRanges:vuln.affectedVersionRanges??undefined,affectedVersionRangesCount:vuln.affectedVersionRangesCount,affectedVersionRangesTruncated:vuln.affectedVersionRangesTruncated,fixedInVersions:vuln.fixedInVersions??undefined,publishedAt:vuln.publishedAt??undefined,modifiedAt:vuln.modifiedAt??undefined,withdrawnAt:vuln.withdrawnAt??undefined,aliases:vuln.aliases??undefined,isMalicious:vuln.isMalicious??undefined,affectsInspectedVersion:vuln.affectsInspectedVersion,matchedAffectedVersionRanges:vuln.matchedAffectedVersionRanges,duplicateIds:vuln.duplicateIds})),upgradePaths:data.security.upgradePaths??undefined}:undefined;return{package:identity,security}}async fetchTransitiveVulnerabilityAudit(token,directIdentity,minSeverity,advisoryScope,params){if(!directIdentity.registry){throw new MalformedPackageIntelligenceResponseError("Vulnerability report response missing registry for transitive audit.")}let response;try{response=await postPkgseerGraphql({endpointUrl:this.endpointUrl,token,query:buildPackageTransitiveVulnerabilityAuditQuery(advisoryScope),variables:{registry:params.registry,name:directIdentity.name,version:directIdentity.version,minSeverity,scope:advisoryScope,includeTransitiveAdvisoryDetails:params.includeTransitiveAdvisoryDetails===true},fetchFn:this.fetchFn,clientHeaders:this.runtime.clientHeaders,userAgent:this.runtime.userAgent,diagnostics:this.runtime.diagnostics})}catch(cause){if(cause instanceof PkgseerTransportError){throw this.createTransportError(cause)}throw cause}if(response.status<200||response.status>=300){throw this.createHttpError(response)}const parsed=transitiveAuditGraphQLResponseSchema.safeParse(response.parsedBody);if(!parsed.success){throw new MalformedPackageIntelligenceResponseError("Malformed response from the package-intelligence service.")}if(parsed.data.errors&&parsed.data.errors.length>0){throw promoteGenericVersionNotFound(this.createGraphQLError(parsed.data.errors),{registry:params.registry,packageName:directIdentity.name,version:directIdentity.version})}const data=parsed.data.data?.packageDependencies;if(!data){throw new MalformedPackageIntelligenceResponseError("Empty response from the package-intelligence service.")}const packageIdentity=data.package;if(packageIdentity?.name!==directIdentity.name||packageIdentity.registry!==directIdentity.registry||packageIdentity.version!==directIdentity.version){throw new MalformedPackageIntelligenceResponseError("Transitive vulnerability audit response package identity differs from the direct report.")}const summary=data.dependencies?.transitive?.vulnerabilitySummary;if(!summary){throw new MalformedPackageIntelligenceResponseError("Transitive vulnerability audit response missing vulnerability summary.")}return this.normaliseTransitiveVulnerabilityAudit(summary,advisoryScope)}normaliseTransitiveVulnerabilityAudit(summary,advisoryScope){const packages=summary.packages.filter((pkg)=>pkg.selectedCount>0).map((pkg)=>{const occurrences=pkg.advisoryOccurrences??[];if(occurrences.length!==pkg.selectedCount){throw new MalformedPackageIntelligenceResponseError("Transitive vulnerability audit package occurrence count differs from selected count.")}return{registry:pkg.registry,name:pkg.name,occurrenceCount:pkg.selectedCount,occurrences:occurrences.map((occurrence)=>{const isAffected=occurrence.affectsResolvedVersion;if(advisoryScope==="AFFECTED"&&!isAffected||advisoryScope==="NON_AFFECTING"&&isAffected){throw new MalformedPackageIntelligenceResponseError("Transitive vulnerability audit occurrence differs from the requested scope.")}const hasMatchedAffectedRange=occurrence.matchedAffectedVersionRanges.length>0;if(isAffected!==hasMatchedAffectedRange){throw new MalformedPackageIntelligenceResponseError("Transitive vulnerability audit occurrence has inconsistent affectedness proof.")}const hasHigherFixes=occurrence.fixVersionsAboveResolved.length>0;const nearestFixedVersion=occurrence.nearestFixedVersion??undefined;const hasNearestFix=nearestFixedVersion!==undefined;if(!isAffected&&(hasHigherFixes||hasNearestFix)||hasHigherFixes!==hasNearestFix||hasNearestFix&&!occurrence.fixVersionsAboveResolved.includes(nearestFixedVersion)){throw new MalformedPackageIntelligenceResponseError("Transitive vulnerability audit fix metadata is inconsistent.")}return{version:occurrence.version,affectsResolvedVersion:occurrence.affectsResolvedVersion,matchedAffectedVersionRanges:occurrence.matchedAffectedVersionRanges,fixVersionsAboveResolved:occurrence.fixVersionsAboveResolved,nearestFixedVersion,advisory:this.normaliseTransitiveAuditAdvisory(occurrence.advisory)}})}});const normalisedOccurrenceCount=packages.reduce((total,pkg)=>total+pkg.occurrences.length,0);const occurrenceCount=summary.selected.totalVulnerabilities;if(normalisedOccurrenceCount!==occurrenceCount){throw new MalformedPackageIntelligenceResponseError("Transitive vulnerability audit occurrence count differs from selected total.")}return{advisoryScope,totalPackagesAnalyzed:summary.totalPackagesAnalyzed,packageCount:packages.length,occurrenceCount,calculatedAt:summary.calculatedAt??undefined,packages}}async packageDependencies(params){return withServiceDiagnostics(this.runtime.diagnostics,"pkg-intel.dependencies.request",()=>executeWithTokenRefresh({getToken:()=>this.tokenProvider.getToken(),forceRefresh:()=>this.tokenProvider.forceRefresh(),shouldRefresh:isTokenRefreshableError,executeWithToken:(token)=>this.executePackageDependencies(token,params)}))}async packageUpgradeDependencyProbe(params){return withServiceDiagnostics(this.runtime.diagnostics,"pkg-intel.upgrade-dependency-probe.request",()=>executeWithTokenRefresh({getToken:()=>this.tokenProvider.getToken(),forceRefresh:()=>this.tokenProvider.forceRefresh(),shouldRefresh:isTokenRefreshableError,executeWithToken:(token)=>this.executePackageUpgradeDependencyProbe(token,params)}))}async packageUpgradeReview(params){return withServiceDiagnostics(this.runtime.diagnostics,"pkg-intel.upgrade-review.request",()=>executeWithTokenRefresh({getToken:()=>this.tokenProvider.getToken(),forceRefresh:()=>this.tokenProvider.forceRefresh(),shouldRefresh:isTokenRefreshableError,executeWithToken:(token)=>this.executePackageUpgradeReview(token,params)}))}async executePackageUpgradeReview(token,params){let response;try{response=await postPkgseerGraphql({endpointUrl:this.endpointUrl,token,query:PACKAGE_UPGRADE_REVIEW_QUERY,variables:{packages:params.packages,includeTransitiveSecurity:params.includeTransitiveSecurity,includeDependencyIssues:params.includeDependencyIssues,minSeverity:params.minSeverity,changelogLimit:params.changelogLimit},fetchFn:this.fetchFn,clientHeaders:this.runtime.clientHeaders,userAgent:this.runtime.userAgent,diagnostics:this.runtime.diagnostics})}catch(cause){if(cause instanceof PkgseerTransportError){throw this.createTransportError(cause)}throw cause}if(response.status<200||response.status>=300){throw this.createHttpError(response)}const parsed=packageUpgradeReviewGraphQLResponseSchema.safeParse(response.parsedBody);if(!parsed.success){throw new MalformedPackageIntelligenceResponseError("Malformed response from the package-intelligence service.")}if(parsed.data.errors&&parsed.data.errors.length>0){throw this.createGraphQLError(parsed.data.errors)}const data=parsed.data.data?.packageUpgradeReview;if(!data){throw new MalformedPackageIntelligenceResponseError("Empty response from the package-intelligence service.")}return stripNullProperties(data)}async executePackageUpgradeDependencyProbe(token,params){const includeTransitiveRisk=params.includeTransitiveSecurity===true||params.includeDependencyIssues===true||params.includeDependencyChanges===true;let response;try{response=await postPkgseerGraphql({endpointUrl:this.endpointUrl,token,query:PACKAGE_UPGRADE_DEPENDENCY_PROBE_QUERY,variables:{registry:params.registry,name:params.packageName,version:params.version,includeTransitiveRisk,includeTransitiveSecurity:params.includeTransitiveSecurity===true,includeDependencyIssues:params.includeDependencyIssues===true,includeDependencyChanges:params.includeDependencyChanges===true,includeGroups:params.includeGroups===true,lifecycle:params.includeGroups===true?["peer"]:undefined,minSeverity:params.minSeverity},fetchFn:this.fetchFn,clientHeaders:this.runtime.clientHeaders,userAgent:this.runtime.userAgent,diagnostics:this.runtime.diagnostics})}catch(cause){if(cause instanceof PkgseerTransportError){throw this.createTransportError(cause)}throw cause}if(response.status<200||response.status>=300){throw this.createHttpError(response)}const parsed=dependenciesGraphQLResponseSchema.safeParse(response.parsedBody);if(!parsed.success){throw new MalformedPackageIntelligenceResponseError("Malformed response from the package-intelligence service.")}if(parsed.data.errors&&parsed.data.errors.length>0){throw promoteGenericVersionNotFound(this.createGraphQLError(parsed.data.errors),params)}const data=parsed.data.data?.packageDependencies;if(!data){throw new MalformedPackageIntelligenceResponseError("Empty response from the package-intelligence service.")}return this.normaliseDependencyReport(data)}async executePackageDependencies(token,params){let response;try{response=await postPkgseerGraphql({endpointUrl:this.endpointUrl,token,query:PACKAGE_DEPENDENCIES_QUERY,variables:{registry:params.registry,name:params.packageName,version:params.version,includeTransitive:params.includeDependencyIssues===true?true:params.includeTransitive,includeTransitiveDetails:params.includeTransitiveDetails!==false,includeDependencyGraph:params.includeTransitive===true||params.includeDependencyIssues===true,includeDependencyIssues:params.includeDependencyIssues===true,includeGroups:params.includeGroups!==false,maxDepth:params.maxDepth,lifecycle:params.lifecycle&&params.lifecycle.length>0?params.lifecycle:undefined},fetchFn:this.fetchFn,clientHeaders:this.runtime.clientHeaders,userAgent:this.runtime.userAgent,diagnostics:this.runtime.diagnostics})}catch(cause){if(cause instanceof PkgseerTransportError){throw this.createTransportError(cause)}throw cause}if(response.status<200||response.status>=300){throw this.createHttpError(response)}const parsed=dependenciesGraphQLResponseSchema.safeParse(response.parsedBody);if(!parsed.success){throw new MalformedPackageIntelligenceResponseError("Malformed response from the package-intelligence service.")}if(parsed.data.errors&&parsed.data.errors.length>0){throw promoteGenericVersionNotFound(this.createGraphQLError(parsed.data.errors),params)}const data=parsed.data.data?.packageDependencies;if(!data){throw new MalformedPackageIntelligenceResponseError("Empty response from the package-intelligence service.")}const report=this.normaliseDependencyReport(data);if(params.includeDependencyIssues===true){const transitive=report.dependencies?.transitive;if(!transitive?.dependencyIssues){throw new MalformedPackageIntelligenceResponseError("Dependency issue analysis response missing dependency issues.")}if(!transitive.dependencyGraph){throw new MalformedPackageIntelligenceResponseError("Dependency issue analysis response missing dependency graph.")}}if(params.includeTransitive===true){const transitive=report.dependencies?.transitive;const hasConflictEdges=transitive?.dependencyConflicts?.some((conflict)=>conflict.conflictingEdges.length>0);if(hasConflictEdges&&!transitive?.dependencyGraph){throw new MalformedPackageIntelligenceResponseError("Transitive dependency conflict edges response missing dependency graph.")}}return report}normaliseDependencyReport(data){const name=data.package?.name??undefined;const version=data.package?.version??undefined;if(!name||!version){throw new MalformedPackageIntelligenceResponseError("Package dependencies response missing required name/version.")}const identity={name,version,registry:data.package?.registry??undefined,publishedAt:data.package?.publishedAt??undefined,deprecated:data.package?.deprecated??undefined,deprecationReason:data.package?.deprecationReason??undefined};const bundle=data.dependencies;const dependencies=bundle?{direct:bundle.direct?.map((entry)=>{if(!entry.name){throw new MalformedPackageIntelligenceResponseError("Dependency entry missing required name.")}return{name:entry.name,versionConstraint:entry.versionConstraint??undefined,type:entry.type??undefined}})??undefined,transitive:bundle.transitive?{totalEdges:bundle.transitive.totalEdges??undefined,uniquePackagesCount:bundle.transitive.uniquePackagesCount??undefined,uniqueDependencies:bundle.transitive.uniqueDependencies??undefined,dependencyConflicts:bundle.transitive.dependencyConflicts?.map((c)=>({packageName:c.packageName,requiredVersions:c.requiredVersions,conflictingEdges:c.conflictingEdges.map((edge)=>({fromIndex:edge.fromIndex??undefined,toIndex:edge.toIndex,versionConstraint:edge.versionConstraint,dependencyType:edge.dependencyType}))}))??undefined,circularDependencyCycles:bundle.transitive.circularDependencyCycles?.map((cycle)=>({cycleStart:cycle.cycleStart,circularPath:cycle.circularPath,displayChain:cycle.displayChain}))??undefined,dependencyGraph:bundle.transitive.dependencyGraph?{formatVersion:bundle.transitive.dependencyGraph.formatVersion,nodes:bundle.transitive.dependencyGraph.nodes.map((n)=>({registry:n.registry,name:n.name,version:n.version??undefined})),edges:bundle.transitive.dependencyGraph.edges.map((e)=>({fromIndex:e.fromIndex??undefined,toIndex:e.toIndex,constraint:e.constraint??undefined,dependencyType:e.dependencyType??undefined}))}:undefined,vulnerabilitySummary:this.normaliseTransitiveVulnerabilitySummary(bundle.transitive.vulnerabilitySummary),dependencyIssues:this.normaliseDependencyIssuesSummary(bundle.transitive.dependencyIssues)}:undefined}:undefined;const dependencyGroups=data.dependencyGroups?{primaryGroup:data.dependencyGroups.primaryGroup??undefined,environmentMarkers:data.dependencyGroups.environmentMarkers?.map((m)=>({type:m.type??undefined,value:m.value??undefined,raw:m.raw??undefined}))??undefined,groups:data.dependencyGroups.groups.map((group)=>({name:group.name,lifecycle:group.lifecycle,conditionType:group.conditionType,conditionValue:group.conditionValue??undefined,selectionMode:group.selectionMode,exclusiveGroup:group.exclusiveGroup??undefined,fallbackPriority:group.fallbackPriority??undefined,compatibleWith:group.compatibleWith??undefined,defaultEnabled:group.defaultEnabled??undefined,dependencies:group.dependencies.map((entry)=>({name:entry.name,constraint:entry.constraint??undefined}))}))}:undefined;return{package:identity,dependencies,dependencyGroups}}normaliseTransitiveVulnerabilitySummary(summary){if(!summary)return;return{affected:summary.affected,nonAffecting:summary.nonAffecting,combined:summary.combined,totalPackagesAnalyzed:summary.totalPackagesAnalyzed,affectedPackageCount:summary.affectedPackageCount,calculatedAt:summary.calculatedAt??undefined,packages:summary.packages.map((pkg)=>({registry:pkg.registry,name:pkg.name,versions:pkg.versions,affectedCount:pkg.affectedCount,nonAffectingCount:pkg.nonAffectingCount,totalCount:pkg.totalCount,maxSeverityScore:pkg.maxSeverityScore??undefined,maxSeverityLabel:pkg.maxSeverityLabel??undefined,advisoryIds:pkg.advisoryIds,mostCritical:pkg.mostCritical?this.normaliseVulnerabilitySummaryDetail(pkg.mostCritical):undefined,advisoryOccurrences:pkg.advisoryOccurrences?.map((occurrence)=>({version:occurrence.version,affectsResolvedVersion:occurrence.affectsResolvedVersion,matchedAffectedVersionRanges:occurrence.matchedAffectedVersionRanges,fixVersionsAboveResolved:occurrence.fixVersionsAboveResolved,nearestFixedVersion:occurrence.nearestFixedVersion??undefined,advisory:this.normaliseVulnerabilitySummaryDetail(occurrence.advisory)}))??undefined}))}}normaliseVulnerabilitySummaryDetail(advisory){return{osvId:advisory.osvId??undefined,registry:advisory.registry??undefined,packageName:advisory.packageName??undefined,summary:advisory.summary??undefined,severityScore:advisory.severityScore??undefined,severityType:advisory.severityType??undefined,affectedVersionRanges:advisory.affectedVersionRanges??undefined,fixedInVersions:advisory.fixedInVersions??undefined,publishedAt:advisory.publishedAt??undefined,modifiedAt:advisory.modifiedAt??undefined,withdrawnAt:advisory.withdrawnAt??undefined,aliases:advisory.aliases??undefined,isMalicious:advisory.isMalicious??undefined}}normaliseTransitiveAuditAdvisory(advisory){return{osvId:advisory.osvId??undefined,summary:advisory.summary??undefined,severityScore:advisory.severityScore??undefined,affectedVersionRanges:advisory.affectedVersionRanges?.length?advisory.affectedVersionRanges:undefined,fixedInVersions:advisory.fixedInVersions?.length?advisory.fixedInVersions:undefined,publishedAt:advisory.publishedAt??undefined,modifiedAt:advisory.modifiedAt??undefined,aliases:advisory.aliases??undefined,isMalicious:advisory.isMalicious??undefined}}normaliseDependencyIssuesSummary(issues){if(!issues)return;return{totalCount:issues.totalCount,deprecatedCount:issues.deprecatedCount,outdatedCount:issues.outdatedCount,duplicateCount:issues.duplicateCount,conflictCount:issues.conflictCount,deprecatedPackages:issues.deprecatedPackages.map((pkg)=>({registry:pkg.registry,name:pkg.name,versions:pkg.versions,reasons:pkg.reasons.map((reason)=>({version:reason.version,reason:reason.reason??undefined}))})),outdatedPackages:issues.outdatedPackages.map((pkg)=>({registry:pkg.registry,name:pkg.name,latestVersion:pkg.latestVersion??undefined,severity:pkg.severity,versions:pkg.versions.map((version)=>({version:version.version,severity:version.severity})),repositoryUrl:pkg.repositoryUrl??undefined})),duplicatePackages:issues.duplicatePackages.map((pkg)=>({registry:pkg.registry??undefined,name:pkg.name,versions:pkg.versions})),conflicts:issues.conflicts.map((conflict)=>({registry:conflict.registry??undefined,name:conflict.name,versions:conflict.versions,requiredVersions:conflict.requiredVersions,conflictingEdges:conflict.conflictingEdges.map((edge)=>({fromIndex:edge.fromIndex??undefined,toIndex:edge.toIndex,versionConstraint:edge.versionConstraint,dependencyType:edge.dependencyType}))}))}}async packageChangelog(params){return withServiceDiagnostics(this.runtime.diagnostics,"pkg-intel.changelog.request",()=>executeWithTokenRefresh({getToken:()=>this.tokenProvider.getToken(),forceRefresh:()=>this.tokenProvider.forceRefresh(),shouldRefresh:isTokenRefreshableError,executeWithToken:(token)=>this.executePackageChangelog(token,params)}))}async executePackageChangelog(token,params){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,docsReadTarget:page.docsReadTarget,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,docsReadTarget:data.page.docsReadTarget,title:data.page.title??undefined,content:data.page.content??undefined,contentFormat:data.page.contentFormat??undefined,breadcrumbs:data.page.breadcrumbs??undefined,linkName:data.page.linkName??undefined,lastUpdatedAt:data.page.lastUpdatedAt??undefined,sourceKind:data.page.sourceKind??undefined,source:data.page.source?{url:data.page.source.url??undefined,label:data.page.source.label??undefined}:undefined,repoUrl:data.page.repoUrl??undefined,gitRef:data.page.gitRef??undefined,requestedRef:data.page.requestedRef??undefined,filePath:data.page.filePath??undefined,baseUrl:data.page.baseUrl??undefined}:undefined}}}function 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)}})}}import{z as z5}from"zod";var latestVersionMaliciousEvidenceSchema=z5.object({advisories:z5.array(z5.object({osvId:z5.string(),classificationReasons:z5.array(z5.string())})).max(5),totalCount:z5.number().int().nonnegative(),truncated:z5.boolean()}).nullable();var compactMatchSchema=z5.object({confidence:z5.string()});var candidateEvidenceSchema=z5.object({canonicalKey:z5.string(),nameSimilarity:z5.number().nullable()});var detailedMatchSchema=compactMatchSchema.extend({matchedAliases:z5.array(z5.string()),matchTier:z5.number().int(),score:z5.number()});var listTargetSchema=z5.object({kind:z5.string(),canonicalKey:z5.string(),latestVersionMaliciousStatus:z5.string(),latestVersionMaliciousEvidence:latestVersionMaliciousEvidenceSchema,description:z5.string().nullable().optional(),repositoryUrl:z5.string().nullable().optional(),stars:z5.number().int().nullable().optional(),downloadsLastMonth:z5.number().int().nullable().optional(),downloadsTotal:z5.number().int().nullable().optional(),docsAvailable:z5.boolean(),codeAvailable:z5.boolean(),groupKey:z5.string().nullable(),match:compactMatchSchema.nullable(),docsPageCount:z5.number().int().nullable(),codeFileCount:z5.number().int().nullable(),license:z5.string().nullable()});var targetReferenceSchema=z5.object({kind:z5.string(),canonicalKey:z5.string(),confidence:z5.string()});var detailedTargetSchema=listTargetSchema.omit({match:true}).extend({match:detailedMatchSchema.nullable(),displayName:z5.string(),registry:z5.string().nullable().optional(),packageName:z5.string().nullable().optional(),latestVersion:z5.string().nullable().optional(),repositoryOwner:z5.string().nullable().optional(),repositoryName:z5.string().nullable().optional(),documentationUrl:z5.string().nullable().optional()});var graphQLErrorSchema3=z5.object({message:z5.string(),extensions:z5.record(z5.string(),z5.unknown()).optional()});function responseSchema(targetSchema,includeNameSimilarity){const resultSchema=z5.object({best:targetReferenceSchema.nullable(),protectedMatches:z5.array(targetReferenceSchema),candidates:includeNameSimilarity?z5.array(candidateEvidenceSchema):z5.array(candidateEvidenceSchema).optional(),targets:z5.array(targetSchema),targetsTruncated:z5.boolean(),ambiguous:z5.boolean(),ambiguousReason:z5.string()});return z5.object({data:z5.object({resolveTarget:resultSchema.nullable()}).nullable().optional(),errors:z5.array(graphQLErrorSchema3).optional()})}var RESOLVE_TARGET_QUERY=`
1427
1508
  query ResolveTarget(
1428
1509
  $name: String!
1429
1510
  $query: String