@gitkraken/provider-apis 0.48.0 → 0.50.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 +16 -0
- package/dist/index.js +238 -236
- package/dist/index.provider-utils.js +1 -1
- package/dist/index.providers.js +245 -243
- package/dist/providers/azureDevops/azureDevOps.d.ts +26 -11
- package/dist/providers/bitbucket/bitbucket.d.ts +11 -9
- package/dist/providers/bitbucketServer/bitbucketServer.d.ts +12 -2
- package/dist/providers/github/github.d.ts +4 -2
- package/dist/providers/github/githubHelpers.d.ts +19 -1
- package/dist/providers/gitlab/gitlab.d.ts +33 -11
- package/dist/providers/jira/jira.d.ts +5 -1
- package/dist/providers/jira/jiraHelpers.d.ts +13 -1
- package/dist/providers/jira/jiraServer.d.ts +5 -1
- package/dist/types/exportedTypes/gitProvider.d.ts +10 -0
- package/dist/types/exportedTypes/github.d.ts +13 -1
- package/dist/types/exportedTypes/gitlab.d.ts +12 -0
- package/dist/types/exportedTypes/types.d.ts +16 -0
- package/dist/types/internalTypes/bitbucket.d.ts +1 -1
- package/dist/types/internalTypes/github.d.ts +1 -0
- package/dist/types/internalTypes/gitlab.d.ts +7 -0
- package/dist/utils.d.ts +17 -0
- package/package.json +3 -2
package/dist/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
"use strict";var $t=Object.defineProperty;var Bs=Object.getOwnPropertyDescriptor;var Qs=Object.getOwnPropertyNames;var Fs=Object.prototype.hasOwnProperty;var z=(s,r)=>{for(var e in r)$t(s,e,{get:r[e],enumerable:!0})},Ms=(s,r,e,t)=>{if(r&&typeof r=="object"||typeof r=="function")for(let n of Qs(r))!Fs.call(s,n)&&n!==e&&$t(s,n,{get:()=>r[n],enumerable:!(t=Bs(r,n))||t.enumerable});return s};var zs=s=>Ms($t({},"__esModule",{value:!0}),s);var Ho={};z(Ho,{AzureDevOps:()=>me,AzureDevopsUtils:()=>lt,Bitbucket:()=>ge,BitbucketServer:()=>he,BitbucketServerUtils:()=>_e,BitbucketUtils:()=>pt,EntityIdentifierProviderType:()=>k,EntityIdentifierUtils:()=>wt,EntityType:()=>N,EntityVersion:()=>_,GitBuildStatusStage:()=>Lr,GitBuildStatusState:()=>ve,GitDiffLineType:()=>At,GitHub:()=>fe,GitHubIssueCloseReason:()=>ks,GitHubUtils:()=>vt,GitIssueState:()=>Ne,GitLab:()=>Ie,GitLabUtils:()=>Et,GitMergeStrategy:()=>ce,GitProviderUtils:()=>qt,GitPullRequestMergeableState:()=>Y,GitPullRequestReviewState:()=>W,GitPullRequestState:()=>ae,GraphQLErrors:()=>R,Jira:()=>be,JiraServer:()=>ye,JiraUtils:()=>St,Linear:()=>Pe,PullRequestAsyncStatus:()=>Os,Trello:()=>we,TrelloUtils:()=>Ct,Utils:()=>Wo,default:()=>zo,isFetch:()=>Ge});module.exports=zs(Ho);var jr=require("diff");var Lr=(n=>(n.Build="build",n.Production="production",n.Staging="staging",n.Test="test",n))(Lr||{}),ve=(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))(ve||{}),ce=(o=>(o.MergeCommit="MERGE_COMMIT",o.Rebase="REBASE",o.RebaseThenMergeCommit="REBASE_THEN_MERGE_COMMIT",o.FastForward="FAST_FORWARD",o.Squash="SQUASH",o))(ce||{}),ae=(t=>(t.Open="OPEN",t.Closed="CLOSED",t.Merged="MERGED",t))(ae||{}),W=(n=>(n.Approved="APPROVED",n.ChangesRequested="CHANGES_REQUESTED",n.Commented="COMMENTED",n.ReviewRequested="REVIEW_REQUESTED",n))(W||{}),Y=(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))(Y||{}),At=(t=>(t.ADDED="ADDED",t.DELETED="DELETED",t.UNMODIFIED="UNMODIFIED",t))(At||{});var Ur={APPROVED:0,COMMENTED:1,REVIEW_REQUESTED:2,CHANGES_REQUESTED:3},H=s=>!s||s.length===0?null:s.reduce((r,e)=>Ur[e.state]>Ur[r]?e.state:r,"APPROVED"),Te=(s,r)=>s.name||s.username||s.email||r,ue=s=>{let r=Object.values(s).map(e=>e.name).sort((e,t)=>e.localeCompare(t));return Object.values(s).forEach(e=>{e.priority!==-1&&(e.priority=r.indexOf(e.name))}),s};var Lt=(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))(Lt||{});var $=100;var Tr=globalThis.fetch;var Ws=async s=>{let r=s.headers.get("content-type")||"",e=null;if(r.startsWith("application/json")){let o=await s.text();e=o.trim().length>0?JSON.parse(o):null}else if(r.startsWith("text/")||r===""||r.startsWith("application/vnd.github.diff")||r.startsWith("application/vnd.github.patch"))e=await s.text();else if(r.startsWith("application/vnd.github.raw+json")||r.startsWith("application/octet-stream"))e=await s.arrayBuffer();else throw new Error(`Unsupported content-type: ${r}`);let t={};s.headers.forEach((o,i)=>{t[i]=o});let n={body:e,headers:t,status:s.status,statusText:s.statusText};if(!s.ok){let o=new Error(s.statusText);throw Object.assign(o,{response:n}),o}return n},Ut=s=>async({url:r,...e})=>{let t=await s(r,e);return Ws(t)};var Ge=(s,r=!1)=>s.name==="fetch"||r;var F=class{constructor(r){let e=r?.request||Tr;this.config={...r,request:Ge(e,r?.forceIsFetch)?Ut(e):e}}updateConfig(r){this.config={...this.config,...r,request:r.request&&Ge(r.request,r?.forceIsFetch??this.config.forceIsFetch)?Ut(r.request):this.config.request}}},j=class extends F{};var f=(s,r)=>{let e={};return s&&(e.Authorization=`${r?"Basic":"Bearer"} ${s}`),e},Gr=s=>s?s.reduce((r,e)=>(r[e]=!0,r),{}):void 0,se=(s,r,e)=>!s||r.some(t=>s[t])?e:"",Or=async s=>{let r=[],e=!0,t;for(;e;){let n=await s(t);r=r.concat(n.data),e=!!n?.pageInfo?.hasNextPage,t=n?.pageInfo?.endCursor||n?.pageInfo?.nextPage}return r};async function Tt(s){return(await Promise.allSettled(s)).map(e=>Hs(e)).filter(e=>e!=null)}function Hs(s,r=void 0){return s?.status==="fulfilled"?s.value:r}var Js="https://app.vssps.visualstudio.com/_apis",Vs="https://vssps.dev.azure.com/",Ks="https://dev.azure.com",w=(s,r={})=>f(r.token||s.token,r.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/"),Gt=(s,r)=>{let e=r.baseUrl||s.baseUrl||Js;return e=e.replace(/\/$/,""),e},C=(s,r)=>{let e=r.baseUrl||s.baseUrl||Ks;return e=e.replace(/\/$/,""),e},Ot=(s,r)=>{let e=r.baseUrl||s.baseUrl||Vs;return e=e.replace(/\/$/,""),e};var Xs={active:"OPEN",completed:"MERGED",abandoned:"CLOSED"},Ys=s=>{if(typeof s!="string")return s;let r=s.charAt(0).toUpperCase()+s.slice(1);return Lt[r]??0},Zs=new Set([2,3,4,5]),en={10:"APPROVED",5:"APPROVED",0:"REVIEW_REQUESTED",[-5]:"CHANGES_REQUESTED",[-10]:"CHANGES_REQUESTED"},le=s=>({id:s.id,name:s.displayName??null,username:(s.uniqueName||s.displayName)??null,email:null,avatarUrl:s.imageUrl??null,url:null}),Oe=s=>s.startsWith("refs/heads/")?s.replace("refs/heads/",""):s,tn=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"}},kt=(s,r,e,t,n,o)=>`${s}|${r}|${e}|${t}|${n}|${o}`,xr=s=>{let r=s.split("|");if(r.length!==6)throw new Error("Invalid Azure comment ID format");return{namespace:r[0],project:r[1],repoName:r[2],prId:r[3],threadId:r[4],commentId:r[5]}},_r=(s,r,e,t,n)=>`${s}|${r}|${e}|${t}|${n}`,xt=s=>{let r=s.split("|");if(r.length!==5)throw new Error("Invalid Azure thread ID format");return{namespace:r[0],project:r[1],repoName:r[2],prId:r[3],threadId:r[4]}},Ee=(s,r)=>{let e=[],t=[];return r.reviewers.forEach(n=>{let o={reviewer:le(n),state:en[n.vote??0]||"REVIEW_REQUESTED"};n.isRequired&&e.push(o),t.push(o)}),{id:r.pullRequestId.toString(),title:r.title,description:r.description??null,number:r.codeReviewId,state:Xs[r.status],isDraft:r.isDraft,commentCount:null,upvoteCount:null,author:le(r.createdBy),createdDate:new Date(r.creationDate),updatedDate:new Date(r.closedDate||r.creationDate),closedDate:r.closedDate?new Date(r.closedDate):null,mergedDate:r.closedDate&&r.status==="completed"?new Date(r.closedDate):null,repository:{id:r.repository.id,name:r.repository.name,project:r.repository.project.name,owner:{login:s},remoteInfo:null},headCommit:{buildStatuses:null},baseRef:{name:Oe(r.targetRefName),oid:r.lastMergeTargetCommit.commitId},headRef:{name:Oe(r.sourceRefName),oid:r.lastMergeSourceCommit.commitId},url:kr(r),assignees:r.reviewers.map(le),reviews:t,reviewDecision:H(e),additions:null,deletions:null,fileCount:null,commitCount:null,headRepository:r.forkSource?{id:r.forkSource.repository.id,name:r.forkSource.repository.name,project:void 0,owner:{login:s},remoteInfo:null}:{id:r.repository.id,name:r.repository.name,project:r.repository.project.name,owner:{login:s},remoteInfo:null},mergeableState:tn(r.mergeStatus),labels:r.labels?.map(n=>({color:null,description:null,id:n.id,name:n.name}))??[],permissions:null}},Nr=(s,r)=>({id:r.id,name:r.name,namespace:s,project:r.project.name,projectId:r.project.id,webUrl:r.webUrl,httpsUrl:r.remoteUrl,sshUrl:r.sshUrl,defaultBranch:r.defaultBranch?{name:Oe(r.defaultBranch)}:null,permissions:null}),rn=(s,r,e,t)=>{let n=e.fields,o=n["System.AssignedTo"],i=n["System.State"],a=n["System.WorkItemType"],u;return i&&a&&(u=t[a]?.[i]),{id:e.id.toString(),number:e.id.toString(),title:n["System.Title"],commentCount:n["System.CommentCount"],author:{avatarUrl:n["System.CreatedBy"]._links?.avatar?.href??null,email:null,id:n["System.CreatedBy"].id,name:n["System.CreatedBy"].uniqueName??null,username:n["System.CreatedBy"].displayName??null,url:null},closedDate:n["Microsoft.VSTS.Common.ClosedDate"]?new Date(n["Microsoft.VSTS.Common.ClosedDate"]):null,createdDate:new Date(n["System.CreatedDate"]),updatedDate:new Date(n["System.ChangedDate"]),url:e._links.html.href,assignees:o?[{avatarUrl:o._links?.avatar?.href??null,email:null,id:o.id,name:o.uniqueName??null,username:o.displayName??null,url:null}]:[],description:n["System.Description"]??null,state:{name:u?.title||i,color:null},type:n["System.WorkItemType"],repository:null,project:{namespace:s,name:r,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()}))??[]}},me=class extends j{constructor(){super(...arguments);this.cachedUserIds=new Map;this.inflightUserIds=new Map}getCurrentUserId(e,t){let n=JSON.stringify([e,t.token??null,t.isPAT??this.config.isPAT??!1,t.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,t,n);return this.inflightUserIds.set(n,a),a}async fetchCurrentUserId(e,t,n){try{let o=await this.getCurrentUserForInstance({namespace:e},t);return this.cachedUserIds.set(n,o.data.id),o.data.id}finally{this.inflightUserIds.delete(n)}}getRepoApiUrl(e,t,n,o){return`${C(this.config,o)}/${encodeURIComponent(e)}/${encodeURIComponent(t)}/_apis/git/repositories/${encodeURIComponent(n)}`}async getCurrentUser(e={},t={}){if(t.isPAT||this.config.isPAT)throw new Error("Azure DevOps does not support PATs for this function.");let n=`${Gt(this.config,t)}/profile/profiles/me`,o=await this.config.request({url:n,headers:w(this.config,t)});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,t={}){let o=(await this.config.request({url:`${C(this.config,t)}/${encodeURIComponent(e.namespace)}/_apis/ConnectionData`,headers:w(this.config,t)})).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,t={}){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,t)}/${encodeURIComponent(e.repo.namespace)}/${encodeURIComponent(e.repo.project)}/_apis/git/repositories/${encodeURIComponent(e.repo.name)}/commits/${e.oid}`,headers:w(this.config,t)})).body.author;return{data:{name:o.name,email:o.email,avatarUrl:o.imageUrl}}}async getOrgsForUser(e,t={}){let n=`${Gt(this.config,t)}/accounts?memberId=${e.userId}&api-version=6.0`;return{data:(await this.config.request({url:n,headers:w(this.config,t)})).body.value.map(i=>({id:i.accountId,name:i.accountName}))}}async getCollectionsForUser(e,t={}){let n=`${C(this.config,t)}/_apis/projectCollections`;return{data:(await this.config.request({url:n,headers:w(this.config,t)})).body.value.map(i=>({id:i.id,name:i.name}))}}async getAzureProjects(e,t={}){let n=new URL(`${C(this.config,t)}/${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:w(this.config,t)}),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,t={}){let{namespace:n,projectId:o}=e;return{data:{scope:(await this.config.request({url:`${Ot(this.config,t)}/${encodeURIComponent(n)}/_apis/graph/descriptors/${o}?api-version=6.0`,headers:w(this.config,t)})).body.value}}}async getAzureGraphAccountsForAzureProject(e,t={}){let{namespace:n,projectScopeDescriptor:o,cursor:i}=e,a=new URL(`${Ot(this.config,t)}/${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:w(this.config,t)}),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,t={}){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:w(this.config,t)});return{data:{avatarUrl:n.avatarUrl,email:n.email,id:o.body.value,name:n.name,username:n.username,url:null}}}async getAccountsFromAzureGraphAccounts(e,t={}){let n=[];for(let o of e.azureGraphAccounts){let i=await this.getAccountFromAzureGraphAccount({azureGraphAccount:o},t);n.push(i.data)}return{data:n}}async getRepo(e,t={}){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,t)}/${encodeURIComponent(e.namespace)}/${encodeURIComponent(e.project)}/_apis/git/repositories/${encodeURIComponent(e.name)}`,headers:w(this.config,t)});return{data:Nr(e.namespace,n.body)}}async getRepos(e,t={}){let n=[],o=[];return await Promise.all(e.map(async i=>{try{let a=await this.getRepo(i,t);n.push(a.data)}catch(a){o.push({input:i,error:a})}})),{data:n,errors:o}}async getReposForAzureProject(e,t={}){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,t)}/${encodeURIComponent(e.namespace)}/${encodeURIComponent(e.project)}/_apis/git/repositories`,headers:w(this.config,t)})).body.value.map(o=>Nr(e.namespace,o))}}async getRefs(e,t,n={}){if(!t.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(t.repo.namespace)}/${encodeURIComponent(t.repo.project)}/_apis/git/repositories/${encodeURIComponent(t.repo.name)}/refs`);o.searchParams.set("filter",e),o.searchParams.set("$top",$.toString()),t.cursor&&o.searchParams.set("continuationToken",t.cursor);let i=await this.config.request({url:o.toString(),headers:w(this.config,n)}),a=i.headers["x-ms-continuationtoken"];return{pageInfo:{hasNextPage:!!a,endCursor:a||null},data:i.body.value.map(u=>({name:Oe(u.name),commit:{oid:u.objectId,authoredDate:null,committedDate:null}}))}}async getBranches(e,t={}){return this.getRefs("heads",e,t)}async getTags(e,t={}){return this.getRefs("tags",e,t)}async getPullRequestsForRepoBase(e,t={},n=100){let{page:o,repo:i,assigneeLogins:a,authorLogin:u}=e||{},l=o||1;if(!i.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let p="searchCriteria.status=1";return a&&a.length&&(p+=`&searchCriteria.reviewerId=${a[0]}`),u&&(p+=`&searchCriteria.creatorId=${u}`),await this.config.request({url:`${C(this.config,t)}/${encodeURIComponent(i.namespace)}/${encodeURIComponent(i.project||"")}/_apis/git/repositories/${encodeURIComponent(i.name)}/pullRequests?${p}&%24top=${n}&%24skip=${(l-1)*n}`,headers:w(this.config,t)})}async getPullRequestsForRepo(e,t={}){let o=e.page||1,i=await this.getPullRequestsForRepoBase(e,t,100);return{pageInfo:{hasNextPage:i.body.value.length===100,nextPage:o+1},data:i.body.value.map(a=>Ee(e.repo.namespace,a))}}async getPullRequestsForRepos(e,t={}){if(!e.repos.every(i=>i.project))throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let{repos:n}=e||{},o=[];return await Promise.all(n.map(async i=>{try{(await this.getPullRequestsForRepoBase({repo:i,...e},t)).body.value.forEach(u=>{o.push(Ee(i.namespace,u))})}catch(a){if(a.statusCode!==404&&a.statusCode!==401)throw a}})),{data:o}}async getPullRequestsForProjectBase(e,t={},n=100){let{namespace:o,project:i,page:a,assigneeLogins:u,authorLogin:l,repo:p}=e;if(p?.project&&p.project!==i)throw new Error("Could not fetch pull requests, project mismatch");let c=a||1,d=new URL(`${C(this.config,t)}/${encodeURIComponent(o)}/${encodeURIComponent(i)}/_apis/git/pullRequests`);return d.searchParams.set("searchCriteria.status","1"),d.searchParams.set("$top",n.toString()),d.searchParams.set("$skip",((c-1)*n).toString()),p?.id&&p?.project===i&&d.searchParams.set("searchCriteria.repositoryId",p.id),u&&u.length&&d.searchParams.set("searchCriteria.reviewerId",u[0]),l&&d.searchParams.set("searchCriteria.creatorId",l),await this.config.request({url:d.toString(),headers:w(this.config,t)})}async getPullRequestsForProject(e,t={}){let o=e.page||1,i=await this.getPullRequestsForProjectBase(e,t,100);return{pageInfo:{hasNextPage:i?.body.value.length===100,nextPage:o+1},data:i?.body.value.map(a=>Ee(e.namespace,a))||[]}}async getPullRequestsForProjects(e,t={}){let{projects:n}=e||{},o=[];return await Promise.all(n.map(async i=>{try{(!e.repo||e.repo.project&&e.repo.project===i.project)&&(await this.getPullRequestsForProjectBase({...i,...e},t))?.body.value.forEach(u=>{o.push(Ee(i.namespace,u))})}catch(a){if(a.statusCode!==404&&a.statusCode!==401)throw a}})),{data:o}}async getAzurePullRequestLastMergeStatus(e,t={}){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,t)}/${encodeURIComponent(n)}/${encodeURIComponent(o||"")}/_apis/git/repositories/${i}/pullrequests/${a}?includeCommits=true?api-version=6.0`,headers:{...w(this.config,t)}});if(!u.body.mergeStatus)throw new Error("Could not fetch pull request");return{data:u.body.mergeStatus}}async updatePullRequest(e,t,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:t,headers:{...w(this.config,n),"Content-Type":"application/json"}})}async closePullRequest(e,t={}){let{pullRequest:n}=e,o={status:"abandoned"};if(!(await this.updatePullRequest(n,JSON.stringify(o),t)).body.status)throw new Error("Could not close pull request")}async mergePullRequest(e,t={}){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),t)).body.status)throw new Error("Could not merge pull request")}async addPullRequestLabel(e,t={}){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,t)}/${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:{...w(this.config,t),"Content-Type":"application/json"}})).body.id)throw new Error("Could not add pull request label")}async removePullRequestLabel(e,t={}){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,t)}/${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:{...w(this.config,t)}})}async setPullRequestLabels(e,t={}){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},t);for(let a of i)o.find(u=>a.id===u.id)||await this.removePullRequestLabel({pullRequest:n,label:a},t)}async setPullRequestAsDraft(e,t={}){let{pullRequest:n,isDraft:o}=e,i={isDraft:o};if(!(await this.updatePullRequest(n,JSON.stringify(i),t)).body.status)throw new Error("Could not set the pull request as draft")}async addPullRequestReviewer(e,t={}){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,t)}/${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:{...w(this.config,t),"Content-Type":"application/json"}})).body.id)throw new Error("Could not add pull request reviewer")}async removePullRequestReviewer(e,t={}){let{pullRequest:n,reviewer:o}=e;await this.config.request({method:"DELETE",url:`${C(this.config,t)}/${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:{...w(this.config,t),Accept:"application/json"}})}async setPullRequestReviewers(e,t={}){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},t);for(let i of n.assignees)o.find(a=>i.id===a.id)||await this.removePullRequestReviewer({pullRequest:n,reviewer:i},t)}async getIssuesForAzureProject(e,t={}){let{page:n,assigneeLogins:o,authorLogin:i,mentionLogin:a,labelNames:u,statusByWorkItemIdByStatusId:l}=e||{},p=n||1,c=200,d=["[Microsoft.VSTS.Common.ClosedDate] = ''","[System.TeamProject] = @project","[Microsoft.VSTS.Common.ResolvedDate] = ''"];i&&d.push(`[System.CreatedBy] = '${i.replace("'","''")}'`),o&&o[0]&&d.push(`[System.AssignedTo] = '${o[0].replace("'","''")}'`),a&&d.push("[System.Id] IN (@recentMentions)"),u&&u.forEach(h=>d.push(`[System.Tags] Contains '${h}'`));let g=`Select [Microsoft.VSTS.Common.ClosedDate], [Microsoft.VSTS.Common.ResolvedDate] From WorkItems Where ${d.join(" AND ")} order by [System.CreatedDate] desc`,m=await this.config.request({url:`${C(this.config,t)}/${encodeURIComponent(e.namespace)}/${encodeURIComponent(e.project)}/_apis/wit/wiql?api-version=6.0`,body:JSON.stringify({query:g}),method:"POST",headers:{...w(this.config,t),"Content-Type":"application/json"}}),I=m.body.workItems.slice((p-1)*c,c*p).map(h=>h.id);if(I.length==0)return{pageInfo:{hasNextPage:!1,nextPage:null},data:[]};let y=await this.config.request({url:`${C(this.config,t)}/${encodeURIComponent(e.namespace)}/${encodeURIComponent(e.project)}/_apis/wit/workitemsbatch?api-version=6.0`,body:JSON.stringify({ids:I,$expand:"Links"}),method:"POST",headers:{...w(this.config,t),"Content-Type":"application/json"}});return{pageInfo:{hasNextPage:m.body.workItems.length>c*p,nextPage:p+1},data:y.body.value.map(h=>rn(e.namespace,e.project,h,l||{}))}}async getPermissionsForRepos(e,t={}){let{namespace:n,repos:o}=e,i={4:["canPush","canCreateWebhook"],1024:["isAdmin"],2048:["isAdmin"],4096:["isAdmin"],8192:["isAdmin"]},a=c=>{let d="2e9eb7ed-3c0a-47d4-87c1-0ffdd275fd87",g=`repoV2/${c.projectId}/${c.id}`;return Object.keys(i).map(m=>({securityNamespaceId:d,token:g,permissions:m}))},u={alwaysAllowAdministrators:!1,evaluations:o.flatMap(a)};return{data:(await this.config.request({method:"POST",url:`${C(this.config,t)}/${encodeURIComponent(n)}/_apis/security/permissionevaluationbatch?api-version=7.0`,body:JSON.stringify(u),headers:{...w(this.config,t),"Content-Type":"application/json"}})).body.evaluations.reduce((c,d)=>{let[,g,m]=d.token.split("/"),I=`${g}/${m}`,y=i[d.permissions];for(let h of y)c[I]===void 0&&(c[I]={canCreateWebhook:!0,canPush:!0,isAdmin:!0}),d.value===!1&&(c[I][h]=!1);return c},{})}}async decorateReposWithPermissions(e,t={}){let{namespace:n,repos:o}=e,i=await this.getPermissionsForRepos({namespace:n,repos:o},t);return{data:o.map(a=>({...a,permissions:i.data[`${a.projectId}/${a.id}`]}))}}async updateIssue(e,t,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(t),headers:{...w(this.config,n),"Content-Type":"application/json-patch+json"}})}async setIssueStatus(e,t={}){let{issue:n,status:o}=e,i=[{op:"add",path:"/fields/System.State",value:o.name}];if(!(await this.updateIssue(n,i,t)).body.fields?.["System.State"])throw new Error("Could not set issue status")}async setIssueAssignee(e,t={}){let{issue:n,assignee:o}=e,i=[{op:"add",path:"/fields/System.AssignedTo",value:o?.name??""}];if(!(await this.updateIssue(n,i,t)).body.fields?.["System.State"])throw new Error("Could not set issue assignee")}async setIssueLabels(e,t={}){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,t)).body.fields?.["System.Tags"])throw new Error("Could not set issue tags")}async getIssueTypesForAzureProject(e,t={}){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,t)}/${encodeURIComponent(n)}/${encodeURIComponent(o||"")}/_apis/wit/workitemtypes?api-version=6.0`,headers:{...w(this.config,t)}})).body.value}}async getLabelsForProject(e,t={}){let{namespace:n,project:o}=e;return{data:(await this.config.request({url:`${C(this.config,t)}/${encodeURIComponent(n)}/${encodeURIComponent(o||"")}/_apis/wit/tags?api-version=6.0`,headers:{...w(this.config,t)}})).body.value.map(a=>({color:null,description:null,id:a.id,name:a.name,url:a.url}))}}async getPullRequestForRepo(e,t={}){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,t)}/pullrequests/${o}?api-version=7.1`,headers:w(this.config,t)});return{data:Ee(n.namespace,i.body)}}async getPullRequestDescription(e,t={}){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,t)}/pullrequests/${o}?api-version=7.1`,headers:w(this.config,t)})).body?.description??""}}}catch{return{data:{description:null}}}}async setPullRequestDescription(e,t={}){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,t)}/pullrequests/${o}?api-version=7.1`,headers:{...w(this.config,t),"Content-Type":"application/json"},body:JSON.stringify({description:i})})).body?.description??i}}}async getMergeBase(e,t={}){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,t)}/commits/${encodeURIComponent(e.base)}/mergebases?otherCommitId=${encodeURIComponent(e.head)}&api-version=7.1`,headers:w(this.config,t)});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,t={}){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,t)}/items?path=${encodeURIComponent(e.path)}&versionDescriptor[version]=${encodeURIComponent(e.ref)}&versionDescriptor[versionType]=commit&api-version=7.1`,headers:{...w(this.config,t),Accept:"application/octet-stream"}});return{data:new Blob([n.body])}}async getPullRequestDiff(e,t={}){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,t),o=w(this.config,t),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,c=u.body.value;if(c.length===0)return"";let d=c[c.length-1],g=1e3,m=[],I=0;for(;;){let E=(await this.config.request({url:`${n}/pullrequests/${e.pullRequestId}/iterations/${d.id}/changes?api-version=7.1&$top=${g}&$skip=${I}`,headers:o})).body.changeEntries??[];if(E.length===0||(m.push(...E),E.length<g))break;I+=E.length}if(m.length===0)return"";let y=5,h=[],v=new TextDecoder,D=P=>P instanceof ArrayBuffer?v.decode(P):typeof P=="string"?P:"",x=async(P,E)=>{try{let oe=await this.config.request({url:`${n}/items?path=${encodeURIComponent(P)}&versionDescriptor[version]=${encodeURIComponent(E)}&versionDescriptor[versionType]=commit&includeContent=true&api-version=7.1`,headers:i});return D(oe.body)}catch{return""}},S=P=>{if(typeof P=="number")return{add:(P&1)!==0,rename:(P&8)!==0,delete:(P&16)!==0};let E=P.toLowerCase().split(",").map(oe=>oe.trim());return{add:E.includes("add"),rename:E.includes("rename"),delete:E.includes("delete")}};for(let P=0;P<m.length;P+=y){let E=m.slice(P,P+y),oe=await Promise.all(E.map(async pe=>{let{add:de,rename:Dt,delete:ie}=S(pe.changeType),qe=pe.originalPath??pe.item.originalPath,U=pe.item.path,Ue=ie?U??qe??"":U??"",Ar=Dt||ie?qe??Ue:Ue,[xs,_s]=await Promise.all([de?Promise.resolve(""):x(Ar,l),ie?Promise.resolve(""):x(Ue,p)]),Ns=de?"/dev/null":`a${Ar}`,js=ie?"/dev/null":`b${Ue}`;return(0,jr.createTwoFilesPatch)(Ns,js,xs,_s)}));h.push(...oe)}return h.join(`
|
|
2
|
-
`)}getPullRequestWriteHeaders(e){return{...w(this.config,e),"Content-Type":"application/json"}}setReviewerVote(e,t,n,o,i){return this.config.request({method:"PUT",url:`${e}/pullRequests/${t}/reviewers/${encodeURIComponent(n)}?api-version=7.1`,headers:this.getPullRequestWriteHeaders(i),body:JSON.stringify({vote:o})})}postPullRequestThread(e,t,n,o){return this.config.request({method:"POST",url:`${e}/pullRequests/${t}/threads?api-version=7.1`,headers:this.getPullRequestWriteHeaders(o),body:JSON.stringify({comments:[{parentCommentId:0,content:n,commentType:1}],status:1})})}async getCommentsForPullRequest(e,t={}){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,t),o=w(this.config,t),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:kt(e.repo.namespace,e.repo.project,e.repo.name,e.pullRequestNumber,u.id,l.id),author:l.author?le(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,t={}){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,t);await this.postPullRequestThread(n,e.pullRequest.id,e.comment,t)}async addInlineCommentToPullRequest(e,t={}){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,t),o=this.getPullRequestWriteHeaders(t);if(e.threadId){let p=xt(e.threadId),c=e.pullRequest.repository.owner.login,d=e.pullRequest.repository.project,g=e.pullRequest.repository.name,m=String(e.pullRequest.id);if(p.namespace!==c||p.project!==d||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 ${c}/${d}/${g} pull request ${m}.`);let y=(await this.config.request({url:`${n}/pullRequests/${e.pullRequest.id}/threads/${p.threadId}?api-version=7.1`,headers:w(this.config,t)})).body.comments?.find(v=>v.parentCommentId===0);if(!y)throw new Error(`Could not determine root comment for Azure DevOps thread ${p.threadId}.`);let h=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 kt(c,d,g,Number(m),Number(p.threadId),h.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 _r(e.pullRequest.repository.owner.login,e.pullRequest.repository.project,e.pullRequest.repository.name,Number(e.pullRequest.id),l.body.id)}async editComment(e,t={}){let n=xr(e.commentId),o=this.getRepoApiUrl(n.namespace,n.project,n.repoName,t);await this.config.request({method:"PATCH",url:`${o}/pullRequests/${n.prId}/threads/${n.threadId}/comments/${n.commentId}?api-version=7.1`,headers:this.getPullRequestWriteHeaders(t),body:JSON.stringify({content:e.body})})}async editInlineComment(e,t={}){return this.editComment(e,t)}async deleteComment(e,t={}){let n=xr(e.commentId),o=this.getRepoApiUrl(n.namespace,n.project,n.repoName,t);await this.config.request({method:"DELETE",url:`${o}/pullRequests/${n.prId}/threads/${n.threadId}/comments/${n.commentId}?api-version=7.1`,headers:w(this.config,t)})}async deleteInlineComment(e,t={}){return this.deleteComment(e,t)}async resolveReviewThread(e,t={}){let n=xt(e.threadId),o=this.getRepoApiUrl(n.namespace,n.project,n.repoName,t);await this.config.request({method:"PATCH",url:`${o}/pullRequests/${n.prId}/threads/${n.threadId}?api-version=7.1`,headers:this.getPullRequestWriteHeaders(t),body:JSON.stringify({status:2})})}async unresolveReviewThread(e,t={}){let n=xt(e.threadId),o=this.getRepoApiUrl(n.namespace,n.project,n.repoName,t);await this.config.request({method:"PATCH",url:`${o}/pullRequests/${n.prId}/threads/${n.threadId}?api-version=7.1`,headers:this.getPullRequestWriteHeaders(t),body:JSON.stringify({status:1})})}async approvePullRequest(e,t={}){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,t),i=await this.getCurrentUserId(n,t);await Promise.all([this.setReviewerVote(o,e.pullRequest.id,i,10,t),e.comment?this.postPullRequestThread(o,e.pullRequest.id,e.comment,t):null])}async requestPullRequestChanges(e,t={}){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,t),i=await this.getCurrentUserId(n,t);await this.postPullRequestThread(o,e.pullRequest.id,e.comment,t),await this.setReviewerVote(o,e.pullRequest.id,i,-5,t)}async commentOnPullRequest(e,t={}){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,t);await this.postPullRequestThread(n,e.pullRequest.id,e.comment,t)}async getReviewsForPullRequest(e,t={}){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,t),l=w(this.config,t),[p,c]=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})]),d=(h,v)=>kt(n,o,i,a,h,v),g=h=>_r(n,o,i,a,h),m=new Map;for(let h of c.body.value){if(h.isDeleted)continue;let v=h.comments.filter(U=>!U.isDeleted&&U.commentType!=="system"),D=v.find(U=>U.parentCommentId===0)??v[0];if(!D)continue;let x=D.author?.id;if(!x)continue;let S=v.filter(U=>U.id!==D.id),P=h.threadContext,E=P?.rightFileStart?{side:"RIGHT",start:P.rightFileStart,end:P.rightFileEnd}:P?.leftFileStart?{side:"LEFT",start:P.leftFileStart,end:P.leftFileEnd}:null,oe=E?.end?.line??E?.start.line??null,pe=E?.start&&E.end&&E.start.line!==E.end.line?E.start.line:null,de=P?.filePath??"",Dt=de.startsWith("/")?de.slice(1):de,ie={id:d(h.id,D.id),author:D.author?le(D.author):null,body:D.content??"",createdAt:D.publishedDate?new Date(D.publishedDate):null,url:"",diffLines:[],filename:Dt,replies:S.map(U=>({id:d(h.id,U.id),author:U.author?le(U.author):null,body:U.content??"",createdAt:U.publishedDate?new Date(U.publishedDate):null,url:""})),isOutdated:!1,isResolved:Zs.has(Ys(h.status)),line:oe,startLine:pe,side:E?.side??null,threadId:g(h.id)},qe=m.get(x);qe?qe.push(ie):m.set(x,[ie])}let I=[],y=new Set;for(let h of p.body.value){if(h.hasDeclined)continue;let v=h.vote??0,D=m.get(h.id);v===0&&!D?.length||(I.push({id:h.id,author:le(h),body:"",createdAt:null,url:"",reviewComments:D??[]}),y.add(h.id))}for(let[h,v]of m){if(y.has(h)||!v.length)continue;let D=v[0].author;D&&I.push({id:h,author:D,body:"",createdAt:null,url:"",reviewComments:v})}return{data:I}}};var L=(s,r={})=>f(r.token||s.token,r.isPAT||s.isPAT);var T="https://api.bitbucket.org/2.0",sn={OPEN:"OPEN",MERGED:"MERGED",DECLINED:"CLOSED"},ke={owner:4,admin:3,contributor:2,member:1},xe=s=>({id:s.uuid,name:s.display_name||s.nickname,username:s.nickname||s.display_name,email:null,avatarUrl:s.links.avatar.href,url:s.links.html.href}),Br=s=>{let r=s.links.clone,e=r?.find(n=>n.name==="ssh"),t=r?.find(n=>n.name==="https");return e&&t?{cloneUrlHTTPS:t.href,cloneUrlSSH:e.href}:null},_t=s=>({id:s.uuid,namespace:s.workspace.slug,name:s.slug,webUrl:s.links.html.href,httpsUrl:s.links.clone.find(r=>r.name==="https")?.href??null,sshUrl:s.links.clone.find(r=>r.name==="ssh")?.href??null,defaultBranch:{name:s.mainbranch.name},permissions:null}),Nt=s=>{let r=s.id,e=s.participants?.map(t=>{let n="REVIEW_REQUESTED";return t.approved?n="APPROVED":t.state==="changes_requested"?n="CHANGES_REQUESTED":t.participated_on!==null&&(n="COMMENTED"),{reviewer:xe(t.user),state:n}})??[];return{id:r.toString(),title:s.title,description:s.description,number:r,state:sn[s.state],isDraft:!1,commentCount:s.comment_count,upvoteCount:null,author:xe(s.author),createdDate:new Date(s.created_on),updatedDate:new Date(s.updated_on),closedDate:null,mergedDate:null,repository:{id:s.destination.repository.uuid,name:s.destination.repository.name,owner:{login:s.destination.repository.full_name.split("/")[0]},remoteInfo:Br(s.destination.repository)},headCommit:{buildStatuses:null},baseRef:{name:s.destination.branch.name,oid:s.destination.commit.hash},headRef:{name:s.source.branch.name,oid:s.source.commit.hash},url:s.links.html.href,assignees:null,reviews:e,reviewDecision:H(e),additions:null,deletions:null,fileCount:null,commitCount:null,headRepository:{id:s.source.repository.uuid,name:s.source.repository.name,owner:{login:s.source.repository.full_name.split("/")[0]},remoteInfo:Br(s.source.repository)},mergeableState:"MERGEABLE",permissions:null}},nn=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}}},on=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}}},ge=class extends F{async refreshToken(r){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 ${r.base64ClientIDColonClientSecret}`},body:`grant_type=refresh_token&refresh_token=${r.refreshToken}`})).body}}async getCurrentUser(r={},e={}){let t=await this.config.request({url:`${T}/user`,headers:L(this.config,e)});return{data:xe(t.body)}}async getUserForCommit(r,e={}){let n=(await this.config.request({url:`${T}/repositories/${r.repo.namespace}/${r.repo.name}/commit/${r.oid}`,headers:L(this.config,e)})).body.author,o=n.raw.match(/([^<]+)<(.+)>/);return{data:{name:o?o[1].trim():null,email:o?o[2]:null,avatarUrl:n.user?.links.avatar.href||null}}}async getRepo(r,e={}){let t=await this.config.request({url:`${T}/repositories/${r.namespace}/${r.name}`,headers:L(this.config,e)});return{data:_t(t.body)}}async getRepos(r,e={}){let t=[],n=[];return await Promise.all(r.map(async o=>{try{let i=await this.getRepo(o,e);t.push(i.data)}catch(i){n.push({input:o,error:i})}})),{data:t,errors:n}}async getReposForWorkspace(r,e={}){let t=new URL(`${T}/repositories/${encodeURIComponent(r.workspace)}`);t.searchParams.set("page",r.page?.toString()||"1"),t.searchParams.set("pagelen",$.toString()),r.minimumRole&&t.searchParams.set("role",r.minimumRole);let n=await this.config.request({url:t.toString(),headers:L(this.config,e)}),o=!!n.body.next;return{pageInfo:{hasNextPage:o,nextPage:o?n.body.page+1:null},data:n.body.values.map(_t)}}async getAllReposForWorkspace(r,e={}){let t=[],n=1;for(;n!==null;){let o=await this.getReposForWorkspace({workspace:r.workspace,minimumRole:r.minimumRole,page:n},e);t.push(...o.data),n=o.pageInfo.hasNextPage?o.pageInfo.nextPage:null}return t}async getAllReposForWorkspaceWithPermissions(r,e={}){let t=new Map,n=[],o=ke[r.minimumRole||"member"];o<=ke.admin&&n.push("admin"),o<=ke.contributor&&n.push("contributor"),o<=ke.member&&n.push("member");let i=[];for(let a of n){i=await this.getAllReposForWorkspace({workspace:r.workspace,minimumRole:a},e);for(let u of i)t.has(u.id)||t.set(u.id,a)}return{data:i.map(a=>{let u=t.get(a.id)||"member";return{...a,permissions:on(u)}})}}async getReposForCurrentUser(r,e={}){let t=new URL(`${T}/repositories`);t.searchParams.set("role","member"),t.searchParams.set("pagelen",$.toString()),r.cursor&&t.searchParams.set("after",r.cursor);let n=await this.config.request({url:t.toString(),headers:L(this.config,e)}),o=!!n.body.next,i=null;return n.body.next&&(i=new URL(n.body.next).searchParams.get("after")),{pageInfo:{hasNextPage:o,endCursor:i},data:n.body.values.map(_t)}}async getBranches(r,e={}){let t=new URL(`${T}/repositories/${r.repo.namespace}/${r.repo.name}/refs/branches`);t.searchParams.set("page",r.page?.toString()||"1"),t.searchParams.set("pagelen",$.toString());let n=await this.config.request({url:t.toString(),headers:L(this.config,e)}),o=!!n.body.next;return{pageInfo:{hasNextPage:o,nextPage:o?n.body.page+1:null},data:n.body.values.map(i=>{let a=new Date(i.target.date);return{name:i.name,commit:{oid:i.target.hash,authoredDate:a,committedDate:a}}})}}async getTags(r,e={}){let t=new URL(`${T}/repositories/${r.repo.namespace}/${r.repo.name}/refs/tags`);t.searchParams.set("pagelen",$.toString()),r.cursor&&t.searchParams.set("page",r.cursor);let n=await this.config.request({url:t.toString(),headers:L(this.config,e)}),o=!!n.body.next,i=null;return n.body.next&&(i=new URL(n.body.next).searchParams.get("page")),{pageInfo:{hasNextPage:o,endCursor:i},data:n.body.values.map(a=>{let u=new Date(a.target.date);return{name:a.name,commit:{oid:a.target.hash,authoredDate:u,committedDate:u}}})}}async getWorkspacesForCurrentUser(r={},e={}){let t=new URL(`${T}/user/workspaces`);t.searchParams.set("page",r?.page?.toString()||"1"),t.searchParams.set("pagelen","50"),r?.administrator!==void 0&&t.searchParams.set("administrator",r.administrator.toString());let n=await this.config.request({url:t.toString(),headers:L(this.config,e)}),o=!!n.body.next;return{pageInfo:{hasNextPage:o,nextPage:o?n.body.page+1:null},data:n.body.values.map(i=>({id:i.workspace.uuid,slug:i.workspace.slug}))}}async getWorkspacesForUser(r,e={}){let t=new URL(`${T}/user/permissions/workspaces`);t.searchParams.set("page",r.page?.toString()||"1"),t.searchParams.set("pagelen","50");let n=await this.config.request({url:t.toString(),headers:L(this.config,e)}),o=!!n.body.next;return{pageInfo:{hasNextPage:o,nextPage:o?n.body.page+1:null},data:n.body.values.map(i=>({id:i.workspace.uuid,slug:i.workspace.slug,name:i.workspace.name}))}}async getPullRequestsForUserAndWorkspace(r,e={}){let t=new URL(`${T}/workspaces/${r.workspaceSlug}/pullrequests/${r.userId}`);if(t.searchParams.set("fields","+values.participants,+values.destination.repository.links.clone.*,+values.source.repository.links.clone.*"),t.searchParams.set("page",r.page?.toString()||"1"),t.searchParams.set("pagelen","50"),r.repos&&r.repos.length>0){let i=`state = "open" AND (${r.repos.map(a=>`source.repository.full_name = "${a.namespace}/${a.name}"`).join(" OR ")})`;t.searchParams.set("q",i)}let n=await this.config.request({url:t.toString(),headers:L(this.config,e)}),o=!!n.body.next;return{pageInfo:{hasNextPage:o,nextPage:o?n.body.page+1:null},data:n.body.values.map(Nt)}}async getPullRequestsForRepoBase(r,e={}){let t=new URL(`${T}/repositories/${encodeURI(r.repo.namespace)}/${encodeURI(r.repo.name)}/pullrequests?state=OPEN`),n=[];r.reviewerId&&n.push(`reviewers.uuid="${r.reviewerId}"`),r.authorLogin&&n.push(`author.uuid="${r.authorLogin}"`);let o='state="OPEN"';return n.length&&(o+=` AND (${n.join(r.useOrFilter?" OR ":" AND ")})`),t.searchParams.set("fields","+values.participants,+values.destination.repository.links.clone.*,+values.source.repository.links.clone.*"),t.searchParams.set("page",r.page?.toString()||"1"),t.searchParams.set("pagelen","50"),t.searchParams.set("q",o),await this.config.request({url:t.toString(),headers:L(this.config,e)})}async getPullRequestsForRepo(r,e={}){let t=[],n=await this.getPullRequestsForRepoBase(r,e);n.body.values.forEach(i=>{t.push(Nt(i))});let o=!!n.body.next;return{pageInfo:{hasNextPage:o,nextPage:o?n.body.page+1:null},data:t}}async getPullRequestsForRepos(r,e={}){let t=[];return await Promise.all(r.repos.map(async n=>{try{(await this.getPullRequestsForRepoBase({repo:n,...r},e)).body.values.forEach(i=>{t.push(Nt(i))})}catch(o){if(o.statusCode!==404&&o.statusCode!==401)throw o}})),{data:t}}async getAccountsForWorkspace(r,e={}){let t=new URL(`${T}/workspaces/${encodeURI(r.workspace)}/members`);t.searchParams.set("page",r.page?.toString()||"1"),t.searchParams.set("pagelen","100");let n=await this.config.request({url:t.toString(),headers:L(this.config,e)}),o=!!n.body.next;return{pageInfo:{hasNextPage:o,nextPage:o?n.body.page+1:null},data:n.body.values.map(i=>xe(i.user))}}async getReposPermissionsForCurrentUser(r,e={}){let t=new URL(`${T}/user/permissions/repositories`);t.searchParams.set("page",r.page?.toString()||"1"),t.searchParams.set("pagelen","100");let n=await this.config.request({url:t.toString(),headers:L(this.config,e)}),o=!!n.body.next;return{pageInfo:{hasNextPage:o,nextPage:o?n.body.page+1:null},data:n.body.values.reduce((i,a)=>({...i,[a.repository.uuid]:nn(a.permission)}),{})}}async decorateReposWithPermissions(r,e={}){let t={},n=1;do{let o=await this.getReposPermissionsForCurrentUser({page:n},e);t={...o.data,...t},n=o.pageInfo.hasNextPage?o.pageInfo.nextPage:null}while(n!==null);return{data:r.repos.map(o=>({...o,permissions:t[o.id]??{canCreateWebhook:!1,canPush:!1,isAdmin:!1}}))}}async closePullRequest(r,e={}){let{pullRequest:t}=r;if(!(await this.config.request({method:"POST",url:`${T}/repositories/${t.repository.owner.login}/${t.repository.name}/pullrequests/${t.id}/decline`,headers:L(this.config,e)})).body.title)throw new Error("Could not close pull request")}async mergePullRequest(r,e={}){let{pullRequest:t,mergeStrategy:n}=r,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:`${T}/repositories/${t.repository.owner.login}/${t.repository.name}/pullrequests/${t.id}/merge`,body:JSON.stringify(i),headers:{...L(this.config,e),"Content-Type":"application/json"}})).body.title)throw new Error("Could not merge pull request")}async setPullRequestReviewers(r,e={}){let{pullRequest:t,reviewers:n}=r,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:`${T}/repositories/${t.repository.owner.login}/${t.repository.name}/pullrequests/${t.id}`,body:JSON.stringify(o),headers:{...L(this.config,e),"Content-Type":"application/json"}})).body.title)throw new Error("Could not set pull request reviewers")}};var _e={};z(_e,{normalizePermissions:()=>jt,restApiPullRequestToCommonPullRequest:()=>an});var an=s=>Se(s),jt=s=>s?s.find(r=>r.permission==="USER_ADMIN"||r.permission==="PROJECT_ADMIN"||r.permission==="ADMIN"||r.permission==="SYS_ADMIN"||r.permission==="REPO_ADMIN")?{canCreateWebhook:!0,canPush:!0,isAdmin:!0}:s.find(r=>r.permission==="REPO_WRITE"||r.permission==="REPO_CREATE"||r.permission==="PROJECT_CREATE"||r.permission==="PROJECT_WRITE")?{canCreateWebhook:!1,canPush:!0,isAdmin:!1}:{canCreateWebhook:!1,canPush:!1,isAdmin:!1}:{canCreateWebhook:!1,canPush:!1,isAdmin:!1};var Ce=s=>{let r=s.links.self[0].href;return{name:s.displayName,email:s.emailAddress,avatarUrl:s.avatarUrl??(r&&`${r}/avatar.png`),id:s.id.toString(),username:s.name,url:r}},Se=s=>{let r={OPEN:"OPEN",MERGED:"MERGED",DECLINED:"CLOSED"},e={UNAPPROVED:"REVIEW_REQUESTED",NEEDS_WORK:"CHANGES_REQUESTED",APPROVED:"APPROVED"},t=s.reviewers.map(u=>({reviewer:Ce(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:r[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:Ce(s.author.user),assignees:null,reviews:t,reviewDecision:H(t),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}},Qr=s=>({id:s.id.toString(),namespace:s.project.key,name:s.slug,webUrl:s.links.self[0]?.href??null,httpsUrl:s.links.clone.find(r=>r.name==="https"||r.name==="http")?.href??null,sshUrl:s.links.clone.find(r=>r.name==="ssh")?.href??null,defaultBranch:null,permissions:null}),he=class extends j{getBaseUrl(r){let e=r.baseUrl||this.config.baseUrl;if(!e)throw new Error('Bitbucket Server requires "baseUrl"');return e}getRequestHeaders(r){return f(r.token||this.config.token)}async getCurrentUser(r={},e={}){let t=await this.config.request({url:`${this.getBaseUrl(e)}/users?limit=2`,headers:this.getRequestHeaders(e)}),{headers:{"x-auserid":n,"x-ausername":o}}=t,i=n?parseInt(n,10):null,a=decodeURIComponent(o),l=(await this.config.request({url:`${this.getBaseUrl(e)}/users?filter=${o}&avatarSize=64`,headers:this.getRequestHeaders(e)})).body.values.find(({emailAddress:p,id:c,name:d,slug:g})=>i?i===c:a===d||a===p||a===g);if(!l)throw new Error("Could not find current Bitbucket Server user");return{data:Ce(l)}}async getUserForCommit(r,e){let{repo:t,oid:n}=r,o=await this.config.request({url:`${this.getBaseUrl(e)}/projects/${t.namespace}/repos/${t.name}/commits/${n}`,headers:this.getRequestHeaders(e)});if(!o.body.author)throw new Error("Could not find user for commit");return{data:Ce(o.body.author)}}async getRepo(r,e={}){let t=await this.config.request({url:`${this.getBaseUrl(e)}/projects/${r.namespace}/repos/${r.name}`,headers:this.getRequestHeaders(e)});return{data:Qr(t.body)}}async getRepos(r,e={}){let t=[],n=[];return await Promise.all(r.map(async o=>{try{let i=await this.getRepo(o,e);t.push(i.data)}catch(i){n.push({input:o,error:i})}})),{data:t,errors:n}}async getReposForCurrentUser(r,e={}){let t=r.page??0,n=await this.config.request({url:`${this.getBaseUrl(e)}/repos?start=${t}`,headers:this.getRequestHeaders(e)});return{pageInfo:{hasNextPage:!n.body.isLastPage,nextPage:n.body.nextPageStart},data:n.body.values.map(Qr)}}async getRepoPermissionsForUsername(r,e={}){let t=new URL(`${this.getBaseUrl(e)}/projects/${r.repo.namespace}/repos/${r.repo.name}/permissions/search?filterText=${r.username}`);try{let n=await this.config.request({url:t.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(r,e={}){return await Promise.all(r.repos.map(async n=>{let o=await this.getRepoPermissionsForUsername({repo:n,username:r.username},e);return{...n,permissions:o.data}}))}async getPullRequestsForRepoBase(r,e={}){let t=new URL(`${this.getBaseUrl(e)}/projects/${encodeURI(r.repo.namespace)}/repos/${encodeURI(r.repo.name)}/pull-requests?state=OPEN`);return t.searchParams.set("start",r.page?.toString()||"0"),t.searchParams.set("limit","50"),await this.config.request({url:t.toString(),headers:this.getRequestHeaders(e)})}async getPullRequestsForRepo(r,e={}){let t=[],n=await this.getPullRequestsForRepoBase(r,e);n.body.values.forEach(i=>{if(r.authorLogin&&i.author.user.name!==r.authorLogin)return null;t.push(Se(i))});let o=n.body.values.length!==0;return{pageInfo:{hasNextPage:o,nextPage:o?n.body.start+n.body.values.length:null},data:t}}async getPullRequestsForRepos(r,e={}){let t=[];return await Promise.all(r.repos.map(async n=>{try{(await this.getPullRequestsForRepoBase({repo:n,...r},e)).body.values.forEach(i=>{if(r.authorLogin&&i.author.user.name!==r.authorLogin)return null;t.push(Se(i))})}catch(o){if(o.statusCode!==404&&o.statusCode!==401)throw o}})),{data:t}}async getPullRequestsForCurrentUser(r,e={}){let t=new URL(`${this.getBaseUrl(e)}/dashboard/pull-requests`);t.searchParams.set("state","OPEN"),t.searchParams.set("start",r.page?.toString()||"0"),t.searchParams.set("limit","50");let n=await this.config.request({url:t.toString(),headers:this.getRequestHeaders(e)}),o=n.body.values.length!==0;return{pageInfo:{hasNextPage:o,nextPage:o?n.body.start+n.body.values.length:null},data:n.body.values.map(Se)}}async closePullRequest(r,e={}){let{pullRequest:t}=r;if(t.version===void 0)throw new Error('Bitbucket Server requires "version" for this function.');if(!(await this.config.request({method:"POST",url:`${this.getBaseUrl(e)}/projects/${t.repository.owner.login}/repos/${t.repository.name}/pull-requests/${t.id}/decline`,body:JSON.stringify({version:t.version}),headers:{...this.getRequestHeaders(e),"Content-Type":"application/json"}})).body.title)throw new Error("Could not close pull request")}async mergePullRequest(r,e={}){let{pullRequest:t,mergeStrategyId:n}=r;if(r.mergeStrategy)throw new Error('Bitbucket Server uses "mergeStrategyId" instead of "mergeStrategy".');if(t.version===void 0)throw new Error('Bitbucket Server requires "version" for this function.');if(!(await this.config.request({method:"POST",url:`${this.getBaseUrl(e)}/projects/${t.repository.owner.login}/repos/${t.repository.name}/pull-requests/${t.id}/merge`,body:JSON.stringify({strategyId:n,version:t.version}),headers:{...this.getRequestHeaders(e),"Content-Type":"application/json"}})).body.title)throw new Error("Could not merge pull request")}async getMergeStrategies(r={}){let e=await this.config.request({url:`${this.getBaseUrl(r)}/admin/pull-requests/git`,headers:{...this.getRequestHeaders(r),"Content-Type":"application/json"}});return{data:{defaultStrategy:e.body.mergeConfig.defaultStrategy,strategies:e.body.mergeConfig.strategies}}}async setPullRequestReviewers(r,e={}){let{pullRequest:t,reviewers:n}=r;if(t.version===void 0)throw new Error('Bitbucket Server requires "version" for this function.');let o={reviewers:n.map(a=>{if(a.username)throw new Error('Bitbucket Server reviewer requires "username" for this function.');return{user:{name:a.username}}}),version:t.version};if(!(await this.config.request({method:"PUT",url:`${this.getBaseUrl(e)}/projects/${t.repository.owner.login}/repos/${t.repository.name}/pull-requests/${t.id}`,body:JSON.stringify(o),headers:{...this.getRequestHeaders(e),"Content-Type":"application/json"}})).body.title)throw new Error("Could not set pull request reviewers")}async getAccountsForProject(r,e={}){let t=new URL(`${this.getBaseUrl(e)}/projects/${encodeURI(r.project)}/permissions/users`);t.searchParams.set("start",r.page?.toString()||"0"),t.searchParams.set("limit","50");let n=await this.config.request({url:t.toString(),headers:this.getRequestHeaders(e)}),o=n.body.values.length!==0;return{pageInfo:{hasNextPage:o,nextPage:o?n.body.start+n.body.values.length:null},data:n.body.values.map(i=>Ce(i.user))}}};var ss=require("js-base64");var Ne=(e=>(e.Open="OPEN",e.Closed="CLOSED",e))(Ne||{});var R=class extends Error{constructor(e,t){let n=t?.map(i=>`'${i.message}'`).join(", "),o=n?`${e}: ${n}`:e;super(o);this.graphQLErrors=t??[]}};var un={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]},Fr=15,Mr=100,De={__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"},O=s=>!!s,J=(s,r)=>{let e=un[r];for(let t=0;t<3;t++){if(s[t]>e[t])return!0;if(s[t]<e[t])return!1}return!0},Be="https://api.github.com",ln=`${Be}/graphql`,Qe=`
|
|
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 wi={};H(wi,{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:()=>Ut,Linear:()=>Ee,PullRequestAsyncStatus:()=>rn,Trello:()=>Se,TrelloUtils:()=>Gt,Utils:()=>Pi,default:()=>yi,isFetch:()=>Be});module.exports=mn(wi);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 G=(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}},Un=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}}},Gn=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:G(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: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: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:G(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:Gn(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(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: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: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:G(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:G(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: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=>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: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]:Un(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 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,Ue={__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=`
|
|
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
|
+
`,xn=`
|
|
11
11
|
... on CheckRun {
|
|
12
12
|
completedAt
|
|
13
13
|
conclusion
|
|
@@ -16,63 +16,63 @@ url
|
|
|
16
16
|
permalink
|
|
17
17
|
startedAt
|
|
18
18
|
}
|
|
19
|
-
`,
|
|
19
|
+
`,He=/\/api\/v\d+$/,Ke=`
|
|
20
20
|
color
|
|
21
21
|
description
|
|
22
22
|
id
|
|
23
23
|
name
|
|
24
|
-
`,
|
|
24
|
+
`,is=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.")},Nn=(s,t)=>{let e=t.baseUrl||s.baseUrl;return e?(e=e.replace(/\/$/,""),is(e),He.test(e)&&(e=e.replace(He,"")),`${e}/api/graphql`):kn},X=(s,t)=>{let e=t.baseUrl||s.baseUrl;return e?(e=e.replace(/\/$/,""),is(e),He.test(e)&&(e=e.replace(He,"")),`${e}/api/v3`):Ve},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:Nn(s,e),method:"POST",headers:r,body:JSON.stringify(t)})},Bn={user:!0,"user:email":!0,"read:user":!0},te=s=>s.some(t=>Bn[t]),F=(s=!1,t=!1,e)=>`
|
|
25
25
|
__typename
|
|
26
|
-
${
|
|
27
|
-
${
|
|
28
|
-
${
|
|
29
|
-
${
|
|
30
|
-
${
|
|
31
|
-
${
|
|
32
|
-
${
|
|
33
|
-
`,
|
|
26
|
+
${ie(e,["graphQLId"],"id")}
|
|
27
|
+
${ie(e,["id"],"databaseId")}
|
|
28
|
+
${ie(e,["name"],"name")}
|
|
29
|
+
${ie(e,["name","username"],"login")}
|
|
30
|
+
${t?ie(e,["email"],"email"):""}
|
|
31
|
+
${ie(e,["avatarUrl"],`avatarUrl${s?"(size: $avatarSize)":""}`)}
|
|
32
|
+
${ie(e,["url"],"url")}
|
|
33
|
+
`,jn=(s=!1)=>`
|
|
34
34
|
latestReviews(first: 100) {
|
|
35
35
|
nodes {
|
|
36
36
|
author {
|
|
37
37
|
... on User {
|
|
38
|
-
${
|
|
38
|
+
${F(!1,s)}
|
|
39
39
|
}
|
|
40
40
|
... on EnterpriseUserAccount {
|
|
41
|
-
${
|
|
41
|
+
${Ht(!1)}
|
|
42
42
|
}
|
|
43
43
|
}
|
|
44
44
|
state
|
|
45
45
|
}
|
|
46
46
|
}
|
|
47
|
-
`,
|
|
47
|
+
`,as=(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
|
+
`,Ht=(s=!1)=>`
|
|
55
55
|
__typename
|
|
56
56
|
id
|
|
57
57
|
login
|
|
58
58
|
avatarUrl${s?"(size: $avatarSize)":""}
|
|
59
59
|
url
|
|
60
|
-
`,
|
|
60
|
+
`,Xe=(s,t=!1,e)=>`
|
|
61
61
|
id
|
|
62
|
-
${!e||
|
|
62
|
+
${!e||K(e,"PR_FULL_DATABASE_ID")?"fullDatabaseId":"databaseId"}
|
|
63
63
|
number
|
|
64
64
|
title
|
|
65
65
|
body
|
|
66
66
|
state
|
|
67
67
|
author {
|
|
68
68
|
... on User {
|
|
69
|
-
${
|
|
69
|
+
${F(!1,t)}
|
|
70
70
|
}
|
|
71
71
|
... on Bot {
|
|
72
|
-
${
|
|
72
|
+
${as(!1)}
|
|
73
73
|
}
|
|
74
74
|
... on EnterpriseUserAccount {
|
|
75
|
-
${
|
|
75
|
+
${Ht(!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||
|
|
88
|
+
${!e||K(e,"CHECK_RUN")?xn:""}
|
|
89
89
|
... on StatusContext {
|
|
90
90
|
context
|
|
91
91
|
createdAt
|
|
@@ -132,6 +132,7 @@ headRepository {
|
|
|
132
132
|
}
|
|
133
133
|
url
|
|
134
134
|
sshUrl
|
|
135
|
+
isFork
|
|
135
136
|
}
|
|
136
137
|
${s?"isDraft":""}
|
|
137
138
|
url
|
|
@@ -147,47 +148,47 @@ closedAt
|
|
|
147
148
|
mergedAt
|
|
148
149
|
assignees(first: 100) {
|
|
149
150
|
nodes {
|
|
150
|
-
${
|
|
151
|
+
${F(!1,t)}
|
|
151
152
|
}
|
|
152
153
|
}
|
|
153
154
|
reviewRequests(first: 100) {
|
|
154
155
|
nodes {
|
|
155
|
-
${!e||
|
|
156
|
+
${!e||K(e,"AS_CODE_OWNER")?"asCodeOwner":""}
|
|
156
157
|
requestedReviewer {
|
|
157
158
|
... on User {
|
|
158
|
-
${
|
|
159
|
+
${F(!1,t)}
|
|
159
160
|
}
|
|
160
161
|
}
|
|
161
162
|
}
|
|
162
163
|
}
|
|
163
|
-
${!e||
|
|
164
|
+
${!e||K(e,"LATEST_REVIEWS")?jn(t):""}
|
|
164
165
|
additions
|
|
165
166
|
deletions
|
|
166
167
|
changedFiles
|
|
167
168
|
mergeable
|
|
168
169
|
mergeStateStatus
|
|
169
170
|
milestone {
|
|
170
|
-
${
|
|
171
|
+
${Je}
|
|
171
172
|
}
|
|
172
173
|
labels(first: 100) {
|
|
173
174
|
nodes {
|
|
174
|
-
${
|
|
175
|
+
${Ke}
|
|
175
176
|
}
|
|
176
177
|
}
|
|
177
|
-
${!e||
|
|
178
|
-
`,
|
|
178
|
+
${!e||K(e,"VIEWER_CAN_MERGE_AS_ADMIN")?"viewerCanMergeAsAdmin":""}
|
|
179
|
+
`,Qn=(s=!1,t)=>`
|
|
179
180
|
id
|
|
180
|
-
${!
|
|
181
|
+
${!t||K(t,"ISSUE_FULL_DATABASE_ID")?"fullDatabaseId":"databaseId"}
|
|
181
182
|
title
|
|
182
183
|
author {
|
|
183
184
|
... on User {
|
|
184
|
-
${
|
|
185
|
+
${F(!1,s)}
|
|
185
186
|
}
|
|
186
187
|
... on Bot {
|
|
187
|
-
${
|
|
188
|
+
${as(!1)}
|
|
188
189
|
}
|
|
189
190
|
... on EnterpriseUserAccount {
|
|
190
|
-
${
|
|
191
|
+
${Ht(!1)}
|
|
191
192
|
}
|
|
192
193
|
}
|
|
193
194
|
closedAt
|
|
@@ -211,39 +212,39 @@ comments {
|
|
|
211
212
|
}
|
|
212
213
|
assignees(first: 100) {
|
|
213
214
|
nodes {
|
|
214
|
-
${
|
|
215
|
+
${F(!1,s)}
|
|
215
216
|
}
|
|
216
217
|
}
|
|
217
218
|
state
|
|
218
219
|
milestone {
|
|
219
|
-
${
|
|
220
|
+
${Je}
|
|
220
221
|
}
|
|
221
222
|
labels(first: 100) {
|
|
222
223
|
nodes {
|
|
223
|
-
${
|
|
224
|
+
${Ke}
|
|
224
225
|
}
|
|
225
226
|
}
|
|
226
|
-
`,
|
|
227
|
+
`,Fn={"-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"},zn=new RegExp('(([^\\s]+:)?\\"(?:[^\\"\\\\]|\\\\.)*\\"?)|([^\\"\\s]+)',"g"),Vt=s=>{let t=[];return(s.match(zn)??[]).forEach(r=>{if(r.includes(":")&&r!="is:closed"){let n=r.split(":")[0];Fn[n]&&t.push(r)}}),t},Jt="is:open",us=s=>{if(!s||s.length===0)return Jt;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"},ls=s=>{if(!s||s.length===0)return Jt;let t=new Set(s),e=t.has("OPEN"),r=t.has("CLOSED");return e&&r?"":r?"is:closed":"is:open"},Kt=(s,t,e,r)=>{let n=s==="issue",o=r.stateQualifier??Jt;return{query:`
|
|
227
228
|
query SearchIssuesOrPullRequests($query: String! $after: String) {
|
|
228
|
-
search(type:ISSUE query:$query first: ${
|
|
229
|
+
search(type:ISSUE query:$query first: ${r.maxPageSize} after:$after) {
|
|
229
230
|
pageInfo {
|
|
230
231
|
hasNextPage
|
|
231
232
|
endCursor
|
|
232
233
|
}
|
|
233
234
|
nodes {
|
|
234
235
|
... on ${n?"Issue":"PullRequest"} {
|
|
235
|
-
${n?
|
|
236
|
+
${n?Qn(r.supportsEmail,r.enterpriseVersion??null):Xe(r.supportsDrafts??!1,r.supportsEmail,r.enterpriseVersion??null)}
|
|
236
237
|
}
|
|
237
238
|
}
|
|
238
239
|
}
|
|
239
|
-
}`,variables:{query:`is:${s}
|
|
240
|
+
}`,variables:{query:`is:${s} ${o} ${r.includeFromArchivedRepos?"":"archived:false"} ${t}`,after:e}}},Mn="Field 'isDraft' doesn't exist on type 'PullRequest'",Ze=(s=[])=>s.some(t=>t?.message===Mn),Wn=/@@ -(\d+)(?:,\d+ | )\+(\d+)(?:,\d+ | )@@(?:\\n)?/,Hn=`
|
|
240
241
|
\
|
|
241
|
-
+`,
|
|
242
|
+
+`,ps=(s,t,e,r)=>{let n=Wn.exec(s);if(!n||!n[0]||!n[1])return[];let o=parseInt(n[1],10),i=parseInt(n[2],10),a=s.replace(Hn,`
|
|
242
243
|
+`).split(`
|
|
243
|
-
`).slice(1),u=o-1,l=i-1,p=a.map(g=>{let m,
|
|
244
|
-
`;break}case"+":{m="ADDED",l+=1,
|
|
245
|
-
`;break}default:m="UNMODIFIED",l+=1,u+=1,
|
|
246
|
-
`}return{line:
|
|
244
|
+
`).slice(1),u=o-1,l=i-1,p=a.map(g=>{let m,h;switch(g[0]){case"-":{m="DELETED",u+=1,h=`${g.slice(1)}
|
|
245
|
+
`;break}case"+":{m="ADDED",l+=1,h=`${g.slice(1)}
|
|
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}}),d=e,c=t;if(d!==null&&c!==null&&r!==null&&d<c){let g=0,m=p.length,h=r==="LEFT"?"oldLineNumber":"newLineNumber";for(let y=0;y<p.length;y++){let P=p[y][h];P===d?g=y:P===c&&(m=y)}p=p.slice(g,m+1)}return p},ds=s=>{let t=s.author;return t||(t=Ue),{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 cs=`mutation DeleteIssueComment(
|
|
247
248
|
$issueCommentId: ID!
|
|
248
249
|
) {
|
|
249
250
|
deleteIssueComment(input: {
|
|
@@ -251,7 +252,7 @@ query SearchIssuesOrPullRequests($query: String! $after: String) {
|
|
|
251
252
|
}) {
|
|
252
253
|
clientMutationId
|
|
253
254
|
}
|
|
254
|
-
}`,
|
|
255
|
+
}`,ms=`mutation DeletePullRequestReviewComment(
|
|
255
256
|
$pullRequestReviewCommentId: ID!
|
|
256
257
|
) {
|
|
257
258
|
deletePullRequestReviewComment(input: {
|
|
@@ -261,7 +262,7 @@ query SearchIssuesOrPullRequests($query: String! $after: String) {
|
|
|
261
262
|
id
|
|
262
263
|
}
|
|
263
264
|
}
|
|
264
|
-
}`,
|
|
265
|
+
}`,gs=`mutation UpdateIssueComment(
|
|
265
266
|
$issueCommentId: ID!,
|
|
266
267
|
$body: String!
|
|
267
268
|
) {
|
|
@@ -274,7 +275,7 @@ query SearchIssuesOrPullRequests($query: String! $after: String) {
|
|
|
274
275
|
body
|
|
275
276
|
}
|
|
276
277
|
}
|
|
277
|
-
}`,
|
|
278
|
+
}`,hs=`mutation ResolveReviewThread(
|
|
278
279
|
$pullRequestReviewThreadId: ID!
|
|
279
280
|
) {
|
|
280
281
|
resolveReviewThread(input: {
|
|
@@ -285,7 +286,7 @@ query SearchIssuesOrPullRequests($query: String! $after: String) {
|
|
|
285
286
|
isResolved
|
|
286
287
|
}
|
|
287
288
|
}
|
|
288
|
-
}`,
|
|
289
|
+
}`,fs=`mutation UnresolveReviewThread(
|
|
289
290
|
$pullRequestReviewThreadId: ID!
|
|
290
291
|
) {
|
|
291
292
|
unresolveReviewThread(input: {
|
|
@@ -296,7 +297,7 @@ query SearchIssuesOrPullRequests($query: String! $after: String) {
|
|
|
296
297
|
isResolved
|
|
297
298
|
}
|
|
298
299
|
}
|
|
299
|
-
}`,
|
|
300
|
+
}`,Rs=`mutation UpdatePullRequestReviewComment(
|
|
300
301
|
$pullRequestReviewCommentId: ID!,
|
|
301
302
|
$body: String!
|
|
302
303
|
) {
|
|
@@ -309,7 +310,7 @@ query SearchIssuesOrPullRequests($query: String! $after: String) {
|
|
|
309
310
|
body
|
|
310
311
|
}
|
|
311
312
|
}
|
|
312
|
-
}`;var
|
|
313
|
+
}`;var Is=s=>`
|
|
313
314
|
query GetPullRequestComments(
|
|
314
315
|
$namespace: String!
|
|
315
316
|
$name: String!
|
|
@@ -355,7 +356,7 @@ query GetPullRequestComments(
|
|
|
355
356
|
}
|
|
356
357
|
}
|
|
357
358
|
}
|
|
358
|
-
`;var
|
|
359
|
+
`;var Xt=`
|
|
359
360
|
id
|
|
360
361
|
databaseId
|
|
361
362
|
owner {
|
|
@@ -368,18 +369,18 @@ defaultBranchRef {
|
|
|
368
369
|
name
|
|
369
370
|
}
|
|
370
371
|
viewerPermission
|
|
371
|
-
`,
|
|
372
|
+
`,Vn={APPROVED:"APPROVED",CHANGES_REQUESTED:"CHANGES_REQUESTED",COMMENTED:"COMMENTED",REVIEW_REQUESTED:"REVIEW_REQUESTED"},Jn={MERGEABLE:"MERGEABLE",CONFLICTING:"CONFLICTS",UNKNOWN:"UNKNOWN"},Kn={BEHIND:"BEHIND",BLOCKED:"BLOCKED",UNKNOWN:"UNKNOWN_AND_BLOCKED",UNSTABLE:"UNSTABLE",CLEAN:null,DIRTY:null,DRAFT:null,HAS_HOOKS:null},Xn={OPEN:"OPEN",CLOSED:"CLOSED"},Zn=["ADMIN","MAINTAIN","TRIAGE","WRITE"],er=s=>({color:`#${s.color}`,description:s.description,graphQLId:s.id,id:null,name:s.name}),Yn=s=>({canCreateWebhook:s==="ADMIN",canPush:s==="ADMIN"||s==="MAINTAIN"||s==="WRITE",isAdmin:s==="ADMIN"}),Zt=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:Yn(s.viewerPermission)}),eo=s=>({canCreateWebhook:s.admin,canPush:s.admin||s.maintain||s.push,isAdmin:s.admin}),bs=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:eo(s.permissions)}),to=s=>({path:s.path,isDirectory:s.type==="tree"}),ro={OPEN:"OPEN",CLOSED:"CLOSED",MERGED:"MERGED"},so={id:!0,graphQLId:!0,name:!0,username:!0,email:!0,avatarUrl:!0,url:!0},W=(s,t=so)=>{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},no=(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]},oo=s=>({ERROR:"ERROR",EXPECTED:"PENDING",FAILURE:"FAILED",PENDING:"PENDING",SUCCESS:"SUCCESS"})[s],Yt=s=>{let t=null;s.author?t=s.author:t=Ue;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=Ue;return i.author&&i.author.__typename&&(a=i.author),{reviewer:W(a),state:Vn[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:ro[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:oo(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:no(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:Kn[s.mergeStateStatus]??Jn[s.mergeable],milestone:s.milestone?tr(s.milestone):null,labels:s.labels?.nodes?.filter(k).map(er)??[],permissions:{canMerge:Zn.includes(s.repository.viewerPermission),canMergeAndBypassProtections:s.viewerCanMergeAsAdmin??!1}}},io=s=>{let{id:t,comments:e,isOutdated:r,isResolved:n,line:o,startLine:i,diffSide:a,originalLine:u,originalStartLine:l,startDiffSide:p}=s,d=e.nodes?.[0];if(!d)return null;let{author:c,body:g,databaseId:m,fullDatabaseId:h,id:y,path:f,publishedAt:P,url:v}=d,A=o??u,D=i??l,w=a??p;return{author:c?{avatarUrl:c.avatarUrl,email:null,name:c.login}:null,body:g,createdAt:P?new Date(P):null,diffLines:ps(d.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(ao)??[],url:v,line:A,startLine:D,side:w}},ao=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}),uo=s=>{let t=null;return s.author?t=s.author:t=Ue,{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:Xn[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?tr(s.milestone):null,labels:s.labels?.nodes?.filter(k).map(er)??[]}},tr=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}),ye=class extends Q{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(Ve)?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=Br(e.fields),o=await this.getScopes(r),i=await b(this.config,{query:`
|
|
372
373
|
query getCurrentUser {
|
|
373
374
|
viewer {
|
|
374
|
-
${
|
|
375
|
+
${F(!1,te(o),n)}
|
|
375
376
|
}
|
|
376
377
|
}
|
|
377
|
-
`},
|
|
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:`
|
|
378
379
|
query getAccountsForRepo($owner: String!, $name: String! $cursor: String, $first: Int!) {
|
|
379
380
|
repository(owner: $owner, name: $name) {
|
|
380
381
|
assignableUsers(first: $first, after: $cursor) {
|
|
381
382
|
nodes {
|
|
382
|
-
${
|
|
383
|
+
${F(!1,te(n))}
|
|
383
384
|
}
|
|
384
385
|
pageInfo {
|
|
385
386
|
endCursor
|
|
@@ -388,7 +389,7 @@ query getAccountsForRepo($owner: String!, $name: String! $cursor: String, $first
|
|
|
388
389
|
}
|
|
389
390
|
}
|
|
390
391
|
}
|
|
391
|
-
`,variables:{owner:o,name:i,cursor:a,first:$}},
|
|
392
|
+
`,variables:{owner:o,name:i,cursor:a,first:$}},r);if(!u.body.data)throw new I("Could not fetch accounts for repo",u.body.errors);return{pageInfo:u.body.data.repository?.assignableUsers?.pageInfo??{endCursor:null,hasNextPage:!1},data:u.body.data.repository?.assignableUsers?.nodes?.map(l=>W(l))??[]}}async getUserForCommit(e,r={}){let n=await b(this.config,{query:`
|
|
392
393
|
query getUserForCommit(
|
|
393
394
|
$owner: String!
|
|
394
395
|
$name: String!
|
|
@@ -407,7 +408,7 @@ query getUserForCommit(
|
|
|
407
408
|
}
|
|
408
409
|
}
|
|
409
410
|
}
|
|
410
|
-
`,variables:{owner:e.repo.namespace,name:e.repo.name,oid:e.oid,avatarSize:e.avatarSize}},
|
|
411
|
+
`,variables:{owner:e.repo.namespace,name:e.repo.name,oid:e.oid,avatarSize:e.avatarSize}},r),o=n.body.data?.repository;if(!o)throw new I("Repository not found.",n.body.errors);let i=o.object?.author;if(!i)throw new I("Commit not found.",n.body.errors);return{data:{name:i.name,email:i.email,avatarUrl:this.getEnterpriseAvatarUrlIfNeeded(i.avatarUrl,i.email,r)}}}async createCommit(e,r={}){let{commitMessage:n,deletedFiles:o,newOrModifiedFiles:i,repo:a,target:u}=e,l=await b(this.config,{query:`
|
|
411
412
|
mutation createCommitOnBranch(
|
|
412
413
|
$branchName: String!,
|
|
413
414
|
$expectedHeadOid: GitObjectID!,
|
|
@@ -434,23 +435,23 @@ mutation createCommitOnBranch(
|
|
|
434
435
|
}
|
|
435
436
|
}
|
|
436
437
|
}
|
|
437
|
-
`,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(([p,d])=>({contents:ys.Base64.encode(d),path:p})),deletions:o.map(p=>({path:p}))},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:`
|
|
438
439
|
query getAccountForEmail($query: String! $avatarSize: Int) {
|
|
439
440
|
search(query: $query, type: USER, first: 1) {
|
|
440
441
|
nodes {
|
|
441
442
|
... on User {
|
|
442
|
-
${
|
|
443
|
+
${F(!0,te(n))}
|
|
443
444
|
}
|
|
444
445
|
}
|
|
445
446
|
}
|
|
446
447
|
}
|
|
447
|
-
`,variables:{query:`in:email ${e.email}`,avatarSize:e.avatarSize}},
|
|
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:`
|
|
448
449
|
query getUserForUsername($login: String! $avatarSize: Int) {
|
|
449
450
|
user(login: $login) {
|
|
450
|
-
${
|
|
451
|
+
${F(!0,te(n))}
|
|
451
452
|
}
|
|
452
453
|
}
|
|
453
|
-
`,variables:{login:e.username,avatarSize:e.avatarSize}},
|
|
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:`
|
|
454
455
|
query getOrgsForCurrentUser($cursor: String, $first: Int!) {
|
|
455
456
|
viewer {
|
|
456
457
|
organizations(first: $first after: $cursor) {
|
|
@@ -469,7 +470,7 @@ query getOrgsForCurrentUser($cursor: String, $first: Int!) {
|
|
|
469
470
|
}
|
|
470
471
|
}
|
|
471
472
|
}
|
|
472
|
-
`,variables:{cursor:e.cursor,first:$}},
|
|
473
|
+
`,variables:{cursor:e.cursor,first:$}},r);if(!n.body.data)throw new I("Could not fetch orgs for current user",n.body.errors);let o=n.body.data.viewer.organizations.nodes||[];return{pageInfo:n.body.data.viewer.organizations.pageInfo,data:o.map(i=>({id:i.databaseId.toString(),graphQLId:i.id,username:i.login,name:i.name||null,email:i.email||null,avatarUrl:i.avatarUrl}))}}async getOrgMembers(e,r={}){let n=await b(this.config,{query:`
|
|
473
474
|
query getOrgMember($cursor: String, $first: Int!, $login: String!) {
|
|
474
475
|
viewer {
|
|
475
476
|
organization(login: $login) {
|
|
@@ -479,28 +480,28 @@ query getOrgMember($cursor: String, $first: Int!, $login: String!) {
|
|
|
479
480
|
hasNextPage
|
|
480
481
|
}
|
|
481
482
|
nodes {
|
|
482
|
-
${
|
|
483
|
+
${F(!1,!0)}
|
|
483
484
|
}
|
|
484
485
|
}
|
|
485
486
|
}
|
|
486
487
|
}
|
|
487
488
|
}
|
|
488
|
-
`,variables:{cursor:e.cursor,first:$,login:e.org}},
|
|
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:`
|
|
489
490
|
query getRepo($owner: String!, $name: String!) {
|
|
490
491
|
repository(owner: $owner, name: $name) {
|
|
491
|
-
${
|
|
492
|
+
${Xt}
|
|
492
493
|
}
|
|
493
494
|
}
|
|
494
|
-
`,variables:{owner:e.namespace,name:e.name}},
|
|
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:Zt(n.body.data.repository)}}async getRepos(e,r={}){let n=e.map(({namespace:u,name:l},p)=>`
|
|
495
496
|
getRepo_${p}: repository(owner: "${u}", name: "${l}") {
|
|
496
|
-
${
|
|
497
|
+
${Xt}
|
|
497
498
|
}
|
|
498
499
|
`).join(`
|
|
499
500
|
`),o=await b(this.config,{query:`
|
|
500
501
|
query batchGetRepos {
|
|
501
502
|
${n}
|
|
502
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 p=o.body.data[`getRepo_${l}`];p?i.push(Zt(p)):a.push({input:u})}),{data:i,errors:a}}async fetchMultipleRESTPages(e,r,n,o){let i=[];for(let d=0;d<r;d++)i.push(n(e+d));let a=await Promise.all(i),u=[];for(let d of a){if(!d.body)throw new Error(d.statusText||"Unknown error");u=u.concat(d.body.map(c=>o(c)))}let l=a.every(d=>d.body.length===100),p=e+r;return{data:u,pageInfo:{hasNextPage:l,nextPage:l?p:null}}}async getReposForCurrentUser(e,r={}){if(e.simultaneousPagesToFetch&&e.simultaneousPagesToFetch>40)throw new Error("The argument 'simultaneousPagesToFetch' cannot exceed 40 for 'getReposForCurrentUser'");let n=new URLSearchParams;n.append("per_page","100"),e.affiliations&&n.append("affiliation",e.affiliations.join(","));let o=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,bs)}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,bs)}async getReposForUsernames(e,r={}){if(!e.usernames.length)return{pageInfo:{endCursor:null,hasNextPage:!1},data:[]};let n=await b(this.config,{query:`
|
|
504
505
|
query getReposForUsernames($query: String!, $cursor: String, $first: Int!) {
|
|
505
506
|
search(query: $query, type: REPOSITORY, first: $first, after: $cursor) {
|
|
506
507
|
pageInfo {
|
|
@@ -509,12 +510,12 @@ query getReposForUsernames($query: String!, $cursor: String, $first: Int!) {
|
|
|
509
510
|
}
|
|
510
511
|
nodes {
|
|
511
512
|
... on Repository {
|
|
512
|
-
${
|
|
513
|
+
${Xt}
|
|
513
514
|
}
|
|
514
515
|
}
|
|
515
516
|
}
|
|
516
517
|
}
|
|
517
|
-
`,variables:{query:`fork:true ${e.usernames.map(i=>`user:${i}`).join(" ")}`,cursor:e.cursor,first:$}},
|
|
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(Zt)}}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:`
|
|
518
519
|
query getRefs($owner: String!, $name: String!, $refPrefix: String!, $cursor: String, $first: Int!) {
|
|
519
520
|
repository(owner: $owner, name: $name) {
|
|
520
521
|
refs(refPrefix: $refPrefix first: $first after: $cursor) {
|
|
@@ -535,7 +536,7 @@ query getRefs($owner: String!, $name: String!, $refPrefix: String!, $cursor: Str
|
|
|
535
536
|
}
|
|
536
537
|
}
|
|
537
538
|
}
|
|
538
|
-
`,variables:{owner:
|
|
539
|
+
`,variables:{owner:r.repo.namespace,name:r.repo.name,refPrefix:e,cursor:r.cursor,first:$}},n),i=o.body.data?.repository;if(!i)throw new I("Ref repository not found.",o.body.errors);let a=i.refs;return a?{pageInfo:a.pageInfo,data:(a.nodes||[]).map(u=>{let l=u.target?.oid?u.target:null;return{name:u.name,commit:l?{oid:l.oid,authoredDate:new Date(l.authoredDate),committedDate:new Date(l.committedDate)}:null}})}:{pageInfo:{endCursor:null,hasNextPage:!1},data:[]}}async getBranches(e,r={}){return this.getRefs("refs/heads/",e,r)}async getTags(e,r={}){return this.getRefs("refs/tags/",e,r)}async getBlame(e,r={}){let n=await b(this.config,{query:`
|
|
539
540
|
query getBlame($owner: String!, $name: String!, $ref: String!, $path: String!) {
|
|
540
541
|
repository(owner: $owner, name: $name) {
|
|
541
542
|
object(expression: $ref) {
|
|
@@ -574,7 +575,7 @@ query getBlame($owner: String!, $name: String!, $ref: String!, $path: String!) {
|
|
|
574
575
|
}
|
|
575
576
|
}
|
|
576
577
|
}
|
|
577
|
-
`,variables:{owner:e.repo.namespace,name:e.repo.name,ref:e.ref,path:e.path}},
|
|
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=te(o),a=us(e.states),u=d=>{let c=d&&typeof e.isDraft=="boolean"?`${e.query} draft:${e.isDraft}`:e.query;return Kt("pr",c,e.cursor,{maxPageSize:e.maxPageSize??ns,supportsEmail:i,supportsDrafts:d,enterpriseVersion:n,includeFromArchivedRepos:e.includeFromArchivedRepos,stateQualifier:a})},l=await b(this.config,u(!0),r);l.body.errors&&Ze(l.body.errors)&&(this.config.baseUrl||r.baseUrl)&&(l=await b(this.config,u(!1),r));let{data:p}=l.body;if(!p)throw new I("Could not search pull requests",l.body.errors);return{pageInfo:{hasNextPage:p.search.pageInfo.hasNextPage,endCursor:p.search.pageInfo.endCursor},data:x(p.search.nodes?.filter(k).map(Yt)||[],e.states)}}async searchIssues(e,r={}){let n=await this.getEnterpriseVersion(r),o=await this.getScopes(r),i=te(o),a=ls(e.states),u=await b(this.config,Kt("issue",e.query,e.cursor,{supportsEmail:i,includeFromArchivedRepos:e.includeFromArchivedRepos,maxPageSize:e.maxPageSize??os,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(uo)||[]}}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:p,labelNames:d,maxPageSize:c}=e,g=Vt(l||"");return a.forEach(m=>{g.push(`repo:${m.namespace}/${m.name}`)}),n&&n.forEach(m=>{g.push(`assignee:${m}`)}),o&&g.push(`updated:<${o}`),i&&g.push(`author:${i}`),u&&g.push(`review-requested:${u}`),p&&g.push(`mentions:${p}`),d&&d.forEach(m=>{g.push(`label:"${m}"`)}),this.searchPullRequests({query:`sort:updated ${g.join(" ")}`,isDraft:e.isDraft,cursor:e.cursor,includeFromArchivedRepos:e.includeFromArchivedRepos,maxPageSize:c,states:e.states},r)}async getPullRequestForRepo(e,r={}){let n=await this.getEnterpriseVersion(r),o=await this.getScopes(r),i=te(o),a=d=>({query:`query getPullRequest(
|
|
578
579
|
$owner: String!
|
|
579
580
|
$name: String!
|
|
580
581
|
$number: Int!
|
|
@@ -584,24 +585,24 @@ query getBlame($owner: String!, $name: String!, $ref: String!, $path: String!) {
|
|
|
584
585
|
name: $name
|
|
585
586
|
) {
|
|
586
587
|
pullRequest(number: $number) {
|
|
587
|
-
${
|
|
588
|
+
${Xe(d,i,n)}
|
|
588
589
|
}
|
|
589
590
|
}
|
|
590
|
-
}`,variables:{owner:e.repo.namespace,name:e.repo.name,number:e.number}}),u=await b(this.config,a(!0),
|
|
591
|
+
}`,variables:{owner:e.repo.namespace,name:e.repo.name,number:e.number}}),u=await b(this.config,a(!0),r);u.body.errors&&Ze(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 p=u.body.data?.repository.pullRequest;return{data:p?Yt(p):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=te(o),a=d=>({query:`query getPullRequest(
|
|
591
592
|
$graphQLId: ID!
|
|
592
593
|
) {
|
|
593
594
|
node(id: $graphQLId) {
|
|
594
595
|
... on PullRequest {
|
|
595
|
-
${
|
|
596
|
+
${Xe(d,i,n)}
|
|
596
597
|
}
|
|
597
598
|
}
|
|
598
|
-
}`,variables:{graphQLId:e.graphQLId}}),u=await b(this.config,a(!0),
|
|
599
|
+
}`,variables:{graphQLId:e.graphQLId}}),u=await b(this.config,a(!0),r);u.body.errors&&Ze(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 p=u.body.data?.node;return{data:p?Yt(p):null}}async closePullRequest(e,r={}){let{pullRequest:{graphQLId:n}}=e;if(!n)throw new Error('GitHub requires "graphQLId" for this function.');let o=`mutation ClosePullRequest($pullRequestGraphQLId: ID!) {
|
|
599
600
|
closePullRequest(input: { pullRequestId: $pullRequestGraphQLId }) {
|
|
600
601
|
pullRequest {
|
|
601
602
|
id
|
|
602
603
|
}
|
|
603
604
|
}
|
|
604
|
-
}`,i=await b(this.config,{query:`${o}`,variables:{pullRequestGraphQLId:n}},
|
|
605
|
+
}`,i=await b(this.config,{query:`${o}`,variables:{pullRequestGraphQLId:n}},r);if(!i.body.data?.closePullRequest?.pullRequest?.id)throw new I("Could not close pull request",i.body.errors)}async mergePullRequest(e,r={}){let{pullRequest:n,mergeStrategy:o}=e;if(!n.graphQLId)throw new Error('GitHub requires "graphQLId" for this function.');if(!n.headRef?.oid)throw new Error('GitHub requires "headRef.oid" for this function.');let i;switch(o){case"MERGE_COMMIT":{i="MERGE";break}case"REBASE":{i="REBASE";break}case"SQUASH":{i="SQUASH";break}}let a=`mutation MergePullRequest(
|
|
605
606
|
$pullRequestGraphQLId: ID!,
|
|
606
607
|
$expectedSourceSha: GitObjectID!,
|
|
607
608
|
$mergeStrategy: PullRequestMergeMethod,
|
|
@@ -615,7 +616,7 @@ query getBlame($owner: String!, $name: String!, $ref: String!, $path: String!) {
|
|
|
615
616
|
id
|
|
616
617
|
}
|
|
617
618
|
}
|
|
618
|
-
}`,u=await b(this.config,{query:`${a}`,variables:{pullRequestGraphQLId:n.graphQLId,expectedSourceSha:n.headRef.oid,mergeStrategy:i}},
|
|
619
|
+
}`,u=await b(this.config,{query:`${a}`,variables:{pullRequestGraphQLId:n.graphQLId,expectedSourceSha:n.headRef.oid,mergeStrategy:i}},r);if(!u.body.data?.mergePullRequest?.pullRequest?.id)throw new I("Could not merge pull request",u.body.errors)}async approvePullRequest(e,r={}){let{pullRequest:n,comment:o}=e;if(!n.graphQLId)throw new Error('GitHub requires "graphQLId" for this function.');let i=`mutation ApprovePullRequest(
|
|
619
620
|
$pullRequestId: ID!,
|
|
620
621
|
$body: String
|
|
621
622
|
) {
|
|
@@ -628,7 +629,7 @@ query getBlame($owner: String!, $name: String!, $ref: String!, $path: String!) {
|
|
|
628
629
|
id
|
|
629
630
|
}
|
|
630
631
|
}
|
|
631
|
-
}`,a=await b(this.config,{query:i,variables:{pullRequestId:n.graphQLId,body:o||null}},
|
|
632
|
+
}`,a=await b(this.config,{query:i,variables:{pullRequestId:n.graphQLId,body:o||null}},r);if(!a.body.data?.addPullRequestReview?.pullRequestReview?.id)throw new I("Could not approve pull request",a.body.errors)}async requestPullRequestChanges(e,r={}){let{pullRequest:n,comment:o}=e;if(!n.graphQLId)throw new Error('GitHub requires "graphQLId" for this function.');if(!o||o.trim()==="")throw new Error("GitHub requires a comment when requesting changes.");let i=`mutation RequestPullRequestChanges(
|
|
632
633
|
$pullRequestId: ID!,
|
|
633
634
|
$body: String!
|
|
634
635
|
) {
|
|
@@ -641,7 +642,7 @@ query getBlame($owner: String!, $name: String!, $ref: String!, $path: String!) {
|
|
|
641
642
|
id
|
|
642
643
|
}
|
|
643
644
|
}
|
|
644
|
-
}`,a=await b(this.config,{query:i,variables:{pullRequestId:n.graphQLId,body:o}},
|
|
645
|
+
}`,a=await b(this.config,{query:i,variables:{pullRequestId:n.graphQLId,body:o}},r);if(!a.body.data?.addPullRequestReview?.pullRequestReview?.id)throw new I("Could not request pull request changes",a.body.errors)}async commentOnPullRequest(e,r={}){let{pullRequest:n,comment:o}=e;if(!n.graphQLId)throw new Error('GitHub requires "graphQLId" for this function.');if(!o||o.trim()==="")throw new Error("GitHub requires a comment when commenting on a pull request.");let i=`mutation CommentOnPullRequest(
|
|
645
646
|
$pullRequestId: ID!,
|
|
646
647
|
$body: String!
|
|
647
648
|
) {
|
|
@@ -654,7 +655,7 @@ query getBlame($owner: String!, $name: String!, $ref: String!, $path: String!) {
|
|
|
654
655
|
id
|
|
655
656
|
}
|
|
656
657
|
}
|
|
657
|
-
}`,a=await b(this.config,{query:i,variables:{pullRequestId:n.graphQLId,body:o}},
|
|
658
|
+
}`,a=await b(this.config,{query:i,variables:{pullRequestId:n.graphQLId,body:o}},r);if(!a.body.data?.addPullRequestReview?.pullRequestReview?.id)throw new I("Could not comment on pull request",a.body.errors)}async reviewPullRequest(e,r={}){let{pullRequest:n,reviewEvent:o,comment:i}=e;switch(o){case"APPROVE":return this.approvePullRequest({pullRequest:n,comment:i},r);case"REQUEST_CHANGES":return this.requestPullRequestChanges({pullRequest:n,comment:i??""},r);case"COMMENT":return this.commentOnPullRequest({pullRequest:n,comment:i??""},r)}}async addCommentToPullRequest(e,r={}){let{pullRequest:n,comment:o}=e;if(!n.graphQLId)throw new Error('GitHub requires "graphQLId" for this function.');if(!o||o.trim()==="")throw new Error("GitHub requires a comment when adding a comment to a pull request.");let i=`mutation AddCommentToPullRequest(
|
|
658
659
|
$subjectId: ID!,
|
|
659
660
|
$body: String!
|
|
660
661
|
) {
|
|
@@ -668,7 +669,7 @@ query getBlame($owner: String!, $name: String!, $ref: String!, $path: String!) {
|
|
|
668
669
|
}
|
|
669
670
|
}
|
|
670
671
|
}
|
|
671
|
-
}`,a=await b(this.config,{query:i,variables:{subjectId:n.graphQLId,body:o}},
|
|
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:ms,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:cs,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:gs,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:Rs,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:hs,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:fs,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(
|
|
672
673
|
$threadId: ID!,
|
|
673
674
|
$body: String!
|
|
674
675
|
) {
|
|
@@ -680,7 +681,7 @@ query getBlame($owner: String!, $name: String!, $ref: String!, $path: String!) {
|
|
|
680
681
|
id
|
|
681
682
|
}
|
|
682
683
|
}
|
|
683
|
-
}`,a=await b(this.config,{query:i,variables:{threadId:n,body:o}},
|
|
684
|
+
}`,a=await b(this.config,{query:i,variables:{threadId:n,body:o}},r);if(!a.body.data?.addPullRequestReviewThreadReply?.comment?.id)throw new I("Could not add reply to pull request review thread",a.body.errors);return n}async createReviewThread(e,r){let{pullRequest:n,comment:o,path:i,line:a,side:u}=e,l=`mutation AddInlineCommentToPullRequest(
|
|
684
685
|
$pullRequestId: ID!,
|
|
685
686
|
$body: String!,
|
|
686
687
|
$path: String!,
|
|
@@ -706,43 +707,43 @@ query getBlame($owner: String!, $name: String!, $ref: String!, $path: String!) {
|
|
|
706
707
|
}
|
|
707
708
|
}
|
|
708
709
|
}
|
|
709
|
-
}`,p=await b(this.config,{query:l,variables:{pullRequestId:n.graphQLId,body:o,path:i,line:a,side:u}},
|
|
710
|
+
}`,p=await b(this.config,{query:l,variables:{pullRequestId:n.graphQLId,body:o,path:i,line:a,side:u}},r);if(!p.body.data?.addPullRequestReview?.pullRequestReview?.id)throw new I("Could not add inline comment to pull request",p.body.errors);return p.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) {
|
|
710
711
|
updatePullRequest(input: { pullRequestId: $pullRequestGraphQLId, milestoneId: $milestoneGraphQLId }) {
|
|
711
712
|
pullRequest {
|
|
712
713
|
id
|
|
713
714
|
}
|
|
714
715
|
}
|
|
715
|
-
}`,a=await b(this.config,{query:`${i}`,variables:{pullRequestGraphQLId:n.graphQLId,milestoneGraphQLId:o?.graphQLId??null}},
|
|
716
|
+
}`,a=await b(this.config,{query:`${i}`,variables:{pullRequestGraphQLId:n.graphQLId,milestoneGraphQLId:o?.graphQLId??null}},r);if(!a.body.data?.updatePullRequest?.pullRequest?.id)throw new I("Could not set milestone of pull request",a.body.errors)}async markPullRequestReadyForReview(e,r){let n=`mutation MarkReadyToReview($pullRequestGraphQLId: ID!) {
|
|
716
717
|
markPullRequestReadyForReview(input: { pullRequestId: $pullRequestGraphQLId }) {
|
|
717
718
|
pullRequest {
|
|
718
719
|
id
|
|
719
720
|
}
|
|
720
721
|
}
|
|
721
|
-
}`,o=await b(this.config,{query:n,variables:{pullRequestGraphQLId:e}},
|
|
722
|
+
}`,o=await b(this.config,{query:n,variables:{pullRequestGraphQLId:e}},r);if(!o.body.data?.markPullRequestReadyForReview?.pullRequest?.id)throw new I("Could not mark pull request ready to review",o.body.errors)}async convertPullRequestToDraft(e,r){let n=`mutation ConvertToDraft($pullRequestGraphQLId: ID!) {
|
|
722
723
|
convertPullRequestToDraft(input: { pullRequestId: $pullRequestGraphQLId }) {
|
|
723
724
|
pullRequest {
|
|
724
725
|
id
|
|
725
726
|
}
|
|
726
727
|
}
|
|
727
|
-
}`,o=await b(this.config,{query:n,variables:{pullRequestGraphQLId:e}},
|
|
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(d=>d.state!=="REVIEW_REQUESTED").map(d=>{if(!d.reviewer.graphQLId)throw new Error('GitHub requires reviewer "graphQLId" for this function.');return d.reviewer.graphQLId}),u=i.map(d=>{if(!d.graphQLId)throw new Error('GitHub requires reviewer "graphQLId" for this function.');return d.graphQLId}).filter(d=>a.indexOf(d)===-1),l=`mutation SetPullRequestReviewers($pullRequestGraphQLId: ID!, $reviewerGraphQLIds: [ID!]!) {
|
|
728
729
|
requestReviews(input: { pullRequestId: $pullRequestGraphQLId, userIds: $reviewerGraphQLIds }) {
|
|
729
730
|
pullRequest {
|
|
730
731
|
id
|
|
731
732
|
}
|
|
732
733
|
}
|
|
733
|
-
}`,p=await b(this.config,{query:l,variables:{pullRequestGraphQLId:o,reviewerGraphQLIds:u}},
|
|
734
|
+
}`,p=await b(this.config,{query:l,variables:{pullRequestGraphQLId:o,reviewerGraphQLIds:u}},r);if(!p.body.data?.requestReviews?.pullRequest?.id)throw new I("Could not set pull request reviewers",p.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 p of i){if(!p.graphQLId)throw new Error('GitHub requires reviwer "graphQLId" for this function.');if(!n.find(d=>d.reviewer.graphQLId===p.graphQLId))throw new Error("Can only re-request review from existing reviewer.");a.push(p.graphQLId)}let u=`mutation SetPullRequestReviewers($pullRequestGraphQLId: ID!, $reviewerGraphQLIds: [ID!]!) {
|
|
734
735
|
requestReviews(input: { pullRequestId: $pullRequestGraphQLId, userIds: $reviewerGraphQLIds, union: true }) {
|
|
735
736
|
pullRequest {
|
|
736
737
|
id
|
|
737
738
|
}
|
|
738
739
|
}
|
|
739
|
-
}`,l=await b(this.config,{query:u,variables:{pullRequestGraphQLId:o,reviewerGraphQLIds:a}},
|
|
740
|
+
}`,l=await b(this.config,{query:u,variables:{pullRequestGraphQLId:o,reviewerGraphQLIds:a}},r);if(!l.body.data?.requestReviews?.pullRequest?.id)throw new I("Could not re-request pull request reviews",l.body.errors)}async setPullRequestAssignees(e,r={}){let{pullRequest:n,assignees:o}=e;if(!n.graphQLId)throw new Error('GitHub requires "graphQLId" for this function.');let i=o.map(l=>{if(!l.graphQLId)throw new Error('GitHub requires assignee "graphQLId" for this function.');return l.graphQLId}),a=`mutation SetPullRequestAssignees($pullRequestGraphQLId: ID!, $assigneeGraphQLIds: [ID!]!) {
|
|
740
741
|
updatePullRequest(input: { pullRequestId: $pullRequestGraphQLId, assigneeIds: $assigneeGraphQLIds }) {
|
|
741
742
|
pullRequest {
|
|
742
743
|
id
|
|
743
744
|
}
|
|
744
745
|
}
|
|
745
|
-
}`,u=await b(this.config,{query:a,variables:{pullRequestGraphQLId:n.graphQLId,assigneeGraphQLIds:i}},
|
|
746
|
+
}`,u=await b(this.config,{query:a,variables:{pullRequestGraphQLId:n.graphQLId,assigneeGraphQLIds:i}},r);if(!u.body.data?.updatePullRequest?.pullRequest?.id)throw new I("Could not set pull request assignees",u.body.errors)}async getReviewsForPullRequest(e,r={}){let n=await this.getEnterpriseVersion(r),{repo:{namespace:o,name:i},pullRequestId:a}=e,u=`query getPullRequests(
|
|
746
747
|
$namespace: String!
|
|
747
748
|
$name: String!
|
|
748
749
|
$pullRequestId: Int!
|
|
@@ -770,7 +771,7 @@ query getBlame($owner: String!, $name: String!, $ref: String!, $path: String!) {
|
|
|
770
771
|
login
|
|
771
772
|
}
|
|
772
773
|
body
|
|
773
|
-
${!n||
|
|
774
|
+
${!n||K(n,"PR_REVIEW_COMMENT_FULL_DATABASE_ID")?"fullDatabaseId":"databaseId"}
|
|
774
775
|
diffHunk
|
|
775
776
|
id
|
|
776
777
|
path
|
|
@@ -790,7 +791,7 @@ query getBlame($owner: String!, $name: String!, $ref: String!, $path: String!) {
|
|
|
790
791
|
login
|
|
791
792
|
}
|
|
792
793
|
body
|
|
793
|
-
${!n||
|
|
794
|
+
${!n||K(n,"PR_REVIEW_FULL_DATABASE_ID")?"fullDatabaseId":"databaseId"}
|
|
794
795
|
id
|
|
795
796
|
publishedAt
|
|
796
797
|
url
|
|
@@ -798,54 +799,54 @@ query getBlame($owner: String!, $name: String!, $ref: String!, $path: String!) {
|
|
|
798
799
|
}
|
|
799
800
|
}
|
|
800
801
|
}
|
|
801
|
-
}`,l=await b(this.config,{query:u,variables:{namespace:o,name:i,pullRequestId:a}},
|
|
802
|
+
}`,l=await b(this.config,{query:u,variables:{namespace:o,name:i,pullRequestId:a}},r),p=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=io(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=>p[c.id]).map(c=>({author:c.author?{avatarUrl:c.author.avatarUrl,email:null,name:c.author.login}:null,body:c.body,createdAt:c.publishedAt?new Date(c.publishedAt):null,id:c.fullDatabaseId??c.databaseId.toString(),graphQLId:c.id,reviewComments:p[c.id],url:c.url}))??[]}}async 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,p=await b(this.config,{query:Is(o),variables:{namespace:i,name:a,pullRequestNumber:u,cursor:l,first:$}},r),d=p.body.data?.repository;if(!d)throw new I("Could not fetch pull request comments",p.body.errors);return{data:d.pullRequest.comments.nodes?.filter(k).map(ds)??[],pageInfo:d.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={},p=[],d=c=>{l[c.id]||(l[c.id]=!0,p.push(c))};return a?.data.forEach(d),u?.data.forEach(d),{pageInfo:{hasNextPage:a?.pageInfo.hasNextPage||u?.pageInfo.hasNextPage||!1,endCursor:`${a?.pageInfo.hasNextPage&&a?.pageInfo.endCursor||"null"};${u?.pageInfo.hasNextPage&&u?.pageInfo.endCursor||"null"}`},data:p}}async setPullRequestLabels(e,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!]) {
|
|
802
803
|
updatePullRequest(input: { pullRequestId: $pullRequestGraphQLId, labelIds: $labelGraphQLIds }) {
|
|
803
804
|
pullRequest {
|
|
804
805
|
id
|
|
805
806
|
}
|
|
806
807
|
}
|
|
807
|
-
}`,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})}},
|
|
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=Vt(e.startQuery||""),{cursor:o,assigneeLogins:i,updatedBefore:a,authorLogin:u,mentionLogin:l,labelNames:p}=e;return e.repos.forEach(d=>{n.push(`repo:${d.namespace}/${d.name}`)}),i&&i.forEach(d=>{n.push(`assignee:${d}`)}),a&&n.push(`updated:<${a}`),u&&n.push(`author:${u}`),l&&n.push(`mentions:${l}`),p&&p.forEach(d=>{n.push(`label:"${d}"`)}),this.searchIssues({query:`sort:updated ${n.join(" ")}`,cursor:o,includeFromArchivedRepos:e.includeFromArchivedRepos,maxPageSize:e.maxPageSize,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!) {
|
|
808
809
|
closeIssue(input: { issueId: $issueGraphQLId, stateReason: $reason }) {
|
|
809
810
|
issue {
|
|
810
811
|
id
|
|
811
812
|
}
|
|
812
813
|
}
|
|
813
|
-
}`,a=await b(this.config,{query:i,variables:{issueGraphQLId:n.graphQLId,reason:o}},
|
|
814
|
+
}`,a=await b(this.config,{query:i,variables:{issueGraphQLId:n.graphQLId,reason:o}},r);if(!a.body.data?.closeIssue?.issue?.id)throw new I("Could not close issue with reason",a.body.errors)}async closeIssue(e,r={}){let{issue:n}=e;if(!n.graphQLId)throw new Error('GitHub requires "graphQLId" for this function.');let o=`mutation SetIssueState($issueGraphQLId: ID!) {
|
|
814
815
|
updateIssue(input: { id: $issueGraphQLId, state: CLOSED }) {
|
|
815
816
|
issue {
|
|
816
817
|
id
|
|
817
818
|
}
|
|
818
819
|
}
|
|
819
|
-
}`,i=await b(this.config,{query:o,variables:{issueGraphQLId:n.graphQLId}},
|
|
820
|
+
}`,i=await b(this.config,{query:o,variables:{issueGraphQLId:n.graphQLId}},r);if(!i.body.data?.updateIssue?.issue?.id)throw new I("Could not close issue",i.body.errors)}async reOpenIssue(e,r={}){let{issue:n}=e;if(!n.graphQLId)throw new Error('GitHub requires "graphQLId" for this function.');let o=`mutation ReOpenIssue($issueGraphQLId: ID!) {
|
|
820
821
|
reopenIssue(input: { issueId: $issueGraphQLId }) {
|
|
821
822
|
issue {
|
|
822
823
|
id
|
|
823
824
|
}
|
|
824
825
|
}
|
|
825
|
-
}`,i=await b(this.config,{query:o,variables:{issueGraphQLId:n.graphQLId}},
|
|
826
|
+
}`,i=await b(this.config,{query:o,variables:{issueGraphQLId:n.graphQLId}},r);if(!i.body.data?.reopenIssue?.issue?.id)throw new I("Could not reopen issue",i.body.errors)}async setIssueLabels(e,r={}){let{issue:n,labels:o}=e;if(!n.graphQLId)throw new Error('GitHub requires "graphQLId" for this function.');let i=o.map(l=>l.graphQLId),a=`mutation SetIssueLabels($issueGraphQLId: ID!, $labelGraphQLIds: [ID!]) {
|
|
826
827
|
updateIssue(input: { id: $issueGraphQLId, labelIds: $labelGraphQLIds }) {
|
|
827
828
|
issue {
|
|
828
829
|
id
|
|
829
830
|
}
|
|
830
831
|
}
|
|
831
|
-
}`,u=await b(this.config,{query:a,variables:{issueGraphQLId:n.graphQLId,labelGraphQLIds:i}},
|
|
832
|
+
}`,u=await b(this.config,{query:a,variables:{issueGraphQLId:n.graphQLId,labelGraphQLIds:i}},r);if(!u.body.data?.updateIssue?.issue?.id)throw new I("Could not set issue labels",u.body.errors)}async setIssueMilestone(e,r={}){let{issue:n,milestone:o}=e;if(!n.graphQLId)throw new Error('GitHub requires "graphQLId" for this function.');if(o&&!o.graphQLId)throw new Error('GitHub requires milestone "graphQLId" for this function.');let i=`mutation SetIssueMilestone($issueGraphQLId: ID!, $milestoneGraphQLId: ID) {
|
|
832
833
|
updateIssue(input: { id: $issueGraphQLId, milestoneId: $milestoneGraphQLId }) {
|
|
833
834
|
issue {
|
|
834
835
|
id
|
|
835
836
|
}
|
|
836
837
|
}
|
|
837
|
-
}`,a=await b(this.config,{query:`${i}`,variables:{issueGraphQLId:n.graphQLId,milestoneGraphQLId:o?.graphQLId??null}},
|
|
838
|
+
}`,a=await b(this.config,{query:`${i}`,variables:{issueGraphQLId:n.graphQLId,milestoneGraphQLId:o?.graphQLId??null}},r);if(!a.body.data?.updateIssue?.issue?.id)throw new I("Could not set milestone of issue",a.body.errors)}async setIssueAssignees(e,r={}){let{issue:n,assignees:o}=e;if(!n.graphQLId)throw new Error('GitHub requires "graphQLId" for this function.');let i=o.map(l=>{if(!l.graphQLId)throw new Error('GitHub requires assignee "graphQLId" for this function.');return l.graphQLId}),a=`mutation SetIssueAssignees($issueGraphQLId: ID!, $assigneeGraphQLIds: [ID!]!) {
|
|
838
839
|
updateIssue(input: { id: $issueGraphQLId, assigneeIds: $assigneeGraphQLIds }) {
|
|
839
840
|
issue {
|
|
840
841
|
id
|
|
841
842
|
}
|
|
842
843
|
}
|
|
843
|
-
}`,u=await b(this.config,{query:a,variables:{issueGraphQLId:n.graphQLId,assigneeGraphQLIds:i}},
|
|
844
|
+
}`,u=await b(this.config,{query:a,variables:{issueGraphQLId:n.graphQLId,assigneeGraphQLIds:i}},r);if(!u.body.data?.updateIssue?.issue?.id)throw new I("Could not set issue assignees",u.body.errors)}async getMilestonesForRepo(e,r={}){let{repo:{namespace:n,name:o},cursor:i}=e,a=await b(this.config,{query:`
|
|
844
845
|
query getLabelsForRepo($owner: String!, $name: String! $cursor: String, $first: Int!) {
|
|
845
846
|
repository(owner: $owner, name: $name) {
|
|
846
847
|
milestones(first: $first, after: $cursor) {
|
|
847
848
|
nodes {
|
|
848
|
-
${
|
|
849
|
+
${Je}
|
|
849
850
|
}
|
|
850
851
|
pageInfo {
|
|
851
852
|
endCursor
|
|
@@ -854,12 +855,12 @@ query getLabelsForRepo($owner: String!, $name: String! $cursor: String, $first:
|
|
|
854
855
|
}
|
|
855
856
|
}
|
|
856
857
|
}
|
|
857
|
-
`,variables:{owner:n,name:o,cursor:i,first:$}},
|
|
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(tr)??[]}}async getLabelsForRepo(e,r={}){let{repo:{namespace:n,name:o},cursor:i}=e,a=await b(this.config,{query:`
|
|
858
859
|
query getLabelsForRepo($owner: String!, $name: String! $cursor: String, $first: Int!) {
|
|
859
860
|
repository(owner: $owner, name: $name) {
|
|
860
861
|
labels(first: $first, after: $cursor) {
|
|
861
862
|
nodes {
|
|
862
|
-
${
|
|
863
|
+
${Ke}
|
|
863
864
|
}
|
|
864
865
|
pageInfo {
|
|
865
866
|
endCursor
|
|
@@ -868,7 +869,7 @@ query getLabelsForRepo($owner: String!, $name: String! $cursor: String, $first:
|
|
|
868
869
|
}
|
|
869
870
|
}
|
|
870
871
|
}
|
|
871
|
-
`,variables:{owner:n,name:o,cursor:i,first:$}},
|
|
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(er)??[]}}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(to)}}};var lo="https://gitlab.com/api/v4",po="https://gitlab.com/api/graphql",rr=/\/api\/v\d+$/,Ps=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(/\/$/,""),Ps(e),rr.test(e)||(e=e+"/api/v4"),e):lo},co=(s,t)=>{let e=t.baseUrl||s.baseUrl;return e?(e=e.replace(/\/$/,""),Ps(e),rr.test(e)&&(e=e.replace(rr,"")),`${e}/api/graphql`):po},E=(s,t,e)=>{let r=R(e.token||s.token);return s.request({url:co(s,e),method:"POST",headers:{...r,"Content-Type":"application/json"},body:JSON.stringify(t)})},Ge=s=>s?.map(t=>`"${t.message}"`).join(", ");var dr=s=>s.split("/").slice(0,-1).join("/"),cr=s=>s.split("/").at(-1)??"",ws=s=>{let t=parseInt(`${s["x-next-page"]}`,10);return Number.isNaN(t)?{hasNextPage:!1,nextPage:null}:{hasNextPage:!0,nextPage:t}},Ye=s=>({id:s.id.replace(Pe,""),graphQLId:s.id,namespace:dr(s.fullPath),name:cr(s.fullPath),webUrl:s.webUrl}),Te=s=>({id:s.id.replace(Pe,""),graphQLId:s.id,httpsUrl:s.httpUrlToRepo,namespace:dr(s.fullPath),name:cr(s.fullPath),sshUrl:s.sshUrlToRepo,webUrl:s.webUrl}),mo={assigned:"assignedMergeRequests",authored:"authoredMergeRequests",reviewRequested:"reviewRequestedMergeRequests"},go={CAN_BE_MERGED:"MERGEABLE",CANNOT_BE_MERGED:"CONFLICTS",CANNOT_BE_MERGED_RECHECK:"UNKNOWN",UNCHECKED:"UNKNOWN",CHECKING:"UNKNOWN"};var Ss="gid://gitlab/User/",Pe="gid://gitlab/Project/",ho="gid://gitlab/MergeRequest/",fo="gid://gitlab/Issue/",Ro="gid://gitlab/ProjectLabel/",Io="gid://gitlab/Milestone/",bo="gid://gitlab/Ci::Build/",mr=`
|
|
872
873
|
description
|
|
873
874
|
dueDate
|
|
874
875
|
id
|
|
@@ -877,7 +878,7 @@ startDate
|
|
|
877
878
|
state
|
|
878
879
|
title
|
|
879
880
|
webPath
|
|
880
|
-
`,
|
|
881
|
+
`,sr=`
|
|
881
882
|
id
|
|
882
883
|
fullPath
|
|
883
884
|
webUrl
|
|
@@ -891,25 +892,31 @@ userPermissions {
|
|
|
891
892
|
downloadCode
|
|
892
893
|
pushCode
|
|
893
894
|
}
|
|
894
|
-
`,
|
|
895
|
+
`,re=`
|
|
895
896
|
id
|
|
896
897
|
name
|
|
897
898
|
username
|
|
898
899
|
publicEmail
|
|
899
900
|
avatarUrl
|
|
900
901
|
webUrl
|
|
901
|
-
`,
|
|
902
|
+
`,gr=`
|
|
902
903
|
color
|
|
903
904
|
description
|
|
904
905
|
id
|
|
905
906
|
title
|
|
906
|
-
`,
|
|
907
|
+
`,Oe=`
|
|
908
|
+
id
|
|
909
|
+
httpUrlToRepo
|
|
910
|
+
fullPath
|
|
911
|
+
sshUrlToRepo
|
|
912
|
+
webUrl
|
|
913
|
+
`,nr=`
|
|
907
914
|
author {
|
|
908
|
-
${
|
|
915
|
+
${re}
|
|
909
916
|
}
|
|
910
917
|
assignees {
|
|
911
918
|
nodes {
|
|
912
|
-
${
|
|
919
|
+
${re}
|
|
913
920
|
}
|
|
914
921
|
}
|
|
915
922
|
closedAt
|
|
@@ -920,7 +927,7 @@ id
|
|
|
920
927
|
iid
|
|
921
928
|
labels {
|
|
922
929
|
nodes {
|
|
923
|
-
${
|
|
930
|
+
${gr}
|
|
924
931
|
}
|
|
925
932
|
}
|
|
926
933
|
state
|
|
@@ -931,9 +938,9 @@ upvotes
|
|
|
931
938
|
userNotesCount
|
|
932
939
|
webUrl
|
|
933
940
|
milestone {
|
|
934
|
-
${
|
|
941
|
+
${mr}
|
|
935
942
|
}
|
|
936
|
-
`,
|
|
943
|
+
`,yo=`
|
|
937
944
|
stages {
|
|
938
945
|
nodes {
|
|
939
946
|
jobs {
|
|
@@ -949,11 +956,11 @@ stages {
|
|
|
949
956
|
name
|
|
950
957
|
}
|
|
951
958
|
}
|
|
952
|
-
`,
|
|
959
|
+
`,or=(s,t,e)=>`
|
|
953
960
|
id
|
|
954
961
|
state
|
|
955
962
|
author {
|
|
956
|
-
${
|
|
963
|
+
${re}
|
|
957
964
|
}
|
|
958
965
|
diffRefs {
|
|
959
966
|
baseSha
|
|
@@ -979,12 +986,12 @@ targetBranch
|
|
|
979
986
|
sourceBranch
|
|
980
987
|
assignees {
|
|
981
988
|
nodes {
|
|
982
|
-
${
|
|
989
|
+
${re}
|
|
983
990
|
}
|
|
984
991
|
}
|
|
985
992
|
reviewers {
|
|
986
993
|
nodes {
|
|
987
|
-
${
|
|
994
|
+
${re}
|
|
988
995
|
mergeRequestInteraction {
|
|
989
996
|
approved
|
|
990
997
|
reviewState
|
|
@@ -994,25 +1001,25 @@ reviewers {
|
|
|
994
1001
|
mergeStatusEnum
|
|
995
1002
|
labels {
|
|
996
1003
|
nodes {
|
|
997
|
-
${
|
|
1004
|
+
${gr}
|
|
998
1005
|
}
|
|
999
1006
|
}
|
|
1000
|
-
${s
|
|
1001
|
-
${
|
|
1002
|
-
${e?`headPipeline { ${
|
|
1003
|
-
`,
|
|
1007
|
+
${s?`project { ${Oe} archived } sourceProject { ${Oe} }`:""}
|
|
1008
|
+
${t?`milestone { ${mr} }`:""}
|
|
1009
|
+
${e?`headPipeline { ${yo} }`:""}
|
|
1010
|
+
`,_=s=>`${s.namespace}/${s.name}`,Po=s=>`${s.namespace}/${s.name}`,wo=s=>/Field '[^']+' (?:doesn'?t|does not) exist on type|Field '[^']+' is not defined|undefined field '[^']+' on type/i.test(s.message),qo=s=>({canCreateWebhook:s.adminOperations,canPush:s.pushCode,isAdmin:s.adminOperations}),ir=s=>({id:s.id.replace(Pe,""),graphQLId:s.id,namespace:dr(s.fullPath),name:cr(s.fullPath),webUrl:s.webUrl,httpsUrl:s.httpUrlToRepo,sshUrl:s.sshUrlToRepo,defaultBranch:s.repository?.rootRef?{name:s.repository.rootRef}:null,permissions:qo(s.userPermissions)}),vo=s=>({path:s.path,isDirectory:s.type==="tree"}),Eo={opened:"OPEN",merged:"MERGED",closed:"CLOSED"},So={OPEN:"opened",MERGED:"merged",CLOSED:"closed"},qs=s=>{if(!s||s.length===0)return"state: opened";let t=Array.from(new Set(s));return t.length>1?"":`state: ${So[t[0]]}`},vs=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"}`},ae=100,et=(s,t,e)=>!t&&s?.startsWith("/")?`https://gitlab.com${s}`:t&&s?.startsWith("/")&&e?`${e.replace(/\/+?$/,"")}${s}`:s,se=(s,t,e)=>{let r=et(s.avatarUrl,t,e);return{id:s.id.replace(Ss,""),graphQLId:s.id,name:s.name,username:s.username,email:s.publicEmail??null,avatarUrl:r,url:s.webUrl}},hr=s=>({color:s.color,description:s.description,id:s.id.replace(Ro,""),graphQLId:s.id,name:s.title}),Co=(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,Do=(s,t,e)=>{let r={APPROVED:"APPROVED",REQUESTED_CHANGES:"CHANGES_REQUESTED",REVIEWED:"COMMENTED",UNAPPROVED:"REVIEW_REQUESTED",UNREVIEWED:"REVIEW_REQUESTED"};return{reviewer:se(s,t,e),state:s.mergeRequestInteraction?.reviewState?r[s.mergeRequestInteraction.reviewState]:"REVIEW_REQUESTED"}},ar=(s,t,e,r,n)=>{let o=s.reviewers?.nodes?s.reviewers.nodes.map(i=>Do(i,r,n)):null;return{id:s.id.replace(ho,""),graphQLId:s.id,title:s.title,description:s.description,number:parseInt(s.iid,10),state:Eo[s.state],commentCount:s.userNotesCount||0,upvoteCount:s.upvotes,author:s.author?se(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:Co(a.status,a.allowFailure),stage:i.name??null,startedAt:new Date(a.createdAt),url:`${t.webUrl}/-/jobs/${a.id.replace(bo,"")}`}))??[])??[]},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=>se(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:go[s.mergeStatusEnum],milestone:s.milestone?fr(s.milestone,t.webUrl):null,labels:s.labels?.nodes?.map(hr)??[],permissions:null}},ur=(s,t,e,r)=>({author:se(s.author,e,r),assignees:s.assignees.nodes.map(n=>se(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(fo,""),labels:s.labels?.nodes?.map(hr)??[],number:s.iid,repository:{id:t.id.replace(Pe,""),graphQLId:t.id,name:t.name,owner:{login:t.namespace}},updatedDate:new Date(s.updatedAt),upvoteCount:s.upvotes,state:{name:s.state,color:null},type:s.type,title:s.title,url:s.webUrl,milestone:s.milestone?fr(s.milestone,t.webUrl):null}),fr=(s,t)=>({id:s.id.replace(Io,""),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}),Ao=s=>Buffer.from(JSON.stringify(s),"utf8").toString("base64"),$o=(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}}},Lo=(s,t,e)=>({id:s.id.toString(),graphQLId:`${Ss}${s.id}`,name:s.name,username:s.username,email:s.email??null,avatarUrl:et(s.avatar_url,t,e),url:s.web_url}),Es=(s,t,e)=>({avatarUrl:et(s.avatar_url,t,e)??"",email:null,name:s.name}),Uo=s=>s?.new_line!=null?"RIGHT":s?.old_line!=null?"LEFT":null,Go=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(`
|
|
1004
1011
|
`)}
|
|
1005
1012
|
${s.diff.endsWith(`
|
|
1006
1013
|
`)?s.diff:`${s.diff}
|
|
1007
|
-
`}`):`${
|
|
1014
|
+
`}`):`${r.join(`
|
|
1008
1015
|
`)}
|
|
1009
|
-
`},
|
|
1016
|
+
`},Cs="|",pr=(s,t,e,r)=>[s,t,e.toString(),r.toString()].join(Cs),To=s=>{let t=s.split(Cs);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]}},lr=(s,t,e,r)=>({author:s.author?Lo(s.author,t,e):null,body:s.body,createdAt:s.created_at?new Date(s.created_at):null,id:pr(r.namespace,r.name,r.mergeRequestIid,s.id),url:""}),we=class extends Q{getIsSelfHosted(t){return!!t.baseUrl||!!this.config.baseUrl}async getCurrentUser(t={},e={}){let n=(await E(this.config,{query:`
|
|
1010
1017
|
query getCurrentUser {
|
|
1011
1018
|
currentUser {
|
|
1012
|
-
${
|
|
1019
|
+
${re}
|
|
1013
1020
|
}
|
|
1014
1021
|
}
|
|
1015
|
-
`},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:se(n,this.getIsSelfHosted(e),this.config.baseUrl??e.baseUrl)}}async getUserForCommit(t,e={}){let r=_(t.repo),o=(await E(this.config,{query:`
|
|
1016
1023
|
query getUserForCommit($fullPath: ID!, $oid: String!) {
|
|
1017
1024
|
project(fullPath: $fullPath) {
|
|
1018
1025
|
repository {
|
|
@@ -1028,21 +1035,21 @@ query getUserForCommit($fullPath: ID!, $oid: String!) {
|
|
|
1028
1035
|
}
|
|
1029
1036
|
}
|
|
1030
1037
|
}
|
|
1031
|
-
`,variables:{fullPath:
|
|
1038
|
+
`,variables:{fullPath:r,oid:t.oid}},e)).body.data?.project?.repository?.tree?.lastCommit;if(!o)throw new Error("Commit not found.");let i=et(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:`
|
|
1032
1039
|
query getAccountForEmail($email: String!) {
|
|
1033
1040
|
users(search: $email) {
|
|
1034
1041
|
nodes {
|
|
1035
|
-
${
|
|
1042
|
+
${re}
|
|
1036
1043
|
}
|
|
1037
1044
|
}
|
|
1038
1045
|
}
|
|
1039
|
-
`,variables:{email:
|
|
1046
|
+
`,variables:{email:t.email}},e)).body.data?.users?.nodes?.[0];if(!n)throw new Error("User not found.");return{data:se(n,this.getIsSelfHosted(e),this.config.baseUrl??e.baseUrl)}}async getAccountForUsername(t,e={}){let n=(await E(this.config,{query:`
|
|
1040
1047
|
query getAccountForUsername($username: String!) {
|
|
1041
1048
|
user(username: $username) {
|
|
1042
|
-
${
|
|
1049
|
+
${re}
|
|
1043
1050
|
}
|
|
1044
1051
|
}
|
|
1045
|
-
`,variables:{username:
|
|
1052
|
+
`,variables:{username:t.username}},e)).body.data?.user;if(!n)throw new Error("User not found.");return{data:se(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:`
|
|
1046
1053
|
query getAccountsForRepo(
|
|
1047
1054
|
$fullPath: ID!
|
|
1048
1055
|
$after: String
|
|
@@ -1053,7 +1060,7 @@ query getAccountsForRepo(
|
|
|
1053
1060
|
projectMembers(after: $after) {
|
|
1054
1061
|
nodes {
|
|
1055
1062
|
user {
|
|
1056
|
-
${
|
|
1063
|
+
${re}
|
|
1057
1064
|
}
|
|
1058
1065
|
}
|
|
1059
1066
|
pageInfo {
|
|
@@ -1063,22 +1070,22 @@ query getAccountsForRepo(
|
|
|
1063
1070
|
}
|
|
1064
1071
|
}
|
|
1065
1072
|
}
|
|
1066
|
-
`,variables:{fullPath:`${
|
|
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=>se(u,this.getIsSelfHosted(e),this.config.baseUrl??e.baseUrl))??[]}}async getRepo(t,e={}){let r=_(t),n=await E(this.config,{query:`
|
|
1067
1074
|
query getRepo($fullPath: ID!) {
|
|
1068
1075
|
project(fullPath: $fullPath) {
|
|
1069
|
-
${
|
|
1076
|
+
${sr}
|
|
1070
1077
|
}
|
|
1071
1078
|
}
|
|
1072
|
-
`,variables:{fullPath:
|
|
1079
|
+
`,variables:{fullPath:r}},e);if(!n.body.data?.project)throw new Error(`Repository ${r} not found`);return{data:ir(n.body.data.project)}}async getReposBase(t,e={}){let n=t.map(_).map((u,l)=>`
|
|
1073
1080
|
getRepo_${l}: project(fullPath: "${u}") {
|
|
1074
|
-
${
|
|
1081
|
+
${sr}
|
|
1075
1082
|
}
|
|
1076
1083
|
`).join(`
|
|
1077
|
-
`),o=await
|
|
1084
|
+
`),o=await E(this.config,{query:`
|
|
1078
1085
|
query batchGetRepos {
|
|
1079
1086
|
${n}
|
|
1080
1087
|
}
|
|
1081
|
-
`},e);if(!o.body.data)throw new Error(
|
|
1088
|
+
`},e);if(!o.body.data)throw new Error(Ge(o.body.errors)||o.statusText||"Unknown error");let i=[],a=[];return t.forEach((u,l)=>{let p=o.body.data[`getRepo_${l}`];p?i.push(ir(p)):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:`
|
|
1082
1089
|
query getReposForCurrentUser($after: String) {
|
|
1083
1090
|
projects(membership: true first: 100 after: $after) {
|
|
1084
1091
|
pageInfo {
|
|
@@ -1086,29 +1093,29 @@ query getReposForCurrentUser($after: String) {
|
|
|
1086
1093
|
hasNextPage
|
|
1087
1094
|
}
|
|
1088
1095
|
nodes {
|
|
1089
|
-
${
|
|
1096
|
+
${sr}
|
|
1090
1097
|
}
|
|
1091
1098
|
}
|
|
1092
1099
|
}
|
|
1093
|
-
`,variables:{after:
|
|
1100
|
+
`,variables:{after:t.cursor}},e);if(!r.body.data?.projects)throw new Error(Ge(r.body.errors)||r.statusText||"Unknown error");let n=r.body.data?.projects?.nodes||[];return{pageInfo:r.body.data?.projects?.pageInfo,data:n.map(ir)}}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:ws(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:ws(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=mo[t.association],o=qs(t.states),i=L(t.pageSize,{fallback:ae,max:ae}),a=await E(this.config,{query:`
|
|
1094
1101
|
query getPullRequestsForUser($username: String! $cursor: String $labelNames: [String!]) {
|
|
1095
1102
|
user(username: $username) {
|
|
1096
|
-
${n}(
|
|
1103
|
+
${n}(${o} first: ${i} after:$cursor labels: $labelNames${r?` ${r}`:""}) {
|
|
1097
1104
|
pageInfo {
|
|
1098
1105
|
endCursor
|
|
1099
1106
|
hasNextPage
|
|
1100
1107
|
}
|
|
1101
1108
|
nodes {
|
|
1102
|
-
${
|
|
1109
|
+
${or(!0,!0,!0)}
|
|
1103
1110
|
}
|
|
1104
1111
|
}
|
|
1105
1112
|
}
|
|
1106
1113
|
}
|
|
1107
|
-
`,variables:{username:
|
|
1114
|
+
`,variables:{username:t.username,cursor:t.cursor,labelNames:t.labelNames}},e);if(!a.body.data)throw new Error(Ge(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(p=>t.includeFromArchivedRepos||!p.project.archived).map(p=>ar(p,Te(p.project),p.sourceProject?Te(p.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=[],p=[],d=[],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"?p.push(null):p.push(this.getPullRequestsForUser({username:t.username,association:"assigned",cursor:a[c],includeFromArchivedRepos:t.includeFromArchivedRepos,labelNames:t.labelNames,...D&&{repo:D}},e)),u[c]==="null"?d.push(null):d.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,p,d].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=[],p=[],d=(c,g,m)=>{l.push(`$${c}: ${m}`),p.push(`${c}: $${c}`),u[c]=g};return e&&d("updatedBefore",e,"Time"),n&&d("authorUsername",n,"String"),o&&o.length&&(o.length===1?d("assigneeUsername",o[0],"String"):d("assigneeUsernames",o,"[String!]")),i&&d("labelName",i,"[String]"),r!=null&&d("draft",r,"Boolean"),a&&d("reviewerUsername",a,"String"),{variables:u,variableTypes:l,mergeRequestArguments:p}}async getPullRequestsForRepoBase(t,e={},r){let{cursor:n,repo:o}=t||{},i=_(o),a=qs(t.states),u=L(t.pageSize,{fallback:ae,max:ae}),{variables:l,variableTypes:p,mergeRequestArguments:d}=this.getVariablesForPullRequests(t),c={fullPath:i,...l},g=await E(this.config,{query:`
|
|
1108
1115
|
query getPullRequestsForRepo(
|
|
1109
1116
|
$fullPath: ID!
|
|
1110
1117
|
$after: String
|
|
1111
|
-
${
|
|
1118
|
+
${p.length?p.join(" "):""}
|
|
1112
1119
|
) {
|
|
1113
1120
|
project(
|
|
1114
1121
|
fullPath: $fullPath
|
|
@@ -1118,30 +1125,33 @@ query getPullRequestsForRepo(
|
|
|
1118
1125
|
webUrl
|
|
1119
1126
|
archived
|
|
1120
1127
|
mergeRequests(
|
|
1121
|
-
first:
|
|
1122
|
-
|
|
1128
|
+
first: ${u}
|
|
1129
|
+
${a}
|
|
1123
1130
|
sort: UPDATED_DESC
|
|
1124
1131
|
after: $after
|
|
1125
|
-
${
|
|
1132
|
+
${d.length?d.join(" "):""}
|
|
1126
1133
|
) {
|
|
1127
1134
|
pageInfo {
|
|
1128
1135
|
endCursor
|
|
1129
1136
|
hasNextPage
|
|
1130
1137
|
}
|
|
1131
1138
|
nodes {
|
|
1132
|
-
${
|
|
1139
|
+
${or(!1,!0,!0)}
|
|
1140
|
+
sourceProject {
|
|
1141
|
+
${Oe}
|
|
1142
|
+
}
|
|
1133
1143
|
}
|
|
1134
1144
|
}
|
|
1135
1145
|
}
|
|
1136
1146
|
}
|
|
1137
|
-
`,variables:{...
|
|
1147
|
+
`,variables:{...c,after:n}},e),m=[],h=g.body.data?.project;if(!r&&h?.archived)return{pageInfo:null,data:[]};let y=Ye(h||{id:"",fullPath:"",webUrl:""});return(h?.mergeRequests?.nodes||[]).forEach(P=>{let v=P.sourceProject?Te(P.sourceProject):null;m.push(ar(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(d=>this.getPullRequestsForRepoBase({repo:d,assigneeLogins:n,updatedBefore:o,authorLogin:i,labelNames:a,isDraft:u,reviewRequestedLogin:l,states:t.states,pageSize:t.pageSize},e,t.includeFromArchivedRepos??!1)))).flatMap(d=>d.data)}}async closePullRequest(t,e={}){let{pullRequest:r}=t,n=`mutation ClosePullRequest($fullPath: ID!, $pullRequestId: String!) {
|
|
1138
1148
|
mergeRequestUpdate(input: { projectPath: $fullPath, iid: $pullRequestId, state: CLOSED }) {
|
|
1139
1149
|
errors,
|
|
1140
1150
|
mergeRequest {
|
|
1141
1151
|
id
|
|
1142
1152
|
}
|
|
1143
1153
|
}
|
|
1144
|
-
}`,i=(await
|
|
1154
|
+
}`,i=(await E(this.config,{query:n,variables:{fullPath:`${r.repository.owner.login}/${r.repository.name}`,pullRequestId:r.number.toString()}},e)).body.data?.mergeRequestUpdate;if(!i?.mergeRequest?.id||i?.errors?.length!==0)throw new Error("Could not close pull request")}async mergePullRequest(t,e={}){let{pullRequest:r,mergeStrategy:n}=t;if(!r.headRef?.oid)throw new Error('GitLab requires "headRef.oid" for this function.');let o=`mutation MergePullRequest(
|
|
1145
1155
|
$fullPath: ID!,
|
|
1146
1156
|
$pullRequestId: String!,
|
|
1147
1157
|
$expectedSourceSha: String!,
|
|
@@ -1158,63 +1168,63 @@ query getPullRequestsForRepo(
|
|
|
1158
1168
|
id
|
|
1159
1169
|
}
|
|
1160
1170
|
}
|
|
1161
|
-
}`,a=(await
|
|
1171
|
+
}`,a=(await E(this.config,{query:o,variables:{fullPath:`${r.repository.owner.login}/${r.repository.name}`,pullRequestId:r.number.toString(),expectedSourceSha:r.headRef.oid,squash:n==="SQUASH"}},e)).body.data?.mergeRequestAccept;if(!a?.mergeRequest?.id||a?.errors?.length!==0)throw new Error("Could not merge pull request")}async setPullRequestMilestone(t,e={}){let{pullRequest:r,milestone:n}=t;if(!r.graphQLId)throw new Error('GitHub requires "graphQLId" for this function.');let o=`mutation SetPullRequestMilestone($fullPath: ID!, $pullRequestId: String!, $milestoneGraphQLId: MilestoneID) {
|
|
1162
1172
|
mergeRequestSetMilestone(input: { projectPath: $fullPath, iid: $pullRequestId, milestoneId: $milestoneGraphQLId }) {
|
|
1163
1173
|
errors,
|
|
1164
1174
|
mergeRequest {
|
|
1165
1175
|
id
|
|
1166
1176
|
}
|
|
1167
1177
|
}
|
|
1168
|
-
}`,i=await
|
|
1178
|
+
}`,i=await E(this.config,{query:o,variables:{fullPath:`${r.repository.owner.login}/${r.repository.name}`,pullRequestId:r.number.toString(),milestoneGraphQLId:n?.graphQLId}},e),a=i.body.data?.mergeRequestSetMilestone;if(!a?.mergeRequest?.id||i.body.errors||a?.errors?.length!==0)throw new Error("Could not set milestone of pull request")}async setPullRequestAsDraft(t,e={}){let{pullRequest:r,isDraft:n}=t,o=`mutation MergeRequestSetDraft($fullPath: ID!, $pullRequestId: String!, $isDraft: Boolean!) {
|
|
1169
1179
|
mergeRequestSetDraft(input: { projectPath: $fullPath, iid: $pullRequestId, draft: $isDraft }) {
|
|
1170
1180
|
errors,
|
|
1171
1181
|
mergeRequest {
|
|
1172
1182
|
id
|
|
1173
1183
|
}
|
|
1174
1184
|
}
|
|
1175
|
-
}`,a=(await
|
|
1185
|
+
}`,a=(await E(this.config,{query:o,variables:{fullPath:`${r.repository.owner.login}/${r.repository.name}`,pullRequestId:r.number.toString(),isDraft:n}},e)).body.data?.mergeRequestSetDraft;if(!a?.mergeRequest?.id||a?.errors?.length!==0)throw new Error("Could not set pull request as draft")}async setPullRequestReviewers(t,e={}){let{pullRequest:r,reviewers:n}=t,o=n.map(l=>{if(!l.username)throw new Error('GitLab requires reviewer "username" for this function.');return l.username}),i=`mutation MergeRequestSetReviewers($fullPath: ID!, $pullRequestId: String!, $reviewerUsernames: [String!]!) {
|
|
1176
1186
|
mergeRequestSetReviewers(input: { projectPath: $fullPath, iid: $pullRequestId, reviewerUsernames: $reviewerUsernames }) {
|
|
1177
1187
|
errors,
|
|
1178
1188
|
mergeRequest {
|
|
1179
1189
|
id
|
|
1180
1190
|
}
|
|
1181
1191
|
}
|
|
1182
|
-
}`,u=(await
|
|
1192
|
+
}`,u=(await E(this.config,{query:i,variables:{fullPath:`${r.repository.owner.login}/${r.repository.name}`,pullRequestId:r.number.toString(),reviewerUsernames:o}},e)).body.data?.mergeRequestSetReviewers;if(!u?.mergeRequest?.id||u?.errors?.length!==0)throw new Error("Could not set pull request reviewers")}async reRequestPullRequestReview(t,e={}){let{pullRequest:r,reviewer:n}=t;if(!n.graphQLId)throw new Error('GitLab requires reviwer "graphQLId" for this function.');let o=`mutation MergeRequestReviewerRereview($fullPath: ID!, $pullRequestId: String!, $reviewerUserId: UserID!) {
|
|
1183
1193
|
mergeRequestReviewerRereview(input: { projectPath: $fullPath, iid: $pullRequestId, userId: $reviewerUserId }) {
|
|
1184
1194
|
errors,
|
|
1185
1195
|
mergeRequest {
|
|
1186
1196
|
id
|
|
1187
1197
|
}
|
|
1188
1198
|
}
|
|
1189
|
-
}`,a=(await
|
|
1199
|
+
}`,a=(await E(this.config,{query:o,variables:{fullPath:`${r.repository.owner.login}/${r.repository.name}`,pullRequestId:r.number.toString(),reviewerUserId:n.graphQLId}},e)).body.data?.mergeRequestReviewerRereview;if(!a?.mergeRequest?.id||a?.errors?.length!==0)throw new Error("Could not set pull request reviewers")}async reRequestPullRequestReviews(t,e={}){let{pullRequest:r,reviewers:n}=t,o=r.reviews;if(!o)throw new Error('GitLab requires "reviews" for this function.');let i=n.filter(a=>o.find(u=>u.reviewer.graphQLId===a.graphQLId));await Promise.all(i.map(a=>this.reRequestPullRequestReview({pullRequest:r,reviewer:a},e)))}async setPullRequestAssignees(t,e={}){let{pullRequest:r,assignees:n}=t,o=n.map(l=>{if(!l.username)throw new Error('GitLab requires assignee "username" for this function.');return l.username}),i=`mutation MergeRequestSetAssignees($fullPath: ID!, $pullRequestId: String!, $assigneeUsernames: [String!]!) {
|
|
1190
1200
|
mergeRequestSetAssignees(input: { projectPath: $fullPath, iid: $pullRequestId, assigneeUsernames: $assigneeUsernames }) {
|
|
1191
1201
|
errors,
|
|
1192
1202
|
mergeRequest {
|
|
1193
1203
|
id
|
|
1194
1204
|
}
|
|
1195
1205
|
}
|
|
1196
|
-
}`,u=(await
|
|
1206
|
+
}`,u=(await E(this.config,{query:i,variables:{fullPath:`${r.repository.owner.login}/${r.repository.name}`,pullRequestId:r.number.toString(),assigneeUsernames:o}},e)).body.data?.mergeRequestSetAssignees;if(!u?.mergeRequest?.id||u?.errors?.length!==0)throw new Error("Could not set pull request assignees")}async setPullRequestLabels(t,e={}){let{pullRequest:r,labels:n}=t,o=n.map(u=>{if(!u.graphQLId)throw new Error('GitLab requires "graphQLId" for labels in this function.');return u.graphQLId}),i=`mutation SetPullRequestLabels($fullPath: ID!, $pullRequestId: String!, $labelGraphQLIds: [LabelID!]!) {
|
|
1197
1207
|
mergeRequestSetLabels(input: { projectPath: $fullPath, iid: $pullRequestId, labelIds: $labelGraphQLIds }) {
|
|
1198
1208
|
mergeRequest {
|
|
1199
1209
|
id
|
|
1200
1210
|
}
|
|
1201
1211
|
}
|
|
1202
|
-
}`;if(!(await
|
|
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=Po(t),n=await E(this.config,{query:`
|
|
1203
1213
|
query GetSingleIssue($projectId: ID!, $issueNumber: String!) {
|
|
1204
1214
|
project(fullPath: $projectId) {
|
|
1205
1215
|
id
|
|
1206
1216
|
fullPath
|
|
1207
1217
|
webUrl
|
|
1208
1218
|
issue(iid: $issueNumber) {
|
|
1209
|
-
${
|
|
1219
|
+
${nr}
|
|
1210
1220
|
}
|
|
1211
1221
|
}
|
|
1212
1222
|
}
|
|
1213
|
-
`,variables:{issueNumber:
|
|
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:ur(n.body.data.project.issue,Ye(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=(p,d,c)=>{a.push(`$${p}: ${c}`),u.push(`${p}: $${p}`),i[p]=d};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=vs(t.states),a=L(t.pageSize,{fallback:ae,max:ae}),{variables:u,variableTypes:l,issueArguments:p}=this.getVariablesForIssues(t),d={fullPath:o,...u},c=`
|
|
1214
1224
|
query GetIssuesFromProject(
|
|
1215
1225
|
$fullPath: ID!
|
|
1216
1226
|
$after: String
|
|
1217
|
-
${
|
|
1227
|
+
${l.length?l.join(" "):""}
|
|
1218
1228
|
) {
|
|
1219
1229
|
project(
|
|
1220
1230
|
fullPath: $fullPath
|
|
@@ -1223,14 +1233,14 @@ query GetSingleIssue($projectId: ID!, $issueNumber: String!) {
|
|
|
1223
1233
|
fullPath
|
|
1224
1234
|
webUrl
|
|
1225
1235
|
issues(
|
|
1226
|
-
first:
|
|
1227
|
-
|
|
1236
|
+
first: ${a}
|
|
1237
|
+
${i}
|
|
1228
1238
|
sort: UPDATED_DESC
|
|
1229
1239
|
after: $after
|
|
1230
|
-
${
|
|
1240
|
+
${p.length?p.join(" "):""}
|
|
1231
1241
|
) {
|
|
1232
1242
|
nodes {
|
|
1233
|
-
${
|
|
1243
|
+
${nr}
|
|
1234
1244
|
}
|
|
1235
1245
|
pageInfo {
|
|
1236
1246
|
endCursor
|
|
@@ -1238,11 +1248,11 @@ query GetSingleIssue($projectId: ID!, $issueNumber: String!) {
|
|
|
1238
1248
|
}
|
|
1239
1249
|
}
|
|
1240
1250
|
}
|
|
1241
|
-
}`,
|
|
1251
|
+
}`,g=await E(this.config,{query:c,variables:{...d,after:r}},e),m=[],h=g.body.data?.project,y=Ye(h||{id:"",fullPath:"",webUrl:""});return(h?.issues?.nodes||[]).forEach(P=>{m.push(ur(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=vs(t.states),o=L(t.pageSize,{fallback:ae,max:ae}),i=t.repoIds.map(h=>h.toString().startsWith(Pe)?h:`${Pe}${h}`),{variables:a,variableTypes:u,issueArguments:l}=this.getVariablesForIssues(t),p={projectIds:i,...a},d=`
|
|
1242
1252
|
query GetIssuesFromProject(
|
|
1243
1253
|
$projectIds: [ID!]
|
|
1244
1254
|
$after: String
|
|
1245
|
-
${
|
|
1255
|
+
${u.length?u.join(" "):""}
|
|
1246
1256
|
) {
|
|
1247
1257
|
projects(
|
|
1248
1258
|
ids: $projectIds
|
|
@@ -1258,30 +1268,30 @@ query GetSingleIssue($projectId: ID!, $issueNumber: String!) {
|
|
|
1258
1268
|
webUrl
|
|
1259
1269
|
archived
|
|
1260
1270
|
issues(
|
|
1261
|
-
first:
|
|
1262
|
-
|
|
1271
|
+
first: ${o}
|
|
1272
|
+
${n}
|
|
1263
1273
|
sort: UPDATED_DESC
|
|
1264
|
-
${
|
|
1274
|
+
${l.length?l.join(" "):""}
|
|
1265
1275
|
) {
|
|
1266
1276
|
nodes {
|
|
1267
|
-
${
|
|
1277
|
+
${nr}
|
|
1268
1278
|
}
|
|
1269
1279
|
}
|
|
1270
1280
|
}
|
|
1271
1281
|
}
|
|
1272
|
-
}`,
|
|
1282
|
+
}`,c=await E(this.config,{query:d,variables:{...p,after:r}},e),g=[];return(c.body.data?.projects?.nodes||[]).forEach(h=>{if(!t.includeFromArchivedRepos&&h.archived)return;let y=Ye(h);(h.issues?.nodes||[]).forEach(P=>g.push(ur(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!) {
|
|
1273
1283
|
updateIssue(input: { projectPath: $fullPath, iid: $issueId, stateEvent: $status }) {
|
|
1274
1284
|
issue {
|
|
1275
1285
|
id
|
|
1276
1286
|
}
|
|
1277
1287
|
}
|
|
1278
|
-
}`;if(!(await
|
|
1288
|
+
}`;if(!(await E(this.config,{query:o,variables:{fullPath:`${r.repository.owner.login}/${r.repository.name}`,issueId:r.number,status:n==="OPEN"?"REOPEN":"CLOSE"}},e)).body.data?.updateIssue?.issue?.id)throw new Error("Could not set issue status")}async closeIssue(t,e={}){await this.setIssueState({...t,state:"CLOSED"},e)}async reOpenIssue(t,e={}){await this.setIssueState({...t,state:"OPEN"},e)}async setIssueLabels(t,e={}){let{issue:r,labels:n}=t;if(!r.repository)throw new Error('GitLab requires a "repository" for this function.');let o=n.map(u=>{if(!u.graphQLId)throw new Error('GitLab requires label "graphQLId" for this function.');return u.graphQLId}),i=`mutation SetIssueLabels($fullPath: ID!, $issueId: String!, $labelGraphQLIds: [ID!]) {
|
|
1279
1289
|
updateIssue(input: { projectPath: $fullPath, iid: $issueId, labelIds: $labelGraphQLIds }) {
|
|
1280
1290
|
issue {
|
|
1281
1291
|
id
|
|
1282
1292
|
}
|
|
1283
1293
|
}
|
|
1284
|
-
}`;if(!(await
|
|
1294
|
+
}`;if(!(await E(this.config,{query:i,variables:{fullPath:`${r.repository.owner.login}/${r.repository.name}`,issueId:r.number,labelGraphQLIds:o}},e)).body.data?.updateIssue?.issue?.id)throw new Error("Could not set issue labels")}async setIssueMilestone(t,e={}){let{issue:r,milestone:n}=t;if(!r.repository)throw new Error('GitLab requires "repository" for this function.');let o=`mutation SetIssueMilestone($fullPath: ID!, $issueId: String!, $milestoneId: ID) {
|
|
1285
1295
|
updateIssue(input: { projectPath: $fullPath, iid: $issueId, milestoneId: $milestoneId }) {
|
|
1286
1296
|
errors
|
|
1287
1297
|
issue {
|
|
@@ -1291,14 +1301,14 @@ query GetSingleIssue($projectId: ID!, $issueNumber: String!) {
|
|
|
1291
1301
|
}
|
|
1292
1302
|
}
|
|
1293
1303
|
}
|
|
1294
|
-
}`,i=await
|
|
1304
|
+
}`,i=await E(this.config,{query:o,variables:{fullPath:`${r.repository.owner.login}/${r.repository.name}`,issueId:r.number,milestoneId:n?.id??null}},e),a=i.body.data?.updateIssue;if(!a?.issue?.id||i.body.errors||a?.errors?.length!==0)throw new Error("Could not set milestone of issue")}async setIssueAssignees(t,e={}){let{issue:r,assignees:n}=t;if(!r.repository)throw new Error('GitLab requires "repository" for this function.');let o=n.map(l=>l.username),i=`mutation SetIssueAssignees($fullPath: ID!, $issueId: String!, $assigneeUsernames: [String!]!) {
|
|
1295
1305
|
issueSetAssignees(input: { projectPath: $fullPath, iid: $issueId, assigneeUsernames: $assigneeUsernames }) {
|
|
1296
1306
|
errors,
|
|
1297
1307
|
issue {
|
|
1298
1308
|
id
|
|
1299
1309
|
}
|
|
1300
1310
|
}
|
|
1301
|
-
}`,u=(await
|
|
1311
|
+
}`,u=(await E(this.config,{query:i,variables:{fullPath:`${r.repository.owner.login}/${r.repository.name}`,issueId:r.number,assigneeUsernames:o}},e)).body.data?.issueSetAssignees;if(!u?.issue?.id||u?.errors?.length!==0)throw new Error("Could not set issue assignees")}async getMilestonesForRepo(t,e={}){let{repo:{namespace:r,name:n},cursor:o}=t,i=await E(this.config,{query:`
|
|
1302
1312
|
query getLabelsForRepo(
|
|
1303
1313
|
$fullPath: ID!
|
|
1304
1314
|
$after: String
|
|
@@ -1309,7 +1319,7 @@ query getLabelsForRepo(
|
|
|
1309
1319
|
webUrl
|
|
1310
1320
|
milestones(after: $after) {
|
|
1311
1321
|
nodes {
|
|
1312
|
-
${
|
|
1322
|
+
${mr}
|
|
1313
1323
|
}
|
|
1314
1324
|
pageInfo {
|
|
1315
1325
|
endCursor
|
|
@@ -1318,7 +1328,7 @@ query getLabelsForRepo(
|
|
|
1318
1328
|
}
|
|
1319
1329
|
}
|
|
1320
1330
|
}
|
|
1321
|
-
`,variables:{fullPath:`${
|
|
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=>fr(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:`
|
|
1322
1332
|
query getLabelsForRepo(
|
|
1323
1333
|
$fullPath: ID!
|
|
1324
1334
|
$after: String
|
|
@@ -1328,7 +1338,7 @@ query getLabelsForRepo(
|
|
|
1328
1338
|
) {
|
|
1329
1339
|
labels(after: $after) {
|
|
1330
1340
|
nodes {
|
|
1331
|
-
${
|
|
1341
|
+
${gr}
|
|
1332
1342
|
}
|
|
1333
1343
|
pageInfo {
|
|
1334
1344
|
endCursor
|
|
@@ -1337,36 +1347,28 @@ query getLabelsForRepo(
|
|
|
1337
1347
|
}
|
|
1338
1348
|
}
|
|
1339
1349
|
}
|
|
1340
|
-
`,variables:{fullPath:`${
|
|
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(hr)??[]}}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(vo),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:`
|
|
1341
1351
|
query getPullRequestForRepo($fullPath: ID!, $iid: String!) {
|
|
1342
1352
|
project(fullPath: $fullPath) {
|
|
1343
|
-
|
|
1344
|
-
httpUrlToRepo
|
|
1345
|
-
fullPath
|
|
1346
|
-
sshUrlToRepo
|
|
1347
|
-
webUrl
|
|
1353
|
+
${Oe}
|
|
1348
1354
|
archived
|
|
1349
1355
|
mergeRequest(iid: $iid) {
|
|
1350
|
-
${
|
|
1356
|
+
${or(!1,!0,!0)}
|
|
1351
1357
|
sourceProject {
|
|
1352
|
-
|
|
1353
|
-
httpUrlToRepo
|
|
1354
|
-
fullPath
|
|
1355
|
-
sshUrlToRepo
|
|
1356
|
-
webUrl
|
|
1358
|
+
${Oe}
|
|
1357
1359
|
}
|
|
1358
1360
|
}
|
|
1359
1361
|
}
|
|
1360
1362
|
}
|
|
1361
|
-
`,variables:{fullPath:t,iid:r.number.toString()}},e)).body.data?.project,i=o?.mergeRequest;if(!o||!i)return{data:null};let a=He(o),u=i.sourceProject?He(i.sourceProject):null;return{data:er(i,a,u,this.getIsSelfHosted(e),this.config.baseUrl??e.baseUrl)}}getMergeRequestUrl(r,e,t){let n=G(r);return`${A(this.config,t)}/projects/${encodeURIComponent(n)}/merge_requests/${e}`}async getPullRequestDescription(r,e={}){try{return{data:{description:(await this.config.request({url:this.getMergeRequestUrl(r.repo,r.number,e),headers:f(e.token||this.config.token)})).body?.description??""}}}catch{return{data:{description:null}}}}async setPullRequestDescription(r,e={}){return{data:{description:(await this.config.request({method:"PUT",url:this.getMergeRequestUrl(r.repo,r.number,e),headers:{...f(e.token||this.config.token),"Content-Type":"application/json"},body:JSON.stringify({description:r.description})})).body?.description??r.description}}}async getFileContents(r,e={}){let t=G(r.repo),n=new URL(`${A(this.config,e)}/projects/${encodeURIComponent(t)}/repository/files/${encodeURIComponent(r.path)}/raw`);n.searchParams.set("ref",r.ref);let o=await this.config.request({url:n.toString(),headers:f(e.token||this.config.token)});return{data:new Blob([o.body])}}async getCommentsForPullRequest(r,e={}){let t=G(r.repo),{page:n,perPage:o}=eo(r.cursor,$),i=new URL(`${A(this.config,e)}/projects/${encodeURIComponent(t)}/merge_requests/${r.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:f(e.token||this.config.token)}),u=this.getIsSelfHosted(e),l=this.config.baseUrl??e.baseUrl,p={namespace:r.repo.namespace,name:r.repo.name,mergeRequestIid:r.pullRequestNumber},c=a.body.filter(m=>!m.system&&!m.position).map(m=>rr(m,u,l,p)),d=!!a.headers["x-next-page"],g=d?Zn({page:n+1,perPage:o}):null;return{data:c,pageInfo:{endCursor:g,hasNextPage:d}}}async getReviewsForPullRequest(r,e={}){let t=G(r.repo),n=this.getIsSelfHosted(e),o=this.config.baseUrl??e.baseUrl,i=f(e.token||this.config.token),a=A(this.config,e),u=encodeURIComponent(t),[l,p]=await Promise.all([this.config.request({url:`${a}/projects/${u}/merge_requests/${r.pullRequestId}/approvals`,headers:i}),this.fetchAllMergeRequestDiscussions(t,r.pullRequestId,e)]),c=(l.body.approved_by??[]).map(m=>m?.user).filter(m=>!!m).map(m=>{let I=os(m,n,o),y=`approval-${m.id}`;return{author:I,body:"",createdAt:l.body.updated_at?new Date(l.body.updated_at):null,id:y,graphQLId:y,reviewComments:[],url:l.body.web_url??""}}),d={namespace:r.repo.namespace,name:r.repo.name,mergeRequestIid:r.pullRequestId},g=p.filter(m=>m.notes.some(I=>!I.system&&!!I.position)).map(m=>{let I=m.notes.filter(P=>!P.system),h=I.filter(P=>!!P.position)[0];if(!h)return null;let v=I.filter(P=>P.id!==h.id).map(P=>rr(P,n,o,d)),x={...rr(h,n,o,d),diffLines:[],filename:h.position?.new_path??h.position?.old_path??"",line:h.position?.new_line??h.position?.old_line??null,startLine:h.position?.line_range?.start?.new_line??null,side:ro(h.position),isOutdated:!1,isResolved:!!m.resolved,threadId:m.id,replies:v};return{author:h.author?os(h.author,n,o):null,body:h.body??"",createdAt:h.created_at?new Date(h.created_at):null,id:m.id,graphQLId:m.id,reviewComments:[x],url:""}}).filter(m=>m!==null);return{data:[...c,...g]}}async getPullRequestDiff(r,e={}){let t=G(r.repo),n=encodeURIComponent(t),o=A(this.config,e);return(await this.fetchAllPagedGitLabREST(`${o}/projects/${n}/merge_requests/${r.pullRequestId}/diffs`,e)).map(so).join("")}async getMergeBase(r,e={}){let t=G(r.repo),n=new URL(`${A(this.config,e)}/projects/${encodeURIComponent(t)}/repository/merge_base`);n.searchParams.append("refs[]",r.base),n.searchParams.append("refs[]",r.head);let i=(await this.config.request({url:n.toString(),headers:f(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(r,e,t){let n=A(this.config,t),o=encodeURIComponent(r);return this.fetchAllPagedGitLabREST(`${n}/projects/${o}/merge_requests/${e}/discussions`,t)}async fetchAllPagedGitLabREST(r,e){let t=f(e.token||this.config.token),n=[],o=1,i=50;for(;o<=i;){let a=new URL(r);a.searchParams.set("page",o.toString()),a.searchParams.set("per_page",$.toString());let u=await this.config.request({url:a.toString(),headers:t});n.push(...u.body);let l=u.headers["x-next-page"];if(!l)break;let p=parseInt(`${l}`,10);if(Number.isNaN(p))break;o=p}return n}async addCommentToPullRequest(r,e={}){let{pullRequest:t,comment:n}=r;if(!n||n.trim()==="")throw new Error("GitLab requires a comment when adding a comment to a pull request.");let o=`${t.repository.owner.login}/${t.repository.name}`,i=`${A(this.config,e)}/projects/${encodeURIComponent(o)}/merge_requests/${t.number}/notes`;if(!(await this.config.request({method:"POST",url:i,headers:{...f(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(r,e={}){let{pullRequest:t,comment:n,path:o,line:i,side:a="RIGHT",threadId:u}=r;if(!n?.trim())throw new Error("GitLab requires a comment when adding an inline comment to a pull request.");let l=`${t.repository.owner.login}/${t.repository.name}`,p=encodeURIComponent(l),c=A(this.config,e),d={...f(e.token||this.config.token),"Content-Type":"application/json"};if(u){let v=await this.config.request({method:"POST",url:`${c}/projects/${p}/merge_requests/${t.number}/discussions/${encodeURIComponent(u)}/notes`,headers:d,body:JSON.stringify({body:n})});return v.body?.id!=null?sr(t.repository.owner.login,t.repository.name,t.number,v.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:`${c}/projects/${p}/merge_requests/${t.number}`,headers:f(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 I={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"?I.new_line=i:I.old_line=i;let h=(await this.config.request({method:"POST",url:`${c}/projects/${p}/merge_requests/${t.number}/discussions`,headers:d,body:JSON.stringify({body:n,position:I})})).body?.notes?.[0]?.id;return h!=null?sr(t.repository.owner.login,t.repository.name,t.number,h):void 0}getNoteUrl(r,e){if(!r)throw new Error('GitLab requires "commentId" for this function.');let{namespace:t,name:n,mergeRequestIid:o,noteId:i}=no(r);return`${A(this.config,e)}/projects/${encodeURIComponent(`${t}/${n}`)}/merge_requests/${o}/notes/${i}`}async deleteNote(r,e){await this.config.request({method:"DELETE",url:this.getNoteUrl(r,e),headers:f(e.token||this.config.token)})}async deleteComment(r,e={}){await this.deleteNote(r.commentId,e)}async deleteInlineComment(r,e={}){await this.deleteNote(r.commentId,e)}async editNote(r,e,t){if(!e?.trim())throw new Error("GitLab requires a body when editing a comment.");if(!(await this.config.request({method:"PUT",url:this.getNoteUrl(r,t),headers:{...f(t.token||this.config.token),"Content-Type":"application/json"},body:JSON.stringify({body:e})})).body?.id)throw new Error("Could not edit comment")}async editComment(r,e={}){await this.editNote(r.commentId,r.body,e)}async editInlineComment(r,e={}){await this.editNote(r.commentId,r.body,e)}async resolveReviewThread(r,e={}){await this.setReviewThreadResolved(r,!0,e)}async unresolveReviewThread(r,e={}){await this.setReviewThreadResolved(r,!1,e)}async setReviewThreadResolved(r,e,t){if(!r.repo||r.pullRequestNumber==null)throw new Error("GitLab requires input.repo and input.pullRequestNumber to locate the discussion to (un)resolve.");if(!r.threadId)throw new Error("GitLab requires input.threadId to (un)resolve a discussion.");let n=G(r.repo),o=new URL(`${A(this.config,t)}/projects/${encodeURIComponent(n)}/merge_requests/${r.pullRequestNumber}/discussions/${encodeURIComponent(r.threadId)}`);o.searchParams.set("resolved",e?"true":"false"),await this.config.request({url:o.toString(),method:"PUT",headers:f(t.token||this.config.token)})}async approvePullRequest(r,e={}){let{pullRequest:t,comment:n}=r,o=`${t.repository.owner.login}/${t.repository.name}`,i=A(this.config,e),a=encodeURIComponent(o),u=f(e.token||this.config.token);await this.config.request({url:`${i}/projects/${a}/merge_requests/${t.number}/approve`,method:"POST",headers:u}),n&&n.trim()!==""&&await this.postMergeRequestNote(o,t.number,n,e)}async commentOnPullRequest(r,e={}){let{pullRequest:t,comment:n}=r;if(!n||n.trim()==="")throw new Error("GitLab requires a comment when commenting on a pull request.");let o=`${t.repository.owner.login}/${t.repository.name}`;await this.postMergeRequestNote(o,t.number,n,e)}async requestPullRequestChanges(r,e={}){let{pullRequest:t,comment:n}=r;if(!n||n.trim()==="")throw new Error("GitLab requires a comment when requesting changes on a pull request.");let o=`${t.repository.owner.login}/${t.repository.name}`;if(!await this.tryRequestChangesMutation(o,t.number,e)){let u=`${A(this.config,e)}/projects/${encodeURIComponent(o)}/merge_requests/${t.number}`,l=f(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,t.number,n,e)}async tryRequestChangesMutation(r,e,t){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=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`${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}=$o(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,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?Ao({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=U(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:Uo(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=U(this.config,e);return(await this.fetchAllPagedGitLabREST(`${o}/projects/${n}/merge_requests/${t.pullRequestId}/diffs`,e)).map(Go).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){let r=R(e.token||this.config.token),n=[],o=1,i=50;for(;o<=i;){let a=new URL(t);a.searchParams.set("page",o.toString()),a.searchParams.set("per_page",$.toString());let u=await this.config.request({url:a.toString(),headers:r});n.push(...u.body);let l=u.headers["x-next-page"];if(!l)break;let p=parseInt(`${l}`,10);if(Number.isNaN(p))break;o=p}return n}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}`,p=encodeURIComponent(l),d=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:`${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}=To(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!) {
|
|
1362
1364
|
mergeRequestRequestChanges(input: { projectPath: $fullPath, iid: $pullRequestId }) {
|
|
1363
1365
|
errors
|
|
1364
1366
|
mergeRequest {
|
|
1365
1367
|
id
|
|
1366
1368
|
}
|
|
1367
1369
|
}
|
|
1368
|
-
}`,o=await
|
|
1369
|
-
OR comment ~ currentUser() OR summary ~ currentUser() OR description ~ currentUser())`];i&&i.forEach(h=>u.push(`labels = "${h}"`));let l=`${u.join(" AND ")} ORDER BY updated DESC`,p=!o,c=p?ls:us,d=new URL(`${ne(s,t,o)}${c}`);d.searchParams.set("jql",l),d.searchParams.set("maxResults",Ve.toString()),d.searchParams.set("fields",pr.join(",")),d.searchParams.set("expand","transitions"),n&&(p?d.searchParams.set("startAt",n):d.searchParams.set("nextPageToken",n));let g=await s.request({url:d.toString(),headers:f(t.token||s.token)}),m=g.body.issues.map(h=>dr(h,a,e,o)),I=!1,y="";return p?(I=m.length==Ve,y=(parseInt(n??"0",10)+m.length).toString()):(I=!!g.body.nextPageToken,y=g.body.nextPageToken??null),{data:m,pageInfo:{hasNextPage:I,endCursor:y}}},ps=async(s,r,e,t={})=>{let{cursor:n,resourceId:o,jql:i,fields:a}=r||{},u=[...pr],l=a?.Sprint;l&&u.push(l);let p=!o,c=p?ls:us,d=new URL(`${ne(s,t,o)}${c}`);d.searchParams.set("jql",i.join(" AND ")),d.searchParams.set("maxResults",Ve.toString()),d.searchParams.set("fields",u.join(",")),d.searchParams.set("expand","transitions"),n&&(p?d.searchParams.set("startAt",n):d.searchParams.set("nextPageToken",n));let g=await s.request({url:d.toString(),headers:f(t.token||s.token)}),m=g.body.issues.map(h=>dr(h,a,e,o)),I=!1,y="";return p?(I=m.length==Ve,y=(parseInt(n??"0",10)+m.length).toString()):(I=!!g.body.nextPageToken,y=g.body.nextPageToken??null),{data:m,pageInfo:{hasNextPage:I,endCursor:y}}},et=async(s,r,e,t={})=>{let{assigneeLogins:n,authorLogin:o,mentionLogin:i,labelNames:a,cursor:u,projectKey:l,resourceId:p,fields:c}=r||{},d=[`project = "${l}"`,"statusCategory != Done"];return o&&d.push(`creator in ("${o}")`),n&&n.length!==0&&d.push(`assignee in ("${n.join('", "')}")`),i&&d.push(`comment ~ "${i}"`),a&&a.forEach(g=>d.push(`labels = "${g}"`)),ps(s,{resourceId:p,jql:d,cursor:u,fields:c},e,t)},tt=async(s,r,e,t={})=>{let{assigneeLogins:n,authorLogin:o,mentionLogin:i,labelNames:a,cursor:u,projectKeys:l,resourceId:p,fields:c}=r||{},g=["("+l.map(m=>`project = "${m}"`).join(" OR ")+")","statusCategory != Done"];return o&&g.push(`creator in ("${o}")`),n&&n.length!==0&&g.push(`assignee in ("${n.join('", "')}")`),i&&g.push(`comment ~ "${i}"`),a&&a.forEach(m=>g.push(`labels = "${m}"`)),ps(s,{resourceId:p,jql:g,fields:c,cursor:u},e,t)},rt=async(s,r,e={})=>{let{issue:t,labels:n}=r;if(!t.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:`${ne(s,e,t.project.resourceId??void 0)}/rest/api/2/issue/${t.id}`,body:JSON.stringify(o),headers:{...f(e.token||s.token),"Content-Type":"application/json"}})},st=async(s,r,e={})=>{let{issue:t,components:n}=r;if(!t.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:`${ne(s,e,t.project.resourceId??void 0)}/rest/api/2/issue/${t.id}`,body:JSON.stringify(o),headers:{...f(e.token||s.token),"Content-Type":"application/json"}})},nt=async(s,r,e={})=>{let{issue:t,status:n}=r;if(!t.project)throw new Error('Jira requires a "project" for this function.');if(!n.id)throw new Error('Jira requires a status "id" for this function.');let o={transition:{id:n.id}};await s.request({method:"POST",url:`${ne(s,e,t.project.resourceId??void 0)}/rest/api/2/issue/${t.id}/transitions`,body:JSON.stringify(o),headers:{...f(e.token||s.token),"Content-Type":"application/json"}})},ot=async(s,r,e={})=>{let{resourceId:t,projectIdOrKey:n}=r,o=new URL(`${ne(s,e,t)}/rest/api/2/project/${n}/components`);return{data:(await s.request({url:o.toString(),headers:f(e.token||s.token)})).body}};var Ae="https://api.atlassian.com/ex/jira",cr=100,be=class extends F{constructor(){super(...arguments);this._resourceUrlCache={};this._issueFieldsCache={}}async getIssueFieldsForResource(e,t={}){if(!this._issueFieldsCache[e.resourceId]){let n=await Xe(this.config,e,t);this._issueFieldsCache[e.resourceId]=n.reduce((o,i)=>({...o,[i.name]:i.id}),{})}return this._issueFieldsCache[e.resourceId]??null}async getResourceUrl(e,t={}){let n=t.token||this.config.token;if(!n)return null;let o=this._resourceUrlCache[n];return o?o[e.resourceId]??null:(await this.getJiraResourcesForCurrentUser(t),this._resourceUrlCache[n]?.[e.resourceId]??null)}async getCurrentUserForResource(e,t={}){let n=await this.getResourceUrl({resourceId:e.resourceId},t),o=await this.config.request({url:`${t.baseUrl||Ae}/${e.resourceId}/rest/api/2/myself`,headers:f(t.token||this.config.token)});return{data:{name:o.body.displayName,email:o.body.emailAddress,avatarUrl:o.body.avatarUrls["48x48"],id:o.body.accountId,username:o.body.displayName,url:n?`${n}/jira/people/${o.body.accountId}`:null}}}async getJiraResourcesForCurrentUser(e={}){let t=await this.config.request({url:`${e.baseUrl||"https://api.atlassian.com/"}/oauth/token/accessible-resources`,headers:f(e.token||this.config.token)}),n=e.token||this.config.token,o=n?this._resourceUrlCache[n]||{}:void 0,i=t.body.map(a=>(o&&(o[a.id]=a.url),{avatarUrl:a.avatarUrl,id:a.id,name:a.name,url:a.url}));return n&&(this._resourceUrlCache[n]=o),{data:i}}async getJiraProjectsForResource(e,t={}){let n=new URL(`${t.baseUrl||Ae}/${e.resourceId}/rest/api/2/project/search`);n.searchParams.set("maxResults",cr.toString()),e.cursor&&n.searchParams.set("startAt",e.cursor);let o=await this.config.request({url:n.toString(),headers:f(t.token||this.config.token)});return{pageInfo:{hasNextPage:o.body.values.length!==0,endCursor:(o.body.startAt+o.body.values.length).toString()},data:o.body.values.map(i=>({id:i.id,key:i.key,name:i.name,resourceId:e.resourceId}))}}async getJiraProjectsForResources(e,t={}){let n=[];return await Promise.all(e.resourceIds.map(async o=>{try{return await Or(i=>this.getJiraProjectsForResource({resourceId:o,cursor:i},t))}catch{return[]}})).then((...o)=>{o.forEach(i=>{n=n.concat(...i)})}),{data:n}}async getAccountsForJiraProject(e,t={}){let{resourceId:n,projectKey:o,cursor:i}=e,a=await this.getResourceUrl({resourceId:n},t),u=new URL(`${t.baseUrl||Ae}/${n}/rest/api/2/user/assignable/search`);u.searchParams.set("maxResults",cr.toString()),i&&u.searchParams.set("startAt",i),u.searchParams.set("project",o);let l=await this.config.request({url:u.toString(),headers:f(t.token||this.config.token)});return{pageInfo:{hasNextPage:l.body.length!==0,endCursor:((i?parseInt(i):0)+l.body.length).toString()},data:l.body.filter(p=>p.accountType!=="app"&&p.active).map(p=>Ke(p,a,!1))}}async getComponentsForJiraProject(e,t={}){return await ot(this.config,e,t)}async getIssue(e,t={}){let n=await this.getIssueFieldsForResource({resourceId:e.resourceId},t),o=await this.getResourceUrl({resourceId:e.resourceId},t);return await Ye(this.config,{...e,fields:n},o,t)}async getIssuesForProject(e,t={}){let n=await this.getIssueFieldsForResource({resourceId:e.resourceId},t),o=await this.getResourceUrl({resourceId:e.resourceId},t);return await et(this.config,{...e,fields:n},o,t)}async getIssuesForProjects(e,t={}){let n=await this.getIssueFieldsForResource({resourceId:e.resourceId},t),o=await this.getResourceUrl({resourceId:e.resourceId},t);return await tt(this.config,{...e,fields:n},o,t)}async getIssuesForResourceForCurrentUser(e,t={}){let n=await this.getIssueFieldsForResource({resourceId:e.resourceId},t),o=await this.getResourceUrl({resourceId:e.resourceId},t);return await Ze(this.config,{...e,fields:n},o,t)}async setIssueStatus(e,t={}){await nt(this.config,e,t)}async setIssueAssignee(e,t={}){let{issue:n,assignee:o}=e;if(!n.project)throw new Error('Jira Cloud requires a "project" for this function.');if(!n.project.resourceId)throw new Error('Jira Cloud requires a project "resourceId" for this function.');let i={accountId:o?.id};await this.config.request({method:"PUT",url:`${t.baseUrl||Ae}/${n.project.resourceId}/rest/api/2/issue/${n.id}/assignee`,body:JSON.stringify(i),headers:{...f(t.token||this.config.token),"Content-Type":"application/json"}})}async setIssueComponents(e,t={}){await st(this.config,e,t)}async setIssueLabels(e,t={}){await rt(this.config,e,t)}async getLabelsForResource(e,t={}){let{resourceId:n,cursor:o}=e,i=new URL(`${t.baseUrl||Ae}/${n}/rest/api/2/label`);i.searchParams.set("maxResults",cr.toString()),o&&i.searchParams.set("startAt",o);let a=await this.config.request({url:i.toString(),headers:f(t.token||this.config.token)});return{pageInfo:{hasNextPage:!a.body.isLast,endCursor:(a.body.startAt+a.body.values.length).toString()},data:a.body.values.map(u=>({color:null,description:null,id:null,name:u}))}}};var ye=class extends j{constructor(){super(...arguments);this._issueFieldsCache={}}async getIssueFieldsForResource(e={}){let t=e?.baseUrl||this.config.baseUrl||"";if(!this._issueFieldsCache[t]){let n=await Xe(this.config,{},e);this._issueFieldsCache[t]=n.reduce((o,i)=>({...o,[i.name]:i.id}),{})}return this._issueFieldsCache[t]??null}async getCurrentUser(e={}){let t=await this.config.request({url:`${e?.baseUrl||this.config.baseUrl}/rest/api/2/myself`,headers:f(e?.token||this.config.token)});return{data:{name:t.body.displayName,email:t.body.emailAddress,avatarUrl:t.body.avatarUrls["48x48"],id:t.body.key,username:t.body.displayName,url:null}}}async getJiraProjects(e={}){return{data:(await this.config.request({url:`${e?.baseUrl||this.config.baseUrl}/rest/api/2/project`,headers:f(e?.token||this.config.token)})).body.map(n=>({id:n.id,name:n.name}))}}async getIssue(e,t={}){let n=e.resourceUrl||t.baseUrl||this.config.baseUrl;if(!n)throw new Error('Jira Server requires a "resourceUrl" or "baseUrl" for this function.');let o=await this.getIssueFieldsForResource(t);return await Ye(this.config,{...e,fields:o},n,t)}async getIssuesForProject(e,t={}){let n=e.resourceUrl||t.baseUrl||this.config.baseUrl;if(!n)throw new Error('Jira Server requires a "resourceUrl" or "baseUrl" for this function.');let o=await this.getIssueFieldsForResource(t);return await et(this.config,{...e,fields:o},n,t)}async getIssuesForProjects(e,t={}){let n=e.resourceUrl||t.baseUrl||this.config.baseUrl;if(!n)throw new Error('Jira Server requires a "resourceUrl" or "baseUrl" for this function.');let o=await this.getIssueFieldsForResource(t);return await tt(this.config,{...e,fields:o},n,t)}async getIssuesForResourceForCurrentUser(e,t={}){let n=e.resourceUrl||t.baseUrl||this.config.baseUrl;if(!n)throw new Error('Jira Server requires a "resourceUrl" or "baseUrl" for this function.');let o=await this.getIssueFieldsForResource(t);return await Ze(this.config,{...e,fields:o},n,t)}async setIssueStatus(e,t={}){await nt(this.config,e,t)}async setIssueLabels(e,t={}){await rt(this.config,e,t)}async setIssueComponents(e,t={}){await st(this.config,e,t)}async getLabels(e={}){return{data:(await this.config.request({url:`${e?.baseUrl||this.config.baseUrl}/rest/api/2/jql/autocompletedata/suggestions?fieldName=labels`,headers:f(e.token||this.config.token)})).body.results.map(({displayName:n})=>({color:null,description:null,id:null,name:n}))}}async getComponentsForJiraProject(e,t={}){return await ot(this.config,e,t)}};var gr=100,it=class{constructor(){this.set=new Set;this.arr=[]}push(...r){let e=r.filter(t=>!this.set.has(t.id));this.arr.push(...e),e.forEach(t=>this.set.add(t.id))}get length(){return this.arr.length}get items(){return this.arr}},re=async(s,r,e,t)=>{let n=r.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:t})});if(o.status>=400)throw new Error(`Linear API request failed: ${o.status} ${o.statusText}`);let i=o.body;if(i.errors)throw new Error(`Linear GraphQL errors: ${i.errors.map(a=>a.message).join(", ")}`);return i.data},mr=s=>s?s instanceof Date?s:new Date(s):null,mo=`
|
|
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(wo))return!1;throw new Error(`Could not request pull request changes: ${Ge(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 Oo="https://api.atlassian.com/ex/jira",tt=100,Ds=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"},Rr=["assignee","comment","summary","created","creator","updated","votes","issuetype","status","labels","components","project","fixVersions","description"],As="/rest/api/2/search/jql",$s="/rest/api/2/search",Ir=(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:rt(s.fields.creator,e,o),updatedDate:new Date(s.fields.updated),assignees:n?[rt(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:No(s.fields.status),statusTransitions:s.transitions?.map(_o)??[],components:s.fields.components?.map(ko)??[],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(Bo),fixVersions:s.fields.fixVersions.map(jo)}},_o=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}}},ko=s=>({description:s.description??null,id:s.id,name:s.name}),xo=(s,t,e)=>e&&s.name?`${t}/secure/ViewProfile.jspa?name=${encodeURIComponent(s.name)}`:`${t}/jira/people/${s.accountId}`,rt=(s,t,e)=>({id:(e?s.key:s.accountId)??"",name:s.displayName,email:s.emailAddress,avatarUrl:s.avatarUrls["48x48"],username:s.displayName,url:xo(s,t,e)}),No=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}},Bo=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}),jo=s=>({id:s.id,description:s.description,name:s.name,archived:s.archived,released:s.released,releaseDate:s.releaseDate?new Date(s.releaseDate):null}),ue=(s,t,e)=>e?`${t.baseUrl||Oo}/${e}`:`${t?.baseUrl||s.baseUrl}`,st=async(s,t,e={})=>{let{resourceId:r}=t;return(await s.request({url:`${ue(s,e,r)}/rest/api/2/field`,headers:R(e.token||s.token)})).body},nt=async(s,t,e,r={})=>{let{number:n,resourceId:o,fields:i}=t||{},a=await s.request({url:`${ue(s,r,o)}/rest/api/2/issue/${n}?fields=${Rr.join(",")}&expand=transitions`,headers:R(r.token||s.token)});return{data:Ir(a.body,i,e,o)}},ot=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`,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,Qo=`
|
|
1370
1372
|
id
|
|
1371
1373
|
name
|
|
1372
1374
|
description
|
|
@@ -1374,11 +1376,11 @@ OR comment ~ currentUser() OR summary ~ currentUser() OR description ~ currentUs
|
|
|
1374
1376
|
startDate
|
|
1375
1377
|
targetDate
|
|
1376
1378
|
url
|
|
1377
|
-
`,
|
|
1379
|
+
`,Us=s=>({id:s.id,name:s.name,description:s.description??null,state:s.state,startDate:yr(s.startDate),targetDate:yr(s.targetDate),url:s.url}),Gs=async(s,t,e)=>{let r=`
|
|
1378
1380
|
query GetProjects($first: Int!, $after: String) {
|
|
1379
1381
|
projects(first: $first, after: $after) {
|
|
1380
1382
|
nodes {
|
|
1381
|
-
${
|
|
1383
|
+
${Qo}
|
|
1382
1384
|
}
|
|
1383
1385
|
pageInfo {
|
|
1384
1386
|
hasNextPage
|
|
@@ -1386,7 +1388,7 @@ OR comment ~ currentUser() OR summary ~ currentUser() OR description ~ currentUs
|
|
|
1386
1388
|
}
|
|
1387
1389
|
}
|
|
1388
1390
|
}
|
|
1389
|
-
`;return(await
|
|
1391
|
+
`;return(await ne(s,t,r,{first:Pr,after:e})).projects},Fo=`
|
|
1390
1392
|
id
|
|
1391
1393
|
name
|
|
1392
1394
|
number
|
|
@@ -1394,11 +1396,11 @@ OR comment ~ currentUser() OR summary ~ currentUser() OR description ~ currentUs
|
|
|
1394
1396
|
startsAt
|
|
1395
1397
|
endsAt
|
|
1396
1398
|
completedAt
|
|
1397
|
-
`,
|
|
1399
|
+
`,Ts=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:yr(s.completedAt),url:""}),Os=async(s,t,e)=>{let r=`
|
|
1398
1400
|
query GetCycles($first: Int!, $after: String) {
|
|
1399
1401
|
cycles(first: $first, after: $after) {
|
|
1400
1402
|
nodes {
|
|
1401
|
-
${
|
|
1403
|
+
${Fo}
|
|
1402
1404
|
}
|
|
1403
1405
|
pageInfo {
|
|
1404
1406
|
hasNextPage
|
|
@@ -1406,16 +1408,16 @@ OR comment ~ currentUser() OR summary ~ currentUser() OR description ~ currentUs
|
|
|
1406
1408
|
}
|
|
1407
1409
|
}
|
|
1408
1410
|
}
|
|
1409
|
-
`;return(await
|
|
1411
|
+
`;return(await ne(s,t,r,{first:Pr,after:e})).cycles},zo=`
|
|
1410
1412
|
id
|
|
1411
1413
|
name
|
|
1412
1414
|
color
|
|
1413
1415
|
description
|
|
1414
|
-
`,
|
|
1416
|
+
`,_s=s=>({id:s.id,name:s.name,color:s.color,description:s.description??null}),ks=async(s,t,e)=>{let r=`
|
|
1415
1417
|
query GetLabels($first: Int!, $after: String) {
|
|
1416
1418
|
projectLabels(first: $first, after: $after) {
|
|
1417
1419
|
nodes {
|
|
1418
|
-
${
|
|
1420
|
+
${zo}
|
|
1419
1421
|
}
|
|
1420
1422
|
pageInfo {
|
|
1421
1423
|
hasNextPage
|
|
@@ -1423,36 +1425,36 @@ OR comment ~ currentUser() OR summary ~ currentUser() OR description ~ currentUs
|
|
|
1423
1425
|
}
|
|
1424
1426
|
}
|
|
1425
1427
|
}
|
|
1426
|
-
`;return(await
|
|
1428
|
+
`;return(await ne(s,t,r,{first:Pr,after:e})).projectLabels};var ke=(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))(ke||{});function xs(s,t){return s?`${ke[s]}:${t||""}`:t??null}function Ns(s){if(!s)return{category:0};let[t,e]=s.split(":");return t in ke?{category:ke[t],cursor:e||void 0}:{category:0,cursor:s}}var Bs=100;function gt(s){return s?s instanceof Date?s:new Date(s):null}var Fs=`
|
|
1427
1429
|
id
|
|
1428
1430
|
name
|
|
1429
1431
|
key
|
|
1430
1432
|
icon
|
|
1431
|
-
`;function
|
|
1433
|
+
`;function Mo(s){return{id:s.id,name:s.name,key:s.key,iconUrl:s.icon}}var js=`
|
|
1432
1434
|
id
|
|
1433
1435
|
name
|
|
1434
1436
|
avatarUrl
|
|
1435
|
-
`;function
|
|
1437
|
+
`;function Qs(s){return s?{id:s.id,name:s.name,username:s.name,email:null,avatarUrl:s.avatarUrl??null,url:null}:null}var Wo=`
|
|
1436
1438
|
id
|
|
1437
1439
|
name
|
|
1438
|
-
`;function
|
|
1440
|
+
`;function Ho(s,t){if(s)return{id:s.id,name:s.name,key:t?.key||null,namespace:null,resourceId:t?.id||null}}var Vo=`
|
|
1439
1441
|
id
|
|
1440
1442
|
sortOrder
|
|
1441
1443
|
name
|
|
1442
1444
|
description
|
|
1443
1445
|
status
|
|
1444
1446
|
targetDate
|
|
1445
|
-
`;function
|
|
1447
|
+
`;function Jo(s){return s?{id:s.id,number:s.sortOrder,title:s.name,description:s.description??null,isOpen:s.status!=="done",url:"",startDate:null,dueDate:gt(s.targetDate)}:null}function Ko(s){switch(s){case"completed":case"canceled":return"DONE";case"started":return"IN_PROGRESS";default:return"TO_DO"}}var Xo=`
|
|
1446
1448
|
id
|
|
1447
1449
|
name
|
|
1448
1450
|
color
|
|
1449
1451
|
type
|
|
1450
|
-
`;function
|
|
1452
|
+
`;function Zo(s){return s?{id:s.id,name:s.name,color:s.color,category:Ko(s.type)}:null}var qr=`
|
|
1451
1453
|
creator {
|
|
1452
|
-
${
|
|
1454
|
+
${js}
|
|
1453
1455
|
}
|
|
1454
1456
|
assignee {
|
|
1455
|
-
${
|
|
1457
|
+
${js}
|
|
1456
1458
|
}
|
|
1457
1459
|
archivedAt
|
|
1458
1460
|
createdAt
|
|
@@ -1460,35 +1462,35 @@ OR comment ~ currentUser() OR summary ~ currentUser() OR description ~ currentUs
|
|
|
1460
1462
|
id
|
|
1461
1463
|
identifier
|
|
1462
1464
|
project {
|
|
1463
|
-
${
|
|
1465
|
+
${Wo}
|
|
1464
1466
|
}
|
|
1465
1467
|
team {
|
|
1466
|
-
${
|
|
1468
|
+
${Fs}
|
|
1467
1469
|
}
|
|
1468
1470
|
state {
|
|
1469
|
-
${
|
|
1471
|
+
${Xo}
|
|
1470
1472
|
}
|
|
1471
1473
|
title
|
|
1472
1474
|
updatedAt
|
|
1473
1475
|
url
|
|
1474
1476
|
projectMilestone {
|
|
1475
|
-
${
|
|
1477
|
+
${Vo}
|
|
1476
1478
|
}
|
|
1477
|
-
`;async function
|
|
1479
|
+
`;async function wr(s){return{author:Qs(await s.creator),assignees:[Qs(await s.assignee)].filter(t=>t!=null),commentCount:null,closedDate:gt(s.archivedAt),createdDate:gt(s.createdAt),description:s.description??null,id:s.id,labels:[],number:s.identifier,repository:null,project:Ho(await s.project,await s.team),state:Zo(await s.state),title:s.title,type:null,updatedDate:gt(s.updatedAt),upvoteCount:null,url:s.url,milestone:Jo(await s.projectMilestone)}}var mt=`
|
|
1478
1480
|
nodes {
|
|
1479
|
-
${
|
|
1481
|
+
${qr}
|
|
1480
1482
|
}
|
|
1481
1483
|
pageInfo {
|
|
1482
1484
|
hasNextPage
|
|
1483
1485
|
endCursor
|
|
1484
1486
|
}
|
|
1485
|
-
`,
|
|
1487
|
+
`,Ee=class extends M{async fetchIssue(t,e){let r=`
|
|
1486
1488
|
query GetIssue($identifier: String!) {
|
|
1487
1489
|
issue(id: $identifier) {
|
|
1488
|
-
${
|
|
1490
|
+
${qr}
|
|
1489
1491
|
}
|
|
1490
1492
|
}
|
|
1491
|
-
`;return(await
|
|
1493
|
+
`;return(await ne(this.config,e,r,{identifier:t})).issue}async fetchOrganization(t){let e=`
|
|
1492
1494
|
query GetOrganization {
|
|
1493
1495
|
organization {
|
|
1494
1496
|
id
|
|
@@ -1496,15 +1498,15 @@ OR comment ~ currentUser() OR summary ~ currentUser() OR description ~ currentUs
|
|
|
1496
1498
|
urlKey
|
|
1497
1499
|
}
|
|
1498
1500
|
}
|
|
1499
|
-
`;return(await
|
|
1501
|
+
`;return(await ne(this.config,t,e)).organization}async fetchTeams(t){let e=`
|
|
1500
1502
|
query GetTeams {
|
|
1501
1503
|
teams {
|
|
1502
1504
|
nodes {
|
|
1503
|
-
${
|
|
1505
|
+
${Fs}
|
|
1504
1506
|
}
|
|
1505
1507
|
}
|
|
1506
1508
|
}
|
|
1507
|
-
`;return(await
|
|
1509
|
+
`;return(await ne(this.config,t,e)).teams}async rawRequest(t,e,r){return{data:await ne(this.config,t,e,r)}}async fetchViewer(t){let e=`
|
|
1508
1510
|
query GetViewer {
|
|
1509
1511
|
viewer {
|
|
1510
1512
|
id
|
|
@@ -1513,23 +1515,23 @@ OR comment ~ currentUser() OR summary ~ currentUser() OR description ~ currentUs
|
|
|
1513
1515
|
displayName
|
|
1514
1516
|
}
|
|
1515
1517
|
}
|
|
1516
|
-
`;return(await
|
|
1518
|
+
`;return(await ne(this.config,t,e)).viewer}async getIssue(t,e={}){let r=await this.fetchIssue(t.number,e);return{data:await wr(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(Mo)}}async getProjects(t={},e={}){let r=await Gs(this.config,e,t.cursor??void 0);return{data:r.nodes.map(Us),pageInfo:{hasNextPage:r.pageInfo.hasNextPage,endCursor:r.pageInfo.endCursor??null}}}async getCycles(t={},e={}){let r=await Os(this.config,e,t.cursor??void 0);return{data:r.nodes.map(Ts),pageInfo:{hasNextPage:r.pageInfo.hasNextPage,endCursor:r.pageInfo.endCursor??null}}}async getLabels(t={},e={}){let r=await ks(this.config,e,t.cursor??void 0);return{data:r.nodes.map(_s),pageInfo:{hasNextPage:r.pageInfo.hasNextPage,endCursor:r.pageInfo.endCursor??null}}}async getCurrentUser(t={}){return{data:await this.fetchViewer(t)}}async getIssuesForCurrentUser(t,e={}){let{cursor:r}=t,{category:n,cursor:o}=Ns(r),i=await this.fetchViewer(e),a,u,l=new ct,p=async(d,c)=>{if(u||n>d)return;let g=await c(Math.max(Bs-l.length,1),n===d?o:void 0);if(!g)return;let m=await kt(g.nodes.map(wr));l.push(...m),g.pageInfo.hasNextPage&&(a=d,u=g.pageInfo.endCursor)};return await p(1,async(d,c)=>(await this.rawRequest(e,`
|
|
1517
1519
|
query GetAssignedIssues($first: Int!, $after: String) {
|
|
1518
1520
|
viewer {
|
|
1519
1521
|
issues: assignedIssues(first: $first, after: $after) {
|
|
1520
|
-
${
|
|
1522
|
+
${mt}
|
|
1521
1523
|
}
|
|
1522
1524
|
}
|
|
1523
1525
|
}
|
|
1524
|
-
`,{first:
|
|
1526
|
+
`,{first:d,after:c})).data?.viewer?.issues),await p(2,async(d,c)=>(await this.rawRequest(e,`
|
|
1525
1527
|
query GetCreatedIssues($first: Int!, $after: String) {
|
|
1526
1528
|
viewer {
|
|
1527
1529
|
issues: createdIssues(first: $first, after: $after) {
|
|
1528
|
-
${
|
|
1530
|
+
${mt}
|
|
1529
1531
|
}
|
|
1530
1532
|
}
|
|
1531
1533
|
}
|
|
1532
|
-
`,{first:
|
|
1534
|
+
`,{first:d,after:c})).data?.viewer?.issues),await p(4,async(d,c)=>(await this.rawRequest(e,`
|
|
1533
1535
|
query GetMentionedIssues($first: Int!, $after: String) {
|
|
1534
1536
|
issues(
|
|
1535
1537
|
first: $first
|
|
@@ -1550,10 +1552,10 @@ OR comment ~ currentUser() OR summary ~ currentUser() OR description ~ currentUs
|
|
|
1550
1552
|
}]
|
|
1551
1553
|
}
|
|
1552
1554
|
){
|
|
1553
|
-
${
|
|
1555
|
+
${mt}
|
|
1554
1556
|
}
|
|
1555
1557
|
}
|
|
1556
|
-
`,{first:
|
|
1558
|
+
`,{first:d,after:c})).data?.issues),await p(5,async(d,c)=>{let m=(await this.rawRequest(e,`
|
|
1557
1559
|
query GetCommentedIssues($first: Int!, $after: String) {
|
|
1558
1560
|
comments(
|
|
1559
1561
|
first: $first
|
|
@@ -1576,7 +1578,7 @@ OR comment ~ currentUser() OR summary ~ currentUser() OR description ~ currentUs
|
|
|
1576
1578
|
){
|
|
1577
1579
|
nodes {
|
|
1578
1580
|
issue {
|
|
1579
|
-
${
|
|
1581
|
+
${qr}
|
|
1580
1582
|
}
|
|
1581
1583
|
}
|
|
1582
1584
|
pageInfo {
|
|
@@ -1585,10 +1587,10 @@ OR comment ~ currentUser() OR summary ~ currentUser() OR description ~ currentUs
|
|
|
1585
1587
|
}
|
|
1586
1588
|
}
|
|
1587
1589
|
}
|
|
1588
|
-
`,{first:
|
|
1590
|
+
`,{first:d,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:xs(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=`
|
|
1589
1591
|
query GetIssues($first: Int!, $after: String) {
|
|
1590
1592
|
issues(first: $first, after: $after${u?", ":""}${u}) {
|
|
1591
|
-
${
|
|
1593
|
+
${mt}
|
|
1592
1594
|
}
|
|
1593
1595
|
}
|
|
1594
|
-
`,c=(await this.rawRequest(e,l,{first:bs,after:i})).data?.issues;return c?{data:await Tt(c.nodes.map(hr)),pageInfo:{hasNextPage:c.pageInfo.hasNextPage,endCursor:c.pageInfo.endCursor??null}}:{data:[],pageInfo:{hasNextPage:!1,endCursor:null}}}};var K="https://api.trello.com",vo=1e3,X=(s,r)=>({...f(r),Authorization:`OAuth oauth_consumer_key="${s}", oauth_token="${r}"`}),Eo=s=>({id:s.id,username:s.username,url:s.url,name:s.fullName,email:s.email,avatarUrl:s.avatarUrl}),So=(s,r)=>{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(t=>({id:t.id,username:t.username,name:t.fullName,email:null,avatarUrl:t.avatarUrl,url:null})),description:null,state:r[s.idList??""]?{id:s.idList,name:r[s.idList].name,color:null}:null,type:null,repository:null,upvoteCount:s.badges.votes,labels:s.labels.map(t=>({color:t.color,description:null,id:t.id,name:t.name}))}},we=class extends F{async getCurrentUser(r,e={}){let t=await this.config.request({url:`${e.baseUrl||K}/1/members/me`,headers:X(r.appKey,e.token||this.config.token)});return{data:{name:t.body.fullName,email:t.body.email,avatarUrl:t.body.avatarHash?`https://trello-members.s3.amazonaws.com/${t.body.id}/${t.body.avatarHash}/50.png`:null,id:t.body.id,username:t.body.username,url:t.body.url}}}async getBoardsForCurrentUser(r,e={}){return{data:(await this.config.request({url:`${e.baseUrl||K}/1/members/me/boards?fields=name&filter=open`,headers:X(r.appKey,e.token||this.config.token)})).body.map(n=>({id:n.id,name:n.name}))}}async getListsForTrelloBoard(r,e={}){let{appKey:t,boardId:n}=r;return{data:(await this.config.request({url:`${e.baseUrl||K}/1/boards/${n}/lists`,headers:X(t,e.token||this.config.token)})).body}}async getAccountForId(r,e={}){let{appKey:t,memberId:n}=r,o=await this.config.request({url:`${e.baseUrl||K}/1/members/${n}`,headers:X(t,e.token||this.config.token)});return{data:Eo(o.body)}}async getAccountsForTrelloBoard(r,e={}){let{appKey:t,boardId:n}=r;return{data:(await this.config.request({url:`${e.baseUrl||K}/1/boards/${n}/members`,headers:X(t,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(r,e={}){let t=["-is:archived","sort:edited"],{appKey:n,boardId:o,filterText:i,assigneeLogins:a,labelNamesOrColors:u,trelloBoardListsById:l}=r||{};a&&t.push("@me"),u&&u.forEach(d=>t.push(`label:"${d}"`));let p=`${i?`${i}`:""}${t.join(" ")} board:${o}`;return{data:(await this.config.request({url:`${e.baseUrl||K}/1/search?query=${p}&cards_limit=${vo}&card_members=true`,headers:X(n,e.token||this.config.token)})).body.cards.map(d=>So(d,l||{}))}}async updateIssue(r,e,t,n){return await this.config.request({method:"PUT",url:`${n.baseUrl||K}/1/cards/${e.id}?${t}`,headers:X(r,n.token||this.config.token)})}async setIssueStatus(r,e={}){let{appKey:t,issue:n,status:o}=r;if(!o.id)throw new Error('Trello requires a status "id" for this function.');let i=`idList=${o.id}`;if(!(await this.updateIssue(t,n,i,e)).body.id)throw new Error("Could not set issue status")}async setIssueAssignees(r,e={}){let{appKey:t,issue:n,assignees:o}=r,i=o.map(l=>l.id),a=`idMembers=${encodeURIComponent(i.join(","))}`;if(!(await this.updateIssue(t,n,a,e)).body.id)throw new Error("Could not set issue status")}async setIssueLabels(r,e={}){let{appKey:t,issue:n,labels:o}=r,i=o.map(u=>u.id).join(",");if(!(await this.config.request({method:"PUT",url:`${e.baseUrl||K}/1/cards/${n.id}?idLabels=${encodeURIComponent(i)}`,headers:X(t,e.token||this.config.token)})).body.id)throw new Error("Could not set issue status")}async setIssueArchived(r,e={}){let{appKey:t,issue:n,archived:o}=r;if(!(await this.config.request({method:"PUT",url:`${e.baseUrl||K}/1/cards/${n.id}?closed=${o}`,headers:X(t,e.token||this.config.token)})).body.id)throw new Error("Could not update issue archived status")}async archiveIssue(r,e={}){await this.setIssueArchived({...r,archived:!0},e)}async unArchiveIssue(r,e={}){await this.setIssueArchived({...r,archived:!1},e)}async getLabelsForBoard(r,e={}){let{appKey:t,boardId:n}=r;return{data:(await this.config.request({url:`${e.baseUrl||K}/1/boards/${n}/labels`,headers:X(t,e.token||this.config.token)})).body.map(i=>({color:i.color,description:null,id:i.id,name:i.name}))}}};var lt={};z(lt,{default:()=>Co});var Co={};var pt={};z(pt,{default:()=>Do});var Do={};var wt={};z(wt,{decode:()=>Rr,decodeV0:()=>Uo,encode:()=>Lo,validate:()=>Ao});var _=(e=>(e.Zero="0",e.One="1",e))(_||{}),N=(e=>(e.PullRequest="pr",e.Issue="issue",e))(N||{}),k=(d=>(d.Azure="azure",d.AzureDevOpsServer="azureDevOpsServer",d.Github="github",d.GithubEnterprise="githubEnterprise",d.Gitlab="gitlab",d.GitlabSelfHosted="gitlabSelfHosted",d.Bitbucket="bitbucket",d.BitbucketServer="bitbucketServer",d.Jira="jira",d.JiraServer="jiraServer",d.Linear="linear",d.Trello="trello",d))(k||{});var dt=class{constructor(){}validate(r){if(!r.organizationName)throw new Error("organizationName is required");if(!r.projectId)throw new Error("projectId is required");if(!r.entityId)throw new Error("issueId is required")}encode(r){if(this.validate(r),!r.organizationName||!r.projectId||!r.entityId)throw new Error("Missing required fields for Azure DevOps issue uniqueId");let e=[];return e.push(r.provider),e.push("issue"),e.push("1"),r.provider==="azureDevOpsServer"?e.push(r.domain):e.push(""),e.push(r.organizationName),e.push(r.projectId),e.push(r.entityId),JSON.stringify(e)}decode(r){if(r.length<7)throw new Error("Invalid Azure DevOps issue uniqueId, check version");return{provider:r[0],entityType:r[1],version:r[2],domain:r[3]==""?null:r[3],resourceId:null,accountOrOrgId:null,organizationName:r[4],projectId:r[5],repoId:null,entityId:r[6]}}};var ct=class{constructor(){}validate(r){if(!r.organizationName)throw new Error("organizationName is required");if(!r.projectId)throw new Error("projectId is required");if(!r.repoId)throw new Error("repoId is required");if(!r.entityId)throw new Error("entityId is required")}encode(r){if(this.validate(r),!r.organizationName||!r.projectId||!r.repoId||!r.entityId)throw new Error("Missing required fields for Azure DevOps pull request uniqueId");let e=[];return e.push(r.provider),e.push("pr"),e.push("1"),r.provider==="azureDevOpsServer"?e.push(r.domain):e.push(""),e.push(r.organizationName),e.push(r.projectId),e.push(r.repoId),e.push(r.entityId),JSON.stringify(e)}decode(r){if(r.length<8)throw new Error("Invalid Azure DevOps pull request uniqueId, check version");return{provider:r[0],entityType:r[1],version:r[2],domain:r[3]==""?null:r[3],resourceId:null,accountOrOrgId:null,organizationName:r[4],projectId:r[5],repoId:r[6],entityId:r[7]}}};var mt=class{constructor(){}validate(r){if(!r.repoId)throw new Error("repoId is required");if(!r.entityId)throw new Error("issueId is required")}encode(r){if(this.validate(r),!r.repoId||!r.entityId)throw new Error("Missing required fields for Bitbucket DevOps issue uniqueId");let e=[];return e.push(r.provider),e.push("issue"),e.push("1"),r.provider==="bitbucketServer"?e.push(r.domain):e.push(""),e.push(r.repoId),e.push(r.entityId),JSON.stringify(e)}decode(r){if(r.length<6)throw new Error("Invalid Bitbucket DevOps issue uniqueId, check version");return{provider:r[0],entityType:r[1],version:r[2],domain:r[3]==""?null:r[3],resourceId:null,accountOrOrgId:null,organizationName:null,projectId:null,repoId:r[4],entityId:r[5]}}};var gt=class{constructor(){}validate(r){if(!r.repoId)throw new Error("repoId is required");if(!r.entityId)throw new Error("entityId is required")}encode(r){if(this.validate(r),!r.repoId||!r.entityId)throw new Error("Missing required fields for Bitbucket DevOps pull request uniqueId");let e=[];return e.push(r.provider),e.push("pr"),e.push("1"),r.provider==="bitbucketServer"?e.push(r.domain):e.push(""),e.push(r.repoId),e.push(r.entityId),JSON.stringify(e)}decode(r){if(r.length<6)throw new Error("Invalid Bitbucket DevOps pull request uniqueId, check version");return{provider:r[0],entityType:r[1],version:r[2],domain:r[3]==""?null:r[3],resourceId:null,accountOrOrgId:null,organizationName:null,projectId:null,repoId:r[4],entityId:r[5]}}};var ht=class{constructor(){}validate(r){if(!r.entityId)throw new Error("entityId is required")}encode(r){if(this.validate(r),!r.entityId)throw new Error("Missing required fields for Github issue uniqueId");let e=[];return e.push(r.provider),e.push("issue"),e.push("1"),r.provider==="githubEnterprise"?e.push(r.domain):e.push(""),e.push(r.entityId),JSON.stringify(e)}decode(r){if(r.length<5)throw new Error("Invalid Github issue uniqueId, check version");return{provider:r[0],entityType:r[1],version:r[2],domain:r[3]==""?null:r[3],resourceId:null,accountOrOrgId:null,organizationName:null,projectId:null,repoId:null,entityId:r[4]}}};var ft=class{constructor(){}validate(r){if(!r.entityId)throw new Error("entityId is required")}encode(r){if(this.validate(r),!r.entityId)throw new Error("Missing required fields for Github pull request uniqueId");let e=[];return e.push(r.provider),e.push("pr"),e.push("1"),r.provider==="githubEnterprise"?e.push(r.domain):e.push(""),e.push(r.entityId),JSON.stringify(e)}decode(r){if(r.length<5)throw new Error("Invalid Github pull request uniqueId, check version");return{provider:r[0],entityType:r[1],version:r[2],domain:r[3]==""?null:r[3],resourceId:null,accountOrOrgId:null,organizationName:null,projectId:null,repoId:null,entityId:r[4]}}};var Rt=class{constructor(){}validate(r){if(!r.entityId)throw new Error("entityId is required")}encode(r){if(this.validate(r),!r.entityId)throw new Error("Missing required fields for Gitlab issue uniqueId");let e=[];return e.push(r.provider),e.push("issue"),e.push("1"),r.provider==="gitlabSelfHosted"?e.push(r.domain):e.push(""),e.push(r.entityId),JSON.stringify(e)}decode(r){if(r.length<5)throw new Error("Invalid Gitlab issue uniqueId, check version");return{provider:r[0],entityType:r[1],version:r[2],domain:r[3]==""?null:r[3],resourceId:null,accountOrOrgId:null,organizationName:null,projectId:null,repoId:null,entityId:r[4]}}};var It=class{constructor(){}validate(r){if(!r.entityId)throw new Error("entityId is required")}encode(r){if(this.validate(r),!r.entityId)throw new Error("Missing required fields for Gitlab pull request uniqueId");let e=[];return e.push(r.provider),e.push("pr"),e.push("1"),r.provider==="gitlabSelfHosted"?e.push(r.domain):e.push(""),e.push(r.entityId),JSON.stringify(e)}decode(r){if(r.length<5)throw new Error("Invalid Gitlab pull request uniqueId, check version");return{provider:r[0],entityType:r[1],version:r[2],domain:r[3]==""?null:r[3],resourceId:null,accountOrOrgId:null,organizationName:null,projectId:null,repoId:null,entityId:r[4]}}};var bt=class{constructor(){}validate(r){if(!r.projectId)throw new Error("projectId is required");if(!r.entityId)throw new Error("entityId is required")}encode(r){if(this.validate(r),!r.projectId||!r.entityId)throw new Error("Missing required fields for Jira issue uniqueId");let e=[];return e.push(r.provider),e.push("issue"),e.push("1"),r.provider=="jira"?(e.push(""),e.push(r.resourceId)):(e.push(r.domain),e.push("")),e.push(r.projectId),e.push(r.entityId),JSON.stringify(e)}decode(r){if(r.length<7)throw new Error("Invalid Jira issue uniqueId, check version");return{provider:r[0],entityType:r[1],version:r[2],domain:r[3]==""?null:r[3],resourceId:r[4]==""?null:r[4],accountOrOrgId:null,organizationName:null,projectId:r[5],repoId:null,entityId:r[6]}}};var yt=class{constructor(){}validate(r){if(!r.accountOrOrgId)throw new Error("accountOrOrgId is required");if(!r.projectId)throw new Error("projectId is required");if(!r.entityId)throw new Error("entityId is required")}encode(r){if(this.validate(r),!r.accountOrOrgId||!r.projectId||!r.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(r.accountOrOrgId),e.push(r.projectId),e.push(r.entityId),JSON.stringify(e)}decode(r){if(r.length<7)throw new Error("Invalid Trello issue uniqueId, check version");return{provider:r[0],entityType:r[1],version:r[2],domain:r[3]==""?null:r[3],resourceId:null,accountOrOrgId:r[4],organizationName:null,projectId:r[5],repoId:null,entityId:r[6]}}};var Pt=(s,r)=>{if(r!=="issue"&&r!=="pr")throw new Error("unknown entityType");switch(s){case"azure":case"azureDevOpsServer":return r==="pr"?new ct:new dt;case"bitbucket":case"bitbucketServer":return r==="pr"?new gt:new mt;case"github":case"githubEnterprise":return r==="pr"?new ft:new ht;case"gitlab":case"gitlabSelfHosted":return r==="pr"?new It:new Rt;case"jira":case"jiraServer":if(r==="pr")throw new Error("EntityType PullRequest is not valid for Jira");return new bt;case"trello":if(r==="pr")throw new Error("EntityType PullRequest is not valid for Jira");return new yt;default:throw new Error("unknown provider")}},$o=s=>{if(!s.entityType)throw new Error("entityType is required");if(!s.provider)throw new Error("provider is required");if(!s.entityId)throw new Error("entityID is required")},Ao=s=>{if(s.version==="0"){$o(s);return}Pt(s.provider,s.entityType).validate(s)},Lo=s=>Pt(s.provider,s.entityType).encode(s),Rr=s=>{let r=JSON.parse(s);if(!r||!r.length)throw new Error("invalid issue unique id");return Pt(r[0],r[1]).decode(r)},Uo=(s,r,e)=>{if(!e)throw new Error("entityID is required");try{let t=JSON.parse(e);if(!t||!t.length)throw new Error("Invalid pull request uniqueId");let n=[s,r,"0",...t];return Pt(s,r).decode(n)}catch{return{provider:s,entityType:r,version:"0",domain:"",resourceId:null,accountOrOrgId:null,organizationName:null,projectId:null,repoId:null,entityId:e}}};var qt={};z(qt,{CHANGES_REQUESTED_ACTION_CATEGORY:()=>Ds,CHANGES_REQUESTED_BUCKET_ID:()=>vr,CONFLICTS_ACTION_CATEGORY:()=>Ss,CONFLICTS_BUCKET_ID:()=>wr,DRAFT_ACTION_CATEGORY:()=>Ls,DRAFT_BUCKET_ID:()=>Cr,FAILING_CI_ACTION_CATEGORY:()=>Es,FAILING_CI_BUCKET_ID:()=>Pr,NEEDS_MY_REVIEW_ACTION_CATEGORY:()=>Cs,NEEDS_MY_REVIEW_BUCKET_ID:()=>qr,OTHER_ACTION_CATEGORY:()=>Us,OTHER_BUCKET_ID:()=>Dr,PINNED_BUCKET_ID:()=>Ir,READY_TO_MERGE_ACTION_CATEGORY:()=>qs,READY_TO_MERGE_BUCKET_ID:()=>br,REVIEWER_COMMENTED_ACTION_CATEGORY:()=>$s,REVIEWER_COMMENTED_BUCKET_ID:()=>Er,SNOOZED_BUCKET_ID:()=>$r,UNASSIGNED_REVIEWERS_ACTION_CATEGORY:()=>vs,UNASSIGNED_REVIEWERS_BUCKET_ID:()=>yr,WAITING_FOR_REVIEW_ACTION_CATEGORY:()=>As,WAITING_FOR_REVIEW_BUCKET_ID:()=>Sr,getActionablePullRequests:()=>Ts,groupPullRequestsByAssignee:()=>Oo,groupPullRequestsByAuthor:()=>ko,groupPullRequestsByGitKrakenTeam:()=>jo,groupPullRequestsByRepo:()=>Go,groupPullRequestsByReviewer:()=>xo,groupPullRequestsByWorkspace:()=>No,groupPullRequestsIntoBuckets:()=>To});var Q=(s,r,e,t)=>({id:s,faIconName:e,name:r,priority:t,pullRequests:[]}),Ir="pinned",br="readyToMerge",yr="unassignedReviewers",Pr="failingCI",wr="conflicts",qr="needsMyReview",vr="changesRequested",Er="reviewerCommented",Sr="waitingForReview",Cr="draft",Dr="other",$r="snoozed",qs="readyToMerge",vs="unassignedReviewers",Es="failingCI",Ss="conflicts",Cs="needsMyReview",Ds="changesRequested",$s="reviewerCommented",As="waitingForReview",Ls="draft",Us="other",Ts=(s,r,e)=>s.map(t=>{let o={...t,...{suggestedActionCategory:Us,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}};r&&(o.viewer.isAuthor=t.author?.id===r.id,o.viewer.isAssignee=t.assignees?.some(u=>u.id===r.id)??!1,o.viewer.isReviewer=t.reviews?.some(u=>u.reviewer.id===r.id)??!1),o.viewer.canMerge=t.permissions?.canMerge??!0,o.hasConflicts=t.mergeableState==="CONFLICTS",o.failingCI=t.headCommit?.buildStatuses?.some(u=>u.state==="ERROR"||u.state==="FAILED")||t.mergeableState==="FAILING_CHECKS",o.commentReviewCount=t.reviews?.filter(u=>u.state==="COMMENTED").length??0,o.approvalReviewCount=t.reviews?.filter(u=>u.state==="APPROVED").length??0,o.changeRequestReviewCount=t.reviews?.filter(u=>u.state==="CHANGES_REQUESTED").length??0;let i=e?.enrichedItemsByUniqueId?.[t.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?.[t.uuid]?.count||0;return a&&(o.codeSuggestionsCount=a),(!r||o.viewer.isAuthor||o.viewer.isAssignee&&!o.viewer.isReviewer)&&o.viewer.canMerge&&!o.isDraft&&!o.failingCI&&t.mergeableState==="MERGEABLE"&&(o.viewer.shouldMerge=!0,o.suggestedActionCategory=qs),(!r||o.viewer.isAuthor)&&t.isDraft&&(o.suggestedActionCategory=Ls),(!r||o.viewer.isAuthor)&&t.reviewDecision==="REVIEW_REQUESTED"&&(o.suggestedActionCategory=As,o.viewer.waitingOnReviews=!0),(!r||o.viewer.isAuthor)&&t.reviewDecision==="COMMENTED"&&(o.suggestedActionCategory=$s),(!r||o.viewer.isAuthor)&&o.failingCI&&(o.suggestedActionCategory=Es),(!r||o.viewer.isAuthor)&&o.hasConflicts&&(o.suggestedActionCategory=Ss),(!r||o.viewer.isAuthor)&&(t.reviewDecision==="CHANGES_REQUESTED"||o.codeSuggestionsCount>0)&&(o.suggestedActionCategory=Ds),(!r||o.viewer.isAuthor)&&!t.reviews?.length&&(o.suggestedActionCategory=vs,o.viewer.shouldAssignReviewer=!0),r&&t.reviews?.some(u=>u.reviewer.id===r.id&&u.state==="REVIEW_REQUESTED")&&(o.suggestedActionCategory=Cs,o.viewer.shouldReview=!0),o}),To=(s,r,e)=>{let t={pinned:Q(Ir,"Pinned","thumbtack",e?.bucketPriorityOverride?.pinned??-1),readyToMerge:Q(br,"Ready to Merge","code-merge",e?.bucketPriorityOverride?.readyToMerge??0),unassignedReviewers:Q(yr,"Unassigned Reviewers","user-plus",e?.bucketPriorityOverride?.unassignedReviewers??1),failingCI:Q(Pr,"Failing CI","circle-x",e?.bucketPriorityOverride?.failingCI??2),conflicts:Q(wr,"Resolve Conflicts","triangle-exclamation",e?.bucketPriorityOverride?.conflicts??3),needsMyReview:Q(qr,"Needs My Review","eye",e?.bucketPriorityOverride?.needsMyReview??4),changesRequested:Q(vr,"Suggested Changes","file-plus",e?.bucketPriorityOverride?.changesRequested??5),reviewerCommented:Q(Er,"Reviewer Commented","comment",e?.bucketPriorityOverride?.reviewerCommented??6),waitingForReview:Q(Sr,"Waiting for Review","circle-pause",e?.bucketPriorityOverride?.waitingForReview??7),draft:Q(Cr,"Draft","compass-drafting",e?.bucketPriorityOverride?.draft??8),other:Q(Dr,"Other","ellipsis",e?.bucketPriorityOverride?.other??9),snoozed:Q($r,"Snoozed","snooze",e?.bucketPriorityOverride?.snoozed??10)},o=Ts(s,r,e).reduce((i,a)=>(i[a.uuid]=a,i),{});return s.forEach(i=>{let a=o[i.uuid],u=!0;if(a.viewer.snoozed){t[$r].pullRequests.push(i);return}a.viewer.pinned&&t[Ir].pullRequests.push(i),(!r||a.viewer.isAuthor||a.viewer.isAssignee&&!a.viewer.isReviewer)&&!a.isDraft&&a.viewer.canMerge&&a.mergeableState==="MERGEABLE"&&(t[br].pullRequests.push(i),u=!1),a.viewer.shouldAssignReviewer&&(t[yr].pullRequests.push(i),u=!1),(!r||a.viewer.isAuthor)&&a.failingCI&&(t[Pr].pullRequests.push(i),u=!1),(!r||a.viewer.isAuthor)&&a.hasConflicts&&(t[wr].pullRequests.push(i),u=!1),a.viewer.shouldReview&&(t[qr].pullRequests.push(i),u=!1),(!r||a.viewer.isAuthor)&&(a.reviewDecision==="CHANGES_REQUESTED"||a.codeSuggestionsCount>0)&&(t[vr].pullRequests.push(i),u=!1),(!r||a.viewer.isAuthor)&&a.reviewDecision==="COMMENTED"&&(t[Er].pullRequests.push(i),u=!1),(!r||a.viewer.isAuthor)&&a.reviewDecision==="REVIEW_REQUESTED"&&(t[Sr].pullRequests.push(i),u=!1),a.isDraft&&(t[Cr].pullRequests.push(i),u=!1),u&&t[Dr].pullRequests.push(i)}),Object.values(t).forEach(i=>{i.pullRequests.sort((a,u)=>o[a.uuid].priority-o[u.uuid].priority)}),t},Go=s=>{let r={};return s.forEach(e=>{let t=e.repository.id;r[t]?r[t].pullRequests.push(e):r[t]={name:e.repository.name,priority:0,pullRequests:[e],id:t}}),ue(r)},Oo=s=>{let r="internal-no-assignees",e={[r]:{name:"No assignees",priority:-1,pullRequests:[],id:r,faIconName:"user-slash"}};return s.forEach(t=>{t.assignees&&t.assignees.length?t.assignees.forEach(n=>{let o=n.id;e[o]?e[o].pullRequests.push(t):e[o]={accountData:n,name:Te(n,`Unknown Assignee ${Object.keys(e).length}`),priority:0,pullRequests:[t],id:o}}):e[r].pullRequests.push(t)}),ue(e)},ko=s=>{let r="internal-no-author",e={[r]:{name:"No author",priority:-1,pullRequests:[],id:r,faIconName:"user-slash"}};return s.forEach(t=>{if(t.author){let n=t.author.id;e[n]?e[n].pullRequests.push(t):e[n]={accountData:t.author,name:Te(t.author,`Unknown Author ${Object.keys(e).length}`),priority:0,pullRequests:[t],id:n}}else e[r].pullRequests.push(t)}),ue(e)},xo=s=>{let r="internal-no-reviewer",e={[r]:{name:"No reviewers",priority:-1,pullRequests:[],id:r,faIconName:"user-slash"}};return s.forEach(t=>{t.reviews&&t.reviews.length?t.reviews.forEach(n=>{let o=n.reviewer.id;e[o]?e[o].pullRequests.push(t):e[o]={accountData:n.reviewer,name:Te(n.reviewer,`Unknown Reviewer ${Object.keys(e).length}`),priority:0,pullRequests:[t],id:o}}):e[r].pullRequests.push(t)}),ue(e)},_o=s=>s.azureProject?[`${s.azureProject}-${s.azureOrganizationId}`]:s.providerData?.repositories.nodes.map(r=>`${s.provider}-${r.repositoryId}`)??[],No=(s,r)=>{let e="internal-no-workspace",t={[e]:{name:"No workspace",priority:-1,pullRequests:[],id:e,faIconName:"folder-xmark"}};if(r.length){let n=r.reduce((o,i)=>(_o(i).forEach(u=>{o[u]?o[u].push(i):o[u]=[i]}),o),{});s.forEach(o=>{let{provider:i}=Rr(o.uuid),a=i==="github"?o.repository.graphQLId:o.repository.id,u=i==="azure"?[`${i}-${a}`,`${o.repository.project}-${o.repository.owner.login}`]:[`${i}-${a}`],l=!1,p=u.reduce((c,d)=>n[d]?c.concat(n[d]):c,[]);p?.length&&p.forEach(c=>{l=!0;let d=c.id;t[d]?t[d].pullRequests.push(o):t[d]={name:c.name,priority:0,pullRequests:[o],id:d,faIconName:"folder"}}),l||t[e].pullRequests.push(o)})}else t[e].pullRequests=s;return ue(t)},jo=(s,r,e,t)=>{let n="internal-no-team",o={[n]:{name:"No team",priority:-1,pullRequests:[],id:n}};return t.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)),t.forEach(l=>{if(l.members?.some(c=>{let d=r[c.id]?.[e]?.providerID;return d&&u.has(d)})){a=!0;let c=l.id;o[c]?o[c].pullRequests.push(i):o[c]={name:l.name,priority:0,pullRequests:[i],id:c,teamData:l}}}),a||o[n].pullRequests.push(i)}):o[n].pullRequests=s,ue(o)};var vt={};z(vt,{getPullRequestRank:()=>Bo});var Bo=(s,r,e)=>{let t=0,n,o;return s.reviews?.forEach(i=>{i.reviewer.id===r&&(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===r?t+=1e3:s.assignees?.find(i=>i.id===r)?t+=900:n==="REVIEW_REQUESTED"?t+=800:e&&(t+=700),o==="APPROVED"?s.mergeableState==="MERGEABLE"?t+=100:s.mergeableState==="CONFLICTS"?t+=90:t+=80:o=="CHANGES_REQUESTED"&&(t+=70),t};var Et={};z(Et,{default:()=>Qo});var Qo={};var St={};z(St,{default:()=>Fo});var Fo={};var Ct={};z(Ct,{default:()=>Mo});var Mo={};var Gs=s=>{let r={request:s?.request};return{azureDevOps:new me({...r,...s?.azureDevOps}),bitbucket:new ge({...r,...s?.bitbucket}),bitbucketServer:new he({...r,...s?.bitbucketServer}),github:new fe({...r,...s?.github}),gitlab:new Ie({...r,...s?.gitlab}),jira:new be({...r,...s?.jira}),jiraServer:new ye({...r,...s?.jiraServer}),linear:new Pe({...r,...s?.linear}),trello:new we({...r,...s?.trello})}};var Os=(i=>(i.Conflicts="conflicts",i.Failure="failure",i.NotSet="notSet",i.Queued="queued",i.RejectedByPolicy="rejectedByPolicy",i.Succeeded="succeeded",i))(Os||{});var ks=(e=>(e.Completed="COMPLETED",e.NotPlanned="NOT_PLANNED",e))(ks||{});var zo=Gs;var Wo={azureDevOps:lt,bitbucket:pt,bitbucketServer:_e,github:vt,gitlab:Et,gitProvider:qt,jira:St,trello:Ct,entityIdentifier:wt};
|
|
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",Yo=1e3,Y=(s,t)=>({...R(t),Authorization:`OAuth oauth_consumer_key="${s}", oauth_token="${t}"`}),ei=s=>({id:s.id,username:s.username,url:s.url,name:s.fullName,email:s.email,avatarUrl:s.avatarUrl}),ti=(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:ei(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=${Yo}&card_members=true`,headers:Y(n,e.token||this.config.token)})).body.cards.map(c=>ti(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:()=>ri});var ri={};var ft={};H(ft,{default:()=>si});var si={};var Dt={};H(Dt,{decode:()=>vr,decodeV0:()=>ai,encode:()=>ii,validate:()=>oi});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")}},ni=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")},oi=s=>{if(s.version==="0"){ni(s);return}Ct(s.provider,s.entityType).validate(s)},ii=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)},ai=(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:()=>Ur,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:()=>Gr,getActionablePullRequests:()=>en,groupPullRequestsByAssignee:()=>pi,groupPullRequestsByAuthor:()=>di,groupPullRequestsByGitKrakenTeam:()=>hi,groupPullRequestsByRepo:()=>li,groupPullRequestsByReviewer:()=>ci,groupPullRequestsByWorkspace:()=>gi,groupPullRequestsIntoBuckets:()=>ui});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",Ur="reviewerCommented",Gr="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}),ui=(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(Ur,"Reviewer Commented","comment",e?.bucketPriorityOverride?.reviewerCommented??6),waitingForReview:z(Gr,"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[Ur].pullRequests.push(i),u=!1),(!t||a.viewer.isAuthor)&&a.reviewDecision==="REVIEW_REQUESTED"&&(r[Gr].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},li=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)},pi=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)},di=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)},ci=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)},mi=s=>s.azureProject?[`${s.azureProject}-${s.azureOrganizationId}`]:s.providerData?.repositories.nodes.map(t=>`${s.provider}-${t.repositoryId}`)??[],gi=(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)=>(mi(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)},hi=(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:()=>fi});var fi=(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:()=>Ri});var Ri={};var Ut={};H(Ut,{default:()=>Ii});var Ii={};var Gt={};H(Gt,{default:()=>bi});var bi={};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 yi=tn;var Pi={azureDevOps:ht,bitbucket:ft,bitbucketServer:We,github:$t,gitlab:Lt,gitProvider:At,jira:Ut,trello:Gt,entityIdentifier:Dt};
|