@gitkraken/provider-apis 0.49.0 → 0.50.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 rt=Object.defineProperty;var Jr=Object.getOwnPropertyDescriptor;var Vr=Object.getOwnPropertyNames;var Kr=Object.prototype.hasOwnProperty;var Xr=(s,n)=>{for(var e in n)rt(s,e,{get:n[e],enumerable:!0})},Zr=(s,n,e,t)=>{if(n&&typeof n=="object"||typeof n=="function")for(let r of Vr(n))!Kr.call(s,r)&&r!==e&&rt(s,r,{get:()=>n[r],enumerable:!(t=Jr(n,r))||t.enumerable});return s};var Yr=s=>Zr(rt({},"__esModule",{value:!0}),s);var Tn={};Xr(Tn,{AzureDevOps:()=>ae,Bitbucket:()=>ue,BitbucketServer:()=>le,EntityIdentifierProviderType:()=>Qr,EntityType:()=>jr,EntityVersion:()=>Fr,GitBuildStatusStage:()=>Mt,GitBuildStatusState:()=>ve,GitDiffLineType:()=>st,GitHub:()=>pe,GitHubIssueCloseReason:()=>Br,GitIssueState:()=>Le,GitLab:()=>ce,GitMergeStrategy:()=>ie,GitPullRequestMergeableState:()=>re,GitPullRequestReviewState:()=>K,GitPullRequestState:()=>te,GraphQLErrors:()=>R,Jira:()=>me,JiraServer:()=>ge,PullRequestAsyncStatus:()=>Nr,Trello:()=>he,default:()=>Gn,isFetch:()=>Se});module.exports=Yr(Tn);var Yt=require("diff");var Mt=(r=>(r.Build="build",r.Production="production",r.Staging="staging",r.Test="test",r))(Mt||{}),ve=(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))(ve||{}),ie=(o=>(o.MergeCommit="MERGE_COMMIT",o.Rebase="REBASE",o.RebaseThenMergeCommit="REBASE_THEN_MERGE_COMMIT",o.FastForward="FAST_FORWARD",o.Squash="SQUASH",o))(ie||{}),te=(t=>(t.Open="OPEN",t.Closed="CLOSED",t.Merged="MERGED",t))(te||{}),K=(r=>(r.Approved="APPROVED",r.ChangesRequested="CHANGES_REQUESTED",r.Commented="COMMENTED",r.ReviewRequested="REVIEW_REQUESTED",r))(K||{}),re=(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))(re||{}),st=(t=>(t.ADDED="ADDED",t.DELETED="DELETED",t.UNMODIFIED="UNMODIFIED",t))(st||{});var zt={APPROVED:0,COMMENTED:1,REVIEW_REQUESTED:2,CHANGES_REQUESTED:3},j=s=>!s||s.length===0?null:s.reduce((n,e)=>zt[e.state]>zt[n]?e.state:n,"APPROVED");var nt=(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))(nt||{});var $=100;var Ht=globalThis.fetch;var es=async s=>{let n=s.headers.get("content-type")||"",e=null;if(n.startsWith("application/json")){let o=await s.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 s.text();else if(n.startsWith("application/vnd.github.raw+json")||n.startsWith("application/octet-stream"))e=await s.arrayBuffer();else throw new Error(`Unsupported content-type: ${n}`);let t={};s.headers.forEach((o,i)=>{t[i]=o});let r={body:e,headers:t,status:s.status,statusText:s.statusText};if(!s.ok){let o=new Error(s.statusText);throw Object.assign(o,{response:r}),o}return r},ot=s=>async({url:n,...e})=>{let t=await s(n,e);return es(t)};var Se=(s,n=!1)=>s.name==="fetch"||n;var N=class{constructor(n){let e=n?.request||Ht;this.config={...n,request:Se(e,n?.forceIsFetch)?ot(e):e}}updateConfig(n){this.config={...this.config,...n,request:n.request&&Se(n.request,n?.forceIsFetch??this.config.forceIsFetch)?ot(n.request):this.config.request}}},_=class extends N{};var f=(s,n)=>{let e={};return s&&(e.Authorization=`${n?"Basic":"Bearer"} ${s}`),e},Wt=s=>s?s.reduce((n,e)=>(n[e]=!0,n),{}):void 0,X=(s,n,e)=>!s||n.some(t=>s[t])?e:"",Jt=async s=>{let n=[],e=!0,t;for(;e;){let r=await s(t);n=n.concat(r.data),e=!!r?.pageInfo?.hasNextPage,t=r?.pageInfo?.endCursor||r?.pageInfo?.nextPage}return n};async function it(s){return(await Promise.allSettled(s)).map(e=>ts(e)).filter(e=>e!=null)}function ts(s,n=void 0){return s?.status==="fulfilled"?s.value:n}var rs="https://app.vssps.visualstudio.com/_apis",ss="https://vssps.dev.azure.com/",ns="https://dev.azure.com",w=(s,n={})=>f(n.token||s.token,n.isPAT||s.isPAT),Vt=s=>s.url.replace("/_apis/git/repositories/","/_git/").replace(`/${s.repository.project.id}/`,`/${encodeURIComponent(s.repository.project.name)}/`).replace(`/${s.repository.id}/`,`/${encodeURIComponent(s.repository.name)}/`).replace("/pullRequests/","/pullrequest/"),at=(s,n)=>{let e=n.baseUrl||s.baseUrl||rs;return e=e.replace(/\/$/,""),e},C=(s,n)=>{let e=n.baseUrl||s.baseUrl||ns;return e=e.replace(/\/$/,""),e},ut=(s,n)=>{let e=n.baseUrl||s.baseUrl||ss;return e=e.replace(/\/$/,""),e};var os={active:"OPEN",completed:"MERGED",abandoned:"CLOSED"},is=s=>{if(typeof s!="string")return s;let n=s.charAt(0).toUpperCase()+s.slice(1);return nt[n]??0},as=new Set([2,3,4,5]),us={10:"APPROVED",5:"APPROVED",0:"REVIEW_REQUESTED",[-5]:"CHANGES_REQUESTED",[-10]:"CHANGES_REQUESTED"},se=s=>({id:s.id,name:s.displayName??null,username:(s.uniqueName||s.displayName)??null,email:null,avatarUrl:s.imageUrl??null,url:null}),Ee=s=>s.startsWith("refs/heads/")?s.replace("refs/heads/",""):s,ls=s=>{switch(s){case"conflicts":return"CONFLICTS";case"failure":return"FAILING_CHECKS";case"rejectedByPolicy":return"BLOCKED";case"succeeded":return"MERGEABLE";case"notSet":case"queued":default:return"UNKNOWN"}},lt=(s,n,e,t,r,o)=>`${s}|${n}|${e}|${t}|${r}|${o}`,Kt=s=>{let n=s.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]}},Xt=(s,n,e,t,r)=>`${s}|${n}|${e}|${t}|${r}`,pt=s=>{let n=s.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]}},Re=(s,n)=>{let e=[],t=[];return n.reviewers.forEach(r=>{let o={reviewer:se(r),state:us[r.vote??0]||"REVIEW_REQUESTED"};r.isRequired&&e.push(o),t.push(o)}),{id:n.pullRequestId.toString(),title:n.title,description:n.description??null,number:n.codeReviewId,state:os[n.status],isDraft:n.isDraft,commentCount:null,upvoteCount:null,author:se(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,repository:{id:n.repository.id,name:n.repository.name,project:n.repository.project.name,owner:{login:s},remoteInfo:null},headCommit:{buildStatuses:null},baseRef:{name:Ee(n.targetRefName),oid:n.lastMergeTargetCommit.commitId},headRef:{name:Ee(n.sourceRefName),oid:n.lastMergeSourceCommit.commitId},url:Vt(n),assignees:n.reviewers.map(se),reviews:t,reviewDecision:j(e),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:s},remoteInfo:null}:{id:n.repository.id,name:n.repository.name,project:n.repository.project.name,owner:{login:s},remoteInfo:null},mergeableState:ls(n.mergeStatus),labels:n.labels?.map(r=>({color:null,description:null,id:r.id,name:r.name}))??[],permissions:null}},Zt=(s,n)=>({id:n.id,name:n.name,namespace:s,project:n.project.name,projectId:n.project.id,webUrl:n.webUrl,httpsUrl:n.remoteUrl,sshUrl:n.sshUrl,defaultBranch:n.defaultBranch?{name:Ee(n.defaultBranch)}:null,permissions:null}),ps=(s,n,e,t)=>{let r=e.fields,o=r["System.AssignedTo"],i=r["System.State"],a=r["System.WorkItemType"],u;return i&&a&&(u=t[a]?.[i]),{id:e.id.toString(),number:e.id.toString(),title:r["System.Title"],commentCount:r["System.CommentCount"],author:{avatarUrl:r["System.CreatedBy"]._links?.avatar?.href??null,email:null,id:r["System.CreatedBy"].id,name:r["System.CreatedBy"].uniqueName??null,username:r["System.CreatedBy"].displayName??null,url:null},closedDate:r["Microsoft.VSTS.Common.ClosedDate"]?new Date(r["Microsoft.VSTS.Common.ClosedDate"]):null,createdDate:new Date(r["System.CreatedDate"]),updatedDate:new Date(r["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:r["System.Description"]??null,state:{name:u?.title||i,color:null},type:r["System.WorkItemType"],repository:null,project:{namespace:s,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()}))??[]}},ae=class extends _{constructor(){super(...arguments);this.cachedUserIds=new Map;this.inflightUserIds=new Map}getCurrentUserId(e,t){let r=JSON.stringify([e,t.token??null,t.isPAT??this.config.isPAT??!1,t.baseUrl??null]),o=this.cachedUserIds.get(r);if(o)return Promise.resolve(o);let i=this.inflightUserIds.get(r);if(i)return i;let a=this.fetchCurrentUserId(e,t,r);return this.inflightUserIds.set(r,a),a}async fetchCurrentUserId(e,t,r){try{let o=await this.getCurrentUserForInstance({namespace:e},t);return this.cachedUserIds.set(r,o.data.id),o.data.id}finally{this.inflightUserIds.delete(r)}}getRepoApiUrl(e,t,r,o){return`${C(this.config,o)}/${encodeURIComponent(e)}/${encodeURIComponent(t)}/_apis/git/repositories/${encodeURIComponent(r)}`}async getCurrentUser(e={},t={}){if(t.isPAT||this.config.isPAT)throw new Error("Azure DevOps does not support PATs for this function.");let r=`${at(this.config,t)}/profile/profiles/me`,o=await this.config.request({url:r,headers:w(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:w(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:w(this.config,t)})).body.author;return{data:{name:o.name,email:o.email,avatarUrl:o.imageUrl}}}async getOrgsForUser(e,t={}){let r=`${at(this.config,t)}/accounts?memberId=${e.userId}&api-version=6.0`;return{data:(await this.config.request({url:r,headers:w(this.config,t)})).body.value.map(i=>({id:i.accountId,name:i.accountName}))}}async getCollectionsForUser(e,t={}){let r=`${C(this.config,t)}/_apis/projectCollections`;return{data:(await this.config.request({url:r,headers:w(this.config,t)})).body.value.map(i=>({id:i.id,name:i.name}))}}async getAzureProjects(e,t={}){let r=new URL(`${C(this.config,t)}/${encodeURIComponent(e.namespace)}/_apis/projects`);r.searchParams.set("$top",$.toString()),e.cursor&&r.searchParams.set("$skip",e.cursor);let o=await this.config.request({url:r.toString(),headers:w(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:r,projectId:o}=e;return{data:{scope:(await this.config.request({url:`${ut(this.config,t)}/${encodeURIComponent(r)}/_apis/graph/descriptors/${o}?api-version=6.0`,headers:w(this.config,t)})).body.value}}}async getAzureGraphAccountsForAzureProject(e,t={}){let{namespace:r,projectScopeDescriptor:o,cursor:i}=e,a=new URL(`${ut(this.config,t)}/${encodeURIComponent(r)}/_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:w(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:r}=e;if(!r.storageKeyURL)throw new Error("Expected 'storageKeyURL' to not be null for 'azureGraphAccount'");let o=await this.config.request({url:r.storageKeyURL,headers:w(this.config,t)});return{data:{avatarUrl:r.avatarUrl,email:r.email,id:o.body.value,name:r.name,username:r.username,url:null}}}async getAccountsFromAzureGraphAccounts(e,t={}){let r=[];for(let o of e.azureGraphAccounts){let i=await this.getAccountFromAzureGraphAccount({azureGraphAccount:o},t);r.push(i.data)}return{data:r}}async getRepo(e,t={}){if(!e.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let r=await this.config.request({url:`${C(this.config,t)}/${encodeURIComponent(e.namespace)}/${encodeURIComponent(e.project)}/_apis/git/repositories/${encodeURIComponent(e.name)}`,headers:w(this.config,t)});return{data:Zt(e.namespace,r.body)}}async getRepos(e,t={}){let r=[],o=[];return await Promise.all(e.map(async i=>{try{let a=await this.getRepo(i,t);r.push(a.data)}catch(a){o.push({input:i,error:a})}})),{data:r,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:w(this.config,t)})).body.value.map(o=>Zt(e.namespace,o))}}async getRefs(e,t,r={}){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,r)}/${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",$.toString()),t.cursor&&o.searchParams.set("continuationToken",t.cursor);let i=await this.config.request({url:o.toString(),headers:w(this.config,r)}),a=i.headers["x-ms-continuationtoken"];return{pageInfo:{hasNextPage:!!a,endCursor:a||null},data:i.body.value.map(u=>({name:Ee(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 getPullRequestsForRepoBase(e,t={},r=100){let{page:o,repo:i,assigneeLogins:a,authorLogin:u}=e||{},l=o||1;if(!i.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let p="searchCriteria.status=1";return a&&a.length&&(p+=`&searchCriteria.reviewerId=${a[0]}`),u&&(p+=`&searchCriteria.creatorId=${u}`),await this.config.request({url:`${C(this.config,t)}/${encodeURIComponent(i.namespace)}/${encodeURIComponent(i.project||"")}/_apis/git/repositories/${encodeURIComponent(i.name)}/pullRequests?${p}&%24top=${r}&%24skip=${(l-1)*r}`,headers:w(this.config,t)})}async getPullRequestsForRepo(e,t={}){let o=e.page||1,i=await this.getPullRequestsForRepoBase(e,t,100);return{pageInfo:{hasNextPage:i.body.value.length===100,nextPage:o+1},data:i.body.value.map(a=>Re(e.repo.namespace,a))}}async getPullRequestsForRepos(e,t={}){if(!e.repos.every(i=>i.project))throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let{repos:r}=e||{},o=[];return await Promise.all(r.map(async i=>{try{(await this.getPullRequestsForRepoBase({repo:i,...e},t)).body.value.forEach(u=>{o.push(Re(i.namespace,u))})}catch(a){if(a.statusCode!==404&&a.statusCode!==401)throw a}})),{data:o}}async getPullRequestsForProjectBase(e,t={},r=100){let{namespace:o,project:i,page:a,assigneeLogins:u,authorLogin:l,repo:p}=e;if(p?.project&&p.project!==i)throw new Error("Could not fetch pull requests, project mismatch");let c=a||1,d=new URL(`${C(this.config,t)}/${encodeURIComponent(o)}/${encodeURIComponent(i)}/_apis/git/pullRequests`);return d.searchParams.set("searchCriteria.status","1"),d.searchParams.set("$top",r.toString()),d.searchParams.set("$skip",((c-1)*r).toString()),p?.id&&p?.project===i&&d.searchParams.set("searchCriteria.repositoryId",p.id),u&&u.length&&d.searchParams.set("searchCriteria.reviewerId",u[0]),l&&d.searchParams.set("searchCriteria.creatorId",l),await this.config.request({url:d.toString(),headers:w(this.config,t)})}async getPullRequestsForProject(e,t={}){let o=e.page||1,i=await this.getPullRequestsForProjectBase(e,t,100);return{pageInfo:{hasNextPage:i?.body.value.length===100,nextPage:o+1},data:i?.body.value.map(a=>Re(e.namespace,a))||[]}}async getPullRequestsForProjects(e,t={}){let{projects:r}=e||{},o=[];return await Promise.all(r.map(async i=>{try{(!e.repo||e.repo.project&&e.repo.project===i.project)&&(await this.getPullRequestsForProjectBase({...i,...e},t))?.body.value.forEach(u=>{o.push(Re(i.namespace,u))})}catch(a){if(a.statusCode!==404&&a.statusCode!==401)throw a}})),{data:o}}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:r,project:o,name:i},pullRequestId:a}=e,u=await this.config.request({url:`${C(this.config,t)}/${encodeURIComponent(r)}/${encodeURIComponent(o||"")}/_apis/git/repositories/${i}/pullrequests/${a}?includeCommits=true?api-version=6.0`,headers:{...w(this.config,t)}});if(!u.body.mergeStatus)throw new Error("Could not fetch pull request");return{data:u.body.mergeStatus}}async updatePullRequest(e,t,r){return await this.config.request({method:"PATCH",url:`${C(this.config,r)}/${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:{...w(this.config,r),"Content-Type":"application/json"}})}async closePullRequest(e,t={}){let{pullRequest:r}=e,o={status:"abandoned"};if(!(await this.updatePullRequest(r,JSON.stringify(o),t)).body.status)throw new Error("Could not close pull request")}async mergePullRequest(e,t={}){let{pullRequest:r,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:r.headRef?.oid},status:"completed"};if(!(await this.updatePullRequest(r,JSON.stringify(a),t)).body.status)throw new Error("Could not merge pull request")}async addPullRequestLabel(e,t={}){let{pullRequest:r,label:o}=e;if(!r.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(r.repository.owner.login)}/${encodeURIComponent(r.repository.project)}/_apis/git/repositories/${r.repository.name}/pullrequests/${r.id}/labels?api-version=6.0`,body:JSON.stringify(i),headers:{...w(this.config,t),"Content-Type":"application/json"}})).body.id)throw new Error("Could not add pull request label")}async removePullRequestLabel(e,t={}){let{pullRequest:r,label:o}=e;if(!r.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(r.repository.owner.login)}/${encodeURIComponent(r.repository.project)}/_apis/git/repositories/${r.repository.name}/pullrequests/${r.id}/labels/${encodeURIComponent(o.name)}?api-version=6.0`,headers:{...w(this.config,t)}})}async setPullRequestLabels(e,t={}){let{pullRequest:r,labels:o}=e;if(!r.repository.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let i=r.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:r,label:a},t);for(let a of i)o.find(u=>a.id===u.id)||await this.removePullRequestLabel({pullRequest:r,label:a},t)}async setPullRequestAsDraft(e,t={}){let{pullRequest:r,isDraft:o}=e,i={isDraft:o};if(!(await this.updatePullRequest(r,JSON.stringify(i),t)).body.status)throw new Error("Could not set the pull request as draft")}async addPullRequestReviewer(e,t={}){let{pullRequest:r,reviewer:o,isRequired:i}=e,a={id:o.id,isRequired:i};if(!(await this.config.request({method:"PUT",url:`${C(this.config,t)}/${encodeURIComponent(r.repository.owner.login)}/${encodeURIComponent(r.repository.project)}/_apis/git/repositories/${r.repository.name}/pullrequests/${r.id}/reviewers/${o.id}?api-version=6.0`,body:JSON.stringify(a),headers:{...w(this.config,t),"Content-Type":"application/json"}})).body.id)throw new Error("Could not add pull request reviewer")}async removePullRequestReviewer(e,t={}){let{pullRequest:r,reviewer:o}=e;await this.config.request({method:"DELETE",url:`${C(this.config,t)}/${encodeURIComponent(r.repository.owner.login)}/${encodeURIComponent(r.repository.project)}/_apis/git/repositories/${r.repository.name}/pullrequests/${r.id}/reviewers/${o.id}?api-version=6.0`,headers:{...w(this.config,t),Accept:"application/json"}})}async setPullRequestReviewers(e,t={}){let{pullRequest:r,reviewers:o}=e;for(let i of o)r.assignees.find(a=>a.id===i.id)||await this.addPullRequestReviewer({pullRequest:r,reviewer:i,isRequired:!0},t);for(let i of r.assignees)o.find(a=>i.id===a.id)||await this.removePullRequestReviewer({pullRequest:r,reviewer:i},t)}async getIssuesForAzureProject(e,t={}){let{page:r,assigneeLogins:o,authorLogin:i,mentionLogin:a,labelNames:u,statusByWorkItemIdByStatusId:l}=e||{},p=r||1,c=200,d=["[Microsoft.VSTS.Common.ClosedDate] = ''","[System.TeamProject] = @project","[Microsoft.VSTS.Common.ResolvedDate] = ''"];i&&d.push(`[System.CreatedBy] = '${i.replace("'","''")}'`),o&&o[0]&&d.push(`[System.AssignedTo] = '${o[0].replace("'","''")}'`),a&&d.push("[System.Id] IN (@recentMentions)"),u&&u.forEach(h=>d.push(`[System.Tags] Contains '${h}'`));let g=`Select [Microsoft.VSTS.Common.ClosedDate], [Microsoft.VSTS.Common.ResolvedDate] From WorkItems Where ${d.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:{...w(this.config,t),"Content-Type":"application/json"}}),I=m.body.workItems.slice((p-1)*c,c*p).map(h=>h.id);if(I.length==0)return{pageInfo:{hasNextPage:!1,nextPage:null},data:[]};let y=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:I,$expand:"Links"}),method:"POST",headers:{...w(this.config,t),"Content-Type":"application/json"}});return{pageInfo:{hasNextPage:m.body.workItems.length>c*p,nextPage:p+1},data:y.body.value.map(h=>ps(e.namespace,e.project,h,l||{}))}}async getPermissionsForRepos(e,t={}){let{namespace:r,repos:o}=e,i={4:["canPush","canCreateWebhook"],1024:["isAdmin"],2048:["isAdmin"],4096:["isAdmin"],8192:["isAdmin"]},a=c=>{let d="2e9eb7ed-3c0a-47d4-87c1-0ffdd275fd87",g=`repoV2/${c.projectId}/${c.id}`;return Object.keys(i).map(m=>({securityNamespaceId:d,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(r)}/_apis/security/permissionevaluationbatch?api-version=7.0`,body:JSON.stringify(u),headers:{...w(this.config,t),"Content-Type":"application/json"}})).body.evaluations.reduce((c,d)=>{let[,g,m]=d.token.split("/"),I=`${g}/${m}`,y=i[d.permissions];for(let h of y)c[I]===void 0&&(c[I]={canCreateWebhook:!0,canPush:!0,isAdmin:!0}),d.value===!1&&(c[I][h]=!1);return c},{})}}async decorateReposWithPermissions(e,t={}){let{namespace:r,repos:o}=e,i=await this.getPermissionsForRepos({namespace:r,repos:o},t);return{data:o.map(a=>({...a,permissions:i.data[`${a.projectId}/${a.id}`]}))}}async updateIssue(e,t,r={}){return await this.config.request({method:"PATCH",url:`${C(this.config,r)}/${encodeURIComponent(e.project.namespace)}/${encodeURIComponent(e.project.name)}/_apis/wit/workitems/${e.id}?api-version=6.0`,body:JSON.stringify(t),headers:{...w(this.config,r),"Content-Type":"application/json-patch+json"}})}async setIssueStatus(e,t={}){let{issue:r,status:o}=e,i=[{op:"add",path:"/fields/System.State",value:o.name}];if(!(await this.updateIssue(r,i,t)).body.fields?.["System.State"])throw new Error("Could not set issue status")}async setIssueAssignee(e,t={}){let{issue:r,assignee:o}=e,i=[{op:"add",path:"/fields/System.AssignedTo",value:o?.name??""}];if(!(await this.updateIssue(r,i,t)).body.fields?.["System.State"])throw new Error("Could not set issue assignee")}async setIssueLabels(e,t={}){let{issue:r,labels:o}=e,a=[{op:"replace",path:"/fields/System.Tags",value:o.map(l=>l.name).join(";")}];if(!(await this.updateIssue(r,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:r,project:o}=e;return{data:(await this.config.request({url:`${C(this.config,t)}/${encodeURIComponent(r)}/${encodeURIComponent(o||"")}/_apis/wit/workitemtypes?api-version=6.0`,headers:{...w(this.config,t)}})).body.value}}async getLabelsForProject(e,t={}){let{namespace:r,project:o}=e;return{data:(await this.config.request({url:`${C(this.config,t)}/${encodeURIComponent(r)}/${encodeURIComponent(o||"")}/_apis/wit/tags?api-version=6.0`,headers:{...w(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:r,number:o}=e;if(!r.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let i=await this.config.request({url:`${this.getRepoApiUrl(r.namespace,r.project,r.name,t)}/pullrequests/${o}?api-version=7.1`,headers:w(this.config,t)});return{data:Re(r.namespace,i.body)}}async getPullRequestDescription(e,t={}){let{repo:r,number:o}=e;if(!r.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(r.namespace,r.project,r.name,t)}/pullrequests/${o}?api-version=7.1`,headers:w(this.config,t)})).body?.description??""}}}catch{return{data:{description:null}}}}async setPullRequestDescription(e,t={}){let{repo:r,number:o,description:i}=e;if(!r.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(r.namespace,r.project,r.name,t)}/pullrequests/${o}?api-version=7.1`,headers:{...w(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 r=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:w(this.config,t)});if(!r.body.value?.length)throw new Error("No merge base found between the specified commits.");return{data:r.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 r=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:{...w(this.config,t),Accept:"application/octet-stream"}});return{data:new Blob([r.body])}}async getPullRequestDiff(e,t={}){if(!e.repo.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let r=this.getRepoApiUrl(e.repo.namespace,e.repo.project,e.repo.name,t),o=w(this.config,t),i={...o,Accept:"application/octet-stream"},[a,u]=await Promise.all([this.config.request({url:`${r}/pullrequests/${e.pullRequestId}?api-version=7.1`,headers:o}),this.config.request({url:`${r}/pullrequests/${e.pullRequestId}/iterations?api-version=7.1`,headers:o})]),l=a.body.lastMergeTargetCommit.commitId,p=a.body.lastMergeSourceCommit.commitId,c=u.body.value;if(c.length===0)return"";let d=c[c.length-1],g=1e3,m=[],I=0;for(;;){let S=(await this.config.request({url:`${r}/pullrequests/${e.pullRequestId}/iterations/${d.id}/changes?api-version=7.1&$top=${g}&$skip=${I}`,headers:o})).body.changeEntries??[];if(S.length===0||(m.push(...S),S.length<g))break;I+=S.length}if(m.length===0)return"";let y=5,h=[],v=new TextDecoder,D=P=>P instanceof ArrayBuffer?v.decode(P):typeof P=="string"?P:"",x=async(P,S)=>{try{let Y=await this.config.request({url:`${r}/items?path=${encodeURIComponent(P)}&versionDescriptor[version]=${encodeURIComponent(S)}&versionDescriptor[versionType]=commit&includeContent=true&api-version=7.1`,headers:i});return D(Y.body)}catch{return""}},E=P=>{if(typeof P=="number")return{add:(P&1)!==0,rename:(P&8)!==0,delete:(P&16)!==0};let S=P.toLowerCase().split(",").map(Y=>Y.trim());return{add:S.includes("add"),rename:S.includes("rename"),delete:S.includes("delete")}};for(let P=0;P<m.length;P+=y){let S=m.slice(P,P+y),Y=await Promise.all(S.map(async ne=>{let{add:oe,rename:tt,delete:ee}=E(ne.changeType),fe=ne.originalPath??ne.item.originalPath,A=ne.item.path,qe=ee?A??fe??"":A??"",Bt=tt||ee?fe??qe:qe,[Mr,zr]=await Promise.all([oe?Promise.resolve(""):x(Bt,l),ee?Promise.resolve(""):x(qe,p)]),Hr=oe?"/dev/null":`a${Bt}`,Wr=ee?"/dev/null":`b${qe}`;return(0,Yt.createTwoFilesPatch)(Hr,Wr,Mr,zr)}));h.push(...Y)}return h.join(`
2
- `)}getPullRequestWriteHeaders(e){return{...w(this.config,e),"Content-Type":"application/json"}}setReviewerVote(e,t,r,o,i){return this.config.request({method:"PUT",url:`${e}/pullRequests/${t}/reviewers/${encodeURIComponent(r)}?api-version=7.1`,headers:this.getPullRequestWriteHeaders(i),body:JSON.stringify({vote:o})})}postPullRequestThread(e,t,r,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:r,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 r=this.getRepoApiUrl(e.repo.namespace,e.repo.project,e.repo.name,t),o=w(this.config,t),i=await this.config.request({url:`${r}/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:lt(e.repo.namespace,e.repo.project,e.repo.name,e.pullRequestNumber,u.id,l.id),author:l.author?se(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 r=this.getRepoApiUrl(e.pullRequest.repository.owner.login,e.pullRequest.repository.project,e.pullRequest.repository.name,t);await this.postPullRequestThread(r,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 r=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=pt(e.threadId),c=e.pullRequest.repository.owner.login,d=e.pullRequest.repository.project,g=e.pullRequest.repository.name,m=String(e.pullRequest.id);if(p.namespace!==c||p.project!==d||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 ${c}/${d}/${g} pull request ${m}.`);let y=(await this.config.request({url:`${r}/pullRequests/${e.pullRequest.id}/threads/${p.threadId}?api-version=7.1`,headers:w(this.config,t)})).body.comments?.find(v=>v.parentCommentId===0);if(!y)throw new Error(`Could not determine root comment for Azure DevOps thread ${p.threadId}.`);let h=await this.config.request({method:"POST",url:`${r}/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 lt(c,d,g,Number(m),Number(p.threadId),h.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:`${r}/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 Xt(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 r=Kt(e.commentId),o=this.getRepoApiUrl(r.namespace,r.project,r.repoName,t);await this.config.request({method:"PATCH",url:`${o}/pullRequests/${r.prId}/threads/${r.threadId}/comments/${r.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 r=Kt(e.commentId),o=this.getRepoApiUrl(r.namespace,r.project,r.repoName,t);await this.config.request({method:"DELETE",url:`${o}/pullRequests/${r.prId}/threads/${r.threadId}/comments/${r.commentId}?api-version=7.1`,headers:w(this.config,t)})}async deleteInlineComment(e,t={}){return this.deleteComment(e,t)}async resolveReviewThread(e,t={}){let r=pt(e.threadId),o=this.getRepoApiUrl(r.namespace,r.project,r.repoName,t);await this.config.request({method:"PATCH",url:`${o}/pullRequests/${r.prId}/threads/${r.threadId}?api-version=7.1`,headers:this.getPullRequestWriteHeaders(t),body:JSON.stringify({status:2})})}async unresolveReviewThread(e,t={}){let r=pt(e.threadId),o=this.getRepoApiUrl(r.namespace,r.project,r.repoName,t);await this.config.request({method:"PATCH",url:`${o}/pullRequests/${r.prId}/threads/${r.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 r=e.pullRequest.repository.owner.login,o=this.getRepoApiUrl(r,e.pullRequest.repository.project,e.pullRequest.repository.name,t),i=await this.getCurrentUserId(r,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 r=e.pullRequest.repository.owner.login,o=this.getRepoApiUrl(r,e.pullRequest.repository.project,e.pullRequest.repository.name,t),i=await this.getCurrentUserId(r,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 r=this.getRepoApiUrl(e.pullRequest.repository.owner.login,e.pullRequest.repository.project,e.pullRequest.repository.name,t);await this.postPullRequestThread(r,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:r,project:o,name:i}=e.repo,{pullRequestId:a}=e,u=this.getRepoApiUrl(r,o,i,t),l=w(this.config,t),[p,c]=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})]),d=(h,v)=>lt(r,o,i,a,h,v),g=h=>Xt(r,o,i,a,h),m=new Map;for(let h of c.body.value){if(h.isDeleted)continue;let v=h.comments.filter(A=>!A.isDeleted&&A.commentType!=="system"),D=v.find(A=>A.parentCommentId===0)??v[0];if(!D)continue;let x=D.author?.id;if(!x)continue;let E=v.filter(A=>A.id!==D.id),P=h.threadContext,S=P?.rightFileStart?{side:"RIGHT",start:P.rightFileStart,end:P.rightFileEnd}:P?.leftFileStart?{side:"LEFT",start:P.leftFileStart,end:P.leftFileEnd}:null,Y=S?.end?.line??S?.start.line??null,ne=S?.start&&S.end&&S.start.line!==S.end.line?S.start.line:null,oe=P?.filePath??"",tt=oe.startsWith("/")?oe.slice(1):oe,ee={id:d(h.id,D.id),author:D.author?se(D.author):null,body:D.content??"",createdAt:D.publishedDate?new Date(D.publishedDate):null,url:"",diffLines:[],filename:tt,replies:E.map(A=>({id:d(h.id,A.id),author:A.author?se(A.author):null,body:A.content??"",createdAt:A.publishedDate?new Date(A.publishedDate):null,url:""})),isOutdated:!1,isResolved:as.has(is(h.status)),line:Y,startLine:ne,side:S?.side??null,threadId:g(h.id)},fe=m.get(x);fe?fe.push(ee):m.set(x,[ee])}let I=[],y=new Set;for(let h of p.body.value){if(h.hasDeclined)continue;let v=h.vote??0,D=m.get(h.id);v===0&&!D?.length||(I.push({id:h.id,author:se(h),body:"",createdAt:null,url:"",reviewComments:D??[]}),y.add(h.id))}for(let[h,v]of m){if(y.has(h)||!v.length)continue;let D=v[0].author;D&&I.push({id:h,author:D,body:"",createdAt:null,url:"",reviewComments:v})}return{data:I}}};var U=(s,n={})=>f(n.token||s.token,n.isPAT||s.isPAT);var G="https://api.bitbucket.org/2.0",ds={OPEN:"OPEN",MERGED:"MERGED",DECLINED:"CLOSED"},Ce={owner:4,admin:3,contributor:2,member:1},$e=s=>({id:s.uuid,name:s.display_name||s.nickname,username:s.nickname||s.display_name,email:null,avatarUrl:s.links.avatar.href,url:s.links.html.href}),er=s=>{let n=s.links.clone,e=n?.find(r=>r.name==="ssh"),t=n?.find(r=>r.name==="https");return e&&t?{cloneUrlHTTPS:t.href,cloneUrlSSH:e.href}:null},dt=s=>({id:s.uuid,namespace:s.workspace.slug,name:s.slug,webUrl:s.links.html.href,httpsUrl:s.links.clone.find(n=>n.name==="https")?.href??null,sshUrl:s.links.clone.find(n=>n.name==="ssh")?.href??null,defaultBranch:{name:s.mainbranch.name},permissions:null}),ct=s=>{let n=s.id,e=s.participants?.map(t=>{let r="REVIEW_REQUESTED";return t.approved?r="APPROVED":t.state==="changes_requested"?r="CHANGES_REQUESTED":t.participated_on!==null&&(r="COMMENTED"),{reviewer:$e(t.user),state:r}})??[];return{id:n.toString(),title:s.title,description:s.description,number:n,state:ds[s.state],isDraft:!1,commentCount:s.comment_count,upvoteCount:null,author:$e(s.author),createdDate:new Date(s.created_on),updatedDate:new Date(s.updated_on),closedDate:null,mergedDate:null,repository:{id:s.destination.repository.uuid,name:s.destination.repository.name,owner:{login:s.destination.repository.full_name.split("/")[0]},remoteInfo:er(s.destination.repository)},headCommit:{buildStatuses:null},baseRef:{name:s.destination.branch.name,oid:s.destination.commit.hash},headRef:{name:s.source.branch.name,oid:s.source.commit.hash},url:s.links.html.href,assignees:null,reviews:e,reviewDecision:j(e),additions:null,deletions:null,fileCount:null,commitCount:null,headRepository:{id:s.source.repository.uuid,name:s.source.repository.name,owner:{login:s.source.repository.full_name.split("/")[0]},remoteInfo:er(s.source.repository)},mergeableState:"MERGEABLE",permissions:null}},cs=s=>{switch(s){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}}},ms=s=>{switch(s){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}}},ue=class extends N{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:`${G}/user`,headers:U(this.config,e)});return{data:$e(t.body)}}async getUserForCommit(n,e={}){let r=(await this.config.request({url:`${G}/repositories/${n.repo.namespace}/${n.repo.name}/commit/${n.oid}`,headers:U(this.config,e)})).body.author,o=r.raw.match(/([^<]+)<(.+)>/);return{data:{name:o?o[1].trim():null,email:o?o[2]:null,avatarUrl:r.user?.links.avatar.href||null}}}async getRepo(n,e={}){let t=await this.config.request({url:`${G}/repositories/${n.namespace}/${n.name}`,headers:U(this.config,e)});return{data:dt(t.body)}}async getRepos(n,e={}){let t=[],r=[];return await Promise.all(n.map(async o=>{try{let i=await this.getRepo(o,e);t.push(i.data)}catch(i){r.push({input:o,error:i})}})),{data:t,errors:r}}async getReposForWorkspace(n,e={}){let t=new URL(`${G}/repositories/${encodeURIComponent(n.workspace)}`);t.searchParams.set("page",n.page?.toString()||"1"),t.searchParams.set("pagelen",$.toString()),n.minimumRole&&t.searchParams.set("role",n.minimumRole);let r=await this.config.request({url:t.toString(),headers:U(this.config,e)}),o=!!r.body.next;return{pageInfo:{hasNextPage:o,nextPage:o?r.body.page+1:null},data:r.body.values.map(dt)}}async getAllReposForWorkspace(n,e={}){let t=[],r=1;for(;r!==null;){let o=await this.getReposForWorkspace({workspace:n.workspace,minimumRole:n.minimumRole,page:r},e);t.push(...o.data),r=o.pageInfo.hasNextPage?o.pageInfo.nextPage:null}return t}async getAllReposForWorkspaceWithPermissions(n,e={}){let t=new Map,r=[],o=Ce[n.minimumRole||"member"];o<=Ce.admin&&r.push("admin"),o<=Ce.contributor&&r.push("contributor"),o<=Ce.member&&r.push("member");let i=[];for(let a of r){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:ms(u)}})}}async getReposForCurrentUser(n,e={}){let t=new URL(`${G}/repositories`);t.searchParams.set("role","member"),t.searchParams.set("pagelen",$.toString()),n.cursor&&t.searchParams.set("after",n.cursor);let r=await this.config.request({url:t.toString(),headers:U(this.config,e)}),o=!!r.body.next,i=null;return r.body.next&&(i=new URL(r.body.next).searchParams.get("after")),{pageInfo:{hasNextPage:o,endCursor:i},data:r.body.values.map(dt)}}async getBranches(n,e={}){let t=new URL(`${G}/repositories/${n.repo.namespace}/${n.repo.name}/refs/branches`);t.searchParams.set("page",n.page?.toString()||"1"),t.searchParams.set("pagelen",$.toString());let r=await this.config.request({url:t.toString(),headers:U(this.config,e)}),o=!!r.body.next;return{pageInfo:{hasNextPage:o,nextPage:o?r.body.page+1:null},data:r.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(`${G}/repositories/${n.repo.namespace}/${n.repo.name}/refs/tags`);t.searchParams.set("pagelen",$.toString()),n.cursor&&t.searchParams.set("page",n.cursor);let r=await this.config.request({url:t.toString(),headers:U(this.config,e)}),o=!!r.body.next,i=null;return r.body.next&&(i=new URL(r.body.next).searchParams.get("page")),{pageInfo:{hasNextPage:o,endCursor:i},data:r.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(`${G}/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 r=await this.config.request({url:t.toString(),headers:U(this.config,e)}),o=!!r.body.next;return{pageInfo:{hasNextPage:o,nextPage:o?r.body.page+1:null},data:r.body.values.map(i=>({id:i.workspace.uuid,slug:i.workspace.slug}))}}async getWorkspacesForUser(n,e={}){let t=new URL(`${G}/user/permissions/workspaces`);t.searchParams.set("page",n.page?.toString()||"1"),t.searchParams.set("pagelen","50");let r=await this.config.request({url:t.toString(),headers:U(this.config,e)}),o=!!r.body.next;return{pageInfo:{hasNextPage:o,nextPage:o?r.body.page+1:null},data:r.body.values.map(i=>({id:i.workspace.uuid,slug:i.workspace.slug,name:i.workspace.name}))}}async getPullRequestsForUserAndWorkspace(n,e={}){let t=new URL(`${G}/workspaces/${n.workspaceSlug}/pullrequests/${n.userId}`);if(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","50"),n.repos&&n.repos.length>0){let i=`state = "open" AND (${n.repos.map(a=>`source.repository.full_name = "${a.namespace}/${a.name}"`).join(" OR ")})`;t.searchParams.set("q",i)}let r=await this.config.request({url:t.toString(),headers:U(this.config,e)}),o=!!r.body.next;return{pageInfo:{hasNextPage:o,nextPage:o?r.body.page+1:null},data:r.body.values.map(ct)}}async getPullRequestsForRepoBase(n,e={}){let t=new URL(`${G}/repositories/${encodeURI(n.repo.namespace)}/${encodeURI(n.repo.name)}/pullrequests?state=OPEN`),r=[];n.reviewerId&&r.push(`reviewers.uuid="${n.reviewerId}"`),n.authorLogin&&r.push(`author.uuid="${n.authorLogin}"`);let o='state="OPEN"';return r.length&&(o+=` AND (${r.join(n.useOrFilter?" OR ":" AND ")})`),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","50"),t.searchParams.set("q",o),await this.config.request({url:t.toString(),headers:U(this.config,e)})}async getPullRequestsForRepo(n,e={}){let t=[],r=await this.getPullRequestsForRepoBase(n,e);r.body.values.forEach(i=>{t.push(ct(i))});let o=!!r.body.next;return{pageInfo:{hasNextPage:o,nextPage:o?r.body.page+1:null},data:t}}async getPullRequestsForRepos(n,e={}){let t=[];return await Promise.all(n.repos.map(async r=>{try{(await this.getPullRequestsForRepoBase({repo:r,...n},e)).body.values.forEach(i=>{t.push(ct(i))})}catch(o){if(o.statusCode!==404&&o.statusCode!==401)throw o}})),{data:t}}async getAccountsForWorkspace(n,e={}){let t=new URL(`${G}/workspaces/${encodeURI(n.workspace)}/members`);t.searchParams.set("page",n.page?.toString()||"1"),t.searchParams.set("pagelen","100");let r=await this.config.request({url:t.toString(),headers:U(this.config,e)}),o=!!r.body.next;return{pageInfo:{hasNextPage:o,nextPage:o?r.body.page+1:null},data:r.body.values.map(i=>$e(i.user))}}async getReposPermissionsForCurrentUser(n,e={}){let t=new URL(`${G}/user/permissions/repositories`);t.searchParams.set("page",n.page?.toString()||"1"),t.searchParams.set("pagelen","100");let r=await this.config.request({url:t.toString(),headers:U(this.config,e)}),o=!!r.body.next;return{pageInfo:{hasNextPage:o,nextPage:o?r.body.page+1:null},data:r.body.values.reduce((i,a)=>({...i,[a.repository.uuid]:cs(a.permission)}),{})}}async decorateReposWithPermissions(n,e={}){let t={},r=1;do{let o=await this.getReposPermissionsForCurrentUser({page:r},e);t={...o.data,...t},r=o.pageInfo.hasNextPage?o.pageInfo.nextPage:null}while(r!==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:`${G}/repositories/${t.repository.owner.login}/${t.repository.name}/pullrequests/${t.id}/decline`,headers:U(this.config,e)})).body.title)throw new Error("Could not close pull request")}async mergePullRequest(n,e={}){let{pullRequest:t,mergeStrategy:r}=n,o;switch(r){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:`${G}/repositories/${t.repository.owner.login}/${t.repository.name}/pullrequests/${t.id}/merge`,body:JSON.stringify(i),headers:{...U(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:r}=n,o={reviewers:r.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:`${G}/repositories/${t.repository.owner.login}/${t.repository.name}/pullrequests/${t.id}`,body:JSON.stringify(o),headers:{...U(this.config,e),"Content-Type":"application/json"}})).body.title)throw new Error("Could not set pull request reviewers")}};var tr=s=>s?s.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}:s.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 Ie=s=>{let n=s.links.self[0].href;return{name:s.displayName,email:s.emailAddress,avatarUrl:s.avatarUrl??(n&&`${n}/avatar.png`),id:s.id.toString(),username:s.name,url:n}},De=s=>{let n={OPEN:"OPEN",MERGED:"MERGED",DECLINED:"CLOSED"},e={UNAPPROVED:"REVIEW_REQUESTED",NEEDS_WORK:"CHANGES_REQUESTED",APPROVED:"APPROVED"},t=s.reviewers.map(u=>({reviewer:Ie(u.user),state:e[u.status]})),r=s.toRef.repository.links.clone.find(u=>u.name==="ssh")?.href??null,o=s.toRef.repository.links.clone.find(u=>u.name==="https")?.href??null;o||(o=s.toRef.repository.links.clone.find(u=>u.name==="http")?.href??null);let i=s.fromRef.repository.links.clone.find(u=>u.name==="ssh")?.href??null,a=s.fromRef.repository.links.clone.find(u=>u.name==="https")?.href??null;return a||(a=s.fromRef.repository.links.clone.find(u=>u.name==="http")?.href??null),{id:s.id.toString(),number:s.id,title:s.title,description:s.description,url:s.links.self[0].href,state:n[s.state],isDraft:!1,createdDate:new Date(s.createdDate),updatedDate:new Date(s.updatedDate),closedDate:s.closedDate?new Date(s.closedDate):null,mergedDate:s.state=="MERGED"&&s.closedDate?new Date(s.closedDate):null,baseRef:{name:s.toRef.displayId,oid:s.toRef.latestCommit},headRef:{name:s.fromRef.displayId,oid:s.fromRef.latestCommit},commentCount:s.properties.commentCount,upvoteCount:null,commitCount:null,fileCount:null,additions:null,deletions:null,author:Ie(s.author.user),assignees:null,reviews:t,reviewDecision:j(t),repository:{id:s.toRef.repository.id.toString(),name:s.toRef.repository.name,owner:{login:s.toRef.repository.project.key},remoteInfo:o&&r?{cloneUrlHTTPS:o,cloneUrlSSH:r}:null},headRepository:{id:s.fromRef.repository.id.toString(),name:s.fromRef.repository.name,owner:{login:s.fromRef.repository.project.key},remoteInfo:a&&i?{cloneUrlHTTPS:a,cloneUrlSSH:i}:null},headCommit:null,mergeableState:"MERGEABLE",permissions:null,version:s.version}},rr=s=>({id:s.id.toString(),namespace:s.project.key,name:s.slug,webUrl:s.links.self[0]?.href??null,httpsUrl:s.links.clone.find(n=>n.name==="https"||n.name==="http")?.href??null,sshUrl:s.links.clone.find(n=>n.name==="ssh")?.href??null,defaultBranch:null,permissions:null}),le=class extends _{getBaseUrl(n){let e=n.baseUrl||this.config.baseUrl;if(!e)throw new Error('Bitbucket Server requires "baseUrl"');return e}getRequestHeaders(n){return f(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":r,"x-ausername":o}}=t,i=r?parseInt(r,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:c,name:d,slug:g})=>i?i===c:a===d||a===p||a===g);if(!l)throw new Error("Could not find current Bitbucket Server user");return{data:Ie(l)}}async getUserForCommit(n,e){let{repo:t,oid:r}=n,o=await this.config.request({url:`${this.getBaseUrl(e)}/projects/${t.namespace}/repos/${t.name}/commits/${r}`,headers:this.getRequestHeaders(e)});if(!o.body.author)throw new Error("Could not find user for commit");return{data:Ie(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:rr(t.body)}}async getRepos(n,e={}){let t=[],r=[];return await Promise.all(n.map(async o=>{try{let i=await this.getRepo(o,e);t.push(i.data)}catch(i){r.push({input:o,error:i})}})),{data:t,errors:r}}async getReposForCurrentUser(n,e={}){let t=n.page??0,r=await this.config.request({url:`${this.getBaseUrl(e)}/repos?start=${t}`,headers:this.getRequestHeaders(e)});return{pageInfo:{hasNextPage:!r.body.isLastPage,nextPage:r.body.nextPageStart},data:r.body.values.map(rr)}}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 r=await this.config.request({url:t.toString(),headers:this.getRequestHeaders(e)});return{data:tr(r.body.values)}}catch(r){if(r.response?.status===401)return{data:{canCreateWebhook:!1,canPush:!1,isAdmin:!1}};throw r}}async decorateReposWithPermissions(n,e={}){return await Promise.all(n.repos.map(async r=>{let o=await this.getRepoPermissionsForUsername({repo:r,username:n.username},e);return{...r,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?state=OPEN`);return t.searchParams.set("start",n.page?.toString()||"0"),t.searchParams.set("limit","50"),await this.config.request({url:t.toString(),headers:this.getRequestHeaders(e)})}async getPullRequestsForRepo(n,e={}){let t=[],r=await this.getPullRequestsForRepoBase(n,e);r.body.values.forEach(i=>{if(n.authorLogin&&i.author.user.name!==n.authorLogin)return null;t.push(De(i))});let o=r.body.values.length!==0;return{pageInfo:{hasNextPage:o,nextPage:o?r.body.start+r.body.values.length:null},data:t}}async getPullRequestsForRepos(n,e={}){let t=[];return await Promise.all(n.repos.map(async r=>{try{(await this.getPullRequestsForRepoBase({repo:r,...n},e)).body.values.forEach(i=>{if(n.authorLogin&&i.author.user.name!==n.authorLogin)return null;t.push(De(i))})}catch(o){if(o.statusCode!==404&&o.statusCode!==401)throw o}})),{data:t}}async getPullRequestsForCurrentUser(n,e={}){let t=new URL(`${this.getBaseUrl(e)}/dashboard/pull-requests`);t.searchParams.set("state","OPEN"),t.searchParams.set("start",n.page?.toString()||"0"),t.searchParams.set("limit","50");let r=await this.config.request({url:t.toString(),headers:this.getRequestHeaders(e)}),o=r.body.values.length!==0;return{pageInfo:{hasNextPage:o,nextPage:o?r.body.start+r.body.values.length:null},data:r.body.values.map(De)}}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:r}=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:r,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:r}=n;if(t.version===void 0)throw new Error('Bitbucket Server requires "version" for this function.');let o={reviewers:r.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 r=await this.config.request({url:t.toString(),headers:this.getRequestHeaders(e)}),o=r.body.values.length!==0;return{pageInfo:{hasNextPage:o,nextPage:o?r.body.start+r.body.values.length:null},data:r.body.values.map(i=>Ie(i.user))}}};var Rr=require("js-base64");var Le=(e=>(e.Open="OPEN",e.Closed="CLOSED",e))(Le||{});var R=class extends Error{constructor(e,t){let r=t?.map(i=>`'${i.message}'`).join(", "),o=r?`${e}: ${r}`:e;super(o);this.graphQLErrors=t??[]}};var gs={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]},sr=15,nr=100,be={__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"},O=s=>!!s,Q=(s,n)=>{let e=gs[n];for(let t=0;t<3;t++){if(s[t]>e[t])return!0;if(s[t]<e[t])return!1}return!0},Ae="https://api.github.com",hs=`${Ae}/graphql`,Ge=`
1
+ "use strict";var ut=Object.defineProperty;var gs=Object.getOwnPropertyDescriptor;var hs=Object.getOwnPropertyNames;var fs=Object.prototype.hasOwnProperty;var Rs=(r,n)=>{for(var e in n)ut(r,e,{get:n[e],enumerable:!0})},Is=(r,n,e,t)=>{if(n&&typeof n=="object"||typeof n=="function")for(let s of hs(n))!fs.call(r,s)&&s!==e&&ut(r,s,{get:()=>n[s],enumerable:!(t=gs(n,s))||t.enumerable});return r};var bs=r=>Is(ut({},"__esModule",{value:!0}),r);var uo={};Rs(uo,{AzureDevOps:()=>de,Bitbucket:()=>ce,BitbucketServer:()=>me,EntityIdentifierProviderType:()=>us,EntityType:()=>as,EntityVersion:()=>is,GitBuildStatusStage:()=>Xt,GitBuildStatusState:()=>Le,GitDiffLineType:()=>lt,GitHub:()=>ge,GitHubIssueCloseReason:()=>ls,GitIssueState:()=>ie,GitLab:()=>fe,GitMergeStrategy:()=>pe,GitPullRequestMergeableState:()=>oe,GitPullRequestReviewState:()=>Y,GitPullRequestState:()=>Z,GraphQLErrors:()=>I,Jira:()=>Re,JiraServer:()=>Ie,PullRequestAsyncStatus:()=>os,Trello:()=>be,default:()=>ao,isFetch:()=>Ue});module.exports=bs(uo);var ur=require("diff");var Xt=(s=>(s.Build="build",s.Production="production",s.Staging="staging",s.Test="test",s))(Xt||{}),Le=(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))(Le||{}),pe=(o=>(o.MergeCommit="MERGE_COMMIT",o.Rebase="REBASE",o.RebaseThenMergeCommit="REBASE_THEN_MERGE_COMMIT",o.FastForward="FAST_FORWARD",o.Squash="SQUASH",o))(pe||{}),Z=(t=>(t.Open="OPEN",t.Closed="CLOSED",t.Merged="MERGED",t))(Z||{}),Y=(s=>(s.Approved="APPROVED",s.ChangesRequested="CHANGES_REQUESTED",s.Commented="COMMENTED",s.ReviewRequested="REVIEW_REQUESTED",s))(Y||{}),oe=(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))(oe||{}),lt=(t=>(t.ADDED="ADDED",t.DELETED="DELETED",t.UNMODIFIED="UNMODIFIED",t))(lt||{});var Zt={APPROVED:0,COMMENTED:1,REVIEW_REQUESTED:2,CHANGES_REQUESTED:3},B=r=>!r||r.length===0?null:r.reduce((n,e)=>Zt[e.state]>Zt[n]?e.state:n,"APPROVED");var R=(r,n)=>{let e={};return r&&(e.Authorization=`${n?"Basic":"Bearer"} ${r}`),e},Yt=r=>r?r.reduce((n,e)=>(n[e]=!0,n),{}):void 0,ee=(r,n,e)=>!r||n.some(t=>r[t])?e:"",er=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 pt(r){return(await Promise.allSettled(r)).map(e=>ys(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))};function ys(r,n=void 0){return r?.status==="fulfilled"?r.value:n}async function tr(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 ie=(e=>(e.Open="OPEN",e.Closed="CLOSED",e))(ie||{});var dt=(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))(dt||{});var L=100;var rr=globalThis.fetch;var Ps=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},ct=r=>async({url:n,...e})=>{let t=await r(n,e);return Ps(t)};var Ue=(r,n=!1)=>r.name==="fetch"||n;var j=class{constructor(n){let e=n?.request||rr;this.config={...n,request:Ue(e,n?.forceIsFetch)?ct(e):e}}updateConfig(n){this.config={...this.config,...n,request:n.request&&Ue(n.request,n?.forceIsFetch??this.config.forceIsFetch)?ct(n.request):this.config.request}}},N=class extends j{};var ws="https://app.vssps.visualstudio.com/_apis",qs="https://vssps.dev.azure.com/",Ss="https://dev.azure.com",q=(r,n={})=>R(n.token||r.token,n.isPAT||r.isPAT),sr=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/"),mt=(r,n)=>{let e=n.baseUrl||r.baseUrl||ws;return e=e.replace(/\/$/,""),e},C=(r,n)=>{let e=n.baseUrl||r.baseUrl||Ss;return e=e.replace(/\/$/,""),e},gt=(r,n)=>{let e=n.baseUrl||r.baseUrl||qs;return e=e.replace(/\/$/,""),e};var vs={active:"OPEN",completed:"MERGED",abandoned:"CLOSED"},Es={OPEN:"active",MERGED:"completed",CLOSED:"abandoned"},Ae=100,Cs=200,$s=200,nr=r=>{if(!r||r.length===0)return"active";let n=Array.from(new Set(r.map(e=>Es[e])));return n.length===1?n[0]:"all"},Ds=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] = ''"]},Ls=r=>{if(typeof r!="string")return r;let n=r.charAt(0).toUpperCase()+r.slice(1);return dt[n]??0},Us=new Set([2,3,4,5]),As={10:"APPROVED",5:"APPROVED",0:"REVIEW_REQUESTED",[-5]:"CHANGES_REQUESTED",[-10]:"CHANGES_REQUESTED"},ae=r=>({id:r.id,name:r.displayName??null,username:(r.uniqueName||r.displayName)??null,email:null,avatarUrl:r.imageUrl??null,url:null}),Ge=r=>r.startsWith("refs/heads/")?r.replace("refs/heads/",""):r,Gs=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"}},ht=(r,n,e,t,s,o)=>`${r}|${n}|${e}|${t}|${s}|${o}`,or=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]}},ir=(r,n,e,t,s)=>`${r}|${n}|${e}|${t}|${s}`,ft=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]}},Pe=(r,n,e)=>{let t=!!n.forkSource,s=[],o=[];return n.reviewers.forEach(i=>{let a={reviewer:ae(i),state:As[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:vs[n.status],isDraft:n.isDraft,commentCount:null,upvoteCount:null,author:ae(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:Ge(n.targetRefName),oid:n.lastMergeTargetCommit.commitId},headRef:{name:Ge(n.sourceRefName),oid:n.lastMergeSourceCommit.commitId},url:sr(n),assignees:n.reviewers.map(ae),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:Gs(n.mergeStatus),labels:n.labels?.map(i=>({color:null,description:null,id:i.id,name:i.name}))??[],permissions:null}},ar=(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:Ge(n.defaultBranch)}:null,permissions:null}),Ts=(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()}))??[]}},de=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=`${mt(this.config,t)}/profile/profiles/me`,o=await this.config.request({url:s,headers:q(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:q(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:q(this.config,t)})).body.author;return{data:{name:o.name,email:o.email,avatarUrl:o.imageUrl}}}async getOrgsForUser(e,t={}){let s=`${mt(this.config,t)}/accounts?memberId=${e.userId}&api-version=6.0`;return{data:(await this.config.request({url:s,headers:q(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:q(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:q(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:`${gt(this.config,t)}/${encodeURIComponent(s)}/_apis/graph/descriptors/${o}?api-version=6.0`,headers:q(this.config,t)})).body.value}}}async getAzureGraphAccountsForAzureProject(e,t={}){let{namespace:s,projectScopeDescriptor:o,cursor:i}=e,a=new URL(`${gt(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:q(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:q(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:q(this.config,t)});return{data:ar(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:q(this.config,t)})).body.value.map(o=>ar(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:q(this.config,s)}),a=i.headers["x-ms-continuationtoken"];return{pageInfo:{hasNextPage:!!a,endCursor:a||null},data:i.body.value.map(u=>({name:Ge(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 tr([...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:q(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=Ae){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=${nr(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=${d}&%24skip=${(p-1)*d}`,headers:q(this.config,t)})}async getPullRequestsForRepo(e,t={}){let s=U(e.pageSize,{fallback:Ae}),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=>Pe(e.repo.namespace,l,u)),e.states)}}async getPullRequestsForRepos(e,t={}){if(!e.repos.every(u=>u.project))throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let{repos:s}=e||{},o=[];await Promise.all(s.map(async u=>{try{let l=await this.getPullRequestsForRepoBase({repo:u,...e},t);o.push({namespace:u.namespace,pullRequests:l.body.value})}catch(l){if(l.statusCode!==404&&l.statusCode!==401)throw l}}));let i=await this.fetchRemoteInfoByRepoId(e.includeRemoteInfo,o,t),a=o.flatMap(({namespace:u,pullRequests:l})=>l.map(p=>Pe(u,p,i)));return{data:k(a,e.states)}}async getPullRequestsForProjectBase(e,t={},s=Ae){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(`${C(this.config,t)}/${encodeURIComponent(o)}/${encodeURIComponent(i)}/_apis/git/pullRequests`);return h.searchParams.set("searchCriteria.status",nr(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:q(this.config,t)})}async getPullRequestsForProject(e,t={}){let s=U(e.pageSize,{fallback:Ae}),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=>Pe(e.namespace,l,u))||[],e.states)}}async getPullRequestsForProjects(e,t={}){let{projects:s}=e||{},o=[];await Promise.all(s.map(async u=>{try{if(!e.repo||e.repo.project&&e.repo.project===u.project){let l=await this.getPullRequestsForProjectBase({...u,...e},t);l&&o.push({namespace:u.namespace,pullRequests:l.body.value})}}catch(l){if(l.statusCode!==404&&l.statusCode!==401)throw l}}));let i=await this.fetchRemoteInfoByRepoId(e.includeRemoteInfo,o,t),a=o.flatMap(({namespace:u,pullRequests:l})=>l.map(p=>Pe(u,p,i)));return{data:k(a,e.states)}}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:{...q(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:{...q(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:{...q(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:{...q(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:{...q(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:{...q(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:Cs}),$s),c=["[System.TeamProject] = @project",...Ds(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:{...q(this.config,t),"Content-Type":"application/json"}}),h=m.body.workItems.slice((p-1)*d,d*p).map(D=>D.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 S=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:{...q(this.config,t),"Content-Type":"application/json"}});return{pageInfo:{hasNextPage:P,nextPage:P?p+1:null,currentPage:p,totalCount:y,totalPages:f},data:S.body.value.map(D=>Ts(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=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:`${C(this.config,t)}/${encodeURIComponent(s)}/_apis/security/permissionevaluationbatch?api-version=7.0`,body:JSON.stringify(u),headers:{...q(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:`${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:{...q(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:{...q(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:{...q(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:q(this.config,t)}),a=await this.fetchRemoteInfoByRepoId(e.includeRemoteInfo,[{namespace:s.namespace,pullRequests:[i.body]}],t);return{data:Pe(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:q(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:{...q(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:q(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:{...q(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=q(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,S=w=>w instanceof ArrayBuffer?P.decode(w):typeof w=="string"?w:"",D=async(w,E)=>{try{let se=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 S(se.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(se=>se.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),se=await Promise.all(E.map(async ue=>{let{add:le,rename:at,delete:ne}=$(ue.changeType),ye=ue.originalPath??ue.item.originalPath,T=ue.item.path,De=ne?T??ye??"":T??"",Kt=at||ne?ye??De:De,[ps,ds]=await Promise.all([le?Promise.resolve(""):D(Kt,l),ne?Promise.resolve(""):D(De,p)]),cs=le?"/dev/null":`a${Kt}`,ms=ne?"/dev/null":`b${De}`;return(0,ur.createTwoFilesPatch)(cs,ms,ps,ds)}));f.push(...se)}return f.join(`
2
+ `)}getPullRequestWriteHeaders(e){return{...q(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=q(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:ht(e.repo.namespace,e.repo.project,e.repo.name,e.pullRequestNumber,u.id,l.id),author:l.author?ae(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=ft(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:q(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 ht(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 ir(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=or(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=or(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:q(this.config,t)})}async deleteInlineComment(e,t={}){return this.deleteComment(e,t)}async resolveReviewThread(e,t={}){let s=ft(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=ft(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=q(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)=>ht(s,o,i,a,f,P),g=f=>ir(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"),S=P.find(T=>T.parentCommentId===0)??P[0];if(!S)continue;let D=S.author?.id;if(!D)continue;let $=P.filter(T=>T.id!==S.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,se=E?.end?.line??E?.start.line??null,ue=E?.start&&E.end&&E.start.line!==E.end.line?E.start.line:null,le=w?.filePath??"",at=le.startsWith("/")?le.slice(1):le,ne={id:c(f.id,S.id),author:S.author?ae(S.author):null,body:S.content??"",createdAt:S.publishedDate?new Date(S.publishedDate):null,url:"",diffLines:[],filename:at,replies:$.map(T=>({id:c(f.id,T.id),author:T.author?ae(T.author):null,body:T.content??"",createdAt:T.publishedDate?new Date(T.publishedDate):null,url:""})),isOutdated:!1,isResolved:Us.has(Ls(f.status)),line:se,startLine:ue,side:E?.side??null,threadId:g(f.id)},ye=m.get(D);ye?ye.push(ne):m.set(D,[ne])}let h=[],y=new Set;for(let f of p.body.value){if(f.hasDeclined)continue;let P=f.vote??0,S=m.get(f.id);P===0&&!S?.length||(h.push({id:f.id,author:ae(f),body:"",createdAt:null,url:"",reviewComments:S??[]}),y.add(f.id))}for(let[f,P]of m){if(y.has(f)||!P.length)continue;let S=P[0].author;S&&h.push({id:f,author:S,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",Os={OPEN:"OPEN",MERGED:"MERGED",DECLINED:"CLOSED",SUPERSEDED:"CLOSED"},_s={OPEN:["OPEN"],MERGED:["MERGED"],CLOSED:["DECLINED","SUPERSEDED"]},Te=50,lr=r=>{let n=!r||r.length===0?["OPEN"]:Array.from(new Set(r.flatMap(t=>_s[t]))),e=n.map(t=>`state="${t}"`).join(" OR ");return n.length>1?`(${e})`:e},xs=r=>r.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),pr=r=>{let n=r?.trim();if(!n)return null;let e=xs(n);return`(title ~ "${e}" OR description ~ "${e}")`},dr=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}},Oe={owner:4,admin:3,contributor:2,member:1},_e=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}),cr=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},Rt=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}),It=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:_e(t.user),state:s}})??[];return{id:n.toString(),title:r.title,description:r.description,number:n,state:Os[r.state],isDraft:!1,commentCount:r.comment_count,upvoteCount:null,author:_e(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:cr(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:cr(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}}},Ns=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}}},ce=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:_e(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:Rt(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(Rt)}}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=Oe[n.minimumRole||"member"];o<=Oe.admin&&s.push("admin"),o<=Oe.contributor&&s.push("contributor"),o<=Oe.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:Ns(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(Rt)}}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",U(n.pageSize,{fallback:Te,max:Te}).toString());let s=[lr(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=pr(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:dr(i.body),data:i.body.values.map(It)}}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=lr(n.states);s.length&&(o+=` AND (${s.join(n.useOrFilter?" OR ":" AND ")})`);let i=pr(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:Te,max:Te}).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(It(o))}),{pageInfo:dr(s.body),data:t}}async getPullRequestsForRepos(n,e={}){let t=[];return await Promise.all(n.repos.map(async s=>{try{(await this.getPullRequestsForRepoBase({repo:s,...n},e)).body.values.forEach(i=>{t.push(It(i))})}catch(o){if(o.statusCode!==404&&o.statusCode!==401)throw o}})),{data:t}}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=>_e(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 mr=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 we=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}},xe=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:we(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:we(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}},gr=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}),hr=50,Fs={OPEN:"OPEN",MERGED:"MERGED",CLOSED:"DECLINED"},fr=r=>{if(!r||r.length===0)return"OPEN";let n=Array.from(new Set(r.map(e=>Fs[e])));return n.length===1?n[0]:"ALL"},Rr=(r,n)=>typeof r!="number"||n<=0?null:Math.floor(r/n)+1,me=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:we(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:we(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:gr(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(gr)}}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:mr(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",fr(n.states)),t.searchParams.set("start",n.page?.toString()||"0"),t.searchParams.set("limit",U(n.pageSize,{fallback:hr}).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(xe(i))});let o=!s.body.isLastPage;return{pageInfo:{hasNextPage:o,nextPage:o?s.body.nextPageStart:null,currentPage:Rr(s.body.start,s.body.limit)},data:k(t,n.states)}}async getPullRequestsForRepos(n,e={}){let t=[];return await Promise.all(n.repos.map(async s=>{try{(await this.getPullRequestsForRepoBase({repo:s,...n},e)).body.values.forEach(i=>{if(n.authorLogin&&i.author.user.name!==n.authorLogin)return null;t.push(xe(i))})}catch(o){if(o.statusCode!==404&&o.statusCode!==401)throw o}})),{data:k(t,n.states)}}async getPullRequestsForCurrentUser(n,e={}){let t=new URL(`${this.getBaseUrl(e)}/dashboard/pull-requests`);t.searchParams.set("state",fr(n.states)),t.searchParams.set("start",n.page?.toString()||"0");let s=U(n.pageSize,{fallback:hr});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:Rr(o.body.start,o.body.limit)},data:k(o.body.values.map(xe),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=>we(i.user))}}};var Tr=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 js={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]},Ir=15,br=100,qe={__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=js[n];for(let t=0;t<3;t++){if(r[t]>e[t])return!0;if(r[t]<e[t])return!1}return!0},Ne="https://api.github.com",Qs=`${Ne}/graphql`,Fe=`
3
3
  description
4
4
  dueOn
5
5
  id
@@ -7,7 +7,7 @@ number
7
7
  state
8
8
  title
9
9
  url
10
- `,fs=`
10
+ `,Bs=`
11
11
  ... on CheckRun {
12
12
  completedAt
13
13
  conclusion
@@ -16,63 +16,63 @@ url
16
16
  permalink
17
17
  startedAt
18
18
  }
19
- `,Ue=/\/api\/v\d+$/,Te=`
19
+ `,ke=/\/api\/v\d+$/,je=`
20
20
  color
21
21
  description
22
22
  id
23
23
  name
24
- `,or=s=>{if(s.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.")},Rs=(s,n)=>{let e=n.baseUrl||s.baseUrl;return e?(e=e.replace(/\/$/,""),or(e),Ue.test(e)&&(e=e.replace(Ue,"")),`${e}/api/graphql`):hs},B=(s,n)=>{let e=n.baseUrl||s.baseUrl;return e?(e=e.replace(/\/$/,""),or(e),Ue.test(e)&&(e=e.replace(Ue,"")),`${e}/api/v3`):Ae},b=(s,n,e)=>{let t=f(e.token||s.token);return t["X-Github-Next-Global-ID"]="1",t["Content-Type"]="application/json",t.Accept="application/vnd.github.merge-info-preview+json",s.request({url:Rs(s,e),method:"POST",headers:t,body:JSON.stringify(n)})},Is={user:!0,"user:email":!0,"read:user":!0},H=s=>s.some(n=>Is[n]),k=(s=!1,n=!1,e)=>`
24
+ `,yr=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.")},Ms=(r,n)=>{let e=n.baseUrl||r.baseUrl;return e?(e=e.replace(/\/$/,""),yr(e),ke.test(e)&&(e=e.replace(ke,"")),`${e}/api/graphql`):Qs},z=(r,n)=>{let e=n.baseUrl||r.baseUrl;return e?(e=e.replace(/\/$/,""),yr(e),ke.test(e)&&(e=e.replace(ke,"")),`${e}/api/v3`):Ne},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:Ms(r,e),method:"POST",headers:t,body:JSON.stringify(n)})},zs={user:!0,"user:email":!0,"read:user":!0},J=r=>r.some(n=>zs[n]),F=(r=!1,n=!1,e)=>`
25
25
  __typename
26
- ${X(e,["graphQLId"],"id")}
27
- ${X(e,["id"],"databaseId")}
28
- ${X(e,["name"],"name")}
29
- ${X(e,["name","username"],"login")}
30
- ${n?X(e,["email"],"email"):""}
31
- ${X(e,["avatarUrl"],`avatarUrl${s?"(size: $avatarSize)":""}`)}
32
- ${X(e,["url"],"url")}
33
- `,bs=(s=!1)=>`
26
+ ${ee(e,["graphQLId"],"id")}
27
+ ${ee(e,["id"],"databaseId")}
28
+ ${ee(e,["name"],"name")}
29
+ ${ee(e,["name","username"],"login")}
30
+ ${n?ee(e,["email"],"email"):""}
31
+ ${ee(e,["avatarUrl"],`avatarUrl${r?"(size: $avatarSize)":""}`)}
32
+ ${ee(e,["url"],"url")}
33
+ `,Hs=(r=!1)=>`
34
34
  latestReviews(first: 100) {
35
35
  nodes {
36
36
  author {
37
37
  ... on User {
38
- ${k(!1,s)}
38
+ ${F(!1,r)}
39
39
  }
40
40
  ... on EnterpriseUserAccount {
41
- ${mt(!1)}
41
+ ${bt(!1)}
42
42
  }
43
43
  }
44
44
  state
45
45
  }
46
46
  }
47
- `,ir=(s=!1)=>`
47
+ `,Pr=(r=!1)=>`
48
48
  __typename
49
49
  id
50
50
  databaseId
51
51
  login
52
- avatarUrl${s?"(size: $avatarSize)":""}
52
+ avatarUrl${r?"(size: $avatarSize)":""}
53
53
  url
54
- `,mt=(s=!1)=>`
54
+ `,bt=(r=!1)=>`
55
55
  __typename
56
56
  id
57
57
  login
58
- avatarUrl${s?"(size: $avatarSize)":""}
58
+ avatarUrl${r?"(size: $avatarSize)":""}
59
59
  url
60
- `,Oe=(s,n=!1,e)=>`
60
+ `,Qe=(r,n=!1,e)=>`
61
61
  id
62
- ${!e||Q(e,"PR_FULL_DATABASE_ID")?"fullDatabaseId":"databaseId"}
62
+ ${!e||M(e,"PR_FULL_DATABASE_ID")?"fullDatabaseId":"databaseId"}
63
63
  number
64
64
  title
65
65
  body
66
66
  state
67
67
  author {
68
68
  ... on User {
69
- ${k(!1,n)}
69
+ ${F(!1,n)}
70
70
  }
71
71
  ... on Bot {
72
- ${ir(!1)}
72
+ ${Pr(!1)}
73
73
  }
74
74
  ... on EnterpriseUserAccount {
75
- ${mt(!1)}
75
+ ${bt(!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||Q(e,"CHECK_RUN")?fs:""}
88
+ ${!e||M(e,"CHECK_RUN")?Bs:""}
89
89
  ... on StatusContext {
90
90
  context
91
91
  createdAt
@@ -132,8 +132,9 @@ headRepository {
132
132
  }
133
133
  url
134
134
  sshUrl
135
+ isFork
135
136
  }
136
- ${s?"isDraft":""}
137
+ ${r?"isDraft":""}
137
138
  url
138
139
  createdAt
139
140
  comments {
@@ -147,47 +148,47 @@ closedAt
147
148
  mergedAt
148
149
  assignees(first: 100) {
149
150
  nodes {
150
- ${k(!1,n)}
151
+ ${F(!1,n)}
151
152
  }
152
153
  }
153
154
  reviewRequests(first: 100) {
154
155
  nodes {
155
- ${!e||Q(e,"AS_CODE_OWNER")?"asCodeOwner":""}
156
+ ${!e||M(e,"AS_CODE_OWNER")?"asCodeOwner":""}
156
157
  requestedReviewer {
157
158
  ... on User {
158
- ${k(!1,n)}
159
+ ${F(!1,n)}
159
160
  }
160
161
  }
161
162
  }
162
163
  }
163
- ${!e||Q(e,"LATEST_REVIEWS")?bs(n):""}
164
+ ${!e||M(e,"LATEST_REVIEWS")?Hs(n):""}
164
165
  additions
165
166
  deletions
166
167
  changedFiles
167
168
  mergeable
168
169
  mergeStateStatus
169
170
  milestone {
170
- ${Ge}
171
+ ${Fe}
171
172
  }
172
173
  labels(first: 100) {
173
174
  nodes {
174
- ${Te}
175
+ ${je}
175
176
  }
176
177
  }
177
- ${!e||Q(e,"VIEWER_CAN_MERGE_AS_ADMIN")?"viewerCanMergeAsAdmin":""}
178
- `,ys=(s=!1,n)=>`
178
+ ${!e||M(e,"VIEWER_CAN_MERGE_AS_ADMIN")?"viewerCanMergeAsAdmin":""}
179
+ `,Ws=(r=!1,n)=>`
179
180
  id
180
- ${!n||Q(n,"ISSUE_FULL_DATABASE_ID")?"fullDatabaseId":"databaseId"}
181
+ ${!n||M(n,"ISSUE_FULL_DATABASE_ID")?"fullDatabaseId":"databaseId"}
181
182
  title
182
183
  author {
183
184
  ... on User {
184
- ${k(!1,s)}
185
+ ${F(!1,r)}
185
186
  }
186
187
  ... on Bot {
187
- ${ir(!1)}
188
+ ${Pr(!1)}
188
189
  }
189
190
  ... on EnterpriseUserAccount {
190
- ${mt(!1)}
191
+ ${bt(!1)}
191
192
  }
192
193
  }
193
194
  closedAt
@@ -211,19 +212,19 @@ comments {
211
212
  }
212
213
  assignees(first: 100) {
213
214
  nodes {
214
- ${k(!1,s)}
215
+ ${F(!1,r)}
215
216
  }
216
217
  }
217
218
  state
218
219
  milestone {
219
- ${Ge}
220
+ ${Fe}
220
221
  }
221
222
  labels(first: 100) {
222
223
  nodes {
223
- ${Te}
224
+ ${je}
224
225
  }
225
226
  }
226
- `,Ps={"-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"},ws=new RegExp('(([^\\s]+:)?\\"(?:[^\\"\\\\]|\\\\.)*\\"?)|([^\\"\\s]+)',"g"),gt=s=>{let n=[];return(s.match(ws)??[]).forEach(t=>{if(t.includes(":")&&t!="is:closed"){let r=t.split(":")[0];Ps[r]&&n.push(t)}}),n},ht=(s,n,e,t)=>{let r=s==="issue";return{query:`
227
+ `,Js={"-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"},Vs=new RegExp('(([^\\s]+:)?\\"(?:[^\\"\\\\]|\\\\.)*\\"?)|([^\\"\\s]+)',"g"),yt=r=>{let n=[];return(r.match(Vs)??[]).forEach(t=>{if(t.includes(":")&&t!="is:closed"){let s=t.split(":")[0];Js[s]&&n.push(t)}}),n},Pt="is:open",wr=r=>{if(!r||r.length===0)return Pt;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"},qr=r=>{if(!r||r.length===0)return Pt;let n=new Set(r),e=n.has("OPEN"),t=n.has("CLOSED");return e&&t?"":t?"is:closed":"is:open"},wt=(r,n,e,t)=>{let s=r==="issue",o=t.stateQualifier??Pt;return{query:`
227
228
  query SearchIssuesOrPullRequests($query: String! $after: String) {
228
229
  search(type:ISSUE query:$query first: ${t.maxPageSize} after:$after) {
229
230
  pageInfo {
@@ -231,19 +232,19 @@ query SearchIssuesOrPullRequests($query: String! $after: String) {
231
232
  endCursor
232
233
  }
233
234
  nodes {
234
- ... on ${r?"Issue":"PullRequest"} {
235
- ${r?ys(t.supportsEmail,t.enterpriseVersion??null):Oe(t.supportsDrafts??!1,t.supportsEmail,t.enterpriseVersion??null)}
235
+ ... on ${s?"Issue":"PullRequest"} {
236
+ ${s?Ws(t.supportsEmail,t.enterpriseVersion??null):Qe(t.supportsDrafts??!1,t.supportsEmail,t.enterpriseVersion??null)}
236
237
  }
237
238
  }
238
239
  }
239
- }`,variables:{query:`is:${s} is:open ${t.includeFromArchivedRepos?"":"archived:false"} ${n}`,after:e}}},qs="Field 'isDraft' doesn't exist on type 'PullRequest'",xe=(s=[])=>s.some(n=>n?.message===qs),vs=/@@ -(\d+)(?:,\d+ | )\+(\d+)(?:,\d+ | )@@(?:\\n)?/,Ss=`
240
+ }`,variables:{query:`is:${r} ${o} ${t.includeFromArchivedRepos?"":"archived:false"} ${n}`,after:e}}},Ks="Field 'isDraft' doesn't exist on type 'PullRequest'",Be=(r=[])=>r.some(n=>n?.message===Ks),Xs=/@@ -(\d+)(?:,\d+ | )\+(\d+)(?:,\d+ | )@@(?:\\n)?/,Zs=`
240
241
  \
241
- +`,ar=(s,n,e,t)=>{let r=vs.exec(s);if(!r||!r[0]||!r[1])return[];let o=parseInt(r[1],10),i=parseInt(r[2],10),a=s.replace(Ss,`
242
+ +`,Sr=(r,n,e,t)=>{let s=Xs.exec(r);if(!s||!s[0]||!s[1])return[];let o=parseInt(s[1],10),i=parseInt(s[2],10),a=r.replace(Zs,`
242
243
  +`).split(`
243
- `).slice(1),u=o-1,l=i-1,p=a.map(g=>{let m,I;switch(g[0]){case"-":{m="DELETED",u+=1,I=`${g.slice(1)}
244
- `;break}case"+":{m="ADDED",l+=1,I=`${g.slice(1)}
245
- `;break}default:m="UNMODIFIED",l+=1,u+=1,I=`${g}
246
- `}return{line:I,oldLineNumber:m!=="ADDED"?u:null,newLineNumber:m!=="DELETED"?l:null,type:m}}),c=e,d=n;if(c!==null&&d!==null&&t!==null&&c<d){let g=0,m=p.length,I=t==="LEFT"?"oldLineNumber":"newLineNumber";for(let y=0;y<p.length;y++){let v=p[y][I];v===c?g=y:v===d&&(m=y)}p=p.slice(g,m+1)}return p},ur=s=>{let n=s.author;return n||(n=be),{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:s.body,createdAt:s.publishedAt?new Date(s.publishedAt):null,graphQLId:s.id,id:s.fullDatabaseId??s.databaseId?.toString()??s.id,url:s.url}};var lr=`mutation DeleteIssueComment(
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
+ `;break}case"+":{m="ADDED",l+=1,h=`${g.slice(1)}
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}}),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},vr=r=>{let n=r.author;return n||(n=qe),{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 Er=`mutation DeleteIssueComment(
247
248
  $issueCommentId: ID!
248
249
  ) {
249
250
  deleteIssueComment(input: {
@@ -251,7 +252,7 @@ query SearchIssuesOrPullRequests($query: String! $after: String) {
251
252
  }) {
252
253
  clientMutationId
253
254
  }
254
- }`,pr=`mutation DeletePullRequestReviewComment(
255
+ }`,Cr=`mutation DeletePullRequestReviewComment(
255
256
  $pullRequestReviewCommentId: ID!
256
257
  ) {
257
258
  deletePullRequestReviewComment(input: {
@@ -261,7 +262,7 @@ query SearchIssuesOrPullRequests($query: String! $after: String) {
261
262
  id
262
263
  }
263
264
  }
264
- }`,dr=`mutation UpdateIssueComment(
265
+ }`,$r=`mutation UpdateIssueComment(
265
266
  $issueCommentId: ID!,
266
267
  $body: String!
267
268
  ) {
@@ -274,7 +275,7 @@ query SearchIssuesOrPullRequests($query: String! $after: String) {
274
275
  body
275
276
  }
276
277
  }
277
- }`,cr=`mutation ResolveReviewThread(
278
+ }`,Dr=`mutation ResolveReviewThread(
278
279
  $pullRequestReviewThreadId: ID!
279
280
  ) {
280
281
  resolveReviewThread(input: {
@@ -285,7 +286,7 @@ query SearchIssuesOrPullRequests($query: String! $after: String) {
285
286
  isResolved
286
287
  }
287
288
  }
288
- }`,mr=`mutation UnresolveReviewThread(
289
+ }`,Lr=`mutation UnresolveReviewThread(
289
290
  $pullRequestReviewThreadId: ID!
290
291
  ) {
291
292
  unresolveReviewThread(input: {
@@ -296,7 +297,7 @@ query SearchIssuesOrPullRequests($query: String! $after: String) {
296
297
  isResolved
297
298
  }
298
299
  }
299
- }`,gr=`mutation UpdatePullRequestReviewComment(
300
+ }`,Ur=`mutation UpdatePullRequestReviewComment(
300
301
  $pullRequestReviewCommentId: ID!,
301
302
  $body: String!
302
303
  ) {
@@ -309,7 +310,7 @@ query SearchIssuesOrPullRequests($query: String! $after: String) {
309
310
  body
310
311
  }
311
312
  }
312
- }`;var hr=s=>`
313
+ }`;var Ar=r=>`
313
314
  query GetPullRequestComments(
314
315
  $namespace: String!
315
316
  $name: String!
@@ -322,7 +323,7 @@ query GetPullRequestComments(
322
323
  comments(first: $first, after: $cursor) {
323
324
  nodes {
324
325
  id
325
- ${s?"fullDatabaseId":"databaseId"}
326
+ ${r?"fullDatabaseId":"databaseId"}
326
327
  author {
327
328
  ... on User {
328
329
  id
@@ -355,7 +356,7 @@ query GetPullRequestComments(
355
356
  }
356
357
  }
357
358
  }
358
- `;var ft=`
359
+ `;var qt=`
359
360
  id
360
361
  databaseId
361
362
  owner {
@@ -368,18 +369,18 @@ defaultBranchRef {
368
369
  name
369
370
  }
370
371
  viewerPermission
371
- `,Es={APPROVED:"APPROVED",CHANGES_REQUESTED:"CHANGES_REQUESTED",COMMENTED:"COMMENTED",REVIEW_REQUESTED:"REVIEW_REQUESTED"},Cs={MERGEABLE:"MERGEABLE",CONFLICTING:"CONFLICTS",UNKNOWN:"UNKNOWN"},$s={BEHIND:"BEHIND",BLOCKED:"BLOCKED",UNKNOWN:"UNKNOWN_AND_BLOCKED",UNSTABLE:"UNSTABLE",CLEAN:null,DIRTY:null,DRAFT:null,HAS_HOOKS:null},Ds={OPEN:"OPEN",CLOSED:"CLOSED"},Ls=["ADMIN","MAINTAIN","TRIAGE","WRITE"],bt=s=>({color:`#${s.color}`,description:s.description,graphQLId:s.id,id:null,name:s.name}),Us=s=>({canCreateWebhook:s==="ADMIN",canPush:s==="ADMIN"||s==="MAINTAIN"||s==="WRITE",isAdmin:s==="ADMIN"}),Rt=s=>({id:s.databaseId.toString(),graphQLId:s.id,namespace:s.owner.login,name:s.name,webUrl:s.url,httpsUrl:s.url.endsWith(".git")?s.url:`${s.url}.git`,sshUrl:s.sshUrl,defaultBranch:s.defaultBranchRef,permissions:Us(s.viewerPermission)}),As=s=>({canCreateWebhook:s.admin,canPush:s.admin||s.maintain||s.push,isAdmin:s.admin}),fr=s=>({id:s.id.toString(),graphQLId:s.node_id,namespace:s.owner.login,name:s.name,webUrl:s.html_url,httpsUrl:s.clone_url,sshUrl:s.ssh_url,defaultBranch:{name:s.default_branch},permissions:As(s.permissions)}),Gs=s=>({path:s.path,isDirectory:s.type==="tree"}),Ts={OPEN:"OPEN",CLOSED:"CLOSED",MERGED:"MERGED"},Os={id:!0,graphQLId:!0,name:!0,username:!0,email:!0,avatarUrl:!0,url:!0},F=(s,n=Os)=>{let e={};return n.id&&(e.id="databaseId"in s?s.databaseId.toString():s.id),n.graphQLId&&(e.graphQLId=s.id),n.name&&(e.name=s.name??s.login),n.username&&(e.username=s.login),n.email&&(e.email=s.email??null),n.avatarUrl&&(e.avatarUrl=s.avatarUrl),n.url&&(e.url=s.url),e},xs=(s,n)=>{let e={IN_PROGRESS:"RUNNING",PENDING:"PENDING",QUEUED:"PENDING",REQUESTED:"PENDING",WAITING:"PENDING"};return s!=="COMPLETED"?e[s]:{ACTION_REQUIRED:"ACTION_REQUIRED",CANCELLED:"CANCELLED",FAILURE:"FAILED",NEUTRAL:null,SKIPPED:"SKIPPED",STALE:"FAILED",STARTUP_FAILURE:"FAILED",SUCCESS:"SUCCESS",TIMED_OUT:"ERROR"}[n]},_s=s=>({ERROR:"ERROR",EXPECTED:"PENDING",FAILURE:"FAILED",PENDING:"PENDING",SUCCESS:"SUCCESS"})[s],It=s=>{let n=null;s.author?n=s.author:n=be;let e=(s.reviewRequests?.nodes||[]).filter(O).filter(i=>!i.asCodeOwner),t=s.headRepository?.url;t&&!t.endsWith(".git")&&(t=`${t}.git`);let r=s.repository?.url;r&&!r.endsWith(".git")&&(r=`${r}.git`);let o=e.filter(i=>i.requestedReviewer&&"__typename"in i.requestedReviewer).map(i=>({reviewer:F(i.requestedReviewer),state:"REVIEW_REQUESTED"})).concat((s.latestReviews?.nodes||[]).filter(O).map(i=>{let a=be;return i.author&&i.author.__typename&&(a=i.author),{reviewer:F(a),state:Es[i.state]}}));return{id:s.fullDatabaseId!==void 0?s.fullDatabaseId:s.databaseId.toString(),graphQLId:s.id,title:s.title,description:s.body,number:s.number,state:Ts[s.state],commentCount:s.comments.totalCount,upvoteCount:s.reactions.totalCount,author:n&&n.__typename?F(n):null,createdDate:new Date(s.createdAt),isDraft:s.isDraft,repository:{id:s.repository.databaseId.toString(),graphQLId:s.repository.id,name:s.repository.name,owner:{login:s.repository.owner.login},remoteInfo:{cloneUrlHTTPS:r,cloneUrlSSH:s.repository.sshUrl}},headRepository:s.headRepository?{id:s.headRepository.databaseId.toString(),graphQLId:s.headRepository.id,name:s.headRepository.name,owner:{login:s.headRepository.owner.login},remoteInfo:{cloneUrlHTTPS:t,cloneUrlSSH:s.headRepository.sshUrl}}:null,headCommit:{buildStatuses:s.commits.nodes?.filter(O)[0]?.commit.statusCheckRollup?.contexts.nodes?.filter(O).map(i=>"context"in i?{completedAt:null,description:i.description,name:i.context,state:_s(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:xs(i.status,i.conclusion),startedAt:i.startedAt?new Date(i.startedAt):null,stage:null,url:i.permalink})??[]},headRef:s.headRef?{name:s.headRef.name,oid:s.headRef.target?.oid??null}:null,baseRef:s.baseRef?{name:s.baseRef.name,oid:s.baseRef.target?.oid??null}:null,url:s.url,updatedDate:new Date(s.updatedAt),closedDate:s.closedAt?new Date(s.closedAt):null,mergedDate:s.mergedAt?new Date(s.mergedAt):null,assignees:s.assignees.nodes?s.assignees.nodes.filter(O).map(i=>F(i)):null,reviews:o,reviewDecision:j(o),additions:s.additions,deletions:s.deletions,fileCount:s.changedFiles,commitCount:s.commits.totalCount,mergeableState:$s[s.mergeStateStatus]??Cs[s.mergeable],milestone:s.milestone?yt(s.milestone):null,labels:s.labels?.nodes?.filter(O).map(bt)??[],permissions:{canMerge:Ls.includes(s.repository.viewerPermission),canMergeAndBypassProtections:s.viewerCanMergeAsAdmin??!1}}},ks=s=>{let{id:n,comments:e,isOutdated:t,isResolved:r,line:o,startLine:i,diffSide:a,originalLine:u,originalStartLine:l,startDiffSide:p}=s,c=e.nodes?.[0];if(!c)return null;let{author:d,body:g,databaseId:m,fullDatabaseId:I,id:y,path:h,publishedAt:v,url:D}=c,x=o??u,E=i??l,P=a??p;return{author:d?{avatarUrl:d.avatarUrl,email:null,name:d.login}:null,body:g,createdAt:v?new Date(v):null,diffLines:ar(c.diffHunk,x,E,P),id:I??m.toString(),isOutdated:t,isResolved:r,graphQLId:y,threadId:n,filename:h,replies:e.nodes?.filter(O).slice(1).map(Ns)??[],url:D,line:x,startLine:E,side:P}},Ns=s=>({author:s.author?{avatarUrl:s.author.avatarUrl,email:null,name:s.author.login}:null,body:s.body,createdAt:s.publishedAt?new Date(s.publishedAt):null,graphQLId:s.id,id:s.fullDatabaseId??s.databaseId.toString(),url:s.url}),Fs=s=>{let n=null;return s.author?n=s.author:n=be,{id:s.fullDatabaseId!==void 0?s.fullDatabaseId:s.databaseId.toString(),graphQLId:s.id,number:s.number,title:s.title,author:n&&n.__typename?F(n):null,commentCount:s.comments.totalCount,closedDate:s.closedAt?new Date(s.closedAt):null,createdDate:new Date(s.createdAt),description:null,state:{name:Ds[s.state],color:null},type:null,repository:{id:s.repository.databaseId.toString(),graphQLId:s.repository.id,name:s.repository.name,owner:{login:s.repository.owner.login}},url:s.url,updatedDate:new Date(s.updatedAt),assignees:s.assignees.nodes?.filter(O).map(e=>F(e))??[],upvoteCount:s.reactions.totalCount,milestone:s.milestone?yt(s.milestone):null,labels:s.labels?.nodes?.filter(O).map(bt)??[]}},yt=s=>({id:s.number.toString(),graphQLId:s.id.toString(),number:s.number,title:s.title,description:s.description,isOpen:s.state=="OPEN",url:s.url,startDate:null,dueDate:s.dueOn?new Date(s.dueOn):null}),pe=class extends _{constructor(){super(...arguments);this._scopesCache={};this._enterpriseVersionsCache={}}async getScopes(e){let t=e.token||this.config.token;if(!t)return[];let r=this._scopesCache[t];if(!r){let i=(await b(this.config,{query:"query { rateLimit(dryRun: true) { __typename } }"},e)).headers["x-oauth-scopes"];r=i?i.split(", "):[],this._scopesCache[t]=r}return r}async getEnterpriseVersion(e){let t=e.baseUrl||this.config.baseUrl;if(!t)return null;let r=this._enterpriseVersionsCache[t];if(!r){let o=await this.config.request({url:`${B(this.config,e)}/meta`,headers:f(e.token||this.config.token)});if(!o.body.installed_version)return null;r=o.body.installed_version.split(".").slice(0,3).map(i=>parseInt(i,10)),this._enterpriseVersionsCache[t]=r}return r}getEnterpriseAvatarUrlIfNeeded(e,t,r){let o=r.baseUrl||this.config.baseUrl;return!o||o.startsWith(Ae)?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 r=Wt(e.fields),o=await this.getScopes(t),i=await b(this.config,{query:`
372
+ `,Ys={APPROVED:"APPROVED",CHANGES_REQUESTED:"CHANGES_REQUESTED",COMMENTED:"COMMENTED",REVIEW_REQUESTED:"REVIEW_REQUESTED"},en={MERGEABLE:"MERGEABLE",CONFLICTING:"CONFLICTS",UNKNOWN:"UNKNOWN"},tn={BEHIND:"BEHIND",BLOCKED:"BLOCKED",UNKNOWN:"UNKNOWN_AND_BLOCKED",UNSTABLE:"UNSTABLE",CLEAN:null,DIRTY:null,DRAFT:null,HAS_HOOKS:null},rn={OPEN:"OPEN",CLOSED:"CLOSED"},sn=["ADMIN","MAINTAIN","TRIAGE","WRITE"],Et=r=>({color:`#${r.color}`,description:r.description,graphQLId:r.id,id:null,name:r.name}),nn=r=>({canCreateWebhook:r==="ADMIN",canPush:r==="ADMIN"||r==="MAINTAIN"||r==="WRITE",isAdmin:r==="ADMIN"}),St=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:nn(r.viewerPermission)}),on=r=>({canCreateWebhook:r.admin,canPush:r.admin||r.maintain||r.push,isAdmin:r.admin}),Gr=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:on(r.permissions)}),an=r=>({path:r.path,isDirectory:r.type==="tree"}),un={OPEN:"OPEN",CLOSED:"CLOSED",MERGED:"MERGED"},ln={id:!0,graphQLId:!0,name:!0,username:!0,email:!0,avatarUrl:!0,url:!0},Q=(r,n=ln)=>{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},pn=(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],vt=r=>{let n=null;r.author?n=r.author:n=qe;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=qe;return i.author&&i.author.__typename&&(a=i.author),{reviewer:Q(a),state:Ys[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:un[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:pn(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:tn[r.mergeStateStatus]??en[r.mergeable],milestone:r.milestone?Ct(r.milestone):null,labels:r.labels?.nodes?.filter(x).map(Et)??[],permissions:{canMerge:sn.includes(r.repository.viewerPermission),canMergeAndBypassProtections:r.viewerCanMergeAsAdmin??!1}}},cn=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:S}=d,D=o??u,$=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:Sr(d.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(mn)??[],url:S,line:D,startLine:$,side:w}},mn=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}),gn=r=>{let n=null;return r.author?n=r.author:n=qe,{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:rn[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?Ct(r.milestone):null,labels:r.labels?.nodes?.filter(x).map(Et)??[]}},Ct=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}),ge=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(Ne)?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=Yt(e.fields),o=await this.getScopes(t),i=await b(this.config,{query:`
372
373
  query getCurrentUser {
373
374
  viewer {
374
- ${k(!1,H(o),r)}
375
+ ${F(!1,J(o),s)}
375
376
  }
376
377
  }
377
- `},t),a=i.body.data?.viewer;if(!a)throw new R("Current user not found.",i.body.errors);return{data:F(a,r)}}async getAccountsForRepo(e,t={}){let r=await this.getScopes(t),{repo:{namespace:o,name:i},cursor:a}=e,u=await b(this.config,{query:`
378
+ `},t),a=i.body.data?.viewer;if(!a)throw new I("Current user not found.",i.body.errors);return{data:Q(a,s)}}async getAccountsForRepo(e,t={}){let s=await this.getScopes(t),{repo:{namespace:o,name:i},cursor:a}=e,u=await b(this.config,{query:`
378
379
  query getAccountsForRepo($owner: String!, $name: String! $cursor: String, $first: Int!) {
379
380
  repository(owner: $owner, name: $name) {
380
381
  assignableUsers(first: $first, after: $cursor) {
381
382
  nodes {
382
- ${k(!1,H(r))}
383
+ ${F(!1,J(s))}
383
384
  }
384
385
  pageInfo {
385
386
  endCursor
@@ -388,7 +389,7 @@ query getAccountsForRepo($owner: String!, $name: String! $cursor: String, $first
388
389
  }
389
390
  }
390
391
  }
391
- `,variables:{owner:o,name:i,cursor:a,first:$}},t);if(!u.body.data)throw new R("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=>F(l))??[]}}async getUserForCommit(e,t={}){let r=await b(this.config,{query:`
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
393
  query getUserForCommit(
393
394
  $owner: String!
394
395
  $name: String!
@@ -407,7 +408,7 @@ query getUserForCommit(
407
408
  }
408
409
  }
409
410
  }
410
- `,variables:{owner:e.repo.namespace,name:e.repo.name,oid:e.oid,avatarSize:e.avatarSize}},t),o=r.body.data?.repository;if(!o)throw new R("Repository not found.",r.body.errors);let i=o.object?.author;if(!i)throw new R("Commit not found.",r.body.errors);return{data:{name:i.name,email:i.email,avatarUrl:this.getEnterpriseAvatarUrlIfNeeded(i.avatarUrl,i.email,t)}}}async createCommit(e,t={}){let{commitMessage:r,deletedFiles:o,newOrModifiedFiles:i,repo:a,target:u}=e,l=await b(this.config,{query:`
411
+ `,variables:{owner:e.repo.namespace,name:e.repo.name,oid:e.oid,avatarSize:e.avatarSize}},t),o=s.body.data?.repository;if(!o)throw new I("Repository not found.",s.body.errors);let i=o.object?.author;if(!i)throw new I("Commit not found.",s.body.errors);return{data:{name:i.name,email:i.email,avatarUrl:this.getEnterpriseAvatarUrlIfNeeded(i.avatarUrl,i.email,t)}}}async createCommit(e,t={}){let{commitMessage:s,deletedFiles:o,newOrModifiedFiles:i,repo:a,target:u}=e,l=await b(this.config,{query:`
411
412
  mutation createCommitOnBranch(
412
413
  $branchName: String!,
413
414
  $expectedHeadOid: GitObjectID!,
@@ -434,23 +435,23 @@ mutation createCommitOnBranch(
434
435
  }
435
436
  }
436
437
  }
437
- `,variables:{branchName:u.name,expectedHeadOid:u.oid,fileChanges:{additions:Object.entries(i).map(([p,c])=>({contents:Rr.Base64.encode(c),path:p})),deletions:o.map(p=>({path:p}))},message:{body:r.description,headline:r.summary},repositoryNameWithOwner:`${a.namespace}/${a.name}`}},t);if(!l.body.data)throw new R("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 r=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:Tr.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:`
438
439
  query getAccountForEmail($query: String! $avatarSize: Int) {
439
440
  search(query: $query, type: USER, first: 1) {
440
441
  nodes {
441
442
  ... on User {
442
- ${k(!0,H(r))}
443
+ ${F(!0,J(s))}
443
444
  }
444
445
  }
445
446
  }
446
447
  }
447
- `,variables:{query:`in:email ${e.email}`,avatarSize:e.avatarSize}},t),i=o.body.data?.search?.nodes?.[0];if(!i)throw new R("Could not find user via email",o.body.errors);return{data:F({...i,avatarUrl:this.getEnterpriseAvatarUrlIfNeeded(i.avatarUrl,i.email,t)})}}async getAccountForUsername(e,t={}){let r=await this.getScopes(t),o=await b(this.config,{query:`
448
+ `,variables:{query:`in:email ${e.email}`,avatarSize:e.avatarSize}},t),i=o.body.data?.search?.nodes?.[0];if(!i)throw new I("Could not find user via email",o.body.errors);return{data:Q({...i,avatarUrl:this.getEnterpriseAvatarUrlIfNeeded(i.avatarUrl,i.email,t)})}}async getAccountForUsername(e,t={}){let s=await this.getScopes(t),o=await b(this.config,{query:`
448
449
  query getUserForUsername($login: String! $avatarSize: Int) {
449
450
  user(login: $login) {
450
- ${k(!0,H(r))}
451
+ ${F(!0,J(s))}
451
452
  }
452
453
  }
453
- `,variables:{login:e.username,avatarSize:e.avatarSize}},t),i=o.body.data?.user;if(!i)throw new R("Could not find user via username",o.body.errors);return{data:F({...i,avatarUrl:this.getEnterpriseAvatarUrlIfNeeded(i.avatarUrl,i.email,t)})}}async getOrgsForCurrentUser(e={},t={}){let r=await b(this.config,{query:`
454
+ `,variables:{login:e.username,avatarSize:e.avatarSize}},t),i=o.body.data?.user;if(!i)throw new I("Could not find user via username",o.body.errors);return{data:Q({...i,avatarUrl:this.getEnterpriseAvatarUrlIfNeeded(i.avatarUrl,i.email,t)})}}async getOrgsForCurrentUser(e={},t={}){let s=await b(this.config,{query:`
454
455
  query getOrgsForCurrentUser($cursor: String, $first: Int!) {
455
456
  viewer {
456
457
  organizations(first: $first after: $cursor) {
@@ -469,7 +470,7 @@ query getOrgsForCurrentUser($cursor: String, $first: Int!) {
469
470
  }
470
471
  }
471
472
  }
472
- `,variables:{cursor:e.cursor,first:$}},t);if(!r.body.data)throw new R("Could not fetch orgs for current user",r.body.errors);let o=r.body.data.viewer.organizations.nodes||[];return{pageInfo:r.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 r=await b(this.config,{query:`
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
474
  query getOrgMember($cursor: String, $first: Int!, $login: String!) {
474
475
  viewer {
475
476
  organization(login: $login) {
@@ -479,28 +480,28 @@ query getOrgMember($cursor: String, $first: Int!, $login: String!) {
479
480
  hasNextPage
480
481
  }
481
482
  nodes {
482
- ${k(!1,!0)}
483
+ ${F(!1,!0)}
483
484
  }
484
485
  }
485
486
  }
486
487
  }
487
488
  }
488
- `,variables:{cursor:e.cursor,first:$,login:e.org}},t);if(!r.body.data?.viewer.organization?.membersWithRole&&r.body.errors?.length)throw new R("Could not read the members of the organization",r.body.errors);let o=r.body.data?.viewer.organization?.membersWithRole.nodes||[];return{pageInfo:{hasNextPage:r.body.data?.viewer.organization?.membersWithRole.pageInfo.hasNextPage??!1,endCursor:r.body.data?.viewer.organization?.membersWithRole.pageInfo.endCursor??null},data:o.map(i=>F({...i,avatarUrl:this.getEnterpriseAvatarUrlIfNeeded(i.avatarUrl,i.email,t)}))}}async getRepo(e,t={}){let r=await b(this.config,{query:`
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
490
  query getRepo($owner: String!, $name: String!) {
490
491
  repository(owner: $owner, name: $name) {
491
- ${ft}
492
+ ${qt}
492
493
  }
493
494
  }
494
- `,variables:{owner:e.namespace,name:e.name}},t);if(!r.body.data?.repository)throw new R(`Repository ${e.namespace}/${e.name} not found`,r.body.errors);return{data:Rt(r.body.data.repository)}}async getRepos(e,t={}){let r=e.map(({namespace:u,name:l},p)=>`
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:St(s.body.data.repository)}}async getRepos(e,t={}){let s=e.map(({namespace:u,name:l},p)=>`
495
496
  getRepo_${p}: repository(owner: "${u}", name: "${l}") {
496
- ${ft}
497
+ ${qt}
497
498
  }
498
499
  `).join(`
499
500
  `),o=await b(this.config,{query:`
500
501
  query batchGetRepos {
501
- ${r}
502
+ ${s}
502
503
  }
503
- `},t);if(!o.body.data)throw new R("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(Rt(p)):a.push({input:u})}),{data:i,errors:a}}async fetchMultipleRESTPages(e,t,r,o){let i=[];for(let c=0;c<t;c++)i.push(r(e+c));let a=await Promise.all(i),u=[];for(let c of a){if(!c.body)throw new Error(c.statusText||"Unknown error");u=u.concat(c.body.map(d=>o(d)))}let l=a.every(c=>c.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 r=new URLSearchParams;r.append("per_page","100"),e.affiliations&&r.append("affiliation",e.affiliations.join(","));let o=i=>this.config.request({url:`${B(this.config,t)}/user/repos?${r.toString()}&page=${i}`,headers:{...f(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,fr)}async getReposForOrg(e,t={}){if(e.simultaneousPagesToFetch&&e.simultaneousPagesToFetch>40)throw new Error("The argument 'simultaneousPagesToFetch' cannot exceed 40 for 'getReposForOrg'");let r=o=>this.config.request({url:`${B(this.config,t)}/orgs/${e.orgName}/repos?per_page=100&page=${o}`,headers:{...f(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,r,fr)}async getReposForUsernames(e,t={}){if(!e.usernames.length)return{pageInfo:{endCursor:null,hasNextPage:!1},data:[]};let r=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(St(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:`${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,Gr)}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,Gr)}async getReposForUsernames(e,t={}){if(!e.usernames.length)return{pageInfo:{endCursor:null,hasNextPage:!1},data:[]};let s=await b(this.config,{query:`
504
505
  query getReposForUsernames($query: String!, $cursor: String, $first: Int!) {
505
506
  search(query: $query, type: REPOSITORY, first: $first, after: $cursor) {
506
507
  pageInfo {
@@ -509,12 +510,12 @@ query getReposForUsernames($query: String!, $cursor: String, $first: Int!) {
509
510
  }
510
511
  nodes {
511
512
  ... on Repository {
512
- ${ft}
513
+ ${qt}
513
514
  }
514
515
  }
515
516
  }
516
517
  }
517
- `,variables:{query:`fork:true ${e.usernames.map(i=>`user:${i}`).join(" ")}`,cursor:e.cursor,first:$}},t);if(!r.body.data)throw new R("Could not fetch repos for usernames",r.body.errors);let o=r.body.data.search.nodes||[];return{pageInfo:r.body.data.search.pageInfo,data:o.map(Rt)}}async getReposForOwners(e,t={}){return this.getReposForUsernames({usernames:e.owners.filter(r=>r.username).map(r=>r.username),cursor:e.cursor},t)}async getRefs(e,t,r={}){let o=await b(this.config,{query:`
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(St)}}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
519
  query getRefs($owner: String!, $name: String!, $refPrefix: String!, $cursor: String, $first: Int!) {
519
520
  repository(owner: $owner, name: $name) {
520
521
  refs(refPrefix: $refPrefix first: $first after: $cursor) {
@@ -535,7 +536,7 @@ query getRefs($owner: String!, $name: String!, $refPrefix: String!, $cursor: Str
535
536
  }
536
537
  }
537
538
  }
538
- `,variables:{owner:t.repo.namespace,name:t.repo.name,refPrefix:e,cursor:t.cursor,first:$}},r),i=o.body.data?.repository;if(!i)throw new R("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 r=await b(this.config,{query:`
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
540
  query getBlame($owner: String!, $name: String!, $ref: String!, $path: String!) {
540
541
  repository(owner: $owner, name: $name) {
541
542
  object(expression: $ref) {
@@ -574,7 +575,7 @@ query getBlame($owner: String!, $name: String!, $ref: String!, $path: String!) {
574
575
  }
575
576
  }
576
577
  }
577
- `,variables:{owner:e.repo.namespace,name:e.repo.name,ref:e.ref,path:e.path}},t),o=r.body.data?.repository;if(!o)throw new R("Blame repository not found.",r.body.errors);let i=o.object;if(!i||!("blame"in i))throw new R("Ref not found.",r.body.errors);if(i.blame.ranges.length===0)throw new R("File not found.",r.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 r=await this.config.request({url:`${B(this.config,t)}/repos/${e.repo.namespace}/${e.repo.name}/contents/${encodeURIComponent(e.path)}?ref=${e.ref}`,headers:{...f(t.token||this.config.token),Accept:"application/vnd.github.raw+json"}});if(r.headers["content-type"].startsWith("application/json"))throw new Error(`GitHub: got directory when fetching "${e.path}", getFileContents does not support fetching directories`);if(!r.headers["content-type"].startsWith("application/vnd.github.raw+json"))throw new Error(`GitHub: unsupported content type "${r.headers["content-type"]}" when fetching "${e.path}"`);return{data:new Blob([r.body])}}async getMergeBase(e,t={}){return{data:(await this.config.request({url:`${B(this.config,t)}/repos/${e.repo.namespace}/${e.repo.name}/compare/${encodeURIComponent(e.base)}...${encodeURIComponent(e.head)}`,headers:f(t.token||this.config.token)})).body.merge_base_commit.sha}}async getPullRequestDiff(e,t={}){return(await this.config.request({url:`${B(this.config,t)}/repos/${e.repo.namespace}/${e.repo.name}/pulls/${e.pullRequestId}`,headers:{...f(t.token||this.config.token),Accept:"application/vnd.github.diff"}})).body??""}async searchPullRequests(e,t={}){let r=await this.getEnterpriseVersion(t),o=await this.getScopes(t),i=H(o),a=p=>{let c=p&&typeof e.isDraft=="boolean"?`${e.query} draft:${e.isDraft}`:e.query;return ht("pr",c,e.cursor,{maxPageSize:e.maxPageSize??sr,supportsEmail:i,supportsDrafts:p,enterpriseVersion:r,includeFromArchivedRepos:e.includeFromArchivedRepos})},u=await b(this.config,a(!0),t);u.body.errors&&xe(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 R("Could not search pull requests",u.body.errors);return{pageInfo:{hasNextPage:l.search.pageInfo.hasNextPage,endCursor:l.search.pageInfo.endCursor},data:l.search.nodes?.filter(O).map(It)||[]}}async searchIssues(e,t={}){let r=await this.getEnterpriseVersion(t),o=await this.getScopes(t),i=H(o),a=await b(this.config,ht("issue",e.query,e.cursor,{supportsEmail:i,includeFromArchivedRepos:e.includeFromArchivedRepos,maxPageSize:e.maxPageSize??nr,enterpriseVersion:r}),t),{data:u}=a.body;if(!u)throw new R("Could not search issues",a.body.errors);return{pageInfo:{hasNextPage:u.search.pageInfo.hasNextPage,endCursor:u.search.pageInfo.endCursor},data:u.search.nodes?.filter(O).map(Fs)||[]}}async getPullRequestsAssociatedWithUser(e,t={}){let r=[`involves:${e.username}`];return e.repos?.length&&e.repos.forEach(o=>{r.push(`repo:${o.namespace}/${o.name}`)}),e.labelNames&&e.labelNames.forEach(o=>{r.push(`label:"${o}"`)}),this.searchPullRequests({query:r.join(" "),cursor:e.cursor,includeFromArchivedRepos:e.includeFromArchivedRepos,maxPageSize:e.maxPageSize},t)}async getPullRequestsForRepos(e,t={}){let{assigneeLogins:r,updatedBefore:o,authorLogin:i,repos:a,reviewRequestedLogin:u,startQuery:l,mentionLogin:p,labelNames:c,maxPageSize:d}=e,g=gt(l||"");return a.forEach(m=>{g.push(`repo:${m.namespace}/${m.name}`)}),r&&r.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}`),c&&c.forEach(m=>{g.push(`label:"${m}"`)}),this.searchPullRequests({query:`sort:updated ${g.join(" ")}`,isDraft:e.isDraft,cursor:e.cursor,includeFromArchivedRepos:e.includeFromArchivedRepos,maxPageSize:d},t)}async getPullRequestForRepo(e,t={}){let r=await this.getEnterpriseVersion(t),o=await this.getScopes(t),i=H(o),a=c=>({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:`${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=J(o),a=wr(e.states),u=d=>{let c=d&&typeof e.isDraft=="boolean"?`${e.query} draft:${e.isDraft}`:e.query;return wt("pr",c,e.cursor,{maxPageSize:e.maxPageSize??Ir,supportsEmail:i,supportsDrafts:d,enterpriseVersion:s,includeFromArchivedRepos:e.includeFromArchivedRepos,stateQualifier:a})},l=await b(this.config,u(!0),t);l.body.errors&&Be(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(vt)||[],e.states)}}async searchIssues(e,t={}){let s=await this.getEnterpriseVersion(t),o=await this.getScopes(t),i=J(o),a=qr(e.states),u=await b(this.config,wt("issue",e.query,e.cursor,{supportsEmail:i,includeFromArchivedRepos:e.includeFromArchivedRepos,maxPageSize:e.maxPageSize??br,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(gn)||[]}}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=yt(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=J(o),a=d=>({query:`query getPullRequest(
578
579
  $owner: String!
579
580
  $name: String!
580
581
  $number: Int!
@@ -584,24 +585,24 @@ query getBlame($owner: String!, $name: String!, $ref: String!, $path: String!) {
584
585
  name: $name
585
586
  ) {
586
587
  pullRequest(number: $number) {
587
- ${Oe(c,i,r)}
588
+ ${Qe(d,i,s)}
588
589
  }
589
590
  }
590
- }`,variables:{owner:e.repo.namespace,name:e.repo.name,number:e.number}}),u=await b(this.config,a(!0),t);u.body.errors&&xe(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 R("Could not fetch pull request by number",u.body.errors);let p=u.body.data?.repository.pullRequest;return{data:p?It(p):null}}async getPullRequestDescription(e,t={}){try{let r=await this.config.request({url:`${B(this.config,t)}/repos/${e.repo.namespace}/${e.repo.name}/pulls/${e.number}`,headers:{...f(t.token||this.config.token),Accept:"application/vnd.github.full+json"}});return{data:{description:r.body?.body??"",descriptionHtml:r.body?.body_html||null}}}catch{return{data:{description:null,descriptionHtml:null}}}}async setPullRequestDescription(e,t={}){let r=await this.config.request({method:"PATCH",url:`${B(this.config,t)}/repos/${e.repo.namespace}/${e.repo.name}/pulls/${e.number}`,headers:{...f(t.token||this.config.token),Accept:"application/vnd.github+json","Content-Type":"application/json"},body:JSON.stringify({body:e.description})});return{data:{description:r.body?.body??e.description,descriptionHtml:r.body?.body_html||null}}}async getPullRequestByGraphQLId(e,t={}){let r=await this.getEnterpriseVersion(t),o=await this.getScopes(t),i=H(o),a=c=>({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&&Be(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?vt(p):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=J(o),a=d=>({query:`query getPullRequest(
591
592
  $graphQLId: ID!
592
593
  ) {
593
594
  node(id: $graphQLId) {
594
595
  ... on PullRequest {
595
- ${Oe(c,i,r)}
596
+ ${Qe(d,i,s)}
596
597
  }
597
598
  }
598
- }`,variables:{graphQLId:e.graphQLId}}),u=await b(this.config,a(!0),t);u.body.errors&&xe(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 R("Could not fetch pull request by id",u.body.errors);let p=u.body.data?.node;return{data:p?It(p):null}}async closePullRequest(e,t={}){let{pullRequest:{graphQLId:r}}=e;if(!r)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&&Be(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?vt(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!) {
599
600
  closePullRequest(input: { pullRequestId: $pullRequestGraphQLId }) {
600
601
  pullRequest {
601
602
  id
602
603
  }
603
604
  }
604
- }`,i=await b(this.config,{query:`${o}`,variables:{pullRequestGraphQLId:r}},t);if(!i.body.data?.closePullRequest?.pullRequest?.id)throw new R("Could not close pull request",i.body.errors)}async mergePullRequest(e,t={}){let{pullRequest:r,mergeStrategy:o}=e;if(!r.graphQLId)throw new Error('GitHub requires "graphQLId" for this function.');if(!r.headRef?.oid)throw new Error('GitHub requires "headRef.oid" for this function.');let i;switch(o){case"MERGE_COMMIT":{i="MERGE";break}case"REBASE":{i="REBASE";break}case"SQUASH":{i="SQUASH";break}}let a=`mutation MergePullRequest(
605
+ }`,i=await b(this.config,{query:`${o}`,variables:{pullRequestGraphQLId:s}},t);if(!i.body.data?.closePullRequest?.pullRequest?.id)throw new I("Could not close pull request",i.body.errors)}async mergePullRequest(e,t={}){let{pullRequest:s,mergeStrategy:o}=e;if(!s.graphQLId)throw new Error('GitHub requires "graphQLId" for this function.');if(!s.headRef?.oid)throw new Error('GitHub requires "headRef.oid" for this function.');let i;switch(o){case"MERGE_COMMIT":{i="MERGE";break}case"REBASE":{i="REBASE";break}case"SQUASH":{i="SQUASH";break}}let a=`mutation MergePullRequest(
605
606
  $pullRequestGraphQLId: ID!,
606
607
  $expectedSourceSha: GitObjectID!,
607
608
  $mergeStrategy: PullRequestMergeMethod,
@@ -615,7 +616,7 @@ query getBlame($owner: String!, $name: String!, $ref: String!, $path: String!) {
615
616
  id
616
617
  }
617
618
  }
618
- }`,u=await b(this.config,{query:`${a}`,variables:{pullRequestGraphQLId:r.graphQLId,expectedSourceSha:r.headRef.oid,mergeStrategy:i}},t);if(!u.body.data?.mergePullRequest?.pullRequest?.id)throw new R("Could not merge pull request",u.body.errors)}async approvePullRequest(e,t={}){let{pullRequest:r,comment:o}=e;if(!r.graphQLId)throw new Error('GitHub requires "graphQLId" for this function.');let i=`mutation ApprovePullRequest(
619
+ }`,u=await b(this.config,{query:`${a}`,variables:{pullRequestGraphQLId:s.graphQLId,expectedSourceSha:s.headRef.oid,mergeStrategy:i}},t);if(!u.body.data?.mergePullRequest?.pullRequest?.id)throw new I("Could not merge pull request",u.body.errors)}async approvePullRequest(e,t={}){let{pullRequest:s,comment:o}=e;if(!s.graphQLId)throw new Error('GitHub requires "graphQLId" for this function.');let i=`mutation ApprovePullRequest(
619
620
  $pullRequestId: ID!,
620
621
  $body: String
621
622
  ) {
@@ -628,7 +629,7 @@ query getBlame($owner: String!, $name: String!, $ref: String!, $path: String!) {
628
629
  id
629
630
  }
630
631
  }
631
- }`,a=await b(this.config,{query:i,variables:{pullRequestId:r.graphQLId,body:o||null}},t);if(!a.body.data?.addPullRequestReview?.pullRequestReview?.id)throw new R("Could not approve pull request",a.body.errors)}async requestPullRequestChanges(e,t={}){let{pullRequest:r,comment:o}=e;if(!r.graphQLId)throw new Error('GitHub requires "graphQLId" for this function.');if(!o||o.trim()==="")throw new Error("GitHub requires a comment when requesting changes.");let i=`mutation RequestPullRequestChanges(
632
+ }`,a=await b(this.config,{query:i,variables:{pullRequestId:s.graphQLId,body:o||null}},t);if(!a.body.data?.addPullRequestReview?.pullRequestReview?.id)throw new I("Could not approve pull request",a.body.errors)}async requestPullRequestChanges(e,t={}){let{pullRequest:s,comment:o}=e;if(!s.graphQLId)throw new Error('GitHub requires "graphQLId" for this function.');if(!o||o.trim()==="")throw new Error("GitHub requires a comment when requesting changes.");let i=`mutation RequestPullRequestChanges(
632
633
  $pullRequestId: ID!,
633
634
  $body: String!
634
635
  ) {
@@ -641,7 +642,7 @@ query getBlame($owner: String!, $name: String!, $ref: String!, $path: String!) {
641
642
  id
642
643
  }
643
644
  }
644
- }`,a=await b(this.config,{query:i,variables:{pullRequestId:r.graphQLId,body:o}},t);if(!a.body.data?.addPullRequestReview?.pullRequestReview?.id)throw new R("Could not request pull request changes",a.body.errors)}async commentOnPullRequest(e,t={}){let{pullRequest:r,comment:o}=e;if(!r.graphQLId)throw new Error('GitHub requires "graphQLId" for this function.');if(!o||o.trim()==="")throw new Error("GitHub requires a comment when commenting on a pull request.");let i=`mutation CommentOnPullRequest(
645
+ }`,a=await b(this.config,{query:i,variables:{pullRequestId:s.graphQLId,body:o}},t);if(!a.body.data?.addPullRequestReview?.pullRequestReview?.id)throw new I("Could not request pull request changes",a.body.errors)}async commentOnPullRequest(e,t={}){let{pullRequest:s,comment:o}=e;if(!s.graphQLId)throw new Error('GitHub requires "graphQLId" for this function.');if(!o||o.trim()==="")throw new Error("GitHub requires a comment when commenting on a pull request.");let i=`mutation CommentOnPullRequest(
645
646
  $pullRequestId: ID!,
646
647
  $body: String!
647
648
  ) {
@@ -654,7 +655,7 @@ query getBlame($owner: String!, $name: String!, $ref: String!, $path: String!) {
654
655
  id
655
656
  }
656
657
  }
657
- }`,a=await b(this.config,{query:i,variables:{pullRequestId:r.graphQLId,body:o}},t);if(!a.body.data?.addPullRequestReview?.pullRequestReview?.id)throw new R("Could not comment on pull request",a.body.errors)}async reviewPullRequest(e,t={}){let{pullRequest:r,reviewEvent:o,comment:i}=e;switch(o){case"APPROVE":return this.approvePullRequest({pullRequest:r,comment:i},t);case"REQUEST_CHANGES":return this.requestPullRequestChanges({pullRequest:r,comment:i??""},t);case"COMMENT":return this.commentOnPullRequest({pullRequest:r,comment:i??""},t)}}async addCommentToPullRequest(e,t={}){let{pullRequest:r,comment:o}=e;if(!r.graphQLId)throw new Error('GitHub requires "graphQLId" for this function.');if(!o||o.trim()==="")throw new Error("GitHub requires a comment when adding a comment to a pull request.");let i=`mutation AddCommentToPullRequest(
658
+ }`,a=await b(this.config,{query:i,variables:{pullRequestId:s.graphQLId,body:o}},t);if(!a.body.data?.addPullRequestReview?.pullRequestReview?.id)throw new I("Could not comment on pull request",a.body.errors)}async reviewPullRequest(e,t={}){let{pullRequest:s,reviewEvent:o,comment:i}=e;switch(o){case"APPROVE":return this.approvePullRequest({pullRequest:s,comment:i},t);case"REQUEST_CHANGES":return this.requestPullRequestChanges({pullRequest:s,comment:i??""},t);case"COMMENT":return this.commentOnPullRequest({pullRequest:s,comment:i??""},t)}}async addCommentToPullRequest(e,t={}){let{pullRequest:s,comment:o}=e;if(!s.graphQLId)throw new Error('GitHub requires "graphQLId" for this function.');if(!o||o.trim()==="")throw new Error("GitHub requires a comment when adding a comment to a pull request.");let i=`mutation AddCommentToPullRequest(
658
659
  $subjectId: ID!,
659
660
  $body: String!
660
661
  ) {
@@ -668,7 +669,7 @@ query getBlame($owner: String!, $name: String!, $ref: String!, $path: String!) {
668
669
  }
669
670
  }
670
671
  }
671
- }`,a=await b(this.config,{query:i,variables:{subjectId:r.graphQLId,body:o}},t);if(!a.body.data?.addComment?.commentEdge?.node?.id)throw new R("Could not add comment to pull request",a.body.errors)}async addInlineCommentToPullRequest(e,t={}){let{pullRequest:r,comment:o,path:i,line:a,side:u="RIGHT",threadId:l}=e;if(!r.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:r,comment:o,path:i,line:a,side:u},t)}async deleteInlineComment(e,t={}){let{commentId:r}=e;if(!r)throw new Error('GitHub requires "commentId" for this function.');let o=await b(this.config,{query:pr,variables:{pullRequestReviewCommentId:r}},t);if(!o.body.data?.deletePullRequestReviewComment)throw new R("Could not delete inline comment",o.body.errors)}async deleteComment(e,t={}){let{commentId:r}=e;if(!r)throw new Error('GitHub requires "commentId" for this function.');let o=await b(this.config,{query:lr,variables:{issueCommentId:r}},t);if(!o.body.data?.deleteIssueComment)throw new R("Could not delete comment",o.body.errors)}async editComment(e,t={}){let{commentId:r,body:o}=e;if(!r)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:dr,variables:{issueCommentId:r,body:o}},t);if(!i.body.data?.updateIssueComment?.issueComment?.id)throw new R("Could not edit comment",i.body.errors)}async editInlineComment(e,t={}){let{commentId:r,body:o}=e;if(!r)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:gr,variables:{pullRequestReviewCommentId:r,body:o}},t);if(!i.body.data?.updatePullRequestReviewComment?.pullRequestReviewComment?.id)throw new R("Could not edit inline comment",i.body.errors)}async resolveReviewThread(e,t={}){let{threadId:r}=e;if(!r)throw new Error('GitHub requires "threadId" for this function.');let o=await b(this.config,{query:cr,variables:{pullRequestReviewThreadId:r}},t);if(!o.body.data?.resolveReviewThread?.thread?.id)throw new R("Could not resolve review thread",o.body.errors)}async unresolveReviewThread(e,t={}){let{threadId:r}=e;if(!r)throw new Error('GitHub requires "threadId" for this function.');let o=await b(this.config,{query:mr,variables:{pullRequestReviewThreadId:r}},t);if(!o.body.data?.unresolveReviewThread?.thread?.id)throw new R("Could not unresolve review thread",o.body.errors)}async addReplyToReviewThread(e,t){let{threadId:r,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:Cr,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:Er,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:$r,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:Ur,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:Dr,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:Lr,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
673
  $threadId: ID!,
673
674
  $body: String!
674
675
  ) {
@@ -680,7 +681,7 @@ query getBlame($owner: String!, $name: String!, $ref: String!, $path: String!) {
680
681
  id
681
682
  }
682
683
  }
683
- }`,a=await b(this.config,{query:i,variables:{threadId:r,body:o}},t);if(!a.body.data?.addPullRequestReviewThreadReply?.comment?.id)throw new R("Could not add reply to pull request review thread",a.body.errors);return r}async createReviewThread(e,t){let{pullRequest:r,comment:o,path:i,line:a,side:u}=e,l=`mutation AddInlineCommentToPullRequest(
684
+ }`,a=await b(this.config,{query:i,variables:{threadId:s,body:o}},t);if(!a.body.data?.addPullRequestReviewThreadReply?.comment?.id)throw new I("Could not add reply to pull request review thread",a.body.errors);return s}async createReviewThread(e,t){let{pullRequest:s,comment:o,path:i,line:a,side:u}=e,l=`mutation AddInlineCommentToPullRequest(
684
685
  $pullRequestId: ID!,
685
686
  $body: String!,
686
687
  $path: String!,
@@ -706,43 +707,43 @@ query getBlame($owner: String!, $name: String!, $ref: String!, $path: String!) {
706
707
  }
707
708
  }
708
709
  }
709
- }`,p=await b(this.config,{query:l,variables:{pullRequestId:r.graphQLId,body:o,path:i,line:a,side:u}},t);if(!p.body.data?.addPullRequestReview?.pullRequestReview?.id)throw new R("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:r,milestone:o}=e;if(!r.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) {
710
711
  updatePullRequest(input: { pullRequestId: $pullRequestGraphQLId, milestoneId: $milestoneGraphQLId }) {
711
712
  pullRequest {
712
713
  id
713
714
  }
714
715
  }
715
- }`,a=await b(this.config,{query:`${i}`,variables:{pullRequestGraphQLId:r.graphQLId,milestoneGraphQLId:o?.graphQLId??null}},t);if(!a.body.data?.updatePullRequest?.pullRequest?.id)throw new R("Could not set milestone of pull request",a.body.errors)}async markPullRequestReadyForReview(e,t){let r=`mutation MarkReadyToReview($pullRequestGraphQLId: ID!) {
716
+ }`,a=await b(this.config,{query:`${i}`,variables:{pullRequestGraphQLId:s.graphQLId,milestoneGraphQLId:o?.graphQLId??null}},t);if(!a.body.data?.updatePullRequest?.pullRequest?.id)throw new I("Could not set milestone of pull request",a.body.errors)}async markPullRequestReadyForReview(e,t){let s=`mutation MarkReadyToReview($pullRequestGraphQLId: ID!) {
716
717
  markPullRequestReadyForReview(input: { pullRequestId: $pullRequestGraphQLId }) {
717
718
  pullRequest {
718
719
  id
719
720
  }
720
721
  }
721
- }`,o=await b(this.config,{query:r,variables:{pullRequestGraphQLId:e}},t);if(!o.body.data?.markPullRequestReadyForReview?.pullRequest?.id)throw new R("Could not mark pull request ready to review",o.body.errors)}async convertPullRequestToDraft(e,t){let r=`mutation ConvertToDraft($pullRequestGraphQLId: ID!) {
722
+ }`,o=await b(this.config,{query:s,variables:{pullRequestGraphQLId:e}},t);if(!o.body.data?.markPullRequestReadyForReview?.pullRequest?.id)throw new I("Could not mark pull request ready to review",o.body.errors)}async convertPullRequestToDraft(e,t){let s=`mutation ConvertToDraft($pullRequestGraphQLId: ID!) {
722
723
  convertPullRequestToDraft(input: { pullRequestId: $pullRequestGraphQLId }) {
723
724
  pullRequest {
724
725
  id
725
726
  }
726
727
  }
727
- }`,o=await b(this.config,{query:r,variables:{pullRequestGraphQLId:e}},t);if(!o.body.data?.convertPullRequestToDraft?.pullRequest?.id)throw new R("Could not convert pull request to draft",o.body.errors)}async setPullRequestAsDraft(e,t={}){let{pullRequest:{graphQLId:r},isDraft:o}=e;if(!r)throw new Error('GitHub requires "graphQLId" for this function.');if(o){await this.convertPullRequestToDraft(r,t);return}await this.markPullRequestReadyForReview(r,t)}async setPullRequestReviewers(e,t={}){let{pullRequest:{reviews:r,graphQLId:o},reviewers:i}=e;if(!r)throw new Error('GitHub requires "reviews" for this function');if(!o)throw new Error('GitHub requires "graphQLId" for this function.');let a=r.filter(c=>c.state!=="REVIEW_REQUESTED").map(c=>{if(!c.reviewer.graphQLId)throw new Error('GitHub requires reviewer "graphQLId" for this function.');return c.reviewer.graphQLId}),u=i.map(c=>{if(!c.graphQLId)throw new Error('GitHub requires reviewer "graphQLId" for this function.');return c.graphQLId}).filter(c=>a.indexOf(c)===-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!]!) {
728
729
  requestReviews(input: { pullRequestId: $pullRequestGraphQLId, userIds: $reviewerGraphQLIds }) {
729
730
  pullRequest {
730
731
  id
731
732
  }
732
733
  }
733
- }`,p=await b(this.config,{query:l,variables:{pullRequestGraphQLId:o,reviewerGraphQLIds:u}},t);if(!p.body.data?.requestReviews?.pullRequest?.id)throw new R("Could not set pull request reviewers",p.body.errors)}async reRequestPullRequestReviews(e,t={}){let{pullRequest:{reviews:r,graphQLId:o},reviewers:i}=e;if(!o)throw new Error('GitHub requires "graphQLId" for this function.');if(!r)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(!r.find(c=>c.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!]!) {
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!]!) {
734
735
  requestReviews(input: { pullRequestId: $pullRequestGraphQLId, userIds: $reviewerGraphQLIds, union: true }) {
735
736
  pullRequest {
736
737
  id
737
738
  }
738
739
  }
739
- }`,l=await b(this.config,{query:u,variables:{pullRequestGraphQLId:o,reviewerGraphQLIds:a}},t);if(!l.body.data?.requestReviews?.pullRequest?.id)throw new R("Could not re-request pull request reviews",l.body.errors)}async setPullRequestAssignees(e,t={}){let{pullRequest:r,assignees:o}=e;if(!r.graphQLId)throw new Error('GitHub requires "graphQLId" for this function.');let i=o.map(l=>{if(!l.graphQLId)throw new Error('GitHub requires assignee "graphQLId" for this function.');return l.graphQLId}),a=`mutation SetPullRequestAssignees($pullRequestGraphQLId: ID!, $assigneeGraphQLIds: [ID!]!) {
740
+ }`,l=await b(this.config,{query:u,variables:{pullRequestGraphQLId:o,reviewerGraphQLIds:a}},t);if(!l.body.data?.requestReviews?.pullRequest?.id)throw new I("Could not re-request pull request reviews",l.body.errors)}async setPullRequestAssignees(e,t={}){let{pullRequest:s,assignees:o}=e;if(!s.graphQLId)throw new Error('GitHub requires "graphQLId" for this function.');let i=o.map(l=>{if(!l.graphQLId)throw new Error('GitHub requires assignee "graphQLId" for this function.');return l.graphQLId}),a=`mutation SetPullRequestAssignees($pullRequestGraphQLId: ID!, $assigneeGraphQLIds: [ID!]!) {
740
741
  updatePullRequest(input: { pullRequestId: $pullRequestGraphQLId, assigneeIds: $assigneeGraphQLIds }) {
741
742
  pullRequest {
742
743
  id
743
744
  }
744
745
  }
745
- }`,u=await b(this.config,{query:a,variables:{pullRequestGraphQLId:r.graphQLId,assigneeGraphQLIds:i}},t);if(!u.body.data?.updatePullRequest?.pullRequest?.id)throw new R("Could not set pull request assignees",u.body.errors)}async getReviewsForPullRequest(e,t={}){let r=await this.getEnterpriseVersion(t),{repo:{namespace:o,name:i},pullRequestId:a}=e,u=`query getPullRequests(
746
+ }`,u=await b(this.config,{query:a,variables:{pullRequestGraphQLId:s.graphQLId,assigneeGraphQLIds:i}},t);if(!u.body.data?.updatePullRequest?.pullRequest?.id)throw new I("Could not set pull request assignees",u.body.errors)}async getReviewsForPullRequest(e,t={}){let s=await this.getEnterpriseVersion(t),{repo:{namespace:o,name:i},pullRequestId:a}=e,u=`query getPullRequests(
746
747
  $namespace: String!
747
748
  $name: String!
748
749
  $pullRequestId: Int!
@@ -770,7 +771,7 @@ query getBlame($owner: String!, $name: String!, $ref: String!, $path: String!) {
770
771
  login
771
772
  }
772
773
  body
773
- ${!r||Q(r,"PR_REVIEW_COMMENT_FULL_DATABASE_ID")?"fullDatabaseId":"databaseId"}
774
+ ${!s||M(s,"PR_REVIEW_COMMENT_FULL_DATABASE_ID")?"fullDatabaseId":"databaseId"}
774
775
  diffHunk
775
776
  id
776
777
  path
@@ -790,7 +791,7 @@ query getBlame($owner: String!, $name: String!, $ref: String!, $path: String!) {
790
791
  login
791
792
  }
792
793
  body
793
- ${!r||Q(r,"PR_REVIEW_FULL_DATABASE_ID")?"fullDatabaseId":"databaseId"}
794
+ ${!s||M(s,"PR_REVIEW_FULL_DATABASE_ID")?"fullDatabaseId":"databaseId"}
794
795
  id
795
796
  publishedAt
796
797
  url
@@ -798,54 +799,54 @@ query getBlame($owner: String!, $name: String!, $ref: String!, $path: String!) {
798
799
  }
799
800
  }
800
801
  }
801
- }`,l=await b(this.config,{query:u,variables:{namespace:o,name:i,pullRequestId:a}},t),p=l.body.data?.repository.pullRequest.reviewThreads.nodes?.filter(O).reduce((d,g)=>{if(!g.comments.nodes?.[0]?.pullRequestReview)return d;let m=g.comments.nodes[0].pullRequestReview,I=ks(g);return I&&(d[m.id]||(d[m.id]=[]),d[m.id].push(I)),d},{})??{};return{data:l.body.data?.repository.pullRequest.reviews.nodes?.filter(O).filter(d=>p[d.id]).map(d=>({author:d.author?{avatarUrl:d.author.avatarUrl,email:null,name:d.author.login}:null,body:d.body,createdAt:d.publishedAt?new Date(d.publishedAt):null,id:d.fullDatabaseId??d.databaseId.toString(),graphQLId:d.id,reviewComments:p[d.id],url:d.url}))??[]}}async getCommentsForPullRequest(e,t={}){let r=await this.getEnterpriseVersion(t),o=!r||Q(r,"ISSUE_FULL_DATABASE_ID"),{repo:{namespace:i,name:a},pullRequestNumber:u,cursor:l}=e,p=await b(this.config,{query:hr(o),variables:{namespace:i,name:a,pullRequestNumber:u,cursor:l,first:$}},t),c=p.body.data?.repository;if(!c)throw new R("Could not fetch pull request comments",p.body.errors);return{data:c.pullRequest.comments.nodes?.filter(O).map(ur)??[],pageInfo:c.pullRequest.comments.pageInfo}}async getIssuesAssociatedWithUser(e,t={}){let[r,o]=e.cursor?.split(";")||[void 0,void 0],i=[];e.labelNames&&e.labelNames.forEach(d=>{i.push(`label:"${d}"`)});let[a,u]=await Promise.all([r==="null"?null:this.searchIssues({query:`author:${e.username} ${i.join(" ")}`,cursor:r,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=[],c=d=>{l[d.id]||(l[d.id]=!0,p.push(d))};return a?.data.forEach(c),u?.data.forEach(c),{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:r,labels:o}=e;if(!r.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=cn(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||M(s,"ISSUE_FULL_DATABASE_ID"),{repo:{namespace:i,name:a},pullRequestNumber:u,cursor:l}=e,p=await b(this.config,{query:Ar(o),variables:{namespace:i,name:a,pullRequestNumber:u,cursor:l,first:L}},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(vr)??[],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!]) {
802
803
  updatePullRequest(input: { pullRequestId: $pullRequestGraphQLId, labelIds: $labelGraphQLIds }) {
803
804
  pullRequest {
804
805
  id
805
806
  }
806
807
  }
807
- }`,a=await b(this.config,{query:i,variables:{pullRequestGraphQLId:r.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 R("Could not set pull request labels",a.body.errors)}async getIssuesForRepos(e,t={}){let r=gt(e.startQuery||""),{cursor:o,assigneeLogins:i,updatedBefore:a,authorLogin:u,mentionLogin:l,labelNames:p}=e;return e.repos.forEach(c=>{r.push(`repo:${c.namespace}/${c.name}`)}),i&&i.forEach(c=>{r.push(`assignee:${c}`)}),a&&r.push(`updated:<${a}`),u&&r.push(`author:${u}`),l&&r.push(`mentions:${l}`),p&&p.forEach(c=>{r.push(`label:"${c}"`)}),this.searchIssues({query:`sort:updated ${r.join(" ")}`,cursor:o,includeFromArchivedRepos:e.includeFromArchivedRepos,maxPageSize:e.maxPageSize},t)}async closeIssueWithReason(e,t={}){let{issue:r,reason:o}=e;if(!r.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=yt(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!) {
808
809
  closeIssue(input: { issueId: $issueGraphQLId, stateReason: $reason }) {
809
810
  issue {
810
811
  id
811
812
  }
812
813
  }
813
- }`,a=await b(this.config,{query:i,variables:{issueGraphQLId:r.graphQLId,reason:o}},t);if(!a.body.data?.closeIssue?.issue?.id)throw new R("Could not close issue with reason",a.body.errors)}async closeIssue(e,t={}){let{issue:r}=e;if(!r.graphQLId)throw new Error('GitHub requires "graphQLId" for this function.');let o=`mutation SetIssueState($issueGraphQLId: ID!) {
814
+ }`,a=await b(this.config,{query:i,variables:{issueGraphQLId:s.graphQLId,reason:o}},t);if(!a.body.data?.closeIssue?.issue?.id)throw new I("Could not close issue with reason",a.body.errors)}async closeIssue(e,t={}){let{issue:s}=e;if(!s.graphQLId)throw new Error('GitHub requires "graphQLId" for this function.');let o=`mutation SetIssueState($issueGraphQLId: ID!) {
814
815
  updateIssue(input: { id: $issueGraphQLId, state: CLOSED }) {
815
816
  issue {
816
817
  id
817
818
  }
818
819
  }
819
- }`,i=await b(this.config,{query:o,variables:{issueGraphQLId:r.graphQLId}},t);if(!i.body.data?.updateIssue?.issue?.id)throw new R("Could not close issue",i.body.errors)}async reOpenIssue(e,t={}){let{issue:r}=e;if(!r.graphQLId)throw new Error('GitHub requires "graphQLId" for this function.');let o=`mutation ReOpenIssue($issueGraphQLId: ID!) {
820
+ }`,i=await b(this.config,{query:o,variables:{issueGraphQLId:s.graphQLId}},t);if(!i.body.data?.updateIssue?.issue?.id)throw new I("Could not close issue",i.body.errors)}async reOpenIssue(e,t={}){let{issue:s}=e;if(!s.graphQLId)throw new Error('GitHub requires "graphQLId" for this function.');let o=`mutation ReOpenIssue($issueGraphQLId: ID!) {
820
821
  reopenIssue(input: { issueId: $issueGraphQLId }) {
821
822
  issue {
822
823
  id
823
824
  }
824
825
  }
825
- }`,i=await b(this.config,{query:o,variables:{issueGraphQLId:r.graphQLId}},t);if(!i.body.data?.reopenIssue?.issue?.id)throw new R("Could not reopen issue",i.body.errors)}async setIssueLabels(e,t={}){let{issue:r,labels:o}=e;if(!r.graphQLId)throw new Error('GitHub requires "graphQLId" for this function.');let i=o.map(l=>l.graphQLId),a=`mutation SetIssueLabels($issueGraphQLId: ID!, $labelGraphQLIds: [ID!]) {
826
+ }`,i=await b(this.config,{query:o,variables:{issueGraphQLId:s.graphQLId}},t);if(!i.body.data?.reopenIssue?.issue?.id)throw new I("Could not reopen issue",i.body.errors)}async setIssueLabels(e,t={}){let{issue:s,labels:o}=e;if(!s.graphQLId)throw new Error('GitHub requires "graphQLId" for this function.');let i=o.map(l=>l.graphQLId),a=`mutation SetIssueLabels($issueGraphQLId: ID!, $labelGraphQLIds: [ID!]) {
826
827
  updateIssue(input: { id: $issueGraphQLId, labelIds: $labelGraphQLIds }) {
827
828
  issue {
828
829
  id
829
830
  }
830
831
  }
831
- }`,u=await b(this.config,{query:a,variables:{issueGraphQLId:r.graphQLId,labelGraphQLIds:i}},t);if(!u.body.data?.updateIssue?.issue?.id)throw new R("Could not set issue labels",u.body.errors)}async setIssueMilestone(e,t={}){let{issue:r,milestone:o}=e;if(!r.graphQLId)throw new Error('GitHub requires "graphQLId" for this function.');if(o&&!o.graphQLId)throw new Error('GitHub requires milestone "graphQLId" for this function.');let i=`mutation SetIssueMilestone($issueGraphQLId: ID!, $milestoneGraphQLId: ID) {
832
+ }`,u=await b(this.config,{query:a,variables:{issueGraphQLId:s.graphQLId,labelGraphQLIds:i}},t);if(!u.body.data?.updateIssue?.issue?.id)throw new I("Could not set issue labels",u.body.errors)}async setIssueMilestone(e,t={}){let{issue:s,milestone:o}=e;if(!s.graphQLId)throw new Error('GitHub requires "graphQLId" for this function.');if(o&&!o.graphQLId)throw new Error('GitHub requires milestone "graphQLId" for this function.');let i=`mutation SetIssueMilestone($issueGraphQLId: ID!, $milestoneGraphQLId: ID) {
832
833
  updateIssue(input: { id: $issueGraphQLId, milestoneId: $milestoneGraphQLId }) {
833
834
  issue {
834
835
  id
835
836
  }
836
837
  }
837
- }`,a=await b(this.config,{query:`${i}`,variables:{issueGraphQLId:r.graphQLId,milestoneGraphQLId:o?.graphQLId??null}},t);if(!a.body.data?.updateIssue?.issue?.id)throw new R("Could not set milestone of issue",a.body.errors)}async setIssueAssignees(e,t={}){let{issue:r,assignees:o}=e;if(!r.graphQLId)throw new Error('GitHub requires "graphQLId" for this function.');let i=o.map(l=>{if(!l.graphQLId)throw new Error('GitHub requires assignee "graphQLId" for this function.');return l.graphQLId}),a=`mutation SetIssueAssignees($issueGraphQLId: ID!, $assigneeGraphQLIds: [ID!]!) {
838
+ }`,a=await b(this.config,{query:`${i}`,variables:{issueGraphQLId:s.graphQLId,milestoneGraphQLId:o?.graphQLId??null}},t);if(!a.body.data?.updateIssue?.issue?.id)throw new I("Could not set milestone of issue",a.body.errors)}async setIssueAssignees(e,t={}){let{issue:s,assignees:o}=e;if(!s.graphQLId)throw new Error('GitHub requires "graphQLId" for this function.');let i=o.map(l=>{if(!l.graphQLId)throw new Error('GitHub requires assignee "graphQLId" for this function.');return l.graphQLId}),a=`mutation SetIssueAssignees($issueGraphQLId: ID!, $assigneeGraphQLIds: [ID!]!) {
838
839
  updateIssue(input: { id: $issueGraphQLId, assigneeIds: $assigneeGraphQLIds }) {
839
840
  issue {
840
841
  id
841
842
  }
842
843
  }
843
- }`,u=await b(this.config,{query:a,variables:{issueGraphQLId:r.graphQLId,assigneeGraphQLIds:i}},t);if(!u.body.data?.updateIssue?.issue?.id)throw new R("Could not set issue assignees",u.body.errors)}async getMilestonesForRepo(e,t={}){let{repo:{namespace:r,name:o},cursor:i}=e,a=await b(this.config,{query:`
844
+ }`,u=await b(this.config,{query:a,variables:{issueGraphQLId:s.graphQLId,assigneeGraphQLIds:i}},t);if(!u.body.data?.updateIssue?.issue?.id)throw new I("Could not set issue assignees",u.body.errors)}async getMilestonesForRepo(e,t={}){let{repo:{namespace:s,name:o},cursor:i}=e,a=await b(this.config,{query:`
844
845
  query getLabelsForRepo($owner: String!, $name: String! $cursor: String, $first: Int!) {
845
846
  repository(owner: $owner, name: $name) {
846
847
  milestones(first: $first, after: $cursor) {
847
848
  nodes {
848
- ${Ge}
849
+ ${Fe}
849
850
  }
850
851
  pageInfo {
851
852
  endCursor
@@ -854,12 +855,12 @@ query getLabelsForRepo($owner: String!, $name: String! $cursor: String, $first:
854
855
  }
855
856
  }
856
857
  }
857
- `,variables:{owner:r,name:o,cursor:i,first:$}},t);if(!a.body.data)throw new R("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(yt)??[]}}async getLabelsForRepo(e,t={}){let{repo:{namespace:r,name:o},cursor:i}=e,a=await b(this.config,{query:`
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(Ct)??[]}}async getLabelsForRepo(e,t={}){let{repo:{namespace:s,name:o},cursor:i}=e,a=await b(this.config,{query:`
858
859
  query getLabelsForRepo($owner: String!, $name: String! $cursor: String, $first: Int!) {
859
860
  repository(owner: $owner, name: $name) {
860
861
  labels(first: $first, after: $cursor) {
861
862
  nodes {
862
- ${Te}
863
+ ${je}
863
864
  }
864
865
  pageInfo {
865
866
  endCursor
@@ -868,7 +869,7 @@ query getLabelsForRepo($owner: String!, $name: String! $cursor: String, $first:
868
869
  }
869
870
  }
870
871
  }
871
- `,variables:{owner:r,name:o,cursor:i,first:$}},t);if(!a.body.data)throw new R("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(bt)??[]}}async getTreeForRepo(e,t={}){let r=await this.config.request({url:`${B(this.config,t)}/repos/${e.repo.namespace}/${e.repo.name}/git/trees/${e.branch}?recursive=1`,headers:{...f(t.token||this.config.token)}});if(!r.body)throw new Error("Could not fetch trees");return{data:r.body.tree.map(Gs)}}};var js="https://gitlab.com/api/v4",Qs="https://gitlab.com/api/graphql",Pt=/\/api\/v\d+$/,Ir=s=>{if(s.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.")},L=(s,n)=>{let e=n.baseUrl||s.baseUrl;return e?(e=e.replace(/\/$/,""),Ir(e),Pt.test(e)||(e=e+"/api/v4"),e):js},Bs=(s,n)=>{let e=n.baseUrl||s.baseUrl;return e?(e=e.replace(/\/$/,""),Ir(e),Pt.test(e)&&(e=e.replace(Pt,"")),`${e}/api/graphql`):Qs},q=(s,n,e)=>{let t=f(e.token||s.token);return s.request({url:Bs(s,e),method:"POST",headers:{...t,"Content-Type":"application/json"},body:JSON.stringify(n)})},ye=s=>s?.map(n=>`"${n.message}"`).join(", ");var Lt=s=>s.split("/").slice(0,-1).join("/"),Ut=s=>s.split("/").at(-1)??"",br=s=>{let n=parseInt(`${s["x-next-page"]}`,10);return Number.isNaN(n)?{hasNextPage:!1,nextPage:null}:{hasNextPage:!0,nextPage:n}},_e=s=>({id:s.id.replace(de,""),graphQLId:s.id,namespace:Lt(s.fullPath),name:Ut(s.fullPath),webUrl:s.webUrl}),ke=s=>({id:s.id.replace(de,""),graphQLId:s.id,httpsUrl:s.httpUrlToRepo,namespace:Lt(s.fullPath),name:Ut(s.fullPath),sshUrl:s.sshUrlToRepo,webUrl:s.webUrl}),Ms={assigned:"assignedMergeRequests",authored:"authoredMergeRequests",reviewRequested:"reviewRequestedMergeRequests"},zs={CAN_BE_MERGED:"MERGEABLE",CANNOT_BE_MERGED:"CONFLICTS",CANNOT_BE_MERGED_RECHECK:"UNKNOWN",UNCHECKED:"UNKNOWN",CHECKING:"UNKNOWN"};var Pr="gid://gitlab/User/",de="gid://gitlab/Project/",Hs="gid://gitlab/MergeRequest/",Ws="gid://gitlab/Issue/",Js="gid://gitlab/ProjectLabel/",Vs="gid://gitlab/Milestone/",Ks="gid://gitlab/Ci::Build/",At=`
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(Et)??[]}}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(an)}}};var hn="https://gitlab.com/api/v4",fn="https://gitlab.com/api/graphql",$t=/\/api\/v\d+$/,Or=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(/\/$/,""),Or(e),$t.test(e)||(e=e+"/api/v4"),e):hn},Rn=(r,n)=>{let e=n.baseUrl||r.baseUrl;return e?(e=e.replace(/\/$/,""),Or(e),$t.test(e)&&(e=e.replace($t,"")),`${e}/api/graphql`):fn},v=(r,n,e)=>{let t=R(e.token||r.token);return r.request({url:Rn(r,e),method:"POST",headers:{...t,"Content-Type":"application/json"},body:JSON.stringify(n)})},Se=r=>r?.map(n=>`"${n.message}"`).join(", ");var xt=r=>r.split("/").slice(0,-1).join("/"),kt=r=>r.split("/").at(-1)??"",_r=r=>{let n=parseInt(`${r["x-next-page"]}`,10);return Number.isNaN(n)?{hasNextPage:!1,nextPage:null}:{hasNextPage:!0,nextPage:n}},Me=r=>({id:r.id.replace(he,""),graphQLId:r.id,namespace:xt(r.fullPath),name:kt(r.fullPath),webUrl:r.webUrl}),ve=r=>({id:r.id.replace(he,""),graphQLId:r.id,httpsUrl:r.httpUrlToRepo,namespace:xt(r.fullPath),name:kt(r.fullPath),sshUrl:r.sshUrlToRepo,webUrl:r.webUrl}),In={assigned:"assignedMergeRequests",authored:"authoredMergeRequests",reviewRequested:"reviewRequestedMergeRequests"},bn={CAN_BE_MERGED:"MERGEABLE",CANNOT_BE_MERGED:"CONFLICTS",CANNOT_BE_MERGED_RECHECK:"UNKNOWN",UNCHECKED:"UNKNOWN",CHECKING:"UNKNOWN"};var Fr="gid://gitlab/User/",he="gid://gitlab/Project/",yn="gid://gitlab/MergeRequest/",Pn="gid://gitlab/Issue/",wn="gid://gitlab/ProjectLabel/",qn="gid://gitlab/Milestone/",Sn="gid://gitlab/Ci::Build/",Nt=`
872
873
  description
873
874
  dueDate
874
875
  id
@@ -877,7 +878,7 @@ startDate
877
878
  state
878
879
  title
879
880
  webPath
880
- `,wt=`
881
+ `,Dt=`
881
882
  id
882
883
  fullPath
883
884
  webUrl
@@ -891,25 +892,31 @@ userPermissions {
891
892
  downloadCode
892
893
  pushCode
893
894
  }
894
- `,W=`
895
+ `,V=`
895
896
  id
896
897
  name
897
898
  username
898
899
  publicEmail
899
900
  avatarUrl
900
901
  webUrl
901
- `,Gt=`
902
+ `,Ft=`
902
903
  color
903
904
  description
904
905
  id
905
906
  title
906
- `,qt=`
907
+ `,Ee=`
908
+ id
909
+ httpUrlToRepo
910
+ fullPath
911
+ sshUrlToRepo
912
+ webUrl
913
+ `,Lt=`
907
914
  author {
908
- ${W}
915
+ ${V}
909
916
  }
910
917
  assignees {
911
918
  nodes {
912
- ${W}
919
+ ${V}
913
920
  }
914
921
  }
915
922
  closedAt
@@ -920,7 +927,7 @@ id
920
927
  iid
921
928
  labels {
922
929
  nodes {
923
- ${Gt}
930
+ ${Ft}
924
931
  }
925
932
  }
926
933
  state
@@ -931,9 +938,9 @@ upvotes
931
938
  userNotesCount
932
939
  webUrl
933
940
  milestone {
934
- ${At}
941
+ ${Nt}
935
942
  }
936
- `,Xs=`
943
+ `,vn=`
937
944
  stages {
938
945
  nodes {
939
946
  jobs {
@@ -949,11 +956,11 @@ stages {
949
956
  name
950
957
  }
951
958
  }
952
- `,vt=(s,n,e)=>`
959
+ `,Ut=(r,n,e)=>`
953
960
  id
954
961
  state
955
962
  author {
956
- ${W}
963
+ ${V}
957
964
  }
958
965
  diffRefs {
959
966
  baseSha
@@ -979,12 +986,12 @@ targetBranch
979
986
  sourceBranch
980
987
  assignees {
981
988
  nodes {
982
- ${W}
989
+ ${V}
983
990
  }
984
991
  }
985
992
  reviewers {
986
993
  nodes {
987
- ${W}
994
+ ${V}
988
995
  mergeRequestInteraction {
989
996
  approved
990
997
  reviewState
@@ -994,25 +1001,25 @@ reviewers {
994
1001
  mergeStatusEnum
995
1002
  labels {
996
1003
  nodes {
997
- ${Gt}
1004
+ ${Ft}
998
1005
  }
999
1006
  }
1000
- ${s?"project { id httpUrlToRepo fullPath sshUrlToRepo webUrl archived } sourceProject { id httpUrlToRepo fullPath sshUrlToRepo webUrl }":""}
1001
- ${n?`milestone { ${At} }`:""}
1002
- ${e?`headPipeline { ${Xs} }`:""}
1003
- `,T=s=>`${s.namespace}/${s.name}`,Zs=s=>`${s.namespace}/${s.name}`,Ys=s=>/Field '[^']+' (?:doesn'?t|does not) exist on type|Field '[^']+' is not defined|undefined field '[^']+' on type/i.test(s.message),en=s=>({canCreateWebhook:s.adminOperations,canPush:s.pushCode,isAdmin:s.adminOperations}),St=s=>({id:s.id.replace(de,""),graphQLId:s.id,namespace:Lt(s.fullPath),name:Ut(s.fullPath),webUrl:s.webUrl,httpsUrl:s.httpUrlToRepo,sshUrl:s.sshUrlToRepo,defaultBranch:s.repository?.rootRef?{name:s.repository.rootRef}:null,permissions:en(s.userPermissions)}),tn=s=>({path:s.path,isDirectory:s.type==="tree"}),rn={opened:"OPEN",merged:"MERGED",closed:"CLOSED"},Ne=(s,n,e)=>!n&&s?.startsWith("/")?`https://gitlab.com${s}`:n&&s?.startsWith("/")&&e?`${e.replace(/\/+?$/,"")}${s}`:s,J=(s,n,e)=>{let t=Ne(s.avatarUrl,n,e);return{id:s.id.replace(Pr,""),graphQLId:s.id,name:s.name,username:s.username,email:s.publicEmail??null,avatarUrl:t,url:s.webUrl}},Tt=s=>({color:s.color,description:s.description,id:s.id.replace(Js,""),graphQLId:s.id,name:s.title}),sn=(s,n)=>s?s==="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"}[s]:null,nn=(s,n,e)=>{let t={APPROVED:"APPROVED",REQUESTED_CHANGES:"CHANGES_REQUESTED",REVIEWED:"COMMENTED",UNAPPROVED:"REVIEW_REQUESTED",UNREVIEWED:"REVIEW_REQUESTED"};return{reviewer:J(s,n,e),state:s.mergeRequestInteraction?.reviewState?t[s.mergeRequestInteraction.reviewState]:"REVIEW_REQUESTED"}},Et=(s,n,e,t,r)=>{let o=s.reviewers?.nodes?s.reviewers.nodes.map(i=>nn(i,t,r)):null;return{id:s.id.replace(Hs,""),graphQLId:s.id,title:s.title,description:s.description,number:parseInt(s.iid,10),state:rn[s.state],commentCount:s.userNotesCount||0,upvoteCount:s.upvotes,author:s.author?J(s.author,t,r):null,createdDate:new Date(s.createdAt),isDraft:s.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},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:s.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:sn(a.status,a.allowFailure),stage:i.name??null,startedAt:new Date(a.createdAt),url:`${n.webUrl}/-/jobs/${a.id.replace(Ks,"")}`}))??[])??[]},baseRef:{name:s.targetBranch,oid:s.diffRefs?.baseSha??null},headRef:{name:s.sourceBranch,oid:s.diffRefs?.headSha??null},url:s.webUrl,updatedDate:new Date(s.updatedAt),closedDate:s.mergedAt?new Date(s.mergedAt):null,mergedDate:s.mergedAt?new Date(s.mergedAt):null,assignees:s.assignees?.nodes?s.assignees.nodes.map(i=>J(i,t,r)):null,reviews:o,reviewDecision:j(o),additions:s.diffStatsSummary?.additions||0,deletions:s.diffStatsSummary?.deletions||0,fileCount:s.diffStatsSummary?.fileCount||0,commitCount:s.commitCount||0,mergeableState:zs[s.mergeStatusEnum],milestone:s.milestone?Ot(s.milestone,n.webUrl):null,labels:s.labels?.nodes?.map(Tt)??[],permissions:null}},Ct=(s,n,e,t)=>({author:J(s.author,e,t),assignees:s.assignees.nodes.map(r=>J(r,e,t)),commentCount:s.userNotesCount,closedDate:s.closedAt?new Date(s.closedAt):null,createdDate:new Date(s.createdAt),description:s.description,graphQLId:s.id,id:s.id.replace(Ws,""),labels:s.labels?.nodes?.map(Tt)??[],number:s.iid,repository:{id:n.id.replace(de,""),graphQLId:n.id,name:n.name,owner:{login:n.namespace}},updatedDate:new Date(s.updatedAt),upvoteCount:s.upvotes,state:{name:s.state,color:null},type:s.type,title:s.title,url:s.webUrl,milestone:s.milestone?Ot(s.milestone,n.webUrl):null}),Ot=(s,n)=>({id:s.id.replace(Vs,""),graphQLId:s.id,number:parseInt(s.iid,10),title:s.title,description:s.description,isOpen:s.state==="active",url:`${n}/-/${s.webPath.replace(/.+?\/-\//,"")}`,startDate:s.startDate?new Date(s.startDate):null,dueDate:s.dueDate?new Date(s.dueDate):null}),on=s=>Buffer.from(JSON.stringify(s),"utf8").toString("base64"),an=(s,n)=>{if(!s)return{page:1,perPage:n};try{let e=JSON.parse(Buffer.from(s,"base64").toString("utf8")),t=typeof e.page=="number"&&e.page>0?e.page:1,r=typeof e.perPage=="number"&&e.perPage>0?e.perPage:n;return{page:t,perPage:r}}catch{return{page:1,perPage:n}}},un=(s,n,e)=>({id:s.id.toString(),graphQLId:`${Pr}${s.id}`,name:s.name,username:s.username,email:s.email??null,avatarUrl:Ne(s.avatar_url,n,e),url:s.web_url}),yr=(s,n,e)=>({avatarUrl:Ne(s.avatar_url,n,e)??"",email:null,name:s.name}),ln=s=>s?.new_line!=null?"RIGHT":s?.old_line!=null?"LEFT":null,pn=s=>{let n=s.old_path||s.new_path,e=s.new_path||s.old_path,t=[`diff --git a/${n} b/${e}`];return s.new_file&&s.b_mode?t.push(`new file mode ${s.b_mode}`):s.deleted_file&&s.a_mode?t.push(`deleted file mode ${s.a_mode}`):s.a_mode&&s.b_mode&&s.a_mode!==s.b_mode&&(t.push(`old mode ${s.a_mode}`),t.push(`new mode ${s.b_mode}`)),s.renamed_file&&(t.push(`rename from ${s.old_path}`),t.push(`rename to ${s.new_path}`)),s.diff&&s.diff.length>0?(t.push(`--- ${s.new_file?"/dev/null":`a/${n}`}`),t.push(`+++ ${s.deleted_file?"/dev/null":`b/${e}`}`),`${t.join(`
1007
+ ${r?`project { ${Ee} archived } sourceProject { ${Ee} }`:""}
1008
+ ${n?`milestone { ${Nt} }`:""}
1009
+ ${e?`headPipeline { ${vn} }`:""}
1010
+ `,_=r=>`${r.namespace}/${r.name}`,En=r=>`${r.namespace}/${r.name}`,Cn=r=>/Field '[^']+' (?:doesn'?t|does not) exist on type|Field '[^']+' is not defined|undefined field '[^']+' on type/i.test(r.message),$n=r=>({canCreateWebhook:r.adminOperations,canPush:r.pushCode,isAdmin:r.adminOperations}),At=r=>({id:r.id.replace(he,""),graphQLId:r.id,namespace:xt(r.fullPath),name:kt(r.fullPath),webUrl:r.webUrl,httpsUrl:r.httpUrlToRepo,sshUrl:r.sshUrlToRepo,defaultBranch:r.repository?.rootRef?{name:r.repository.rootRef}:null,permissions:$n(r.userPermissions)}),Dn=r=>({path:r.path,isDirectory:r.type==="tree"}),Ln={opened:"OPEN",merged:"MERGED",closed:"CLOSED"},Un={OPEN:"opened",MERGED:"merged",CLOSED:"closed"},xr=r=>{if(!r||r.length===0)return"state: opened";let n=Array.from(new Set(r));return n.length>1?"":`state: ${Un[n[0]]}`},kr=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"}`},te=100,ze=(r,n,e)=>!n&&r?.startsWith("/")?`https://gitlab.com${r}`:n&&r?.startsWith("/")&&e?`${e.replace(/\/+?$/,"")}${r}`:r,K=(r,n,e)=>{let t=ze(r.avatarUrl,n,e);return{id:r.id.replace(Fr,""),graphQLId:r.id,name:r.name,username:r.username,email:r.publicEmail??null,avatarUrl:t,url:r.webUrl}},jt=r=>({color:r.color,description:r.description,id:r.id.replace(wn,""),graphQLId:r.id,name:r.title}),An=(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,Gn=(r,n,e)=>{let t={APPROVED:"APPROVED",REQUESTED_CHANGES:"CHANGES_REQUESTED",REVIEWED:"COMMENTED",UNAPPROVED:"REVIEW_REQUESTED",UNREVIEWED:"REVIEW_REQUESTED"};return{reviewer:K(r,n,e),state:r.mergeRequestInteraction?.reviewState?t[r.mergeRequestInteraction.reviewState]:"REVIEW_REQUESTED"}},Gt=(r,n,e,t,s)=>{let o=r.reviewers?.nodes?r.reviewers.nodes.map(i=>Gn(i,t,s)):null;return{id:r.id.replace(yn,""),graphQLId:r.id,title:r.title,description:r.description,number:parseInt(r.iid,10),state:Ln[r.state],commentCount:r.userNotesCount||0,upvoteCount:r.upvotes,author:r.author?K(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:An(a.status,a.allowFailure),stage:i.name??null,startedAt:new Date(a.createdAt),url:`${n.webUrl}/-/jobs/${a.id.replace(Sn,"")}`}))??[])??[]},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=>K(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:bn[r.mergeStatusEnum],milestone:r.milestone?Qt(r.milestone,n.webUrl):null,labels:r.labels?.nodes?.map(jt)??[],permissions:null}},Tt=(r,n,e,t)=>({author:K(r.author,e,t),assignees:r.assignees.nodes.map(s=>K(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(Pn,""),labels:r.labels?.nodes?.map(jt)??[],number:r.iid,repository:{id:n.id.replace(he,""),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?Qt(r.milestone,n.webUrl):null}),Qt=(r,n)=>({id:r.id.replace(qn,""),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}),Tn=r=>Buffer.from(JSON.stringify(r),"utf8").toString("base64"),On=(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}}},_n=(r,n,e)=>({id:r.id.toString(),graphQLId:`${Fr}${r.id}`,name:r.name,username:r.username,email:r.email??null,avatarUrl:ze(r.avatar_url,n,e),url:r.web_url}),Nr=(r,n,e)=>({avatarUrl:ze(r.avatar_url,n,e)??"",email:null,name:r.name}),xn=r=>r?.new_line!=null?"RIGHT":r?.old_line!=null?"LEFT":null,kn=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(`
1004
1011
  `)}
1005
- ${s.diff.endsWith(`
1006
- `)?s.diff:`${s.diff}
1012
+ ${r.diff.endsWith(`
1013
+ `)?r.diff:`${r.diff}
1007
1014
  `}`):`${t.join(`
1008
1015
  `)}
1009
- `},wr="|",Dt=(s,n,e,t)=>[s,n,e.toString(),t.toString()].join(wr),dn=s=>{let n=s.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]}},$t=(s,n,e,t)=>({author:s.author?un(s.author,n,e):null,body:s.body,createdAt:s.created_at?new Date(s.created_at):null,id:Dt(t.namespace,t.name,t.mergeRequestIid,s.id),url:""}),ce=class extends _{getIsSelfHosted(n){return!!n.baseUrl||!!this.config.baseUrl}async getCurrentUser(n={},e={}){let r=(await q(this.config,{query:`
1016
+ `},jr="|",_t=(r,n,e,t)=>[r,n,e.toString(),t.toString()].join(jr),Nn=r=>{let n=r.split(jr);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]}},Ot=(r,n,e,t)=>({author:r.author?_n(r.author,n,e):null,body:r.body,createdAt:r.created_at?new Date(r.created_at):null,id:_t(t.namespace,t.name,t.mergeRequestIid,r.id),url:""}),fe=class extends N{getIsSelfHosted(n){return!!n.baseUrl||!!this.config.baseUrl}async getCurrentUser(n={},e={}){let s=(await v(this.config,{query:`
1010
1017
  query getCurrentUser {
1011
1018
  currentUser {
1012
- ${W}
1019
+ ${V}
1013
1020
  }
1014
1021
  }
1015
- `},e)).body.data?.currentUser;if(!r)throw new Error("Current user not found.");return{data:J(r,this.getIsSelfHosted(e),this.config.baseUrl??e.baseUrl)}}async getUserForCommit(n,e={}){let t=T(n.repo),o=(await q(this.config,{query:`
1022
+ `},e)).body.data?.currentUser;if(!s)throw new Error("Current user not found.");return{data:K(s,this.getIsSelfHosted(e),this.config.baseUrl??e.baseUrl)}}async getUserForCommit(n,e={}){let t=_(n.repo),o=(await v(this.config,{query:`
1016
1023
  query getUserForCommit($fullPath: ID!, $oid: String!) {
1017
1024
  project(fullPath: $fullPath) {
1018
1025
  repository {
@@ -1028,21 +1035,21 @@ query getUserForCommit($fullPath: ID!, $oid: String!) {
1028
1035
  }
1029
1036
  }
1030
1037
  }
1031
- `,variables:{fullPath:t,oid:n.oid}},e)).body.data?.project?.repository?.tree?.lastCommit;if(!o)throw new Error("Commit not found.");let i=Ne(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 r=(await q(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=ze(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:`
1032
1039
  query getAccountForEmail($email: String!) {
1033
1040
  users(search: $email) {
1034
1041
  nodes {
1035
- ${W}
1042
+ ${V}
1036
1043
  }
1037
1044
  }
1038
1045
  }
1039
- `,variables:{email:n.email}},e)).body.data?.users?.nodes?.[0];if(!r)throw new Error("User not found.");return{data:J(r,this.getIsSelfHosted(e),this.config.baseUrl??e.baseUrl)}}async getAccountForUsername(n,e={}){let r=(await q(this.config,{query:`
1046
+ `,variables:{email:n.email}},e)).body.data?.users?.nodes?.[0];if(!s)throw new Error("User not found.");return{data:K(s,this.getIsSelfHosted(e),this.config.baseUrl??e.baseUrl)}}async getAccountForUsername(n,e={}){let s=(await v(this.config,{query:`
1040
1047
  query getAccountForUsername($username: String!) {
1041
1048
  user(username: $username) {
1042
- ${W}
1049
+ ${V}
1043
1050
  }
1044
1051
  }
1045
- `,variables:{username:n.username}},e)).body.data?.user;if(!r)throw new Error("User not found.");return{data:J(r,this.getIsSelfHosted(e),this.config.baseUrl??e.baseUrl)}}async getAccountsForRepo(n,e={}){let{repo:{namespace:t,name:r},cursor:o}=n,i=await q(this.config,{query:`
1052
+ `,variables:{username:n.username}},e)).body.data?.user;if(!s)throw new Error("User not found.");return{data:K(s,this.getIsSelfHosted(e),this.config.baseUrl??e.baseUrl)}}async getAccountsForRepo(n,e={}){let{repo:{namespace:t,name:s},cursor:o}=n,i=await v(this.config,{query:`
1046
1053
  query getAccountsForRepo(
1047
1054
  $fullPath: ID!
1048
1055
  $after: String
@@ -1053,7 +1060,7 @@ query getAccountsForRepo(
1053
1060
  projectMembers(after: $after) {
1054
1061
  nodes {
1055
1062
  user {
1056
- ${W}
1063
+ ${V}
1057
1064
  }
1058
1065
  }
1059
1066
  pageInfo {
@@ -1063,22 +1070,22 @@ query getAccountsForRepo(
1063
1070
  }
1064
1071
  }
1065
1072
  }
1066
- `,variables:{fullPath:`${t}/${r}`,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=>J(u,this.getIsSelfHosted(e),this.config.baseUrl??e.baseUrl))??[]}}async getRepo(n,e={}){let t=T(n),r=await q(this.config,{query:`
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=>K(u,this.getIsSelfHosted(e),this.config.baseUrl??e.baseUrl))??[]}}async getRepo(n,e={}){let t=_(n),s=await v(this.config,{query:`
1067
1074
  query getRepo($fullPath: ID!) {
1068
1075
  project(fullPath: $fullPath) {
1069
- ${wt}
1076
+ ${Dt}
1070
1077
  }
1071
1078
  }
1072
- `,variables:{fullPath:t}},e);if(!r.body.data?.project)throw new Error(`Repository ${t} not found`);return{data:St(r.body.data.project)}}async getReposBase(n,e={}){let r=n.map(T).map((u,l)=>`
1079
+ `,variables:{fullPath:t}},e);if(!s.body.data?.project)throw new Error(`Repository ${t} not found`);return{data:At(s.body.data.project)}}async getReposBase(n,e={}){let s=n.map(_).map((u,l)=>`
1073
1080
  getRepo_${l}: project(fullPath: "${u}") {
1074
- ${wt}
1081
+ ${Dt}
1075
1082
  }
1076
1083
  `).join(`
1077
- `),o=await q(this.config,{query:`
1084
+ `),o=await v(this.config,{query:`
1078
1085
  query batchGetRepos {
1079
- ${r}
1086
+ ${s}
1080
1087
  }
1081
- `},e);if(!o.body.data)throw new Error(ye(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(St(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 q(this.config,{query:`
1088
+ `},e);if(!o.body.data)throw new Error(Se(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(At(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:`
1082
1089
  query getReposForCurrentUser($after: String) {
1083
1090
  projects(membership: true first: 100 after: $after) {
1084
1091
  pageInfo {
@@ -1086,29 +1093,29 @@ query getReposForCurrentUser($after: String) {
1086
1093
  hasNextPage
1087
1094
  }
1088
1095
  nodes {
1089
- ${wt}
1096
+ ${Dt}
1090
1097
  }
1091
1098
  }
1092
1099
  }
1093
- `,variables:{after:n.cursor}},e);if(!t.body.data?.projects)throw new Error(ye(t.body.errors)||t.statusText||"Unknown error");let r=t.body.data?.projects?.nodes||[];return{pageInfo:t.body.data?.projects?.pageInfo,data:r.map(St)}}async getGroupsForCurrentUser(n={},e={}){let t=new URL(`${L(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",$.toString());let r=await this.config.request({url:t.toString(),headers:f(e.token||this.config.token)});return{pageInfo:br(r.headers),data:r.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 r=T(e.repo),o=new URL(`${L(this.config,t)}/projects/${encodeURIComponent(r)}/repository/${n}`);o.searchParams.set("page",e.page?.toString()||"1"),o.searchParams.set("per_page",$.toString());let i=await this.config.request({url:o.toString(),headers:f(t.token||this.config.token)});return{pageInfo:br(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=T(n.repo),r=new URL(`${L(this.config,e)}/projects/${encodeURIComponent(t)}/repository/files/${encodeURIComponent(n.path)}/blame`);r.searchParams.set("ref",n.ref);let o=await this.config.request({url:r.toString(),headers:f(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 r=Ms[n.association],o=await q(this.config,{query:`
1100
+ `,variables:{after:n.cursor}},e);if(!t.body.data?.projects)throw new Error(Se(t.body.errors)||t.statusText||"Unknown error");let s=t.body.data?.projects?.nodes||[];return{pageInfo:t.body.data?.projects?.pageInfo,data:s.map(At)}}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",L.toString());let s=await this.config.request({url:t.toString(),headers:R(e.token||this.config.token)});return{pageInfo:_r(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",L.toString());let i=await this.config.request({url:o.toString(),headers:R(t.token||this.config.token)});return{pageInfo:_r(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=In[n.association],o=xr(n.states),i=U(n.pageSize,{fallback:te,max:te}),a=await v(this.config,{query:`
1094
1101
  query getPullRequestsForUser($username: String! $cursor: String $labelNames: [String!]) {
1095
1102
  user(username: $username) {
1096
- ${r}(state:opened first:100 after:$cursor labels: $labelNames${t?` ${t}`:""}) {
1103
+ ${s}(${o} first: ${i} after:$cursor labels: $labelNames${t?` ${t}`:""}) {
1097
1104
  pageInfo {
1098
1105
  endCursor
1099
1106
  hasNextPage
1100
1107
  }
1101
1108
  nodes {
1102
- ${vt(!0,!0,!0)}
1109
+ ${Ut(!0,!0,!0)}
1103
1110
  }
1104
1111
  }
1105
1112
  }
1106
1113
  }
1107
- `,variables:{username:n.username,cursor:n.cursor,labelNames:n.labelNames}},e);if(!o.body.data)throw new Error(ye(o.body.errors)||o.statusText||"Unknown error");if(!o.body.data.user)throw new Error("User not found");let i=o.body.data.user[r];if(!i)throw new Error("Unexpected response");return{pageInfo:i.pageInfo,data:i.nodes?.filter(a=>n.includeFromArchivedRepos||!a.project.archived).map(a=>Et(a,ke(a.project),ke(a.sourceProject),this.getIsSelfHosted(e),this.config.baseUrl??e.baseUrl))||[]}}async getPullRequestsAssociatedWithUser(n,e={}){let[t,r,o]=n.cursor?.split(";")||[void 0,void 0,void 0],i=t?.split("-")||[],a=r?.split("-")||[],u=o?.split("-")||[],l=[],p=[],c=[],d=0;do{let E=n.repos&&n.repos[d];i[d]==="null"?l.push(null):l.push(this.getPullRequestsForUser({username:n.username,association:"authored",cursor:i[d],includeFromArchivedRepos:n.includeFromArchivedRepos,labelNames:n.labelNames,...E&&{repo:E}},e)),a[d]==="null"?p.push(null):p.push(this.getPullRequestsForUser({username:n.username,association:"assigned",cursor:a[d],includeFromArchivedRepos:n.includeFromArchivedRepos,labelNames:n.labelNames,...E&&{repo:E}},e)),u[d]==="null"?c.push(null):c.push(this.getPullRequestsForUser({username:n.username,association:"reviewRequested",cursor:u[d],includeFromArchivedRepos:n.includeFromArchivedRepos,labelNames:n.labelNames,...E&&{repo:E}},e)),d++}while(d<(n.repos?.length||0));let g=[l,p,c].flat(),m=await Promise.all(g),I={},y=[],h=E=>{I[E.id]||(I[E.id]=!0,y.push(E))},v=!1,x=m.map((E,P)=>{let S="";return E&&E.data.forEach(h),E?.pageInfo.hasNextPage?(v=!0,S+=`${E.pageInfo.endCursor||"null"}`):S+="null",n.repos?.length&&(P+1)%n.repos.length!==0?S+="-":P+1<m.length&&(S+=";"),S}).join("");return{pageInfo:{hasNextPage:v,endCursor:x},data:y}}getVariablesForPullRequests(n){let{updatedBefore:e,isDraft:t,authorLogin:r,assigneeLogins:o,labelNames:i,reviewRequestedLogin:a}=n||{},u={},l=[],p=[],c=(d,g,m)=>{l.push(`$${d}: ${m}`),p.push(`${d}: $${d}`),u[d]=g};return e&&c("updatedBefore",e,"Time"),r&&c("authorUsername",r,"String"),o&&c("assigneeUsername",o[0],"String"),i&&c("labelName",i,"[String]"),t!=null&&c("draft",t,"Boolean"),a&&c("reviewerUsername",a,"String"),{variables:u,variableTypes:l,mergeRequestArguments:p}}async getPullRequestsForRepoBase(n,e={},t){let{cursor:r,repo:o}=n||{},i=T(o),{variables:a,variableTypes:u,mergeRequestArguments:l}=this.getVariablesForPullRequests(n),p={fullPath:i,...a},c=await q(this.config,{query:`
1114
+ `,variables:{username:n.username,cursor:n.cursor,labelNames:n.labelNames}},e);if(!a.body.data)throw new Error(Se(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=>Gt(p,ve(p.project),p.sourceProject?ve(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 $=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"?p.push(null):p.push(this.getPullRequestsForUser({username:n.username,association:"assigned",cursor:a[c],includeFromArchivedRepos:n.includeFromArchivedRepos,labelNames:n.labelNames,...$&&{repo:$}},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,...$&&{repo:$}},e)),c++}while(c<(n.repos?.length||0));let g=[l,p,d].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=[],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=xr(n.states),u=U(n.pageSize,{fallback:te,max:te}),{variables:l,variableTypes:p,mergeRequestArguments:d}=this.getVariablesForPullRequests(n),c={fullPath:i,...l},g=await v(this.config,{query:`
1108
1115
  query getPullRequestsForRepo(
1109
1116
  $fullPath: ID!
1110
1117
  $after: String
1111
- ${u.length?u.join(" "):""}
1118
+ ${p.length?p.join(" "):""}
1112
1119
  ) {
1113
1120
  project(
1114
1121
  fullPath: $fullPath
@@ -1118,30 +1125,33 @@ query getPullRequestsForRepo(
1118
1125
  webUrl
1119
1126
  archived
1120
1127
  mergeRequests(
1121
- first: 100
1122
- state: opened
1128
+ first: ${u}
1129
+ ${a}
1123
1130
  sort: UPDATED_DESC
1124
1131
  after: $after
1125
- ${l.length?l.join(" "):""}
1132
+ ${d.length?d.join(" "):""}
1126
1133
  ) {
1127
1134
  pageInfo {
1128
1135
  endCursor
1129
1136
  hasNextPage
1130
1137
  }
1131
1138
  nodes {
1132
- ${vt(!1,!0,!0)}
1139
+ ${Ut(!1,!0,!0)}
1140
+ sourceProject {
1141
+ ${Ee}
1142
+ }
1133
1143
  }
1134
1144
  }
1135
1145
  }
1136
1146
  }
1137
- `,variables:{...p,after:r}},e),d=[],g=c.body.data?.project;if(!t&&g?.archived)return{pageInfo:null,data:[]};let m=_e(g||{id:"",fullPath:"",webUrl:""});return(g?.mergeRequests?.nodes||[]).forEach(y=>{d.push(Et(y,m,null,this.getIsSelfHosted(e),this.config.baseUrl??e.baseUrl))}),{pageInfo:g?.mergeRequests?.pageInfo,data:d}}async getPullRequestsForRepo(n,e={}){return this.getPullRequestsForRepoBase(n,e,!1)}async getPullRequestsForRepos(n,e={}){let{repos:t,assigneeLogins:r,updatedBefore:o,authorLogin:i,labelNames:a,isDraft:u,reviewRequestedLogin:l}=n;return{data:(await Promise.all(t.map(c=>this.getPullRequestsForRepoBase({repo:c,assigneeLogins:r,updatedBefore:o,authorLogin:i,labelNames:a,isDraft:u,reviewRequestedLogin:l},e,n.includeFromArchivedRepos??!1)))).flatMap(c=>c.data)}}async closePullRequest(n,e={}){let{pullRequest:t}=n,r=`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=Me(h||{id:"",fullPath:"",webUrl:""});return(h?.mergeRequests?.nodes||[]).forEach(P=>{let S=P.sourceProject?ve(P.sourceProject):null;m.push(Gt(P,y,S,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!) {
1138
1148
  mergeRequestUpdate(input: { projectPath: $fullPath, iid: $pullRequestId, state: CLOSED }) {
1139
1149
  errors,
1140
1150
  mergeRequest {
1141
1151
  id
1142
1152
  }
1143
1153
  }
1144
- }`,i=(await q(this.config,{query:r,variables:{fullPath:`${t.repository.owner.login}/${t.repository.name}`,pullRequestId:t.number.toString()}},e)).body.data?.mergeRequestUpdate;if(!i?.mergeRequest?.id||i?.errors?.length!==0)throw new Error("Could not close pull request")}async mergePullRequest(n,e={}){let{pullRequest:t,mergeStrategy:r}=n;if(!t.headRef?.oid)throw new Error('GitLab requires "headRef.oid" for this function.');let o=`mutation MergePullRequest(
1154
+ }`,i=(await v(this.config,{query:s,variables:{fullPath:`${t.repository.owner.login}/${t.repository.name}`,pullRequestId:t.number.toString()}},e)).body.data?.mergeRequestUpdate;if(!i?.mergeRequest?.id||i?.errors?.length!==0)throw new Error("Could not close pull request")}async mergePullRequest(n,e={}){let{pullRequest:t,mergeStrategy:s}=n;if(!t.headRef?.oid)throw new Error('GitLab requires "headRef.oid" for this function.');let o=`mutation MergePullRequest(
1145
1155
  $fullPath: ID!,
1146
1156
  $pullRequestId: String!,
1147
1157
  $expectedSourceSha: String!,
@@ -1158,63 +1168,63 @@ query getPullRequestsForRepo(
1158
1168
  id
1159
1169
  }
1160
1170
  }
1161
- }`,a=(await q(this.config,{query:o,variables:{fullPath:`${t.repository.owner.login}/${t.repository.name}`,pullRequestId:t.number.toString(),expectedSourceSha:t.headRef.oid,squash:r==="SQUASH"}},e)).body.data?.mergeRequestAccept;if(!a?.mergeRequest?.id||a?.errors?.length!==0)throw new Error("Could not merge pull request")}async setPullRequestMilestone(n,e={}){let{pullRequest:t,milestone:r}=n;if(!t.graphQLId)throw new Error('GitHub requires "graphQLId" for this function.');let o=`mutation SetPullRequestMilestone($fullPath: ID!, $pullRequestId: String!, $milestoneGraphQLId: MilestoneID) {
1171
+ }`,a=(await v(this.config,{query:o,variables:{fullPath:`${t.repository.owner.login}/${t.repository.name}`,pullRequestId:t.number.toString(),expectedSourceSha:t.headRef.oid,squash:s==="SQUASH"}},e)).body.data?.mergeRequestAccept;if(!a?.mergeRequest?.id||a?.errors?.length!==0)throw new Error("Could not merge pull request")}async setPullRequestMilestone(n,e={}){let{pullRequest:t,milestone:s}=n;if(!t.graphQLId)throw new Error('GitHub requires "graphQLId" for this function.');let o=`mutation SetPullRequestMilestone($fullPath: ID!, $pullRequestId: String!, $milestoneGraphQLId: MilestoneID) {
1162
1172
  mergeRequestSetMilestone(input: { projectPath: $fullPath, iid: $pullRequestId, milestoneId: $milestoneGraphQLId }) {
1163
1173
  errors,
1164
1174
  mergeRequest {
1165
1175
  id
1166
1176
  }
1167
1177
  }
1168
- }`,i=await q(this.config,{query:o,variables:{fullPath:`${t.repository.owner.login}/${t.repository.name}`,pullRequestId:t.number.toString(),milestoneGraphQLId:r?.graphQLId}},e),a=i.body.data?.mergeRequestSetMilestone;if(!a?.mergeRequest?.id||i.body.errors||a?.errors?.length!==0)throw new Error("Could not set milestone of pull request")}async setPullRequestAsDraft(n,e={}){let{pullRequest:t,isDraft:r}=n,o=`mutation MergeRequestSetDraft($fullPath: ID!, $pullRequestId: String!, $isDraft: Boolean!) {
1178
+ }`,i=await v(this.config,{query:o,variables:{fullPath:`${t.repository.owner.login}/${t.repository.name}`,pullRequestId:t.number.toString(),milestoneGraphQLId:s?.graphQLId}},e),a=i.body.data?.mergeRequestSetMilestone;if(!a?.mergeRequest?.id||i.body.errors||a?.errors?.length!==0)throw new Error("Could not set milestone of pull request")}async setPullRequestAsDraft(n,e={}){let{pullRequest:t,isDraft:s}=n,o=`mutation MergeRequestSetDraft($fullPath: ID!, $pullRequestId: String!, $isDraft: Boolean!) {
1169
1179
  mergeRequestSetDraft(input: { projectPath: $fullPath, iid: $pullRequestId, draft: $isDraft }) {
1170
1180
  errors,
1171
1181
  mergeRequest {
1172
1182
  id
1173
1183
  }
1174
1184
  }
1175
- }`,a=(await q(this.config,{query:o,variables:{fullPath:`${t.repository.owner.login}/${t.repository.name}`,pullRequestId:t.number.toString(),isDraft:r}},e)).body.data?.mergeRequestSetDraft;if(!a?.mergeRequest?.id||a?.errors?.length!==0)throw new Error("Could not set pull request as draft")}async setPullRequestReviewers(n,e={}){let{pullRequest:t,reviewers:r}=n,o=r.map(l=>{if(!l.username)throw new Error('GitLab requires reviewer "username" for this function.');return l.username}),i=`mutation MergeRequestSetReviewers($fullPath: ID!, $pullRequestId: String!, $reviewerUsernames: [String!]!) {
1185
+ }`,a=(await v(this.config,{query:o,variables:{fullPath:`${t.repository.owner.login}/${t.repository.name}`,pullRequestId:t.number.toString(),isDraft:s}},e)).body.data?.mergeRequestSetDraft;if(!a?.mergeRequest?.id||a?.errors?.length!==0)throw new Error("Could not set pull request as draft")}async setPullRequestReviewers(n,e={}){let{pullRequest:t,reviewers:s}=n,o=s.map(l=>{if(!l.username)throw new Error('GitLab requires reviewer "username" for this function.');return l.username}),i=`mutation MergeRequestSetReviewers($fullPath: ID!, $pullRequestId: String!, $reviewerUsernames: [String!]!) {
1176
1186
  mergeRequestSetReviewers(input: { projectPath: $fullPath, iid: $pullRequestId, reviewerUsernames: $reviewerUsernames }) {
1177
1187
  errors,
1178
1188
  mergeRequest {
1179
1189
  id
1180
1190
  }
1181
1191
  }
1182
- }`,u=(await q(this.config,{query:i,variables:{fullPath:`${t.repository.owner.login}/${t.repository.name}`,pullRequestId:t.number.toString(),reviewerUsernames:o}},e)).body.data?.mergeRequestSetReviewers;if(!u?.mergeRequest?.id||u?.errors?.length!==0)throw new Error("Could not set pull request reviewers")}async reRequestPullRequestReview(n,e={}){let{pullRequest:t,reviewer:r}=n;if(!r.graphQLId)throw new Error('GitLab requires reviwer "graphQLId" for this function.');let o=`mutation MergeRequestReviewerRereview($fullPath: ID!, $pullRequestId: String!, $reviewerUserId: UserID!) {
1192
+ }`,u=(await v(this.config,{query:i,variables:{fullPath:`${t.repository.owner.login}/${t.repository.name}`,pullRequestId:t.number.toString(),reviewerUsernames:o}},e)).body.data?.mergeRequestSetReviewers;if(!u?.mergeRequest?.id||u?.errors?.length!==0)throw new Error("Could not set pull request reviewers")}async reRequestPullRequestReview(n,e={}){let{pullRequest:t,reviewer:s}=n;if(!s.graphQLId)throw new Error('GitLab requires reviwer "graphQLId" for this function.');let o=`mutation MergeRequestReviewerRereview($fullPath: ID!, $pullRequestId: String!, $reviewerUserId: UserID!) {
1183
1193
  mergeRequestReviewerRereview(input: { projectPath: $fullPath, iid: $pullRequestId, userId: $reviewerUserId }) {
1184
1194
  errors,
1185
1195
  mergeRequest {
1186
1196
  id
1187
1197
  }
1188
1198
  }
1189
- }`,a=(await q(this.config,{query:o,variables:{fullPath:`${t.repository.owner.login}/${t.repository.name}`,pullRequestId:t.number.toString(),reviewerUserId:r.graphQLId}},e)).body.data?.mergeRequestReviewerRereview;if(!a?.mergeRequest?.id||a?.errors?.length!==0)throw new Error("Could not set pull request reviewers")}async reRequestPullRequestReviews(n,e={}){let{pullRequest:t,reviewers:r}=n,o=t.reviews;if(!o)throw new Error('GitLab requires "reviews" for this function.');let i=r.filter(a=>o.find(u=>u.reviewer.graphQLId===a.graphQLId));await Promise.all(i.map(a=>this.reRequestPullRequestReview({pullRequest:t,reviewer:a},e)))}async setPullRequestAssignees(n,e={}){let{pullRequest:t,assignees:r}=n,o=r.map(l=>{if(!l.username)throw new Error('GitLab requires assignee "username" for this function.');return l.username}),i=`mutation MergeRequestSetAssignees($fullPath: ID!, $pullRequestId: String!, $assigneeUsernames: [String!]!) {
1199
+ }`,a=(await v(this.config,{query:o,variables:{fullPath:`${t.repository.owner.login}/${t.repository.name}`,pullRequestId:t.number.toString(),reviewerUserId:s.graphQLId}},e)).body.data?.mergeRequestReviewerRereview;if(!a?.mergeRequest?.id||a?.errors?.length!==0)throw new Error("Could not set pull request reviewers")}async reRequestPullRequestReviews(n,e={}){let{pullRequest:t,reviewers:s}=n,o=t.reviews;if(!o)throw new Error('GitLab requires "reviews" for this function.');let i=s.filter(a=>o.find(u=>u.reviewer.graphQLId===a.graphQLId));await Promise.all(i.map(a=>this.reRequestPullRequestReview({pullRequest:t,reviewer:a},e)))}async setPullRequestAssignees(n,e={}){let{pullRequest:t,assignees:s}=n,o=s.map(l=>{if(!l.username)throw new Error('GitLab requires assignee "username" for this function.');return l.username}),i=`mutation MergeRequestSetAssignees($fullPath: ID!, $pullRequestId: String!, $assigneeUsernames: [String!]!) {
1190
1200
  mergeRequestSetAssignees(input: { projectPath: $fullPath, iid: $pullRequestId, assigneeUsernames: $assigneeUsernames }) {
1191
1201
  errors,
1192
1202
  mergeRequest {
1193
1203
  id
1194
1204
  }
1195
1205
  }
1196
- }`,u=(await q(this.config,{query:i,variables:{fullPath:`${t.repository.owner.login}/${t.repository.name}`,pullRequestId:t.number.toString(),assigneeUsernames:o}},e)).body.data?.mergeRequestSetAssignees;if(!u?.mergeRequest?.id||u?.errors?.length!==0)throw new Error("Could not set pull request assignees")}async setPullRequestLabels(n,e={}){let{pullRequest:t,labels:r}=n,o=r.map(u=>{if(!u.graphQLId)throw new Error('GitLab requires "graphQLId" for labels in this function.');return u.graphQLId}),i=`mutation SetPullRequestLabels($fullPath: ID!, $pullRequestId: String!, $labelGraphQLIds: [LabelID!]!) {
1206
+ }`,u=(await v(this.config,{query:i,variables:{fullPath:`${t.repository.owner.login}/${t.repository.name}`,pullRequestId:t.number.toString(),assigneeUsernames:o}},e)).body.data?.mergeRequestSetAssignees;if(!u?.mergeRequest?.id||u?.errors?.length!==0)throw new Error("Could not set pull request assignees")}async setPullRequestLabels(n,e={}){let{pullRequest:t,labels:s}=n,o=s.map(u=>{if(!u.graphQLId)throw new Error('GitLab requires "graphQLId" for labels in this function.');return u.graphQLId}),i=`mutation SetPullRequestLabels($fullPath: ID!, $pullRequestId: String!, $labelGraphQLIds: [LabelID!]!) {
1197
1207
  mergeRequestSetLabels(input: { projectPath: $fullPath, iid: $pullRequestId, labelIds: $labelGraphQLIds }) {
1198
1208
  mergeRequest {
1199
1209
  id
1200
1210
  }
1201
1211
  }
1202
- }`;if(!(await q(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=Zs(n),r=await q(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=En(n),s=await v(this.config,{query:`
1203
1213
  query GetSingleIssue($projectId: ID!, $issueNumber: String!) {
1204
1214
  project(fullPath: $projectId) {
1205
1215
  id
1206
1216
  fullPath
1207
1217
  webUrl
1208
1218
  issue(iid: $issueNumber) {
1209
- ${qt}
1219
+ ${Lt}
1210
1220
  }
1211
1221
  }
1212
1222
  }
1213
- `,variables:{issueNumber:n.number,projectId:t}},e);if(!r.body.data?.project)throw new Error(`Repository ${t} not found`);if(!r.body.data?.project?.issue)throw new Error(`Issue ${n.number} not found`);return{data:Ct(r.body.data.project.issue,_e(r.body.data.project),this.getIsSelfHosted(e),this.config.baseUrl??e.baseUrl)}}getVariablesForIssues(n){let{updatedBefore:e,authorLogin:t,assigneeLogins:r,labelNames:o}=n||{},i={},a=[],u=[],l=(p,c,d)=>{a.push(`$${p}: ${d}`),u.push(`${p}: $${p}`),i[p]=c};return e&&l("updatedBefore",e,"Time"),t&&l("authorUsername",t,"String"),r&&l("assigneeUsername",r[0],"String"),o&&l("labelName",o,"[String]"),{variables:i,variableTypes:a,issueArguments:u}}async getIssuesForRepo(n,e={}){let{cursor:t,repo:r}=n||{},o=T(r),{variables:i,variableTypes:a,issueArguments:u}=this.getVariablesForIssues(n),l={fullPath:o,...i},p=`
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:Tt(s.body.data.project.issue,Me(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=kr(n.states),a=U(n.pageSize,{fallback:te,max:te}),{variables:u,variableTypes:l,issueArguments:p}=this.getVariablesForIssues(n),d={fullPath:o,...u},c=`
1214
1224
  query GetIssuesFromProject(
1215
1225
  $fullPath: ID!
1216
1226
  $after: String
1217
- ${a.length?a.join(" "):""}
1227
+ ${l.length?l.join(" "):""}
1218
1228
  ) {
1219
1229
  project(
1220
1230
  fullPath: $fullPath
@@ -1223,14 +1233,14 @@ query GetSingleIssue($projectId: ID!, $issueNumber: String!) {
1223
1233
  fullPath
1224
1234
  webUrl
1225
1235
  issues(
1226
- first: 100
1227
- state: opened
1236
+ first: ${a}
1237
+ ${i}
1228
1238
  sort: UPDATED_DESC
1229
1239
  after: $after
1230
- ${u.length?u.join(" "):""}
1240
+ ${p.length?p.join(" "):""}
1231
1241
  ) {
1232
1242
  nodes {
1233
- ${qt}
1243
+ ${Lt}
1234
1244
  }
1235
1245
  pageInfo {
1236
1246
  endCursor
@@ -1238,11 +1248,11 @@ query GetSingleIssue($projectId: ID!, $issueNumber: String!) {
1238
1248
  }
1239
1249
  }
1240
1250
  }
1241
- }`,c=await q(this.config,{query:p,variables:{...l,after:t}},e),d=[],g=c.body.data?.project,m=_e(g||{id:"",fullPath:"",webUrl:""});return(g?.issues?.nodes||[]).forEach(y=>{d.push(Ct(y,m,this.getIsSelfHosted(e),this.config.baseUrl??e.baseUrl))}),{pageInfo:g?.issues?.pageInfo??{endCursor:null,hasNextPage:!1},data:d.sort((y,h)=>(y.updatedDate||y.createdDate).getTime()-(h.updatedDate||h.createdDate).getTime())}}async getIssuesForRepos(n,e={}){let{cursor:t}=n||{},r=n.repoIds.map(g=>g.toString().startsWith(de)?g:`${de}${g}`),{variables:o,variableTypes:i,mergeRequestArguments:a}=this.getVariablesForPullRequests(n),u={projectIds:r,...o},l=`
1251
+ }`,g=await v(this.config,{query:c,variables:{...d,after:t}},e),m=[],h=g.body.data?.project,y=Me(h||{id:"",fullPath:"",webUrl:""});return(h?.issues?.nodes||[]).forEach(P=>{m.push(Tt(P,y,this.getIsSelfHosted(e),this.config.baseUrl??e.baseUrl))}),{pageInfo:h?.issues?.pageInfo??{endCursor:null,hasNextPage:!1},data:m.sort((P,S)=>(P.updatedDate||P.createdDate).getTime()-(S.updatedDate||S.createdDate).getTime())}}async getIssuesForRepos(n,e={}){let{cursor:t}=n||{},s=kr(n.states),o=U(n.pageSize,{fallback:te,max:te}),i=n.repoIds.map(h=>h.toString().startsWith(he)?h:`${he}${h}`),{variables:a,variableTypes:u,issueArguments:l}=this.getVariablesForIssues(n),p={projectIds:i,...a},d=`
1242
1252
  query GetIssuesFromProject(
1243
1253
  $projectIds: [ID!]
1244
1254
  $after: String
1245
- ${i.length?i.join(" "):""}
1255
+ ${u.length?u.join(" "):""}
1246
1256
  ) {
1247
1257
  projects(
1248
1258
  ids: $projectIds
@@ -1258,30 +1268,30 @@ query GetSingleIssue($projectId: ID!, $issueNumber: String!) {
1258
1268
  webUrl
1259
1269
  archived
1260
1270
  issues(
1261
- first: 100
1262
- state: opened
1271
+ first: ${o}
1272
+ ${s}
1263
1273
  sort: UPDATED_DESC
1264
- ${a.length?a.join(" "):""}
1274
+ ${l.length?l.join(" "):""}
1265
1275
  ) {
1266
1276
  nodes {
1267
- ${qt}
1277
+ ${Lt}
1268
1278
  }
1269
1279
  }
1270
1280
  }
1271
1281
  }
1272
- }`,p=await q(this.config,{query:l,variables:{...u,after:t}},e),c=[];return(p.body.data?.projects?.nodes||[]).forEach(g=>{if(!n.includeFromArchivedRepos&&g.archived)return;let m=_e(g);(g.issues?.nodes||[]).forEach(y=>c.push(Ct(y,m,this.getIsSelfHosted(e),this.config.baseUrl??e.baseUrl)))}),{pageInfo:p.body?.data?.projects?.pageInfo??{endCursor:null,hasNextPage:!1},data:c.sort((g,m)=>(g.updatedDate||g.createdDate).getTime()-(m.updatedDate||m.createdDate).getTime())}}async setIssueState(n,e={}){let{issue:t,state:r}=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=Me(h);(h.issues?.nodes||[]).forEach(P=>g.push(Tt(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!) {
1273
1283
  updateIssue(input: { projectPath: $fullPath, iid: $issueId, stateEvent: $status }) {
1274
1284
  issue {
1275
1285
  id
1276
1286
  }
1277
1287
  }
1278
- }`;if(!(await q(this.config,{query:o,variables:{fullPath:`${t.repository.owner.login}/${t.repository.name}`,issueId:t.number,status:r==="OPEN"?"REOPEN":"CLOSE"}},e)).body.data?.updateIssue?.issue?.id)throw new Error("Could not set issue status")}async closeIssue(n,e={}){await this.setIssueState({...n,state:"CLOSED"},e)}async reOpenIssue(n,e={}){await this.setIssueState({...n,state:"OPEN"},e)}async setIssueLabels(n,e={}){let{issue:t,labels:r}=n;if(!t.repository)throw new Error('GitLab requires a "repository" for this function.');let o=r.map(u=>{if(!u.graphQLId)throw new Error('GitLab requires label "graphQLId" for this function.');return u.graphQLId}),i=`mutation SetIssueLabels($fullPath: ID!, $issueId: String!, $labelGraphQLIds: [ID!]) {
1288
+ }`;if(!(await v(this.config,{query:o,variables:{fullPath:`${t.repository.owner.login}/${t.repository.name}`,issueId:t.number,status:s==="OPEN"?"REOPEN":"CLOSE"}},e)).body.data?.updateIssue?.issue?.id)throw new Error("Could not set issue status")}async closeIssue(n,e={}){await this.setIssueState({...n,state:"CLOSED"},e)}async reOpenIssue(n,e={}){await this.setIssueState({...n,state:"OPEN"},e)}async setIssueLabels(n,e={}){let{issue:t,labels:s}=n;if(!t.repository)throw new Error('GitLab requires a "repository" for this function.');let o=s.map(u=>{if(!u.graphQLId)throw new Error('GitLab requires label "graphQLId" for this function.');return u.graphQLId}),i=`mutation SetIssueLabels($fullPath: ID!, $issueId: String!, $labelGraphQLIds: [ID!]) {
1279
1289
  updateIssue(input: { projectPath: $fullPath, iid: $issueId, labelIds: $labelGraphQLIds }) {
1280
1290
  issue {
1281
1291
  id
1282
1292
  }
1283
1293
  }
1284
- }`;if(!(await q(this.config,{query:i,variables:{fullPath:`${t.repository.owner.login}/${t.repository.name}`,issueId:t.number,labelGraphQLIds:o}},e)).body.data?.updateIssue?.issue?.id)throw new Error("Could not set issue labels")}async setIssueMilestone(n,e={}){let{issue:t,milestone:r}=n;if(!t.repository)throw new Error('GitLab requires "repository" for this function.');let o=`mutation SetIssueMilestone($fullPath: ID!, $issueId: String!, $milestoneId: ID) {
1294
+ }`;if(!(await v(this.config,{query:i,variables:{fullPath:`${t.repository.owner.login}/${t.repository.name}`,issueId:t.number,labelGraphQLIds:o}},e)).body.data?.updateIssue?.issue?.id)throw new Error("Could not set issue labels")}async setIssueMilestone(n,e={}){let{issue:t,milestone:s}=n;if(!t.repository)throw new Error('GitLab requires "repository" for this function.');let o=`mutation SetIssueMilestone($fullPath: ID!, $issueId: String!, $milestoneId: ID) {
1285
1295
  updateIssue(input: { projectPath: $fullPath, iid: $issueId, milestoneId: $milestoneId }) {
1286
1296
  errors
1287
1297
  issue {
@@ -1291,14 +1301,14 @@ query GetSingleIssue($projectId: ID!, $issueNumber: String!) {
1291
1301
  }
1292
1302
  }
1293
1303
  }
1294
- }`,i=await q(this.config,{query:o,variables:{fullPath:`${t.repository.owner.login}/${t.repository.name}`,issueId:t.number,milestoneId:r?.id??null}},e),a=i.body.data?.updateIssue;if(!a?.issue?.id||i.body.errors||a?.errors?.length!==0)throw new Error("Could not set milestone of issue")}async setIssueAssignees(n,e={}){let{issue:t,assignees:r}=n;if(!t.repository)throw new Error('GitLab requires "repository" for this function.');let o=r.map(l=>l.username),i=`mutation SetIssueAssignees($fullPath: ID!, $issueId: String!, $assigneeUsernames: [String!]!) {
1304
+ }`,i=await v(this.config,{query:o,variables:{fullPath:`${t.repository.owner.login}/${t.repository.name}`,issueId:t.number,milestoneId:s?.id??null}},e),a=i.body.data?.updateIssue;if(!a?.issue?.id||i.body.errors||a?.errors?.length!==0)throw new Error("Could not set milestone of issue")}async setIssueAssignees(n,e={}){let{issue:t,assignees:s}=n;if(!t.repository)throw new Error('GitLab requires "repository" for this function.');let o=s.map(l=>l.username),i=`mutation SetIssueAssignees($fullPath: ID!, $issueId: String!, $assigneeUsernames: [String!]!) {
1295
1305
  issueSetAssignees(input: { projectPath: $fullPath, iid: $issueId, assigneeUsernames: $assigneeUsernames }) {
1296
1306
  errors,
1297
1307
  issue {
1298
1308
  id
1299
1309
  }
1300
1310
  }
1301
- }`,u=(await q(this.config,{query:i,variables:{fullPath:`${t.repository.owner.login}/${t.repository.name}`,issueId:t.number,assigneeUsernames:o}},e)).body.data?.issueSetAssignees;if(!u?.issue?.id||u?.errors?.length!==0)throw new Error("Could not set issue assignees")}async getMilestonesForRepo(n,e={}){let{repo:{namespace:t,name:r},cursor:o}=n,i=await q(this.config,{query:`
1311
+ }`,u=(await v(this.config,{query:i,variables:{fullPath:`${t.repository.owner.login}/${t.repository.name}`,issueId:t.number,assigneeUsernames:o}},e)).body.data?.issueSetAssignees;if(!u?.issue?.id||u?.errors?.length!==0)throw new Error("Could not set issue assignees")}async getMilestonesForRepo(n,e={}){let{repo:{namespace:t,name:s},cursor:o}=n,i=await v(this.config,{query:`
1302
1312
  query getLabelsForRepo(
1303
1313
  $fullPath: ID!
1304
1314
  $after: String
@@ -1309,7 +1319,7 @@ query getLabelsForRepo(
1309
1319
  webUrl
1310
1320
  milestones(after: $after) {
1311
1321
  nodes {
1312
- ${At}
1322
+ ${Nt}
1313
1323
  }
1314
1324
  pageInfo {
1315
1325
  endCursor
@@ -1318,7 +1328,7 @@ query getLabelsForRepo(
1318
1328
  }
1319
1329
  }
1320
1330
  }
1321
- `,variables:{fullPath:`${t}/${r}`,after:o}},e);return{pageInfo:i.body.data?.project?.milestones?.pageInfo??{endCursor:null,hasNextPage:!1},data:i.body.data?.project?.milestones?.nodes?.map(a=>Ot(a,i.body.data?.project?.webUrl||""))??[]}}async getLabelsForRepo(n,e={}){let{repo:{namespace:t,name:r},cursor:o}=n,i=await q(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=>Qt(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:`
1322
1332
  query getLabelsForRepo(
1323
1333
  $fullPath: ID!
1324
1334
  $after: String
@@ -1328,7 +1338,7 @@ query getLabelsForRepo(
1328
1338
  ) {
1329
1339
  labels(after: $after) {
1330
1340
  nodes {
1331
- ${Gt}
1341
+ ${Ft}
1332
1342
  }
1333
1343
  pageInfo {
1334
1344
  endCursor
@@ -1337,36 +1347,28 @@ query getLabelsForRepo(
1337
1347
  }
1338
1348
  }
1339
1349
  }
1340
- `,variables:{fullPath:`${t}/${r}`,after:o}},e);return{pageInfo:i.body.data?.project?.labels?.pageInfo??{endCursor:null,hasNextPage:!1},data:i.body.data?.project?.labels?.nodes?.map(Tt)??[]}}async getTreeForRepo(n,e={}){let t=T(n.repo),r=new URL(n.cursor??`${L(this.config,e)}/projects/${encodeURIComponent(t)}/repository/tree`);r.searchParams.set("per_page","10000"),r.searchParams.set("recursive","true"),r.searchParams.set("pagination","keyset"),r.searchParams.set("ref",n.branch);let o=await this.config.request({url:r.toString(),headers:f(e.token||this.config.token)}),i=o.headers.link;return{data:o.body.map(tn),pageInfo:{endCursor:i?i.substring(1,i.indexOf(">")):null,hasNextPage:!!i}}}async getPullRequestForRepo(n,e={}){let t=T(n.repo),o=(await q(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(jt)??[]}}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(Dn),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:`
1341
1351
  query getPullRequestForRepo($fullPath: ID!, $iid: String!) {
1342
1352
  project(fullPath: $fullPath) {
1343
- id
1344
- httpUrlToRepo
1345
- fullPath
1346
- sshUrlToRepo
1347
- webUrl
1353
+ ${Ee}
1348
1354
  archived
1349
1355
  mergeRequest(iid: $iid) {
1350
- ${vt(!1,!0,!0)}
1356
+ ${Ut(!1,!0,!0)}
1351
1357
  sourceProject {
1352
- id
1353
- httpUrlToRepo
1354
- fullPath
1355
- sshUrlToRepo
1356
- webUrl
1358
+ ${Ee}
1357
1359
  }
1358
1360
  }
1359
1361
  }
1360
1362
  }
1361
- `,variables:{fullPath:t,iid:n.number.toString()}},e)).body.data?.project,i=o?.mergeRequest;if(!o||!i)return{data:null};let a=ke(o),u=i.sourceProject?ke(i.sourceProject):null;return{data:Et(i,a,u,this.getIsSelfHosted(e),this.config.baseUrl??e.baseUrl)}}getMergeRequestUrl(n,e,t){let r=T(n);return`${L(this.config,t)}/projects/${encodeURIComponent(r)}/merge_requests/${e}`}async getPullRequestDescription(n,e={}){try{return{data:{description:(await this.config.request({url:this.getMergeRequestUrl(n.repo,n.number,e),headers:f(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:{...f(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=T(n.repo),r=new URL(`${L(this.config,e)}/projects/${encodeURIComponent(t)}/repository/files/${encodeURIComponent(n.path)}/raw`);r.searchParams.set("ref",n.ref);let o=await this.config.request({url:r.toString(),headers:f(e.token||this.config.token)});return{data:new Blob([o.body])}}async getCommentsForPullRequest(n,e={}){let t=T(n.repo),{page:r,perPage:o}=an(n.cursor,$),i=new URL(`${L(this.config,e)}/projects/${encodeURIComponent(t)}/merge_requests/${n.pullRequestNumber}/notes`);i.searchParams.set("page",r.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:f(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},c=a.body.filter(m=>!m.system&&!m.position).map(m=>$t(m,u,l,p)),d=!!a.headers["x-next-page"],g=d?on({page:r+1,perPage:o}):null;return{data:c,pageInfo:{endCursor:g,hasNextPage:d}}}async getReviewsForPullRequest(n,e={}){let t=T(n.repo),r=this.getIsSelfHosted(e),o=this.config.baseUrl??e.baseUrl,i=f(e.token||this.config.token),a=L(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)]),c=(l.body.approved_by??[]).map(m=>m?.user).filter(m=>!!m).map(m=>{let I=yr(m,r,o),y=`approval-${m.id}`;return{author:I,body:"",createdAt:l.body.updated_at?new Date(l.body.updated_at):null,id:y,graphQLId:y,reviewComments:[],url:l.body.web_url??""}}),d={namespace:n.repo.namespace,name:n.repo.name,mergeRequestIid:n.pullRequestId},g=p.filter(m=>m.notes.some(I=>!I.system&&!!I.position)).map(m=>{let I=m.notes.filter(P=>!P.system),h=I.filter(P=>!!P.position)[0];if(!h)return null;let v=I.filter(P=>P.id!==h.id).map(P=>$t(P,r,o,d)),x={...$t(h,r,o,d),diffLines:[],filename:h.position?.new_path??h.position?.old_path??"",line:h.position?.new_line??h.position?.old_line??null,startLine:h.position?.line_range?.start?.new_line??null,side:ln(h.position),isOutdated:!1,isResolved:!!m.resolved,threadId:m.id,replies:v};return{author:h.author?yr(h.author,r,o):null,body:h.body??"",createdAt:h.created_at?new Date(h.created_at):null,id:m.id,graphQLId:m.id,reviewComments:[x],url:""}}).filter(m=>m!==null);return{data:[...c,...g]}}async getPullRequestDiff(n,e={}){let t=T(n.repo),r=encodeURIComponent(t),o=L(this.config,e);return(await this.fetchAllPagedGitLabREST(`${o}/projects/${r}/merge_requests/${n.pullRequestId}/diffs`,e)).map(pn).join("")}async getMergeBase(n,e={}){let t=T(n.repo),r=new URL(`${L(this.config,e)}/projects/${encodeURIComponent(t)}/repository/merge_base`);r.searchParams.append("refs[]",n.base),r.searchParams.append("refs[]",n.head);let i=(await this.config.request({url:r.toString(),headers:f(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 r=L(this.config,t),o=encodeURIComponent(n);return this.fetchAllPagedGitLabREST(`${r}/projects/${o}/merge_requests/${e}/discussions`,t)}async fetchAllPagedGitLabREST(n,e){let t=f(e.token||this.config.token),r=[],o=1,i=50;for(;o<=i;){let a=new URL(n);a.searchParams.set("page",o.toString()),a.searchParams.set("per_page",$.toString());let u=await this.config.request({url:a.toString(),headers:t});r.push(...u.body);let l=u.headers["x-next-page"];if(!l)break;let p=parseInt(`${l}`,10);if(Number.isNaN(p))break;o=p}return r}async addCommentToPullRequest(n,e={}){let{pullRequest:t,comment:r}=n;if(!r||r.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=`${L(this.config,e)}/projects/${encodeURIComponent(o)}/merge_requests/${t.number}/notes`;if(!(await this.config.request({method:"POST",url:i,headers:{...f(e.token||this.config.token),"Content-Type":"application/json"},body:JSON.stringify({body:r})})).body?.id)throw new Error("Could not add comment to pull request")}async addInlineCommentToPullRequest(n,e={}){let{pullRequest:t,comment:r,path:o,line:i,side:a="RIGHT",threadId:u}=n;if(!r?.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),c=L(this.config,e),d={...f(e.token||this.config.token),"Content-Type":"application/json"};if(u){let v=await this.config.request({method:"POST",url:`${c}/projects/${p}/merge_requests/${t.number}/discussions/${encodeURIComponent(u)}/notes`,headers:d,body:JSON.stringify({body:r})});return v.body?.id!=null?Dt(t.repository.owner.login,t.repository.name,t.number,v.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:`${c}/projects/${p}/merge_requests/${t.number}`,headers:f(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 I={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"?I.new_line=i:I.old_line=i;let h=(await this.config.request({method:"POST",url:`${c}/projects/${p}/merge_requests/${t.number}/discussions`,headers:d,body:JSON.stringify({body:r,position:I})})).body?.notes?.[0]?.id;return h!=null?Dt(t.repository.owner.login,t.repository.name,t.number,h):void 0}getNoteUrl(n,e){if(!n)throw new Error('GitLab requires "commentId" for this function.');let{namespace:t,name:r,mergeRequestIid:o,noteId:i}=dn(n);return`${L(this.config,e)}/projects/${encodeURIComponent(`${t}/${r}`)}/merge_requests/${o}/notes/${i}`}async deleteNote(n,e){await this.config.request({method:"DELETE",url:this.getNoteUrl(n,e),headers:f(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:{...f(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 r=T(n.repo),o=new URL(`${L(this.config,t)}/projects/${encodeURIComponent(r)}/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:f(t.token||this.config.token)})}async approvePullRequest(n,e={}){let{pullRequest:t,comment:r}=n,o=`${t.repository.owner.login}/${t.repository.name}`,i=L(this.config,e),a=encodeURIComponent(o),u=f(e.token||this.config.token);await this.config.request({url:`${i}/projects/${a}/merge_requests/${t.number}/approve`,method:"POST",headers:u}),r&&r.trim()!==""&&await this.postMergeRequestNote(o,t.number,r,e)}async commentOnPullRequest(n,e={}){let{pullRequest:t,comment:r}=n;if(!r||r.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,r,e)}async requestPullRequestChanges(n,e={}){let{pullRequest:t,comment:r}=n;if(!r||r.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=`${L(this.config,e)}/projects/${encodeURIComponent(o)}/merge_requests/${t.number}`,l=f(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,r,e)}async tryRequestChangesMutation(n,e,t){let r=`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=ve(o),u=i.sourceProject?ve(i.sourceProject):null;return{data:Gt(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}=On(n.cursor,L),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=>Ot(m,u,l,p)),c=!!a.headers["x-next-page"],g=c?Tn({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=Nr(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=>Ot(w,s,o,c)),D={...Ot(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?Nr(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:[...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)).map(kn).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){let t=R(e.token||this.config.token),s=[],o=1,i=50;for(;o<=i;){let a=new URL(n);a.searchParams.set("page",o.toString()),a.searchParams.set("per_page",L.toString());let u=await this.config.request({url:a.toString(),headers:t});s.push(...u.body);let l=u.headers["x-next-page"];if(!l)break;let p=parseInt(`${l}`,10);if(Number.isNaN(p))break;o=p}return s}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?_t(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?_t(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}=Nn(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!) {
1362
1364
  mergeRequestRequestChanges(input: { projectPath: $fullPath, iid: $pullRequestId }) {
1363
1365
  errors
1364
1366
  mergeRequest {
1365
1367
  id
1366
1368
  }
1367
1369
  }
1368
- }`,o=await q(this.config,{query:r,variables:{fullPath:n,pullRequestId:e.toString()}},t),i=o.body.errors;if(i?.length){if(i.some(Ys))return!1;throw new Error(`Could not request pull request changes: ${ye(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,r){let o=L(this.config,r),i=encodeURIComponent(n),a=f(r.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 cn="https://api.atlassian.com/ex/jira",Fe=100,xt=["assignee","comment","summary","created","creator","updated","votes","issuetype","status","labels","components","project","fixVersions","description"],qr="/rest/api/2/search/jql",vr="/rest/api/2/search",_t=(s,n,e,t)=>{let r=s.fields.assignee,o=!t,i=(s.fields[n?.Sprint??""]??[]).filter(a=>typeof a=="object");return{id:s.id,commentCount:s.fields.comment.comments.length,number:s.key,title:s.fields.summary,url:e?`${e}/browse/${s.key}`:null,closedDate:null,createdDate:new Date(s.fields.created),author:je(s.fields.creator,e,o),updatedDate:new Date(s.fields.updated),assignees:r?[je(r,e,o)]:[],description:s.fields.description,repository:null,project:{name:s.fields.project.name,resourceId:t??null,key:s.fields.project.key,namespace:null,id:s.fields.project.id},state:fn(s.fields.status),statusTransitions:s.transitions?.map(mn)??[],components:s.fields.components?.map(gn)??[],type:s.fields.issuetype.name,upvoteCount:s.fields.votes?.votes||0,labels:s.fields.labels?.map(a=>({color:null,description:null,id:null,name:a}))??[],sprints:i.map(Rn),fixVersions:s.fields.fixVersions.map(In)}},mn=s=>{let n;switch(s.to.statusCategory.name){case"To Do":n="TO_DO";break;case"In Progress":n="IN_PROGRESS";break;default:n="DONE";break}return{name:s.name,id:s.id,to:{id:s.to.id,name:s.to.name,color:s.to.statusCategory.colorName,category:n}}},gn=s=>({description:s.description??null,id:s.id,name:s.name}),hn=(s,n,e)=>e&&s.name?`${n}/secure/ViewProfile.jspa?name=${encodeURIComponent(s.name)}`:`${n}/jira/people/${s.accountId}`,je=(s,n,e)=>({id:(e?s.key:s.accountId)??"",name:s.displayName,email:s.emailAddress,avatarUrl:s.avatarUrls["48x48"],username:s.displayName,url:hn(s,n,e)}),fn=s=>{let n;switch(s.statusCategory.name){case"To Do":n="TO_DO";break;case"In Progress":n="IN_PROGRESS";break;default:n="DONE";break}return{id:s.id,name:s.name,color:s.statusCategory.colorName,category:n}},Rn=s=>({id:s.id.toString(),name:s.name,isActive:s.state==="active",startDate:s.startDate?new Date(s.startDate):null,endDate:s.endDate?new Date(s.endDate):null,completedDate:s.completeDate?new Date(s.completeDate):null}),In=s=>({id:s.id,description:s.description,name:s.name,archived:s.archived,released:s.released,releaseDate:s.releaseDate?new Date(s.releaseDate):null}),Z=(s,n,e)=>e?`${n.baseUrl||cn}/${e}`:`${n?.baseUrl||s.baseUrl}`,Qe=async(s,n,e={})=>{let{resourceId:t}=n;return(await s.request({url:`${Z(s,e,t)}/rest/api/2/field`,headers:f(e.token||s.token)})).body},Be=async(s,n,e,t={})=>{let{number:r,resourceId:o,fields:i}=n||{},a=await s.request({url:`${Z(s,t,o)}/rest/api/2/issue/${r}?fields=${xt.join(",")}&expand=transitions`,headers:f(t.token||s.token)});return{data:_t(a.body,i,e,o)}},Me=async(s,n,e,t={})=>{let{cursor:r,resourceId:o,labelNames:i,fields:a}=n||{},u=["statusCategory != Done",`(creator = currentUser() OR assignee = currentUser()
1369
- OR comment ~ currentUser() OR summary ~ currentUser() OR description ~ currentUser())`];i&&i.forEach(h=>u.push(`labels = "${h}"`));let l=`${u.join(" AND ")} ORDER BY updated DESC`,p=!o,c=p?vr:qr,d=new URL(`${Z(s,t,o)}${c}`);d.searchParams.set("jql",l),d.searchParams.set("maxResults",Fe.toString()),d.searchParams.set("fields",xt.join(",")),d.searchParams.set("expand","transitions"),r&&(p?d.searchParams.set("startAt",r):d.searchParams.set("nextPageToken",r));let g=await s.request({url:d.toString(),headers:f(t.token||s.token)}),m=g.body.issues.map(h=>_t(h,a,e,o)),I=!1,y="";return p?(I=m.length==Fe,y=(parseInt(r??"0",10)+m.length).toString()):(I=!!g.body.nextPageToken,y=g.body.nextPageToken??null),{data:m,pageInfo:{hasNextPage:I,endCursor:y}}},Sr=async(s,n,e,t={})=>{let{cursor:r,resourceId:o,jql:i,fields:a}=n||{},u=[...xt],l=a?.Sprint;l&&u.push(l);let p=!o,c=p?vr:qr,d=new URL(`${Z(s,t,o)}${c}`);d.searchParams.set("jql",i.join(" AND ")),d.searchParams.set("maxResults",Fe.toString()),d.searchParams.set("fields",u.join(",")),d.searchParams.set("expand","transitions"),r&&(p?d.searchParams.set("startAt",r):d.searchParams.set("nextPageToken",r));let g=await s.request({url:d.toString(),headers:f(t.token||s.token)}),m=g.body.issues.map(h=>_t(h,a,e,o)),I=!1,y="";return p?(I=m.length==Fe,y=(parseInt(r??"0",10)+m.length).toString()):(I=!!g.body.nextPageToken,y=g.body.nextPageToken??null),{data:m,pageInfo:{hasNextPage:I,endCursor:y}}},ze=async(s,n,e,t={})=>{let{assigneeLogins:r,authorLogin:o,mentionLogin:i,labelNames:a,cursor:u,projectKey:l,resourceId:p,fields:c}=n||{},d=[`project = "${l}"`,"statusCategory != Done"];return o&&d.push(`creator in ("${o}")`),r&&r.length!==0&&d.push(`assignee in ("${r.join('", "')}")`),i&&d.push(`comment ~ "${i}"`),a&&a.forEach(g=>d.push(`labels = "${g}"`)),Sr(s,{resourceId:p,jql:d,cursor:u,fields:c},e,t)},He=async(s,n,e,t={})=>{let{assigneeLogins:r,authorLogin:o,mentionLogin:i,labelNames:a,cursor:u,projectKeys:l,resourceId:p,fields:c}=n||{},g=["("+l.map(m=>`project = "${m}"`).join(" OR ")+")","statusCategory != Done"];return o&&g.push(`creator in ("${o}")`),r&&r.length!==0&&g.push(`assignee in ("${r.join('", "')}")`),i&&g.push(`comment ~ "${i}"`),a&&a.forEach(m=>g.push(`labels = "${m}"`)),Sr(s,{resourceId:p,jql:g,fields:c,cursor:u},e,t)},We=async(s,n,e={})=>{let{issue:t,labels:r}=n;if(!t.project)throw new Error('Jira requires a "project" for this function.');let o={fields:{labels:r.map(i=>i.name)}};await s.request({method:"PUT",url:`${Z(s,e,t.project.resourceId??void 0)}/rest/api/2/issue/${t.id}`,body:JSON.stringify(o),headers:{...f(e.token||s.token),"Content-Type":"application/json"}})},Je=async(s,n,e={})=>{let{issue:t,components:r}=n;if(!t.project)throw new Error('Jira requires a "project" for this function.');let o={fields:{components:r.map(i=>({id:i.id}))}};await s.request({method:"PUT",url:`${Z(s,e,t.project.resourceId??void 0)}/rest/api/2/issue/${t.id}`,body:JSON.stringify(o),headers:{...f(e.token||s.token),"Content-Type":"application/json"}})},Ve=async(s,n,e={})=>{let{issue:t,status:r}=n;if(!t.project)throw new Error('Jira requires a "project" for this function.');if(!r.id)throw new Error('Jira requires a status "id" for this function.');let o={transition:{id:r.id}};await s.request({method:"POST",url:`${Z(s,e,t.project.resourceId??void 0)}/rest/api/2/issue/${t.id}/transitions`,body:JSON.stringify(o),headers:{...f(e.token||s.token),"Content-Type":"application/json"}})},Ke=async(s,n,e={})=>{let{resourceId:t,projectIdOrKey:r}=n,o=new URL(`${Z(s,e,t)}/rest/api/2/project/${r}/components`);return{data:(await s.request({url:o.toString(),headers:f(e.token||s.token)})).body}};var Pe="https://api.atlassian.com/ex/jira",kt=100,me=class extends N{constructor(){super(...arguments);this._resourceUrlCache={};this._issueFieldsCache={}}async getIssueFieldsForResource(e,t={}){if(!this._issueFieldsCache[e.resourceId]){let r=await Qe(this.config,e,t);this._issueFieldsCache[e.resourceId]=r.reduce((o,i)=>({...o,[i.name]:i.id}),{})}return this._issueFieldsCache[e.resourceId]??null}async getResourceUrl(e,t={}){let r=t.token||this.config.token;if(!r)return null;let o=this._resourceUrlCache[r];return o?o[e.resourceId]??null:(await this.getJiraResourcesForCurrentUser(t),this._resourceUrlCache[r]?.[e.resourceId]??null)}async getCurrentUserForResource(e,t={}){let r=await this.getResourceUrl({resourceId:e.resourceId},t),o=await this.config.request({url:`${t.baseUrl||Pe}/${e.resourceId}/rest/api/2/myself`,headers:f(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:r?`${r}/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:f(e.token||this.config.token)}),r=e.token||this.config.token,o=r?this._resourceUrlCache[r]||{}: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 r&&(this._resourceUrlCache[r]=o),{data:i}}async getJiraProjectsForResource(e,t={}){let r=new URL(`${t.baseUrl||Pe}/${e.resourceId}/rest/api/2/project/search`);r.searchParams.set("maxResults",kt.toString()),e.cursor&&r.searchParams.set("startAt",e.cursor);let o=await this.config.request({url:r.toString(),headers:f(t.token||this.config.token)});return{pageInfo:{hasNextPage:o.body.values.length!==0,endCursor:(o.body.startAt+o.body.values.length).toString()},data:o.body.values.map(i=>({id:i.id,key:i.key,name:i.name,resourceId:e.resourceId}))}}async getJiraProjectsForResources(e,t={}){let r=[];return await Promise.all(e.resourceIds.map(async o=>{try{return await Jt(i=>this.getJiraProjectsForResource({resourceId:o,cursor:i},t))}catch{return[]}})).then((...o)=>{o.forEach(i=>{r=r.concat(...i)})}),{data:r}}async getAccountsForJiraProject(e,t={}){let{resourceId:r,projectKey:o,cursor:i}=e,a=await this.getResourceUrl({resourceId:r},t),u=new URL(`${t.baseUrl||Pe}/${r}/rest/api/2/user/assignable/search`);u.searchParams.set("maxResults",kt.toString()),i&&u.searchParams.set("startAt",i),u.searchParams.set("project",o);let l=await this.config.request({url:u.toString(),headers:f(t.token||this.config.token)});return{pageInfo:{hasNextPage:l.body.length!==0,endCursor:((i?parseInt(i):0)+l.body.length).toString()},data:l.body.filter(p=>p.accountType!=="app"&&p.active).map(p=>je(p,a,!1))}}async getComponentsForJiraProject(e,t={}){return await Ke(this.config,e,t)}async getIssue(e,t={}){let r=await this.getIssueFieldsForResource({resourceId:e.resourceId},t),o=await this.getResourceUrl({resourceId:e.resourceId},t);return await Be(this.config,{...e,fields:r},o,t)}async getIssuesForProject(e,t={}){let r=await this.getIssueFieldsForResource({resourceId:e.resourceId},t),o=await this.getResourceUrl({resourceId:e.resourceId},t);return await ze(this.config,{...e,fields:r},o,t)}async getIssuesForProjects(e,t={}){let r=await this.getIssueFieldsForResource({resourceId:e.resourceId},t),o=await this.getResourceUrl({resourceId:e.resourceId},t);return await He(this.config,{...e,fields:r},o,t)}async getIssuesForResourceForCurrentUser(e,t={}){let r=await this.getIssueFieldsForResource({resourceId:e.resourceId},t),o=await this.getResourceUrl({resourceId:e.resourceId},t);return await Me(this.config,{...e,fields:r},o,t)}async setIssueStatus(e,t={}){await Ve(this.config,e,t)}async setIssueAssignee(e,t={}){let{issue:r,assignee:o}=e;if(!r.project)throw new Error('Jira Cloud requires a "project" for this function.');if(!r.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||Pe}/${r.project.resourceId}/rest/api/2/issue/${r.id}/assignee`,body:JSON.stringify(i),headers:{...f(t.token||this.config.token),"Content-Type":"application/json"}})}async setIssueComponents(e,t={}){await Je(this.config,e,t)}async setIssueLabels(e,t={}){await We(this.config,e,t)}async getLabelsForResource(e,t={}){let{resourceId:r,cursor:o}=e,i=new URL(`${t.baseUrl||Pe}/${r}/rest/api/2/label`);i.searchParams.set("maxResults",kt.toString()),o&&i.searchParams.set("startAt",o);let a=await this.config.request({url:i.toString(),headers:f(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 ge=class extends _{constructor(){super(...arguments);this._issueFieldsCache={}}async getIssueFieldsForResource(e={}){let t=e?.baseUrl||this.config.baseUrl||"";if(!this._issueFieldsCache[t]){let r=await Qe(this.config,{},e);this._issueFieldsCache[t]=r.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:f(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:f(e?.token||this.config.token)})).body.map(r=>({id:r.id,name:r.name}))}}async getIssue(e,t={}){let r=e.resourceUrl||t.baseUrl||this.config.baseUrl;if(!r)throw new Error('Jira Server requires a "resourceUrl" or "baseUrl" for this function.');let o=await this.getIssueFieldsForResource(t);return await Be(this.config,{...e,fields:o},r,t)}async getIssuesForProject(e,t={}){let r=e.resourceUrl||t.baseUrl||this.config.baseUrl;if(!r)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},r,t)}async getIssuesForProjects(e,t={}){let r=e.resourceUrl||t.baseUrl||this.config.baseUrl;if(!r)throw new Error('Jira Server requires a "resourceUrl" or "baseUrl" for this function.');let o=await this.getIssueFieldsForResource(t);return await He(this.config,{...e,fields:o},r,t)}async getIssuesForResourceForCurrentUser(e,t={}){let r=e.resourceUrl||t.baseUrl||this.config.baseUrl;if(!r)throw new Error('Jira Server requires a "resourceUrl" or "baseUrl" for this function.');let o=await this.getIssueFieldsForResource(t);return await Me(this.config,{...e,fields:o},r,t)}async setIssueStatus(e,t={}){await Ve(this.config,e,t)}async setIssueLabels(e,t={}){await We(this.config,e,t)}async setIssueComponents(e,t={}){await Je(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:f(e.token||this.config.token)})).body.results.map(({displayName:r})=>({color:null,description:null,id:null,name:r}))}}async getComponentsForJiraProject(e,t={}){return await Ke(this.config,e,t)}};var M="https://api.trello.com",bn=1e3,z=(s,n)=>({...f(n),Authorization:`OAuth oauth_consumer_key="${s}", oauth_token="${n}"`}),yn=s=>({id:s.id,username:s.username,url:s.url,name:s.fullName,email:s.email,avatarUrl:s.avatarUrl}),Pn=(s,n)=>{let e=new Date(1e3*parseInt(s.id.substring(0,8),16));return{id:s.id,commentCount:s.badges.comments,number:s.idShort.toString(),title:s.name,url:s.url,closedDate:null,createdDate:new Date(e.toISOString()),author:null,updatedDate:new Date(s.dateLastActivity),assignees:s.members.map(t=>({id:t.id,username:t.username,name:t.fullName,email:null,avatarUrl:t.avatarUrl,url:null})),description:null,state:n[s.idList??""]?{id:s.idList,name:n[s.idList].name,color:null}:null,type:null,repository:null,upvoteCount:s.badges.votes,labels:s.labels.map(t=>({color:t.color,description:null,id:t.id,name:t.name}))}},he=class extends N{async getCurrentUser(n,e={}){let t=await this.config.request({url:`${e.baseUrl||M}/1/members/me`,headers:z(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||M}/1/members/me/boards?fields=name&filter=open`,headers:z(n.appKey,e.token||this.config.token)})).body.map(r=>({id:r.id,name:r.name}))}}async getListsForTrelloBoard(n,e={}){let{appKey:t,boardId:r}=n;return{data:(await this.config.request({url:`${e.baseUrl||M}/1/boards/${r}/lists`,headers:z(t,e.token||this.config.token)})).body}}async getAccountForId(n,e={}){let{appKey:t,memberId:r}=n,o=await this.config.request({url:`${e.baseUrl||M}/1/members/${r}`,headers:z(t,e.token||this.config.token)});return{data:yn(o.body)}}async getAccountsForTrelloBoard(n,e={}){let{appKey:t,boardId:r}=n;return{data:(await this.config.request({url:`${e.baseUrl||M}/1/boards/${r}/members`,headers:z(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:r,boardId:o,filterText:i,assigneeLogins:a,labelNamesOrColors:u,trelloBoardListsById:l}=n||{};a&&t.push("@me"),u&&u.forEach(d=>t.push(`label:"${d}"`));let p=`${i?`${i}`:""}${t.join(" ")} board:${o}`;return{data:(await this.config.request({url:`${e.baseUrl||M}/1/search?query=${p}&cards_limit=${bn}&card_members=true`,headers:z(r,e.token||this.config.token)})).body.cards.map(d=>Pn(d,l||{}))}}async updateIssue(n,e,t,r){return await this.config.request({method:"PUT",url:`${r.baseUrl||M}/1/cards/${e.id}?${t}`,headers:z(n,r.token||this.config.token)})}async setIssueStatus(n,e={}){let{appKey:t,issue:r,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,r,i,e)).body.id)throw new Error("Could not set issue status")}async setIssueAssignees(n,e={}){let{appKey:t,issue:r,assignees:o}=n,i=o.map(l=>l.id),a=`idMembers=${encodeURIComponent(i.join(","))}`;if(!(await this.updateIssue(t,r,a,e)).body.id)throw new Error("Could not set issue status")}async setIssueLabels(n,e={}){let{appKey:t,issue:r,labels:o}=n,i=o.map(u=>u.id).join(",");if(!(await this.config.request({method:"PUT",url:`${e.baseUrl||M}/1/cards/${r.id}?idLabels=${encodeURIComponent(i)}`,headers:z(t,e.token||this.config.token)})).body.id)throw new Error("Could not set issue status")}async setIssueArchived(n,e={}){let{appKey:t,issue:r,archived:o}=n;if(!(await this.config.request({method:"PUT",url:`${e.baseUrl||M}/1/cards/${r.id}?closed=${o}`,headers:z(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:r}=n;return{data:(await this.config.request({url:`${e.baseUrl||M}/1/boards/${r}/labels`,headers:z(t,e.token||this.config.token)})).body.map(i=>({color:i.color,description:null,id:i.id,name:i.name}))}}};var Ft=100,Xe=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}},V=async(s,n,e,t)=>{let r=n.token||s.token;if(!r)throw new Error("Linear API key is required");let o=await s.request({url:"https://api.linear.app/graphql",method:"POST",headers:{Authorization:r,"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},Nt=s=>s?s instanceof Date?s:new Date(s):null,wn=`
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(Cn))return!1;throw new Error(`Could not request pull request changes: ${Se(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 Fn="https://api.atlassian.com/ex/jira",He=100,Qr=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"},Bt=["assignee","comment","summary","created","creator","updated","votes","issuetype","status","labels","components","project","fixVersions","description"],Br="/rest/api/2/search/jql",Mr="/rest/api/2/search",Mt=(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:We(r.fields.creator,e,o),updatedDate:new Date(r.fields.updated),assignees:s?[We(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:Mn(r.fields.status),statusTransitions:r.transitions?.map(jn)??[],components:r.fields.components?.map(Qn)??[],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(zn),fixVersions:r.fields.fixVersions.map(Hn)}},jn=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}}},Qn=r=>({description:r.description??null,id:r.id,name:r.name}),Bn=(r,n,e)=>e&&r.name?`${n}/secure/ViewProfile.jspa?name=${encodeURIComponent(r.name)}`:`${n}/jira/people/${r.accountId}`,We=(r,n,e)=>({id:(e?r.key:r.accountId)??"",name:r.displayName,email:r.emailAddress,avatarUrl:r.avatarUrls["48x48"],username:r.displayName,url:Bn(r,n,e)}),Mn=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}},zn=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}),Hn=r=>({id:r.id,description:r.description,name:r.name,archived:r.archived,released:r.released,releaseDate:r.releaseDate?new Date(r.releaseDate):null}),re=(r,n,e)=>e?`${n.baseUrl||Fn}/${e}`:`${n?.baseUrl||r.baseUrl}`,Je=async(r,n,e={})=>{let{resourceId:t}=n;return(await r.request({url:`${re(r,e,t)}/rest/api/2/field`,headers:R(e.token||r.token)})).body},Ve=async(r,n,e,t={})=>{let{number:s,resourceId:o,fields:i}=n||{},a=await r.request({url:`${re(r,t,o)}/rest/api/2/issue/${s}?fields=${Bt.join(",")}&expand=transitions`,headers:R(t.token||r.token)});return{data:Mt(a.body,i,e,o)}},Ke=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?Mr:Br,c=new URL(`${re(r,t,o)}${d}`);c.searchParams.set("jql",l),c.searchParams.set("maxResults",He.toString()),c.searchParams.set("fields",Bt.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=>Mt(f,a,e,o)),h=!1,y="";return p?(h=m.length==He,y=(parseInt(s??"0",10)+m.length).toString()):(h=!!g.body.nextPageToken,y=g.body.nextPageToken??null),{data:m,pageInfo:{hasNextPage:h,endCursor:y}}},zr=async(r,n,e,t={})=>{let{cursor:s,resourceId:o,jql:i,fields:a}=n||{},u=U(n?.pageSize,{fallback:He,max:He}),l=[...Bt],p=a?.Sprint;p&&l.push(p);let d=!o,c=d?Mr:Br,g=new URL(`${re(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=>Mt(P,a,e,o)),y=!1,f="";if(d){let P=parseInt(s??"0",10),S=typeof m.body.startAt=="number"?m.body.startAt:Number.isNaN(P)?0:P,D=m.body.total;y=typeof D=="number"?S+h.length<D:h.length===u,f=(S+h.length).toString()}else y=!!m.body.nextPageToken,f=m.body.nextPageToken??null;return{data:h,pageInfo:{hasNextPage:y,endCursor:f}}},Xe=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=Qr(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}"`)),zr(r,{resourceId:p,jql:c,cursor:u,fields:d,pageSize:n.pageSize},e,t)},Ze=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=Qr(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}"`)),zr(r,{resourceId:p,jql:g,fields:d,cursor:u,pageSize:n.pageSize},e,t)},Ye=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:`${re(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"}})},et=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:`${re(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"}})},tt=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:`${re(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"}})},rt=async(r,n,e={})=>{let{resourceId:t,projectIdOrKey:s}=n,o=new URL(`${re(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 Ce="https://api.atlassian.com/ex/jira",zt=100,Re=class extends j{constructor(){super(...arguments);this._resourceUrlCache={};this._issueFieldsCache={}}async getIssueFieldsForResource(e,t={}){if(!this._issueFieldsCache[e.resourceId]){let s=await Je(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||Ce}/${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||Ce}/${e.resourceId}/rest/api/2/project/search`);s.searchParams.set("maxResults",zt.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()},data:o.body.values.map(i=>({id:i.id,key:i.key,name:i.name,resourceId:e.resourceId}))}}async getJiraProjectsForResources(e,t={}){let s=[];return await Promise.all(e.resourceIds.map(async o=>{try{return await er(i=>this.getJiraProjectsForResource({resourceId:o,cursor:i},t))}catch{return[]}})).then((...o)=>{o.forEach(i=>{s=s.concat(...i)})}),{data:s}}async getAccountsForJiraProject(e,t={}){let{resourceId:s,projectKey:o,cursor:i}=e,a=await this.getResourceUrl({resourceId:s},t),u=new URL(`${t.baseUrl||Ce}/${s}/rest/api/2/user/assignable/search`);u.searchParams.set("maxResults",zt.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()},data:l.body.filter(p=>p.accountType!=="app"&&p.active).map(p=>We(p,a,!1))}}async getComponentsForJiraProject(e,t={}){return await rt(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 Ve(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 Xe(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 Ze(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 Ke(this.config,{...e,fields:s},o,t)}async setIssueStatus(e,t={}){await tt(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||Ce}/${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 et(this.config,e,t)}async setIssueLabels(e,t={}){await Ye(this.config,e,t)}async getLabelsForResource(e,t={}){let{resourceId:s,cursor:o}=e,i=new URL(`${t.baseUrl||Ce}/${s}/rest/api/2/label`);i.searchParams.set("maxResults",zt.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 Ie=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 Je(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 Ve(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 Xe(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 Ze(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 Ke(this.config,{...e,fields:o},s,t)}async setIssueStatus(e,t={}){await tt(this.config,e,t)}async setIssueLabels(e,t={}){await Ye(this.config,e,t)}async setIssueComponents(e,t={}){await et(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 rt(this.config,e,t)}};var H="https://api.trello.com",Wn=1e3,W=(r,n)=>({...R(n),Authorization:`OAuth oauth_consumer_key="${r}", oauth_token="${n}"`}),Jn=r=>({id:r.id,username:r.username,url:r.url,name:r.fullName,email:r.email,avatarUrl:r.avatarUrl}),Vn=(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}))}},be=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:Jn(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(c=>t.push(`label:"${c}"`));let p=`${i?`${i}`:""}${t.join(" ")} board:${o}`;return{data:(await this.config.request({url:`${e.baseUrl||H}/1/search?query=${p}&cards_limit=${Wn}&card_members=true`,headers:W(s,e.token||this.config.token)})).body.cards.map(c=>Vn(c,l||{}))}}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 Wt=100,st=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}},X=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},Ht=r=>r?r instanceof Date?r:new Date(r):null,Kn=`
1370
1372
  id
1371
1373
  name
1372
1374
  description
@@ -1374,11 +1376,11 @@ OR comment ~ currentUser() OR summary ~ currentUser() OR description ~ currentUs
1374
1376
  startDate
1375
1377
  targetDate
1376
1378
  url
1377
- `,Er=s=>({id:s.id,name:s.name,description:s.description??null,state:s.state,startDate:Nt(s.startDate),targetDate:Nt(s.targetDate),url:s.url}),Cr=async(s,n,e)=>{let t=`
1379
+ `,Hr=r=>({id:r.id,name:r.name,description:r.description??null,state:r.state,startDate:Ht(r.startDate),targetDate:Ht(r.targetDate),url:r.url}),Wr=async(r,n,e)=>{let t=`
1378
1380
  query GetProjects($first: Int!, $after: String) {
1379
1381
  projects(first: $first, after: $after) {
1380
1382
  nodes {
1381
- ${wn}
1383
+ ${Kn}
1382
1384
  }
1383
1385
  pageInfo {
1384
1386
  hasNextPage
@@ -1386,7 +1388,7 @@ OR comment ~ currentUser() OR summary ~ currentUser() OR description ~ currentUs
1386
1388
  }
1387
1389
  }
1388
1390
  }
1389
- `;return(await V(s,n,t,{first:Ft,after:e})).projects},qn=`
1391
+ `;return(await X(r,n,t,{first:Wt,after:e})).projects},Xn=`
1390
1392
  id
1391
1393
  name
1392
1394
  number
@@ -1394,11 +1396,11 @@ OR comment ~ currentUser() OR summary ~ currentUser() OR description ~ currentUs
1394
1396
  startsAt
1395
1397
  endsAt
1396
1398
  completedAt
1397
- `,$r=s=>({id:s.id,name:s.name??`Cycle ${s.number}`,number:s.number,description:s.description??null,startsAt:new Date(s.startsAt),endsAt:new Date(s.endsAt),completedAt:Nt(s.completedAt),url:""}),Dr=async(s,n,e)=>{let t=`
1399
+ `,Jr=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:Ht(r.completedAt),url:""}),Vr=async(r,n,e)=>{let t=`
1398
1400
  query GetCycles($first: Int!, $after: String) {
1399
1401
  cycles(first: $first, after: $after) {
1400
1402
  nodes {
1401
- ${qn}
1403
+ ${Xn}
1402
1404
  }
1403
1405
  pageInfo {
1404
1406
  hasNextPage
@@ -1406,16 +1408,16 @@ OR comment ~ currentUser() OR summary ~ currentUser() OR description ~ currentUs
1406
1408
  }
1407
1409
  }
1408
1410
  }
1409
- `;return(await V(s,n,t,{first:Ft,after:e})).cycles},vn=`
1411
+ `;return(await X(r,n,t,{first:Wt,after:e})).cycles},Zn=`
1410
1412
  id
1411
1413
  name
1412
1414
  color
1413
1415
  description
1414
- `,Lr=s=>({id:s.id,name:s.name,color:s.color,description:s.description??null}),Ur=async(s,n,e)=>{let t=`
1416
+ `,Kr=r=>({id:r.id,name:r.name,color:r.color,description:r.description??null}),Xr=async(r,n,e)=>{let t=`
1415
1417
  query GetLabels($first: Int!, $after: String) {
1416
1418
  projectLabels(first: $first, after: $after) {
1417
1419
  nodes {
1418
- ${vn}
1420
+ ${Zn}
1419
1421
  }
1420
1422
  pageInfo {
1421
1423
  hasNextPage
@@ -1423,36 +1425,36 @@ OR comment ~ currentUser() OR summary ~ currentUser() OR description ~ currentUs
1423
1425
  }
1424
1426
  }
1425
1427
  }
1426
- `;return(await V(s,n,t,{first:Ft,after:e})).projectLabels};var we=(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))(we||{});function Ar(s,n){return s?`${we[s]}:${n||""}`:n??null}function Gr(s){if(!s)return{category:0};let[n,e]=s.split(":");return n in we?{category:we[n],cursor:e||void 0}:{category:0,cursor:s}}var Tr=100;function Ye(s){return s?s instanceof Date?s:new Date(s):null}var _r=`
1428
+ `;return(await X(r,n,t,{first:Wt,after:e})).projectLabels};var $e=(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))($e||{});function Zr(r,n){return r?`${$e[r]}:${n||""}`:n??null}function Yr(r){if(!r)return{category:0};let[n,e]=r.split(":");return n in $e?{category:$e[n],cursor:e||void 0}:{category:0,cursor:r}}var es=100;function ot(r){return r?r instanceof Date?r:new Date(r):null}var ss=`
1427
1429
  id
1428
1430
  name
1429
1431
  key
1430
1432
  icon
1431
- `;function Sn(s){return{id:s.id,name:s.name,key:s.key,iconUrl:s.icon}}var Or=`
1433
+ `;function Yn(r){return{id:r.id,name:r.name,key:r.key,iconUrl:r.icon}}var ts=`
1432
1434
  id
1433
1435
  name
1434
1436
  avatarUrl
1435
- `;function xr(s){return s?{id:s.id,name:s.name,username:s.name,email:null,avatarUrl:s.avatarUrl??null,url:null}:null}var En=`
1437
+ `;function rs(r){return r?{id:r.id,name:r.name,username:r.name,email:null,avatarUrl:r.avatarUrl??null,url:null}:null}var eo=`
1436
1438
  id
1437
1439
  name
1438
- `;function Cn(s,n){if(s)return{id:s.id,name:s.name,key:n?.key||null,namespace:null,resourceId:n?.id||null}}var $n=`
1440
+ `;function to(r,n){if(r)return{id:r.id,name:r.name,key:n?.key||null,namespace:null,resourceId:n?.id||null}}var ro=`
1439
1441
  id
1440
1442
  sortOrder
1441
1443
  name
1442
1444
  description
1443
1445
  status
1444
1446
  targetDate
1445
- `;function Dn(s){return s?{id:s.id,number:s.sortOrder,title:s.name,description:s.description??null,isOpen:s.status!=="done",url:"",startDate:null,dueDate:Ye(s.targetDate)}:null}function Ln(s){switch(s){case"completed":case"canceled":return"DONE";case"started":return"IN_PROGRESS";default:return"TO_DO"}}var Un=`
1447
+ `;function so(r){return r?{id:r.id,number:r.sortOrder,title:r.name,description:r.description??null,isOpen:r.status!=="done",url:"",startDate:null,dueDate:ot(r.targetDate)}:null}function no(r){switch(r){case"completed":case"canceled":return"DONE";case"started":return"IN_PROGRESS";default:return"TO_DO"}}var oo=`
1446
1448
  id
1447
1449
  name
1448
1450
  color
1449
1451
  type
1450
- `;function An(s){return s?{id:s.id,name:s.name,color:s.color,category:Ln(s.type)}:null}var Qt=`
1452
+ `;function io(r){return r?{id:r.id,name:r.name,color:r.color,category:no(r.type)}:null}var Vt=`
1451
1453
  creator {
1452
- ${Or}
1454
+ ${ts}
1453
1455
  }
1454
1456
  assignee {
1455
- ${Or}
1457
+ ${ts}
1456
1458
  }
1457
1459
  archivedAt
1458
1460
  createdAt
@@ -1460,35 +1462,35 @@ OR comment ~ currentUser() OR summary ~ currentUser() OR description ~ currentUs
1460
1462
  id
1461
1463
  identifier
1462
1464
  project {
1463
- ${En}
1465
+ ${eo}
1464
1466
  }
1465
1467
  team {
1466
- ${_r}
1468
+ ${ss}
1467
1469
  }
1468
1470
  state {
1469
- ${Un}
1471
+ ${oo}
1470
1472
  }
1471
1473
  title
1472
1474
  updatedAt
1473
1475
  url
1474
1476
  projectMilestone {
1475
- ${$n}
1477
+ ${ro}
1476
1478
  }
1477
- `;async function jt(s){return{author:xr(await s.creator),assignees:[xr(await s.assignee)].filter(n=>n!=null),commentCount:null,closedDate:Ye(s.archivedAt),createdDate:Ye(s.createdAt),description:s.description??null,id:s.id,labels:[],number:s.identifier,repository:null,project:Cn(await s.project,await s.team),state:An(await s.state),title:s.title,type:null,updatedDate:Ye(s.updatedAt),upvoteCount:null,url:s.url,milestone:Dn(await s.projectMilestone)}}var Ze=`
1479
+ `;async function Jt(r){return{author:rs(await r.creator),assignees:[rs(await r.assignee)].filter(n=>n!=null),commentCount:null,closedDate:ot(r.archivedAt),createdDate:ot(r.createdAt),description:r.description??null,id:r.id,labels:[],number:r.identifier,repository:null,project:to(await r.project,await r.team),state:io(await r.state),title:r.title,type:null,updatedDate:ot(r.updatedAt),upvoteCount:null,url:r.url,milestone:so(await r.projectMilestone)}}var nt=`
1478
1480
  nodes {
1479
- ${Qt}
1481
+ ${Vt}
1480
1482
  }
1481
1483
  pageInfo {
1482
1484
  hasNextPage
1483
1485
  endCursor
1484
1486
  }
1485
- `,et=class extends N{async fetchIssue(n,e){let t=`
1487
+ `,it=class extends j{async fetchIssue(n,e){let t=`
1486
1488
  query GetIssue($identifier: String!) {
1487
1489
  issue(id: $identifier) {
1488
- ${Qt}
1490
+ ${Vt}
1489
1491
  }
1490
1492
  }
1491
- `;return(await V(this.config,e,t,{identifier:n})).issue}async fetchOrganization(n){let e=`
1493
+ `;return(await X(this.config,e,t,{identifier:n})).issue}async fetchOrganization(n){let e=`
1492
1494
  query GetOrganization {
1493
1495
  organization {
1494
1496
  id
@@ -1496,15 +1498,15 @@ OR comment ~ currentUser() OR summary ~ currentUser() OR description ~ currentUs
1496
1498
  urlKey
1497
1499
  }
1498
1500
  }
1499
- `;return(await V(this.config,n,e)).organization}async fetchTeams(n){let e=`
1501
+ `;return(await X(this.config,n,e)).organization}async fetchTeams(n){let e=`
1500
1502
  query GetTeams {
1501
1503
  teams {
1502
1504
  nodes {
1503
- ${_r}
1505
+ ${ss}
1504
1506
  }
1505
1507
  }
1506
1508
  }
1507
- `;return(await V(this.config,n,e)).teams}async rawRequest(n,e,t){return{data:await V(this.config,n,e,t)}}async fetchViewer(n){let e=`
1509
+ `;return(await X(this.config,n,e)).teams}async rawRequest(n,e,t){return{data:await X(this.config,n,e,t)}}async fetchViewer(n){let e=`
1508
1510
  query GetViewer {
1509
1511
  viewer {
1510
1512
  id
@@ -1513,23 +1515,23 @@ OR comment ~ currentUser() OR summary ~ currentUser() OR description ~ currentUs
1513
1515
  displayName
1514
1516
  }
1515
1517
  }
1516
- `;return(await V(this.config,n,e)).viewer}async getIssue(n,e={}){let t=await this.fetchIssue(n.number,e);return{data:await jt(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(Sn)}}async getProjects(n={},e={}){let t=await Cr(this.config,e,n.cursor??void 0);return{data:t.nodes.map(Er),pageInfo:{hasNextPage:t.pageInfo.hasNextPage,endCursor:t.pageInfo.endCursor??null}}}async getCycles(n={},e={}){let t=await Dr(this.config,e,n.cursor??void 0);return{data:t.nodes.map($r),pageInfo:{hasNextPage:t.pageInfo.hasNextPage,endCursor:t.pageInfo.endCursor??null}}}async getLabels(n={},e={}){let t=await Ur(this.config,e,n.cursor??void 0);return{data:t.nodes.map(Lr),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:r,cursor:o}=Gr(t),i=await this.fetchViewer(e),a,u,l=new Xe,p=async(c,d)=>{if(u||r>c)return;let g=await d(Math.max(Tr-l.length,1),r===c?o:void 0);if(!g)return;let m=await it(g.nodes.map(jt));l.push(...m),g.pageInfo.hasNextPage&&(a=c,u=g.pageInfo.endCursor)};return await p(1,async(c,d)=>(await this.rawRequest(e,`
1518
+ `;return(await X(this.config,n,e)).viewer}async getIssue(n,e={}){let t=await this.fetchIssue(n.number,e);return{data:await Jt(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(Yn)}}async getProjects(n={},e={}){let t=await Wr(this.config,e,n.cursor??void 0);return{data:t.nodes.map(Hr),pageInfo:{hasNextPage:t.pageInfo.hasNextPage,endCursor:t.pageInfo.endCursor??null}}}async getCycles(n={},e={}){let t=await Vr(this.config,e,n.cursor??void 0);return{data:t.nodes.map(Jr),pageInfo:{hasNextPage:t.pageInfo.hasNextPage,endCursor:t.pageInfo.endCursor??null}}}async getLabels(n={},e={}){let t=await Xr(this.config,e,n.cursor??void 0);return{data:t.nodes.map(Kr),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}=Yr(t),i=await this.fetchViewer(e),a,u,l=new st,p=async(d,c)=>{if(u||s>d)return;let g=await c(Math.max(es-l.length,1),s===d?o:void 0);if(!g)return;let m=await pt(g.nodes.map(Jt));l.push(...m),g.pageInfo.hasNextPage&&(a=d,u=g.pageInfo.endCursor)};return await p(1,async(d,c)=>(await this.rawRequest(e,`
1517
1519
  query GetAssignedIssues($first: Int!, $after: String) {
1518
1520
  viewer {
1519
1521
  issues: assignedIssues(first: $first, after: $after) {
1520
- ${Ze}
1522
+ ${nt}
1521
1523
  }
1522
1524
  }
1523
1525
  }
1524
- `,{first:c,after:d})).data?.viewer?.issues),await p(2,async(c,d)=>(await this.rawRequest(e,`
1526
+ `,{first:d,after:c})).data?.viewer?.issues),await p(2,async(d,c)=>(await this.rawRequest(e,`
1525
1527
  query GetCreatedIssues($first: Int!, $after: String) {
1526
1528
  viewer {
1527
1529
  issues: createdIssues(first: $first, after: $after) {
1528
- ${Ze}
1530
+ ${nt}
1529
1531
  }
1530
1532
  }
1531
1533
  }
1532
- `,{first:c,after:d})).data?.viewer?.issues),await p(4,async(c,d)=>(await this.rawRequest(e,`
1534
+ `,{first:d,after:c})).data?.viewer?.issues),await p(4,async(d,c)=>(await this.rawRequest(e,`
1533
1535
  query GetMentionedIssues($first: Int!, $after: String) {
1534
1536
  issues(
1535
1537
  first: $first
@@ -1550,10 +1552,10 @@ OR comment ~ currentUser() OR summary ~ currentUser() OR description ~ currentUs
1550
1552
  }]
1551
1553
  }
1552
1554
  ){
1553
- ${Ze}
1555
+ ${nt}
1554
1556
  }
1555
1557
  }
1556
- `,{first:c,after:d})).data?.issues),await p(5,async(c,d)=>{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,`
1557
1559
  query GetCommentedIssues($first: Int!, $after: String) {
1558
1560
  comments(
1559
1561
  first: $first
@@ -1576,7 +1578,7 @@ OR comment ~ currentUser() OR summary ~ currentUser() OR description ~ currentUs
1576
1578
  ){
1577
1579
  nodes {
1578
1580
  issue {
1579
- ${Qt}
1581
+ ${Vt}
1580
1582
  }
1581
1583
  }
1582
1584
  pageInfo {
@@ -1585,10 +1587,10 @@ OR comment ~ currentUser() OR summary ~ currentUser() OR description ~ currentUs
1585
1587
  }
1586
1588
  }
1587
1589
  }
1588
- `,{first:c,after:d})).data?.comments;return m?{nodes:m.nodes.map(y=>y.issue),pageInfo:m.pageInfo}:void 0}),{data:l.items,pageInfo:{hasNextPage:!!u,endCursor:Ar(a,u)}}}async getIssues(n,e={}){let{teams:t,projects:r,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(r&&r.length>0){let g=r.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:Zr(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=`
1589
1591
  query GetIssues($first: Int!, $after: String) {
1590
1592
  issues(first: $first, after: $after${u?", ":""}${u}) {
1591
- ${Ze}
1593
+ ${nt}
1592
1594
  }
1593
1595
  }
1594
- `,c=(await this.rawRequest(e,l,{first:Tr,after:i})).data?.issues;return c?{data:await it(c.nodes.map(jt)),pageInfo:{hasNextPage:c.pageInfo.hasNextPage,endCursor:c.pageInfo.endCursor??null}}:{data:[],pageInfo:{hasNextPage:!1,endCursor:null}}}};var kr=s=>{let n={request:s?.request};return{azureDevOps:new ae({...n,...s?.azureDevOps}),bitbucket:new ue({...n,...s?.bitbucket}),bitbucketServer:new le({...n,...s?.bitbucketServer}),github:new pe({...n,...s?.github}),gitlab:new ce({...n,...s?.gitlab}),jira:new me({...n,...s?.jira}),jiraServer:new ge({...n,...s?.jiraServer}),linear:new et({...n,...s?.linear}),trello:new he({...n,...s?.trello})}};var Nr=(i=>(i.Conflicts="conflicts",i.Failure="failure",i.NotSet="notSet",i.Queued="queued",i.RejectedByPolicy="rejectedByPolicy",i.Succeeded="succeeded",i))(Nr||{});var Fr=(e=>(e.Zero="0",e.One="1",e))(Fr||{}),jr=(e=>(e.PullRequest="pr",e.Issue="issue",e))(jr||{}),Qr=(d=>(d.Azure="azure",d.AzureDevOpsServer="azureDevOpsServer",d.Github="github",d.GithubEnterprise="githubEnterprise",d.Gitlab="gitlab",d.GitlabSelfHosted="gitlabSelfHosted",d.Bitbucket="bitbucket",d.BitbucketServer="bitbucketServer",d.Jira="jira",d.JiraServer="jiraServer",d.Linear="linear",d.Trello="trello",d))(Qr||{});var Br=(e=>(e.Completed="COMPLETED",e.NotPlanned="NOT_PLANNED",e))(Br||{});var Gn=kr;
1596
+ `,d=(await this.rawRequest(e,l,{first:es,after:i})).data?.issues;return d?{data:await pt(d.nodes.map(Jt)),pageInfo:{hasNextPage:d.pageInfo.hasNextPage,endCursor:d.pageInfo.endCursor??null}}:{data:[],pageInfo:{hasNextPage:!1,endCursor:null}}}};var ns=r=>{let n={request:r?.request};return{azureDevOps:new de({...n,...r?.azureDevOps}),bitbucket:new ce({...n,...r?.bitbucket}),bitbucketServer:new me({...n,...r?.bitbucketServer}),github:new ge({...n,...r?.github}),gitlab:new fe({...n,...r?.gitlab}),jira:new Re({...n,...r?.jira}),jiraServer:new Ie({...n,...r?.jiraServer}),linear:new it({...n,...r?.linear}),trello:new be({...n,...r?.trello})}};var os=(i=>(i.Conflicts="conflicts",i.Failure="failure",i.NotSet="notSet",i.Queued="queued",i.RejectedByPolicy="rejectedByPolicy",i.Succeeded="succeeded",i))(os||{});var is=(e=>(e.Zero="0",e.One="1",e))(is||{}),as=(e=>(e.PullRequest="pr",e.Issue="issue",e))(as||{}),us=(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))(us||{});var ls=(e=>(e.Completed="COMPLETED",e.NotPlanned="NOT_PLANNED",e))(ls||{});var ao=ns;