@gitkraken/provider-apis 0.30.0 → 0.31.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,4 @@
1
- "use strict";var _e=Object.defineProperty;var cr=Object.getOwnPropertyDescriptor;var gr=Object.getOwnPropertyNames;var mr=Object.prototype.hasOwnProperty;var hr=(t,s)=>{for(var e in s)_e(t,e,{get:s[e],enumerable:!0})},fr=(t,s,e,r)=>{if(s&&typeof s=="object"||typeof s=="function")for(let n of gr(s))!mr.call(t,n)&&n!==e&&_e(t,n,{get:()=>s[n],enumerable:!(r=cr(s,n))||r.enumerable});return t};var Ir=t=>fr(_e({},"__esModule",{value:!0}),t);var js={};hr(js,{AzureDevOps:()=>H,Bitbucket:()=>J,BitbucketServer:()=>V,EntityIdentifierProviderType:()=>lr,EntityType:()=>ur,EntityVersion:()=>ir,GitBuildStatusStage:()=>Pt,GitBuildStatusState:()=>ue,GitDiffLineType:()=>Fe,GitHub:()=>X,GitHubIssueCloseReason:()=>pr,GitIssueState:()=>me,GitLab:()=>Y,GitMergeStrategy:()=>W,GitPullRequestMergeableState:()=>M,GitPullRequestReviewState:()=>F,GitPullRequestState:()=>z,GraphQLErrors:()=>f,Jira:()=>ee,JiraServer:()=>te,PullRequestAsyncStatus:()=>ar,Trello:()=>re,default:()=>Qs,isFetch:()=>le});module.exports=Ir(js);var Pt=(n=>(n.Build="build",n.Production="production",n.Staging="staging",n.Test="test",n))(Pt||{}),ue=(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))(ue||{}),W=(o=>(o.MergeCommit="MERGE_COMMIT",o.Rebase="REBASE",o.RebaseThenMergeCommit="REBASE_THEN_MERGE_COMMIT",o.FastForward="FAST_FORWARD",o.Squash="SQUASH",o))(W||{}),z=(r=>(r.Open="OPEN",r.Closed="CLOSED",r.Merged="MERGED",r))(z||{}),F=(n=>(n.Approved="APPROVED",n.ChangesRequested="CHANGES_REQUESTED",n.Commented="COMMENTED",n.ReviewRequested="REVIEW_REQUESTED",n))(F||{}),M=(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))(M||{}),Fe=(r=>(r.ADDED="ADDED",r.DELETED="DELETED",r.UNMODIFIED="UNMODIFIED",r))(Fe||{});var wt={APPROVED:0,COMMENTED:1,REVIEW_REQUESTED:2,CHANGES_REQUESTED:3},G=t=>!t||t.length===0?null:t.reduce((s,e)=>wt[e.state]>wt[s]?e.state:s,"APPROVED");var S=100;var St=globalThis.fetch;var Rr=async t=>{let s=t.headers.get("content-type")||"",e=null;if(s.startsWith("application/json")){let o=await t.text();e=o.trim().length>0?JSON.parse(o):null}else if(s.startsWith("text/")||s==="")e=await t.text();else if(s.startsWith("application/vnd.github.raw+json"))e=await t.arrayBuffer();else throw new Error(`Unsupported content-type: ${s}`);let r={};t.headers.forEach((o,a)=>{r[a]=o});let n={body:e,headers:r,status:t.status,statusText:t.statusText};if(!t.ok){let o=new Error(t.statusText);throw Object.assign(o,{response:n}),o}return n},Qe=t=>async({url:s,...e})=>{let r=await t(s,e);return Rr(r)};var le=(t,s=!1)=>t.name==="fetch"||s;var U=class{constructor(s){let e=s?.request||St;this.config={...s,request:le(e,s?.forceIsFetch)?Qe(e):e}}updateConfig(s){this.config={...this.config,...s,request:s.request&&le(s.request,s?.forceIsFetch??this.config.forceIsFetch)?Qe(s.request):this.config.request}}},L=class extends U{};var h=(t,s)=>{let e={};return t&&(e.Authorization=`${s?"Basic":"Bearer"} ${t}`),e},vt=t=>t?t.reduce((s,e)=>(s[e]=!0,s),{}):void 0,Q=(t,s,e)=>!t||s.some(r=>t[r])?e:"",Et=async t=>{let s=[],e=!0,r;for(;e;){let n=await t(r);s=s.concat(n.data),e=!!n?.pageInfo?.hasNextPage,r=n?.pageInfo?.endCursor||n?.pageInfo?.nextPage}return s};async function je(t){return(await Promise.allSettled(t)).map(e=>br(e)).filter(e=>e!=null)}function br(t,s=void 0){return t?.status==="fulfilled"?t.value:s}var yr="https://app.vssps.visualstudio.com/_apis",Pr="https://vssps.dev.azure.com/",wr="https://dev.azure.com",P=(t,s={})=>h(s.token||t.token,s.isPAT||t.isPAT),qt=t=>t.url.replace("/_apis/git/repositories/","/_git/").replace(`/${t.repository.project.id}/`,`/${encodeURIComponent(t.repository.project.name)}/`).replace(`/${t.repository.id}/`,`/${encodeURIComponent(t.repository.name)}/`).replace("/pullRequests/","/pullrequest/"),Be=(t,s)=>{let e=s.baseUrl||t.baseUrl||yr;return e=e.replace(/\/$/,""),e},w=(t,s)=>{let e=s.baseUrl||t.baseUrl||wr;return e=e.replace(/\/$/,""),e},ze=(t,s)=>{let e=s.baseUrl||t.baseUrl||Pr;return e=e.replace(/\/$/,""),e};var Sr={active:"OPEN",completed:"MERGED",abandoned:"CLOSED"},vr={10:"APPROVED",5:"APPROVED",0:"REVIEW_REQUESTED",[-5]:"CHANGES_REQUESTED",[-10]:"CHANGES_REQUESTED"},Me=t=>({id:t.id,name:t.displayName??null,username:(t.uniqueName||t.displayName)??null,email:null,avatarUrl:t.imageUrl??null,url:null}),de=t=>t.startsWith("refs/heads/")?t.replace("refs/heads/",""):t,Er=t=>{switch(t){case"conflicts":return"CONFLICTS";case"failure":return"FAILING_CHECKS";case"rejectedByPolicy":return"BLOCKED";case"succeeded":return"MERGEABLE";case"notSet":case"queued":default:return"UNKNOWN"}},pe=(t,s)=>{let e=[],r=[];return s.reviewers.forEach(n=>{let o={reviewer:Me(n),state:vr[n.vote??0]||"REVIEW_REQUESTED"};n.isRequired&&e.push(o),r.push(o)}),{id:s.pullRequestId.toString(),title:s.title,number:s.codeReviewId,state:Sr[s.status],isDraft:s.isDraft,commentCount:null,upvoteCount:null,author:Me(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:t},remoteInfo:null},headCommit:{buildStatuses:null},baseRef:{name:de(s.targetRefName),oid:s.lastMergeTargetCommit.commitId},headRef:{name:de(s.sourceRefName),oid:s.lastMergeSourceCommit.commitId},url:qt(s),assignees:s.reviewers.map(Me),reviews:r,reviewDecision:G(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:t},remoteInfo:null}:{id:s.repository.id,name:s.repository.name,project:s.repository.project.name,owner:{login:t},remoteInfo:null},mergeableState:Er(s.mergeStatus),labels:s.labels?.map(n=>({color:null,description:null,id:n.id,name:n.name}))??[],permissions:null}},Ct=(t,s)=>({id:s.id,name:s.name,namespace:t,project:s.project.name,projectId:s.project.id,webUrl:s.webUrl,httpsUrl:s.remoteUrl,sshUrl:s.sshUrl,defaultBranch:s.defaultBranch?{name:de(s.defaultBranch)}:null,permissions:null}),qr=(t,s,e,r)=>{let n=e.fields,o=n["System.AssignedTo"],a=n["System.State"],i=n["System.WorkItemType"],u;return a&&i&&(u=r[i]?.[a]),{id:e.id.toString(),number:e.id.toString(),title:n["System.Title"],commentCount:n["System.CommentCount"],author:{avatarUrl:n["System.CreatedBy"]._links?.avatar?.href??null,email:null,id:n["System.CreatedBy"].id,name:n["System.CreatedBy"].uniqueName??null,username:n["System.CreatedBy"].displayName??null,url:null},closedDate:n["Microsoft.VSTS.Common.ClosedDate"]?new Date(n["Microsoft.VSTS.Common.ClosedDate"]):null,createdDate:new Date(n["System.CreatedDate"]),updatedDate:new Date(n["System.ChangedDate"]),url:e._links.html.href,assignees:o?[{avatarUrl:o._links?.avatar?.href??null,email:null,id:o.id,name:o.uniqueName??null,username:o.displayName??null,url:null}]:[],description:n["System.Description"]??null,state:{name:u?.title||a,color:null},type:n["System.WorkItemType"],repository:null,project:{namespace:t,name:s,resourceId:null,key:null,id:null},upvoteCount:0,labels:e.fields["System.Tags"]?.split(";").map(l=>({color:null,description:null,id:null,name:l.trim()}))??[]}},H=class extends L{async getCurrentUser(s={},e={}){if(e.isPAT||this.config.isPAT)throw new Error("Azure DevOps does not support PATs for this function.");let r=`${Be(this.config,e)}/profile/profiles/me`,n=await this.config.request({url:r,headers:P(this.config,e)});return{data:{id:n.body.id,name:n.body.displayName,username:n.body.displayName,email:n.body.emailAddress,avatarUrl:null,url:null}}}async getCurrentUserForInstance(s,e={}){let n=(await this.config.request({url:`${w(this.config,e)}/${encodeURIComponent(s.namespace)}/_apis/ConnectionData`,headers:P(this.config,e)})).body.authorizedUser;if(n.providerDisplayName==="Anonymous")throw new Error("Current user not found.");return{data:{id:n.id,name:n.providerDisplayName,username:n.providerDisplayName,email:n.properties.Account.$value,avatarUrl:null,url:null}}}async getUserForCommit(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:`${w(this.config,e)}/${encodeURIComponent(s.repo.namespace)}/${encodeURIComponent(s.repo.project)}/_apis/git/repositories/${encodeURIComponent(s.repo.name)}/commits/${s.oid}`,headers:P(this.config,e)})).body.author;return{data:{name:n.name,email:n.email,avatarUrl:n.imageUrl}}}async getOrgsForUser(s,e={}){let r=`${Be(this.config,e)}/accounts?memberId=${s.userId}&api-version=6.0`;return{data:(await this.config.request({url:r,headers:P(this.config,e)})).body.value.map(o=>({id:o.accountId,name:o.accountName}))}}async getCollectionsForUser(s,e={}){let r=`${w(this.config,e)}/_apis/projectCollections`;return{data:(await this.config.request({url:r,headers:P(this.config,e)})).body.value.map(o=>({id:o.id,name:o.name}))}}async getAzureProjects(s,e={}){let r=new URL(`${w(this.config,e)}/${encodeURIComponent(s.namespace)}/_apis/projects`);r.searchParams.set("$top",S.toString()),s.cursor&&r.searchParams.set("$skip",s.cursor);let n=await this.config.request({url:r.toString(),headers:P(this.config,e)}),o=n.headers["x-ms-continuationtoken"];return{pageInfo:{hasNextPage:!!o,endCursor:o||null},data:n.body.value.map(a=>({id:a.id,name:a.name,namespace:s.namespace}))}}async getAzureProjectScopeDescriptor(s,e={}){let{namespace:r,projectId:n}=s;return{data:{scope:(await this.config.request({url:`${ze(this.config,e)}/${encodeURIComponent(r)}/_apis/graph/descriptors/${n}?api-version=6.0`,headers:P(this.config,e)})).body.value}}}async getAzureGraphAccountsForAzureProject(s,e={}){let{namespace:r,projectScopeDescriptor:n,cursor:o}=s,a=new URL(`${ze(this.config,e)}/${encodeURIComponent(r)}/_apis/graph/users`);n&&a.searchParams.set("scopeDescriptor",n),o&&a.searchParams.set("continuationToken",o);let i=await this.config.request({url:a.toString(),headers:P(this.config,e)}),u=i.headers["x-ms-continuationtoken"];return{pageInfo:{endCursor:u||null,hasNextPage:!!u},data:i.body.value.map(l=>({avatarUrl:l._links?.avatar?.href??null,descriptor:l.descriptor??null,email:l.mailAddress??null,name:l.displayName??null,storageKeyURL:l._links?.storageKey?.href??null,username:l.displayName??null}))}}async getAccountFromAzureGraphAccount(s,e={}){let{azureGraphAccount:r}=s;if(!r.storageKeyURL)throw new Error("Expected 'storageKeyURL' to not be null for 'azureGraphAccount'");let n=await this.config.request({url:r.storageKeyURL,headers:P(this.config,e)});return{data:{avatarUrl:r.avatarUrl,email:r.email,id:n.body.value,name:r.name,username:r.username,url:null}}}async getAccountsFromAzureGraphAccounts(s,e={}){let r=[];for(let n of s.azureGraphAccounts){let o=await this.getAccountFromAzureGraphAccount({azureGraphAccount:n},e);r.push(o.data)}return{data:r}}async getRepo(s,e={}){if(!s.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let r=await this.config.request({url:`${w(this.config,e)}/${encodeURIComponent(s.namespace)}/${encodeURIComponent(s.project)}/_apis/git/repositories/${encodeURIComponent(s.name)}`,headers:P(this.config,e)});return{data:Ct(s.namespace,r.body)}}async getRepos(s,e={}){let r=[],n=[];return await Promise.all(s.map(async o=>{try{let a=await this.getRepo(o,e);r.push(a.data)}catch(a){n.push({input:o,error:a})}})),{data:r,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:`${w(this.config,e)}/${encodeURIComponent(s.namespace)}/${encodeURIComponent(s.project)}/_apis/git/repositories`,headers:P(this.config,e)})).body.value.map(n=>Ct(s.namespace,n))}}async getRefs(s,e,r={}){if(!e.repo.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let n=new URL(`${w(this.config,r)}/${encodeURIComponent(e.repo.namespace)}/${encodeURIComponent(e.repo.project)}/_apis/git/repositories/${encodeURIComponent(e.repo.name)}/refs`);n.searchParams.set("filter",s),n.searchParams.set("$top",S.toString()),e.cursor&&n.searchParams.set("continuationToken",e.cursor);let o=await this.config.request({url:n.toString(),headers:P(this.config,r)}),a=o.headers["x-ms-continuationtoken"];return{pageInfo:{hasNextPage:!!a,endCursor:a||null},data:o.body.value.map(i=>({name:de(i.name),commit:{oid:i.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={},r=100){let{page:n,repo:o,assigneeLogins:a,authorLogin:i}=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 a&&a.length&&(l+=`&searchCriteria.reviewerId=${a[0]}`),i&&(l+=`&searchCriteria.creatorId=${i}`),await this.config.request({url:`${w(this.config,e)}/${encodeURIComponent(o.namespace)}/${encodeURIComponent(o.project||"")}/_apis/git/repositories/${encodeURIComponent(o.name)}/pullRequests?${l}&%24top=${r}&%24skip=${(u-1)*r}`,headers:P(this.config,e)})}async getPullRequestsForRepo(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(a=>pe(s.repo.namespace,a))}}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:r}=s||{},n=[];return await Promise.all(r.map(async o=>{try{(await this.getPullRequestsForRepoBase({repo:o,...s},e)).body.value.forEach(i=>{n.push(pe(o.namespace,i))})}catch(a){if(a.statusCode!==404&&a.statusCode!==401)throw a}})),{data:n}}async getPullRequestsForProjectBase(s,e={},r=100){let{namespace:n,project:o,page:a,assigneeLogins:i,authorLogin:u,repo:l}=s;if(l?.project&&l.project!==o)throw new Error("Could not fetch pull requests, project mismatch");let p=a||1,d=new URL(`${w(this.config,e)}/${encodeURIComponent(n)}/${encodeURIComponent(o)}/_apis/git/pullRequests`);return d.searchParams.set("searchCriteria.status","1"),d.searchParams.set("$top",r.toString()),d.searchParams.set("$skip",((p-1)*r).toString()),l?.id&&l?.project===o&&d.searchParams.set("searchCriteria.repositoryId",l.id),i&&i.length&&d.searchParams.set("searchCriteria.reviewerId",i[0]),u&&d.searchParams.set("searchCriteria.creatorId",u),await this.config.request({url:d.toString(),headers:P(this.config,e)})}async getPullRequestsForProject(s,e={}){let n=s.page||1,o=await this.getPullRequestsForProjectBase(s,e,100);return{pageInfo:{hasNextPage:o?.body.value.length===100,nextPage:n+1},data:o?.body.value.map(a=>pe(s.namespace,a))||[]}}async getPullRequestsForProjects(s,e={}){let{projects:r}=s||{},n=[];return await Promise.all(r.map(async o=>{try{(!s.repo||s.repo.project&&s.repo.project===o.project)&&(await this.getPullRequestsForProjectBase({...o,...s},e))?.body.value.forEach(i=>{n.push(pe(o.namespace,i))})}catch(a){if(a.statusCode!==404&&a.statusCode!==401)throw a}})),{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:r,project:n,name:o},pullRequestId:a}=s,i=await this.config.request({url:`${w(this.config,e)}/${encodeURIComponent(r)}/${encodeURIComponent(n||"")}/_apis/git/repositories/${o}/pullrequests/${a}?includeCommits=true?api-version=6.0`,headers:{...P(this.config,e)}});if(!i.body.mergeStatus)throw new Error("Could not fetch pull request");return{data:i.body.mergeStatus}}async updatePullRequest(s,e,r){return await this.config.request({method:"PATCH",url:`${w(this.config,r)}/${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:{...P(this.config,r),"Content-Type":"application/json"}})}async closePullRequest(s,e={}){let{pullRequest:r}=s,n={status:"abandoned"};if(!(await this.updatePullRequest(r,JSON.stringify(n),e)).body.status)throw new Error("Could not close pull request")}async mergePullRequest(s,e={}){let{pullRequest:r,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 a={completionOptions:{mergeStrategy:o},lastMergeSourceCommit:{commitId:r.headRef?.oid},status:"completed"};if(!(await this.updatePullRequest(r,JSON.stringify(a),e)).body.status)throw new Error("Could not merge pull request")}async addPullRequestLabel(s,e={}){let{pullRequest:r,label:n}=s;if(!r.repository.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let o={name:n.name};if(!(await this.config.request({method:"POST",url:`${w(this.config,e)}/${encodeURIComponent(r.repository.owner.login)}/${encodeURIComponent(r.repository.project)}/_apis/git/repositories/${r.repository.name}/pullrequests/${r.id}/labels?api-version=6.0`,body:JSON.stringify(o),headers:{...P(this.config,e),"Content-Type":"application/json"}})).body.id)throw new Error("Could not add pull request label")}async removePullRequestLabel(s,e={}){let{pullRequest:r,label:n}=s;if(!r.repository.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');await this.config.request({method:"DELETE",url:`${w(this.config,e)}/${encodeURIComponent(r.repository.owner.login)}/${encodeURIComponent(r.repository.project)}/_apis/git/repositories/${r.repository.name}/pullrequests/${r.id}/labels/${encodeURIComponent(n.name)}?api-version=6.0`,headers:{...P(this.config,e)}})}async setPullRequestLabels(s,e={}){let{pullRequest:r,labels:n}=s;if(!r.repository.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let o=r.labels;if(!o)throw new Error('Azure DevOps requires "labels" for this function.');for(let a of n)o.find(i=>i.id===a.id)||await this.addPullRequestLabel({pullRequest:r,label:a},e);for(let a of o)n.find(i=>a.id===i.id)||await this.removePullRequestLabel({pullRequest:r,label:a},e)}async setPullRequestAsDraft(s,e={}){let{pullRequest:r,isDraft:n}=s,o={isDraft:n};if(!(await this.updatePullRequest(r,JSON.stringify(o),e)).body.status)throw new Error("Could not set the pull request as draft")}async addPullRequestReviewer(s,e={}){let{pullRequest:r,reviewer:n,isRequired:o}=s,a={id:n.id,isRequired:o};if(!(await this.config.request({method:"PUT",url:`${w(this.config,e)}/${encodeURIComponent(r.repository.owner.login)}/${encodeURIComponent(r.repository.project)}/_apis/git/repositories/${r.repository.name}/pullrequests/${r.id}/reviewers/${n.id}?api-version=6.0`,body:JSON.stringify(a),headers:{...P(this.config,e),"Content-Type":"application/json"}})).body.id)throw new Error("Could not add pull request reviewer")}async removePullRequestReviewer(s,e={}){let{pullRequest:r,reviewer:n}=s;await this.config.request({method:"DELETE",url:`${w(this.config,e)}/${encodeURIComponent(r.repository.owner.login)}/${encodeURIComponent(r.repository.project)}/_apis/git/repositories/${r.repository.name}/pullrequests/${r.id}/reviewers/${n.id}?api-version=6.0`,headers:{...P(this.config,e),Accept:"application/json"}})}async setPullRequestReviewers(s,e={}){let{pullRequest:r,reviewers:n}=s;for(let o of n)r.assignees.find(a=>a.id===o.id)||await this.addPullRequestReviewer({pullRequest:r,reviewer:o,isRequired:!0},e);for(let o of r.assignees)n.find(a=>o.id===a.id)||await this.removePullRequestReviewer({pullRequest:r,reviewer:o},e)}async getIssuesForAzureProject(s,e={}){let{page:r,assigneeLogins:n,authorLogin:o,mentionLogin:a,labelNames:i,statusByWorkItemIdByStatusId:u}=s||{},l=r||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("'","''")}'`),a&&d.push("[System.Id] IN (@recentMentions)"),i&&i.forEach(R=>d.push(`[System.Tags] Contains '${R}'`));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:`${w(this.config,e)}/${encodeURIComponent(s.namespace)}/${encodeURIComponent(s.project)}/_apis/wit/wiql?api-version=6.0`,body:JSON.stringify({query:c}),method:"POST",headers:{...P(this.config,e),"Content-Type":"application/json"}}),m=g.body.workItems.slice((l-1)*p,p*l).map(R=>R.id);if(m.length==0)return{pageInfo:{hasNextPage:!1,nextPage:null},data:[]};let b=await this.config.request({url:`${w(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:{...P(this.config,e),"Content-Type":"application/json"}});return{pageInfo:{hasNextPage:g.body.workItems.length>p*l,nextPage:l+1},data:b.body.value.map(R=>qr(s.namespace,s.project,R,u||{}))}}async getPermissionsForRepos(s,e={}){let{namespace:r,repos:n}=s,o={4:["canPush","canCreateWebhook"],1024:["isAdmin"],2048:["isAdmin"],4096:["isAdmin"],8192:["isAdmin"]},a=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}))},i={alwaysAllowAdministrators:!1,evaluations:n.flatMap(a)};return{data:(await this.config.request({method:"POST",url:`${w(this.config,e)}/${encodeURIComponent(r)}/_apis/security/permissionevaluationbatch?api-version=7.0`,body:JSON.stringify(i),headers:{...P(this.config,e),"Content-Type":"application/json"}})).body.evaluations.reduce((p,d)=>{let[,c,g]=d.token.split("/"),m=`${c}/${g}`,b=o[d.permissions];for(let R of b)p[m]===void 0&&(p[m]={canCreateWebhook:!0,canPush:!0,isAdmin:!0}),d.value===!1&&(p[m][R]=!1);return p},{})}}async decorateReposWithPermissions(s,e={}){let{namespace:r,repos:n}=s,o=await this.getPermissionsForRepos({namespace:r,repos:n},e);return{data:n.map(a=>({...a,permissions:o.data[`${a.projectId}/${a.id}`]}))}}async updateIssue(s,e,r={}){return await this.config.request({method:"PATCH",url:`${w(this.config,r)}/${encodeURIComponent(s.project.namespace)}/${encodeURIComponent(s.project.name)}/_apis/wit/workitems/${s.id}?api-version=6.0`,body:JSON.stringify(e),headers:{...P(this.config,r),"Content-Type":"application/json-patch+json"}})}async setIssueStatus(s,e={}){let{issue:r,status:n}=s,o=[{op:"add",path:"/fields/System.State",value:n.name}];if(!(await this.updateIssue(r,o,e)).body.fields?.["System.State"])throw new Error("Could not set issue status")}async setIssueAssignee(s,e={}){let{issue:r,assignee:n}=s,o=[{op:"add",path:"/fields/System.AssignedTo",value:n?.name??""}];if(!(await this.updateIssue(r,o,e)).body.fields?.["System.State"])throw new Error("Could not set issue assignee")}async setIssueLabels(s,e={}){let{issue:r,labels:n}=s,a=[{op:"replace",path:"/fields/System.Tags",value:n.map(u=>u.name).join(";")}];if(!(await this.updateIssue(r,a,e)).body.fields?.["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:r,project:n}=s;return{data:(await this.config.request({url:`${w(this.config,e)}/${encodeURIComponent(r)}/${encodeURIComponent(n||"")}/_apis/wit/workitemtypes?api-version=6.0`,headers:{...P(this.config,e)}})).body.value}}async getLabelsForProject(s,e={}){let{namespace:r,project:n}=s;return{data:(await this.config.request({url:`${w(this.config,e)}/${encodeURIComponent(r)}/${encodeURIComponent(n||"")}/_apis/wit/tags?api-version=6.0`,headers:{...P(this.config,e)}})).body.value.map(a=>({color:null,description:null,id:a.id,name:a.name,url:a.url}))}}};var E=(t,s={})=>h(s.token||t.token,s.isPAT||t.isPAT);var q="https://api.bitbucket.org/2.0",Cr={OPEN:"OPEN",MERGED:"MERGED",DECLINED:"CLOSED"},ce=t=>({id:t.uuid,name:t.display_name||t.nickname,username:t.nickname||t.display_name,email:null,avatarUrl:t.links.avatar.href,url:t.links.html.href}),Lt=t=>{let s=t.links.clone,e=s?.find(n=>n.name==="ssh"),r=s?.find(n=>n.name==="https");return e&&r?{cloneUrlHTTPS:r.href,cloneUrlSSH:e.href}:null},Dt=t=>({id:t.uuid,namespace:t.workspace.slug,name:t.slug,webUrl:t.links.html.href,httpsUrl:t.links.clone.find(s=>s.name==="https")?.href??null,sshUrl:t.links.clone.find(s=>s.name==="ssh")?.href??null,defaultBranch:{name:t.mainbranch.name},permissions:null}),We=t=>{let s=t.id,e=t.participants?.map(r=>{let n="REVIEW_REQUESTED";return r.approved?n="APPROVED":r.state==="changes_requested"?n="CHANGES_REQUESTED":r.participated_on!==null&&(n="COMMENTED"),{reviewer:ce(r.user),state:n}})??[];return{id:s.toString(),title:t.title,number:s,state:Cr[t.state],isDraft:!1,commentCount:t.comment_count,upvoteCount:null,author:ce(t.author),createdDate:new Date(t.created_on),updatedDate:new Date(t.updated_on),closedDate:null,mergedDate:null,repository:{id:t.destination.repository.uuid,name:t.destination.repository.name,owner:{login:t.destination.repository.full_name.split("/")[0]},remoteInfo:Lt(t.destination.repository)},headCommit:{buildStatuses:null},baseRef:{name:t.destination.branch.name,oid:t.destination.commit.hash},headRef:{name:t.source.branch.name,oid:t.source.commit.hash},url:t.links.html.href,assignees:null,reviews:e,reviewDecision:G(e),additions:null,deletions:null,fileCount:null,commitCount:null,headRepository:{id:t.source.repository.uuid,name:t.source.repository.name,owner:{login:t.source.repository.full_name.split("/")[0]},remoteInfo:Lt(t.source.repository)},mergeableState:"MERGEABLE",permissions:null}},Lr=t=>{switch(t){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}}},J=class extends U{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 r=await this.config.request({url:`${q}/user`,headers:E(this.config,e)});return{data:ce(r.body)}}async getUserForCommit(s,e={}){let n=(await this.config.request({url:`${q}/repositories/${s.repo.namespace}/${s.repo.name}/commit/${s.oid}`,headers:E(this.config,e)})).body.author,o=n.raw.match(/([^<]+)<(.+)>/);return{data:{name:o?o[1].trim():null,email:o?o[2]:null,avatarUrl:n.user?.links.avatar.href||null}}}async getRepo(s,e={}){let r=await this.config.request({url:`${q}/repositories/${s.namespace}/${s.name}`,headers:E(this.config,e)});return{data:Dt(r.body)}}async getRepos(s,e={}){let r=[],n=[];return await Promise.all(s.map(async o=>{try{let a=await this.getRepo(o,e);r.push(a.data)}catch(a){n.push({input:o,error:a})}})),{data:r,errors:n}}async getReposForCurrentUser(s,e={}){let r=new URL(`${q}/repositories`);r.searchParams.set("role","member"),r.searchParams.set("pagelen",S.toString()),s.cursor&&r.searchParams.set("after",s.cursor);let n=await this.config.request({url:r.toString(),headers:E(this.config,e)}),o=!!n.body.next,a=null;return n.body.next&&(a=new URL(n.body.next).searchParams.get("after")),{pageInfo:{hasNextPage:o,endCursor:a},data:n.body.values.map(Dt)}}async getBranches(s,e={}){let r=new URL(`${q}/repositories/${s.repo.namespace}/${s.repo.name}/refs/branches`);r.searchParams.set("page",s.page?.toString()||"1"),r.searchParams.set("pagelen",S.toString());let n=await this.config.request({url:r.toString(),headers:E(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 i=new Date(a.target.date);return{name:a.name,commit:{oid:a.target.hash,authoredDate:i,committedDate:i}}})}}async getTags(s,e={}){let r=new URL(`${q}/repositories/${s.repo.namespace}/${s.repo.name}/refs/tags`);r.searchParams.set("pagelen",S.toString()),s.cursor&&r.searchParams.set("page",s.cursor);let n=await this.config.request({url:r.toString(),headers:E(this.config,e)}),o=!!n.body.next,a=null;return n.body.next&&(a=new URL(n.body.next).searchParams.get("page")),{pageInfo:{hasNextPage:o,endCursor:a},data:n.body.values.map(i=>{let u=new Date(i.target.date);return{name:i.name,commit:{oid:i.target.hash,authoredDate:u,committedDate:u}}})}}async getWorkspacesForUser(s,e={}){let r=new URL(`${q}/user/permissions/workspaces`);r.searchParams.set("page",s.page?.toString()||"1"),r.searchParams.set("pagelen","50");let n=await this.config.request({url:r.toString(),headers:E(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={}){let r=new URL(`${q}/workspaces/${s.workspaceSlug}/pullrequests/${s.userId}`);if(r.searchParams.set("fields","+values.participants,+values.destination.repository.links.clone.*,+values.source.repository.links.clone.*"),r.searchParams.set("page",s.page?.toString()||"1"),r.searchParams.set("pagelen","50"),s.repos&&s.repos.length>0){let a=`state = "open" AND (${s.repos.map(i=>`source.repository.full_name = "${i.namespace}/${i.name}"`).join(" OR ")})`;r.searchParams.set("q",a)}let n=await this.config.request({url:r.toString(),headers:E(this.config,e)}),o=!!n.body.next;return{pageInfo:{hasNextPage:o,nextPage:o?n.body.page+1:null},data:n.body.values.map(We)}}async getPullRequestsForRepoBase(s,e={}){let r=new URL(`${q}/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 ")})`),r.searchParams.set("fields","+values.participants,+values.destination.repository.links.clone.*,+values.source.repository.links.clone.*"),r.searchParams.set("page",s.page?.toString()||"1"),r.searchParams.set("pagelen","50"),r.searchParams.set("q",o),await this.config.request({url:r.toString(),headers:E(this.config,e)})}async getPullRequestsForRepo(s,e={}){let r=[],n=await this.getPullRequestsForRepoBase(s,e);n.body.values.forEach(a=>{r.push(We(a))});let o=!!n.body.next;return{pageInfo:{hasNextPage:o,nextPage:o?n.body.page+1:null},data:r}}async getPullRequestsForRepos(s,e={}){let r=[];return await Promise.all(s.repos.map(async n=>{try{(await this.getPullRequestsForRepoBase({repo:n,...s},e)).body.values.forEach(a=>{r.push(We(a))})}catch(o){if(o.statusCode!==404&&o.statusCode!==401)throw o}})),{data:r}}async getAccountsForWorkspace(s,e={}){let r=new URL(`${q}/workspaces/${encodeURI(s.workspace)}/members`);r.searchParams.set("page",s.page?.toString()||"1"),r.searchParams.set("pagelen","100");let n=await this.config.request({url:r.toString(),headers:E(this.config,e)}),o=!!n.body.next;return{pageInfo:{hasNextPage:o,nextPage:o?n.body.page+1:null},data:n.body.values.map(a=>ce(a.user))}}async getReposPermissionsForCurrentUser(s,e={}){let r=new URL(`${q}/user/permissions/repositories`);r.searchParams.set("page",s.page?.toString()||"1"),r.searchParams.set("pagelen","100");let n=await this.config.request({url:r.toString(),headers:E(this.config,e)}),o=!!n.body.next;return{pageInfo:{hasNextPage:o,nextPage:o?n.body.page+1:null},data:n.body.values.reduce((a,i)=>({...a,[i.repository.uuid]:Lr(i.permission)}),{})}}async decorateReposWithPermissions(s,e={}){let r={},n=1;do{let o=await this.getReposPermissionsForCurrentUser({page:n},e);r={...o.data,...r},n=o.pageInfo.hasNextPage?o.pageInfo.nextPage:null}while(n!==null);return{data:s.repos.map(o=>({...o,permissions:r[o.id]??{canCreateWebhook:!1,canPush:!1,isAdmin:!1}}))}}async closePullRequest(s,e={}){let{pullRequest:r}=s;if(!(await this.config.request({method:"POST",url:`${q}/repositories/${r.repository.owner.login}/${r.repository.name}/pullrequests/${r.id}/decline`,headers:E(this.config,e)})).body.title)throw new Error("Could not close pull request")}async mergePullRequest(s,e={}){let{pullRequest:r,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 a={merge_strategy:o,type:"pullrequest"};if(!(await this.config.request({method:"POST",url:`${q}/repositories/${r.repository.owner.login}/${r.repository.name}/pullrequests/${r.id}/merge`,body:JSON.stringify(a),headers:{...E(this.config,e),"Content-Type":"application/json"}})).body.title)throw new Error("Could not merge pull request")}async setPullRequestReviewers(s,e={}){let{pullRequest:r,reviewers:n}=s,o={reviewers:n.map(i=>{if(i.username)throw new Error('Bitbucket reviewer requires "username" for this function.');return{username:i.username}})};if(!(await this.config.request({method:"PUT",url:`${q}/repositories/${r.repository.owner.login}/${r.repository.name}/pullrequests/${r.id}`,body:JSON.stringify(o),headers:{...E(this.config,e),"Content-Type":"application/json"}})).body.title)throw new Error("Could not set pull request reviewers")}};var $t=t=>t?t.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}:t.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 oe=t=>{let s=t.links.self[0].href;return{name:t.displayName,email:t.emailAddress,avatarUrl:t.avatarUrl??(s&&`${s}/avatar.png`),id:t.id.toString(),username:t.name,url:s}},ge=t=>{let s={OPEN:"OPEN",MERGED:"MERGED",DECLINED:"CLOSED"},e={UNAPPROVED:"REVIEW_REQUESTED",NEEDS_WORK:"CHANGES_REQUESTED",APPROVED:"APPROVED"},r=t.reviewers.map(u=>({reviewer:oe(u.user),state:e[u.status]})),n=t.toRef.repository.links.clone.find(u=>u.name==="ssh")?.href??null,o=t.toRef.repository.links.clone.find(u=>u.name==="https")?.href??null;o||(o=t.toRef.repository.links.clone.find(u=>u.name==="http")?.href??null);let a=t.fromRef.repository.links.clone.find(u=>u.name==="ssh")?.href??null,i=t.fromRef.repository.links.clone.find(u=>u.name==="https")?.href??null;return i||(i=t.fromRef.repository.links.clone.find(u=>u.name==="http")?.href??null),{id:t.id.toString(),number:t.id,title:t.title,url:t.links.self[0].href,state:s[t.state],isDraft:!1,createdDate:new Date(t.createdDate),updatedDate:new Date(t.updatedDate),closedDate:t.closedDate?new Date(t.closedDate):null,mergedDate:t.state=="MERGED"&&t.closedDate?new Date(t.closedDate):null,baseRef:{name:t.toRef.displayId,oid:t.toRef.latestCommit},headRef:{name:t.fromRef.displayId,oid:t.fromRef.latestCommit},commentCount:t.properties.commentCount,upvoteCount:null,commitCount:null,fileCount:null,additions:null,deletions:null,author:oe(t.author.user),assignees:null,reviews:r,reviewDecision:G(r),repository:{id:t.toRef.repository.id.toString(),name:t.toRef.repository.name,owner:{login:t.toRef.repository.project.key},remoteInfo:o&&n?{cloneUrlHTTPS:o,cloneUrlSSH:n}:null},headRepository:{id:t.fromRef.repository.id.toString(),name:t.fromRef.repository.name,owner:{login:t.fromRef.repository.project.key},remoteInfo:i&&a?{cloneUrlHTTPS:i,cloneUrlSSH:a}:null},headCommit:null,mergeableState:"MERGEABLE",permissions:null,version:t.version}},Ut=t=>({id:t.id.toString(),namespace:t.project.key,name:t.slug,webUrl:t.links.self[0]?.href??null,httpsUrl:t.links.clone.find(s=>s.name==="https"||s.name==="http")?.href??null,sshUrl:t.links.clone.find(s=>s.name==="ssh")?.href??null,defaultBranch:null,permissions:null}),V=class extends L{getBaseUrl(s){let e=s.baseUrl||this.config.baseUrl;if(!e)throw new Error('Bitbucket Server requires "baseUrl"');return e}getRequestHeaders(s){return h(s.token||this.config.token)}async getCurrentUser(s={},e={}){let r=await this.config.request({url:`${this.getBaseUrl(e)}/users?limit=2`,headers:this.getRequestHeaders(e)}),{headers:{"x-auserid":n,"x-ausername":o}}=r,a=n?parseInt(n,10):null,i=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})=>a?a===d:i===c||i===p||i===g);if(!l)throw new Error("Could not find current Bitbucket Server user");return{data:oe(l)}}async getUserForCommit(s,e){let{repo:r,oid:n}=s,o=await this.config.request({url:`${this.getBaseUrl(e)}/projects/${r.namespace}/repos/${r.name}/commits/${n}`,headers:this.getRequestHeaders(e)});if(!o.body.author)throw new Error("Could not find user for commit");return{data:oe(o.body.author)}}async getRepo(s,e={}){let r=await this.config.request({url:`${this.getBaseUrl(e)}/projects/${s.namespace}/repos/${s.name}`,headers:this.getRequestHeaders(e)});return{data:Ut(r.body)}}async getRepos(s,e={}){let r=[],n=[];return await Promise.all(s.map(async o=>{try{let a=await this.getRepo(o,e);r.push(a.data)}catch(a){n.push({input:o,error:a})}})),{data:r,errors:n}}async getReposForCurrentUser(s,e={}){let r=s.page??0,n=await this.config.request({url:`${this.getBaseUrl(e)}/repos?start=${r}`,headers:this.getRequestHeaders(e)});return{pageInfo:{hasNextPage:!n.body.isLastPage,nextPage:n.body.nextPageStart},data:n.body.values.map(Ut)}}async getRepoPermissionsForUsername(s,e={}){let r=new URL(`${this.getBaseUrl(e)}/projects/${s.repo.namespace}/repos/${s.repo.name}/permissions/search?filterText=${s.username}`);try{let n=await this.config.request({url:r.toString(),headers:this.getRequestHeaders(e)});return{data:$t(n.body.values)}}catch(n){if(n.response?.status===401)return{data:{canCreateWebhook:!1,canPush:!1,isAdmin:!1}};throw n}}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={}){let r=new URL(`${this.getBaseUrl(e)}/projects/${encodeURI(s.repo.namespace)}/repos/${encodeURI(s.repo.name)}/pull-requests?state=OPEN`);return r.searchParams.set("start",s.page?.toString()||"0"),r.searchParams.set("limit","50"),await this.config.request({url:r.toString(),headers:this.getRequestHeaders(e)})}async getPullRequestsForRepo(s,e={}){let r=[],n=await this.getPullRequestsForRepoBase(s,e);n.body.values.forEach(a=>{if(s.authorLogin&&a.author.user.name!==s.authorLogin)return null;r.push(ge(a))});let o=n.body.values.length!==0;return{pageInfo:{hasNextPage:o,nextPage:o?n.body.start+n.body.values.length:null},data:r}}async getPullRequestsForRepos(s,e={}){let r=[];return await Promise.all(s.repos.map(async n=>{try{(await this.getPullRequestsForRepoBase({repo:n,...s},e)).body.values.forEach(a=>{if(s.authorLogin&&a.author.user.name!==s.authorLogin)return null;r.push(ge(a))})}catch(o){if(o.statusCode!==404&&o.statusCode!==401)throw o}})),{data:r}}async getPullRequestsForCurrentUser(s,e={}){let r=new URL(`${this.getBaseUrl(e)}/dashboard/pull-requests`);r.searchParams.set("state","OPEN"),r.searchParams.set("start",s.page?.toString()||"0"),r.searchParams.set("limit","50");let n=await this.config.request({url:r.toString(),headers:this.getRequestHeaders(e)}),o=n.body.values.length!==0;return{pageInfo:{hasNextPage:o,nextPage:o?n.body.start+n.body.values.length:null},data:n.body.values.map(ge)}}async closePullRequest(s,e={}){let{pullRequest:r}=s;if(r.version===void 0)throw new Error('Bitbucket Server requires "version" for this function.');if(!(await this.config.request({method:"POST",url:`${this.getBaseUrl(e)}/projects/${r.repository.owner.login}/repos/${r.repository.name}/pull-requests/${r.id}/decline`,body:JSON.stringify({version:r.version}),headers:{...this.getRequestHeaders(e),"Content-Type":"application/json"}})).body.title)throw new Error("Could not close pull request")}async mergePullRequest(s,e={}){let{pullRequest:r,mergeStrategyId:n}=s;if(s.mergeStrategy)throw new Error('Bitbucket Server uses "mergeStrategyId" instead of "mergeStrategy".');if(r.version===void 0)throw new Error('Bitbucket Server requires "version" for this function.');if(!(await this.config.request({method:"POST",url:`${this.getBaseUrl(e)}/projects/${r.repository.owner.login}/repos/${r.repository.name}/pull-requests/${r.id}/merge`,body:JSON.stringify({strategyId:n,version:r.version}),headers:{...this.getRequestHeaders(e),"Content-Type":"application/json"}})).body.title)throw new Error("Could not merge pull request")}async getMergeStrategies(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:r,reviewers:n}=s;if(r.version===void 0)throw new Error('Bitbucket Server requires "version" for this function.');let o={reviewers:n.map(i=>{if(i.username)throw new Error('Bitbucket Server reviewer requires "username" for this function.');return{user:{name:i.username}}}),version:r.version};if(!(await this.config.request({method:"PUT",url:`${this.getBaseUrl(e)}/projects/${r.repository.owner.login}/repos/${r.repository.name}/pull-requests/${r.id}`,body:JSON.stringify(o),headers:{...this.getRequestHeaders(e),"Content-Type":"application/json"}})).body.title)throw new Error("Could not set pull request reviewers")}async getAccountsForProject(s,e={}){let r=new URL(`${this.getBaseUrl(e)}/projects/${encodeURI(s.project)}/permissions/users`);r.searchParams.set("start",s.page?.toString()||"0"),r.searchParams.set("limit","50");let n=await this.config.request({url:r.toString(),headers:this.getRequestHeaders(e)}),o=n.body.values.length!==0;return{pageInfo:{hasNextPage:o,nextPage:o?n.body.start+n.body.values.length:null},data:n.body.values.map(a=>oe(a.user))}}};var Nt=require("js-base64");var me=(e=>(e.Open="OPEN",e.Closed="CLOSED",e))(me||{});var f=class extends Error{constructor(e,r){let n=r?.map(a=>`'${a.message}'`).join(", "),o=n?`${e}: ${n}`:e;super(o);this.graphQLErrors=r??[]}};var Dr={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]},At=15,Gt=100,C=t=>!!t,O=(t,s)=>{let e=Dr[s];for(let r=0;r<3;r++){if(t[r]>e[r])return!0;if(t[r]<e[r])return!1}return!0},fe="https://api.github.com",$r=`${fe}/graphql`,Ie=`
1
+ "use strict";var _e=Object.defineProperty;var cr=Object.getOwnPropertyDescriptor;var gr=Object.getOwnPropertyNames;var mr=Object.prototype.hasOwnProperty;var hr=(r,s)=>{for(var e in s)_e(r,e,{get:s[e],enumerable:!0})},fr=(r,s,e,t)=>{if(s&&typeof s=="object"||typeof s=="function")for(let n of gr(s))!mr.call(r,n)&&n!==e&&_e(r,n,{get:()=>s[n],enumerable:!(t=cr(s,n))||t.enumerable});return r};var Rr=r=>fr(_e({},"__esModule",{value:!0}),r);var js={};hr(js,{AzureDevOps:()=>H,Bitbucket:()=>J,BitbucketServer:()=>V,EntityIdentifierProviderType:()=>lr,EntityType:()=>ur,EntityVersion:()=>ir,GitBuildStatusStage:()=>Pt,GitBuildStatusState:()=>ue,GitDiffLineType:()=>Fe,GitHub:()=>X,GitHubIssueCloseReason:()=>pr,GitIssueState:()=>me,GitLab:()=>Y,GitMergeStrategy:()=>W,GitPullRequestMergeableState:()=>M,GitPullRequestReviewState:()=>F,GitPullRequestState:()=>z,GraphQLErrors:()=>f,Jira:()=>ee,JiraServer:()=>te,PullRequestAsyncStatus:()=>ar,Trello:()=>re,default:()=>Qs,isFetch:()=>le});module.exports=Rr(js);var Pt=(n=>(n.Build="build",n.Production="production",n.Staging="staging",n.Test="test",n))(Pt||{}),ue=(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))(ue||{}),W=(o=>(o.MergeCommit="MERGE_COMMIT",o.Rebase="REBASE",o.RebaseThenMergeCommit="REBASE_THEN_MERGE_COMMIT",o.FastForward="FAST_FORWARD",o.Squash="SQUASH",o))(W||{}),z=(t=>(t.Open="OPEN",t.Closed="CLOSED",t.Merged="MERGED",t))(z||{}),F=(n=>(n.Approved="APPROVED",n.ChangesRequested="CHANGES_REQUESTED",n.Commented="COMMENTED",n.ReviewRequested="REVIEW_REQUESTED",n))(F||{}),M=(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))(M||{}),Fe=(t=>(t.ADDED="ADDED",t.DELETED="DELETED",t.UNMODIFIED="UNMODIFIED",t))(Fe||{});var wt={APPROVED:0,COMMENTED:1,REVIEW_REQUESTED:2,CHANGES_REQUESTED:3},G=r=>!r||r.length===0?null:r.reduce((s,e)=>wt[e.state]>wt[s]?e.state:s,"APPROVED");var S=100;var St=globalThis.fetch;var Ir=async r=>{let s=r.headers.get("content-type")||"",e=null;if(s.startsWith("application/json")){let o=await r.text();e=o.trim().length>0?JSON.parse(o):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={};r.headers.forEach((o,a)=>{t[a]=o});let n={body:e,headers:t,status:r.status,statusText:r.statusText};if(!r.ok){let o=new Error(r.statusText);throw Object.assign(o,{response:n}),o}return n},Qe=r=>async({url:s,...e})=>{let t=await r(s,e);return Ir(t)};var le=(r,s=!1)=>r.name==="fetch"||s;var U=class{constructor(s){let e=s?.request||St;this.config={...s,request:le(e,s?.forceIsFetch)?Qe(e):e}}updateConfig(s){this.config={...this.config,...s,request:s.request&&le(s.request,s?.forceIsFetch??this.config.forceIsFetch)?Qe(s.request):this.config.request}}},L=class extends U{};var h=(r,s)=>{let e={};return r&&(e.Authorization=`${s?"Basic":"Bearer"} ${r}`),e},vt=r=>r?r.reduce((s,e)=>(s[e]=!0,s),{}):void 0,Q=(r,s,e)=>!r||s.some(t=>r[t])?e:"",qt=async r=>{let s=[],e=!0,t;for(;e;){let n=await r(t);s=s.concat(n.data),e=!!n?.pageInfo?.hasNextPage,t=n?.pageInfo?.endCursor||n?.pageInfo?.nextPage}return s};async function je(r){return(await Promise.allSettled(r)).map(e=>br(e)).filter(e=>e!=null)}function br(r,s=void 0){return r?.status==="fulfilled"?r.value:s}var yr="https://app.vssps.visualstudio.com/_apis",Pr="https://vssps.dev.azure.com/",wr="https://dev.azure.com",P=(r,s={})=>h(s.token||r.token,s.isPAT||r.isPAT),Et=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/"),Be=(r,s)=>{let e=s.baseUrl||r.baseUrl||yr;return e=e.replace(/\/$/,""),e},w=(r,s)=>{let e=s.baseUrl||r.baseUrl||wr;return e=e.replace(/\/$/,""),e},ze=(r,s)=>{let e=s.baseUrl||r.baseUrl||Pr;return e=e.replace(/\/$/,""),e};var Sr={active:"OPEN",completed:"MERGED",abandoned:"CLOSED"},vr={10:"APPROVED",5:"APPROVED",0:"REVIEW_REQUESTED",[-5]:"CHANGES_REQUESTED",[-10]:"CHANGES_REQUESTED"},Me=r=>({id:r.id,name:r.displayName??null,username:(r.uniqueName||r.displayName)??null,email:null,avatarUrl:r.imageUrl??null,url:null}),de=r=>r.startsWith("refs/heads/")?r.replace("refs/heads/",""):r,qr=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"}},pe=(r,s)=>{let e=[],t=[];return s.reviewers.forEach(n=>{let o={reviewer:Me(n),state:vr[n.vote??0]||"REVIEW_REQUESTED"};n.isRequired&&e.push(o),t.push(o)}),{id:s.pullRequestId.toString(),title:s.title,number:s.codeReviewId,state:Sr[s.status],isDraft:s.isDraft,commentCount:null,upvoteCount:null,author:Me(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:de(s.targetRefName),oid:s.lastMergeTargetCommit.commitId},headRef:{name:de(s.sourceRefName),oid:s.lastMergeSourceCommit.commitId},url:Et(s),assignees:s.reviewers.map(Me),reviews:t,reviewDecision:G(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:qr(s.mergeStatus),labels:s.labels?.map(n=>({color:null,description:null,id:n.id,name:n.name}))??[],permissions:null}},Ct=(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:de(s.defaultBranch)}:null,permissions:null}),Er=(r,s,e,t)=>{let n=e.fields,o=n["System.AssignedTo"],a=n["System.State"],i=n["System.WorkItemType"],u;return a&&i&&(u=t[i]?.[a]),{id:e.id.toString(),number:e.id.toString(),title:n["System.Title"],commentCount:n["System.CommentCount"],author:{avatarUrl:n["System.CreatedBy"]._links?.avatar?.href??null,email:null,id:n["System.CreatedBy"].id,name:n["System.CreatedBy"].uniqueName??null,username:n["System.CreatedBy"].displayName??null,url:null},closedDate:n["Microsoft.VSTS.Common.ClosedDate"]?new Date(n["Microsoft.VSTS.Common.ClosedDate"]):null,createdDate:new Date(n["System.CreatedDate"]),updatedDate:new Date(n["System.ChangedDate"]),url:e._links.html.href,assignees:o?[{avatarUrl:o._links?.avatar?.href??null,email:null,id:o.id,name:o.uniqueName??null,username:o.displayName??null,url:null}]:[],description:n["System.Description"]??null,state:{name:u?.title||a,color:null},type:n["System.WorkItemType"],repository:null,project:{namespace:r,name:s,resourceId:null,key:null,id:null},upvoteCount:0,labels:e.fields["System.Tags"]?.split(";").map(l=>({color:null,description:null,id:null,name:l.trim()}))??[]}},H=class extends L{async getCurrentUser(s={},e={}){if(e.isPAT||this.config.isPAT)throw new Error("Azure DevOps does not support PATs for this function.");let t=`${Be(this.config,e)}/profile/profiles/me`,n=await this.config.request({url:t,headers:P(this.config,e)});return{data:{id:n.body.id,name:n.body.displayName,username:n.body.displayName,email:n.body.emailAddress,avatarUrl:null,url:null}}}async getCurrentUserForInstance(s,e={}){let n=(await this.config.request({url:`${w(this.config,e)}/${encodeURIComponent(s.namespace)}/_apis/ConnectionData`,headers:P(this.config,e)})).body.authorizedUser;if(n.providerDisplayName==="Anonymous")throw new Error("Current user not found.");return{data:{id:n.id,name:n.providerDisplayName,username:n.providerDisplayName,email:n.properties.Account.$value,avatarUrl:null,url:null}}}async getUserForCommit(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:`${w(this.config,e)}/${encodeURIComponent(s.repo.namespace)}/${encodeURIComponent(s.repo.project)}/_apis/git/repositories/${encodeURIComponent(s.repo.name)}/commits/${s.oid}`,headers:P(this.config,e)})).body.author;return{data:{name:n.name,email:n.email,avatarUrl:n.imageUrl}}}async getOrgsForUser(s,e={}){let t=`${Be(this.config,e)}/accounts?memberId=${s.userId}&api-version=6.0`;return{data:(await this.config.request({url:t,headers:P(this.config,e)})).body.value.map(o=>({id:o.accountId,name:o.accountName}))}}async getCollectionsForUser(s,e={}){let t=`${w(this.config,e)}/_apis/projectCollections`;return{data:(await this.config.request({url:t,headers:P(this.config,e)})).body.value.map(o=>({id:o.id,name:o.name}))}}async getAzureProjects(s,e={}){let t=new URL(`${w(this.config,e)}/${encodeURIComponent(s.namespace)}/_apis/projects`);t.searchParams.set("$top",S.toString()),s.cursor&&t.searchParams.set("$skip",s.cursor);let n=await this.config.request({url:t.toString(),headers:P(this.config,e)}),o=n.headers["x-ms-continuationtoken"];return{pageInfo:{hasNextPage:!!o,endCursor:o||null},data:n.body.value.map(a=>({id:a.id,name:a.name,namespace:s.namespace}))}}async getAzureProjectScopeDescriptor(s,e={}){let{namespace:t,projectId:n}=s;return{data:{scope:(await this.config.request({url:`${ze(this.config,e)}/${encodeURIComponent(t)}/_apis/graph/descriptors/${n}?api-version=6.0`,headers:P(this.config,e)})).body.value}}}async getAzureGraphAccountsForAzureProject(s,e={}){let{namespace:t,projectScopeDescriptor:n,cursor:o}=s,a=new URL(`${ze(this.config,e)}/${encodeURIComponent(t)}/_apis/graph/users`);n&&a.searchParams.set("scopeDescriptor",n),o&&a.searchParams.set("continuationToken",o);let i=await this.config.request({url:a.toString(),headers:P(this.config,e)}),u=i.headers["x-ms-continuationtoken"];return{pageInfo:{endCursor:u||null,hasNextPage:!!u},data:i.body.value.map(l=>({avatarUrl:l._links?.avatar?.href??null,descriptor:l.descriptor??null,email:l.mailAddress??null,name:l.displayName??null,storageKeyURL:l._links?.storageKey?.href??null,username:l.displayName??null}))}}async getAccountFromAzureGraphAccount(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:P(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:`${w(this.config,e)}/${encodeURIComponent(s.namespace)}/${encodeURIComponent(s.project)}/_apis/git/repositories/${encodeURIComponent(s.name)}`,headers:P(this.config,e)});return{data:Ct(s.namespace,t.body)}}async getRepos(s,e={}){let t=[],n=[];return await Promise.all(s.map(async o=>{try{let a=await this.getRepo(o,e);t.push(a.data)}catch(a){n.push({input:o,error:a})}})),{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:`${w(this.config,e)}/${encodeURIComponent(s.namespace)}/${encodeURIComponent(s.project)}/_apis/git/repositories`,headers:P(this.config,e)})).body.value.map(n=>Ct(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(`${w(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",S.toString()),e.cursor&&n.searchParams.set("continuationToken",e.cursor);let o=await this.config.request({url:n.toString(),headers:P(this.config,t)}),a=o.headers["x-ms-continuationtoken"];return{pageInfo:{hasNextPage:!!a,endCursor:a||null},data:o.body.value.map(i=>({name:de(i.name),commit:{oid:i.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:a,authorLogin:i}=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 a&&a.length&&(l+=`&searchCriteria.reviewerId=${a[0]}`),i&&(l+=`&searchCriteria.creatorId=${i}`),await this.config.request({url:`${w(this.config,e)}/${encodeURIComponent(o.namespace)}/${encodeURIComponent(o.project||"")}/_apis/git/repositories/${encodeURIComponent(o.name)}/pullRequests?${l}&%24top=${t}&%24skip=${(u-1)*t}`,headers:P(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(a=>pe(s.repo.namespace,a))}}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(i=>{n.push(pe(o.namespace,i))})}catch(a){if(a.statusCode!==404&&a.statusCode!==401)throw a}})),{data:n}}async getPullRequestsForProjectBase(s,e={},t=100){let{namespace:n,project:o,page:a,assigneeLogins:i,authorLogin:u,repo:l}=s;if(l?.project&&l.project!==o)throw new Error("Could not fetch pull requests, project mismatch");let p=a||1,d=new URL(`${w(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?.id&&l?.project===o&&d.searchParams.set("searchCriteria.repositoryId",l.id),i&&i.length&&d.searchParams.set("searchCriteria.reviewerId",i[0]),u&&d.searchParams.set("searchCriteria.creatorId",u),await this.config.request({url:d.toString(),headers:P(this.config,e)})}async getPullRequestsForProject(s,e={}){let n=s.page||1,o=await this.getPullRequestsForProjectBase(s,e,100);return{pageInfo:{hasNextPage:o?.body.value.length===100,nextPage:n+1},data:o?.body.value.map(a=>pe(s.namespace,a))||[]}}async getPullRequestsForProjects(s,e={}){let{projects:t}=s||{},n=[];return await Promise.all(t.map(async o=>{try{(!s.repo||s.repo.project&&s.repo.project===o.project)&&(await this.getPullRequestsForProjectBase({...o,...s},e))?.body.value.forEach(i=>{n.push(pe(o.namespace,i))})}catch(a){if(a.statusCode!==404&&a.statusCode!==401)throw a}})),{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:a}=s,i=await this.config.request({url:`${w(this.config,e)}/${encodeURIComponent(t)}/${encodeURIComponent(n||"")}/_apis/git/repositories/${o}/pullrequests/${a}?includeCommits=true?api-version=6.0`,headers:{...P(this.config,e)}});if(!i.body.mergeStatus)throw new Error("Could not fetch pull request");return{data:i.body.mergeStatus}}async updatePullRequest(s,e,t){return await this.config.request({method:"PATCH",url:`${w(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:{...P(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={}){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 a={completionOptions:{mergeStrategy:o},lastMergeSourceCommit:{commitId:t.headRef?.oid},status:"completed"};if(!(await this.updatePullRequest(t,JSON.stringify(a),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:`${w(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:{...P(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:`${w(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:{...P(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 a of n)o.find(i=>i.id===a.id)||await this.addPullRequestLabel({pullRequest:t,label:a},e);for(let a of o)n.find(i=>a.id===i.id)||await this.removePullRequestLabel({pullRequest:t,label:a},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,a={id:n.id,isRequired:o};if(!(await this.config.request({method:"PUT",url:`${w(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(a),headers:{...P(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:`${w(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:{...P(this.config,e),Accept:"application/json"}})}async setPullRequestReviewers(s,e={}){let{pullRequest:t,reviewers:n}=s;for(let o of n)t.assignees.find(a=>a.id===o.id)||await this.addPullRequestReviewer({pullRequest:t,reviewer:o,isRequired:!0},e);for(let o of t.assignees)n.find(a=>o.id===a.id)||await this.removePullRequestReviewer({pullRequest:t,reviewer:o},e)}async getIssuesForAzureProject(s,e={}){let{page:t,assigneeLogins:n,authorLogin:o,mentionLogin:a,labelNames:i,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("'","''")}'`),a&&d.push("[System.Id] IN (@recentMentions)"),i&&i.forEach(I=>d.push(`[System.Tags] Contains '${I}'`));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:`${w(this.config,e)}/${encodeURIComponent(s.namespace)}/${encodeURIComponent(s.project)}/_apis/wit/wiql?api-version=6.0`,body:JSON.stringify({query:c}),method:"POST",headers:{...P(this.config,e),"Content-Type":"application/json"}}),m=g.body.workItems.slice((l-1)*p,p*l).map(I=>I.id);if(m.length==0)return{pageInfo:{hasNextPage:!1,nextPage:null},data:[]};let b=await this.config.request({url:`${w(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:{...P(this.config,e),"Content-Type":"application/json"}});return{pageInfo:{hasNextPage:g.body.workItems.length>p*l,nextPage:l+1},data:b.body.value.map(I=>Er(s.namespace,s.project,I,u||{}))}}async getPermissionsForRepos(s,e={}){let{namespace:t,repos:n}=s,o={4:["canPush","canCreateWebhook"],1024:["isAdmin"],2048:["isAdmin"],4096:["isAdmin"],8192:["isAdmin"]},a=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}))},i={alwaysAllowAdministrators:!1,evaluations:n.flatMap(a)};return{data:(await this.config.request({method:"POST",url:`${w(this.config,e)}/${encodeURIComponent(t)}/_apis/security/permissionevaluationbatch?api-version=7.0`,body:JSON.stringify(i),headers:{...P(this.config,e),"Content-Type":"application/json"}})).body.evaluations.reduce((p,d)=>{let[,c,g]=d.token.split("/"),m=`${c}/${g}`,b=o[d.permissions];for(let I of b)p[m]===void 0&&(p[m]={canCreateWebhook:!0,canPush:!0,isAdmin:!0}),d.value===!1&&(p[m][I]=!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(a=>({...a,permissions:o.data[`${a.projectId}/${a.id}`]}))}}async updateIssue(s,e,t={}){return await this.config.request({method:"PATCH",url:`${w(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:{...P(this.config,t),"Content-Type":"application/json-patch+json"}})}async setIssueStatus(s,e={}){let{issue:t,status:n}=s,o=[{op:"add",path:"/fields/System.State",value:n.name}];if(!(await this.updateIssue(t,o,e)).body.fields?.["System.State"])throw new Error("Could not set issue status")}async setIssueAssignee(s,e={}){let{issue:t,assignee:n}=s,o=[{op:"add",path:"/fields/System.AssignedTo",value:n?.name??""}];if(!(await this.updateIssue(t,o,e)).body.fields?.["System.State"])throw new Error("Could not set issue assignee")}async setIssueLabels(s,e={}){let{issue:t,labels:n}=s,a=[{op:"replace",path:"/fields/System.Tags",value:n.map(u=>u.name).join(";")}];if(!(await this.updateIssue(t,a,e)).body.fields?.["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:`${w(this.config,e)}/${encodeURIComponent(t)}/${encodeURIComponent(n||"")}/_apis/wit/workitemtypes?api-version=6.0`,headers:{...P(this.config,e)}})).body.value}}async getLabelsForProject(s,e={}){let{namespace:t,project:n}=s;return{data:(await this.config.request({url:`${w(this.config,e)}/${encodeURIComponent(t)}/${encodeURIComponent(n||"")}/_apis/wit/tags?api-version=6.0`,headers:{...P(this.config,e)}})).body.value.map(a=>({color:null,description:null,id:a.id,name:a.name,url:a.url}))}}};var q=(r,s={})=>h(s.token||r.token,s.isPAT||r.isPAT);var E="https://api.bitbucket.org/2.0",Cr={OPEN:"OPEN",MERGED:"MERGED",DECLINED:"CLOSED"},ce=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}),Lt=r=>{let s=r.links.clone,e=s?.find(n=>n.name==="ssh"),t=s?.find(n=>n.name==="https");return e&&t?{cloneUrlHTTPS:t.href,cloneUrlSSH:e.href}:null},Dt=r=>({id:r.uuid,namespace:r.workspace.slug,name:r.slug,webUrl:r.links.html.href,httpsUrl:r.links.clone.find(s=>s.name==="https")?.href??null,sshUrl:r.links.clone.find(s=>s.name==="ssh")?.href??null,defaultBranch:{name:r.mainbranch.name},permissions:null}),We=r=>{let s=r.id,e=r.participants?.map(t=>{let n="REVIEW_REQUESTED";return t.approved?n="APPROVED":t.state==="changes_requested"?n="CHANGES_REQUESTED":t.participated_on!==null&&(n="COMMENTED"),{reviewer:ce(t.user),state:n}})??[];return{id:s.toString(),title:r.title,number:s,state:Cr[r.state],isDraft:!1,commentCount:r.comment_count,upvoteCount:null,author:ce(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:Lt(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:G(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:Lt(r.source.repository)},mergeableState:"MERGEABLE",permissions:null}},Lr=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}}},J=class extends U{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:`${E}/user`,headers:q(this.config,e)});return{data:ce(t.body)}}async getUserForCommit(s,e={}){let n=(await this.config.request({url:`${E}/repositories/${s.repo.namespace}/${s.repo.name}/commit/${s.oid}`,headers:q(this.config,e)})).body.author,o=n.raw.match(/([^<]+)<(.+)>/);return{data:{name:o?o[1].trim():null,email:o?o[2]:null,avatarUrl:n.user?.links.avatar.href||null}}}async getRepo(s,e={}){let t=await this.config.request({url:`${E}/repositories/${s.namespace}/${s.name}`,headers:q(this.config,e)});return{data:Dt(t.body)}}async getRepos(s,e={}){let t=[],n=[];return await Promise.all(s.map(async o=>{try{let a=await this.getRepo(o,e);t.push(a.data)}catch(a){n.push({input:o,error:a})}})),{data:t,errors:n}}async getReposForCurrentUser(s,e={}){let t=new URL(`${E}/repositories`);t.searchParams.set("role","member"),t.searchParams.set("pagelen",S.toString()),s.cursor&&t.searchParams.set("after",s.cursor);let n=await this.config.request({url:t.toString(),headers:q(this.config,e)}),o=!!n.body.next,a=null;return n.body.next&&(a=new URL(n.body.next).searchParams.get("after")),{pageInfo:{hasNextPage:o,endCursor:a},data:n.body.values.map(Dt)}}async getBranches(s,e={}){let t=new URL(`${E}/repositories/${s.repo.namespace}/${s.repo.name}/refs/branches`);t.searchParams.set("page",s.page?.toString()||"1"),t.searchParams.set("pagelen",S.toString());let n=await this.config.request({url:t.toString(),headers:q(this.config,e)}),o=!!n.body.next;return{pageInfo:{hasNextPage:o,nextPage:o?n.body.page+1:null},data:n.body.values.map(a=>{let i=new Date(a.target.date);return{name:a.name,commit:{oid:a.target.hash,authoredDate:i,committedDate:i}}})}}async getTags(s,e={}){let t=new URL(`${E}/repositories/${s.repo.namespace}/${s.repo.name}/refs/tags`);t.searchParams.set("pagelen",S.toString()),s.cursor&&t.searchParams.set("page",s.cursor);let n=await this.config.request({url:t.toString(),headers:q(this.config,e)}),o=!!n.body.next,a=null;return n.body.next&&(a=new URL(n.body.next).searchParams.get("page")),{pageInfo:{hasNextPage:o,endCursor:a},data:n.body.values.map(i=>{let u=new Date(i.target.date);return{name:i.name,commit:{oid:i.target.hash,authoredDate:u,committedDate:u}}})}}async getWorkspacesForUser(s,e={}){let t=new URL(`${E}/user/permissions/workspaces`);t.searchParams.set("page",s.page?.toString()||"1"),t.searchParams.set("pagelen","50");let n=await this.config.request({url:t.toString(),headers:q(this.config,e)}),o=!!n.body.next;return{pageInfo:{hasNextPage:o,nextPage:o?n.body.page+1:null},data:n.body.values.map(a=>({id:a.workspace.uuid,slug:a.workspace.slug,name:a.workspace.name}))}}async getPullRequestsForUserAndWorkspace(s,e={}){let t=new URL(`${E}/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",s.page?.toString()||"1"),t.searchParams.set("pagelen","50"),s.repos&&s.repos.length>0){let a=`state = "open" AND (${s.repos.map(i=>`source.repository.full_name = "${i.namespace}/${i.name}"`).join(" OR ")})`;t.searchParams.set("q",a)}let n=await this.config.request({url:t.toString(),headers:q(this.config,e)}),o=!!n.body.next;return{pageInfo:{hasNextPage:o,nextPage:o?n.body.page+1:null},data:n.body.values.map(We)}}async getPullRequestsForRepoBase(s,e={}){let t=new URL(`${E}/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",s.page?.toString()||"1"),t.searchParams.set("pagelen","50"),t.searchParams.set("q",o),await this.config.request({url:t.toString(),headers:q(this.config,e)})}async getPullRequestsForRepo(s,e={}){let t=[],n=await this.getPullRequestsForRepoBase(s,e);n.body.values.forEach(a=>{t.push(We(a))});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(a=>{t.push(We(a))})}catch(o){if(o.statusCode!==404&&o.statusCode!==401)throw o}})),{data:t}}async getAccountsForWorkspace(s,e={}){let t=new URL(`${E}/workspaces/${encodeURI(s.workspace)}/members`);t.searchParams.set("page",s.page?.toString()||"1"),t.searchParams.set("pagelen","100");let n=await this.config.request({url:t.toString(),headers:q(this.config,e)}),o=!!n.body.next;return{pageInfo:{hasNextPage:o,nextPage:o?n.body.page+1:null},data:n.body.values.map(a=>ce(a.user))}}async getReposPermissionsForCurrentUser(s,e={}){let t=new URL(`${E}/user/permissions/repositories`);t.searchParams.set("page",s.page?.toString()||"1"),t.searchParams.set("pagelen","100");let n=await this.config.request({url:t.toString(),headers:q(this.config,e)}),o=!!n.body.next;return{pageInfo:{hasNextPage:o,nextPage:o?n.body.page+1:null},data:n.body.values.reduce((a,i)=>({...a,[i.repository.uuid]:Lr(i.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:`${E}/repositories/${t.repository.owner.login}/${t.repository.name}/pullrequests/${t.id}/decline`,headers:q(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 a={merge_strategy:o,type:"pullrequest"};if(!(await this.config.request({method:"POST",url:`${E}/repositories/${t.repository.owner.login}/${t.repository.name}/pullrequests/${t.id}/merge`,body:JSON.stringify(a),headers:{...q(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(i=>{if(i.username)throw new Error('Bitbucket reviewer requires "username" for this function.');return{username:i.username}})};if(!(await this.config.request({method:"PUT",url:`${E}/repositories/${t.repository.owner.login}/${t.repository.name}/pullrequests/${t.id}`,body:JSON.stringify(o),headers:{...q(this.config,e),"Content-Type":"application/json"}})).body.title)throw new Error("Could not set pull request reviewers")}};var $t=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 oe=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}},ge=r=>{let s={OPEN:"OPEN",MERGED:"MERGED",DECLINED:"CLOSED"},e={UNAPPROVED:"REVIEW_REQUESTED",NEEDS_WORK:"CHANGES_REQUESTED",APPROVED:"APPROVED"},t=r.reviewers.map(u=>({reviewer:oe(u.user),state:e[u.status]})),n=r.toRef.repository.links.clone.find(u=>u.name==="ssh")?.href??null,o=r.toRef.repository.links.clone.find(u=>u.name==="https")?.href??null;o||(o=r.toRef.repository.links.clone.find(u=>u.name==="http")?.href??null);let a=r.fromRef.repository.links.clone.find(u=>u.name==="ssh")?.href??null,i=r.fromRef.repository.links.clone.find(u=>u.name==="https")?.href??null;return i||(i=r.fromRef.repository.links.clone.find(u=>u.name==="http")?.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:oe(r.author.user),assignees:null,reviews:t,reviewDecision:G(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:i&&a?{cloneUrlHTTPS:i,cloneUrlSSH:a}:null},headCommit:null,mergeableState:"MERGEABLE",permissions:null,version:r.version}},Ut=r=>({id:r.id.toString(),namespace:r.project.key,name:r.slug,webUrl:r.links.self[0]?.href??null,httpsUrl:r.links.clone.find(s=>s.name==="https"||s.name==="http")?.href??null,sshUrl:r.links.clone.find(s=>s.name==="ssh")?.href??null,defaultBranch:null,permissions:null}),V=class extends L{getBaseUrl(s){let e=s.baseUrl||this.config.baseUrl;if(!e)throw new Error('Bitbucket Server requires "baseUrl"');return e}getRequestHeaders(s){return h(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,a=n?parseInt(n,10):null,i=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})=>a?a===d:i===c||i===p||i===g);if(!l)throw new Error("Could not find current Bitbucket Server user");return{data:oe(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:oe(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:Ut(t.body)}}async getRepos(s,e={}){let t=[],n=[];return await Promise.all(s.map(async o=>{try{let a=await this.getRepo(o,e);t.push(a.data)}catch(a){n.push({input:o,error:a})}})),{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(Ut)}}async getRepoPermissionsForUsername(s,e={}){let t=new URL(`${this.getBaseUrl(e)}/projects/${s.repo.namespace}/repos/${s.repo.name}/permissions/search?filterText=${s.username}`);try{let n=await this.config.request({url:t.toString(),headers:this.getRequestHeaders(e)});return{data:$t(n.body.values)}}catch(n){if(n.response?.status===401)return{data:{canCreateWebhook:!1,canPush:!1,isAdmin:!1}};throw n}}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={}){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",s.page?.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(a=>{if(s.authorLogin&&a.author.user.name!==s.authorLogin)return null;t.push(ge(a))});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(a=>{if(s.authorLogin&&a.author.user.name!==s.authorLogin)return null;t.push(ge(a))})}catch(o){if(o.statusCode!==404&&o.statusCode!==401)throw o}})),{data:t}}async getPullRequestsForCurrentUser(s,e={}){let t=new URL(`${this.getBaseUrl(e)}/dashboard/pull-requests`);t.searchParams.set("state","OPEN"),t.searchParams.set("start",s.page?.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(ge)}}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(i=>{if(i.username)throw new Error('Bitbucket Server reviewer requires "username" for this function.');return{user:{name:i.username}}}),version:t.version};if(!(await this.config.request({method:"PUT",url:`${this.getBaseUrl(e)}/projects/${t.repository.owner.login}/repos/${t.repository.name}/pull-requests/${t.id}`,body:JSON.stringify(o),headers:{...this.getRequestHeaders(e),"Content-Type":"application/json"}})).body.title)throw new Error("Could not set pull request reviewers")}async getAccountsForProject(s,e={}){let t=new URL(`${this.getBaseUrl(e)}/projects/${encodeURI(s.project)}/permissions/users`);t.searchParams.set("start",s.page?.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(a=>oe(a.user))}}};var Nt=require("js-base64");var me=(e=>(e.Open="OPEN",e.Closed="CLOSED",e))(me||{});var f=class extends Error{constructor(e,t){let n=t?.map(a=>`'${a.message}'`).join(", "),o=n?`${e}: ${n}`:e;super(o);this.graphQLErrors=t??[]}};var Dr={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]},At=15,Gt=100,C=r=>!!r,O=(r,s)=>{let e=Dr[s];for(let t=0;t<3;t++){if(r[t]>e[t])return!0;if(r[t]<e[t])return!1}return!0},fe="https://api.github.com",$r=`${fe}/graphql`,Re=`
2
2
  description
3
3
  dueOn
4
4
  id
@@ -15,26 +15,26 @@ url
15
15
  permalink
16
16
  startedAt
17
17
  }
18
- `,he=/\/api\/v\d+$/,Re=`
18
+ `,he=/\/api\/v\d+$/,Ie=`
19
19
  color
20
20
  description
21
21
  id
22
22
  name
23
- `,Tt=t=>{if(t.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.")},Ar=(t,s)=>{let e=s.baseUrl||t.baseUrl;return e?(e=e.replace(/\/$/,""),Tt(e),he.test(e)&&(e=e.replace(he,"")),`${e}/api/graphql`):$r},K=(t,s)=>{let e=s.baseUrl||t.baseUrl;return e?(e=e.replace(/\/$/,""),Tt(e),he.test(e)&&(e=e.replace(he,"")),`${e}/api/v3`):fe},I=(t,s,e)=>{let r=h(e.token||t.token);return r["X-Github-Next-Global-ID"]="1",r["Content-Type"]="application/json",r.Accept="application/vnd.github.merge-info-preview+json",t.request({url:Ar(t,e),method:"POST",headers:r,body:JSON.stringify(s)})},Gr={user:!0,"user:email":!0,"read:user":!0},x=t=>t.some(s=>Gr[s]),D=(t=!1,s=!1,e)=>`
23
+ `,Tt=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.")},Ar=(r,s)=>{let e=s.baseUrl||r.baseUrl;return e?(e=e.replace(/\/$/,""),Tt(e),he.test(e)&&(e=e.replace(he,"")),`${e}/api/graphql`):$r},K=(r,s)=>{let e=s.baseUrl||r.baseUrl;return e?(e=e.replace(/\/$/,""),Tt(e),he.test(e)&&(e=e.replace(he,"")),`${e}/api/v3`):fe},R=(r,s,e)=>{let t=h(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:Ar(r,e),method:"POST",headers:t,body:JSON.stringify(s)})},Gr={user:!0,"user:email":!0,"read:user":!0},x=r=>r.some(s=>Gr[s]),D=(r=!1,s=!1,e)=>`
24
24
  __typename
25
25
  ${Q(e,["graphQLId"],"id")}
26
26
  ${Q(e,["id"],"databaseId")}
27
27
  ${Q(e,["name"],"name")}
28
28
  ${Q(e,["name","username"],"login")}
29
29
  ${s?Q(e,["email"],"email"):""}
30
- ${Q(e,["avatarUrl"],`avatarUrl${t?"(size: $avatarSize)":""}`)}
30
+ ${Q(e,["avatarUrl"],`avatarUrl${r?"(size: $avatarSize)":""}`)}
31
31
  ${Q(e,["url"],"url")}
32
- `,Tr=(t=!1)=>`
32
+ `,Tr=(r=!1)=>`
33
33
  latestReviews(first: 100) {
34
34
  nodes {
35
35
  author {
36
36
  ... on User {
37
- ${D(!1,t)}
37
+ ${D(!1,r)}
38
38
  }
39
39
  ... on EnterpriseUserAccount {
40
40
  ${He(!1)}
@@ -43,20 +43,20 @@ latestReviews(first: 100) {
43
43
  state
44
44
  }
45
45
  }
46
- `,Ot=(t=!1)=>`
46
+ `,Ot=(r=!1)=>`
47
47
  __typename
48
48
  id
49
49
  databaseId
50
50
  login
51
- avatarUrl${t?"(size: $avatarSize)":""}
51
+ avatarUrl${r?"(size: $avatarSize)":""}
52
52
  url
53
- `,He=(t=!1)=>`
53
+ `,He=(r=!1)=>`
54
54
  __typename
55
55
  id
56
56
  login
57
- avatarUrl${t?"(size: $avatarSize)":""}
57
+ avatarUrl${r?"(size: $avatarSize)":""}
58
58
  url
59
- `,be=(t,s=!1,e)=>`
59
+ `,be=(r,s=!1,e)=>`
60
60
  id
61
61
  ${!e||O(e,"PR_FULL_DATABASE_ID")?"fullDatabaseId":"databaseId"}
62
62
  number
@@ -131,7 +131,7 @@ headRepository {
131
131
  url
132
132
  sshUrl
133
133
  }
134
- ${t?"isDraft":""}
134
+ ${r?"isDraft":""}
135
135
  url
136
136
  createdAt
137
137
  comments {
@@ -165,21 +165,21 @@ changedFiles
165
165
  mergeable
166
166
  mergeStateStatus
167
167
  milestone {
168
- ${Ie}
168
+ ${Re}
169
169
  }
170
170
  labels(first: 100) {
171
171
  nodes {
172
- ${Re}
172
+ ${Ie}
173
173
  }
174
174
  }
175
175
  ${!e||O(e,"VIEWER_CAN_MERGE_AS_ADMIN")?"viewerCanMergeAsAdmin":""}
176
- `,Or=(t=!1,s)=>`
176
+ `,Or=(r=!1,s)=>`
177
177
  id
178
178
  ${!s||O(s,"ISSUE_FULL_DATABASE_ID")?"fullDatabaseId":"databaseId"}
179
179
  title
180
180
  author {
181
181
  ... on User {
182
- ${D(!1,t)}
182
+ ${D(!1,r)}
183
183
  }
184
184
  ... on Bot {
185
185
  ${Ot(!1)}
@@ -209,39 +209,39 @@ comments {
209
209
  }
210
210
  assignees(first: 100) {
211
211
  nodes {
212
- ${D(!1,t)}
212
+ ${D(!1,r)}
213
213
  }
214
214
  }
215
215
  state
216
216
  milestone {
217
- ${Ie}
217
+ ${Re}
218
218
  }
219
219
  labels(first: 100) {
220
220
  nodes {
221
- ${Re}
221
+ ${Ie}
222
222
  }
223
223
  }
224
- `,xr={"-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"},kr=new RegExp('(([^\\s]+:)?\\"(?:[^\\"\\\\]|\\\\.)*\\"?)|([^\\"\\s]+)',"g"),Je=t=>{let s=[];return(t.match(kr)??[]).forEach(r=>{if(r.includes(":")&&r!="is:closed"){let n=r.split(":")[0];xr[n]&&s.push(r)}}),s},Ve=(t,s,e,r)=>{let n=t==="issue";return{query:`
224
+ `,xr={"-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"},kr=new RegExp('(([^\\s]+:)?\\"(?:[^\\"\\\\]|\\\\.)*\\"?)|([^\\"\\s]+)',"g"),Je=r=>{let s=[];return(r.match(kr)??[]).forEach(t=>{if(t.includes(":")&&t!="is:closed"){let n=t.split(":")[0];xr[n]&&s.push(t)}}),s},Ve=(r,s,e,t)=>{let n=r==="issue";return{query:`
225
225
  query SearchIssuesOrPullRequests($query: String! $after: String) {
226
- search(type:ISSUE query:$query first: ${r.maxPageSize} after:$after) {
226
+ search(type:ISSUE query:$query first: ${t.maxPageSize} after:$after) {
227
227
  pageInfo {
228
228
  hasNextPage
229
229
  endCursor
230
230
  }
231
231
  nodes {
232
232
  ... on ${n?"Issue":"PullRequest"} {
233
- ${n?Or(r.supportsEmail,r.enterpriseVersion??null):be(r.supportsDrafts??!1,r.supportsEmail,r.enterpriseVersion??null)}
233
+ ${n?Or(t.supportsEmail,t.enterpriseVersion??null):be(t.supportsDrafts??!1,t.supportsEmail,t.enterpriseVersion??null)}
234
234
  }
235
235
  }
236
236
  }
237
- }`,variables:{query:`is:${t} is:open ${r.includeFromArchivedRepos?"":"archived:false"} ${s}`,after:e}}},Nr="Field 'isDraft' doesn't exist on type 'PullRequest'",ye=(t=[])=>t.some(s=>s?.message===Nr),_r=/@@ -(\d+)(?:,\d+ | )\+(\d+)(?:,\d+ | )@@(?:\\n)?/,Fr=`
237
+ }`,variables:{query:`is:${r} is:open ${t.includeFromArchivedRepos?"":"archived:false"} ${s}`,after:e}}},Nr="Field 'isDraft' doesn't exist on type 'PullRequest'",ye=(r=[])=>r.some(s=>s?.message===Nr),_r=/@@ -(\d+)(?:,\d+ | )\+(\d+)(?:,\d+ | )@@(?:\\n)?/,Fr=`
238
238
  \
239
- +`,xt=(t,s,e,r)=>{let n=_r.exec(t);if(!n||!n[0]||!n[1])return[];let o=parseInt(n[1],10),a=parseInt(n[2],10),i=t.replace(Fr,`
239
+ +`,xt=(r,s,e,t)=>{let n=_r.exec(r);if(!n||!n[0]||!n[1])return[];let o=parseInt(n[1],10),a=parseInt(n[2],10),i=r.replace(Fr,`
240
240
  +`).split(`
241
241
  `).slice(1),u=o-1,l=a-1,p=i.map(g=>{let m,b;switch(g[0]){case"-":{m="DELETED",u+=1,b=`${g.slice(1)}
242
242
  `;break}case"+":{m="ADDED",l+=1,b=`${g.slice(1)}
243
243
  `;break}default:m="UNMODIFIED",l+=1,u+=1,b=`${g}
244
- `}return{line:b,oldLineNumber:m!=="ADDED"?u:null,newLineNumber:m!=="DELETED"?l:null,type:m}}),d=e,c=s;if(d!==null&&c!==null&&r!==null&&d<c){let g=0,m=p.length,b=r==="LEFT"?"oldLineNumber":"newLineNumber";for(let R=0;R<p.length;R++){let se=p[R][b];se===d?g=R:se===c&&(m=R)}p=p.slice(g,m+1)}return p};var Ke=`
244
+ `}return{line:b,oldLineNumber:m!=="ADDED"?u:null,newLineNumber:m!=="DELETED"?l:null,type:m}}),d=e,c=s;if(d!==null&&c!==null&&t!==null&&d<c){let g=0,m=p.length,b=t==="LEFT"?"oldLineNumber":"newLineNumber";for(let I=0;I<p.length;I++){let se=p[I][b];se===d?g=I:se===c&&(m=I)}p=p.slice(g,m+1)}return p};var Ke=`
245
245
  id
246
246
  databaseId
247
247
  owner {
@@ -254,13 +254,13 @@ defaultBranchRef {
254
254
  name
255
255
  }
256
256
  viewerPermission
257
- `,Ye={__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"},Qr={APPROVED:"APPROVED",CHANGES_REQUESTED:"CHANGES_REQUESTED",COMMENTED:"COMMENTED",REVIEW_REQUESTED:"REVIEW_REQUESTED"},jr={MERGEABLE:"MERGEABLE",CONFLICTING:"CONFLICTS",UNKNOWN:"UNKNOWN"},Br={BEHIND:"BEHIND",BLOCKED:"BLOCKED",UNKNOWN:"UNKNOWN_AND_BLOCKED",UNSTABLE:"UNSTABLE",CLEAN:null,DIRTY:null,DRAFT:null,HAS_HOOKS:null},zr={OPEN:"OPEN",CLOSED:"CLOSED"},Mr=["ADMIN","MAINTAIN","TRIAGE","WRITE"],et=t=>({color:`#${t.color}`,description:t.description,graphQLId:t.id,id:null,name:t.name}),Wr=t=>({canCreateWebhook:t==="ADMIN",canPush:t==="ADMIN"||t==="MAINTAIN"||t==="WRITE",isAdmin:t==="ADMIN"}),Xe=t=>({id:t.databaseId.toString(),graphQLId:t.id,namespace:t.owner.login,name:t.name,webUrl:t.url,httpsUrl:t.url.endsWith(".git")?t.url:`${t.url}.git`,sshUrl:t.sshUrl,defaultBranch:t.defaultBranchRef,permissions:Wr(t.viewerPermission)}),Hr=t=>({canCreateWebhook:t.admin,canPush:t.admin||t.maintain||t.push,isAdmin:t.admin}),kt=t=>({id:t.id.toString(),graphQLId:t.node_id,namespace:t.owner.login,name:t.name,webUrl:t.html_url,httpsUrl:t.clone_url,sshUrl:t.ssh_url,defaultBranch:{name:t.default_branch},permissions:Hr(t.permissions)}),Jr=t=>({path:t.path,isDirectory:t.type==="tree"}),Vr={OPEN:"OPEN",CLOSED:"CLOSED",MERGED:"MERGED"},Kr={id:!0,graphQLId:!0,name:!0,username:!0,email:!0,avatarUrl:!0,url:!0},A=(t,s=Kr)=>{let e={};return s.id&&(e.id="databaseId"in t?t.databaseId.toString():t.id),s.graphQLId&&(e.graphQLId=t.id),s.name&&(e.name=t.name??t.login),s.username&&(e.username=t.login),s.email&&(e.email=t.email??null),s.avatarUrl&&(e.avatarUrl=t.avatarUrl),s.url&&(e.url=t.url),e},Xr=(t,s)=>{let e={IN_PROGRESS:"RUNNING",PENDING:"PENDING",QUEUED:"PENDING",REQUESTED:"PENDING",WAITING:"PENDING"};return t!=="COMPLETED"?e[t]:{ACTION_REQUIRED:"ACTION_REQUIRED",CANCELLED:"CANCELLED",FAILURE:"FAILED",NEUTRAL:null,SKIPPED:"SKIPPED",STALE:"FAILED",STARTUP_FAILURE:"FAILED",SUCCESS:"SUCCESS",TIMED_OUT:"ERROR"}[s]},Zr=t=>({ERROR:"ERROR",EXPECTED:"PENDING",FAILURE:"FAILED",PENDING:"PENDING",SUCCESS:"SUCCESS"})[t],Ze=t=>{let s=null;t.author?s=t.author:s=Ye;let e=(t.reviewRequests?.nodes||[]).filter(C).filter(a=>!a.asCodeOwner),r=t.headRepository?.url;r&&!r.endsWith(".git")&&(r=`${r}.git`);let n=t.repository?.url;n&&!n.endsWith(".git")&&(n=`${n}.git`);let o=e.filter(a=>a.requestedReviewer&&"__typename"in a.requestedReviewer).map(a=>({reviewer:A(a.requestedReviewer),state:"REVIEW_REQUESTED"})).concat((t.latestReviews?.nodes||[]).filter(C).map(a=>{let i=Ye;return a.author&&a.author.__typename&&(i=a.author),{reviewer:A(i),state:Qr[a.state]}}));return{id:t.fullDatabaseId!==void 0?t.fullDatabaseId:t.databaseId.toString(),graphQLId:t.id,title:t.title,number:t.number,state:Vr[t.state],commentCount:t.comments.totalCount,upvoteCount:t.reactions.totalCount,author:s&&s.__typename?A(s):null,createdDate:new Date(t.createdAt),isDraft:t.isDraft,repository:{id:t.repository.databaseId.toString(),graphQLId:t.repository.id,name:t.repository.name,owner:{login:t.repository.owner.login},remoteInfo:{cloneUrlHTTPS:n,cloneUrlSSH:t.repository.sshUrl}},headRepository:t.headRepository?{id:t.headRepository.databaseId.toString(),graphQLId:t.headRepository.id,name:t.headRepository.name,owner:{login:t.headRepository.owner.login},remoteInfo:{cloneUrlHTTPS:r,cloneUrlSSH:t.headRepository.sshUrl}}:null,headCommit:{buildStatuses:t.commits.nodes?.filter(C)[0]?.commit.statusCheckRollup?.contexts.nodes?.filter(C).map(a=>"context"in a?{completedAt:null,description:a.description,name:a.context,state:Zr(a.state),startedAt:new Date(a.createdAt),stage:null,url:a.targetUrl}:{completedAt:a.completedAt?new Date(a.completedAt):null,description:null,name:a.name,state:Xr(a.status,a.conclusion),startedAt:a.startedAt?new Date(a.startedAt):null,stage:null,url:a.permalink})??[]},headRef:t.headRef?{name:t.headRef.name,oid:t.headRef.target?.oid??null}:null,baseRef:t.baseRef?{name:t.baseRef.name,oid:t.baseRef.target?.oid??null}:null,url:t.url,updatedDate:new Date(t.updatedAt),closedDate:t.closedAt?new Date(t.closedAt):null,mergedDate:t.mergedAt?new Date(t.mergedAt):null,assignees:t.assignees.nodes?t.assignees.nodes.filter(C).map(a=>A(a)):null,reviews:o,reviewDecision:G(o),additions:t.additions,deletions:t.deletions,fileCount:t.changedFiles,commitCount:t.commits.totalCount,mergeableState:Br[t.mergeStateStatus]??jr[t.mergeable],milestone:t.milestone?tt(t.milestone):null,labels:t.labels?.nodes?.filter(C).map(et)??[],permissions:{canMerge:Mr.includes(t.repository.viewerPermission),canMergeAndBypassProtections:t.viewerCanMergeAsAdmin??!1}}},Yr=t=>{let{comments:s,isOutdated:e,isResolved:r,originalLine:n,originalStartLine:o,startDiffSide:a}=t,i=s.nodes?.[0];if(!i)return null;let{author:u,body:l,databaseId:p,fullDatabaseId:d,id:c,path:g,publishedAt:m,url:b}=i;return{author:u?{avatarUrl:u.avatarUrl,email:null,name:u.login}:null,body:l,createdAt:m?new Date(m):null,diffLines:xt(i.diffHunk,n,o,a),id:d??p.toString(),isOutdated:e,isResolved:r,graphQLId:c,filename:g,replies:s.nodes?.filter(C).slice(1).map(es)??[],url:b}},es=t=>({author:t.author?{avatarUrl:t.author.avatarUrl,email:null,name:t.author.login}:null,body:t.body,createdAt:t.publishedAt?new Date(t.publishedAt):null,graphQLId:t.id,id:t.fullDatabaseId??t.databaseId.toString(),url:t.url}),ts=t=>{let s=null;return t.author?s=t.author:s=Ye,{id:t.fullDatabaseId!==void 0?t.fullDatabaseId:t.databaseId.toString(),graphQLId:t.id,number:t.number,title:t.title,author:s&&s.__typename?A(s):null,commentCount:t.comments.totalCount,closedDate:t.closedAt?new Date(t.closedAt):null,createdDate:new Date(t.createdAt),description:null,state:{name:zr[t.state],color:null},type:null,repository:{id:t.repository.databaseId.toString(),graphQLId:t.repository.id,name:t.repository.name,owner:{login:t.repository.owner.login}},url:t.url,updatedDate:new Date(t.updatedAt),assignees:t.assignees.nodes?.filter(C).map(e=>A(e))??[],upvoteCount:t.reactions.totalCount,milestone:t.milestone?tt(t.milestone):null,labels:t.labels?.nodes?.filter(C).map(et)??[]}},tt=t=>({id:t.number.toString(),graphQLId:t.id.toString(),number:t.number,title:t.title,description:t.description,isOpen:t.state=="OPEN",url:t.url,startDate:null,dueDate:t.dueOn?new Date(t.dueOn):null}),X=class extends L{constructor(){super(...arguments);this._scopesCache={};this._enterpriseVersionsCache={}}async getScopes(e){let r=e.token||this.config.token;if(!r)return[];let n=this._scopesCache[r];if(!n){let a=(await I(this.config,{query:"query { rateLimit(dryRun: true) { __typename } }"},e)).headers["x-oauth-scopes"];n=a?a.split(", "):[],this._scopesCache[r]=n}return n}async getEnterpriseVersion(e){let r=e.baseUrl||this.config.baseUrl;if(!r)return null;let n=this._enterpriseVersionsCache[r];if(!n){let o=await this.config.request({url:`${K(this.config,e)}/meta`,headers:h(e.token||this.config.token)});if(!o.body.installed_version)return null;n=o.body.installed_version.split(".").slice(0,3).map(a=>parseInt(a,10)),this._enterpriseVersionsCache[r]=n}return n}getEnterpriseAvatarUrlIfNeeded(e,r,n){let o=n.baseUrl||this.config.baseUrl;return!o||o.startsWith(fe)?e:r?`https://avatars.githubusercontent.com/u/e?email=${encodeURIComponent(r)}`:""}async getCurrentUser(e={},r={}){if(e.fields&&!e.fields.length)throw new Error('"fields" must contain at least one field or be omitted');let n=vt(e.fields),o=await this.getScopes(r),a=await I(this.config,{query:`
257
+ `,Ye={__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"},Qr={APPROVED:"APPROVED",CHANGES_REQUESTED:"CHANGES_REQUESTED",COMMENTED:"COMMENTED",REVIEW_REQUESTED:"REVIEW_REQUESTED"},jr={MERGEABLE:"MERGEABLE",CONFLICTING:"CONFLICTS",UNKNOWN:"UNKNOWN"},Br={BEHIND:"BEHIND",BLOCKED:"BLOCKED",UNKNOWN:"UNKNOWN_AND_BLOCKED",UNSTABLE:"UNSTABLE",CLEAN:null,DIRTY:null,DRAFT:null,HAS_HOOKS:null},zr={OPEN:"OPEN",CLOSED:"CLOSED"},Mr=["ADMIN","MAINTAIN","TRIAGE","WRITE"],et=r=>({color:`#${r.color}`,description:r.description,graphQLId:r.id,id:null,name:r.name}),Wr=r=>({canCreateWebhook:r==="ADMIN",canPush:r==="ADMIN"||r==="MAINTAIN"||r==="WRITE",isAdmin:r==="ADMIN"}),Xe=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:Wr(r.viewerPermission)}),Hr=r=>({canCreateWebhook:r.admin,canPush:r.admin||r.maintain||r.push,isAdmin:r.admin}),kt=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:Hr(r.permissions)}),Jr=r=>({path:r.path,isDirectory:r.type==="tree"}),Vr={OPEN:"OPEN",CLOSED:"CLOSED",MERGED:"MERGED"},Kr={id:!0,graphQLId:!0,name:!0,username:!0,email:!0,avatarUrl:!0,url:!0},A=(r,s=Kr)=>{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},Xr=(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]},Zr=r=>({ERROR:"ERROR",EXPECTED:"PENDING",FAILURE:"FAILED",PENDING:"PENDING",SUCCESS:"SUCCESS"})[r],Ze=r=>{let s=null;r.author?s=r.author:s=Ye;let e=(r.reviewRequests?.nodes||[]).filter(C).filter(a=>!a.asCodeOwner),t=r.headRepository?.url;t&&!t.endsWith(".git")&&(t=`${t}.git`);let n=r.repository?.url;n&&!n.endsWith(".git")&&(n=`${n}.git`);let o=e.filter(a=>a.requestedReviewer&&"__typename"in a.requestedReviewer).map(a=>({reviewer:A(a.requestedReviewer),state:"REVIEW_REQUESTED"})).concat((r.latestReviews?.nodes||[]).filter(C).map(a=>{let i=Ye;return a.author&&a.author.__typename&&(i=a.author),{reviewer:A(i),state:Qr[a.state]}}));return{id:r.fullDatabaseId!==void 0?r.fullDatabaseId:r.databaseId.toString(),graphQLId:r.id,title:r.title,number:r.number,state:Vr[r.state],commentCount:r.comments.totalCount,upvoteCount:r.reactions.totalCount,author:s&&s.__typename?A(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:r.commits.nodes?.filter(C)[0]?.commit.statusCheckRollup?.contexts.nodes?.filter(C).map(a=>"context"in a?{completedAt:null,description:a.description,name:a.context,state:Zr(a.state),startedAt:new Date(a.createdAt),stage:null,url:a.targetUrl}:{completedAt:a.completedAt?new Date(a.completedAt):null,description:null,name:a.name,state:Xr(a.status,a.conclusion),startedAt:a.startedAt?new Date(a.startedAt):null,stage:null,url:a.permalink})??[]},headRef:r.headRef?{name:r.headRef.name,oid:r.headRef.target?.oid??null}:null,baseRef:r.baseRef?{name:r.baseRef.name,oid:r.baseRef.target?.oid??null}:null,url:r.url,updatedDate:new Date(r.updatedAt),closedDate:r.closedAt?new Date(r.closedAt):null,mergedDate:r.mergedAt?new Date(r.mergedAt):null,assignees:r.assignees.nodes?r.assignees.nodes.filter(C).map(a=>A(a)):null,reviews:o,reviewDecision:G(o),additions:r.additions,deletions:r.deletions,fileCount:r.changedFiles,commitCount:r.commits.totalCount,mergeableState:Br[r.mergeStateStatus]??jr[r.mergeable],milestone:r.milestone?tt(r.milestone):null,labels:r.labels?.nodes?.filter(C).map(et)??[],permissions:{canMerge:Mr.includes(r.repository.viewerPermission),canMergeAndBypassProtections:r.viewerCanMergeAsAdmin??!1}}},Yr=r=>{let{comments:s,isOutdated:e,isResolved:t,originalLine:n,originalStartLine:o,startDiffSide:a}=r,i=s.nodes?.[0];if(!i)return null;let{author:u,body:l,databaseId:p,fullDatabaseId:d,id:c,path:g,publishedAt:m,url:b}=i;return{author:u?{avatarUrl:u.avatarUrl,email:null,name:u.login}:null,body:l,createdAt:m?new Date(m):null,diffLines:xt(i.diffHunk,n,o,a),id:d??p.toString(),isOutdated:e,isResolved:t,graphQLId:c,filename:g,replies:s.nodes?.filter(C).slice(1).map(es)??[],url:b}},es=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}),ts=r=>{let s=null;return r.author?s=r.author:s=Ye,{id:r.fullDatabaseId!==void 0?r.fullDatabaseId:r.databaseId.toString(),graphQLId:r.id,number:r.number,title:r.title,author:s&&s.__typename?A(s):null,commentCount:r.comments.totalCount,closedDate:r.closedAt?new Date(r.closedAt):null,createdDate:new Date(r.createdAt),description:null,state:{name:zr[r.state],color:null},type:null,repository:{id:r.repository.databaseId.toString(),graphQLId:r.repository.id,name:r.repository.name,owner:{login:r.repository.owner.login}},url:r.url,updatedDate:new Date(r.updatedAt),assignees:r.assignees.nodes?.filter(C).map(e=>A(e))??[],upvoteCount:r.reactions.totalCount,milestone:r.milestone?tt(r.milestone):null,labels:r.labels?.nodes?.filter(C).map(et)??[]}},tt=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}),X=class extends L{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 a=(await R(this.config,{query:"query { rateLimit(dryRun: true) { __typename } }"},e)).headers["x-oauth-scopes"];n=a?a.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:`${K(this.config,e)}/meta`,headers:h(e.token||this.config.token)});if(!o.body.installed_version)return null;n=o.body.installed_version.split(".").slice(0,3).map(a=>parseInt(a,10)),this._enterpriseVersionsCache[t]=n}return n}getEnterpriseAvatarUrlIfNeeded(e,t,n){let o=n.baseUrl||this.config.baseUrl;return!o||o.startsWith(fe)?e:t?`https://avatars.githubusercontent.com/u/e?email=${encodeURIComponent(t)}`:""}async getCurrentUser(e={},t={}){if(e.fields&&!e.fields.length)throw new Error('"fields" must contain at least one field or be omitted');let n=vt(e.fields),o=await this.getScopes(t),a=await R(this.config,{query:`
258
258
  query getCurrentUser {
259
259
  viewer {
260
260
  ${D(!1,x(o),n)}
261
261
  }
262
262
  }
263
- `},r),i=a.body.data?.viewer;if(!i)throw new f("Current user not found.",a.body.errors);return{data:A(i,n)}}async getAccountsForRepo(e,r={}){let n=await this.getScopes(r),{repo:{namespace:o,name:a},cursor:i}=e,u=await I(this.config,{query:`
263
+ `},t),i=a.body.data?.viewer;if(!i)throw new f("Current user not found.",a.body.errors);return{data:A(i,n)}}async getAccountsForRepo(e,t={}){let n=await this.getScopes(t),{repo:{namespace:o,name:a},cursor:i}=e,u=await R(this.config,{query:`
264
264
  query getAccountsForRepo($owner: String!, $name: String! $cursor: String, $first: Int!) {
265
265
  repository(owner: $owner, name: $name) {
266
266
  assignableUsers(first: $first, after: $cursor) {
@@ -274,7 +274,7 @@ query getAccountsForRepo($owner: String!, $name: String! $cursor: String, $first
274
274
  }
275
275
  }
276
276
  }
277
- `,variables:{owner:o,name:a,cursor:i,first:S}},r);if(!u.body.data)throw new f("Could not fetch accounts for repo",u.body.errors);return{pageInfo:u.body.data.repository?.assignableUsers?.pageInfo??{endCursor:null,hasNextPage:!1},data:u.body.data.repository?.assignableUsers?.nodes?.map(l=>A(l))??[]}}async getUserForCommit(e,r={}){let n=await I(this.config,{query:`
277
+ `,variables:{owner:o,name:a,cursor:i,first:S}},t);if(!u.body.data)throw new f("Could not fetch accounts for repo",u.body.errors);return{pageInfo:u.body.data.repository?.assignableUsers?.pageInfo??{endCursor:null,hasNextPage:!1},data:u.body.data.repository?.assignableUsers?.nodes?.map(l=>A(l))??[]}}async getUserForCommit(e,t={}){let n=await R(this.config,{query:`
278
278
  query getUserForCommit(
279
279
  $owner: String!
280
280
  $name: String!
@@ -293,7 +293,7 @@ query getUserForCommit(
293
293
  }
294
294
  }
295
295
  }
296
- `,variables:{owner:e.repo.namespace,name:e.repo.name,oid:e.oid,avatarSize:e.avatarSize}},r),o=n.body.data?.repository;if(!o)throw new f("Repository not found.",n.body.errors);let a=o.object?.author;if(!a)throw new f("Commit not found.",n.body.errors);return{data:{name:a.name,email:a.email,avatarUrl:this.getEnterpriseAvatarUrlIfNeeded(a.avatarUrl,a.email,r)}}}async createCommit(e,r={}){let{commitMessage:n,deletedFiles:o,newOrModifiedFiles:a,repo:i,target:u}=e,l=await I(this.config,{query:`
296
+ `,variables:{owner:e.repo.namespace,name:e.repo.name,oid:e.oid,avatarSize:e.avatarSize}},t),o=n.body.data?.repository;if(!o)throw new f("Repository not found.",n.body.errors);let a=o.object?.author;if(!a)throw new f("Commit not found.",n.body.errors);return{data:{name:a.name,email:a.email,avatarUrl:this.getEnterpriseAvatarUrlIfNeeded(a.avatarUrl,a.email,t)}}}async createCommit(e,t={}){let{commitMessage:n,deletedFiles:o,newOrModifiedFiles:a,repo:i,target:u}=e,l=await R(this.config,{query:`
297
297
  mutation createCommitOnBranch(
298
298
  $branchName: String!,
299
299
  $expectedHeadOid: GitObjectID!,
@@ -320,7 +320,7 @@ mutation createCommitOnBranch(
320
320
  }
321
321
  }
322
322
  }
323
- `,variables:{branchName:u.name,expectedHeadOid:u.oid,fileChanges:{additions:Object.entries(a).map(([p,d])=>({contents:Nt.Base64.encode(d),path:p})),deletions:o.map(p=>({path:p}))},message:{body:n.description,headline:n.summary},repositoryNameWithOwner:`${i.namespace}/${i.name}`}},r);if(!l.body.data)throw new f("Could not create commit",l.body.errors);return{data:{name:l.body.data.createCommitOnBranch.ref.name,commit:{authoredDate:new Date(l.body.data.createCommitOnBranch.commit.authoredDate),committedDate:new Date(l.body.data.createCommitOnBranch.commit.committedDate),oid:l.body.data.createCommitOnBranch.commit.oid}}}}async getAccountForEmail(e,r={}){let n=await this.getScopes(r),o=await I(this.config,{query:`
323
+ `,variables:{branchName:u.name,expectedHeadOid:u.oid,fileChanges:{additions:Object.entries(a).map(([p,d])=>({contents:Nt.Base64.encode(d),path:p})),deletions:o.map(p=>({path:p}))},message:{body:n.description,headline:n.summary},repositoryNameWithOwner:`${i.namespace}/${i.name}`}},t);if(!l.body.data)throw new f("Could not create commit",l.body.errors);return{data:{name:l.body.data.createCommitOnBranch.ref.name,commit:{authoredDate:new Date(l.body.data.createCommitOnBranch.commit.authoredDate),committedDate:new Date(l.body.data.createCommitOnBranch.commit.committedDate),oid:l.body.data.createCommitOnBranch.commit.oid}}}}async getAccountForEmail(e,t={}){let n=await this.getScopes(t),o=await R(this.config,{query:`
324
324
  query getAccountForEmail($query: String! $avatarSize: Int) {
325
325
  search(query: $query, type: USER, first: 1) {
326
326
  nodes {
@@ -330,13 +330,13 @@ query getAccountForEmail($query: String! $avatarSize: Int) {
330
330
  }
331
331
  }
332
332
  }
333
- `,variables:{query:`in:email ${e.email}`,avatarSize:e.avatarSize}},r),a=o.body.data?.search?.nodes?.[0];if(!a)throw new f("Could not find user via email",o.body.errors);return{data:A({...a,avatarUrl:this.getEnterpriseAvatarUrlIfNeeded(a.avatarUrl,a.email,r)})}}async getAccountForUsername(e,r={}){let n=await this.getScopes(r),o=await I(this.config,{query:`
333
+ `,variables:{query:`in:email ${e.email}`,avatarSize:e.avatarSize}},t),a=o.body.data?.search?.nodes?.[0];if(!a)throw new f("Could not find user via email",o.body.errors);return{data:A({...a,avatarUrl:this.getEnterpriseAvatarUrlIfNeeded(a.avatarUrl,a.email,t)})}}async getAccountForUsername(e,t={}){let n=await this.getScopes(t),o=await R(this.config,{query:`
334
334
  query getUserForUsername($login: String! $avatarSize: Int) {
335
335
  user(login: $login) {
336
336
  ${D(!0,x(n))}
337
337
  }
338
338
  }
339
- `,variables:{login:e.username,avatarSize:e.avatarSize}},r),a=o.body.data?.user;if(!a)throw new f("Could not find user via username",o.body.errors);return{data:A({...a,avatarUrl:this.getEnterpriseAvatarUrlIfNeeded(a.avatarUrl,a.email,r)})}}async getOrgsForCurrentUser(e={},r={}){let n=await I(this.config,{query:`
339
+ `,variables:{login:e.username,avatarSize:e.avatarSize}},t),a=o.body.data?.user;if(!a)throw new f("Could not find user via username",o.body.errors);return{data:A({...a,avatarUrl:this.getEnterpriseAvatarUrlIfNeeded(a.avatarUrl,a.email,t)})}}async getOrgsForCurrentUser(e={},t={}){let n=await R(this.config,{query:`
340
340
  query getOrgsForCurrentUser($cursor: String, $first: Int!) {
341
341
  viewer {
342
342
  organizations(first: $first after: $cursor) {
@@ -355,7 +355,7 @@ query getOrgsForCurrentUser($cursor: String, $first: Int!) {
355
355
  }
356
356
  }
357
357
  }
358
- `,variables:{cursor:e.cursor,first:S}},r);if(!n.body.data)throw new f("Could not fetch orgs for current user",n.body.errors);let o=n.body.data.viewer.organizations.nodes||[];return{pageInfo:n.body.data.viewer.organizations.pageInfo,data:o.map(a=>({id:a.databaseId.toString(),graphQLId:a.id,username:a.login,name:a.name||null,email:a.email||null,avatarUrl:a.avatarUrl}))}}async getOrgMembers(e,r={}){let n=await I(this.config,{query:`
358
+ `,variables:{cursor:e.cursor,first:S}},t);if(!n.body.data)throw new f("Could not fetch orgs for current user",n.body.errors);let o=n.body.data.viewer.organizations.nodes||[];return{pageInfo:n.body.data.viewer.organizations.pageInfo,data:o.map(a=>({id:a.databaseId.toString(),graphQLId:a.id,username:a.login,name:a.name||null,email:a.email||null,avatarUrl:a.avatarUrl}))}}async getOrgMembers(e,t={}){let n=await R(this.config,{query:`
359
359
  query getOrgMember($cursor: String, $first: Int!, $login: String!) {
360
360
  viewer {
361
361
  organization(login: $login) {
@@ -371,22 +371,22 @@ query getOrgMember($cursor: String, $first: Int!, $login: String!) {
371
371
  }
372
372
  }
373
373
  }
374
- `,variables:{cursor:e.cursor,first:S,login:e.org}},r);if(!n.body.data?.viewer.organization?.membersWithRole&&n.body.errors?.length)throw new f("Could not read the members of the organization",n.body.errors);let o=n.body.data?.viewer.organization?.membersWithRole.nodes||[];return{pageInfo:{hasNextPage:n.body.data?.viewer.organization?.membersWithRole.pageInfo.hasNextPage??!1,endCursor:n.body.data?.viewer.organization?.membersWithRole.pageInfo.endCursor??null},data:o.map(a=>A({...a,avatarUrl:this.getEnterpriseAvatarUrlIfNeeded(a.avatarUrl,a.email,r)}))}}async getRepo(e,r={}){let n=await I(this.config,{query:`
374
+ `,variables:{cursor:e.cursor,first:S,login:e.org}},t);if(!n.body.data?.viewer.organization?.membersWithRole&&n.body.errors?.length)throw new f("Could not read the members of the organization",n.body.errors);let o=n.body.data?.viewer.organization?.membersWithRole.nodes||[];return{pageInfo:{hasNextPage:n.body.data?.viewer.organization?.membersWithRole.pageInfo.hasNextPage??!1,endCursor:n.body.data?.viewer.organization?.membersWithRole.pageInfo.endCursor??null},data:o.map(a=>A({...a,avatarUrl:this.getEnterpriseAvatarUrlIfNeeded(a.avatarUrl,a.email,t)}))}}async getRepo(e,t={}){let n=await R(this.config,{query:`
375
375
  query getRepo($owner: String!, $name: String!) {
376
376
  repository(owner: $owner, name: $name) {
377
377
  ${Ke}
378
378
  }
379
379
  }
380
- `,variables:{owner:e.namespace,name:e.name}},r);if(!n.body.data?.repository)throw new f(`Repository ${e.namespace}/${e.name} not found`,n.body.errors);return{data:Xe(n.body.data.repository)}}async getRepos(e,r={}){let n=e.map(({namespace:u,name:l},p)=>`
380
+ `,variables:{owner:e.namespace,name:e.name}},t);if(!n.body.data?.repository)throw new f(`Repository ${e.namespace}/${e.name} not found`,n.body.errors);return{data:Xe(n.body.data.repository)}}async getRepos(e,t={}){let n=e.map(({namespace:u,name:l},p)=>`
381
381
  getRepo_${p}: repository(owner: "${u}", name: "${l}") {
382
382
  ${Ke}
383
383
  }
384
384
  `).join(`
385
- `),o=await I(this.config,{query:`
385
+ `),o=await R(this.config,{query:`
386
386
  query batchGetRepos {
387
387
  ${n}
388
388
  }
389
- `},r);if(!o.body.data)throw new f("Could not fetch repos",o.body.errors);let a=[],i=[];return e.forEach((u,l)=>{let p=o.body.data[`getRepo_${l}`];p?a.push(Xe(p)):i.push({input:u})}),{data:a,errors:i}}async fetchMultipleRESTPages(e,r,n,o){let a=[];for(let d=0;d<r;d++)a.push(n(e+d));let i=await Promise.all(a),u=[];for(let d of i){if(!d.body)throw new Error(d.statusText||"Unknown error");u=u.concat(d.body.map(c=>o(c)))}let l=i.every(d=>d.body.length===100),p=e+r;return{data:u,pageInfo:{hasNextPage:l,nextPage:l?p:null}}}async getReposForCurrentUser(e,r={}){if(e.simultaneousPagesToFetch&&e.simultaneousPagesToFetch>40)throw new Error("The argument 'simultaneousPagesToFetch' cannot exceed 40 for 'getReposForCurrentUser'");let n=new URLSearchParams;n.append("per_page","100"),e.affiliations&&n.append("affiliation",e.affiliations.join(","));let o=a=>this.config.request({url:`${K(this.config,r)}/user/repos?${n.toString()}&page=${a}`,headers:{...h(r.token||this.config.token),Accept:"application/vnd.github.raw+json","X-Github-Next-Global-ID":1}});return await this.fetchMultipleRESTPages(e.page??1,e.simultaneousPagesToFetch??4,o,kt)}async getReposForOrg(e,r={}){if(e.simultaneousPagesToFetch&&e.simultaneousPagesToFetch>40)throw new Error("The argument 'simultaneousPagesToFetch' cannot exceed 40 for 'getReposForOrg'");let n=o=>this.config.request({url:`${K(this.config,r)}/orgs/${e.orgName}/repos?per_page=100&page=${o}`,headers:{...h(r.token||this.config.token),Accept:"application/vnd.github.raw+json","X-Github-Next-Global-ID":1}});return await this.fetchMultipleRESTPages(e.page??1,e.simultaneousPagesToFetch??4,n,kt)}async getReposForUsernames(e,r={}){if(!e.usernames.length)return{pageInfo:{endCursor:null,hasNextPage:!1},data:[]};let n=await I(this.config,{query:`
389
+ `},t);if(!o.body.data)throw new f("Could not fetch repos",o.body.errors);let a=[],i=[];return e.forEach((u,l)=>{let p=o.body.data[`getRepo_${l}`];p?a.push(Xe(p)):i.push({input:u})}),{data:a,errors:i}}async fetchMultipleRESTPages(e,t,n,o){let a=[];for(let d=0;d<t;d++)a.push(n(e+d));let i=await Promise.all(a),u=[];for(let d of i){if(!d.body)throw new Error(d.statusText||"Unknown error");u=u.concat(d.body.map(c=>o(c)))}let l=i.every(d=>d.body.length===100),p=e+t;return{data:u,pageInfo:{hasNextPage:l,nextPage:l?p:null}}}async getReposForCurrentUser(e,t={}){if(e.simultaneousPagesToFetch&&e.simultaneousPagesToFetch>40)throw new Error("The argument 'simultaneousPagesToFetch' cannot exceed 40 for 'getReposForCurrentUser'");let n=new URLSearchParams;n.append("per_page","100"),e.affiliations&&n.append("affiliation",e.affiliations.join(","));let o=a=>this.config.request({url:`${K(this.config,t)}/user/repos?${n.toString()}&page=${a}`,headers:{...h(t.token||this.config.token),Accept:"application/vnd.github.raw+json","X-Github-Next-Global-ID":1}});return await this.fetchMultipleRESTPages(e.page??1,e.simultaneousPagesToFetch??4,o,kt)}async getReposForOrg(e,t={}){if(e.simultaneousPagesToFetch&&e.simultaneousPagesToFetch>40)throw new Error("The argument 'simultaneousPagesToFetch' cannot exceed 40 for 'getReposForOrg'");let n=o=>this.config.request({url:`${K(this.config,t)}/orgs/${e.orgName}/repos?per_page=100&page=${o}`,headers:{...h(t.token||this.config.token),Accept:"application/vnd.github.raw+json","X-Github-Next-Global-ID":1}});return await this.fetchMultipleRESTPages(e.page??1,e.simultaneousPagesToFetch??4,n,kt)}async getReposForUsernames(e,t={}){if(!e.usernames.length)return{pageInfo:{endCursor:null,hasNextPage:!1},data:[]};let n=await R(this.config,{query:`
390
390
  query getReposForUsernames($query: String!, $cursor: String, $first: Int!) {
391
391
  search(query: $query, type: REPOSITORY, first: $first, after: $cursor) {
392
392
  pageInfo {
@@ -400,7 +400,7 @@ query getReposForUsernames($query: String!, $cursor: String, $first: Int!) {
400
400
  }
401
401
  }
402
402
  }
403
- `,variables:{query:`fork:true ${e.usernames.map(a=>`user:${a}`).join(" ")}`,cursor:e.cursor,first:S}},r);if(!n.body.data)throw new f("Could not fetch repos for usernames",n.body.errors);let o=n.body.data.search.nodes||[];return{pageInfo:n.body.data.search.pageInfo,data:o.map(Xe)}}async getReposForOwners(e,r={}){return this.getReposForUsernames({usernames:e.owners.filter(n=>n.username).map(n=>n.username),cursor:e.cursor},r)}async getRefs(e,r,n={}){let o=await I(this.config,{query:`
403
+ `,variables:{query:`fork:true ${e.usernames.map(a=>`user:${a}`).join(" ")}`,cursor:e.cursor,first:S}},t);if(!n.body.data)throw new f("Could not fetch repos for usernames",n.body.errors);let o=n.body.data.search.nodes||[];return{pageInfo:n.body.data.search.pageInfo,data:o.map(Xe)}}async getReposForOwners(e,t={}){return this.getReposForUsernames({usernames:e.owners.filter(n=>n.username).map(n=>n.username),cursor:e.cursor},t)}async getRefs(e,t,n={}){let o=await R(this.config,{query:`
404
404
  query getRefs($owner: String!, $name: String!, $refPrefix: String!, $cursor: String, $first: Int!) {
405
405
  repository(owner: $owner, name: $name) {
406
406
  refs(refPrefix: $refPrefix first: $first after: $cursor) {
@@ -421,7 +421,7 @@ query getRefs($owner: String!, $name: String!, $refPrefix: String!, $cursor: Str
421
421
  }
422
422
  }
423
423
  }
424
- `,variables:{owner:r.repo.namespace,name:r.repo.name,refPrefix:e,cursor:r.cursor,first:S}},n),a=o.body.data?.repository;if(!a)throw new f("Ref repository not found.",o.body.errors);let i=a.refs;return i?{pageInfo:i.pageInfo,data:(i.nodes||[]).map(u=>{let l=u.target?.oid?u.target:null;return{name:u.name,commit:l?{oid:l.oid,authoredDate:new Date(l.authoredDate),committedDate:new Date(l.committedDate)}:null}})}:{pageInfo:{endCursor:null,hasNextPage:!1},data:[]}}async getBranches(e,r={}){return this.getRefs("refs/heads/",e,r)}async getTags(e,r={}){return this.getRefs("refs/tags/",e,r)}async getBlame(e,r={}){let n=await I(this.config,{query:`
424
+ `,variables:{owner:t.repo.namespace,name:t.repo.name,refPrefix:e,cursor:t.cursor,first:S}},n),a=o.body.data?.repository;if(!a)throw new f("Ref repository not found.",o.body.errors);let i=a.refs;return i?{pageInfo:i.pageInfo,data:(i.nodes||[]).map(u=>{let l=u.target?.oid?u.target:null;return{name:u.name,commit:l?{oid:l.oid,authoredDate:new Date(l.authoredDate),committedDate:new Date(l.committedDate)}:null}})}:{pageInfo:{endCursor:null,hasNextPage:!1},data:[]}}async getBranches(e,t={}){return this.getRefs("refs/heads/",e,t)}async getTags(e,t={}){return this.getRefs("refs/tags/",e,t)}async getBlame(e,t={}){let n=await R(this.config,{query:`
425
425
  query getBlame($owner: String!, $name: String!, $ref: String!, $path: String!) {
426
426
  repository(owner: $owner, name: $name) {
427
427
  object(expression: $ref) {
@@ -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}},r),o=n.body.data?.repository;if(!o)throw new f("Blame repository not found.",n.body.errors);let a=o.object;if(!a||!("blame"in a))throw new f("Ref not found.",n.body.errors);if(a.blame.ranges.length===0)throw new f("File not found.",n.body.errors);return{data:{ranges:a.blame.ranges.map(i=>({startingLine:i.startingLine,endingLine:i.endingLine,commit:{oid:i.commit.oid,parentOids:i.commit.parents.nodes?.map(u=>u.oid)||[],authoredDate:new Date(i.commit.authoredDate),author:i.commit.author?{name:i.commit.author.name,email:i.commit.author.email,avatarUrl:i.commit.author.avatarUrl}:null,committedDate:new Date(i.commit.committedDate),committer:i.commit.committer?{name:i.commit.committer.name,email:i.commit.committer.email,avatarUrl:i.commit.committer.avatarUrl}:null,message:i.commit.message,fileCount:i.commit.changedFilesIfAvailable,additions:i.commit.additions,deletions:i.commit.deletions}}))}}}async getFileContents(e,r={}){let n=await this.config.request({url:`${K(this.config,r)}/repos/${e.repo.namespace}/${e.repo.name}/contents/${encodeURIComponent(e.path)}?ref=${e.ref}`,headers:{...h(r.token||this.config.token),Accept:"application/vnd.github.raw+json"}});if(n.headers["content-type"].startsWith("application/json"))throw new Error(`GitHub: got directory when fetching "${e.path}", getFileContents does not support fetching directories`);if(!n.headers["content-type"].startsWith("application/vnd.github.raw+json"))throw new Error(`GitHub: unsupported content type "${n.headers["content-type"]}" when fetching "${e.path}"`);return{data:new Blob([n.body])}}async searchPullRequests(e,r={}){let n=await this.getEnterpriseVersion(r),o=await this.getScopes(r),a=x(o),i=p=>{let d=p&&typeof e.isDraft=="boolean"?`${e.query} draft:${e.isDraft}`:e.query;return Ve("pr",d,e.cursor,{maxPageSize:e.maxPageSize??At,supportsEmail:a,supportsDrafts:p,enterpriseVersion:n,includeFromArchivedRepos:e.includeFromArchivedRepos})},u=await I(this.config,i(!0),r);u.body.errors&&ye(u.body.errors)&&(this.config.baseUrl||r.baseUrl)&&(u=await I(this.config,i(!1),r));let{data:l}=u.body;if(!l)throw new f("Could not search pull requests",u.body.errors);return{pageInfo:{hasNextPage:l.search.pageInfo.hasNextPage,endCursor:l.search.pageInfo.endCursor},data:l.search.nodes?.filter(C).map(Ze)||[]}}async searchIssues(e,r={}){let n=await this.getEnterpriseVersion(r),o=await this.getScopes(r),a=x(o),i=await I(this.config,Ve("issue",e.query,e.cursor,{supportsEmail:a,includeFromArchivedRepos:e.includeFromArchivedRepos,maxPageSize:e.maxPageSize??Gt,enterpriseVersion:n}),r),{data:u}=i.body;if(!u)throw new f("Could not search issues",i.body.errors);return{pageInfo:{hasNextPage:u.search.pageInfo.hasNextPage,endCursor:u.search.pageInfo.endCursor},data:u.search.nodes?.filter(C).map(ts)||[]}}async getPullRequestsAssociatedWithUser(e,r={}){let n=[`involves:${e.username}`];return e.repos?.length&&e.repos.forEach(o=>{n.push(`repo:${o.namespace}/${o.name}`)}),e.labelNames&&e.labelNames.forEach(o=>{n.push(`label:"${o}"`)}),this.searchPullRequests({query:n.join(" "),cursor:e.cursor,includeFromArchivedRepos:e.includeFromArchivedRepos,maxPageSize:e.maxPageSize},r)}async getPullRequestsForRepos(e,r={}){let{assigneeLogins:n,updatedBefore:o,authorLogin:a,repos:i,reviewRequestedLogin:u,startQuery:l,mentionLogin:p,labelNames:d,maxPageSize:c}=e,g=Je(l||"");return i.forEach(m=>{g.push(`repo:${m.namespace}/${m.name}`)}),n&&n.forEach(m=>{g.push(`assignee:${m}`)}),o&&g.push(`updated:<${o}`),a&&g.push(`author:${a}`),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},r)}async getPullRequestForRepo(e,r={}){let n=await this.getEnterpriseVersion(r),o=await this.getScopes(r),a=x(o),i=d=>({query:`query getPullRequest(
463
+ `,variables:{owner:e.repo.namespace,name:e.repo.name,ref:e.ref,path:e.path}},t),o=n.body.data?.repository;if(!o)throw new f("Blame repository not found.",n.body.errors);let a=o.object;if(!a||!("blame"in a))throw new f("Ref not found.",n.body.errors);if(a.blame.ranges.length===0)throw new f("File not found.",n.body.errors);return{data:{ranges:a.blame.ranges.map(i=>({startingLine:i.startingLine,endingLine:i.endingLine,commit:{oid:i.commit.oid,parentOids:i.commit.parents.nodes?.map(u=>u.oid)||[],authoredDate:new Date(i.commit.authoredDate),author:i.commit.author?{name:i.commit.author.name,email:i.commit.author.email,avatarUrl:i.commit.author.avatarUrl}:null,committedDate:new Date(i.commit.committedDate),committer:i.commit.committer?{name:i.commit.committer.name,email:i.commit.committer.email,avatarUrl:i.commit.committer.avatarUrl}:null,message:i.commit.message,fileCount:i.commit.changedFilesIfAvailable,additions:i.commit.additions,deletions:i.commit.deletions}}))}}}async getFileContents(e,t={}){let n=await this.config.request({url:`${K(this.config,t)}/repos/${e.repo.namespace}/${e.repo.name}/contents/${encodeURIComponent(e.path)}?ref=${e.ref}`,headers:{...h(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={}){let n=await this.getEnterpriseVersion(t),o=await this.getScopes(t),a=x(o),i=p=>{let d=p&&typeof e.isDraft=="boolean"?`${e.query} draft:${e.isDraft}`:e.query;return Ve("pr",d,e.cursor,{maxPageSize:e.maxPageSize??At,supportsEmail:a,supportsDrafts:p,enterpriseVersion:n,includeFromArchivedRepos:e.includeFromArchivedRepos})},u=await R(this.config,i(!0),t);u.body.errors&&ye(u.body.errors)&&(this.config.baseUrl||t.baseUrl)&&(u=await R(this.config,i(!1),t));let{data:l}=u.body;if(!l)throw new f("Could not search pull requests",u.body.errors);return{pageInfo:{hasNextPage:l.search.pageInfo.hasNextPage,endCursor:l.search.pageInfo.endCursor},data:l.search.nodes?.filter(C).map(Ze)||[]}}async searchIssues(e,t={}){let n=await this.getEnterpriseVersion(t),o=await this.getScopes(t),a=x(o),i=await R(this.config,Ve("issue",e.query,e.cursor,{supportsEmail:a,includeFromArchivedRepos:e.includeFromArchivedRepos,maxPageSize:e.maxPageSize??Gt,enterpriseVersion:n}),t),{data:u}=i.body;if(!u)throw new f("Could not search issues",i.body.errors);return{pageInfo:{hasNextPage:u.search.pageInfo.hasNextPage,endCursor:u.search.pageInfo.endCursor},data:u.search.nodes?.filter(C).map(ts)||[]}}async getPullRequestsAssociatedWithUser(e,t={}){let n=[`involves:${e.username}`];return e.repos?.length&&e.repos.forEach(o=>{n.push(`repo:${o.namespace}/${o.name}`)}),e.labelNames&&e.labelNames.forEach(o=>{n.push(`label:"${o}"`)}),this.searchPullRequests({query:n.join(" "),cursor:e.cursor,includeFromArchivedRepos:e.includeFromArchivedRepos,maxPageSize:e.maxPageSize},t)}async getPullRequestsForRepos(e,t={}){let{assigneeLogins:n,updatedBefore:o,authorLogin:a,repos:i,reviewRequestedLogin:u,startQuery:l,mentionLogin:p,labelNames:d,maxPageSize:c}=e,g=Je(l||"");return i.forEach(m=>{g.push(`repo:${m.namespace}/${m.name}`)}),n&&n.forEach(m=>{g.push(`assignee:${m}`)}),o&&g.push(`updated:<${o}`),a&&g.push(`author:${a}`),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={}){let n=await this.getEnterpriseVersion(t),o=await this.getScopes(t),a=x(o),i=d=>({query:`query getPullRequest(
464
464
  $owner: String!
465
465
  $name: String!
466
466
  $number: Int!
@@ -473,7 +473,7 @@ query getBlame($owner: String!, $name: String!, $ref: String!, $path: String!) {
473
473
  ${be(d,a,n)}
474
474
  }
475
475
  }
476
- }`,variables:{owner:e.repo.namespace,name:e.repo.name,number:e.number}}),u=await I(this.config,i(!0),r);u.body.errors&&ye(u.body.errors)&&(this.config.baseUrl||r.baseUrl)&&(u=await I(this.config,i(!1),r));let{data:l}=u.body;if(!l)throw new f("Could not fetch pull request by number",u.body.errors);let p=u.body.data?.repository.pullRequest;return{data:p?Ze(p):null}}async getPullRequestByGraphQLId(e,r={}){let n=await this.getEnterpriseVersion(r),o=await this.getScopes(r),a=x(o),i=d=>({query:`query getPullRequest(
476
+ }`,variables:{owner:e.repo.namespace,name:e.repo.name,number:e.number}}),u=await R(this.config,i(!0),t);u.body.errors&&ye(u.body.errors)&&(this.config.baseUrl||t.baseUrl)&&(u=await R(this.config,i(!1),t));let{data:l}=u.body;if(!l)throw new f("Could not fetch pull request by number",u.body.errors);let p=u.body.data?.repository.pullRequest;return{data:p?Ze(p):null}}async getPullRequestByGraphQLId(e,t={}){let n=await this.getEnterpriseVersion(t),o=await this.getScopes(t),a=x(o),i=d=>({query:`query getPullRequest(
477
477
  $graphQLId: ID!
478
478
  ) {
479
479
  node(id: $graphQLId) {
@@ -481,13 +481,13 @@ query getBlame($owner: String!, $name: String!, $ref: String!, $path: String!) {
481
481
  ${be(d,a,n)}
482
482
  }
483
483
  }
484
- }`,variables:{graphQLId:e.graphQLId}}),u=await I(this.config,i(!0),r);u.body.errors&&ye(u.body.errors)&&(this.config.baseUrl||r.baseUrl)&&(u=await I(this.config,i(!1),r));let{data:l}=u.body;if(!l)throw new f("Could not fetch pull request by id",u.body.errors);let p=u.body.data?.node;return{data:p?Ze(p):null}}async closePullRequest(e,r={}){let{pullRequest:{graphQLId:n}}=e;if(!n)throw new Error('GitHub requires "graphQLId" for this function.');let o=`mutation ClosePullRequest($pullRequestGraphQLId: ID!) {
484
+ }`,variables:{graphQLId:e.graphQLId}}),u=await R(this.config,i(!0),t);u.body.errors&&ye(u.body.errors)&&(this.config.baseUrl||t.baseUrl)&&(u=await R(this.config,i(!1),t));let{data:l}=u.body;if(!l)throw new f("Could not fetch pull request by id",u.body.errors);let p=u.body.data?.node;return{data:p?Ze(p):null}}async closePullRequest(e,t={}){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
488
488
  }
489
489
  }
490
- }`,a=await I(this.config,{query:`${o}`,variables:{pullRequestGraphQLId:n}},r);if(!a.body.data?.closePullRequest?.pullRequest?.id)throw new f("Could not close pull request",a.body.errors)}async mergePullRequest(e,r={}){let{pullRequest:n,mergeStrategy:o}=e;if(!n.graphQLId)throw new Error('GitHub requires "graphQLId" for this function.');if(!n.headRef?.oid)throw new Error('GitHub requires "headRef.oid" for this function.');let a;switch(o){case"MERGE_COMMIT":{a="MERGE";break}case"REBASE":{a="REBASE";break}case"SQUASH":{a="SQUASH";break}}let i=`mutation MergePullRequest(
490
+ }`,a=await R(this.config,{query:`${o}`,variables:{pullRequestGraphQLId:n}},t);if(!a.body.data?.closePullRequest?.pullRequest?.id)throw new f("Could not close pull request",a.body.errors)}async mergePullRequest(e,t={}){let{pullRequest:n,mergeStrategy:o}=e;if(!n.graphQLId)throw new Error('GitHub requires "graphQLId" for this function.');if(!n.headRef?.oid)throw new Error('GitHub requires "headRef.oid" for this function.');let a;switch(o){case"MERGE_COMMIT":{a="MERGE";break}case"REBASE":{a="REBASE";break}case"SQUASH":{a="SQUASH";break}}let i=`mutation MergePullRequest(
491
491
  $pullRequestGraphQLId: ID!,
492
492
  $expectedSourceSha: GitObjectID!,
493
493
  $mergeStrategy: PullRequestMergeMethod,
@@ -501,43 +501,82 @@ query getBlame($owner: String!, $name: String!, $ref: String!, $path: String!) {
501
501
  id
502
502
  }
503
503
  }
504
- }`,u=await I(this.config,{query:`${i}`,variables:{pullRequestGraphQLId:n.graphQLId,expectedSourceSha:n.headRef.oid,mergeStrategy:a}},r);if(!u.body.data?.mergePullRequest?.pullRequest?.id)throw new f("Could not merge pull request",u.body.errors)}async setPullRequestMilestone(e,r={}){let{pullRequest:n,milestone:o}=e;if(!n.graphQLId)throw new Error('GitHub requires "graphQLId" for this function.');let a=`mutation SetPullRequestMilestone($pullRequestGraphQLId: ID!, $milestoneGraphQLId: ID) {
504
+ }`,u=await R(this.config,{query:`${i}`,variables:{pullRequestGraphQLId:n.graphQLId,expectedSourceSha:n.headRef.oid,mergeStrategy:a}},t);if(!u.body.data?.mergePullRequest?.pullRequest?.id)throw new f("Could not merge pull request",u.body.errors)}async approvePullRequest(e,t={}){let{pullRequest:n,comment:o}=e;if(!n.graphQLId)throw new Error('GitHub requires "graphQLId" for this function.');let a=`mutation ApprovePullRequest(
505
+ $pullRequestId: ID!,
506
+ $body: String
507
+ ) {
508
+ addPullRequestReview(input: {
509
+ pullRequestId: $pullRequestId,
510
+ event: APPROVE,
511
+ body: $body
512
+ }) {
513
+ pullRequestReview {
514
+ id
515
+ }
516
+ }
517
+ }`,i=await R(this.config,{query:a,variables:{pullRequestId:n.graphQLId,body:o||null}},t);if(!i.body.data?.addPullRequestReview?.pullRequestReview?.id)throw new f("Could not approve pull request",i.body.errors)}async requestPullRequestChanges(e,t={}){let{pullRequest:n,comment:o}=e;if(!n.graphQLId)throw new Error('GitHub requires "graphQLId" for this function.');if(!o||o.trim()==="")throw new Error("GitHub requires a comment when requesting changes.");let a=`mutation RequestPullRequestChanges(
518
+ $pullRequestId: ID!,
519
+ $body: String!
520
+ ) {
521
+ addPullRequestReview(input: {
522
+ pullRequestId: $pullRequestId,
523
+ event: REQUEST_CHANGES,
524
+ body: $body
525
+ }) {
526
+ pullRequestReview {
527
+ id
528
+ }
529
+ }
530
+ }`,i=await R(this.config,{query:a,variables:{pullRequestId:n.graphQLId,body:o}},t);if(!i.body.data?.addPullRequestReview?.pullRequestReview?.id)throw new f("Could not request pull request changes",i.body.errors)}async commentOnPullRequest(e,t={}){let{pullRequest:n,comment:o}=e;if(!n.graphQLId)throw new Error('GitHub requires "graphQLId" for this function.');if(!o||o.trim()==="")throw new Error("GitHub requires a comment when commenting on a pull request.");let a=`mutation CommentOnPullRequest(
531
+ $pullRequestId: ID!,
532
+ $body: String!
533
+ ) {
534
+ addPullRequestReview(input: {
535
+ pullRequestId: $pullRequestId,
536
+ event: COMMENT,
537
+ body: $body
538
+ }) {
539
+ pullRequestReview {
540
+ id
541
+ }
542
+ }
543
+ }`,i=await R(this.config,{query:a,variables:{pullRequestId:n.graphQLId,body:o}},t);if(!i.body.data?.addPullRequestReview?.pullRequestReview?.id)throw new f("Could not comment on pull request",i.body.errors)}async setPullRequestMilestone(e,t={}){let{pullRequest:n,milestone:o}=e;if(!n.graphQLId)throw new Error('GitHub requires "graphQLId" for this function.');let a=`mutation SetPullRequestMilestone($pullRequestGraphQLId: ID!, $milestoneGraphQLId: ID) {
505
544
  updatePullRequest(input: { pullRequestId: $pullRequestGraphQLId, milestoneId: $milestoneGraphQLId }) {
506
545
  pullRequest {
507
546
  id
508
547
  }
509
548
  }
510
- }`,i=await I(this.config,{query:`${a}`,variables:{pullRequestGraphQLId:n.graphQLId,milestoneGraphQLId:o?.graphQLId??null}},r);if(!i.body.data?.updatePullRequest?.pullRequest?.id)throw new f("Could not set milestone of pull request",i.body.errors)}async markPullRequestReadyForReview(e,r){let n=`mutation MarkReadyToReview($pullRequestGraphQLId: ID!) {
549
+ }`,i=await R(this.config,{query:`${a}`,variables:{pullRequestGraphQLId:n.graphQLId,milestoneGraphQLId:o?.graphQLId??null}},t);if(!i.body.data?.updatePullRequest?.pullRequest?.id)throw new f("Could not set milestone of pull request",i.body.errors)}async markPullRequestReadyForReview(e,t){let n=`mutation MarkReadyToReview($pullRequestGraphQLId: ID!) {
511
550
  markPullRequestReadyForReview(input: { pullRequestId: $pullRequestGraphQLId }) {
512
551
  pullRequest {
513
552
  id
514
553
  }
515
554
  }
516
- }`,o=await I(this.config,{query:n,variables:{pullRequestGraphQLId:e}},r);if(!o.body.data?.markPullRequestReadyForReview?.pullRequest?.id)throw new f("Could not mark pull request ready to review",o.body.errors)}async convertPullRequestToDraft(e,r){let n=`mutation ConvertToDraft($pullRequestGraphQLId: ID!) {
555
+ }`,o=await R(this.config,{query:n,variables:{pullRequestGraphQLId:e}},t);if(!o.body.data?.markPullRequestReadyForReview?.pullRequest?.id)throw new f("Could not mark pull request ready to review",o.body.errors)}async convertPullRequestToDraft(e,t){let n=`mutation ConvertToDraft($pullRequestGraphQLId: ID!) {
517
556
  convertPullRequestToDraft(input: { pullRequestId: $pullRequestGraphQLId }) {
518
557
  pullRequest {
519
558
  id
520
559
  }
521
560
  }
522
- }`,o=await I(this.config,{query:n,variables:{pullRequestGraphQLId:e}},r);if(!o.body.data?.convertPullRequestToDraft?.pullRequest?.id)throw new f("Could not convert pull request to draft",o.body.errors)}async setPullRequestAsDraft(e,r={}){let{pullRequest:{graphQLId:n},isDraft:o}=e;if(!n)throw new Error('GitHub requires "graphQLId" for this function.');if(o){await this.convertPullRequestToDraft(n,r);return}await this.markPullRequestReadyForReview(n,r)}async setPullRequestReviewers(e,r={}){let{pullRequest:{reviews:n,graphQLId:o},reviewers:a}=e;if(!n)throw new Error('GitHub requires "reviews" for this function');if(!o)throw new Error('GitHub requires "graphQLId" for this function.');let i=n.filter(d=>d.state!=="REVIEW_REQUESTED").map(d=>{if(!d.reviewer.graphQLId)throw new Error('GitHub requires reviewer "graphQLId" for this function.');return d.reviewer.graphQLId}),u=a.map(d=>{if(!d.graphQLId)throw new Error('GitHub requires reviewer "graphQLId" for this function.');return d.graphQLId}).filter(d=>i.indexOf(d)===-1),l=`mutation SetPullRequestReviewers($pullRequestGraphQLId: ID!, $reviewerGraphQLIds: [ID!]!) {
561
+ }`,o=await R(this.config,{query:n,variables:{pullRequestGraphQLId:e}},t);if(!o.body.data?.convertPullRequestToDraft?.pullRequest?.id)throw new f("Could not convert pull request to draft",o.body.errors)}async setPullRequestAsDraft(e,t={}){let{pullRequest:{graphQLId:n},isDraft:o}=e;if(!n)throw new Error('GitHub requires "graphQLId" for this function.');if(o){await this.convertPullRequestToDraft(n,t);return}await this.markPullRequestReadyForReview(n,t)}async setPullRequestReviewers(e,t={}){let{pullRequest:{reviews:n,graphQLId:o},reviewers:a}=e;if(!n)throw new Error('GitHub requires "reviews" for this function');if(!o)throw new Error('GitHub requires "graphQLId" for this function.');let i=n.filter(d=>d.state!=="REVIEW_REQUESTED").map(d=>{if(!d.reviewer.graphQLId)throw new Error('GitHub requires reviewer "graphQLId" for this function.');return d.reviewer.graphQLId}),u=a.map(d=>{if(!d.graphQLId)throw new Error('GitHub requires reviewer "graphQLId" for this function.');return d.graphQLId}).filter(d=>i.indexOf(d)===-1),l=`mutation SetPullRequestReviewers($pullRequestGraphQLId: ID!, $reviewerGraphQLIds: [ID!]!) {
523
562
  requestReviews(input: { pullRequestId: $pullRequestGraphQLId, userIds: $reviewerGraphQLIds }) {
524
563
  pullRequest {
525
564
  id
526
565
  }
527
566
  }
528
- }`,p=await I(this.config,{query:l,variables:{pullRequestGraphQLId:o,reviewerGraphQLIds:u}},r);if(!p.body.data?.requestReviews?.pullRequest?.id)throw new f("Could not set pull request reviewers",p.body.errors)}async reRequestPullRequestReviews(e,r={}){let{pullRequest:{reviews:n,graphQLId:o},reviewers:a}=e;if(!o)throw new Error('GitHub requires "graphQLId" for this function.');if(!n)throw new Error('GitHub requires "reviews" for this function.');let i=[];for(let p of a){if(!p.graphQLId)throw new Error('GitHub requires reviwer "graphQLId" for this function.');if(!n.find(d=>d.reviewer.graphQLId===p.graphQLId))throw new Error("Can only re-request review from existing reviewer.");i.push(p.graphQLId)}let u=`mutation SetPullRequestReviewers($pullRequestGraphQLId: ID!, $reviewerGraphQLIds: [ID!]!) {
567
+ }`,p=await R(this.config,{query:l,variables:{pullRequestGraphQLId:o,reviewerGraphQLIds:u}},t);if(!p.body.data?.requestReviews?.pullRequest?.id)throw new f("Could not set pull request reviewers",p.body.errors)}async reRequestPullRequestReviews(e,t={}){let{pullRequest:{reviews:n,graphQLId:o},reviewers:a}=e;if(!o)throw new Error('GitHub requires "graphQLId" for this function.');if(!n)throw new Error('GitHub requires "reviews" for this function.');let i=[];for(let p of a){if(!p.graphQLId)throw new Error('GitHub requires reviwer "graphQLId" for this function.');if(!n.find(d=>d.reviewer.graphQLId===p.graphQLId))throw new Error("Can only re-request review from existing reviewer.");i.push(p.graphQLId)}let u=`mutation SetPullRequestReviewers($pullRequestGraphQLId: ID!, $reviewerGraphQLIds: [ID!]!) {
529
568
  requestReviews(input: { pullRequestId: $pullRequestGraphQLId, userIds: $reviewerGraphQLIds, union: true }) {
530
569
  pullRequest {
531
570
  id
532
571
  }
533
572
  }
534
- }`,l=await I(this.config,{query:u,variables:{pullRequestGraphQLId:o,reviewerGraphQLIds:i}},r);if(!l.body.data?.requestReviews?.pullRequest?.id)throw new f("Could not re-request pull request reviews",l.body.errors)}async setPullRequestAssignees(e,r={}){let{pullRequest:n,assignees:o}=e;if(!n.graphQLId)throw new Error('GitHub requires "graphQLId" for this function.');let a=o.map(l=>{if(!l.graphQLId)throw new Error('GitHub requires assignee "graphQLId" for this function.');return l.graphQLId}),i=`mutation SetPullRequestAssignees($pullRequestGraphQLId: ID!, $assigneeGraphQLIds: [ID!]!) {
573
+ }`,l=await R(this.config,{query:u,variables:{pullRequestGraphQLId:o,reviewerGraphQLIds:i}},t);if(!l.body.data?.requestReviews?.pullRequest?.id)throw new f("Could not re-request pull request reviews",l.body.errors)}async setPullRequestAssignees(e,t={}){let{pullRequest:n,assignees:o}=e;if(!n.graphQLId)throw new Error('GitHub requires "graphQLId" for this function.');let a=o.map(l=>{if(!l.graphQLId)throw new Error('GitHub requires assignee "graphQLId" for this function.');return l.graphQLId}),i=`mutation SetPullRequestAssignees($pullRequestGraphQLId: ID!, $assigneeGraphQLIds: [ID!]!) {
535
574
  updatePullRequest(input: { pullRequestId: $pullRequestGraphQLId, assigneeIds: $assigneeGraphQLIds }) {
536
575
  pullRequest {
537
576
  id
538
577
  }
539
578
  }
540
- }`,u=await I(this.config,{query:i,variables:{pullRequestGraphQLId:n.graphQLId,assigneeGraphQLIds:a}},r);if(!u.body.data?.updatePullRequest?.pullRequest?.id)throw new f("Could not set pull request assignees",u.body.errors)}async getReviewsForPullRequest(e,r={}){let n=await this.getEnterpriseVersion(r),{repo:{namespace:o,name:a},pullRequestId:i}=e,u=`query getPullRequests(
579
+ }`,u=await R(this.config,{query:i,variables:{pullRequestGraphQLId:n.graphQLId,assigneeGraphQLIds:a}},t);if(!u.body.data?.updatePullRequest?.pullRequest?.id)throw new f("Could not set pull request assignees",u.body.errors)}async getReviewsForPullRequest(e,t={}){let n=await this.getEnterpriseVersion(t),{repo:{namespace:o,name:a},pullRequestId:i}=e,u=`query getPullRequests(
541
580
  $namespace: String!
542
581
  $name: String!
543
582
  $pullRequestId: Int!
@@ -589,54 +628,54 @@ query getBlame($owner: String!, $name: String!, $ref: String!, $path: String!) {
589
628
  }
590
629
  }
591
630
  }
592
- }`,l=await I(this.config,{query:u,variables:{namespace:o,name:a,pullRequestId:i}},r),p=l.body.data?.repository.pullRequest.reviewThreads.nodes?.filter(C).reduce((c,g)=>{if(!g.comments.nodes?.[0]?.pullRequestReview)return c;let m=g.comments.nodes[0].pullRequestReview,b=Yr(g);return b&&(c[m.id]||(c[m.id]=[]),c[m.id].push(b)),c},{})??{};return{data:l.body.data?.repository.pullRequest.reviews.nodes?.filter(C).filter(c=>p[c.id]).map(c=>({author:c.author?{avatarUrl:c.author.avatarUrl,email:null,name:c.author.login}:null,body:c.body,createdAt:c.publishedAt?new Date(c.publishedAt):null,id:c.fullDatabaseId??c.databaseId.toString(),graphQLId:c.id,reviewComments:p[c.id],url:c.url}))??[]}}async getIssuesAssociatedWithUser(e,r={}){let[n,o]=e.cursor?.split(";")||[void 0,void 0],a=[];e.labelNames&&e.labelNames.forEach(c=>{a.push(`label:"${c}"`)});let[i,u]=await Promise.all([n==="null"?null:this.searchIssues({query:`author:${e.username} ${a.join(" ")}`,cursor:n,includeFromArchivedRepos:e.includeFromArchivedRepos,maxPageSize:e.maxPageSize},r),o==="null"?null:this.searchIssues({query:`assignee:${e.username} ${a.join(" ")}`,cursor:o,includeFromArchivedRepos:e.includeFromArchivedRepos,maxPageSize:e.maxPageSize},r)]),l={},p=[],d=c=>{l[c.id]||(l[c.id]=!0,p.push(c))};return i?.data.forEach(d),u?.data.forEach(d),{pageInfo:{hasNextPage:i?.pageInfo.hasNextPage||u?.pageInfo.hasNextPage||!1,endCursor:`${i?.pageInfo.hasNextPage&&i?.pageInfo.endCursor||"null"};${u?.pageInfo.hasNextPage&&u?.pageInfo.endCursor||"null"}`},data:p}}async setPullRequestLabels(e,r={}){let{pullRequest:n,labels:o}=e;if(!n.graphQLId)throw new Error('GitHub requires "graphQLId" for this function.');let a=`mutation SetPullRequestLabels($pullRequestGraphQLId: ID!, $labelGraphQLIds: [ID!]) {
631
+ }`,l=await R(this.config,{query:u,variables:{namespace:o,name:a,pullRequestId:i}},t),p=l.body.data?.repository.pullRequest.reviewThreads.nodes?.filter(C).reduce((c,g)=>{if(!g.comments.nodes?.[0]?.pullRequestReview)return c;let m=g.comments.nodes[0].pullRequestReview,b=Yr(g);return b&&(c[m.id]||(c[m.id]=[]),c[m.id].push(b)),c},{})??{};return{data:l.body.data?.repository.pullRequest.reviews.nodes?.filter(C).filter(c=>p[c.id]).map(c=>({author:c.author?{avatarUrl:c.author.avatarUrl,email:null,name:c.author.login}:null,body:c.body,createdAt:c.publishedAt?new Date(c.publishedAt):null,id:c.fullDatabaseId??c.databaseId.toString(),graphQLId:c.id,reviewComments:p[c.id],url:c.url}))??[]}}async getIssuesAssociatedWithUser(e,t={}){let[n,o]=e.cursor?.split(";")||[void 0,void 0],a=[];e.labelNames&&e.labelNames.forEach(c=>{a.push(`label:"${c}"`)});let[i,u]=await Promise.all([n==="null"?null:this.searchIssues({query:`author:${e.username} ${a.join(" ")}`,cursor:n,includeFromArchivedRepos:e.includeFromArchivedRepos,maxPageSize:e.maxPageSize},t),o==="null"?null:this.searchIssues({query:`assignee:${e.username} ${a.join(" ")}`,cursor:o,includeFromArchivedRepos:e.includeFromArchivedRepos,maxPageSize:e.maxPageSize},t)]),l={},p=[],d=c=>{l[c.id]||(l[c.id]=!0,p.push(c))};return i?.data.forEach(d),u?.data.forEach(d),{pageInfo:{hasNextPage:i?.pageInfo.hasNextPage||u?.pageInfo.hasNextPage||!1,endCursor:`${i?.pageInfo.hasNextPage&&i?.pageInfo.endCursor||"null"};${u?.pageInfo.hasNextPage&&u?.pageInfo.endCursor||"null"}`},data:p}}async setPullRequestLabels(e,t={}){let{pullRequest:n,labels:o}=e;if(!n.graphQLId)throw new Error('GitHub requires "graphQLId" for this function.');let a=`mutation SetPullRequestLabels($pullRequestGraphQLId: ID!, $labelGraphQLIds: [ID!]) {
593
632
  updatePullRequest(input: { pullRequestId: $pullRequestGraphQLId, labelIds: $labelGraphQLIds }) {
594
633
  pullRequest {
595
634
  id
596
635
  }
597
636
  }
598
- }`,i=await I(this.config,{query:a,variables:{pullRequestGraphQLId:n.graphQLId,labelGraphQLIds:o.map(u=>{if(!u.graphQLId)throw new Error('GitHub requires label "graphQLId" for this function.');return u.graphQLId})}},r);if(!i.body.data?.updatePullRequest?.pullRequest?.id)throw new f("Could not set pull request labels",i.body.errors)}async getIssuesForRepos(e,r={}){let n=Je(e.startQuery||""),{cursor:o,assigneeLogins:a,updatedBefore:i,authorLogin:u,mentionLogin:l,labelNames:p}=e;return e.repos.forEach(d=>{n.push(`repo:${d.namespace}/${d.name}`)}),a&&a.forEach(d=>{n.push(`assignee:${d}`)}),i&&n.push(`updated:<${i}`),u&&n.push(`author:${u}`),l&&n.push(`mentions:${l}`),p&&p.forEach(d=>{n.push(`label:"${d}"`)}),this.searchIssues({query:`sort:updated ${n.join(" ")}`,cursor:o,includeFromArchivedRepos:e.includeFromArchivedRepos,maxPageSize:e.maxPageSize},r)}async closeIssueWithReason(e,r={}){let{issue:n,reason:o}=e;if(!n.graphQLId)throw new Error('GitHub requires "graphQLId" for this function.');let a=`mutation CloseIssueWithReason($issueGraphQLId: ID!, $reason: IssueClosedStateReason!) {
637
+ }`,i=await R(this.config,{query:a,variables:{pullRequestGraphQLId:n.graphQLId,labelGraphQLIds:o.map(u=>{if(!u.graphQLId)throw new Error('GitHub requires label "graphQLId" for this function.');return u.graphQLId})}},t);if(!i.body.data?.updatePullRequest?.pullRequest?.id)throw new f("Could not set pull request labels",i.body.errors)}async getIssuesForRepos(e,t={}){let n=Je(e.startQuery||""),{cursor:o,assigneeLogins:a,updatedBefore:i,authorLogin:u,mentionLogin:l,labelNames:p}=e;return e.repos.forEach(d=>{n.push(`repo:${d.namespace}/${d.name}`)}),a&&a.forEach(d=>{n.push(`assignee:${d}`)}),i&&n.push(`updated:<${i}`),u&&n.push(`author:${u}`),l&&n.push(`mentions:${l}`),p&&p.forEach(d=>{n.push(`label:"${d}"`)}),this.searchIssues({query:`sort:updated ${n.join(" ")}`,cursor:o,includeFromArchivedRepos:e.includeFromArchivedRepos,maxPageSize:e.maxPageSize},t)}async closeIssueWithReason(e,t={}){let{issue:n,reason:o}=e;if(!n.graphQLId)throw new Error('GitHub requires "graphQLId" for this function.');let a=`mutation CloseIssueWithReason($issueGraphQLId: ID!, $reason: IssueClosedStateReason!) {
599
638
  closeIssue(input: { issueId: $issueGraphQLId, stateReason: $reason }) {
600
639
  issue {
601
640
  id
602
641
  }
603
642
  }
604
- }`,i=await I(this.config,{query:a,variables:{issueGraphQLId:n.graphQLId,reason:o}},r);if(!i.body.data?.closeIssue?.issue?.id)throw new f("Could not close issue with reason",i.body.errors)}async closeIssue(e,r={}){let{issue:n}=e;if(!n.graphQLId)throw new Error('GitHub requires "graphQLId" for this function.');let o=`mutation SetIssueState($issueGraphQLId: ID!) {
643
+ }`,i=await R(this.config,{query:a,variables:{issueGraphQLId:n.graphQLId,reason:o}},t);if(!i.body.data?.closeIssue?.issue?.id)throw new f("Could not close issue with reason",i.body.errors)}async closeIssue(e,t={}){let{issue:n}=e;if(!n.graphQLId)throw new Error('GitHub requires "graphQLId" for this function.');let o=`mutation SetIssueState($issueGraphQLId: ID!) {
605
644
  updateIssue(input: { id: $issueGraphQLId, state: CLOSED }) {
606
645
  issue {
607
646
  id
608
647
  }
609
648
  }
610
- }`,a=await I(this.config,{query:o,variables:{issueGraphQLId:n.graphQLId}},r);if(!a.body.data?.updateIssue?.issue?.id)throw new f("Could not close issue",a.body.errors)}async reOpenIssue(e,r={}){let{issue:n}=e;if(!n.graphQLId)throw new Error('GitHub requires "graphQLId" for this function.');let o=`mutation ReOpenIssue($issueGraphQLId: ID!) {
649
+ }`,a=await R(this.config,{query:o,variables:{issueGraphQLId:n.graphQLId}},t);if(!a.body.data?.updateIssue?.issue?.id)throw new f("Could not close issue",a.body.errors)}async reOpenIssue(e,t={}){let{issue:n}=e;if(!n.graphQLId)throw new Error('GitHub requires "graphQLId" for this function.');let o=`mutation ReOpenIssue($issueGraphQLId: ID!) {
611
650
  reopenIssue(input: { issueId: $issueGraphQLId }) {
612
651
  issue {
613
652
  id
614
653
  }
615
654
  }
616
- }`,a=await I(this.config,{query:o,variables:{issueGraphQLId:n.graphQLId}},r);if(!a.body.data?.reopenIssue?.issue?.id)throw new f("Could not reopen issue",a.body.errors)}async setIssueLabels(e,r={}){let{issue:n,labels:o}=e;if(!n.graphQLId)throw new Error('GitHub requires "graphQLId" for this function.');let a=o.map(l=>l.graphQLId),i=`mutation SetIssueLabels($issueGraphQLId: ID!, $labelGraphQLIds: [ID!]) {
655
+ }`,a=await R(this.config,{query:o,variables:{issueGraphQLId:n.graphQLId}},t);if(!a.body.data?.reopenIssue?.issue?.id)throw new f("Could not reopen issue",a.body.errors)}async setIssueLabels(e,t={}){let{issue:n,labels:o}=e;if(!n.graphQLId)throw new Error('GitHub requires "graphQLId" for this function.');let a=o.map(l=>l.graphQLId),i=`mutation SetIssueLabels($issueGraphQLId: ID!, $labelGraphQLIds: [ID!]) {
617
656
  updateIssue(input: { id: $issueGraphQLId, labelIds: $labelGraphQLIds }) {
618
657
  issue {
619
658
  id
620
659
  }
621
660
  }
622
- }`,u=await I(this.config,{query:i,variables:{issueGraphQLId:n.graphQLId,labelGraphQLIds:a}},r);if(!u.body.data?.updateIssue?.issue?.id)throw new f("Could not set issue labels",u.body.errors)}async setIssueMilestone(e,r={}){let{issue:n,milestone:o}=e;if(!n.graphQLId)throw new Error('GitHub requires "graphQLId" for this function.');if(o&&!o.graphQLId)throw new Error('GitHub requires milestone "graphQLId" for this function.');let a=`mutation SetIssueMilestone($issueGraphQLId: ID!, $milestoneGraphQLId: ID) {
661
+ }`,u=await R(this.config,{query:i,variables:{issueGraphQLId:n.graphQLId,labelGraphQLIds:a}},t);if(!u.body.data?.updateIssue?.issue?.id)throw new f("Could not set issue labels",u.body.errors)}async setIssueMilestone(e,t={}){let{issue:n,milestone:o}=e;if(!n.graphQLId)throw new Error('GitHub requires "graphQLId" for this function.');if(o&&!o.graphQLId)throw new Error('GitHub requires milestone "graphQLId" for this function.');let a=`mutation SetIssueMilestone($issueGraphQLId: ID!, $milestoneGraphQLId: ID) {
623
662
  updateIssue(input: { id: $issueGraphQLId, milestoneId: $milestoneGraphQLId }) {
624
663
  issue {
625
664
  id
626
665
  }
627
666
  }
628
- }`,i=await I(this.config,{query:`${a}`,variables:{issueGraphQLId:n.graphQLId,milestoneGraphQLId:o?.graphQLId??null}},r);if(!i.body.data?.updateIssue?.issue?.id)throw new f("Could not set milestone of issue",i.body.errors)}async setIssueAssignees(e,r={}){let{issue:n,assignees:o}=e;if(!n.graphQLId)throw new Error('GitHub requires "graphQLId" for this function.');let a=o.map(l=>{if(!l.graphQLId)throw new Error('GitHub requires assignee "graphQLId" for this function.');return l.graphQLId}),i=`mutation SetIssueAssignees($issueGraphQLId: ID!, $assigneeGraphQLIds: [ID!]!) {
667
+ }`,i=await R(this.config,{query:`${a}`,variables:{issueGraphQLId:n.graphQLId,milestoneGraphQLId:o?.graphQLId??null}},t);if(!i.body.data?.updateIssue?.issue?.id)throw new f("Could not set milestone of issue",i.body.errors)}async setIssueAssignees(e,t={}){let{issue:n,assignees:o}=e;if(!n.graphQLId)throw new Error('GitHub requires "graphQLId" for this function.');let a=o.map(l=>{if(!l.graphQLId)throw new Error('GitHub requires assignee "graphQLId" for this function.');return l.graphQLId}),i=`mutation SetIssueAssignees($issueGraphQLId: ID!, $assigneeGraphQLIds: [ID!]!) {
629
668
  updateIssue(input: { id: $issueGraphQLId, assigneeIds: $assigneeGraphQLIds }) {
630
669
  issue {
631
670
  id
632
671
  }
633
672
  }
634
- }`,u=await I(this.config,{query:i,variables:{issueGraphQLId:n.graphQLId,assigneeGraphQLIds:a}},r);if(!u.body.data?.updateIssue?.issue?.id)throw new f("Could not set issue assignees",u.body.errors)}async getMilestonesForRepo(e,r={}){let{repo:{namespace:n,name:o},cursor:a}=e,i=await I(this.config,{query:`
673
+ }`,u=await R(this.config,{query:i,variables:{issueGraphQLId:n.graphQLId,assigneeGraphQLIds:a}},t);if(!u.body.data?.updateIssue?.issue?.id)throw new f("Could not set issue assignees",u.body.errors)}async getMilestonesForRepo(e,t={}){let{repo:{namespace:n,name:o},cursor:a}=e,i=await R(this.config,{query:`
635
674
  query getLabelsForRepo($owner: String!, $name: String! $cursor: String, $first: Int!) {
636
675
  repository(owner: $owner, name: $name) {
637
676
  milestones(first: $first, after: $cursor) {
638
677
  nodes {
639
- ${Ie}
678
+ ${Re}
640
679
  }
641
680
  pageInfo {
642
681
  endCursor
@@ -645,12 +684,12 @@ query getLabelsForRepo($owner: String!, $name: String! $cursor: String, $first:
645
684
  }
646
685
  }
647
686
  }
648
- `,variables:{owner:n,name:o,cursor:a,first:S}},r);if(!i.body.data)throw new f("Could not fetch milestones",i.body.errors);return{pageInfo:i.body.data.repository.milestones?.pageInfo??{endCursor:null,hasNextPage:!1},data:i.body.data.repository.milestones?.nodes?.map(tt)??[]}}async getLabelsForRepo(e,r={}){let{repo:{namespace:n,name:o},cursor:a}=e,i=await I(this.config,{query:`
687
+ `,variables:{owner:n,name:o,cursor:a,first:S}},t);if(!i.body.data)throw new f("Could not fetch milestones",i.body.errors);return{pageInfo:i.body.data.repository.milestones?.pageInfo??{endCursor:null,hasNextPage:!1},data:i.body.data.repository.milestones?.nodes?.map(tt)??[]}}async getLabelsForRepo(e,t={}){let{repo:{namespace:n,name:o},cursor:a}=e,i=await R(this.config,{query:`
649
688
  query getLabelsForRepo($owner: String!, $name: String! $cursor: String, $first: Int!) {
650
689
  repository(owner: $owner, name: $name) {
651
690
  labels(first: $first, after: $cursor) {
652
691
  nodes {
653
- ${Re}
692
+ ${Ie}
654
693
  }
655
694
  pageInfo {
656
695
  endCursor
@@ -659,7 +698,7 @@ query getLabelsForRepo($owner: String!, $name: String! $cursor: String, $first:
659
698
  }
660
699
  }
661
700
  }
662
- `,variables:{owner:n,name:o,cursor:a,first:S}},r);if(!i.body.data)throw new f("Could not fetch labels",i.body.errors);return{pageInfo:i.body.data.repository.labels?.pageInfo??{endCursor:null,hasNextPage:!1},data:i.body.data.repository.labels?.nodes?.map(et)??[]}}async getTreeForRepo(e,r={}){let n=await this.config.request({url:`${K(this.config,r)}/repos/${e.repo.namespace}/${e.repo.name}/git/trees/${e.branch}?recursive=1`,headers:{...h(r.token||this.config.token)}});if(!n.body)throw new Error("Could not fetch trees");return{data:n.body.tree.map(Jr)}}};var rs="https://gitlab.com/api/v4",ss="https://gitlab.com/api/graphql",rt=/\/api\/v\d+$/,_t=t=>{if(t.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.")},Pe=(t,s)=>{let e=s.baseUrl||t.baseUrl;return e?(e=e.replace(/\/$/,""),_t(e),rt.test(e)||(e=e+"/api/v4"),e):rs},ns=(t,s)=>{let e=s.baseUrl||t.baseUrl;return e?(e=e.replace(/\/$/,""),_t(e),rt.test(e)&&(e=e.replace(rt,"")),`${e}/api/graphql`):ss},y=(t,s,e)=>{let r=h(e.token||t.token);return t.request({url:ns(t,e),method:"POST",headers:{...r,"Content-Type":"application/json"},body:JSON.stringify(s)})},we=t=>t?.map(s=>`"${s.message}"`).join(", ");var it=t=>t.split("/").slice(0,-1).join("/"),ut=t=>t.split("/").at(-1)??"",Se=t=>({id:t.id.replace(Z,""),graphQLId:t.id,namespace:it(t.fullPath),name:ut(t.fullPath),webUrl:t.webUrl}),Ft=t=>({id:t.id.replace(Z,""),graphQLId:t.id,httpsUrl:t.httpUrlToRepo,namespace:it(t.fullPath),name:ut(t.fullPath),sshUrl:t.sshUrlToRepo,webUrl:t.webUrl}),os={assigned:"assignedMergeRequests",authored:"authoredMergeRequests",reviewRequested:"reviewRequestedMergeRequests"},as={CAN_BE_MERGED:"MERGEABLE",CANNOT_BE_MERGED:"CONFLICTS",CANNOT_BE_MERGED_RECHECK:"UNKNOWN",UNCHECKED:"UNKNOWN",CHECKING:"UNKNOWN"};var is="gid://gitlab/User/",Z="gid://gitlab/Project/",us="gid://gitlab/MergeRequest/",ls="gid://gitlab/Issue/",ps="gid://gitlab/ProjectLabel/",ds="gid://gitlab/Milestone/",cs="gid://gitlab/Ci::Build/",lt=`
701
+ `,variables:{owner:n,name:o,cursor:a,first:S}},t);if(!i.body.data)throw new f("Could not fetch labels",i.body.errors);return{pageInfo:i.body.data.repository.labels?.pageInfo??{endCursor:null,hasNextPage:!1},data:i.body.data.repository.labels?.nodes?.map(et)??[]}}async getTreeForRepo(e,t={}){let n=await this.config.request({url:`${K(this.config,t)}/repos/${e.repo.namespace}/${e.repo.name}/git/trees/${e.branch}?recursive=1`,headers:{...h(t.token||this.config.token)}});if(!n.body)throw new Error("Could not fetch trees");return{data:n.body.tree.map(Jr)}}};var rs="https://gitlab.com/api/v4",ss="https://gitlab.com/api/graphql",rt=/\/api\/v\d+$/,_t=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.")},Pe=(r,s)=>{let e=s.baseUrl||r.baseUrl;return e?(e=e.replace(/\/$/,""),_t(e),rt.test(e)||(e=e+"/api/v4"),e):rs},ns=(r,s)=>{let e=s.baseUrl||r.baseUrl;return e?(e=e.replace(/\/$/,""),_t(e),rt.test(e)&&(e=e.replace(rt,"")),`${e}/api/graphql`):ss},y=(r,s,e)=>{let t=h(e.token||r.token);return r.request({url:ns(r,e),method:"POST",headers:{...t,"Content-Type":"application/json"},body:JSON.stringify(s)})},we=r=>r?.map(s=>`"${s.message}"`).join(", ");var it=r=>r.split("/").slice(0,-1).join("/"),ut=r=>r.split("/").at(-1)??"",Se=r=>({id:r.id.replace(Z,""),graphQLId:r.id,namespace:it(r.fullPath),name:ut(r.fullPath),webUrl:r.webUrl}),Ft=r=>({id:r.id.replace(Z,""),graphQLId:r.id,httpsUrl:r.httpUrlToRepo,namespace:it(r.fullPath),name:ut(r.fullPath),sshUrl:r.sshUrlToRepo,webUrl:r.webUrl}),os={assigned:"assignedMergeRequests",authored:"authoredMergeRequests",reviewRequested:"reviewRequestedMergeRequests"},as={CAN_BE_MERGED:"MERGEABLE",CANNOT_BE_MERGED:"CONFLICTS",CANNOT_BE_MERGED_RECHECK:"UNKNOWN",UNCHECKED:"UNKNOWN",CHECKING:"UNKNOWN"};var is="gid://gitlab/User/",Z="gid://gitlab/Project/",us="gid://gitlab/MergeRequest/",ls="gid://gitlab/Issue/",ps="gid://gitlab/ProjectLabel/",ds="gid://gitlab/Milestone/",cs="gid://gitlab/Ci::Build/",lt=`
663
702
  description
664
703
  dueDate
665
704
  id
@@ -740,7 +779,7 @@ stages {
740
779
  name
741
780
  }
742
781
  }
743
- `,Qt=(t,s,e)=>`
782
+ `,Qt=(r,s,e)=>`
744
783
  id
745
784
  state
746
785
  author {
@@ -787,16 +826,16 @@ labels {
787
826
  ${pt}
788
827
  }
789
828
  }
790
- ${t?"project { id httpUrlToRepo fullPath sshUrlToRepo webUrl archived } sourceProject { id httpUrlToRepo fullPath sshUrlToRepo webUrl }":""}
829
+ ${r?"project { id httpUrlToRepo fullPath sshUrlToRepo webUrl archived } sourceProject { id httpUrlToRepo fullPath sshUrlToRepo webUrl }":""}
791
830
  ${s?`milestone { ${lt} }`:""}
792
831
  ${e?`headPipeline { ${gs} }`:""}
793
- `,j=t=>`${t.namespace}/${t.name}`,ms=t=>`${t.namespace}/${t.name}`,hs=t=>({canCreateWebhook:t.adminOperations,canPush:t.pushCode,isAdmin:t.adminOperations}),ot=t=>({id:t.id.replace(Z,""),graphQLId:t.id,namespace:it(t.fullPath),name:ut(t.fullPath),webUrl:t.webUrl,httpsUrl:t.httpUrlToRepo,sshUrl:t.sshUrlToRepo,defaultBranch:t.repository?.rootRef?{name:t.repository.rootRef}:null,permissions:hs(t.userPermissions)}),fs=t=>({path:t.path,isDirectory:t.type==="tree"}),Is={opened:"OPEN",merged:"MERGED",closed:"CLOSED"},Bt=(t,s,e)=>!s&&t?.startsWith("/")?`https://gitlab.com${t}`:s&&t?.startsWith("/")&&e?`${e.replace(/\/+?$/,"")}${t}`:t,N=(t,s,e)=>{let r=Bt(t.avatarUrl,s,e);return{id:t.id.replace(is,""),graphQLId:t.id,name:t.name,username:t.username,email:t.publicEmail??null,avatarUrl:r,url:t.webUrl}},dt=t=>({color:t.color,description:t.description,id:t.id.replace(ps,""),graphQLId:t.id,name:t.title}),Rs=(t,s)=>t?t==="FAILED"&&s?"WARNING":{CANCELED:"CANCELLED",CREATED:"PENDING",FAILED:"FAILED",MANUAL:"OPTIONAL_ACTION_REQUIRED",PENDING:"PENDING",PREPARING:"RUNNING",RUNNING:"RUNNING",SCHEDULED:"PENDING",SKIPPED:"SKIPPED",SUCCESS:"SUCCESS",WAITING_FOR_CALLBACK:"PENDING",WAITING_FOR_RESOURCE:"PENDING"}[t]:null,bs=(t,s,e)=>{let r={APPROVED:"APPROVED",REQUESTED_CHANGES:"CHANGES_REQUESTED",REVIEWED:"COMMENTED",UNAPPROVED:"REVIEW_REQUESTED",UNREVIEWED:"REVIEW_REQUESTED"};return{reviewer:N(t,s,e),state:t.mergeRequestInteraction?.reviewState?r[t.mergeRequestInteraction.reviewState]:"REVIEW_REQUESTED"}},jt=(t,s,e,r,n)=>{let o=t.reviewers?.nodes?t.reviewers.nodes.map(a=>bs(a,r,n)):null;return{id:t.id.replace(us,""),graphQLId:t.id,title:t.title,number:parseInt(t.iid,10),state:Is[t.state],commentCount:t.userNotesCount||0,upvoteCount:t.upvotes,author:t.author?N(t.author,r,n):null,createdDate:new Date(t.createdAt),isDraft:t.draft,repository:{id:s.id,graphQLId:s.graphQLId,name:s.name,owner:{login:s.namespace},remoteInfo:s.httpsUrl&&s.sshUrl?{cloneUrlHTTPS:s.httpsUrl,cloneUrlSSH:s.sshUrl}:null},headRepository:e?{id:e.id,graphQLId:e.graphQLId,name:e.name,owner:{login:e.namespace},remoteInfo:{cloneUrlHTTPS:e.httpsUrl,cloneUrlSSH:e.sshUrl}}:null,headCommit:{buildStatuses:t.headPipeline?.stages?.nodes?.flatMap(a=>a.jobs?.nodes?.map(i=>({completedAt:i.finishedAt?new Date(i.finishedAt):null,description:null,name:i.name??null,state:Rs(i.status,i.allowFailure),stage:a.name??null,startedAt:new Date(i.createdAt),url:`${s.webUrl}/-/jobs/${i.id.replace(cs,"")}`}))??[])??[]},baseRef:{name:t.targetBranch,oid:t.diffRefs?.baseSha??null},headRef:{name:t.sourceBranch,oid:t.diffRefs?.headSha??null},url:t.webUrl,updatedDate:new Date(t.updatedAt),closedDate:t.mergedAt?new Date(t.mergedAt):null,mergedDate:t.mergedAt?new Date(t.mergedAt):null,assignees:t.assignees?.nodes?t.assignees.nodes.map(a=>N(a,r,n)):null,reviews:o,reviewDecision:G(o),additions:t.diffStatsSummary?.additions||0,deletions:t.diffStatsSummary?.deletions||0,fileCount:t.diffStatsSummary?.fileCount||0,commitCount:t.commitCount||0,mergeableState:as[t.mergeStatusEnum],milestone:t.milestone?ct(t.milestone,s.webUrl):null,labels:t.labels?.nodes?.map(dt)??[],permissions:null}},at=(t,s,e,r)=>({author:N(t.author,e,r),assignees:t.assignees.nodes.map(n=>N(n,e,r)),commentCount:t.userNotesCount,closedDate:t.closedAt?new Date(t.closedAt):null,createdDate:new Date(t.createdAt),description:t.description,graphQLId:t.id,id:t.id.replace(ls,""),labels:t.labels?.nodes?.map(dt)??[],number:t.iid,repository:{id:s.id.replace(Z,""),graphQLId:s.id,name:s.name,owner:{login:s.namespace}},updatedDate:new Date(t.updatedAt),upvoteCount:t.upvotes,state:{name:t.state,color:null},type:t.type,title:t.title,url:t.webUrl,milestone:t.milestone?ct(t.milestone,s.webUrl):null}),ct=(t,s)=>({id:t.id.replace(ds,""),graphQLId:t.id,number:parseInt(t.iid,10),title:t.title,description:t.description,isOpen:t.state==="active",url:`${s}/-/${t.webPath.replace(/.+?\/-\//,"")}`,startDate:t.startDate?new Date(t.startDate):null,dueDate:t.dueDate?new Date(t.dueDate):null}),Y=class extends L{getIsSelfHosted(s){return!!s.baseUrl||!!this.config.baseUrl}async getCurrentUser(s={},e={}){let n=(await y(this.config,{query:`
832
+ `,j=r=>`${r.namespace}/${r.name}`,ms=r=>`${r.namespace}/${r.name}`,hs=r=>({canCreateWebhook:r.adminOperations,canPush:r.pushCode,isAdmin:r.adminOperations}),ot=r=>({id:r.id.replace(Z,""),graphQLId:r.id,namespace:it(r.fullPath),name:ut(r.fullPath),webUrl:r.webUrl,httpsUrl:r.httpUrlToRepo,sshUrl:r.sshUrlToRepo,defaultBranch:r.repository?.rootRef?{name:r.repository.rootRef}:null,permissions:hs(r.userPermissions)}),fs=r=>({path:r.path,isDirectory:r.type==="tree"}),Rs={opened:"OPEN",merged:"MERGED",closed:"CLOSED"},Bt=(r,s,e)=>!s&&r?.startsWith("/")?`https://gitlab.com${r}`:s&&r?.startsWith("/")&&e?`${e.replace(/\/+?$/,"")}${r}`:r,N=(r,s,e)=>{let t=Bt(r.avatarUrl,s,e);return{id:r.id.replace(is,""),graphQLId:r.id,name:r.name,username:r.username,email:r.publicEmail??null,avatarUrl:t,url:r.webUrl}},dt=r=>({color:r.color,description:r.description,id:r.id.replace(ps,""),graphQLId:r.id,name:r.title}),Is=(r,s)=>r?r==="FAILED"&&s?"WARNING":{CANCELED:"CANCELLED",CREATED:"PENDING",FAILED:"FAILED",MANUAL:"OPTIONAL_ACTION_REQUIRED",PENDING:"PENDING",PREPARING:"RUNNING",RUNNING:"RUNNING",SCHEDULED:"PENDING",SKIPPED:"SKIPPED",SUCCESS:"SUCCESS",WAITING_FOR_CALLBACK:"PENDING",WAITING_FOR_RESOURCE:"PENDING"}[r]:null,bs=(r,s,e)=>{let t={APPROVED:"APPROVED",REQUESTED_CHANGES:"CHANGES_REQUESTED",REVIEWED:"COMMENTED",UNAPPROVED:"REVIEW_REQUESTED",UNREVIEWED:"REVIEW_REQUESTED"};return{reviewer:N(r,s,e),state:r.mergeRequestInteraction?.reviewState?t[r.mergeRequestInteraction.reviewState]:"REVIEW_REQUESTED"}},jt=(r,s,e,t,n)=>{let o=r.reviewers?.nodes?r.reviewers.nodes.map(a=>bs(a,t,n)):null;return{id:r.id.replace(us,""),graphQLId:r.id,title:r.title,number:parseInt(r.iid,10),state:Rs[r.state],commentCount:r.userNotesCount||0,upvoteCount:r.upvotes,author:r.author?N(r.author,t,n):null,createdDate:new Date(r.createdAt),isDraft:r.draft,repository:{id:s.id,graphQLId:s.graphQLId,name:s.name,owner:{login:s.namespace},remoteInfo:s.httpsUrl&&s.sshUrl?{cloneUrlHTTPS:s.httpsUrl,cloneUrlSSH:s.sshUrl}:null},headRepository:e?{id:e.id,graphQLId:e.graphQLId,name:e.name,owner:{login:e.namespace},remoteInfo:{cloneUrlHTTPS:e.httpsUrl,cloneUrlSSH:e.sshUrl}}:null,headCommit:{buildStatuses:r.headPipeline?.stages?.nodes?.flatMap(a=>a.jobs?.nodes?.map(i=>({completedAt:i.finishedAt?new Date(i.finishedAt):null,description:null,name:i.name??null,state:Is(i.status,i.allowFailure),stage:a.name??null,startedAt:new Date(i.createdAt),url:`${s.webUrl}/-/jobs/${i.id.replace(cs,"")}`}))??[])??[]},baseRef:{name:r.targetBranch,oid:r.diffRefs?.baseSha??null},headRef:{name:r.sourceBranch,oid:r.diffRefs?.headSha??null},url:r.webUrl,updatedDate:new Date(r.updatedAt),closedDate:r.mergedAt?new Date(r.mergedAt):null,mergedDate:r.mergedAt?new Date(r.mergedAt):null,assignees:r.assignees?.nodes?r.assignees.nodes.map(a=>N(a,t,n)):null,reviews:o,reviewDecision:G(o),additions:r.diffStatsSummary?.additions||0,deletions:r.diffStatsSummary?.deletions||0,fileCount:r.diffStatsSummary?.fileCount||0,commitCount:r.commitCount||0,mergeableState:as[r.mergeStatusEnum],milestone:r.milestone?ct(r.milestone,s.webUrl):null,labels:r.labels?.nodes?.map(dt)??[],permissions:null}},at=(r,s,e,t)=>({author:N(r.author,e,t),assignees:r.assignees.nodes.map(n=>N(n,e,t)),commentCount:r.userNotesCount,closedDate:r.closedAt?new Date(r.closedAt):null,createdDate:new Date(r.createdAt),description:r.description,graphQLId:r.id,id:r.id.replace(ls,""),labels:r.labels?.nodes?.map(dt)??[],number:r.iid,repository:{id:s.id.replace(Z,""),graphQLId:s.id,name:s.name,owner:{login:s.namespace}},updatedDate:new Date(r.updatedAt),upvoteCount:r.upvotes,state:{name:r.state,color:null},type:r.type,title:r.title,url:r.webUrl,milestone:r.milestone?ct(r.milestone,s.webUrl):null}),ct=(r,s)=>({id:r.id.replace(ds,""),graphQLId:r.id,number:parseInt(r.iid,10),title:r.title,description:r.description,isOpen:r.state==="active",url:`${s}/-/${r.webPath.replace(/.+?\/-\//,"")}`,startDate:r.startDate?new Date(r.startDate):null,dueDate:r.dueDate?new Date(r.dueDate):null}),Y=class extends L{getIsSelfHosted(s){return!!s.baseUrl||!!this.config.baseUrl}async getCurrentUser(s={},e={}){let n=(await y(this.config,{query:`
794
833
  query getCurrentUser {
795
834
  currentUser {
796
835
  ${k}
797
836
  }
798
837
  }
799
- `},e)).body.data?.currentUser;if(!n)throw new Error("Current user not found.");return{data:N(n,this.getIsSelfHosted(e),this.config.baseUrl??e.baseUrl)}}async getUserForCommit(s,e={}){let r=j(s.repo),o=(await y(this.config,{query:`
838
+ `},e)).body.data?.currentUser;if(!n)throw new Error("Current user not found.");return{data:N(n,this.getIsSelfHosted(e),this.config.baseUrl??e.baseUrl)}}async getUserForCommit(s,e={}){let t=j(s.repo),o=(await y(this.config,{query:`
800
839
  query getUserForCommit($fullPath: ID!, $oid: String!) {
801
840
  project(fullPath: $fullPath) {
802
841
  repository {
@@ -812,7 +851,7 @@ query getUserForCommit($fullPath: ID!, $oid: String!) {
812
851
  }
813
852
  }
814
853
  }
815
- `,variables:{fullPath:r,oid:s.oid}},e)).body.data?.project?.repository?.tree?.lastCommit;if(!o)throw new Error("Commit not found.");let a=Bt(o.author.avatarUrl,this.getIsSelfHosted(e),this.config.baseUrl??e.baseUrl);return{data:{name:o.authorName,email:o.authorEmail,avatarUrl:a}}}async getAccountForEmail(s,e={}){let n=(await y(this.config,{query:`
854
+ `,variables:{fullPath:t,oid:s.oid}},e)).body.data?.project?.repository?.tree?.lastCommit;if(!o)throw new Error("Commit not found.");let a=Bt(o.author.avatarUrl,this.getIsSelfHosted(e),this.config.baseUrl??e.baseUrl);return{data:{name:o.authorName,email:o.authorEmail,avatarUrl:a}}}async getAccountForEmail(s,e={}){let n=(await y(this.config,{query:`
816
855
  query getAccountForEmail($email: String!) {
817
856
  users(search: $email) {
818
857
  nodes {
@@ -826,7 +865,7 @@ query getAccountForUsername($username: String!) {
826
865
  ${k}
827
866
  }
828
867
  }
829
- `,variables:{username:s.username}},e)).body.data?.user;if(!n)throw new Error("User not found.");return{data:N(n,this.getIsSelfHosted(e),this.config.baseUrl??e.baseUrl)}}async getAccountsForRepo(s,e={}){let{repo:{namespace:r,name:n},cursor:o}=s,a=await y(this.config,{query:`
868
+ `,variables:{username:s.username}},e)).body.data?.user;if(!n)throw new Error("User not found.");return{data:N(n,this.getIsSelfHosted(e),this.config.baseUrl??e.baseUrl)}}async getAccountsForRepo(s,e={}){let{repo:{namespace:t,name:n},cursor:o}=s,a=await y(this.config,{query:`
830
869
  query getAccountsForRepo(
831
870
  $fullPath: ID!
832
871
  $after: String
@@ -847,13 +886,13 @@ query getAccountsForRepo(
847
886
  }
848
887
  }
849
888
  }
850
- `,variables:{fullPath:`${r}/${n}`,after:o}},e),i=a.body.data?.project?.projectMembers?.nodes?.map(u=>u.user).filter(u=>u!==null);return{pageInfo:a.body.data?.project?.projectMembers?.pageInfo??{endCursor:null,hasNextPage:!1},data:i?.map(u=>N(u,this.getIsSelfHosted(e),this.config.baseUrl??e.baseUrl))??[]}}async getRepo(s,e={}){let r=j(s),n=await y(this.config,{query:`
889
+ `,variables:{fullPath:`${t}/${n}`,after:o}},e),i=a.body.data?.project?.projectMembers?.nodes?.map(u=>u.user).filter(u=>u!==null);return{pageInfo:a.body.data?.project?.projectMembers?.pageInfo??{endCursor:null,hasNextPage:!1},data:i?.map(u=>N(u,this.getIsSelfHosted(e),this.config.baseUrl??e.baseUrl))??[]}}async getRepo(s,e={}){let t=j(s),n=await y(this.config,{query:`
851
890
  query getRepo($fullPath: ID!) {
852
891
  project(fullPath: $fullPath) {
853
892
  ${st}
854
893
  }
855
894
  }
856
- `,variables:{fullPath:r}},e);if(!n.body.data?.project)throw new Error(`Repository ${r} not found`);return{data:ot(n.body.data.project)}}async getReposBase(s,e={}){let n=s.map(j).map((u,l)=>`
895
+ `,variables:{fullPath:t}},e);if(!n.body.data?.project)throw new Error(`Repository ${t} not found`);return{data:ot(n.body.data.project)}}async getReposBase(s,e={}){let n=s.map(j).map((u,l)=>`
857
896
  getRepo_${l}: project(fullPath: "${u}") {
858
897
  ${st}
859
898
  }
@@ -862,7 +901,7 @@ query getRepo($fullPath: ID!) {
862
901
  query batchGetRepos {
863
902
  ${n}
864
903
  }
865
- `},e);if(!o.body.data)throw new Error(we(o.body.errors)||o.statusText||"Unknown error");let a=[],i=[];return s.forEach((u,l)=>{let p=o.body.data[`getRepo_${l}`];p?a.push(ot(p)):i.push({input:u})}),{data:a,errors:i}}async getRepos(s,e={}){let r=[];for(let a=0;a<s.length;a+=15)r.push(s.slice(a,a+15));return(await Promise.all(r.map(a=>this.getReposBase(a,e)))).reduce((a,i)=>({data:[...a.data,...i.data],errors:[...a.errors,...i.errors]}),{data:[],errors:[]})}async getReposForCurrentUser(s,e={}){let r=await y(this.config,{query:`
904
+ `},e);if(!o.body.data)throw new Error(we(o.body.errors)||o.statusText||"Unknown error");let a=[],i=[];return s.forEach((u,l)=>{let p=o.body.data[`getRepo_${l}`];p?a.push(ot(p)):i.push({input:u})}),{data:a,errors:i}}async getRepos(s,e={}){let t=[];for(let a=0;a<s.length;a+=15)t.push(s.slice(a,a+15));return(await Promise.all(t.map(a=>this.getReposBase(a,e)))).reduce((a,i)=>({data:[...a.data,...i.data],errors:[...a.errors,...i.errors]}),{data:[],errors:[]})}async getReposForCurrentUser(s,e={}){let t=await y(this.config,{query:`
866
905
  query getReposForCurrentUser($after: String) {
867
906
  projects(membership: true first: 100 after: $after) {
868
907
  pageInfo {
@@ -874,10 +913,10 @@ query getReposForCurrentUser($after: String) {
874
913
  }
875
914
  }
876
915
  }
877
- `,variables:{after:s.cursor}},e);if(!r.body.data?.projects)throw new Error(we(r.body.errors)||r.statusText||"Unknown error");let n=r.body.data?.projects?.nodes||[];return{pageInfo:r.body.data?.projects?.pageInfo,data:n.map(ot)}}async getRefs(s,e,r={}){let n=j(e.repo),o=new URL(`${Pe(this.config,r)}/projects/${encodeURIComponent(n)}/repository/${s}`);o.searchParams.set("page",e.page?.toString()||"1"),o.searchParams.set("per_page",S.toString());let a=await this.config.request({url:o.toString(),headers:h(r.token||this.config.token)}),i=a.headers["x-next-page"];return{pageInfo:{hasNextPage:!!i,nextPage:i?parseInt(i,10):null},data:a.body.map(u=>({name:u.name,commit:{oid:u.commit.id,authoredDate:new Date(u.commit.authored_date),committedDate:new Date(u.commit.committed_date)}}))}}async getBranches(s,e={}){return this.getRefs("branches",s,e)}async getTags(s,e={}){return this.getRefs("tags",s,e)}async getBlame(s,e={}){let r=j(s.repo),n=new URL(`${Pe(this.config,e)}/projects/${encodeURIComponent(r)}/repository/files/${encodeURIComponent(s.path)}/blame`);n.searchParams.set("ref",s.ref);let o=await this.config.request({url:n.toString(),headers:h(e.token||this.config.token)}),a=0;return{data:{ranges:o.body.map(i=>{let u=a+1;return a+=i.lines.length,{startingLine:u,endingLine:a,commit:{oid:i.commit.id,parentOids:i.commit.parent_ids,authoredDate:new Date(i.commit.authored_date),author:{name:i.commit.author_name,email:i.commit.author_email,avatarUrl:null},committedDate:new Date(i.commit.committed_date),committer:{name:i.commit.committer_name,email:i.commit.committer_email,avatarUrl:null},message:i.commit.message,fileCount:null,additions:null,deletions:null}}})}}}async getPullRequestsForUser(s,e={}){let r="";s.repo?.id?r=`projectId:"${s.repo.id}"`:s.repo?.namespace&&s.repo?.name&&(r=`projectPath:"${s.repo.namespace}/${s.repo.name}"`);let n=os[s.association],o=await y(this.config,{query:`
916
+ `,variables:{after:s.cursor}},e);if(!t.body.data?.projects)throw new Error(we(t.body.errors)||t.statusText||"Unknown error");let n=t.body.data?.projects?.nodes||[];return{pageInfo:t.body.data?.projects?.pageInfo,data:n.map(ot)}}async getRefs(s,e,t={}){let n=j(e.repo),o=new URL(`${Pe(this.config,t)}/projects/${encodeURIComponent(n)}/repository/${s}`);o.searchParams.set("page",e.page?.toString()||"1"),o.searchParams.set("per_page",S.toString());let a=await this.config.request({url:o.toString(),headers:h(t.token||this.config.token)}),i=a.headers["x-next-page"];return{pageInfo:{hasNextPage:!!i,nextPage:i?parseInt(i,10):null},data:a.body.map(u=>({name:u.name,commit:{oid:u.commit.id,authoredDate:new Date(u.commit.authored_date),committedDate:new Date(u.commit.committed_date)}}))}}async getBranches(s,e={}){return this.getRefs("branches",s,e)}async getTags(s,e={}){return this.getRefs("tags",s,e)}async getBlame(s,e={}){let t=j(s.repo),n=new URL(`${Pe(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:h(e.token||this.config.token)}),a=0;return{data:{ranges:o.body.map(i=>{let u=a+1;return a+=i.lines.length,{startingLine:u,endingLine:a,commit:{oid:i.commit.id,parentOids:i.commit.parent_ids,authoredDate:new Date(i.commit.authored_date),author:{name:i.commit.author_name,email:i.commit.author_email,avatarUrl:null},committedDate:new Date(i.commit.committed_date),committer:{name:i.commit.committer_name,email:i.commit.committer_email,avatarUrl:null},message:i.commit.message,fileCount:null,additions:null,deletions:null}}})}}}async getPullRequestsForUser(s,e={}){let t="";s.repo?.id?t=`projectId:"${s.repo.id}"`:s.repo?.namespace&&s.repo?.name&&(t=`projectPath:"${s.repo.namespace}/${s.repo.name}"`);let n=os[s.association],o=await y(this.config,{query:`
878
917
  query getPullRequestsForUser($username: String! $cursor: String $labelNames: [String!]) {
879
918
  user(username: $username) {
880
- ${n}(state:opened first:100 after:$cursor labels: $labelNames${r?` ${r}`:""}) {
919
+ ${n}(state:opened first:100 after:$cursor labels: $labelNames${t?` ${t}`:""}) {
881
920
  pageInfo {
882
921
  endCursor
883
922
  hasNextPage
@@ -888,7 +927,7 @@ query getPullRequestsForUser($username: String! $cursor: String $labelNames: [St
888
927
  }
889
928
  }
890
929
  }
891
- `,variables:{username:s.username,cursor:s.cursor,labelNames:s.labelNames}},e);if(!o.body.data)throw new Error(we(o.body.errors)||o.statusText||"Unknown error");if(!o.body.data.user)throw new Error("User not found");let a=o.body.data.user[n];if(!a)throw new Error("Unexpected response");return{pageInfo:a.pageInfo,data:a.nodes?.filter(i=>s.includeFromArchivedRepos||!i.project.archived).map(i=>jt(i,Ft(i.project),Ft(i.sourceProject),this.getIsSelfHosted(e),this.config.baseUrl??e.baseUrl))||[]}}async getPullRequestsAssociatedWithUser(s,e={}){let[r,n,o]=s.cursor?.split(";")||[void 0,void 0,void 0],a=r?.split("-")||[],i=n?.split("-")||[],u=o?.split("-")||[],l=[],p=[],d=[],c=0;do{let v=s.repos&&s.repos[c];a[c]==="null"?l.push(null):l.push(this.getPullRequestsForUser({username:s.username,association:"authored",cursor:a[c],includeFromArchivedRepos:s.includeFromArchivedRepos,labelNames:s.labelNames,...v&&{repo:v}},e)),i[c]==="null"?p.push(null):p.push(this.getPullRequestsForUser({username:s.username,association:"assigned",cursor:i[c],includeFromArchivedRepos:s.includeFromArchivedRepos,labelNames:s.labelNames,...v&&{repo:v}},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,...v&&{repo:v}},e)),c++}while(c<(s.repos?.length||0));let g=[l,p,d].flat(),m=await Promise.all(g),b={},R=[],$=v=>{b[v.id]||(b[v.id]=!0,R.push(v))},se=!1,dr=m.map((v,yt)=>{let ne="";return v&&v.data.forEach($),v?.pageInfo.hasNextPage?(se=!0,ne+=`${v.pageInfo.endCursor||"null"}`):ne+="null",s.repos?.length&&(yt+1)%s.repos.length!==0?ne+="-":yt+1<m.length&&(ne+=";"),ne}).join("");return{pageInfo:{hasNextPage:se,endCursor:dr},data:R}}getVariablesForPullRequests(s){let{updatedBefore:e,isDraft:r,authorLogin:n,assigneeLogins:o,labelNames:a,reviewRequestedLogin:i}=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"),a&&d("labelName",a,"[String]"),r!=null&&d("draft",r,"Boolean"),i&&d("reviewerUsername",i,"String"),{variables:u,variableTypes:l,mergeRequestArguments:p}}async getPullRequestsForRepoBase(s,e={},r){let{cursor:n,repo:o}=s||{},a=j(o),{variables:i,variableTypes:u,mergeRequestArguments:l}=this.getVariablesForPullRequests(s),p={fullPath:a,...i},d=await y(this.config,{query:`
930
+ `,variables:{username:s.username,cursor:s.cursor,labelNames:s.labelNames}},e);if(!o.body.data)throw new Error(we(o.body.errors)||o.statusText||"Unknown error");if(!o.body.data.user)throw new Error("User not found");let a=o.body.data.user[n];if(!a)throw new Error("Unexpected response");return{pageInfo:a.pageInfo,data:a.nodes?.filter(i=>s.includeFromArchivedRepos||!i.project.archived).map(i=>jt(i,Ft(i.project),Ft(i.sourceProject),this.getIsSelfHosted(e),this.config.baseUrl??e.baseUrl))||[]}}async getPullRequestsAssociatedWithUser(s,e={}){let[t,n,o]=s.cursor?.split(";")||[void 0,void 0,void 0],a=t?.split("-")||[],i=n?.split("-")||[],u=o?.split("-")||[],l=[],p=[],d=[],c=0;do{let v=s.repos&&s.repos[c];a[c]==="null"?l.push(null):l.push(this.getPullRequestsForUser({username:s.username,association:"authored",cursor:a[c],includeFromArchivedRepos:s.includeFromArchivedRepos,labelNames:s.labelNames,...v&&{repo:v}},e)),i[c]==="null"?p.push(null):p.push(this.getPullRequestsForUser({username:s.username,association:"assigned",cursor:i[c],includeFromArchivedRepos:s.includeFromArchivedRepos,labelNames:s.labelNames,...v&&{repo:v}},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,...v&&{repo:v}},e)),c++}while(c<(s.repos?.length||0));let g=[l,p,d].flat(),m=await Promise.all(g),b={},I=[],$=v=>{b[v.id]||(b[v.id]=!0,I.push(v))},se=!1,dr=m.map((v,yt)=>{let ne="";return v&&v.data.forEach($),v?.pageInfo.hasNextPage?(se=!0,ne+=`${v.pageInfo.endCursor||"null"}`):ne+="null",s.repos?.length&&(yt+1)%s.repos.length!==0?ne+="-":yt+1<m.length&&(ne+=";"),ne}).join("");return{pageInfo:{hasNextPage:se,endCursor:dr},data:I}}getVariablesForPullRequests(s){let{updatedBefore:e,isDraft:t,authorLogin:n,assigneeLogins:o,labelNames:a,reviewRequestedLogin:i}=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"),a&&d("labelName",a,"[String]"),t!=null&&d("draft",t,"Boolean"),i&&d("reviewerUsername",i,"String"),{variables:u,variableTypes:l,mergeRequestArguments:p}}async getPullRequestsForRepoBase(s,e={},t){let{cursor:n,repo:o}=s||{},a=j(o),{variables:i,variableTypes:u,mergeRequestArguments:l}=this.getVariablesForPullRequests(s),p={fullPath:a,...i},d=await y(this.config,{query:`
892
931
  query getPullRequestsForRepo(
893
932
  $fullPath: ID!
894
933
  $after: String
@@ -918,14 +957,14 @@ query getPullRequestsForRepo(
918
957
  }
919
958
  }
920
959
  }
921
- `,variables:{...p,after:n}},e),c=[],g=d.body.data?.project;if(!r&&g?.archived)return{pageInfo:null,data:[]};let m=Se(g||{id:"",fullPath:"",webUrl:""});return(g?.mergeRequests?.nodes||[]).forEach(R=>{c.push(jt(R,m,null,this.getIsSelfHosted(e),this.config.baseUrl??e.baseUrl))}),{pageInfo:g?.mergeRequests?.pageInfo,data:c}}async getPullRequestsForRepo(s,e={}){return this.getPullRequestsForRepoBase(s,e,!1)}async getPullRequestsForRepos(s,e={}){let{repos:r,assigneeLogins:n,updatedBefore:o,authorLogin:a,labelNames:i,isDraft:u,reviewRequestedLogin:l}=s;return{data:(await Promise.all(r.map(d=>this.getPullRequestsForRepoBase({repo:d,assigneeLogins:n,updatedBefore:o,authorLogin:a,labelNames:i,isDraft:u,reviewRequestedLogin:l},e,s.includeFromArchivedRepos??!1)))).flatMap(d=>d.data)}}async closePullRequest(s,e={}){let{pullRequest:r}=s,n=`mutation ClosePullRequest($fullPath: ID!, $pullRequestId: String!) {
960
+ `,variables:{...p,after:n}},e),c=[],g=d.body.data?.project;if(!t&&g?.archived)return{pageInfo:null,data:[]};let m=Se(g||{id:"",fullPath:"",webUrl:""});return(g?.mergeRequests?.nodes||[]).forEach(I=>{c.push(jt(I,m,null,this.getIsSelfHosted(e),this.config.baseUrl??e.baseUrl))}),{pageInfo:g?.mergeRequests?.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:a,labelNames:i,isDraft:u,reviewRequestedLogin:l}=s;return{data:(await Promise.all(t.map(d=>this.getPullRequestsForRepoBase({repo:d,assigneeLogins:n,updatedBefore:o,authorLogin:a,labelNames:i,isDraft:u,reviewRequestedLogin:l},e,s.includeFromArchivedRepos??!1)))).flatMap(d=>d.data)}}async closePullRequest(s,e={}){let{pullRequest:t}=s,n=`mutation ClosePullRequest($fullPath: ID!, $pullRequestId: String!) {
922
961
  mergeRequestUpdate(input: { projectPath: $fullPath, iid: $pullRequestId, state: CLOSED }) {
923
962
  errors,
924
963
  mergeRequest {
925
964
  id
926
965
  }
927
966
  }
928
- }`,a=(await y(this.config,{query:n,variables:{fullPath:`${r.repository.owner.login}/${r.repository.name}`,pullRequestId:r.number.toString()}},e)).body.data?.mergeRequestUpdate;if(!a?.mergeRequest?.id||a?.errors?.length!==0)throw new Error("Could not close pull request")}async mergePullRequest(s,e={}){let{pullRequest:r,mergeStrategy:n}=s;if(!r.headRef?.oid)throw new Error('GitLab requires "headRef.oid" for this function.');let o=`mutation MergePullRequest(
967
+ }`,a=(await y(this.config,{query:n,variables:{fullPath:`${t.repository.owner.login}/${t.repository.name}`,pullRequestId:t.number.toString()}},e)).body.data?.mergeRequestUpdate;if(!a?.mergeRequest?.id||a?.errors?.length!==0)throw new Error("Could not close pull request")}async mergePullRequest(s,e={}){let{pullRequest:t,mergeStrategy:n}=s;if(!t.headRef?.oid)throw new Error('GitLab requires "headRef.oid" for this function.');let o=`mutation MergePullRequest(
929
968
  $fullPath: ID!,
930
969
  $pullRequestId: String!,
931
970
  $expectedSourceSha: String!,
@@ -942,48 +981,48 @@ query getPullRequestsForRepo(
942
981
  id
943
982
  }
944
983
  }
945
- }`,i=(await y(this.config,{query:o,variables:{fullPath:`${r.repository.owner.login}/${r.repository.name}`,pullRequestId:r.number.toString(),expectedSourceSha:r.headRef.oid,squash:n==="SQUASH"}},e)).body.data?.mergeRequestAccept;if(!i?.mergeRequest?.id||i?.errors?.length!==0)throw new Error("Could not merge pull request")}async setPullRequestMilestone(s,e={}){let{pullRequest:r,milestone:n}=s;if(!r.graphQLId)throw new Error('GitHub requires "graphQLId" for this function.');let o=`mutation SetPullRequestMilestone($fullPath: ID!, $pullRequestId: String!, $milestoneGraphQLId: MilestoneID) {
984
+ }`,i=(await y(this.config,{query:o,variables:{fullPath:`${t.repository.owner.login}/${t.repository.name}`,pullRequestId:t.number.toString(),expectedSourceSha:t.headRef.oid,squash:n==="SQUASH"}},e)).body.data?.mergeRequestAccept;if(!i?.mergeRequest?.id||i?.errors?.length!==0)throw new Error("Could not merge pull request")}async setPullRequestMilestone(s,e={}){let{pullRequest:t,milestone:n}=s;if(!t.graphQLId)throw new Error('GitHub requires "graphQLId" for this function.');let o=`mutation SetPullRequestMilestone($fullPath: ID!, $pullRequestId: String!, $milestoneGraphQLId: MilestoneID) {
946
985
  mergeRequestSetMilestone(input: { projectPath: $fullPath, iid: $pullRequestId, milestoneId: $milestoneGraphQLId }) {
947
986
  errors,
948
987
  mergeRequest {
949
988
  id
950
989
  }
951
990
  }
952
- }`,a=await y(this.config,{query:o,variables:{fullPath:`${r.repository.owner.login}/${r.repository.name}`,pullRequestId:r.number.toString(),milestoneGraphQLId:n?.graphQLId}},e),i=a.body.data?.mergeRequestSetMilestone;if(!i?.mergeRequest?.id||a.body.errors||i?.errors?.length!==0)throw new Error("Could not set milestone of pull request")}async setPullRequestAsDraft(s,e={}){let{pullRequest:r,isDraft:n}=s,o=`mutation MergeRequestSetDraft($fullPath: ID!, $pullRequestId: String!, $isDraft: Boolean!) {
991
+ }`,a=await y(this.config,{query:o,variables:{fullPath:`${t.repository.owner.login}/${t.repository.name}`,pullRequestId:t.number.toString(),milestoneGraphQLId:n?.graphQLId}},e),i=a.body.data?.mergeRequestSetMilestone;if(!i?.mergeRequest?.id||a.body.errors||i?.errors?.length!==0)throw new Error("Could not set milestone of pull request")}async setPullRequestAsDraft(s,e={}){let{pullRequest:t,isDraft:n}=s,o=`mutation MergeRequestSetDraft($fullPath: ID!, $pullRequestId: String!, $isDraft: Boolean!) {
953
992
  mergeRequestSetDraft(input: { projectPath: $fullPath, iid: $pullRequestId, draft: $isDraft }) {
954
993
  errors,
955
994
  mergeRequest {
956
995
  id
957
996
  }
958
997
  }
959
- }`,i=(await y(this.config,{query:o,variables:{fullPath:`${r.repository.owner.login}/${r.repository.name}`,pullRequestId:r.number.toString(),isDraft:n}},e)).body.data?.mergeRequestSetDraft;if(!i?.mergeRequest?.id||i?.errors?.length!==0)throw new Error("Could not set pull request as draft")}async setPullRequestReviewers(s,e={}){let{pullRequest:r,reviewers:n}=s,o=n.map(l=>{if(!l.username)throw new Error('GitLab requires reviewer "username" for this function.');return l.username}),a=`mutation MergeRequestSetReviewers($fullPath: ID!, $pullRequestId: String!, $reviewerUsernames: [String!]!) {
998
+ }`,i=(await y(this.config,{query:o,variables:{fullPath:`${t.repository.owner.login}/${t.repository.name}`,pullRequestId:t.number.toString(),isDraft:n}},e)).body.data?.mergeRequestSetDraft;if(!i?.mergeRequest?.id||i?.errors?.length!==0)throw new Error("Could not set pull request as draft")}async setPullRequestReviewers(s,e={}){let{pullRequest:t,reviewers:n}=s,o=n.map(l=>{if(!l.username)throw new Error('GitLab requires reviewer "username" for this function.');return l.username}),a=`mutation MergeRequestSetReviewers($fullPath: ID!, $pullRequestId: String!, $reviewerUsernames: [String!]!) {
960
999
  mergeRequestSetReviewers(input: { projectPath: $fullPath, iid: $pullRequestId, reviewerUsernames: $reviewerUsernames }) {
961
1000
  errors,
962
1001
  mergeRequest {
963
1002
  id
964
1003
  }
965
1004
  }
966
- }`,u=(await y(this.config,{query:a,variables:{fullPath:`${r.repository.owner.login}/${r.repository.name}`,pullRequestId:r.number.toString(),reviewerUsernames:o}},e)).body.data?.mergeRequestSetReviewers;if(!u?.mergeRequest?.id||u?.errors?.length!==0)throw new Error("Could not set pull request reviewers")}async reRequestPullRequestReview(s,e={}){let{pullRequest:r,reviewer:n}=s;if(!n.graphQLId)throw new Error('GitLab requires reviwer "graphQLId" for this function.');let o=`mutation MergeRequestReviewerRereview($fullPath: ID!, $pullRequestId: String!, $reviewerUserId: UserID!) {
1005
+ }`,u=(await y(this.config,{query:a,variables:{fullPath:`${t.repository.owner.login}/${t.repository.name}`,pullRequestId:t.number.toString(),reviewerUsernames:o}},e)).body.data?.mergeRequestSetReviewers;if(!u?.mergeRequest?.id||u?.errors?.length!==0)throw new Error("Could not set pull request reviewers")}async reRequestPullRequestReview(s,e={}){let{pullRequest:t,reviewer:n}=s;if(!n.graphQLId)throw new Error('GitLab requires reviwer "graphQLId" for this function.');let o=`mutation MergeRequestReviewerRereview($fullPath: ID!, $pullRequestId: String!, $reviewerUserId: UserID!) {
967
1006
  mergeRequestReviewerRereview(input: { projectPath: $fullPath, iid: $pullRequestId, userId: $reviewerUserId }) {
968
1007
  errors,
969
1008
  mergeRequest {
970
1009
  id
971
1010
  }
972
1011
  }
973
- }`,i=(await y(this.config,{query:o,variables:{fullPath:`${r.repository.owner.login}/${r.repository.name}`,pullRequestId:r.number.toString(),reviewerUserId:n.graphQLId}},e)).body.data?.mergeRequestReviewerRereview;if(!i?.mergeRequest?.id||i?.errors?.length!==0)throw new Error("Could not set pull request reviewers")}async reRequestPullRequestReviews(s,e={}){let{pullRequest:r,reviewers:n}=s,o=r.reviews;if(!o)throw new Error('GitLab requires "reviews" for this function.');let a=n.filter(i=>o.find(u=>u.reviewer.graphQLId===i.graphQLId));await Promise.all(a.map(i=>this.reRequestPullRequestReview({pullRequest:r,reviewer:i},e)))}async setPullRequestAssignees(s,e={}){let{pullRequest:r,assignees:n}=s,o=n.map(l=>{if(!l.username)throw new Error('GitLab requires assignee "username" for this function.');return l.username}),a=`mutation MergeRequestSetAssignees($fullPath: ID!, $pullRequestId: String!, $assigneeUsernames: [String!]!) {
1012
+ }`,i=(await y(this.config,{query:o,variables:{fullPath:`${t.repository.owner.login}/${t.repository.name}`,pullRequestId:t.number.toString(),reviewerUserId:n.graphQLId}},e)).body.data?.mergeRequestReviewerRereview;if(!i?.mergeRequest?.id||i?.errors?.length!==0)throw new Error("Could not set pull request reviewers")}async reRequestPullRequestReviews(s,e={}){let{pullRequest:t,reviewers:n}=s,o=t.reviews;if(!o)throw new Error('GitLab requires "reviews" for this function.');let a=n.filter(i=>o.find(u=>u.reviewer.graphQLId===i.graphQLId));await Promise.all(a.map(i=>this.reRequestPullRequestReview({pullRequest:t,reviewer:i},e)))}async setPullRequestAssignees(s,e={}){let{pullRequest:t,assignees:n}=s,o=n.map(l=>{if(!l.username)throw new Error('GitLab requires assignee "username" for this function.');return l.username}),a=`mutation MergeRequestSetAssignees($fullPath: ID!, $pullRequestId: String!, $assigneeUsernames: [String!]!) {
974
1013
  mergeRequestSetAssignees(input: { projectPath: $fullPath, iid: $pullRequestId, assigneeUsernames: $assigneeUsernames }) {
975
1014
  errors,
976
1015
  mergeRequest {
977
1016
  id
978
1017
  }
979
1018
  }
980
- }`,u=(await y(this.config,{query:a,variables:{fullPath:`${r.repository.owner.login}/${r.repository.name}`,pullRequestId:r.number.toString(),assigneeUsernames:o}},e)).body.data?.mergeRequestSetAssignees;if(!u?.mergeRequest?.id||u?.errors?.length!==0)throw new Error("Could not set pull request assignees")}async setPullRequestLabels(s,e={}){let{pullRequest:r,labels:n}=s,o=n.map(u=>{if(!u.graphQLId)throw new Error('GitLab requires "graphQLId" for labels in this function.');return u.graphQLId}),a=`mutation SetPullRequestLabels($fullPath: ID!, $pullRequestId: String!, $labelGraphQLIds: [LabelID!]!) {
1019
+ }`,u=(await y(this.config,{query:a,variables:{fullPath:`${t.repository.owner.login}/${t.repository.name}`,pullRequestId:t.number.toString(),assigneeUsernames:o}},e)).body.data?.mergeRequestSetAssignees;if(!u?.mergeRequest?.id||u?.errors?.length!==0)throw new Error("Could not set pull request assignees")}async setPullRequestLabels(s,e={}){let{pullRequest:t,labels:n}=s,o=n.map(u=>{if(!u.graphQLId)throw new Error('GitLab requires "graphQLId" for labels in this function.');return u.graphQLId}),a=`mutation SetPullRequestLabels($fullPath: ID!, $pullRequestId: String!, $labelGraphQLIds: [LabelID!]!) {
981
1020
  mergeRequestSetLabels(input: { projectPath: $fullPath, iid: $pullRequestId, labelIds: $labelGraphQLIds }) {
982
1021
  mergeRequest {
983
1022
  id
984
1023
  }
985
1024
  }
986
- }`;if(!(await y(this.config,{query:a,variables:{fullPath:`${r.repository.owner.login}/${r.repository.name}`,pullRequestId:r.number.toString(),labelGraphQLIds:o}},e)).body.data?.mergeRequestSetLabels?.mergeRequest?.id)throw new Error("Could not set pull request labels")}async getIssue(s,e={}){let r=ms(s),n=await y(this.config,{query:`
1025
+ }`;if(!(await y(this.config,{query:a,variables:{fullPath:`${t.repository.owner.login}/${t.repository.name}`,pullRequestId:t.number.toString(),labelGraphQLIds:o}},e)).body.data?.mergeRequestSetLabels?.mergeRequest?.id)throw new Error("Could not set pull request labels")}async getIssue(s,e={}){let t=ms(s),n=await y(this.config,{query:`
987
1026
  query GetSingleIssue($projectId: ID!, $issueNumber: String!) {
988
1027
  project(fullPath: $projectId) {
989
1028
  id
@@ -994,7 +1033,7 @@ query GetSingleIssue($projectId: ID!, $issueNumber: String!) {
994
1033
  }
995
1034
  }
996
1035
  }
997
- `,variables:{issueNumber:s.number,projectId:r}},e);if(!n.body.data?.project)throw new Error(`Repository ${r} not found`);if(!n.body.data?.project?.issue)throw new Error(`Issue ${s.number} not found`);return{data:at(n.body.data.project.issue,Se(n.body.data.project),this.getIsSelfHosted(e),this.config.baseUrl??e.baseUrl)}}getVariablesForIssues(s){let{updatedBefore:e,authorLogin:r,assigneeLogins:n,labelNames:o}=s||{},a={},i=[],u=[],l=(p,d,c)=>{i.push(`$${p}: ${c}`),u.push(`${p}: $${p}`),a[p]=d};return e&&l("updatedBefore",e,"Time"),r&&l("authorUsername",r,"String"),n&&l("assigneeUsername",n[0],"String"),o&&l("labelName",o,"[String]"),{variables:a,variableTypes:i,issueArguments:u}}async getIssuesForRepo(s,e={}){let{cursor:r,repo:n}=s||{},o=j(n),{variables:a,variableTypes:i,issueArguments:u}=this.getVariablesForIssues(s),l={fullPath:o,...a},p=`
1036
+ `,variables:{issueNumber:s.number,projectId:t}},e);if(!n.body.data?.project)throw new Error(`Repository ${t} not found`);if(!n.body.data?.project?.issue)throw new Error(`Issue ${s.number} not found`);return{data:at(n.body.data.project.issue,Se(n.body.data.project),this.getIsSelfHosted(e),this.config.baseUrl??e.baseUrl)}}getVariablesForIssues(s){let{updatedBefore:e,authorLogin:t,assigneeLogins:n,labelNames:o}=s||{},a={},i=[],u=[],l=(p,d,c)=>{i.push(`$${p}: ${c}`),u.push(`${p}: $${p}`),a[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:a,variableTypes:i,issueArguments:u}}async getIssuesForRepo(s,e={}){let{cursor:t,repo:n}=s||{},o=j(n),{variables:a,variableTypes:i,issueArguments:u}=this.getVariablesForIssues(s),l={fullPath:o,...a},p=`
998
1037
  query GetIssuesFromProject(
999
1038
  $fullPath: ID!
1000
1039
  $after: String
@@ -1022,7 +1061,7 @@ query GetSingleIssue($projectId: ID!, $issueNumber: String!) {
1022
1061
  }
1023
1062
  }
1024
1063
  }
1025
- }`,d=await y(this.config,{query:p,variables:{...l,after:r}},e),c=[],g=d.body.data?.project,m=Se(g||{id:"",fullPath:"",webUrl:""});return(g?.issues?.nodes||[]).forEach(R=>{c.push(at(R,m,this.getIsSelfHosted(e),this.config.baseUrl??e.baseUrl))}),{pageInfo:g?.issues?.pageInfo??{endCursor:null,hasNextPage:!1},data:c.sort((R,$)=>(R.updatedDate||R.createdDate).getTime()-($.updatedDate||$.createdDate).getTime())}}async getIssuesForRepos(s,e={}){let{cursor:r}=s||{},n=s.repoIds.map(g=>g.toString().startsWith(Z)?g:`${Z}${g}`),{variables:o,variableTypes:a,mergeRequestArguments:i}=this.getVariablesForPullRequests(s),u={projectIds:n,...o},l=`
1064
+ }`,d=await y(this.config,{query:p,variables:{...l,after:t}},e),c=[],g=d.body.data?.project,m=Se(g||{id:"",fullPath:"",webUrl:""});return(g?.issues?.nodes||[]).forEach(I=>{c.push(at(I,m,this.getIsSelfHosted(e),this.config.baseUrl??e.baseUrl))}),{pageInfo:g?.issues?.pageInfo??{endCursor:null,hasNextPage:!1},data:c.sort((I,$)=>(I.updatedDate||I.createdDate).getTime()-($.updatedDate||$.createdDate).getTime())}}async getIssuesForRepos(s,e={}){let{cursor:t}=s||{},n=s.repoIds.map(g=>g.toString().startsWith(Z)?g:`${Z}${g}`),{variables:o,variableTypes:a,mergeRequestArguments:i}=this.getVariablesForPullRequests(s),u={projectIds:n,...o},l=`
1026
1065
  query GetIssuesFromProject(
1027
1066
  $projectIds: [ID!]
1028
1067
  $after: String
@@ -1053,19 +1092,19 @@ query GetSingleIssue($projectId: ID!, $issueNumber: String!) {
1053
1092
  }
1054
1093
  }
1055
1094
  }
1056
- }`,p=await y(this.config,{query:l,variables:{...u,after:r}},e),d=[];return(p.body.data?.projects?.nodes||[]).forEach(g=>{if(!s.includeFromArchivedRepos&&g.archived)return;let m=Se(g);(g.issues?.nodes||[]).forEach(R=>d.push(at(R,m,this.getIsSelfHosted(e),this.config.baseUrl??e.baseUrl)))}),{pageInfo:p.body?.data?.projects?.pageInfo??{endCursor:null,hasNextPage:!1},data:d.sort((g,m)=>(g.updatedDate||g.createdDate).getTime()-(m.updatedDate||m.createdDate).getTime())}}async setIssueState(s,e={}){let{issue:r,state:n}=s;if(!r.repository)throw new Error('GitLab requires "repository" for this function.');let o=`mutation SetIssueState($fullPath: ID!, $issueId: String!, $status: IssueStateEvent!) {
1095
+ }`,p=await y(this.config,{query:l,variables:{...u,after:t}},e),d=[];return(p.body.data?.projects?.nodes||[]).forEach(g=>{if(!s.includeFromArchivedRepos&&g.archived)return;let m=Se(g);(g.issues?.nodes||[]).forEach(I=>d.push(at(I,m,this.getIsSelfHosted(e),this.config.baseUrl??e.baseUrl)))}),{pageInfo:p.body?.data?.projects?.pageInfo??{endCursor:null,hasNextPage:!1},data:d.sort((g,m)=>(g.updatedDate||g.createdDate).getTime()-(m.updatedDate||m.createdDate).getTime())}}async setIssueState(s,e={}){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
1096
  updateIssue(input: { projectPath: $fullPath, iid: $issueId, stateEvent: $status }) {
1058
1097
  issue {
1059
1098
  id
1060
1099
  }
1061
1100
  }
1062
- }`;if(!(await y(this.config,{query:o,variables:{fullPath:`${r.repository.owner.login}/${r.repository.name}`,issueId:r.number,status:n==="OPEN"?"REOPEN":"CLOSE"}},e)).body.data?.updateIssue?.issue?.id)throw new Error("Could not set issue status")}async closeIssue(s,e={}){await this.setIssueState({...s,state:"CLOSED"},e)}async reOpenIssue(s,e={}){await this.setIssueState({...s,state:"OPEN"},e)}async setIssueLabels(s,e={}){let{issue:r,labels:n}=s;if(!r.repository)throw new Error('GitLab requires a "repository" for this function.');let o=n.map(u=>{if(!u.graphQLId)throw new Error('GitLab requires label "graphQLId" for this function.');return u.graphQLId}),a=`mutation SetIssueLabels($fullPath: ID!, $issueId: String!, $labelGraphQLIds: [ID!]) {
1101
+ }`;if(!(await y(this.config,{query:o,variables:{fullPath:`${t.repository.owner.login}/${t.repository.name}`,issueId:t.number,status:n==="OPEN"?"REOPEN":"CLOSE"}},e)).body.data?.updateIssue?.issue?.id)throw new Error("Could not set issue status")}async closeIssue(s,e={}){await this.setIssueState({...s,state:"CLOSED"},e)}async reOpenIssue(s,e={}){await this.setIssueState({...s,state:"OPEN"},e)}async setIssueLabels(s,e={}){let{issue:t,labels:n}=s;if(!t.repository)throw new Error('GitLab requires a "repository" for this function.');let o=n.map(u=>{if(!u.graphQLId)throw new Error('GitLab requires label "graphQLId" for this function.');return u.graphQLId}),a=`mutation SetIssueLabels($fullPath: ID!, $issueId: String!, $labelGraphQLIds: [ID!]) {
1063
1102
  updateIssue(input: { projectPath: $fullPath, iid: $issueId, labelIds: $labelGraphQLIds }) {
1064
1103
  issue {
1065
1104
  id
1066
1105
  }
1067
1106
  }
1068
- }`;if(!(await y(this.config,{query:a,variables:{fullPath:`${r.repository.owner.login}/${r.repository.name}`,issueId:r.number,labelGraphQLIds:o}},e)).body.data?.updateIssue?.issue?.id)throw new Error("Could not set issue labels")}async setIssueMilestone(s,e={}){let{issue:r,milestone:n}=s;if(!r.repository)throw new Error('GitLab requires "repository" for this function.');let o=`mutation SetIssueMilestone($fullPath: ID!, $issueId: String!, $milestoneId: ID) {
1107
+ }`;if(!(await y(this.config,{query:a,variables:{fullPath:`${t.repository.owner.login}/${t.repository.name}`,issueId:t.number,labelGraphQLIds:o}},e)).body.data?.updateIssue?.issue?.id)throw new Error("Could not set issue labels")}async setIssueMilestone(s,e={}){let{issue:t,milestone:n}=s;if(!t.repository)throw new Error('GitLab requires "repository" for this function.');let o=`mutation SetIssueMilestone($fullPath: ID!, $issueId: String!, $milestoneId: ID) {
1069
1108
  updateIssue(input: { projectPath: $fullPath, iid: $issueId, milestoneId: $milestoneId }) {
1070
1109
  errors
1071
1110
  issue {
@@ -1075,14 +1114,14 @@ query GetSingleIssue($projectId: ID!, $issueNumber: String!) {
1075
1114
  }
1076
1115
  }
1077
1116
  }
1078
- }`,a=await y(this.config,{query:o,variables:{fullPath:`${r.repository.owner.login}/${r.repository.name}`,issueId:r.number,milestoneId:n?.id??null}},e),i=a.body.data?.updateIssue;if(!i?.issue?.id||a.body.errors||i?.errors?.length!==0)throw new Error("Could not set milestone of issue")}async setIssueAssignees(s,e={}){let{issue:r,assignees:n}=s;if(!r.repository)throw new Error('GitLab requires "repository" for this function.');let o=n.map(l=>l.username),a=`mutation SetIssueAssignees($fullPath: ID!, $issueId: String!, $assigneeUsernames: [String!]!) {
1117
+ }`,a=await y(this.config,{query:o,variables:{fullPath:`${t.repository.owner.login}/${t.repository.name}`,issueId:t.number,milestoneId:n?.id??null}},e),i=a.body.data?.updateIssue;if(!i?.issue?.id||a.body.errors||i?.errors?.length!==0)throw new Error("Could not set milestone of issue")}async setIssueAssignees(s,e={}){let{issue:t,assignees:n}=s;if(!t.repository)throw new Error('GitLab requires "repository" for this function.');let o=n.map(l=>l.username),a=`mutation SetIssueAssignees($fullPath: ID!, $issueId: String!, $assigneeUsernames: [String!]!) {
1079
1118
  issueSetAssignees(input: { projectPath: $fullPath, iid: $issueId, assigneeUsernames: $assigneeUsernames }) {
1080
1119
  errors,
1081
1120
  issue {
1082
1121
  id
1083
1122
  }
1084
1123
  }
1085
- }`,u=(await y(this.config,{query:a,variables:{fullPath:`${r.repository.owner.login}/${r.repository.name}`,issueId:r.number,assigneeUsernames:o}},e)).body.data?.issueSetAssignees;if(!u?.issue?.id||u?.errors?.length!==0)throw new Error("Could not set issue assignees")}async getMilestonesForRepo(s,e={}){let{repo:{namespace:r,name:n},cursor:o}=s,a=await y(this.config,{query:`
1124
+ }`,u=(await y(this.config,{query:a,variables:{fullPath:`${t.repository.owner.login}/${t.repository.name}`,issueId:t.number,assigneeUsernames:o}},e)).body.data?.issueSetAssignees;if(!u?.issue?.id||u?.errors?.length!==0)throw new Error("Could not set issue assignees")}async getMilestonesForRepo(s,e={}){let{repo:{namespace:t,name:n},cursor:o}=s,a=await y(this.config,{query:`
1086
1125
  query getLabelsForRepo(
1087
1126
  $fullPath: ID!
1088
1127
  $after: String
@@ -1102,7 +1141,7 @@ query getLabelsForRepo(
1102
1141
  }
1103
1142
  }
1104
1143
  }
1105
- `,variables:{fullPath:`${r}/${n}`,after:o}},e);return{pageInfo:a.body.data?.project?.milestones?.pageInfo??{endCursor:null,hasNextPage:!1},data:a.body.data?.project?.milestones?.nodes?.map(i=>ct(i,a.body.data?.project?.webUrl||""))??[]}}async getLabelsForRepo(s,e={}){let{repo:{namespace:r,name:n},cursor:o}=s,a=await y(this.config,{query:`
1144
+ `,variables:{fullPath:`${t}/${n}`,after:o}},e);return{pageInfo:a.body.data?.project?.milestones?.pageInfo??{endCursor:null,hasNextPage:!1},data:a.body.data?.project?.milestones?.nodes?.map(i=>ct(i,a.body.data?.project?.webUrl||""))??[]}}async getLabelsForRepo(s,e={}){let{repo:{namespace:t,name:n},cursor:o}=s,a=await y(this.config,{query:`
1106
1145
  query getLabelsForRepo(
1107
1146
  $fullPath: ID!
1108
1147
  $after: String
@@ -1121,8 +1160,8 @@ query getLabelsForRepo(
1121
1160
  }
1122
1161
  }
1123
1162
  }
1124
- `,variables:{fullPath:`${r}/${n}`,after:o}},e);return{pageInfo:a.body.data?.project?.labels?.pageInfo??{endCursor:null,hasNextPage:!1},data:a.body.data?.project?.labels?.nodes?.map(dt)??[]}}async getTreeForRepo(s,e={}){let r=j(s.repo),n=new URL(s.cursor??`${Pe(this.config,e)}/projects/${encodeURIComponent(r)}/repository/tree`);n.searchParams.set("per_page","10000"),n.searchParams.set("recursive","true"),n.searchParams.set("pagination","keyset"),n.searchParams.set("ref",s.branch);let o=await this.config.request({url:n.toString(),headers:h(e.token||this.config.token)}),a=o.headers.link;return{data:o.body.map(fs),pageInfo:{endCursor:a?a.substring(1,a.indexOf(">")):null,hasNextPage:!!a}}}};var ys="https://api.atlassian.com/ex/jira",ve=100,gt=["assignee","comment","summary","created","creator","updated","votes","issuetype","status","labels","components","project","fixVersions","description"],zt="/rest/api/2/search/jql",Mt="/rest/api/2/search",mt=(t,s,e,r)=>{let n=t.fields.assignee,o=!r,a=(t.fields[s?.Sprint??""]??[]).filter(i=>typeof i=="object");return{id:t.id,commentCount:t.fields.comment.comments.length,number:t.key,title:t.fields.summary,url:e?`${e}/browse/${t.key}`:null,closedDate:null,createdDate:new Date(t.fields.created),author:Ee(t.fields.creator,e,o),updatedDate:new Date(t.fields.updated),assignees:n?[Ee(n,e,o)]:[],description:t.fields.description,repository:null,project:{name:t.fields.project.name,resourceId:r??null,key:t.fields.project.key,namespace:null,id:t.fields.project.id},state:vs(t.fields.status),statusTransitions:t.transitions?.map(Ps)??[],components:t.fields.components?.map(ws)??[],type:t.fields.issuetype.name,upvoteCount:t.fields.votes?.votes||0,labels:t.fields.labels?.map(i=>({color:null,description:null,id:null,name:i}))??[],sprints:a.map(Es),fixVersions:t.fields.fixVersions.map(qs)}},Ps=t=>{let s;switch(t.to.statusCategory.name){case"To Do":s="TO_DO";break;case"In Progress":s="IN_PROGRESS";break;default:s="DONE";break}return{name:t.name,id:t.id,to:{id:t.to.id,name:t.to.name,color:t.to.statusCategory.colorName,category:s}}},ws=t=>({description:t.description??null,id:t.id,name:t.name}),Ss=(t,s,e)=>e&&t.name?`${s}/secure/ViewProfile.jspa?name=${encodeURIComponent(t.name)}`:`${s}/jira/people/${t.accountId}`,Ee=(t,s,e)=>({id:(e?t.key:t.accountId)??"",name:t.displayName,email:t.emailAddress,avatarUrl:t.avatarUrls["48x48"],username:t.displayName,url:Ss(t,s,e)}),vs=t=>{let s;switch(t.statusCategory.name){case"To Do":s="TO_DO";break;case"In Progress":s="IN_PROGRESS";break;default:s="DONE";break}return{id:t.id,name:t.name,color:t.statusCategory.colorName,category:s}},Es=t=>({id:t.id.toString(),name:t.name,isActive:t.state==="active",startDate:t.startDate?new Date(t.startDate):null,endDate:t.endDate?new Date(t.endDate):null,completedDate:t.completeDate?new Date(t.completeDate):null}),qs=t=>({id:t.id,description:t.description,name:t.name,archived:t.archived,released:t.released,releaseDate:t.releaseDate?new Date(t.releaseDate):null}),B=(t,s,e)=>e?`${s.baseUrl||ys}/${e}`:`${s?.baseUrl||t.baseUrl}`,qe=async(t,s,e={})=>{let{resourceId:r}=s;return(await t.request({url:`${B(t,e,r)}/rest/api/2/field`,headers:h(e.token||t.token)})).body},Ce=async(t,s,e,r={})=>{let{number:n,resourceId:o,fields:a}=s||{},i=await t.request({url:`${B(t,r,o)}/rest/api/2/issue/${n}?fields=${gt.join(",")}&expand=transitions`,headers:h(r.token||t.token)});return{data:mt(i.body,a,e,o)}},Le=async(t,s,e,r={})=>{let{cursor:n,resourceId:o,labelNames:a,fields:i}=s||{},u=["statusCategory != Done",`(creator = currentUser() OR assignee = currentUser()
1125
- OR comment ~ currentUser() OR summary ~ currentUser() OR description ~ currentUser())`];a&&a.forEach($=>u.push(`labels = "${$}"`));let l=`${u.join(" AND ")} ORDER BY updated DESC`,p=!o,d=p?Mt:zt,c=new URL(`${B(t,r,o)}${d}`);c.searchParams.set("jql",l),c.searchParams.set("maxResults",ve.toString()),c.searchParams.set("fields",gt.join(",")),c.searchParams.set("expand","transitions"),n&&(p?c.searchParams.set("startAt",n):c.searchParams.set("nextPageToken",n));let g=await t.request({url:c.toString(),headers:h(r.token||t.token)}),m=g.body.issues.map($=>mt($,i,e,o)),b=!1,R="";return p?(b=m.length==ve,R=(parseInt(n??"0",10)+m.length).toString()):(b=!!g.body.nextPageToken,R=g.body.nextPageToken??null),{data:m,pageInfo:{hasNextPage:b,endCursor:R}}},Wt=async(t,s,e,r={})=>{let{cursor:n,resourceId:o,jql:a,fields:i}=s||{},u=[...gt],l=i?.Sprint;l&&u.push(l);let p=!o,d=p?Mt:zt,c=new URL(`${B(t,r,o)}${d}`);c.searchParams.set("jql",a.join(" AND ")),c.searchParams.set("maxResults",ve.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 t.request({url:c.toString(),headers:h(r.token||t.token)}),m=g.body.issues.map($=>mt($,i,e,o)),b=!1,R="";return p?(b=m.length==ve,R=(parseInt(n??"0",10)+m.length).toString()):(b=!!g.body.nextPageToken,R=g.body.nextPageToken??null),{data:m,pageInfo:{hasNextPage:b,endCursor:R}}},De=async(t,s,e,r={})=>{let{assigneeLogins:n,authorLogin:o,mentionLogin:a,labelNames:i,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('", "')}")`),a&&c.push(`comment ~ "${a}"`),i&&i.forEach(g=>c.push(`labels = "${g}"`)),Wt(t,{resourceId:p,jql:c,cursor:u,fields:d},e,r)},$e=async(t,s,e,r={})=>{let{assigneeLogins:n,authorLogin:o,mentionLogin:a,labelNames:i,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('", "')}")`),a&&g.push(`comment ~ "${a}"`),i&&i.forEach(m=>g.push(`labels = "${m}"`)),Wt(t,{resourceId:p,jql:g,fields:d,cursor:u},e,r)},Ue=async(t,s,e={})=>{let{issue:r,labels:n}=s;if(!r.project)throw new Error('Jira requires a "project" for this function.');let o={fields:{labels:n.map(a=>a.name)}};await t.request({method:"PUT",url:`${B(t,e,r.project.resourceId??void 0)}/rest/api/2/issue/${r.id}`,body:JSON.stringify(o),headers:{...h(e.token||t.token),"Content-Type":"application/json"}})},Ae=async(t,s,e={})=>{let{issue:r,components:n}=s;if(!r.project)throw new Error('Jira requires a "project" for this function.');let o={fields:{components:n.map(a=>({id:a.id}))}};await t.request({method:"PUT",url:`${B(t,e,r.project.resourceId??void 0)}/rest/api/2/issue/${r.id}`,body:JSON.stringify(o),headers:{...h(e.token||t.token),"Content-Type":"application/json"}})},Ge=async(t,s,e={})=>{let{issue:r,status:n}=s;if(!r.project)throw new Error('Jira requires a "project" for this function.');if(!n.id)throw new Error('Jira requires a status "id" for this function.');let o={transition:{id:n.id}};await t.request({method:"POST",url:`${B(t,e,r.project.resourceId??void 0)}/rest/api/2/issue/${r.id}/transitions`,body:JSON.stringify(o),headers:{...h(e.token||t.token),"Content-Type":"application/json"}})},Te=async(t,s,e={})=>{let{resourceId:r,projectIdOrKey:n}=s,o=new URL(`${B(t,e,r)}/rest/api/2/project/${n}/components`);return{data:(await t.request({url:o.toString(),headers:h(e.token||t.token)})).body}};var ae="https://api.atlassian.com/ex/jira",ht=100,ee=class extends U{constructor(){super(...arguments);this._resourceUrlCache={};this._issueFieldsCache={}}async getIssueFieldsForResource(e,r={}){if(!this._issueFieldsCache[e.resourceId]){let n=await qe(this.config,e,r);this._issueFieldsCache[e.resourceId]=n.reduce((o,a)=>({...o,[a.name]:a.id}),{})}return this._issueFieldsCache[e.resourceId]??null}async getResourceUrl(e,r={}){let n=r.token||this.config.token;if(!n)return null;let o=this._resourceUrlCache[n];return o?o[e.resourceId]??null:(await this.getJiraResourcesForCurrentUser(r),this._resourceUrlCache[n]?.[e.resourceId]??null)}async getCurrentUserForResource(e,r={}){let n=await this.getResourceUrl({resourceId:e.resourceId},r),o=await this.config.request({url:`${r.baseUrl||ae}/${e.resourceId}/rest/api/2/myself`,headers:h(r.token||this.config.token)});return{data:{name:o.body.displayName,email:o.body.emailAddress,avatarUrl:o.body.avatarUrls["48x48"],id:o.body.accountId,username:o.body.displayName,url:n?`${n}/jira/people/${o.body.accountId}`:null}}}async getJiraResourcesForCurrentUser(e={}){let r=await this.config.request({url:`${e.baseUrl||"https://api.atlassian.com/"}/oauth/token/accessible-resources`,headers:h(e.token||this.config.token)}),n=e.token||this.config.token,o=n?this._resourceUrlCache[n]||{}:void 0,a=r.body.map(i=>(o&&(o[i.id]=i.url),{avatarUrl:i.avatarUrl,id:i.id,name:i.name,url:i.url}));return n&&(this._resourceUrlCache[n]=o),{data:a}}async getJiraProjectsForResource(e,r={}){let n=new URL(`${r.baseUrl||ae}/${e.resourceId}/rest/api/2/project/search`);n.searchParams.set("maxResults",ht.toString()),e.cursor&&n.searchParams.set("startAt",e.cursor);let o=await this.config.request({url:n.toString(),headers:h(r.token||this.config.token)});return{pageInfo:{hasNextPage:o.body.values.length!==0,endCursor:(o.body.startAt+o.body.values.length).toString()},data:o.body.values.map(a=>({id:a.id,key:a.key,name:a.name,resourceId:e.resourceId}))}}async getJiraProjectsForResources(e,r={}){let n=[];return await Promise.all(e.resourceIds.map(async o=>{try{return await Et(a=>this.getJiraProjectsForResource({resourceId:o,cursor:a},r))}catch{return[]}})).then((...o)=>{o.forEach(a=>{n=n.concat(...a)})}),{data:n}}async getAccountsForJiraProject(e,r={}){let{resourceId:n,projectKey:o,cursor:a}=e,i=await this.getResourceUrl({resourceId:n},r),u=new URL(`${r.baseUrl||ae}/${n}/rest/api/2/user/assignable/search`);u.searchParams.set("maxResults",ht.toString()),a&&u.searchParams.set("startAt",a),u.searchParams.set("project",o);let l=await this.config.request({url:u.toString(),headers:h(r.token||this.config.token)});return{pageInfo:{hasNextPage:l.body.length!==0,endCursor:((a?parseInt(a):0)+l.body.length).toString()},data:l.body.filter(p=>p.accountType!=="app"&&p.active).map(p=>Ee(p,i,!1))}}async getComponentsForJiraProject(e,r={}){return await Te(this.config,e,r)}async getIssue(e,r={}){let n=await this.getIssueFieldsForResource({resourceId:e.resourceId},r),o=await this.getResourceUrl({resourceId:e.resourceId},r);return await Ce(this.config,{...e,fields:n},o,r)}async getIssuesForProject(e,r={}){let n=await this.getIssueFieldsForResource({resourceId:e.resourceId},r),o=await this.getResourceUrl({resourceId:e.resourceId},r);return await De(this.config,{...e,fields:n},o,r)}async getIssuesForProjects(e,r={}){let n=await this.getIssueFieldsForResource({resourceId:e.resourceId},r),o=await this.getResourceUrl({resourceId:e.resourceId},r);return await $e(this.config,{...e,fields:n},o,r)}async getIssuesForResourceForCurrentUser(e,r={}){let n=await this.getIssueFieldsForResource({resourceId:e.resourceId},r),o=await this.getResourceUrl({resourceId:e.resourceId},r);return await Le(this.config,{...e,fields:n},o,r)}async setIssueStatus(e,r={}){await Ge(this.config,e,r)}async setIssueAssignee(e,r={}){let{issue:n,assignee:o}=e;if(!n.project)throw new Error('Jira Cloud requires a "project" for this function.');if(!n.project.resourceId)throw new Error('Jira Cloud requires a project "resourceId" for this function.');let a={accountId:o?.id};await this.config.request({method:"PUT",url:`${r.baseUrl||ae}/${n.project.resourceId}/rest/api/2/issue/${n.id}/assignee`,body:JSON.stringify(a),headers:{...h(r.token||this.config.token),"Content-Type":"application/json"}})}async setIssueComponents(e,r={}){await Ae(this.config,e,r)}async setIssueLabels(e,r={}){await Ue(this.config,e,r)}async getLabelsForResource(e,r={}){let{resourceId:n,cursor:o}=e,a=new URL(`${r.baseUrl||ae}/${n}/rest/api/2/label`);a.searchParams.set("maxResults",ht.toString()),o&&a.searchParams.set("startAt",o);let i=await this.config.request({url:a.toString(),headers:h(r.token||this.config.token)});return{pageInfo:{hasNextPage:!i.body.isLast,endCursor:(i.body.startAt+i.body.values.length).toString()},data:i.body.values.map(u=>({color:null,description:null,id:null,name:u}))}}};var te=class extends L{constructor(){super(...arguments);this._issueFieldsCache={}}async getIssueFieldsForResource(e={}){let r=e?.baseUrl||this.config.baseUrl||"";if(!this._issueFieldsCache[r]){let n=await qe(this.config,{},e);this._issueFieldsCache[r]=n.reduce((o,a)=>({...o,[a.name]:a.id}),{})}return this._issueFieldsCache[r]??null}async getCurrentUser(e={}){let r=await this.config.request({url:`${e?.baseUrl||this.config.baseUrl}/rest/api/2/myself`,headers:h(e?.token||this.config.token)});return{data:{name:r.body.displayName,email:r.body.emailAddress,avatarUrl:r.body.avatarUrls["48x48"],id:r.body.key,username:r.body.displayName,url:null}}}async getJiraProjects(e={}){return{data:(await this.config.request({url:`${e?.baseUrl||this.config.baseUrl}/rest/api/2/project`,headers:h(e?.token||this.config.token)})).body.map(n=>({id:n.id,name:n.name}))}}async getIssue(e,r={}){let n=e.resourceUrl||r.baseUrl||this.config.baseUrl;if(!n)throw new Error('Jira Server requires a "resourceUrl" or "baseUrl" for this function.');let o=await this.getIssueFieldsForResource(r);return await Ce(this.config,{...e,fields:o},n,r)}async getIssuesForProject(e,r={}){let n=e.resourceUrl||r.baseUrl||this.config.baseUrl;if(!n)throw new Error('Jira Server requires a "resourceUrl" or "baseUrl" for this function.');let o=await this.getIssueFieldsForResource(r);return await De(this.config,{...e,fields:o},n,r)}async getIssuesForProjects(e,r={}){let n=e.resourceUrl||r.baseUrl||this.config.baseUrl;if(!n)throw new Error('Jira Server requires a "resourceUrl" or "baseUrl" for this function.');let o=await this.getIssueFieldsForResource(r);return await $e(this.config,{...e,fields:o},n,r)}async getIssuesForResourceForCurrentUser(e,r={}){let n=e.resourceUrl||r.baseUrl||this.config.baseUrl;if(!n)throw new Error('Jira Server requires a "resourceUrl" or "baseUrl" for this function.');let o=await this.getIssueFieldsForResource(r);return await Le(this.config,{...e,fields:o},n,r)}async setIssueStatus(e,r={}){await Ge(this.config,e,r)}async setIssueLabels(e,r={}){await Ue(this.config,e,r)}async setIssueComponents(e,r={}){await Ae(this.config,e,r)}async getLabels(e={}){return{data:(await this.config.request({url:`${e?.baseUrl||this.config.baseUrl}/rest/api/2/jql/autocompletedata/suggestions?fieldName=labels`,headers:h(e.token||this.config.token)})).body.results.map(({displayName:n})=>({color:null,description:null,id:null,name:n}))}}async getComponentsForJiraProject(e,r={}){return await Te(this.config,e,r)}};var T="https://api.trello.com",Cs=1e3,Ls=t=>({id:t.id,username:t.username,url:t.url,name:t.fullName,email:t.email,avatarUrl:t.avatarUrl}),Ds=(t,s)=>{let e=new Date(1e3*parseInt(t.id.substring(0,8),16));return{id:t.id,commentCount:t.badges.comments,number:t.idShort.toString(),title:t.name,url:t.url,closedDate:null,createdDate:new Date(e.toISOString()),author:null,updatedDate:new Date(t.dateLastActivity),assignees:t.members.map(r=>({id:r.id,username:r.username,name:r.fullName,email:null,avatarUrl:r.avatarUrl,url:null})),description:null,state:s[t.idList??""]?{id:t.idList,name:s[t.idList].name,color:null}:null,type:null,repository:null,upvoteCount:t.badges.votes,labels:t.labels.map(r=>({color:r.color,description:null,id:r.id,name:r.name}))}},re=class extends U{async getCurrentUser(s,e={}){let r=await this.config.request({url:`${e.baseUrl||T}/1/members/me?key=${s.appKey}&token=${e.token||this.config.token}`,headers:h(e.token||this.config.token)});return{data:{name:r.body.fullName,email:r.body.email,avatarUrl:r.body.avatarHash?`https://trello-members.s3.amazonaws.com/${r.body.id}/${r.body.avatarHash}/50.png`:null,id:r.body.id,username:r.body.username,url:r.body.url}}}async getBoardsForCurrentUser(s,e={}){return{data:(await this.config.request({url:`${e.baseUrl||T}/1/members/me/boards?fields=name&key=${s.appKey}&token=${e.token||this.config.token}&filter=open`,headers:h(e.token||this.config.token)})).body.map(n=>({id:n.id,name:n.name}))}}async getListsForTrelloBoard(s,e={}){let{appKey:r,boardId:n}=s;return{data:(await this.config.request({url:`${e.baseUrl||T}/1/boards/${n}/lists?key=${r}&token=${e.token||this.config.token}`,headers:h(e.token||this.config.token)})).body}}async getAccountForId(s,e={}){let{appKey:r,memberId:n}=s,o=await this.config.request({url:`${e.baseUrl||T}/1/members/${n}/?key=${r}&token=${e.token||this.config.token}`});return{data:Ls(o.body)}}async getAccountsForTrelloBoard(s,e={}){let{appKey:r,boardId:n}=s;return{data:(await this.config.request({url:`${e.baseUrl||T}/1/boards/${n}/members?key=${r}&token=${e.token||this.config.token}`,headers:h(e.token||this.config.token)})).body.map(a=>({id:a.id,name:a.fullName,username:a.username,email:null,avatarUrl:null,url:null}))}}async getIssuesForBoard(s,e={}){let r=["-is:archived","sort:edited"],{appKey:n,boardId:o,filterText:a,assigneeLogins:i,labelNamesOrColors:u,trelloBoardListsById:l}=s||{};i&&r.push("@me"),u&&u.forEach(c=>r.push(`label:"${c}"`));let p=`${a?`${a}`:""}${r.join(" ")} board:${o}`;return{data:(await this.config.request({url:`${e.baseUrl||T}/1/search?key=${n}&query=${p}&cards_limit=${Cs}&token=${e.token||this.config.token}&card_members=true`,headers:h(e.token||this.config.token)})).body.cards.map(c=>Ds(c,l||{}))}}async updateIssue(s,e,r,n){return await this.config.request({method:"PUT",url:`${n.baseUrl||T}/1/cards/${e.id}?key=${s}&token=${n.token||this.config.token}&${r}`,headers:h(n.token||this.config.token)})}async setIssueStatus(s,e={}){let{appKey:r,issue:n,status:o}=s;if(!o.id)throw new Error('Trello requires a status "id" for this function.');let a=`idList=${o.id}`;if(!(await this.updateIssue(r,n,a,e)).body.id)throw new Error("Could not set issue status")}async setIssueAssignees(s,e={}){let{appKey:r,issue:n,assignees:o}=s,a=o.map(l=>l.id),i=`idMembers=${encodeURIComponent(a.join(","))}`;if(!(await this.updateIssue(r,n,i,e)).body.id)throw new Error("Could not set issue status")}async setIssueLabels(s,e={}){let{appKey:r,issue:n,labels:o}=s,a=o.map(u=>u.id).join(",");if(!(await this.config.request({method:"PUT",url:`${e.baseUrl||T}/1/cards/${n.id}?key=${r}&token=${e.token||this.config.token}&idLabels=${encodeURIComponent(a)}`,headers:h(e.token||this.config.token)})).body.id)throw new Error("Could not set issue status")}async setIssueArchived(s,e={}){let{appKey:r,issue:n,archived:o}=s;if(!(await this.config.request({method:"PUT",url:`${e.baseUrl||T}/1/cards/${n.id}?key=${r}&token=${e.token||this.config.token}&closed=${o}`,headers:h(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:r,boardId:n}=s;return{data:(await this.config.request({url:`${e.baseUrl||T}/1/boards/${n}/labels?key=${r}&token=${e.token||this.config.token}`,headers:h(e.token||this.config.token)})).body.map(a=>({color:a.color,description:null,id:a.id,name:a.name}))}}};var It=100,Oe=class{constructor(){this.set=new Set;this.arr=[]}push(...s){let e=s.filter(r=>!this.set.has(r.id));this.arr.push(...e),e.forEach(r=>this.set.add(r.id))}get length(){return this.arr.length}get items(){return this.arr}},_=async(t,s,e,r)=>{let n=s.token||t.token;if(!n)throw new Error("Linear API key is required");let o=await t.request({url:"https://api.linear.app/graphql",method:"POST",headers:{Authorization:n,"Content-Type":"application/json"},body:JSON.stringify({query:e,variables:r})});if(o.status>=400)throw new Error(`Linear API request failed: ${o.status} ${o.statusText}`);let a=o.body;if(a.errors)throw new Error(`Linear GraphQL errors: ${a.errors.map(i=>i.message).join(", ")}`);return a.data},ft=t=>t?t instanceof Date?t:new Date(t):null,$s=`
1163
+ `,variables:{fullPath:`${t}/${n}`,after:o}},e);return{pageInfo:a.body.data?.project?.labels?.pageInfo??{endCursor:null,hasNextPage:!1},data:a.body.data?.project?.labels?.nodes?.map(dt)??[]}}async getTreeForRepo(s,e={}){let t=j(s.repo),n=new URL(s.cursor??`${Pe(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:h(e.token||this.config.token)}),a=o.headers.link;return{data:o.body.map(fs),pageInfo:{endCursor:a?a.substring(1,a.indexOf(">")):null,hasNextPage:!!a}}}};var ys="https://api.atlassian.com/ex/jira",ve=100,gt=["assignee","comment","summary","created","creator","updated","votes","issuetype","status","labels","components","project","fixVersions","description"],zt="/rest/api/2/search/jql",Mt="/rest/api/2/search",mt=(r,s,e,t)=>{let n=r.fields.assignee,o=!t,a=(r.fields[s?.Sprint??""]??[]).filter(i=>typeof i=="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:qe(r.fields.creator,e,o),updatedDate:new Date(r.fields.updated),assignees:n?[qe(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:vs(r.fields.status),statusTransitions:r.transitions?.map(Ps)??[],components:r.fields.components?.map(ws)??[],type:r.fields.issuetype.name,upvoteCount:r.fields.votes?.votes||0,labels:r.fields.labels?.map(i=>({color:null,description:null,id:null,name:i}))??[],sprints:a.map(qs),fixVersions:r.fields.fixVersions.map(Es)}},Ps=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}}},ws=r=>({description:r.description??null,id:r.id,name:r.name}),Ss=(r,s,e)=>e&&r.name?`${s}/secure/ViewProfile.jspa?name=${encodeURIComponent(r.name)}`:`${s}/jira/people/${r.accountId}`,qe=(r,s,e)=>({id:(e?r.key:r.accountId)??"",name:r.displayName,email:r.emailAddress,avatarUrl:r.avatarUrls["48x48"],username:r.displayName,url:Ss(r,s,e)}),vs=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}},qs=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}),Es=r=>({id:r.id,description:r.description,name:r.name,archived:r.archived,released:r.released,releaseDate:r.releaseDate?new Date(r.releaseDate):null}),B=(r,s,e)=>e?`${s.baseUrl||ys}/${e}`:`${s?.baseUrl||r.baseUrl}`,Ee=async(r,s,e={})=>{let{resourceId:t}=s;return(await r.request({url:`${B(r,e,t)}/rest/api/2/field`,headers:h(e.token||r.token)})).body},Ce=async(r,s,e,t={})=>{let{number:n,resourceId:o,fields:a}=s||{},i=await r.request({url:`${B(r,t,o)}/rest/api/2/issue/${n}?fields=${gt.join(",")}&expand=transitions`,headers:h(t.token||r.token)});return{data:mt(i.body,a,e,o)}},Le=async(r,s,e,t={})=>{let{cursor:n,resourceId:o,labelNames:a,fields:i}=s||{},u=["statusCategory != Done",`(creator = currentUser() OR assignee = currentUser()
1164
+ OR comment ~ currentUser() OR summary ~ currentUser() OR description ~ currentUser())`];a&&a.forEach($=>u.push(`labels = "${$}"`));let l=`${u.join(" AND ")} ORDER BY updated DESC`,p=!o,d=p?Mt:zt,c=new URL(`${B(r,t,o)}${d}`);c.searchParams.set("jql",l),c.searchParams.set("maxResults",ve.toString()),c.searchParams.set("fields",gt.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:h(t.token||r.token)}),m=g.body.issues.map($=>mt($,i,e,o)),b=!1,I="";return p?(b=m.length==ve,I=(parseInt(n??"0",10)+m.length).toString()):(b=!!g.body.nextPageToken,I=g.body.nextPageToken??null),{data:m,pageInfo:{hasNextPage:b,endCursor:I}}},Wt=async(r,s,e,t={})=>{let{cursor:n,resourceId:o,jql:a,fields:i}=s||{},u=[...gt],l=i?.Sprint;l&&u.push(l);let p=!o,d=p?Mt:zt,c=new URL(`${B(r,t,o)}${d}`);c.searchParams.set("jql",a.join(" AND ")),c.searchParams.set("maxResults",ve.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:h(t.token||r.token)}),m=g.body.issues.map($=>mt($,i,e,o)),b=!1,I="";return p?(b=m.length==ve,I=(parseInt(n??"0",10)+m.length).toString()):(b=!!g.body.nextPageToken,I=g.body.nextPageToken??null),{data:m,pageInfo:{hasNextPage:b,endCursor:I}}},De=async(r,s,e,t={})=>{let{assigneeLogins:n,authorLogin:o,mentionLogin:a,labelNames:i,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('", "')}")`),a&&c.push(`comment ~ "${a}"`),i&&i.forEach(g=>c.push(`labels = "${g}"`)),Wt(r,{resourceId:p,jql:c,cursor:u,fields:d},e,t)},$e=async(r,s,e,t={})=>{let{assigneeLogins:n,authorLogin:o,mentionLogin:a,labelNames:i,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('", "')}")`),a&&g.push(`comment ~ "${a}"`),i&&i.forEach(m=>g.push(`labels = "${m}"`)),Wt(r,{resourceId:p,jql:g,fields:d,cursor:u},e,t)},Ue=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(a=>a.name)}};await r.request({method:"PUT",url:`${B(r,e,t.project.resourceId??void 0)}/rest/api/2/issue/${t.id}`,body:JSON.stringify(o),headers:{...h(e.token||r.token),"Content-Type":"application/json"}})},Ae=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(a=>({id:a.id}))}};await r.request({method:"PUT",url:`${B(r,e,t.project.resourceId??void 0)}/rest/api/2/issue/${t.id}`,body:JSON.stringify(o),headers:{...h(e.token||r.token),"Content-Type":"application/json"}})},Ge=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:`${B(r,e,t.project.resourceId??void 0)}/rest/api/2/issue/${t.id}/transitions`,body:JSON.stringify(o),headers:{...h(e.token||r.token),"Content-Type":"application/json"}})},Te=async(r,s,e={})=>{let{resourceId:t,projectIdOrKey:n}=s,o=new URL(`${B(r,e,t)}/rest/api/2/project/${n}/components`);return{data:(await r.request({url:o.toString(),headers:h(e.token||r.token)})).body}};var ae="https://api.atlassian.com/ex/jira",ht=100,ee=class extends U{constructor(){super(...arguments);this._resourceUrlCache={};this._issueFieldsCache={}}async getIssueFieldsForResource(e,t={}){if(!this._issueFieldsCache[e.resourceId]){let n=await Ee(this.config,e,t);this._issueFieldsCache[e.resourceId]=n.reduce((o,a)=>({...o,[a.name]:a.id}),{})}return this._issueFieldsCache[e.resourceId]??null}async getResourceUrl(e,t={}){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),this._resourceUrlCache[n]?.[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:h(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:h(e.token||this.config.token)}),n=e.token||this.config.token,o=n?this._resourceUrlCache[n]||{}:void 0,a=t.body.map(i=>(o&&(o[i.id]=i.url),{avatarUrl:i.avatarUrl,id:i.id,name:i.name,url:i.url}));return n&&(this._resourceUrlCache[n]=o),{data:a}}async getJiraProjectsForResource(e,t={}){let n=new URL(`${t.baseUrl||ae}/${e.resourceId}/rest/api/2/project/search`);n.searchParams.set("maxResults",ht.toString()),e.cursor&&n.searchParams.set("startAt",e.cursor);let o=await this.config.request({url:n.toString(),headers:h(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(a=>({id:a.id,key:a.key,name:a.name,resourceId:e.resourceId}))}}async getJiraProjectsForResources(e,t={}){let n=[];return await Promise.all(e.resourceIds.map(async o=>{try{return await qt(a=>this.getJiraProjectsForResource({resourceId:o,cursor:a},t))}catch{return[]}})).then((...o)=>{o.forEach(a=>{n=n.concat(...a)})}),{data:n}}async getAccountsForJiraProject(e,t={}){let{resourceId:n,projectKey:o,cursor:a}=e,i=await this.getResourceUrl({resourceId:n},t),u=new URL(`${t.baseUrl||ae}/${n}/rest/api/2/user/assignable/search`);u.searchParams.set("maxResults",ht.toString()),a&&u.searchParams.set("startAt",a),u.searchParams.set("project",o);let l=await this.config.request({url:u.toString(),headers:h(t.token||this.config.token)});return{pageInfo:{hasNextPage:l.body.length!==0,endCursor:((a?parseInt(a):0)+l.body.length).toString()},data:l.body.filter(p=>p.accountType!=="app"&&p.active).map(p=>qe(p,i,!1))}}async getComponentsForJiraProject(e,t={}){return await Te(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 Ce(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 De(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 $e(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 Le(this.config,{...e,fields:n},o,t)}async setIssueStatus(e,t={}){await Ge(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 a={accountId: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(a),headers:{...h(t.token||this.config.token),"Content-Type":"application/json"}})}async setIssueComponents(e,t={}){await Ae(this.config,e,t)}async setIssueLabels(e,t={}){await Ue(this.config,e,t)}async getLabelsForResource(e,t={}){let{resourceId:n,cursor:o}=e,a=new URL(`${t.baseUrl||ae}/${n}/rest/api/2/label`);a.searchParams.set("maxResults",ht.toString()),o&&a.searchParams.set("startAt",o);let i=await this.config.request({url:a.toString(),headers:h(t.token||this.config.token)});return{pageInfo:{hasNextPage:!i.body.isLast,endCursor:(i.body.startAt+i.body.values.length).toString()},data:i.body.values.map(u=>({color:null,description:null,id:null,name:u}))}}};var te=class extends L{constructor(){super(...arguments);this._issueFieldsCache={}}async getIssueFieldsForResource(e={}){let t=e?.baseUrl||this.config.baseUrl||"";if(!this._issueFieldsCache[t]){let n=await Ee(this.config,{},e);this._issueFieldsCache[t]=n.reduce((o,a)=>({...o,[a.name]:a.id}),{})}return this._issueFieldsCache[t]??null}async getCurrentUser(e={}){let t=await this.config.request({url:`${e?.baseUrl||this.config.baseUrl}/rest/api/2/myself`,headers:h(e?.token||this.config.token)});return{data:{name:t.body.displayName,email:t.body.emailAddress,avatarUrl:t.body.avatarUrls["48x48"],id:t.body.key,username:t.body.displayName,url:null}}}async getJiraProjects(e={}){return{data:(await this.config.request({url:`${e?.baseUrl||this.config.baseUrl}/rest/api/2/project`,headers:h(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 Ce(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 De(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 $e(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 Le(this.config,{...e,fields:o},n,t)}async setIssueStatus(e,t={}){await Ge(this.config,e,t)}async setIssueLabels(e,t={}){await Ue(this.config,e,t)}async setIssueComponents(e,t={}){await Ae(this.config,e,t)}async getLabels(e={}){return{data:(await this.config.request({url:`${e?.baseUrl||this.config.baseUrl}/rest/api/2/jql/autocompletedata/suggestions?fieldName=labels`,headers:h(e.token||this.config.token)})).body.results.map(({displayName:n})=>({color:null,description:null,id:null,name:n}))}}async getComponentsForJiraProject(e,t={}){return await Te(this.config,e,t)}};var T="https://api.trello.com",Cs=1e3,Ls=r=>({id:r.id,username:r.username,url:r.url,name:r.fullName,email:r.email,avatarUrl:r.avatarUrl}),Ds=(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}))}},re=class extends U{async getCurrentUser(s,e={}){let t=await this.config.request({url:`${e.baseUrl||T}/1/members/me?key=${s.appKey}&token=${e.token||this.config.token}`,headers:h(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||T}/1/members/me/boards?fields=name&key=${s.appKey}&token=${e.token||this.config.token}&filter=open`,headers:h(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||T}/1/boards/${n}/lists?key=${t}&token=${e.token||this.config.token}`,headers:h(e.token||this.config.token)})).body}}async getAccountForId(s,e={}){let{appKey:t,memberId:n}=s,o=await this.config.request({url:`${e.baseUrl||T}/1/members/${n}/?key=${t}&token=${e.token||this.config.token}`});return{data:Ls(o.body)}}async getAccountsForTrelloBoard(s,e={}){let{appKey:t,boardId:n}=s;return{data:(await this.config.request({url:`${e.baseUrl||T}/1/boards/${n}/members?key=${t}&token=${e.token||this.config.token}`,headers:h(e.token||this.config.token)})).body.map(a=>({id:a.id,name:a.fullName,username:a.username,email:null,avatarUrl:null,url:null}))}}async getIssuesForBoard(s,e={}){let t=["-is:archived","sort:edited"],{appKey:n,boardId:o,filterText:a,assigneeLogins:i,labelNamesOrColors:u,trelloBoardListsById:l}=s||{};i&&t.push("@me"),u&&u.forEach(c=>t.push(`label:"${c}"`));let p=`${a?`${a}`:""}${t.join(" ")} board:${o}`;return{data:(await this.config.request({url:`${e.baseUrl||T}/1/search?key=${n}&query=${p}&cards_limit=${Cs}&token=${e.token||this.config.token}&card_members=true`,headers:h(e.token||this.config.token)})).body.cards.map(c=>Ds(c,l||{}))}}async updateIssue(s,e,t,n){return await this.config.request({method:"PUT",url:`${n.baseUrl||T}/1/cards/${e.id}?key=${s}&token=${n.token||this.config.token}&${t}`,headers:h(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 a=`idList=${o.id}`;if(!(await this.updateIssue(t,n,a,e)).body.id)throw new Error("Could not set issue status")}async setIssueAssignees(s,e={}){let{appKey:t,issue:n,assignees:o}=s,a=o.map(l=>l.id),i=`idMembers=${encodeURIComponent(a.join(","))}`;if(!(await this.updateIssue(t,n,i,e)).body.id)throw new Error("Could not set issue status")}async setIssueLabels(s,e={}){let{appKey:t,issue:n,labels:o}=s,a=o.map(u=>u.id).join(",");if(!(await this.config.request({method:"PUT",url:`${e.baseUrl||T}/1/cards/${n.id}?key=${t}&token=${e.token||this.config.token}&idLabels=${encodeURIComponent(a)}`,headers:h(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||T}/1/cards/${n.id}?key=${t}&token=${e.token||this.config.token}&closed=${o}`,headers:h(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||T}/1/boards/${n}/labels?key=${t}&token=${e.token||this.config.token}`,headers:h(e.token||this.config.token)})).body.map(a=>({color:a.color,description:null,id:a.id,name:a.name}))}}};var Rt=100,Oe=class{constructor(){this.set=new Set;this.arr=[]}push(...s){let e=s.filter(t=>!this.set.has(t.id));this.arr.push(...e),e.forEach(t=>this.set.add(t.id))}get length(){return this.arr.length}get items(){return this.arr}},_=async(r,s,e,t)=>{let n=s.token||r.token;if(!n)throw new Error("Linear API key is required");let o=await r.request({url:"https://api.linear.app/graphql",method:"POST",headers:{Authorization:n,"Content-Type":"application/json"},body:JSON.stringify({query:e,variables:t})});if(o.status>=400)throw new Error(`Linear API request failed: ${o.status} ${o.statusText}`);let a=o.body;if(a.errors)throw new Error(`Linear GraphQL errors: ${a.errors.map(i=>i.message).join(", ")}`);return a.data},ft=r=>r?r instanceof Date?r:new Date(r):null,$s=`
1126
1165
  id
1127
1166
  name
1128
1167
  description
@@ -1130,7 +1169,7 @@ OR comment ~ currentUser() OR summary ~ currentUser() OR description ~ currentUs
1130
1169
  startDate
1131
1170
  targetDate
1132
1171
  url
1133
- `,Ht=t=>({id:t.id,name:t.name,description:t.description??null,state:t.state,startDate:ft(t.startDate),targetDate:ft(t.targetDate),url:t.url}),Jt=async(t,s,e)=>{let r=`
1172
+ `,Ht=r=>({id:r.id,name:r.name,description:r.description??null,state:r.state,startDate:ft(r.startDate),targetDate:ft(r.targetDate),url:r.url}),Jt=async(r,s,e)=>{let t=`
1134
1173
  query GetProjects($first: Int!, $after: String) {
1135
1174
  projects(first: $first, after: $after) {
1136
1175
  nodes {
@@ -1142,7 +1181,7 @@ OR comment ~ currentUser() OR summary ~ currentUser() OR description ~ currentUs
1142
1181
  }
1143
1182
  }
1144
1183
  }
1145
- `;return(await _(t,s,r,{first:It,after:e})).projects},Us=`
1184
+ `;return(await _(r,s,t,{first:Rt,after:e})).projects},Us=`
1146
1185
  id
1147
1186
  name
1148
1187
  number
@@ -1150,7 +1189,7 @@ OR comment ~ currentUser() OR summary ~ currentUser() OR description ~ currentUs
1150
1189
  startsAt
1151
1190
  endsAt
1152
1191
  completedAt
1153
- `,Vt=t=>({id:t.id,name:t.name??`Cycle ${t.number}`,number:t.number,description:t.description??null,startsAt:new Date(t.startsAt),endsAt:new Date(t.endsAt),completedAt:ft(t.completedAt),url:""}),Kt=async(t,s,e)=>{let r=`
1192
+ `,Vt=r=>({id:r.id,name:r.name??`Cycle ${r.number}`,number:r.number,description:r.description??null,startsAt:new Date(r.startsAt),endsAt:new Date(r.endsAt),completedAt:ft(r.completedAt),url:""}),Kt=async(r,s,e)=>{let t=`
1154
1193
  query GetCycles($first: Int!, $after: String) {
1155
1194
  cycles(first: $first, after: $after) {
1156
1195
  nodes {
@@ -1162,12 +1201,12 @@ OR comment ~ currentUser() OR summary ~ currentUser() OR description ~ currentUs
1162
1201
  }
1163
1202
  }
1164
1203
  }
1165
- `;return(await _(t,s,r,{first:It,after:e})).cycles},As=`
1204
+ `;return(await _(r,s,t,{first:Rt,after:e})).cycles},As=`
1166
1205
  id
1167
1206
  name
1168
1207
  color
1169
1208
  description
1170
- `,Xt=t=>({id:t.id,name:t.name,color:t.color,description:t.description??null}),Zt=async(t,s,e)=>{let r=`
1209
+ `,Xt=r=>({id:r.id,name:r.name,color:r.color,description:r.description??null}),Zt=async(r,s,e)=>{let t=`
1171
1210
  query GetLabels($first: Int!, $after: String) {
1172
1211
  projectLabels(first: $first, after: $after) {
1173
1212
  nodes {
@@ -1179,31 +1218,31 @@ OR comment ~ currentUser() OR summary ~ currentUser() OR description ~ currentUs
1179
1218
  }
1180
1219
  }
1181
1220
  }
1182
- `;return(await _(t,s,r,{first:It,after:e})).projectLabels};var ie=(a=>(a[a.None=0]="None",a[a.Assignee=1]="Assignee",a[a.Creator=2]="Creator",a[a.Mention=3]="Mention",a[a.MentionInDescription=4]="MentionInDescription",a[a.MentionInComments=5]="MentionInComments",a))(ie||{});function Yt(t,s){return t?`${ie[t]}:${s||""}`:s??null}function er(t){if(!t)return{category:0};let[s,e]=t.split(":");return s in ie?{category:ie[s],cursor:e||void 0}:{category:0,cursor:t}}var tr=100;function ke(t){return t?t instanceof Date?t:new Date(t):null}var nr=`
1221
+ `;return(await _(r,s,t,{first:Rt,after:e})).projectLabels};var ie=(a=>(a[a.None=0]="None",a[a.Assignee=1]="Assignee",a[a.Creator=2]="Creator",a[a.Mention=3]="Mention",a[a.MentionInDescription=4]="MentionInDescription",a[a.MentionInComments=5]="MentionInComments",a))(ie||{});function Yt(r,s){return r?`${ie[r]}:${s||""}`:s??null}function er(r){if(!r)return{category:0};let[s,e]=r.split(":");return s in ie?{category:ie[s],cursor:e||void 0}:{category:0,cursor:r}}var tr=100;function ke(r){return r?r instanceof Date?r:new Date(r):null}var nr=`
1183
1222
  id
1184
1223
  name
1185
1224
  key
1186
1225
  icon
1187
- `;function Gs(t){return{id:t.id,name:t.name,key:t.key,iconUrl:t.icon}}var rr=`
1226
+ `;function Gs(r){return{id:r.id,name:r.name,key:r.key,iconUrl:r.icon}}var rr=`
1188
1227
  id
1189
1228
  name
1190
1229
  avatarUrl
1191
- `;function sr(t){return t?{id:t.id,name:t.name,username:t.name,email:null,avatarUrl:t.avatarUrl??null,url:null}:null}var Ts=`
1230
+ `;function sr(r){return r?{id:r.id,name:r.name,username:r.name,email:null,avatarUrl:r.avatarUrl??null,url:null}:null}var Ts=`
1192
1231
  id
1193
1232
  name
1194
- `;function Os(t,s){if(t)return{id:t.id,name:t.name,key:s?.key||null,namespace:null,resourceId:s?.id||null}}var xs=`
1233
+ `;function Os(r,s){if(r)return{id:r.id,name:r.name,key:s?.key||null,namespace:null,resourceId:s?.id||null}}var xs=`
1195
1234
  id
1196
1235
  sortOrder
1197
1236
  name
1198
1237
  description
1199
1238
  status
1200
1239
  targetDate
1201
- `;function ks(t){return t?{id:t.id,number:t.sortOrder,title:t.name,description:t.description??null,isOpen:t.status!=="done",url:"",startDate:null,dueDate:ke(t.targetDate)}:null}function Ns(t){switch(t){case"completed":case"canceled":return"DONE";case"started":return"IN_PROGRESS";default:return"TO_DO"}}var _s=`
1240
+ `;function ks(r){return r?{id:r.id,number:r.sortOrder,title:r.name,description:r.description??null,isOpen:r.status!=="done",url:"",startDate:null,dueDate:ke(r.targetDate)}:null}function Ns(r){switch(r){case"completed":case"canceled":return"DONE";case"started":return"IN_PROGRESS";default:return"TO_DO"}}var _s=`
1202
1241
  id
1203
1242
  name
1204
1243
  color
1205
1244
  type
1206
- `;function Fs(t){return t?{id:t.id,name:t.name,color:t.color,category:Ns(t.type)}:null}var bt=`
1245
+ `;function Fs(r){return r?{id:r.id,name:r.name,color:r.color,category:Ns(r.type)}:null}var bt=`
1207
1246
  creator {
1208
1247
  ${rr}
1209
1248
  }
@@ -1230,7 +1269,7 @@ OR comment ~ currentUser() OR summary ~ currentUser() OR description ~ currentUs
1230
1269
  projectMilestone {
1231
1270
  ${xs}
1232
1271
  }
1233
- `;async function Rt(t){return{author:sr(await t.creator),assignees:[sr(await t.assignee)].filter(s=>s!=null),commentCount:null,closedDate:ke(t.archivedAt),createdDate:ke(t.createdAt),description:t.description??null,id:t.id,labels:[],number:t.identifier,repository:null,project:Os(await t.project,await t.team),state:Fs(await t.state),title:t.title,type:null,updatedDate:ke(t.updatedAt),upvoteCount:null,url:t.url,milestone:ks(await t.projectMilestone)}}var xe=`
1272
+ `;async function It(r){return{author:sr(await r.creator),assignees:[sr(await r.assignee)].filter(s=>s!=null),commentCount:null,closedDate:ke(r.archivedAt),createdDate:ke(r.createdAt),description:r.description??null,id:r.id,labels:[],number:r.identifier,repository:null,project:Os(await r.project,await r.team),state:Fs(await r.state),title:r.title,type:null,updatedDate:ke(r.updatedAt),upvoteCount:null,url:r.url,milestone:ks(await r.projectMilestone)}}var xe=`
1234
1273
  nodes {
1235
1274
  ${bt}
1236
1275
  }
@@ -1238,13 +1277,13 @@ OR comment ~ currentUser() OR summary ~ currentUser() OR description ~ currentUs
1238
1277
  hasNextPage
1239
1278
  endCursor
1240
1279
  }
1241
- `,Ne=class extends U{async fetchIssue(s,e){let r=`
1280
+ `,Ne=class extends U{async fetchIssue(s,e){let t=`
1242
1281
  query GetIssue($identifier: String!) {
1243
1282
  issue(id: $identifier) {
1244
1283
  ${bt}
1245
1284
  }
1246
1285
  }
1247
- `;return(await _(this.config,e,r,{identifier:s})).issue}async fetchOrganization(s){let e=`
1286
+ `;return(await _(this.config,e,t,{identifier:s})).issue}async fetchOrganization(s){let e=`
1248
1287
  query GetOrganization {
1249
1288
  organization {
1250
1289
  id
@@ -1260,7 +1299,7 @@ OR comment ~ currentUser() OR summary ~ currentUser() OR description ~ currentUs
1260
1299
  }
1261
1300
  }
1262
1301
  }
1263
- `;return(await _(this.config,s,e)).teams}async rawRequest(s,e,r){return{data:await _(this.config,s,e,r)}}async fetchViewer(s){let e=`
1302
+ `;return(await _(this.config,s,e)).teams}async rawRequest(s,e,t){return{data:await _(this.config,s,e,t)}}async fetchViewer(s){let e=`
1264
1303
  query GetViewer {
1265
1304
  viewer {
1266
1305
  id
@@ -1269,7 +1308,7 @@ OR comment ~ currentUser() OR summary ~ currentUser() OR description ~ currentUs
1269
1308
  displayName
1270
1309
  }
1271
1310
  }
1272
- `;return(await _(this.config,s,e)).viewer}async getIssue(s,e={}){let r=await this.fetchIssue(s.number,e);return{data:await Rt(r)}}async getLinearOrganization(s={}){let e=await this.fetchOrganization(s);return{data:{id:e.id,name:e.name,key:e.urlKey,url:`https://linear.app/${e.urlKey}`}}}async getTeamsForCurrentUser(s={}){return{data:(await this.fetchTeams(s)).nodes.map(Gs)}}async getProjects(s={},e={}){let r=await Jt(this.config,e,s.cursor??void 0);return{data:r.nodes.map(Ht),pageInfo:{hasNextPage:r.pageInfo.hasNextPage,endCursor:r.pageInfo.endCursor??null}}}async getCycles(s={},e={}){let r=await Kt(this.config,e,s.cursor??void 0);return{data:r.nodes.map(Vt),pageInfo:{hasNextPage:r.pageInfo.hasNextPage,endCursor:r.pageInfo.endCursor??null}}}async getLabels(s={},e={}){let r=await Zt(this.config,e,s.cursor??void 0);return{data:r.nodes.map(Xt),pageInfo:{hasNextPage:r.pageInfo.hasNextPage,endCursor:r.pageInfo.endCursor??null}}}async getCurrentUser(s={}){return{data:await this.fetchViewer(s)}}async getIssuesForCurrentUser(s,e={}){let{cursor:r}=s,{category:n,cursor:o}=er(r),a=await this.fetchViewer(e),i,u,l=new Oe,p=async(d,c)=>{if(u||n>d)return;let g=await c(Math.max(tr-l.length,1),n===d?o:void 0);if(!g)return;let m=await je(g.nodes.map(Rt));l.push(...m),g.pageInfo.hasNextPage&&(i=d,u=g.pageInfo.endCursor)};return await p(1,async(d,c)=>(await this.rawRequest(e,`
1311
+ `;return(await _(this.config,s,e)).viewer}async getIssue(s,e={}){let t=await this.fetchIssue(s.number,e);return{data:await It(t)}}async getLinearOrganization(s={}){let e=await this.fetchOrganization(s);return{data:{id:e.id,name:e.name,key:e.urlKey,url:`https://linear.app/${e.urlKey}`}}}async getTeamsForCurrentUser(s={}){return{data:(await this.fetchTeams(s)).nodes.map(Gs)}}async getProjects(s={},e={}){let t=await Jt(this.config,e,s.cursor??void 0);return{data:t.nodes.map(Ht),pageInfo:{hasNextPage:t.pageInfo.hasNextPage,endCursor:t.pageInfo.endCursor??null}}}async getCycles(s={},e={}){let t=await Kt(this.config,e,s.cursor??void 0);return{data:t.nodes.map(Vt),pageInfo:{hasNextPage:t.pageInfo.hasNextPage,endCursor:t.pageInfo.endCursor??null}}}async getLabels(s={},e={}){let t=await Zt(this.config,e,s.cursor??void 0);return{data:t.nodes.map(Xt),pageInfo:{hasNextPage:t.pageInfo.hasNextPage,endCursor:t.pageInfo.endCursor??null}}}async getCurrentUser(s={}){return{data:await this.fetchViewer(s)}}async getIssuesForCurrentUser(s,e={}){let{cursor:t}=s,{category:n,cursor:o}=er(t),a=await this.fetchViewer(e),i,u,l=new Oe,p=async(d,c)=>{if(u||n>d)return;let g=await c(Math.max(tr-l.length,1),n===d?o:void 0);if(!g)return;let m=await je(g.nodes.map(It));l.push(...m),g.pageInfo.hasNextPage&&(i=d,u=g.pageInfo.endCursor)};return await p(1,async(d,c)=>(await this.rawRequest(e,`
1273
1312
  query GetAssignedIssues($first: Int!, $after: String) {
1274
1313
  viewer {
1275
1314
  issues: assignedIssues(first: $first, after: $after) {
@@ -1341,10 +1380,10 @@ OR comment ~ currentUser() OR summary ~ currentUser() OR description ~ currentUs
1341
1380
  }
1342
1381
  }
1343
1382
  }
1344
- `,{first:d,after:c})).data?.comments;return m?{nodes:m.nodes.map(R=>R.issue),pageInfo:m.pageInfo}:void 0}),{data:l.items,pageInfo:{hasNextPage:!!u,endCursor:Yt(i,u)}}}async getIssues(s,e={}){let{teams:r,projects:n,labels:o,cursor:a}=s,i=[];if(r&&r.length>0){let g=r.map(m=>`"${m}"`).join(", ");i.push(`team: { id: { in: [${g}] } }`)}if(n&&n.length>0){let g=n.map(m=>`"${m}"`).join(", ");i.push(`project: { id: { in: [${g}] } }`)}if(o&&o.length>0){let g=o.map(m=>`"${m}"`).join(", ");i.push(`labels: { name: { in: [${g}] } }`)}let u=i.length>0?`filter: { ${i.join(", ")} }`:"",l=`
1383
+ `,{first:d,after:c})).data?.comments;return m?{nodes:m.nodes.map(I=>I.issue),pageInfo:m.pageInfo}:void 0}),{data:l.items,pageInfo:{hasNextPage:!!u,endCursor:Yt(i,u)}}}async getIssues(s,e={}){let{teams:t,projects:n,labels:o,cursor:a}=s,i=[];if(t&&t.length>0){let g=t.map(m=>`"${m}"`).join(", ");i.push(`team: { id: { in: [${g}] } }`)}if(n&&n.length>0){let g=n.map(m=>`"${m}"`).join(", ");i.push(`project: { id: { in: [${g}] } }`)}if(o&&o.length>0){let g=o.map(m=>`"${m}"`).join(", ");i.push(`labels: { name: { in: [${g}] } }`)}let u=i.length>0?`filter: { ${i.join(", ")} }`:"",l=`
1345
1384
  query GetIssues($first: Int!, $after: String) {
1346
1385
  issues(first: $first, after: $after${u?", ":""}${u}) {
1347
1386
  ${xe}
1348
1387
  }
1349
1388
  }
1350
- `,d=(await this.rawRequest(e,l,{first:tr,after:a})).data?.issues;return d?{data:await je(d.nodes.map(Rt)),pageInfo:{hasNextPage:d.pageInfo.hasNextPage,endCursor:d.pageInfo.endCursor??null}}:{data:[],pageInfo:{hasNextPage:!1,endCursor:null}}}};var or=t=>{let s={request:t?.request};return{azureDevOps:new H({...s,...t?.azureDevOps}),bitbucket:new J({...s,...t?.bitbucket}),bitbucketServer:new V({...s,...t?.bitbucketServer}),github:new X({...s,...t?.github}),gitlab:new Y({...s,...t?.gitlab}),jira:new ee({...s,...t?.jira}),jiraServer:new te({...s,...t?.jiraServer}),linear:new Ne({...s,...t?.linear}),trello:new re({...s,...t?.trello})}};var ar=(a=>(a.Conflicts="conflicts",a.Failure="failure",a.NotSet="notSet",a.Queued="queued",a.RejectedByPolicy="rejectedByPolicy",a.Succeeded="succeeded",a))(ar||{});var ir=(e=>(e.Zero="0",e.One="1",e))(ir||{}),ur=(e=>(e.PullRequest="pr",e.Issue="issue",e))(ur||{}),lr=(c=>(c.Azure="azure",c.AzureDevOpsServer="azureDevOpsServer",c.Github="github",c.GithubEnterprise="githubEnterprise",c.Gitlab="gitlab",c.GitlabSelfHosted="gitlabSelfHosted",c.Bitbucket="bitbucket",c.BitbucketServer="bitbucketServer",c.Jira="jira",c.JiraServer="jiraServer",c.Linear="linear",c.Trello="trello",c))(lr||{});var pr=(e=>(e.Completed="COMPLETED",e.NotPlanned="NOT_PLANNED",e))(pr||{});var Qs=or;
1389
+ `,d=(await this.rawRequest(e,l,{first:tr,after:a})).data?.issues;return d?{data:await je(d.nodes.map(It)),pageInfo:{hasNextPage:d.pageInfo.hasNextPage,endCursor:d.pageInfo.endCursor??null}}:{data:[],pageInfo:{hasNextPage:!1,endCursor:null}}}};var or=r=>{let s={request:r?.request};return{azureDevOps:new H({...s,...r?.azureDevOps}),bitbucket:new J({...s,...r?.bitbucket}),bitbucketServer:new V({...s,...r?.bitbucketServer}),github:new X({...s,...r?.github}),gitlab:new Y({...s,...r?.gitlab}),jira:new ee({...s,...r?.jira}),jiraServer:new te({...s,...r?.jiraServer}),linear:new Ne({...s,...r?.linear}),trello:new re({...s,...r?.trello})}};var ar=(a=>(a.Conflicts="conflicts",a.Failure="failure",a.NotSet="notSet",a.Queued="queued",a.RejectedByPolicy="rejectedByPolicy",a.Succeeded="succeeded",a))(ar||{});var ir=(e=>(e.Zero="0",e.One="1",e))(ir||{}),ur=(e=>(e.PullRequest="pr",e.Issue="issue",e))(ur||{}),lr=(c=>(c.Azure="azure",c.AzureDevOpsServer="azureDevOpsServer",c.Github="github",c.GithubEnterprise="githubEnterprise",c.Gitlab="gitlab",c.GitlabSelfHosted="gitlabSelfHosted",c.Bitbucket="bitbucket",c.BitbucketServer="bitbucketServer",c.Jira="jira",c.JiraServer="jiraServer",c.Linear="linear",c.Trello="trello",c))(lr||{});var pr=(e=>(e.Completed="COMPLETED",e.NotPlanned="NOT_PLANNED",e))(pr||{});var Qs=or;