@gitkraken/provider-apis 0.51.0 → 0.52.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 +8 -0
- package/dist/index.js +175 -175
- package/dist/index.provider-utils.js +1 -1
- package/dist/index.providers.js +168 -168
- package/dist/providers/azureDevops/azureDevOps.d.ts +2 -0
- package/dist/providers/bitbucket/bitbucket.d.ts +1 -0
- package/dist/providers/bitbucketServer/bitbucketServer.d.ts +1 -0
- package/dist/providers/jira/jira.d.ts +2 -0
- package/dist/providers/trello/trello.d.ts +1 -0
- package/dist/types/exportedTypes/types.d.ts +38 -0
- package/dist/utils.d.ts +44 -2
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
"use strict";var Ot=Object.defineProperty;var ln=Object.getOwnPropertyDescriptor;var pn=Object.getOwnPropertyNames;var dn=Object.prototype.hasOwnProperty;var H=(s,t)=>{for(var e in t)Ot(s,e,{get:t[e],enumerable:!0})},cn=(s,t,e,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of pn(t))!dn.call(s,n)&&n!==e&&Ot(s,n,{get:()=>t[n],enumerable:!(r=ln(t,n))||r.enumerable});return s};var mn=s=>cn(Ot({},"__esModule",{value:!0}),s);var vi={};H(vi,{AzureDevOps:()=>Re,AzureDevopsUtils:()=>ht,Bitbucket:()=>Ie,BitbucketServer:()=>be,BitbucketServerUtils:()=>We,BitbucketUtils:()=>ft,EntityIdentifierProviderType:()=>N,EntityIdentifierUtils:()=>Dt,EntityType:()=>j,EntityVersion:()=>B,GitBuildStatusStage:()=>xr,GitBuildStatusState:()=>De,GitDiffLineType:()=>_t,GitHub:()=>ye,GitHubIssueCloseReason:()=>sn,GitHubUtils:()=>$t,GitIssueState:()=>ce,GitLab:()=>we,GitLabUtils:()=>Lt,GitMergeStrategy:()=>fe,GitProviderUtils:()=>At,GitPullRequestMergeableState:()=>ee,GitPullRequestReviewState:()=>V,GitPullRequestState:()=>oe,GraphQLErrors:()=>I,Jira:()=>qe,JiraServer:()=>ve,JiraUtils:()=>Gt,Linear:()=>Ee,PullRequestAsyncStatus:()=>rn,Trello:()=>Se,TrelloUtils:()=>Ut,Utils:()=>qi,default:()=>wi,isFetch:()=>Be});module.exports=mn(vi);var Jr=require("diff");var xr=(n=>(n.Build="build",n.Production="production",n.Staging="staging",n.Test="test",n))(xr||{}),De=(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))(De||{}),fe=(o=>(o.MergeCommit="MERGE_COMMIT",o.Rebase="REBASE",o.RebaseThenMergeCommit="REBASE_THEN_MERGE_COMMIT",o.FastForward="FAST_FORWARD",o.Squash="SQUASH",o))(fe||{}),oe=(r=>(r.Open="OPEN",r.Closed="CLOSED",r.Merged="MERGED",r))(oe||{}),V=(n=>(n.Approved="APPROVED",n.ChangesRequested="CHANGES_REQUESTED",n.Commented="COMMENTED",n.ReviewRequested="REVIEW_REQUESTED",n))(V||{}),ee=(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))(ee||{}),_t=(r=>(r.ADDED="ADDED",r.DELETED="DELETED",r.UNMODIFIED="UNMODIFIED",r))(_t||{});var Nr={APPROVED:0,COMMENTED:1,REVIEW_REQUESTED:2,CHANGES_REQUESTED:3},J=s=>!s||s.length===0?null:s.reduce((t,e)=>Nr[e.state]>Nr[t]?e.state:t,"APPROVED"),Ne=(s,t)=>s.name||s.username||s.email||t,de=s=>{let t=Object.values(s).map(e=>e.name).sort((e,r)=>e.localeCompare(r));return Object.values(s).forEach(e=>{e.priority!==-1&&(e.priority=t.indexOf(e.name))}),s};var R=(s,t)=>{let e={};return s&&(e.Authorization=`${t?"Basic":"Bearer"} ${s}`),e},Br=s=>s?s.reduce((t,e)=>(t[e]=!0,t),{}):void 0,ie=(s,t,e)=>!s||t.some(r=>s[r])?e:"",jr=async s=>{let t=[],e=!0,r;for(;e;){let n=await s(r);t=t.concat(n.data),e=!!n?.pageInfo?.hasNextPage,r=n?.pageInfo?.endCursor||n?.pageInfo?.nextPage}return t};async function kt(s){return(await Promise.allSettled(s)).map(e=>gn(e)).filter(e=>e!=null)}var L=(s,{fallback:t,max:e})=>!s||s<=0?t:e===void 0?s:Math.min(s,e),x=(s,t)=>{if(!t||t.length===0)return s;let e=new Set(t);return s.filter(r=>e.has(r.state))};function gn(s,t=void 0){return s?.status==="fulfilled"?s.value:t}async function Qr(s,t,e){if(!Number.isFinite(t)||!Number.isInteger(t)||t<=0)throw new Error("batchSize must be a positive integer");for(let r=0;r<s.length;r+=t){let n=s.slice(r,r+t);await Promise.all(n.map(e))}}var ce=(e=>(e.Open="OPEN",e.Closed="CLOSED",e))(ce||{});var xt=(a=>(a[a.Unknown=0]="Unknown",a[a.Active=1]="Active",a[a.Fixed=2]="Fixed",a[a.WontFix=3]="WontFix",a[a.Closed=4]="Closed",a[a.ByDesign=5]="ByDesign",a[a.Pending=6]="Pending",a))(xt||{});var $=100;var Fr=globalThis.fetch;var hn=async s=>{let t=s.headers.get("content-type")||"",e=null;if(t.startsWith("application/json")){let o=await s.text();e=o.trim().length>0?JSON.parse(o):null}else if(t.startsWith("text/")||t===""||t.startsWith("application/vnd.github.diff")||t.startsWith("application/vnd.github.patch"))e=await s.text();else if(t.startsWith("application/vnd.github.raw+json")||t.startsWith("application/octet-stream"))e=await s.arrayBuffer();else throw new Error(`Unsupported content-type: ${t}`);let r={};s.headers.forEach((o,i)=>{r[i]=o});let n={body:e,headers:r,status:s.status,statusText:s.statusText};if(!s.ok){let o=new Error(s.statusText);throw Object.assign(o,{response:n}),o}return n},Nt=s=>async({url:t,...e})=>{let r=await s(t,e);return hn(r)};var Be=(s,t=!1)=>s.name==="fetch"||t;var M=class{constructor(t){let e=t?.request||Fr;this.config={...t,request:Be(e,t?.forceIsFetch)?Nt(e):e}}updateConfig(t){this.config={...this.config,...t,request:t.request&&Be(t.request,t?.forceIsFetch??this.config.forceIsFetch)?Nt(t.request):this.config.request}}},Q=class extends M{};var fn="https://app.vssps.visualstudio.com/_apis",Rn="https://vssps.dev.azure.com/",In="https://dev.azure.com",q=(s,t={})=>R(t.token||s.token,t.isPAT||s.isPAT),zr=s=>s.url.replace("/_apis/git/repositories/","/_git/").replace(`/${s.repository.project.id}/`,`/${encodeURIComponent(s.repository.project.name)}/`).replace(`/${s.repository.id}/`,`/${encodeURIComponent(s.repository.name)}/`).replace("/pullRequests/","/pullrequest/"),Bt=(s,t)=>{let e=t.baseUrl||s.baseUrl||fn;return e=e.replace(/\/$/,""),e},C=(s,t)=>{let e=t.baseUrl||s.baseUrl||In;return e=e.replace(/\/$/,""),e},jt=(s,t)=>{let e=t.baseUrl||s.baseUrl||Rn;return e=e.replace(/\/$/,""),e};var bn={active:"OPEN",completed:"MERGED",abandoned:"CLOSED"},yn={OPEN:"active",MERGED:"completed",CLOSED:"abandoned"},je=100,Pn=200,wn=200,Mr=s=>{if(!s||s.length===0)return"active";let t=Array.from(new Set(s.map(e=>yn[e])));return t.length===1?t[0]:"all"},qn=s=>{if(!s||s.length===0)return["[Microsoft.VSTS.Common.ClosedDate] = ''","[Microsoft.VSTS.Common.ResolvedDate] = ''"];let t=new Set(s),e=t.has("OPEN"),r=t.has("CLOSED");return e&&r?[]:r?["([Microsoft.VSTS.Common.ClosedDate] <> '' OR [Microsoft.VSTS.Common.ResolvedDate] <> '')"]:["[Microsoft.VSTS.Common.ClosedDate] = ''","[Microsoft.VSTS.Common.ResolvedDate] = ''"]},vn=s=>{if(typeof s!="string")return s;let t=s.charAt(0).toUpperCase()+s.slice(1);return xt[t]??0},En=new Set([2,3,4,5]),Sn={10:"APPROVED",5:"APPROVED",0:"REVIEW_REQUESTED",[-5]:"CHANGES_REQUESTED",[-10]:"CHANGES_REQUESTED"},me=s=>({id:s.id,name:s.displayName??null,username:(s.uniqueName||s.displayName)??null,email:null,avatarUrl:s.imageUrl??null,url:null}),Qe=s=>s.startsWith("refs/heads/")?s.replace("refs/heads/",""):s,Cn=s=>{switch(s){case"conflicts":return"CONFLICTS";case"failure":return"FAILING_CHECKS";case"rejectedByPolicy":return"BLOCKED";case"succeeded":return"MERGEABLE";case"notSet":case"queued":default:return"UNKNOWN"}},Qt=(s,t,e,r,n,o)=>`${s}|${t}|${e}|${r}|${n}|${o}`,Wr=s=>{let t=s.split("|");if(t.length!==6)throw new Error("Invalid Azure comment ID format");return{namespace:t[0],project:t[1],repoName:t[2],prId:t[3],threadId:t[4],commentId:t[5]}},Hr=(s,t,e,r,n)=>`${s}|${t}|${e}|${r}|${n}`,Ft=s=>{let t=s.split("|");if(t.length!==5)throw new Error("Invalid Azure thread ID format");return{namespace:t[0],project:t[1],repoName:t[2],prId:t[3],threadId:t[4]}},Ae=(s,t,e)=>{let r=!!t.forkSource,n=[],o=[];return t.reviewers.forEach(i=>{let a={reviewer:me(i),state:Sn[i.vote??0]||"REVIEW_REQUESTED"};i.isRequired&&n.push(a),o.push(a)}),{id:t.pullRequestId.toString(),title:t.title,description:t.description??null,number:t.codeReviewId,state:bn[t.status],isDraft:t.isDraft,commentCount:null,upvoteCount:null,author:me(t.createdBy),createdDate:new Date(t.creationDate),updatedDate:new Date(t.closedDate||t.creationDate),closedDate:t.closedDate?new Date(t.closedDate):null,mergedDate:t.closedDate&&t.status==="completed"?new Date(t.closedDate):null,isCrossRepository:r,repository:{id:t.repository.id,name:t.repository.name,project:t.repository.project.name,owner:{login:s},remoteInfo:e?.get(t.repository.id)??null},headCommit:{buildStatuses:null},baseRef:{name:Qe(t.targetRefName),oid:t.lastMergeTargetCommit.commitId},headRef:{name:Qe(t.sourceRefName),oid:t.lastMergeSourceCommit.commitId},url:zr(t),assignees:t.reviewers.map(me),reviews:o,reviewDecision:J(n),additions:null,deletions:null,fileCount:null,commitCount:null,headRepository:t.forkSource?{id:t.forkSource.repository.id,name:t.forkSource.repository.name,project:void 0,owner:{login:s},remoteInfo:e?.get(t.forkSource.repository.id)??null,isFork:!0}:{id:t.repository.id,name:t.repository.name,project:t.repository.project.name,owner:{login:s},remoteInfo:e?.get(t.repository.id)??null,isFork:!1},mergeableState:Cn(t.mergeStatus),labels:t.labels?.map(i=>({color:null,description:null,id:i.id,name:i.name}))??[],permissions:null}},Vr=(s,t)=>({id:t.id,name:t.name,namespace:s,project:t.project.name,projectId:t.project.id,webUrl:t.webUrl,httpsUrl:t.remoteUrl,sshUrl:t.sshUrl,defaultBranch:t.defaultBranch?{name:Qe(t.defaultBranch)}:null,permissions:null}),Dn=(s,t,e,r)=>{let n=e.fields,o=n["System.AssignedTo"],i=n["System.State"],a=n["System.WorkItemType"],u;return i&&a&&(u=r[a]?.[i]),{id:e.id.toString(),number:e.id.toString(),title:n["System.Title"],commentCount:n["System.CommentCount"],author:{avatarUrl:n["System.CreatedBy"]._links?.avatar?.href??null,email:null,id:n["System.CreatedBy"].id,name:n["System.CreatedBy"].uniqueName??null,username:n["System.CreatedBy"].displayName??null,url:null},closedDate:n["Microsoft.VSTS.Common.ClosedDate"]?new Date(n["Microsoft.VSTS.Common.ClosedDate"]):null,createdDate:new Date(n["System.CreatedDate"]),updatedDate:new Date(n["System.ChangedDate"]),url:e._links.html.href,assignees:o?[{avatarUrl:o._links?.avatar?.href??null,email:null,id:o.id,name:o.uniqueName??null,username:o.displayName??null,url:null}]:[],description:n["System.Description"]??null,state:{name:u?.title||i,color:null},type:n["System.WorkItemType"],repository:null,project:{namespace:s,name:t,resourceId:null,key:null,id:null},upvoteCount:0,labels:e.fields["System.Tags"]?.split(";").map(l=>({color:null,description:null,id:null,name:l.trim()}))??[]}},Re=class extends Q{constructor(){super(...arguments);this.cachedUserIds=new Map;this.inflightUserIds=new Map}getCurrentUserId(e,r){let n=JSON.stringify([e,r.token??null,r.isPAT??this.config.isPAT??!1,r.baseUrl??null]),o=this.cachedUserIds.get(n);if(o)return Promise.resolve(o);let i=this.inflightUserIds.get(n);if(i)return i;let a=this.fetchCurrentUserId(e,r,n);return this.inflightUserIds.set(n,a),a}async fetchCurrentUserId(e,r,n){try{let o=await this.getCurrentUserForInstance({namespace:e},r);return this.cachedUserIds.set(n,o.data.id),o.data.id}finally{this.inflightUserIds.delete(n)}}getRepoApiUrl(e,r,n,o){return`${C(this.config,o)}/${encodeURIComponent(e)}/${encodeURIComponent(r)}/_apis/git/repositories/${encodeURIComponent(n)}`}async getCurrentUser(e={},r={}){if(r.isPAT||this.config.isPAT)throw new Error("Azure DevOps does not support PATs for this function.");let n=`${Bt(this.config,r)}/profile/profiles/me`,o=await this.config.request({url:n,headers:q(this.config,r)});return{data:{id:o.body.id,name:o.body.displayName,username:o.body.displayName,email:o.body.emailAddress,avatarUrl:null,url:null}}}async getCurrentUserForInstance(e,r={}){let o=(await this.config.request({url:`${C(this.config,r)}/${encodeURIComponent(e.namespace)}/_apis/ConnectionData`,headers:q(this.config,r)})).body.authorizedUser;if(o.providerDisplayName==="Anonymous")throw new Error("Current user not found.");return{data:{id:o.id,name:o.providerDisplayName,username:o.providerDisplayName,email:o.properties.Account.$value,avatarUrl:null,url:null}}}async getUserForCommit(e,r={}){if(!e.repo.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let o=(await this.config.request({url:`${C(this.config,r)}/${encodeURIComponent(e.repo.namespace)}/${encodeURIComponent(e.repo.project)}/_apis/git/repositories/${encodeURIComponent(e.repo.name)}/commits/${e.oid}`,headers:q(this.config,r)})).body.author;return{data:{name:o.name,email:o.email,avatarUrl:o.imageUrl}}}async getOrgsForUser(e,r={}){let n=`${Bt(this.config,r)}/accounts?memberId=${e.userId}&api-version=6.0`;return{data:(await this.config.request({url:n,headers:q(this.config,r)})).body.value.map(i=>({id:i.accountId,name:i.accountName}))}}async getCollectionsForUser(e,r={}){let n=`${C(this.config,r)}/_apis/projectCollections`;return{data:(await this.config.request({url:n,headers:q(this.config,r)})).body.value.map(i=>({id:i.id,name:i.name}))}}async getAzureProjects(e,r={}){let n=new URL(`${C(this.config,r)}/${encodeURIComponent(e.namespace)}/_apis/projects`);n.searchParams.set("$top",$.toString()),e.cursor&&n.searchParams.set("$skip",e.cursor);let o=await this.config.request({url:n.toString(),headers:q(this.config,r)}),i=o.headers["x-ms-continuationtoken"];return{pageInfo:{hasNextPage:!!i,endCursor:i||null},data:o.body.value.map(a=>({id:a.id,name:a.name,namespace:e.namespace}))}}async getAzureProjectScopeDescriptor(e,r={}){let{namespace:n,projectId:o}=e;return{data:{scope:(await this.config.request({url:`${jt(this.config,r)}/${encodeURIComponent(n)}/_apis/graph/descriptors/${o}?api-version=6.0`,headers:q(this.config,r)})).body.value}}}async getAzureGraphAccountsForAzureProject(e,r={}){let{namespace:n,projectScopeDescriptor:o,cursor:i}=e,a=new URL(`${jt(this.config,r)}/${encodeURIComponent(n)}/_apis/graph/users`);o&&a.searchParams.set("scopeDescriptor",o),i&&a.searchParams.set("continuationToken",i);let u=await this.config.request({url:a.toString(),headers:q(this.config,r)}),l=u.headers["x-ms-continuationtoken"];return{pageInfo:{endCursor:l||null,hasNextPage:!!l},data:u.body.value.map(p=>({avatarUrl:p._links?.avatar?.href??null,descriptor:p.descriptor??null,email:p.mailAddress??null,name:p.displayName??null,storageKeyURL:p._links?.storageKey?.href??null,username:p.displayName??null}))}}async getAccountFromAzureGraphAccount(e,r={}){let{azureGraphAccount:n}=e;if(!n.storageKeyURL)throw new Error("Expected 'storageKeyURL' to not be null for 'azureGraphAccount'");let o=await this.config.request({url:n.storageKeyURL,headers:q(this.config,r)});return{data:{avatarUrl:n.avatarUrl,email:n.email,id:o.body.value,name:n.name,username:n.username,url:null}}}async getAccountsFromAzureGraphAccounts(e,r={}){let n=[];for(let o of e.azureGraphAccounts){let i=await this.getAccountFromAzureGraphAccount({azureGraphAccount:o},r);n.push(i.data)}return{data:n}}async getRepo(e,r={}){if(!e.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let n=await this.config.request({url:`${C(this.config,r)}/${encodeURIComponent(e.namespace)}/${encodeURIComponent(e.project)}/_apis/git/repositories/${encodeURIComponent(e.name)}`,headers:q(this.config,r)});return{data:Vr(e.namespace,n.body)}}async getRepos(e,r={}){let n=[],o=[];return await Promise.all(e.map(async i=>{try{let a=await this.getRepo(i,r);n.push(a.data)}catch(a){o.push({input:i,error:a})}})),{data:n,errors:o}}async getReposForAzureProject(e,r={}){if(!e.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');return{data:(await this.config.request({url:`${C(this.config,r)}/${encodeURIComponent(e.namespace)}/${encodeURIComponent(e.project)}/_apis/git/repositories`,headers:q(this.config,r)})).body.value.map(o=>Vr(e.namespace,o))}}async getRefs(e,r,n={}){if(!r.repo.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let o=new URL(`${C(this.config,n)}/${encodeURIComponent(r.repo.namespace)}/${encodeURIComponent(r.repo.project)}/_apis/git/repositories/${encodeURIComponent(r.repo.name)}/refs`);o.searchParams.set("filter",e),o.searchParams.set("$top",$.toString()),r.cursor&&o.searchParams.set("continuationToken",r.cursor);let i=await this.config.request({url:o.toString(),headers:q(this.config,n)}),a=i.headers["x-ms-continuationtoken"];return{pageInfo:{hasNextPage:!!a,endCursor:a||null},data:i.body.value.map(u=>({name:Qe(u.name),commit:{oid:u.objectId,authoredDate:null,committedDate:null}}))}}async getBranches(e,r={}){return this.getRefs("heads",e,r)}async getTags(e,r={}){return this.getRefs("tags",e,r)}async fetchRemoteInfoByRepoId(e,r,n){let o=new Map;if(!e)return o;let i=new Map;for(let{namespace:a,pullRequests:u}of r)for(let l of u)i.has(l.repository.id)||i.set(l.repository.id,a),l.forkSource&&!i.has(l.forkSource.repository.id)&&i.set(l.forkSource.repository.id,a);return await Qr([...i],10,async([a,u])=>{try{let l=await this.config.request({url:`${C(this.config,n)}/${encodeURIComponent(u)}/_apis/git/repositories/${encodeURIComponent(a)}`,headers:q(this.config,n)}),{remoteUrl:p,sshUrl:d}=l.body;p&&d&&o.set(a,{cloneUrlHTTPS:p,cloneUrlSSH:d})}catch{}}),o}async getPullRequestsForRepoBase(e,r={},n=je){let{page:o,repo:i,assigneeLogins:a,authorLogin:u,reviewerId:l}=e||{},p=o||1;if(!i.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let d=L(e.pageSize,{fallback:n}),c=l??(a&&a.length?a[0]:void 0),g=`searchCriteria.status=${Mr(e.states)}`;return c&&(g+=`&searchCriteria.reviewerId=${encodeURIComponent(c)}`),u&&(g+=`&searchCriteria.creatorId=${encodeURIComponent(u)}`),await this.config.request({url:`${C(this.config,r)}/${encodeURIComponent(i.namespace)}/${encodeURIComponent(i.project||"")}/_apis/git/repositories/${encodeURIComponent(i.name)}/pullRequests?${g}&%24top=${d}&%24skip=${(p-1)*d}`,headers:q(this.config,r)})}async getPullRequestsForRepo(e,r={}){let n=L(e.pageSize,{fallback:je}),o=e.page||1,i=await this.getPullRequestsForRepoBase(e,r,n),a=i.body.value.length===n,u=await this.fetchRemoteInfoByRepoId(e.includeRemoteInfo,[{namespace:e.repo.namespace,pullRequests:i.body.value}],r);return{pageInfo:{hasNextPage:a,nextPage:a?o+1:null,currentPage:o},data:x(i.body.value.map(l=>Ae(e.repo.namespace,l,u)),e.states)}}async getPullRequestsForRepos(e,r={}){if(!e.repos.every(u=>u.project))throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let{repos:n}=e||{},o=[];await Promise.all(n.map(async u=>{try{let l=await this.getPullRequestsForRepoBase({repo:u,...e},r);o.push({namespace:u.namespace,pullRequests:l.body.value})}catch(l){if(l.statusCode!==404&&l.statusCode!==401)throw l}}));let i=await this.fetchRemoteInfoByRepoId(e.includeRemoteInfo,o,r),a=o.flatMap(({namespace:u,pullRequests:l})=>l.map(p=>Ae(u,p,i)));return{data:x(a,e.states)}}async getPullRequestsForProjectBase(e,r={},n=je){let{namespace:o,project:i,page:a,assigneeLogins:u,authorLogin:l,reviewerId:p,repo:d}=e;if(d?.project&&d.project!==i)throw new Error("Could not fetch pull requests, project mismatch");let c=a||1,g=L(e.pageSize,{fallback:n}),m=p??(u&&u.length?u[0]:void 0),h=new URL(`${C(this.config,r)}/${encodeURIComponent(o)}/${encodeURIComponent(i)}/_apis/git/pullRequests`);return h.searchParams.set("searchCriteria.status",Mr(e.states)),h.searchParams.set("$top",g.toString()),h.searchParams.set("$skip",((c-1)*g).toString()),d?.id&&d?.project===i&&h.searchParams.set("searchCriteria.repositoryId",d.id),m&&h.searchParams.set("searchCriteria.reviewerId",m),l&&h.searchParams.set("searchCriteria.creatorId",l),await this.config.request({url:h.toString(),headers:q(this.config,r)})}async getPullRequestsForProject(e,r={}){let n=L(e.pageSize,{fallback:je}),o=e.page||1,i=await this.getPullRequestsForProjectBase(e,r,n),a=i.body.value.length===n,u=await this.fetchRemoteInfoByRepoId(e.includeRemoteInfo,i?[{namespace:e.namespace,pullRequests:i.body.value}]:[],r);return{pageInfo:{hasNextPage:a,nextPage:a?o+1:null,currentPage:o},data:x(i?.body.value.map(l=>Ae(e.namespace,l,u))||[],e.states)}}async getPullRequestsForProjects(e,r={}){let{projects:n}=e||{},o=[];await Promise.all(n.map(async u=>{try{if(!e.repo||e.repo.project&&e.repo.project===u.project){let l=await this.getPullRequestsForProjectBase({...u,...e},r);l&&o.push({namespace:u.namespace,pullRequests:l.body.value})}}catch(l){if(l.statusCode!==404&&l.statusCode!==401)throw l}}));let i=await this.fetchRemoteInfoByRepoId(e.includeRemoteInfo,o,r),a=o.flatMap(({namespace:u,pullRequests:l})=>l.map(p=>Ae(u,p,i)));return{data:x(a,e.states)}}async getAzurePullRequestLastMergeStatus(e,r={}){if(!e.repo.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let{repo:{namespace:n,project:o,name:i},pullRequestId:a}=e,u=await this.config.request({url:`${C(this.config,r)}/${encodeURIComponent(n)}/${encodeURIComponent(o||"")}/_apis/git/repositories/${i}/pullrequests/${a}?includeCommits=true?api-version=6.0`,headers:{...q(this.config,r)}});if(!u.body.mergeStatus)throw new Error("Could not fetch pull request");return{data:u.body.mergeStatus}}async updatePullRequest(e,r,n){return await this.config.request({method:"PATCH",url:`${C(this.config,n)}/${encodeURIComponent(e.repository.owner.login)}/${encodeURIComponent(e.repository.project)}/_apis/git/repositories/${e.repository.name}/pullrequests/${e.id}?api-version=6.0`,body:r,headers:{...q(this.config,n),"Content-Type":"application/json"}})}async closePullRequest(e,r={}){let{pullRequest:n}=e,o={status:"abandoned"};if(!(await this.updatePullRequest(n,JSON.stringify(o),r)).body.status)throw new Error("Could not close pull request")}async mergePullRequest(e,r={}){let{pullRequest:n,mergeStrategy:o}=e,i;switch(o){case"MERGE_COMMIT":{i="noFastForward";break}case"REBASE":{i="rebase";break}case"REBASE_THEN_MERGE_COMMIT":{i="rebaseMerge";break}case"SQUASH":{i="squash";break}}let a={completionOptions:{mergeStrategy:i},lastMergeSourceCommit:{commitId:n.headRef?.oid},status:"completed"};if(!(await this.updatePullRequest(n,JSON.stringify(a),r)).body.status)throw new Error("Could not merge pull request")}async addPullRequestLabel(e,r={}){let{pullRequest:n,label:o}=e;if(!n.repository.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let i={name:o.name};if(!(await this.config.request({method:"POST",url:`${C(this.config,r)}/${encodeURIComponent(n.repository.owner.login)}/${encodeURIComponent(n.repository.project)}/_apis/git/repositories/${n.repository.name}/pullrequests/${n.id}/labels?api-version=6.0`,body:JSON.stringify(i),headers:{...q(this.config,r),"Content-Type":"application/json"}})).body.id)throw new Error("Could not add pull request label")}async removePullRequestLabel(e,r={}){let{pullRequest:n,label:o}=e;if(!n.repository.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');await this.config.request({method:"DELETE",url:`${C(this.config,r)}/${encodeURIComponent(n.repository.owner.login)}/${encodeURIComponent(n.repository.project)}/_apis/git/repositories/${n.repository.name}/pullrequests/${n.id}/labels/${encodeURIComponent(o.name)}?api-version=6.0`,headers:{...q(this.config,r)}})}async setPullRequestLabels(e,r={}){let{pullRequest:n,labels:o}=e;if(!n.repository.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let i=n.labels;if(!i)throw new Error('Azure DevOps requires "labels" for this function.');for(let a of o)i.find(u=>u.id===a.id)||await this.addPullRequestLabel({pullRequest:n,label:a},r);for(let a of i)o.find(u=>a.id===u.id)||await this.removePullRequestLabel({pullRequest:n,label:a},r)}async setPullRequestAsDraft(e,r={}){let{pullRequest:n,isDraft:o}=e,i={isDraft:o};if(!(await this.updatePullRequest(n,JSON.stringify(i),r)).body.status)throw new Error("Could not set the pull request as draft")}async addPullRequestReviewer(e,r={}){let{pullRequest:n,reviewer:o,isRequired:i}=e,a={id:o.id,isRequired:i};if(!(await this.config.request({method:"PUT",url:`${C(this.config,r)}/${encodeURIComponent(n.repository.owner.login)}/${encodeURIComponent(n.repository.project)}/_apis/git/repositories/${n.repository.name}/pullrequests/${n.id}/reviewers/${o.id}?api-version=6.0`,body:JSON.stringify(a),headers:{...q(this.config,r),"Content-Type":"application/json"}})).body.id)throw new Error("Could not add pull request reviewer")}async removePullRequestReviewer(e,r={}){let{pullRequest:n,reviewer:o}=e;await this.config.request({method:"DELETE",url:`${C(this.config,r)}/${encodeURIComponent(n.repository.owner.login)}/${encodeURIComponent(n.repository.project)}/_apis/git/repositories/${n.repository.name}/pullrequests/${n.id}/reviewers/${o.id}?api-version=6.0`,headers:{...q(this.config,r),Accept:"application/json"}})}async setPullRequestReviewers(e,r={}){let{pullRequest:n,reviewers:o}=e;for(let i of o)n.assignees.find(a=>a.id===i.id)||await this.addPullRequestReviewer({pullRequest:n,reviewer:i,isRequired:!0},r);for(let i of n.assignees)o.find(a=>i.id===a.id)||await this.removePullRequestReviewer({pullRequest:n,reviewer:i},r)}async getIssuesForAzureProject(e,r={}){let{page:n,assigneeLogins:o,authorLogin:i,mentionLogin:a,labelNames:u,statusByWorkItemIdByStatusId:l}=e||{},p=n||1,d=Math.min(L(e.pageSize,{fallback:Pn}),wn),c=["[System.TeamProject] = @project",...qn(e.states)];i&&c.push(`[System.CreatedBy] = '${i.replace("'","''")}'`),o&&o[0]&&c.push(`[System.AssignedTo] = '${o[0].replace("'","''")}'`),a&&c.push("[System.Id] IN (@recentMentions)"),u&&u.forEach(A=>c.push(`[System.Tags] Contains '${A}'`));let g=`Select [Microsoft.VSTS.Common.ClosedDate], [Microsoft.VSTS.Common.ResolvedDate] From WorkItems Where ${c.join(" AND ")} order by [System.CreatedDate] desc`,m=await this.config.request({url:`${C(this.config,r)}/${encodeURIComponent(e.namespace)}/${encodeURIComponent(e.project)}/_apis/wit/wiql?api-version=6.0`,body:JSON.stringify({query:g}),method:"POST",headers:{...q(this.config,r),"Content-Type":"application/json"}}),h=m.body.workItems.slice((p-1)*d,d*p).map(A=>A.id),y=m.body.workItems.length,f=Math.ceil(y/d),P=y>d*p;if(h.length===0)return{pageInfo:{hasNextPage:!1,nextPage:null,currentPage:p,totalCount:y,totalPages:f},data:[]};let v=await this.config.request({url:`${C(this.config,r)}/${encodeURIComponent(e.namespace)}/${encodeURIComponent(e.project)}/_apis/wit/workitemsbatch?api-version=6.0`,body:JSON.stringify({ids:h,$expand:"Links"}),method:"POST",headers:{...q(this.config,r),"Content-Type":"application/json"}});return{pageInfo:{hasNextPage:P,nextPage:P?p+1:null,currentPage:p,totalCount:y,totalPages:f},data:v.body.value.map(A=>Dn(e.namespace,e.project,A,l||{}))}}async getPermissionsForRepos(e,r={}){let{namespace:n,repos:o}=e,i={4:["canPush","canCreateWebhook"],1024:["isAdmin"],2048:["isAdmin"],4096:["isAdmin"],8192:["isAdmin"]},a=d=>{let c="2e9eb7ed-3c0a-47d4-87c1-0ffdd275fd87",g=`repoV2/${d.projectId}/${d.id}`;return Object.keys(i).map(m=>({securityNamespaceId:c,token:g,permissions:m}))},u={alwaysAllowAdministrators:!1,evaluations:o.flatMap(a)};return{data:(await this.config.request({method:"POST",url:`${C(this.config,r)}/${encodeURIComponent(n)}/_apis/security/permissionevaluationbatch?api-version=7.0`,body:JSON.stringify(u),headers:{...q(this.config,r),"Content-Type":"application/json"}})).body.evaluations.reduce((d,c)=>{let[,g,m]=c.token.split("/"),h=`${g}/${m}`,y=i[c.permissions];for(let f of y)d[h]===void 0&&(d[h]={canCreateWebhook:!0,canPush:!0,isAdmin:!0}),c.value===!1&&(d[h][f]=!1);return d},{})}}async decorateReposWithPermissions(e,r={}){let{namespace:n,repos:o}=e,i=await this.getPermissionsForRepos({namespace:n,repos:o},r);return{data:o.map(a=>({...a,permissions:i.data[`${a.projectId}/${a.id}`]}))}}async updateIssue(e,r,n={}){return await this.config.request({method:"PATCH",url:`${C(this.config,n)}/${encodeURIComponent(e.project.namespace)}/${encodeURIComponent(e.project.name)}/_apis/wit/workitems/${e.id}?api-version=6.0`,body:JSON.stringify(r),headers:{...q(this.config,n),"Content-Type":"application/json-patch+json"}})}async setIssueStatus(e,r={}){let{issue:n,status:o}=e,i=[{op:"add",path:"/fields/System.State",value:o.name}];if(!(await this.updateIssue(n,i,r)).body.fields?.["System.State"])throw new Error("Could not set issue status")}async setIssueAssignee(e,r={}){let{issue:n,assignee:o}=e,i=[{op:"add",path:"/fields/System.AssignedTo",value:o?.name??""}];if(!(await this.updateIssue(n,i,r)).body.fields?.["System.State"])throw new Error("Could not set issue assignee")}async setIssueLabels(e,r={}){let{issue:n,labels:o}=e,a=[{op:"replace",path:"/fields/System.Tags",value:o.map(l=>l.name).join(";")}];if(!(await this.updateIssue(n,a,r)).body.fields?.["System.Tags"])throw new Error("Could not set issue tags")}async getIssueTypesForAzureProject(e,r={}){if(!e.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let{namespace:n,project:o}=e;return{data:(await this.config.request({url:`${C(this.config,r)}/${encodeURIComponent(n)}/${encodeURIComponent(o||"")}/_apis/wit/workitemtypes?api-version=6.0`,headers:{...q(this.config,r)}})).body.value}}async getLabelsForProject(e,r={}){let{namespace:n,project:o}=e;return{data:(await this.config.request({url:`${C(this.config,r)}/${encodeURIComponent(n)}/${encodeURIComponent(o||"")}/_apis/wit/tags?api-version=6.0`,headers:{...q(this.config,r)}})).body.value.map(a=>({color:null,description:null,id:a.id,name:a.name,url:a.url}))}}async getPullRequestForRepo(e,r={}){let{repo:n,number:o}=e;if(!n.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let i=await this.config.request({url:`${this.getRepoApiUrl(n.namespace,n.project,n.name,r)}/pullrequests/${o}?api-version=7.1`,headers:q(this.config,r)}),a=await this.fetchRemoteInfoByRepoId(e.includeRemoteInfo,[{namespace:n.namespace,pullRequests:[i.body]}],r);return{data:Ae(n.namespace,i.body,a)}}async getPullRequestDescription(e,r={}){let{repo:n,number:o}=e;if(!n.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');try{return{data:{description:(await this.config.request({url:`${this.getRepoApiUrl(n.namespace,n.project,n.name,r)}/pullrequests/${o}?api-version=7.1`,headers:q(this.config,r)})).body?.description??""}}}catch{return{data:{description:null}}}}async setPullRequestDescription(e,r={}){let{repo:n,number:o,description:i}=e;if(!n.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');return{data:{description:(await this.config.request({method:"PATCH",url:`${this.getRepoApiUrl(n.namespace,n.project,n.name,r)}/pullrequests/${o}?api-version=7.1`,headers:{...q(this.config,r),"Content-Type":"application/json"},body:JSON.stringify({description:i})})).body?.description??i}}}async getMergeBase(e,r={}){if(!e.repo.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let n=await this.config.request({url:`${this.getRepoApiUrl(e.repo.namespace,e.repo.project,e.repo.name,r)}/commits/${encodeURIComponent(e.base)}/mergebases?otherCommitId=${encodeURIComponent(e.head)}&api-version=7.1`,headers:q(this.config,r)});if(!n.body.value?.length)throw new Error("No merge base found between the specified commits.");return{data:n.body.value[0].commitId}}async getFileContents(e,r={}){if(!e.repo.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let n=await this.config.request({url:`${this.getRepoApiUrl(e.repo.namespace,e.repo.project,e.repo.name,r)}/items?path=${encodeURIComponent(e.path)}&versionDescriptor[version]=${encodeURIComponent(e.ref)}&versionDescriptor[versionType]=commit&api-version=7.1`,headers:{...q(this.config,r),Accept:"application/octet-stream"}});return{data:new Blob([n.body])}}async getPullRequestDiff(e,r={}){if(!e.repo.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let n=this.getRepoApiUrl(e.repo.namespace,e.repo.project,e.repo.name,r),o=q(this.config,r),i={...o,Accept:"application/octet-stream"},[a,u]=await Promise.all([this.config.request({url:`${n}/pullrequests/${e.pullRequestId}?api-version=7.1`,headers:o}),this.config.request({url:`${n}/pullrequests/${e.pullRequestId}/iterations?api-version=7.1`,headers:o})]),l=a.body.lastMergeTargetCommit.commitId,p=a.body.lastMergeSourceCommit.commitId,d=u.body.value;if(d.length===0)return"";let c=d[d.length-1],g=1e3,m=[],h=0;for(;;){let S=(await this.config.request({url:`${n}/pullrequests/${e.pullRequestId}/iterations/${c.id}/changes?api-version=7.1&$top=${g}&$skip=${h}`,headers:o})).body.changeEntries??[];if(S.length===0||(m.push(...S),S.length<g))break;h+=S.length}if(m.length===0)return"";let y=5,f=[],P=new TextDecoder,v=w=>w instanceof ArrayBuffer?P.decode(w):typeof w=="string"?w:"",A=async(w,S)=>{try{let le=await this.config.request({url:`${n}/items?path=${encodeURIComponent(w)}&versionDescriptor[version]=${encodeURIComponent(S)}&versionDescriptor[versionType]=commit&includeContent=true&api-version=7.1`,headers:i});return v(le.body)}catch{return""}},D=w=>{if(typeof w=="number")return{add:(w&1)!==0,rename:(w&8)!==0,delete:(w&16)!==0};let S=w.toLowerCase().split(",").map(le=>le.trim());return{add:S.includes("add"),rename:S.includes("rename"),delete:S.includes("delete")}};for(let w=0;w<m.length;w+=y){let S=m.slice(w,w+y),le=await Promise.all(S.map(async ge=>{let{add:he,rename:Tt,delete:pe}=D(ge.changeType),Ce=ge.originalPath??ge.item.originalPath,T=ge.item.path,xe=pe?T??Ce??"":T??"",kr=Tt||pe?Ce??xe:xe,[nn,on]=await Promise.all([he?Promise.resolve(""):A(kr,l),pe?Promise.resolve(""):A(xe,p)]),an=he?"/dev/null":`a${kr}`,un=pe?"/dev/null":`b${xe}`;return(0,Jr.createTwoFilesPatch)(an,un,nn,on)}));f.push(...le)}return f.join(`
|
|
2
|
-
`)}getPullRequestWriteHeaders(e){return{...q(this.config,e),"Content-Type":"application/json"}}setReviewerVote(e,r,n,o,i){return this.config.request({method:"PUT",url:`${e}/pullRequests/${r}/reviewers/${encodeURIComponent(n)}?api-version=7.1`,headers:this.getPullRequestWriteHeaders(i),body:JSON.stringify({vote:o})})}postPullRequestThread(e,r,n,o){return this.config.request({method:"POST",url:`${e}/pullRequests/${r}/threads?api-version=7.1`,headers:this.getPullRequestWriteHeaders(o),body:JSON.stringify({comments:[{parentCommentId:0,content:n,commentType:1}],status:1})})}async getCommentsForPullRequest(e,r={}){if(!e.repo.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let n=this.getRepoApiUrl(e.repo.namespace,e.repo.project,e.repo.name,r),o=q(this.config,r),i=await this.config.request({url:`${n}/pullRequests/${e.pullRequestNumber}/threads?api-version=7.1`,headers:o}),a=[];for(let u of i.body.value)if(!(u.isDeleted||u.threadContext))for(let l of u.comments)l.commentType==="system"||l.isDeleted||a.push({id:Qt(e.repo.namespace,e.repo.project,e.repo.name,e.pullRequestNumber,u.id,l.id),author:l.author?me(l.author):null,body:l.content||"",createdAt:l.publishedDate?new Date(l.publishedDate):null,url:""});return{data:a,pageInfo:{hasNextPage:!1,endCursor:null}}}async addCommentToPullRequest(e,r={}){if(!e.pullRequest.repository.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let n=this.getRepoApiUrl(e.pullRequest.repository.owner.login,e.pullRequest.repository.project,e.pullRequest.repository.name,r);await this.postPullRequestThread(n,e.pullRequest.id,e.comment,r)}async addInlineCommentToPullRequest(e,r={}){if(!e.pullRequest.repository.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let n=this.getRepoApiUrl(e.pullRequest.repository.owner.login,e.pullRequest.repository.project,e.pullRequest.repository.name,r),o=this.getPullRequestWriteHeaders(r);if(e.threadId){let p=Ft(e.threadId),d=e.pullRequest.repository.owner.login,c=e.pullRequest.repository.project,g=e.pullRequest.repository.name,m=String(e.pullRequest.id);if(p.namespace!==d||p.project!==c||p.repoName!==g||p.prId!==m)throw new Error(`Azure thread ID context mismatch: threadId targets ${p.namespace}/${p.project}/${p.repoName} pull request ${p.prId}, but input.pullRequest targets ${d}/${c}/${g} pull request ${m}.`);let y=(await this.config.request({url:`${n}/pullRequests/${e.pullRequest.id}/threads/${p.threadId}?api-version=7.1`,headers:q(this.config,r)})).body.comments?.find(P=>P.parentCommentId===0);if(!y)throw new Error(`Could not determine root comment for Azure DevOps thread ${p.threadId}.`);let f=await this.config.request({method:"POST",url:`${n}/pullRequests/${e.pullRequest.id}/threads/${p.threadId}/comments?api-version=7.1`,headers:o,body:JSON.stringify({content:e.comment,parentCommentId:y.id,commentType:1})});return Qt(d,c,g,Number(m),Number(p.threadId),f.body.id)}let i=e.path.startsWith("/")?e.path:`/${e.path}`,a={line:e.line,offset:1},u={filePath:i};e.side==="LEFT"?(u.leftFileStart=a,u.leftFileEnd=a):(u.rightFileStart=a,u.rightFileEnd=a);let l=await this.config.request({method:"POST",url:`${n}/pullRequests/${e.pullRequest.id}/threads?api-version=7.1`,headers:o,body:JSON.stringify({comments:[{parentCommentId:0,content:e.comment,commentType:1}],status:1,threadContext:u})});return Hr(e.pullRequest.repository.owner.login,e.pullRequest.repository.project,e.pullRequest.repository.name,Number(e.pullRequest.id),l.body.id)}async editComment(e,r={}){let n=Wr(e.commentId),o=this.getRepoApiUrl(n.namespace,n.project,n.repoName,r);await this.config.request({method:"PATCH",url:`${o}/pullRequests/${n.prId}/threads/${n.threadId}/comments/${n.commentId}?api-version=7.1`,headers:this.getPullRequestWriteHeaders(r),body:JSON.stringify({content:e.body})})}async editInlineComment(e,r={}){return this.editComment(e,r)}async deleteComment(e,r={}){let n=Wr(e.commentId),o=this.getRepoApiUrl(n.namespace,n.project,n.repoName,r);await this.config.request({method:"DELETE",url:`${o}/pullRequests/${n.prId}/threads/${n.threadId}/comments/${n.commentId}?api-version=7.1`,headers:q(this.config,r)})}async deleteInlineComment(e,r={}){return this.deleteComment(e,r)}async resolveReviewThread(e,r={}){let n=Ft(e.threadId),o=this.getRepoApiUrl(n.namespace,n.project,n.repoName,r);await this.config.request({method:"PATCH",url:`${o}/pullRequests/${n.prId}/threads/${n.threadId}?api-version=7.1`,headers:this.getPullRequestWriteHeaders(r),body:JSON.stringify({status:2})})}async unresolveReviewThread(e,r={}){let n=Ft(e.threadId),o=this.getRepoApiUrl(n.namespace,n.project,n.repoName,r);await this.config.request({method:"PATCH",url:`${o}/pullRequests/${n.prId}/threads/${n.threadId}?api-version=7.1`,headers:this.getPullRequestWriteHeaders(r),body:JSON.stringify({status:1})})}async approvePullRequest(e,r={}){if(!e.pullRequest.repository.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let n=e.pullRequest.repository.owner.login,o=this.getRepoApiUrl(n,e.pullRequest.repository.project,e.pullRequest.repository.name,r),i=await this.getCurrentUserId(n,r);await Promise.all([this.setReviewerVote(o,e.pullRequest.id,i,10,r),e.comment?this.postPullRequestThread(o,e.pullRequest.id,e.comment,r):null])}async requestPullRequestChanges(e,r={}){if(!e.pullRequest.repository.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let n=e.pullRequest.repository.owner.login,o=this.getRepoApiUrl(n,e.pullRequest.repository.project,e.pullRequest.repository.name,r),i=await this.getCurrentUserId(n,r);await this.postPullRequestThread(o,e.pullRequest.id,e.comment,r),await this.setReviewerVote(o,e.pullRequest.id,i,-5,r)}async commentOnPullRequest(e,r={}){if(!e.pullRequest.repository.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let n=this.getRepoApiUrl(e.pullRequest.repository.owner.login,e.pullRequest.repository.project,e.pullRequest.repository.name,r);await this.postPullRequestThread(n,e.pullRequest.id,e.comment,r)}async getReviewsForPullRequest(e,r={}){if(!e.repo.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let{namespace:n,project:o,name:i}=e.repo,{pullRequestId:a}=e,u=this.getRepoApiUrl(n,o,i,r),l=q(this.config,r),[p,d]=await Promise.all([this.config.request({url:`${u}/pullRequests/${a}/reviewers?api-version=7.1`,headers:l}),this.config.request({url:`${u}/pullRequests/${a}/threads?api-version=7.1`,headers:l})]),c=(f,P)=>Qt(n,o,i,a,f,P),g=f=>Hr(n,o,i,a,f),m=new Map;for(let f of d.body.value){if(f.isDeleted)continue;let P=f.comments.filter(T=>!T.isDeleted&&T.commentType!=="system"),v=P.find(T=>T.parentCommentId===0)??P[0];if(!v)continue;let A=v.author?.id;if(!A)continue;let D=P.filter(T=>T.id!==v.id),w=f.threadContext,S=w?.rightFileStart?{side:"RIGHT",start:w.rightFileStart,end:w.rightFileEnd}:w?.leftFileStart?{side:"LEFT",start:w.leftFileStart,end:w.leftFileEnd}:null,le=S?.end?.line??S?.start.line??null,ge=S?.start&&S.end&&S.start.line!==S.end.line?S.start.line:null,he=w?.filePath??"",Tt=he.startsWith("/")?he.slice(1):he,pe={id:c(f.id,v.id),author:v.author?me(v.author):null,body:v.content??"",createdAt:v.publishedDate?new Date(v.publishedDate):null,url:"",diffLines:[],filename:Tt,replies:D.map(T=>({id:c(f.id,T.id),author:T.author?me(T.author):null,body:T.content??"",createdAt:T.publishedDate?new Date(T.publishedDate):null,url:""})),isOutdated:!1,isResolved:En.has(vn(f.status)),line:le,startLine:ge,side:S?.side??null,threadId:g(f.id)},Ce=m.get(A);Ce?Ce.push(pe):m.set(A,[pe])}let h=[],y=new Set;for(let f of p.body.value){if(f.hasDeclined)continue;let P=f.vote??0,v=m.get(f.id);P===0&&!v?.length||(h.push({id:f.id,author:me(f),body:"",createdAt:null,url:"",reviewComments:v??[]}),y.add(f.id))}for(let[f,P]of m){if(y.has(f)||!P.length)continue;let v=P[0].author;v&&h.push({id:f,author:v,body:"",createdAt:null,url:"",reviewComments:P})}return{data:h}}};var U=(s,t={})=>R(t.token||s.token,t.isPAT||s.isPAT);var O="https://api.bitbucket.org/2.0",An={OPEN:"OPEN",MERGED:"MERGED",DECLINED:"CLOSED",SUPERSEDED:"CLOSED"},$n={OPEN:["OPEN"],MERGED:["MERGED"],CLOSED:["DECLINED","SUPERSEDED"]},Fe=50,Kr=s=>{let t=!s||s.length===0?["OPEN"]:Array.from(new Set(s.flatMap(r=>$n[r]))),e=t.map(r=>`state="${r}"`).join(" OR ");return t.length>1?`(${e})`:e},Ln=s=>s.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),Xr=s=>{let t=s?.trim();if(!t)return null;let e=Ln(t);return`(title ~ "${e}" OR description ~ "${e}")`},Zr=s=>{let t=!!s.next,e=typeof s.size=="number"?s.size:null,r=typeof s.pagelen=="number"&&s.pagelen>0?s.pagelen:null;return{hasNextPage:t,nextPage:t?s.page+1:null,currentPage:typeof s.page=="number"?s.page:null,totalCount:e,totalPages:e!==null&&r?Math.ceil(e/r):null}},ze={owner:4,admin:3,contributor:2,member:1},Me=s=>({id:s.uuid,name:s.display_name||s.nickname,username:s.nickname||s.display_name,email:null,avatarUrl:s.links.avatar.href,url:s.links.html.href}),Yr=s=>{let t=s.links.clone,e=t?.find(n=>n.name==="ssh"),r=t?.find(n=>n.name==="https");return e&&r?{cloneUrlHTTPS:r.href,cloneUrlSSH:e.href}:null},zt=s=>({id:s.uuid,namespace:s.workspace.slug,name:s.slug,webUrl:s.links.html.href,httpsUrl:s.links.clone.find(t=>t.name==="https")?.href??null,sshUrl:s.links.clone.find(t=>t.name==="ssh")?.href??null,defaultBranch:{name:s.mainbranch.name},permissions:null}),Mt=s=>{let t=s.id,e=s.participants?.map(r=>{let n="REVIEW_REQUESTED";return r.approved?n="APPROVED":r.state==="changes_requested"?n="CHANGES_REQUESTED":r.participated_on!==null&&(n="COMMENTED"),{reviewer:Me(r.user),state:n}})??[];return{id:t.toString(),title:s.title,description:s.description,number:t,state:An[s.state],isDraft:!1,commentCount:s.comment_count,upvoteCount:null,author:Me(s.author),createdDate:new Date(s.created_on),updatedDate:new Date(s.updated_on),closedDate:null,mergedDate:null,repository:{id:s.destination.repository.uuid,name:s.destination.repository.name,owner:{login:s.destination.repository.full_name.split("/")[0]},remoteInfo:Yr(s.destination.repository)},headCommit:{buildStatuses:null},baseRef:{name:s.destination.branch.name,oid:s.destination.commit.hash},headRef:{name:s.source.branch.name,oid:s.source.commit.hash},url:s.links.html.href,assignees:null,reviews:e,reviewDecision:J(e),additions:null,deletions:null,fileCount:null,commitCount:null,isCrossRepository:s.source.repository.uuid!==s.destination.repository.uuid,headRepository:{id:s.source.repository.uuid,name:s.source.repository.name,owner:{login:s.source.repository.full_name.split("/")[0]},remoteInfo:Yr(s.source.repository)},mergeableState:"MERGEABLE",permissions:null}},Gn=s=>{switch(s){case"owner":case"admin":return{canCreateWebhook:!0,canPush:!0,isAdmin:!0};case"write":return{canCreateWebhook:!1,canPush:!0,isAdmin:!1};case"read":case"none":return{canCreateWebhook:!1,canPush:!1,isAdmin:!1}}},Un=s=>{switch(s){case"owner":case"admin":return{canCreateWebhook:!0,canPush:!0,isAdmin:!0};case"contributor":return{canCreateWebhook:!1,canPush:!0,isAdmin:!1};default:return{canCreateWebhook:!1,canPush:!1,isAdmin:!1}}},Ie=class extends M{async refreshToken(t){return{data:(await this.config.request({url:"https://bitbucket.org/site/oauth2/access_token",method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Authorization:`Basic ${t.base64ClientIDColonClientSecret}`},body:`grant_type=refresh_token&refresh_token=${t.refreshToken}`})).body}}async getCurrentUser(t={},e={}){let r=await this.config.request({url:`${O}/user`,headers:U(this.config,e)});return{data:Me(r.body)}}async getUserForCommit(t,e={}){let n=(await this.config.request({url:`${O}/repositories/${t.repo.namespace}/${t.repo.name}/commit/${t.oid}`,headers:U(this.config,e)})).body.author,o=n.raw.match(/([^<]+)<(.+)>/);return{data:{name:o?o[1].trim():null,email:o?o[2]:null,avatarUrl:n.user?.links.avatar.href||null}}}async getRepo(t,e={}){let r=await this.config.request({url:`${O}/repositories/${t.namespace}/${t.name}`,headers:U(this.config,e)});return{data:zt(r.body)}}async getRepos(t,e={}){let r=[],n=[];return await Promise.all(t.map(async o=>{try{let i=await this.getRepo(o,e);r.push(i.data)}catch(i){n.push({input:o,error:i})}})),{data:r,errors:n}}async getReposForWorkspace(t,e={}){let r=new URL(`${O}/repositories/${encodeURIComponent(t.workspace)}`);r.searchParams.set("page",t.page?.toString()||"1"),r.searchParams.set("pagelen",$.toString()),t.minimumRole&&r.searchParams.set("role",t.minimumRole);let n=await this.config.request({url:r.toString(),headers:U(this.config,e)}),o=!!n.body.next;return{pageInfo:{hasNextPage:o,nextPage:o?n.body.page+1:null},data:n.body.values.map(zt)}}async getAllReposForWorkspace(t,e={}){let r=[],n=1;for(;n!==null;){let o=await this.getReposForWorkspace({workspace:t.workspace,minimumRole:t.minimumRole,page:n},e);r.push(...o.data),n=o.pageInfo.hasNextPage?o.pageInfo.nextPage:null}return r}async getAllReposForWorkspaceWithPermissions(t,e={}){let r=new Map,n=[],o=ze[t.minimumRole||"member"];o<=ze.admin&&n.push("admin"),o<=ze.contributor&&n.push("contributor"),o<=ze.member&&n.push("member");let i=[];for(let a of n){i=await this.getAllReposForWorkspace({workspace:t.workspace,minimumRole:a},e);for(let u of i)r.has(u.id)||r.set(u.id,a)}return{data:i.map(a=>{let u=r.get(a.id)||"member";return{...a,permissions:Un(u)}})}}async getReposForCurrentUser(t,e={}){let r=new URL(`${O}/repositories`);r.searchParams.set("role","member"),r.searchParams.set("pagelen",$.toString()),t.cursor&&r.searchParams.set("after",t.cursor);let n=await this.config.request({url:r.toString(),headers:U(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(zt)}}async getBranches(t,e={}){let r=new URL(`${O}/repositories/${t.repo.namespace}/${t.repo.name}/refs/branches`);r.searchParams.set("page",t.page?.toString()||"1"),r.searchParams.set("pagelen",$.toString());let n=await this.config.request({url:r.toString(),headers:U(this.config,e)}),o=!!n.body.next;return{pageInfo:{hasNextPage:o,nextPage:o?n.body.page+1:null},data:n.body.values.map(i=>{let a=new Date(i.target.date);return{name:i.name,commit:{oid:i.target.hash,authoredDate:a,committedDate:a}}})}}async getTags(t,e={}){let r=new URL(`${O}/repositories/${t.repo.namespace}/${t.repo.name}/refs/tags`);r.searchParams.set("pagelen",$.toString()),t.cursor&&r.searchParams.set("page",t.cursor);let n=await this.config.request({url:r.toString(),headers:U(this.config,e)}),o=!!n.body.next,i=null;return n.body.next&&(i=new URL(n.body.next).searchParams.get("page")),{pageInfo:{hasNextPage:o,endCursor:i},data:n.body.values.map(a=>{let u=new Date(a.target.date);return{name:a.name,commit:{oid:a.target.hash,authoredDate:u,committedDate:u}}})}}async getWorkspacesForCurrentUser(t={},e={}){let r=new URL(`${O}/user/workspaces`);r.searchParams.set("page",t?.page?.toString()||"1"),r.searchParams.set("pagelen","50"),t?.administrator!==void 0&&r.searchParams.set("administrator",t.administrator.toString());let n=await this.config.request({url:r.toString(),headers:U(this.config,e)}),o=!!n.body.next;return{pageInfo:{hasNextPage:o,nextPage:o?n.body.page+1:null},data:n.body.values.map(i=>({id:i.workspace.uuid,slug:i.workspace.slug}))}}async getWorkspacesForUser(t,e={}){let r=new URL(`${O}/user/permissions/workspaces`);r.searchParams.set("page",t.page?.toString()||"1"),r.searchParams.set("pagelen","50");let n=await this.config.request({url:r.toString(),headers:U(this.config,e)}),o=!!n.body.next;return{pageInfo:{hasNextPage:o,nextPage:o?n.body.page+1:null},data:n.body.values.map(i=>({id:i.workspace.uuid,slug:i.workspace.slug,name:i.workspace.name}))}}async getPullRequestsForUserAndWorkspace(t,e={}){let r=new URL(`${O}/workspaces/${t.workspaceSlug}/pullrequests/${t.userId}`);r.searchParams.set("fields","+values.participants,+values.destination.repository.links.clone.*,+values.source.repository.links.clone.*"),r.searchParams.set("page",t.page?.toString()||"1"),r.searchParams.set("pagelen",L(t.pageSize,{fallback:Fe,max:Fe}).toString());let n=[Kr(t.states)];t.repos&&t.repos.length>0&&n.push(`(${t.repos.map(a=>`source.repository.full_name = "${a.namespace}/${a.name}"`).join(" OR ")})`);let o=Xr(t.query);o&&n.push(o),r.searchParams.set("q",n.join(" AND "));let i=await this.config.request({url:r.toString(),headers:U(this.config,e)});return{pageInfo:Zr(i.body),data:i.body.values.map(Mt)}}async getPullRequestsForRepoBase(t,e={}){let r=new URL(`${O}/repositories/${encodeURI(t.repo.namespace)}/${encodeURI(t.repo.name)}/pullrequests`),n=[];t.reviewerId&&n.push(`reviewers.uuid="${t.reviewerId}"`),t.authorLogin&&n.push(`author.uuid="${t.authorLogin}"`);let o=Kr(t.states);n.length&&(o+=` AND (${n.join(t.useOrFilter?" OR ":" AND ")})`);let i=Xr(t.query);return i&&(o+=` AND ${i}`),r.searchParams.set("fields","+values.participants,+values.destination.repository.links.clone.*,+values.source.repository.links.clone.*"),r.searchParams.set("page",t.page?.toString()||"1"),r.searchParams.set("pagelen",L(t.pageSize,{fallback:Fe,max:Fe}).toString()),r.searchParams.set("q",o),await this.config.request({url:r.toString(),headers:U(this.config,e)})}async getPullRequestsForRepo(t,e={}){let r=[],n=await this.getPullRequestsForRepoBase(t,e);return n.body.values.forEach(o=>{r.push(Mt(o))}),{pageInfo:Zr(n.body),data:r}}async getPullRequestsForRepos(t,e={}){let r=[];return await Promise.all(t.repos.map(async n=>{try{(await this.getPullRequestsForRepoBase({repo:n,...t},e)).body.values.forEach(i=>{r.push(Mt(i))})}catch(o){if(o.statusCode!==404&&o.statusCode!==401)throw o}})),{data:r}}async getAccountsForWorkspace(t,e={}){let r=new URL(`${O}/workspaces/${encodeURI(t.workspace)}/members`);r.searchParams.set("page",t.page?.toString()||"1"),r.searchParams.set("pagelen","100");let n=await this.config.request({url:r.toString(),headers:U(this.config,e)}),o=!!n.body.next;return{pageInfo:{hasNextPage:o,nextPage:o?n.body.page+1:null},data:n.body.values.map(i=>Me(i.user))}}async getReposPermissionsForCurrentUser(t,e={}){let r=new URL(`${O}/user/permissions/repositories`);r.searchParams.set("page",t.page?.toString()||"1"),r.searchParams.set("pagelen","100");let n=await this.config.request({url:r.toString(),headers:U(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]:Gn(a.permission)}),{})}}async decorateReposWithPermissions(t,e={}){let r={},n=1;do{let o=await this.getReposPermissionsForCurrentUser({page:n},e);r={...o.data,...r},n=o.pageInfo.hasNextPage?o.pageInfo.nextPage:null}while(n!==null);return{data:t.repos.map(o=>({...o,permissions:r[o.id]??{canCreateWebhook:!1,canPush:!1,isAdmin:!1}}))}}async closePullRequest(t,e={}){let{pullRequest:r}=t;if(!(await this.config.request({method:"POST",url:`${O}/repositories/${r.repository.owner.login}/${r.repository.name}/pullrequests/${r.id}/decline`,headers:U(this.config,e)})).body.title)throw new Error("Could not close pull request")}async mergePullRequest(t,e={}){let{pullRequest:r,mergeStrategy:n}=t,o;switch(n){case"MERGE_COMMIT":{o="merge_commit";break}case"FAST_FORWARD":{o="fast_forward";break}case"SQUASH":{o="squash";break}}let i={merge_strategy:o,type:"pullrequest"};if(!(await this.config.request({method:"POST",url:`${O}/repositories/${r.repository.owner.login}/${r.repository.name}/pullrequests/${r.id}/merge`,body:JSON.stringify(i),headers:{...U(this.config,e),"Content-Type":"application/json"}})).body.title)throw new Error("Could not merge pull request")}async setPullRequestReviewers(t,e={}){let{pullRequest:r,reviewers:n}=t,o={reviewers:n.map(a=>{if(a.username)throw new Error('Bitbucket reviewer requires "username" for this function.');return{username:a.username}})};if(!(await this.config.request({method:"PUT",url:`${O}/repositories/${r.repository.owner.login}/${r.repository.name}/pullrequests/${r.id}`,body:JSON.stringify(o),headers:{...U(this.config,e),"Content-Type":"application/json"}})).body.title)throw new Error("Could not set pull request reviewers")}};var We={};H(We,{normalizePermissions:()=>Wt,restApiPullRequestToCommonPullRequest:()=>Tn});var Tn=s=>$e(s),Wt=s=>s?s.find(t=>t.permission==="USER_ADMIN"||t.permission==="PROJECT_ADMIN"||t.permission==="ADMIN"||t.permission==="SYS_ADMIN"||t.permission==="REPO_ADMIN")?{canCreateWebhook:!0,canPush:!0,isAdmin:!0}:s.find(t=>t.permission==="REPO_WRITE"||t.permission==="REPO_CREATE"||t.permission==="PROJECT_CREATE"||t.permission==="PROJECT_WRITE")?{canCreateWebhook:!1,canPush:!0,isAdmin:!1}:{canCreateWebhook:!1,canPush:!1,isAdmin:!1}:{canCreateWebhook:!1,canPush:!1,isAdmin:!1};var Le=s=>{let t=s.links.self[0].href;return{name:s.displayName,email:s.emailAddress,avatarUrl:s.avatarUrl??(t&&`${t}/avatar.png`),id:s.id.toString(),username:s.name,url:t}},$e=s=>{let t={OPEN:"OPEN",MERGED:"MERGED",DECLINED:"CLOSED"},e={UNAPPROVED:"REVIEW_REQUESTED",NEEDS_WORK:"CHANGES_REQUESTED",APPROVED:"APPROVED"},r=s.reviewers.map(u=>({reviewer:Le(u.user),state:e[u.status]})),n=s.toRef.repository.links.clone.find(u=>u.name==="ssh")?.href??null,o=s.toRef.repository.links.clone.find(u=>u.name==="https")?.href??null;o||(o=s.toRef.repository.links.clone.find(u=>u.name==="http")?.href??null);let i=s.fromRef.repository.links.clone.find(u=>u.name==="ssh")?.href??null,a=s.fromRef.repository.links.clone.find(u=>u.name==="https")?.href??null;return a||(a=s.fromRef.repository.links.clone.find(u=>u.name==="http")?.href??null),{id:s.id.toString(),number:s.id,title:s.title,description:s.description,url:s.links.self[0].href,state:t[s.state],isDraft:!1,createdDate:new Date(s.createdDate),updatedDate:new Date(s.updatedDate),closedDate:s.closedDate?new Date(s.closedDate):null,mergedDate:s.state=="MERGED"&&s.closedDate?new Date(s.closedDate):null,baseRef:{name:s.toRef.displayId,oid:s.toRef.latestCommit},headRef:{name:s.fromRef.displayId,oid:s.fromRef.latestCommit},commentCount:s.properties.commentCount,upvoteCount:null,commitCount:null,fileCount:null,additions:null,deletions:null,author:Le(s.author.user),assignees:null,reviews:r,reviewDecision:J(r),isCrossRepository:s.fromRef.repository.id!==s.toRef.repository.id,repository:{id:s.toRef.repository.id.toString(),name:s.toRef.repository.name,owner:{login:s.toRef.repository.project.key},remoteInfo:o&&n?{cloneUrlHTTPS:o,cloneUrlSSH:n}:null},headRepository:{id:s.fromRef.repository.id.toString(),name:s.fromRef.repository.name,owner:{login:s.fromRef.repository.project.key},remoteInfo:a&&i?{cloneUrlHTTPS:a,cloneUrlSSH:i}:null},headCommit:null,mergeableState:"MERGEABLE",permissions:null,version:s.version}},es=s=>({id:s.id.toString(),namespace:s.project.key,name:s.slug,webUrl:s.links.self[0]?.href??null,httpsUrl:s.links.clone.find(t=>t.name==="https"||t.name==="http")?.href??null,sshUrl:s.links.clone.find(t=>t.name==="ssh")?.href??null,defaultBranch:null,permissions:null}),ts=50,On={OPEN:"OPEN",MERGED:"MERGED",CLOSED:"DECLINED"},rs=s=>{if(!s||s.length===0)return"OPEN";let t=Array.from(new Set(s.map(e=>On[e])));return t.length===1?t[0]:"ALL"},ss=(s,t)=>typeof s!="number"||t<=0?null:Math.floor(s/t)+1,be=class extends Q{getBaseUrl(t){let e=t.baseUrl||this.config.baseUrl;if(!e)throw new Error('Bitbucket Server requires "baseUrl"');return e}getRequestHeaders(t){return R(t.token||this.config.token)}async getCurrentUser(t={},e={}){let r=await this.config.request({url:`${this.getBaseUrl(e)}/users?limit=2`,headers:this.getRequestHeaders(e)}),{headers:{"x-auserid":n,"x-ausername":o}}=r,i=n?parseInt(n,10):null,a=decodeURIComponent(o),l=(await this.config.request({url:`${this.getBaseUrl(e)}/users?filter=${o}&avatarSize=64`,headers:this.getRequestHeaders(e)})).body.values.find(({emailAddress: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:Le(l)}}async getUserForCommit(t,e){let{repo:r,oid:n}=t,o=await this.config.request({url:`${this.getBaseUrl(e)}/projects/${r.namespace}/repos/${r.name}/commits/${n}`,headers:this.getRequestHeaders(e)});if(!o.body.author)throw new Error("Could not find user for commit");return{data:Le(o.body.author)}}async getRepo(t,e={}){let r=await this.config.request({url:`${this.getBaseUrl(e)}/projects/${t.namespace}/repos/${t.name}`,headers:this.getRequestHeaders(e)});return{data:es(r.body)}}async getRepos(t,e={}){let r=[],n=[];return await Promise.all(t.map(async o=>{try{let i=await this.getRepo(o,e);r.push(i.data)}catch(i){n.push({input:o,error:i})}})),{data:r,errors:n}}async getReposForCurrentUser(t,e={}){let r=t.page??0,n=await this.config.request({url:`${this.getBaseUrl(e)}/repos?start=${r}`,headers:this.getRequestHeaders(e)});return{pageInfo:{hasNextPage:!n.body.isLastPage,nextPage:n.body.nextPageStart},data:n.body.values.map(es)}}async getRepoPermissionsForUsername(t,e={}){let r=new URL(`${this.getBaseUrl(e)}/projects/${t.repo.namespace}/repos/${t.repo.name}/permissions/search?filterText=${t.username}`);try{let n=await this.config.request({url:r.toString(),headers:this.getRequestHeaders(e)});return{data:Wt(n.body.values)}}catch(n){if(n.response?.status===401)return{data:{canCreateWebhook:!1,canPush:!1,isAdmin:!1}};throw n}}async decorateReposWithPermissions(t,e={}){return await Promise.all(t.repos.map(async n=>{let o=await this.getRepoPermissionsForUsername({repo:n,username:t.username},e);return{...n,permissions:o.data}}))}async getPullRequestsForRepoBase(t,e={}){let r=new URL(`${this.getBaseUrl(e)}/projects/${encodeURI(t.repo.namespace)}/repos/${encodeURI(t.repo.name)}/pull-requests`);return r.searchParams.set("state",rs(t.states)),r.searchParams.set("start",t.page?.toString()||"0"),r.searchParams.set("limit",L(t.pageSize,{fallback:ts}).toString()),t.reviewerLogin&&(r.searchParams.set("role.1","REVIEWER"),r.searchParams.set("username.1",t.reviewerLogin)),await this.config.request({url:r.toString(),headers:this.getRequestHeaders(e)})}async getPullRequestsForRepo(t,e={}){let r=[],n=await this.getPullRequestsForRepoBase(t,e);n.body.values.forEach(i=>{if(t.authorLogin&&i.author.user.name!==t.authorLogin)return null;r.push($e(i))});let o=!n.body.isLastPage;return{pageInfo:{hasNextPage:o,nextPage:o?n.body.nextPageStart:null,currentPage:ss(n.body.start,n.body.limit)},data:x(r,t.states)}}async getPullRequestsForRepos(t,e={}){let r=[];return await Promise.all(t.repos.map(async n=>{try{(await this.getPullRequestsForRepoBase({repo:n,...t},e)).body.values.forEach(i=>{if(t.authorLogin&&i.author.user.name!==t.authorLogin)return null;r.push($e(i))})}catch(o){if(o.statusCode!==404&&o.statusCode!==401)throw o}})),{data:x(r,t.states)}}async getPullRequestsForCurrentUser(t,e={}){let r=new URL(`${this.getBaseUrl(e)}/dashboard/pull-requests`);r.searchParams.set("state",rs(t.states)),r.searchParams.set("start",t.page?.toString()||"0");let n=L(t.pageSize,{fallback:ts});r.searchParams.set("limit",n.toString()),t.reviewerLogin&&(r.searchParams.set("role.1","REVIEWER"),r.searchParams.set("username.1",t.reviewerLogin));let o=await this.config.request({url:r.toString(),headers:this.getRequestHeaders(e)}),i=!o.body.isLastPage;return{pageInfo:{hasNextPage:i,nextPage:i?o.body.nextPageStart:null,currentPage:ss(o.body.start,o.body.limit)},data:x(o.body.values.map($e),t.states)}}async closePullRequest(t,e={}){let{pullRequest:r}=t;if(r.version===void 0)throw new Error('Bitbucket Server requires "version" for this function.');if(!(await this.config.request({method:"POST",url:`${this.getBaseUrl(e)}/projects/${r.repository.owner.login}/repos/${r.repository.name}/pull-requests/${r.id}/decline`,body:JSON.stringify({version:r.version}),headers:{...this.getRequestHeaders(e),"Content-Type":"application/json"}})).body.title)throw new Error("Could not close pull request")}async mergePullRequest(t,e={}){let{pullRequest:r,mergeStrategyId:n}=t;if(t.mergeStrategy)throw new Error('Bitbucket Server uses "mergeStrategyId" instead of "mergeStrategy".');if(r.version===void 0)throw new Error('Bitbucket Server requires "version" for this function.');if(!(await this.config.request({method:"POST",url:`${this.getBaseUrl(e)}/projects/${r.repository.owner.login}/repos/${r.repository.name}/pull-requests/${r.id}/merge`,body:JSON.stringify({strategyId:n,version:r.version}),headers:{...this.getRequestHeaders(e),"Content-Type":"application/json"}})).body.title)throw new Error("Could not merge pull request")}async getMergeStrategies(t={}){let e=await this.config.request({url:`${this.getBaseUrl(t)}/admin/pull-requests/git`,headers:{...this.getRequestHeaders(t),"Content-Type":"application/json"}});return{data:{defaultStrategy:e.body.mergeConfig.defaultStrategy,strategies:e.body.mergeConfig.strategies}}}async setPullRequestReviewers(t,e={}){let{pullRequest:r,reviewers:n}=t;if(r.version===void 0)throw new Error('Bitbucket Server requires "version" for this function.');let o={reviewers:n.map(a=>{if(a.username)throw new Error('Bitbucket Server reviewer requires "username" for this function.');return{user:{name:a.username}}}),version:r.version};if(!(await this.config.request({method:"PUT",url:`${this.getBaseUrl(e)}/projects/${r.repository.owner.login}/repos/${r.repository.name}/pull-requests/${r.id}`,body:JSON.stringify(o),headers:{...this.getRequestHeaders(e),"Content-Type":"application/json"}})).body.title)throw new Error("Could not set pull request reviewers")}async getAccountsForProject(t,e={}){let r=new URL(`${this.getBaseUrl(e)}/projects/${encodeURI(t.project)}/permissions/users`);r.searchParams.set("start",t.page?.toString()||"0"),r.searchParams.set("limit","50");let n=await this.config.request({url:r.toString(),headers:this.getRequestHeaders(e)}),o=n.body.values.length!==0;return{pageInfo:{hasNextPage:o,nextPage:o?n.body.start+n.body.values.length:null},data:n.body.values.map(i=>Le(i.user))}}};var ys=require("js-base64");var I=class extends Error{constructor(e,r){let n=r?.map(i=>`'${i.message}'`).join(", "),o=n?`${e}: ${n}`:e;super(o);this.graphQLErrors=r??[]}};var _n={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]},ns=15,os=100,Ge={__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"},k=s=>!!s,K=(s,t)=>{let e=_n[t];for(let r=0;r<3;r++){if(s[r]>e[r])return!0;if(s[r]<e[r])return!1}return!0},Ve="https://api.github.com",kn=`${Ve}/graphql`,Je=`
|
|
1
|
+
"use strict";var xt=Object.defineProperty;var fn=Object.getOwnPropertyDescriptor;var Rn=Object.getOwnPropertyNames;var In=Object.prototype.hasOwnProperty;var H=(s,t)=>{for(var e in t)xt(s,e,{get:t[e],enumerable:!0})},bn=(s,t,e,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of Rn(t))!In.call(s,n)&&n!==e&&xt(s,n,{get:()=>t[n],enumerable:!(r=fn(t,n))||r.enumerable});return s};var yn=s=>bn(xt({},"__esModule",{value:!0}),s);var Oi={};H(Oi,{AzureDevOps:()=>Pe,AzureDevopsUtils:()=>It,Bitbucket:()=>we,BitbucketServer:()=>qe,BitbucketServerUtils:()=>Je,BitbucketUtils:()=>bt,EntityIdentifierProviderType:()=>N,EntityIdentifierUtils:()=>Lt,EntityType:()=>j,EntityVersion:()=>B,GitBuildStatusStage:()=>jr,GitBuildStatusState:()=>Ue,GitDiffLineType:()=>Nt,GitHub:()=>ve,GitHubIssueCloseReason:()=>dn,GitHubUtils:()=>Gt,GitIssueState:()=>ge,GitLab:()=>Se,GitLabUtils:()=>Tt,GitMergeStrategy:()=>Ie,GitProviderUtils:()=>Ut,GitPullRequestMergeableState:()=>ee,GitPullRequestReviewState:()=>V,GitPullRequestState:()=>ie,GraphQLErrors:()=>I,Jira:()=>Ce,JiraServer:()=>De,JiraUtils:()=>Ot,Linear:()=>Ae,PullRequestAsyncStatus:()=>pn,Trello:()=>$e,TrelloUtils:()=>_t,Utils:()=>Ti,default:()=>Gi,isFetch:()=>ze});module.exports=yn(Oi);var ts=require("diff");var jr=(n=>(n.Build="build",n.Production="production",n.Staging="staging",n.Test="test",n))(jr||{}),Ue=(d=>(d.ActionRequired="ACTION_REQUIRED",d.Cancelled="CANCELLED",d.Error="ERROR",d.Failed="FAILED",d.Pending="PENDING",d.Running="RUNNING",d.Skipped="SKIPPED",d.Success="SUCCESS",d.Warning="WARNING",d.OptionalActionRequired="OPTIONAL_ACTION_REQUIRED",d))(Ue||{}),Ie=(o=>(o.MergeCommit="MERGE_COMMIT",o.Rebase="REBASE",o.RebaseThenMergeCommit="REBASE_THEN_MERGE_COMMIT",o.FastForward="FAST_FORWARD",o.Squash="SQUASH",o))(Ie||{}),ie=(r=>(r.Open="OPEN",r.Closed="CLOSED",r.Merged="MERGED",r))(ie||{}),V=(n=>(n.Approved="APPROVED",n.ChangesRequested="CHANGES_REQUESTED",n.Commented="COMMENTED",n.ReviewRequested="REVIEW_REQUESTED",n))(V||{}),ee=(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))(ee||{}),Nt=(r=>(r.ADDED="ADDED",r.DELETED="DELETED",r.UNMODIFIED="UNMODIFIED",r))(Nt||{});var Fr={APPROVED:0,COMMENTED:1,REVIEW_REQUESTED:2,CHANGES_REQUESTED:3},J=s=>!s||s.length===0?null:s.reduce((t,e)=>Fr[e.state]>Fr[t]?e.state:t,"APPROVED"),Qe=(s,t)=>s.name||s.username||s.email||t,ce=s=>{let t=Object.values(s).map(e=>e.name).sort((e,r)=>e.localeCompare(r));return Object.values(s).forEach(e=>{e.priority!==-1&&(e.priority=t.indexOf(e.name))}),s};var Pn=new Set(["ECONNABORTED","ECONNREFUSED","ECONNRESET","EAI_AGAIN","ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"]),R=(s,t)=>{let e={};return s&&(e.Authorization=`${t?"Basic":"Bearer"} ${s}`),e},Mr=s=>s?s.reduce((t,e)=>(t[e]=!0,t),{}):void 0,ae=(s,t,e)=>!s||t.some(r=>s[r])?e:"",Wr=async s=>{let t=[],e=!0,r;for(;e;){let n=await s(r);t=t.concat(n.data),e=!!n?.pageInfo?.hasNextPage,r=n?.pageInfo?.endCursor||n?.pageInfo?.nextPage}return t};async function Bt(s){return(await Promise.allSettled(s)).map(e=>Sn(e)).filter(e=>e!=null)}var L=(s,{fallback:t,max:e})=>!s||s<=0?t:e===void 0?s:Math.min(s,e),x=(s,t)=>{if(!t||t.length===0)return s;let e=new Set(t);return s.filter(r=>e.has(r.state))},wn=s=>{if(!(!s||typeof s!="object")){if("statusCode"in s&&typeof s.statusCode=="number")return s.statusCode;if("response"in s&&s.response&&typeof s.response=="object"&&"status"in s.response&&typeof s.response.status=="number")return s.response.status}},qn=s=>{if(!(!s||typeof s!="object"||!("code"in s)||typeof s.code!="string"))return s.code},Hr=s=>{if(typeof s=="string")return s;if(s instanceof Error)return s.message},vn=s=>{let t=wn(s);if(t===401)return"authentication";if(t===404)return"not-found";if(t===429)return"rate-limit";if(t!==void 0)return"provider";let e=qn(s);if(e&&Pn.has(e))return"network";let r=Hr(s)?.toLowerCase();return r&&(r.includes("network")||r.includes("fetch failed")||r.includes("timed out")||r.includes("timeout")||r.includes("econn")||r.includes("enotfound")||r.includes("eai_again"))?"network":"unknown"},En=(s,t)=>{let e=Hr(t);return{scope:s,kind:vn(t),...e?{message:e}:{}}},be=(s,t=[])=>({completeness:s,...t.length?{failures:t}:{}}),Qr={complete:0,unknown:1,partial:2},zr=(s,t)=>Qr[s]>=Qr[t]?s:t,me=s=>s?s.id||`${s.namespace}/${s.name}`:void 0;async function te(s,{run:t,failureScope:e,completeness:r}){let n=await Promise.all(s.map(async u=>{try{return{scope:u,result:await t(u)}}catch(l){return{scope:u,error:l}}})),o=[],i=[],a="complete";return n.forEach(u=>{if("error"in u){o.push(En(e(u.scope),u.error)),a=zr(a,"partial");return}if(u.result===void 0)return;let l=u.result;a=zr(a,r?r(l):"complete"),i.push({scope:u.scope,result:l})}),{successes:i,metadata:be(a,o)}}function Sn(s,t=void 0){return s?.status==="fulfilled"?s.value:t}async function Vr(s,t,e){if(!Number.isFinite(t)||!Number.isInteger(t)||t<=0)throw new Error("batchSize must be a positive integer");for(let r=0;r<s.length;r+=t){let n=s.slice(r,r+t);await Promise.all(n.map(e))}}var ge=(e=>(e.Open="OPEN",e.Closed="CLOSED",e))(ge||{});var jt=(a=>(a[a.Unknown=0]="Unknown",a[a.Active=1]="Active",a[a.Fixed=2]="Fixed",a[a.WontFix=3]="WontFix",a[a.Closed=4]="Closed",a[a.ByDesign=5]="ByDesign",a[a.Pending=6]="Pending",a))(jt||{});var $=100;var Jr=globalThis.fetch;var Cn=async s=>{let t=s.headers.get("content-type")||"",e=null;if(t.startsWith("application/json")){let o=await s.text();e=o.trim().length>0?JSON.parse(o):null}else if(t.startsWith("text/")||t===""||t.startsWith("application/vnd.github.diff")||t.startsWith("application/vnd.github.patch"))e=await s.text();else if(t.startsWith("application/vnd.github.raw+json")||t.startsWith("application/octet-stream"))e=await s.arrayBuffer();else throw new Error(`Unsupported content-type: ${t}`);let r={};s.headers.forEach((o,i)=>{r[i]=o});let n={body:e,headers:r,status:s.status,statusText:s.statusText};if(!s.ok){let o=new Error(s.statusText);throw Object.assign(o,{response:n}),o}return n},Ft=s=>async({url:t,...e})=>{let r=await s(t,e);return Cn(r)};var ze=(s,t=!1)=>s.name==="fetch"||t;var M=class{constructor(t){let e=t?.request||Jr;this.config={...t,request:ze(e,t?.forceIsFetch)?Ft(e):e}}updateConfig(t){this.config={...this.config,...t,request:t.request&&ze(t.request,t?.forceIsFetch??this.config.forceIsFetch)?Ft(t.request):this.config.request}}},F=class extends M{};var Dn="https://app.vssps.visualstudio.com/_apis",An="https://vssps.dev.azure.com/",$n="https://dev.azure.com",q=(s,t={})=>R(t.token||s.token,t.isPAT||s.isPAT),Kr=s=>s.url.replace("/_apis/git/repositories/","/_git/").replace(`/${s.repository.project.id}/`,`/${encodeURIComponent(s.repository.project.name)}/`).replace(`/${s.repository.id}/`,`/${encodeURIComponent(s.repository.name)}/`).replace("/pullRequests/","/pullrequest/"),Qt=(s,t)=>{let e=t.baseUrl||s.baseUrl||Dn;return e=e.replace(/\/$/,""),e},C=(s,t)=>{let e=t.baseUrl||s.baseUrl||$n;return e=e.replace(/\/$/,""),e},zt=(s,t)=>{let e=t.baseUrl||s.baseUrl||An;return e=e.replace(/\/$/,""),e};var Ln={active:"OPEN",completed:"MERGED",abandoned:"CLOSED"},Un={OPEN:"active",MERGED:"completed",CLOSED:"abandoned"},ye=100,Gn=200,Tn=200,Xr=s=>{if(!s||s.length===0)return"active";let t=Array.from(new Set(s.map(e=>Un[e])));return t.length===1?t[0]:"all"},On=s=>{if(!s||s.length===0)return["[Microsoft.VSTS.Common.ClosedDate] = ''","[Microsoft.VSTS.Common.ResolvedDate] = ''"];let t=new Set(s),e=t.has("OPEN"),r=t.has("CLOSED");return e&&r?[]:r?["([Microsoft.VSTS.Common.ClosedDate] <> '' OR [Microsoft.VSTS.Common.ResolvedDate] <> '')"]:["[Microsoft.VSTS.Common.ClosedDate] = ''","[Microsoft.VSTS.Common.ResolvedDate] = ''"]},_n=s=>{if(typeof s!="string")return s;let t=s.charAt(0).toUpperCase()+s.slice(1);return jt[t]??0},kn=new Set([2,3,4,5]),xn={10:"APPROVED",5:"APPROVED",0:"REVIEW_REQUESTED",[-5]:"CHANGES_REQUESTED",[-10]:"CHANGES_REQUESTED"},he=s=>({id:s.id,name:s.displayName??null,username:(s.uniqueName||s.displayName)??null,email:null,avatarUrl:s.imageUrl??null,url:null}),Me=s=>s.startsWith("refs/heads/")?s.replace("refs/heads/",""):s,Nn=s=>{switch(s){case"conflicts":return"CONFLICTS";case"failure":return"FAILING_CHECKS";case"rejectedByPolicy":return"BLOCKED";case"succeeded":return"MERGEABLE";case"notSet":case"queued":default:return"UNKNOWN"}},Mt=(s,t,e,r,n,o)=>`${s}|${t}|${e}|${r}|${n}|${o}`,Zr=s=>{let t=s.split("|");if(t.length!==6)throw new Error("Invalid Azure comment ID format");return{namespace:t[0],project:t[1],repoName:t[2],prId:t[3],threadId:t[4],commentId:t[5]}},Yr=(s,t,e,r,n)=>`${s}|${t}|${e}|${r}|${n}`,Wt=s=>{let t=s.split("|");if(t.length!==5)throw new Error("Invalid Azure thread ID format");return{namespace:t[0],project:t[1],repoName:t[2],prId:t[3],threadId:t[4]}},Ge=(s,t,e)=>{let r=!!t.forkSource,n=[],o=[];return t.reviewers.forEach(i=>{let a={reviewer:he(i),state:xn[i.vote??0]||"REVIEW_REQUESTED"};i.isRequired&&n.push(a),o.push(a)}),{id:t.pullRequestId.toString(),title:t.title,description:t.description??null,number:t.codeReviewId,state:Ln[t.status],isDraft:t.isDraft,commentCount:null,upvoteCount:null,author:he(t.createdBy),createdDate:new Date(t.creationDate),updatedDate:new Date(t.closedDate||t.creationDate),closedDate:t.closedDate?new Date(t.closedDate):null,mergedDate:t.closedDate&&t.status==="completed"?new Date(t.closedDate):null,isCrossRepository:r,repository:{id:t.repository.id,name:t.repository.name,project:t.repository.project.name,owner:{login:s},remoteInfo:e?.get(t.repository.id)??null},headCommit:{buildStatuses:null},baseRef:{name:Me(t.targetRefName),oid:t.lastMergeTargetCommit.commitId},headRef:{name:Me(t.sourceRefName),oid:t.lastMergeSourceCommit.commitId},url:Kr(t),assignees:t.reviewers.map(he),reviews:o,reviewDecision:J(n),additions:null,deletions:null,fileCount:null,commitCount:null,headRepository:t.forkSource?{id:t.forkSource.repository.id,name:t.forkSource.repository.name,project:void 0,owner:{login:s},remoteInfo:e?.get(t.forkSource.repository.id)??null,isFork:!0}:{id:t.repository.id,name:t.repository.name,project:t.repository.project.name,owner:{login:s},remoteInfo:e?.get(t.repository.id)??null,isFork:!1},mergeableState:Nn(t.mergeStatus),labels:t.labels?.map(i=>({color:null,description:null,id:i.id,name:i.name}))??[],permissions:null}},es=(s,t)=>({id:t.id,name:t.name,namespace:s,project:t.project.name,projectId:t.project.id,webUrl:t.webUrl,httpsUrl:t.remoteUrl,sshUrl:t.sshUrl,defaultBranch:t.defaultBranch?{name:Me(t.defaultBranch)}:null,permissions:null}),Bn=(s,t,e,r)=>{let n=e.fields,o=n["System.AssignedTo"],i=n["System.State"],a=n["System.WorkItemType"],u;return i&&a&&(u=r[a]?.[i]),{id:e.id.toString(),number:e.id.toString(),title:n["System.Title"],commentCount:n["System.CommentCount"],author:{avatarUrl:n["System.CreatedBy"]._links?.avatar?.href??null,email:null,id:n["System.CreatedBy"].id,name:n["System.CreatedBy"].uniqueName??null,username:n["System.CreatedBy"].displayName??null,url:null},closedDate:n["Microsoft.VSTS.Common.ClosedDate"]?new Date(n["Microsoft.VSTS.Common.ClosedDate"]):null,createdDate:new Date(n["System.CreatedDate"]),updatedDate:new Date(n["System.ChangedDate"]),url:e._links.html.href,assignees:o?[{avatarUrl:o._links?.avatar?.href??null,email:null,id:o.id,name:o.uniqueName??null,username:o.displayName??null,url:null}]:[],description:n["System.Description"]??null,state:{name:u?.title||i,color:null},type:n["System.WorkItemType"],repository:null,project:{namespace:s,name:t,resourceId:null,key:null,id:null},upvoteCount:0,labels:e.fields["System.Tags"]?.split(";").map(l=>({color:null,description:null,id:null,name:l.trim()}))??[]}},Pe=class extends F{constructor(){super(...arguments);this.cachedUserIds=new Map;this.inflightUserIds=new Map}getCurrentUserId(e,r){let n=JSON.stringify([e,r.token??null,r.isPAT??this.config.isPAT??!1,r.baseUrl??null]),o=this.cachedUserIds.get(n);if(o)return Promise.resolve(o);let i=this.inflightUserIds.get(n);if(i)return i;let a=this.fetchCurrentUserId(e,r,n);return this.inflightUserIds.set(n,a),a}async fetchCurrentUserId(e,r,n){try{let o=await this.getCurrentUserForInstance({namespace:e},r);return this.cachedUserIds.set(n,o.data.id),o.data.id}finally{this.inflightUserIds.delete(n)}}getRepoApiUrl(e,r,n,o){return`${C(this.config,o)}/${encodeURIComponent(e)}/${encodeURIComponent(r)}/_apis/git/repositories/${encodeURIComponent(n)}`}async getCurrentUser(e={},r={}){if(r.isPAT||this.config.isPAT)throw new Error("Azure DevOps does not support PATs for this function.");let n=`${Qt(this.config,r)}/profile/profiles/me`,o=await this.config.request({url:n,headers:q(this.config,r)});return{data:{id:o.body.id,name:o.body.displayName,username:o.body.displayName,email:o.body.emailAddress,avatarUrl:null,url:null}}}async getCurrentUserForInstance(e,r={}){let o=(await this.config.request({url:`${C(this.config,r)}/${encodeURIComponent(e.namespace)}/_apis/ConnectionData`,headers:q(this.config,r)})).body.authorizedUser;if(o.providerDisplayName==="Anonymous")throw new Error("Current user not found.");return{data:{id:o.id,name:o.providerDisplayName,username:o.providerDisplayName,email:o.properties.Account.$value,avatarUrl:null,url:null}}}async getUserForCommit(e,r={}){if(!e.repo.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let o=(await this.config.request({url:`${C(this.config,r)}/${encodeURIComponent(e.repo.namespace)}/${encodeURIComponent(e.repo.project)}/_apis/git/repositories/${encodeURIComponent(e.repo.name)}/commits/${e.oid}`,headers:q(this.config,r)})).body.author;return{data:{name:o.name,email:o.email,avatarUrl:o.imageUrl}}}async getOrgsForUser(e,r={}){let n=`${Qt(this.config,r)}/accounts?memberId=${e.userId}&api-version=6.0`;return{data:(await this.config.request({url:n,headers:q(this.config,r)})).body.value.map(i=>({id:i.accountId,name:i.accountName}))}}async getCollectionsForUser(e,r={}){let n=`${C(this.config,r)}/_apis/projectCollections`;return{data:(await this.config.request({url:n,headers:q(this.config,r)})).body.value.map(i=>({id:i.id,name:i.name}))}}async getAzureProjects(e,r={}){let n=new URL(`${C(this.config,r)}/${encodeURIComponent(e.namespace)}/_apis/projects`);n.searchParams.set("$top",$.toString()),e.cursor&&n.searchParams.set("$skip",e.cursor);let o=await this.config.request({url:n.toString(),headers:q(this.config,r)}),i=o.headers["x-ms-continuationtoken"];return{pageInfo:{hasNextPage:!!i,endCursor:i||null},data:o.body.value.map(a=>({id:a.id,name:a.name,namespace:e.namespace}))}}async getAzureProjectScopeDescriptor(e,r={}){let{namespace:n,projectId:o}=e;return{data:{scope:(await this.config.request({url:`${zt(this.config,r)}/${encodeURIComponent(n)}/_apis/graph/descriptors/${o}?api-version=6.0`,headers:q(this.config,r)})).body.value}}}async getAzureGraphAccountsForAzureProject(e,r={}){let{namespace:n,projectScopeDescriptor:o,cursor:i}=e,a=new URL(`${zt(this.config,r)}/${encodeURIComponent(n)}/_apis/graph/users`);o&&a.searchParams.set("scopeDescriptor",o),i&&a.searchParams.set("continuationToken",i);let u=await this.config.request({url:a.toString(),headers:q(this.config,r)}),l=u.headers["x-ms-continuationtoken"];return{pageInfo:{endCursor:l||null,hasNextPage:!!l},data:u.body.value.map(d=>({avatarUrl:d._links?.avatar?.href??null,descriptor:d.descriptor??null,email:d.mailAddress??null,name:d.displayName??null,storageKeyURL:d._links?.storageKey?.href??null,username:d.displayName??null}))}}async getAccountFromAzureGraphAccount(e,r={}){let{azureGraphAccount:n}=e;if(!n.storageKeyURL)throw new Error("Expected 'storageKeyURL' to not be null for 'azureGraphAccount'");let o=await this.config.request({url:n.storageKeyURL,headers:q(this.config,r)});return{data:{avatarUrl:n.avatarUrl,email:n.email,id:o.body.value,name:n.name,username:n.username,url:null}}}async getAccountsFromAzureGraphAccounts(e,r={}){let n=[];for(let o of e.azureGraphAccounts){let i=await this.getAccountFromAzureGraphAccount({azureGraphAccount:o},r);n.push(i.data)}return{data:n}}async getRepo(e,r={}){if(!e.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let n=await this.config.request({url:`${C(this.config,r)}/${encodeURIComponent(e.namespace)}/${encodeURIComponent(e.project)}/_apis/git/repositories/${encodeURIComponent(e.name)}`,headers:q(this.config,r)});return{data:es(e.namespace,n.body)}}async getRepos(e,r={}){let n=[],o=[];return await Promise.all(e.map(async i=>{try{let a=await this.getRepo(i,r);n.push(a.data)}catch(a){o.push({input:i,error:a})}})),{data:n,errors:o}}async getReposForAzureProject(e,r={}){if(!e.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');return{data:(await this.config.request({url:`${C(this.config,r)}/${encodeURIComponent(e.namespace)}/${encodeURIComponent(e.project)}/_apis/git/repositories`,headers:q(this.config,r)})).body.value.map(o=>es(e.namespace,o))}}async getRefs(e,r,n={}){if(!r.repo.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let o=new URL(`${C(this.config,n)}/${encodeURIComponent(r.repo.namespace)}/${encodeURIComponent(r.repo.project)}/_apis/git/repositories/${encodeURIComponent(r.repo.name)}/refs`);o.searchParams.set("filter",e),o.searchParams.set("$top",$.toString()),r.cursor&&o.searchParams.set("continuationToken",r.cursor);let i=await this.config.request({url:o.toString(),headers:q(this.config,n)}),a=i.headers["x-ms-continuationtoken"];return{pageInfo:{hasNextPage:!!a,endCursor:a||null},data:i.body.value.map(u=>({name:Me(u.name),commit:{oid:u.objectId,authoredDate:null,committedDate:null}}))}}async getBranches(e,r={}){return this.getRefs("heads",e,r)}async getTags(e,r={}){return this.getRefs("tags",e,r)}async fetchRemoteInfoByRepoId(e,r,n){let o=new Map;if(!e)return o;let i=new Map;for(let{namespace:a,pullRequests:u}of r)for(let l of u)i.has(l.repository.id)||i.set(l.repository.id,a),l.forkSource&&!i.has(l.forkSource.repository.id)&&i.set(l.forkSource.repository.id,a);return await Vr([...i],10,async([a,u])=>{try{let l=await this.config.request({url:`${C(this.config,n)}/${encodeURIComponent(u)}/_apis/git/repositories/${encodeURIComponent(a)}`,headers:q(this.config,n)}),{remoteUrl:d,sshUrl:p}=l.body;d&&p&&o.set(a,{cloneUrlHTTPS:d,cloneUrlSSH:p})}catch{}}),o}async getPullRequestsForRepoBase(e,r={},n=ye){let{page:o,repo:i,assigneeLogins:a,authorLogin:u,reviewerId:l}=e||{},d=o||1;if(!i.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let p=L(e.pageSize,{fallback:n}),c=l??(a&&a.length?a[0]:void 0),g=`searchCriteria.status=${Xr(e.states)}`;return c&&(g+=`&searchCriteria.reviewerId=${encodeURIComponent(c)}`),u&&(g+=`&searchCriteria.creatorId=${encodeURIComponent(u)}`),await this.config.request({url:`${C(this.config,r)}/${encodeURIComponent(i.namespace)}/${encodeURIComponent(i.project||"")}/_apis/git/repositories/${encodeURIComponent(i.name)}/pullRequests?${g}&%24top=${p}&%24skip=${(d-1)*p}`,headers:q(this.config,r)})}async getPullRequestsForRepo(e,r={}){let n=L(e.pageSize,{fallback:ye}),o=e.page||1,i=await this.getPullRequestsForRepoBase(e,r,n),a=i.body.value.length===n,u=await this.fetchRemoteInfoByRepoId(e.includeRemoteInfo,[{namespace:e.repo.namespace,pullRequests:i.body.value}],r);return{pageInfo:{hasNextPage:a,nextPage:a?o+1:null,currentPage:o},data:x(i.body.value.map(l=>Ge(e.repo.namespace,l,u)),e.states)}}async getPullRequestsForRepos(e,r={}){if(!e.repos.every(p=>p.project))throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let{repos:n}=e||{},o=L(e.pageSize,{fallback:ye}),{successes:i,metadata:a}=await te(n,{run:p=>this.getPullRequestsForRepoBase({repo:p,assigneeLogins:e.assigneeLogins,authorLogin:e.authorLogin,reviewerId:e.reviewerId,states:e.states,pageSize:o},r,o),failureScope:p=>({providerId:"azure",projectId:p.project,repositoryId:me(p)}),completeness:p=>p.body.value.length===o?"unknown":"complete"}),u=i.map(({scope:p,result:c})=>({namespace:p.namespace,pullRequests:c.body.value})),l=await this.fetchRemoteInfoByRepoId(e.includeRemoteInfo,u,r),d=u.flatMap(({namespace:p,pullRequests:c})=>c.map(g=>Ge(p,g,l)));return{data:x(d,e.states),metadata:a}}async getPullRequestsForProjectBase(e,r={},n=ye){let{namespace:o,project:i,page:a,assigneeLogins:u,authorLogin:l,reviewerId:d,repo:p}=e;if(p?.project&&p.project!==i)throw new Error("Could not fetch pull requests, project mismatch");let c=a||1,g=L(e.pageSize,{fallback:n}),m=d??(u&&u.length?u[0]:void 0),h=new URL(`${C(this.config,r)}/${encodeURIComponent(o)}/${encodeURIComponent(i)}/_apis/git/pullRequests`);return h.searchParams.set("searchCriteria.status",Xr(e.states)),h.searchParams.set("$top",g.toString()),h.searchParams.set("$skip",((c-1)*g).toString()),p?.id&&p?.project===i&&h.searchParams.set("searchCriteria.repositoryId",p.id),m&&h.searchParams.set("searchCriteria.reviewerId",m),l&&h.searchParams.set("searchCriteria.creatorId",l),await this.config.request({url:h.toString(),headers:q(this.config,r)})}async getPullRequestsForProject(e,r={}){let n=L(e.pageSize,{fallback:ye}),o=e.page||1,i=await this.getPullRequestsForProjectBase(e,r,n),a=i.body.value.length===n,u=await this.fetchRemoteInfoByRepoId(e.includeRemoteInfo,i?[{namespace:e.namespace,pullRequests:i.body.value}]:[],r);return{pageInfo:{hasNextPage:a,nextPage:a?o+1:null,currentPage:o},data:x(i?.body.value.map(l=>Ge(e.namespace,l,u))||[],e.states)}}async getPullRequestsForProjects(e,r={}){let{projects:n}=e||{};if(e.repo&&!e.repo.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let o=L(e.pageSize,{fallback:ye}),{successes:i,metadata:a}=await te(n,{run:p=>e.repo&&e.repo.project!==p.project?Promise.resolve(void 0):this.getPullRequestsForProjectBase({...p,assigneeLogins:e.assigneeLogins,authorLogin:e.authorLogin,reviewerId:e.reviewerId,states:e.states,pageSize:o,repo:e.repo},r,o),failureScope:p=>({providerId:"azure",projectId:p.project,repositoryId:me(e.repo)}),completeness:p=>p.body.value.length===o?"unknown":"complete"}),u=i.map(({scope:p,result:c})=>({namespace:p.namespace,pullRequests:c.body.value})),l=await this.fetchRemoteInfoByRepoId(e.includeRemoteInfo,u,r),d=u.flatMap(({namespace:p,pullRequests:c})=>c.map(g=>Ge(p,g,l)));return{data:x(d,e.states),metadata:a}}async getAzurePullRequestLastMergeStatus(e,r={}){if(!e.repo.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let{repo:{namespace:n,project:o,name:i},pullRequestId:a}=e,u=await this.config.request({url:`${C(this.config,r)}/${encodeURIComponent(n)}/${encodeURIComponent(o||"")}/_apis/git/repositories/${i}/pullrequests/${a}?includeCommits=true?api-version=6.0`,headers:{...q(this.config,r)}});if(!u.body.mergeStatus)throw new Error("Could not fetch pull request");return{data:u.body.mergeStatus}}async updatePullRequest(e,r,n){return await this.config.request({method:"PATCH",url:`${C(this.config,n)}/${encodeURIComponent(e.repository.owner.login)}/${encodeURIComponent(e.repository.project)}/_apis/git/repositories/${e.repository.name}/pullrequests/${e.id}?api-version=6.0`,body:r,headers:{...q(this.config,n),"Content-Type":"application/json"}})}async closePullRequest(e,r={}){let{pullRequest:n}=e,o={status:"abandoned"};if(!(await this.updatePullRequest(n,JSON.stringify(o),r)).body.status)throw new Error("Could not close pull request")}async mergePullRequest(e,r={}){let{pullRequest:n,mergeStrategy:o}=e,i;switch(o){case"MERGE_COMMIT":{i="noFastForward";break}case"REBASE":{i="rebase";break}case"REBASE_THEN_MERGE_COMMIT":{i="rebaseMerge";break}case"SQUASH":{i="squash";break}}let a={completionOptions:{mergeStrategy:i},lastMergeSourceCommit:{commitId:n.headRef?.oid},status:"completed"};if(!(await this.updatePullRequest(n,JSON.stringify(a),r)).body.status)throw new Error("Could not merge pull request")}async addPullRequestLabel(e,r={}){let{pullRequest:n,label:o}=e;if(!n.repository.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let i={name:o.name};if(!(await this.config.request({method:"POST",url:`${C(this.config,r)}/${encodeURIComponent(n.repository.owner.login)}/${encodeURIComponent(n.repository.project)}/_apis/git/repositories/${n.repository.name}/pullrequests/${n.id}/labels?api-version=6.0`,body:JSON.stringify(i),headers:{...q(this.config,r),"Content-Type":"application/json"}})).body.id)throw new Error("Could not add pull request label")}async removePullRequestLabel(e,r={}){let{pullRequest:n,label:o}=e;if(!n.repository.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');await this.config.request({method:"DELETE",url:`${C(this.config,r)}/${encodeURIComponent(n.repository.owner.login)}/${encodeURIComponent(n.repository.project)}/_apis/git/repositories/${n.repository.name}/pullrequests/${n.id}/labels/${encodeURIComponent(o.name)}?api-version=6.0`,headers:{...q(this.config,r)}})}async setPullRequestLabels(e,r={}){let{pullRequest:n,labels:o}=e;if(!n.repository.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let i=n.labels;if(!i)throw new Error('Azure DevOps requires "labels" for this function.');for(let a of o)i.find(u=>u.id===a.id)||await this.addPullRequestLabel({pullRequest:n,label:a},r);for(let a of i)o.find(u=>a.id===u.id)||await this.removePullRequestLabel({pullRequest:n,label:a},r)}async setPullRequestAsDraft(e,r={}){let{pullRequest:n,isDraft:o}=e,i={isDraft:o};if(!(await this.updatePullRequest(n,JSON.stringify(i),r)).body.status)throw new Error("Could not set the pull request as draft")}async addPullRequestReviewer(e,r={}){let{pullRequest:n,reviewer:o,isRequired:i}=e,a={id:o.id,isRequired:i};if(!(await this.config.request({method:"PUT",url:`${C(this.config,r)}/${encodeURIComponent(n.repository.owner.login)}/${encodeURIComponent(n.repository.project)}/_apis/git/repositories/${n.repository.name}/pullrequests/${n.id}/reviewers/${o.id}?api-version=6.0`,body:JSON.stringify(a),headers:{...q(this.config,r),"Content-Type":"application/json"}})).body.id)throw new Error("Could not add pull request reviewer")}async removePullRequestReviewer(e,r={}){let{pullRequest:n,reviewer:o}=e;await this.config.request({method:"DELETE",url:`${C(this.config,r)}/${encodeURIComponent(n.repository.owner.login)}/${encodeURIComponent(n.repository.project)}/_apis/git/repositories/${n.repository.name}/pullrequests/${n.id}/reviewers/${o.id}?api-version=6.0`,headers:{...q(this.config,r),Accept:"application/json"}})}async setPullRequestReviewers(e,r={}){let{pullRequest:n,reviewers:o}=e;for(let i of o)n.assignees.find(a=>a.id===i.id)||await this.addPullRequestReviewer({pullRequest:n,reviewer:i,isRequired:!0},r);for(let i of n.assignees)o.find(a=>i.id===a.id)||await this.removePullRequestReviewer({pullRequest:n,reviewer:i},r)}async getIssuesForAzureProject(e,r={}){let{page:n,assigneeLogins:o,authorLogin:i,mentionLogin:a,labelNames:u,statusByWorkItemIdByStatusId:l}=e||{},d=n||1,p=Math.min(L(e.pageSize,{fallback:Gn}),Tn),c=["[System.TeamProject] = @project",...On(e.states)];i&&c.push(`[System.CreatedBy] = '${i.replace("'","''")}'`),o&&o[0]&&c.push(`[System.AssignedTo] = '${o[0].replace("'","''")}'`),a&&c.push("[System.Id] IN (@recentMentions)"),u&&u.forEach(A=>c.push(`[System.Tags] Contains '${A}'`));let g=`Select [Microsoft.VSTS.Common.ClosedDate], [Microsoft.VSTS.Common.ResolvedDate] From WorkItems Where ${c.join(" AND ")} order by [System.CreatedDate] desc`,m=await this.config.request({url:`${C(this.config,r)}/${encodeURIComponent(e.namespace)}/${encodeURIComponent(e.project)}/_apis/wit/wiql?api-version=6.0`,body:JSON.stringify({query:g}),method:"POST",headers:{...q(this.config,r),"Content-Type":"application/json"}}),h=m.body.workItems.slice((d-1)*p,p*d).map(A=>A.id),y=m.body.workItems.length,f=Math.ceil(y/p),P=y>p*d;if(h.length===0)return{pageInfo:{hasNextPage:!1,nextPage:null,currentPage:d,totalCount:y,totalPages:f},data:[]};let v=await this.config.request({url:`${C(this.config,r)}/${encodeURIComponent(e.namespace)}/${encodeURIComponent(e.project)}/_apis/wit/workitemsbatch?api-version=6.0`,body:JSON.stringify({ids:h,$expand:"Links"}),method:"POST",headers:{...q(this.config,r),"Content-Type":"application/json"}});return{pageInfo:{hasNextPage:P,nextPage:P?d+1:null,currentPage:d,totalCount:y,totalPages:f},data:v.body.value.map(A=>Bn(e.namespace,e.project,A,l||{}))}}async getPermissionsForRepos(e,r={}){let{namespace:n,repos:o}=e,i={4:["canPush","canCreateWebhook"],1024:["isAdmin"],2048:["isAdmin"],4096:["isAdmin"],8192:["isAdmin"]},a=p=>{let c="2e9eb7ed-3c0a-47d4-87c1-0ffdd275fd87",g=`repoV2/${p.projectId}/${p.id}`;return Object.keys(i).map(m=>({securityNamespaceId:c,token:g,permissions:m}))},u={alwaysAllowAdministrators:!1,evaluations:o.flatMap(a)};return{data:(await this.config.request({method:"POST",url:`${C(this.config,r)}/${encodeURIComponent(n)}/_apis/security/permissionevaluationbatch?api-version=7.0`,body:JSON.stringify(u),headers:{...q(this.config,r),"Content-Type":"application/json"}})).body.evaluations.reduce((p,c)=>{let[,g,m]=c.token.split("/"),h=`${g}/${m}`,y=i[c.permissions];for(let f of y)p[h]===void 0&&(p[h]={canCreateWebhook:!0,canPush:!0,isAdmin:!0}),c.value===!1&&(p[h][f]=!1);return p},{})}}async decorateReposWithPermissions(e,r={}){let{namespace:n,repos:o}=e,i=await this.getPermissionsForRepos({namespace:n,repos:o},r);return{data:o.map(a=>({...a,permissions:i.data[`${a.projectId}/${a.id}`]}))}}async updateIssue(e,r,n={}){return await this.config.request({method:"PATCH",url:`${C(this.config,n)}/${encodeURIComponent(e.project.namespace)}/${encodeURIComponent(e.project.name)}/_apis/wit/workitems/${e.id}?api-version=6.0`,body:JSON.stringify(r),headers:{...q(this.config,n),"Content-Type":"application/json-patch+json"}})}async setIssueStatus(e,r={}){let{issue:n,status:o}=e,i=[{op:"add",path:"/fields/System.State",value:o.name}];if(!(await this.updateIssue(n,i,r)).body.fields?.["System.State"])throw new Error("Could not set issue status")}async setIssueAssignee(e,r={}){let{issue:n,assignee:o}=e,i=[{op:"add",path:"/fields/System.AssignedTo",value:o?.name??""}];if(!(await this.updateIssue(n,i,r)).body.fields?.["System.State"])throw new Error("Could not set issue assignee")}async setIssueLabels(e,r={}){let{issue:n,labels:o}=e,a=[{op:"replace",path:"/fields/System.Tags",value:o.map(l=>l.name).join(";")}];if(!(await this.updateIssue(n,a,r)).body.fields?.["System.Tags"])throw new Error("Could not set issue tags")}async getIssueTypesForAzureProject(e,r={}){if(!e.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let{namespace:n,project:o}=e;return{data:(await this.config.request({url:`${C(this.config,r)}/${encodeURIComponent(n)}/${encodeURIComponent(o||"")}/_apis/wit/workitemtypes?api-version=6.0`,headers:{...q(this.config,r)}})).body.value}}async getLabelsForProject(e,r={}){let{namespace:n,project:o}=e;return{data:(await this.config.request({url:`${C(this.config,r)}/${encodeURIComponent(n)}/${encodeURIComponent(o||"")}/_apis/wit/tags?api-version=6.0`,headers:{...q(this.config,r)}})).body.value.map(a=>({color:null,description:null,id:a.id,name:a.name,url:a.url}))}}async getPullRequestForRepo(e,r={}){let{repo:n,number:o}=e;if(!n.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let i=await this.config.request({url:`${this.getRepoApiUrl(n.namespace,n.project,n.name,r)}/pullrequests/${o}?api-version=7.1`,headers:q(this.config,r)}),a=await this.fetchRemoteInfoByRepoId(e.includeRemoteInfo,[{namespace:n.namespace,pullRequests:[i.body]}],r);return{data:Ge(n.namespace,i.body,a)}}async getPullRequestDescription(e,r={}){let{repo:n,number:o}=e;if(!n.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');try{return{data:{description:(await this.config.request({url:`${this.getRepoApiUrl(n.namespace,n.project,n.name,r)}/pullrequests/${o}?api-version=7.1`,headers:q(this.config,r)})).body?.description??""}}}catch{return{data:{description:null}}}}async setPullRequestDescription(e,r={}){let{repo:n,number:o,description:i}=e;if(!n.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');return{data:{description:(await this.config.request({method:"PATCH",url:`${this.getRepoApiUrl(n.namespace,n.project,n.name,r)}/pullrequests/${o}?api-version=7.1`,headers:{...q(this.config,r),"Content-Type":"application/json"},body:JSON.stringify({description:i})})).body?.description??i}}}async getMergeBase(e,r={}){if(!e.repo.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let n=await this.config.request({url:`${this.getRepoApiUrl(e.repo.namespace,e.repo.project,e.repo.name,r)}/commits/${encodeURIComponent(e.base)}/mergebases?otherCommitId=${encodeURIComponent(e.head)}&api-version=7.1`,headers:q(this.config,r)});if(!n.body.value?.length)throw new Error("No merge base found between the specified commits.");return{data:n.body.value[0].commitId}}async getFileContents(e,r={}){if(!e.repo.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let n=await this.config.request({url:`${this.getRepoApiUrl(e.repo.namespace,e.repo.project,e.repo.name,r)}/items?path=${encodeURIComponent(e.path)}&versionDescriptor[version]=${encodeURIComponent(e.ref)}&versionDescriptor[versionType]=commit&api-version=7.1`,headers:{...q(this.config,r),Accept:"application/octet-stream"}});return{data:new Blob([n.body])}}async getPullRequestDiff(e,r={}){if(!e.repo.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let n=this.getRepoApiUrl(e.repo.namespace,e.repo.project,e.repo.name,r),o=q(this.config,r),i={...o,Accept:"application/octet-stream"},[a,u]=await Promise.all([this.config.request({url:`${n}/pullrequests/${e.pullRequestId}?api-version=7.1`,headers:o}),this.config.request({url:`${n}/pullrequests/${e.pullRequestId}/iterations?api-version=7.1`,headers:o})]),l=a.body.lastMergeTargetCommit.commitId,d=a.body.lastMergeSourceCommit.commitId,p=u.body.value;if(p.length===0)return"";let c=p[p.length-1],g=1e3,m=[],h=0;for(;;){let S=(await this.config.request({url:`${n}/pullrequests/${e.pullRequestId}/iterations/${c.id}/changes?api-version=7.1&$top=${g}&$skip=${h}`,headers:o})).body.changeEntries??[];if(S.length===0||(m.push(...S),S.length<g))break;h+=S.length}if(m.length===0)return"";let y=5,f=[],P=new TextDecoder,v=w=>w instanceof ArrayBuffer?P.decode(w):typeof w=="string"?w:"",A=async(w,S)=>{try{let pe=await this.config.request({url:`${n}/items?path=${encodeURIComponent(w)}&versionDescriptor[version]=${encodeURIComponent(S)}&versionDescriptor[versionType]=commit&includeContent=true&api-version=7.1`,headers:i});return v(pe.body)}catch{return""}},D=w=>{if(typeof w=="number")return{add:(w&1)!==0,rename:(w&8)!==0,delete:(w&16)!==0};let S=w.toLowerCase().split(",").map(pe=>pe.trim());return{add:S.includes("add"),rename:S.includes("rename"),delete:S.includes("delete")}};for(let w=0;w<m.length;w+=y){let S=m.slice(w,w+y),pe=await Promise.all(S.map(async fe=>{let{add:Re,rename:kt,delete:de}=D(fe.changeType),Le=fe.originalPath??fe.item.originalPath,T=fe.item.path,Fe=de?T??Le??"":T??"",Br=kt||de?Le??Fe:Fe,[cn,mn]=await Promise.all([Re?Promise.resolve(""):A(Br,l),de?Promise.resolve(""):A(Fe,d)]),gn=Re?"/dev/null":`a${Br}`,hn=de?"/dev/null":`b${Fe}`;return(0,ts.createTwoFilesPatch)(gn,hn,cn,mn)}));f.push(...pe)}return f.join(`
|
|
2
|
+
`)}getPullRequestWriteHeaders(e){return{...q(this.config,e),"Content-Type":"application/json"}}setReviewerVote(e,r,n,o,i){return this.config.request({method:"PUT",url:`${e}/pullRequests/${r}/reviewers/${encodeURIComponent(n)}?api-version=7.1`,headers:this.getPullRequestWriteHeaders(i),body:JSON.stringify({vote:o})})}postPullRequestThread(e,r,n,o){return this.config.request({method:"POST",url:`${e}/pullRequests/${r}/threads?api-version=7.1`,headers:this.getPullRequestWriteHeaders(o),body:JSON.stringify({comments:[{parentCommentId:0,content:n,commentType:1}],status:1})})}async getCommentsForPullRequest(e,r={}){if(!e.repo.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let n=this.getRepoApiUrl(e.repo.namespace,e.repo.project,e.repo.name,r),o=q(this.config,r),i=await this.config.request({url:`${n}/pullRequests/${e.pullRequestNumber}/threads?api-version=7.1`,headers:o}),a=[];for(let u of i.body.value)if(!(u.isDeleted||u.threadContext))for(let l of u.comments)l.commentType==="system"||l.isDeleted||a.push({id:Mt(e.repo.namespace,e.repo.project,e.repo.name,e.pullRequestNumber,u.id,l.id),author:l.author?he(l.author):null,body:l.content||"",createdAt:l.publishedDate?new Date(l.publishedDate):null,url:""});return{data:a,pageInfo:{hasNextPage:!1,endCursor:null}}}async addCommentToPullRequest(e,r={}){if(!e.pullRequest.repository.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let n=this.getRepoApiUrl(e.pullRequest.repository.owner.login,e.pullRequest.repository.project,e.pullRequest.repository.name,r);await this.postPullRequestThread(n,e.pullRequest.id,e.comment,r)}async addInlineCommentToPullRequest(e,r={}){if(!e.pullRequest.repository.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let n=this.getRepoApiUrl(e.pullRequest.repository.owner.login,e.pullRequest.repository.project,e.pullRequest.repository.name,r),o=this.getPullRequestWriteHeaders(r);if(e.threadId){let d=Wt(e.threadId),p=e.pullRequest.repository.owner.login,c=e.pullRequest.repository.project,g=e.pullRequest.repository.name,m=String(e.pullRequest.id);if(d.namespace!==p||d.project!==c||d.repoName!==g||d.prId!==m)throw new Error(`Azure thread ID context mismatch: threadId targets ${d.namespace}/${d.project}/${d.repoName} pull request ${d.prId}, but input.pullRequest targets ${p}/${c}/${g} pull request ${m}.`);let y=(await this.config.request({url:`${n}/pullRequests/${e.pullRequest.id}/threads/${d.threadId}?api-version=7.1`,headers:q(this.config,r)})).body.comments?.find(P=>P.parentCommentId===0);if(!y)throw new Error(`Could not determine root comment for Azure DevOps thread ${d.threadId}.`);let f=await this.config.request({method:"POST",url:`${n}/pullRequests/${e.pullRequest.id}/threads/${d.threadId}/comments?api-version=7.1`,headers:o,body:JSON.stringify({content:e.comment,parentCommentId:y.id,commentType:1})});return Mt(p,c,g,Number(m),Number(d.threadId),f.body.id)}let i=e.path.startsWith("/")?e.path:`/${e.path}`,a={line:e.line,offset:1},u={filePath:i};e.side==="LEFT"?(u.leftFileStart=a,u.leftFileEnd=a):(u.rightFileStart=a,u.rightFileEnd=a);let l=await this.config.request({method:"POST",url:`${n}/pullRequests/${e.pullRequest.id}/threads?api-version=7.1`,headers:o,body:JSON.stringify({comments:[{parentCommentId:0,content:e.comment,commentType:1}],status:1,threadContext:u})});return Yr(e.pullRequest.repository.owner.login,e.pullRequest.repository.project,e.pullRequest.repository.name,Number(e.pullRequest.id),l.body.id)}async editComment(e,r={}){let n=Zr(e.commentId),o=this.getRepoApiUrl(n.namespace,n.project,n.repoName,r);await this.config.request({method:"PATCH",url:`${o}/pullRequests/${n.prId}/threads/${n.threadId}/comments/${n.commentId}?api-version=7.1`,headers:this.getPullRequestWriteHeaders(r),body:JSON.stringify({content:e.body})})}async editInlineComment(e,r={}){return this.editComment(e,r)}async deleteComment(e,r={}){let n=Zr(e.commentId),o=this.getRepoApiUrl(n.namespace,n.project,n.repoName,r);await this.config.request({method:"DELETE",url:`${o}/pullRequests/${n.prId}/threads/${n.threadId}/comments/${n.commentId}?api-version=7.1`,headers:q(this.config,r)})}async deleteInlineComment(e,r={}){return this.deleteComment(e,r)}async resolveReviewThread(e,r={}){let n=Wt(e.threadId),o=this.getRepoApiUrl(n.namespace,n.project,n.repoName,r);await this.config.request({method:"PATCH",url:`${o}/pullRequests/${n.prId}/threads/${n.threadId}?api-version=7.1`,headers:this.getPullRequestWriteHeaders(r),body:JSON.stringify({status:2})})}async unresolveReviewThread(e,r={}){let n=Wt(e.threadId),o=this.getRepoApiUrl(n.namespace,n.project,n.repoName,r);await this.config.request({method:"PATCH",url:`${o}/pullRequests/${n.prId}/threads/${n.threadId}?api-version=7.1`,headers:this.getPullRequestWriteHeaders(r),body:JSON.stringify({status:1})})}async approvePullRequest(e,r={}){if(!e.pullRequest.repository.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let n=e.pullRequest.repository.owner.login,o=this.getRepoApiUrl(n,e.pullRequest.repository.project,e.pullRequest.repository.name,r),i=await this.getCurrentUserId(n,r);await Promise.all([this.setReviewerVote(o,e.pullRequest.id,i,10,r),e.comment?this.postPullRequestThread(o,e.pullRequest.id,e.comment,r):null])}async requestPullRequestChanges(e,r={}){if(!e.pullRequest.repository.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let n=e.pullRequest.repository.owner.login,o=this.getRepoApiUrl(n,e.pullRequest.repository.project,e.pullRequest.repository.name,r),i=await this.getCurrentUserId(n,r);await this.postPullRequestThread(o,e.pullRequest.id,e.comment,r),await this.setReviewerVote(o,e.pullRequest.id,i,-5,r)}async commentOnPullRequest(e,r={}){if(!e.pullRequest.repository.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let n=this.getRepoApiUrl(e.pullRequest.repository.owner.login,e.pullRequest.repository.project,e.pullRequest.repository.name,r);await this.postPullRequestThread(n,e.pullRequest.id,e.comment,r)}async getReviewsForPullRequest(e,r={}){if(!e.repo.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let{namespace:n,project:o,name:i}=e.repo,{pullRequestId:a}=e,u=this.getRepoApiUrl(n,o,i,r),l=q(this.config,r),[d,p]=await Promise.all([this.config.request({url:`${u}/pullRequests/${a}/reviewers?api-version=7.1`,headers:l}),this.config.request({url:`${u}/pullRequests/${a}/threads?api-version=7.1`,headers:l})]),c=(f,P)=>Mt(n,o,i,a,f,P),g=f=>Yr(n,o,i,a,f),m=new Map;for(let f of p.body.value){if(f.isDeleted)continue;let P=f.comments.filter(T=>!T.isDeleted&&T.commentType!=="system"),v=P.find(T=>T.parentCommentId===0)??P[0];if(!v)continue;let A=v.author?.id;if(!A)continue;let D=P.filter(T=>T.id!==v.id),w=f.threadContext,S=w?.rightFileStart?{side:"RIGHT",start:w.rightFileStart,end:w.rightFileEnd}:w?.leftFileStart?{side:"LEFT",start:w.leftFileStart,end:w.leftFileEnd}:null,pe=S?.end?.line??S?.start.line??null,fe=S?.start&&S.end&&S.start.line!==S.end.line?S.start.line:null,Re=w?.filePath??"",kt=Re.startsWith("/")?Re.slice(1):Re,de={id:c(f.id,v.id),author:v.author?he(v.author):null,body:v.content??"",createdAt:v.publishedDate?new Date(v.publishedDate):null,url:"",diffLines:[],filename:kt,replies:D.map(T=>({id:c(f.id,T.id),author:T.author?he(T.author):null,body:T.content??"",createdAt:T.publishedDate?new Date(T.publishedDate):null,url:""})),isOutdated:!1,isResolved:kn.has(_n(f.status)),line:pe,startLine:fe,side:S?.side??null,threadId:g(f.id)},Le=m.get(A);Le?Le.push(de):m.set(A,[de])}let h=[],y=new Set;for(let f of d.body.value){if(f.hasDeclined)continue;let P=f.vote??0,v=m.get(f.id);P===0&&!v?.length||(h.push({id:f.id,author:he(f),body:"",createdAt:null,url:"",reviewComments:v??[]}),y.add(f.id))}for(let[f,P]of m){if(y.has(f)||!P.length)continue;let v=P[0].author;v&&h.push({id:f,author:v,body:"",createdAt:null,url:"",reviewComments:P})}return{data:h}}};var G=(s,t={})=>R(t.token||s.token,t.isPAT||s.isPAT);var O="https://api.bitbucket.org/2.0",jn={OPEN:"OPEN",MERGED:"MERGED",DECLINED:"CLOSED",SUPERSEDED:"CLOSED"},Fn={OPEN:["OPEN"],MERGED:["MERGED"],CLOSED:["DECLINED","SUPERSEDED"]},We=50,rs=s=>{let t=!s||s.length===0?["OPEN"]:Array.from(new Set(s.flatMap(r=>Fn[r]))),e=t.map(r=>`state="${r}"`).join(" OR ");return t.length>1?`(${e})`:e},Qn=s=>s.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),ss=s=>{let t=s?.trim();if(!t)return null;let e=Qn(t);return`(title ~ "${e}" OR description ~ "${e}")`},ns=s=>{let t=!!s.next,e=typeof s.size=="number"?s.size:null,r=typeof s.pagelen=="number"&&s.pagelen>0?s.pagelen:null;return{hasNextPage:t,nextPage:t?s.page+1:null,currentPage:typeof s.page=="number"?s.page:null,totalCount:e,totalPages:e!==null&&r?Math.ceil(e/r):null}},He={owner:4,admin:3,contributor:2,member:1},Ve=s=>({id:s.uuid,name:s.display_name||s.nickname,username:s.nickname||s.display_name,email:null,avatarUrl:s.links.avatar.href,url:s.links.html.href}),os=s=>{let t=s.links.clone,e=t?.find(n=>n.name==="ssh"),r=t?.find(n=>n.name==="https");return e&&r?{cloneUrlHTTPS:r.href,cloneUrlSSH:e.href}:null},Ht=s=>({id:s.uuid,namespace:s.workspace.slug,name:s.slug,webUrl:s.links.html.href,httpsUrl:s.links.clone.find(t=>t.name==="https")?.href??null,sshUrl:s.links.clone.find(t=>t.name==="ssh")?.href??null,defaultBranch:{name:s.mainbranch.name},permissions:null}),Vt=s=>{let t=s.id,e=s.participants?.map(r=>{let n="REVIEW_REQUESTED";return r.approved?n="APPROVED":r.state==="changes_requested"?n="CHANGES_REQUESTED":r.participated_on!==null&&(n="COMMENTED"),{reviewer:Ve(r.user),state:n}})??[];return{id:t.toString(),title:s.title,description:s.description,number:t,state:jn[s.state],isDraft:!1,commentCount:s.comment_count,upvoteCount:null,author:Ve(s.author),createdDate:new Date(s.created_on),updatedDate:new Date(s.updated_on),closedDate:null,mergedDate:null,repository:{id:s.destination.repository.uuid,name:s.destination.repository.name,owner:{login:s.destination.repository.full_name.split("/")[0]},remoteInfo:os(s.destination.repository)},headCommit:{buildStatuses:null},baseRef:{name:s.destination.branch.name,oid:s.destination.commit.hash},headRef:{name:s.source.branch.name,oid:s.source.commit.hash},url:s.links.html.href,assignees:null,reviews:e,reviewDecision:J(e),additions:null,deletions:null,fileCount:null,commitCount:null,isCrossRepository:s.source.repository.uuid!==s.destination.repository.uuid,headRepository:{id:s.source.repository.uuid,name:s.source.repository.name,owner:{login:s.source.repository.full_name.split("/")[0]},remoteInfo:os(s.source.repository)},mergeableState:"MERGEABLE",permissions:null}},zn=s=>{switch(s){case"owner":case"admin":return{canCreateWebhook:!0,canPush:!0,isAdmin:!0};case"write":return{canCreateWebhook:!1,canPush:!0,isAdmin:!1};case"read":case"none":return{canCreateWebhook:!1,canPush:!1,isAdmin:!1}}},Mn=s=>{switch(s){case"owner":case"admin":return{canCreateWebhook:!0,canPush:!0,isAdmin:!0};case"contributor":return{canCreateWebhook:!1,canPush:!0,isAdmin:!1};default:return{canCreateWebhook:!1,canPush:!1,isAdmin:!1}}},we=class extends M{async refreshToken(t){return{data:(await this.config.request({url:"https://bitbucket.org/site/oauth2/access_token",method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Authorization:`Basic ${t.base64ClientIDColonClientSecret}`},body:`grant_type=refresh_token&refresh_token=${t.refreshToken}`})).body}}async getCurrentUser(t={},e={}){let r=await this.config.request({url:`${O}/user`,headers:G(this.config,e)});return{data:Ve(r.body)}}async getUserForCommit(t,e={}){let n=(await this.config.request({url:`${O}/repositories/${t.repo.namespace}/${t.repo.name}/commit/${t.oid}`,headers:G(this.config,e)})).body.author,o=n.raw.match(/([^<]+)<(.+)>/);return{data:{name:o?o[1].trim():null,email:o?o[2]:null,avatarUrl:n.user?.links.avatar.href||null}}}async getRepo(t,e={}){let r=await this.config.request({url:`${O}/repositories/${t.namespace}/${t.name}`,headers:G(this.config,e)});return{data:Ht(r.body)}}async getRepos(t,e={}){let r=[],n=[];return await Promise.all(t.map(async o=>{try{let i=await this.getRepo(o,e);r.push(i.data)}catch(i){n.push({input:o,error:i})}})),{data:r,errors:n}}async getReposForWorkspace(t,e={}){let r=new URL(`${O}/repositories/${encodeURIComponent(t.workspace)}`);r.searchParams.set("page",t.page?.toString()||"1"),r.searchParams.set("pagelen",$.toString()),t.minimumRole&&r.searchParams.set("role",t.minimumRole);let n=await this.config.request({url:r.toString(),headers:G(this.config,e)}),o=!!n.body.next;return{pageInfo:{hasNextPage:o,nextPage:o?n.body.page+1:null},data:n.body.values.map(Ht)}}async getAllReposForWorkspace(t,e={}){let r=[],n=1;for(;n!==null;){let o=await this.getReposForWorkspace({workspace:t.workspace,minimumRole:t.minimumRole,page:n},e);r.push(...o.data),n=o.pageInfo.hasNextPage?o.pageInfo.nextPage:null}return r}async getAllReposForWorkspaceWithPermissions(t,e={}){let r=new Map,n=[],o=He[t.minimumRole||"member"];o<=He.admin&&n.push("admin"),o<=He.contributor&&n.push("contributor"),o<=He.member&&n.push("member");let i=[];for(let a of n){i=await this.getAllReposForWorkspace({workspace:t.workspace,minimumRole:a},e);for(let u of i)r.has(u.id)||r.set(u.id,a)}return{data:i.map(a=>{let u=r.get(a.id)||"member";return{...a,permissions:Mn(u)}})}}async getReposForCurrentUser(t,e={}){let r=new URL(`${O}/repositories`);r.searchParams.set("role","member"),r.searchParams.set("pagelen",$.toString()),t.cursor&&r.searchParams.set("after",t.cursor);let n=await this.config.request({url:r.toString(),headers:G(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(Ht)}}async getBranches(t,e={}){let r=new URL(`${O}/repositories/${t.repo.namespace}/${t.repo.name}/refs/branches`);r.searchParams.set("page",t.page?.toString()||"1"),r.searchParams.set("pagelen",$.toString());let n=await this.config.request({url:r.toString(),headers:G(this.config,e)}),o=!!n.body.next;return{pageInfo:{hasNextPage:o,nextPage:o?n.body.page+1:null},data:n.body.values.map(i=>{let a=new Date(i.target.date);return{name:i.name,commit:{oid:i.target.hash,authoredDate:a,committedDate:a}}})}}async getTags(t,e={}){let r=new URL(`${O}/repositories/${t.repo.namespace}/${t.repo.name}/refs/tags`);r.searchParams.set("pagelen",$.toString()),t.cursor&&r.searchParams.set("page",t.cursor);let n=await this.config.request({url:r.toString(),headers:G(this.config,e)}),o=!!n.body.next,i=null;return n.body.next&&(i=new URL(n.body.next).searchParams.get("page")),{pageInfo:{hasNextPage:o,endCursor:i},data:n.body.values.map(a=>{let u=new Date(a.target.date);return{name:a.name,commit:{oid:a.target.hash,authoredDate:u,committedDate:u}}})}}async getWorkspacesForCurrentUser(t={},e={}){let r=new URL(`${O}/user/workspaces`);r.searchParams.set("page",t?.page?.toString()||"1"),r.searchParams.set("pagelen","50"),t?.administrator!==void 0&&r.searchParams.set("administrator",t.administrator.toString());let n=await this.config.request({url:r.toString(),headers:G(this.config,e)}),o=!!n.body.next;return{pageInfo:{hasNextPage:o,nextPage:o?n.body.page+1:null},data:n.body.values.map(i=>({id:i.workspace.uuid,slug:i.workspace.slug}))}}async getWorkspacesForUser(t,e={}){let r=new URL(`${O}/user/permissions/workspaces`);r.searchParams.set("page",t.page?.toString()||"1"),r.searchParams.set("pagelen","50");let n=await this.config.request({url:r.toString(),headers:G(this.config,e)}),o=!!n.body.next;return{pageInfo:{hasNextPage:o,nextPage:o?n.body.page+1:null},data:n.body.values.map(i=>({id:i.workspace.uuid,slug:i.workspace.slug,name:i.workspace.name}))}}async getPullRequestsForUserAndWorkspace(t,e={}){let r=new URL(`${O}/workspaces/${t.workspaceSlug}/pullrequests/${t.userId}`);r.searchParams.set("fields","+values.participants,+values.destination.repository.links.clone.*,+values.source.repository.links.clone.*"),r.searchParams.set("page",t.page?.toString()||"1"),r.searchParams.set("pagelen",L(t.pageSize,{fallback:We,max:We}).toString());let n=[rs(t.states)];t.repos&&t.repos.length>0&&n.push(`(${t.repos.map(a=>`source.repository.full_name = "${a.namespace}/${a.name}"`).join(" OR ")})`);let o=ss(t.query);o&&n.push(o),r.searchParams.set("q",n.join(" AND "));let i=await this.config.request({url:r.toString(),headers:G(this.config,e)});return{pageInfo:ns(i.body),data:i.body.values.map(Vt)}}async getPullRequestsForRepoBase(t,e={}){let r=new URL(`${O}/repositories/${encodeURI(t.repo.namespace)}/${encodeURI(t.repo.name)}/pullrequests`),n=[];t.reviewerId&&n.push(`reviewers.uuid="${t.reviewerId}"`),t.authorLogin&&n.push(`author.uuid="${t.authorLogin}"`);let o=rs(t.states);n.length&&(o+=` AND (${n.join(t.useOrFilter?" OR ":" AND ")})`);let i=ss(t.query);return i&&(o+=` AND ${i}`),r.searchParams.set("fields","+values.participants,+values.destination.repository.links.clone.*,+values.source.repository.links.clone.*"),r.searchParams.set("page",t.page?.toString()||"1"),r.searchParams.set("pagelen",L(t.pageSize,{fallback:We,max:We}).toString()),r.searchParams.set("q",o),await this.config.request({url:r.toString(),headers:G(this.config,e)})}async getPullRequestsForRepo(t,e={}){let r=[],n=await this.getPullRequestsForRepoBase(t,e);return n.body.values.forEach(o=>{r.push(Vt(o))}),{pageInfo:ns(n.body),data:r}}async getPullRequestsForRepos(t,e={}){let{successes:r,metadata:n}=await te(t.repos,{run:i=>this.getPullRequestsForRepoBase({repo:i,authorLogin:t.authorLogin,reviewerId:t.reviewerId,useOrFilter:t.useOrFilter,states:t.states,query:t.query,pageSize:t.pageSize},e),failureScope:i=>({providerId:"bitbucket",repositoryId:me(i)}),completeness:i=>i.body.next?"partial":"complete"}),o=[];return r.forEach(({result:i})=>{i.body.values.forEach(a=>{o.push(Vt(a))})}),{data:o,metadata:n}}async getAccountsForWorkspace(t,e={}){let r=new URL(`${O}/workspaces/${encodeURI(t.workspace)}/members`);r.searchParams.set("page",t.page?.toString()||"1"),r.searchParams.set("pagelen","100");let n=await this.config.request({url:r.toString(),headers:G(this.config,e)}),o=!!n.body.next;return{pageInfo:{hasNextPage:o,nextPage:o?n.body.page+1:null},data:n.body.values.map(i=>Ve(i.user))}}async getReposPermissionsForCurrentUser(t,e={}){let r=new URL(`${O}/user/permissions/repositories`);r.searchParams.set("page",t.page?.toString()||"1"),r.searchParams.set("pagelen","100");let n=await this.config.request({url:r.toString(),headers:G(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]:zn(a.permission)}),{})}}async decorateReposWithPermissions(t,e={}){let r={},n=1;do{let o=await this.getReposPermissionsForCurrentUser({page:n},e);r={...o.data,...r},n=o.pageInfo.hasNextPage?o.pageInfo.nextPage:null}while(n!==null);return{data:t.repos.map(o=>({...o,permissions:r[o.id]??{canCreateWebhook:!1,canPush:!1,isAdmin:!1}}))}}async closePullRequest(t,e={}){let{pullRequest:r}=t;if(!(await this.config.request({method:"POST",url:`${O}/repositories/${r.repository.owner.login}/${r.repository.name}/pullrequests/${r.id}/decline`,headers:G(this.config,e)})).body.title)throw new Error("Could not close pull request")}async mergePullRequest(t,e={}){let{pullRequest:r,mergeStrategy:n}=t,o;switch(n){case"MERGE_COMMIT":{o="merge_commit";break}case"FAST_FORWARD":{o="fast_forward";break}case"SQUASH":{o="squash";break}}let i={merge_strategy:o,type:"pullrequest"};if(!(await this.config.request({method:"POST",url:`${O}/repositories/${r.repository.owner.login}/${r.repository.name}/pullrequests/${r.id}/merge`,body:JSON.stringify(i),headers:{...G(this.config,e),"Content-Type":"application/json"}})).body.title)throw new Error("Could not merge pull request")}async setPullRequestReviewers(t,e={}){let{pullRequest:r,reviewers:n}=t,o={reviewers:n.map(a=>{if(a.username)throw new Error('Bitbucket reviewer requires "username" for this function.');return{username:a.username}})};if(!(await this.config.request({method:"PUT",url:`${O}/repositories/${r.repository.owner.login}/${r.repository.name}/pullrequests/${r.id}`,body:JSON.stringify(o),headers:{...G(this.config,e),"Content-Type":"application/json"}})).body.title)throw new Error("Could not set pull request reviewers")}};var Je={};H(Je,{normalizePermissions:()=>Jt,restApiPullRequestToCommonPullRequest:()=>Wn});var Wn=s=>Te(s),Jt=s=>s?s.find(t=>t.permission==="USER_ADMIN"||t.permission==="PROJECT_ADMIN"||t.permission==="ADMIN"||t.permission==="SYS_ADMIN"||t.permission==="REPO_ADMIN")?{canCreateWebhook:!0,canPush:!0,isAdmin:!0}:s.find(t=>t.permission==="REPO_WRITE"||t.permission==="REPO_CREATE"||t.permission==="PROJECT_CREATE"||t.permission==="PROJECT_WRITE")?{canCreateWebhook:!1,canPush:!0,isAdmin:!1}:{canCreateWebhook:!1,canPush:!1,isAdmin:!1}:{canCreateWebhook:!1,canPush:!1,isAdmin:!1};var Oe=s=>{let t=s.links.self[0].href;return{name:s.displayName,email:s.emailAddress,avatarUrl:s.avatarUrl??(t&&`${t}/avatar.png`),id:s.id.toString(),username:s.name,url:t}},Te=s=>{let t={OPEN:"OPEN",MERGED:"MERGED",DECLINED:"CLOSED"},e={UNAPPROVED:"REVIEW_REQUESTED",NEEDS_WORK:"CHANGES_REQUESTED",APPROVED:"APPROVED"},r=s.reviewers.map(u=>({reviewer:Oe(u.user),state:e[u.status]})),n=s.toRef.repository.links.clone.find(u=>u.name==="ssh")?.href??null,o=s.toRef.repository.links.clone.find(u=>u.name==="https")?.href??null;o||(o=s.toRef.repository.links.clone.find(u=>u.name==="http")?.href??null);let i=s.fromRef.repository.links.clone.find(u=>u.name==="ssh")?.href??null,a=s.fromRef.repository.links.clone.find(u=>u.name==="https")?.href??null;return a||(a=s.fromRef.repository.links.clone.find(u=>u.name==="http")?.href??null),{id:s.id.toString(),number:s.id,title:s.title,description:s.description,url:s.links.self[0].href,state:t[s.state],isDraft:!1,createdDate:new Date(s.createdDate),updatedDate:new Date(s.updatedDate),closedDate:s.closedDate?new Date(s.closedDate):null,mergedDate:s.state=="MERGED"&&s.closedDate?new Date(s.closedDate):null,baseRef:{name:s.toRef.displayId,oid:s.toRef.latestCommit},headRef:{name:s.fromRef.displayId,oid:s.fromRef.latestCommit},commentCount:s.properties.commentCount,upvoteCount:null,commitCount:null,fileCount:null,additions:null,deletions:null,author:Oe(s.author.user),assignees:null,reviews:r,reviewDecision:J(r),isCrossRepository:s.fromRef.repository.id!==s.toRef.repository.id,repository:{id:s.toRef.repository.id.toString(),name:s.toRef.repository.name,owner:{login:s.toRef.repository.project.key},remoteInfo:o&&n?{cloneUrlHTTPS:o,cloneUrlSSH:n}:null},headRepository:{id:s.fromRef.repository.id.toString(),name:s.fromRef.repository.name,owner:{login:s.fromRef.repository.project.key},remoteInfo:a&&i?{cloneUrlHTTPS:a,cloneUrlSSH:i}:null},headCommit:null,mergeableState:"MERGEABLE",permissions:null,version:s.version}},is=s=>({id:s.id.toString(),namespace:s.project.key,name:s.slug,webUrl:s.links.self[0]?.href??null,httpsUrl:s.links.clone.find(t=>t.name==="https"||t.name==="http")?.href??null,sshUrl:s.links.clone.find(t=>t.name==="ssh")?.href??null,defaultBranch:null,permissions:null}),as=50,Hn={OPEN:"OPEN",MERGED:"MERGED",CLOSED:"DECLINED"},us=s=>{if(!s||s.length===0)return"OPEN";let t=Array.from(new Set(s.map(e=>Hn[e])));return t.length===1?t[0]:"ALL"},ls=(s,t)=>typeof s!="number"||t<=0?null:Math.floor(s/t)+1,qe=class extends F{getBaseUrl(t){let e=t.baseUrl||this.config.baseUrl;if(!e)throw new Error('Bitbucket Server requires "baseUrl"');return e}getRequestHeaders(t){return R(t.token||this.config.token)}async getCurrentUser(t={},e={}){let r=await this.config.request({url:`${this.getBaseUrl(e)}/users?limit=2`,headers:this.getRequestHeaders(e)}),{headers:{"x-auserid":n,"x-ausername":o}}=r,i=n?parseInt(n,10):null,a=decodeURIComponent(o),l=(await this.config.request({url:`${this.getBaseUrl(e)}/users?filter=${o}&avatarSize=64`,headers:this.getRequestHeaders(e)})).body.values.find(({emailAddress:d,id:p,name:c,slug:g})=>i?i===p:a===c||a===d||a===g);if(!l)throw new Error("Could not find current Bitbucket Server user");return{data:Oe(l)}}async getUserForCommit(t,e){let{repo:r,oid:n}=t,o=await this.config.request({url:`${this.getBaseUrl(e)}/projects/${r.namespace}/repos/${r.name}/commits/${n}`,headers:this.getRequestHeaders(e)});if(!o.body.author)throw new Error("Could not find user for commit");return{data:Oe(o.body.author)}}async getRepo(t,e={}){let r=await this.config.request({url:`${this.getBaseUrl(e)}/projects/${t.namespace}/repos/${t.name}`,headers:this.getRequestHeaders(e)});return{data:is(r.body)}}async getRepos(t,e={}){let r=[],n=[];return await Promise.all(t.map(async o=>{try{let i=await this.getRepo(o,e);r.push(i.data)}catch(i){n.push({input:o,error:i})}})),{data:r,errors:n}}async getReposForCurrentUser(t,e={}){let r=t.page??0,n=await this.config.request({url:`${this.getBaseUrl(e)}/repos?start=${r}`,headers:this.getRequestHeaders(e)});return{pageInfo:{hasNextPage:!n.body.isLastPage,nextPage:n.body.nextPageStart},data:n.body.values.map(is)}}async getRepoPermissionsForUsername(t,e={}){let r=new URL(`${this.getBaseUrl(e)}/projects/${t.repo.namespace}/repos/${t.repo.name}/permissions/search?filterText=${t.username}`);try{let n=await this.config.request({url:r.toString(),headers:this.getRequestHeaders(e)});return{data:Jt(n.body.values)}}catch(n){if(n.response?.status===401)return{data:{canCreateWebhook:!1,canPush:!1,isAdmin:!1}};throw n}}async decorateReposWithPermissions(t,e={}){return await Promise.all(t.repos.map(async n=>{let o=await this.getRepoPermissionsForUsername({repo:n,username:t.username},e);return{...n,permissions:o.data}}))}async getPullRequestsForRepoBase(t,e={}){let r=new URL(`${this.getBaseUrl(e)}/projects/${encodeURI(t.repo.namespace)}/repos/${encodeURI(t.repo.name)}/pull-requests`);return r.searchParams.set("state",us(t.states)),r.searchParams.set("start",t.page?.toString()||"0"),r.searchParams.set("limit",L(t.pageSize,{fallback:as}).toString()),t.reviewerLogin&&(r.searchParams.set("role.1","REVIEWER"),r.searchParams.set("username.1",t.reviewerLogin)),await this.config.request({url:r.toString(),headers:this.getRequestHeaders(e)})}async getPullRequestsForRepo(t,e={}){let r=[],n=await this.getPullRequestsForRepoBase(t,e);n.body.values.forEach(i=>{if(t.authorLogin&&i.author.user.name!==t.authorLogin)return null;r.push(Te(i))});let o=!n.body.isLastPage;return{pageInfo:{hasNextPage:o,nextPage:o?n.body.nextPageStart:null,currentPage:ls(n.body.start,n.body.limit)},data:x(r,t.states)}}async getPullRequestsForRepos(t,e={}){let{successes:r,metadata:n}=await te(t.repos,{run:i=>this.getPullRequestsForRepoBase({repo:i,reviewerLogin:t.reviewerLogin,states:t.states,pageSize:t.pageSize},e),failureScope:i=>({providerId:"bitbucketServer",repositoryId:me(i)}),completeness:i=>i.body.isLastPage?"complete":"partial"}),o=[];return r.forEach(({result:i})=>{i.body.values.forEach(a=>{t.authorLogin&&a.author.user.name!==t.authorLogin||o.push(Te(a))})}),{data:x(o,t.states),metadata:n}}async getPullRequestsForCurrentUser(t,e={}){let r=new URL(`${this.getBaseUrl(e)}/dashboard/pull-requests`);r.searchParams.set("state",us(t.states)),r.searchParams.set("start",t.page?.toString()||"0");let n=L(t.pageSize,{fallback:as});r.searchParams.set("limit",n.toString()),t.reviewerLogin&&(r.searchParams.set("role.1","REVIEWER"),r.searchParams.set("username.1",t.reviewerLogin));let o=await this.config.request({url:r.toString(),headers:this.getRequestHeaders(e)}),i=!o.body.isLastPage;return{pageInfo:{hasNextPage:i,nextPage:i?o.body.nextPageStart:null,currentPage:ls(o.body.start,o.body.limit)},data:x(o.body.values.map(Te),t.states)}}async closePullRequest(t,e={}){let{pullRequest:r}=t;if(r.version===void 0)throw new Error('Bitbucket Server requires "version" for this function.');if(!(await this.config.request({method:"POST",url:`${this.getBaseUrl(e)}/projects/${r.repository.owner.login}/repos/${r.repository.name}/pull-requests/${r.id}/decline`,body:JSON.stringify({version:r.version}),headers:{...this.getRequestHeaders(e),"Content-Type":"application/json"}})).body.title)throw new Error("Could not close pull request")}async mergePullRequest(t,e={}){let{pullRequest:r,mergeStrategyId:n}=t;if(t.mergeStrategy)throw new Error('Bitbucket Server uses "mergeStrategyId" instead of "mergeStrategy".');if(r.version===void 0)throw new Error('Bitbucket Server requires "version" for this function.');if(!(await this.config.request({method:"POST",url:`${this.getBaseUrl(e)}/projects/${r.repository.owner.login}/repos/${r.repository.name}/pull-requests/${r.id}/merge`,body:JSON.stringify({strategyId:n,version:r.version}),headers:{...this.getRequestHeaders(e),"Content-Type":"application/json"}})).body.title)throw new Error("Could not merge pull request")}async getMergeStrategies(t={}){let e=await this.config.request({url:`${this.getBaseUrl(t)}/admin/pull-requests/git`,headers:{...this.getRequestHeaders(t),"Content-Type":"application/json"}});return{data:{defaultStrategy:e.body.mergeConfig.defaultStrategy,strategies:e.body.mergeConfig.strategies}}}async setPullRequestReviewers(t,e={}){let{pullRequest:r,reviewers:n}=t;if(r.version===void 0)throw new Error('Bitbucket Server requires "version" for this function.');let o={reviewers:n.map(a=>{if(a.username)throw new Error('Bitbucket Server reviewer requires "username" for this function.');return{user:{name:a.username}}}),version:r.version};if(!(await this.config.request({method:"PUT",url:`${this.getBaseUrl(e)}/projects/${r.repository.owner.login}/repos/${r.repository.name}/pull-requests/${r.id}`,body:JSON.stringify(o),headers:{...this.getRequestHeaders(e),"Content-Type":"application/json"}})).body.title)throw new Error("Could not set pull request reviewers")}async getAccountsForProject(t,e={}){let r=new URL(`${this.getBaseUrl(e)}/projects/${encodeURI(t.project)}/permissions/users`);r.searchParams.set("start",t.page?.toString()||"0"),r.searchParams.set("limit","50");let n=await this.config.request({url:r.toString(),headers:this.getRequestHeaders(e)}),o=n.body.values.length!==0;return{pageInfo:{hasNextPage:o,nextPage:o?n.body.start+n.body.values.length:null},data:n.body.values.map(i=>Oe(i.user))}}};var Ss=require("js-base64");var I=class extends Error{constructor(e,r){let n=r?.map(i=>`'${i.message}'`).join(", "),o=n?`${e}: ${n}`:e;super(o);this.graphQLErrors=r??[]}};var Vn={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]},ps=15,ds=100,_e={__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"},k=s=>!!s,K=(s,t)=>{let e=Vn[t];for(let r=0;r<3;r++){if(s[r]>e[r])return!0;if(s[r]<e[r])return!1}return!0},Xe="https://api.github.com",Jn=`${Xe}/graphql`,Ze=`
|
|
3
3
|
description
|
|
4
4
|
dueOn
|
|
5
5
|
id
|
|
@@ -7,7 +7,7 @@ number
|
|
|
7
7
|
state
|
|
8
8
|
title
|
|
9
9
|
url
|
|
10
|
-
`,
|
|
10
|
+
`,Kn=`
|
|
11
11
|
... on CheckRun {
|
|
12
12
|
completedAt
|
|
13
13
|
conclusion
|
|
@@ -16,48 +16,48 @@ url
|
|
|
16
16
|
permalink
|
|
17
17
|
startedAt
|
|
18
18
|
}
|
|
19
|
-
`,
|
|
19
|
+
`,Ke=/\/api\/v\d+$/,Ye=`
|
|
20
20
|
color
|
|
21
21
|
description
|
|
22
22
|
id
|
|
23
23
|
name
|
|
24
|
-
`,
|
|
24
|
+
`,cs=s=>{if(s.endsWith("/api/graphql"))throw new Error("The graphql endpoint is being used as the baseUrl. This package uses both GraphQL and REST APIs, and the REST version cannot be assumed. Use the REST endpoint as the baseUrl instead.")},Xn=(s,t)=>{let e=t.baseUrl||s.baseUrl;return e?(e=e.replace(/\/$/,""),cs(e),Ke.test(e)&&(e=e.replace(Ke,"")),`${e}/api/graphql`):Jn},X=(s,t)=>{let e=t.baseUrl||s.baseUrl;return e?(e=e.replace(/\/$/,""),cs(e),Ke.test(e)&&(e=e.replace(Ke,"")),`${e}/api/v3`):Xe},b=(s,t,e)=>{let r=R(e.token||s.token);return r["X-Github-Next-Global-ID"]="1",r["Content-Type"]="application/json",r.Accept="application/vnd.github.merge-info-preview+json",s.request({url:Xn(s,e),method:"POST",headers:r,body:JSON.stringify(t)})},Zn={user:!0,"user:email":!0,"read:user":!0},re=s=>s.some(t=>Zn[t]),Q=(s=!1,t=!1,e)=>`
|
|
25
25
|
__typename
|
|
26
|
-
${
|
|
27
|
-
${
|
|
28
|
-
${
|
|
29
|
-
${
|
|
30
|
-
${t?
|
|
31
|
-
${
|
|
32
|
-
${
|
|
33
|
-
`,
|
|
26
|
+
${ae(e,["graphQLId"],"id")}
|
|
27
|
+
${ae(e,["id"],"databaseId")}
|
|
28
|
+
${ae(e,["name"],"name")}
|
|
29
|
+
${ae(e,["name","username"],"login")}
|
|
30
|
+
${t?ae(e,["email"],"email"):""}
|
|
31
|
+
${ae(e,["avatarUrl"],`avatarUrl${s?"(size: $avatarSize)":""}`)}
|
|
32
|
+
${ae(e,["url"],"url")}
|
|
33
|
+
`,Yn=(s=!1)=>`
|
|
34
34
|
latestReviews(first: 100) {
|
|
35
35
|
nodes {
|
|
36
36
|
author {
|
|
37
37
|
... on User {
|
|
38
|
-
${
|
|
38
|
+
${Q(!1,s)}
|
|
39
39
|
}
|
|
40
40
|
... on EnterpriseUserAccount {
|
|
41
|
-
${
|
|
41
|
+
${Kt(!1)}
|
|
42
42
|
}
|
|
43
43
|
}
|
|
44
44
|
state
|
|
45
45
|
}
|
|
46
46
|
}
|
|
47
|
-
`,
|
|
47
|
+
`,ms=(s=!1)=>`
|
|
48
48
|
__typename
|
|
49
49
|
id
|
|
50
50
|
databaseId
|
|
51
51
|
login
|
|
52
52
|
avatarUrl${s?"(size: $avatarSize)":""}
|
|
53
53
|
url
|
|
54
|
-
`,
|
|
54
|
+
`,Kt=(s=!1)=>`
|
|
55
55
|
__typename
|
|
56
56
|
id
|
|
57
57
|
login
|
|
58
58
|
avatarUrl${s?"(size: $avatarSize)":""}
|
|
59
59
|
url
|
|
60
|
-
`,
|
|
60
|
+
`,et=(s,t=!1,e)=>`
|
|
61
61
|
id
|
|
62
62
|
${!e||K(e,"PR_FULL_DATABASE_ID")?"fullDatabaseId":"databaseId"}
|
|
63
63
|
number
|
|
@@ -66,13 +66,13 @@ body
|
|
|
66
66
|
state
|
|
67
67
|
author {
|
|
68
68
|
... on User {
|
|
69
|
-
${
|
|
69
|
+
${Q(!1,t)}
|
|
70
70
|
}
|
|
71
71
|
... on Bot {
|
|
72
|
-
${
|
|
72
|
+
${ms(!1)}
|
|
73
73
|
}
|
|
74
74
|
... on EnterpriseUserAccount {
|
|
75
|
-
${
|
|
75
|
+
${Kt(!1)}
|
|
76
76
|
}
|
|
77
77
|
}
|
|
78
78
|
commits(last: 1) {
|
|
@@ -85,7 +85,7 @@ commits(last: 1) {
|
|
|
85
85
|
contexts(first: 100) {
|
|
86
86
|
totalCount
|
|
87
87
|
nodes {
|
|
88
|
-
${!e||K(e,"CHECK_RUN")?
|
|
88
|
+
${!e||K(e,"CHECK_RUN")?Kn:""}
|
|
89
89
|
... on StatusContext {
|
|
90
90
|
context
|
|
91
91
|
createdAt
|
|
@@ -148,7 +148,7 @@ closedAt
|
|
|
148
148
|
mergedAt
|
|
149
149
|
assignees(first: 100) {
|
|
150
150
|
nodes {
|
|
151
|
-
${
|
|
151
|
+
${Q(!1,t)}
|
|
152
152
|
}
|
|
153
153
|
}
|
|
154
154
|
reviewRequests(first: 100) {
|
|
@@ -156,39 +156,39 @@ reviewRequests(first: 100) {
|
|
|
156
156
|
${!e||K(e,"AS_CODE_OWNER")?"asCodeOwner":""}
|
|
157
157
|
requestedReviewer {
|
|
158
158
|
... on User {
|
|
159
|
-
${
|
|
159
|
+
${Q(!1,t)}
|
|
160
160
|
}
|
|
161
161
|
}
|
|
162
162
|
}
|
|
163
163
|
}
|
|
164
|
-
${!e||K(e,"LATEST_REVIEWS")?
|
|
164
|
+
${!e||K(e,"LATEST_REVIEWS")?Yn(t):""}
|
|
165
165
|
additions
|
|
166
166
|
deletions
|
|
167
167
|
changedFiles
|
|
168
168
|
mergeable
|
|
169
169
|
mergeStateStatus
|
|
170
170
|
milestone {
|
|
171
|
-
${
|
|
171
|
+
${Ze}
|
|
172
172
|
}
|
|
173
173
|
labels(first: 100) {
|
|
174
174
|
nodes {
|
|
175
|
-
${
|
|
175
|
+
${Ye}
|
|
176
176
|
}
|
|
177
177
|
}
|
|
178
178
|
${!e||K(e,"VIEWER_CAN_MERGE_AS_ADMIN")?"viewerCanMergeAsAdmin":""}
|
|
179
|
-
`,
|
|
179
|
+
`,eo=(s=!1,t)=>`
|
|
180
180
|
id
|
|
181
181
|
${!t||K(t,"ISSUE_FULL_DATABASE_ID")?"fullDatabaseId":"databaseId"}
|
|
182
182
|
title
|
|
183
183
|
author {
|
|
184
184
|
... on User {
|
|
185
|
-
${
|
|
185
|
+
${Q(!1,s)}
|
|
186
186
|
}
|
|
187
187
|
... on Bot {
|
|
188
|
-
${
|
|
188
|
+
${ms(!1)}
|
|
189
189
|
}
|
|
190
190
|
... on EnterpriseUserAccount {
|
|
191
|
-
${
|
|
191
|
+
${Kt(!1)}
|
|
192
192
|
}
|
|
193
193
|
}
|
|
194
194
|
closedAt
|
|
@@ -212,19 +212,19 @@ comments {
|
|
|
212
212
|
}
|
|
213
213
|
assignees(first: 100) {
|
|
214
214
|
nodes {
|
|
215
|
-
${
|
|
215
|
+
${Q(!1,s)}
|
|
216
216
|
}
|
|
217
217
|
}
|
|
218
218
|
state
|
|
219
219
|
milestone {
|
|
220
|
-
${
|
|
220
|
+
${Ze}
|
|
221
221
|
}
|
|
222
222
|
labels(first: 100) {
|
|
223
223
|
nodes {
|
|
224
|
-
${
|
|
224
|
+
${Ye}
|
|
225
225
|
}
|
|
226
226
|
}
|
|
227
|
-
`,
|
|
227
|
+
`,to={"-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"},ro=new RegExp('(([^\\s]+:)?\\"(?:[^\\"\\\\]|\\\\.)*\\"?)|([^\\"\\s]+)',"g"),Xt=s=>{let t=[];return(s.match(ro)??[]).forEach(r=>{if(r.includes(":")&&r!="is:closed"){let n=r.split(":")[0];to[n]&&t.push(r)}}),t},Zt="is:open",gs=s=>{if(!s||s.length===0)return Zt;let t=new Set(s),e=t.has("OPEN"),r=t.has("CLOSED"),n=t.has("MERGED");return e&&(r||n)?"":e?"is:open":r&&n?"is:closed":n?"is:merged":"is:closed is:unmerged"},hs=s=>{if(!s||s.length===0)return Zt;let t=new Set(s),e=t.has("OPEN"),r=t.has("CLOSED");return e&&r?"":r?"is:closed":"is:open"},Yt=(s,t,e,r)=>{let n=s==="issue",o=r.stateQualifier??Zt;return{query:`
|
|
228
228
|
query SearchIssuesOrPullRequests($query: String! $after: String) {
|
|
229
229
|
search(type:ISSUE query:$query first: ${r.maxPageSize} after:$after) {
|
|
230
230
|
pageInfo {
|
|
@@ -233,18 +233,18 @@ query SearchIssuesOrPullRequests($query: String! $after: String) {
|
|
|
233
233
|
}
|
|
234
234
|
nodes {
|
|
235
235
|
... on ${n?"Issue":"PullRequest"} {
|
|
236
|
-
${n?
|
|
236
|
+
${n?eo(r.supportsEmail,r.enterpriseVersion??null):et(r.supportsDrafts??!1,r.supportsEmail,r.enterpriseVersion??null)}
|
|
237
237
|
}
|
|
238
238
|
}
|
|
239
239
|
}
|
|
240
|
-
}`,variables:{query:`is:${s} ${o} ${r.includeFromArchivedRepos?"":"archived:false"} ${t}`,after:e}}},
|
|
240
|
+
}`,variables:{query:`is:${s} ${o} ${r.includeFromArchivedRepos?"":"archived:false"} ${t}`,after:e}}},so="Field 'isDraft' doesn't exist on type 'PullRequest'",tt=(s=[])=>s.some(t=>t?.message===so),no=/@@ -(\d+)(?:,\d+ | )\+(\d+)(?:,\d+ | )@@(?:\\n)?/,oo=`
|
|
241
241
|
\
|
|
242
|
-
+`,
|
|
242
|
+
+`,fs=(s,t,e,r)=>{let n=no.exec(s);if(!n||!n[0]||!n[1])return[];let o=parseInt(n[1],10),i=parseInt(n[2],10),a=s.replace(oo,`
|
|
243
243
|
+`).split(`
|
|
244
|
-
`).slice(1),u=o-1,l=i-1,
|
|
244
|
+
`).slice(1),u=o-1,l=i-1,d=a.map(g=>{let m,h;switch(g[0]){case"-":{m="DELETED",u+=1,h=`${g.slice(1)}
|
|
245
245
|
`;break}case"+":{m="ADDED",l+=1,h=`${g.slice(1)}
|
|
246
246
|
`;break}default:m="UNMODIFIED",l+=1,u+=1,h=`${g}
|
|
247
|
-
`}return{line:h,oldLineNumber:m!=="ADDED"?u:null,newLineNumber:m!=="DELETED"?l:null,type:m}}),
|
|
247
|
+
`}return{line:h,oldLineNumber:m!=="ADDED"?u:null,newLineNumber:m!=="DELETED"?l:null,type:m}}),p=e,c=t;if(p!==null&&c!==null&&r!==null&&p<c){let g=0,m=d.length,h=r==="LEFT"?"oldLineNumber":"newLineNumber";for(let y=0;y<d.length;y++){let P=d[y][h];P===p?g=y:P===c&&(m=y)}d=d.slice(g,m+1)}return d},Rs=s=>{let t=s.author;return t||(t=_e),{author:{id:"databaseId"in t?t.databaseId.toString():t.id,graphQLId:t.id,name:("name"in t?t.name:t.login)??t.login,username:t.login,email:("email"in t?t.email:null)??null,avatarUrl:t.avatarUrl,url:t.url},body:s.body,createdAt:s.publishedAt?new Date(s.publishedAt):null,graphQLId:s.id,id:s.fullDatabaseId??s.databaseId?.toString()??s.id,url:s.url}};var Is=`mutation DeleteIssueComment(
|
|
248
248
|
$issueCommentId: ID!
|
|
249
249
|
) {
|
|
250
250
|
deleteIssueComment(input: {
|
|
@@ -252,7 +252,7 @@ query SearchIssuesOrPullRequests($query: String! $after: String) {
|
|
|
252
252
|
}) {
|
|
253
253
|
clientMutationId
|
|
254
254
|
}
|
|
255
|
-
}`,
|
|
255
|
+
}`,bs=`mutation DeletePullRequestReviewComment(
|
|
256
256
|
$pullRequestReviewCommentId: ID!
|
|
257
257
|
) {
|
|
258
258
|
deletePullRequestReviewComment(input: {
|
|
@@ -262,7 +262,7 @@ query SearchIssuesOrPullRequests($query: String! $after: String) {
|
|
|
262
262
|
id
|
|
263
263
|
}
|
|
264
264
|
}
|
|
265
|
-
}`,
|
|
265
|
+
}`,ys=`mutation UpdateIssueComment(
|
|
266
266
|
$issueCommentId: ID!,
|
|
267
267
|
$body: String!
|
|
268
268
|
) {
|
|
@@ -275,7 +275,7 @@ query SearchIssuesOrPullRequests($query: String! $after: String) {
|
|
|
275
275
|
body
|
|
276
276
|
}
|
|
277
277
|
}
|
|
278
|
-
}`,
|
|
278
|
+
}`,Ps=`mutation ResolveReviewThread(
|
|
279
279
|
$pullRequestReviewThreadId: ID!
|
|
280
280
|
) {
|
|
281
281
|
resolveReviewThread(input: {
|
|
@@ -286,7 +286,7 @@ query SearchIssuesOrPullRequests($query: String! $after: String) {
|
|
|
286
286
|
isResolved
|
|
287
287
|
}
|
|
288
288
|
}
|
|
289
|
-
}`,
|
|
289
|
+
}`,ws=`mutation UnresolveReviewThread(
|
|
290
290
|
$pullRequestReviewThreadId: ID!
|
|
291
291
|
) {
|
|
292
292
|
unresolveReviewThread(input: {
|
|
@@ -297,7 +297,7 @@ query SearchIssuesOrPullRequests($query: String! $after: String) {
|
|
|
297
297
|
isResolved
|
|
298
298
|
}
|
|
299
299
|
}
|
|
300
|
-
}`,
|
|
300
|
+
}`,qs=`mutation UpdatePullRequestReviewComment(
|
|
301
301
|
$pullRequestReviewCommentId: ID!,
|
|
302
302
|
$body: String!
|
|
303
303
|
) {
|
|
@@ -310,7 +310,7 @@ query SearchIssuesOrPullRequests($query: String! $after: String) {
|
|
|
310
310
|
body
|
|
311
311
|
}
|
|
312
312
|
}
|
|
313
|
-
}`;var
|
|
313
|
+
}`;var vs=s=>`
|
|
314
314
|
query GetPullRequestComments(
|
|
315
315
|
$namespace: String!
|
|
316
316
|
$name: String!
|
|
@@ -356,7 +356,7 @@ query GetPullRequestComments(
|
|
|
356
356
|
}
|
|
357
357
|
}
|
|
358
358
|
}
|
|
359
|
-
`;var
|
|
359
|
+
`;var er=`
|
|
360
360
|
id
|
|
361
361
|
databaseId
|
|
362
362
|
owner {
|
|
@@ -369,10 +369,10 @@ defaultBranchRef {
|
|
|
369
369
|
name
|
|
370
370
|
}
|
|
371
371
|
viewerPermission
|
|
372
|
-
`,
|
|
372
|
+
`,io={APPROVED:"APPROVED",CHANGES_REQUESTED:"CHANGES_REQUESTED",COMMENTED:"COMMENTED",REVIEW_REQUESTED:"REVIEW_REQUESTED"},ao={MERGEABLE:"MERGEABLE",CONFLICTING:"CONFLICTS",UNKNOWN:"UNKNOWN"},uo={BEHIND:"BEHIND",BLOCKED:"BLOCKED",UNKNOWN:"UNKNOWN_AND_BLOCKED",UNSTABLE:"UNSTABLE",CLEAN:null,DIRTY:null,DRAFT:null,HAS_HOOKS:null},lo={OPEN:"OPEN",CLOSED:"CLOSED"},po=["ADMIN","MAINTAIN","TRIAGE","WRITE"],sr=s=>({color:`#${s.color}`,description:s.description,graphQLId:s.id,id:null,name:s.name}),co=s=>({canCreateWebhook:s==="ADMIN",canPush:s==="ADMIN"||s==="MAINTAIN"||s==="WRITE",isAdmin:s==="ADMIN"}),tr=s=>({id:s.databaseId.toString(),graphQLId:s.id,namespace:s.owner.login,name:s.name,webUrl:s.url,httpsUrl:s.url.endsWith(".git")?s.url:`${s.url}.git`,sshUrl:s.sshUrl,defaultBranch:s.defaultBranchRef,permissions:co(s.viewerPermission)}),mo=s=>({canCreateWebhook:s.admin,canPush:s.admin||s.maintain||s.push,isAdmin:s.admin}),Es=s=>({id:s.id.toString(),graphQLId:s.node_id,namespace:s.owner.login,name:s.name,webUrl:s.html_url,httpsUrl:s.clone_url,sshUrl:s.ssh_url,defaultBranch:{name:s.default_branch},permissions:mo(s.permissions)}),go=s=>({path:s.path,isDirectory:s.type==="tree"}),ho={OPEN:"OPEN",CLOSED:"CLOSED",MERGED:"MERGED"},fo={id:!0,graphQLId:!0,name:!0,username:!0,email:!0,avatarUrl:!0,url:!0},W=(s,t=fo)=>{let e={};return t.id&&(e.id="databaseId"in s?s.databaseId.toString():s.id),t.graphQLId&&(e.graphQLId=s.id),t.name&&(e.name=s.name??s.login),t.username&&(e.username=s.login),t.email&&(e.email=s.email??null),t.avatarUrl&&(e.avatarUrl=s.avatarUrl),t.url&&(e.url=s.url),e},Ro=(s,t)=>{let e={IN_PROGRESS:"RUNNING",PENDING:"PENDING",QUEUED:"PENDING",REQUESTED:"PENDING",WAITING:"PENDING"};return s!=="COMPLETED"?e[s]:{ACTION_REQUIRED:"ACTION_REQUIRED",CANCELLED:"CANCELLED",FAILURE:"FAILED",NEUTRAL:null,SKIPPED:"SKIPPED",STALE:"FAILED",STARTUP_FAILURE:"FAILED",SUCCESS:"SUCCESS",TIMED_OUT:"ERROR"}[t]},Io=s=>({ERROR:"ERROR",EXPECTED:"PENDING",FAILURE:"FAILED",PENDING:"PENDING",SUCCESS:"SUCCESS"})[s],rr=s=>{let t=null;s.author?t=s.author:t=_e;let e=(s.reviewRequests?.nodes||[]).filter(k).filter(i=>!i.asCodeOwner),r=s.headRepository?.url;r&&!r.endsWith(".git")&&(r=`${r}.git`);let n=s.repository?.url;n&&!n.endsWith(".git")&&(n=`${n}.git`);let o=e.filter(i=>i.requestedReviewer&&"__typename"in i.requestedReviewer).map(i=>({reviewer:W(i.requestedReviewer),state:"REVIEW_REQUESTED"})).concat((s.latestReviews?.nodes||[]).filter(k).map(i=>{let a=_e;return i.author&&i.author.__typename&&(a=i.author),{reviewer:W(a),state:io[i.state]}}));return{id:s.fullDatabaseId!==void 0?s.fullDatabaseId:s.databaseId.toString(),graphQLId:s.id,title:s.title,description:s.body,number:s.number,state:ho[s.state],commentCount:s.comments.totalCount,upvoteCount:s.reactions.totalCount,author:t&&t.__typename?W(t):null,createdDate:new Date(s.createdAt),isDraft:s.isDraft,repository:{id:s.repository.databaseId.toString(),graphQLId:s.repository.id,name:s.repository.name,owner:{login:s.repository.owner.login},remoteInfo:{cloneUrlHTTPS:n,cloneUrlSSH:s.repository.sshUrl}},isCrossRepository:s.headRepository!=null&&s.headRepository.databaseId!==s.repository.databaseId,headRepository:s.headRepository?{id:s.headRepository.databaseId.toString(),graphQLId:s.headRepository.id,name:s.headRepository.name,owner:{login:s.headRepository.owner.login},remoteInfo:{cloneUrlHTTPS:r,cloneUrlSSH:s.headRepository.sshUrl},isFork:s.headRepository.isFork}:null,headCommit:{buildStatuses:s.commits.nodes?.filter(k)[0]?.commit.statusCheckRollup?.contexts.nodes?.filter(k).map(i=>"context"in i?{completedAt:null,description:i.description,name:i.context,state:Io(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:Ro(i.status,i.conclusion),startedAt:i.startedAt?new Date(i.startedAt):null,stage:null,url:i.permalink})??[]},headRef:s.headRef?{name:s.headRef.name,oid:s.headRef.target?.oid??null}:null,baseRef:s.baseRef?{name:s.baseRef.name,oid:s.baseRef.target?.oid??null}:null,url:s.url,updatedDate:new Date(s.updatedAt),closedDate:s.closedAt?new Date(s.closedAt):null,mergedDate:s.mergedAt?new Date(s.mergedAt):null,assignees:s.assignees.nodes?s.assignees.nodes.filter(k).map(i=>W(i)):null,reviews:o,reviewDecision:J(o),additions:s.additions,deletions:s.deletions,fileCount:s.changedFiles,commitCount:s.commits.totalCount,mergeableState:uo[s.mergeStateStatus]??ao[s.mergeable],milestone:s.milestone?nr(s.milestone):null,labels:s.labels?.nodes?.filter(k).map(sr)??[],permissions:{canMerge:po.includes(s.repository.viewerPermission),canMergeAndBypassProtections:s.viewerCanMergeAsAdmin??!1}}},bo=s=>{let{id:t,comments:e,isOutdated:r,isResolved:n,line:o,startLine:i,diffSide:a,originalLine:u,originalStartLine:l,startDiffSide:d}=s,p=e.nodes?.[0];if(!p)return null;let{author:c,body:g,databaseId:m,fullDatabaseId:h,id:y,path:f,publishedAt:P,url:v}=p,A=o??u,D=i??l,w=a??d;return{author:c?{avatarUrl:c.avatarUrl,email:null,name:c.login}:null,body:g,createdAt:P?new Date(P):null,diffLines:fs(p.diffHunk,A,D,w),id:h??m.toString(),isOutdated:r,isResolved:n,graphQLId:y,threadId:t,filename:f,replies:e.nodes?.filter(k).slice(1).map(yo)??[],url:v,line:A,startLine:D,side:w}},yo=s=>({author:s.author?{avatarUrl:s.author.avatarUrl,email:null,name:s.author.login}:null,body:s.body,createdAt:s.publishedAt?new Date(s.publishedAt):null,graphQLId:s.id,id:s.fullDatabaseId??s.databaseId.toString(),url:s.url}),Po=s=>{let t=null;return s.author?t=s.author:t=_e,{id:s.fullDatabaseId!==void 0?s.fullDatabaseId:s.databaseId.toString(),graphQLId:s.id,number:s.number,title:s.title,author:t&&t.__typename?W(t):null,commentCount:s.comments.totalCount,closedDate:s.closedAt?new Date(s.closedAt):null,createdDate:new Date(s.createdAt),description:null,state:{name:lo[s.state],color:null},type:null,repository:{id:s.repository.databaseId.toString(),graphQLId:s.repository.id,name:s.repository.name,owner:{login:s.repository.owner.login}},url:s.url,updatedDate:new Date(s.updatedAt),assignees:s.assignees.nodes?.filter(k).map(e=>W(e))??[],upvoteCount:s.reactions.totalCount,milestone:s.milestone?nr(s.milestone):null,labels:s.labels?.nodes?.filter(k).map(sr)??[]}},nr=s=>({id:s.number.toString(),graphQLId:s.id.toString(),number:s.number,title:s.title,description:s.description,isOpen:s.state=="OPEN",url:s.url,startDate:null,dueDate:s.dueOn?new Date(s.dueOn):null}),ve=class extends F{constructor(){super(...arguments);this._scopesCache={};this._enterpriseVersionsCache={}}async getScopes(e){let r=e.token||this.config.token;if(!r)return[];let n=this._scopesCache[r];if(!n){let i=(await b(this.config,{query:"query { rateLimit(dryRun: true) { __typename } }"},e)).headers["x-oauth-scopes"];n=i?i.split(", "):[],this._scopesCache[r]=n}return n}async getEnterpriseVersion(e){let r=e.baseUrl||this.config.baseUrl;if(!r)return null;let n=this._enterpriseVersionsCache[r];if(!n){let o=await this.config.request({url:`${X(this.config,e)}/meta`,headers:R(e.token||this.config.token)});if(!o.body.installed_version)return null;n=o.body.installed_version.split(".").slice(0,3).map(i=>parseInt(i,10)),this._enterpriseVersionsCache[r]=n}return n}getEnterpriseAvatarUrlIfNeeded(e,r,n){let o=n.baseUrl||this.config.baseUrl;return!o||o.startsWith(Xe)?e:r?`https://avatars.githubusercontent.com/u/e?email=${encodeURIComponent(r)}`:""}async getCurrentUser(e={},r={}){if(e.fields&&!e.fields.length)throw new Error('"fields" must contain at least one field or be omitted');let n=Mr(e.fields),o=await this.getScopes(r),i=await b(this.config,{query:`
|
|
373
373
|
query getCurrentUser {
|
|
374
374
|
viewer {
|
|
375
|
-
${
|
|
375
|
+
${Q(!1,re(o),n)}
|
|
376
376
|
}
|
|
377
377
|
}
|
|
378
378
|
`},r),a=i.body.data?.viewer;if(!a)throw new I("Current user not found.",i.body.errors);return{data:W(a,n)}}async getAccountsForRepo(e,r={}){let n=await this.getScopes(r),{repo:{namespace:o,name:i},cursor:a}=e,u=await b(this.config,{query:`
|
|
@@ -380,7 +380,7 @@ query getAccountsForRepo($owner: String!, $name: String! $cursor: String, $first
|
|
|
380
380
|
repository(owner: $owner, name: $name) {
|
|
381
381
|
assignableUsers(first: $first, after: $cursor) {
|
|
382
382
|
nodes {
|
|
383
|
-
${
|
|
383
|
+
${Q(!1,re(n))}
|
|
384
384
|
}
|
|
385
385
|
pageInfo {
|
|
386
386
|
endCursor
|
|
@@ -435,12 +435,12 @@ mutation createCommitOnBranch(
|
|
|
435
435
|
}
|
|
436
436
|
}
|
|
437
437
|
}
|
|
438
|
-
`,variables:{branchName:u.name,expectedHeadOid:u.oid,fileChanges:{additions:Object.entries(i).map(([p
|
|
438
|
+
`,variables:{branchName:u.name,expectedHeadOid:u.oid,fileChanges:{additions:Object.entries(i).map(([d,p])=>({contents:Ss.Base64.encode(p),path:d})),deletions:o.map(d=>({path:d}))},message:{body:n.description,headline:n.summary},repositoryNameWithOwner:`${a.namespace}/${a.name}`}},r);if(!l.body.data)throw new I("Could not create commit",l.body.errors);return{data:{name:l.body.data.createCommitOnBranch.ref.name,commit:{authoredDate:new Date(l.body.data.createCommitOnBranch.commit.authoredDate),committedDate:new Date(l.body.data.createCommitOnBranch.commit.committedDate),oid:l.body.data.createCommitOnBranch.commit.oid}}}}async getAccountForEmail(e,r={}){let n=await this.getScopes(r),o=await b(this.config,{query:`
|
|
439
439
|
query getAccountForEmail($query: String! $avatarSize: Int) {
|
|
440
440
|
search(query: $query, type: USER, first: 1) {
|
|
441
441
|
nodes {
|
|
442
442
|
... on User {
|
|
443
|
-
${
|
|
443
|
+
${Q(!0,re(n))}
|
|
444
444
|
}
|
|
445
445
|
}
|
|
446
446
|
}
|
|
@@ -448,7 +448,7 @@ query getAccountForEmail($query: String! $avatarSize: Int) {
|
|
|
448
448
|
`,variables:{query:`in:email ${e.email}`,avatarSize:e.avatarSize}},r),i=o.body.data?.search?.nodes?.[0];if(!i)throw new I("Could not find user via email",o.body.errors);return{data:W({...i,avatarUrl:this.getEnterpriseAvatarUrlIfNeeded(i.avatarUrl,i.email,r)})}}async getAccountForUsername(e,r={}){let n=await this.getScopes(r),o=await b(this.config,{query:`
|
|
449
449
|
query getUserForUsername($login: String! $avatarSize: Int) {
|
|
450
450
|
user(login: $login) {
|
|
451
|
-
${
|
|
451
|
+
${Q(!0,re(n))}
|
|
452
452
|
}
|
|
453
453
|
}
|
|
454
454
|
`,variables:{login:e.username,avatarSize:e.avatarSize}},r),i=o.body.data?.user;if(!i)throw new I("Could not find user via username",o.body.errors);return{data:W({...i,avatarUrl:this.getEnterpriseAvatarUrlIfNeeded(i.avatarUrl,i.email,r)})}}async getOrgsForCurrentUser(e={},r={}){let n=await b(this.config,{query:`
|
|
@@ -480,7 +480,7 @@ query getOrgMember($cursor: String, $first: Int!, $login: String!) {
|
|
|
480
480
|
hasNextPage
|
|
481
481
|
}
|
|
482
482
|
nodes {
|
|
483
|
-
${
|
|
483
|
+
${Q(!1,!0)}
|
|
484
484
|
}
|
|
485
485
|
}
|
|
486
486
|
}
|
|
@@ -489,19 +489,19 @@ query getOrgMember($cursor: String, $first: Int!, $login: String!) {
|
|
|
489
489
|
`,variables:{cursor:e.cursor,first:$,login:e.org}},r);if(!n.body.data?.viewer.organization?.membersWithRole&&n.body.errors?.length)throw new I("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=>W({...i,avatarUrl:this.getEnterpriseAvatarUrlIfNeeded(i.avatarUrl,i.email,r)}))}}async getRepo(e,r={}){let n=await b(this.config,{query:`
|
|
490
490
|
query getRepo($owner: String!, $name: String!) {
|
|
491
491
|
repository(owner: $owner, name: $name) {
|
|
492
|
-
${
|
|
492
|
+
${er}
|
|
493
493
|
}
|
|
494
494
|
}
|
|
495
|
-
`,variables:{owner:e.namespace,name:e.name}},r);if(!n.body.data?.repository)throw new I(`Repository ${e.namespace}/${e.name} not found`,n.body.errors);return{data:
|
|
496
|
-
getRepo_${
|
|
497
|
-
${
|
|
495
|
+
`,variables:{owner:e.namespace,name:e.name}},r);if(!n.body.data?.repository)throw new I(`Repository ${e.namespace}/${e.name} not found`,n.body.errors);return{data:tr(n.body.data.repository)}}async getRepos(e,r={}){let n=e.map(({namespace:u,name:l},d)=>`
|
|
496
|
+
getRepo_${d}: repository(owner: "${u}", name: "${l}") {
|
|
497
|
+
${er}
|
|
498
498
|
}
|
|
499
499
|
`).join(`
|
|
500
500
|
`),o=await b(this.config,{query:`
|
|
501
501
|
query batchGetRepos {
|
|
502
502
|
${n}
|
|
503
503
|
}
|
|
504
|
-
`},r);if(!o.body.data)throw new I("Could not fetch repos",o.body.errors);let i=[],a=[];return e.forEach((u,l)=>{let
|
|
504
|
+
`},r);if(!o.body.data)throw new I("Could not fetch repos",o.body.errors);let i=[],a=[];return e.forEach((u,l)=>{let d=o.body.data[`getRepo_${l}`];d?i.push(tr(d)):a.push({input:u})}),{data:i,errors:a}}async fetchMultipleRESTPages(e,r,n,o){let i=[];for(let p=0;p<r;p++)i.push(n(e+p));let a=await Promise.all(i),u=[];for(let p of a){if(!p.body)throw new Error(p.statusText||"Unknown error");u=u.concat(p.body.map(c=>o(c)))}let l=a.every(p=>p.body.length===100),d=e+r;return{data:u,pageInfo:{hasNextPage:l,nextPage:l?d:null}}}async getReposForCurrentUser(e,r={}){if(e.simultaneousPagesToFetch&&e.simultaneousPagesToFetch>40)throw new Error("The argument 'simultaneousPagesToFetch' cannot exceed 40 for 'getReposForCurrentUser'");let n=new URLSearchParams;n.append("per_page","100"),e.affiliations&&n.append("affiliation",e.affiliations.join(","));let o=i=>this.config.request({url:`${X(this.config,r)}/user/repos?${n.toString()}&page=${i}`,headers:{...R(r.token||this.config.token),Accept:"application/vnd.github.raw+json","X-Github-Next-Global-ID":1}});return await this.fetchMultipleRESTPages(e.page??1,e.simultaneousPagesToFetch??4,o,Es)}async getReposForOrg(e,r={}){if(e.simultaneousPagesToFetch&&e.simultaneousPagesToFetch>40)throw new Error("The argument 'simultaneousPagesToFetch' cannot exceed 40 for 'getReposForOrg'");let n=o=>this.config.request({url:`${X(this.config,r)}/orgs/${e.orgName}/repos?per_page=100&page=${o}`,headers:{...R(r.token||this.config.token),Accept:"application/vnd.github.raw+json","X-Github-Next-Global-ID":1}});return await this.fetchMultipleRESTPages(e.page??1,e.simultaneousPagesToFetch??4,n,Es)}async getReposForUsernames(e,r={}){if(!e.usernames.length)return{pageInfo:{endCursor:null,hasNextPage:!1},data:[]};let n=await b(this.config,{query:`
|
|
505
505
|
query getReposForUsernames($query: String!, $cursor: String, $first: Int!) {
|
|
506
506
|
search(query: $query, type: REPOSITORY, first: $first, after: $cursor) {
|
|
507
507
|
pageInfo {
|
|
@@ -510,12 +510,12 @@ query getReposForUsernames($query: String!, $cursor: String, $first: Int!) {
|
|
|
510
510
|
}
|
|
511
511
|
nodes {
|
|
512
512
|
... on Repository {
|
|
513
|
-
${
|
|
513
|
+
${er}
|
|
514
514
|
}
|
|
515
515
|
}
|
|
516
516
|
}
|
|
517
517
|
}
|
|
518
|
-
`,variables:{query:`fork:true ${e.usernames.map(i=>`user:${i}`).join(" ")}`,cursor:e.cursor,first:$}},r);if(!n.body.data)throw new I("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(
|
|
518
|
+
`,variables:{query:`fork:true ${e.usernames.map(i=>`user:${i}`).join(" ")}`,cursor:e.cursor,first:$}},r);if(!n.body.data)throw new I("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(tr)}}async getReposForOwners(e,r={}){return this.getReposForUsernames({usernames:e.owners.filter(n=>n.username).map(n=>n.username),cursor:e.cursor},r)}async getRefs(e,r,n={}){let o=await b(this.config,{query:`
|
|
519
519
|
query getRefs($owner: String!, $name: String!, $refPrefix: String!, $cursor: String, $first: Int!) {
|
|
520
520
|
repository(owner: $owner, name: $name) {
|
|
521
521
|
refs(refPrefix: $refPrefix first: $first after: $cursor) {
|
|
@@ -575,7 +575,7 @@ query getBlame($owner: String!, $name: String!, $ref: String!, $path: String!) {
|
|
|
575
575
|
}
|
|
576
576
|
}
|
|
577
577
|
}
|
|
578
|
-
`,variables:{owner:e.repo.namespace,name:e.repo.name,ref:e.ref,path:e.path}},r),o=n.body.data?.repository;if(!o)throw new I("Blame repository not found.",n.body.errors);let i=o.object;if(!i||!("blame"in i))throw new I("Ref not found.",n.body.errors);if(i.blame.ranges.length===0)throw new I("File not found.",n.body.errors);return{data:{ranges:i.blame.ranges.map(a=>({startingLine:a.startingLine,endingLine:a.endingLine,commit:{oid:a.commit.oid,parentOids:a.commit.parents.nodes?.map(u=>u.oid)||[],authoredDate:new Date(a.commit.authoredDate),author:a.commit.author?{name:a.commit.author.name,email:a.commit.author.email,avatarUrl:a.commit.author.avatarUrl}:null,committedDate:new Date(a.commit.committedDate),committer:a.commit.committer?{name:a.commit.committer.name,email:a.commit.committer.email,avatarUrl:a.commit.committer.avatarUrl}:null,message:a.commit.message,fileCount:a.commit.changedFilesIfAvailable,additions:a.commit.additions,deletions:a.commit.deletions}}))}}}async getFileContents(e,r={}){let n=await this.config.request({url:`${X(this.config,r)}/repos/${e.repo.namespace}/${e.repo.name}/contents/${encodeURIComponent(e.path)}?ref=${e.ref}`,headers:{...R(r.token||this.config.token),Accept:"application/vnd.github.raw+json"}});if(n.headers["content-type"].startsWith("application/json"))throw new Error(`GitHub: got directory when fetching "${e.path}", getFileContents does not support fetching directories`);if(!n.headers["content-type"].startsWith("application/vnd.github.raw+json"))throw new Error(`GitHub: unsupported content type "${n.headers["content-type"]}" when fetching "${e.path}"`);return{data:new Blob([n.body])}}async getMergeBase(e,r={}){return{data:(await this.config.request({url:`${X(this.config,r)}/repos/${e.repo.namespace}/${e.repo.name}/compare/${encodeURIComponent(e.base)}...${encodeURIComponent(e.head)}`,headers:R(r.token||this.config.token)})).body.merge_base_commit.sha}}async getPullRequestDiff(e,r={}){return(await this.config.request({url:`${X(this.config,r)}/repos/${e.repo.namespace}/${e.repo.name}/pulls/${e.pullRequestId}`,headers:{...R(r.token||this.config.token),Accept:"application/vnd.github.diff"}})).body??""}async searchPullRequests(e,r={}){let n=await this.getEnterpriseVersion(r),o=await this.getScopes(r),i=
|
|
578
|
+
`,variables:{owner:e.repo.namespace,name:e.repo.name,ref:e.ref,path:e.path}},r),o=n.body.data?.repository;if(!o)throw new I("Blame repository not found.",n.body.errors);let i=o.object;if(!i||!("blame"in i))throw new I("Ref not found.",n.body.errors);if(i.blame.ranges.length===0)throw new I("File not found.",n.body.errors);return{data:{ranges:i.blame.ranges.map(a=>({startingLine:a.startingLine,endingLine:a.endingLine,commit:{oid:a.commit.oid,parentOids:a.commit.parents.nodes?.map(u=>u.oid)||[],authoredDate:new Date(a.commit.authoredDate),author:a.commit.author?{name:a.commit.author.name,email:a.commit.author.email,avatarUrl:a.commit.author.avatarUrl}:null,committedDate:new Date(a.commit.committedDate),committer:a.commit.committer?{name:a.commit.committer.name,email:a.commit.committer.email,avatarUrl:a.commit.committer.avatarUrl}:null,message:a.commit.message,fileCount:a.commit.changedFilesIfAvailable,additions:a.commit.additions,deletions:a.commit.deletions}}))}}}async getFileContents(e,r={}){let n=await this.config.request({url:`${X(this.config,r)}/repos/${e.repo.namespace}/${e.repo.name}/contents/${encodeURIComponent(e.path)}?ref=${e.ref}`,headers:{...R(r.token||this.config.token),Accept:"application/vnd.github.raw+json"}});if(n.headers["content-type"].startsWith("application/json"))throw new Error(`GitHub: got directory when fetching "${e.path}", getFileContents does not support fetching directories`);if(!n.headers["content-type"].startsWith("application/vnd.github.raw+json"))throw new Error(`GitHub: unsupported content type "${n.headers["content-type"]}" when fetching "${e.path}"`);return{data:new Blob([n.body])}}async getMergeBase(e,r={}){return{data:(await this.config.request({url:`${X(this.config,r)}/repos/${e.repo.namespace}/${e.repo.name}/compare/${encodeURIComponent(e.base)}...${encodeURIComponent(e.head)}`,headers:R(r.token||this.config.token)})).body.merge_base_commit.sha}}async getPullRequestDiff(e,r={}){return(await this.config.request({url:`${X(this.config,r)}/repos/${e.repo.namespace}/${e.repo.name}/pulls/${e.pullRequestId}`,headers:{...R(r.token||this.config.token),Accept:"application/vnd.github.diff"}})).body??""}async searchPullRequests(e,r={}){let n=await this.getEnterpriseVersion(r),o=await this.getScopes(r),i=re(o),a=gs(e.states),u=p=>{let c=p&&typeof e.isDraft=="boolean"?`${e.query} draft:${e.isDraft}`:e.query;return Yt("pr",c,e.cursor,{maxPageSize:e.maxPageSize??ps,supportsEmail:i,supportsDrafts:p,enterpriseVersion:n,includeFromArchivedRepos:e.includeFromArchivedRepos,stateQualifier:a})},l=await b(this.config,u(!0),r);l.body.errors&&tt(l.body.errors)&&(this.config.baseUrl||r.baseUrl)&&(l=await b(this.config,u(!1),r));let{data:d}=l.body;if(!d)throw new I("Could not search pull requests",l.body.errors);return{pageInfo:{hasNextPage:d.search.pageInfo.hasNextPage,endCursor:d.search.pageInfo.endCursor},data:x(d.search.nodes?.filter(k).map(rr)||[],e.states)}}async searchIssues(e,r={}){let n=await this.getEnterpriseVersion(r),o=await this.getScopes(r),i=re(o),a=hs(e.states),u=await b(this.config,Yt("issue",e.query,e.cursor,{supportsEmail:i,includeFromArchivedRepos:e.includeFromArchivedRepos,maxPageSize:e.maxPageSize??ds,enterpriseVersion:n,stateQualifier:a}),r),{data:l}=u.body;if(!l)throw new I("Could not search issues",u.body.errors);return{pageInfo:{hasNextPage:l.search.pageInfo.hasNextPage,endCursor:l.search.pageInfo.endCursor},data:l.search.nodes?.filter(k).map(Po)||[]}}async getPullRequestsAssociatedWithUser(e,r={}){let n=[`involves:${e.username}`];return e.repos?.length&&e.repos.forEach(o=>{n.push(`repo:${o.namespace}/${o.name}`)}),e.labelNames&&e.labelNames.forEach(o=>{n.push(`label:"${o}"`)}),this.searchPullRequests({query:n.join(" "),cursor:e.cursor,includeFromArchivedRepos:e.includeFromArchivedRepos,maxPageSize:e.maxPageSize},r)}async getPullRequestsForRepos(e,r={}){let{assigneeLogins:n,updatedBefore:o,authorLogin:i,repos:a,reviewRequestedLogin:u,startQuery:l,mentionLogin:d,labelNames:p,maxPageSize:c}=e,g=Xt(l||"");return a.forEach(m=>{g.push(`repo:${m.namespace}/${m.name}`)}),n&&n.forEach(m=>{g.push(`assignee:${m}`)}),o&&g.push(`updated:<${o}`),i&&g.push(`author:${i}`),u&&g.push(`review-requested:${u}`),d&&g.push(`mentions:${d}`),p&&p.forEach(m=>{g.push(`label:"${m}"`)}),this.searchPullRequests({query:`sort:updated ${g.join(" ")}`,isDraft:e.isDraft,cursor:e.cursor,includeFromArchivedRepos:e.includeFromArchivedRepos,maxPageSize:c,states:e.states},r)}async getPullRequestForRepo(e,r={}){let n=await this.getEnterpriseVersion(r),o=await this.getScopes(r),i=re(o),a=p=>({query:`query getPullRequest(
|
|
579
579
|
$owner: String!
|
|
580
580
|
$name: String!
|
|
581
581
|
$number: Int!
|
|
@@ -585,18 +585,18 @@ query getBlame($owner: String!, $name: String!, $ref: String!, $path: String!) {
|
|
|
585
585
|
name: $name
|
|
586
586
|
) {
|
|
587
587
|
pullRequest(number: $number) {
|
|
588
|
-
${
|
|
588
|
+
${et(p,i,n)}
|
|
589
589
|
}
|
|
590
590
|
}
|
|
591
|
-
}`,variables:{owner:e.repo.namespace,name:e.repo.name,number:e.number}}),u=await b(this.config,a(!0),r);u.body.errors&&
|
|
591
|
+
}`,variables:{owner:e.repo.namespace,name:e.repo.name,number:e.number}}),u=await b(this.config,a(!0),r);u.body.errors&&tt(u.body.errors)&&(this.config.baseUrl||r.baseUrl)&&(u=await b(this.config,a(!1),r));let{data:l}=u.body;if(!l)throw new I("Could not fetch pull request by number",u.body.errors);let d=u.body.data?.repository.pullRequest;return{data:d?rr(d):null}}async getPullRequestDescription(e,r={}){try{let n=await this.config.request({url:`${X(this.config,r)}/repos/${e.repo.namespace}/${e.repo.name}/pulls/${e.number}`,headers:{...R(r.token||this.config.token),Accept:"application/vnd.github.full+json"}});return{data:{description:n.body?.body??"",descriptionHtml:n.body?.body_html||null}}}catch{return{data:{description:null,descriptionHtml:null}}}}async setPullRequestDescription(e,r={}){let n=await this.config.request({method:"PATCH",url:`${X(this.config,r)}/repos/${e.repo.namespace}/${e.repo.name}/pulls/${e.number}`,headers:{...R(r.token||this.config.token),Accept:"application/vnd.github+json","Content-Type":"application/json"},body:JSON.stringify({body:e.description})});return{data:{description:n.body?.body??e.description,descriptionHtml:n.body?.body_html||null}}}async getPullRequestByGraphQLId(e,r={}){let n=await this.getEnterpriseVersion(r),o=await this.getScopes(r),i=re(o),a=p=>({query:`query getPullRequest(
|
|
592
592
|
$graphQLId: ID!
|
|
593
593
|
) {
|
|
594
594
|
node(id: $graphQLId) {
|
|
595
595
|
... on PullRequest {
|
|
596
|
-
${
|
|
596
|
+
${et(p,i,n)}
|
|
597
597
|
}
|
|
598
598
|
}
|
|
599
|
-
}`,variables:{graphQLId:e.graphQLId}}),u=await b(this.config,a(!0),r);u.body.errors&&
|
|
599
|
+
}`,variables:{graphQLId:e.graphQLId}}),u=await b(this.config,a(!0),r);u.body.errors&&tt(u.body.errors)&&(this.config.baseUrl||r.baseUrl)&&(u=await b(this.config,a(!1),r));let{data:l}=u.body;if(!l)throw new I("Could not fetch pull request by id",u.body.errors);let d=u.body.data?.node;return{data:d?rr(d):null}}async closePullRequest(e,r={}){let{pullRequest:{graphQLId:n}}=e;if(!n)throw new Error('GitHub requires "graphQLId" for this function.');let o=`mutation ClosePullRequest($pullRequestGraphQLId: ID!) {
|
|
600
600
|
closePullRequest(input: { pullRequestId: $pullRequestGraphQLId }) {
|
|
601
601
|
pullRequest {
|
|
602
602
|
id
|
|
@@ -669,7 +669,7 @@ query getBlame($owner: String!, $name: String!, $ref: String!, $path: String!) {
|
|
|
669
669
|
}
|
|
670
670
|
}
|
|
671
671
|
}
|
|
672
|
-
}`,a=await b(this.config,{query:i,variables:{subjectId:n.graphQLId,body:o}},r);if(!a.body.data?.addComment?.commentEdge?.node?.id)throw new I("Could not add comment to pull request",a.body.errors)}async addInlineCommentToPullRequest(e,r={}){let{pullRequest:n,comment:o,path:i,line:a,side:u="RIGHT",threadId:l}=e;if(!n.graphQLId)throw new Error('GitHub requires "graphQLId" for this function.');if(!o?.trim())throw new Error("GitHub requires a comment when adding an inline comment to a pull request.");if(l)return this.addReplyToReviewThread({threadId:l,comment:o},r);if(!i?.trim())throw new Error("GitHub requires a file path when adding an inline comment to a pull request.");if(!Number.isInteger(a)||a<1)throw new Error("GitHub requires a positive line number when adding an inline comment to a pull request.");if(u!=="LEFT"&&u!=="RIGHT")throw new Error('GitHub requires side to be either "LEFT" or "RIGHT".');return this.createReviewThread({pullRequest:n,comment:o,path:i,line:a,side:u},r)}async deleteInlineComment(e,r={}){let{commentId:n}=e;if(!n)throw new Error('GitHub requires "commentId" for this function.');let o=await b(this.config,{query:
|
|
672
|
+
}`,a=await b(this.config,{query:i,variables:{subjectId:n.graphQLId,body:o}},r);if(!a.body.data?.addComment?.commentEdge?.node?.id)throw new I("Could not add comment to pull request",a.body.errors)}async addInlineCommentToPullRequest(e,r={}){let{pullRequest:n,comment:o,path:i,line:a,side:u="RIGHT",threadId:l}=e;if(!n.graphQLId)throw new Error('GitHub requires "graphQLId" for this function.');if(!o?.trim())throw new Error("GitHub requires a comment when adding an inline comment to a pull request.");if(l)return this.addReplyToReviewThread({threadId:l,comment:o},r);if(!i?.trim())throw new Error("GitHub requires a file path when adding an inline comment to a pull request.");if(!Number.isInteger(a)||a<1)throw new Error("GitHub requires a positive line number when adding an inline comment to a pull request.");if(u!=="LEFT"&&u!=="RIGHT")throw new Error('GitHub requires side to be either "LEFT" or "RIGHT".');return this.createReviewThread({pullRequest:n,comment:o,path:i,line:a,side:u},r)}async deleteInlineComment(e,r={}){let{commentId:n}=e;if(!n)throw new Error('GitHub requires "commentId" for this function.');let o=await b(this.config,{query:bs,variables:{pullRequestReviewCommentId:n}},r);if(!o.body.data?.deletePullRequestReviewComment)throw new I("Could not delete inline comment",o.body.errors)}async deleteComment(e,r={}){let{commentId:n}=e;if(!n)throw new Error('GitHub requires "commentId" for this function.');let o=await b(this.config,{query:Is,variables:{issueCommentId:n}},r);if(!o.body.data?.deleteIssueComment)throw new I("Could not delete comment",o.body.errors)}async editComment(e,r={}){let{commentId:n,body:o}=e;if(!n)throw new Error('GitHub requires "commentId" for this function.');if(!o?.trim())throw new Error("GitHub requires a body when editing a comment.");let i=await b(this.config,{query:ys,variables:{issueCommentId:n,body:o}},r);if(!i.body.data?.updateIssueComment?.issueComment?.id)throw new I("Could not edit comment",i.body.errors)}async editInlineComment(e,r={}){let{commentId:n,body:o}=e;if(!n)throw new Error('GitHub requires "commentId" for this function.');if(!o?.trim())throw new Error("GitHub requires a body when editing an inline comment.");let i=await b(this.config,{query:qs,variables:{pullRequestReviewCommentId:n,body:o}},r);if(!i.body.data?.updatePullRequestReviewComment?.pullRequestReviewComment?.id)throw new I("Could not edit inline comment",i.body.errors)}async resolveReviewThread(e,r={}){let{threadId:n}=e;if(!n)throw new Error('GitHub requires "threadId" for this function.');let o=await b(this.config,{query:Ps,variables:{pullRequestReviewThreadId:n}},r);if(!o.body.data?.resolveReviewThread?.thread?.id)throw new I("Could not resolve review thread",o.body.errors)}async unresolveReviewThread(e,r={}){let{threadId:n}=e;if(!n)throw new Error('GitHub requires "threadId" for this function.');let o=await b(this.config,{query:ws,variables:{pullRequestReviewThreadId:n}},r);if(!o.body.data?.unresolveReviewThread?.thread?.id)throw new I("Could not unresolve review thread",o.body.errors)}async addReplyToReviewThread(e,r){let{threadId:n,comment:o}=e,i=`mutation AddPullRequestReviewThreadReply(
|
|
673
673
|
$threadId: ID!,
|
|
674
674
|
$body: String!
|
|
675
675
|
) {
|
|
@@ -707,7 +707,7 @@ query getBlame($owner: String!, $name: String!, $ref: String!, $path: String!) {
|
|
|
707
707
|
}
|
|
708
708
|
}
|
|
709
709
|
}
|
|
710
|
-
}`,
|
|
710
|
+
}`,d=await b(this.config,{query:l,variables:{pullRequestId:n.graphQLId,body:o,path:i,line:a,side:u}},r);if(!d.body.data?.addPullRequestReview?.pullRequestReview?.id)throw new I("Could not add inline comment to pull request",d.body.errors);return d.body.data?.addPullRequestReview?.pullRequestReview?.comments?.nodes?.[0]?.id}async setPullRequestMilestone(e,r={}){let{pullRequest:n,milestone:o}=e;if(!n.graphQLId)throw new Error('GitHub requires "graphQLId" for this function.');let i=`mutation SetPullRequestMilestone($pullRequestGraphQLId: ID!, $milestoneGraphQLId: ID) {
|
|
711
711
|
updatePullRequest(input: { pullRequestId: $pullRequestGraphQLId, milestoneId: $milestoneGraphQLId }) {
|
|
712
712
|
pullRequest {
|
|
713
713
|
id
|
|
@@ -725,13 +725,13 @@ query getBlame($owner: String!, $name: String!, $ref: String!, $path: String!) {
|
|
|
725
725
|
id
|
|
726
726
|
}
|
|
727
727
|
}
|
|
728
|
-
}`,o=await b(this.config,{query:n,variables:{pullRequestGraphQLId:e}},r);if(!o.body.data?.convertPullRequestToDraft?.pullRequest?.id)throw new I("Could not convert pull request to draft",o.body.errors)}async setPullRequestAsDraft(e,r={}){let{pullRequest:{graphQLId:n},isDraft:o}=e;if(!n)throw new Error('GitHub requires "graphQLId" for this function.');if(o){await this.convertPullRequestToDraft(n,r);return}await this.markPullRequestReadyForReview(n,r)}async setPullRequestReviewers(e,r={}){let{pullRequest:{reviews:n,graphQLId:o},reviewers: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(
|
|
728
|
+
}`,o=await b(this.config,{query:n,variables:{pullRequestGraphQLId:e}},r);if(!o.body.data?.convertPullRequestToDraft?.pullRequest?.id)throw new I("Could not convert pull request to draft",o.body.errors)}async setPullRequestAsDraft(e,r={}){let{pullRequest:{graphQLId:n},isDraft:o}=e;if(!n)throw new Error('GitHub requires "graphQLId" for this function.');if(o){await this.convertPullRequestToDraft(n,r);return}await this.markPullRequestReadyForReview(n,r)}async setPullRequestReviewers(e,r={}){let{pullRequest:{reviews:n,graphQLId:o},reviewers: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(p=>p.state!=="REVIEW_REQUESTED").map(p=>{if(!p.reviewer.graphQLId)throw new Error('GitHub requires reviewer "graphQLId" for this function.');return p.reviewer.graphQLId}),u=i.map(p=>{if(!p.graphQLId)throw new Error('GitHub requires reviewer "graphQLId" for this function.');return p.graphQLId}).filter(p=>a.indexOf(p)===-1),l=`mutation SetPullRequestReviewers($pullRequestGraphQLId: ID!, $reviewerGraphQLIds: [ID!]!) {
|
|
729
729
|
requestReviews(input: { pullRequestId: $pullRequestGraphQLId, userIds: $reviewerGraphQLIds }) {
|
|
730
730
|
pullRequest {
|
|
731
731
|
id
|
|
732
732
|
}
|
|
733
733
|
}
|
|
734
|
-
}`,
|
|
734
|
+
}`,d=await b(this.config,{query:l,variables:{pullRequestGraphQLId:o,reviewerGraphQLIds:u}},r);if(!d.body.data?.requestReviews?.pullRequest?.id)throw new I("Could not set pull request reviewers",d.body.errors)}async reRequestPullRequestReviews(e,r={}){let{pullRequest:{reviews:n,graphQLId:o},reviewers:i}=e;if(!o)throw new Error('GitHub requires "graphQLId" for this function.');if(!n)throw new Error('GitHub requires "reviews" for this function.');let a=[];for(let d of i){if(!d.graphQLId)throw new Error('GitHub requires reviwer "graphQLId" for this function.');if(!n.find(p=>p.reviewer.graphQLId===d.graphQLId))throw new Error("Can only re-request review from existing reviewer.");a.push(d.graphQLId)}let u=`mutation SetPullRequestReviewers($pullRequestGraphQLId: ID!, $reviewerGraphQLIds: [ID!]!) {
|
|
735
735
|
requestReviews(input: { pullRequestId: $pullRequestGraphQLId, userIds: $reviewerGraphQLIds, union: true }) {
|
|
736
736
|
pullRequest {
|
|
737
737
|
id
|
|
@@ -799,13 +799,13 @@ query getBlame($owner: String!, $name: String!, $ref: String!, $path: String!) {
|
|
|
799
799
|
}
|
|
800
800
|
}
|
|
801
801
|
}
|
|
802
|
-
}`,l=await b(this.config,{query:u,variables:{namespace:o,name:i,pullRequestId:a}},r),
|
|
802
|
+
}`,l=await b(this.config,{query:u,variables:{namespace:o,name:i,pullRequestId:a}},r),d=l.body.data?.repository.pullRequest.reviewThreads.nodes?.filter(k).reduce((c,g)=>{if(!g.comments.nodes?.[0]?.pullRequestReview)return c;let m=g.comments.nodes[0].pullRequestReview,h=bo(g);return h&&(c[m.id]||(c[m.id]=[]),c[m.id].push(h)),c},{})??{};return{data:l.body.data?.repository.pullRequest.reviews.nodes?.filter(k).filter(c=>d[c.id]).map(c=>({author:c.author?{avatarUrl:c.author.avatarUrl,email:null,name:c.author.login}:null,body:c.body,createdAt:c.publishedAt?new Date(c.publishedAt):null,id:c.fullDatabaseId??c.databaseId.toString(),graphQLId:c.id,reviewComments:d[c.id],url:c.url}))??[]}}async getCommentsForPullRequest(e,r={}){let n=await this.getEnterpriseVersion(r),o=!n||K(n,"ISSUE_FULL_DATABASE_ID"),{repo:{namespace:i,name:a},pullRequestNumber:u,cursor:l}=e,d=await b(this.config,{query:vs(o),variables:{namespace:i,name:a,pullRequestNumber:u,cursor:l,first:$}},r),p=d.body.data?.repository;if(!p)throw new I("Could not fetch pull request comments",d.body.errors);return{data:p.pullRequest.comments.nodes?.filter(k).map(Rs)??[],pageInfo:p.pullRequest.comments.pageInfo}}async getIssuesAssociatedWithUser(e,r={}){let[n,o]=e.cursor?.split(";")||[void 0,void 0],i=[];e.labelNames&&e.labelNames.forEach(c=>{i.push(`label:"${c}"`)});let[a,u]=await Promise.all([n==="null"?null:this.searchIssues({query:`author:${e.username} ${i.join(" ")}`,cursor:n,includeFromArchivedRepos:e.includeFromArchivedRepos,maxPageSize:e.maxPageSize},r),o==="null"?null:this.searchIssues({query:`assignee:${e.username} ${i.join(" ")}`,cursor:o,includeFromArchivedRepos:e.includeFromArchivedRepos,maxPageSize:e.maxPageSize},r)]),l={},d=[],p=c=>{l[c.id]||(l[c.id]=!0,d.push(c))};return a?.data.forEach(p),u?.data.forEach(p),{pageInfo:{hasNextPage:a?.pageInfo.hasNextPage||u?.pageInfo.hasNextPage||!1,endCursor:`${a?.pageInfo.hasNextPage&&a?.pageInfo.endCursor||"null"};${u?.pageInfo.hasNextPage&&u?.pageInfo.endCursor||"null"}`},data:d}}async setPullRequestLabels(e,r={}){let{pullRequest:n,labels:o}=e;if(!n.graphQLId)throw new Error('GitHub requires "graphQLId" for this function.');let i=`mutation SetPullRequestLabels($pullRequestGraphQLId: ID!, $labelGraphQLIds: [ID!]) {
|
|
803
803
|
updatePullRequest(input: { pullRequestId: $pullRequestGraphQLId, labelIds: $labelGraphQLIds }) {
|
|
804
804
|
pullRequest {
|
|
805
805
|
id
|
|
806
806
|
}
|
|
807
807
|
}
|
|
808
|
-
}`,a=await b(this.config,{query:i,variables:{pullRequestGraphQLId:n.graphQLId,labelGraphQLIds:o.map(u=>{if(!u.graphQLId)throw new Error('GitHub requires label "graphQLId" for this function.');return u.graphQLId})}},r);if(!a.body.data?.updatePullRequest?.pullRequest?.id)throw new I("Could not set pull request labels",a.body.errors)}async getIssuesForRepos(e,r={}){let n=
|
|
808
|
+
}`,a=await b(this.config,{query:i,variables:{pullRequestGraphQLId:n.graphQLId,labelGraphQLIds:o.map(u=>{if(!u.graphQLId)throw new Error('GitHub requires label "graphQLId" for this function.');return u.graphQLId})}},r);if(!a.body.data?.updatePullRequest?.pullRequest?.id)throw new I("Could not set pull request labels",a.body.errors)}async getIssuesForRepos(e,r={}){let n=Xt(e.startQuery||""),{cursor:o,assigneeLogins:i,updatedBefore:a,authorLogin:u,mentionLogin:l,labelNames:d}=e;return e.repos.forEach(p=>{n.push(`repo:${p.namespace}/${p.name}`)}),i&&i.forEach(p=>{n.push(`assignee:${p}`)}),a&&n.push(`updated:<${a}`),u&&n.push(`author:${u}`),l&&n.push(`mentions:${l}`),d&&d.forEach(p=>{n.push(`label:"${p}"`)}),this.searchIssues({query:`sort:updated ${n.join(" ")}`,cursor:o,includeFromArchivedRepos:e.includeFromArchivedRepos,maxPageSize:e.maxPageSize,states:e.states},r)}async closeIssueWithReason(e,r={}){let{issue:n,reason:o}=e;if(!n.graphQLId)throw new Error('GitHub requires "graphQLId" for this function.');let i=`mutation CloseIssueWithReason($issueGraphQLId: ID!, $reason: IssueClosedStateReason!) {
|
|
809
809
|
closeIssue(input: { issueId: $issueGraphQLId, stateReason: $reason }) {
|
|
810
810
|
issue {
|
|
811
811
|
id
|
|
@@ -846,7 +846,7 @@ query getLabelsForRepo($owner: String!, $name: String! $cursor: String, $first:
|
|
|
846
846
|
repository(owner: $owner, name: $name) {
|
|
847
847
|
milestones(first: $first, after: $cursor) {
|
|
848
848
|
nodes {
|
|
849
|
-
${
|
|
849
|
+
${Ze}
|
|
850
850
|
}
|
|
851
851
|
pageInfo {
|
|
852
852
|
endCursor
|
|
@@ -855,12 +855,12 @@ query getLabelsForRepo($owner: String!, $name: String! $cursor: String, $first:
|
|
|
855
855
|
}
|
|
856
856
|
}
|
|
857
857
|
}
|
|
858
|
-
`,variables:{owner:n,name:o,cursor:i,first:$}},r);if(!a.body.data)throw new I("Could not fetch milestones",a.body.errors);return{pageInfo:a.body.data.repository.milestones?.pageInfo??{endCursor:null,hasNextPage:!1},data:a.body.data.repository.milestones?.nodes?.map(
|
|
858
|
+
`,variables:{owner:n,name:o,cursor:i,first:$}},r);if(!a.body.data)throw new I("Could not fetch milestones",a.body.errors);return{pageInfo:a.body.data.repository.milestones?.pageInfo??{endCursor:null,hasNextPage:!1},data:a.body.data.repository.milestones?.nodes?.map(nr)??[]}}async getLabelsForRepo(e,r={}){let{repo:{namespace:n,name:o},cursor:i}=e,a=await b(this.config,{query:`
|
|
859
859
|
query getLabelsForRepo($owner: String!, $name: String! $cursor: String, $first: Int!) {
|
|
860
860
|
repository(owner: $owner, name: $name) {
|
|
861
861
|
labels(first: $first, after: $cursor) {
|
|
862
862
|
nodes {
|
|
863
|
-
${
|
|
863
|
+
${Ye}
|
|
864
864
|
}
|
|
865
865
|
pageInfo {
|
|
866
866
|
endCursor
|
|
@@ -869,7 +869,7 @@ query getLabelsForRepo($owner: String!, $name: String! $cursor: String, $first:
|
|
|
869
869
|
}
|
|
870
870
|
}
|
|
871
871
|
}
|
|
872
|
-
`,variables:{owner:n,name:o,cursor:i,first:$}},r);if(!a.body.data)throw new I("Could not fetch labels",a.body.errors);return{pageInfo:a.body.data.repository.labels?.pageInfo??{endCursor:null,hasNextPage:!1},data:a.body.data.repository.labels?.nodes?.map(
|
|
872
|
+
`,variables:{owner:n,name:o,cursor:i,first:$}},r);if(!a.body.data)throw new I("Could not fetch labels",a.body.errors);return{pageInfo:a.body.data.repository.labels?.pageInfo??{endCursor:null,hasNextPage:!1},data:a.body.data.repository.labels?.nodes?.map(sr)??[]}}async getTreeForRepo(e,r={}){let n=await this.config.request({url:`${X(this.config,r)}/repos/${e.repo.namespace}/${e.repo.name}/git/trees/${e.branch}?recursive=1`,headers:{...R(r.token||this.config.token)}});if(!n.body)throw new Error("Could not fetch trees");return{data:n.body.tree.map(go)}}};var wo="https://gitlab.com/api/v4",qo="https://gitlab.com/api/graphql",or=/\/api\/v\d+$/,Cs=s=>{if(s.endsWith("/api/graphql"))throw new Error("The graphql endpoint is being used as the baseUrl. This package uses both GraphQL and REST APIs, and the REST version cannot be assumed. Use the REST endpoint as the baseUrl instead.")},U=(s,t)=>{let e=t.baseUrl||s.baseUrl;return e?(e=e.replace(/\/$/,""),Cs(e),or.test(e)||(e=e+"/api/v4"),e):wo},vo=(s,t)=>{let e=t.baseUrl||s.baseUrl;return e?(e=e.replace(/\/$/,""),Cs(e),or.test(e)&&(e=e.replace(or,"")),`${e}/api/graphql`):qo},E=(s,t,e)=>{let r=R(e.token||s.token);return s.request({url:vo(s,e),method:"POST",headers:{...r,"Content-Type":"application/json"},body:JSON.stringify(t)})},ke=s=>s?.map(t=>`"${t.message}"`).join(", ");var gr=s=>s.split("/").slice(0,-1).join("/"),hr=s=>s.split("/").at(-1)??"",Ds=s=>{let t=parseInt(`${s["x-next-page"]}`,10);return Number.isNaN(t)?{hasNextPage:!1,nextPage:null}:{hasNextPage:!0,nextPage:t}},rt=s=>({id:s.id.replace(Ee,""),graphQLId:s.id,namespace:gr(s.fullPath),name:hr(s.fullPath),webUrl:s.webUrl}),xe=s=>({id:s.id.replace(Ee,""),graphQLId:s.id,httpsUrl:s.httpUrlToRepo,namespace:gr(s.fullPath),name:hr(s.fullPath),sshUrl:s.sshUrlToRepo,webUrl:s.webUrl}),Eo={assigned:"assignedMergeRequests",authored:"authoredMergeRequests",reviewRequested:"reviewRequestedMergeRequests"},So={CAN_BE_MERGED:"MERGEABLE",CANNOT_BE_MERGED:"CONFLICTS",CANNOT_BE_MERGED_RECHECK:"UNKNOWN",UNCHECKED:"UNKNOWN",CHECKING:"UNKNOWN"};var Us="gid://gitlab/User/",Ee="gid://gitlab/Project/",Co="gid://gitlab/MergeRequest/",Do="gid://gitlab/Issue/",Ao="gid://gitlab/ProjectLabel/",$o="gid://gitlab/Milestone/",Lo="gid://gitlab/Ci::Build/",fr=`
|
|
873
873
|
description
|
|
874
874
|
dueDate
|
|
875
875
|
id
|
|
@@ -878,7 +878,7 @@ startDate
|
|
|
878
878
|
state
|
|
879
879
|
title
|
|
880
880
|
webPath
|
|
881
|
-
`,
|
|
881
|
+
`,ir=`
|
|
882
882
|
id
|
|
883
883
|
fullPath
|
|
884
884
|
webUrl
|
|
@@ -892,31 +892,31 @@ userPermissions {
|
|
|
892
892
|
downloadCode
|
|
893
893
|
pushCode
|
|
894
894
|
}
|
|
895
|
-
`,
|
|
895
|
+
`,se=`
|
|
896
896
|
id
|
|
897
897
|
name
|
|
898
898
|
username
|
|
899
899
|
publicEmail
|
|
900
900
|
avatarUrl
|
|
901
901
|
webUrl
|
|
902
|
-
`,
|
|
902
|
+
`,Rr=`
|
|
903
903
|
color
|
|
904
904
|
description
|
|
905
905
|
id
|
|
906
906
|
title
|
|
907
|
-
`,
|
|
907
|
+
`,Ne=`
|
|
908
908
|
id
|
|
909
909
|
httpUrlToRepo
|
|
910
910
|
fullPath
|
|
911
911
|
sshUrlToRepo
|
|
912
912
|
webUrl
|
|
913
|
-
`,
|
|
913
|
+
`,ar=`
|
|
914
914
|
author {
|
|
915
|
-
${
|
|
915
|
+
${se}
|
|
916
916
|
}
|
|
917
917
|
assignees {
|
|
918
918
|
nodes {
|
|
919
|
-
${
|
|
919
|
+
${se}
|
|
920
920
|
}
|
|
921
921
|
}
|
|
922
922
|
closedAt
|
|
@@ -927,7 +927,7 @@ id
|
|
|
927
927
|
iid
|
|
928
928
|
labels {
|
|
929
929
|
nodes {
|
|
930
|
-
${
|
|
930
|
+
${Rr}
|
|
931
931
|
}
|
|
932
932
|
}
|
|
933
933
|
state
|
|
@@ -938,9 +938,9 @@ upvotes
|
|
|
938
938
|
userNotesCount
|
|
939
939
|
webUrl
|
|
940
940
|
milestone {
|
|
941
|
-
${
|
|
941
|
+
${fr}
|
|
942
942
|
}
|
|
943
|
-
`,
|
|
943
|
+
`,Uo=`
|
|
944
944
|
stages {
|
|
945
945
|
nodes {
|
|
946
946
|
jobs {
|
|
@@ -956,11 +956,11 @@ stages {
|
|
|
956
956
|
name
|
|
957
957
|
}
|
|
958
958
|
}
|
|
959
|
-
`,
|
|
959
|
+
`,ur=(s,t,e)=>`
|
|
960
960
|
id
|
|
961
961
|
state
|
|
962
962
|
author {
|
|
963
|
-
${
|
|
963
|
+
${se}
|
|
964
964
|
}
|
|
965
965
|
diffRefs {
|
|
966
966
|
baseSha
|
|
@@ -986,12 +986,12 @@ targetBranch
|
|
|
986
986
|
sourceBranch
|
|
987
987
|
assignees {
|
|
988
988
|
nodes {
|
|
989
|
-
${
|
|
989
|
+
${se}
|
|
990
990
|
}
|
|
991
991
|
}
|
|
992
992
|
reviewers {
|
|
993
993
|
nodes {
|
|
994
|
-
${
|
|
994
|
+
${se}
|
|
995
995
|
mergeRequestInteraction {
|
|
996
996
|
approved
|
|
997
997
|
reviewState
|
|
@@ -1001,25 +1001,25 @@ reviewers {
|
|
|
1001
1001
|
mergeStatusEnum
|
|
1002
1002
|
labels {
|
|
1003
1003
|
nodes {
|
|
1004
|
-
${
|
|
1004
|
+
${Rr}
|
|
1005
1005
|
}
|
|
1006
1006
|
}
|
|
1007
|
-
${s?`project { ${
|
|
1008
|
-
${t?`milestone { ${
|
|
1009
|
-
${e?`headPipeline { ${
|
|
1010
|
-
`,_=s=>`${s.namespace}/${s.name}`,
|
|
1007
|
+
${s?`project { ${Ne} archived } sourceProject { ${Ne} }`:""}
|
|
1008
|
+
${t?`milestone { ${fr} }`:""}
|
|
1009
|
+
${e?`headPipeline { ${Uo} }`:""}
|
|
1010
|
+
`,_=s=>`${s.namespace}/${s.name}`,Go=s=>`${s.namespace}/${s.name}`,To=s=>/Field '[^']+' (?:doesn'?t|does not) exist on type|Field '[^']+' is not defined|undefined field '[^']+' on type/i.test(s.message),Oo=s=>({canCreateWebhook:s.adminOperations,canPush:s.pushCode,isAdmin:s.adminOperations}),lr=s=>({id:s.id.replace(Ee,""),graphQLId:s.id,namespace:gr(s.fullPath),name:hr(s.fullPath),webUrl:s.webUrl,httpsUrl:s.httpUrlToRepo,sshUrl:s.sshUrlToRepo,defaultBranch:s.repository?.rootRef?{name:s.repository.rootRef}:null,permissions:Oo(s.userPermissions)}),_o=s=>({path:s.path,isDirectory:s.type==="tree"}),ko={opened:"OPEN",merged:"MERGED",closed:"CLOSED"},xo={OPEN:"opened",MERGED:"merged",CLOSED:"closed"},As=s=>{if(!s||s.length===0)return"state: opened";let t=Array.from(new Set(s));return t.length>1?"":`state: ${xo[t[0]]}`},$s=s=>{if(!s||s.length===0)return"state: opened";let t=Array.from(new Set(s));return t.length>1?"":`state: ${t[0]==="CLOSED"?"closed":"opened"}`},ue=100,No=20,Bo=250,st=(s,t,e)=>!t&&s?.startsWith("/")?`https://gitlab.com${s}`:t&&s?.startsWith("/")&&e?`${e.replace(/\/+?$/,"")}${s}`:s,ne=(s,t,e)=>{let r=st(s.avatarUrl,t,e);return{id:s.id.replace(Us,""),graphQLId:s.id,name:s.name,username:s.username,email:s.publicEmail??null,avatarUrl:r,url:s.webUrl}},Ir=s=>({color:s.color,description:s.description,id:s.id.replace(Ao,""),graphQLId:s.id,name:s.title}),jo=(s,t)=>s?s==="FAILED"&&t?"WARNING":{CANCELED:"CANCELLED",CREATED:"PENDING",FAILED:"FAILED",MANUAL:"OPTIONAL_ACTION_REQUIRED",PENDING:"PENDING",PREPARING:"RUNNING",RUNNING:"RUNNING",SCHEDULED:"PENDING",SKIPPED:"SKIPPED",SUCCESS:"SUCCESS",WAITING_FOR_CALLBACK:"PENDING",WAITING_FOR_RESOURCE:"PENDING"}[s]:null,Fo=(s,t,e)=>{let r={APPROVED:"APPROVED",REQUESTED_CHANGES:"CHANGES_REQUESTED",REVIEWED:"COMMENTED",UNAPPROVED:"REVIEW_REQUESTED",UNREVIEWED:"REVIEW_REQUESTED"};return{reviewer:ne(s,t,e),state:s.mergeRequestInteraction?.reviewState?r[s.mergeRequestInteraction.reviewState]:"REVIEW_REQUESTED"}},pr=(s,t,e,r,n)=>{let o=s.reviewers?.nodes?s.reviewers.nodes.map(i=>Fo(i,r,n)):null;return{id:s.id.replace(Co,""),graphQLId:s.id,title:s.title,description:s.description,number:parseInt(s.iid,10),state:ko[s.state],commentCount:s.userNotesCount||0,upvoteCount:s.upvotes,author:s.author?ne(s.author,r,n):null,createdDate:new Date(s.createdAt),isDraft:s.draft,repository:{id:t.id,graphQLId:t.graphQLId,name:t.name,owner:{login:t.namespace},remoteInfo:t.httpsUrl&&t.sshUrl?{cloneUrlHTTPS:t.httpsUrl,cloneUrlSSH:t.sshUrl}:null},isCrossRepository:e!=null&&e.id!==t.id,headRepository:e?{id:e.id,graphQLId:e.graphQLId,name:e.name,owner:{login:e.namespace},remoteInfo:{cloneUrlHTTPS:e.httpsUrl,cloneUrlSSH:e.sshUrl}}:null,headCommit:{buildStatuses:s.headPipeline?.stages?.nodes?.flatMap(i=>i.jobs?.nodes?.map(a=>({completedAt:a.finishedAt?new Date(a.finishedAt):null,description:null,name:a.name??null,state:jo(a.status,a.allowFailure),stage:i.name??null,startedAt:new Date(a.createdAt),url:`${t.webUrl}/-/jobs/${a.id.replace(Lo,"")}`}))??[])??[]},baseRef:{name:s.targetBranch,oid:s.diffRefs?.baseSha??null},headRef:{name:s.sourceBranch,oid:s.diffRefs?.headSha??null},url:s.webUrl,updatedDate:new Date(s.updatedAt),closedDate:s.mergedAt?new Date(s.mergedAt):null,mergedDate:s.mergedAt?new Date(s.mergedAt):null,assignees:s.assignees?.nodes?s.assignees.nodes.map(i=>ne(i,r,n)):null,reviews:o,reviewDecision:J(o),additions:s.diffStatsSummary?.additions||0,deletions:s.diffStatsSummary?.deletions||0,fileCount:s.diffStatsSummary?.fileCount||0,commitCount:s.commitCount||0,mergeableState:So[s.mergeStatusEnum],milestone:s.milestone?br(s.milestone,t.webUrl):null,labels:s.labels?.nodes?.map(Ir)??[],permissions:null}},dr=(s,t,e,r)=>({author:ne(s.author,e,r),assignees:s.assignees.nodes.map(n=>ne(n,e,r)),commentCount:s.userNotesCount,closedDate:s.closedAt?new Date(s.closedAt):null,createdDate:new Date(s.createdAt),description:s.description,graphQLId:s.id,id:s.id.replace(Do,""),labels:s.labels?.nodes?.map(Ir)??[],number:s.iid,repository:{id:t.id.replace(Ee,""),graphQLId:t.id,name:t.name,owner:{login:t.namespace}},updatedDate:new Date(s.updatedAt),upvoteCount:s.upvotes,state:{name:s.state,color:null},type:s.type,title:s.title,url:s.webUrl,milestone:s.milestone?br(s.milestone,t.webUrl):null}),br=(s,t)=>({id:s.id.replace($o,""),graphQLId:s.id,number:parseInt(s.iid,10),title:s.title,description:s.description,isOpen:s.state==="active",url:`${t}/-/${s.webPath.replace(/.+?\/-\//,"")}`,startDate:s.startDate?new Date(s.startDate):null,dueDate:s.dueDate?new Date(s.dueDate):null}),Qo=s=>Buffer.from(JSON.stringify(s),"utf8").toString("base64"),zo=(s,t)=>{if(!s)return{page:1,perPage:t};try{let e=JSON.parse(Buffer.from(s,"base64").toString("utf8")),r=typeof e.page=="number"&&e.page>0?e.page:1,n=typeof e.perPage=="number"&&e.perPage>0?e.perPage:t;return{page:r,perPage:n}}catch{return{page:1,perPage:t}}},Mo=(s,t,e)=>({id:s.id.toString(),graphQLId:`${Us}${s.id}`,name:s.name,username:s.username,email:s.email??null,avatarUrl:st(s.avatar_url,t,e),url:s.web_url}),Ls=(s,t,e)=>({avatarUrl:st(s.avatar_url,t,e)??"",email:null,name:s.name}),Wo=s=>s?.new_line!=null?"RIGHT":s?.old_line!=null?"LEFT":null,Ho=s=>{let t=s.old_path||s.new_path,e=s.new_path||s.old_path,r=[`diff --git a/${t} b/${e}`];return s.new_file&&s.b_mode?r.push(`new file mode ${s.b_mode}`):s.deleted_file&&s.a_mode?r.push(`deleted file mode ${s.a_mode}`):s.a_mode&&s.b_mode&&s.a_mode!==s.b_mode&&(r.push(`old mode ${s.a_mode}`),r.push(`new mode ${s.b_mode}`)),s.renamed_file&&(r.push(`rename from ${s.old_path}`),r.push(`rename to ${s.new_path}`)),s.diff&&s.diff.length>0?(r.push(`--- ${s.new_file?"/dev/null":`a/${t}`}`),r.push(`+++ ${s.deleted_file?"/dev/null":`b/${e}`}`),`${r.join(`
|
|
1011
1011
|
`)}
|
|
1012
1012
|
${s.diff.endsWith(`
|
|
1013
1013
|
`)?s.diff:`${s.diff}
|
|
1014
1014
|
`}`):`${r.join(`
|
|
1015
1015
|
`)}
|
|
1016
|
-
`},
|
|
1016
|
+
`},Gs="|",mr=(s,t,e,r)=>[s,t,e.toString(),r.toString()].join(Gs),Vo=s=>{let t=s.split(Gs);if(t.length!==4)throw new Error("Invalid GitLab comment ID format \u2014 expected a composite ID produced by getCommentsForPullRequest or addInlineCommentToPullRequest.");return{namespace:t[0],name:t[1],mergeRequestIid:t[2],noteId:t[3]}},cr=(s,t,e,r)=>({author:s.author?Mo(s.author,t,e):null,body:s.body,createdAt:s.created_at?new Date(s.created_at):null,id:mr(r.namespace,r.name,r.mergeRequestIid,s.id),url:""}),Se=class extends F{getIsSelfHosted(t){return!!t.baseUrl||!!this.config.baseUrl}async getCurrentUser(t={},e={}){let n=(await E(this.config,{query:`
|
|
1017
1017
|
query getCurrentUser {
|
|
1018
1018
|
currentUser {
|
|
1019
|
-
${
|
|
1019
|
+
${se}
|
|
1020
1020
|
}
|
|
1021
1021
|
}
|
|
1022
|
-
`},e)).body.data?.currentUser;if(!n)throw new Error("Current user not found.");return{data:
|
|
1022
|
+
`},e)).body.data?.currentUser;if(!n)throw new Error("Current user not found.");return{data:ne(n,this.getIsSelfHosted(e),this.config.baseUrl??e.baseUrl)}}async getUserForCommit(t,e={}){let r=_(t.repo),o=(await E(this.config,{query:`
|
|
1023
1023
|
query getUserForCommit($fullPath: ID!, $oid: String!) {
|
|
1024
1024
|
project(fullPath: $fullPath) {
|
|
1025
1025
|
repository {
|
|
@@ -1035,21 +1035,21 @@ query getUserForCommit($fullPath: ID!, $oid: String!) {
|
|
|
1035
1035
|
}
|
|
1036
1036
|
}
|
|
1037
1037
|
}
|
|
1038
|
-
`,variables:{fullPath:r,oid:t.oid}},e)).body.data?.project?.repository?.tree?.lastCommit;if(!o)throw new Error("Commit not found.");let i=
|
|
1038
|
+
`,variables:{fullPath:r,oid:t.oid}},e)).body.data?.project?.repository?.tree?.lastCommit;if(!o)throw new Error("Commit not found.");let i=st(o.author.avatarUrl,this.getIsSelfHosted(e),this.config.baseUrl??e.baseUrl);return{data:{name:o.authorName,email:o.authorEmail,avatarUrl:i}}}async getAccountForEmail(t,e={}){let n=(await E(this.config,{query:`
|
|
1039
1039
|
query getAccountForEmail($email: String!) {
|
|
1040
1040
|
users(search: $email) {
|
|
1041
1041
|
nodes {
|
|
1042
|
-
${
|
|
1042
|
+
${se}
|
|
1043
1043
|
}
|
|
1044
1044
|
}
|
|
1045
1045
|
}
|
|
1046
|
-
`,variables:{email:t.email}},e)).body.data?.users?.nodes?.[0];if(!n)throw new Error("User not found.");return{data:
|
|
1046
|
+
`,variables:{email:t.email}},e)).body.data?.users?.nodes?.[0];if(!n)throw new Error("User not found.");return{data:ne(n,this.getIsSelfHosted(e),this.config.baseUrl??e.baseUrl)}}async getAccountForUsername(t,e={}){let n=(await E(this.config,{query:`
|
|
1047
1047
|
query getAccountForUsername($username: String!) {
|
|
1048
1048
|
user(username: $username) {
|
|
1049
|
-
${
|
|
1049
|
+
${se}
|
|
1050
1050
|
}
|
|
1051
1051
|
}
|
|
1052
|
-
`,variables:{username:t.username}},e)).body.data?.user;if(!n)throw new Error("User not found.");return{data:
|
|
1052
|
+
`,variables:{username:t.username}},e)).body.data?.user;if(!n)throw new Error("User not found.");return{data:ne(n,this.getIsSelfHosted(e),this.config.baseUrl??e.baseUrl)}}async getAccountsForRepo(t,e={}){let{repo:{namespace:r,name:n},cursor:o}=t,i=await E(this.config,{query:`
|
|
1053
1053
|
query getAccountsForRepo(
|
|
1054
1054
|
$fullPath: ID!
|
|
1055
1055
|
$after: String
|
|
@@ -1060,7 +1060,7 @@ query getAccountsForRepo(
|
|
|
1060
1060
|
projectMembers(after: $after) {
|
|
1061
1061
|
nodes {
|
|
1062
1062
|
user {
|
|
1063
|
-
${
|
|
1063
|
+
${se}
|
|
1064
1064
|
}
|
|
1065
1065
|
}
|
|
1066
1066
|
pageInfo {
|
|
@@ -1070,22 +1070,22 @@ query getAccountsForRepo(
|
|
|
1070
1070
|
}
|
|
1071
1071
|
}
|
|
1072
1072
|
}
|
|
1073
|
-
`,variables:{fullPath:`${r}/${n}`,after:o}},e),a=i.body.data?.project?.projectMembers?.nodes?.map(u=>u.user).filter(u=>u!==null);return{pageInfo:i.body.data?.project?.projectMembers?.pageInfo??{endCursor:null,hasNextPage:!1},data:a?.map(u=>
|
|
1073
|
+
`,variables:{fullPath:`${r}/${n}`,after:o}},e),a=i.body.data?.project?.projectMembers?.nodes?.map(u=>u.user).filter(u=>u!==null);return{pageInfo:i.body.data?.project?.projectMembers?.pageInfo??{endCursor:null,hasNextPage:!1},data:a?.map(u=>ne(u,this.getIsSelfHosted(e),this.config.baseUrl??e.baseUrl))??[]}}async getRepo(t,e={}){let r=_(t),n=await E(this.config,{query:`
|
|
1074
1074
|
query getRepo($fullPath: ID!) {
|
|
1075
1075
|
project(fullPath: $fullPath) {
|
|
1076
|
-
${
|
|
1076
|
+
${ir}
|
|
1077
1077
|
}
|
|
1078
1078
|
}
|
|
1079
|
-
`,variables:{fullPath:r}},e);if(!n.body.data?.project)throw new Error(`Repository ${r} not found`);return{data:
|
|
1079
|
+
`,variables:{fullPath:r}},e);if(!n.body.data?.project)throw new Error(`Repository ${r} not found`);return{data:lr(n.body.data.project)}}async getReposBase(t,e={}){let n=t.map(_).map((u,l)=>`
|
|
1080
1080
|
getRepo_${l}: project(fullPath: "${u}") {
|
|
1081
|
-
${
|
|
1081
|
+
${ir}
|
|
1082
1082
|
}
|
|
1083
1083
|
`).join(`
|
|
1084
1084
|
`),o=await E(this.config,{query:`
|
|
1085
1085
|
query batchGetRepos {
|
|
1086
1086
|
${n}
|
|
1087
1087
|
}
|
|
1088
|
-
`},e);if(!o.body.data)throw new Error(
|
|
1088
|
+
`},e);if(!o.body.data)throw new Error(ke(o.body.errors)||o.statusText||"Unknown error");let i=[],a=[];return t.forEach((u,l)=>{let d=o.body.data[`getRepo_${l}`];d?i.push(lr(d)):a.push({input:u})}),{data:i,errors:a}}async getRepos(t,e={}){let r=[];for(let i=0;i<t.length;i+=15)r.push(t.slice(i,i+15));return(await Promise.all(r.map(i=>this.getReposBase(i,e)))).reduce((i,a)=>({data:[...i.data,...a.data],errors:[...i.errors,...a.errors]}),{data:[],errors:[]})}async getReposForCurrentUser(t,e={}){let r=await E(this.config,{query:`
|
|
1089
1089
|
query getReposForCurrentUser($after: String) {
|
|
1090
1090
|
projects(membership: true first: 100 after: $after) {
|
|
1091
1091
|
pageInfo {
|
|
@@ -1093,11 +1093,11 @@ query getReposForCurrentUser($after: String) {
|
|
|
1093
1093
|
hasNextPage
|
|
1094
1094
|
}
|
|
1095
1095
|
nodes {
|
|
1096
|
-
${
|
|
1096
|
+
${ir}
|
|
1097
1097
|
}
|
|
1098
1098
|
}
|
|
1099
1099
|
}
|
|
1100
|
-
`,variables:{after:t.cursor}},e);if(!r.body.data?.projects)throw new Error(
|
|
1100
|
+
`,variables:{after:t.cursor}},e);if(!r.body.data?.projects)throw new Error(ke(r.body.errors)||r.statusText||"Unknown error");let n=r.body.data?.projects?.nodes||[];return{pageInfo:r.body.data?.projects?.pageInfo,data:n.map(lr)}}async getGroupsForCurrentUser(t={},e={}){let r=new URL(`${U(this.config,e)}/groups`);r.searchParams.set("top_level_only",(t.topLevelOnly??!0).toString()),r.searchParams.set("page",t.page?.toString()||"1"),r.searchParams.set("per_page",$.toString());let n=await this.config.request({url:r.toString(),headers:R(e.token||this.config.token)});return{pageInfo:Ds(n.headers),data:n.body.map(o=>({id:o.id.toString(),path:o.path,fullPath:o.full_path,name:o.name,webUrl:o.web_url}))}}async getRefs(t,e,r={}){let n=_(e.repo),o=new URL(`${U(this.config,r)}/projects/${encodeURIComponent(n)}/repository/${t}`);o.searchParams.set("page",e.page?.toString()||"1"),o.searchParams.set("per_page",$.toString());let i=await this.config.request({url:o.toString(),headers:R(r.token||this.config.token)});return{pageInfo:Ds(i.headers),data:i.body.map(a=>({name:a.name,commit:{oid:a.commit.id,authoredDate:new Date(a.commit.authored_date),committedDate:new Date(a.commit.committed_date)}}))}}async getBranches(t,e={}){return this.getRefs("branches",t,e)}async getTags(t,e={}){return this.getRefs("tags",t,e)}async getBlame(t,e={}){let r=_(t.repo),n=new URL(`${U(this.config,e)}/projects/${encodeURIComponent(r)}/repository/files/${encodeURIComponent(t.path)}/blame`);n.searchParams.set("ref",t.ref);let o=await this.config.request({url:n.toString(),headers:R(e.token||this.config.token)}),i=0;return{data:{ranges:o.body.map(a=>{let u=i+1;return i+=a.lines.length,{startingLine:u,endingLine:i,commit:{oid:a.commit.id,parentOids:a.commit.parent_ids,authoredDate:new Date(a.commit.authored_date),author:{name:a.commit.author_name,email:a.commit.author_email,avatarUrl:null},committedDate:new Date(a.commit.committed_date),committer:{name:a.commit.committer_name,email:a.commit.committer_email,avatarUrl:null},message:a.commit.message,fileCount:null,additions:null,deletions:null}}})}}}async getPullRequestsForUser(t,e={}){let r="";t.repo?.id?r=`projectId:"${t.repo.id}"`:t.repo?.namespace&&t.repo?.name&&(r=`projectPath:"${t.repo.namespace}/${t.repo.name}"`);let n=Eo[t.association],o=As(t.states),i=L(t.pageSize,{fallback:ue,max:ue}),a=await E(this.config,{query:`
|
|
1101
1101
|
query getPullRequestsForUser($username: String! $cursor: String $labelNames: [String!]) {
|
|
1102
1102
|
user(username: $username) {
|
|
1103
1103
|
${n}(${o} first: ${i} after:$cursor labels: $labelNames${r?` ${r}`:""}) {
|
|
@@ -1106,16 +1106,16 @@ query getPullRequestsForUser($username: String! $cursor: String $labelNames: [St
|
|
|
1106
1106
|
hasNextPage
|
|
1107
1107
|
}
|
|
1108
1108
|
nodes {
|
|
1109
|
-
${
|
|
1109
|
+
${ur(!0,!0,!0)}
|
|
1110
1110
|
}
|
|
1111
1111
|
}
|
|
1112
1112
|
}
|
|
1113
1113
|
}
|
|
1114
|
-
`,variables:{username:t.username,cursor:t.cursor,labelNames:t.labelNames}},e);if(!a.body.data)throw new Error(
|
|
1114
|
+
`,variables:{username:t.username,cursor:t.cursor,labelNames:t.labelNames}},e);if(!a.body.data)throw new Error(ke(a.body.errors)||a.statusText||"Unknown error");if(!a.body.data.user)throw new Error("User not found");let u=a.body.data.user[n];if(!u)throw new Error("Unexpected response");let l=u.nodes?.filter(d=>t.includeFromArchivedRepos||!d.project.archived).map(d=>pr(d,xe(d.project),d.sourceProject?xe(d.sourceProject):null,this.getIsSelfHosted(e),this.config.baseUrl??e.baseUrl))||[];return{pageInfo:u.pageInfo,data:x(l,t.states)}}async getPullRequestsAssociatedWithUser(t,e={}){let[r,n,o]=t.cursor?.split(";")||[void 0,void 0,void 0],i=r?.split("-")||[],a=n?.split("-")||[],u=o?.split("-")||[],l=[],d=[],p=[],c=0;do{let D=t.repos&&t.repos[c];i[c]==="null"?l.push(null):l.push(this.getPullRequestsForUser({username:t.username,association:"authored",cursor:i[c],includeFromArchivedRepos:t.includeFromArchivedRepos,labelNames:t.labelNames,...D&&{repo:D}},e)),a[c]==="null"?d.push(null):d.push(this.getPullRequestsForUser({username:t.username,association:"assigned",cursor:a[c],includeFromArchivedRepos:t.includeFromArchivedRepos,labelNames:t.labelNames,...D&&{repo:D}},e)),u[c]==="null"?p.push(null):p.push(this.getPullRequestsForUser({username:t.username,association:"reviewRequested",cursor:u[c],includeFromArchivedRepos:t.includeFromArchivedRepos,labelNames:t.labelNames,...D&&{repo:D}},e)),c++}while(c<(t.repos?.length||0));let g=[l,d,p].flat(),m=await Promise.all(g),h={},y=[],f=D=>{h[D.id]||(h[D.id]=!0,y.push(D))},P=!1,A=m.map((D,w)=>{let S="";return D&&D.data.forEach(f),D?.pageInfo.hasNextPage?(P=!0,S+=`${D.pageInfo.endCursor||"null"}`):S+="null",t.repos?.length&&(w+1)%t.repos.length!==0?S+="-":w+1<m.length&&(S+=";"),S}).join("");return{pageInfo:{hasNextPage:P,endCursor:A},data:y}}getVariablesForPullRequests(t){let{updatedBefore:e,isDraft:r,authorLogin:n,assigneeLogins:o,labelNames:i,reviewRequestedLogin:a}=t||{},u={},l=[],d=[],p=(c,g,m)=>{l.push(`$${c}: ${m}`),d.push(`${c}: $${c}`),u[c]=g};return e&&p("updatedBefore",e,"Time"),n&&p("authorUsername",n,"String"),o&&o.length&&(o.length===1?p("assigneeUsername",o[0],"String"):p("assigneeUsernames",o,"[String!]")),i&&p("labelName",i,"[String]"),r!=null&&p("draft",r,"Boolean"),a&&p("reviewerUsername",a,"String"),{variables:u,variableTypes:l,mergeRequestArguments:d}}async getPullRequestsForRepoBase(t,e={},r){let{cursor:n,repo:o}=t||{},i=_(o),a=As(t.states),u=L(t.pageSize,{fallback:ue,max:ue}),{variables:l,variableTypes:d,mergeRequestArguments:p}=this.getVariablesForPullRequests(t),c={fullPath:i,...l},g=await E(this.config,{query:`
|
|
1115
1115
|
query getPullRequestsForRepo(
|
|
1116
1116
|
$fullPath: ID!
|
|
1117
1117
|
$after: String
|
|
1118
|
-
${
|
|
1118
|
+
${d.length?d.join(" "):""}
|
|
1119
1119
|
) {
|
|
1120
1120
|
project(
|
|
1121
1121
|
fullPath: $fullPath
|
|
@@ -1129,22 +1129,22 @@ query getPullRequestsForRepo(
|
|
|
1129
1129
|
${a}
|
|
1130
1130
|
sort: UPDATED_DESC
|
|
1131
1131
|
after: $after
|
|
1132
|
-
${
|
|
1132
|
+
${p.length?p.join(" "):""}
|
|
1133
1133
|
) {
|
|
1134
1134
|
pageInfo {
|
|
1135
1135
|
endCursor
|
|
1136
1136
|
hasNextPage
|
|
1137
1137
|
}
|
|
1138
1138
|
nodes {
|
|
1139
|
-
${
|
|
1139
|
+
${ur(!1,!0,!0)}
|
|
1140
1140
|
sourceProject {
|
|
1141
|
-
${
|
|
1141
|
+
${Ne}
|
|
1142
1142
|
}
|
|
1143
1143
|
}
|
|
1144
1144
|
}
|
|
1145
1145
|
}
|
|
1146
1146
|
}
|
|
1147
|
-
`,variables:{...c,after:n}},e),m=[],h=g.body.data?.project;if(!r&&h?.archived)return{pageInfo:null,data:[]};let y=
|
|
1147
|
+
`,variables:{...c,after:n}},e),m=[],h=g.body.data?.project;if(!r&&h?.archived)return{pageInfo:null,data:[]};let y=rt(h||{id:"",fullPath:"",webUrl:""});return(h?.mergeRequests?.nodes||[]).forEach(P=>{let v=P.sourceProject?xe(P.sourceProject):null;m.push(pr(P,y,v,this.getIsSelfHosted(e),this.config.baseUrl??e.baseUrl))}),{pageInfo:h?.mergeRequests?.pageInfo,data:x(m,t.states)}}async getPullRequestsForRepo(t,e={}){return this.getPullRequestsForRepoBase(t,e,!1)}async getPullRequestsForRepos(t,e={}){let{repos:r,assigneeLogins:n,updatedBefore:o,authorLogin:i,labelNames:a,isDraft:u,reviewRequestedLogin:l}=t;return{data:(await Promise.all(r.map(p=>this.getPullRequestsForRepoBase({repo:p,assigneeLogins:n,updatedBefore:o,authorLogin:i,labelNames:a,isDraft:u,reviewRequestedLogin:l,states:t.states,pageSize:t.pageSize},e,t.includeFromArchivedRepos??!1)))).flatMap(p=>p.data)}}async closePullRequest(t,e={}){let{pullRequest:r}=t,n=`mutation ClosePullRequest($fullPath: ID!, $pullRequestId: String!) {
|
|
1148
1148
|
mergeRequestUpdate(input: { projectPath: $fullPath, iid: $pullRequestId, state: CLOSED }) {
|
|
1149
1149
|
errors,
|
|
1150
1150
|
mergeRequest {
|
|
@@ -1209,18 +1209,18 @@ query getPullRequestsForRepo(
|
|
|
1209
1209
|
id
|
|
1210
1210
|
}
|
|
1211
1211
|
}
|
|
1212
|
-
}`;if(!(await E(this.config,{query:i,variables:{fullPath:`${r.repository.owner.login}/${r.repository.name}`,pullRequestId:r.number.toString(),labelGraphQLIds:o}},e)).body.data?.mergeRequestSetLabels?.mergeRequest?.id)throw new Error("Could not set pull request labels")}async getIssue(t,e={}){let r=
|
|
1212
|
+
}`;if(!(await E(this.config,{query:i,variables:{fullPath:`${r.repository.owner.login}/${r.repository.name}`,pullRequestId:r.number.toString(),labelGraphQLIds:o}},e)).body.data?.mergeRequestSetLabels?.mergeRequest?.id)throw new Error("Could not set pull request labels")}async getIssue(t,e={}){let r=Go(t),n=await E(this.config,{query:`
|
|
1213
1213
|
query GetSingleIssue($projectId: ID!, $issueNumber: String!) {
|
|
1214
1214
|
project(fullPath: $projectId) {
|
|
1215
1215
|
id
|
|
1216
1216
|
fullPath
|
|
1217
1217
|
webUrl
|
|
1218
1218
|
issue(iid: $issueNumber) {
|
|
1219
|
-
${
|
|
1219
|
+
${ar}
|
|
1220
1220
|
}
|
|
1221
1221
|
}
|
|
1222
1222
|
}
|
|
1223
|
-
`,variables:{issueNumber:t.number,projectId:r}},e);if(!n.body.data?.project)throw new Error(`Repository ${r} not found`);if(!n.body.data?.project?.issue)throw new Error(`Issue ${t.number} not found`);return{data:
|
|
1223
|
+
`,variables:{issueNumber:t.number,projectId:r}},e);if(!n.body.data?.project)throw new Error(`Repository ${r} not found`);if(!n.body.data?.project?.issue)throw new Error(`Issue ${t.number} not found`);return{data:dr(n.body.data.project.issue,rt(n.body.data.project),this.getIsSelfHosted(e),this.config.baseUrl??e.baseUrl)}}getVariablesForIssues(t){let{updatedBefore:e,authorLogin:r,assigneeLogins:n,labelNames:o}=t||{},i={},a=[],u=[],l=(d,p,c)=>{a.push(`$${d}: ${c}`),u.push(`${d}: $${d}`),i[d]=p};return e&&l("updatedBefore",e,"Time"),r&&l("authorUsername",r,"String"),n&&n.length&&(n.length===1?l("assigneeUsername",n[0],"String"):l("assigneeUsernames",n,"[String!]")),o&&l("labelName",o,"[String]"),{variables:i,variableTypes:a,issueArguments:u}}async getIssuesForRepo(t,e={}){let{cursor:r,repo:n}=t||{},o=_(n),i=$s(t.states),a=L(t.pageSize,{fallback:ue,max:ue}),{variables:u,variableTypes:l,issueArguments:d}=this.getVariablesForIssues(t),p={fullPath:o,...u},c=`
|
|
1224
1224
|
query GetIssuesFromProject(
|
|
1225
1225
|
$fullPath: ID!
|
|
1226
1226
|
$after: String
|
|
@@ -1237,10 +1237,10 @@ query GetSingleIssue($projectId: ID!, $issueNumber: String!) {
|
|
|
1237
1237
|
${i}
|
|
1238
1238
|
sort: UPDATED_DESC
|
|
1239
1239
|
after: $after
|
|
1240
|
-
${
|
|
1240
|
+
${d.length?d.join(" "):""}
|
|
1241
1241
|
) {
|
|
1242
1242
|
nodes {
|
|
1243
|
-
${
|
|
1243
|
+
${ar}
|
|
1244
1244
|
}
|
|
1245
1245
|
pageInfo {
|
|
1246
1246
|
endCursor
|
|
@@ -1248,7 +1248,7 @@ query GetSingleIssue($projectId: ID!, $issueNumber: String!) {
|
|
|
1248
1248
|
}
|
|
1249
1249
|
}
|
|
1250
1250
|
}
|
|
1251
|
-
}`,g=await E(this.config,{query:c,variables:{...
|
|
1251
|
+
}`,g=await E(this.config,{query:c,variables:{...p,after:r}},e),m=[],h=g.body.data?.project,y=rt(h||{id:"",fullPath:"",webUrl:""});return(h?.issues?.nodes||[]).forEach(P=>{m.push(dr(P,y,this.getIsSelfHosted(e),this.config.baseUrl??e.baseUrl))}),{pageInfo:h?.issues?.pageInfo??{endCursor:null,hasNextPage:!1},data:m.sort((P,v)=>(P.updatedDate||P.createdDate).getTime()-(v.updatedDate||v.createdDate).getTime())}}async getIssuesForRepos(t,e={}){let{cursor:r}=t||{},n=$s(t.states),o=L(t.pageSize,{fallback:ue,max:ue}),i=t.repoIds.map(h=>h.toString().startsWith(Ee)?h:`${Ee}${h}`),{variables:a,variableTypes:u,issueArguments:l}=this.getVariablesForIssues(t),d={projectIds:i,...a},p=`
|
|
1252
1252
|
query GetIssuesFromProject(
|
|
1253
1253
|
$projectIds: [ID!]
|
|
1254
1254
|
$after: String
|
|
@@ -1274,12 +1274,12 @@ query GetSingleIssue($projectId: ID!, $issueNumber: String!) {
|
|
|
1274
1274
|
${l.length?l.join(" "):""}
|
|
1275
1275
|
) {
|
|
1276
1276
|
nodes {
|
|
1277
|
-
${
|
|
1277
|
+
${ar}
|
|
1278
1278
|
}
|
|
1279
1279
|
}
|
|
1280
1280
|
}
|
|
1281
1281
|
}
|
|
1282
|
-
}`,c=await E(this.config,{query:
|
|
1282
|
+
}`,c=await E(this.config,{query:p,variables:{...d,after:r}},e),g=[];return(c.body.data?.projects?.nodes||[]).forEach(h=>{if(!t.includeFromArchivedRepos&&h.archived)return;let y=rt(h);(h.issues?.nodes||[]).forEach(P=>g.push(dr(P,y,this.getIsSelfHosted(e),this.config.baseUrl??e.baseUrl)))}),{pageInfo:c.body?.data?.projects?.pageInfo??{endCursor:null,hasNextPage:!1},data:g.sort((h,y)=>(h.updatedDate||h.createdDate).getTime()-(y.updatedDate||y.createdDate).getTime())}}async setIssueState(t,e={}){let{issue:r,state:n}=t;if(!r.repository)throw new Error('GitLab requires "repository" for this function.');let o=`mutation SetIssueState($fullPath: ID!, $issueId: String!, $status: IssueStateEvent!) {
|
|
1283
1283
|
updateIssue(input: { projectPath: $fullPath, iid: $issueId, stateEvent: $status }) {
|
|
1284
1284
|
issue {
|
|
1285
1285
|
id
|
|
@@ -1319,7 +1319,7 @@ query getLabelsForRepo(
|
|
|
1319
1319
|
webUrl
|
|
1320
1320
|
milestones(after: $after) {
|
|
1321
1321
|
nodes {
|
|
1322
|
-
${
|
|
1322
|
+
${fr}
|
|
1323
1323
|
}
|
|
1324
1324
|
pageInfo {
|
|
1325
1325
|
endCursor
|
|
@@ -1328,7 +1328,7 @@ query getLabelsForRepo(
|
|
|
1328
1328
|
}
|
|
1329
1329
|
}
|
|
1330
1330
|
}
|
|
1331
|
-
`,variables:{fullPath:`${r}/${n}`,after:o}},e);return{pageInfo:i.body.data?.project?.milestones?.pageInfo??{endCursor:null,hasNextPage:!1},data:i.body.data?.project?.milestones?.nodes?.map(a=>
|
|
1331
|
+
`,variables:{fullPath:`${r}/${n}`,after:o}},e);return{pageInfo:i.body.data?.project?.milestones?.pageInfo??{endCursor:null,hasNextPage:!1},data:i.body.data?.project?.milestones?.nodes?.map(a=>br(a,i.body.data?.project?.webUrl||""))??[]}}async getLabelsForRepo(t,e={}){let{repo:{namespace:r,name:n},cursor:o}=t,i=await E(this.config,{query:`
|
|
1332
1332
|
query getLabelsForRepo(
|
|
1333
1333
|
$fullPath: ID!
|
|
1334
1334
|
$after: String
|
|
@@ -1338,7 +1338,7 @@ query getLabelsForRepo(
|
|
|
1338
1338
|
) {
|
|
1339
1339
|
labels(after: $after) {
|
|
1340
1340
|
nodes {
|
|
1341
|
-
${
|
|
1341
|
+
${Rr}
|
|
1342
1342
|
}
|
|
1343
1343
|
pageInfo {
|
|
1344
1344
|
endCursor
|
|
@@ -1347,28 +1347,28 @@ query getLabelsForRepo(
|
|
|
1347
1347
|
}
|
|
1348
1348
|
}
|
|
1349
1349
|
}
|
|
1350
|
-
`,variables:{fullPath:`${r}/${n}`,after:o}},e);return{pageInfo:i.body.data?.project?.labels?.pageInfo??{endCursor:null,hasNextPage:!1},data:i.body.data?.project?.labels?.nodes?.map(
|
|
1350
|
+
`,variables:{fullPath:`${r}/${n}`,after:o}},e);return{pageInfo:i.body.data?.project?.labels?.pageInfo??{endCursor:null,hasNextPage:!1},data:i.body.data?.project?.labels?.nodes?.map(Ir)??[]}}async getTreeForRepo(t,e={}){let r=_(t.repo),n=new URL(t.cursor??`${U(this.config,e)}/projects/${encodeURIComponent(r)}/repository/tree`);n.searchParams.set("per_page","10000"),n.searchParams.set("recursive","true"),n.searchParams.set("pagination","keyset"),n.searchParams.set("ref",t.branch);let o=await this.config.request({url:n.toString(),headers:R(e.token||this.config.token)}),i=o.headers.link;return{data:o.body.map(_o),pageInfo:{endCursor:i?i.substring(1,i.indexOf(">")):null,hasNextPage:!!i}}}async getPullRequestForRepo(t,e={}){let r=_(t.repo),o=(await E(this.config,{query:`
|
|
1351
1351
|
query getPullRequestForRepo($fullPath: ID!, $iid: String!) {
|
|
1352
1352
|
project(fullPath: $fullPath) {
|
|
1353
|
-
${
|
|
1353
|
+
${Ne}
|
|
1354
1354
|
archived
|
|
1355
1355
|
mergeRequest(iid: $iid) {
|
|
1356
|
-
${
|
|
1356
|
+
${ur(!1,!0,!0)}
|
|
1357
1357
|
sourceProject {
|
|
1358
|
-
${
|
|
1358
|
+
${Ne}
|
|
1359
1359
|
}
|
|
1360
1360
|
}
|
|
1361
1361
|
}
|
|
1362
1362
|
}
|
|
1363
|
-
`,variables:{fullPath:r,iid:t.number.toString()}},e)).body.data?.project,i=o?.mergeRequest;if(!o||!i)return{data:null};let a=Te(o),u=i.sourceProject?Te(i.sourceProject):null;return{data:ar(i,a,u,this.getIsSelfHosted(e),this.config.baseUrl??e.baseUrl)}}getMergeRequestUrl(t,e,r){let n=_(t);return`${G(this.config,r)}/projects/${encodeURIComponent(n)}/merge_requests/${e}`}async getPullRequestDescription(t,e={}){try{return{data:{description:(await this.config.request({url:this.getMergeRequestUrl(t.repo,t.number,e),headers:R(e.token||this.config.token)})).body?.description??""}}}catch{return{data:{description:null}}}}async setPullRequestDescription(t,e={}){return{data:{description:(await this.config.request({method:"PUT",url:this.getMergeRequestUrl(t.repo,t.number,e),headers:{...R(e.token||this.config.token),"Content-Type":"application/json"},body:JSON.stringify({description:t.description})})).body?.description??t.description}}}async getFileContents(t,e={}){let r=_(t.repo),n=new URL(`${G(this.config,e)}/projects/${encodeURIComponent(r)}/repository/files/${encodeURIComponent(t.path)}/raw`);n.searchParams.set("ref",t.ref);let o=await this.config.request({url:n.toString(),headers:R(e.token||this.config.token)});return{data:new Blob([o.body])}}async getCommentsForPullRequest(t,e={}){let r=_(t.repo),{page:n,perPage:o}=Go(t.cursor,$),i=new URL(`${G(this.config,e)}/projects/${encodeURIComponent(r)}/merge_requests/${t.pullRequestNumber}/notes`);i.searchParams.set("page",n.toString()),i.searchParams.set("per_page",o.toString()),i.searchParams.set("sort","asc"),i.searchParams.set("order_by","created_at");let a=await this.config.request({url:i.toString(),headers:R(e.token||this.config.token)}),u=this.getIsSelfHosted(e),l=this.config.baseUrl??e.baseUrl,p={namespace:t.repo.namespace,name:t.repo.name,mergeRequestIid:t.pullRequestNumber},d=a.body.filter(m=>!m.system&&!m.position).map(m=>lr(m,u,l,p)),c=!!a.headers["x-next-page"],g=c?Lo({page:n+1,perPage:o}):null;return{data:d,pageInfo:{endCursor:g,hasNextPage:c}}}async getReviewsForPullRequest(t,e={}){let r=_(t.repo),n=this.getIsSelfHosted(e),o=this.config.baseUrl??e.baseUrl,i=R(e.token||this.config.token),a=G(this.config,e),u=encodeURIComponent(r),[l,p]=await Promise.all([this.config.request({url:`${a}/projects/${u}/merge_requests/${t.pullRequestId}/approvals`,headers:i}),this.fetchAllMergeRequestDiscussions(r,t.pullRequestId,e)]),d=(l.body.approved_by??[]).map(m=>m?.user).filter(m=>!!m).map(m=>{let h=Es(m,n,o),y=`approval-${m.id}`;return{author:h,body:"",createdAt:l.body.updated_at?new Date(l.body.updated_at):null,id:y,graphQLId:y,reviewComments:[],url:l.body.web_url??""}}),c={namespace:t.repo.namespace,name:t.repo.name,mergeRequestIid:t.pullRequestId},g=p.filter(m=>m.notes.some(h=>!h.system&&!!h.position)).map(m=>{let h=m.notes.filter(w=>!w.system),f=h.filter(w=>!!w.position)[0];if(!f)return null;let P=h.filter(w=>w.id!==f.id).map(w=>lr(w,n,o,c)),A={...lr(f,n,o,c),diffLines:[],filename:f.position?.new_path??f.position?.old_path??"",line:f.position?.new_line??f.position?.old_line??null,startLine:f.position?.line_range?.start?.new_line??null,side:To(f.position),isOutdated:!1,isResolved:!!m.resolved,threadId:m.id,replies:P};return{author:f.author?Es(f.author,n,o):null,body:f.body??"",createdAt:f.created_at?new Date(f.created_at):null,id:m.id,graphQLId:m.id,reviewComments:[A],url:""}}).filter(m=>m!==null);return{data:[...d,...g]}}async getPullRequestDiff(t,e={}){let r=_(t.repo),n=encodeURIComponent(r),o=G(this.config,e);return(await this.fetchAllPagedGitLabREST(`${o}/projects/${n}/merge_requests/${t.pullRequestId}/diffs`,e,{perPage:Co,maxPages:Do})).map(Oo).join("")}async getMergeBase(t,e={}){let r=_(t.repo),n=new URL(`${G(this.config,e)}/projects/${encodeURIComponent(r)}/repository/merge_base`);n.searchParams.append("refs[]",t.base),n.searchParams.append("refs[]",t.head);let i=(await this.config.request({url:n.toString(),headers:R(e.token||this.config.token)})).body?.id;if(!i)throw new Error("No merge base found between the specified commits.");return{data:i}}async fetchAllMergeRequestDiscussions(t,e,r){let n=G(this.config,r),o=encodeURIComponent(t);return this.fetchAllPagedGitLabREST(`${n}/projects/${o}/merge_requests/${e}/discussions`,r)}async fetchAllPagedGitLabREST(t,e,{perPage:r=$,maxPages:n=50}={}){let o=R(e.token||this.config.token),i=[],a=1;for(;a<=n;){let u=new URL(t);u.searchParams.set("page",a.toString()),u.searchParams.set("per_page",r.toString());let l=await this.config.request({url:u.toString(),headers:o});i.push(...l.body);let p=l.headers["x-next-page"];if(!p)break;let d=parseInt(`${p}`,10);if(Number.isNaN(d)||d<=a)break;a=d}return i}async addCommentToPullRequest(t,e={}){let{pullRequest:r,comment:n}=t;if(!n||n.trim()==="")throw new Error("GitLab requires a comment when adding a comment to a pull request.");let o=`${r.repository.owner.login}/${r.repository.name}`,i=`${G(this.config,e)}/projects/${encodeURIComponent(o)}/merge_requests/${r.number}/notes`;if(!(await this.config.request({method:"POST",url:i,headers:{...R(e.token||this.config.token),"Content-Type":"application/json"},body:JSON.stringify({body:n})})).body?.id)throw new Error("Could not add comment to pull request")}async addInlineCommentToPullRequest(t,e={}){let{pullRequest:r,comment:n,path:o,line:i,side:a="RIGHT",threadId:u}=t;if(!n?.trim())throw new Error("GitLab requires a comment when adding an inline comment to a pull request.");let l=`${r.repository.owner.login}/${r.repository.name}`,p=encodeURIComponent(l),d=G(this.config,e),c={...R(e.token||this.config.token),"Content-Type":"application/json"};if(u){let P=await this.config.request({method:"POST",url:`${d}/projects/${p}/merge_requests/${r.number}/discussions/${encodeURIComponent(u)}/notes`,headers:c,body:JSON.stringify({body:n})});return P.body?.id!=null?pr(r.repository.owner.login,r.repository.name,r.number,P.body.id):void 0}if(!o?.trim())throw new Error("GitLab requires a file path when adding an inline comment to a pull request.");if(!Number.isInteger(i)||i<1)throw new Error("GitLab requires a positive line number when adding an inline comment to a pull request.");if(a!=="LEFT"&&a!=="RIGHT")throw new Error('GitLab requires side to be either "LEFT" or "RIGHT".');let m=(await this.config.request({url:`${d}/projects/${p}/merge_requests/${r.number}`,headers:R(e.token||this.config.token)})).body?.diff_refs;if(!m?.base_sha||!m?.start_sha||!m?.head_sha)throw new Error("Could not resolve merge request diff refs required to create an inline comment");let h={position_type:"text",base_sha:m.base_sha,start_sha:m.start_sha,head_sha:m.head_sha,new_path:o,old_path:o};a==="RIGHT"?h.new_line=i:h.old_line=i;let f=(await this.config.request({method:"POST",url:`${d}/projects/${p}/merge_requests/${r.number}/discussions`,headers:c,body:JSON.stringify({body:n,position:h})})).body?.notes?.[0]?.id;return f!=null?pr(r.repository.owner.login,r.repository.name,r.number,f):void 0}getNoteUrl(t,e){if(!t)throw new Error('GitLab requires "commentId" for this function.');let{namespace:r,name:n,mergeRequestIid:o,noteId:i}=_o(t);return`${G(this.config,e)}/projects/${encodeURIComponent(`${r}/${n}`)}/merge_requests/${o}/notes/${i}`}async deleteNote(t,e){await this.config.request({method:"DELETE",url:this.getNoteUrl(t,e),headers:R(e.token||this.config.token)})}async deleteComment(t,e={}){await this.deleteNote(t.commentId,e)}async deleteInlineComment(t,e={}){await this.deleteNote(t.commentId,e)}async editNote(t,e,r){if(!e?.trim())throw new Error("GitLab requires a body when editing a comment.");if(!(await this.config.request({method:"PUT",url:this.getNoteUrl(t,r),headers:{...R(r.token||this.config.token),"Content-Type":"application/json"},body:JSON.stringify({body:e})})).body?.id)throw new Error("Could not edit comment")}async editComment(t,e={}){await this.editNote(t.commentId,t.body,e)}async editInlineComment(t,e={}){await this.editNote(t.commentId,t.body,e)}async resolveReviewThread(t,e={}){await this.setReviewThreadResolved(t,!0,e)}async unresolveReviewThread(t,e={}){await this.setReviewThreadResolved(t,!1,e)}async setReviewThreadResolved(t,e,r){if(!t.repo||t.pullRequestNumber==null)throw new Error("GitLab requires input.repo and input.pullRequestNumber to locate the discussion to (un)resolve.");if(!t.threadId)throw new Error("GitLab requires input.threadId to (un)resolve a discussion.");let n=_(t.repo),o=new URL(`${G(this.config,r)}/projects/${encodeURIComponent(n)}/merge_requests/${t.pullRequestNumber}/discussions/${encodeURIComponent(t.threadId)}`);o.searchParams.set("resolved",e?"true":"false"),await this.config.request({url:o.toString(),method:"PUT",headers:R(r.token||this.config.token)})}async approvePullRequest(t,e={}){let{pullRequest:r,comment:n}=t,o=`${r.repository.owner.login}/${r.repository.name}`,i=G(this.config,e),a=encodeURIComponent(o),u=R(e.token||this.config.token);await this.config.request({url:`${i}/projects/${a}/merge_requests/${r.number}/approve`,method:"POST",headers:u}),n&&n.trim()!==""&&await this.postMergeRequestNote(o,r.number,n,e)}async commentOnPullRequest(t,e={}){let{pullRequest:r,comment:n}=t;if(!n||n.trim()==="")throw new Error("GitLab requires a comment when commenting on a pull request.");let o=`${r.repository.owner.login}/${r.repository.name}`;await this.postMergeRequestNote(o,r.number,n,e)}async requestPullRequestChanges(t,e={}){let{pullRequest:r,comment:n}=t;if(!n||n.trim()==="")throw new Error("GitLab requires a comment when requesting changes on a pull request.");let o=`${r.repository.owner.login}/${r.repository.name}`;if(!await this.tryRequestChangesMutation(o,r.number,e)){let u=`${G(this.config,e)}/projects/${encodeURIComponent(o)}/merge_requests/${r.number}`,l=R(e.token||this.config.token);(await this.config.request({url:`${u}/approvals`,method:"GET",headers:l})).body?.user_has_approved&&await this.config.request({url:`${u}/unapprove`,method:"POST",headers:l})}await this.postMergeRequestNote(o,r.number,n,e)}async tryRequestChangesMutation(t,e,r){let n=`mutation MergeRequestRequestChanges($fullPath: ID!, $pullRequestId: String!) {
|
|
1363
|
+
`,variables:{fullPath:r,iid:t.number.toString()}},e)).body.data?.project,i=o?.mergeRequest;if(!o||!i)return{data:null};let a=xe(o),u=i.sourceProject?xe(i.sourceProject):null;return{data:pr(i,a,u,this.getIsSelfHosted(e),this.config.baseUrl??e.baseUrl)}}getMergeRequestUrl(t,e,r){let n=_(t);return`${U(this.config,r)}/projects/${encodeURIComponent(n)}/merge_requests/${e}`}async getPullRequestDescription(t,e={}){try{return{data:{description:(await this.config.request({url:this.getMergeRequestUrl(t.repo,t.number,e),headers:R(e.token||this.config.token)})).body?.description??""}}}catch{return{data:{description:null}}}}async setPullRequestDescription(t,e={}){return{data:{description:(await this.config.request({method:"PUT",url:this.getMergeRequestUrl(t.repo,t.number,e),headers:{...R(e.token||this.config.token),"Content-Type":"application/json"},body:JSON.stringify({description:t.description})})).body?.description??t.description}}}async getFileContents(t,e={}){let r=_(t.repo),n=new URL(`${U(this.config,e)}/projects/${encodeURIComponent(r)}/repository/files/${encodeURIComponent(t.path)}/raw`);n.searchParams.set("ref",t.ref);let o=await this.config.request({url:n.toString(),headers:R(e.token||this.config.token)});return{data:new Blob([o.body])}}async getCommentsForPullRequest(t,e={}){let r=_(t.repo),{page:n,perPage:o}=zo(t.cursor,$),i=new URL(`${U(this.config,e)}/projects/${encodeURIComponent(r)}/merge_requests/${t.pullRequestNumber}/notes`);i.searchParams.set("page",n.toString()),i.searchParams.set("per_page",o.toString()),i.searchParams.set("sort","asc"),i.searchParams.set("order_by","created_at");let a=await this.config.request({url:i.toString(),headers:R(e.token||this.config.token)}),u=this.getIsSelfHosted(e),l=this.config.baseUrl??e.baseUrl,d={namespace:t.repo.namespace,name:t.repo.name,mergeRequestIid:t.pullRequestNumber},p=a.body.filter(m=>!m.system&&!m.position).map(m=>cr(m,u,l,d)),c=!!a.headers["x-next-page"],g=c?Qo({page:n+1,perPage:o}):null;return{data:p,pageInfo:{endCursor:g,hasNextPage:c}}}async getReviewsForPullRequest(t,e={}){let r=_(t.repo),n=this.getIsSelfHosted(e),o=this.config.baseUrl??e.baseUrl,i=R(e.token||this.config.token),a=U(this.config,e),u=encodeURIComponent(r),[l,d]=await Promise.all([this.config.request({url:`${a}/projects/${u}/merge_requests/${t.pullRequestId}/approvals`,headers:i}),this.fetchAllMergeRequestDiscussions(r,t.pullRequestId,e)]),p=(l.body.approved_by??[]).map(m=>m?.user).filter(m=>!!m).map(m=>{let h=Ls(m,n,o),y=`approval-${m.id}`;return{author:h,body:"",createdAt:l.body.updated_at?new Date(l.body.updated_at):null,id:y,graphQLId:y,reviewComments:[],url:l.body.web_url??""}}),c={namespace:t.repo.namespace,name:t.repo.name,mergeRequestIid:t.pullRequestId},g=d.filter(m=>m.notes.some(h=>!h.system&&!!h.position)).map(m=>{let h=m.notes.filter(w=>!w.system),f=h.filter(w=>!!w.position)[0];if(!f)return null;let P=h.filter(w=>w.id!==f.id).map(w=>cr(w,n,o,c)),A={...cr(f,n,o,c),diffLines:[],filename:f.position?.new_path??f.position?.old_path??"",line:f.position?.new_line??f.position?.old_line??null,startLine:f.position?.line_range?.start?.new_line??null,side:Wo(f.position),isOutdated:!1,isResolved:!!m.resolved,threadId:m.id,replies:P};return{author:f.author?Ls(f.author,n,o):null,body:f.body??"",createdAt:f.created_at?new Date(f.created_at):null,id:m.id,graphQLId:m.id,reviewComments:[A],url:""}}).filter(m=>m!==null);return{data:[...p,...g]}}async getPullRequestDiff(t,e={}){let r=_(t.repo),n=encodeURIComponent(r),o=U(this.config,e);return(await this.fetchAllPagedGitLabREST(`${o}/projects/${n}/merge_requests/${t.pullRequestId}/diffs`,e,{perPage:No,maxPages:Bo})).map(Ho).join("")}async getMergeBase(t,e={}){let r=_(t.repo),n=new URL(`${U(this.config,e)}/projects/${encodeURIComponent(r)}/repository/merge_base`);n.searchParams.append("refs[]",t.base),n.searchParams.append("refs[]",t.head);let i=(await this.config.request({url:n.toString(),headers:R(e.token||this.config.token)})).body?.id;if(!i)throw new Error("No merge base found between the specified commits.");return{data:i}}async fetchAllMergeRequestDiscussions(t,e,r){let n=U(this.config,r),o=encodeURIComponent(t);return this.fetchAllPagedGitLabREST(`${n}/projects/${o}/merge_requests/${e}/discussions`,r)}async fetchAllPagedGitLabREST(t,e,{perPage:r=$,maxPages:n=50}={}){let o=R(e.token||this.config.token),i=[],a=1;for(;a<=n;){let u=new URL(t);u.searchParams.set("page",a.toString()),u.searchParams.set("per_page",r.toString());let l=await this.config.request({url:u.toString(),headers:o});i.push(...l.body);let d=l.headers["x-next-page"];if(!d)break;let p=parseInt(`${d}`,10);if(Number.isNaN(p)||p<=a)break;a=p}return i}async addCommentToPullRequest(t,e={}){let{pullRequest:r,comment:n}=t;if(!n||n.trim()==="")throw new Error("GitLab requires a comment when adding a comment to a pull request.");let o=`${r.repository.owner.login}/${r.repository.name}`,i=`${U(this.config,e)}/projects/${encodeURIComponent(o)}/merge_requests/${r.number}/notes`;if(!(await this.config.request({method:"POST",url:i,headers:{...R(e.token||this.config.token),"Content-Type":"application/json"},body:JSON.stringify({body:n})})).body?.id)throw new Error("Could not add comment to pull request")}async addInlineCommentToPullRequest(t,e={}){let{pullRequest:r,comment:n,path:o,line:i,side:a="RIGHT",threadId:u}=t;if(!n?.trim())throw new Error("GitLab requires a comment when adding an inline comment to a pull request.");let l=`${r.repository.owner.login}/${r.repository.name}`,d=encodeURIComponent(l),p=U(this.config,e),c={...R(e.token||this.config.token),"Content-Type":"application/json"};if(u){let P=await this.config.request({method:"POST",url:`${p}/projects/${d}/merge_requests/${r.number}/discussions/${encodeURIComponent(u)}/notes`,headers:c,body:JSON.stringify({body:n})});return P.body?.id!=null?mr(r.repository.owner.login,r.repository.name,r.number,P.body.id):void 0}if(!o?.trim())throw new Error("GitLab requires a file path when adding an inline comment to a pull request.");if(!Number.isInteger(i)||i<1)throw new Error("GitLab requires a positive line number when adding an inline comment to a pull request.");if(a!=="LEFT"&&a!=="RIGHT")throw new Error('GitLab requires side to be either "LEFT" or "RIGHT".');let m=(await this.config.request({url:`${p}/projects/${d}/merge_requests/${r.number}`,headers:R(e.token||this.config.token)})).body?.diff_refs;if(!m?.base_sha||!m?.start_sha||!m?.head_sha)throw new Error("Could not resolve merge request diff refs required to create an inline comment");let h={position_type:"text",base_sha:m.base_sha,start_sha:m.start_sha,head_sha:m.head_sha,new_path:o,old_path:o};a==="RIGHT"?h.new_line=i:h.old_line=i;let f=(await this.config.request({method:"POST",url:`${p}/projects/${d}/merge_requests/${r.number}/discussions`,headers:c,body:JSON.stringify({body:n,position:h})})).body?.notes?.[0]?.id;return f!=null?mr(r.repository.owner.login,r.repository.name,r.number,f):void 0}getNoteUrl(t,e){if(!t)throw new Error('GitLab requires "commentId" for this function.');let{namespace:r,name:n,mergeRequestIid:o,noteId:i}=Vo(t);return`${U(this.config,e)}/projects/${encodeURIComponent(`${r}/${n}`)}/merge_requests/${o}/notes/${i}`}async deleteNote(t,e){await this.config.request({method:"DELETE",url:this.getNoteUrl(t,e),headers:R(e.token||this.config.token)})}async deleteComment(t,e={}){await this.deleteNote(t.commentId,e)}async deleteInlineComment(t,e={}){await this.deleteNote(t.commentId,e)}async editNote(t,e,r){if(!e?.trim())throw new Error("GitLab requires a body when editing a comment.");if(!(await this.config.request({method:"PUT",url:this.getNoteUrl(t,r),headers:{...R(r.token||this.config.token),"Content-Type":"application/json"},body:JSON.stringify({body:e})})).body?.id)throw new Error("Could not edit comment")}async editComment(t,e={}){await this.editNote(t.commentId,t.body,e)}async editInlineComment(t,e={}){await this.editNote(t.commentId,t.body,e)}async resolveReviewThread(t,e={}){await this.setReviewThreadResolved(t,!0,e)}async unresolveReviewThread(t,e={}){await this.setReviewThreadResolved(t,!1,e)}async setReviewThreadResolved(t,e,r){if(!t.repo||t.pullRequestNumber==null)throw new Error("GitLab requires input.repo and input.pullRequestNumber to locate the discussion to (un)resolve.");if(!t.threadId)throw new Error("GitLab requires input.threadId to (un)resolve a discussion.");let n=_(t.repo),o=new URL(`${U(this.config,r)}/projects/${encodeURIComponent(n)}/merge_requests/${t.pullRequestNumber}/discussions/${encodeURIComponent(t.threadId)}`);o.searchParams.set("resolved",e?"true":"false"),await this.config.request({url:o.toString(),method:"PUT",headers:R(r.token||this.config.token)})}async approvePullRequest(t,e={}){let{pullRequest:r,comment:n}=t,o=`${r.repository.owner.login}/${r.repository.name}`,i=U(this.config,e),a=encodeURIComponent(o),u=R(e.token||this.config.token);await this.config.request({url:`${i}/projects/${a}/merge_requests/${r.number}/approve`,method:"POST",headers:u}),n&&n.trim()!==""&&await this.postMergeRequestNote(o,r.number,n,e)}async commentOnPullRequest(t,e={}){let{pullRequest:r,comment:n}=t;if(!n||n.trim()==="")throw new Error("GitLab requires a comment when commenting on a pull request.");let o=`${r.repository.owner.login}/${r.repository.name}`;await this.postMergeRequestNote(o,r.number,n,e)}async requestPullRequestChanges(t,e={}){let{pullRequest:r,comment:n}=t;if(!n||n.trim()==="")throw new Error("GitLab requires a comment when requesting changes on a pull request.");let o=`${r.repository.owner.login}/${r.repository.name}`;if(!await this.tryRequestChangesMutation(o,r.number,e)){let u=`${U(this.config,e)}/projects/${encodeURIComponent(o)}/merge_requests/${r.number}`,l=R(e.token||this.config.token);(await this.config.request({url:`${u}/approvals`,method:"GET",headers:l})).body?.user_has_approved&&await this.config.request({url:`${u}/unapprove`,method:"POST",headers:l})}await this.postMergeRequestNote(o,r.number,n,e)}async tryRequestChangesMutation(t,e,r){let n=`mutation MergeRequestRequestChanges($fullPath: ID!, $pullRequestId: String!) {
|
|
1364
1364
|
mergeRequestRequestChanges(input: { projectPath: $fullPath, iid: $pullRequestId }) {
|
|
1365
1365
|
errors
|
|
1366
1366
|
mergeRequest {
|
|
1367
1367
|
id
|
|
1368
1368
|
}
|
|
1369
1369
|
}
|
|
1370
|
-
}`,o=await E(this.config,{query:n,variables:{fullPath:t,pullRequestId:e.toString()}},r),i=o.body.errors;if(i?.length){if(i.some(
|
|
1371
|
-
OR comment ~ currentUser() OR summary ~ currentUser() OR description ~ currentUser())`];i&&i.forEach(f=>u.push(`labels = "${f}"`));let l=`${u.join(" AND ")} ORDER BY updated DESC`,p=!o,d=p?$s:As,c=new URL(`${ue(s,r,o)}${d}`);c.searchParams.set("jql",l),c.searchParams.set("maxResults",tt.toString()),c.searchParams.set("fields",Rr.join(",")),c.searchParams.set("expand","transitions"),n&&(p?c.searchParams.set("startAt",n):c.searchParams.set("nextPageToken",n));let g=await s.request({url:c.toString(),headers:R(r.token||s.token)}),m=g.body.issues.map(f=>Ir(f,a,e,o)),h=!1,y="";return p?(h=m.length==tt,y=(parseInt(n??"0",10)+m.length).toString()):(h=!!g.body.nextPageToken,y=g.body.nextPageToken??null),{data:m,pageInfo:{hasNextPage:h,endCursor:y}}},Ls=async(s,t,e,r={})=>{let{cursor:n,resourceId:o,jql:i,fields:a}=t||{},u=L(t?.pageSize,{fallback:tt,max:tt}),l=[...Rr],p=a?.Sprint;p&&l.push(p);let d=!o,c=d?$s:As,g=new URL(`${ue(s,r,o)}${c}`);g.searchParams.set("jql",i.join(" AND ")),g.searchParams.set("maxResults",u.toString()),g.searchParams.set("fields",l.join(",")),g.searchParams.set("expand","transitions"),n&&(d?g.searchParams.set("startAt",n):g.searchParams.set("nextPageToken",n));let m=await s.request({url:g.toString(),headers:R(r.token||s.token)}),h=m.body.issues.map(P=>Ir(P,a,e,o)),y=!1,f="";if(d){let P=parseInt(n??"0",10),v=typeof m.body.startAt=="number"?m.body.startAt:Number.isNaN(P)?0:P,A=m.body.total;y=typeof A=="number"?v+h.length<A:h.length===u,f=(v+h.length).toString()}else y=!!m.body.nextPageToken,f=m.body.nextPageToken??null;return{data:h,pageInfo:{hasNextPage:y,endCursor:f}}},it=async(s,t,e,r={})=>{let{assigneeLogins:n,authorLogin:o,mentionLogin:i,labelNames:a,cursor:u,projectKey:l,resourceId:p,fields:d}=t||{},c=[`project = "${l}"`],g=Ds(t.states);return g&&c.push(g),o&&c.push(`creator in ("${o}")`),n&&n.length!==0&&c.push(`assignee in ("${n.join('", "')}")`),i&&c.push(`comment ~ "${i}"`),a&&a.forEach(m=>c.push(`labels = "${m}"`)),Ls(s,{resourceId:p,jql:c,cursor:u,fields:d,pageSize:t.pageSize},e,r)},at=async(s,t,e,r={})=>{let{assigneeLogins:n,authorLogin:o,mentionLogin:i,labelNames:a,cursor:u,projectKeys:l,resourceId:p,fields:d}=t||{},g=["("+l.map(h=>`project = "${h}"`).join(" OR ")+")"],m=Ds(t.states);return m&&g.push(m),o&&g.push(`creator in ("${o}")`),n&&n.length!==0&&g.push(`assignee in ("${n.join('", "')}")`),i&&g.push(`comment ~ "${i}"`),a&&a.forEach(h=>g.push(`labels = "${h}"`)),Ls(s,{resourceId:p,jql:g,fields:d,cursor:u,pageSize:t.pageSize},e,r)},ut=async(s,t,e={})=>{let{issue:r,labels:n}=t;if(!r.project)throw new Error('Jira requires a "project" for this function.');let o={fields:{labels:n.map(i=>i.name)}};await s.request({method:"PUT",url:`${ue(s,e,r.project.resourceId??void 0)}/rest/api/2/issue/${r.id}`,body:JSON.stringify(o),headers:{...R(e.token||s.token),"Content-Type":"application/json"}})},lt=async(s,t,e={})=>{let{issue:r,components:n}=t;if(!r.project)throw new Error('Jira requires a "project" for this function.');let o={fields:{components:n.map(i=>({id:i.id}))}};await s.request({method:"PUT",url:`${ue(s,e,r.project.resourceId??void 0)}/rest/api/2/issue/${r.id}`,body:JSON.stringify(o),headers:{...R(e.token||s.token),"Content-Type":"application/json"}})},pt=async(s,t,e={})=>{let{issue:r,status:n}=t;if(!r.project)throw new Error('Jira requires a "project" for this function.');if(!n.id)throw new Error('Jira requires a status "id" for this function.');let o={transition:{id:n.id}};await s.request({method:"POST",url:`${ue(s,e,r.project.resourceId??void 0)}/rest/api/2/issue/${r.id}/transitions`,body:JSON.stringify(o),headers:{...R(e.token||s.token),"Content-Type":"application/json"}})},dt=async(s,t,e={})=>{let{resourceId:r,projectIdOrKey:n}=t,o=new URL(`${ue(s,e,r)}/rest/api/2/project/${n}/components`);return{data:(await s.request({url:o.toString(),headers:R(e.token||s.token)})).body}};var _e="https://api.atlassian.com/ex/jira",br=100,qe=class extends M{constructor(){super(...arguments);this._resourceUrlCache={};this._issueFieldsCache={}}async getIssueFieldsForResource(e,r={}){if(!this._issueFieldsCache[e.resourceId]){let n=await st(this.config,e,r);this._issueFieldsCache[e.resourceId]=n.reduce((o,i)=>({...o,[i.name]:i.id}),{})}return this._issueFieldsCache[e.resourceId]??null}async getResourceUrl(e,r={}){let n=r.token||this.config.token;if(!n)return null;let o=this._resourceUrlCache[n];return o?o[e.resourceId]??null:(await this.getJiraResourcesForCurrentUser(r),this._resourceUrlCache[n]?.[e.resourceId]??null)}async getCurrentUserForResource(e,r={}){let n=await this.getResourceUrl({resourceId:e.resourceId},r),o=await this.config.request({url:`${r.baseUrl||_e}/${e.resourceId}/rest/api/2/myself`,headers:R(r.token||this.config.token)});return{data:{name:o.body.displayName,email:o.body.emailAddress,avatarUrl:o.body.avatarUrls["48x48"],id:o.body.accountId,username:o.body.displayName,url:n?`${n}/jira/people/${o.body.accountId}`:null}}}async getJiraResourcesForCurrentUser(e={}){let r=await this.config.request({url:`${e.baseUrl||"https://api.atlassian.com/"}/oauth/token/accessible-resources`,headers:R(e.token||this.config.token)}),n=e.token||this.config.token,o=n?this._resourceUrlCache[n]||{}:void 0,i=r.body.map(a=>(o&&(o[a.id]=a.url),{avatarUrl:a.avatarUrl,id:a.id,name:a.name,url:a.url}));return n&&(this._resourceUrlCache[n]=o),{data:i}}async getJiraProjectsForResource(e,r={}){let n=new URL(`${r.baseUrl||_e}/${e.resourceId}/rest/api/2/project/search`);n.searchParams.set("maxResults",br.toString()),e.cursor&&n.searchParams.set("startAt",e.cursor);let o=await this.config.request({url:n.toString(),headers:R(r.token||this.config.token)});return{pageInfo:{hasNextPage:o.body.values.length!==0,endCursor:(o.body.startAt+o.body.values.length).toString()},data:o.body.values.map(i=>({id:i.id,key:i.key,name:i.name,resourceId:e.resourceId}))}}async getJiraProjectsForResources(e,r={}){let n=[];return await Promise.all(e.resourceIds.map(async o=>{try{return await jr(i=>this.getJiraProjectsForResource({resourceId:o,cursor:i},r))}catch{return[]}})).then((...o)=>{o.forEach(i=>{n=n.concat(...i)})}),{data:n}}async getAccountsForJiraProject(e,r={}){let{resourceId:n,projectKey:o,cursor:i}=e,a=await this.getResourceUrl({resourceId:n},r),u=new URL(`${r.baseUrl||_e}/${n}/rest/api/2/user/assignable/search`);u.searchParams.set("maxResults",br.toString()),i&&u.searchParams.set("startAt",i),u.searchParams.set("project",o);let l=await this.config.request({url:u.toString(),headers:R(r.token||this.config.token)});return{pageInfo:{hasNextPage:l.body.length!==0,endCursor:((i?parseInt(i):0)+l.body.length).toString()},data:l.body.filter(p=>p.accountType!=="app"&&p.active).map(p=>rt(p,a,!1))}}async getComponentsForJiraProject(e,r={}){return await dt(this.config,e,r)}async getIssue(e,r={}){let n=await this.getIssueFieldsForResource({resourceId:e.resourceId},r),o=await this.getResourceUrl({resourceId:e.resourceId},r);return await nt(this.config,{...e,fields:n},o,r)}async getIssuesForProject(e,r={}){let n=await this.getIssueFieldsForResource({resourceId:e.resourceId},r),o=await this.getResourceUrl({resourceId:e.resourceId},r);return await it(this.config,{...e,fields:n},o,r)}async getIssuesForProjects(e,r={}){let n=await this.getIssueFieldsForResource({resourceId:e.resourceId},r),o=await this.getResourceUrl({resourceId:e.resourceId},r);return await at(this.config,{...e,fields:n},o,r)}async getIssuesForResourceForCurrentUser(e,r={}){let n=await this.getIssueFieldsForResource({resourceId:e.resourceId},r),o=await this.getResourceUrl({resourceId:e.resourceId},r);return await ot(this.config,{...e,fields:n},o,r)}async setIssueStatus(e,r={}){await pt(this.config,e,r)}async setIssueAssignee(e,r={}){let{issue:n,assignee:o}=e;if(!n.project)throw new Error('Jira Cloud requires a "project" for this function.');if(!n.project.resourceId)throw new Error('Jira Cloud requires a project "resourceId" for this function.');let i={accountId:o?.id};await this.config.request({method:"PUT",url:`${r.baseUrl||_e}/${n.project.resourceId}/rest/api/2/issue/${n.id}/assignee`,body:JSON.stringify(i),headers:{...R(r.token||this.config.token),"Content-Type":"application/json"}})}async setIssueComponents(e,r={}){await lt(this.config,e,r)}async setIssueLabels(e,r={}){await ut(this.config,e,r)}async getLabelsForResource(e,r={}){let{resourceId:n,cursor:o}=e,i=new URL(`${r.baseUrl||_e}/${n}/rest/api/2/label`);i.searchParams.set("maxResults",br.toString()),o&&i.searchParams.set("startAt",o);let a=await this.config.request({url:i.toString(),headers:R(r.token||this.config.token)});return{pageInfo:{hasNextPage:!a.body.isLast,endCursor:(a.body.startAt+a.body.values.length).toString()},data:a.body.values.map(u=>({color:null,description:null,id:null,name:u}))}}};var ve=class extends Q{constructor(){super(...arguments);this._issueFieldsCache={}}async getIssueFieldsForResource(e={}){let r=e?.baseUrl||this.config.baseUrl||"";if(!this._issueFieldsCache[r]){let n=await st(this.config,{},e);this._issueFieldsCache[r]=n.reduce((o,i)=>({...o,[i.name]:i.id}),{})}return this._issueFieldsCache[r]??null}async getCurrentUser(e={}){let r=await this.config.request({url:`${e?.baseUrl||this.config.baseUrl}/rest/api/2/myself`,headers:R(e?.token||this.config.token)});return{data:{name:r.body.displayName,email:r.body.emailAddress,avatarUrl:r.body.avatarUrls["48x48"],id:r.body.key,username:r.body.displayName,url:null}}}async getJiraProjects(e={}){return{data:(await this.config.request({url:`${e?.baseUrl||this.config.baseUrl}/rest/api/2/project`,headers:R(e?.token||this.config.token)})).body.map(n=>({id:n.id,name:n.name}))}}async getIssue(e,r={}){let n=e.resourceUrl||r.baseUrl||this.config.baseUrl;if(!n)throw new Error('Jira Server requires a "resourceUrl" or "baseUrl" for this function.');let o=await this.getIssueFieldsForResource(r);return await nt(this.config,{...e,fields:o},n,r)}async getIssuesForProject(e,r={}){let n=e.resourceUrl||r.baseUrl||this.config.baseUrl;if(!n)throw new Error('Jira Server requires a "resourceUrl" or "baseUrl" for this function.');let o=await this.getIssueFieldsForResource(r);return await it(this.config,{...e,fields:o},n,r)}async getIssuesForProjects(e,r={}){let n=e.resourceUrl||r.baseUrl||this.config.baseUrl;if(!n)throw new Error('Jira Server requires a "resourceUrl" or "baseUrl" for this function.');let o=await this.getIssueFieldsForResource(r);return await at(this.config,{...e,fields:o},n,r)}async getIssuesForResourceForCurrentUser(e,r={}){let n=e.resourceUrl||r.baseUrl||this.config.baseUrl;if(!n)throw new Error('Jira Server requires a "resourceUrl" or "baseUrl" for this function.');let o=await this.getIssueFieldsForResource(r);return await ot(this.config,{...e,fields:o},n,r)}async setIssueStatus(e,r={}){await pt(this.config,e,r)}async setIssueLabels(e,r={}){await ut(this.config,e,r)}async setIssueComponents(e,r={}){await lt(this.config,e,r)}async getLabels(e={}){return{data:(await this.config.request({url:`${e?.baseUrl||this.config.baseUrl}/rest/api/2/jql/autocompletedata/suggestions?fieldName=labels`,headers:R(e.token||this.config.token)})).body.results.map(({displayName:n})=>({color:null,description:null,id:null,name:n}))}}async getComponentsForJiraProject(e,r={}){return await dt(this.config,e,r)}};var Pr=100,ct=class{constructor(){this.set=new Set;this.arr=[]}push(...t){let e=t.filter(r=>!this.set.has(r.id));this.arr.push(...e),e.forEach(r=>this.set.add(r.id))}get length(){return this.arr.length}get items(){return this.arr}},ne=async(s,t,e,r)=>{let n=t.token||s.token;if(!n)throw new Error("Linear API key is required");let o=await s.request({url:"https://api.linear.app/graphql",method:"POST",headers:{Authorization:n,"Content-Type":"application/json"},body:JSON.stringify({query:e,variables:r})});if(o.status>=400)throw new Error(`Linear API request failed: ${o.status} ${o.statusText}`);let i=o.body;if(i.errors)throw new Error(`Linear GraphQL errors: ${i.errors.map(a=>a.message).join(", ")}`);return i.data},yr=s=>s?s instanceof Date?s:new Date(s):null,zo=`
|
|
1370
|
+
}`,o=await E(this.config,{query:n,variables:{fullPath:t,pullRequestId:e.toString()}},r),i=o.body.errors;if(i?.length){if(i.some(To))return!1;throw new Error(`Could not request pull request changes: ${ke(i)}`)}let a=o.body.data?.mergeRequestRequestChanges;if(a?.errors&&a.errors.length>0)throw new Error(`Could not request pull request changes: ${a.errors.join(", ")}`);if(!a?.mergeRequest?.id)throw new Error("Could not request pull request changes");return!0}async postMergeRequestNote(t,e,r,n){let o=U(this.config,n),i=encodeURIComponent(t),a=R(n.token||this.config.token);await this.config.request({url:`${o}/projects/${i}/merge_requests/${e}/notes`,method:"POST",headers:{...a,"Content-Type":"application/json"},body:JSON.stringify({body:r})})}};var Jo="https://api.atlassian.com/ex/jira",nt=100,Ts=s=>{if(!s||s.length===0)return"statusCategory != Done";let t=new Set(s),e=t.has("OPEN"),r=t.has("CLOSED");return e&&r?null:r?"statusCategory = Done":"statusCategory != Done"},yr=["assignee","comment","summary","created","creator","updated","votes","issuetype","status","labels","components","project","fixVersions","description"],Os="/rest/api/2/search/jql",_s="/rest/api/2/search",Pr=(s,t,e,r)=>{let n=s.fields.assignee,o=!r,i=(s.fields[t?.Sprint??""]??[]).filter(a=>typeof a=="object");return{id:s.id,commentCount:s.fields.comment.comments.length,number:s.key,title:s.fields.summary,url:e?`${e}/browse/${s.key}`:null,closedDate:null,createdDate:new Date(s.fields.created),author:ot(s.fields.creator,e,o),updatedDate:new Date(s.fields.updated),assignees:n?[ot(n,e,o)]:[],description:s.fields.description,repository:null,project:{name:s.fields.project.name,resourceId:r??null,key:s.fields.project.key,namespace:null,id:s.fields.project.id},state:Yo(s.fields.status),statusTransitions:s.transitions?.map(Ko)??[],components:s.fields.components?.map(Xo)??[],type:s.fields.issuetype.name,upvoteCount:s.fields.votes?.votes||0,labels:s.fields.labels?.map(a=>({color:null,description:null,id:null,name:a}))??[],sprints:i.map(ei),fixVersions:s.fields.fixVersions.map(ti)}},Ko=s=>{let t;switch(s.to.statusCategory.name){case"To Do":t="TO_DO";break;case"In Progress":t="IN_PROGRESS";break;default:t="DONE";break}return{name:s.name,id:s.id,to:{id:s.to.id,name:s.to.name,color:s.to.statusCategory.colorName,category:t}}},Xo=s=>({description:s.description??null,id:s.id,name:s.name}),Zo=(s,t,e)=>e&&s.name?`${t}/secure/ViewProfile.jspa?name=${encodeURIComponent(s.name)}`:`${t}/jira/people/${s.accountId}`,ot=(s,t,e)=>({id:(e?s.key:s.accountId)??"",name:s.displayName,email:s.emailAddress,avatarUrl:s.avatarUrls["48x48"],username:s.displayName,url:Zo(s,t,e)}),Yo=s=>{let t;switch(s.statusCategory.name){case"To Do":t="TO_DO";break;case"In Progress":t="IN_PROGRESS";break;default:t="DONE";break}return{id:s.id,name:s.name,color:s.statusCategory.colorName,category:t}},ei=s=>({id:s.id.toString(),name:s.name,isActive:s.state==="active",startDate:s.startDate?new Date(s.startDate):null,endDate:s.endDate?new Date(s.endDate):null,completedDate:s.completeDate?new Date(s.completeDate):null}),ti=s=>({id:s.id,description:s.description,name:s.name,archived:s.archived,released:s.released,releaseDate:s.releaseDate?new Date(s.releaseDate):null}),le=(s,t,e)=>e?`${t.baseUrl||Jo}/${e}`:`${t?.baseUrl||s.baseUrl}`,it=async(s,t,e={})=>{let{resourceId:r}=t;return(await s.request({url:`${le(s,e,r)}/rest/api/2/field`,headers:R(e.token||s.token)})).body},at=async(s,t,e,r={})=>{let{number:n,resourceId:o,fields:i}=t||{},a=await s.request({url:`${le(s,r,o)}/rest/api/2/issue/${n}?fields=${yr.join(",")}&expand=transitions`,headers:R(r.token||s.token)});return{data:Pr(a.body,i,e,o)}},ut=async(s,t,e,r={})=>{let{cursor:n,resourceId:o,labelNames:i,fields:a}=t||{},u=["statusCategory != Done",`(creator = currentUser() OR assignee = currentUser()
|
|
1371
|
+
OR comment ~ currentUser() OR summary ~ currentUser() OR description ~ currentUser())`];i&&i.forEach(f=>u.push(`labels = "${f}"`));let l=`${u.join(" AND ")} ORDER BY updated DESC`,d=!o,p=d?_s:Os,c=new URL(`${le(s,r,o)}${p}`);c.searchParams.set("jql",l),c.searchParams.set("maxResults",nt.toString()),c.searchParams.set("fields",yr.join(",")),c.searchParams.set("expand","transitions"),n&&(d?c.searchParams.set("startAt",n):c.searchParams.set("nextPageToken",n));let g=await s.request({url:c.toString(),headers:R(r.token||s.token)}),m=g.body.issues.map(f=>Pr(f,a,e,o)),h=!1,y="";return d?(h=m.length==nt,y=(parseInt(n??"0",10)+m.length).toString()):(h=!!g.body.nextPageToken,y=g.body.nextPageToken??null),{data:m,pageInfo:{hasNextPage:h,endCursor:y}}},ks=async(s,t,e,r={})=>{let{cursor:n,resourceId:o,jql:i,fields:a}=t||{},u=L(t?.pageSize,{fallback:nt,max:nt}),l=[...yr],d=a?.Sprint;d&&l.push(d);let p=!o,c=p?_s:Os,g=new URL(`${le(s,r,o)}${c}`);g.searchParams.set("jql",i.join(" AND ")),g.searchParams.set("maxResults",u.toString()),g.searchParams.set("fields",l.join(",")),g.searchParams.set("expand","transitions"),n&&(p?g.searchParams.set("startAt",n):g.searchParams.set("nextPageToken",n));let m=await s.request({url:g.toString(),headers:R(r.token||s.token)}),h=m.body.issues.map(P=>Pr(P,a,e,o)),y=!1,f="";if(p){let P=parseInt(n??"0",10),v=typeof m.body.startAt=="number"?m.body.startAt:Number.isNaN(P)?0:P,A=m.body.total;y=typeof A=="number"?v+h.length<A:h.length===u,f=(v+h.length).toString()}else y=!!m.body.nextPageToken,f=m.body.nextPageToken??null;return{data:h,pageInfo:{hasNextPage:y,endCursor:f}}},lt=async(s,t,e,r={})=>{let{assigneeLogins:n,authorLogin:o,mentionLogin:i,labelNames:a,cursor:u,projectKey:l,resourceId:d,fields:p}=t||{},c=[`project = "${l}"`],g=Ts(t.states);return g&&c.push(g),o&&c.push(`creator in ("${o}")`),n&&n.length!==0&&c.push(`assignee in ("${n.join('", "')}")`),i&&c.push(`comment ~ "${i}"`),a&&a.forEach(m=>c.push(`labels = "${m}"`)),ks(s,{resourceId:d,jql:c,cursor:u,fields:p,pageSize:t.pageSize},e,r)},pt=async(s,t,e,r={})=>{let{assigneeLogins:n,authorLogin:o,mentionLogin:i,labelNames:a,cursor:u,projectKeys:l,resourceId:d,fields:p}=t||{},g=["("+l.map(h=>`project = "${h}"`).join(" OR ")+")"],m=Ts(t.states);return m&&g.push(m),o&&g.push(`creator in ("${o}")`),n&&n.length!==0&&g.push(`assignee in ("${n.join('", "')}")`),i&&g.push(`comment ~ "${i}"`),a&&a.forEach(h=>g.push(`labels = "${h}"`)),ks(s,{resourceId:d,jql:g,fields:p,cursor:u,pageSize:t.pageSize},e,r)},dt=async(s,t,e={})=>{let{issue:r,labels:n}=t;if(!r.project)throw new Error('Jira requires a "project" for this function.');let o={fields:{labels:n.map(i=>i.name)}};await s.request({method:"PUT",url:`${le(s,e,r.project.resourceId??void 0)}/rest/api/2/issue/${r.id}`,body:JSON.stringify(o),headers:{...R(e.token||s.token),"Content-Type":"application/json"}})},ct=async(s,t,e={})=>{let{issue:r,components:n}=t;if(!r.project)throw new Error('Jira requires a "project" for this function.');let o={fields:{components:n.map(i=>({id:i.id}))}};await s.request({method:"PUT",url:`${le(s,e,r.project.resourceId??void 0)}/rest/api/2/issue/${r.id}`,body:JSON.stringify(o),headers:{...R(e.token||s.token),"Content-Type":"application/json"}})},mt=async(s,t,e={})=>{let{issue:r,status:n}=t;if(!r.project)throw new Error('Jira requires a "project" for this function.');if(!n.id)throw new Error('Jira requires a status "id" for this function.');let o={transition:{id:n.id}};await s.request({method:"POST",url:`${le(s,e,r.project.resourceId??void 0)}/rest/api/2/issue/${r.id}/transitions`,body:JSON.stringify(o),headers:{...R(e.token||s.token),"Content-Type":"application/json"}})},gt=async(s,t,e={})=>{let{resourceId:r,projectIdOrKey:n}=t,o=new URL(`${le(s,e,r)}/rest/api/2/project/${n}/components`);return{data:(await s.request({url:o.toString(),headers:R(e.token||s.token)})).body}};var Be="https://api.atlassian.com/ex/jira",wr=100,Ce=class extends M{constructor(){super(...arguments);this._resourceUrlCache={};this._issueFieldsCache={}}async getIssueFieldsForResource(e,r={}){if(!this._issueFieldsCache[e.resourceId]){let n=await it(this.config,e,r);this._issueFieldsCache[e.resourceId]=n.reduce((o,i)=>({...o,[i.name]:i.id}),{})}return this._issueFieldsCache[e.resourceId]??null}async getResourceUrl(e,r={}){let n=r.token||this.config.token;if(!n)return null;let o=this._resourceUrlCache[n];return o?o[e.resourceId]??null:(await this.getJiraResourcesForCurrentUser(r),this._resourceUrlCache[n]?.[e.resourceId]??null)}async getCurrentUserForResource(e,r={}){let n=await this.getResourceUrl({resourceId:e.resourceId},r),o=await this.config.request({url:`${r.baseUrl||Be}/${e.resourceId}/rest/api/2/myself`,headers:R(r.token||this.config.token)});return{data:{name:o.body.displayName,email:o.body.emailAddress,avatarUrl:o.body.avatarUrls["48x48"],id:o.body.accountId,username:o.body.displayName,url:n?`${n}/jira/people/${o.body.accountId}`:null}}}async getJiraResourcesForCurrentUser(e={}){let r=await this.config.request({url:`${e.baseUrl||"https://api.atlassian.com/"}/oauth/token/accessible-resources`,headers:R(e.token||this.config.token)}),n=e.token||this.config.token,o=n?this._resourceUrlCache[n]||{}:void 0,i=r.body.map(a=>(o&&(o[a.id]=a.url),{avatarUrl:a.avatarUrl,id:a.id,name:a.name,url:a.url}));return n&&(this._resourceUrlCache[n]=o),{data:i}}async getJiraProjectsForResource(e,r={}){let n=new URL(`${r.baseUrl||Be}/${e.resourceId}/rest/api/2/project/search`);n.searchParams.set("maxResults",wr.toString()),e.cursor&&n.searchParams.set("startAt",e.cursor);let o=await this.config.request({url:n.toString(),headers:R(r.token||this.config.token)});return{pageInfo:{hasNextPage:o.body.values.length!==0,endCursor:(o.body.startAt+o.body.values.length).toString()},metadata:be("complete"),data:o.body.values.map(i=>({id:i.id,key:i.key,name:i.name,resourceId:e.resourceId}))}}async getJiraProjectsForResources(e,r={}){let{successes:n,metadata:o}=await te(e.resourceIds,{run:a=>Wr(u=>this.getJiraProjectsForResource({resourceId:a,cursor:u},r)),failureScope:a=>({providerId:"jira",resourceId:a})}),i=[];return n.forEach(({result:a})=>{i.push(...a)}),{data:i,metadata:o}}async getAccountsForJiraProject(e,r={}){let{resourceId:n,projectKey:o,cursor:i}=e,a=await this.getResourceUrl({resourceId:n},r),u=new URL(`${r.baseUrl||Be}/${n}/rest/api/2/user/assignable/search`);u.searchParams.set("maxResults",wr.toString()),i&&u.searchParams.set("startAt",i),u.searchParams.set("project",o);let l=await this.config.request({url:u.toString(),headers:R(r.token||this.config.token)});return{pageInfo:{hasNextPage:l.body.length!==0,endCursor:((i?parseInt(i):0)+l.body.length).toString()},metadata:be("complete"),data:l.body.filter(d=>d.accountType!=="app"&&d.active).map(d=>ot(d,a,!1))}}async getComponentsForJiraProject(e,r={}){return await gt(this.config,e,r)}async getIssue(e,r={}){let n=await this.getIssueFieldsForResource({resourceId:e.resourceId},r),o=await this.getResourceUrl({resourceId:e.resourceId},r);return await at(this.config,{...e,fields:n},o,r)}async getIssuesForProject(e,r={}){let n=await this.getIssueFieldsForResource({resourceId:e.resourceId},r),o=await this.getResourceUrl({resourceId:e.resourceId},r);return await lt(this.config,{...e,fields:n},o,r)}async getIssuesForProjects(e,r={}){let n=await this.getIssueFieldsForResource({resourceId:e.resourceId},r),o=await this.getResourceUrl({resourceId:e.resourceId},r);return await pt(this.config,{...e,fields:n},o,r)}async getIssuesForResourceForCurrentUser(e,r={}){let n=await this.getIssueFieldsForResource({resourceId:e.resourceId},r),o=await this.getResourceUrl({resourceId:e.resourceId},r);return await ut(this.config,{...e,fields:n},o,r)}async setIssueStatus(e,r={}){await mt(this.config,e,r)}async setIssueAssignee(e,r={}){let{issue:n,assignee:o}=e;if(!n.project)throw new Error('Jira Cloud requires a "project" for this function.');if(!n.project.resourceId)throw new Error('Jira Cloud requires a project "resourceId" for this function.');let i={accountId:o?.id};await this.config.request({method:"PUT",url:`${r.baseUrl||Be}/${n.project.resourceId}/rest/api/2/issue/${n.id}/assignee`,body:JSON.stringify(i),headers:{...R(r.token||this.config.token),"Content-Type":"application/json"}})}async setIssueComponents(e,r={}){await ct(this.config,e,r)}async setIssueLabels(e,r={}){await dt(this.config,e,r)}async getLabelsForResource(e,r={}){let{resourceId:n,cursor:o}=e,i=new URL(`${r.baseUrl||Be}/${n}/rest/api/2/label`);i.searchParams.set("maxResults",wr.toString()),o&&i.searchParams.set("startAt",o);let a=await this.config.request({url:i.toString(),headers:R(r.token||this.config.token)});return{pageInfo:{hasNextPage:!a.body.isLast,endCursor:(a.body.startAt+a.body.values.length).toString()},data:a.body.values.map(u=>({color:null,description:null,id:null,name:u}))}}};var De=class extends F{constructor(){super(...arguments);this._issueFieldsCache={}}async getIssueFieldsForResource(e={}){let r=e?.baseUrl||this.config.baseUrl||"";if(!this._issueFieldsCache[r]){let n=await it(this.config,{},e);this._issueFieldsCache[r]=n.reduce((o,i)=>({...o,[i.name]:i.id}),{})}return this._issueFieldsCache[r]??null}async getCurrentUser(e={}){let r=await this.config.request({url:`${e?.baseUrl||this.config.baseUrl}/rest/api/2/myself`,headers:R(e?.token||this.config.token)});return{data:{name:r.body.displayName,email:r.body.emailAddress,avatarUrl:r.body.avatarUrls["48x48"],id:r.body.key,username:r.body.displayName,url:null}}}async getJiraProjects(e={}){return{data:(await this.config.request({url:`${e?.baseUrl||this.config.baseUrl}/rest/api/2/project`,headers:R(e?.token||this.config.token)})).body.map(n=>({id:n.id,name:n.name}))}}async getIssue(e,r={}){let n=e.resourceUrl||r.baseUrl||this.config.baseUrl;if(!n)throw new Error('Jira Server requires a "resourceUrl" or "baseUrl" for this function.');let o=await this.getIssueFieldsForResource(r);return await at(this.config,{...e,fields:o},n,r)}async getIssuesForProject(e,r={}){let n=e.resourceUrl||r.baseUrl||this.config.baseUrl;if(!n)throw new Error('Jira Server requires a "resourceUrl" or "baseUrl" for this function.');let o=await this.getIssueFieldsForResource(r);return await lt(this.config,{...e,fields:o},n,r)}async getIssuesForProjects(e,r={}){let n=e.resourceUrl||r.baseUrl||this.config.baseUrl;if(!n)throw new Error('Jira Server requires a "resourceUrl" or "baseUrl" for this function.');let o=await this.getIssueFieldsForResource(r);return await pt(this.config,{...e,fields:o},n,r)}async getIssuesForResourceForCurrentUser(e,r={}){let n=e.resourceUrl||r.baseUrl||this.config.baseUrl;if(!n)throw new Error('Jira Server requires a "resourceUrl" or "baseUrl" for this function.');let o=await this.getIssueFieldsForResource(r);return await ut(this.config,{...e,fields:o},n,r)}async setIssueStatus(e,r={}){await mt(this.config,e,r)}async setIssueLabels(e,r={}){await dt(this.config,e,r)}async setIssueComponents(e,r={}){await ct(this.config,e,r)}async getLabels(e={}){return{data:(await this.config.request({url:`${e?.baseUrl||this.config.baseUrl}/rest/api/2/jql/autocompletedata/suggestions?fieldName=labels`,headers:R(e.token||this.config.token)})).body.results.map(({displayName:n})=>({color:null,description:null,id:null,name:n}))}}async getComponentsForJiraProject(e,r={}){return await gt(this.config,e,r)}};var vr=100,ht=class{constructor(){this.set=new Set;this.arr=[]}push(...t){let e=t.filter(r=>!this.set.has(r.id));this.arr.push(...e),e.forEach(r=>this.set.add(r.id))}get length(){return this.arr.length}get items(){return this.arr}},oe=async(s,t,e,r)=>{let n=t.token||s.token;if(!n)throw new Error("Linear API key is required");let o=await s.request({url:"https://api.linear.app/graphql",method:"POST",headers:{Authorization:n,"Content-Type":"application/json"},body:JSON.stringify({query:e,variables:r})});if(o.status>=400)throw new Error(`Linear API request failed: ${o.status} ${o.statusText}`);let i=o.body;if(i.errors)throw new Error(`Linear GraphQL errors: ${i.errors.map(a=>a.message).join(", ")}`);return i.data},qr=s=>s?s instanceof Date?s:new Date(s):null,ri=`
|
|
1372
1372
|
id
|
|
1373
1373
|
name
|
|
1374
1374
|
description
|
|
@@ -1376,11 +1376,11 @@ OR comment ~ currentUser() OR summary ~ currentUser() OR description ~ currentUs
|
|
|
1376
1376
|
startDate
|
|
1377
1377
|
targetDate
|
|
1378
1378
|
url
|
|
1379
|
-
`,
|
|
1379
|
+
`,xs=s=>({id:s.id,name:s.name,description:s.description??null,state:s.state,startDate:qr(s.startDate),targetDate:qr(s.targetDate),url:s.url}),Ns=async(s,t,e)=>{let r=`
|
|
1380
1380
|
query GetProjects($first: Int!, $after: String) {
|
|
1381
1381
|
projects(first: $first, after: $after) {
|
|
1382
1382
|
nodes {
|
|
1383
|
-
${
|
|
1383
|
+
${ri}
|
|
1384
1384
|
}
|
|
1385
1385
|
pageInfo {
|
|
1386
1386
|
hasNextPage
|
|
@@ -1388,7 +1388,7 @@ OR comment ~ currentUser() OR summary ~ currentUser() OR description ~ currentUs
|
|
|
1388
1388
|
}
|
|
1389
1389
|
}
|
|
1390
1390
|
}
|
|
1391
|
-
`;return(await
|
|
1391
|
+
`;return(await oe(s,t,r,{first:vr,after:e})).projects},si=`
|
|
1392
1392
|
id
|
|
1393
1393
|
name
|
|
1394
1394
|
number
|
|
@@ -1396,11 +1396,11 @@ OR comment ~ currentUser() OR summary ~ currentUser() OR description ~ currentUs
|
|
|
1396
1396
|
startsAt
|
|
1397
1397
|
endsAt
|
|
1398
1398
|
completedAt
|
|
1399
|
-
`,
|
|
1399
|
+
`,Bs=s=>({id:s.id,name:s.name??`Cycle ${s.number}`,number:s.number,description:s.description??null,startsAt:new Date(s.startsAt),endsAt:new Date(s.endsAt),completedAt:qr(s.completedAt),url:""}),js=async(s,t,e)=>{let r=`
|
|
1400
1400
|
query GetCycles($first: Int!, $after: String) {
|
|
1401
1401
|
cycles(first: $first, after: $after) {
|
|
1402
1402
|
nodes {
|
|
1403
|
-
${
|
|
1403
|
+
${si}
|
|
1404
1404
|
}
|
|
1405
1405
|
pageInfo {
|
|
1406
1406
|
hasNextPage
|
|
@@ -1408,16 +1408,16 @@ OR comment ~ currentUser() OR summary ~ currentUser() OR description ~ currentUs
|
|
|
1408
1408
|
}
|
|
1409
1409
|
}
|
|
1410
1410
|
}
|
|
1411
|
-
`;return(await
|
|
1411
|
+
`;return(await oe(s,t,r,{first:vr,after:e})).cycles},ni=`
|
|
1412
1412
|
id
|
|
1413
1413
|
name
|
|
1414
1414
|
color
|
|
1415
1415
|
description
|
|
1416
|
-
`,
|
|
1416
|
+
`,Fs=s=>({id:s.id,name:s.name,color:s.color,description:s.description??null}),Qs=async(s,t,e)=>{let r=`
|
|
1417
1417
|
query GetLabels($first: Int!, $after: String) {
|
|
1418
1418
|
projectLabels(first: $first, after: $after) {
|
|
1419
1419
|
nodes {
|
|
1420
|
-
${
|
|
1420
|
+
${ni}
|
|
1421
1421
|
}
|
|
1422
1422
|
pageInfo {
|
|
1423
1423
|
hasNextPage
|
|
@@ -1425,36 +1425,36 @@ OR comment ~ currentUser() OR summary ~ currentUser() OR description ~ currentUs
|
|
|
1425
1425
|
}
|
|
1426
1426
|
}
|
|
1427
1427
|
}
|
|
1428
|
-
`;return(await
|
|
1428
|
+
`;return(await oe(s,t,r,{first:vr,after:e})).projectLabels};var je=(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))(je||{});function zs(s,t){return s?`${je[s]}:${t||""}`:t??null}function Ms(s){if(!s)return{category:0};let[t,e]=s.split(":");return t in je?{category:je[t],cursor:e||void 0}:{category:0,cursor:s}}var Ws=100;function Rt(s){return s?s instanceof Date?s:new Date(s):null}var Js=`
|
|
1429
1429
|
id
|
|
1430
1430
|
name
|
|
1431
1431
|
key
|
|
1432
1432
|
icon
|
|
1433
|
-
`;function
|
|
1433
|
+
`;function oi(s){return{id:s.id,name:s.name,key:s.key,iconUrl:s.icon}}var Hs=`
|
|
1434
1434
|
id
|
|
1435
1435
|
name
|
|
1436
1436
|
avatarUrl
|
|
1437
|
-
`;function
|
|
1437
|
+
`;function Vs(s){return s?{id:s.id,name:s.name,username:s.name,email:null,avatarUrl:s.avatarUrl??null,url:null}:null}var ii=`
|
|
1438
1438
|
id
|
|
1439
1439
|
name
|
|
1440
|
-
`;function
|
|
1440
|
+
`;function ai(s,t){if(s)return{id:s.id,name:s.name,key:t?.key||null,namespace:null,resourceId:t?.id||null}}var ui=`
|
|
1441
1441
|
id
|
|
1442
1442
|
sortOrder
|
|
1443
1443
|
name
|
|
1444
1444
|
description
|
|
1445
1445
|
status
|
|
1446
1446
|
targetDate
|
|
1447
|
-
`;function
|
|
1447
|
+
`;function li(s){return s?{id:s.id,number:s.sortOrder,title:s.name,description:s.description??null,isOpen:s.status!=="done",url:"",startDate:null,dueDate:Rt(s.targetDate)}:null}function pi(s){switch(s){case"completed":case"canceled":return"DONE";case"started":return"IN_PROGRESS";default:return"TO_DO"}}var di=`
|
|
1448
1448
|
id
|
|
1449
1449
|
name
|
|
1450
1450
|
color
|
|
1451
1451
|
type
|
|
1452
|
-
`;function
|
|
1452
|
+
`;function ci(s){return s?{id:s.id,name:s.name,color:s.color,category:pi(s.type)}:null}var Sr=`
|
|
1453
1453
|
creator {
|
|
1454
|
-
${
|
|
1454
|
+
${Hs}
|
|
1455
1455
|
}
|
|
1456
1456
|
assignee {
|
|
1457
|
-
${
|
|
1457
|
+
${Hs}
|
|
1458
1458
|
}
|
|
1459
1459
|
archivedAt
|
|
1460
1460
|
createdAt
|
|
@@ -1462,35 +1462,35 @@ OR comment ~ currentUser() OR summary ~ currentUser() OR description ~ currentUs
|
|
|
1462
1462
|
id
|
|
1463
1463
|
identifier
|
|
1464
1464
|
project {
|
|
1465
|
-
${
|
|
1465
|
+
${ii}
|
|
1466
1466
|
}
|
|
1467
1467
|
team {
|
|
1468
|
-
${
|
|
1468
|
+
${Js}
|
|
1469
1469
|
}
|
|
1470
1470
|
state {
|
|
1471
|
-
${
|
|
1471
|
+
${di}
|
|
1472
1472
|
}
|
|
1473
1473
|
title
|
|
1474
1474
|
updatedAt
|
|
1475
1475
|
url
|
|
1476
1476
|
projectMilestone {
|
|
1477
|
-
${
|
|
1477
|
+
${ui}
|
|
1478
1478
|
}
|
|
1479
|
-
`;async function
|
|
1479
|
+
`;async function Er(s){return{author:Vs(await s.creator),assignees:[Vs(await s.assignee)].filter(t=>t!=null),commentCount:null,closedDate:Rt(s.archivedAt),createdDate:Rt(s.createdAt),description:s.description??null,id:s.id,labels:[],number:s.identifier,repository:null,project:ai(await s.project,await s.team),state:ci(await s.state),title:s.title,type:null,updatedDate:Rt(s.updatedAt),upvoteCount:null,url:s.url,milestone:li(await s.projectMilestone)}}var ft=`
|
|
1480
1480
|
nodes {
|
|
1481
|
-
${
|
|
1481
|
+
${Sr}
|
|
1482
1482
|
}
|
|
1483
1483
|
pageInfo {
|
|
1484
1484
|
hasNextPage
|
|
1485
1485
|
endCursor
|
|
1486
1486
|
}
|
|
1487
|
-
`,
|
|
1487
|
+
`,Ae=class extends M{async fetchIssue(t,e){let r=`
|
|
1488
1488
|
query GetIssue($identifier: String!) {
|
|
1489
1489
|
issue(id: $identifier) {
|
|
1490
|
-
${
|
|
1490
|
+
${Sr}
|
|
1491
1491
|
}
|
|
1492
1492
|
}
|
|
1493
|
-
`;return(await
|
|
1493
|
+
`;return(await oe(this.config,e,r,{identifier:t})).issue}async fetchOrganization(t){let e=`
|
|
1494
1494
|
query GetOrganization {
|
|
1495
1495
|
organization {
|
|
1496
1496
|
id
|
|
@@ -1498,15 +1498,15 @@ OR comment ~ currentUser() OR summary ~ currentUser() OR description ~ currentUs
|
|
|
1498
1498
|
urlKey
|
|
1499
1499
|
}
|
|
1500
1500
|
}
|
|
1501
|
-
`;return(await
|
|
1501
|
+
`;return(await oe(this.config,t,e)).organization}async fetchTeams(t){let e=`
|
|
1502
1502
|
query GetTeams {
|
|
1503
1503
|
teams {
|
|
1504
1504
|
nodes {
|
|
1505
|
-
${
|
|
1505
|
+
${Js}
|
|
1506
1506
|
}
|
|
1507
1507
|
}
|
|
1508
1508
|
}
|
|
1509
|
-
`;return(await
|
|
1509
|
+
`;return(await oe(this.config,t,e)).teams}async rawRequest(t,e,r){return{data:await oe(this.config,t,e,r)}}async fetchViewer(t){let e=`
|
|
1510
1510
|
query GetViewer {
|
|
1511
1511
|
viewer {
|
|
1512
1512
|
id
|
|
@@ -1515,23 +1515,23 @@ OR comment ~ currentUser() OR summary ~ currentUser() OR description ~ currentUs
|
|
|
1515
1515
|
displayName
|
|
1516
1516
|
}
|
|
1517
1517
|
}
|
|
1518
|
-
`;return(await
|
|
1518
|
+
`;return(await oe(this.config,t,e)).viewer}async getIssue(t,e={}){let r=await this.fetchIssue(t.number,e);return{data:await Er(r)}}async getLinearOrganization(t={}){let e=await this.fetchOrganization(t);return{data:{id:e.id,name:e.name,key:e.urlKey,url:`https://linear.app/${e.urlKey}`}}}async getTeamsForCurrentUser(t={}){return{data:(await this.fetchTeams(t)).nodes.map(oi)}}async getProjects(t={},e={}){let r=await Ns(this.config,e,t.cursor??void 0);return{data:r.nodes.map(xs),pageInfo:{hasNextPage:r.pageInfo.hasNextPage,endCursor:r.pageInfo.endCursor??null}}}async getCycles(t={},e={}){let r=await js(this.config,e,t.cursor??void 0);return{data:r.nodes.map(Bs),pageInfo:{hasNextPage:r.pageInfo.hasNextPage,endCursor:r.pageInfo.endCursor??null}}}async getLabels(t={},e={}){let r=await Qs(this.config,e,t.cursor??void 0);return{data:r.nodes.map(Fs),pageInfo:{hasNextPage:r.pageInfo.hasNextPage,endCursor:r.pageInfo.endCursor??null}}}async getCurrentUser(t={}){return{data:await this.fetchViewer(t)}}async getIssuesForCurrentUser(t,e={}){let{cursor:r}=t,{category:n,cursor:o}=Ms(r),i=await this.fetchViewer(e),a,u,l=new ht,d=async(p,c)=>{if(u||n>p)return;let g=await c(Math.max(Ws-l.length,1),n===p?o:void 0);if(!g)return;let m=await Bt(g.nodes.map(Er));l.push(...m),g.pageInfo.hasNextPage&&(a=p,u=g.pageInfo.endCursor)};return await d(1,async(p,c)=>(await this.rawRequest(e,`
|
|
1519
1519
|
query GetAssignedIssues($first: Int!, $after: String) {
|
|
1520
1520
|
viewer {
|
|
1521
1521
|
issues: assignedIssues(first: $first, after: $after) {
|
|
1522
|
-
${
|
|
1522
|
+
${ft}
|
|
1523
1523
|
}
|
|
1524
1524
|
}
|
|
1525
1525
|
}
|
|
1526
|
-
`,{first:
|
|
1526
|
+
`,{first:p,after:c})).data?.viewer?.issues),await d(2,async(p,c)=>(await this.rawRequest(e,`
|
|
1527
1527
|
query GetCreatedIssues($first: Int!, $after: String) {
|
|
1528
1528
|
viewer {
|
|
1529
1529
|
issues: createdIssues(first: $first, after: $after) {
|
|
1530
|
-
${
|
|
1530
|
+
${ft}
|
|
1531
1531
|
}
|
|
1532
1532
|
}
|
|
1533
1533
|
}
|
|
1534
|
-
`,{first:
|
|
1534
|
+
`,{first:p,after:c})).data?.viewer?.issues),await d(4,async(p,c)=>(await this.rawRequest(e,`
|
|
1535
1535
|
query GetMentionedIssues($first: Int!, $after: String) {
|
|
1536
1536
|
issues(
|
|
1537
1537
|
first: $first
|
|
@@ -1552,10 +1552,10 @@ OR comment ~ currentUser() OR summary ~ currentUser() OR description ~ currentUs
|
|
|
1552
1552
|
}]
|
|
1553
1553
|
}
|
|
1554
1554
|
){
|
|
1555
|
-
${
|
|
1555
|
+
${ft}
|
|
1556
1556
|
}
|
|
1557
1557
|
}
|
|
1558
|
-
`,{first:
|
|
1558
|
+
`,{first:p,after:c})).data?.issues),await d(5,async(p,c)=>{let m=(await this.rawRequest(e,`
|
|
1559
1559
|
query GetCommentedIssues($first: Int!, $after: String) {
|
|
1560
1560
|
comments(
|
|
1561
1561
|
first: $first
|
|
@@ -1578,7 +1578,7 @@ OR comment ~ currentUser() OR summary ~ currentUser() OR description ~ currentUs
|
|
|
1578
1578
|
){
|
|
1579
1579
|
nodes {
|
|
1580
1580
|
issue {
|
|
1581
|
-
${
|
|
1581
|
+
${Sr}
|
|
1582
1582
|
}
|
|
1583
1583
|
}
|
|
1584
1584
|
pageInfo {
|
|
@@ -1587,10 +1587,10 @@ OR comment ~ currentUser() OR summary ~ currentUser() OR description ~ currentUs
|
|
|
1587
1587
|
}
|
|
1588
1588
|
}
|
|
1589
1589
|
}
|
|
1590
|
-
`,{first:
|
|
1590
|
+
`,{first:p,after:c})).data?.comments;return m?{nodes:m.nodes.map(y=>y.issue),pageInfo:m.pageInfo}:void 0}),{data:l.items,pageInfo:{hasNextPage:!!u,endCursor:zs(a,u)}}}async getIssues(t,e={}){let{teams:r,projects:n,labels:o,cursor:i}=t,a=[];if(r&&r.length>0){let g=r.map(m=>`"${m}"`).join(", ");a.push(`team: { id: { in: [${g}] } }`)}if(n&&n.length>0){let g=n.map(m=>`"${m}"`).join(", ");a.push(`project: { id: { in: [${g}] } }`)}if(o&&o.length>0){let g=o.map(m=>`"${m}"`).join(", ");a.push(`labels: { name: { in: [${g}] } }`)}let u=a.length>0?`filter: { ${a.join(", ")} }`:"",l=`
|
|
1591
1591
|
query GetIssues($first: Int!, $after: String) {
|
|
1592
1592
|
issues(first: $first, after: $after${u?", ":""}${u}) {
|
|
1593
|
-
${
|
|
1593
|
+
${ft}
|
|
1594
1594
|
}
|
|
1595
1595
|
}
|
|
1596
|
-
`,d=(await this.rawRequest(e,l,{first:Bs,after:i})).data?.issues;return d?{data:await kt(d.nodes.map(wr)),pageInfo:{hasNextPage:d.pageInfo.hasNextPage,endCursor:d.pageInfo.endCursor??null}}:{data:[],pageInfo:{hasNextPage:!1,endCursor:null}}}};var Z="https://api.trello.com",ti=1e3,Y=(s,t)=>({...R(t),Authorization:`OAuth oauth_consumer_key="${s}", oauth_token="${t}"`}),ri=s=>({id:s.id,username:s.username,url:s.url,name:s.fullName,email:s.email,avatarUrl:s.avatarUrl}),si=(s,t)=>{let e=new Date(1e3*parseInt(s.id.substring(0,8),16));return{id:s.id,commentCount:s.badges.comments,number:s.idShort.toString(),title:s.name,url:s.url,closedDate:null,createdDate:new Date(e.toISOString()),author:null,updatedDate:new Date(s.dateLastActivity),assignees:s.members.map(r=>({id:r.id,username:r.username,name:r.fullName,email:null,avatarUrl:r.avatarUrl,url:null})),description:null,state:t[s.idList??""]?{id:s.idList,name:t[s.idList].name,color:null}:null,type:null,repository:null,upvoteCount:s.badges.votes,labels:s.labels.map(r=>({color:r.color,description:null,id:r.id,name:r.name}))}},Se=class extends M{async getCurrentUser(t,e={}){let r=await this.config.request({url:`${e.baseUrl||Z}/1/members/me`,headers:Y(t.appKey,e.token||this.config.token)});return{data:{name:r.body.fullName,email:r.body.email,avatarUrl:r.body.avatarHash?`https://trello-members.s3.amazonaws.com/${r.body.id}/${r.body.avatarHash}/50.png`:null,id:r.body.id,username:r.body.username,url:r.body.url}}}async getBoardsForCurrentUser(t,e={}){return{data:(await this.config.request({url:`${e.baseUrl||Z}/1/members/me/boards?fields=name&filter=open`,headers:Y(t.appKey,e.token||this.config.token)})).body.map(n=>({id:n.id,name:n.name}))}}async getListsForTrelloBoard(t,e={}){let{appKey:r,boardId:n}=t;return{data:(await this.config.request({url:`${e.baseUrl||Z}/1/boards/${n}/lists`,headers:Y(r,e.token||this.config.token)})).body}}async getAccountForId(t,e={}){let{appKey:r,memberId:n}=t,o=await this.config.request({url:`${e.baseUrl||Z}/1/members/${n}`,headers:Y(r,e.token||this.config.token)});return{data:ri(o.body)}}async getAccountsForTrelloBoard(t,e={}){let{appKey:r,boardId:n}=t;return{data:(await this.config.request({url:`${e.baseUrl||Z}/1/boards/${n}/members`,headers:Y(r,e.token||this.config.token)})).body.map(i=>({id:i.id,name:i.fullName,username:i.username,email:null,avatarUrl:null,url:null}))}}async getIssuesForBoard(t,e={}){let r=["-is:archived","sort:edited"],{appKey:n,boardId:o,filterText:i,assigneeLogins:a,labelNamesOrColors:u,trelloBoardListsById:l}=t||{};a&&r.push("@me"),u&&u.forEach(c=>r.push(`label:"${c}"`));let p=`${i?`${i}`:""}${r.join(" ")} board:${o}`;return{data:(await this.config.request({url:`${e.baseUrl||Z}/1/search?query=${p}&cards_limit=${ti}&card_members=true`,headers:Y(n,e.token||this.config.token)})).body.cards.map(c=>si(c,l||{}))}}async updateIssue(t,e,r,n){return await this.config.request({method:"PUT",url:`${n.baseUrl||Z}/1/cards/${e.id}?${r}`,headers:Y(t,n.token||this.config.token)})}async setIssueStatus(t,e={}){let{appKey:r,issue:n,status:o}=t;if(!o.id)throw new Error('Trello requires a status "id" for this function.');let i=`idList=${o.id}`;if(!(await this.updateIssue(r,n,i,e)).body.id)throw new Error("Could not set issue status")}async setIssueAssignees(t,e={}){let{appKey:r,issue:n,assignees:o}=t,i=o.map(l=>l.id),a=`idMembers=${encodeURIComponent(i.join(","))}`;if(!(await this.updateIssue(r,n,a,e)).body.id)throw new Error("Could not set issue status")}async setIssueLabels(t,e={}){let{appKey:r,issue:n,labels:o}=t,i=o.map(u=>u.id).join(",");if(!(await this.config.request({method:"PUT",url:`${e.baseUrl||Z}/1/cards/${n.id}?idLabels=${encodeURIComponent(i)}`,headers:Y(r,e.token||this.config.token)})).body.id)throw new Error("Could not set issue status")}async setIssueArchived(t,e={}){let{appKey:r,issue:n,archived:o}=t;if(!(await this.config.request({method:"PUT",url:`${e.baseUrl||Z}/1/cards/${n.id}?closed=${o}`,headers:Y(r,e.token||this.config.token)})).body.id)throw new Error("Could not update issue archived status")}async archiveIssue(t,e={}){await this.setIssueArchived({...t,archived:!0},e)}async unArchiveIssue(t,e={}){await this.setIssueArchived({...t,archived:!1},e)}async getLabelsForBoard(t,e={}){let{appKey:r,boardId:n}=t;return{data:(await this.config.request({url:`${e.baseUrl||Z}/1/boards/${n}/labels`,headers:Y(r,e.token||this.config.token)})).body.map(i=>({color:i.color,description:null,id:i.id,name:i.name}))}}};var ht={};H(ht,{default:()=>ni});var ni={};var ft={};H(ft,{default:()=>oi});var oi={};var Dt={};H(Dt,{decode:()=>vr,decodeV0:()=>li,encode:()=>ui,validate:()=>ai});var B=(e=>(e.Zero="0",e.One="1",e))(B||{}),j=(e=>(e.PullRequest="pr",e.Issue="issue",e))(j||{}),N=(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))(N||{});var Rt=class{constructor(){}validate(t){if(!t.organizationName)throw new Error("organizationName is required");if(!t.projectId)throw new Error("projectId is required");if(!t.entityId)throw new Error("issueId is required")}encode(t){if(this.validate(t),!t.organizationName||!t.projectId||!t.entityId)throw new Error("Missing required fields for Azure DevOps issue uniqueId");let e=[];return e.push(t.provider),e.push("issue"),e.push("1"),t.provider==="azureDevOpsServer"?e.push(t.domain):e.push(""),e.push(t.organizationName),e.push(t.projectId),e.push(t.entityId),JSON.stringify(e)}decode(t){if(t.length<7)throw new Error("Invalid Azure DevOps issue uniqueId, check version");return{provider:t[0],entityType:t[1],version:t[2],domain:t[3]==""?null:t[3],resourceId:null,accountOrOrgId:null,organizationName:t[4],projectId:t[5],repoId:null,entityId:t[6]}}};var It=class{constructor(){}validate(t){if(!t.organizationName)throw new Error("organizationName is required");if(!t.projectId)throw new Error("projectId is required");if(!t.repoId)throw new Error("repoId is required");if(!t.entityId)throw new Error("entityId is required")}encode(t){if(this.validate(t),!t.organizationName||!t.projectId||!t.repoId||!t.entityId)throw new Error("Missing required fields for Azure DevOps pull request uniqueId");let e=[];return e.push(t.provider),e.push("pr"),e.push("1"),t.provider==="azureDevOpsServer"?e.push(t.domain):e.push(""),e.push(t.organizationName),e.push(t.projectId),e.push(t.repoId),e.push(t.entityId),JSON.stringify(e)}decode(t){if(t.length<8)throw new Error("Invalid Azure DevOps pull request uniqueId, check version");return{provider:t[0],entityType:t[1],version:t[2],domain:t[3]==""?null:t[3],resourceId:null,accountOrOrgId:null,organizationName:t[4],projectId:t[5],repoId:t[6],entityId:t[7]}}};var bt=class{constructor(){}validate(t){if(!t.repoId)throw new Error("repoId is required");if(!t.entityId)throw new Error("issueId is required")}encode(t){if(this.validate(t),!t.repoId||!t.entityId)throw new Error("Missing required fields for Bitbucket DevOps issue uniqueId");let e=[];return e.push(t.provider),e.push("issue"),e.push("1"),t.provider==="bitbucketServer"?e.push(t.domain):e.push(""),e.push(t.repoId),e.push(t.entityId),JSON.stringify(e)}decode(t){if(t.length<6)throw new Error("Invalid Bitbucket DevOps issue uniqueId, check version");return{provider:t[0],entityType:t[1],version:t[2],domain:t[3]==""?null:t[3],resourceId:null,accountOrOrgId:null,organizationName:null,projectId:null,repoId:t[4],entityId:t[5]}}};var yt=class{constructor(){}validate(t){if(!t.repoId)throw new Error("repoId is required");if(!t.entityId)throw new Error("entityId is required")}encode(t){if(this.validate(t),!t.repoId||!t.entityId)throw new Error("Missing required fields for Bitbucket DevOps pull request uniqueId");let e=[];return e.push(t.provider),e.push("pr"),e.push("1"),t.provider==="bitbucketServer"?e.push(t.domain):e.push(""),e.push(t.repoId),e.push(t.entityId),JSON.stringify(e)}decode(t){if(t.length<6)throw new Error("Invalid Bitbucket DevOps pull request uniqueId, check version");return{provider:t[0],entityType:t[1],version:t[2],domain:t[3]==""?null:t[3],resourceId:null,accountOrOrgId:null,organizationName:null,projectId:null,repoId:t[4],entityId:t[5]}}};var Pt=class{constructor(){}validate(t){if(!t.entityId)throw new Error("entityId is required")}encode(t){if(this.validate(t),!t.entityId)throw new Error("Missing required fields for Github issue uniqueId");let e=[];return e.push(t.provider),e.push("issue"),e.push("1"),t.provider==="githubEnterprise"?e.push(t.domain):e.push(""),e.push(t.entityId),JSON.stringify(e)}decode(t){if(t.length<5)throw new Error("Invalid Github issue uniqueId, check version");return{provider:t[0],entityType:t[1],version:t[2],domain:t[3]==""?null:t[3],resourceId:null,accountOrOrgId:null,organizationName:null,projectId:null,repoId:null,entityId:t[4]}}};var wt=class{constructor(){}validate(t){if(!t.entityId)throw new Error("entityId is required")}encode(t){if(this.validate(t),!t.entityId)throw new Error("Missing required fields for Github pull request uniqueId");let e=[];return e.push(t.provider),e.push("pr"),e.push("1"),t.provider==="githubEnterprise"?e.push(t.domain):e.push(""),e.push(t.entityId),JSON.stringify(e)}decode(t){if(t.length<5)throw new Error("Invalid Github pull request uniqueId, check version");return{provider:t[0],entityType:t[1],version:t[2],domain:t[3]==""?null:t[3],resourceId:null,accountOrOrgId:null,organizationName:null,projectId:null,repoId:null,entityId:t[4]}}};var qt=class{constructor(){}validate(t){if(!t.entityId)throw new Error("entityId is required")}encode(t){if(this.validate(t),!t.entityId)throw new Error("Missing required fields for Gitlab issue uniqueId");let e=[];return e.push(t.provider),e.push("issue"),e.push("1"),t.provider==="gitlabSelfHosted"?e.push(t.domain):e.push(""),e.push(t.entityId),JSON.stringify(e)}decode(t){if(t.length<5)throw new Error("Invalid Gitlab issue uniqueId, check version");return{provider:t[0],entityType:t[1],version:t[2],domain:t[3]==""?null:t[3],resourceId:null,accountOrOrgId:null,organizationName:null,projectId:null,repoId:null,entityId:t[4]}}};var vt=class{constructor(){}validate(t){if(!t.entityId)throw new Error("entityId is required")}encode(t){if(this.validate(t),!t.entityId)throw new Error("Missing required fields for Gitlab pull request uniqueId");let e=[];return e.push(t.provider),e.push("pr"),e.push("1"),t.provider==="gitlabSelfHosted"?e.push(t.domain):e.push(""),e.push(t.entityId),JSON.stringify(e)}decode(t){if(t.length<5)throw new Error("Invalid Gitlab pull request uniqueId, check version");return{provider:t[0],entityType:t[1],version:t[2],domain:t[3]==""?null:t[3],resourceId:null,accountOrOrgId:null,organizationName:null,projectId:null,repoId:null,entityId:t[4]}}};var Et=class{constructor(){}validate(t){if(!t.projectId)throw new Error("projectId is required");if(!t.entityId)throw new Error("entityId is required")}encode(t){if(this.validate(t),!t.projectId||!t.entityId)throw new Error("Missing required fields for Jira issue uniqueId");let e=[];return e.push(t.provider),e.push("issue"),e.push("1"),t.provider=="jira"?(e.push(""),e.push(t.resourceId)):(e.push(t.domain),e.push("")),e.push(t.projectId),e.push(t.entityId),JSON.stringify(e)}decode(t){if(t.length<7)throw new Error("Invalid Jira issue uniqueId, check version");return{provider:t[0],entityType:t[1],version:t[2],domain:t[3]==""?null:t[3],resourceId:t[4]==""?null:t[4],accountOrOrgId:null,organizationName:null,projectId:t[5],repoId:null,entityId:t[6]}}};var St=class{constructor(){}validate(t){if(!t.accountOrOrgId)throw new Error("accountOrOrgId is required");if(!t.projectId)throw new Error("projectId is required");if(!t.entityId)throw new Error("entityId is required")}encode(t){if(this.validate(t),!t.accountOrOrgId||!t.projectId||!t.entityId)throw new Error("Missing required fields for Trello issue uniqueId");let e=[];return e.push("trello"),e.push("issue"),e.push("1"),e.push(""),e.push(t.accountOrOrgId),e.push(t.projectId),e.push(t.entityId),JSON.stringify(e)}decode(t){if(t.length<7)throw new Error("Invalid Trello issue uniqueId, check version");return{provider:t[0],entityType:t[1],version:t[2],domain:t[3]==""?null:t[3],resourceId:null,accountOrOrgId:t[4],organizationName:null,projectId:t[5],repoId:null,entityId:t[6]}}};var Ct=(s,t)=>{if(t!=="issue"&&t!=="pr")throw new Error("unknown entityType");switch(s){case"azure":case"azureDevOpsServer":return t==="pr"?new It:new Rt;case"bitbucket":case"bitbucketServer":return t==="pr"?new yt:new bt;case"github":case"githubEnterprise":return t==="pr"?new wt:new Pt;case"gitlab":case"gitlabSelfHosted":return t==="pr"?new vt:new qt;case"jira":case"jiraServer":if(t==="pr")throw new Error("EntityType PullRequest is not valid for Jira");return new Et;case"trello":if(t==="pr")throw new Error("EntityType PullRequest is not valid for Jira");return new St;default:throw new Error("unknown provider")}},ii=s=>{if(!s.entityType)throw new Error("entityType is required");if(!s.provider)throw new Error("provider is required");if(!s.entityId)throw new Error("entityID is required")},ai=s=>{if(s.version==="0"){ii(s);return}Ct(s.provider,s.entityType).validate(s)},ui=s=>Ct(s.provider,s.entityType).encode(s),vr=s=>{let t=JSON.parse(s);if(!t||!t.length)throw new Error("invalid issue unique id");return Ct(t[0],t[1]).decode(t)},li=(s,t,e)=>{if(!e)throw new Error("entityID is required");try{let r=JSON.parse(e);if(!r||!r.length)throw new Error("Invalid pull request uniqueId");let n=[s,t,"0",...r];return Ct(s,t).decode(n)}catch{return{provider:s,entityType:t,version:"0",domain:"",resourceId:null,accountOrOrgId:null,organizationName:null,projectId:null,repoId:null,entityId:e}}};var At={};H(At,{CHANGES_REQUESTED_ACTION_CATEGORY:()=>Js,CHANGES_REQUESTED_BUCKET_ID:()=>Lr,CONFLICTS_ACTION_CATEGORY:()=>Hs,CONFLICTS_BUCKET_ID:()=>Ar,DRAFT_ACTION_CATEGORY:()=>Zs,DRAFT_BUCKET_ID:()=>Tr,FAILING_CI_ACTION_CATEGORY:()=>Ws,FAILING_CI_BUCKET_ID:()=>Dr,NEEDS_MY_REVIEW_ACTION_CATEGORY:()=>Vs,NEEDS_MY_REVIEW_BUCKET_ID:()=>$r,OTHER_ACTION_CATEGORY:()=>Ys,OTHER_BUCKET_ID:()=>Or,PINNED_BUCKET_ID:()=>Er,READY_TO_MERGE_ACTION_CATEGORY:()=>zs,READY_TO_MERGE_BUCKET_ID:()=>Sr,REVIEWER_COMMENTED_ACTION_CATEGORY:()=>Ks,REVIEWER_COMMENTED_BUCKET_ID:()=>Gr,SNOOZED_BUCKET_ID:()=>_r,UNASSIGNED_REVIEWERS_ACTION_CATEGORY:()=>Ms,UNASSIGNED_REVIEWERS_BUCKET_ID:()=>Cr,WAITING_FOR_REVIEW_ACTION_CATEGORY:()=>Xs,WAITING_FOR_REVIEW_BUCKET_ID:()=>Ur,getActionablePullRequests:()=>en,groupPullRequestsByAssignee:()=>ci,groupPullRequestsByAuthor:()=>mi,groupPullRequestsByGitKrakenTeam:()=>Ri,groupPullRequestsByRepo:()=>di,groupPullRequestsByReviewer:()=>gi,groupPullRequestsByWorkspace:()=>fi,groupPullRequestsIntoBuckets:()=>pi});var z=(s,t,e,r)=>({id:s,faIconName:e,name:t,priority:r,pullRequests:[]}),Er="pinned",Sr="readyToMerge",Cr="unassignedReviewers",Dr="failingCI",Ar="conflicts",$r="needsMyReview",Lr="changesRequested",Gr="reviewerCommented",Ur="waitingForReview",Tr="draft",Or="other",_r="snoozed",zs="readyToMerge",Ms="unassignedReviewers",Ws="failingCI",Hs="conflicts",Vs="needsMyReview",Js="changesRequested",Ks="reviewerCommented",Xs="waitingForReview",Zs="draft",Ys="other",en=(s,t,e)=>s.map(r=>{let o={...r,...{suggestedActionCategory:Ys,priority:1e3,viewer:{canMerge:!1,isAuthor:!1,isAssignee:!1,isReviewer:!1,shouldMerge:!1,shouldAssignReviewer:!1,waitingOnReviews:!1,shouldReview:!1},failingCI:!1,hasConflicts:!1,changeRequestReviewCount:0,codeSuggestionsCount:0,commentReviewCount:0,approvalReviewCount:0}};t&&(o.viewer.isAuthor=r.author?.id===t.id,o.viewer.isAssignee=r.assignees?.some(u=>u.id===t.id)??!1,o.viewer.isReviewer=r.reviews?.some(u=>u.reviewer.id===t.id)??!1),o.viewer.canMerge=r.permissions?.canMerge??!0,o.hasConflicts=r.mergeableState==="CONFLICTS",o.failingCI=r.headCommit?.buildStatuses?.some(u=>u.state==="ERROR"||u.state==="FAILED")||r.mergeableState==="FAILING_CHECKS",o.commentReviewCount=r.reviews?.filter(u=>u.state==="COMMENTED").length??0,o.approvalReviewCount=r.reviews?.filter(u=>u.state==="APPROVED").length??0,o.changeRequestReviewCount=r.reviews?.filter(u=>u.state==="CHANGES_REQUESTED").length??0;let i=e?.enrichedItemsByUniqueId?.[r.uuid];i!=null&&(o.viewer.enrichedItems=i,i.some(u=>u.type==="pin")&&(o.viewer.pinned=!0,o.priority-=800),i.some(u=>u.type==="snooze")&&(o.viewer.snoozed=!0));let a=e?.codeSuggestionsCountByPrUuid?.[r.uuid]?.count||0;return a&&(o.codeSuggestionsCount=a),(!t||o.viewer.isAuthor||o.viewer.isAssignee&&!o.viewer.isReviewer)&&o.viewer.canMerge&&!o.isDraft&&!o.failingCI&&r.mergeableState==="MERGEABLE"&&(o.viewer.shouldMerge=!0,o.suggestedActionCategory=zs),(!t||o.viewer.isAuthor)&&r.isDraft&&(o.suggestedActionCategory=Zs),(!t||o.viewer.isAuthor)&&r.reviewDecision==="REVIEW_REQUESTED"&&(o.suggestedActionCategory=Xs,o.viewer.waitingOnReviews=!0),(!t||o.viewer.isAuthor)&&r.reviewDecision==="COMMENTED"&&(o.suggestedActionCategory=Ks),(!t||o.viewer.isAuthor)&&o.failingCI&&(o.suggestedActionCategory=Ws),(!t||o.viewer.isAuthor)&&o.hasConflicts&&(o.suggestedActionCategory=Hs),(!t||o.viewer.isAuthor)&&(r.reviewDecision==="CHANGES_REQUESTED"||o.codeSuggestionsCount>0)&&(o.suggestedActionCategory=Js),(!t||o.viewer.isAuthor)&&!r.reviews?.length&&(o.suggestedActionCategory=Ms,o.viewer.shouldAssignReviewer=!0),t&&r.reviews?.some(u=>u.reviewer.id===t.id&&u.state==="REVIEW_REQUESTED")&&(o.suggestedActionCategory=Vs,o.viewer.shouldReview=!0),o}),pi=(s,t,e)=>{let r={pinned:z(Er,"Pinned","thumbtack",e?.bucketPriorityOverride?.pinned??-1),readyToMerge:z(Sr,"Ready to Merge","code-merge",e?.bucketPriorityOverride?.readyToMerge??0),unassignedReviewers:z(Cr,"Unassigned Reviewers","user-plus",e?.bucketPriorityOverride?.unassignedReviewers??1),failingCI:z(Dr,"Failing CI","circle-x",e?.bucketPriorityOverride?.failingCI??2),conflicts:z(Ar,"Resolve Conflicts","triangle-exclamation",e?.bucketPriorityOverride?.conflicts??3),needsMyReview:z($r,"Needs My Review","eye",e?.bucketPriorityOverride?.needsMyReview??4),changesRequested:z(Lr,"Suggested Changes","file-plus",e?.bucketPriorityOverride?.changesRequested??5),reviewerCommented:z(Gr,"Reviewer Commented","comment",e?.bucketPriorityOverride?.reviewerCommented??6),waitingForReview:z(Ur,"Waiting for Review","circle-pause",e?.bucketPriorityOverride?.waitingForReview??7),draft:z(Tr,"Draft","compass-drafting",e?.bucketPriorityOverride?.draft??8),other:z(Or,"Other","ellipsis",e?.bucketPriorityOverride?.other??9),snoozed:z(_r,"Snoozed","snooze",e?.bucketPriorityOverride?.snoozed??10)},o=en(s,t,e).reduce((i,a)=>(i[a.uuid]=a,i),{});return s.forEach(i=>{let a=o[i.uuid],u=!0;if(a.viewer.snoozed){r[_r].pullRequests.push(i);return}a.viewer.pinned&&r[Er].pullRequests.push(i),(!t||a.viewer.isAuthor||a.viewer.isAssignee&&!a.viewer.isReviewer)&&!a.isDraft&&a.viewer.canMerge&&a.mergeableState==="MERGEABLE"&&(r[Sr].pullRequests.push(i),u=!1),a.viewer.shouldAssignReviewer&&(r[Cr].pullRequests.push(i),u=!1),(!t||a.viewer.isAuthor)&&a.failingCI&&(r[Dr].pullRequests.push(i),u=!1),(!t||a.viewer.isAuthor)&&a.hasConflicts&&(r[Ar].pullRequests.push(i),u=!1),a.viewer.shouldReview&&(r[$r].pullRequests.push(i),u=!1),(!t||a.viewer.isAuthor)&&(a.reviewDecision==="CHANGES_REQUESTED"||a.codeSuggestionsCount>0)&&(r[Lr].pullRequests.push(i),u=!1),(!t||a.viewer.isAuthor)&&a.reviewDecision==="COMMENTED"&&(r[Gr].pullRequests.push(i),u=!1),(!t||a.viewer.isAuthor)&&a.reviewDecision==="REVIEW_REQUESTED"&&(r[Ur].pullRequests.push(i),u=!1),a.isDraft&&(r[Tr].pullRequests.push(i),u=!1),u&&r[Or].pullRequests.push(i)}),Object.values(r).forEach(i=>{i.pullRequests.sort((a,u)=>o[a.uuid].priority-o[u.uuid].priority)}),r},di=s=>{let t={};return s.forEach(e=>{let r=e.repository.id;t[r]?t[r].pullRequests.push(e):t[r]={name:e.repository.name,priority:0,pullRequests:[e],id:r}}),de(t)},ci=s=>{let t="internal-no-assignees",e={[t]:{name:"No assignees",priority:-1,pullRequests:[],id:t,faIconName:"user-slash"}};return s.forEach(r=>{r.assignees&&r.assignees.length?r.assignees.forEach(n=>{let o=n.id;e[o]?e[o].pullRequests.push(r):e[o]={accountData:n,name:Ne(n,`Unknown Assignee ${Object.keys(e).length}`),priority:0,pullRequests:[r],id:o}}):e[t].pullRequests.push(r)}),de(e)},mi=s=>{let t="internal-no-author",e={[t]:{name:"No author",priority:-1,pullRequests:[],id:t,faIconName:"user-slash"}};return s.forEach(r=>{if(r.author){let n=r.author.id;e[n]?e[n].pullRequests.push(r):e[n]={accountData:r.author,name:Ne(r.author,`Unknown Author ${Object.keys(e).length}`),priority:0,pullRequests:[r],id:n}}else e[t].pullRequests.push(r)}),de(e)},gi=s=>{let t="internal-no-reviewer",e={[t]:{name:"No reviewers",priority:-1,pullRequests:[],id:t,faIconName:"user-slash"}};return s.forEach(r=>{r.reviews&&r.reviews.length?r.reviews.forEach(n=>{let o=n.reviewer.id;e[o]?e[o].pullRequests.push(r):e[o]={accountData:n.reviewer,name:Ne(n.reviewer,`Unknown Reviewer ${Object.keys(e).length}`),priority:0,pullRequests:[r],id:o}}):e[t].pullRequests.push(r)}),de(e)},hi=s=>s.azureProject?[`${s.azureProject}-${s.azureOrganizationId}`]:s.providerData?.repositories.nodes.map(t=>`${s.provider}-${t.repositoryId}`)??[],fi=(s,t)=>{let e="internal-no-workspace",r={[e]:{name:"No workspace",priority:-1,pullRequests:[],id:e,faIconName:"folder-xmark"}};if(t.length){let n=t.reduce((o,i)=>(hi(i).forEach(u=>{o[u]?o[u].push(i):o[u]=[i]}),o),{});s.forEach(o=>{let{provider:i}=vr(o.uuid),a=i==="github"?o.repository.graphQLId:o.repository.id,u=i==="azure"?[`${i}-${a}`,`${o.repository.project}-${o.repository.owner.login}`]:[`${i}-${a}`],l=!1,p=u.reduce((d,c)=>n[c]?d.concat(n[c]):d,[]);p?.length&&p.forEach(d=>{l=!0;let c=d.id;r[c]?r[c].pullRequests.push(o):r[c]={name:d.name,priority:0,pullRequests:[o],id:c,faIconName:"folder"}}),l||r[e].pullRequests.push(o)})}else r[e].pullRequests=s;return de(r)},Ri=(s,t,e,r)=>{let n="internal-no-team",o={[n]:{name:"No team",priority:-1,pullRequests:[],id:n}};return r.length?s.forEach(i=>{let a=!1,u=new Set;u.add(i.author?.id),i.assignees?.forEach(l=>u.add(l.id)),i.reviews?.forEach(l=>u.add(l.reviewer.id)),r.forEach(l=>{if(l.members?.some(d=>{let c=t[d.id]?.[e]?.providerID;return c&&u.has(c)})){a=!0;let d=l.id;o[d]?o[d].pullRequests.push(i):o[d]={name:l.name,priority:0,pullRequests:[i],id:d,teamData:l}}}),a||o[n].pullRequests.push(i)}):o[n].pullRequests=s,de(o)};var $t={};H($t,{getPullRequestRank:()=>Ii});var Ii=(s,t,e)=>{let r=0,n,o;return s.reviews?.forEach(i=>{i.reviewer.id===t&&(n=i.state),i.state==="CHANGES_REQUESTED"?o="CHANGES_REQUESTED":i.state==="APPROVED"&&o!=="CHANGES_REQUESTED"&&(o="APPROVED")}),o||(o="REVIEW_REQUESTED"),s.author?.id===t?r+=1e3:s.assignees?.find(i=>i.id===t)?r+=900:n==="REVIEW_REQUESTED"?r+=800:e&&(r+=700),o==="APPROVED"?s.mergeableState==="MERGEABLE"?r+=100:s.mergeableState==="CONFLICTS"?r+=90:r+=80:o=="CHANGES_REQUESTED"&&(r+=70),r};var Lt={};H(Lt,{default:()=>bi});var bi={};var Gt={};H(Gt,{default:()=>yi});var yi={};var Ut={};H(Ut,{default:()=>Pi});var Pi={};var tn=s=>{let t={request:s?.request};return{azureDevOps:new Re({...t,...s?.azureDevOps}),bitbucket:new Ie({...t,...s?.bitbucket}),bitbucketServer:new be({...t,...s?.bitbucketServer}),github:new ye({...t,...s?.github}),gitlab:new we({...t,...s?.gitlab}),jira:new qe({...t,...s?.jira}),jiraServer:new ve({...t,...s?.jiraServer}),linear:new Ee({...t,...s?.linear}),trello:new Se({...t,...s?.trello})}};var rn=(i=>(i.Conflicts="conflicts",i.Failure="failure",i.NotSet="notSet",i.Queued="queued",i.RejectedByPolicy="rejectedByPolicy",i.Succeeded="succeeded",i))(rn||{});var sn=(e=>(e.Completed="COMPLETED",e.NotPlanned="NOT_PLANNED",e))(sn||{});var wi=tn;var qi={azureDevOps:ht,bitbucket:ft,bitbucketServer:We,github:$t,gitlab:Lt,gitProvider:At,jira:Gt,trello:Ut,entityIdentifier:Dt};
|
|
1596
|
+
`,p=(await this.rawRequest(e,l,{first:Ws,after:i})).data?.issues;return p?{data:await Bt(p.nodes.map(Er)),pageInfo:{hasNextPage:p.pageInfo.hasNextPage,endCursor:p.pageInfo.endCursor??null}}:{data:[],pageInfo:{hasNextPage:!1,endCursor:null}}}};var Z="https://api.trello.com",Ks=1e3,Y=(s,t)=>({...R(t),Authorization:`OAuth oauth_consumer_key="${s}", oauth_token="${t}"`}),mi=s=>({id:s.id,username:s.username,url:s.url,name:s.fullName,email:s.email,avatarUrl:s.avatarUrl}),gi=(s,t)=>{let e=new Date(1e3*parseInt(s.id.substring(0,8),16));return{id:s.id,commentCount:s.badges.comments,number:s.idShort.toString(),title:s.name,url:s.url,closedDate:null,createdDate:new Date(e.toISOString()),author:null,updatedDate:new Date(s.dateLastActivity),assignees:s.members.map(r=>({id:r.id,username:r.username,name:r.fullName,email:null,avatarUrl:r.avatarUrl,url:null})),description:null,state:t[s.idList??""]?{id:s.idList,name:t[s.idList].name,color:null}:null,type:null,repository:null,upvoteCount:s.badges.votes,labels:s.labels.map(r=>({color:r.color,description:null,id:r.id,name:r.name}))}},$e=class extends M{async getCurrentUser(t,e={}){let r=await this.config.request({url:`${e.baseUrl||Z}/1/members/me`,headers:Y(t.appKey,e.token||this.config.token)});return{data:{name:r.body.fullName,email:r.body.email,avatarUrl:r.body.avatarHash?`https://trello-members.s3.amazonaws.com/${r.body.id}/${r.body.avatarHash}/50.png`:null,id:r.body.id,username:r.body.username,url:r.body.url}}}async getBoardsForCurrentUser(t,e={}){return{data:(await this.config.request({url:`${e.baseUrl||Z}/1/members/me/boards?fields=name&filter=open`,headers:Y(t.appKey,e.token||this.config.token)})).body.map(n=>({id:n.id,name:n.name}))}}async getListsForTrelloBoard(t,e={}){let{appKey:r,boardId:n}=t;return{data:(await this.config.request({url:`${e.baseUrl||Z}/1/boards/${n}/lists`,headers:Y(r,e.token||this.config.token)})).body}}async getAccountForId(t,e={}){let{appKey:r,memberId:n}=t,o=await this.config.request({url:`${e.baseUrl||Z}/1/members/${n}`,headers:Y(r,e.token||this.config.token)});return{data:mi(o.body)}}async getAccountsForTrelloBoard(t,e={}){let{appKey:r,boardId:n}=t;return{data:(await this.config.request({url:`${e.baseUrl||Z}/1/boards/${n}/members`,headers:Y(r,e.token||this.config.token)})).body.map(i=>({id:i.id,name:i.fullName,username:i.username,email:null,avatarUrl:null,url:null}))}}async getIssuesForBoard(t,e={}){let r=["-is:archived","sort:edited"],{appKey:n,boardId:o,filterText:i,assigneeLogins:a,labelNamesOrColors:u,trelloBoardListsById:l}=t||{};a&&r.push("@me"),u&&u.forEach(g=>r.push(`label:"${g}"`));let d=`${i?`${i}`:""}${r.join(" ")} board:${o}`,p=await this.config.request({url:`${e.baseUrl||Z}/1/search?query=${d}&cards_limit=${Ks}&card_members=true`,headers:Y(n,e.token||this.config.token)}),c=p.body.cards.length>=Ks?"unknown":"complete";return{data:p.body.cards.map(g=>gi(g,l||{})),metadata:be(c)}}async updateIssue(t,e,r,n){return await this.config.request({method:"PUT",url:`${n.baseUrl||Z}/1/cards/${e.id}?${r}`,headers:Y(t,n.token||this.config.token)})}async setIssueStatus(t,e={}){let{appKey:r,issue:n,status:o}=t;if(!o.id)throw new Error('Trello requires a status "id" for this function.');let i=`idList=${o.id}`;if(!(await this.updateIssue(r,n,i,e)).body.id)throw new Error("Could not set issue status")}async setIssueAssignees(t,e={}){let{appKey:r,issue:n,assignees:o}=t,i=o.map(l=>l.id),a=`idMembers=${encodeURIComponent(i.join(","))}`;if(!(await this.updateIssue(r,n,a,e)).body.id)throw new Error("Could not set issue status")}async setIssueLabels(t,e={}){let{appKey:r,issue:n,labels:o}=t,i=o.map(u=>u.id).join(",");if(!(await this.config.request({method:"PUT",url:`${e.baseUrl||Z}/1/cards/${n.id}?idLabels=${encodeURIComponent(i)}`,headers:Y(r,e.token||this.config.token)})).body.id)throw new Error("Could not set issue status")}async setIssueArchived(t,e={}){let{appKey:r,issue:n,archived:o}=t;if(!(await this.config.request({method:"PUT",url:`${e.baseUrl||Z}/1/cards/${n.id}?closed=${o}`,headers:Y(r,e.token||this.config.token)})).body.id)throw new Error("Could not update issue archived status")}async archiveIssue(t,e={}){await this.setIssueArchived({...t,archived:!0},e)}async unArchiveIssue(t,e={}){await this.setIssueArchived({...t,archived:!1},e)}async getLabelsForBoard(t,e={}){let{appKey:r,boardId:n}=t;return{data:(await this.config.request({url:`${e.baseUrl||Z}/1/boards/${n}/labels`,headers:Y(r,e.token||this.config.token)})).body.map(i=>({color:i.color,description:null,id:i.id,name:i.name}))}}};var It={};H(It,{default:()=>hi});var hi={};var bt={};H(bt,{default:()=>fi});var fi={};var Lt={};H(Lt,{decode:()=>Cr,decodeV0:()=>yi,encode:()=>bi,validate:()=>Ii});var B=(e=>(e.Zero="0",e.One="1",e))(B||{}),j=(e=>(e.PullRequest="pr",e.Issue="issue",e))(j||{}),N=(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))(N||{});var yt=class{constructor(){}validate(t){if(!t.organizationName)throw new Error("organizationName is required");if(!t.projectId)throw new Error("projectId is required");if(!t.entityId)throw new Error("issueId is required")}encode(t){if(this.validate(t),!t.organizationName||!t.projectId||!t.entityId)throw new Error("Missing required fields for Azure DevOps issue uniqueId");let e=[];return e.push(t.provider),e.push("issue"),e.push("1"),t.provider==="azureDevOpsServer"?e.push(t.domain):e.push(""),e.push(t.organizationName),e.push(t.projectId),e.push(t.entityId),JSON.stringify(e)}decode(t){if(t.length<7)throw new Error("Invalid Azure DevOps issue uniqueId, check version");return{provider:t[0],entityType:t[1],version:t[2],domain:t[3]==""?null:t[3],resourceId:null,accountOrOrgId:null,organizationName:t[4],projectId:t[5],repoId:null,entityId:t[6]}}};var Pt=class{constructor(){}validate(t){if(!t.organizationName)throw new Error("organizationName is required");if(!t.projectId)throw new Error("projectId is required");if(!t.repoId)throw new Error("repoId is required");if(!t.entityId)throw new Error("entityId is required")}encode(t){if(this.validate(t),!t.organizationName||!t.projectId||!t.repoId||!t.entityId)throw new Error("Missing required fields for Azure DevOps pull request uniqueId");let e=[];return e.push(t.provider),e.push("pr"),e.push("1"),t.provider==="azureDevOpsServer"?e.push(t.domain):e.push(""),e.push(t.organizationName),e.push(t.projectId),e.push(t.repoId),e.push(t.entityId),JSON.stringify(e)}decode(t){if(t.length<8)throw new Error("Invalid Azure DevOps pull request uniqueId, check version");return{provider:t[0],entityType:t[1],version:t[2],domain:t[3]==""?null:t[3],resourceId:null,accountOrOrgId:null,organizationName:t[4],projectId:t[5],repoId:t[6],entityId:t[7]}}};var wt=class{constructor(){}validate(t){if(!t.repoId)throw new Error("repoId is required");if(!t.entityId)throw new Error("issueId is required")}encode(t){if(this.validate(t),!t.repoId||!t.entityId)throw new Error("Missing required fields for Bitbucket DevOps issue uniqueId");let e=[];return e.push(t.provider),e.push("issue"),e.push("1"),t.provider==="bitbucketServer"?e.push(t.domain):e.push(""),e.push(t.repoId),e.push(t.entityId),JSON.stringify(e)}decode(t){if(t.length<6)throw new Error("Invalid Bitbucket DevOps issue uniqueId, check version");return{provider:t[0],entityType:t[1],version:t[2],domain:t[3]==""?null:t[3],resourceId:null,accountOrOrgId:null,organizationName:null,projectId:null,repoId:t[4],entityId:t[5]}}};var qt=class{constructor(){}validate(t){if(!t.repoId)throw new Error("repoId is required");if(!t.entityId)throw new Error("entityId is required")}encode(t){if(this.validate(t),!t.repoId||!t.entityId)throw new Error("Missing required fields for Bitbucket DevOps pull request uniqueId");let e=[];return e.push(t.provider),e.push("pr"),e.push("1"),t.provider==="bitbucketServer"?e.push(t.domain):e.push(""),e.push(t.repoId),e.push(t.entityId),JSON.stringify(e)}decode(t){if(t.length<6)throw new Error("Invalid Bitbucket DevOps pull request uniqueId, check version");return{provider:t[0],entityType:t[1],version:t[2],domain:t[3]==""?null:t[3],resourceId:null,accountOrOrgId:null,organizationName:null,projectId:null,repoId:t[4],entityId:t[5]}}};var vt=class{constructor(){}validate(t){if(!t.entityId)throw new Error("entityId is required")}encode(t){if(this.validate(t),!t.entityId)throw new Error("Missing required fields for Github issue uniqueId");let e=[];return e.push(t.provider),e.push("issue"),e.push("1"),t.provider==="githubEnterprise"?e.push(t.domain):e.push(""),e.push(t.entityId),JSON.stringify(e)}decode(t){if(t.length<5)throw new Error("Invalid Github issue uniqueId, check version");return{provider:t[0],entityType:t[1],version:t[2],domain:t[3]==""?null:t[3],resourceId:null,accountOrOrgId:null,organizationName:null,projectId:null,repoId:null,entityId:t[4]}}};var Et=class{constructor(){}validate(t){if(!t.entityId)throw new Error("entityId is required")}encode(t){if(this.validate(t),!t.entityId)throw new Error("Missing required fields for Github pull request uniqueId");let e=[];return e.push(t.provider),e.push("pr"),e.push("1"),t.provider==="githubEnterprise"?e.push(t.domain):e.push(""),e.push(t.entityId),JSON.stringify(e)}decode(t){if(t.length<5)throw new Error("Invalid Github pull request uniqueId, check version");return{provider:t[0],entityType:t[1],version:t[2],domain:t[3]==""?null:t[3],resourceId:null,accountOrOrgId:null,organizationName:null,projectId:null,repoId:null,entityId:t[4]}}};var St=class{constructor(){}validate(t){if(!t.entityId)throw new Error("entityId is required")}encode(t){if(this.validate(t),!t.entityId)throw new Error("Missing required fields for Gitlab issue uniqueId");let e=[];return e.push(t.provider),e.push("issue"),e.push("1"),t.provider==="gitlabSelfHosted"?e.push(t.domain):e.push(""),e.push(t.entityId),JSON.stringify(e)}decode(t){if(t.length<5)throw new Error("Invalid Gitlab issue uniqueId, check version");return{provider:t[0],entityType:t[1],version:t[2],domain:t[3]==""?null:t[3],resourceId:null,accountOrOrgId:null,organizationName:null,projectId:null,repoId:null,entityId:t[4]}}};var Ct=class{constructor(){}validate(t){if(!t.entityId)throw new Error("entityId is required")}encode(t){if(this.validate(t),!t.entityId)throw new Error("Missing required fields for Gitlab pull request uniqueId");let e=[];return e.push(t.provider),e.push("pr"),e.push("1"),t.provider==="gitlabSelfHosted"?e.push(t.domain):e.push(""),e.push(t.entityId),JSON.stringify(e)}decode(t){if(t.length<5)throw new Error("Invalid Gitlab pull request uniqueId, check version");return{provider:t[0],entityType:t[1],version:t[2],domain:t[3]==""?null:t[3],resourceId:null,accountOrOrgId:null,organizationName:null,projectId:null,repoId:null,entityId:t[4]}}};var Dt=class{constructor(){}validate(t){if(!t.projectId)throw new Error("projectId is required");if(!t.entityId)throw new Error("entityId is required")}encode(t){if(this.validate(t),!t.projectId||!t.entityId)throw new Error("Missing required fields for Jira issue uniqueId");let e=[];return e.push(t.provider),e.push("issue"),e.push("1"),t.provider=="jira"?(e.push(""),e.push(t.resourceId)):(e.push(t.domain),e.push("")),e.push(t.projectId),e.push(t.entityId),JSON.stringify(e)}decode(t){if(t.length<7)throw new Error("Invalid Jira issue uniqueId, check version");return{provider:t[0],entityType:t[1],version:t[2],domain:t[3]==""?null:t[3],resourceId:t[4]==""?null:t[4],accountOrOrgId:null,organizationName:null,projectId:t[5],repoId:null,entityId:t[6]}}};var At=class{constructor(){}validate(t){if(!t.accountOrOrgId)throw new Error("accountOrOrgId is required");if(!t.projectId)throw new Error("projectId is required");if(!t.entityId)throw new Error("entityId is required")}encode(t){if(this.validate(t),!t.accountOrOrgId||!t.projectId||!t.entityId)throw new Error("Missing required fields for Trello issue uniqueId");let e=[];return e.push("trello"),e.push("issue"),e.push("1"),e.push(""),e.push(t.accountOrOrgId),e.push(t.projectId),e.push(t.entityId),JSON.stringify(e)}decode(t){if(t.length<7)throw new Error("Invalid Trello issue uniqueId, check version");return{provider:t[0],entityType:t[1],version:t[2],domain:t[3]==""?null:t[3],resourceId:null,accountOrOrgId:t[4],organizationName:null,projectId:t[5],repoId:null,entityId:t[6]}}};var $t=(s,t)=>{if(t!=="issue"&&t!=="pr")throw new Error("unknown entityType");switch(s){case"azure":case"azureDevOpsServer":return t==="pr"?new Pt:new yt;case"bitbucket":case"bitbucketServer":return t==="pr"?new qt:new wt;case"github":case"githubEnterprise":return t==="pr"?new Et:new vt;case"gitlab":case"gitlabSelfHosted":return t==="pr"?new Ct:new St;case"jira":case"jiraServer":if(t==="pr")throw new Error("EntityType PullRequest is not valid for Jira");return new Dt;case"trello":if(t==="pr")throw new Error("EntityType PullRequest is not valid for Jira");return new At;default:throw new Error("unknown provider")}},Ri=s=>{if(!s.entityType)throw new Error("entityType is required");if(!s.provider)throw new Error("provider is required");if(!s.entityId)throw new Error("entityID is required")},Ii=s=>{if(s.version==="0"){Ri(s);return}$t(s.provider,s.entityType).validate(s)},bi=s=>$t(s.provider,s.entityType).encode(s),Cr=s=>{let t=JSON.parse(s);if(!t||!t.length)throw new Error("invalid issue unique id");return $t(t[0],t[1]).decode(t)},yi=(s,t,e)=>{if(!e)throw new Error("entityID is required");try{let r=JSON.parse(e);if(!r||!r.length)throw new Error("Invalid pull request uniqueId");let n=[s,t,"0",...r];return $t(s,t).decode(n)}catch{return{provider:s,entityType:t,version:"0",domain:"",resourceId:null,accountOrOrgId:null,organizationName:null,projectId:null,repoId:null,entityId:e}}};var Ut={};H(Ut,{CHANGES_REQUESTED_ACTION_CATEGORY:()=>rn,CHANGES_REQUESTED_BUCKET_ID:()=>Tr,CONFLICTS_ACTION_CATEGORY:()=>en,CONFLICTS_BUCKET_ID:()=>Ur,DRAFT_ACTION_CATEGORY:()=>on,DRAFT_BUCKET_ID:()=>kr,FAILING_CI_ACTION_CATEGORY:()=>Ys,FAILING_CI_BUCKET_ID:()=>Lr,NEEDS_MY_REVIEW_ACTION_CATEGORY:()=>tn,NEEDS_MY_REVIEW_BUCKET_ID:()=>Gr,OTHER_ACTION_CATEGORY:()=>an,OTHER_BUCKET_ID:()=>xr,PINNED_BUCKET_ID:()=>Dr,READY_TO_MERGE_ACTION_CATEGORY:()=>Xs,READY_TO_MERGE_BUCKET_ID:()=>Ar,REVIEWER_COMMENTED_ACTION_CATEGORY:()=>sn,REVIEWER_COMMENTED_BUCKET_ID:()=>Or,SNOOZED_BUCKET_ID:()=>Nr,UNASSIGNED_REVIEWERS_ACTION_CATEGORY:()=>Zs,UNASSIGNED_REVIEWERS_BUCKET_ID:()=>$r,WAITING_FOR_REVIEW_ACTION_CATEGORY:()=>nn,WAITING_FOR_REVIEW_BUCKET_ID:()=>_r,getActionablePullRequests:()=>un,groupPullRequestsByAssignee:()=>qi,groupPullRequestsByAuthor:()=>vi,groupPullRequestsByGitKrakenTeam:()=>Di,groupPullRequestsByRepo:()=>wi,groupPullRequestsByReviewer:()=>Ei,groupPullRequestsByWorkspace:()=>Ci,groupPullRequestsIntoBuckets:()=>Pi});var z=(s,t,e,r)=>({id:s,faIconName:e,name:t,priority:r,pullRequests:[]}),Dr="pinned",Ar="readyToMerge",$r="unassignedReviewers",Lr="failingCI",Ur="conflicts",Gr="needsMyReview",Tr="changesRequested",Or="reviewerCommented",_r="waitingForReview",kr="draft",xr="other",Nr="snoozed",Xs="readyToMerge",Zs="unassignedReviewers",Ys="failingCI",en="conflicts",tn="needsMyReview",rn="changesRequested",sn="reviewerCommented",nn="waitingForReview",on="draft",an="other",un=(s,t,e)=>s.map(r=>{let o={...r,...{suggestedActionCategory:an,priority:1e3,viewer:{canMerge:!1,isAuthor:!1,isAssignee:!1,isReviewer:!1,shouldMerge:!1,shouldAssignReviewer:!1,waitingOnReviews:!1,shouldReview:!1},failingCI:!1,hasConflicts:!1,changeRequestReviewCount:0,codeSuggestionsCount:0,commentReviewCount:0,approvalReviewCount:0}};t&&(o.viewer.isAuthor=r.author?.id===t.id,o.viewer.isAssignee=r.assignees?.some(u=>u.id===t.id)??!1,o.viewer.isReviewer=r.reviews?.some(u=>u.reviewer.id===t.id)??!1),o.viewer.canMerge=r.permissions?.canMerge??!0,o.hasConflicts=r.mergeableState==="CONFLICTS",o.failingCI=r.headCommit?.buildStatuses?.some(u=>u.state==="ERROR"||u.state==="FAILED")||r.mergeableState==="FAILING_CHECKS",o.commentReviewCount=r.reviews?.filter(u=>u.state==="COMMENTED").length??0,o.approvalReviewCount=r.reviews?.filter(u=>u.state==="APPROVED").length??0,o.changeRequestReviewCount=r.reviews?.filter(u=>u.state==="CHANGES_REQUESTED").length??0;let i=e?.enrichedItemsByUniqueId?.[r.uuid];i!=null&&(o.viewer.enrichedItems=i,i.some(u=>u.type==="pin")&&(o.viewer.pinned=!0,o.priority-=800),i.some(u=>u.type==="snooze")&&(o.viewer.snoozed=!0));let a=e?.codeSuggestionsCountByPrUuid?.[r.uuid]?.count||0;return a&&(o.codeSuggestionsCount=a),(!t||o.viewer.isAuthor||o.viewer.isAssignee&&!o.viewer.isReviewer)&&o.viewer.canMerge&&!o.isDraft&&!o.failingCI&&r.mergeableState==="MERGEABLE"&&(o.viewer.shouldMerge=!0,o.suggestedActionCategory=Xs),(!t||o.viewer.isAuthor)&&r.isDraft&&(o.suggestedActionCategory=on),(!t||o.viewer.isAuthor)&&r.reviewDecision==="REVIEW_REQUESTED"&&(o.suggestedActionCategory=nn,o.viewer.waitingOnReviews=!0),(!t||o.viewer.isAuthor)&&r.reviewDecision==="COMMENTED"&&(o.suggestedActionCategory=sn),(!t||o.viewer.isAuthor)&&o.failingCI&&(o.suggestedActionCategory=Ys),(!t||o.viewer.isAuthor)&&o.hasConflicts&&(o.suggestedActionCategory=en),(!t||o.viewer.isAuthor)&&(r.reviewDecision==="CHANGES_REQUESTED"||o.codeSuggestionsCount>0)&&(o.suggestedActionCategory=rn),(!t||o.viewer.isAuthor)&&!r.reviews?.length&&(o.suggestedActionCategory=Zs,o.viewer.shouldAssignReviewer=!0),t&&r.reviews?.some(u=>u.reviewer.id===t.id&&u.state==="REVIEW_REQUESTED")&&(o.suggestedActionCategory=tn,o.viewer.shouldReview=!0),o}),Pi=(s,t,e)=>{let r={pinned:z(Dr,"Pinned","thumbtack",e?.bucketPriorityOverride?.pinned??-1),readyToMerge:z(Ar,"Ready to Merge","code-merge",e?.bucketPriorityOverride?.readyToMerge??0),unassignedReviewers:z($r,"Unassigned Reviewers","user-plus",e?.bucketPriorityOverride?.unassignedReviewers??1),failingCI:z(Lr,"Failing CI","circle-x",e?.bucketPriorityOverride?.failingCI??2),conflicts:z(Ur,"Resolve Conflicts","triangle-exclamation",e?.bucketPriorityOverride?.conflicts??3),needsMyReview:z(Gr,"Needs My Review","eye",e?.bucketPriorityOverride?.needsMyReview??4),changesRequested:z(Tr,"Suggested Changes","file-plus",e?.bucketPriorityOverride?.changesRequested??5),reviewerCommented:z(Or,"Reviewer Commented","comment",e?.bucketPriorityOverride?.reviewerCommented??6),waitingForReview:z(_r,"Waiting for Review","circle-pause",e?.bucketPriorityOverride?.waitingForReview??7),draft:z(kr,"Draft","compass-drafting",e?.bucketPriorityOverride?.draft??8),other:z(xr,"Other","ellipsis",e?.bucketPriorityOverride?.other??9),snoozed:z(Nr,"Snoozed","snooze",e?.bucketPriorityOverride?.snoozed??10)},o=un(s,t,e).reduce((i,a)=>(i[a.uuid]=a,i),{});return s.forEach(i=>{let a=o[i.uuid],u=!0;if(a.viewer.snoozed){r[Nr].pullRequests.push(i);return}a.viewer.pinned&&r[Dr].pullRequests.push(i),(!t||a.viewer.isAuthor||a.viewer.isAssignee&&!a.viewer.isReviewer)&&!a.isDraft&&a.viewer.canMerge&&a.mergeableState==="MERGEABLE"&&(r[Ar].pullRequests.push(i),u=!1),a.viewer.shouldAssignReviewer&&(r[$r].pullRequests.push(i),u=!1),(!t||a.viewer.isAuthor)&&a.failingCI&&(r[Lr].pullRequests.push(i),u=!1),(!t||a.viewer.isAuthor)&&a.hasConflicts&&(r[Ur].pullRequests.push(i),u=!1),a.viewer.shouldReview&&(r[Gr].pullRequests.push(i),u=!1),(!t||a.viewer.isAuthor)&&(a.reviewDecision==="CHANGES_REQUESTED"||a.codeSuggestionsCount>0)&&(r[Tr].pullRequests.push(i),u=!1),(!t||a.viewer.isAuthor)&&a.reviewDecision==="COMMENTED"&&(r[Or].pullRequests.push(i),u=!1),(!t||a.viewer.isAuthor)&&a.reviewDecision==="REVIEW_REQUESTED"&&(r[_r].pullRequests.push(i),u=!1),a.isDraft&&(r[kr].pullRequests.push(i),u=!1),u&&r[xr].pullRequests.push(i)}),Object.values(r).forEach(i=>{i.pullRequests.sort((a,u)=>o[a.uuid].priority-o[u.uuid].priority)}),r},wi=s=>{let t={};return s.forEach(e=>{let r=e.repository.id;t[r]?t[r].pullRequests.push(e):t[r]={name:e.repository.name,priority:0,pullRequests:[e],id:r}}),ce(t)},qi=s=>{let t="internal-no-assignees",e={[t]:{name:"No assignees",priority:-1,pullRequests:[],id:t,faIconName:"user-slash"}};return s.forEach(r=>{r.assignees&&r.assignees.length?r.assignees.forEach(n=>{let o=n.id;e[o]?e[o].pullRequests.push(r):e[o]={accountData:n,name:Qe(n,`Unknown Assignee ${Object.keys(e).length}`),priority:0,pullRequests:[r],id:o}}):e[t].pullRequests.push(r)}),ce(e)},vi=s=>{let t="internal-no-author",e={[t]:{name:"No author",priority:-1,pullRequests:[],id:t,faIconName:"user-slash"}};return s.forEach(r=>{if(r.author){let n=r.author.id;e[n]?e[n].pullRequests.push(r):e[n]={accountData:r.author,name:Qe(r.author,`Unknown Author ${Object.keys(e).length}`),priority:0,pullRequests:[r],id:n}}else e[t].pullRequests.push(r)}),ce(e)},Ei=s=>{let t="internal-no-reviewer",e={[t]:{name:"No reviewers",priority:-1,pullRequests:[],id:t,faIconName:"user-slash"}};return s.forEach(r=>{r.reviews&&r.reviews.length?r.reviews.forEach(n=>{let o=n.reviewer.id;e[o]?e[o].pullRequests.push(r):e[o]={accountData:n.reviewer,name:Qe(n.reviewer,`Unknown Reviewer ${Object.keys(e).length}`),priority:0,pullRequests:[r],id:o}}):e[t].pullRequests.push(r)}),ce(e)},Si=s=>s.azureProject?[`${s.azureProject}-${s.azureOrganizationId}`]:s.providerData?.repositories.nodes.map(t=>`${s.provider}-${t.repositoryId}`)??[],Ci=(s,t)=>{let e="internal-no-workspace",r={[e]:{name:"No workspace",priority:-1,pullRequests:[],id:e,faIconName:"folder-xmark"}};if(t.length){let n=t.reduce((o,i)=>(Si(i).forEach(u=>{o[u]?o[u].push(i):o[u]=[i]}),o),{});s.forEach(o=>{let{provider:i}=Cr(o.uuid),a=i==="github"?o.repository.graphQLId:o.repository.id,u=i==="azure"?[`${i}-${a}`,`${o.repository.project}-${o.repository.owner.login}`]:[`${i}-${a}`],l=!1,d=u.reduce((p,c)=>n[c]?p.concat(n[c]):p,[]);d?.length&&d.forEach(p=>{l=!0;let c=p.id;r[c]?r[c].pullRequests.push(o):r[c]={name:p.name,priority:0,pullRequests:[o],id:c,faIconName:"folder"}}),l||r[e].pullRequests.push(o)})}else r[e].pullRequests=s;return ce(r)},Di=(s,t,e,r)=>{let n="internal-no-team",o={[n]:{name:"No team",priority:-1,pullRequests:[],id:n}};return r.length?s.forEach(i=>{let a=!1,u=new Set;u.add(i.author?.id),i.assignees?.forEach(l=>u.add(l.id)),i.reviews?.forEach(l=>u.add(l.reviewer.id)),r.forEach(l=>{if(l.members?.some(p=>{let c=t[p.id]?.[e]?.providerID;return c&&u.has(c)})){a=!0;let p=l.id;o[p]?o[p].pullRequests.push(i):o[p]={name:l.name,priority:0,pullRequests:[i],id:p,teamData:l}}}),a||o[n].pullRequests.push(i)}):o[n].pullRequests=s,ce(o)};var Gt={};H(Gt,{getPullRequestRank:()=>Ai});var Ai=(s,t,e)=>{let r=0,n,o;return s.reviews?.forEach(i=>{i.reviewer.id===t&&(n=i.state),i.state==="CHANGES_REQUESTED"?o="CHANGES_REQUESTED":i.state==="APPROVED"&&o!=="CHANGES_REQUESTED"&&(o="APPROVED")}),o||(o="REVIEW_REQUESTED"),s.author?.id===t?r+=1e3:s.assignees?.find(i=>i.id===t)?r+=900:n==="REVIEW_REQUESTED"?r+=800:e&&(r+=700),o==="APPROVED"?s.mergeableState==="MERGEABLE"?r+=100:s.mergeableState==="CONFLICTS"?r+=90:r+=80:o=="CHANGES_REQUESTED"&&(r+=70),r};var Tt={};H(Tt,{default:()=>$i});var $i={};var Ot={};H(Ot,{default:()=>Li});var Li={};var _t={};H(_t,{default:()=>Ui});var Ui={};var ln=s=>{let t={request:s?.request};return{azureDevOps:new Pe({...t,...s?.azureDevOps}),bitbucket:new we({...t,...s?.bitbucket}),bitbucketServer:new qe({...t,...s?.bitbucketServer}),github:new ve({...t,...s?.github}),gitlab:new Se({...t,...s?.gitlab}),jira:new Ce({...t,...s?.jira}),jiraServer:new De({...t,...s?.jiraServer}),linear:new Ae({...t,...s?.linear}),trello:new $e({...t,...s?.trello})}};var pn=(i=>(i.Conflicts="conflicts",i.Failure="failure",i.NotSet="notSet",i.Queued="queued",i.RejectedByPolicy="rejectedByPolicy",i.Succeeded="succeeded",i))(pn||{});var dn=(e=>(e.Completed="COMPLETED",e.NotPlanned="NOT_PLANNED",e))(dn||{});var Gi=ln;var Ti={azureDevOps:It,bitbucket:bt,bitbucketServer:Je,github:Gt,gitlab:Tt,gitProvider:Ut,jira:Ot,trello:_t,entityIdentifier:Lt};
|