githits 0.12.0 → 0.13.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.
@@ -0,0 +1,1852 @@
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=`
2
+ availableRefs {
3
+ version
4
+ ref
5
+ }`;var TARGET_RESOLUTION_SUGGESTED_REFS_SELECTION=`
6
+ suggestedRefs {
7
+ version
8
+ ref
9
+ }`;var DISCOVERY_TARGET_PROGRESS_SUGGESTED_REFS_SELECTION=`
10
+ suggestedRefs {
11
+ version
12
+ ref
13
+ }`;var DOC_COVERAGE_SELECTION=`
14
+ coverage {
15
+ coverageState
16
+ coverageReason
17
+ pagesCrawled
18
+ frontierRemaining
19
+ artifactOverflowPageCount
20
+ estimatedTotalPages
21
+ note
22
+ }`;var DOCUMENTATION_CONTRIBUTORS_SELECTION=`
23
+ contributors {
24
+ kind
25
+ state
26
+ freshness
27
+ resultCount
28
+ repositoryUrl
29
+ commitSha
30
+ siteKey
31
+ siteUrl
32
+ ${DOC_COVERAGE_SELECTION}
33
+ }`;var TARGET_RESOLUTION_SELECTION=`
34
+ targetResolution {
35
+ requested {
36
+ kind
37
+ registry
38
+ packageName
39
+ version
40
+ repoUrl
41
+ gitRef
42
+ commitSha
43
+ }
44
+ resolvedRequested {
45
+ kind
46
+ registry
47
+ packageName
48
+ version
49
+ repoUrl
50
+ gitRef
51
+ commitSha
52
+ }
53
+ served {
54
+ kind
55
+ registry
56
+ packageName
57
+ version
58
+ repoUrl
59
+ gitRef
60
+ commitSha
61
+ }
62
+ freshness
63
+ freshnessReason
64
+ indexingRef
65
+ availableVersions {
66
+ version
67
+ ref
68
+ }
69
+ ${TARGET_RESOLUTION_AVAILABLE_REFS_SELECTION}
70
+ ${TARGET_RESOLUTION_SUGGESTED_REFS_SELECTION}
71
+ }`;var CODE_CONTEXT_AVAILABLE_VERSIONS_SELECTION=`
72
+ availableVersions {
73
+ version
74
+ ref
75
+ }`;var DISCOVERY_TARGET_PROGRESS_RETRY_SELECTION=`
76
+ availableVersions {
77
+ version
78
+ ref
79
+ }
80
+ availableRefs {
81
+ version
82
+ ref
83
+ }
84
+ ${DISCOVERY_TARGET_PROGRESS_SUGGESTED_REFS_SELECTION}`;var INDEXING_DURATION_ESTIMATE_SELECTION=`
85
+ indexingEstimate {
86
+ lowerSeconds
87
+ upperSeconds
88
+ elapsedSeconds
89
+ sampleCount
90
+ source
91
+ }`;var UNIFIED_SEARCH_LOCATOR_SELECTION=`
92
+ registry
93
+ packageName
94
+ version
95
+ pageId
96
+ docsReadTarget
97
+ sourceKind
98
+ sourceUrl
99
+ repoUrl
100
+ gitRef
101
+ commitSha
102
+ requestedRef
103
+ filePath
104
+ repositoryFilePath
105
+ startLine
106
+ endLine
107
+ evidenceRange {
108
+ startLine
109
+ endLine
110
+ matchLine
111
+ rangeKind
112
+ matchSpansTruncated
113
+ }
114
+ indexedRange {
115
+ startLine
116
+ endLine
117
+ }
118
+ symbolContext {
119
+ name
120
+ qualifiedPath
121
+ kind
122
+ relation
123
+ definitionRange {
124
+ filePath
125
+ repositoryFilePath
126
+ startLine
127
+ endLine
128
+ }
129
+ }
130
+ fileContentHash
131
+ symbolRef
132
+ qualifiedPath
133
+ kind
134
+ category
135
+ language`;var UNIFIED_SEARCH_REPOSITORY_EVIDENCE_SELECTION=`
136
+ repositoryEvidence {
137
+ semanticContext {
138
+ scopes {
139
+ name
140
+ qualifiedPath
141
+ kind
142
+ parentQualifiedPath
143
+ declarationStartLine
144
+ declarationEndLine
145
+ parameterNames
146
+ returnType
147
+ symbolRef
148
+ }
149
+ scopeChainTruncated
150
+ preferredRead {
151
+ targetLabel
152
+ registry
153
+ packageName
154
+ version
155
+ repoUrl
156
+ gitRef
157
+ commitSha
158
+ requestedRef
159
+ filePath
160
+ repositoryFilePath
161
+ startLine
162
+ endLine
163
+ }
164
+ }
165
+ focusedSource {
166
+ startLine
167
+ endLine
168
+ matchLine
169
+ rangeKind
170
+ matchSpansTruncated
171
+ linesOmittedBefore
172
+ linesOmittedAfter
173
+ lines {
174
+ lineNumber
175
+ text
176
+ highlights
177
+ prefixTruncated
178
+ suffixTruncated
179
+ }
180
+ }
181
+ }
182
+ contentSafety {
183
+ filtered
184
+ modifications
185
+ }`;var UNIFIED_SEARCH_QUERY=`
186
+ query UnifiedSearch(
187
+ $targets: [SearchPackageInput!]!
188
+ $query: String!
189
+ $sources: [DiscoverySearchSource!]
190
+ $filters: DiscoverySearchFiltersInput
191
+ $allowPartialResults: Boolean
192
+ $limit: Int
193
+ $offset: Int
194
+ $waitTimeoutMs: Int
195
+ ) {
196
+ search(
197
+ targets: $targets
198
+ query: $query
199
+ sources: $sources
200
+ filters: $filters
201
+ allowPartialResults: $allowPartialResults
202
+ limit: $limit
203
+ offset: $offset
204
+ waitTimeoutMs: $waitTimeoutMs
205
+ ) {
206
+ completed
207
+ searchRef
208
+ result {
209
+ query
210
+ queryWarnings
211
+ sources
212
+ results {
213
+ id
214
+ resultType
215
+ targetLabel
216
+ requestedTargetLabel
217
+ freshTargetLabel
218
+ servedTargetLabel
219
+ freshness
220
+ title
221
+ summary
222
+ score
223
+ highlights {
224
+ title
225
+ summary
226
+ }
227
+ ${UNIFIED_SEARCH_REPOSITORY_EVIDENCE_SELECTION}
228
+ locator {
229
+ ${UNIFIED_SEARCH_LOCATOR_SELECTION}
230
+ }
231
+ }
232
+ page {
233
+ offset
234
+ limit
235
+ returned
236
+ hasMore
237
+ }
238
+ partialResults
239
+ evidenceNotice
240
+ sourceStatus {
241
+ source
242
+ targetLabel
243
+ requestedTargetLabel
244
+ freshTargetLabel
245
+ servedTargetLabel
246
+ ${TARGET_RESOLUTION_SELECTION}
247
+ indexingStatus
248
+ codeIndexState
249
+ resultCount
250
+ appliedFilters
251
+ ignoredFilters
252
+ incompatibleFilters
253
+ appliedQueryFeatures
254
+ ignoredQueryFeatures
255
+ incompatibleQueryFeatures
256
+ suggestedSiteTargets
257
+ suggestedSiteTargetsTruncated
258
+ note
259
+ ${DOC_COVERAGE_SELECTION}
260
+ ${DOCUMENTATION_CONTRIBUTORS_SELECTION}
261
+ }
262
+ }
263
+ progress {
264
+ searchRef
265
+ status
266
+ targetsTotal
267
+ targetsReady
268
+ elapsedMs
269
+ query
270
+ queryWarnings
271
+ sources
272
+ requestedSources
273
+ targetMode
274
+ requestedTargets {
275
+ registry
276
+ name
277
+ version
278
+ repoUrl
279
+ gitRef
280
+ site
281
+ }
282
+ filters {
283
+ fileIntent
284
+ kind
285
+ category
286
+ publicOnly
287
+ pathPrefix
288
+ }
289
+ limit
290
+ offset
291
+ targets {
292
+ requested
293
+ resolvedRequested
294
+ served
295
+ freshness
296
+ indexingRef
297
+ requestedRefKind
298
+ ${TARGET_RESOLUTION_SELECTION}
299
+ ${DISCOVERY_TARGET_PROGRESS_RETRY_SELECTION}
300
+ ${DOC_COVERAGE_SELECTION}
301
+ }
302
+ expiresAt
303
+ }
304
+ }
305
+ }`;var UNIFIED_SEARCH_STATUS_QUERY=`
306
+ query UnifiedSearchStatus($searchRef: String!, $includeResults: Boolean!, $waitTimeoutMs: Int) {
307
+ discoverySearchProgress(searchRef: $searchRef, includeResults: $includeResults, waitTimeoutMs: $waitTimeoutMs) {
308
+ searchRef
309
+ status
310
+ targetsTotal
311
+ targetsReady
312
+ elapsedMs
313
+ query
314
+ queryWarnings
315
+ sources
316
+ requestedSources
317
+ targetMode
318
+ requestedTargets {
319
+ registry
320
+ name
321
+ version
322
+ repoUrl
323
+ gitRef
324
+ site
325
+ }
326
+ filters {
327
+ fileIntent
328
+ kind
329
+ category
330
+ publicOnly
331
+ pathPrefix
332
+ }
333
+ limit
334
+ offset
335
+ targets {
336
+ requested
337
+ resolvedRequested
338
+ served
339
+ freshness
340
+ indexingRef
341
+ requestedRefKind
342
+ ${TARGET_RESOLUTION_SELECTION}
343
+ ${DISCOVERY_TARGET_PROGRESS_RETRY_SELECTION}
344
+ ${DOC_COVERAGE_SELECTION}
345
+ }
346
+ expiresAt
347
+ results {
348
+ query
349
+ queryWarnings
350
+ sources
351
+ results {
352
+ id
353
+ resultType
354
+ targetLabel
355
+ requestedTargetLabel
356
+ freshTargetLabel
357
+ servedTargetLabel
358
+ freshness
359
+ title
360
+ summary
361
+ score
362
+ highlights {
363
+ title
364
+ summary
365
+ }
366
+ ${UNIFIED_SEARCH_REPOSITORY_EVIDENCE_SELECTION}
367
+ locator {
368
+ ${UNIFIED_SEARCH_LOCATOR_SELECTION}
369
+ }
370
+ }
371
+ page {
372
+ offset
373
+ limit
374
+ returned
375
+ hasMore
376
+ }
377
+ partialResults
378
+ evidenceNotice
379
+ sourceStatus {
380
+ source
381
+ targetLabel
382
+ requestedTargetLabel
383
+ freshTargetLabel
384
+ servedTargetLabel
385
+ ${TARGET_RESOLUTION_SELECTION}
386
+ indexingStatus
387
+ codeIndexState
388
+ resultCount
389
+ appliedFilters
390
+ ignoredFilters
391
+ incompatibleFilters
392
+ appliedQueryFeatures
393
+ ignoredQueryFeatures
394
+ incompatibleQueryFeatures
395
+ suggestedSiteTargets
396
+ suggestedSiteTargetsTruncated
397
+ note
398
+ ${DOC_COVERAGE_SELECTION}
399
+ ${DOCUMENTATION_CONTRIBUTORS_SELECTION}
400
+ }
401
+ }
402
+ }
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 {
404
+ registry
405
+ name
406
+ repoUrl
407
+ }
408
+ fromResolution {
409
+ requested
410
+ resolvedVersion
411
+ ref
412
+ commitSha
413
+ refKind
414
+ versionSource
415
+ }
416
+ toResolution {
417
+ requested
418
+ resolvedVersion
419
+ ref
420
+ commitSha
421
+ refKind
422
+ versionSource
423
+ }
424
+ raw {
425
+ summary {
426
+ filesChanged
427
+ added
428
+ deleted
429
+ modified
430
+ modeChanged
431
+ typeChanged
432
+ inventoryComplete
433
+ unprojectableFiles
434
+ }
435
+ scope {
436
+ status
437
+ fromSubpath
438
+ toSubpath
439
+ pathPrefix
440
+ pathGlob
441
+ }
442
+ contentCoverage
443
+ contentFailure {
444
+ code
445
+ retryable
446
+ retryAfterMs
447
+ stage
448
+ limitKind
449
+ }
450
+ files {
451
+ path
452
+ pathEncoding
453
+ status
454
+ modeChanged
455
+ typeChanged
456
+ contentStatus
457
+ contentSafety {
458
+ filtered
459
+ modifications
460
+ }`;function buildCodeDiffQuery(mode){const contentFields=mode==="inventory"?"":mode==="stats"?`
461
+ additions
462
+ deletions`:`
463
+ additions
464
+ deletions
465
+ patch
466
+ contentOmissionReason`;return`
467
+ query CodeDiff(
468
+ $registry: Registry
469
+ $name: String
470
+ $fromVersion: String
471
+ $toVersion: String
472
+ $repoUrl: String
473
+ $fromRef: String
474
+ $toRef: String
475
+ $rawOptions: RawCodeDiffOptions
476
+ ) {
477
+ codeDiff(
478
+ registry: $registry
479
+ name: $name
480
+ fromVersion: $fromVersion
481
+ toVersion: $toVersion
482
+ repoUrl: $repoUrl
483
+ fromRef: $fromRef
484
+ toRef: $toRef
485
+ rawOptions: $rawOptions
486
+ ) {
487
+ ${CODE_DIFF_COMMON_SELECTION}${contentFields}
488
+ }
489
+ hasMoreFiles
490
+ }
491
+ }
492
+ }`}var navigationResolutionSchema=z3.object({requestedVersion:z3.string().nullable().optional(),requestedRef:z3.string().nullable().optional(),resolvedRef:z3.string().nullable().optional(),commitSha:z3.string().nullable().optional()}).nullable().optional();var navigationDiagnosticsSchema=z3.object({hint:z3.string().nullable().optional()}).nullable().optional();var repoFileEntrySchema=z3.object({path:z3.string(),name:z3.string().nullable().optional(),language:z3.string().nullable().optional(),fileType:z3.string().nullable().optional(),byteSize:z3.number().int().nullable().optional()});var listRepoFilesResponseSchema=z3.object({files:z3.array(repoFileEntrySchema),total:z3.number().int(),hasMore:z3.boolean(),indexedVersion:z3.string().nullable().optional(),resolution:navigationResolutionSchema,targetResolution:targetResolutionSchema,diagnostics:navigationDiagnosticsSchema,codeIndexState:z3.string(),indexingRef:z3.string().nullable().optional(),availableVersions:z3.array(availableVersionSchema).nullable().optional(),indexingEstimate:indexingDurationEstimateSchema});var listRepoFilesGraphQLResponseSchema=z3.object({data:z3.object({listRepoFiles:listRepoFilesResponseSchema.nullable().optional()}).nullable().optional(),errors:z3.array(graphQLErrorSchema).optional()});var LIST_REPO_FILES_QUERY=`
493
+ query ListRepoFiles(
494
+ $registry: Registry
495
+ $packageName: String
496
+ $repoUrl: String
497
+ $gitRef: String
498
+ $version: String
499
+ $pathPrefix: String
500
+ $pathSelectors: [FilePathSelectorInput!]
501
+ $extensions: [String!]
502
+ $fileTypes: [String!]
503
+ $languages: [String!]
504
+ $fileIntent: FileIntent
505
+ $fileIntents: [FileIntent!]
506
+ $excludeFileIntents: [FileIntent!]
507
+ $excludeDocFiles: Boolean
508
+ $excludeTestFiles: Boolean
509
+ $includeHidden: Boolean
510
+ $limit: Int
511
+ $waitTimeoutMs: Int
512
+ ) {
513
+ listRepoFiles(
514
+ registry: $registry
515
+ packageName: $packageName
516
+ repoUrl: $repoUrl
517
+ gitRef: $gitRef
518
+ version: $version
519
+ pathPrefix: $pathPrefix
520
+ pathSelectors: $pathSelectors
521
+ extensions: $extensions
522
+ fileTypes: $fileTypes
523
+ languages: $languages
524
+ fileIntent: $fileIntent
525
+ fileIntents: $fileIntents
526
+ excludeFileIntents: $excludeFileIntents
527
+ excludeDocFiles: $excludeDocFiles
528
+ excludeTestFiles: $excludeTestFiles
529
+ includeHidden: $includeHidden
530
+ limit: $limit
531
+ waitTimeoutMs: $waitTimeoutMs
532
+ ) {
533
+ files {
534
+ path
535
+ name
536
+ language
537
+ fileType
538
+ byteSize
539
+ }
540
+ total
541
+ hasMore
542
+ indexedVersion
543
+ resolution {
544
+ requestedVersion
545
+ requestedRef
546
+ resolvedRef
547
+ commitSha
548
+ }
549
+ ${TARGET_RESOLUTION_SELECTION}
550
+ diagnostics {
551
+ hint
552
+ }
553
+ codeIndexState
554
+ indexingRef
555
+ availableVersions {
556
+ version
557
+ ref
558
+ }
559
+ ${INDEXING_DURATION_ESTIMATE_SELECTION}
560
+ }
561
+ }`;var codeContextResponseSchema=z3.object({content:z3.string().nullable().optional(),filePath:z3.string().nullable().optional(),language:z3.string().nullable().optional(),totalLines:z3.number().int().nullable().optional(),startLine:z3.number().int().nullable().optional(),endLine:z3.number().int().nullable().optional(),repoUrl:z3.string().nullable().optional(),gitRef:z3.string().nullable().optional(),isBinary:z3.boolean().nullable().optional(),codeIndexState:z3.string(),indexingRef:z3.string().nullable().optional(),availableVersions:z3.array(availableVersionSchema).nullable().optional(),indexingEstimate:indexingDurationEstimateSchema,targetResolution:targetResolutionSchema});var fetchCodeContextGraphQLResponseSchema=z3.object({data:z3.object({fetchCodeContext:codeContextResponseSchema.nullable().optional()}).nullable().optional(),errors:z3.array(graphQLErrorSchema).optional()});var FETCH_CODE_CONTEXT_QUERY=`
562
+ query FetchCodeContext(
563
+ $registry: Registry
564
+ $packageName: String
565
+ $repoUrl: String
566
+ $gitRef: String
567
+ $version: String
568
+ $filePath: String!
569
+ $startLine: Int
570
+ $endLine: Int
571
+ $waitTimeoutMs: Int
572
+ ) {
573
+ fetchCodeContext(
574
+ registry: $registry
575
+ packageName: $packageName
576
+ repoUrl: $repoUrl
577
+ gitRef: $gitRef
578
+ version: $version
579
+ filePath: $filePath
580
+ startLine: $startLine
581
+ endLine: $endLine
582
+ waitTimeoutMs: $waitTimeoutMs
583
+ ) {
584
+ content
585
+ filePath
586
+ language
587
+ totalLines
588
+ startLine
589
+ endLine
590
+ repoUrl
591
+ gitRef
592
+ isBinary
593
+ codeIndexState
594
+ indexingRef
595
+ ${CODE_CONTEXT_AVAILABLE_VERSIONS_SELECTION}
596
+ ${INDEXING_DURATION_ESTIMATE_SELECTION}
597
+ ${TARGET_RESOLUTION_SELECTION}
598
+ }
599
+ }`;var grepRepoMatchSchema=z3.object({filePath:z3.string(),line:z3.number().int(),matchStartByte:z3.number().int(),matchEndByte:z3.number().int(),lineContent:z3.string(),contextBefore:z3.array(z3.string()).nullable().optional(),contextAfter:z3.array(z3.string()).nullable().optional(),fileContentHash:z3.string().nullable().optional(),fileIntent:z3.string().nullable().optional(),symbolRowId:z3.string().nullable().optional(),symbol:z3.object({symbolRef:z3.string().optional(),name:z3.string().optional(),qualifiedPath:z3.string().nullable().optional(),kind:z3.string().nullable().optional(),category:z3.string().nullable().optional(),arity:z3.number().int().nullable().optional(),isPublic:z3.boolean().nullable().optional(),filePath:z3.string().nullable().optional(),startLine:z3.number().int().nullable().optional(),endLine:z3.number().int().nullable().optional(),contentHash:z3.string().nullable().optional(),parentPath:z3.string().nullable().optional()}).nullable().optional()});var grepRepoResponseSchema=z3.object({matches:z3.array(grepRepoMatchSchema),nextCursor:z3.string().nullable().optional(),hasMore:z3.boolean(),truncatedReason:z3.enum(["NONE","MAX_MATCHES","MAX_MATCHES_PER_FILE","DEADLINE"]),routeTaken:z3.enum(["SINGLE_FILE","CONTENT_INDEX"]).nullable().optional(),filesScanned:z3.number().int(),filesInScope:z3.number().int(),binaryFilesSkipped:z3.number().int(),filesTooLargeSkipped:z3.number().int(),totalMatches:z3.number().int(),uniqueFilesMatched:z3.number().int(),indexedVersion:z3.string().nullable().optional(),resolution:navigationResolutionSchema,targetResolution:targetResolutionSchema,codeIndexState:z3.string(),indexingRef:z3.string().nullable().optional(),availableVersions:z3.array(availableVersionSchema).nullable().optional(),indexingEstimate:indexingDurationEstimateSchema});var grepRepoGraphQLResponseSchema=z3.object({data:z3.object({grepRepo:grepRepoResponseSchema.nullable().optional()}).nullable().optional(),errors:z3.array(graphQLErrorSchema).optional()});var GREP_REPO_SYMBOL_SELECTIONS={symbol_ref:"symbolRef",name:"name",qualified_path:"qualifiedPath",kind:"kind",category:"category",arity:"arity",is_public:"isPublic",file_path:"filePath",start_line:"startLine",end_line:"endLine",content_hash:"contentHash",parent_path:"parentPath"};function buildGrepRepoQuery(symbolFields){const symbolSelection=(symbolFields??[]).map((field)=>GREP_REPO_SYMBOL_SELECTIONS[field]).filter((field)=>Boolean(field)).filter((field,index,fields)=>fields.indexOf(field)===index).join(`
600
+ `);const symbolBlock=symbolSelection.length>0?`
601
+ symbol {
602
+ ${symbolSelection}
603
+ }`:"";return`
604
+ query GrepRepo(
605
+ $registry: Registry
606
+ $packageName: String
607
+ $repoUrl: String
608
+ $gitRef: String
609
+ $version: String
610
+ $waitTimeoutMs: Int
611
+ $pattern: String!
612
+ $patternType: GrepPatternType
613
+ $caseSensitive: Boolean
614
+ $pathSelectors: [GrepPathSelectorInput!]
615
+ $extensions: [String!]
616
+ $excludeDocFiles: Boolean
617
+ $excludeTestFiles: Boolean
618
+ $allowUnscoped: Boolean
619
+ $contextLinesBefore: Int
620
+ $contextLinesAfter: Int
621
+ $maxMatches: Int
622
+ $maxMatchesPerFile: Int
623
+ $cursor: String
624
+ $symbolFields: [String!]
625
+ ) {
626
+ grepRepo(
627
+ registry: $registry
628
+ packageName: $packageName
629
+ repoUrl: $repoUrl
630
+ gitRef: $gitRef
631
+ version: $version
632
+ waitTimeoutMs: $waitTimeoutMs
633
+ pattern: $pattern
634
+ patternType: $patternType
635
+ caseSensitive: $caseSensitive
636
+ pathSelectors: $pathSelectors
637
+ extensions: $extensions
638
+ excludeDocFiles: $excludeDocFiles
639
+ excludeTestFiles: $excludeTestFiles
640
+ allowUnscoped: $allowUnscoped
641
+ contextLinesBefore: $contextLinesBefore
642
+ contextLinesAfter: $contextLinesAfter
643
+ maxMatches: $maxMatches
644
+ maxMatchesPerFile: $maxMatchesPerFile
645
+ cursor: $cursor
646
+ symbolFields: $symbolFields
647
+ ) {
648
+ matches {
649
+ filePath
650
+ line
651
+ matchStartByte
652
+ matchEndByte
653
+ lineContent
654
+ contextBefore
655
+ contextAfter
656
+ fileContentHash
657
+ fileIntent
658
+ symbolRowId${symbolBlock}
659
+ }
660
+ nextCursor
661
+ totalMatches
662
+ hasMore
663
+ truncatedReason
664
+ routeTaken
665
+ filesScanned
666
+ filesInScope
667
+ binaryFilesSkipped
668
+ filesTooLargeSkipped
669
+ uniqueFilesMatched
670
+ indexedVersion
671
+ resolution {
672
+ requestedVersion
673
+ requestedRef
674
+ resolvedRef
675
+ commitSha
676
+ }
677
+ ${TARGET_RESOLUTION_SELECTION}
678
+ codeIndexState
679
+ indexingRef
680
+ availableVersions {
681
+ version
682
+ ref
683
+ }
684
+ ${INDEXING_DURATION_ESTIMATE_SELECTION}
685
+ }
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=`
687
+ query PackageSummary(
688
+ $registry: Registry!
689
+ $name: String!
690
+ $includeVerboseFields: Boolean! = true
691
+ ) {
692
+ packageSummary(registry: $registry, name: $name) {
693
+ package {
694
+ name
695
+ registry
696
+ description
697
+ latestVersion
698
+ latestVersionPublishedAt
699
+ homepage
700
+ repositoryUrl
701
+ license
702
+ downloadsLastMonth
703
+ downloadsTotal
704
+ versionCount @include(if: $includeVerboseFields)
705
+ downloadsRefreshedAt @include(if: $includeVerboseFields)
706
+ githubRepository {
707
+ stargazersCount
708
+ forksCount
709
+ openIssuesCount
710
+ archived
711
+ language @include(if: $includeVerboseFields)
712
+ topics @include(if: $includeVerboseFields)
713
+ pushedAt @include(if: $includeVerboseFields)
714
+ }
715
+ }
716
+ security {
717
+ vulnerabilityCount
718
+ allVulnerabilityCount
719
+ hasCurrentVulnerabilities
720
+ recentVulnerabilities @include(if: $includeVerboseFields) {
721
+ osvId
722
+ summary
723
+ severityScore
724
+ publishedAt
725
+ }
726
+ }
727
+ latestChangelogs(limit: 3) @include(if: $includeVerboseFields) {
728
+ version
729
+ publishedAt
730
+ body
731
+ }
732
+ }
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=`
734
+ query PackageVulnerabilities(
735
+ $registry: Registry!
736
+ $name: String!
737
+ $version: String
738
+ $minSeverity: Float
739
+ $includeWithdrawn: Boolean
740
+ $scope: VulnerabilityScope = AFFECTED
741
+ $after: String
742
+ ) {
743
+ packageVulnerabilities(
744
+ registry: $registry
745
+ name: $name
746
+ version: $version
747
+ minSeverity: $minSeverity
748
+ includeWithdrawn: $includeWithdrawn
749
+ ) {
750
+ package {
751
+ name
752
+ registry
753
+ version
754
+ }
755
+ security {
756
+ affectedVulnerabilityCount
757
+ nonAffectingVulnerabilityCount
758
+ allVulnerabilityCount
759
+ currentVersionAffected
760
+ upgradePaths
761
+ advisories(scope: $scope, first: 100, after: $after) {
762
+ entries {
763
+ osvId
764
+ summary
765
+ severityScore
766
+ severityType
767
+ affectedVersionRanges
768
+ affectedVersionRangesCount
769
+ affectedVersionRangesTruncated
770
+ fixedInVersions
771
+ publishedAt
772
+ modifiedAt
773
+ withdrawnAt
774
+ aliases
775
+ isMalicious
776
+ affectsInspectedVersion
777
+ matchedAffectedVersionRanges
778
+ duplicateIds
779
+ }
780
+ pageInfo {
781
+ hasNextPage
782
+ endCursor
783
+ totalCount
784
+ }
785
+ }
786
+ }
787
+ }
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=`
789
+ query PackageDependencies(
790
+ $registry: Registry!
791
+ $name: String!
792
+ $version: String
793
+ $includeTransitive: Boolean
794
+ $includeTransitiveDetails: Boolean! = true
795
+ $includeDependencyGraph: Boolean! = true
796
+ $includeGroups: Boolean! = true
797
+ $includeDependencyIssues: Boolean! = false
798
+ $maxDepth: Int
799
+ $lifecycle: [String!]
800
+ ) {
801
+ packageDependencies(
802
+ registry: $registry
803
+ name: $name
804
+ version: $version
805
+ includeTransitive: $includeTransitive
806
+ maxDepth: $maxDepth
807
+ lifecycle: $lifecycle
808
+ ) {
809
+ package {
810
+ name
811
+ registry
812
+ version
813
+ }
814
+ dependencies {
815
+ # Backend-side summary block intentionally not selected — our
816
+ # envelope computes runtime.count client-side from direct[].length
817
+ # so the invariant runtime.count === runtime.items.length always
818
+ # holds regardless of backend-side drift.
819
+ direct {
820
+ name
821
+ versionConstraint
822
+ type
823
+ }
824
+ transitive {
825
+ totalEdges @include(if: $includeTransitiveDetails)
826
+ uniquePackagesCount @include(if: $includeTransitiveDetails)
827
+ uniqueDependencies @include(if: $includeTransitiveDetails)
828
+ dependencyConflicts @include(if: $includeTransitiveDetails) {
829
+ packageName
830
+ requiredVersions
831
+ conflictingEdges {
832
+ fromIndex
833
+ toIndex
834
+ versionConstraint
835
+ dependencyType
836
+ }
837
+ }
838
+ circularDependencyCycles @include(if: $includeTransitiveDetails) {
839
+ cycleStart
840
+ circularPath
841
+ displayChain
842
+ }
843
+ dependencyGraph @include(if: $includeDependencyGraph) {
844
+ formatVersion
845
+ nodes {
846
+ registry
847
+ name
848
+ version
849
+ }
850
+ edges {
851
+ fromIndex
852
+ toIndex
853
+ constraint
854
+ dependencyType
855
+ }
856
+ }
857
+ dependencyIssues @include(if: $includeDependencyIssues) {
858
+ totalCount
859
+ deprecatedCount
860
+ outdatedCount
861
+ duplicateCount
862
+ conflictCount
863
+ deprecatedPackages {
864
+ registry
865
+ name
866
+ versions
867
+ reasons {
868
+ version
869
+ reason
870
+ }
871
+ }
872
+ outdatedPackages {
873
+ registry
874
+ name
875
+ latestVersion
876
+ severity
877
+ versions {
878
+ version
879
+ severity
880
+ }
881
+ repositoryUrl
882
+ }
883
+ duplicatePackages {
884
+ registry
885
+ name
886
+ versions
887
+ }
888
+ conflicts {
889
+ registry
890
+ name
891
+ versions
892
+ requiredVersions
893
+ conflictingEdges {
894
+ fromIndex
895
+ toIndex
896
+ versionConstraint
897
+ dependencyType
898
+ }
899
+ }
900
+ }
901
+ }
902
+ }
903
+ dependencyGroups @include(if: $includeGroups) {
904
+ primaryGroup
905
+ environmentMarkers {
906
+ type
907
+ value
908
+ raw
909
+ }
910
+ groups {
911
+ name
912
+ lifecycle
913
+ conditionType
914
+ conditionValue
915
+ selectionMode
916
+ exclusiveGroup
917
+ fallbackPriority
918
+ compatibleWith
919
+ defaultEnabled
920
+ dependencies {
921
+ name
922
+ constraint
923
+ }
924
+ }
925
+ }
926
+ }
927
+ }`;var PACKAGE_UPGRADE_DEPENDENCY_PROBE_QUERY=`
928
+ query PackageUpgradeDependencyProbe(
929
+ $registry: Registry!
930
+ $name: String!
931
+ $version: String!
932
+ $includeTransitiveRisk: Boolean!
933
+ $includeTransitiveSecurity: Boolean!
934
+ $includeDependencyIssues: Boolean!
935
+ $includeDependencyChanges: Boolean!
936
+ $includeGroups: Boolean!
937
+ $lifecycle: [String!]
938
+ $minSeverity: Float
939
+ ) {
940
+ packageDependencies(
941
+ registry: $registry
942
+ name: $name
943
+ version: $version
944
+ includeTransitive: $includeTransitiveRisk
945
+ lifecycle: $lifecycle
946
+ ) {
947
+ package {
948
+ name
949
+ registry
950
+ version
951
+ publishedAt
952
+ deprecated
953
+ deprecationReason
954
+ }
955
+ dependencies {
956
+ direct {
957
+ name
958
+ versionConstraint
959
+ type
960
+ }
961
+ transitive @include(if: $includeTransitiveRisk) {
962
+ dependencyGraph @include(if: $includeDependencyChanges) {
963
+ formatVersion
964
+ nodes {
965
+ registry
966
+ name
967
+ version
968
+ }
969
+ edges {
970
+ fromIndex
971
+ toIndex
972
+ constraint
973
+ dependencyType
974
+ }
975
+ }
976
+ vulnerabilitySummary(minSeverity: $minSeverity) @include(if: $includeTransitiveSecurity) {
977
+ affected {
978
+ totalVulnerabilities
979
+ critical
980
+ high
981
+ medium
982
+ low
983
+ unknown
984
+ }
985
+ nonAffecting {
986
+ totalVulnerabilities
987
+ critical
988
+ high
989
+ medium
990
+ low
991
+ unknown
992
+ }
993
+ combined {
994
+ totalVulnerabilities
995
+ critical
996
+ high
997
+ medium
998
+ low
999
+ unknown
1000
+ }
1001
+ totalPackagesAnalyzed
1002
+ affectedPackageCount
1003
+ calculatedAt
1004
+ packages {
1005
+ registry
1006
+ name
1007
+ versions
1008
+ affectedCount
1009
+ nonAffectingCount
1010
+ totalCount
1011
+ maxSeverityScore
1012
+ maxSeverityLabel
1013
+ advisoryIds(scope: AFFECTED)
1014
+ mostCritical {
1015
+ osvId
1016
+ registry
1017
+ packageName
1018
+ summary
1019
+ severityScore
1020
+ severityType
1021
+ affectedVersionRanges
1022
+ fixedInVersions
1023
+ publishedAt
1024
+ modifiedAt
1025
+ withdrawnAt
1026
+ aliases
1027
+ isMalicious
1028
+ }
1029
+ advisoryOccurrences(scope: AFFECTED, minSeverity: $minSeverity, limit: 5) {
1030
+ version
1031
+ affectsResolvedVersion
1032
+ matchedAffectedVersionRanges
1033
+ fixVersionsAboveResolved
1034
+ nearestFixedVersion
1035
+ advisory {
1036
+ osvId
1037
+ registry
1038
+ packageName
1039
+ summary
1040
+ severityScore
1041
+ severityType
1042
+ affectedVersionRanges
1043
+ fixedInVersions
1044
+ publishedAt
1045
+ modifiedAt
1046
+ withdrawnAt
1047
+ aliases
1048
+ isMalicious
1049
+ }
1050
+ }
1051
+ }
1052
+ }
1053
+ dependencyIssues @include(if: $includeDependencyIssues) {
1054
+ totalCount
1055
+ deprecatedCount
1056
+ outdatedCount
1057
+ duplicateCount
1058
+ conflictCount
1059
+ deprecatedPackages {
1060
+ registry
1061
+ name
1062
+ versions
1063
+ reasons {
1064
+ version
1065
+ reason
1066
+ }
1067
+ }
1068
+ outdatedPackages {
1069
+ registry
1070
+ name
1071
+ latestVersion
1072
+ severity
1073
+ versions {
1074
+ version
1075
+ severity
1076
+ }
1077
+ repositoryUrl
1078
+ }
1079
+ duplicatePackages {
1080
+ registry
1081
+ name
1082
+ versions
1083
+ }
1084
+ conflicts {
1085
+ registry
1086
+ name
1087
+ versions
1088
+ requiredVersions
1089
+ conflictingEdges {
1090
+ fromIndex
1091
+ toIndex
1092
+ versionConstraint
1093
+ dependencyType
1094
+ }
1095
+ }
1096
+ }
1097
+ }
1098
+ }
1099
+ dependencyGroups @include(if: $includeGroups) {
1100
+ primaryGroup
1101
+ environmentMarkers {
1102
+ type
1103
+ value
1104
+ raw
1105
+ }
1106
+ groups {
1107
+ name
1108
+ lifecycle
1109
+ conditionType
1110
+ conditionValue
1111
+ selectionMode
1112
+ exclusiveGroup
1113
+ fallbackPriority
1114
+ compatibleWith
1115
+ defaultEnabled
1116
+ dependencies {
1117
+ name
1118
+ constraint
1119
+ }
1120
+ }
1121
+ }
1122
+ }
1123
+ }`;var packageUpgradeAdvisorySchema=z4.object({id:z4.string().nullable().optional(),aliases:z4.array(z4.string()),summary:z4.string().nullable().optional(),severity:z4.number().nullable().optional(),severityLabel:z4.string().nullable().optional(),fixedIn:z4.array(z4.string()),isMalicious:z4.boolean().nullable().optional()});var packageUpgradeVersionVulnerabilitySummarySchema=z4.object({version:z4.string(),publishedAt:z4.string().nullable().optional(),deprecated:z4.boolean().nullable().optional(),deprecationReason:z4.string().nullable().optional(),affectedCount:z4.number().int(),nonAffectingCount:z4.number().int(),allCount:z4.number().int(),lastModifiedAt:z4.string().nullable().optional(),advisories:z4.array(packageUpgradeAdvisorySchema)}).nullable().optional();var packageUpgradeTransitivePackagePageSchema=z4.object({entries:z4.array(z4.object({id:z4.string(),registry:z4.string(),name:z4.string(),versions:z4.array(z4.string()),affectedCount:z4.number().int(),maxSeverityScore:z4.number().nullable().optional(),maxSeverityLabel:z4.string().nullable().optional(),advisoryIds:z4.array(z4.string())})),totalCount:z4.number().int(),truncated:z4.boolean()});var packageUpgradeTransitiveSecuritySchema=z4.object({currentAffected:z4.number().int(),targetAffected:z4.number().int(),introducedPackages:z4.array(z4.string()),fixedPackages:z4.array(z4.string()),introducedPackageDetails:packageUpgradeTransitivePackagePageSchema,fixedPackageDetails:packageUpgradeTransitivePackagePageSchema,stillAffectedPackageDetails:packageUpgradeTransitivePackagePageSchema}).nullable().optional();var packageUpgradeSecuritySchema=z4.object({current:packageUpgradeVersionVulnerabilitySummarySchema,target:packageUpgradeVersionVulnerabilitySummarySchema,added:z4.array(packageUpgradeAdvisorySchema),removed:z4.array(packageUpgradeAdvisorySchema),notAddressed:z4.array(packageUpgradeAdvisorySchema),fixed:z4.array(packageUpgradeAdvisorySchema),introduced:z4.array(packageUpgradeAdvisorySchema),unchanged:z4.array(packageUpgradeAdvisorySchema),transitive:packageUpgradeTransitiveSecuritySchema});var packageUpgradeChangelogEntrySchema=z4.object({version:z4.string().nullable().optional(),publishedAt:z4.string().nullable().optional(),htmlUrl:z4.string().nullable().optional(),body:z4.string().nullable().optional(),bodyPreview:z4.string().nullable().optional(),headline:z4.string().nullable().optional(),signals:z4.array(z4.string())});var packageUpgradeChangelogSchema=z4.object({source:z4.string().nullable().optional(),fallback:z4.string().nullable().optional(),entries:z4.array(packageUpgradeChangelogEntrySchema),sampledEntries:z4.array(packageUpgradeChangelogEntrySchema),keywordEntries:z4.array(packageUpgradeChangelogEntrySchema),totalKeywordEntries:z4.number().int(),totalEntries:z4.number().int(),totalEntriesWithBodies:z4.number().int(),truncated:z4.boolean(),hasReleaseNoteBodies:z4.boolean(),breakingSignals:z4.array(z4.string()),migrationSignals:z4.array(z4.string())});var packageUpgradeCompatibilitySchema=z4.object({peerDependencyChanges:z4.array(z4.string()),notes:z4.array(z4.string())}).nullable().optional();var packageUpgradeDependencyChangeItemSchema=z4.object({name:z4.string(),registry:z4.string().nullable().optional(),version:z4.string().nullable().optional(),fromVersions:z4.array(z4.string()),toVersions:z4.array(z4.string()),constraint:z4.string().nullable().optional(),type:z4.string().nullable().optional()});var packageUpgradeDependencyChangeGroupSchema=z4.object({added:z4.array(packageUpgradeDependencyChangeItemSchema),removed:z4.array(packageUpgradeDependencyChangeItemSchema),changed:z4.array(packageUpgradeDependencyChangeItemSchema)});var packageUpgradeDependencyChangesSchema=z4.object({direct:packageUpgradeDependencyChangeGroupSchema,transitive:packageUpgradeDependencyChangeGroupSchema}).nullable().optional();var packageUpgradeDependencyIssuesSchema=z4.object({currentTotal:z4.number().int(),targetTotal:z4.number().int(),introducedDeprecated:z4.array(z4.string()),introducedDuplicates:z4.array(z4.string()),introducedConflicts:z4.array(z4.string()),introducedOutdated:z4.array(z4.string())}).nullable().optional();var packageUpgradeReviewSchema=z4.object({registry:z4.string(),name:z4.string(),currentVersion:z4.string(),targetVersion:z4.string(),latestVersion:z4.string().nullable().optional(),versionDelta:z4.string(),security:packageUpgradeSecuritySchema,changelog:packageUpgradeChangelogSchema,compatibility:packageUpgradeCompatibilitySchema,dependencyChanges:packageUpgradeDependencyChangesSchema,dependencyIssues:packageUpgradeDependencyIssuesSchema,unknowns:z4.array(z4.string())});var packageUpgradeReviewResponseSchema=z4.object({summary:z4.object({total:z4.number().int(),withUnknowns:z4.number().int(),withAddedAdvisories:z4.number().int(),withBreakingSignals:z4.number().int(),withDirectDependencyChanges:z4.number().int(),withTransitiveVulnerabilityAdditions:z4.number().int()}),reviews:z4.array(packageUpgradeReviewSchema)});var packageUpgradeReviewGraphQLResponseSchema=z4.object({data:z4.object({packageUpgradeReview:packageUpgradeReviewResponseSchema.nullable().optional()}).nullable().optional(),errors:z4.array(graphQLErrorSchema2).optional()});var PACKAGE_UPGRADE_REVIEW_QUERY=`
1124
+ query PackageUpgradeReview(
1125
+ $packages: [PackageUpgradeReviewPackageInput!]!
1126
+ $includeTransitiveSecurity: Boolean!
1127
+ $includeDependencyIssues: Boolean!
1128
+ $minSeverity: Float
1129
+ $changelogLimit: Int!
1130
+ ) {
1131
+ packageUpgradeReview(
1132
+ packages: $packages
1133
+ includeTransitiveSecurity: $includeTransitiveSecurity
1134
+ minSeverity: $minSeverity
1135
+ changelogLimit: $changelogLimit
1136
+ ) {
1137
+ summary {
1138
+ total
1139
+ withUnknowns
1140
+ withAddedAdvisories
1141
+ withBreakingSignals
1142
+ withDirectDependencyChanges
1143
+ withTransitiveVulnerabilityAdditions
1144
+ }
1145
+ reviews {
1146
+ registry
1147
+ name
1148
+ currentVersion
1149
+ targetVersion
1150
+ latestVersion
1151
+ versionDelta
1152
+ security {
1153
+ current {
1154
+ version
1155
+ publishedAt
1156
+ deprecated
1157
+ deprecationReason
1158
+ affectedCount
1159
+ nonAffectingCount
1160
+ allCount
1161
+ lastModifiedAt
1162
+ advisories {
1163
+ ...PackageUpgradeAdvisoryFields
1164
+ }
1165
+ }
1166
+ target {
1167
+ version
1168
+ publishedAt
1169
+ deprecated
1170
+ deprecationReason
1171
+ affectedCount
1172
+ nonAffectingCount
1173
+ allCount
1174
+ lastModifiedAt
1175
+ advisories {
1176
+ ...PackageUpgradeAdvisoryFields
1177
+ }
1178
+ }
1179
+ added {
1180
+ ...PackageUpgradeAdvisoryFields
1181
+ }
1182
+ removed {
1183
+ ...PackageUpgradeAdvisoryFields
1184
+ }
1185
+ notAddressed {
1186
+ ...PackageUpgradeAdvisoryFields
1187
+ }
1188
+ fixed {
1189
+ ...PackageUpgradeAdvisoryFields
1190
+ }
1191
+ introduced {
1192
+ ...PackageUpgradeAdvisoryFields
1193
+ }
1194
+ unchanged {
1195
+ ...PackageUpgradeAdvisoryFields
1196
+ }
1197
+ transitive @include(if: $includeTransitiveSecurity) {
1198
+ currentAffected
1199
+ targetAffected
1200
+ introducedPackages
1201
+ fixedPackages
1202
+ introducedPackageDetails(first: 50) {
1203
+ ...PackageUpgradeTransitivePackagePageFields
1204
+ }
1205
+ fixedPackageDetails(first: 50) {
1206
+ ...PackageUpgradeTransitivePackagePageFields
1207
+ }
1208
+ stillAffectedPackageDetails(first: 50) {
1209
+ ...PackageUpgradeTransitivePackagePageFields
1210
+ }
1211
+ }
1212
+ }
1213
+ changelog {
1214
+ source
1215
+ fallback
1216
+ entries {
1217
+ ...PackageUpgradeChangelogEntryFields
1218
+ }
1219
+ sampledEntries {
1220
+ ...PackageUpgradeChangelogEntryFields
1221
+ }
1222
+ keywordEntries {
1223
+ ...PackageUpgradeChangelogEntryFields
1224
+ }
1225
+ totalKeywordEntries
1226
+ totalEntries
1227
+ totalEntriesWithBodies
1228
+ truncated
1229
+ hasReleaseNoteBodies
1230
+ breakingSignals
1231
+ migrationSignals
1232
+ }
1233
+ compatibility {
1234
+ peerDependencyChanges
1235
+ notes
1236
+ }
1237
+ dependencyChanges {
1238
+ direct {
1239
+ ...PackageUpgradeDependencyChangeGroupFields
1240
+ }
1241
+ transitive {
1242
+ ...PackageUpgradeDependencyChangeGroupFields
1243
+ }
1244
+ }
1245
+ dependencyIssues @include(if: $includeDependencyIssues) {
1246
+ currentTotal
1247
+ targetTotal
1248
+ introducedDeprecated
1249
+ introducedDuplicates
1250
+ introducedConflicts
1251
+ introducedOutdated
1252
+ }
1253
+ unknowns
1254
+ }
1255
+ }
1256
+ }
1257
+
1258
+ fragment PackageUpgradeAdvisoryFields on PackageUpgradeAdvisorySummary {
1259
+ id
1260
+ aliases
1261
+ summary
1262
+ severity
1263
+ severityLabel
1264
+ fixedIn
1265
+ isMalicious
1266
+ }
1267
+
1268
+ fragment PackageUpgradeTransitivePackagePageFields on PackageUpgradeTransitivePackagePage {
1269
+ entries {
1270
+ id
1271
+ registry
1272
+ name
1273
+ versions
1274
+ affectedCount
1275
+ maxSeverityScore
1276
+ maxSeverityLabel
1277
+ advisoryIds
1278
+ }
1279
+ totalCount
1280
+ truncated
1281
+ }
1282
+
1283
+ fragment PackageUpgradeChangelogEntryFields on PackageUpgradeChangelogEntry {
1284
+ version
1285
+ publishedAt
1286
+ htmlUrl
1287
+ body
1288
+ bodyPreview
1289
+ headline
1290
+ signals
1291
+ }
1292
+
1293
+ fragment PackageUpgradeDependencyChangeGroupFields on PackageUpgradeDependencyChangeGroup {
1294
+ added {
1295
+ name
1296
+ registry
1297
+ version
1298
+ fromVersions
1299
+ toVersions
1300
+ constraint
1301
+ type
1302
+ }
1303
+ removed {
1304
+ name
1305
+ registry
1306
+ version
1307
+ fromVersions
1308
+ toVersions
1309
+ constraint
1310
+ type
1311
+ }
1312
+ changed {
1313
+ name
1314
+ registry
1315
+ version
1316
+ fromVersions
1317
+ toVersions
1318
+ constraint
1319
+ type
1320
+ }
1321
+ }`;var changelogPackageInfoSchema=z4.object({name:z4.string().nullable().optional(),registry:z4.string().nullable().optional(),repoUrl:z4.string().nullable().optional(),fromVersion:z4.string().nullable().optional(),toVersion:z4.string().nullable().optional(),limit:z4.number().int().nullable().optional()}).nullable().optional();var changelogEntryDetailSchema=z4.object({version:z4.string().nullable().optional(),normalizedVersion:z4.string().nullable().optional(),body:z4.string().nullable().optional(),htmlUrl:z4.string().nullable().optional(),publishedAt:z4.string().nullable().optional()});var changelogReportResponseSchema=z4.object({package:changelogPackageInfoSchema,source:z4.string().nullable().optional(),entries:z4.array(changelogEntryDetailSchema).nullable().optional()});var changelogGraphQLResponseSchema=z4.object({data:z4.object({packageChangelog:changelogReportResponseSchema.nullable().optional()}).nullable().optional(),errors:z4.array(graphQLErrorSchema2).optional()});var PACKAGE_CHANGELOG_QUERY=`
1322
+ query PackageChangelog(
1323
+ $registry: Registry
1324
+ $name: String
1325
+ $repoUrl: String
1326
+ $gitRef: String
1327
+ $fromVersion: String
1328
+ $toVersion: String
1329
+ $limit: Int
1330
+ $includeBodies: Boolean! = true
1331
+ ) {
1332
+ packageChangelog(
1333
+ registry: $registry
1334
+ name: $name
1335
+ repoUrl: $repoUrl
1336
+ gitRef: $gitRef
1337
+ fromVersion: $fromVersion
1338
+ toVersion: $toVersion
1339
+ limit: $limit
1340
+ ) {
1341
+ package {
1342
+ name
1343
+ registry
1344
+ repoUrl
1345
+ fromVersion
1346
+ toVersion
1347
+ limit
1348
+ }
1349
+ source
1350
+ entries {
1351
+ version
1352
+ normalizedVersion
1353
+ body @include(if: $includeBodies)
1354
+ htmlUrl
1355
+ publishedAt
1356
+ }
1357
+ }
1358
+ }`;var packageDocSourceKindSchema=z4.enum(["CRAWLED","REPOSITORY"]);var packageDocPageSummarySchema=z4.object({id:z4.string().nullable().optional(),docsReadTarget:z4.string(),title:z4.string().nullable().optional(),slug:z4.string().nullable().optional(),order:z4.number().int().nullable().optional(),linkName:z4.string().nullable().optional(),lastUpdatedAt:z4.string().nullable().optional(),sourceKind:packageDocSourceKindSchema.nullable().optional(),sourceUrl:z4.string().nullable().optional(),repoUrl:z4.string().nullable().optional(),gitRef:z4.string().nullable().optional(),requestedRef:z4.string().nullable().optional(),filePath:z4.string().nullable().optional()});var packageDocsPageInfoSchema=z4.object({hasNextPage:z4.boolean(),endCursor:z4.string().nullable().optional(),totalCount:z4.number().int().nullable().optional()}).nullable().optional();var packageDocsListResponseSchema=z4.object({registry:z4.string().nullable().optional(),packageName:z4.string().nullable().optional(),version:z4.string().nullable().optional(),stale:z4.boolean().nullable().optional(),pages:z4.array(packageDocPageSummarySchema).nullable().optional(),pageInfo:packageDocsPageInfoSchema});var packageDocSourceSchema=z4.object({url:z4.string().nullable().optional(),label:z4.string().nullable().optional()}).nullable().optional();var packageDocPageSchema=z4.object({id:z4.string().nullable().optional(),docsReadTarget:z4.string(),title:z4.string().nullable().optional(),content:z4.string().nullable().optional(),contentFormat:z4.string().nullable().optional(),breadcrumbs:z4.array(z4.string()).nullable().optional(),linkName:z4.string().nullable().optional(),lastUpdatedAt:z4.string().nullable().optional(),sourceKind:packageDocSourceKindSchema.nullable().optional(),source:packageDocSourceSchema,repoUrl:z4.string().nullable().optional(),gitRef:z4.string().nullable().optional(),requestedRef:z4.string().nullable().optional(),filePath:z4.string().nullable().optional(),baseUrl:z4.string().nullable().optional()}).nullable().optional();var packageDocResultResponseSchema=z4.object({registry:z4.string().nullable().optional(),packageName:z4.string().nullable().optional(),version:z4.string().nullable().optional(),sourceKind:packageDocSourceKindSchema.nullable().optional(),page:packageDocPageSchema});var packageDocsListGraphQLResponseSchema=z4.object({data:z4.object({listPackageDocs:packageDocsListResponseSchema.nullable().optional()}).nullable().optional(),errors:z4.array(graphQLErrorSchema2).optional()});var packageDocReadGraphQLResponseSchema=z4.object({data:z4.object({getDocPage:packageDocResultResponseSchema.nullable().optional()}).nullable().optional(),errors:z4.array(graphQLErrorSchema2).optional()});var LIST_PACKAGE_DOCS_QUERY=`
1359
+ query ListPackageDocs(
1360
+ $registry: Registry!
1361
+ $packageName: String!
1362
+ $version: String
1363
+ $limit: Int
1364
+ $after: String
1365
+ ) {
1366
+ listPackageDocs(
1367
+ registry: $registry
1368
+ packageName: $packageName
1369
+ version: $version
1370
+ limit: $limit
1371
+ after: $after
1372
+ ) {
1373
+ registry
1374
+ packageName
1375
+ version
1376
+ stale
1377
+ pages {
1378
+ id
1379
+ docsReadTarget
1380
+ title
1381
+ slug
1382
+ order
1383
+ linkName
1384
+ lastUpdatedAt
1385
+ sourceKind
1386
+ sourceUrl
1387
+ repoUrl
1388
+ gitRef
1389
+ requestedRef
1390
+ filePath
1391
+ }
1392
+ pageInfo {
1393
+ hasNextPage
1394
+ endCursor
1395
+ totalCount
1396
+ }
1397
+ }
1398
+ }`;var READ_PACKAGE_DOC_QUERY=`
1399
+ query ReadPackageDoc($pageId: String!) {
1400
+ getDocPage(pageId: $pageId) {
1401
+ registry
1402
+ packageName
1403
+ version
1404
+ sourceKind
1405
+ page {
1406
+ id
1407
+ docsReadTarget
1408
+ title
1409
+ content
1410
+ contentFormat
1411
+ breadcrumbs
1412
+ linkName
1413
+ lastUpdatedAt
1414
+ sourceKind
1415
+ source {
1416
+ url
1417
+ label
1418
+ }
1419
+ repoUrl
1420
+ gitRef
1421
+ requestedRef
1422
+ filePath
1423
+ baseUrl
1424
+ }
1425
+ }
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=`
1427
+ query ResolveTarget(
1428
+ $name: String!
1429
+ $query: String
1430
+ $registries: [Registry!]
1431
+ $preferredKinds: [TargetResolutionKind!]
1432
+ $intentHints: [String!]
1433
+ $limit: Int!
1434
+ $includeDetailedFields: Boolean!
1435
+ $includeNameSimilarity: Boolean!
1436
+ ) {
1437
+ resolveTarget(
1438
+ name: $name
1439
+ query: $query
1440
+ registries: $registries
1441
+ preferredKinds: $preferredKinds
1442
+ intentHints: $intentHints
1443
+ limit: $limit
1444
+ ) {
1445
+ best {
1446
+ ...ResolveTargetReferenceFields
1447
+ }
1448
+ protectedMatches {
1449
+ ...ResolveTargetReferenceFields
1450
+ }
1451
+ candidates @include(if: $includeNameSimilarity) {
1452
+ canonicalKey
1453
+ nameSimilarity
1454
+ }
1455
+ targetsTruncated
1456
+ targets {
1457
+ ...ResolveTargetListFields
1458
+ ...ResolveTargetJsonFields @include(if: $includeDetailedFields)
1459
+ match {
1460
+ confidence
1461
+ ...ResolveTargetMatchJsonFields @include(if: $includeDetailedFields)
1462
+ }
1463
+ }
1464
+ ambiguous
1465
+ ambiguousReason
1466
+ }
1467
+ }
1468
+
1469
+ fragment ResolveTargetReferenceFields on TargetResolutionCandidate {
1470
+ kind
1471
+ canonicalKey
1472
+ confidence
1473
+ }
1474
+
1475
+ fragment ResolveTargetListFields on TargetResolutionTarget {
1476
+ kind
1477
+ canonicalKey
1478
+ latestVersionMaliciousStatus
1479
+ latestVersionMaliciousEvidence {
1480
+ advisories {
1481
+ osvId
1482
+ classificationReasons
1483
+ }
1484
+ totalCount
1485
+ truncated
1486
+ }
1487
+ description
1488
+ repositoryUrl
1489
+ stars
1490
+ downloadsLastMonth
1491
+ downloadsTotal
1492
+ docsAvailable
1493
+ codeAvailable
1494
+ groupKey
1495
+ docsPageCount
1496
+ codeFileCount
1497
+ license
1498
+ }
1499
+
1500
+ fragment ResolveTargetJsonFields on TargetResolutionTarget {
1501
+ displayName
1502
+ registry
1503
+ packageName
1504
+ latestVersion
1505
+ repositoryOwner
1506
+ repositoryName
1507
+ documentationUrl
1508
+ }
1509
+
1510
+ fragment ResolveTargetMatchJsonFields on TargetResolutionMatch {
1511
+ matchedAliases
1512
+ matchTier
1513
+ score
1514
+ }`;class ResolveTargetServiceImpl{endpointUrl;tokenProvider;fetchFn;runtime;constructor(endpointUrl,tokenProvider,fetchFn=globalThis.fetch,runtime={}){this.endpointUrl=endpointUrl;this.tokenProvider=tokenProvider;this.fetchFn=fetchFn;this.runtime=runtime}async resolveTarget(params){return withServiceDiagnostics(this.runtime.diagnostics,"resolve-target.request",()=>executeWithTokenRefresh({getToken:()=>this.tokenProvider.getToken(),forceRefresh:()=>this.tokenProvider.forceRefresh(),shouldRefresh:(error)=>error instanceof AuthenticationError,executeWithToken:(token)=>this.executeResolveTarget(token,params)}))}async executeResolveTarget(token,params){let response;try{response=await postPkgseerGraphql({endpointUrl:this.endpointUrl,token,query:RESOLVE_TARGET_QUERY,variables:buildVariables(params),fetchFn:this.fetchFn,clientHeaders:this.runtime.clientHeaders,userAgent:this.runtime.userAgent,diagnostics:this.runtime.diagnostics})}catch(cause){if(cause instanceof PkgseerTransportError){throw createPackageIntelligenceTransportError(cause)}throw cause}if(response.status<200||response.status>=300){throw createPackageIntelligenceHttpError(response)}const parsed=(params.includeDetailedFields?responseSchema(detailedTargetSchema,params.includeNameSimilarity):responseSchema(listTargetSchema,params.includeNameSimilarity)).safeParse(response.parsedBody);if(!parsed.success){throw new MalformedPackageIntelligenceResponseError("Malformed response from the target-resolution service.")}if(parsed.data.errors&&parsed.data.errors.length>0){throw createPackageIntelligenceGraphQLError(parsed.data.errors,this.runtime.clientVersion,this.runtime.diagnostics)}const result=parsed.data.data?.resolveTarget;if(!result){throw new MalformedPackageIntelligenceResponseError("Empty response from the target-resolution service.")}const nameSimilarityByCanonicalKey=new Map((result.candidates??[]).map((candidate)=>[candidate.canonicalKey,candidate.nameSimilarity]));return{best:result.best?normaliseReference(result.best):undefined,protectedMatches:result.protectedMatches.map(normaliseReference),targets:result.targets.map((target)=>normaliseTarget(target,nameSimilarityByCanonicalKey.get(target.canonicalKey))),targetsTruncated:result.targetsTruncated,ambiguous:result.ambiguous,ambiguousReason:result.ambiguousReason}}}function normaliseReference(target){return{kind:target.kind,canonicalKey:target.canonicalKey,confidence:target.confidence}}function buildVariables(params){const variables={name:params.name,limit:params.limit,includeDetailedFields:params.includeDetailedFields,includeNameSimilarity:params.includeNameSimilarity};if(params.query!==undefined)variables.query=params.query;if(params.registries!==undefined)variables.registries=params.registries;if(params.preferredKinds!==undefined){variables.preferredKinds=params.preferredKinds}if(params.intentHints!==undefined)variables.intentHints=params.intentHints;return variables}function normaliseTarget(target,nameSimilarity){const result={kind:target.kind,canonicalKey:target.canonicalKey,latestVersionMaliciousStatus:target.latestVersionMaliciousStatus,docsAvailable:target.docsAvailable,codeAvailable:target.codeAvailable};assignDefined(result,"description",target.description);assignDefined(result,"latestVersionMaliciousEvidence",target.latestVersionMaliciousEvidence);assignDefined(result,"repositoryUrl",target.repositoryUrl);assignDefined(result,"stars",target.stars);assignDefined(result,"downloadsLastMonth",target.downloadsLastMonth);assignDefined(result,"downloadsTotal",target.downloadsTotal);assignDefined(result,"groupKey",target.groupKey);assignDefined(result,"docsPageCount",target.docsPageCount);assignDefined(result,"codeFileCount",target.codeFileCount);assignDefined(result,"license",target.license);if(target.match){const match={confidence:target.match.confidence};assignDefined(match,"nameSimilarity",nameSimilarity);if("matchedAliases"in target.match){assignDefined(match,"matchedAliases",target.match.matchedAliases);assignDefined(match,"matchTier",target.match.matchTier);assignDefined(match,"score",target.match.score)}result.match=match}if("displayName"in target){assignDefined(result,"displayName",target.displayName);assignDefined(result,"registry",target.registry);assignDefined(result,"packageName",target.packageName);assignDefined(result,"latestVersion",target.latestVersion);assignDefined(result,"repositoryOwner",target.repositoryOwner);assignDefined(result,"repositoryName",target.repositoryName);assignDefined(result,"documentationUrl",target.documentationUrl)}return result}function assignDefined(target,key,value){if(value!==null&&value!==undefined)target[key]=value}function createStaticTokenProvider(token){return{getToken:async()=>token,forceRefresh:async()=>{return}}}import{createHash as createHash2,randomUUID}from"node:crypto";var MAX_HEADER_BYTES=256;var SESSION_ENV_VARS=["TERM_SESSION_ID","ITERM_SESSION_ID","WEZTERM_PANE","KITTY_PID","ALACRITTY_SOCKET","WT_SESSION","VSCODE_PID","SUPERSET_PANE_ID","SUPERSET_WORKSPACE_ID","STARSHIP_SESSION_KEY","SSH_CONNECTION"];var cachedSessionId;function resolveRawSessionId(env=process.env,ppid=process.ppid){for(const key of SESSION_ENV_VARS){const value=env[key];if(value&&value.trim().length>0){return value.trim()}}if(typeof ppid==="number"&&!Number.isNaN(ppid)&&ppid>0){return String(ppid)}return randomUUID()}function getSessionId(env,ppid){if(cachedSessionId!==undefined&&env===undefined&&ppid===undefined){return cachedSessionId}const raw=resolveRawSessionId(env,ppid);const hashed=hashValue(raw);if(env===undefined&&ppid===undefined){cachedSessionId=hashed}return hashed}function hashValue(input){return createHash2("sha256").update(input).digest("hex").slice(0,16)}var AGENT_PROBES=[{envVar:"OPENCODE",name:"opencode"},{envVar:"CLAUDECODE",name:"claude-code"},{envVar:"CURSOR_TRACE_ID",name:"cursor"},{envVar:"WINDSURF_CONFIG_DIR",name:"windsurf"},{envVar:"ZED_TERM",name:"zed"},{envVar:"VSCODE_PID",name:"vscode"}];function parseAgentString(raw){const trimmed=raw.trim();if(trimmed.length===0)return;const slashIndex=trimmed.indexOf("/");if(slashIndex===-1)return{name:trimmed};const name=trimmed.slice(0,slashIndex);const ver=trimmed.slice(slashIndex+1);if(name.length===0)return;return{name,version:ver||undefined}}function formatAgentInfo(info){return info.version?`${info.name}/${info.version}`:info.name}function resolveAgentInfo(env=process.env){const explicit=env.GITHITS_AGENT;if(explicit&&explicit.trim().length>0){return parseAgentString(explicit)}for(const probe of AGENT_PROBES){const value=env[probe.envVar];if(value&&value.trim().length>0){return{name:probe.name}}}return}var CONTROL_CHARS=/[\x00-\x1f\x7f-\x9f]/g;function sanitizeHeaderValue(value){if(value===undefined||value===null||typeof value!=="string"){return}const cleaned=value.replace(CONTROL_CHARS,"").trim();if(cleaned.length===0)return;if(Buffer.byteLength(cleaned,"utf8")>MAX_HEADER_BYTES)return;return cleaned}function createClientHeaderBuilder(options){return()=>buildClientHeadersWithContext({clientName:options.clientName,clientVersion:options.clientVersion,agentProvider:options.agentProvider,env:options.env,ppid:options.ppid})}function buildClientHeadersWithContext(context){try{const headers={};const name=sanitizeHeaderValue(context.clientName);if(name){headers["x-githits-client-name"]=name}const safeClientVersion=sanitizeHeaderValue(context.clientVersion);if(safeClientVersion){headers["x-githits-client-version"]=safeClientVersion}const agentInfo=context.agentProvider?.()??resolveAgentInfo(context.env);if(agentInfo){const agentValue=sanitizeHeaderValue(formatAgentInfo(agentInfo));if(agentValue){headers["x-githits-agent"]=agentValue}}const sessionId=sanitizeHeaderValue(getSessionId(context.env,context.ppid));if(sessionId){headers["x-githits-session-id"]=sessionId}return headers}catch{return{}}}var APP_DIR="githits";var USER_AUTH_STATE_DIR=".githits";function getAppConfigDir(fs){return getAppConfigDirForEnv(fs,process.env,process.platform,fs.getHomeDir())}function getAppConfigDirForEnv(fs,env,platform,home=getHomeDirForEnv(fs,env,platform)){if(platform==="win32"){return fs.joinPath(env.APPDATA??fs.joinPath(home,"AppData","Roaming"),APP_DIR)}return fs.joinPath(env.XDG_CONFIG_HOME??fs.joinPath(home,".config"),APP_DIR)}function getAuthConfigPath(fs){return fs.joinPath(getAppConfigDir(fs),"config.toml")}function getAuthConfigPathForEnv(fs,env,platform){return fs.joinPath(getAppConfigDirForEnv(fs,env,platform),"config.toml")}function getAuthFileStorageDir(fs){return fs.joinPath(getAppConfigDir(fs),"auth")}function getAuthFileStorageDirForEnv(fs,env,platform){return fs.joinPath(getAppConfigDirForEnv(fs,env,platform),"auth")}function getHomeDirForEnv(fs,env,platform){if(platform==="win32"&&env.USERPROFILE)return env.USERPROFILE;if(platform!=="win32"&&env.HOME)return env.HOME;return fs.getHomeDir()}function getLegacyAuthStorageDir(fs){return fs.joinPath(fs.getHomeDir(),USER_AUTH_STATE_DIR)}function getLegacyAuthStorageDirForEnv(fs,env,platform){return fs.joinPath(getHomeDirForEnv(fs,env,platform),USER_AUTH_STATE_DIR)}function getAuthLockDir(fs){return fs.joinPath(fs.getHomeDir(),USER_AUTH_STATE_DIR)}function getLegacyMacAppConfigDir(fs){return fs.joinPath(fs.getHomeDir(),"Library","Application Support",APP_DIR)}function getLegacyMacAppConfigDirForEnv(fs,env){return fs.joinPath(getHomeDirForEnv(fs,env,"darwin"),"Library","Application Support",APP_DIR)}function getLegacyMacAuthConfigPath(fs){return fs.joinPath(getLegacyMacAppConfigDir(fs),"config.toml")}function getLegacyMacAuthConfigPathForEnv(fs,env){return fs.joinPath(getLegacyMacAppConfigDirForEnv(fs,env),"config.toml")}function getLegacyMacAuthFileStorageDir(fs){return fs.joinPath(getLegacyMacAppConfigDir(fs),"auth")}function getLegacyMacAuthFileStorageDirForEnv(fs,env){return fs.joinPath(getLegacyMacAppConfigDirForEnv(fs,env),"auth")}import{z as z6}from"zod";import{parse as parseToml}from"smol-toml";class AppConfigError extends Error{constructor(message){super(message);this.name="AppConfigError"}}async function readAppConfig(fs){let configPath=getAuthConfigPath(fs);if(!await fs.exists(configPath)){const legacyMacConfigPath=getLegacyMacAuthConfigPath(fs);if(process.platform==="darwin"&&await fs.exists(legacyMacConfigPath)){configPath=legacyMacConfigPath}else{return{configPath,data:{}}}}try{return{configPath,data:parseToml(await fs.readFile(configPath))}}catch(error){const message=error instanceof Error?error.message:String(error);throw new AppConfigError(`Cannot parse GitHits config at ${configPath}: ${message}`)}}var AUTH_STORAGE_MODES=["keychain","file"];var AUTH_STORAGE_MODE_VALUES=new Set(AUTH_STORAGE_MODES);var CONFIG_SCHEMA=z6.object({auth:z6.object({storage:z6.string().optional()}).optional()}).passthrough();class AuthConfigError extends Error{constructor(message){super(message);this.name="AuthConfigError"}}function parseAuthStorageMode(value){const normalized=value.trim().toLowerCase();if(AUTH_STORAGE_MODE_VALUES.has(normalized)){return normalized}throw new AuthConfigError(`Invalid auth storage mode "${value}". Use "keychain" or "file". File mode stores OAuth credentials unencrypted on disk.`)}async function loadAuthConfig(fs){const envMode=process.env.GITHITS_AUTH_STORAGE;if(envMode!==undefined&&envMode.trim()!==""){try{return{storage:parseAuthStorageMode(envMode),configPath:getAuthConfigPath(fs)}}catch(error){if(error instanceof AuthConfigError){throw new AuthConfigError(`Invalid GITHITS_AUTH_STORAGE: ${error.message}`)}throw error}}let document;try{document=await readAppConfig(fs)}catch(error){if(error instanceof AppConfigError){throw new AuthConfigError(error.message)}throw error}const parsed=CONFIG_SCHEMA.safeParse(document.data);if(!parsed.success){throw new AuthConfigError(`Invalid GitHits config at ${document.configPath}: ${z6.prettifyError(parsed.error)}`)}const configuredMode=parsed.data.auth?.storage;if(configuredMode===undefined||configuredMode.trim()===""){return{storage:"keychain",configPath:document.configPath}}try{return{storage:parseAuthStorageMode(configuredMode),configPath:document.configPath}}catch(error){if(error instanceof AuthConfigError){throw new AuthConfigError(`Invalid GitHits config at ${document.configPath}: ${error.message}`)}throw error}}var AUTH_FILE="auth.json";var CLIENT_FILE="client.json";var DIR_MODE=448;var FILE_MODE=384;class AuthStorageImpl{fs;configDir;authPath;clientPath;constructor(fs,configDir){this.fs=fs;this.configDir=configDir??getAuthFileStorageDir(fs);this.authPath=fs.joinPath(this.configDir,AUTH_FILE);this.clientPath=fs.joinPath(this.configDir,CLIENT_FILE)}getStorageLocation(){return this.configDir}async loadTokens(baseUrl){const stored=await this.loadAuthFile();if(!stored)return null;return stored.tokens[normalizeBaseUrl(baseUrl)]??null}async saveTokens(baseUrl,data){const stored=await this.loadAuthFile()??{version:1,tokens:{}};stored.tokens[normalizeBaseUrl(baseUrl)]=data;await this.fs.ensureDir(this.configDir,DIR_MODE);await this.fs.atomicWriteFile(this.authPath,JSON.stringify(stored,null,2),FILE_MODE)}async saveTokensIfUnchanged(baseUrl,expected,data){const current=await this.loadTokens(baseUrl);if(!sameTokenData(current,expected))return false;await this.saveTokens(baseUrl,data);return true}async clearTokens(baseUrl){const stored=await this.loadAuthFile();if(!stored)return;delete stored.tokens[normalizeBaseUrl(baseUrl)];if(Object.keys(stored.tokens).length===0){await this.fs.deleteFile(this.authPath)}else{await this.fs.atomicWriteFile(this.authPath,JSON.stringify(stored,null,2),FILE_MODE)}}async clearTokensIfUnchanged(baseUrl,expected){const current=await this.loadTokens(baseUrl);if(!sameTokenData(current,expected))return false;await this.clearTokens(baseUrl);return true}clearActiveTokensIfUnchanged(baseUrl,expected){return this.clearTokensIfUnchanged(baseUrl,expected)}async loadClient(baseUrl){const stored=await this.loadClientFile();if(!stored)return null;return stored.clients[normalizeBaseUrl(baseUrl)]??null}async clearClient(baseUrl){const stored=await this.loadClientFile();if(!stored)return;delete stored.clients[normalizeBaseUrl(baseUrl)];if(Object.keys(stored.clients).length===0){await this.fs.deleteFile(this.clientPath)}else{await this.fs.atomicWriteFile(this.clientPath,JSON.stringify(stored,null,2),FILE_MODE)}}async saveClient(baseUrl,data){const stored=await this.loadClientFile()??{version:1,clients:{}};stored.clients[normalizeBaseUrl(baseUrl)]=data;await this.fs.ensureDir(this.configDir,DIR_MODE);await this.fs.atomicWriteFile(this.clientPath,JSON.stringify(stored,null,2),FILE_MODE)}clearActiveClient(baseUrl){return this.clearClient(baseUrl)}async saveAuthSession(baseUrl,client,tokens){await this.saveClient(baseUrl,client);await this.saveTokens(baseUrl,tokens)}async clearAuthSession(baseUrl){await clearAuthSessionBestEffort(()=>this.clearTokens(baseUrl),()=>this.clearClient(baseUrl))}async loadAuthFile(){if(!await this.fs.exists(this.authPath))return null;try{const content=await this.fs.readFile(this.authPath);const data=JSON.parse(content);if(data.version!==1||!data.tokens)return null;return data}catch{return null}}async loadClientFile(){if(!await this.fs.exists(this.clientPath))return null;try{const content=await this.fs.readFile(this.clientPath);const data=JSON.parse(content);if(data.version!==1||!data.clients)return null;return data}catch{return null}}}function normalizeBaseUrl(url){return url.replace(/\/+$/,"")}function sameTokenData(a,b){if(a===null||b===null)return a===b;return a.accessToken===b.accessToken&&a.refreshToken===b.refreshToken&&a.expiresAt===b.expiresAt&&a.createdAt===b.createdAt}async function clearAuthSessionBestEffort(clearTokens,clearClient){let firstError;try{await clearTokens()}catch(error){firstError=error}try{await clearClient()}catch(error){firstError??=error}if(firstError)throw firstError}var DIAGNOSTICS_FILE="diagnostics.json";var DIR_MODE2=448;var FILE_MODE2=384;var CLEAR_REASONS=new Set(["logout","terminal_invalid_refresh_token","terminal_invalid_client"]);class AuthDiagnosticsStorage{fs;configDir;diagnosticsPath;constructor(fs,configDir){this.fs=fs;this.configDir=configDir??getAuthFileStorageDir(fs);this.diagnosticsPath=fs.joinPath(this.configDir,DIAGNOSTICS_FILE)}async recordClear(baseUrl,reason){try{const stored=await this.loadFile()??{version:1,events:{}};stored.events[normalizeBaseUrl(baseUrl)]={reason,at:new Date().toISOString()};await this.fs.ensureDir(this.configDir,DIR_MODE2);await this.fs.atomicWriteFile(this.diagnosticsPath,JSON.stringify(stored,null,2),FILE_MODE2)}catch{}}async load(baseUrl){const stored=await this.loadFile();if(!stored)return null;const event=stored.events[normalizeBaseUrl(baseUrl)]??null;return isAuthClearEvent(event)?event:null}async loadFile(){if(!await this.fs.exists(this.diagnosticsPath))return null;try{const content=await this.fs.readFile(this.diagnosticsPath);const data=JSON.parse(content);if(!isRecord2(data)||data.version!==1||!isRecord2(data.events)){return null}return data}catch{return null}}}function isRecord2(value){return typeof value==="object"&&value!==null&&!Array.isArray(value)}function isAuthClearReason(value){return typeof value==="string"&&CLEAR_REASONS.has(value)}function isAuthClearEvent(value){if(value===null||typeof value!=="object")return false;return isAuthClearReason(value.reason)&&typeof value.at==="string"&&value.at.length>0}import{createServer}from"node:http";import{z as z7}from"zod";class TokenRefreshError extends Error{status;body;oauthError;oauthErrorDescription;constructor(status,body){const details=parseOAuthErrorBody(body);const description=parseHttpErrorDetail(body,OAUTH_ERROR_DETAIL_FIELDS);super(description?`Token refresh failed with HTTP ${status}: ${description}`:`Token refresh failed with HTTP ${status}`);this.name="TokenRefreshError";this.status=status;this.body=body;this.oauthError=details.oauthError;this.oauthErrorDescription=details.oauthErrorDescription}}class AuthServiceImpl{fetchFn;fetchTimeoutMs;constructor(fetchFn,fetchTimeoutMs=DEFAULT_FETCH_TIMEOUT_MS){this.fetchFn=fetchFn;this.fetchTimeoutMs=fetchTimeoutMs}async discoverEndpoints(mcpBaseUrl){const validatedBaseUrl=validateServiceUrl(mcpBaseUrl,"GITHITS_MCP_URL");const url=`${validatedBaseUrl.replace(/\/+$/,"")}/.well-known/oauth-authorization-server`;const response=await fetchWithTimeout(url,{},this.fetchOptions());if(!response.ok){throw new Error(`Failed to discover OAuth endpoints: ${response.status} ${response.statusText}`)}const data=await readJsonResponse(response,"OAuth metadata response was not valid JSON.");const parsed=OAUTH_METADATA_SCHEMA.safeParse(data);if(!parsed.success){throw new Error("OAuth metadata missing required endpoints")}return{authorizationEndpoint:validateServiceUrl(parsed.data.authorization_endpoint,"OAuth authorization endpoint"),tokenEndpoint:validateServiceUrl(parsed.data.token_endpoint,"OAuth token endpoint"),registrationEndpoint:validateServiceUrl(parsed.data.registration_endpoint,"OAuth registration endpoint")}}async registerClient(params){const registrationEndpoint=validateServiceUrl(params.registrationEndpoint,"OAuth registration endpoint");const response=await fetchWithTimeout(registrationEndpoint,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({client_name:"GitHits CLI",redirect_uris:params.redirectUris,grant_types:["authorization_code","refresh_token"],response_types:["code"],token_endpoint_auth_method:"client_secret_post"})},this.fetchOptions());if(!response.ok){const body=await response.text().catch(()=>"");const detail=parseHttpErrorDetail(body,OAUTH_ERROR_DETAIL_FIELDS);throw new Error(`Client registration failed with HTTP ${response.status}.${detail?` ${detail}`:""}`)}const data=await readJsonResponse(response,"Client registration response was not valid JSON.");const parsed=CLIENT_REGISTRATION_SCHEMA.safeParse(data);if(!parsed.success){throw new Error("Client registration response missing required fields")}return{clientId:parsed.data.client_id,clientSecret:parsed.data.client_secret}}generatePkceParams(){const verifier=generateCodeVerifier();return{verifier,challenge:generateCodeChallenge(verifier),state:generateState()}}buildAuthUrl(params){const url=new URL(params.authorizationEndpoint);url.searchParams.set("response_type","code");url.searchParams.set("client_id",params.clientId);url.searchParams.set("redirect_uri",params.redirectUri);url.searchParams.set("state",params.state);url.searchParams.set("code_challenge",params.codeChallenge);url.searchParams.set("code_challenge_method","S256");return url.toString()}startCallbackServer(port,expectedState){const server=createServer();const connections=new Set;let callbackHandled=false;let resolved=false;server.on("connection",(socket)=>{connections.add(socket);socket.once("close",()=>connections.delete(socket))});const result=new Promise((resolve)=>{server.on("request",(req,res)=>{const address=server.address();const actualPort=typeof address==="object"&&address!==null?address.port:port;const url=new URL(req.url??"",`http://127.0.0.1:${actualPort}`);if(url.pathname==="/favicon.ico"){res.writeHead(204);res.end();return}if(url.pathname!=="/callback"){if(callbackHandled){sendHtmlResponse(res,200,successHtml("You're already signed in."));return}sendHtmlResponse(res,404,errorHtml("Invalid callback path.","Run `githits login` to start authentication."));return}const code=url.searchParams.get("code");const state=url.searchParams.get("state");const error=url.searchParams.get("error");const errorDescription=url.searchParams.get("error_description");const evaluation=evaluateCallback({code,state,error,errorDescription,expectedState});callbackHandled=true;const settle=()=>{if(!resolved){resolved=true;resolve(evaluation.result)}};res.once("finish",settle);res.once("close",settle);sendHtmlResponse(res,evaluation.statusCode,evaluation.html)})});return new Promise((resolve,reject)=>{const onError=(err)=>{reject(new Error(`Failed to start callback server: ${err.message}`))};server.once("error",onError);server.listen(port,"127.0.0.1",()=>{server.off("error",onError);server.on("error",()=>{});resolve({result,close:()=>closeCallbackServerConnections(server,connections)})})})}async exchangeCodeForTokens(params){const body=new URLSearchParams({grant_type:"authorization_code",client_id:params.clientId,client_secret:params.clientSecret,code:params.code,code_verifier:params.codeVerifier,redirect_uri:params.redirectUri});const tokenEndpoint=validateServiceUrl(params.tokenEndpoint,"OAuth token endpoint");const response=await fetchWithTimeout(tokenEndpoint,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:body.toString()},this.fetchOptions());if(!response.ok){const body=await response.text().catch(()=>"");const detail=parseHttpErrorDetail(body,OAUTH_ERROR_DETAIL_FIELDS);throw new Error(`Token exchange failed with HTTP ${response.status}.${detail?` ${detail}`:""}`)}return parseTokenResponse(await readJsonResponse(response,"Token exchange response was not valid JSON."))}async refreshAccessToken(params){const body=new URLSearchParams({grant_type:"refresh_token",client_id:params.clientId,client_secret:params.clientSecret,refresh_token:params.refreshToken});const tokenEndpoint=validateServiceUrl(params.tokenEndpoint,"OAuth token endpoint");const response=await fetchWithTimeout(tokenEndpoint,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:body.toString()},this.fetchOptions());if(!response.ok){const error=await response.text();throw new TokenRefreshError(response.status,error)}return parseRefreshTokenResponse(await readJsonResponse(response,"Token refresh response was not valid JSON."))}fetchOptions(){return{fetchFn:this.fetchFn,timeoutMs:this.fetchTimeoutMs}}}function classifyTerminalRefreshError(error){if(!(error instanceof TokenRefreshError)||error.status<400||error.status>=500){return}const oauthError=error.oauthError?.toLowerCase();const text=[error.oauthError,error.oauthErrorDescription,error.body,error.message].filter((part)=>typeof part==="string").join(" ").toLowerCase();if(oauthError==="invalid_client"||text.includes("client not found")||text.includes("client id not found")||text.includes("client_id not found")||text.includes("oauth client not found")||text.includes("client does not match")||text.includes("client authentication required")||text.includes("invalid client credentials")){return"invalid_client"}if(oauthError==="invalid_grant"&&(text.includes("invalid refresh token")||text.includes("refresh token already used")||text.includes("already used")||text.includes("session expired")||text.includes("session not found"))){return"invalid_refresh_token"}return}function parseOAuthErrorBody(body){try{const parsed=JSON.parse(body);return{oauthError:stringField2(parsed.error),oauthErrorDescription:stringField2(parsed.error_description)??stringField2(parsed.errorDescription)??stringField2(parsed.message)??stringField2(parsed.msg)}}catch{return{oauthError:undefined,oauthErrorDescription:undefined}}}function stringField2(value){return typeof value==="string"&&value.trim()?value:undefined}var OAUTH_ERROR_DETAIL_FIELDS=["detail","error_description","message","error"];var OAUTH_METADATA_SCHEMA=z7.object({authorization_endpoint:z7.string().min(1),token_endpoint:z7.string().min(1),registration_endpoint:z7.string().min(1)});var CLIENT_REGISTRATION_SCHEMA=z7.object({client_id:z7.string().min(1),client_secret:z7.string().min(1)});var EXPIRES_IN_SCHEMA=z7.union([z7.number(),z7.string().trim().regex(/^\d+(?:\.\d+)?$/).transform(Number)]).pipe(z7.number().positive());var TOKEN_RESPONSE_SCHEMA=z7.object({access_token:z7.string().min(1),refresh_token:z7.string().min(1),expires_in:EXPIRES_IN_SCHEMA.optional()});var REFRESH_TOKEN_RESPONSE_SCHEMA=z7.object({access_token:z7.string().min(1),refresh_token:z7.string().min(1).optional(),expires_in:EXPIRES_IN_SCHEMA.optional()});async function readJsonResponse(response,message){try{return await response.json()}catch(cause){throw new Error(message,{cause})}}function parseTokenResponse(data){const parsed=TOKEN_RESPONSE_SCHEMA.safeParse(data);if(!parsed.success){throw new Error("Token response missing required fields")}return{accessToken:parsed.data.access_token,refreshToken:parsed.data.refresh_token,expiresIn:parsed.data.expires_in??3600}}function parseRefreshTokenResponse(data){const parsed=REFRESH_TOKEN_RESPONSE_SCHEMA.safeParse(data);if(!parsed.success){throw new Error("Token response missing required fields")}return{accessToken:parsed.data.access_token,refreshToken:parsed.data.refresh_token,expiresIn:parsed.data.expires_in??3600}}function successHtml(title="You're signed in"){return`<!DOCTYPE html>
1515
+ <html><head>
1516
+ <title>GitHits CLI</title>
1517
+ <meta charset="utf-8">
1518
+ <meta name="viewport" content="width=device-width, initial-scale=1">
1519
+ <link rel="preconnect" href="https://fonts.googleapis.com">
1520
+ <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
1521
+ <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;600;700&family=Lexend:wght@600&display=swap" rel="stylesheet">
1522
+ <style>
1523
+ *, *::before, *::after { box-sizing: border-box; }
1524
+ body {
1525
+ margin: 0;
1526
+ min-height: 100vh;
1527
+ width: 100%;
1528
+ padding: 16px;
1529
+ background: #21262d;
1530
+ color: #ffffff;
1531
+ font-family: 'Inter', sans-serif;
1532
+ display: flex;
1533
+ align-items: center;
1534
+ justify-content: center;
1535
+ }
1536
+ .content {
1537
+ display: flex;
1538
+ flex-direction: column;
1539
+ align-items: center;
1540
+ gap: 20px;
1541
+ padding: 0 16px;
1542
+ }
1543
+ .message {
1544
+ display: flex;
1545
+ flex-direction: column;
1546
+ align-items: center;
1547
+ gap: 8px;
1548
+ }
1549
+ .success-icon {
1550
+ width: 48px;
1551
+ height: 48px;
1552
+ border-radius: 50%;
1553
+ border: 2px solid #57fec9;
1554
+ background: transparent;
1555
+ display: flex;
1556
+ align-items: center;
1557
+ justify-content: center;
1558
+ }
1559
+ .heading {
1560
+ font-family: 'Lexend', sans-serif;
1561
+ font-weight: 600;
1562
+ font-size: 32px;
1563
+ line-height: 40px;
1564
+ color: #ffffff;
1565
+ margin: 0;
1566
+ text-align: center;
1567
+ text-wrap: pretty;
1568
+ }
1569
+ .text {
1570
+ font-family: 'Inter', sans-serif;
1571
+ font-weight: 400;
1572
+ font-size: 16px;
1573
+ line-height: 24px;
1574
+ margin: 0;
1575
+ text-align: center;
1576
+ text-wrap: pretty;
1577
+ }
1578
+ .text-muted {
1579
+ color: #abb2bf;
1580
+ }${COPY_BTN_CSS}
1581
+ </style>
1582
+ </head>
1583
+ <body>
1584
+ <div class="content">
1585
+ <div class="success-icon" aria-hidden="true">
1586
+ <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="24" height="24" fill="none" stroke="#57fec9" stroke-width="3" stroke-linecap="round" stroke-linejoin="round">
1587
+ <polyline points="20 6 9 17 4 12" />
1588
+ </svg>
1589
+ </div>
1590
+ <div class="message">
1591
+ <h1 class="heading">${escapeHtml(title)}</h1>
1592
+ <p class="text text-muted">You can close this window and return to your terminal.</p>
1593
+ </div>
1594
+
1595
+ <svg class="wordmark" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 554 129.3" width="103" height="24" role="img" aria-label="GitHits">
1596
+ <title>GitHits</title>
1597
+ <defs>
1598
+ <linearGradient id="wm-grad" x1="234.9" y1="64.7" x2="555.5" y2="64.7" gradientUnits="userSpaceOnUse">
1599
+ <stop offset="0" style="stop-color: #ff4fae" />
1600
+ <stop offset="1" style="stop-color: #ff872f" />
1601
+ </linearGradient>
1602
+ </defs>
1603
+ <path d="M148.6,29.1c7.9,0,14.4-6.4,14.4-14.4S156.6.3,148.6.3s-14.4,6.4-14.4,14.4,6.4,14.4,14.4,14.4Z" fill="#ff4fae" />
1604
+ <path d="M383.9,29.1c7.9,0,14.4-6.4,14.4-14.4s-6.4-14.4-14.4-14.4-14.4,6.4-14.4,14.4,6.4,14.4,14.4,14.4ZM396.4,40.8h-25v86.6h25V40.8ZM454.3,8.5h-25v32.3h-18.8v24h18.8v62.6h25v-62.6h18.8v-24h-18.8V8.5ZM553.1,92.2c-.9-2.6-2.2-4.9-4.1-6.9-2.2-2.4-5.1-4.4-8.8-6.2-3.7-1.8-8.2-3.4-13.4-4.9-4.1-1.1-7.3-2.1-9.6-3-2.4-.9-4.1-1.7-5.3-2.4-1.1-.8-1.9-1.7-2.5-2.9-.6-1.1-.9-2.3-.9-3.5s.2-2.4.7-3.4,1.2-1.9,2.2-2.6c1-.7,2.2-1.3,3.7-1.6s3.2-.5,5-.5,4.5.4,7.1,1.3c2.6.9,5.2,2.1,7.7,3.7,2.5,1.6,4.7,3.3,6.7,5.2l12.5-14.2c-2.8-2.8-6-5.2-9.6-7.3-3.7-2.1-7.7-3.7-11.9-4.8-4.3-1.1-8.7-1.7-13.2-1.7s-8.8.7-12.9,1.9c-4.1,1.3-7.7,3.1-10.8,5.5s-5.6,5.2-7.3,8.5c-1.8,3.3-2.6,7-2.6,11s.5,6.4,1.6,9.2c1,2.8,2.5,5.3,4.5,7.7,2.3,2.5,5.4,4.7,9.3,6.7s8.6,3.7,14.2,5.1c3.6,1,6.6,1.9,8.9,2.8,2.3.8,4,1.6,5.1,2.3,2,1.4,3,3.3,3,5.7s-.2,2.4-.7,3.5-1.2,2-2.2,2.7-2.2,1.3-3.5,1.7c-1.4.4-2.9.6-4.5.6-4.2,0-8.4-.8-12.5-2.5-4.2-1.6-7.9-4.3-11.2-8l-14.7,12.8c3.8,4.8,8.9,8.6,15.2,11.4,6.3,2.8,13.5,4.1,21.7,4.1s12.5-1.2,17.8-3.7,9.4-5.8,12.4-10.1c3-4.3,4.5-9.2,4.5-14.7s-.4-6-1.3-8.6h-.3ZM327.2,60.5h-50.2V6h-25v121.4h25v-42.8h50.2v42.8h25V6h-25v54.5Z" fill="url(#wm-grad)" />
1605
+ <path d="M239.1,64.8v-24h-18.8V8.5h-25v32.3h-18.8v24h18.8v62.6h25v-62.6h18.8ZM161.1,40.8h-25v86.6h25V40.8ZM91.6,84.6h-26.8v-24h54s1.2,4.3,1.1,12.1c-.3,30.6-25.3,55.5-55.9,55.7h-.5C27.4,128.4-1.6,98.3,0,61.8,1.5,29.6,27.4,3.4,59.6,1.4c21-1.2,40,7.7,52.4,22.4l-17.2,17.2c-7.7-10.1-20.3-16.4-34.3-15.4-19.4,1.4-35,17.1-36.4,36.5-1.6,23,16.6,42.2,39.3,42.2s28-19.7,28-19.7h.2Z" fill="#ff4fae" />
1606
+ </svg>
1607
+
1608
+ ${HELP_CTA}
1609
+ </div>
1610
+ ${COPY_SCRIPT_HTML}
1611
+ </body></html>`}var KNOWN_OAUTH_ERROR_MESSAGES={access_denied:"Access was denied."};function describeOauthError(code,description){const mapped=KNOWN_OAUTH_ERROR_MESSAGES[code];if(mapped)return mapped;if(description){return/[.!?]$/.test(description)?description:`${description}.`}return"Something went wrong while signing in."}function evaluateCallback(input){if(input.error){const message=input.errorDescription?`${input.error}: ${input.errorDescription}`:input.error;const browserMessage=describeOauthError(input.error,input.errorDescription);return{statusCode:200,html:errorHtml(browserMessage,input.error,RETRY_CTA),result:{type:"oauth_error",message}}}if(input.code&&input.state){if(input.state!==input.expectedState){return{statusCode:400,html:errorHtml("Sign-in could not be verified for security reasons.",undefined,RETRY_CTA),result:{type:"state_mismatch",message:"Security validation failed (state mismatch)"}}}return{statusCode:200,html:successHtml(),result:{type:"success",code:input.code,state:input.state}}}return{statusCode:400,html:errorHtml("Sign-in did not complete correctly.",undefined,RETRY_CTA),result:{type:"invalid_callback",message:"Authentication callback missing required parameters"}}}function errorHtml(error,errorCode,ctaHtml){const errorCodeHtml=errorCode?`<p class="error-code">Error code: <code>${escapeHtml(errorCode)}</code></p>`:"";return`<!DOCTYPE html>
1612
+ <html><head>
1613
+ <title>GitHits CLI</title>
1614
+ <meta charset="utf-8">
1615
+ <meta name="viewport" content="width=device-width, initial-scale=1">
1616
+ <link rel="preconnect" href="https://fonts.googleapis.com">
1617
+ <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
1618
+ <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;600;700&family=Lexend:wght@600&display=swap" rel="stylesheet">
1619
+ <style>
1620
+ *, *::before, *::after { box-sizing: border-box; }
1621
+ body {
1622
+ margin: 0;
1623
+ min-height: 100vh;
1624
+ width: 100%;
1625
+ padding: 16px;
1626
+ background: #21262d;
1627
+ color: #ffffff;
1628
+ font-family: 'Inter', sans-serif;
1629
+ display: flex;
1630
+ align-items: center;
1631
+ justify-content: center;
1632
+ }
1633
+ .content {
1634
+ display: flex;
1635
+ flex-direction: column;
1636
+ align-items: center;
1637
+ gap: 20px;
1638
+ padding: 0 16px;
1639
+ }
1640
+ .message {
1641
+ display: flex;
1642
+ flex-direction: column;
1643
+ align-items: center;
1644
+ gap: 8px;
1645
+ }
1646
+ .error-icon {
1647
+ width: 48px;
1648
+ height: 48px;
1649
+ border-radius: 50%;
1650
+ border: 2px solid #ff5a6a;
1651
+ background: transparent;
1652
+ display: flex;
1653
+ align-items: center;
1654
+ justify-content: center;
1655
+ }
1656
+ .heading {
1657
+ font-family: 'Lexend', sans-serif;
1658
+ font-weight: 600;
1659
+ font-size: 32px;
1660
+ line-height: 40px;
1661
+ color: #ffffff;
1662
+ margin: 0;
1663
+ text-align: center;
1664
+ text-wrap: pretty;
1665
+ }
1666
+ .text {
1667
+ font-family: 'Inter', sans-serif;
1668
+ font-weight: 400;
1669
+ font-size: 16px;
1670
+ line-height: 24px;
1671
+ margin: 0;
1672
+ text-align: center;
1673
+ text-wrap: pretty;
1674
+ }
1675
+ .text-muted {
1676
+ color: #abb2bf;
1677
+ }
1678
+ .footer-text {
1679
+ font-family: 'Inter', sans-serif;
1680
+ font-weight: 400;
1681
+ font-size: 12px;
1682
+ line-height: 16px;
1683
+ color: #abb2bf;
1684
+ margin: 0;
1685
+ text-align: center;
1686
+ text-wrap: pretty;
1687
+ }
1688
+ .footer-link {
1689
+ color: inherit;
1690
+ text-decoration: underline;
1691
+ text-underline-offset: 2px;
1692
+ }
1693
+ .error-code {
1694
+ font-family: 'Inter', sans-serif;
1695
+ font-weight: 400;
1696
+ font-size: 12px;
1697
+ line-height: 16px;
1698
+ color: #abb2bf;
1699
+ opacity: 0.7;
1700
+ margin: 4px 0 0;
1701
+ text-align: center;
1702
+ }
1703
+ .error-code code {
1704
+ font-size: 11px;
1705
+ padding: 0 5px;
1706
+ }
1707
+ code {
1708
+ font-family: 'Consolas', monospace;
1709
+ font-size: 13px;
1710
+ background: rgba(255, 255, 255, 0.08);
1711
+ padding: 1px 6px;
1712
+ border-radius: 4px;
1713
+ color: #ffffff;
1714
+ }${COPY_BTN_CSS}
1715
+ </style>
1716
+ </head>
1717
+ <body>
1718
+ <div class="content">
1719
+ <div class="error-icon" aria-hidden="true">
1720
+ <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="24" height="24" fill="none" stroke="#ff5a6a" stroke-width="3" stroke-linecap="round" stroke-linejoin="round">
1721
+ <line x1="18" y1="6" x2="6" y2="18"/>
1722
+ <line x1="6" y1="6" x2="18" y2="18"/>
1723
+ </svg>
1724
+ </div>
1725
+
1726
+ <div class="message">
1727
+ <h1 class="heading">Sign-in failed</h1>
1728
+ <p class="text text-muted">${escapeHtml(error)}</p>
1729
+ ${errorCodeHtml}
1730
+ </div>
1731
+
1732
+ ${ctaHtml??""}
1733
+
1734
+ <svg class="wordmark" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 554 129.3" width="103" height="24" role="img" aria-label="GitHits">
1735
+ <title>GitHits</title>
1736
+ <defs>
1737
+ <linearGradient id="wm-grad" x1="234.9" y1="64.7" x2="555.5" y2="64.7" gradientUnits="userSpaceOnUse">
1738
+ <stop offset="0" style="stop-color: #ff4fae" />
1739
+ <stop offset="1" style="stop-color: #ff872f" />
1740
+ </linearGradient>
1741
+ </defs>
1742
+ <path d="M148.6,29.1c7.9,0,14.4-6.4,14.4-14.4S156.6.3,148.6.3s-14.4,6.4-14.4,14.4,6.4,14.4,14.4,14.4Z" fill="#ff4fae" />
1743
+ <path d="M383.9,29.1c7.9,0,14.4-6.4,14.4-14.4s-6.4-14.4-14.4-14.4-14.4,6.4-14.4,14.4,6.4,14.4,14.4,14.4ZM396.4,40.8h-25v86.6h25V40.8ZM454.3,8.5h-25v32.3h-18.8v24h18.8v62.6h25v-62.6h18.8v-24h-18.8V8.5ZM553.1,92.2c-.9-2.6-2.2-4.9-4.1-6.9-2.2-2.4-5.1-4.4-8.8-6.2-3.7-1.8-8.2-3.4-13.4-4.9-4.1-1.1-7.3-2.1-9.6-3-2.4-.9-4.1-1.7-5.3-2.4-1.1-.8-1.9-1.7-2.5-2.9-.6-1.1-.9-2.3-.9-3.5s.2-2.4.7-3.4,1.2-1.9,2.2-2.6c1-.7,2.2-1.3,3.7-1.6s3.2-.5,5-.5,4.5.4,7.1,1.3c2.6.9,5.2,2.1,7.7,3.7,2.5,1.6,4.7,3.3,6.7,5.2l12.5-14.2c-2.8-2.8-6-5.2-9.6-7.3-3.7-2.1-7.7-3.7-11.9-4.8-4.3-1.1-8.7-1.7-13.2-1.7s-8.8.7-12.9,1.9c-4.1,1.3-7.7,3.1-10.8,5.5s-5.6,5.2-7.3,8.5c-1.8,3.3-2.6,7-2.6,11s.5,6.4,1.6,9.2c1,2.8,2.5,5.3,4.5,7.7,2.3,2.5,5.4,4.7,9.3,6.7s8.6,3.7,14.2,5.1c3.6,1,6.6,1.9,8.9,2.8,2.3.8,4,1.6,5.1,2.3,2,1.4,3,3.3,3,5.7s-.2,2.4-.7,3.5-1.2,2-2.2,2.7-2.2,1.3-3.5,1.7c-1.4.4-2.9.6-4.5.6-4.2,0-8.4-.8-12.5-2.5-4.2-1.6-7.9-4.3-11.2-8l-14.7,12.8c3.8,4.8,8.9,8.6,15.2,11.4,6.3,2.8,13.5,4.1,21.7,4.1s12.5-1.2,17.8-3.7,9.4-5.8,12.4-10.1c3-4.3,4.5-9.2,4.5-14.7s-.4-6-1.3-8.6h-.3ZM327.2,60.5h-50.2V6h-25v121.4h25v-42.8h50.2v42.8h25V6h-25v54.5Z" fill="url(#wm-grad)" />
1744
+ <path d="M239.1,64.8v-24h-18.8V8.5h-25v32.3h-18.8v24h18.8v62.6h25v-62.6h18.8ZM161.1,40.8h-25v86.6h25V40.8ZM91.6,84.6h-26.8v-24h54s1.2,4.3,1.1,12.1c-.3,30.6-25.3,55.5-55.9,55.7h-.5C27.4,128.4-1.6,98.3,0,61.8,1.5,29.6,27.4,3.4,59.6,1.4c21-1.2,40,7.7,52.4,22.4l-17.2,17.2c-7.7-10.1-20.3-16.4-34.3-15.4-19.4,1.4-35,17.1-36.4,36.5-1.6,23,16.6,42.2,39.3,42.2s28-19.7,28-19.7h.2Z" fill="#ff4fae" />
1745
+ </svg>
1746
+
1747
+ <p class="footer-text">Having trouble? Check our <a class="footer-link" href="https://app.githits.com/docs/" target="_blank" rel="noopener noreferrer">documentation</a> or contact <a class="footer-link" href="mailto:support@githits.com">support</a>.</p>
1748
+ </div>
1749
+ ${COPY_SCRIPT_HTML}
1750
+ </body></html>`}function sendHtmlResponse(res,statusCode,html){res.writeHead(statusCode,{"Content-Type":"text/html; charset=utf-8"});res.end(html)}function closeCallbackServerConnections(server,connections){return new Promise((resolve,reject)=>{const destroyConnections=()=>{for(const socket of connections)socket.destroy()};if(!server.listening){destroyConnections();resolve();return}server.close((error)=>{if(error)reject(error);else resolve()});destroyConnections()})}var COPY_ICON_SVG=`<svg class="githits-cli-icon githits-cli-icon-copy" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><rect x="9" y="9" width="13" height="13" rx="2" ry="2"></rect><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"></path></svg>`;var CHECK_ICON_SVG=`<svg class="githits-cli-icon githits-cli-icon-check" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="3" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><polyline points="20 6 9 17 4 12"></polyline></svg>`;function commandButton(cmd){const escaped=escapeHtml(cmd);return`<button type="button" class="githits-cli-btn" data-copy="${escaped}" aria-label="Copy command: ${escaped}"><span class="githits-cli-cmd">${escaped}</span>${COPY_ICON_SVG}${CHECK_ICON_SVG}</button>`}function ctaBlock(introHtml,commands){const buttons=commands.map(commandButton).join(`
1751
+ `);return`<div class="cli-cta">
1752
+ <p class="tip">${introHtml}</p>
1753
+ ${buttons}
1754
+ </div>`}var COPY_BTN_CSS=`
1755
+ .wordmark {
1756
+ margin: 16px 0;
1757
+ }
1758
+ .cli-cta {
1759
+ display: flex;
1760
+ flex-direction: column;
1761
+ align-items: center;
1762
+ gap: 12px;
1763
+ margin: 16px 0 0;
1764
+ }
1765
+ .wordmark + .cli-cta {
1766
+ margin-top: 0;
1767
+ }
1768
+ .tip {
1769
+ font-family: 'Inter', sans-serif;
1770
+ font-weight: 400;
1771
+ font-size: 14px;
1772
+ line-height: 20px;
1773
+ color: #d5d9df;
1774
+ margin: 0;
1775
+ text-align: center;
1776
+ text-wrap: pretty;
1777
+ }
1778
+ .githits-cli-btn {
1779
+ display: inline-flex;
1780
+ align-items: center;
1781
+ gap: 0.5rem;
1782
+ background-color: rgba(255, 255, 255, 0.08);
1783
+ border: none;
1784
+ border-radius: 0.5rem;
1785
+ padding: 1rem 1.25rem;
1786
+ font-family: Consolas, ui-monospace, SFMono-Regular, Menlo, Monaco, monospace;
1787
+ font-size: 14px;
1788
+ font-weight: 500;
1789
+ color: #abb2bf;
1790
+ cursor: pointer;
1791
+ line-height: 1;
1792
+ transition: background-color 0.2s ease, transform 0.1s ease, color 0.2s ease;
1793
+ }
1794
+ .githits-cli-btn:hover {
1795
+ color: #d5d9df;
1796
+ }
1797
+ .githits-cli-btn:active {
1798
+ transform: scale(0.98);
1799
+ }
1800
+ .githits-cli-btn:focus-visible {
1801
+ outline: 2px solid #abb2bf;
1802
+ outline-offset: 2px;
1803
+ }
1804
+ .githits-cli-cmd {
1805
+ white-space: nowrap;
1806
+ }
1807
+ .githits-cli-icon {
1808
+ width: 14px;
1809
+ height: 14px;
1810
+ color: #abb2bf;
1811
+ flex-shrink: 0;
1812
+ }
1813
+ .githits-cli-btn.copied .githits-cli-icon-copy { display: none; }
1814
+ .githits-cli-btn:not(.copied) .githits-cli-icon-check { display: none; }
1815
+ .githits-cli-btn.copied .githits-cli-icon { color: #abb2bf; }`;var COPY_SCRIPT_HTML=`<script>
1816
+ (function() {
1817
+ var timers = new WeakMap();
1818
+ var buttons = document.querySelectorAll('.githits-cli-btn');
1819
+ for (var i = 0; i < buttons.length; i++) {
1820
+ buttons[i].addEventListener('click', function(e) {
1821
+ var target = e.currentTarget;
1822
+ var text = target.getAttribute('data-copy');
1823
+ if (!text || !navigator.clipboard) return;
1824
+ navigator.clipboard.writeText(text).then(function() {
1825
+ target.classList.add('copied');
1826
+ var existing = timers.get(target);
1827
+ if (existing) clearTimeout(existing);
1828
+ timers.set(target, setTimeout(function() {
1829
+ target.classList.remove('copied');
1830
+ timers.delete(target);
1831
+ }, 1500));
1832
+ });
1833
+ });
1834
+ }
1835
+ })();
1836
+ </script>`;var RETRY_CTA=ctaBlock("To try again, run these commands in your terminal:",["npx githits@latest logout","npx githits@latest login"]);var HELP_CTA=ctaBlock("Explore available commands with:",["npx githits@latest --help"]);function escapeHtml(text){return text.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}var METADATA_FILE="metadata.json";var DIR_MODE3=448;var FILE_MODE3=384;class AuthSessionMetadataStorage{fs;configDir;metadataPath;constructor(fs,configDir){this.fs=fs;this.configDir=configDir??getAuthFileStorageDir(fs);this.metadataPath=fs.joinPath(this.configDir,METADATA_FILE)}async load(baseUrl){const stored=await this.loadFile();if(!stored)return null;const metadata=stored.sessions[normalizeBaseUrl(baseUrl)]??null;return isAuthSessionMetadata(metadata)?metadata:null}async saveFromTokens(baseUrl,tokens){const stored=await this.loadFile()??{version:1,sessions:{}};stored.sessions[normalizeBaseUrl(baseUrl)]={createdAt:tokens.createdAt,expiresAt:tokens.expiresAt,updatedAt:new Date().toISOString()};await this.fs.ensureDir(this.configDir,DIR_MODE3);await this.fs.atomicWriteFile(this.metadataPath,JSON.stringify(stored,null,2),FILE_MODE3)}async clear(baseUrl){const stored=await this.loadFile();if(!stored)return;delete stored.sessions[normalizeBaseUrl(baseUrl)];if(Object.keys(stored.sessions).length===0){await this.fs.deleteFile(this.metadataPath);return}await this.fs.atomicWriteFile(this.metadataPath,JSON.stringify(stored,null,2),FILE_MODE3)}async loadFile(){if(!await this.fs.exists(this.metadataPath))return null;try{const content=await this.fs.readFile(this.metadataPath);const data=JSON.parse(content);if(data.version!==1||!data.sessions)return null;return data}catch{return null}}}function isAuthSessionMetadata(value){if(value===null||typeof value!=="object")return false;return typeof value.createdAt==="string"&&value.createdAt.length>0&&typeof value.updatedAt==="string"&&value.updatedAt.length>0&&(value.expiresAt===null||typeof value.expiresAt==="string"&&value.expiresAt.length>0)}import open from"open";class BrowserServiceImpl{async open(url){await open(url)}}var WINDOWS_MAX_ENTRY_SIZE=1200;var CHUNKED_PREFIX="CHUNKED:";var MAX_CHUNK_COUNT=100;function chunkKey(account,writeId,index){return`${account}:chunk:${writeId}:${index}`}function parseChunkedSentinel(value){if(!value.startsWith(CHUNKED_PREFIX))return null;const rest=value.slice(CHUNKED_PREFIX.length);const colonIndex=rest.indexOf(":");if(colonIndex===-1)return null;const writeId=rest.slice(0,colonIndex);if(writeId.length===0)return null;const countStr=rest.slice(colonIndex+1);const count=Number(countStr);if(!Number.isInteger(count)||count<=0)return null;return{writeId,count}}function splitIntoChunks(value,maxSize){if(value.length===0)return[""];const chunks=[];for(let offset=0;offset<value.length;offset+=maxSize){chunks.push(value.slice(offset,offset+maxSize))}return chunks}function generateWriteId(){let id;do{id=Math.random().toString(36).slice(2,8)}while(id.length<6);return id}class ChunkingKeyringService{inner;maxEntrySize;constructor(inner,maxEntrySize=WINDOWS_MAX_ENTRY_SIZE){this.inner=inner;this.maxEntrySize=maxEntrySize}getPassword(service,account){const value=this.inner.getPassword(service,account);if(value===null)return null;if(!value.startsWith(CHUNKED_PREFIX))return value;const sentinel=parseChunkedSentinel(value);if(sentinel===null)return null;const chunks=[];for(let i=0;i<sentinel.count;i++){const chunk=this.inner.getPassword(service,chunkKey(account,sentinel.writeId,i));if(chunk===null){console.error(`Warning: Incomplete chunked keychain entry for "${account}" (missing chunk ${i} of ${sentinel.count}). Treating as missing.`);return null}chunks.push(chunk)}return chunks.join("")}setPassword(service,account,password){const oldValue=this.readOldSentinel(service,account);if(password.length<=this.maxEntrySize){this.inner.setPassword(service,account,password)}else{const chunks=splitIntoChunks(password,this.maxEntrySize);if(chunks.length>MAX_CHUNK_COUNT){throw new Error(`Value requires ${chunks.length} chunks, exceeding maximum of ${MAX_CHUNK_COUNT}. `+`This likely indicates a bug — credential data should not be this large.`)}const writeId=generateWriteId();for(const[i,chunk]of chunks.entries()){this.inner.setPassword(service,chunkKey(account,writeId,i),chunk)}this.inner.setPassword(service,account,`${CHUNKED_PREFIX}${writeId}:${chunks.length}`)}if(oldValue!==null){this.deleteChunkEntries(service,account,oldValue)}}deletePassword(service,account){const oldValue=this.readOldSentinel(service,account);if(oldValue!==null){this.deleteChunkEntries(service,account,oldValue)}return this.inner.deletePassword(service,account)}readOldSentinel(service,account){try{const value=this.inner.getPassword(service,account);if(value===null)return null;return parseChunkedSentinel(value)}catch{return null}}deleteChunkEntries(service,account,sentinel){for(let i=0;i<sentinel.count;i++){try{this.inner.deletePassword(service,chunkKey(account,sentinel.writeId,i))}catch{}}}}import{randomUUID as randomUUID2}from"node:crypto";import{mkdir,mkdtemp,readdir,readFile,rename as renamePath,rmdir,stat,unlink,writeFile}from"node:fs/promises";import{homedir,tmpdir}from"node:os";import{dirname,join}from"node:path";class FileSystemServiceImpl{async readFile(path){return readFile(path,"utf-8")}async writeFile(path,contents,mode){await writeFile(path,contents,{mode})}async writeFileExclusive(path,contents,mode){await writeFile(path,contents,{mode,flag:"wx"})}async deleteFile(path){try{await unlink(path)}catch(error){if(error.code!=="ENOENT"){throw error}}}async deleteDirIfEmpty(path){try{await rmdir(path)}catch(error){const code=error.code;if(code!=="ENOENT"&&code!=="ENOTEMPTY"&&code!=="EEXIST"&&code!=="ENOTDIR"){throw error}}}async rename(source,destination){await renamePath(source,destination)}async exists(path){try{await stat(path);return true}catch{return false}}async ensureDir(path,mode){await mkdir(path,{recursive:true,mode})}async createTempDir(prefix){return mkdtemp(join(tmpdir(),prefix))}getHomeDir(){return homedir()}joinPath(...segments){return join(...segments)}getCwd(){return process.cwd()}getDirname(path){return dirname(path)}async readdir(path){return readdir(path)}async isDirectory(path){try{const stats=await stat(path);return stats.isDirectory()}catch{return false}}async atomicWriteFile(path,contents,maximumMode){const tmpPath=`${path}.${process.pid}.${randomUUID2()}.tmp`;const normalizedMaximum=maximumMode===undefined?undefined:maximumMode&511;let mode=normalizedMaximum??384;try{const existing=await stat(path);const existingMode=existing.mode&511;mode=normalizedMaximum===undefined?existingMode:existingMode&normalizedMaximum}catch{}try{await writeFile(tmpPath,contents,{mode});await renamePath(tmpPath,path)}catch(error){try{await unlink(tmpPath)}catch{}throw error}}}var SERVICE_NAME="githits";var TOKEN_PREFIX="v1:tokens:";var CLIENT_PREFIX="v1:client:";function parseJsonOrNull2(json){if(json===null)return null;try{const parsed=JSON.parse(json);if(typeof parsed!=="object"||parsed===null)return null;return parsed}catch{return null}}function isValidTokenData(data){if(typeof data!=="object"||data===null)return false;const d=data;return typeof d.accessToken==="string"&&d.accessToken.length>0&&typeof d.refreshToken==="string"&&d.refreshToken.length>0&&typeof d.createdAt==="string"&&d.createdAt.length>0&&(d.expiresAt===null||typeof d.expiresAt==="string"&&d.expiresAt.length>0)}function isValidClientRegistration(data){if(typeof data!=="object"||data===null)return false;const d=data;return typeof d.clientId==="string"&&d.clientId.length>0&&typeof d.clientSecret==="string"&&d.clientSecret.length>0&&typeof d.redirectUri==="string"&&d.redirectUri.length>0&&typeof d.registeredAt==="string"&&d.registeredAt.length>0}class KeychainAuthStorage{keyring;constructor(keyring){this.keyring=keyring}async loadTokens(baseUrl){const key=`${TOKEN_PREFIX}${normalizeBaseUrl(baseUrl)}`;const json=this.keyring.getPassword(SERVICE_NAME,key);const data=parseJsonOrNull2(json);if(data!==null&&!isValidTokenData(data))return null;return data}async saveTokens(baseUrl,data){const key=`${TOKEN_PREFIX}${normalizeBaseUrl(baseUrl)}`;this.keyring.setPassword(SERVICE_NAME,key,JSON.stringify(data))}async saveTokensIfUnchanged(baseUrl,expected,data){const current=await this.loadTokens(baseUrl);if(!sameTokenData(current,expected))return false;await this.saveTokens(baseUrl,data);return true}async clearTokens(baseUrl){const key=`${TOKEN_PREFIX}${normalizeBaseUrl(baseUrl)}`;this.keyring.deletePassword(SERVICE_NAME,key)}async clearTokensIfUnchanged(baseUrl,expected){const current=await this.loadTokens(baseUrl);if(!sameTokenData(current,expected))return false;await this.clearTokens(baseUrl);return true}clearActiveTokensIfUnchanged(baseUrl,expected){return this.clearTokensIfUnchanged(baseUrl,expected)}async loadClient(baseUrl){const key=`${CLIENT_PREFIX}${normalizeBaseUrl(baseUrl)}`;const json=this.keyring.getPassword(SERVICE_NAME,key);const data=parseJsonOrNull2(json);if(data!==null&&!isValidClientRegistration(data))return null;return data}async saveClient(baseUrl,data){const key=`${CLIENT_PREFIX}${normalizeBaseUrl(baseUrl)}`;this.keyring.setPassword(SERVICE_NAME,key,JSON.stringify(data))}async clearClient(baseUrl){const key=`${CLIENT_PREFIX}${normalizeBaseUrl(baseUrl)}`;this.keyring.deletePassword(SERVICE_NAME,key)}clearActiveClient(baseUrl){return this.clearClient(baseUrl)}async saveAuthSession(baseUrl,client,tokens){await this.saveClient(baseUrl,client);await this.saveTokens(baseUrl,tokens)}async clearAuthSession(baseUrl){await clearAuthSessionBestEffort(()=>this.clearTokens(baseUrl),()=>this.clearClient(baseUrl))}getStorageLocation(){switch(process.platform){case"darwin":return"macOS Keychain (githits)";case"win32":return"Windows Credential Manager (githits)";default:return"System keychain (githits)"}}}import{Entry}from"@napi-rs/keyring";class KeychainUnavailableError extends Error{constructor(message,cause){super(message);this.name="KeychainUnavailableError";this.cause=cause}}function wrapKeyringError(error){const message=error instanceof Error?error.message:String(error);throw new KeychainUnavailableError(`System keychain unavailable: ${message}`,error)}class KeyringServiceImpl{getPassword(service,account){try{return new Entry(service,account).getPassword()}catch(error){wrapKeyringError(error)}}setPassword(service,account,password){try{new Entry(service,account).setPassword(password)}catch(error){wrapKeyringError(error)}}deletePassword(service,account){try{return new Entry(service,account).deleteCredential()}catch(error){wrapKeyringError(error)}}}import{AsyncLocalStorage}from"node:async_hooks";import{execFile}from"node:child_process";import{createHash as createHash3,randomUUID as randomUUID3}from"node:crypto";import{mkdir as mkdir2}from"node:fs/promises";import{dirname as dirname2}from"node:path";import{promisify}from"node:util";var LOCK_DIR="auth.lock";var LOCK_TIMEOUT_MS=DEFAULT_FETCH_TIMEOUT_MS*2+1e4;var LOCK_RETRY_MS=25;var LOCK_OWNER_RECHECK_MS=1000;var ORPHANED_LOCK_MS=5000;var OWNER_FILE="owner.json";var RECLAIM_FILE_PREFIX="reclaim-";var RELEASE_DIR_PREFIX=`${LOCK_DIR}.release-`;var RECLAIM_OWNER_HASH_PATTERN=/^[0-9a-f]{64}$/;var MAX_NODE_PROCESS_ID=2147483647;var PROCESS_IDENTITY_LOOKUP_TIMEOUT_MS=5000;var RELEASE_OWNER_READ_ATTEMPTS=3;var CLEANUP_FILE_DELETE_ATTEMPTS=3;var execFileAsync=promisify(execFile);class AuthStorageLockTimeoutError extends Error{constructor(message){super(message);this.name="AuthStorageLockTimeoutError"}}function withAuthStorageLock(storage,fn){return storage.withAuthStorageLock(fn)}class LockedAuthStorage{storage;fileSystemService;lockPath;lockTimeoutMs;isOwnerAlive;processStartedAtLookup;currentProcessStartedAtPromise;lockContext=new AsyncLocalStorage;currentOwner=null;lockLoads;constructor(storage,fileSystemService,options={}){this.storage=storage;this.fileSystemService=fileSystemService;this.lockTimeoutMs=options.lockTimeoutMs??LOCK_TIMEOUT_MS;this.processStartedAtLookup=options.getProcessStartedAt??getProcessStartedAt;this.isOwnerAlive=options.isOwnerAlive??((pid,processStartedAt)=>isOriginalProcessAlive(pid,processStartedAt,pid===process.pid?()=>this.getCurrentProcessStartedAt():this.processStartedAtLookup));this.lockLoads=storage.requiresLoadLock===true;this.lockPath=fileSystemService.joinPath(getAuthLockDir(fileSystemService),LOCK_DIR)}loadTokens(baseUrl){return this.lockLoads?this.withAuthStorageLock(()=>this.storage.loadTokens(baseUrl)):this.storage.loadTokens(baseUrl)}saveTokens(baseUrl,data){return this.withAuthStorageLock(()=>this.storage.saveTokens(baseUrl,data))}saveTokensIfUnchanged(baseUrl,expected,data){return this.withAuthStorageLock(()=>this.storage.saveTokensIfUnchanged(baseUrl,expected,data))}clearTokens(baseUrl){return this.withAuthStorageLock(()=>this.storage.clearTokens(baseUrl))}clearTokensIfUnchanged(baseUrl,expected){return this.withAuthStorageLock(()=>this.storage.clearTokensIfUnchanged(baseUrl,expected))}clearActiveTokensIfUnchanged(baseUrl,expected){return this.withAuthStorageLock(()=>this.storage.clearActiveTokensIfUnchanged(baseUrl,expected))}loadClient(baseUrl){return this.lockLoads?this.withAuthStorageLock(()=>this.storage.loadClient(baseUrl)):this.storage.loadClient(baseUrl)}saveClient(baseUrl,data){return this.withAuthStorageLock(()=>this.storage.saveClient(baseUrl,data))}clearClient(baseUrl){return this.withAuthStorageLock(()=>this.storage.clearClient(baseUrl))}clearActiveClient(baseUrl){return this.withAuthStorageLock(()=>this.storage.clearActiveClient(baseUrl))}saveAuthSession(baseUrl,client,tokens){return this.withAuthStorageLock(()=>this.storage.saveAuthSession(baseUrl,client,tokens))}clearAuthSession(baseUrl){return this.withAuthStorageLock(()=>this.storage.clearAuthSession(baseUrl))}getStorageLocation(){return this.storage.getStorageLocation()}async withAuthStorageLock(fn){const ownerId=this.lockContext.getStore();if(ownerId&&this.currentOwner?.id===ownerId){return fn()}const acquiredOwner=await this.acquireLock();try{return await this.lockContext.run(acquiredOwner.id,fn)}finally{await this.releaseLock(acquiredOwner)}}async acquireLock(){const processStartedAt=await this.getCurrentProcessStartedAt();const startedAt=Date.now();let nextOwnerCheckAt=0;await mkdir2(dirname2(this.lockPath),{recursive:true,mode:448});while(true){try{await mkdir2(this.lockPath,{recursive:false,mode:448});try{const owner=await this.writeOwner(processStartedAt);return owner}catch(error){const code=error.code;if(code==="EEXIST"||code==="ENOENT"){if(Date.now()-startedAt>=this.lockTimeoutMs){throw this.createLockTimeoutError()}await sleep(LOCK_RETRY_MS);continue}await this.fileSystemService.deleteDirIfEmpty(this.lockPath).catch(()=>{return});throw error}}catch(error){if(error.code!=="EEXIST")throw error;const now=Date.now();if(now>=nextOwnerCheckAt){await this.reclaimStaleLock();nextOwnerCheckAt=Date.now()+LOCK_OWNER_RECHECK_MS}if(Date.now()-startedAt>=this.lockTimeoutMs){throw this.createLockTimeoutError()}await sleep(LOCK_RETRY_MS)}}}createLockTimeoutError(){return new AuthStorageLockTimeoutError(`Timed out waiting for GitHits auth storage lock at ${this.lockPath}. After stopping all GitHits CLI and MCP processes, remove this directory and retry.`)}getCurrentProcessStartedAt(){if(!this.currentProcessStartedAtPromise){const lookup=this.processStartedAtLookup(process.pid);this.currentProcessStartedAtPromise=lookup;lookup.then((startedAt)=>{if(startedAt===null&&this.currentProcessStartedAtPromise===lookup){this.currentProcessStartedAtPromise=undefined}},()=>{if(this.currentProcessStartedAtPromise===lookup){this.currentProcessStartedAtPromise=undefined}})}return this.currentProcessStartedAtPromise}async writeOwner(processStartedAt){const owner={id:randomUUID3(),pid:process.pid,createdAt:new Date().toISOString(),processStartedAt};await this.fileSystemService.writeFileExclusive(this.ownerPath(),JSON.stringify(owner),384);this.currentOwner=owner;return owner}async reclaimStaleLock(){const ownerResult=await this.readOwner();if(ownerResult.state==="missing"){await this.reclaimOldOwnerlessLock();return}if(ownerResult.state==="unknown")return;const owner=ownerResult.owner;const ownerDead=!await this.isOwnerAlive(owner.pid,owner.processStartedAt);if(!ownerDead)return;await this.reclaimProvenDeadOwner(owner)}async reclaimProvenDeadOwner(owner){const claimPath=this.reclaimPath(owner.id);try{await this.fileSystemService.writeFileExclusive(claimPath,"",384)}catch{return}const currentOwner=await this.readOwner();let removedExpectedOwner=false;if(currentOwner.state==="present"&&currentOwner.owner.id===owner.id){removedExpectedOwner=await this.deleteFileForCleanup(this.ownerPath())}if(!await this.deleteFileForCleanup(claimPath)){return}if(!removedExpectedOwner)return;await this.fileSystemService.deleteDirIfEmpty(this.lockPath).catch(()=>{return})}async reclaimOldOwnerlessLock(){const createdAtMs=await lockCreatedAtMs(this.lockPath);if(Date.now()-createdAtMs<ORPHANED_LOCK_MS)return;let entries;try{entries=await this.fileSystemService.readdir(this.lockPath)}catch{return}if(entries.some((entry)=>!isReclaimFileName(entry)))return;for(const entry of entries){const claimPath=this.fileSystemService.joinPath(this.lockPath,entry);if(!await this.deleteFileForCleanup(claimPath))return}await this.fileSystemService.deleteDirIfEmpty(this.lockPath).catch(()=>{return})}async readOwner(){let raw;try{raw=await this.fileSystemService.readFile(this.ownerPath())}catch(error){return error.code==="ENOENT"?{state:"missing"}:{state:"unknown"}}try{const parsed=JSON.parse(raw);if(typeof parsed.id!=="string"||typeof parsed.pid!=="number"||!Number.isSafeInteger(parsed.pid)||parsed.pid<=0||parsed.pid>MAX_NODE_PROCESS_ID||typeof parsed.createdAt!=="string"||!(typeof parsed.processStartedAt==="string"||parsed.processStartedAt===null)){return{state:"unknown"}}const owner={id:parsed.id,pid:parsed.pid,createdAt:parsed.createdAt,processStartedAt:parsed.processStartedAt};return{state:"present",owner}}catch{return{state:"unknown"}}}async releaseLock(owner){if(this.currentOwner?.id===owner.id)this.currentOwner=null;const currentOwner=await this.readOwnerForRelease();if(currentOwner.state!=="present"||currentOwner.owner.id!==owner.id)return;if(!await this.deleteFileForCleanup(this.ownerPath()))return;const releasePath=this.releasePath(owner.id);try{await this.fileSystemService.rename(this.lockPath,releasePath)}catch{return}await this.fileSystemService.deleteDirIfEmpty(releasePath).catch(()=>{return})}ownerPath(){return this.fileSystemService.joinPath(this.lockPath,OWNER_FILE)}reclaimPath(ownerId){const ownerHash=createHash3("sha256").update(ownerId).digest("hex");return this.fileSystemService.joinPath(this.lockPath,`${RECLAIM_FILE_PREFIX}${ownerHash}`)}releasePath(ownerId){const ownerHash=createHash3("sha256").update(ownerId).digest("hex");return this.fileSystemService.joinPath(this.fileSystemService.getDirname(this.lockPath),`${RELEASE_DIR_PREFIX}${ownerHash}`)}async readOwnerForRelease(){let result=await this.readOwner();for(let attempt=1;result.state==="unknown"&&attempt<RELEASE_OWNER_READ_ATTEMPTS;attempt+=1){await sleep(LOCK_RETRY_MS);result=await this.readOwner()}return result}async deleteFileForCleanup(path){for(let attempt=1;attempt<=CLEANUP_FILE_DELETE_ATTEMPTS;attempt+=1){try{await this.fileSystemService.deleteFile(path);return true}catch(error){const code=error.code;const retryable=code==="EACCES"||code==="EBUSY"||code==="EPERM";if(!retryable||attempt===CLEANUP_FILE_DELETE_ATTEMPTS)return false;await sleep(LOCK_RETRY_MS)}}return false}}function sleep(ms){return new Promise((resolve)=>setTimeout(resolve,ms))}function isReclaimFileName(entry){return entry.startsWith(RECLAIM_FILE_PREFIX)&&RECLAIM_OWNER_HASH_PATTERN.test(entry.slice(RECLAIM_FILE_PREFIX.length))}async function isOriginalProcessAlive(pid,processStartedAt,getStartedAt){if(!isProcessAlive(pid))return false;if(!processStartedAt)return true;let observedStartedAt;try{observedStartedAt=await getStartedAt(pid)}catch{return true}if(!observedStartedAt)return true;return observedStartedAt===processStartedAt}function isProcessAlive(pid){if(pid<=0)return false;try{process.kill(pid,0);return true}catch(error){const code=error.code;return code!=="ESRCH"}}async function getProcessStartedAt(pid){try{if(process.platform==="win32"){const{stdout}=await execFileAsync("powershell.exe",["-NoProfile","-Command",`(Get-Process -Id ${pid}).StartTime.ToUniversalTime().ToString('o')`],{timeout:PROCESS_IDENTITY_LOOKUP_TIMEOUT_MS,killSignal:"SIGKILL",windowsHide:true});return stdout.trim()||null}const{stdout}=await execFileAsync("ps",["-p",String(pid),"-o","lstart="],{timeout:PROCESS_IDENTITY_LOOKUP_TIMEOUT_MS,killSignal:"SIGKILL"});const parsed=Date.parse(stdout.trim());return Number.isNaN(parsed)?null:new Date(parsed).toISOString()}catch{return null}}async function lockCreatedAtMs(path){try{const{stat}=await import("node:fs/promises");return(await stat(path)).mtimeMs}catch{return 0}}class AuthStoragePolicyError extends Error{constructor(message){super(message);this.name="AuthStoragePolicyError"}}function createFileAuthStorageGuidance(configPath){return`OAuth credentials were not saved to plaintext file storage.
1837
+
1838
+ Options:
1839
+ 1. Unlock or fix your system keychain.
1840
+ 2. Use GITHITS_API_TOKEN for CI/automation.
1841
+ 3. If you accept storing OAuth credentials unencrypted on disk, set:
1842
+
1843
+ [auth]
1844
+ storage = "file"
1845
+
1846
+ in ${configPath}, or run with GITHITS_AUTH_STORAGE=file.
1847
+
1848
+ Warning: file storage is plaintext. Use it only on machines where local file access is trusted.`}class ModeAwareFileAuthStorage{storage;mode;configPath;constructor(storage,mode,configPath="your GitHits config.toml"){this.storage=storage;this.mode=mode;this.configPath=configPath}loadTokens(baseUrl){return this.storage.loadTokens(baseUrl)}async saveTokens(baseUrl,data){this.assertFileMode();await this.storage.saveTokens(baseUrl,data)}async saveTokensIfUnchanged(baseUrl,expected,data){this.assertFileMode();return this.storage.saveTokensIfUnchanged(baseUrl,expected,data)}clearTokens(baseUrl){return this.storage.clearTokens(baseUrl)}clearTokensIfUnchanged(baseUrl,expected){return this.storage.clearTokensIfUnchanged(baseUrl,expected)}clearActiveTokensIfUnchanged(baseUrl,expected){return this.storage.clearActiveTokensIfUnchanged(baseUrl,expected)}loadClient(baseUrl){return this.storage.loadClient(baseUrl)}async saveClient(baseUrl,data){this.assertFileMode();await this.storage.saveClient(baseUrl,data)}clearClient(baseUrl){return this.storage.clearClient(baseUrl)}clearActiveClient(baseUrl){return this.storage.clearActiveClient(baseUrl)}async saveAuthSession(baseUrl,client,tokens){this.assertFileMode();await this.storage.saveAuthSession(baseUrl,client,tokens)}clearAuthSession(baseUrl){return this.storage.clearAuthSession(baseUrl)}getStorageLocation(){return this.storage.getStorageLocation()}assertFileMode(){if(this.mode==="file")return;throw new AuthStoragePolicyError(createFileAuthStorageGuidance(this.configPath))}}class MigratingAuthStorage{primary;file;legacy;mode;configPath;onWarning;metadata;additionalLegacyStores;warnedAmbiguousPlaintext=false;requiresLoadLock;constructor(primary,file,legacy,mode,configPath="your GitHits config.toml",onWarning=()=>{},metadata,additionalLegacyStores=[]){this.primary=primary;this.file=file;this.legacy=legacy;this.mode=mode;this.configPath=configPath;this.onWarning=onWarning;this.metadata=metadata;this.additionalLegacyStores=additionalLegacyStores;this.requiresLoadLock=mode==="file"}async loadTokens(baseUrl){if(this.mode==="file"){return this.loadTokensFileMode(baseUrl)}return this.loadTokensKeychainMode(baseUrl)}async saveTokens(baseUrl,data){if(this.mode==="file"){await this.file.saveTokens(baseUrl,data);await this.saveMetadataBestEffort(baseUrl,data);return}try{await this.primary.saveTokens(baseUrl,data);await this.saveMetadataBestEffort(baseUrl,data)}catch(error){throw this.toPolicyError(error)}}async saveTokensIfUnchanged(baseUrl,expected,data){const current=await this.loadTokens(baseUrl);if(!this.sameTokenData(current,expected))return false;await this.saveTokens(baseUrl,data);return true}async clearTokens(baseUrl){const primaryError=await this.clearBestEffort(()=>this.primary.clearTokens(baseUrl));await this.clearBestEffort(()=>this.file.clearTokens(baseUrl));await this.clearBestEffort(()=>this.legacy.clearTokens(baseUrl));for(const legacy of this.additionalLegacyStores){await this.clearBestEffort(()=>legacy.clearTokens(baseUrl))}await this.clearBestEffort(()=>this.metadata?.clear(baseUrl)??Promise.resolve());if(primaryError&&!(primaryError instanceof KeychainUnavailableError)){throw primaryError}}async clearTokensIfUnchanged(baseUrl,expected){const current=await this.loadTokens(baseUrl);if(!this.sameTokenData(current,expected))return false;await this.clearTokens(baseUrl);return true}async clearActiveTokensIfUnchanged(baseUrl,expected){const current=await this.currentActiveTokens(baseUrl);if(!this.sameTokenData(current,expected))return false;let firstError;for(const store of this.activeStores()){const error=await this.clearBestEffort(()=>store.clearTokens(baseUrl));firstError??=error}const metadataError=await this.clearBestEffort(()=>this.metadata?.clear(baseUrl)??Promise.resolve());firstError??=metadataError;if(firstError&&!(firstError instanceof KeychainUnavailableError)){throw firstError}return true}async loadClient(baseUrl){if(this.mode==="file"){return this.loadClientFileMode(baseUrl)}return this.loadClientKeychainMode(baseUrl)}async saveClient(baseUrl,data){if(this.mode==="file"){await this.file.saveClient(baseUrl,data);return}try{await this.primary.saveClient(baseUrl,data)}catch(error){throw this.toPolicyError(error)}}async clearClient(baseUrl){const primaryError=await this.clearBestEffort(()=>this.primary.clearClient(baseUrl));await this.clearBestEffort(()=>this.file.clearClient(baseUrl));await this.clearBestEffort(()=>this.legacy.clearClient(baseUrl));for(const legacy of this.additionalLegacyStores){await this.clearBestEffort(()=>legacy.clearClient(baseUrl))}if(primaryError&&!(primaryError instanceof KeychainUnavailableError)){throw primaryError}}async clearActiveClient(baseUrl){let firstError;for(const store of this.activeStores()){const error=await this.clearBestEffort(()=>store.clearClient(baseUrl));firstError??=error}if(firstError&&!(firstError instanceof KeychainUnavailableError)){throw firstError}}async saveAuthSession(baseUrl,client,tokens){if(this.mode==="file"){await this.file.saveAuthSession(baseUrl,client,tokens);await this.saveMetadataBestEffort(baseUrl,tokens);return}try{await this.primary.saveAuthSession(baseUrl,client,tokens);await this.saveMetadataBestEffort(baseUrl,tokens)}catch(error){throw this.toPolicyError(error)}}async clearAuthSession(baseUrl){const primaryError=await this.clearBestEffort(()=>this.primary.clearAuthSession(baseUrl));await this.clearBestEffort(()=>this.file.clearAuthSession(baseUrl));await this.clearBestEffort(()=>this.legacy.clearAuthSession(baseUrl));for(const legacy of this.additionalLegacyStores){await this.clearBestEffort(()=>legacy.clearAuthSession(baseUrl))}await this.clearBestEffort(()=>this.metadata?.clear(baseUrl)??Promise.resolve());if(primaryError&&!(primaryError instanceof KeychainUnavailableError)){throw primaryError}}getStorageLocation(){return this.mode==="file"?this.file.getStorageLocation():this.primary.getStorageLocation()}async loadTokensKeychainMode(baseUrl){try{const primaryTokens=await this.primary.loadTokens(baseUrl);if(primaryTokens){await this.saveMetadataBestEffort(baseUrl,primaryTokens);return primaryTokens}}catch(error){throw this.toPolicyError(error)}return null}async loadTokensFileMode(baseUrl){const candidate=await this.selectPlaintextTokenCandidate(baseUrl);if(candidate){if(candidate.ambiguous){await this.file.saveTokens(baseUrl,candidate.data);for(const legacy of this.getLegacyStores()){await this.clearBestEffort(()=>legacy.clearTokens(baseUrl))}}else if(candidate.source==="legacy"){await this.file.saveTokens(baseUrl,candidate.data);await this.clearBestEffort(()=>candidate.storage.clearTokens(baseUrl))}await this.saveMetadataBestEffort(baseUrl,candidate.data);return candidate.data}return null}async loadClientKeychainMode(baseUrl){try{const primaryClient=await this.primary.loadClient(baseUrl);if(primaryClient)return primaryClient}catch(error){throw this.toPolicyError(error)}return null}async loadClientFileMode(baseUrl){const candidate=await this.selectPlaintextClientCandidate(baseUrl);if(candidate){if(candidate.ambiguous){await this.file.saveClient(baseUrl,candidate.data);for(const legacy of this.getLegacyStores()){await this.clearBestEffort(()=>legacy.clearClient(baseUrl))}}else if(candidate.source==="legacy"){await this.file.saveClient(baseUrl,candidate.data);await this.clearBestEffort(()=>candidate.storage.clearClient(baseUrl))}return candidate.data}return null}async selectPlaintextTokenCandidate(baseUrl){const candidates=[];const fileTokens=await this.file.loadTokens(baseUrl);if(fileTokens){candidates.push({data:fileTokens,source:"file",storage:this.file,timestamp:fileTokens.createdAt,ambiguous:false})}for(const legacy of this.getLegacyStores()){const legacyTokens=await legacy.loadTokens(baseUrl);if(legacyTokens){candidates.push({data:legacyTokens,source:"legacy",storage:legacy,timestamp:legacyTokens.createdAt,ambiguous:false})}}return this.selectNewestCandidate(candidates)}async selectPlaintextClientCandidate(baseUrl){const candidates=[];const fileClient=await this.file.loadClient(baseUrl);if(fileClient){candidates.push({data:fileClient,source:"file",storage:this.file,timestamp:fileClient.registeredAt,ambiguous:false})}for(const legacy of this.getLegacyStores()){const legacyClient=await legacy.loadClient(baseUrl);if(legacyClient){candidates.push({data:legacyClient,source:"legacy",storage:legacy,timestamp:legacyClient.registeredAt,ambiguous:false})}}return this.selectNewestCandidate(candidates)}selectNewestCandidate(candidates){if(candidates.length===0)return null;if(candidates.length===1)return candidates[0]??null;const parsed=candidates.map((candidate)=>({candidate,timestampMs:Date.parse(candidate.timestamp)}));if(parsed.some((entry)=>Number.isNaN(entry.timestampMs))){return this.selectCanonicalAmbiguousCandidate(candidates)}const sorted=[...parsed].sort((a,b)=>b.timestampMs-a.timestampMs);const first=sorted[0];const second=sorted[1];if(!first)return candidates[0]??null;if(second&&first.timestampMs===second.timestampMs){return this.selectCanonicalAmbiguousCandidate(candidates)}return first.candidate}selectCanonicalAmbiguousCandidate(candidates){const selected=candidates.find((candidate)=>candidate.source==="file")??null;if(!selected){this.warnAmbiguousPlaintext();return null}selected.ambiguous=true;return selected}getLegacyStores(){return[...this.additionalLegacyStores,this.legacy]}activeStores(){return this.mode==="file"?[this.file,...this.getLegacyStores()]:[this.primary]}async currentActiveTokens(baseUrl){if(this.mode==="file"){const candidate=await this.selectPlaintextTokenCandidate(baseUrl);return candidate?.data??null}try{return await this.primary.loadTokens(baseUrl)}catch(error){throw this.toPolicyError(error)}}async clearBestEffort(fn){try{await fn();return}catch(error){return error}}async saveMetadataBestEffort(baseUrl,tokens){await this.clearBestEffort(()=>this.metadata?.saveFromTokens(baseUrl,tokens)??Promise.resolve())}toPolicyError(error){if(!(error instanceof KeychainUnavailableError))return error;return new AuthStoragePolicyError(`System keychain is unavailable. ${createFileAuthStorageGuidance(this.configPath)}`)}warnAmbiguousPlaintext(){if(this.warnedAmbiguousPlaintext)return;this.warnedAmbiguousPlaintext=true;this.onWarning("Warning: multiple legacy plaintext auth entries exist with ambiguous timestamps; no canonical config-path entry was found, so the legacy entries were left intact.")}sameTokenData(a,b){if(a===null||b===null)return a===b;return a.accessToken===b.accessToken&&a.refreshToken===b.refreshToken&&a.expiresAt===b.expiresAt&&a.createdAt===b.createdAt}}import{ProxyAgent,fetch as undiciFetch}from"undici";var NODE_USE_ENV_PROXY="NODE_USE_ENV_PROXY";var USE_ENV_PROXY_FLAG="--use-env-proxy";function createCliFetch(options={}){const env=options.env??process.env;const baseFetch=options.baseFetch??globalThis.fetch;const proxyConfig=getProxyConfig(env);if(!proxyConfig.httpProxy&&!proxyConfig.httpsProxy){return baseFetch}if(isNativeEnvProxyActive({env,execArgv:options.execArgv??process.execArgv,nodeOptions:options.nodeOptions??env.NODE_OPTIONS,nodeVersion:options.nodeVersion??process.versions.node})){return baseFetch}validateProxySelection(proxyConfig.httpProxy);validateProxySelection(proxyConfig.httpsProxy);const fetchWithDispatcher=options.undiciFetch??undiciFetch;const createProxyAgent=options.createProxyAgent??((proxyUrl)=>new ProxyAgent({uri:proxyUrl,proxyTunnel:false}));const proxyAgents=new Map;return async(input,init)=>{const targetUrl=getRequestUrl(input);if(!targetUrl){return baseFetch(input,init)}const proxy=resolveProxyForUrl(targetUrl,proxyConfig);if(!proxy){return baseFetch(input,init)}let dispatcher=proxyAgents.get(proxy.value);if(!dispatcher){dispatcher=createProxyAgent(proxy.value);proxyAgents.set(proxy.value,dispatcher)}try{const undiciInit={...init,dispatcher};return await fetchWithDispatcher(input,undiciInit)}catch(error){throw createSanitizedProxyRequestError(proxy,error)}}}function createLazyCliFetch(options={}){let fetchFn;return async(input,init)=>{fetchFn??=createCliFetch(options);return await fetchFn(input,init)}}function getProxyConfig(env){return{httpProxy:getEnvSelection(env,"HTTP_PROXY"),httpsProxy:getEnvSelection(env,"HTTPS_PROXY"),noProxy:getEnvSelection(env,"NO_PROXY")?.value}}function isNativeEnvProxyActive(options){const envOptIn=options.env[NODE_USE_ENV_PROXY]==="1";const flagOptIn=hasUseEnvProxyFlag(options.execArgv)||hasUseEnvProxyFlag(splitNodeOptions(options.nodeOptions));if(envOptIn&&supportsNativeEnvProxyEnv(options.nodeVersion)){return true}return flagOptIn&&supportsNativeEnvProxyFlag(options.nodeVersion)}function resolveProxyForUrl(targetUrl,proxyConfig){if(shouldBypassProxy(targetUrl,proxyConfig.noProxy)){return}if(targetUrl.protocol==="http:"){return proxyConfig.httpProxy}if(targetUrl.protocol==="https:"){return proxyConfig.httpsProxy??proxyConfig.httpProxy}return}function redactProxyUrl(value){try{const url=new URL(value);url.username="";url.password="";url.pathname="";url.search="";url.hash="";return url.toString()}catch{return"<invalid proxy URL>"}}function getEnvSelection(env,upperName){const lowerName=upperName.toLowerCase();if(hasEnvKey(env,lowerName)){const lowerValue=env[lowerName];return lowerValue?{name:lowerName,value:lowerValue}:undefined}if(hasEnvKey(env,upperName)){const upperValue=env[upperName];return upperValue?{name:upperName,value:upperValue}:undefined}return}function hasEnvKey(env,key){return Object.hasOwn(env,key)}function validateProxySelection(selection){if(!selection){return}let parsed;try{parsed=new URL(selection.value)}catch{throw new Error(`${selection.name} must be an http:// or https:// proxy URL.`)}if(parsed.protocol!=="http:"&&parsed.protocol!=="https:"||!parsed.host){throw new Error(`${selection.name} must be an http:// or https:// proxy URL.`)}}function getRequestUrl(input){try{if(typeof input==="string"||input instanceof URL){return new URL(input)}if(typeof Request!=="undefined"&&input instanceof Request){return new URL(input.url)}}catch{return}return}function shouldBypassProxy(targetUrl,noProxy){if(!noProxy){return false}if(noProxy.trim()==="*"){return true}const hostname=normalizeHostname(targetUrl.hostname);const port=Number.parseInt(targetUrl.port,10)||defaultPort(targetUrl);for(const rawEntry of noProxy.split(/[,\s]/)){const entry=rawEntry.trim().toLowerCase();if(!entry){continue}if(entry==="*"){return true}const{host:entryHost,port:entryPort}=parseNoProxyEntry(entry);if(entryPort&&entryPort!==port){continue}if(matchesNoProxyHost(hostname,entryHost)){return true}}return false}function matchesNoProxyHost(hostname,entryHost){const normalizedEntryHost=entryHost.replace(/^\*?\./,"");return hostname===normalizedEntryHost||hostname.endsWith(`.${normalizedEntryHost}`)}function parseNoProxyEntry(entry){const bracketedIpv6=entry.match(/^\[([^\]]+)\](?::(\d+))?$/);if(bracketedIpv6?.[1]){return{host:normalizeHostname(bracketedIpv6[1]),port:bracketedIpv6[2]?Number.parseInt(bracketedIpv6[2],10):0}}if(entry.includes(":")){const lastColon=entry.lastIndexOf(":");const maybePort=entry.slice(lastColon+1);const hostPart=entry.slice(0,lastColon);if(!hostPart.includes(":")&&/^\d+$/.test(maybePort)){return{host:normalizeHostname(hostPart),port:Number.parseInt(maybePort,10)}}return{host:normalizeHostname(entry),port:0}}return{host:normalizeHostname(entry),port:0}}function normalizeHostname(hostname){return hostname.replace(/^\[|\]$/g,"").toLowerCase()}function defaultPort(url){if(url.protocol==="http:"){return 80}if(url.protocol==="https:"){return 443}return 0}function hasUseEnvProxyFlag(args){return args.some((arg)=>arg===USE_ENV_PROXY_FLAG)}function splitNodeOptions(value){if(!value){return[]}return value.match(/(?:[^\s"']+|"[^"]*"|'[^']*')+/g)??[]}function supportsNativeEnvProxyEnv(nodeVersion){const parsed=parseNodeVersion(nodeVersion);if(!parsed){return false}const[major,minor]=parsed;if(major===22){return minor>=21}if(major===23){return false}return major>=24}function supportsNativeEnvProxyFlag(nodeVersion){const parsed=parseNodeVersion(nodeVersion);if(!parsed){return false}const[major,minor]=parsed;if(major===22){return minor>=21}if(major===24){return minor>=5}return major>=25}function parseNodeVersion(value){const match=value.match(/^(\d+)\.(\d+)\./);if(!match?.[1]||!match[2]){return}return[Number.parseInt(match[1],10),Number.parseInt(match[2],10)]}function createSanitizedProxyRequestError(proxy,error){const reason=sanitizeErrorMessage(error);return new Error(`Proxy request failed using ${proxy.name} (${redactProxyUrl(proxy.value)})${reason?`: ${reason}`:"."}`)}function sanitizeErrorMessage(error){if(!(error instanceof Error)||!error.message){return""}return error.message.replace(/https?:\/\/\S+/gi,(match)=>redactProxyUrl(match)).replace(/\b(?!https?:)[A-Za-z][A-Za-z0-9+.-]*:\/\/\S+/gi,"<redacted URL>")}import{writeSync}from"node:fs";var ENABLED_VALUES=new Set(["1","true","yes","on"]);function isTelemetryEnabled(env=process.env){const raw=env.GITHITS_TELEMETRY?.trim().toLowerCase();if(!raw)return false;return ENABLED_VALUES.has(raw)}class TelemetryCollector{enabled;now;write;sessionStartMs;spans=[];activeSpans=new Map;nextId=1;flushed=false;constructor(options={}){this.enabled=isTelemetryEnabled(options.env);this.now=options.now??(()=>globalThis.performance.now());this.write=options.write??((text)=>writeSync(process.stderr.fd,text));this.sessionStartMs=this.now()}isEnabled(){return this.enabled}startSpan(name,attributes){if(!this.enabled)return;const span={id:this.nextId++,name,startMs:this.now(),attributes:sanitiseAttributes(attributes)};this.spans.push(span);this.activeSpans.set(span.id,span);return{id:span.id}}endSpan(handle,attributes){if(!this.enabled||!handle)return;const span=this.activeSpans.get(handle.id);if(!span||span.endMs!==undefined)return;span.endMs=this.now();span.attributes=mergeAttributes(span.attributes,attributes);this.activeSpans.delete(handle.id)}flush(exitCode=0){if(!this.enabled||this.flushed)return;const nowMs=this.now();for(const span of this.activeSpans.values()){if(span.endMs!==undefined)continue;span.endMs=nowMs;span.endedAtExit=true}this.activeSpans.clear();this.write(formatTelemetryReport(this.spans,this.sessionStartMs,nowMs,exitCode));this.flushed=true}}async function withTelemetrySpan(name,operation,attributes){const handle=telemetryCollector.startSpan(name,attributes);try{const result=await operation();telemetryCollector.endSpan(handle);return result}catch(error){telemetryCollector.endSpan(handle,{error:true});throw error}}function startTelemetrySpan(name,attributes){return telemetryCollector.startSpan(name,attributes)}function endTelemetrySpan(handle,attributes){telemetryCollector.endSpan(handle,attributes)}function flushTelemetry(exitCode=0){telemetryCollector.flush(exitCode)}var telemetryCollector=new TelemetryCollector;function sanitiseAttributes(attributes){if(!attributes)return;const entries=Object.entries(attributes).filter(([,value])=>value!==undefined);if(entries.length===0)return;return Object.fromEntries(entries)}function mergeAttributes(initial,extra){if(!initial&&!extra)return;return sanitiseAttributes({...initial??{},...extra??{}})}function formatTelemetryReport(spans,sessionStartMs,sessionEndMs,exitCode){const lines=["[githits telemetry]",`exit: ${exitCode}`,`total: ${formatMs(sessionEndMs-sessionStartMs)}`];const orderedSpans=[...spans].sort((left,right)=>{if(left.startMs!==right.startMs){return left.startMs-right.startMs}return left.id-right.id});for(const span of orderedSpans){const endMs=span.endMs??sessionEndMs;const details=[`start +${formatMs(span.startMs-sessionStartMs)}`];if(span.endedAtExit){details.push("ended-at-exit")}const attrs=formatAttributes(span.attributes);if(attrs){details.push(attrs)}lines.push(`- ${span.name}: ${formatMs(endMs-span.startMs)} (${details.join(", ")})`)}return`${lines.join(`
1849
+ `)}
1850
+ `}function formatAttributes(attributes){if(!attributes)return"";return Object.entries(attributes).map(([key,value])=>`${key}=${String(value)}`).join(" ")}function formatMs(value){return`${value.toFixed(1)}ms`}var PROACTIVE_REFRESH_RATIO=0.9;function shouldRefreshToken(token,ratio,now){if(!token.expiresAt){return{expired:false,shouldRefresh:false}}const expiresAt=new Date(token.expiresAt).getTime();const nowMs=now.getTime();if(nowMs>=expiresAt){return{expired:true,shouldRefresh:true}}const createdAt=new Date(token.createdAt).getTime();const lifetime=expiresAt-createdAt;if(lifetime<=0){return{expired:false,shouldRefresh:false}}const threshold=createdAt+lifetime*ratio;return{expired:false,shouldRefresh:nowMs>=threshold}}async function refreshExpiredToken(authService,authStorage,mcpUrl){const manager=new TokenManager({authService,authStorage,mcpUrl,refreshFailureMode:"return-undefined"});return manager.forceRefresh()}class TokenManager{authService;authStorage;mcpUrl;refreshFailureMode;authDiagnostics;cachedToken=null;softRefreshPromise=null;forceRefreshPromise=null;constructor(deps){this.authService=deps.authService;this.authStorage=deps.authStorage;this.mcpUrl=deps.mcpUrl;this.refreshFailureMode=deps.refreshFailureMode??"throw";this.authDiagnostics=deps.authDiagnostics}async getToken(){return withTelemetrySpan("token-manager.get-token",async()=>{const activeForceRefresh=this.forceRefreshPromise;if(activeForceRefresh){return(await activeForceRefresh).accessToken}if(!this.cachedToken){const storedToken=await withTelemetrySpan("token-manager.load-tokens",()=>this.authStorage.loadTokens(this.mcpUrl));const startedForceRefresh=this.forceRefreshPromise;if(startedForceRefresh){return(await startedForceRefresh).accessToken}if(!this.cachedToken){this.cachedToken=storedToken}if(!this.cachedToken)return}const currentToken=this.cachedToken.accessToken;const{expired,shouldRefresh}=shouldRefreshToken(this.cachedToken,PROACTIVE_REFRESH_RATIO,new Date);if(!shouldRefresh){return currentToken}let refresh;try{refresh=await this.refreshFromGetToken()}catch(error){if(!expired)return currentToken;throw error}if(refresh.accessToken){return refresh.accessToken}if(refresh.invalidatedCurrentToken){return}if(!expired){return currentToken}return})}async forceRefresh(){return withTelemetrySpan("token-manager.force-refresh",()=>this.refreshAfterAuthFailure())}refreshFromGetToken(){return this.softRefresh()}async softRefresh(){if(this.forceRefreshPromise)return this.forceRefreshPromise;if(this.softRefreshPromise)return this.softRefreshPromise;this.softRefreshPromise=this.executeRefresh();try{return await this.softRefreshPromise}finally{this.softRefreshPromise=null}}async refreshAfterAuthFailure(){const result=await this.forceEndpointRefresh();return result.accessToken}async forceEndpointRefresh(){if(this.forceRefreshPromise)return this.forceRefreshPromise;this.forceRefreshPromise=(async()=>{const softResult=await this.softRefreshPromise?.catch(()=>{return});if(softResult?.accessToken&&softResult.refreshedViaEndpoint){return softResult}return this.executeRefresh()})();try{return await this.forceRefreshPromise}finally{this.forceRefreshPromise=null}}async executeRefresh(){return withAuthStorageLock(this.authStorage,()=>withTelemetrySpan("token-manager.refresh",async()=>{const candidate=await this.loadRefreshCandidate();if(!candidate)return refreshResult(undefined,false);if(candidate.externallyUpdated){const{shouldRefresh}=shouldRefreshToken(candidate.tokens,PROACTIVE_REFRESH_RATIO,new Date);if(!shouldRefresh)return refreshResult(candidate.tokens.accessToken,false)}const tokens=candidate.tokens;const client=await withTelemetrySpan("token-manager.load-client",()=>this.authStorage.loadClient(this.mcpUrl));if(!client){if(this.refreshFailureMode==="return-undefined"){return refreshResult(undefined,false)}throw new AuthenticationError("Stored GitHits credentials cannot be refreshed because the OAuth client registration is missing or unreadable.","local")}let response;try{const metadata=await withTelemetrySpan("token-manager.discover-endpoints",()=>this.authService.discoverEndpoints(this.mcpUrl));response=await withTelemetrySpan("token-manager.refresh-access-token",()=>this.authService.refreshAccessToken({tokenEndpoint:metadata.tokenEndpoint,clientId:client.clientId,clientSecret:client.clientSecret,refreshToken:tokens.refreshToken}))}catch(error){const terminalFailure=classifyTerminalRefreshError(error);const reloadedToken=await this.loadExternallyUpdatedToken(tokens);if(reloadedToken)return refreshResult(reloadedToken.accessToken,false);const isExpired=tokens.expiresAt?new Date>=new Date(tokens.expiresAt):false;if(terminalFailure){return this.clearTerminalRefreshFailure(tokens,terminalFailure)}if(candidate.externallyUpdated&&!isExpired){return refreshResult(tokens.accessToken,false)}if(isExpired){const currentStoredTokens=await this.loadExternallyUpdatedToken(tokens);if(currentStoredTokens){return refreshResult(currentStoredTokens.accessToken,false)}}if(this.refreshFailureMode==="return-undefined"){return refreshResult(undefined,false)}throw error}const newTokenData={accessToken:response.accessToken,refreshToken:response.refreshToken??tokens.refreshToken,expiresAt:new Date(Date.now()+response.expiresIn*1000).toISOString(),createdAt:new Date().toISOString()};const saved=await withTelemetrySpan("token-manager.save-tokens",()=>this.authStorage.saveTokensIfUnchanged(this.mcpUrl,tokens,newTokenData));if(!saved){return this.resolveSuccessfulRefreshConflict(tokens,response,newTokenData)}this.cachedToken=newTokenData;return refreshResult(response.accessToken,true)}))}async resolveSuccessfulRefreshConflict(refreshedFrom,response,newTokenData){const currentToken=await withTelemetrySpan("token-manager.reload-tokens",()=>this.authStorage.loadTokens(this.mcpUrl));if(!currentToken){this.cachedToken=null;return refreshResult(undefined,false)}if(!response.refreshToken||currentToken.refreshToken!==refreshedFrom.refreshToken){this.cachedToken=currentToken;return refreshResult(currentToken.accessToken,false)}const saved=await withTelemetrySpan("token-manager.save-rotated-tokens-after-conflict",()=>this.authStorage.saveTokensIfUnchanged(this.mcpUrl,currentToken,newTokenData));if(saved){this.cachedToken=newTokenData;return refreshResult(newTokenData.accessToken,true)}const latestToken=await withTelemetrySpan("token-manager.reload-tokens",()=>this.authStorage.loadTokens(this.mcpUrl));this.cachedToken=latestToken;return refreshResult(latestToken?.accessToken,false)}async clearTerminalRefreshFailure(failedTokens,reason){const cleared=await withTelemetrySpan("token-manager.clear-terminal-refresh-failure",()=>this.authStorage.clearActiveTokensIfUnchanged(this.mcpUrl,failedTokens),{reason:`terminal_${reason}`});if(!cleared){const latestToken=await withTelemetrySpan("token-manager.reload-tokens",()=>this.authStorage.loadTokens(this.mcpUrl));this.cachedToken=latestToken;return refreshResult(latestToken?.accessToken,false,!latestToken)}if(reason==="invalid_client"){await withTelemetrySpan("token-manager.clear-invalid-client",()=>this.authStorage.clearActiveClient(this.mcpUrl),{reason:"terminal_invalid_client"}).catch(()=>{return})}await this.authDiagnostics?.recordClear(this.mcpUrl,`terminal_${reason}`);this.cachedToken=null;return refreshResult(undefined,false,true)}async loadRefreshCandidate(){const storedTokens=await withTelemetrySpan("token-manager.load-tokens",()=>this.authStorage.loadTokens(this.mcpUrl));if(!this.cachedToken){this.cachedToken=storedTokens;return storedTokens?{tokens:storedTokens,externallyUpdated:false}:null}if(!storedTokens){this.cachedToken=null;return null}if(!areSameTokenData(storedTokens,this.cachedToken)){this.cachedToken=storedTokens;return{tokens:storedTokens,externallyUpdated:true}}return{tokens:this.cachedToken,externallyUpdated:false}}async loadExternallyUpdatedToken(failedTokens){const storedTokens=await withTelemetrySpan("token-manager.reload-tokens",()=>this.authStorage.loadTokens(this.mcpUrl));if(!storedTokens)return;if(areSameTokenData(storedTokens,failedTokens))return;this.cachedToken=storedTokens;return storedTokens}}function areSameTokenData(a,b){return a.accessToken===b.accessToken&&a.refreshToken===b.refreshToken&&a.expiresAt===b.expiresAt&&a.createdAt===b.createdAt}function refreshResult(accessToken,refreshedViaEndpoint,invalidatedCurrentToken=false){return{accessToken,refreshedViaEndpoint,invalidatedCurrentToken}}function debugLog(area,payload){if(!isAreaEnabled(area))return;const line={ts:new Date().toISOString(),area,...payload};let text;try{text=JSON.stringify(line)}catch{text=JSON.stringify({ts:line.ts,area,error:"debug-log payload not serialisable"})}process.stderr.write(`${text}
1851
+ `)}function isDebugAreaEnabled(area){return isAreaEnabled(area)}function isAreaEnabled(area){const raw=process.env.GITHITS_DEBUG;if(!raw||raw==="")return false;const scopes=raw.split(",").map((s)=>s.trim()).filter(Boolean);if(scopes.includes(area))return true;if(isExplicitOnlyArea(area))return false;return scopes.includes("*")}function isExplicitOnlyArea(area){return area==="code-nav-wire"}var BASE_CLIENT_NAME="githits-cli";var USER_AGENT=`${BASE_CLIENT_NAME}/${version2}`;async function createAuthStorage(fileSystemService){return withTelemetrySpan("container.create-auth-storage",async()=>{const authConfig=await loadAuthConfig(fileSystemService);recordAuthFingerprint(authConfig.storage);return createAuthStorageForMode(fileSystemService,authConfig.storage,authConfig.configPath)})}function recordAuthFingerprint(mode,env=process.env){const handle=startTelemetrySpan("auth.fingerprint",{mode,platform:process.platform,homeSet:Boolean(env.HOME),xdgConfigHomeSet:Boolean(env.XDG_CONFIG_HOME),appDataSet:Boolean(env.APPDATA),userProfileSet:Boolean(env.USERPROFILE)});endTelemetrySpan(handle)}function createAuthStorageForMode(fileSystemService,mode,configPath="your GitHits config.toml"){const fileStorage=new ModeAwareFileAuthStorage(new AuthStorageImpl(fileSystemService,getAuthFileStorageDir(fileSystemService)),mode,configPath);const legacyStorage=new AuthStorageImpl(fileSystemService,getLegacyAuthStorageDir(fileSystemService));const additionalLegacyStores=process.platform==="darwin"?[new AuthStorageImpl(fileSystemService,getLegacyMacAuthFileStorageDir(fileSystemService))]:[];const rawKeyring=new KeyringServiceImpl;const keyring=process.platform==="win32"?new ChunkingKeyringService(rawKeyring,WINDOWS_MAX_ENTRY_SIZE):rawKeyring;const keychainStorage=new KeychainAuthStorage(keyring);const metadataStorage=new AuthSessionMetadataStorage(fileSystemService);return new LockedAuthStorage(new MigratingAuthStorage(keychainStorage,fileStorage,legacyStorage,mode,configPath,(message)=>console.error(message),metadataStorage,additionalLegacyStores),fileSystemService)}async function loadAutoLoginAuthSessionMetadata2(){const envToken=getEnvApiToken();if(envToken){const now=new Date().toISOString();return{createdAt:now,expiresAt:null,updatedAt:now}}const fileSystemService=new FileSystemServiceImpl;const metadataStorage=new AuthSessionMetadataStorage(fileSystemService);return metadataStorage.load(getMcpStorageKeyUrl())}async function clearAutoLoginAuthSessionMetadata2(){const fileSystemService=new FileSystemServiceImpl;const metadataStorage=new AuthSessionMetadataStorage(fileSystemService);await metadataStorage.clear(getMcpStorageKeyUrl())}async function createAuthCommandDependencies2(){return withTelemetrySpan("container.create-auth-command",async()=>{const fileSystemService=new FileSystemServiceImpl;return{authStorage:await createAuthStorage(fileSystemService),authService:new AuthServiceImpl(createLazyCliFetch()),browserService:new BrowserServiceImpl,fileSystemService,authDiagnostics:new AuthDiagnosticsStorage(fileSystemService),mcpUrl:getMcpStorageKeyUrl(),envApiToken:getEnvApiToken()}})}async function createLogoutCommandDependencies2(){return withTelemetrySpan("container.create-logout-command",async()=>{const fileSystemService=new FileSystemServiceImpl;return{authStorage:createAuthStorageForMode(fileSystemService,"keychain",getAuthConfigPath(fileSystemService)),authDiagnostics:new AuthDiagnosticsStorage(fileSystemService),mcpUrl:getMcpStorageKeyUrl()}})}async function createAuthStatusDependencies2(){return withTelemetrySpan("container.create-auth-status",async()=>{const fileSystemService=new FileSystemServiceImpl;const envApiToken=getEnvApiToken();return{authStorage:envApiToken?createAuthStorageForMode(fileSystemService,"keychain"):await createAuthStorage(fileSystemService),authService:new AuthServiceImpl(createLazyCliFetch()),browserService:new BrowserServiceImpl,fileSystemService,authDiagnostics:new AuthDiagnosticsStorage(fileSystemService),mcpUrl:getMcpStorageKeyUrl(),envApiToken}})}async function createContainer2(options={}){return withTelemetrySpan("container.create",async()=>{const resolveStoredToken=options.resolveStoredToken??true;const mcpUrl=getMcpUrl();const apiUrl=getApiUrl();const codeNavigationUrl=getCodeNavigationUrl();const fileSystemService=new FileSystemServiceImpl;const fetchFn=createCliFetch();const authService=new AuthServiceImpl(fetchFn);const browserService=new BrowserServiceImpl;const clientHeaders=createClientHeaderBuilder({clientName:options.clientName??BASE_CLIENT_NAME,clientVersion:version2,agentProvider:options.agentProvider});const diagnostics={withOperation:withTelemetrySpan,isEnabled:isDebugAreaEnabled,debug:debugLog};const serviceRuntime={clientHeaders,userAgent:USER_AGENT,clientVersion:version2,diagnostics};const envToken=getEnvApiToken();if(envToken){const authStorage=createAuthStorageForMode(fileSystemService,"keychain");const tokenProvider=createStaticTokenProvider(envToken);const codeNavigationService=new CodeNavigationServiceImpl(codeNavigationUrl,tokenProvider,fetchFn,serviceRuntime);const packageIntelligenceService=new PackageIntelligenceServiceImpl(codeNavigationUrl,tokenProvider,fetchFn,serviceRuntime);const resolveTargetService=new ResolveTargetServiceImpl(codeNavigationUrl,tokenProvider,fetchFn,serviceRuntime);const agenticAskService=new AgenticAskServiceImpl(apiUrl,tokenProvider,fetchFn,{...serviceRuntime,timeoutMs:AGENTIC_ASK_REQUEST_TIMEOUT_MS});return{authStorage,authService,browserService,fileSystemService,mcpUrl,apiUrl,apiToken:envToken,hasValidToken:true,envApiToken:envToken,codeNavigationUrl,codeNavigationService,packageIntelligenceService,resolveTargetService,agenticAskService,githitsService:new GitHitsServiceImpl(apiUrl,envToken,fetchFn,undefined,serviceRuntime),tokenProvider}}const authStorage=await createAuthStorage(fileSystemService);const tokenManager=new TokenManager({authService,authStorage,mcpUrl,...options.refreshFailureMode!==undefined?{refreshFailureMode:options.refreshFailureMode}:{},authDiagnostics:new AuthDiagnosticsStorage(fileSystemService)});const apiToken=resolveStoredToken?await withTelemetrySpan("container.token.get",()=>tokenManager.getToken()):undefined;if(resolveStoredToken&&apiToken===undefined){await new AuthSessionMetadataStorage(fileSystemService).clear(mcpUrl)}const codeNavigationService=new CodeNavigationServiceImpl(codeNavigationUrl,tokenManager,fetchFn,serviceRuntime);const packageIntelligenceService=new PackageIntelligenceServiceImpl(codeNavigationUrl,tokenManager,fetchFn,serviceRuntime);const resolveTargetService=new ResolveTargetServiceImpl(codeNavigationUrl,tokenManager,fetchFn,serviceRuntime);const agenticAskService=new AgenticAskServiceImpl(apiUrl,tokenManager,fetchFn,{...serviceRuntime,timeoutMs:AGENTIC_ASK_REQUEST_TIMEOUT_MS});return{authStorage,authService,browserService,fileSystemService,mcpUrl,apiUrl,apiToken,hasValidToken:apiToken!==undefined,envApiToken:undefined,codeNavigationUrl,codeNavigationService,packageIntelligenceService,resolveTargetService,agenticAskService,githitsService:new RefreshingGitHitsService(apiUrl,tokenManager,(innerApiUrl,token)=>new GitHitsServiceImpl(innerApiUrl,token,fetchFn,undefined,serviceRuntime),serviceRuntime),tokenProvider:tokenManager}})}
1852
+ export{LOCAL_AUTHENTICATION_MISSING_MESSAGE,SERVER_AUTHENTICATION_REJECTED_MESSAGE,AuthenticationError,ApiRateLimitError,FetchTimeoutError,fetchWithTimeout,isFetchTimeoutError,TERMS_URL,TermsAcceptanceRequiredError,DEFAULT_MCP_URL,DEFAULT_API_URL,DEFAULT_CODE_NAV_URL,validateServiceUrl,normalizeSingleLineText,AgenticAskHttpError,AgenticAskRequestTimeoutError,AgenticAskConnectionError,MalformedAgenticAskResponseError,AgenticAskResponseTooLargeError,normalizeAgenticAskThreadId,CLIENT_UPDATE_REQUIRED_REASON,ClientUpdateRequiredError,PKGSEER_REGISTRY_ARGS,PKGSEER_REGISTRY_LIST,toPkgseerRegistry,toPkgseerRegistryLowercase,isKnownPkgseerRegistryArg,GREP_REPO_SYMBOL_FIELDS,CodeNavigationAccessError,CodeNavigationGraphQLError,CodeNavigationIndexingError,CodeNavigationUnresolvableError,MalformedCodeNavigationResponseError,CodeDiffError,CodeNavigationTargetNotFoundError,CodeNavigationFileNotFoundError,CodeNavigationVersionNotFoundError,CodeNavigationRefNotFoundError,CodeNavigationValidationError,CodeNavigationFeatureFlagRequiredError,CodeNavigationNetworkError,CodeNavigationBackendError,PackageIntelligenceAccessError,PackageIntelligenceFeatureFlagRequiredError,PackageIntelligenceNetworkError,PackageIntelligenceBackendError,PackageIntelligenceGraphQLError,PackageIntelligenceTargetNotFoundError,PackageIntelligenceValidationError,PackageIntelligenceVersionNotFoundError,MalformedPackageIntelligenceResponseError,PackageIntelligenceChangelogSourceNotFoundError,getAppConfigDirForEnv,getAuthConfigPath,getAuthConfigPathForEnv,getAuthFileStorageDirForEnv,getLegacyAuthStorageDirForEnv,getLegacyMacAuthConfigPathForEnv,getLegacyMacAuthFileStorageDirForEnv,AppConfigError,readAppConfig,AuthConfigError,parseAuthStorageMode,AuthStorageLockTimeoutError,AuthStoragePolicyError,debugLog,isDebugAreaEnabled,normalizeBaseUrl,isAuthClearReason,FileSystemServiceImpl,createCliFetch,createLazyCliFetch,isTelemetryEnabled,withTelemetrySpan,startTelemetrySpan,endTelemetrySpan,flushTelemetry,refreshExpiredToken,loadAutoLoginAuthSessionMetadata2,clearAutoLoginAuthSessionMetadata2,createAuthCommandDependencies2,createLogoutCommandDependencies2,createAuthStatusDependencies2,createContainer2};