@gitkraken/provider-apis 0.31.0 → 0.33.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +10 -0
- package/dist/index.js +188 -131
- package/dist/index.provider-utils.js +1 -1
- package/dist/index.providers.js +226 -169
- package/dist/providers/gitProvider.d.ts +6 -1
- package/dist/providers/github/github.d.ts +8 -1
- package/dist/types/exportedTypes/gitProvider.d.ts +12 -0
- package/dist/types/internalTypes/github.d.ts +4 -0
- package/package.json +2 -2
package/dist/index.providers.js
CHANGED
|
@@ -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=(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=`
|
|
1
|
+
"use strict";var Qe=Object.defineProperty;var gr=Object.getOwnPropertyDescriptor;var mr=Object.getOwnPropertyNames;var hr=Object.prototype.hasOwnProperty;var fr=(r,s)=>{for(var e in s)Qe(r,e,{get:s[e],enumerable:!0})},Rr=(r,s,e,t)=>{if(s&&typeof s=="object"||typeof s=="function")for(let n of mr(s))!hr.call(r,n)&&n!==e&&Qe(r,n,{get:()=>s[n],enumerable:!(t=gr(s,n))||t.enumerable});return r};var Ir=r=>Rr(Qe({},"__esModule",{value:!0}),r);var Bs={};fr(Bs,{AzureDevOps:()=>J,Bitbucket:()=>V,BitbucketServer:()=>K,EntityIdentifierProviderType:()=>dr,EntityType:()=>pr,EntityVersion:()=>lr,GitBuildStatusStage:()=>St,GitBuildStatusState:()=>le,GitDiffLineType:()=>je,GitHub:()=>Z,GitHubIssueCloseReason:()=>cr,GitIssueState:()=>he,GitLab:()=>ee,GitMergeStrategy:()=>W,GitPullRequestMergeableState:()=>H,GitPullRequestReviewState:()=>F,GitPullRequestState:()=>M,GraphQLErrors:()=>f,Jira:()=>te,JiraServer:()=>re,PullRequestAsyncStatus:()=>ur,Trello:()=>se,default:()=>js,isFetch:()=>pe});module.exports=Ir(Bs);var St=(n=>(n.Build="build",n.Production="production",n.Staging="staging",n.Test="test",n))(St||{}),le=(p=>(p.ActionRequired="ACTION_REQUIRED",p.Cancelled="CANCELLED",p.Error="ERROR",p.Failed="FAILED",p.Pending="PENDING",p.Running="RUNNING",p.Skipped="SKIPPED",p.Success="SUCCESS",p.Warning="WARNING",p.OptionalActionRequired="OPTIONAL_ACTION_REQUIRED",p))(le||{}),W=(o=>(o.MergeCommit="MERGE_COMMIT",o.Rebase="REBASE",o.RebaseThenMergeCommit="REBASE_THEN_MERGE_COMMIT",o.FastForward="FAST_FORWARD",o.Squash="SQUASH",o))(W||{}),M=(t=>(t.Open="OPEN",t.Closed="CLOSED",t.Merged="MERGED",t))(M||{}),F=(n=>(n.Approved="APPROVED",n.ChangesRequested="CHANGES_REQUESTED",n.Commented="COMMENTED",n.ReviewRequested="REVIEW_REQUESTED",n))(F||{}),H=(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))(H||{}),je=(t=>(t.ADDED="ADDED",t.DELETED="DELETED",t.UNMODIFIED="UNMODIFIED",t))(je||{});var vt={APPROVED:0,COMMENTED:1,REVIEW_REQUESTED:2,CHANGES_REQUESTED:3},G=r=>!r||r.length===0?null:r.reduce((s,e)=>vt[e.state]>vt[s]?e.state:s,"APPROVED");var v=100;var qt=globalThis.fetch;var br=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,i)=>{t[i]=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},Be=r=>async({url:s,...e})=>{let t=await r(s,e);return br(t)};var pe=(r,s=!1)=>r.name==="fetch"||s;var U=class{constructor(s){let e=s?.request||qt;this.config={...s,request:pe(e,s?.forceIsFetch)?Be(e):e}}updateConfig(s){this.config={...this.config,...s,request:s.request&&pe(s.request,s?.forceIsFetch??this.config.forceIsFetch)?Be(s.request):this.config.request}}},D=class extends U{};var h=(r,s)=>{let e={};return r&&(e.Authorization=`${s?"Basic":"Bearer"} ${r}`),e},Et=r=>r?r.reduce((s,e)=>(s[e]=!0,s),{}):void 0,Q=(r,s,e)=>!r||s.some(t=>r[t])?e:"",Ct=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 ze(r){return(await Promise.allSettled(r)).map(e=>yr(e)).filter(e=>e!=null)}function yr(r,s=void 0){return r?.status==="fulfilled"?r.value:s}var Pr="https://app.vssps.visualstudio.com/_apis",wr="https://vssps.dev.azure.com/",Sr="https://dev.azure.com",P=(r,s={})=>h(s.token||r.token,s.isPAT||r.isPAT),Lt=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/"),Me=(r,s)=>{let e=s.baseUrl||r.baseUrl||Pr;return e=e.replace(/\/$/,""),e},w=(r,s)=>{let e=s.baseUrl||r.baseUrl||Sr;return e=e.replace(/\/$/,""),e},He=(r,s)=>{let e=s.baseUrl||r.baseUrl||wr;return e=e.replace(/\/$/,""),e};var vr={active:"OPEN",completed:"MERGED",abandoned:"CLOSED"},qr={10:"APPROVED",5:"APPROVED",0:"REVIEW_REQUESTED",[-5]:"CHANGES_REQUESTED",[-10]:"CHANGES_REQUESTED"},We=r=>({id:r.id,name:r.displayName??null,username:(r.uniqueName||r.displayName)??null,email:null,avatarUrl:r.imageUrl??null,url:null}),ce=r=>r.startsWith("refs/heads/")?r.replace("refs/heads/",""):r,Er=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"}},de=(r,s)=>{let e=[],t=[];return s.reviewers.forEach(n=>{let o={reviewer:We(n),state:qr[n.vote??0]||"REVIEW_REQUESTED"};n.isRequired&&e.push(o),t.push(o)}),{id:s.pullRequestId.toString(),title:s.title,description:s.description??null,number:s.codeReviewId,state:vr[s.status],isDraft:s.isDraft,commentCount:null,upvoteCount:null,author:We(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:ce(s.targetRefName),oid:s.lastMergeTargetCommit.commitId},headRef:{name:ce(s.sourceRefName),oid:s.lastMergeSourceCommit.commitId},url:Lt(s),assignees:s.reviewers.map(We),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:Er(s.mergeStatus),labels:s.labels?.map(n=>({color:null,description:null,id:n.id,name:n.name}))??[],permissions:null}},Dt=(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:ce(s.defaultBranch)}:null,permissions:null}),Cr=(r,s,e,t)=>{let n=e.fields,o=n["System.AssignedTo"],i=n["System.State"],a=n["System.WorkItemType"],u;return i&&a&&(u=t[a]?.[i]),{id:e.id.toString(),number:e.id.toString(),title:n["System.Title"],commentCount:n["System.CommentCount"],author:{avatarUrl:n["System.CreatedBy"]._links?.avatar?.href??null,email:null,id:n["System.CreatedBy"].id,name:n["System.CreatedBy"].uniqueName??null,username:n["System.CreatedBy"].displayName??null,url:null},closedDate:n["Microsoft.VSTS.Common.ClosedDate"]?new Date(n["Microsoft.VSTS.Common.ClosedDate"]):null,createdDate:new Date(n["System.CreatedDate"]),updatedDate:new Date(n["System.ChangedDate"]),url:e._links.html.href,assignees:o?[{avatarUrl:o._links?.avatar?.href??null,email:null,id:o.id,name:o.uniqueName??null,username:o.displayName??null,url:null}]:[],description:n["System.Description"]??null,state:{name:u?.title||i,color:null},type:n["System.WorkItemType"],repository:null,project:{namespace: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()}))??[]}},J=class extends D{async getCurrentUser(s={},e={}){if(e.isPAT||this.config.isPAT)throw new Error("Azure DevOps does not support PATs for this function.");let t=`${Me(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=`${Me(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",v.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(i=>({id:i.id,name:i.name,namespace:s.namespace}))}}async getAzureProjectScopeDescriptor(s,e={}){let{namespace:t,projectId:n}=s;return{data:{scope:(await this.config.request({url:`${He(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,i=new URL(`${He(this.config,e)}/${encodeURIComponent(t)}/_apis/graph/users`);n&&i.searchParams.set("scopeDescriptor",n),o&&i.searchParams.set("continuationToken",o);let a=await this.config.request({url:i.toString(),headers:P(this.config,e)}),u=a.headers["x-ms-continuationtoken"];return{pageInfo:{endCursor:u||null,hasNextPage:!!u},data:a.body.value.map(l=>({avatarUrl:l._links?.avatar?.href??null,descriptor:l.descriptor??null,email:l.mailAddress??null,name:l.displayName??null,storageKeyURL:l._links?.storageKey?.href??null,username:l.displayName??null}))}}async getAccountFromAzureGraphAccount(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:Dt(s.namespace,t.body)}}async getRepos(s,e={}){let t=[],n=[];return await Promise.all(s.map(async o=>{try{let i=await this.getRepo(o,e);t.push(i.data)}catch(i){n.push({input:o,error:i})}})),{data:t,errors:n}}async getReposForAzureProject(s,e={}){if(!s.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');return{data:(await this.config.request({url:`${w(this.config,e)}/${encodeURIComponent(s.namespace)}/${encodeURIComponent(s.project)}/_apis/git/repositories`,headers:P(this.config,e)})).body.value.map(n=>Dt(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",v.toString()),e.cursor&&n.searchParams.set("continuationToken",e.cursor);let o=await this.config.request({url:n.toString(),headers:P(this.config,t)}),i=o.headers["x-ms-continuationtoken"];return{pageInfo:{hasNextPage:!!i,endCursor:i||null},data:o.body.value.map(a=>({name:ce(a.name),commit:{oid:a.objectId,authoredDate:null,committedDate:null}}))}}async getBranches(s,e={}){return this.getRefs("heads",s,e)}async getTags(s,e={}){return this.getRefs("tags",s,e)}async getPullRequestsForRepoBase(s,e={},t=100){let{page:n,repo:o,assigneeLogins:i,authorLogin:a}=s||{},u=n||1;if(!o.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let l="searchCriteria.status=1";return i&&i.length&&(l+=`&searchCriteria.reviewerId=${i[0]}`),a&&(l+=`&searchCriteria.creatorId=${a}`),await this.config.request({url:`${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(i=>de(s.repo.namespace,i))}}async getPullRequestsForRepos(s,e={}){if(!s.repos.every(o=>o.project))throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let{repos:t}=s||{},n=[];return await Promise.all(t.map(async o=>{try{(await this.getPullRequestsForRepoBase({repo:o,...s},e)).body.value.forEach(a=>{n.push(de(o.namespace,a))})}catch(i){if(i.statusCode!==404&&i.statusCode!==401)throw i}})),{data:n}}async getPullRequestsForProjectBase(s,e={},t=100){let{namespace:n,project:o,page:i,assigneeLogins:a,authorLogin:u,repo:l}=s;if(l?.project&&l.project!==o)throw new Error("Could not fetch pull requests, project mismatch");let p=i||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),a&&a.length&&d.searchParams.set("searchCriteria.reviewerId",a[0]),u&&d.searchParams.set("searchCriteria.creatorId",u),await this.config.request({url:d.toString(),headers: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(i=>de(s.namespace,i))||[]}}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(a=>{n.push(de(o.namespace,a))})}catch(i){if(i.statusCode!==404&&i.statusCode!==401)throw i}})),{data:n}}async getAzurePullRequestLastMergeStatus(s,e={}){if(!s.repo.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let{repo:{namespace:t,project:n,name:o},pullRequestId:i}=s,a=await this.config.request({url:`${w(this.config,e)}/${encodeURIComponent(t)}/${encodeURIComponent(n||"")}/_apis/git/repositories/${o}/pullrequests/${i}?includeCommits=true?api-version=6.0`,headers:{...P(this.config,e)}});if(!a.body.mergeStatus)throw new Error("Could not fetch pull request");return{data:a.body.mergeStatus}}async updatePullRequest(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 i={completionOptions:{mergeStrategy:o},lastMergeSourceCommit:{commitId:t.headRef?.oid},status:"completed"};if(!(await this.updatePullRequest(t,JSON.stringify(i),e)).body.status)throw new Error("Could not merge pull request")}async addPullRequestLabel(s,e={}){let{pullRequest:t,label:n}=s;if(!t.repository.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let o={name:n.name};if(!(await this.config.request({method:"POST",url:`${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 i of n)o.find(a=>a.id===i.id)||await this.addPullRequestLabel({pullRequest:t,label:i},e);for(let i of o)n.find(a=>i.id===a.id)||await this.removePullRequestLabel({pullRequest:t,label:i},e)}async setPullRequestAsDraft(s,e={}){let{pullRequest:t,isDraft:n}=s,o={isDraft:n};if(!(await this.updatePullRequest(t,JSON.stringify(o),e)).body.status)throw new Error("Could not set the pull request as draft")}async addPullRequestReviewer(s,e={}){let{pullRequest:t,reviewer:n,isRequired:o}=s,i={id:n.id,isRequired:o};if(!(await this.config.request({method:"PUT",url:`${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(i),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(i=>i.id===o.id)||await this.addPullRequestReviewer({pullRequest:t,reviewer:o,isRequired:!0},e);for(let o of t.assignees)n.find(i=>o.id===i.id)||await this.removePullRequestReviewer({pullRequest:t,reviewer:o},e)}async getIssuesForAzureProject(s,e={}){let{page:t,assigneeLogins:n,authorLogin:o,mentionLogin:i,labelNames:a,statusByWorkItemIdByStatusId:u}=s||{},l=t||1,p=200,d=["[Microsoft.VSTS.Common.ClosedDate] = ''","[System.TeamProject] = @project","[Microsoft.VSTS.Common.ResolvedDate] = ''"];o&&d.push(`[System.CreatedBy] = '${o.replace("'","''")}'`),n&&n[0]&&d.push(`[System.AssignedTo] = '${n[0].replace("'","''")}'`),i&&d.push("[System.Id] IN (@recentMentions)"),a&&a.forEach(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=>Cr(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"]},i=p=>{let d="2e9eb7ed-3c0a-47d4-87c1-0ffdd275fd87",c=`repoV2/${p.projectId}/${p.id}`;return Object.keys(o).map(g=>({securityNamespaceId:d,token:c,permissions:g}))},a={alwaysAllowAdministrators:!1,evaluations:n.flatMap(i)};return{data:(await this.config.request({method:"POST",url:`${w(this.config,e)}/${encodeURIComponent(t)}/_apis/security/permissionevaluationbatch?api-version=7.0`,body:JSON.stringify(a),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(i=>({...i,permissions:o.data[`${i.projectId}/${i.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,i=[{op:"replace",path:"/fields/System.Tags",value:n.map(u=>u.name).join(";")}];if(!(await this.updateIssue(t,i,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(i=>({color:null,description:null,id:i.id,name:i.name,url:i.url}))}}};var q=(r,s={})=>h(s.token||r.token,s.isPAT||r.isPAT);var C="https://api.bitbucket.org/2.0",Lr={OPEN:"OPEN",MERGED:"MERGED",DECLINED:"CLOSED"},ge=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}),$t=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},Ut=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}),Je=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:ge(t.user),state:n}})??[];return{id:s.toString(),title:r.title,description:r.description,number:s,state:Lr[r.state],isDraft:!1,commentCount:r.comment_count,upvoteCount:null,author:ge(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:$t(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:$t(r.source.repository)},mergeableState:"MERGEABLE",permissions:null}},Dr=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}}},V=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:`${C}/user`,headers:q(this.config,e)});return{data:ge(t.body)}}async getUserForCommit(s,e={}){let n=(await this.config.request({url:`${C}/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:`${C}/repositories/${s.namespace}/${s.name}`,headers:q(this.config,e)});return{data:Ut(t.body)}}async getRepos(s,e={}){let t=[],n=[];return await Promise.all(s.map(async o=>{try{let i=await this.getRepo(o,e);t.push(i.data)}catch(i){n.push({input:o,error:i})}})),{data:t,errors:n}}async getReposForCurrentUser(s,e={}){let t=new URL(`${C}/repositories`);t.searchParams.set("role","member"),t.searchParams.set("pagelen",v.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,i=null;return n.body.next&&(i=new URL(n.body.next).searchParams.get("after")),{pageInfo:{hasNextPage:o,endCursor:i},data:n.body.values.map(Ut)}}async getBranches(s,e={}){let t=new URL(`${C}/repositories/${s.repo.namespace}/${s.repo.name}/refs/branches`);t.searchParams.set("page",s.page?.toString()||"1"),t.searchParams.set("pagelen",v.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(i=>{let a=new Date(i.target.date);return{name:i.name,commit:{oid:i.target.hash,authoredDate:a,committedDate:a}}})}}async getTags(s,e={}){let t=new URL(`${C}/repositories/${s.repo.namespace}/${s.repo.name}/refs/tags`);t.searchParams.set("pagelen",v.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,i=null;return n.body.next&&(i=new URL(n.body.next).searchParams.get("page")),{pageInfo:{hasNextPage:o,endCursor:i},data:n.body.values.map(a=>{let u=new Date(a.target.date);return{name:a.name,commit:{oid:a.target.hash,authoredDate:u,committedDate:u}}})}}async getWorkspacesForUser(s,e={}){let t=new URL(`${C}/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(i=>({id:i.workspace.uuid,slug:i.workspace.slug,name:i.workspace.name}))}}async getPullRequestsForUserAndWorkspace(s,e={}){let t=new URL(`${C}/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 i=`state = "open" AND (${s.repos.map(a=>`source.repository.full_name = "${a.namespace}/${a.name}"`).join(" OR ")})`;t.searchParams.set("q",i)}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(Je)}}async getPullRequestsForRepoBase(s,e={}){let t=new URL(`${C}/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(i=>{t.push(Je(i))});let o=!!n.body.next;return{pageInfo:{hasNextPage:o,nextPage:o?n.body.page+1:null},data:t}}async getPullRequestsForRepos(s,e={}){let t=[];return await Promise.all(s.repos.map(async n=>{try{(await this.getPullRequestsForRepoBase({repo:n,...s},e)).body.values.forEach(i=>{t.push(Je(i))})}catch(o){if(o.statusCode!==404&&o.statusCode!==401)throw o}})),{data:t}}async getAccountsForWorkspace(s,e={}){let t=new URL(`${C}/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(i=>ge(i.user))}}async getReposPermissionsForCurrentUser(s,e={}){let t=new URL(`${C}/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((i,a)=>({...i,[a.repository.uuid]:Dr(a.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:`${C}/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 i={merge_strategy:o,type:"pullrequest"};if(!(await this.config.request({method:"POST",url:`${C}/repositories/${t.repository.owner.login}/${t.repository.name}/pullrequests/${t.id}/merge`,body:JSON.stringify(i),headers:{...q(this.config,e),"Content-Type":"application/json"}})).body.title)throw new Error("Could not merge pull request")}async setPullRequestReviewers(s,e={}){let{pullRequest:t,reviewers:n}=s,o={reviewers:n.map(a=>{if(a.username)throw new Error('Bitbucket reviewer requires "username" for this function.');return{username:a.username}})};if(!(await this.config.request({method:"PUT",url:`${C}/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 At=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}},me=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 i=r.fromRef.repository.links.clone.find(u=>u.name==="ssh")?.href??null,a=r.fromRef.repository.links.clone.find(u=>u.name==="https")?.href??null;return a||(a=r.fromRef.repository.links.clone.find(u=>u.name==="http")?.href??null),{id:r.id.toString(),number:r.id,title:r.title,description:r.description,url:r.links.self[0].href,state: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:a&&i?{cloneUrlHTTPS:a,cloneUrlSSH:i}:null},headCommit:null,mergeableState:"MERGEABLE",permissions:null,version:r.version}},Gt=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}),K=class extends D{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,i=n?parseInt(n,10):null,a=decodeURIComponent(o),l=(await this.config.request({url:`${this.getBaseUrl(e)}/users?filter=${o}&avatarSize=64`,headers:this.getRequestHeaders(e)})).body.values.find(({emailAddress:p,id:d,name:c,slug:g})=>i?i===d:a===c||a===p||a===g);if(!l)throw new Error("Could not find current Bitbucket Server user");return{data: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:Gt(t.body)}}async getRepos(s,e={}){let t=[],n=[];return await Promise.all(s.map(async o=>{try{let i=await this.getRepo(o,e);t.push(i.data)}catch(i){n.push({input:o,error:i})}})),{data:t,errors:n}}async getReposForCurrentUser(s,e={}){let t=s.page??0,n=await this.config.request({url:`${this.getBaseUrl(e)}/repos?start=${t}`,headers:this.getRequestHeaders(e)});return{pageInfo:{hasNextPage:!n.body.isLastPage,nextPage:n.body.nextPageStart},data:n.body.values.map(Gt)}}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:At(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(i=>{if(s.authorLogin&&i.author.user.name!==s.authorLogin)return null;t.push(me(i))});let o=n.body.values.length!==0;return{pageInfo:{hasNextPage:o,nextPage:o?n.body.start+n.body.values.length:null},data:t}}async getPullRequestsForRepos(s,e={}){let t=[];return await Promise.all(s.repos.map(async n=>{try{(await this.getPullRequestsForRepoBase({repo:n,...s},e)).body.values.forEach(i=>{if(s.authorLogin&&i.author.user.name!==s.authorLogin)return null;t.push(me(i))})}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(me)}}async closePullRequest(s,e={}){let{pullRequest:t}=s;if(t.version===void 0)throw new Error('Bitbucket Server requires "version" for this function.');if(!(await this.config.request({method:"POST",url:`${this.getBaseUrl(e)}/projects/${t.repository.owner.login}/repos/${t.repository.name}/pull-requests/${t.id}/decline`,body:JSON.stringify({version:t.version}),headers:{...this.getRequestHeaders(e),"Content-Type":"application/json"}})).body.title)throw new Error("Could not close pull request")}async mergePullRequest(s,e={}){let{pullRequest:t,mergeStrategyId:n}=s;if(s.mergeStrategy)throw new Error('Bitbucket Server uses "mergeStrategyId" instead of "mergeStrategy".');if(t.version===void 0)throw new Error('Bitbucket Server requires "version" for this function.');if(!(await this.config.request({method:"POST",url:`${this.getBaseUrl(e)}/projects/${t.repository.owner.login}/repos/${t.repository.name}/pull-requests/${t.id}/merge`,body:JSON.stringify({strategyId:n,version:t.version}),headers:{...this.getRequestHeaders(e),"Content-Type":"application/json"}})).body.title)throw new Error("Could not merge pull request")}async getMergeStrategies(s={}){let e=await this.config.request({url:`${this.getBaseUrl(s)}/admin/pull-requests/git`,headers:{...this.getRequestHeaders(s),"Content-Type":"application/json"}});return{data:{defaultStrategy:e.body.mergeConfig.defaultStrategy,strategies:e.body.mergeConfig.strategies}}}async setPullRequestReviewers(s,e={}){let{pullRequest:t,reviewers:n}=s;if(t.version===void 0)throw new Error('Bitbucket Server requires "version" for this function.');let o={reviewers:n.map(a=>{if(a.username)throw new Error('Bitbucket Server reviewer requires "username" for this function.');return{user:{name:a.username}}}),version:t.version};if(!(await this.config.request({method:"PUT",url:`${this.getBaseUrl(e)}/projects/${t.repository.owner.login}/repos/${t.repository.name}/pull-requests/${t.id}`,body:JSON.stringify(o),headers:{...this.getRequestHeaders(e),"Content-Type":"application/json"}})).body.title)throw new Error("Could not set pull request reviewers")}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(i=>oe(i.user))}}};var Ft=require("js-base64");var he=(e=>(e.Open="OPEN",e.Closed="CLOSED",e))(he||{});var f=class extends Error{constructor(e,t){let n=t?.map(i=>`'${i.message}'`).join(", "),o=n?`${e}: ${n}`:e;super(o);this.graphQLErrors=t??[]}};var $r={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]},Tt=15,Ot=100,L=r=>!!r,O=(r,s)=>{let e=$r[s];for(let t=0;t<3;t++){if(r[t]>e[t])return!0;if(r[t]<e[t])return!1}return!0},Re="https://api.github.com",Ur=`${Re}/graphql`,Ie=`
|
|
2
2
|
description
|
|
3
3
|
dueOn
|
|
4
4
|
id
|
|
@@ -6,7 +6,7 @@ number
|
|
|
6
6
|
state
|
|
7
7
|
title
|
|
8
8
|
url
|
|
9
|
-
`,
|
|
9
|
+
`,Ar=`
|
|
10
10
|
... on CheckRun {
|
|
11
11
|
completedAt
|
|
12
12
|
conclusion
|
|
@@ -15,12 +15,12 @@ url
|
|
|
15
15
|
permalink
|
|
16
16
|
startedAt
|
|
17
17
|
}
|
|
18
|
-
`,
|
|
18
|
+
`,fe=/\/api\/v\d+$/,be=`
|
|
19
19
|
color
|
|
20
20
|
description
|
|
21
21
|
id
|
|
22
22
|
name
|
|
23
|
-
`,
|
|
23
|
+
`,xt=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.")},Gr=(r,s)=>{let e=s.baseUrl||r.baseUrl;return e?(e=e.replace(/\/$/,""),xt(e),fe.test(e)&&(e=e.replace(fe,"")),`${e}/api/graphql`):Ur},X=(r,s)=>{let e=s.baseUrl||r.baseUrl;return e?(e=e.replace(/\/$/,""),xt(e),fe.test(e)&&(e=e.replace(fe,"")),`${e}/api/v3`):Re},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:Gr(r,e),method:"POST",headers:t,body:JSON.stringify(s)})},Tr={user:!0,"user:email":!0,"read:user":!0},x=r=>r.some(s=>Tr[s]),$=(r=!1,s=!1,e)=>`
|
|
24
24
|
__typename
|
|
25
25
|
${Q(e,["graphQLId"],"id")}
|
|
26
26
|
${Q(e,["id"],"databaseId")}
|
|
@@ -29,48 +29,49 @@ ${Q(e,["name","username"],"login")}
|
|
|
29
29
|
${s?Q(e,["email"],"email"):""}
|
|
30
30
|
${Q(e,["avatarUrl"],`avatarUrl${r?"(size: $avatarSize)":""}`)}
|
|
31
31
|
${Q(e,["url"],"url")}
|
|
32
|
-
`,
|
|
32
|
+
`,Or=(r=!1)=>`
|
|
33
33
|
latestReviews(first: 100) {
|
|
34
34
|
nodes {
|
|
35
35
|
author {
|
|
36
36
|
... on User {
|
|
37
|
-
${
|
|
37
|
+
${$(!1,r)}
|
|
38
38
|
}
|
|
39
39
|
... on EnterpriseUserAccount {
|
|
40
|
-
${
|
|
40
|
+
${Ve(!1)}
|
|
41
41
|
}
|
|
42
42
|
}
|
|
43
43
|
state
|
|
44
44
|
}
|
|
45
45
|
}
|
|
46
|
-
`,
|
|
46
|
+
`,kt=(r=!1)=>`
|
|
47
47
|
__typename
|
|
48
48
|
id
|
|
49
49
|
databaseId
|
|
50
50
|
login
|
|
51
51
|
avatarUrl${r?"(size: $avatarSize)":""}
|
|
52
52
|
url
|
|
53
|
-
`,
|
|
53
|
+
`,Ve=(r=!1)=>`
|
|
54
54
|
__typename
|
|
55
55
|
id
|
|
56
56
|
login
|
|
57
57
|
avatarUrl${r?"(size: $avatarSize)":""}
|
|
58
58
|
url
|
|
59
|
-
`,
|
|
59
|
+
`,ye=(r,s=!1,e)=>`
|
|
60
60
|
id
|
|
61
61
|
${!e||O(e,"PR_FULL_DATABASE_ID")?"fullDatabaseId":"databaseId"}
|
|
62
62
|
number
|
|
63
63
|
title
|
|
64
|
+
body
|
|
64
65
|
state
|
|
65
66
|
author {
|
|
66
67
|
... on User {
|
|
67
|
-
${
|
|
68
|
+
${$(!1,s)}
|
|
68
69
|
}
|
|
69
70
|
... on Bot {
|
|
70
|
-
${
|
|
71
|
+
${kt(!1)}
|
|
71
72
|
}
|
|
72
73
|
... on EnterpriseUserAccount {
|
|
73
|
-
${
|
|
74
|
+
${Ve(!1)}
|
|
74
75
|
}
|
|
75
76
|
}
|
|
76
77
|
commits(last: 1) {
|
|
@@ -83,7 +84,7 @@ commits(last: 1) {
|
|
|
83
84
|
contexts(first: 100) {
|
|
84
85
|
totalCount
|
|
85
86
|
nodes {
|
|
86
|
-
${!e||O(e,"CHECK_RUN")?
|
|
87
|
+
${!e||O(e,"CHECK_RUN")?Ar:""}
|
|
87
88
|
... on StatusContext {
|
|
88
89
|
context
|
|
89
90
|
createdAt
|
|
@@ -145,7 +146,7 @@ closedAt
|
|
|
145
146
|
mergedAt
|
|
146
147
|
assignees(first: 100) {
|
|
147
148
|
nodes {
|
|
148
|
-
${
|
|
149
|
+
${$(!1,s)}
|
|
149
150
|
}
|
|
150
151
|
}
|
|
151
152
|
reviewRequests(first: 100) {
|
|
@@ -153,39 +154,39 @@ reviewRequests(first: 100) {
|
|
|
153
154
|
${!e||O(e,"AS_CODE_OWNER")?"asCodeOwner":""}
|
|
154
155
|
requestedReviewer {
|
|
155
156
|
... on User {
|
|
156
|
-
${
|
|
157
|
+
${$(!1,s)}
|
|
157
158
|
}
|
|
158
159
|
}
|
|
159
160
|
}
|
|
160
161
|
}
|
|
161
|
-
${!e||O(e,"LATEST_REVIEWS")?
|
|
162
|
+
${!e||O(e,"LATEST_REVIEWS")?Or(s):""}
|
|
162
163
|
additions
|
|
163
164
|
deletions
|
|
164
165
|
changedFiles
|
|
165
166
|
mergeable
|
|
166
167
|
mergeStateStatus
|
|
167
168
|
milestone {
|
|
168
|
-
${
|
|
169
|
+
${Ie}
|
|
169
170
|
}
|
|
170
171
|
labels(first: 100) {
|
|
171
172
|
nodes {
|
|
172
|
-
${
|
|
173
|
+
${be}
|
|
173
174
|
}
|
|
174
175
|
}
|
|
175
176
|
${!e||O(e,"VIEWER_CAN_MERGE_AS_ADMIN")?"viewerCanMergeAsAdmin":""}
|
|
176
|
-
`,
|
|
177
|
+
`,xr=(r=!1,s)=>`
|
|
177
178
|
id
|
|
178
179
|
${!s||O(s,"ISSUE_FULL_DATABASE_ID")?"fullDatabaseId":"databaseId"}
|
|
179
180
|
title
|
|
180
181
|
author {
|
|
181
182
|
... on User {
|
|
182
|
-
${
|
|
183
|
+
${$(!1,r)}
|
|
183
184
|
}
|
|
184
185
|
... on Bot {
|
|
185
|
-
${
|
|
186
|
+
${kt(!1)}
|
|
186
187
|
}
|
|
187
188
|
... on EnterpriseUserAccount {
|
|
188
|
-
${
|
|
189
|
+
${Ve(!1)}
|
|
189
190
|
}
|
|
190
191
|
}
|
|
191
192
|
closedAt
|
|
@@ -209,19 +210,19 @@ comments {
|
|
|
209
210
|
}
|
|
210
211
|
assignees(first: 100) {
|
|
211
212
|
nodes {
|
|
212
|
-
${
|
|
213
|
+
${$(!1,r)}
|
|
213
214
|
}
|
|
214
215
|
}
|
|
215
216
|
state
|
|
216
217
|
milestone {
|
|
217
|
-
${
|
|
218
|
+
${Ie}
|
|
218
219
|
}
|
|
219
220
|
labels(first: 100) {
|
|
220
221
|
nodes {
|
|
221
|
-
${
|
|
222
|
+
${be}
|
|
222
223
|
}
|
|
223
224
|
}
|
|
224
|
-
`,
|
|
225
|
+
`,kr={"-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"},Nr=new RegExp('(([^\\s]+:)?\\"(?:[^\\"\\\\]|\\\\.)*\\"?)|([^\\"\\s]+)',"g"),Ke=r=>{let s=[];return(r.match(Nr)??[]).forEach(t=>{if(t.includes(":")&&t!="is:closed"){let n=t.split(":")[0];kr[n]&&s.push(t)}}),s},Xe=(r,s,e,t)=>{let n=r==="issue";return{query:`
|
|
225
226
|
query SearchIssuesOrPullRequests($query: String! $after: String) {
|
|
226
227
|
search(type:ISSUE query:$query first: ${t.maxPageSize} after:$after) {
|
|
227
228
|
pageInfo {
|
|
@@ -230,18 +231,18 @@ query SearchIssuesOrPullRequests($query: String! $after: String) {
|
|
|
230
231
|
}
|
|
231
232
|
nodes {
|
|
232
233
|
... on ${n?"Issue":"PullRequest"} {
|
|
233
|
-
${n?
|
|
234
|
+
${n?xr(t.supportsEmail,t.enterpriseVersion??null):ye(t.supportsDrafts??!1,t.supportsEmail,t.enterpriseVersion??null)}
|
|
234
235
|
}
|
|
235
236
|
}
|
|
236
237
|
}
|
|
237
|
-
}`,variables:{query:`is:${r} is:open ${t.includeFromArchivedRepos?"":"archived:false"} ${s}`,after:e}}},
|
|
238
|
+
}`,variables:{query:`is:${r} is:open ${t.includeFromArchivedRepos?"":"archived:false"} ${s}`,after:e}}},_r="Field 'isDraft' doesn't exist on type 'PullRequest'",Pe=(r=[])=>r.some(s=>s?.message===_r),Fr=/@@ -(\d+)(?:,\d+ | )\+(\d+)(?:,\d+ | )@@(?:\\n)?/,Qr=`
|
|
238
239
|
\
|
|
239
|
-
+`,
|
|
240
|
+
+`,Nt=(r,s,e,t)=>{let n=Fr.exec(r);if(!n||!n[0]||!n[1])return[];let o=parseInt(n[1],10),i=parseInt(n[2],10),a=r.replace(Qr,`
|
|
240
241
|
+`).split(`
|
|
241
|
-
`).slice(1),u=o-1,l=
|
|
242
|
+
`).slice(1),u=o-1,l=i-1,p=a.map(g=>{let m,b;switch(g[0]){case"-":{m="DELETED",u+=1,b=`${g.slice(1)}
|
|
242
243
|
`;break}case"+":{m="ADDED",l+=1,b=`${g.slice(1)}
|
|
243
244
|
`;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&&t!==null&&d<c){let g=0,m=p.length,b=t==="LEFT"?"oldLineNumber":"newLineNumber";for(let I=0;I<p.length;I++){let
|
|
245
|
+
`}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 z=p[I][b];z===d?g=I:z===c&&(m=I)}p=p.slice(g,m+1)}return p};var Ze=`
|
|
245
246
|
id
|
|
246
247
|
databaseId
|
|
247
248
|
owner {
|
|
@@ -254,18 +255,18 @@ defaultBranchRef {
|
|
|
254
255
|
name
|
|
255
256
|
}
|
|
256
257
|
viewerPermission
|
|
257
|
-
`,
|
|
258
|
+
`,tt={__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"},jr={APPROVED:"APPROVED",CHANGES_REQUESTED:"CHANGES_REQUESTED",COMMENTED:"COMMENTED",REVIEW_REQUESTED:"REVIEW_REQUESTED"},Br={MERGEABLE:"MERGEABLE",CONFLICTING:"CONFLICTS",UNKNOWN:"UNKNOWN"},zr={BEHIND:"BEHIND",BLOCKED:"BLOCKED",UNKNOWN:"UNKNOWN_AND_BLOCKED",UNSTABLE:"UNSTABLE",CLEAN:null,DIRTY:null,DRAFT:null,HAS_HOOKS:null},Mr={OPEN:"OPEN",CLOSED:"CLOSED"},Hr=["ADMIN","MAINTAIN","TRIAGE","WRITE"],rt=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"}),Ye=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)}),Jr=r=>({canCreateWebhook:r.admin,canPush:r.admin||r.maintain||r.push,isAdmin:r.admin}),_t=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:Jr(r.permissions)}),Vr=r=>({path:r.path,isDirectory:r.type==="tree"}),Kr={OPEN:"OPEN",CLOSED:"CLOSED",MERGED:"MERGED"},Xr={id:!0,graphQLId:!0,name:!0,username:!0,email:!0,avatarUrl:!0,url:!0},A=(r,s=Xr)=>{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},Zr=(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]},Yr=r=>({ERROR:"ERROR",EXPECTED:"PENDING",FAILURE:"FAILED",PENDING:"PENDING",SUCCESS:"SUCCESS"})[r],et=r=>{let s=null;r.author?s=r.author:s=tt;let e=(r.reviewRequests?.nodes||[]).filter(L).filter(i=>!i.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(i=>i.requestedReviewer&&"__typename"in i.requestedReviewer).map(i=>({reviewer:A(i.requestedReviewer),state:"REVIEW_REQUESTED"})).concat((r.latestReviews?.nodes||[]).filter(L).map(i=>{let a=tt;return i.author&&i.author.__typename&&(a=i.author),{reviewer:A(a),state:jr[i.state]}}));return{id:r.fullDatabaseId!==void 0?r.fullDatabaseId:r.databaseId.toString(),graphQLId:r.id,title:r.title,description:r.body,number:r.number,state:Kr[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(L)[0]?.commit.statusCheckRollup?.contexts.nodes?.filter(L).map(i=>"context"in i?{completedAt:null,description:i.description,name:i.context,state:Yr(i.state),startedAt:new Date(i.createdAt),stage:null,url:i.targetUrl}:{completedAt:i.completedAt?new Date(i.completedAt):null,description:null,name:i.name,state:Zr(i.status,i.conclusion),startedAt:i.startedAt?new Date(i.startedAt):null,stage:null,url:i.permalink})??[]},headRef:r.headRef?{name:r.headRef.name,oid:r.headRef.target?.oid??null}:null,baseRef:r.baseRef?{name:r.baseRef.name,oid:r.baseRef.target?.oid??null}:null,url:r.url,updatedDate:new Date(r.updatedAt),closedDate:r.closedAt?new Date(r.closedAt):null,mergedDate:r.mergedAt?new Date(r.mergedAt):null,assignees:r.assignees.nodes?r.assignees.nodes.filter(L).map(i=>A(i)):null,reviews:o,reviewDecision:G(o),additions:r.additions,deletions:r.deletions,fileCount:r.changedFiles,commitCount:r.commits.totalCount,mergeableState:zr[r.mergeStateStatus]??Br[r.mergeable],milestone:r.milestone?st(r.milestone):null,labels:r.labels?.nodes?.filter(L).map(rt)??[],permissions:{canMerge:Hr.includes(r.repository.viewerPermission),canMergeAndBypassProtections:r.viewerCanMergeAsAdmin??!1}}},es=r=>{let{comments:s,isOutdated:e,isResolved:t,line:n,startLine:o,diffSide:i,originalLine:a,originalStartLine:u,startDiffSide:l}=r,p=s.nodes?.[0];if(!p)return null;let{author:d,body:c,databaseId:g,fullDatabaseId:m,id:b,path:I,publishedAt:E,url:z}=p,Fe=n??a,ue=o??u,S=i??l;return{author:d?{avatarUrl:d.avatarUrl,email:null,name:d.login}:null,body:c,createdAt:E?new Date(E):null,diffLines:Nt(p.diffHunk,Fe,ue,S),id:m??g.toString(),isOutdated:e,isResolved:t,graphQLId:b,filename:I,replies:s.nodes?.filter(L).slice(1).map(ts)??[],url:z,line:Fe,startLine:ue,side:S}},ts=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}),rs=r=>{let s=null;return r.author?s=r.author:s=tt,{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:Mr[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(L).map(e=>A(e))??[],upvoteCount:r.reactions.totalCount,milestone:r.milestone?st(r.milestone):null,labels:r.labels?.nodes?.filter(L).map(rt)??[]}},st=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}),Z=class extends D{constructor(){super(...arguments);this._scopesCache={};this._enterpriseVersionsCache={}}async getScopes(e){let t=e.token||this.config.token;if(!t)return[];let n=this._scopesCache[t];if(!n){let i=(await R(this.config,{query:"query { rateLimit(dryRun: true) { __typename } }"},e)).headers["x-oauth-scopes"];n=i?i.split(", "):[],this._scopesCache[t]=n}return n}async getEnterpriseVersion(e){let t=e.baseUrl||this.config.baseUrl;if(!t)return null;let n=this._enterpriseVersionsCache[t];if(!n){let o=await this.config.request({url:`${X(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(i=>parseInt(i,10)),this._enterpriseVersionsCache[t]=n}return n}getEnterpriseAvatarUrlIfNeeded(e,t,n){let o=n.baseUrl||this.config.baseUrl;return!o||o.startsWith(Re)?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=Et(e.fields),o=await this.getScopes(t),i=await R(this.config,{query:`
|
|
258
259
|
query getCurrentUser {
|
|
259
260
|
viewer {
|
|
260
|
-
${
|
|
261
|
+
${$(!1,x(o),n)}
|
|
261
262
|
}
|
|
262
263
|
}
|
|
263
|
-
`},t),i
|
|
264
|
+
`},t),a=i.body.data?.viewer;if(!a)throw new f("Current user not found.",i.body.errors);return{data:A(a,n)}}async getAccountsForRepo(e,t={}){let n=await this.getScopes(t),{repo:{namespace:o,name:i},cursor:a}=e,u=await R(this.config,{query:`
|
|
264
265
|
query getAccountsForRepo($owner: String!, $name: String! $cursor: String, $first: Int!) {
|
|
265
266
|
repository(owner: $owner, name: $name) {
|
|
266
267
|
assignableUsers(first: $first, after: $cursor) {
|
|
267
268
|
nodes {
|
|
268
|
-
${
|
|
269
|
+
${$(!1,x(n))}
|
|
269
270
|
}
|
|
270
271
|
pageInfo {
|
|
271
272
|
endCursor
|
|
@@ -274,7 +275,7 @@ query getAccountsForRepo($owner: String!, $name: String! $cursor: String, $first
|
|
|
274
275
|
}
|
|
275
276
|
}
|
|
276
277
|
}
|
|
277
|
-
`,variables:{owner:o,name:
|
|
278
|
+
`,variables:{owner:o,name:i,cursor:a,first:v}},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
279
|
query getUserForCommit(
|
|
279
280
|
$owner: String!
|
|
280
281
|
$name: String!
|
|
@@ -293,7 +294,7 @@ query getUserForCommit(
|
|
|
293
294
|
}
|
|
294
295
|
}
|
|
295
296
|
}
|
|
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
|
|
297
|
+
`,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 i=o.object?.author;if(!i)throw new f("Commit not found.",n.body.errors);return{data:{name:i.name,email:i.email,avatarUrl:this.getEnterpriseAvatarUrlIfNeeded(i.avatarUrl,i.email,t)}}}async createCommit(e,t={}){let{commitMessage:n,deletedFiles:o,newOrModifiedFiles:i,repo:a,target:u}=e,l=await R(this.config,{query:`
|
|
297
298
|
mutation createCommitOnBranch(
|
|
298
299
|
$branchName: String!,
|
|
299
300
|
$expectedHeadOid: GitObjectID!,
|
|
@@ -320,23 +321,23 @@ mutation createCommitOnBranch(
|
|
|
320
321
|
}
|
|
321
322
|
}
|
|
322
323
|
}
|
|
323
|
-
`,variables:{branchName:u.name,expectedHeadOid:u.oid,fileChanges:{additions:Object.entries(
|
|
324
|
+
`,variables:{branchName:u.name,expectedHeadOid:u.oid,fileChanges:{additions:Object.entries(i).map(([p,d])=>({contents:Ft.Base64.encode(d),path:p})),deletions:o.map(p=>({path:p}))},message:{body:n.description,headline:n.summary},repositoryNameWithOwner:`${a.namespace}/${a.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
325
|
query getAccountForEmail($query: String! $avatarSize: Int) {
|
|
325
326
|
search(query: $query, type: USER, first: 1) {
|
|
326
327
|
nodes {
|
|
327
328
|
... on User {
|
|
328
|
-
${
|
|
329
|
+
${$(!0,x(n))}
|
|
329
330
|
}
|
|
330
331
|
}
|
|
331
332
|
}
|
|
332
333
|
}
|
|
333
|
-
`,variables:{query:`in:email ${e.email}`,avatarSize:e.avatarSize}},t),
|
|
334
|
+
`,variables:{query:`in:email ${e.email}`,avatarSize:e.avatarSize}},t),i=o.body.data?.search?.nodes?.[0];if(!i)throw new f("Could not find user via email",o.body.errors);return{data:A({...i,avatarUrl:this.getEnterpriseAvatarUrlIfNeeded(i.avatarUrl,i.email,t)})}}async getAccountForUsername(e,t={}){let n=await this.getScopes(t),o=await R(this.config,{query:`
|
|
334
335
|
query getUserForUsername($login: String! $avatarSize: Int) {
|
|
335
336
|
user(login: $login) {
|
|
336
|
-
${
|
|
337
|
+
${$(!0,x(n))}
|
|
337
338
|
}
|
|
338
339
|
}
|
|
339
|
-
`,variables:{login:e.username,avatarSize:e.avatarSize}},t),
|
|
340
|
+
`,variables:{login:e.username,avatarSize:e.avatarSize}},t),i=o.body.data?.user;if(!i)throw new f("Could not find user via username",o.body.errors);return{data:A({...i,avatarUrl:this.getEnterpriseAvatarUrlIfNeeded(i.avatarUrl,i.email,t)})}}async getOrgsForCurrentUser(e={},t={}){let n=await R(this.config,{query:`
|
|
340
341
|
query getOrgsForCurrentUser($cursor: String, $first: Int!) {
|
|
341
342
|
viewer {
|
|
342
343
|
organizations(first: $first after: $cursor) {
|
|
@@ -355,7 +356,7 @@ query getOrgsForCurrentUser($cursor: String, $first: Int!) {
|
|
|
355
356
|
}
|
|
356
357
|
}
|
|
357
358
|
}
|
|
358
|
-
`,variables:{cursor:e.cursor,first:
|
|
359
|
+
`,variables:{cursor:e.cursor,first:v}},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(i=>({id:i.databaseId.toString(),graphQLId:i.id,username:i.login,name:i.name||null,email:i.email||null,avatarUrl:i.avatarUrl}))}}async getOrgMembers(e,t={}){let n=await R(this.config,{query:`
|
|
359
360
|
query getOrgMember($cursor: String, $first: Int!, $login: String!) {
|
|
360
361
|
viewer {
|
|
361
362
|
organization(login: $login) {
|
|
@@ -365,28 +366,28 @@ query getOrgMember($cursor: String, $first: Int!, $login: String!) {
|
|
|
365
366
|
hasNextPage
|
|
366
367
|
}
|
|
367
368
|
nodes {
|
|
368
|
-
${
|
|
369
|
+
${$(!1,!0)}
|
|
369
370
|
}
|
|
370
371
|
}
|
|
371
372
|
}
|
|
372
373
|
}
|
|
373
374
|
}
|
|
374
|
-
`,variables:{cursor:e.cursor,first:
|
|
375
|
+
`,variables:{cursor:e.cursor,first:v,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(i=>A({...i,avatarUrl:this.getEnterpriseAvatarUrlIfNeeded(i.avatarUrl,i.email,t)}))}}async getRepo(e,t={}){let n=await R(this.config,{query:`
|
|
375
376
|
query getRepo($owner: String!, $name: String!) {
|
|
376
377
|
repository(owner: $owner, name: $name) {
|
|
377
|
-
${
|
|
378
|
+
${Ze}
|
|
378
379
|
}
|
|
379
380
|
}
|
|
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:
|
|
381
|
+
`,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:Ye(n.body.data.repository)}}async getRepos(e,t={}){let n=e.map(({namespace:u,name:l},p)=>`
|
|
381
382
|
getRepo_${p}: repository(owner: "${u}", name: "${l}") {
|
|
382
|
-
${
|
|
383
|
+
${Ze}
|
|
383
384
|
}
|
|
384
385
|
`).join(`
|
|
385
386
|
`),o=await R(this.config,{query:`
|
|
386
387
|
query batchGetRepos {
|
|
387
388
|
${n}
|
|
388
389
|
}
|
|
389
|
-
`},t);if(!o.body.data)throw new f("Could not fetch repos",o.body.errors);let
|
|
390
|
+
`},t);if(!o.body.data)throw new f("Could not fetch repos",o.body.errors);let i=[],a=[];return e.forEach((u,l)=>{let p=o.body.data[`getRepo_${l}`];p?i.push(Ye(p)):a.push({input:u})}),{data:i,errors:a}}async fetchMultipleRESTPages(e,t,n,o){let i=[];for(let d=0;d<t;d++)i.push(n(e+d));let a=await Promise.all(i),u=[];for(let d of a){if(!d.body)throw new Error(d.statusText||"Unknown error");u=u.concat(d.body.map(c=>o(c)))}let l=a.every(d=>d.body.length===100),p=e+t;return{data:u,pageInfo:{hasNextPage:l,nextPage:l?p:null}}}async getReposForCurrentUser(e,t={}){if(e.simultaneousPagesToFetch&&e.simultaneousPagesToFetch>40)throw new Error("The argument 'simultaneousPagesToFetch' cannot exceed 40 for 'getReposForCurrentUser'");let n=new URLSearchParams;n.append("per_page","100"),e.affiliations&&n.append("affiliation",e.affiliations.join(","));let o=i=>this.config.request({url:`${X(this.config,t)}/user/repos?${n.toString()}&page=${i}`,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,_t)}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:`${X(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,_t)}async getReposForUsernames(e,t={}){if(!e.usernames.length)return{pageInfo:{endCursor:null,hasNextPage:!1},data:[]};let n=await R(this.config,{query:`
|
|
390
391
|
query getReposForUsernames($query: String!, $cursor: String, $first: Int!) {
|
|
391
392
|
search(query: $query, type: REPOSITORY, first: $first, after: $cursor) {
|
|
392
393
|
pageInfo {
|
|
@@ -395,12 +396,12 @@ query getReposForUsernames($query: String!, $cursor: String, $first: Int!) {
|
|
|
395
396
|
}
|
|
396
397
|
nodes {
|
|
397
398
|
... on Repository {
|
|
398
|
-
${
|
|
399
|
+
${Ze}
|
|
399
400
|
}
|
|
400
401
|
}
|
|
401
402
|
}
|
|
402
403
|
}
|
|
403
|
-
`,variables:{query:`fork:true ${e.usernames.map(
|
|
404
|
+
`,variables:{query:`fork:true ${e.usernames.map(i=>`user:${i}`).join(" ")}`,cursor:e.cursor,first:v}},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(Ye)}}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
405
|
query getRefs($owner: String!, $name: String!, $refPrefix: String!, $cursor: String, $first: Int!) {
|
|
405
406
|
repository(owner: $owner, name: $name) {
|
|
406
407
|
refs(refPrefix: $refPrefix first: $first after: $cursor) {
|
|
@@ -421,7 +422,7 @@ query getRefs($owner: String!, $name: String!, $refPrefix: String!, $cursor: Str
|
|
|
421
422
|
}
|
|
422
423
|
}
|
|
423
424
|
}
|
|
424
|
-
`,variables:{owner:t.repo.namespace,name:t.repo.name,refPrefix:e,cursor:t.cursor,first:
|
|
425
|
+
`,variables:{owner:t.repo.namespace,name:t.repo.name,refPrefix:e,cursor:t.cursor,first:v}},n),i=o.body.data?.repository;if(!i)throw new f("Ref repository not found.",o.body.errors);let a=i.refs;return a?{pageInfo:a.pageInfo,data:(a.nodes||[]).map(u=>{let l=u.target?.oid?u.target:null;return{name:u.name,commit:l?{oid:l.oid,authoredDate:new Date(l.authoredDate),committedDate:new Date(l.committedDate)}:null}})}:{pageInfo:{endCursor:null,hasNextPage:!1},data:[]}}async getBranches(e,t={}){return this.getRefs("refs/heads/",e,t)}async getTags(e,t={}){return this.getRefs("refs/tags/",e,t)}async getBlame(e,t={}){let n=await R(this.config,{query:`
|
|
425
426
|
query getBlame($owner: String!, $name: String!, $ref: String!, $path: String!) {
|
|
426
427
|
repository(owner: $owner, name: $name) {
|
|
427
428
|
object(expression: $ref) {
|
|
@@ -460,7 +461,7 @@ query getBlame($owner: String!, $name: String!, $ref: String!, $path: String!) {
|
|
|
460
461
|
}
|
|
461
462
|
}
|
|
462
463
|
}
|
|
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
|
|
464
|
+
`,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 i=o.object;if(!i||!("blame"in i))throw new f("Ref not found.",n.body.errors);if(i.blame.ranges.length===0)throw new f("File not found.",n.body.errors);return{data:{ranges:i.blame.ranges.map(a=>({startingLine:a.startingLine,endingLine:a.endingLine,commit:{oid:a.commit.oid,parentOids:a.commit.parents.nodes?.map(u=>u.oid)||[],authoredDate:new Date(a.commit.authoredDate),author:a.commit.author?{name:a.commit.author.name,email:a.commit.author.email,avatarUrl:a.commit.author.avatarUrl}:null,committedDate:new Date(a.commit.committedDate),committer:a.commit.committer?{name:a.commit.committer.name,email:a.commit.committer.email,avatarUrl:a.commit.committer.avatarUrl}:null,message:a.commit.message,fileCount:a.commit.changedFilesIfAvailable,additions:a.commit.additions,deletions:a.commit.deletions}}))}}}async getFileContents(e,t={}){let n=await this.config.request({url:`${X(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),i=x(o),a=p=>{let d=p&&typeof e.isDraft=="boolean"?`${e.query} draft:${e.isDraft}`:e.query;return Xe("pr",d,e.cursor,{maxPageSize:e.maxPageSize??Tt,supportsEmail:i,supportsDrafts:p,enterpriseVersion:n,includeFromArchivedRepos:e.includeFromArchivedRepos})},u=await R(this.config,a(!0),t);u.body.errors&&Pe(u.body.errors)&&(this.config.baseUrl||t.baseUrl)&&(u=await R(this.config,a(!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(L).map(et)||[]}}async searchIssues(e,t={}){let n=await this.getEnterpriseVersion(t),o=await this.getScopes(t),i=x(o),a=await R(this.config,Xe("issue",e.query,e.cursor,{supportsEmail:i,includeFromArchivedRepos:e.includeFromArchivedRepos,maxPageSize:e.maxPageSize??Ot,enterpriseVersion:n}),t),{data:u}=a.body;if(!u)throw new f("Could not search issues",a.body.errors);return{pageInfo:{hasNextPage:u.search.pageInfo.hasNextPage,endCursor:u.search.pageInfo.endCursor},data:u.search.nodes?.filter(L).map(rs)||[]}}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:i,repos:a,reviewRequestedLogin:u,startQuery:l,mentionLogin:p,labelNames:d,maxPageSize:c}=e,g=Ke(l||"");return a.forEach(m=>{g.push(`repo:${m.namespace}/${m.name}`)}),n&&n.forEach(m=>{g.push(`assignee:${m}`)}),o&&g.push(`updated:<${o}`),i&&g.push(`author:${i}`),u&&g.push(`review-requested:${u}`),p&&g.push(`mentions:${p}`),d&&d.forEach(m=>{g.push(`label:"${m}"`)}),this.searchPullRequests({query:`sort:updated ${g.join(" ")}`,isDraft:e.isDraft,cursor:e.cursor,includeFromArchivedRepos:e.includeFromArchivedRepos,maxPageSize:c},t)}async getPullRequestForRepo(e,t={}){let n=await this.getEnterpriseVersion(t),o=await this.getScopes(t),i=x(o),a=d=>({query:`query getPullRequest(
|
|
464
465
|
$owner: String!
|
|
465
466
|
$name: String!
|
|
466
467
|
$number: Int!
|
|
@@ -470,24 +471,24 @@ query getBlame($owner: String!, $name: String!, $ref: String!, $path: String!) {
|
|
|
470
471
|
name: $name
|
|
471
472
|
) {
|
|
472
473
|
pullRequest(number: $number) {
|
|
473
|
-
${
|
|
474
|
+
${ye(d,i,n)}
|
|
474
475
|
}
|
|
475
476
|
}
|
|
476
|
-
}`,variables:{owner:e.repo.namespace,name:e.repo.name,number:e.number}}),u=await R(this.config,
|
|
477
|
+
}`,variables:{owner:e.repo.namespace,name:e.repo.name,number:e.number}}),u=await R(this.config,a(!0),t);u.body.errors&&Pe(u.body.errors)&&(this.config.baseUrl||t.baseUrl)&&(u=await R(this.config,a(!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?et(p):null}}async getPullRequestByGraphQLId(e,t={}){let n=await this.getEnterpriseVersion(t),o=await this.getScopes(t),i=x(o),a=d=>({query:`query getPullRequest(
|
|
477
478
|
$graphQLId: ID!
|
|
478
479
|
) {
|
|
479
480
|
node(id: $graphQLId) {
|
|
480
481
|
... on PullRequest {
|
|
481
|
-
${
|
|
482
|
+
${ye(d,i,n)}
|
|
482
483
|
}
|
|
483
484
|
}
|
|
484
|
-
}`,variables:{graphQLId:e.graphQLId}}),u=await R(this.config,
|
|
485
|
+
}`,variables:{graphQLId:e.graphQLId}}),u=await R(this.config,a(!0),t);u.body.errors&&Pe(u.body.errors)&&(this.config.baseUrl||t.baseUrl)&&(u=await R(this.config,a(!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?et(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
486
|
closePullRequest(input: { pullRequestId: $pullRequestGraphQLId }) {
|
|
486
487
|
pullRequest {
|
|
487
488
|
id
|
|
488
489
|
}
|
|
489
490
|
}
|
|
490
|
-
}`,
|
|
491
|
+
}`,i=await R(this.config,{query:`${o}`,variables:{pullRequestGraphQLId:n}},t);if(!i.body.data?.closePullRequest?.pullRequest?.id)throw new f("Could not close pull request",i.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 i;switch(o){case"MERGE_COMMIT":{i="MERGE";break}case"REBASE":{i="REBASE";break}case"SQUASH":{i="SQUASH";break}}let a=`mutation MergePullRequest(
|
|
491
492
|
$pullRequestGraphQLId: ID!,
|
|
492
493
|
$expectedSourceSha: GitObjectID!,
|
|
493
494
|
$mergeStrategy: PullRequestMergeMethod,
|
|
@@ -501,7 +502,7 @@ query getBlame($owner: String!, $name: String!, $ref: String!, $path: String!) {
|
|
|
501
502
|
id
|
|
502
503
|
}
|
|
503
504
|
}
|
|
504
|
-
}`,u=await R(this.config,{query:`${
|
|
505
|
+
}`,u=await R(this.config,{query:`${a}`,variables:{pullRequestGraphQLId:n.graphQLId,expectedSourceSha:n.headRef.oid,mergeStrategy:i}},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 i=`mutation ApprovePullRequest(
|
|
505
506
|
$pullRequestId: ID!,
|
|
506
507
|
$body: String
|
|
507
508
|
) {
|
|
@@ -514,7 +515,7 @@ query getBlame($owner: String!, $name: String!, $ref: String!, $path: String!) {
|
|
|
514
515
|
id
|
|
515
516
|
}
|
|
516
517
|
}
|
|
517
|
-
}`,
|
|
518
|
+
}`,a=await R(this.config,{query:i,variables:{pullRequestId:n.graphQLId,body:o||null}},t);if(!a.body.data?.addPullRequestReview?.pullRequestReview?.id)throw new f("Could not approve pull request",a.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 i=`mutation RequestPullRequestChanges(
|
|
518
519
|
$pullRequestId: ID!,
|
|
519
520
|
$body: String!
|
|
520
521
|
) {
|
|
@@ -527,7 +528,7 @@ query getBlame($owner: String!, $name: String!, $ref: String!, $path: String!) {
|
|
|
527
528
|
id
|
|
528
529
|
}
|
|
529
530
|
}
|
|
530
|
-
}`,
|
|
531
|
+
}`,a=await R(this.config,{query:i,variables:{pullRequestId:n.graphQLId,body:o}},t);if(!a.body.data?.addPullRequestReview?.pullRequestReview?.id)throw new f("Could not request pull request changes",a.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 i=`mutation CommentOnPullRequest(
|
|
531
532
|
$pullRequestId: ID!,
|
|
532
533
|
$body: String!
|
|
533
534
|
) {
|
|
@@ -540,13 +541,65 @@ query getBlame($owner: String!, $name: String!, $ref: String!, $path: String!) {
|
|
|
540
541
|
id
|
|
541
542
|
}
|
|
542
543
|
}
|
|
543
|
-
}`,
|
|
544
|
+
}`,a=await R(this.config,{query:i,variables:{pullRequestId:n.graphQLId,body:o}},t);if(!a.body.data?.addPullRequestReview?.pullRequestReview?.id)throw new f("Could not comment on pull request",a.body.errors)}async addCommentToPullRequest(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 adding a comment to a pull request.");let i=`mutation AddCommentToPullRequest(
|
|
545
|
+
$subjectId: ID!,
|
|
546
|
+
$body: String!
|
|
547
|
+
) {
|
|
548
|
+
addComment(input: {
|
|
549
|
+
subjectId: $subjectId,
|
|
550
|
+
body: $body
|
|
551
|
+
}) {
|
|
552
|
+
commentEdge {
|
|
553
|
+
node {
|
|
554
|
+
id
|
|
555
|
+
}
|
|
556
|
+
}
|
|
557
|
+
}
|
|
558
|
+
}`,a=await R(this.config,{query:i,variables:{subjectId:n.graphQLId,body:o}},t);if(!a.body.data?.addComment?.commentEdge?.node?.id)throw new f("Could not add comment to pull request",a.body.errors)}async addInlineCommentToPullRequest(e,t={}){let{pullRequest:n,comment:o,path:i,line:a,side:u="RIGHT",threadId:l}=e;if(!n.graphQLId)throw new Error('GitHub requires "graphQLId" for this function.');if(!o?.trim())throw new Error("GitHub requires a comment when adding an inline comment to a pull request.");if(l)return this.addReplyToReviewThread({threadId:l,comment:o},t);if(!i?.trim())throw new Error("GitHub requires a file path when adding an inline comment to a pull request.");if(!Number.isInteger(a)||a<1)throw new Error("GitHub requires a positive line number when adding an inline comment to a pull request.");if(u!=="LEFT"&&u!=="RIGHT")throw new Error('GitHub requires side to be either "LEFT" or "RIGHT".');return this.createReviewThread({pullRequest:n,comment:o,path:i,line:a,side:u},t)}async addReplyToReviewThread(e,t){let{threadId:n,comment:o}=e,i=`mutation AddPullRequestReviewThreadReply(
|
|
559
|
+
$threadId: ID!,
|
|
560
|
+
$body: String!
|
|
561
|
+
) {
|
|
562
|
+
addPullRequestReviewThreadReply(input: {
|
|
563
|
+
pullRequestReviewThreadId: $threadId,
|
|
564
|
+
body: $body
|
|
565
|
+
}) {
|
|
566
|
+
comment {
|
|
567
|
+
id
|
|
568
|
+
}
|
|
569
|
+
}
|
|
570
|
+
}`,a=await R(this.config,{query:i,variables:{threadId:n,body:o}},t);if(!a.body.data?.addPullRequestReviewThreadReply?.comment?.id)throw new f("Could not add reply to pull request review thread",a.body.errors);return n}async createReviewThread(e,t){let{pullRequest:n,comment:o,path:i,line:a,side:u}=e,l=`mutation AddInlineCommentToPullRequest(
|
|
571
|
+
$pullRequestId: ID!,
|
|
572
|
+
$body: String!,
|
|
573
|
+
$path: String!,
|
|
574
|
+
$line: Int!,
|
|
575
|
+
$side: DiffSide
|
|
576
|
+
) {
|
|
577
|
+
addPullRequestReview(input: {
|
|
578
|
+
pullRequestId: $pullRequestId,
|
|
579
|
+
event: COMMENT,
|
|
580
|
+
threads: [{
|
|
581
|
+
path: $path,
|
|
582
|
+
body: $body,
|
|
583
|
+
line: $line,
|
|
584
|
+
side: $side
|
|
585
|
+
}]
|
|
586
|
+
}) {
|
|
587
|
+
pullRequestReview {
|
|
588
|
+
id
|
|
589
|
+
comments(first: 1) {
|
|
590
|
+
nodes {
|
|
591
|
+
id
|
|
592
|
+
}
|
|
593
|
+
}
|
|
594
|
+
}
|
|
595
|
+
}
|
|
596
|
+
}`,p=await R(this.config,{query:l,variables:{pullRequestId:n.graphQLId,body:o,path:i,line:a,side:u}},t);if(!p.body.data?.addPullRequestReview?.pullRequestReview?.id)throw new f("Could not add inline comment to pull request",p.body.errors);return p.body.data?.addPullRequestReview?.pullRequestReview?.comments?.nodes?.[0]?.id}async setPullRequestMilestone(e,t={}){let{pullRequest:n,milestone:o}=e;if(!n.graphQLId)throw new Error('GitHub requires "graphQLId" for this function.');let i=`mutation SetPullRequestMilestone($pullRequestGraphQLId: ID!, $milestoneGraphQLId: ID) {
|
|
544
597
|
updatePullRequest(input: { pullRequestId: $pullRequestGraphQLId, milestoneId: $milestoneGraphQLId }) {
|
|
545
598
|
pullRequest {
|
|
546
599
|
id
|
|
547
600
|
}
|
|
548
601
|
}
|
|
549
|
-
}`,
|
|
602
|
+
}`,a=await R(this.config,{query:`${i}`,variables:{pullRequestGraphQLId:n.graphQLId,milestoneGraphQLId:o?.graphQLId??null}},t);if(!a.body.data?.updatePullRequest?.pullRequest?.id)throw new f("Could not set milestone of pull request",a.body.errors)}async markPullRequestReadyForReview(e,t){let n=`mutation MarkReadyToReview($pullRequestGraphQLId: ID!) {
|
|
550
603
|
markPullRequestReadyForReview(input: { pullRequestId: $pullRequestGraphQLId }) {
|
|
551
604
|
pullRequest {
|
|
552
605
|
id
|
|
@@ -558,25 +611,25 @@ query getBlame($owner: String!, $name: String!, $ref: String!, $path: String!) {
|
|
|
558
611
|
id
|
|
559
612
|
}
|
|
560
613
|
}
|
|
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:
|
|
614
|
+
}`,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:i}=e;if(!n)throw new Error('GitHub requires "reviews" for this function');if(!o)throw new Error('GitHub requires "graphQLId" for this function.');let a=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=i.map(d=>{if(!d.graphQLId)throw new Error('GitHub requires reviewer "graphQLId" for this function.');return d.graphQLId}).filter(d=>a.indexOf(d)===-1),l=`mutation SetPullRequestReviewers($pullRequestGraphQLId: ID!, $reviewerGraphQLIds: [ID!]!) {
|
|
562
615
|
requestReviews(input: { pullRequestId: $pullRequestGraphQLId, userIds: $reviewerGraphQLIds }) {
|
|
563
616
|
pullRequest {
|
|
564
617
|
id
|
|
565
618
|
}
|
|
566
619
|
}
|
|
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:
|
|
620
|
+
}`,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:i}=e;if(!o)throw new Error('GitHub requires "graphQLId" for this function.');if(!n)throw new Error('GitHub requires "reviews" for this function.');let a=[];for(let p of i){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.");a.push(p.graphQLId)}let u=`mutation SetPullRequestReviewers($pullRequestGraphQLId: ID!, $reviewerGraphQLIds: [ID!]!) {
|
|
568
621
|
requestReviews(input: { pullRequestId: $pullRequestGraphQLId, userIds: $reviewerGraphQLIds, union: true }) {
|
|
569
622
|
pullRequest {
|
|
570
623
|
id
|
|
571
624
|
}
|
|
572
625
|
}
|
|
573
|
-
}`,l=await R(this.config,{query:u,variables:{pullRequestGraphQLId:o,reviewerGraphQLIds:
|
|
626
|
+
}`,l=await R(this.config,{query:u,variables:{pullRequestGraphQLId:o,reviewerGraphQLIds:a}},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 i=o.map(l=>{if(!l.graphQLId)throw new Error('GitHub requires assignee "graphQLId" for this function.');return l.graphQLId}),a=`mutation SetPullRequestAssignees($pullRequestGraphQLId: ID!, $assigneeGraphQLIds: [ID!]!) {
|
|
574
627
|
updatePullRequest(input: { pullRequestId: $pullRequestGraphQLId, assigneeIds: $assigneeGraphQLIds }) {
|
|
575
628
|
pullRequest {
|
|
576
629
|
id
|
|
577
630
|
}
|
|
578
631
|
}
|
|
579
|
-
}`,u=await R(this.config,{query:
|
|
632
|
+
}`,u=await R(this.config,{query:a,variables:{pullRequestGraphQLId:n.graphQLId,assigneeGraphQLIds:i}},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:i},pullRequestId:a}=e,u=`query getPullRequests(
|
|
580
633
|
$namespace: String!
|
|
581
634
|
$name: String!
|
|
582
635
|
$pullRequestId: Int!
|
|
@@ -590,6 +643,9 @@ query getBlame($owner: String!, $name: String!, $ref: String!, $path: String!) {
|
|
|
590
643
|
nodes {
|
|
591
644
|
isOutdated
|
|
592
645
|
isResolved
|
|
646
|
+
line
|
|
647
|
+
startLine
|
|
648
|
+
diffSide
|
|
593
649
|
originalLine
|
|
594
650
|
originalStartLine
|
|
595
651
|
startDiffSide
|
|
@@ -628,54 +684,54 @@ query getBlame($owner: String!, $name: String!, $ref: String!, $path: String!) {
|
|
|
628
684
|
}
|
|
629
685
|
}
|
|
630
686
|
}
|
|
631
|
-
}`,l=await R(this.config,{query:u,variables:{namespace:o,name:
|
|
687
|
+
}`,l=await R(this.config,{query:u,variables:{namespace:o,name:i,pullRequestId:a}},t),p=l.body.data?.repository.pullRequest.reviewThreads.nodes?.filter(L).reduce((c,g)=>{if(!g.comments.nodes?.[0]?.pullRequestReview)return c;let m=g.comments.nodes[0].pullRequestReview,b=es(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(L).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],i=[];e.labelNames&&e.labelNames.forEach(c=>{i.push(`label:"${c}"`)});let[a,u]=await Promise.all([n==="null"?null:this.searchIssues({query:`author:${e.username} ${i.join(" ")}`,cursor:n,includeFromArchivedRepos:e.includeFromArchivedRepos,maxPageSize:e.maxPageSize},t),o==="null"?null:this.searchIssues({query:`assignee:${e.username} ${i.join(" ")}`,cursor:o,includeFromArchivedRepos:e.includeFromArchivedRepos,maxPageSize:e.maxPageSize},t)]),l={},p=[],d=c=>{l[c.id]||(l[c.id]=!0,p.push(c))};return a?.data.forEach(d),u?.data.forEach(d),{pageInfo:{hasNextPage:a?.pageInfo.hasNextPage||u?.pageInfo.hasNextPage||!1,endCursor:`${a?.pageInfo.hasNextPage&&a?.pageInfo.endCursor||"null"};${u?.pageInfo.hasNextPage&&u?.pageInfo.endCursor||"null"}`},data:p}}async setPullRequestLabels(e,t={}){let{pullRequest:n,labels:o}=e;if(!n.graphQLId)throw new Error('GitHub requires "graphQLId" for this function.');let i=`mutation SetPullRequestLabels($pullRequestGraphQLId: ID!, $labelGraphQLIds: [ID!]) {
|
|
632
688
|
updatePullRequest(input: { pullRequestId: $pullRequestGraphQLId, labelIds: $labelGraphQLIds }) {
|
|
633
689
|
pullRequest {
|
|
634
690
|
id
|
|
635
691
|
}
|
|
636
692
|
}
|
|
637
|
-
}`,
|
|
693
|
+
}`,a=await R(this.config,{query:i,variables:{pullRequestGraphQLId:n.graphQLId,labelGraphQLIds:o.map(u=>{if(!u.graphQLId)throw new Error('GitHub requires label "graphQLId" for this function.');return u.graphQLId})}},t);if(!a.body.data?.updatePullRequest?.pullRequest?.id)throw new f("Could not set pull request labels",a.body.errors)}async getIssuesForRepos(e,t={}){let n=Ke(e.startQuery||""),{cursor:o,assigneeLogins:i,updatedBefore:a,authorLogin:u,mentionLogin:l,labelNames:p}=e;return e.repos.forEach(d=>{n.push(`repo:${d.namespace}/${d.name}`)}),i&&i.forEach(d=>{n.push(`assignee:${d}`)}),a&&n.push(`updated:<${a}`),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 i=`mutation CloseIssueWithReason($issueGraphQLId: ID!, $reason: IssueClosedStateReason!) {
|
|
638
694
|
closeIssue(input: { issueId: $issueGraphQLId, stateReason: $reason }) {
|
|
639
695
|
issue {
|
|
640
696
|
id
|
|
641
697
|
}
|
|
642
698
|
}
|
|
643
|
-
}`,
|
|
699
|
+
}`,a=await R(this.config,{query:i,variables:{issueGraphQLId:n.graphQLId,reason:o}},t);if(!a.body.data?.closeIssue?.issue?.id)throw new f("Could not close issue with reason",a.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!) {
|
|
644
700
|
updateIssue(input: { id: $issueGraphQLId, state: CLOSED }) {
|
|
645
701
|
issue {
|
|
646
702
|
id
|
|
647
703
|
}
|
|
648
704
|
}
|
|
649
|
-
}`,
|
|
705
|
+
}`,i=await R(this.config,{query:o,variables:{issueGraphQLId:n.graphQLId}},t);if(!i.body.data?.updateIssue?.issue?.id)throw new f("Could not close issue",i.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!) {
|
|
650
706
|
reopenIssue(input: { issueId: $issueGraphQLId }) {
|
|
651
707
|
issue {
|
|
652
708
|
id
|
|
653
709
|
}
|
|
654
710
|
}
|
|
655
|
-
}`,
|
|
711
|
+
}`,i=await R(this.config,{query:o,variables:{issueGraphQLId:n.graphQLId}},t);if(!i.body.data?.reopenIssue?.issue?.id)throw new f("Could not reopen issue",i.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 i=o.map(l=>l.graphQLId),a=`mutation SetIssueLabels($issueGraphQLId: ID!, $labelGraphQLIds: [ID!]) {
|
|
656
712
|
updateIssue(input: { id: $issueGraphQLId, labelIds: $labelGraphQLIds }) {
|
|
657
713
|
issue {
|
|
658
714
|
id
|
|
659
715
|
}
|
|
660
716
|
}
|
|
661
|
-
}`,u=await R(this.config,{query:
|
|
717
|
+
}`,u=await R(this.config,{query:a,variables:{issueGraphQLId:n.graphQLId,labelGraphQLIds:i}},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 i=`mutation SetIssueMilestone($issueGraphQLId: ID!, $milestoneGraphQLId: ID) {
|
|
662
718
|
updateIssue(input: { id: $issueGraphQLId, milestoneId: $milestoneGraphQLId }) {
|
|
663
719
|
issue {
|
|
664
720
|
id
|
|
665
721
|
}
|
|
666
722
|
}
|
|
667
|
-
}`,
|
|
723
|
+
}`,a=await R(this.config,{query:`${i}`,variables:{issueGraphQLId:n.graphQLId,milestoneGraphQLId:o?.graphQLId??null}},t);if(!a.body.data?.updateIssue?.issue?.id)throw new f("Could not set milestone of issue",a.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 i=o.map(l=>{if(!l.graphQLId)throw new Error('GitHub requires assignee "graphQLId" for this function.');return l.graphQLId}),a=`mutation SetIssueAssignees($issueGraphQLId: ID!, $assigneeGraphQLIds: [ID!]!) {
|
|
668
724
|
updateIssue(input: { id: $issueGraphQLId, assigneeIds: $assigneeGraphQLIds }) {
|
|
669
725
|
issue {
|
|
670
726
|
id
|
|
671
727
|
}
|
|
672
728
|
}
|
|
673
|
-
}`,u=await R(this.config,{query:
|
|
729
|
+
}`,u=await R(this.config,{query:a,variables:{issueGraphQLId:n.graphQLId,assigneeGraphQLIds:i}},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:i}=e,a=await R(this.config,{query:`
|
|
674
730
|
query getLabelsForRepo($owner: String!, $name: String! $cursor: String, $first: Int!) {
|
|
675
731
|
repository(owner: $owner, name: $name) {
|
|
676
732
|
milestones(first: $first, after: $cursor) {
|
|
677
733
|
nodes {
|
|
678
|
-
${
|
|
734
|
+
${Ie}
|
|
679
735
|
}
|
|
680
736
|
pageInfo {
|
|
681
737
|
endCursor
|
|
@@ -684,12 +740,12 @@ query getLabelsForRepo($owner: String!, $name: String! $cursor: String, $first:
|
|
|
684
740
|
}
|
|
685
741
|
}
|
|
686
742
|
}
|
|
687
|
-
`,variables:{owner:n,name:o,cursor:
|
|
743
|
+
`,variables:{owner:n,name:o,cursor:i,first:v}},t);if(!a.body.data)throw new f("Could not fetch milestones",a.body.errors);return{pageInfo:a.body.data.repository.milestones?.pageInfo??{endCursor:null,hasNextPage:!1},data:a.body.data.repository.milestones?.nodes?.map(st)??[]}}async getLabelsForRepo(e,t={}){let{repo:{namespace:n,name:o},cursor:i}=e,a=await R(this.config,{query:`
|
|
688
744
|
query getLabelsForRepo($owner: String!, $name: String! $cursor: String, $first: Int!) {
|
|
689
745
|
repository(owner: $owner, name: $name) {
|
|
690
746
|
labels(first: $first, after: $cursor) {
|
|
691
747
|
nodes {
|
|
692
|
-
${
|
|
748
|
+
${be}
|
|
693
749
|
}
|
|
694
750
|
pageInfo {
|
|
695
751
|
endCursor
|
|
@@ -698,7 +754,7 @@ query getLabelsForRepo($owner: String!, $name: String! $cursor: String, $first:
|
|
|
698
754
|
}
|
|
699
755
|
}
|
|
700
756
|
}
|
|
701
|
-
`,variables:{owner:n,name:o,cursor:
|
|
757
|
+
`,variables:{owner:n,name:o,cursor:i,first:v}},t);if(!a.body.data)throw new f("Could not fetch labels",a.body.errors);return{pageInfo:a.body.data.repository.labels?.pageInfo??{endCursor:null,hasNextPage:!1},data:a.body.data.repository.labels?.nodes?.map(rt)??[]}}async getTreeForRepo(e,t={}){let n=await this.config.request({url:`${X(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(Vr)}}};var ss="https://gitlab.com/api/v4",ns="https://gitlab.com/api/graphql",nt=/\/api\/v\d+$/,Qt=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.")},we=(r,s)=>{let e=s.baseUrl||r.baseUrl;return e?(e=e.replace(/\/$/,""),Qt(e),nt.test(e)||(e=e+"/api/v4"),e):ss},os=(r,s)=>{let e=s.baseUrl||r.baseUrl;return e?(e=e.replace(/\/$/,""),Qt(e),nt.test(e)&&(e=e.replace(nt,"")),`${e}/api/graphql`):ns},y=(r,s,e)=>{let t=h(e.token||r.token);return r.request({url:os(r,e),method:"POST",headers:{...t,"Content-Type":"application/json"},body:JSON.stringify(s)})},Se=r=>r?.map(s=>`"${s.message}"`).join(", ");var lt=r=>r.split("/").slice(0,-1).join("/"),pt=r=>r.split("/").at(-1)??"",ve=r=>({id:r.id.replace(Y,""),graphQLId:r.id,namespace:lt(r.fullPath),name:pt(r.fullPath),webUrl:r.webUrl}),jt=r=>({id:r.id.replace(Y,""),graphQLId:r.id,httpsUrl:r.httpUrlToRepo,namespace:lt(r.fullPath),name:pt(r.fullPath),sshUrl:r.sshUrlToRepo,webUrl:r.webUrl}),is={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 us="gid://gitlab/User/",Y="gid://gitlab/Project/",ls="gid://gitlab/MergeRequest/",ps="gid://gitlab/Issue/",ds="gid://gitlab/ProjectLabel/",cs="gid://gitlab/Milestone/",gs="gid://gitlab/Ci::Build/",dt=`
|
|
702
758
|
description
|
|
703
759
|
dueDate
|
|
704
760
|
id
|
|
@@ -707,7 +763,7 @@ startDate
|
|
|
707
763
|
state
|
|
708
764
|
title
|
|
709
765
|
webPath
|
|
710
|
-
`,
|
|
766
|
+
`,ot=`
|
|
711
767
|
id
|
|
712
768
|
fullPath
|
|
713
769
|
webUrl
|
|
@@ -728,12 +784,12 @@ username
|
|
|
728
784
|
publicEmail
|
|
729
785
|
avatarUrl
|
|
730
786
|
webUrl
|
|
731
|
-
`,
|
|
787
|
+
`,ct=`
|
|
732
788
|
color
|
|
733
789
|
description
|
|
734
790
|
id
|
|
735
791
|
title
|
|
736
|
-
`,
|
|
792
|
+
`,it=`
|
|
737
793
|
author {
|
|
738
794
|
${k}
|
|
739
795
|
}
|
|
@@ -750,7 +806,7 @@ id
|
|
|
750
806
|
iid
|
|
751
807
|
labels {
|
|
752
808
|
nodes {
|
|
753
|
-
${
|
|
809
|
+
${ct}
|
|
754
810
|
}
|
|
755
811
|
}
|
|
756
812
|
state
|
|
@@ -761,9 +817,9 @@ upvotes
|
|
|
761
817
|
userNotesCount
|
|
762
818
|
webUrl
|
|
763
819
|
milestone {
|
|
764
|
-
${
|
|
820
|
+
${dt}
|
|
765
821
|
}
|
|
766
|
-
`,
|
|
822
|
+
`,ms=`
|
|
767
823
|
stages {
|
|
768
824
|
nodes {
|
|
769
825
|
jobs {
|
|
@@ -779,7 +835,7 @@ stages {
|
|
|
779
835
|
name
|
|
780
836
|
}
|
|
781
837
|
}
|
|
782
|
-
`,
|
|
838
|
+
`,Bt=(r,s,e)=>`
|
|
783
839
|
id
|
|
784
840
|
state
|
|
785
841
|
author {
|
|
@@ -799,6 +855,7 @@ draft
|
|
|
799
855
|
userNotesCount
|
|
800
856
|
upvotes
|
|
801
857
|
title
|
|
858
|
+
description
|
|
802
859
|
webUrl
|
|
803
860
|
createdAt
|
|
804
861
|
updatedAt
|
|
@@ -823,13 +880,13 @@ reviewers {
|
|
|
823
880
|
mergeStatusEnum
|
|
824
881
|
labels {
|
|
825
882
|
nodes {
|
|
826
|
-
${
|
|
883
|
+
${ct}
|
|
827
884
|
}
|
|
828
885
|
}
|
|
829
886
|
${r?"project { id httpUrlToRepo fullPath sshUrlToRepo webUrl archived } sourceProject { id httpUrlToRepo fullPath sshUrlToRepo webUrl }":""}
|
|
830
|
-
${s?`milestone { ${
|
|
831
|
-
${e?`headPipeline { ${
|
|
832
|
-
`,j=r=>`${r.namespace}/${r.name}`,
|
|
887
|
+
${s?`milestone { ${dt} }`:""}
|
|
888
|
+
${e?`headPipeline { ${ms} }`:""}
|
|
889
|
+
`,j=r=>`${r.namespace}/${r.name}`,hs=r=>`${r.namespace}/${r.name}`,fs=r=>({canCreateWebhook:r.adminOperations,canPush:r.pushCode,isAdmin:r.adminOperations}),at=r=>({id:r.id.replace(Y,""),graphQLId:r.id,namespace:lt(r.fullPath),name:pt(r.fullPath),webUrl:r.webUrl,httpsUrl:r.httpUrlToRepo,sshUrl:r.sshUrlToRepo,defaultBranch:r.repository?.rootRef?{name:r.repository.rootRef}:null,permissions:fs(r.userPermissions)}),Rs=r=>({path:r.path,isDirectory:r.type==="tree"}),Is={opened:"OPEN",merged:"MERGED",closed:"CLOSED"},Mt=(r,s,e)=>!s&&r?.startsWith("/")?`https://gitlab.com${r}`:s&&r?.startsWith("/")&&e?`${e.replace(/\/+?$/,"")}${r}`:r,N=(r,s,e)=>{let t=Mt(r.avatarUrl,s,e);return{id:r.id.replace(us,""),graphQLId:r.id,name:r.name,username:r.username,email:r.publicEmail??null,avatarUrl:t,url:r.webUrl}},gt=r=>({color:r.color,description:r.description,id:r.id.replace(ds,""),graphQLId:r.id,name:r.title}),bs=(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,ys=(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"}},zt=(r,s,e,t,n)=>{let o=r.reviewers?.nodes?r.reviewers.nodes.map(i=>ys(i,t,n)):null;return{id:r.id.replace(ls,""),graphQLId:r.id,title:r.title,description:r.description,number:parseInt(r.iid,10),state:Is[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(i=>i.jobs?.nodes?.map(a=>({completedAt:a.finishedAt?new Date(a.finishedAt):null,description:null,name:a.name??null,state:bs(a.status,a.allowFailure),stage:i.name??null,startedAt:new Date(a.createdAt),url:`${s.webUrl}/-/jobs/${a.id.replace(gs,"")}`}))??[])??[]},baseRef:{name:r.targetBranch,oid:r.diffRefs?.baseSha??null},headRef:{name:r.sourceBranch,oid:r.diffRefs?.headSha??null},url:r.webUrl,updatedDate:new Date(r.updatedAt),closedDate:r.mergedAt?new Date(r.mergedAt):null,mergedDate:r.mergedAt?new Date(r.mergedAt):null,assignees:r.assignees?.nodes?r.assignees.nodes.map(i=>N(i,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?mt(r.milestone,s.webUrl):null,labels:r.labels?.nodes?.map(gt)??[],permissions:null}},ut=(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(ps,""),labels:r.labels?.nodes?.map(gt)??[],number:r.iid,repository:{id:s.id.replace(Y,""),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?mt(r.milestone,s.webUrl):null}),mt=(r,s)=>({id:r.id.replace(cs,""),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}),ee=class extends D{getIsSelfHosted(s){return!!s.baseUrl||!!this.config.baseUrl}async getCurrentUser(s={},e={}){let n=(await y(this.config,{query:`
|
|
833
890
|
query getCurrentUser {
|
|
834
891
|
currentUser {
|
|
835
892
|
${k}
|
|
@@ -851,7 +908,7 @@ query getUserForCommit($fullPath: ID!, $oid: String!) {
|
|
|
851
908
|
}
|
|
852
909
|
}
|
|
853
910
|
}
|
|
854
|
-
`,variables:{fullPath:t,oid:s.oid}},e)).body.data?.project?.repository?.tree?.lastCommit;if(!o)throw new Error("Commit not found.");let
|
|
911
|
+
`,variables:{fullPath:t,oid:s.oid}},e)).body.data?.project?.repository?.tree?.lastCommit;if(!o)throw new Error("Commit not found.");let i=Mt(o.author.avatarUrl,this.getIsSelfHosted(e),this.config.baseUrl??e.baseUrl);return{data:{name:o.authorName,email:o.authorEmail,avatarUrl:i}}}async getAccountForEmail(s,e={}){let n=(await y(this.config,{query:`
|
|
855
912
|
query getAccountForEmail($email: String!) {
|
|
856
913
|
users(search: $email) {
|
|
857
914
|
nodes {
|
|
@@ -865,7 +922,7 @@ query getAccountForUsername($username: String!) {
|
|
|
865
922
|
${k}
|
|
866
923
|
}
|
|
867
924
|
}
|
|
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,
|
|
925
|
+
`,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,i=await y(this.config,{query:`
|
|
869
926
|
query getAccountsForRepo(
|
|
870
927
|
$fullPath: ID!
|
|
871
928
|
$after: String
|
|
@@ -886,22 +943,22 @@ query getAccountsForRepo(
|
|
|
886
943
|
}
|
|
887
944
|
}
|
|
888
945
|
}
|
|
889
|
-
`,variables:{fullPath:`${t}/${n}`,after:o}},e),i
|
|
946
|
+
`,variables:{fullPath:`${t}/${n}`,after:o}},e),a=i.body.data?.project?.projectMembers?.nodes?.map(u=>u.user).filter(u=>u!==null);return{pageInfo:i.body.data?.project?.projectMembers?.pageInfo??{endCursor:null,hasNextPage:!1},data:a?.map(u=>N(u,this.getIsSelfHosted(e),this.config.baseUrl??e.baseUrl))??[]}}async getRepo(s,e={}){let t=j(s),n=await y(this.config,{query:`
|
|
890
947
|
query getRepo($fullPath: ID!) {
|
|
891
948
|
project(fullPath: $fullPath) {
|
|
892
|
-
${
|
|
949
|
+
${ot}
|
|
893
950
|
}
|
|
894
951
|
}
|
|
895
|
-
`,variables:{fullPath:t}},e);if(!n.body.data?.project)throw new Error(`Repository ${t} not found`);return{data:
|
|
952
|
+
`,variables:{fullPath:t}},e);if(!n.body.data?.project)throw new Error(`Repository ${t} not found`);return{data:at(n.body.data.project)}}async getReposBase(s,e={}){let n=s.map(j).map((u,l)=>`
|
|
896
953
|
getRepo_${l}: project(fullPath: "${u}") {
|
|
897
|
-
${
|
|
954
|
+
${ot}
|
|
898
955
|
}
|
|
899
956
|
`).join(`
|
|
900
957
|
`),o=await y(this.config,{query:`
|
|
901
958
|
query batchGetRepos {
|
|
902
959
|
${n}
|
|
903
960
|
}
|
|
904
|
-
`},e);if(!o.body.data)throw new Error(
|
|
961
|
+
`},e);if(!o.body.data)throw new Error(Se(o.body.errors)||o.statusText||"Unknown error");let i=[],a=[];return s.forEach((u,l)=>{let p=o.body.data[`getRepo_${l}`];p?i.push(at(p)):a.push({input:u})}),{data:i,errors:a}}async getRepos(s,e={}){let t=[];for(let i=0;i<s.length;i+=15)t.push(s.slice(i,i+15));return(await Promise.all(t.map(i=>this.getReposBase(i,e)))).reduce((i,a)=>({data:[...i.data,...a.data],errors:[...i.errors,...a.errors]}),{data:[],errors:[]})}async getReposForCurrentUser(s,e={}){let t=await y(this.config,{query:`
|
|
905
962
|
query getReposForCurrentUser($after: String) {
|
|
906
963
|
projects(membership: true first: 100 after: $after) {
|
|
907
964
|
pageInfo {
|
|
@@ -909,11 +966,11 @@ query getReposForCurrentUser($after: String) {
|
|
|
909
966
|
hasNextPage
|
|
910
967
|
}
|
|
911
968
|
nodes {
|
|
912
|
-
${
|
|
969
|
+
${ot}
|
|
913
970
|
}
|
|
914
971
|
}
|
|
915
972
|
}
|
|
916
|
-
`,variables:{after:s.cursor}},e);if(!t.body.data?.projects)throw new Error(
|
|
973
|
+
`,variables:{after:s.cursor}},e);if(!t.body.data?.projects)throw new Error(Se(t.body.errors)||t.statusText||"Unknown error");let n=t.body.data?.projects?.nodes||[];return{pageInfo:t.body.data?.projects?.pageInfo,data:n.map(at)}}async getRefs(s,e,t={}){let n=j(e.repo),o=new URL(`${we(this.config,t)}/projects/${encodeURIComponent(n)}/repository/${s}`);o.searchParams.set("page",e.page?.toString()||"1"),o.searchParams.set("per_page",v.toString());let i=await this.config.request({url:o.toString(),headers:h(t.token||this.config.token)}),a=i.headers["x-next-page"];return{pageInfo:{hasNextPage:!!a,nextPage:a?parseInt(a,10):null},data:i.body.map(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(`${we(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)}),i=0;return{data:{ranges:o.body.map(a=>{let u=i+1;return i+=a.lines.length,{startingLine:u,endingLine:i,commit:{oid:a.commit.id,parentOids:a.commit.parent_ids,authoredDate:new Date(a.commit.authored_date),author:{name:a.commit.author_name,email:a.commit.author_email,avatarUrl:null},committedDate:new Date(a.commit.committed_date),committer:{name:a.commit.committer_name,email:a.commit.committer_email,avatarUrl:null},message:a.commit.message,fileCount:null,additions:null,deletions:null}}})}}}async getPullRequestsForUser(s,e={}){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=is[s.association],o=await y(this.config,{query:`
|
|
917
974
|
query getPullRequestsForUser($username: String! $cursor: String $labelNames: [String!]) {
|
|
918
975
|
user(username: $username) {
|
|
919
976
|
${n}(state:opened first:100 after:$cursor labels: $labelNames${t?` ${t}`:""}) {
|
|
@@ -922,12 +979,12 @@ query getPullRequestsForUser($username: String! $cursor: String $labelNames: [St
|
|
|
922
979
|
hasNextPage
|
|
923
980
|
}
|
|
924
981
|
nodes {
|
|
925
|
-
${
|
|
982
|
+
${Bt(!0,!0,!0)}
|
|
926
983
|
}
|
|
927
984
|
}
|
|
928
985
|
}
|
|
929
986
|
}
|
|
930
|
-
`,variables:{username:s.username,cursor:s.cursor,labelNames:s.labelNames}},e);if(!o.body.data)throw new Error(
|
|
987
|
+
`,variables:{username:s.username,cursor:s.cursor,labelNames:s.labelNames}},e);if(!o.body.data)throw new Error(Se(o.body.errors)||o.statusText||"Unknown error");if(!o.body.data.user)throw new Error("User not found");let i=o.body.data.user[n];if(!i)throw new Error("Unexpected response");return{pageInfo:i.pageInfo,data:i.nodes?.filter(a=>s.includeFromArchivedRepos||!a.project.archived).map(a=>zt(a,jt(a.project),jt(a.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],i=t?.split("-")||[],a=n?.split("-")||[],u=o?.split("-")||[],l=[],p=[],d=[],c=0;do{let S=s.repos&&s.repos[c];i[c]==="null"?l.push(null):l.push(this.getPullRequestsForUser({username:s.username,association:"authored",cursor:i[c],includeFromArchivedRepos:s.includeFromArchivedRepos,labelNames:s.labelNames,...S&&{repo:S}},e)),a[c]==="null"?p.push(null):p.push(this.getPullRequestsForUser({username:s.username,association:"assigned",cursor:a[c],includeFromArchivedRepos:s.includeFromArchivedRepos,labelNames:s.labelNames,...S&&{repo:S}},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,...S&&{repo:S}},e)),c++}while(c<(s.repos?.length||0));let g=[l,p,d].flat(),m=await Promise.all(g),b={},I=[],E=S=>{b[S.id]||(b[S.id]=!0,I.push(S))},z=!1,ue=m.map((S,wt)=>{let ne="";return S&&S.data.forEach(E),S?.pageInfo.hasNextPage?(z=!0,ne+=`${S.pageInfo.endCursor||"null"}`):ne+="null",s.repos?.length&&(wt+1)%s.repos.length!==0?ne+="-":wt+1<m.length&&(ne+=";"),ne}).join("");return{pageInfo:{hasNextPage:z,endCursor:ue},data:I}}getVariablesForPullRequests(s){let{updatedBefore:e,isDraft:t,authorLogin:n,assigneeLogins:o,labelNames:i,reviewRequestedLogin:a}=s||{},u={},l=[],p=[],d=(c,g,m)=>{l.push(`$${c}: ${m}`),p.push(`${c}: $${c}`),u[c]=g};return e&&d("updatedBefore",e,"Time"),n&&d("authorUsername",n,"String"),o&&d("assigneeUsername",o[0],"String"),i&&d("labelName",i,"[String]"),t!=null&&d("draft",t,"Boolean"),a&&d("reviewerUsername",a,"String"),{variables:u,variableTypes:l,mergeRequestArguments:p}}async getPullRequestsForRepoBase(s,e={},t){let{cursor:n,repo:o}=s||{},i=j(o),{variables:a,variableTypes:u,mergeRequestArguments:l}=this.getVariablesForPullRequests(s),p={fullPath:i,...a},d=await y(this.config,{query:`
|
|
931
988
|
query getPullRequestsForRepo(
|
|
932
989
|
$fullPath: ID!
|
|
933
990
|
$after: String
|
|
@@ -952,19 +1009,19 @@ query getPullRequestsForRepo(
|
|
|
952
1009
|
hasNextPage
|
|
953
1010
|
}
|
|
954
1011
|
nodes {
|
|
955
|
-
${
|
|
1012
|
+
${Bt(!1,!0,!0)}
|
|
956
1013
|
}
|
|
957
1014
|
}
|
|
958
1015
|
}
|
|
959
1016
|
}
|
|
960
|
-
`,variables:{...p,after:n}},e),c=[],g=d.body.data?.project;if(!t&&g?.archived)return{pageInfo:null,data:[]};let m=
|
|
1017
|
+
`,variables:{...p,after:n}},e),c=[],g=d.body.data?.project;if(!t&&g?.archived)return{pageInfo:null,data:[]};let m=ve(g||{id:"",fullPath:"",webUrl:""});return(g?.mergeRequests?.nodes||[]).forEach(I=>{c.push(zt(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:i,labelNames:a,isDraft:u,reviewRequestedLogin:l}=s;return{data:(await Promise.all(t.map(d=>this.getPullRequestsForRepoBase({repo:d,assigneeLogins:n,updatedBefore:o,authorLogin:i,labelNames:a,isDraft:u,reviewRequestedLogin:l},e,s.includeFromArchivedRepos??!1)))).flatMap(d=>d.data)}}async closePullRequest(s,e={}){let{pullRequest:t}=s,n=`mutation ClosePullRequest($fullPath: ID!, $pullRequestId: String!) {
|
|
961
1018
|
mergeRequestUpdate(input: { projectPath: $fullPath, iid: $pullRequestId, state: CLOSED }) {
|
|
962
1019
|
errors,
|
|
963
1020
|
mergeRequest {
|
|
964
1021
|
id
|
|
965
1022
|
}
|
|
966
1023
|
}
|
|
967
|
-
}`,
|
|
1024
|
+
}`,i=(await y(this.config,{query:n,variables:{fullPath:`${t.repository.owner.login}/${t.repository.name}`,pullRequestId:t.number.toString()}},e)).body.data?.mergeRequestUpdate;if(!i?.mergeRequest?.id||i?.errors?.length!==0)throw new Error("Could not close pull request")}async mergePullRequest(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(
|
|
968
1025
|
$fullPath: ID!,
|
|
969
1026
|
$pullRequestId: String!,
|
|
970
1027
|
$expectedSourceSha: String!,
|
|
@@ -981,63 +1038,63 @@ query getPullRequestsForRepo(
|
|
|
981
1038
|
id
|
|
982
1039
|
}
|
|
983
1040
|
}
|
|
984
|
-
}`,
|
|
1041
|
+
}`,a=(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(!a?.mergeRequest?.id||a?.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) {
|
|
985
1042
|
mergeRequestSetMilestone(input: { projectPath: $fullPath, iid: $pullRequestId, milestoneId: $milestoneGraphQLId }) {
|
|
986
1043
|
errors,
|
|
987
1044
|
mergeRequest {
|
|
988
1045
|
id
|
|
989
1046
|
}
|
|
990
1047
|
}
|
|
991
|
-
}`,
|
|
1048
|
+
}`,i=await y(this.config,{query:o,variables:{fullPath:`${t.repository.owner.login}/${t.repository.name}`,pullRequestId:t.number.toString(),milestoneGraphQLId:n?.graphQLId}},e),a=i.body.data?.mergeRequestSetMilestone;if(!a?.mergeRequest?.id||i.body.errors||a?.errors?.length!==0)throw new Error("Could not set milestone of pull request")}async setPullRequestAsDraft(s,e={}){let{pullRequest:t,isDraft:n}=s,o=`mutation MergeRequestSetDraft($fullPath: ID!, $pullRequestId: String!, $isDraft: Boolean!) {
|
|
992
1049
|
mergeRequestSetDraft(input: { projectPath: $fullPath, iid: $pullRequestId, draft: $isDraft }) {
|
|
993
1050
|
errors,
|
|
994
1051
|
mergeRequest {
|
|
995
1052
|
id
|
|
996
1053
|
}
|
|
997
1054
|
}
|
|
998
|
-
}`,
|
|
1055
|
+
}`,a=(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(!a?.mergeRequest?.id||a?.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}),i=`mutation MergeRequestSetReviewers($fullPath: ID!, $pullRequestId: String!, $reviewerUsernames: [String!]!) {
|
|
999
1056
|
mergeRequestSetReviewers(input: { projectPath: $fullPath, iid: $pullRequestId, reviewerUsernames: $reviewerUsernames }) {
|
|
1000
1057
|
errors,
|
|
1001
1058
|
mergeRequest {
|
|
1002
1059
|
id
|
|
1003
1060
|
}
|
|
1004
1061
|
}
|
|
1005
|
-
}`,u=(await y(this.config,{query:
|
|
1062
|
+
}`,u=(await y(this.config,{query:i,variables:{fullPath:`${t.repository.owner.login}/${t.repository.name}`,pullRequestId:t.number.toString(),reviewerUsernames:o}},e)).body.data?.mergeRequestSetReviewers;if(!u?.mergeRequest?.id||u?.errors?.length!==0)throw new Error("Could not set pull request reviewers")}async reRequestPullRequestReview(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!) {
|
|
1006
1063
|
mergeRequestReviewerRereview(input: { projectPath: $fullPath, iid: $pullRequestId, userId: $reviewerUserId }) {
|
|
1007
1064
|
errors,
|
|
1008
1065
|
mergeRequest {
|
|
1009
1066
|
id
|
|
1010
1067
|
}
|
|
1011
1068
|
}
|
|
1012
|
-
}`,
|
|
1069
|
+
}`,a=(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(!a?.mergeRequest?.id||a?.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 i=n.filter(a=>o.find(u=>u.reviewer.graphQLId===a.graphQLId));await Promise.all(i.map(a=>this.reRequestPullRequestReview({pullRequest:t,reviewer:a},e)))}async setPullRequestAssignees(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}),i=`mutation MergeRequestSetAssignees($fullPath: ID!, $pullRequestId: String!, $assigneeUsernames: [String!]!) {
|
|
1013
1070
|
mergeRequestSetAssignees(input: { projectPath: $fullPath, iid: $pullRequestId, assigneeUsernames: $assigneeUsernames }) {
|
|
1014
1071
|
errors,
|
|
1015
1072
|
mergeRequest {
|
|
1016
1073
|
id
|
|
1017
1074
|
}
|
|
1018
1075
|
}
|
|
1019
|
-
}`,u=(await y(this.config,{query:
|
|
1076
|
+
}`,u=(await y(this.config,{query:i,variables:{fullPath:`${t.repository.owner.login}/${t.repository.name}`,pullRequestId:t.number.toString(),assigneeUsernames:o}},e)).body.data?.mergeRequestSetAssignees;if(!u?.mergeRequest?.id||u?.errors?.length!==0)throw new Error("Could not set pull request assignees")}async setPullRequestLabels(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}),i=`mutation SetPullRequestLabels($fullPath: ID!, $pullRequestId: String!, $labelGraphQLIds: [LabelID!]!) {
|
|
1020
1077
|
mergeRequestSetLabels(input: { projectPath: $fullPath, iid: $pullRequestId, labelIds: $labelGraphQLIds }) {
|
|
1021
1078
|
mergeRequest {
|
|
1022
1079
|
id
|
|
1023
1080
|
}
|
|
1024
1081
|
}
|
|
1025
|
-
}`;if(!(await y(this.config,{query:
|
|
1082
|
+
}`;if(!(await y(this.config,{query:i,variables:{fullPath:`${t.repository.owner.login}/${t.repository.name}`,pullRequestId:t.number.toString(),labelGraphQLIds:o}},e)).body.data?.mergeRequestSetLabels?.mergeRequest?.id)throw new Error("Could not set pull request labels")}async getIssue(s,e={}){let t=hs(s),n=await y(this.config,{query:`
|
|
1026
1083
|
query GetSingleIssue($projectId: ID!, $issueNumber: String!) {
|
|
1027
1084
|
project(fullPath: $projectId) {
|
|
1028
1085
|
id
|
|
1029
1086
|
fullPath
|
|
1030
1087
|
webUrl
|
|
1031
1088
|
issue(iid: $issueNumber) {
|
|
1032
|
-
${
|
|
1089
|
+
${it}
|
|
1033
1090
|
}
|
|
1034
1091
|
}
|
|
1035
1092
|
}
|
|
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:
|
|
1093
|
+
`,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:ut(n.body.data.project.issue,ve(n.body.data.project),this.getIsSelfHosted(e),this.config.baseUrl??e.baseUrl)}}getVariablesForIssues(s){let{updatedBefore:e,authorLogin:t,assigneeLogins:n,labelNames:o}=s||{},i={},a=[],u=[],l=(p,d,c)=>{a.push(`$${p}: ${c}`),u.push(`${p}: $${p}`),i[p]=d};return e&&l("updatedBefore",e,"Time"),t&&l("authorUsername",t,"String"),n&&l("assigneeUsername",n[0],"String"),o&&l("labelName",o,"[String]"),{variables:i,variableTypes:a,issueArguments:u}}async getIssuesForRepo(s,e={}){let{cursor:t,repo:n}=s||{},o=j(n),{variables:i,variableTypes:a,issueArguments:u}=this.getVariablesForIssues(s),l={fullPath:o,...i},p=`
|
|
1037
1094
|
query GetIssuesFromProject(
|
|
1038
1095
|
$fullPath: ID!
|
|
1039
1096
|
$after: String
|
|
1040
|
-
${
|
|
1097
|
+
${a.length?a.join(" "):""}
|
|
1041
1098
|
) {
|
|
1042
1099
|
project(
|
|
1043
1100
|
fullPath: $fullPath
|
|
@@ -1053,7 +1110,7 @@ query GetSingleIssue($projectId: ID!, $issueNumber: String!) {
|
|
|
1053
1110
|
${u.length?u.join(" "):""}
|
|
1054
1111
|
) {
|
|
1055
1112
|
nodes {
|
|
1056
|
-
${
|
|
1113
|
+
${it}
|
|
1057
1114
|
}
|
|
1058
1115
|
pageInfo {
|
|
1059
1116
|
endCursor
|
|
@@ -1061,11 +1118,11 @@ query GetSingleIssue($projectId: ID!, $issueNumber: String!) {
|
|
|
1061
1118
|
}
|
|
1062
1119
|
}
|
|
1063
1120
|
}
|
|
1064
|
-
}`,d=await y(this.config,{query:p,variables:{...l,after:t}},e),c=[],g=d.body.data?.project,m=
|
|
1121
|
+
}`,d=await y(this.config,{query:p,variables:{...l,after:t}},e),c=[],g=d.body.data?.project,m=ve(g||{id:"",fullPath:"",webUrl:""});return(g?.issues?.nodes||[]).forEach(I=>{c.push(ut(I,m,this.getIsSelfHosted(e),this.config.baseUrl??e.baseUrl))}),{pageInfo:g?.issues?.pageInfo??{endCursor:null,hasNextPage:!1},data:c.sort((I,E)=>(I.updatedDate||I.createdDate).getTime()-(E.updatedDate||E.createdDate).getTime())}}async getIssuesForRepos(s,e={}){let{cursor:t}=s||{},n=s.repoIds.map(g=>g.toString().startsWith(Y)?g:`${Y}${g}`),{variables:o,variableTypes:i,mergeRequestArguments:a}=this.getVariablesForPullRequests(s),u={projectIds:n,...o},l=`
|
|
1065
1122
|
query GetIssuesFromProject(
|
|
1066
1123
|
$projectIds: [ID!]
|
|
1067
1124
|
$after: String
|
|
1068
|
-
${
|
|
1125
|
+
${i.length?i.join(" "):""}
|
|
1069
1126
|
) {
|
|
1070
1127
|
projects(
|
|
1071
1128
|
ids: $projectIds
|
|
@@ -1084,27 +1141,27 @@ query GetSingleIssue($projectId: ID!, $issueNumber: String!) {
|
|
|
1084
1141
|
first: 100
|
|
1085
1142
|
state: opened
|
|
1086
1143
|
sort: UPDATED_DESC
|
|
1087
|
-
${
|
|
1144
|
+
${a.length?a.join(" "):""}
|
|
1088
1145
|
) {
|
|
1089
1146
|
nodes {
|
|
1090
|
-
${
|
|
1147
|
+
${it}
|
|
1091
1148
|
}
|
|
1092
1149
|
}
|
|
1093
1150
|
}
|
|
1094
1151
|
}
|
|
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=
|
|
1152
|
+
}`,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=ve(g);(g.issues?.nodes||[]).forEach(I=>d.push(ut(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!) {
|
|
1096
1153
|
updateIssue(input: { projectPath: $fullPath, iid: $issueId, stateEvent: $status }) {
|
|
1097
1154
|
issue {
|
|
1098
1155
|
id
|
|
1099
1156
|
}
|
|
1100
1157
|
}
|
|
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}),
|
|
1158
|
+
}`;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}),i=`mutation SetIssueLabels($fullPath: ID!, $issueId: String!, $labelGraphQLIds: [ID!]) {
|
|
1102
1159
|
updateIssue(input: { projectPath: $fullPath, iid: $issueId, labelIds: $labelGraphQLIds }) {
|
|
1103
1160
|
issue {
|
|
1104
1161
|
id
|
|
1105
1162
|
}
|
|
1106
1163
|
}
|
|
1107
|
-
}`;if(!(await y(this.config,{query:
|
|
1164
|
+
}`;if(!(await y(this.config,{query:i,variables:{fullPath:`${t.repository.owner.login}/${t.repository.name}`,issueId:t.number,labelGraphQLIds:o}},e)).body.data?.updateIssue?.issue?.id)throw new Error("Could not set issue labels")}async setIssueMilestone(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) {
|
|
1108
1165
|
updateIssue(input: { projectPath: $fullPath, iid: $issueId, milestoneId: $milestoneId }) {
|
|
1109
1166
|
errors
|
|
1110
1167
|
issue {
|
|
@@ -1114,14 +1171,14 @@ query GetSingleIssue($projectId: ID!, $issueNumber: String!) {
|
|
|
1114
1171
|
}
|
|
1115
1172
|
}
|
|
1116
1173
|
}
|
|
1117
|
-
}`,
|
|
1174
|
+
}`,i=await y(this.config,{query:o,variables:{fullPath:`${t.repository.owner.login}/${t.repository.name}`,issueId:t.number,milestoneId:n?.id??null}},e),a=i.body.data?.updateIssue;if(!a?.issue?.id||i.body.errors||a?.errors?.length!==0)throw new Error("Could not set milestone of issue")}async setIssueAssignees(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),i=`mutation SetIssueAssignees($fullPath: ID!, $issueId: String!, $assigneeUsernames: [String!]!) {
|
|
1118
1175
|
issueSetAssignees(input: { projectPath: $fullPath, iid: $issueId, assigneeUsernames: $assigneeUsernames }) {
|
|
1119
1176
|
errors,
|
|
1120
1177
|
issue {
|
|
1121
1178
|
id
|
|
1122
1179
|
}
|
|
1123
1180
|
}
|
|
1124
|
-
}`,u=(await y(this.config,{query:
|
|
1181
|
+
}`,u=(await y(this.config,{query:i,variables:{fullPath:`${t.repository.owner.login}/${t.repository.name}`,issueId:t.number,assigneeUsernames:o}},e)).body.data?.issueSetAssignees;if(!u?.issue?.id||u?.errors?.length!==0)throw new Error("Could not set issue assignees")}async getMilestonesForRepo(s,e={}){let{repo:{namespace:t,name:n},cursor:o}=s,i=await y(this.config,{query:`
|
|
1125
1182
|
query getLabelsForRepo(
|
|
1126
1183
|
$fullPath: ID!
|
|
1127
1184
|
$after: String
|
|
@@ -1132,7 +1189,7 @@ query getLabelsForRepo(
|
|
|
1132
1189
|
webUrl
|
|
1133
1190
|
milestones(after: $after) {
|
|
1134
1191
|
nodes {
|
|
1135
|
-
${
|
|
1192
|
+
${dt}
|
|
1136
1193
|
}
|
|
1137
1194
|
pageInfo {
|
|
1138
1195
|
endCursor
|
|
@@ -1141,7 +1198,7 @@ query getLabelsForRepo(
|
|
|
1141
1198
|
}
|
|
1142
1199
|
}
|
|
1143
1200
|
}
|
|
1144
|
-
`,variables:{fullPath:`${t}/${n}`,after:o}},e);return{pageInfo:
|
|
1201
|
+
`,variables:{fullPath:`${t}/${n}`,after:o}},e);return{pageInfo:i.body.data?.project?.milestones?.pageInfo??{endCursor:null,hasNextPage:!1},data:i.body.data?.project?.milestones?.nodes?.map(a=>mt(a,i.body.data?.project?.webUrl||""))??[]}}async getLabelsForRepo(s,e={}){let{repo:{namespace:t,name:n},cursor:o}=s,i=await y(this.config,{query:`
|
|
1145
1202
|
query getLabelsForRepo(
|
|
1146
1203
|
$fullPath: ID!
|
|
1147
1204
|
$after: String
|
|
@@ -1151,7 +1208,7 @@ query getLabelsForRepo(
|
|
|
1151
1208
|
) {
|
|
1152
1209
|
labels(after: $after) {
|
|
1153
1210
|
nodes {
|
|
1154
|
-
${
|
|
1211
|
+
${ct}
|
|
1155
1212
|
}
|
|
1156
1213
|
pageInfo {
|
|
1157
1214
|
endCursor
|
|
@@ -1160,8 +1217,8 @@ query getLabelsForRepo(
|
|
|
1160
1217
|
}
|
|
1161
1218
|
}
|
|
1162
1219
|
}
|
|
1163
|
-
`,variables:{fullPath:`${t}/${n}`,after:o}},e);return{pageInfo:
|
|
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=`
|
|
1220
|
+
`,variables:{fullPath:`${t}/${n}`,after:o}},e);return{pageInfo:i.body.data?.project?.labels?.pageInfo??{endCursor:null,hasNextPage:!1},data:i.body.data?.project?.labels?.nodes?.map(gt)??[]}}async getTreeForRepo(s,e={}){let t=j(s.repo),n=new URL(s.cursor??`${we(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)}),i=o.headers.link;return{data:o.body.map(Rs),pageInfo:{endCursor:i?i.substring(1,i.indexOf(">")):null,hasNextPage:!!i}}}};var Ps="https://api.atlassian.com/ex/jira",qe=100,ht=["assignee","comment","summary","created","creator","updated","votes","issuetype","status","labels","components","project","fixVersions","description"],Ht="/rest/api/2/search/jql",Wt="/rest/api/2/search",ft=(r,s,e,t)=>{let n=r.fields.assignee,o=!t,i=(r.fields[s?.Sprint??""]??[]).filter(a=>typeof a=="object");return{id:r.id,commentCount:r.fields.comment.comments.length,number:r.key,title:r.fields.summary,url:e?`${e}/browse/${r.key}`:null,closedDate:null,createdDate:new Date(r.fields.created),author:Ee(r.fields.creator,e,o),updatedDate:new Date(r.fields.updated),assignees:n?[Ee(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:qs(r.fields.status),statusTransitions:r.transitions?.map(ws)??[],components:r.fields.components?.map(Ss)??[],type:r.fields.issuetype.name,upvoteCount:r.fields.votes?.votes||0,labels:r.fields.labels?.map(a=>({color:null,description:null,id:null,name:a}))??[],sprints:i.map(Es),fixVersions:r.fields.fixVersions.map(Cs)}},ws=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}}},Ss=r=>({description:r.description??null,id:r.id,name:r.name}),vs=(r,s,e)=>e&&r.name?`${s}/secure/ViewProfile.jspa?name=${encodeURIComponent(r.name)}`:`${s}/jira/people/${r.accountId}`,Ee=(r,s,e)=>({id:(e?r.key:r.accountId)??"",name:r.displayName,email:r.emailAddress,avatarUrl:r.avatarUrls["48x48"],username:r.displayName,url:vs(r,s,e)}),qs=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}},Es=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}),Cs=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||Ps}/${e}`:`${s?.baseUrl||r.baseUrl}`,Ce=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},Le=async(r,s,e,t={})=>{let{number:n,resourceId:o,fields:i}=s||{},a=await r.request({url:`${B(r,t,o)}/rest/api/2/issue/${n}?fields=${ht.join(",")}&expand=transitions`,headers:h(t.token||r.token)});return{data:ft(a.body,i,e,o)}},De=async(r,s,e,t={})=>{let{cursor:n,resourceId:o,labelNames:i,fields:a}=s||{},u=["statusCategory != Done",`(creator = currentUser() OR assignee = currentUser()
|
|
1221
|
+
OR comment ~ currentUser() OR summary ~ currentUser() OR description ~ currentUser())`];i&&i.forEach(E=>u.push(`labels = "${E}"`));let l=`${u.join(" AND ")} ORDER BY updated DESC`,p=!o,d=p?Wt:Ht,c=new URL(`${B(r,t,o)}${d}`);c.searchParams.set("jql",l),c.searchParams.set("maxResults",qe.toString()),c.searchParams.set("fields",ht.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(E=>ft(E,a,e,o)),b=!1,I="";return p?(b=m.length==qe,I=(parseInt(n??"0",10)+m.length).toString()):(b=!!g.body.nextPageToken,I=g.body.nextPageToken??null),{data:m,pageInfo:{hasNextPage:b,endCursor:I}}},Jt=async(r,s,e,t={})=>{let{cursor:n,resourceId:o,jql:i,fields:a}=s||{},u=[...ht],l=a?.Sprint;l&&u.push(l);let p=!o,d=p?Wt:Ht,c=new URL(`${B(r,t,o)}${d}`);c.searchParams.set("jql",i.join(" AND ")),c.searchParams.set("maxResults",qe.toString()),c.searchParams.set("fields",u.join(",")),c.searchParams.set("expand","transitions"),n&&(p?c.searchParams.set("startAt",n):c.searchParams.set("nextPageToken",n));let g=await r.request({url:c.toString(),headers:h(t.token||r.token)}),m=g.body.issues.map(E=>ft(E,a,e,o)),b=!1,I="";return p?(b=m.length==qe,I=(parseInt(n??"0",10)+m.length).toString()):(b=!!g.body.nextPageToken,I=g.body.nextPageToken??null),{data:m,pageInfo:{hasNextPage:b,endCursor:I}}},$e=async(r,s,e,t={})=>{let{assigneeLogins:n,authorLogin:o,mentionLogin:i,labelNames:a,cursor:u,projectKey:l,resourceId:p,fields:d}=s||{},c=[`project = "${l}"`,"statusCategory != Done"];return o&&c.push(`creator in ("${o}")`),n&&n.length!==0&&c.push(`assignee in ("${n.join('", "')}")`),i&&c.push(`comment ~ "${i}"`),a&&a.forEach(g=>c.push(`labels = "${g}"`)),Jt(r,{resourceId:p,jql:c,cursor:u,fields:d},e,t)},Ue=async(r,s,e,t={})=>{let{assigneeLogins:n,authorLogin:o,mentionLogin:i,labelNames:a,cursor:u,projectKeys:l,resourceId:p,fields:d}=s||{},g=["("+l.map(m=>`project = "${m}"`).join(" OR ")+")","statusCategory != Done"];return o&&g.push(`creator in ("${o}")`),n&&n.length!==0&&g.push(`assignee in ("${n.join('", "')}")`),i&&g.push(`comment ~ "${i}"`),a&&a.forEach(m=>g.push(`labels = "${m}"`)),Jt(r,{resourceId:p,jql:g,fields:d,cursor:u},e,t)},Ae=async(r,s,e={})=>{let{issue:t,labels:n}=s;if(!t.project)throw new Error('Jira requires a "project" for this function.');let o={fields:{labels:n.map(i=>i.name)}};await r.request({method:"PUT",url:`${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,components:n}=s;if(!t.project)throw new Error('Jira requires a "project" for this function.');let o={fields:{components:n.map(i=>({id:i.id}))}};await r.request({method:"PUT",url:`${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"}})},Te=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"}})},Oe=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 ie="https://api.atlassian.com/ex/jira",Rt=100,te=class extends U{constructor(){super(...arguments);this._resourceUrlCache={};this._issueFieldsCache={}}async getIssueFieldsForResource(e,t={}){if(!this._issueFieldsCache[e.resourceId]){let n=await Ce(this.config,e,t);this._issueFieldsCache[e.resourceId]=n.reduce((o,i)=>({...o,[i.name]:i.id}),{})}return this._issueFieldsCache[e.resourceId]??null}async getResourceUrl(e,t={}){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||ie}/${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,i=t.body.map(a=>(o&&(o[a.id]=a.url),{avatarUrl:a.avatarUrl,id:a.id,name:a.name,url:a.url}));return n&&(this._resourceUrlCache[n]=o),{data:i}}async getJiraProjectsForResource(e,t={}){let n=new URL(`${t.baseUrl||ie}/${e.resourceId}/rest/api/2/project/search`);n.searchParams.set("maxResults",Rt.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(i=>({id:i.id,key:i.key,name:i.name,resourceId:e.resourceId}))}}async getJiraProjectsForResources(e,t={}){let n=[];return await Promise.all(e.resourceIds.map(async o=>{try{return await Ct(i=>this.getJiraProjectsForResource({resourceId:o,cursor:i},t))}catch{return[]}})).then((...o)=>{o.forEach(i=>{n=n.concat(...i)})}),{data:n}}async getAccountsForJiraProject(e,t={}){let{resourceId:n,projectKey:o,cursor:i}=e,a=await this.getResourceUrl({resourceId:n},t),u=new URL(`${t.baseUrl||ie}/${n}/rest/api/2/user/assignable/search`);u.searchParams.set("maxResults",Rt.toString()),i&&u.searchParams.set("startAt",i),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:((i?parseInt(i):0)+l.body.length).toString()},data:l.body.filter(p=>p.accountType!=="app"&&p.active).map(p=>Ee(p,a,!1))}}async getComponentsForJiraProject(e,t={}){return await Oe(this.config,e,t)}async getIssue(e,t={}){let n=await this.getIssueFieldsForResource({resourceId:e.resourceId},t),o=await this.getResourceUrl({resourceId:e.resourceId},t);return await Le(this.config,{...e,fields:n},o,t)}async getIssuesForProject(e,t={}){let n=await this.getIssueFieldsForResource({resourceId:e.resourceId},t),o=await this.getResourceUrl({resourceId:e.resourceId},t);return await $e(this.config,{...e,fields:n},o,t)}async getIssuesForProjects(e,t={}){let n=await this.getIssueFieldsForResource({resourceId:e.resourceId},t),o=await this.getResourceUrl({resourceId:e.resourceId},t);return await Ue(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 De(this.config,{...e,fields:n},o,t)}async setIssueStatus(e,t={}){await Te(this.config,e,t)}async setIssueAssignee(e,t={}){let{issue:n,assignee:o}=e;if(!n.project)throw new Error('Jira Cloud requires a "project" for this function.');if(!n.project.resourceId)throw new Error('Jira Cloud requires a project "resourceId" for this function.');let i={accountId:o?.id};await this.config.request({method:"PUT",url:`${t.baseUrl||ie}/${n.project.resourceId}/rest/api/2/issue/${n.id}/assignee`,body:JSON.stringify(i),headers:{...h(t.token||this.config.token),"Content-Type":"application/json"}})}async setIssueComponents(e,t={}){await Ge(this.config,e,t)}async setIssueLabels(e,t={}){await Ae(this.config,e,t)}async getLabelsForResource(e,t={}){let{resourceId:n,cursor:o}=e,i=new URL(`${t.baseUrl||ie}/${n}/rest/api/2/label`);i.searchParams.set("maxResults",Rt.toString()),o&&i.searchParams.set("startAt",o);let a=await this.config.request({url:i.toString(),headers:h(t.token||this.config.token)});return{pageInfo:{hasNextPage:!a.body.isLast,endCursor:(a.body.startAt+a.body.values.length).toString()},data:a.body.values.map(u=>({color:null,description:null,id:null,name:u}))}}};var re=class extends D{constructor(){super(...arguments);this._issueFieldsCache={}}async getIssueFieldsForResource(e={}){let t=e?.baseUrl||this.config.baseUrl||"";if(!this._issueFieldsCache[t]){let n=await Ce(this.config,{},e);this._issueFieldsCache[t]=n.reduce((o,i)=>({...o,[i.name]:i.id}),{})}return this._issueFieldsCache[t]??null}async getCurrentUser(e={}){let t=await this.config.request({url:`${e?.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 Le(this.config,{...e,fields:o},n,t)}async getIssuesForProject(e,t={}){let n=e.resourceUrl||t.baseUrl||this.config.baseUrl;if(!n)throw new Error('Jira Server requires a "resourceUrl" or "baseUrl" for this function.');let o=await this.getIssueFieldsForResource(t);return await $e(this.config,{...e,fields:o},n,t)}async getIssuesForProjects(e,t={}){let n=e.resourceUrl||t.baseUrl||this.config.baseUrl;if(!n)throw new Error('Jira Server requires a "resourceUrl" or "baseUrl" for this function.');let o=await this.getIssueFieldsForResource(t);return await Ue(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 De(this.config,{...e,fields:o},n,t)}async setIssueStatus(e,t={}){await Te(this.config,e,t)}async setIssueLabels(e,t={}){await Ae(this.config,e,t)}async setIssueComponents(e,t={}){await Ge(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 Oe(this.config,e,t)}};var T="https://api.trello.com",Ls=1e3,Ds=r=>({id:r.id,username:r.username,url:r.url,name:r.fullName,email:r.email,avatarUrl:r.avatarUrl}),$s=(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}))}},se=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:Ds(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(i=>({id:i.id,name:i.fullName,username:i.username,email:null,avatarUrl:null,url:null}))}}async getIssuesForBoard(s,e={}){let t=["-is:archived","sort:edited"],{appKey:n,boardId:o,filterText:i,assigneeLogins:a,labelNamesOrColors:u,trelloBoardListsById:l}=s||{};a&&t.push("@me"),u&&u.forEach(c=>t.push(`label:"${c}"`));let p=`${i?`${i}`:""}${t.join(" ")} board:${o}`;return{data:(await this.config.request({url:`${e.baseUrl||T}/1/search?key=${n}&query=${p}&cards_limit=${Ls}&token=${e.token||this.config.token}&card_members=true`,headers:h(e.token||this.config.token)})).body.cards.map(c=>$s(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 i=`idList=${o.id}`;if(!(await this.updateIssue(t,n,i,e)).body.id)throw new Error("Could not set issue status")}async setIssueAssignees(s,e={}){let{appKey:t,issue:n,assignees:o}=s,i=o.map(l=>l.id),a=`idMembers=${encodeURIComponent(i.join(","))}`;if(!(await this.updateIssue(t,n,a,e)).body.id)throw new Error("Could not set issue status")}async setIssueLabels(s,e={}){let{appKey:t,issue:n,labels:o}=s,i=o.map(u=>u.id).join(",");if(!(await this.config.request({method:"PUT",url:`${e.baseUrl||T}/1/cards/${n.id}?key=${t}&token=${e.token||this.config.token}&idLabels=${encodeURIComponent(i)}`,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(i=>({color:i.color,description:null,id:i.id,name:i.name}))}}};var bt=100,xe=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 i=o.body;if(i.errors)throw new Error(`Linear GraphQL errors: ${i.errors.map(a=>a.message).join(", ")}`);return i.data},It=r=>r?r instanceof Date?r:new Date(r):null,Us=`
|
|
1165
1222
|
id
|
|
1166
1223
|
name
|
|
1167
1224
|
description
|
|
@@ -1169,11 +1226,11 @@ OR comment ~ currentUser() OR summary ~ currentUser() OR description ~ currentUs
|
|
|
1169
1226
|
startDate
|
|
1170
1227
|
targetDate
|
|
1171
1228
|
url
|
|
1172
|
-
`,
|
|
1229
|
+
`,Vt=r=>({id:r.id,name:r.name,description:r.description??null,state:r.state,startDate:It(r.startDate),targetDate:It(r.targetDate),url:r.url}),Kt=async(r,s,e)=>{let t=`
|
|
1173
1230
|
query GetProjects($first: Int!, $after: String) {
|
|
1174
1231
|
projects(first: $first, after: $after) {
|
|
1175
1232
|
nodes {
|
|
1176
|
-
${
|
|
1233
|
+
${Us}
|
|
1177
1234
|
}
|
|
1178
1235
|
pageInfo {
|
|
1179
1236
|
hasNextPage
|
|
@@ -1181,7 +1238,7 @@ OR comment ~ currentUser() OR summary ~ currentUser() OR description ~ currentUs
|
|
|
1181
1238
|
}
|
|
1182
1239
|
}
|
|
1183
1240
|
}
|
|
1184
|
-
`;return(await _(r,s,t,{first:
|
|
1241
|
+
`;return(await _(r,s,t,{first:bt,after:e})).projects},As=`
|
|
1185
1242
|
id
|
|
1186
1243
|
name
|
|
1187
1244
|
number
|
|
@@ -1189,11 +1246,11 @@ OR comment ~ currentUser() OR summary ~ currentUser() OR description ~ currentUs
|
|
|
1189
1246
|
startsAt
|
|
1190
1247
|
endsAt
|
|
1191
1248
|
completedAt
|
|
1192
|
-
`,
|
|
1249
|
+
`,Xt=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:It(r.completedAt),url:""}),Zt=async(r,s,e)=>{let t=`
|
|
1193
1250
|
query GetCycles($first: Int!, $after: String) {
|
|
1194
1251
|
cycles(first: $first, after: $after) {
|
|
1195
1252
|
nodes {
|
|
1196
|
-
${
|
|
1253
|
+
${As}
|
|
1197
1254
|
}
|
|
1198
1255
|
pageInfo {
|
|
1199
1256
|
hasNextPage
|
|
@@ -1201,16 +1258,16 @@ OR comment ~ currentUser() OR summary ~ currentUser() OR description ~ currentUs
|
|
|
1201
1258
|
}
|
|
1202
1259
|
}
|
|
1203
1260
|
}
|
|
1204
|
-
`;return(await _(r,s,t,{first:
|
|
1261
|
+
`;return(await _(r,s,t,{first:bt,after:e})).cycles},Gs=`
|
|
1205
1262
|
id
|
|
1206
1263
|
name
|
|
1207
1264
|
color
|
|
1208
1265
|
description
|
|
1209
|
-
`,
|
|
1266
|
+
`,Yt=r=>({id:r.id,name:r.name,color:r.color,description:r.description??null}),er=async(r,s,e)=>{let t=`
|
|
1210
1267
|
query GetLabels($first: Int!, $after: String) {
|
|
1211
1268
|
projectLabels(first: $first, after: $after) {
|
|
1212
1269
|
nodes {
|
|
1213
|
-
${
|
|
1270
|
+
${Gs}
|
|
1214
1271
|
}
|
|
1215
1272
|
pageInfo {
|
|
1216
1273
|
hasNextPage
|
|
@@ -1218,36 +1275,36 @@ OR comment ~ currentUser() OR summary ~ currentUser() OR description ~ currentUs
|
|
|
1218
1275
|
}
|
|
1219
1276
|
}
|
|
1220
1277
|
}
|
|
1221
|
-
`;return(await _(r,s,t,{first:
|
|
1278
|
+
`;return(await _(r,s,t,{first:bt,after:e})).projectLabels};var ae=(i=>(i[i.None=0]="None",i[i.Assignee=1]="Assignee",i[i.Creator=2]="Creator",i[i.Mention=3]="Mention",i[i.MentionInDescription=4]="MentionInDescription",i[i.MentionInComments=5]="MentionInComments",i))(ae||{});function tr(r,s){return r?`${ae[r]}:${s||""}`:s??null}function rr(r){if(!r)return{category:0};let[s,e]=r.split(":");return s in ae?{category:ae[s],cursor:e||void 0}:{category:0,cursor:r}}var sr=100;function Ne(r){return r?r instanceof Date?r:new Date(r):null}var ir=`
|
|
1222
1279
|
id
|
|
1223
1280
|
name
|
|
1224
1281
|
key
|
|
1225
1282
|
icon
|
|
1226
|
-
`;function
|
|
1283
|
+
`;function Ts(r){return{id:r.id,name:r.name,key:r.key,iconUrl:r.icon}}var nr=`
|
|
1227
1284
|
id
|
|
1228
1285
|
name
|
|
1229
1286
|
avatarUrl
|
|
1230
|
-
`;function
|
|
1287
|
+
`;function or(r){return r?{id:r.id,name:r.name,username:r.name,email:null,avatarUrl:r.avatarUrl??null,url:null}:null}var Os=`
|
|
1231
1288
|
id
|
|
1232
1289
|
name
|
|
1233
|
-
`;function
|
|
1290
|
+
`;function xs(r,s){if(r)return{id:r.id,name:r.name,key:s?.key||null,namespace:null,resourceId:s?.id||null}}var ks=`
|
|
1234
1291
|
id
|
|
1235
1292
|
sortOrder
|
|
1236
1293
|
name
|
|
1237
1294
|
description
|
|
1238
1295
|
status
|
|
1239
1296
|
targetDate
|
|
1240
|
-
`;function
|
|
1297
|
+
`;function Ns(r){return r?{id:r.id,number:r.sortOrder,title:r.name,description:r.description??null,isOpen:r.status!=="done",url:"",startDate:null,dueDate:Ne(r.targetDate)}:null}function _s(r){switch(r){case"completed":case"canceled":return"DONE";case"started":return"IN_PROGRESS";default:return"TO_DO"}}var Fs=`
|
|
1241
1298
|
id
|
|
1242
1299
|
name
|
|
1243
1300
|
color
|
|
1244
1301
|
type
|
|
1245
|
-
`;function
|
|
1302
|
+
`;function Qs(r){return r?{id:r.id,name:r.name,color:r.color,category:_s(r.type)}:null}var Pt=`
|
|
1246
1303
|
creator {
|
|
1247
|
-
${
|
|
1304
|
+
${nr}
|
|
1248
1305
|
}
|
|
1249
1306
|
assignee {
|
|
1250
|
-
${
|
|
1307
|
+
${nr}
|
|
1251
1308
|
}
|
|
1252
1309
|
archivedAt
|
|
1253
1310
|
createdAt
|
|
@@ -1255,32 +1312,32 @@ OR comment ~ currentUser() OR summary ~ currentUser() OR description ~ currentUs
|
|
|
1255
1312
|
id
|
|
1256
1313
|
identifier
|
|
1257
1314
|
project {
|
|
1258
|
-
${
|
|
1315
|
+
${Os}
|
|
1259
1316
|
}
|
|
1260
1317
|
team {
|
|
1261
|
-
${
|
|
1318
|
+
${ir}
|
|
1262
1319
|
}
|
|
1263
1320
|
state {
|
|
1264
|
-
${
|
|
1321
|
+
${Fs}
|
|
1265
1322
|
}
|
|
1266
1323
|
title
|
|
1267
1324
|
updatedAt
|
|
1268
1325
|
url
|
|
1269
1326
|
projectMilestone {
|
|
1270
|
-
${
|
|
1327
|
+
${ks}
|
|
1271
1328
|
}
|
|
1272
|
-
`;async function
|
|
1329
|
+
`;async function yt(r){return{author:or(await r.creator),assignees:[or(await r.assignee)].filter(s=>s!=null),commentCount:null,closedDate:Ne(r.archivedAt),createdDate:Ne(r.createdAt),description:r.description??null,id:r.id,labels:[],number:r.identifier,repository:null,project:xs(await r.project,await r.team),state:Qs(await r.state),title:r.title,type:null,updatedDate:Ne(r.updatedAt),upvoteCount:null,url:r.url,milestone:Ns(await r.projectMilestone)}}var ke=`
|
|
1273
1330
|
nodes {
|
|
1274
|
-
${
|
|
1331
|
+
${Pt}
|
|
1275
1332
|
}
|
|
1276
1333
|
pageInfo {
|
|
1277
1334
|
hasNextPage
|
|
1278
1335
|
endCursor
|
|
1279
1336
|
}
|
|
1280
|
-
`,
|
|
1337
|
+
`,_e=class extends U{async fetchIssue(s,e){let t=`
|
|
1281
1338
|
query GetIssue($identifier: String!) {
|
|
1282
1339
|
issue(id: $identifier) {
|
|
1283
|
-
${
|
|
1340
|
+
${Pt}
|
|
1284
1341
|
}
|
|
1285
1342
|
}
|
|
1286
1343
|
`;return(await _(this.config,e,t,{identifier:s})).issue}async fetchOrganization(s){let e=`
|
|
@@ -1295,7 +1352,7 @@ OR comment ~ currentUser() OR summary ~ currentUser() OR description ~ currentUs
|
|
|
1295
1352
|
query GetTeams {
|
|
1296
1353
|
teams {
|
|
1297
1354
|
nodes {
|
|
1298
|
-
${
|
|
1355
|
+
${ir}
|
|
1299
1356
|
}
|
|
1300
1357
|
}
|
|
1301
1358
|
}
|
|
@@ -1308,11 +1365,11 @@ OR comment ~ currentUser() OR summary ~ currentUser() OR description ~ currentUs
|
|
|
1308
1365
|
displayName
|
|
1309
1366
|
}
|
|
1310
1367
|
}
|
|
1311
|
-
`;return(await _(this.config,s,e)).viewer}async getIssue(s,e={}){let t=await this.fetchIssue(s.number,e);return{data:await
|
|
1368
|
+
`;return(await _(this.config,s,e)).viewer}async getIssue(s,e={}){let t=await this.fetchIssue(s.number,e);return{data:await yt(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(Ts)}}async getProjects(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 getCycles(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 getLabels(s={},e={}){let t=await er(this.config,e,s.cursor??void 0);return{data:t.nodes.map(Yt),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}=rr(t),i=await this.fetchViewer(e),a,u,l=new xe,p=async(d,c)=>{if(u||n>d)return;let g=await c(Math.max(sr-l.length,1),n===d?o:void 0);if(!g)return;let m=await ze(g.nodes.map(yt));l.push(...m),g.pageInfo.hasNextPage&&(a=d,u=g.pageInfo.endCursor)};return await p(1,async(d,c)=>(await this.rawRequest(e,`
|
|
1312
1369
|
query GetAssignedIssues($first: Int!, $after: String) {
|
|
1313
1370
|
viewer {
|
|
1314
1371
|
issues: assignedIssues(first: $first, after: $after) {
|
|
1315
|
-
${
|
|
1372
|
+
${ke}
|
|
1316
1373
|
}
|
|
1317
1374
|
}
|
|
1318
1375
|
}
|
|
@@ -1320,7 +1377,7 @@ OR comment ~ currentUser() OR summary ~ currentUser() OR description ~ currentUs
|
|
|
1320
1377
|
query GetCreatedIssues($first: Int!, $after: String) {
|
|
1321
1378
|
viewer {
|
|
1322
1379
|
issues: createdIssues(first: $first, after: $after) {
|
|
1323
|
-
${
|
|
1380
|
+
${ke}
|
|
1324
1381
|
}
|
|
1325
1382
|
}
|
|
1326
1383
|
}
|
|
@@ -1332,20 +1389,20 @@ OR comment ~ currentUser() OR summary ~ currentUser() OR description ~ currentUs
|
|
|
1332
1389
|
filter: {
|
|
1333
1390
|
or: [{
|
|
1334
1391
|
searchableContent: {
|
|
1335
|
-
contains: "${
|
|
1392
|
+
contains: "${i.displayName}"
|
|
1336
1393
|
}
|
|
1337
1394
|
},{
|
|
1338
1395
|
searchableContent: {
|
|
1339
|
-
contains: "${
|
|
1396
|
+
contains: "${i.email}"
|
|
1340
1397
|
}
|
|
1341
1398
|
},{
|
|
1342
1399
|
searchableContent: {
|
|
1343
|
-
contains: "${
|
|
1400
|
+
contains: "${i.name}"
|
|
1344
1401
|
}
|
|
1345
1402
|
}]
|
|
1346
1403
|
}
|
|
1347
1404
|
){
|
|
1348
|
-
${
|
|
1405
|
+
${ke}
|
|
1349
1406
|
}
|
|
1350
1407
|
}
|
|
1351
1408
|
`,{first:d,after:c})).data?.issues),await p(5,async(d,c)=>{let m=(await this.rawRequest(e,`
|
|
@@ -1356,22 +1413,22 @@ OR comment ~ currentUser() OR summary ~ currentUser() OR description ~ currentUs
|
|
|
1356
1413
|
filter: {
|
|
1357
1414
|
or: [{
|
|
1358
1415
|
body: {
|
|
1359
|
-
contains: "${
|
|
1416
|
+
contains: "${i.displayName}"
|
|
1360
1417
|
}
|
|
1361
1418
|
},{
|
|
1362
1419
|
body: {
|
|
1363
|
-
contains: "${
|
|
1420
|
+
contains: "${i.email}"
|
|
1364
1421
|
}
|
|
1365
1422
|
},{
|
|
1366
1423
|
body: {
|
|
1367
|
-
contains: "${
|
|
1424
|
+
contains: "${i.name}"
|
|
1368
1425
|
}
|
|
1369
1426
|
}]
|
|
1370
1427
|
}
|
|
1371
1428
|
){
|
|
1372
1429
|
nodes {
|
|
1373
1430
|
issue {
|
|
1374
|
-
${
|
|
1431
|
+
${Pt}
|
|
1375
1432
|
}
|
|
1376
1433
|
}
|
|
1377
1434
|
pageInfo {
|
|
@@ -1380,10 +1437,10 @@ OR comment ~ currentUser() OR summary ~ currentUser() OR description ~ currentUs
|
|
|
1380
1437
|
}
|
|
1381
1438
|
}
|
|
1382
1439
|
}
|
|
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:
|
|
1440
|
+
`,{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:tr(a,u)}}}async getIssues(s,e={}){let{teams:t,projects:n,labels:o,cursor:i}=s,a=[];if(t&&t.length>0){let g=t.map(m=>`"${m}"`).join(", ");a.push(`team: { id: { in: [${g}] } }`)}if(n&&n.length>0){let g=n.map(m=>`"${m}"`).join(", ");a.push(`project: { id: { in: [${g}] } }`)}if(o&&o.length>0){let g=o.map(m=>`"${m}"`).join(", ");a.push(`labels: { name: { in: [${g}] } }`)}let u=a.length>0?`filter: { ${a.join(", ")} }`:"",l=`
|
|
1384
1441
|
query GetIssues($first: Int!, $after: String) {
|
|
1385
1442
|
issues(first: $first, after: $after${u?", ":""}${u}) {
|
|
1386
|
-
${
|
|
1443
|
+
${ke}
|
|
1387
1444
|
}
|
|
1388
1445
|
}
|
|
1389
|
-
`,d=(await this.rawRequest(e,l,{first:
|
|
1446
|
+
`,d=(await this.rawRequest(e,l,{first:sr,after:i})).data?.issues;return d?{data:await ze(d.nodes.map(yt)),pageInfo:{hasNextPage:d.pageInfo.hasNextPage,endCursor:d.pageInfo.endCursor??null}}:{data:[],pageInfo:{hasNextPage:!1,endCursor:null}}}};var ar=r=>{let s={request:r?.request};return{azureDevOps:new J({...s,...r?.azureDevOps}),bitbucket:new V({...s,...r?.bitbucket}),bitbucketServer:new K({...s,...r?.bitbucketServer}),github:new Z({...s,...r?.github}),gitlab:new ee({...s,...r?.gitlab}),jira:new te({...s,...r?.jira}),jiraServer:new re({...s,...r?.jiraServer}),linear:new _e({...s,...r?.linear}),trello:new se({...s,...r?.trello})}};var ur=(i=>(i.Conflicts="conflicts",i.Failure="failure",i.NotSet="notSet",i.Queued="queued",i.RejectedByPolicy="rejectedByPolicy",i.Succeeded="succeeded",i))(ur||{});var lr=(e=>(e.Zero="0",e.One="1",e))(lr||{}),pr=(e=>(e.PullRequest="pr",e.Issue="issue",e))(pr||{}),dr=(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))(dr||{});var cr=(e=>(e.Completed="COMPLETED",e.NotPlanned="NOT_PLANNED",e))(cr||{});var js=ar;
|