githits 0.4.12 → 0.4.13
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.
- package/.claude-plugin/marketplace.json +1 -1
- package/.claude-plugin/plugin.json +1 -1
- package/.plugin/plugin.json +1 -1
- package/dist/cli.js +213 -15763
- package/dist/index.js +1 -6
- package/dist/shared/chunk-33j95qx6.js +2 -0
- package/dist/shared/chunk-ancbjszp.js +1304 -0
- package/dist/shared/chunk-q9yem3rk.js +1 -0
- package/gemini-extension.json +1 -1
- package/package.json +7 -3
- package/plugins/claude/.claude-plugin/plugin.json +1 -1
- package/plugins/claude/skills/onboarding/SKILL.md +119 -0
- package/skills/githits-onboarding/SKILL.md +168 -0
- package/skills/githits-onboarding/references/troubleshooting.md +58 -0
- package/dist/shared/chunk-1045f3nq.js +0 -6628
- package/dist/shared/chunk-cp1jj1n1.js +0 -15
- package/dist/shared/chunk-tmhsq5ft.js +0 -6
|
@@ -0,0 +1,1304 @@
|
|
|
1
|
+
import{__require,version}from"./chunk-33j95qx6.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")}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){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}from"zod";function debugLog(area,payload){if(!isAreaEnabled(area))return;const line={ts:new Date().toISOString(),area,...payload};let text;try{text=JSON.stringify(line)}catch{text=JSON.stringify({ts:line.ts,area,error:"debug-log payload not serialisable"})}process.stderr.write(`${text}
|
|
2
|
+
`)}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 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}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;let response;try{response=await fetchWithTimeout(`${baseUrl(request.endpointUrl)}/api/graphql`,{method:"POST",headers:{...request.clientHeaders?.(),Authorization:`Bearer ${request.token}`,"Content-Type":"application/json","User-Agent":userAgent},body:JSON.stringify({query:request.query,variables:request.variables})},{fetchFn:request.fetchFn,timeoutMs})}catch(cause){debugLog("pkg-graphql",{event:"transport-error",errorName:cause instanceof Error?cause.name:typeof cause,hasCause:true});throw new PkgseerTransportError("Network request failed before a response was received. Caller should re-wrap with a domain-specific message.",{cause})}const responseBody=await response.text().catch(()=>"");const parsedBody=parseJsonOrNull(responseBody);return{status:response.status,responseBody,parsedBody}}function parseJsonOrNull(body){if(!body)return null;try{return JSON.parse(body)}catch{return null}}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(`
|
|
3
|
+
`)}
|
|
4
|
+
`}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 AUTHENTICATION_REQUIRED_MESSAGE="Authentication required.";var LOCAL_AUTHENTICATION_MISSING_MESSAGE="No local GitHits authentication token found.";var SERVER_AUTHENTICATION_REJECTED_MESSAGE="GitHits could not accept the authentication token.";class AuthenticationError extends Error{source;constructor(message=AUTHENTICATION_REQUIRED_MESSAGE,source="local"){super(message);this.name="AuthenticationError";this.source=source}}function parseDetail(body){if(!body)return;try{const parsed=JSON.parse(body);if(typeof parsed.detail==="string")return parsed.detail}catch{return body}return}class GitHitsServiceImpl{apiUrl;token;fetchFn;fetchTimeoutMs;runtime;constructor(apiUrl,token,fetchFn,fetchTimeoutMs=DEFAULT_FETCH_TIMEOUT_MS,runtime={}){this.apiUrl=apiUrl;this.token=token;this.fetchFn=fetchFn;this.fetchTimeoutMs=fetchTimeoutMs;this.runtime=runtime}async search(params){return withTelemetrySpan("githits.search.request",async()=>{const response=await fetchWithTimeout(`${this.apiUrl}/search`,{method:"POST",headers:this.headers(),body:JSON.stringify({query:params.query,language:params.language,license_mode:params.licenseMode??"strict",include_explanation:params.includeExplanation??false})},this.fetchOptions());if(!response.ok){throw await this.createError(response)}return response.text()})}async getLanguages(){return withTelemetrySpan("githits.languages.request",async()=>{const response=await fetchWithTimeout(`${this.apiUrl}/languages`,{headers:this.headers()},this.fetchOptions());if(!response.ok){throw await this.createError(response)}return response.json()})}async searchLanguages(query,limit=5){return withTelemetrySpan("githits.languages.search.request",async()=>{const params=new URLSearchParams({query,limit:String(limit)});const response=await fetchWithTimeout(`${this.apiUrl}/languages?${params.toString()}`,{headers:this.headers()},this.fetchOptions());if(!response.ok){throw await this.createError(response)}return response.json()})}async submitFeedback(params){return withTelemetrySpan("githits.feedback.request",async()=>{const response=await fetchWithTimeout(`${this.apiUrl}/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}})},this.fetchOptions());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(){return{fetchFn:this.fetchFn,timeoutMs:this.fetchTimeoutMs}}async createError(response){const status=response.status;const body=await response.text().catch(()=>"");switch(status){case 401:return new AuthenticationError(SERVER_AUTHENTICATION_REJECTED_MESSAGE,"server");case 403:return new Error("Access denied.");case 404:return new Error(parseDetail(body)||"Resource not found.");default:{if(status>=500){const detail=body?`: ${body}`:"";return new Error(`Server error (${status})${detail}`)}return new Error(body||`Request failed with status ${status}`)}}}}async function executeWithTokenRefresh(options){const token=await options.getToken();if(!token){throw new AuthenticationError(LOCAL_AUTHENTICATION_MISSING_MESSAGE,"local")}try{return await options.executeWithToken(token)}catch(error){if(!options.shouldRefresh(error)){throw error}const refreshedToken=await options.forceRefresh();if(!refreshedToken){throw error}return options.executeWithToken(refreshedToken)}}class CodeNavigationAccessError extends Error{constructor(message){super(message);this.name="CodeNavigationAccessError"}}class CodeNavigationGraphQLError extends Error{code;constructor(message,code){super(message);this.code=code;this.name="CodeNavigationGraphQLError"}}class CodeNavigationIndexingError extends Error{indexingRef;availableVersions;availableRefs;targetResolution;constructor(message,indexingRef,availableVersions,availableRefs,targetResolution){super(message);this.indexingRef=indexingRef;this.availableVersions=availableVersions;this.availableRefs=availableRefs;this.targetResolution=targetResolution;this.name="CodeNavigationIndexingError"}}class CodeNavigationUnresolvableError extends Error{constructor(message){super(message);this.name="CodeNavigationUnresolvableError"}}class MalformedCodeNavigationResponseError extends Error{constructor(message){super(message);this.name="MalformedCodeNavigationResponseError"}}class CodeNavigationTargetNotFoundError extends Error{availableVersions;constructor(message,availableVersions){super(message);this.availableVersions=availableVersions;this.name="CodeNavigationTargetNotFoundError"}}class CodeNavigationFileNotFoundError extends Error{filePath;constructor(message,filePath){super(message);this.filePath=filePath;this.name="CodeNavigationFileNotFoundError"}}class CodeNavigationVersionNotFoundError extends Error{packageName;requestedVersion;latestIndexed;availableVersions;constructor(message,packageName,requestedVersion,latestIndexed,availableVersions){super(message);this.packageName=packageName;this.requestedVersion=requestedVersion;this.latestIndexed=latestIndexed;this.availableVersions=availableVersions;this.name="CodeNavigationVersionNotFoundError"}}class CodeNavigationValidationError extends Error{constructor(message){super(message);this.name="CodeNavigationValidationError"}}class CodeNavigationFeatureFlagRequiredError extends Error{constructor(message){super(message);this.name="CodeNavigationFeatureFlagRequiredError"}}class CodeNavigationNetworkError extends Error{constructor(message,options){super(message,options);this.name="CodeNavigationNetworkError"}}class CodeNavigationBackendError extends Error{status;graphqlCode;retryable;constructor(message,status,graphqlCode,retryable){super(message);this.status=status;this.graphqlCode=graphqlCode;this.retryable=retryable;this.name="CodeNavigationBackendError"}}var TARGET_RESOLUTION_AVAILABLE_REFS_SELECTION=`
|
|
5
|
+
availableRefs {
|
|
6
|
+
version
|
|
7
|
+
ref
|
|
8
|
+
}`;var TARGET_RESOLUTION_SELECTION=`
|
|
9
|
+
targetResolution {
|
|
10
|
+
requested {
|
|
11
|
+
kind
|
|
12
|
+
registry
|
|
13
|
+
packageName
|
|
14
|
+
version
|
|
15
|
+
repoUrl
|
|
16
|
+
gitRef
|
|
17
|
+
commitSha
|
|
18
|
+
}
|
|
19
|
+
resolvedRequested {
|
|
20
|
+
kind
|
|
21
|
+
registry
|
|
22
|
+
packageName
|
|
23
|
+
version
|
|
24
|
+
repoUrl
|
|
25
|
+
gitRef
|
|
26
|
+
commitSha
|
|
27
|
+
}
|
|
28
|
+
served {
|
|
29
|
+
kind
|
|
30
|
+
registry
|
|
31
|
+
packageName
|
|
32
|
+
version
|
|
33
|
+
repoUrl
|
|
34
|
+
gitRef
|
|
35
|
+
commitSha
|
|
36
|
+
}
|
|
37
|
+
freshness
|
|
38
|
+
freshnessReason
|
|
39
|
+
indexingRef
|
|
40
|
+
availableVersions {
|
|
41
|
+
version
|
|
42
|
+
ref
|
|
43
|
+
}
|
|
44
|
+
${TARGET_RESOLUTION_AVAILABLE_REFS_SELECTION}
|
|
45
|
+
}`;var CODE_CONTEXT_AVAILABLE_VERSIONS_SELECTION=`
|
|
46
|
+
availableVersions {
|
|
47
|
+
version
|
|
48
|
+
ref
|
|
49
|
+
}`;var DISCOVERY_TARGET_PROGRESS_RETRY_SELECTION=`
|
|
50
|
+
availableVersions {
|
|
51
|
+
version
|
|
52
|
+
ref
|
|
53
|
+
}
|
|
54
|
+
availableRefs {
|
|
55
|
+
version
|
|
56
|
+
ref
|
|
57
|
+
}`;var UNIFIED_SEARCH_QUERY=`
|
|
58
|
+
query UnifiedSearch(
|
|
59
|
+
$targets: [SearchPackageInput!]!
|
|
60
|
+
$query: String!
|
|
61
|
+
$sources: [DiscoverySearchSource!]
|
|
62
|
+
$filters: DiscoverySearchFiltersInput
|
|
63
|
+
$allowPartialResults: Boolean
|
|
64
|
+
$limit: Int
|
|
65
|
+
$offset: Int
|
|
66
|
+
$waitTimeoutMs: Int
|
|
67
|
+
) {
|
|
68
|
+
search(
|
|
69
|
+
targets: $targets
|
|
70
|
+
query: $query
|
|
71
|
+
sources: $sources
|
|
72
|
+
filters: $filters
|
|
73
|
+
allowPartialResults: $allowPartialResults
|
|
74
|
+
limit: $limit
|
|
75
|
+
offset: $offset
|
|
76
|
+
waitTimeoutMs: $waitTimeoutMs
|
|
77
|
+
) {
|
|
78
|
+
completed
|
|
79
|
+
searchRef
|
|
80
|
+
result {
|
|
81
|
+
query
|
|
82
|
+
queryWarnings
|
|
83
|
+
sources
|
|
84
|
+
results {
|
|
85
|
+
id
|
|
86
|
+
resultType
|
|
87
|
+
targetLabel
|
|
88
|
+
requestedTargetLabel
|
|
89
|
+
freshTargetLabel
|
|
90
|
+
servedTargetLabel
|
|
91
|
+
freshness
|
|
92
|
+
title
|
|
93
|
+
summary
|
|
94
|
+
score
|
|
95
|
+
highlights {
|
|
96
|
+
title
|
|
97
|
+
summary
|
|
98
|
+
}
|
|
99
|
+
locator {
|
|
100
|
+
registry
|
|
101
|
+
packageName
|
|
102
|
+
version
|
|
103
|
+
pageId
|
|
104
|
+
sourceKind
|
|
105
|
+
sourceUrl
|
|
106
|
+
repoUrl
|
|
107
|
+
gitRef
|
|
108
|
+
requestedRef
|
|
109
|
+
filePath
|
|
110
|
+
startLine
|
|
111
|
+
endLine
|
|
112
|
+
fileContentHash
|
|
113
|
+
symbolRef
|
|
114
|
+
qualifiedPath
|
|
115
|
+
kind
|
|
116
|
+
category
|
|
117
|
+
language
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
page {
|
|
121
|
+
offset
|
|
122
|
+
limit
|
|
123
|
+
returned
|
|
124
|
+
hasMore
|
|
125
|
+
}
|
|
126
|
+
partialResults
|
|
127
|
+
sourceStatus {
|
|
128
|
+
source
|
|
129
|
+
targetLabel
|
|
130
|
+
requestedTargetLabel
|
|
131
|
+
freshTargetLabel
|
|
132
|
+
servedTargetLabel
|
|
133
|
+
${TARGET_RESOLUTION_SELECTION}
|
|
134
|
+
indexingStatus
|
|
135
|
+
codeIndexState
|
|
136
|
+
resultCount
|
|
137
|
+
appliedFilters
|
|
138
|
+
ignoredFilters
|
|
139
|
+
incompatibleFilters
|
|
140
|
+
appliedQueryFeatures
|
|
141
|
+
ignoredQueryFeatures
|
|
142
|
+
incompatibleQueryFeatures
|
|
143
|
+
note
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
progress {
|
|
147
|
+
searchRef
|
|
148
|
+
status
|
|
149
|
+
targetsTotal
|
|
150
|
+
targetsReady
|
|
151
|
+
elapsedMs
|
|
152
|
+
query
|
|
153
|
+
queryWarnings
|
|
154
|
+
sources
|
|
155
|
+
requestedSources
|
|
156
|
+
targetMode
|
|
157
|
+
requestedTargets {
|
|
158
|
+
registry
|
|
159
|
+
name
|
|
160
|
+
version
|
|
161
|
+
repoUrl
|
|
162
|
+
gitRef
|
|
163
|
+
}
|
|
164
|
+
filters {
|
|
165
|
+
fileIntent
|
|
166
|
+
kind
|
|
167
|
+
category
|
|
168
|
+
publicOnly
|
|
169
|
+
pathPrefix
|
|
170
|
+
}
|
|
171
|
+
limit
|
|
172
|
+
offset
|
|
173
|
+
targets {
|
|
174
|
+
requested
|
|
175
|
+
resolvedRequested
|
|
176
|
+
served
|
|
177
|
+
freshness
|
|
178
|
+
indexingRef
|
|
179
|
+
requestedRefKind
|
|
180
|
+
${TARGET_RESOLUTION_SELECTION}
|
|
181
|
+
${DISCOVERY_TARGET_PROGRESS_RETRY_SELECTION}
|
|
182
|
+
}
|
|
183
|
+
expiresAt
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
}`;var UNIFIED_SEARCH_STATUS_QUERY=`
|
|
187
|
+
query UnifiedSearchStatus($searchRef: String!, $includeResults: Boolean!) {
|
|
188
|
+
discoverySearchProgress(searchRef: $searchRef, includeResults: $includeResults) {
|
|
189
|
+
searchRef
|
|
190
|
+
status
|
|
191
|
+
targetsTotal
|
|
192
|
+
targetsReady
|
|
193
|
+
elapsedMs
|
|
194
|
+
query
|
|
195
|
+
queryWarnings
|
|
196
|
+
sources
|
|
197
|
+
requestedSources
|
|
198
|
+
targetMode
|
|
199
|
+
requestedTargets {
|
|
200
|
+
registry
|
|
201
|
+
name
|
|
202
|
+
version
|
|
203
|
+
repoUrl
|
|
204
|
+
gitRef
|
|
205
|
+
}
|
|
206
|
+
filters {
|
|
207
|
+
fileIntent
|
|
208
|
+
kind
|
|
209
|
+
category
|
|
210
|
+
publicOnly
|
|
211
|
+
pathPrefix
|
|
212
|
+
}
|
|
213
|
+
limit
|
|
214
|
+
offset
|
|
215
|
+
targets {
|
|
216
|
+
requested
|
|
217
|
+
resolvedRequested
|
|
218
|
+
served
|
|
219
|
+
freshness
|
|
220
|
+
indexingRef
|
|
221
|
+
requestedRefKind
|
|
222
|
+
${TARGET_RESOLUTION_SELECTION}
|
|
223
|
+
${DISCOVERY_TARGET_PROGRESS_RETRY_SELECTION}
|
|
224
|
+
}
|
|
225
|
+
expiresAt
|
|
226
|
+
results {
|
|
227
|
+
query
|
|
228
|
+
queryWarnings
|
|
229
|
+
sources
|
|
230
|
+
results {
|
|
231
|
+
id
|
|
232
|
+
resultType
|
|
233
|
+
targetLabel
|
|
234
|
+
requestedTargetLabel
|
|
235
|
+
freshTargetLabel
|
|
236
|
+
servedTargetLabel
|
|
237
|
+
freshness
|
|
238
|
+
title
|
|
239
|
+
summary
|
|
240
|
+
score
|
|
241
|
+
highlights {
|
|
242
|
+
title
|
|
243
|
+
summary
|
|
244
|
+
}
|
|
245
|
+
locator {
|
|
246
|
+
registry
|
|
247
|
+
packageName
|
|
248
|
+
version
|
|
249
|
+
pageId
|
|
250
|
+
sourceKind
|
|
251
|
+
sourceUrl
|
|
252
|
+
repoUrl
|
|
253
|
+
gitRef
|
|
254
|
+
requestedRef
|
|
255
|
+
filePath
|
|
256
|
+
startLine
|
|
257
|
+
endLine
|
|
258
|
+
fileContentHash
|
|
259
|
+
symbolRef
|
|
260
|
+
qualifiedPath
|
|
261
|
+
kind
|
|
262
|
+
category
|
|
263
|
+
language
|
|
264
|
+
}
|
|
265
|
+
}
|
|
266
|
+
page {
|
|
267
|
+
offset
|
|
268
|
+
limit
|
|
269
|
+
returned
|
|
270
|
+
hasMore
|
|
271
|
+
}
|
|
272
|
+
partialResults
|
|
273
|
+
sourceStatus {
|
|
274
|
+
source
|
|
275
|
+
targetLabel
|
|
276
|
+
requestedTargetLabel
|
|
277
|
+
freshTargetLabel
|
|
278
|
+
servedTargetLabel
|
|
279
|
+
${TARGET_RESOLUTION_SELECTION}
|
|
280
|
+
indexingStatus
|
|
281
|
+
codeIndexState
|
|
282
|
+
resultCount
|
|
283
|
+
appliedFilters
|
|
284
|
+
ignoredFilters
|
|
285
|
+
incompatibleFilters
|
|
286
|
+
appliedQueryFeatures
|
|
287
|
+
ignoredQueryFeatures
|
|
288
|
+
incompatibleQueryFeatures
|
|
289
|
+
note
|
|
290
|
+
}
|
|
291
|
+
}
|
|
292
|
+
}
|
|
293
|
+
}`;function debugUnifiedSearchRequest(variables){if(!isDebugAreaEnabled("code-nav"))return;const serialised=serialiseForDebug(variables);const filters=asRecord(serialised.filters);debugLog("code-nav",{event:"request",operation:"search",targetCount:Array.isArray(serialised.targets)?serialised.targets.length:0,sources:Array.isArray(serialised.sources)?serialised.sources:[],hasFilters:filters!==undefined,filterKeys:filters?Object.keys(filters).sort():[],fileIntent:filters&&typeof filters.fileIntent==="string"?filters.fileIntent:"omitted",allowPartialResults:serialised.allowPartialResults===true,presentVariableKeys:Object.keys(serialised).sort(),hasLimit:typeof serialised.limit==="number",hasOffset:typeof serialised.offset==="number",waitTimeoutMs:typeof serialised.waitTimeoutMs==="number"?serialised.waitTimeoutMs:undefined})}function debugGraphqlWireRequest(operation,graphqlQuery,variables){if(!isDebugAreaEnabled("code-nav-wire"))return;debugLog("code-nav-wire",{event:"wire-request",operation,graphqlQuery,variables:serialiseForDebug(variables)})}function serialiseForDebug(value){try{const text=JSON.stringify(value);if(!text)return{};const parsed=JSON.parse(text);return asRecord(parsed)??{}}catch{return{}}}function asRecord(value){if(value&&typeof value==="object"&&!Array.isArray(value)){return value}return}var availableVersionSchema=z.object({version:z.string().nullable().optional(),ref:z.string()});var targetResolutionIdentitySchema=z.object({kind:z.string().nullable().optional(),registry:z.string().nullable().optional(),packageName:z.string().nullable().optional(),version:z.string().nullable().optional(),repoUrl:z.string().nullable().optional(),gitRef:z.string().nullable().optional(),commitSha:z.string().nullable().optional()}).nullable().optional();var targetResolutionSchema=z.object({requested:targetResolutionIdentitySchema,resolvedRequested:targetResolutionIdentitySchema,served:targetResolutionIdentitySchema,freshness:z.string().nullable().optional(),freshnessReason:z.string().nullable().optional(),indexingRef:z.string().nullable().optional(),availableVersions:z.array(availableVersionSchema).nullable().optional(),availableRefs:z.array(availableVersionSchema).nullable().optional()}).nullable().optional();var unifiedSearchSourceSchema=z.enum(["AUTO","DOCS","CODE","SYMBOL"]);var unifiedSearchResultTypeSchema=z.enum(["DOCUMENTATION_PAGE","REPOSITORY_SYMBOL","REPOSITORY_CODE","REPOSITORY_DOC"]);var unifiedSearchLocatorSchema=z.object({registry:z.string().nullable().optional(),packageName:z.string().nullable().optional(),version:z.string().nullable().optional(),pageId:z.string().nullable().optional(),sourceKind:z.string().nullable().optional(),sourceUrl:z.string().nullable().optional(),repoUrl:z.string().nullable().optional(),gitRef:z.string().nullable().optional(),requestedRef:z.string().nullable().optional(),filePath:z.string().nullable().optional(),startLine:z.number().int().nullable().optional(),endLine:z.number().int().nullable().optional(),fileContentHash:z.string().nullable().optional(),symbolRef:z.string().nullable().optional(),qualifiedPath:z.string().nullable().optional(),kind:z.string().nullable().optional(),category:z.string().nullable().optional(),language:z.string().nullable().optional()});var unifiedSearchHitSchema=z.object({id:z.string(),resultType:unifiedSearchResultTypeSchema,targetLabel:z.string(),requestedTargetLabel:z.string().nullable().optional(),freshTargetLabel:z.string().nullable().optional(),servedTargetLabel:z.string().nullable().optional(),freshness:z.string().nullable().optional(),title:z.string().nullable().optional(),summary:z.string().nullable().optional(),score:z.number().nullable().optional(),highlights:z.object({title:z.array(z.tuple([z.number().int(),z.number().int()])).nullable().optional(),summary:z.array(z.tuple([z.number().int(),z.number().int()])).nullable().optional()}).nullable().optional(),locator:unifiedSearchLocatorSchema});var unifiedSearchPageInfoSchema=z.object({offset:z.number().int(),limit:z.number().int(),returned:z.number().int(),hasMore:z.boolean()});var unifiedSearchSourceStatusSchema=z.object({source:unifiedSearchSourceSchema,targetLabel:z.string(),requestedTargetLabel:z.string().nullable().optional(),freshTargetLabel:z.string().nullable().optional(),servedTargetLabel:z.string().nullable().optional(),targetResolution:targetResolutionSchema,indexingStatus:z.string().nullable().optional(),codeIndexState:z.string().nullable().optional(),resultCount:z.number().int().nullable().optional(),appliedFilters:z.array(z.string()),ignoredFilters:z.array(z.string()),incompatibleFilters:z.array(z.string()),appliedQueryFeatures:z.array(z.string()),ignoredQueryFeatures:z.array(z.string()),incompatibleQueryFeatures:z.array(z.string()),note:z.string().nullable().optional()});var unifiedSearchResultSchema=z.object({query:z.string(),queryWarnings:z.array(z.string()),sources:z.array(unifiedSearchSourceSchema),results:z.array(unifiedSearchHitSchema),page:unifiedSearchPageInfoSchema,partialResults:z.boolean(),sourceStatus:z.array(unifiedSearchSourceStatusSchema)});var unifiedSearchSessionStatusSchema=z.enum(["PENDING","INDEXING","SEARCHING","COMPLETED","TIMEOUT","FAILED"]);var unifiedSearchFiltersSchema=z.object({fileIntent:z.string().nullable().optional(),kind:z.string().nullable().optional(),category:z.string().nullable().optional(),publicOnly:z.boolean().nullable().optional(),pathPrefix:z.string().nullable().optional()}).nullable().optional();var unifiedSearchProgressTargetSchema=z.object({requested:z.string().nullable().optional(),resolvedRequested:z.string().nullable().optional(),served:z.string().nullable().optional(),freshness:z.string().nullable().optional(),indexingRef:z.string().nullable().optional(),requestedRefKind:z.string().nullable().optional(),targetResolution:targetResolutionSchema,availableVersions:z.array(availableVersionSchema).nullable().optional(),availableRefs:z.array(availableVersionSchema).nullable().optional()});var unifiedSearchRequestedTargetSchema=z.object({registry:z.string().nullable().optional(),name:z.string().nullable().optional(),version:z.string().nullable().optional(),repoUrl:z.string().nullable().optional(),gitRef:z.string().nullable().optional()});var unifiedSearchProgressSchema=z.object({searchRef:z.string(),status:unifiedSearchSessionStatusSchema,targetsTotal:z.number().int(),targetsReady:z.number().int(),elapsedMs:z.number().int(),query:z.string(),queryWarnings:z.array(z.string()),sources:z.array(unifiedSearchSourceSchema),requestedSources:z.array(unifiedSearchSourceSchema).nullable().optional(),targetMode:z.string().nullable().optional(),requestedTargets:z.array(unifiedSearchRequestedTargetSchema).nullable().optional(),filters:unifiedSearchFiltersSchema,limit:z.number().int().nullable().optional(),offset:z.number().int().nullable().optional(),targets:z.array(unifiedSearchProgressTargetSchema).nullable().optional(),expiresAt:z.string().nullable().optional(),results:unifiedSearchResultSchema.nullable().optional()});var asyncUnifiedSearchResultSchema=z.object({completed:z.boolean(),searchRef:z.string().nullable().optional(),result:unifiedSearchResultSchema.nullable().optional(),progress:unifiedSearchProgressSchema.nullable().optional()});var graphQLErrorSchema=z.object({message:z.string(),extensions:z.record(z.string(),z.unknown()).optional()});var navigationResolutionSchema=z.object({requestedVersion:z.string().nullable().optional(),requestedRef:z.string().nullable().optional(),resolvedRef:z.string().nullable().optional(),commitSha:z.string().nullable().optional()}).nullable().optional();var navigationDiagnosticsSchema=z.object({hint:z.string().nullable().optional()}).nullable().optional();var repoFileEntrySchema=z.object({path:z.string(),name:z.string().nullable().optional(),language:z.string().nullable().optional(),fileType:z.string().nullable().optional(),byteSize:z.number().int().nullable().optional()});var listRepoFilesResponseSchema=z.object({files:z.array(repoFileEntrySchema),total:z.number().int(),hasMore:z.boolean(),indexedVersion:z.string().nullable().optional(),resolution:navigationResolutionSchema,targetResolution:targetResolutionSchema,diagnostics:navigationDiagnosticsSchema,codeIndexState:z.string(),indexingRef:z.string().nullable().optional(),availableVersions:z.array(availableVersionSchema).nullable().optional()});var listRepoFilesGraphQLResponseSchema=z.object({data:z.object({listRepoFiles:listRepoFilesResponseSchema.nullable().optional()}).nullable().optional(),errors:z.array(graphQLErrorSchema).optional()});var LIST_REPO_FILES_QUERY=`
|
|
294
|
+
query ListRepoFiles(
|
|
295
|
+
$registry: Registry
|
|
296
|
+
$packageName: String
|
|
297
|
+
$repoUrl: String
|
|
298
|
+
$gitRef: String
|
|
299
|
+
$version: String
|
|
300
|
+
$pathPrefix: String
|
|
301
|
+
$pathSelectors: [FilePathSelectorInput!]
|
|
302
|
+
$extensions: [String!]
|
|
303
|
+
$fileTypes: [String!]
|
|
304
|
+
$languages: [String!]
|
|
305
|
+
$fileIntent: FileIntent
|
|
306
|
+
$fileIntents: [FileIntent!]
|
|
307
|
+
$excludeFileIntents: [FileIntent!]
|
|
308
|
+
$excludeDocFiles: Boolean
|
|
309
|
+
$excludeTestFiles: Boolean
|
|
310
|
+
$includeHidden: Boolean
|
|
311
|
+
$limit: Int
|
|
312
|
+
$waitTimeoutMs: Int
|
|
313
|
+
) {
|
|
314
|
+
listRepoFiles(
|
|
315
|
+
registry: $registry
|
|
316
|
+
packageName: $packageName
|
|
317
|
+
repoUrl: $repoUrl
|
|
318
|
+
gitRef: $gitRef
|
|
319
|
+
version: $version
|
|
320
|
+
pathPrefix: $pathPrefix
|
|
321
|
+
pathSelectors: $pathSelectors
|
|
322
|
+
extensions: $extensions
|
|
323
|
+
fileTypes: $fileTypes
|
|
324
|
+
languages: $languages
|
|
325
|
+
fileIntent: $fileIntent
|
|
326
|
+
fileIntents: $fileIntents
|
|
327
|
+
excludeFileIntents: $excludeFileIntents
|
|
328
|
+
excludeDocFiles: $excludeDocFiles
|
|
329
|
+
excludeTestFiles: $excludeTestFiles
|
|
330
|
+
includeHidden: $includeHidden
|
|
331
|
+
limit: $limit
|
|
332
|
+
waitTimeoutMs: $waitTimeoutMs
|
|
333
|
+
) {
|
|
334
|
+
files {
|
|
335
|
+
path
|
|
336
|
+
name
|
|
337
|
+
language
|
|
338
|
+
fileType
|
|
339
|
+
byteSize
|
|
340
|
+
}
|
|
341
|
+
total
|
|
342
|
+
hasMore
|
|
343
|
+
indexedVersion
|
|
344
|
+
resolution {
|
|
345
|
+
requestedVersion
|
|
346
|
+
requestedRef
|
|
347
|
+
resolvedRef
|
|
348
|
+
commitSha
|
|
349
|
+
}
|
|
350
|
+
${TARGET_RESOLUTION_SELECTION}
|
|
351
|
+
diagnostics {
|
|
352
|
+
hint
|
|
353
|
+
}
|
|
354
|
+
codeIndexState
|
|
355
|
+
indexingRef
|
|
356
|
+
availableVersions {
|
|
357
|
+
version
|
|
358
|
+
ref
|
|
359
|
+
}
|
|
360
|
+
}
|
|
361
|
+
}`;var codeContextResponseSchema=z.object({content:z.string().nullable().optional(),filePath:z.string().nullable().optional(),language:z.string().nullable().optional(),totalLines:z.number().int().nullable().optional(),startLine:z.number().int().nullable().optional(),endLine:z.number().int().nullable().optional(),repoUrl:z.string().nullable().optional(),gitRef:z.string().nullable().optional(),isBinary:z.boolean().nullable().optional(),codeIndexState:z.string(),indexingRef:z.string().nullable().optional(),availableVersions:z.array(availableVersionSchema).nullable().optional(),targetResolution:targetResolutionSchema});var fetchCodeContextGraphQLResponseSchema=z.object({data:z.object({fetchCodeContext:codeContextResponseSchema.nullable().optional()}).nullable().optional(),errors:z.array(graphQLErrorSchema).optional()});var FETCH_CODE_CONTEXT_QUERY=`
|
|
362
|
+
query FetchCodeContext(
|
|
363
|
+
$registry: Registry
|
|
364
|
+
$packageName: String
|
|
365
|
+
$repoUrl: String
|
|
366
|
+
$gitRef: String
|
|
367
|
+
$version: String
|
|
368
|
+
$filePath: String!
|
|
369
|
+
$startLine: Int
|
|
370
|
+
$endLine: Int
|
|
371
|
+
$waitTimeoutMs: Int
|
|
372
|
+
) {
|
|
373
|
+
fetchCodeContext(
|
|
374
|
+
registry: $registry
|
|
375
|
+
packageName: $packageName
|
|
376
|
+
repoUrl: $repoUrl
|
|
377
|
+
gitRef: $gitRef
|
|
378
|
+
version: $version
|
|
379
|
+
filePath: $filePath
|
|
380
|
+
startLine: $startLine
|
|
381
|
+
endLine: $endLine
|
|
382
|
+
waitTimeoutMs: $waitTimeoutMs
|
|
383
|
+
) {
|
|
384
|
+
content
|
|
385
|
+
filePath
|
|
386
|
+
language
|
|
387
|
+
totalLines
|
|
388
|
+
startLine
|
|
389
|
+
endLine
|
|
390
|
+
repoUrl
|
|
391
|
+
gitRef
|
|
392
|
+
isBinary
|
|
393
|
+
codeIndexState
|
|
394
|
+
indexingRef
|
|
395
|
+
${CODE_CONTEXT_AVAILABLE_VERSIONS_SELECTION}
|
|
396
|
+
${TARGET_RESOLUTION_SELECTION}
|
|
397
|
+
}
|
|
398
|
+
}`;var grepRepoMatchSchema=z.object({filePath:z.string(),line:z.number().int(),matchStartByte:z.number().int(),matchEndByte:z.number().int(),lineContent:z.string(),contextBefore:z.array(z.string()).nullable().optional(),contextAfter:z.array(z.string()).nullable().optional(),fileContentHash:z.string().nullable().optional(),fileIntent:z.string().nullable().optional(),symbolRowId:z.string().nullable().optional(),symbol:z.object({symbolRef:z.string().optional(),name:z.string().optional(),qualifiedPath:z.string().nullable().optional(),kind:z.string().nullable().optional(),category:z.string().nullable().optional(),arity:z.number().int().nullable().optional(),isPublic:z.boolean().nullable().optional(),filePath:z.string().nullable().optional(),startLine:z.number().int().nullable().optional(),endLine:z.number().int().nullable().optional(),code:z.string().nullable().optional(),callerCount:z.number().int().nullable().optional(),contentHash:z.string().nullable().optional(),parentSymbolRef:z.string().nullable().optional(),parentPath:z.string().nullable().optional()}).nullable().optional()});var grepRepoResponseSchema=z.object({matches:z.array(grepRepoMatchSchema),nextCursor:z.string().nullable().optional(),hasMore:z.boolean(),truncatedReason:z.enum(["NONE","MAX_MATCHES","MAX_MATCHES_PER_FILE","DEADLINE"]),routeTaken:z.enum(["SINGLE_FILE","CONTENT_INDEX"]).nullable().optional(),filesScanned:z.number().int(),filesInScope:z.number().int(),binaryFilesSkipped:z.number().int(),filesTooLargeSkipped:z.number().int(),totalMatches:z.number().int(),uniqueFilesMatched:z.number().int(),indexedVersion:z.string().nullable().optional(),resolution:navigationResolutionSchema,targetResolution:targetResolutionSchema,codeIndexState:z.string(),indexingRef:z.string().nullable().optional(),availableVersions:z.array(availableVersionSchema).nullable().optional()});var grepRepoGraphQLResponseSchema=z.object({data:z.object({grepRepo:grepRepoResponseSchema.nullable().optional()}).nullable().optional(),errors:z.array(graphQLErrorSchema).optional()});var GREP_REPO_SYMBOL_SELECTIONS={symbol_ref:"symbolRef",name:"name",qualified_path:"qualifiedPath",kind:"kind",category:"category",arity:"arity",is_public:"isPublic",file_path:"filePath",start_line:"startLine",end_line:"endLine",code:"code",caller_count:"callerCount",content_hash:"contentHash",parent_symbol_ref:"parentSymbolRef",parent_path:"parentPath"};function buildGrepRepoQuery(symbolFields){const symbolSelection=(symbolFields??[]).map((field)=>GREP_REPO_SYMBOL_SELECTIONS[field]).filter((field)=>Boolean(field)).filter((field,index,fields)=>fields.indexOf(field)===index).join(`
|
|
399
|
+
`);const symbolBlock=symbolSelection.length>0?`
|
|
400
|
+
symbol {
|
|
401
|
+
${symbolSelection}
|
|
402
|
+
}`:"";return`
|
|
403
|
+
query GrepRepo(
|
|
404
|
+
$registry: Registry
|
|
405
|
+
$packageName: String
|
|
406
|
+
$repoUrl: String
|
|
407
|
+
$gitRef: String
|
|
408
|
+
$version: String
|
|
409
|
+
$waitTimeoutMs: Int
|
|
410
|
+
$pattern: String!
|
|
411
|
+
$patternType: GrepPatternType
|
|
412
|
+
$caseSensitive: Boolean
|
|
413
|
+
$pathSelectors: [GrepPathSelectorInput!]
|
|
414
|
+
$extensions: [String!]
|
|
415
|
+
$excludeDocFiles: Boolean
|
|
416
|
+
$excludeTestFiles: Boolean
|
|
417
|
+
$allowUnscoped: Boolean
|
|
418
|
+
$contextLinesBefore: Int
|
|
419
|
+
$contextLinesAfter: Int
|
|
420
|
+
$maxMatches: Int
|
|
421
|
+
$maxMatchesPerFile: Int
|
|
422
|
+
$cursor: String
|
|
423
|
+
$symbolFields: [String!]
|
|
424
|
+
) {
|
|
425
|
+
grepRepo(
|
|
426
|
+
registry: $registry
|
|
427
|
+
packageName: $packageName
|
|
428
|
+
repoUrl: $repoUrl
|
|
429
|
+
gitRef: $gitRef
|
|
430
|
+
version: $version
|
|
431
|
+
waitTimeoutMs: $waitTimeoutMs
|
|
432
|
+
pattern: $pattern
|
|
433
|
+
patternType: $patternType
|
|
434
|
+
caseSensitive: $caseSensitive
|
|
435
|
+
pathSelectors: $pathSelectors
|
|
436
|
+
extensions: $extensions
|
|
437
|
+
excludeDocFiles: $excludeDocFiles
|
|
438
|
+
excludeTestFiles: $excludeTestFiles
|
|
439
|
+
allowUnscoped: $allowUnscoped
|
|
440
|
+
contextLinesBefore: $contextLinesBefore
|
|
441
|
+
contextLinesAfter: $contextLinesAfter
|
|
442
|
+
maxMatches: $maxMatches
|
|
443
|
+
maxMatchesPerFile: $maxMatchesPerFile
|
|
444
|
+
cursor: $cursor
|
|
445
|
+
symbolFields: $symbolFields
|
|
446
|
+
) {
|
|
447
|
+
matches {
|
|
448
|
+
filePath
|
|
449
|
+
line
|
|
450
|
+
matchStartByte
|
|
451
|
+
matchEndByte
|
|
452
|
+
lineContent
|
|
453
|
+
contextBefore
|
|
454
|
+
contextAfter
|
|
455
|
+
fileContentHash
|
|
456
|
+
fileIntent
|
|
457
|
+
symbolRowId${symbolBlock}
|
|
458
|
+
}
|
|
459
|
+
nextCursor
|
|
460
|
+
totalMatches
|
|
461
|
+
hasMore
|
|
462
|
+
truncatedReason
|
|
463
|
+
routeTaken
|
|
464
|
+
filesScanned
|
|
465
|
+
filesInScope
|
|
466
|
+
binaryFilesSkipped
|
|
467
|
+
filesTooLargeSkipped
|
|
468
|
+
uniqueFilesMatched
|
|
469
|
+
indexedVersion
|
|
470
|
+
resolution {
|
|
471
|
+
requestedVersion
|
|
472
|
+
requestedRef
|
|
473
|
+
resolvedRef
|
|
474
|
+
commitSha
|
|
475
|
+
}
|
|
476
|
+
${TARGET_RESOLUTION_SELECTION}
|
|
477
|
+
codeIndexState
|
|
478
|
+
indexingRef
|
|
479
|
+
availableVersions {
|
|
480
|
+
version
|
|
481
|
+
ref
|
|
482
|
+
}
|
|
483
|
+
}
|
|
484
|
+
}`}var unifiedSearchGraphQLResponseSchema=z.object({data:z.object({search:asyncUnifiedSearchResultSchema.nullable().optional()}).nullable().optional(),errors:z.array(graphQLErrorSchema).optional()});var unifiedSearchStatusGraphQLResponseSchema=z.object({data:z.object({discoverySearchProgress:unifiedSearchProgressSchema.nullable().optional()}).nullable().optional(),errors:z.array(graphQLErrorSchema).optional()});class CodeNavigationServiceImpl{codeNavigationUrl;tokenProvider;fetchFn;runtime;constructor(codeNavigationUrl,tokenProvider,fetchFn=globalThis.fetch,runtime={}){this.codeNavigationUrl=codeNavigationUrl;this.tokenProvider=tokenProvider;this.fetchFn=fetchFn;this.runtime=runtime}async postGraphqlWithTargetResolutionFallback(input){const response=await postPkgseerGraphql({endpointUrl:this.codeNavigationUrl,token:input.token,query:input.query,variables:input.variables,fetchFn:this.fetchFn,clientHeaders:this.runtime.clientHeaders,userAgent:this.runtime.userAgent});if(response.status<200||response.status>=300)return response;if(!hasSchemaMismatchErrors(response.parsedBody))return response;for(const fallbackQuery of buildTargetResolutionFallbackQueries(input.query)){debugLog("code-nav",{event:"target-resolution-query-fallback"});const fallbackResponse=await postPkgseerGraphql({endpointUrl:this.codeNavigationUrl,token:input.token,query:fallbackQuery,variables:input.variables,fetchFn:this.fetchFn,clientHeaders:this.runtime.clientHeaders,userAgent:this.runtime.userAgent});if(!hasSchemaMismatchErrors(fallbackResponse.parsedBody)){return fallbackResponse}}return response}async search(params){return executeWithTokenRefresh({getToken:()=>this.tokenProvider.getToken(),forceRefresh:()=>this.tokenProvider.forceRefresh(),shouldRefresh:(error)=>error instanceof AuthenticationError,executeWithToken:(token)=>this.executeUnifiedSearch(token,params)})}async searchStatus(searchRef){return executeWithTokenRefresh({getToken:()=>this.tokenProvider.getToken(),forceRefresh:()=>this.tokenProvider.forceRefresh(),shouldRefresh:(error)=>error instanceof AuthenticationError,executeWithToken:(token)=>this.executeUnifiedSearchStatus(token,searchRef)})}async executeUnifiedSearch(token,params){if(params.targets.length===0){throw new CodeNavigationValidationError("At least one search target is required.")}let response;const variables={targets:params.targets.map((target)=>({registry:target.registry,name:target.packageName,version:target.version,repoUrl:target.repoUrl,gitRef:target.gitRef})),query:params.query,sources:params.sources,filters:params.filters,allowPartialResults:params.allowPartialResults??false,limit:params.limit,offset:params.offset,waitTimeoutMs:params.waitTimeoutMs};debugUnifiedSearchRequest(variables);debugGraphqlWireRequest("search",UNIFIED_SEARCH_QUERY,variables);try{response=await this.postGraphqlWithTargetResolutionFallback({token,query:UNIFIED_SEARCH_QUERY,variables})}catch(cause){if(cause instanceof PkgseerTransportError){throw this.createTransportError(cause)}throw cause}if(response.status<200||response.status>=300){throw this.createHttpError(response)}const parsed=unifiedSearchGraphQLResponseSchema.safeParse(response.parsedBody);if(!parsed.success){throw new MalformedCodeNavigationResponseError("Malformed response from code navigation service.")}if(parsed.data.errors&&parsed.data.errors.length>0){throw this.createGraphQLError(parsed.data.errors)}const data=parsed.data.data?.search;if(!data){throw new MalformedCodeNavigationResponseError("Malformed response from code navigation service.")}return this.normaliseUnifiedSearchOutcome(data)}async executeUnifiedSearchStatus(token,searchRef){let response;try{response=await this.postGraphqlWithTargetResolutionFallback({token,query:UNIFIED_SEARCH_STATUS_QUERY,variables:{searchRef,includeResults:true}})}catch(cause){if(cause instanceof PkgseerTransportError){throw this.createTransportError(cause)}throw cause}if(response.status<200||response.status>=300){throw this.createHttpError(response)}const parsed=unifiedSearchStatusGraphQLResponseSchema.safeParse(response.parsedBody);if(!parsed.success){throw new MalformedCodeNavigationResponseError("Malformed response from code navigation service.")}if(parsed.data.errors&&parsed.data.errors.length>0){throw this.createGraphQLError(parsed.data.errors)}const data=parsed.data.data?.discoverySearchProgress;if(!data){throw new MalformedCodeNavigationResponseError("Malformed response from code navigation service.")}const progress=this.normaliseUnifiedSearchProgress(data);const result=data.results?this.normaliseUnifiedSearchResult(data.results):undefined;if(result&&progress.status==="COMPLETED"){return{state:"completed",completed:true,searchRef:progress.searchRef,result,progress}}return{state:"incomplete",completed:false,searchRef:progress.searchRef,result,progress}}createHttpError(response){const status=response.status;const detail=parseDetail2(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);if(isClientUpdateRequiredGraphQLError({message,code})){return new ClientUpdateRequiredError(undefined,undefined,this.runtime.clientVersion)}if(isGraphQLSchemaMismatchError({message,code})){const sanitized="Backend protocol mismatch. Your CLI may be newer than the server, or the server may require a newer CLI. Run `githits update-check` to verify your installed version. Set GITHITS_DEBUG=code-nav-wire to inspect GraphQL details during local development.";debugLog("code-nav",{event:"graphql-schema-mismatch",code:code??"omitted",message});return new CodeNavigationBackendError(isDebugAreaEnabled("code-nav-wire")?message:sanitized,undefined,code,retryable)}switch(code){case"PACKAGE_INDEXING":return new CodeNavigationIndexingError(this.createIndexingMessage(indexingRef),indexingRef,parseAvailableVersions(extensions),parseAvailableRefs(extensions),parseTargetResolution(extensions));case"GREP_PATTERN_TOO_SHORT":case"GREP_PATTERN_TOO_LONG":case"GREP_PATTERN_INVALID":case"GREP_INVALID_REGEX":case"GREP_UNSUPPORTED_PATTERN":case"GREP_PATTERN_TOO_UNSELECTIVE":case"GREP_SCOPE_REQUIRED":case"GREP_SELECTOR_INVALID":case"GREP_CURSOR_INVALID":case"GREP_CONTEXT_TOO_LARGE":case"GREP_CONTEXT_NEGATIVE":case"GREP_MAX_MATCHES_TOO_LARGE":case"GREP_MAX_MATCHES_INVALID":return new CodeNavigationValidationError(message);case"VERSION_NOT_FOUND":return new CodeNavigationVersionNotFoundError(message,typeof extensions?.package==="string"?extensions.package:undefined,typeof extensions?.requested_version==="string"?extensions.requested_version:undefined,typeof extensions?.latest_indexed==="string"?extensions.latest_indexed:undefined,parseAvailableVersions(extensions));case"NOT_FOUND":case"PACKAGE_NOT_FOUND":case"NO_REPOSITORY_URL":return new CodeNavigationTargetNotFoundError(message);case"FILE_NOT_FOUND":return new CodeNavigationFileNotFoundError(message,typeof extensions?.file_path==="string"?extensions.file_path:typeof extensions?.filePath==="string"?extensions.filePath:undefined);case"UNSUPPORTED_REGISTRY":case"VALIDATION_ERROR":return new CodeNavigationValidationError(message);case"FEATURE_FLAG_REQUIRED":return new CodeNavigationFeatureFlagRequiredError(message);case"UNAUTHORIZED":return new AuthenticationError(SERVER_AUTHENTICATION_REJECTED_MESSAGE,"server");case"FORBIDDEN":return new CodeNavigationAccessError("Code navigation access denied. This feature may not be enabled for your account.");case"UPSTREAM_ERROR":case"TIMEOUT":case"RATE_LIMITED":case"GREP_FILE_TOO_LARGE":case"GREP_TIMEOUT":case"GREP_SERVICE_UNAVAILABLE":case"GREP_FAILED":case"GREP_INDEX_NOT_AVAILABLE":case"INTERNAL_ERROR":case"UNKNOWN_ERROR":return new CodeNavigationBackendError(message,undefined,code,retryable);default:break}if(code===undefined){if(isAuthMessage(message)){return new CodeNavigationAccessError("Code navigation access denied. This feature may not be enabled for your account.")}if(isUnresolvableMessage(message)){return new CodeNavigationUnresolvableError(message)}if(isTargetNotFoundMessage(message)){return new CodeNavigationTargetNotFoundError(message)}}return new CodeNavigationBackendError(message,undefined,code,retryable)}createIndexingMessage(indexingRef){const base="Target is still indexing. Indexing usually completes within 30 seconds. Retry this request, or pass a longer wait timeout (CLI: `--wait 60000`, MCP: `wait_timeout_ms: 60000`) to block until ready.";if(indexingRef){return`${base} Indexing reference: ${indexingRef}.`}return base}normaliseUnifiedSearchOutcome(data){const progress=data.progress?this.normaliseUnifiedSearchProgress(data.progress):undefined;if(data.completed){if(!data.result){throw new MalformedCodeNavigationResponseError("Completed unified search response missing result payload.")}return{state:"completed",completed:true,searchRef:data.searchRef??undefined,result:this.normaliseUnifiedSearchResult(data.result),progress}}const searchRef=data.searchRef??progress?.searchRef;if(!searchRef){throw new MalformedCodeNavigationResponseError("Incomplete unified search response missing search reference.")}const result=data.result?this.normaliseUnifiedSearchResult(data.result):undefined;return{state:"incomplete",completed:false,searchRef,result,progress}}normaliseUnifiedSearchResult(result){return{query:result.query,queryWarnings:result.queryWarnings,sources:result.sources,results:result.results.map((entry)=>({id:entry.id,resultType:entry.resultType,targetLabel:entry.targetLabel,requestedTargetLabel:entry.requestedTargetLabel??undefined,freshTargetLabel:entry.freshTargetLabel??undefined,servedTargetLabel:entry.servedTargetLabel??undefined,freshness:entry.freshness??undefined,title:entry.title??undefined,summary:entry.summary??undefined,score:entry.score??undefined,highlights:entry.highlights?{title:entry.highlights.title??undefined,summary:entry.highlights.summary??undefined}:undefined,locator:{registry:entry.locator.registry??undefined,packageName:entry.locator.packageName??undefined,version:entry.locator.version??undefined,pageId:entry.locator.pageId??undefined,sourceKind:entry.locator.sourceKind??undefined,sourceUrl:entry.locator.sourceUrl??undefined,repoUrl:entry.locator.repoUrl??undefined,gitRef:entry.locator.gitRef??undefined,requestedRef:entry.locator.requestedRef??undefined,filePath:entry.locator.filePath??undefined,startLine:entry.locator.startLine??undefined,endLine:entry.locator.endLine??undefined,fileContentHash:entry.locator.fileContentHash??undefined,symbolRef:entry.locator.symbolRef??undefined,qualifiedPath:entry.locator.qualifiedPath??undefined,kind:entry.locator.kind??undefined,category:entry.locator.category??undefined,language:entry.locator.language??undefined}})),page:{offset:result.page.offset,limit:result.page.limit,returned:result.page.returned,hasMore:result.page.hasMore},partialResults:result.partialResults,sourceStatus:result.sourceStatus.map((entry)=>({source:entry.source,targetLabel:entry.targetLabel,requestedTargetLabel:entry.requestedTargetLabel??undefined,freshTargetLabel:entry.freshTargetLabel??undefined,servedTargetLabel:entry.servedTargetLabel??undefined,targetResolution:normaliseTargetResolution(entry.targetResolution),indexingStatus:entry.indexingStatus??undefined,codeIndexState:entry.codeIndexState??undefined,resultCount:entry.resultCount??undefined,appliedFilters:entry.appliedFilters,ignoredFilters:entry.ignoredFilters,incompatibleFilters:entry.incompatibleFilters,appliedQueryFeatures:entry.appliedQueryFeatures,ignoredQueryFeatures:entry.ignoredQueryFeatures,incompatibleQueryFeatures:entry.incompatibleQueryFeatures,note:entry.note??undefined}))}}normaliseUnifiedSearchProgress(progress){return{searchRef:progress.searchRef,status:progress.status,targetsTotal:progress.targetsTotal,targetsReady:progress.targetsReady,elapsedMs:progress.elapsedMs,query:progress.query,queryWarnings:progress.queryWarnings,sources:progress.sources,requestedSources:progress.requestedSources??undefined,targetMode:normaliseTargetMode(progress.targetMode),requestedTargets:progress.requestedTargets?.map((target)=>({registry:target.registry?target.registry:undefined,name:target.name??undefined,version:target.version??undefined,repoUrl:target.repoUrl??undefined,gitRef:target.gitRef??undefined})),filters:normaliseProgressFilters(progress.filters),limit:progress.limit??undefined,offset:progress.offset??undefined,targets:progress.targets?.map((target)=>({requested:target.requested??undefined,resolvedRequested:target.resolvedRequested??undefined,served:target.served??undefined,freshness:target.freshness??undefined,indexingRef:target.indexingRef??undefined,requestedRefKind:normaliseRequestedRefKind(target.requestedRefKind),targetResolution:normaliseTargetResolution(target.targetResolution),availableVersions:normaliseAvailableVersions(target.availableVersions),availableRefs:normaliseAvailableVersions(target.availableRefs)})),expiresAt:progress.expiresAt??undefined}}throwIfIndexing(data){if(data.codeIndexState==="INDEXING"){const targetResolution=normaliseTargetResolution(data.targetResolution);throw new CodeNavigationIndexingError(this.createIndexingMessage(data.indexingRef??targetResolution?.indexingRef),data.indexingRef??targetResolution?.indexingRef,normaliseAvailableVersions(data.availableVersions)??targetResolution?.availableVersions,targetResolution?.availableRefs,targetResolution)}}async listFiles(params){return executeWithTokenRefresh({getToken:()=>this.tokenProvider.getToken(),forceRefresh:()=>this.tokenProvider.forceRefresh(),shouldRefresh:(error)=>error instanceof AuthenticationError,executeWithToken:(token)=>this.executeListFiles(token,params)})}async executeListFiles(token,params){let response;try{response=await this.postGraphqlWithTargetResolutionFallback({token,query:LIST_REPO_FILES_QUERY,variables:{registry:params.target.registry,packageName:params.target.packageName,repoUrl:params.target.repoUrl,gitRef:params.target.gitRef,version:params.target.version,pathPrefix:params.pathPrefix,pathSelectors:params.pathSelectors?.map((entry)=>({kind:entry.kind,value:entry.value})),extensions:params.extensions,fileTypes:params.fileTypes,languages:params.languages,fileIntent:params.fileIntent,fileIntents:params.fileIntents,excludeFileIntents:params.excludeFileIntents,excludeDocFiles:params.excludeDocFiles,excludeTestFiles:params.excludeTestFiles,includeHidden:params.includeHidden,limit:params.limit,waitTimeoutMs:params.waitTimeoutMs}})}catch(cause){if(cause instanceof PkgseerTransportError){throw this.createTransportError(cause)}throw cause}if(response.status<200||response.status>=300){throw this.createHttpError(response)}const parsed=listRepoFilesGraphQLResponseSchema.safeParse(response.parsedBody);if(!parsed.success){throw new MalformedCodeNavigationResponseError("Malformed response from code navigation service.")}if(parsed.data.errors&&parsed.data.errors.length>0){throw this.createGraphQLError(parsed.data.errors)}const data=parsed.data.data?.listRepoFiles;if(!data){throw new MalformedCodeNavigationResponseError("Malformed response from code navigation service.")}this.throwIfIndexing(data);return{files:data.files.map((entry)=>({path:entry.path,name:entry.name??undefined,language:entry.language??undefined,fileType:entry.fileType??undefined,byteSize:entry.byteSize??undefined})),total:data.total,hasMore:data.hasMore,indexedVersion:data.indexedVersion??undefined,resolution:data.resolution?{requestedVersion:data.resolution.requestedVersion??undefined,requestedRef:data.resolution.requestedRef??undefined,resolvedRef:data.resolution.resolvedRef??undefined,commitSha:data.resolution.commitSha??undefined}:undefined,targetResolution:normaliseTargetResolution(data.targetResolution),hint:data.diagnostics?.hint??undefined}}async readFile(params){return executeWithTokenRefresh({getToken:()=>this.tokenProvider.getToken(),forceRefresh:()=>this.tokenProvider.forceRefresh(),shouldRefresh:(error)=>error instanceof AuthenticationError,executeWithToken:(token)=>this.executeReadFile(token,params)})}async executeReadFile(token,params){let response;try{response=await this.postGraphqlWithTargetResolutionFallback({token,query:FETCH_CODE_CONTEXT_QUERY,variables:{registry:params.target.registry,packageName:params.target.packageName,repoUrl:params.target.repoUrl,gitRef:params.target.gitRef,version:params.target.version,filePath:params.filePath,startLine:params.startLine,endLine:params.endLine,waitTimeoutMs:params.waitTimeoutMs}})}catch(cause){if(cause instanceof PkgseerTransportError){throw this.createTransportError(cause)}throw cause}if(response.status<200||response.status>=300){throw this.createHttpError(response)}const parsed=fetchCodeContextGraphQLResponseSchema.safeParse(response.parsedBody);if(!parsed.success){throw new MalformedCodeNavigationResponseError("Malformed response from code navigation service.")}if(parsed.data.errors&&parsed.data.errors.length>0){throw this.createGraphQLError(parsed.data.errors)}const data=parsed.data.data?.fetchCodeContext;if(!data){throw new MalformedCodeNavigationResponseError("Malformed response from code navigation service.")}this.throwIfIndexing(data);return{filePath:data.filePath??undefined,language:data.language??undefined,totalLines:data.totalLines??undefined,startLine:data.startLine??undefined,endLine:data.endLine??undefined,content:data.content??undefined,isBinary:data.isBinary??undefined,targetResolution:normaliseTargetResolution(data.targetResolution),availableVersions:normaliseAvailableVersions(data.availableVersions)}}async grepRepo(params){return executeWithTokenRefresh({getToken:()=>this.tokenProvider.getToken(),forceRefresh:()=>this.tokenProvider.forceRefresh(),shouldRefresh:(error)=>error instanceof AuthenticationError,executeWithToken:(token)=>this.executeGrepRepo(token,params)})}async executeGrepRepo(token,params){let response;try{response=await this.postGraphqlWithTargetResolutionFallback({token,query:buildGrepRepoQuery(params.symbolFields),variables:{registry:params.target.registry,packageName:params.target.packageName,repoUrl:params.target.repoUrl,gitRef:params.target.gitRef,version:params.target.version,waitTimeoutMs:params.waitTimeoutMs,pattern:params.pattern,patternType:params.patternType,caseSensitive:params.caseSensitive,pathSelectors:params.pathSelectors?.map((entry)=>({kind:entry.kind,value:entry.value})),extensions:params.extensions,excludeDocFiles:params.excludeDocFiles,excludeTestFiles:params.excludeTestFiles,allowUnscoped:params.allowUnscoped,contextLinesBefore:params.contextLinesBefore,contextLinesAfter:params.contextLinesAfter,maxMatches:params.maxMatches,maxMatchesPerFile:params.maxMatchesPerFile,cursor:params.cursor,symbolFields:params.symbolFields}})}catch(cause){if(cause instanceof PkgseerTransportError){throw this.createTransportError(cause)}throw cause}if(response.status<200||response.status>=300){throw this.createHttpError(response)}const parsed=grepRepoGraphQLResponseSchema.safeParse(response.parsedBody);if(!parsed.success){throw new MalformedCodeNavigationResponseError("Malformed response from code navigation service.")}if(parsed.data.errors&&parsed.data.errors.length>0){throw this.createGraphQLError(parsed.data.errors)}const data=parsed.data.data?.grepRepo;if(!data){throw new MalformedCodeNavigationResponseError("Malformed response from code navigation service.")}this.throwIfIndexing(data);return{matches:data.matches.map((entry)=>({filePath:entry.filePath,line:entry.line,matchStartByte:entry.matchStartByte,matchEndByte:entry.matchEndByte,lineContent:entry.lineContent,contextBefore:entry.contextBefore??undefined,contextAfter:entry.contextAfter??undefined,fileContentHash:entry.fileContentHash??undefined,fileIntent:entry.fileIntent??undefined,symbolRowId:entry.symbolRowId??undefined,symbol:entry.symbol?{symbolRef:entry.symbol.symbolRef,name:entry.symbol.name,qualifiedPath:entry.symbol.qualifiedPath??undefined,kind:entry.symbol.kind??undefined,category:entry.symbol.category??undefined,arity:entry.symbol.arity??undefined,isPublic:entry.symbol.isPublic??undefined,filePath:entry.symbol.filePath??undefined,startLine:entry.symbol.startLine??undefined,endLine:entry.symbol.endLine??undefined,code:entry.symbol.code??undefined,callerCount:entry.symbol.callerCount??undefined,contentHash:entry.symbol.contentHash??undefined,parentSymbolRef:entry.symbol.parentSymbolRef??undefined,parentPath:entry.symbol.parentPath??undefined}:undefined})),nextCursor:data.nextCursor??undefined,hasMore:data.hasMore,truncatedReason:data.truncatedReason,routeTaken:data.routeTaken??undefined,filesScanned:data.filesScanned,filesInScope:data.filesInScope,binaryFilesSkipped:data.binaryFilesSkipped,filesTooLargeSkipped:data.filesTooLargeSkipped,totalMatches:data.totalMatches,uniqueFilesMatched:data.uniqueFilesMatched,indexedVersion:data.indexedVersion??undefined,resolution:data.resolution?{requestedVersion:data.resolution.requestedVersion??undefined,requestedRef:data.resolution.requestedRef??undefined,resolvedRef:data.resolution.resolvedRef??undefined,commitSha:data.resolution.commitSha??undefined}:undefined,targetResolution:normaliseTargetResolution(data.targetResolution)}}}function 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 buildTargetResolutionFallbackQueries(query){const candidates=[query.replaceAll(TARGET_RESOLUTION_AVAILABLE_REFS_SELECTION,""),query.replaceAll(DISCOVERY_TARGET_PROGRESS_RETRY_SELECTION,""),query.replaceAll(CODE_CONTEXT_AVAILABLE_VERSIONS_SELECTION,""),query.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 parseTargetResolution(extensions){const raw=extensions?.target_resolution??extensions?.targetResolution;const parsed=targetResolutionSchema.safeParse(raw);if(!parsed.success)return;return normaliseTargetResolution(parsed.data)}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)??[]}}function normaliseTargetResolutionIdentity(identity){if(!identity)return;const out={};if(identity.kind)out.kind=identity.kind;if(identity.registry)out.registry=identity.registry;if(identity.packageName)out.packageName=identity.packageName;if(identity.version)out.version=identity.version;if(identity.repoUrl)out.repoUrl=identity.repoUrl;if(identity.gitRef)out.gitRef=identity.gitRef;if(identity.commitSha)out.commitSha=identity.commitSha;return Object.keys(out).length>0?out:undefined}function isAuthMessage(message){const lower=message.toLowerCase();return lower.includes("unauthorized")||lower.includes("forbidden")||lower.includes("permission")||lower.includes("authentication")}function normaliseTargetMode(value){if(value==="PACKAGES"||value==="REPO"||value==="MIXED"){return value}return}function normaliseRequestedRefKind(value){switch(value){case"OMITTED_VERSION":case"LATEST_VERSION":case"EXACT_VERSION":case"DEFAULT_BRANCH":case"HEAD":case"BRANCH":case"SHA":return value;default:return}}function normaliseProgressFilters(filters){if(!filters)return;const out={};if(filters.fileIntent)out.fileIntent=filters.fileIntent;if(filters.kind)out.kind=filters.kind;if(filters.category)out.category=filters.category;if(typeof filters.publicOnly==="boolean"){out.publicOnly=filters.publicOnly}if(filters.pathPrefix)out.pathPrefix=filters.pathPrefix;return Object.keys(out).length>0?out:undefined}function isTargetNotFoundMessage(message){const lower=message.toLowerCase();return lower.includes("not found")||lower.includes("unknown package")||lower.includes("no such package")||lower.includes("does not exist")}function isUnresolvableMessage(message){const lower=message.toLowerCase();return lower.includes("could not resolve")||lower.includes("cannot resolve")}var DEFAULT_MCP_URL="https://mcp.githits.com";var DEFAULT_API_URL="https://api.githits.com";var DEFAULT_CODE_NAV_URL="https://pkgseer.dev";function getMcpUrl(){return process.env.GITHITS_MCP_URL??DEFAULT_MCP_URL}function getApiUrl(){return process.env.GITHITS_API_URL??DEFAULT_API_URL}function getCodeNavigationUrl(){const explicitUrl=process.env.GITHITS_CODE_NAV_URL??process.env.PKGSEER_URL;if(explicitUrl){return explicitUrl}return DEFAULT_CODE_NAV_URL}function getEnvApiToken(){return process.env.GITHITS_API_TOKEN}import{z as z2}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=z2.object({stargazersCount:z2.number().int().nullable().optional(),forksCount:z2.number().int().nullable().optional(),openIssuesCount:z2.number().int().nullable().optional(),archived:z2.boolean().nullable().optional(),language:z2.string().nullable().optional(),topics:z2.array(z2.string()).nullable().optional(),pushedAt:z2.string().nullable().optional()}).nullable().optional();var packageIdentitySchema=z2.object({name:z2.string().nullable().optional(),registry:z2.string().nullable().optional(),description:z2.string().nullable().optional(),latestVersion:z2.string().nullable().optional(),latestVersionPublishedAt:z2.string().nullable().optional(),homepage:z2.string().nullable().optional(),repositoryUrl:z2.string().nullable().optional(),license:z2.string().nullable().optional(),downloadsLastMonth:z2.number().int().nullable().optional(),downloadsTotal:z2.number().int().nullable().optional(),githubRepository:githubRepositorySchema});var vulnerabilityOverviewSchema=z2.object({osvId:z2.string().nullable().optional(),summary:z2.string().nullable().optional(),severityScore:z2.number().nullable().optional(),publishedAt:z2.string().nullable().optional()});var packageSecurityOverviewSchema=z2.object({vulnerabilityCount:z2.number().int().nullable().optional(),hasCurrentVulnerabilities:z2.boolean().nullable().optional(),recentVulnerabilities:z2.array(vulnerabilityOverviewSchema).nullable().optional()}).nullable().optional();var changelogEntrySchema=z2.object({version:z2.string().nullable().optional(),publishedAt:z2.string().nullable().optional(),body:z2.string().nullable().optional()});var packageSummaryResponseSchema=z2.object({package:packageIdentitySchema.nullable().optional(),security:packageSecurityOverviewSchema,latestChangelogs:z2.array(changelogEntrySchema).nullable().optional()});var graphQLErrorSchema2=z2.object({message:z2.string(),extensions:z2.record(z2.string(),z2.unknown()).optional()});var graphQLResponseSchema=z2.object({data:z2.object({packageSummary:packageSummaryResponseSchema.nullable().optional()}).nullable().optional(),errors:z2.array(graphQLErrorSchema2).optional()});var PACKAGE_SUMMARY_QUERY=`
|
|
485
|
+
query PackageSummary($registry: Registry!, $name: String!) {
|
|
486
|
+
packageSummary(registry: $registry, name: $name) {
|
|
487
|
+
package {
|
|
488
|
+
name
|
|
489
|
+
registry
|
|
490
|
+
description
|
|
491
|
+
latestVersion
|
|
492
|
+
latestVersionPublishedAt
|
|
493
|
+
homepage
|
|
494
|
+
repositoryUrl
|
|
495
|
+
license
|
|
496
|
+
downloadsLastMonth
|
|
497
|
+
downloadsTotal
|
|
498
|
+
githubRepository {
|
|
499
|
+
stargazersCount
|
|
500
|
+
forksCount
|
|
501
|
+
openIssuesCount
|
|
502
|
+
archived
|
|
503
|
+
language
|
|
504
|
+
topics
|
|
505
|
+
pushedAt
|
|
506
|
+
}
|
|
507
|
+
}
|
|
508
|
+
security {
|
|
509
|
+
vulnerabilityCount
|
|
510
|
+
hasCurrentVulnerabilities
|
|
511
|
+
recentVulnerabilities {
|
|
512
|
+
osvId
|
|
513
|
+
summary
|
|
514
|
+
severityScore
|
|
515
|
+
publishedAt
|
|
516
|
+
}
|
|
517
|
+
}
|
|
518
|
+
latestChangelogs(limit: 3) {
|
|
519
|
+
version
|
|
520
|
+
publishedAt
|
|
521
|
+
body
|
|
522
|
+
}
|
|
523
|
+
}
|
|
524
|
+
}`;var packageVersionIdentitySchema=z2.object({name:z2.string().nullable().optional(),registry:z2.string().nullable().optional(),version:z2.string().nullable().optional(),publishedAt:z2.string().nullable().optional(),deprecated:z2.boolean().nullable().optional(),deprecationReason:z2.string().nullable().optional()});var vulnerabilityDetailSchema=z2.object({osvId:z2.string().nullable().optional(),summary:z2.string().nullable().optional(),severityScore:z2.number().nullable().optional(),severityType:z2.string().nullable().optional(),affectedVersionRanges:z2.array(z2.string()).nullable().optional(),affectedVersionRangesCount:z2.number().int(),affectedVersionRangesTruncated:z2.boolean(),fixedInVersions:z2.array(z2.string()).nullable().optional(),publishedAt:z2.string().nullable().optional(),modifiedAt:z2.string().nullable().optional(),withdrawnAt:z2.string().nullable().optional(),aliases:z2.array(z2.string()).nullable().optional(),isMalicious:z2.boolean().nullable().optional(),affectsInspectedVersion:z2.boolean(),matchedAffectedVersionRanges:z2.array(z2.string()),duplicateIds:z2.array(z2.string())});var pageInfoSchema=z2.object({hasNextPage:z2.boolean(),endCursor:z2.string().nullable().optional(),totalCount:z2.number().int()});var vulnerabilityAdvisoryPageSchema=z2.object({entries:z2.array(vulnerabilityDetailSchema),pageInfo:pageInfoSchema});var vulnerabilitySecurityDetailsSchema=z2.object({affectedVulnerabilityCount:z2.number().int(),nonAffectingVulnerabilityCount:z2.number().int(),allVulnerabilityCount:z2.number().int(),currentVersionAffected:z2.boolean().nullable().optional(),advisories:vulnerabilityAdvisoryPageSchema,upgradePaths:z2.array(z2.string()).nullable().optional()}).nullable().optional();var vulnerabilityReportResponseSchema=z2.object({package:packageVersionIdentitySchema.nullable().optional(),security:vulnerabilitySecurityDetailsSchema});var vulnerabilitiesGraphQLResponseSchema=z2.object({data:z2.object({packageVulnerabilities:vulnerabilityReportResponseSchema.nullable().optional()}).nullable().optional(),errors:z2.array(graphQLErrorSchema2).optional()});var PACKAGE_VULNERABILITIES_QUERY=`
|
|
525
|
+
query PackageVulnerabilities(
|
|
526
|
+
$registry: Registry!
|
|
527
|
+
$name: String!
|
|
528
|
+
$version: String
|
|
529
|
+
$minSeverity: Float
|
|
530
|
+
$includeWithdrawn: Boolean
|
|
531
|
+
$scope: VulnerabilityScope = AFFECTED
|
|
532
|
+
$after: String
|
|
533
|
+
) {
|
|
534
|
+
packageVulnerabilities(
|
|
535
|
+
registry: $registry
|
|
536
|
+
name: $name
|
|
537
|
+
version: $version
|
|
538
|
+
minSeverity: $minSeverity
|
|
539
|
+
includeWithdrawn: $includeWithdrawn
|
|
540
|
+
) {
|
|
541
|
+
package {
|
|
542
|
+
name
|
|
543
|
+
registry
|
|
544
|
+
version
|
|
545
|
+
}
|
|
546
|
+
security {
|
|
547
|
+
affectedVulnerabilityCount
|
|
548
|
+
nonAffectingVulnerabilityCount
|
|
549
|
+
allVulnerabilityCount
|
|
550
|
+
currentVersionAffected
|
|
551
|
+
upgradePaths
|
|
552
|
+
advisories(scope: $scope, first: 100, after: $after) {
|
|
553
|
+
entries {
|
|
554
|
+
osvId
|
|
555
|
+
summary
|
|
556
|
+
severityScore
|
|
557
|
+
severityType
|
|
558
|
+
affectedVersionRanges
|
|
559
|
+
affectedVersionRangesCount
|
|
560
|
+
affectedVersionRangesTruncated
|
|
561
|
+
fixedInVersions
|
|
562
|
+
publishedAt
|
|
563
|
+
modifiedAt
|
|
564
|
+
withdrawnAt
|
|
565
|
+
aliases
|
|
566
|
+
isMalicious
|
|
567
|
+
affectsInspectedVersion
|
|
568
|
+
matchedAffectedVersionRanges
|
|
569
|
+
duplicateIds
|
|
570
|
+
}
|
|
571
|
+
pageInfo {
|
|
572
|
+
hasNextPage
|
|
573
|
+
endCursor
|
|
574
|
+
totalCount
|
|
575
|
+
}
|
|
576
|
+
}
|
|
577
|
+
}
|
|
578
|
+
}
|
|
579
|
+
}`;var directDependencySchema=z2.object({name:z2.string().nullable().optional(),versionConstraint:z2.string().nullable().optional(),type:z2.string().nullable().optional()});var dependencyGraphNodeSchema=z2.object({registry:z2.string(),name:z2.string(),version:z2.string().nullable().optional()});var dependencyGraphEdgeSchema=z2.object({fromIndex:z2.number().int().nullable().optional(),toIndex:z2.number().int(),constraint:z2.string().nullable().optional(),dependencyType:z2.string().nullable().optional()});var dependencyGraphSchema=z2.object({formatVersion:z2.number().int(),nodes:z2.array(dependencyGraphNodeSchema),edges:z2.array(dependencyGraphEdgeSchema)});var vulnerabilityCountSummarySchema=z2.object({totalVulnerabilities:z2.number().int(),critical:z2.number().int(),high:z2.number().int(),medium:z2.number().int(),low:z2.number().int(),unknown:z2.number().int()});var vulnerabilitySummaryDetailSchema=z2.object({osvId:z2.string().nullable().optional(),registry:z2.string().nullable().optional(),packageName:z2.string().nullable().optional(),summary:z2.string().nullable().optional(),severityScore:z2.number().nullable().optional(),severityType:z2.string().nullable().optional(),affectedVersionRanges:z2.array(z2.string()).nullable().optional(),fixedInVersions:z2.array(z2.string()).nullable().optional(),publishedAt:z2.string().nullable().optional(),modifiedAt:z2.string().nullable().optional(),withdrawnAt:z2.string().nullable().optional(),aliases:z2.array(z2.string()).nullable().optional(),isMalicious:z2.boolean().nullable().optional()});var transitiveDependencyVulnerabilitySchema=z2.object({version:z2.string(),affectsResolvedVersion:z2.boolean(),matchedAffectedVersionRanges:z2.array(z2.string()),fixVersionsAboveResolved:z2.array(z2.string()),nearestFixedVersion:z2.string().nullable().optional(),advisory:vulnerabilitySummaryDetailSchema});var transitiveVulnerablePackageSchema=z2.object({registry:z2.string(),name:z2.string(),versions:z2.array(z2.string()),affectedCount:z2.number().int(),nonAffectingCount:z2.number().int(),totalCount:z2.number().int(),maxSeverityScore:z2.number().nullable().optional(),maxSeverityLabel:z2.string().nullable().optional(),advisoryIds:z2.array(z2.string()),mostCritical:vulnerabilitySummaryDetailSchema.nullable().optional(),advisoryOccurrences:z2.array(transitiveDependencyVulnerabilitySchema).nullable().optional()});var transitiveVulnerabilitySummarySchema=z2.object({affected:vulnerabilityCountSummarySchema,nonAffecting:vulnerabilityCountSummarySchema,combined:vulnerabilityCountSummarySchema,totalPackagesAnalyzed:z2.number().int(),affectedPackageCount:z2.number().int(),packages:z2.array(transitiveVulnerablePackageSchema),calculatedAt:z2.string().nullable().optional()}).nullable().optional();var dependencyDeprecationReasonSchema=z2.object({version:z2.string(),reason:z2.string().nullable().optional()});var deprecatedDependencySchema=z2.object({registry:z2.string(),name:z2.string(),versions:z2.array(z2.string()),reasons:z2.array(dependencyDeprecationReasonSchema)});var outdatedDependencyVersionSchema=z2.object({version:z2.string(),severity:z2.string()});var outdatedDependencySchema=z2.object({registry:z2.string(),name:z2.string(),latestVersion:z2.string().nullable().optional(),severity:z2.string(),versions:z2.array(outdatedDependencyVersionSchema),repositoryUrl:z2.string().nullable().optional()});var duplicateDependencySchema=z2.object({registry:z2.string().nullable().optional(),name:z2.string(),versions:z2.array(z2.string())});var dependencyConflictEdgeSchema=z2.object({fromIndex:z2.number().int().nullable().optional(),toIndex:z2.number().int(),versionConstraint:z2.string(),dependencyType:z2.string()});var dependencyConflictSchema=z2.object({packageName:z2.string(),requiredVersions:z2.array(z2.string()),conflictingEdges:z2.array(dependencyConflictEdgeSchema)});var dependencyIssueConflictSchema=z2.object({registry:z2.string().nullable().optional(),name:z2.string(),versions:z2.array(z2.string()),requiredVersions:z2.array(z2.string()),conflictingEdges:z2.array(dependencyConflictEdgeSchema)});var dependencyIssuesSummarySchema=z2.object({totalCount:z2.number().int(),deprecatedCount:z2.number().int(),outdatedCount:z2.number().int(),duplicateCount:z2.number().int(),conflictCount:z2.number().int(),deprecatedPackages:z2.array(deprecatedDependencySchema),outdatedPackages:z2.array(outdatedDependencySchema),duplicatePackages:z2.array(duplicateDependencySchema),conflicts:z2.array(dependencyIssueConflictSchema)}).nullable().optional();var circularDependencyCycleSchema=z2.object({cycleStart:z2.string(),circularPath:z2.array(z2.string()),displayChain:z2.string()});var environmentMarkerSchema=z2.object({type:z2.string().nullable().optional(),value:z2.string().nullable().optional(),raw:z2.string().nullable().optional()});var transitiveDependencySchema=z2.object({totalEdges:z2.number().int().nullable().optional(),uniquePackagesCount:z2.number().int().nullable().optional(),uniqueDependencies:z2.array(z2.string()).nullable().optional(),dependencyConflicts:z2.array(dependencyConflictSchema).nullable().optional(),circularDependencyCycles:z2.array(circularDependencyCycleSchema).nullable().optional(),dependencyGraph:dependencyGraphSchema.nullable().optional(),vulnerabilitySummary:transitiveVulnerabilitySummarySchema,dependencyIssues:dependencyIssuesSummarySchema}).nullable().optional();var dependencyBundleSchema=z2.object({direct:z2.array(directDependencySchema).nullable().optional(),transitive:transitiveDependencySchema}).nullable().optional();var groupDependencySchema=z2.object({name:z2.string(),constraint:z2.string().nullable().optional()});var dependencyGroupSchema=z2.object({name:z2.string(),lifecycle:z2.string(),conditionType:z2.string(),conditionValue:z2.string().nullable().optional(),selectionMode:z2.string(),exclusiveGroup:z2.string().nullable().optional(),fallbackPriority:z2.number().int().nullable().optional(),compatibleWith:z2.array(z2.string()).nullable().optional(),defaultEnabled:z2.boolean().nullable().optional(),dependencies:z2.array(groupDependencySchema)});var dependencyGroupsInfoSchema=z2.object({primaryGroup:z2.string().nullable().optional(),environmentMarkers:z2.array(environmentMarkerSchema).nullable().optional(),groups:z2.array(dependencyGroupSchema)}).nullable().optional();var dependencyReportResponseSchema=z2.object({package:packageVersionIdentitySchema.nullable().optional(),dependencies:dependencyBundleSchema,dependencyGroups:dependencyGroupsInfoSchema});var dependenciesGraphQLResponseSchema=z2.object({data:z2.object({packageDependencies:dependencyReportResponseSchema.nullable().optional()}).nullable().optional(),errors:z2.array(graphQLErrorSchema2).optional()});var PACKAGE_DEPENDENCIES_QUERY=`
|
|
580
|
+
query PackageDependencies(
|
|
581
|
+
$registry: Registry!
|
|
582
|
+
$name: String!
|
|
583
|
+
$version: String
|
|
584
|
+
$includeTransitive: Boolean
|
|
585
|
+
$maxDepth: Int
|
|
586
|
+
$lifecycle: [String!]
|
|
587
|
+
) {
|
|
588
|
+
packageDependencies(
|
|
589
|
+
registry: $registry
|
|
590
|
+
name: $name
|
|
591
|
+
version: $version
|
|
592
|
+
includeTransitive: $includeTransitive
|
|
593
|
+
maxDepth: $maxDepth
|
|
594
|
+
lifecycle: $lifecycle
|
|
595
|
+
) {
|
|
596
|
+
package {
|
|
597
|
+
name
|
|
598
|
+
registry
|
|
599
|
+
version
|
|
600
|
+
}
|
|
601
|
+
dependencies {
|
|
602
|
+
# Backend-side summary block intentionally not selected — our
|
|
603
|
+
# envelope computes runtime.count client-side from direct[].length
|
|
604
|
+
# so the invariant runtime.count === runtime.items.length always
|
|
605
|
+
# holds regardless of backend-side drift.
|
|
606
|
+
direct {
|
|
607
|
+
name
|
|
608
|
+
versionConstraint
|
|
609
|
+
type
|
|
610
|
+
}
|
|
611
|
+
transitive {
|
|
612
|
+
totalEdges
|
|
613
|
+
uniquePackagesCount
|
|
614
|
+
uniqueDependencies
|
|
615
|
+
dependencyConflicts {
|
|
616
|
+
packageName
|
|
617
|
+
requiredVersions
|
|
618
|
+
conflictingEdges {
|
|
619
|
+
fromIndex
|
|
620
|
+
toIndex
|
|
621
|
+
versionConstraint
|
|
622
|
+
dependencyType
|
|
623
|
+
}
|
|
624
|
+
}
|
|
625
|
+
circularDependencyCycles {
|
|
626
|
+
cycleStart
|
|
627
|
+
circularPath
|
|
628
|
+
displayChain
|
|
629
|
+
}
|
|
630
|
+
dependencyGraph {
|
|
631
|
+
formatVersion
|
|
632
|
+
nodes {
|
|
633
|
+
registry
|
|
634
|
+
name
|
|
635
|
+
version
|
|
636
|
+
}
|
|
637
|
+
edges {
|
|
638
|
+
fromIndex
|
|
639
|
+
toIndex
|
|
640
|
+
constraint
|
|
641
|
+
dependencyType
|
|
642
|
+
}
|
|
643
|
+
}
|
|
644
|
+
}
|
|
645
|
+
}
|
|
646
|
+
dependencyGroups {
|
|
647
|
+
primaryGroup
|
|
648
|
+
environmentMarkers {
|
|
649
|
+
type
|
|
650
|
+
value
|
|
651
|
+
raw
|
|
652
|
+
}
|
|
653
|
+
groups {
|
|
654
|
+
name
|
|
655
|
+
lifecycle
|
|
656
|
+
conditionType
|
|
657
|
+
conditionValue
|
|
658
|
+
selectionMode
|
|
659
|
+
exclusiveGroup
|
|
660
|
+
fallbackPriority
|
|
661
|
+
compatibleWith
|
|
662
|
+
defaultEnabled
|
|
663
|
+
dependencies {
|
|
664
|
+
name
|
|
665
|
+
constraint
|
|
666
|
+
}
|
|
667
|
+
}
|
|
668
|
+
}
|
|
669
|
+
}
|
|
670
|
+
}`;var PACKAGE_UPGRADE_DEPENDENCY_PROBE_QUERY=`
|
|
671
|
+
query PackageUpgradeDependencyProbe(
|
|
672
|
+
$registry: Registry!
|
|
673
|
+
$name: String!
|
|
674
|
+
$version: String!
|
|
675
|
+
$includeTransitiveRisk: Boolean!
|
|
676
|
+
$includeTransitiveSecurity: Boolean!
|
|
677
|
+
$includeDependencyIssues: Boolean!
|
|
678
|
+
$includeDependencyChanges: Boolean!
|
|
679
|
+
$includeGroups: Boolean!
|
|
680
|
+
$lifecycle: [String!]
|
|
681
|
+
$minSeverity: Float
|
|
682
|
+
) {
|
|
683
|
+
packageDependencies(
|
|
684
|
+
registry: $registry
|
|
685
|
+
name: $name
|
|
686
|
+
version: $version
|
|
687
|
+
includeTransitive: $includeTransitiveRisk
|
|
688
|
+
lifecycle: $lifecycle
|
|
689
|
+
) {
|
|
690
|
+
package {
|
|
691
|
+
name
|
|
692
|
+
registry
|
|
693
|
+
version
|
|
694
|
+
publishedAt
|
|
695
|
+
deprecated
|
|
696
|
+
deprecationReason
|
|
697
|
+
}
|
|
698
|
+
dependencies {
|
|
699
|
+
direct {
|
|
700
|
+
name
|
|
701
|
+
versionConstraint
|
|
702
|
+
type
|
|
703
|
+
}
|
|
704
|
+
transitive @include(if: $includeTransitiveRisk) {
|
|
705
|
+
dependencyGraph @include(if: $includeDependencyChanges) {
|
|
706
|
+
formatVersion
|
|
707
|
+
nodes {
|
|
708
|
+
registry
|
|
709
|
+
name
|
|
710
|
+
version
|
|
711
|
+
}
|
|
712
|
+
edges {
|
|
713
|
+
fromIndex
|
|
714
|
+
toIndex
|
|
715
|
+
constraint
|
|
716
|
+
dependencyType
|
|
717
|
+
}
|
|
718
|
+
}
|
|
719
|
+
vulnerabilitySummary(minSeverity: $minSeverity) @include(if: $includeTransitiveSecurity) {
|
|
720
|
+
affected {
|
|
721
|
+
totalVulnerabilities
|
|
722
|
+
critical
|
|
723
|
+
high
|
|
724
|
+
medium
|
|
725
|
+
low
|
|
726
|
+
unknown
|
|
727
|
+
}
|
|
728
|
+
nonAffecting {
|
|
729
|
+
totalVulnerabilities
|
|
730
|
+
critical
|
|
731
|
+
high
|
|
732
|
+
medium
|
|
733
|
+
low
|
|
734
|
+
unknown
|
|
735
|
+
}
|
|
736
|
+
combined {
|
|
737
|
+
totalVulnerabilities
|
|
738
|
+
critical
|
|
739
|
+
high
|
|
740
|
+
medium
|
|
741
|
+
low
|
|
742
|
+
unknown
|
|
743
|
+
}
|
|
744
|
+
totalPackagesAnalyzed
|
|
745
|
+
affectedPackageCount
|
|
746
|
+
calculatedAt
|
|
747
|
+
packages {
|
|
748
|
+
registry
|
|
749
|
+
name
|
|
750
|
+
versions
|
|
751
|
+
affectedCount
|
|
752
|
+
nonAffectingCount
|
|
753
|
+
totalCount
|
|
754
|
+
maxSeverityScore
|
|
755
|
+
maxSeverityLabel
|
|
756
|
+
advisoryIds(scope: AFFECTED)
|
|
757
|
+
mostCritical {
|
|
758
|
+
osvId
|
|
759
|
+
registry
|
|
760
|
+
packageName
|
|
761
|
+
summary
|
|
762
|
+
severityScore
|
|
763
|
+
severityType
|
|
764
|
+
affectedVersionRanges
|
|
765
|
+
fixedInVersions
|
|
766
|
+
publishedAt
|
|
767
|
+
modifiedAt
|
|
768
|
+
withdrawnAt
|
|
769
|
+
aliases
|
|
770
|
+
isMalicious
|
|
771
|
+
}
|
|
772
|
+
advisoryOccurrences(scope: AFFECTED, minSeverity: $minSeverity, limit: 5) {
|
|
773
|
+
version
|
|
774
|
+
affectsResolvedVersion
|
|
775
|
+
matchedAffectedVersionRanges
|
|
776
|
+
fixVersionsAboveResolved
|
|
777
|
+
nearestFixedVersion
|
|
778
|
+
advisory {
|
|
779
|
+
osvId
|
|
780
|
+
registry
|
|
781
|
+
packageName
|
|
782
|
+
summary
|
|
783
|
+
severityScore
|
|
784
|
+
severityType
|
|
785
|
+
affectedVersionRanges
|
|
786
|
+
fixedInVersions
|
|
787
|
+
publishedAt
|
|
788
|
+
modifiedAt
|
|
789
|
+
withdrawnAt
|
|
790
|
+
aliases
|
|
791
|
+
isMalicious
|
|
792
|
+
}
|
|
793
|
+
}
|
|
794
|
+
}
|
|
795
|
+
}
|
|
796
|
+
dependencyIssues @include(if: $includeDependencyIssues) {
|
|
797
|
+
totalCount
|
|
798
|
+
deprecatedCount
|
|
799
|
+
outdatedCount
|
|
800
|
+
duplicateCount
|
|
801
|
+
conflictCount
|
|
802
|
+
deprecatedPackages {
|
|
803
|
+
registry
|
|
804
|
+
name
|
|
805
|
+
versions
|
|
806
|
+
reasons {
|
|
807
|
+
version
|
|
808
|
+
reason
|
|
809
|
+
}
|
|
810
|
+
}
|
|
811
|
+
outdatedPackages {
|
|
812
|
+
registry
|
|
813
|
+
name
|
|
814
|
+
latestVersion
|
|
815
|
+
severity
|
|
816
|
+
versions {
|
|
817
|
+
version
|
|
818
|
+
severity
|
|
819
|
+
}
|
|
820
|
+
repositoryUrl
|
|
821
|
+
}
|
|
822
|
+
duplicatePackages {
|
|
823
|
+
registry
|
|
824
|
+
name
|
|
825
|
+
versions
|
|
826
|
+
}
|
|
827
|
+
conflicts {
|
|
828
|
+
registry
|
|
829
|
+
name
|
|
830
|
+
versions
|
|
831
|
+
requiredVersions
|
|
832
|
+
conflictingEdges {
|
|
833
|
+
fromIndex
|
|
834
|
+
toIndex
|
|
835
|
+
versionConstraint
|
|
836
|
+
dependencyType
|
|
837
|
+
}
|
|
838
|
+
}
|
|
839
|
+
}
|
|
840
|
+
}
|
|
841
|
+
}
|
|
842
|
+
dependencyGroups @include(if: $includeGroups) {
|
|
843
|
+
primaryGroup
|
|
844
|
+
environmentMarkers {
|
|
845
|
+
type
|
|
846
|
+
value
|
|
847
|
+
raw
|
|
848
|
+
}
|
|
849
|
+
groups {
|
|
850
|
+
name
|
|
851
|
+
lifecycle
|
|
852
|
+
conditionType
|
|
853
|
+
conditionValue
|
|
854
|
+
selectionMode
|
|
855
|
+
exclusiveGroup
|
|
856
|
+
fallbackPriority
|
|
857
|
+
compatibleWith
|
|
858
|
+
defaultEnabled
|
|
859
|
+
dependencies {
|
|
860
|
+
name
|
|
861
|
+
constraint
|
|
862
|
+
}
|
|
863
|
+
}
|
|
864
|
+
}
|
|
865
|
+
}
|
|
866
|
+
}`;var changelogPackageInfoSchema=z2.object({name:z2.string().nullable().optional(),registry:z2.string().nullable().optional(),repoUrl:z2.string().nullable().optional(),fromVersion:z2.string().nullable().optional(),toVersion:z2.string().nullable().optional(),limit:z2.number().int().nullable().optional()}).nullable().optional();var changelogEntryDetailSchema=z2.object({version:z2.string().nullable().optional(),normalizedVersion:z2.string().nullable().optional(),body:z2.string().nullable().optional(),htmlUrl:z2.string().nullable().optional(),publishedAt:z2.string().nullable().optional(),metadata:z2.unknown().nullable().optional()});var changelogReportResponseSchema=z2.object({package:changelogPackageInfoSchema,source:z2.string().nullable().optional(),entries:z2.array(changelogEntryDetailSchema).nullable().optional()});var changelogGraphQLResponseSchema=z2.object({data:z2.object({packageChangelog:changelogReportResponseSchema.nullable().optional()}).nullable().optional(),errors:z2.array(graphQLErrorSchema2).optional()});var PACKAGE_CHANGELOG_QUERY=`
|
|
867
|
+
query PackageChangelog(
|
|
868
|
+
$registry: Registry
|
|
869
|
+
$name: String
|
|
870
|
+
$repoUrl: String
|
|
871
|
+
$gitRef: String
|
|
872
|
+
$fromVersion: String
|
|
873
|
+
$toVersion: String
|
|
874
|
+
$limit: Int
|
|
875
|
+
) {
|
|
876
|
+
packageChangelog(
|
|
877
|
+
registry: $registry
|
|
878
|
+
name: $name
|
|
879
|
+
repoUrl: $repoUrl
|
|
880
|
+
gitRef: $gitRef
|
|
881
|
+
fromVersion: $fromVersion
|
|
882
|
+
toVersion: $toVersion
|
|
883
|
+
limit: $limit
|
|
884
|
+
) {
|
|
885
|
+
package {
|
|
886
|
+
name
|
|
887
|
+
registry
|
|
888
|
+
repoUrl
|
|
889
|
+
fromVersion
|
|
890
|
+
toVersion
|
|
891
|
+
limit
|
|
892
|
+
}
|
|
893
|
+
source
|
|
894
|
+
entries {
|
|
895
|
+
version
|
|
896
|
+
normalizedVersion
|
|
897
|
+
body
|
|
898
|
+
htmlUrl
|
|
899
|
+
publishedAt
|
|
900
|
+
metadata
|
|
901
|
+
}
|
|
902
|
+
}
|
|
903
|
+
}`;var packageDocSourceKindSchema=z2.enum(["CRAWLED","REPOSITORY"]);var packageDocPageSummarySchema=z2.object({id:z2.string().nullable().optional(),title:z2.string().nullable().optional(),slug:z2.string().nullable().optional(),order:z2.number().int().nullable().optional(),linkName:z2.string().nullable().optional(),lastUpdatedAt:z2.string().nullable().optional(),sourceKind:packageDocSourceKindSchema.nullable().optional(),sourceUrl:z2.string().nullable().optional(),repoUrl:z2.string().nullable().optional(),gitRef:z2.string().nullable().optional(),requestedRef:z2.string().nullable().optional(),filePath:z2.string().nullable().optional()});var packageDocsPageInfoSchema=z2.object({hasNextPage:z2.boolean(),endCursor:z2.string().nullable().optional(),totalCount:z2.number().int().nullable().optional()}).nullable().optional();var packageDocsListResponseSchema=z2.object({registry:z2.string().nullable().optional(),packageName:z2.string().nullable().optional(),version:z2.string().nullable().optional(),stale:z2.boolean().nullable().optional(),pages:z2.array(packageDocPageSummarySchema).nullable().optional(),pageInfo:packageDocsPageInfoSchema});var packageDocSourceSchema=z2.object({url:z2.string().nullable().optional(),label:z2.string().nullable().optional()}).nullable().optional();var packageDocPageSchema=z2.object({id:z2.string().nullable().optional(),title:z2.string().nullable().optional(),content:z2.string().nullable().optional(),contentFormat:z2.string().nullable().optional(),breadcrumbs:z2.array(z2.string()).nullable().optional(),linkName:z2.string().nullable().optional(),lastUpdatedAt:z2.string().nullable().optional(),sourceKind:packageDocSourceKindSchema.nullable().optional(),source:packageDocSourceSchema,repoUrl:z2.string().nullable().optional(),gitRef:z2.string().nullable().optional(),requestedRef:z2.string().nullable().optional(),filePath:z2.string().nullable().optional(),baseUrl:z2.string().nullable().optional()}).nullable().optional();var packageDocResultResponseSchema=z2.object({registry:z2.string().nullable().optional(),packageName:z2.string().nullable().optional(),version:z2.string().nullable().optional(),sourceKind:packageDocSourceKindSchema.nullable().optional(),page:packageDocPageSchema});var packageDocsListGraphQLResponseSchema=z2.object({data:z2.object({listPackageDocs:packageDocsListResponseSchema.nullable().optional()}).nullable().optional(),errors:z2.array(graphQLErrorSchema2).optional()});var packageDocReadGraphQLResponseSchema=z2.object({data:z2.object({getDocPage:packageDocResultResponseSchema.nullable().optional()}).nullable().optional(),errors:z2.array(graphQLErrorSchema2).optional()});var LIST_PACKAGE_DOCS_QUERY=`
|
|
904
|
+
query ListPackageDocs(
|
|
905
|
+
$registry: Registry!
|
|
906
|
+
$packageName: String!
|
|
907
|
+
$version: String
|
|
908
|
+
$limit: Int
|
|
909
|
+
$after: String
|
|
910
|
+
) {
|
|
911
|
+
listPackageDocs(
|
|
912
|
+
registry: $registry
|
|
913
|
+
packageName: $packageName
|
|
914
|
+
version: $version
|
|
915
|
+
limit: $limit
|
|
916
|
+
after: $after
|
|
917
|
+
) {
|
|
918
|
+
registry
|
|
919
|
+
packageName
|
|
920
|
+
version
|
|
921
|
+
stale
|
|
922
|
+
pages {
|
|
923
|
+
id
|
|
924
|
+
title
|
|
925
|
+
slug
|
|
926
|
+
order
|
|
927
|
+
linkName
|
|
928
|
+
lastUpdatedAt
|
|
929
|
+
sourceKind
|
|
930
|
+
sourceUrl
|
|
931
|
+
repoUrl
|
|
932
|
+
gitRef
|
|
933
|
+
requestedRef
|
|
934
|
+
filePath
|
|
935
|
+
}
|
|
936
|
+
pageInfo {
|
|
937
|
+
hasNextPage
|
|
938
|
+
endCursor
|
|
939
|
+
totalCount
|
|
940
|
+
}
|
|
941
|
+
}
|
|
942
|
+
}`;var READ_PACKAGE_DOC_QUERY=`
|
|
943
|
+
query ReadPackageDoc($pageId: String!) {
|
|
944
|
+
getDocPage(pageId: $pageId) {
|
|
945
|
+
registry
|
|
946
|
+
packageName
|
|
947
|
+
version
|
|
948
|
+
sourceKind
|
|
949
|
+
page {
|
|
950
|
+
id
|
|
951
|
+
title
|
|
952
|
+
content
|
|
953
|
+
contentFormat
|
|
954
|
+
breadcrumbs
|
|
955
|
+
linkName
|
|
956
|
+
lastUpdatedAt
|
|
957
|
+
sourceKind
|
|
958
|
+
source {
|
|
959
|
+
url
|
|
960
|
+
label
|
|
961
|
+
}
|
|
962
|
+
repoUrl
|
|
963
|
+
gitRef
|
|
964
|
+
requestedRef
|
|
965
|
+
filePath
|
|
966
|
+
baseUrl
|
|
967
|
+
}
|
|
968
|
+
}
|
|
969
|
+
}`;class PackageIntelligenceServiceImpl{endpointUrl;tokenProvider;fetchFn;runtime;constructor(endpointUrl,tokenProvider,fetchFn=globalThis.fetch,runtime={}){this.endpointUrl=endpointUrl;this.tokenProvider=tokenProvider;this.fetchFn=fetchFn;this.runtime=runtime}async packageSummary(params){return withTelemetrySpan("pkg-intel.summary.request",()=>executeWithTokenRefresh({getToken:()=>this.tokenProvider.getToken(),forceRefresh:()=>this.tokenProvider.forceRefresh(),shouldRefresh:(error)=>error instanceof AuthenticationError,executeWithToken:(token)=>this.executePackageSummary(token,params)}))}async executePackageSummary(token,params){let response;try{response=await postPkgseerGraphql({endpointUrl:this.endpointUrl,token,query:PACKAGE_SUMMARY_QUERY,variables:{registry:params.registry,name:params.packageName},fetchFn:this.fetchFn,clientHeaders:this.runtime.clientHeaders,userAgent:this.runtime.userAgent})}catch(cause){if(cause instanceof PkgseerTransportError){throw this.createTransportError(cause)}throw cause}if(response.status<200||response.status>=300){throw this.createHttpError(response)}const parsed=graphQLResponseSchema.safeParse(response.parsedBody);if(!parsed.success){throw new MalformedPackageIntelligenceResponseError("Malformed response from the package-intelligence service.")}if(parsed.data.errors&&parsed.data.errors.length>0){throw this.createGraphQLError(parsed.data.errors)}const data=parsed.data.data?.packageSummary;if(!data){throw new MalformedPackageIntelligenceResponseError("Empty response from the package-intelligence service.")}return this.normalise(data)}createHttpError(response){const status=response.status;const detail=parseDetail3(response.responseBody);if(status===401){return new AuthenticationError(SERVER_AUTHENTICATION_REJECTED_MESSAGE,"server")}if(status===403){return new PackageIntelligenceAccessError(detail??"Access denied.")}if(status>=500){return new PackageIntelligenceBackendError(detail?`Server error (${status}): ${detail}`:`Server error (${status})`,status)}return new PackageIntelligenceBackendError(detail??`Request failed with status ${status}`,status)}createTransportError(error){if(isFetchTimeoutError(error.cause)){return new PackageIntelligenceBackendError("Package intelligence request timed out.",undefined,"TIMEOUT",true)}return new PackageIntelligenceNetworkError("Could not reach the package intelligence service. Check your connection or set GITHITS_CODE_NAV_URL.",{cause:error})}createGraphQLError(errors){const message=errors.map((error)=>error.message).join(", ");const extensions=getPrimaryExtensions2(errors);const code=typeof extensions?.code==="string"?extensions.code:undefined;const retryable=typeof extensions?.retryable==="boolean"?extensions.retryable:undefined;if(isClientUpdateRequiredGraphQLError({message,code})){return new ClientUpdateRequiredError(undefined,undefined,this.runtime.clientVersion)}if(isGraphQLSchemaMismatchError({message,code})){const sanitized="Backend protocol mismatch. Your CLI may be newer than the server, or the server may require a newer CLI. Run `githits update-check` to verify your installed version. Set GITHITS_DEBUG=pkg-graphql to inspect GraphQL details during local development.";debugLog("pkg-graphql",{event:"graphql-schema-mismatch",code:code??"omitted",message});return new PackageIntelligenceBackendError(isDebugAreaEnabled("pkg-graphql")?message:sanitized,undefined,code,retryable)}switch(code){case"NOT_FOUND":case"PACKAGE_NOT_FOUND":return new PackageIntelligenceTargetNotFoundError(message);case"VERSION_NOT_FOUND":return new PackageIntelligenceVersionNotFoundError(message,typeof extensions?.package==="string"?extensions.package:undefined,typeof extensions?.requested_version==="string"?extensions.requested_version:undefined,parseVersionList(extensions?.available_versions??extensions?.availableVersions));case"UNSUPPORTED_REGISTRY":case"VALIDATION_ERROR":return new PackageIntelligenceValidationError(message);case"FEATURE_FLAG_REQUIRED":return new PackageIntelligenceFeatureFlagRequiredError(message);case"UNAUTHORIZED":return new AuthenticationError(SERVER_AUTHENTICATION_REJECTED_MESSAGE,"server");case"FORBIDDEN":return new PackageIntelligenceAccessError("Access denied. This feature may not be enabled for your account.");case"UPSTREAM_ERROR":case"TIMEOUT":case"RATE_LIMITED":case"INTERNAL_ERROR":case"UNKNOWN_ERROR":return new PackageIntelligenceBackendError(message,undefined,code,retryable);default:break}return new PackageIntelligenceBackendError(message,undefined,code,retryable)}normalise(data){const name=data.package?.name??undefined;const latestVersion=data.package?.latestVersion??undefined;if(!name||!latestVersion){throw new MalformedPackageIntelligenceResponseError("Package summary response missing required name/latestVersion.")}const pkg=data.package;const github=pkg?.githubRepository;const identity={name,latestVersion,registry:pkg?.registry??undefined,description:pkg?.description??undefined,latestVersionPublishedAt:pkg?.latestVersionPublishedAt??undefined,homepage:pkg?.homepage??undefined,repositoryUrl:pkg?.repositoryUrl??undefined,license:pkg?.license??undefined,downloadsLastMonth:pkg?.downloadsLastMonth??undefined,downloadsTotal:pkg?.downloadsTotal??undefined,githubRepository:github?{stargazersCount:github.stargazersCount??undefined,forksCount:github.forksCount??undefined,openIssuesCount:github.openIssuesCount??undefined,archived:github.archived??undefined,language:github.language??undefined,topics:github.topics??undefined,pushedAt:github.pushedAt??undefined}:undefined};const security=data.security?{vulnerabilityCount:data.security.vulnerabilityCount??undefined,hasCurrentVulnerabilities:data.security.hasCurrentVulnerabilities??undefined,recentVulnerabilities:data.security.recentVulnerabilities?.map((vuln)=>({osvId:vuln.osvId??undefined,summary:vuln.summary??undefined,severityScore:vuln.severityScore??undefined,publishedAt:vuln.publishedAt??undefined}))??undefined}:undefined;const latestChangelogs=data.latestChangelogs?.map((entry)=>({version:entry.version??undefined,publishedAt:entry.publishedAt??undefined,body:entry.body??undefined}))??undefined;return{package:identity,security,latestChangelogs}}async packageVulnerabilities(params){return withTelemetrySpan("pkg-intel.vulnerabilities.request",()=>executeWithTokenRefresh({getToken:()=>this.tokenProvider.getToken(),forceRefresh:()=>this.tokenProvider.forceRefresh(),shouldRefresh:(error)=>error instanceof AuthenticationError,executeWithToken:(token)=>this.executePackageVulnerabilities(token,params)}))}async executePackageVulnerabilities(token,params){let after=null;let firstPage;const entries=[];const seenCursors=new Set;do{const page=await this.fetchPackageVulnerabilitiesPage(token,params,after);if(!firstPage)firstPage=page;const advisoryPage=page.security?.advisories;if(!advisoryPage){after=null;break}entries.push(...advisoryPage.entries);if(advisoryPage.pageInfo.hasNextPage){const nextCursor=advisoryPage.pageInfo.endCursor;if(!nextCursor){throw new MalformedPackageIntelligenceResponseError("Vulnerability response pagination omitted next cursor.")}if(seenCursors.has(nextCursor)){throw new MalformedPackageIntelligenceResponseError("Vulnerability response pagination repeated a cursor.")}seenCursors.add(nextCursor);after=nextCursor}else{after=null}}while(after!==null);if(!firstPage){throw new MalformedPackageIntelligenceResponseError("Empty response from the package-intelligence service.")}if(firstPage.security){const expectedCount=firstPage.security.advisories.pageInfo.totalCount;if(entries.length!==expectedCount){throw new MalformedPackageIntelligenceResponseError("Vulnerability response pagination returned an incomplete advisory set.")}}const data=firstPage.security?{...firstPage,security:{...firstPage.security,advisories:{...firstPage.security.advisories,entries}}}:firstPage;return this.normaliseVulnerabilityReport(data)}async fetchPackageVulnerabilitiesPage(token,params,after){let response;try{response=await postPkgseerGraphql({endpointUrl:this.endpointUrl,token,query:PACKAGE_VULNERABILITIES_QUERY,variables:{registry:params.registry,name:params.packageName,version:params.version,minSeverity:params.minSeverity,includeWithdrawn:params.includeWithdrawn,scope:params.advisoryScope,after},fetchFn:this.fetchFn,clientHeaders:this.runtime.clientHeaders,userAgent:this.runtime.userAgent})}catch(cause){if(cause instanceof PkgseerTransportError){throw this.createTransportError(cause)}throw cause}if(response.status<200||response.status>=300){throw this.createHttpError(response)}const parsed=vulnerabilitiesGraphQLResponseSchema.safeParse(response.parsedBody);if(!parsed.success){throw new MalformedPackageIntelligenceResponseError("Malformed response from the package-intelligence service.")}if(parsed.data.errors&&parsed.data.errors.length>0){throw promoteGenericVersionNotFound(this.createGraphQLError(parsed.data.errors),params)}const data=parsed.data.data?.packageVulnerabilities;if(!data){throw new MalformedPackageIntelligenceResponseError("Empty response from the package-intelligence service.")}return data}normaliseVulnerabilityReport(data){const name=data.package?.name??undefined;const version2=data.package?.version??undefined;if(!name||!version2){throw new MalformedPackageIntelligenceResponseError("Vulnerability report response missing required name/version.")}const identity={name,version:version2,registry:data.package?.registry??undefined,publishedAt:data.package?.publishedAt??undefined,deprecated:data.package?.deprecated??undefined,deprecationReason:data.package?.deprecationReason??undefined};const security=data.security?{affectedVulnerabilityCount:data.security.affectedVulnerabilityCount,nonAffectingVulnerabilityCount:data.security.nonAffectingVulnerabilityCount,allVulnerabilityCount:data.security.allVulnerabilityCount,currentVersionAffected:data.security.currentVersionAffected??undefined,vulnerabilities:data.security.advisories.entries.map((vuln)=>({osvId:vuln.osvId??undefined,summary:vuln.summary??undefined,severityScore:vuln.severityScore??undefined,severityType:vuln.severityType??undefined,affectedVersionRanges:vuln.affectedVersionRanges??undefined,affectedVersionRangesCount:vuln.affectedVersionRangesCount,affectedVersionRangesTruncated:vuln.affectedVersionRangesTruncated,fixedInVersions:vuln.fixedInVersions??undefined,publishedAt:vuln.publishedAt??undefined,modifiedAt:vuln.modifiedAt??undefined,withdrawnAt:vuln.withdrawnAt??undefined,aliases:vuln.aliases??undefined,isMalicious:vuln.isMalicious??undefined,affectsInspectedVersion:vuln.affectsInspectedVersion,matchedAffectedVersionRanges:vuln.matchedAffectedVersionRanges,duplicateIds:vuln.duplicateIds})),upgradePaths:data.security.upgradePaths??undefined}:undefined;return{package:identity,security}}async packageDependencies(params){return withTelemetrySpan("pkg-intel.dependencies.request",()=>executeWithTokenRefresh({getToken:()=>this.tokenProvider.getToken(),forceRefresh:()=>this.tokenProvider.forceRefresh(),shouldRefresh:(error)=>error instanceof AuthenticationError,executeWithToken:(token)=>this.executePackageDependencies(token,params)}))}async packageUpgradeDependencyProbe(params){return withTelemetrySpan("pkg-intel.upgrade-dependency-probe.request",()=>executeWithTokenRefresh({getToken:()=>this.tokenProvider.getToken(),forceRefresh:()=>this.tokenProvider.forceRefresh(),shouldRefresh:(error)=>error instanceof AuthenticationError,executeWithToken:(token)=>this.executePackageUpgradeDependencyProbe(token,params)}))}async executePackageUpgradeDependencyProbe(token,params){const includeTransitiveRisk=params.includeTransitiveSecurity===true||params.includeDependencyIssues===true||params.includeDependencyChanges===true;let response;try{response=await postPkgseerGraphql({endpointUrl:this.endpointUrl,token,query:PACKAGE_UPGRADE_DEPENDENCY_PROBE_QUERY,variables:{registry:params.registry,name:params.packageName,version:params.version,includeTransitiveRisk,includeTransitiveSecurity:params.includeTransitiveSecurity===true,includeDependencyIssues:params.includeDependencyIssues===true,includeDependencyChanges:params.includeDependencyChanges===true,includeGroups:params.includeGroups===true,lifecycle:params.includeGroups===true?["peer"]:undefined,minSeverity:params.minSeverity},fetchFn:this.fetchFn,clientHeaders:this.runtime.clientHeaders,userAgent:this.runtime.userAgent})}catch(cause){if(cause instanceof PkgseerTransportError){throw this.createTransportError(cause)}throw cause}if(response.status<200||response.status>=300){throw this.createHttpError(response)}const parsed=dependenciesGraphQLResponseSchema.safeParse(response.parsedBody);if(!parsed.success){throw new MalformedPackageIntelligenceResponseError("Malformed response from the package-intelligence service.")}if(parsed.data.errors&&parsed.data.errors.length>0){throw promoteGenericVersionNotFound(this.createGraphQLError(parsed.data.errors),params)}const data=parsed.data.data?.packageDependencies;if(!data){throw new MalformedPackageIntelligenceResponseError("Empty response from the package-intelligence service.")}return this.normaliseDependencyReport(data)}async executePackageDependencies(token,params){let response;try{response=await postPkgseerGraphql({endpointUrl:this.endpointUrl,token,query:PACKAGE_DEPENDENCIES_QUERY,variables:{registry:params.registry,name:params.packageName,version:params.version,includeTransitive:params.includeTransitive,maxDepth:params.maxDepth,lifecycle:params.lifecycle&¶ms.lifecycle.length>0?params.lifecycle:undefined},fetchFn:this.fetchFn,clientHeaders:this.runtime.clientHeaders,userAgent:this.runtime.userAgent})}catch(cause){if(cause instanceof PkgseerTransportError){throw this.createTransportError(cause)}throw cause}if(response.status<200||response.status>=300){throw this.createHttpError(response)}const parsed=dependenciesGraphQLResponseSchema.safeParse(response.parsedBody);if(!parsed.success){throw new MalformedPackageIntelligenceResponseError("Malformed response from the package-intelligence service.")}if(parsed.data.errors&&parsed.data.errors.length>0){throw promoteGenericVersionNotFound(this.createGraphQLError(parsed.data.errors),params)}const data=parsed.data.data?.packageDependencies;if(!data){throw new MalformedPackageIntelligenceResponseError("Empty response from the package-intelligence service.")}return this.normaliseDependencyReport(data)}normaliseDependencyReport(data){const name=data.package?.name??undefined;const version2=data.package?.version??undefined;if(!name||!version2){throw new MalformedPackageIntelligenceResponseError("Package dependencies response missing required name/version.")}const identity={name,version:version2,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((version2)=>({version:version2.version,severity:version2.severity})),repositoryUrl:pkg.repositoryUrl??undefined})),duplicatePackages:issues.duplicatePackages.map((pkg)=>({registry:pkg.registry??undefined,name:pkg.name,versions:pkg.versions})),conflicts:issues.conflicts.map((conflict)=>({registry:conflict.registry??undefined,name:conflict.name,versions:conflict.versions,requiredVersions:conflict.requiredVersions,conflictingEdges:conflict.conflictingEdges.map((edge)=>({fromIndex:edge.fromIndex??undefined,toIndex:edge.toIndex,versionConstraint:edge.versionConstraint,dependencyType:edge.dependencyType}))}))}}async packageChangelog(params){return withTelemetrySpan("pkg-intel.changelog.request",()=>executeWithTokenRefresh({getToken:()=>this.tokenProvider.getToken(),forceRefresh:()=>this.tokenProvider.forceRefresh(),shouldRefresh:(error)=>error instanceof AuthenticationError,executeWithToken:(token)=>this.executePackageChangelog(token,params)}))}async executePackageChangelog(token,params){let response;try{response=await postPkgseerGraphql({endpointUrl:this.endpointUrl,token,query:PACKAGE_CHANGELOG_QUERY,variables:{registry:params.registry,name:params.packageName,repoUrl:params.repoUrl,gitRef:params.gitRef,fromVersion:params.fromVersion,toVersion:params.toVersion,limit:params.limit},fetchFn:this.fetchFn,clientHeaders:this.runtime.clientHeaders,userAgent:this.runtime.userAgent})}catch(cause){if(cause instanceof PkgseerTransportError){throw this.createTransportError(cause)}throw cause}if(response.status<200||response.status>=300){throw this.createHttpError(response)}const parsed=changelogGraphQLResponseSchema.safeParse(response.parsedBody);if(!parsed.success){throw new MalformedPackageIntelligenceResponseError("Malformed response from the package-intelligence service.")}if(parsed.data.errors&&parsed.data.errors.length>0){throw promoteGenericVersionNotFound(this.createGraphQLError(parsed.data.errors),params)}const data=parsed.data.data?.packageChangelog;if(!data){throw new MalformedPackageIntelligenceResponseError("Empty response from the package-intelligence service.")}return this.normaliseChangelogReport(data,params)}normaliseChangelogReport(data,params){const source=data.source?.trim()?data.source:undefined;const rawEntries=data.entries??[];if(!source&&rawEntries.length===0){const target=params.repoUrl??(params.registry&¶ms.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,metadata:entry.metadata??undefined}));const packageInfo=data.package?{name:data.package.name??undefined,registry:data.package.registry??undefined,repoUrl:data.package.repoUrl??undefined,fromVersion:data.package.fromVersion??undefined,toVersion:data.package.toVersion??undefined,limit:data.package.limit??undefined}:undefined;return{package:packageInfo,source,entries}}async listPackageDocs(params){return withTelemetrySpan("pkg-intel.docs.list",()=>executeWithTokenRefresh({getToken:()=>this.tokenProvider.getToken(),forceRefresh:()=>this.tokenProvider.forceRefresh(),shouldRefresh:(error)=>error instanceof AuthenticationError,executeWithToken:(token)=>this.executeListPackageDocs(token,params)}))}async executeListPackageDocs(token,params){let response;try{response=await postPkgseerGraphql({endpointUrl:this.endpointUrl,token,query:LIST_PACKAGE_DOCS_QUERY,variables:{registry:params.registry,packageName:params.packageName,version:params.version,limit:params.limit,after:params.after},fetchFn:this.fetchFn,clientHeaders:this.runtime.clientHeaders,userAgent:this.runtime.userAgent})}catch(cause){if(cause instanceof PkgseerTransportError){throw this.createTransportError(cause)}throw cause}if(response.status<200||response.status>=300){throw this.createHttpError(response)}const parsed=packageDocsListGraphQLResponseSchema.safeParse(response.parsedBody);if(!parsed.success){throw new MalformedPackageIntelligenceResponseError("Malformed response from the package-intelligence service.")}if(parsed.data.errors&&parsed.data.errors.length>0){throw promoteGenericVersionNotFound(this.createGraphQLError(parsed.data.errors),params)}const data=parsed.data.data?.listPackageDocs;if(!data){throw new MalformedPackageIntelligenceResponseError("Empty response from the package-intelligence service.")}return this.normalisePackageDocsList(data)}normalisePackageDocsList(data){return{registry:data.registry??undefined,packageName:data.packageName??undefined,version:data.version??undefined,stale:data.stale??undefined,pages:data.pages?.map((page)=>({id:page.id??undefined,title:page.title??undefined,slug:page.slug??undefined,order:page.order??undefined,linkName:page.linkName??undefined,lastUpdatedAt:page.lastUpdatedAt??undefined,sourceKind:page.sourceKind??undefined,sourceUrl:page.sourceUrl??undefined,repoUrl:page.repoUrl??undefined,gitRef:page.gitRef??undefined,requestedRef:page.requestedRef??undefined,filePath:page.filePath??undefined}))??[],pageInfo:data.pageInfo?{hasNextPage:data.pageInfo.hasNextPage,endCursor:data.pageInfo.endCursor??undefined,totalCount:data.pageInfo.totalCount??undefined}:undefined}}async readPackageDoc(params){return withTelemetrySpan("pkg-intel.docs.read",()=>executeWithTokenRefresh({getToken:()=>this.tokenProvider.getToken(),forceRefresh:()=>this.tokenProvider.forceRefresh(),shouldRefresh:(error)=>error instanceof AuthenticationError,executeWithToken:(token)=>this.executeReadPackageDoc(token,params)}))}async executeReadPackageDoc(token,params){let response;try{response=await postPkgseerGraphql({endpointUrl:this.endpointUrl,token,query:READ_PACKAGE_DOC_QUERY,variables:{pageId:params.pageId},fetchFn:this.fetchFn,clientHeaders:this.runtime.clientHeaders,userAgent:this.runtime.userAgent})}catch(cause){if(cause instanceof PkgseerTransportError){throw this.createTransportError(cause)}throw cause}if(response.status<200||response.status>=300){throw this.createHttpError(response)}const parsed=packageDocReadGraphQLResponseSchema.safeParse(response.parsedBody);if(!parsed.success){throw new MalformedPackageIntelligenceResponseError("Malformed response from the package-intelligence service.")}if(parsed.data.errors&&parsed.data.errors.length>0){throw this.createGraphQLError(parsed.data.errors)}const data=parsed.data.data?.getDocPage;if(!data){throw new MalformedPackageIntelligenceResponseError("Empty response from the package-intelligence service.")}return this.normalisePackageDocResult(data)}normalisePackageDocResult(data){return{registry:data.registry??undefined,packageName:data.packageName??undefined,version:data.version??undefined,sourceKind:data.sourceKind??undefined,page:data.page?{id:data.page.id??undefined,title:data.page.title??undefined,content:data.page.content??undefined,contentFormat:data.page.contentFormat??undefined,breadcrumbs:data.page.breadcrumbs??undefined,linkName:data.page.linkName??undefined,lastUpdatedAt:data.page.lastUpdatedAt??undefined,sourceKind:data.page.sourceKind??undefined,source:data.page.source?{url:data.page.source.url??undefined,label:data.page.source.label??undefined}:undefined,repoUrl:data.page.repoUrl??undefined,gitRef:data.page.gitRef??undefined,requestedRef:data.page.requestedRef??undefined,filePath:data.page.filePath??undefined,baseUrl:data.page.baseUrl??undefined}:undefined}}}function parseDetail3(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,runtime={}){this.apiUrl=apiUrl;this.tokenProvider=tokenProvider;this.serviceFactory=serviceFactory;this.runtime=runtime}async search(params){return this.withTokenRefresh((service)=>service.search(params))}async getLanguages(){return this.withTokenRefresh((service)=>service.getLanguages())}async searchLanguages(query,limit){return this.withTokenRefresh((service)=>service.searchLanguages(query,limit))}async submitFeedback(params){return this.withTokenRefresh((service)=>service.submitFeedback(params))}async withTokenRefresh(operation){return executeWithTokenRefresh({getToken:()=>this.tokenProvider.getToken(),forceRefresh:()=>this.tokenProvider.forceRefresh(),shouldRefresh:(error)=>error instanceof AuthenticationError,executeWithToken:async(token)=>{const service=this.serviceFactory?this.serviceFactory(this.apiUrl,token):new GitHitsServiceImpl(this.apiUrl,token,undefined,undefined,this.runtime);return operation(service)}})}}var PKGSEER_REGISTRY_ARGS=["npm","pypi","hex","crates","nuget","maven","zig","vcpkg","packagist","rubygems","go","swift"];var registryMap={npm:"NPM",pypi:"PYPI",hex:"HEX",crates:"CRATES",nuget:"NUGET",maven:"MAVEN",zig:"ZIG",vcpkg:"VCPKG",packagist:"PACKAGIST",rubygems:"RUBYGEMS",go:"GO",swift:"SWIFT"};var PKGSEER_REGISTRY_LIST=PKGSEER_REGISTRY_ARGS.join(", ");function toPkgseerRegistry(registry){return registryMap[registry]}function toPkgseerRegistryLowercase(registry){for(const[lower,upper]of Object.entries(registryMap)){if(upper===registry)return lower}throw new Error(`Unknown registry value: ${String(registry)} (schema drift?)`)}function isKnownPkgseerRegistryArg(value){return value in registryMap}import{createHash 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";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(),".githits")}function getLegacyAuthStorageDirForEnv(fs,env,platform){return fs.joinPath(getHomeDirForEnv(fs,env,platform),".githits")}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{parse as parseToml}from"smol-toml";import{z as z3}from"zod";var AUTH_STORAGE_MODES=["keychain","file"];var AUTH_STORAGE_MODE_VALUES=new Set(AUTH_STORAGE_MODES);var CONFIG_SCHEMA=z3.object({auth:z3.object({storage:z3.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){let configPath=getAuthConfigPath(fs);const envMode=process.env.GITHITS_AUTH_STORAGE;if(envMode!==undefined&&envMode.trim()!==""){try{return{storage:parseAuthStorageMode(envMode),configPath}}catch(error){if(error instanceof AuthConfigError){throw new AuthConfigError(`Invalid GITHITS_AUTH_STORAGE: ${error.message}`)}throw error}}if(!await fs.exists(configPath)){const legacyMacConfigPath=getLegacyMacAuthConfigPath(fs);if(process.platform==="darwin"&&await fs.exists(legacyMacConfigPath)){configPath=legacyMacConfigPath}else{return{storage:"keychain",configPath}}}let rawConfig;try{rawConfig=parseToml(await fs.readFile(configPath))}catch(error){const message=error instanceof Error?error.message:String(error);throw new AuthConfigError(`Cannot parse GitHits config at ${configPath}: ${message}`)}const parsed=CONFIG_SCHEMA.safeParse(rawConfig);if(!parsed.success){throw new AuthConfigError(`Invalid GitHits config at ${configPath}: ${z3.prettifyError(parsed.error)}`)}const configuredMode=parsed.data.auth?.storage;if(configuredMode===undefined||configuredMode.trim()===""){return{storage:"keychain",configPath}}try{return{storage:parseAuthStorageMode(configuredMode),configPath}}catch(error){if(error instanceof AuthConfigError){throw new AuthConfigError(`Invalid GitHits config at ${configPath}: ${error.message}`)}throw error}}import{createServer}from"node:http";class AuthServiceImpl{fetchFn;fetchTimeoutMs;constructor(fetchFn,fetchTimeoutMs=DEFAULT_FETCH_TIMEOUT_MS){this.fetchFn=fetchFn;this.fetchTimeoutMs=fetchTimeoutMs}async discoverEndpoints(mcpBaseUrl){const url=`${mcpBaseUrl}/.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 response.json();const authorizationEndpoint=data.authorization_endpoint;const tokenEndpoint=data.token_endpoint;const registrationEndpoint=data.registration_endpoint;if(!authorizationEndpoint||!tokenEndpoint||!registrationEndpoint){throw new Error("OAuth metadata missing required endpoints")}return{authorizationEndpoint,tokenEndpoint,registrationEndpoint}}async registerClient(params){const response=await fetchWithTimeout(params.registrationEndpoint,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({client_name:"GitHits CLI",redirect_uris:[params.redirectUri],grant_types:["authorization_code","refresh_token"],response_types:["code"],token_endpoint_auth_method:"client_secret_post"})},this.fetchOptions());if(!response.ok){const error=await response.text();throw new Error(`Client registration failed: ${error}`)}const data=await response.json();if(!data.client_id||!data.client_secret){throw new Error("Client registration response missing required fields")}return{clientId:data.client_id,clientSecret: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){let closeTimer;const server=createServer();let callbackHandled=false;let resolved=false;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;sendHtmlResponse(res,evaluation.statusCode,evaluation.html);if(!resolved){resolved=true;resolve(evaluation.result)}if(closeTimer)clearTimeout(closeTimer);closeTimer=setTimeout(()=>closeServer(server),1500)})});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:async()=>{if(closeTimer)clearTimeout(closeTimer);await closeServer(server)}})})})}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 response=await fetchWithTimeout(params.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 Error(`Token exchange failed: ${error}`)}return parseTokenResponse(await response.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 response=await fetchWithTimeout(params.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 Error(`Token refresh failed: ${error}`)}return parseRefreshTokenResponse(await response.json())}fetchOptions(){return{fetchFn:this.fetchFn,timeoutMs:this.fetchTimeoutMs}}}function parseTokenResponse(data){const d=data;if(!d.access_token||!d.refresh_token){throw new Error("Token response missing required fields")}return{accessToken:d.access_token,refreshToken:d.refresh_token,expiresIn:d.expires_in||3600}}function parseRefreshTokenResponse(data){const d=data;if(!d.access_token){throw new Error("Token response missing required fields")}return{accessToken:d.access_token,refreshToken:typeof d.refresh_token==="string"?d.refresh_token:undefined,expiresIn:d.expires_in||3600}}function successHtml(title="You're signed in"){return`<!DOCTYPE html>
|
|
970
|
+
<html><head>
|
|
971
|
+
<title>GitHits CLI</title>
|
|
972
|
+
<meta charset="utf-8">
|
|
973
|
+
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
974
|
+
<link rel="preconnect" href="https://fonts.googleapis.com">
|
|
975
|
+
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
|
|
976
|
+
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;600;700&family=Lexend:wght@600&display=swap" rel="stylesheet">
|
|
977
|
+
<style>
|
|
978
|
+
*, *::before, *::after { box-sizing: border-box; }
|
|
979
|
+
body {
|
|
980
|
+
margin: 0;
|
|
981
|
+
min-height: 100vh;
|
|
982
|
+
width: 100%;
|
|
983
|
+
padding: 16px;
|
|
984
|
+
background: #21262d;
|
|
985
|
+
color: #ffffff;
|
|
986
|
+
font-family: 'Inter', sans-serif;
|
|
987
|
+
display: flex;
|
|
988
|
+
align-items: center;
|
|
989
|
+
justify-content: center;
|
|
990
|
+
}
|
|
991
|
+
.content {
|
|
992
|
+
display: flex;
|
|
993
|
+
flex-direction: column;
|
|
994
|
+
align-items: center;
|
|
995
|
+
gap: 20px;
|
|
996
|
+
padding: 0 16px;
|
|
997
|
+
}
|
|
998
|
+
.message {
|
|
999
|
+
display: flex;
|
|
1000
|
+
flex-direction: column;
|
|
1001
|
+
align-items: center;
|
|
1002
|
+
gap: 8px;
|
|
1003
|
+
}
|
|
1004
|
+
.success-icon {
|
|
1005
|
+
width: 48px;
|
|
1006
|
+
height: 48px;
|
|
1007
|
+
border-radius: 50%;
|
|
1008
|
+
border: 2px solid #57fec9;
|
|
1009
|
+
background: transparent;
|
|
1010
|
+
display: flex;
|
|
1011
|
+
align-items: center;
|
|
1012
|
+
justify-content: center;
|
|
1013
|
+
}
|
|
1014
|
+
.heading {
|
|
1015
|
+
font-family: 'Lexend', sans-serif;
|
|
1016
|
+
font-weight: 600;
|
|
1017
|
+
font-size: 32px;
|
|
1018
|
+
line-height: 40px;
|
|
1019
|
+
color: #ffffff;
|
|
1020
|
+
margin: 0;
|
|
1021
|
+
text-align: center;
|
|
1022
|
+
text-wrap: pretty;
|
|
1023
|
+
}
|
|
1024
|
+
.text {
|
|
1025
|
+
font-family: 'Inter', sans-serif;
|
|
1026
|
+
font-weight: 400;
|
|
1027
|
+
font-size: 16px;
|
|
1028
|
+
line-height: 24px;
|
|
1029
|
+
margin: 0;
|
|
1030
|
+
text-align: center;
|
|
1031
|
+
text-wrap: pretty;
|
|
1032
|
+
}
|
|
1033
|
+
.text-muted {
|
|
1034
|
+
color: #abb2bf;
|
|
1035
|
+
}${COPY_BTN_CSS}
|
|
1036
|
+
</style>
|
|
1037
|
+
</head>
|
|
1038
|
+
<body>
|
|
1039
|
+
<div class="content">
|
|
1040
|
+
<div class="success-icon" aria-hidden="true">
|
|
1041
|
+
<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">
|
|
1042
|
+
<polyline points="20 6 9 17 4 12" />
|
|
1043
|
+
</svg>
|
|
1044
|
+
</div>
|
|
1045
|
+
<div class="message">
|
|
1046
|
+
<h1 class="heading">${escapeHtml(title)}</h1>
|
|
1047
|
+
<p class="text text-muted">You can close this window and return to your terminal.</p>
|
|
1048
|
+
</div>
|
|
1049
|
+
|
|
1050
|
+
<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">
|
|
1051
|
+
<title>GitHits</title>
|
|
1052
|
+
<defs>
|
|
1053
|
+
<linearGradient id="wm-grad" x1="234.9" y1="64.7" x2="555.5" y2="64.7" gradientUnits="userSpaceOnUse">
|
|
1054
|
+
<stop offset="0" style="stop-color: #ff4fae" />
|
|
1055
|
+
<stop offset="1" style="stop-color: #ff872f" />
|
|
1056
|
+
</linearGradient>
|
|
1057
|
+
</defs>
|
|
1058
|
+
<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" />
|
|
1059
|
+
<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)" />
|
|
1060
|
+
<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" />
|
|
1061
|
+
</svg>
|
|
1062
|
+
|
|
1063
|
+
${HELP_CTA}
|
|
1064
|
+
</div>
|
|
1065
|
+
${COPY_SCRIPT_HTML}
|
|
1066
|
+
</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>
|
|
1067
|
+
<html><head>
|
|
1068
|
+
<title>GitHits CLI</title>
|
|
1069
|
+
<meta charset="utf-8">
|
|
1070
|
+
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
1071
|
+
<link rel="preconnect" href="https://fonts.googleapis.com">
|
|
1072
|
+
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
|
|
1073
|
+
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;600;700&family=Lexend:wght@600&display=swap" rel="stylesheet">
|
|
1074
|
+
<style>
|
|
1075
|
+
*, *::before, *::after { box-sizing: border-box; }
|
|
1076
|
+
body {
|
|
1077
|
+
margin: 0;
|
|
1078
|
+
min-height: 100vh;
|
|
1079
|
+
width: 100%;
|
|
1080
|
+
padding: 16px;
|
|
1081
|
+
background: #21262d;
|
|
1082
|
+
color: #ffffff;
|
|
1083
|
+
font-family: 'Inter', sans-serif;
|
|
1084
|
+
display: flex;
|
|
1085
|
+
align-items: center;
|
|
1086
|
+
justify-content: center;
|
|
1087
|
+
}
|
|
1088
|
+
.content {
|
|
1089
|
+
display: flex;
|
|
1090
|
+
flex-direction: column;
|
|
1091
|
+
align-items: center;
|
|
1092
|
+
gap: 20px;
|
|
1093
|
+
padding: 0 16px;
|
|
1094
|
+
}
|
|
1095
|
+
.message {
|
|
1096
|
+
display: flex;
|
|
1097
|
+
flex-direction: column;
|
|
1098
|
+
align-items: center;
|
|
1099
|
+
gap: 8px;
|
|
1100
|
+
}
|
|
1101
|
+
.error-icon {
|
|
1102
|
+
width: 48px;
|
|
1103
|
+
height: 48px;
|
|
1104
|
+
border-radius: 50%;
|
|
1105
|
+
border: 2px solid #ff5a6a;
|
|
1106
|
+
background: transparent;
|
|
1107
|
+
display: flex;
|
|
1108
|
+
align-items: center;
|
|
1109
|
+
justify-content: center;
|
|
1110
|
+
}
|
|
1111
|
+
.heading {
|
|
1112
|
+
font-family: 'Lexend', sans-serif;
|
|
1113
|
+
font-weight: 600;
|
|
1114
|
+
font-size: 32px;
|
|
1115
|
+
line-height: 40px;
|
|
1116
|
+
color: #ffffff;
|
|
1117
|
+
margin: 0;
|
|
1118
|
+
text-align: center;
|
|
1119
|
+
text-wrap: pretty;
|
|
1120
|
+
}
|
|
1121
|
+
.text {
|
|
1122
|
+
font-family: 'Inter', sans-serif;
|
|
1123
|
+
font-weight: 400;
|
|
1124
|
+
font-size: 16px;
|
|
1125
|
+
line-height: 24px;
|
|
1126
|
+
margin: 0;
|
|
1127
|
+
text-align: center;
|
|
1128
|
+
text-wrap: pretty;
|
|
1129
|
+
}
|
|
1130
|
+
.text-muted {
|
|
1131
|
+
color: #abb2bf;
|
|
1132
|
+
}
|
|
1133
|
+
.footer-text {
|
|
1134
|
+
font-family: 'Inter', sans-serif;
|
|
1135
|
+
font-weight: 400;
|
|
1136
|
+
font-size: 12px;
|
|
1137
|
+
line-height: 16px;
|
|
1138
|
+
color: #abb2bf;
|
|
1139
|
+
margin: 0;
|
|
1140
|
+
text-align: center;
|
|
1141
|
+
text-wrap: pretty;
|
|
1142
|
+
}
|
|
1143
|
+
.footer-link {
|
|
1144
|
+
color: inherit;
|
|
1145
|
+
text-decoration: underline;
|
|
1146
|
+
text-underline-offset: 2px;
|
|
1147
|
+
}
|
|
1148
|
+
.error-code {
|
|
1149
|
+
font-family: 'Inter', sans-serif;
|
|
1150
|
+
font-weight: 400;
|
|
1151
|
+
font-size: 12px;
|
|
1152
|
+
line-height: 16px;
|
|
1153
|
+
color: #abb2bf;
|
|
1154
|
+
opacity: 0.7;
|
|
1155
|
+
margin: 4px 0 0;
|
|
1156
|
+
text-align: center;
|
|
1157
|
+
}
|
|
1158
|
+
.error-code code {
|
|
1159
|
+
font-size: 11px;
|
|
1160
|
+
padding: 0 5px;
|
|
1161
|
+
}
|
|
1162
|
+
code {
|
|
1163
|
+
font-family: 'Consolas', monospace;
|
|
1164
|
+
font-size: 13px;
|
|
1165
|
+
background: rgba(255, 255, 255, 0.08);
|
|
1166
|
+
padding: 1px 6px;
|
|
1167
|
+
border-radius: 4px;
|
|
1168
|
+
color: #ffffff;
|
|
1169
|
+
}${COPY_BTN_CSS}
|
|
1170
|
+
</style>
|
|
1171
|
+
</head>
|
|
1172
|
+
<body>
|
|
1173
|
+
<div class="content">
|
|
1174
|
+
<div class="error-icon" aria-hidden="true">
|
|
1175
|
+
<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">
|
|
1176
|
+
<line x1="18" y1="6" x2="6" y2="18"/>
|
|
1177
|
+
<line x1="6" y1="6" x2="18" y2="18"/>
|
|
1178
|
+
</svg>
|
|
1179
|
+
</div>
|
|
1180
|
+
|
|
1181
|
+
<div class="message">
|
|
1182
|
+
<h1 class="heading">Sign-in failed</h1>
|
|
1183
|
+
<p class="text text-muted">${escapeHtml(error)}</p>
|
|
1184
|
+
${errorCodeHtml}
|
|
1185
|
+
</div>
|
|
1186
|
+
|
|
1187
|
+
${ctaHtml??""}
|
|
1188
|
+
|
|
1189
|
+
<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">
|
|
1190
|
+
<title>GitHits</title>
|
|
1191
|
+
<defs>
|
|
1192
|
+
<linearGradient id="wm-grad" x1="234.9" y1="64.7" x2="555.5" y2="64.7" gradientUnits="userSpaceOnUse">
|
|
1193
|
+
<stop offset="0" style="stop-color: #ff4fae" />
|
|
1194
|
+
<stop offset="1" style="stop-color: #ff872f" />
|
|
1195
|
+
</linearGradient>
|
|
1196
|
+
</defs>
|
|
1197
|
+
<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" />
|
|
1198
|
+
<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)" />
|
|
1199
|
+
<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" />
|
|
1200
|
+
</svg>
|
|
1201
|
+
|
|
1202
|
+
<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>
|
|
1203
|
+
</div>
|
|
1204
|
+
${COPY_SCRIPT_HTML}
|
|
1205
|
+
</body></html>`}function sendHtmlResponse(res,statusCode,html){res.writeHead(statusCode,{"Content-Type":"text/html; charset=utf-8"});res.end(html)}function closeServer(server){return new Promise((resolve,reject)=>{if(!server.listening){resolve();return}server.close((error)=>{if(error)reject(error);else resolve()})})}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(`
|
|
1206
|
+
`);return`<div class="cli-cta">
|
|
1207
|
+
<p class="tip">${introHtml}</p>
|
|
1208
|
+
${buttons}
|
|
1209
|
+
</div>`}var COPY_BTN_CSS=`
|
|
1210
|
+
.wordmark {
|
|
1211
|
+
margin: 16px 0;
|
|
1212
|
+
}
|
|
1213
|
+
.cli-cta {
|
|
1214
|
+
display: flex;
|
|
1215
|
+
flex-direction: column;
|
|
1216
|
+
align-items: center;
|
|
1217
|
+
gap: 12px;
|
|
1218
|
+
margin: 16px 0 0;
|
|
1219
|
+
}
|
|
1220
|
+
.wordmark + .cli-cta {
|
|
1221
|
+
margin-top: 0;
|
|
1222
|
+
}
|
|
1223
|
+
.tip {
|
|
1224
|
+
font-family: 'Inter', sans-serif;
|
|
1225
|
+
font-weight: 400;
|
|
1226
|
+
font-size: 14px;
|
|
1227
|
+
line-height: 20px;
|
|
1228
|
+
color: #d5d9df;
|
|
1229
|
+
margin: 0;
|
|
1230
|
+
text-align: center;
|
|
1231
|
+
text-wrap: pretty;
|
|
1232
|
+
}
|
|
1233
|
+
.githits-cli-btn {
|
|
1234
|
+
display: inline-flex;
|
|
1235
|
+
align-items: center;
|
|
1236
|
+
gap: 0.5rem;
|
|
1237
|
+
background-color: rgba(255, 255, 255, 0.08);
|
|
1238
|
+
border: none;
|
|
1239
|
+
border-radius: 0.5rem;
|
|
1240
|
+
padding: 1rem 1.25rem;
|
|
1241
|
+
font-family: Consolas, ui-monospace, SFMono-Regular, Menlo, Monaco, monospace;
|
|
1242
|
+
font-size: 14px;
|
|
1243
|
+
font-weight: 500;
|
|
1244
|
+
color: #abb2bf;
|
|
1245
|
+
cursor: pointer;
|
|
1246
|
+
line-height: 1;
|
|
1247
|
+
transition: background-color 0.2s ease, transform 0.1s ease, color 0.2s ease;
|
|
1248
|
+
}
|
|
1249
|
+
.githits-cli-btn:hover {
|
|
1250
|
+
color: #d5d9df;
|
|
1251
|
+
}
|
|
1252
|
+
.githits-cli-btn:active {
|
|
1253
|
+
transform: scale(0.98);
|
|
1254
|
+
}
|
|
1255
|
+
.githits-cli-btn:focus-visible {
|
|
1256
|
+
outline: 2px solid #abb2bf;
|
|
1257
|
+
outline-offset: 2px;
|
|
1258
|
+
}
|
|
1259
|
+
.githits-cli-cmd {
|
|
1260
|
+
white-space: nowrap;
|
|
1261
|
+
}
|
|
1262
|
+
.githits-cli-icon {
|
|
1263
|
+
width: 14px;
|
|
1264
|
+
height: 14px;
|
|
1265
|
+
color: #abb2bf;
|
|
1266
|
+
flex-shrink: 0;
|
|
1267
|
+
}
|
|
1268
|
+
.githits-cli-btn.copied .githits-cli-icon-copy { display: none; }
|
|
1269
|
+
.githits-cli-btn:not(.copied) .githits-cli-icon-check { display: none; }
|
|
1270
|
+
.githits-cli-btn.copied .githits-cli-icon { color: #abb2bf; }`;var COPY_SCRIPT_HTML=`<script>
|
|
1271
|
+
(function() {
|
|
1272
|
+
var timers = new WeakMap();
|
|
1273
|
+
var buttons = document.querySelectorAll('.githits-cli-btn');
|
|
1274
|
+
for (var i = 0; i < buttons.length; i++) {
|
|
1275
|
+
buttons[i].addEventListener('click', function(e) {
|
|
1276
|
+
var target = e.currentTarget;
|
|
1277
|
+
var text = target.getAttribute('data-copy');
|
|
1278
|
+
if (!text || !navigator.clipboard) return;
|
|
1279
|
+
navigator.clipboard.writeText(text).then(function() {
|
|
1280
|
+
target.classList.add('copied');
|
|
1281
|
+
var existing = timers.get(target);
|
|
1282
|
+
if (existing) clearTimeout(existing);
|
|
1283
|
+
timers.set(target, setTimeout(function() {
|
|
1284
|
+
target.classList.remove('copied');
|
|
1285
|
+
timers.delete(target);
|
|
1286
|
+
}, 1500));
|
|
1287
|
+
});
|
|
1288
|
+
});
|
|
1289
|
+
}
|
|
1290
|
+
})();
|
|
1291
|
+
</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,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}var AUTH_FILE="auth.json";var CLIENT_FILE="client.json";var DIR_MODE=448;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(baseUrl2){const stored=await this.loadAuthFile();if(!stored)return null;return stored.tokens[normalizeBaseUrl(baseUrl2)]??null}async saveTokens(baseUrl2,data){const stored=await this.loadAuthFile()??{version:1,tokens:{}};stored.tokens[normalizeBaseUrl(baseUrl2)]=data;await this.fs.ensureDir(this.configDir,DIR_MODE);await this.fs.atomicWriteFile(this.authPath,JSON.stringify(stored,null,2))}async saveTokensIfUnchanged(baseUrl2,expected,data){const current=await this.loadTokens(baseUrl2);if(!sameTokenData(current,expected))return false;await this.saveTokens(baseUrl2,data);return true}async clearTokens(baseUrl2){const stored=await this.loadAuthFile();if(!stored)return;delete stored.tokens[normalizeBaseUrl(baseUrl2)];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))}}async clearTokensIfUnchanged(baseUrl2,expected){const current=await this.loadTokens(baseUrl2);if(!sameTokenData(current,expected))return false;await this.clearTokens(baseUrl2);return true}async loadClient(baseUrl2){const stored=await this.loadClientFile();if(!stored)return null;return stored.clients[normalizeBaseUrl(baseUrl2)]??null}async clearClient(baseUrl2){const stored=await this.loadClientFile();if(!stored)return;delete stored.clients[normalizeBaseUrl(baseUrl2)];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))}}async saveClient(baseUrl2,data){const stored=await this.loadClientFile()??{version:1,clients:{}};stored.clients[normalizeBaseUrl(baseUrl2)]=data;await this.fs.ensureDir(this.configDir,DIR_MODE);await this.fs.atomicWriteFile(this.clientPath,JSON.stringify(stored,null,2))}async saveAuthSession(baseUrl2,client,tokens){await this.saveClient(baseUrl2,client);await this.saveTokens(baseUrl2,tokens)}async clearAuthSession(baseUrl2){await clearAuthSessionBestEffort(()=>this.clearTokens(baseUrl2),()=>this.clearClient(baseUrl2))}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 METADATA_FILE="metadata.json";var DIR_MODE2=448;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(baseUrl2){const stored=await this.loadFile();if(!stored)return null;const metadata=stored.sessions[normalizeBaseUrl(baseUrl2)]??null;return isAuthSessionMetadata(metadata)?metadata:null}async saveFromTokens(baseUrl2,tokens){const stored=await this.loadFile()??{version:1,sessions:{}};stored.sessions[normalizeBaseUrl(baseUrl2)]={createdAt:tokens.createdAt,expiresAt:tokens.expiresAt,updatedAt:new Date().toISOString()};await this.fs.ensureDir(this.configDir,DIR_MODE2);await this.fs.atomicWriteFile(this.metadataPath,JSON.stringify(stored,null,2))}async clear(baseUrl2){const stored=await this.loadFile();if(!stored)return;delete stored.sessions[normalizeBaseUrl(baseUrl2)];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))}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,readdir,readFile,rename,stat,unlink,writeFile}from"node:fs/promises";import{homedir}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 deleteFile(path){try{await unlink(path)}catch(error){if(error.code!=="ENOENT"){throw error}}}async exists(path){try{await stat(path);return true}catch{return false}}async ensureDir(path,mode){await mkdir(path,{recursive:true,mode})}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){const tmpPath=`${path}.${process.pid}.${randomUUID2()}.tmp`;let mode=384;try{const existing=await stat(path);mode=existing.mode&511}catch{}try{await writeFile(tmpPath,contents,{mode});await rename(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(baseUrl2){const key=`${TOKEN_PREFIX}${normalizeBaseUrl(baseUrl2)}`;const json=this.keyring.getPassword(SERVICE_NAME,key);const data=parseJsonOrNull2(json);if(data!==null&&!isValidTokenData(data))return null;return data}async saveTokens(baseUrl2,data){const key=`${TOKEN_PREFIX}${normalizeBaseUrl(baseUrl2)}`;this.keyring.setPassword(SERVICE_NAME,key,JSON.stringify(data))}async saveTokensIfUnchanged(baseUrl2,expected,data){const current=await this.loadTokens(baseUrl2);if(!sameTokenData(current,expected))return false;await this.saveTokens(baseUrl2,data);return true}async clearTokens(baseUrl2){const key=`${TOKEN_PREFIX}${normalizeBaseUrl(baseUrl2)}`;this.keyring.deletePassword(SERVICE_NAME,key)}async clearTokensIfUnchanged(baseUrl2,expected){const current=await this.loadTokens(baseUrl2);if(!sameTokenData(current,expected))return false;await this.clearTokens(baseUrl2);return true}async loadClient(baseUrl2){const key=`${CLIENT_PREFIX}${normalizeBaseUrl(baseUrl2)}`;const json=this.keyring.getPassword(SERVICE_NAME,key);const data=parseJsonOrNull2(json);if(data!==null&&!isValidClientRegistration(data))return null;return data}async saveClient(baseUrl2,data){const key=`${CLIENT_PREFIX}${normalizeBaseUrl(baseUrl2)}`;this.keyring.setPassword(SERVICE_NAME,key,JSON.stringify(data))}async clearClient(baseUrl2){const key=`${CLIENT_PREFIX}${normalizeBaseUrl(baseUrl2)}`;this.keyring.deletePassword(SERVICE_NAME,key)}async saveAuthSession(baseUrl2,client,tokens){await this.saveClient(baseUrl2,client);await this.saveTokens(baseUrl2,tokens)}async clearAuthSession(baseUrl2){await clearAuthSessionBestEffort(()=>this.clearTokens(baseUrl2),()=>this.clearClient(baseUrl2))}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{randomUUID as randomUUID3}from"node:crypto";import{mkdir as mkdir2,readFile as readFile2,rm,writeFile as writeFile2}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 ORPHANED_LOCK_MS=5000;var OWNER_FILE="owner.json";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;lockPath;lockTimeoutMs;isOwnerAlive;lockContext=new AsyncLocalStorage;currentOwner=null;constructor(storage,fileSystemService,options={}){this.storage=storage;this.lockTimeoutMs=options.lockTimeoutMs??LOCK_TIMEOUT_MS;this.isOwnerAlive=options.isOwnerAlive??isOriginalProcessAlive;this.lockPath=fileSystemService.joinPath(getAppConfigDir(fileSystemService),LOCK_DIR)}loadTokens(baseUrl2){return this.storage.loadTokens(baseUrl2)}saveTokens(baseUrl2,data){return this.withAuthStorageLock(()=>this.storage.saveTokens(baseUrl2,data))}saveTokensIfUnchanged(baseUrl2,expected,data){return this.withAuthStorageLock(()=>this.storage.saveTokensIfUnchanged(baseUrl2,expected,data))}clearTokens(baseUrl2){return this.withAuthStorageLock(()=>this.storage.clearTokens(baseUrl2))}clearTokensIfUnchanged(baseUrl2,expected){return this.withAuthStorageLock(()=>this.storage.clearTokensIfUnchanged(baseUrl2,expected))}loadClient(baseUrl2){return this.storage.loadClient(baseUrl2)}saveClient(baseUrl2,data){return this.withAuthStorageLock(()=>this.storage.saveClient(baseUrl2,data))}clearClient(baseUrl2){return this.withAuthStorageLock(()=>this.storage.clearClient(baseUrl2))}saveAuthSession(baseUrl2,client,tokens){return this.withAuthStorageLock(()=>this.storage.saveAuthSession(baseUrl2,client,tokens))}clearAuthSession(baseUrl2){return this.withAuthStorageLock(()=>this.storage.clearAuthSession(baseUrl2))}getStorageLocation(){return this.storage.getStorageLocation()}async withAuthStorageLock(fn){const ownerId=this.lockContext.getStore();if(ownerId&&this.currentOwner?.id===ownerId){return fn()}await this.acquireLock();const acquiredOwnerId=this.currentOwner?.id;try{return await this.lockContext.run(acquiredOwnerId??"",fn)}finally{await this.releaseLock()}}async acquireLock(){const processStartedAt=await getProcessStartedAt(process.pid);const startedAt=Date.now();await mkdir2(dirname2(this.lockPath),{recursive:true,mode:448});while(true){try{await mkdir2(this.lockPath,{recursive:false,mode:448});try{await this.writeOwner(processStartedAt)}catch(error){this.currentOwner=null;if(error.code==="EEXIST"){await sleep(LOCK_RETRY_MS);continue}await rm(this.lockPath,{recursive:true,force:true}).catch(()=>{return});throw error}return}catch(error){if(error.code!=="EEXIST")throw error;await this.reclaimStaleLock();if(Date.now()-startedAt>=this.lockTimeoutMs){throw new AuthStorageLockTimeoutError(`Timed out waiting for GitHits auth storage lock at ${this.lockPath}. If no githits process is running, remove this directory and retry.`)}await sleep(LOCK_RETRY_MS)}}}async writeOwner(processStartedAt){const owner={id:randomUUID3(),pid:process.pid,createdAt:new Date().toISOString(),processStartedAt};await writeFile2(this.ownerPath(),JSON.stringify(owner),{mode:384,flag:"wx"});this.currentOwner=owner}async reclaimStaleLock(){const owner=await this.readOwner();if(!owner){await this.reclaimOldOwnerlessLock();return}const ownerDead=!await this.isOwnerAlive(owner.pid,owner.processStartedAt);if(!ownerDead)return;const currentOwner=await this.readOwner();if(!currentOwner||currentOwner.id!==owner.id)return;await rm(this.lockPath,{recursive:true,force:true}).catch(()=>{return})}async reclaimOldOwnerlessLock(){const createdAtMs=await lockCreatedAtMs(this.lockPath);if(Date.now()-createdAtMs<ORPHANED_LOCK_MS)return;await rm(this.lockPath,{recursive:true,force:true}).catch(()=>{return})}async readOwner(){try{const raw=await readFile2(this.ownerPath(),"utf8");const parsed=JSON.parse(raw);if(typeof parsed.id!=="string"||typeof parsed.pid!=="number"||typeof parsed.createdAt!=="string"||!(typeof parsed.processStartedAt==="string"||parsed.processStartedAt===null)){return null}return{id:parsed.id,pid:parsed.pid,createdAt:parsed.createdAt,processStartedAt:parsed.processStartedAt}}catch{return null}}async releaseLock(){const owner=this.currentOwner;this.currentOwner=null;if(!owner)return;const currentOwner=await this.readOwner();if(!currentOwner||currentOwner.id!==owner.id)return;await rm(this.lockPath,{recursive:true,force:true}).catch(()=>{return})}ownerPath(){return`${this.lockPath}/${OWNER_FILE}`}}function sleep(ms){return new Promise((resolve)=>setTimeout(resolve,ms))}async function isOriginalProcessAlive(pid,processStartedAt){if(!isProcessAlive(pid))return false;if(!processStartedAt)return true;return await getProcessStartedAt(pid)===processStartedAt}function isProcessAlive(pid){if(pid<=0)return false;try{process.kill(pid,0);return true}catch(error){const code=error.code;return code==="EPERM"}}async function getProcessStartedAt(pid){try{if(process.platform==="win32"){const{stdout:stdout2}=await execFileAsync("powershell.exe",["-NoProfile","-Command",`(Get-Process -Id ${pid}).StartTime.ToUniversalTime().ToString('o')`]);return stdout2.trim()||null}const{stdout}=await execFileAsync("ps",["-p",String(pid),"-o","lstart="]);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:stat2}=await import("node:fs/promises");return(await stat2(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.
|
|
1292
|
+
|
|
1293
|
+
Options:
|
|
1294
|
+
1. Unlock or fix your system keychain.
|
|
1295
|
+
2. Use GITHITS_API_TOKEN for CI/automation.
|
|
1296
|
+
3. If you accept storing OAuth credentials unencrypted on disk, set:
|
|
1297
|
+
|
|
1298
|
+
[auth]
|
|
1299
|
+
storage = "file"
|
|
1300
|
+
|
|
1301
|
+
in ${configPath}, or run with GITHITS_AUTH_STORAGE=file.
|
|
1302
|
+
|
|
1303
|
+
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(baseUrl2){return this.storage.loadTokens(baseUrl2)}async saveTokens(baseUrl2,data){this.assertFileMode();await this.storage.saveTokens(baseUrl2,data)}async saveTokensIfUnchanged(baseUrl2,expected,data){this.assertFileMode();return this.storage.saveTokensIfUnchanged(baseUrl2,expected,data)}clearTokens(baseUrl2){return this.storage.clearTokens(baseUrl2)}clearTokensIfUnchanged(baseUrl2,expected){return this.storage.clearTokensIfUnchanged(baseUrl2,expected)}loadClient(baseUrl2){return this.storage.loadClient(baseUrl2)}async saveClient(baseUrl2,data){this.assertFileMode();await this.storage.saveClient(baseUrl2,data)}clearClient(baseUrl2){return this.storage.clearClient(baseUrl2)}async saveAuthSession(baseUrl2,client,tokens){this.assertFileMode();await this.storage.saveAuthSession(baseUrl2,client,tokens)}clearAuthSession(baseUrl2){return this.storage.clearAuthSession(baseUrl2)}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;warnedFileModeKeychainExport=false;warnedAmbiguousPlaintext=false;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}async loadTokens(baseUrl2){if(this.mode==="file"){return this.loadTokensFileMode(baseUrl2)}return this.loadTokensKeychainMode(baseUrl2)}async saveTokens(baseUrl2,data){if(this.mode==="file"){await this.file.saveTokens(baseUrl2,data);await this.saveMetadataBestEffort(baseUrl2,data);return}try{await this.primary.saveTokens(baseUrl2,data);await this.saveMetadataBestEffort(baseUrl2,data)}catch(error){throw this.toPolicyError(error)}}async saveTokensIfUnchanged(baseUrl2,expected,data){const current=await this.loadTokens(baseUrl2);if(!this.sameTokenData(current,expected))return false;await this.saveTokens(baseUrl2,data);return true}async clearTokens(baseUrl2){const primaryError=await this.clearBestEffort(()=>this.primary.clearTokens(baseUrl2));await this.clearBestEffort(()=>this.file.clearTokens(baseUrl2));await this.clearBestEffort(()=>this.legacy.clearTokens(baseUrl2));for(const legacy of this.additionalLegacyStores){await this.clearBestEffort(()=>legacy.clearTokens(baseUrl2))}await this.clearBestEffort(()=>this.metadata?.clear(baseUrl2)??Promise.resolve());if(primaryError&&!(primaryError instanceof KeychainUnavailableError)){throw primaryError}}async clearTokensIfUnchanged(baseUrl2,expected){const current=await this.loadTokens(baseUrl2);if(!this.sameTokenData(current,expected))return false;await this.clearTokens(baseUrl2);return true}async loadClient(baseUrl2){if(this.mode==="file"){return this.loadClientFileMode(baseUrl2)}return this.loadClientKeychainMode(baseUrl2)}async saveClient(baseUrl2,data){if(this.mode==="file"){await this.file.saveClient(baseUrl2,data);return}try{await this.primary.saveClient(baseUrl2,data)}catch(error){throw this.toPolicyError(error)}}async clearClient(baseUrl2){const primaryError=await this.clearBestEffort(()=>this.primary.clearClient(baseUrl2));await this.clearBestEffort(()=>this.file.clearClient(baseUrl2));await this.clearBestEffort(()=>this.legacy.clearClient(baseUrl2));for(const legacy of this.additionalLegacyStores){await this.clearBestEffort(()=>legacy.clearClient(baseUrl2))}if(primaryError&&!(primaryError instanceof KeychainUnavailableError)){throw primaryError}}async saveAuthSession(baseUrl2,client,tokens){if(this.mode==="file"){await this.file.saveAuthSession(baseUrl2,client,tokens);await this.saveMetadataBestEffort(baseUrl2,tokens);return}try{await this.primary.saveAuthSession(baseUrl2,client,tokens);await this.saveMetadataBestEffort(baseUrl2,tokens)}catch(error){throw this.toPolicyError(error)}}async clearAuthSession(baseUrl2){const primaryError=await this.clearBestEffort(()=>this.primary.clearAuthSession(baseUrl2));await this.clearBestEffort(()=>this.file.clearAuthSession(baseUrl2));await this.clearBestEffort(()=>this.legacy.clearAuthSession(baseUrl2));for(const legacy of this.additionalLegacyStores){await this.clearBestEffort(()=>legacy.clearAuthSession(baseUrl2))}await this.clearBestEffort(()=>this.metadata?.clear(baseUrl2)??Promise.resolve());if(primaryError&&!(primaryError instanceof KeychainUnavailableError)){throw primaryError}}getStorageLocation(){return this.mode==="file"?this.file.getStorageLocation():this.primary.getStorageLocation()}async loadTokensKeychainMode(baseUrl2){try{const primaryTokens=await this.primary.loadTokens(baseUrl2);if(primaryTokens){await this.saveMetadataBestEffort(baseUrl2,primaryTokens);return primaryTokens}}catch(error){if(!(error instanceof KeychainUnavailableError))throw error}const candidate=await this.selectPlaintextTokenCandidate(baseUrl2);if(!candidate)return null;try{await this.primary.saveTokens(baseUrl2,candidate.data)}catch(error){if(error instanceof KeychainUnavailableError)return candidate.data;throw error}await this.clearMigratedPlaintext(baseUrl2,"tokens",candidate.source,candidate.storage,candidate.ambiguous);await this.saveMetadataBestEffort(baseUrl2,candidate.data);return candidate.data}async loadTokensFileMode(baseUrl2){const candidate=await this.selectPlaintextTokenCandidate(baseUrl2);if(candidate){if(candidate.source==="legacy"){await this.file.saveTokens(baseUrl2,candidate.data);await this.clearBestEffort(()=>candidate.storage.clearTokens(baseUrl2))}await this.saveMetadataBestEffort(baseUrl2,candidate.data);return candidate.data}let primaryTokens=null;try{primaryTokens=await this.primary.loadTokens(baseUrl2)}catch(error){if(!(error instanceof KeychainUnavailableError))throw error}if(!primaryTokens)return null;this.warnKeychainExport();await this.file.saveTokens(baseUrl2,primaryTokens);await this.saveMetadataBestEffort(baseUrl2,primaryTokens);return primaryTokens}async loadClientKeychainMode(baseUrl2){try{const primaryClient=await this.primary.loadClient(baseUrl2);if(primaryClient)return primaryClient}catch(error){if(!(error instanceof KeychainUnavailableError))throw error}const candidate=await this.selectPlaintextClientCandidate(baseUrl2);if(!candidate)return null;try{await this.primary.saveClient(baseUrl2,candidate.data)}catch(error){if(error instanceof KeychainUnavailableError)return candidate.data;throw error}await this.clearMigratedPlaintext(baseUrl2,"client",candidate.source,candidate.storage,candidate.ambiguous);return candidate.data}async loadClientFileMode(baseUrl2){const candidate=await this.selectPlaintextClientCandidate(baseUrl2);if(candidate){if(candidate.source==="legacy"){await this.file.saveClient(baseUrl2,candidate.data);await this.clearBestEffort(()=>candidate.storage.clearClient(baseUrl2))}return candidate.data}let primaryClient=null;try{primaryClient=await this.primary.loadClient(baseUrl2)}catch(error){if(!(error instanceof KeychainUnavailableError))throw error}if(!primaryClient)return null;this.warnKeychainExport();await this.file.saveClient(baseUrl2,primaryClient);return primaryClient}async selectPlaintextTokenCandidate(baseUrl2){const candidates=[];const fileTokens=await this.file.loadTokens(baseUrl2);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(baseUrl2);if(legacyTokens){candidates.push({data:legacyTokens,source:"legacy",storage:legacy,timestamp:legacyTokens.createdAt,ambiguous:false})}}return this.selectNewestCandidate(candidates)}async selectPlaintextClientCandidate(baseUrl2){const candidates=[];const fileClient=await this.file.loadClient(baseUrl2);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(baseUrl2);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))){this.warnAmbiguousPlaintext();const selected=candidates.find((candidate)=>candidate.source==="file")??null;if(selected)selected.ambiguous=true;return selected}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){this.warnAmbiguousPlaintext();const selected=candidates.find((candidate)=>candidate.source==="file")??null;if(!selected)return null;selected.ambiguous=true;return selected}return first.candidate}async clearMigratedPlaintext(baseUrl2,kind,source,storage,ambiguous=false){if(!ambiguous){await this.clearPlaintextSource(this.file,baseUrl2,kind);for(const legacy of this.getLegacyStores()){await this.clearPlaintextSource(legacy,baseUrl2,kind)}return}if(source==="file"){await this.clearPlaintextSource(this.file,baseUrl2,kind);return}if(source==="legacy"){await this.clearPlaintextSource(storage,baseUrl2,kind)}}getLegacyStores(){return[...this.additionalLegacyStores,this.legacy]}async clearPlaintextSource(storage,baseUrl2,kind){await this.clearBestEffort(()=>kind==="tokens"?storage.clearTokens(baseUrl2):storage.clearClient(baseUrl2))}async clearBestEffort(fn){try{await fn();return}catch(error){return error}}async saveMetadataBestEffort(baseUrl2,tokens){await this.clearBestEffort(()=>this.metadata?.saveFromTokens(baseUrl2,tokens)??Promise.resolve())}toPolicyError(error){if(!(error instanceof KeychainUnavailableError))return error;return new AuthStoragePolicyError(`System keychain is unavailable. ${createFileAuthStorageGuidance(this.configPath)}`)}warnKeychainExport(){if(this.warnedFileModeKeychainExport)return;this.warnedFileModeKeychainExport=true;this.onWarning("Warning: auth.storage=file is exporting existing keychain credentials to plaintext file storage.")}warnAmbiguousPlaintext(){if(this.warnedAmbiguousPlaintext)return;this.warnedAmbiguousPlaintext=true;this.onWarning("Warning: multiple plaintext auth entries exist with ambiguous timestamps; using the new config auth path and leaving the other entry 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}}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});return manager.forceRefresh()}class TokenManager{authService;authStorage;mcpUrl;cachedToken=null;softRefreshPromise=null;forceRefreshPromise=null;constructor(deps){this.authService=deps.authService;this.authStorage=deps.authStorage;this.mcpUrl=deps.mcpUrl}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}const refreshedToken=await this.refreshFromGetToken();if(refreshedToken){return refreshedToken}if(!expired){return currentToken}return})}async forceRefresh(){return withTelemetrySpan("token-manager.force-refresh",()=>this.refreshAfterAuthFailure())}async refreshFromGetToken(){const result=await this.softRefresh();return result.accessToken}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)return refreshResult(undefined,false);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{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(candidate.externallyUpdated&&!isExpired){return refreshResult(tokens.accessToken,false)}if(isExpired){const currentStoredTokens=await this.loadExternallyUpdatedToken(tokens);if(currentStoredTokens){return refreshResult(currentStoredTokens.accessToken,false)}const cleared=await withTelemetrySpan("token-manager.clear-tokens-if-unchanged",()=>this.authStorage.clearTokensIfUnchanged(this.mcpUrl,tokens));if(!cleared){const currentToken=await this.authStorage.loadTokens(this.mcpUrl);this.cachedToken=currentToken;return refreshResult(currentToken?.accessToken,false)}this.cachedToken=null}return refreshResult(undefined,false)}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 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){return{accessToken,refreshedViaEndpoint}}var BASE_CLIENT_NAME="githits-cli";var USER_AGENT=`${BASE_CLIENT_NAME}/${version}`;async function createAuthStorage(fileSystemService){return withTelemetrySpan("container.create-auth-storage",async()=>{const authConfig=await loadAuthConfig(fileSystemService);return createAuthStorageForMode(fileSystemService,authConfig.storage,authConfig.configPath)})}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 loadAutoLoginAuthSessionMetadata(){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(getMcpUrl())}async function clearAutoLoginAuthSessionMetadata(){const fileSystemService=new FileSystemServiceImpl;const metadataStorage=new AuthSessionMetadataStorage(fileSystemService);await metadataStorage.clear(getMcpUrl())}async function createAuthCommandDependencies(){return withTelemetrySpan("container.create-auth-command",async()=>{const fileSystemService=new FileSystemServiceImpl;return{authStorage:await createAuthStorage(fileSystemService),authService:new AuthServiceImpl,browserService:new BrowserServiceImpl,fileSystemService,mcpUrl:getMcpUrl(),apiUrl:getApiUrl(),envApiToken:getEnvApiToken()}})}async function createAuthStatusDependencies(){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,browserService:new BrowserServiceImpl,fileSystemService,mcpUrl:getMcpUrl(),apiUrl:getApiUrl(),envApiToken}})}function createStaticTokenProvider(token){return{getToken:async()=>token,forceRefresh:async()=>{return}}}async function createContainer(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 authService=new AuthServiceImpl;const browserService=new BrowserServiceImpl;const clientHeaders=createClientHeaderBuilder({clientName:options.clientName??BASE_CLIENT_NAME,clientVersion:version,agentProvider:options.agentProvider});const serviceRuntime={clientHeaders,userAgent:USER_AGENT,clientVersion:version};const envToken=getEnvApiToken();if(envToken){const authStorage2=createAuthStorageForMode(fileSystemService,"keychain");const tokenProvider=createStaticTokenProvider(envToken);const codeNavigationService2=new CodeNavigationServiceImpl(codeNavigationUrl,tokenProvider,globalThis.fetch,serviceRuntime);const packageIntelligenceService2=new PackageIntelligenceServiceImpl(codeNavigationUrl,tokenProvider,globalThis.fetch,serviceRuntime);return{authStorage:authStorage2,authService,browserService,fileSystemService,mcpUrl,apiUrl,apiToken:envToken,hasValidToken:true,envApiToken:envToken,codeNavigationUrl,codeNavigationService:codeNavigationService2,packageIntelligenceService:packageIntelligenceService2,githitsService:new GitHitsServiceImpl(apiUrl,envToken,undefined,undefined,serviceRuntime)}}const authStorage=await createAuthStorage(fileSystemService);const tokenManager=new TokenManager({authService,authStorage,mcpUrl});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,globalThis.fetch,serviceRuntime);const packageIntelligenceService=new PackageIntelligenceServiceImpl(codeNavigationUrl,tokenManager,globalThis.fetch,serviceRuntime);return{authStorage,authService,browserService,fileSystemService,mcpUrl,apiUrl,apiToken,hasValidToken:apiToken!==undefined,envApiToken:undefined,codeNavigationUrl,codeNavigationService,packageIntelligenceService,githitsService:new RefreshingGitHitsService(apiUrl,tokenManager,undefined,serviceRuntime)}})}
|
|
1304
|
+
export{CLIENT_UPDATE_REQUIRED_REASON,ClientUpdateRequiredError,debugLog,isTelemetryEnabled,withTelemetrySpan,startTelemetrySpan,endTelemetrySpan,flushTelemetry,LOCAL_AUTHENTICATION_MISSING_MESSAGE,AuthenticationError,CodeNavigationAccessError,CodeNavigationGraphQLError,CodeNavigationIndexingError,CodeNavigationUnresolvableError,MalformedCodeNavigationResponseError,CodeNavigationTargetNotFoundError,CodeNavigationFileNotFoundError,CodeNavigationVersionNotFoundError,CodeNavigationValidationError,CodeNavigationFeatureFlagRequiredError,CodeNavigationNetworkError,CodeNavigationBackendError,DEFAULT_MCP_URL,DEFAULT_API_URL,DEFAULT_CODE_NAV_URL,getCodeNavigationUrl,PackageIntelligenceAccessError,PackageIntelligenceFeatureFlagRequiredError,PackageIntelligenceNetworkError,PackageIntelligenceBackendError,PackageIntelligenceGraphQLError,PackageIntelligenceTargetNotFoundError,PackageIntelligenceValidationError,PackageIntelligenceVersionNotFoundError,MalformedPackageIntelligenceResponseError,PackageIntelligenceChangelogSourceNotFoundError,PKGSEER_REGISTRY_ARGS,PKGSEER_REGISTRY_LIST,toPkgseerRegistry,toPkgseerRegistryLowercase,isKnownPkgseerRegistryArg,getAppConfigDirForEnv,getAuthConfigPathForEnv,getAuthFileStorageDirForEnv,getLegacyAuthStorageDirForEnv,getLegacyMacAuthConfigPathForEnv,getLegacyMacAuthFileStorageDirForEnv,AuthConfigError,parseAuthStorageMode,AuthStorageLockTimeoutError,AuthStoragePolicyError,normalizeBaseUrl,FileSystemServiceImpl,refreshExpiredToken,loadAutoLoginAuthSessionMetadata,clearAutoLoginAuthSessionMetadata,createAuthCommandDependencies,createAuthStatusDependencies,createContainer};
|