@gitlab/duo-cli 8.62.1 → 8.62.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1143,7 +1143,7 @@ ${ePQ(C)}`:""};if(typeof Q==="string"){let E=B?`
1143
1143
  ${D(B)}`:"";this.#E(`${Q}${E}${I(B)}`,A)}else{let E=UA1(Q);if(!E)return;this.#E(`${D(E)}${I(Q)}`,A)}}#E(A,Q){let B=`${XA1.default().format("YYYY-MM-DDTHH:mm:ss:SSS")} [${Q}]: `,D=(I)=>I.replace(/\n/g,`
1144
1144
  ${" ".repeat(tPQ)}`);this.#A.write(`${B}${D(A)}`)}setContext(A){this.#B=A}debug(A,Q){this.#D(AD.DEBUG,A,Q)}info(A,Q){this.#D(AD.INFO,A,Q)}warn(A,Q){this.#D(AD.WARNING,A,Q)}error(A,Q){this.#D(AD.ERROR,A,Q)}withContext(A){let Q=new gw(this.#A,this.#Q);return Q.setContext(A),Q}}gw=G1([zA1.Injectable(T1,[kw,cu])],gw);var s0A=fA(x1(),1);var a0A=fA(x1(),1);var KA1=fA(x1(),1),b4=KA1.createInterfaceId("GitLabApiService");var VA1=fA(iD(),1);function wA1(A){return(A.split(`
1145
1145
  `).find((Q)=>Q.trim())??A.replace(`
1146
- `,"")).trim()}function ASQ(A){return wA1(A).match(/^(query|mutation|subscription)\s+/)?.[1]}function QSQ(A){return wA1(A).match(/(?:query|mutation|subscription)\s+(\w+)/)?.[1]}function vAA(A){let Q=ASQ(A),B=QSQ(A);if(Q)return`${Q}: ${B??"anonymous"}`;return}var BSQ=(A)=>{if(A.method==="GET"||A.method==="HEAD")return;if(!A.body)return;return g2("Body",JSON.stringify(A.body))},DSQ=(A)=>{if(A.method==="POST"||A.method==="PATCH"||A.method==="PUT")return;if(!A.searchParams)return;return g2("Search Params",JSON.stringify(A.searchParams))},ISQ=(A)=>{if(!A.headers)return;return g2("Headers",JSON.stringify(A.headers))},pu=(A)=>{switch(A.type){case"graphql":return AC("GraphQL Request",g2("Query",A.query.replace(/[\s\n]+/g," ").trim()),g2("Variables",JSON.stringify(A.variables)));case"rest":return AC("REST Request",g2("Method",A.method),g2("Path",A.path),ISQ(A),DSQ(A),BSQ(A));default:return g2("Unknown request type",A.type)}};var $A1=(A)=>{try{return JSON.parse(A)?.error}catch{return}},ESQ=(A)=>{if(!A)return"";try{return JSON.parse(A)?.error_description??""}catch{return""}},HXA=(A,Q)=>Boolean(A.status===401&&Q&&$A1(Q)==="invalid_token"),VXA=(A,Q)=>Boolean(A.status===400&&Q&&$A1(Q)==="invalid_grant");class kAA extends Error{request;cause;constructor(A,Q,B){super(A);this.request=Q,this.cause=B?.cause}get sanitizedMessage(){return"API request failed"}}class $XA extends kAA{status;constructor(A,Q,B,D){super(A,Q,D);this.status=B}}class lu extends $XA{type="rest";response;#A;constructor(A,Q,B,D){let I=`Fetching ${B} from ${Q.url} failed. ${ESQ(D)}`;if(HXA(Q,D))I=`Request for ${B} failed because the token is expired or revoked.`;if(VXA(Q,D))I="Request to refresh token failed, because it's revoked or already refreshed.";super(I,A,Q.status);this.response=Q,this.#A=D}isInvalidTokenOrInvalidRefresh(){return HXA(this.response,this.#A)||VXA(this.response,this.#A)}get ctx(){return AC("Error details",pu(this.request),this.#Q())}get sanitizedMessage(){if(HXA(this.response,this.#A))return"Request failed because the token is expired or revoked.";if(VXA(this.response,this.#A))return"Request to refresh token failed, because it's revoked or already refreshed.";return`Request failed with error code: ${this.response.status}`}#Q(){let A=Object.fromEntries(this.response.headers.entries());return AC("Response",g2("Status",String(this.status)),!VA1.default.isEmpty(A)?g2("Headers",JSON.stringify(A)):void 0,this.#A?g2("Response body",this.#A):void 0)}get body(){return this.#A}}var HA1=(A)=>A.errors?.map((Q)=>Q.message).join(",")||"";class WXA extends $XA{type="graphql";graphQlResponse;#A;constructor(A,Q){let B=vAA(A.query),D=`GraphQL request "${B}" failed with ${HA1(Q)}`;super(D,A,Q.status);this.graphQlResponse=Q,this.#A=B}get sanitizedMessage(){return`GraphQL request "${this.#A}" failed with status ${this.graphQlResponse.status}`}get ctx(){return AC("Error details",pu(this.request),this.#Q())}#Q(){return AC("Response",g2("Status",String(this.graphQlResponse.status)),g2("Errors",HA1(this.graphQlResponse)))}}class gAA extends kAA{type="network";cause;constructor(A,Q){let B=Q instanceof Error?Q.message:`Network error occurred: ${Q}`;super(B,A);this.cause=Q}get ctx(){return AC("Error details",pu(this.request),this.#A())}get sanitizedMessage(){let A=this.cause,Q=A?.code||A?.errno,B=this.#Q(Q);return`Network error occurred${B?`: ${B}`:""}`}#A(){if(!this.cause||!(this.cause instanceof Error))return;let A=this.cause;if(A.code||A.errno){let Q=A.code||A.errno,B=this.#Q(Q),D=B?`${B} (${Q})`:`Error code: ${Q}`;return g2("Network issue",D)}return}#Q(A){return{ENOTFOUND:"DNS lookup failed - hostname could not be resolved",ECONNREFUSED:"Connection refused - server is not accepting connections",ECONNRESET:"Connection reset by peer - server closed the connection unexpectedly",ETIMEDOUT:"Connection timed out - server did not respond in time",EHOSTUNREACH:"Host unreachable - network route to server not available",ENETUNREACH:"Network unreachable - no network connectivity",ECONNABORTED:"Connection aborted - request was cancelled",EBADF:"Bad file descriptor - network connection issue",EPIPE:"Broken pipe - connection closed while writing data",EAI_AGAIN:"DNS lookup failed temporarily - try again later"}[A]}}class CSQ extends kAA{type="timeout";#A;constructor(A,Q){let B=`Request timed out${Q?` after ${Q}ms`:""}`;super(B,A);this.#A=B}get ctx(){return AC("Error details",pu(this.request))}get sanitizedMessage(){return this.#A}}var WA1=lu;function bAA(A){return A instanceof lu}var iu={type:"rest",method:"GET",path:"/api/v4/version"};var NA1=(A)=>bAA(A)&&(A.status<400||A.status>=500);var fAA=JSON;var MA1=(A)=>A.toUpperCase(),qA1=(A)=>{let Q={};return A.forEach((B,D)=>{Q[D]=B}),Q};var OA1=(A,Q,B)=>{return A.document?A:{document:A,variables:Q,requestHeaders:B,signal:void 0}},LA1=(A,Q,B)=>{return A.query?A:{query:A,variables:Q,requestHeaders:B,signal:void 0}},_A1=(A,Q)=>{return A.documents?A:{documents:A,requestHeaders:Q,signal:void 0}};var g1A=fA($81(),1),W81=(A)=>{let Q=void 0,B=A.definitions.filter((D)=>D.kind==="OperationDefinition");if(B.length===1)Q=B[0]?.name?.value;return Q},dL=(A)=>{if(typeof A==="string"){let B=void 0;try{let D=g1A.parse(A);B=W81(D)}catch(D){}return{query:A,operationName:B}}let Q=W81(A);return{query:g1A.print(A),operationName:Q}};class OF extends Error{constructor(A,Q){let B=`${OF.extractMessage(A)}: ${JSON.stringify({response:A,request:Q})}`;super(B);if(Object.setPrototypeOf(this,OF.prototype),this.response=A,this.request=Q,typeof Error.captureStackTrace==="function")Error.captureStackTrace(this,OF)}static extractMessage(A){return A.errors?.[0]?.message??`GraphQL Error (Code: ${A.status})`}}var vW=fA(Y21(),1);var xiQ="connection_init",hiQ="connection_ack",U21="ping",X21="pong",miQ="subscribe",uiQ="next",diQ="error",z21="complete";class yW{get type(){return this._type}get id(){return this._id}get payload(){return this._payload}constructor(A,Q,B){this._type=A,this._payload=Q,this._id=B}get text(){let A={type:this.type};if(this.id!=null&&this.id!=null)A.id=this.id;if(this.payload!=null&&this.payload!=null)A.payload=this.payload;return JSON.stringify(A)}static parse(A,Q){let{type:B,payload:D,id:I}=JSON.parse(A);return new yW(B,Q(D),I)}}class EKA{constructor(A,{onInit:Q,onAcknowledged:B,onPing:D,onPong:I}){this.socketState={acknowledged:!1,lastRequestId:0,subscriptions:{}},this.socket=A,A.addEventListener("open",async(E)=>{this.socketState.acknowledged=!1,this.socketState.subscriptions={},A.send(piQ(Q?await Q():null).text)}),A.addEventListener("close",(E)=>{this.socketState.acknowledged=!1,this.socketState.subscriptions={}}),A.addEventListener("error",(E)=>{console.error(E)}),A.addEventListener("message",(E)=>{try{let C=ciQ(E.data);switch(C.type){case hiQ:{if(this.socketState.acknowledged)console.warn("Duplicate CONNECTION_ACK message ignored");else if(this.socketState.acknowledged=!0,B)B(C.payload);return}case U21:{if(D)D(C.payload).then((G)=>A.send(G21(G).text));else A.send(G21(null).text);return}case X21:{if(I)I(C.payload);return}}if(!this.socketState.acknowledged)return;if(C.id===void 0||C.id===null||!this.socketState.subscriptions[C.id])return;let{query:F,variables:J,subscriber:Y}=this.socketState.subscriptions[C.id];switch(C.type){case uiQ:{if(!C.payload.errors&&C.payload.data)Y.next&&Y.next(C.payload.data);if(C.payload.errors)Y.error&&Y.error(new OF({...C.payload,status:200},{query:F,variables:J}));return}case diQ:{Y.error&&Y.error(new OF({errors:C.payload,status:200},{query:F,variables:J}));return}case z21:{Y.complete&&Y.complete(),delete this.socketState.subscriptions[C.id];return}}}catch(C){console.error(C),A.close(1006)}A.close(4400,"Unknown graphql-ws message.")})}makeSubscribe(A,Q,B,D){let I=(this.socketState.lastRequestId++).toString();return this.socketState.subscriptions[I]={query:A,variables:D,subscriber:B},this.socket.send(iiQ(I,{query:A,operationName:Q,variables:D}).text),()=>{this.socket.send(aiQ(I).text),delete this.socketState.subscriptions[I]}}rawRequest(A,Q){return new Promise((B,D)=>{let I;this.rawSubscribe(A,{next:(E,C)=>I={data:E,extensions:C},error:D,complete:()=>B(I)},Q)})}request(A,Q){return new Promise((B,D)=>{let I;this.subscribe(A,{next:(E)=>I=E,error:D,complete:()=>B(I)},Q)})}subscribe(A,Q,B){let{query:D,operationName:I}=dL(A);return this.makeSubscribe(D,I,Q,B)}rawSubscribe(A,Q,B){return this.makeSubscribe(A,void 0,Q,B)}ping(A){this.socket.send(liQ(A).text)}close(){this.socket.close(1000)}}EKA.PROTOCOL="graphql-transport-ws";function ciQ(A,Q=(B)=>B){return yW.parse(A,Q)}function piQ(A){return new yW(xiQ,A)}function liQ(A){return new yW(U21,A,void 0)}function G21(A){return new yW(X21,A,void 0)}function iiQ(A,Q){return new yW(miQ,Q,A)}function aiQ(A){return new yW(z21,void 0,A)}var jy=(A)=>{let Q={};if(A)if(typeof Headers<"u"&&A instanceof Headers||vW&&vW.Headers&&A instanceof vW.Headers)Q=qA1(A);else if(Array.isArray(A))A.forEach(([B,D])=>{if(B&&D!==void 0)Q[B]=D});else Q=A;return Q},Z21=(A)=>A.replace(/([\s,]|#[^\n\r]+)+/g," ").trim(),niQ=(A)=>{if(!Array.isArray(A.query)){let D=A,I=[`query=${encodeURIComponent(Z21(D.query))}`];if(A.variables)I.push(`variables=${encodeURIComponent(D.jsonSerializer.stringify(D.variables))}`);if(D.operationName)I.push(`operationName=${encodeURIComponent(D.operationName)}`);return I.join("&")}if(typeof A.variables<"u"&&!Array.isArray(A.variables))throw Error("Cannot create query with given variable type, array expected");let Q=A,B=A.query.reduce((D,I,E)=>{return D.push({query:Z21(I),variables:Q.variables?Q.jsonSerializer.stringify(Q.variables[E]):void 0}),D},[]);return`query=${encodeURIComponent(Q.jsonSerializer.stringify(B))}`},oiQ=(A)=>async(Q)=>{let{url:B,query:D,variables:I,operationName:E,fetch:C,fetchOptions:F,middleware:J}=Q,Y={...Q.headers},G="",X=void 0;if(A==="POST"){if(X=riQ(D,I,E,F.jsonSerializer),typeof X==="string")Y["Content-Type"]="application/json"}else G=niQ({query:D,variables:I,operationName:E,jsonSerializer:F.jsonSerializer??fAA});let z={method:A,headers:Y,body:X,...F},U=B,Z=z;if(J){let K=await Promise.resolve(J({...z,url:B,operationName:E,variables:I})),{url:H,...W}=K;U=H,Z=W}if(G)U=`${U}?${G}`;return await C(U,Z)};class JKA{constructor(A,Q={}){this.url=A,this.requestConfig=Q,this.rawRequest=async(...B)=>{let[D,I,E]=B,C=LA1(D,I,E),{headers:F,fetch:J=vW.default,method:Y="POST",requestMiddleware:G,responseMiddleware:X,...z}=this.requestConfig,{url:U}=this;if(C.signal!==void 0)z.signal=C.signal;let{operationName:Z}=dL(C.query);return CKA({url:U,query:C.query,variables:C.variables,headers:{...jy(FKA(F)),...jy(C.requestHeaders)},operationName:Z,fetch:J,method:Y,fetchOptions:z,middleware:G}).then((K)=>{if(X)X(K);return K}).catch((K)=>{if(X)X(K);throw K})}}async request(A,...Q){let[B,D]=Q,I=OA1(A,B,D),{headers:E,fetch:C=vW.default,method:F="POST",requestMiddleware:J,responseMiddleware:Y,...G}=this.requestConfig,{url:X}=this;if(I.signal!==void 0)G.signal=I.signal;let{query:z,operationName:U}=dL(I.document);return CKA({url:X,query:z,variables:I.variables,headers:{...jy(FKA(E)),...jy(I.requestHeaders)},operationName:U,fetch:C,method:F,fetchOptions:G,middleware:J}).then((Z)=>{if(Y)Y(Z);return Z.data}).catch((Z)=>{if(Y)Y(Z);throw Z})}batchRequests(A,Q){let B=_A1(A,Q),{headers:D,...I}=this.requestConfig;if(B.signal!==void 0)I.signal=B.signal;let E=B.documents.map(({document:F})=>dL(F).query),C=B.documents.map(({variables:F})=>F);return CKA({url:this.url,query:E,variables:C,headers:{...jy(FKA(D)),...jy(B.requestHeaders)},operationName:void 0,fetch:this.requestConfig.fetch??vW.default,method:this.requestConfig.method||"POST",fetchOptions:I,middleware:this.requestConfig.requestMiddleware}).then((F)=>{if(this.requestConfig.responseMiddleware)this.requestConfig.responseMiddleware(F);return F.data}).catch((F)=>{if(this.requestConfig.responseMiddleware)this.requestConfig.responseMiddleware(F);throw F})}setHeaders(A){return this.requestConfig.headers=A,this}setHeader(A,Q){let{headers:B}=this.requestConfig;if(B)B[A]=Q;else this.requestConfig.headers={[A]:Q};return this}setEndpoint(A){return this.url=A,this}}var CKA=async(A)=>{let{query:Q,variables:B,fetchOptions:D}=A,I=oiQ(MA1(A.method??"post")),E=Array.isArray(A.query),C=await I(A),F=await siQ(C,D.jsonSerializer??fAA),J=Array.isArray(F)?!F.some(({data:G})=>!G):Boolean(F.data),Y=Array.isArray(F)||!F.errors||Array.isArray(F.errors)&&!F.errors.length||D.errorPolicy==="all"||D.errorPolicy==="ignore";if(C.ok&&Y&&J){let{errors:G,...X}=Array.isArray(F)?F:F,z=D.errorPolicy==="ignore"?X:F;return{...E?{data:z}:z,headers:C.headers,status:C.status}}else throw new OF({...typeof F==="string"?{error:F}:F,status:C.status,headers:C.headers},{query:Q,variables:B})};var riQ=(A,Q,B,D)=>{let I=D??fAA;if(!Array.isArray(A))return I.stringify({query:A,variables:Q,operationName:B});if(typeof Q<"u"&&!Array.isArray(Q))throw Error("Cannot create request body with given variable type, array expected");let E=A.reduce((C,F,J)=>{return C.push({query:F,variables:Q?Q[J]:void 0}),C},[]);return I.stringify(E)},siQ=async(A,Q)=>{let B;if(A.headers.forEach((D,I)=>{if(I.toLowerCase()==="content-type")B=D}),B&&(B.toLowerCase().startsWith("application/json")||B.toLowerCase().startsWith("application/graphql+json")||B.toLowerCase().startsWith("application/graphql-response+json")))return Q.parse(await A.text());else return A.text()},FKA=(A)=>{return typeof A==="function"?A():A},xz=(A,...Q)=>{return A.reduce((B,D,I)=>`${B}${D}${I in Q?String(Q[I]):""}`,"")};var K21=async(A,Q,B)=>{if(!Q.ok){let D=await Q.text().catch(()=>{return});throw new WA1(A,Q,B,D)}};function A2(){return"8.62.1"}var w21=(A)=>{let Q=A?`${A?.name}:${A?.version}`:"missing client info";return`gitlab-language-server:${A2()} (${Q})`};function H21(A){return A!==null&&A!==void 0}var YKA=(A,Q)=>{return Object.entries(Q).forEach(([B,D])=>{if(H21(D))A.searchParams.append(B,String(D))}),A},d1A=(A)=>A.toString().replace(/\/?$/,"/"),Py=(A)=>A.replace(/^\.?\/?/,"./"),V21=(A)=>{if(A.startsWith("git@")){let Q=A.match(/git@([^:]+):(.+)/);if(Q){let[,B,D]=Q;return`https://${B}/${D}`}}if(A.startsWith("git://"))return A.replace("git://","https://");if(A.startsWith("ssh://"))return A.replace("ssh://","https://").replace(/git@([^/]+)/,"$1");return A};var tiQ=(A)=>A.split("/").pop()||"unknown resource";class GKA{#A;#Q;#B;#D;#I;constructor(A,Q,B,D,I){this.#A=A,this.#Q=Q,this.#B=new URL(d1A(D)),this.#D=I,this.#I=B}getDefaultHeaders(){return{Authorization:`Bearer ${this.#D}`,"User-Agent":w21(this.#I),"X-Gitlab-Language-Server-Version":A2()}}async fetchFromApiRaw(A){try{let Q=`Unknown request method "${A.method}", request type "${A.type}"`;switch(A.method){case"GET":return await this.#C(A);case"POST":return await this.#F(A);case"PATCH":return await this.#J(A);case"PUT":return await this.#Y(A);case"HEAD":return await this.#G(A);default:throw Error(Q)}}catch(Q){throw new gAA(A,Q)}}async fetchFromApi(A){if(A.type==="graphql")return this.#E(A);let Q=await this.fetchFromApiRaw(A);return await K21(A,Q,tiQ(A.path)),Q.json()}fetchOperation=(A)=>(Q)=>this.fetchFromApi({...A,signal:Q});async#E(A){let Q=new URL("./api/graphql",this.#B),B=vAA(A.query);if(B)this.#A.debug(`[SimpleApiClient] Making GraphQL request: ${B}`);let D=async(E,C)=>{let F=E instanceof URL?E.toString():E;return this.#Q.post(F,{...C,headers:{...C?.headers},signal:A.signal})},I=new JKA(Q.href,{fetch:D,headers:{...this.getDefaultHeaders()}});try{return await I.request(A.query,A.variables)}catch(E){if(E instanceof OF)throw new WXA(A,E.response);throw new gAA(A,E)}}async#C(A){let Q=Py(A.path),B=new URL(Q,this.#B);return YKA(B,A.searchParams??{}),this.#Q.get(B,{headers:{...this.getDefaultHeaders(),...A.headers},signal:A.signal})}async#F(A){let Q=Py(A.path),B=new URL(Q,this.#B);return this.#Q.post(B,{headers:{"Content-Type":"application/json",...this.getDefaultHeaders(),...A.headers},body:JSON.stringify(A.body),signal:A.signal})}async#J(A){let Q=Py(A.path),B=new URL(Q,this.#B);return this.#Q.patch(B,{headers:{"Content-Type":"application/json",...this.getDefaultHeaders(),...A.headers},body:JSON.stringify(A.body),signal:A.signal})}async#Y(A){let Q=Py(A.path),B=new URL(Q,this.#B);return this.#Q.put(B,{headers:{"Content-Type":"application/json",...this.getDefaultHeaders(),...A.headers},body:JSON.stringify(A.body),signal:A.signal})}async#G(A){let Q=Py(A.path),B=new URL(Q,this.#B);return YKA(B,A.searchParams??{}),this.#Q.head(B,{headers:{...this.getDefaultHeaders(),...A.headers},signal:A.signal})}}var $21="api",W21=(A)=>{if(!(A instanceof lu)||!A.isInvalidTokenOrInvalidRefresh())return{valid:!1,reason:"unknown",message:`Token validation failed: ${A}`};return{valid:!1,reason:"invalid_token",message:"Token is invalid or expired."}},N21=(A)=>{if(A.includes($21))return;return{valid:!1,reason:"invalid_scopes",message:`Token has scope(s) ${A.map((B)=>`'${B}'`).join(", ")} (needs ${$21}).`}};async function eiQ(A,Q){let B={type:"rest",method:"GET",path:"/api/v4/personal_access_tokens/self"},{scopes:D}=await A.fetchFromApi(B),I=N21(D);if(I)return I;return{valid:!0,tokenInfo:{scopes:D,type:"pat",token:Q}}}async function AaQ(A,Q){let B={type:"rest",method:"GET",path:"/oauth/token/info"},{scope:D}=await A.fetchFromApi(B),I=N21(D);if(I)return I;return{valid:!0,tokenInfo:{scopes:D,type:"oauth",token:Q}}}async function M21(A,Q){if(!Q)return{valid:!1,message:"No token provided",reason:"invalid_token"};let B=await Promise.all([eiQ(A,Q).catch(W21),AaQ(A,Q).catch(W21)]),D=B.find((F)=>F.valid);if(D)return D;let I=B.filter((F)=>!F.valid),E=I.find((F)=>F.reason==="invalid_scopes");if(E)return E;let C=I.find((F)=>F.reason==="invalid_token");if(C)return C;return B[0]}var c1A=fA(x1(),1);var UKA=c1A.createInterfaceId("ProjectService");class md{#A;#Q;constructor(A,Q){this.#A=Q,this.#Q=y1(A,"[ProjectService]")}async getProjectFromPathWithNamespace(A){return this.#Q.debug(`Fetching details for project: ${A}`),this.#A.fetchFromApi({type:"rest",method:"GET",path:`/api/v4/projects/${encodeURIComponent(A)}`})}async getProjectIdsFromPaths(A){return(await this.#A.fetchFromApi({type:"graphql",query:xz`
1146
+ `,"")).trim()}function ASQ(A){return wA1(A).match(/^(query|mutation|subscription)\s+/)?.[1]}function QSQ(A){return wA1(A).match(/(?:query|mutation|subscription)\s+(\w+)/)?.[1]}function vAA(A){let Q=ASQ(A),B=QSQ(A);if(Q)return`${Q}: ${B??"anonymous"}`;return}var BSQ=(A)=>{if(A.method==="GET"||A.method==="HEAD")return;if(!A.body)return;return g2("Body",JSON.stringify(A.body))},DSQ=(A)=>{if(A.method==="POST"||A.method==="PATCH"||A.method==="PUT")return;if(!A.searchParams)return;return g2("Search Params",JSON.stringify(A.searchParams))},ISQ=(A)=>{if(!A.headers)return;return g2("Headers",JSON.stringify(A.headers))},pu=(A)=>{switch(A.type){case"graphql":return AC("GraphQL Request",g2("Query",A.query.replace(/[\s\n]+/g," ").trim()),g2("Variables",JSON.stringify(A.variables)));case"rest":return AC("REST Request",g2("Method",A.method),g2("Path",A.path),ISQ(A),DSQ(A),BSQ(A));default:return g2("Unknown request type",A.type)}};var $A1=(A)=>{try{return JSON.parse(A)?.error}catch{return}},ESQ=(A)=>{if(!A)return"";try{return JSON.parse(A)?.error_description??""}catch{return""}},HXA=(A,Q)=>Boolean(A.status===401&&Q&&$A1(Q)==="invalid_token"),VXA=(A,Q)=>Boolean(A.status===400&&Q&&$A1(Q)==="invalid_grant");class kAA extends Error{request;cause;constructor(A,Q,B){super(A);this.request=Q,this.cause=B?.cause}get sanitizedMessage(){return"API request failed"}}class $XA extends kAA{status;constructor(A,Q,B,D){super(A,Q,D);this.status=B}}class lu extends $XA{type="rest";response;#A;constructor(A,Q,B,D){let I=`Fetching ${B} from ${Q.url} failed. ${ESQ(D)}`;if(HXA(Q,D))I=`Request for ${B} failed because the token is expired or revoked.`;if(VXA(Q,D))I="Request to refresh token failed, because it's revoked or already refreshed.";super(I,A,Q.status);this.response=Q,this.#A=D}isInvalidTokenOrInvalidRefresh(){return HXA(this.response,this.#A)||VXA(this.response,this.#A)}get ctx(){return AC("Error details",pu(this.request),this.#Q())}get sanitizedMessage(){if(HXA(this.response,this.#A))return"Request failed because the token is expired or revoked.";if(VXA(this.response,this.#A))return"Request to refresh token failed, because it's revoked or already refreshed.";return`Request failed with error code: ${this.response.status}`}#Q(){let A=Object.fromEntries(this.response.headers.entries());return AC("Response",g2("Status",String(this.status)),!VA1.default.isEmpty(A)?g2("Headers",JSON.stringify(A)):void 0,this.#A?g2("Response body",this.#A):void 0)}get body(){return this.#A}}var HA1=(A)=>A.errors?.map((Q)=>Q.message).join(",")||"";class WXA extends $XA{type="graphql";graphQlResponse;#A;constructor(A,Q){let B=vAA(A.query),D=`GraphQL request "${B}" failed with ${HA1(Q)}`;super(D,A,Q.status);this.graphQlResponse=Q,this.#A=B}get sanitizedMessage(){return`GraphQL request "${this.#A}" failed with status ${this.graphQlResponse.status}`}get ctx(){return AC("Error details",pu(this.request),this.#Q())}#Q(){return AC("Response",g2("Status",String(this.graphQlResponse.status)),g2("Errors",HA1(this.graphQlResponse)))}}class gAA extends kAA{type="network";cause;constructor(A,Q){let B=Q instanceof Error?Q.message:`Network error occurred: ${Q}`;super(B,A);this.cause=Q}get ctx(){return AC("Error details",pu(this.request),this.#A())}get sanitizedMessage(){let A=this.cause,Q=A?.code||A?.errno,B=this.#Q(Q);return`Network error occurred${B?`: ${B}`:""}`}#A(){if(!this.cause||!(this.cause instanceof Error))return;let A=this.cause;if(A.code||A.errno){let Q=A.code||A.errno,B=this.#Q(Q),D=B?`${B} (${Q})`:`Error code: ${Q}`;return g2("Network issue",D)}return}#Q(A){return{ENOTFOUND:"DNS lookup failed - hostname could not be resolved",ECONNREFUSED:"Connection refused - server is not accepting connections",ECONNRESET:"Connection reset by peer - server closed the connection unexpectedly",ETIMEDOUT:"Connection timed out - server did not respond in time",EHOSTUNREACH:"Host unreachable - network route to server not available",ENETUNREACH:"Network unreachable - no network connectivity",ECONNABORTED:"Connection aborted - request was cancelled",EBADF:"Bad file descriptor - network connection issue",EPIPE:"Broken pipe - connection closed while writing data",EAI_AGAIN:"DNS lookup failed temporarily - try again later"}[A]}}class CSQ extends kAA{type="timeout";#A;constructor(A,Q){let B=`Request timed out${Q?` after ${Q}ms`:""}`;super(B,A);this.#A=B}get ctx(){return AC("Error details",pu(this.request))}get sanitizedMessage(){return this.#A}}var WA1=lu;function bAA(A){return A instanceof lu}var iu={type:"rest",method:"GET",path:"/api/v4/version"};var NA1=(A)=>bAA(A)&&(A.status<400||A.status>=500);var fAA=JSON;var MA1=(A)=>A.toUpperCase(),qA1=(A)=>{let Q={};return A.forEach((B,D)=>{Q[D]=B}),Q};var OA1=(A,Q,B)=>{return A.document?A:{document:A,variables:Q,requestHeaders:B,signal:void 0}},LA1=(A,Q,B)=>{return A.query?A:{query:A,variables:Q,requestHeaders:B,signal:void 0}},_A1=(A,Q)=>{return A.documents?A:{documents:A,requestHeaders:Q,signal:void 0}};var g1A=fA($81(),1),W81=(A)=>{let Q=void 0,B=A.definitions.filter((D)=>D.kind==="OperationDefinition");if(B.length===1)Q=B[0]?.name?.value;return Q},dL=(A)=>{if(typeof A==="string"){let B=void 0;try{let D=g1A.parse(A);B=W81(D)}catch(D){}return{query:A,operationName:B}}let Q=W81(A);return{query:g1A.print(A),operationName:Q}};class OF extends Error{constructor(A,Q){let B=`${OF.extractMessage(A)}: ${JSON.stringify({response:A,request:Q})}`;super(B);if(Object.setPrototypeOf(this,OF.prototype),this.response=A,this.request=Q,typeof Error.captureStackTrace==="function")Error.captureStackTrace(this,OF)}static extractMessage(A){return A.errors?.[0]?.message??`GraphQL Error (Code: ${A.status})`}}var vW=fA(Y21(),1);var xiQ="connection_init",hiQ="connection_ack",U21="ping",X21="pong",miQ="subscribe",uiQ="next",diQ="error",z21="complete";class yW{get type(){return this._type}get id(){return this._id}get payload(){return this._payload}constructor(A,Q,B){this._type=A,this._payload=Q,this._id=B}get text(){let A={type:this.type};if(this.id!=null&&this.id!=null)A.id=this.id;if(this.payload!=null&&this.payload!=null)A.payload=this.payload;return JSON.stringify(A)}static parse(A,Q){let{type:B,payload:D,id:I}=JSON.parse(A);return new yW(B,Q(D),I)}}class EKA{constructor(A,{onInit:Q,onAcknowledged:B,onPing:D,onPong:I}){this.socketState={acknowledged:!1,lastRequestId:0,subscriptions:{}},this.socket=A,A.addEventListener("open",async(E)=>{this.socketState.acknowledged=!1,this.socketState.subscriptions={},A.send(piQ(Q?await Q():null).text)}),A.addEventListener("close",(E)=>{this.socketState.acknowledged=!1,this.socketState.subscriptions={}}),A.addEventListener("error",(E)=>{console.error(E)}),A.addEventListener("message",(E)=>{try{let C=ciQ(E.data);switch(C.type){case hiQ:{if(this.socketState.acknowledged)console.warn("Duplicate CONNECTION_ACK message ignored");else if(this.socketState.acknowledged=!0,B)B(C.payload);return}case U21:{if(D)D(C.payload).then((G)=>A.send(G21(G).text));else A.send(G21(null).text);return}case X21:{if(I)I(C.payload);return}}if(!this.socketState.acknowledged)return;if(C.id===void 0||C.id===null||!this.socketState.subscriptions[C.id])return;let{query:F,variables:J,subscriber:Y}=this.socketState.subscriptions[C.id];switch(C.type){case uiQ:{if(!C.payload.errors&&C.payload.data)Y.next&&Y.next(C.payload.data);if(C.payload.errors)Y.error&&Y.error(new OF({...C.payload,status:200},{query:F,variables:J}));return}case diQ:{Y.error&&Y.error(new OF({errors:C.payload,status:200},{query:F,variables:J}));return}case z21:{Y.complete&&Y.complete(),delete this.socketState.subscriptions[C.id];return}}}catch(C){console.error(C),A.close(1006)}A.close(4400,"Unknown graphql-ws message.")})}makeSubscribe(A,Q,B,D){let I=(this.socketState.lastRequestId++).toString();return this.socketState.subscriptions[I]={query:A,variables:D,subscriber:B},this.socket.send(iiQ(I,{query:A,operationName:Q,variables:D}).text),()=>{this.socket.send(aiQ(I).text),delete this.socketState.subscriptions[I]}}rawRequest(A,Q){return new Promise((B,D)=>{let I;this.rawSubscribe(A,{next:(E,C)=>I={data:E,extensions:C},error:D,complete:()=>B(I)},Q)})}request(A,Q){return new Promise((B,D)=>{let I;this.subscribe(A,{next:(E)=>I=E,error:D,complete:()=>B(I)},Q)})}subscribe(A,Q,B){let{query:D,operationName:I}=dL(A);return this.makeSubscribe(D,I,Q,B)}rawSubscribe(A,Q,B){return this.makeSubscribe(A,void 0,Q,B)}ping(A){this.socket.send(liQ(A).text)}close(){this.socket.close(1000)}}EKA.PROTOCOL="graphql-transport-ws";function ciQ(A,Q=(B)=>B){return yW.parse(A,Q)}function piQ(A){return new yW(xiQ,A)}function liQ(A){return new yW(U21,A,void 0)}function G21(A){return new yW(X21,A,void 0)}function iiQ(A,Q){return new yW(miQ,Q,A)}function aiQ(A){return new yW(z21,void 0,A)}var jy=(A)=>{let Q={};if(A)if(typeof Headers<"u"&&A instanceof Headers||vW&&vW.Headers&&A instanceof vW.Headers)Q=qA1(A);else if(Array.isArray(A))A.forEach(([B,D])=>{if(B&&D!==void 0)Q[B]=D});else Q=A;return Q},Z21=(A)=>A.replace(/([\s,]|#[^\n\r]+)+/g," ").trim(),niQ=(A)=>{if(!Array.isArray(A.query)){let D=A,I=[`query=${encodeURIComponent(Z21(D.query))}`];if(A.variables)I.push(`variables=${encodeURIComponent(D.jsonSerializer.stringify(D.variables))}`);if(D.operationName)I.push(`operationName=${encodeURIComponent(D.operationName)}`);return I.join("&")}if(typeof A.variables<"u"&&!Array.isArray(A.variables))throw Error("Cannot create query with given variable type, array expected");let Q=A,B=A.query.reduce((D,I,E)=>{return D.push({query:Z21(I),variables:Q.variables?Q.jsonSerializer.stringify(Q.variables[E]):void 0}),D},[]);return`query=${encodeURIComponent(Q.jsonSerializer.stringify(B))}`},oiQ=(A)=>async(Q)=>{let{url:B,query:D,variables:I,operationName:E,fetch:C,fetchOptions:F,middleware:J}=Q,Y={...Q.headers},G="",X=void 0;if(A==="POST"){if(X=riQ(D,I,E,F.jsonSerializer),typeof X==="string")Y["Content-Type"]="application/json"}else G=niQ({query:D,variables:I,operationName:E,jsonSerializer:F.jsonSerializer??fAA});let z={method:A,headers:Y,body:X,...F},U=B,Z=z;if(J){let K=await Promise.resolve(J({...z,url:B,operationName:E,variables:I})),{url:H,...W}=K;U=H,Z=W}if(G)U=`${U}?${G}`;return await C(U,Z)};class JKA{constructor(A,Q={}){this.url=A,this.requestConfig=Q,this.rawRequest=async(...B)=>{let[D,I,E]=B,C=LA1(D,I,E),{headers:F,fetch:J=vW.default,method:Y="POST",requestMiddleware:G,responseMiddleware:X,...z}=this.requestConfig,{url:U}=this;if(C.signal!==void 0)z.signal=C.signal;let{operationName:Z}=dL(C.query);return CKA({url:U,query:C.query,variables:C.variables,headers:{...jy(FKA(F)),...jy(C.requestHeaders)},operationName:Z,fetch:J,method:Y,fetchOptions:z,middleware:G}).then((K)=>{if(X)X(K);return K}).catch((K)=>{if(X)X(K);throw K})}}async request(A,...Q){let[B,D]=Q,I=OA1(A,B,D),{headers:E,fetch:C=vW.default,method:F="POST",requestMiddleware:J,responseMiddleware:Y,...G}=this.requestConfig,{url:X}=this;if(I.signal!==void 0)G.signal=I.signal;let{query:z,operationName:U}=dL(I.document);return CKA({url:X,query:z,variables:I.variables,headers:{...jy(FKA(E)),...jy(I.requestHeaders)},operationName:U,fetch:C,method:F,fetchOptions:G,middleware:J}).then((Z)=>{if(Y)Y(Z);return Z.data}).catch((Z)=>{if(Y)Y(Z);throw Z})}batchRequests(A,Q){let B=_A1(A,Q),{headers:D,...I}=this.requestConfig;if(B.signal!==void 0)I.signal=B.signal;let E=B.documents.map(({document:F})=>dL(F).query),C=B.documents.map(({variables:F})=>F);return CKA({url:this.url,query:E,variables:C,headers:{...jy(FKA(D)),...jy(B.requestHeaders)},operationName:void 0,fetch:this.requestConfig.fetch??vW.default,method:this.requestConfig.method||"POST",fetchOptions:I,middleware:this.requestConfig.requestMiddleware}).then((F)=>{if(this.requestConfig.responseMiddleware)this.requestConfig.responseMiddleware(F);return F.data}).catch((F)=>{if(this.requestConfig.responseMiddleware)this.requestConfig.responseMiddleware(F);throw F})}setHeaders(A){return this.requestConfig.headers=A,this}setHeader(A,Q){let{headers:B}=this.requestConfig;if(B)B[A]=Q;else this.requestConfig.headers={[A]:Q};return this}setEndpoint(A){return this.url=A,this}}var CKA=async(A)=>{let{query:Q,variables:B,fetchOptions:D}=A,I=oiQ(MA1(A.method??"post")),E=Array.isArray(A.query),C=await I(A),F=await siQ(C,D.jsonSerializer??fAA),J=Array.isArray(F)?!F.some(({data:G})=>!G):Boolean(F.data),Y=Array.isArray(F)||!F.errors||Array.isArray(F.errors)&&!F.errors.length||D.errorPolicy==="all"||D.errorPolicy==="ignore";if(C.ok&&Y&&J){let{errors:G,...X}=Array.isArray(F)?F:F,z=D.errorPolicy==="ignore"?X:F;return{...E?{data:z}:z,headers:C.headers,status:C.status}}else throw new OF({...typeof F==="string"?{error:F}:F,status:C.status,headers:C.headers},{query:Q,variables:B})};var riQ=(A,Q,B,D)=>{let I=D??fAA;if(!Array.isArray(A))return I.stringify({query:A,variables:Q,operationName:B});if(typeof Q<"u"&&!Array.isArray(Q))throw Error("Cannot create request body with given variable type, array expected");let E=A.reduce((C,F,J)=>{return C.push({query:F,variables:Q?Q[J]:void 0}),C},[]);return I.stringify(E)},siQ=async(A,Q)=>{let B;if(A.headers.forEach((D,I)=>{if(I.toLowerCase()==="content-type")B=D}),B&&(B.toLowerCase().startsWith("application/json")||B.toLowerCase().startsWith("application/graphql+json")||B.toLowerCase().startsWith("application/graphql-response+json")))return Q.parse(await A.text());else return A.text()},FKA=(A)=>{return typeof A==="function"?A():A},xz=(A,...Q)=>{return A.reduce((B,D,I)=>`${B}${D}${I in Q?String(Q[I]):""}`,"")};var K21=async(A,Q,B)=>{if(!Q.ok){let D=await Q.text().catch(()=>{return});throw new WA1(A,Q,B,D)}};function A2(){return"8.62.2"}var w21=(A)=>{let Q=A?`${A?.name}:${A?.version}`:"missing client info";return`gitlab-language-server:${A2()} (${Q})`};function H21(A){return A!==null&&A!==void 0}var YKA=(A,Q)=>{return Object.entries(Q).forEach(([B,D])=>{if(H21(D))A.searchParams.append(B,String(D))}),A},d1A=(A)=>A.toString().replace(/\/?$/,"/"),Py=(A)=>A.replace(/^\.?\/?/,"./"),V21=(A)=>{if(A.startsWith("git@")){let Q=A.match(/git@([^:]+):(.+)/);if(Q){let[,B,D]=Q;return`https://${B}/${D}`}}if(A.startsWith("git://"))return A.replace("git://","https://");if(A.startsWith("ssh://"))return A.replace("ssh://","https://").replace(/git@([^/]+)/,"$1");return A};var tiQ=(A)=>A.split("/").pop()||"unknown resource";class GKA{#A;#Q;#B;#D;#I;constructor(A,Q,B,D,I){this.#A=A,this.#Q=Q,this.#B=new URL(d1A(D)),this.#D=I,this.#I=B}getDefaultHeaders(){return{Authorization:`Bearer ${this.#D}`,"User-Agent":w21(this.#I),"X-Gitlab-Language-Server-Version":A2()}}async fetchFromApiRaw(A){try{let Q=`Unknown request method "${A.method}", request type "${A.type}"`;switch(A.method){case"GET":return await this.#C(A);case"POST":return await this.#F(A);case"PATCH":return await this.#J(A);case"PUT":return await this.#Y(A);case"HEAD":return await this.#G(A);default:throw Error(Q)}}catch(Q){throw new gAA(A,Q)}}async fetchFromApi(A){if(A.type==="graphql")return this.#E(A);let Q=await this.fetchFromApiRaw(A);return await K21(A,Q,tiQ(A.path)),Q.json()}fetchOperation=(A)=>(Q)=>this.fetchFromApi({...A,signal:Q});async#E(A){let Q=new URL("./api/graphql",this.#B),B=vAA(A.query);if(B)this.#A.debug(`[SimpleApiClient] Making GraphQL request: ${B}`);let D=async(E,C)=>{let F=E instanceof URL?E.toString():E;return this.#Q.post(F,{...C,headers:{...C?.headers},signal:A.signal})},I=new JKA(Q.href,{fetch:D,headers:{...this.getDefaultHeaders()}});try{return await I.request(A.query,A.variables)}catch(E){if(E instanceof OF)throw new WXA(A,E.response);throw new gAA(A,E)}}async#C(A){let Q=Py(A.path),B=new URL(Q,this.#B);return YKA(B,A.searchParams??{}),this.#Q.get(B,{headers:{...this.getDefaultHeaders(),...A.headers},signal:A.signal})}async#F(A){let Q=Py(A.path),B=new URL(Q,this.#B);return this.#Q.post(B,{headers:{"Content-Type":"application/json",...this.getDefaultHeaders(),...A.headers},body:JSON.stringify(A.body),signal:A.signal})}async#J(A){let Q=Py(A.path),B=new URL(Q,this.#B);return this.#Q.patch(B,{headers:{"Content-Type":"application/json",...this.getDefaultHeaders(),...A.headers},body:JSON.stringify(A.body),signal:A.signal})}async#Y(A){let Q=Py(A.path),B=new URL(Q,this.#B);return this.#Q.put(B,{headers:{"Content-Type":"application/json",...this.getDefaultHeaders(),...A.headers},body:JSON.stringify(A.body),signal:A.signal})}async#G(A){let Q=Py(A.path),B=new URL(Q,this.#B);return YKA(B,A.searchParams??{}),this.#Q.head(B,{headers:{...this.getDefaultHeaders(),...A.headers},signal:A.signal})}}var $21="api",W21=(A)=>{if(!(A instanceof lu)||!A.isInvalidTokenOrInvalidRefresh())return{valid:!1,reason:"unknown",message:`Token validation failed: ${A}`};return{valid:!1,reason:"invalid_token",message:"Token is invalid or expired."}},N21=(A)=>{if(A.includes($21))return;return{valid:!1,reason:"invalid_scopes",message:`Token has scope(s) ${A.map((B)=>`'${B}'`).join(", ")} (needs ${$21}).`}};async function eiQ(A,Q){let B={type:"rest",method:"GET",path:"/api/v4/personal_access_tokens/self"},{scopes:D}=await A.fetchFromApi(B),I=N21(D);if(I)return I;return{valid:!0,tokenInfo:{scopes:D,type:"pat",token:Q}}}async function AaQ(A,Q){let B={type:"rest",method:"GET",path:"/oauth/token/info"},{scope:D}=await A.fetchFromApi(B),I=N21(D);if(I)return I;return{valid:!0,tokenInfo:{scopes:D,type:"oauth",token:Q}}}async function M21(A,Q){if(!Q)return{valid:!1,message:"No token provided",reason:"invalid_token"};let B=await Promise.all([eiQ(A,Q).catch(W21),AaQ(A,Q).catch(W21)]),D=B.find((F)=>F.valid);if(D)return D;let I=B.filter((F)=>!F.valid),E=I.find((F)=>F.reason==="invalid_scopes");if(E)return E;let C=I.find((F)=>F.reason==="invalid_token");if(C)return C;return B[0]}var c1A=fA(x1(),1);var UKA=c1A.createInterfaceId("ProjectService");class md{#A;#Q;constructor(A,Q){this.#A=Q,this.#Q=y1(A,"[ProjectService]")}async getProjectFromPathWithNamespace(A){return this.#Q.debug(`Fetching details for project: ${A}`),this.#A.fetchFromApi({type:"rest",method:"GET",path:`/api/v4/projects/${encodeURIComponent(A)}`})}async getProjectIdsFromPaths(A){return(await this.#A.fetchFromApi({type:"graphql",query:xz`
1147
1147
  query getProjectIds($fullPaths: [String!]!) {
1148
1148
  projects(fullPaths: $fullPaths) {
1149
1149
  nodes {
@@ -1570,7 +1570,7 @@ Run 'duo config edit' to update your token.`;return this.#I.fire({isInValidState
1570
1570
  `),cursorLine:0,cursorColumn:0}}}class yR{#A;#Q;#B=new lvA;#D;#I;#E;#C;#F;#J;#Y;#G;#U=new ivA;#z=new avA;#X=new nvA;#K;#Z;#$=js1.throttle(()=>this.#q(),500,{leading:!0,trailing:!0});constructor(A,Q,B,D,I,E,C,F){this.#D=y1(A,"[TUIController]"),this.#Y=C,this.#I=Q,this.#E=B,this.#C=D,this.#F=I,this.#J=E,this.#G=F,this.#U.onSubmit=(J)=>this.#S({type:"SEND_PROMPT",prompt:J}),this.#z.onSubmit=(J)=>this.#R(J),this.#U.onStateChange=(J)=>this.#B.setState({...this.#B.getState(),input:J}),this.#z.onStateChange=(J)=>this.#B.setState({...this.#B.getState(),input:J}),this.#X.onStateChange=(J)=>this.#B.setState({...this.#B.getState(),input:J}),this.#X.onCancel=()=>this.#O(),this.#X.onSelect=(J)=>this.#_(J),this.#X.onDelete=(J)=>this.#k(J),this.#X.onQueryChange=(J)=>this.#v(J)}async initialize(A){this.#A=A,this.#B.initialize((Q)=>this.#A?.(Q)),this.#V(),this.#K=this.#w()}async#w(){this.#D.debug(`CLI run config:
1571
1571
  ${G3A(this.#F,this.#E)}`);try{let{backend:A,workspaceFolder:Q,username:B,gitlabRemote:D,sessionId:I}=await this.#C.initialize();if(this.#Q=new X3A(I,A,this.#D),D)this.#B.setState({...this.#B.getState(),gitlabRemoteInfo:{status:"connected",gitlabPath:D.namespaceWithPath,gitlabHost:D.host}});else this.#B.setState({...this.#B.getState(),gitlabRemoteInfo:{status:"error",errorMessage:`Could not find GitLab remote info in workspace ${Q}. Some features might not be available.`}});if(BD(this.#H()),A.preinitialize)BD(A.preinitialize().catch((E)=>{this.#D.warn("Backend pre-initialization failed (non-critical)",E)}));this.#N(B),await this.#W()}catch(A){this.#I.handleError("Duo CLI initialization failed",A),this.#B.setState({...this.#B.getState(),criticalErrorMessage:A instanceof Error?A.message:"Unknown initialization error"}),await this.#G.exit(1)}}async#H(){let A=await this.#Y.checkForUpdate(this.#F.cliVersion);if(A){if(A instanceof Error)this.#D.warn("Failed to check for updates",A);this.#B.setState({...this.#B.getState(),updateInfo:A})}}async#W(){let A=process.env.GLAB_CONFIG_DIR||UZ();if(!A){this.#D.warn("Unable to determine baseDir for prompt history storage, this will be skipped!");return}let Q=n04(A,"duo-cli-prompt-history.json"),B=new CZ(this.#D,Q);try{this.#Z=new ovA(this.#D),await this.#Z?.load(B,this.#F.cwd),this.#D.debug("Loaded prompt history")}catch(D){this.#D.error("Failed to load prompt history",D)}}getCallbacks(){return{onKeyPress:(A)=>{if(A.name==="escape"&&this.#B.getState().isLoading&&this.#Q){this.#D.info("Cancelling stream due to ESC key press"),this.#Q.cancelStream();return}let Q=this.#B.getState().input.inputType,B=A.raw||A.name;if(Q===$7.TEXT)this.#U.handleKeyPress(B,A);else if(Q===$7.CHOICE)this.#z.handleKeyPress(B,A);else if(Q===$7.PROMPT_HISTORY_SEARCH)this.#X.handleKeyPress(B,A)},onSubmit:(A)=>{this.#U.onSubmit(A)},onExit:()=>this.#j(),toggleExpanded:()=>{let A=this.#B.getState();this.#B.setState({...A,expanded:!A.expanded})},onContextSearch:async(A,Q)=>await this.#J?.searchContextItems({category:A,query:Q})??[],onContextItemSelected:async(A)=>{await this.#J?.addSelectedContextItem(A)},onTextChange:async(A)=>{await this.#J?.syncWithTextBuffer(A)},onHistoryPrevious:()=>{if(!this.#Z)return;let A=this.#B.getState(),Q=this.#Z?.handlePrevious(A.input);if(Q)this.#B.setState({...A,input:Q})},onHistoryNext:()=>{if(!this.#Z)return;let A=this.#B.getState(),Q=this.#Z?.handleNext(A.input);if(Q)this.#B.setState({...A,input:Q})},onOpenHistorySearch:()=>this.#y(),onCancelHistorySearch:()=>this.#O(),onHistorySearchQueryChange:(A)=>this.#v(A),onSelectHistoryItem:(A)=>this.#_(A),onDeleteHistoryItem:(A)=>this.#k(A)}}#V(){this.#B.setState({elements:[],isLoading:!1,input:FN,expanded:!1,cwd:this.#F.cwd,gitlabRemoteInfo:{status:"not-checked"}})}#N(A){let Q=this.#B.getState();this.#B.setState({...Q,username:A})}#M(){this.#$.cancel(),this.#q()}#q(){if(!this.#Q)return;this.#B.setState({...this.#B.getState(),elements:[...this.#Q.elements],isLoading:this.#Q.isLoading})}async#R(A){let Q=this.#B.getState();if(Q.isLoading)return;this.#B.setState({...Q,input:FN}),await this.#L(A)}async#S(A){if(this.#B.getState().isLoading||!A.prompt.trim())return;await this.#Z?.add(A.prompt),this.#U.clear(),await this.#L(A)}async#L(A){if(this.#B.setState({...this.#B.getState(),input:FN,isLoading:!0}),await this.#K,!this.#Q)throw Error("Session not initialized");if(A.type==="SEND_PROMPT")this.#Q.addUserMessageAndStartLoading(A.prompt),this.#M();let Q=await this.#P(A),B;for await(let D of this.#Q.sendMessageStream(Q))if(B=D,this.#T(D))this.#$();else this.#M();if(B?.type==="error")this.#I.handleError("Error in message streaming",Error(B.error));if(B?.type==="tool"&&B.state.type==="approval_request"){let D=B,I={type:"SEND_TOOL_APPROVAL",scope:"session",toolId:D.id,toolName:D.name};this.#z.setChoice([{label:"Approve",value:{...I,approved:!0}},{label:"Reject",value:{...I,approved:!1}}])}this.#M()}#T(A){return A.type==="message"&&A.role==="assistant"&&!A.isComplete}async#P(A){if(A.type!=="SEND_PROMPT")return A;let Q=A;try{let B=await this.#J.retrieveContextItemsWithContent({mode:"agentic"});Q.aiContextItems=[...Q.aiContextItems||[],...B||[]],await this.#J.clearSelectedContextItems()}catch(B){this.#D.error("Failed to get AIContextItems for message. Context items will be omitted.",B)}return Q}#j(){BD(this.#G.exit(0))}#y(){if(!this.#Z)return;let A=this.#Z.handleOpenSearch();this.#X.setState(A)}#O(){if(!this.#Z)return;let A=this.#B.getState(),Q=this.#Z.handleCancelSearch();this.#B.setState({...A,input:Q})}#v(A){if(!this.#Z)return;let Q=this.#Z.search(A,10);this.#X.updateSearchResults(A,Q)}#_(A){if(!this.#Z)return;let Q=this.#B.getState(),B=this.#Z.handleSelectItem(A);this.#B.setState({...Q,input:B})}async#k(A){if(!this.#Z)return;let Q=this.#B.getState();if(await this.#Z.remove(A)===-1)return;if(Q.input.inputType===$7.PROMPT_HISTORY_SEARCH){let D=this.#Z.search(Q.input.searchQuery,10);this.#X.updateAfterDelete(D)}}}yR=G1([Z3A.Service({dependencies:[T1,jU,FI,oH,X9,pvA,ryA,cH],lifetime:Z3A.ServiceLifetime.Singleton})],yR);var K3A=fA(x1(),1);class vR{#A;#Q;#B;#D;#I;#E;#C;#F=null;constructor(A,Q,B,D,I,E){this.#Q=y1(A,"[RunController]"),this.#B=Q,this.#D=B,this.#I=D,this.#E=I,this.#C=E}async initialize(){this.#Q.debug(`CLI run config:
1572
1572
  ${G3A(this.#E,this.#D)}`);try{let{backend:A}=await this.#I.initialize();if(this.#A=A,A.preinitialize)try{await A.preinitialize()}catch(Q){this.#Q.warn("Backend pre-initialization failed (non-critical)",Q)}}catch(A){this.#B.handleError("Duo CLI initialization failed",A),await this.#C.exit(1)}}async execute(){if(!this.#A||this.#E.command?.name!=="run")throw Error("Controller not initialized. Call initialize() first.");let{goal:A}=this.#E.command;this.#Q?.info(`Executing workflow: ${JSON.stringify({goal:A},null,4)}`);let Q={id:Date.now().toString(),type:"message",role:"user",content:A,timestamp:Date.now(),isComplete:!0};try{let B;for await(let D of this.#A.sendMessageStream({type:"SEND_PROMPT",prompt:Q.content}))this.#J(D),B=D;if(this.#F)this.#Q?.info(JSON.stringify(this.#F,null,2));await this.#C.exit(B?.type==="ERROR"?1:0)}catch(B){throw this.#Q?.error("Workflow failed:",B instanceof Error?B.message:String(B)),B}}#J(A){switch(A.type){case"TEXT_CHUNK":{if(!this.#F||this.#F.id!==A.messageId){if(this.#F)this.#Q?.info(JSON.stringify(this.#F,null,4));this.#F={id:A.messageId,type:"message",role:"assistant",content:A.content,timestamp:A.timestamp,isComplete:!1}}else this.#F.content+=A.content;break}case"TOOL_START":{this.#Q?.info(`Tool started: ${A.name}`);break}case"TOOL_COMPLETE":{if(this.#Q?.info(`Tool completed: ${A.toolId}`),A.error)this.#Q?.error(`Tool error: ${A.error}`);break}case"TOOL_AWAITING_APPROVAL":break;case"ERROR":{this.#Q?.error(`Error: ${A.message}`);break}default:{let Q=A;this.#Q?.warn(`Unexpected event received: ${JSON.stringify(Q)}`);break}}}}vR=G1([K3A.Service({dependencies:[T1,jU,FI,oH,X9,cH],lifetime:K3A.ServiceLifetime.Singleton})],vR);var o04=()=>{return"production"},rvA,w3A=async()=>{if(!rvA){let A=rL1(),Q=await sL1(),B=A2(),D=o04();rvA={terminalName:A,isKittyProtocolSupported:Q,duoCliVersion:B,environment:D}}return rvA};import{statSync as r04}from"node:fs";import{isAbsolute as s04,normalize as t04,resolve as e04}from"node:path";function Ps1(A,Q=process.cwd()){let B;if(s04(A))B=t04(A);else B=e04(Q,A);return AQ4(B),B}function AQ4(A){try{if(!r04(A).isDirectory())throw new VW(`Path "${A}" exists but is not a directory`)}catch(Q){if(Q instanceof Error&&Q.code==="ENOENT")throw new VW(`Directory "${A}" does not exist`);throw Q}}function Ss1(A){try{let Q=JSON.parse(A);return Array.isArray(Q)?Q.map((D)=>({category:D.Category||D.category,content:D.Content||D.content,metadata:D.metadata||{}})):[]}catch(Q){if(Q instanceof SyntaxError)throw new VW(`Invalid JSON format: ${Q.message}`);throw new VW(`AI Context Item schema error: ${Q}`)}}var ys1=fA(x1(),1);class H3A{#A;constructor(A){this.#A=A}get logLevel(){return this.#A}}class ia extends H3A{constructor(A){super(A.logLevel)}}ia=G1([ys1.Injectable(cu,[X9])],ia);import{existsSync as DQ4,mkdirSync as IQ4,writeFileSync as EQ4}from"node:fs";import{appendFile as CQ4}from"node:fs/promises";import{join as FQ4,sep as JQ4}from"node:path";var tvA=fA(ks1(),1);class evA extends Error{name="TimeoutError";constructor(A,Q){super(A,Q);Error.captureStackTrace?.(this,evA)}}var gs1=(A)=>A.reason??new DOMException("This operation was aborted.","AbortError");function AkA(A,Q){let{milliseconds:B,fallback:D,message:I,customTimers:E={setTimeout,clearTimeout},signal:C}=Q,F,J,G=new Promise((X,z)=>{if(typeof B!=="number"||Math.sign(B)!==1)throw TypeError(`Expected \`milliseconds\` to be a positive number, got \`${B}\``);if(C?.aborted){z(gs1(C));return}if(C)J=()=>{z(gs1(C))},C.addEventListener("abort",J,{once:!0});if(A.then(X,z),B===Number.POSITIVE_INFINITY)return;let U=new evA;F=E.setTimeout.call(void 0,()=>{if(D){try{X(D())}catch(Z){z(Z)}return}if(typeof A.cancel==="function")A.cancel();if(I===!1)X();else if(I instanceof Error)z(I);else U.message=I??`Promise timed out after ${B} milliseconds`,z(U)},B)}).finally(()=>{if(G.clear(),J&&C)C.removeEventListener("abort",J)});return G.clear=()=>{E.clearTimeout.call(void 0,F),F=void 0},G}function QkA(A,Q,B){let D=0,I=A.length;while(I>0){let E=Math.trunc(I/2),C=D+E;if(B(A[C],Q)<=0)D=++C,I-=E+1;else I=E}return D}class $3A{#A=[];enqueue(A,Q){let{priority:B=0,id:D}=Q??{},I={priority:B,id:D,run:A};if(this.size===0||this.#A[this.size-1].priority>=B){this.#A.push(I);return}let E=QkA(this.#A,I,(C,F)=>F.priority-C.priority);this.#A.splice(E,0,I)}setPriority(A,Q){let B=this.#A.findIndex((I)=>I.id===A);if(B===-1)throw ReferenceError(`No promise function with the id "${A}" exists in the queue.`);let[D]=this.#A.splice(B,1);this.enqueue(D.run,{priority:Q,id:A})}dequeue(){return this.#A.shift()?.run}filter(A){return this.#A.filter((Q)=>Q.priority===A.priority).map((Q)=>Q.run)}get size(){return this.#A.length}}class W3A extends tvA.default{#A;#Q;#B=0;#D;#I=!1;#E=!1;#C;#F=0;#J=0;#Y;#G;#U;#z;#X=0;#K;#Z;#$=1n;#w=new Map;timeout;constructor(A){super();if(A={carryoverIntervalCount:!1,intervalCap:Number.POSITIVE_INFINITY,interval:0,concurrency:Number.POSITIVE_INFINITY,autoStart:!0,queueClass:$3A,...A},!(typeof A.intervalCap==="number"&&A.intervalCap>=1))throw TypeError(`Expected \`intervalCap\` to be a number from 1 and up, got \`${A.intervalCap?.toString()??""}\` (${typeof A.intervalCap})`);if(A.interval===void 0||!(Number.isFinite(A.interval)&&A.interval>=0))throw TypeError(`Expected \`interval\` to be a finite number >= 0, got \`${A.interval?.toString()??""}\` (${typeof A.interval})`);if(this.#A=A.carryoverIntervalCount??A.carryoverConcurrencyCount??!1,this.#Q=A.intervalCap===Number.POSITIVE_INFINITY||A.interval===0,this.#D=A.intervalCap,this.#C=A.interval,this.#U=new A.queueClass,this.#z=A.queueClass,this.concurrency=A.concurrency,A.timeout!==void 0&&!(Number.isFinite(A.timeout)&&A.timeout>0))throw TypeError(`Expected \`timeout\` to be a positive finite number, got \`${A.timeout}\` (${typeof A.timeout})`);this.timeout=A.timeout,this.#Z=A.autoStart===!1,this.#v()}get#H(){return this.#Q||this.#B<this.#D}get#W(){return this.#X<this.#K}#V(){if(this.#X--,this.#X===0)this.emit("pendingZero");this.#L(),this.emit("next")}#N(){this.#P(),this.#T(),this.#G=void 0}get#M(){let A=Date.now();if(this.#Y===void 0){let Q=this.#F-A;if(Q<0){if(this.#J>0){let B=A-this.#J;if(B<this.#C)return this.#q(this.#C-B),!0}this.#B=this.#A?this.#X:0}else return this.#q(Q),!0}return!1}#q(A){if(this.#G!==void 0)return;this.#G=setTimeout(()=>{this.#N()},A)}#R(){if(this.#Y)clearInterval(this.#Y),this.#Y=void 0}#S(){if(this.#G)clearTimeout(this.#G),this.#G=void 0}#L(){if(this.#U.size===0){if(this.#R(),this.emit("empty"),this.#X===0)this.#S(),this.emit("idle");return!1}let A=!1;if(!this.#Z){let Q=!this.#M;if(this.#H&&this.#W){let B=this.#U.dequeue();if(!this.#Q)this.#B++,this.#_();if(this.emit("active"),this.#J=Date.now(),B(),Q)this.#T();A=!0}}return A}#T(){if(this.#Q||this.#Y!==void 0)return;this.#Y=setInterval(()=>{this.#P()},this.#C),this.#F=Date.now()+this.#C}#P(){if(this.#B===0&&this.#X===0&&this.#Y)this.#R();this.#B=this.#A?this.#X:0,this.#j(),this.#_()}#j(){while(this.#L());}get concurrency(){return this.#K}set concurrency(A){if(!(typeof A==="number"&&A>=1))throw TypeError(`Expected \`concurrency\` to be a number from 1 and up, got \`${A}\` (${typeof A})`);this.#K=A,this.#j()}async#y(A){return new Promise((Q,B)=>{A.addEventListener("abort",()=>{B(A.reason)},{once:!0})})}setPriority(A,Q){if(typeof Q!=="number"||!Number.isFinite(Q))throw TypeError(`Expected \`priority\` to be a finite number, got \`${Q}\` (${typeof Q})`);this.#U.setPriority(A,Q)}async add(A,Q={}){return Q.id??=(this.#$++).toString(),Q={timeout:this.timeout,...Q},new Promise((B,D)=>{let I=Symbol(`task-${Q.id}`);this.#U.enqueue(async()=>{this.#X++,this.#w.set(I,{id:Q.id,priority:Q.priority??0,startTime:Date.now(),timeout:Q.timeout});try{try{Q.signal?.throwIfAborted()}catch(F){if(!this.#Q)this.#B--;throw this.#w.delete(I),F}let E=A({signal:Q.signal});if(Q.timeout)E=AkA(Promise.resolve(E),{milliseconds:Q.timeout,message:`Task timed out after ${Q.timeout}ms (queue has ${this.#X} running, ${this.#U.size} waiting)`});if(Q.signal)E=Promise.race([E,this.#y(Q.signal)]);let C=await E;B(C),this.emit("completed",C)}catch(E){D(E),this.emit("error",E)}finally{this.#w.delete(I),queueMicrotask(()=>{this.#V()})}},Q),this.emit("add"),this.#L()})}async addAll(A,Q){return Promise.all(A.map(async(B)=>this.add(B,Q)))}start(){if(!this.#Z)return this;return this.#Z=!1,this.#j(),this}pause(){this.#Z=!0}clear(){this.#U=new this.#z,this.#k()}async onEmpty(){if(this.#U.size===0)return;await this.#O("empty")}async onSizeLessThan(A){if(this.#U.size<A)return;await this.#O("next",()=>this.#U.size<A)}async onIdle(){if(this.#X===0&&this.#U.size===0)return;await this.#O("idle")}async onPendingZero(){if(this.#X===0)return;await this.#O("pendingZero")}async onRateLimit(){if(this.isRateLimited)return;await this.#O("rateLimit")}async onRateLimitCleared(){if(!this.isRateLimited)return;await this.#O("rateLimitCleared")}async onError(){return new Promise((A,Q)=>{let B=(D)=>{this.off("error",B),Q(D)};this.on("error",B)})}async#O(A,Q){return new Promise((B)=>{let D=()=>{if(Q&&!Q())return;this.off(A,D),B()};this.on(A,D)})}get size(){return this.#U.size}sizeBy(A){return this.#U.filter(A).length}get pending(){return this.#X}get isPaused(){return this.#Z}#v(){if(this.#Q)return;this.on("add",()=>{if(this.#U.size>0)this.#_()}),this.on("next",()=>{this.#_()})}#_(){if(this.#Q||this.#E)return;this.#E=!0,queueMicrotask(()=>{this.#E=!1,this.#k()})}#k(){let A=this.#I,Q=!this.#Q&&this.#B>=this.#D&&this.#U.size>0;if(Q!==A)this.#I=Q,this.emit(Q?"rateLimit":"rateLimitCleared")}get isRateLimited(){return this.#I}get isSaturated(){return this.#X===this.#K&&this.#U.size>0||this.isRateLimited&&this.#U.size>0}get runningTasks(){return[...this.#w.values()].map((A)=>({...A}))}}var bs1=fA(x1(),1);class kR{#A;#Q=new W3A({concurrency:1});constructor(){this.#A=this.#D(),this.#I(),setImmediate(()=>cJ1())}write(A){if(!this.#A){console.error(A);return}let Q=this.#A;BD(this.#Q.add(async()=>{try{await CQ4(Q,`${A}
1573
- `)}catch(B){console.error(`Failed to write to log file: ${Q}`,B),console.error(A)}}))}#B(){let Q=process.cwd().split(JQ4).slice(-3).join("-"),B=new Date().toISOString().replace(/[:.]/g,"-").slice(0,19);return`duo-cli-log-${Q}-${B}.log`}#D(){try{let A=jc();if(!DQ4(A))IQ4(A,{recursive:!0});let Q=FQ4(A,this.#B());return EQ4(Q,""),Q}catch(A){console.error("Failed to create log file. Logs will be printed to stderr.",A);return}}#I(){process.on("exit",()=>{if(!this.#A)return;console.error(`CLI log file: ${this.#A}`)})}flush(){return this.#Q.onIdle()}}kR=G1([bs1.Injectable(kw,[])],kR);var YQ4=l.object({gitlabBaseUrl:l.string().optional(),gitlabAuthToken:l.string().optional()}),fs1="duo-cli-config";class xs1{#A;#Q;#B;constructor(A,Q,B){this.#A=A,this.#B=B,this.#Q=Q}async saveConfig(A){try{let{configurationEntries:Q}=A,B={gitlabAuthToken:"",gitlabBaseUrl:""};for(let D of Q){let I=D.key;if(I in B)B[I]=D.value}return this.#A=B,await this.#Q.set(fs1,B),i4()}catch(Q){return this.#B.error("Failed to save configuration:",Q),c6(Q)}}exit(){process.exit(0)}getDuoConfiguration(){return{gitlabBaseUrl:this.#A.gitlabBaseUrl||"https://gitlab.com",gitlabAuthToken:this.#A.gitlabAuthToken||""}}async initialize(){let A=await this.#Q.get(fs1),Q=YQ4.safeParse(A);if(!Q.success)return;let B=this.#D(this.#A);this.#A={...Q.data,...B}}isMissingConfiguration(){let{gitlabAuthToken:A,gitlabBaseUrl:Q}=this.getDuoConfiguration();return!A||!Q}getConfigurationModel(){return{configurationEntries:[{key:"gitlabBaseUrl",value:this.#A.gitlabBaseUrl??"",displayName:"\uD83D\uDD17 GitLab Instance URL",description:"The URL of the GitLab instance to connect to.",defaultValue:"https://gitlab.com",isSensitive:!1},{key:"gitlabAuthToken",value:this.#A.gitlabAuthToken??"",displayName:"\uD83D\uDD16 GitLab Token",description:"GitLab access token with API permissions. Create one here: https://gitlab.com/-/user_settings/personal_access_tokens",defaultValue:"",isSensitive:!0}]}}#D(A){return Object.fromEntries(Object.entries(A).filter(([,Q])=>Q!=null&&Q!==""))}}var N3A=async(A={})=>{let Q=new kR,B=new H3A("info"),D=new gw(Q,B),I=new CZ(D),E=new xs1(A,I,D);return await E.initialize(),E};var BkA=(A,Q)=>{cp(rA(nL1,{initialState:A.getConfigurationModel(),controller:A}),Q)};var _G=fA(x1(),1);var rF0=fA(jt1(),1),sF0=fA(v80(),1),tF0=fA(iD(),1),eF0=fA(x1(),1);import jM4 from"https";import PM4 from"http";import LhA from"fs";var A22=GT(),FM4=gn(),Q22=Kf(),B22=a30(),JM4=zT(),D22=afA(),YM4=W70(),I22=R70(),E22=S70(),GM4=_4(),FIA=E4(),{InvalidArgumentError:CIA}=GM4,uf=$D0(),C22=fn(),F22=$xA(),{MockCallHistory:J22,MockCallHistoryLog:Y22}=MxA(),G22=jxA(),U22=LxA(),X22=OI0(),z22=ExA(),Z22=XDA(),{getGlobalDispatcher:UM4,setGlobalDispatcher:K22}=LDA(),w22=Lf(),H22=xxA();Object.assign(FM4.prototype,uf);var JIA=JM4;var YIA=YM4;var KM4={redirect:gI0(),responseError:xI0(),retry:mI0(),dump:cI0(),dns:aI0(),cache:zE0(),decompress:WE0()},nF0={MemoryCacheStore:mxA()};var XM4=ME0();nF0.SqliteCacheStore=XM4;var wM4={parseHeaders:FIA.parseHeaders,headerNameToString:FIA.headerNameToString};function ko(A){return(Q,B,D)=>{if(typeof B==="function")D=B,B=null;if(!Q||typeof Q!=="string"&&typeof Q!=="object"&&!(Q instanceof URL))throw new CIA("invalid url");if(B!=null&&typeof B!=="object")throw new CIA("invalid opts");if(B&&B.path!=null){if(typeof B.path!=="string")throw new CIA("invalid opts.path");let C=B.path;if(!B.path.startsWith("/"))C=`/${C}`;Q=new URL(FIA.parseOrigin(Q).origin+C)}else{if(!B)B=typeof Q==="object"?Q:{};Q=FIA.parseURL(Q)}let{agent:I,dispatcher:E=UM4()}=B;if(I)throw new CIA("unsupported opts.agent. Did you mean opts.client?");return A.call(E,{...B,origin:Q.origin,path:Q.search?`${Q.pathname}${Q.search}`:Q.pathname,method:B.method||(B.body?"PUT":"GET")},D)}}var V22=_o().fetch;var HM4=$T().Headers,VM4=Oo().Response,$M4=Pf().Request,WM4=d7A().FormData;var{setGlobalOrigin:$22,getGlobalOrigin:W22}=YfA();var{CacheStorage:zM4}=PC0(),{kConstruct:ZM4}=F2();var NM4=new zM4(ZM4);var{deleteCookie:N22,getCookies:M22,getSetCookies:q22,setCookie:O22,parseCookie:L22}=cC0();var{parseMIMEType:_22,serializeAMimeType:R22}=pF();var{CloseEvent:T22,ErrorEvent:j22,MessageEvent:P22}=oDA(),{WebSocket:S22,ping:y22}=OF0();var MM4=yF0().WebSocketStream,qM4=WhA().WebSocketError,OM4=ko(uf.request),LM4=ko(uf.stream),_M4=ko(uf.pipeline),RM4=ko(uf.connect),TM4=ko(uf.upgrade);var{EventSource:v22}=aF0();var oF0=new PM4.Agent({keepAlive:!0});class go extends UyA{#A;#Q;#B;#D=!1;#I;#E;#C;constructor(A,Q){super();this.#C=A,this.#E={rejectUnauthorized:!0},this.#B=Q,this.#I=this.#F()}async initialize(){try{let A=await rF0.getProxySettings();if(A?.http){if(process.env.http_proxy=`${A.http.protocol}://${A.http.host}:${A.http.port}`,this.#C.info(`fetch: Detected http proxy through settings: ${process.env.http_proxy}`),A.http?.credentials&&A.http.credentials?.username&&A.http.credentials?.password)this.#C.info(`fetch: Added credentials to http_proxy for username: ${A.http.credentials.username}`),process.env.http_proxy=`${A.http.protocol}://${A.http.credentials.username}:${A.http.credentials.password}@${A.http.host}:${A.http.port}`}if(A?.https){if(process.env.https_proxy=`${A.https.protocol}://${A.https.host}:${A.https.port}`,this.#C.info(`fetch: Detected https proxy through settings: ${process.env.https_proxy}`),A.https?.credentials&&A.https.credentials?.username&&A.https.credentials?.password)this.#C.info(`fetch: Added credentials to HTTPS_PROXY for username: ${A.https.credentials.username}`),process.env.https_proxy=`${A.https.protocol}://${A.https.credentials.username}:${A.https.credentials.password}@${A.https.host}:${A.https.port}`}if(!A?.http&&!A?.https)this.#C.info("fetch: Detected no proxy settings")}catch(A){this.#C.warn("Unable to load proxy settings",A)}if(this.#B)this.#C.debug(`fetch: Detected user proxy ${this.#B}`),process.env.http_proxy=this.#B,process.env.https_proxy=this.#B;if(process.env.http_proxy||process.env.https_proxy){let A=process.env.NO_PROXY??process.env.no_proxy??"";if(A?.length)this.#C.info(`fetch: Skipping proxy for hosts in no_proxy: ${A}`);this.#Q=this.#J(),this.#A=new YIA(this.#U())}else this.#A=new JIA(this.#U());this.#D=!0}async destroy(){this.#Q?.destroy()}async fetchBase(A,Q){if(!this.#D)throw Error("LsFetch not initialized. Make sure LsFetch.initialize() was called.");return this.#Y(A,{...Q,agent:this.#G(A),dispatcher:this.#A},super.fetchBase)}async fetch(A,Q){if(!this.#D)throw Error("LsFetch not initialized. Make sure LsFetch.initialize() was called.");let B=new AbortController,D=AbortSignal.timeout(E5A);[Q?.signal,D].forEach((I)=>{I?.addEventListener("abort",()=>B.abort(I.reason),{once:!0})});try{return await this.#Y(A,{...Q,signal:B.signal,agent:this.#G(A),dispatcher:this.#A},super.fetch)}catch(I){if(Qb(I)){let{reason:E}=B.signal;if(E instanceof Error&&E.name==="TimeoutError")throw new XyA(A)}throw I}}getWebSocketOptions(A){let Q=this.#G(A),B=A.toString().startsWith("https://")?"https":"http",D=Q===this.#Q?"proxy":B;return{...this.#E,agent:Q,agentType:D}}updateAgentOptions({ignoreCertificateErrors:A,ca:Q,cert:B,certKey:D}){let I={};try{I={...Q?{ca:LhA.readFileSync(Q)}:{},...B?{cert:LhA.readFileSync(B)}:{},...D?{key:LhA.readFileSync(D)}:{}}}catch(C){this.#C.error("Error reading https agent options from file",C)}let E={rejectUnauthorized:!A,...I};if(tF0.default.isEqual(E,this.#E))return;if(this.#E=E,this.#I=this.#F(),this.#Q)this.#Q=this.#J(),this.#A=new YIA(this.#U());else this.#A=new JIA(this.#U())}async*streamResponse(A,Q){let B=this.#C;if(!A.body)return;let D=new TextDecoder;async function*I(E){for await(let C of E){if(Q.isCancellationRequested){if("destroy"in E)B.debug("Cancelling stream"),E.destroy();return}yield D.decode(C)}}yield*I(A.body)}#F(){let A={...this.#E,keepAlive:!0};return this.#C.debug(`fetch: https agent with options initialized ${JSON.stringify(this.#X(A))}.`),new jM4.Agent(A)}#J(){return this.#C.debug(`fetch: proxy agent with options initialized ${JSON.stringify(this.#X(this.#E))}.`),new sF0.ProxyAgent(this.#E)}async#Y(A,Q,B){let D=Date.now(),I=this.#z(A);if(Q.agent===oF0)this.#C.debug(`fetch: request for ${I} made with http agent.`);else{let E=Q.agent===this.#Q?"proxy":"https";this.#C.debug(`fetch: request for ${I} made with ${E} agent.`)}try{let E=await B(A,Q),C=Date.now()-D;return this.#C.debug(`fetch: request to ${I} returned HTTP ${E.status} after ${C} ms`),E}catch(E){let C=Date.now()-D;throw this.#C.debug(`fetch: request to ${I} threw an exception after ${C} ms`),E}}#G(A){if(this.#Q)return this.#Q;if(A.toString().startsWith("https://"))return this.#I;return oF0}#U=()=>({keepAliveTimeout:1000,requestTls:this.#E});#z(A){if(A instanceof URL)return A.toString();if(typeof A==="string")return A;return A.url}#X(A){let{ca:Q,cert:B,key:D,...I}=A;return{...I,...Q?{ca:"<hidden>"}:{},...B?{cert:"<hidden>"}:{},...D?{key:"<hidden>"}:{}}}}go=G1([eF0.Injectable(XI,[T1])],go);var VK=fA(x1(),1);var a22=l.object({prefix:l.string().describe("The text before the cursor."),suffix:l.string().describe("The text after the cursor."),fileRelativePath:l.string().describe("Path to a file relative to the workspace, or identical to document URI if file does not belong to a workspace."),position:l.object({line:l.number(),character:l.number()}).describe("The position in the document."),uri:l.string().describe("The URI of the document."),languageId:l.string().describe("languageId of the document"),workspaceFolder:l.object({uri:l.string(),name:l.string()}).optional().describe("The workspace folder that the document belongs to.")});var bo=fA(x1(),1);var AJ0=fA(x1(),1),_hA=AJ0.createInterfaceId("RpcMessageSender");class RhA extends Error{details;constructor(A,Q){super(A);this.name="RpcValidationError",this.details=Q}}class ThA extends RhA{constructor(A,Q){super(`Parameter validation failed for ${A}`,Q);this.name="RpcParamsValidationError"}}class jhA extends RhA{constructor(A,Q){super(`Response validation failed for ${A}`,Q);this.name="RpcResponseValidationError"}}class QJ0{#A;#Q;constructor(A,Q){this.#A=A,this.#Q=Q}send=async(A,Q)=>{if(!this.#Q.getMessageDefinitions().includes(A))throw Error(`Unknown message ${A.methodName}.`);if(A.paramsSchema&&Q!==void 0)this.#B(A.paramsSchema,Q,A.methodName,(B,D)=>new ThA(B,D));if(A.type==="notification"){await this.#A.sendNotification(A.methodName,Q);return}if(A.type==="request"){let B=await this.#A.sendRequest(A.methodName,Q);return this.#B(A.responseSchema,B,A.methodName,(D,I)=>new jhA(D,I))}throw Error("Unknown message type")};#B(A,Q,B,D){let I=A.safeParse(Q);if(!I.success)throw D(B,I.error.message);return I.data}}var SM4=l.union([l.literal(1),l.literal(2),l.literal(3),l.literal(4)]),yM4=l.union([l.literal(1),l.literal(2)]),vM4=l.object({range:l.object({start:l.object({line:l.number().min(0),character:l.number().min(0)}),end:l.object({line:l.number().min(0),character:l.number().min(0)})}),message:l.string(),severity:SM4.optional(),code:l.union([l.string(),l.number()]).optional(),source:l.string().optional(),relatedInformation:l.array(l.any()).optional(),tags:l.array(yM4).optional(),data:l.any().optional()}),kM4=l.object({fileUri:l.string()}),gM4=l.array(vM4),PhA=eL("$/gitlab/document-quality/get-diagnostics").withParams(kM4).withResponse(gM4).build();var fo=bo.createInterfaceId("DocumentQualityService");class GIA{#A;#Q;constructor(A,Q){this.#A=y1(A,"[DocumentQualityService]"),this.#Q=Q}async getDiagnostics(A){try{this.#A.debug(`Getting diagnostics for file: "${A}"`);let Q=await this.#Q.send(PhA,{fileUri:A.toString()});return this.#A.debug(`Received ${Q.length} diagnostics for file: "${A}"`),Q}catch(Q){return this.#A.error(`Failed to get diagnostics for file: "${A}"`,Q),[]}}}GIA=G1([bo.Injectable(fo,[T1,_hA])],GIA);class UIA{getMessageDefinitions(){return[PhA]}}UIA=G1([bo.Injectable(d51,[])],UIA);function BJ0(A){let Q=`[${A.range.start.line}:${A.range.start.character} - ${A.range.end.line}:${A.range.end.character}]`,B=A.source?`source: "${A.source}"`:void 0,D=A.code?`code: "${A.code}"`:void 0,I=[B,D].filter(Boolean),E=I.length?` (${I.join(", ")})`:"";return`${A.severity}: ${A.message} ${Q}${E}`}function bM4(A,Q){return A.line>Q.line||A.line===Q.line&&A.character>=Q.character}function fM4(A,Q){return A.line<Q.line||A.line===Q.line&&A.character<=Q.character}function xM4(A,Q){return fM4(A.start,Q.end)&&bM4(A.end,Q.start)}function DJ0(A,Q){return Q.some((B)=>xM4(A,B))}function IJ0(A){let Q=A.start.line+1,B=A.start.character+1,D=A.end.line+1,I=A.end.character+1;if(Q===D){if(B===I)return`line ${Q}:${B}`;return`line ${Q}:${B}-${I}`}return`line ${Q}:${B} to line ${D}:${I}`}var ZIA=fA(x1(),1);var zV=(A,...Q)=>{return A.reduce((B,D,I)=>`${B}${D}${I in Q?String(Q[I]):""}`,"")};var EJ0={supportedSinceInstanceVersion:"18.5.0",query:zV`
1573
+ `)}catch(B){console.error(`Failed to write to log file: ${Q}`,B),console.error(A)}}))}#B(){let Q=process.cwd().split(JQ4).slice(-3).join("-"),B=new Date().toISOString().replace(/[:.]/g,"-").slice(0,19);return`duo-cli-log-${Q}-${B}.log`}#D(){try{let A=jc();if(!DQ4(A))IQ4(A,{recursive:!0});let Q=FQ4(A,this.#B());return EQ4(Q,""),Q}catch(A){console.error("Failed to create log file. Logs will be printed to stderr.",A);return}}#I(){process.on("exit",()=>{if(!this.#A)return;console.error(`CLI log file: ${this.#A}`)})}flush(){return this.#Q.onIdle()}}kR=G1([bs1.Injectable(kw,[])],kR);var YQ4=l.object({gitlabBaseUrl:l.string().optional(),gitlabAuthToken:l.string().optional()}),fs1="duo-cli-config";class xs1{#A;#Q;#B;constructor(A,Q,B){this.#A=A,this.#B=B,this.#Q=Q}async saveConfig(A){try{let{configurationEntries:Q}=A,B={gitlabAuthToken:"",gitlabBaseUrl:""};for(let D of Q){let I=D.key;if(I in B)B[I]=D.value}return this.#A=B,await this.#Q.set(fs1,B),i4()}catch(Q){return this.#B.error("Failed to save configuration:",Q),c6(Q)}}exit(){process.exit(0)}getDuoConfiguration(){return{gitlabBaseUrl:this.#A.gitlabBaseUrl||"https://gitlab.com",gitlabAuthToken:this.#A.gitlabAuthToken||""}}async initialize(){let A=await this.#Q.get(fs1),Q=YQ4.safeParse(A);if(!Q.success)return;let B=this.#D(this.#A);this.#A={...Q.data,...B}}isMissingConfiguration(){let{gitlabAuthToken:A,gitlabBaseUrl:Q}=this.getDuoConfiguration();return!A||!Q}getConfigurationModel(){return{configurationEntries:[{key:"gitlabBaseUrl",value:this.#A.gitlabBaseUrl??"",displayName:"\uD83D\uDD17 GitLab Instance URL",description:"The URL of the GitLab instance to connect to.",defaultValue:"https://gitlab.com",isSensitive:!1},{key:"gitlabAuthToken",value:this.#A.gitlabAuthToken??"",displayName:"\uD83D\uDD16 GitLab Token",description:"GitLab access token with API permissions. Create one here: https://gitlab.com/-/user_settings/personal_access_tokens",defaultValue:"",isSensitive:!0}]}}#D(A){return Object.fromEntries(Object.entries(A).filter(([,Q])=>Q!=null&&Q!==""))}}var N3A=async(A={})=>{let Q=new kR,B=new H3A("info"),D=new gw(Q,B),I=new CZ(D),E=new xs1(A,I,D);return await E.initialize(),E};var BkA=(A,Q)=>{cp(rA(nL1,{initialState:A.getConfigurationModel(),controller:A}),Q)};var _G=fA(x1(),1);var rF0=fA(jt1(),1),sF0=fA(v80(),1),tF0=fA(iD(),1),eF0=fA(x1(),1);import jM4 from"https";import PM4 from"http";import LhA from"fs";var A22=GT(),FM4=gn(),Q22=Kf(),B22=a30(),JM4=zT(),D22=afA(),YM4=W70(),I22=R70(),E22=S70(),GM4=_4(),FIA=E4(),{InvalidArgumentError:CIA}=GM4,uf=$D0(),C22=fn(),F22=$xA(),{MockCallHistory:J22,MockCallHistoryLog:Y22}=MxA(),G22=jxA(),U22=LxA(),X22=OI0(),z22=ExA(),Z22=XDA(),{getGlobalDispatcher:UM4,setGlobalDispatcher:K22}=LDA(),w22=Lf(),H22=xxA();Object.assign(FM4.prototype,uf);var JIA=JM4;var YIA=YM4;var KM4={redirect:gI0(),responseError:xI0(),retry:mI0(),dump:cI0(),dns:aI0(),cache:zE0(),decompress:WE0()},nF0={MemoryCacheStore:mxA()};var XM4=ME0();nF0.SqliteCacheStore=XM4;var wM4={parseHeaders:FIA.parseHeaders,headerNameToString:FIA.headerNameToString};function ko(A){return(Q,B,D)=>{if(typeof B==="function")D=B,B=null;if(!Q||typeof Q!=="string"&&typeof Q!=="object"&&!(Q instanceof URL))throw new CIA("invalid url");if(B!=null&&typeof B!=="object")throw new CIA("invalid opts");if(B&&B.path!=null){if(typeof B.path!=="string")throw new CIA("invalid opts.path");let C=B.path;if(!B.path.startsWith("/"))C=`/${C}`;Q=new URL(FIA.parseOrigin(Q).origin+C)}else{if(!B)B=typeof Q==="object"?Q:{};Q=FIA.parseURL(Q)}let{agent:I,dispatcher:E=UM4()}=B;if(I)throw new CIA("unsupported opts.agent. Did you mean opts.client?");return A.call(E,{...B,origin:Q.origin,path:Q.search?`${Q.pathname}${Q.search}`:Q.pathname,method:B.method||(B.body?"PUT":"GET")},D)}}var V22=_o().fetch;var HM4=$T().Headers,VM4=Oo().Response,$M4=Pf().Request,WM4=d7A().FormData;var{setGlobalOrigin:$22,getGlobalOrigin:W22}=YfA();var{CacheStorage:zM4}=PC0(),{kConstruct:ZM4}=F2();var NM4=new zM4(ZM4);var{deleteCookie:N22,getCookies:M22,getSetCookies:q22,setCookie:O22,parseCookie:L22}=cC0();var{parseMIMEType:_22,serializeAMimeType:R22}=pF();var{CloseEvent:T22,ErrorEvent:j22,MessageEvent:P22}=oDA(),{WebSocket:S22,ping:y22}=OF0();var MM4=yF0().WebSocketStream,qM4=WhA().WebSocketError,OM4=ko(uf.request),LM4=ko(uf.stream),_M4=ko(uf.pipeline),RM4=ko(uf.connect),TM4=ko(uf.upgrade);var{EventSource:v22}=aF0();var oF0=new PM4.Agent({keepAlive:!0});class go extends UyA{#A;#Q;#B;#D=!1;#I;#E;#C;constructor(A,Q){super();this.#C=A,this.#E={rejectUnauthorized:!0},this.#B=Q,this.#I=this.#F()}async initialize(){try{let A=await rF0.getProxySettings();if(A?.http){if(process.env.http_proxy=`${A.http.protocol}://${A.http.host}:${A.http.port}`,this.#C.info(`fetch: Detected http proxy through settings: ${process.env.http_proxy}`),A.http?.credentials&&A.http.credentials?.username&&A.http.credentials?.password)this.#C.info(`fetch: Added credentials to http_proxy for username: ${A.http.credentials.username}`),process.env.http_proxy=`${A.http.protocol}://${A.http.credentials.username}:${A.http.credentials.password}@${A.http.host}:${A.http.port}`}if(A?.https){if(process.env.https_proxy=`${A.https.protocol}://${A.https.host}:${A.https.port}`,this.#C.info(`fetch: Detected https proxy through settings: ${process.env.https_proxy}`),A.https?.credentials&&A.https.credentials?.username&&A.https.credentials?.password)this.#C.info(`fetch: Added credentials to HTTPS_PROXY for username: ${A.https.credentials.username}`),process.env.https_proxy=`${A.https.protocol}://${A.https.credentials.username}:${A.https.credentials.password}@${A.https.host}:${A.https.port}`}if(process.env.wss_proxy||process.env.ws_proxy)this.#C.info(`fetch: Detected existing ${process.env.wss_proxy?"wss_proxy":"ws_proxy"} setting`);else if(A?.https)this.#C.info("fetch: Setting WebSocket proxy based on https_proxy setting"),process.env.ws_proxy=process.env.https_proxy,process.env.wss_proxy=process.env.https_proxy;else if(A?.http)this.#C.info("fetch: Setting WebSocket proxy based on http_proxy setting"),process.env.ws_proxy=process.env.http_proxy,process.env.wss_proxy=process.env.http_proxy;if(!A?.http&&!A?.https&&!process.env.ws_proxy&&!process.env.wss_proxy)this.#C.info("fetch: Detected no proxy settings")}catch(A){this.#C.warn("Unable to load proxy settings",A)}if(this.#B)this.#C.debug(`fetch: Detected user proxy ${this.#B}`),process.env.http_proxy=this.#B,process.env.https_proxy=this.#B;if(process.env.http_proxy||process.env.https_proxy||process.env.ws_proxy||process.env.wss_proxy){let A=process.env.NO_PROXY??process.env.no_proxy??"";if(A?.length)this.#C.info(`fetch: Skipping proxy for hosts in no_proxy: ${A}`);this.#Q=this.#J(),this.#A=new YIA(this.#U())}else this.#A=new JIA(this.#U());this.#D=!0}async destroy(){this.#Q?.destroy()}async fetchBase(A,Q){if(!this.#D)throw Error("LsFetch not initialized. Make sure LsFetch.initialize() was called.");return this.#Y(A,{...Q,agent:this.#G(A),dispatcher:this.#A},super.fetchBase)}async fetch(A,Q){if(!this.#D)throw Error("LsFetch not initialized. Make sure LsFetch.initialize() was called.");let B=new AbortController,D=AbortSignal.timeout(E5A);[Q?.signal,D].forEach((I)=>{I?.addEventListener("abort",()=>B.abort(I.reason),{once:!0})});try{return await this.#Y(A,{...Q,signal:B.signal,agent:this.#G(A),dispatcher:this.#A},super.fetch)}catch(I){if(Qb(I)){let{reason:E}=B.signal;if(E instanceof Error&&E.name==="TimeoutError")throw new XyA(A)}throw I}}getWebSocketOptions(A){let Q=this.#G(A),B=A.toString().startsWith("https://")?"https":"http",D=Q===this.#Q?"proxy":B;return{...this.#E,agent:Q,agentType:D}}updateAgentOptions({ignoreCertificateErrors:A,ca:Q,cert:B,certKey:D}){let I={};try{I={...Q?{ca:LhA.readFileSync(Q)}:{},...B?{cert:LhA.readFileSync(B)}:{},...D?{key:LhA.readFileSync(D)}:{}}}catch(C){this.#C.error("Error reading https agent options from file",C)}let E={rejectUnauthorized:!A,...I};if(tF0.default.isEqual(E,this.#E))return;if(this.#E=E,this.#I=this.#F(),this.#Q)this.#Q=this.#J(),this.#A=new YIA(this.#U());else this.#A=new JIA(this.#U())}async*streamResponse(A,Q){let B=this.#C;if(!A.body)return;let D=new TextDecoder;async function*I(E){for await(let C of E){if(Q.isCancellationRequested){if("destroy"in E)B.debug("Cancelling stream"),E.destroy();return}yield D.decode(C)}}yield*I(A.body)}#F(){let A={...this.#E,keepAlive:!0};return this.#C.debug(`fetch: https agent with options initialized ${JSON.stringify(this.#X(A))}.`),new jM4.Agent(A)}#J(){return this.#C.debug(`fetch: proxy agent with options initialized ${JSON.stringify(this.#X(this.#E))}.`),new sF0.ProxyAgent(this.#E)}async#Y(A,Q,B){let D=Date.now(),I=this.#z(A);if(Q.agent===oF0)this.#C.debug(`fetch: request for ${I} made with http agent.`);else{let E=Q.agent===this.#Q?"proxy":"https";this.#C.debug(`fetch: request for ${I} made with ${E} agent.`)}try{let E=await B(A,Q),C=Date.now()-D;return this.#C.debug(`fetch: request to ${I} returned HTTP ${E.status} after ${C} ms`),E}catch(E){let C=Date.now()-D;throw this.#C.debug(`fetch: request to ${I} threw an exception after ${C} ms`),E}}#G(A){if(this.#Q)return this.#Q;if(A.toString().startsWith("https://"))return this.#I;return oF0}#U=()=>({keepAliveTimeout:1000,requestTls:this.#E});#z(A){if(A instanceof URL)return A.toString();if(typeof A==="string")return A;return A.url}#X(A){let{ca:Q,cert:B,key:D,...I}=A;return{...I,...Q?{ca:"<hidden>"}:{},...B?{cert:"<hidden>"}:{},...D?{key:"<hidden>"}:{}}}}go=G1([eF0.Injectable(XI,[T1])],go);var VK=fA(x1(),1);var a22=l.object({prefix:l.string().describe("The text before the cursor."),suffix:l.string().describe("The text after the cursor."),fileRelativePath:l.string().describe("Path to a file relative to the workspace, or identical to document URI if file does not belong to a workspace."),position:l.object({line:l.number(),character:l.number()}).describe("The position in the document."),uri:l.string().describe("The URI of the document."),languageId:l.string().describe("languageId of the document"),workspaceFolder:l.object({uri:l.string(),name:l.string()}).optional().describe("The workspace folder that the document belongs to.")});var bo=fA(x1(),1);var AJ0=fA(x1(),1),_hA=AJ0.createInterfaceId("RpcMessageSender");class RhA extends Error{details;constructor(A,Q){super(A);this.name="RpcValidationError",this.details=Q}}class ThA extends RhA{constructor(A,Q){super(`Parameter validation failed for ${A}`,Q);this.name="RpcParamsValidationError"}}class jhA extends RhA{constructor(A,Q){super(`Response validation failed for ${A}`,Q);this.name="RpcResponseValidationError"}}class QJ0{#A;#Q;constructor(A,Q){this.#A=A,this.#Q=Q}send=async(A,Q)=>{if(!this.#Q.getMessageDefinitions().includes(A))throw Error(`Unknown message ${A.methodName}.`);if(A.paramsSchema&&Q!==void 0)this.#B(A.paramsSchema,Q,A.methodName,(B,D)=>new ThA(B,D));if(A.type==="notification"){await this.#A.sendNotification(A.methodName,Q);return}if(A.type==="request"){let B=await this.#A.sendRequest(A.methodName,Q);return this.#B(A.responseSchema,B,A.methodName,(D,I)=>new jhA(D,I))}throw Error("Unknown message type")};#B(A,Q,B,D){let I=A.safeParse(Q);if(!I.success)throw D(B,I.error.message);return I.data}}var SM4=l.union([l.literal(1),l.literal(2),l.literal(3),l.literal(4)]),yM4=l.union([l.literal(1),l.literal(2)]),vM4=l.object({range:l.object({start:l.object({line:l.number().min(0),character:l.number().min(0)}),end:l.object({line:l.number().min(0),character:l.number().min(0)})}),message:l.string(),severity:SM4.optional(),code:l.union([l.string(),l.number()]).optional(),source:l.string().optional(),relatedInformation:l.array(l.any()).optional(),tags:l.array(yM4).optional(),data:l.any().optional()}),kM4=l.object({fileUri:l.string()}),gM4=l.array(vM4),PhA=eL("$/gitlab/document-quality/get-diagnostics").withParams(kM4).withResponse(gM4).build();var fo=bo.createInterfaceId("DocumentQualityService");class GIA{#A;#Q;constructor(A,Q){this.#A=y1(A,"[DocumentQualityService]"),this.#Q=Q}async getDiagnostics(A){try{this.#A.debug(`Getting diagnostics for file: "${A}"`);let Q=await this.#Q.send(PhA,{fileUri:A.toString()});return this.#A.debug(`Received ${Q.length} diagnostics for file: "${A}"`),Q}catch(Q){return this.#A.error(`Failed to get diagnostics for file: "${A}"`,Q),[]}}}GIA=G1([bo.Injectable(fo,[T1,_hA])],GIA);class UIA{getMessageDefinitions(){return[PhA]}}UIA=G1([bo.Injectable(d51,[])],UIA);function BJ0(A){let Q=`[${A.range.start.line}:${A.range.start.character} - ${A.range.end.line}:${A.range.end.character}]`,B=A.source?`source: "${A.source}"`:void 0,D=A.code?`code: "${A.code}"`:void 0,I=[B,D].filter(Boolean),E=I.length?` (${I.join(", ")})`:"";return`${A.severity}: ${A.message} ${Q}${E}`}function bM4(A,Q){return A.line>Q.line||A.line===Q.line&&A.character>=Q.character}function fM4(A,Q){return A.line<Q.line||A.line===Q.line&&A.character<=Q.character}function xM4(A,Q){return fM4(A.start,Q.end)&&bM4(A.end,Q.start)}function DJ0(A,Q){return Q.some((B)=>xM4(A,B))}function IJ0(A){let Q=A.start.line+1,B=A.start.character+1,D=A.end.line+1,I=A.end.character+1;if(Q===D){if(B===I)return`line ${Q}:${B}`;return`line ${Q}:${B}-${I}`}return`line ${Q}:${B} to line ${D}:${I}`}var ZIA=fA(x1(),1);var zV=(A,...Q)=>{return A.reduce((B,D,I)=>`${B}${D}${I in Q?String(Q[I]):""}`,"")};var EJ0={supportedSinceInstanceVersion:"18.5.0",query:zV`
1574
1574
  query lsp_aiChatAvailableModels($rootNamespaceId: GroupID!) {
1575
1575
  metadata {
1576
1576
  featureFlags(names: ["ai_user_model_switching"]) {
@@ -2080,5 +2080,5 @@ ${JSON.stringify(B,null,4)}`)}}pe=G1([pGA.Injectable(ftA,[T1,X9])],pe);var LRQ=f
2080
2080
  <gitlab_instance_version>${B}</gitlab_instance_version>
2081
2081
  </gitlab_instance>`}}ie=G1([_RQ.Injectable(fF,[T1,b4])],ie);function RRQ(A){A.addClass(DM),A.addClass(le,ie),A.addClass(dj),A.addClass(SM)}var hm=fA(x1(),1);class xtA{#A;#Q=new Z7;#B;#D;#I;constructor(A,Q,B){this.#A=y1(A,"[PreConfiguredCliApiService]"),this.#I=B;let D=Q.gitlab_rails,I=new URL(D.base_url);this.#B={instanceVersion:Q.duo_workflow_service.headers["X-Gitlab-Version"]||"unknown",instanceUrl:I},this.#D={token:D.token,scopes:[],type:"pat"},this.#A.debug("Pre-configured API service created with provided token and metadata")}async initialize(){return this.#A.debug("Starting pre-configured API initialization (no API calls)"),this.#Q.fire({isInValidState:!0,instanceInfo:this.#B,tokenInfo:this.#D}),this.#A.debug("Pre-configured API initialization complete, onApiReconfigured event fired"),i4(void 0)}get instanceInfo(){return this.#B}get tokenInfo(){return this.#D}fetchFromApi(A){return this.#I.fetchFromApi(A)}fetchFromApiRaw(A){return this.#I.fetchFromApiRaw(A)}fetchOperation(A){return this.#I.fetchOperation(A)}connectToCable(){return this.#I.connectToCable()}onApiReconfigured=this.#Q.event;getSimpleClient(){return this.#I.getSimpleClient()}}class htA{#A;#Q;constructor(A,Q){this.#A=y1(A,"[PreConfiguredWorkflowTokenService]"),this.#Q=Q}async getToken(A,Q){if(!this.#Q)throw Error("Token service has been disposed");return this.#A.debug(`Returning pre-configured token for workflow "${A}", type: "${Q}"`),this.#Q}getTokenFromCache(){return this.#Q}cacheToken(A,Q,B){this.#A.warn(`Ignoring cache request for workflow "${A}", type "${Q}" - using pre-configured tokens which are immutable`)}async revokeToken(A,Q){this.#A.debug(`Ignoring revoke request for workflow "${A}" - pre-configured tokens cannot be revoked`)}dispose(){this.#Q=null,this.#A.debug("Disposed pre-configured token")}}var TRQ=fA(x1(),1);class ae extends ys{constructor(A){super(A,"[OSInformationContextProvider]")}async getItems(){try{let A=this.detectOSInfo();if(!A)return this.logger.info("No OS information detected"),[];return[{category:"os_information",content:this.#A(A),id:"os_information",metadata:{title:"Operating System",enabled:!0,subType:"os",icon:"monitor",secondaryText:this.buildOSInfoContent(A),subTypeLabel:"System Information"}}]}catch(A){return this.logger.warn("Could not detect OS information",A),[]}}#A(A){return`<os><platform>${A.platform}</platform><architecture>${A.architecture}</architecture></os>`}}ae=G1([TRQ.Injectable(fF,[T1])],ae);function jRQ(A,Q){let{workflowToken:B}=Q.command;if(Q.command.name==="run"&&B)A.add(hm.createFactoryDescriptor({aliases:[yM],factory:(I)=>new htA(I.getRequiredService(T1),B),lifetime:hm.ServiceLifetime.Singleton})),A.add(hm.createFactoryDescriptor({aliases:[b4],factory:(I)=>{return new xtA(I.getRequiredService(T1),B,new DM(Q,I.getRequiredService(T1),I.getRequiredService(XI)))},lifetime:hm.ServiceLifetime.Singleton}));else A.addClass(SM,DM);A.addClass(Q.command.name==="run"?ae:dj)}function PRQ(A,Q){if(ua()==="anthropic")RRQ(A);else jRQ(A,Q)}var lRQ=fA(dRQ(),1);import{basename as E48,join as iGA,relative as cRQ}from"node:path";var iRQ=fA(x1(),1);var pRQ=10;class oe extends syA{chatRequiredFeature="include_file_context";#A;#Q;#B;#D;#I;constructor(A,Q,B,D,I){super("local_file_search",y1(A,"[CliFileContextProvider]"));this.#A=Q,this.#Q=B,this.#B=D,this.#D=I,this.#I=w51(this.#F.bind(this),50)}#E(A){if(A.workspaceFolders&&A.workspaceFolders.length>0)return A.workspaceFolders;return[{uri:GE.file(this.#Q.cwd).toString(),name:E48(this.#Q.cwd)}]}async searchContextItems(A){if(A.query.trim()===""){let Q=this.#E(A);return this.#C(Q)}return this.#I(A)}async#C(A){this.logger.debug("Getting modified files (empty query)");let Q=await this.#A.getRepositoriesForWorkspaces(A),B=new Map,D=await Promise.all(Array.from(Q.entries()).map(async([E,C])=>{let F=GE.parse(C.uri).fsPath,J=await E.getStatus(),Y=cRQ(F,E.fsPath);return J.files.map((G)=>{let X=Y?iGA(Y,G.path):G.path;return{absolutePath:iGA(E.fsPath,G.path),relativePath:X,workspaceFolder:C}})}));for(let E of D.flat())B.set(E.absolutePath,E);let I=Array.from(B.values()).slice(0,pRQ);return this.logger.debug(`Found ${I.length} modified files`),Promise.all(I.map((E)=>this.#J(E)))}async#F(A){let Q=A.query.trim(),B=this.#E(A);this.logger.debug(`Searching for files matching: "${Q}"`);let D=await this.#A.getRepositoriesForWorkspaces(B),I=new Map,E=await Promise.all(Array.from(D.entries()).map(async([J,Y])=>{let G=GE.parse(Y.uri).fsPath,X=await J.getFiles(),z=cRQ(G,J.fsPath);return X.map((U)=>{let Z=z?iGA(z,U):U;return{absolutePath:iGA(G,Z),relativePath:Z,workspaceFolder:Y}})}));for(let J of E.flat())I.set(J.absolutePath,J);let C=Array.from(I.keys()),F=lRQ.filter(C,Q,{maxResults:pRQ});return this.logger.debug(`Found ${F.length} files matching query`),Promise.all(F.map((J)=>I.get(J)).filter((J)=>J!==void 0).map((J)=>this.#J(J)))}async#J(A){let Q=GE.file(A.absolutePath),B=[];if(await Eb(Q,this.#B))B.push(DvA);return{id:A.absolutePath,category:"file",metadata:{title:A.relativePath,enabled:B.length===0,disabledReasons:B.length>0?B:void 0,icon:"document",secondaryText:this.#Y(A.relativePath),subType:"local_file_search",subTypeLabel:"Project file",relativePath:A.relativePath,workspaceFolder:A.workspaceFolder,project:this.#D.get("projectPath")??"not a GitLab project"}}}#Y(A){if(/\s/.test(A))return`@"${A}"`;return`@${A}`}async retrieveContextItemsWithContent(){let A=await this.getSelectedContextItems();return Promise.all(A.map((Q)=>this.getItemWithContent(Q)))}async getItemWithContent(A){let{readFile:Q}=this.#B.promises,B=(await Q(A.id)).toString("utf-8");return{...A,content:B}}}oe=G1([iRQ.Injectable(p5A,[T1,M2,X9,OY,l4])],oe);async function utA(A,Q,B){let D=new _G.ServiceCollection;if(D.add(_G.createInstanceDescriptor({instance:Q,aliases:[X9]})),D.add(_G.createInstanceDescriptor({instance:B,aliases:[cH]})),A?.logDestination==="stdout")D.addClass(de);else D.addClass(kR);D.addClass(ia,gw,go,pe),D.add(_G.createFactoryDescriptor({aliases:[pr],factory:(J)=>new MCA(J,J.getRequiredService(T1)),lifetime:_G.ServiceLifetime.Singleton})),D.addClass(qc,df,cf,Vh,xo),D.addClass(Ss),D.addClass(ce,Kh),U5A(D),D.addClass(qj,ls,$h,jx,Px,pf,Kk,JN,YN,zh,gx,bx,yx,Ph,jh,fx,xx,Hh,Sx,kx,hx,Zh,vx),D.add(_G.createInstanceDescriptor({instance:{getDiagnostics:async()=>[]},aliases:[fo]})),D.add(_G.createInstanceDescriptor({instance:{isClientFlagEnabled:()=>!1,isInstanceFlagEnabled:()=>!1,updateInstanceFeatureFlags:async()=>{}},aliases:[aL]})),D.addClass(md,ud),D.addClass(Qe,Oc,Mc,Rc),D.add(_G.createInstanceDescriptor({instance:{isChatFeatureEnabled:()=>Promise.resolve(!0),isSuggestionsFeatureEnabled:()=>Promise.resolve(!0)},aliases:[Fb]})),D.addClass(CZ,$k),D.addClass(Kb,wb,Hb,Vb),D.addClass(ga,la,ka,vs,Wh,oe),D.addClass(Be),D.addClass(oH),D.addClass(ya),D.addClass(vR),D.addClass(yR),D.addClass(da),D.addClass(Ie),D.addClass(ue,Ee),PRQ(D,Q);let I=D.build();I.getRequiredService(ftA).logDebugDetails(),await I.getRequiredService(XI).initialize();let F=global;return F.__errorHandler=I.getRequiredService(jU),B.setDiContainer(I),I}var C48=process.platform==="win32",aGA=qs1(),nGA=new cH,ZO=new xeA,dtA=async(A)=>{let Q=global.__errorHandler;if(Q){let B=new tw("Duo CLI uncaught exception",A);Q.handleError(B.message,B)}else console.error("Duo CLI uncaught exception",A);await nGA.exit(1)};process.on("unhandledRejection",dtA);process.on("uncaughtException",dtA);var ctA=A2();ZO.name("duo").description("GitLab Duo for your command line").version(ctA,"-v, --version","Display version number").option("-C, --cwd <path>","change working directory",(A)=>Ps1(A),process.cwd()).addOption(new I8("--gitlab-base-url <url>","Base URL of GitLab instance").env("GITLAB_URL").default(process.env.GITLAB_BASE_URL)).addOption(new I8("--gitlab-auth-token <token>","Authentication token for GitLab instance").env("GITLAB_TOKEN").default(process.env.GITLAB_OAUTH_TOKEN)).addOption(new I8("--log-level <level>","Set logging level").choices(Object.values(AD)).env("LOG_LEVEL").default(AD.DEBUG)).addOption(new I8("--git-http-user <user>","Username for git HTTP authentication credentials").env("DUO_WORKFLOW_GIT_HTTP_USER")).addOption(new I8("--git-http-password <password>","Password for git HTTP authentication credentials").env("DUO_WORKFLOW_GIT_HTTP_PASSWORD")).addOption(new I8("--git-user-email <email>","Email for git commit attribution").env("DUO_WORKFLOW_GIT_USER_EMAIL")).addOption(new I8("--git-user-name <name>","Name for git commit attribution").env("DUO_WORKFLOW_GIT_USER_NAME")).addOption(new I8("--telemetry-enabled","Enable collection of telemetry and error events").env("DUO_WORKFLOW_TELEMETRY_ENABLED").default(!0)).hook("preAction",(A)=>{if(A.optsWithGlobals().logLevel===AD.DEBUG)sUA()});aGA.registerOptions(ZO.addOption(new I8("--existing-session-id <sessionId>","ID of existing session to resume").default(process.env.DUO_WORKFLOW_WORKFLOW_ID)).action(async(A)=>{let Q=ZO.opts(),{cwd:B,logLevel:D,gitHttpUser:I,gitHttpPassword:E,gitUserEmail:C,gitUserName:F,telemetryEnabled:J}=Q,{existingSessionId:Y}=A,G=await N3A(Q),X=await w3A();if(G.isMissingConfiguration()){BkA(G,X);return}let U=G.getDuoConfiguration(),Z=aGA.mapConfig({cliVersion:ctA,cwd:B,envInfo:X,gitHttpPassword:E,gitHttpUser:I,gitUserEmail:C,gitUserName:F,gitlabAuthToken:U.gitlabAuthToken,gitlabBaseUrl:U.gitlabBaseUrl,logLevel:D,telemetryEnabled:J,command:{name:"tui",existingSessionId:Y}},{programConfig:Q,commandConfig:A}),H=(await utA({logDestination:"file"},Z,nGA)).getRequiredService(yR);tL1(H,X,nGA)}));var F48=ZO.command("config").description("configuration management commands");F48.command("edit").description("edit duo CLI configuration").action(async()=>{let A=await N3A(),Q=await w3A();BkA(A,Q)});var oGA=ZO.command("log").description("log management commands");oGA.command("last").description("open the last log file").action(()=>{hJ1()});oGA.command("list").description("list all log files").action(()=>{mJ1()});oGA.command("tail [args...]").description(`tail the last log file. "args" can be any standard ${C48?'PowerShell "Get-Content"':'"tail"'} arguments`).allowUnknownOption().action((A)=>uJ1(A||[]));oGA.command("clear").description("remove all existing log files").action(()=>{dJ1()});aGA.registerOptions(ZO.command("run").description("Run a workflow in non-interactive / headless mode").addOption(new I8("-g, --goal <goal>","Goal/prompt for the session").default(process.env.DUO_WORKFLOW_GOAL).makeOptionMandatory()).addOption(new I8("--ai-context-items <contextItems>","JSON encoded array of additional context items").env("DUO_WORKFLOW_ADDITIONAL_CONTEXT_CONTENT").argParser((A)=>Ss1(A))).action(async(A)=>{let Q=ZO.opts(),{cwd:B,existingSessionId:D,gitHttpPassword:I,gitHttpUser:E,gitUserEmail:C,gitUserName:F,logLevel:J,telemetryEnabled:Y}=Q,{goal:G,aiContextItems:X}=A,U=(await N3A(Q)).getDuoConfiguration(),Z=await w3A();if(!U.gitlabAuthToken)throw new VW("--gitlab-auth-token / GITLAB_AUTH_TOKEN option is required.");let K=aGA.mapConfig({cliVersion:ctA,cwd:B,gitlabBaseUrl:U.gitlabBaseUrl,gitlabAuthToken:U.gitlabAuthToken,logLevel:J,envInfo:Z,gitHttpUser:E,gitHttpPassword:I,gitUserEmail:C,gitUserName:F,telemetryEnabled:Y,command:{name:"run",goal:G,aiContextItems:X,existingSessionId:D}},{programConfig:Q,commandConfig:A}),W=(await utA({logDestination:"stdout"},K,nGA)).getRequiredService(vR);await W.initialize(),await W.execute()}));try{await ZO.parseAsync(process.argv)}catch(A){await dtA(A)}
2082
2082
 
2083
- //# debugId=2EF0A8D36680D8CC64756E2164756E21
2083
+ //# debugId=4716A078D2F344EB64756E2164756E21
2084
2084
  //# sourceMappingURL=index.js.map