@gitkraken/provider-apis 0.29.4 → 0.29.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,4 @@
1
- "use strict";var Vt=Object.create;var le=Object.defineProperty;var Kt=Object.getOwnPropertyDescriptor;var Xt=Object.getOwnPropertyNames;var Zt=Object.getPrototypeOf,Yt=Object.prototype.hasOwnProperty;var er=(r,s)=>{for(var e in s)le(r,e,{get:s[e],enumerable:!0})},ht=(r,s,e,t)=>{if(s&&typeof s=="object"||typeof s=="function")for(let n of Xt(s))!Yt.call(r,n)&&n!==e&&le(r,n,{get:()=>s[n],enumerable:!(t=Kt(s,n))||t.enumerable});return r};var tr=(r,s,e)=>(e=r!=null?Vt(Zt(r)):{},ht(s||!r||!r.__esModule?le(e,"default",{value:r,enumerable:!0}):e,r)),rr=r=>ht(le({},"__esModule",{value:!0}),r);var hs={};er(hs,{AzureDevOps:()=>K,Bitbucket:()=>X,BitbucketServer:()=>Z,EntityIdentifierProviderType:()=>Ht,EntityType:()=>Wt,EntityVersion:()=>zt,GitBuildStatusStage:()=>ft,GitBuildStatusState:()=>pe,GitDiffLineType:()=>ke,GitHub:()=>ee,GitHubIssueCloseReason:()=>Jt,GitIssueState:()=>fe,GitLab:()=>re,GitMergeStrategy:()=>V,GitPullRequestMergeableState:()=>J,GitPullRequestReviewState:()=>j,GitPullRequestState:()=>H,GraphQLErrors:()=>b,Jira:()=>se,JiraServer:()=>ne,PullRequestAsyncStatus:()=>Mt,Trello:()=>oe,default:()=>ms,isFetch:()=>de});module.exports=rr(hs);var ft=(n=>(n.Build="build",n.Production="production",n.Staging="staging",n.Test="test",n))(ft||{}),pe=(p=>(p.ActionRequired="ACTION_REQUIRED",p.Cancelled="CANCELLED",p.Error="ERROR",p.Failed="FAILED",p.Pending="PENDING",p.Running="RUNNING",p.Skipped="SKIPPED",p.Success="SUCCESS",p.Warning="WARNING",p.OptionalActionRequired="OPTIONAL_ACTION_REQUIRED",p))(pe||{}),V=(o=>(o.MergeCommit="MERGE_COMMIT",o.Rebase="REBASE",o.RebaseThenMergeCommit="REBASE_THEN_MERGE_COMMIT",o.FastForward="FAST_FORWARD",o.Squash="SQUASH",o))(V||{}),H=(t=>(t.Open="OPEN",t.Closed="CLOSED",t.Merged="MERGED",t))(H||{}),j=(n=>(n.Approved="APPROVED",n.ChangesRequested="CHANGES_REQUESTED",n.Commented="COMMENTED",n.ReviewRequested="REVIEW_REQUESTED",n))(j||{}),J=(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))(J||{}),ke=(t=>(t.ADDED="ADDED",t.DELETED="DELETED",t.UNMODIFIED="UNMODIFIED",t))(ke||{});var Rt={APPROVED:0,COMMENTED:1,REVIEW_REQUESTED:2,CHANGES_REQUESTED:3},x=r=>!r||r.length===0?null:r.reduce((s,e)=>Rt[e.state]>Rt[s]?e.state:s,"APPROVED");var C=100;var It=tr(require("node-fetch")),bt=globalThis.fetch||It.default;var sr=async r=>{let s=r.headers.get("content-type")||"",e=null;if(s.startsWith("application/json")){let n=await r.text();e=n.trim().length>0?JSON.parse(n):null}else if(s.startsWith("text/")||s==="")e=await r.text();else if(s.startsWith("application/vnd.github.raw+json"))e=await r.arrayBuffer();else throw new Error(`Unsupported content-type: ${s}`);let t={body:e,headers:Object.fromEntries(r.headers.entries()),status:r.status,statusText:r.statusText};if(!r.ok){let n=new Error(r.statusText);throw Object.assign(n,{response:t}),n}return t},Ne=r=>async({url:s,...e})=>{let t=await r(s,e);return sr(t)};var de=(r,s=!1)=>r.name==="fetch"||s;var N=class{constructor(s){let e=(s==null?void 0:s.request)||bt;this.config={...s,request:de(e,s==null?void 0:s.forceIsFetch)?Ne(e):e}}updateConfig(s){this.config={...this.config,...s,request:s.request&&de(s.request,(s==null?void 0:s.forceIsFetch)??this.config.forceIsFetch)?Ne(s.request):this.config.request}}},A=class extends N{};var I=(r,s)=>{let e={};return r&&(e.Authorization=`${s?"Basic":"Bearer"} ${r}`),e},yt=r=>r?r.reduce((s,e)=>(s[e]=!0,s),{}):void 0,M=(r,s,e)=>!r||s.some(t=>r[t])?e:"",Pt=async r=>{var n,o,i;let s=[],e=!0,t;for(;e;){let a=await r(t);s=s.concat(a.data),e=!!((n=a==null?void 0:a.pageInfo)!=null&&n.hasNextPage),t=((o=a==null?void 0:a.pageInfo)==null?void 0:o.endCursor)||((i=a==null?void 0:a.pageInfo)==null?void 0:i.nextPage)}return s};var nr="https://app.vssps.visualstudio.com/_apis",or="https://vssps.dev.azure.com/",ir="https://dev.azure.com",S=(r,s={})=>I(s.token||r.token,s.isPAT||r.isPAT),wt=r=>r.url.replace("/_apis/git/repositories/","/_git/").replace(`/${r.repository.project.id}/`,`/${encodeURIComponent(r.repository.project.name)}/`).replace(`/${r.repository.id}/`,`/${encodeURIComponent(r.repository.name)}/`).replace("/pullRequests/","/pullrequest/"),Fe=(r,s)=>{let e=s.baseUrl||r.baseUrl||nr;return e=e.replace(/\/$/,""),e},v=(r,s)=>{let e=s.baseUrl||r.baseUrl||ir;return e=e.replace(/\/$/,""),e},_e=(r,s)=>{let e=s.baseUrl||r.baseUrl||or;return e=e.replace(/\/$/,""),e};var ar={active:"OPEN",completed:"MERGED",abandoned:"CLOSED"},ur={10:"APPROVED",5:"APPROVED",0:"REVIEW_REQUESTED",[-5]:"CHANGES_REQUESTED",[-10]:"CHANGES_REQUESTED"},Qe=r=>({id:r.id,name:r.displayName??null,username:(r.uniqueName||r.displayName)??null,email:null,avatarUrl:r.imageUrl??null,url:null}),ge=r=>r.startsWith("refs/heads/")?r.replace("refs/heads/",""):r,lr=r=>{switch(r){case"conflicts":return"CONFLICTS";case"failure":return"FAILING_CHECKS";case"rejectedByPolicy":return"BLOCKED";case"succeeded":return"MERGEABLE";case"notSet":case"queued":default:return"UNKNOWN"}},ce=(r,s)=>{var n;let e=[],t=[];return s.reviewers.forEach(o=>{let i={reviewer:Qe(o),state:ur[o.vote??0]||"REVIEW_REQUESTED"};o.isRequired&&e.push(i),t.push(i)}),{id:s.pullRequestId.toString(),title:s.title,number:s.codeReviewId,state:ar[s.status],isDraft:s.isDraft,commentCount:null,upvoteCount:null,author:Qe(s.createdBy),createdDate:new Date(s.creationDate),updatedDate:new Date(s.closedDate||s.creationDate),closedDate:s.closedDate?new Date(s.closedDate):null,mergedDate:s.closedDate&&s.status==="completed"?new Date(s.closedDate):null,repository:{id:s.repository.id,name:s.repository.name,project:s.repository.project.name,owner:{login:r},remoteInfo:null},headCommit:{buildStatuses:null},baseRef:{name:ge(s.targetRefName),oid:s.lastMergeTargetCommit.commitId},headRef:{name:ge(s.sourceRefName),oid:s.lastMergeSourceCommit.commitId},url:wt(s),assignees:s.reviewers.map(Qe),reviews:t,reviewDecision:x(e),additions:null,deletions:null,fileCount:null,commitCount:null,headRepository:s.forkSource?{id:s.forkSource.repository.id,name:s.forkSource.repository.name,project:void 0,owner:{login:r},remoteInfo:null}:{id:s.repository.id,name:s.repository.name,project:s.repository.project.name,owner:{login:r},remoteInfo:null},mergeableState:lr(s.mergeStatus),labels:((n=s.labels)==null?void 0:n.map(o=>({color:null,description:null,id:o.id,name:o.name})))??[],permissions:null}},St=(r,s)=>({id:s.id,name:s.name,namespace:r,project:s.project.name,projectId:s.project.id,webUrl:s.webUrl,httpsUrl:s.remoteUrl,sshUrl:s.sshUrl,defaultBranch:s.defaultBranch?{name:ge(s.defaultBranch)}:null,permissions:null}),pr=(r,s,e,t)=>{var l,p,d,c,g,m;let n=e.fields,o=n["System.AssignedTo"],i=n["System.State"],a=n["System.WorkItemType"],u;return i&&a&&(u=(l=t[a])==null?void 0:l[i]),{id:e.id.toString(),number:e.id.toString(),title:n["System.Title"],commentCount:n["System.CommentCount"],author:{avatarUrl:((d=(p=n["System.CreatedBy"]._links)==null?void 0:p.avatar)==null?void 0:d.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:((g=(c=o._links)==null?void 0:c.avatar)==null?void 0:g.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==null?void 0:u.title)||i,color:null},type:n["System.WorkItemType"],repository:null,project:{namespace:r,name:s,resourceId:null,key:null,id:null},upvoteCount:0,labels:((m=e.fields["System.Tags"])==null?void 0:m.split(";").map(R=>({color:null,description:null,id:null,name:R.trim()})))??[]}},K=class extends A{async getCurrentUser(s={},e={}){if(e.isPAT||this.config.isPAT)throw new Error("Azure DevOps does not support PATs for this function.");let t=`${Fe(this.config,e)}/profile/profiles/me`,n=await this.config.request({url:t,headers:S(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(s,e={}){let n=(await this.config.request({url:`${v(this.config,e)}/${encodeURIComponent(s.namespace)}/_apis/ConnectionData`,headers:S(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(s,e={}){if(!s.repo.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let n=(await this.config.request({url:`${v(this.config,e)}/${encodeURIComponent(s.repo.namespace)}/${encodeURIComponent(s.repo.project)}/_apis/git/repositories/${encodeURIComponent(s.repo.name)}/commits/${s.oid}`,headers:S(this.config,e)})).body.author;return{data:{name:n.name,email:n.email,avatarUrl:n.imageUrl}}}async getOrgsForUser(s,e={}){let t=`${Fe(this.config,e)}/accounts?memberId=${s.userId}&api-version=6.0`;return{data:(await this.config.request({url:t,headers:S(this.config,e)})).body.value.map(o=>({id:o.accountId,name:o.accountName}))}}async getCollectionsForUser(s,e={}){let t=`${v(this.config,e)}/_apis/projectCollections`;return{data:(await this.config.request({url:t,headers:S(this.config,e)})).body.value.map(o=>({id:o.id,name:o.name}))}}async getAzureProjects(s,e={}){let t=new URL(`${v(this.config,e)}/${encodeURIComponent(s.namespace)}/_apis/projects`);t.searchParams.set("$top",C.toString()),s.cursor&&t.searchParams.set("$skip",s.cursor);let n=await this.config.request({url:t.toString(),headers:S(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:s.namespace}))}}async getAzureProjectScopeDescriptor(s,e={}){let{namespace:t,projectId:n}=s;return{data:{scope:(await this.config.request({url:`${_e(this.config,e)}/${encodeURIComponent(t)}/_apis/graph/descriptors/${n}?api-version=6.0`,headers:S(this.config,e)})).body.value}}}async getAzureGraphAccountsForAzureProject(s,e={}){let{namespace:t,projectScopeDescriptor:n,cursor:o}=s,i=new URL(`${_e(this.config,e)}/${encodeURIComponent(t)}/_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:S(this.config,e)}),u=a.headers["x-ms-continuationtoken"];return{pageInfo:{endCursor:u||null,hasNextPage:!!u},data:a.body.value.map(l=>{var p,d,c,g;return{avatarUrl:((d=(p=l._links)==null?void 0:p.avatar)==null?void 0:d.href)??null,descriptor:l.descriptor??null,email:l.mailAddress??null,name:l.displayName??null,storageKeyURL:((g=(c=l._links)==null?void 0:c.storageKey)==null?void 0:g.href)??null,username:l.displayName??null}})}}async getAccountFromAzureGraphAccount(s,e={}){let{azureGraphAccount:t}=s;if(!t.storageKeyURL)throw new Error("Expected 'storageKeyURL' to not be null for 'azureGraphAccount'");let n=await this.config.request({url:t.storageKeyURL,headers:S(this.config,e)});return{data:{avatarUrl:t.avatarUrl,email:t.email,id:n.body.value,name:t.name,username:t.username,url:null}}}async getAccountsFromAzureGraphAccounts(s,e={}){let t=[];for(let n of s.azureGraphAccounts){let o=await this.getAccountFromAzureGraphAccount({azureGraphAccount:n},e);t.push(o.data)}return{data:t}}async getRepo(s,e={}){if(!s.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let t=await this.config.request({url:`${v(this.config,e)}/${encodeURIComponent(s.namespace)}/${encodeURIComponent(s.project)}/_apis/git/repositories/${encodeURIComponent(s.name)}`,headers:S(this.config,e)});return{data:St(s.namespace,t.body)}}async getRepos(s,e={}){let t=[],n=[];return await Promise.all(s.map(async o=>{try{let i=await this.getRepo(o,e);t.push(i.data)}catch(i){n.push({input:o,error:i})}})),{data:t,errors:n}}async getReposForAzureProject(s,e={}){if(!s.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');return{data:(await this.config.request({url:`${v(this.config,e)}/${encodeURIComponent(s.namespace)}/${encodeURIComponent(s.project)}/_apis/git/repositories`,headers:S(this.config,e)})).body.value.map(n=>St(s.namespace,n))}}async getRefs(s,e,t={}){if(!e.repo.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let n=new URL(`${v(this.config,t)}/${encodeURIComponent(e.repo.namespace)}/${encodeURIComponent(e.repo.project)}/_apis/git/repositories/${encodeURIComponent(e.repo.name)}/refs`);n.searchParams.set("filter",s),n.searchParams.set("$top",C.toString()),e.cursor&&n.searchParams.set("continuationToken",e.cursor);let o=await this.config.request({url:n.toString(),headers:S(this.config,t)}),i=o.headers["x-ms-continuationtoken"];return{pageInfo:{hasNextPage:!!i,endCursor:i||null},data:o.body.value.map(a=>({name:ge(a.name),commit:{oid:a.objectId,authoredDate:null,committedDate:null}}))}}async getBranches(s,e={}){return this.getRefs("heads",s,e)}async getTags(s,e={}){return this.getRefs("tags",s,e)}async getPullRequestsForRepoBase(s,e={},t=100){let{page:n,repo:o,assigneeLogins:i,authorLogin:a}=s||{},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:`${v(this.config,e)}/${encodeURIComponent(o.namespace)}/${encodeURIComponent(o.project||"")}/_apis/git/repositories/${encodeURIComponent(o.name)}/pullRequests?${l}&%24top=${t}&%24skip=${(u-1)*t}`,headers:S(this.config,e)})}async getPullRequestsForRepo(s,e={}){let n=s.page||1,o=await this.getPullRequestsForRepoBase(s,e,100);return{pageInfo:{hasNextPage:o.body.value.length===100,nextPage:n+1},data:o.body.value.map(i=>ce(s.repo.namespace,i))}}async getPullRequestsForRepos(s,e={}){if(!s.repos.every(o=>o.project))throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let{repos:t}=s||{},n=[];return await Promise.all(t.map(async o=>{try{(await this.getPullRequestsForRepoBase({repo:o,...s},e)).body.value.forEach(a=>{n.push(ce(o.namespace,a))})}catch(i){if(i.statusCode!==404&&i.statusCode!==401)throw i}})),{data:n}}async getPullRequestsForProjectBase(s,e={},t=100){let{namespace:n,project:o,page:i,assigneeLogins:a,authorLogin:u,repo:l}=s;if(l!=null&&l.project&&l.project!==o)throw new Error("Could not fetch pull requests, project mismatch");let p=i||1,d=new URL(`${v(this.config,e)}/${encodeURIComponent(n)}/${encodeURIComponent(o)}/_apis/git/pullRequests`);return d.searchParams.set("searchCriteria.status","1"),d.searchParams.set("$top",t.toString()),d.searchParams.set("$skip",((p-1)*t).toString()),l!=null&&l.id&&(l==null?void 0:l.project)===o&&d.searchParams.set("searchCriteria.repositoryId",l.id),a&&a.length&&d.searchParams.set("searchCriteria.reviewerId",a[0]),u&&d.searchParams.set("searchCriteria.creatorId",u),await this.config.request({url:d.toString(),headers:S(this.config,e)})}async getPullRequestsForProject(s,e={}){let n=s.page||1,o=await this.getPullRequestsForProjectBase(s,e,100);return{pageInfo:{hasNextPage:(o==null?void 0:o.body.value.length)===100,nextPage:n+1},data:(o==null?void 0:o.body.value.map(i=>ce(s.namespace,i)))||[]}}async getPullRequestsForProjects(s,e={}){let{projects:t}=s||{},n=[];return await Promise.all(t.map(async o=>{try{if(!s.repo||s.repo.project&&s.repo.project===o.project){let i=await this.getPullRequestsForProjectBase({...o,...s},e);i==null||i.body.value.forEach(a=>{n.push(ce(o.namespace,a))})}}catch(i){if(i.statusCode!==404&&i.statusCode!==401)throw i}})),{data:n}}async getAzurePullRequestLastMergeStatus(s,e={}){if(!s.repo.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let{repo:{namespace:t,project:n,name:o},pullRequestId:i}=s,a=await this.config.request({url:`${v(this.config,e)}/${encodeURIComponent(t)}/${encodeURIComponent(n||"")}/_apis/git/repositories/${o}/pullrequests/${i}?includeCommits=true?api-version=6.0`,headers:{...S(this.config,e)}});if(!a.body.mergeStatus)throw new Error("Could not fetch pull request");return{data:a.body.mergeStatus}}async updatePullRequest(s,e,t){return await this.config.request({method:"PATCH",url:`${v(this.config,t)}/${encodeURIComponent(s.repository.owner.login)}/${encodeURIComponent(s.repository.project)}/_apis/git/repositories/${s.repository.name}/pullrequests/${s.id}?api-version=6.0`,body:e,headers:{...S(this.config,t),"Content-Type":"application/json"}})}async closePullRequest(s,e={}){let{pullRequest:t}=s,n={status:"abandoned"};if(!(await this.updatePullRequest(t,JSON.stringify(n),e)).body.status)throw new Error("Could not close pull request")}async mergePullRequest(s,e={}){var u;let{pullRequest:t,mergeStrategy:n}=s,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:(u=t.headRef)==null?void 0:u.oid},status:"completed"};if(!(await this.updatePullRequest(t,JSON.stringify(i),e)).body.status)throw new Error("Could not merge pull request")}async addPullRequestLabel(s,e={}){let{pullRequest:t,label:n}=s;if(!t.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:`${v(this.config,e)}/${encodeURIComponent(t.repository.owner.login)}/${encodeURIComponent(t.repository.project)}/_apis/git/repositories/${t.repository.name}/pullrequests/${t.id}/labels?api-version=6.0`,body:JSON.stringify(o),headers:{...S(this.config,e),"Content-Type":"application/json"}})).body.id)throw new Error("Could not add pull request label")}async removePullRequestLabel(s,e={}){let{pullRequest:t,label:n}=s;if(!t.repository.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');await this.config.request({method:"DELETE",url:`${v(this.config,e)}/${encodeURIComponent(t.repository.owner.login)}/${encodeURIComponent(t.repository.project)}/_apis/git/repositories/${t.repository.name}/pullrequests/${t.id}/labels/${encodeURIComponent(n.name)}?api-version=6.0`,headers:{...S(this.config,e)}})}async setPullRequestLabels(s,e={}){let{pullRequest:t,labels:n}=s;if(!t.repository.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let o=t.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:t,label:i},e);for(let i of o)n.find(a=>i.id===a.id)||await this.removePullRequestLabel({pullRequest:t,label:i},e)}async setPullRequestAsDraft(s,e={}){let{pullRequest:t,isDraft:n}=s,o={isDraft:n};if(!(await this.updatePullRequest(t,JSON.stringify(o),e)).body.status)throw new Error("Could not set the pull request as draft")}async addPullRequestReviewer(s,e={}){let{pullRequest:t,reviewer:n,isRequired:o}=s,i={id:n.id,isRequired:o};if(!(await this.config.request({method:"PUT",url:`${v(this.config,e)}/${encodeURIComponent(t.repository.owner.login)}/${encodeURIComponent(t.repository.project)}/_apis/git/repositories/${t.repository.name}/pullrequests/${t.id}/reviewers/${n.id}?api-version=6.0`,body:JSON.stringify(i),headers:{...S(this.config,e),"Content-Type":"application/json"}})).body.id)throw new Error("Could not add pull request reviewer")}async removePullRequestReviewer(s,e={}){let{pullRequest:t,reviewer:n}=s;await this.config.request({method:"DELETE",url:`${v(this.config,e)}/${encodeURIComponent(t.repository.owner.login)}/${encodeURIComponent(t.repository.project)}/_apis/git/repositories/${t.repository.name}/pullrequests/${t.id}/reviewers/${n.id}?api-version=6.0`,headers:{...S(this.config,e),Accept:"application/json"}})}async setPullRequestReviewers(s,e={}){let{pullRequest:t,reviewers:n}=s;for(let o of n)t.assignees.find(i=>i.id===o.id)||await this.addPullRequestReviewer({pullRequest:t,reviewer:o,isRequired:!0},e);for(let o of t.assignees)n.find(i=>o.id===i.id)||await this.removePullRequestReviewer({pullRequest:t,reviewer:o},e)}async getIssuesForAzureProject(s,e={}){let{page:t,assigneeLogins:n,authorLogin:o,mentionLogin:i,labelNames:a,statusByWorkItemIdByStatusId:u}=s||{},l=t||1,p=200,d=["[Microsoft.VSTS.Common.ClosedDate] = ''","[System.TeamProject] = @project","[Microsoft.VSTS.Common.ResolvedDate] = ''"];o&&d.push(`[System.CreatedBy] = '${o.replace("'","''")}'`),n&&n[0]&&d.push(`[System.AssignedTo] = '${n[0].replace("'","''")}'`),i&&d.push("[System.Id] IN (@recentMentions)"),a&&a.forEach(h=>d.push(`[System.Tags] Contains '${h}'`));let c=`Select [Microsoft.VSTS.Common.ClosedDate], [Microsoft.VSTS.Common.ResolvedDate] From WorkItems Where ${d.join(" AND ")} order by [System.CreatedDate] desc`,g=await this.config.request({url:`${v(this.config,e)}/${encodeURIComponent(s.namespace)}/${encodeURIComponent(s.project)}/_apis/wit/wiql?api-version=6.0`,body:JSON.stringify({query:c}),method:"POST",headers:{...S(this.config,e),"Content-Type":"application/json"}}),m=g.body.workItems.slice((l-1)*p,p*l).map(h=>h.id);if(m.length==0)return{pageInfo:{hasNextPage:!1,nextPage:null},data:[]};let R=await this.config.request({url:`${v(this.config,e)}/${encodeURIComponent(s.namespace)}/${encodeURIComponent(s.project)}/_apis/wit/workitemsbatch?api-version=6.0`,body:JSON.stringify({ids:m,$expand:"Links"}),method:"POST",headers:{...S(this.config,e),"Content-Type":"application/json"}});return{pageInfo:{hasNextPage:g.body.workItems.length>p*l,nextPage:l+1},data:R.body.value.map(h=>pr(s.namespace,s.project,h,u||{}))}}async getPermissionsForRepos(s,e={}){let{namespace:t,repos:n}=s,o={4:["canPush","canCreateWebhook"],1024:["isAdmin"],2048:["isAdmin"],4096:["isAdmin"],8192:["isAdmin"]},i=p=>{let d="2e9eb7ed-3c0a-47d4-87c1-0ffdd275fd87",c=`repoV2/${p.projectId}/${p.id}`;return Object.keys(o).map(g=>({securityNamespaceId:d,token:c,permissions:g}))},a={alwaysAllowAdministrators:!1,evaluations:n.flatMap(i)};return{data:(await this.config.request({method:"POST",url:`${v(this.config,e)}/${encodeURIComponent(t)}/_apis/security/permissionevaluationbatch?api-version=7.0`,body:JSON.stringify(a),headers:{...S(this.config,e),"Content-Type":"application/json"}})).body.evaluations.reduce((p,d)=>{let[,c,g]=d.token.split("/"),m=`${c}/${g}`,R=o[d.permissions];for(let h of R)p[m]===void 0&&(p[m]={canCreateWebhook:!0,canPush:!0,isAdmin:!0}),d.value===!1&&(p[m][h]=!1);return p},{})}}async decorateReposWithPermissions(s,e={}){let{namespace:t,repos:n}=s,o=await this.getPermissionsForRepos({namespace:t,repos:n},e);return{data:n.map(i=>({...i,permissions:o.data[`${i.projectId}/${i.id}`]}))}}async updateIssue(s,e,t={}){return await this.config.request({method:"PATCH",url:`${v(this.config,t)}/${encodeURIComponent(s.project.namespace)}/${encodeURIComponent(s.project.name)}/_apis/wit/workitems/${s.id}?api-version=6.0`,body:JSON.stringify(e),headers:{...S(this.config,t),"Content-Type":"application/json-patch+json"}})}async setIssueStatus(s,e={}){var a;let{issue:t,status:n}=s,o=[{op:"add",path:"/fields/System.State",value:n.name}];if(!((a=(await this.updateIssue(t,o,e)).body.fields)!=null&&a["System.State"]))throw new Error("Could not set issue status")}async setIssueAssignee(s,e={}){var a;let{issue:t,assignee:n}=s,o=[{op:"add",path:"/fields/System.AssignedTo",value:(n==null?void 0:n.name)??""}];if(!((a=(await this.updateIssue(t,o,e)).body.fields)!=null&&a["System.State"]))throw new Error("Could not set issue assignee")}async setIssueLabels(s,e={}){var u;let{issue:t,labels:n}=s,i=[{op:"replace",path:"/fields/System.Tags",value:n.map(l=>l.name).join(";")}];if(!((u=(await this.updateIssue(t,i,e)).body.fields)!=null&&u["System.Tags"]))throw new Error("Could not set issue tags")}async getIssueTypesForAzureProject(s,e={}){if(!s.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let{namespace:t,project:n}=s;return{data:(await this.config.request({url:`${v(this.config,e)}/${encodeURIComponent(t)}/${encodeURIComponent(n||"")}/_apis/wit/workitemtypes?api-version=6.0`,headers:{...S(this.config,e)}})).body.value}}async getLabelsForProject(s,e={}){let{namespace:t,project:n}=s;return{data:(await this.config.request({url:`${v(this.config,e)}/${encodeURIComponent(t)}/${encodeURIComponent(n||"")}/_apis/wit/tags?api-version=6.0`,headers:{...S(this.config,e)}})).body.value.map(i=>({color:null,description:null,id:i.id,name:i.name,url:i.url}))}}};var L=(r,s={})=>I(s.token||r.token,s.isPAT||r.isPAT);var U="https://api.bitbucket.org/2.0",dr={OPEN:"OPEN",MERGED:"MERGED",DECLINED:"CLOSED"},me=r=>({id:r.uuid,name:r.display_name||r.nickname,username:r.nickname||r.display_name,email:null,avatarUrl:r.links.avatar.href,url:r.links.html.href}),vt=r=>{let s=r.links.clone,e=s==null?void 0:s.find(n=>n.name==="ssh"),t=s==null?void 0:s.find(n=>n.name==="https");return e&&t?{cloneUrlHTTPS:t.href,cloneUrlSSH:e.href}:null},Et=r=>{var s,e;return{id:r.uuid,namespace:r.workspace.slug,name:r.slug,webUrl:r.links.html.href,httpsUrl:((s=r.links.clone.find(t=>t.name==="https"))==null?void 0:s.href)??null,sshUrl:((e=r.links.clone.find(t=>t.name==="ssh"))==null?void 0:e.href)??null,defaultBranch:{name:r.mainbranch.name},permissions:null}},Be=r=>{var t;let s=r.id,e=((t=r.participants)==null?void 0:t.map(n=>{let o="REVIEW_REQUESTED";return n.approved?o="APPROVED":n.state==="changes_requested"?o="CHANGES_REQUESTED":n.participated_on!==null&&(o="COMMENTED"),{reviewer:me(n.user),state:o}}))??[];return{id:s.toString(),title:r.title,number:s,state:dr[r.state],isDraft:!1,commentCount:r.comment_count,upvoteCount:null,author:me(r.author),createdDate:new Date(r.created_on),updatedDate:new Date(r.updated_on),closedDate:null,mergedDate:null,repository:{id:r.destination.repository.uuid,name:r.destination.repository.name,owner:{login:r.destination.repository.full_name.split("/")[0]},remoteInfo:vt(r.destination.repository)},headCommit:{buildStatuses:null},baseRef:{name:r.destination.branch.name,oid:r.destination.commit.hash},headRef:{name:r.source.branch.name,oid:r.source.commit.hash},url:r.links.html.href,assignees:null,reviews:e,reviewDecision:x(e),additions:null,deletions:null,fileCount:null,commitCount:null,headRepository:{id:r.source.repository.uuid,name:r.source.repository.name,owner:{login:r.source.repository.full_name.split("/")[0]},remoteInfo:vt(r.source.repository)},mergeableState:"MERGEABLE",permissions:null}},cr=r=>{switch(r){case"owner":case"admin":return{canCreateWebhook:!0,canPush:!0,isAdmin:!0};case"write":return{canCreateWebhook:!1,canPush:!0,isAdmin:!1};case"read":case"none":return{canCreateWebhook:!1,canPush:!1,isAdmin:!1}}},X=class extends N{async refreshToken(s){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 ${s.base64ClientIDColonClientSecret}`},body:`grant_type=refresh_token&refresh_token=${s.refreshToken}`})).body}}async getCurrentUser(s={},e={}){let t=await this.config.request({url:`${U}/user`,headers:L(this.config,e)});return{data:me(t.body)}}async getUserForCommit(s,e={}){var i;let n=(await this.config.request({url:`${U}/repositories/${s.repo.namespace}/${s.repo.name}/commit/${s.oid}`,headers:L(this.config,e)})).body.author,o=n.raw.match(/([^<]+)<(.+)>/);return{data:{name:o?o[1].trim():null,email:o?o[2]:null,avatarUrl:((i=n.user)==null?void 0:i.links.avatar.href)||null}}}async getRepo(s,e={}){let t=await this.config.request({url:`${U}/repositories/${s.namespace}/${s.name}`,headers:L(this.config,e)});return{data:Et(t.body)}}async getRepos(s,e={}){let t=[],n=[];return await Promise.all(s.map(async o=>{try{let i=await this.getRepo(o,e);t.push(i.data)}catch(i){n.push({input:o,error:i})}})),{data:t,errors:n}}async getReposForCurrentUser(s,e={}){let t=new URL(`${U}/repositories`);t.searchParams.set("role","member"),t.searchParams.set("pagelen",C.toString()),s.cursor&&t.searchParams.set("after",s.cursor);let n=await this.config.request({url:t.toString(),headers:L(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(s,e={}){var i;let t=new URL(`${U}/repositories/${s.repo.namespace}/${s.repo.name}/refs/branches`);t.searchParams.set("page",((i=s.page)==null?void 0:i.toString())||"1"),t.searchParams.set("pagelen",C.toString());let n=await this.config.request({url:t.toString(),headers:L(this.config,e)}),o=!!n.body.next;return{pageInfo:{hasNextPage:o,nextPage:o?n.body.page+1:null},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 getTags(s,e={}){let t=new URL(`${U}/repositories/${s.repo.namespace}/${s.repo.name}/refs/tags`);t.searchParams.set("pagelen",C.toString()),s.cursor&&t.searchParams.set("page",s.cursor);let n=await this.config.request({url:t.toString(),headers:L(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 getWorkspacesForUser(s,e={}){var i;let t=new URL(`${U}/user/permissions/workspaces`);t.searchParams.set("page",((i=s.page)==null?void 0:i.toString())||"1"),t.searchParams.set("pagelen","50");let n=await this.config.request({url:t.toString(),headers:L(this.config,e)}),o=!!n.body.next;return{pageInfo:{hasNextPage:o,nextPage:o?n.body.page+1:null},data:n.body.values.map(a=>({id:a.workspace.uuid,slug:a.workspace.slug,name:a.workspace.name}))}}async getPullRequestsForUserAndWorkspace(s,e={}){var i;let t=new URL(`${U}/workspaces/${s.workspaceSlug}/pullrequests/${s.userId}`);if(t.searchParams.set("fields","+values.participants,+values.destination.repository.links.clone.*,+values.source.repository.links.clone.*"),t.searchParams.set("page",((i=s.page)==null?void 0:i.toString())||"1"),t.searchParams.set("pagelen","50"),s.repos&&s.repos.length>0){let a=`state = "open" AND (${s.repos.map(u=>`source.repository.full_name = "${u.namespace}/${u.name}"`).join(" OR ")})`;t.searchParams.set("q",a)}let n=await this.config.request({url:t.toString(),headers:L(this.config,e)}),o=!!n.body.next;return{pageInfo:{hasNextPage:o,nextPage:o?n.body.page+1:null},data:n.body.values.map(Be)}}async getPullRequestsForRepoBase(s,e={}){var i;let t=new URL(`${U}/repositories/${encodeURI(s.repo.namespace)}/${encodeURI(s.repo.name)}/pullrequests?state=OPEN`),n=[];s.reviewerId&&n.push(`reviewers.uuid="${s.reviewerId}"`),s.authorLogin&&n.push(`author.uuid="${s.authorLogin}"`);let o='state="OPEN"';return n.length&&(o+=` AND (${n.join(s.useOrFilter?" OR ":" AND ")})`),t.searchParams.set("fields","+values.participants,+values.destination.repository.links.clone.*,+values.source.repository.links.clone.*"),t.searchParams.set("page",((i=s.page)==null?void 0:i.toString())||"1"),t.searchParams.set("pagelen","50"),t.searchParams.set("q",o),await this.config.request({url:t.toString(),headers:L(this.config,e)})}async getPullRequestsForRepo(s,e={}){let t=[],n=await this.getPullRequestsForRepoBase(s,e);n.body.values.forEach(i=>{t.push(Be(i))});let o=!!n.body.next;return{pageInfo:{hasNextPage:o,nextPage:o?n.body.page+1:null},data:t}}async getPullRequestsForRepos(s,e={}){let t=[];return await Promise.all(s.repos.map(async n=>{try{(await this.getPullRequestsForRepoBase({repo:n,...s},e)).body.values.forEach(i=>{t.push(Be(i))})}catch(o){if(o.statusCode!==404&&o.statusCode!==401)throw o}})),{data:t}}async getAccountsForWorkspace(s,e={}){var i;let t=new URL(`${U}/workspaces/${encodeURI(s.workspace)}/members`);t.searchParams.set("page",((i=s.page)==null?void 0:i.toString())||"1"),t.searchParams.set("pagelen","100");let n=await this.config.request({url:t.toString(),headers:L(this.config,e)}),o=!!n.body.next;return{pageInfo:{hasNextPage:o,nextPage:o?n.body.page+1:null},data:n.body.values.map(a=>me(a.user))}}async getReposPermissionsForCurrentUser(s,e={}){var i;let t=new URL(`${U}/user/permissions/repositories`);t.searchParams.set("page",((i=s.page)==null?void 0:i.toString())||"1"),t.searchParams.set("pagelen","100");let n=await this.config.request({url:t.toString(),headers:L(this.config,e)}),o=!!n.body.next;return{pageInfo:{hasNextPage:o,nextPage:o?n.body.page+1:null},data:n.body.values.reduce((a,u)=>({...a,[u.repository.uuid]:cr(u.permission)}),{})}}async decorateReposWithPermissions(s,e={}){let t={},n=1;do{let o=await this.getReposPermissionsForCurrentUser({page:n},e);t={...o.data,...t},n=o.pageInfo.hasNextPage?o.pageInfo.nextPage:null}while(n!==null);return{data:s.repos.map(o=>({...o,permissions:t[o.id]??{canCreateWebhook:!1,canPush:!1,isAdmin:!1}}))}}async closePullRequest(s,e={}){let{pullRequest:t}=s;if(!(await this.config.request({method:"POST",url:`${U}/repositories/${t.repository.owner.login}/${t.repository.name}/pullrequests/${t.id}/decline`,headers:L(this.config,e)})).body.title)throw new Error("Could not close pull request")}async mergePullRequest(s,e={}){let{pullRequest:t,mergeStrategy:n}=s,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:`${U}/repositories/${t.repository.owner.login}/${t.repository.name}/pullrequests/${t.id}/merge`,body:JSON.stringify(i),headers:{...L(this.config,e),"Content-Type":"application/json"}})).body.title)throw new Error("Could not merge pull request")}async setPullRequestReviewers(s,e={}){let{pullRequest:t,reviewers:n}=s,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:`${U}/repositories/${t.repository.owner.login}/${t.repository.name}/pullrequests/${t.id}`,body:JSON.stringify(o),headers:{...L(this.config,e),"Content-Type":"application/json"}})).body.title)throw new Error("Could not set pull request reviewers")}};var qt=r=>r?r.find(s=>s.permission==="USER_ADMIN"||s.permission==="PROJECT_ADMIN"||s.permission==="ADMIN"||s.permission==="SYS_ADMIN"||s.permission==="REPO_ADMIN")?{canCreateWebhook:!0,canPush:!0,isAdmin:!0}:r.find(s=>s.permission==="REPO_WRITE"||s.permission==="REPO_CREATE"||s.permission==="PROJECT_CREATE"||s.permission==="PROJECT_WRITE")?{canCreateWebhook:!1,canPush:!0,isAdmin:!1}:{canCreateWebhook:!1,canPush:!1,isAdmin:!1}:{canCreateWebhook:!1,canPush:!1,isAdmin:!1};var je=r=>({name:r.displayName,email:r.emailAddress,avatarUrl:r.avatarUrl??null,id:r.id.toString(),username:r.name,url:r.links.self[0].href}),he=r=>{var u,l,p,d,c,g;let s={OPEN:"OPEN",MERGED:"MERGED",DECLINED:"CLOSED"},e={UNAPPROVED:"REVIEW_REQUESTED",NEEDS_WORK:"CHANGES_REQUESTED",APPROVED:"APPROVED"},t=r.reviewers.map(m=>({reviewer:je(m.user),state:e[m.status]})),n=((u=r.toRef.repository.links.clone.find(m=>m.name==="ssh"))==null?void 0:u.href)??null,o=((l=r.toRef.repository.links.clone.find(m=>m.name==="https"))==null?void 0:l.href)??null;o||(o=((p=r.toRef.repository.links.clone.find(m=>m.name==="http"))==null?void 0:p.href)??null);let i=((d=r.fromRef.repository.links.clone.find(m=>m.name==="ssh"))==null?void 0:d.href)??null,a=((c=r.fromRef.repository.links.clone.find(m=>m.name==="https"))==null?void 0:c.href)??null;return a||(a=((g=r.fromRef.repository.links.clone.find(m=>m.name==="http"))==null?void 0:g.href)??null),{id:r.id.toString(),number:r.id,title:r.title,url:r.links.self[0].href,state:s[r.state],isDraft:!1,createdDate:new Date(r.createdDate),updatedDate:new Date(r.updatedDate),closedDate:r.closedDate?new Date(r.closedDate):null,mergedDate:r.state=="MERGED"&&r.closedDate?new Date(r.closedDate):null,baseRef:{name:r.toRef.displayId,oid:r.toRef.latestCommit},headRef:{name:r.fromRef.displayId,oid:r.fromRef.latestCommit},commentCount:r.properties.commentCount,upvoteCount:null,commitCount:null,fileCount:null,additions:null,deletions:null,author:je(r.author.user),assignees:null,reviews:t,reviewDecision:x(t),repository:{id:r.toRef.repository.id.toString(),name:r.toRef.repository.name,owner:{login:r.toRef.repository.project.key},remoteInfo:o&&n?{cloneUrlHTTPS:o,cloneUrlSSH:n}:null},headRepository:{id:r.fromRef.repository.id.toString(),name:r.fromRef.repository.name,owner:{login:r.fromRef.repository.project.key},remoteInfo:a&&i?{cloneUrlHTTPS:a,cloneUrlSSH:i}:null},headCommit:null,mergeableState:"MERGEABLE",permissions:null,version:r.version}},Ct=r=>{var s,e,t;return{id:r.id.toString(),namespace:r.project.key,name:r.slug,webUrl:((s=r.links.self[0])==null?void 0:s.href)??null,httpsUrl:((e=r.links.clone.find(n=>n.name==="https"||n.name==="http"))==null?void 0:e.href)??null,sshUrl:((t=r.links.clone.find(n=>n.name==="ssh"))==null?void 0:t.href)??null,defaultBranch:null,permissions:null}},Z=class extends A{getBaseUrl(s){let e=s.baseUrl||this.config.baseUrl;if(!e)throw new Error('Bitbucket Server requires "baseUrl"');return e}getRequestHeaders(s){return I(s.token||this.config.token)}async getCurrentUser(s={},e={}){let t=await this.config.request({url:`${this.getBaseUrl(e)}/users?limit=2`,headers:this.getRequestHeaders(e)}),{headers:{"x-auserid":n,"x-ausername":o}}=t,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:p,id:d,name:c,slug:g})=>i?i===d:a===c||a===p||a===g);if(!l)throw new Error("Could not find current Bitbucket Server user");return{data:je(l)}}async getRepo(s,e={}){let t=await this.config.request({url:`${this.getBaseUrl(e)}/projects/${s.namespace}/repos/${s.name}`,headers:this.getRequestHeaders(e)});return{data:Ct(t.body)}}async getRepos(s,e={}){let t=[],n=[];return await Promise.all(s.map(async o=>{try{let i=await this.getRepo(o,e);t.push(i.data)}catch(i){n.push({input:o,error:i})}})),{data:t,errors:n}}async getReposForCurrentUser(s,e={}){let t=s.page??0,n=await this.config.request({url:`${this.getBaseUrl(e)}/repos?start=${t}`,headers:this.getRequestHeaders(e)});return{pageInfo:{hasNextPage:!n.body.isLastPage,nextPage:n.body.nextPageStart},data:n.body.values.map(Ct)}}async getRepoPermissionsForUsername(s,e={}){var n;let t=new URL(`${this.getBaseUrl(e)}/projects/${s.repo.namespace}/repos/${s.repo.name}/permissions/search?filterText=${s.username}`);try{let o=await this.config.request({url:t.toString(),headers:this.getRequestHeaders(e)});return{data:qt(o.body.values)}}catch(o){if(((n=o.response)==null?void 0:n.status)===401)return{data:{canCreateWebhook:!1,canPush:!1,isAdmin:!1}};throw o}}async decorateReposWithPermissions(s,e={}){return await Promise.all(s.repos.map(async n=>{let o=await this.getRepoPermissionsForUsername({repo:n,username:s.username},e);return{...n,permissions:o.data}}))}async getPullRequestsForRepoBase(s,e={}){var n;let t=new URL(`${this.getBaseUrl(e)}/projects/${encodeURI(s.repo.namespace)}/repos/${encodeURI(s.repo.name)}/pull-requests?state=OPEN`);return t.searchParams.set("start",((n=s.page)==null?void 0:n.toString())||"0"),t.searchParams.set("limit","50"),await this.config.request({url:t.toString(),headers:this.getRequestHeaders(e)})}async getPullRequestsForRepo(s,e={}){let t=[],n=await this.getPullRequestsForRepoBase(s,e);n.body.values.forEach(i=>{if(s.authorLogin&&i.author.user.name!==s.authorLogin)return null;t.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:t}}async getPullRequestsForRepos(s,e={}){let t=[];return await Promise.all(s.repos.map(async n=>{try{(await this.getPullRequestsForRepoBase({repo:n,...s},e)).body.values.forEach(i=>{if(s.authorLogin&&i.author.user.name!==s.authorLogin)return null;t.push(he(i))})}catch(o){if(o.statusCode!==404&&o.statusCode!==401)throw o}})),{data:t}}async getPullRequestsForCurrentUser(s,e={}){var i;let t=new URL(`${this.getBaseUrl(e)}/dashboard/pull-requests`);t.searchParams.set("state","OPEN"),t.searchParams.set("start",((i=s.page)==null?void 0:i.toString())||"0"),t.searchParams.set("limit","50");let n=await this.config.request({url:t.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(s,e={}){let{pullRequest:t}=s;if(t.version===void 0)throw new Error('Bitbucket Server requires "version" for this function.');if(!(await this.config.request({method:"POST",url:`${this.getBaseUrl(e)}/projects/${t.repository.owner.login}/repos/${t.repository.name}/pull-requests/${t.id}/decline`,body:JSON.stringify({version:t.version}),headers:{...this.getRequestHeaders(e),"Content-Type":"application/json"}})).body.title)throw new Error("Could not close pull request")}async mergePullRequest(s,e={}){let{pullRequest:t,mergeStrategyId:n}=s;if(s.mergeStrategy)throw new Error('Bitbucket Server uses "mergeStrategyId" instead of "mergeStrategy".');if(t.version===void 0)throw new Error('Bitbucket Server requires "version" for this function.');if(!(await this.config.request({method:"POST",url:`${this.getBaseUrl(e)}/projects/${t.repository.owner.login}/repos/${t.repository.name}/pull-requests/${t.id}/merge`,body:JSON.stringify({strategyId:n,version:t.version}),headers:{...this.getRequestHeaders(e),"Content-Type":"application/json"}})).body.title)throw new Error("Could not merge pull request")}async getMergeStrategies(s={}){let e=await this.config.request({url:`${this.getBaseUrl(s)}/admin/pull-requests/git`,headers:{...this.getRequestHeaders(s),"Content-Type":"application/json"}});return{data:{defaultStrategy:e.body.mergeConfig.defaultStrategy,strategies:e.body.mergeConfig.strategies}}}async setPullRequestReviewers(s,e={}){let{pullRequest:t,reviewers:n}=s;if(t.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:t.version};if(!(await this.config.request({method:"PUT",url:`${this.getBaseUrl(e)}/projects/${t.repository.owner.login}/repos/${t.repository.name}/pull-requests/${t.id}`,body:JSON.stringify(o),headers:{...this.getRequestHeaders(e),"Content-Type":"application/json"}})).body.title)throw new Error("Could not set pull request reviewers")}};var Tt=require("js-base64");var fe=(e=>(e.Open="OPEN",e.Closed="CLOSED",e))(fe||{});var b=class extends Error{constructor(e,t){let n=t==null?void 0:t.map(i=>`'${i.message}'`).join(", "),o=n?`${e}: ${n}`:e;super(o);this.graphQLErrors=t??[]}};var gr={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]},Dt=15,Lt=100,$=r=>!!r,F=(r,s)=>{let e=gr[s];for(let t=0;t<3;t++){if(r[t]>e[t])return!0;if(r[t]<e[t])return!1}return!0},Ie="https://api.github.com",mr=`${Ie}/graphql`,be=`
1
+ "use strict";var Vt=Object.create;var le=Object.defineProperty;var Kt=Object.getOwnPropertyDescriptor;var Xt=Object.getOwnPropertyNames;var Zt=Object.getPrototypeOf,Yt=Object.prototype.hasOwnProperty;var er=(r,s)=>{for(var e in s)le(r,e,{get:s[e],enumerable:!0})},ht=(r,s,e,t)=>{if(s&&typeof s=="object"||typeof s=="function")for(let n of Xt(s))!Yt.call(r,n)&&n!==e&&le(r,n,{get:()=>s[n],enumerable:!(t=Kt(s,n))||t.enumerable});return r};var tr=(r,s,e)=>(e=r!=null?Vt(Zt(r)):{},ht(s||!r||!r.__esModule?le(e,"default",{value:r,enumerable:!0}):e,r)),rr=r=>ht(le({},"__esModule",{value:!0}),r);var hs={};er(hs,{AzureDevOps:()=>K,Bitbucket:()=>X,BitbucketServer:()=>Z,EntityIdentifierProviderType:()=>Ht,EntityType:()=>Wt,EntityVersion:()=>zt,GitBuildStatusStage:()=>ft,GitBuildStatusState:()=>pe,GitDiffLineType:()=>Ne,GitHub:()=>ee,GitHubIssueCloseReason:()=>Jt,GitIssueState:()=>Re,GitLab:()=>re,GitMergeStrategy:()=>V,GitPullRequestMergeableState:()=>J,GitPullRequestReviewState:()=>j,GitPullRequestState:()=>H,GraphQLErrors:()=>b,Jira:()=>se,JiraServer:()=>ne,PullRequestAsyncStatus:()=>Mt,Trello:()=>oe,default:()=>ms,isFetch:()=>de});module.exports=rr(hs);var ft=(n=>(n.Build="build",n.Production="production",n.Staging="staging",n.Test="test",n))(ft||{}),pe=(p=>(p.ActionRequired="ACTION_REQUIRED",p.Cancelled="CANCELLED",p.Error="ERROR",p.Failed="FAILED",p.Pending="PENDING",p.Running="RUNNING",p.Skipped="SKIPPED",p.Success="SUCCESS",p.Warning="WARNING",p.OptionalActionRequired="OPTIONAL_ACTION_REQUIRED",p))(pe||{}),V=(o=>(o.MergeCommit="MERGE_COMMIT",o.Rebase="REBASE",o.RebaseThenMergeCommit="REBASE_THEN_MERGE_COMMIT",o.FastForward="FAST_FORWARD",o.Squash="SQUASH",o))(V||{}),H=(t=>(t.Open="OPEN",t.Closed="CLOSED",t.Merged="MERGED",t))(H||{}),j=(n=>(n.Approved="APPROVED",n.ChangesRequested="CHANGES_REQUESTED",n.Commented="COMMENTED",n.ReviewRequested="REVIEW_REQUESTED",n))(j||{}),J=(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))(J||{}),Ne=(t=>(t.ADDED="ADDED",t.DELETED="DELETED",t.UNMODIFIED="UNMODIFIED",t))(Ne||{});var Rt={APPROVED:0,COMMENTED:1,REVIEW_REQUESTED:2,CHANGES_REQUESTED:3},x=r=>!r||r.length===0?null:r.reduce((s,e)=>Rt[e.state]>Rt[s]?e.state:s,"APPROVED");var C=100;var It=tr(require("node-fetch")),bt=globalThis.fetch||It.default;var sr=async r=>{let s=r.headers.get("content-type")||"",e=null;if(s.startsWith("application/json")){let n=await r.text();e=n.trim().length>0?JSON.parse(n):null}else if(s.startsWith("text/")||s==="")e=await r.text();else if(s.startsWith("application/vnd.github.raw+json"))e=await r.arrayBuffer();else throw new Error(`Unsupported content-type: ${s}`);let t={body:e,headers:Object.fromEntries(r.headers.entries()),status:r.status,statusText:r.statusText};if(!r.ok){let n=new Error(r.statusText);throw Object.assign(n,{response:t}),n}return t},Fe=r=>async({url:s,...e})=>{let t=await r(s,e);return sr(t)};var de=(r,s=!1)=>r.name==="fetch"||s;var N=class{constructor(s){let e=(s==null?void 0:s.request)||bt;this.config={...s,request:de(e,s==null?void 0:s.forceIsFetch)?Fe(e):e}}updateConfig(s){this.config={...this.config,...s,request:s.request&&de(s.request,(s==null?void 0:s.forceIsFetch)??this.config.forceIsFetch)?Fe(s.request):this.config.request}}},A=class extends N{};var I=(r,s)=>{let e={};return r&&(e.Authorization=`${s?"Basic":"Bearer"} ${r}`),e},yt=r=>r?r.reduce((s,e)=>(s[e]=!0,s),{}):void 0,M=(r,s,e)=>!r||s.some(t=>r[t])?e:"",Pt=async r=>{var n,o,i;let s=[],e=!0,t;for(;e;){let a=await r(t);s=s.concat(a.data),e=!!((n=a==null?void 0:a.pageInfo)!=null&&n.hasNextPage),t=((o=a==null?void 0:a.pageInfo)==null?void 0:o.endCursor)||((i=a==null?void 0:a.pageInfo)==null?void 0:i.nextPage)}return s};var nr="https://app.vssps.visualstudio.com/_apis",or="https://vssps.dev.azure.com/",ir="https://dev.azure.com",S=(r,s={})=>I(s.token||r.token,s.isPAT||r.isPAT),wt=r=>r.url.replace("/_apis/git/repositories/","/_git/").replace(`/${r.repository.project.id}/`,`/${encodeURIComponent(r.repository.project.name)}/`).replace(`/${r.repository.id}/`,`/${encodeURIComponent(r.repository.name)}/`).replace("/pullRequests/","/pullrequest/"),_e=(r,s)=>{let e=s.baseUrl||r.baseUrl||nr;return e=e.replace(/\/$/,""),e},v=(r,s)=>{let e=s.baseUrl||r.baseUrl||ir;return e=e.replace(/\/$/,""),e},Qe=(r,s)=>{let e=s.baseUrl||r.baseUrl||or;return e=e.replace(/\/$/,""),e};var ar={active:"OPEN",completed:"MERGED",abandoned:"CLOSED"},ur={10:"APPROVED",5:"APPROVED",0:"REVIEW_REQUESTED",[-5]:"CHANGES_REQUESTED",[-10]:"CHANGES_REQUESTED"},Be=r=>({id:r.id,name:r.displayName??null,username:(r.uniqueName||r.displayName)??null,email:null,avatarUrl:r.imageUrl??null,url:null}),ge=r=>r.startsWith("refs/heads/")?r.replace("refs/heads/",""):r,lr=r=>{switch(r){case"conflicts":return"CONFLICTS";case"failure":return"FAILING_CHECKS";case"rejectedByPolicy":return"BLOCKED";case"succeeded":return"MERGEABLE";case"notSet":case"queued":default:return"UNKNOWN"}},ce=(r,s)=>{var n;let e=[],t=[];return s.reviewers.forEach(o=>{let i={reviewer:Be(o),state:ur[o.vote??0]||"REVIEW_REQUESTED"};o.isRequired&&e.push(i),t.push(i)}),{id:s.pullRequestId.toString(),title:s.title,number:s.codeReviewId,state:ar[s.status],isDraft:s.isDraft,commentCount:null,upvoteCount:null,author:Be(s.createdBy),createdDate:new Date(s.creationDate),updatedDate:new Date(s.closedDate||s.creationDate),closedDate:s.closedDate?new Date(s.closedDate):null,mergedDate:s.closedDate&&s.status==="completed"?new Date(s.closedDate):null,repository:{id:s.repository.id,name:s.repository.name,project:s.repository.project.name,owner:{login:r},remoteInfo:null},headCommit:{buildStatuses:null},baseRef:{name:ge(s.targetRefName),oid:s.lastMergeTargetCommit.commitId},headRef:{name:ge(s.sourceRefName),oid:s.lastMergeSourceCommit.commitId},url:wt(s),assignees:s.reviewers.map(Be),reviews:t,reviewDecision:x(e),additions:null,deletions:null,fileCount:null,commitCount:null,headRepository:s.forkSource?{id:s.forkSource.repository.id,name:s.forkSource.repository.name,project:void 0,owner:{login:r},remoteInfo:null}:{id:s.repository.id,name:s.repository.name,project:s.repository.project.name,owner:{login:r},remoteInfo:null},mergeableState:lr(s.mergeStatus),labels:((n=s.labels)==null?void 0:n.map(o=>({color:null,description:null,id:o.id,name:o.name})))??[],permissions:null}},St=(r,s)=>({id:s.id,name:s.name,namespace:r,project:s.project.name,projectId:s.project.id,webUrl:s.webUrl,httpsUrl:s.remoteUrl,sshUrl:s.sshUrl,defaultBranch:s.defaultBranch?{name:ge(s.defaultBranch)}:null,permissions:null}),pr=(r,s,e,t)=>{var l,p,d,c,g,m;let n=e.fields,o=n["System.AssignedTo"],i=n["System.State"],a=n["System.WorkItemType"],u;return i&&a&&(u=(l=t[a])==null?void 0:l[i]),{id:e.id.toString(),number:e.id.toString(),title:n["System.Title"],commentCount:n["System.CommentCount"],author:{avatarUrl:((d=(p=n["System.CreatedBy"]._links)==null?void 0:p.avatar)==null?void 0:d.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:((g=(c=o._links)==null?void 0:c.avatar)==null?void 0:g.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==null?void 0:u.title)||i,color:null},type:n["System.WorkItemType"],repository:null,project:{namespace:r,name:s,resourceId:null,key:null,id:null},upvoteCount:0,labels:((m=e.fields["System.Tags"])==null?void 0:m.split(";").map(R=>({color:null,description:null,id:null,name:R.trim()})))??[]}},K=class extends A{async getCurrentUser(s={},e={}){if(e.isPAT||this.config.isPAT)throw new Error("Azure DevOps does not support PATs for this function.");let t=`${_e(this.config,e)}/profile/profiles/me`,n=await this.config.request({url:t,headers:S(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(s,e={}){let n=(await this.config.request({url:`${v(this.config,e)}/${encodeURIComponent(s.namespace)}/_apis/ConnectionData`,headers:S(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(s,e={}){if(!s.repo.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let n=(await this.config.request({url:`${v(this.config,e)}/${encodeURIComponent(s.repo.namespace)}/${encodeURIComponent(s.repo.project)}/_apis/git/repositories/${encodeURIComponent(s.repo.name)}/commits/${s.oid}`,headers:S(this.config,e)})).body.author;return{data:{name:n.name,email:n.email,avatarUrl:n.imageUrl}}}async getOrgsForUser(s,e={}){let t=`${_e(this.config,e)}/accounts?memberId=${s.userId}&api-version=6.0`;return{data:(await this.config.request({url:t,headers:S(this.config,e)})).body.value.map(o=>({id:o.accountId,name:o.accountName}))}}async getCollectionsForUser(s,e={}){let t=`${v(this.config,e)}/_apis/projectCollections`;return{data:(await this.config.request({url:t,headers:S(this.config,e)})).body.value.map(o=>({id:o.id,name:o.name}))}}async getAzureProjects(s,e={}){let t=new URL(`${v(this.config,e)}/${encodeURIComponent(s.namespace)}/_apis/projects`);t.searchParams.set("$top",C.toString()),s.cursor&&t.searchParams.set("$skip",s.cursor);let n=await this.config.request({url:t.toString(),headers:S(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:s.namespace}))}}async getAzureProjectScopeDescriptor(s,e={}){let{namespace:t,projectId:n}=s;return{data:{scope:(await this.config.request({url:`${Qe(this.config,e)}/${encodeURIComponent(t)}/_apis/graph/descriptors/${n}?api-version=6.0`,headers:S(this.config,e)})).body.value}}}async getAzureGraphAccountsForAzureProject(s,e={}){let{namespace:t,projectScopeDescriptor:n,cursor:o}=s,i=new URL(`${Qe(this.config,e)}/${encodeURIComponent(t)}/_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:S(this.config,e)}),u=a.headers["x-ms-continuationtoken"];return{pageInfo:{endCursor:u||null,hasNextPage:!!u},data:a.body.value.map(l=>{var p,d,c,g;return{avatarUrl:((d=(p=l._links)==null?void 0:p.avatar)==null?void 0:d.href)??null,descriptor:l.descriptor??null,email:l.mailAddress??null,name:l.displayName??null,storageKeyURL:((g=(c=l._links)==null?void 0:c.storageKey)==null?void 0:g.href)??null,username:l.displayName??null}})}}async getAccountFromAzureGraphAccount(s,e={}){let{azureGraphAccount:t}=s;if(!t.storageKeyURL)throw new Error("Expected 'storageKeyURL' to not be null for 'azureGraphAccount'");let n=await this.config.request({url:t.storageKeyURL,headers:S(this.config,e)});return{data:{avatarUrl:t.avatarUrl,email:t.email,id:n.body.value,name:t.name,username:t.username,url:null}}}async getAccountsFromAzureGraphAccounts(s,e={}){let t=[];for(let n of s.azureGraphAccounts){let o=await this.getAccountFromAzureGraphAccount({azureGraphAccount:n},e);t.push(o.data)}return{data:t}}async getRepo(s,e={}){if(!s.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let t=await this.config.request({url:`${v(this.config,e)}/${encodeURIComponent(s.namespace)}/${encodeURIComponent(s.project)}/_apis/git/repositories/${encodeURIComponent(s.name)}`,headers:S(this.config,e)});return{data:St(s.namespace,t.body)}}async getRepos(s,e={}){let t=[],n=[];return await Promise.all(s.map(async o=>{try{let i=await this.getRepo(o,e);t.push(i.data)}catch(i){n.push({input:o,error:i})}})),{data:t,errors:n}}async getReposForAzureProject(s,e={}){if(!s.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');return{data:(await this.config.request({url:`${v(this.config,e)}/${encodeURIComponent(s.namespace)}/${encodeURIComponent(s.project)}/_apis/git/repositories`,headers:S(this.config,e)})).body.value.map(n=>St(s.namespace,n))}}async getRefs(s,e,t={}){if(!e.repo.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let n=new URL(`${v(this.config,t)}/${encodeURIComponent(e.repo.namespace)}/${encodeURIComponent(e.repo.project)}/_apis/git/repositories/${encodeURIComponent(e.repo.name)}/refs`);n.searchParams.set("filter",s),n.searchParams.set("$top",C.toString()),e.cursor&&n.searchParams.set("continuationToken",e.cursor);let o=await this.config.request({url:n.toString(),headers:S(this.config,t)}),i=o.headers["x-ms-continuationtoken"];return{pageInfo:{hasNextPage:!!i,endCursor:i||null},data:o.body.value.map(a=>({name:ge(a.name),commit:{oid:a.objectId,authoredDate:null,committedDate:null}}))}}async getBranches(s,e={}){return this.getRefs("heads",s,e)}async getTags(s,e={}){return this.getRefs("tags",s,e)}async getPullRequestsForRepoBase(s,e={},t=100){let{page:n,repo:o,assigneeLogins:i,authorLogin:a}=s||{},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:`${v(this.config,e)}/${encodeURIComponent(o.namespace)}/${encodeURIComponent(o.project||"")}/_apis/git/repositories/${encodeURIComponent(o.name)}/pullRequests?${l}&%24top=${t}&%24skip=${(u-1)*t}`,headers:S(this.config,e)})}async getPullRequestsForRepo(s,e={}){let n=s.page||1,o=await this.getPullRequestsForRepoBase(s,e,100);return{pageInfo:{hasNextPage:o.body.value.length===100,nextPage:n+1},data:o.body.value.map(i=>ce(s.repo.namespace,i))}}async getPullRequestsForRepos(s,e={}){if(!s.repos.every(o=>o.project))throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let{repos:t}=s||{},n=[];return await Promise.all(t.map(async o=>{try{(await this.getPullRequestsForRepoBase({repo:o,...s},e)).body.value.forEach(a=>{n.push(ce(o.namespace,a))})}catch(i){if(i.statusCode!==404&&i.statusCode!==401)throw i}})),{data:n}}async getPullRequestsForProjectBase(s,e={},t=100){let{namespace:n,project:o,page:i,assigneeLogins:a,authorLogin:u,repo:l}=s;if(l!=null&&l.project&&l.project!==o)throw new Error("Could not fetch pull requests, project mismatch");let p=i||1,d=new URL(`${v(this.config,e)}/${encodeURIComponent(n)}/${encodeURIComponent(o)}/_apis/git/pullRequests`);return d.searchParams.set("searchCriteria.status","1"),d.searchParams.set("$top",t.toString()),d.searchParams.set("$skip",((p-1)*t).toString()),l!=null&&l.id&&(l==null?void 0:l.project)===o&&d.searchParams.set("searchCriteria.repositoryId",l.id),a&&a.length&&d.searchParams.set("searchCriteria.reviewerId",a[0]),u&&d.searchParams.set("searchCriteria.creatorId",u),await this.config.request({url:d.toString(),headers:S(this.config,e)})}async getPullRequestsForProject(s,e={}){let n=s.page||1,o=await this.getPullRequestsForProjectBase(s,e,100);return{pageInfo:{hasNextPage:(o==null?void 0:o.body.value.length)===100,nextPage:n+1},data:(o==null?void 0:o.body.value.map(i=>ce(s.namespace,i)))||[]}}async getPullRequestsForProjects(s,e={}){let{projects:t}=s||{},n=[];return await Promise.all(t.map(async o=>{try{if(!s.repo||s.repo.project&&s.repo.project===o.project){let i=await this.getPullRequestsForProjectBase({...o,...s},e);i==null||i.body.value.forEach(a=>{n.push(ce(o.namespace,a))})}}catch(i){if(i.statusCode!==404&&i.statusCode!==401)throw i}})),{data:n}}async getAzurePullRequestLastMergeStatus(s,e={}){if(!s.repo.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let{repo:{namespace:t,project:n,name:o},pullRequestId:i}=s,a=await this.config.request({url:`${v(this.config,e)}/${encodeURIComponent(t)}/${encodeURIComponent(n||"")}/_apis/git/repositories/${o}/pullrequests/${i}?includeCommits=true?api-version=6.0`,headers:{...S(this.config,e)}});if(!a.body.mergeStatus)throw new Error("Could not fetch pull request");return{data:a.body.mergeStatus}}async updatePullRequest(s,e,t){return await this.config.request({method:"PATCH",url:`${v(this.config,t)}/${encodeURIComponent(s.repository.owner.login)}/${encodeURIComponent(s.repository.project)}/_apis/git/repositories/${s.repository.name}/pullrequests/${s.id}?api-version=6.0`,body:e,headers:{...S(this.config,t),"Content-Type":"application/json"}})}async closePullRequest(s,e={}){let{pullRequest:t}=s,n={status:"abandoned"};if(!(await this.updatePullRequest(t,JSON.stringify(n),e)).body.status)throw new Error("Could not close pull request")}async mergePullRequest(s,e={}){var u;let{pullRequest:t,mergeStrategy:n}=s,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:(u=t.headRef)==null?void 0:u.oid},status:"completed"};if(!(await this.updatePullRequest(t,JSON.stringify(i),e)).body.status)throw new Error("Could not merge pull request")}async addPullRequestLabel(s,e={}){let{pullRequest:t,label:n}=s;if(!t.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:`${v(this.config,e)}/${encodeURIComponent(t.repository.owner.login)}/${encodeURIComponent(t.repository.project)}/_apis/git/repositories/${t.repository.name}/pullrequests/${t.id}/labels?api-version=6.0`,body:JSON.stringify(o),headers:{...S(this.config,e),"Content-Type":"application/json"}})).body.id)throw new Error("Could not add pull request label")}async removePullRequestLabel(s,e={}){let{pullRequest:t,label:n}=s;if(!t.repository.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');await this.config.request({method:"DELETE",url:`${v(this.config,e)}/${encodeURIComponent(t.repository.owner.login)}/${encodeURIComponent(t.repository.project)}/_apis/git/repositories/${t.repository.name}/pullrequests/${t.id}/labels/${encodeURIComponent(n.name)}?api-version=6.0`,headers:{...S(this.config,e)}})}async setPullRequestLabels(s,e={}){let{pullRequest:t,labels:n}=s;if(!t.repository.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let o=t.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:t,label:i},e);for(let i of o)n.find(a=>i.id===a.id)||await this.removePullRequestLabel({pullRequest:t,label:i},e)}async setPullRequestAsDraft(s,e={}){let{pullRequest:t,isDraft:n}=s,o={isDraft:n};if(!(await this.updatePullRequest(t,JSON.stringify(o),e)).body.status)throw new Error("Could not set the pull request as draft")}async addPullRequestReviewer(s,e={}){let{pullRequest:t,reviewer:n,isRequired:o}=s,i={id:n.id,isRequired:o};if(!(await this.config.request({method:"PUT",url:`${v(this.config,e)}/${encodeURIComponent(t.repository.owner.login)}/${encodeURIComponent(t.repository.project)}/_apis/git/repositories/${t.repository.name}/pullrequests/${t.id}/reviewers/${n.id}?api-version=6.0`,body:JSON.stringify(i),headers:{...S(this.config,e),"Content-Type":"application/json"}})).body.id)throw new Error("Could not add pull request reviewer")}async removePullRequestReviewer(s,e={}){let{pullRequest:t,reviewer:n}=s;await this.config.request({method:"DELETE",url:`${v(this.config,e)}/${encodeURIComponent(t.repository.owner.login)}/${encodeURIComponent(t.repository.project)}/_apis/git/repositories/${t.repository.name}/pullrequests/${t.id}/reviewers/${n.id}?api-version=6.0`,headers:{...S(this.config,e),Accept:"application/json"}})}async setPullRequestReviewers(s,e={}){let{pullRequest:t,reviewers:n}=s;for(let o of n)t.assignees.find(i=>i.id===o.id)||await this.addPullRequestReviewer({pullRequest:t,reviewer:o,isRequired:!0},e);for(let o of t.assignees)n.find(i=>o.id===i.id)||await this.removePullRequestReviewer({pullRequest:t,reviewer:o},e)}async getIssuesForAzureProject(s,e={}){let{page:t,assigneeLogins:n,authorLogin:o,mentionLogin:i,labelNames:a,statusByWorkItemIdByStatusId:u}=s||{},l=t||1,p=200,d=["[Microsoft.VSTS.Common.ClosedDate] = ''","[System.TeamProject] = @project","[Microsoft.VSTS.Common.ResolvedDate] = ''"];o&&d.push(`[System.CreatedBy] = '${o.replace("'","''")}'`),n&&n[0]&&d.push(`[System.AssignedTo] = '${n[0].replace("'","''")}'`),i&&d.push("[System.Id] IN (@recentMentions)"),a&&a.forEach(h=>d.push(`[System.Tags] Contains '${h}'`));let c=`Select [Microsoft.VSTS.Common.ClosedDate], [Microsoft.VSTS.Common.ResolvedDate] From WorkItems Where ${d.join(" AND ")} order by [System.CreatedDate] desc`,g=await this.config.request({url:`${v(this.config,e)}/${encodeURIComponent(s.namespace)}/${encodeURIComponent(s.project)}/_apis/wit/wiql?api-version=6.0`,body:JSON.stringify({query:c}),method:"POST",headers:{...S(this.config,e),"Content-Type":"application/json"}}),m=g.body.workItems.slice((l-1)*p,p*l).map(h=>h.id);if(m.length==0)return{pageInfo:{hasNextPage:!1,nextPage:null},data:[]};let R=await this.config.request({url:`${v(this.config,e)}/${encodeURIComponent(s.namespace)}/${encodeURIComponent(s.project)}/_apis/wit/workitemsbatch?api-version=6.0`,body:JSON.stringify({ids:m,$expand:"Links"}),method:"POST",headers:{...S(this.config,e),"Content-Type":"application/json"}});return{pageInfo:{hasNextPage:g.body.workItems.length>p*l,nextPage:l+1},data:R.body.value.map(h=>pr(s.namespace,s.project,h,u||{}))}}async getPermissionsForRepos(s,e={}){let{namespace:t,repos:n}=s,o={4:["canPush","canCreateWebhook"],1024:["isAdmin"],2048:["isAdmin"],4096:["isAdmin"],8192:["isAdmin"]},i=p=>{let d="2e9eb7ed-3c0a-47d4-87c1-0ffdd275fd87",c=`repoV2/${p.projectId}/${p.id}`;return Object.keys(o).map(g=>({securityNamespaceId:d,token:c,permissions:g}))},a={alwaysAllowAdministrators:!1,evaluations:n.flatMap(i)};return{data:(await this.config.request({method:"POST",url:`${v(this.config,e)}/${encodeURIComponent(t)}/_apis/security/permissionevaluationbatch?api-version=7.0`,body:JSON.stringify(a),headers:{...S(this.config,e),"Content-Type":"application/json"}})).body.evaluations.reduce((p,d)=>{let[,c,g]=d.token.split("/"),m=`${c}/${g}`,R=o[d.permissions];for(let h of R)p[m]===void 0&&(p[m]={canCreateWebhook:!0,canPush:!0,isAdmin:!0}),d.value===!1&&(p[m][h]=!1);return p},{})}}async decorateReposWithPermissions(s,e={}){let{namespace:t,repos:n}=s,o=await this.getPermissionsForRepos({namespace:t,repos:n},e);return{data:n.map(i=>({...i,permissions:o.data[`${i.projectId}/${i.id}`]}))}}async updateIssue(s,e,t={}){return await this.config.request({method:"PATCH",url:`${v(this.config,t)}/${encodeURIComponent(s.project.namespace)}/${encodeURIComponent(s.project.name)}/_apis/wit/workitems/${s.id}?api-version=6.0`,body:JSON.stringify(e),headers:{...S(this.config,t),"Content-Type":"application/json-patch+json"}})}async setIssueStatus(s,e={}){var a;let{issue:t,status:n}=s,o=[{op:"add",path:"/fields/System.State",value:n.name}];if(!((a=(await this.updateIssue(t,o,e)).body.fields)!=null&&a["System.State"]))throw new Error("Could not set issue status")}async setIssueAssignee(s,e={}){var a;let{issue:t,assignee:n}=s,o=[{op:"add",path:"/fields/System.AssignedTo",value:(n==null?void 0:n.name)??""}];if(!((a=(await this.updateIssue(t,o,e)).body.fields)!=null&&a["System.State"]))throw new Error("Could not set issue assignee")}async setIssueLabels(s,e={}){var u;let{issue:t,labels:n}=s,i=[{op:"replace",path:"/fields/System.Tags",value:n.map(l=>l.name).join(";")}];if(!((u=(await this.updateIssue(t,i,e)).body.fields)!=null&&u["System.Tags"]))throw new Error("Could not set issue tags")}async getIssueTypesForAzureProject(s,e={}){if(!s.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let{namespace:t,project:n}=s;return{data:(await this.config.request({url:`${v(this.config,e)}/${encodeURIComponent(t)}/${encodeURIComponent(n||"")}/_apis/wit/workitemtypes?api-version=6.0`,headers:{...S(this.config,e)}})).body.value}}async getLabelsForProject(s,e={}){let{namespace:t,project:n}=s;return{data:(await this.config.request({url:`${v(this.config,e)}/${encodeURIComponent(t)}/${encodeURIComponent(n||"")}/_apis/wit/tags?api-version=6.0`,headers:{...S(this.config,e)}})).body.value.map(i=>({color:null,description:null,id:i.id,name:i.name,url:i.url}))}}};var L=(r,s={})=>I(s.token||r.token,s.isPAT||r.isPAT);var U="https://api.bitbucket.org/2.0",dr={OPEN:"OPEN",MERGED:"MERGED",DECLINED:"CLOSED"},me=r=>({id:r.uuid,name:r.display_name||r.nickname,username:r.nickname||r.display_name,email:null,avatarUrl:r.links.avatar.href,url:r.links.html.href}),vt=r=>{let s=r.links.clone,e=s==null?void 0:s.find(n=>n.name==="ssh"),t=s==null?void 0:s.find(n=>n.name==="https");return e&&t?{cloneUrlHTTPS:t.href,cloneUrlSSH:e.href}:null},Et=r=>{var s,e;return{id:r.uuid,namespace:r.workspace.slug,name:r.slug,webUrl:r.links.html.href,httpsUrl:((s=r.links.clone.find(t=>t.name==="https"))==null?void 0:s.href)??null,sshUrl:((e=r.links.clone.find(t=>t.name==="ssh"))==null?void 0:e.href)??null,defaultBranch:{name:r.mainbranch.name},permissions:null}},je=r=>{var t;let s=r.id,e=((t=r.participants)==null?void 0:t.map(n=>{let o="REVIEW_REQUESTED";return n.approved?o="APPROVED":n.state==="changes_requested"?o="CHANGES_REQUESTED":n.participated_on!==null&&(o="COMMENTED"),{reviewer:me(n.user),state:o}}))??[];return{id:s.toString(),title:r.title,number:s,state:dr[r.state],isDraft:!1,commentCount:r.comment_count,upvoteCount:null,author:me(r.author),createdDate:new Date(r.created_on),updatedDate:new Date(r.updated_on),closedDate:null,mergedDate:null,repository:{id:r.destination.repository.uuid,name:r.destination.repository.name,owner:{login:r.destination.repository.full_name.split("/")[0]},remoteInfo:vt(r.destination.repository)},headCommit:{buildStatuses:null},baseRef:{name:r.destination.branch.name,oid:r.destination.commit.hash},headRef:{name:r.source.branch.name,oid:r.source.commit.hash},url:r.links.html.href,assignees:null,reviews:e,reviewDecision:x(e),additions:null,deletions:null,fileCount:null,commitCount:null,headRepository:{id:r.source.repository.uuid,name:r.source.repository.name,owner:{login:r.source.repository.full_name.split("/")[0]},remoteInfo:vt(r.source.repository)},mergeableState:"MERGEABLE",permissions:null}},cr=r=>{switch(r){case"owner":case"admin":return{canCreateWebhook:!0,canPush:!0,isAdmin:!0};case"write":return{canCreateWebhook:!1,canPush:!0,isAdmin:!1};case"read":case"none":return{canCreateWebhook:!1,canPush:!1,isAdmin:!1}}},X=class extends N{async refreshToken(s){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 ${s.base64ClientIDColonClientSecret}`},body:`grant_type=refresh_token&refresh_token=${s.refreshToken}`})).body}}async getCurrentUser(s={},e={}){let t=await this.config.request({url:`${U}/user`,headers:L(this.config,e)});return{data:me(t.body)}}async getUserForCommit(s,e={}){var i;let n=(await this.config.request({url:`${U}/repositories/${s.repo.namespace}/${s.repo.name}/commit/${s.oid}`,headers:L(this.config,e)})).body.author,o=n.raw.match(/([^<]+)<(.+)>/);return{data:{name:o?o[1].trim():null,email:o?o[2]:null,avatarUrl:((i=n.user)==null?void 0:i.links.avatar.href)||null}}}async getRepo(s,e={}){let t=await this.config.request({url:`${U}/repositories/${s.namespace}/${s.name}`,headers:L(this.config,e)});return{data:Et(t.body)}}async getRepos(s,e={}){let t=[],n=[];return await Promise.all(s.map(async o=>{try{let i=await this.getRepo(o,e);t.push(i.data)}catch(i){n.push({input:o,error:i})}})),{data:t,errors:n}}async getReposForCurrentUser(s,e={}){let t=new URL(`${U}/repositories`);t.searchParams.set("role","member"),t.searchParams.set("pagelen",C.toString()),s.cursor&&t.searchParams.set("after",s.cursor);let n=await this.config.request({url:t.toString(),headers:L(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(s,e={}){var i;let t=new URL(`${U}/repositories/${s.repo.namespace}/${s.repo.name}/refs/branches`);t.searchParams.set("page",((i=s.page)==null?void 0:i.toString())||"1"),t.searchParams.set("pagelen",C.toString());let n=await this.config.request({url:t.toString(),headers:L(this.config,e)}),o=!!n.body.next;return{pageInfo:{hasNextPage:o,nextPage:o?n.body.page+1:null},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 getTags(s,e={}){let t=new URL(`${U}/repositories/${s.repo.namespace}/${s.repo.name}/refs/tags`);t.searchParams.set("pagelen",C.toString()),s.cursor&&t.searchParams.set("page",s.cursor);let n=await this.config.request({url:t.toString(),headers:L(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 getWorkspacesForUser(s,e={}){var i;let t=new URL(`${U}/user/permissions/workspaces`);t.searchParams.set("page",((i=s.page)==null?void 0:i.toString())||"1"),t.searchParams.set("pagelen","50");let n=await this.config.request({url:t.toString(),headers:L(this.config,e)}),o=!!n.body.next;return{pageInfo:{hasNextPage:o,nextPage:o?n.body.page+1:null},data:n.body.values.map(a=>({id:a.workspace.uuid,slug:a.workspace.slug,name:a.workspace.name}))}}async getPullRequestsForUserAndWorkspace(s,e={}){var i;let t=new URL(`${U}/workspaces/${s.workspaceSlug}/pullrequests/${s.userId}`);if(t.searchParams.set("fields","+values.participants,+values.destination.repository.links.clone.*,+values.source.repository.links.clone.*"),t.searchParams.set("page",((i=s.page)==null?void 0:i.toString())||"1"),t.searchParams.set("pagelen","50"),s.repos&&s.repos.length>0){let a=`state = "open" AND (${s.repos.map(u=>`source.repository.full_name = "${u.namespace}/${u.name}"`).join(" OR ")})`;t.searchParams.set("q",a)}let n=await this.config.request({url:t.toString(),headers:L(this.config,e)}),o=!!n.body.next;return{pageInfo:{hasNextPage:o,nextPage:o?n.body.page+1:null},data:n.body.values.map(je)}}async getPullRequestsForRepoBase(s,e={}){var i;let t=new URL(`${U}/repositories/${encodeURI(s.repo.namespace)}/${encodeURI(s.repo.name)}/pullrequests?state=OPEN`),n=[];s.reviewerId&&n.push(`reviewers.uuid="${s.reviewerId}"`),s.authorLogin&&n.push(`author.uuid="${s.authorLogin}"`);let o='state="OPEN"';return n.length&&(o+=` AND (${n.join(s.useOrFilter?" OR ":" AND ")})`),t.searchParams.set("fields","+values.participants,+values.destination.repository.links.clone.*,+values.source.repository.links.clone.*"),t.searchParams.set("page",((i=s.page)==null?void 0:i.toString())||"1"),t.searchParams.set("pagelen","50"),t.searchParams.set("q",o),await this.config.request({url:t.toString(),headers:L(this.config,e)})}async getPullRequestsForRepo(s,e={}){let t=[],n=await this.getPullRequestsForRepoBase(s,e);n.body.values.forEach(i=>{t.push(je(i))});let o=!!n.body.next;return{pageInfo:{hasNextPage:o,nextPage:o?n.body.page+1:null},data:t}}async getPullRequestsForRepos(s,e={}){let t=[];return await Promise.all(s.repos.map(async n=>{try{(await this.getPullRequestsForRepoBase({repo:n,...s},e)).body.values.forEach(i=>{t.push(je(i))})}catch(o){if(o.statusCode!==404&&o.statusCode!==401)throw o}})),{data:t}}async getAccountsForWorkspace(s,e={}){var i;let t=new URL(`${U}/workspaces/${encodeURI(s.workspace)}/members`);t.searchParams.set("page",((i=s.page)==null?void 0:i.toString())||"1"),t.searchParams.set("pagelen","100");let n=await this.config.request({url:t.toString(),headers:L(this.config,e)}),o=!!n.body.next;return{pageInfo:{hasNextPage:o,nextPage:o?n.body.page+1:null},data:n.body.values.map(a=>me(a.user))}}async getReposPermissionsForCurrentUser(s,e={}){var i;let t=new URL(`${U}/user/permissions/repositories`);t.searchParams.set("page",((i=s.page)==null?void 0:i.toString())||"1"),t.searchParams.set("pagelen","100");let n=await this.config.request({url:t.toString(),headers:L(this.config,e)}),o=!!n.body.next;return{pageInfo:{hasNextPage:o,nextPage:o?n.body.page+1:null},data:n.body.values.reduce((a,u)=>({...a,[u.repository.uuid]:cr(u.permission)}),{})}}async decorateReposWithPermissions(s,e={}){let t={},n=1;do{let o=await this.getReposPermissionsForCurrentUser({page:n},e);t={...o.data,...t},n=o.pageInfo.hasNextPage?o.pageInfo.nextPage:null}while(n!==null);return{data:s.repos.map(o=>({...o,permissions:t[o.id]??{canCreateWebhook:!1,canPush:!1,isAdmin:!1}}))}}async closePullRequest(s,e={}){let{pullRequest:t}=s;if(!(await this.config.request({method:"POST",url:`${U}/repositories/${t.repository.owner.login}/${t.repository.name}/pullrequests/${t.id}/decline`,headers:L(this.config,e)})).body.title)throw new Error("Could not close pull request")}async mergePullRequest(s,e={}){let{pullRequest:t,mergeStrategy:n}=s,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:`${U}/repositories/${t.repository.owner.login}/${t.repository.name}/pullrequests/${t.id}/merge`,body:JSON.stringify(i),headers:{...L(this.config,e),"Content-Type":"application/json"}})).body.title)throw new Error("Could not merge pull request")}async setPullRequestReviewers(s,e={}){let{pullRequest:t,reviewers:n}=s,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:`${U}/repositories/${t.repository.owner.login}/${t.repository.name}/pullrequests/${t.id}`,body:JSON.stringify(o),headers:{...L(this.config,e),"Content-Type":"application/json"}})).body.title)throw new Error("Could not set pull request reviewers")}};var qt=r=>r?r.find(s=>s.permission==="USER_ADMIN"||s.permission==="PROJECT_ADMIN"||s.permission==="ADMIN"||s.permission==="SYS_ADMIN"||s.permission==="REPO_ADMIN")?{canCreateWebhook:!0,canPush:!0,isAdmin:!0}:r.find(s=>s.permission==="REPO_WRITE"||s.permission==="REPO_CREATE"||s.permission==="PROJECT_CREATE"||s.permission==="PROJECT_WRITE")?{canCreateWebhook:!1,canPush:!0,isAdmin:!1}:{canCreateWebhook:!1,canPush:!1,isAdmin:!1}:{canCreateWebhook:!1,canPush:!1,isAdmin:!1};var fe=r=>{let s=r.links.self[0].href;return{name:r.displayName,email:r.emailAddress,avatarUrl:r.avatarUrl??(s&&`${s}/avatar.png`),id:r.id.toString(),username:r.name,url:s}},he=r=>{var u,l,p,d,c,g;let s={OPEN:"OPEN",MERGED:"MERGED",DECLINED:"CLOSED"},e={UNAPPROVED:"REVIEW_REQUESTED",NEEDS_WORK:"CHANGES_REQUESTED",APPROVED:"APPROVED"},t=r.reviewers.map(m=>({reviewer:fe(m.user),state:e[m.status]})),n=((u=r.toRef.repository.links.clone.find(m=>m.name==="ssh"))==null?void 0:u.href)??null,o=((l=r.toRef.repository.links.clone.find(m=>m.name==="https"))==null?void 0:l.href)??null;o||(o=((p=r.toRef.repository.links.clone.find(m=>m.name==="http"))==null?void 0:p.href)??null);let i=((d=r.fromRef.repository.links.clone.find(m=>m.name==="ssh"))==null?void 0:d.href)??null,a=((c=r.fromRef.repository.links.clone.find(m=>m.name==="https"))==null?void 0:c.href)??null;return a||(a=((g=r.fromRef.repository.links.clone.find(m=>m.name==="http"))==null?void 0:g.href)??null),{id:r.id.toString(),number:r.id,title:r.title,url:r.links.self[0].href,state:s[r.state],isDraft:!1,createdDate:new Date(r.createdDate),updatedDate:new Date(r.updatedDate),closedDate:r.closedDate?new Date(r.closedDate):null,mergedDate:r.state=="MERGED"&&r.closedDate?new Date(r.closedDate):null,baseRef:{name:r.toRef.displayId,oid:r.toRef.latestCommit},headRef:{name:r.fromRef.displayId,oid:r.fromRef.latestCommit},commentCount:r.properties.commentCount,upvoteCount:null,commitCount:null,fileCount:null,additions:null,deletions:null,author:fe(r.author.user),assignees:null,reviews:t,reviewDecision:x(t),repository:{id:r.toRef.repository.id.toString(),name:r.toRef.repository.name,owner:{login:r.toRef.repository.project.key},remoteInfo:o&&n?{cloneUrlHTTPS:o,cloneUrlSSH:n}:null},headRepository:{id:r.fromRef.repository.id.toString(),name:r.fromRef.repository.name,owner:{login:r.fromRef.repository.project.key},remoteInfo:a&&i?{cloneUrlHTTPS:a,cloneUrlSSH:i}:null},headCommit:null,mergeableState:"MERGEABLE",permissions:null,version:r.version}},Ct=r=>{var s,e,t;return{id:r.id.toString(),namespace:r.project.key,name:r.slug,webUrl:((s=r.links.self[0])==null?void 0:s.href)??null,httpsUrl:((e=r.links.clone.find(n=>n.name==="https"||n.name==="http"))==null?void 0:e.href)??null,sshUrl:((t=r.links.clone.find(n=>n.name==="ssh"))==null?void 0:t.href)??null,defaultBranch:null,permissions:null}},Z=class extends A{getBaseUrl(s){let e=s.baseUrl||this.config.baseUrl;if(!e)throw new Error('Bitbucket Server requires "baseUrl"');return e}getRequestHeaders(s){return I(s.token||this.config.token)}async getCurrentUser(s={},e={}){let t=await this.config.request({url:`${this.getBaseUrl(e)}/users?limit=2`,headers:this.getRequestHeaders(e)}),{headers:{"x-auserid":n,"x-ausername":o}}=t,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:p,id:d,name:c,slug:g})=>i?i===d:a===c||a===p||a===g);if(!l)throw new Error("Could not find current Bitbucket Server user");return{data:fe(l)}}async getUserForCommit(s,e){let{repo:t,oid:n}=s,o=await this.config.request({url:`${this.getBaseUrl(e)}/projects/${t.namespace}/repos/${t.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(s,e={}){let t=await this.config.request({url:`${this.getBaseUrl(e)}/projects/${s.namespace}/repos/${s.name}`,headers:this.getRequestHeaders(e)});return{data:Ct(t.body)}}async getRepos(s,e={}){let t=[],n=[];return await Promise.all(s.map(async o=>{try{let i=await this.getRepo(o,e);t.push(i.data)}catch(i){n.push({input:o,error:i})}})),{data:t,errors:n}}async getReposForCurrentUser(s,e={}){let t=s.page??0,n=await this.config.request({url:`${this.getBaseUrl(e)}/repos?start=${t}`,headers:this.getRequestHeaders(e)});return{pageInfo:{hasNextPage:!n.body.isLastPage,nextPage:n.body.nextPageStart},data:n.body.values.map(Ct)}}async getRepoPermissionsForUsername(s,e={}){var n;let t=new URL(`${this.getBaseUrl(e)}/projects/${s.repo.namespace}/repos/${s.repo.name}/permissions/search?filterText=${s.username}`);try{let o=await this.config.request({url:t.toString(),headers:this.getRequestHeaders(e)});return{data:qt(o.body.values)}}catch(o){if(((n=o.response)==null?void 0:n.status)===401)return{data:{canCreateWebhook:!1,canPush:!1,isAdmin:!1}};throw o}}async decorateReposWithPermissions(s,e={}){return await Promise.all(s.repos.map(async n=>{let o=await this.getRepoPermissionsForUsername({repo:n,username:s.username},e);return{...n,permissions:o.data}}))}async getPullRequestsForRepoBase(s,e={}){var n;let t=new URL(`${this.getBaseUrl(e)}/projects/${encodeURI(s.repo.namespace)}/repos/${encodeURI(s.repo.name)}/pull-requests?state=OPEN`);return t.searchParams.set("start",((n=s.page)==null?void 0:n.toString())||"0"),t.searchParams.set("limit","50"),await this.config.request({url:t.toString(),headers:this.getRequestHeaders(e)})}async getPullRequestsForRepo(s,e={}){let t=[],n=await this.getPullRequestsForRepoBase(s,e);n.body.values.forEach(i=>{if(s.authorLogin&&i.author.user.name!==s.authorLogin)return null;t.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:t}}async getPullRequestsForRepos(s,e={}){let t=[];return await Promise.all(s.repos.map(async n=>{try{(await this.getPullRequestsForRepoBase({repo:n,...s},e)).body.values.forEach(i=>{if(s.authorLogin&&i.author.user.name!==s.authorLogin)return null;t.push(he(i))})}catch(o){if(o.statusCode!==404&&o.statusCode!==401)throw o}})),{data:t}}async getPullRequestsForCurrentUser(s,e={}){var i;let t=new URL(`${this.getBaseUrl(e)}/dashboard/pull-requests`);t.searchParams.set("state","OPEN"),t.searchParams.set("start",((i=s.page)==null?void 0:i.toString())||"0"),t.searchParams.set("limit","50");let n=await this.config.request({url:t.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(s,e={}){let{pullRequest:t}=s;if(t.version===void 0)throw new Error('Bitbucket Server requires "version" for this function.');if(!(await this.config.request({method:"POST",url:`${this.getBaseUrl(e)}/projects/${t.repository.owner.login}/repos/${t.repository.name}/pull-requests/${t.id}/decline`,body:JSON.stringify({version:t.version}),headers:{...this.getRequestHeaders(e),"Content-Type":"application/json"}})).body.title)throw new Error("Could not close pull request")}async mergePullRequest(s,e={}){let{pullRequest:t,mergeStrategyId:n}=s;if(s.mergeStrategy)throw new Error('Bitbucket Server uses "mergeStrategyId" instead of "mergeStrategy".');if(t.version===void 0)throw new Error('Bitbucket Server requires "version" for this function.');if(!(await this.config.request({method:"POST",url:`${this.getBaseUrl(e)}/projects/${t.repository.owner.login}/repos/${t.repository.name}/pull-requests/${t.id}/merge`,body:JSON.stringify({strategyId:n,version:t.version}),headers:{...this.getRequestHeaders(e),"Content-Type":"application/json"}})).body.title)throw new Error("Could not merge pull request")}async getMergeStrategies(s={}){let e=await this.config.request({url:`${this.getBaseUrl(s)}/admin/pull-requests/git`,headers:{...this.getRequestHeaders(s),"Content-Type":"application/json"}});return{data:{defaultStrategy:e.body.mergeConfig.defaultStrategy,strategies:e.body.mergeConfig.strategies}}}async setPullRequestReviewers(s,e={}){let{pullRequest:t,reviewers:n}=s;if(t.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:t.version};if(!(await this.config.request({method:"PUT",url:`${this.getBaseUrl(e)}/projects/${t.repository.owner.login}/repos/${t.repository.name}/pull-requests/${t.id}`,body:JSON.stringify(o),headers:{...this.getRequestHeaders(e),"Content-Type":"application/json"}})).body.title)throw new Error("Could not set pull request reviewers")}};var Tt=require("js-base64");var Re=(e=>(e.Open="OPEN",e.Closed="CLOSED",e))(Re||{});var b=class extends Error{constructor(e,t){let n=t==null?void 0:t.map(i=>`'${i.message}'`).join(", "),o=n?`${e}: ${n}`:e;super(o);this.graphQLErrors=t??[]}};var gr={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]},Dt=15,Lt=100,$=r=>!!r,F=(r,s)=>{let e=gr[s];for(let t=0;t<3;t++){if(r[t]>e[t])return!0;if(r[t]<e[t])return!1}return!0},be="https://api.github.com",mr=`${be}/graphql`,ye=`
2
2
  description
3
3
  dueOn
4
4
  id
@@ -15,12 +15,12 @@ url
15
15
  permalink
16
16
  startedAt
17
17
  }
18
- `,Re=/\/api\/v\d+$/,ye=`
18
+ `,Ie=/\/api\/v\d+$/,Pe=`
19
19
  color
20
20
  description
21
21
  id
22
22
  name
23
- `,Ut=r=>{if(r.endsWith("/api/graphql"))throw new Error("The graphql endpoint is being used as the baseUrl. This package uses both GraphQL and REST APIs, and the REST version cannot be assumed. Use the REST endpoint as the baseUrl instead.")},fr=(r,s)=>{let e=s.baseUrl||r.baseUrl;return e?(e=e.replace(/\/$/,""),Ut(e),Re.test(e)&&(e=e.replace(Re,"")),`${e}/api/graphql`):mr},Y=(r,s)=>{let e=s.baseUrl||r.baseUrl;return e?(e=e.replace(/\/$/,""),Ut(e),Re.test(e)&&(e=e.replace(Re,"")),`${e}/api/v3`):Ie},y=(r,s,e)=>{let t=I(e.token||r.token);return t["X-Github-Next-Global-ID"]="1",t["Content-Type"]="application/json",t.Accept="application/vnd.github.merge-info-preview+json",r.request({url:fr(r,e),method:"POST",headers:t,body:JSON.stringify(s)})},Rr={user:!0,"user:email":!0,"read:user":!0},_=r=>r.some(s=>Rr[s]),G=(r=!1,s=!1,e)=>`
23
+ `,Ut=r=>{if(r.endsWith("/api/graphql"))throw new Error("The graphql endpoint is being used as the baseUrl. This package uses both GraphQL and REST APIs, and the REST version cannot be assumed. Use the REST endpoint as the baseUrl instead.")},fr=(r,s)=>{let e=s.baseUrl||r.baseUrl;return e?(e=e.replace(/\/$/,""),Ut(e),Ie.test(e)&&(e=e.replace(Ie,"")),`${e}/api/graphql`):mr},Y=(r,s)=>{let e=s.baseUrl||r.baseUrl;return e?(e=e.replace(/\/$/,""),Ut(e),Ie.test(e)&&(e=e.replace(Ie,"")),`${e}/api/v3`):be},y=(r,s,e)=>{let t=I(e.token||r.token);return t["X-Github-Next-Global-ID"]="1",t["Content-Type"]="application/json",t.Accept="application/vnd.github.merge-info-preview+json",r.request({url:fr(r,e),method:"POST",headers:t,body:JSON.stringify(s)})},Rr={user:!0,"user:email":!0,"read:user":!0},_=r=>r.some(s=>Rr[s]),G=(r=!1,s=!1,e)=>`
24
24
  __typename
25
25
  ${M(e,["graphQLId"],"id")}
26
26
  ${M(e,["id"],"databaseId")}
@@ -56,7 +56,7 @@ id
56
56
  login
57
57
  avatarUrl${r?"(size: $avatarSize)":""}
58
58
  url
59
- `,Pe=(r,s=!1,e)=>`
59
+ `,we=(r,s=!1,e)=>`
60
60
  id
61
61
  ${!e||F(e,"PR_FULL_DATABASE_ID")?"fullDatabaseId":"databaseId"}
62
62
  number
@@ -165,11 +165,11 @@ changedFiles
165
165
  mergeable
166
166
  mergeStateStatus
167
167
  milestone {
168
- ${be}
168
+ ${ye}
169
169
  }
170
170
  labels(first: 100) {
171
171
  nodes {
172
- ${ye}
172
+ ${Pe}
173
173
  }
174
174
  }
175
175
  ${!e||F(e,"VIEWER_CAN_MERGE_AS_ADMIN")?"viewerCanMergeAsAdmin":""}
@@ -214,11 +214,11 @@ assignees(first: 100) {
214
214
  }
215
215
  state
216
216
  milestone {
217
- ${be}
217
+ ${ye}
218
218
  }
219
219
  labels(first: 100) {
220
220
  nodes {
221
- ${ye}
221
+ ${Pe}
222
222
  }
223
223
  }
224
224
  `,yr={"-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"},Pr=new RegExp('(([^\\s]+:)?\\"(?:[^\\"\\\\]|\\\\.)*\\"?)|([^\\"\\s]+)',"g"),ze=r=>{let s=[];return(r.match(Pr)??[]).forEach(t=>{if(t.includes(":")&&t!="is:closed"){let n=t.split(":")[0];yr[n]&&s.push(t)}}),s},We=(r,s,e,t)=>{let n=r==="issue";return{query:`
@@ -230,11 +230,11 @@ query SearchIssuesOrPullRequests($query: String! $after: String) {
230
230
  }
231
231
  nodes {
232
232
  ... on ${n?"Issue":"PullRequest"} {
233
- ${n?br(t.supportsEmail,t.enterpriseVersion??null):Pe(t.supportsDrafts??!1,t.supportsEmail,t.enterpriseVersion??null)}
233
+ ${n?br(t.supportsEmail,t.enterpriseVersion??null):we(t.supportsDrafts??!1,t.supportsEmail,t.enterpriseVersion??null)}
234
234
  }
235
235
  }
236
236
  }
237
- }`,variables:{query:`is:${r} is:open ${t.includeFromArchivedRepos?"":"archived:false"} ${s}`,after:e}}},wr="Field 'isDraft' doesn't exist on type 'PullRequest'",we=(r=[])=>r.some(s=>(s==null?void 0:s.message)===wr),Sr=/@@ -(\d+)(?:,\d+ | )\+(\d+)(?:,\d+ | )@@(?:\\n)?/,vr=`
237
+ }`,variables:{query:`is:${r} is:open ${t.includeFromArchivedRepos?"":"archived:false"} ${s}`,after:e}}},wr="Field 'isDraft' doesn't exist on type 'PullRequest'",Se=(r=[])=>r.some(s=>(s==null?void 0:s.message)===wr),Sr=/@@ -(\d+)(?:,\d+ | )\+(\d+)(?:,\d+ | )@@(?:\\n)?/,vr=`
238
238
  \
239
239
  +`,At=(r,s,e,t)=>{let n=Sr.exec(r);if(!n||!n[0]||!n[1])return[];let o=parseInt(n[1],10),i=parseInt(n[2],10),a=r.replace(vr,`
240
240
  +`).split(`
@@ -254,7 +254,7 @@ defaultBranchRef {
254
254
  name
255
255
  }
256
256
  viewerPermission
257
- `,Ke={__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"},Er={APPROVED:"APPROVED",CHANGES_REQUESTED:"CHANGES_REQUESTED",COMMENTED:"COMMENTED",REVIEW_REQUESTED:"REVIEW_REQUESTED"},qr={MERGEABLE:"MERGEABLE",CONFLICTING:"CONFLICTS",UNKNOWN:"UNKNOWN"},Cr={BEHIND:"BEHIND",BLOCKED:"BLOCKED",UNKNOWN:"UNKNOWN_AND_BLOCKED",UNSTABLE:"UNSTABLE",CLEAN:null,DIRTY:null,DRAFT:null,HAS_HOOKS:null},Dr={OPEN:"OPEN",CLOSED:"CLOSED"},Lr=["ADMIN","MAINTAIN","TRIAGE","WRITE"],Xe=r=>({color:`#${r.color}`,description:r.description,graphQLId:r.id,id:null,name:r.name}),Ur=r=>({canCreateWebhook:r==="ADMIN",canPush:r==="ADMIN"||r==="MAINTAIN"||r==="WRITE",isAdmin:r==="ADMIN"}),Je=r=>({id:r.databaseId.toString(),graphQLId:r.id,namespace:r.owner.login,name:r.name,webUrl:r.url,httpsUrl:r.url.endsWith(".git")?r.url:`${r.url}.git`,sshUrl:r.sshUrl,defaultBranch:r.defaultBranchRef,permissions:Ur(r.viewerPermission)}),$r=r=>({canCreateWebhook:r.admin,canPush:r.admin||r.maintain||r.push,isAdmin:r.admin}),Gt=r=>({id:r.id.toString(),graphQLId:r.node_id,namespace:r.owner.login,name:r.name,webUrl:r.html_url,httpsUrl:r.clone_url,sshUrl:r.ssh_url,defaultBranch:{name:r.default_branch},permissions:$r(r.permissions)}),Ar=r=>({path:r.path,isDirectory:r.type==="tree"}),Gr={OPEN:"OPEN",CLOSED:"CLOSED",MERGED:"MERGED"},Tr={id:!0,graphQLId:!0,name:!0,username:!0,email:!0,avatarUrl:!0,url:!0},O=(r,s=Tr)=>{let e={};return s.id&&(e.id="databaseId"in r?r.databaseId.toString():r.id),s.graphQLId&&(e.graphQLId=r.id),s.name&&(e.name=r.name??r.login),s.username&&(e.username=r.login),s.email&&(e.email=r.email??null),s.avatarUrl&&(e.avatarUrl=r.avatarUrl),s.url&&(e.url=r.url),e},Or=(r,s)=>{let e={IN_PROGRESS:"RUNNING",PENDING:"PENDING",QUEUED:"PENDING",REQUESTED:"PENDING",WAITING:"PENDING"};return r!=="COMPLETED"?e[r]:{ACTION_REQUIRED:"ACTION_REQUIRED",CANCELLED:"CANCELLED",FAILURE:"FAILED",NEUTRAL:null,SKIPPED:"SKIPPED",STALE:"FAILED",STARTUP_FAILURE:"FAILED",SUCCESS:"SUCCESS",TIMED_OUT:"ERROR"}[s]},xr=r=>({ERROR:"ERROR",EXPECTED:"PENDING",FAILURE:"FAILED",PENDING:"PENDING",SUCCESS:"SUCCESS"})[r],Ve=r=>{var i,a,u,l,p,d,c,g,m,R,h,P;let s=null;r.author?s=r.author:s=Ke;let e=(((i=r.reviewRequests)==null?void 0:i.nodes)||[]).filter($).filter(f=>!f.asCodeOwner),t=(a=r.headRepository)==null?void 0:a.url;t&&!t.endsWith(".git")&&(t=`${t}.git`);let n=(u=r.repository)==null?void 0:u.url;n&&!n.endsWith(".git")&&(n=`${n}.git`);let o=e.filter(f=>f.requestedReviewer&&"__typename"in f.requestedReviewer).map(f=>({reviewer:O(f.requestedReviewer),state:"REVIEW_REQUESTED"})).concat((((l=r.latestReviews)==null?void 0:l.nodes)||[]).filter($).map(f=>{let E=Ke;return f.author&&f.author.__typename&&(E=f.author),{reviewer:O(E),state:Er[f.state]}}));return{id:r.fullDatabaseId!==void 0?r.fullDatabaseId:r.databaseId.toString(),graphQLId:r.id,title:r.title,number:r.number,state:Gr[r.state],commentCount:r.comments.totalCount,upvoteCount:r.reactions.totalCount,author:s&&s.__typename?O(s):null,createdDate:new Date(r.createdAt),isDraft:r.isDraft,repository:{id:r.repository.databaseId.toString(),graphQLId:r.repository.id,name:r.repository.name,owner:{login:r.repository.owner.login},remoteInfo:{cloneUrlHTTPS:n,cloneUrlSSH:r.repository.sshUrl}},headRepository:r.headRepository?{id:r.headRepository.databaseId.toString(),graphQLId:r.headRepository.id,name:r.headRepository.name,owner:{login:r.headRepository.owner.login},remoteInfo:{cloneUrlHTTPS:t,cloneUrlSSH:r.headRepository.sshUrl}}:null,headCommit:{buildStatuses:((g=(c=(d=(p=r.commits.nodes)==null?void 0:p.filter($)[0])==null?void 0:d.commit.statusCheckRollup)==null?void 0:c.contexts.nodes)==null?void 0:g.filter($).map(f=>"context"in f?{completedAt:null,description:f.description,name:f.context,state:xr(f.state),startedAt:new Date(f.createdAt),stage:null,url:f.targetUrl}:{completedAt:f.completedAt?new Date(f.completedAt):null,description:null,name:f.name,state:Or(f.status,f.conclusion),startedAt:f.startedAt?new Date(f.startedAt):null,stage:null,url:f.permalink}))??[]},headRef:r.headRef?{name:r.headRef.name,oid:((m=r.headRef.target)==null?void 0:m.oid)??null}:null,baseRef:r.baseRef?{name:r.baseRef.name,oid:((R=r.baseRef.target)==null?void 0:R.oid)??null}:null,url:r.url,updatedDate:new Date(r.updatedAt),closedDate:r.closedAt?new Date(r.closedAt):null,mergedDate:r.mergedAt?new Date(r.mergedAt):null,assignees:r.assignees.nodes?r.assignees.nodes.filter($).map(f=>O(f)):null,reviews:o,reviewDecision:x(o),additions:r.additions,deletions:r.deletions,fileCount:r.changedFiles,commitCount:r.commits.totalCount,mergeableState:Cr[r.mergeStateStatus]??qr[r.mergeable],milestone:r.milestone?Ze(r.milestone):null,labels:((P=(h=r.labels)==null?void 0:h.nodes)==null?void 0:P.filter($).map(Xe))??[],permissions:{canMerge:Lr.includes(r.repository.viewerPermission),canMergeAndBypassProtections:r.viewerCanMergeAsAdmin??!1}}},kr=r=>{var h,P;let{comments:s,isOutdated:e,isResolved:t,originalLine:n,originalStartLine:o,startDiffSide:i}=r,a=(h=s.nodes)==null?void 0:h[0];if(!a)return null;let{author:u,body:l,databaseId:p,fullDatabaseId:d,id:c,path:g,publishedAt:m,url:R}=a;return{author:u?{avatarUrl:u.avatarUrl,email:null,name:u.login}:null,body:l,createdAt:m?new Date(m):null,diffLines:At(a.diffHunk,n,o,i),id:d??p.toString(),isOutdated:e,isResolved:t,graphQLId:c,filename:g,replies:((P=s.nodes)==null?void 0:P.filter($).slice(1).map(Nr))??[],url:R}},Nr=r=>({author:r.author?{avatarUrl:r.author.avatarUrl,email:null,name:r.author.login}:null,body:r.body,createdAt:r.publishedAt?new Date(r.publishedAt):null,graphQLId:r.id,id:r.fullDatabaseId??r.databaseId.toString(),url:r.url}),Fr=r=>{var e,t,n;let s=null;return r.author?s=r.author:s=Ke,{id:r.fullDatabaseId!==void 0?r.fullDatabaseId:r.databaseId.toString(),graphQLId:r.id,number:r.number,title:r.title,author:s&&s.__typename?O(s):null,commentCount:r.comments.totalCount,closedDate:r.closedAt?new Date(r.closedAt):null,createdDate:new Date(r.createdAt),description:null,state:{name:Dr[r.state],color:null},type:null,repository:{id:r.repository.databaseId.toString(),graphQLId:r.repository.id,name:r.repository.name,owner:{login:r.repository.owner.login}},url:r.url,updatedDate:new Date(r.updatedAt),assignees:((e=r.assignees.nodes)==null?void 0:e.filter($).map(o=>O(o)))??[],upvoteCount:r.reactions.totalCount,milestone:r.milestone?Ze(r.milestone):null,labels:((n=(t=r.labels)==null?void 0:t.nodes)==null?void 0:n.filter($).map(Xe))??[]}},Ze=r=>({id:r.number.toString(),graphQLId:r.id.toString(),number:r.number,title:r.title,description:r.description,isOpen:r.state=="OPEN",url:r.url,startDate:null,dueDate:r.dueOn?new Date(r.dueOn):null}),ee=class extends A{constructor(){super(...arguments);this._scopesCache={};this._enterpriseVersionsCache={}}async getScopes(e){let t=e.token||this.config.token;if(!t)return[];let n=this._scopesCache[t];if(!n){let i=(await y(this.config,{query:"query { rateLimit(dryRun: true) { __typename } }"},e)).headers["x-oauth-scopes"];n=i?i.split(", "):[],this._scopesCache[t]=n}return n}async getEnterpriseVersion(e){let t=e.baseUrl||this.config.baseUrl;if(!t)return null;let n=this._enterpriseVersionsCache[t];if(!n){let o=await this.config.request({url:`${Y(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[t]=n}return n}getEnterpriseAvatarUrlIfNeeded(e,t,n){let o=n.baseUrl||this.config.baseUrl;return!o||o.startsWith(Ie)?e:t?`https://avatars.githubusercontent.com/u/e?email=${encodeURIComponent(t)}`:""}async getCurrentUser(e={},t={}){var u;if(e.fields&&!e.fields.length)throw new Error('"fields" must contain at least one field or be omitted');let n=yt(e.fields),o=await this.getScopes(t),i=await y(this.config,{query:`
257
+ `,Ke={__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"},Er={APPROVED:"APPROVED",CHANGES_REQUESTED:"CHANGES_REQUESTED",COMMENTED:"COMMENTED",REVIEW_REQUESTED:"REVIEW_REQUESTED"},qr={MERGEABLE:"MERGEABLE",CONFLICTING:"CONFLICTS",UNKNOWN:"UNKNOWN"},Cr={BEHIND:"BEHIND",BLOCKED:"BLOCKED",UNKNOWN:"UNKNOWN_AND_BLOCKED",UNSTABLE:"UNSTABLE",CLEAN:null,DIRTY:null,DRAFT:null,HAS_HOOKS:null},Dr={OPEN:"OPEN",CLOSED:"CLOSED"},Lr=["ADMIN","MAINTAIN","TRIAGE","WRITE"],Xe=r=>({color:`#${r.color}`,description:r.description,graphQLId:r.id,id:null,name:r.name}),Ur=r=>({canCreateWebhook:r==="ADMIN",canPush:r==="ADMIN"||r==="MAINTAIN"||r==="WRITE",isAdmin:r==="ADMIN"}),Je=r=>({id:r.databaseId.toString(),graphQLId:r.id,namespace:r.owner.login,name:r.name,webUrl:r.url,httpsUrl:r.url.endsWith(".git")?r.url:`${r.url}.git`,sshUrl:r.sshUrl,defaultBranch:r.defaultBranchRef,permissions:Ur(r.viewerPermission)}),$r=r=>({canCreateWebhook:r.admin,canPush:r.admin||r.maintain||r.push,isAdmin:r.admin}),Gt=r=>({id:r.id.toString(),graphQLId:r.node_id,namespace:r.owner.login,name:r.name,webUrl:r.html_url,httpsUrl:r.clone_url,sshUrl:r.ssh_url,defaultBranch:{name:r.default_branch},permissions:$r(r.permissions)}),Ar=r=>({path:r.path,isDirectory:r.type==="tree"}),Gr={OPEN:"OPEN",CLOSED:"CLOSED",MERGED:"MERGED"},Tr={id:!0,graphQLId:!0,name:!0,username:!0,email:!0,avatarUrl:!0,url:!0},O=(r,s=Tr)=>{let e={};return s.id&&(e.id="databaseId"in r?r.databaseId.toString():r.id),s.graphQLId&&(e.graphQLId=r.id),s.name&&(e.name=r.name??r.login),s.username&&(e.username=r.login),s.email&&(e.email=r.email??null),s.avatarUrl&&(e.avatarUrl=r.avatarUrl),s.url&&(e.url=r.url),e},Or=(r,s)=>{let e={IN_PROGRESS:"RUNNING",PENDING:"PENDING",QUEUED:"PENDING",REQUESTED:"PENDING",WAITING:"PENDING"};return r!=="COMPLETED"?e[r]:{ACTION_REQUIRED:"ACTION_REQUIRED",CANCELLED:"CANCELLED",FAILURE:"FAILED",NEUTRAL:null,SKIPPED:"SKIPPED",STALE:"FAILED",STARTUP_FAILURE:"FAILED",SUCCESS:"SUCCESS",TIMED_OUT:"ERROR"}[s]},xr=r=>({ERROR:"ERROR",EXPECTED:"PENDING",FAILURE:"FAILED",PENDING:"PENDING",SUCCESS:"SUCCESS"})[r],Ve=r=>{var i,a,u,l,p,d,c,g,m,R,h,P;let s=null;r.author?s=r.author:s=Ke;let e=(((i=r.reviewRequests)==null?void 0:i.nodes)||[]).filter($).filter(f=>!f.asCodeOwner),t=(a=r.headRepository)==null?void 0:a.url;t&&!t.endsWith(".git")&&(t=`${t}.git`);let n=(u=r.repository)==null?void 0:u.url;n&&!n.endsWith(".git")&&(n=`${n}.git`);let o=e.filter(f=>f.requestedReviewer&&"__typename"in f.requestedReviewer).map(f=>({reviewer:O(f.requestedReviewer),state:"REVIEW_REQUESTED"})).concat((((l=r.latestReviews)==null?void 0:l.nodes)||[]).filter($).map(f=>{let E=Ke;return f.author&&f.author.__typename&&(E=f.author),{reviewer:O(E),state:Er[f.state]}}));return{id:r.fullDatabaseId!==void 0?r.fullDatabaseId:r.databaseId.toString(),graphQLId:r.id,title:r.title,number:r.number,state:Gr[r.state],commentCount:r.comments.totalCount,upvoteCount:r.reactions.totalCount,author:s&&s.__typename?O(s):null,createdDate:new Date(r.createdAt),isDraft:r.isDraft,repository:{id:r.repository.databaseId.toString(),graphQLId:r.repository.id,name:r.repository.name,owner:{login:r.repository.owner.login},remoteInfo:{cloneUrlHTTPS:n,cloneUrlSSH:r.repository.sshUrl}},headRepository:r.headRepository?{id:r.headRepository.databaseId.toString(),graphQLId:r.headRepository.id,name:r.headRepository.name,owner:{login:r.headRepository.owner.login},remoteInfo:{cloneUrlHTTPS:t,cloneUrlSSH:r.headRepository.sshUrl}}:null,headCommit:{buildStatuses:((g=(c=(d=(p=r.commits.nodes)==null?void 0:p.filter($)[0])==null?void 0:d.commit.statusCheckRollup)==null?void 0:c.contexts.nodes)==null?void 0:g.filter($).map(f=>"context"in f?{completedAt:null,description:f.description,name:f.context,state:xr(f.state),startedAt:new Date(f.createdAt),stage:null,url:f.targetUrl}:{completedAt:f.completedAt?new Date(f.completedAt):null,description:null,name:f.name,state:Or(f.status,f.conclusion),startedAt:f.startedAt?new Date(f.startedAt):null,stage:null,url:f.permalink}))??[]},headRef:r.headRef?{name:r.headRef.name,oid:((m=r.headRef.target)==null?void 0:m.oid)??null}:null,baseRef:r.baseRef?{name:r.baseRef.name,oid:((R=r.baseRef.target)==null?void 0:R.oid)??null}:null,url:r.url,updatedDate:new Date(r.updatedAt),closedDate:r.closedAt?new Date(r.closedAt):null,mergedDate:r.mergedAt?new Date(r.mergedAt):null,assignees:r.assignees.nodes?r.assignees.nodes.filter($).map(f=>O(f)):null,reviews:o,reviewDecision:x(o),additions:r.additions,deletions:r.deletions,fileCount:r.changedFiles,commitCount:r.commits.totalCount,mergeableState:Cr[r.mergeStateStatus]??qr[r.mergeable],milestone:r.milestone?Ze(r.milestone):null,labels:((P=(h=r.labels)==null?void 0:h.nodes)==null?void 0:P.filter($).map(Xe))??[],permissions:{canMerge:Lr.includes(r.repository.viewerPermission),canMergeAndBypassProtections:r.viewerCanMergeAsAdmin??!1}}},kr=r=>{var h,P;let{comments:s,isOutdated:e,isResolved:t,originalLine:n,originalStartLine:o,startDiffSide:i}=r,a=(h=s.nodes)==null?void 0:h[0];if(!a)return null;let{author:u,body:l,databaseId:p,fullDatabaseId:d,id:c,path:g,publishedAt:m,url:R}=a;return{author:u?{avatarUrl:u.avatarUrl,email:null,name:u.login}:null,body:l,createdAt:m?new Date(m):null,diffLines:At(a.diffHunk,n,o,i),id:d??p.toString(),isOutdated:e,isResolved:t,graphQLId:c,filename:g,replies:((P=s.nodes)==null?void 0:P.filter($).slice(1).map(Nr))??[],url:R}},Nr=r=>({author:r.author?{avatarUrl:r.author.avatarUrl,email:null,name:r.author.login}:null,body:r.body,createdAt:r.publishedAt?new Date(r.publishedAt):null,graphQLId:r.id,id:r.fullDatabaseId??r.databaseId.toString(),url:r.url}),Fr=r=>{var e,t,n;let s=null;return r.author?s=r.author:s=Ke,{id:r.fullDatabaseId!==void 0?r.fullDatabaseId:r.databaseId.toString(),graphQLId:r.id,number:r.number,title:r.title,author:s&&s.__typename?O(s):null,commentCount:r.comments.totalCount,closedDate:r.closedAt?new Date(r.closedAt):null,createdDate:new Date(r.createdAt),description:null,state:{name:Dr[r.state],color:null},type:null,repository:{id:r.repository.databaseId.toString(),graphQLId:r.repository.id,name:r.repository.name,owner:{login:r.repository.owner.login}},url:r.url,updatedDate:new Date(r.updatedAt),assignees:((e=r.assignees.nodes)==null?void 0:e.filter($).map(o=>O(o)))??[],upvoteCount:r.reactions.totalCount,milestone:r.milestone?Ze(r.milestone):null,labels:((n=(t=r.labels)==null?void 0:t.nodes)==null?void 0:n.filter($).map(Xe))??[]}},Ze=r=>({id:r.number.toString(),graphQLId:r.id.toString(),number:r.number,title:r.title,description:r.description,isOpen:r.state=="OPEN",url:r.url,startDate:null,dueDate:r.dueOn?new Date(r.dueOn):null}),ee=class extends A{constructor(){super(...arguments);this._scopesCache={};this._enterpriseVersionsCache={}}async getScopes(e){let t=e.token||this.config.token;if(!t)return[];let n=this._scopesCache[t];if(!n){let i=(await y(this.config,{query:"query { rateLimit(dryRun: true) { __typename } }"},e)).headers["x-oauth-scopes"];n=i?i.split(", "):[],this._scopesCache[t]=n}return n}async getEnterpriseVersion(e){let t=e.baseUrl||this.config.baseUrl;if(!t)return null;let n=this._enterpriseVersionsCache[t];if(!n){let o=await this.config.request({url:`${Y(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[t]=n}return n}getEnterpriseAvatarUrlIfNeeded(e,t,n){let o=n.baseUrl||this.config.baseUrl;return!o||o.startsWith(be)?e:t?`https://avatars.githubusercontent.com/u/e?email=${encodeURIComponent(t)}`:""}async getCurrentUser(e={},t={}){var u;if(e.fields&&!e.fields.length)throw new Error('"fields" must contain at least one field or be omitted');let n=yt(e.fields),o=await this.getScopes(t),i=await y(this.config,{query:`
258
258
  query getCurrentUser {
259
259
  viewer {
260
260
  ${G(!1,_(o),n)}
@@ -460,7 +460,7 @@ query getBlame($owner: String!, $name: String!, $ref: String!, $path: String!) {
460
460
  }
461
461
  }
462
462
  }
463
- `,variables:{owner:e.repo.namespace,name:e.repo.name,ref:e.ref,path:e.path}},t),o=(a=n.body.data)==null?void 0:a.repository;if(!o)throw new b("Blame repository not found.",n.body.errors);let i=o.object;if(!i||!("blame"in i))throw new b("Ref not found.",n.body.errors);if(i.blame.ranges.length===0)throw new b("File not found.",n.body.errors);return{data:{ranges:i.blame.ranges.map(u=>{var l;return{startingLine:u.startingLine,endingLine:u.endingLine,commit:{oid:u.commit.oid,parentOids:((l=u.commit.parents.nodes)==null?void 0:l.map(p=>p.oid))||[],authoredDate:new Date(u.commit.authoredDate),author:u.commit.author?{name:u.commit.author.name,email:u.commit.author.email,avatarUrl:u.commit.author.avatarUrl}:null,committedDate:new Date(u.commit.committedDate),committer:u.commit.committer?{name:u.commit.committer.name,email:u.commit.committer.email,avatarUrl:u.commit.committer.avatarUrl}:null,message:u.commit.message,fileCount:u.commit.changedFilesIfAvailable,additions:u.commit.additions,deletions:u.commit.deletions}}})}}}async getFileContents(e,t={}){let n=await this.config.request({url:`${Y(this.config,t)}/repos/${e.repo.namespace}/${e.repo.name}/contents/${encodeURIComponent(e.path)}?ref=${e.ref}`,headers:{...I(t.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 searchPullRequests(e,t={}){var p;let n=await this.getEnterpriseVersion(t),o=await this.getScopes(t),i=_(o),a=d=>{let c=d&&typeof e.isDraft=="boolean"?`${e.query} draft:${e.isDraft}`:e.query;return We("pr",c,e.cursor,{maxPageSize:e.maxPageSize??Dt,supportsEmail:i,supportsDrafts:d,enterpriseVersion:n,includeFromArchivedRepos:e.includeFromArchivedRepos})},u=await y(this.config,a(!0),t);u.body.errors&&we(u.body.errors)&&(this.config.baseUrl||t.baseUrl)&&(u=await y(this.config,a(!1),t));let{data:l}=u.body;if(!l)throw new b("Could not search pull requests",u.body.errors);return{pageInfo:{hasNextPage:l.search.pageInfo.hasNextPage,endCursor:l.search.pageInfo.endCursor},data:((p=l.search.nodes)==null?void 0:p.filter($).map(Ve))||[]}}async searchIssues(e,t={}){var l;let n=await this.getEnterpriseVersion(t),o=await this.getScopes(t),i=_(o),a=await y(this.config,We("issue",e.query,e.cursor,{supportsEmail:i,includeFromArchivedRepos:e.includeFromArchivedRepos,maxPageSize:e.maxPageSize??Lt,enterpriseVersion:n}),t),{data:u}=a.body;if(!u)throw new b("Could not search issues",a.body.errors);return{pageInfo:{hasNextPage:u.search.pageInfo.hasNextPage,endCursor:u.search.pageInfo.endCursor},data:((l=u.search.nodes)==null?void 0:l.filter($).map(Fr))||[]}}async getPullRequestsAssociatedWithUser(e,t={}){var o;let n=[`involves:${e.username}`];return(o=e.repos)!=null&&o.length&&e.repos.forEach(i=>{n.push(`repo:${i.namespace}/${i.name}`)}),e.labelNames&&e.labelNames.forEach(i=>{n.push(`label:"${i}"`)}),this.searchPullRequests({query:n.join(" "),cursor:e.cursor,includeFromArchivedRepos:e.includeFromArchivedRepos,maxPageSize:e.maxPageSize},t)}async getPullRequestsForRepos(e,t={}){let{assigneeLogins:n,updatedBefore:o,authorLogin:i,repos:a,reviewRequestedLogin:u,startQuery:l,mentionLogin:p,labelNames:d,maxPageSize:c}=e,g=ze(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}`),p&&g.push(`mentions:${p}`),d&&d.forEach(m=>{g.push(`label:"${m}"`)}),this.searchPullRequests({query:`sort:updated ${g.join(" ")}`,isDraft:e.isDraft,cursor:e.cursor,includeFromArchivedRepos:e.includeFromArchivedRepos,maxPageSize:c},t)}async getPullRequestForRepo(e,t={}){var d;let n=await this.getEnterpriseVersion(t),o=await this.getScopes(t),i=_(o),a=c=>({query:`query getPullRequest(
463
+ `,variables:{owner:e.repo.namespace,name:e.repo.name,ref:e.ref,path:e.path}},t),o=(a=n.body.data)==null?void 0:a.repository;if(!o)throw new b("Blame repository not found.",n.body.errors);let i=o.object;if(!i||!("blame"in i))throw new b("Ref not found.",n.body.errors);if(i.blame.ranges.length===0)throw new b("File not found.",n.body.errors);return{data:{ranges:i.blame.ranges.map(u=>{var l;return{startingLine:u.startingLine,endingLine:u.endingLine,commit:{oid:u.commit.oid,parentOids:((l=u.commit.parents.nodes)==null?void 0:l.map(p=>p.oid))||[],authoredDate:new Date(u.commit.authoredDate),author:u.commit.author?{name:u.commit.author.name,email:u.commit.author.email,avatarUrl:u.commit.author.avatarUrl}:null,committedDate:new Date(u.commit.committedDate),committer:u.commit.committer?{name:u.commit.committer.name,email:u.commit.committer.email,avatarUrl:u.commit.committer.avatarUrl}:null,message:u.commit.message,fileCount:u.commit.changedFilesIfAvailable,additions:u.commit.additions,deletions:u.commit.deletions}}})}}}async getFileContents(e,t={}){let n=await this.config.request({url:`${Y(this.config,t)}/repos/${e.repo.namespace}/${e.repo.name}/contents/${encodeURIComponent(e.path)}?ref=${e.ref}`,headers:{...I(t.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 searchPullRequests(e,t={}){var p;let n=await this.getEnterpriseVersion(t),o=await this.getScopes(t),i=_(o),a=d=>{let c=d&&typeof e.isDraft=="boolean"?`${e.query} draft:${e.isDraft}`:e.query;return We("pr",c,e.cursor,{maxPageSize:e.maxPageSize??Dt,supportsEmail:i,supportsDrafts:d,enterpriseVersion:n,includeFromArchivedRepos:e.includeFromArchivedRepos})},u=await y(this.config,a(!0),t);u.body.errors&&Se(u.body.errors)&&(this.config.baseUrl||t.baseUrl)&&(u=await y(this.config,a(!1),t));let{data:l}=u.body;if(!l)throw new b("Could not search pull requests",u.body.errors);return{pageInfo:{hasNextPage:l.search.pageInfo.hasNextPage,endCursor:l.search.pageInfo.endCursor},data:((p=l.search.nodes)==null?void 0:p.filter($).map(Ve))||[]}}async searchIssues(e,t={}){var l;let n=await this.getEnterpriseVersion(t),o=await this.getScopes(t),i=_(o),a=await y(this.config,We("issue",e.query,e.cursor,{supportsEmail:i,includeFromArchivedRepos:e.includeFromArchivedRepos,maxPageSize:e.maxPageSize??Lt,enterpriseVersion:n}),t),{data:u}=a.body;if(!u)throw new b("Could not search issues",a.body.errors);return{pageInfo:{hasNextPage:u.search.pageInfo.hasNextPage,endCursor:u.search.pageInfo.endCursor},data:((l=u.search.nodes)==null?void 0:l.filter($).map(Fr))||[]}}async getPullRequestsAssociatedWithUser(e,t={}){var o;let n=[`involves:${e.username}`];return(o=e.repos)!=null&&o.length&&e.repos.forEach(i=>{n.push(`repo:${i.namespace}/${i.name}`)}),e.labelNames&&e.labelNames.forEach(i=>{n.push(`label:"${i}"`)}),this.searchPullRequests({query:n.join(" "),cursor:e.cursor,includeFromArchivedRepos:e.includeFromArchivedRepos,maxPageSize:e.maxPageSize},t)}async getPullRequestsForRepos(e,t={}){let{assigneeLogins:n,updatedBefore:o,authorLogin:i,repos:a,reviewRequestedLogin:u,startQuery:l,mentionLogin:p,labelNames:d,maxPageSize:c}=e,g=ze(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}`),p&&g.push(`mentions:${p}`),d&&d.forEach(m=>{g.push(`label:"${m}"`)}),this.searchPullRequests({query:`sort:updated ${g.join(" ")}`,isDraft:e.isDraft,cursor:e.cursor,includeFromArchivedRepos:e.includeFromArchivedRepos,maxPageSize:c},t)}async getPullRequestForRepo(e,t={}){var d;let n=await this.getEnterpriseVersion(t),o=await this.getScopes(t),i=_(o),a=c=>({query:`query getPullRequest(
464
464
  $owner: String!
465
465
  $name: String!
466
466
  $number: Int!
@@ -470,18 +470,18 @@ query getBlame($owner: String!, $name: String!, $ref: String!, $path: String!) {
470
470
  name: $name
471
471
  ) {
472
472
  pullRequest(number: $number) {
473
- ${Pe(c,i,n)}
473
+ ${we(c,i,n)}
474
474
  }
475
475
  }
476
- }`,variables:{owner:e.repo.namespace,name:e.repo.name,number:e.number}}),u=await y(this.config,a(!0),t);u.body.errors&&we(u.body.errors)&&(this.config.baseUrl||t.baseUrl)&&(u=await y(this.config,a(!1),t));let{data:l}=u.body;if(!l)throw new b("Could not fetch pull request by number",u.body.errors);let p=(d=u.body.data)==null?void 0:d.repository.pullRequest;return{data:p?Ve(p):null}}async getPullRequestByGraphQLId(e,t={}){var d;let n=await this.getEnterpriseVersion(t),o=await this.getScopes(t),i=_(o),a=c=>({query:`query getPullRequest(
476
+ }`,variables:{owner:e.repo.namespace,name:e.repo.name,number:e.number}}),u=await y(this.config,a(!0),t);u.body.errors&&Se(u.body.errors)&&(this.config.baseUrl||t.baseUrl)&&(u=await y(this.config,a(!1),t));let{data:l}=u.body;if(!l)throw new b("Could not fetch pull request by number",u.body.errors);let p=(d=u.body.data)==null?void 0:d.repository.pullRequest;return{data:p?Ve(p):null}}async getPullRequestByGraphQLId(e,t={}){var d;let n=await this.getEnterpriseVersion(t),o=await this.getScopes(t),i=_(o),a=c=>({query:`query getPullRequest(
477
477
  $graphQLId: ID!
478
478
  ) {
479
479
  node(id: $graphQLId) {
480
480
  ... on PullRequest {
481
- ${Pe(c,i,n)}
481
+ ${we(c,i,n)}
482
482
  }
483
483
  }
484
- }`,variables:{graphQLId:e.graphQLId}}),u=await y(this.config,a(!0),t);u.body.errors&&we(u.body.errors)&&(this.config.baseUrl||t.baseUrl)&&(u=await y(this.config,a(!1),t));let{data:l}=u.body;if(!l)throw new b("Could not fetch pull request by id",u.body.errors);let p=(d=u.body.data)==null?void 0:d.node;return{data:p?Ve(p):null}}async closePullRequest(e,t={}){var a,u,l;let{pullRequest:{graphQLId:n}}=e;if(!n)throw new Error('GitHub requires "graphQLId" for this function.');let o=`mutation ClosePullRequest($pullRequestGraphQLId: ID!) {
484
+ }`,variables:{graphQLId:e.graphQLId}}),u=await y(this.config,a(!0),t);u.body.errors&&Se(u.body.errors)&&(this.config.baseUrl||t.baseUrl)&&(u=await y(this.config,a(!1),t));let{data:l}=u.body;if(!l)throw new b("Could not fetch pull request by id",u.body.errors);let p=(d=u.body.data)==null?void 0:d.node;return{data:p?Ve(p):null}}async closePullRequest(e,t={}){var a,u,l;let{pullRequest:{graphQLId:n}}=e;if(!n)throw new Error('GitHub requires "graphQLId" for this function.');let o=`mutation ClosePullRequest($pullRequestGraphQLId: ID!) {
485
485
  closePullRequest(input: { pullRequestId: $pullRequestGraphQLId }) {
486
486
  pullRequest {
487
487
  id
@@ -636,7 +636,7 @@ query getLabelsForRepo($owner: String!, $name: String! $cursor: String, $first:
636
636
  repository(owner: $owner, name: $name) {
637
637
  milestones(first: $first, after: $cursor) {
638
638
  nodes {
639
- ${be}
639
+ ${ye}
640
640
  }
641
641
  pageInfo {
642
642
  endCursor
@@ -650,7 +650,7 @@ query getLabelsForRepo($owner: String!, $name: String! $cursor: String, $first:
650
650
  repository(owner: $owner, name: $name) {
651
651
  labels(first: $first, after: $cursor) {
652
652
  nodes {
653
- ${ye}
653
+ ${Pe}
654
654
  }
655
655
  pageInfo {
656
656
  endCursor
@@ -659,7 +659,7 @@ query getLabelsForRepo($owner: String!, $name: String! $cursor: String, $first:
659
659
  }
660
660
  }
661
661
  }
662
- `,variables:{owner:n,name:o,cursor:i,first:C}},t);if(!a.body.data)throw new b("Could not fetch labels",a.body.errors);return{pageInfo:((u=a.body.data.repository.labels)==null?void 0:u.pageInfo)??{endCursor:null,hasNextPage:!1},data:((p=(l=a.body.data.repository.labels)==null?void 0:l.nodes)==null?void 0:p.map(Xe))??[]}}async getTreeForRepo(e,t={}){let n=await this.config.request({url:`${Y(this.config,t)}/repos/${e.repo.namespace}/${e.repo.name}/git/trees/${e.branch}?recursive=1`,headers:{...I(t.token||this.config.token)}});if(!n.body)throw new Error("Could not fetch trees");return{data:n.body.tree.map(Ar)}}};var _r="https://gitlab.com/api/v4",Qr="https://gitlab.com/api/graphql",Ye=/\/api\/v\d+$/,Ot=r=>{if(r.endsWith("/api/graphql"))throw new Error("The graphql endpoint is being used as the baseUrl. This package uses both GraphQL and REST APIs, and the REST version cannot be assumed. Use the REST endpoint as the baseUrl instead.")},Se=(r,s)=>{let e=s.baseUrl||r.baseUrl;return e?(e=e.replace(/\/$/,""),Ot(e),Ye.test(e)||(e=e+"/api/v4"),e):_r},Br=(r,s)=>{let e=s.baseUrl||r.baseUrl;return e?(e=e.replace(/\/$/,""),Ot(e),Ye.test(e)&&(e=e.replace(Ye,"")),`${e}/api/graphql`):Qr},w=(r,s,e)=>{let t=I(e.token||r.token);return r.request({url:Br(r,e),method:"POST",headers:{...t,"Content-Type":"application/json"},body:JSON.stringify(s)})},ve=r=>r==null?void 0:r.map(s=>`"${s.message}"`).join(", ");var nt=r=>r.split("/").slice(0,-1).join("/"),ot=r=>r.split("/").at(-1)??"",Ee=r=>({id:r.id.replace(te,""),graphQLId:r.id,namespace:nt(r.fullPath),name:ot(r.fullPath),webUrl:r.webUrl}),xt=r=>({id:r.id.replace(te,""),graphQLId:r.id,httpsUrl:r.httpUrlToRepo,namespace:nt(r.fullPath),name:ot(r.fullPath),sshUrl:r.sshUrlToRepo,webUrl:r.webUrl}),jr={assigned:"assignedMergeRequests",authored:"authoredMergeRequests",reviewRequested:"reviewRequestedMergeRequests"},Mr={CAN_BE_MERGED:"MERGEABLE",CANNOT_BE_MERGED:"CONFLICTS",CANNOT_BE_MERGED_RECHECK:"UNKNOWN",UNCHECKED:"UNKNOWN",CHECKING:"UNKNOWN"};var zr="gid://gitlab/User/",te="gid://gitlab/Project/",Wr="gid://gitlab/MergeRequest/",Hr="gid://gitlab/Issue/",Jr="gid://gitlab/ProjectLabel/",Vr="gid://gitlab/Milestone/",Kr="gid://gitlab/Ci::Build/",it=`
662
+ `,variables:{owner:n,name:o,cursor:i,first:C}},t);if(!a.body.data)throw new b("Could not fetch labels",a.body.errors);return{pageInfo:((u=a.body.data.repository.labels)==null?void 0:u.pageInfo)??{endCursor:null,hasNextPage:!1},data:((p=(l=a.body.data.repository.labels)==null?void 0:l.nodes)==null?void 0:p.map(Xe))??[]}}async getTreeForRepo(e,t={}){let n=await this.config.request({url:`${Y(this.config,t)}/repos/${e.repo.namespace}/${e.repo.name}/git/trees/${e.branch}?recursive=1`,headers:{...I(t.token||this.config.token)}});if(!n.body)throw new Error("Could not fetch trees");return{data:n.body.tree.map(Ar)}}};var _r="https://gitlab.com/api/v4",Qr="https://gitlab.com/api/graphql",Ye=/\/api\/v\d+$/,Ot=r=>{if(r.endsWith("/api/graphql"))throw new Error("The graphql endpoint is being used as the baseUrl. This package uses both GraphQL and REST APIs, and the REST version cannot be assumed. Use the REST endpoint as the baseUrl instead.")},ve=(r,s)=>{let e=s.baseUrl||r.baseUrl;return e?(e=e.replace(/\/$/,""),Ot(e),Ye.test(e)||(e=e+"/api/v4"),e):_r},Br=(r,s)=>{let e=s.baseUrl||r.baseUrl;return e?(e=e.replace(/\/$/,""),Ot(e),Ye.test(e)&&(e=e.replace(Ye,"")),`${e}/api/graphql`):Qr},w=(r,s,e)=>{let t=I(e.token||r.token);return r.request({url:Br(r,e),method:"POST",headers:{...t,"Content-Type":"application/json"},body:JSON.stringify(s)})},Ee=r=>r==null?void 0:r.map(s=>`"${s.message}"`).join(", ");var nt=r=>r.split("/").slice(0,-1).join("/"),ot=r=>r.split("/").at(-1)??"",qe=r=>({id:r.id.replace(te,""),graphQLId:r.id,namespace:nt(r.fullPath),name:ot(r.fullPath),webUrl:r.webUrl}),xt=r=>({id:r.id.replace(te,""),graphQLId:r.id,httpsUrl:r.httpUrlToRepo,namespace:nt(r.fullPath),name:ot(r.fullPath),sshUrl:r.sshUrlToRepo,webUrl:r.webUrl}),jr={assigned:"assignedMergeRequests",authored:"authoredMergeRequests",reviewRequested:"reviewRequestedMergeRequests"},Mr={CAN_BE_MERGED:"MERGEABLE",CANNOT_BE_MERGED:"CONFLICTS",CANNOT_BE_MERGED_RECHECK:"UNKNOWN",UNCHECKED:"UNKNOWN",CHECKING:"UNKNOWN"};var zr="gid://gitlab/User/",te="gid://gitlab/Project/",Wr="gid://gitlab/MergeRequest/",Hr="gid://gitlab/Issue/",Jr="gid://gitlab/ProjectLabel/",Vr="gid://gitlab/Milestone/",Kr="gid://gitlab/Ci::Build/",it=`
663
663
  description
664
664
  dueDate
665
665
  id
@@ -862,7 +862,7 @@ query getRepo($fullPath: ID!) {
862
862
  query batchGetRepos {
863
863
  ${n}
864
864
  }
865
- `},e);if(!o.body.data)throw new Error(ve(o.body.errors)||o.statusText||"Unknown error");let i=[],a=[];return s.forEach((u,l)=>{let p=o.body.data[`getRepo_${l}`];p?i.push(rt(p)):a.push({input:u})}),{data:i,errors:a}}async getRepos(s,e={}){let t=[];for(let i=0;i<s.length;i+=15)t.push(s.slice(i,i+15));return(await Promise.all(t.map(i=>this.getReposBase(i,e)))).reduce((i,a)=>({data:[...i.data,...a.data],errors:[...i.errors,...a.errors]}),{data:[],errors:[]})}async getReposForCurrentUser(s,e={}){var o,i,a,u,l;let t=await w(this.config,{query:`
865
+ `},e);if(!o.body.data)throw new Error(Ee(o.body.errors)||o.statusText||"Unknown error");let i=[],a=[];return s.forEach((u,l)=>{let p=o.body.data[`getRepo_${l}`];p?i.push(rt(p)):a.push({input:u})}),{data:i,errors:a}}async getRepos(s,e={}){let t=[];for(let i=0;i<s.length;i+=15)t.push(s.slice(i,i+15));return(await Promise.all(t.map(i=>this.getReposBase(i,e)))).reduce((i,a)=>({data:[...i.data,...a.data],errors:[...i.errors,...a.errors]}),{data:[],errors:[]})}async getReposForCurrentUser(s,e={}){var o,i,a,u,l;let t=await w(this.config,{query:`
866
866
  query getReposForCurrentUser($after: String) {
867
867
  projects(membership: true first: 100 after: $after) {
868
868
  pageInfo {
@@ -874,7 +874,7 @@ query getReposForCurrentUser($after: String) {
874
874
  }
875
875
  }
876
876
  }
877
- `,variables:{after:s.cursor}},e);if(!((o=t.body.data)!=null&&o.projects))throw new Error(ve(t.body.errors)||t.statusText||"Unknown error");let n=((a=(i=t.body.data)==null?void 0:i.projects)==null?void 0:a.nodes)||[];return{pageInfo:(l=(u=t.body.data)==null?void 0:u.projects)==null?void 0:l.pageInfo,data:n.map(rt)}}async getRefs(s,e,t={}){var u;let n=z(e.repo),o=new URL(`${Se(this.config,t)}/projects/${encodeURIComponent(n)}/repository/${s}`);o.searchParams.set("page",((u=e.page)==null?void 0:u.toString())||"1"),o.searchParams.set("per_page",C.toString());let i=await this.config.request({url:o.toString(),headers:I(t.token||this.config.token)}),a=i.headers["x-next-page"];return{pageInfo:{hasNextPage:!!a,nextPage:a?parseInt(a,10):null},data:i.body.map(l=>({name:l.name,commit:{oid:l.commit.id,authoredDate:new Date(l.commit.authored_date),committedDate:new Date(l.commit.committed_date)}}))}}async getBranches(s,e={}){return this.getRefs("branches",s,e)}async getTags(s,e={}){return this.getRefs("tags",s,e)}async getBlame(s,e={}){let t=z(s.repo),n=new URL(`${Se(this.config,e)}/projects/${encodeURIComponent(t)}/repository/files/${encodeURIComponent(s.path)}/blame`);n.searchParams.set("ref",s.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(s,e={}){var a,u,l,p;let t="";(a=s.repo)!=null&&a.id?t=`projectId:"${s.repo.id}"`:(u=s.repo)!=null&&u.namespace&&((l=s.repo)!=null&&l.name)&&(t=`projectPath:"${s.repo.namespace}/${s.repo.name}"`);let n=jr[s.association],o=await w(this.config,{query:`
877
+ `,variables:{after:s.cursor}},e);if(!((o=t.body.data)!=null&&o.projects))throw new Error(Ee(t.body.errors)||t.statusText||"Unknown error");let n=((a=(i=t.body.data)==null?void 0:i.projects)==null?void 0:a.nodes)||[];return{pageInfo:(l=(u=t.body.data)==null?void 0:u.projects)==null?void 0:l.pageInfo,data:n.map(rt)}}async getRefs(s,e,t={}){var u;let n=z(e.repo),o=new URL(`${ve(this.config,t)}/projects/${encodeURIComponent(n)}/repository/${s}`);o.searchParams.set("page",((u=e.page)==null?void 0:u.toString())||"1"),o.searchParams.set("per_page",C.toString());let i=await this.config.request({url:o.toString(),headers:I(t.token||this.config.token)}),a=i.headers["x-next-page"];return{pageInfo:{hasNextPage:!!a,nextPage:a?parseInt(a,10):null},data:i.body.map(l=>({name:l.name,commit:{oid:l.commit.id,authoredDate:new Date(l.commit.authored_date),committedDate:new Date(l.commit.committed_date)}}))}}async getBranches(s,e={}){return this.getRefs("branches",s,e)}async getTags(s,e={}){return this.getRefs("tags",s,e)}async getBlame(s,e={}){let t=z(s.repo),n=new URL(`${ve(this.config,e)}/projects/${encodeURIComponent(t)}/repository/files/${encodeURIComponent(s.path)}/blame`);n.searchParams.set("ref",s.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(s,e={}){var a,u,l,p;let t="";(a=s.repo)!=null&&a.id?t=`projectId:"${s.repo.id}"`:(u=s.repo)!=null&&u.namespace&&((l=s.repo)!=null&&l.name)&&(t=`projectPath:"${s.repo.namespace}/${s.repo.name}"`);let n=jr[s.association],o=await w(this.config,{query:`
878
878
  query getPullRequestsForUser($username: String! $cursor: String $labelNames: [String!]) {
879
879
  user(username: $username) {
880
880
  ${n}(state:opened first:100 after:$cursor labels: $labelNames${t?` ${t}`:""}) {
@@ -888,7 +888,7 @@ query getPullRequestsForUser($username: String! $cursor: String $labelNames: [St
888
888
  }
889
889
  }
890
890
  }
891
- `,variables:{username:s.username,cursor:s.cursor,labelNames:s.labelNames}},e);if(!o.body.data)throw new Error(ve(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:((p=i.nodes)==null?void 0:p.filter(d=>s.includeFromArchivedRepos||!d.project.archived).map(d=>Nt(d,xt(d.project),xt(d.sourceProject),this.getIsSelfHosted(e),this.config.baseUrl??e.baseUrl)))||[]}}async getPullRequestsAssociatedWithUser(s,e={}){var D,ue;let[t,n,o]=((D=s.cursor)==null?void 0:D.split(";"))||[void 0,void 0,void 0],i=(t==null?void 0:t.split("-"))||[],a=(n==null?void 0:n.split("-"))||[],u=(o==null?void 0:o.split("-"))||[],l=[],p=[],d=[],c=0;do{let q=s.repos&&s.repos[c];i[c]==="null"?l.push(null):l.push(this.getPullRequestsForUser({username:s.username,association:"authored",cursor:i[c],includeFromArchivedRepos:s.includeFromArchivedRepos,labelNames:s.labelNames,...q&&{repo:q}},e)),a[c]==="null"?p.push(null):p.push(this.getPullRequestsForUser({username:s.username,association:"assigned",cursor:a[c],includeFromArchivedRepos:s.includeFromArchivedRepos,labelNames:s.labelNames,...q&&{repo:q}},e)),u[c]==="null"?d.push(null):d.push(this.getPullRequestsForUser({username:s.username,association:"reviewRequested",cursor:u[c],includeFromArchivedRepos:s.includeFromArchivedRepos,labelNames:s.labelNames,...q&&{repo:q}},e)),c++}while(c<(((ue=s.repos)==null?void 0:ue.length)||0));let g=[l,p,d].flat(),m=await Promise.all(g),R={},h=[],P=q=>{R[q.id]||(R[q.id]=!0,h.push(q))},f=!1,T=m.map((q,gt)=>{var mt;let ie="";return q&&q.data.forEach(P),q!=null&&q.pageInfo.hasNextPage?(f=!0,ie+=`${q.pageInfo.endCursor||"null"}`):ie+="null",(mt=s.repos)!=null&&mt.length&&(gt+1)%s.repos.length!==0?ie+="-":gt+1<m.length&&(ie+=";"),ie}).join("");return{pageInfo:{hasNextPage:f,endCursor:T},data:h}}getVariablesForPullRequests(s){let{updatedBefore:e,isDraft:t,authorLogin:n,assigneeLogins:o,labelNames:i,reviewRequestedLogin:a}=s||{},u={},l=[],p=[],d=(c,g,m)=>{l.push(`$${c}: ${m}`),p.push(`${c}: $${c}`),u[c]=g};return e&&d("updatedBefore",e,"Time"),n&&d("authorUsername",n,"String"),o&&d("assigneeUsername",o[0],"String"),i&&d("labelName",i,"[String]"),t!=null&&d("draft",t,"Boolean"),a&&d("reviewerUsername",a,"String"),{variables:u,variableTypes:l,mergeRequestArguments:p}}async getPullRequestsForRepoBase(s,e={},t){var h,P,f;let{cursor:n,repo:o}=s||{},i=z(o),{variables:a,variableTypes:u,mergeRequestArguments:l}=this.getVariablesForPullRequests(s),p={fullPath:i,...a},d=await w(this.config,{query:`
891
+ `,variables:{username:s.username,cursor:s.cursor,labelNames:s.labelNames}},e);if(!o.body.data)throw new Error(Ee(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:((p=i.nodes)==null?void 0:p.filter(d=>s.includeFromArchivedRepos||!d.project.archived).map(d=>Nt(d,xt(d.project),xt(d.sourceProject),this.getIsSelfHosted(e),this.config.baseUrl??e.baseUrl)))||[]}}async getPullRequestsAssociatedWithUser(s,e={}){var D,ue;let[t,n,o]=((D=s.cursor)==null?void 0:D.split(";"))||[void 0,void 0,void 0],i=(t==null?void 0:t.split("-"))||[],a=(n==null?void 0:n.split("-"))||[],u=(o==null?void 0:o.split("-"))||[],l=[],p=[],d=[],c=0;do{let q=s.repos&&s.repos[c];i[c]==="null"?l.push(null):l.push(this.getPullRequestsForUser({username:s.username,association:"authored",cursor:i[c],includeFromArchivedRepos:s.includeFromArchivedRepos,labelNames:s.labelNames,...q&&{repo:q}},e)),a[c]==="null"?p.push(null):p.push(this.getPullRequestsForUser({username:s.username,association:"assigned",cursor:a[c],includeFromArchivedRepos:s.includeFromArchivedRepos,labelNames:s.labelNames,...q&&{repo:q}},e)),u[c]==="null"?d.push(null):d.push(this.getPullRequestsForUser({username:s.username,association:"reviewRequested",cursor:u[c],includeFromArchivedRepos:s.includeFromArchivedRepos,labelNames:s.labelNames,...q&&{repo:q}},e)),c++}while(c<(((ue=s.repos)==null?void 0:ue.length)||0));let g=[l,p,d].flat(),m=await Promise.all(g),R={},h=[],P=q=>{R[q.id]||(R[q.id]=!0,h.push(q))},f=!1,T=m.map((q,gt)=>{var mt;let ie="";return q&&q.data.forEach(P),q!=null&&q.pageInfo.hasNextPage?(f=!0,ie+=`${q.pageInfo.endCursor||"null"}`):ie+="null",(mt=s.repos)!=null&&mt.length&&(gt+1)%s.repos.length!==0?ie+="-":gt+1<m.length&&(ie+=";"),ie}).join("");return{pageInfo:{hasNextPage:f,endCursor:T},data:h}}getVariablesForPullRequests(s){let{updatedBefore:e,isDraft:t,authorLogin:n,assigneeLogins:o,labelNames:i,reviewRequestedLogin:a}=s||{},u={},l=[],p=[],d=(c,g,m)=>{l.push(`$${c}: ${m}`),p.push(`${c}: $${c}`),u[c]=g};return e&&d("updatedBefore",e,"Time"),n&&d("authorUsername",n,"String"),o&&d("assigneeUsername",o[0],"String"),i&&d("labelName",i,"[String]"),t!=null&&d("draft",t,"Boolean"),a&&d("reviewerUsername",a,"String"),{variables:u,variableTypes:l,mergeRequestArguments:p}}async getPullRequestsForRepoBase(s,e={},t){var h,P,f;let{cursor:n,repo:o}=s||{},i=z(o),{variables:a,variableTypes:u,mergeRequestArguments:l}=this.getVariablesForPullRequests(s),p={fullPath:i,...a},d=await w(this.config,{query:`
892
892
  query getPullRequestsForRepo(
893
893
  $fullPath: ID!
894
894
  $after: String
@@ -918,7 +918,7 @@ query getPullRequestsForRepo(
918
918
  }
919
919
  }
920
920
  }
921
- `,variables:{...p,after:n}},e),c=[],g=(h=d.body.data)==null?void 0:h.project;if(!t&&(g!=null&&g.archived))return{pageInfo:null,data:[]};let m=Ee(g||{id:"",fullPath:"",webUrl:""});return(((P=g==null?void 0:g.mergeRequests)==null?void 0:P.nodes)||[]).forEach(E=>{c.push(Nt(E,m,null,this.getIsSelfHosted(e),this.config.baseUrl??e.baseUrl))}),{pageInfo:(f=g==null?void 0:g.mergeRequests)==null?void 0:f.pageInfo,data:c}}async getPullRequestsForRepo(s,e={}){return this.getPullRequestsForRepoBase(s,e,!1)}async getPullRequestsForRepos(s,e={}){let{repos:t,assigneeLogins:n,updatedBefore:o,authorLogin:i,labelNames:a,isDraft:u,reviewRequestedLogin:l}=s;return{data:(await Promise.all(t.map(d=>this.getPullRequestsForRepoBase({repo:d,assigneeLogins:n,updatedBefore:o,authorLogin:i,labelNames:a,isDraft:u,reviewRequestedLogin:l},e,s.includeFromArchivedRepos??!1)))).flatMap(d=>d.data)}}async closePullRequest(s,e={}){var a,u,l;let{pullRequest:t}=s,n=`mutation ClosePullRequest($fullPath: ID!, $pullRequestId: String!) {
921
+ `,variables:{...p,after:n}},e),c=[],g=(h=d.body.data)==null?void 0:h.project;if(!t&&(g!=null&&g.archived))return{pageInfo:null,data:[]};let m=qe(g||{id:"",fullPath:"",webUrl:""});return(((P=g==null?void 0:g.mergeRequests)==null?void 0:P.nodes)||[]).forEach(E=>{c.push(Nt(E,m,null,this.getIsSelfHosted(e),this.config.baseUrl??e.baseUrl))}),{pageInfo:(f=g==null?void 0:g.mergeRequests)==null?void 0:f.pageInfo,data:c}}async getPullRequestsForRepo(s,e={}){return this.getPullRequestsForRepoBase(s,e,!1)}async getPullRequestsForRepos(s,e={}){let{repos:t,assigneeLogins:n,updatedBefore:o,authorLogin:i,labelNames:a,isDraft:u,reviewRequestedLogin:l}=s;return{data:(await Promise.all(t.map(d=>this.getPullRequestsForRepoBase({repo:d,assigneeLogins:n,updatedBefore:o,authorLogin:i,labelNames:a,isDraft:u,reviewRequestedLogin:l},e,s.includeFromArchivedRepos??!1)))).flatMap(d=>d.data)}}async closePullRequest(s,e={}){var a,u,l;let{pullRequest:t}=s,n=`mutation ClosePullRequest($fullPath: ID!, $pullRequestId: String!) {
922
922
  mergeRequestUpdate(input: { projectPath: $fullPath, iid: $pullRequestId, state: CLOSED }) {
923
923
  errors,
924
924
  mergeRequest {
@@ -994,7 +994,7 @@ query GetSingleIssue($projectId: ID!, $issueNumber: String!) {
994
994
  }
995
995
  }
996
996
  }
997
- `,variables:{issueNumber:s.number,projectId:t}},e);if(!((o=n.body.data)!=null&&o.project))throw new Error(`Repository ${t} not found`);if(!((a=(i=n.body.data)==null?void 0:i.project)!=null&&a.issue))throw new Error(`Issue ${s.number} not found`);return{data:st(n.body.data.project.issue,Ee(n.body.data.project),this.getIsSelfHosted(e),this.config.baseUrl??e.baseUrl)}}getVariablesForIssues(s){let{updatedBefore:e,authorLogin:t,assigneeLogins:n,labelNames:o}=s||{},i={},a=[],u=[],l=(p,d,c)=>{a.push(`$${p}: ${c}`),u.push(`${p}: $${p}`),i[p]=d};return e&&l("updatedBefore",e,"Time"),t&&l("authorUsername",t,"String"),n&&l("assigneeUsername",n[0],"String"),o&&l("labelName",o,"[String]"),{variables:i,variableTypes:a,issueArguments:u}}async getIssuesForRepo(s,e={}){var h,P,f;let{cursor:t,repo:n}=s||{},o=z(n),{variables:i,variableTypes:a,issueArguments:u}=this.getVariablesForIssues(s),l={fullPath:o,...i},p=`
997
+ `,variables:{issueNumber:s.number,projectId:t}},e);if(!((o=n.body.data)!=null&&o.project))throw new Error(`Repository ${t} not found`);if(!((a=(i=n.body.data)==null?void 0:i.project)!=null&&a.issue))throw new Error(`Issue ${s.number} not found`);return{data:st(n.body.data.project.issue,qe(n.body.data.project),this.getIsSelfHosted(e),this.config.baseUrl??e.baseUrl)}}getVariablesForIssues(s){let{updatedBefore:e,authorLogin:t,assigneeLogins:n,labelNames:o}=s||{},i={},a=[],u=[],l=(p,d,c)=>{a.push(`$${p}: ${c}`),u.push(`${p}: $${p}`),i[p]=d};return e&&l("updatedBefore",e,"Time"),t&&l("authorUsername",t,"String"),n&&l("assigneeUsername",n[0],"String"),o&&l("labelName",o,"[String]"),{variables:i,variableTypes:a,issueArguments:u}}async getIssuesForRepo(s,e={}){var h,P,f;let{cursor:t,repo:n}=s||{},o=z(n),{variables:i,variableTypes:a,issueArguments:u}=this.getVariablesForIssues(s),l={fullPath:o,...i},p=`
998
998
  query GetIssuesFromProject(
999
999
  $fullPath: ID!
1000
1000
  $after: String
@@ -1022,7 +1022,7 @@ query GetSingleIssue($projectId: ID!, $issueNumber: String!) {
1022
1022
  }
1023
1023
  }
1024
1024
  }
1025
- }`,d=await w(this.config,{query:p,variables:{...l,after:t}},e),c=[],g=(h=d.body.data)==null?void 0:h.project,m=Ee(g||{id:"",fullPath:"",webUrl:""});return(((P=g==null?void 0:g.issues)==null?void 0:P.nodes)||[]).forEach(E=>{c.push(st(E,m,this.getIsSelfHosted(e),this.config.baseUrl??e.baseUrl))}),{pageInfo:((f=g==null?void 0:g.issues)==null?void 0:f.pageInfo)??{endCursor:null,hasNextPage:!1},data:c.sort((E,T)=>(E.updatedDate||E.createdDate).getTime()-(T.updatedDate||T.createdDate).getTime())}}async getIssuesForRepos(s,e={}){var g,m,R,h,P;let{cursor:t}=s||{},n=s.repoIds.map(f=>f.toString().startsWith(te)?f:`${te}${f}`),{variables:o,variableTypes:i,mergeRequestArguments:a}=this.getVariablesForPullRequests(s),u={projectIds:n,...o},l=`
1025
+ }`,d=await w(this.config,{query:p,variables:{...l,after:t}},e),c=[],g=(h=d.body.data)==null?void 0:h.project,m=qe(g||{id:"",fullPath:"",webUrl:""});return(((P=g==null?void 0:g.issues)==null?void 0:P.nodes)||[]).forEach(E=>{c.push(st(E,m,this.getIsSelfHosted(e),this.config.baseUrl??e.baseUrl))}),{pageInfo:((f=g==null?void 0:g.issues)==null?void 0:f.pageInfo)??{endCursor:null,hasNextPage:!1},data:c.sort((E,T)=>(E.updatedDate||E.createdDate).getTime()-(T.updatedDate||T.createdDate).getTime())}}async getIssuesForRepos(s,e={}){var g,m,R,h,P;let{cursor:t}=s||{},n=s.repoIds.map(f=>f.toString().startsWith(te)?f:`${te}${f}`),{variables:o,variableTypes:i,mergeRequestArguments:a}=this.getVariablesForPullRequests(s),u={projectIds:n,...o},l=`
1026
1026
  query GetIssuesFromProject(
1027
1027
  $projectIds: [ID!]
1028
1028
  $after: String
@@ -1053,7 +1053,7 @@ query GetSingleIssue($projectId: ID!, $issueNumber: String!) {
1053
1053
  }
1054
1054
  }
1055
1055
  }
1056
- }`,p=await w(this.config,{query:l,variables:{...u,after:t}},e),d=[];return(((m=(g=p.body.data)==null?void 0:g.projects)==null?void 0:m.nodes)||[]).forEach(f=>{var D;if(!s.includeFromArchivedRepos&&f.archived)return;let E=Ee(f);(((D=f.issues)==null?void 0:D.nodes)||[]).forEach(ue=>d.push(st(ue,E,this.getIsSelfHosted(e),this.config.baseUrl??e.baseUrl)))}),{pageInfo:((P=(h=(R=p.body)==null?void 0:R.data)==null?void 0:h.projects)==null?void 0:P.pageInfo)??{endCursor:null,hasNextPage:!1},data:d.sort((f,E)=>(f.updatedDate||f.createdDate).getTime()-(E.updatedDate||E.createdDate).getTime())}}async setIssueState(s,e={}){var a,u,l;let{issue:t,state:n}=s;if(!t.repository)throw new Error('GitLab requires "repository" for this function.');let o=`mutation SetIssueState($fullPath: ID!, $issueId: String!, $status: IssueStateEvent!) {
1056
+ }`,p=await w(this.config,{query:l,variables:{...u,after:t}},e),d=[];return(((m=(g=p.body.data)==null?void 0:g.projects)==null?void 0:m.nodes)||[]).forEach(f=>{var D;if(!s.includeFromArchivedRepos&&f.archived)return;let E=qe(f);(((D=f.issues)==null?void 0:D.nodes)||[]).forEach(ue=>d.push(st(ue,E,this.getIsSelfHosted(e),this.config.baseUrl??e.baseUrl)))}),{pageInfo:((P=(h=(R=p.body)==null?void 0:R.data)==null?void 0:h.projects)==null?void 0:P.pageInfo)??{endCursor:null,hasNextPage:!1},data:d.sort((f,E)=>(f.updatedDate||f.createdDate).getTime()-(E.updatedDate||E.createdDate).getTime())}}async setIssueState(s,e={}){var a,u,l;let{issue:t,state:n}=s;if(!t.repository)throw new Error('GitLab requires "repository" for this function.');let o=`mutation SetIssueState($fullPath: ID!, $issueId: String!, $status: IssueStateEvent!) {
1057
1057
  updateIssue(input: { projectPath: $fullPath, iid: $issueId, stateEvent: $status }) {
1058
1058
  issue {
1059
1059
  id
@@ -1121,5 +1121,5 @@ query getLabelsForRepo(
1121
1121
  }
1122
1122
  }
1123
1123
  }
1124
- `,variables:{fullPath:`${t}/${n}`,after:o}},e);return{pageInfo:((l=(u=(a=i.body.data)==null?void 0:a.project)==null?void 0:u.labels)==null?void 0:l.pageInfo)??{endCursor:null,hasNextPage:!1},data:((g=(c=(d=(p=i.body.data)==null?void 0:p.project)==null?void 0:d.labels)==null?void 0:c.nodes)==null?void 0:g.map(ut))??[]}}async getTreeForRepo(s,e={}){let t=z(s.repo),n=new URL(s.cursor??`${Se(this.config,e)}/projects/${encodeURIComponent(t)}/repository/tree`);n.searchParams.set("per_page","10000"),n.searchParams.set("recursive","true"),n.searchParams.set("pagination","keyset"),n.searchParams.set("ref",s.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(es),pageInfo:{endCursor:i?i.substring(1,i.indexOf(">")):null,hasNextPage:!!i}}}};var ns="https://api.atlassian.com/ex/jira",qe=100,pt=["assignee","comment","summary","created","creator","updated","votes","issuetype","status","labels","components","project","fixVersions","description"],_t="/rest/api/2/search/jql",Qt="/rest/api/2/search",dt=(r,s,e,t)=>{var a,u,l,p;let n=r.fields.assignee,o=!t,i=(r.fields[(s==null?void 0:s.Sprint)??""]??[]).filter(d=>typeof d=="object");return{id:r.id,commentCount:r.fields.comment.comments.length,number:r.key,title:r.fields.summary,url:e?`${e}/browse/${r.key}`:null,closedDate:null,createdDate:new Date(r.fields.created),author:Ce(r.fields.creator,e,o),updatedDate:new Date(r.fields.updated),assignees:n?[Ce(n,e,o)]:[],description:r.fields.description,repository:null,project:{name:r.fields.project.name,resourceId:t??null,key:r.fields.project.key,namespace:null,id:r.fields.project.id},state:us(r.fields.status),statusTransitions:((a=r.transitions)==null?void 0:a.map(os))??[],components:((u=r.fields.components)==null?void 0:u.map(is))??[],type:r.fields.issuetype.name,upvoteCount:((l=r.fields.votes)==null?void 0:l.votes)||0,labels:((p=r.fields.labels)==null?void 0:p.map(d=>({color:null,description:null,id:null,name:d})))??[],sprints:i.map(ls),fixVersions:r.fields.fixVersions.map(ps)}},os=r=>{let s;switch(r.to.statusCategory.name){case"To Do":s="TO_DO";break;case"In Progress":s="IN_PROGRESS";break;default:s="DONE";break}return{name:r.name,id:r.id,to:{id:r.to.id,name:r.to.name,color:r.to.statusCategory.colorName,category:s}}},is=r=>({description:r.description??null,id:r.id,name:r.name}),as=(r,s,e)=>e&&r.name?`${s}/secure/ViewProfile.jspa?name=${encodeURIComponent(r.name)}`:`${s}/jira/people/${r.accountId}`,Ce=(r,s,e)=>({id:(e?r.key:r.accountId)??"",name:r.displayName,email:r.emailAddress,avatarUrl:r.avatarUrls["48x48"],username:r.displayName,url:as(r,s,e)}),us=r=>{let s;switch(r.statusCategory.name){case"To Do":s="TO_DO";break;case"In Progress":s="IN_PROGRESS";break;default:s="DONE";break}return{id:r.id,name:r.name,color:r.statusCategory.colorName,category:s}},ls=r=>({id:r.id.toString(),name:r.name,isActive:r.state==="active",startDate:r.startDate?new Date(r.startDate):null,endDate:r.endDate?new Date(r.endDate):null,completedDate:r.completeDate?new Date(r.completeDate):null}),ps=r=>({id:r.id,description:r.description,name:r.name,archived:r.archived,released:r.released,releaseDate:r.releaseDate?new Date(r.releaseDate):null}),W=(r,s,e)=>e?`${s.baseUrl||ns}/${e}`:`${(s==null?void 0:s.baseUrl)||r.baseUrl}`,De=async(r,s,e={})=>{let{resourceId:t}=s;return(await r.request({url:`${W(r,e,t)}/rest/api/2/field`,headers:I(e.token||r.token)})).body},Le=async(r,s,e,t={})=>{let{number:n,resourceId:o,fields:i}=s||{},a=await r.request({url:`${W(r,t,o)}/rest/api/2/issue/${n}?fields=${pt.join(",")}&expand=transitions`,headers:I(t.token||r.token)});return{data:dt(a.body,i,e,o)}},Ue=async(r,s,e,t={})=>{let{cursor:n,resourceId:o,labelNames:i,fields:a}=s||{},u=["statusCategory != Done",`(creator = currentUser() OR assignee = currentUser()
1125
- OR comment ~ currentUser() OR summary ~ currentUser() OR description ~ currentUser())`];i&&i.forEach(P=>u.push(`labels = "${P}"`));let l=`${u.join(" AND ")} ORDER BY updated DESC`,p=!o,d=p?Qt:_t,c=new URL(`${W(r,t,o)}${d}`);c.searchParams.set("jql",l),c.searchParams.set("maxResults",qe.toString()),c.searchParams.set("fields",pt.join(",")),c.searchParams.set("expand","transitions"),n&&(p?c.searchParams.set("startAt",n):c.searchParams.set("nextPageToken",n));let g=await r.request({url:c.toString(),headers:I(t.token||r.token)}),m=g.body.issues.map(P=>dt(P,a,e,o)),R=!1,h="";return p?(R=m.length==qe,h=(parseInt(n??"0",10)+m.length).toString()):(R=!!g.body.nextPageToken,h=g.body.nextPageToken??null),{data:m,pageInfo:{hasNextPage:R,endCursor:h}}},Bt=async(r,s,e,t={})=>{let{cursor:n,resourceId:o,jql:i,fields:a}=s||{},u=[...pt],l=a==null?void 0:a.Sprint;l&&u.push(l);let p=!o,d=p?Qt:_t,c=new URL(`${W(r,t,o)}${d}`);c.searchParams.set("jql",i.join(" AND ")),c.searchParams.set("maxResults",qe.toString()),c.searchParams.set("fields",u.join(",")),c.searchParams.set("expand","transitions"),n&&(p?c.searchParams.set("startAt",n):c.searchParams.set("nextPageToken",n));let g=await r.request({url:c.toString(),headers:I(t.token||r.token)}),m=g.body.issues.map(P=>dt(P,a,e,o)),R=!1,h="";return p?(R=m.length==qe,h=(parseInt(n??"0",10)+m.length).toString()):(R=!!g.body.nextPageToken,h=g.body.nextPageToken??null),{data:m,pageInfo:{hasNextPage:R,endCursor:h}}},$e=async(r,s,e,t={})=>{let{assigneeLogins:n,authorLogin:o,mentionLogin:i,labelNames:a,cursor:u,projectKey:l,resourceId:p,fields:d}=s||{},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}"`)),Bt(r,{resourceId:p,jql:c,cursor:u,fields:d},e,t)},Ae=async(r,s,e,t={})=>{let{assigneeLogins:n,authorLogin:o,mentionLogin:i,labelNames:a,cursor:u,projectKeys:l,resourceId:p,fields:d}=s||{},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}"`)),Bt(r,{resourceId:p,jql:g,fields:d,cursor:u},e,t)},Ge=async(r,s,e={})=>{let{issue:t,labels:n}=s;if(!t.project)throw new Error('Jira requires a "project" for this function.');let o={fields:{labels:n.map(i=>i.name)}};await r.request({method:"PUT",url:`${W(r,e,t.project.resourceId??void 0)}/rest/api/2/issue/${t.id}`,body:JSON.stringify(o),headers:{...I(e.token||r.token),"Content-Type":"application/json"}})},Te=async(r,s,e={})=>{let{issue:t,components:n}=s;if(!t.project)throw new Error('Jira requires a "project" for this function.');let o={fields:{components:n.map(i=>({id:i.id}))}};await r.request({method:"PUT",url:`${W(r,e,t.project.resourceId??void 0)}/rest/api/2/issue/${t.id}`,body:JSON.stringify(o),headers:{...I(e.token||r.token),"Content-Type":"application/json"}})},Oe=async(r,s,e={})=>{let{issue:t,status:n}=s;if(!t.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 r.request({method:"POST",url:`${W(r,e,t.project.resourceId??void 0)}/rest/api/2/issue/${t.id}/transitions`,body:JSON.stringify(o),headers:{...I(e.token||r.token),"Content-Type":"application/json"}})},xe=async(r,s,e={})=>{let{resourceId:t,projectIdOrKey:n}=s,o=new URL(`${W(r,e,t)}/rest/api/2/project/${n}/components`);return{data:(await r.request({url:o.toString(),headers:I(e.token||r.token)})).body}};var ae="https://api.atlassian.com/ex/jira",ct=100,se=class extends N{constructor(){super(...arguments);this._resourceUrlCache={};this._issueFieldsCache={}}async getIssueFieldsForResource(e,t={}){if(!this._issueFieldsCache[e.resourceId]){let n=await De(this.config,e,t);this._issueFieldsCache[e.resourceId]=n.reduce((o,i)=>({...o,[i.name]:i.id}),{})}return this._issueFieldsCache[e.resourceId]??null}async getResourceUrl(e,t={}){var i;let n=t.token||this.config.token;if(!n)return null;let o=this._resourceUrlCache[n];return o?o[e.resourceId]??null:(await this.getJiraResourcesForCurrentUser(t),((i=this._resourceUrlCache[n])==null?void 0:i[e.resourceId])??null)}async getCurrentUserForResource(e,t={}){let n=await this.getResourceUrl({resourceId:e.resourceId},t),o=await this.config.request({url:`${t.baseUrl||ae}/${e.resourceId}/rest/api/2/myself`,headers:I(t.token||this.config.token)});return{data:{name:o.body.displayName,email:o.body.emailAddress,avatarUrl:o.body.avatarUrls["48x48"],id:o.body.accountId,username:o.body.displayName,url:n?`${n}/jira/people/${o.body.accountId}`:null}}}async getJiraResourcesForCurrentUser(e={}){let t=await this.config.request({url:`${e.baseUrl||"https://api.atlassian.com/"}/oauth/token/accessible-resources`,headers:I(e.token||this.config.token)}),n=e.token||this.config.token,o=n?this._resourceUrlCache[n]||{}:void 0,i=t.body.map(a=>(o&&(o[a.id]=a.url),{avatarUrl:a.avatarUrl,id:a.id,name:a.name,url:a.url}));return n&&(this._resourceUrlCache[n]=o),{data:i}}async getJiraProjectsForResource(e,t={}){let n=new URL(`${t.baseUrl||ae}/${e.resourceId}/rest/api/2/project/search`);n.searchParams.set("maxResults",ct.toString()),e.cursor&&n.searchParams.set("startAt",e.cursor);let o=await this.config.request({url:n.toString(),headers:I(t.token||this.config.token)});return{pageInfo:{hasNextPage:o.body.values.length!==0,endCursor:(o.body.startAt+o.body.values.length).toString()},data:o.body.values.map(i=>({id:i.id,key:i.key,name:i.name,resourceId:e.resourceId}))}}async getJiraProjectsForResources(e,t={}){let n=[];return await Promise.all(e.resourceIds.map(async o=>{try{return await Pt(i=>this.getJiraProjectsForResource({resourceId:o,cursor:i},t))}catch{return[]}})).then((...o)=>{o.forEach(i=>{n=n.concat(...i)})}),{data:n}}async getAccountsForJiraProject(e,t={}){let{resourceId:n,projectKey:o,cursor:i}=e,a=await this.getResourceUrl({resourceId:n},t),u=new URL(`${t.baseUrl||ae}/${n}/rest/api/2/user/assignable/search`);u.searchParams.set("maxResults",ct.toString()),i&&u.searchParams.set("startAt",i),u.searchParams.set("project",o);let l=await this.config.request({url:u.toString(),headers:I(t.token||this.config.token)});return{pageInfo:{hasNextPage:l.body.length!==0,endCursor:((i?parseInt(i):0)+l.body.length).toString()},data:l.body.filter(p=>p.accountType!=="app"&&p.active).map(p=>Ce(p,a,!1))}}async getComponentsForJiraProject(e,t={}){return await xe(this.config,e,t)}async getIssue(e,t={}){let n=await this.getIssueFieldsForResource({resourceId:e.resourceId},t),o=await this.getResourceUrl({resourceId:e.resourceId},t);return await Le(this.config,{...e,fields:n},o,t)}async getIssuesForProject(e,t={}){let n=await this.getIssueFieldsForResource({resourceId:e.resourceId},t),o=await this.getResourceUrl({resourceId:e.resourceId},t);return await $e(this.config,{...e,fields:n},o,t)}async getIssuesForProjects(e,t={}){let n=await this.getIssueFieldsForResource({resourceId:e.resourceId},t),o=await this.getResourceUrl({resourceId:e.resourceId},t);return await Ae(this.config,{...e,fields:n},o,t)}async getIssuesForResourceForCurrentUser(e,t={}){let n=await this.getIssueFieldsForResource({resourceId:e.resourceId},t),o=await this.getResourceUrl({resourceId:e.resourceId},t);return await Ue(this.config,{...e,fields:n},o,t)}async setIssueStatus(e,t={}){await Oe(this.config,e,t)}async setIssueAssignee(e,t={}){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==null?void 0:o.id};await this.config.request({method:"PUT",url:`${t.baseUrl||ae}/${n.project.resourceId}/rest/api/2/issue/${n.id}/assignee`,body:JSON.stringify(i),headers:{...I(t.token||this.config.token),"Content-Type":"application/json"}})}async setIssueComponents(e,t={}){await Te(this.config,e,t)}async setIssueLabels(e,t={}){await Ge(this.config,e,t)}async getLabelsForResource(e,t={}){let{resourceId:n,cursor:o}=e,i=new URL(`${t.baseUrl||ae}/${n}/rest/api/2/label`);i.searchParams.set("maxResults",ct.toString()),o&&i.searchParams.set("startAt",o);let a=await this.config.request({url:i.toString(),headers:I(t.token||this.config.token)});return{pageInfo:{hasNextPage:!a.body.isLast,endCursor:(a.body.startAt+a.body.values.length).toString()},data:a.body.values.map(u=>({color:null,description:null,id:null,name:u}))}}};var ne=class extends A{constructor(){super(...arguments);this._issueFieldsCache={}}async getIssueFieldsForResource(e={}){let t=(e==null?void 0:e.baseUrl)||this.config.baseUrl||"";if(!this._issueFieldsCache[t]){let n=await De(this.config,{},e);this._issueFieldsCache[t]=n.reduce((o,i)=>({...o,[i.name]:i.id}),{})}return this._issueFieldsCache[t]??null}async getCurrentUser(e={}){let t=await this.config.request({url:`${(e==null?void 0:e.baseUrl)||this.config.baseUrl}/rest/api/2/myself`,headers:I((e==null?void 0:e.token)||this.config.token)});return{data:{name:t.body.displayName,email:t.body.emailAddress,avatarUrl:t.body.avatarUrls["48x48"],id:t.body.key,username:t.body.displayName,url:null}}}async getJiraProjects(e={}){return{data:(await this.config.request({url:`${(e==null?void 0:e.baseUrl)||this.config.baseUrl}/rest/api/2/project`,headers:I((e==null?void 0:e.token)||this.config.token)})).body.map(n=>({id:n.id,name:n.name}))}}async getIssue(e,t={}){let n=e.resourceUrl||t.baseUrl||this.config.baseUrl;if(!n)throw new Error('Jira Server requires a "resourceUrl" or "baseUrl" for this function.');let o=await this.getIssueFieldsForResource(t);return await Le(this.config,{...e,fields:o},n,t)}async getIssuesForProject(e,t={}){let n=e.resourceUrl||t.baseUrl||this.config.baseUrl;if(!n)throw new Error('Jira Server requires a "resourceUrl" or "baseUrl" for this function.');let o=await this.getIssueFieldsForResource(t);return await $e(this.config,{...e,fields:o},n,t)}async getIssuesForProjects(e,t={}){let n=e.resourceUrl||t.baseUrl||this.config.baseUrl;if(!n)throw new Error('Jira Server requires a "resourceUrl" or "baseUrl" for this function.');let o=await this.getIssueFieldsForResource(t);return await Ae(this.config,{...e,fields:o},n,t)}async getIssuesForResourceForCurrentUser(e,t={}){let n=e.resourceUrl||t.baseUrl||this.config.baseUrl;if(!n)throw new Error('Jira Server requires a "resourceUrl" or "baseUrl" for this function.');let o=await this.getIssueFieldsForResource(t);return await Ue(this.config,{...e,fields:o},n,t)}async setIssueStatus(e,t={}){await Oe(this.config,e,t)}async setIssueLabels(e,t={}){await Ge(this.config,e,t)}async setIssueComponents(e,t={}){await Te(this.config,e,t)}async getLabels(e={}){return{data:(await this.config.request({url:`${(e==null?void 0: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,t={}){return await xe(this.config,e,t)}};var k="https://api.trello.com",ds=1e3,cs=r=>({id:r.id,username:r.username,url:r.url,name:r.fullName,email:r.email,avatarUrl:r.avatarUrl}),gs=(r,s)=>{let e=new Date(1e3*parseInt(r.id.substring(0,8),16));return{id:r.id,commentCount:r.badges.comments,number:r.idShort.toString(),title:r.name,url:r.url,closedDate:null,createdDate:new Date(e.toISOString()),author:null,updatedDate:new Date(r.dateLastActivity),assignees:r.members.map(t=>({id:t.id,username:t.username,name:t.fullName,email:null,avatarUrl:t.avatarUrl,url:null})),description:null,state:s[r.idList??""]?{id:r.idList,name:s[r.idList].name,color:null}:null,type:null,repository:null,upvoteCount:r.badges.votes,labels:r.labels.map(t=>({color:t.color,description:null,id:t.id,name:t.name}))}},oe=class extends N{async getCurrentUser(s,e={}){let t=await this.config.request({url:`${e.baseUrl||k}/1/members/me?key=${s.appKey}&token=${e.token||this.config.token}`,headers:I(e.token||this.config.token)});return{data:{name:t.body.fullName,email:t.body.email,avatarUrl:t.body.avatarHash?`https://trello-members.s3.amazonaws.com/${t.body.id}/${t.body.avatarHash}/50.png`:null,id:t.body.id,username:t.body.username,url:t.body.url}}}async getBoardsForCurrentUser(s,e={}){return{data:(await this.config.request({url:`${e.baseUrl||k}/1/members/me/boards?fields=name&key=${s.appKey}&token=${e.token||this.config.token}&filter=open`,headers:I(e.token||this.config.token)})).body.map(n=>({id:n.id,name:n.name}))}}async getListsForTrelloBoard(s,e={}){let{appKey:t,boardId:n}=s;return{data:(await this.config.request({url:`${e.baseUrl||k}/1/boards/${n}/lists?key=${t}&token=${e.token||this.config.token}`,headers:I(e.token||this.config.token)})).body}}async getAccountForId(s,e={}){let{appKey:t,memberId:n}=s,o=await this.config.request({url:`${e.baseUrl||k}/1/members/${n}/?key=${t}&token=${e.token||this.config.token}`});return{data:cs(o.body)}}async getAccountsForTrelloBoard(s,e={}){let{appKey:t,boardId:n}=s;return{data:(await this.config.request({url:`${e.baseUrl||k}/1/boards/${n}/members?key=${t}&token=${e.token||this.config.token}`,headers:I(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(s,e={}){let t=["-is:archived","sort:edited"],{appKey:n,boardId:o,filterText:i,assigneeLogins:a,labelNamesOrColors:u,trelloBoardListsById:l}=s||{};a&&t.push("@me"),u&&u.forEach(c=>t.push(`label:"${c}"`));let p=`${i?`${i}`:""}${t.join(" ")} board:${o}`;return{data:(await this.config.request({url:`${e.baseUrl||k}/1/search?key=${n}&query=${p}&cards_limit=${ds}&token=${e.token||this.config.token}&card_members=true`,headers:I(e.token||this.config.token)})).body.cards.map(c=>gs(c,l||{}))}}async updateIssue(s,e,t,n){return await this.config.request({method:"PUT",url:`${n.baseUrl||k}/1/cards/${e.id}?key=${s}&token=${n.token||this.config.token}&${t}`,headers:I(n.token||this.config.token)})}async setIssueStatus(s,e={}){let{appKey:t,issue:n,status:o}=s;if(!o.id)throw new Error('Trello requires a status "id" for this function.');let i=`idList=${o.id}`;if(!(await this.updateIssue(t,n,i,e)).body.id)throw new Error("Could not set issue status")}async setIssueAssignees(s,e={}){let{appKey:t,issue:n,assignees:o}=s,i=o.map(l=>l.id),a=`idMembers=${encodeURIComponent(i.join(","))}`;if(!(await this.updateIssue(t,n,a,e)).body.id)throw new Error("Could not set issue status")}async setIssueLabels(s,e={}){let{appKey:t,issue:n,labels:o}=s,i=o.map(u=>u.id).join(",");if(!(await this.config.request({method:"PUT",url:`${e.baseUrl||k}/1/cards/${n.id}?key=${t}&token=${e.token||this.config.token}&idLabels=${encodeURIComponent(i)}`,headers:I(e.token||this.config.token)})).body.id)throw new Error("Could not set issue status")}async setIssueArchived(s,e={}){let{appKey:t,issue:n,archived:o}=s;if(!(await this.config.request({method:"PUT",url:`${e.baseUrl||k}/1/cards/${n.id}?key=${t}&token=${e.token||this.config.token}&closed=${o}`,headers:I(e.token||this.config.token)})).body.id)throw new Error("Could not update issue archived status")}async archiveIssue(s,e={}){await this.setIssueArchived({...s,archived:!0},e)}async unArchiveIssue(s,e={}){await this.setIssueArchived({...s,archived:!1},e)}async getLabelsForBoard(s,e={}){let{appKey:t,boardId:n}=s;return{data:(await this.config.request({url:`${e.baseUrl||k}/1/boards/${n}/labels?key=${t}&token=${e.token||this.config.token}`,headers:I(e.token||this.config.token)})).body.map(i=>({color:i.color,description:null,id:i.id,name:i.name}))}}};var jt=r=>{let s={request:r==null?void 0:r.request};return{azureDevOps:new K({...s,...r==null?void 0:r.azureDevOps}),bitbucket:new X({...s,...r==null?void 0:r.bitbucket}),bitbucketServer:new Z({...s,...r==null?void 0:r.bitbucketServer}),github:new ee({...s,...r==null?void 0:r.github}),gitlab:new re({...s,...r==null?void 0:r.gitlab}),jira:new se({...s,...r==null?void 0:r.jira}),jiraServer:new ne({...s,...r==null?void 0:r.jiraServer}),trello:new oe({...s,...r==null?void 0:r.trello})}};var Mt=(i=>(i.Conflicts="conflicts",i.Failure="failure",i.NotSet="notSet",i.Queued="queued",i.RejectedByPolicy="rejectedByPolicy",i.Succeeded="succeeded",i))(Mt||{});var zt=(e=>(e.Zero="0",e.One="1",e))(zt||{}),Wt=(e=>(e.PullRequest="pr",e.Issue="issue",e))(Wt||{}),Ht=(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.Trello="trello",d))(Ht||{});var Jt=(e=>(e.Completed="COMPLETED",e.NotPlanned="NOT_PLANNED",e))(Jt||{});var ms=jt;
1124
+ `,variables:{fullPath:`${t}/${n}`,after:o}},e);return{pageInfo:((l=(u=(a=i.body.data)==null?void 0:a.project)==null?void 0:u.labels)==null?void 0:l.pageInfo)??{endCursor:null,hasNextPage:!1},data:((g=(c=(d=(p=i.body.data)==null?void 0:p.project)==null?void 0:d.labels)==null?void 0:c.nodes)==null?void 0:g.map(ut))??[]}}async getTreeForRepo(s,e={}){let t=z(s.repo),n=new URL(s.cursor??`${ve(this.config,e)}/projects/${encodeURIComponent(t)}/repository/tree`);n.searchParams.set("per_page","10000"),n.searchParams.set("recursive","true"),n.searchParams.set("pagination","keyset"),n.searchParams.set("ref",s.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(es),pageInfo:{endCursor:i?i.substring(1,i.indexOf(">")):null,hasNextPage:!!i}}}};var ns="https://api.atlassian.com/ex/jira",Ce=100,pt=["assignee","comment","summary","created","creator","updated","votes","issuetype","status","labels","components","project","fixVersions","description"],_t="/rest/api/2/search/jql",Qt="/rest/api/2/search",dt=(r,s,e,t)=>{var a,u,l,p;let n=r.fields.assignee,o=!t,i=(r.fields[(s==null?void 0:s.Sprint)??""]??[]).filter(d=>typeof d=="object");return{id:r.id,commentCount:r.fields.comment.comments.length,number:r.key,title:r.fields.summary,url:e?`${e}/browse/${r.key}`:null,closedDate:null,createdDate:new Date(r.fields.created),author:De(r.fields.creator,e,o),updatedDate:new Date(r.fields.updated),assignees:n?[De(n,e,o)]:[],description:r.fields.description,repository:null,project:{name:r.fields.project.name,resourceId:t??null,key:r.fields.project.key,namespace:null,id:r.fields.project.id},state:us(r.fields.status),statusTransitions:((a=r.transitions)==null?void 0:a.map(os))??[],components:((u=r.fields.components)==null?void 0:u.map(is))??[],type:r.fields.issuetype.name,upvoteCount:((l=r.fields.votes)==null?void 0:l.votes)||0,labels:((p=r.fields.labels)==null?void 0:p.map(d=>({color:null,description:null,id:null,name:d})))??[],sprints:i.map(ls),fixVersions:r.fields.fixVersions.map(ps)}},os=r=>{let s;switch(r.to.statusCategory.name){case"To Do":s="TO_DO";break;case"In Progress":s="IN_PROGRESS";break;default:s="DONE";break}return{name:r.name,id:r.id,to:{id:r.to.id,name:r.to.name,color:r.to.statusCategory.colorName,category:s}}},is=r=>({description:r.description??null,id:r.id,name:r.name}),as=(r,s,e)=>e&&r.name?`${s}/secure/ViewProfile.jspa?name=${encodeURIComponent(r.name)}`:`${s}/jira/people/${r.accountId}`,De=(r,s,e)=>({id:(e?r.key:r.accountId)??"",name:r.displayName,email:r.emailAddress,avatarUrl:r.avatarUrls["48x48"],username:r.displayName,url:as(r,s,e)}),us=r=>{let s;switch(r.statusCategory.name){case"To Do":s="TO_DO";break;case"In Progress":s="IN_PROGRESS";break;default:s="DONE";break}return{id:r.id,name:r.name,color:r.statusCategory.colorName,category:s}},ls=r=>({id:r.id.toString(),name:r.name,isActive:r.state==="active",startDate:r.startDate?new Date(r.startDate):null,endDate:r.endDate?new Date(r.endDate):null,completedDate:r.completeDate?new Date(r.completeDate):null}),ps=r=>({id:r.id,description:r.description,name:r.name,archived:r.archived,released:r.released,releaseDate:r.releaseDate?new Date(r.releaseDate):null}),W=(r,s,e)=>e?`${s.baseUrl||ns}/${e}`:`${(s==null?void 0:s.baseUrl)||r.baseUrl}`,Le=async(r,s,e={})=>{let{resourceId:t}=s;return(await r.request({url:`${W(r,e,t)}/rest/api/2/field`,headers:I(e.token||r.token)})).body},Ue=async(r,s,e,t={})=>{let{number:n,resourceId:o,fields:i}=s||{},a=await r.request({url:`${W(r,t,o)}/rest/api/2/issue/${n}?fields=${pt.join(",")}&expand=transitions`,headers:I(t.token||r.token)});return{data:dt(a.body,i,e,o)}},$e=async(r,s,e,t={})=>{let{cursor:n,resourceId:o,labelNames:i,fields:a}=s||{},u=["statusCategory != Done",`(creator = currentUser() OR assignee = currentUser()
1125
+ OR comment ~ currentUser() OR summary ~ currentUser() OR description ~ currentUser())`];i&&i.forEach(P=>u.push(`labels = "${P}"`));let l=`${u.join(" AND ")} ORDER BY updated DESC`,p=!o,d=p?Qt:_t,c=new URL(`${W(r,t,o)}${d}`);c.searchParams.set("jql",l),c.searchParams.set("maxResults",Ce.toString()),c.searchParams.set("fields",pt.join(",")),c.searchParams.set("expand","transitions"),n&&(p?c.searchParams.set("startAt",n):c.searchParams.set("nextPageToken",n));let g=await r.request({url:c.toString(),headers:I(t.token||r.token)}),m=g.body.issues.map(P=>dt(P,a,e,o)),R=!1,h="";return p?(R=m.length==Ce,h=(parseInt(n??"0",10)+m.length).toString()):(R=!!g.body.nextPageToken,h=g.body.nextPageToken??null),{data:m,pageInfo:{hasNextPage:R,endCursor:h}}},Bt=async(r,s,e,t={})=>{let{cursor:n,resourceId:o,jql:i,fields:a}=s||{},u=[...pt],l=a==null?void 0:a.Sprint;l&&u.push(l);let p=!o,d=p?Qt:_t,c=new URL(`${W(r,t,o)}${d}`);c.searchParams.set("jql",i.join(" AND ")),c.searchParams.set("maxResults",Ce.toString()),c.searchParams.set("fields",u.join(",")),c.searchParams.set("expand","transitions"),n&&(p?c.searchParams.set("startAt",n):c.searchParams.set("nextPageToken",n));let g=await r.request({url:c.toString(),headers:I(t.token||r.token)}),m=g.body.issues.map(P=>dt(P,a,e,o)),R=!1,h="";return p?(R=m.length==Ce,h=(parseInt(n??"0",10)+m.length).toString()):(R=!!g.body.nextPageToken,h=g.body.nextPageToken??null),{data:m,pageInfo:{hasNextPage:R,endCursor:h}}},Ae=async(r,s,e,t={})=>{let{assigneeLogins:n,authorLogin:o,mentionLogin:i,labelNames:a,cursor:u,projectKey:l,resourceId:p,fields:d}=s||{},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}"`)),Bt(r,{resourceId:p,jql:c,cursor:u,fields:d},e,t)},Ge=async(r,s,e,t={})=>{let{assigneeLogins:n,authorLogin:o,mentionLogin:i,labelNames:a,cursor:u,projectKeys:l,resourceId:p,fields:d}=s||{},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}"`)),Bt(r,{resourceId:p,jql:g,fields:d,cursor:u},e,t)},Te=async(r,s,e={})=>{let{issue:t,labels:n}=s;if(!t.project)throw new Error('Jira requires a "project" for this function.');let o={fields:{labels:n.map(i=>i.name)}};await r.request({method:"PUT",url:`${W(r,e,t.project.resourceId??void 0)}/rest/api/2/issue/${t.id}`,body:JSON.stringify(o),headers:{...I(e.token||r.token),"Content-Type":"application/json"}})},Oe=async(r,s,e={})=>{let{issue:t,components:n}=s;if(!t.project)throw new Error('Jira requires a "project" for this function.');let o={fields:{components:n.map(i=>({id:i.id}))}};await r.request({method:"PUT",url:`${W(r,e,t.project.resourceId??void 0)}/rest/api/2/issue/${t.id}`,body:JSON.stringify(o),headers:{...I(e.token||r.token),"Content-Type":"application/json"}})},xe=async(r,s,e={})=>{let{issue:t,status:n}=s;if(!t.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 r.request({method:"POST",url:`${W(r,e,t.project.resourceId??void 0)}/rest/api/2/issue/${t.id}/transitions`,body:JSON.stringify(o),headers:{...I(e.token||r.token),"Content-Type":"application/json"}})},ke=async(r,s,e={})=>{let{resourceId:t,projectIdOrKey:n}=s,o=new URL(`${W(r,e,t)}/rest/api/2/project/${n}/components`);return{data:(await r.request({url:o.toString(),headers:I(e.token||r.token)})).body}};var ae="https://api.atlassian.com/ex/jira",ct=100,se=class extends N{constructor(){super(...arguments);this._resourceUrlCache={};this._issueFieldsCache={}}async getIssueFieldsForResource(e,t={}){if(!this._issueFieldsCache[e.resourceId]){let n=await Le(this.config,e,t);this._issueFieldsCache[e.resourceId]=n.reduce((o,i)=>({...o,[i.name]:i.id}),{})}return this._issueFieldsCache[e.resourceId]??null}async getResourceUrl(e,t={}){var i;let n=t.token||this.config.token;if(!n)return null;let o=this._resourceUrlCache[n];return o?o[e.resourceId]??null:(await this.getJiraResourcesForCurrentUser(t),((i=this._resourceUrlCache[n])==null?void 0:i[e.resourceId])??null)}async getCurrentUserForResource(e,t={}){let n=await this.getResourceUrl({resourceId:e.resourceId},t),o=await this.config.request({url:`${t.baseUrl||ae}/${e.resourceId}/rest/api/2/myself`,headers:I(t.token||this.config.token)});return{data:{name:o.body.displayName,email:o.body.emailAddress,avatarUrl:o.body.avatarUrls["48x48"],id:o.body.accountId,username:o.body.displayName,url:n?`${n}/jira/people/${o.body.accountId}`:null}}}async getJiraResourcesForCurrentUser(e={}){let t=await this.config.request({url:`${e.baseUrl||"https://api.atlassian.com/"}/oauth/token/accessible-resources`,headers:I(e.token||this.config.token)}),n=e.token||this.config.token,o=n?this._resourceUrlCache[n]||{}:void 0,i=t.body.map(a=>(o&&(o[a.id]=a.url),{avatarUrl:a.avatarUrl,id:a.id,name:a.name,url:a.url}));return n&&(this._resourceUrlCache[n]=o),{data:i}}async getJiraProjectsForResource(e,t={}){let n=new URL(`${t.baseUrl||ae}/${e.resourceId}/rest/api/2/project/search`);n.searchParams.set("maxResults",ct.toString()),e.cursor&&n.searchParams.set("startAt",e.cursor);let o=await this.config.request({url:n.toString(),headers:I(t.token||this.config.token)});return{pageInfo:{hasNextPage:o.body.values.length!==0,endCursor:(o.body.startAt+o.body.values.length).toString()},data:o.body.values.map(i=>({id:i.id,key:i.key,name:i.name,resourceId:e.resourceId}))}}async getJiraProjectsForResources(e,t={}){let n=[];return await Promise.all(e.resourceIds.map(async o=>{try{return await Pt(i=>this.getJiraProjectsForResource({resourceId:o,cursor:i},t))}catch{return[]}})).then((...o)=>{o.forEach(i=>{n=n.concat(...i)})}),{data:n}}async getAccountsForJiraProject(e,t={}){let{resourceId:n,projectKey:o,cursor:i}=e,a=await this.getResourceUrl({resourceId:n},t),u=new URL(`${t.baseUrl||ae}/${n}/rest/api/2/user/assignable/search`);u.searchParams.set("maxResults",ct.toString()),i&&u.searchParams.set("startAt",i),u.searchParams.set("project",o);let l=await this.config.request({url:u.toString(),headers:I(t.token||this.config.token)});return{pageInfo:{hasNextPage:l.body.length!==0,endCursor:((i?parseInt(i):0)+l.body.length).toString()},data:l.body.filter(p=>p.accountType!=="app"&&p.active).map(p=>De(p,a,!1))}}async getComponentsForJiraProject(e,t={}){return await ke(this.config,e,t)}async getIssue(e,t={}){let n=await this.getIssueFieldsForResource({resourceId:e.resourceId},t),o=await this.getResourceUrl({resourceId:e.resourceId},t);return await Ue(this.config,{...e,fields:n},o,t)}async getIssuesForProject(e,t={}){let n=await this.getIssueFieldsForResource({resourceId:e.resourceId},t),o=await this.getResourceUrl({resourceId:e.resourceId},t);return await Ae(this.config,{...e,fields:n},o,t)}async getIssuesForProjects(e,t={}){let n=await this.getIssueFieldsForResource({resourceId:e.resourceId},t),o=await this.getResourceUrl({resourceId:e.resourceId},t);return await Ge(this.config,{...e,fields:n},o,t)}async getIssuesForResourceForCurrentUser(e,t={}){let n=await this.getIssueFieldsForResource({resourceId:e.resourceId},t),o=await this.getResourceUrl({resourceId:e.resourceId},t);return await $e(this.config,{...e,fields:n},o,t)}async setIssueStatus(e,t={}){await xe(this.config,e,t)}async setIssueAssignee(e,t={}){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==null?void 0:o.id};await this.config.request({method:"PUT",url:`${t.baseUrl||ae}/${n.project.resourceId}/rest/api/2/issue/${n.id}/assignee`,body:JSON.stringify(i),headers:{...I(t.token||this.config.token),"Content-Type":"application/json"}})}async setIssueComponents(e,t={}){await Oe(this.config,e,t)}async setIssueLabels(e,t={}){await Te(this.config,e,t)}async getLabelsForResource(e,t={}){let{resourceId:n,cursor:o}=e,i=new URL(`${t.baseUrl||ae}/${n}/rest/api/2/label`);i.searchParams.set("maxResults",ct.toString()),o&&i.searchParams.set("startAt",o);let a=await this.config.request({url:i.toString(),headers:I(t.token||this.config.token)});return{pageInfo:{hasNextPage:!a.body.isLast,endCursor:(a.body.startAt+a.body.values.length).toString()},data:a.body.values.map(u=>({color:null,description:null,id:null,name:u}))}}};var ne=class extends A{constructor(){super(...arguments);this._issueFieldsCache={}}async getIssueFieldsForResource(e={}){let t=(e==null?void 0:e.baseUrl)||this.config.baseUrl||"";if(!this._issueFieldsCache[t]){let n=await Le(this.config,{},e);this._issueFieldsCache[t]=n.reduce((o,i)=>({...o,[i.name]:i.id}),{})}return this._issueFieldsCache[t]??null}async getCurrentUser(e={}){let t=await this.config.request({url:`${(e==null?void 0:e.baseUrl)||this.config.baseUrl}/rest/api/2/myself`,headers:I((e==null?void 0:e.token)||this.config.token)});return{data:{name:t.body.displayName,email:t.body.emailAddress,avatarUrl:t.body.avatarUrls["48x48"],id:t.body.key,username:t.body.displayName,url:null}}}async getJiraProjects(e={}){return{data:(await this.config.request({url:`${(e==null?void 0:e.baseUrl)||this.config.baseUrl}/rest/api/2/project`,headers:I((e==null?void 0:e.token)||this.config.token)})).body.map(n=>({id:n.id,name:n.name}))}}async getIssue(e,t={}){let n=e.resourceUrl||t.baseUrl||this.config.baseUrl;if(!n)throw new Error('Jira Server requires a "resourceUrl" or "baseUrl" for this function.');let o=await this.getIssueFieldsForResource(t);return await Ue(this.config,{...e,fields:o},n,t)}async getIssuesForProject(e,t={}){let n=e.resourceUrl||t.baseUrl||this.config.baseUrl;if(!n)throw new Error('Jira Server requires a "resourceUrl" or "baseUrl" for this function.');let o=await this.getIssueFieldsForResource(t);return await Ae(this.config,{...e,fields:o},n,t)}async getIssuesForProjects(e,t={}){let n=e.resourceUrl||t.baseUrl||this.config.baseUrl;if(!n)throw new Error('Jira Server requires a "resourceUrl" or "baseUrl" for this function.');let o=await this.getIssueFieldsForResource(t);return await Ge(this.config,{...e,fields:o},n,t)}async getIssuesForResourceForCurrentUser(e,t={}){let n=e.resourceUrl||t.baseUrl||this.config.baseUrl;if(!n)throw new Error('Jira Server requires a "resourceUrl" or "baseUrl" for this function.');let o=await this.getIssueFieldsForResource(t);return await $e(this.config,{...e,fields:o},n,t)}async setIssueStatus(e,t={}){await xe(this.config,e,t)}async setIssueLabels(e,t={}){await Te(this.config,e,t)}async setIssueComponents(e,t={}){await Oe(this.config,e,t)}async getLabels(e={}){return{data:(await this.config.request({url:`${(e==null?void 0: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,t={}){return await ke(this.config,e,t)}};var k="https://api.trello.com",ds=1e3,cs=r=>({id:r.id,username:r.username,url:r.url,name:r.fullName,email:r.email,avatarUrl:r.avatarUrl}),gs=(r,s)=>{let e=new Date(1e3*parseInt(r.id.substring(0,8),16));return{id:r.id,commentCount:r.badges.comments,number:r.idShort.toString(),title:r.name,url:r.url,closedDate:null,createdDate:new Date(e.toISOString()),author:null,updatedDate:new Date(r.dateLastActivity),assignees:r.members.map(t=>({id:t.id,username:t.username,name:t.fullName,email:null,avatarUrl:t.avatarUrl,url:null})),description:null,state:s[r.idList??""]?{id:r.idList,name:s[r.idList].name,color:null}:null,type:null,repository:null,upvoteCount:r.badges.votes,labels:r.labels.map(t=>({color:t.color,description:null,id:t.id,name:t.name}))}},oe=class extends N{async getCurrentUser(s,e={}){let t=await this.config.request({url:`${e.baseUrl||k}/1/members/me?key=${s.appKey}&token=${e.token||this.config.token}`,headers:I(e.token||this.config.token)});return{data:{name:t.body.fullName,email:t.body.email,avatarUrl:t.body.avatarHash?`https://trello-members.s3.amazonaws.com/${t.body.id}/${t.body.avatarHash}/50.png`:null,id:t.body.id,username:t.body.username,url:t.body.url}}}async getBoardsForCurrentUser(s,e={}){return{data:(await this.config.request({url:`${e.baseUrl||k}/1/members/me/boards?fields=name&key=${s.appKey}&token=${e.token||this.config.token}&filter=open`,headers:I(e.token||this.config.token)})).body.map(n=>({id:n.id,name:n.name}))}}async getListsForTrelloBoard(s,e={}){let{appKey:t,boardId:n}=s;return{data:(await this.config.request({url:`${e.baseUrl||k}/1/boards/${n}/lists?key=${t}&token=${e.token||this.config.token}`,headers:I(e.token||this.config.token)})).body}}async getAccountForId(s,e={}){let{appKey:t,memberId:n}=s,o=await this.config.request({url:`${e.baseUrl||k}/1/members/${n}/?key=${t}&token=${e.token||this.config.token}`});return{data:cs(o.body)}}async getAccountsForTrelloBoard(s,e={}){let{appKey:t,boardId:n}=s;return{data:(await this.config.request({url:`${e.baseUrl||k}/1/boards/${n}/members?key=${t}&token=${e.token||this.config.token}`,headers:I(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(s,e={}){let t=["-is:archived","sort:edited"],{appKey:n,boardId:o,filterText:i,assigneeLogins:a,labelNamesOrColors:u,trelloBoardListsById:l}=s||{};a&&t.push("@me"),u&&u.forEach(c=>t.push(`label:"${c}"`));let p=`${i?`${i}`:""}${t.join(" ")} board:${o}`;return{data:(await this.config.request({url:`${e.baseUrl||k}/1/search?key=${n}&query=${p}&cards_limit=${ds}&token=${e.token||this.config.token}&card_members=true`,headers:I(e.token||this.config.token)})).body.cards.map(c=>gs(c,l||{}))}}async updateIssue(s,e,t,n){return await this.config.request({method:"PUT",url:`${n.baseUrl||k}/1/cards/${e.id}?key=${s}&token=${n.token||this.config.token}&${t}`,headers:I(n.token||this.config.token)})}async setIssueStatus(s,e={}){let{appKey:t,issue:n,status:o}=s;if(!o.id)throw new Error('Trello requires a status "id" for this function.');let i=`idList=${o.id}`;if(!(await this.updateIssue(t,n,i,e)).body.id)throw new Error("Could not set issue status")}async setIssueAssignees(s,e={}){let{appKey:t,issue:n,assignees:o}=s,i=o.map(l=>l.id),a=`idMembers=${encodeURIComponent(i.join(","))}`;if(!(await this.updateIssue(t,n,a,e)).body.id)throw new Error("Could not set issue status")}async setIssueLabels(s,e={}){let{appKey:t,issue:n,labels:o}=s,i=o.map(u=>u.id).join(",");if(!(await this.config.request({method:"PUT",url:`${e.baseUrl||k}/1/cards/${n.id}?key=${t}&token=${e.token||this.config.token}&idLabels=${encodeURIComponent(i)}`,headers:I(e.token||this.config.token)})).body.id)throw new Error("Could not set issue status")}async setIssueArchived(s,e={}){let{appKey:t,issue:n,archived:o}=s;if(!(await this.config.request({method:"PUT",url:`${e.baseUrl||k}/1/cards/${n.id}?key=${t}&token=${e.token||this.config.token}&closed=${o}`,headers:I(e.token||this.config.token)})).body.id)throw new Error("Could not update issue archived status")}async archiveIssue(s,e={}){await this.setIssueArchived({...s,archived:!0},e)}async unArchiveIssue(s,e={}){await this.setIssueArchived({...s,archived:!1},e)}async getLabelsForBoard(s,e={}){let{appKey:t,boardId:n}=s;return{data:(await this.config.request({url:`${e.baseUrl||k}/1/boards/${n}/labels?key=${t}&token=${e.token||this.config.token}`,headers:I(e.token||this.config.token)})).body.map(i=>({color:i.color,description:null,id:i.id,name:i.name}))}}};var jt=r=>{let s={request:r==null?void 0:r.request};return{azureDevOps:new K({...s,...r==null?void 0:r.azureDevOps}),bitbucket:new X({...s,...r==null?void 0:r.bitbucket}),bitbucketServer:new Z({...s,...r==null?void 0:r.bitbucketServer}),github:new ee({...s,...r==null?void 0:r.github}),gitlab:new re({...s,...r==null?void 0:r.gitlab}),jira:new se({...s,...r==null?void 0:r.jira}),jiraServer:new ne({...s,...r==null?void 0:r.jiraServer}),trello:new oe({...s,...r==null?void 0:r.trello})}};var Mt=(i=>(i.Conflicts="conflicts",i.Failure="failure",i.NotSet="notSet",i.Queued="queued",i.RejectedByPolicy="rejectedByPolicy",i.Succeeded="succeeded",i))(Mt||{});var zt=(e=>(e.Zero="0",e.One="1",e))(zt||{}),Wt=(e=>(e.PullRequest="pr",e.Issue="issue",e))(Wt||{}),Ht=(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.Trello="trello",d))(Ht||{});var Jt=(e=>(e.Completed="COMPLETED",e.NotPlanned="NOT_PLANNED",e))(Jt||{});var ms=jt;