@gitkraken/provider-apis 0.42.0 → 0.43.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.
package/dist/index.js CHANGED
@@ -1,4 +1,5 @@
1
- "use strict";var It=Object.defineProperty;var Is=Object.getOwnPropertyDescriptor;var Rs=Object.getOwnPropertyNames;var ys=Object.prototype.hasOwnProperty;var k=(s,t)=>{for(var e in t)It(s,e,{get:t[e],enumerable:!0})},bs=(s,t,e,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of Rs(t))!ys.call(s,n)&&n!==e&&It(s,n,{get:()=>t[n],enumerable:!(r=Is(t,n))||r.enumerable});return s};var Ps=s=>bs(It({},"__esModule",{value:!0}),s);var ho={};k(ho,{AzureDevOps:()=>re,AzureDevopsUtils:()=>Ye,Bitbucket:()=>se,BitbucketServer:()=>ne,BitbucketServerUtils:()=>Ce,BitbucketUtils:()=>Ze,EntityIdentifierProviderType:()=>D,EntityIdentifierUtils:()=>dt,EntityType:()=>U,EntityVersion:()=>A,GitBuildStatusStage:()=>gr,GitBuildStatusState:()=>me,GitDiffLineType:()=>Rt,GitHub:()=>oe,GitHubIssueCloseReason:()=>fs,GitHubUtils:()=>gt,GitIssueState:()=>De,GitLab:()=>ae,GitLabUtils:()=>mt,GitMergeStrategy:()=>te,GitProviderUtils:()=>ct,GitPullRequestMergeableState:()=>F,GitPullRequestReviewState:()=>N,GitPullRequestState:()=>Y,GraphQLErrors:()=>h,Jira:()=>ue,JiraServer:()=>le,JiraUtils:()=>ht,Linear:()=>pe,PullRequestAsyncStatus:()=>hs,Trello:()=>de,TrelloUtils:()=>ft,Utils:()=>mo,default:()=>go,isFetch:()=>we});module.exports=Ps(ho);var gr=(n=>(n.Build="build",n.Production="production",n.Staging="staging",n.Test="test",n))(gr||{}),me=(c=>(c.ActionRequired="ACTION_REQUIRED",c.Cancelled="CANCELLED",c.Error="ERROR",c.Failed="FAILED",c.Pending="PENDING",c.Running="RUNNING",c.Skipped="SKIPPED",c.Success="SUCCESS",c.Warning="WARNING",c.OptionalActionRequired="OPTIONAL_ACTION_REQUIRED",c))(me||{}),te=(o=>(o.MergeCommit="MERGE_COMMIT",o.Rebase="REBASE",o.RebaseThenMergeCommit="REBASE_THEN_MERGE_COMMIT",o.FastForward="FAST_FORWARD",o.Squash="SQUASH",o))(te||{}),Y=(r=>(r.Open="OPEN",r.Closed="CLOSED",r.Merged="MERGED",r))(Y||{}),N=(n=>(n.Approved="APPROVED",n.ChangesRequested="CHANGES_REQUESTED",n.Commented="COMMENTED",n.ReviewRequested="REVIEW_REQUESTED",n))(N||{}),F=(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))(F||{}),Rt=(r=>(r.ADDED="ADDED",r.DELETED="DELETED",r.UNMODIFIED="UNMODIFIED",r))(Rt||{});var mr={APPROVED:0,COMMENTED:1,REVIEW_REQUESTED:2,CHANGES_REQUESTED:3},_=s=>!s||s.length===0?null:s.reduce((t,e)=>mr[e.state]>mr[t]?e.state:t,"APPROVED"),Pe=(s,t)=>s.name||s.username||s.email||t,Z=s=>{let t=Object.values(s).map(e=>e.name).sort((e,r)=>e.localeCompare(r));return Object.values(s).forEach(e=>{e.priority!==-1&&(e.priority=t.indexOf(e.name))}),s};var v=100;var hr=globalThis.fetch;var ws=async s=>{let t=s.headers.get("content-type")||"",e=null;if(t.startsWith("application/json")){let o=await s.text();e=o.trim().length>0?JSON.parse(o):null}else if(t.startsWith("text/")||t==="")e=await s.text();else if(t.startsWith("application/vnd.github.raw+json"))e=await s.arrayBuffer();else throw new Error(`Unsupported content-type: ${t}`);let r={};s.headers.forEach((o,i)=>{r[i]=o});let n={body:e,headers:r,status:s.status,statusText:s.statusText};if(!s.ok){let o=new Error(s.statusText);throw Object.assign(o,{response:n}),o}return n},yt=s=>async({url:t,...e})=>{let r=await s(t,e);return ws(r)};var we=(s,t=!1)=>s.name==="fetch"||t;var O=class{constructor(t){let e=t?.request||hr;this.config={...t,request:we(e,t?.forceIsFetch)?yt(e):e}}updateConfig(t){this.config={...this.config,...t,request:t.request&&we(t.request,t?.forceIsFetch??this.config.forceIsFetch)?yt(t.request):this.config.request}}},$=class extends O{};var I=(s,t)=>{let e={};return s&&(e.Authorization=`${t?"Basic":"Bearer"} ${s}`),e},fr=s=>s?s.reduce((t,e)=>(t[e]=!0,t),{}):void 0,J=(s,t,e)=>!s||t.some(r=>s[r])?e:"",Ir=async s=>{let t=[],e=!0,r;for(;e;){let n=await s(r);t=t.concat(n.data),e=!!n?.pageInfo?.hasNextPage,r=n?.pageInfo?.endCursor||n?.pageInfo?.nextPage}return t};async function bt(s){return(await Promise.allSettled(s)).map(e=>vs(e)).filter(e=>e!=null)}function vs(s,t=void 0){return s?.status==="fulfilled"?s.value:t}var Es="https://app.vssps.visualstudio.com/_apis",qs="https://vssps.dev.azure.com/",Ss="https://dev.azure.com",P=(s,t={})=>I(t.token||s.token,t.isPAT||s.isPAT),Rr=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/"),Pt=(s,t)=>{let e=t.baseUrl||s.baseUrl||Es;return e=e.replace(/\/$/,""),e},w=(s,t)=>{let e=t.baseUrl||s.baseUrl||Ss;return e=e.replace(/\/$/,""),e},wt=(s,t)=>{let e=t.baseUrl||s.baseUrl||qs;return e=e.replace(/\/$/,""),e};var Cs={active:"OPEN",completed:"MERGED",abandoned:"CLOSED"},Ds={10:"APPROVED",5:"APPROVED",0:"REVIEW_REQUESTED",[-5]:"CHANGES_REQUESTED",[-10]:"CHANGES_REQUESTED"},vt=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"}},ve=(s,t)=>{let e=[],r=[];return t.reviewers.forEach(n=>{let o={reviewer:vt(n),state:Ds[n.vote??0]||"REVIEW_REQUESTED"};n.isRequired&&e.push(o),r.push(o)}),{id:t.pullRequestId.toString(),title:t.title,description:t.description??null,number:t.codeReviewId,state:Cs[t.status],isDraft:t.isDraft,commentCount:null,upvoteCount:null,author:vt(t.createdBy),createdDate:new Date(t.creationDate),updatedDate:new Date(t.closedDate||t.creationDate),closedDate:t.closedDate?new Date(t.closedDate):null,mergedDate:t.closedDate&&t.status==="completed"?new Date(t.closedDate):null,repository:{id:t.repository.id,name:t.repository.name,project:t.repository.project.name,owner:{login:s},remoteInfo:null},headCommit:{buildStatuses:null},baseRef:{name:Ee(t.targetRefName),oid:t.lastMergeTargetCommit.commitId},headRef:{name:Ee(t.sourceRefName),oid:t.lastMergeSourceCommit.commitId},url:Rr(t),assignees:t.reviewers.map(vt),reviews:r,reviewDecision:_(e),additions:null,deletions:null,fileCount:null,commitCount:null,headRepository:t.forkSource?{id:t.forkSource.repository.id,name:t.forkSource.repository.name,project:void 0,owner:{login:s},remoteInfo:null}:{id:t.repository.id,name:t.repository.name,project:t.repository.project.name,owner:{login:s},remoteInfo:null},mergeableState:Ls(t.mergeStatus),labels:t.labels?.map(n=>({color:null,description:null,id:n.id,name:n.name}))??[],permissions:null}},yr=(s,t)=>({id:t.id,name:t.name,namespace:s,project:t.project.name,projectId:t.project.id,webUrl:t.webUrl,httpsUrl:t.remoteUrl,sshUrl:t.sshUrl,defaultBranch:t.defaultBranch?{name:Ee(t.defaultBranch)}:null,permissions:null}),As=(s,t,e,r)=>{let n=e.fields,o=n["System.AssignedTo"],i=n["System.State"],a=n["System.WorkItemType"],u;return i&&a&&(u=r[a]?.[i]),{id:e.id.toString(),number:e.id.toString(),title:n["System.Title"],commentCount:n["System.CommentCount"],author:{avatarUrl:n["System.CreatedBy"]._links?.avatar?.href??null,email:null,id:n["System.CreatedBy"].id,name:n["System.CreatedBy"].uniqueName??null,username:n["System.CreatedBy"].displayName??null,url:null},closedDate:n["Microsoft.VSTS.Common.ClosedDate"]?new Date(n["Microsoft.VSTS.Common.ClosedDate"]):null,createdDate:new Date(n["System.CreatedDate"]),updatedDate:new Date(n["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:n["System.Description"]??null,state:{name:u?.title||i,color:null},type:n["System.WorkItemType"],repository:null,project:{namespace:s,name:t,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()}))??[]}},re=class extends ${async getCurrentUser(t={},e={}){if(e.isPAT||this.config.isPAT)throw new Error("Azure DevOps does not support PATs for this function.");let r=`${Pt(this.config,e)}/profile/profiles/me`,n=await this.config.request({url:r,headers:P(this.config,e)});return{data:{id:n.body.id,name:n.body.displayName,username:n.body.displayName,email:n.body.emailAddress,avatarUrl:null,url:null}}}async getCurrentUserForInstance(t,e={}){let n=(await this.config.request({url:`${w(this.config,e)}/${encodeURIComponent(t.namespace)}/_apis/ConnectionData`,headers:P(this.config,e)})).body.authorizedUser;if(n.providerDisplayName==="Anonymous")throw new Error("Current user not found.");return{data:{id:n.id,name:n.providerDisplayName,username:n.providerDisplayName,email:n.properties.Account.$value,avatarUrl:null,url:null}}}async getUserForCommit(t,e={}){if(!t.repo.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let n=(await this.config.request({url:`${w(this.config,e)}/${encodeURIComponent(t.repo.namespace)}/${encodeURIComponent(t.repo.project)}/_apis/git/repositories/${encodeURIComponent(t.repo.name)}/commits/${t.oid}`,headers:P(this.config,e)})).body.author;return{data:{name:n.name,email:n.email,avatarUrl:n.imageUrl}}}async getOrgsForUser(t,e={}){let r=`${Pt(this.config,e)}/accounts?memberId=${t.userId}&api-version=6.0`;return{data:(await this.config.request({url:r,headers:P(this.config,e)})).body.value.map(o=>({id:o.accountId,name:o.accountName}))}}async getCollectionsForUser(t,e={}){let r=`${w(this.config,e)}/_apis/projectCollections`;return{data:(await this.config.request({url:r,headers:P(this.config,e)})).body.value.map(o=>({id:o.id,name:o.name}))}}async getAzureProjects(t,e={}){let r=new URL(`${w(this.config,e)}/${encodeURIComponent(t.namespace)}/_apis/projects`);r.searchParams.set("$top",v.toString()),t.cursor&&r.searchParams.set("$skip",t.cursor);let n=await this.config.request({url:r.toString(),headers:P(this.config,e)}),o=n.headers["x-ms-continuationtoken"];return{pageInfo:{hasNextPage:!!o,endCursor:o||null},data:n.body.value.map(i=>({id:i.id,name:i.name,namespace:t.namespace}))}}async getAzureProjectScopeDescriptor(t,e={}){let{namespace:r,projectId:n}=t;return{data:{scope:(await this.config.request({url:`${wt(this.config,e)}/${encodeURIComponent(r)}/_apis/graph/descriptors/${n}?api-version=6.0`,headers:P(this.config,e)})).body.value}}}async getAzureGraphAccountsForAzureProject(t,e={}){let{namespace:r,projectScopeDescriptor:n,cursor:o}=t,i=new URL(`${wt(this.config,e)}/${encodeURIComponent(r)}/_apis/graph/users`);n&&i.searchParams.set("scopeDescriptor",n),o&&i.searchParams.set("continuationToken",o);let a=await this.config.request({url:i.toString(),headers:P(this.config,e)}),u=a.headers["x-ms-continuationtoken"];return{pageInfo:{endCursor:u||null,hasNextPage:!!u},data:a.body.value.map(l=>({avatarUrl:l._links?.avatar?.href??null,descriptor:l.descriptor??null,email:l.mailAddress??null,name:l.displayName??null,storageKeyURL:l._links?.storageKey?.href??null,username:l.displayName??null}))}}async getAccountFromAzureGraphAccount(t,e={}){let{azureGraphAccount:r}=t;if(!r.storageKeyURL)throw new Error("Expected 'storageKeyURL' to not be null for 'azureGraphAccount'");let n=await this.config.request({url:r.storageKeyURL,headers:P(this.config,e)});return{data:{avatarUrl:r.avatarUrl,email:r.email,id:n.body.value,name:r.name,username:r.username,url:null}}}async getAccountsFromAzureGraphAccounts(t,e={}){let r=[];for(let n of t.azureGraphAccounts){let o=await this.getAccountFromAzureGraphAccount({azureGraphAccount:n},e);r.push(o.data)}return{data:r}}async getRepo(t,e={}){if(!t.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let r=await this.config.request({url:`${w(this.config,e)}/${encodeURIComponent(t.namespace)}/${encodeURIComponent(t.project)}/_apis/git/repositories/${encodeURIComponent(t.name)}`,headers:P(this.config,e)});return{data:yr(t.namespace,r.body)}}async getRepos(t,e={}){let r=[],n=[];return await Promise.all(t.map(async o=>{try{let i=await this.getRepo(o,e);r.push(i.data)}catch(i){n.push({input:o,error:i})}})),{data:r,errors:n}}async getReposForAzureProject(t,e={}){if(!t.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');return{data:(await this.config.request({url:`${w(this.config,e)}/${encodeURIComponent(t.namespace)}/${encodeURIComponent(t.project)}/_apis/git/repositories`,headers:P(this.config,e)})).body.value.map(n=>yr(t.namespace,n))}}async getRefs(t,e,r={}){if(!e.repo.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let n=new URL(`${w(this.config,r)}/${encodeURIComponent(e.repo.namespace)}/${encodeURIComponent(e.repo.project)}/_apis/git/repositories/${encodeURIComponent(e.repo.name)}/refs`);n.searchParams.set("filter",t),n.searchParams.set("$top",v.toString()),e.cursor&&n.searchParams.set("continuationToken",e.cursor);let o=await this.config.request({url:n.toString(),headers:P(this.config,r)}),i=o.headers["x-ms-continuationtoken"];return{pageInfo:{hasNextPage:!!i,endCursor:i||null},data:o.body.value.map(a=>({name:Ee(a.name),commit:{oid:a.objectId,authoredDate:null,committedDate:null}}))}}async getBranches(t,e={}){return this.getRefs("heads",t,e)}async getTags(t,e={}){return this.getRefs("tags",t,e)}async getPullRequestsForRepoBase(t,e={},r=100){let{page:n,repo:o,assigneeLogins:i,authorLogin:a}=t||{},u=n||1;if(!o.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let l="searchCriteria.status=1";return i&&i.length&&(l+=`&searchCriteria.reviewerId=${i[0]}`),a&&(l+=`&searchCriteria.creatorId=${a}`),await this.config.request({url:`${w(this.config,e)}/${encodeURIComponent(o.namespace)}/${encodeURIComponent(o.project||"")}/_apis/git/repositories/${encodeURIComponent(o.name)}/pullRequests?${l}&%24top=${r}&%24skip=${(u-1)*r}`,headers:P(this.config,e)})}async getPullRequestsForRepo(t,e={}){let n=t.page||1,o=await this.getPullRequestsForRepoBase(t,e,100);return{pageInfo:{hasNextPage:o.body.value.length===100,nextPage:n+1},data:o.body.value.map(i=>ve(t.repo.namespace,i))}}async getPullRequestsForRepos(t,e={}){if(!t.repos.every(o=>o.project))throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let{repos:r}=t||{},n=[];return await Promise.all(r.map(async o=>{try{(await this.getPullRequestsForRepoBase({repo:o,...t},e)).body.value.forEach(a=>{n.push(ve(o.namespace,a))})}catch(i){if(i.statusCode!==404&&i.statusCode!==401)throw i}})),{data:n}}async getPullRequestsForProjectBase(t,e={},r=100){let{namespace:n,project:o,page:i,assigneeLogins:a,authorLogin:u,repo:l}=t;if(l?.project&&l.project!==o)throw new Error("Could not fetch pull requests, project mismatch");let c=i||1,p=new URL(`${w(this.config,e)}/${encodeURIComponent(n)}/${encodeURIComponent(o)}/_apis/git/pullRequests`);return p.searchParams.set("searchCriteria.status","1"),p.searchParams.set("$top",r.toString()),p.searchParams.set("$skip",((c-1)*r).toString()),l?.id&&l?.project===o&&p.searchParams.set("searchCriteria.repositoryId",l.id),a&&a.length&&p.searchParams.set("searchCriteria.reviewerId",a[0]),u&&p.searchParams.set("searchCriteria.creatorId",u),await this.config.request({url:p.toString(),headers:P(this.config,e)})}async getPullRequestsForProject(t,e={}){let n=t.page||1,o=await this.getPullRequestsForProjectBase(t,e,100);return{pageInfo:{hasNextPage:o?.body.value.length===100,nextPage:n+1},data:o?.body.value.map(i=>ve(t.namespace,i))||[]}}async getPullRequestsForProjects(t,e={}){let{projects:r}=t||{},n=[];return await Promise.all(r.map(async o=>{try{(!t.repo||t.repo.project&&t.repo.project===o.project)&&(await this.getPullRequestsForProjectBase({...o,...t},e))?.body.value.forEach(a=>{n.push(ve(o.namespace,a))})}catch(i){if(i.statusCode!==404&&i.statusCode!==401)throw i}})),{data:n}}async getAzurePullRequestLastMergeStatus(t,e={}){if(!t.repo.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let{repo:{namespace:r,project:n,name:o},pullRequestId:i}=t,a=await this.config.request({url:`${w(this.config,e)}/${encodeURIComponent(r)}/${encodeURIComponent(n||"")}/_apis/git/repositories/${o}/pullrequests/${i}?includeCommits=true?api-version=6.0`,headers:{...P(this.config,e)}});if(!a.body.mergeStatus)throw new Error("Could not fetch pull request");return{data:a.body.mergeStatus}}async updatePullRequest(t,e,r){return await this.config.request({method:"PATCH",url:`${w(this.config,r)}/${encodeURIComponent(t.repository.owner.login)}/${encodeURIComponent(t.repository.project)}/_apis/git/repositories/${t.repository.name}/pullrequests/${t.id}?api-version=6.0`,body:e,headers:{...P(this.config,r),"Content-Type":"application/json"}})}async closePullRequest(t,e={}){let{pullRequest:r}=t,n={status:"abandoned"};if(!(await this.updatePullRequest(r,JSON.stringify(n),e)).body.status)throw new Error("Could not close pull request")}async mergePullRequest(t,e={}){let{pullRequest:r,mergeStrategy:n}=t,o;switch(n){case"MERGE_COMMIT":{o="noFastForward";break}case"REBASE":{o="rebase";break}case"REBASE_THEN_MERGE_COMMIT":{o="rebaseMerge";break}case"SQUASH":{o="squash";break}}let i={completionOptions:{mergeStrategy:o},lastMergeSourceCommit:{commitId:r.headRef?.oid},status:"completed"};if(!(await this.updatePullRequest(r,JSON.stringify(i),e)).body.status)throw new Error("Could not merge pull request")}async addPullRequestLabel(t,e={}){let{pullRequest:r,label:n}=t;if(!r.repository.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let o={name:n.name};if(!(await this.config.request({method:"POST",url:`${w(this.config,e)}/${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(o),headers:{...P(this.config,e),"Content-Type":"application/json"}})).body.id)throw new Error("Could not add pull request label")}async removePullRequestLabel(t,e={}){let{pullRequest:r,label:n}=t;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:`${w(this.config,e)}/${encodeURIComponent(r.repository.owner.login)}/${encodeURIComponent(r.repository.project)}/_apis/git/repositories/${r.repository.name}/pullrequests/${r.id}/labels/${encodeURIComponent(n.name)}?api-version=6.0`,headers:{...P(this.config,e)}})}async setPullRequestLabels(t,e={}){let{pullRequest:r,labels:n}=t;if(!r.repository.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let o=r.labels;if(!o)throw new Error('Azure DevOps requires "labels" for this function.');for(let i of n)o.find(a=>a.id===i.id)||await this.addPullRequestLabel({pullRequest:r,label:i},e);for(let i of o)n.find(a=>i.id===a.id)||await this.removePullRequestLabel({pullRequest:r,label:i},e)}async setPullRequestAsDraft(t,e={}){let{pullRequest:r,isDraft:n}=t,o={isDraft:n};if(!(await this.updatePullRequest(r,JSON.stringify(o),e)).body.status)throw new Error("Could not set the pull request as draft")}async addPullRequestReviewer(t,e={}){let{pullRequest:r,reviewer:n,isRequired:o}=t,i={id:n.id,isRequired:o};if(!(await this.config.request({method:"PUT",url:`${w(this.config,e)}/${encodeURIComponent(r.repository.owner.login)}/${encodeURIComponent(r.repository.project)}/_apis/git/repositories/${r.repository.name}/pullrequests/${r.id}/reviewers/${n.id}?api-version=6.0`,body:JSON.stringify(i),headers:{...P(this.config,e),"Content-Type":"application/json"}})).body.id)throw new Error("Could not add pull request reviewer")}async removePullRequestReviewer(t,e={}){let{pullRequest:r,reviewer:n}=t;await this.config.request({method:"DELETE",url:`${w(this.config,e)}/${encodeURIComponent(r.repository.owner.login)}/${encodeURIComponent(r.repository.project)}/_apis/git/repositories/${r.repository.name}/pullrequests/${r.id}/reviewers/${n.id}?api-version=6.0`,headers:{...P(this.config,e),Accept:"application/json"}})}async setPullRequestReviewers(t,e={}){let{pullRequest:r,reviewers:n}=t;for(let o of n)r.assignees.find(i=>i.id===o.id)||await this.addPullRequestReviewer({pullRequest:r,reviewer:o,isRequired:!0},e);for(let o of r.assignees)n.find(i=>o.id===i.id)||await this.removePullRequestReviewer({pullRequest:r,reviewer:o},e)}async getIssuesForAzureProject(t,e={}){let{page:r,assigneeLogins:n,authorLogin:o,mentionLogin:i,labelNames:a,statusByWorkItemIdByStatusId:u}=t||{},l=r||1,c=200,p=["[Microsoft.VSTS.Common.ClosedDate] = ''","[System.TeamProject] = @project","[Microsoft.VSTS.Common.ResolvedDate] = ''"];o&&p.push(`[System.CreatedBy] = '${o.replace("'","''")}'`),n&&n[0]&&p.push(`[System.AssignedTo] = '${n[0].replace("'","''")}'`),i&&p.push("[System.Id] IN (@recentMentions)"),a&&a.forEach(R=>p.push(`[System.Tags] Contains '${R}'`));let d=`Select [Microsoft.VSTS.Common.ClosedDate], [Microsoft.VSTS.Common.ResolvedDate] From WorkItems Where ${p.join(" AND ")} order by [System.CreatedDate] desc`,g=await this.config.request({url:`${w(this.config,e)}/${encodeURIComponent(t.namespace)}/${encodeURIComponent(t.project)}/_apis/wit/wiql?api-version=6.0`,body:JSON.stringify({query:d}),method:"POST",headers:{...P(this.config,e),"Content-Type":"application/json"}}),m=g.body.workItems.slice((l-1)*c,c*l).map(R=>R.id);if(m.length==0)return{pageInfo:{hasNextPage:!1,nextPage:null},data:[]};let y=await this.config.request({url:`${w(this.config,e)}/${encodeURIComponent(t.namespace)}/${encodeURIComponent(t.project)}/_apis/wit/workitemsbatch?api-version=6.0`,body:JSON.stringify({ids:m,$expand:"Links"}),method:"POST",headers:{...P(this.config,e),"Content-Type":"application/json"}});return{pageInfo:{hasNextPage:g.body.workItems.length>c*l,nextPage:l+1},data:y.body.value.map(R=>As(t.namespace,t.project,R,u||{}))}}async getPermissionsForRepos(t,e={}){let{namespace:r,repos:n}=t,o={4:["canPush","canCreateWebhook"],1024:["isAdmin"],2048:["isAdmin"],4096:["isAdmin"],8192:["isAdmin"]},i=c=>{let p="2e9eb7ed-3c0a-47d4-87c1-0ffdd275fd87",d=`repoV2/${c.projectId}/${c.id}`;return Object.keys(o).map(g=>({securityNamespaceId:p,token:d,permissions:g}))},a={alwaysAllowAdministrators:!1,evaluations:n.flatMap(i)};return{data:(await this.config.request({method:"POST",url:`${w(this.config,e)}/${encodeURIComponent(r)}/_apis/security/permissionevaluationbatch?api-version=7.0`,body:JSON.stringify(a),headers:{...P(this.config,e),"Content-Type":"application/json"}})).body.evaluations.reduce((c,p)=>{let[,d,g]=p.token.split("/"),m=`${d}/${g}`,y=o[p.permissions];for(let R of y)c[m]===void 0&&(c[m]={canCreateWebhook:!0,canPush:!0,isAdmin:!0}),p.value===!1&&(c[m][R]=!1);return c},{})}}async decorateReposWithPermissions(t,e={}){let{namespace:r,repos:n}=t,o=await this.getPermissionsForRepos({namespace:r,repos:n},e);return{data:n.map(i=>({...i,permissions:o.data[`${i.projectId}/${i.id}`]}))}}async updateIssue(t,e,r={}){return await this.config.request({method:"PATCH",url:`${w(this.config,r)}/${encodeURIComponent(t.project.namespace)}/${encodeURIComponent(t.project.name)}/_apis/wit/workitems/${t.id}?api-version=6.0`,body:JSON.stringify(e),headers:{...P(this.config,r),"Content-Type":"application/json-patch+json"}})}async setIssueStatus(t,e={}){let{issue:r,status:n}=t,o=[{op:"add",path:"/fields/System.State",value:n.name}];if(!(await this.updateIssue(r,o,e)).body.fields?.["System.State"])throw new Error("Could not set issue status")}async setIssueAssignee(t,e={}){let{issue:r,assignee:n}=t,o=[{op:"add",path:"/fields/System.AssignedTo",value:n?.name??""}];if(!(await this.updateIssue(r,o,e)).body.fields?.["System.State"])throw new Error("Could not set issue assignee")}async setIssueLabels(t,e={}){let{issue:r,labels:n}=t,i=[{op:"replace",path:"/fields/System.Tags",value:n.map(u=>u.name).join(";")}];if(!(await this.updateIssue(r,i,e)).body.fields?.["System.Tags"])throw new Error("Could not set issue tags")}async getIssueTypesForAzureProject(t,e={}){if(!t.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let{namespace:r,project:n}=t;return{data:(await this.config.request({url:`${w(this.config,e)}/${encodeURIComponent(r)}/${encodeURIComponent(n||"")}/_apis/wit/workitemtypes?api-version=6.0`,headers:{...P(this.config,e)}})).body.value}}async getLabelsForProject(t,e={}){let{namespace:r,project:n}=t;return{data:(await this.config.request({url:`${w(this.config,e)}/${encodeURIComponent(r)}/${encodeURIComponent(n||"")}/_apis/wit/tags?api-version=6.0`,headers:{...P(this.config,e)}})).body.value.map(i=>({color:null,description:null,id:i.id,name:i.name,url:i.url}))}}};var q=(s,t={})=>I(t.token||s.token,t.isPAT||s.isPAT);var S="https://api.bitbucket.org/2.0",Us={OPEN:"OPEN",MERGED:"MERGED",DECLINED:"CLOSED"},qe={owner:4,admin:3,contributor:2,member:1},Se=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}),br=s=>{let t=s.links.clone,e=t?.find(n=>n.name==="ssh"),r=t?.find(n=>n.name==="https");return e&&r?{cloneUrlHTTPS:r.href,cloneUrlSSH:e.href}:null},Et=s=>({id:s.uuid,namespace:s.workspace.slug,name:s.slug,webUrl:s.links.html.href,httpsUrl:s.links.clone.find(t=>t.name==="https")?.href??null,sshUrl:s.links.clone.find(t=>t.name==="ssh")?.href??null,defaultBranch:{name:s.mainbranch.name},permissions:null}),qt=s=>{let t=s.id,e=s.participants?.map(r=>{let n="REVIEW_REQUESTED";return r.approved?n="APPROVED":r.state==="changes_requested"?n="CHANGES_REQUESTED":r.participated_on!==null&&(n="COMMENTED"),{reviewer:Se(r.user),state:n}})??[];return{id:t.toString(),title:s.title,description:s.description,number:t,state:Us[s.state],isDraft:!1,commentCount:s.comment_count,upvoteCount:null,author:Se(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:br(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:_(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:br(s.source.repository)},mergeableState:"MERGEABLE",permissions:null}},$s=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}}},Ts=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}}},se=class extends O{async refreshToken(t){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 ${t.base64ClientIDColonClientSecret}`},body:`grant_type=refresh_token&refresh_token=${t.refreshToken}`})).body}}async getCurrentUser(t={},e={}){let r=await this.config.request({url:`${S}/user`,headers:q(this.config,e)});return{data:Se(r.body)}}async getUserForCommit(t,e={}){let n=(await this.config.request({url:`${S}/repositories/${t.repo.namespace}/${t.repo.name}/commit/${t.oid}`,headers:q(this.config,e)})).body.author,o=n.raw.match(/([^<]+)<(.+)>/);return{data:{name:o?o[1].trim():null,email:o?o[2]:null,avatarUrl:n.user?.links.avatar.href||null}}}async getRepo(t,e={}){let r=await this.config.request({url:`${S}/repositories/${t.namespace}/${t.name}`,headers:q(this.config,e)});return{data:Et(r.body)}}async getRepos(t,e={}){let r=[],n=[];return await Promise.all(t.map(async o=>{try{let i=await this.getRepo(o,e);r.push(i.data)}catch(i){n.push({input:o,error:i})}})),{data:r,errors:n}}async getReposForWorkspace(t,e={}){let r=new URL(`${S}/repositories/${encodeURIComponent(t.workspace)}`);r.searchParams.set("page",t.page?.toString()||"1"),r.searchParams.set("pagelen",v.toString()),t.minimumRole&&r.searchParams.set("role",t.minimumRole);let n=await this.config.request({url:r.toString(),headers:q(this.config,e)}),o=!!n.body.next;return{pageInfo:{hasNextPage:o,nextPage:o?n.body.page+1:null},data:n.body.values.map(Et)}}async getAllReposForWorkspace(t,e={}){let r=[],n=1;for(;n!==null;){let o=await this.getReposForWorkspace({workspace:t.workspace,minimumRole:t.minimumRole,page:n},e);r.push(...o.data),n=o.pageInfo.hasNextPage?o.pageInfo.nextPage:null}return r}async getAllReposForWorkspaceWithPermissions(t,e={}){let r=new Map,n=[],o=qe[t.minimumRole||"member"];o<=qe.admin&&n.push("admin"),o<=qe.contributor&&n.push("contributor"),o<=qe.member&&n.push("member");let i=[];for(let a of n){i=await this.getAllReposForWorkspace({workspace:t.workspace,minimumRole:a},e);for(let u of i)r.has(u.id)||r.set(u.id,a)}return{data:i.map(a=>{let u=r.get(a.id)||"member";return{...a,permissions:Ts(u)}})}}async getReposForCurrentUser(t,e={}){let r=new URL(`${S}/repositories`);r.searchParams.set("role","member"),r.searchParams.set("pagelen",v.toString()),t.cursor&&r.searchParams.set("after",t.cursor);let n=await this.config.request({url:r.toString(),headers:q(this.config,e)}),o=!!n.body.next,i=null;return n.body.next&&(i=new URL(n.body.next).searchParams.get("after")),{pageInfo:{hasNextPage:o,endCursor:i},data:n.body.values.map(Et)}}async getBranches(t,e={}){let r=new URL(`${S}/repositories/${t.repo.namespace}/${t.repo.name}/refs/branches`);r.searchParams.set("page",t.page?.toString()||"1"),r.searchParams.set("pagelen",v.toString());let n=await this.config.request({url:r.toString(),headers:q(this.config,e)}),o=!!n.body.next;return{pageInfo:{hasNextPage:o,nextPage:o?n.body.page+1:null},data:n.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(t,e={}){let r=new URL(`${S}/repositories/${t.repo.namespace}/${t.repo.name}/refs/tags`);r.searchParams.set("pagelen",v.toString()),t.cursor&&r.searchParams.set("page",t.cursor);let n=await this.config.request({url:r.toString(),headers:q(this.config,e)}),o=!!n.body.next,i=null;return n.body.next&&(i=new URL(n.body.next).searchParams.get("page")),{pageInfo:{hasNextPage:o,endCursor:i},data:n.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(t={},e={}){let r=new URL(`${S}/user/workspaces`);r.searchParams.set("page",t?.page?.toString()||"1"),r.searchParams.set("pagelen","50"),t?.administrator!==void 0&&r.searchParams.set("administrator",t.administrator.toString());let n=await this.config.request({url:r.toString(),headers:q(this.config,e)}),o=!!n.body.next;return{pageInfo:{hasNextPage:o,nextPage:o?n.body.page+1:null},data:n.body.values.map(i=>({id:i.workspace.uuid,slug:i.workspace.slug}))}}async getWorkspacesForUser(t,e={}){let r=new URL(`${S}/user/permissions/workspaces`);r.searchParams.set("page",t.page?.toString()||"1"),r.searchParams.set("pagelen","50");let n=await this.config.request({url:r.toString(),headers:q(this.config,e)}),o=!!n.body.next;return{pageInfo:{hasNextPage:o,nextPage:o?n.body.page+1:null},data:n.body.values.map(i=>({id:i.workspace.uuid,slug:i.workspace.slug,name:i.workspace.name}))}}async getPullRequestsForUserAndWorkspace(t,e={}){let r=new URL(`${S}/workspaces/${t.workspaceSlug}/pullrequests/${t.userId}`);if(r.searchParams.set("fields","+values.participants,+values.destination.repository.links.clone.*,+values.source.repository.links.clone.*"),r.searchParams.set("page",t.page?.toString()||"1"),r.searchParams.set("pagelen","50"),t.repos&&t.repos.length>0){let i=`state = "open" AND (${t.repos.map(a=>`source.repository.full_name = "${a.namespace}/${a.name}"`).join(" OR ")})`;r.searchParams.set("q",i)}let n=await this.config.request({url:r.toString(),headers:q(this.config,e)}),o=!!n.body.next;return{pageInfo:{hasNextPage:o,nextPage:o?n.body.page+1:null},data:n.body.values.map(qt)}}async getPullRequestsForRepoBase(t,e={}){let r=new URL(`${S}/repositories/${encodeURI(t.repo.namespace)}/${encodeURI(t.repo.name)}/pullrequests?state=OPEN`),n=[];t.reviewerId&&n.push(`reviewers.uuid="${t.reviewerId}"`),t.authorLogin&&n.push(`author.uuid="${t.authorLogin}"`);let o='state="OPEN"';return n.length&&(o+=` AND (${n.join(t.useOrFilter?" OR ":" AND ")})`),r.searchParams.set("fields","+values.participants,+values.destination.repository.links.clone.*,+values.source.repository.links.clone.*"),r.searchParams.set("page",t.page?.toString()||"1"),r.searchParams.set("pagelen","50"),r.searchParams.set("q",o),await this.config.request({url:r.toString(),headers:q(this.config,e)})}async getPullRequestsForRepo(t,e={}){let r=[],n=await this.getPullRequestsForRepoBase(t,e);n.body.values.forEach(i=>{r.push(qt(i))});let o=!!n.body.next;return{pageInfo:{hasNextPage:o,nextPage:o?n.body.page+1:null},data:r}}async getPullRequestsForRepos(t,e={}){let r=[];return await Promise.all(t.repos.map(async n=>{try{(await this.getPullRequestsForRepoBase({repo:n,...t},e)).body.values.forEach(i=>{r.push(qt(i))})}catch(o){if(o.statusCode!==404&&o.statusCode!==401)throw o}})),{data:r}}async getAccountsForWorkspace(t,e={}){let r=new URL(`${S}/workspaces/${encodeURI(t.workspace)}/members`);r.searchParams.set("page",t.page?.toString()||"1"),r.searchParams.set("pagelen","100");let n=await this.config.request({url:r.toString(),headers:q(this.config,e)}),o=!!n.body.next;return{pageInfo:{hasNextPage:o,nextPage:o?n.body.page+1:null},data:n.body.values.map(i=>Se(i.user))}}async getReposPermissionsForCurrentUser(t,e={}){let r=new URL(`${S}/user/permissions/repositories`);r.searchParams.set("page",t.page?.toString()||"1"),r.searchParams.set("pagelen","100");let n=await this.config.request({url:r.toString(),headers:q(this.config,e)}),o=!!n.body.next;return{pageInfo:{hasNextPage:o,nextPage:o?n.body.page+1:null},data:n.body.values.reduce((i,a)=>({...i,[a.repository.uuid]:$s(a.permission)}),{})}}async decorateReposWithPermissions(t,e={}){let r={},n=1;do{let o=await this.getReposPermissionsForCurrentUser({page:n},e);r={...o.data,...r},n=o.pageInfo.hasNextPage?o.pageInfo.nextPage:null}while(n!==null);return{data:t.repos.map(o=>({...o,permissions:r[o.id]??{canCreateWebhook:!1,canPush:!1,isAdmin:!1}}))}}async closePullRequest(t,e={}){let{pullRequest:r}=t;if(!(await this.config.request({method:"POST",url:`${S}/repositories/${r.repository.owner.login}/${r.repository.name}/pullrequests/${r.id}/decline`,headers:q(this.config,e)})).body.title)throw new Error("Could not close pull request")}async mergePullRequest(t,e={}){let{pullRequest:r,mergeStrategy:n}=t,o;switch(n){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:`${S}/repositories/${r.repository.owner.login}/${r.repository.name}/pullrequests/${r.id}/merge`,body:JSON.stringify(i),headers:{...q(this.config,e),"Content-Type":"application/json"}})).body.title)throw new Error("Could not merge pull request")}async setPullRequestReviewers(t,e={}){let{pullRequest:r,reviewers:n}=t,o={reviewers:n.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:`${S}/repositories/${r.repository.owner.login}/${r.repository.name}/pullrequests/${r.id}`,body:JSON.stringify(o),headers:{...q(this.config,e),"Content-Type":"application/json"}})).body.title)throw new Error("Could not set pull request reviewers")}};var Ce={};k(Ce,{normalizePermissions:()=>St,restApiPullRequestToCommonPullRequest:()=>Gs});var Gs=s=>he(s),St=s=>s?s.find(t=>t.permission==="USER_ADMIN"||t.permission==="PROJECT_ADMIN"||t.permission==="ADMIN"||t.permission==="SYS_ADMIN"||t.permission==="REPO_ADMIN")?{canCreateWebhook:!0,canPush:!0,isAdmin:!0}:s.find(t=>t.permission==="REPO_WRITE"||t.permission==="REPO_CREATE"||t.permission==="PROJECT_CREATE"||t.permission==="PROJECT_WRITE")?{canCreateWebhook:!1,canPush:!0,isAdmin:!1}:{canCreateWebhook:!1,canPush:!1,isAdmin:!1}:{canCreateWebhook:!1,canPush:!1,isAdmin:!1};var fe=s=>{let t=s.links.self[0].href;return{name:s.displayName,email:s.emailAddress,avatarUrl:s.avatarUrl??(t&&`${t}/avatar.png`),id:s.id.toString(),username:s.name,url:t}},he=s=>{let t={OPEN:"OPEN",MERGED:"MERGED",DECLINED:"CLOSED"},e={UNAPPROVED:"REVIEW_REQUESTED",NEEDS_WORK:"CHANGES_REQUESTED",APPROVED:"APPROVED"},r=s.reviewers.map(u=>({reviewer:fe(u.user),state:e[u.status]})),n=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:t[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:fe(s.author.user),assignees:null,reviews:r,reviewDecision:_(r),repository:{id:s.toRef.repository.id.toString(),name:s.toRef.repository.name,owner:{login:s.toRef.repository.project.key},remoteInfo:o&&n?{cloneUrlHTTPS:o,cloneUrlSSH:n}: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}},Pr=s=>({id:s.id.toString(),namespace:s.project.key,name:s.slug,webUrl:s.links.self[0]?.href??null,httpsUrl:s.links.clone.find(t=>t.name==="https"||t.name==="http")?.href??null,sshUrl:s.links.clone.find(t=>t.name==="ssh")?.href??null,defaultBranch:null,permissions:null}),ne=class extends ${getBaseUrl(t){let e=t.baseUrl||this.config.baseUrl;if(!e)throw new Error('Bitbucket Server requires "baseUrl"');return e}getRequestHeaders(t){return I(t.token||this.config.token)}async getCurrentUser(t={},e={}){let r=await this.config.request({url:`${this.getBaseUrl(e)}/users?limit=2`,headers:this.getRequestHeaders(e)}),{headers:{"x-auserid":n,"x-ausername":o}}=r,i=n?parseInt(n,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:c,id:p,name:d,slug:g})=>i?i===p:a===d||a===c||a===g);if(!l)throw new Error("Could not find current Bitbucket Server user");return{data:fe(l)}}async getUserForCommit(t,e){let{repo:r,oid:n}=t,o=await this.config.request({url:`${this.getBaseUrl(e)}/projects/${r.namespace}/repos/${r.name}/commits/${n}`,headers:this.getRequestHeaders(e)});if(!o.body.author)throw new Error("Could not find user for commit");return{data:fe(o.body.author)}}async getRepo(t,e={}){let r=await this.config.request({url:`${this.getBaseUrl(e)}/projects/${t.namespace}/repos/${t.name}`,headers:this.getRequestHeaders(e)});return{data:Pr(r.body)}}async getRepos(t,e={}){let r=[],n=[];return await Promise.all(t.map(async o=>{try{let i=await this.getRepo(o,e);r.push(i.data)}catch(i){n.push({input:o,error:i})}})),{data:r,errors:n}}async getReposForCurrentUser(t,e={}){let r=t.page??0,n=await this.config.request({url:`${this.getBaseUrl(e)}/repos?start=${r}`,headers:this.getRequestHeaders(e)});return{pageInfo:{hasNextPage:!n.body.isLastPage,nextPage:n.body.nextPageStart},data:n.body.values.map(Pr)}}async getRepoPermissionsForUsername(t,e={}){let r=new URL(`${this.getBaseUrl(e)}/projects/${t.repo.namespace}/repos/${t.repo.name}/permissions/search?filterText=${t.username}`);try{let n=await this.config.request({url:r.toString(),headers:this.getRequestHeaders(e)});return{data:St(n.body.values)}}catch(n){if(n.response?.status===401)return{data:{canCreateWebhook:!1,canPush:!1,isAdmin:!1}};throw n}}async decorateReposWithPermissions(t,e={}){return await Promise.all(t.repos.map(async n=>{let o=await this.getRepoPermissionsForUsername({repo:n,username:t.username},e);return{...n,permissions:o.data}}))}async getPullRequestsForRepoBase(t,e={}){let r=new URL(`${this.getBaseUrl(e)}/projects/${encodeURI(t.repo.namespace)}/repos/${encodeURI(t.repo.name)}/pull-requests?state=OPEN`);return r.searchParams.set("start",t.page?.toString()||"0"),r.searchParams.set("limit","50"),await this.config.request({url:r.toString(),headers:this.getRequestHeaders(e)})}async getPullRequestsForRepo(t,e={}){let r=[],n=await this.getPullRequestsForRepoBase(t,e);n.body.values.forEach(i=>{if(t.authorLogin&&i.author.user.name!==t.authorLogin)return null;r.push(he(i))});let o=n.body.values.length!==0;return{pageInfo:{hasNextPage:o,nextPage:o?n.body.start+n.body.values.length:null},data:r}}async getPullRequestsForRepos(t,e={}){let r=[];return await Promise.all(t.repos.map(async n=>{try{(await this.getPullRequestsForRepoBase({repo:n,...t},e)).body.values.forEach(i=>{if(t.authorLogin&&i.author.user.name!==t.authorLogin)return null;r.push(he(i))})}catch(o){if(o.statusCode!==404&&o.statusCode!==401)throw o}})),{data:r}}async getPullRequestsForCurrentUser(t,e={}){let r=new URL(`${this.getBaseUrl(e)}/dashboard/pull-requests`);r.searchParams.set("state","OPEN"),r.searchParams.set("start",t.page?.toString()||"0"),r.searchParams.set("limit","50");let n=await this.config.request({url:r.toString(),headers:this.getRequestHeaders(e)}),o=n.body.values.length!==0;return{pageInfo:{hasNextPage:o,nextPage:o?n.body.start+n.body.values.length:null},data:n.body.values.map(he)}}async closePullRequest(t,e={}){let{pullRequest:r}=t;if(r.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/${r.repository.owner.login}/repos/${r.repository.name}/pull-requests/${r.id}/decline`,body:JSON.stringify({version:r.version}),headers:{...this.getRequestHeaders(e),"Content-Type":"application/json"}})).body.title)throw new Error("Could not close pull request")}async mergePullRequest(t,e={}){let{pullRequest:r,mergeStrategyId:n}=t;if(t.mergeStrategy)throw new Error('Bitbucket Server uses "mergeStrategyId" instead of "mergeStrategy".');if(r.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/${r.repository.owner.login}/repos/${r.repository.name}/pull-requests/${r.id}/merge`,body:JSON.stringify({strategyId:n,version:r.version}),headers:{...this.getRequestHeaders(e),"Content-Type":"application/json"}})).body.title)throw new Error("Could not merge pull request")}async getMergeStrategies(t={}){let e=await this.config.request({url:`${this.getBaseUrl(t)}/admin/pull-requests/git`,headers:{...this.getRequestHeaders(t),"Content-Type":"application/json"}});return{data:{defaultStrategy:e.body.mergeConfig.defaultStrategy,strategies:e.body.mergeConfig.strategies}}}async setPullRequestReviewers(t,e={}){let{pullRequest:r,reviewers:n}=t;if(r.version===void 0)throw new Error('Bitbucket Server requires "version" for this function.');let o={reviewers:n.map(a=>{if(a.username)throw new Error('Bitbucket Server reviewer requires "username" for this function.');return{user:{name:a.username}}}),version:r.version};if(!(await this.config.request({method:"PUT",url:`${this.getBaseUrl(e)}/projects/${r.repository.owner.login}/repos/${r.repository.name}/pull-requests/${r.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(t,e={}){let r=new URL(`${this.getBaseUrl(e)}/projects/${encodeURI(t.project)}/permissions/users`);r.searchParams.set("start",t.page?.toString()||"0"),r.searchParams.set("limit","50");let n=await this.config.request({url:r.toString(),headers:this.getRequestHeaders(e)}),o=n.body.values.length!==0;return{pageInfo:{hasNextPage:o,nextPage:o?n.body.start+n.body.values.length:null},data:n.body.values.map(i=>fe(i.user))}}};var xr=require("js-base64");var De=(e=>(e.Open="OPEN",e.Closed="CLOSED",e))(De||{});var h=class extends Error{constructor(e,r){let n=r?.map(i=>`'${i.message}'`).join(", "),o=n?`${e}: ${n}`:e;super(o);this.graphQLErrors=r??[]}};var Os={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]},wr=15,vr=100,Ie={__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"},C=s=>!!s,B=(s,t)=>{let e=Os[t];for(let r=0;r<3;r++){if(s[r]>e[r])return!0;if(s[r]<e[r])return!1}return!0},Ae="https://api.github.com",xs=`${Ae}/graphql`,Ue=`
1
+ "use strict";var bt=Object.defineProperty;var Cs=Object.getOwnPropertyDescriptor;var Ds=Object.getOwnPropertyNames;var As=Object.prototype.hasOwnProperty;var _=(s,t)=>{for(var e in t)bt(s,e,{get:t[e],enumerable:!0})},Ls=(s,t,e,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of Ds(t))!As.call(s,n)&&n!==e&&bt(s,n,{get:()=>t[n],enumerable:!(r=Cs(t,n))||r.enumerable});return s};var Us=s=>Ls(bt({},"__esModule",{value:!0}),s);var qo={};_(qo,{AzureDevOps:()=>ie,AzureDevopsUtils:()=>et,Bitbucket:()=>ae,BitbucketServer:()=>ue,BitbucketServerUtils:()=>Ae,BitbucketUtils:()=>tt,EntityIdentifierProviderType:()=>L,EntityIdentifierUtils:()=>gt,EntityType:()=>$,EntityVersion:()=>U,GitBuildStatusStage:()=>Rr,GitBuildStatusState:()=>fe,GitDiffLineType:()=>Pt,GitHub:()=>le,GitHubIssueCloseReason:()=>ws,GitHubUtils:()=>ht,GitIssueState:()=>Le,GitLab:()=>de,GitLabUtils:()=>ft,GitMergeStrategy:()=>oe,GitProviderUtils:()=>mt,GitPullRequestMergeableState:()=>W,GitPullRequestReviewState:()=>B,GitPullRequestState:()=>ee,GraphQLErrors:()=>h,Jira:()=>ce,JiraServer:()=>ge,JiraUtils:()=>It,Linear:()=>me,PullRequestAsyncStatus:()=>Ps,Trello:()=>he,TrelloUtils:()=>Rt,Utils:()=>Eo,default:()=>vo,isFetch:()=>qe});module.exports=Us(qo);var qr=require("diff");var Rr=(n=>(n.Build="build",n.Production="production",n.Staging="staging",n.Test="test",n))(Rr||{}),fe=(d=>(d.ActionRequired="ACTION_REQUIRED",d.Cancelled="CANCELLED",d.Error="ERROR",d.Failed="FAILED",d.Pending="PENDING",d.Running="RUNNING",d.Skipped="SKIPPED",d.Success="SUCCESS",d.Warning="WARNING",d.OptionalActionRequired="OPTIONAL_ACTION_REQUIRED",d))(fe||{}),oe=(o=>(o.MergeCommit="MERGE_COMMIT",o.Rebase="REBASE",o.RebaseThenMergeCommit="REBASE_THEN_MERGE_COMMIT",o.FastForward="FAST_FORWARD",o.Squash="SQUASH",o))(oe||{}),ee=(r=>(r.Open="OPEN",r.Closed="CLOSED",r.Merged="MERGED",r))(ee||{}),B=(n=>(n.Approved="APPROVED",n.ChangesRequested="CHANGES_REQUESTED",n.Commented="COMMENTED",n.ReviewRequested="REVIEW_REQUESTED",n))(B||{}),W=(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))(W||{}),Pt=(r=>(r.ADDED="ADDED",r.DELETED="DELETED",r.UNMODIFIED="UNMODIFIED",r))(Pt||{});var yr={APPROVED:0,COMMENTED:1,REVIEW_REQUESTED:2,CHANGES_REQUESTED:3},Q=s=>!s||s.length===0?null:s.reduce((t,e)=>yr[e.state]>yr[t]?e.state:t,"APPROVED"),Ee=(s,t)=>s.name||s.username||s.email||t,te=s=>{let t=Object.values(s).map(e=>e.name).sort((e,r)=>e.localeCompare(r));return Object.values(s).forEach(e=>{e.priority!==-1&&(e.priority=t.indexOf(e.name))}),s};var E=100;var br=globalThis.fetch;var $s=async s=>{let t=s.headers.get("content-type")||"",e=null;if(t.startsWith("application/json")){let o=await s.text();e=o.trim().length>0?JSON.parse(o):null}else if(t.startsWith("text/")||t==="")e=await s.text();else if(t.startsWith("application/vnd.github.raw+json")||t.startsWith("application/octet-stream"))e=await s.arrayBuffer();else throw new Error(`Unsupported content-type: ${t}`);let r={};s.headers.forEach((o,i)=>{r[i]=o});let n={body:e,headers:r,status:s.status,statusText:s.statusText};if(!s.ok){let o=new Error(s.statusText);throw Object.assign(o,{response:n}),o}return n},wt=s=>async({url:t,...e})=>{let r=await s(t,e);return $s(r)};var qe=(s,t=!1)=>s.name==="fetch"||t;var k=class{constructor(t){let e=t?.request||br;this.config={...t,request:qe(e,t?.forceIsFetch)?wt(e):e}}updateConfig(t){this.config={...this.config,...t,request:t.request&&qe(t.request,t?.forceIsFetch??this.config.forceIsFetch)?wt(t.request):this.config.request}}},G=class extends k{};var I=(s,t)=>{let e={};return s&&(e.Authorization=`${t?"Basic":"Bearer"} ${s}`),e},Pr=s=>s?s.reduce((t,e)=>(t[e]=!0,t),{}):void 0,X=(s,t,e)=>!s||t.some(r=>s[r])?e:"",wr=async s=>{let t=[],e=!0,r;for(;e;){let n=await s(r);t=t.concat(n.data),e=!!n?.pageInfo?.hasNextPage,r=n?.pageInfo?.endCursor||n?.pageInfo?.nextPage}return t};async function vt(s){return(await Promise.allSettled(s)).map(e=>Gs(e)).filter(e=>e!=null)}function Gs(s,t=void 0){return s?.status==="fulfilled"?s.value:t}var Ts="https://app.vssps.visualstudio.com/_apis",Os="https://vssps.dev.azure.com/",xs="https://dev.azure.com",b=(s,t={})=>I(t.token||s.token,t.isPAT||s.isPAT),vr=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/"),Et=(s,t)=>{let e=t.baseUrl||s.baseUrl||Ts;return e=e.replace(/\/$/,""),e},w=(s,t)=>{let e=t.baseUrl||s.baseUrl||xs;return e=e.replace(/\/$/,""),e},qt=(s,t)=>{let e=t.baseUrl||s.baseUrl||Os;return e=e.replace(/\/$/,""),e};var ks={active:"OPEN",completed:"MERGED",abandoned:"CLOSED"},Ns={10:"APPROVED",5:"APPROVED",0:"REVIEW_REQUESTED",[-5]:"CHANGES_REQUESTED",[-10]:"CHANGES_REQUESTED"},St=s=>({id:s.id,name:s.displayName??null,username:(s.uniqueName||s.displayName)??null,email:null,avatarUrl:s.imageUrl??null,url:null}),Se=s=>s.startsWith("refs/heads/")?s.replace("refs/heads/",""):s,_s=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"}},Ie=(s,t)=>{let e=[],r=[];return t.reviewers.forEach(n=>{let o={reviewer:St(n),state:Ns[n.vote??0]||"REVIEW_REQUESTED"};n.isRequired&&e.push(o),r.push(o)}),{id:t.pullRequestId.toString(),title:t.title,description:t.description??null,number:t.codeReviewId,state:ks[t.status],isDraft:t.isDraft,commentCount:null,upvoteCount:null,author:St(t.createdBy),createdDate:new Date(t.creationDate),updatedDate:new Date(t.closedDate||t.creationDate),closedDate:t.closedDate?new Date(t.closedDate):null,mergedDate:t.closedDate&&t.status==="completed"?new Date(t.closedDate):null,repository:{id:t.repository.id,name:t.repository.name,project:t.repository.project.name,owner:{login:s},remoteInfo:null},headCommit:{buildStatuses:null},baseRef:{name:Se(t.targetRefName),oid:t.lastMergeTargetCommit.commitId},headRef:{name:Se(t.sourceRefName),oid:t.lastMergeSourceCommit.commitId},url:vr(t),assignees:t.reviewers.map(St),reviews:r,reviewDecision:Q(e),additions:null,deletions:null,fileCount:null,commitCount:null,headRepository:t.forkSource?{id:t.forkSource.repository.id,name:t.forkSource.repository.name,project:void 0,owner:{login:s},remoteInfo:null}:{id:t.repository.id,name:t.repository.name,project:t.repository.project.name,owner:{login:s},remoteInfo:null},mergeableState:_s(t.mergeStatus),labels:t.labels?.map(n=>({color:null,description:null,id:n.id,name:n.name}))??[],permissions:null}},Er=(s,t)=>({id:t.id,name:t.name,namespace:s,project:t.project.name,projectId:t.project.id,webUrl:t.webUrl,httpsUrl:t.remoteUrl,sshUrl:t.sshUrl,defaultBranch:t.defaultBranch?{name:Se(t.defaultBranch)}:null,permissions:null}),Bs=(s,t,e,r)=>{let n=e.fields,o=n["System.AssignedTo"],i=n["System.State"],a=n["System.WorkItemType"],u;return i&&a&&(u=r[a]?.[i]),{id:e.id.toString(),number:e.id.toString(),title:n["System.Title"],commentCount:n["System.CommentCount"],author:{avatarUrl:n["System.CreatedBy"]._links?.avatar?.href??null,email:null,id:n["System.CreatedBy"].id,name:n["System.CreatedBy"].uniqueName??null,username:n["System.CreatedBy"].displayName??null,url:null},closedDate:n["Microsoft.VSTS.Common.ClosedDate"]?new Date(n["Microsoft.VSTS.Common.ClosedDate"]):null,createdDate:new Date(n["System.CreatedDate"]),updatedDate:new Date(n["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:n["System.Description"]??null,state:{name:u?.title||i,color:null},type:n["System.WorkItemType"],repository:null,project:{namespace:s,name:t,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()}))??[]}},ie=class extends G{getRepoApiUrl(t,e,r,n){return`${w(this.config,n)}/${encodeURIComponent(t)}/${encodeURIComponent(e)}/_apis/git/repositories/${encodeURIComponent(r)}`}async getCurrentUser(t={},e={}){if(e.isPAT||this.config.isPAT)throw new Error("Azure DevOps does not support PATs for this function.");let r=`${Et(this.config,e)}/profile/profiles/me`,n=await this.config.request({url:r,headers:b(this.config,e)});return{data:{id:n.body.id,name:n.body.displayName,username:n.body.displayName,email:n.body.emailAddress,avatarUrl:null,url:null}}}async getCurrentUserForInstance(t,e={}){let n=(await this.config.request({url:`${w(this.config,e)}/${encodeURIComponent(t.namespace)}/_apis/ConnectionData`,headers:b(this.config,e)})).body.authorizedUser;if(n.providerDisplayName==="Anonymous")throw new Error("Current user not found.");return{data:{id:n.id,name:n.providerDisplayName,username:n.providerDisplayName,email:n.properties.Account.$value,avatarUrl:null,url:null}}}async getUserForCommit(t,e={}){if(!t.repo.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let n=(await this.config.request({url:`${w(this.config,e)}/${encodeURIComponent(t.repo.namespace)}/${encodeURIComponent(t.repo.project)}/_apis/git/repositories/${encodeURIComponent(t.repo.name)}/commits/${t.oid}`,headers:b(this.config,e)})).body.author;return{data:{name:n.name,email:n.email,avatarUrl:n.imageUrl}}}async getOrgsForUser(t,e={}){let r=`${Et(this.config,e)}/accounts?memberId=${t.userId}&api-version=6.0`;return{data:(await this.config.request({url:r,headers:b(this.config,e)})).body.value.map(o=>({id:o.accountId,name:o.accountName}))}}async getCollectionsForUser(t,e={}){let r=`${w(this.config,e)}/_apis/projectCollections`;return{data:(await this.config.request({url:r,headers:b(this.config,e)})).body.value.map(o=>({id:o.id,name:o.name}))}}async getAzureProjects(t,e={}){let r=new URL(`${w(this.config,e)}/${encodeURIComponent(t.namespace)}/_apis/projects`);r.searchParams.set("$top",E.toString()),t.cursor&&r.searchParams.set("$skip",t.cursor);let n=await this.config.request({url:r.toString(),headers:b(this.config,e)}),o=n.headers["x-ms-continuationtoken"];return{pageInfo:{hasNextPage:!!o,endCursor:o||null},data:n.body.value.map(i=>({id:i.id,name:i.name,namespace:t.namespace}))}}async getAzureProjectScopeDescriptor(t,e={}){let{namespace:r,projectId:n}=t;return{data:{scope:(await this.config.request({url:`${qt(this.config,e)}/${encodeURIComponent(r)}/_apis/graph/descriptors/${n}?api-version=6.0`,headers:b(this.config,e)})).body.value}}}async getAzureGraphAccountsForAzureProject(t,e={}){let{namespace:r,projectScopeDescriptor:n,cursor:o}=t,i=new URL(`${qt(this.config,e)}/${encodeURIComponent(r)}/_apis/graph/users`);n&&i.searchParams.set("scopeDescriptor",n),o&&i.searchParams.set("continuationToken",o);let a=await this.config.request({url:i.toString(),headers:b(this.config,e)}),u=a.headers["x-ms-continuationtoken"];return{pageInfo:{endCursor:u||null,hasNextPage:!!u},data:a.body.value.map(l=>({avatarUrl:l._links?.avatar?.href??null,descriptor:l.descriptor??null,email:l.mailAddress??null,name:l.displayName??null,storageKeyURL:l._links?.storageKey?.href??null,username:l.displayName??null}))}}async getAccountFromAzureGraphAccount(t,e={}){let{azureGraphAccount:r}=t;if(!r.storageKeyURL)throw new Error("Expected 'storageKeyURL' to not be null for 'azureGraphAccount'");let n=await this.config.request({url:r.storageKeyURL,headers:b(this.config,e)});return{data:{avatarUrl:r.avatarUrl,email:r.email,id:n.body.value,name:r.name,username:r.username,url:null}}}async getAccountsFromAzureGraphAccounts(t,e={}){let r=[];for(let n of t.azureGraphAccounts){let o=await this.getAccountFromAzureGraphAccount({azureGraphAccount:n},e);r.push(o.data)}return{data:r}}async getRepo(t,e={}){if(!t.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let r=await this.config.request({url:`${w(this.config,e)}/${encodeURIComponent(t.namespace)}/${encodeURIComponent(t.project)}/_apis/git/repositories/${encodeURIComponent(t.name)}`,headers:b(this.config,e)});return{data:Er(t.namespace,r.body)}}async getRepos(t,e={}){let r=[],n=[];return await Promise.all(t.map(async o=>{try{let i=await this.getRepo(o,e);r.push(i.data)}catch(i){n.push({input:o,error:i})}})),{data:r,errors:n}}async getReposForAzureProject(t,e={}){if(!t.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');return{data:(await this.config.request({url:`${w(this.config,e)}/${encodeURIComponent(t.namespace)}/${encodeURIComponent(t.project)}/_apis/git/repositories`,headers:b(this.config,e)})).body.value.map(n=>Er(t.namespace,n))}}async getRefs(t,e,r={}){if(!e.repo.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let n=new URL(`${w(this.config,r)}/${encodeURIComponent(e.repo.namespace)}/${encodeURIComponent(e.repo.project)}/_apis/git/repositories/${encodeURIComponent(e.repo.name)}/refs`);n.searchParams.set("filter",t),n.searchParams.set("$top",E.toString()),e.cursor&&n.searchParams.set("continuationToken",e.cursor);let o=await this.config.request({url:n.toString(),headers:b(this.config,r)}),i=o.headers["x-ms-continuationtoken"];return{pageInfo:{hasNextPage:!!i,endCursor:i||null},data:o.body.value.map(a=>({name:Se(a.name),commit:{oid:a.objectId,authoredDate:null,committedDate:null}}))}}async getBranches(t,e={}){return this.getRefs("heads",t,e)}async getTags(t,e={}){return this.getRefs("tags",t,e)}async getPullRequestsForRepoBase(t,e={},r=100){let{page:n,repo:o,assigneeLogins:i,authorLogin:a}=t||{},u=n||1;if(!o.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let l="searchCriteria.status=1";return i&&i.length&&(l+=`&searchCriteria.reviewerId=${i[0]}`),a&&(l+=`&searchCriteria.creatorId=${a}`),await this.config.request({url:`${w(this.config,e)}/${encodeURIComponent(o.namespace)}/${encodeURIComponent(o.project||"")}/_apis/git/repositories/${encodeURIComponent(o.name)}/pullRequests?${l}&%24top=${r}&%24skip=${(u-1)*r}`,headers:b(this.config,e)})}async getPullRequestsForRepo(t,e={}){let n=t.page||1,o=await this.getPullRequestsForRepoBase(t,e,100);return{pageInfo:{hasNextPage:o.body.value.length===100,nextPage:n+1},data:o.body.value.map(i=>Ie(t.repo.namespace,i))}}async getPullRequestsForRepos(t,e={}){if(!t.repos.every(o=>o.project))throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let{repos:r}=t||{},n=[];return await Promise.all(r.map(async o=>{try{(await this.getPullRequestsForRepoBase({repo:o,...t},e)).body.value.forEach(a=>{n.push(Ie(o.namespace,a))})}catch(i){if(i.statusCode!==404&&i.statusCode!==401)throw i}})),{data:n}}async getPullRequestsForProjectBase(t,e={},r=100){let{namespace:n,project:o,page:i,assigneeLogins:a,authorLogin:u,repo:l}=t;if(l?.project&&l.project!==o)throw new Error("Could not fetch pull requests, project mismatch");let d=i||1,p=new URL(`${w(this.config,e)}/${encodeURIComponent(n)}/${encodeURIComponent(o)}/_apis/git/pullRequests`);return p.searchParams.set("searchCriteria.status","1"),p.searchParams.set("$top",r.toString()),p.searchParams.set("$skip",((d-1)*r).toString()),l?.id&&l?.project===o&&p.searchParams.set("searchCriteria.repositoryId",l.id),a&&a.length&&p.searchParams.set("searchCriteria.reviewerId",a[0]),u&&p.searchParams.set("searchCriteria.creatorId",u),await this.config.request({url:p.toString(),headers:b(this.config,e)})}async getPullRequestsForProject(t,e={}){let n=t.page||1,o=await this.getPullRequestsForProjectBase(t,e,100);return{pageInfo:{hasNextPage:o?.body.value.length===100,nextPage:n+1},data:o?.body.value.map(i=>Ie(t.namespace,i))||[]}}async getPullRequestsForProjects(t,e={}){let{projects:r}=t||{},n=[];return await Promise.all(r.map(async o=>{try{(!t.repo||t.repo.project&&t.repo.project===o.project)&&(await this.getPullRequestsForProjectBase({...o,...t},e))?.body.value.forEach(a=>{n.push(Ie(o.namespace,a))})}catch(i){if(i.statusCode!==404&&i.statusCode!==401)throw i}})),{data:n}}async getAzurePullRequestLastMergeStatus(t,e={}){if(!t.repo.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let{repo:{namespace:r,project:n,name:o},pullRequestId:i}=t,a=await this.config.request({url:`${w(this.config,e)}/${encodeURIComponent(r)}/${encodeURIComponent(n||"")}/_apis/git/repositories/${o}/pullrequests/${i}?includeCommits=true?api-version=6.0`,headers:{...b(this.config,e)}});if(!a.body.mergeStatus)throw new Error("Could not fetch pull request");return{data:a.body.mergeStatus}}async updatePullRequest(t,e,r){return await this.config.request({method:"PATCH",url:`${w(this.config,r)}/${encodeURIComponent(t.repository.owner.login)}/${encodeURIComponent(t.repository.project)}/_apis/git/repositories/${t.repository.name}/pullrequests/${t.id}?api-version=6.0`,body:e,headers:{...b(this.config,r),"Content-Type":"application/json"}})}async closePullRequest(t,e={}){let{pullRequest:r}=t,n={status:"abandoned"};if(!(await this.updatePullRequest(r,JSON.stringify(n),e)).body.status)throw new Error("Could not close pull request")}async mergePullRequest(t,e={}){let{pullRequest:r,mergeStrategy:n}=t,o;switch(n){case"MERGE_COMMIT":{o="noFastForward";break}case"REBASE":{o="rebase";break}case"REBASE_THEN_MERGE_COMMIT":{o="rebaseMerge";break}case"SQUASH":{o="squash";break}}let i={completionOptions:{mergeStrategy:o},lastMergeSourceCommit:{commitId:r.headRef?.oid},status:"completed"};if(!(await this.updatePullRequest(r,JSON.stringify(i),e)).body.status)throw new Error("Could not merge pull request")}async addPullRequestLabel(t,e={}){let{pullRequest:r,label:n}=t;if(!r.repository.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let o={name:n.name};if(!(await this.config.request({method:"POST",url:`${w(this.config,e)}/${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(o),headers:{...b(this.config,e),"Content-Type":"application/json"}})).body.id)throw new Error("Could not add pull request label")}async removePullRequestLabel(t,e={}){let{pullRequest:r,label:n}=t;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:`${w(this.config,e)}/${encodeURIComponent(r.repository.owner.login)}/${encodeURIComponent(r.repository.project)}/_apis/git/repositories/${r.repository.name}/pullrequests/${r.id}/labels/${encodeURIComponent(n.name)}?api-version=6.0`,headers:{...b(this.config,e)}})}async setPullRequestLabels(t,e={}){let{pullRequest:r,labels:n}=t;if(!r.repository.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let o=r.labels;if(!o)throw new Error('Azure DevOps requires "labels" for this function.');for(let i of n)o.find(a=>a.id===i.id)||await this.addPullRequestLabel({pullRequest:r,label:i},e);for(let i of o)n.find(a=>i.id===a.id)||await this.removePullRequestLabel({pullRequest:r,label:i},e)}async setPullRequestAsDraft(t,e={}){let{pullRequest:r,isDraft:n}=t,o={isDraft:n};if(!(await this.updatePullRequest(r,JSON.stringify(o),e)).body.status)throw new Error("Could not set the pull request as draft")}async addPullRequestReviewer(t,e={}){let{pullRequest:r,reviewer:n,isRequired:o}=t,i={id:n.id,isRequired:o};if(!(await this.config.request({method:"PUT",url:`${w(this.config,e)}/${encodeURIComponent(r.repository.owner.login)}/${encodeURIComponent(r.repository.project)}/_apis/git/repositories/${r.repository.name}/pullrequests/${r.id}/reviewers/${n.id}?api-version=6.0`,body:JSON.stringify(i),headers:{...b(this.config,e),"Content-Type":"application/json"}})).body.id)throw new Error("Could not add pull request reviewer")}async removePullRequestReviewer(t,e={}){let{pullRequest:r,reviewer:n}=t;await this.config.request({method:"DELETE",url:`${w(this.config,e)}/${encodeURIComponent(r.repository.owner.login)}/${encodeURIComponent(r.repository.project)}/_apis/git/repositories/${r.repository.name}/pullrequests/${r.id}/reviewers/${n.id}?api-version=6.0`,headers:{...b(this.config,e),Accept:"application/json"}})}async setPullRequestReviewers(t,e={}){let{pullRequest:r,reviewers:n}=t;for(let o of n)r.assignees.find(i=>i.id===o.id)||await this.addPullRequestReviewer({pullRequest:r,reviewer:o,isRequired:!0},e);for(let o of r.assignees)n.find(i=>o.id===i.id)||await this.removePullRequestReviewer({pullRequest:r,reviewer:o},e)}async getIssuesForAzureProject(t,e={}){let{page:r,assigneeLogins:n,authorLogin:o,mentionLogin:i,labelNames:a,statusByWorkItemIdByStatusId:u}=t||{},l=r||1,d=200,p=["[Microsoft.VSTS.Common.ClosedDate] = ''","[System.TeamProject] = @project","[Microsoft.VSTS.Common.ResolvedDate] = ''"];o&&p.push(`[System.CreatedBy] = '${o.replace("'","''")}'`),n&&n[0]&&p.push(`[System.AssignedTo] = '${n[0].replace("'","''")}'`),i&&p.push("[System.Id] IN (@recentMentions)"),a&&a.forEach(R=>p.push(`[System.Tags] Contains '${R}'`));let c=`Select [Microsoft.VSTS.Common.ClosedDate], [Microsoft.VSTS.Common.ResolvedDate] From WorkItems Where ${p.join(" AND ")} order by [System.CreatedDate] desc`,g=await this.config.request({url:`${w(this.config,e)}/${encodeURIComponent(t.namespace)}/${encodeURIComponent(t.project)}/_apis/wit/wiql?api-version=6.0`,body:JSON.stringify({query:c}),method:"POST",headers:{...b(this.config,e),"Content-Type":"application/json"}}),m=g.body.workItems.slice((l-1)*d,d*l).map(R=>R.id);if(m.length==0)return{pageInfo:{hasNextPage:!1,nextPage:null},data:[]};let y=await this.config.request({url:`${w(this.config,e)}/${encodeURIComponent(t.namespace)}/${encodeURIComponent(t.project)}/_apis/wit/workitemsbatch?api-version=6.0`,body:JSON.stringify({ids:m,$expand:"Links"}),method:"POST",headers:{...b(this.config,e),"Content-Type":"application/json"}});return{pageInfo:{hasNextPage:g.body.workItems.length>d*l,nextPage:l+1},data:y.body.value.map(R=>Bs(t.namespace,t.project,R,u||{}))}}async getPermissionsForRepos(t,e={}){let{namespace:r,repos:n}=t,o={4:["canPush","canCreateWebhook"],1024:["isAdmin"],2048:["isAdmin"],4096:["isAdmin"],8192:["isAdmin"]},i=d=>{let p="2e9eb7ed-3c0a-47d4-87c1-0ffdd275fd87",c=`repoV2/${d.projectId}/${d.id}`;return Object.keys(o).map(g=>({securityNamespaceId:p,token:c,permissions:g}))},a={alwaysAllowAdministrators:!1,evaluations:n.flatMap(i)};return{data:(await this.config.request({method:"POST",url:`${w(this.config,e)}/${encodeURIComponent(r)}/_apis/security/permissionevaluationbatch?api-version=7.0`,body:JSON.stringify(a),headers:{...b(this.config,e),"Content-Type":"application/json"}})).body.evaluations.reduce((d,p)=>{let[,c,g]=p.token.split("/"),m=`${c}/${g}`,y=o[p.permissions];for(let R of y)d[m]===void 0&&(d[m]={canCreateWebhook:!0,canPush:!0,isAdmin:!0}),p.value===!1&&(d[m][R]=!1);return d},{})}}async decorateReposWithPermissions(t,e={}){let{namespace:r,repos:n}=t,o=await this.getPermissionsForRepos({namespace:r,repos:n},e);return{data:n.map(i=>({...i,permissions:o.data[`${i.projectId}/${i.id}`]}))}}async updateIssue(t,e,r={}){return await this.config.request({method:"PATCH",url:`${w(this.config,r)}/${encodeURIComponent(t.project.namespace)}/${encodeURIComponent(t.project.name)}/_apis/wit/workitems/${t.id}?api-version=6.0`,body:JSON.stringify(e),headers:{...b(this.config,r),"Content-Type":"application/json-patch+json"}})}async setIssueStatus(t,e={}){let{issue:r,status:n}=t,o=[{op:"add",path:"/fields/System.State",value:n.name}];if(!(await this.updateIssue(r,o,e)).body.fields?.["System.State"])throw new Error("Could not set issue status")}async setIssueAssignee(t,e={}){let{issue:r,assignee:n}=t,o=[{op:"add",path:"/fields/System.AssignedTo",value:n?.name??""}];if(!(await this.updateIssue(r,o,e)).body.fields?.["System.State"])throw new Error("Could not set issue assignee")}async setIssueLabels(t,e={}){let{issue:r,labels:n}=t,i=[{op:"replace",path:"/fields/System.Tags",value:n.map(u=>u.name).join(";")}];if(!(await this.updateIssue(r,i,e)).body.fields?.["System.Tags"])throw new Error("Could not set issue tags")}async getIssueTypesForAzureProject(t,e={}){if(!t.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let{namespace:r,project:n}=t;return{data:(await this.config.request({url:`${w(this.config,e)}/${encodeURIComponent(r)}/${encodeURIComponent(n||"")}/_apis/wit/workitemtypes?api-version=6.0`,headers:{...b(this.config,e)}})).body.value}}async getLabelsForProject(t,e={}){let{namespace:r,project:n}=t;return{data:(await this.config.request({url:`${w(this.config,e)}/${encodeURIComponent(r)}/${encodeURIComponent(n||"")}/_apis/wit/tags?api-version=6.0`,headers:{...b(this.config,e)}})).body.value.map(i=>({color:null,description:null,id:i.id,name:i.name,url:i.url}))}}async getPullRequestForRepo(t,e={}){let{repo:r,number:n}=t;if(!r.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let o=await this.config.request({url:`${this.getRepoApiUrl(r.namespace,r.project,r.name,e)}/pullrequests/${n}?api-version=7.1`,headers:b(this.config,e)});return{data:Ie(r.namespace,o.body)}}async getMergeBase(t,e={}){if(!t.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(t.repo.namespace,t.repo.project,t.repo.name,e)}/commits/${encodeURIComponent(t.base)}/mergebases?otherCommitId=${encodeURIComponent(t.head)}&api-version=7.1`,headers:b(this.config,e)});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(t,e={}){if(!t.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(t.repo.namespace,t.repo.project,t.repo.name,e)}/items?path=${encodeURIComponent(t.path)}&versionDescriptor[version]=${encodeURIComponent(t.ref)}&versionDescriptor[versionType]=commit&api-version=7.1`,headers:{...b(this.config,e),Accept:"application/octet-stream"}});return{data:new Blob([r.body])}}async getPullRequestDiff(t,e={}){if(!t.repo.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let r=this.getRepoApiUrl(t.repo.namespace,t.repo.project,t.repo.name,e),n=b(this.config,e),o={...n,Accept:"application/octet-stream"},[i,a]=await Promise.all([this.config.request({url:`${r}/pullrequests/${t.pullRequestId}?api-version=7.1`,headers:n}),this.config.request({url:`${r}/pullrequests/${t.pullRequestId}/iterations?api-version=7.1`,headers:n})]),u=i.body.lastMergeTargetCommit.commitId,l=i.body.lastMergeSourceCommit.commitId,d=a.body.value;if(d.length===0)return"";let p=d[d.length-1],g=(await this.config.request({url:`${r}/pullrequests/${t.pullRequestId}/iterations/${p.id}/changes?api-version=7.1`,headers:n})).body.changeEntries;if(g.length===0)return"";let m=5,y=[],R=new TextDecoder,D=q=>q instanceof ArrayBuffer?R.decode(q):typeof q=="string"?q:"",x=async(q,z)=>{try{let yt=await this.config.request({url:`${r}/items?path=${encodeURIComponent(q)}&versionDescriptor[version]=${encodeURIComponent(z)}&versionDescriptor[versionType]=commit&includeContent=true&api-version=7.1`,headers:o});return D(yt.body)}catch{return""}},ve=1,se=8,v=16;for(let q=0;q<g.length;q+=m){let z=g.slice(q,q+m),yt=await Promise.all(z.map(async ne=>{let hr=ne.item.path,vs=(ne.changeType&ve)!==0,Es=(ne.changeType&se)!==0,fr=(ne.changeType&v)!==0&&ne.item.originalPath?ne.item.originalPath:hr,Ir=hr,[qs,Ss]=await Promise.all([vs?Promise.resolve(""):x(fr,u),Es?Promise.resolve(""):x(Ir,l)]);return(0,qr.createTwoFilesPatch)(`a${fr}`,`b${Ir}`,qs,Ss)}));y.push(...yt)}return y.join(`
2
+ `)}};var S=(s,t={})=>I(t.token||s.token,t.isPAT||s.isPAT);var C="https://api.bitbucket.org/2.0",Qs={OPEN:"OPEN",MERGED:"MERGED",DECLINED:"CLOSED"},Ce={owner:4,admin:3,contributor:2,member:1},De=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}),Sr=s=>{let t=s.links.clone,e=t?.find(n=>n.name==="ssh"),r=t?.find(n=>n.name==="https");return e&&r?{cloneUrlHTTPS:r.href,cloneUrlSSH:e.href}:null},Ct=s=>({id:s.uuid,namespace:s.workspace.slug,name:s.slug,webUrl:s.links.html.href,httpsUrl:s.links.clone.find(t=>t.name==="https")?.href??null,sshUrl:s.links.clone.find(t=>t.name==="ssh")?.href??null,defaultBranch:{name:s.mainbranch.name},permissions:null}),Dt=s=>{let t=s.id,e=s.participants?.map(r=>{let n="REVIEW_REQUESTED";return r.approved?n="APPROVED":r.state==="changes_requested"?n="CHANGES_REQUESTED":r.participated_on!==null&&(n="COMMENTED"),{reviewer:De(r.user),state:n}})??[];return{id:t.toString(),title:s.title,description:s.description,number:t,state:Qs[s.state],isDraft:!1,commentCount:s.comment_count,upvoteCount:null,author:De(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:Sr(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:Q(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:Sr(s.source.repository)},mergeableState:"MERGEABLE",permissions:null}},js=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}}},Fs=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}}},ae=class extends k{async refreshToken(t){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 ${t.base64ClientIDColonClientSecret}`},body:`grant_type=refresh_token&refresh_token=${t.refreshToken}`})).body}}async getCurrentUser(t={},e={}){let r=await this.config.request({url:`${C}/user`,headers:S(this.config,e)});return{data:De(r.body)}}async getUserForCommit(t,e={}){let n=(await this.config.request({url:`${C}/repositories/${t.repo.namespace}/${t.repo.name}/commit/${t.oid}`,headers:S(this.config,e)})).body.author,o=n.raw.match(/([^<]+)<(.+)>/);return{data:{name:o?o[1].trim():null,email:o?o[2]:null,avatarUrl:n.user?.links.avatar.href||null}}}async getRepo(t,e={}){let r=await this.config.request({url:`${C}/repositories/${t.namespace}/${t.name}`,headers:S(this.config,e)});return{data:Ct(r.body)}}async getRepos(t,e={}){let r=[],n=[];return await Promise.all(t.map(async o=>{try{let i=await this.getRepo(o,e);r.push(i.data)}catch(i){n.push({input:o,error:i})}})),{data:r,errors:n}}async getReposForWorkspace(t,e={}){let r=new URL(`${C}/repositories/${encodeURIComponent(t.workspace)}`);r.searchParams.set("page",t.page?.toString()||"1"),r.searchParams.set("pagelen",E.toString()),t.minimumRole&&r.searchParams.set("role",t.minimumRole);let n=await this.config.request({url:r.toString(),headers:S(this.config,e)}),o=!!n.body.next;return{pageInfo:{hasNextPage:o,nextPage:o?n.body.page+1:null},data:n.body.values.map(Ct)}}async getAllReposForWorkspace(t,e={}){let r=[],n=1;for(;n!==null;){let o=await this.getReposForWorkspace({workspace:t.workspace,minimumRole:t.minimumRole,page:n},e);r.push(...o.data),n=o.pageInfo.hasNextPage?o.pageInfo.nextPage:null}return r}async getAllReposForWorkspaceWithPermissions(t,e={}){let r=new Map,n=[],o=Ce[t.minimumRole||"member"];o<=Ce.admin&&n.push("admin"),o<=Ce.contributor&&n.push("contributor"),o<=Ce.member&&n.push("member");let i=[];for(let a of n){i=await this.getAllReposForWorkspace({workspace:t.workspace,minimumRole:a},e);for(let u of i)r.has(u.id)||r.set(u.id,a)}return{data:i.map(a=>{let u=r.get(a.id)||"member";return{...a,permissions:Fs(u)}})}}async getReposForCurrentUser(t,e={}){let r=new URL(`${C}/repositories`);r.searchParams.set("role","member"),r.searchParams.set("pagelen",E.toString()),t.cursor&&r.searchParams.set("after",t.cursor);let n=await this.config.request({url:r.toString(),headers:S(this.config,e)}),o=!!n.body.next,i=null;return n.body.next&&(i=new URL(n.body.next).searchParams.get("after")),{pageInfo:{hasNextPage:o,endCursor:i},data:n.body.values.map(Ct)}}async getBranches(t,e={}){let r=new URL(`${C}/repositories/${t.repo.namespace}/${t.repo.name}/refs/branches`);r.searchParams.set("page",t.page?.toString()||"1"),r.searchParams.set("pagelen",E.toString());let n=await this.config.request({url:r.toString(),headers:S(this.config,e)}),o=!!n.body.next;return{pageInfo:{hasNextPage:o,nextPage:o?n.body.page+1:null},data:n.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(t,e={}){let r=new URL(`${C}/repositories/${t.repo.namespace}/${t.repo.name}/refs/tags`);r.searchParams.set("pagelen",E.toString()),t.cursor&&r.searchParams.set("page",t.cursor);let n=await this.config.request({url:r.toString(),headers:S(this.config,e)}),o=!!n.body.next,i=null;return n.body.next&&(i=new URL(n.body.next).searchParams.get("page")),{pageInfo:{hasNextPage:o,endCursor:i},data:n.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(t={},e={}){let r=new URL(`${C}/user/workspaces`);r.searchParams.set("page",t?.page?.toString()||"1"),r.searchParams.set("pagelen","50"),t?.administrator!==void 0&&r.searchParams.set("administrator",t.administrator.toString());let n=await this.config.request({url:r.toString(),headers:S(this.config,e)}),o=!!n.body.next;return{pageInfo:{hasNextPage:o,nextPage:o?n.body.page+1:null},data:n.body.values.map(i=>({id:i.workspace.uuid,slug:i.workspace.slug}))}}async getWorkspacesForUser(t,e={}){let r=new URL(`${C}/user/permissions/workspaces`);r.searchParams.set("page",t.page?.toString()||"1"),r.searchParams.set("pagelen","50");let n=await this.config.request({url:r.toString(),headers:S(this.config,e)}),o=!!n.body.next;return{pageInfo:{hasNextPage:o,nextPage:o?n.body.page+1:null},data:n.body.values.map(i=>({id:i.workspace.uuid,slug:i.workspace.slug,name:i.workspace.name}))}}async getPullRequestsForUserAndWorkspace(t,e={}){let r=new URL(`${C}/workspaces/${t.workspaceSlug}/pullrequests/${t.userId}`);if(r.searchParams.set("fields","+values.participants,+values.destination.repository.links.clone.*,+values.source.repository.links.clone.*"),r.searchParams.set("page",t.page?.toString()||"1"),r.searchParams.set("pagelen","50"),t.repos&&t.repos.length>0){let i=`state = "open" AND (${t.repos.map(a=>`source.repository.full_name = "${a.namespace}/${a.name}"`).join(" OR ")})`;r.searchParams.set("q",i)}let n=await this.config.request({url:r.toString(),headers:S(this.config,e)}),o=!!n.body.next;return{pageInfo:{hasNextPage:o,nextPage:o?n.body.page+1:null},data:n.body.values.map(Dt)}}async getPullRequestsForRepoBase(t,e={}){let r=new URL(`${C}/repositories/${encodeURI(t.repo.namespace)}/${encodeURI(t.repo.name)}/pullrequests?state=OPEN`),n=[];t.reviewerId&&n.push(`reviewers.uuid="${t.reviewerId}"`),t.authorLogin&&n.push(`author.uuid="${t.authorLogin}"`);let o='state="OPEN"';return n.length&&(o+=` AND (${n.join(t.useOrFilter?" OR ":" AND ")})`),r.searchParams.set("fields","+values.participants,+values.destination.repository.links.clone.*,+values.source.repository.links.clone.*"),r.searchParams.set("page",t.page?.toString()||"1"),r.searchParams.set("pagelen","50"),r.searchParams.set("q",o),await this.config.request({url:r.toString(),headers:S(this.config,e)})}async getPullRequestsForRepo(t,e={}){let r=[],n=await this.getPullRequestsForRepoBase(t,e);n.body.values.forEach(i=>{r.push(Dt(i))});let o=!!n.body.next;return{pageInfo:{hasNextPage:o,nextPage:o?n.body.page+1:null},data:r}}async getPullRequestsForRepos(t,e={}){let r=[];return await Promise.all(t.repos.map(async n=>{try{(await this.getPullRequestsForRepoBase({repo:n,...t},e)).body.values.forEach(i=>{r.push(Dt(i))})}catch(o){if(o.statusCode!==404&&o.statusCode!==401)throw o}})),{data:r}}async getAccountsForWorkspace(t,e={}){let r=new URL(`${C}/workspaces/${encodeURI(t.workspace)}/members`);r.searchParams.set("page",t.page?.toString()||"1"),r.searchParams.set("pagelen","100");let n=await this.config.request({url:r.toString(),headers:S(this.config,e)}),o=!!n.body.next;return{pageInfo:{hasNextPage:o,nextPage:o?n.body.page+1:null},data:n.body.values.map(i=>De(i.user))}}async getReposPermissionsForCurrentUser(t,e={}){let r=new URL(`${C}/user/permissions/repositories`);r.searchParams.set("page",t.page?.toString()||"1"),r.searchParams.set("pagelen","100");let n=await this.config.request({url:r.toString(),headers:S(this.config,e)}),o=!!n.body.next;return{pageInfo:{hasNextPage:o,nextPage:o?n.body.page+1:null},data:n.body.values.reduce((i,a)=>({...i,[a.repository.uuid]:js(a.permission)}),{})}}async decorateReposWithPermissions(t,e={}){let r={},n=1;do{let o=await this.getReposPermissionsForCurrentUser({page:n},e);r={...o.data,...r},n=o.pageInfo.hasNextPage?o.pageInfo.nextPage:null}while(n!==null);return{data:t.repos.map(o=>({...o,permissions:r[o.id]??{canCreateWebhook:!1,canPush:!1,isAdmin:!1}}))}}async closePullRequest(t,e={}){let{pullRequest:r}=t;if(!(await this.config.request({method:"POST",url:`${C}/repositories/${r.repository.owner.login}/${r.repository.name}/pullrequests/${r.id}/decline`,headers:S(this.config,e)})).body.title)throw new Error("Could not close pull request")}async mergePullRequest(t,e={}){let{pullRequest:r,mergeStrategy:n}=t,o;switch(n){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:`${C}/repositories/${r.repository.owner.login}/${r.repository.name}/pullrequests/${r.id}/merge`,body:JSON.stringify(i),headers:{...S(this.config,e),"Content-Type":"application/json"}})).body.title)throw new Error("Could not merge pull request")}async setPullRequestReviewers(t,e={}){let{pullRequest:r,reviewers:n}=t,o={reviewers:n.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:`${C}/repositories/${r.repository.owner.login}/${r.repository.name}/pullrequests/${r.id}`,body:JSON.stringify(o),headers:{...S(this.config,e),"Content-Type":"application/json"}})).body.title)throw new Error("Could not set pull request reviewers")}};var Ae={};_(Ae,{normalizePermissions:()=>At,restApiPullRequestToCommonPullRequest:()=>Ms});var Ms=s=>Re(s),At=s=>s?s.find(t=>t.permission==="USER_ADMIN"||t.permission==="PROJECT_ADMIN"||t.permission==="ADMIN"||t.permission==="SYS_ADMIN"||t.permission==="REPO_ADMIN")?{canCreateWebhook:!0,canPush:!0,isAdmin:!0}:s.find(t=>t.permission==="REPO_WRITE"||t.permission==="REPO_CREATE"||t.permission==="PROJECT_CREATE"||t.permission==="PROJECT_WRITE")?{canCreateWebhook:!1,canPush:!0,isAdmin:!1}:{canCreateWebhook:!1,canPush:!1,isAdmin:!1}:{canCreateWebhook:!1,canPush:!1,isAdmin:!1};var ye=s=>{let t=s.links.self[0].href;return{name:s.displayName,email:s.emailAddress,avatarUrl:s.avatarUrl??(t&&`${t}/avatar.png`),id:s.id.toString(),username:s.name,url:t}},Re=s=>{let t={OPEN:"OPEN",MERGED:"MERGED",DECLINED:"CLOSED"},e={UNAPPROVED:"REVIEW_REQUESTED",NEEDS_WORK:"CHANGES_REQUESTED",APPROVED:"APPROVED"},r=s.reviewers.map(u=>({reviewer:ye(u.user),state:e[u.status]})),n=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:t[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:ye(s.author.user),assignees:null,reviews:r,reviewDecision:Q(r),repository:{id:s.toRef.repository.id.toString(),name:s.toRef.repository.name,owner:{login:s.toRef.repository.project.key},remoteInfo:o&&n?{cloneUrlHTTPS:o,cloneUrlSSH:n}: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}},Cr=s=>({id:s.id.toString(),namespace:s.project.key,name:s.slug,webUrl:s.links.self[0]?.href??null,httpsUrl:s.links.clone.find(t=>t.name==="https"||t.name==="http")?.href??null,sshUrl:s.links.clone.find(t=>t.name==="ssh")?.href??null,defaultBranch:null,permissions:null}),ue=class extends G{getBaseUrl(t){let e=t.baseUrl||this.config.baseUrl;if(!e)throw new Error('Bitbucket Server requires "baseUrl"');return e}getRequestHeaders(t){return I(t.token||this.config.token)}async getCurrentUser(t={},e={}){let r=await this.config.request({url:`${this.getBaseUrl(e)}/users?limit=2`,headers:this.getRequestHeaders(e)}),{headers:{"x-auserid":n,"x-ausername":o}}=r,i=n?parseInt(n,10):null,a=decodeURIComponent(o),l=(await this.config.request({url:`${this.getBaseUrl(e)}/users?filter=${o}&avatarSize=64`,headers:this.getRequestHeaders(e)})).body.values.find(({emailAddress:d,id:p,name:c,slug:g})=>i?i===p:a===c||a===d||a===g);if(!l)throw new Error("Could not find current Bitbucket Server user");return{data:ye(l)}}async getUserForCommit(t,e){let{repo:r,oid:n}=t,o=await this.config.request({url:`${this.getBaseUrl(e)}/projects/${r.namespace}/repos/${r.name}/commits/${n}`,headers:this.getRequestHeaders(e)});if(!o.body.author)throw new Error("Could not find user for commit");return{data:ye(o.body.author)}}async getRepo(t,e={}){let r=await this.config.request({url:`${this.getBaseUrl(e)}/projects/${t.namespace}/repos/${t.name}`,headers:this.getRequestHeaders(e)});return{data:Cr(r.body)}}async getRepos(t,e={}){let r=[],n=[];return await Promise.all(t.map(async o=>{try{let i=await this.getRepo(o,e);r.push(i.data)}catch(i){n.push({input:o,error:i})}})),{data:r,errors:n}}async getReposForCurrentUser(t,e={}){let r=t.page??0,n=await this.config.request({url:`${this.getBaseUrl(e)}/repos?start=${r}`,headers:this.getRequestHeaders(e)});return{pageInfo:{hasNextPage:!n.body.isLastPage,nextPage:n.body.nextPageStart},data:n.body.values.map(Cr)}}async getRepoPermissionsForUsername(t,e={}){let r=new URL(`${this.getBaseUrl(e)}/projects/${t.repo.namespace}/repos/${t.repo.name}/permissions/search?filterText=${t.username}`);try{let n=await this.config.request({url:r.toString(),headers:this.getRequestHeaders(e)});return{data:At(n.body.values)}}catch(n){if(n.response?.status===401)return{data:{canCreateWebhook:!1,canPush:!1,isAdmin:!1}};throw n}}async decorateReposWithPermissions(t,e={}){return await Promise.all(t.repos.map(async n=>{let o=await this.getRepoPermissionsForUsername({repo:n,username:t.username},e);return{...n,permissions:o.data}}))}async getPullRequestsForRepoBase(t,e={}){let r=new URL(`${this.getBaseUrl(e)}/projects/${encodeURI(t.repo.namespace)}/repos/${encodeURI(t.repo.name)}/pull-requests?state=OPEN`);return r.searchParams.set("start",t.page?.toString()||"0"),r.searchParams.set("limit","50"),await this.config.request({url:r.toString(),headers:this.getRequestHeaders(e)})}async getPullRequestsForRepo(t,e={}){let r=[],n=await this.getPullRequestsForRepoBase(t,e);n.body.values.forEach(i=>{if(t.authorLogin&&i.author.user.name!==t.authorLogin)return null;r.push(Re(i))});let o=n.body.values.length!==0;return{pageInfo:{hasNextPage:o,nextPage:o?n.body.start+n.body.values.length:null},data:r}}async getPullRequestsForRepos(t,e={}){let r=[];return await Promise.all(t.repos.map(async n=>{try{(await this.getPullRequestsForRepoBase({repo:n,...t},e)).body.values.forEach(i=>{if(t.authorLogin&&i.author.user.name!==t.authorLogin)return null;r.push(Re(i))})}catch(o){if(o.statusCode!==404&&o.statusCode!==401)throw o}})),{data:r}}async getPullRequestsForCurrentUser(t,e={}){let r=new URL(`${this.getBaseUrl(e)}/dashboard/pull-requests`);r.searchParams.set("state","OPEN"),r.searchParams.set("start",t.page?.toString()||"0"),r.searchParams.set("limit","50");let n=await this.config.request({url:r.toString(),headers:this.getRequestHeaders(e)}),o=n.body.values.length!==0;return{pageInfo:{hasNextPage:o,nextPage:o?n.body.start+n.body.values.length:null},data:n.body.values.map(Re)}}async closePullRequest(t,e={}){let{pullRequest:r}=t;if(r.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/${r.repository.owner.login}/repos/${r.repository.name}/pull-requests/${r.id}/decline`,body:JSON.stringify({version:r.version}),headers:{...this.getRequestHeaders(e),"Content-Type":"application/json"}})).body.title)throw new Error("Could not close pull request")}async mergePullRequest(t,e={}){let{pullRequest:r,mergeStrategyId:n}=t;if(t.mergeStrategy)throw new Error('Bitbucket Server uses "mergeStrategyId" instead of "mergeStrategy".');if(r.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/${r.repository.owner.login}/repos/${r.repository.name}/pull-requests/${r.id}/merge`,body:JSON.stringify({strategyId:n,version:r.version}),headers:{...this.getRequestHeaders(e),"Content-Type":"application/json"}})).body.title)throw new Error("Could not merge pull request")}async getMergeStrategies(t={}){let e=await this.config.request({url:`${this.getBaseUrl(t)}/admin/pull-requests/git`,headers:{...this.getRequestHeaders(t),"Content-Type":"application/json"}});return{data:{defaultStrategy:e.body.mergeConfig.defaultStrategy,strategies:e.body.mergeConfig.strategies}}}async setPullRequestReviewers(t,e={}){let{pullRequest:r,reviewers:n}=t;if(r.version===void 0)throw new Error('Bitbucket Server requires "version" for this function.');let o={reviewers:n.map(a=>{if(a.username)throw new Error('Bitbucket Server reviewer requires "username" for this function.');return{user:{name:a.username}}}),version:r.version};if(!(await this.config.request({method:"PUT",url:`${this.getBaseUrl(e)}/projects/${r.repository.owner.login}/repos/${r.repository.name}/pull-requests/${r.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(t,e={}){let r=new URL(`${this.getBaseUrl(e)}/projects/${encodeURI(t.project)}/permissions/users`);r.searchParams.set("start",t.page?.toString()||"0"),r.searchParams.set("limit","50");let n=await this.config.request({url:r.toString(),headers:this.getRequestHeaders(e)}),o=n.body.values.length!==0;return{pageInfo:{hasNextPage:o,nextPage:o?n.body.start+n.body.values.length:null},data:n.body.values.map(i=>ye(i.user))}}};var jr=require("js-base64");var Le=(e=>(e.Open="OPEN",e.Closed="CLOSED",e))(Le||{});var h=class extends Error{constructor(e,r){let n=r?.map(i=>`'${i.message}'`).join(", "),o=n?`${e}: ${n}`:e;super(o);this.graphQLErrors=r??[]}};var zs={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]},Dr=15,Ar=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"},A=s=>!!s,j=(s,t)=>{let e=zs[t];for(let r=0;r<3;r++){if(s[r]>e[r])return!0;if(s[r]<e[r])return!1}return!0},$e="https://api.github.com",Ws=`${$e}/graphql`,Ge=`
2
3
  description
3
4
  dueOn
4
5
  id
@@ -6,7 +7,7 @@ number
6
7
  state
7
8
  title
8
9
  url
9
- `,ks=`
10
+ `,Hs=`
10
11
  ... on CheckRun {
11
12
  completedAt
12
13
  conclusion
@@ -15,21 +16,21 @@ url
15
16
  permalink
16
17
  startedAt
17
18
  }
18
- `,Le=/\/api\/v\d+$/,$e=`
19
+ `,Ue=/\/api\/v\d+$/,Te=`
19
20
  color
20
21
  description
21
22
  id
22
23
  name
23
- `,Er=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.")},Ns=(s,t)=>{let e=t.baseUrl||s.baseUrl;return e?(e=e.replace(/\/$/,""),Er(e),Le.test(e)&&(e=e.replace(Le,"")),`${e}/api/graphql`):xs},ee=(s,t)=>{let e=t.baseUrl||s.baseUrl;return e?(e=e.replace(/\/$/,""),Er(e),Le.test(e)&&(e=e.replace(Le,"")),`${e}/api/v3`):Ae},f=(s,t,e)=>{let r=I(e.token||s.token);return r["X-Github-Next-Global-ID"]="1",r["Content-Type"]="application/json",r.Accept="application/vnd.github.merge-info-preview+json",s.request({url:Ns(s,e),method:"POST",headers:r,body:JSON.stringify(t)})},_s={user:!0,"user:email":!0,"read:user":!0},M=s=>s.some(t=>_s[t]),T=(s=!1,t=!1,e)=>`
24
+ `,Lr=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.")},Vs=(s,t)=>{let e=t.baseUrl||s.baseUrl;return e?(e=e.replace(/\/$/,""),Lr(e),Ue.test(e)&&(e=e.replace(Ue,"")),`${e}/api/graphql`):Ws},re=(s,t)=>{let e=t.baseUrl||s.baseUrl;return e?(e=e.replace(/\/$/,""),Lr(e),Ue.test(e)&&(e=e.replace(Ue,"")),`${e}/api/v3`):$e},f=(s,t,e)=>{let r=I(e.token||s.token);return r["X-Github-Next-Global-ID"]="1",r["Content-Type"]="application/json",r.Accept="application/vnd.github.merge-info-preview+json",s.request({url:Vs(s,e),method:"POST",headers:r,body:JSON.stringify(t)})},Js={user:!0,"user:email":!0,"read:user":!0},H=s=>s.some(t=>Js[t]),T=(s=!1,t=!1,e)=>`
24
25
  __typename
25
- ${J(e,["graphQLId"],"id")}
26
- ${J(e,["id"],"databaseId")}
27
- ${J(e,["name"],"name")}
28
- ${J(e,["name","username"],"login")}
29
- ${t?J(e,["email"],"email"):""}
30
- ${J(e,["avatarUrl"],`avatarUrl${s?"(size: $avatarSize)":""}`)}
31
- ${J(e,["url"],"url")}
32
- `,Bs=(s=!1)=>`
26
+ ${X(e,["graphQLId"],"id")}
27
+ ${X(e,["id"],"databaseId")}
28
+ ${X(e,["name"],"name")}
29
+ ${X(e,["name","username"],"login")}
30
+ ${t?X(e,["email"],"email"):""}
31
+ ${X(e,["avatarUrl"],`avatarUrl${s?"(size: $avatarSize)":""}`)}
32
+ ${X(e,["url"],"url")}
33
+ `,Ks=(s=!1)=>`
33
34
  latestReviews(first: 100) {
34
35
  nodes {
35
36
  author {
@@ -37,28 +38,28 @@ latestReviews(first: 100) {
37
38
  ${T(!1,s)}
38
39
  }
39
40
  ... on EnterpriseUserAccount {
40
- ${Ct(!1)}
41
+ ${Lt(!1)}
41
42
  }
42
43
  }
43
44
  state
44
45
  }
45
46
  }
46
- `,qr=(s=!1)=>`
47
+ `,Ur=(s=!1)=>`
47
48
  __typename
48
49
  id
49
50
  databaseId
50
51
  login
51
52
  avatarUrl${s?"(size: $avatarSize)":""}
52
53
  url
53
- `,Ct=(s=!1)=>`
54
+ `,Lt=(s=!1)=>`
54
55
  __typename
55
56
  id
56
57
  login
57
58
  avatarUrl${s?"(size: $avatarSize)":""}
58
59
  url
59
- `,Te=(s,t=!1,e)=>`
60
+ `,Oe=(s,t=!1,e)=>`
60
61
  id
61
- ${!e||B(e,"PR_FULL_DATABASE_ID")?"fullDatabaseId":"databaseId"}
62
+ ${!e||j(e,"PR_FULL_DATABASE_ID")?"fullDatabaseId":"databaseId"}
62
63
  number
63
64
  title
64
65
  body
@@ -68,10 +69,10 @@ author {
68
69
  ${T(!1,t)}
69
70
  }
70
71
  ... on Bot {
71
- ${qr(!1)}
72
+ ${Ur(!1)}
72
73
  }
73
74
  ... on EnterpriseUserAccount {
74
- ${Ct(!1)}
75
+ ${Lt(!1)}
75
76
  }
76
77
  }
77
78
  commits(last: 1) {
@@ -84,7 +85,7 @@ commits(last: 1) {
84
85
  contexts(first: 100) {
85
86
  totalCount
86
87
  nodes {
87
- ${!e||B(e,"CHECK_RUN")?ks:""}
88
+ ${!e||j(e,"CHECK_RUN")?Hs:""}
88
89
  ... on StatusContext {
89
90
  context
90
91
  createdAt
@@ -151,7 +152,7 @@ assignees(first: 100) {
151
152
  }
152
153
  reviewRequests(first: 100) {
153
154
  nodes {
154
- ${!e||B(e,"AS_CODE_OWNER")?"asCodeOwner":""}
155
+ ${!e||j(e,"AS_CODE_OWNER")?"asCodeOwner":""}
155
156
  requestedReviewer {
156
157
  ... on User {
157
158
  ${T(!1,t)}
@@ -159,34 +160,34 @@ reviewRequests(first: 100) {
159
160
  }
160
161
  }
161
162
  }
162
- ${!e||B(e,"LATEST_REVIEWS")?Bs(t):""}
163
+ ${!e||j(e,"LATEST_REVIEWS")?Ks(t):""}
163
164
  additions
164
165
  deletions
165
166
  changedFiles
166
167
  mergeable
167
168
  mergeStateStatus
168
169
  milestone {
169
- ${Ue}
170
+ ${Ge}
170
171
  }
171
172
  labels(first: 100) {
172
173
  nodes {
173
- ${$e}
174
+ ${Te}
174
175
  }
175
176
  }
176
- ${!e||B(e,"VIEWER_CAN_MERGE_AS_ADMIN")?"viewerCanMergeAsAdmin":""}
177
- `,Qs=(s=!1,t)=>`
177
+ ${!e||j(e,"VIEWER_CAN_MERGE_AS_ADMIN")?"viewerCanMergeAsAdmin":""}
178
+ `,Xs=(s=!1,t)=>`
178
179
  id
179
- ${!t||B(t,"ISSUE_FULL_DATABASE_ID")?"fullDatabaseId":"databaseId"}
180
+ ${!t||j(t,"ISSUE_FULL_DATABASE_ID")?"fullDatabaseId":"databaseId"}
180
181
  title
181
182
  author {
182
183
  ... on User {
183
184
  ${T(!1,s)}
184
185
  }
185
186
  ... on Bot {
186
- ${qr(!1)}
187
+ ${Ur(!1)}
187
188
  }
188
189
  ... on EnterpriseUserAccount {
189
- ${Ct(!1)}
190
+ ${Lt(!1)}
190
191
  }
191
192
  }
192
193
  closedAt
@@ -215,14 +216,14 @@ assignees(first: 100) {
215
216
  }
216
217
  state
217
218
  milestone {
218
- ${Ue}
219
+ ${Ge}
219
220
  }
220
221
  labels(first: 100) {
221
222
  nodes {
222
- ${$e}
223
+ ${Te}
223
224
  }
224
225
  }
225
- `,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"},Fs=new RegExp('(([^\\s]+:)?\\"(?:[^\\"\\\\]|\\\\.)*\\"?)|([^\\"\\s]+)',"g"),Dt=s=>{let t=[];return(s.match(Fs)??[]).forEach(r=>{if(r.includes(":")&&r!="is:closed"){let n=r.split(":")[0];js[n]&&t.push(r)}}),t},Lt=(s,t,e,r)=>{let n=s==="issue";return{query:`
226
+ `,Ys={"-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"},Zs=new RegExp('(([^\\s]+:)?\\"(?:[^\\"\\\\]|\\\\.)*\\"?)|([^\\"\\s]+)',"g"),Ut=s=>{let t=[];return(s.match(Zs)??[]).forEach(r=>{if(r.includes(":")&&r!="is:closed"){let n=r.split(":")[0];Ys[n]&&t.push(r)}}),t},$t=(s,t,e,r)=>{let n=s==="issue";return{query:`
226
227
  query SearchIssuesOrPullRequests($query: String! $after: String) {
227
228
  search(type:ISSUE query:$query first: ${r.maxPageSize} after:$after) {
228
229
  pageInfo {
@@ -231,18 +232,18 @@ query SearchIssuesOrPullRequests($query: String! $after: String) {
231
232
  }
232
233
  nodes {
233
234
  ... on ${n?"Issue":"PullRequest"} {
234
- ${n?Qs(r.supportsEmail,r.enterpriseVersion??null):Te(r.supportsDrafts??!1,r.supportsEmail,r.enterpriseVersion??null)}
235
+ ${n?Xs(r.supportsEmail,r.enterpriseVersion??null):Oe(r.supportsDrafts??!1,r.supportsEmail,r.enterpriseVersion??null)}
235
236
  }
236
237
  }
237
238
  }
238
- }`,variables:{query:`is:${s} is:open ${r.includeFromArchivedRepos?"":"archived:false"} ${t}`,after:e}}},Ms="Field 'isDraft' doesn't exist on type 'PullRequest'",Ge=(s=[])=>s.some(t=>t?.message===Ms),zs=/@@ -(\d+)(?:,\d+ | )\+(\d+)(?:,\d+ | )@@(?:\\n)?/,Ws=`
239
+ }`,variables:{query:`is:${s} is:open ${r.includeFromArchivedRepos?"":"archived:false"} ${t}`,after:e}}},en="Field 'isDraft' doesn't exist on type 'PullRequest'",xe=(s=[])=>s.some(t=>t?.message===en),tn=/@@ -(\d+)(?:,\d+ | )\+(\d+)(?:,\d+ | )@@(?:\\n)?/,rn=`
239
240
  \
240
- +`,Sr=(s,t,e,r)=>{let n=zs.exec(s);if(!n||!n[0]||!n[1])return[];let o=parseInt(n[1],10),i=parseInt(n[2],10),a=s.replace(Ws,`
241
+ +`,$r=(s,t,e,r)=>{let n=tn.exec(s);if(!n||!n[0]||!n[1])return[];let o=parseInt(n[1],10),i=parseInt(n[2],10),a=s.replace(rn,`
241
242
  +`).split(`
242
- `).slice(1),u=o-1,l=i-1,c=a.map(g=>{let m,y;switch(g[0]){case"-":{m="DELETED",u+=1,y=`${g.slice(1)}
243
+ `).slice(1),u=o-1,l=i-1,d=a.map(g=>{let m,y;switch(g[0]){case"-":{m="DELETED",u+=1,y=`${g.slice(1)}
243
244
  `;break}case"+":{m="ADDED",l+=1,y=`${g.slice(1)}
244
245
  `;break}default:m="UNMODIFIED",l+=1,u+=1,y=`${g}
245
- `}return{line:y,oldLineNumber:m!=="ADDED"?u:null,newLineNumber:m!=="DELETED"?l:null,type:m}}),p=e,d=t;if(p!==null&&d!==null&&r!==null&&p<d){let g=0,m=c.length,y=r==="LEFT"?"oldLineNumber":"newLineNumber";for(let R=0;R<c.length;R++){let V=c[R][y];V===p?g=R:V===d&&(m=R)}c=c.slice(g,m+1)}return c},Cr=s=>{let t=s.author;return t||(t=Ie),{author:{id:"databaseId"in t?t.databaseId.toString():t.id,graphQLId:t.id,name:("name"in t?t.name:t.login)??t.login,username:t.login,email:("email"in t?t.email:null)??null,avatarUrl:t.avatarUrl,url:t.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 Dr=`mutation DeleteIssueComment(
246
+ `}return{line:y,oldLineNumber:m!=="ADDED"?u:null,newLineNumber:m!=="DELETED"?l:null,type:m}}),p=e,c=t;if(p!==null&&c!==null&&r!==null&&p<c){let g=0,m=d.length,y=r==="LEFT"?"oldLineNumber":"newLineNumber";for(let R=0;R<d.length;R++){let x=d[R][y];x===p?g=R:x===c&&(m=R)}d=d.slice(g,m+1)}return d},Gr=s=>{let t=s.author;return t||(t=be),{author:{id:"databaseId"in t?t.databaseId.toString():t.id,graphQLId:t.id,name:("name"in t?t.name:t.login)??t.login,username:t.login,email:("email"in t?t.email:null)??null,avatarUrl:t.avatarUrl,url:t.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 Tr=`mutation DeleteIssueComment(
246
247
  $issueCommentId: ID!
247
248
  ) {
248
249
  deleteIssueComment(input: {
@@ -250,7 +251,7 @@ query SearchIssuesOrPullRequests($query: String! $after: String) {
250
251
  }) {
251
252
  clientMutationId
252
253
  }
253
- }`,Lr=`mutation DeletePullRequestReviewComment(
254
+ }`,Or=`mutation DeletePullRequestReviewComment(
254
255
  $pullRequestReviewCommentId: ID!
255
256
  ) {
256
257
  deletePullRequestReviewComment(input: {
@@ -260,7 +261,7 @@ query SearchIssuesOrPullRequests($query: String! $after: String) {
260
261
  id
261
262
  }
262
263
  }
263
- }`,Ar=`mutation UpdateIssueComment(
264
+ }`,xr=`mutation UpdateIssueComment(
264
265
  $issueCommentId: ID!,
265
266
  $body: String!
266
267
  ) {
@@ -273,7 +274,7 @@ query SearchIssuesOrPullRequests($query: String! $after: String) {
273
274
  body
274
275
  }
275
276
  }
276
- }`,Ur=`mutation ResolveReviewThread(
277
+ }`,kr=`mutation ResolveReviewThread(
277
278
  $pullRequestReviewThreadId: ID!
278
279
  ) {
279
280
  resolveReviewThread(input: {
@@ -284,7 +285,7 @@ query SearchIssuesOrPullRequests($query: String! $after: String) {
284
285
  isResolved
285
286
  }
286
287
  }
287
- }`,$r=`mutation UnresolveReviewThread(
288
+ }`,Nr=`mutation UnresolveReviewThread(
288
289
  $pullRequestReviewThreadId: ID!
289
290
  ) {
290
291
  unresolveReviewThread(input: {
@@ -295,7 +296,7 @@ query SearchIssuesOrPullRequests($query: String! $after: String) {
295
296
  isResolved
296
297
  }
297
298
  }
298
- }`,Tr=`mutation UpdatePullRequestReviewComment(
299
+ }`,_r=`mutation UpdatePullRequestReviewComment(
299
300
  $pullRequestReviewCommentId: ID!,
300
301
  $body: String!
301
302
  ) {
@@ -308,7 +309,7 @@ query SearchIssuesOrPullRequests($query: String! $after: String) {
308
309
  body
309
310
  }
310
311
  }
311
- }`;var Gr=s=>`
312
+ }`;var Br=s=>`
312
313
  query GetPullRequestComments(
313
314
  $namespace: String!
314
315
  $name: String!
@@ -354,7 +355,7 @@ query GetPullRequestComments(
354
355
  }
355
356
  }
356
357
  }
357
- `;var At=`
358
+ `;var Gt=`
358
359
  id
359
360
  databaseId
360
361
  owner {
@@ -367,18 +368,18 @@ defaultBranchRef {
367
368
  name
368
369
  }
369
370
  viewerPermission
370
- `,Hs={APPROVED:"APPROVED",CHANGES_REQUESTED:"CHANGES_REQUESTED",COMMENTED:"COMMENTED",REVIEW_REQUESTED:"REVIEW_REQUESTED"},Vs={MERGEABLE:"MERGEABLE",CONFLICTING:"CONFLICTS",UNKNOWN:"UNKNOWN"},Js={BEHIND:"BEHIND",BLOCKED:"BLOCKED",UNKNOWN:"UNKNOWN_AND_BLOCKED",UNSTABLE:"UNSTABLE",CLEAN:null,DIRTY:null,DRAFT:null,HAS_HOOKS:null},Ks={OPEN:"OPEN",CLOSED:"CLOSED"},Xs=["ADMIN","MAINTAIN","TRIAGE","WRITE"],Tt=s=>({color:`#${s.color}`,description:s.description,graphQLId:s.id,id:null,name:s.name}),Ys=s=>({canCreateWebhook:s==="ADMIN",canPush:s==="ADMIN"||s==="MAINTAIN"||s==="WRITE",isAdmin:s==="ADMIN"}),Ut=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:Ys(s.viewerPermission)}),Zs=s=>({canCreateWebhook:s.admin,canPush:s.admin||s.maintain||s.push,isAdmin:s.admin}),Or=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:Zs(s.permissions)}),en=s=>({path:s.path,isDirectory:s.type==="tree"}),tn={OPEN:"OPEN",CLOSED:"CLOSED",MERGED:"MERGED"},rn={id:!0,graphQLId:!0,name:!0,username:!0,email:!0,avatarUrl:!0,url:!0},x=(s,t=rn)=>{let e={};return t.id&&(e.id="databaseId"in s?s.databaseId.toString():s.id),t.graphQLId&&(e.graphQLId=s.id),t.name&&(e.name=s.name??s.login),t.username&&(e.username=s.login),t.email&&(e.email=s.email??null),t.avatarUrl&&(e.avatarUrl=s.avatarUrl),t.url&&(e.url=s.url),e},sn=(s,t)=>{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"}[t]},nn=s=>({ERROR:"ERROR",EXPECTED:"PENDING",FAILURE:"FAILED",PENDING:"PENDING",SUCCESS:"SUCCESS"})[s],$t=s=>{let t=null;s.author?t=s.author:t=Ie;let e=(s.reviewRequests?.nodes||[]).filter(C).filter(i=>!i.asCodeOwner),r=s.headRepository?.url;r&&!r.endsWith(".git")&&(r=`${r}.git`);let n=s.repository?.url;n&&!n.endsWith(".git")&&(n=`${n}.git`);let o=e.filter(i=>i.requestedReviewer&&"__typename"in i.requestedReviewer).map(i=>({reviewer:x(i.requestedReviewer),state:"REVIEW_REQUESTED"})).concat((s.latestReviews?.nodes||[]).filter(C).map(i=>{let a=Ie;return i.author&&i.author.__typename&&(a=i.author),{reviewer:x(a),state:Hs[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:tn[s.state],commentCount:s.comments.totalCount,upvoteCount:s.reactions.totalCount,author:t&&t.__typename?x(t):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:n,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:r,cloneUrlSSH:s.headRepository.sshUrl}}:null,headCommit:{buildStatuses:s.commits.nodes?.filter(C)[0]?.commit.statusCheckRollup?.contexts.nodes?.filter(C).map(i=>"context"in i?{completedAt:null,description:i.description,name:i.context,state:nn(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:sn(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(C).map(i=>x(i)):null,reviews:o,reviewDecision:_(o),additions:s.additions,deletions:s.deletions,fileCount:s.changedFiles,commitCount:s.commits.totalCount,mergeableState:Js[s.mergeStateStatus]??Vs[s.mergeable],milestone:s.milestone?Gt(s.milestone):null,labels:s.labels?.nodes?.filter(C).map(Tt)??[],permissions:{canMerge:Xs.includes(s.repository.viewerPermission),canMergeAndBypassProtections:s.viewerCanMergeAsAdmin??!1}}},on=s=>{let{id:t,comments:e,isOutdated:r,isResolved:n,line:o,startLine:i,diffSide:a,originalLine:u,originalStartLine:l,startDiffSide:c}=s,p=e.nodes?.[0];if(!p)return null;let{author:d,body:g,databaseId:m,fullDatabaseId:y,id:R,path:L,publishedAt:V,url:cr}=p,be=o??u,E=i??l,ce=a??c;return{author:d?{avatarUrl:d.avatarUrl,email:null,name:d.login}:null,body:g,createdAt:V?new Date(V):null,diffLines:Sr(p.diffHunk,be,E,ce),id:y??m.toString(),isOutdated:r,isResolved:n,graphQLId:R,threadId:t,filename:L,replies:e.nodes?.filter(C).slice(1).map(an)??[],url:cr,line:be,startLine:E,side:ce}},an=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}),un=s=>{let t=null;return s.author?t=s.author:t=Ie,{id:s.fullDatabaseId!==void 0?s.fullDatabaseId:s.databaseId.toString(),graphQLId:s.id,number:s.number,title:s.title,author:t&&t.__typename?x(t):null,commentCount:s.comments.totalCount,closedDate:s.closedAt?new Date(s.closedAt):null,createdDate:new Date(s.createdAt),description:null,state:{name:Ks[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(C).map(e=>x(e))??[],upvoteCount:s.reactions.totalCount,milestone:s.milestone?Gt(s.milestone):null,labels:s.labels?.nodes?.filter(C).map(Tt)??[]}},Gt=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}),oe=class extends ${constructor(){super(...arguments);this._scopesCache={};this._enterpriseVersionsCache={}}async getScopes(e){let r=e.token||this.config.token;if(!r)return[];let n=this._scopesCache[r];if(!n){let i=(await f(this.config,{query:"query { rateLimit(dryRun: true) { __typename } }"},e)).headers["x-oauth-scopes"];n=i?i.split(", "):[],this._scopesCache[r]=n}return n}async getEnterpriseVersion(e){let r=e.baseUrl||this.config.baseUrl;if(!r)return null;let n=this._enterpriseVersionsCache[r];if(!n){let o=await this.config.request({url:`${ee(this.config,e)}/meta`,headers:I(e.token||this.config.token)});if(!o.body.installed_version)return null;n=o.body.installed_version.split(".").slice(0,3).map(i=>parseInt(i,10)),this._enterpriseVersionsCache[r]=n}return n}getEnterpriseAvatarUrlIfNeeded(e,r,n){let o=n.baseUrl||this.config.baseUrl;return!o||o.startsWith(Ae)?e:r?`https://avatars.githubusercontent.com/u/e?email=${encodeURIComponent(r)}`:""}async getCurrentUser(e={},r={}){if(e.fields&&!e.fields.length)throw new Error('"fields" must contain at least one field or be omitted');let n=fr(e.fields),o=await this.getScopes(r),i=await f(this.config,{query:`
371
+ `,sn={APPROVED:"APPROVED",CHANGES_REQUESTED:"CHANGES_REQUESTED",COMMENTED:"COMMENTED",REVIEW_REQUESTED:"REVIEW_REQUESTED"},nn={MERGEABLE:"MERGEABLE",CONFLICTING:"CONFLICTS",UNKNOWN:"UNKNOWN"},on={BEHIND:"BEHIND",BLOCKED:"BLOCKED",UNKNOWN:"UNKNOWN_AND_BLOCKED",UNSTABLE:"UNSTABLE",CLEAN:null,DIRTY:null,DRAFT:null,HAS_HOOKS:null},an={OPEN:"OPEN",CLOSED:"CLOSED"},un=["ADMIN","MAINTAIN","TRIAGE","WRITE"],xt=s=>({color:`#${s.color}`,description:s.description,graphQLId:s.id,id:null,name:s.name}),ln=s=>({canCreateWebhook:s==="ADMIN",canPush:s==="ADMIN"||s==="MAINTAIN"||s==="WRITE",isAdmin:s==="ADMIN"}),Tt=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:ln(s.viewerPermission)}),pn=s=>({canCreateWebhook:s.admin,canPush:s.admin||s.maintain||s.push,isAdmin:s.admin}),Qr=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:pn(s.permissions)}),dn=s=>({path:s.path,isDirectory:s.type==="tree"}),cn={OPEN:"OPEN",CLOSED:"CLOSED",MERGED:"MERGED"},gn={id:!0,graphQLId:!0,name:!0,username:!0,email:!0,avatarUrl:!0,url:!0},N=(s,t=gn)=>{let e={};return t.id&&(e.id="databaseId"in s?s.databaseId.toString():s.id),t.graphQLId&&(e.graphQLId=s.id),t.name&&(e.name=s.name??s.login),t.username&&(e.username=s.login),t.email&&(e.email=s.email??null),t.avatarUrl&&(e.avatarUrl=s.avatarUrl),t.url&&(e.url=s.url),e},mn=(s,t)=>{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"}[t]},hn=s=>({ERROR:"ERROR",EXPECTED:"PENDING",FAILURE:"FAILED",PENDING:"PENDING",SUCCESS:"SUCCESS"})[s],Ot=s=>{let t=null;s.author?t=s.author:t=be;let e=(s.reviewRequests?.nodes||[]).filter(A).filter(i=>!i.asCodeOwner),r=s.headRepository?.url;r&&!r.endsWith(".git")&&(r=`${r}.git`);let n=s.repository?.url;n&&!n.endsWith(".git")&&(n=`${n}.git`);let o=e.filter(i=>i.requestedReviewer&&"__typename"in i.requestedReviewer).map(i=>({reviewer:N(i.requestedReviewer),state:"REVIEW_REQUESTED"})).concat((s.latestReviews?.nodes||[]).filter(A).map(i=>{let a=be;return i.author&&i.author.__typename&&(a=i.author),{reviewer:N(a),state:sn[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:cn[s.state],commentCount:s.comments.totalCount,upvoteCount:s.reactions.totalCount,author:t&&t.__typename?N(t):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:n,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:r,cloneUrlSSH:s.headRepository.sshUrl}}:null,headCommit:{buildStatuses:s.commits.nodes?.filter(A)[0]?.commit.statusCheckRollup?.contexts.nodes?.filter(A).map(i=>"context"in i?{completedAt:null,description:i.description,name:i.context,state:hn(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:mn(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(A).map(i=>N(i)):null,reviews:o,reviewDecision:Q(o),additions:s.additions,deletions:s.deletions,fileCount:s.changedFiles,commitCount:s.commits.totalCount,mergeableState:on[s.mergeStateStatus]??nn[s.mergeable],milestone:s.milestone?kt(s.milestone):null,labels:s.labels?.nodes?.filter(A).map(xt)??[],permissions:{canMerge:un.includes(s.repository.viewerPermission),canMergeAndBypassProtections:s.viewerCanMergeAsAdmin??!1}}},fn=s=>{let{id:t,comments:e,isOutdated:r,isResolved:n,line:o,startLine:i,diffSide:a,originalLine:u,originalStartLine:l,startDiffSide:d}=s,p=e.nodes?.[0];if(!p)return null;let{author:c,body:g,databaseId:m,fullDatabaseId:y,id:R,path:D,publishedAt:x,url:ve}=p,se=o??u,v=i??l,q=a??d;return{author:c?{avatarUrl:c.avatarUrl,email:null,name:c.login}:null,body:g,createdAt:x?new Date(x):null,diffLines:$r(p.diffHunk,se,v,q),id:y??m.toString(),isOutdated:r,isResolved:n,graphQLId:R,threadId:t,filename:D,replies:e.nodes?.filter(A).slice(1).map(In)??[],url:ve,line:se,startLine:v,side:q}},In=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}),Rn=s=>{let t=null;return s.author?t=s.author:t=be,{id:s.fullDatabaseId!==void 0?s.fullDatabaseId:s.databaseId.toString(),graphQLId:s.id,number:s.number,title:s.title,author:t&&t.__typename?N(t):null,commentCount:s.comments.totalCount,closedDate:s.closedAt?new Date(s.closedAt):null,createdDate:new Date(s.createdAt),description:null,state:{name:an[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(A).map(e=>N(e))??[],upvoteCount:s.reactions.totalCount,milestone:s.milestone?kt(s.milestone):null,labels:s.labels?.nodes?.filter(A).map(xt)??[]}},kt=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}),le=class extends G{constructor(){super(...arguments);this._scopesCache={};this._enterpriseVersionsCache={}}async getScopes(e){let r=e.token||this.config.token;if(!r)return[];let n=this._scopesCache[r];if(!n){let i=(await f(this.config,{query:"query { rateLimit(dryRun: true) { __typename } }"},e)).headers["x-oauth-scopes"];n=i?i.split(", "):[],this._scopesCache[r]=n}return n}async getEnterpriseVersion(e){let r=e.baseUrl||this.config.baseUrl;if(!r)return null;let n=this._enterpriseVersionsCache[r];if(!n){let o=await this.config.request({url:`${re(this.config,e)}/meta`,headers:I(e.token||this.config.token)});if(!o.body.installed_version)return null;n=o.body.installed_version.split(".").slice(0,3).map(i=>parseInt(i,10)),this._enterpriseVersionsCache[r]=n}return n}getEnterpriseAvatarUrlIfNeeded(e,r,n){let o=n.baseUrl||this.config.baseUrl;return!o||o.startsWith($e)?e:r?`https://avatars.githubusercontent.com/u/e?email=${encodeURIComponent(r)}`:""}async getCurrentUser(e={},r={}){if(e.fields&&!e.fields.length)throw new Error('"fields" must contain at least one field or be omitted');let n=Pr(e.fields),o=await this.getScopes(r),i=await f(this.config,{query:`
371
372
  query getCurrentUser {
372
373
  viewer {
373
- ${T(!1,M(o),n)}
374
+ ${T(!1,H(o),n)}
374
375
  }
375
376
  }
376
- `},r),a=i.body.data?.viewer;if(!a)throw new h("Current user not found.",i.body.errors);return{data:x(a,n)}}async getAccountsForRepo(e,r={}){let n=await this.getScopes(r),{repo:{namespace:o,name:i},cursor:a}=e,u=await f(this.config,{query:`
377
+ `},r),a=i.body.data?.viewer;if(!a)throw new h("Current user not found.",i.body.errors);return{data:N(a,n)}}async getAccountsForRepo(e,r={}){let n=await this.getScopes(r),{repo:{namespace:o,name:i},cursor:a}=e,u=await f(this.config,{query:`
377
378
  query getAccountsForRepo($owner: String!, $name: String! $cursor: String, $first: Int!) {
378
379
  repository(owner: $owner, name: $name) {
379
380
  assignableUsers(first: $first, after: $cursor) {
380
381
  nodes {
381
- ${T(!1,M(n))}
382
+ ${T(!1,H(n))}
382
383
  }
383
384
  pageInfo {
384
385
  endCursor
@@ -387,7 +388,7 @@ query getAccountsForRepo($owner: String!, $name: String! $cursor: String, $first
387
388
  }
388
389
  }
389
390
  }
390
- `,variables:{owner:o,name:i,cursor:a,first:v}},r);if(!u.body.data)throw new h("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=>x(l))??[]}}async getUserForCommit(e,r={}){let n=await f(this.config,{query:`
391
+ `,variables:{owner:o,name:i,cursor:a,first:E}},r);if(!u.body.data)throw new h("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=>N(l))??[]}}async getUserForCommit(e,r={}){let n=await f(this.config,{query:`
391
392
  query getUserForCommit(
392
393
  $owner: String!
393
394
  $name: String!
@@ -433,23 +434,23 @@ mutation createCommitOnBranch(
433
434
  }
434
435
  }
435
436
  }
436
- `,variables:{branchName:u.name,expectedHeadOid:u.oid,fileChanges:{additions:Object.entries(i).map(([c,p])=>({contents:xr.Base64.encode(p),path:c})),deletions:o.map(c=>({path:c}))},message:{body:n.description,headline:n.summary},repositoryNameWithOwner:`${a.namespace}/${a.name}`}},r);if(!l.body.data)throw new h("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,r={}){let n=await this.getScopes(r),o=await f(this.config,{query:`
437
+ `,variables:{branchName:u.name,expectedHeadOid:u.oid,fileChanges:{additions:Object.entries(i).map(([d,p])=>({contents:jr.Base64.encode(p),path:d})),deletions:o.map(d=>({path:d}))},message:{body:n.description,headline:n.summary},repositoryNameWithOwner:`${a.namespace}/${a.name}`}},r);if(!l.body.data)throw new h("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,r={}){let n=await this.getScopes(r),o=await f(this.config,{query:`
437
438
  query getAccountForEmail($query: String! $avatarSize: Int) {
438
439
  search(query: $query, type: USER, first: 1) {
439
440
  nodes {
440
441
  ... on User {
441
- ${T(!0,M(n))}
442
+ ${T(!0,H(n))}
442
443
  }
443
444
  }
444
445
  }
445
446
  }
446
- `,variables:{query:`in:email ${e.email}`,avatarSize:e.avatarSize}},r),i=o.body.data?.search?.nodes?.[0];if(!i)throw new h("Could not find user via email",o.body.errors);return{data:x({...i,avatarUrl:this.getEnterpriseAvatarUrlIfNeeded(i.avatarUrl,i.email,r)})}}async getAccountForUsername(e,r={}){let n=await this.getScopes(r),o=await f(this.config,{query:`
447
+ `,variables:{query:`in:email ${e.email}`,avatarSize:e.avatarSize}},r),i=o.body.data?.search?.nodes?.[0];if(!i)throw new h("Could not find user via email",o.body.errors);return{data:N({...i,avatarUrl:this.getEnterpriseAvatarUrlIfNeeded(i.avatarUrl,i.email,r)})}}async getAccountForUsername(e,r={}){let n=await this.getScopes(r),o=await f(this.config,{query:`
447
448
  query getUserForUsername($login: String! $avatarSize: Int) {
448
449
  user(login: $login) {
449
- ${T(!0,M(n))}
450
+ ${T(!0,H(n))}
450
451
  }
451
452
  }
452
- `,variables:{login:e.username,avatarSize:e.avatarSize}},r),i=o.body.data?.user;if(!i)throw new h("Could not find user via username",o.body.errors);return{data:x({...i,avatarUrl:this.getEnterpriseAvatarUrlIfNeeded(i.avatarUrl,i.email,r)})}}async getOrgsForCurrentUser(e={},r={}){let n=await f(this.config,{query:`
453
+ `,variables:{login:e.username,avatarSize:e.avatarSize}},r),i=o.body.data?.user;if(!i)throw new h("Could not find user via username",o.body.errors);return{data:N({...i,avatarUrl:this.getEnterpriseAvatarUrlIfNeeded(i.avatarUrl,i.email,r)})}}async getOrgsForCurrentUser(e={},r={}){let n=await f(this.config,{query:`
453
454
  query getOrgsForCurrentUser($cursor: String, $first: Int!) {
454
455
  viewer {
455
456
  organizations(first: $first after: $cursor) {
@@ -468,7 +469,7 @@ query getOrgsForCurrentUser($cursor: String, $first: Int!) {
468
469
  }
469
470
  }
470
471
  }
471
- `,variables:{cursor:e.cursor,first:v}},r);if(!n.body.data)throw new h("Could not fetch orgs for current user",n.body.errors);let o=n.body.data.viewer.organizations.nodes||[];return{pageInfo:n.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,r={}){let n=await f(this.config,{query:`
472
+ `,variables:{cursor:e.cursor,first:E}},r);if(!n.body.data)throw new h("Could not fetch orgs for current user",n.body.errors);let o=n.body.data.viewer.organizations.nodes||[];return{pageInfo:n.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,r={}){let n=await f(this.config,{query:`
472
473
  query getOrgMember($cursor: String, $first: Int!, $login: String!) {
473
474
  viewer {
474
475
  organization(login: $login) {
@@ -484,22 +485,22 @@ query getOrgMember($cursor: String, $first: Int!, $login: String!) {
484
485
  }
485
486
  }
486
487
  }
487
- `,variables:{cursor:e.cursor,first:v,login:e.org}},r);if(!n.body.data?.viewer.organization?.membersWithRole&&n.body.errors?.length)throw new h("Could not read the members of the organization",n.body.errors);let o=n.body.data?.viewer.organization?.membersWithRole.nodes||[];return{pageInfo:{hasNextPage:n.body.data?.viewer.organization?.membersWithRole.pageInfo.hasNextPage??!1,endCursor:n.body.data?.viewer.organization?.membersWithRole.pageInfo.endCursor??null},data:o.map(i=>x({...i,avatarUrl:this.getEnterpriseAvatarUrlIfNeeded(i.avatarUrl,i.email,r)}))}}async getRepo(e,r={}){let n=await f(this.config,{query:`
488
+ `,variables:{cursor:e.cursor,first:E,login:e.org}},r);if(!n.body.data?.viewer.organization?.membersWithRole&&n.body.errors?.length)throw new h("Could not read the members of the organization",n.body.errors);let o=n.body.data?.viewer.organization?.membersWithRole.nodes||[];return{pageInfo:{hasNextPage:n.body.data?.viewer.organization?.membersWithRole.pageInfo.hasNextPage??!1,endCursor:n.body.data?.viewer.organization?.membersWithRole.pageInfo.endCursor??null},data:o.map(i=>N({...i,avatarUrl:this.getEnterpriseAvatarUrlIfNeeded(i.avatarUrl,i.email,r)}))}}async getRepo(e,r={}){let n=await f(this.config,{query:`
488
489
  query getRepo($owner: String!, $name: String!) {
489
490
  repository(owner: $owner, name: $name) {
490
- ${At}
491
+ ${Gt}
491
492
  }
492
493
  }
493
- `,variables:{owner:e.namespace,name:e.name}},r);if(!n.body.data?.repository)throw new h(`Repository ${e.namespace}/${e.name} not found`,n.body.errors);return{data:Ut(n.body.data.repository)}}async getRepos(e,r={}){let n=e.map(({namespace:u,name:l},c)=>`
494
- getRepo_${c}: repository(owner: "${u}", name: "${l}") {
495
- ${At}
494
+ `,variables:{owner:e.namespace,name:e.name}},r);if(!n.body.data?.repository)throw new h(`Repository ${e.namespace}/${e.name} not found`,n.body.errors);return{data:Tt(n.body.data.repository)}}async getRepos(e,r={}){let n=e.map(({namespace:u,name:l},d)=>`
495
+ getRepo_${d}: repository(owner: "${u}", name: "${l}") {
496
+ ${Gt}
496
497
  }
497
498
  `).join(`
498
499
  `),o=await f(this.config,{query:`
499
500
  query batchGetRepos {
500
501
  ${n}
501
502
  }
502
- `},r);if(!o.body.data)throw new h("Could not fetch repos",o.body.errors);let i=[],a=[];return e.forEach((u,l)=>{let c=o.body.data[`getRepo_${l}`];c?i.push(Ut(c)):a.push({input:u})}),{data:i,errors:a}}async fetchMultipleRESTPages(e,r,n,o){let i=[];for(let p=0;p<r;p++)i.push(n(e+p));let a=await Promise.all(i),u=[];for(let p of a){if(!p.body)throw new Error(p.statusText||"Unknown error");u=u.concat(p.body.map(d=>o(d)))}let l=a.every(p=>p.body.length===100),c=e+r;return{data:u,pageInfo:{hasNextPage:l,nextPage:l?c:null}}}async getReposForCurrentUser(e,r={}){if(e.simultaneousPagesToFetch&&e.simultaneousPagesToFetch>40)throw new Error("The argument 'simultaneousPagesToFetch' cannot exceed 40 for 'getReposForCurrentUser'");let n=new URLSearchParams;n.append("per_page","100"),e.affiliations&&n.append("affiliation",e.affiliations.join(","));let o=i=>this.config.request({url:`${ee(this.config,r)}/user/repos?${n.toString()}&page=${i}`,headers:{...I(r.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,Or)}async getReposForOrg(e,r={}){if(e.simultaneousPagesToFetch&&e.simultaneousPagesToFetch>40)throw new Error("The argument 'simultaneousPagesToFetch' cannot exceed 40 for 'getReposForOrg'");let n=o=>this.config.request({url:`${ee(this.config,r)}/orgs/${e.orgName}/repos?per_page=100&page=${o}`,headers:{...I(r.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,n,Or)}async getReposForUsernames(e,r={}){if(!e.usernames.length)return{pageInfo:{endCursor:null,hasNextPage:!1},data:[]};let n=await f(this.config,{query:`
503
+ `},r);if(!o.body.data)throw new h("Could not fetch repos",o.body.errors);let i=[],a=[];return e.forEach((u,l)=>{let d=o.body.data[`getRepo_${l}`];d?i.push(Tt(d)):a.push({input:u})}),{data:i,errors:a}}async fetchMultipleRESTPages(e,r,n,o){let i=[];for(let p=0;p<r;p++)i.push(n(e+p));let a=await Promise.all(i),u=[];for(let p of a){if(!p.body)throw new Error(p.statusText||"Unknown error");u=u.concat(p.body.map(c=>o(c)))}let l=a.every(p=>p.body.length===100),d=e+r;return{data:u,pageInfo:{hasNextPage:l,nextPage:l?d:null}}}async getReposForCurrentUser(e,r={}){if(e.simultaneousPagesToFetch&&e.simultaneousPagesToFetch>40)throw new Error("The argument 'simultaneousPagesToFetch' cannot exceed 40 for 'getReposForCurrentUser'");let n=new URLSearchParams;n.append("per_page","100"),e.affiliations&&n.append("affiliation",e.affiliations.join(","));let o=i=>this.config.request({url:`${re(this.config,r)}/user/repos?${n.toString()}&page=${i}`,headers:{...I(r.token||this.config.token),Accept:"application/vnd.github.raw+json","X-Github-Next-Global-ID":1}});return await this.fetchMultipleRESTPages(e.page??1,e.simultaneousPagesToFetch??4,o,Qr)}async getReposForOrg(e,r={}){if(e.simultaneousPagesToFetch&&e.simultaneousPagesToFetch>40)throw new Error("The argument 'simultaneousPagesToFetch' cannot exceed 40 for 'getReposForOrg'");let n=o=>this.config.request({url:`${re(this.config,r)}/orgs/${e.orgName}/repos?per_page=100&page=${o}`,headers:{...I(r.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,n,Qr)}async getReposForUsernames(e,r={}){if(!e.usernames.length)return{pageInfo:{endCursor:null,hasNextPage:!1},data:[]};let n=await f(this.config,{query:`
503
504
  query getReposForUsernames($query: String!, $cursor: String, $first: Int!) {
504
505
  search(query: $query, type: REPOSITORY, first: $first, after: $cursor) {
505
506
  pageInfo {
@@ -508,12 +509,12 @@ query getReposForUsernames($query: String!, $cursor: String, $first: Int!) {
508
509
  }
509
510
  nodes {
510
511
  ... on Repository {
511
- ${At}
512
+ ${Gt}
512
513
  }
513
514
  }
514
515
  }
515
516
  }
516
- `,variables:{query:`fork:true ${e.usernames.map(i=>`user:${i}`).join(" ")}`,cursor:e.cursor,first:v}},r);if(!n.body.data)throw new h("Could not fetch repos for usernames",n.body.errors);let o=n.body.data.search.nodes||[];return{pageInfo:n.body.data.search.pageInfo,data:o.map(Ut)}}async getReposForOwners(e,r={}){return this.getReposForUsernames({usernames:e.owners.filter(n=>n.username).map(n=>n.username),cursor:e.cursor},r)}async getRefs(e,r,n={}){let o=await f(this.config,{query:`
517
+ `,variables:{query:`fork:true ${e.usernames.map(i=>`user:${i}`).join(" ")}`,cursor:e.cursor,first:E}},r);if(!n.body.data)throw new h("Could not fetch repos for usernames",n.body.errors);let o=n.body.data.search.nodes||[];return{pageInfo:n.body.data.search.pageInfo,data:o.map(Tt)}}async getReposForOwners(e,r={}){return this.getReposForUsernames({usernames:e.owners.filter(n=>n.username).map(n=>n.username),cursor:e.cursor},r)}async getRefs(e,r,n={}){let o=await f(this.config,{query:`
517
518
  query getRefs($owner: String!, $name: String!, $refPrefix: String!, $cursor: String, $first: Int!) {
518
519
  repository(owner: $owner, name: $name) {
519
520
  refs(refPrefix: $refPrefix first: $first after: $cursor) {
@@ -534,7 +535,7 @@ query getRefs($owner: String!, $name: String!, $refPrefix: String!, $cursor: Str
534
535
  }
535
536
  }
536
537
  }
537
- `,variables:{owner:r.repo.namespace,name:r.repo.name,refPrefix:e,cursor:r.cursor,first:v}},n),i=o.body.data?.repository;if(!i)throw new h("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,r={}){return this.getRefs("refs/heads/",e,r)}async getTags(e,r={}){return this.getRefs("refs/tags/",e,r)}async getBlame(e,r={}){let n=await f(this.config,{query:`
538
+ `,variables:{owner:r.repo.namespace,name:r.repo.name,refPrefix:e,cursor:r.cursor,first:E}},n),i=o.body.data?.repository;if(!i)throw new h("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,r={}){return this.getRefs("refs/heads/",e,r)}async getTags(e,r={}){return this.getRefs("refs/tags/",e,r)}async getBlame(e,r={}){let n=await f(this.config,{query:`
538
539
  query getBlame($owner: String!, $name: String!, $ref: String!, $path: String!) {
539
540
  repository(owner: $owner, name: $name) {
540
541
  object(expression: $ref) {
@@ -573,7 +574,7 @@ query getBlame($owner: String!, $name: String!, $ref: String!, $path: String!) {
573
574
  }
574
575
  }
575
576
  }
576
- `,variables:{owner:e.repo.namespace,name:e.repo.name,ref:e.ref,path:e.path}},r),o=n.body.data?.repository;if(!o)throw new h("Blame repository not found.",n.body.errors);let i=o.object;if(!i||!("blame"in i))throw new h("Ref not found.",n.body.errors);if(i.blame.ranges.length===0)throw new h("File not found.",n.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,r={}){let n=await this.config.request({url:`${ee(this.config,r)}/repos/${e.repo.namespace}/${e.repo.name}/contents/${encodeURIComponent(e.path)}?ref=${e.ref}`,headers:{...I(r.token||this.config.token),Accept:"application/vnd.github.raw+json"}});if(n.headers["content-type"].startsWith("application/json"))throw new Error(`GitHub: got directory when fetching "${e.path}", getFileContents does not support fetching directories`);if(!n.headers["content-type"].startsWith("application/vnd.github.raw+json"))throw new Error(`GitHub: unsupported content type "${n.headers["content-type"]}" when fetching "${e.path}"`);return{data:new Blob([n.body])}}async getMergeBase(e,r={}){return{data:(await this.config.request({url:`${ee(this.config,r)}/repos/${e.repo.namespace}/${e.repo.name}/compare/${encodeURIComponent(e.base)}...${encodeURIComponent(e.head)}`,headers:I(r.token||this.config.token)})).body.merge_base_commit.sha}}async searchPullRequests(e,r={}){let n=await this.getEnterpriseVersion(r),o=await this.getScopes(r),i=M(o),a=c=>{let p=c&&typeof e.isDraft=="boolean"?`${e.query} draft:${e.isDraft}`:e.query;return Lt("pr",p,e.cursor,{maxPageSize:e.maxPageSize??wr,supportsEmail:i,supportsDrafts:c,enterpriseVersion:n,includeFromArchivedRepos:e.includeFromArchivedRepos})},u=await f(this.config,a(!0),r);u.body.errors&&Ge(u.body.errors)&&(this.config.baseUrl||r.baseUrl)&&(u=await f(this.config,a(!1),r));let{data:l}=u.body;if(!l)throw new h("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(C).map($t)||[]}}async searchIssues(e,r={}){let n=await this.getEnterpriseVersion(r),o=await this.getScopes(r),i=M(o),a=await f(this.config,Lt("issue",e.query,e.cursor,{supportsEmail:i,includeFromArchivedRepos:e.includeFromArchivedRepos,maxPageSize:e.maxPageSize??vr,enterpriseVersion:n}),r),{data:u}=a.body;if(!u)throw new h("Could not search issues",a.body.errors);return{pageInfo:{hasNextPage:u.search.pageInfo.hasNextPage,endCursor:u.search.pageInfo.endCursor},data:u.search.nodes?.filter(C).map(un)||[]}}async getPullRequestsAssociatedWithUser(e,r={}){let n=[`involves:${e.username}`];return e.repos?.length&&e.repos.forEach(o=>{n.push(`repo:${o.namespace}/${o.name}`)}),e.labelNames&&e.labelNames.forEach(o=>{n.push(`label:"${o}"`)}),this.searchPullRequests({query:n.join(" "),cursor:e.cursor,includeFromArchivedRepos:e.includeFromArchivedRepos,maxPageSize:e.maxPageSize},r)}async getPullRequestsForRepos(e,r={}){let{assigneeLogins:n,updatedBefore:o,authorLogin:i,repos:a,reviewRequestedLogin:u,startQuery:l,mentionLogin:c,labelNames:p,maxPageSize:d}=e,g=Dt(l||"");return a.forEach(m=>{g.push(`repo:${m.namespace}/${m.name}`)}),n&&n.forEach(m=>{g.push(`assignee:${m}`)}),o&&g.push(`updated:<${o}`),i&&g.push(`author:${i}`),u&&g.push(`review-requested:${u}`),c&&g.push(`mentions:${c}`),p&&p.forEach(m=>{g.push(`label:"${m}"`)}),this.searchPullRequests({query:`sort:updated ${g.join(" ")}`,isDraft:e.isDraft,cursor:e.cursor,includeFromArchivedRepos:e.includeFromArchivedRepos,maxPageSize:d},r)}async getPullRequestForRepo(e,r={}){let n=await this.getEnterpriseVersion(r),o=await this.getScopes(r),i=M(o),a=p=>({query:`query getPullRequest(
577
+ `,variables:{owner:e.repo.namespace,name:e.repo.name,ref:e.ref,path:e.path}},r),o=n.body.data?.repository;if(!o)throw new h("Blame repository not found.",n.body.errors);let i=o.object;if(!i||!("blame"in i))throw new h("Ref not found.",n.body.errors);if(i.blame.ranges.length===0)throw new h("File not found.",n.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,r={}){let n=await this.config.request({url:`${re(this.config,r)}/repos/${e.repo.namespace}/${e.repo.name}/contents/${encodeURIComponent(e.path)}?ref=${e.ref}`,headers:{...I(r.token||this.config.token),Accept:"application/vnd.github.raw+json"}});if(n.headers["content-type"].startsWith("application/json"))throw new Error(`GitHub: got directory when fetching "${e.path}", getFileContents does not support fetching directories`);if(!n.headers["content-type"].startsWith("application/vnd.github.raw+json"))throw new Error(`GitHub: unsupported content type "${n.headers["content-type"]}" when fetching "${e.path}"`);return{data:new Blob([n.body])}}async getMergeBase(e,r={}){return{data:(await this.config.request({url:`${re(this.config,r)}/repos/${e.repo.namespace}/${e.repo.name}/compare/${encodeURIComponent(e.base)}...${encodeURIComponent(e.head)}`,headers:I(r.token||this.config.token)})).body.merge_base_commit.sha}}async searchPullRequests(e,r={}){let n=await this.getEnterpriseVersion(r),o=await this.getScopes(r),i=H(o),a=d=>{let p=d&&typeof e.isDraft=="boolean"?`${e.query} draft:${e.isDraft}`:e.query;return $t("pr",p,e.cursor,{maxPageSize:e.maxPageSize??Dr,supportsEmail:i,supportsDrafts:d,enterpriseVersion:n,includeFromArchivedRepos:e.includeFromArchivedRepos})},u=await f(this.config,a(!0),r);u.body.errors&&xe(u.body.errors)&&(this.config.baseUrl||r.baseUrl)&&(u=await f(this.config,a(!1),r));let{data:l}=u.body;if(!l)throw new h("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(A).map(Ot)||[]}}async searchIssues(e,r={}){let n=await this.getEnterpriseVersion(r),o=await this.getScopes(r),i=H(o),a=await f(this.config,$t("issue",e.query,e.cursor,{supportsEmail:i,includeFromArchivedRepos:e.includeFromArchivedRepos,maxPageSize:e.maxPageSize??Ar,enterpriseVersion:n}),r),{data:u}=a.body;if(!u)throw new h("Could not search issues",a.body.errors);return{pageInfo:{hasNextPage:u.search.pageInfo.hasNextPage,endCursor:u.search.pageInfo.endCursor},data:u.search.nodes?.filter(A).map(Rn)||[]}}async getPullRequestsAssociatedWithUser(e,r={}){let n=[`involves:${e.username}`];return e.repos?.length&&e.repos.forEach(o=>{n.push(`repo:${o.namespace}/${o.name}`)}),e.labelNames&&e.labelNames.forEach(o=>{n.push(`label:"${o}"`)}),this.searchPullRequests({query:n.join(" "),cursor:e.cursor,includeFromArchivedRepos:e.includeFromArchivedRepos,maxPageSize:e.maxPageSize},r)}async getPullRequestsForRepos(e,r={}){let{assigneeLogins:n,updatedBefore:o,authorLogin:i,repos:a,reviewRequestedLogin:u,startQuery:l,mentionLogin:d,labelNames:p,maxPageSize:c}=e,g=Ut(l||"");return a.forEach(m=>{g.push(`repo:${m.namespace}/${m.name}`)}),n&&n.forEach(m=>{g.push(`assignee:${m}`)}),o&&g.push(`updated:<${o}`),i&&g.push(`author:${i}`),u&&g.push(`review-requested:${u}`),d&&g.push(`mentions:${d}`),p&&p.forEach(m=>{g.push(`label:"${m}"`)}),this.searchPullRequests({query:`sort:updated ${g.join(" ")}`,isDraft:e.isDraft,cursor:e.cursor,includeFromArchivedRepos:e.includeFromArchivedRepos,maxPageSize:c},r)}async getPullRequestForRepo(e,r={}){let n=await this.getEnterpriseVersion(r),o=await this.getScopes(r),i=H(o),a=p=>({query:`query getPullRequest(
577
578
  $owner: String!
578
579
  $name: String!
579
580
  $number: Int!
@@ -583,18 +584,18 @@ query getBlame($owner: String!, $name: String!, $ref: String!, $path: String!) {
583
584
  name: $name
584
585
  ) {
585
586
  pullRequest(number: $number) {
586
- ${Te(p,i,n)}
587
+ ${Oe(p,i,n)}
587
588
  }
588
589
  }
589
- }`,variables:{owner:e.repo.namespace,name:e.repo.name,number:e.number}}),u=await f(this.config,a(!0),r);u.body.errors&&Ge(u.body.errors)&&(this.config.baseUrl||r.baseUrl)&&(u=await f(this.config,a(!1),r));let{data:l}=u.body;if(!l)throw new h("Could not fetch pull request by number",u.body.errors);let c=u.body.data?.repository.pullRequest;return{data:c?$t(c):null}}async getPullRequestByGraphQLId(e,r={}){let n=await this.getEnterpriseVersion(r),o=await this.getScopes(r),i=M(o),a=p=>({query:`query getPullRequest(
590
+ }`,variables:{owner:e.repo.namespace,name:e.repo.name,number:e.number}}),u=await f(this.config,a(!0),r);u.body.errors&&xe(u.body.errors)&&(this.config.baseUrl||r.baseUrl)&&(u=await f(this.config,a(!1),r));let{data:l}=u.body;if(!l)throw new h("Could not fetch pull request by number",u.body.errors);let d=u.body.data?.repository.pullRequest;return{data:d?Ot(d):null}}async getPullRequestByGraphQLId(e,r={}){let n=await this.getEnterpriseVersion(r),o=await this.getScopes(r),i=H(o),a=p=>({query:`query getPullRequest(
590
591
  $graphQLId: ID!
591
592
  ) {
592
593
  node(id: $graphQLId) {
593
594
  ... on PullRequest {
594
- ${Te(p,i,n)}
595
+ ${Oe(p,i,n)}
595
596
  }
596
597
  }
597
- }`,variables:{graphQLId:e.graphQLId}}),u=await f(this.config,a(!0),r);u.body.errors&&Ge(u.body.errors)&&(this.config.baseUrl||r.baseUrl)&&(u=await f(this.config,a(!1),r));let{data:l}=u.body;if(!l)throw new h("Could not fetch pull request by id",u.body.errors);let c=u.body.data?.node;return{data:c?$t(c):null}}async closePullRequest(e,r={}){let{pullRequest:{graphQLId:n}}=e;if(!n)throw new Error('GitHub requires "graphQLId" for this function.');let o=`mutation ClosePullRequest($pullRequestGraphQLId: ID!) {
598
+ }`,variables:{graphQLId:e.graphQLId}}),u=await f(this.config,a(!0),r);u.body.errors&&xe(u.body.errors)&&(this.config.baseUrl||r.baseUrl)&&(u=await f(this.config,a(!1),r));let{data:l}=u.body;if(!l)throw new h("Could not fetch pull request by id",u.body.errors);let d=u.body.data?.node;return{data:d?Ot(d):null}}async closePullRequest(e,r={}){let{pullRequest:{graphQLId:n}}=e;if(!n)throw new Error('GitHub requires "graphQLId" for this function.');let o=`mutation ClosePullRequest($pullRequestGraphQLId: ID!) {
598
599
  closePullRequest(input: { pullRequestId: $pullRequestGraphQLId }) {
599
600
  pullRequest {
600
601
  id
@@ -667,7 +668,7 @@ query getBlame($owner: String!, $name: String!, $ref: String!, $path: String!) {
667
668
  }
668
669
  }
669
670
  }
670
- }`,a=await f(this.config,{query:i,variables:{subjectId:n.graphQLId,body:o}},r);if(!a.body.data?.addComment?.commentEdge?.node?.id)throw new h("Could not add comment to pull request",a.body.errors)}async addInlineCommentToPullRequest(e,r={}){let{pullRequest:n,comment:o,path:i,line:a,side:u="RIGHT",threadId:l}=e;if(!n.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},r);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:n,comment:o,path:i,line:a,side:u},r)}async deleteInlineComment(e,r={}){let{commentId:n}=e;if(!n)throw new Error('GitHub requires "commentId" for this function.');let o=await f(this.config,{query:Lr,variables:{pullRequestReviewCommentId:n}},r);if(!o.body.data?.deletePullRequestReviewComment)throw new h("Could not delete inline comment",o.body.errors)}async deleteComment(e,r={}){let{commentId:n}=e;if(!n)throw new Error('GitHub requires "commentId" for this function.');let o=await f(this.config,{query:Dr,variables:{issueCommentId:n}},r);if(!o.body.data?.deleteIssueComment)throw new h("Could not delete comment",o.body.errors)}async editComment(e,r={}){let{commentId:n,body:o}=e;if(!n)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 f(this.config,{query:Ar,variables:{issueCommentId:n,body:o}},r);if(!i.body.data?.updateIssueComment?.issueComment?.id)throw new h("Could not edit comment",i.body.errors)}async editInlineComment(e,r={}){let{commentId:n,body:o}=e;if(!n)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 f(this.config,{query:Tr,variables:{pullRequestReviewCommentId:n,body:o}},r);if(!i.body.data?.updatePullRequestReviewComment?.pullRequestReviewComment?.id)throw new h("Could not edit inline comment",i.body.errors)}async resolveReviewThread(e,r={}){let{threadId:n}=e;if(!n)throw new Error('GitHub requires "threadId" for this function.');let o=await f(this.config,{query:Ur,variables:{pullRequestReviewThreadId:n}},r);if(!o.body.data?.resolveReviewThread?.thread?.id)throw new h("Could not resolve review thread",o.body.errors)}async unresolveReviewThread(e,r={}){let{threadId:n}=e;if(!n)throw new Error('GitHub requires "threadId" for this function.');let o=await f(this.config,{query:$r,variables:{pullRequestReviewThreadId:n}},r);if(!o.body.data?.unresolveReviewThread?.thread?.id)throw new h("Could not unresolve review thread",o.body.errors)}async addReplyToReviewThread(e,r){let{threadId:n,comment:o}=e,i=`mutation AddPullRequestReviewThreadReply(
671
+ }`,a=await f(this.config,{query:i,variables:{subjectId:n.graphQLId,body:o}},r);if(!a.body.data?.addComment?.commentEdge?.node?.id)throw new h("Could not add comment to pull request",a.body.errors)}async addInlineCommentToPullRequest(e,r={}){let{pullRequest:n,comment:o,path:i,line:a,side:u="RIGHT",threadId:l}=e;if(!n.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},r);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:n,comment:o,path:i,line:a,side:u},r)}async deleteInlineComment(e,r={}){let{commentId:n}=e;if(!n)throw new Error('GitHub requires "commentId" for this function.');let o=await f(this.config,{query:Or,variables:{pullRequestReviewCommentId:n}},r);if(!o.body.data?.deletePullRequestReviewComment)throw new h("Could not delete inline comment",o.body.errors)}async deleteComment(e,r={}){let{commentId:n}=e;if(!n)throw new Error('GitHub requires "commentId" for this function.');let o=await f(this.config,{query:Tr,variables:{issueCommentId:n}},r);if(!o.body.data?.deleteIssueComment)throw new h("Could not delete comment",o.body.errors)}async editComment(e,r={}){let{commentId:n,body:o}=e;if(!n)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 f(this.config,{query:xr,variables:{issueCommentId:n,body:o}},r);if(!i.body.data?.updateIssueComment?.issueComment?.id)throw new h("Could not edit comment",i.body.errors)}async editInlineComment(e,r={}){let{commentId:n,body:o}=e;if(!n)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 f(this.config,{query:_r,variables:{pullRequestReviewCommentId:n,body:o}},r);if(!i.body.data?.updatePullRequestReviewComment?.pullRequestReviewComment?.id)throw new h("Could not edit inline comment",i.body.errors)}async resolveReviewThread(e,r={}){let{threadId:n}=e;if(!n)throw new Error('GitHub requires "threadId" for this function.');let o=await f(this.config,{query:kr,variables:{pullRequestReviewThreadId:n}},r);if(!o.body.data?.resolveReviewThread?.thread?.id)throw new h("Could not resolve review thread",o.body.errors)}async unresolveReviewThread(e,r={}){let{threadId:n}=e;if(!n)throw new Error('GitHub requires "threadId" for this function.');let o=await f(this.config,{query:Nr,variables:{pullRequestReviewThreadId:n}},r);if(!o.body.data?.unresolveReviewThread?.thread?.id)throw new h("Could not unresolve review thread",o.body.errors)}async addReplyToReviewThread(e,r){let{threadId:n,comment:o}=e,i=`mutation AddPullRequestReviewThreadReply(
671
672
  $threadId: ID!,
672
673
  $body: String!
673
674
  ) {
@@ -705,7 +706,7 @@ query getBlame($owner: String!, $name: String!, $ref: String!, $path: String!) {
705
706
  }
706
707
  }
707
708
  }
708
- }`,c=await f(this.config,{query:l,variables:{pullRequestId:n.graphQLId,body:o,path:i,line:a,side:u}},r);if(!c.body.data?.addPullRequestReview?.pullRequestReview?.id)throw new h("Could not add inline comment to pull request",c.body.errors);return c.body.data?.addPullRequestReview?.pullRequestReview?.comments?.nodes?.[0]?.id}async setPullRequestMilestone(e,r={}){let{pullRequest:n,milestone:o}=e;if(!n.graphQLId)throw new Error('GitHub requires "graphQLId" for this function.');let i=`mutation SetPullRequestMilestone($pullRequestGraphQLId: ID!, $milestoneGraphQLId: ID) {
709
+ }`,d=await f(this.config,{query:l,variables:{pullRequestId:n.graphQLId,body:o,path:i,line:a,side:u}},r);if(!d.body.data?.addPullRequestReview?.pullRequestReview?.id)throw new h("Could not add inline comment to pull request",d.body.errors);return d.body.data?.addPullRequestReview?.pullRequestReview?.comments?.nodes?.[0]?.id}async setPullRequestMilestone(e,r={}){let{pullRequest:n,milestone:o}=e;if(!n.graphQLId)throw new Error('GitHub requires "graphQLId" for this function.');let i=`mutation SetPullRequestMilestone($pullRequestGraphQLId: ID!, $milestoneGraphQLId: ID) {
709
710
  updatePullRequest(input: { pullRequestId: $pullRequestGraphQLId, milestoneId: $milestoneGraphQLId }) {
710
711
  pullRequest {
711
712
  id
@@ -729,7 +730,7 @@ query getBlame($owner: String!, $name: String!, $ref: String!, $path: String!) {
729
730
  id
730
731
  }
731
732
  }
732
- }`,c=await f(this.config,{query:l,variables:{pullRequestGraphQLId:o,reviewerGraphQLIds:u}},r);if(!c.body.data?.requestReviews?.pullRequest?.id)throw new h("Could not set pull request reviewers",c.body.errors)}async reRequestPullRequestReviews(e,r={}){let{pullRequest:{reviews:n,graphQLId:o},reviewers:i}=e;if(!o)throw new Error('GitHub requires "graphQLId" for this function.');if(!n)throw new Error('GitHub requires "reviews" for this function.');let a=[];for(let c of i){if(!c.graphQLId)throw new Error('GitHub requires reviwer "graphQLId" for this function.');if(!n.find(p=>p.reviewer.graphQLId===c.graphQLId))throw new Error("Can only re-request review from existing reviewer.");a.push(c.graphQLId)}let u=`mutation SetPullRequestReviewers($pullRequestGraphQLId: ID!, $reviewerGraphQLIds: [ID!]!) {
733
+ }`,d=await f(this.config,{query:l,variables:{pullRequestGraphQLId:o,reviewerGraphQLIds:u}},r);if(!d.body.data?.requestReviews?.pullRequest?.id)throw new h("Could not set pull request reviewers",d.body.errors)}async reRequestPullRequestReviews(e,r={}){let{pullRequest:{reviews:n,graphQLId:o},reviewers:i}=e;if(!o)throw new Error('GitHub requires "graphQLId" for this function.');if(!n)throw new Error('GitHub requires "reviews" for this function.');let a=[];for(let d of i){if(!d.graphQLId)throw new Error('GitHub requires reviwer "graphQLId" for this function.');if(!n.find(p=>p.reviewer.graphQLId===d.graphQLId))throw new Error("Can only re-request review from existing reviewer.");a.push(d.graphQLId)}let u=`mutation SetPullRequestReviewers($pullRequestGraphQLId: ID!, $reviewerGraphQLIds: [ID!]!) {
733
734
  requestReviews(input: { pullRequestId: $pullRequestGraphQLId, userIds: $reviewerGraphQLIds, union: true }) {
734
735
  pullRequest {
735
736
  id
@@ -769,7 +770,7 @@ query getBlame($owner: String!, $name: String!, $ref: String!, $path: String!) {
769
770
  login
770
771
  }
771
772
  body
772
- ${!n||B(n,"PR_REVIEW_COMMENT_FULL_DATABASE_ID")?"fullDatabaseId":"databaseId"}
773
+ ${!n||j(n,"PR_REVIEW_COMMENT_FULL_DATABASE_ID")?"fullDatabaseId":"databaseId"}
773
774
  diffHunk
774
775
  id
775
776
  path
@@ -789,7 +790,7 @@ query getBlame($owner: String!, $name: String!, $ref: String!, $path: String!) {
789
790
  login
790
791
  }
791
792
  body
792
- ${!n||B(n,"PR_REVIEW_FULL_DATABASE_ID")?"fullDatabaseId":"databaseId"}
793
+ ${!n||j(n,"PR_REVIEW_FULL_DATABASE_ID")?"fullDatabaseId":"databaseId"}
793
794
  id
794
795
  publishedAt
795
796
  url
@@ -797,13 +798,13 @@ query getBlame($owner: String!, $name: String!, $ref: String!, $path: String!) {
797
798
  }
798
799
  }
799
800
  }
800
- }`,l=await f(this.config,{query:u,variables:{namespace:o,name:i,pullRequestId:a}},r),c=l.body.data?.repository.pullRequest.reviewThreads.nodes?.filter(C).reduce((d,g)=>{if(!g.comments.nodes?.[0]?.pullRequestReview)return d;let m=g.comments.nodes[0].pullRequestReview,y=on(g);return y&&(d[m.id]||(d[m.id]=[]),d[m.id].push(y)),d},{})??{};return{data:l.body.data?.repository.pullRequest.reviews.nodes?.filter(C).filter(d=>c[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:c[d.id],url:d.url}))??[]}}async getCommentsForPullRequest(e,r={}){let n=await this.getEnterpriseVersion(r),o=!n||B(n,"ISSUE_FULL_DATABASE_ID"),{repo:{namespace:i,name:a},pullRequestNumber:u,cursor:l}=e,c=await f(this.config,{query:Gr(o),variables:{namespace:i,name:a,pullRequestNumber:u,cursor:l,first:v}},r),p=c.body.data?.repository;if(!p)throw new h("Could not fetch pull request comments",c.body.errors);return{data:p.pullRequest.comments.nodes?.filter(C).map(Cr)??[],pageInfo:p.pullRequest.comments.pageInfo}}async getIssuesAssociatedWithUser(e,r={}){let[n,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([n==="null"?null:this.searchIssues({query:`author:${e.username} ${i.join(" ")}`,cursor:n,includeFromArchivedRepos:e.includeFromArchivedRepos,maxPageSize:e.maxPageSize},r),o==="null"?null:this.searchIssues({query:`assignee:${e.username} ${i.join(" ")}`,cursor:o,includeFromArchivedRepos:e.includeFromArchivedRepos,maxPageSize:e.maxPageSize},r)]),l={},c=[],p=d=>{l[d.id]||(l[d.id]=!0,c.push(d))};return a?.data.forEach(p),u?.data.forEach(p),{pageInfo:{hasNextPage:a?.pageInfo.hasNextPage||u?.pageInfo.hasNextPage||!1,endCursor:`${a?.pageInfo.hasNextPage&&a?.pageInfo.endCursor||"null"};${u?.pageInfo.hasNextPage&&u?.pageInfo.endCursor||"null"}`},data:c}}async setPullRequestLabels(e,r={}){let{pullRequest:n,labels:o}=e;if(!n.graphQLId)throw new Error('GitHub requires "graphQLId" for this function.');let i=`mutation SetPullRequestLabels($pullRequestGraphQLId: ID!, $labelGraphQLIds: [ID!]) {
801
+ }`,l=await f(this.config,{query:u,variables:{namespace:o,name:i,pullRequestId:a}},r),d=l.body.data?.repository.pullRequest.reviewThreads.nodes?.filter(A).reduce((c,g)=>{if(!g.comments.nodes?.[0]?.pullRequestReview)return c;let m=g.comments.nodes[0].pullRequestReview,y=fn(g);return y&&(c[m.id]||(c[m.id]=[]),c[m.id].push(y)),c},{})??{};return{data:l.body.data?.repository.pullRequest.reviews.nodes?.filter(A).filter(c=>d[c.id]).map(c=>({author:c.author?{avatarUrl:c.author.avatarUrl,email:null,name:c.author.login}:null,body:c.body,createdAt:c.publishedAt?new Date(c.publishedAt):null,id:c.fullDatabaseId??c.databaseId.toString(),graphQLId:c.id,reviewComments:d[c.id],url:c.url}))??[]}}async getCommentsForPullRequest(e,r={}){let n=await this.getEnterpriseVersion(r),o=!n||j(n,"ISSUE_FULL_DATABASE_ID"),{repo:{namespace:i,name:a},pullRequestNumber:u,cursor:l}=e,d=await f(this.config,{query:Br(o),variables:{namespace:i,name:a,pullRequestNumber:u,cursor:l,first:E}},r),p=d.body.data?.repository;if(!p)throw new h("Could not fetch pull request comments",d.body.errors);return{data:p.pullRequest.comments.nodes?.filter(A).map(Gr)??[],pageInfo:p.pullRequest.comments.pageInfo}}async getIssuesAssociatedWithUser(e,r={}){let[n,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([n==="null"?null:this.searchIssues({query:`author:${e.username} ${i.join(" ")}`,cursor:n,includeFromArchivedRepos:e.includeFromArchivedRepos,maxPageSize:e.maxPageSize},r),o==="null"?null:this.searchIssues({query:`assignee:${e.username} ${i.join(" ")}`,cursor:o,includeFromArchivedRepos:e.includeFromArchivedRepos,maxPageSize:e.maxPageSize},r)]),l={},d=[],p=c=>{l[c.id]||(l[c.id]=!0,d.push(c))};return a?.data.forEach(p),u?.data.forEach(p),{pageInfo:{hasNextPage:a?.pageInfo.hasNextPage||u?.pageInfo.hasNextPage||!1,endCursor:`${a?.pageInfo.hasNextPage&&a?.pageInfo.endCursor||"null"};${u?.pageInfo.hasNextPage&&u?.pageInfo.endCursor||"null"}`},data:d}}async setPullRequestLabels(e,r={}){let{pullRequest:n,labels:o}=e;if(!n.graphQLId)throw new Error('GitHub requires "graphQLId" for this function.');let i=`mutation SetPullRequestLabels($pullRequestGraphQLId: ID!, $labelGraphQLIds: [ID!]) {
801
802
  updatePullRequest(input: { pullRequestId: $pullRequestGraphQLId, labelIds: $labelGraphQLIds }) {
802
803
  pullRequest {
803
804
  id
804
805
  }
805
806
  }
806
- }`,a=await f(this.config,{query:i,variables:{pullRequestGraphQLId:n.graphQLId,labelGraphQLIds:o.map(u=>{if(!u.graphQLId)throw new Error('GitHub requires label "graphQLId" for this function.');return u.graphQLId})}},r);if(!a.body.data?.updatePullRequest?.pullRequest?.id)throw new h("Could not set pull request labels",a.body.errors)}async getIssuesForRepos(e,r={}){let n=Dt(e.startQuery||""),{cursor:o,assigneeLogins:i,updatedBefore:a,authorLogin:u,mentionLogin:l,labelNames:c}=e;return e.repos.forEach(p=>{n.push(`repo:${p.namespace}/${p.name}`)}),i&&i.forEach(p=>{n.push(`assignee:${p}`)}),a&&n.push(`updated:<${a}`),u&&n.push(`author:${u}`),l&&n.push(`mentions:${l}`),c&&c.forEach(p=>{n.push(`label:"${p}"`)}),this.searchIssues({query:`sort:updated ${n.join(" ")}`,cursor:o,includeFromArchivedRepos:e.includeFromArchivedRepos,maxPageSize:e.maxPageSize},r)}async closeIssueWithReason(e,r={}){let{issue:n,reason:o}=e;if(!n.graphQLId)throw new Error('GitHub requires "graphQLId" for this function.');let i=`mutation CloseIssueWithReason($issueGraphQLId: ID!, $reason: IssueClosedStateReason!) {
807
+ }`,a=await f(this.config,{query:i,variables:{pullRequestGraphQLId:n.graphQLId,labelGraphQLIds:o.map(u=>{if(!u.graphQLId)throw new Error('GitHub requires label "graphQLId" for this function.');return u.graphQLId})}},r);if(!a.body.data?.updatePullRequest?.pullRequest?.id)throw new h("Could not set pull request labels",a.body.errors)}async getIssuesForRepos(e,r={}){let n=Ut(e.startQuery||""),{cursor:o,assigneeLogins:i,updatedBefore:a,authorLogin:u,mentionLogin:l,labelNames:d}=e;return e.repos.forEach(p=>{n.push(`repo:${p.namespace}/${p.name}`)}),i&&i.forEach(p=>{n.push(`assignee:${p}`)}),a&&n.push(`updated:<${a}`),u&&n.push(`author:${u}`),l&&n.push(`mentions:${l}`),d&&d.forEach(p=>{n.push(`label:"${p}"`)}),this.searchIssues({query:`sort:updated ${n.join(" ")}`,cursor:o,includeFromArchivedRepos:e.includeFromArchivedRepos,maxPageSize:e.maxPageSize},r)}async closeIssueWithReason(e,r={}){let{issue:n,reason:o}=e;if(!n.graphQLId)throw new Error('GitHub requires "graphQLId" for this function.');let i=`mutation CloseIssueWithReason($issueGraphQLId: ID!, $reason: IssueClosedStateReason!) {
807
808
  closeIssue(input: { issueId: $issueGraphQLId, stateReason: $reason }) {
808
809
  issue {
809
810
  id
@@ -844,7 +845,7 @@ query getLabelsForRepo($owner: String!, $name: String! $cursor: String, $first:
844
845
  repository(owner: $owner, name: $name) {
845
846
  milestones(first: $first, after: $cursor) {
846
847
  nodes {
847
- ${Ue}
848
+ ${Ge}
848
849
  }
849
850
  pageInfo {
850
851
  endCursor
@@ -853,12 +854,12 @@ query getLabelsForRepo($owner: String!, $name: String! $cursor: String, $first:
853
854
  }
854
855
  }
855
856
  }
856
- `,variables:{owner:n,name:o,cursor:i,first:v}},r);if(!a.body.data)throw new h("Could not fetch milestones",a.body.errors);return{pageInfo:a.body.data.repository.milestones?.pageInfo??{endCursor:null,hasNextPage:!1},data:a.body.data.repository.milestones?.nodes?.map(Gt)??[]}}async getLabelsForRepo(e,r={}){let{repo:{namespace:n,name:o},cursor:i}=e,a=await f(this.config,{query:`
857
+ `,variables:{owner:n,name:o,cursor:i,first:E}},r);if(!a.body.data)throw new h("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(kt)??[]}}async getLabelsForRepo(e,r={}){let{repo:{namespace:n,name:o},cursor:i}=e,a=await f(this.config,{query:`
857
858
  query getLabelsForRepo($owner: String!, $name: String! $cursor: String, $first: Int!) {
858
859
  repository(owner: $owner, name: $name) {
859
860
  labels(first: $first, after: $cursor) {
860
861
  nodes {
861
- ${$e}
862
+ ${Te}
862
863
  }
863
864
  pageInfo {
864
865
  endCursor
@@ -867,7 +868,7 @@ query getLabelsForRepo($owner: String!, $name: String! $cursor: String, $first:
867
868
  }
868
869
  }
869
870
  }
870
- `,variables:{owner:n,name:o,cursor:i,first:v}},r);if(!a.body.data)throw new h("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(Tt)??[]}}async getTreeForRepo(e,r={}){let n=await this.config.request({url:`${ee(this.config,r)}/repos/${e.repo.namespace}/${e.repo.name}/git/trees/${e.branch}?recursive=1`,headers:{...I(r.token||this.config.token)}});if(!n.body)throw new Error("Could not fetch trees");return{data:n.body.tree.map(en)}}};var ln="https://gitlab.com/api/v4",pn="https://gitlab.com/api/graphql",Ot=/\/api\/v\d+$/,kr=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.")},Oe=(s,t)=>{let e=t.baseUrl||s.baseUrl;return e?(e=e.replace(/\/$/,""),kr(e),Ot.test(e)||(e=e+"/api/v4"),e):ln},dn=(s,t)=>{let e=t.baseUrl||s.baseUrl;return e?(e=e.replace(/\/$/,""),kr(e),Ot.test(e)&&(e=e.replace(Ot,"")),`${e}/api/graphql`):pn},b=(s,t,e)=>{let r=I(e.token||s.token);return s.request({url:dn(s,e),method:"POST",headers:{...r,"Content-Type":"application/json"},body:JSON.stringify(t)})},xe=s=>s?.map(t=>`"${t.message}"`).join(", ");var Bt=s=>s.split("/").slice(0,-1).join("/"),Qt=s=>s.split("/").at(-1)??"",ke=s=>({id:s.id.replace(ie,""),graphQLId:s.id,namespace:Bt(s.fullPath),name:Qt(s.fullPath),webUrl:s.webUrl}),Nr=s=>({id:s.id.replace(ie,""),graphQLId:s.id,httpsUrl:s.httpUrlToRepo,namespace:Bt(s.fullPath),name:Qt(s.fullPath),sshUrl:s.sshUrlToRepo,webUrl:s.webUrl}),cn={assigned:"assignedMergeRequests",authored:"authoredMergeRequests",reviewRequested:"reviewRequestedMergeRequests"},gn={CAN_BE_MERGED:"MERGEABLE",CANNOT_BE_MERGED:"CONFLICTS",CANNOT_BE_MERGED_RECHECK:"UNKNOWN",UNCHECKED:"UNKNOWN",CHECKING:"UNKNOWN"};var mn="gid://gitlab/User/",ie="gid://gitlab/Project/",hn="gid://gitlab/MergeRequest/",fn="gid://gitlab/Issue/",In="gid://gitlab/ProjectLabel/",Rn="gid://gitlab/Milestone/",yn="gid://gitlab/Ci::Build/",jt=`
871
+ `,variables:{owner:n,name:o,cursor:i,first:E}},r);if(!a.body.data)throw new h("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(xt)??[]}}async getTreeForRepo(e,r={}){let n=await this.config.request({url:`${re(this.config,r)}/repos/${e.repo.namespace}/${e.repo.name}/git/trees/${e.branch}?recursive=1`,headers:{...I(r.token||this.config.token)}});if(!n.body)throw new Error("Could not fetch trees");return{data:n.body.tree.map(dn)}}};var yn="https://gitlab.com/api/v4",bn="https://gitlab.com/api/graphql",Nt=/\/api\/v\d+$/,Fr=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.")},ke=(s,t)=>{let e=t.baseUrl||s.baseUrl;return e?(e=e.replace(/\/$/,""),Fr(e),Nt.test(e)||(e=e+"/api/v4"),e):yn},Pn=(s,t)=>{let e=t.baseUrl||s.baseUrl;return e?(e=e.replace(/\/$/,""),Fr(e),Nt.test(e)&&(e=e.replace(Nt,"")),`${e}/api/graphql`):bn},P=(s,t,e)=>{let r=I(e.token||s.token);return s.request({url:Pn(s,e),method:"POST",headers:{...r,"Content-Type":"application/json"},body:JSON.stringify(t)})},Ne=s=>s?.map(t=>`"${t.message}"`).join(", ");var Ft=s=>s.split("/").slice(0,-1).join("/"),Mt=s=>s.split("/").at(-1)??"",_e=s=>({id:s.id.replace(pe,""),graphQLId:s.id,namespace:Ft(s.fullPath),name:Mt(s.fullPath),webUrl:s.webUrl}),Mr=s=>({id:s.id.replace(pe,""),graphQLId:s.id,httpsUrl:s.httpUrlToRepo,namespace:Ft(s.fullPath),name:Mt(s.fullPath),sshUrl:s.sshUrlToRepo,webUrl:s.webUrl}),wn={assigned:"assignedMergeRequests",authored:"authoredMergeRequests",reviewRequested:"reviewRequestedMergeRequests"},vn={CAN_BE_MERGED:"MERGEABLE",CANNOT_BE_MERGED:"CONFLICTS",CANNOT_BE_MERGED_RECHECK:"UNKNOWN",UNCHECKED:"UNKNOWN",CHECKING:"UNKNOWN"};var En="gid://gitlab/User/",pe="gid://gitlab/Project/",qn="gid://gitlab/MergeRequest/",Sn="gid://gitlab/Issue/",Cn="gid://gitlab/ProjectLabel/",Dn="gid://gitlab/Milestone/",An="gid://gitlab/Ci::Build/",zt=`
871
872
  description
872
873
  dueDate
873
874
  id
@@ -876,7 +877,7 @@ startDate
876
877
  state
877
878
  title
878
879
  webPath
879
- `,xt=`
880
+ `,_t=`
880
881
  id
881
882
  fullPath
882
883
  webUrl
@@ -890,25 +891,25 @@ userPermissions {
890
891
  downloadCode
891
892
  pushCode
892
893
  }
893
- `,z=`
894
+ `,V=`
894
895
  id
895
896
  name
896
897
  username
897
898
  publicEmail
898
899
  avatarUrl
899
900
  webUrl
900
- `,Ft=`
901
+ `,Wt=`
901
902
  color
902
903
  description
903
904
  id
904
905
  title
905
- `,kt=`
906
+ `,Bt=`
906
907
  author {
907
- ${z}
908
+ ${V}
908
909
  }
909
910
  assignees {
910
911
  nodes {
911
- ${z}
912
+ ${V}
912
913
  }
913
914
  }
914
915
  closedAt
@@ -919,7 +920,7 @@ id
919
920
  iid
920
921
  labels {
921
922
  nodes {
922
- ${Ft}
923
+ ${Wt}
923
924
  }
924
925
  }
925
926
  state
@@ -930,9 +931,9 @@ upvotes
930
931
  userNotesCount
931
932
  webUrl
932
933
  milestone {
933
- ${jt}
934
+ ${zt}
934
935
  }
935
- `,bn=`
936
+ `,Ln=`
936
937
  stages {
937
938
  nodes {
938
939
  jobs {
@@ -948,11 +949,11 @@ stages {
948
949
  name
949
950
  }
950
951
  }
951
- `,_r=(s,t,e)=>`
952
+ `,zr=(s,t,e)=>`
952
953
  id
953
954
  state
954
955
  author {
955
- ${z}
956
+ ${V}
956
957
  }
957
958
  diffRefs {
958
959
  baseSha
@@ -978,12 +979,12 @@ targetBranch
978
979
  sourceBranch
979
980
  assignees {
980
981
  nodes {
981
- ${z}
982
+ ${V}
982
983
  }
983
984
  }
984
985
  reviewers {
985
986
  nodes {
986
- ${z}
987
+ ${V}
987
988
  mergeRequestInteraction {
988
989
  approved
989
990
  reviewState
@@ -993,19 +994,19 @@ reviewers {
993
994
  mergeStatusEnum
994
995
  labels {
995
996
  nodes {
996
- ${Ft}
997
+ ${Wt}
997
998
  }
998
999
  }
999
1000
  ${s?"project { id httpUrlToRepo fullPath sshUrlToRepo webUrl archived } sourceProject { id httpUrlToRepo fullPath sshUrlToRepo webUrl }":""}
1000
- ${t?`milestone { ${jt} }`:""}
1001
- ${e?`headPipeline { ${bn} }`:""}
1002
- `,K=s=>`${s.namespace}/${s.name}`,Pn=s=>`${s.namespace}/${s.name}`,wn=s=>({canCreateWebhook:s.adminOperations,canPush:s.pushCode,isAdmin:s.adminOperations}),Nt=s=>({id:s.id.replace(ie,""),graphQLId:s.id,namespace:Bt(s.fullPath),name:Qt(s.fullPath),webUrl:s.webUrl,httpsUrl:s.httpUrlToRepo,sshUrl:s.sshUrlToRepo,defaultBranch:s.repository?.rootRef?{name:s.repository.rootRef}:null,permissions:wn(s.userPermissions)}),vn=s=>({path:s.path,isDirectory:s.type==="tree"}),En={opened:"OPEN",merged:"MERGED",closed:"CLOSED"},Qr=(s,t,e)=>!t&&s?.startsWith("/")?`https://gitlab.com${s}`:t&&s?.startsWith("/")&&e?`${e.replace(/\/+?$/,"")}${s}`:s,W=(s,t,e)=>{let r=Qr(s.avatarUrl,t,e);return{id:s.id.replace(mn,""),graphQLId:s.id,name:s.name,username:s.username,email:s.publicEmail??null,avatarUrl:r,url:s.webUrl}},Mt=s=>({color:s.color,description:s.description,id:s.id.replace(In,""),graphQLId:s.id,name:s.title}),qn=(s,t)=>s?s==="FAILED"&&t?"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,Sn=(s,t,e)=>{let r={APPROVED:"APPROVED",REQUESTED_CHANGES:"CHANGES_REQUESTED",REVIEWED:"COMMENTED",UNAPPROVED:"REVIEW_REQUESTED",UNREVIEWED:"REVIEW_REQUESTED"};return{reviewer:W(s,t,e),state:s.mergeRequestInteraction?.reviewState?r[s.mergeRequestInteraction.reviewState]:"REVIEW_REQUESTED"}},Br=(s,t,e,r,n)=>{let o=s.reviewers?.nodes?s.reviewers.nodes.map(i=>Sn(i,r,n)):null;return{id:s.id.replace(hn,""),graphQLId:s.id,title:s.title,description:s.description,number:parseInt(s.iid,10),state:En[s.state],commentCount:s.userNotesCount||0,upvoteCount:s.upvotes,author:s.author?W(s.author,r,n):null,createdDate:new Date(s.createdAt),isDraft:s.draft,repository:{id:t.id,graphQLId:t.graphQLId,name:t.name,owner:{login:t.namespace},remoteInfo:t.httpsUrl&&t.sshUrl?{cloneUrlHTTPS:t.httpsUrl,cloneUrlSSH:t.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:qn(a.status,a.allowFailure),stage:i.name??null,startedAt:new Date(a.createdAt),url:`${t.webUrl}/-/jobs/${a.id.replace(yn,"")}`}))??[])??[]},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=>W(i,r,n)):null,reviews:o,reviewDecision:_(o),additions:s.diffStatsSummary?.additions||0,deletions:s.diffStatsSummary?.deletions||0,fileCount:s.diffStatsSummary?.fileCount||0,commitCount:s.commitCount||0,mergeableState:gn[s.mergeStatusEnum],milestone:s.milestone?zt(s.milestone,t.webUrl):null,labels:s.labels?.nodes?.map(Mt)??[],permissions:null}},_t=(s,t,e,r)=>({author:W(s.author,e,r),assignees:s.assignees.nodes.map(n=>W(n,e,r)),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(fn,""),labels:s.labels?.nodes?.map(Mt)??[],number:s.iid,repository:{id:t.id.replace(ie,""),graphQLId:t.id,name:t.name,owner:{login:t.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?zt(s.milestone,t.webUrl):null}),zt=(s,t)=>({id:s.id.replace(Rn,""),graphQLId:s.id,number:parseInt(s.iid,10),title:s.title,description:s.description,isOpen:s.state==="active",url:`${t}/-/${s.webPath.replace(/.+?\/-\//,"")}`,startDate:s.startDate?new Date(s.startDate):null,dueDate:s.dueDate?new Date(s.dueDate):null}),ae=class extends ${getIsSelfHosted(t){return!!t.baseUrl||!!this.config.baseUrl}async getCurrentUser(t={},e={}){let n=(await b(this.config,{query:`
1001
+ ${t?`milestone { ${zt} }`:""}
1002
+ ${e?`headPipeline { ${Ln} }`:""}
1003
+ `,Y=s=>`${s.namespace}/${s.name}`,Un=s=>`${s.namespace}/${s.name}`,$n=s=>({canCreateWebhook:s.adminOperations,canPush:s.pushCode,isAdmin:s.adminOperations}),Qt=s=>({id:s.id.replace(pe,""),graphQLId:s.id,namespace:Ft(s.fullPath),name:Mt(s.fullPath),webUrl:s.webUrl,httpsUrl:s.httpUrlToRepo,sshUrl:s.sshUrlToRepo,defaultBranch:s.repository?.rootRef?{name:s.repository.rootRef}:null,permissions:$n(s.userPermissions)}),Gn=s=>({path:s.path,isDirectory:s.type==="tree"}),Tn={opened:"OPEN",merged:"MERGED",closed:"CLOSED"},Hr=(s,t,e)=>!t&&s?.startsWith("/")?`https://gitlab.com${s}`:t&&s?.startsWith("/")&&e?`${e.replace(/\/+?$/,"")}${s}`:s,J=(s,t,e)=>{let r=Hr(s.avatarUrl,t,e);return{id:s.id.replace(En,""),graphQLId:s.id,name:s.name,username:s.username,email:s.publicEmail??null,avatarUrl:r,url:s.webUrl}},Ht=s=>({color:s.color,description:s.description,id:s.id.replace(Cn,""),graphQLId:s.id,name:s.title}),On=(s,t)=>s?s==="FAILED"&&t?"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,xn=(s,t,e)=>{let r={APPROVED:"APPROVED",REQUESTED_CHANGES:"CHANGES_REQUESTED",REVIEWED:"COMMENTED",UNAPPROVED:"REVIEW_REQUESTED",UNREVIEWED:"REVIEW_REQUESTED"};return{reviewer:J(s,t,e),state:s.mergeRequestInteraction?.reviewState?r[s.mergeRequestInteraction.reviewState]:"REVIEW_REQUESTED"}},Wr=(s,t,e,r,n)=>{let o=s.reviewers?.nodes?s.reviewers.nodes.map(i=>xn(i,r,n)):null;return{id:s.id.replace(qn,""),graphQLId:s.id,title:s.title,description:s.description,number:parseInt(s.iid,10),state:Tn[s.state],commentCount:s.userNotesCount||0,upvoteCount:s.upvotes,author:s.author?J(s.author,r,n):null,createdDate:new Date(s.createdAt),isDraft:s.draft,repository:{id:t.id,graphQLId:t.graphQLId,name:t.name,owner:{login:t.namespace},remoteInfo:t.httpsUrl&&t.sshUrl?{cloneUrlHTTPS:t.httpsUrl,cloneUrlSSH:t.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:On(a.status,a.allowFailure),stage:i.name??null,startedAt:new Date(a.createdAt),url:`${t.webUrl}/-/jobs/${a.id.replace(An,"")}`}))??[])??[]},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,r,n)):null,reviews:o,reviewDecision:Q(o),additions:s.diffStatsSummary?.additions||0,deletions:s.diffStatsSummary?.deletions||0,fileCount:s.diffStatsSummary?.fileCount||0,commitCount:s.commitCount||0,mergeableState:vn[s.mergeStatusEnum],milestone:s.milestone?Vt(s.milestone,t.webUrl):null,labels:s.labels?.nodes?.map(Ht)??[],permissions:null}},jt=(s,t,e,r)=>({author:J(s.author,e,r),assignees:s.assignees.nodes.map(n=>J(n,e,r)),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(Sn,""),labels:s.labels?.nodes?.map(Ht)??[],number:s.iid,repository:{id:t.id.replace(pe,""),graphQLId:t.id,name:t.name,owner:{login:t.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?Vt(s.milestone,t.webUrl):null}),Vt=(s,t)=>({id:s.id.replace(Dn,""),graphQLId:s.id,number:parseInt(s.iid,10),title:s.title,description:s.description,isOpen:s.state==="active",url:`${t}/-/${s.webPath.replace(/.+?\/-\//,"")}`,startDate:s.startDate?new Date(s.startDate):null,dueDate:s.dueDate?new Date(s.dueDate):null}),de=class extends G{getIsSelfHosted(t){return!!t.baseUrl||!!this.config.baseUrl}async getCurrentUser(t={},e={}){let n=(await P(this.config,{query:`
1003
1004
  query getCurrentUser {
1004
1005
  currentUser {
1005
- ${z}
1006
+ ${V}
1006
1007
  }
1007
1008
  }
1008
- `},e)).body.data?.currentUser;if(!n)throw new Error("Current user not found.");return{data:W(n,this.getIsSelfHosted(e),this.config.baseUrl??e.baseUrl)}}async getUserForCommit(t,e={}){let r=K(t.repo),o=(await b(this.config,{query:`
1009
+ `},e)).body.data?.currentUser;if(!n)throw new Error("Current user not found.");return{data:J(n,this.getIsSelfHosted(e),this.config.baseUrl??e.baseUrl)}}async getUserForCommit(t,e={}){let r=Y(t.repo),o=(await P(this.config,{query:`
1009
1010
  query getUserForCommit($fullPath: ID!, $oid: String!) {
1010
1011
  project(fullPath: $fullPath) {
1011
1012
  repository {
@@ -1021,21 +1022,21 @@ query getUserForCommit($fullPath: ID!, $oid: String!) {
1021
1022
  }
1022
1023
  }
1023
1024
  }
1024
- `,variables:{fullPath:r,oid:t.oid}},e)).body.data?.project?.repository?.tree?.lastCommit;if(!o)throw new Error("Commit not found.");let i=Qr(o.author.avatarUrl,this.getIsSelfHosted(e),this.config.baseUrl??e.baseUrl);return{data:{name:o.authorName,email:o.authorEmail,avatarUrl:i}}}async getAccountForEmail(t,e={}){let n=(await b(this.config,{query:`
1025
+ `,variables:{fullPath:r,oid:t.oid}},e)).body.data?.project?.repository?.tree?.lastCommit;if(!o)throw new Error("Commit not found.");let i=Hr(o.author.avatarUrl,this.getIsSelfHosted(e),this.config.baseUrl??e.baseUrl);return{data:{name:o.authorName,email:o.authorEmail,avatarUrl:i}}}async getAccountForEmail(t,e={}){let n=(await P(this.config,{query:`
1025
1026
  query getAccountForEmail($email: String!) {
1026
1027
  users(search: $email) {
1027
1028
  nodes {
1028
- ${z}
1029
+ ${V}
1029
1030
  }
1030
1031
  }
1031
1032
  }
1032
- `,variables:{email:t.email}},e)).body.data?.users?.nodes?.[0];if(!n)throw new Error("User not found.");return{data:W(n,this.getIsSelfHosted(e),this.config.baseUrl??e.baseUrl)}}async getAccountForUsername(t,e={}){let n=(await b(this.config,{query:`
1033
+ `,variables:{email:t.email}},e)).body.data?.users?.nodes?.[0];if(!n)throw new Error("User not found.");return{data:J(n,this.getIsSelfHosted(e),this.config.baseUrl??e.baseUrl)}}async getAccountForUsername(t,e={}){let n=(await P(this.config,{query:`
1033
1034
  query getAccountForUsername($username: String!) {
1034
1035
  user(username: $username) {
1035
- ${z}
1036
+ ${V}
1036
1037
  }
1037
1038
  }
1038
- `,variables:{username:t.username}},e)).body.data?.user;if(!n)throw new Error("User not found.");return{data:W(n,this.getIsSelfHosted(e),this.config.baseUrl??e.baseUrl)}}async getAccountsForRepo(t,e={}){let{repo:{namespace:r,name:n},cursor:o}=t,i=await b(this.config,{query:`
1039
+ `,variables:{username:t.username}},e)).body.data?.user;if(!n)throw new Error("User not found.");return{data:J(n,this.getIsSelfHosted(e),this.config.baseUrl??e.baseUrl)}}async getAccountsForRepo(t,e={}){let{repo:{namespace:r,name:n},cursor:o}=t,i=await P(this.config,{query:`
1039
1040
  query getAccountsForRepo(
1040
1041
  $fullPath: ID!
1041
1042
  $after: String
@@ -1046,7 +1047,7 @@ query getAccountsForRepo(
1046
1047
  projectMembers(after: $after) {
1047
1048
  nodes {
1048
1049
  user {
1049
- ${z}
1050
+ ${V}
1050
1051
  }
1051
1052
  }
1052
1053
  pageInfo {
@@ -1056,22 +1057,22 @@ query getAccountsForRepo(
1056
1057
  }
1057
1058
  }
1058
1059
  }
1059
- `,variables:{fullPath:`${r}/${n}`,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=>W(u,this.getIsSelfHosted(e),this.config.baseUrl??e.baseUrl))??[]}}async getRepo(t,e={}){let r=K(t),n=await b(this.config,{query:`
1060
+ `,variables:{fullPath:`${r}/${n}`,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(t,e={}){let r=Y(t),n=await P(this.config,{query:`
1060
1061
  query getRepo($fullPath: ID!) {
1061
1062
  project(fullPath: $fullPath) {
1062
- ${xt}
1063
+ ${_t}
1063
1064
  }
1064
1065
  }
1065
- `,variables:{fullPath:r}},e);if(!n.body.data?.project)throw new Error(`Repository ${r} not found`);return{data:Nt(n.body.data.project)}}async getReposBase(t,e={}){let n=t.map(K).map((u,l)=>`
1066
+ `,variables:{fullPath:r}},e);if(!n.body.data?.project)throw new Error(`Repository ${r} not found`);return{data:Qt(n.body.data.project)}}async getReposBase(t,e={}){let n=t.map(Y).map((u,l)=>`
1066
1067
  getRepo_${l}: project(fullPath: "${u}") {
1067
- ${xt}
1068
+ ${_t}
1068
1069
  }
1069
1070
  `).join(`
1070
- `),o=await b(this.config,{query:`
1071
+ `),o=await P(this.config,{query:`
1071
1072
  query batchGetRepos {
1072
1073
  ${n}
1073
1074
  }
1074
- `},e);if(!o.body.data)throw new Error(xe(o.body.errors)||o.statusText||"Unknown error");let i=[],a=[];return t.forEach((u,l)=>{let c=o.body.data[`getRepo_${l}`];c?i.push(Nt(c)):a.push({input:u})}),{data:i,errors:a}}async getRepos(t,e={}){let r=[];for(let i=0;i<t.length;i+=15)r.push(t.slice(i,i+15));return(await Promise.all(r.map(i=>this.getReposBase(i,e)))).reduce((i,a)=>({data:[...i.data,...a.data],errors:[...i.errors,...a.errors]}),{data:[],errors:[]})}async getReposForCurrentUser(t,e={}){let r=await b(this.config,{query:`
1075
+ `},e);if(!o.body.data)throw new Error(Ne(o.body.errors)||o.statusText||"Unknown error");let i=[],a=[];return t.forEach((u,l)=>{let d=o.body.data[`getRepo_${l}`];d?i.push(Qt(d)):a.push({input:u})}),{data:i,errors:a}}async getRepos(t,e={}){let r=[];for(let i=0;i<t.length;i+=15)r.push(t.slice(i,i+15));return(await Promise.all(r.map(i=>this.getReposBase(i,e)))).reduce((i,a)=>({data:[...i.data,...a.data],errors:[...i.errors,...a.errors]}),{data:[],errors:[]})}async getReposForCurrentUser(t,e={}){let r=await P(this.config,{query:`
1075
1076
  query getReposForCurrentUser($after: String) {
1076
1077
  projects(membership: true first: 100 after: $after) {
1077
1078
  pageInfo {
@@ -1079,11 +1080,11 @@ query getReposForCurrentUser($after: String) {
1079
1080
  hasNextPage
1080
1081
  }
1081
1082
  nodes {
1082
- ${xt}
1083
+ ${_t}
1083
1084
  }
1084
1085
  }
1085
1086
  }
1086
- `,variables:{after:t.cursor}},e);if(!r.body.data?.projects)throw new Error(xe(r.body.errors)||r.statusText||"Unknown error");let n=r.body.data?.projects?.nodes||[];return{pageInfo:r.body.data?.projects?.pageInfo,data:n.map(Nt)}}async getRefs(t,e,r={}){let n=K(e.repo),o=new URL(`${Oe(this.config,r)}/projects/${encodeURIComponent(n)}/repository/${t}`);o.searchParams.set("page",e.page?.toString()||"1"),o.searchParams.set("per_page",v.toString());let i=await this.config.request({url:o.toString(),headers:I(r.token||this.config.token)}),a=i.headers["x-next-page"];return{pageInfo:{hasNextPage:!!a,nextPage:a?parseInt(a,10):null},data:i.body.map(u=>({name:u.name,commit:{oid:u.commit.id,authoredDate:new Date(u.commit.authored_date),committedDate:new Date(u.commit.committed_date)}}))}}async getBranches(t,e={}){return this.getRefs("branches",t,e)}async getTags(t,e={}){return this.getRefs("tags",t,e)}async getBlame(t,e={}){let r=K(t.repo),n=new URL(`${Oe(this.config,e)}/projects/${encodeURIComponent(r)}/repository/files/${encodeURIComponent(t.path)}/blame`);n.searchParams.set("ref",t.ref);let o=await this.config.request({url:n.toString(),headers:I(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(t,e={}){let r="";t.repo?.id?r=`projectId:"${t.repo.id}"`:t.repo?.namespace&&t.repo?.name&&(r=`projectPath:"${t.repo.namespace}/${t.repo.name}"`);let n=cn[t.association],o=await b(this.config,{query:`
1087
+ `,variables:{after:t.cursor}},e);if(!r.body.data?.projects)throw new Error(Ne(r.body.errors)||r.statusText||"Unknown error");let n=r.body.data?.projects?.nodes||[];return{pageInfo:r.body.data?.projects?.pageInfo,data:n.map(Qt)}}async getRefs(t,e,r={}){let n=Y(e.repo),o=new URL(`${ke(this.config,r)}/projects/${encodeURIComponent(n)}/repository/${t}`);o.searchParams.set("page",e.page?.toString()||"1"),o.searchParams.set("per_page",E.toString());let i=await this.config.request({url:o.toString(),headers:I(r.token||this.config.token)}),a=i.headers["x-next-page"];return{pageInfo:{hasNextPage:!!a,nextPage:a?parseInt(a,10):null},data:i.body.map(u=>({name:u.name,commit:{oid:u.commit.id,authoredDate:new Date(u.commit.authored_date),committedDate:new Date(u.commit.committed_date)}}))}}async getBranches(t,e={}){return this.getRefs("branches",t,e)}async getTags(t,e={}){return this.getRefs("tags",t,e)}async getBlame(t,e={}){let r=Y(t.repo),n=new URL(`${ke(this.config,e)}/projects/${encodeURIComponent(r)}/repository/files/${encodeURIComponent(t.path)}/blame`);n.searchParams.set("ref",t.ref);let o=await this.config.request({url:n.toString(),headers:I(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(t,e={}){let r="";t.repo?.id?r=`projectId:"${t.repo.id}"`:t.repo?.namespace&&t.repo?.name&&(r=`projectPath:"${t.repo.namespace}/${t.repo.name}"`);let n=wn[t.association],o=await P(this.config,{query:`
1087
1088
  query getPullRequestsForUser($username: String! $cursor: String $labelNames: [String!]) {
1088
1089
  user(username: $username) {
1089
1090
  ${n}(state:opened first:100 after:$cursor labels: $labelNames${r?` ${r}`:""}) {
@@ -1092,12 +1093,12 @@ query getPullRequestsForUser($username: String! $cursor: String $labelNames: [St
1092
1093
  hasNextPage
1093
1094
  }
1094
1095
  nodes {
1095
- ${_r(!0,!0,!0)}
1096
+ ${zr(!0,!0,!0)}
1096
1097
  }
1097
1098
  }
1098
1099
  }
1099
1100
  }
1100
- `,variables:{username:t.username,cursor:t.cursor,labelNames:t.labelNames}},e);if(!o.body.data)throw new Error(xe(o.body.errors)||o.statusText||"Unknown error");if(!o.body.data.user)throw new Error("User not found");let i=o.body.data.user[n];if(!i)throw new Error("Unexpected response");return{pageInfo:i.pageInfo,data:i.nodes?.filter(a=>t.includeFromArchivedRepos||!a.project.archived).map(a=>Br(a,Nr(a.project),Nr(a.sourceProject),this.getIsSelfHosted(e),this.config.baseUrl??e.baseUrl))||[]}}async getPullRequestsAssociatedWithUser(t,e={}){let[r,n,o]=t.cursor?.split(";")||[void 0,void 0,void 0],i=r?.split("-")||[],a=n?.split("-")||[],u=o?.split("-")||[],l=[],c=[],p=[],d=0;do{let E=t.repos&&t.repos[d];i[d]==="null"?l.push(null):l.push(this.getPullRequestsForUser({username:t.username,association:"authored",cursor:i[d],includeFromArchivedRepos:t.includeFromArchivedRepos,labelNames:t.labelNames,...E&&{repo:E}},e)),a[d]==="null"?c.push(null):c.push(this.getPullRequestsForUser({username:t.username,association:"assigned",cursor:a[d],includeFromArchivedRepos:t.includeFromArchivedRepos,labelNames:t.labelNames,...E&&{repo:E}},e)),u[d]==="null"?p.push(null):p.push(this.getPullRequestsForUser({username:t.username,association:"reviewRequested",cursor:u[d],includeFromArchivedRepos:t.includeFromArchivedRepos,labelNames:t.labelNames,...E&&{repo:E}},e)),d++}while(d<(t.repos?.length||0));let g=[l,c,p].flat(),m=await Promise.all(g),y={},R=[],L=E=>{y[E.id]||(y[E.id]=!0,R.push(E))},V=!1,be=m.map((E,ce)=>{let ge="";return E&&E.data.forEach(L),E?.pageInfo.hasNextPage?(V=!0,ge+=`${E.pageInfo.endCursor||"null"}`):ge+="null",t.repos?.length&&(ce+1)%t.repos.length!==0?ge+="-":ce+1<m.length&&(ge+=";"),ge}).join("");return{pageInfo:{hasNextPage:V,endCursor:be},data:R}}getVariablesForPullRequests(t){let{updatedBefore:e,isDraft:r,authorLogin:n,assigneeLogins:o,labelNames:i,reviewRequestedLogin:a}=t||{},u={},l=[],c=[],p=(d,g,m)=>{l.push(`$${d}: ${m}`),c.push(`${d}: $${d}`),u[d]=g};return e&&p("updatedBefore",e,"Time"),n&&p("authorUsername",n,"String"),o&&p("assigneeUsername",o[0],"String"),i&&p("labelName",i,"[String]"),r!=null&&p("draft",r,"Boolean"),a&&p("reviewerUsername",a,"String"),{variables:u,variableTypes:l,mergeRequestArguments:c}}async getPullRequestsForRepoBase(t,e={},r){let{cursor:n,repo:o}=t||{},i=K(o),{variables:a,variableTypes:u,mergeRequestArguments:l}=this.getVariablesForPullRequests(t),c={fullPath:i,...a},p=await b(this.config,{query:`
1101
+ `,variables:{username:t.username,cursor:t.cursor,labelNames:t.labelNames}},e);if(!o.body.data)throw new Error(Ne(o.body.errors)||o.statusText||"Unknown error");if(!o.body.data.user)throw new Error("User not found");let i=o.body.data.user[n];if(!i)throw new Error("Unexpected response");return{pageInfo:i.pageInfo,data:i.nodes?.filter(a=>t.includeFromArchivedRepos||!a.project.archived).map(a=>Wr(a,Mr(a.project),Mr(a.sourceProject),this.getIsSelfHosted(e),this.config.baseUrl??e.baseUrl))||[]}}async getPullRequestsAssociatedWithUser(t,e={}){let[r,n,o]=t.cursor?.split(";")||[void 0,void 0,void 0],i=r?.split("-")||[],a=n?.split("-")||[],u=o?.split("-")||[],l=[],d=[],p=[],c=0;do{let v=t.repos&&t.repos[c];i[c]==="null"?l.push(null):l.push(this.getPullRequestsForUser({username:t.username,association:"authored",cursor:i[c],includeFromArchivedRepos:t.includeFromArchivedRepos,labelNames:t.labelNames,...v&&{repo:v}},e)),a[c]==="null"?d.push(null):d.push(this.getPullRequestsForUser({username:t.username,association:"assigned",cursor:a[c],includeFromArchivedRepos:t.includeFromArchivedRepos,labelNames:t.labelNames,...v&&{repo:v}},e)),u[c]==="null"?p.push(null):p.push(this.getPullRequestsForUser({username:t.username,association:"reviewRequested",cursor:u[c],includeFromArchivedRepos:t.includeFromArchivedRepos,labelNames:t.labelNames,...v&&{repo:v}},e)),c++}while(c<(t.repos?.length||0));let g=[l,d,p].flat(),m=await Promise.all(g),y={},R=[],D=v=>{y[v.id]||(y[v.id]=!0,R.push(v))},x=!1,se=m.map((v,q)=>{let z="";return v&&v.data.forEach(D),v?.pageInfo.hasNextPage?(x=!0,z+=`${v.pageInfo.endCursor||"null"}`):z+="null",t.repos?.length&&(q+1)%t.repos.length!==0?z+="-":q+1<m.length&&(z+=";"),z}).join("");return{pageInfo:{hasNextPage:x,endCursor:se},data:R}}getVariablesForPullRequests(t){let{updatedBefore:e,isDraft:r,authorLogin:n,assigneeLogins:o,labelNames:i,reviewRequestedLogin:a}=t||{},u={},l=[],d=[],p=(c,g,m)=>{l.push(`$${c}: ${m}`),d.push(`${c}: $${c}`),u[c]=g};return e&&p("updatedBefore",e,"Time"),n&&p("authorUsername",n,"String"),o&&p("assigneeUsername",o[0],"String"),i&&p("labelName",i,"[String]"),r!=null&&p("draft",r,"Boolean"),a&&p("reviewerUsername",a,"String"),{variables:u,variableTypes:l,mergeRequestArguments:d}}async getPullRequestsForRepoBase(t,e={},r){let{cursor:n,repo:o}=t||{},i=Y(o),{variables:a,variableTypes:u,mergeRequestArguments:l}=this.getVariablesForPullRequests(t),d={fullPath:i,...a},p=await P(this.config,{query:`
1101
1102
  query getPullRequestsForRepo(
1102
1103
  $fullPath: ID!
1103
1104
  $after: String
@@ -1122,19 +1123,19 @@ query getPullRequestsForRepo(
1122
1123
  hasNextPage
1123
1124
  }
1124
1125
  nodes {
1125
- ${_r(!1,!0,!0)}
1126
+ ${zr(!1,!0,!0)}
1126
1127
  }
1127
1128
  }
1128
1129
  }
1129
1130
  }
1130
- `,variables:{...c,after:n}},e),d=[],g=p.body.data?.project;if(!r&&g?.archived)return{pageInfo:null,data:[]};let m=ke(g||{id:"",fullPath:"",webUrl:""});return(g?.mergeRequests?.nodes||[]).forEach(R=>{d.push(Br(R,m,null,this.getIsSelfHosted(e),this.config.baseUrl??e.baseUrl))}),{pageInfo:g?.mergeRequests?.pageInfo,data:d}}async getPullRequestsForRepo(t,e={}){return this.getPullRequestsForRepoBase(t,e,!1)}async getPullRequestsForRepos(t,e={}){let{repos:r,assigneeLogins:n,updatedBefore:o,authorLogin:i,labelNames:a,isDraft:u,reviewRequestedLogin:l}=t;return{data:(await Promise.all(r.map(p=>this.getPullRequestsForRepoBase({repo:p,assigneeLogins:n,updatedBefore:o,authorLogin:i,labelNames:a,isDraft:u,reviewRequestedLogin:l},e,t.includeFromArchivedRepos??!1)))).flatMap(p=>p.data)}}async closePullRequest(t,e={}){let{pullRequest:r}=t,n=`mutation ClosePullRequest($fullPath: ID!, $pullRequestId: String!) {
1131
+ `,variables:{...d,after:n}},e),c=[],g=p.body.data?.project;if(!r&&g?.archived)return{pageInfo:null,data:[]};let m=_e(g||{id:"",fullPath:"",webUrl:""});return(g?.mergeRequests?.nodes||[]).forEach(R=>{c.push(Wr(R,m,null,this.getIsSelfHosted(e),this.config.baseUrl??e.baseUrl))}),{pageInfo:g?.mergeRequests?.pageInfo,data:c}}async getPullRequestsForRepo(t,e={}){return this.getPullRequestsForRepoBase(t,e,!1)}async getPullRequestsForRepos(t,e={}){let{repos:r,assigneeLogins:n,updatedBefore:o,authorLogin:i,labelNames:a,isDraft:u,reviewRequestedLogin:l}=t;return{data:(await Promise.all(r.map(p=>this.getPullRequestsForRepoBase({repo:p,assigneeLogins:n,updatedBefore:o,authorLogin:i,labelNames:a,isDraft:u,reviewRequestedLogin:l},e,t.includeFromArchivedRepos??!1)))).flatMap(p=>p.data)}}async closePullRequest(t,e={}){let{pullRequest:r}=t,n=`mutation ClosePullRequest($fullPath: ID!, $pullRequestId: String!) {
1131
1132
  mergeRequestUpdate(input: { projectPath: $fullPath, iid: $pullRequestId, state: CLOSED }) {
1132
1133
  errors,
1133
1134
  mergeRequest {
1134
1135
  id
1135
1136
  }
1136
1137
  }
1137
- }`,i=(await b(this.config,{query:n,variables:{fullPath:`${r.repository.owner.login}/${r.repository.name}`,pullRequestId:r.number.toString()}},e)).body.data?.mergeRequestUpdate;if(!i?.mergeRequest?.id||i?.errors?.length!==0)throw new Error("Could not close pull request")}async mergePullRequest(t,e={}){let{pullRequest:r,mergeStrategy:n}=t;if(!r.headRef?.oid)throw new Error('GitLab requires "headRef.oid" for this function.');let o=`mutation MergePullRequest(
1138
+ }`,i=(await P(this.config,{query:n,variables:{fullPath:`${r.repository.owner.login}/${r.repository.name}`,pullRequestId:r.number.toString()}},e)).body.data?.mergeRequestUpdate;if(!i?.mergeRequest?.id||i?.errors?.length!==0)throw new Error("Could not close pull request")}async mergePullRequest(t,e={}){let{pullRequest:r,mergeStrategy:n}=t;if(!r.headRef?.oid)throw new Error('GitLab requires "headRef.oid" for this function.');let o=`mutation MergePullRequest(
1138
1139
  $fullPath: ID!,
1139
1140
  $pullRequestId: String!,
1140
1141
  $expectedSourceSha: String!,
@@ -1151,59 +1152,59 @@ query getPullRequestsForRepo(
1151
1152
  id
1152
1153
  }
1153
1154
  }
1154
- }`,a=(await b(this.config,{query:o,variables:{fullPath:`${r.repository.owner.login}/${r.repository.name}`,pullRequestId:r.number.toString(),expectedSourceSha:r.headRef.oid,squash:n==="SQUASH"}},e)).body.data?.mergeRequestAccept;if(!a?.mergeRequest?.id||a?.errors?.length!==0)throw new Error("Could not merge pull request")}async setPullRequestMilestone(t,e={}){let{pullRequest:r,milestone:n}=t;if(!r.graphQLId)throw new Error('GitHub requires "graphQLId" for this function.');let o=`mutation SetPullRequestMilestone($fullPath: ID!, $pullRequestId: String!, $milestoneGraphQLId: MilestoneID) {
1155
+ }`,a=(await P(this.config,{query:o,variables:{fullPath:`${r.repository.owner.login}/${r.repository.name}`,pullRequestId:r.number.toString(),expectedSourceSha:r.headRef.oid,squash:n==="SQUASH"}},e)).body.data?.mergeRequestAccept;if(!a?.mergeRequest?.id||a?.errors?.length!==0)throw new Error("Could not merge pull request")}async setPullRequestMilestone(t,e={}){let{pullRequest:r,milestone:n}=t;if(!r.graphQLId)throw new Error('GitHub requires "graphQLId" for this function.');let o=`mutation SetPullRequestMilestone($fullPath: ID!, $pullRequestId: String!, $milestoneGraphQLId: MilestoneID) {
1155
1156
  mergeRequestSetMilestone(input: { projectPath: $fullPath, iid: $pullRequestId, milestoneId: $milestoneGraphQLId }) {
1156
1157
  errors,
1157
1158
  mergeRequest {
1158
1159
  id
1159
1160
  }
1160
1161
  }
1161
- }`,i=await b(this.config,{query:o,variables:{fullPath:`${r.repository.owner.login}/${r.repository.name}`,pullRequestId:r.number.toString(),milestoneGraphQLId:n?.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(t,e={}){let{pullRequest:r,isDraft:n}=t,o=`mutation MergeRequestSetDraft($fullPath: ID!, $pullRequestId: String!, $isDraft: Boolean!) {
1162
+ }`,i=await P(this.config,{query:o,variables:{fullPath:`${r.repository.owner.login}/${r.repository.name}`,pullRequestId:r.number.toString(),milestoneGraphQLId:n?.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(t,e={}){let{pullRequest:r,isDraft:n}=t,o=`mutation MergeRequestSetDraft($fullPath: ID!, $pullRequestId: String!, $isDraft: Boolean!) {
1162
1163
  mergeRequestSetDraft(input: { projectPath: $fullPath, iid: $pullRequestId, draft: $isDraft }) {
1163
1164
  errors,
1164
1165
  mergeRequest {
1165
1166
  id
1166
1167
  }
1167
1168
  }
1168
- }`,a=(await b(this.config,{query:o,variables:{fullPath:`${r.repository.owner.login}/${r.repository.name}`,pullRequestId:r.number.toString(),isDraft:n}},e)).body.data?.mergeRequestSetDraft;if(!a?.mergeRequest?.id||a?.errors?.length!==0)throw new Error("Could not set pull request as draft")}async setPullRequestReviewers(t,e={}){let{pullRequest:r,reviewers:n}=t,o=n.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!]!) {
1169
+ }`,a=(await P(this.config,{query:o,variables:{fullPath:`${r.repository.owner.login}/${r.repository.name}`,pullRequestId:r.number.toString(),isDraft:n}},e)).body.data?.mergeRequestSetDraft;if(!a?.mergeRequest?.id||a?.errors?.length!==0)throw new Error("Could not set pull request as draft")}async setPullRequestReviewers(t,e={}){let{pullRequest:r,reviewers:n}=t,o=n.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!]!) {
1169
1170
  mergeRequestSetReviewers(input: { projectPath: $fullPath, iid: $pullRequestId, reviewerUsernames: $reviewerUsernames }) {
1170
1171
  errors,
1171
1172
  mergeRequest {
1172
1173
  id
1173
1174
  }
1174
1175
  }
1175
- }`,u=(await b(this.config,{query:i,variables:{fullPath:`${r.repository.owner.login}/${r.repository.name}`,pullRequestId:r.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(t,e={}){let{pullRequest:r,reviewer:n}=t;if(!n.graphQLId)throw new Error('GitLab requires reviwer "graphQLId" for this function.');let o=`mutation MergeRequestReviewerRereview($fullPath: ID!, $pullRequestId: String!, $reviewerUserId: UserID!) {
1176
+ }`,u=(await P(this.config,{query:i,variables:{fullPath:`${r.repository.owner.login}/${r.repository.name}`,pullRequestId:r.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(t,e={}){let{pullRequest:r,reviewer:n}=t;if(!n.graphQLId)throw new Error('GitLab requires reviwer "graphQLId" for this function.');let o=`mutation MergeRequestReviewerRereview($fullPath: ID!, $pullRequestId: String!, $reviewerUserId: UserID!) {
1176
1177
  mergeRequestReviewerRereview(input: { projectPath: $fullPath, iid: $pullRequestId, userId: $reviewerUserId }) {
1177
1178
  errors,
1178
1179
  mergeRequest {
1179
1180
  id
1180
1181
  }
1181
1182
  }
1182
- }`,a=(await b(this.config,{query:o,variables:{fullPath:`${r.repository.owner.login}/${r.repository.name}`,pullRequestId:r.number.toString(),reviewerUserId:n.graphQLId}},e)).body.data?.mergeRequestReviewerRereview;if(!a?.mergeRequest?.id||a?.errors?.length!==0)throw new Error("Could not set pull request reviewers")}async reRequestPullRequestReviews(t,e={}){let{pullRequest:r,reviewers:n}=t,o=r.reviews;if(!o)throw new Error('GitLab requires "reviews" for this function.');let i=n.filter(a=>o.find(u=>u.reviewer.graphQLId===a.graphQLId));await Promise.all(i.map(a=>this.reRequestPullRequestReview({pullRequest:r,reviewer:a},e)))}async setPullRequestAssignees(t,e={}){let{pullRequest:r,assignees:n}=t,o=n.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!]!) {
1183
+ }`,a=(await P(this.config,{query:o,variables:{fullPath:`${r.repository.owner.login}/${r.repository.name}`,pullRequestId:r.number.toString(),reviewerUserId:n.graphQLId}},e)).body.data?.mergeRequestReviewerRereview;if(!a?.mergeRequest?.id||a?.errors?.length!==0)throw new Error("Could not set pull request reviewers")}async reRequestPullRequestReviews(t,e={}){let{pullRequest:r,reviewers:n}=t,o=r.reviews;if(!o)throw new Error('GitLab requires "reviews" for this function.');let i=n.filter(a=>o.find(u=>u.reviewer.graphQLId===a.graphQLId));await Promise.all(i.map(a=>this.reRequestPullRequestReview({pullRequest:r,reviewer:a},e)))}async setPullRequestAssignees(t,e={}){let{pullRequest:r,assignees:n}=t,o=n.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!]!) {
1183
1184
  mergeRequestSetAssignees(input: { projectPath: $fullPath, iid: $pullRequestId, assigneeUsernames: $assigneeUsernames }) {
1184
1185
  errors,
1185
1186
  mergeRequest {
1186
1187
  id
1187
1188
  }
1188
1189
  }
1189
- }`,u=(await b(this.config,{query:i,variables:{fullPath:`${r.repository.owner.login}/${r.repository.name}`,pullRequestId:r.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(t,e={}){let{pullRequest:r,labels:n}=t,o=n.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!]!) {
1190
+ }`,u=(await P(this.config,{query:i,variables:{fullPath:`${r.repository.owner.login}/${r.repository.name}`,pullRequestId:r.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(t,e={}){let{pullRequest:r,labels:n}=t,o=n.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!]!) {
1190
1191
  mergeRequestSetLabels(input: { projectPath: $fullPath, iid: $pullRequestId, labelIds: $labelGraphQLIds }) {
1191
1192
  mergeRequest {
1192
1193
  id
1193
1194
  }
1194
1195
  }
1195
- }`;if(!(await b(this.config,{query:i,variables:{fullPath:`${r.repository.owner.login}/${r.repository.name}`,pullRequestId:r.number.toString(),labelGraphQLIds:o}},e)).body.data?.mergeRequestSetLabels?.mergeRequest?.id)throw new Error("Could not set pull request labels")}async getIssue(t,e={}){let r=Pn(t),n=await b(this.config,{query:`
1196
+ }`;if(!(await P(this.config,{query:i,variables:{fullPath:`${r.repository.owner.login}/${r.repository.name}`,pullRequestId:r.number.toString(),labelGraphQLIds:o}},e)).body.data?.mergeRequestSetLabels?.mergeRequest?.id)throw new Error("Could not set pull request labels")}async getIssue(t,e={}){let r=Un(t),n=await P(this.config,{query:`
1196
1197
  query GetSingleIssue($projectId: ID!, $issueNumber: String!) {
1197
1198
  project(fullPath: $projectId) {
1198
1199
  id
1199
1200
  fullPath
1200
1201
  webUrl
1201
1202
  issue(iid: $issueNumber) {
1202
- ${kt}
1203
+ ${Bt}
1203
1204
  }
1204
1205
  }
1205
1206
  }
1206
- `,variables:{issueNumber:t.number,projectId:r}},e);if(!n.body.data?.project)throw new Error(`Repository ${r} not found`);if(!n.body.data?.project?.issue)throw new Error(`Issue ${t.number} not found`);return{data:_t(n.body.data.project.issue,ke(n.body.data.project),this.getIsSelfHosted(e),this.config.baseUrl??e.baseUrl)}}getVariablesForIssues(t){let{updatedBefore:e,authorLogin:r,assigneeLogins:n,labelNames:o}=t||{},i={},a=[],u=[],l=(c,p,d)=>{a.push(`$${c}: ${d}`),u.push(`${c}: $${c}`),i[c]=p};return e&&l("updatedBefore",e,"Time"),r&&l("authorUsername",r,"String"),n&&l("assigneeUsername",n[0],"String"),o&&l("labelName",o,"[String]"),{variables:i,variableTypes:a,issueArguments:u}}async getIssuesForRepo(t,e={}){let{cursor:r,repo:n}=t||{},o=K(n),{variables:i,variableTypes:a,issueArguments:u}=this.getVariablesForIssues(t),l={fullPath:o,...i},c=`
1207
+ `,variables:{issueNumber:t.number,projectId:r}},e);if(!n.body.data?.project)throw new Error(`Repository ${r} not found`);if(!n.body.data?.project?.issue)throw new Error(`Issue ${t.number} not found`);return{data:jt(n.body.data.project.issue,_e(n.body.data.project),this.getIsSelfHosted(e),this.config.baseUrl??e.baseUrl)}}getVariablesForIssues(t){let{updatedBefore:e,authorLogin:r,assigneeLogins:n,labelNames:o}=t||{},i={},a=[],u=[],l=(d,p,c)=>{a.push(`$${d}: ${c}`),u.push(`${d}: $${d}`),i[d]=p};return e&&l("updatedBefore",e,"Time"),r&&l("authorUsername",r,"String"),n&&l("assigneeUsername",n[0],"String"),o&&l("labelName",o,"[String]"),{variables:i,variableTypes:a,issueArguments:u}}async getIssuesForRepo(t,e={}){let{cursor:r,repo:n}=t||{},o=Y(n),{variables:i,variableTypes:a,issueArguments:u}=this.getVariablesForIssues(t),l={fullPath:o,...i},d=`
1207
1208
  query GetIssuesFromProject(
1208
1209
  $fullPath: ID!
1209
1210
  $after: String
@@ -1223,7 +1224,7 @@ query GetSingleIssue($projectId: ID!, $issueNumber: String!) {
1223
1224
  ${u.length?u.join(" "):""}
1224
1225
  ) {
1225
1226
  nodes {
1226
- ${kt}
1227
+ ${Bt}
1227
1228
  }
1228
1229
  pageInfo {
1229
1230
  endCursor
@@ -1231,7 +1232,7 @@ query GetSingleIssue($projectId: ID!, $issueNumber: String!) {
1231
1232
  }
1232
1233
  }
1233
1234
  }
1234
- }`,p=await b(this.config,{query:c,variables:{...l,after:r}},e),d=[],g=p.body.data?.project,m=ke(g||{id:"",fullPath:"",webUrl:""});return(g?.issues?.nodes||[]).forEach(R=>{d.push(_t(R,m,this.getIsSelfHosted(e),this.config.baseUrl??e.baseUrl))}),{pageInfo:g?.issues?.pageInfo??{endCursor:null,hasNextPage:!1},data:d.sort((R,L)=>(R.updatedDate||R.createdDate).getTime()-(L.updatedDate||L.createdDate).getTime())}}async getIssuesForRepos(t,e={}){let{cursor:r}=t||{},n=t.repoIds.map(g=>g.toString().startsWith(ie)?g:`${ie}${g}`),{variables:o,variableTypes:i,mergeRequestArguments:a}=this.getVariablesForPullRequests(t),u={projectIds:n,...o},l=`
1235
+ }`,p=await P(this.config,{query:d,variables:{...l,after:r}},e),c=[],g=p.body.data?.project,m=_e(g||{id:"",fullPath:"",webUrl:""});return(g?.issues?.nodes||[]).forEach(R=>{c.push(jt(R,m,this.getIsSelfHosted(e),this.config.baseUrl??e.baseUrl))}),{pageInfo:g?.issues?.pageInfo??{endCursor:null,hasNextPage:!1},data:c.sort((R,D)=>(R.updatedDate||R.createdDate).getTime()-(D.updatedDate||D.createdDate).getTime())}}async getIssuesForRepos(t,e={}){let{cursor:r}=t||{},n=t.repoIds.map(g=>g.toString().startsWith(pe)?g:`${pe}${g}`),{variables:o,variableTypes:i,mergeRequestArguments:a}=this.getVariablesForPullRequests(t),u={projectIds:n,...o},l=`
1235
1236
  query GetIssuesFromProject(
1236
1237
  $projectIds: [ID!]
1237
1238
  $after: String
@@ -1257,24 +1258,24 @@ query GetSingleIssue($projectId: ID!, $issueNumber: String!) {
1257
1258
  ${a.length?a.join(" "):""}
1258
1259
  ) {
1259
1260
  nodes {
1260
- ${kt}
1261
+ ${Bt}
1261
1262
  }
1262
1263
  }
1263
1264
  }
1264
1265
  }
1265
- }`,c=await b(this.config,{query:l,variables:{...u,after:r}},e),p=[];return(c.body.data?.projects?.nodes||[]).forEach(g=>{if(!t.includeFromArchivedRepos&&g.archived)return;let m=ke(g);(g.issues?.nodes||[]).forEach(R=>p.push(_t(R,m,this.getIsSelfHosted(e),this.config.baseUrl??e.baseUrl)))}),{pageInfo:c.body?.data?.projects?.pageInfo??{endCursor:null,hasNextPage:!1},data:p.sort((g,m)=>(g.updatedDate||g.createdDate).getTime()-(m.updatedDate||m.createdDate).getTime())}}async setIssueState(t,e={}){let{issue:r,state:n}=t;if(!r.repository)throw new Error('GitLab requires "repository" for this function.');let o=`mutation SetIssueState($fullPath: ID!, $issueId: String!, $status: IssueStateEvent!) {
1266
+ }`,d=await P(this.config,{query:l,variables:{...u,after:r}},e),p=[];return(d.body.data?.projects?.nodes||[]).forEach(g=>{if(!t.includeFromArchivedRepos&&g.archived)return;let m=_e(g);(g.issues?.nodes||[]).forEach(R=>p.push(jt(R,m,this.getIsSelfHosted(e),this.config.baseUrl??e.baseUrl)))}),{pageInfo:d.body?.data?.projects?.pageInfo??{endCursor:null,hasNextPage:!1},data:p.sort((g,m)=>(g.updatedDate||g.createdDate).getTime()-(m.updatedDate||m.createdDate).getTime())}}async setIssueState(t,e={}){let{issue:r,state:n}=t;if(!r.repository)throw new Error('GitLab requires "repository" for this function.');let o=`mutation SetIssueState($fullPath: ID!, $issueId: String!, $status: IssueStateEvent!) {
1266
1267
  updateIssue(input: { projectPath: $fullPath, iid: $issueId, stateEvent: $status }) {
1267
1268
  issue {
1268
1269
  id
1269
1270
  }
1270
1271
  }
1271
- }`;if(!(await b(this.config,{query:o,variables:{fullPath:`${r.repository.owner.login}/${r.repository.name}`,issueId:r.number,status:n==="OPEN"?"REOPEN":"CLOSE"}},e)).body.data?.updateIssue?.issue?.id)throw new Error("Could not set issue status")}async closeIssue(t,e={}){await this.setIssueState({...t,state:"CLOSED"},e)}async reOpenIssue(t,e={}){await this.setIssueState({...t,state:"OPEN"},e)}async setIssueLabels(t,e={}){let{issue:r,labels:n}=t;if(!r.repository)throw new Error('GitLab requires a "repository" for this function.');let o=n.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!]) {
1272
+ }`;if(!(await P(this.config,{query:o,variables:{fullPath:`${r.repository.owner.login}/${r.repository.name}`,issueId:r.number,status:n==="OPEN"?"REOPEN":"CLOSE"}},e)).body.data?.updateIssue?.issue?.id)throw new Error("Could not set issue status")}async closeIssue(t,e={}){await this.setIssueState({...t,state:"CLOSED"},e)}async reOpenIssue(t,e={}){await this.setIssueState({...t,state:"OPEN"},e)}async setIssueLabels(t,e={}){let{issue:r,labels:n}=t;if(!r.repository)throw new Error('GitLab requires a "repository" for this function.');let o=n.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!]) {
1272
1273
  updateIssue(input: { projectPath: $fullPath, iid: $issueId, labelIds: $labelGraphQLIds }) {
1273
1274
  issue {
1274
1275
  id
1275
1276
  }
1276
1277
  }
1277
- }`;if(!(await b(this.config,{query:i,variables:{fullPath:`${r.repository.owner.login}/${r.repository.name}`,issueId:r.number,labelGraphQLIds:o}},e)).body.data?.updateIssue?.issue?.id)throw new Error("Could not set issue labels")}async setIssueMilestone(t,e={}){let{issue:r,milestone:n}=t;if(!r.repository)throw new Error('GitLab requires "repository" for this function.');let o=`mutation SetIssueMilestone($fullPath: ID!, $issueId: String!, $milestoneId: ID) {
1278
+ }`;if(!(await P(this.config,{query:i,variables:{fullPath:`${r.repository.owner.login}/${r.repository.name}`,issueId:r.number,labelGraphQLIds:o}},e)).body.data?.updateIssue?.issue?.id)throw new Error("Could not set issue labels")}async setIssueMilestone(t,e={}){let{issue:r,milestone:n}=t;if(!r.repository)throw new Error('GitLab requires "repository" for this function.');let o=`mutation SetIssueMilestone($fullPath: ID!, $issueId: String!, $milestoneId: ID) {
1278
1279
  updateIssue(input: { projectPath: $fullPath, iid: $issueId, milestoneId: $milestoneId }) {
1279
1280
  errors
1280
1281
  issue {
@@ -1284,14 +1285,14 @@ query GetSingleIssue($projectId: ID!, $issueNumber: String!) {
1284
1285
  }
1285
1286
  }
1286
1287
  }
1287
- }`,i=await b(this.config,{query:o,variables:{fullPath:`${r.repository.owner.login}/${r.repository.name}`,issueId:r.number,milestoneId:n?.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(t,e={}){let{issue:r,assignees:n}=t;if(!r.repository)throw new Error('GitLab requires "repository" for this function.');let o=n.map(l=>l.username),i=`mutation SetIssueAssignees($fullPath: ID!, $issueId: String!, $assigneeUsernames: [String!]!) {
1288
+ }`,i=await P(this.config,{query:o,variables:{fullPath:`${r.repository.owner.login}/${r.repository.name}`,issueId:r.number,milestoneId:n?.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(t,e={}){let{issue:r,assignees:n}=t;if(!r.repository)throw new Error('GitLab requires "repository" for this function.');let o=n.map(l=>l.username),i=`mutation SetIssueAssignees($fullPath: ID!, $issueId: String!, $assigneeUsernames: [String!]!) {
1288
1289
  issueSetAssignees(input: { projectPath: $fullPath, iid: $issueId, assigneeUsernames: $assigneeUsernames }) {
1289
1290
  errors,
1290
1291
  issue {
1291
1292
  id
1292
1293
  }
1293
1294
  }
1294
- }`,u=(await b(this.config,{query:i,variables:{fullPath:`${r.repository.owner.login}/${r.repository.name}`,issueId:r.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(t,e={}){let{repo:{namespace:r,name:n},cursor:o}=t,i=await b(this.config,{query:`
1295
+ }`,u=(await P(this.config,{query:i,variables:{fullPath:`${r.repository.owner.login}/${r.repository.name}`,issueId:r.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(t,e={}){let{repo:{namespace:r,name:n},cursor:o}=t,i=await P(this.config,{query:`
1295
1296
  query getLabelsForRepo(
1296
1297
  $fullPath: ID!
1297
1298
  $after: String
@@ -1302,7 +1303,7 @@ query getLabelsForRepo(
1302
1303
  webUrl
1303
1304
  milestones(after: $after) {
1304
1305
  nodes {
1305
- ${jt}
1306
+ ${zt}
1306
1307
  }
1307
1308
  pageInfo {
1308
1309
  endCursor
@@ -1311,7 +1312,7 @@ query getLabelsForRepo(
1311
1312
  }
1312
1313
  }
1313
1314
  }
1314
- `,variables:{fullPath:`${r}/${n}`,after:o}},e);return{pageInfo:i.body.data?.project?.milestones?.pageInfo??{endCursor:null,hasNextPage:!1},data:i.body.data?.project?.milestones?.nodes?.map(a=>zt(a,i.body.data?.project?.webUrl||""))??[]}}async getLabelsForRepo(t,e={}){let{repo:{namespace:r,name:n},cursor:o}=t,i=await b(this.config,{query:`
1315
+ `,variables:{fullPath:`${r}/${n}`,after:o}},e);return{pageInfo:i.body.data?.project?.milestones?.pageInfo??{endCursor:null,hasNextPage:!1},data:i.body.data?.project?.milestones?.nodes?.map(a=>Vt(a,i.body.data?.project?.webUrl||""))??[]}}async getLabelsForRepo(t,e={}){let{repo:{namespace:r,name:n},cursor:o}=t,i=await P(this.config,{query:`
1315
1316
  query getLabelsForRepo(
1316
1317
  $fullPath: ID!
1317
1318
  $after: String
@@ -1321,7 +1322,7 @@ query getLabelsForRepo(
1321
1322
  ) {
1322
1323
  labels(after: $after) {
1323
1324
  nodes {
1324
- ${Ft}
1325
+ ${Wt}
1325
1326
  }
1326
1327
  pageInfo {
1327
1328
  endCursor
@@ -1330,8 +1331,8 @@ query getLabelsForRepo(
1330
1331
  }
1331
1332
  }
1332
1333
  }
1333
- `,variables:{fullPath:`${r}/${n}`,after:o}},e);return{pageInfo:i.body.data?.project?.labels?.pageInfo??{endCursor:null,hasNextPage:!1},data:i.body.data?.project?.labels?.nodes?.map(Mt)??[]}}async getTreeForRepo(t,e={}){let r=K(t.repo),n=new URL(t.cursor??`${Oe(this.config,e)}/projects/${encodeURIComponent(r)}/repository/tree`);n.searchParams.set("per_page","10000"),n.searchParams.set("recursive","true"),n.searchParams.set("pagination","keyset"),n.searchParams.set("ref",t.branch);let o=await this.config.request({url:n.toString(),headers:I(e.token||this.config.token)}),i=o.headers.link;return{data:o.body.map(vn),pageInfo:{endCursor:i?i.substring(1,i.indexOf(">")):null,hasNextPage:!!i}}}};var Cn="https://api.atlassian.com/ex/jira",Ne=100,Wt=["assignee","comment","summary","created","creator","updated","votes","issuetype","status","labels","components","project","fixVersions","description"],jr="/rest/api/2/search/jql",Fr="/rest/api/2/search",Ht=(s,t,e,r)=>{let n=s.fields.assignee,o=!r,i=(s.fields[t?.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:_e(s.fields.creator,e,o),updatedDate:new Date(s.fields.updated),assignees:n?[_e(n,e,o)]:[],description:s.fields.description,repository:null,project:{name:s.fields.project.name,resourceId:r??null,key:s.fields.project.key,namespace:null,id:s.fields.project.id},state:Un(s.fields.status),statusTransitions:s.transitions?.map(Dn)??[],components:s.fields.components?.map(Ln)??[],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($n),fixVersions:s.fields.fixVersions.map(Tn)}},Dn=s=>{let t;switch(s.to.statusCategory.name){case"To Do":t="TO_DO";break;case"In Progress":t="IN_PROGRESS";break;default:t="DONE";break}return{name:s.name,id:s.id,to:{id:s.to.id,name:s.to.name,color:s.to.statusCategory.colorName,category:t}}},Ln=s=>({description:s.description??null,id:s.id,name:s.name}),An=(s,t,e)=>e&&s.name?`${t}/secure/ViewProfile.jspa?name=${encodeURIComponent(s.name)}`:`${t}/jira/people/${s.accountId}`,_e=(s,t,e)=>({id:(e?s.key:s.accountId)??"",name:s.displayName,email:s.emailAddress,avatarUrl:s.avatarUrls["48x48"],username:s.displayName,url:An(s,t,e)}),Un=s=>{let t;switch(s.statusCategory.name){case"To Do":t="TO_DO";break;case"In Progress":t="IN_PROGRESS";break;default:t="DONE";break}return{id:s.id,name:s.name,color:s.statusCategory.colorName,category:t}},$n=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}),Tn=s=>({id:s.id,description:s.description,name:s.name,archived:s.archived,released:s.released,releaseDate:s.releaseDate?new Date(s.releaseDate):null}),X=(s,t,e)=>e?`${t.baseUrl||Cn}/${e}`:`${t?.baseUrl||s.baseUrl}`,Be=async(s,t,e={})=>{let{resourceId:r}=t;return(await s.request({url:`${X(s,e,r)}/rest/api/2/field`,headers:I(e.token||s.token)})).body},Qe=async(s,t,e,r={})=>{let{number:n,resourceId:o,fields:i}=t||{},a=await s.request({url:`${X(s,r,o)}/rest/api/2/issue/${n}?fields=${Wt.join(",")}&expand=transitions`,headers:I(r.token||s.token)});return{data:Ht(a.body,i,e,o)}},je=async(s,t,e,r={})=>{let{cursor:n,resourceId:o,labelNames:i,fields:a}=t||{},u=["statusCategory != Done",`(creator = currentUser() OR assignee = currentUser()
1334
- OR comment ~ currentUser() OR summary ~ currentUser() OR description ~ currentUser())`];i&&i.forEach(L=>u.push(`labels = "${L}"`));let l=`${u.join(" AND ")} ORDER BY updated DESC`,c=!o,p=c?Fr:jr,d=new URL(`${X(s,r,o)}${p}`);d.searchParams.set("jql",l),d.searchParams.set("maxResults",Ne.toString()),d.searchParams.set("fields",Wt.join(",")),d.searchParams.set("expand","transitions"),n&&(c?d.searchParams.set("startAt",n):d.searchParams.set("nextPageToken",n));let g=await s.request({url:d.toString(),headers:I(r.token||s.token)}),m=g.body.issues.map(L=>Ht(L,a,e,o)),y=!1,R="";return c?(y=m.length==Ne,R=(parseInt(n??"0",10)+m.length).toString()):(y=!!g.body.nextPageToken,R=g.body.nextPageToken??null),{data:m,pageInfo:{hasNextPage:y,endCursor:R}}},Mr=async(s,t,e,r={})=>{let{cursor:n,resourceId:o,jql:i,fields:a}=t||{},u=[...Wt],l=a?.Sprint;l&&u.push(l);let c=!o,p=c?Fr:jr,d=new URL(`${X(s,r,o)}${p}`);d.searchParams.set("jql",i.join(" AND ")),d.searchParams.set("maxResults",Ne.toString()),d.searchParams.set("fields",u.join(",")),d.searchParams.set("expand","transitions"),n&&(c?d.searchParams.set("startAt",n):d.searchParams.set("nextPageToken",n));let g=await s.request({url:d.toString(),headers:I(r.token||s.token)}),m=g.body.issues.map(L=>Ht(L,a,e,o)),y=!1,R="";return c?(y=m.length==Ne,R=(parseInt(n??"0",10)+m.length).toString()):(y=!!g.body.nextPageToken,R=g.body.nextPageToken??null),{data:m,pageInfo:{hasNextPage:y,endCursor:R}}},Fe=async(s,t,e,r={})=>{let{assigneeLogins:n,authorLogin:o,mentionLogin:i,labelNames:a,cursor:u,projectKey:l,resourceId:c,fields:p}=t||{},d=[`project = "${l}"`,"statusCategory != Done"];return o&&d.push(`creator in ("${o}")`),n&&n.length!==0&&d.push(`assignee in ("${n.join('", "')}")`),i&&d.push(`comment ~ "${i}"`),a&&a.forEach(g=>d.push(`labels = "${g}"`)),Mr(s,{resourceId:c,jql:d,cursor:u,fields:p},e,r)},Me=async(s,t,e,r={})=>{let{assigneeLogins:n,authorLogin:o,mentionLogin:i,labelNames:a,cursor:u,projectKeys:l,resourceId:c,fields:p}=t||{},g=["("+l.map(m=>`project = "${m}"`).join(" OR ")+")","statusCategory != Done"];return o&&g.push(`creator in ("${o}")`),n&&n.length!==0&&g.push(`assignee in ("${n.join('", "')}")`),i&&g.push(`comment ~ "${i}"`),a&&a.forEach(m=>g.push(`labels = "${m}"`)),Mr(s,{resourceId:c,jql:g,fields:p,cursor:u},e,r)},ze=async(s,t,e={})=>{let{issue:r,labels:n}=t;if(!r.project)throw new Error('Jira requires a "project" for this function.');let o={fields:{labels:n.map(i=>i.name)}};await s.request({method:"PUT",url:`${X(s,e,r.project.resourceId??void 0)}/rest/api/2/issue/${r.id}`,body:JSON.stringify(o),headers:{...I(e.token||s.token),"Content-Type":"application/json"}})},We=async(s,t,e={})=>{let{issue:r,components:n}=t;if(!r.project)throw new Error('Jira requires a "project" for this function.');let o={fields:{components:n.map(i=>({id:i.id}))}};await s.request({method:"PUT",url:`${X(s,e,r.project.resourceId??void 0)}/rest/api/2/issue/${r.id}`,body:JSON.stringify(o),headers:{...I(e.token||s.token),"Content-Type":"application/json"}})},He=async(s,t,e={})=>{let{issue:r,status:n}=t;if(!r.project)throw new Error('Jira requires a "project" for this function.');if(!n.id)throw new Error('Jira requires a status "id" for this function.');let o={transition:{id:n.id}};await s.request({method:"POST",url:`${X(s,e,r.project.resourceId??void 0)}/rest/api/2/issue/${r.id}/transitions`,body:JSON.stringify(o),headers:{...I(e.token||s.token),"Content-Type":"application/json"}})},Ve=async(s,t,e={})=>{let{resourceId:r,projectIdOrKey:n}=t,o=new URL(`${X(s,e,r)}/rest/api/2/project/${n}/components`);return{data:(await s.request({url:o.toString(),headers:I(e.token||s.token)})).body}};var Re="https://api.atlassian.com/ex/jira",Vt=100,ue=class extends O{constructor(){super(...arguments);this._resourceUrlCache={};this._issueFieldsCache={}}async getIssueFieldsForResource(e,r={}){if(!this._issueFieldsCache[e.resourceId]){let n=await Be(this.config,e,r);this._issueFieldsCache[e.resourceId]=n.reduce((o,i)=>({...o,[i.name]:i.id}),{})}return this._issueFieldsCache[e.resourceId]??null}async getResourceUrl(e,r={}){let n=r.token||this.config.token;if(!n)return null;let o=this._resourceUrlCache[n];return o?o[e.resourceId]??null:(await this.getJiraResourcesForCurrentUser(r),this._resourceUrlCache[n]?.[e.resourceId]??null)}async getCurrentUserForResource(e,r={}){let n=await this.getResourceUrl({resourceId:e.resourceId},r),o=await this.config.request({url:`${r.baseUrl||Re}/${e.resourceId}/rest/api/2/myself`,headers:I(r.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:n?`${n}/jira/people/${o.body.accountId}`:null}}}async getJiraResourcesForCurrentUser(e={}){let r=await this.config.request({url:`${e.baseUrl||"https://api.atlassian.com/"}/oauth/token/accessible-resources`,headers:I(e.token||this.config.token)}),n=e.token||this.config.token,o=n?this._resourceUrlCache[n]||{}:void 0,i=r.body.map(a=>(o&&(o[a.id]=a.url),{avatarUrl:a.avatarUrl,id:a.id,name:a.name,url:a.url}));return n&&(this._resourceUrlCache[n]=o),{data:i}}async getJiraProjectsForResource(e,r={}){let n=new URL(`${r.baseUrl||Re}/${e.resourceId}/rest/api/2/project/search`);n.searchParams.set("maxResults",Vt.toString()),e.cursor&&n.searchParams.set("startAt",e.cursor);let o=await this.config.request({url:n.toString(),headers:I(r.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,r={}){let n=[];return await Promise.all(e.resourceIds.map(async o=>{try{return await Ir(i=>this.getJiraProjectsForResource({resourceId:o,cursor:i},r))}catch{return[]}})).then((...o)=>{o.forEach(i=>{n=n.concat(...i)})}),{data:n}}async getAccountsForJiraProject(e,r={}){let{resourceId:n,projectKey:o,cursor:i}=e,a=await this.getResourceUrl({resourceId:n},r),u=new URL(`${r.baseUrl||Re}/${n}/rest/api/2/user/assignable/search`);u.searchParams.set("maxResults",Vt.toString()),i&&u.searchParams.set("startAt",i),u.searchParams.set("project",o);let l=await this.config.request({url:u.toString(),headers:I(r.token||this.config.token)});return{pageInfo:{hasNextPage:l.body.length!==0,endCursor:((i?parseInt(i):0)+l.body.length).toString()},data:l.body.filter(c=>c.accountType!=="app"&&c.active).map(c=>_e(c,a,!1))}}async getComponentsForJiraProject(e,r={}){return await Ve(this.config,e,r)}async getIssue(e,r={}){let n=await this.getIssueFieldsForResource({resourceId:e.resourceId},r),o=await this.getResourceUrl({resourceId:e.resourceId},r);return await Qe(this.config,{...e,fields:n},o,r)}async getIssuesForProject(e,r={}){let n=await this.getIssueFieldsForResource({resourceId:e.resourceId},r),o=await this.getResourceUrl({resourceId:e.resourceId},r);return await Fe(this.config,{...e,fields:n},o,r)}async getIssuesForProjects(e,r={}){let n=await this.getIssueFieldsForResource({resourceId:e.resourceId},r),o=await this.getResourceUrl({resourceId:e.resourceId},r);return await Me(this.config,{...e,fields:n},o,r)}async getIssuesForResourceForCurrentUser(e,r={}){let n=await this.getIssueFieldsForResource({resourceId:e.resourceId},r),o=await this.getResourceUrl({resourceId:e.resourceId},r);return await je(this.config,{...e,fields:n},o,r)}async setIssueStatus(e,r={}){await He(this.config,e,r)}async setIssueAssignee(e,r={}){let{issue:n,assignee:o}=e;if(!n.project)throw new Error('Jira Cloud requires a "project" for this function.');if(!n.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:`${r.baseUrl||Re}/${n.project.resourceId}/rest/api/2/issue/${n.id}/assignee`,body:JSON.stringify(i),headers:{...I(r.token||this.config.token),"Content-Type":"application/json"}})}async setIssueComponents(e,r={}){await We(this.config,e,r)}async setIssueLabels(e,r={}){await ze(this.config,e,r)}async getLabelsForResource(e,r={}){let{resourceId:n,cursor:o}=e,i=new URL(`${r.baseUrl||Re}/${n}/rest/api/2/label`);i.searchParams.set("maxResults",Vt.toString()),o&&i.searchParams.set("startAt",o);let a=await this.config.request({url:i.toString(),headers:I(r.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 le=class extends ${constructor(){super(...arguments);this._issueFieldsCache={}}async getIssueFieldsForResource(e={}){let r=e?.baseUrl||this.config.baseUrl||"";if(!this._issueFieldsCache[r]){let n=await Be(this.config,{},e);this._issueFieldsCache[r]=n.reduce((o,i)=>({...o,[i.name]:i.id}),{})}return this._issueFieldsCache[r]??null}async getCurrentUser(e={}){let r=await this.config.request({url:`${e?.baseUrl||this.config.baseUrl}/rest/api/2/myself`,headers:I(e?.token||this.config.token)});return{data:{name:r.body.displayName,email:r.body.emailAddress,avatarUrl:r.body.avatarUrls["48x48"],id:r.body.key,username:r.body.displayName,url:null}}}async getJiraProjects(e={}){return{data:(await this.config.request({url:`${e?.baseUrl||this.config.baseUrl}/rest/api/2/project`,headers:I(e?.token||this.config.token)})).body.map(n=>({id:n.id,name:n.name}))}}async getIssue(e,r={}){let n=e.resourceUrl||r.baseUrl||this.config.baseUrl;if(!n)throw new Error('Jira Server requires a "resourceUrl" or "baseUrl" for this function.');let o=await this.getIssueFieldsForResource(r);return await Qe(this.config,{...e,fields:o},n,r)}async getIssuesForProject(e,r={}){let n=e.resourceUrl||r.baseUrl||this.config.baseUrl;if(!n)throw new Error('Jira Server requires a "resourceUrl" or "baseUrl" for this function.');let o=await this.getIssueFieldsForResource(r);return await Fe(this.config,{...e,fields:o},n,r)}async getIssuesForProjects(e,r={}){let n=e.resourceUrl||r.baseUrl||this.config.baseUrl;if(!n)throw new Error('Jira Server requires a "resourceUrl" or "baseUrl" for this function.');let o=await this.getIssueFieldsForResource(r);return await Me(this.config,{...e,fields:o},n,r)}async getIssuesForResourceForCurrentUser(e,r={}){let n=e.resourceUrl||r.baseUrl||this.config.baseUrl;if(!n)throw new Error('Jira Server requires a "resourceUrl" or "baseUrl" for this function.');let o=await this.getIssueFieldsForResource(r);return await je(this.config,{...e,fields:o},n,r)}async setIssueStatus(e,r={}){await He(this.config,e,r)}async setIssueLabels(e,r={}){await ze(this.config,e,r)}async setIssueComponents(e,r={}){await We(this.config,e,r)}async getLabels(e={}){return{data:(await this.config.request({url:`${e?.baseUrl||this.config.baseUrl}/rest/api/2/jql/autocompletedata/suggestions?fieldName=labels`,headers:I(e.token||this.config.token)})).body.results.map(({displayName:n})=>({color:null,description:null,id:null,name:n}))}}async getComponentsForJiraProject(e,r={}){return await Ve(this.config,e,r)}};var Kt=100,Je=class{constructor(){this.set=new Set;this.arr=[]}push(...t){let e=t.filter(r=>!this.set.has(r.id));this.arr.push(...e),e.forEach(r=>this.set.add(r.id))}get length(){return this.arr.length}get items(){return this.arr}},H=async(s,t,e,r)=>{let n=t.token||s.token;if(!n)throw new Error("Linear API key is required");let o=await s.request({url:"https://api.linear.app/graphql",method:"POST",headers:{Authorization:n,"Content-Type":"application/json"},body:JSON.stringify({query:e,variables:r})});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},Jt=s=>s?s instanceof Date?s:new Date(s):null,Gn=`
1334
+ `,variables:{fullPath:`${r}/${n}`,after:o}},e);return{pageInfo:i.body.data?.project?.labels?.pageInfo??{endCursor:null,hasNextPage:!1},data:i.body.data?.project?.labels?.nodes?.map(Ht)??[]}}async getTreeForRepo(t,e={}){let r=Y(t.repo),n=new URL(t.cursor??`${ke(this.config,e)}/projects/${encodeURIComponent(r)}/repository/tree`);n.searchParams.set("per_page","10000"),n.searchParams.set("recursive","true"),n.searchParams.set("pagination","keyset"),n.searchParams.set("ref",t.branch);let o=await this.config.request({url:n.toString(),headers:I(e.token||this.config.token)}),i=o.headers.link;return{data:o.body.map(Gn),pageInfo:{endCursor:i?i.substring(1,i.indexOf(">")):null,hasNextPage:!!i}}}};var kn="https://api.atlassian.com/ex/jira",Be=100,Jt=["assignee","comment","summary","created","creator","updated","votes","issuetype","status","labels","components","project","fixVersions","description"],Vr="/rest/api/2/search/jql",Jr="/rest/api/2/search",Kt=(s,t,e,r)=>{let n=s.fields.assignee,o=!r,i=(s.fields[t?.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:Qe(s.fields.creator,e,o),updatedDate:new Date(s.fields.updated),assignees:n?[Qe(n,e,o)]:[],description:s.fields.description,repository:null,project:{name:s.fields.project.name,resourceId:r??null,key:s.fields.project.key,namespace:null,id:s.fields.project.id},state:Qn(s.fields.status),statusTransitions:s.transitions?.map(Nn)??[],components:s.fields.components?.map(_n)??[],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(jn),fixVersions:s.fields.fixVersions.map(Fn)}},Nn=s=>{let t;switch(s.to.statusCategory.name){case"To Do":t="TO_DO";break;case"In Progress":t="IN_PROGRESS";break;default:t="DONE";break}return{name:s.name,id:s.id,to:{id:s.to.id,name:s.to.name,color:s.to.statusCategory.colorName,category:t}}},_n=s=>({description:s.description??null,id:s.id,name:s.name}),Bn=(s,t,e)=>e&&s.name?`${t}/secure/ViewProfile.jspa?name=${encodeURIComponent(s.name)}`:`${t}/jira/people/${s.accountId}`,Qe=(s,t,e)=>({id:(e?s.key:s.accountId)??"",name:s.displayName,email:s.emailAddress,avatarUrl:s.avatarUrls["48x48"],username:s.displayName,url:Bn(s,t,e)}),Qn=s=>{let t;switch(s.statusCategory.name){case"To Do":t="TO_DO";break;case"In Progress":t="IN_PROGRESS";break;default:t="DONE";break}return{id:s.id,name:s.name,color:s.statusCategory.colorName,category:t}},jn=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}),Fn=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,t,e)=>e?`${t.baseUrl||kn}/${e}`:`${t?.baseUrl||s.baseUrl}`,je=async(s,t,e={})=>{let{resourceId:r}=t;return(await s.request({url:`${Z(s,e,r)}/rest/api/2/field`,headers:I(e.token||s.token)})).body},Fe=async(s,t,e,r={})=>{let{number:n,resourceId:o,fields:i}=t||{},a=await s.request({url:`${Z(s,r,o)}/rest/api/2/issue/${n}?fields=${Jt.join(",")}&expand=transitions`,headers:I(r.token||s.token)});return{data:Kt(a.body,i,e,o)}},Me=async(s,t,e,r={})=>{let{cursor:n,resourceId:o,labelNames:i,fields:a}=t||{},u=["statusCategory != Done",`(creator = currentUser() OR assignee = currentUser()
1335
+ OR comment ~ currentUser() OR summary ~ currentUser() OR description ~ currentUser())`];i&&i.forEach(D=>u.push(`labels = "${D}"`));let l=`${u.join(" AND ")} ORDER BY updated DESC`,d=!o,p=d?Jr:Vr,c=new URL(`${Z(s,r,o)}${p}`);c.searchParams.set("jql",l),c.searchParams.set("maxResults",Be.toString()),c.searchParams.set("fields",Jt.join(",")),c.searchParams.set("expand","transitions"),n&&(d?c.searchParams.set("startAt",n):c.searchParams.set("nextPageToken",n));let g=await s.request({url:c.toString(),headers:I(r.token||s.token)}),m=g.body.issues.map(D=>Kt(D,a,e,o)),y=!1,R="";return d?(y=m.length==Be,R=(parseInt(n??"0",10)+m.length).toString()):(y=!!g.body.nextPageToken,R=g.body.nextPageToken??null),{data:m,pageInfo:{hasNextPage:y,endCursor:R}}},Kr=async(s,t,e,r={})=>{let{cursor:n,resourceId:o,jql:i,fields:a}=t||{},u=[...Jt],l=a?.Sprint;l&&u.push(l);let d=!o,p=d?Jr:Vr,c=new URL(`${Z(s,r,o)}${p}`);c.searchParams.set("jql",i.join(" AND ")),c.searchParams.set("maxResults",Be.toString()),c.searchParams.set("fields",u.join(",")),c.searchParams.set("expand","transitions"),n&&(d?c.searchParams.set("startAt",n):c.searchParams.set("nextPageToken",n));let g=await s.request({url:c.toString(),headers:I(r.token||s.token)}),m=g.body.issues.map(D=>Kt(D,a,e,o)),y=!1,R="";return d?(y=m.length==Be,R=(parseInt(n??"0",10)+m.length).toString()):(y=!!g.body.nextPageToken,R=g.body.nextPageToken??null),{data:m,pageInfo:{hasNextPage:y,endCursor:R}}},ze=async(s,t,e,r={})=>{let{assigneeLogins:n,authorLogin:o,mentionLogin:i,labelNames:a,cursor:u,projectKey:l,resourceId:d,fields:p}=t||{},c=[`project = "${l}"`,"statusCategory != Done"];return o&&c.push(`creator in ("${o}")`),n&&n.length!==0&&c.push(`assignee in ("${n.join('", "')}")`),i&&c.push(`comment ~ "${i}"`),a&&a.forEach(g=>c.push(`labels = "${g}"`)),Kr(s,{resourceId:d,jql:c,cursor:u,fields:p},e,r)},We=async(s,t,e,r={})=>{let{assigneeLogins:n,authorLogin:o,mentionLogin:i,labelNames:a,cursor:u,projectKeys:l,resourceId:d,fields:p}=t||{},g=["("+l.map(m=>`project = "${m}"`).join(" OR ")+")","statusCategory != Done"];return o&&g.push(`creator in ("${o}")`),n&&n.length!==0&&g.push(`assignee in ("${n.join('", "')}")`),i&&g.push(`comment ~ "${i}"`),a&&a.forEach(m=>g.push(`labels = "${m}"`)),Kr(s,{resourceId:d,jql:g,fields:p,cursor:u},e,r)},He=async(s,t,e={})=>{let{issue:r,labels:n}=t;if(!r.project)throw new Error('Jira requires a "project" for this function.');let o={fields:{labels:n.map(i=>i.name)}};await s.request({method:"PUT",url:`${Z(s,e,r.project.resourceId??void 0)}/rest/api/2/issue/${r.id}`,body:JSON.stringify(o),headers:{...I(e.token||s.token),"Content-Type":"application/json"}})},Ve=async(s,t,e={})=>{let{issue:r,components:n}=t;if(!r.project)throw new Error('Jira requires a "project" for this function.');let o={fields:{components:n.map(i=>({id:i.id}))}};await s.request({method:"PUT",url:`${Z(s,e,r.project.resourceId??void 0)}/rest/api/2/issue/${r.id}`,body:JSON.stringify(o),headers:{...I(e.token||s.token),"Content-Type":"application/json"}})},Je=async(s,t,e={})=>{let{issue:r,status:n}=t;if(!r.project)throw new Error('Jira requires a "project" for this function.');if(!n.id)throw new Error('Jira requires a status "id" for this function.');let o={transition:{id:n.id}};await s.request({method:"POST",url:`${Z(s,e,r.project.resourceId??void 0)}/rest/api/2/issue/${r.id}/transitions`,body:JSON.stringify(o),headers:{...I(e.token||s.token),"Content-Type":"application/json"}})},Ke=async(s,t,e={})=>{let{resourceId:r,projectIdOrKey:n}=t,o=new URL(`${Z(s,e,r)}/rest/api/2/project/${n}/components`);return{data:(await s.request({url:o.toString(),headers:I(e.token||s.token)})).body}};var Pe="https://api.atlassian.com/ex/jira",Xt=100,ce=class extends k{constructor(){super(...arguments);this._resourceUrlCache={};this._issueFieldsCache={}}async getIssueFieldsForResource(e,r={}){if(!this._issueFieldsCache[e.resourceId]){let n=await je(this.config,e,r);this._issueFieldsCache[e.resourceId]=n.reduce((o,i)=>({...o,[i.name]:i.id}),{})}return this._issueFieldsCache[e.resourceId]??null}async getResourceUrl(e,r={}){let n=r.token||this.config.token;if(!n)return null;let o=this._resourceUrlCache[n];return o?o[e.resourceId]??null:(await this.getJiraResourcesForCurrentUser(r),this._resourceUrlCache[n]?.[e.resourceId]??null)}async getCurrentUserForResource(e,r={}){let n=await this.getResourceUrl({resourceId:e.resourceId},r),o=await this.config.request({url:`${r.baseUrl||Pe}/${e.resourceId}/rest/api/2/myself`,headers:I(r.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:n?`${n}/jira/people/${o.body.accountId}`:null}}}async getJiraResourcesForCurrentUser(e={}){let r=await this.config.request({url:`${e.baseUrl||"https://api.atlassian.com/"}/oauth/token/accessible-resources`,headers:I(e.token||this.config.token)}),n=e.token||this.config.token,o=n?this._resourceUrlCache[n]||{}:void 0,i=r.body.map(a=>(o&&(o[a.id]=a.url),{avatarUrl:a.avatarUrl,id:a.id,name:a.name,url:a.url}));return n&&(this._resourceUrlCache[n]=o),{data:i}}async getJiraProjectsForResource(e,r={}){let n=new URL(`${r.baseUrl||Pe}/${e.resourceId}/rest/api/2/project/search`);n.searchParams.set("maxResults",Xt.toString()),e.cursor&&n.searchParams.set("startAt",e.cursor);let o=await this.config.request({url:n.toString(),headers:I(r.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,r={}){let n=[];return await Promise.all(e.resourceIds.map(async o=>{try{return await wr(i=>this.getJiraProjectsForResource({resourceId:o,cursor:i},r))}catch{return[]}})).then((...o)=>{o.forEach(i=>{n=n.concat(...i)})}),{data:n}}async getAccountsForJiraProject(e,r={}){let{resourceId:n,projectKey:o,cursor:i}=e,a=await this.getResourceUrl({resourceId:n},r),u=new URL(`${r.baseUrl||Pe}/${n}/rest/api/2/user/assignable/search`);u.searchParams.set("maxResults",Xt.toString()),i&&u.searchParams.set("startAt",i),u.searchParams.set("project",o);let l=await this.config.request({url:u.toString(),headers:I(r.token||this.config.token)});return{pageInfo:{hasNextPage:l.body.length!==0,endCursor:((i?parseInt(i):0)+l.body.length).toString()},data:l.body.filter(d=>d.accountType!=="app"&&d.active).map(d=>Qe(d,a,!1))}}async getComponentsForJiraProject(e,r={}){return await Ke(this.config,e,r)}async getIssue(e,r={}){let n=await this.getIssueFieldsForResource({resourceId:e.resourceId},r),o=await this.getResourceUrl({resourceId:e.resourceId},r);return await Fe(this.config,{...e,fields:n},o,r)}async getIssuesForProject(e,r={}){let n=await this.getIssueFieldsForResource({resourceId:e.resourceId},r),o=await this.getResourceUrl({resourceId:e.resourceId},r);return await ze(this.config,{...e,fields:n},o,r)}async getIssuesForProjects(e,r={}){let n=await this.getIssueFieldsForResource({resourceId:e.resourceId},r),o=await this.getResourceUrl({resourceId:e.resourceId},r);return await We(this.config,{...e,fields:n},o,r)}async getIssuesForResourceForCurrentUser(e,r={}){let n=await this.getIssueFieldsForResource({resourceId:e.resourceId},r),o=await this.getResourceUrl({resourceId:e.resourceId},r);return await Me(this.config,{...e,fields:n},o,r)}async setIssueStatus(e,r={}){await Je(this.config,e,r)}async setIssueAssignee(e,r={}){let{issue:n,assignee:o}=e;if(!n.project)throw new Error('Jira Cloud requires a "project" for this function.');if(!n.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:`${r.baseUrl||Pe}/${n.project.resourceId}/rest/api/2/issue/${n.id}/assignee`,body:JSON.stringify(i),headers:{...I(r.token||this.config.token),"Content-Type":"application/json"}})}async setIssueComponents(e,r={}){await Ve(this.config,e,r)}async setIssueLabels(e,r={}){await He(this.config,e,r)}async getLabelsForResource(e,r={}){let{resourceId:n,cursor:o}=e,i=new URL(`${r.baseUrl||Pe}/${n}/rest/api/2/label`);i.searchParams.set("maxResults",Xt.toString()),o&&i.searchParams.set("startAt",o);let a=await this.config.request({url:i.toString(),headers:I(r.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 G{constructor(){super(...arguments);this._issueFieldsCache={}}async getIssueFieldsForResource(e={}){let r=e?.baseUrl||this.config.baseUrl||"";if(!this._issueFieldsCache[r]){let n=await je(this.config,{},e);this._issueFieldsCache[r]=n.reduce((o,i)=>({...o,[i.name]:i.id}),{})}return this._issueFieldsCache[r]??null}async getCurrentUser(e={}){let r=await this.config.request({url:`${e?.baseUrl||this.config.baseUrl}/rest/api/2/myself`,headers:I(e?.token||this.config.token)});return{data:{name:r.body.displayName,email:r.body.emailAddress,avatarUrl:r.body.avatarUrls["48x48"],id:r.body.key,username:r.body.displayName,url:null}}}async getJiraProjects(e={}){return{data:(await this.config.request({url:`${e?.baseUrl||this.config.baseUrl}/rest/api/2/project`,headers:I(e?.token||this.config.token)})).body.map(n=>({id:n.id,name:n.name}))}}async getIssue(e,r={}){let n=e.resourceUrl||r.baseUrl||this.config.baseUrl;if(!n)throw new Error('Jira Server requires a "resourceUrl" or "baseUrl" for this function.');let o=await this.getIssueFieldsForResource(r);return await Fe(this.config,{...e,fields:o},n,r)}async getIssuesForProject(e,r={}){let n=e.resourceUrl||r.baseUrl||this.config.baseUrl;if(!n)throw new Error('Jira Server requires a "resourceUrl" or "baseUrl" for this function.');let o=await this.getIssueFieldsForResource(r);return await ze(this.config,{...e,fields:o},n,r)}async getIssuesForProjects(e,r={}){let n=e.resourceUrl||r.baseUrl||this.config.baseUrl;if(!n)throw new Error('Jira Server requires a "resourceUrl" or "baseUrl" for this function.');let o=await this.getIssueFieldsForResource(r);return await We(this.config,{...e,fields:o},n,r)}async getIssuesForResourceForCurrentUser(e,r={}){let n=e.resourceUrl||r.baseUrl||this.config.baseUrl;if(!n)throw new Error('Jira Server requires a "resourceUrl" or "baseUrl" for this function.');let o=await this.getIssueFieldsForResource(r);return await Me(this.config,{...e,fields:o},n,r)}async setIssueStatus(e,r={}){await Je(this.config,e,r)}async setIssueLabels(e,r={}){await He(this.config,e,r)}async setIssueComponents(e,r={}){await Ve(this.config,e,r)}async getLabels(e={}){return{data:(await this.config.request({url:`${e?.baseUrl||this.config.baseUrl}/rest/api/2/jql/autocompletedata/suggestions?fieldName=labels`,headers:I(e.token||this.config.token)})).body.results.map(({displayName:n})=>({color:null,description:null,id:null,name:n}))}}async getComponentsForJiraProject(e,r={}){return await Ke(this.config,e,r)}};var Zt=100,Xe=class{constructor(){this.set=new Set;this.arr=[]}push(...t){let e=t.filter(r=>!this.set.has(r.id));this.arr.push(...e),e.forEach(r=>this.set.add(r.id))}get length(){return this.arr.length}get items(){return this.arr}},K=async(s,t,e,r)=>{let n=t.token||s.token;if(!n)throw new Error("Linear API key is required");let o=await s.request({url:"https://api.linear.app/graphql",method:"POST",headers:{Authorization:n,"Content-Type":"application/json"},body:JSON.stringify({query:e,variables:r})});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},Yt=s=>s?s instanceof Date?s:new Date(s):null,Mn=`
1335
1336
  id
1336
1337
  name
1337
1338
  description
@@ -1339,11 +1340,11 @@ OR comment ~ currentUser() OR summary ~ currentUser() OR description ~ currentUs
1339
1340
  startDate
1340
1341
  targetDate
1341
1342
  url
1342
- `,zr=s=>({id:s.id,name:s.name,description:s.description??null,state:s.state,startDate:Jt(s.startDate),targetDate:Jt(s.targetDate),url:s.url}),Wr=async(s,t,e)=>{let r=`
1343
+ `,Xr=s=>({id:s.id,name:s.name,description:s.description??null,state:s.state,startDate:Yt(s.startDate),targetDate:Yt(s.targetDate),url:s.url}),Yr=async(s,t,e)=>{let r=`
1343
1344
  query GetProjects($first: Int!, $after: String) {
1344
1345
  projects(first: $first, after: $after) {
1345
1346
  nodes {
1346
- ${Gn}
1347
+ ${Mn}
1347
1348
  }
1348
1349
  pageInfo {
1349
1350
  hasNextPage
@@ -1351,7 +1352,7 @@ OR comment ~ currentUser() OR summary ~ currentUser() OR description ~ currentUs
1351
1352
  }
1352
1353
  }
1353
1354
  }
1354
- `;return(await H(s,t,r,{first:Kt,after:e})).projects},On=`
1355
+ `;return(await K(s,t,r,{first:Zt,after:e})).projects},zn=`
1355
1356
  id
1356
1357
  name
1357
1358
  number
@@ -1359,11 +1360,11 @@ OR comment ~ currentUser() OR summary ~ currentUser() OR description ~ currentUs
1359
1360
  startsAt
1360
1361
  endsAt
1361
1362
  completedAt
1362
- `,Hr=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:Jt(s.completedAt),url:""}),Vr=async(s,t,e)=>{let r=`
1363
+ `,Zr=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:Yt(s.completedAt),url:""}),es=async(s,t,e)=>{let r=`
1363
1364
  query GetCycles($first: Int!, $after: String) {
1364
1365
  cycles(first: $first, after: $after) {
1365
1366
  nodes {
1366
- ${On}
1367
+ ${zn}
1367
1368
  }
1368
1369
  pageInfo {
1369
1370
  hasNextPage
@@ -1371,16 +1372,16 @@ OR comment ~ currentUser() OR summary ~ currentUser() OR description ~ currentUs
1371
1372
  }
1372
1373
  }
1373
1374
  }
1374
- `;return(await H(s,t,r,{first:Kt,after:e})).cycles},xn=`
1375
+ `;return(await K(s,t,r,{first:Zt,after:e})).cycles},Wn=`
1375
1376
  id
1376
1377
  name
1377
1378
  color
1378
1379
  description
1379
- `,Jr=s=>({id:s.id,name:s.name,color:s.color,description:s.description??null}),Kr=async(s,t,e)=>{let r=`
1380
+ `,ts=s=>({id:s.id,name:s.name,color:s.color,description:s.description??null}),rs=async(s,t,e)=>{let r=`
1380
1381
  query GetLabels($first: Int!, $after: String) {
1381
1382
  projectLabels(first: $first, after: $after) {
1382
1383
  nodes {
1383
- ${xn}
1384
+ ${Wn}
1384
1385
  }
1385
1386
  pageInfo {
1386
1387
  hasNextPage
@@ -1388,36 +1389,36 @@ OR comment ~ currentUser() OR summary ~ currentUser() OR description ~ currentUs
1388
1389
  }
1389
1390
  }
1390
1391
  }
1391
- `;return(await H(s,t,r,{first:Kt,after:e})).projectLabels};var ye=(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))(ye||{});function Xr(s,t){return s?`${ye[s]}:${t||""}`:t??null}function Yr(s){if(!s)return{category:0};let[t,e]=s.split(":");return t in ye?{category:ye[t],cursor:e||void 0}:{category:0,cursor:s}}var Zr=100;function Xe(s){return s?s instanceof Date?s:new Date(s):null}var rs=`
1392
+ `;return(await K(s,t,r,{first:Zt,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 ss(s,t){return s?`${we[s]}:${t||""}`:t??null}function ns(s){if(!s)return{category:0};let[t,e]=s.split(":");return t in we?{category:we[t],cursor:e||void 0}:{category:0,cursor:s}}var os=100;function Ze(s){return s?s instanceof Date?s:new Date(s):null}var us=`
1392
1393
  id
1393
1394
  name
1394
1395
  key
1395
1396
  icon
1396
- `;function kn(s){return{id:s.id,name:s.name,key:s.key,iconUrl:s.icon}}var es=`
1397
+ `;function Hn(s){return{id:s.id,name:s.name,key:s.key,iconUrl:s.icon}}var is=`
1397
1398
  id
1398
1399
  name
1399
1400
  avatarUrl
1400
- `;function ts(s){return s?{id:s.id,name:s.name,username:s.name,email:null,avatarUrl:s.avatarUrl??null,url:null}:null}var Nn=`
1401
+ `;function as(s){return s?{id:s.id,name:s.name,username:s.name,email:null,avatarUrl:s.avatarUrl??null,url:null}:null}var Vn=`
1401
1402
  id
1402
1403
  name
1403
- `;function _n(s,t){if(s)return{id:s.id,name:s.name,key:t?.key||null,namespace:null,resourceId:t?.id||null}}var Bn=`
1404
+ `;function Jn(s,t){if(s)return{id:s.id,name:s.name,key:t?.key||null,namespace:null,resourceId:t?.id||null}}var Kn=`
1404
1405
  id
1405
1406
  sortOrder
1406
1407
  name
1407
1408
  description
1408
1409
  status
1409
1410
  targetDate
1410
- `;function Qn(s){return s?{id:s.id,number:s.sortOrder,title:s.name,description:s.description??null,isOpen:s.status!=="done",url:"",startDate:null,dueDate:Xe(s.targetDate)}:null}function jn(s){switch(s){case"completed":case"canceled":return"DONE";case"started":return"IN_PROGRESS";default:return"TO_DO"}}var Fn=`
1411
+ `;function Xn(s){return s?{id:s.id,number:s.sortOrder,title:s.name,description:s.description??null,isOpen:s.status!=="done",url:"",startDate:null,dueDate:Ze(s.targetDate)}:null}function Yn(s){switch(s){case"completed":case"canceled":return"DONE";case"started":return"IN_PROGRESS";default:return"TO_DO"}}var Zn=`
1411
1412
  id
1412
1413
  name
1413
1414
  color
1414
1415
  type
1415
- `;function Mn(s){return s?{id:s.id,name:s.name,color:s.color,category:jn(s.type)}:null}var Yt=`
1416
+ `;function eo(s){return s?{id:s.id,name:s.name,color:s.color,category:Yn(s.type)}:null}var tr=`
1416
1417
  creator {
1417
- ${es}
1418
+ ${is}
1418
1419
  }
1419
1420
  assignee {
1420
- ${es}
1421
+ ${is}
1421
1422
  }
1422
1423
  archivedAt
1423
1424
  createdAt
@@ -1425,35 +1426,35 @@ OR comment ~ currentUser() OR summary ~ currentUser() OR description ~ currentUs
1425
1426
  id
1426
1427
  identifier
1427
1428
  project {
1428
- ${Nn}
1429
+ ${Vn}
1429
1430
  }
1430
1431
  team {
1431
- ${rs}
1432
+ ${us}
1432
1433
  }
1433
1434
  state {
1434
- ${Fn}
1435
+ ${Zn}
1435
1436
  }
1436
1437
  title
1437
1438
  updatedAt
1438
1439
  url
1439
1440
  projectMilestone {
1440
- ${Bn}
1441
+ ${Kn}
1441
1442
  }
1442
- `;async function Xt(s){return{author:ts(await s.creator),assignees:[ts(await s.assignee)].filter(t=>t!=null),commentCount:null,closedDate:Xe(s.archivedAt),createdDate:Xe(s.createdAt),description:s.description??null,id:s.id,labels:[],number:s.identifier,repository:null,project:_n(await s.project,await s.team),state:Mn(await s.state),title:s.title,type:null,updatedDate:Xe(s.updatedAt),upvoteCount:null,url:s.url,milestone:Qn(await s.projectMilestone)}}var Ke=`
1443
+ `;async function er(s){return{author:as(await s.creator),assignees:[as(await s.assignee)].filter(t=>t!=null),commentCount:null,closedDate:Ze(s.archivedAt),createdDate:Ze(s.createdAt),description:s.description??null,id:s.id,labels:[],number:s.identifier,repository:null,project:Jn(await s.project,await s.team),state:eo(await s.state),title:s.title,type:null,updatedDate:Ze(s.updatedAt),upvoteCount:null,url:s.url,milestone:Xn(await s.projectMilestone)}}var Ye=`
1443
1444
  nodes {
1444
- ${Yt}
1445
+ ${tr}
1445
1446
  }
1446
1447
  pageInfo {
1447
1448
  hasNextPage
1448
1449
  endCursor
1449
1450
  }
1450
- `,pe=class extends O{async fetchIssue(t,e){let r=`
1451
+ `,me=class extends k{async fetchIssue(t,e){let r=`
1451
1452
  query GetIssue($identifier: String!) {
1452
1453
  issue(id: $identifier) {
1453
- ${Yt}
1454
+ ${tr}
1454
1455
  }
1455
1456
  }
1456
- `;return(await H(this.config,e,r,{identifier:t})).issue}async fetchOrganization(t){let e=`
1457
+ `;return(await K(this.config,e,r,{identifier:t})).issue}async fetchOrganization(t){let e=`
1457
1458
  query GetOrganization {
1458
1459
  organization {
1459
1460
  id
@@ -1461,15 +1462,15 @@ OR comment ~ currentUser() OR summary ~ currentUser() OR description ~ currentUs
1461
1462
  urlKey
1462
1463
  }
1463
1464
  }
1464
- `;return(await H(this.config,t,e)).organization}async fetchTeams(t){let e=`
1465
+ `;return(await K(this.config,t,e)).organization}async fetchTeams(t){let e=`
1465
1466
  query GetTeams {
1466
1467
  teams {
1467
1468
  nodes {
1468
- ${rs}
1469
+ ${us}
1469
1470
  }
1470
1471
  }
1471
1472
  }
1472
- `;return(await H(this.config,t,e)).teams}async rawRequest(t,e,r){return{data:await H(this.config,t,e,r)}}async fetchViewer(t){let e=`
1473
+ `;return(await K(this.config,t,e)).teams}async rawRequest(t,e,r){return{data:await K(this.config,t,e,r)}}async fetchViewer(t){let e=`
1473
1474
  query GetViewer {
1474
1475
  viewer {
1475
1476
  id
@@ -1478,23 +1479,23 @@ OR comment ~ currentUser() OR summary ~ currentUser() OR description ~ currentUs
1478
1479
  displayName
1479
1480
  }
1480
1481
  }
1481
- `;return(await H(this.config,t,e)).viewer}async getIssue(t,e={}){let r=await this.fetchIssue(t.number,e);return{data:await Xt(r)}}async getLinearOrganization(t={}){let e=await this.fetchOrganization(t);return{data:{id:e.id,name:e.name,key:e.urlKey,url:`https://linear.app/${e.urlKey}`}}}async getTeamsForCurrentUser(t={}){return{data:(await this.fetchTeams(t)).nodes.map(kn)}}async getProjects(t={},e={}){let r=await Wr(this.config,e,t.cursor??void 0);return{data:r.nodes.map(zr),pageInfo:{hasNextPage:r.pageInfo.hasNextPage,endCursor:r.pageInfo.endCursor??null}}}async getCycles(t={},e={}){let r=await Vr(this.config,e,t.cursor??void 0);return{data:r.nodes.map(Hr),pageInfo:{hasNextPage:r.pageInfo.hasNextPage,endCursor:r.pageInfo.endCursor??null}}}async getLabels(t={},e={}){let r=await Kr(this.config,e,t.cursor??void 0);return{data:r.nodes.map(Jr),pageInfo:{hasNextPage:r.pageInfo.hasNextPage,endCursor:r.pageInfo.endCursor??null}}}async getCurrentUser(t={}){return{data:await this.fetchViewer(t)}}async getIssuesForCurrentUser(t,e={}){let{cursor:r}=t,{category:n,cursor:o}=Yr(r),i=await this.fetchViewer(e),a,u,l=new Je,c=async(p,d)=>{if(u||n>p)return;let g=await d(Math.max(Zr-l.length,1),n===p?o:void 0);if(!g)return;let m=await bt(g.nodes.map(Xt));l.push(...m),g.pageInfo.hasNextPage&&(a=p,u=g.pageInfo.endCursor)};return await c(1,async(p,d)=>(await this.rawRequest(e,`
1482
+ `;return(await K(this.config,t,e)).viewer}async getIssue(t,e={}){let r=await this.fetchIssue(t.number,e);return{data:await er(r)}}async getLinearOrganization(t={}){let e=await this.fetchOrganization(t);return{data:{id:e.id,name:e.name,key:e.urlKey,url:`https://linear.app/${e.urlKey}`}}}async getTeamsForCurrentUser(t={}){return{data:(await this.fetchTeams(t)).nodes.map(Hn)}}async getProjects(t={},e={}){let r=await Yr(this.config,e,t.cursor??void 0);return{data:r.nodes.map(Xr),pageInfo:{hasNextPage:r.pageInfo.hasNextPage,endCursor:r.pageInfo.endCursor??null}}}async getCycles(t={},e={}){let r=await es(this.config,e,t.cursor??void 0);return{data:r.nodes.map(Zr),pageInfo:{hasNextPage:r.pageInfo.hasNextPage,endCursor:r.pageInfo.endCursor??null}}}async getLabels(t={},e={}){let r=await rs(this.config,e,t.cursor??void 0);return{data:r.nodes.map(ts),pageInfo:{hasNextPage:r.pageInfo.hasNextPage,endCursor:r.pageInfo.endCursor??null}}}async getCurrentUser(t={}){return{data:await this.fetchViewer(t)}}async getIssuesForCurrentUser(t,e={}){let{cursor:r}=t,{category:n,cursor:o}=ns(r),i=await this.fetchViewer(e),a,u,l=new Xe,d=async(p,c)=>{if(u||n>p)return;let g=await c(Math.max(os-l.length,1),n===p?o:void 0);if(!g)return;let m=await vt(g.nodes.map(er));l.push(...m),g.pageInfo.hasNextPage&&(a=p,u=g.pageInfo.endCursor)};return await d(1,async(p,c)=>(await this.rawRequest(e,`
1482
1483
  query GetAssignedIssues($first: Int!, $after: String) {
1483
1484
  viewer {
1484
1485
  issues: assignedIssues(first: $first, after: $after) {
1485
- ${Ke}
1486
+ ${Ye}
1486
1487
  }
1487
1488
  }
1488
1489
  }
1489
- `,{first:p,after:d})).data?.viewer?.issues),await c(2,async(p,d)=>(await this.rawRequest(e,`
1490
+ `,{first:p,after:c})).data?.viewer?.issues),await d(2,async(p,c)=>(await this.rawRequest(e,`
1490
1491
  query GetCreatedIssues($first: Int!, $after: String) {
1491
1492
  viewer {
1492
1493
  issues: createdIssues(first: $first, after: $after) {
1493
- ${Ke}
1494
+ ${Ye}
1494
1495
  }
1495
1496
  }
1496
1497
  }
1497
- `,{first:p,after:d})).data?.viewer?.issues),await c(4,async(p,d)=>(await this.rawRequest(e,`
1498
+ `,{first:p,after:c})).data?.viewer?.issues),await d(4,async(p,c)=>(await this.rawRequest(e,`
1498
1499
  query GetMentionedIssues($first: Int!, $after: String) {
1499
1500
  issues(
1500
1501
  first: $first
@@ -1515,10 +1516,10 @@ OR comment ~ currentUser() OR summary ~ currentUser() OR description ~ currentUs
1515
1516
  }]
1516
1517
  }
1517
1518
  ){
1518
- ${Ke}
1519
+ ${Ye}
1519
1520
  }
1520
1521
  }
1521
- `,{first:p,after:d})).data?.issues),await c(5,async(p,d)=>{let m=(await this.rawRequest(e,`
1522
+ `,{first:p,after:c})).data?.issues),await d(5,async(p,c)=>{let m=(await this.rawRequest(e,`
1522
1523
  query GetCommentedIssues($first: Int!, $after: String) {
1523
1524
  comments(
1524
1525
  first: $first
@@ -1541,7 +1542,7 @@ OR comment ~ currentUser() OR summary ~ currentUser() OR description ~ currentUs
1541
1542
  ){
1542
1543
  nodes {
1543
1544
  issue {
1544
- ${Yt}
1545
+ ${tr}
1545
1546
  }
1546
1547
  }
1547
1548
  pageInfo {
@@ -1550,10 +1551,10 @@ OR comment ~ currentUser() OR summary ~ currentUser() OR description ~ currentUs
1550
1551
  }
1551
1552
  }
1552
1553
  }
1553
- `,{first:p,after:d})).data?.comments;return m?{nodes:m.nodes.map(R=>R.issue),pageInfo:m.pageInfo}:void 0}),{data:l.items,pageInfo:{hasNextPage:!!u,endCursor:Xr(a,u)}}}async getIssues(t,e={}){let{teams:r,projects:n,labels:o,cursor:i}=t,a=[];if(r&&r.length>0){let g=r.map(m=>`"${m}"`).join(", ");a.push(`team: { id: { in: [${g}] } }`)}if(n&&n.length>0){let g=n.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=`
1554
+ `,{first:p,after:c})).data?.comments;return m?{nodes:m.nodes.map(R=>R.issue),pageInfo:m.pageInfo}:void 0}),{data:l.items,pageInfo:{hasNextPage:!!u,endCursor:ss(a,u)}}}async getIssues(t,e={}){let{teams:r,projects:n,labels:o,cursor:i}=t,a=[];if(r&&r.length>0){let g=r.map(m=>`"${m}"`).join(", ");a.push(`team: { id: { in: [${g}] } }`)}if(n&&n.length>0){let g=n.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=`
1554
1555
  query GetIssues($first: Int!, $after: String) {
1555
1556
  issues(first: $first, after: $after${u?", ":""}${u}) {
1556
- ${Ke}
1557
+ ${Ye}
1557
1558
  }
1558
1559
  }
1559
- `,p=(await this.rawRequest(e,l,{first:Zr,after:i})).data?.issues;return p?{data:await bt(p.nodes.map(Xt)),pageInfo:{hasNextPage:p.pageInfo.hasNextPage,endCursor:p.pageInfo.endCursor??null}}:{data:[],pageInfo:{hasNextPage:!1,endCursor:null}}}};var Q="https://api.trello.com",zn=1e3,j=(s,t)=>({...I(t),Authorization:`OAuth oauth_consumer_key="${s}", oauth_token="${t}"`}),Wn=s=>({id:s.id,username:s.username,url:s.url,name:s.fullName,email:s.email,avatarUrl:s.avatarUrl}),Hn=(s,t)=>{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(r=>({id:r.id,username:r.username,name:r.fullName,email:null,avatarUrl:r.avatarUrl,url:null})),description:null,state:t[s.idList??""]?{id:s.idList,name:t[s.idList].name,color:null}:null,type:null,repository:null,upvoteCount:s.badges.votes,labels:s.labels.map(r=>({color:r.color,description:null,id:r.id,name:r.name}))}},de=class extends O{async getCurrentUser(t,e={}){let r=await this.config.request({url:`${e.baseUrl||Q}/1/members/me`,headers:j(t.appKey,e.token||this.config.token)});return{data:{name:r.body.fullName,email:r.body.email,avatarUrl:r.body.avatarHash?`https://trello-members.s3.amazonaws.com/${r.body.id}/${r.body.avatarHash}/50.png`:null,id:r.body.id,username:r.body.username,url:r.body.url}}}async getBoardsForCurrentUser(t,e={}){return{data:(await this.config.request({url:`${e.baseUrl||Q}/1/members/me/boards?fields=name&filter=open`,headers:j(t.appKey,e.token||this.config.token)})).body.map(n=>({id:n.id,name:n.name}))}}async getListsForTrelloBoard(t,e={}){let{appKey:r,boardId:n}=t;return{data:(await this.config.request({url:`${e.baseUrl||Q}/1/boards/${n}/lists`,headers:j(r,e.token||this.config.token)})).body}}async getAccountForId(t,e={}){let{appKey:r,memberId:n}=t,o=await this.config.request({url:`${e.baseUrl||Q}/1/members/${n}`,headers:j(r,e.token||this.config.token)});return{data:Wn(o.body)}}async getAccountsForTrelloBoard(t,e={}){let{appKey:r,boardId:n}=t;return{data:(await this.config.request({url:`${e.baseUrl||Q}/1/boards/${n}/members`,headers:j(r,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(t,e={}){let r=["-is:archived","sort:edited"],{appKey:n,boardId:o,filterText:i,assigneeLogins:a,labelNamesOrColors:u,trelloBoardListsById:l}=t||{};a&&r.push("@me"),u&&u.forEach(d=>r.push(`label:"${d}"`));let c=`${i?`${i}`:""}${r.join(" ")} board:${o}`;return{data:(await this.config.request({url:`${e.baseUrl||Q}/1/search?query=${c}&cards_limit=${zn}&card_members=true`,headers:j(n,e.token||this.config.token)})).body.cards.map(d=>Hn(d,l||{}))}}async updateIssue(t,e,r,n){return await this.config.request({method:"PUT",url:`${n.baseUrl||Q}/1/cards/${e.id}?${r}`,headers:j(t,n.token||this.config.token)})}async setIssueStatus(t,e={}){let{appKey:r,issue:n,status:o}=t;if(!o.id)throw new Error('Trello requires a status "id" for this function.');let i=`idList=${o.id}`;if(!(await this.updateIssue(r,n,i,e)).body.id)throw new Error("Could not set issue status")}async setIssueAssignees(t,e={}){let{appKey:r,issue:n,assignees:o}=t,i=o.map(l=>l.id),a=`idMembers=${encodeURIComponent(i.join(","))}`;if(!(await this.updateIssue(r,n,a,e)).body.id)throw new Error("Could not set issue status")}async setIssueLabels(t,e={}){let{appKey:r,issue:n,labels:o}=t,i=o.map(u=>u.id).join(",");if(!(await this.config.request({method:"PUT",url:`${e.baseUrl||Q}/1/cards/${n.id}?idLabels=${encodeURIComponent(i)}`,headers:j(r,e.token||this.config.token)})).body.id)throw new Error("Could not set issue status")}async setIssueArchived(t,e={}){let{appKey:r,issue:n,archived:o}=t;if(!(await this.config.request({method:"PUT",url:`${e.baseUrl||Q}/1/cards/${n.id}?closed=${o}`,headers:j(r,e.token||this.config.token)})).body.id)throw new Error("Could not update issue archived status")}async archiveIssue(t,e={}){await this.setIssueArchived({...t,archived:!0},e)}async unArchiveIssue(t,e={}){await this.setIssueArchived({...t,archived:!1},e)}async getLabelsForBoard(t,e={}){let{appKey:r,boardId:n}=t;return{data:(await this.config.request({url:`${e.baseUrl||Q}/1/boards/${n}/labels`,headers:j(r,e.token||this.config.token)})).body.map(i=>({color:i.color,description:null,id:i.id,name:i.name}))}}};var Ye={};k(Ye,{default:()=>Vn});var Vn={};var Ze={};k(Ze,{default:()=>Jn});var Jn={};var dt={};k(dt,{decode:()=>Zt,decodeV0:()=>Zn,encode:()=>Yn,validate:()=>Xn});var A=(e=>(e.Zero="0",e.One="1",e))(A||{}),U=(e=>(e.PullRequest="pr",e.Issue="issue",e))(U||{}),D=(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))(D||{});var et=class{constructor(){}validate(t){if(!t.organizationName)throw new Error("organizationName is required");if(!t.projectId)throw new Error("projectId is required");if(!t.entityId)throw new Error("issueId is required")}encode(t){if(this.validate(t),!t.organizationName||!t.projectId||!t.entityId)throw new Error("Missing required fields for Azure DevOps issue uniqueId");let e=[];return e.push(t.provider),e.push("issue"),e.push("1"),t.provider==="azureDevOpsServer"?e.push(t.domain):e.push(""),e.push(t.organizationName),e.push(t.projectId),e.push(t.entityId),JSON.stringify(e)}decode(t){if(t.length<7)throw new Error("Invalid Azure DevOps issue uniqueId, check version");return{provider:t[0],entityType:t[1],version:t[2],domain:t[3]==""?null:t[3],resourceId:null,accountOrOrgId:null,organizationName:t[4],projectId:t[5],repoId:null,entityId:t[6]}}};var tt=class{constructor(){}validate(t){if(!t.organizationName)throw new Error("organizationName is required");if(!t.projectId)throw new Error("projectId is required");if(!t.repoId)throw new Error("repoId is required");if(!t.entityId)throw new Error("entityId is required")}encode(t){if(this.validate(t),!t.organizationName||!t.projectId||!t.repoId||!t.entityId)throw new Error("Missing required fields for Azure DevOps pull request uniqueId");let e=[];return e.push(t.provider),e.push("pr"),e.push("1"),t.provider==="azureDevOpsServer"?e.push(t.domain):e.push(""),e.push(t.organizationName),e.push(t.projectId),e.push(t.repoId),e.push(t.entityId),JSON.stringify(e)}decode(t){if(t.length<8)throw new Error("Invalid Azure DevOps pull request uniqueId, check version");return{provider:t[0],entityType:t[1],version:t[2],domain:t[3]==""?null:t[3],resourceId:null,accountOrOrgId:null,organizationName:t[4],projectId:t[5],repoId:t[6],entityId:t[7]}}};var rt=class{constructor(){}validate(t){if(!t.repoId)throw new Error("repoId is required");if(!t.entityId)throw new Error("issueId is required")}encode(t){if(this.validate(t),!t.repoId||!t.entityId)throw new Error("Missing required fields for Bitbucket DevOps issue uniqueId");let e=[];return e.push(t.provider),e.push("issue"),e.push("1"),t.provider==="bitbucketServer"?e.push(t.domain):e.push(""),e.push(t.repoId),e.push(t.entityId),JSON.stringify(e)}decode(t){if(t.length<6)throw new Error("Invalid Bitbucket DevOps issue uniqueId, check version");return{provider:t[0],entityType:t[1],version:t[2],domain:t[3]==""?null:t[3],resourceId:null,accountOrOrgId:null,organizationName:null,projectId:null,repoId:t[4],entityId:t[5]}}};var st=class{constructor(){}validate(t){if(!t.repoId)throw new Error("repoId is required");if(!t.entityId)throw new Error("entityId is required")}encode(t){if(this.validate(t),!t.repoId||!t.entityId)throw new Error("Missing required fields for Bitbucket DevOps pull request uniqueId");let e=[];return e.push(t.provider),e.push("pr"),e.push("1"),t.provider==="bitbucketServer"?e.push(t.domain):e.push(""),e.push(t.repoId),e.push(t.entityId),JSON.stringify(e)}decode(t){if(t.length<6)throw new Error("Invalid Bitbucket DevOps pull request uniqueId, check version");return{provider:t[0],entityType:t[1],version:t[2],domain:t[3]==""?null:t[3],resourceId:null,accountOrOrgId:null,organizationName:null,projectId:null,repoId:t[4],entityId:t[5]}}};var nt=class{constructor(){}validate(t){if(!t.entityId)throw new Error("entityId is required")}encode(t){if(this.validate(t),!t.entityId)throw new Error("Missing required fields for Github issue uniqueId");let e=[];return e.push(t.provider),e.push("issue"),e.push("1"),t.provider==="githubEnterprise"?e.push(t.domain):e.push(""),e.push(t.entityId),JSON.stringify(e)}decode(t){if(t.length<5)throw new Error("Invalid Github issue uniqueId, check version");return{provider:t[0],entityType:t[1],version:t[2],domain:t[3]==""?null:t[3],resourceId:null,accountOrOrgId:null,organizationName:null,projectId:null,repoId:null,entityId:t[4]}}};var ot=class{constructor(){}validate(t){if(!t.entityId)throw new Error("entityId is required")}encode(t){if(this.validate(t),!t.entityId)throw new Error("Missing required fields for Github pull request uniqueId");let e=[];return e.push(t.provider),e.push("pr"),e.push("1"),t.provider==="githubEnterprise"?e.push(t.domain):e.push(""),e.push(t.entityId),JSON.stringify(e)}decode(t){if(t.length<5)throw new Error("Invalid Github pull request uniqueId, check version");return{provider:t[0],entityType:t[1],version:t[2],domain:t[3]==""?null:t[3],resourceId:null,accountOrOrgId:null,organizationName:null,projectId:null,repoId:null,entityId:t[4]}}};var it=class{constructor(){}validate(t){if(!t.entityId)throw new Error("entityId is required")}encode(t){if(this.validate(t),!t.entityId)throw new Error("Missing required fields for Gitlab issue uniqueId");let e=[];return e.push(t.provider),e.push("issue"),e.push("1"),t.provider==="gitlabSelfHosted"?e.push(t.domain):e.push(""),e.push(t.entityId),JSON.stringify(e)}decode(t){if(t.length<5)throw new Error("Invalid Gitlab issue uniqueId, check version");return{provider:t[0],entityType:t[1],version:t[2],domain:t[3]==""?null:t[3],resourceId:null,accountOrOrgId:null,organizationName:null,projectId:null,repoId:null,entityId:t[4]}}};var at=class{constructor(){}validate(t){if(!t.entityId)throw new Error("entityId is required")}encode(t){if(this.validate(t),!t.entityId)throw new Error("Missing required fields for Gitlab pull request uniqueId");let e=[];return e.push(t.provider),e.push("pr"),e.push("1"),t.provider==="gitlabSelfHosted"?e.push(t.domain):e.push(""),e.push(t.entityId),JSON.stringify(e)}decode(t){if(t.length<5)throw new Error("Invalid Gitlab pull request uniqueId, check version");return{provider:t[0],entityType:t[1],version:t[2],domain:t[3]==""?null:t[3],resourceId:null,accountOrOrgId:null,organizationName:null,projectId:null,repoId:null,entityId:t[4]}}};var ut=class{constructor(){}validate(t){if(!t.projectId)throw new Error("projectId is required");if(!t.entityId)throw new Error("entityId is required")}encode(t){if(this.validate(t),!t.projectId||!t.entityId)throw new Error("Missing required fields for Jira issue uniqueId");let e=[];return e.push(t.provider),e.push("issue"),e.push("1"),t.provider=="jira"?(e.push(""),e.push(t.resourceId)):(e.push(t.domain),e.push("")),e.push(t.projectId),e.push(t.entityId),JSON.stringify(e)}decode(t){if(t.length<7)throw new Error("Invalid Jira issue uniqueId, check version");return{provider:t[0],entityType:t[1],version:t[2],domain:t[3]==""?null:t[3],resourceId:t[4]==""?null:t[4],accountOrOrgId:null,organizationName:null,projectId:t[5],repoId:null,entityId:t[6]}}};var lt=class{constructor(){}validate(t){if(!t.accountOrOrgId)throw new Error("accountOrOrgId is required");if(!t.projectId)throw new Error("projectId is required");if(!t.entityId)throw new Error("entityId is required")}encode(t){if(this.validate(t),!t.accountOrOrgId||!t.projectId||!t.entityId)throw new Error("Missing required fields for Trello issue uniqueId");let e=[];return e.push("trello"),e.push("issue"),e.push("1"),e.push(""),e.push(t.accountOrOrgId),e.push(t.projectId),e.push(t.entityId),JSON.stringify(e)}decode(t){if(t.length<7)throw new Error("Invalid Trello issue uniqueId, check version");return{provider:t[0],entityType:t[1],version:t[2],domain:t[3]==""?null:t[3],resourceId:null,accountOrOrgId:t[4],organizationName:null,projectId:t[5],repoId:null,entityId:t[6]}}};var pt=(s,t)=>{if(t!=="issue"&&t!=="pr")throw new Error("unknown entityType");switch(s){case"azure":case"azureDevOpsServer":return t==="pr"?new tt:new et;case"bitbucket":case"bitbucketServer":return t==="pr"?new st:new rt;case"github":case"githubEnterprise":return t==="pr"?new ot:new nt;case"gitlab":case"gitlabSelfHosted":return t==="pr"?new at:new it;case"jira":case"jiraServer":if(t==="pr")throw new Error("EntityType PullRequest is not valid for Jira");return new ut;case"trello":if(t==="pr")throw new Error("EntityType PullRequest is not valid for Jira");return new lt;default:throw new Error("unknown provider")}},Kn=s=>{if(!s.entityType)throw new Error("entityType is required");if(!s.provider)throw new Error("provider is required");if(!s.entityId)throw new Error("entityID is required")},Xn=s=>{if(s.version==="0"){Kn(s);return}pt(s.provider,s.entityType).validate(s)},Yn=s=>pt(s.provider,s.entityType).encode(s),Zt=s=>{let t=JSON.parse(s);if(!t||!t.length)throw new Error("invalid issue unique id");return pt(t[0],t[1]).decode(t)},Zn=(s,t,e)=>{if(!e)throw new Error("entityID is required");try{let r=JSON.parse(e);if(!r||!r.length)throw new Error("Invalid pull request uniqueId");let n=[s,t,"0",...r];return pt(s,t).decode(n)}catch{return{provider:s,entityType:t,version:"0",domain:"",resourceId:null,accountOrOrgId:null,organizationName:null,projectId:null,repoId:null,entityId:e}}};var ct={};k(ct,{CHANGES_REQUESTED_ACTION_CATEGORY:()=>us,CHANGES_REQUESTED_BUCKET_ID:()=>ir,CONFLICTS_ACTION_CATEGORY:()=>is,CONFLICTS_BUCKET_ID:()=>nr,DRAFT_ACTION_CATEGORY:()=>ds,DRAFT_BUCKET_ID:()=>lr,FAILING_CI_ACTION_CATEGORY:()=>os,FAILING_CI_BUCKET_ID:()=>sr,NEEDS_MY_REVIEW_ACTION_CATEGORY:()=>as,NEEDS_MY_REVIEW_BUCKET_ID:()=>or,OTHER_ACTION_CATEGORY:()=>cs,OTHER_BUCKET_ID:()=>pr,PINNED_BUCKET_ID:()=>er,READY_TO_MERGE_ACTION_CATEGORY:()=>ss,READY_TO_MERGE_BUCKET_ID:()=>tr,REVIEWER_COMMENTED_ACTION_CATEGORY:()=>ls,REVIEWER_COMMENTED_BUCKET_ID:()=>ar,SNOOZED_BUCKET_ID:()=>dr,UNASSIGNED_REVIEWERS_ACTION_CATEGORY:()=>ns,UNASSIGNED_REVIEWERS_BUCKET_ID:()=>rr,WAITING_FOR_REVIEW_ACTION_CATEGORY:()=>ps,WAITING_FOR_REVIEW_BUCKET_ID:()=>ur,getActionablePullRequests:()=>gs,groupPullRequestsByAssignee:()=>ro,groupPullRequestsByAuthor:()=>so,groupPullRequestsByGitKrakenTeam:()=>ao,groupPullRequestsByRepo:()=>to,groupPullRequestsByReviewer:()=>no,groupPullRequestsByWorkspace:()=>io,groupPullRequestsIntoBuckets:()=>eo});var G=(s,t,e,r)=>({id:s,faIconName:e,name:t,priority:r,pullRequests:[]}),er="pinned",tr="readyToMerge",rr="unassignedReviewers",sr="failingCI",nr="conflicts",or="needsMyReview",ir="changesRequested",ar="reviewerCommented",ur="waitingForReview",lr="draft",pr="other",dr="snoozed",ss="readyToMerge",ns="unassignedReviewers",os="failingCI",is="conflicts",as="needsMyReview",us="changesRequested",ls="reviewerCommented",ps="waitingForReview",ds="draft",cs="other",gs=(s,t,e)=>s.map(r=>{let o={...r,...{suggestedActionCategory:cs,priority:1e3,viewer:{canMerge:!1,isAuthor:!1,isAssignee:!1,isReviewer:!1,shouldMerge:!1,shouldAssignReviewer:!1,waitingOnReviews:!1,shouldReview:!1},failingCI:!1,hasConflicts:!1,changeRequestReviewCount:0,codeSuggestionsCount:0,commentReviewCount:0,approvalReviewCount:0}};t&&(o.viewer.isAuthor=r.author?.id===t.id,o.viewer.isAssignee=r.assignees?.some(u=>u.id===t.id)??!1,o.viewer.isReviewer=r.reviews?.some(u=>u.reviewer.id===t.id)??!1),o.viewer.canMerge=r.permissions?.canMerge??!0,o.hasConflicts=r.mergeableState==="CONFLICTS",o.failingCI=r.headCommit?.buildStatuses?.some(u=>u.state==="ERROR"||u.state==="FAILED")||r.mergeableState==="FAILING_CHECKS",o.commentReviewCount=r.reviews?.filter(u=>u.state==="COMMENTED").length??0,o.approvalReviewCount=r.reviews?.filter(u=>u.state==="APPROVED").length??0,o.changeRequestReviewCount=r.reviews?.filter(u=>u.state==="CHANGES_REQUESTED").length??0;let i=e?.enrichedItemsByUniqueId?.[r.uuid];i!=null&&(o.viewer.enrichedItems=i,i.some(u=>u.type==="pin")&&(o.viewer.pinned=!0,o.priority-=800),i.some(u=>u.type==="snooze")&&(o.viewer.snoozed=!0));let a=e?.codeSuggestionsCountByPrUuid?.[r.uuid]?.count||0;return a&&(o.codeSuggestionsCount=a),(!t||o.viewer.isAuthor||o.viewer.isAssignee&&!o.viewer.isReviewer)&&o.viewer.canMerge&&!o.isDraft&&!o.failingCI&&r.mergeableState==="MERGEABLE"&&(o.viewer.shouldMerge=!0,o.suggestedActionCategory=ss),(!t||o.viewer.isAuthor)&&r.isDraft&&(o.suggestedActionCategory=ds),(!t||o.viewer.isAuthor)&&r.reviewDecision==="REVIEW_REQUESTED"&&(o.suggestedActionCategory=ps,o.viewer.waitingOnReviews=!0),(!t||o.viewer.isAuthor)&&r.reviewDecision==="COMMENTED"&&(o.suggestedActionCategory=ls),(!t||o.viewer.isAuthor)&&o.failingCI&&(o.suggestedActionCategory=os),(!t||o.viewer.isAuthor)&&o.hasConflicts&&(o.suggestedActionCategory=is),(!t||o.viewer.isAuthor)&&(r.reviewDecision==="CHANGES_REQUESTED"||o.codeSuggestionsCount>0)&&(o.suggestedActionCategory=us),(!t||o.viewer.isAuthor)&&!r.reviews?.length&&(o.suggestedActionCategory=ns,o.viewer.shouldAssignReviewer=!0),t&&r.reviews?.some(u=>u.reviewer.id===t.id&&u.state==="REVIEW_REQUESTED")&&(o.suggestedActionCategory=as,o.viewer.shouldReview=!0),o}),eo=(s,t,e)=>{let r={pinned:G(er,"Pinned","thumbtack",e?.bucketPriorityOverride?.pinned??-1),readyToMerge:G(tr,"Ready to Merge","code-merge",e?.bucketPriorityOverride?.readyToMerge??0),unassignedReviewers:G(rr,"Unassigned Reviewers","user-plus",e?.bucketPriorityOverride?.unassignedReviewers??1),failingCI:G(sr,"Failing CI","circle-x",e?.bucketPriorityOverride?.failingCI??2),conflicts:G(nr,"Resolve Conflicts","triangle-exclamation",e?.bucketPriorityOverride?.conflicts??3),needsMyReview:G(or,"Needs My Review","eye",e?.bucketPriorityOverride?.needsMyReview??4),changesRequested:G(ir,"Suggested Changes","file-plus",e?.bucketPriorityOverride?.changesRequested??5),reviewerCommented:G(ar,"Reviewer Commented","comment",e?.bucketPriorityOverride?.reviewerCommented??6),waitingForReview:G(ur,"Waiting for Review","circle-pause",e?.bucketPriorityOverride?.waitingForReview??7),draft:G(lr,"Draft","compass-drafting",e?.bucketPriorityOverride?.draft??8),other:G(pr,"Other","ellipsis",e?.bucketPriorityOverride?.other??9),snoozed:G(dr,"Snoozed","snooze",e?.bucketPriorityOverride?.snoozed??10)},o=gs(s,t,e).reduce((i,a)=>(i[a.uuid]=a,i),{});return s.forEach(i=>{let a=o[i.uuid],u=!0;if(a.viewer.snoozed){r[dr].pullRequests.push(i);return}a.viewer.pinned&&r[er].pullRequests.push(i),(!t||a.viewer.isAuthor||a.viewer.isAssignee&&!a.viewer.isReviewer)&&!a.isDraft&&a.viewer.canMerge&&a.mergeableState==="MERGEABLE"&&(r[tr].pullRequests.push(i),u=!1),a.viewer.shouldAssignReviewer&&(r[rr].pullRequests.push(i),u=!1),(!t||a.viewer.isAuthor)&&a.failingCI&&(r[sr].pullRequests.push(i),u=!1),(!t||a.viewer.isAuthor)&&a.hasConflicts&&(r[nr].pullRequests.push(i),u=!1),a.viewer.shouldReview&&(r[or].pullRequests.push(i),u=!1),(!t||a.viewer.isAuthor)&&(a.reviewDecision==="CHANGES_REQUESTED"||a.codeSuggestionsCount>0)&&(r[ir].pullRequests.push(i),u=!1),(!t||a.viewer.isAuthor)&&a.reviewDecision==="COMMENTED"&&(r[ar].pullRequests.push(i),u=!1),(!t||a.viewer.isAuthor)&&a.reviewDecision==="REVIEW_REQUESTED"&&(r[ur].pullRequests.push(i),u=!1),a.isDraft&&(r[lr].pullRequests.push(i),u=!1),u&&r[pr].pullRequests.push(i)}),Object.values(r).forEach(i=>{i.pullRequests.sort((a,u)=>o[a.uuid].priority-o[u.uuid].priority)}),r},to=s=>{let t={};return s.forEach(e=>{let r=e.repository.id;t[r]?t[r].pullRequests.push(e):t[r]={name:e.repository.name,priority:0,pullRequests:[e],id:r}}),Z(t)},ro=s=>{let t="internal-no-assignees",e={[t]:{name:"No assignees",priority:-1,pullRequests:[],id:t,faIconName:"user-slash"}};return s.forEach(r=>{r.assignees&&r.assignees.length?r.assignees.forEach(n=>{let o=n.id;e[o]?e[o].pullRequests.push(r):e[o]={accountData:n,name:Pe(n,`Unknown Assignee ${Object.keys(e).length}`),priority:0,pullRequests:[r],id:o}}):e[t].pullRequests.push(r)}),Z(e)},so=s=>{let t="internal-no-author",e={[t]:{name:"No author",priority:-1,pullRequests:[],id:t,faIconName:"user-slash"}};return s.forEach(r=>{if(r.author){let n=r.author.id;e[n]?e[n].pullRequests.push(r):e[n]={accountData:r.author,name:Pe(r.author,`Unknown Author ${Object.keys(e).length}`),priority:0,pullRequests:[r],id:n}}else e[t].pullRequests.push(r)}),Z(e)},no=s=>{let t="internal-no-reviewer",e={[t]:{name:"No reviewers",priority:-1,pullRequests:[],id:t,faIconName:"user-slash"}};return s.forEach(r=>{r.reviews&&r.reviews.length?r.reviews.forEach(n=>{let o=n.reviewer.id;e[o]?e[o].pullRequests.push(r):e[o]={accountData:n.reviewer,name:Pe(n.reviewer,`Unknown Reviewer ${Object.keys(e).length}`),priority:0,pullRequests:[r],id:o}}):e[t].pullRequests.push(r)}),Z(e)},oo=s=>s.azureProject?[`${s.azureProject}-${s.azureOrganizationId}`]:s.providerData?.repositories.nodes.map(t=>`${s.provider}-${t.repositoryId}`)??[],io=(s,t)=>{let e="internal-no-workspace",r={[e]:{name:"No workspace",priority:-1,pullRequests:[],id:e,faIconName:"folder-xmark"}};if(t.length){let n=t.reduce((o,i)=>(oo(i).forEach(u=>{o[u]?o[u].push(i):o[u]=[i]}),o),{});s.forEach(o=>{let{provider:i}=Zt(o.uuid),a=i==="github"?o.repository.graphQLId:o.repository.id,u=i==="azure"?[`${i}-${a}`,`${o.repository.project}-${o.repository.owner.login}`]:[`${i}-${a}`],l=!1,c=u.reduce((p,d)=>n[d]?p.concat(n[d]):p,[]);c?.length&&c.forEach(p=>{l=!0;let d=p.id;r[d]?r[d].pullRequests.push(o):r[d]={name:p.name,priority:0,pullRequests:[o],id:d,faIconName:"folder"}}),l||r[e].pullRequests.push(o)})}else r[e].pullRequests=s;return Z(r)},ao=(s,t,e,r)=>{let n="internal-no-team",o={[n]:{name:"No team",priority:-1,pullRequests:[],id:n}};return r.length?s.forEach(i=>{let a=!1,u=new Set;u.add(i.author?.id),i.assignees?.forEach(l=>u.add(l.id)),i.reviews?.forEach(l=>u.add(l.reviewer.id)),r.forEach(l=>{if(l.members?.some(p=>{let d=t[p.id]?.[e]?.providerID;return d&&u.has(d)})){a=!0;let p=l.id;o[p]?o[p].pullRequests.push(i):o[p]={name:l.name,priority:0,pullRequests:[i],id:p,teamData:l}}}),a||o[n].pullRequests.push(i)}):o[n].pullRequests=s,Z(o)};var gt={};k(gt,{getPullRequestRank:()=>uo});var uo=(s,t,e)=>{let r=0,n,o;return s.reviews?.forEach(i=>{i.reviewer.id===t&&(n=i.state),i.state==="CHANGES_REQUESTED"?o="CHANGES_REQUESTED":i.state==="APPROVED"&&o!=="CHANGES_REQUESTED"&&(o="APPROVED")}),o||(o="REVIEW_REQUESTED"),s.author?.id===t?r+=1e3:s.assignees?.find(i=>i.id===t)?r+=900:n==="REVIEW_REQUESTED"?r+=800:e&&(r+=700),o==="APPROVED"?s.mergeableState==="MERGEABLE"?r+=100:s.mergeableState==="CONFLICTS"?r+=90:r+=80:o=="CHANGES_REQUESTED"&&(r+=70),r};var mt={};k(mt,{default:()=>lo});var lo={};var ht={};k(ht,{default:()=>po});var po={};var ft={};k(ft,{default:()=>co});var co={};var ms=s=>{let t={request:s?.request};return{azureDevOps:new re({...t,...s?.azureDevOps}),bitbucket:new se({...t,...s?.bitbucket}),bitbucketServer:new ne({...t,...s?.bitbucketServer}),github:new oe({...t,...s?.github}),gitlab:new ae({...t,...s?.gitlab}),jira:new ue({...t,...s?.jira}),jiraServer:new le({...t,...s?.jiraServer}),linear:new pe({...t,...s?.linear}),trello:new de({...t,...s?.trello})}};var hs=(i=>(i.Conflicts="conflicts",i.Failure="failure",i.NotSet="notSet",i.Queued="queued",i.RejectedByPolicy="rejectedByPolicy",i.Succeeded="succeeded",i))(hs||{});var fs=(e=>(e.Completed="COMPLETED",e.NotPlanned="NOT_PLANNED",e))(fs||{});var go=ms;var mo={azureDevOps:Ye,bitbucket:Ze,bitbucketServer:Ce,github:gt,gitlab:mt,gitProvider:ct,jira:ht,trello:ft,entityIdentifier:dt};
1560
+ `,p=(await this.rawRequest(e,l,{first:os,after:i})).data?.issues;return p?{data:await vt(p.nodes.map(er)),pageInfo:{hasNextPage:p.pageInfo.hasNextPage,endCursor:p.pageInfo.endCursor??null}}:{data:[],pageInfo:{hasNextPage:!1,endCursor:null}}}};var F="https://api.trello.com",to=1e3,M=(s,t)=>({...I(t),Authorization:`OAuth oauth_consumer_key="${s}", oauth_token="${t}"`}),ro=s=>({id:s.id,username:s.username,url:s.url,name:s.fullName,email:s.email,avatarUrl:s.avatarUrl}),so=(s,t)=>{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(r=>({id:r.id,username:r.username,name:r.fullName,email:null,avatarUrl:r.avatarUrl,url:null})),description:null,state:t[s.idList??""]?{id:s.idList,name:t[s.idList].name,color:null}:null,type:null,repository:null,upvoteCount:s.badges.votes,labels:s.labels.map(r=>({color:r.color,description:null,id:r.id,name:r.name}))}},he=class extends k{async getCurrentUser(t,e={}){let r=await this.config.request({url:`${e.baseUrl||F}/1/members/me`,headers:M(t.appKey,e.token||this.config.token)});return{data:{name:r.body.fullName,email:r.body.email,avatarUrl:r.body.avatarHash?`https://trello-members.s3.amazonaws.com/${r.body.id}/${r.body.avatarHash}/50.png`:null,id:r.body.id,username:r.body.username,url:r.body.url}}}async getBoardsForCurrentUser(t,e={}){return{data:(await this.config.request({url:`${e.baseUrl||F}/1/members/me/boards?fields=name&filter=open`,headers:M(t.appKey,e.token||this.config.token)})).body.map(n=>({id:n.id,name:n.name}))}}async getListsForTrelloBoard(t,e={}){let{appKey:r,boardId:n}=t;return{data:(await this.config.request({url:`${e.baseUrl||F}/1/boards/${n}/lists`,headers:M(r,e.token||this.config.token)})).body}}async getAccountForId(t,e={}){let{appKey:r,memberId:n}=t,o=await this.config.request({url:`${e.baseUrl||F}/1/members/${n}`,headers:M(r,e.token||this.config.token)});return{data:ro(o.body)}}async getAccountsForTrelloBoard(t,e={}){let{appKey:r,boardId:n}=t;return{data:(await this.config.request({url:`${e.baseUrl||F}/1/boards/${n}/members`,headers:M(r,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(t,e={}){let r=["-is:archived","sort:edited"],{appKey:n,boardId:o,filterText:i,assigneeLogins:a,labelNamesOrColors:u,trelloBoardListsById:l}=t||{};a&&r.push("@me"),u&&u.forEach(c=>r.push(`label:"${c}"`));let d=`${i?`${i}`:""}${r.join(" ")} board:${o}`;return{data:(await this.config.request({url:`${e.baseUrl||F}/1/search?query=${d}&cards_limit=${to}&card_members=true`,headers:M(n,e.token||this.config.token)})).body.cards.map(c=>so(c,l||{}))}}async updateIssue(t,e,r,n){return await this.config.request({method:"PUT",url:`${n.baseUrl||F}/1/cards/${e.id}?${r}`,headers:M(t,n.token||this.config.token)})}async setIssueStatus(t,e={}){let{appKey:r,issue:n,status:o}=t;if(!o.id)throw new Error('Trello requires a status "id" for this function.');let i=`idList=${o.id}`;if(!(await this.updateIssue(r,n,i,e)).body.id)throw new Error("Could not set issue status")}async setIssueAssignees(t,e={}){let{appKey:r,issue:n,assignees:o}=t,i=o.map(l=>l.id),a=`idMembers=${encodeURIComponent(i.join(","))}`;if(!(await this.updateIssue(r,n,a,e)).body.id)throw new Error("Could not set issue status")}async setIssueLabels(t,e={}){let{appKey:r,issue:n,labels:o}=t,i=o.map(u=>u.id).join(",");if(!(await this.config.request({method:"PUT",url:`${e.baseUrl||F}/1/cards/${n.id}?idLabels=${encodeURIComponent(i)}`,headers:M(r,e.token||this.config.token)})).body.id)throw new Error("Could not set issue status")}async setIssueArchived(t,e={}){let{appKey:r,issue:n,archived:o}=t;if(!(await this.config.request({method:"PUT",url:`${e.baseUrl||F}/1/cards/${n.id}?closed=${o}`,headers:M(r,e.token||this.config.token)})).body.id)throw new Error("Could not update issue archived status")}async archiveIssue(t,e={}){await this.setIssueArchived({...t,archived:!0},e)}async unArchiveIssue(t,e={}){await this.setIssueArchived({...t,archived:!1},e)}async getLabelsForBoard(t,e={}){let{appKey:r,boardId:n}=t;return{data:(await this.config.request({url:`${e.baseUrl||F}/1/boards/${n}/labels`,headers:M(r,e.token||this.config.token)})).body.map(i=>({color:i.color,description:null,id:i.id,name:i.name}))}}};var et={};_(et,{default:()=>no});var no={};var tt={};_(tt,{default:()=>oo});var oo={};var gt={};_(gt,{decode:()=>rr,decodeV0:()=>lo,encode:()=>uo,validate:()=>ao});var U=(e=>(e.Zero="0",e.One="1",e))(U||{}),$=(e=>(e.PullRequest="pr",e.Issue="issue",e))($||{}),L=(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))(L||{});var rt=class{constructor(){}validate(t){if(!t.organizationName)throw new Error("organizationName is required");if(!t.projectId)throw new Error("projectId is required");if(!t.entityId)throw new Error("issueId is required")}encode(t){if(this.validate(t),!t.organizationName||!t.projectId||!t.entityId)throw new Error("Missing required fields for Azure DevOps issue uniqueId");let e=[];return e.push(t.provider),e.push("issue"),e.push("1"),t.provider==="azureDevOpsServer"?e.push(t.domain):e.push(""),e.push(t.organizationName),e.push(t.projectId),e.push(t.entityId),JSON.stringify(e)}decode(t){if(t.length<7)throw new Error("Invalid Azure DevOps issue uniqueId, check version");return{provider:t[0],entityType:t[1],version:t[2],domain:t[3]==""?null:t[3],resourceId:null,accountOrOrgId:null,organizationName:t[4],projectId:t[5],repoId:null,entityId:t[6]}}};var st=class{constructor(){}validate(t){if(!t.organizationName)throw new Error("organizationName is required");if(!t.projectId)throw new Error("projectId is required");if(!t.repoId)throw new Error("repoId is required");if(!t.entityId)throw new Error("entityId is required")}encode(t){if(this.validate(t),!t.organizationName||!t.projectId||!t.repoId||!t.entityId)throw new Error("Missing required fields for Azure DevOps pull request uniqueId");let e=[];return e.push(t.provider),e.push("pr"),e.push("1"),t.provider==="azureDevOpsServer"?e.push(t.domain):e.push(""),e.push(t.organizationName),e.push(t.projectId),e.push(t.repoId),e.push(t.entityId),JSON.stringify(e)}decode(t){if(t.length<8)throw new Error("Invalid Azure DevOps pull request uniqueId, check version");return{provider:t[0],entityType:t[1],version:t[2],domain:t[3]==""?null:t[3],resourceId:null,accountOrOrgId:null,organizationName:t[4],projectId:t[5],repoId:t[6],entityId:t[7]}}};var nt=class{constructor(){}validate(t){if(!t.repoId)throw new Error("repoId is required");if(!t.entityId)throw new Error("issueId is required")}encode(t){if(this.validate(t),!t.repoId||!t.entityId)throw new Error("Missing required fields for Bitbucket DevOps issue uniqueId");let e=[];return e.push(t.provider),e.push("issue"),e.push("1"),t.provider==="bitbucketServer"?e.push(t.domain):e.push(""),e.push(t.repoId),e.push(t.entityId),JSON.stringify(e)}decode(t){if(t.length<6)throw new Error("Invalid Bitbucket DevOps issue uniqueId, check version");return{provider:t[0],entityType:t[1],version:t[2],domain:t[3]==""?null:t[3],resourceId:null,accountOrOrgId:null,organizationName:null,projectId:null,repoId:t[4],entityId:t[5]}}};var ot=class{constructor(){}validate(t){if(!t.repoId)throw new Error("repoId is required");if(!t.entityId)throw new Error("entityId is required")}encode(t){if(this.validate(t),!t.repoId||!t.entityId)throw new Error("Missing required fields for Bitbucket DevOps pull request uniqueId");let e=[];return e.push(t.provider),e.push("pr"),e.push("1"),t.provider==="bitbucketServer"?e.push(t.domain):e.push(""),e.push(t.repoId),e.push(t.entityId),JSON.stringify(e)}decode(t){if(t.length<6)throw new Error("Invalid Bitbucket DevOps pull request uniqueId, check version");return{provider:t[0],entityType:t[1],version:t[2],domain:t[3]==""?null:t[3],resourceId:null,accountOrOrgId:null,organizationName:null,projectId:null,repoId:t[4],entityId:t[5]}}};var it=class{constructor(){}validate(t){if(!t.entityId)throw new Error("entityId is required")}encode(t){if(this.validate(t),!t.entityId)throw new Error("Missing required fields for Github issue uniqueId");let e=[];return e.push(t.provider),e.push("issue"),e.push("1"),t.provider==="githubEnterprise"?e.push(t.domain):e.push(""),e.push(t.entityId),JSON.stringify(e)}decode(t){if(t.length<5)throw new Error("Invalid Github issue uniqueId, check version");return{provider:t[0],entityType:t[1],version:t[2],domain:t[3]==""?null:t[3],resourceId:null,accountOrOrgId:null,organizationName:null,projectId:null,repoId:null,entityId:t[4]}}};var at=class{constructor(){}validate(t){if(!t.entityId)throw new Error("entityId is required")}encode(t){if(this.validate(t),!t.entityId)throw new Error("Missing required fields for Github pull request uniqueId");let e=[];return e.push(t.provider),e.push("pr"),e.push("1"),t.provider==="githubEnterprise"?e.push(t.domain):e.push(""),e.push(t.entityId),JSON.stringify(e)}decode(t){if(t.length<5)throw new Error("Invalid Github pull request uniqueId, check version");return{provider:t[0],entityType:t[1],version:t[2],domain:t[3]==""?null:t[3],resourceId:null,accountOrOrgId:null,organizationName:null,projectId:null,repoId:null,entityId:t[4]}}};var ut=class{constructor(){}validate(t){if(!t.entityId)throw new Error("entityId is required")}encode(t){if(this.validate(t),!t.entityId)throw new Error("Missing required fields for Gitlab issue uniqueId");let e=[];return e.push(t.provider),e.push("issue"),e.push("1"),t.provider==="gitlabSelfHosted"?e.push(t.domain):e.push(""),e.push(t.entityId),JSON.stringify(e)}decode(t){if(t.length<5)throw new Error("Invalid Gitlab issue uniqueId, check version");return{provider:t[0],entityType:t[1],version:t[2],domain:t[3]==""?null:t[3],resourceId:null,accountOrOrgId:null,organizationName:null,projectId:null,repoId:null,entityId:t[4]}}};var lt=class{constructor(){}validate(t){if(!t.entityId)throw new Error("entityId is required")}encode(t){if(this.validate(t),!t.entityId)throw new Error("Missing required fields for Gitlab pull request uniqueId");let e=[];return e.push(t.provider),e.push("pr"),e.push("1"),t.provider==="gitlabSelfHosted"?e.push(t.domain):e.push(""),e.push(t.entityId),JSON.stringify(e)}decode(t){if(t.length<5)throw new Error("Invalid Gitlab pull request uniqueId, check version");return{provider:t[0],entityType:t[1],version:t[2],domain:t[3]==""?null:t[3],resourceId:null,accountOrOrgId:null,organizationName:null,projectId:null,repoId:null,entityId:t[4]}}};var pt=class{constructor(){}validate(t){if(!t.projectId)throw new Error("projectId is required");if(!t.entityId)throw new Error("entityId is required")}encode(t){if(this.validate(t),!t.projectId||!t.entityId)throw new Error("Missing required fields for Jira issue uniqueId");let e=[];return e.push(t.provider),e.push("issue"),e.push("1"),t.provider=="jira"?(e.push(""),e.push(t.resourceId)):(e.push(t.domain),e.push("")),e.push(t.projectId),e.push(t.entityId),JSON.stringify(e)}decode(t){if(t.length<7)throw new Error("Invalid Jira issue uniqueId, check version");return{provider:t[0],entityType:t[1],version:t[2],domain:t[3]==""?null:t[3],resourceId:t[4]==""?null:t[4],accountOrOrgId:null,organizationName:null,projectId:t[5],repoId:null,entityId:t[6]}}};var dt=class{constructor(){}validate(t){if(!t.accountOrOrgId)throw new Error("accountOrOrgId is required");if(!t.projectId)throw new Error("projectId is required");if(!t.entityId)throw new Error("entityId is required")}encode(t){if(this.validate(t),!t.accountOrOrgId||!t.projectId||!t.entityId)throw new Error("Missing required fields for Trello issue uniqueId");let e=[];return e.push("trello"),e.push("issue"),e.push("1"),e.push(""),e.push(t.accountOrOrgId),e.push(t.projectId),e.push(t.entityId),JSON.stringify(e)}decode(t){if(t.length<7)throw new Error("Invalid Trello issue uniqueId, check version");return{provider:t[0],entityType:t[1],version:t[2],domain:t[3]==""?null:t[3],resourceId:null,accountOrOrgId:t[4],organizationName:null,projectId:t[5],repoId:null,entityId:t[6]}}};var ct=(s,t)=>{if(t!=="issue"&&t!=="pr")throw new Error("unknown entityType");switch(s){case"azure":case"azureDevOpsServer":return t==="pr"?new st:new rt;case"bitbucket":case"bitbucketServer":return t==="pr"?new ot:new nt;case"github":case"githubEnterprise":return t==="pr"?new at:new it;case"gitlab":case"gitlabSelfHosted":return t==="pr"?new lt:new ut;case"jira":case"jiraServer":if(t==="pr")throw new Error("EntityType PullRequest is not valid for Jira");return new pt;case"trello":if(t==="pr")throw new Error("EntityType PullRequest is not valid for Jira");return new dt;default:throw new Error("unknown provider")}},io=s=>{if(!s.entityType)throw new Error("entityType is required");if(!s.provider)throw new Error("provider is required");if(!s.entityId)throw new Error("entityID is required")},ao=s=>{if(s.version==="0"){io(s);return}ct(s.provider,s.entityType).validate(s)},uo=s=>ct(s.provider,s.entityType).encode(s),rr=s=>{let t=JSON.parse(s);if(!t||!t.length)throw new Error("invalid issue unique id");return ct(t[0],t[1]).decode(t)},lo=(s,t,e)=>{if(!e)throw new Error("entityID is required");try{let r=JSON.parse(e);if(!r||!r.length)throw new Error("Invalid pull request uniqueId");let n=[s,t,"0",...r];return ct(s,t).decode(n)}catch{return{provider:s,entityType:t,version:"0",domain:"",resourceId:null,accountOrOrgId:null,organizationName:null,projectId:null,repoId:null,entityId:e}}};var mt={};_(mt,{CHANGES_REQUESTED_ACTION_CATEGORY:()=>ms,CHANGES_REQUESTED_BUCKET_ID:()=>lr,CONFLICTS_ACTION_CATEGORY:()=>cs,CONFLICTS_BUCKET_ID:()=>ar,DRAFT_ACTION_CATEGORY:()=>Is,DRAFT_BUCKET_ID:()=>cr,FAILING_CI_ACTION_CATEGORY:()=>ds,FAILING_CI_BUCKET_ID:()=>ir,NEEDS_MY_REVIEW_ACTION_CATEGORY:()=>gs,NEEDS_MY_REVIEW_BUCKET_ID:()=>ur,OTHER_ACTION_CATEGORY:()=>Rs,OTHER_BUCKET_ID:()=>gr,PINNED_BUCKET_ID:()=>sr,READY_TO_MERGE_ACTION_CATEGORY:()=>ls,READY_TO_MERGE_BUCKET_ID:()=>nr,REVIEWER_COMMENTED_ACTION_CATEGORY:()=>hs,REVIEWER_COMMENTED_BUCKET_ID:()=>pr,SNOOZED_BUCKET_ID:()=>mr,UNASSIGNED_REVIEWERS_ACTION_CATEGORY:()=>ps,UNASSIGNED_REVIEWERS_BUCKET_ID:()=>or,WAITING_FOR_REVIEW_ACTION_CATEGORY:()=>fs,WAITING_FOR_REVIEW_BUCKET_ID:()=>dr,getActionablePullRequests:()=>ys,groupPullRequestsByAssignee:()=>go,groupPullRequestsByAuthor:()=>mo,groupPullRequestsByGitKrakenTeam:()=>Ro,groupPullRequestsByRepo:()=>co,groupPullRequestsByReviewer:()=>ho,groupPullRequestsByWorkspace:()=>Io,groupPullRequestsIntoBuckets:()=>po});var O=(s,t,e,r)=>({id:s,faIconName:e,name:t,priority:r,pullRequests:[]}),sr="pinned",nr="readyToMerge",or="unassignedReviewers",ir="failingCI",ar="conflicts",ur="needsMyReview",lr="changesRequested",pr="reviewerCommented",dr="waitingForReview",cr="draft",gr="other",mr="snoozed",ls="readyToMerge",ps="unassignedReviewers",ds="failingCI",cs="conflicts",gs="needsMyReview",ms="changesRequested",hs="reviewerCommented",fs="waitingForReview",Is="draft",Rs="other",ys=(s,t,e)=>s.map(r=>{let o={...r,...{suggestedActionCategory:Rs,priority:1e3,viewer:{canMerge:!1,isAuthor:!1,isAssignee:!1,isReviewer:!1,shouldMerge:!1,shouldAssignReviewer:!1,waitingOnReviews:!1,shouldReview:!1},failingCI:!1,hasConflicts:!1,changeRequestReviewCount:0,codeSuggestionsCount:0,commentReviewCount:0,approvalReviewCount:0}};t&&(o.viewer.isAuthor=r.author?.id===t.id,o.viewer.isAssignee=r.assignees?.some(u=>u.id===t.id)??!1,o.viewer.isReviewer=r.reviews?.some(u=>u.reviewer.id===t.id)??!1),o.viewer.canMerge=r.permissions?.canMerge??!0,o.hasConflicts=r.mergeableState==="CONFLICTS",o.failingCI=r.headCommit?.buildStatuses?.some(u=>u.state==="ERROR"||u.state==="FAILED")||r.mergeableState==="FAILING_CHECKS",o.commentReviewCount=r.reviews?.filter(u=>u.state==="COMMENTED").length??0,o.approvalReviewCount=r.reviews?.filter(u=>u.state==="APPROVED").length??0,o.changeRequestReviewCount=r.reviews?.filter(u=>u.state==="CHANGES_REQUESTED").length??0;let i=e?.enrichedItemsByUniqueId?.[r.uuid];i!=null&&(o.viewer.enrichedItems=i,i.some(u=>u.type==="pin")&&(o.viewer.pinned=!0,o.priority-=800),i.some(u=>u.type==="snooze")&&(o.viewer.snoozed=!0));let a=e?.codeSuggestionsCountByPrUuid?.[r.uuid]?.count||0;return a&&(o.codeSuggestionsCount=a),(!t||o.viewer.isAuthor||o.viewer.isAssignee&&!o.viewer.isReviewer)&&o.viewer.canMerge&&!o.isDraft&&!o.failingCI&&r.mergeableState==="MERGEABLE"&&(o.viewer.shouldMerge=!0,o.suggestedActionCategory=ls),(!t||o.viewer.isAuthor)&&r.isDraft&&(o.suggestedActionCategory=Is),(!t||o.viewer.isAuthor)&&r.reviewDecision==="REVIEW_REQUESTED"&&(o.suggestedActionCategory=fs,o.viewer.waitingOnReviews=!0),(!t||o.viewer.isAuthor)&&r.reviewDecision==="COMMENTED"&&(o.suggestedActionCategory=hs),(!t||o.viewer.isAuthor)&&o.failingCI&&(o.suggestedActionCategory=ds),(!t||o.viewer.isAuthor)&&o.hasConflicts&&(o.suggestedActionCategory=cs),(!t||o.viewer.isAuthor)&&(r.reviewDecision==="CHANGES_REQUESTED"||o.codeSuggestionsCount>0)&&(o.suggestedActionCategory=ms),(!t||o.viewer.isAuthor)&&!r.reviews?.length&&(o.suggestedActionCategory=ps,o.viewer.shouldAssignReviewer=!0),t&&r.reviews?.some(u=>u.reviewer.id===t.id&&u.state==="REVIEW_REQUESTED")&&(o.suggestedActionCategory=gs,o.viewer.shouldReview=!0),o}),po=(s,t,e)=>{let r={pinned:O(sr,"Pinned","thumbtack",e?.bucketPriorityOverride?.pinned??-1),readyToMerge:O(nr,"Ready to Merge","code-merge",e?.bucketPriorityOverride?.readyToMerge??0),unassignedReviewers:O(or,"Unassigned Reviewers","user-plus",e?.bucketPriorityOverride?.unassignedReviewers??1),failingCI:O(ir,"Failing CI","circle-x",e?.bucketPriorityOverride?.failingCI??2),conflicts:O(ar,"Resolve Conflicts","triangle-exclamation",e?.bucketPriorityOverride?.conflicts??3),needsMyReview:O(ur,"Needs My Review","eye",e?.bucketPriorityOverride?.needsMyReview??4),changesRequested:O(lr,"Suggested Changes","file-plus",e?.bucketPriorityOverride?.changesRequested??5),reviewerCommented:O(pr,"Reviewer Commented","comment",e?.bucketPriorityOverride?.reviewerCommented??6),waitingForReview:O(dr,"Waiting for Review","circle-pause",e?.bucketPriorityOverride?.waitingForReview??7),draft:O(cr,"Draft","compass-drafting",e?.bucketPriorityOverride?.draft??8),other:O(gr,"Other","ellipsis",e?.bucketPriorityOverride?.other??9),snoozed:O(mr,"Snoozed","snooze",e?.bucketPriorityOverride?.snoozed??10)},o=ys(s,t,e).reduce((i,a)=>(i[a.uuid]=a,i),{});return s.forEach(i=>{let a=o[i.uuid],u=!0;if(a.viewer.snoozed){r[mr].pullRequests.push(i);return}a.viewer.pinned&&r[sr].pullRequests.push(i),(!t||a.viewer.isAuthor||a.viewer.isAssignee&&!a.viewer.isReviewer)&&!a.isDraft&&a.viewer.canMerge&&a.mergeableState==="MERGEABLE"&&(r[nr].pullRequests.push(i),u=!1),a.viewer.shouldAssignReviewer&&(r[or].pullRequests.push(i),u=!1),(!t||a.viewer.isAuthor)&&a.failingCI&&(r[ir].pullRequests.push(i),u=!1),(!t||a.viewer.isAuthor)&&a.hasConflicts&&(r[ar].pullRequests.push(i),u=!1),a.viewer.shouldReview&&(r[ur].pullRequests.push(i),u=!1),(!t||a.viewer.isAuthor)&&(a.reviewDecision==="CHANGES_REQUESTED"||a.codeSuggestionsCount>0)&&(r[lr].pullRequests.push(i),u=!1),(!t||a.viewer.isAuthor)&&a.reviewDecision==="COMMENTED"&&(r[pr].pullRequests.push(i),u=!1),(!t||a.viewer.isAuthor)&&a.reviewDecision==="REVIEW_REQUESTED"&&(r[dr].pullRequests.push(i),u=!1),a.isDraft&&(r[cr].pullRequests.push(i),u=!1),u&&r[gr].pullRequests.push(i)}),Object.values(r).forEach(i=>{i.pullRequests.sort((a,u)=>o[a.uuid].priority-o[u.uuid].priority)}),r},co=s=>{let t={};return s.forEach(e=>{let r=e.repository.id;t[r]?t[r].pullRequests.push(e):t[r]={name:e.repository.name,priority:0,pullRequests:[e],id:r}}),te(t)},go=s=>{let t="internal-no-assignees",e={[t]:{name:"No assignees",priority:-1,pullRequests:[],id:t,faIconName:"user-slash"}};return s.forEach(r=>{r.assignees&&r.assignees.length?r.assignees.forEach(n=>{let o=n.id;e[o]?e[o].pullRequests.push(r):e[o]={accountData:n,name:Ee(n,`Unknown Assignee ${Object.keys(e).length}`),priority:0,pullRequests:[r],id:o}}):e[t].pullRequests.push(r)}),te(e)},mo=s=>{let t="internal-no-author",e={[t]:{name:"No author",priority:-1,pullRequests:[],id:t,faIconName:"user-slash"}};return s.forEach(r=>{if(r.author){let n=r.author.id;e[n]?e[n].pullRequests.push(r):e[n]={accountData:r.author,name:Ee(r.author,`Unknown Author ${Object.keys(e).length}`),priority:0,pullRequests:[r],id:n}}else e[t].pullRequests.push(r)}),te(e)},ho=s=>{let t="internal-no-reviewer",e={[t]:{name:"No reviewers",priority:-1,pullRequests:[],id:t,faIconName:"user-slash"}};return s.forEach(r=>{r.reviews&&r.reviews.length?r.reviews.forEach(n=>{let o=n.reviewer.id;e[o]?e[o].pullRequests.push(r):e[o]={accountData:n.reviewer,name:Ee(n.reviewer,`Unknown Reviewer ${Object.keys(e).length}`),priority:0,pullRequests:[r],id:o}}):e[t].pullRequests.push(r)}),te(e)},fo=s=>s.azureProject?[`${s.azureProject}-${s.azureOrganizationId}`]:s.providerData?.repositories.nodes.map(t=>`${s.provider}-${t.repositoryId}`)??[],Io=(s,t)=>{let e="internal-no-workspace",r={[e]:{name:"No workspace",priority:-1,pullRequests:[],id:e,faIconName:"folder-xmark"}};if(t.length){let n=t.reduce((o,i)=>(fo(i).forEach(u=>{o[u]?o[u].push(i):o[u]=[i]}),o),{});s.forEach(o=>{let{provider:i}=rr(o.uuid),a=i==="github"?o.repository.graphQLId:o.repository.id,u=i==="azure"?[`${i}-${a}`,`${o.repository.project}-${o.repository.owner.login}`]:[`${i}-${a}`],l=!1,d=u.reduce((p,c)=>n[c]?p.concat(n[c]):p,[]);d?.length&&d.forEach(p=>{l=!0;let c=p.id;r[c]?r[c].pullRequests.push(o):r[c]={name:p.name,priority:0,pullRequests:[o],id:c,faIconName:"folder"}}),l||r[e].pullRequests.push(o)})}else r[e].pullRequests=s;return te(r)},Ro=(s,t,e,r)=>{let n="internal-no-team",o={[n]:{name:"No team",priority:-1,pullRequests:[],id:n}};return r.length?s.forEach(i=>{let a=!1,u=new Set;u.add(i.author?.id),i.assignees?.forEach(l=>u.add(l.id)),i.reviews?.forEach(l=>u.add(l.reviewer.id)),r.forEach(l=>{if(l.members?.some(p=>{let c=t[p.id]?.[e]?.providerID;return c&&u.has(c)})){a=!0;let p=l.id;o[p]?o[p].pullRequests.push(i):o[p]={name:l.name,priority:0,pullRequests:[i],id:p,teamData:l}}}),a||o[n].pullRequests.push(i)}):o[n].pullRequests=s,te(o)};var ht={};_(ht,{getPullRequestRank:()=>yo});var yo=(s,t,e)=>{let r=0,n,o;return s.reviews?.forEach(i=>{i.reviewer.id===t&&(n=i.state),i.state==="CHANGES_REQUESTED"?o="CHANGES_REQUESTED":i.state==="APPROVED"&&o!=="CHANGES_REQUESTED"&&(o="APPROVED")}),o||(o="REVIEW_REQUESTED"),s.author?.id===t?r+=1e3:s.assignees?.find(i=>i.id===t)?r+=900:n==="REVIEW_REQUESTED"?r+=800:e&&(r+=700),o==="APPROVED"?s.mergeableState==="MERGEABLE"?r+=100:s.mergeableState==="CONFLICTS"?r+=90:r+=80:o=="CHANGES_REQUESTED"&&(r+=70),r};var ft={};_(ft,{default:()=>bo});var bo={};var It={};_(It,{default:()=>Po});var Po={};var Rt={};_(Rt,{default:()=>wo});var wo={};var bs=s=>{let t={request:s?.request};return{azureDevOps:new ie({...t,...s?.azureDevOps}),bitbucket:new ae({...t,...s?.bitbucket}),bitbucketServer:new ue({...t,...s?.bitbucketServer}),github:new le({...t,...s?.github}),gitlab:new de({...t,...s?.gitlab}),jira:new ce({...t,...s?.jira}),jiraServer:new ge({...t,...s?.jiraServer}),linear:new me({...t,...s?.linear}),trello:new he({...t,...s?.trello})}};var Ps=(i=>(i.Conflicts="conflicts",i.Failure="failure",i.NotSet="notSet",i.Queued="queued",i.RejectedByPolicy="rejectedByPolicy",i.Succeeded="succeeded",i))(Ps||{});var ws=(e=>(e.Completed="COMPLETED",e.NotPlanned="NOT_PLANNED",e))(ws||{});var vo=bs;var Eo={azureDevOps:et,bitbucket:tt,bitbucketServer:Ae,github:ht,gitlab:ft,gitProvider:mt,jira:It,trello:Rt,entityIdentifier:gt};