@gitkraken/provider-apis 0.52.0 → 0.53.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,5 +1,5 @@
1
- "use strict";var dt=Object.defineProperty;var Ps=Object.getOwnPropertyDescriptor;var ws=Object.getOwnPropertyNames;var Ss=Object.prototype.hasOwnProperty;var qs=(r,n)=>{for(var e in n)dt(r,e,{get:n[e],enumerable:!0})},vs=(r,n,e,t)=>{if(n&&typeof n=="object"||typeof n=="function")for(let s of ws(n))!Ss.call(r,s)&&s!==e&&dt(r,s,{get:()=>n[s],enumerable:!(t=Ps(n,s))||t.enumerable});return r};var Es=r=>vs(dt({},"__esModule",{value:!0}),r);var wo={};qs(wo,{AzureDevOps:()=>he,Bitbucket:()=>fe,BitbucketServer:()=>Re,EntityIdentifierProviderType:()=>hs,EntityType:()=>gs,EntityVersion:()=>ms,GitBuildStatusStage:()=>er,GitBuildStatusState:()=>Te,GitDiffLineType:()=>ct,GitHub:()=>Ie,GitHubIssueCloseReason:()=>fs,GitIssueState:()=>ue,GitLab:()=>ye,GitMergeStrategy:()=>ce,GitPullRequestMergeableState:()=>ie,GitPullRequestReviewState:()=>ee,GitPullRequestState:()=>Y,GraphQLErrors:()=>I,Jira:()=>Pe,JiraServer:()=>we,PullRequestAsyncStatus:()=>cs,Trello:()=>Se,default:()=>Po,isFetch:()=>Oe});module.exports=Es(wo);var gr=require("diff");var er=(s=>(s.Build="build",s.Production="production",s.Staging="staging",s.Test="test",s))(er||{}),Te=(d=>(d.ActionRequired="ACTION_REQUIRED",d.Cancelled="CANCELLED",d.Error="ERROR",d.Failed="FAILED",d.Pending="PENDING",d.Running="RUNNING",d.Skipped="SKIPPED",d.Success="SUCCESS",d.Warning="WARNING",d.OptionalActionRequired="OPTIONAL_ACTION_REQUIRED",d))(Te||{}),ce=(o=>(o.MergeCommit="MERGE_COMMIT",o.Rebase="REBASE",o.RebaseThenMergeCommit="REBASE_THEN_MERGE_COMMIT",o.FastForward="FAST_FORWARD",o.Squash="SQUASH",o))(ce||{}),Y=(t=>(t.Open="OPEN",t.Closed="CLOSED",t.Merged="MERGED",t))(Y||{}),ee=(s=>(s.Approved="APPROVED",s.ChangesRequested="CHANGES_REQUESTED",s.Commented="COMMENTED",s.ReviewRequested="REVIEW_REQUESTED",s))(ee||{}),ie=(u=>(u.Behind="BEHIND",u.Blocked="BLOCKED",u.Conflicts="CONFLICTS",u.FailingChecks="FAILING_CHECKS",u.Mergeable="MERGEABLE",u.Unknown="UNKNOWN",u.UnknownAndBlocked="UNKNOWN_AND_BLOCKED",u.Unstable="UNSTABLE",u))(ie||{}),ct=(t=>(t.ADDED="ADDED",t.DELETED="DELETED",t.UNMODIFIED="UNMODIFIED",t))(ct||{});var tr={APPROVED:0,COMMENTED:1,REVIEW_REQUESTED:2,CHANGES_REQUESTED:3},B=r=>!r||r.length===0?null:r.reduce((n,e)=>tr[e.state]>tr[n]?e.state:n,"APPROVED");var Cs=new Set(["ECONNABORTED","ECONNREFUSED","ECONNRESET","EAI_AGAIN","ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"]),R=(r,n)=>{let e={};return r&&(e.Authorization=`${n?"Basic":"Bearer"} ${r}`),e},nr=r=>r?r.reduce((n,e)=>(n[e]=!0,n),{}):void 0,te=(r,n,e)=>!r||n.some(t=>r[t])?e:"",or=async r=>{let n=[],e=!0,t;for(;e;){let s=await r(t);n=n.concat(s.data),e=!!s?.pageInfo?.hasNextPage,t=s?.pageInfo?.endCursor||s?.pageInfo?.nextPage}return n};async function mt(r){return(await Promise.allSettled(r)).map(e=>Us(e)).filter(e=>e!=null)}var A=(r,{fallback:n,max:e})=>!r||r<=0?n:e===void 0?r:Math.min(r,e),k=(r,n)=>{if(!n||n.length===0)return r;let e=new Set(n);return r.filter(t=>e.has(t.state))},$s=r=>{if(!(!r||typeof r!="object")){if("statusCode"in r&&typeof r.statusCode=="number")return r.statusCode;if("response"in r&&r.response&&typeof r.response=="object"&&"status"in r.response&&typeof r.response.status=="number")return r.response.status}},Ds=r=>{if(!(!r||typeof r!="object"||!("code"in r)||typeof r.code!="string"))return r.code},ir=r=>{if(typeof r=="string")return r;if(r instanceof Error)return r.message},Ls=r=>{let n=$s(r);if(n===401)return"authentication";if(n===404)return"not-found";if(n===429)return"rate-limit";if(n!==void 0)return"provider";let e=Ds(r);if(e&&Cs.has(e))return"network";let t=ir(r)?.toLowerCase();return t&&(t.includes("network")||t.includes("fetch failed")||t.includes("timed out")||t.includes("timeout")||t.includes("econn")||t.includes("enotfound")||t.includes("eai_again"))?"network":"unknown"},As=(r,n)=>{let e=ir(n);return{scope:r,kind:Ls(n),...e?{message:e}:{}}},me=(r,n=[])=>({completeness:r,...n.length?{failures:n}:{}}),rr={complete:0,unknown:1,partial:2},sr=(r,n)=>rr[r]>=rr[n]?r:n,ae=r=>r?r.id||`${r.namespace}/${r.name}`:void 0;async function J(r,{run:n,failureScope:e,completeness:t}){let s=await Promise.all(r.map(async u=>{try{return{scope:u,result:await n(u)}}catch(l){return{scope:u,error:l}}})),o=[],i=[],a="complete";return s.forEach(u=>{if("error"in u){o.push(As(e(u.scope),u.error)),a=sr(a,"partial");return}if(u.result===void 0)return;let l=u.result;a=sr(a,t?t(l):"complete"),i.push({scope:u.scope,result:l})}),{successes:i,metadata:me(a,o)}}function Us(r,n=void 0){return r?.status==="fulfilled"?r.value:n}async function ar(r,n,e){if(!Number.isFinite(n)||!Number.isInteger(n)||n<=0)throw new Error("batchSize must be a positive integer");for(let t=0;t<r.length;t+=n){let s=r.slice(t,t+n);await Promise.all(s.map(e))}}var ue=(e=>(e.Open="OPEN",e.Closed="CLOSED",e))(ue||{});var gt=(a=>(a[a.Unknown=0]="Unknown",a[a.Active=1]="Active",a[a.Fixed=2]="Fixed",a[a.WontFix=3]="WontFix",a[a.Closed=4]="Closed",a[a.ByDesign=5]="ByDesign",a[a.Pending=6]="Pending",a))(gt||{});var L=100;var ur=globalThis.fetch;var Gs=async r=>{let n=r.headers.get("content-type")||"",e=null;if(n.startsWith("application/json")){let o=await r.text();e=o.trim().length>0?JSON.parse(o):null}else if(n.startsWith("text/")||n===""||n.startsWith("application/vnd.github.diff")||n.startsWith("application/vnd.github.patch"))e=await r.text();else if(n.startsWith("application/vnd.github.raw+json")||n.startsWith("application/octet-stream"))e=await r.arrayBuffer();else throw new Error(`Unsupported content-type: ${n}`);let t={};r.headers.forEach((o,i)=>{t[i]=o});let s={body:e,headers:t,status:r.status,statusText:r.statusText};if(!r.ok){let o=new Error(r.statusText);throw Object.assign(o,{response:s}),o}return s},ht=r=>async({url:n,...e})=>{let t=await r(n,e);return Gs(t)};var Oe=(r,n=!1)=>r.name==="fetch"||n;var j=class{constructor(n){let e=n?.request||ur;this.config={...n,request:Oe(e,n?.forceIsFetch)?ht(e):e}}updateConfig(n){this.config={...this.config,...n,request:n.request&&Oe(n.request,n?.forceIsFetch??this.config.forceIsFetch)?ht(n.request):this.config.request}}},N=class extends j{};var Ts="https://app.vssps.visualstudio.com/_apis",Os="https://vssps.dev.azure.com/",_s="https://dev.azure.com",S=(r,n={})=>R(n.token||r.token,n.isPAT||r.isPAT),lr=r=>r.url.replace("/_apis/git/repositories/","/_git/").replace(`/${r.repository.project.id}/`,`/${encodeURIComponent(r.repository.project.name)}/`).replace(`/${r.repository.id}/`,`/${encodeURIComponent(r.repository.name)}/`).replace("/pullRequests/","/pullrequest/"),ft=(r,n)=>{let e=n.baseUrl||r.baseUrl||Ts;return e=e.replace(/\/$/,""),e},C=(r,n)=>{let e=n.baseUrl||r.baseUrl||_s;return e=e.replace(/\/$/,""),e},Rt=(r,n)=>{let e=n.baseUrl||r.baseUrl||Os;return e=e.replace(/\/$/,""),e};var xs={active:"OPEN",completed:"MERGED",abandoned:"CLOSED"},ks={OPEN:"active",MERGED:"completed",CLOSED:"abandoned"},ge=100,Ns=200,Fs=200,pr=r=>{if(!r||r.length===0)return"active";let n=Array.from(new Set(r.map(e=>ks[e])));return n.length===1?n[0]:"all"},js=r=>{if(!r||r.length===0)return["[Microsoft.VSTS.Common.ClosedDate] = ''","[Microsoft.VSTS.Common.ResolvedDate] = ''"];let n=new Set(r),e=n.has("OPEN"),t=n.has("CLOSED");return e&&t?[]:t?["([Microsoft.VSTS.Common.ClosedDate] <> '' OR [Microsoft.VSTS.Common.ResolvedDate] <> '')"]:["[Microsoft.VSTS.Common.ClosedDate] = ''","[Microsoft.VSTS.Common.ResolvedDate] = ''"]},Qs=r=>{if(typeof r!="string")return r;let n=r.charAt(0).toUpperCase()+r.slice(1);return gt[n]??0},Bs=new Set([2,3,4,5]),Ms={10:"APPROVED",5:"APPROVED",0:"REVIEW_REQUESTED",[-5]:"CHANGES_REQUESTED",[-10]:"CHANGES_REQUESTED"},le=r=>({id:r.id,name:r.displayName??null,username:(r.uniqueName||r.displayName)??null,email:null,avatarUrl:r.imageUrl??null,url:null}),_e=r=>r.startsWith("refs/heads/")?r.replace("refs/heads/",""):r,zs=r=>{switch(r){case"conflicts":return"CONFLICTS";case"failure":return"FAILING_CHECKS";case"rejectedByPolicy":return"BLOCKED";case"succeeded":return"MERGEABLE";case"notSet":case"queued":default:return"UNKNOWN"}},It=(r,n,e,t,s,o)=>`${r}|${n}|${e}|${t}|${s}|${o}`,dr=r=>{let n=r.split("|");if(n.length!==6)throw new Error("Invalid Azure comment ID format");return{namespace:n[0],project:n[1],repoName:n[2],prId:n[3],threadId:n[4],commentId:n[5]}},cr=(r,n,e,t,s)=>`${r}|${n}|${e}|${t}|${s}`,bt=r=>{let n=r.split("|");if(n.length!==5)throw new Error("Invalid Azure thread ID format");return{namespace:n[0],project:n[1],repoName:n[2],prId:n[3],threadId:n[4]}},ve=(r,n,e)=>{let t=!!n.forkSource,s=[],o=[];return n.reviewers.forEach(i=>{let a={reviewer:le(i),state:Ms[i.vote??0]||"REVIEW_REQUESTED"};i.isRequired&&s.push(a),o.push(a)}),{id:n.pullRequestId.toString(),title:n.title,description:n.description??null,number:n.codeReviewId,state:xs[n.status],isDraft:n.isDraft,commentCount:null,upvoteCount:null,author:le(n.createdBy),createdDate:new Date(n.creationDate),updatedDate:new Date(n.closedDate||n.creationDate),closedDate:n.closedDate?new Date(n.closedDate):null,mergedDate:n.closedDate&&n.status==="completed"?new Date(n.closedDate):null,isCrossRepository:t,repository:{id:n.repository.id,name:n.repository.name,project:n.repository.project.name,owner:{login:r},remoteInfo:e?.get(n.repository.id)??null},headCommit:{buildStatuses:null},baseRef:{name:_e(n.targetRefName),oid:n.lastMergeTargetCommit.commitId},headRef:{name:_e(n.sourceRefName),oid:n.lastMergeSourceCommit.commitId},url:lr(n),assignees:n.reviewers.map(le),reviews:o,reviewDecision:B(s),additions:null,deletions:null,fileCount:null,commitCount:null,headRepository:n.forkSource?{id:n.forkSource.repository.id,name:n.forkSource.repository.name,project:void 0,owner:{login:r},remoteInfo:e?.get(n.forkSource.repository.id)??null,isFork:!0}:{id:n.repository.id,name:n.repository.name,project:n.repository.project.name,owner:{login:r},remoteInfo:e?.get(n.repository.id)??null,isFork:!1},mergeableState:zs(n.mergeStatus),labels:n.labels?.map(i=>({color:null,description:null,id:i.id,name:i.name}))??[],permissions:null}},mr=(r,n)=>({id:n.id,name:n.name,namespace:r,project:n.project.name,projectId:n.project.id,webUrl:n.webUrl,httpsUrl:n.remoteUrl,sshUrl:n.sshUrl,defaultBranch:n.defaultBranch?{name:_e(n.defaultBranch)}:null,permissions:null}),Hs=(r,n,e,t)=>{let s=e.fields,o=s["System.AssignedTo"],i=s["System.State"],a=s["System.WorkItemType"],u;return i&&a&&(u=t[a]?.[i]),{id:e.id.toString(),number:e.id.toString(),title:s["System.Title"],commentCount:s["System.CommentCount"],author:{avatarUrl:s["System.CreatedBy"]._links?.avatar?.href??null,email:null,id:s["System.CreatedBy"].id,name:s["System.CreatedBy"].uniqueName??null,username:s["System.CreatedBy"].displayName??null,url:null},closedDate:s["Microsoft.VSTS.Common.ClosedDate"]?new Date(s["Microsoft.VSTS.Common.ClosedDate"]):null,createdDate:new Date(s["System.CreatedDate"]),updatedDate:new Date(s["System.ChangedDate"]),url:e._links.html.href,assignees:o?[{avatarUrl:o._links?.avatar?.href??null,email:null,id:o.id,name:o.uniqueName??null,username:o.displayName??null,url:null}]:[],description:s["System.Description"]??null,state:{name:u?.title||i,color:null},type:s["System.WorkItemType"],repository:null,project:{namespace:r,name:n,resourceId:null,key:null,id:null},upvoteCount:0,labels:e.fields["System.Tags"]?.split(";").map(l=>({color:null,description:null,id:null,name:l.trim()}))??[]}},he=class extends N{constructor(){super(...arguments);this.cachedUserIds=new Map;this.inflightUserIds=new Map}getCurrentUserId(e,t){let s=JSON.stringify([e,t.token??null,t.isPAT??this.config.isPAT??!1,t.baseUrl??null]),o=this.cachedUserIds.get(s);if(o)return Promise.resolve(o);let i=this.inflightUserIds.get(s);if(i)return i;let a=this.fetchCurrentUserId(e,t,s);return this.inflightUserIds.set(s,a),a}async fetchCurrentUserId(e,t,s){try{let o=await this.getCurrentUserForInstance({namespace:e},t);return this.cachedUserIds.set(s,o.data.id),o.data.id}finally{this.inflightUserIds.delete(s)}}getRepoApiUrl(e,t,s,o){return`${C(this.config,o)}/${encodeURIComponent(e)}/${encodeURIComponent(t)}/_apis/git/repositories/${encodeURIComponent(s)}`}async getCurrentUser(e={},t={}){if(t.isPAT||this.config.isPAT)throw new Error("Azure DevOps does not support PATs for this function.");let s=`${ft(this.config,t)}/profile/profiles/me`,o=await this.config.request({url:s,headers:S(this.config,t)});return{data:{id:o.body.id,name:o.body.displayName,username:o.body.displayName,email:o.body.emailAddress,avatarUrl:null,url:null}}}async getCurrentUserForInstance(e,t={}){let o=(await this.config.request({url:`${C(this.config,t)}/${encodeURIComponent(e.namespace)}/_apis/ConnectionData`,headers:S(this.config,t)})).body.authorizedUser;if(o.providerDisplayName==="Anonymous")throw new Error("Current user not found.");return{data:{id:o.id,name:o.providerDisplayName,username:o.providerDisplayName,email:o.properties.Account.$value,avatarUrl:null,url:null}}}async getUserForCommit(e,t={}){if(!e.repo.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let o=(await this.config.request({url:`${C(this.config,t)}/${encodeURIComponent(e.repo.namespace)}/${encodeURIComponent(e.repo.project)}/_apis/git/repositories/${encodeURIComponent(e.repo.name)}/commits/${e.oid}`,headers:S(this.config,t)})).body.author;return{data:{name:o.name,email:o.email,avatarUrl:o.imageUrl}}}async getOrgsForUser(e,t={}){let s=`${ft(this.config,t)}/accounts?memberId=${e.userId}&api-version=6.0`;return{data:(await this.config.request({url:s,headers:S(this.config,t)})).body.value.map(i=>({id:i.accountId,name:i.accountName}))}}async getCollectionsForUser(e,t={}){let s=`${C(this.config,t)}/_apis/projectCollections`;return{data:(await this.config.request({url:s,headers:S(this.config,t)})).body.value.map(i=>({id:i.id,name:i.name}))}}async getAzureProjects(e,t={}){let s=new URL(`${C(this.config,t)}/${encodeURIComponent(e.namespace)}/_apis/projects`);s.searchParams.set("$top",L.toString()),e.cursor&&s.searchParams.set("$skip",e.cursor);let o=await this.config.request({url:s.toString(),headers:S(this.config,t)}),i=o.headers["x-ms-continuationtoken"];return{pageInfo:{hasNextPage:!!i,endCursor:i||null},data:o.body.value.map(a=>({id:a.id,name:a.name,namespace:e.namespace}))}}async getAzureProjectScopeDescriptor(e,t={}){let{namespace:s,projectId:o}=e;return{data:{scope:(await this.config.request({url:`${Rt(this.config,t)}/${encodeURIComponent(s)}/_apis/graph/descriptors/${o}?api-version=6.0`,headers:S(this.config,t)})).body.value}}}async getAzureGraphAccountsForAzureProject(e,t={}){let{namespace:s,projectScopeDescriptor:o,cursor:i}=e,a=new URL(`${Rt(this.config,t)}/${encodeURIComponent(s)}/_apis/graph/users`);o&&a.searchParams.set("scopeDescriptor",o),i&&a.searchParams.set("continuationToken",i);let u=await this.config.request({url:a.toString(),headers:S(this.config,t)}),l=u.headers["x-ms-continuationtoken"];return{pageInfo:{endCursor:l||null,hasNextPage:!!l},data:u.body.value.map(d=>({avatarUrl:d._links?.avatar?.href??null,descriptor:d.descriptor??null,email:d.mailAddress??null,name:d.displayName??null,storageKeyURL:d._links?.storageKey?.href??null,username:d.displayName??null}))}}async getAccountFromAzureGraphAccount(e,t={}){let{azureGraphAccount:s}=e;if(!s.storageKeyURL)throw new Error("Expected 'storageKeyURL' to not be null for 'azureGraphAccount'");let o=await this.config.request({url:s.storageKeyURL,headers:S(this.config,t)});return{data:{avatarUrl:s.avatarUrl,email:s.email,id:o.body.value,name:s.name,username:s.username,url:null}}}async getAccountsFromAzureGraphAccounts(e,t={}){let s=[];for(let o of e.azureGraphAccounts){let i=await this.getAccountFromAzureGraphAccount({azureGraphAccount:o},t);s.push(i.data)}return{data:s}}async getRepo(e,t={}){if(!e.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let s=await this.config.request({url:`${C(this.config,t)}/${encodeURIComponent(e.namespace)}/${encodeURIComponent(e.project)}/_apis/git/repositories/${encodeURIComponent(e.name)}`,headers:S(this.config,t)});return{data:mr(e.namespace,s.body)}}async getRepos(e,t={}){let s=[],o=[];return await Promise.all(e.map(async i=>{try{let a=await this.getRepo(i,t);s.push(a.data)}catch(a){o.push({input:i,error:a})}})),{data:s,errors:o}}async getReposForAzureProject(e,t={}){if(!e.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');return{data:(await this.config.request({url:`${C(this.config,t)}/${encodeURIComponent(e.namespace)}/${encodeURIComponent(e.project)}/_apis/git/repositories`,headers:S(this.config,t)})).body.value.map(o=>mr(e.namespace,o))}}async getRefs(e,t,s={}){if(!t.repo.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let o=new URL(`${C(this.config,s)}/${encodeURIComponent(t.repo.namespace)}/${encodeURIComponent(t.repo.project)}/_apis/git/repositories/${encodeURIComponent(t.repo.name)}/refs`);o.searchParams.set("filter",e),o.searchParams.set("$top",L.toString()),t.cursor&&o.searchParams.set("continuationToken",t.cursor);let i=await this.config.request({url:o.toString(),headers:S(this.config,s)}),a=i.headers["x-ms-continuationtoken"];return{pageInfo:{hasNextPage:!!a,endCursor:a||null},data:i.body.value.map(u=>({name:_e(u.name),commit:{oid:u.objectId,authoredDate:null,committedDate:null}}))}}async getBranches(e,t={}){return this.getRefs("heads",e,t)}async getTags(e,t={}){return this.getRefs("tags",e,t)}async fetchRemoteInfoByRepoId(e,t,s){let o=new Map;if(!e)return o;let i=new Map;for(let{namespace:a,pullRequests:u}of t)for(let l of u)i.has(l.repository.id)||i.set(l.repository.id,a),l.forkSource&&!i.has(l.forkSource.repository.id)&&i.set(l.forkSource.repository.id,a);return await ar([...i],10,async([a,u])=>{try{let l=await this.config.request({url:`${C(this.config,s)}/${encodeURIComponent(u)}/_apis/git/repositories/${encodeURIComponent(a)}`,headers:S(this.config,s)}),{remoteUrl:d,sshUrl:p}=l.body;d&&p&&o.set(a,{cloneUrlHTTPS:d,cloneUrlSSH:p})}catch{}}),o}async getPullRequestsForRepoBase(e,t={},s=ge){let{page:o,repo:i,assigneeLogins:a,authorLogin:u,reviewerId:l}=e||{},d=o||1;if(!i.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let p=A(e.pageSize,{fallback:s}),c=l??(a&&a.length?a[0]:void 0),g=`searchCriteria.status=${pr(e.states)}`;return c&&(g+=`&searchCriteria.reviewerId=${encodeURIComponent(c)}`),u&&(g+=`&searchCriteria.creatorId=${encodeURIComponent(u)}`),await this.config.request({url:`${C(this.config,t)}/${encodeURIComponent(i.namespace)}/${encodeURIComponent(i.project||"")}/_apis/git/repositories/${encodeURIComponent(i.name)}/pullRequests?${g}&%24top=${p}&%24skip=${(d-1)*p}`,headers:S(this.config,t)})}async getPullRequestsForRepo(e,t={}){let s=A(e.pageSize,{fallback:ge}),o=e.page||1,i=await this.getPullRequestsForRepoBase(e,t,s),a=i.body.value.length===s,u=await this.fetchRemoteInfoByRepoId(e.includeRemoteInfo,[{namespace:e.repo.namespace,pullRequests:i.body.value}],t);return{pageInfo:{hasNextPage:a,nextPage:a?o+1:null,currentPage:o},data:k(i.body.value.map(l=>ve(e.repo.namespace,l,u)),e.states)}}async getPullRequestsForRepos(e,t={}){if(!e.repos.every(p=>p.project))throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let{repos:s}=e||{},o=A(e.pageSize,{fallback:ge}),{successes:i,metadata:a}=await J(s,{run:p=>this.getPullRequestsForRepoBase({repo:p,assigneeLogins:e.assigneeLogins,authorLogin:e.authorLogin,reviewerId:e.reviewerId,states:e.states,pageSize:o},t,o),failureScope:p=>({providerId:"azure",projectId:p.project,repositoryId:ae(p)}),completeness:p=>p.body.value.length===o?"unknown":"complete"}),u=i.map(({scope:p,result:c})=>({namespace:p.namespace,pullRequests:c.body.value})),l=await this.fetchRemoteInfoByRepoId(e.includeRemoteInfo,u,t),d=u.flatMap(({namespace:p,pullRequests:c})=>c.map(g=>ve(p,g,l)));return{data:k(d,e.states),metadata:a}}async getPullRequestsForProjectBase(e,t={},s=ge){let{namespace:o,project:i,page:a,assigneeLogins:u,authorLogin:l,reviewerId:d,repo:p}=e;if(p?.project&&p.project!==i)throw new Error("Could not fetch pull requests, project mismatch");let c=a||1,g=A(e.pageSize,{fallback:s}),m=d??(u&&u.length?u[0]:void 0),h=new URL(`${C(this.config,t)}/${encodeURIComponent(o)}/${encodeURIComponent(i)}/_apis/git/pullRequests`);return h.searchParams.set("searchCriteria.status",pr(e.states)),h.searchParams.set("$top",g.toString()),h.searchParams.set("$skip",((c-1)*g).toString()),p?.id&&p?.project===i&&h.searchParams.set("searchCriteria.repositoryId",p.id),m&&h.searchParams.set("searchCriteria.reviewerId",m),l&&h.searchParams.set("searchCriteria.creatorId",l),await this.config.request({url:h.toString(),headers:S(this.config,t)})}async getPullRequestsForProject(e,t={}){let s=A(e.pageSize,{fallback:ge}),o=e.page||1,i=await this.getPullRequestsForProjectBase(e,t,s),a=i.body.value.length===s,u=await this.fetchRemoteInfoByRepoId(e.includeRemoteInfo,i?[{namespace:e.namespace,pullRequests:i.body.value}]:[],t);return{pageInfo:{hasNextPage:a,nextPage:a?o+1:null,currentPage:o},data:k(i?.body.value.map(l=>ve(e.namespace,l,u))||[],e.states)}}async getPullRequestsForProjects(e,t={}){let{projects:s}=e||{};if(e.repo&&!e.repo.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let o=A(e.pageSize,{fallback:ge}),{successes:i,metadata:a}=await J(s,{run:p=>e.repo&&e.repo.project!==p.project?Promise.resolve(void 0):this.getPullRequestsForProjectBase({...p,assigneeLogins:e.assigneeLogins,authorLogin:e.authorLogin,reviewerId:e.reviewerId,states:e.states,pageSize:o,repo:e.repo},t,o),failureScope:p=>({providerId:"azure",projectId:p.project,repositoryId:ae(e.repo)}),completeness:p=>p.body.value.length===o?"unknown":"complete"}),u=i.map(({scope:p,result:c})=>({namespace:p.namespace,pullRequests:c.body.value})),l=await this.fetchRemoteInfoByRepoId(e.includeRemoteInfo,u,t),d=u.flatMap(({namespace:p,pullRequests:c})=>c.map(g=>ve(p,g,l)));return{data:k(d,e.states),metadata:a}}async getAzurePullRequestLastMergeStatus(e,t={}){if(!e.repo.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let{repo:{namespace:s,project:o,name:i},pullRequestId:a}=e,u=await this.config.request({url:`${C(this.config,t)}/${encodeURIComponent(s)}/${encodeURIComponent(o||"")}/_apis/git/repositories/${i}/pullrequests/${a}?includeCommits=true?api-version=6.0`,headers:{...S(this.config,t)}});if(!u.body.mergeStatus)throw new Error("Could not fetch pull request");return{data:u.body.mergeStatus}}async updatePullRequest(e,t,s){return await this.config.request({method:"PATCH",url:`${C(this.config,s)}/${encodeURIComponent(e.repository.owner.login)}/${encodeURIComponent(e.repository.project)}/_apis/git/repositories/${e.repository.name}/pullrequests/${e.id}?api-version=6.0`,body:t,headers:{...S(this.config,s),"Content-Type":"application/json"}})}async closePullRequest(e,t={}){let{pullRequest:s}=e,o={status:"abandoned"};if(!(await this.updatePullRequest(s,JSON.stringify(o),t)).body.status)throw new Error("Could not close pull request")}async mergePullRequest(e,t={}){let{pullRequest:s,mergeStrategy:o}=e,i;switch(o){case"MERGE_COMMIT":{i="noFastForward";break}case"REBASE":{i="rebase";break}case"REBASE_THEN_MERGE_COMMIT":{i="rebaseMerge";break}case"SQUASH":{i="squash";break}}let a={completionOptions:{mergeStrategy:i},lastMergeSourceCommit:{commitId:s.headRef?.oid},status:"completed"};if(!(await this.updatePullRequest(s,JSON.stringify(a),t)).body.status)throw new Error("Could not merge pull request")}async addPullRequestLabel(e,t={}){let{pullRequest:s,label:o}=e;if(!s.repository.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let i={name:o.name};if(!(await this.config.request({method:"POST",url:`${C(this.config,t)}/${encodeURIComponent(s.repository.owner.login)}/${encodeURIComponent(s.repository.project)}/_apis/git/repositories/${s.repository.name}/pullrequests/${s.id}/labels?api-version=6.0`,body:JSON.stringify(i),headers:{...S(this.config,t),"Content-Type":"application/json"}})).body.id)throw new Error("Could not add pull request label")}async removePullRequestLabel(e,t={}){let{pullRequest:s,label:o}=e;if(!s.repository.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');await this.config.request({method:"DELETE",url:`${C(this.config,t)}/${encodeURIComponent(s.repository.owner.login)}/${encodeURIComponent(s.repository.project)}/_apis/git/repositories/${s.repository.name}/pullrequests/${s.id}/labels/${encodeURIComponent(o.name)}?api-version=6.0`,headers:{...S(this.config,t)}})}async setPullRequestLabels(e,t={}){let{pullRequest:s,labels:o}=e;if(!s.repository.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let i=s.labels;if(!i)throw new Error('Azure DevOps requires "labels" for this function.');for(let a of o)i.find(u=>u.id===a.id)||await this.addPullRequestLabel({pullRequest:s,label:a},t);for(let a of i)o.find(u=>a.id===u.id)||await this.removePullRequestLabel({pullRequest:s,label:a},t)}async setPullRequestAsDraft(e,t={}){let{pullRequest:s,isDraft:o}=e,i={isDraft:o};if(!(await this.updatePullRequest(s,JSON.stringify(i),t)).body.status)throw new Error("Could not set the pull request as draft")}async addPullRequestReviewer(e,t={}){let{pullRequest:s,reviewer:o,isRequired:i}=e,a={id:o.id,isRequired:i};if(!(await this.config.request({method:"PUT",url:`${C(this.config,t)}/${encodeURIComponent(s.repository.owner.login)}/${encodeURIComponent(s.repository.project)}/_apis/git/repositories/${s.repository.name}/pullrequests/${s.id}/reviewers/${o.id}?api-version=6.0`,body:JSON.stringify(a),headers:{...S(this.config,t),"Content-Type":"application/json"}})).body.id)throw new Error("Could not add pull request reviewer")}async removePullRequestReviewer(e,t={}){let{pullRequest:s,reviewer:o}=e;await this.config.request({method:"DELETE",url:`${C(this.config,t)}/${encodeURIComponent(s.repository.owner.login)}/${encodeURIComponent(s.repository.project)}/_apis/git/repositories/${s.repository.name}/pullrequests/${s.id}/reviewers/${o.id}?api-version=6.0`,headers:{...S(this.config,t),Accept:"application/json"}})}async setPullRequestReviewers(e,t={}){let{pullRequest:s,reviewers:o}=e;for(let i of o)s.assignees.find(a=>a.id===i.id)||await this.addPullRequestReviewer({pullRequest:s,reviewer:i,isRequired:!0},t);for(let i of s.assignees)o.find(a=>i.id===a.id)||await this.removePullRequestReviewer({pullRequest:s,reviewer:i},t)}async getIssuesForAzureProject(e,t={}){let{page:s,assigneeLogins:o,authorLogin:i,mentionLogin:a,labelNames:u,statusByWorkItemIdByStatusId:l}=e||{},d=s||1,p=Math.min(A(e.pageSize,{fallback:Ns}),Fs),c=["[System.TeamProject] = @project",...js(e.states)];i&&c.push(`[System.CreatedBy] = '${i.replace("'","''")}'`),o&&o[0]&&c.push(`[System.AssignedTo] = '${o[0].replace("'","''")}'`),a&&c.push("[System.Id] IN (@recentMentions)"),u&&u.forEach(D=>c.push(`[System.Tags] Contains '${D}'`));let g=`Select [Microsoft.VSTS.Common.ClosedDate], [Microsoft.VSTS.Common.ResolvedDate] From WorkItems Where ${c.join(" AND ")} order by [System.CreatedDate] desc`,m=await this.config.request({url:`${C(this.config,t)}/${encodeURIComponent(e.namespace)}/${encodeURIComponent(e.project)}/_apis/wit/wiql?api-version=6.0`,body:JSON.stringify({query:g}),method:"POST",headers:{...S(this.config,t),"Content-Type":"application/json"}}),h=m.body.workItems.slice((d-1)*p,p*d).map(D=>D.id),y=m.body.workItems.length,f=Math.ceil(y/p),P=y>p*d;if(h.length===0)return{pageInfo:{hasNextPage:!1,nextPage:null,currentPage:d,totalCount:y,totalPages:f},data:[]};let q=await this.config.request({url:`${C(this.config,t)}/${encodeURIComponent(e.namespace)}/${encodeURIComponent(e.project)}/_apis/wit/workitemsbatch?api-version=6.0`,body:JSON.stringify({ids:h,$expand:"Links"}),method:"POST",headers:{...S(this.config,t),"Content-Type":"application/json"}});return{pageInfo:{hasNextPage:P,nextPage:P?d+1:null,currentPage:d,totalCount:y,totalPages:f},data:q.body.value.map(D=>Hs(e.namespace,e.project,D,l||{}))}}async getPermissionsForRepos(e,t={}){let{namespace:s,repos:o}=e,i={4:["canPush","canCreateWebhook"],1024:["isAdmin"],2048:["isAdmin"],4096:["isAdmin"],8192:["isAdmin"]},a=p=>{let c="2e9eb7ed-3c0a-47d4-87c1-0ffdd275fd87",g=`repoV2/${p.projectId}/${p.id}`;return Object.keys(i).map(m=>({securityNamespaceId:c,token:g,permissions:m}))},u={alwaysAllowAdministrators:!1,evaluations:o.flatMap(a)};return{data:(await this.config.request({method:"POST",url:`${C(this.config,t)}/${encodeURIComponent(s)}/_apis/security/permissionevaluationbatch?api-version=7.0`,body:JSON.stringify(u),headers:{...S(this.config,t),"Content-Type":"application/json"}})).body.evaluations.reduce((p,c)=>{let[,g,m]=c.token.split("/"),h=`${g}/${m}`,y=i[c.permissions];for(let f of y)p[h]===void 0&&(p[h]={canCreateWebhook:!0,canPush:!0,isAdmin:!0}),c.value===!1&&(p[h][f]=!1);return p},{})}}async decorateReposWithPermissions(e,t={}){let{namespace:s,repos:o}=e,i=await this.getPermissionsForRepos({namespace:s,repos:o},t);return{data:o.map(a=>({...a,permissions:i.data[`${a.projectId}/${a.id}`]}))}}async updateIssue(e,t,s={}){return await this.config.request({method:"PATCH",url:`${C(this.config,s)}/${encodeURIComponent(e.project.namespace)}/${encodeURIComponent(e.project.name)}/_apis/wit/workitems/${e.id}?api-version=6.0`,body:JSON.stringify(t),headers:{...S(this.config,s),"Content-Type":"application/json-patch+json"}})}async setIssueStatus(e,t={}){let{issue:s,status:o}=e,i=[{op:"add",path:"/fields/System.State",value:o.name}];if(!(await this.updateIssue(s,i,t)).body.fields?.["System.State"])throw new Error("Could not set issue status")}async setIssueAssignee(e,t={}){let{issue:s,assignee:o}=e,i=[{op:"add",path:"/fields/System.AssignedTo",value:o?.name??""}];if(!(await this.updateIssue(s,i,t)).body.fields?.["System.State"])throw new Error("Could not set issue assignee")}async setIssueLabels(e,t={}){let{issue:s,labels:o}=e,a=[{op:"replace",path:"/fields/System.Tags",value:o.map(l=>l.name).join(";")}];if(!(await this.updateIssue(s,a,t)).body.fields?.["System.Tags"])throw new Error("Could not set issue tags")}async getIssueTypesForAzureProject(e,t={}){if(!e.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let{namespace:s,project:o}=e;return{data:(await this.config.request({url:`${C(this.config,t)}/${encodeURIComponent(s)}/${encodeURIComponent(o||"")}/_apis/wit/workitemtypes?api-version=6.0`,headers:{...S(this.config,t)}})).body.value}}async getLabelsForProject(e,t={}){let{namespace:s,project:o}=e;return{data:(await this.config.request({url:`${C(this.config,t)}/${encodeURIComponent(s)}/${encodeURIComponent(o||"")}/_apis/wit/tags?api-version=6.0`,headers:{...S(this.config,t)}})).body.value.map(a=>({color:null,description:null,id:a.id,name:a.name,url:a.url}))}}async getPullRequestForRepo(e,t={}){let{repo:s,number:o}=e;if(!s.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let i=await this.config.request({url:`${this.getRepoApiUrl(s.namespace,s.project,s.name,t)}/pullrequests/${o}?api-version=7.1`,headers:S(this.config,t)}),a=await this.fetchRemoteInfoByRepoId(e.includeRemoteInfo,[{namespace:s.namespace,pullRequests:[i.body]}],t);return{data:ve(s.namespace,i.body,a)}}async getPullRequestDescription(e,t={}){let{repo:s,number:o}=e;if(!s.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');try{return{data:{description:(await this.config.request({url:`${this.getRepoApiUrl(s.namespace,s.project,s.name,t)}/pullrequests/${o}?api-version=7.1`,headers:S(this.config,t)})).body?.description??""}}}catch{return{data:{description:null}}}}async setPullRequestDescription(e,t={}){let{repo:s,number:o,description:i}=e;if(!s.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');return{data:{description:(await this.config.request({method:"PATCH",url:`${this.getRepoApiUrl(s.namespace,s.project,s.name,t)}/pullrequests/${o}?api-version=7.1`,headers:{...S(this.config,t),"Content-Type":"application/json"},body:JSON.stringify({description:i})})).body?.description??i}}}async getMergeBase(e,t={}){if(!e.repo.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let s=await this.config.request({url:`${this.getRepoApiUrl(e.repo.namespace,e.repo.project,e.repo.name,t)}/commits/${encodeURIComponent(e.base)}/mergebases?otherCommitId=${encodeURIComponent(e.head)}&api-version=7.1`,headers:S(this.config,t)});if(!s.body.value?.length)throw new Error("No merge base found between the specified commits.");return{data:s.body.value[0].commitId}}async getFileContents(e,t={}){if(!e.repo.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let s=await this.config.request({url:`${this.getRepoApiUrl(e.repo.namespace,e.repo.project,e.repo.name,t)}/items?path=${encodeURIComponent(e.path)}&versionDescriptor[version]=${encodeURIComponent(e.ref)}&versionDescriptor[versionType]=commit&api-version=7.1`,headers:{...S(this.config,t),Accept:"application/octet-stream"}});return{data:new Blob([s.body])}}async getPullRequestDiff(e,t={}){if(!e.repo.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let s=this.getRepoApiUrl(e.repo.namespace,e.repo.project,e.repo.name,t),o=S(this.config,t),i={...o,Accept:"application/octet-stream"},[a,u]=await Promise.all([this.config.request({url:`${s}/pullrequests/${e.pullRequestId}?api-version=7.1`,headers:o}),this.config.request({url:`${s}/pullrequests/${e.pullRequestId}/iterations?api-version=7.1`,headers:o})]),l=a.body.lastMergeTargetCommit.commitId,d=a.body.lastMergeSourceCommit.commitId,p=u.body.value;if(p.length===0)return"";let c=p[p.length-1],g=1e3,m=[],h=0;for(;;){let E=(await this.config.request({url:`${s}/pullrequests/${e.pullRequestId}/iterations/${c.id}/changes?api-version=7.1&$top=${g}&$skip=${h}`,headers:o})).body.changeEntries??[];if(E.length===0||(m.push(...E),E.length<g))break;h+=E.length}if(m.length===0)return"";let y=5,f=[],P=new TextDecoder,q=w=>w instanceof ArrayBuffer?P.decode(w):typeof w=="string"?w:"",D=async(w,E)=>{try{let ne=await this.config.request({url:`${s}/items?path=${encodeURIComponent(w)}&versionDescriptor[version]=${encodeURIComponent(E)}&versionDescriptor[versionType]=commit&includeContent=true&api-version=7.1`,headers:i});return q(ne.body)}catch{return""}},$=w=>{if(typeof w=="number")return{add:(w&1)!==0,rename:(w&8)!==0,delete:(w&16)!==0};let E=w.toLowerCase().split(",").map(ne=>ne.trim());return{add:E.includes("add"),rename:E.includes("rename"),delete:E.includes("delete")}};for(let w=0;w<m.length;w+=y){let E=m.slice(w,w+y),ne=await Promise.all(E.map(async pe=>{let{add:de,rename:pt,delete:oe}=$(pe.changeType),qe=pe.originalPath??pe.item.originalPath,T=pe.item.path,Ge=oe?T??qe??"":T??"",Yt=pt||oe?qe??Ge:Ge,[Rs,Is]=await Promise.all([de?Promise.resolve(""):D(Yt,l),oe?Promise.resolve(""):D(Ge,d)]),bs=de?"/dev/null":`a${Yt}`,ys=oe?"/dev/null":`b${Ge}`;return(0,gr.createTwoFilesPatch)(bs,ys,Rs,Is)}));f.push(...ne)}return f.join(`
2
- `)}getPullRequestWriteHeaders(e){return{...S(this.config,e),"Content-Type":"application/json"}}setReviewerVote(e,t,s,o,i){return this.config.request({method:"PUT",url:`${e}/pullRequests/${t}/reviewers/${encodeURIComponent(s)}?api-version=7.1`,headers:this.getPullRequestWriteHeaders(i),body:JSON.stringify({vote:o})})}postPullRequestThread(e,t,s,o){return this.config.request({method:"POST",url:`${e}/pullRequests/${t}/threads?api-version=7.1`,headers:this.getPullRequestWriteHeaders(o),body:JSON.stringify({comments:[{parentCommentId:0,content:s,commentType:1}],status:1})})}async getCommentsForPullRequest(e,t={}){if(!e.repo.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let s=this.getRepoApiUrl(e.repo.namespace,e.repo.project,e.repo.name,t),o=S(this.config,t),i=await this.config.request({url:`${s}/pullRequests/${e.pullRequestNumber}/threads?api-version=7.1`,headers:o}),a=[];for(let u of i.body.value)if(!(u.isDeleted||u.threadContext))for(let l of u.comments)l.commentType==="system"||l.isDeleted||a.push({id:It(e.repo.namespace,e.repo.project,e.repo.name,e.pullRequestNumber,u.id,l.id),author:l.author?le(l.author):null,body:l.content||"",createdAt:l.publishedDate?new Date(l.publishedDate):null,url:""});return{data:a,pageInfo:{hasNextPage:!1,endCursor:null}}}async addCommentToPullRequest(e,t={}){if(!e.pullRequest.repository.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let s=this.getRepoApiUrl(e.pullRequest.repository.owner.login,e.pullRequest.repository.project,e.pullRequest.repository.name,t);await this.postPullRequestThread(s,e.pullRequest.id,e.comment,t)}async addInlineCommentToPullRequest(e,t={}){if(!e.pullRequest.repository.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let s=this.getRepoApiUrl(e.pullRequest.repository.owner.login,e.pullRequest.repository.project,e.pullRequest.repository.name,t),o=this.getPullRequestWriteHeaders(t);if(e.threadId){let d=bt(e.threadId),p=e.pullRequest.repository.owner.login,c=e.pullRequest.repository.project,g=e.pullRequest.repository.name,m=String(e.pullRequest.id);if(d.namespace!==p||d.project!==c||d.repoName!==g||d.prId!==m)throw new Error(`Azure thread ID context mismatch: threadId targets ${d.namespace}/${d.project}/${d.repoName} pull request ${d.prId}, but input.pullRequest targets ${p}/${c}/${g} pull request ${m}.`);let y=(await this.config.request({url:`${s}/pullRequests/${e.pullRequest.id}/threads/${d.threadId}?api-version=7.1`,headers:S(this.config,t)})).body.comments?.find(P=>P.parentCommentId===0);if(!y)throw new Error(`Could not determine root comment for Azure DevOps thread ${d.threadId}.`);let f=await this.config.request({method:"POST",url:`${s}/pullRequests/${e.pullRequest.id}/threads/${d.threadId}/comments?api-version=7.1`,headers:o,body:JSON.stringify({content:e.comment,parentCommentId:y.id,commentType:1})});return It(p,c,g,Number(m),Number(d.threadId),f.body.id)}let i=e.path.startsWith("/")?e.path:`/${e.path}`,a={line:e.line,offset:1},u={filePath:i};e.side==="LEFT"?(u.leftFileStart=a,u.leftFileEnd=a):(u.rightFileStart=a,u.rightFileEnd=a);let l=await this.config.request({method:"POST",url:`${s}/pullRequests/${e.pullRequest.id}/threads?api-version=7.1`,headers:o,body:JSON.stringify({comments:[{parentCommentId:0,content:e.comment,commentType:1}],status:1,threadContext:u})});return cr(e.pullRequest.repository.owner.login,e.pullRequest.repository.project,e.pullRequest.repository.name,Number(e.pullRequest.id),l.body.id)}async editComment(e,t={}){let s=dr(e.commentId),o=this.getRepoApiUrl(s.namespace,s.project,s.repoName,t);await this.config.request({method:"PATCH",url:`${o}/pullRequests/${s.prId}/threads/${s.threadId}/comments/${s.commentId}?api-version=7.1`,headers:this.getPullRequestWriteHeaders(t),body:JSON.stringify({content:e.body})})}async editInlineComment(e,t={}){return this.editComment(e,t)}async deleteComment(e,t={}){let s=dr(e.commentId),o=this.getRepoApiUrl(s.namespace,s.project,s.repoName,t);await this.config.request({method:"DELETE",url:`${o}/pullRequests/${s.prId}/threads/${s.threadId}/comments/${s.commentId}?api-version=7.1`,headers:S(this.config,t)})}async deleteInlineComment(e,t={}){return this.deleteComment(e,t)}async resolveReviewThread(e,t={}){let s=bt(e.threadId),o=this.getRepoApiUrl(s.namespace,s.project,s.repoName,t);await this.config.request({method:"PATCH",url:`${o}/pullRequests/${s.prId}/threads/${s.threadId}?api-version=7.1`,headers:this.getPullRequestWriteHeaders(t),body:JSON.stringify({status:2})})}async unresolveReviewThread(e,t={}){let s=bt(e.threadId),o=this.getRepoApiUrl(s.namespace,s.project,s.repoName,t);await this.config.request({method:"PATCH",url:`${o}/pullRequests/${s.prId}/threads/${s.threadId}?api-version=7.1`,headers:this.getPullRequestWriteHeaders(t),body:JSON.stringify({status:1})})}async approvePullRequest(e,t={}){if(!e.pullRequest.repository.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let s=e.pullRequest.repository.owner.login,o=this.getRepoApiUrl(s,e.pullRequest.repository.project,e.pullRequest.repository.name,t),i=await this.getCurrentUserId(s,t);await Promise.all([this.setReviewerVote(o,e.pullRequest.id,i,10,t),e.comment?this.postPullRequestThread(o,e.pullRequest.id,e.comment,t):null])}async requestPullRequestChanges(e,t={}){if(!e.pullRequest.repository.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let s=e.pullRequest.repository.owner.login,o=this.getRepoApiUrl(s,e.pullRequest.repository.project,e.pullRequest.repository.name,t),i=await this.getCurrentUserId(s,t);await this.postPullRequestThread(o,e.pullRequest.id,e.comment,t),await this.setReviewerVote(o,e.pullRequest.id,i,-5,t)}async commentOnPullRequest(e,t={}){if(!e.pullRequest.repository.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let s=this.getRepoApiUrl(e.pullRequest.repository.owner.login,e.pullRequest.repository.project,e.pullRequest.repository.name,t);await this.postPullRequestThread(s,e.pullRequest.id,e.comment,t)}async getReviewsForPullRequest(e,t={}){if(!e.repo.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let{namespace:s,project:o,name:i}=e.repo,{pullRequestId:a}=e,u=this.getRepoApiUrl(s,o,i,t),l=S(this.config,t),[d,p]=await Promise.all([this.config.request({url:`${u}/pullRequests/${a}/reviewers?api-version=7.1`,headers:l}),this.config.request({url:`${u}/pullRequests/${a}/threads?api-version=7.1`,headers:l})]),c=(f,P)=>It(s,o,i,a,f,P),g=f=>cr(s,o,i,a,f),m=new Map;for(let f of p.body.value){if(f.isDeleted)continue;let P=f.comments.filter(T=>!T.isDeleted&&T.commentType!=="system"),q=P.find(T=>T.parentCommentId===0)??P[0];if(!q)continue;let D=q.author?.id;if(!D)continue;let $=P.filter(T=>T.id!==q.id),w=f.threadContext,E=w?.rightFileStart?{side:"RIGHT",start:w.rightFileStart,end:w.rightFileEnd}:w?.leftFileStart?{side:"LEFT",start:w.leftFileStart,end:w.leftFileEnd}:null,ne=E?.end?.line??E?.start.line??null,pe=E?.start&&E.end&&E.start.line!==E.end.line?E.start.line:null,de=w?.filePath??"",pt=de.startsWith("/")?de.slice(1):de,oe={id:c(f.id,q.id),author:q.author?le(q.author):null,body:q.content??"",createdAt:q.publishedDate?new Date(q.publishedDate):null,url:"",diffLines:[],filename:pt,replies:$.map(T=>({id:c(f.id,T.id),author:T.author?le(T.author):null,body:T.content??"",createdAt:T.publishedDate?new Date(T.publishedDate):null,url:""})),isOutdated:!1,isResolved:Bs.has(Qs(f.status)),line:ne,startLine:pe,side:E?.side??null,threadId:g(f.id)},qe=m.get(D);qe?qe.push(oe):m.set(D,[oe])}let h=[],y=new Set;for(let f of d.body.value){if(f.hasDeclined)continue;let P=f.vote??0,q=m.get(f.id);P===0&&!q?.length||(h.push({id:f.id,author:le(f),body:"",createdAt:null,url:"",reviewComments:q??[]}),y.add(f.id))}for(let[f,P]of m){if(y.has(f)||!P.length)continue;let q=P[0].author;q&&h.push({id:f,author:q,body:"",createdAt:null,url:"",reviewComments:P})}return{data:h}}};var G=(r,n={})=>R(n.token||r.token,n.isPAT||r.isPAT);var O="https://api.bitbucket.org/2.0",Ws={OPEN:"OPEN",MERGED:"MERGED",DECLINED:"CLOSED",SUPERSEDED:"CLOSED"},Js={OPEN:["OPEN"],MERGED:["MERGED"],CLOSED:["DECLINED","SUPERSEDED"]},xe=50,hr=r=>{let n=!r||r.length===0?["OPEN"]:Array.from(new Set(r.flatMap(t=>Js[t]))),e=n.map(t=>`state="${t}"`).join(" OR ");return n.length>1?`(${e})`:e},Vs=r=>r.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),fr=r=>{let n=r?.trim();if(!n)return null;let e=Vs(n);return`(title ~ "${e}" OR description ~ "${e}")`},Rr=r=>{let n=!!r.next,e=typeof r.size=="number"?r.size:null,t=typeof r.pagelen=="number"&&r.pagelen>0?r.pagelen:null;return{hasNextPage:n,nextPage:n?r.page+1:null,currentPage:typeof r.page=="number"?r.page:null,totalCount:e,totalPages:e!==null&&t?Math.ceil(e/t):null}},ke={owner:4,admin:3,contributor:2,member:1},Ne=r=>({id:r.uuid,name:r.display_name||r.nickname,username:r.nickname||r.display_name,email:null,avatarUrl:r.links.avatar.href,url:r.links.html.href}),Ir=r=>{let n=r.links.clone,e=n?.find(s=>s.name==="ssh"),t=n?.find(s=>s.name==="https");return e&&t?{cloneUrlHTTPS:t.href,cloneUrlSSH:e.href}:null},yt=r=>({id:r.uuid,namespace:r.workspace.slug,name:r.slug,webUrl:r.links.html.href,httpsUrl:r.links.clone.find(n=>n.name==="https")?.href??null,sshUrl:r.links.clone.find(n=>n.name==="ssh")?.href??null,defaultBranch:{name:r.mainbranch.name},permissions:null}),Pt=r=>{let n=r.id,e=r.participants?.map(t=>{let s="REVIEW_REQUESTED";return t.approved?s="APPROVED":t.state==="changes_requested"?s="CHANGES_REQUESTED":t.participated_on!==null&&(s="COMMENTED"),{reviewer:Ne(t.user),state:s}})??[];return{id:n.toString(),title:r.title,description:r.description,number:n,state:Ws[r.state],isDraft:!1,commentCount:r.comment_count,upvoteCount:null,author:Ne(r.author),createdDate:new Date(r.created_on),updatedDate:new Date(r.updated_on),closedDate:null,mergedDate:null,repository:{id:r.destination.repository.uuid,name:r.destination.repository.name,owner:{login:r.destination.repository.full_name.split("/")[0]},remoteInfo:Ir(r.destination.repository)},headCommit:{buildStatuses:null},baseRef:{name:r.destination.branch.name,oid:r.destination.commit.hash},headRef:{name:r.source.branch.name,oid:r.source.commit.hash},url:r.links.html.href,assignees:null,reviews:e,reviewDecision:B(e),additions:null,deletions:null,fileCount:null,commitCount:null,isCrossRepository:r.source.repository.uuid!==r.destination.repository.uuid,headRepository:{id:r.source.repository.uuid,name:r.source.repository.name,owner:{login:r.source.repository.full_name.split("/")[0]},remoteInfo:Ir(r.source.repository)},mergeableState:"MERGEABLE",permissions:null}},Ks=r=>{switch(r){case"owner":case"admin":return{canCreateWebhook:!0,canPush:!0,isAdmin:!0};case"write":return{canCreateWebhook:!1,canPush:!0,isAdmin:!1};case"read":case"none":return{canCreateWebhook:!1,canPush:!1,isAdmin:!1}}},Xs=r=>{switch(r){case"owner":case"admin":return{canCreateWebhook:!0,canPush:!0,isAdmin:!0};case"contributor":return{canCreateWebhook:!1,canPush:!0,isAdmin:!1};default:return{canCreateWebhook:!1,canPush:!1,isAdmin:!1}}},fe=class extends j{async refreshToken(n){return{data:(await this.config.request({url:"https://bitbucket.org/site/oauth2/access_token",method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Authorization:`Basic ${n.base64ClientIDColonClientSecret}`},body:`grant_type=refresh_token&refresh_token=${n.refreshToken}`})).body}}async getCurrentUser(n={},e={}){let t=await this.config.request({url:`${O}/user`,headers:G(this.config,e)});return{data:Ne(t.body)}}async getUserForCommit(n,e={}){let s=(await this.config.request({url:`${O}/repositories/${n.repo.namespace}/${n.repo.name}/commit/${n.oid}`,headers:G(this.config,e)})).body.author,o=s.raw.match(/([^<]+)<(.+)>/);return{data:{name:o?o[1].trim():null,email:o?o[2]:null,avatarUrl:s.user?.links.avatar.href||null}}}async getRepo(n,e={}){let t=await this.config.request({url:`${O}/repositories/${n.namespace}/${n.name}`,headers:G(this.config,e)});return{data:yt(t.body)}}async getRepos(n,e={}){let t=[],s=[];return await Promise.all(n.map(async o=>{try{let i=await this.getRepo(o,e);t.push(i.data)}catch(i){s.push({input:o,error:i})}})),{data:t,errors:s}}async getReposForWorkspace(n,e={}){let t=new URL(`${O}/repositories/${encodeURIComponent(n.workspace)}`);t.searchParams.set("page",n.page?.toString()||"1"),t.searchParams.set("pagelen",L.toString()),n.minimumRole&&t.searchParams.set("role",n.minimumRole);let s=await this.config.request({url:t.toString(),headers:G(this.config,e)}),o=!!s.body.next;return{pageInfo:{hasNextPage:o,nextPage:o?s.body.page+1:null},data:s.body.values.map(yt)}}async getAllReposForWorkspace(n,e={}){let t=[],s=1;for(;s!==null;){let o=await this.getReposForWorkspace({workspace:n.workspace,minimumRole:n.minimumRole,page:s},e);t.push(...o.data),s=o.pageInfo.hasNextPage?o.pageInfo.nextPage:null}return t}async getAllReposForWorkspaceWithPermissions(n,e={}){let t=new Map,s=[],o=ke[n.minimumRole||"member"];o<=ke.admin&&s.push("admin"),o<=ke.contributor&&s.push("contributor"),o<=ke.member&&s.push("member");let i=[];for(let a of s){i=await this.getAllReposForWorkspace({workspace:n.workspace,minimumRole:a},e);for(let u of i)t.has(u.id)||t.set(u.id,a)}return{data:i.map(a=>{let u=t.get(a.id)||"member";return{...a,permissions:Xs(u)}})}}async getReposForCurrentUser(n,e={}){let t=new URL(`${O}/repositories`);t.searchParams.set("role","member"),t.searchParams.set("pagelen",L.toString()),n.cursor&&t.searchParams.set("after",n.cursor);let s=await this.config.request({url:t.toString(),headers:G(this.config,e)}),o=!!s.body.next,i=null;return s.body.next&&(i=new URL(s.body.next).searchParams.get("after")),{pageInfo:{hasNextPage:o,endCursor:i},data:s.body.values.map(yt)}}async getBranches(n,e={}){let t=new URL(`${O}/repositories/${n.repo.namespace}/${n.repo.name}/refs/branches`);t.searchParams.set("page",n.page?.toString()||"1"),t.searchParams.set("pagelen",L.toString());let s=await this.config.request({url:t.toString(),headers:G(this.config,e)}),o=!!s.body.next;return{pageInfo:{hasNextPage:o,nextPage:o?s.body.page+1:null},data:s.body.values.map(i=>{let a=new Date(i.target.date);return{name:i.name,commit:{oid:i.target.hash,authoredDate:a,committedDate:a}}})}}async getTags(n,e={}){let t=new URL(`${O}/repositories/${n.repo.namespace}/${n.repo.name}/refs/tags`);t.searchParams.set("pagelen",L.toString()),n.cursor&&t.searchParams.set("page",n.cursor);let s=await this.config.request({url:t.toString(),headers:G(this.config,e)}),o=!!s.body.next,i=null;return s.body.next&&(i=new URL(s.body.next).searchParams.get("page")),{pageInfo:{hasNextPage:o,endCursor:i},data:s.body.values.map(a=>{let u=new Date(a.target.date);return{name:a.name,commit:{oid:a.target.hash,authoredDate:u,committedDate:u}}})}}async getWorkspacesForCurrentUser(n={},e={}){let t=new URL(`${O}/user/workspaces`);t.searchParams.set("page",n?.page?.toString()||"1"),t.searchParams.set("pagelen","50"),n?.administrator!==void 0&&t.searchParams.set("administrator",n.administrator.toString());let s=await this.config.request({url:t.toString(),headers:G(this.config,e)}),o=!!s.body.next;return{pageInfo:{hasNextPage:o,nextPage:o?s.body.page+1:null},data:s.body.values.map(i=>({id:i.workspace.uuid,slug:i.workspace.slug}))}}async getWorkspacesForUser(n,e={}){let t=new URL(`${O}/user/permissions/workspaces`);t.searchParams.set("page",n.page?.toString()||"1"),t.searchParams.set("pagelen","50");let s=await this.config.request({url:t.toString(),headers:G(this.config,e)}),o=!!s.body.next;return{pageInfo:{hasNextPage:o,nextPage:o?s.body.page+1:null},data:s.body.values.map(i=>({id:i.workspace.uuid,slug:i.workspace.slug,name:i.workspace.name}))}}async getPullRequestsForUserAndWorkspace(n,e={}){let t=new URL(`${O}/workspaces/${n.workspaceSlug}/pullrequests/${n.userId}`);t.searchParams.set("fields","+values.participants,+values.destination.repository.links.clone.*,+values.source.repository.links.clone.*"),t.searchParams.set("page",n.page?.toString()||"1"),t.searchParams.set("pagelen",A(n.pageSize,{fallback:xe,max:xe}).toString());let s=[hr(n.states)];n.repos&&n.repos.length>0&&s.push(`(${n.repos.map(a=>`source.repository.full_name = "${a.namespace}/${a.name}"`).join(" OR ")})`);let o=fr(n.query);o&&s.push(o),t.searchParams.set("q",s.join(" AND "));let i=await this.config.request({url:t.toString(),headers:G(this.config,e)});return{pageInfo:Rr(i.body),data:i.body.values.map(Pt)}}async getPullRequestsForRepoBase(n,e={}){let t=new URL(`${O}/repositories/${encodeURI(n.repo.namespace)}/${encodeURI(n.repo.name)}/pullrequests`),s=[];n.reviewerId&&s.push(`reviewers.uuid="${n.reviewerId}"`),n.authorLogin&&s.push(`author.uuid="${n.authorLogin}"`);let o=hr(n.states);s.length&&(o+=` AND (${s.join(n.useOrFilter?" OR ":" AND ")})`);let i=fr(n.query);return i&&(o+=` AND ${i}`),t.searchParams.set("fields","+values.participants,+values.destination.repository.links.clone.*,+values.source.repository.links.clone.*"),t.searchParams.set("page",n.page?.toString()||"1"),t.searchParams.set("pagelen",A(n.pageSize,{fallback:xe,max:xe}).toString()),t.searchParams.set("q",o),await this.config.request({url:t.toString(),headers:G(this.config,e)})}async getPullRequestsForRepo(n,e={}){let t=[],s=await this.getPullRequestsForRepoBase(n,e);return s.body.values.forEach(o=>{t.push(Pt(o))}),{pageInfo:Rr(s.body),data:t}}async getPullRequestsForRepos(n,e={}){let{successes:t,metadata:s}=await J(n.repos,{run:i=>this.getPullRequestsForRepoBase({repo:i,authorLogin:n.authorLogin,reviewerId:n.reviewerId,useOrFilter:n.useOrFilter,states:n.states,query:n.query,pageSize:n.pageSize},e),failureScope:i=>({providerId:"bitbucket",repositoryId:ae(i)}),completeness:i=>i.body.next?"partial":"complete"}),o=[];return t.forEach(({result:i})=>{i.body.values.forEach(a=>{o.push(Pt(a))})}),{data:o,metadata:s}}async getAccountsForWorkspace(n,e={}){let t=new URL(`${O}/workspaces/${encodeURI(n.workspace)}/members`);t.searchParams.set("page",n.page?.toString()||"1"),t.searchParams.set("pagelen","100");let s=await this.config.request({url:t.toString(),headers:G(this.config,e)}),o=!!s.body.next;return{pageInfo:{hasNextPage:o,nextPage:o?s.body.page+1:null},data:s.body.values.map(i=>Ne(i.user))}}async getReposPermissionsForCurrentUser(n,e={}){let t=new URL(`${O}/user/permissions/repositories`);t.searchParams.set("page",n.page?.toString()||"1"),t.searchParams.set("pagelen","100");let s=await this.config.request({url:t.toString(),headers:G(this.config,e)}),o=!!s.body.next;return{pageInfo:{hasNextPage:o,nextPage:o?s.body.page+1:null},data:s.body.values.reduce((i,a)=>({...i,[a.repository.uuid]:Ks(a.permission)}),{})}}async decorateReposWithPermissions(n,e={}){let t={},s=1;do{let o=await this.getReposPermissionsForCurrentUser({page:s},e);t={...o.data,...t},s=o.pageInfo.hasNextPage?o.pageInfo.nextPage:null}while(s!==null);return{data:n.repos.map(o=>({...o,permissions:t[o.id]??{canCreateWebhook:!1,canPush:!1,isAdmin:!1}}))}}async closePullRequest(n,e={}){let{pullRequest:t}=n;if(!(await this.config.request({method:"POST",url:`${O}/repositories/${t.repository.owner.login}/${t.repository.name}/pullrequests/${t.id}/decline`,headers:G(this.config,e)})).body.title)throw new Error("Could not close pull request")}async mergePullRequest(n,e={}){let{pullRequest:t,mergeStrategy:s}=n,o;switch(s){case"MERGE_COMMIT":{o="merge_commit";break}case"FAST_FORWARD":{o="fast_forward";break}case"SQUASH":{o="squash";break}}let i={merge_strategy:o,type:"pullrequest"};if(!(await this.config.request({method:"POST",url:`${O}/repositories/${t.repository.owner.login}/${t.repository.name}/pullrequests/${t.id}/merge`,body:JSON.stringify(i),headers:{...G(this.config,e),"Content-Type":"application/json"}})).body.title)throw new Error("Could not merge pull request")}async setPullRequestReviewers(n,e={}){let{pullRequest:t,reviewers:s}=n,o={reviewers:s.map(a=>{if(a.username)throw new Error('Bitbucket reviewer requires "username" for this function.');return{username:a.username}})};if(!(await this.config.request({method:"PUT",url:`${O}/repositories/${t.repository.owner.login}/${t.repository.name}/pullrequests/${t.id}`,body:JSON.stringify(o),headers:{...G(this.config,e),"Content-Type":"application/json"}})).body.title)throw new Error("Could not set pull request reviewers")}};var br=r=>r?r.find(n=>n.permission==="USER_ADMIN"||n.permission==="PROJECT_ADMIN"||n.permission==="ADMIN"||n.permission==="SYS_ADMIN"||n.permission==="REPO_ADMIN")?{canCreateWebhook:!0,canPush:!0,isAdmin:!0}:r.find(n=>n.permission==="REPO_WRITE"||n.permission==="REPO_CREATE"||n.permission==="PROJECT_CREATE"||n.permission==="PROJECT_WRITE")?{canCreateWebhook:!1,canPush:!0,isAdmin:!1}:{canCreateWebhook:!1,canPush:!1,isAdmin:!1}:{canCreateWebhook:!1,canPush:!1,isAdmin:!1};var Ee=r=>{let n=r.links.self[0].href;return{name:r.displayName,email:r.emailAddress,avatarUrl:r.avatarUrl??(n&&`${n}/avatar.png`),id:r.id.toString(),username:r.name,url:n}},Fe=r=>{let n={OPEN:"OPEN",MERGED:"MERGED",DECLINED:"CLOSED"},e={UNAPPROVED:"REVIEW_REQUESTED",NEEDS_WORK:"CHANGES_REQUESTED",APPROVED:"APPROVED"},t=r.reviewers.map(u=>({reviewer:Ee(u.user),state:e[u.status]})),s=r.toRef.repository.links.clone.find(u=>u.name==="ssh")?.href??null,o=r.toRef.repository.links.clone.find(u=>u.name==="https")?.href??null;o||(o=r.toRef.repository.links.clone.find(u=>u.name==="http")?.href??null);let i=r.fromRef.repository.links.clone.find(u=>u.name==="ssh")?.href??null,a=r.fromRef.repository.links.clone.find(u=>u.name==="https")?.href??null;return a||(a=r.fromRef.repository.links.clone.find(u=>u.name==="http")?.href??null),{id:r.id.toString(),number:r.id,title:r.title,description:r.description,url:r.links.self[0].href,state:n[r.state],isDraft:!1,createdDate:new Date(r.createdDate),updatedDate:new Date(r.updatedDate),closedDate:r.closedDate?new Date(r.closedDate):null,mergedDate:r.state=="MERGED"&&r.closedDate?new Date(r.closedDate):null,baseRef:{name:r.toRef.displayId,oid:r.toRef.latestCommit},headRef:{name:r.fromRef.displayId,oid:r.fromRef.latestCommit},commentCount:r.properties.commentCount,upvoteCount:null,commitCount:null,fileCount:null,additions:null,deletions:null,author:Ee(r.author.user),assignees:null,reviews:t,reviewDecision:B(t),isCrossRepository:r.fromRef.repository.id!==r.toRef.repository.id,repository:{id:r.toRef.repository.id.toString(),name:r.toRef.repository.name,owner:{login:r.toRef.repository.project.key},remoteInfo:o&&s?{cloneUrlHTTPS:o,cloneUrlSSH:s}:null},headRepository:{id:r.fromRef.repository.id.toString(),name:r.fromRef.repository.name,owner:{login:r.fromRef.repository.project.key},remoteInfo:a&&i?{cloneUrlHTTPS:a,cloneUrlSSH:i}:null},headCommit:null,mergeableState:"MERGEABLE",permissions:null,version:r.version}},yr=r=>({id:r.id.toString(),namespace:r.project.key,name:r.slug,webUrl:r.links.self[0]?.href??null,httpsUrl:r.links.clone.find(n=>n.name==="https"||n.name==="http")?.href??null,sshUrl:r.links.clone.find(n=>n.name==="ssh")?.href??null,defaultBranch:null,permissions:null}),Pr=50,Zs={OPEN:"OPEN",MERGED:"MERGED",CLOSED:"DECLINED"},wr=r=>{if(!r||r.length===0)return"OPEN";let n=Array.from(new Set(r.map(e=>Zs[e])));return n.length===1?n[0]:"ALL"},Sr=(r,n)=>typeof r!="number"||n<=0?null:Math.floor(r/n)+1,Re=class extends N{getBaseUrl(n){let e=n.baseUrl||this.config.baseUrl;if(!e)throw new Error('Bitbucket Server requires "baseUrl"');return e}getRequestHeaders(n){return R(n.token||this.config.token)}async getCurrentUser(n={},e={}){let t=await this.config.request({url:`${this.getBaseUrl(e)}/users?limit=2`,headers:this.getRequestHeaders(e)}),{headers:{"x-auserid":s,"x-ausername":o}}=t,i=s?parseInt(s,10):null,a=decodeURIComponent(o),l=(await this.config.request({url:`${this.getBaseUrl(e)}/users?filter=${o}&avatarSize=64`,headers:this.getRequestHeaders(e)})).body.values.find(({emailAddress:d,id:p,name:c,slug:g})=>i?i===p:a===c||a===d||a===g);if(!l)throw new Error("Could not find current Bitbucket Server user");return{data:Ee(l)}}async getUserForCommit(n,e){let{repo:t,oid:s}=n,o=await this.config.request({url:`${this.getBaseUrl(e)}/projects/${t.namespace}/repos/${t.name}/commits/${s}`,headers:this.getRequestHeaders(e)});if(!o.body.author)throw new Error("Could not find user for commit");return{data:Ee(o.body.author)}}async getRepo(n,e={}){let t=await this.config.request({url:`${this.getBaseUrl(e)}/projects/${n.namespace}/repos/${n.name}`,headers:this.getRequestHeaders(e)});return{data:yr(t.body)}}async getRepos(n,e={}){let t=[],s=[];return await Promise.all(n.map(async o=>{try{let i=await this.getRepo(o,e);t.push(i.data)}catch(i){s.push({input:o,error:i})}})),{data:t,errors:s}}async getReposForCurrentUser(n,e={}){let t=n.page??0,s=await this.config.request({url:`${this.getBaseUrl(e)}/repos?start=${t}`,headers:this.getRequestHeaders(e)});return{pageInfo:{hasNextPage:!s.body.isLastPage,nextPage:s.body.nextPageStart},data:s.body.values.map(yr)}}async getRepoPermissionsForUsername(n,e={}){let t=new URL(`${this.getBaseUrl(e)}/projects/${n.repo.namespace}/repos/${n.repo.name}/permissions/search?filterText=${n.username}`);try{let s=await this.config.request({url:t.toString(),headers:this.getRequestHeaders(e)});return{data:br(s.body.values)}}catch(s){if(s.response?.status===401)return{data:{canCreateWebhook:!1,canPush:!1,isAdmin:!1}};throw s}}async decorateReposWithPermissions(n,e={}){return await Promise.all(n.repos.map(async s=>{let o=await this.getRepoPermissionsForUsername({repo:s,username:n.username},e);return{...s,permissions:o.data}}))}async getPullRequestsForRepoBase(n,e={}){let t=new URL(`${this.getBaseUrl(e)}/projects/${encodeURI(n.repo.namespace)}/repos/${encodeURI(n.repo.name)}/pull-requests`);return t.searchParams.set("state",wr(n.states)),t.searchParams.set("start",n.page?.toString()||"0"),t.searchParams.set("limit",A(n.pageSize,{fallback:Pr}).toString()),n.reviewerLogin&&(t.searchParams.set("role.1","REVIEWER"),t.searchParams.set("username.1",n.reviewerLogin)),await this.config.request({url:t.toString(),headers:this.getRequestHeaders(e)})}async getPullRequestsForRepo(n,e={}){let t=[],s=await this.getPullRequestsForRepoBase(n,e);s.body.values.forEach(i=>{if(n.authorLogin&&i.author.user.name!==n.authorLogin)return null;t.push(Fe(i))});let o=!s.body.isLastPage;return{pageInfo:{hasNextPage:o,nextPage:o?s.body.nextPageStart:null,currentPage:Sr(s.body.start,s.body.limit)},data:k(t,n.states)}}async getPullRequestsForRepos(n,e={}){let{successes:t,metadata:s}=await J(n.repos,{run:i=>this.getPullRequestsForRepoBase({repo:i,reviewerLogin:n.reviewerLogin,states:n.states,pageSize:n.pageSize},e),failureScope:i=>({providerId:"bitbucketServer",repositoryId:ae(i)}),completeness:i=>i.body.isLastPage?"complete":"partial"}),o=[];return t.forEach(({result:i})=>{i.body.values.forEach(a=>{n.authorLogin&&a.author.user.name!==n.authorLogin||o.push(Fe(a))})}),{data:k(o,n.states),metadata:s}}async getPullRequestsForCurrentUser(n,e={}){let t=new URL(`${this.getBaseUrl(e)}/dashboard/pull-requests`);t.searchParams.set("state",wr(n.states)),t.searchParams.set("start",n.page?.toString()||"0");let s=A(n.pageSize,{fallback:Pr});t.searchParams.set("limit",s.toString()),n.reviewerLogin&&(t.searchParams.set("role.1","REVIEWER"),t.searchParams.set("username.1",n.reviewerLogin));let o=await this.config.request({url:t.toString(),headers:this.getRequestHeaders(e)}),i=!o.body.isLastPage;return{pageInfo:{hasNextPage:i,nextPage:i?o.body.nextPageStart:null,currentPage:Sr(o.body.start,o.body.limit)},data:k(o.body.values.map(Fe),n.states)}}async closePullRequest(n,e={}){let{pullRequest:t}=n;if(t.version===void 0)throw new Error('Bitbucket Server requires "version" for this function.');if(!(await this.config.request({method:"POST",url:`${this.getBaseUrl(e)}/projects/${t.repository.owner.login}/repos/${t.repository.name}/pull-requests/${t.id}/decline`,body:JSON.stringify({version:t.version}),headers:{...this.getRequestHeaders(e),"Content-Type":"application/json"}})).body.title)throw new Error("Could not close pull request")}async mergePullRequest(n,e={}){let{pullRequest:t,mergeStrategyId:s}=n;if(n.mergeStrategy)throw new Error('Bitbucket Server uses "mergeStrategyId" instead of "mergeStrategy".');if(t.version===void 0)throw new Error('Bitbucket Server requires "version" for this function.');if(!(await this.config.request({method:"POST",url:`${this.getBaseUrl(e)}/projects/${t.repository.owner.login}/repos/${t.repository.name}/pull-requests/${t.id}/merge`,body:JSON.stringify({strategyId:s,version:t.version}),headers:{...this.getRequestHeaders(e),"Content-Type":"application/json"}})).body.title)throw new Error("Could not merge pull request")}async getMergeStrategies(n={}){let e=await this.config.request({url:`${this.getBaseUrl(n)}/admin/pull-requests/git`,headers:{...this.getRequestHeaders(n),"Content-Type":"application/json"}});return{data:{defaultStrategy:e.body.mergeConfig.defaultStrategy,strategies:e.body.mergeConfig.strategies}}}async setPullRequestReviewers(n,e={}){let{pullRequest:t,reviewers:s}=n;if(t.version===void 0)throw new Error('Bitbucket Server requires "version" for this function.');let o={reviewers:s.map(a=>{if(a.username)throw new Error('Bitbucket Server reviewer requires "username" for this function.');return{user:{name:a.username}}}),version:t.version};if(!(await this.config.request({method:"PUT",url:`${this.getBaseUrl(e)}/projects/${t.repository.owner.login}/repos/${t.repository.name}/pull-requests/${t.id}`,body:JSON.stringify(o),headers:{...this.getRequestHeaders(e),"Content-Type":"application/json"}})).body.title)throw new Error("Could not set pull request reviewers")}async getAccountsForProject(n,e={}){let t=new URL(`${this.getBaseUrl(e)}/projects/${encodeURI(n.project)}/permissions/users`);t.searchParams.set("start",n.page?.toString()||"0"),t.searchParams.set("limit","50");let s=await this.config.request({url:t.toString(),headers:this.getRequestHeaders(e)}),o=s.body.values.length!==0;return{pageInfo:{hasNextPage:o,nextPage:o?s.body.start+s.body.values.length:null},data:s.body.values.map(i=>Ee(i.user))}}};var Fr=require("js-base64");var I=class extends Error{constructor(e,t){let s=t?.map(i=>`'${i.message}'`).join(", "),o=s?`${e}: ${s}`:e;super(o);this.graphQLErrors=t??[]}};var Ys={AS_CODE_OWNER:[3,0,0],CHECK_RUN:[3,0,0],LATEST_REVIEWS:[3,0,0],VIEWER_CAN_MERGE_AS_ADMIN:[3,5,0],ISSUE_FULL_DATABASE_ID:[3,12,0],PR_FULL_DATABASE_ID:[3,13,0],PR_REVIEW_FULL_DATABASE_ID:[3,13,0],PR_REVIEW_COMMENT_FULL_DATABASE_ID:[3,13,0]},qr=15,vr=100,Ce={__typename:"User",id:"U_kgDNJ5k",databaseId:10137,name:"Deleted user",login:"ghost",email:"",avatarUrl:"https://avatars.githubusercontent.com/u/10137?v=4",url:"https://github.com/ghost"},x=r=>!!r,M=(r,n)=>{let e=Ys[n];for(let t=0;t<3;t++){if(r[t]>e[t])return!0;if(r[t]<e[t])return!1}return!0},Qe="https://api.github.com",en=`${Qe}/graphql`,Be=`
1
+ "use strict";var mt=Object.defineProperty;var vs=Object.getOwnPropertyDescriptor;var Es=Object.getOwnPropertyNames;var Cs=Object.prototype.hasOwnProperty;var $s=(r,n)=>{for(var e in n)mt(r,e,{get:n[e],enumerable:!0})},Ds=(r,n,e,t)=>{if(n&&typeof n=="object"||typeof n=="function")for(let s of Es(n))!Cs.call(r,s)&&s!==e&&mt(r,s,{get:()=>n[s],enumerable:!(t=vs(n,s))||t.enumerable});return r};var Ls=r=>Ds(mt({},"__esModule",{value:!0}),r);var Do={};$s(Do,{AzureDevOps:()=>fe,Bitbucket:()=>Re,BitbucketServer:()=>Ie,EntityIdentifierProviderType:()=>bs,EntityType:()=>Is,EntityVersion:()=>Rs,GitBuildStatusStage:()=>sr,GitBuildStatusState:()=>Te,GitDiffLineType:()=>gt,GitHub:()=>be,GitHubIssueCloseReason:()=>ys,GitIssueState:()=>ue,GitLab:()=>ye,GitMergeStrategy:()=>me,GitPullRequestMergeableState:()=>ie,GitPullRequestReviewState:()=>ee,GitPullRequestState:()=>Y,GraphQLErrors:()=>I,Jira:()=>Pe,JiraServer:()=>we,PullRequestAsyncStatus:()=>fs,Trello:()=>Se,default:()=>$o,isFetch:()=>Oe});module.exports=Ls(Do);var Rr=require("diff");var sr=(s=>(s.Build="build",s.Production="production",s.Staging="staging",s.Test="test",s))(sr||{}),Te=(p=>(p.ActionRequired="ACTION_REQUIRED",p.Cancelled="CANCELLED",p.Error="ERROR",p.Failed="FAILED",p.Pending="PENDING",p.Running="RUNNING",p.Skipped="SKIPPED",p.Success="SUCCESS",p.Warning="WARNING",p.OptionalActionRequired="OPTIONAL_ACTION_REQUIRED",p))(Te||{}),me=(o=>(o.MergeCommit="MERGE_COMMIT",o.Rebase="REBASE",o.RebaseThenMergeCommit="REBASE_THEN_MERGE_COMMIT",o.FastForward="FAST_FORWARD",o.Squash="SQUASH",o))(me||{}),Y=(t=>(t.Open="OPEN",t.Closed="CLOSED",t.Merged="MERGED",t))(Y||{}),ee=(s=>(s.Approved="APPROVED",s.ChangesRequested="CHANGES_REQUESTED",s.Commented="COMMENTED",s.ReviewRequested="REVIEW_REQUESTED",s))(ee||{}),ie=(u=>(u.Behind="BEHIND",u.Blocked="BLOCKED",u.Conflicts="CONFLICTS",u.FailingChecks="FAILING_CHECKS",u.Mergeable="MERGEABLE",u.Unknown="UNKNOWN",u.UnknownAndBlocked="UNKNOWN_AND_BLOCKED",u.Unstable="UNSTABLE",u))(ie||{}),gt=(t=>(t.ADDED="ADDED",t.DELETED="DELETED",t.UNMODIFIED="UNMODIFIED",t))(gt||{});var nr={APPROVED:0,COMMENTED:1,REVIEW_REQUESTED:2,CHANGES_REQUESTED:3},B=r=>!r||r.length===0?null:r.reduce((n,e)=>nr[e.state]>nr[n]?e.state:n,"APPROVED");var Us=new Set(["ECONNABORTED","ECONNREFUSED","ECONNRESET","EAI_AGAIN","ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"]),R=(r,n)=>{let e={};return r&&(e.Authorization=`${n?"Basic":"Bearer"} ${r}`),e},ar=r=>r?r.reduce((n,e)=>(n[e]=!0,n),{}):void 0,te=(r,n,e)=>!r||n.some(t=>r[t])?e:"",ur=async r=>{let n=[],e=!0,t;for(;e;){let s=await r(t);n=n.concat(s.data),e=!!s?.pageInfo?.hasNextPage,t=s?.pageInfo?.endCursor||s?.pageInfo?.nextPage}return n};async function ht(r){return(await Promise.allSettled(r)).map(e=>_s(e)).filter(e=>e!=null)}var U=(r,{fallback:n,max:e})=>!r||r<=0?n:e===void 0?r:Math.min(r,e),k=(r,n)=>{if(!n||n.length===0)return r;let e=new Set(n);return r.filter(t=>e.has(t.state))},As=r=>{if(!(!r||typeof r!="object")){if("statusCode"in r&&typeof r.statusCode=="number")return r.statusCode;if("response"in r&&r.response&&typeof r.response=="object"&&"status"in r.response&&typeof r.response.status=="number")return r.response.status}},Gs=r=>{if(!(!r||typeof r!="object"||!("code"in r)||typeof r.code!="string"))return r.code},lr=r=>{if(typeof r=="string")return r;if(r instanceof Error)return r.message},Ts=r=>{let n=As(r);if(n===401)return"authentication";if(n===404)return"not-found";if(n===429)return"rate-limit";if(n!==void 0)return"provider";let e=Gs(r);if(e&&Us.has(e))return"network";let t=lr(r)?.toLowerCase();return t&&(t.includes("network")||t.includes("fetch failed")||t.includes("timed out")||t.includes("timeout")||t.includes("econn")||t.includes("enotfound")||t.includes("eai_again"))?"network":"unknown"},Os=(r,n)=>{let e=lr(n);return{scope:r,kind:Ts(n),...e?{message:e}:{}}},ge=(r,n=[])=>({completeness:r,...n.length?{failures:n}:{}}),or={complete:0,unknown:1,partial:2},ir=(r,n)=>or[r]>=or[n]?r:n,ae=r=>r?r.id||`${r.namespace}/${r.name}`:void 0;async function J(r,{run:n,failureScope:e,completeness:t,concurrency:s}){let o=async p=>{try{return{scope:p,result:await n(p)}}catch(d){return{scope:p,error:d}}},i;if(s===void 0)i=await Promise.all(r.map(o));else{if(!Number.isInteger(s)||s<=0)throw new Error("concurrency must be a positive integer");let p=new Array(r.length);await ft(r.map((d,c)=>({scope:d,index:c})),s,async({scope:d,index:c})=>{p[c]=await o(d)}),i=p}let a=[],u=[],l="complete";return i.forEach(p=>{if("error"in p){a.push(Os(e(p.scope),p.error)),l=ir(l,"partial");return}if(p.result===void 0)return;let d=p.result;l=ir(l,t?t(d):"complete"),u.push({scope:p.scope,result:d})}),{successes:u,metadata:ge(l,a)}}function _s(r,n=void 0){return r?.status==="fulfilled"?r.value:n}async function ft(r,n,e){if(!Number.isFinite(n)||!Number.isInteger(n)||n<=0)throw new Error("batchSize must be a positive integer");for(let t=0;t<r.length;t+=n){let s=r.slice(t,t+n);await Promise.all(s.map(e))}}var ue=(e=>(e.Open="OPEN",e.Closed="CLOSED",e))(ue||{});var Rt=(a=>(a[a.Unknown=0]="Unknown",a[a.Active=1]="Active",a[a.Fixed=2]="Fixed",a[a.WontFix=3]="WontFix",a[a.Closed=4]="Closed",a[a.ByDesign=5]="ByDesign",a[a.Pending=6]="Pending",a))(Rt||{});var C=100;var pr=globalThis.fetch;var xs=async r=>{let n=r.headers.get("content-type")||"",e=null;if(n.startsWith("application/json")){let o=await r.text();e=o.trim().length>0?JSON.parse(o):null}else if(n.startsWith("text/")||n===""||n.startsWith("application/vnd.github.diff")||n.startsWith("application/vnd.github.patch"))e=await r.text();else if(n.startsWith("application/vnd.github.raw+json")||n.startsWith("application/octet-stream"))e=await r.arrayBuffer();else throw new Error(`Unsupported content-type: ${n}`);let t={};r.headers.forEach((o,i)=>{t[i]=o});let s={body:e,headers:t,status:r.status,statusText:r.statusText};if(!r.ok){let o=new Error(r.statusText);throw Object.assign(o,{response:s}),o}return s},It=r=>async({url:n,...e})=>{let t=await r(n,e);return xs(t)};var Oe=(r,n=!1)=>r.name==="fetch"||n;var j=class{constructor(n){let e=n?.request||pr;this.config={...n,request:Oe(e,n?.forceIsFetch)?It(e):e}}updateConfig(n){this.config={...this.config,...n,request:n.request&&Oe(n.request,n?.forceIsFetch??this.config.forceIsFetch)?It(n.request):this.config.request}}},N=class extends j{};var ks="https://app.vssps.visualstudio.com/_apis",Ns="https://vssps.dev.azure.com/",Fs="https://dev.azure.com",S=(r,n={})=>R(n.token||r.token,n.isPAT||r.isPAT),dr=r=>r.url.replace("/_apis/git/repositories/","/_git/").replace(`/${r.repository.project.id}/`,`/${encodeURIComponent(r.repository.project.name)}/`).replace(`/${r.repository.id}/`,`/${encodeURIComponent(r.repository.name)}/`).replace("/pullRequests/","/pullrequest/"),bt=(r,n)=>{let e=n.baseUrl||r.baseUrl||ks;return e=e.replace(/\/$/,""),e},$=(r,n)=>{let e=n.baseUrl||r.baseUrl||Fs;return e=e.replace(/\/$/,""),e},yt=(r,n)=>{let e=n.baseUrl||r.baseUrl||Ns;return e=e.replace(/\/$/,""),e};var js={active:"OPEN",completed:"MERGED",abandoned:"CLOSED"},Qs={OPEN:"active",MERGED:"completed",CLOSED:"abandoned"},he=100,Bs=200,cr=5,zs=200,mr=r=>{if(!r||r.length===0)return"active";let n=Array.from(new Set(r.map(e=>Qs[e])));return n.length===1?n[0]:"all"},Ms=r=>{if(!r||r.length===0)return["[Microsoft.VSTS.Common.ClosedDate] = ''","[Microsoft.VSTS.Common.ResolvedDate] = ''"];let n=new Set(r),e=n.has("OPEN"),t=n.has("CLOSED");return e&&t?[]:t?["([Microsoft.VSTS.Common.ClosedDate] <> '' OR [Microsoft.VSTS.Common.ResolvedDate] <> '')"]:["[Microsoft.VSTS.Common.ClosedDate] = ''","[Microsoft.VSTS.Common.ResolvedDate] = ''"]},Hs=r=>{if(typeof r!="string")return r;let n=r.charAt(0).toUpperCase()+r.slice(1);return Rt[n]??0},Ws=new Set([2,3,4,5]),Js={10:"APPROVED",5:"APPROVED",0:"REVIEW_REQUESTED",[-5]:"CHANGES_REQUESTED",[-10]:"CHANGES_REQUESTED"},le=r=>({id:r.id,name:r.displayName??null,username:(r.uniqueName||r.displayName)??null,email:null,avatarUrl:r.imageUrl??null,url:null}),_e=r=>r.startsWith("refs/heads/")?r.replace("refs/heads/",""):r,Vs=r=>{switch(r){case"conflicts":return"CONFLICTS";case"failure":return"FAILING_CHECKS";case"rejectedByPolicy":return"BLOCKED";case"succeeded":return"MERGEABLE";case"notSet":case"queued":default:return"UNKNOWN"}},Pt=(r,n,e,t,s,o)=>`${r}|${n}|${e}|${t}|${s}|${o}`,gr=r=>{let n=r.split("|");if(n.length!==6)throw new Error("Invalid Azure comment ID format");return{namespace:n[0],project:n[1],repoName:n[2],prId:n[3],threadId:n[4],commentId:n[5]}},hr=(r,n,e,t,s)=>`${r}|${n}|${e}|${t}|${s}`,wt=r=>{let n=r.split("|");if(n.length!==5)throw new Error("Invalid Azure thread ID format");return{namespace:n[0],project:n[1],repoName:n[2],prId:n[3],threadId:n[4]}},ve=(r,n,e)=>{let t=!!n.forkSource,s=[],o=[];return n.reviewers.forEach(i=>{let a={reviewer:le(i),state:Js[i.vote??0]||"REVIEW_REQUESTED"};i.isRequired&&s.push(a),o.push(a)}),{id:n.pullRequestId.toString(),title:n.title,description:n.description??null,number:n.codeReviewId,state:js[n.status],isDraft:n.isDraft,commentCount:null,upvoteCount:null,author:le(n.createdBy),createdDate:new Date(n.creationDate),updatedDate:new Date(n.closedDate||n.creationDate),closedDate:n.closedDate?new Date(n.closedDate):null,mergedDate:n.closedDate&&n.status==="completed"?new Date(n.closedDate):null,isCrossRepository:t,repository:{id:n.repository.id,name:n.repository.name,project:n.repository.project.name,owner:{login:r},remoteInfo:e?.get(n.repository.id)??null},headCommit:{buildStatuses:null},baseRef:{name:_e(n.targetRefName),oid:n.lastMergeTargetCommit.commitId},headRef:{name:_e(n.sourceRefName),oid:n.lastMergeSourceCommit.commitId},url:dr(n),assignees:n.reviewers.map(le),reviews:o,reviewDecision:B(s),additions:null,deletions:null,fileCount:null,commitCount:null,headRepository:n.forkSource?{id:n.forkSource.repository.id,name:n.forkSource.repository.name,project:void 0,owner:{login:r},remoteInfo:e?.get(n.forkSource.repository.id)??null,isFork:!0}:{id:n.repository.id,name:n.repository.name,project:n.repository.project.name,owner:{login:r},remoteInfo:e?.get(n.repository.id)??null,isFork:!1},mergeableState:Vs(n.mergeStatus),labels:n.labels?.map(i=>({color:null,description:null,id:i.id,name:i.name}))??[],permissions:null}},fr=(r,n)=>({id:n.id,name:n.name,namespace:r,project:n.project.name,projectId:n.project.id,webUrl:n.webUrl,httpsUrl:n.remoteUrl,sshUrl:n.sshUrl,defaultBranch:n.defaultBranch?{name:_e(n.defaultBranch)}:null,permissions:null}),Ks=(r,n,e,t)=>{let s=e.fields,o=s["System.AssignedTo"],i=s["System.State"],a=s["System.WorkItemType"],u;return i&&a&&(u=t[a]?.[i]),{id:e.id.toString(),number:e.id.toString(),title:s["System.Title"],commentCount:s["System.CommentCount"],author:{avatarUrl:s["System.CreatedBy"]._links?.avatar?.href??null,email:null,id:s["System.CreatedBy"].id,name:s["System.CreatedBy"].uniqueName??null,username:s["System.CreatedBy"].displayName??null,url:null},closedDate:s["Microsoft.VSTS.Common.ClosedDate"]?new Date(s["Microsoft.VSTS.Common.ClosedDate"]):null,createdDate:new Date(s["System.CreatedDate"]),updatedDate:new Date(s["System.ChangedDate"]),url:e._links.html.href,assignees:o?[{avatarUrl:o._links?.avatar?.href??null,email:null,id:o.id,name:o.uniqueName??null,username:o.displayName??null,url:null}]:[],description:s["System.Description"]??null,state:{name:u?.title||i,color:null},type:s["System.WorkItemType"],repository:null,project:{namespace:r,name:n,resourceId:null,key:null,id:null},upvoteCount:0,labels:e.fields["System.Tags"]?.split(";").map(l=>({color:null,description:null,id:null,name:l.trim()}))??[]}},fe=class extends N{constructor(){super(...arguments);this.cachedUserIds=new Map;this.inflightUserIds=new Map}getCurrentUserId(e,t){let s=JSON.stringify([e,t.token??null,t.isPAT??this.config.isPAT??!1,t.baseUrl??null]),o=this.cachedUserIds.get(s);if(o)return Promise.resolve(o);let i=this.inflightUserIds.get(s);if(i)return i;let a=this.fetchCurrentUserId(e,t,s);return this.inflightUserIds.set(s,a),a}async fetchCurrentUserId(e,t,s){try{let o=await this.getCurrentUserForInstance({namespace:e},t);return this.cachedUserIds.set(s,o.data.id),o.data.id}finally{this.inflightUserIds.delete(s)}}getRepoApiUrl(e,t,s,o){return`${$(this.config,o)}/${encodeURIComponent(e)}/${encodeURIComponent(t)}/_apis/git/repositories/${encodeURIComponent(s)}`}async getCurrentUser(e={},t={}){if(t.isPAT||this.config.isPAT)throw new Error("Azure DevOps does not support PATs for this function.");let s=`${bt(this.config,t)}/profile/profiles/me`,o=await this.config.request({url:s,headers:S(this.config,t)});return{data:{id:o.body.id,name:o.body.displayName,username:o.body.displayName,email:o.body.emailAddress,avatarUrl:null,url:null}}}async getCurrentUserForInstance(e,t={}){let o=(await this.config.request({url:`${$(this.config,t)}/${encodeURIComponent(e.namespace)}/_apis/ConnectionData`,headers:S(this.config,t)})).body.authorizedUser;if(o.providerDisplayName==="Anonymous")throw new Error("Current user not found.");return{data:{id:o.id,name:o.providerDisplayName,username:o.providerDisplayName,email:o.properties.Account.$value,avatarUrl:null,url:null}}}async getUserForCommit(e,t={}){if(!e.repo.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let o=(await this.config.request({url:`${$(this.config,t)}/${encodeURIComponent(e.repo.namespace)}/${encodeURIComponent(e.repo.project)}/_apis/git/repositories/${encodeURIComponent(e.repo.name)}/commits/${e.oid}`,headers:S(this.config,t)})).body.author;return{data:{name:o.name,email:o.email,avatarUrl:o.imageUrl}}}async getOrgsForUser(e,t={}){let s=`${bt(this.config,t)}/accounts?memberId=${e.userId}&api-version=6.0`;return{data:(await this.config.request({url:s,headers:S(this.config,t)})).body.value.map(i=>({id:i.accountId,name:i.accountName}))}}async getCollectionsForUser(e,t={}){let s=`${$(this.config,t)}/_apis/projectCollections`;return{data:(await this.config.request({url:s,headers:S(this.config,t)})).body.value.map(i=>({id:i.id,name:i.name}))}}async getAzureProjects(e,t={}){let s=new URL(`${$(this.config,t)}/${encodeURIComponent(e.namespace)}/_apis/projects`);s.searchParams.set("$top",C.toString()),e.cursor&&s.searchParams.set("$skip",e.cursor);let o=await this.config.request({url:s.toString(),headers:S(this.config,t)}),i=o.headers["x-ms-continuationtoken"];return{pageInfo:{hasNextPage:!!i,endCursor:i||null},data:o.body.value.map(a=>({id:a.id,name:a.name,namespace:e.namespace}))}}async getAzureProjectScopeDescriptor(e,t={}){let{namespace:s,projectId:o}=e;return{data:{scope:(await this.config.request({url:`${yt(this.config,t)}/${encodeURIComponent(s)}/_apis/graph/descriptors/${o}?api-version=6.0`,headers:S(this.config,t)})).body.value}}}async getAzureGraphAccountsForAzureProject(e,t={}){let{namespace:s,projectScopeDescriptor:o,cursor:i}=e,a=new URL(`${yt(this.config,t)}/${encodeURIComponent(s)}/_apis/graph/users`);o&&a.searchParams.set("scopeDescriptor",o),i&&a.searchParams.set("continuationToken",i);let u=await this.config.request({url:a.toString(),headers:S(this.config,t)}),l=u.headers["x-ms-continuationtoken"];return{pageInfo:{endCursor:l||null,hasNextPage:!!l},data:u.body.value.map(p=>({avatarUrl:p._links?.avatar?.href??null,descriptor:p.descriptor??null,email:p.mailAddress??null,name:p.displayName??null,storageKeyURL:p._links?.storageKey?.href??null,username:p.displayName??null}))}}async getAccountFromAzureGraphAccount(e,t={}){let{azureGraphAccount:s}=e;if(!s.storageKeyURL)throw new Error("Expected 'storageKeyURL' to not be null for 'azureGraphAccount'");let o=await this.config.request({url:s.storageKeyURL,headers:S(this.config,t)});return{data:{avatarUrl:s.avatarUrl,email:s.email,id:o.body.value,name:s.name,username:s.username,url:null}}}async getAccountsFromAzureGraphAccounts(e,t={}){let s=[];for(let o of e.azureGraphAccounts){let i=await this.getAccountFromAzureGraphAccount({azureGraphAccount:o},t);s.push(i.data)}return{data:s}}async getRepo(e,t={}){if(!e.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let s=await this.config.request({url:`${$(this.config,t)}/${encodeURIComponent(e.namespace)}/${encodeURIComponent(e.project)}/_apis/git/repositories/${encodeURIComponent(e.name)}`,headers:S(this.config,t)});return{data:fr(e.namespace,s.body)}}async getRepos(e,t={}){let s=[],o=[];return await Promise.all(e.map(async i=>{try{let a=await this.getRepo(i,t);s.push(a.data)}catch(a){o.push({input:i,error:a})}})),{data:s,errors:o}}async getReposForAzureProject(e,t={}){if(!e.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');return{data:(await this.config.request({url:`${$(this.config,t)}/${encodeURIComponent(e.namespace)}/${encodeURIComponent(e.project)}/_apis/git/repositories`,headers:S(this.config,t)})).body.value.map(o=>fr(e.namespace,o))}}async getRefs(e,t,s={}){if(!t.repo.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let o=new URL(`${$(this.config,s)}/${encodeURIComponent(t.repo.namespace)}/${encodeURIComponent(t.repo.project)}/_apis/git/repositories/${encodeURIComponent(t.repo.name)}/refs`);o.searchParams.set("filter",e),o.searchParams.set("$top",C.toString()),t.cursor&&o.searchParams.set("continuationToken",t.cursor);let i=await this.config.request({url:o.toString(),headers:S(this.config,s)}),a=i.headers["x-ms-continuationtoken"];return{pageInfo:{hasNextPage:!!a,endCursor:a||null},data:i.body.value.map(u=>({name:_e(u.name),commit:{oid:u.objectId,authoredDate:null,committedDate:null}}))}}async getBranches(e,t={}){return this.getRefs("heads",e,t)}async getTags(e,t={}){return this.getRefs("tags",e,t)}async fetchRemoteInfoByRepoId(e,t,s){let o=new Map;if(!e)return o;let i=new Map;for(let{namespace:a,pullRequests:u}of t)for(let l of u)i.has(l.repository.id)||i.set(l.repository.id,a),l.forkSource&&!i.has(l.forkSource.repository.id)&&i.set(l.forkSource.repository.id,a);return await ft([...i],10,async([a,u])=>{try{let l=await this.config.request({url:`${$(this.config,s)}/${encodeURIComponent(u)}/_apis/git/repositories/${encodeURIComponent(a)}`,headers:S(this.config,s)}),{remoteUrl:p,sshUrl:d}=l.body;p&&d&&o.set(a,{cloneUrlHTTPS:p,cloneUrlSSH:d})}catch{}}),o}async getPullRequestsForRepoBase(e,t={},s=he){let{page:o,repo:i,assigneeLogins:a,authorLogin:u,reviewerId:l}=e||{},p=o||1;if(!i.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let d=U(e.pageSize,{fallback:s}),c=l??(a&&a.length?a[0]:void 0),g=`searchCriteria.status=${mr(e.states)}`;return c&&(g+=`&searchCriteria.reviewerId=${encodeURIComponent(c)}`),u&&(g+=`&searchCriteria.creatorId=${encodeURIComponent(u)}`),await this.config.request({url:`${$(this.config,t)}/${encodeURIComponent(i.namespace)}/${encodeURIComponent(i.project||"")}/_apis/git/repositories/${encodeURIComponent(i.name)}/pullRequests?${g}&%24top=${d}&%24skip=${(p-1)*d}`,headers:S(this.config,t)})}async getPullRequestsForRepo(e,t={}){let s=U(e.pageSize,{fallback:he}),o=e.page||1,i=await this.getPullRequestsForRepoBase(e,t,s),a=i.body.value.length===s,u=await this.fetchRemoteInfoByRepoId(e.includeRemoteInfo,[{namespace:e.repo.namespace,pullRequests:i.body.value}],t);return{pageInfo:{hasNextPage:a,nextPage:a?o+1:null,currentPage:o},data:k(i.body.value.map(l=>ve(e.repo.namespace,l,u)),e.states)}}async getPullRequestsForRepos(e,t={}){if(!e.repos.every(d=>d.project))throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let{repos:s}=e||{},o=U(e.pageSize,{fallback:he}),{successes:i,metadata:a}=await J(s,{run:d=>this.getPullRequestsForRepoBase({repo:d,assigneeLogins:e.assigneeLogins,authorLogin:e.authorLogin,reviewerId:e.reviewerId,states:e.states,pageSize:o},t,o),failureScope:d=>({providerId:"azure",projectId:d.project,repositoryId:ae(d)}),completeness:d=>d.body.value.length===o?"unknown":"complete",concurrency:cr}),u=i.map(({scope:d,result:c})=>({namespace:d.namespace,pullRequests:c.body.value})),l=await this.fetchRemoteInfoByRepoId(e.includeRemoteInfo,u,t),p=u.flatMap(({namespace:d,pullRequests:c})=>c.map(g=>ve(d,g,l)));return{data:k(p,e.states),metadata:a}}async getPullRequestsForProjectBase(e,t={},s=he){let{namespace:o,project:i,page:a,assigneeLogins:u,authorLogin:l,reviewerId:p,repo:d}=e;if(d?.project&&d.project!==i)throw new Error("Could not fetch pull requests, project mismatch");let c=a||1,g=U(e.pageSize,{fallback:s}),m=p??(u&&u.length?u[0]:void 0),h=new URL(`${$(this.config,t)}/${encodeURIComponent(o)}/${encodeURIComponent(i)}/_apis/git/pullRequests`);return h.searchParams.set("searchCriteria.status",mr(e.states)),h.searchParams.set("$top",g.toString()),h.searchParams.set("$skip",((c-1)*g).toString()),d?.id&&d?.project===i&&h.searchParams.set("searchCriteria.repositoryId",d.id),m&&h.searchParams.set("searchCriteria.reviewerId",m),l&&h.searchParams.set("searchCriteria.creatorId",l),await this.config.request({url:h.toString(),headers:S(this.config,t)})}async getPullRequestsForProject(e,t={}){let s=U(e.pageSize,{fallback:he}),o=e.page||1,i=await this.getPullRequestsForProjectBase(e,t,s),a=i.body.value.length===s,u=await this.fetchRemoteInfoByRepoId(e.includeRemoteInfo,i?[{namespace:e.namespace,pullRequests:i.body.value}]:[],t);return{pageInfo:{hasNextPage:a,nextPage:a?o+1:null,currentPage:o},data:k(i?.body.value.map(l=>ve(e.namespace,l,u))||[],e.states)}}async getPullRequestsForProjects(e,t={}){let{projects:s}=e||{};if(e.repo&&!e.repo.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let o=U(e.pageSize,{fallback:he}),{successes:i,metadata:a}=await J(s,{run:d=>e.repo&&e.repo.project!==d.project?Promise.resolve(void 0):this.getPullRequestsForProjectBase({...d,assigneeLogins:e.assigneeLogins,authorLogin:e.authorLogin,reviewerId:e.reviewerId,states:e.states,pageSize:o,repo:e.repo},t,o),failureScope:d=>({providerId:"azure",projectId:d.project,repositoryId:ae(e.repo)}),completeness:d=>d.body.value.length===o?"unknown":"complete",concurrency:cr}),u=i.map(({scope:d,result:c})=>({namespace:d.namespace,pullRequests:c.body.value})),l=await this.fetchRemoteInfoByRepoId(e.includeRemoteInfo,u,t),p=u.flatMap(({namespace:d,pullRequests:c})=>c.map(g=>ve(d,g,l)));return{data:k(p,e.states),metadata:a}}async getAzurePullRequestLastMergeStatus(e,t={}){if(!e.repo.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let{repo:{namespace:s,project:o,name:i},pullRequestId:a}=e,u=await this.config.request({url:`${$(this.config,t)}/${encodeURIComponent(s)}/${encodeURIComponent(o||"")}/_apis/git/repositories/${i}/pullrequests/${a}?includeCommits=true?api-version=6.0`,headers:{...S(this.config,t)}});if(!u.body.mergeStatus)throw new Error("Could not fetch pull request");return{data:u.body.mergeStatus}}async updatePullRequest(e,t,s){return await this.config.request({method:"PATCH",url:`${$(this.config,s)}/${encodeURIComponent(e.repository.owner.login)}/${encodeURIComponent(e.repository.project)}/_apis/git/repositories/${e.repository.name}/pullrequests/${e.id}?api-version=6.0`,body:t,headers:{...S(this.config,s),"Content-Type":"application/json"}})}async closePullRequest(e,t={}){let{pullRequest:s}=e,o={status:"abandoned"};if(!(await this.updatePullRequest(s,JSON.stringify(o),t)).body.status)throw new Error("Could not close pull request")}async mergePullRequest(e,t={}){let{pullRequest:s,mergeStrategy:o}=e,i;switch(o){case"MERGE_COMMIT":{i="noFastForward";break}case"REBASE":{i="rebase";break}case"REBASE_THEN_MERGE_COMMIT":{i="rebaseMerge";break}case"SQUASH":{i="squash";break}}let a={completionOptions:{mergeStrategy:i},lastMergeSourceCommit:{commitId:s.headRef?.oid},status:"completed"};if(!(await this.updatePullRequest(s,JSON.stringify(a),t)).body.status)throw new Error("Could not merge pull request")}async addPullRequestLabel(e,t={}){let{pullRequest:s,label:o}=e;if(!s.repository.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let i={name:o.name};if(!(await this.config.request({method:"POST",url:`${$(this.config,t)}/${encodeURIComponent(s.repository.owner.login)}/${encodeURIComponent(s.repository.project)}/_apis/git/repositories/${s.repository.name}/pullrequests/${s.id}/labels?api-version=6.0`,body:JSON.stringify(i),headers:{...S(this.config,t),"Content-Type":"application/json"}})).body.id)throw new Error("Could not add pull request label")}async removePullRequestLabel(e,t={}){let{pullRequest:s,label:o}=e;if(!s.repository.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');await this.config.request({method:"DELETE",url:`${$(this.config,t)}/${encodeURIComponent(s.repository.owner.login)}/${encodeURIComponent(s.repository.project)}/_apis/git/repositories/${s.repository.name}/pullrequests/${s.id}/labels/${encodeURIComponent(o.name)}?api-version=6.0`,headers:{...S(this.config,t)}})}async setPullRequestLabels(e,t={}){let{pullRequest:s,labels:o}=e;if(!s.repository.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let i=s.labels;if(!i)throw new Error('Azure DevOps requires "labels" for this function.');for(let a of o)i.find(u=>u.id===a.id)||await this.addPullRequestLabel({pullRequest:s,label:a},t);for(let a of i)o.find(u=>a.id===u.id)||await this.removePullRequestLabel({pullRequest:s,label:a},t)}async setPullRequestAsDraft(e,t={}){let{pullRequest:s,isDraft:o}=e,i={isDraft:o};if(!(await this.updatePullRequest(s,JSON.stringify(i),t)).body.status)throw new Error("Could not set the pull request as draft")}async addPullRequestReviewer(e,t={}){let{pullRequest:s,reviewer:o,isRequired:i}=e,a={id:o.id,isRequired:i};if(!(await this.config.request({method:"PUT",url:`${$(this.config,t)}/${encodeURIComponent(s.repository.owner.login)}/${encodeURIComponent(s.repository.project)}/_apis/git/repositories/${s.repository.name}/pullrequests/${s.id}/reviewers/${o.id}?api-version=6.0`,body:JSON.stringify(a),headers:{...S(this.config,t),"Content-Type":"application/json"}})).body.id)throw new Error("Could not add pull request reviewer")}async removePullRequestReviewer(e,t={}){let{pullRequest:s,reviewer:o}=e;await this.config.request({method:"DELETE",url:`${$(this.config,t)}/${encodeURIComponent(s.repository.owner.login)}/${encodeURIComponent(s.repository.project)}/_apis/git/repositories/${s.repository.name}/pullrequests/${s.id}/reviewers/${o.id}?api-version=6.0`,headers:{...S(this.config,t),Accept:"application/json"}})}async setPullRequestReviewers(e,t={}){let{pullRequest:s,reviewers:o}=e;for(let i of o)s.assignees.find(a=>a.id===i.id)||await this.addPullRequestReviewer({pullRequest:s,reviewer:i,isRequired:!0},t);for(let i of s.assignees)o.find(a=>i.id===a.id)||await this.removePullRequestReviewer({pullRequest:s,reviewer:i},t)}async getIssuesForAzureProject(e,t={}){let{page:s,assigneeLogins:o,authorLogin:i,mentionLogin:a,labelNames:u,statusByWorkItemIdByStatusId:l}=e||{},p=s||1,d=Math.min(U(e.pageSize,{fallback:Bs}),zs),c=["[System.TeamProject] = @project",...Ms(e.states)];i&&c.push(`[System.CreatedBy] = '${i.replace("'","''")}'`),o&&o[0]&&c.push(`[System.AssignedTo] = '${o[0].replace("'","''")}'`),a&&c.push("[System.Id] IN (@recentMentions)"),u&&u.forEach(L=>c.push(`[System.Tags] Contains '${L}'`));let g=`Select [Microsoft.VSTS.Common.ClosedDate], [Microsoft.VSTS.Common.ResolvedDate] From WorkItems Where ${c.join(" AND ")} order by [System.CreatedDate] desc`,m=await this.config.request({url:`${$(this.config,t)}/${encodeURIComponent(e.namespace)}/${encodeURIComponent(e.project)}/_apis/wit/wiql?api-version=6.0`,body:JSON.stringify({query:g}),method:"POST",headers:{...S(this.config,t),"Content-Type":"application/json"}}),h=m.body.workItems.slice((p-1)*d,d*p).map(L=>L.id),y=m.body.workItems.length,f=Math.ceil(y/d),P=y>d*p;if(h.length===0)return{pageInfo:{hasNextPage:!1,nextPage:null,currentPage:p,totalCount:y,totalPages:f},data:[]};let q=await this.config.request({url:`${$(this.config,t)}/${encodeURIComponent(e.namespace)}/${encodeURIComponent(e.project)}/_apis/wit/workitemsbatch?api-version=6.0`,body:JSON.stringify({ids:h,$expand:"Links"}),method:"POST",headers:{...S(this.config,t),"Content-Type":"application/json"}});return{pageInfo:{hasNextPage:P,nextPage:P?p+1:null,currentPage:p,totalCount:y,totalPages:f},data:q.body.value.map(L=>Ks(e.namespace,e.project,L,l||{}))}}async getPermissionsForRepos(e,t={}){let{namespace:s,repos:o}=e,i={4:["canPush","canCreateWebhook"],1024:["isAdmin"],2048:["isAdmin"],4096:["isAdmin"],8192:["isAdmin"]},a=d=>{let c="2e9eb7ed-3c0a-47d4-87c1-0ffdd275fd87",g=`repoV2/${d.projectId}/${d.id}`;return Object.keys(i).map(m=>({securityNamespaceId:c,token:g,permissions:m}))},u={alwaysAllowAdministrators:!1,evaluations:o.flatMap(a)};return{data:(await this.config.request({method:"POST",url:`${$(this.config,t)}/${encodeURIComponent(s)}/_apis/security/permissionevaluationbatch?api-version=7.0`,body:JSON.stringify(u),headers:{...S(this.config,t),"Content-Type":"application/json"}})).body.evaluations.reduce((d,c)=>{let[,g,m]=c.token.split("/"),h=`${g}/${m}`,y=i[c.permissions];for(let f of y)d[h]===void 0&&(d[h]={canCreateWebhook:!0,canPush:!0,isAdmin:!0}),c.value===!1&&(d[h][f]=!1);return d},{})}}async decorateReposWithPermissions(e,t={}){let{namespace:s,repos:o}=e,i=await this.getPermissionsForRepos({namespace:s,repos:o},t);return{data:o.map(a=>({...a,permissions:i.data[`${a.projectId}/${a.id}`]}))}}async updateIssue(e,t,s={}){return await this.config.request({method:"PATCH",url:`${$(this.config,s)}/${encodeURIComponent(e.project.namespace)}/${encodeURIComponent(e.project.name)}/_apis/wit/workitems/${e.id}?api-version=6.0`,body:JSON.stringify(t),headers:{...S(this.config,s),"Content-Type":"application/json-patch+json"}})}async setIssueStatus(e,t={}){let{issue:s,status:o}=e,i=[{op:"add",path:"/fields/System.State",value:o.name}];if(!(await this.updateIssue(s,i,t)).body.fields?.["System.State"])throw new Error("Could not set issue status")}async setIssueAssignee(e,t={}){let{issue:s,assignee:o}=e,i=[{op:"add",path:"/fields/System.AssignedTo",value:o?.name??""}];if(!(await this.updateIssue(s,i,t)).body.fields?.["System.State"])throw new Error("Could not set issue assignee")}async setIssueLabels(e,t={}){let{issue:s,labels:o}=e,a=[{op:"replace",path:"/fields/System.Tags",value:o.map(l=>l.name).join(";")}];if(!(await this.updateIssue(s,a,t)).body.fields?.["System.Tags"])throw new Error("Could not set issue tags")}async getIssueTypesForAzureProject(e,t={}){if(!e.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let{namespace:s,project:o}=e;return{data:(await this.config.request({url:`${$(this.config,t)}/${encodeURIComponent(s)}/${encodeURIComponent(o||"")}/_apis/wit/workitemtypes?api-version=6.0`,headers:{...S(this.config,t)}})).body.value}}async getLabelsForProject(e,t={}){let{namespace:s,project:o}=e;return{data:(await this.config.request({url:`${$(this.config,t)}/${encodeURIComponent(s)}/${encodeURIComponent(o||"")}/_apis/wit/tags?api-version=6.0`,headers:{...S(this.config,t)}})).body.value.map(a=>({color:null,description:null,id:a.id,name:a.name,url:a.url}))}}async getPullRequestForRepo(e,t={}){let{repo:s,number:o}=e;if(!s.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let i=await this.config.request({url:`${this.getRepoApiUrl(s.namespace,s.project,s.name,t)}/pullrequests/${o}?api-version=7.1`,headers:S(this.config,t)}),a=await this.fetchRemoteInfoByRepoId(e.includeRemoteInfo,[{namespace:s.namespace,pullRequests:[i.body]}],t);return{data:ve(s.namespace,i.body,a)}}async getPullRequestDescription(e,t={}){let{repo:s,number:o}=e;if(!s.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');try{return{data:{description:(await this.config.request({url:`${this.getRepoApiUrl(s.namespace,s.project,s.name,t)}/pullrequests/${o}?api-version=7.1`,headers:S(this.config,t)})).body?.description??""}}}catch{return{data:{description:null}}}}async setPullRequestDescription(e,t={}){let{repo:s,number:o,description:i}=e;if(!s.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');return{data:{description:(await this.config.request({method:"PATCH",url:`${this.getRepoApiUrl(s.namespace,s.project,s.name,t)}/pullrequests/${o}?api-version=7.1`,headers:{...S(this.config,t),"Content-Type":"application/json"},body:JSON.stringify({description:i})})).body?.description??i}}}async getMergeBase(e,t={}){if(!e.repo.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let s=await this.config.request({url:`${this.getRepoApiUrl(e.repo.namespace,e.repo.project,e.repo.name,t)}/commits/${encodeURIComponent(e.base)}/mergebases?otherCommitId=${encodeURIComponent(e.head)}&api-version=7.1`,headers:S(this.config,t)});if(!s.body.value?.length)throw new Error("No merge base found between the specified commits.");return{data:s.body.value[0].commitId}}async getFileContents(e,t={}){if(!e.repo.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let s=await this.config.request({url:`${this.getRepoApiUrl(e.repo.namespace,e.repo.project,e.repo.name,t)}/items?path=${encodeURIComponent(e.path)}&versionDescriptor[version]=${encodeURIComponent(e.ref)}&versionDescriptor[versionType]=commit&api-version=7.1`,headers:{...S(this.config,t),Accept:"application/octet-stream"}});return{data:new Blob([s.body])}}async getPullRequestDiff(e,t={}){if(!e.repo.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let s=this.getRepoApiUrl(e.repo.namespace,e.repo.project,e.repo.name,t),o=S(this.config,t),i={...o,Accept:"application/octet-stream"},[a,u]=await Promise.all([this.config.request({url:`${s}/pullrequests/${e.pullRequestId}?api-version=7.1`,headers:o}),this.config.request({url:`${s}/pullrequests/${e.pullRequestId}/iterations?api-version=7.1`,headers:o})]),l=a.body.lastMergeTargetCommit.commitId,p=a.body.lastMergeSourceCommit.commitId,d=u.body.value;if(d.length===0)return"";let c=d[d.length-1],g=1e3,m=[],h=0;for(;;){let E=(await this.config.request({url:`${s}/pullrequests/${e.pullRequestId}/iterations/${c.id}/changes?api-version=7.1&$top=${g}&$skip=${h}`,headers:o})).body.changeEntries??[];if(E.length===0||(m.push(...E),E.length<g))break;h+=E.length}if(m.length===0)return"";let y=5,f=[],P=new TextDecoder,q=w=>w instanceof ArrayBuffer?P.decode(w):typeof w=="string"?w:"",L=async(w,E)=>{try{let ne=await this.config.request({url:`${s}/items?path=${encodeURIComponent(w)}&versionDescriptor[version]=${encodeURIComponent(E)}&versionDescriptor[versionType]=commit&includeContent=true&api-version=7.1`,headers:i});return q(ne.body)}catch{return""}},D=w=>{if(typeof w=="number")return{add:(w&1)!==0,rename:(w&8)!==0,delete:(w&16)!==0};let E=w.toLowerCase().split(",").map(ne=>ne.trim());return{add:E.includes("add"),rename:E.includes("rename"),delete:E.includes("delete")}};for(let w=0;w<m.length;w+=y){let E=m.slice(w,w+y),ne=await Promise.all(E.map(async de=>{let{add:ce,rename:ct,delete:oe}=D(de.changeType),qe=de.originalPath??de.item.originalPath,T=de.item.path,Ge=oe?T??qe??"":T??"",rr=ct||oe?qe??Ge:Ge,[Ps,ws]=await Promise.all([ce?Promise.resolve(""):L(rr,l),oe?Promise.resolve(""):L(Ge,p)]),Ss=ce?"/dev/null":`a${rr}`,qs=oe?"/dev/null":`b${Ge}`;return(0,Rr.createTwoFilesPatch)(Ss,qs,Ps,ws)}));f.push(...ne)}return f.join(`
2
+ `)}getPullRequestWriteHeaders(e){return{...S(this.config,e),"Content-Type":"application/json"}}setReviewerVote(e,t,s,o,i){return this.config.request({method:"PUT",url:`${e}/pullRequests/${t}/reviewers/${encodeURIComponent(s)}?api-version=7.1`,headers:this.getPullRequestWriteHeaders(i),body:JSON.stringify({vote:o})})}postPullRequestThread(e,t,s,o){return this.config.request({method:"POST",url:`${e}/pullRequests/${t}/threads?api-version=7.1`,headers:this.getPullRequestWriteHeaders(o),body:JSON.stringify({comments:[{parentCommentId:0,content:s,commentType:1}],status:1})})}async getCommentsForPullRequest(e,t={}){if(!e.repo.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let s=this.getRepoApiUrl(e.repo.namespace,e.repo.project,e.repo.name,t),o=S(this.config,t),i=await this.config.request({url:`${s}/pullRequests/${e.pullRequestNumber}/threads?api-version=7.1`,headers:o}),a=[];for(let u of i.body.value)if(!(u.isDeleted||u.threadContext))for(let l of u.comments)l.commentType==="system"||l.isDeleted||a.push({id:Pt(e.repo.namespace,e.repo.project,e.repo.name,e.pullRequestNumber,u.id,l.id),author:l.author?le(l.author):null,body:l.content||"",createdAt:l.publishedDate?new Date(l.publishedDate):null,url:""});return{data:a,pageInfo:{hasNextPage:!1,endCursor:null}}}async addCommentToPullRequest(e,t={}){if(!e.pullRequest.repository.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let s=this.getRepoApiUrl(e.pullRequest.repository.owner.login,e.pullRequest.repository.project,e.pullRequest.repository.name,t);await this.postPullRequestThread(s,e.pullRequest.id,e.comment,t)}async addInlineCommentToPullRequest(e,t={}){if(!e.pullRequest.repository.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let s=this.getRepoApiUrl(e.pullRequest.repository.owner.login,e.pullRequest.repository.project,e.pullRequest.repository.name,t),o=this.getPullRequestWriteHeaders(t);if(e.threadId){let p=wt(e.threadId),d=e.pullRequest.repository.owner.login,c=e.pullRequest.repository.project,g=e.pullRequest.repository.name,m=String(e.pullRequest.id);if(p.namespace!==d||p.project!==c||p.repoName!==g||p.prId!==m)throw new Error(`Azure thread ID context mismatch: threadId targets ${p.namespace}/${p.project}/${p.repoName} pull request ${p.prId}, but input.pullRequest targets ${d}/${c}/${g} pull request ${m}.`);let y=(await this.config.request({url:`${s}/pullRequests/${e.pullRequest.id}/threads/${p.threadId}?api-version=7.1`,headers:S(this.config,t)})).body.comments?.find(P=>P.parentCommentId===0);if(!y)throw new Error(`Could not determine root comment for Azure DevOps thread ${p.threadId}.`);let f=await this.config.request({method:"POST",url:`${s}/pullRequests/${e.pullRequest.id}/threads/${p.threadId}/comments?api-version=7.1`,headers:o,body:JSON.stringify({content:e.comment,parentCommentId:y.id,commentType:1})});return Pt(d,c,g,Number(m),Number(p.threadId),f.body.id)}let i=e.path.startsWith("/")?e.path:`/${e.path}`,a={line:e.line,offset:1},u={filePath:i};e.side==="LEFT"?(u.leftFileStart=a,u.leftFileEnd=a):(u.rightFileStart=a,u.rightFileEnd=a);let l=await this.config.request({method:"POST",url:`${s}/pullRequests/${e.pullRequest.id}/threads?api-version=7.1`,headers:o,body:JSON.stringify({comments:[{parentCommentId:0,content:e.comment,commentType:1}],status:1,threadContext:u})});return hr(e.pullRequest.repository.owner.login,e.pullRequest.repository.project,e.pullRequest.repository.name,Number(e.pullRequest.id),l.body.id)}async editComment(e,t={}){let s=gr(e.commentId),o=this.getRepoApiUrl(s.namespace,s.project,s.repoName,t);await this.config.request({method:"PATCH",url:`${o}/pullRequests/${s.prId}/threads/${s.threadId}/comments/${s.commentId}?api-version=7.1`,headers:this.getPullRequestWriteHeaders(t),body:JSON.stringify({content:e.body})})}async editInlineComment(e,t={}){return this.editComment(e,t)}async deleteComment(e,t={}){let s=gr(e.commentId),o=this.getRepoApiUrl(s.namespace,s.project,s.repoName,t);await this.config.request({method:"DELETE",url:`${o}/pullRequests/${s.prId}/threads/${s.threadId}/comments/${s.commentId}?api-version=7.1`,headers:S(this.config,t)})}async deleteInlineComment(e,t={}){return this.deleteComment(e,t)}async resolveReviewThread(e,t={}){let s=wt(e.threadId),o=this.getRepoApiUrl(s.namespace,s.project,s.repoName,t);await this.config.request({method:"PATCH",url:`${o}/pullRequests/${s.prId}/threads/${s.threadId}?api-version=7.1`,headers:this.getPullRequestWriteHeaders(t),body:JSON.stringify({status:2})})}async unresolveReviewThread(e,t={}){let s=wt(e.threadId),o=this.getRepoApiUrl(s.namespace,s.project,s.repoName,t);await this.config.request({method:"PATCH",url:`${o}/pullRequests/${s.prId}/threads/${s.threadId}?api-version=7.1`,headers:this.getPullRequestWriteHeaders(t),body:JSON.stringify({status:1})})}async approvePullRequest(e,t={}){if(!e.pullRequest.repository.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let s=e.pullRequest.repository.owner.login,o=this.getRepoApiUrl(s,e.pullRequest.repository.project,e.pullRequest.repository.name,t),i=await this.getCurrentUserId(s,t);await Promise.all([this.setReviewerVote(o,e.pullRequest.id,i,10,t),e.comment?this.postPullRequestThread(o,e.pullRequest.id,e.comment,t):null])}async requestPullRequestChanges(e,t={}){if(!e.pullRequest.repository.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let s=e.pullRequest.repository.owner.login,o=this.getRepoApiUrl(s,e.pullRequest.repository.project,e.pullRequest.repository.name,t),i=await this.getCurrentUserId(s,t);await this.postPullRequestThread(o,e.pullRequest.id,e.comment,t),await this.setReviewerVote(o,e.pullRequest.id,i,-5,t)}async commentOnPullRequest(e,t={}){if(!e.pullRequest.repository.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let s=this.getRepoApiUrl(e.pullRequest.repository.owner.login,e.pullRequest.repository.project,e.pullRequest.repository.name,t);await this.postPullRequestThread(s,e.pullRequest.id,e.comment,t)}async getReviewsForPullRequest(e,t={}){if(!e.repo.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let{namespace:s,project:o,name:i}=e.repo,{pullRequestId:a}=e,u=this.getRepoApiUrl(s,o,i,t),l=S(this.config,t),[p,d]=await Promise.all([this.config.request({url:`${u}/pullRequests/${a}/reviewers?api-version=7.1`,headers:l}),this.config.request({url:`${u}/pullRequests/${a}/threads?api-version=7.1`,headers:l})]),c=(f,P)=>Pt(s,o,i,a,f,P),g=f=>hr(s,o,i,a,f),m=new Map;for(let f of d.body.value){if(f.isDeleted)continue;let P=f.comments.filter(T=>!T.isDeleted&&T.commentType!=="system"),q=P.find(T=>T.parentCommentId===0)??P[0];if(!q)continue;let L=q.author?.id;if(!L)continue;let D=P.filter(T=>T.id!==q.id),w=f.threadContext,E=w?.rightFileStart?{side:"RIGHT",start:w.rightFileStart,end:w.rightFileEnd}:w?.leftFileStart?{side:"LEFT",start:w.leftFileStart,end:w.leftFileEnd}:null,ne=E?.end?.line??E?.start.line??null,de=E?.start&&E.end&&E.start.line!==E.end.line?E.start.line:null,ce=w?.filePath??"",ct=ce.startsWith("/")?ce.slice(1):ce,oe={id:c(f.id,q.id),author:q.author?le(q.author):null,body:q.content??"",createdAt:q.publishedDate?new Date(q.publishedDate):null,url:"",diffLines:[],filename:ct,replies:D.map(T=>({id:c(f.id,T.id),author:T.author?le(T.author):null,body:T.content??"",createdAt:T.publishedDate?new Date(T.publishedDate):null,url:""})),isOutdated:!1,isResolved:Ws.has(Hs(f.status)),line:ne,startLine:de,side:E?.side??null,threadId:g(f.id)},qe=m.get(L);qe?qe.push(oe):m.set(L,[oe])}let h=[],y=new Set;for(let f of p.body.value){if(f.hasDeclined)continue;let P=f.vote??0,q=m.get(f.id);P===0&&!q?.length||(h.push({id:f.id,author:le(f),body:"",createdAt:null,url:"",reviewComments:q??[]}),y.add(f.id))}for(let[f,P]of m){if(y.has(f)||!P.length)continue;let q=P[0].author;q&&h.push({id:f,author:q,body:"",createdAt:null,url:"",reviewComments:P})}return{data:h}}};var G=(r,n={})=>R(n.token||r.token,n.isPAT||r.isPAT);var O="https://api.bitbucket.org/2.0",Xs={OPEN:"OPEN",MERGED:"MERGED",DECLINED:"CLOSED",SUPERSEDED:"CLOSED"},Zs={OPEN:["OPEN"],MERGED:["MERGED"],CLOSED:["DECLINED","SUPERSEDED"]},xe=50,Ys=5,Ir=r=>{let n=!r||r.length===0?["OPEN"]:Array.from(new Set(r.flatMap(t=>Zs[t]))),e=n.map(t=>`state="${t}"`).join(" OR ");return n.length>1?`(${e})`:e},en=r=>r.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),br=r=>{let n=r?.trim();if(!n)return null;let e=en(n);return`(title ~ "${e}" OR description ~ "${e}")`},yr=r=>{let n=!!r.next,e=typeof r.size=="number"?r.size:null,t=typeof r.pagelen=="number"&&r.pagelen>0?r.pagelen:null;return{hasNextPage:n,nextPage:n?r.page+1:null,currentPage:typeof r.page=="number"?r.page:null,totalCount:e,totalPages:e!==null&&t?Math.ceil(e/t):null}},ke={owner:4,admin:3,contributor:2,member:1},Ne=r=>({id:r.uuid,name:r.display_name||r.nickname,username:r.nickname||r.display_name,email:null,avatarUrl:r.links.avatar.href,url:r.links.html.href}),Pr=r=>{let n=r.links.clone,e=n?.find(s=>s.name==="ssh"),t=n?.find(s=>s.name==="https");return e&&t?{cloneUrlHTTPS:t.href,cloneUrlSSH:e.href}:null},St=r=>({id:r.uuid,namespace:r.workspace.slug,name:r.slug,webUrl:r.links.html.href,httpsUrl:r.links.clone.find(n=>n.name==="https")?.href??null,sshUrl:r.links.clone.find(n=>n.name==="ssh")?.href??null,defaultBranch:{name:r.mainbranch.name},permissions:null}),qt=r=>{let n=r.id,e=r.participants?.map(t=>{let s="REVIEW_REQUESTED";return t.approved?s="APPROVED":t.state==="changes_requested"?s="CHANGES_REQUESTED":t.participated_on!==null&&(s="COMMENTED"),{reviewer:Ne(t.user),state:s}})??[];return{id:n.toString(),title:r.title,description:r.description,number:n,state:Xs[r.state],isDraft:!1,commentCount:r.comment_count,upvoteCount:null,author:Ne(r.author),createdDate:new Date(r.created_on),updatedDate:new Date(r.updated_on),closedDate:null,mergedDate:null,repository:{id:r.destination.repository.uuid,name:r.destination.repository.name,owner:{login:r.destination.repository.full_name.split("/")[0]},remoteInfo:Pr(r.destination.repository)},headCommit:{buildStatuses:null},baseRef:{name:r.destination.branch.name,oid:r.destination.commit.hash},headRef:{name:r.source.branch.name,oid:r.source.commit.hash},url:r.links.html.href,assignees:null,reviews:e,reviewDecision:B(e),additions:null,deletions:null,fileCount:null,commitCount:null,isCrossRepository:r.source.repository.uuid!==r.destination.repository.uuid,headRepository:{id:r.source.repository.uuid,name:r.source.repository.name,owner:{login:r.source.repository.full_name.split("/")[0]},remoteInfo:Pr(r.source.repository)},mergeableState:"MERGEABLE",permissions:null}},tn=r=>{switch(r){case"owner":case"admin":return{canCreateWebhook:!0,canPush:!0,isAdmin:!0};case"write":return{canCreateWebhook:!1,canPush:!0,isAdmin:!1};case"read":case"none":return{canCreateWebhook:!1,canPush:!1,isAdmin:!1}}},rn=r=>{switch(r){case"owner":case"admin":return{canCreateWebhook:!0,canPush:!0,isAdmin:!0};case"contributor":return{canCreateWebhook:!1,canPush:!0,isAdmin:!1};default:return{canCreateWebhook:!1,canPush:!1,isAdmin:!1}}},Re=class extends j{async refreshToken(n){return{data:(await this.config.request({url:"https://bitbucket.org/site/oauth2/access_token",method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Authorization:`Basic ${n.base64ClientIDColonClientSecret}`},body:`grant_type=refresh_token&refresh_token=${n.refreshToken}`})).body}}async getCurrentUser(n={},e={}){let t=await this.config.request({url:`${O}/user`,headers:G(this.config,e)});return{data:Ne(t.body)}}async getUserForCommit(n,e={}){let s=(await this.config.request({url:`${O}/repositories/${n.repo.namespace}/${n.repo.name}/commit/${n.oid}`,headers:G(this.config,e)})).body.author,o=s.raw.match(/([^<]+)<(.+)>/);return{data:{name:o?o[1].trim():null,email:o?o[2]:null,avatarUrl:s.user?.links.avatar.href||null}}}async getRepo(n,e={}){let t=await this.config.request({url:`${O}/repositories/${n.namespace}/${n.name}`,headers:G(this.config,e)});return{data:St(t.body)}}async getRepos(n,e={}){let t=[],s=[];return await Promise.all(n.map(async o=>{try{let i=await this.getRepo(o,e);t.push(i.data)}catch(i){s.push({input:o,error:i})}})),{data:t,errors:s}}async getReposForWorkspace(n,e={}){let t=new URL(`${O}/repositories/${encodeURIComponent(n.workspace)}`);t.searchParams.set("page",n.page?.toString()||"1"),t.searchParams.set("pagelen",C.toString()),n.minimumRole&&t.searchParams.set("role",n.minimumRole);let s=await this.config.request({url:t.toString(),headers:G(this.config,e)}),o=!!s.body.next;return{pageInfo:{hasNextPage:o,nextPage:o?s.body.page+1:null},data:s.body.values.map(St)}}async getAllReposForWorkspace(n,e={}){let t=[],s=1;for(;s!==null;){let o=await this.getReposForWorkspace({workspace:n.workspace,minimumRole:n.minimumRole,page:s},e);t.push(...o.data),s=o.pageInfo.hasNextPage?o.pageInfo.nextPage:null}return t}async getAllReposForWorkspaceWithPermissions(n,e={}){let t=new Map,s=[],o=ke[n.minimumRole||"member"];o<=ke.admin&&s.push("admin"),o<=ke.contributor&&s.push("contributor"),o<=ke.member&&s.push("member");let i=[];for(let a of s){i=await this.getAllReposForWorkspace({workspace:n.workspace,minimumRole:a},e);for(let u of i)t.has(u.id)||t.set(u.id,a)}return{data:i.map(a=>{let u=t.get(a.id)||"member";return{...a,permissions:rn(u)}})}}async getReposForCurrentUser(n,e={}){let t=new URL(`${O}/repositories`);t.searchParams.set("role","member"),t.searchParams.set("pagelen",C.toString()),n.cursor&&t.searchParams.set("after",n.cursor);let s=await this.config.request({url:t.toString(),headers:G(this.config,e)}),o=!!s.body.next,i=null;return s.body.next&&(i=new URL(s.body.next).searchParams.get("after")),{pageInfo:{hasNextPage:o,endCursor:i},data:s.body.values.map(St)}}async getBranches(n,e={}){let t=new URL(`${O}/repositories/${n.repo.namespace}/${n.repo.name}/refs/branches`);t.searchParams.set("page",n.page?.toString()||"1"),t.searchParams.set("pagelen",C.toString());let s=await this.config.request({url:t.toString(),headers:G(this.config,e)}),o=!!s.body.next;return{pageInfo:{hasNextPage:o,nextPage:o?s.body.page+1:null},data:s.body.values.map(i=>{let a=new Date(i.target.date);return{name:i.name,commit:{oid:i.target.hash,authoredDate:a,committedDate:a}}})}}async getTags(n,e={}){let t=new URL(`${O}/repositories/${n.repo.namespace}/${n.repo.name}/refs/tags`);t.searchParams.set("pagelen",C.toString()),n.cursor&&t.searchParams.set("page",n.cursor);let s=await this.config.request({url:t.toString(),headers:G(this.config,e)}),o=!!s.body.next,i=null;return s.body.next&&(i=new URL(s.body.next).searchParams.get("page")),{pageInfo:{hasNextPage:o,endCursor:i},data:s.body.values.map(a=>{let u=new Date(a.target.date);return{name:a.name,commit:{oid:a.target.hash,authoredDate:u,committedDate:u}}})}}async getWorkspacesForCurrentUser(n={},e={}){let t=new URL(`${O}/user/workspaces`);t.searchParams.set("page",n?.page?.toString()||"1"),t.searchParams.set("pagelen","50"),n?.administrator!==void 0&&t.searchParams.set("administrator",n.administrator.toString());let s=await this.config.request({url:t.toString(),headers:G(this.config,e)}),o=!!s.body.next;return{pageInfo:{hasNextPage:o,nextPage:o?s.body.page+1:null},data:s.body.values.map(i=>({id:i.workspace.uuid,slug:i.workspace.slug}))}}async getWorkspacesForUser(n,e={}){let t=new URL(`${O}/user/permissions/workspaces`);t.searchParams.set("page",n.page?.toString()||"1"),t.searchParams.set("pagelen","50");let s=await this.config.request({url:t.toString(),headers:G(this.config,e)}),o=!!s.body.next;return{pageInfo:{hasNextPage:o,nextPage:o?s.body.page+1:null},data:s.body.values.map(i=>({id:i.workspace.uuid,slug:i.workspace.slug,name:i.workspace.name}))}}async getPullRequestsForUserAndWorkspace(n,e={}){let t=new URL(`${O}/workspaces/${n.workspaceSlug}/pullrequests/${n.userId}`);t.searchParams.set("fields","+values.participants,+values.destination.repository.links.clone.*,+values.source.repository.links.clone.*"),t.searchParams.set("page",n.page?.toString()||"1"),t.searchParams.set("pagelen",U(n.pageSize,{fallback:xe,max:xe}).toString());let s=[Ir(n.states)];n.repos&&n.repos.length>0&&s.push(`(${n.repos.map(a=>`source.repository.full_name = "${a.namespace}/${a.name}"`).join(" OR ")})`);let o=br(n.query);o&&s.push(o),t.searchParams.set("q",s.join(" AND "));let i=await this.config.request({url:t.toString(),headers:G(this.config,e)});return{pageInfo:yr(i.body),data:i.body.values.map(qt)}}async getPullRequestsForReviewerAndWorkspace(n,e={}){let t=n.repos?.length?n.repos:await this.getAllReposForWorkspace({workspace:n.workspaceSlug},e);return this.getPullRequestsForRepos({repos:t,reviewerId:n.reviewerId,states:n.states,query:n.query,pageSize:n.pageSize},e)}async getPullRequestsForRepoBase(n,e={}){let t=new URL(`${O}/repositories/${encodeURI(n.repo.namespace)}/${encodeURI(n.repo.name)}/pullrequests`),s=[];n.reviewerId&&s.push(`reviewers.uuid="${n.reviewerId}"`),n.authorLogin&&s.push(`author.uuid="${n.authorLogin}"`);let o=Ir(n.states);s.length&&(o+=` AND (${s.join(n.useOrFilter?" OR ":" AND ")})`);let i=br(n.query);return i&&(o+=` AND ${i}`),t.searchParams.set("fields","+values.participants,+values.destination.repository.links.clone.*,+values.source.repository.links.clone.*"),t.searchParams.set("page",n.page?.toString()||"1"),t.searchParams.set("pagelen",U(n.pageSize,{fallback:xe,max:xe}).toString()),t.searchParams.set("q",o),await this.config.request({url:t.toString(),headers:G(this.config,e)})}async getPullRequestsForRepo(n,e={}){let t=[],s=await this.getPullRequestsForRepoBase(n,e);return s.body.values.forEach(o=>{t.push(qt(o))}),{pageInfo:yr(s.body),data:t}}async getPullRequestsForRepos(n,e={}){let{successes:t,metadata:s}=await J(n.repos,{run:i=>this.getPullRequestsForRepoBase({repo:i,authorLogin:n.authorLogin,reviewerId:n.reviewerId,useOrFilter:n.useOrFilter,states:n.states,query:n.query,pageSize:n.pageSize},e),failureScope:i=>({providerId:"bitbucket",repositoryId:ae(i)}),completeness:i=>i.body.next?"partial":"complete",concurrency:Ys}),o=[];return t.forEach(({result:i})=>{i.body.values.forEach(a=>{o.push(qt(a))})}),{data:o,metadata:s}}async getAccountsForWorkspace(n,e={}){let t=new URL(`${O}/workspaces/${encodeURI(n.workspace)}/members`);t.searchParams.set("page",n.page?.toString()||"1"),t.searchParams.set("pagelen","100");let s=await this.config.request({url:t.toString(),headers:G(this.config,e)}),o=!!s.body.next;return{pageInfo:{hasNextPage:o,nextPage:o?s.body.page+1:null},data:s.body.values.map(i=>Ne(i.user))}}async getReposPermissionsForCurrentUser(n,e={}){let t=new URL(`${O}/user/permissions/repositories`);t.searchParams.set("page",n.page?.toString()||"1"),t.searchParams.set("pagelen","100");let s=await this.config.request({url:t.toString(),headers:G(this.config,e)}),o=!!s.body.next;return{pageInfo:{hasNextPage:o,nextPage:o?s.body.page+1:null},data:s.body.values.reduce((i,a)=>({...i,[a.repository.uuid]:tn(a.permission)}),{})}}async decorateReposWithPermissions(n,e={}){let t={},s=1;do{let o=await this.getReposPermissionsForCurrentUser({page:s},e);t={...o.data,...t},s=o.pageInfo.hasNextPage?o.pageInfo.nextPage:null}while(s!==null);return{data:n.repos.map(o=>({...o,permissions:t[o.id]??{canCreateWebhook:!1,canPush:!1,isAdmin:!1}}))}}async closePullRequest(n,e={}){let{pullRequest:t}=n;if(!(await this.config.request({method:"POST",url:`${O}/repositories/${t.repository.owner.login}/${t.repository.name}/pullrequests/${t.id}/decline`,headers:G(this.config,e)})).body.title)throw new Error("Could not close pull request")}async mergePullRequest(n,e={}){let{pullRequest:t,mergeStrategy:s}=n,o;switch(s){case"MERGE_COMMIT":{o="merge_commit";break}case"FAST_FORWARD":{o="fast_forward";break}case"SQUASH":{o="squash";break}}let i={merge_strategy:o,type:"pullrequest"};if(!(await this.config.request({method:"POST",url:`${O}/repositories/${t.repository.owner.login}/${t.repository.name}/pullrequests/${t.id}/merge`,body:JSON.stringify(i),headers:{...G(this.config,e),"Content-Type":"application/json"}})).body.title)throw new Error("Could not merge pull request")}async setPullRequestReviewers(n,e={}){let{pullRequest:t,reviewers:s}=n,o={reviewers:s.map(a=>{if(a.username)throw new Error('Bitbucket reviewer requires "username" for this function.');return{username:a.username}})};if(!(await this.config.request({method:"PUT",url:`${O}/repositories/${t.repository.owner.login}/${t.repository.name}/pullrequests/${t.id}`,body:JSON.stringify(o),headers:{...G(this.config,e),"Content-Type":"application/json"}})).body.title)throw new Error("Could not set pull request reviewers")}};var wr=r=>r?r.find(n=>n.permission==="USER_ADMIN"||n.permission==="PROJECT_ADMIN"||n.permission==="ADMIN"||n.permission==="SYS_ADMIN"||n.permission==="REPO_ADMIN")?{canCreateWebhook:!0,canPush:!0,isAdmin:!0}:r.find(n=>n.permission==="REPO_WRITE"||n.permission==="REPO_CREATE"||n.permission==="PROJECT_CREATE"||n.permission==="PROJECT_WRITE")?{canCreateWebhook:!1,canPush:!0,isAdmin:!1}:{canCreateWebhook:!1,canPush:!1,isAdmin:!1}:{canCreateWebhook:!1,canPush:!1,isAdmin:!1};var Ee=r=>{let n=r.links.self[0].href;return{name:r.displayName,email:r.emailAddress,avatarUrl:r.avatarUrl??(n&&`${n}/avatar.png`),id:r.id.toString(),username:r.name,url:n}},Fe=r=>{let n={OPEN:"OPEN",MERGED:"MERGED",DECLINED:"CLOSED"},e={UNAPPROVED:"REVIEW_REQUESTED",NEEDS_WORK:"CHANGES_REQUESTED",APPROVED:"APPROVED"},t=r.reviewers.map(u=>({reviewer:Ee(u.user),state:e[u.status]})),s=r.toRef.repository.links.clone.find(u=>u.name==="ssh")?.href??null,o=r.toRef.repository.links.clone.find(u=>u.name==="https")?.href??null;o||(o=r.toRef.repository.links.clone.find(u=>u.name==="http")?.href??null);let i=r.fromRef.repository.links.clone.find(u=>u.name==="ssh")?.href??null,a=r.fromRef.repository.links.clone.find(u=>u.name==="https")?.href??null;return a||(a=r.fromRef.repository.links.clone.find(u=>u.name==="http")?.href??null),{id:r.id.toString(),number:r.id,title:r.title,description:r.description,url:r.links.self[0].href,state:n[r.state],isDraft:!1,createdDate:new Date(r.createdDate),updatedDate:new Date(r.updatedDate),closedDate:r.closedDate?new Date(r.closedDate):null,mergedDate:r.state=="MERGED"&&r.closedDate?new Date(r.closedDate):null,baseRef:{name:r.toRef.displayId,oid:r.toRef.latestCommit},headRef:{name:r.fromRef.displayId,oid:r.fromRef.latestCommit},commentCount:r.properties.commentCount,upvoteCount:null,commitCount:null,fileCount:null,additions:null,deletions:null,author:Ee(r.author.user),assignees:null,reviews:t,reviewDecision:B(t),isCrossRepository:r.fromRef.repository.id!==r.toRef.repository.id,repository:{id:r.toRef.repository.id.toString(),name:r.toRef.repository.name,owner:{login:r.toRef.repository.project.key},remoteInfo:o&&s?{cloneUrlHTTPS:o,cloneUrlSSH:s}:null},headRepository:{id:r.fromRef.repository.id.toString(),name:r.fromRef.repository.name,owner:{login:r.fromRef.repository.project.key},remoteInfo:a&&i?{cloneUrlHTTPS:a,cloneUrlSSH:i}:null},headCommit:null,mergeableState:"MERGEABLE",permissions:null,version:r.version}},Sr=r=>({id:r.id.toString(),namespace:r.project.key,name:r.slug,webUrl:r.links.self[0]?.href??null,httpsUrl:r.links.clone.find(n=>n.name==="https"||n.name==="http")?.href??null,sshUrl:r.links.clone.find(n=>n.name==="ssh")?.href??null,defaultBranch:null,permissions:null}),qr=50,sn=5,nn={OPEN:"OPEN",MERGED:"MERGED",CLOSED:"DECLINED"},vr=r=>{if(!r||r.length===0)return"OPEN";let n=Array.from(new Set(r.map(e=>nn[e])));return n.length===1?n[0]:"ALL"},Er=(r,n)=>typeof r!="number"||n<=0?null:Math.floor(r/n)+1,Ie=class extends N{getBaseUrl(n){let e=n.baseUrl||this.config.baseUrl;if(!e)throw new Error('Bitbucket Server requires "baseUrl"');return e}getRequestHeaders(n){return R(n.token||this.config.token)}async getCurrentUser(n={},e={}){let t=await this.config.request({url:`${this.getBaseUrl(e)}/users?limit=2`,headers:this.getRequestHeaders(e)}),{headers:{"x-auserid":s,"x-ausername":o}}=t,i=s?parseInt(s,10):null,a=decodeURIComponent(o),l=(await this.config.request({url:`${this.getBaseUrl(e)}/users?filter=${o}&avatarSize=64`,headers:this.getRequestHeaders(e)})).body.values.find(({emailAddress:p,id:d,name:c,slug:g})=>i?i===d:a===c||a===p||a===g);if(!l)throw new Error("Could not find current Bitbucket Server user");return{data:Ee(l)}}async getUserForCommit(n,e){let{repo:t,oid:s}=n,o=await this.config.request({url:`${this.getBaseUrl(e)}/projects/${t.namespace}/repos/${t.name}/commits/${s}`,headers:this.getRequestHeaders(e)});if(!o.body.author)throw new Error("Could not find user for commit");return{data:Ee(o.body.author)}}async getRepo(n,e={}){let t=await this.config.request({url:`${this.getBaseUrl(e)}/projects/${n.namespace}/repos/${n.name}`,headers:this.getRequestHeaders(e)});return{data:Sr(t.body)}}async getRepos(n,e={}){let t=[],s=[];return await Promise.all(n.map(async o=>{try{let i=await this.getRepo(o,e);t.push(i.data)}catch(i){s.push({input:o,error:i})}})),{data:t,errors:s}}async getReposForCurrentUser(n,e={}){let t=n.page??0,s=await this.config.request({url:`${this.getBaseUrl(e)}/repos?start=${t}`,headers:this.getRequestHeaders(e)});return{pageInfo:{hasNextPage:!s.body.isLastPage,nextPage:s.body.nextPageStart},data:s.body.values.map(Sr)}}async getRepoPermissionsForUsername(n,e={}){let t=new URL(`${this.getBaseUrl(e)}/projects/${n.repo.namespace}/repos/${n.repo.name}/permissions/search?filterText=${n.username}`);try{let s=await this.config.request({url:t.toString(),headers:this.getRequestHeaders(e)});return{data:wr(s.body.values)}}catch(s){if(s.response?.status===401)return{data:{canCreateWebhook:!1,canPush:!1,isAdmin:!1}};throw s}}async decorateReposWithPermissions(n,e={}){return await Promise.all(n.repos.map(async s=>{let o=await this.getRepoPermissionsForUsername({repo:s,username:n.username},e);return{...s,permissions:o.data}}))}async getPullRequestsForRepoBase(n,e={}){let t=new URL(`${this.getBaseUrl(e)}/projects/${encodeURI(n.repo.namespace)}/repos/${encodeURI(n.repo.name)}/pull-requests`);return t.searchParams.set("state",vr(n.states)),t.searchParams.set("start",n.page?.toString()||"0"),t.searchParams.set("limit",U(n.pageSize,{fallback:qr}).toString()),n.reviewerLogin&&(t.searchParams.set("role.1","REVIEWER"),t.searchParams.set("username.1",n.reviewerLogin)),await this.config.request({url:t.toString(),headers:this.getRequestHeaders(e)})}async getPullRequestsForRepo(n,e={}){let t=[],s=await this.getPullRequestsForRepoBase(n,e);s.body.values.forEach(i=>{if(n.authorLogin&&i.author.user.name!==n.authorLogin)return null;t.push(Fe(i))});let o=!s.body.isLastPage;return{pageInfo:{hasNextPage:o,nextPage:o?s.body.nextPageStart:null,currentPage:Er(s.body.start,s.body.limit)},data:k(t,n.states)}}async getPullRequestsForRepos(n,e={}){let{successes:t,metadata:s}=await J(n.repos,{run:i=>this.getPullRequestsForRepoBase({repo:i,reviewerLogin:n.reviewerLogin,states:n.states,pageSize:n.pageSize},e),failureScope:i=>({providerId:"bitbucketServer",repositoryId:ae(i)}),completeness:i=>i.body.isLastPage?"complete":"partial",concurrency:sn}),o=[];return t.forEach(({result:i})=>{i.body.values.forEach(a=>{n.authorLogin&&a.author.user.name!==n.authorLogin||o.push(Fe(a))})}),{data:k(o,n.states),metadata:s}}async getPullRequestsForCurrentUser(n,e={}){let t=new URL(`${this.getBaseUrl(e)}/dashboard/pull-requests`);t.searchParams.set("state",vr(n.states)),t.searchParams.set("start",n.page?.toString()||"0");let s=U(n.pageSize,{fallback:qr});t.searchParams.set("limit",s.toString()),n.reviewerLogin&&(t.searchParams.set("role.1","REVIEWER"),t.searchParams.set("username.1",n.reviewerLogin));let o=await this.config.request({url:t.toString(),headers:this.getRequestHeaders(e)}),i=!o.body.isLastPage;return{pageInfo:{hasNextPage:i,nextPage:i?o.body.nextPageStart:null,currentPage:Er(o.body.start,o.body.limit)},data:k(o.body.values.map(Fe),n.states)}}async closePullRequest(n,e={}){let{pullRequest:t}=n;if(t.version===void 0)throw new Error('Bitbucket Server requires "version" for this function.');if(!(await this.config.request({method:"POST",url:`${this.getBaseUrl(e)}/projects/${t.repository.owner.login}/repos/${t.repository.name}/pull-requests/${t.id}/decline`,body:JSON.stringify({version:t.version}),headers:{...this.getRequestHeaders(e),"Content-Type":"application/json"}})).body.title)throw new Error("Could not close pull request")}async mergePullRequest(n,e={}){let{pullRequest:t,mergeStrategyId:s}=n;if(n.mergeStrategy)throw new Error('Bitbucket Server uses "mergeStrategyId" instead of "mergeStrategy".');if(t.version===void 0)throw new Error('Bitbucket Server requires "version" for this function.');if(!(await this.config.request({method:"POST",url:`${this.getBaseUrl(e)}/projects/${t.repository.owner.login}/repos/${t.repository.name}/pull-requests/${t.id}/merge`,body:JSON.stringify({strategyId:s,version:t.version}),headers:{...this.getRequestHeaders(e),"Content-Type":"application/json"}})).body.title)throw new Error("Could not merge pull request")}async getMergeStrategies(n={}){let e=await this.config.request({url:`${this.getBaseUrl(n)}/admin/pull-requests/git`,headers:{...this.getRequestHeaders(n),"Content-Type":"application/json"}});return{data:{defaultStrategy:e.body.mergeConfig.defaultStrategy,strategies:e.body.mergeConfig.strategies}}}async setPullRequestReviewers(n,e={}){let{pullRequest:t,reviewers:s}=n;if(t.version===void 0)throw new Error('Bitbucket Server requires "version" for this function.');let o={reviewers:s.map(a=>{if(a.username)throw new Error('Bitbucket Server reviewer requires "username" for this function.');return{user:{name:a.username}}}),version:t.version};if(!(await this.config.request({method:"PUT",url:`${this.getBaseUrl(e)}/projects/${t.repository.owner.login}/repos/${t.repository.name}/pull-requests/${t.id}`,body:JSON.stringify(o),headers:{...this.getRequestHeaders(e),"Content-Type":"application/json"}})).body.title)throw new Error("Could not set pull request reviewers")}async getAccountsForProject(n,e={}){let t=new URL(`${this.getBaseUrl(e)}/projects/${encodeURI(n.project)}/permissions/users`);t.searchParams.set("start",n.page?.toString()||"0"),t.searchParams.set("limit","50");let s=await this.config.request({url:t.toString(),headers:this.getRequestHeaders(e)}),o=s.body.values.length!==0;return{pageInfo:{hasNextPage:o,nextPage:o?s.body.start+s.body.values.length:null},data:s.body.values.map(i=>Ee(i.user))}}};var Br=require("js-base64");var I=class extends Error{constructor(e,t){let s=t?.map(i=>`'${i.message}'`).join(", "),o=s?`${e}: ${s}`:e;super(o);this.graphQLErrors=t??[]}};var on={AS_CODE_OWNER:[3,0,0],CHECK_RUN:[3,0,0],LATEST_REVIEWS:[3,0,0],VIEWER_CAN_MERGE_AS_ADMIN:[3,5,0],ISSUE_FULL_DATABASE_ID:[3,12,0],PR_FULL_DATABASE_ID:[3,13,0],PR_REVIEW_FULL_DATABASE_ID:[3,13,0],PR_REVIEW_COMMENT_FULL_DATABASE_ID:[3,13,0]},Cr=15,$r=100,Ce={__typename:"User",id:"U_kgDNJ5k",databaseId:10137,name:"Deleted user",login:"ghost",email:"",avatarUrl:"https://avatars.githubusercontent.com/u/10137?v=4",url:"https://github.com/ghost"},x=r=>!!r,z=(r,n)=>{let e=on[n];for(let t=0;t<3;t++){if(r[t]>e[t])return!0;if(r[t]<e[t])return!1}return!0},Qe="https://api.github.com",an=`${Qe}/graphql`,Be=`
3
3
  description
4
4
  dueOn
5
5
  id
@@ -7,7 +7,7 @@ number
7
7
  state
8
8
  title
9
9
  url
10
- `,tn=`
10
+ `,un=`
11
11
  ... on CheckRun {
12
12
  completedAt
13
13
  conclusion
@@ -16,12 +16,12 @@ url
16
16
  permalink
17
17
  startedAt
18
18
  }
19
- `,je=/\/api\/v\d+$/,Me=`
19
+ `,je=/\/api\/v\d+$/,ze=`
20
20
  color
21
21
  description
22
22
  id
23
23
  name
24
- `,Er=r=>{if(r.endsWith("/api/graphql"))throw new Error("The graphql endpoint is being used as the baseUrl. This package uses both GraphQL and REST APIs, and the REST version cannot be assumed. Use the REST endpoint as the baseUrl instead.")},rn=(r,n)=>{let e=n.baseUrl||r.baseUrl;return e?(e=e.replace(/\/$/,""),Er(e),je.test(e)&&(e=e.replace(je,"")),`${e}/api/graphql`):en},z=(r,n)=>{let e=n.baseUrl||r.baseUrl;return e?(e=e.replace(/\/$/,""),Er(e),je.test(e)&&(e=e.replace(je,"")),`${e}/api/v3`):Qe},b=(r,n,e)=>{let t=R(e.token||r.token);return t["X-Github-Next-Global-ID"]="1",t["Content-Type"]="application/json",t.Accept="application/vnd.github.merge-info-preview+json",r.request({url:rn(r,e),method:"POST",headers:t,body:JSON.stringify(n)})},sn={user:!0,"user:email":!0,"read:user":!0},V=r=>r.some(n=>sn[n]),F=(r=!1,n=!1,e)=>`
24
+ `,Dr=r=>{if(r.endsWith("/api/graphql"))throw new Error("The graphql endpoint is being used as the baseUrl. This package uses both GraphQL and REST APIs, and the REST version cannot be assumed. Use the REST endpoint as the baseUrl instead.")},ln=(r,n)=>{let e=n.baseUrl||r.baseUrl;return e?(e=e.replace(/\/$/,""),Dr(e),je.test(e)&&(e=e.replace(je,"")),`${e}/api/graphql`):an},M=(r,n)=>{let e=n.baseUrl||r.baseUrl;return e?(e=e.replace(/\/$/,""),Dr(e),je.test(e)&&(e=e.replace(je,"")),`${e}/api/v3`):Qe},b=(r,n,e)=>{let t=R(e.token||r.token);return t["X-Github-Next-Global-ID"]="1",t["Content-Type"]="application/json",t.Accept="application/vnd.github.merge-info-preview+json",r.request({url:ln(r,e),method:"POST",headers:t,body:JSON.stringify(n)})},pn={user:!0,"user:email":!0,"read:user":!0},V=r=>r.some(n=>pn[n]),F=(r=!1,n=!1,e)=>`
25
25
  __typename
26
26
  ${te(e,["graphQLId"],"id")}
27
27
  ${te(e,["id"],"databaseId")}
@@ -30,7 +30,7 @@ ${te(e,["name","username"],"login")}
30
30
  ${n?te(e,["email"],"email"):""}
31
31
  ${te(e,["avatarUrl"],`avatarUrl${r?"(size: $avatarSize)":""}`)}
32
32
  ${te(e,["url"],"url")}
33
- `,nn=(r=!1)=>`
33
+ `,dn=(r=!1)=>`
34
34
  latestReviews(first: 100) {
35
35
  nodes {
36
36
  author {
@@ -38,28 +38,28 @@ latestReviews(first: 100) {
38
38
  ${F(!1,r)}
39
39
  }
40
40
  ... on EnterpriseUserAccount {
41
- ${wt(!1)}
41
+ ${vt(!1)}
42
42
  }
43
43
  }
44
44
  state
45
45
  }
46
46
  }
47
- `,Cr=(r=!1)=>`
47
+ `,Lr=(r=!1)=>`
48
48
  __typename
49
49
  id
50
50
  databaseId
51
51
  login
52
52
  avatarUrl${r?"(size: $avatarSize)":""}
53
53
  url
54
- `,wt=(r=!1)=>`
54
+ `,vt=(r=!1)=>`
55
55
  __typename
56
56
  id
57
57
  login
58
58
  avatarUrl${r?"(size: $avatarSize)":""}
59
59
  url
60
- `,ze=(r,n=!1,e)=>`
60
+ `,Me=(r,n=!1,e)=>`
61
61
  id
62
- ${!e||M(e,"PR_FULL_DATABASE_ID")?"fullDatabaseId":"databaseId"}
62
+ ${!e||z(e,"PR_FULL_DATABASE_ID")?"fullDatabaseId":"databaseId"}
63
63
  number
64
64
  title
65
65
  body
@@ -69,10 +69,10 @@ author {
69
69
  ${F(!1,n)}
70
70
  }
71
71
  ... on Bot {
72
- ${Cr(!1)}
72
+ ${Lr(!1)}
73
73
  }
74
74
  ... on EnterpriseUserAccount {
75
- ${wt(!1)}
75
+ ${vt(!1)}
76
76
  }
77
77
  }
78
78
  commits(last: 1) {
@@ -85,7 +85,7 @@ commits(last: 1) {
85
85
  contexts(first: 100) {
86
86
  totalCount
87
87
  nodes {
88
- ${!e||M(e,"CHECK_RUN")?tn:""}
88
+ ${!e||z(e,"CHECK_RUN")?un:""}
89
89
  ... on StatusContext {
90
90
  context
91
91
  createdAt
@@ -153,7 +153,7 @@ assignees(first: 100) {
153
153
  }
154
154
  reviewRequests(first: 100) {
155
155
  nodes {
156
- ${!e||M(e,"AS_CODE_OWNER")?"asCodeOwner":""}
156
+ ${!e||z(e,"AS_CODE_OWNER")?"asCodeOwner":""}
157
157
  requestedReviewer {
158
158
  ... on User {
159
159
  ${F(!1,n)}
@@ -161,7 +161,7 @@ reviewRequests(first: 100) {
161
161
  }
162
162
  }
163
163
  }
164
- ${!e||M(e,"LATEST_REVIEWS")?nn(n):""}
164
+ ${!e||z(e,"LATEST_REVIEWS")?dn(n):""}
165
165
  additions
166
166
  deletions
167
167
  changedFiles
@@ -172,23 +172,23 @@ milestone {
172
172
  }
173
173
  labels(first: 100) {
174
174
  nodes {
175
- ${Me}
175
+ ${ze}
176
176
  }
177
177
  }
178
- ${!e||M(e,"VIEWER_CAN_MERGE_AS_ADMIN")?"viewerCanMergeAsAdmin":""}
179
- `,on=(r=!1,n)=>`
178
+ ${!e||z(e,"VIEWER_CAN_MERGE_AS_ADMIN")?"viewerCanMergeAsAdmin":""}
179
+ `,cn=(r=!1,n)=>`
180
180
  id
181
- ${!n||M(n,"ISSUE_FULL_DATABASE_ID")?"fullDatabaseId":"databaseId"}
181
+ ${!n||z(n,"ISSUE_FULL_DATABASE_ID")?"fullDatabaseId":"databaseId"}
182
182
  title
183
183
  author {
184
184
  ... on User {
185
185
  ${F(!1,r)}
186
186
  }
187
187
  ... on Bot {
188
- ${Cr(!1)}
188
+ ${Lr(!1)}
189
189
  }
190
190
  ... on EnterpriseUserAccount {
191
- ${wt(!1)}
191
+ ${vt(!1)}
192
192
  }
193
193
  }
194
194
  closedAt
@@ -221,10 +221,10 @@ milestone {
221
221
  }
222
222
  labels(first: 100) {
223
223
  nodes {
224
- ${Me}
224
+ ${ze}
225
225
  }
226
226
  }
227
- `,an={"-linked":"-linked",archived:"archived",assignee:"assignee",author:"author",base:"base",closed:"closed",commenter:"commenter",comments:"comments",created:"created",draft:"draft",head:"head",label:"label",language:"language",linked:"linked",in:"in",interactions:"interactions",involves:"involves",is:"is",mentions:"mentions",merged:"merged",milestone:"milestone",no:"no",org:"org",project:"project",reactions:"reactions",repo:"repo",review:"review","reviewed-by":"reviewed-by","review-requested":"review-requested",state:"state",status:"status",team:"team","team-review-requested":"team-review-requested",type:"type",updated:"updated",user:"user","user-review-requested":"user-review-requested"},un=new RegExp('(([^\\s]+:)?\\"(?:[^\\"\\\\]|\\\\.)*\\"?)|([^\\"\\s]+)',"g"),St=r=>{let n=[];return(r.match(un)??[]).forEach(t=>{if(t.includes(":")&&t!="is:closed"){let s=t.split(":")[0];an[s]&&n.push(t)}}),n},qt="is:open",$r=r=>{if(!r||r.length===0)return qt;let n=new Set(r),e=n.has("OPEN"),t=n.has("CLOSED"),s=n.has("MERGED");return e&&(t||s)?"":e?"is:open":t&&s?"is:closed":s?"is:merged":"is:closed is:unmerged"},Dr=r=>{if(!r||r.length===0)return qt;let n=new Set(r),e=n.has("OPEN"),t=n.has("CLOSED");return e&&t?"":t?"is:closed":"is:open"},vt=(r,n,e,t)=>{let s=r==="issue",o=t.stateQualifier??qt;return{query:`
227
+ `,mn={"-linked":"-linked",archived:"archived",assignee:"assignee",author:"author",base:"base",closed:"closed",commenter:"commenter",comments:"comments",created:"created",draft:"draft",head:"head",label:"label",language:"language",linked:"linked",in:"in",interactions:"interactions",involves:"involves",is:"is",mentions:"mentions",merged:"merged",milestone:"milestone",no:"no",org:"org",project:"project",reactions:"reactions",repo:"repo",review:"review","reviewed-by":"reviewed-by","review-requested":"review-requested",state:"state",status:"status",team:"team","team-review-requested":"team-review-requested",type:"type",updated:"updated",user:"user","user-review-requested":"user-review-requested"},gn=new RegExp('(([^\\s]+:)?\\"(?:[^\\"\\\\]|\\\\.)*\\"?)|([^\\"\\s]+)',"g"),Et=r=>{let n=[];return(r.match(gn)??[]).forEach(t=>{if(t.includes(":")&&t!="is:closed"){let s=t.split(":")[0];mn[s]&&n.push(t)}}),n},Ct="is:open",Ur=r=>{if(!r||r.length===0)return Ct;let n=new Set(r),e=n.has("OPEN"),t=n.has("CLOSED"),s=n.has("MERGED");return e&&(t||s)?"":e?"is:open":t&&s?"is:closed":s?"is:merged":"is:closed is:unmerged"},Ar=r=>{if(!r||r.length===0)return Ct;let n=new Set(r),e=n.has("OPEN"),t=n.has("CLOSED");return e&&t?"":t?"is:closed":"is:open"},$t=(r,n,e,t)=>{let s=r==="issue",o=t.stateQualifier??Ct;return{query:`
228
228
  query SearchIssuesOrPullRequests($query: String! $after: String) {
229
229
  search(type:ISSUE query:$query first: ${t.maxPageSize} after:$after) {
230
230
  pageInfo {
@@ -233,18 +233,18 @@ query SearchIssuesOrPullRequests($query: String! $after: String) {
233
233
  }
234
234
  nodes {
235
235
  ... on ${s?"Issue":"PullRequest"} {
236
- ${s?on(t.supportsEmail,t.enterpriseVersion??null):ze(t.supportsDrafts??!1,t.supportsEmail,t.enterpriseVersion??null)}
236
+ ${s?cn(t.supportsEmail,t.enterpriseVersion??null):Me(t.supportsDrafts??!1,t.supportsEmail,t.enterpriseVersion??null)}
237
237
  }
238
238
  }
239
239
  }
240
- }`,variables:{query:`is:${r} ${o} ${t.includeFromArchivedRepos?"":"archived:false"} ${n}`,after:e}}},ln="Field 'isDraft' doesn't exist on type 'PullRequest'",He=(r=[])=>r.some(n=>n?.message===ln),pn=/@@ -(\d+)(?:,\d+ | )\+(\d+)(?:,\d+ | )@@(?:\\n)?/,dn=`
240
+ }`,variables:{query:`is:${r} ${o} ${t.includeFromArchivedRepos?"":"archived:false"} ${n}`,after:e}}},hn="Field 'isDraft' doesn't exist on type 'PullRequest'",He=(r=[])=>r.some(n=>n?.message===hn),fn=/@@ -(\d+)(?:,\d+ | )\+(\d+)(?:,\d+ | )@@(?:\\n)?/,Rn=`
241
241
  \
242
- +`,Lr=(r,n,e,t)=>{let s=pn.exec(r);if(!s||!s[0]||!s[1])return[];let o=parseInt(s[1],10),i=parseInt(s[2],10),a=r.replace(dn,`
242
+ +`,Gr=(r,n,e,t)=>{let s=fn.exec(r);if(!s||!s[0]||!s[1])return[];let o=parseInt(s[1],10),i=parseInt(s[2],10),a=r.replace(Rn,`
243
243
  +`).split(`
244
- `).slice(1),u=o-1,l=i-1,d=a.map(g=>{let m,h;switch(g[0]){case"-":{m="DELETED",u+=1,h=`${g.slice(1)}
244
+ `).slice(1),u=o-1,l=i-1,p=a.map(g=>{let m,h;switch(g[0]){case"-":{m="DELETED",u+=1,h=`${g.slice(1)}
245
245
  `;break}case"+":{m="ADDED",l+=1,h=`${g.slice(1)}
246
246
  `;break}default:m="UNMODIFIED",l+=1,u+=1,h=`${g}
247
- `}return{line:h,oldLineNumber:m!=="ADDED"?u:null,newLineNumber:m!=="DELETED"?l:null,type:m}}),p=e,c=n;if(p!==null&&c!==null&&t!==null&&p<c){let g=0,m=d.length,h=t==="LEFT"?"oldLineNumber":"newLineNumber";for(let y=0;y<d.length;y++){let P=d[y][h];P===p?g=y:P===c&&(m=y)}d=d.slice(g,m+1)}return d},Ar=r=>{let n=r.author;return n||(n=Ce),{author:{id:"databaseId"in n?n.databaseId.toString():n.id,graphQLId:n.id,name:("name"in n?n.name:n.login)??n.login,username:n.login,email:("email"in n?n.email:null)??null,avatarUrl:n.avatarUrl,url:n.url},body:r.body,createdAt:r.publishedAt?new Date(r.publishedAt):null,graphQLId:r.id,id:r.fullDatabaseId??r.databaseId?.toString()??r.id,url:r.url}};var Ur=`mutation DeleteIssueComment(
247
+ `}return{line:h,oldLineNumber:m!=="ADDED"?u:null,newLineNumber:m!=="DELETED"?l:null,type:m}}),d=e,c=n;if(d!==null&&c!==null&&t!==null&&d<c){let g=0,m=p.length,h=t==="LEFT"?"oldLineNumber":"newLineNumber";for(let y=0;y<p.length;y++){let P=p[y][h];P===d?g=y:P===c&&(m=y)}p=p.slice(g,m+1)}return p},Tr=r=>{let n=r.author;return n||(n=Ce),{author:{id:"databaseId"in n?n.databaseId.toString():n.id,graphQLId:n.id,name:("name"in n?n.name:n.login)??n.login,username:n.login,email:("email"in n?n.email:null)??null,avatarUrl:n.avatarUrl,url:n.url},body:r.body,createdAt:r.publishedAt?new Date(r.publishedAt):null,graphQLId:r.id,id:r.fullDatabaseId??r.databaseId?.toString()??r.id,url:r.url}};var Or=`mutation DeleteIssueComment(
248
248
  $issueCommentId: ID!
249
249
  ) {
250
250
  deleteIssueComment(input: {
@@ -252,7 +252,7 @@ query SearchIssuesOrPullRequests($query: String! $after: String) {
252
252
  }) {
253
253
  clientMutationId
254
254
  }
255
- }`,Gr=`mutation DeletePullRequestReviewComment(
255
+ }`,_r=`mutation DeletePullRequestReviewComment(
256
256
  $pullRequestReviewCommentId: ID!
257
257
  ) {
258
258
  deletePullRequestReviewComment(input: {
@@ -262,7 +262,7 @@ query SearchIssuesOrPullRequests($query: String! $after: String) {
262
262
  id
263
263
  }
264
264
  }
265
- }`,Tr=`mutation UpdateIssueComment(
265
+ }`,xr=`mutation UpdateIssueComment(
266
266
  $issueCommentId: ID!,
267
267
  $body: String!
268
268
  ) {
@@ -275,7 +275,7 @@ query SearchIssuesOrPullRequests($query: String! $after: String) {
275
275
  body
276
276
  }
277
277
  }
278
- }`,Or=`mutation ResolveReviewThread(
278
+ }`,kr=`mutation ResolveReviewThread(
279
279
  $pullRequestReviewThreadId: ID!
280
280
  ) {
281
281
  resolveReviewThread(input: {
@@ -286,7 +286,7 @@ query SearchIssuesOrPullRequests($query: String! $after: String) {
286
286
  isResolved
287
287
  }
288
288
  }
289
- }`,_r=`mutation UnresolveReviewThread(
289
+ }`,Nr=`mutation UnresolveReviewThread(
290
290
  $pullRequestReviewThreadId: ID!
291
291
  ) {
292
292
  unresolveReviewThread(input: {
@@ -297,7 +297,7 @@ query SearchIssuesOrPullRequests($query: String! $after: String) {
297
297
  isResolved
298
298
  }
299
299
  }
300
- }`,xr=`mutation UpdatePullRequestReviewComment(
300
+ }`,Fr=`mutation UpdatePullRequestReviewComment(
301
301
  $pullRequestReviewCommentId: ID!,
302
302
  $body: String!
303
303
  ) {
@@ -310,7 +310,7 @@ query SearchIssuesOrPullRequests($query: String! $after: String) {
310
310
  body
311
311
  }
312
312
  }
313
- }`;var kr=r=>`
313
+ }`;var jr=r=>`
314
314
  query GetPullRequestComments(
315
315
  $namespace: String!
316
316
  $name: String!
@@ -356,7 +356,7 @@ query GetPullRequestComments(
356
356
  }
357
357
  }
358
358
  }
359
- `;var Et=`
359
+ `;var Dt=`
360
360
  id
361
361
  databaseId
362
362
  owner {
@@ -369,7 +369,7 @@ defaultBranchRef {
369
369
  name
370
370
  }
371
371
  viewerPermission
372
- `,cn={APPROVED:"APPROVED",CHANGES_REQUESTED:"CHANGES_REQUESTED",COMMENTED:"COMMENTED",REVIEW_REQUESTED:"REVIEW_REQUESTED"},mn={MERGEABLE:"MERGEABLE",CONFLICTING:"CONFLICTS",UNKNOWN:"UNKNOWN"},gn={BEHIND:"BEHIND",BLOCKED:"BLOCKED",UNKNOWN:"UNKNOWN_AND_BLOCKED",UNSTABLE:"UNSTABLE",CLEAN:null,DIRTY:null,DRAFT:null,HAS_HOOKS:null},hn={OPEN:"OPEN",CLOSED:"CLOSED"},fn=["ADMIN","MAINTAIN","TRIAGE","WRITE"],Dt=r=>({color:`#${r.color}`,description:r.description,graphQLId:r.id,id:null,name:r.name}),Rn=r=>({canCreateWebhook:r==="ADMIN",canPush:r==="ADMIN"||r==="MAINTAIN"||r==="WRITE",isAdmin:r==="ADMIN"}),Ct=r=>({id:r.databaseId.toString(),graphQLId:r.id,namespace:r.owner.login,name:r.name,webUrl:r.url,httpsUrl:r.url.endsWith(".git")?r.url:`${r.url}.git`,sshUrl:r.sshUrl,defaultBranch:r.defaultBranchRef,permissions:Rn(r.viewerPermission)}),In=r=>({canCreateWebhook:r.admin,canPush:r.admin||r.maintain||r.push,isAdmin:r.admin}),Nr=r=>({id:r.id.toString(),graphQLId:r.node_id,namespace:r.owner.login,name:r.name,webUrl:r.html_url,httpsUrl:r.clone_url,sshUrl:r.ssh_url,defaultBranch:{name:r.default_branch},permissions:In(r.permissions)}),bn=r=>({path:r.path,isDirectory:r.type==="tree"}),yn={OPEN:"OPEN",CLOSED:"CLOSED",MERGED:"MERGED"},Pn={id:!0,graphQLId:!0,name:!0,username:!0,email:!0,avatarUrl:!0,url:!0},Q=(r,n=Pn)=>{let e={};return n.id&&(e.id="databaseId"in r?r.databaseId.toString():r.id),n.graphQLId&&(e.graphQLId=r.id),n.name&&(e.name=r.name??r.login),n.username&&(e.username=r.login),n.email&&(e.email=r.email??null),n.avatarUrl&&(e.avatarUrl=r.avatarUrl),n.url&&(e.url=r.url),e},wn=(r,n)=>{let e={IN_PROGRESS:"RUNNING",PENDING:"PENDING",QUEUED:"PENDING",REQUESTED:"PENDING",WAITING:"PENDING"};return r!=="COMPLETED"?e[r]:{ACTION_REQUIRED:"ACTION_REQUIRED",CANCELLED:"CANCELLED",FAILURE:"FAILED",NEUTRAL:null,SKIPPED:"SKIPPED",STALE:"FAILED",STARTUP_FAILURE:"FAILED",SUCCESS:"SUCCESS",TIMED_OUT:"ERROR"}[n]},Sn=r=>({ERROR:"ERROR",EXPECTED:"PENDING",FAILURE:"FAILED",PENDING:"PENDING",SUCCESS:"SUCCESS"})[r],$t=r=>{let n=null;r.author?n=r.author:n=Ce;let e=(r.reviewRequests?.nodes||[]).filter(x).filter(i=>!i.asCodeOwner),t=r.headRepository?.url;t&&!t.endsWith(".git")&&(t=`${t}.git`);let s=r.repository?.url;s&&!s.endsWith(".git")&&(s=`${s}.git`);let o=e.filter(i=>i.requestedReviewer&&"__typename"in i.requestedReviewer).map(i=>({reviewer:Q(i.requestedReviewer),state:"REVIEW_REQUESTED"})).concat((r.latestReviews?.nodes||[]).filter(x).map(i=>{let a=Ce;return i.author&&i.author.__typename&&(a=i.author),{reviewer:Q(a),state:cn[i.state]}}));return{id:r.fullDatabaseId!==void 0?r.fullDatabaseId:r.databaseId.toString(),graphQLId:r.id,title:r.title,description:r.body,number:r.number,state:yn[r.state],commentCount:r.comments.totalCount,upvoteCount:r.reactions.totalCount,author:n&&n.__typename?Q(n):null,createdDate:new Date(r.createdAt),isDraft:r.isDraft,repository:{id:r.repository.databaseId.toString(),graphQLId:r.repository.id,name:r.repository.name,owner:{login:r.repository.owner.login},remoteInfo:{cloneUrlHTTPS:s,cloneUrlSSH:r.repository.sshUrl}},isCrossRepository:r.headRepository!=null&&r.headRepository.databaseId!==r.repository.databaseId,headRepository:r.headRepository?{id:r.headRepository.databaseId.toString(),graphQLId:r.headRepository.id,name:r.headRepository.name,owner:{login:r.headRepository.owner.login},remoteInfo:{cloneUrlHTTPS:t,cloneUrlSSH:r.headRepository.sshUrl},isFork:r.headRepository.isFork}:null,headCommit:{buildStatuses:r.commits.nodes?.filter(x)[0]?.commit.statusCheckRollup?.contexts.nodes?.filter(x).map(i=>"context"in i?{completedAt:null,description:i.description,name:i.context,state:Sn(i.state),startedAt:new Date(i.createdAt),stage:null,url:i.targetUrl}:{completedAt:i.completedAt?new Date(i.completedAt):null,description:null,name:i.name,state:wn(i.status,i.conclusion),startedAt:i.startedAt?new Date(i.startedAt):null,stage:null,url:i.permalink})??[]},headRef:r.headRef?{name:r.headRef.name,oid:r.headRef.target?.oid??null}:null,baseRef:r.baseRef?{name:r.baseRef.name,oid:r.baseRef.target?.oid??null}:null,url:r.url,updatedDate:new Date(r.updatedAt),closedDate:r.closedAt?new Date(r.closedAt):null,mergedDate:r.mergedAt?new Date(r.mergedAt):null,assignees:r.assignees.nodes?r.assignees.nodes.filter(x).map(i=>Q(i)):null,reviews:o,reviewDecision:B(o),additions:r.additions,deletions:r.deletions,fileCount:r.changedFiles,commitCount:r.commits.totalCount,mergeableState:gn[r.mergeStateStatus]??mn[r.mergeable],milestone:r.milestone?Lt(r.milestone):null,labels:r.labels?.nodes?.filter(x).map(Dt)??[],permissions:{canMerge:fn.includes(r.repository.viewerPermission),canMergeAndBypassProtections:r.viewerCanMergeAsAdmin??!1}}},qn=r=>{let{id:n,comments:e,isOutdated:t,isResolved:s,line:o,startLine:i,diffSide:a,originalLine:u,originalStartLine:l,startDiffSide:d}=r,p=e.nodes?.[0];if(!p)return null;let{author:c,body:g,databaseId:m,fullDatabaseId:h,id:y,path:f,publishedAt:P,url:q}=p,D=o??u,$=i??l,w=a??d;return{author:c?{avatarUrl:c.avatarUrl,email:null,name:c.login}:null,body:g,createdAt:P?new Date(P):null,diffLines:Lr(p.diffHunk,D,$,w),id:h??m.toString(),isOutdated:t,isResolved:s,graphQLId:y,threadId:n,filename:f,replies:e.nodes?.filter(x).slice(1).map(vn)??[],url:q,line:D,startLine:$,side:w}},vn=r=>({author:r.author?{avatarUrl:r.author.avatarUrl,email:null,name:r.author.login}:null,body:r.body,createdAt:r.publishedAt?new Date(r.publishedAt):null,graphQLId:r.id,id:r.fullDatabaseId??r.databaseId.toString(),url:r.url}),En=r=>{let n=null;return r.author?n=r.author:n=Ce,{id:r.fullDatabaseId!==void 0?r.fullDatabaseId:r.databaseId.toString(),graphQLId:r.id,number:r.number,title:r.title,author:n&&n.__typename?Q(n):null,commentCount:r.comments.totalCount,closedDate:r.closedAt?new Date(r.closedAt):null,createdDate:new Date(r.createdAt),description:null,state:{name:hn[r.state],color:null},type:null,repository:{id:r.repository.databaseId.toString(),graphQLId:r.repository.id,name:r.repository.name,owner:{login:r.repository.owner.login}},url:r.url,updatedDate:new Date(r.updatedAt),assignees:r.assignees.nodes?.filter(x).map(e=>Q(e))??[],upvoteCount:r.reactions.totalCount,milestone:r.milestone?Lt(r.milestone):null,labels:r.labels?.nodes?.filter(x).map(Dt)??[]}},Lt=r=>({id:r.number.toString(),graphQLId:r.id.toString(),number:r.number,title:r.title,description:r.description,isOpen:r.state=="OPEN",url:r.url,startDate:null,dueDate:r.dueOn?new Date(r.dueOn):null}),Ie=class extends N{constructor(){super(...arguments);this._scopesCache={};this._enterpriseVersionsCache={}}async getScopes(e){let t=e.token||this.config.token;if(!t)return[];let s=this._scopesCache[t];if(!s){let i=(await b(this.config,{query:"query { rateLimit(dryRun: true) { __typename } }"},e)).headers["x-oauth-scopes"];s=i?i.split(", "):[],this._scopesCache[t]=s}return s}async getEnterpriseVersion(e){let t=e.baseUrl||this.config.baseUrl;if(!t)return null;let s=this._enterpriseVersionsCache[t];if(!s){let o=await this.config.request({url:`${z(this.config,e)}/meta`,headers:R(e.token||this.config.token)});if(!o.body.installed_version)return null;s=o.body.installed_version.split(".").slice(0,3).map(i=>parseInt(i,10)),this._enterpriseVersionsCache[t]=s}return s}getEnterpriseAvatarUrlIfNeeded(e,t,s){let o=s.baseUrl||this.config.baseUrl;return!o||o.startsWith(Qe)?e:t?`https://avatars.githubusercontent.com/u/e?email=${encodeURIComponent(t)}`:""}async getCurrentUser(e={},t={}){if(e.fields&&!e.fields.length)throw new Error('"fields" must contain at least one field or be omitted');let s=nr(e.fields),o=await this.getScopes(t),i=await b(this.config,{query:`
372
+ `,In={APPROVED:"APPROVED",CHANGES_REQUESTED:"CHANGES_REQUESTED",COMMENTED:"COMMENTED",REVIEW_REQUESTED:"REVIEW_REQUESTED"},bn={MERGEABLE:"MERGEABLE",CONFLICTING:"CONFLICTS",UNKNOWN:"UNKNOWN"},yn={BEHIND:"BEHIND",BLOCKED:"BLOCKED",UNKNOWN:"UNKNOWN_AND_BLOCKED",UNSTABLE:"UNSTABLE",CLEAN:null,DIRTY:null,DRAFT:null,HAS_HOOKS:null},Pn={OPEN:"OPEN",CLOSED:"CLOSED"},wn=["ADMIN","MAINTAIN","TRIAGE","WRITE"],At=r=>({color:`#${r.color}`,description:r.description,graphQLId:r.id,id:null,name:r.name}),Sn=r=>({canCreateWebhook:r==="ADMIN",canPush:r==="ADMIN"||r==="MAINTAIN"||r==="WRITE",isAdmin:r==="ADMIN"}),Lt=r=>({id:r.databaseId.toString(),graphQLId:r.id,namespace:r.owner.login,name:r.name,webUrl:r.url,httpsUrl:r.url.endsWith(".git")?r.url:`${r.url}.git`,sshUrl:r.sshUrl,defaultBranch:r.defaultBranchRef,permissions:Sn(r.viewerPermission)}),qn=r=>({canCreateWebhook:r.admin,canPush:r.admin||r.maintain||r.push,isAdmin:r.admin}),Qr=r=>({id:r.id.toString(),graphQLId:r.node_id,namespace:r.owner.login,name:r.name,webUrl:r.html_url,httpsUrl:r.clone_url,sshUrl:r.ssh_url,defaultBranch:{name:r.default_branch},permissions:qn(r.permissions)}),vn=r=>({path:r.path,isDirectory:r.type==="tree"}),En={OPEN:"OPEN",CLOSED:"CLOSED",MERGED:"MERGED"},Cn={id:!0,graphQLId:!0,name:!0,username:!0,email:!0,avatarUrl:!0,url:!0},Q=(r,n=Cn)=>{let e={};return n.id&&(e.id="databaseId"in r?r.databaseId.toString():r.id),n.graphQLId&&(e.graphQLId=r.id),n.name&&(e.name=r.name??r.login),n.username&&(e.username=r.login),n.email&&(e.email=r.email??null),n.avatarUrl&&(e.avatarUrl=r.avatarUrl),n.url&&(e.url=r.url),e},$n=(r,n)=>{let e={IN_PROGRESS:"RUNNING",PENDING:"PENDING",QUEUED:"PENDING",REQUESTED:"PENDING",WAITING:"PENDING"};return r!=="COMPLETED"?e[r]:{ACTION_REQUIRED:"ACTION_REQUIRED",CANCELLED:"CANCELLED",FAILURE:"FAILED",NEUTRAL:null,SKIPPED:"SKIPPED",STALE:"FAILED",STARTUP_FAILURE:"FAILED",SUCCESS:"SUCCESS",TIMED_OUT:"ERROR"}[n]},Dn=r=>({ERROR:"ERROR",EXPECTED:"PENDING",FAILURE:"FAILED",PENDING:"PENDING",SUCCESS:"SUCCESS"})[r],Ut=r=>{let n=null;r.author?n=r.author:n=Ce;let e=(r.reviewRequests?.nodes||[]).filter(x).filter(i=>!i.asCodeOwner),t=r.headRepository?.url;t&&!t.endsWith(".git")&&(t=`${t}.git`);let s=r.repository?.url;s&&!s.endsWith(".git")&&(s=`${s}.git`);let o=e.filter(i=>i.requestedReviewer&&"__typename"in i.requestedReviewer).map(i=>({reviewer:Q(i.requestedReviewer),state:"REVIEW_REQUESTED"})).concat((r.latestReviews?.nodes||[]).filter(x).map(i=>{let a=Ce;return i.author&&i.author.__typename&&(a=i.author),{reviewer:Q(a),state:In[i.state]}}));return{id:r.fullDatabaseId!==void 0?r.fullDatabaseId:r.databaseId.toString(),graphQLId:r.id,title:r.title,description:r.body,number:r.number,state:En[r.state],commentCount:r.comments.totalCount,upvoteCount:r.reactions.totalCount,author:n&&n.__typename?Q(n):null,createdDate:new Date(r.createdAt),isDraft:r.isDraft,repository:{id:r.repository.databaseId.toString(),graphQLId:r.repository.id,name:r.repository.name,owner:{login:r.repository.owner.login},remoteInfo:{cloneUrlHTTPS:s,cloneUrlSSH:r.repository.sshUrl}},isCrossRepository:r.headRepository!=null&&r.headRepository.databaseId!==r.repository.databaseId,headRepository:r.headRepository?{id:r.headRepository.databaseId.toString(),graphQLId:r.headRepository.id,name:r.headRepository.name,owner:{login:r.headRepository.owner.login},remoteInfo:{cloneUrlHTTPS:t,cloneUrlSSH:r.headRepository.sshUrl},isFork:r.headRepository.isFork}:null,headCommit:{buildStatuses:r.commits.nodes?.filter(x)[0]?.commit.statusCheckRollup?.contexts.nodes?.filter(x).map(i=>"context"in i?{completedAt:null,description:i.description,name:i.context,state:Dn(i.state),startedAt:new Date(i.createdAt),stage:null,url:i.targetUrl}:{completedAt:i.completedAt?new Date(i.completedAt):null,description:null,name:i.name,state:$n(i.status,i.conclusion),startedAt:i.startedAt?new Date(i.startedAt):null,stage:null,url:i.permalink})??[]},headRef:r.headRef?{name:r.headRef.name,oid:r.headRef.target?.oid??null}:null,baseRef:r.baseRef?{name:r.baseRef.name,oid:r.baseRef.target?.oid??null}:null,url:r.url,updatedDate:new Date(r.updatedAt),closedDate:r.closedAt?new Date(r.closedAt):null,mergedDate:r.mergedAt?new Date(r.mergedAt):null,assignees:r.assignees.nodes?r.assignees.nodes.filter(x).map(i=>Q(i)):null,reviews:o,reviewDecision:B(o),additions:r.additions,deletions:r.deletions,fileCount:r.changedFiles,commitCount:r.commits.totalCount,mergeableState:yn[r.mergeStateStatus]??bn[r.mergeable],milestone:r.milestone?Gt(r.milestone):null,labels:r.labels?.nodes?.filter(x).map(At)??[],permissions:{canMerge:wn.includes(r.repository.viewerPermission),canMergeAndBypassProtections:r.viewerCanMergeAsAdmin??!1}}},Ln=r=>{let{id:n,comments:e,isOutdated:t,isResolved:s,line:o,startLine:i,diffSide:a,originalLine:u,originalStartLine:l,startDiffSide:p}=r,d=e.nodes?.[0];if(!d)return null;let{author:c,body:g,databaseId:m,fullDatabaseId:h,id:y,path:f,publishedAt:P,url:q}=d,L=o??u,D=i??l,w=a??p;return{author:c?{avatarUrl:c.avatarUrl,email:null,name:c.login}:null,body:g,createdAt:P?new Date(P):null,diffLines:Gr(d.diffHunk,L,D,w),id:h??m.toString(),isOutdated:t,isResolved:s,graphQLId:y,threadId:n,filename:f,replies:e.nodes?.filter(x).slice(1).map(Un)??[],url:q,line:L,startLine:D,side:w}},Un=r=>({author:r.author?{avatarUrl:r.author.avatarUrl,email:null,name:r.author.login}:null,body:r.body,createdAt:r.publishedAt?new Date(r.publishedAt):null,graphQLId:r.id,id:r.fullDatabaseId??r.databaseId.toString(),url:r.url}),An=r=>{let n=null;return r.author?n=r.author:n=Ce,{id:r.fullDatabaseId!==void 0?r.fullDatabaseId:r.databaseId.toString(),graphQLId:r.id,number:r.number,title:r.title,author:n&&n.__typename?Q(n):null,commentCount:r.comments.totalCount,closedDate:r.closedAt?new Date(r.closedAt):null,createdDate:new Date(r.createdAt),description:null,state:{name:Pn[r.state],color:null},type:null,repository:{id:r.repository.databaseId.toString(),graphQLId:r.repository.id,name:r.repository.name,owner:{login:r.repository.owner.login}},url:r.url,updatedDate:new Date(r.updatedAt),assignees:r.assignees.nodes?.filter(x).map(e=>Q(e))??[],upvoteCount:r.reactions.totalCount,milestone:r.milestone?Gt(r.milestone):null,labels:r.labels?.nodes?.filter(x).map(At)??[]}},Gt=r=>({id:r.number.toString(),graphQLId:r.id.toString(),number:r.number,title:r.title,description:r.description,isOpen:r.state=="OPEN",url:r.url,startDate:null,dueDate:r.dueOn?new Date(r.dueOn):null}),be=class extends N{constructor(){super(...arguments);this._scopesCache={};this._enterpriseVersionsCache={}}async getScopes(e){let t=e.token||this.config.token;if(!t)return[];let s=this._scopesCache[t];if(!s){let i=(await b(this.config,{query:"query { rateLimit(dryRun: true) { __typename } }"},e)).headers["x-oauth-scopes"];s=i?i.split(", "):[],this._scopesCache[t]=s}return s}async getEnterpriseVersion(e){let t=e.baseUrl||this.config.baseUrl;if(!t)return null;let s=this._enterpriseVersionsCache[t];if(!s){let o=await this.config.request({url:`${M(this.config,e)}/meta`,headers:R(e.token||this.config.token)});if(!o.body.installed_version)return null;s=o.body.installed_version.split(".").slice(0,3).map(i=>parseInt(i,10)),this._enterpriseVersionsCache[t]=s}return s}getEnterpriseAvatarUrlIfNeeded(e,t,s){let o=s.baseUrl||this.config.baseUrl;return!o||o.startsWith(Qe)?e:t?`https://avatars.githubusercontent.com/u/e?email=${encodeURIComponent(t)}`:""}async getCurrentUser(e={},t={}){if(e.fields&&!e.fields.length)throw new Error('"fields" must contain at least one field or be omitted');let s=ar(e.fields),o=await this.getScopes(t),i=await b(this.config,{query:`
373
373
  query getCurrentUser {
374
374
  viewer {
375
375
  ${F(!1,V(o),s)}
@@ -389,7 +389,7 @@ query getAccountsForRepo($owner: String!, $name: String! $cursor: String, $first
389
389
  }
390
390
  }
391
391
  }
392
- `,variables:{owner:o,name:i,cursor:a,first:L}},t);if(!u.body.data)throw new I("Could not fetch accounts for repo",u.body.errors);return{pageInfo:u.body.data.repository?.assignableUsers?.pageInfo??{endCursor:null,hasNextPage:!1},data:u.body.data.repository?.assignableUsers?.nodes?.map(l=>Q(l))??[]}}async getUserForCommit(e,t={}){let s=await b(this.config,{query:`
392
+ `,variables:{owner:o,name:i,cursor:a,first:C}},t);if(!u.body.data)throw new I("Could not fetch accounts for repo",u.body.errors);return{pageInfo:u.body.data.repository?.assignableUsers?.pageInfo??{endCursor:null,hasNextPage:!1},data:u.body.data.repository?.assignableUsers?.nodes?.map(l=>Q(l))??[]}}async getUserForCommit(e,t={}){let s=await b(this.config,{query:`
393
393
  query getUserForCommit(
394
394
  $owner: String!
395
395
  $name: String!
@@ -435,7 +435,7 @@ mutation createCommitOnBranch(
435
435
  }
436
436
  }
437
437
  }
438
- `,variables:{branchName:u.name,expectedHeadOid:u.oid,fileChanges:{additions:Object.entries(i).map(([d,p])=>({contents:Fr.Base64.encode(p),path:d})),deletions:o.map(d=>({path:d}))},message:{body:s.description,headline:s.summary},repositoryNameWithOwner:`${a.namespace}/${a.name}`}},t);if(!l.body.data)throw new I("Could not create commit",l.body.errors);return{data:{name:l.body.data.createCommitOnBranch.ref.name,commit:{authoredDate:new Date(l.body.data.createCommitOnBranch.commit.authoredDate),committedDate:new Date(l.body.data.createCommitOnBranch.commit.committedDate),oid:l.body.data.createCommitOnBranch.commit.oid}}}}async getAccountForEmail(e,t={}){let s=await this.getScopes(t),o=await b(this.config,{query:`
438
+ `,variables:{branchName:u.name,expectedHeadOid:u.oid,fileChanges:{additions:Object.entries(i).map(([p,d])=>({contents:Br.Base64.encode(d),path:p})),deletions:o.map(p=>({path:p}))},message:{body:s.description,headline:s.summary},repositoryNameWithOwner:`${a.namespace}/${a.name}`}},t);if(!l.body.data)throw new I("Could not create commit",l.body.errors);return{data:{name:l.body.data.createCommitOnBranch.ref.name,commit:{authoredDate:new Date(l.body.data.createCommitOnBranch.commit.authoredDate),committedDate:new Date(l.body.data.createCommitOnBranch.commit.committedDate),oid:l.body.data.createCommitOnBranch.commit.oid}}}}async getAccountForEmail(e,t={}){let s=await this.getScopes(t),o=await b(this.config,{query:`
439
439
  query getAccountForEmail($query: String! $avatarSize: Int) {
440
440
  search(query: $query, type: USER, first: 1) {
441
441
  nodes {
@@ -470,7 +470,7 @@ query getOrgsForCurrentUser($cursor: String, $first: Int!) {
470
470
  }
471
471
  }
472
472
  }
473
- `,variables:{cursor:e.cursor,first:L}},t);if(!s.body.data)throw new I("Could not fetch orgs for current user",s.body.errors);let o=s.body.data.viewer.organizations.nodes||[];return{pageInfo:s.body.data.viewer.organizations.pageInfo,data:o.map(i=>({id:i.databaseId.toString(),graphQLId:i.id,username:i.login,name:i.name||null,email:i.email||null,avatarUrl:i.avatarUrl}))}}async getOrgMembers(e,t={}){let s=await b(this.config,{query:`
473
+ `,variables:{cursor:e.cursor,first:C}},t);if(!s.body.data)throw new I("Could not fetch orgs for current user",s.body.errors);let o=s.body.data.viewer.organizations.nodes||[];return{pageInfo:s.body.data.viewer.organizations.pageInfo,data:o.map(i=>({id:i.databaseId.toString(),graphQLId:i.id,username:i.login,name:i.name||null,email:i.email||null,avatarUrl:i.avatarUrl}))}}async getOrgMembers(e,t={}){let s=await b(this.config,{query:`
474
474
  query getOrgMember($cursor: String, $first: Int!, $login: String!) {
475
475
  viewer {
476
476
  organization(login: $login) {
@@ -486,22 +486,22 @@ query getOrgMember($cursor: String, $first: Int!, $login: String!) {
486
486
  }
487
487
  }
488
488
  }
489
- `,variables:{cursor:e.cursor,first:L,login:e.org}},t);if(!s.body.data?.viewer.organization?.membersWithRole&&s.body.errors?.length)throw new I("Could not read the members of the organization",s.body.errors);let o=s.body.data?.viewer.organization?.membersWithRole.nodes||[];return{pageInfo:{hasNextPage:s.body.data?.viewer.organization?.membersWithRole.pageInfo.hasNextPage??!1,endCursor:s.body.data?.viewer.organization?.membersWithRole.pageInfo.endCursor??null},data:o.map(i=>Q({...i,avatarUrl:this.getEnterpriseAvatarUrlIfNeeded(i.avatarUrl,i.email,t)}))}}async getRepo(e,t={}){let s=await b(this.config,{query:`
489
+ `,variables:{cursor:e.cursor,first:C,login:e.org}},t);if(!s.body.data?.viewer.organization?.membersWithRole&&s.body.errors?.length)throw new I("Could not read the members of the organization",s.body.errors);let o=s.body.data?.viewer.organization?.membersWithRole.nodes||[];return{pageInfo:{hasNextPage:s.body.data?.viewer.organization?.membersWithRole.pageInfo.hasNextPage??!1,endCursor:s.body.data?.viewer.organization?.membersWithRole.pageInfo.endCursor??null},data:o.map(i=>Q({...i,avatarUrl:this.getEnterpriseAvatarUrlIfNeeded(i.avatarUrl,i.email,t)}))}}async getRepo(e,t={}){let s=await b(this.config,{query:`
490
490
  query getRepo($owner: String!, $name: String!) {
491
491
  repository(owner: $owner, name: $name) {
492
- ${Et}
492
+ ${Dt}
493
493
  }
494
494
  }
495
- `,variables:{owner:e.namespace,name:e.name}},t);if(!s.body.data?.repository)throw new I(`Repository ${e.namespace}/${e.name} not found`,s.body.errors);return{data:Ct(s.body.data.repository)}}async getRepos(e,t={}){let s=e.map(({namespace:u,name:l},d)=>`
496
- getRepo_${d}: repository(owner: "${u}", name: "${l}") {
497
- ${Et}
495
+ `,variables:{owner:e.namespace,name:e.name}},t);if(!s.body.data?.repository)throw new I(`Repository ${e.namespace}/${e.name} not found`,s.body.errors);return{data:Lt(s.body.data.repository)}}async getRepos(e,t={}){let s=e.map(({namespace:u,name:l},p)=>`
496
+ getRepo_${p}: repository(owner: "${u}", name: "${l}") {
497
+ ${Dt}
498
498
  }
499
499
  `).join(`
500
500
  `),o=await b(this.config,{query:`
501
501
  query batchGetRepos {
502
502
  ${s}
503
503
  }
504
- `},t);if(!o.body.data)throw new I("Could not fetch repos",o.body.errors);let i=[],a=[];return e.forEach((u,l)=>{let d=o.body.data[`getRepo_${l}`];d?i.push(Ct(d)):a.push({input:u})}),{data:i,errors:a}}async fetchMultipleRESTPages(e,t,s,o){let i=[];for(let p=0;p<t;p++)i.push(s(e+p));let a=await Promise.all(i),u=[];for(let p of a){if(!p.body)throw new Error(p.statusText||"Unknown error");u=u.concat(p.body.map(c=>o(c)))}let l=a.every(p=>p.body.length===100),d=e+t;return{data:u,pageInfo:{hasNextPage:l,nextPage:l?d:null}}}async getReposForCurrentUser(e,t={}){if(e.simultaneousPagesToFetch&&e.simultaneousPagesToFetch>40)throw new Error("The argument 'simultaneousPagesToFetch' cannot exceed 40 for 'getReposForCurrentUser'");let s=new URLSearchParams;s.append("per_page","100"),e.affiliations&&s.append("affiliation",e.affiliations.join(","));let o=i=>this.config.request({url:`${z(this.config,t)}/user/repos?${s.toString()}&page=${i}`,headers:{...R(t.token||this.config.token),Accept:"application/vnd.github.raw+json","X-Github-Next-Global-ID":1}});return await this.fetchMultipleRESTPages(e.page??1,e.simultaneousPagesToFetch??4,o,Nr)}async getReposForOrg(e,t={}){if(e.simultaneousPagesToFetch&&e.simultaneousPagesToFetch>40)throw new Error("The argument 'simultaneousPagesToFetch' cannot exceed 40 for 'getReposForOrg'");let s=o=>this.config.request({url:`${z(this.config,t)}/orgs/${e.orgName}/repos?per_page=100&page=${o}`,headers:{...R(t.token||this.config.token),Accept:"application/vnd.github.raw+json","X-Github-Next-Global-ID":1}});return await this.fetchMultipleRESTPages(e.page??1,e.simultaneousPagesToFetch??4,s,Nr)}async getReposForUsernames(e,t={}){if(!e.usernames.length)return{pageInfo:{endCursor:null,hasNextPage:!1},data:[]};let s=await b(this.config,{query:`
504
+ `},t);if(!o.body.data)throw new I("Could not fetch repos",o.body.errors);let i=[],a=[];return e.forEach((u,l)=>{let p=o.body.data[`getRepo_${l}`];p?i.push(Lt(p)):a.push({input:u})}),{data:i,errors:a}}async fetchMultipleRESTPages(e,t,s,o){let i=[];for(let d=0;d<t;d++)i.push(s(e+d));let a=await Promise.all(i),u=[];for(let d of a){if(!d.body)throw new Error(d.statusText||"Unknown error");u=u.concat(d.body.map(c=>o(c)))}let l=a.every(d=>d.body.length===100),p=e+t;return{data:u,pageInfo:{hasNextPage:l,nextPage:l?p:null}}}async getReposForCurrentUser(e,t={}){if(e.simultaneousPagesToFetch&&e.simultaneousPagesToFetch>40)throw new Error("The argument 'simultaneousPagesToFetch' cannot exceed 40 for 'getReposForCurrentUser'");let s=new URLSearchParams;s.append("per_page","100"),e.affiliations&&s.append("affiliation",e.affiliations.join(","));let o=i=>this.config.request({url:`${M(this.config,t)}/user/repos?${s.toString()}&page=${i}`,headers:{...R(t.token||this.config.token),Accept:"application/vnd.github.raw+json","X-Github-Next-Global-ID":1}});return await this.fetchMultipleRESTPages(e.page??1,e.simultaneousPagesToFetch??4,o,Qr)}async getReposForOrg(e,t={}){if(e.simultaneousPagesToFetch&&e.simultaneousPagesToFetch>40)throw new Error("The argument 'simultaneousPagesToFetch' cannot exceed 40 for 'getReposForOrg'");let s=o=>this.config.request({url:`${M(this.config,t)}/orgs/${e.orgName}/repos?per_page=100&page=${o}`,headers:{...R(t.token||this.config.token),Accept:"application/vnd.github.raw+json","X-Github-Next-Global-ID":1}});return await this.fetchMultipleRESTPages(e.page??1,e.simultaneousPagesToFetch??4,s,Qr)}async getReposForUsernames(e,t={}){if(!e.usernames.length)return{pageInfo:{endCursor:null,hasNextPage:!1},data:[]};let s=await b(this.config,{query:`
505
505
  query getReposForUsernames($query: String!, $cursor: String, $first: Int!) {
506
506
  search(query: $query, type: REPOSITORY, first: $first, after: $cursor) {
507
507
  pageInfo {
@@ -510,12 +510,12 @@ query getReposForUsernames($query: String!, $cursor: String, $first: Int!) {
510
510
  }
511
511
  nodes {
512
512
  ... on Repository {
513
- ${Et}
513
+ ${Dt}
514
514
  }
515
515
  }
516
516
  }
517
517
  }
518
- `,variables:{query:`fork:true ${e.usernames.map(i=>`user:${i}`).join(" ")}`,cursor:e.cursor,first:L}},t);if(!s.body.data)throw new I("Could not fetch repos for usernames",s.body.errors);let o=s.body.data.search.nodes||[];return{pageInfo:s.body.data.search.pageInfo,data:o.map(Ct)}}async getReposForOwners(e,t={}){return this.getReposForUsernames({usernames:e.owners.filter(s=>s.username).map(s=>s.username),cursor:e.cursor},t)}async getRefs(e,t,s={}){let o=await b(this.config,{query:`
518
+ `,variables:{query:`fork:true ${e.usernames.map(i=>`user:${i}`).join(" ")}`,cursor:e.cursor,first:C}},t);if(!s.body.data)throw new I("Could not fetch repos for usernames",s.body.errors);let o=s.body.data.search.nodes||[];return{pageInfo:s.body.data.search.pageInfo,data:o.map(Lt)}}async getReposForOwners(e,t={}){return this.getReposForUsernames({usernames:e.owners.filter(s=>s.username).map(s=>s.username),cursor:e.cursor},t)}async getRefs(e,t,s={}){let o=await b(this.config,{query:`
519
519
  query getRefs($owner: String!, $name: String!, $refPrefix: String!, $cursor: String, $first: Int!) {
520
520
  repository(owner: $owner, name: $name) {
521
521
  refs(refPrefix: $refPrefix first: $first after: $cursor) {
@@ -536,7 +536,7 @@ query getRefs($owner: String!, $name: String!, $refPrefix: String!, $cursor: Str
536
536
  }
537
537
  }
538
538
  }
539
- `,variables:{owner:t.repo.namespace,name:t.repo.name,refPrefix:e,cursor:t.cursor,first:L}},s),i=o.body.data?.repository;if(!i)throw new I("Ref repository not found.",o.body.errors);let a=i.refs;return a?{pageInfo:a.pageInfo,data:(a.nodes||[]).map(u=>{let l=u.target?.oid?u.target:null;return{name:u.name,commit:l?{oid:l.oid,authoredDate:new Date(l.authoredDate),committedDate:new Date(l.committedDate)}:null}})}:{pageInfo:{endCursor:null,hasNextPage:!1},data:[]}}async getBranches(e,t={}){return this.getRefs("refs/heads/",e,t)}async getTags(e,t={}){return this.getRefs("refs/tags/",e,t)}async getBlame(e,t={}){let s=await b(this.config,{query:`
539
+ `,variables:{owner:t.repo.namespace,name:t.repo.name,refPrefix:e,cursor:t.cursor,first:C}},s),i=o.body.data?.repository;if(!i)throw new I("Ref repository not found.",o.body.errors);let a=i.refs;return a?{pageInfo:a.pageInfo,data:(a.nodes||[]).map(u=>{let l=u.target?.oid?u.target:null;return{name:u.name,commit:l?{oid:l.oid,authoredDate:new Date(l.authoredDate),committedDate:new Date(l.committedDate)}:null}})}:{pageInfo:{endCursor:null,hasNextPage:!1},data:[]}}async getBranches(e,t={}){return this.getRefs("refs/heads/",e,t)}async getTags(e,t={}){return this.getRefs("refs/tags/",e,t)}async getBlame(e,t={}){let s=await b(this.config,{query:`
540
540
  query getBlame($owner: String!, $name: String!, $ref: String!, $path: String!) {
541
541
  repository(owner: $owner, name: $name) {
542
542
  object(expression: $ref) {
@@ -575,7 +575,7 @@ query getBlame($owner: String!, $name: String!, $ref: String!, $path: String!) {
575
575
  }
576
576
  }
577
577
  }
578
- `,variables:{owner:e.repo.namespace,name:e.repo.name,ref:e.ref,path:e.path}},t),o=s.body.data?.repository;if(!o)throw new I("Blame repository not found.",s.body.errors);let i=o.object;if(!i||!("blame"in i))throw new I("Ref not found.",s.body.errors);if(i.blame.ranges.length===0)throw new I("File not found.",s.body.errors);return{data:{ranges:i.blame.ranges.map(a=>({startingLine:a.startingLine,endingLine:a.endingLine,commit:{oid:a.commit.oid,parentOids:a.commit.parents.nodes?.map(u=>u.oid)||[],authoredDate:new Date(a.commit.authoredDate),author:a.commit.author?{name:a.commit.author.name,email:a.commit.author.email,avatarUrl:a.commit.author.avatarUrl}:null,committedDate:new Date(a.commit.committedDate),committer:a.commit.committer?{name:a.commit.committer.name,email:a.commit.committer.email,avatarUrl:a.commit.committer.avatarUrl}:null,message:a.commit.message,fileCount:a.commit.changedFilesIfAvailable,additions:a.commit.additions,deletions:a.commit.deletions}}))}}}async getFileContents(e,t={}){let s=await this.config.request({url:`${z(this.config,t)}/repos/${e.repo.namespace}/${e.repo.name}/contents/${encodeURIComponent(e.path)}?ref=${e.ref}`,headers:{...R(t.token||this.config.token),Accept:"application/vnd.github.raw+json"}});if(s.headers["content-type"].startsWith("application/json"))throw new Error(`GitHub: got directory when fetching "${e.path}", getFileContents does not support fetching directories`);if(!s.headers["content-type"].startsWith("application/vnd.github.raw+json"))throw new Error(`GitHub: unsupported content type "${s.headers["content-type"]}" when fetching "${e.path}"`);return{data:new Blob([s.body])}}async getMergeBase(e,t={}){return{data:(await this.config.request({url:`${z(this.config,t)}/repos/${e.repo.namespace}/${e.repo.name}/compare/${encodeURIComponent(e.base)}...${encodeURIComponent(e.head)}`,headers:R(t.token||this.config.token)})).body.merge_base_commit.sha}}async getPullRequestDiff(e,t={}){return(await this.config.request({url:`${z(this.config,t)}/repos/${e.repo.namespace}/${e.repo.name}/pulls/${e.pullRequestId}`,headers:{...R(t.token||this.config.token),Accept:"application/vnd.github.diff"}})).body??""}async searchPullRequests(e,t={}){let s=await this.getEnterpriseVersion(t),o=await this.getScopes(t),i=V(o),a=$r(e.states),u=p=>{let c=p&&typeof e.isDraft=="boolean"?`${e.query} draft:${e.isDraft}`:e.query;return vt("pr",c,e.cursor,{maxPageSize:e.maxPageSize??qr,supportsEmail:i,supportsDrafts:p,enterpriseVersion:s,includeFromArchivedRepos:e.includeFromArchivedRepos,stateQualifier:a})},l=await b(this.config,u(!0),t);l.body.errors&&He(l.body.errors)&&(this.config.baseUrl||t.baseUrl)&&(l=await b(this.config,u(!1),t));let{data:d}=l.body;if(!d)throw new I("Could not search pull requests",l.body.errors);return{pageInfo:{hasNextPage:d.search.pageInfo.hasNextPage,endCursor:d.search.pageInfo.endCursor},data:k(d.search.nodes?.filter(x).map($t)||[],e.states)}}async searchIssues(e,t={}){let s=await this.getEnterpriseVersion(t),o=await this.getScopes(t),i=V(o),a=Dr(e.states),u=await b(this.config,vt("issue",e.query,e.cursor,{supportsEmail:i,includeFromArchivedRepos:e.includeFromArchivedRepos,maxPageSize:e.maxPageSize??vr,enterpriseVersion:s,stateQualifier:a}),t),{data:l}=u.body;if(!l)throw new I("Could not search issues",u.body.errors);return{pageInfo:{hasNextPage:l.search.pageInfo.hasNextPage,endCursor:l.search.pageInfo.endCursor},data:l.search.nodes?.filter(x).map(En)||[]}}async getPullRequestsAssociatedWithUser(e,t={}){let s=[`involves:${e.username}`];return e.repos?.length&&e.repos.forEach(o=>{s.push(`repo:${o.namespace}/${o.name}`)}),e.labelNames&&e.labelNames.forEach(o=>{s.push(`label:"${o}"`)}),this.searchPullRequests({query:s.join(" "),cursor:e.cursor,includeFromArchivedRepos:e.includeFromArchivedRepos,maxPageSize:e.maxPageSize},t)}async getPullRequestsForRepos(e,t={}){let{assigneeLogins:s,updatedBefore:o,authorLogin:i,repos:a,reviewRequestedLogin:u,startQuery:l,mentionLogin:d,labelNames:p,maxPageSize:c}=e,g=St(l||"");return a.forEach(m=>{g.push(`repo:${m.namespace}/${m.name}`)}),s&&s.forEach(m=>{g.push(`assignee:${m}`)}),o&&g.push(`updated:<${o}`),i&&g.push(`author:${i}`),u&&g.push(`review-requested:${u}`),d&&g.push(`mentions:${d}`),p&&p.forEach(m=>{g.push(`label:"${m}"`)}),this.searchPullRequests({query:`sort:updated ${g.join(" ")}`,isDraft:e.isDraft,cursor:e.cursor,includeFromArchivedRepos:e.includeFromArchivedRepos,maxPageSize:c,states:e.states},t)}async getPullRequestForRepo(e,t={}){let s=await this.getEnterpriseVersion(t),o=await this.getScopes(t),i=V(o),a=p=>({query:`query getPullRequest(
578
+ `,variables:{owner:e.repo.namespace,name:e.repo.name,ref:e.ref,path:e.path}},t),o=s.body.data?.repository;if(!o)throw new I("Blame repository not found.",s.body.errors);let i=o.object;if(!i||!("blame"in i))throw new I("Ref not found.",s.body.errors);if(i.blame.ranges.length===0)throw new I("File not found.",s.body.errors);return{data:{ranges:i.blame.ranges.map(a=>({startingLine:a.startingLine,endingLine:a.endingLine,commit:{oid:a.commit.oid,parentOids:a.commit.parents.nodes?.map(u=>u.oid)||[],authoredDate:new Date(a.commit.authoredDate),author:a.commit.author?{name:a.commit.author.name,email:a.commit.author.email,avatarUrl:a.commit.author.avatarUrl}:null,committedDate:new Date(a.commit.committedDate),committer:a.commit.committer?{name:a.commit.committer.name,email:a.commit.committer.email,avatarUrl:a.commit.committer.avatarUrl}:null,message:a.commit.message,fileCount:a.commit.changedFilesIfAvailable,additions:a.commit.additions,deletions:a.commit.deletions}}))}}}async getFileContents(e,t={}){let s=await this.config.request({url:`${M(this.config,t)}/repos/${e.repo.namespace}/${e.repo.name}/contents/${encodeURIComponent(e.path)}?ref=${e.ref}`,headers:{...R(t.token||this.config.token),Accept:"application/vnd.github.raw+json"}});if(s.headers["content-type"].startsWith("application/json"))throw new Error(`GitHub: got directory when fetching "${e.path}", getFileContents does not support fetching directories`);if(!s.headers["content-type"].startsWith("application/vnd.github.raw+json"))throw new Error(`GitHub: unsupported content type "${s.headers["content-type"]}" when fetching "${e.path}"`);return{data:new Blob([s.body])}}async getMergeBase(e,t={}){return{data:(await this.config.request({url:`${M(this.config,t)}/repos/${e.repo.namespace}/${e.repo.name}/compare/${encodeURIComponent(e.base)}...${encodeURIComponent(e.head)}`,headers:R(t.token||this.config.token)})).body.merge_base_commit.sha}}async getPullRequestDiff(e,t={}){return(await this.config.request({url:`${M(this.config,t)}/repos/${e.repo.namespace}/${e.repo.name}/pulls/${e.pullRequestId}`,headers:{...R(t.token||this.config.token),Accept:"application/vnd.github.diff"}})).body??""}async searchPullRequests(e,t={}){let s=await this.getEnterpriseVersion(t),o=await this.getScopes(t),i=V(o),a=Ur(e.states),u=d=>{let c=d&&typeof e.isDraft=="boolean"?`${e.query} draft:${e.isDraft}`:e.query;return $t("pr",c,e.cursor,{maxPageSize:e.maxPageSize??Cr,supportsEmail:i,supportsDrafts:d,enterpriseVersion:s,includeFromArchivedRepos:e.includeFromArchivedRepos,stateQualifier:a})},l=await b(this.config,u(!0),t);l.body.errors&&He(l.body.errors)&&(this.config.baseUrl||t.baseUrl)&&(l=await b(this.config,u(!1),t));let{data:p}=l.body;if(!p)throw new I("Could not search pull requests",l.body.errors);return{pageInfo:{hasNextPage:p.search.pageInfo.hasNextPage,endCursor:p.search.pageInfo.endCursor},data:k(p.search.nodes?.filter(x).map(Ut)||[],e.states)}}async searchIssues(e,t={}){let s=await this.getEnterpriseVersion(t),o=await this.getScopes(t),i=V(o),a=Ar(e.states),u=await b(this.config,$t("issue",e.query,e.cursor,{supportsEmail:i,includeFromArchivedRepos:e.includeFromArchivedRepos,maxPageSize:e.maxPageSize??$r,enterpriseVersion:s,stateQualifier:a}),t),{data:l}=u.body;if(!l)throw new I("Could not search issues",u.body.errors);return{pageInfo:{hasNextPage:l.search.pageInfo.hasNextPage,endCursor:l.search.pageInfo.endCursor},data:l.search.nodes?.filter(x).map(An)||[]}}async getPullRequestsAssociatedWithUser(e,t={}){let s=[`involves:${e.username}`];return e.repos?.length&&e.repos.forEach(o=>{s.push(`repo:${o.namespace}/${o.name}`)}),e.labelNames&&e.labelNames.forEach(o=>{s.push(`label:"${o}"`)}),this.searchPullRequests({query:s.join(" "),cursor:e.cursor,includeFromArchivedRepos:e.includeFromArchivedRepos,maxPageSize:e.maxPageSize},t)}async getPullRequestsForRepos(e,t={}){let{assigneeLogins:s,updatedBefore:o,authorLogin:i,repos:a,reviewRequestedLogin:u,startQuery:l,mentionLogin:p,labelNames:d,maxPageSize:c}=e,g=Et(l||"");return a.forEach(m=>{g.push(`repo:${m.namespace}/${m.name}`)}),s&&s.forEach(m=>{g.push(`assignee:${m}`)}),o&&g.push(`updated:<${o}`),i&&g.push(`author:${i}`),u&&g.push(`review-requested:${u}`),p&&g.push(`mentions:${p}`),d&&d.forEach(m=>{g.push(`label:"${m}"`)}),this.searchPullRequests({query:`sort:updated ${g.join(" ")}`,isDraft:e.isDraft,cursor:e.cursor,includeFromArchivedRepos:e.includeFromArchivedRepos,maxPageSize:c,states:e.states},t)}async getPullRequestForRepo(e,t={}){let s=await this.getEnterpriseVersion(t),o=await this.getScopes(t),i=V(o),a=d=>({query:`query getPullRequest(
579
579
  $owner: String!
580
580
  $name: String!
581
581
  $number: Int!
@@ -585,18 +585,18 @@ query getBlame($owner: String!, $name: String!, $ref: String!, $path: String!) {
585
585
  name: $name
586
586
  ) {
587
587
  pullRequest(number: $number) {
588
- ${ze(p,i,s)}
588
+ ${Me(d,i,s)}
589
589
  }
590
590
  }
591
- }`,variables:{owner:e.repo.namespace,name:e.repo.name,number:e.number}}),u=await b(this.config,a(!0),t);u.body.errors&&He(u.body.errors)&&(this.config.baseUrl||t.baseUrl)&&(u=await b(this.config,a(!1),t));let{data:l}=u.body;if(!l)throw new I("Could not fetch pull request by number",u.body.errors);let d=u.body.data?.repository.pullRequest;return{data:d?$t(d):null}}async getPullRequestDescription(e,t={}){try{let s=await this.config.request({url:`${z(this.config,t)}/repos/${e.repo.namespace}/${e.repo.name}/pulls/${e.number}`,headers:{...R(t.token||this.config.token),Accept:"application/vnd.github.full+json"}});return{data:{description:s.body?.body??"",descriptionHtml:s.body?.body_html||null}}}catch{return{data:{description:null,descriptionHtml:null}}}}async setPullRequestDescription(e,t={}){let s=await this.config.request({method:"PATCH",url:`${z(this.config,t)}/repos/${e.repo.namespace}/${e.repo.name}/pulls/${e.number}`,headers:{...R(t.token||this.config.token),Accept:"application/vnd.github+json","Content-Type":"application/json"},body:JSON.stringify({body:e.description})});return{data:{description:s.body?.body??e.description,descriptionHtml:s.body?.body_html||null}}}async getPullRequestByGraphQLId(e,t={}){let s=await this.getEnterpriseVersion(t),o=await this.getScopes(t),i=V(o),a=p=>({query:`query getPullRequest(
591
+ }`,variables:{owner:e.repo.namespace,name:e.repo.name,number:e.number}}),u=await b(this.config,a(!0),t);u.body.errors&&He(u.body.errors)&&(this.config.baseUrl||t.baseUrl)&&(u=await b(this.config,a(!1),t));let{data:l}=u.body;if(!l)throw new I("Could not fetch pull request by number",u.body.errors);let p=u.body.data?.repository.pullRequest;return{data:p?Ut(p):null}}async getPullRequestDescription(e,t={}){try{let s=await this.config.request({url:`${M(this.config,t)}/repos/${e.repo.namespace}/${e.repo.name}/pulls/${e.number}`,headers:{...R(t.token||this.config.token),Accept:"application/vnd.github.full+json"}});return{data:{description:s.body?.body??"",descriptionHtml:s.body?.body_html||null}}}catch{return{data:{description:null,descriptionHtml:null}}}}async setPullRequestDescription(e,t={}){let s=await this.config.request({method:"PATCH",url:`${M(this.config,t)}/repos/${e.repo.namespace}/${e.repo.name}/pulls/${e.number}`,headers:{...R(t.token||this.config.token),Accept:"application/vnd.github+json","Content-Type":"application/json"},body:JSON.stringify({body:e.description})});return{data:{description:s.body?.body??e.description,descriptionHtml:s.body?.body_html||null}}}async getPullRequestByGraphQLId(e,t={}){let s=await this.getEnterpriseVersion(t),o=await this.getScopes(t),i=V(o),a=d=>({query:`query getPullRequest(
592
592
  $graphQLId: ID!
593
593
  ) {
594
594
  node(id: $graphQLId) {
595
595
  ... on PullRequest {
596
- ${ze(p,i,s)}
596
+ ${Me(d,i,s)}
597
597
  }
598
598
  }
599
- }`,variables:{graphQLId:e.graphQLId}}),u=await b(this.config,a(!0),t);u.body.errors&&He(u.body.errors)&&(this.config.baseUrl||t.baseUrl)&&(u=await b(this.config,a(!1),t));let{data:l}=u.body;if(!l)throw new I("Could not fetch pull request by id",u.body.errors);let d=u.body.data?.node;return{data:d?$t(d):null}}async closePullRequest(e,t={}){let{pullRequest:{graphQLId:s}}=e;if(!s)throw new Error('GitHub requires "graphQLId" for this function.');let o=`mutation ClosePullRequest($pullRequestGraphQLId: ID!) {
599
+ }`,variables:{graphQLId:e.graphQLId}}),u=await b(this.config,a(!0),t);u.body.errors&&He(u.body.errors)&&(this.config.baseUrl||t.baseUrl)&&(u=await b(this.config,a(!1),t));let{data:l}=u.body;if(!l)throw new I("Could not fetch pull request by id",u.body.errors);let p=u.body.data?.node;return{data:p?Ut(p):null}}async closePullRequest(e,t={}){let{pullRequest:{graphQLId:s}}=e;if(!s)throw new Error('GitHub requires "graphQLId" for this function.');let o=`mutation ClosePullRequest($pullRequestGraphQLId: ID!) {
600
600
  closePullRequest(input: { pullRequestId: $pullRequestGraphQLId }) {
601
601
  pullRequest {
602
602
  id
@@ -669,7 +669,7 @@ query getBlame($owner: String!, $name: String!, $ref: String!, $path: String!) {
669
669
  }
670
670
  }
671
671
  }
672
- }`,a=await b(this.config,{query:i,variables:{subjectId:s.graphQLId,body:o}},t);if(!a.body.data?.addComment?.commentEdge?.node?.id)throw new I("Could not add comment to pull request",a.body.errors)}async addInlineCommentToPullRequest(e,t={}){let{pullRequest:s,comment:o,path:i,line:a,side:u="RIGHT",threadId:l}=e;if(!s.graphQLId)throw new Error('GitHub requires "graphQLId" for this function.');if(!o?.trim())throw new Error("GitHub requires a comment when adding an inline comment to a pull request.");if(l)return this.addReplyToReviewThread({threadId:l,comment:o},t);if(!i?.trim())throw new Error("GitHub requires a file path when adding an inline comment to a pull request.");if(!Number.isInteger(a)||a<1)throw new Error("GitHub requires a positive line number when adding an inline comment to a pull request.");if(u!=="LEFT"&&u!=="RIGHT")throw new Error('GitHub requires side to be either "LEFT" or "RIGHT".');return this.createReviewThread({pullRequest:s,comment:o,path:i,line:a,side:u},t)}async deleteInlineComment(e,t={}){let{commentId:s}=e;if(!s)throw new Error('GitHub requires "commentId" for this function.');let o=await b(this.config,{query:Gr,variables:{pullRequestReviewCommentId:s}},t);if(!o.body.data?.deletePullRequestReviewComment)throw new I("Could not delete inline comment",o.body.errors)}async deleteComment(e,t={}){let{commentId:s}=e;if(!s)throw new Error('GitHub requires "commentId" for this function.');let o=await b(this.config,{query:Ur,variables:{issueCommentId:s}},t);if(!o.body.data?.deleteIssueComment)throw new I("Could not delete comment",o.body.errors)}async editComment(e,t={}){let{commentId:s,body:o}=e;if(!s)throw new Error('GitHub requires "commentId" for this function.');if(!o?.trim())throw new Error("GitHub requires a body when editing a comment.");let i=await b(this.config,{query:Tr,variables:{issueCommentId:s,body:o}},t);if(!i.body.data?.updateIssueComment?.issueComment?.id)throw new I("Could not edit comment",i.body.errors)}async editInlineComment(e,t={}){let{commentId:s,body:o}=e;if(!s)throw new Error('GitHub requires "commentId" for this function.');if(!o?.trim())throw new Error("GitHub requires a body when editing an inline comment.");let i=await b(this.config,{query:xr,variables:{pullRequestReviewCommentId:s,body:o}},t);if(!i.body.data?.updatePullRequestReviewComment?.pullRequestReviewComment?.id)throw new I("Could not edit inline comment",i.body.errors)}async resolveReviewThread(e,t={}){let{threadId:s}=e;if(!s)throw new Error('GitHub requires "threadId" for this function.');let o=await b(this.config,{query:Or,variables:{pullRequestReviewThreadId:s}},t);if(!o.body.data?.resolveReviewThread?.thread?.id)throw new I("Could not resolve review thread",o.body.errors)}async unresolveReviewThread(e,t={}){let{threadId:s}=e;if(!s)throw new Error('GitHub requires "threadId" for this function.');let o=await b(this.config,{query:_r,variables:{pullRequestReviewThreadId:s}},t);if(!o.body.data?.unresolveReviewThread?.thread?.id)throw new I("Could not unresolve review thread",o.body.errors)}async addReplyToReviewThread(e,t){let{threadId:s,comment:o}=e,i=`mutation AddPullRequestReviewThreadReply(
672
+ }`,a=await b(this.config,{query:i,variables:{subjectId:s.graphQLId,body:o}},t);if(!a.body.data?.addComment?.commentEdge?.node?.id)throw new I("Could not add comment to pull request",a.body.errors)}async addInlineCommentToPullRequest(e,t={}){let{pullRequest:s,comment:o,path:i,line:a,side:u="RIGHT",threadId:l}=e;if(!s.graphQLId)throw new Error('GitHub requires "graphQLId" for this function.');if(!o?.trim())throw new Error("GitHub requires a comment when adding an inline comment to a pull request.");if(l)return this.addReplyToReviewThread({threadId:l,comment:o},t);if(!i?.trim())throw new Error("GitHub requires a file path when adding an inline comment to a pull request.");if(!Number.isInteger(a)||a<1)throw new Error("GitHub requires a positive line number when adding an inline comment to a pull request.");if(u!=="LEFT"&&u!=="RIGHT")throw new Error('GitHub requires side to be either "LEFT" or "RIGHT".');return this.createReviewThread({pullRequest:s,comment:o,path:i,line:a,side:u},t)}async deleteInlineComment(e,t={}){let{commentId:s}=e;if(!s)throw new Error('GitHub requires "commentId" for this function.');let o=await b(this.config,{query:_r,variables:{pullRequestReviewCommentId:s}},t);if(!o.body.data?.deletePullRequestReviewComment)throw new I("Could not delete inline comment",o.body.errors)}async deleteComment(e,t={}){let{commentId:s}=e;if(!s)throw new Error('GitHub requires "commentId" for this function.');let o=await b(this.config,{query:Or,variables:{issueCommentId:s}},t);if(!o.body.data?.deleteIssueComment)throw new I("Could not delete comment",o.body.errors)}async editComment(e,t={}){let{commentId:s,body:o}=e;if(!s)throw new Error('GitHub requires "commentId" for this function.');if(!o?.trim())throw new Error("GitHub requires a body when editing a comment.");let i=await b(this.config,{query:xr,variables:{issueCommentId:s,body:o}},t);if(!i.body.data?.updateIssueComment?.issueComment?.id)throw new I("Could not edit comment",i.body.errors)}async editInlineComment(e,t={}){let{commentId:s,body:o}=e;if(!s)throw new Error('GitHub requires "commentId" for this function.');if(!o?.trim())throw new Error("GitHub requires a body when editing an inline comment.");let i=await b(this.config,{query:Fr,variables:{pullRequestReviewCommentId:s,body:o}},t);if(!i.body.data?.updatePullRequestReviewComment?.pullRequestReviewComment?.id)throw new I("Could not edit inline comment",i.body.errors)}async resolveReviewThread(e,t={}){let{threadId:s}=e;if(!s)throw new Error('GitHub requires "threadId" for this function.');let o=await b(this.config,{query:kr,variables:{pullRequestReviewThreadId:s}},t);if(!o.body.data?.resolveReviewThread?.thread?.id)throw new I("Could not resolve review thread",o.body.errors)}async unresolveReviewThread(e,t={}){let{threadId:s}=e;if(!s)throw new Error('GitHub requires "threadId" for this function.');let o=await b(this.config,{query:Nr,variables:{pullRequestReviewThreadId:s}},t);if(!o.body.data?.unresolveReviewThread?.thread?.id)throw new I("Could not unresolve review thread",o.body.errors)}async addReplyToReviewThread(e,t){let{threadId:s,comment:o}=e,i=`mutation AddPullRequestReviewThreadReply(
673
673
  $threadId: ID!,
674
674
  $body: String!
675
675
  ) {
@@ -707,7 +707,7 @@ query getBlame($owner: String!, $name: String!, $ref: String!, $path: String!) {
707
707
  }
708
708
  }
709
709
  }
710
- }`,d=await b(this.config,{query:l,variables:{pullRequestId:s.graphQLId,body:o,path:i,line:a,side:u}},t);if(!d.body.data?.addPullRequestReview?.pullRequestReview?.id)throw new I("Could not add inline comment to pull request",d.body.errors);return d.body.data?.addPullRequestReview?.pullRequestReview?.comments?.nodes?.[0]?.id}async setPullRequestMilestone(e,t={}){let{pullRequest:s,milestone:o}=e;if(!s.graphQLId)throw new Error('GitHub requires "graphQLId" for this function.');let i=`mutation SetPullRequestMilestone($pullRequestGraphQLId: ID!, $milestoneGraphQLId: ID) {
710
+ }`,p=await b(this.config,{query:l,variables:{pullRequestId:s.graphQLId,body:o,path:i,line:a,side:u}},t);if(!p.body.data?.addPullRequestReview?.pullRequestReview?.id)throw new I("Could not add inline comment to pull request",p.body.errors);return p.body.data?.addPullRequestReview?.pullRequestReview?.comments?.nodes?.[0]?.id}async setPullRequestMilestone(e,t={}){let{pullRequest:s,milestone:o}=e;if(!s.graphQLId)throw new Error('GitHub requires "graphQLId" for this function.');let i=`mutation SetPullRequestMilestone($pullRequestGraphQLId: ID!, $milestoneGraphQLId: ID) {
711
711
  updatePullRequest(input: { pullRequestId: $pullRequestGraphQLId, milestoneId: $milestoneGraphQLId }) {
712
712
  pullRequest {
713
713
  id
@@ -725,13 +725,13 @@ query getBlame($owner: String!, $name: String!, $ref: String!, $path: String!) {
725
725
  id
726
726
  }
727
727
  }
728
- }`,o=await b(this.config,{query:s,variables:{pullRequestGraphQLId:e}},t);if(!o.body.data?.convertPullRequestToDraft?.pullRequest?.id)throw new I("Could not convert pull request to draft",o.body.errors)}async setPullRequestAsDraft(e,t={}){let{pullRequest:{graphQLId:s},isDraft:o}=e;if(!s)throw new Error('GitHub requires "graphQLId" for this function.');if(o){await this.convertPullRequestToDraft(s,t);return}await this.markPullRequestReadyForReview(s,t)}async setPullRequestReviewers(e,t={}){let{pullRequest:{reviews:s,graphQLId:o},reviewers:i}=e;if(!s)throw new Error('GitHub requires "reviews" for this function');if(!o)throw new Error('GitHub requires "graphQLId" for this function.');let a=s.filter(p=>p.state!=="REVIEW_REQUESTED").map(p=>{if(!p.reviewer.graphQLId)throw new Error('GitHub requires reviewer "graphQLId" for this function.');return p.reviewer.graphQLId}),u=i.map(p=>{if(!p.graphQLId)throw new Error('GitHub requires reviewer "graphQLId" for this function.');return p.graphQLId}).filter(p=>a.indexOf(p)===-1),l=`mutation SetPullRequestReviewers($pullRequestGraphQLId: ID!, $reviewerGraphQLIds: [ID!]!) {
728
+ }`,o=await b(this.config,{query:s,variables:{pullRequestGraphQLId:e}},t);if(!o.body.data?.convertPullRequestToDraft?.pullRequest?.id)throw new I("Could not convert pull request to draft",o.body.errors)}async setPullRequestAsDraft(e,t={}){let{pullRequest:{graphQLId:s},isDraft:o}=e;if(!s)throw new Error('GitHub requires "graphQLId" for this function.');if(o){await this.convertPullRequestToDraft(s,t);return}await this.markPullRequestReadyForReview(s,t)}async setPullRequestReviewers(e,t={}){let{pullRequest:{reviews:s,graphQLId:o},reviewers:i}=e;if(!s)throw new Error('GitHub requires "reviews" for this function');if(!o)throw new Error('GitHub requires "graphQLId" for this function.');let a=s.filter(d=>d.state!=="REVIEW_REQUESTED").map(d=>{if(!d.reviewer.graphQLId)throw new Error('GitHub requires reviewer "graphQLId" for this function.');return d.reviewer.graphQLId}),u=i.map(d=>{if(!d.graphQLId)throw new Error('GitHub requires reviewer "graphQLId" for this function.');return d.graphQLId}).filter(d=>a.indexOf(d)===-1),l=`mutation SetPullRequestReviewers($pullRequestGraphQLId: ID!, $reviewerGraphQLIds: [ID!]!) {
729
729
  requestReviews(input: { pullRequestId: $pullRequestGraphQLId, userIds: $reviewerGraphQLIds }) {
730
730
  pullRequest {
731
731
  id
732
732
  }
733
733
  }
734
- }`,d=await b(this.config,{query:l,variables:{pullRequestGraphQLId:o,reviewerGraphQLIds:u}},t);if(!d.body.data?.requestReviews?.pullRequest?.id)throw new I("Could not set pull request reviewers",d.body.errors)}async reRequestPullRequestReviews(e,t={}){let{pullRequest:{reviews:s,graphQLId:o},reviewers:i}=e;if(!o)throw new Error('GitHub requires "graphQLId" for this function.');if(!s)throw new Error('GitHub requires "reviews" for this function.');let a=[];for(let d of i){if(!d.graphQLId)throw new Error('GitHub requires reviwer "graphQLId" for this function.');if(!s.find(p=>p.reviewer.graphQLId===d.graphQLId))throw new Error("Can only re-request review from existing reviewer.");a.push(d.graphQLId)}let u=`mutation SetPullRequestReviewers($pullRequestGraphQLId: ID!, $reviewerGraphQLIds: [ID!]!) {
734
+ }`,p=await b(this.config,{query:l,variables:{pullRequestGraphQLId:o,reviewerGraphQLIds:u}},t);if(!p.body.data?.requestReviews?.pullRequest?.id)throw new I("Could not set pull request reviewers",p.body.errors)}async reRequestPullRequestReviews(e,t={}){let{pullRequest:{reviews:s,graphQLId:o},reviewers:i}=e;if(!o)throw new Error('GitHub requires "graphQLId" for this function.');if(!s)throw new Error('GitHub requires "reviews" for this function.');let a=[];for(let p of i){if(!p.graphQLId)throw new Error('GitHub requires reviwer "graphQLId" for this function.');if(!s.find(d=>d.reviewer.graphQLId===p.graphQLId))throw new Error("Can only re-request review from existing reviewer.");a.push(p.graphQLId)}let u=`mutation SetPullRequestReviewers($pullRequestGraphQLId: ID!, $reviewerGraphQLIds: [ID!]!) {
735
735
  requestReviews(input: { pullRequestId: $pullRequestGraphQLId, userIds: $reviewerGraphQLIds, union: true }) {
736
736
  pullRequest {
737
737
  id
@@ -771,7 +771,7 @@ query getBlame($owner: String!, $name: String!, $ref: String!, $path: String!) {
771
771
  login
772
772
  }
773
773
  body
774
- ${!s||M(s,"PR_REVIEW_COMMENT_FULL_DATABASE_ID")?"fullDatabaseId":"databaseId"}
774
+ ${!s||z(s,"PR_REVIEW_COMMENT_FULL_DATABASE_ID")?"fullDatabaseId":"databaseId"}
775
775
  diffHunk
776
776
  id
777
777
  path
@@ -791,7 +791,7 @@ query getBlame($owner: String!, $name: String!, $ref: String!, $path: String!) {
791
791
  login
792
792
  }
793
793
  body
794
- ${!s||M(s,"PR_REVIEW_FULL_DATABASE_ID")?"fullDatabaseId":"databaseId"}
794
+ ${!s||z(s,"PR_REVIEW_FULL_DATABASE_ID")?"fullDatabaseId":"databaseId"}
795
795
  id
796
796
  publishedAt
797
797
  url
@@ -799,13 +799,13 @@ query getBlame($owner: String!, $name: String!, $ref: String!, $path: String!) {
799
799
  }
800
800
  }
801
801
  }
802
- }`,l=await b(this.config,{query:u,variables:{namespace:o,name:i,pullRequestId:a}},t),d=l.body.data?.repository.pullRequest.reviewThreads.nodes?.filter(x).reduce((c,g)=>{if(!g.comments.nodes?.[0]?.pullRequestReview)return c;let m=g.comments.nodes[0].pullRequestReview,h=qn(g);return h&&(c[m.id]||(c[m.id]=[]),c[m.id].push(h)),c},{})??{};return{data:l.body.data?.repository.pullRequest.reviews.nodes?.filter(x).filter(c=>d[c.id]).map(c=>({author:c.author?{avatarUrl:c.author.avatarUrl,email:null,name:c.author.login}:null,body:c.body,createdAt:c.publishedAt?new Date(c.publishedAt):null,id:c.fullDatabaseId??c.databaseId.toString(),graphQLId:c.id,reviewComments:d[c.id],url:c.url}))??[]}}async getCommentsForPullRequest(e,t={}){let s=await this.getEnterpriseVersion(t),o=!s||M(s,"ISSUE_FULL_DATABASE_ID"),{repo:{namespace:i,name:a},pullRequestNumber:u,cursor:l}=e,d=await b(this.config,{query:kr(o),variables:{namespace:i,name:a,pullRequestNumber:u,cursor:l,first:L}},t),p=d.body.data?.repository;if(!p)throw new I("Could not fetch pull request comments",d.body.errors);return{data:p.pullRequest.comments.nodes?.filter(x).map(Ar)??[],pageInfo:p.pullRequest.comments.pageInfo}}async getIssuesAssociatedWithUser(e,t={}){let[s,o]=e.cursor?.split(";")||[void 0,void 0],i=[];e.labelNames&&e.labelNames.forEach(c=>{i.push(`label:"${c}"`)});let[a,u]=await Promise.all([s==="null"?null:this.searchIssues({query:`author:${e.username} ${i.join(" ")}`,cursor:s,includeFromArchivedRepos:e.includeFromArchivedRepos,maxPageSize:e.maxPageSize},t),o==="null"?null:this.searchIssues({query:`assignee:${e.username} ${i.join(" ")}`,cursor:o,includeFromArchivedRepos:e.includeFromArchivedRepos,maxPageSize:e.maxPageSize},t)]),l={},d=[],p=c=>{l[c.id]||(l[c.id]=!0,d.push(c))};return a?.data.forEach(p),u?.data.forEach(p),{pageInfo:{hasNextPage:a?.pageInfo.hasNextPage||u?.pageInfo.hasNextPage||!1,endCursor:`${a?.pageInfo.hasNextPage&&a?.pageInfo.endCursor||"null"};${u?.pageInfo.hasNextPage&&u?.pageInfo.endCursor||"null"}`},data:d}}async setPullRequestLabels(e,t={}){let{pullRequest:s,labels:o}=e;if(!s.graphQLId)throw new Error('GitHub requires "graphQLId" for this function.');let i=`mutation SetPullRequestLabels($pullRequestGraphQLId: ID!, $labelGraphQLIds: [ID!]) {
802
+ }`,l=await b(this.config,{query:u,variables:{namespace:o,name:i,pullRequestId:a}},t),p=l.body.data?.repository.pullRequest.reviewThreads.nodes?.filter(x).reduce((c,g)=>{if(!g.comments.nodes?.[0]?.pullRequestReview)return c;let m=g.comments.nodes[0].pullRequestReview,h=Ln(g);return h&&(c[m.id]||(c[m.id]=[]),c[m.id].push(h)),c},{})??{};return{data:l.body.data?.repository.pullRequest.reviews.nodes?.filter(x).filter(c=>p[c.id]).map(c=>({author:c.author?{avatarUrl:c.author.avatarUrl,email:null,name:c.author.login}:null,body:c.body,createdAt:c.publishedAt?new Date(c.publishedAt):null,id:c.fullDatabaseId??c.databaseId.toString(),graphQLId:c.id,reviewComments:p[c.id],url:c.url}))??[]}}async getCommentsForPullRequest(e,t={}){let s=await this.getEnterpriseVersion(t),o=!s||z(s,"ISSUE_FULL_DATABASE_ID"),{repo:{namespace:i,name:a},pullRequestNumber:u,cursor:l}=e,p=await b(this.config,{query:jr(o),variables:{namespace:i,name:a,pullRequestNumber:u,cursor:l,first:C}},t),d=p.body.data?.repository;if(!d)throw new I("Could not fetch pull request comments",p.body.errors);return{data:d.pullRequest.comments.nodes?.filter(x).map(Tr)??[],pageInfo:d.pullRequest.comments.pageInfo}}async getIssuesAssociatedWithUser(e,t={}){let[s,o]=e.cursor?.split(";")||[void 0,void 0],i=[];e.labelNames&&e.labelNames.forEach(c=>{i.push(`label:"${c}"`)});let[a,u]=await Promise.all([s==="null"?null:this.searchIssues({query:`author:${e.username} ${i.join(" ")}`,cursor:s,includeFromArchivedRepos:e.includeFromArchivedRepos,maxPageSize:e.maxPageSize},t),o==="null"?null:this.searchIssues({query:`assignee:${e.username} ${i.join(" ")}`,cursor:o,includeFromArchivedRepos:e.includeFromArchivedRepos,maxPageSize:e.maxPageSize},t)]),l={},p=[],d=c=>{l[c.id]||(l[c.id]=!0,p.push(c))};return a?.data.forEach(d),u?.data.forEach(d),{pageInfo:{hasNextPage:a?.pageInfo.hasNextPage||u?.pageInfo.hasNextPage||!1,endCursor:`${a?.pageInfo.hasNextPage&&a?.pageInfo.endCursor||"null"};${u?.pageInfo.hasNextPage&&u?.pageInfo.endCursor||"null"}`},data:p}}async setPullRequestLabels(e,t={}){let{pullRequest:s,labels:o}=e;if(!s.graphQLId)throw new Error('GitHub requires "graphQLId" for this function.');let i=`mutation SetPullRequestLabels($pullRequestGraphQLId: ID!, $labelGraphQLIds: [ID!]) {
803
803
  updatePullRequest(input: { pullRequestId: $pullRequestGraphQLId, labelIds: $labelGraphQLIds }) {
804
804
  pullRequest {
805
805
  id
806
806
  }
807
807
  }
808
- }`,a=await b(this.config,{query:i,variables:{pullRequestGraphQLId:s.graphQLId,labelGraphQLIds:o.map(u=>{if(!u.graphQLId)throw new Error('GitHub requires label "graphQLId" for this function.');return u.graphQLId})}},t);if(!a.body.data?.updatePullRequest?.pullRequest?.id)throw new I("Could not set pull request labels",a.body.errors)}async getIssuesForRepos(e,t={}){let s=St(e.startQuery||""),{cursor:o,assigneeLogins:i,updatedBefore:a,authorLogin:u,mentionLogin:l,labelNames:d}=e;return e.repos.forEach(p=>{s.push(`repo:${p.namespace}/${p.name}`)}),i&&i.forEach(p=>{s.push(`assignee:${p}`)}),a&&s.push(`updated:<${a}`),u&&s.push(`author:${u}`),l&&s.push(`mentions:${l}`),d&&d.forEach(p=>{s.push(`label:"${p}"`)}),this.searchIssues({query:`sort:updated ${s.join(" ")}`,cursor:o,includeFromArchivedRepos:e.includeFromArchivedRepos,maxPageSize:e.maxPageSize,states:e.states},t)}async closeIssueWithReason(e,t={}){let{issue:s,reason:o}=e;if(!s.graphQLId)throw new Error('GitHub requires "graphQLId" for this function.');let i=`mutation CloseIssueWithReason($issueGraphQLId: ID!, $reason: IssueClosedStateReason!) {
808
+ }`,a=await b(this.config,{query:i,variables:{pullRequestGraphQLId:s.graphQLId,labelGraphQLIds:o.map(u=>{if(!u.graphQLId)throw new Error('GitHub requires label "graphQLId" for this function.');return u.graphQLId})}},t);if(!a.body.data?.updatePullRequest?.pullRequest?.id)throw new I("Could not set pull request labels",a.body.errors)}async getIssuesForRepos(e,t={}){let s=Et(e.startQuery||""),{cursor:o,assigneeLogins:i,updatedBefore:a,authorLogin:u,mentionLogin:l,labelNames:p}=e;return e.repos.forEach(d=>{s.push(`repo:${d.namespace}/${d.name}`)}),i&&i.forEach(d=>{s.push(`assignee:${d}`)}),a&&s.push(`updated:<${a}`),u&&s.push(`author:${u}`),l&&s.push(`mentions:${l}`),p&&p.forEach(d=>{s.push(`label:"${d}"`)}),this.searchIssues({query:`sort:updated ${s.join(" ")}`,cursor:o,includeFromArchivedRepos:e.includeFromArchivedRepos,maxPageSize:e.maxPageSize,states:e.states},t)}async closeIssueWithReason(e,t={}){let{issue:s,reason:o}=e;if(!s.graphQLId)throw new Error('GitHub requires "graphQLId" for this function.');let i=`mutation CloseIssueWithReason($issueGraphQLId: ID!, $reason: IssueClosedStateReason!) {
809
809
  closeIssue(input: { issueId: $issueGraphQLId, stateReason: $reason }) {
810
810
  issue {
811
811
  id
@@ -855,12 +855,12 @@ query getLabelsForRepo($owner: String!, $name: String! $cursor: String, $first:
855
855
  }
856
856
  }
857
857
  }
858
- `,variables:{owner:s,name:o,cursor:i,first:L}},t);if(!a.body.data)throw new I("Could not fetch milestones",a.body.errors);return{pageInfo:a.body.data.repository.milestones?.pageInfo??{endCursor:null,hasNextPage:!1},data:a.body.data.repository.milestones?.nodes?.map(Lt)??[]}}async getLabelsForRepo(e,t={}){let{repo:{namespace:s,name:o},cursor:i}=e,a=await b(this.config,{query:`
858
+ `,variables:{owner:s,name:o,cursor:i,first:C}},t);if(!a.body.data)throw new I("Could not fetch milestones",a.body.errors);return{pageInfo:a.body.data.repository.milestones?.pageInfo??{endCursor:null,hasNextPage:!1},data:a.body.data.repository.milestones?.nodes?.map(Gt)??[]}}async getLabelsForRepo(e,t={}){let{repo:{namespace:s,name:o},cursor:i}=e,a=await b(this.config,{query:`
859
859
  query getLabelsForRepo($owner: String!, $name: String! $cursor: String, $first: Int!) {
860
860
  repository(owner: $owner, name: $name) {
861
861
  labels(first: $first, after: $cursor) {
862
862
  nodes {
863
- ${Me}
863
+ ${ze}
864
864
  }
865
865
  pageInfo {
866
866
  endCursor
@@ -869,7 +869,7 @@ query getLabelsForRepo($owner: String!, $name: String! $cursor: String, $first:
869
869
  }
870
870
  }
871
871
  }
872
- `,variables:{owner:s,name:o,cursor:i,first:L}},t);if(!a.body.data)throw new I("Could not fetch labels",a.body.errors);return{pageInfo:a.body.data.repository.labels?.pageInfo??{endCursor:null,hasNextPage:!1},data:a.body.data.repository.labels?.nodes?.map(Dt)??[]}}async getTreeForRepo(e,t={}){let s=await this.config.request({url:`${z(this.config,t)}/repos/${e.repo.namespace}/${e.repo.name}/git/trees/${e.branch}?recursive=1`,headers:{...R(t.token||this.config.token)}});if(!s.body)throw new Error("Could not fetch trees");return{data:s.body.tree.map(bn)}}};var Cn="https://gitlab.com/api/v4",$n="https://gitlab.com/api/graphql",At=/\/api\/v\d+$/,jr=r=>{if(r.endsWith("/api/graphql"))throw new Error("The graphql endpoint is being used as the baseUrl. This package uses both GraphQL and REST APIs, and the REST version cannot be assumed. Use the REST endpoint as the baseUrl instead.")},U=(r,n)=>{let e=n.baseUrl||r.baseUrl;return e?(e=e.replace(/\/$/,""),jr(e),At.test(e)||(e=e+"/api/v4"),e):Cn},Dn=(r,n)=>{let e=n.baseUrl||r.baseUrl;return e?(e=e.replace(/\/$/,""),jr(e),At.test(e)&&(e=e.replace(At,"")),`${e}/api/graphql`):$n},v=(r,n,e)=>{let t=R(e.token||r.token);return r.request({url:Dn(r,e),method:"POST",headers:{...t,"Content-Type":"application/json"},body:JSON.stringify(n)})},$e=r=>r?.map(n=>`"${n.message}"`).join(", ");var Ft=r=>r.split("/").slice(0,-1).join("/"),jt=r=>r.split("/").at(-1)??"",Qr=r=>{let n=parseInt(`${r["x-next-page"]}`,10);return Number.isNaN(n)?{hasNextPage:!1,nextPage:null}:{hasNextPage:!0,nextPage:n}},We=r=>({id:r.id.replace(be,""),graphQLId:r.id,namespace:Ft(r.fullPath),name:jt(r.fullPath),webUrl:r.webUrl}),De=r=>({id:r.id.replace(be,""),graphQLId:r.id,httpsUrl:r.httpUrlToRepo,namespace:Ft(r.fullPath),name:jt(r.fullPath),sshUrl:r.sshUrlToRepo,webUrl:r.webUrl}),Ln={assigned:"assignedMergeRequests",authored:"authoredMergeRequests",reviewRequested:"reviewRequestedMergeRequests"},An={CAN_BE_MERGED:"MERGEABLE",CANNOT_BE_MERGED:"CONFLICTS",CANNOT_BE_MERGED_RECHECK:"UNKNOWN",UNCHECKED:"UNKNOWN",CHECKING:"UNKNOWN"};var Hr="gid://gitlab/User/",be="gid://gitlab/Project/",Un="gid://gitlab/MergeRequest/",Gn="gid://gitlab/Issue/",Tn="gid://gitlab/ProjectLabel/",On="gid://gitlab/Milestone/",_n="gid://gitlab/Ci::Build/",Qt=`
872
+ `,variables:{owner:s,name:o,cursor:i,first:C}},t);if(!a.body.data)throw new I("Could not fetch labels",a.body.errors);return{pageInfo:a.body.data.repository.labels?.pageInfo??{endCursor:null,hasNextPage:!1},data:a.body.data.repository.labels?.nodes?.map(At)??[]}}async getTreeForRepo(e,t={}){let s=await this.config.request({url:`${M(this.config,t)}/repos/${e.repo.namespace}/${e.repo.name}/git/trees/${e.branch}?recursive=1`,headers:{...R(t.token||this.config.token)}});if(!s.body)throw new Error("Could not fetch trees");return{data:s.body.tree.map(vn)}}};var Gn="https://gitlab.com/api/v4",Tn="https://gitlab.com/api/graphql",Tt=/\/api\/v\d+$/,zr=r=>{if(r.endsWith("/api/graphql"))throw new Error("The graphql endpoint is being used as the baseUrl. This package uses both GraphQL and REST APIs, and the REST version cannot be assumed. Use the REST endpoint as the baseUrl instead.")},A=(r,n)=>{let e=n.baseUrl||r.baseUrl;return e?(e=e.replace(/\/$/,""),zr(e),Tt.test(e)||(e=e+"/api/v4"),e):Gn},On=(r,n)=>{let e=n.baseUrl||r.baseUrl;return e?(e=e.replace(/\/$/,""),zr(e),Tt.test(e)&&(e=e.replace(Tt,"")),`${e}/api/graphql`):Tn},v=(r,n,e)=>{let t=R(e.token||r.token);return r.request({url:On(r,e),method:"POST",headers:{...t,"Content-Type":"application/json"},body:JSON.stringify(n)})},$e=r=>r?.map(n=>`"${n.message}"`).join(", ");var Je=r=>r.split("/").slice(0,-1).join("/"),Ve=r=>r.split("/").at(-1)??"",Ot=r=>{let n=parseInt(`${r["x-next-page"]}`,10);return Number.isNaN(n)?{hasNextPage:!1,nextPage:null}:{hasNextPage:!0,nextPage:n}},We=r=>({id:r.id.replace(pe,""),graphQLId:r.id,namespace:Je(r.fullPath),name:Ve(r.fullPath),webUrl:r.webUrl}),De=r=>({id:r.id.replace(pe,""),graphQLId:r.id,httpsUrl:r.httpUrlToRepo,namespace:Je(r.fullPath),name:Ve(r.fullPath),sshUrl:r.sshUrlToRepo,webUrl:r.webUrl}),_n={assigned:"assignedMergeRequests",authored:"authoredMergeRequests",reviewRequested:"reviewRequestedMergeRequests"},xn={CAN_BE_MERGED:"MERGEABLE",CANNOT_BE_MERGED:"CONFLICTS",CANNOT_BE_MERGED_RECHECK:"UNKNOWN",UNCHECKED:"UNKNOWN",CHECKING:"UNKNOWN"};var Vr="gid://gitlab/User/",pe="gid://gitlab/Project/",kn="gid://gitlab/MergeRequest/",Kr="gid://gitlab/Issue/",Nn="gid://gitlab/ProjectLabel/",Fn="gid://gitlab/Milestone/",jn="gid://gitlab/Ci::Build/",Mt=`
873
873
  description
874
874
  dueDate
875
875
  id
@@ -878,7 +878,7 @@ startDate
878
878
  state
879
879
  title
880
880
  webPath
881
- `,Ut=`
881
+ `,_t=`
882
882
  id
883
883
  fullPath
884
884
  webUrl
@@ -899,7 +899,7 @@ username
899
899
  publicEmail
900
900
  avatarUrl
901
901
  webUrl
902
- `,Bt=`
902
+ `,Ht=`
903
903
  color
904
904
  description
905
905
  id
@@ -910,7 +910,7 @@ httpUrlToRepo
910
910
  fullPath
911
911
  sshUrlToRepo
912
912
  webUrl
913
- `,Gt=`
913
+ `,xt=`
914
914
  author {
915
915
  ${K}
916
916
  }
@@ -927,7 +927,7 @@ id
927
927
  iid
928
928
  labels {
929
929
  nodes {
930
- ${Bt}
930
+ ${Ht}
931
931
  }
932
932
  }
933
933
  state
@@ -938,9 +938,9 @@ upvotes
938
938
  userNotesCount
939
939
  webUrl
940
940
  milestone {
941
- ${Qt}
941
+ ${Mt}
942
942
  }
943
- `,xn=`
943
+ `,Qn=`
944
944
  stages {
945
945
  nodes {
946
946
  jobs {
@@ -956,7 +956,7 @@ stages {
956
956
  name
957
957
  }
958
958
  }
959
- `,Tt=(r,n,e)=>`
959
+ `,kt=(r,n,e)=>`
960
960
  id
961
961
  state
962
962
  author {
@@ -1001,19 +1001,19 @@ reviewers {
1001
1001
  mergeStatusEnum
1002
1002
  labels {
1003
1003
  nodes {
1004
- ${Bt}
1004
+ ${Ht}
1005
1005
  }
1006
1006
  }
1007
1007
  ${r?`project { ${Le} archived } sourceProject { ${Le} }`:""}
1008
- ${n?`milestone { ${Qt} }`:""}
1009
- ${e?`headPipeline { ${xn} }`:""}
1010
- `,_=r=>`${r.namespace}/${r.name}`,kn=r=>`${r.namespace}/${r.name}`,Nn=r=>/Field '[^']+' (?:doesn'?t|does not) exist on type|Field '[^']+' is not defined|undefined field '[^']+' on type/i.test(r.message),Fn=r=>({canCreateWebhook:r.adminOperations,canPush:r.pushCode,isAdmin:r.adminOperations}),Ot=r=>({id:r.id.replace(be,""),graphQLId:r.id,namespace:Ft(r.fullPath),name:jt(r.fullPath),webUrl:r.webUrl,httpsUrl:r.httpUrlToRepo,sshUrl:r.sshUrlToRepo,defaultBranch:r.repository?.rootRef?{name:r.repository.rootRef}:null,permissions:Fn(r.userPermissions)}),jn=r=>({path:r.path,isDirectory:r.type==="tree"}),Qn={opened:"OPEN",merged:"MERGED",closed:"CLOSED"},Bn={OPEN:"opened",MERGED:"merged",CLOSED:"closed"},Br=r=>{if(!r||r.length===0)return"state: opened";let n=Array.from(new Set(r));return n.length>1?"":`state: ${Bn[n[0]]}`},Mr=r=>{if(!r||r.length===0)return"state: opened";let n=Array.from(new Set(r));return n.length>1?"":`state: ${n[0]==="CLOSED"?"closed":"opened"}`},re=100,Mn=20,zn=250,Je=(r,n,e)=>!n&&r?.startsWith("/")?`https://gitlab.com${r}`:n&&r?.startsWith("/")&&e?`${e.replace(/\/+?$/,"")}${r}`:r,X=(r,n,e)=>{let t=Je(r.avatarUrl,n,e);return{id:r.id.replace(Hr,""),graphQLId:r.id,name:r.name,username:r.username,email:r.publicEmail??null,avatarUrl:t,url:r.webUrl}},Mt=r=>({color:r.color,description:r.description,id:r.id.replace(Tn,""),graphQLId:r.id,name:r.title}),Hn=(r,n)=>r?r==="FAILED"&&n?"WARNING":{CANCELED:"CANCELLED",CREATED:"PENDING",FAILED:"FAILED",MANUAL:"OPTIONAL_ACTION_REQUIRED",PENDING:"PENDING",PREPARING:"RUNNING",RUNNING:"RUNNING",SCHEDULED:"PENDING",SKIPPED:"SKIPPED",SUCCESS:"SUCCESS",WAITING_FOR_CALLBACK:"PENDING",WAITING_FOR_RESOURCE:"PENDING"}[r]:null,Wn=(r,n,e)=>{let t={APPROVED:"APPROVED",REQUESTED_CHANGES:"CHANGES_REQUESTED",REVIEWED:"COMMENTED",UNAPPROVED:"REVIEW_REQUESTED",UNREVIEWED:"REVIEW_REQUESTED"};return{reviewer:X(r,n,e),state:r.mergeRequestInteraction?.reviewState?t[r.mergeRequestInteraction.reviewState]:"REVIEW_REQUESTED"}},_t=(r,n,e,t,s)=>{let o=r.reviewers?.nodes?r.reviewers.nodes.map(i=>Wn(i,t,s)):null;return{id:r.id.replace(Un,""),graphQLId:r.id,title:r.title,description:r.description,number:parseInt(r.iid,10),state:Qn[r.state],commentCount:r.userNotesCount||0,upvoteCount:r.upvotes,author:r.author?X(r.author,t,s):null,createdDate:new Date(r.createdAt),isDraft:r.draft,repository:{id:n.id,graphQLId:n.graphQLId,name:n.name,owner:{login:n.namespace},remoteInfo:n.httpsUrl&&n.sshUrl?{cloneUrlHTTPS:n.httpsUrl,cloneUrlSSH:n.sshUrl}:null},isCrossRepository:e!=null&&e.id!==n.id,headRepository:e?{id:e.id,graphQLId:e.graphQLId,name:e.name,owner:{login:e.namespace},remoteInfo:{cloneUrlHTTPS:e.httpsUrl,cloneUrlSSH:e.sshUrl}}:null,headCommit:{buildStatuses:r.headPipeline?.stages?.nodes?.flatMap(i=>i.jobs?.nodes?.map(a=>({completedAt:a.finishedAt?new Date(a.finishedAt):null,description:null,name:a.name??null,state:Hn(a.status,a.allowFailure),stage:i.name??null,startedAt:new Date(a.createdAt),url:`${n.webUrl}/-/jobs/${a.id.replace(_n,"")}`}))??[])??[]},baseRef:{name:r.targetBranch,oid:r.diffRefs?.baseSha??null},headRef:{name:r.sourceBranch,oid:r.diffRefs?.headSha??null},url:r.webUrl,updatedDate:new Date(r.updatedAt),closedDate:r.mergedAt?new Date(r.mergedAt):null,mergedDate:r.mergedAt?new Date(r.mergedAt):null,assignees:r.assignees?.nodes?r.assignees.nodes.map(i=>X(i,t,s)):null,reviews:o,reviewDecision:B(o),additions:r.diffStatsSummary?.additions||0,deletions:r.diffStatsSummary?.deletions||0,fileCount:r.diffStatsSummary?.fileCount||0,commitCount:r.commitCount||0,mergeableState:An[r.mergeStatusEnum],milestone:r.milestone?zt(r.milestone,n.webUrl):null,labels:r.labels?.nodes?.map(Mt)??[],permissions:null}},xt=(r,n,e,t)=>({author:X(r.author,e,t),assignees:r.assignees.nodes.map(s=>X(s,e,t)),commentCount:r.userNotesCount,closedDate:r.closedAt?new Date(r.closedAt):null,createdDate:new Date(r.createdAt),description:r.description,graphQLId:r.id,id:r.id.replace(Gn,""),labels:r.labels?.nodes?.map(Mt)??[],number:r.iid,repository:{id:n.id.replace(be,""),graphQLId:n.id,name:n.name,owner:{login:n.namespace}},updatedDate:new Date(r.updatedAt),upvoteCount:r.upvotes,state:{name:r.state,color:null},type:r.type,title:r.title,url:r.webUrl,milestone:r.milestone?zt(r.milestone,n.webUrl):null}),zt=(r,n)=>({id:r.id.replace(On,""),graphQLId:r.id,number:parseInt(r.iid,10),title:r.title,description:r.description,isOpen:r.state==="active",url:`${n}/-/${r.webPath.replace(/.+?\/-\//,"")}`,startDate:r.startDate?new Date(r.startDate):null,dueDate:r.dueDate?new Date(r.dueDate):null}),Jn=r=>Buffer.from(JSON.stringify(r),"utf8").toString("base64"),Vn=(r,n)=>{if(!r)return{page:1,perPage:n};try{let e=JSON.parse(Buffer.from(r,"base64").toString("utf8")),t=typeof e.page=="number"&&e.page>0?e.page:1,s=typeof e.perPage=="number"&&e.perPage>0?e.perPage:n;return{page:t,perPage:s}}catch{return{page:1,perPage:n}}},Kn=(r,n,e)=>({id:r.id.toString(),graphQLId:`${Hr}${r.id}`,name:r.name,username:r.username,email:r.email??null,avatarUrl:Je(r.avatar_url,n,e),url:r.web_url}),zr=(r,n,e)=>({avatarUrl:Je(r.avatar_url,n,e)??"",email:null,name:r.name}),Xn=r=>r?.new_line!=null?"RIGHT":r?.old_line!=null?"LEFT":null,Zn=r=>{let n=r.old_path||r.new_path,e=r.new_path||r.old_path,t=[`diff --git a/${n} b/${e}`];return r.new_file&&r.b_mode?t.push(`new file mode ${r.b_mode}`):r.deleted_file&&r.a_mode?t.push(`deleted file mode ${r.a_mode}`):r.a_mode&&r.b_mode&&r.a_mode!==r.b_mode&&(t.push(`old mode ${r.a_mode}`),t.push(`new mode ${r.b_mode}`)),r.renamed_file&&(t.push(`rename from ${r.old_path}`),t.push(`rename to ${r.new_path}`)),r.diff&&r.diff.length>0?(t.push(`--- ${r.new_file?"/dev/null":`a/${n}`}`),t.push(`+++ ${r.deleted_file?"/dev/null":`b/${e}`}`),`${t.join(`
1008
+ ${n?`milestone { ${Mt} }`:""}
1009
+ ${e?`headPipeline { ${Qn} }`:""}
1010
+ `,_=r=>`${r.namespace}/${r.name}`,Bn=r=>`${r.namespace}/${r.name}`,zn=r=>/Field '[^']+' (?:doesn'?t|does not) exist on type|Field '[^']+' is not defined|undefined field '[^']+' on type/i.test(r.message),Mn=r=>({canCreateWebhook:r.adminOperations,canPush:r.pushCode,isAdmin:r.adminOperations}),Nt=r=>({id:r.id.replace(pe,""),graphQLId:r.id,namespace:Je(r.fullPath),name:Ve(r.fullPath),webUrl:r.webUrl,httpsUrl:r.httpUrlToRepo,sshUrl:r.sshUrlToRepo,defaultBranch:r.repository?.rootRef?{name:r.repository.rootRef}:null,permissions:Mn(r.userPermissions)}),Hn=r=>({path:r.path,isDirectory:r.type==="tree"}),Wn={opened:"OPEN",merged:"MERGED",closed:"CLOSED"},Jn={OPEN:"opened",MERGED:"merged",CLOSED:"closed"},Mr=r=>{if(!r||r.length===0)return"state: opened";let n=Array.from(new Set(r));return n.length>1?"":`state: ${Jn[n[0]]}`},Hr=r=>{if(!r||r.length===0)return"state: opened";let n=Array.from(new Set(r));return n.length>1?"":`state: ${n[0]==="CLOSED"?"closed":"opened"}`},re=100,Vn=20,Kn=250,Ke=(r,n,e)=>!n&&r?.startsWith("/")?`https://gitlab.com${r}`:n&&r?.startsWith("/")&&e?`${e.replace(/\/+?$/,"")}${r}`:r,X=(r,n,e)=>{let t=Ke(r.avatarUrl,n,e);return{id:r.id.replace(Vr,""),graphQLId:r.id,name:r.name,username:r.username,email:r.publicEmail??null,avatarUrl:t,url:r.webUrl}},Wt=r=>({color:r.color,description:r.description,id:r.id.replace(Nn,""),graphQLId:r.id,name:r.title}),Xn=(r,n)=>r?r==="FAILED"&&n?"WARNING":{CANCELED:"CANCELLED",CREATED:"PENDING",FAILED:"FAILED",MANUAL:"OPTIONAL_ACTION_REQUIRED",PENDING:"PENDING",PREPARING:"RUNNING",RUNNING:"RUNNING",SCHEDULED:"PENDING",SKIPPED:"SKIPPED",SUCCESS:"SUCCESS",WAITING_FOR_CALLBACK:"PENDING",WAITING_FOR_RESOURCE:"PENDING"}[r]:null,Zn=(r,n,e)=>{let t={APPROVED:"APPROVED",REQUESTED_CHANGES:"CHANGES_REQUESTED",REVIEWED:"COMMENTED",UNAPPROVED:"REVIEW_REQUESTED",UNREVIEWED:"REVIEW_REQUESTED"};return{reviewer:X(r,n,e),state:r.mergeRequestInteraction?.reviewState?t[r.mergeRequestInteraction.reviewState]:"REVIEW_REQUESTED"}},Ft=(r,n,e,t,s)=>{let o=r.reviewers?.nodes?r.reviewers.nodes.map(i=>Zn(i,t,s)):null;return{id:r.id.replace(kn,""),graphQLId:r.id,title:r.title,description:r.description,number:parseInt(r.iid,10),state:Wn[r.state],commentCount:r.userNotesCount||0,upvoteCount:r.upvotes,author:r.author?X(r.author,t,s):null,createdDate:new Date(r.createdAt),isDraft:r.draft,repository:{id:n.id,graphQLId:n.graphQLId,name:n.name,owner:{login:n.namespace},remoteInfo:n.httpsUrl&&n.sshUrl?{cloneUrlHTTPS:n.httpsUrl,cloneUrlSSH:n.sshUrl}:null},isCrossRepository:e!=null&&e.id!==n.id,headRepository:e?{id:e.id,graphQLId:e.graphQLId,name:e.name,owner:{login:e.namespace},remoteInfo:{cloneUrlHTTPS:e.httpsUrl,cloneUrlSSH:e.sshUrl}}:null,headCommit:{buildStatuses:r.headPipeline?.stages?.nodes?.flatMap(i=>i.jobs?.nodes?.map(a=>({completedAt:a.finishedAt?new Date(a.finishedAt):null,description:null,name:a.name??null,state:Xn(a.status,a.allowFailure),stage:i.name??null,startedAt:new Date(a.createdAt),url:`${n.webUrl}/-/jobs/${a.id.replace(jn,"")}`}))??[])??[]},baseRef:{name:r.targetBranch,oid:r.diffRefs?.baseSha??null},headRef:{name:r.sourceBranch,oid:r.diffRefs?.headSha??null},url:r.webUrl,updatedDate:new Date(r.updatedAt),closedDate:r.mergedAt?new Date(r.mergedAt):null,mergedDate:r.mergedAt?new Date(r.mergedAt):null,assignees:r.assignees?.nodes?r.assignees.nodes.map(i=>X(i,t,s)):null,reviews:o,reviewDecision:B(o),additions:r.diffStatsSummary?.additions||0,deletions:r.diffStatsSummary?.deletions||0,fileCount:r.diffStatsSummary?.fileCount||0,commitCount:r.commitCount||0,mergeableState:xn[r.mergeStatusEnum],milestone:r.milestone?Jt(r.milestone,n.webUrl):null,labels:r.labels?.nodes?.map(Wt)??[],permissions:null}},jt=(r,n,e,t)=>({author:X(r.author,e,t),assignees:r.assignees.nodes.map(s=>X(s,e,t)),commentCount:r.userNotesCount,closedDate:r.closedAt?new Date(r.closedAt):null,createdDate:new Date(r.createdAt),description:r.description,graphQLId:r.id,id:r.id.replace(Kr,""),labels:r.labels?.nodes?.map(Wt)??[],number:r.iid,repository:{id:n.id.replace(pe,""),graphQLId:n.id,name:n.name,owner:{login:n.namespace}},updatedDate:new Date(r.updatedAt),upvoteCount:r.upvotes,state:{name:r.state,color:null},type:r.type,title:r.title,url:r.webUrl,milestone:r.milestone?Jt(r.milestone,n.webUrl):null}),Jt=(r,n)=>({id:r.id.replace(Fn,""),graphQLId:r.id,number:parseInt(r.iid,10),title:r.title,description:r.description,isOpen:r.state==="active",url:`${n}/-/${r.webPath.replace(/.+?\/-\//,"")}`,startDate:r.startDate?new Date(r.startDate):null,dueDate:r.dueDate?new Date(r.dueDate):null}),Yn=r=>Buffer.from(JSON.stringify(r),"utf8").toString("base64"),eo=(r,n)=>{if(!r)return{page:1,perPage:n};try{let e=JSON.parse(Buffer.from(r,"base64").toString("utf8")),t=typeof e.page=="number"&&e.page>0?e.page:1,s=typeof e.perPage=="number"&&e.perPage>0?e.perPage:n;return{page:t,perPage:s}}catch{return{page:1,perPage:n}}},Bt=(r,n,e)=>({id:r.id.toString(),graphQLId:`${Vr}${r.id}`,name:r.name,username:r.username,email:r.email??null,avatarUrl:Ke(r.avatar_url,n,e),url:r.web_url}),Wr=(r,n,e)=>({avatarUrl:Ke(r.avatar_url,n,e)??"",email:null,name:r.name}),Jr=r=>r.replace(/^\/+/,"").split("/")[0]==="groups",to=r=>{let n=r.references?.full;if(n){let t=n.includes("#")?n.slice(0,n.lastIndexOf("#")):n;if(t&&!Jr(t))return t}let e="/-/issues";try{let{pathname:t}=new URL(r.web_url),s=t.indexOf(e);if(s===-1)return;let o=t.slice(0,s).replace(/^\/+/,"");return!o||Jr(o)?void 0:o}catch{return}},ro=(r,n,e)=>{let t=to(r);return{author:r.author?Bt(r.author,n,e):null,assignees:(r.assignees??[]).map(s=>Bt(s,n,e)),commentCount:r.user_notes_count,closedDate:r.closed_at?new Date(r.closed_at):null,createdDate:new Date(r.created_at),description:r.description,graphQLId:`${Kr}${r.id}`,id:r.id.toString(),labels:(r.labels??[]).map(s=>({color:null,description:null,id:null,name:s})),number:r.iid.toString(),repository:{graphQLId:`${pe}${r.project_id}`,id:r.project_id.toString(),name:t?Ve(t):"",owner:{login:t?Je(t):void 0}},updatedDate:new Date(r.updated_at),upvoteCount:r.upvotes,state:{name:r.state,color:null},type:null,title:r.title,url:r.web_url}},so=r=>r?.new_line!=null?"RIGHT":r?.old_line!=null?"LEFT":null,no=r=>{let n=r.old_path||r.new_path,e=r.new_path||r.old_path,t=[`diff --git a/${n} b/${e}`];return r.new_file&&r.b_mode?t.push(`new file mode ${r.b_mode}`):r.deleted_file&&r.a_mode?t.push(`deleted file mode ${r.a_mode}`):r.a_mode&&r.b_mode&&r.a_mode!==r.b_mode&&(t.push(`old mode ${r.a_mode}`),t.push(`new mode ${r.b_mode}`)),r.renamed_file&&(t.push(`rename from ${r.old_path}`),t.push(`rename to ${r.new_path}`)),r.diff&&r.diff.length>0?(t.push(`--- ${r.new_file?"/dev/null":`a/${n}`}`),t.push(`+++ ${r.deleted_file?"/dev/null":`b/${e}`}`),`${t.join(`
1011
1011
  `)}
1012
1012
  ${r.diff.endsWith(`
1013
1013
  `)?r.diff:`${r.diff}
1014
1014
  `}`):`${t.join(`
1015
1015
  `)}
1016
- `},Wr="|",Nt=(r,n,e,t)=>[r,n,e.toString(),t.toString()].join(Wr),Yn=r=>{let n=r.split(Wr);if(n.length!==4)throw new Error("Invalid GitLab comment ID format \u2014 expected a composite ID produced by getCommentsForPullRequest or addInlineCommentToPullRequest.");return{namespace:n[0],name:n[1],mergeRequestIid:n[2],noteId:n[3]}},kt=(r,n,e,t)=>({author:r.author?Kn(r.author,n,e):null,body:r.body,createdAt:r.created_at?new Date(r.created_at):null,id:Nt(t.namespace,t.name,t.mergeRequestIid,r.id),url:""}),ye=class extends N{getIsSelfHosted(n){return!!n.baseUrl||!!this.config.baseUrl}async getCurrentUser(n={},e={}){let s=(await v(this.config,{query:`
1016
+ `},Xr="|",zt=(r,n,e,t)=>[r,n,e.toString(),t.toString()].join(Xr),oo=r=>{let n=r.split(Xr);if(n.length!==4)throw new Error("Invalid GitLab comment ID format \u2014 expected a composite ID produced by getCommentsForPullRequest or addInlineCommentToPullRequest.");return{namespace:n[0],name:n[1],mergeRequestIid:n[2],noteId:n[3]}},Qt=(r,n,e,t)=>({author:r.author?Bt(r.author,n,e):null,body:r.body,createdAt:r.created_at?new Date(r.created_at):null,id:zt(t.namespace,t.name,t.mergeRequestIid,r.id),url:""}),ye=class extends N{getIsSelfHosted(n){return!!n.baseUrl||!!this.config.baseUrl}async getCurrentUser(n={},e={}){let s=(await v(this.config,{query:`
1017
1017
  query getCurrentUser {
1018
1018
  currentUser {
1019
1019
  ${K}
@@ -1035,7 +1035,7 @@ query getUserForCommit($fullPath: ID!, $oid: String!) {
1035
1035
  }
1036
1036
  }
1037
1037
  }
1038
- `,variables:{fullPath:t,oid:n.oid}},e)).body.data?.project?.repository?.tree?.lastCommit;if(!o)throw new Error("Commit not found.");let i=Je(o.author.avatarUrl,this.getIsSelfHosted(e),this.config.baseUrl??e.baseUrl);return{data:{name:o.authorName,email:o.authorEmail,avatarUrl:i}}}async getAccountForEmail(n,e={}){let s=(await v(this.config,{query:`
1038
+ `,variables:{fullPath:t,oid:n.oid}},e)).body.data?.project?.repository?.tree?.lastCommit;if(!o)throw new Error("Commit not found.");let i=Ke(o.author.avatarUrl,this.getIsSelfHosted(e),this.config.baseUrl??e.baseUrl);return{data:{name:o.authorName,email:o.authorEmail,avatarUrl:i}}}async getAccountForEmail(n,e={}){let s=(await v(this.config,{query:`
1039
1039
  query getAccountForEmail($email: String!) {
1040
1040
  users(search: $email) {
1041
1041
  nodes {
@@ -1073,19 +1073,19 @@ query getAccountsForRepo(
1073
1073
  `,variables:{fullPath:`${t}/${s}`,after:o}},e),a=i.body.data?.project?.projectMembers?.nodes?.map(u=>u.user).filter(u=>u!==null);return{pageInfo:i.body.data?.project?.projectMembers?.pageInfo??{endCursor:null,hasNextPage:!1},data:a?.map(u=>X(u,this.getIsSelfHosted(e),this.config.baseUrl??e.baseUrl))??[]}}async getRepo(n,e={}){let t=_(n),s=await v(this.config,{query:`
1074
1074
  query getRepo($fullPath: ID!) {
1075
1075
  project(fullPath: $fullPath) {
1076
- ${Ut}
1076
+ ${_t}
1077
1077
  }
1078
1078
  }
1079
- `,variables:{fullPath:t}},e);if(!s.body.data?.project)throw new Error(`Repository ${t} not found`);return{data:Ot(s.body.data.project)}}async getReposBase(n,e={}){let s=n.map(_).map((u,l)=>`
1079
+ `,variables:{fullPath:t}},e);if(!s.body.data?.project)throw new Error(`Repository ${t} not found`);return{data:Nt(s.body.data.project)}}async getReposBase(n,e={}){let s=n.map(_).map((u,l)=>`
1080
1080
  getRepo_${l}: project(fullPath: "${u}") {
1081
- ${Ut}
1081
+ ${_t}
1082
1082
  }
1083
1083
  `).join(`
1084
1084
  `),o=await v(this.config,{query:`
1085
1085
  query batchGetRepos {
1086
1086
  ${s}
1087
1087
  }
1088
- `},e);if(!o.body.data)throw new Error($e(o.body.errors)||o.statusText||"Unknown error");let i=[],a=[];return n.forEach((u,l)=>{let d=o.body.data[`getRepo_${l}`];d?i.push(Ot(d)):a.push({input:u})}),{data:i,errors:a}}async getRepos(n,e={}){let t=[];for(let i=0;i<n.length;i+=15)t.push(n.slice(i,i+15));return(await Promise.all(t.map(i=>this.getReposBase(i,e)))).reduce((i,a)=>({data:[...i.data,...a.data],errors:[...i.errors,...a.errors]}),{data:[],errors:[]})}async getReposForCurrentUser(n,e={}){let t=await v(this.config,{query:`
1088
+ `},e);if(!o.body.data)throw new Error($e(o.body.errors)||o.statusText||"Unknown error");let i=[],a=[];return n.forEach((u,l)=>{let p=o.body.data[`getRepo_${l}`];p?i.push(Nt(p)):a.push({input:u})}),{data:i,errors:a}}async getRepos(n,e={}){let t=[];for(let i=0;i<n.length;i+=15)t.push(n.slice(i,i+15));return(await Promise.all(t.map(i=>this.getReposBase(i,e)))).reduce((i,a)=>({data:[...i.data,...a.data],errors:[...i.errors,...a.errors]}),{data:[],errors:[]})}async getReposForCurrentUser(n,e={}){let t=await v(this.config,{query:`
1089
1089
  query getReposForCurrentUser($after: String) {
1090
1090
  projects(membership: true first: 100 after: $after) {
1091
1091
  pageInfo {
@@ -1093,11 +1093,11 @@ query getReposForCurrentUser($after: String) {
1093
1093
  hasNextPage
1094
1094
  }
1095
1095
  nodes {
1096
- ${Ut}
1096
+ ${_t}
1097
1097
  }
1098
1098
  }
1099
1099
  }
1100
- `,variables:{after:n.cursor}},e);if(!t.body.data?.projects)throw new Error($e(t.body.errors)||t.statusText||"Unknown error");let s=t.body.data?.projects?.nodes||[];return{pageInfo:t.body.data?.projects?.pageInfo,data:s.map(Ot)}}async getGroupsForCurrentUser(n={},e={}){let t=new URL(`${U(this.config,e)}/groups`);t.searchParams.set("top_level_only",(n.topLevelOnly??!0).toString()),t.searchParams.set("page",n.page?.toString()||"1"),t.searchParams.set("per_page",L.toString());let s=await this.config.request({url:t.toString(),headers:R(e.token||this.config.token)});return{pageInfo:Qr(s.headers),data:s.body.map(o=>({id:o.id.toString(),path:o.path,fullPath:o.full_path,name:o.name,webUrl:o.web_url}))}}async getRefs(n,e,t={}){let s=_(e.repo),o=new URL(`${U(this.config,t)}/projects/${encodeURIComponent(s)}/repository/${n}`);o.searchParams.set("page",e.page?.toString()||"1"),o.searchParams.set("per_page",L.toString());let i=await this.config.request({url:o.toString(),headers:R(t.token||this.config.token)});return{pageInfo:Qr(i.headers),data:i.body.map(a=>({name:a.name,commit:{oid:a.commit.id,authoredDate:new Date(a.commit.authored_date),committedDate:new Date(a.commit.committed_date)}}))}}async getBranches(n,e={}){return this.getRefs("branches",n,e)}async getTags(n,e={}){return this.getRefs("tags",n,e)}async getBlame(n,e={}){let t=_(n.repo),s=new URL(`${U(this.config,e)}/projects/${encodeURIComponent(t)}/repository/files/${encodeURIComponent(n.path)}/blame`);s.searchParams.set("ref",n.ref);let o=await this.config.request({url:s.toString(),headers:R(e.token||this.config.token)}),i=0;return{data:{ranges:o.body.map(a=>{let u=i+1;return i+=a.lines.length,{startingLine:u,endingLine:i,commit:{oid:a.commit.id,parentOids:a.commit.parent_ids,authoredDate:new Date(a.commit.authored_date),author:{name:a.commit.author_name,email:a.commit.author_email,avatarUrl:null},committedDate:new Date(a.commit.committed_date),committer:{name:a.commit.committer_name,email:a.commit.committer_email,avatarUrl:null},message:a.commit.message,fileCount:null,additions:null,deletions:null}}})}}}async getPullRequestsForUser(n,e={}){let t="";n.repo?.id?t=`projectId:"${n.repo.id}"`:n.repo?.namespace&&n.repo?.name&&(t=`projectPath:"${n.repo.namespace}/${n.repo.name}"`);let s=Ln[n.association],o=Br(n.states),i=A(n.pageSize,{fallback:re,max:re}),a=await v(this.config,{query:`
1100
+ `,variables:{after:n.cursor}},e);if(!t.body.data?.projects)throw new Error($e(t.body.errors)||t.statusText||"Unknown error");let s=t.body.data?.projects?.nodes||[];return{pageInfo:t.body.data?.projects?.pageInfo,data:s.map(Nt)}}async getGroupsForCurrentUser(n={},e={}){let t=new URL(`${A(this.config,e)}/groups`);t.searchParams.set("top_level_only",(n.topLevelOnly??!0).toString()),t.searchParams.set("page",n.page?.toString()||"1"),t.searchParams.set("per_page",C.toString());let s=await this.config.request({url:t.toString(),headers:R(e.token||this.config.token)});return{pageInfo:Ot(s.headers),data:s.body.map(o=>({id:o.id.toString(),path:o.path,fullPath:o.full_path,name:o.name,webUrl:o.web_url}))}}async getRefs(n,e,t={}){let s=_(e.repo),o=new URL(`${A(this.config,t)}/projects/${encodeURIComponent(s)}/repository/${n}`);o.searchParams.set("page",e.page?.toString()||"1"),o.searchParams.set("per_page",C.toString());let i=await this.config.request({url:o.toString(),headers:R(t.token||this.config.token)});return{pageInfo:Ot(i.headers),data:i.body.map(a=>({name:a.name,commit:{oid:a.commit.id,authoredDate:new Date(a.commit.authored_date),committedDate:new Date(a.commit.committed_date)}}))}}async getBranches(n,e={}){return this.getRefs("branches",n,e)}async getTags(n,e={}){return this.getRefs("tags",n,e)}async getBlame(n,e={}){let t=_(n.repo),s=new URL(`${A(this.config,e)}/projects/${encodeURIComponent(t)}/repository/files/${encodeURIComponent(n.path)}/blame`);s.searchParams.set("ref",n.ref);let o=await this.config.request({url:s.toString(),headers:R(e.token||this.config.token)}),i=0;return{data:{ranges:o.body.map(a=>{let u=i+1;return i+=a.lines.length,{startingLine:u,endingLine:i,commit:{oid:a.commit.id,parentOids:a.commit.parent_ids,authoredDate:new Date(a.commit.authored_date),author:{name:a.commit.author_name,email:a.commit.author_email,avatarUrl:null},committedDate:new Date(a.commit.committed_date),committer:{name:a.commit.committer_name,email:a.commit.committer_email,avatarUrl:null},message:a.commit.message,fileCount:null,additions:null,deletions:null}}})}}}async getPullRequestsForUser(n,e={}){let t="";n.repo?.id?t=`projectId:"${n.repo.id}"`:n.repo?.namespace&&n.repo?.name&&(t=`projectPath:"${n.repo.namespace}/${n.repo.name}"`);let s=_n[n.association],o=Mr(n.states),i=U(n.pageSize,{fallback:re,max:re}),a=await v(this.config,{query:`
1101
1101
  query getPullRequestsForUser($username: String! $cursor: String $labelNames: [String!]) {
1102
1102
  user(username: $username) {
1103
1103
  ${s}(${o} first: ${i} after:$cursor labels: $labelNames${t?` ${t}`:""}) {
@@ -1106,16 +1106,16 @@ query getPullRequestsForUser($username: String! $cursor: String $labelNames: [St
1106
1106
  hasNextPage
1107
1107
  }
1108
1108
  nodes {
1109
- ${Tt(!0,!0,!0)}
1109
+ ${kt(!0,!0,!0)}
1110
1110
  }
1111
1111
  }
1112
1112
  }
1113
1113
  }
1114
- `,variables:{username:n.username,cursor:n.cursor,labelNames:n.labelNames}},e);if(!a.body.data)throw new Error($e(a.body.errors)||a.statusText||"Unknown error");if(!a.body.data.user)throw new Error("User not found");let u=a.body.data.user[s];if(!u)throw new Error("Unexpected response");let l=u.nodes?.filter(d=>n.includeFromArchivedRepos||!d.project.archived).map(d=>_t(d,De(d.project),d.sourceProject?De(d.sourceProject):null,this.getIsSelfHosted(e),this.config.baseUrl??e.baseUrl))||[];return{pageInfo:u.pageInfo,data:k(l,n.states)}}async getPullRequestsAssociatedWithUser(n,e={}){let[t,s,o]=n.cursor?.split(";")||[void 0,void 0,void 0],i=t?.split("-")||[],a=s?.split("-")||[],u=o?.split("-")||[],l=[],d=[],p=[],c=0;do{let $=n.repos&&n.repos[c];i[c]==="null"?l.push(null):l.push(this.getPullRequestsForUser({username:n.username,association:"authored",cursor:i[c],includeFromArchivedRepos:n.includeFromArchivedRepos,labelNames:n.labelNames,...$&&{repo:$}},e)),a[c]==="null"?d.push(null):d.push(this.getPullRequestsForUser({username:n.username,association:"assigned",cursor:a[c],includeFromArchivedRepos:n.includeFromArchivedRepos,labelNames:n.labelNames,...$&&{repo:$}},e)),u[c]==="null"?p.push(null):p.push(this.getPullRequestsForUser({username:n.username,association:"reviewRequested",cursor:u[c],includeFromArchivedRepos:n.includeFromArchivedRepos,labelNames:n.labelNames,...$&&{repo:$}},e)),c++}while(c<(n.repos?.length||0));let g=[l,d,p].flat(),m=await Promise.all(g),h={},y=[],f=$=>{h[$.id]||(h[$.id]=!0,y.push($))},P=!1,D=m.map(($,w)=>{let E="";return $&&$.data.forEach(f),$?.pageInfo.hasNextPage?(P=!0,E+=`${$.pageInfo.endCursor||"null"}`):E+="null",n.repos?.length&&(w+1)%n.repos.length!==0?E+="-":w+1<m.length&&(E+=";"),E}).join("");return{pageInfo:{hasNextPage:P,endCursor:D},data:y}}getVariablesForPullRequests(n){let{updatedBefore:e,isDraft:t,authorLogin:s,assigneeLogins:o,labelNames:i,reviewRequestedLogin:a}=n||{},u={},l=[],d=[],p=(c,g,m)=>{l.push(`$${c}: ${m}`),d.push(`${c}: $${c}`),u[c]=g};return e&&p("updatedBefore",e,"Time"),s&&p("authorUsername",s,"String"),o&&o.length&&(o.length===1?p("assigneeUsername",o[0],"String"):p("assigneeUsernames",o,"[String!]")),i&&p("labelName",i,"[String]"),t!=null&&p("draft",t,"Boolean"),a&&p("reviewerUsername",a,"String"),{variables:u,variableTypes:l,mergeRequestArguments:d}}async getPullRequestsForRepoBase(n,e={},t){let{cursor:s,repo:o}=n||{},i=_(o),a=Br(n.states),u=A(n.pageSize,{fallback:re,max:re}),{variables:l,variableTypes:d,mergeRequestArguments:p}=this.getVariablesForPullRequests(n),c={fullPath:i,...l},g=await v(this.config,{query:`
1114
+ `,variables:{username:n.username,cursor:n.cursor,labelNames:n.labelNames}},e);if(!a.body.data)throw new Error($e(a.body.errors)||a.statusText||"Unknown error");if(!a.body.data.user)throw new Error("User not found");let u=a.body.data.user[s];if(!u)throw new Error("Unexpected response");let l=u.nodes?.filter(p=>n.includeFromArchivedRepos||!p.project.archived).map(p=>Ft(p,De(p.project),p.sourceProject?De(p.sourceProject):null,this.getIsSelfHosted(e),this.config.baseUrl??e.baseUrl))||[];return{pageInfo:u.pageInfo,data:k(l,n.states)}}async getPullRequestsAssociatedWithUser(n,e={}){let[t,s,o]=n.cursor?.split(";")||[void 0,void 0,void 0],i=t?.split("-")||[],a=s?.split("-")||[],u=o?.split("-")||[],l=[],p=[],d=[],c=0;do{let D=n.repos&&n.repos[c];i[c]==="null"?l.push(null):l.push(this.getPullRequestsForUser({username:n.username,association:"authored",cursor:i[c],includeFromArchivedRepos:n.includeFromArchivedRepos,labelNames:n.labelNames,...D&&{repo:D}},e)),a[c]==="null"?p.push(null):p.push(this.getPullRequestsForUser({username:n.username,association:"assigned",cursor:a[c],includeFromArchivedRepos:n.includeFromArchivedRepos,labelNames:n.labelNames,...D&&{repo:D}},e)),u[c]==="null"?d.push(null):d.push(this.getPullRequestsForUser({username:n.username,association:"reviewRequested",cursor:u[c],includeFromArchivedRepos:n.includeFromArchivedRepos,labelNames:n.labelNames,...D&&{repo:D}},e)),c++}while(c<(n.repos?.length||0));let g=[l,p,d].flat(),m=await Promise.all(g),h={},y=[],f=D=>{h[D.id]||(h[D.id]=!0,y.push(D))},P=!1,L=m.map((D,w)=>{let E="";return D&&D.data.forEach(f),D?.pageInfo.hasNextPage?(P=!0,E+=`${D.pageInfo.endCursor||"null"}`):E+="null",n.repos?.length&&(w+1)%n.repos.length!==0?E+="-":w+1<m.length&&(E+=";"),E}).join("");return{pageInfo:{hasNextPage:P,endCursor:L},data:y}}getVariablesForPullRequests(n){let{updatedBefore:e,isDraft:t,authorLogin:s,assigneeLogins:o,labelNames:i,reviewRequestedLogin:a}=n||{},u={},l=[],p=[],d=(c,g,m)=>{l.push(`$${c}: ${m}`),p.push(`${c}: $${c}`),u[c]=g};return e&&d("updatedBefore",e,"Time"),s&&d("authorUsername",s,"String"),o&&o.length&&(o.length===1?d("assigneeUsername",o[0],"String"):d("assigneeUsernames",o,"[String!]")),i&&d("labelName",i,"[String]"),t!=null&&d("draft",t,"Boolean"),a&&d("reviewerUsername",a,"String"),{variables:u,variableTypes:l,mergeRequestArguments:p}}async getPullRequestsForRepoBase(n,e={},t){let{cursor:s,repo:o}=n||{},i=_(o),a=Mr(n.states),u=U(n.pageSize,{fallback:re,max:re}),{variables:l,variableTypes:p,mergeRequestArguments:d}=this.getVariablesForPullRequests(n),c={fullPath:i,...l},g=await v(this.config,{query:`
1115
1115
  query getPullRequestsForRepo(
1116
1116
  $fullPath: ID!
1117
1117
  $after: String
1118
- ${d.length?d.join(" "):""}
1118
+ ${p.length?p.join(" "):""}
1119
1119
  ) {
1120
1120
  project(
1121
1121
  fullPath: $fullPath
@@ -1129,14 +1129,14 @@ query getPullRequestsForRepo(
1129
1129
  ${a}
1130
1130
  sort: UPDATED_DESC
1131
1131
  after: $after
1132
- ${p.length?p.join(" "):""}
1132
+ ${d.length?d.join(" "):""}
1133
1133
  ) {
1134
1134
  pageInfo {
1135
1135
  endCursor
1136
1136
  hasNextPage
1137
1137
  }
1138
1138
  nodes {
1139
- ${Tt(!1,!0,!0)}
1139
+ ${kt(!1,!0,!0)}
1140
1140
  sourceProject {
1141
1141
  ${Le}
1142
1142
  }
@@ -1144,7 +1144,7 @@ query getPullRequestsForRepo(
1144
1144
  }
1145
1145
  }
1146
1146
  }
1147
- `,variables:{...c,after:s}},e),m=[],h=g.body.data?.project;if(!t&&h?.archived)return{pageInfo:null,data:[]};let y=We(h||{id:"",fullPath:"",webUrl:""});return(h?.mergeRequests?.nodes||[]).forEach(P=>{let q=P.sourceProject?De(P.sourceProject):null;m.push(_t(P,y,q,this.getIsSelfHosted(e),this.config.baseUrl??e.baseUrl))}),{pageInfo:h?.mergeRequests?.pageInfo,data:k(m,n.states)}}async getPullRequestsForRepo(n,e={}){return this.getPullRequestsForRepoBase(n,e,!1)}async getPullRequestsForRepos(n,e={}){let{repos:t,assigneeLogins:s,updatedBefore:o,authorLogin:i,labelNames:a,isDraft:u,reviewRequestedLogin:l}=n;return{data:(await Promise.all(t.map(p=>this.getPullRequestsForRepoBase({repo:p,assigneeLogins:s,updatedBefore:o,authorLogin:i,labelNames:a,isDraft:u,reviewRequestedLogin:l,states:n.states,pageSize:n.pageSize},e,n.includeFromArchivedRepos??!1)))).flatMap(p=>p.data)}}async closePullRequest(n,e={}){let{pullRequest:t}=n,s=`mutation ClosePullRequest($fullPath: ID!, $pullRequestId: String!) {
1147
+ `,variables:{...c,after:s}},e),m=[],h=g.body.data?.project;if(!t&&h?.archived)return{pageInfo:null,data:[]};let y=We(h||{id:"",fullPath:"",webUrl:""});return(h?.mergeRequests?.nodes||[]).forEach(P=>{let q=P.sourceProject?De(P.sourceProject):null;m.push(Ft(P,y,q,this.getIsSelfHosted(e),this.config.baseUrl??e.baseUrl))}),{pageInfo:h?.mergeRequests?.pageInfo,data:k(m,n.states)}}async getPullRequestsForRepo(n,e={}){return this.getPullRequestsForRepoBase(n,e,!1)}async getPullRequestsForRepos(n,e={}){let{repos:t,assigneeLogins:s,updatedBefore:o,authorLogin:i,labelNames:a,isDraft:u,reviewRequestedLogin:l}=n;return{data:(await Promise.all(t.map(d=>this.getPullRequestsForRepoBase({repo:d,assigneeLogins:s,updatedBefore:o,authorLogin:i,labelNames:a,isDraft:u,reviewRequestedLogin:l,states:n.states,pageSize:n.pageSize},e,n.includeFromArchivedRepos??!1)))).flatMap(d=>d.data)}}async closePullRequest(n,e={}){let{pullRequest:t}=n,s=`mutation ClosePullRequest($fullPath: ID!, $pullRequestId: String!) {
1148
1148
  mergeRequestUpdate(input: { projectPath: $fullPath, iid: $pullRequestId, state: CLOSED }) {
1149
1149
  errors,
1150
1150
  mergeRequest {
@@ -1209,18 +1209,18 @@ query getPullRequestsForRepo(
1209
1209
  id
1210
1210
  }
1211
1211
  }
1212
- }`;if(!(await v(this.config,{query:i,variables:{fullPath:`${t.repository.owner.login}/${t.repository.name}`,pullRequestId:t.number.toString(),labelGraphQLIds:o}},e)).body.data?.mergeRequestSetLabels?.mergeRequest?.id)throw new Error("Could not set pull request labels")}async getIssue(n,e={}){let t=kn(n),s=await v(this.config,{query:`
1212
+ }`;if(!(await v(this.config,{query:i,variables:{fullPath:`${t.repository.owner.login}/${t.repository.name}`,pullRequestId:t.number.toString(),labelGraphQLIds:o}},e)).body.data?.mergeRequestSetLabels?.mergeRequest?.id)throw new Error("Could not set pull request labels")}async getIssue(n,e={}){let t=Bn(n),s=await v(this.config,{query:`
1213
1213
  query GetSingleIssue($projectId: ID!, $issueNumber: String!) {
1214
1214
  project(fullPath: $projectId) {
1215
1215
  id
1216
1216
  fullPath
1217
1217
  webUrl
1218
1218
  issue(iid: $issueNumber) {
1219
- ${Gt}
1219
+ ${xt}
1220
1220
  }
1221
1221
  }
1222
1222
  }
1223
- `,variables:{issueNumber:n.number,projectId:t}},e);if(!s.body.data?.project)throw new Error(`Repository ${t} not found`);if(!s.body.data?.project?.issue)throw new Error(`Issue ${n.number} not found`);return{data:xt(s.body.data.project.issue,We(s.body.data.project),this.getIsSelfHosted(e),this.config.baseUrl??e.baseUrl)}}getVariablesForIssues(n){let{updatedBefore:e,authorLogin:t,assigneeLogins:s,labelNames:o}=n||{},i={},a=[],u=[],l=(d,p,c)=>{a.push(`$${d}: ${c}`),u.push(`${d}: $${d}`),i[d]=p};return e&&l("updatedBefore",e,"Time"),t&&l("authorUsername",t,"String"),s&&s.length&&(s.length===1?l("assigneeUsername",s[0],"String"):l("assigneeUsernames",s,"[String!]")),o&&l("labelName",o,"[String]"),{variables:i,variableTypes:a,issueArguments:u}}async getIssuesForRepo(n,e={}){let{cursor:t,repo:s}=n||{},o=_(s),i=Mr(n.states),a=A(n.pageSize,{fallback:re,max:re}),{variables:u,variableTypes:l,issueArguments:d}=this.getVariablesForIssues(n),p={fullPath:o,...u},c=`
1223
+ `,variables:{issueNumber:n.number,projectId:t}},e);if(!s.body.data?.project)throw new Error(`Repository ${t} not found`);if(!s.body.data?.project?.issue)throw new Error(`Issue ${n.number} not found`);return{data:jt(s.body.data.project.issue,We(s.body.data.project),this.getIsSelfHosted(e),this.config.baseUrl??e.baseUrl)}}getVariablesForIssues(n){let{updatedBefore:e,authorLogin:t,assigneeLogins:s,labelNames:o}=n||{},i={},a=[],u=[],l=(p,d,c)=>{a.push(`$${p}: ${c}`),u.push(`${p}: $${p}`),i[p]=d};return e&&l("updatedBefore",e,"Time"),t&&l("authorUsername",t,"String"),s&&s.length&&(s.length===1?l("assigneeUsername",s[0],"String"):l("assigneeUsernames",s,"[String!]")),o&&l("labelName",o,"[String]"),{variables:i,variableTypes:a,issueArguments:u}}async getIssuesForRepo(n,e={}){let{cursor:t,repo:s}=n||{},o=_(s),i=Hr(n.states),a=U(n.pageSize,{fallback:re,max:re}),{variables:u,variableTypes:l,issueArguments:p}=this.getVariablesForIssues(n),d={fullPath:o,...u},c=`
1224
1224
  query GetIssuesFromProject(
1225
1225
  $fullPath: ID!
1226
1226
  $after: String
@@ -1237,10 +1237,10 @@ query GetSingleIssue($projectId: ID!, $issueNumber: String!) {
1237
1237
  ${i}
1238
1238
  sort: UPDATED_DESC
1239
1239
  after: $after
1240
- ${d.length?d.join(" "):""}
1240
+ ${p.length?p.join(" "):""}
1241
1241
  ) {
1242
1242
  nodes {
1243
- ${Gt}
1243
+ ${xt}
1244
1244
  }
1245
1245
  pageInfo {
1246
1246
  endCursor
@@ -1248,7 +1248,7 @@ query GetSingleIssue($projectId: ID!, $issueNumber: String!) {
1248
1248
  }
1249
1249
  }
1250
1250
  }
1251
- }`,g=await v(this.config,{query:c,variables:{...p,after:t}},e),m=[],h=g.body.data?.project,y=We(h||{id:"",fullPath:"",webUrl:""});return(h?.issues?.nodes||[]).forEach(P=>{m.push(xt(P,y,this.getIsSelfHosted(e),this.config.baseUrl??e.baseUrl))}),{pageInfo:h?.issues?.pageInfo??{endCursor:null,hasNextPage:!1},data:m.sort((P,q)=>(P.updatedDate||P.createdDate).getTime()-(q.updatedDate||q.createdDate).getTime())}}async getIssuesForRepos(n,e={}){let{cursor:t}=n||{},s=Mr(n.states),o=A(n.pageSize,{fallback:re,max:re}),i=n.repoIds.map(h=>h.toString().startsWith(be)?h:`${be}${h}`),{variables:a,variableTypes:u,issueArguments:l}=this.getVariablesForIssues(n),d={projectIds:i,...a},p=`
1251
+ }`,g=await v(this.config,{query:c,variables:{...d,after:t}},e),m=[],h=g.body.data?.project,y=We(h||{id:"",fullPath:"",webUrl:""});return(h?.issues?.nodes||[]).forEach(P=>{m.push(jt(P,y,this.getIsSelfHosted(e),this.config.baseUrl??e.baseUrl))}),{pageInfo:h?.issues?.pageInfo??{endCursor:null,hasNextPage:!1},data:m.sort((P,q)=>(P.updatedDate||P.createdDate).getTime()-(q.updatedDate||q.createdDate).getTime())}}async getIssuesForRepos(n,e={}){let{cursor:t}=n||{},s=Hr(n.states),o=U(n.pageSize,{fallback:re,max:re}),i=n.repoIds.map(h=>h.toString().startsWith(pe)?h:`${pe}${h}`),{variables:a,variableTypes:u,issueArguments:l}=this.getVariablesForIssues(n),p={projectIds:i,...a},d=`
1252
1252
  query GetIssuesFromProject(
1253
1253
  $projectIds: [ID!]
1254
1254
  $after: String
@@ -1274,12 +1274,12 @@ query GetSingleIssue($projectId: ID!, $issueNumber: String!) {
1274
1274
  ${l.length?l.join(" "):""}
1275
1275
  ) {
1276
1276
  nodes {
1277
- ${Gt}
1277
+ ${xt}
1278
1278
  }
1279
1279
  }
1280
1280
  }
1281
1281
  }
1282
- }`,c=await v(this.config,{query:p,variables:{...d,after:t}},e),g=[];return(c.body.data?.projects?.nodes||[]).forEach(h=>{if(!n.includeFromArchivedRepos&&h.archived)return;let y=We(h);(h.issues?.nodes||[]).forEach(P=>g.push(xt(P,y,this.getIsSelfHosted(e),this.config.baseUrl??e.baseUrl)))}),{pageInfo:c.body?.data?.projects?.pageInfo??{endCursor:null,hasNextPage:!1},data:g.sort((h,y)=>(h.updatedDate||h.createdDate).getTime()-(y.updatedDate||y.createdDate).getTime())}}async setIssueState(n,e={}){let{issue:t,state:s}=n;if(!t.repository)throw new Error('GitLab requires "repository" for this function.');let o=`mutation SetIssueState($fullPath: ID!, $issueId: String!, $status: IssueStateEvent!) {
1282
+ }`,c=await v(this.config,{query:d,variables:{...p,after:t}},e),g=[];return(c.body.data?.projects?.nodes||[]).forEach(h=>{if(!n.includeFromArchivedRepos&&h.archived)return;let y=We(h);(h.issues?.nodes||[]).forEach(P=>g.push(jt(P,y,this.getIsSelfHosted(e),this.config.baseUrl??e.baseUrl)))}),{pageInfo:c.body?.data?.projects?.pageInfo??{endCursor:null,hasNextPage:!1},data:g.sort((h,y)=>(h.updatedDate||h.createdDate).getTime()-(y.updatedDate||y.createdDate).getTime())}}async getIssuesForCurrentUser(n={},e={}){let t="scope"in n?n.scope??"assigned_to_me":"assigned_to_me",s="assigneeUsername"in n?n.assigneeUsername:void 0,o="page"in n&&n.page?.toString()||"1",i=U("pageSize"in n?n.pageSize:void 0,{fallback:C,max:C}),a=new URL(`${A(this.config,e)}/issues`);a.searchParams.set("scope",t),a.searchParams.set("state","opened"),s&&a.searchParams.set("assignee_username",s),a.searchParams.set("page",o),a.searchParams.set("per_page",i.toString());let u=await this.config.request({url:a.toString(),headers:R(e.token||this.config.token)});return{pageInfo:Ot(u.headers),data:u.body.map(l=>ro(l,this.getIsSelfHosted(e),this.config.baseUrl??e.baseUrl))}}async setIssueState(n,e={}){let{issue:t,state:s}=n;if(!t.repository)throw new Error('GitLab requires "repository" for this function.');let o=`mutation SetIssueState($fullPath: ID!, $issueId: String!, $status: IssueStateEvent!) {
1283
1283
  updateIssue(input: { projectPath: $fullPath, iid: $issueId, stateEvent: $status }) {
1284
1284
  issue {
1285
1285
  id
@@ -1319,7 +1319,7 @@ query getLabelsForRepo(
1319
1319
  webUrl
1320
1320
  milestones(after: $after) {
1321
1321
  nodes {
1322
- ${Qt}
1322
+ ${Mt}
1323
1323
  }
1324
1324
  pageInfo {
1325
1325
  endCursor
@@ -1328,7 +1328,7 @@ query getLabelsForRepo(
1328
1328
  }
1329
1329
  }
1330
1330
  }
1331
- `,variables:{fullPath:`${t}/${s}`,after:o}},e);return{pageInfo:i.body.data?.project?.milestones?.pageInfo??{endCursor:null,hasNextPage:!1},data:i.body.data?.project?.milestones?.nodes?.map(a=>zt(a,i.body.data?.project?.webUrl||""))??[]}}async getLabelsForRepo(n,e={}){let{repo:{namespace:t,name:s},cursor:o}=n,i=await v(this.config,{query:`
1331
+ `,variables:{fullPath:`${t}/${s}`,after:o}},e);return{pageInfo:i.body.data?.project?.milestones?.pageInfo??{endCursor:null,hasNextPage:!1},data:i.body.data?.project?.milestones?.nodes?.map(a=>Jt(a,i.body.data?.project?.webUrl||""))??[]}}async getLabelsForRepo(n,e={}){let{repo:{namespace:t,name:s},cursor:o}=n,i=await v(this.config,{query:`
1332
1332
  query getLabelsForRepo(
1333
1333
  $fullPath: ID!
1334
1334
  $after: String
@@ -1338,7 +1338,7 @@ query getLabelsForRepo(
1338
1338
  ) {
1339
1339
  labels(after: $after) {
1340
1340
  nodes {
1341
- ${Bt}
1341
+ ${Ht}
1342
1342
  }
1343
1343
  pageInfo {
1344
1344
  endCursor
@@ -1347,28 +1347,28 @@ query getLabelsForRepo(
1347
1347
  }
1348
1348
  }
1349
1349
  }
1350
- `,variables:{fullPath:`${t}/${s}`,after:o}},e);return{pageInfo:i.body.data?.project?.labels?.pageInfo??{endCursor:null,hasNextPage:!1},data:i.body.data?.project?.labels?.nodes?.map(Mt)??[]}}async getTreeForRepo(n,e={}){let t=_(n.repo),s=new URL(n.cursor??`${U(this.config,e)}/projects/${encodeURIComponent(t)}/repository/tree`);s.searchParams.set("per_page","10000"),s.searchParams.set("recursive","true"),s.searchParams.set("pagination","keyset"),s.searchParams.set("ref",n.branch);let o=await this.config.request({url:s.toString(),headers:R(e.token||this.config.token)}),i=o.headers.link;return{data:o.body.map(jn),pageInfo:{endCursor:i?i.substring(1,i.indexOf(">")):null,hasNextPage:!!i}}}async getPullRequestForRepo(n,e={}){let t=_(n.repo),o=(await v(this.config,{query:`
1350
+ `,variables:{fullPath:`${t}/${s}`,after:o}},e);return{pageInfo:i.body.data?.project?.labels?.pageInfo??{endCursor:null,hasNextPage:!1},data:i.body.data?.project?.labels?.nodes?.map(Wt)??[]}}async getTreeForRepo(n,e={}){let t=_(n.repo),s=new URL(n.cursor??`${A(this.config,e)}/projects/${encodeURIComponent(t)}/repository/tree`);s.searchParams.set("per_page","10000"),s.searchParams.set("recursive","true"),s.searchParams.set("pagination","keyset"),s.searchParams.set("ref",n.branch);let o=await this.config.request({url:s.toString(),headers:R(e.token||this.config.token)}),i=o.headers.link;return{data:o.body.map(Hn),pageInfo:{endCursor:i?i.substring(1,i.indexOf(">")):null,hasNextPage:!!i}}}async getPullRequestForRepo(n,e={}){let t=_(n.repo),o=(await v(this.config,{query:`
1351
1351
  query getPullRequestForRepo($fullPath: ID!, $iid: String!) {
1352
1352
  project(fullPath: $fullPath) {
1353
1353
  ${Le}
1354
1354
  archived
1355
1355
  mergeRequest(iid: $iid) {
1356
- ${Tt(!1,!0,!0)}
1356
+ ${kt(!1,!0,!0)}
1357
1357
  sourceProject {
1358
1358
  ${Le}
1359
1359
  }
1360
1360
  }
1361
1361
  }
1362
1362
  }
1363
- `,variables:{fullPath:t,iid:n.number.toString()}},e)).body.data?.project,i=o?.mergeRequest;if(!o||!i)return{data:null};let a=De(o),u=i.sourceProject?De(i.sourceProject):null;return{data:_t(i,a,u,this.getIsSelfHosted(e),this.config.baseUrl??e.baseUrl)}}getMergeRequestUrl(n,e,t){let s=_(n);return`${U(this.config,t)}/projects/${encodeURIComponent(s)}/merge_requests/${e}`}async getPullRequestDescription(n,e={}){try{return{data:{description:(await this.config.request({url:this.getMergeRequestUrl(n.repo,n.number,e),headers:R(e.token||this.config.token)})).body?.description??""}}}catch{return{data:{description:null}}}}async setPullRequestDescription(n,e={}){return{data:{description:(await this.config.request({method:"PUT",url:this.getMergeRequestUrl(n.repo,n.number,e),headers:{...R(e.token||this.config.token),"Content-Type":"application/json"},body:JSON.stringify({description:n.description})})).body?.description??n.description}}}async getFileContents(n,e={}){let t=_(n.repo),s=new URL(`${U(this.config,e)}/projects/${encodeURIComponent(t)}/repository/files/${encodeURIComponent(n.path)}/raw`);s.searchParams.set("ref",n.ref);let o=await this.config.request({url:s.toString(),headers:R(e.token||this.config.token)});return{data:new Blob([o.body])}}async getCommentsForPullRequest(n,e={}){let t=_(n.repo),{page:s,perPage:o}=Vn(n.cursor,L),i=new URL(`${U(this.config,e)}/projects/${encodeURIComponent(t)}/merge_requests/${n.pullRequestNumber}/notes`);i.searchParams.set("page",s.toString()),i.searchParams.set("per_page",o.toString()),i.searchParams.set("sort","asc"),i.searchParams.set("order_by","created_at");let a=await this.config.request({url:i.toString(),headers:R(e.token||this.config.token)}),u=this.getIsSelfHosted(e),l=this.config.baseUrl??e.baseUrl,d={namespace:n.repo.namespace,name:n.repo.name,mergeRequestIid:n.pullRequestNumber},p=a.body.filter(m=>!m.system&&!m.position).map(m=>kt(m,u,l,d)),c=!!a.headers["x-next-page"],g=c?Jn({page:s+1,perPage:o}):null;return{data:p,pageInfo:{endCursor:g,hasNextPage:c}}}async getReviewsForPullRequest(n,e={}){let t=_(n.repo),s=this.getIsSelfHosted(e),o=this.config.baseUrl??e.baseUrl,i=R(e.token||this.config.token),a=U(this.config,e),u=encodeURIComponent(t),[l,d]=await Promise.all([this.config.request({url:`${a}/projects/${u}/merge_requests/${n.pullRequestId}/approvals`,headers:i}),this.fetchAllMergeRequestDiscussions(t,n.pullRequestId,e)]),p=(l.body.approved_by??[]).map(m=>m?.user).filter(m=>!!m).map(m=>{let h=zr(m,s,o),y=`approval-${m.id}`;return{author:h,body:"",createdAt:l.body.updated_at?new Date(l.body.updated_at):null,id:y,graphQLId:y,reviewComments:[],url:l.body.web_url??""}}),c={namespace:n.repo.namespace,name:n.repo.name,mergeRequestIid:n.pullRequestId},g=d.filter(m=>m.notes.some(h=>!h.system&&!!h.position)).map(m=>{let h=m.notes.filter(w=>!w.system),f=h.filter(w=>!!w.position)[0];if(!f)return null;let P=h.filter(w=>w.id!==f.id).map(w=>kt(w,s,o,c)),D={...kt(f,s,o,c),diffLines:[],filename:f.position?.new_path??f.position?.old_path??"",line:f.position?.new_line??f.position?.old_line??null,startLine:f.position?.line_range?.start?.new_line??null,side:Xn(f.position),isOutdated:!1,isResolved:!!m.resolved,threadId:m.id,replies:P};return{author:f.author?zr(f.author,s,o):null,body:f.body??"",createdAt:f.created_at?new Date(f.created_at):null,id:m.id,graphQLId:m.id,reviewComments:[D],url:""}}).filter(m=>m!==null);return{data:[...p,...g]}}async getPullRequestDiff(n,e={}){let t=_(n.repo),s=encodeURIComponent(t),o=U(this.config,e);return(await this.fetchAllPagedGitLabREST(`${o}/projects/${s}/merge_requests/${n.pullRequestId}/diffs`,e,{perPage:Mn,maxPages:zn})).map(Zn).join("")}async getMergeBase(n,e={}){let t=_(n.repo),s=new URL(`${U(this.config,e)}/projects/${encodeURIComponent(t)}/repository/merge_base`);s.searchParams.append("refs[]",n.base),s.searchParams.append("refs[]",n.head);let i=(await this.config.request({url:s.toString(),headers:R(e.token||this.config.token)})).body?.id;if(!i)throw new Error("No merge base found between the specified commits.");return{data:i}}async fetchAllMergeRequestDiscussions(n,e,t){let s=U(this.config,t),o=encodeURIComponent(n);return this.fetchAllPagedGitLabREST(`${s}/projects/${o}/merge_requests/${e}/discussions`,t)}async fetchAllPagedGitLabREST(n,e,{perPage:t=L,maxPages:s=50}={}){let o=R(e.token||this.config.token),i=[],a=1;for(;a<=s;){let u=new URL(n);u.searchParams.set("page",a.toString()),u.searchParams.set("per_page",t.toString());let l=await this.config.request({url:u.toString(),headers:o});i.push(...l.body);let d=l.headers["x-next-page"];if(!d)break;let p=parseInt(`${d}`,10);if(Number.isNaN(p)||p<=a)break;a=p}return i}async addCommentToPullRequest(n,e={}){let{pullRequest:t,comment:s}=n;if(!s||s.trim()==="")throw new Error("GitLab requires a comment when adding a comment to a pull request.");let o=`${t.repository.owner.login}/${t.repository.name}`,i=`${U(this.config,e)}/projects/${encodeURIComponent(o)}/merge_requests/${t.number}/notes`;if(!(await this.config.request({method:"POST",url:i,headers:{...R(e.token||this.config.token),"Content-Type":"application/json"},body:JSON.stringify({body:s})})).body?.id)throw new Error("Could not add comment to pull request")}async addInlineCommentToPullRequest(n,e={}){let{pullRequest:t,comment:s,path:o,line:i,side:a="RIGHT",threadId:u}=n;if(!s?.trim())throw new Error("GitLab requires a comment when adding an inline comment to a pull request.");let l=`${t.repository.owner.login}/${t.repository.name}`,d=encodeURIComponent(l),p=U(this.config,e),c={...R(e.token||this.config.token),"Content-Type":"application/json"};if(u){let P=await this.config.request({method:"POST",url:`${p}/projects/${d}/merge_requests/${t.number}/discussions/${encodeURIComponent(u)}/notes`,headers:c,body:JSON.stringify({body:s})});return P.body?.id!=null?Nt(t.repository.owner.login,t.repository.name,t.number,P.body.id):void 0}if(!o?.trim())throw new Error("GitLab requires a file path when adding an inline comment to a pull request.");if(!Number.isInteger(i)||i<1)throw new Error("GitLab requires a positive line number when adding an inline comment to a pull request.");if(a!=="LEFT"&&a!=="RIGHT")throw new Error('GitLab requires side to be either "LEFT" or "RIGHT".');let m=(await this.config.request({url:`${p}/projects/${d}/merge_requests/${t.number}`,headers:R(e.token||this.config.token)})).body?.diff_refs;if(!m?.base_sha||!m?.start_sha||!m?.head_sha)throw new Error("Could not resolve merge request diff refs required to create an inline comment");let h={position_type:"text",base_sha:m.base_sha,start_sha:m.start_sha,head_sha:m.head_sha,new_path:o,old_path:o};a==="RIGHT"?h.new_line=i:h.old_line=i;let f=(await this.config.request({method:"POST",url:`${p}/projects/${d}/merge_requests/${t.number}/discussions`,headers:c,body:JSON.stringify({body:s,position:h})})).body?.notes?.[0]?.id;return f!=null?Nt(t.repository.owner.login,t.repository.name,t.number,f):void 0}getNoteUrl(n,e){if(!n)throw new Error('GitLab requires "commentId" for this function.');let{namespace:t,name:s,mergeRequestIid:o,noteId:i}=Yn(n);return`${U(this.config,e)}/projects/${encodeURIComponent(`${t}/${s}`)}/merge_requests/${o}/notes/${i}`}async deleteNote(n,e){await this.config.request({method:"DELETE",url:this.getNoteUrl(n,e),headers:R(e.token||this.config.token)})}async deleteComment(n,e={}){await this.deleteNote(n.commentId,e)}async deleteInlineComment(n,e={}){await this.deleteNote(n.commentId,e)}async editNote(n,e,t){if(!e?.trim())throw new Error("GitLab requires a body when editing a comment.");if(!(await this.config.request({method:"PUT",url:this.getNoteUrl(n,t),headers:{...R(t.token||this.config.token),"Content-Type":"application/json"},body:JSON.stringify({body:e})})).body?.id)throw new Error("Could not edit comment")}async editComment(n,e={}){await this.editNote(n.commentId,n.body,e)}async editInlineComment(n,e={}){await this.editNote(n.commentId,n.body,e)}async resolveReviewThread(n,e={}){await this.setReviewThreadResolved(n,!0,e)}async unresolveReviewThread(n,e={}){await this.setReviewThreadResolved(n,!1,e)}async setReviewThreadResolved(n,e,t){if(!n.repo||n.pullRequestNumber==null)throw new Error("GitLab requires input.repo and input.pullRequestNumber to locate the discussion to (un)resolve.");if(!n.threadId)throw new Error("GitLab requires input.threadId to (un)resolve a discussion.");let s=_(n.repo),o=new URL(`${U(this.config,t)}/projects/${encodeURIComponent(s)}/merge_requests/${n.pullRequestNumber}/discussions/${encodeURIComponent(n.threadId)}`);o.searchParams.set("resolved",e?"true":"false"),await this.config.request({url:o.toString(),method:"PUT",headers:R(t.token||this.config.token)})}async approvePullRequest(n,e={}){let{pullRequest:t,comment:s}=n,o=`${t.repository.owner.login}/${t.repository.name}`,i=U(this.config,e),a=encodeURIComponent(o),u=R(e.token||this.config.token);await this.config.request({url:`${i}/projects/${a}/merge_requests/${t.number}/approve`,method:"POST",headers:u}),s&&s.trim()!==""&&await this.postMergeRequestNote(o,t.number,s,e)}async commentOnPullRequest(n,e={}){let{pullRequest:t,comment:s}=n;if(!s||s.trim()==="")throw new Error("GitLab requires a comment when commenting on a pull request.");let o=`${t.repository.owner.login}/${t.repository.name}`;await this.postMergeRequestNote(o,t.number,s,e)}async requestPullRequestChanges(n,e={}){let{pullRequest:t,comment:s}=n;if(!s||s.trim()==="")throw new Error("GitLab requires a comment when requesting changes on a pull request.");let o=`${t.repository.owner.login}/${t.repository.name}`;if(!await this.tryRequestChangesMutation(o,t.number,e)){let u=`${U(this.config,e)}/projects/${encodeURIComponent(o)}/merge_requests/${t.number}`,l=R(e.token||this.config.token);(await this.config.request({url:`${u}/approvals`,method:"GET",headers:l})).body?.user_has_approved&&await this.config.request({url:`${u}/unapprove`,method:"POST",headers:l})}await this.postMergeRequestNote(o,t.number,s,e)}async tryRequestChangesMutation(n,e,t){let s=`mutation MergeRequestRequestChanges($fullPath: ID!, $pullRequestId: String!) {
1363
+ `,variables:{fullPath:t,iid:n.number.toString()}},e)).body.data?.project,i=o?.mergeRequest;if(!o||!i)return{data:null};let a=De(o),u=i.sourceProject?De(i.sourceProject):null;return{data:Ft(i,a,u,this.getIsSelfHosted(e),this.config.baseUrl??e.baseUrl)}}getMergeRequestUrl(n,e,t){let s=_(n);return`${A(this.config,t)}/projects/${encodeURIComponent(s)}/merge_requests/${e}`}async getPullRequestDescription(n,e={}){try{return{data:{description:(await this.config.request({url:this.getMergeRequestUrl(n.repo,n.number,e),headers:R(e.token||this.config.token)})).body?.description??""}}}catch{return{data:{description:null}}}}async setPullRequestDescription(n,e={}){return{data:{description:(await this.config.request({method:"PUT",url:this.getMergeRequestUrl(n.repo,n.number,e),headers:{...R(e.token||this.config.token),"Content-Type":"application/json"},body:JSON.stringify({description:n.description})})).body?.description??n.description}}}async getFileContents(n,e={}){let t=_(n.repo),s=new URL(`${A(this.config,e)}/projects/${encodeURIComponent(t)}/repository/files/${encodeURIComponent(n.path)}/raw`);s.searchParams.set("ref",n.ref);let o=await this.config.request({url:s.toString(),headers:R(e.token||this.config.token)});return{data:new Blob([o.body])}}async getCommentsForPullRequest(n,e={}){let t=_(n.repo),{page:s,perPage:o}=eo(n.cursor,C),i=new URL(`${A(this.config,e)}/projects/${encodeURIComponent(t)}/merge_requests/${n.pullRequestNumber}/notes`);i.searchParams.set("page",s.toString()),i.searchParams.set("per_page",o.toString()),i.searchParams.set("sort","asc"),i.searchParams.set("order_by","created_at");let a=await this.config.request({url:i.toString(),headers:R(e.token||this.config.token)}),u=this.getIsSelfHosted(e),l=this.config.baseUrl??e.baseUrl,p={namespace:n.repo.namespace,name:n.repo.name,mergeRequestIid:n.pullRequestNumber},d=a.body.filter(m=>!m.system&&!m.position).map(m=>Qt(m,u,l,p)),c=!!a.headers["x-next-page"],g=c?Yn({page:s+1,perPage:o}):null;return{data:d,pageInfo:{endCursor:g,hasNextPage:c}}}async getReviewsForPullRequest(n,e={}){let t=_(n.repo),s=this.getIsSelfHosted(e),o=this.config.baseUrl??e.baseUrl,i=R(e.token||this.config.token),a=A(this.config,e),u=encodeURIComponent(t),[l,p]=await Promise.all([this.config.request({url:`${a}/projects/${u}/merge_requests/${n.pullRequestId}/approvals`,headers:i}),this.fetchAllMergeRequestDiscussions(t,n.pullRequestId,e)]),d=(l.body.approved_by??[]).map(m=>m?.user).filter(m=>!!m).map(m=>{let h=Wr(m,s,o),y=`approval-${m.id}`;return{author:h,body:"",createdAt:l.body.updated_at?new Date(l.body.updated_at):null,id:y,graphQLId:y,reviewComments:[],url:l.body.web_url??""}}),c={namespace:n.repo.namespace,name:n.repo.name,mergeRequestIid:n.pullRequestId},g=p.filter(m=>m.notes.some(h=>!h.system&&!!h.position)).map(m=>{let h=m.notes.filter(w=>!w.system),f=h.filter(w=>!!w.position)[0];if(!f)return null;let P=h.filter(w=>w.id!==f.id).map(w=>Qt(w,s,o,c)),L={...Qt(f,s,o,c),diffLines:[],filename:f.position?.new_path??f.position?.old_path??"",line:f.position?.new_line??f.position?.old_line??null,startLine:f.position?.line_range?.start?.new_line??null,side:so(f.position),isOutdated:!1,isResolved:!!m.resolved,threadId:m.id,replies:P};return{author:f.author?Wr(f.author,s,o):null,body:f.body??"",createdAt:f.created_at?new Date(f.created_at):null,id:m.id,graphQLId:m.id,reviewComments:[L],url:""}}).filter(m=>m!==null);return{data:[...d,...g]}}async getPullRequestDiff(n,e={}){let t=_(n.repo),s=encodeURIComponent(t),o=A(this.config,e);return(await this.fetchAllPagedGitLabREST(`${o}/projects/${s}/merge_requests/${n.pullRequestId}/diffs`,e,{perPage:Vn,maxPages:Kn})).map(no).join("")}async getMergeBase(n,e={}){let t=_(n.repo),s=new URL(`${A(this.config,e)}/projects/${encodeURIComponent(t)}/repository/merge_base`);s.searchParams.append("refs[]",n.base),s.searchParams.append("refs[]",n.head);let i=(await this.config.request({url:s.toString(),headers:R(e.token||this.config.token)})).body?.id;if(!i)throw new Error("No merge base found between the specified commits.");return{data:i}}async fetchAllMergeRequestDiscussions(n,e,t){let s=A(this.config,t),o=encodeURIComponent(n);return this.fetchAllPagedGitLabREST(`${s}/projects/${o}/merge_requests/${e}/discussions`,t)}async fetchAllPagedGitLabREST(n,e,{perPage:t=C,maxPages:s=50}={}){let o=R(e.token||this.config.token),i=[],a=1;for(;a<=s;){let u=new URL(n);u.searchParams.set("page",a.toString()),u.searchParams.set("per_page",t.toString());let l=await this.config.request({url:u.toString(),headers:o});i.push(...l.body);let p=l.headers["x-next-page"];if(!p)break;let d=parseInt(`${p}`,10);if(Number.isNaN(d)||d<=a)break;a=d}return i}async addCommentToPullRequest(n,e={}){let{pullRequest:t,comment:s}=n;if(!s||s.trim()==="")throw new Error("GitLab requires a comment when adding a comment to a pull request.");let o=`${t.repository.owner.login}/${t.repository.name}`,i=`${A(this.config,e)}/projects/${encodeURIComponent(o)}/merge_requests/${t.number}/notes`;if(!(await this.config.request({method:"POST",url:i,headers:{...R(e.token||this.config.token),"Content-Type":"application/json"},body:JSON.stringify({body:s})})).body?.id)throw new Error("Could not add comment to pull request")}async addInlineCommentToPullRequest(n,e={}){let{pullRequest:t,comment:s,path:o,line:i,side:a="RIGHT",threadId:u}=n;if(!s?.trim())throw new Error("GitLab requires a comment when adding an inline comment to a pull request.");let l=`${t.repository.owner.login}/${t.repository.name}`,p=encodeURIComponent(l),d=A(this.config,e),c={...R(e.token||this.config.token),"Content-Type":"application/json"};if(u){let P=await this.config.request({method:"POST",url:`${d}/projects/${p}/merge_requests/${t.number}/discussions/${encodeURIComponent(u)}/notes`,headers:c,body:JSON.stringify({body:s})});return P.body?.id!=null?zt(t.repository.owner.login,t.repository.name,t.number,P.body.id):void 0}if(!o?.trim())throw new Error("GitLab requires a file path when adding an inline comment to a pull request.");if(!Number.isInteger(i)||i<1)throw new Error("GitLab requires a positive line number when adding an inline comment to a pull request.");if(a!=="LEFT"&&a!=="RIGHT")throw new Error('GitLab requires side to be either "LEFT" or "RIGHT".');let m=(await this.config.request({url:`${d}/projects/${p}/merge_requests/${t.number}`,headers:R(e.token||this.config.token)})).body?.diff_refs;if(!m?.base_sha||!m?.start_sha||!m?.head_sha)throw new Error("Could not resolve merge request diff refs required to create an inline comment");let h={position_type:"text",base_sha:m.base_sha,start_sha:m.start_sha,head_sha:m.head_sha,new_path:o,old_path:o};a==="RIGHT"?h.new_line=i:h.old_line=i;let f=(await this.config.request({method:"POST",url:`${d}/projects/${p}/merge_requests/${t.number}/discussions`,headers:c,body:JSON.stringify({body:s,position:h})})).body?.notes?.[0]?.id;return f!=null?zt(t.repository.owner.login,t.repository.name,t.number,f):void 0}getNoteUrl(n,e){if(!n)throw new Error('GitLab requires "commentId" for this function.');let{namespace:t,name:s,mergeRequestIid:o,noteId:i}=oo(n);return`${A(this.config,e)}/projects/${encodeURIComponent(`${t}/${s}`)}/merge_requests/${o}/notes/${i}`}async deleteNote(n,e){await this.config.request({method:"DELETE",url:this.getNoteUrl(n,e),headers:R(e.token||this.config.token)})}async deleteComment(n,e={}){await this.deleteNote(n.commentId,e)}async deleteInlineComment(n,e={}){await this.deleteNote(n.commentId,e)}async editNote(n,e,t){if(!e?.trim())throw new Error("GitLab requires a body when editing a comment.");if(!(await this.config.request({method:"PUT",url:this.getNoteUrl(n,t),headers:{...R(t.token||this.config.token),"Content-Type":"application/json"},body:JSON.stringify({body:e})})).body?.id)throw new Error("Could not edit comment")}async editComment(n,e={}){await this.editNote(n.commentId,n.body,e)}async editInlineComment(n,e={}){await this.editNote(n.commentId,n.body,e)}async resolveReviewThread(n,e={}){await this.setReviewThreadResolved(n,!0,e)}async unresolveReviewThread(n,e={}){await this.setReviewThreadResolved(n,!1,e)}async setReviewThreadResolved(n,e,t){if(!n.repo||n.pullRequestNumber==null)throw new Error("GitLab requires input.repo and input.pullRequestNumber to locate the discussion to (un)resolve.");if(!n.threadId)throw new Error("GitLab requires input.threadId to (un)resolve a discussion.");let s=_(n.repo),o=new URL(`${A(this.config,t)}/projects/${encodeURIComponent(s)}/merge_requests/${n.pullRequestNumber}/discussions/${encodeURIComponent(n.threadId)}`);o.searchParams.set("resolved",e?"true":"false"),await this.config.request({url:o.toString(),method:"PUT",headers:R(t.token||this.config.token)})}async approvePullRequest(n,e={}){let{pullRequest:t,comment:s}=n,o=`${t.repository.owner.login}/${t.repository.name}`,i=A(this.config,e),a=encodeURIComponent(o),u=R(e.token||this.config.token);await this.config.request({url:`${i}/projects/${a}/merge_requests/${t.number}/approve`,method:"POST",headers:u}),s&&s.trim()!==""&&await this.postMergeRequestNote(o,t.number,s,e)}async commentOnPullRequest(n,e={}){let{pullRequest:t,comment:s}=n;if(!s||s.trim()==="")throw new Error("GitLab requires a comment when commenting on a pull request.");let o=`${t.repository.owner.login}/${t.repository.name}`;await this.postMergeRequestNote(o,t.number,s,e)}async requestPullRequestChanges(n,e={}){let{pullRequest:t,comment:s}=n;if(!s||s.trim()==="")throw new Error("GitLab requires a comment when requesting changes on a pull request.");let o=`${t.repository.owner.login}/${t.repository.name}`;if(!await this.tryRequestChangesMutation(o,t.number,e)){let u=`${A(this.config,e)}/projects/${encodeURIComponent(o)}/merge_requests/${t.number}`,l=R(e.token||this.config.token);(await this.config.request({url:`${u}/approvals`,method:"GET",headers:l})).body?.user_has_approved&&await this.config.request({url:`${u}/unapprove`,method:"POST",headers:l})}await this.postMergeRequestNote(o,t.number,s,e)}async tryRequestChangesMutation(n,e,t){let s=`mutation MergeRequestRequestChanges($fullPath: ID!, $pullRequestId: String!) {
1364
1364
  mergeRequestRequestChanges(input: { projectPath: $fullPath, iid: $pullRequestId }) {
1365
1365
  errors
1366
1366
  mergeRequest {
1367
1367
  id
1368
1368
  }
1369
1369
  }
1370
- }`,o=await v(this.config,{query:s,variables:{fullPath:n,pullRequestId:e.toString()}},t),i=o.body.errors;if(i?.length){if(i.some(Nn))return!1;throw new Error(`Could not request pull request changes: ${$e(i)}`)}let a=o.body.data?.mergeRequestRequestChanges;if(a?.errors&&a.errors.length>0)throw new Error(`Could not request pull request changes: ${a.errors.join(", ")}`);if(!a?.mergeRequest?.id)throw new Error("Could not request pull request changes");return!0}async postMergeRequestNote(n,e,t,s){let o=U(this.config,s),i=encodeURIComponent(n),a=R(s.token||this.config.token);await this.config.request({url:`${o}/projects/${i}/merge_requests/${e}/notes`,method:"POST",headers:{...a,"Content-Type":"application/json"},body:JSON.stringify({body:t})})}};var eo="https://api.atlassian.com/ex/jira",Ve=100,Jr=r=>{if(!r||r.length===0)return"statusCategory != Done";let n=new Set(r),e=n.has("OPEN"),t=n.has("CLOSED");return e&&t?null:t?"statusCategory = Done":"statusCategory != Done"},Ht=["assignee","comment","summary","created","creator","updated","votes","issuetype","status","labels","components","project","fixVersions","description"],Vr="/rest/api/2/search/jql",Kr="/rest/api/2/search",Wt=(r,n,e,t)=>{let s=r.fields.assignee,o=!t,i=(r.fields[n?.Sprint??""]??[]).filter(a=>typeof a=="object");return{id:r.id,commentCount:r.fields.comment.comments.length,number:r.key,title:r.fields.summary,url:e?`${e}/browse/${r.key}`:null,closedDate:null,createdDate:new Date(r.fields.created),author:Ke(r.fields.creator,e,o),updatedDate:new Date(r.fields.updated),assignees:s?[Ke(s,e,o)]:[],description:r.fields.description,repository:null,project:{name:r.fields.project.name,resourceId:t??null,key:r.fields.project.key,namespace:null,id:r.fields.project.id},state:no(r.fields.status),statusTransitions:r.transitions?.map(to)??[],components:r.fields.components?.map(ro)??[],type:r.fields.issuetype.name,upvoteCount:r.fields.votes?.votes||0,labels:r.fields.labels?.map(a=>({color:null,description:null,id:null,name:a}))??[],sprints:i.map(oo),fixVersions:r.fields.fixVersions.map(io)}},to=r=>{let n;switch(r.to.statusCategory.name){case"To Do":n="TO_DO";break;case"In Progress":n="IN_PROGRESS";break;default:n="DONE";break}return{name:r.name,id:r.id,to:{id:r.to.id,name:r.to.name,color:r.to.statusCategory.colorName,category:n}}},ro=r=>({description:r.description??null,id:r.id,name:r.name}),so=(r,n,e)=>e&&r.name?`${n}/secure/ViewProfile.jspa?name=${encodeURIComponent(r.name)}`:`${n}/jira/people/${r.accountId}`,Ke=(r,n,e)=>({id:(e?r.key:r.accountId)??"",name:r.displayName,email:r.emailAddress,avatarUrl:r.avatarUrls["48x48"],username:r.displayName,url:so(r,n,e)}),no=r=>{let n;switch(r.statusCategory.name){case"To Do":n="TO_DO";break;case"In Progress":n="IN_PROGRESS";break;default:n="DONE";break}return{id:r.id,name:r.name,color:r.statusCategory.colorName,category:n}},oo=r=>({id:r.id.toString(),name:r.name,isActive:r.state==="active",startDate:r.startDate?new Date(r.startDate):null,endDate:r.endDate?new Date(r.endDate):null,completedDate:r.completeDate?new Date(r.completeDate):null}),io=r=>({id:r.id,description:r.description,name:r.name,archived:r.archived,released:r.released,releaseDate:r.releaseDate?new Date(r.releaseDate):null}),se=(r,n,e)=>e?`${n.baseUrl||eo}/${e}`:`${n?.baseUrl||r.baseUrl}`,Xe=async(r,n,e={})=>{let{resourceId:t}=n;return(await r.request({url:`${se(r,e,t)}/rest/api/2/field`,headers:R(e.token||r.token)})).body},Ze=async(r,n,e,t={})=>{let{number:s,resourceId:o,fields:i}=n||{},a=await r.request({url:`${se(r,t,o)}/rest/api/2/issue/${s}?fields=${Ht.join(",")}&expand=transitions`,headers:R(t.token||r.token)});return{data:Wt(a.body,i,e,o)}},Ye=async(r,n,e,t={})=>{let{cursor:s,resourceId:o,labelNames:i,fields:a}=n||{},u=["statusCategory != Done",`(creator = currentUser() OR assignee = currentUser()
1371
- OR comment ~ currentUser() OR summary ~ currentUser() OR description ~ currentUser())`];i&&i.forEach(f=>u.push(`labels = "${f}"`));let l=`${u.join(" AND ")} ORDER BY updated DESC`,d=!o,p=d?Kr:Vr,c=new URL(`${se(r,t,o)}${p}`);c.searchParams.set("jql",l),c.searchParams.set("maxResults",Ve.toString()),c.searchParams.set("fields",Ht.join(",")),c.searchParams.set("expand","transitions"),s&&(d?c.searchParams.set("startAt",s):c.searchParams.set("nextPageToken",s));let g=await r.request({url:c.toString(),headers:R(t.token||r.token)}),m=g.body.issues.map(f=>Wt(f,a,e,o)),h=!1,y="";return d?(h=m.length==Ve,y=(parseInt(s??"0",10)+m.length).toString()):(h=!!g.body.nextPageToken,y=g.body.nextPageToken??null),{data:m,pageInfo:{hasNextPage:h,endCursor:y}}},Xr=async(r,n,e,t={})=>{let{cursor:s,resourceId:o,jql:i,fields:a}=n||{},u=A(n?.pageSize,{fallback:Ve,max:Ve}),l=[...Ht],d=a?.Sprint;d&&l.push(d);let p=!o,c=p?Kr:Vr,g=new URL(`${se(r,t,o)}${c}`);g.searchParams.set("jql",i.join(" AND ")),g.searchParams.set("maxResults",u.toString()),g.searchParams.set("fields",l.join(",")),g.searchParams.set("expand","transitions"),s&&(p?g.searchParams.set("startAt",s):g.searchParams.set("nextPageToken",s));let m=await r.request({url:g.toString(),headers:R(t.token||r.token)}),h=m.body.issues.map(P=>Wt(P,a,e,o)),y=!1,f="";if(p){let P=parseInt(s??"0",10),q=typeof m.body.startAt=="number"?m.body.startAt:Number.isNaN(P)?0:P,D=m.body.total;y=typeof D=="number"?q+h.length<D:h.length===u,f=(q+h.length).toString()}else y=!!m.body.nextPageToken,f=m.body.nextPageToken??null;return{data:h,pageInfo:{hasNextPage:y,endCursor:f}}},et=async(r,n,e,t={})=>{let{assigneeLogins:s,authorLogin:o,mentionLogin:i,labelNames:a,cursor:u,projectKey:l,resourceId:d,fields:p}=n||{},c=[`project = "${l}"`],g=Jr(n.states);return g&&c.push(g),o&&c.push(`creator in ("${o}")`),s&&s.length!==0&&c.push(`assignee in ("${s.join('", "')}")`),i&&c.push(`comment ~ "${i}"`),a&&a.forEach(m=>c.push(`labels = "${m}"`)),Xr(r,{resourceId:d,jql:c,cursor:u,fields:p,pageSize:n.pageSize},e,t)},tt=async(r,n,e,t={})=>{let{assigneeLogins:s,authorLogin:o,mentionLogin:i,labelNames:a,cursor:u,projectKeys:l,resourceId:d,fields:p}=n||{},g=["("+l.map(h=>`project = "${h}"`).join(" OR ")+")"],m=Jr(n.states);return m&&g.push(m),o&&g.push(`creator in ("${o}")`),s&&s.length!==0&&g.push(`assignee in ("${s.join('", "')}")`),i&&g.push(`comment ~ "${i}"`),a&&a.forEach(h=>g.push(`labels = "${h}"`)),Xr(r,{resourceId:d,jql:g,fields:p,cursor:u,pageSize:n.pageSize},e,t)},rt=async(r,n,e={})=>{let{issue:t,labels:s}=n;if(!t.project)throw new Error('Jira requires a "project" for this function.');let o={fields:{labels:s.map(i=>i.name)}};await r.request({method:"PUT",url:`${se(r,e,t.project.resourceId??void 0)}/rest/api/2/issue/${t.id}`,body:JSON.stringify(o),headers:{...R(e.token||r.token),"Content-Type":"application/json"}})},st=async(r,n,e={})=>{let{issue:t,components:s}=n;if(!t.project)throw new Error('Jira requires a "project" for this function.');let o={fields:{components:s.map(i=>({id:i.id}))}};await r.request({method:"PUT",url:`${se(r,e,t.project.resourceId??void 0)}/rest/api/2/issue/${t.id}`,body:JSON.stringify(o),headers:{...R(e.token||r.token),"Content-Type":"application/json"}})},nt=async(r,n,e={})=>{let{issue:t,status:s}=n;if(!t.project)throw new Error('Jira requires a "project" for this function.');if(!s.id)throw new Error('Jira requires a status "id" for this function.');let o={transition:{id:s.id}};await r.request({method:"POST",url:`${se(r,e,t.project.resourceId??void 0)}/rest/api/2/issue/${t.id}/transitions`,body:JSON.stringify(o),headers:{...R(e.token||r.token),"Content-Type":"application/json"}})},ot=async(r,n,e={})=>{let{resourceId:t,projectIdOrKey:s}=n,o=new URL(`${se(r,e,t)}/rest/api/2/project/${s}/components`);return{data:(await r.request({url:o.toString(),headers:R(e.token||r.token)})).body}};var Ae="https://api.atlassian.com/ex/jira",Jt=100,Pe=class extends j{constructor(){super(...arguments);this._resourceUrlCache={};this._issueFieldsCache={}}async getIssueFieldsForResource(e,t={}){if(!this._issueFieldsCache[e.resourceId]){let s=await Xe(this.config,e,t);this._issueFieldsCache[e.resourceId]=s.reduce((o,i)=>({...o,[i.name]:i.id}),{})}return this._issueFieldsCache[e.resourceId]??null}async getResourceUrl(e,t={}){let s=t.token||this.config.token;if(!s)return null;let o=this._resourceUrlCache[s];return o?o[e.resourceId]??null:(await this.getJiraResourcesForCurrentUser(t),this._resourceUrlCache[s]?.[e.resourceId]??null)}async getCurrentUserForResource(e,t={}){let s=await this.getResourceUrl({resourceId:e.resourceId},t),o=await this.config.request({url:`${t.baseUrl||Ae}/${e.resourceId}/rest/api/2/myself`,headers:R(t.token||this.config.token)});return{data:{name:o.body.displayName,email:o.body.emailAddress,avatarUrl:o.body.avatarUrls["48x48"],id:o.body.accountId,username:o.body.displayName,url:s?`${s}/jira/people/${o.body.accountId}`:null}}}async getJiraResourcesForCurrentUser(e={}){let t=await this.config.request({url:`${e.baseUrl||"https://api.atlassian.com/"}/oauth/token/accessible-resources`,headers:R(e.token||this.config.token)}),s=e.token||this.config.token,o=s?this._resourceUrlCache[s]||{}:void 0,i=t.body.map(a=>(o&&(o[a.id]=a.url),{avatarUrl:a.avatarUrl,id:a.id,name:a.name,url:a.url}));return s&&(this._resourceUrlCache[s]=o),{data:i}}async getJiraProjectsForResource(e,t={}){let s=new URL(`${t.baseUrl||Ae}/${e.resourceId}/rest/api/2/project/search`);s.searchParams.set("maxResults",Jt.toString()),e.cursor&&s.searchParams.set("startAt",e.cursor);let o=await this.config.request({url:s.toString(),headers:R(t.token||this.config.token)});return{pageInfo:{hasNextPage:o.body.values.length!==0,endCursor:(o.body.startAt+o.body.values.length).toString()},metadata:me("complete"),data:o.body.values.map(i=>({id:i.id,key:i.key,name:i.name,resourceId:e.resourceId}))}}async getJiraProjectsForResources(e,t={}){let{successes:s,metadata:o}=await J(e.resourceIds,{run:a=>or(u=>this.getJiraProjectsForResource({resourceId:a,cursor:u},t)),failureScope:a=>({providerId:"jira",resourceId:a})}),i=[];return s.forEach(({result:a})=>{i.push(...a)}),{data:i,metadata:o}}async getAccountsForJiraProject(e,t={}){let{resourceId:s,projectKey:o,cursor:i}=e,a=await this.getResourceUrl({resourceId:s},t),u=new URL(`${t.baseUrl||Ae}/${s}/rest/api/2/user/assignable/search`);u.searchParams.set("maxResults",Jt.toString()),i&&u.searchParams.set("startAt",i),u.searchParams.set("project",o);let l=await this.config.request({url:u.toString(),headers:R(t.token||this.config.token)});return{pageInfo:{hasNextPage:l.body.length!==0,endCursor:((i?parseInt(i):0)+l.body.length).toString()},metadata:me("complete"),data:l.body.filter(d=>d.accountType!=="app"&&d.active).map(d=>Ke(d,a,!1))}}async getComponentsForJiraProject(e,t={}){return await ot(this.config,e,t)}async getIssue(e,t={}){let s=await this.getIssueFieldsForResource({resourceId:e.resourceId},t),o=await this.getResourceUrl({resourceId:e.resourceId},t);return await Ze(this.config,{...e,fields:s},o,t)}async getIssuesForProject(e,t={}){let s=await this.getIssueFieldsForResource({resourceId:e.resourceId},t),o=await this.getResourceUrl({resourceId:e.resourceId},t);return await et(this.config,{...e,fields:s},o,t)}async getIssuesForProjects(e,t={}){let s=await this.getIssueFieldsForResource({resourceId:e.resourceId},t),o=await this.getResourceUrl({resourceId:e.resourceId},t);return await tt(this.config,{...e,fields:s},o,t)}async getIssuesForResourceForCurrentUser(e,t={}){let s=await this.getIssueFieldsForResource({resourceId:e.resourceId},t),o=await this.getResourceUrl({resourceId:e.resourceId},t);return await Ye(this.config,{...e,fields:s},o,t)}async setIssueStatus(e,t={}){await nt(this.config,e,t)}async setIssueAssignee(e,t={}){let{issue:s,assignee:o}=e;if(!s.project)throw new Error('Jira Cloud requires a "project" for this function.');if(!s.project.resourceId)throw new Error('Jira Cloud requires a project "resourceId" for this function.');let i={accountId:o?.id};await this.config.request({method:"PUT",url:`${t.baseUrl||Ae}/${s.project.resourceId}/rest/api/2/issue/${s.id}/assignee`,body:JSON.stringify(i),headers:{...R(t.token||this.config.token),"Content-Type":"application/json"}})}async setIssueComponents(e,t={}){await st(this.config,e,t)}async setIssueLabels(e,t={}){await rt(this.config,e,t)}async getLabelsForResource(e,t={}){let{resourceId:s,cursor:o}=e,i=new URL(`${t.baseUrl||Ae}/${s}/rest/api/2/label`);i.searchParams.set("maxResults",Jt.toString()),o&&i.searchParams.set("startAt",o);let a=await this.config.request({url:i.toString(),headers:R(t.token||this.config.token)});return{pageInfo:{hasNextPage:!a.body.isLast,endCursor:(a.body.startAt+a.body.values.length).toString()},data:a.body.values.map(u=>({color:null,description:null,id:null,name:u}))}}};var we=class extends N{constructor(){super(...arguments);this._issueFieldsCache={}}async getIssueFieldsForResource(e={}){let t=e?.baseUrl||this.config.baseUrl||"";if(!this._issueFieldsCache[t]){let s=await Xe(this.config,{},e);this._issueFieldsCache[t]=s.reduce((o,i)=>({...o,[i.name]:i.id}),{})}return this._issueFieldsCache[t]??null}async getCurrentUser(e={}){let t=await this.config.request({url:`${e?.baseUrl||this.config.baseUrl}/rest/api/2/myself`,headers:R(e?.token||this.config.token)});return{data:{name:t.body.displayName,email:t.body.emailAddress,avatarUrl:t.body.avatarUrls["48x48"],id:t.body.key,username:t.body.displayName,url:null}}}async getJiraProjects(e={}){return{data:(await this.config.request({url:`${e?.baseUrl||this.config.baseUrl}/rest/api/2/project`,headers:R(e?.token||this.config.token)})).body.map(s=>({id:s.id,name:s.name}))}}async getIssue(e,t={}){let s=e.resourceUrl||t.baseUrl||this.config.baseUrl;if(!s)throw new Error('Jira Server requires a "resourceUrl" or "baseUrl" for this function.');let o=await this.getIssueFieldsForResource(t);return await Ze(this.config,{...e,fields:o},s,t)}async getIssuesForProject(e,t={}){let s=e.resourceUrl||t.baseUrl||this.config.baseUrl;if(!s)throw new Error('Jira Server requires a "resourceUrl" or "baseUrl" for this function.');let o=await this.getIssueFieldsForResource(t);return await et(this.config,{...e,fields:o},s,t)}async getIssuesForProjects(e,t={}){let s=e.resourceUrl||t.baseUrl||this.config.baseUrl;if(!s)throw new Error('Jira Server requires a "resourceUrl" or "baseUrl" for this function.');let o=await this.getIssueFieldsForResource(t);return await tt(this.config,{...e,fields:o},s,t)}async getIssuesForResourceForCurrentUser(e,t={}){let s=e.resourceUrl||t.baseUrl||this.config.baseUrl;if(!s)throw new Error('Jira Server requires a "resourceUrl" or "baseUrl" for this function.');let o=await this.getIssueFieldsForResource(t);return await Ye(this.config,{...e,fields:o},s,t)}async setIssueStatus(e,t={}){await nt(this.config,e,t)}async setIssueLabels(e,t={}){await rt(this.config,e,t)}async setIssueComponents(e,t={}){await st(this.config,e,t)}async getLabels(e={}){return{data:(await this.config.request({url:`${e?.baseUrl||this.config.baseUrl}/rest/api/2/jql/autocompletedata/suggestions?fieldName=labels`,headers:R(e.token||this.config.token)})).body.results.map(({displayName:s})=>({color:null,description:null,id:null,name:s}))}}async getComponentsForJiraProject(e,t={}){return await ot(this.config,e,t)}};var H="https://api.trello.com",Zr=1e3,W=(r,n)=>({...R(n),Authorization:`OAuth oauth_consumer_key="${r}", oauth_token="${n}"`}),ao=r=>({id:r.id,username:r.username,url:r.url,name:r.fullName,email:r.email,avatarUrl:r.avatarUrl}),uo=(r,n)=>{let e=new Date(1e3*parseInt(r.id.substring(0,8),16));return{id:r.id,commentCount:r.badges.comments,number:r.idShort.toString(),title:r.name,url:r.url,closedDate:null,createdDate:new Date(e.toISOString()),author:null,updatedDate:new Date(r.dateLastActivity),assignees:r.members.map(t=>({id:t.id,username:t.username,name:t.fullName,email:null,avatarUrl:t.avatarUrl,url:null})),description:null,state:n[r.idList??""]?{id:r.idList,name:n[r.idList].name,color:null}:null,type:null,repository:null,upvoteCount:r.badges.votes,labels:r.labels.map(t=>({color:t.color,description:null,id:t.id,name:t.name}))}},Se=class extends j{async getCurrentUser(n,e={}){let t=await this.config.request({url:`${e.baseUrl||H}/1/members/me`,headers:W(n.appKey,e.token||this.config.token)});return{data:{name:t.body.fullName,email:t.body.email,avatarUrl:t.body.avatarHash?`https://trello-members.s3.amazonaws.com/${t.body.id}/${t.body.avatarHash}/50.png`:null,id:t.body.id,username:t.body.username,url:t.body.url}}}async getBoardsForCurrentUser(n,e={}){return{data:(await this.config.request({url:`${e.baseUrl||H}/1/members/me/boards?fields=name&filter=open`,headers:W(n.appKey,e.token||this.config.token)})).body.map(s=>({id:s.id,name:s.name}))}}async getListsForTrelloBoard(n,e={}){let{appKey:t,boardId:s}=n;return{data:(await this.config.request({url:`${e.baseUrl||H}/1/boards/${s}/lists`,headers:W(t,e.token||this.config.token)})).body}}async getAccountForId(n,e={}){let{appKey:t,memberId:s}=n,o=await this.config.request({url:`${e.baseUrl||H}/1/members/${s}`,headers:W(t,e.token||this.config.token)});return{data:ao(o.body)}}async getAccountsForTrelloBoard(n,e={}){let{appKey:t,boardId:s}=n;return{data:(await this.config.request({url:`${e.baseUrl||H}/1/boards/${s}/members`,headers:W(t,e.token||this.config.token)})).body.map(i=>({id:i.id,name:i.fullName,username:i.username,email:null,avatarUrl:null,url:null}))}}async getIssuesForBoard(n,e={}){let t=["-is:archived","sort:edited"],{appKey:s,boardId:o,filterText:i,assigneeLogins:a,labelNamesOrColors:u,trelloBoardListsById:l}=n||{};a&&t.push("@me"),u&&u.forEach(g=>t.push(`label:"${g}"`));let d=`${i?`${i}`:""}${t.join(" ")} board:${o}`,p=await this.config.request({url:`${e.baseUrl||H}/1/search?query=${d}&cards_limit=${Zr}&card_members=true`,headers:W(s,e.token||this.config.token)}),c=p.body.cards.length>=Zr?"unknown":"complete";return{data:p.body.cards.map(g=>uo(g,l||{})),metadata:me(c)}}async updateIssue(n,e,t,s){return await this.config.request({method:"PUT",url:`${s.baseUrl||H}/1/cards/${e.id}?${t}`,headers:W(n,s.token||this.config.token)})}async setIssueStatus(n,e={}){let{appKey:t,issue:s,status:o}=n;if(!o.id)throw new Error('Trello requires a status "id" for this function.');let i=`idList=${o.id}`;if(!(await this.updateIssue(t,s,i,e)).body.id)throw new Error("Could not set issue status")}async setIssueAssignees(n,e={}){let{appKey:t,issue:s,assignees:o}=n,i=o.map(l=>l.id),a=`idMembers=${encodeURIComponent(i.join(","))}`;if(!(await this.updateIssue(t,s,a,e)).body.id)throw new Error("Could not set issue status")}async setIssueLabels(n,e={}){let{appKey:t,issue:s,labels:o}=n,i=o.map(u=>u.id).join(",");if(!(await this.config.request({method:"PUT",url:`${e.baseUrl||H}/1/cards/${s.id}?idLabels=${encodeURIComponent(i)}`,headers:W(t,e.token||this.config.token)})).body.id)throw new Error("Could not set issue status")}async setIssueArchived(n,e={}){let{appKey:t,issue:s,archived:o}=n;if(!(await this.config.request({method:"PUT",url:`${e.baseUrl||H}/1/cards/${s.id}?closed=${o}`,headers:W(t,e.token||this.config.token)})).body.id)throw new Error("Could not update issue archived status")}async archiveIssue(n,e={}){await this.setIssueArchived({...n,archived:!0},e)}async unArchiveIssue(n,e={}){await this.setIssueArchived({...n,archived:!1},e)}async getLabelsForBoard(n,e={}){let{appKey:t,boardId:s}=n;return{data:(await this.config.request({url:`${e.baseUrl||H}/1/boards/${s}/labels`,headers:W(t,e.token||this.config.token)})).body.map(i=>({color:i.color,description:null,id:i.id,name:i.name}))}}};var Kt=100,it=class{constructor(){this.set=new Set;this.arr=[]}push(...n){let e=n.filter(t=>!this.set.has(t.id));this.arr.push(...e),e.forEach(t=>this.set.add(t.id))}get length(){return this.arr.length}get items(){return this.arr}},Z=async(r,n,e,t)=>{let s=n.token||r.token;if(!s)throw new Error("Linear API key is required");let o=await r.request({url:"https://api.linear.app/graphql",method:"POST",headers:{Authorization:s,"Content-Type":"application/json"},body:JSON.stringify({query:e,variables:t})});if(o.status>=400)throw new Error(`Linear API request failed: ${o.status} ${o.statusText}`);let i=o.body;if(i.errors)throw new Error(`Linear GraphQL errors: ${i.errors.map(a=>a.message).join(", ")}`);return i.data},Vt=r=>r?r instanceof Date?r:new Date(r):null,lo=`
1370
+ }`,o=await v(this.config,{query:s,variables:{fullPath:n,pullRequestId:e.toString()}},t),i=o.body.errors;if(i?.length){if(i.some(zn))return!1;throw new Error(`Could not request pull request changes: ${$e(i)}`)}let a=o.body.data?.mergeRequestRequestChanges;if(a?.errors&&a.errors.length>0)throw new Error(`Could not request pull request changes: ${a.errors.join(", ")}`);if(!a?.mergeRequest?.id)throw new Error("Could not request pull request changes");return!0}async postMergeRequestNote(n,e,t,s){let o=A(this.config,s),i=encodeURIComponent(n),a=R(s.token||this.config.token);await this.config.request({url:`${o}/projects/${i}/merge_requests/${e}/notes`,method:"POST",headers:{...a,"Content-Type":"application/json"},body:JSON.stringify({body:t})})}};var io="https://api.atlassian.com/ex/jira",Xe=100,Zr=r=>{if(!r||r.length===0)return"statusCategory != Done";let n=new Set(r),e=n.has("OPEN"),t=n.has("CLOSED");return e&&t?null:t?"statusCategory = Done":"statusCategory != Done"},Vt=["assignee","comment","summary","created","creator","updated","votes","issuetype","status","labels","components","project","fixVersions","description"],Yr="/rest/api/2/search/jql",es="/rest/api/2/search",Kt=(r,n,e,t)=>{let s=r.fields.assignee,o=!t,i=(r.fields[n?.Sprint??""]??[]).filter(a=>typeof a=="object");return{id:r.id,commentCount:r.fields.comment.comments.length,number:r.key,title:r.fields.summary,url:e?`${e}/browse/${r.key}`:null,closedDate:null,createdDate:new Date(r.fields.created),author:Ze(r.fields.creator,e,o),updatedDate:new Date(r.fields.updated),assignees:s?[Ze(s,e,o)]:[],description:r.fields.description,repository:null,project:{name:r.fields.project.name,resourceId:t??null,key:r.fields.project.key,namespace:null,id:r.fields.project.id},state:po(r.fields.status),statusTransitions:r.transitions?.map(ao)??[],components:r.fields.components?.map(uo)??[],type:r.fields.issuetype.name,upvoteCount:r.fields.votes?.votes||0,labels:r.fields.labels?.map(a=>({color:null,description:null,id:null,name:a}))??[],sprints:i.map(co),fixVersions:r.fields.fixVersions.map(mo)}},ao=r=>{let n;switch(r.to.statusCategory.name){case"To Do":n="TO_DO";break;case"In Progress":n="IN_PROGRESS";break;default:n="DONE";break}return{name:r.name,id:r.id,to:{id:r.to.id,name:r.to.name,color:r.to.statusCategory.colorName,category:n}}},uo=r=>({description:r.description??null,id:r.id,name:r.name}),lo=(r,n,e)=>e&&r.name?`${n}/secure/ViewProfile.jspa?name=${encodeURIComponent(r.name)}`:`${n}/jira/people/${r.accountId}`,Ze=(r,n,e)=>({id:(e?r.key:r.accountId)??"",name:r.displayName,email:r.emailAddress,avatarUrl:r.avatarUrls["48x48"],username:r.displayName,url:lo(r,n,e)}),po=r=>{let n;switch(r.statusCategory.name){case"To Do":n="TO_DO";break;case"In Progress":n="IN_PROGRESS";break;default:n="DONE";break}return{id:r.id,name:r.name,color:r.statusCategory.colorName,category:n}},co=r=>({id:r.id.toString(),name:r.name,isActive:r.state==="active",startDate:r.startDate?new Date(r.startDate):null,endDate:r.endDate?new Date(r.endDate):null,completedDate:r.completeDate?new Date(r.completeDate):null}),mo=r=>({id:r.id,description:r.description,name:r.name,archived:r.archived,released:r.released,releaseDate:r.releaseDate?new Date(r.releaseDate):null}),se=(r,n,e)=>e?`${n.baseUrl||io}/${e}`:`${n?.baseUrl||r.baseUrl}`,Ye=async(r,n,e={})=>{let{resourceId:t}=n;return(await r.request({url:`${se(r,e,t)}/rest/api/2/field`,headers:R(e.token||r.token)})).body},et=async(r,n,e,t={})=>{let{number:s,resourceId:o,fields:i}=n||{},a=await r.request({url:`${se(r,t,o)}/rest/api/2/issue/${s}?fields=${Vt.join(",")}&expand=transitions`,headers:R(t.token||r.token)});return{data:Kt(a.body,i,e,o)}},tt=async(r,n,e,t={})=>{let{cursor:s,resourceId:o,labelNames:i,fields:a}=n||{},u=["statusCategory != Done",`(creator = currentUser() OR assignee = currentUser()
1371
+ OR comment ~ currentUser() OR summary ~ currentUser() OR description ~ currentUser())`];i&&i.forEach(f=>u.push(`labels = "${f}"`));let l=`${u.join(" AND ")} ORDER BY updated DESC`,p=!o,d=p?es:Yr,c=new URL(`${se(r,t,o)}${d}`);c.searchParams.set("jql",l),c.searchParams.set("maxResults",Xe.toString()),c.searchParams.set("fields",Vt.join(",")),c.searchParams.set("expand","transitions"),s&&(p?c.searchParams.set("startAt",s):c.searchParams.set("nextPageToken",s));let g=await r.request({url:c.toString(),headers:R(t.token||r.token)}),m=g.body.issues.map(f=>Kt(f,a,e,o)),h=!1,y="";return p?(h=m.length==Xe,y=(parseInt(s??"0",10)+m.length).toString()):(h=!!g.body.nextPageToken,y=g.body.nextPageToken??null),{data:m,pageInfo:{hasNextPage:h,endCursor:y}}},ts=async(r,n,e,t={})=>{let{cursor:s,resourceId:o,jql:i,fields:a}=n||{},u=U(n?.pageSize,{fallback:Xe,max:Xe}),l=[...Vt],p=a?.Sprint;p&&l.push(p);let d=!o,c=d?es:Yr,g=new URL(`${se(r,t,o)}${c}`);g.searchParams.set("jql",i.join(" AND ")),g.searchParams.set("maxResults",u.toString()),g.searchParams.set("fields",l.join(",")),g.searchParams.set("expand","transitions"),s&&(d?g.searchParams.set("startAt",s):g.searchParams.set("nextPageToken",s));let m=await r.request({url:g.toString(),headers:R(t.token||r.token)}),h=m.body.issues.map(P=>Kt(P,a,e,o)),y=!1,f="";if(d){let P=parseInt(s??"0",10),q=typeof m.body.startAt=="number"?m.body.startAt:Number.isNaN(P)?0:P,L=m.body.total;y=typeof L=="number"?q+h.length<L:h.length===u,f=(q+h.length).toString()}else y=!!m.body.nextPageToken,f=m.body.nextPageToken??null;return{data:h,pageInfo:{hasNextPage:y,endCursor:f}}},rt=async(r,n,e,t={})=>{let{assigneeLogins:s,authorLogin:o,mentionLogin:i,labelNames:a,cursor:u,projectKey:l,resourceId:p,fields:d}=n||{},c=[`project = "${l}"`],g=Zr(n.states);return g&&c.push(g),o&&c.push(`creator in ("${o}")`),s&&s.length!==0&&c.push(`assignee in ("${s.join('", "')}")`),i&&c.push(`comment ~ "${i}"`),a&&a.forEach(m=>c.push(`labels = "${m}"`)),ts(r,{resourceId:p,jql:c,cursor:u,fields:d,pageSize:n.pageSize},e,t)},st=async(r,n,e,t={})=>{let{assigneeLogins:s,authorLogin:o,mentionLogin:i,labelNames:a,cursor:u,projectKeys:l,resourceId:p,fields:d}=n||{},g=["("+l.map(h=>`project = "${h}"`).join(" OR ")+")"],m=Zr(n.states);return m&&g.push(m),o&&g.push(`creator in ("${o}")`),s&&s.length!==0&&g.push(`assignee in ("${s.join('", "')}")`),i&&g.push(`comment ~ "${i}"`),a&&a.forEach(h=>g.push(`labels = "${h}"`)),ts(r,{resourceId:p,jql:g,fields:d,cursor:u,pageSize:n.pageSize},e,t)},nt=async(r,n,e={})=>{let{issue:t,labels:s}=n;if(!t.project)throw new Error('Jira requires a "project" for this function.');let o={fields:{labels:s.map(i=>i.name)}};await r.request({method:"PUT",url:`${se(r,e,t.project.resourceId??void 0)}/rest/api/2/issue/${t.id}`,body:JSON.stringify(o),headers:{...R(e.token||r.token),"Content-Type":"application/json"}})},ot=async(r,n,e={})=>{let{issue:t,components:s}=n;if(!t.project)throw new Error('Jira requires a "project" for this function.');let o={fields:{components:s.map(i=>({id:i.id}))}};await r.request({method:"PUT",url:`${se(r,e,t.project.resourceId??void 0)}/rest/api/2/issue/${t.id}`,body:JSON.stringify(o),headers:{...R(e.token||r.token),"Content-Type":"application/json"}})},it=async(r,n,e={})=>{let{issue:t,status:s}=n;if(!t.project)throw new Error('Jira requires a "project" for this function.');if(!s.id)throw new Error('Jira requires a status "id" for this function.');let o={transition:{id:s.id}};await r.request({method:"POST",url:`${se(r,e,t.project.resourceId??void 0)}/rest/api/2/issue/${t.id}/transitions`,body:JSON.stringify(o),headers:{...R(e.token||r.token),"Content-Type":"application/json"}})},at=async(r,n,e={})=>{let{resourceId:t,projectIdOrKey:s}=n,o=new URL(`${se(r,e,t)}/rest/api/2/project/${s}/components`);return{data:(await r.request({url:o.toString(),headers:R(e.token||r.token)})).body}};var Ue="https://api.atlassian.com/ex/jira",Xt=100,go=5,Pe=class extends j{constructor(){super(...arguments);this._resourceUrlCache={};this._issueFieldsCache={}}async getIssueFieldsForResource(e,t={}){if(!this._issueFieldsCache[e.resourceId]){let s=await Ye(this.config,e,t);this._issueFieldsCache[e.resourceId]=s.reduce((o,i)=>({...o,[i.name]:i.id}),{})}return this._issueFieldsCache[e.resourceId]??null}async getResourceUrl(e,t={}){let s=t.token||this.config.token;if(!s)return null;let o=this._resourceUrlCache[s];return o?o[e.resourceId]??null:(await this.getJiraResourcesForCurrentUser(t),this._resourceUrlCache[s]?.[e.resourceId]??null)}async getCurrentUserForResource(e,t={}){let s=await this.getResourceUrl({resourceId:e.resourceId},t),o=await this.config.request({url:`${t.baseUrl||Ue}/${e.resourceId}/rest/api/2/myself`,headers:R(t.token||this.config.token)});return{data:{name:o.body.displayName,email:o.body.emailAddress,avatarUrl:o.body.avatarUrls["48x48"],id:o.body.accountId,username:o.body.displayName,url:s?`${s}/jira/people/${o.body.accountId}`:null}}}async getJiraResourcesForCurrentUser(e={}){let t=await this.config.request({url:`${e.baseUrl||"https://api.atlassian.com/"}/oauth/token/accessible-resources`,headers:R(e.token||this.config.token)}),s=e.token||this.config.token,o=s?this._resourceUrlCache[s]||{}:void 0,i=t.body.map(a=>(o&&(o[a.id]=a.url),{avatarUrl:a.avatarUrl,id:a.id,name:a.name,url:a.url}));return s&&(this._resourceUrlCache[s]=o),{data:i}}async getJiraProjectsForResource(e,t={}){let s=new URL(`${t.baseUrl||Ue}/${e.resourceId}/rest/api/2/project/search`);s.searchParams.set("maxResults",Xt.toString()),e.cursor&&s.searchParams.set("startAt",e.cursor);let o=await this.config.request({url:s.toString(),headers:R(t.token||this.config.token)});return{pageInfo:{hasNextPage:o.body.values.length!==0,endCursor:(o.body.startAt+o.body.values.length).toString()},metadata:ge("complete"),data:o.body.values.map(i=>({id:i.id,key:i.key,name:i.name,resourceId:e.resourceId}))}}async getJiraProjectsForResources(e,t={}){let{successes:s,metadata:o}=await J(e.resourceIds,{run:a=>ur(u=>this.getJiraProjectsForResource({resourceId:a,cursor:u},t)),failureScope:a=>({providerId:"jira",resourceId:a}),concurrency:go}),i=[];return s.forEach(({result:a})=>{i.push(...a)}),{data:i,metadata:o}}async getAccountsForJiraProject(e,t={}){let{resourceId:s,projectKey:o,cursor:i}=e,a=await this.getResourceUrl({resourceId:s},t),u=new URL(`${t.baseUrl||Ue}/${s}/rest/api/2/user/assignable/search`);u.searchParams.set("maxResults",Xt.toString()),i&&u.searchParams.set("startAt",i),u.searchParams.set("project",o);let l=await this.config.request({url:u.toString(),headers:R(t.token||this.config.token)});return{pageInfo:{hasNextPage:l.body.length!==0,endCursor:((i?parseInt(i):0)+l.body.length).toString()},metadata:ge("complete"),data:l.body.filter(p=>p.accountType!=="app"&&p.active).map(p=>Ze(p,a,!1))}}async getComponentsForJiraProject(e,t={}){return await at(this.config,e,t)}async getIssue(e,t={}){let s=await this.getIssueFieldsForResource({resourceId:e.resourceId},t),o=await this.getResourceUrl({resourceId:e.resourceId},t);return await et(this.config,{...e,fields:s},o,t)}async getIssuesForProject(e,t={}){let s=await this.getIssueFieldsForResource({resourceId:e.resourceId},t),o=await this.getResourceUrl({resourceId:e.resourceId},t);return await rt(this.config,{...e,fields:s},o,t)}async getIssuesForProjects(e,t={}){let s=await this.getIssueFieldsForResource({resourceId:e.resourceId},t),o=await this.getResourceUrl({resourceId:e.resourceId},t);return await st(this.config,{...e,fields:s},o,t)}async getIssuesForResourceForCurrentUser(e,t={}){let s=await this.getIssueFieldsForResource({resourceId:e.resourceId},t),o=await this.getResourceUrl({resourceId:e.resourceId},t);return await tt(this.config,{...e,fields:s},o,t)}async setIssueStatus(e,t={}){await it(this.config,e,t)}async setIssueAssignee(e,t={}){let{issue:s,assignee:o}=e;if(!s.project)throw new Error('Jira Cloud requires a "project" for this function.');if(!s.project.resourceId)throw new Error('Jira Cloud requires a project "resourceId" for this function.');let i={accountId:o?.id};await this.config.request({method:"PUT",url:`${t.baseUrl||Ue}/${s.project.resourceId}/rest/api/2/issue/${s.id}/assignee`,body:JSON.stringify(i),headers:{...R(t.token||this.config.token),"Content-Type":"application/json"}})}async setIssueComponents(e,t={}){await ot(this.config,e,t)}async setIssueLabels(e,t={}){await nt(this.config,e,t)}async getLabelsForResource(e,t={}){let{resourceId:s,cursor:o}=e,i=new URL(`${t.baseUrl||Ue}/${s}/rest/api/2/label`);i.searchParams.set("maxResults",Xt.toString()),o&&i.searchParams.set("startAt",o);let a=await this.config.request({url:i.toString(),headers:R(t.token||this.config.token)});return{pageInfo:{hasNextPage:!a.body.isLast,endCursor:(a.body.startAt+a.body.values.length).toString()},data:a.body.values.map(u=>({color:null,description:null,id:null,name:u}))}}};var we=class extends N{constructor(){super(...arguments);this._issueFieldsCache={}}async getIssueFieldsForResource(e={}){let t=e?.baseUrl||this.config.baseUrl||"";if(!this._issueFieldsCache[t]){let s=await Ye(this.config,{},e);this._issueFieldsCache[t]=s.reduce((o,i)=>({...o,[i.name]:i.id}),{})}return this._issueFieldsCache[t]??null}async getCurrentUser(e={}){let t=await this.config.request({url:`${e?.baseUrl||this.config.baseUrl}/rest/api/2/myself`,headers:R(e?.token||this.config.token)});return{data:{name:t.body.displayName,email:t.body.emailAddress,avatarUrl:t.body.avatarUrls["48x48"],id:t.body.key,username:t.body.displayName,url:null}}}async getJiraProjects(e={}){return{data:(await this.config.request({url:`${e?.baseUrl||this.config.baseUrl}/rest/api/2/project`,headers:R(e?.token||this.config.token)})).body.map(s=>({id:s.id,name:s.name}))}}async getIssue(e,t={}){let s=e.resourceUrl||t.baseUrl||this.config.baseUrl;if(!s)throw new Error('Jira Server requires a "resourceUrl" or "baseUrl" for this function.');let o=await this.getIssueFieldsForResource(t);return await et(this.config,{...e,fields:o},s,t)}async getIssuesForProject(e,t={}){let s=e.resourceUrl||t.baseUrl||this.config.baseUrl;if(!s)throw new Error('Jira Server requires a "resourceUrl" or "baseUrl" for this function.');let o=await this.getIssueFieldsForResource(t);return await rt(this.config,{...e,fields:o},s,t)}async getIssuesForProjects(e,t={}){let s=e.resourceUrl||t.baseUrl||this.config.baseUrl;if(!s)throw new Error('Jira Server requires a "resourceUrl" or "baseUrl" for this function.');let o=await this.getIssueFieldsForResource(t);return await st(this.config,{...e,fields:o},s,t)}async getIssuesForResourceForCurrentUser(e,t={}){let s=e.resourceUrl||t.baseUrl||this.config.baseUrl;if(!s)throw new Error('Jira Server requires a "resourceUrl" or "baseUrl" for this function.');let o=await this.getIssueFieldsForResource(t);return await tt(this.config,{...e,fields:o},s,t)}async setIssueStatus(e,t={}){await it(this.config,e,t)}async setIssueLabels(e,t={}){await nt(this.config,e,t)}async setIssueComponents(e,t={}){await ot(this.config,e,t)}async getLabels(e={}){return{data:(await this.config.request({url:`${e?.baseUrl||this.config.baseUrl}/rest/api/2/jql/autocompletedata/suggestions?fieldName=labels`,headers:R(e.token||this.config.token)})).body.results.map(({displayName:s})=>({color:null,description:null,id:null,name:s}))}}async getComponentsForJiraProject(e,t={}){return await at(this.config,e,t)}};var H="https://api.trello.com",rs=1e3,W=(r,n)=>({...R(n),Authorization:`OAuth oauth_consumer_key="${r}", oauth_token="${n}"`}),ho=r=>({id:r.id,username:r.username,url:r.url,name:r.fullName,email:r.email,avatarUrl:r.avatarUrl}),fo=(r,n)=>{let e=new Date(1e3*parseInt(r.id.substring(0,8),16));return{id:r.id,commentCount:r.badges.comments,number:r.idShort.toString(),title:r.name,url:r.url,closedDate:null,createdDate:new Date(e.toISOString()),author:null,updatedDate:new Date(r.dateLastActivity),assignees:r.members.map(t=>({id:t.id,username:t.username,name:t.fullName,email:null,avatarUrl:t.avatarUrl,url:null})),description:null,state:n[r.idList??""]?{id:r.idList,name:n[r.idList].name,color:null}:null,type:null,repository:null,upvoteCount:r.badges.votes,labels:r.labels.map(t=>({color:t.color,description:null,id:t.id,name:t.name}))}},Se=class extends j{async getCurrentUser(n,e={}){let t=await this.config.request({url:`${e.baseUrl||H}/1/members/me`,headers:W(n.appKey,e.token||this.config.token)});return{data:{name:t.body.fullName,email:t.body.email,avatarUrl:t.body.avatarHash?`https://trello-members.s3.amazonaws.com/${t.body.id}/${t.body.avatarHash}/50.png`:null,id:t.body.id,username:t.body.username,url:t.body.url}}}async getBoardsForCurrentUser(n,e={}){return{data:(await this.config.request({url:`${e.baseUrl||H}/1/members/me/boards?fields=name&filter=open`,headers:W(n.appKey,e.token||this.config.token)})).body.map(s=>({id:s.id,name:s.name}))}}async getListsForTrelloBoard(n,e={}){let{appKey:t,boardId:s}=n;return{data:(await this.config.request({url:`${e.baseUrl||H}/1/boards/${s}/lists`,headers:W(t,e.token||this.config.token)})).body}}async getAccountForId(n,e={}){let{appKey:t,memberId:s}=n,o=await this.config.request({url:`${e.baseUrl||H}/1/members/${s}`,headers:W(t,e.token||this.config.token)});return{data:ho(o.body)}}async getAccountsForTrelloBoard(n,e={}){let{appKey:t,boardId:s}=n;return{data:(await this.config.request({url:`${e.baseUrl||H}/1/boards/${s}/members`,headers:W(t,e.token||this.config.token)})).body.map(i=>({id:i.id,name:i.fullName,username:i.username,email:null,avatarUrl:null,url:null}))}}async getIssuesForBoard(n,e={}){let t=["-is:archived","sort:edited"],{appKey:s,boardId:o,filterText:i,assigneeLogins:a,labelNamesOrColors:u,trelloBoardListsById:l}=n||{};a&&t.push("@me"),u&&u.forEach(g=>t.push(`label:"${g}"`));let p=`${i?`${i}`:""}${t.join(" ")} board:${o}`,d=await this.config.request({url:`${e.baseUrl||H}/1/search?query=${p}&cards_limit=${rs}&card_members=true`,headers:W(s,e.token||this.config.token)}),c=d.body.cards.length>=rs?"unknown":"complete";return{data:d.body.cards.map(g=>fo(g,l||{})),metadata:ge(c)}}async updateIssue(n,e,t,s){return await this.config.request({method:"PUT",url:`${s.baseUrl||H}/1/cards/${e.id}?${t}`,headers:W(n,s.token||this.config.token)})}async setIssueStatus(n,e={}){let{appKey:t,issue:s,status:o}=n;if(!o.id)throw new Error('Trello requires a status "id" for this function.');let i=`idList=${o.id}`;if(!(await this.updateIssue(t,s,i,e)).body.id)throw new Error("Could not set issue status")}async setIssueAssignees(n,e={}){let{appKey:t,issue:s,assignees:o}=n,i=o.map(l=>l.id),a=`idMembers=${encodeURIComponent(i.join(","))}`;if(!(await this.updateIssue(t,s,a,e)).body.id)throw new Error("Could not set issue status")}async setIssueLabels(n,e={}){let{appKey:t,issue:s,labels:o}=n,i=o.map(u=>u.id).join(",");if(!(await this.config.request({method:"PUT",url:`${e.baseUrl||H}/1/cards/${s.id}?idLabels=${encodeURIComponent(i)}`,headers:W(t,e.token||this.config.token)})).body.id)throw new Error("Could not set issue status")}async setIssueArchived(n,e={}){let{appKey:t,issue:s,archived:o}=n;if(!(await this.config.request({method:"PUT",url:`${e.baseUrl||H}/1/cards/${s.id}?closed=${o}`,headers:W(t,e.token||this.config.token)})).body.id)throw new Error("Could not update issue archived status")}async archiveIssue(n,e={}){await this.setIssueArchived({...n,archived:!0},e)}async unArchiveIssue(n,e={}){await this.setIssueArchived({...n,archived:!1},e)}async getLabelsForBoard(n,e={}){let{appKey:t,boardId:s}=n;return{data:(await this.config.request({url:`${e.baseUrl||H}/1/boards/${s}/labels`,headers:W(t,e.token||this.config.token)})).body.map(i=>({color:i.color,description:null,id:i.id,name:i.name}))}}};var Yt=100,ut=class{constructor(){this.set=new Set;this.arr=[]}push(...n){let e=n.filter(t=>!this.set.has(t.id));this.arr.push(...e),e.forEach(t=>this.set.add(t.id))}get length(){return this.arr.length}get items(){return this.arr}},Z=async(r,n,e,t)=>{let s=n.token||r.token;if(!s)throw new Error("Linear API key is required");let o=await r.request({url:"https://api.linear.app/graphql",method:"POST",headers:{Authorization:s,"Content-Type":"application/json"},body:JSON.stringify({query:e,variables:t})});if(o.status>=400)throw new Error(`Linear API request failed: ${o.status} ${o.statusText}`);let i=o.body;if(i.errors)throw new Error(`Linear GraphQL errors: ${i.errors.map(a=>a.message).join(", ")}`);return i.data},Zt=r=>r?r instanceof Date?r:new Date(r):null,Ro=`
1372
1372
  id
1373
1373
  name
1374
1374
  description
@@ -1376,11 +1376,11 @@ OR comment ~ currentUser() OR summary ~ currentUser() OR description ~ currentUs
1376
1376
  startDate
1377
1377
  targetDate
1378
1378
  url
1379
- `,Yr=r=>({id:r.id,name:r.name,description:r.description??null,state:r.state,startDate:Vt(r.startDate),targetDate:Vt(r.targetDate),url:r.url}),es=async(r,n,e)=>{let t=`
1379
+ `,ss=r=>({id:r.id,name:r.name,description:r.description??null,state:r.state,startDate:Zt(r.startDate),targetDate:Zt(r.targetDate),url:r.url}),ns=async(r,n,e)=>{let t=`
1380
1380
  query GetProjects($first: Int!, $after: String) {
1381
1381
  projects(first: $first, after: $after) {
1382
1382
  nodes {
1383
- ${lo}
1383
+ ${Ro}
1384
1384
  }
1385
1385
  pageInfo {
1386
1386
  hasNextPage
@@ -1388,7 +1388,7 @@ OR comment ~ currentUser() OR summary ~ currentUser() OR description ~ currentUs
1388
1388
  }
1389
1389
  }
1390
1390
  }
1391
- `;return(await Z(r,n,t,{first:Kt,after:e})).projects},po=`
1391
+ `;return(await Z(r,n,t,{first:Yt,after:e})).projects},Io=`
1392
1392
  id
1393
1393
  name
1394
1394
  number
@@ -1396,11 +1396,11 @@ OR comment ~ currentUser() OR summary ~ currentUser() OR description ~ currentUs
1396
1396
  startsAt
1397
1397
  endsAt
1398
1398
  completedAt
1399
- `,ts=r=>({id:r.id,name:r.name??`Cycle ${r.number}`,number:r.number,description:r.description??null,startsAt:new Date(r.startsAt),endsAt:new Date(r.endsAt),completedAt:Vt(r.completedAt),url:""}),rs=async(r,n,e)=>{let t=`
1399
+ `,os=r=>({id:r.id,name:r.name??`Cycle ${r.number}`,number:r.number,description:r.description??null,startsAt:new Date(r.startsAt),endsAt:new Date(r.endsAt),completedAt:Zt(r.completedAt),url:""}),is=async(r,n,e)=>{let t=`
1400
1400
  query GetCycles($first: Int!, $after: String) {
1401
1401
  cycles(first: $first, after: $after) {
1402
1402
  nodes {
1403
- ${po}
1403
+ ${Io}
1404
1404
  }
1405
1405
  pageInfo {
1406
1406
  hasNextPage
@@ -1408,16 +1408,16 @@ OR comment ~ currentUser() OR summary ~ currentUser() OR description ~ currentUs
1408
1408
  }
1409
1409
  }
1410
1410
  }
1411
- `;return(await Z(r,n,t,{first:Kt,after:e})).cycles},co=`
1411
+ `;return(await Z(r,n,t,{first:Yt,after:e})).cycles},bo=`
1412
1412
  id
1413
1413
  name
1414
1414
  color
1415
1415
  description
1416
- `,ss=r=>({id:r.id,name:r.name,color:r.color,description:r.description??null}),ns=async(r,n,e)=>{let t=`
1416
+ `,as=r=>({id:r.id,name:r.name,color:r.color,description:r.description??null}),us=async(r,n,e)=>{let t=`
1417
1417
  query GetLabels($first: Int!, $after: String) {
1418
1418
  projectLabels(first: $first, after: $after) {
1419
1419
  nodes {
1420
- ${co}
1420
+ ${bo}
1421
1421
  }
1422
1422
  pageInfo {
1423
1423
  hasNextPage
@@ -1425,36 +1425,36 @@ OR comment ~ currentUser() OR summary ~ currentUser() OR description ~ currentUs
1425
1425
  }
1426
1426
  }
1427
1427
  }
1428
- `;return(await Z(r,n,t,{first:Kt,after:e})).projectLabels};var Ue=(i=>(i[i.None=0]="None",i[i.Assignee=1]="Assignee",i[i.Creator=2]="Creator",i[i.Mention=3]="Mention",i[i.MentionInDescription=4]="MentionInDescription",i[i.MentionInComments=5]="MentionInComments",i))(Ue||{});function os(r,n){return r?`${Ue[r]}:${n||""}`:n??null}function is(r){if(!r)return{category:0};let[n,e]=r.split(":");return n in Ue?{category:Ue[n],cursor:e||void 0}:{category:0,cursor:r}}var as=100;function ut(r){return r?r instanceof Date?r:new Date(r):null}var ps=`
1428
+ `;return(await Z(r,n,t,{first:Yt,after:e})).projectLabels};var Ae=(i=>(i[i.None=0]="None",i[i.Assignee=1]="Assignee",i[i.Creator=2]="Creator",i[i.Mention=3]="Mention",i[i.MentionInDescription=4]="MentionInDescription",i[i.MentionInComments=5]="MentionInComments",i))(Ae||{});function ls(r,n){return r?`${Ae[r]}:${n||""}`:n??null}function ps(r){if(!r)return{category:0};let[n,e]=r.split(":");return n in Ae?{category:Ae[n],cursor:e||void 0}:{category:0,cursor:r}}var ds=100;function pt(r){return r?r instanceof Date?r:new Date(r):null}var gs=`
1429
1429
  id
1430
1430
  name
1431
1431
  key
1432
1432
  icon
1433
- `;function mo(r){return{id:r.id,name:r.name,key:r.key,iconUrl:r.icon}}var us=`
1433
+ `;function yo(r){return{id:r.id,name:r.name,key:r.key,iconUrl:r.icon}}var cs=`
1434
1434
  id
1435
1435
  name
1436
1436
  avatarUrl
1437
- `;function ls(r){return r?{id:r.id,name:r.name,username:r.name,email:null,avatarUrl:r.avatarUrl??null,url:null}:null}var go=`
1437
+ `;function ms(r){return r?{id:r.id,name:r.name,username:r.name,email:null,avatarUrl:r.avatarUrl??null,url:null}:null}var Po=`
1438
1438
  id
1439
1439
  name
1440
- `;function ho(r,n){if(r)return{id:r.id,name:r.name,key:n?.key||null,namespace:null,resourceId:n?.id||null}}var fo=`
1440
+ `;function wo(r,n){if(r)return{id:r.id,name:r.name,key:n?.key||null,namespace:null,resourceId:n?.id||null}}var So=`
1441
1441
  id
1442
1442
  sortOrder
1443
1443
  name
1444
1444
  description
1445
1445
  status
1446
1446
  targetDate
1447
- `;function Ro(r){return r?{id:r.id,number:r.sortOrder,title:r.name,description:r.description??null,isOpen:r.status!=="done",url:"",startDate:null,dueDate:ut(r.targetDate)}:null}function Io(r){switch(r){case"completed":case"canceled":return"DONE";case"started":return"IN_PROGRESS";default:return"TO_DO"}}var bo=`
1447
+ `;function qo(r){return r?{id:r.id,number:r.sortOrder,title:r.name,description:r.description??null,isOpen:r.status!=="done",url:"",startDate:null,dueDate:pt(r.targetDate)}:null}function vo(r){switch(r){case"completed":case"canceled":return"DONE";case"started":return"IN_PROGRESS";default:return"TO_DO"}}var Eo=`
1448
1448
  id
1449
1449
  name
1450
1450
  color
1451
1451
  type
1452
- `;function yo(r){return r?{id:r.id,name:r.name,color:r.color,category:Io(r.type)}:null}var Zt=`
1452
+ `;function Co(r){return r?{id:r.id,name:r.name,color:r.color,category:vo(r.type)}:null}var tr=`
1453
1453
  creator {
1454
- ${us}
1454
+ ${cs}
1455
1455
  }
1456
1456
  assignee {
1457
- ${us}
1457
+ ${cs}
1458
1458
  }
1459
1459
  archivedAt
1460
1460
  createdAt
@@ -1462,32 +1462,32 @@ OR comment ~ currentUser() OR summary ~ currentUser() OR description ~ currentUs
1462
1462
  id
1463
1463
  identifier
1464
1464
  project {
1465
- ${go}
1465
+ ${Po}
1466
1466
  }
1467
1467
  team {
1468
- ${ps}
1468
+ ${gs}
1469
1469
  }
1470
1470
  state {
1471
- ${bo}
1471
+ ${Eo}
1472
1472
  }
1473
1473
  title
1474
1474
  updatedAt
1475
1475
  url
1476
1476
  projectMilestone {
1477
- ${fo}
1477
+ ${So}
1478
1478
  }
1479
- `;async function Xt(r){return{author:ls(await r.creator),assignees:[ls(await r.assignee)].filter(n=>n!=null),commentCount:null,closedDate:ut(r.archivedAt),createdDate:ut(r.createdAt),description:r.description??null,id:r.id,labels:[],number:r.identifier,repository:null,project:ho(await r.project,await r.team),state:yo(await r.state),title:r.title,type:null,updatedDate:ut(r.updatedAt),upvoteCount:null,url:r.url,milestone:Ro(await r.projectMilestone)}}var at=`
1479
+ `;async function er(r){return{author:ms(await r.creator),assignees:[ms(await r.assignee)].filter(n=>n!=null),commentCount:null,closedDate:pt(r.archivedAt),createdDate:pt(r.createdAt),description:r.description??null,id:r.id,labels:[],number:r.identifier,repository:null,project:wo(await r.project,await r.team),state:Co(await r.state),title:r.title,type:null,updatedDate:pt(r.updatedAt),upvoteCount:null,url:r.url,milestone:qo(await r.projectMilestone)}}var lt=`
1480
1480
  nodes {
1481
- ${Zt}
1481
+ ${tr}
1482
1482
  }
1483
1483
  pageInfo {
1484
1484
  hasNextPage
1485
1485
  endCursor
1486
1486
  }
1487
- `,lt=class extends j{async fetchIssue(n,e){let t=`
1487
+ `,dt=class extends j{async fetchIssue(n,e){let t=`
1488
1488
  query GetIssue($identifier: String!) {
1489
1489
  issue(id: $identifier) {
1490
- ${Zt}
1490
+ ${tr}
1491
1491
  }
1492
1492
  }
1493
1493
  `;return(await Z(this.config,e,t,{identifier:n})).issue}async fetchOrganization(n){let e=`
@@ -1502,7 +1502,7 @@ OR comment ~ currentUser() OR summary ~ currentUser() OR description ~ currentUs
1502
1502
  query GetTeams {
1503
1503
  teams {
1504
1504
  nodes {
1505
- ${ps}
1505
+ ${gs}
1506
1506
  }
1507
1507
  }
1508
1508
  }
@@ -1515,23 +1515,23 @@ OR comment ~ currentUser() OR summary ~ currentUser() OR description ~ currentUs
1515
1515
  displayName
1516
1516
  }
1517
1517
  }
1518
- `;return(await Z(this.config,n,e)).viewer}async getIssue(n,e={}){let t=await this.fetchIssue(n.number,e);return{data:await Xt(t)}}async getLinearOrganization(n={}){let e=await this.fetchOrganization(n);return{data:{id:e.id,name:e.name,key:e.urlKey,url:`https://linear.app/${e.urlKey}`}}}async getTeamsForCurrentUser(n={}){return{data:(await this.fetchTeams(n)).nodes.map(mo)}}async getProjects(n={},e={}){let t=await es(this.config,e,n.cursor??void 0);return{data:t.nodes.map(Yr),pageInfo:{hasNextPage:t.pageInfo.hasNextPage,endCursor:t.pageInfo.endCursor??null}}}async getCycles(n={},e={}){let t=await rs(this.config,e,n.cursor??void 0);return{data:t.nodes.map(ts),pageInfo:{hasNextPage:t.pageInfo.hasNextPage,endCursor:t.pageInfo.endCursor??null}}}async getLabels(n={},e={}){let t=await ns(this.config,e,n.cursor??void 0);return{data:t.nodes.map(ss),pageInfo:{hasNextPage:t.pageInfo.hasNextPage,endCursor:t.pageInfo.endCursor??null}}}async getCurrentUser(n={}){return{data:await this.fetchViewer(n)}}async getIssuesForCurrentUser(n,e={}){let{cursor:t}=n,{category:s,cursor:o}=is(t),i=await this.fetchViewer(e),a,u,l=new it,d=async(p,c)=>{if(u||s>p)return;let g=await c(Math.max(as-l.length,1),s===p?o:void 0);if(!g)return;let m=await mt(g.nodes.map(Xt));l.push(...m),g.pageInfo.hasNextPage&&(a=p,u=g.pageInfo.endCursor)};return await d(1,async(p,c)=>(await this.rawRequest(e,`
1518
+ `;return(await Z(this.config,n,e)).viewer}async getIssue(n,e={}){let t=await this.fetchIssue(n.number,e);return{data:await er(t)}}async getLinearOrganization(n={}){let e=await this.fetchOrganization(n);return{data:{id:e.id,name:e.name,key:e.urlKey,url:`https://linear.app/${e.urlKey}`}}}async getTeamsForCurrentUser(n={}){return{data:(await this.fetchTeams(n)).nodes.map(yo)}}async getProjects(n={},e={}){let t=await ns(this.config,e,n.cursor??void 0);return{data:t.nodes.map(ss),pageInfo:{hasNextPage:t.pageInfo.hasNextPage,endCursor:t.pageInfo.endCursor??null}}}async getCycles(n={},e={}){let t=await is(this.config,e,n.cursor??void 0);return{data:t.nodes.map(os),pageInfo:{hasNextPage:t.pageInfo.hasNextPage,endCursor:t.pageInfo.endCursor??null}}}async getLabels(n={},e={}){let t=await us(this.config,e,n.cursor??void 0);return{data:t.nodes.map(as),pageInfo:{hasNextPage:t.pageInfo.hasNextPage,endCursor:t.pageInfo.endCursor??null}}}async getCurrentUser(n={}){return{data:await this.fetchViewer(n)}}async getIssuesForCurrentUser(n,e={}){let{cursor:t}=n,{category:s,cursor:o}=ps(t),i=await this.fetchViewer(e),a,u,l=new ut,p=async(d,c)=>{if(u||s>d)return;let g=await c(Math.max(ds-l.length,1),s===d?o:void 0);if(!g)return;let m=await ht(g.nodes.map(er));l.push(...m),g.pageInfo.hasNextPage&&(a=d,u=g.pageInfo.endCursor)};return await p(1,async(d,c)=>(await this.rawRequest(e,`
1519
1519
  query GetAssignedIssues($first: Int!, $after: String) {
1520
1520
  viewer {
1521
1521
  issues: assignedIssues(first: $first, after: $after) {
1522
- ${at}
1522
+ ${lt}
1523
1523
  }
1524
1524
  }
1525
1525
  }
1526
- `,{first:p,after:c})).data?.viewer?.issues),await d(2,async(p,c)=>(await this.rawRequest(e,`
1526
+ `,{first:d,after:c})).data?.viewer?.issues),await p(2,async(d,c)=>(await this.rawRequest(e,`
1527
1527
  query GetCreatedIssues($first: Int!, $after: String) {
1528
1528
  viewer {
1529
1529
  issues: createdIssues(first: $first, after: $after) {
1530
- ${at}
1530
+ ${lt}
1531
1531
  }
1532
1532
  }
1533
1533
  }
1534
- `,{first:p,after:c})).data?.viewer?.issues),await d(4,async(p,c)=>(await this.rawRequest(e,`
1534
+ `,{first:d,after:c})).data?.viewer?.issues),await p(4,async(d,c)=>(await this.rawRequest(e,`
1535
1535
  query GetMentionedIssues($first: Int!, $after: String) {
1536
1536
  issues(
1537
1537
  first: $first
@@ -1552,10 +1552,10 @@ OR comment ~ currentUser() OR summary ~ currentUser() OR description ~ currentUs
1552
1552
  }]
1553
1553
  }
1554
1554
  ){
1555
- ${at}
1555
+ ${lt}
1556
1556
  }
1557
1557
  }
1558
- `,{first:p,after:c})).data?.issues),await d(5,async(p,c)=>{let m=(await this.rawRequest(e,`
1558
+ `,{first:d,after:c})).data?.issues),await p(5,async(d,c)=>{let m=(await this.rawRequest(e,`
1559
1559
  query GetCommentedIssues($first: Int!, $after: String) {
1560
1560
  comments(
1561
1561
  first: $first
@@ -1578,7 +1578,7 @@ OR comment ~ currentUser() OR summary ~ currentUser() OR description ~ currentUs
1578
1578
  ){
1579
1579
  nodes {
1580
1580
  issue {
1581
- ${Zt}
1581
+ ${tr}
1582
1582
  }
1583
1583
  }
1584
1584
  pageInfo {
@@ -1587,10 +1587,10 @@ OR comment ~ currentUser() OR summary ~ currentUser() OR description ~ currentUs
1587
1587
  }
1588
1588
  }
1589
1589
  }
1590
- `,{first:p,after:c})).data?.comments;return m?{nodes:m.nodes.map(y=>y.issue),pageInfo:m.pageInfo}:void 0}),{data:l.items,pageInfo:{hasNextPage:!!u,endCursor:os(a,u)}}}async getIssues(n,e={}){let{teams:t,projects:s,labels:o,cursor:i}=n,a=[];if(t&&t.length>0){let g=t.map(m=>`"${m}"`).join(", ");a.push(`team: { id: { in: [${g}] } }`)}if(s&&s.length>0){let g=s.map(m=>`"${m}"`).join(", ");a.push(`project: { id: { in: [${g}] } }`)}if(o&&o.length>0){let g=o.map(m=>`"${m}"`).join(", ");a.push(`labels: { name: { in: [${g}] } }`)}let u=a.length>0?`filter: { ${a.join(", ")} }`:"",l=`
1590
+ `,{first:d,after:c})).data?.comments;return m?{nodes:m.nodes.map(y=>y.issue),pageInfo:m.pageInfo}:void 0}),{data:l.items,pageInfo:{hasNextPage:!!u,endCursor:ls(a,u)}}}async getIssues(n,e={}){let{teams:t,projects:s,labels:o,cursor:i}=n,a=[];if(t&&t.length>0){let g=t.map(m=>`"${m}"`).join(", ");a.push(`team: { id: { in: [${g}] } }`)}if(s&&s.length>0){let g=s.map(m=>`"${m}"`).join(", ");a.push(`project: { id: { in: [${g}] } }`)}if(o&&o.length>0){let g=o.map(m=>`"${m}"`).join(", ");a.push(`labels: { name: { in: [${g}] } }`)}let u=a.length>0?`filter: { ${a.join(", ")} }`:"",l=`
1591
1591
  query GetIssues($first: Int!, $after: String) {
1592
1592
  issues(first: $first, after: $after${u?", ":""}${u}) {
1593
- ${at}
1593
+ ${lt}
1594
1594
  }
1595
1595
  }
1596
- `,p=(await this.rawRequest(e,l,{first:as,after:i})).data?.issues;return p?{data:await mt(p.nodes.map(Xt)),pageInfo:{hasNextPage:p.pageInfo.hasNextPage,endCursor:p.pageInfo.endCursor??null}}:{data:[],pageInfo:{hasNextPage:!1,endCursor:null}}}};var ds=r=>{let n={request:r?.request};return{azureDevOps:new he({...n,...r?.azureDevOps}),bitbucket:new fe({...n,...r?.bitbucket}),bitbucketServer:new Re({...n,...r?.bitbucketServer}),github:new Ie({...n,...r?.github}),gitlab:new ye({...n,...r?.gitlab}),jira:new Pe({...n,...r?.jira}),jiraServer:new we({...n,...r?.jiraServer}),linear:new lt({...n,...r?.linear}),trello:new Se({...n,...r?.trello})}};var cs=(i=>(i.Conflicts="conflicts",i.Failure="failure",i.NotSet="notSet",i.Queued="queued",i.RejectedByPolicy="rejectedByPolicy",i.Succeeded="succeeded",i))(cs||{});var ms=(e=>(e.Zero="0",e.One="1",e))(ms||{}),gs=(e=>(e.PullRequest="pr",e.Issue="issue",e))(gs||{}),hs=(c=>(c.Azure="azure",c.AzureDevOpsServer="azureDevOpsServer",c.Github="github",c.GithubEnterprise="githubEnterprise",c.Gitlab="gitlab",c.GitlabSelfHosted="gitlabSelfHosted",c.Bitbucket="bitbucket",c.BitbucketServer="bitbucketServer",c.Jira="jira",c.JiraServer="jiraServer",c.Linear="linear",c.Trello="trello",c))(hs||{});var fs=(e=>(e.Completed="COMPLETED",e.NotPlanned="NOT_PLANNED",e))(fs||{});var Po=ds;
1596
+ `,d=(await this.rawRequest(e,l,{first:ds,after:i})).data?.issues;return d?{data:await ht(d.nodes.map(er)),pageInfo:{hasNextPage:d.pageInfo.hasNextPage,endCursor:d.pageInfo.endCursor??null}}:{data:[],pageInfo:{hasNextPage:!1,endCursor:null}}}};var hs=r=>{let n={request:r?.request};return{azureDevOps:new fe({...n,...r?.azureDevOps}),bitbucket:new Re({...n,...r?.bitbucket}),bitbucketServer:new Ie({...n,...r?.bitbucketServer}),github:new be({...n,...r?.github}),gitlab:new ye({...n,...r?.gitlab}),jira:new Pe({...n,...r?.jira}),jiraServer:new we({...n,...r?.jiraServer}),linear:new dt({...n,...r?.linear}),trello:new Se({...n,...r?.trello})}};var fs=(i=>(i.Conflicts="conflicts",i.Failure="failure",i.NotSet="notSet",i.Queued="queued",i.RejectedByPolicy="rejectedByPolicy",i.Succeeded="succeeded",i))(fs||{});var Rs=(e=>(e.Zero="0",e.One="1",e))(Rs||{}),Is=(e=>(e.PullRequest="pr",e.Issue="issue",e))(Is||{}),bs=(c=>(c.Azure="azure",c.AzureDevOpsServer="azureDevOpsServer",c.Github="github",c.GithubEnterprise="githubEnterprise",c.Gitlab="gitlab",c.GitlabSelfHosted="gitlabSelfHosted",c.Bitbucket="bitbucket",c.BitbucketServer="bitbucketServer",c.Jira="jira",c.JiraServer="jiraServer",c.Linear="linear",c.Trello="trello",c))(bs||{});var ys=(e=>(e.Completed="COMPLETED",e.NotPlanned="NOT_PLANNED",e))(ys||{});var $o=hs;