@gitkraken/provider-apis 0.48.0 → 0.49.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/dist/index.providers.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
"use strict";var rt=Object.defineProperty;var Wr=Object.getOwnPropertyDescriptor;var Jr=Object.getOwnPropertyNames;var Vr=Object.prototype.hasOwnProperty;var Kr=(s,n)=>{for(var e in n)rt(s,e,{get:n[e],enumerable:!0})},Xr=(s,n,e,t)=>{if(n&&typeof n=="object"||typeof n=="function")for(let r of Jr(n))!Vr.call(s,r)&&r!==e&&rt(s,r,{get:()=>n[r],enumerable:!(t=Wr(n,r))||t.enumerable});return s};var Zr=s=>Xr(rt({},"__esModule",{value:!0}),s);var Gn={};Kr(Gn,{AzureDevOps:()=>ae,Bitbucket:()=>ue,BitbucketServer:()=>le,EntityIdentifierProviderType:()=>jr,EntityType:()=>Fr,EntityVersion:()=>Nr,GitBuildStatusStage:()=>Mt,GitBuildStatusState:()=>ve,GitDiffLineType:()=>st,GitHub:()=>pe,GitHubIssueCloseReason:()=>Qr,GitIssueState:()=>Le,GitLab:()=>ce,GitMergeStrategy:()=>ie,GitPullRequestMergeableState:()=>re,GitPullRequestReviewState:()=>K,GitPullRequestState:()=>te,GraphQLErrors:()=>R,Jira:()=>me,JiraServer:()=>ge,PullRequestAsyncStatus:()=>kr,Trello:()=>he,default:()=>An,isFetch:()=>Se});module.exports=Zr(Gn);var Yt=require("diff");var Mt=(r=>(r.Build="build",r.Production="production",r.Staging="staging",r.Test="test",r))(Mt||{}),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||{}),ie=(o=>(o.MergeCommit="MERGE_COMMIT",o.Rebase="REBASE",o.RebaseThenMergeCommit="REBASE_THEN_MERGE_COMMIT",o.FastForward="FAST_FORWARD",o.Squash="SQUASH",o))(ie||{}),te=(t=>(t.Open="OPEN",t.Closed="CLOSED",t.Merged="MERGED",t))(te||{}),K=(r=>(r.Approved="APPROVED",r.ChangesRequested="CHANGES_REQUESTED",r.Commented="COMMENTED",r.ReviewRequested="REVIEW_REQUESTED",r))(K||{}),re=(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))(re||{}),st=(t=>(t.ADDED="ADDED",t.DELETED="DELETED",t.UNMODIFIED="UNMODIFIED",t))(st||{});var zt={APPROVED:0,COMMENTED:1,REVIEW_REQUESTED:2,CHANGES_REQUESTED:3},j=s=>!s||s.length===0?null:s.reduce((n,e)=>zt[e.state]>zt[n]?e.state:n,"APPROVED");var nt=(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))(nt||{});var D=100;var Ht=globalThis.fetch;var Yr=async s=>{let n=s.headers.get("content-type")||"",e=null;if(n.startsWith("application/json")){let o=await s.text();e=o.trim().length>0?JSON.parse(o):null}else if(n.startsWith("text/")||n===""||n.startsWith("application/vnd.github.diff")||n.startsWith("application/vnd.github.patch"))e=await s.text();else if(n.startsWith("application/vnd.github.raw+json")||n.startsWith("application/octet-stream"))e=await s.arrayBuffer();else throw new Error(`Unsupported content-type: ${n}`);let t={};s.headers.forEach((o,i)=>{t[i]=o});let r={body:e,headers:t,status:s.status,statusText:s.statusText};if(!s.ok){let o=new Error(s.statusText);throw Object.assign(o,{response:r}),o}return r},ot=s=>async({url:n,...e})=>{let t=await s(n,e);return Yr(t)};var Se=(s,n=!1)=>s.name==="fetch"||n;var N=class{constructor(n){let e=n?.request||Ht;this.config={...n,request:Se(e,n?.forceIsFetch)?ot(e):e}}updateConfig(n){this.config={...this.config,...n,request:n.request&&Se(n.request,n?.forceIsFetch??this.config.forceIsFetch)?ot(n.request):this.config.request}}},_=class extends N{};var f=(s,n)=>{let e={};return s&&(e.Authorization=`${n?"Basic":"Bearer"} ${s}`),e},Wt=s=>s?s.reduce((n,e)=>(n[e]=!0,n),{}):void 0,X=(s,n,e)=>!s||n.some(t=>s[t])?e:"",Jt=async s=>{let n=[],e=!0,t;for(;e;){let r=await s(t);n=n.concat(r.data),e=!!r?.pageInfo?.hasNextPage,t=r?.pageInfo?.endCursor||r?.pageInfo?.nextPage}return n};async function it(s){return(await Promise.allSettled(s)).map(e=>es(e)).filter(e=>e!=null)}function es(s,n=void 0){return s?.status==="fulfilled"?s.value:n}var ts="https://app.vssps.visualstudio.com/_apis",rs="https://vssps.dev.azure.com/",ss="https://dev.azure.com",w=(s,n={})=>f(n.token||s.token,n.isPAT||s.isPAT),Vt=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/"),at=(s,n)=>{let e=n.baseUrl||s.baseUrl||ts;return e=e.replace(/\/$/,""),e},C=(s,n)=>{let e=n.baseUrl||s.baseUrl||ss;return e=e.replace(/\/$/,""),e},ut=(s,n)=>{let e=n.baseUrl||s.baseUrl||rs;return e=e.replace(/\/$/,""),e};var ns={active:"OPEN",completed:"MERGED",abandoned:"CLOSED"},os=s=>{if(typeof s!="string")return s;let n=s.charAt(0).toUpperCase()+s.slice(1);return nt[n]??0},is=new Set([2,3,4,5]),as={10:"APPROVED",5:"APPROVED",0:"REVIEW_REQUESTED",[-5]:"CHANGES_REQUESTED",[-10]:"CHANGES_REQUESTED"},se=s=>({id:s.id,name:s.displayName??null,username:(s.uniqueName||s.displayName)??null,email:null,avatarUrl:s.imageUrl??null,url:null}),Ee=s=>s.startsWith("refs/heads/")?s.replace("refs/heads/",""):s,us=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"}},lt=(s,n,e,t,r,o)=>`${s}|${n}|${e}|${t}|${r}|${o}`,Kt=s=>{let n=s.split("|");if(n.length!==6)throw new Error("Invalid Azure comment ID format");return{namespace:n[0],project:n[1],repoName:n[2],prId:n[3],threadId:n[4],commentId:n[5]}},Xt=(s,n,e,t,r)=>`${s}|${n}|${e}|${t}|${r}`,pt=s=>{let n=s.split("|");if(n.length!==5)throw new Error("Invalid Azure thread ID format");return{namespace:n[0],project:n[1],repoName:n[2],prId:n[3],threadId:n[4]}},Re=(s,n)=>{let e=[],t=[];return n.reviewers.forEach(r=>{let o={reviewer:se(r),state:as[r.vote??0]||"REVIEW_REQUESTED"};r.isRequired&&e.push(o),t.push(o)}),{id:n.pullRequestId.toString(),title:n.title,description:n.description??null,number:n.codeReviewId,state:ns[n.status],isDraft:n.isDraft,commentCount:null,upvoteCount:null,author:se(n.createdBy),createdDate:new Date(n.creationDate),updatedDate:new Date(n.closedDate||n.creationDate),closedDate:n.closedDate?new Date(n.closedDate):null,mergedDate:n.closedDate&&n.status==="completed"?new Date(n.closedDate):null,repository:{id:n.repository.id,name:n.repository.name,project:n.repository.project.name,owner:{login:s},remoteInfo:null},headCommit:{buildStatuses:null},baseRef:{name:Ee(n.targetRefName),oid:n.lastMergeTargetCommit.commitId},headRef:{name:Ee(n.sourceRefName),oid:n.lastMergeSourceCommit.commitId},url:Vt(n),assignees:n.reviewers.map(se),reviews:t,reviewDecision:j(e),additions:null,deletions:null,fileCount:null,commitCount:null,headRepository:n.forkSource?{id:n.forkSource.repository.id,name:n.forkSource.repository.name,project:void 0,owner:{login:s},remoteInfo:null}:{id:n.repository.id,name:n.repository.name,project:n.repository.project.name,owner:{login:s},remoteInfo:null},mergeableState:us(n.mergeStatus),labels:n.labels?.map(r=>({color:null,description:null,id:r.id,name:r.name}))??[],permissions:null}},Zt=(s,n)=>({id:n.id,name:n.name,namespace:s,project:n.project.name,projectId:n.project.id,webUrl:n.webUrl,httpsUrl:n.remoteUrl,sshUrl:n.sshUrl,defaultBranch:n.defaultBranch?{name:Ee(n.defaultBranch)}:null,permissions:null}),ls=(s,n,e,t)=>{let r=e.fields,o=r["System.AssignedTo"],i=r["System.State"],a=r["System.WorkItemType"],u;return i&&a&&(u=t[a]?.[i]),{id:e.id.toString(),number:e.id.toString(),title:r["System.Title"],commentCount:r["System.CommentCount"],author:{avatarUrl:r["System.CreatedBy"]._links?.avatar?.href??null,email:null,id:r["System.CreatedBy"].id,name:r["System.CreatedBy"].uniqueName??null,username:r["System.CreatedBy"].displayName??null,url:null},closedDate:r["Microsoft.VSTS.Common.ClosedDate"]?new Date(r["Microsoft.VSTS.Common.ClosedDate"]):null,createdDate:new Date(r["System.CreatedDate"]),updatedDate:new Date(r["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:r["System.Description"]??null,state:{name:u?.title||i,color:null},type:r["System.WorkItemType"],repository:null,project:{namespace:s,name:n,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()}))??[]}},ae=class extends _{constructor(){super(...arguments);this.cachedUserIds=new Map;this.inflightUserIds=new Map}getCurrentUserId(e,t){let r=JSON.stringify([e,t.token??null,t.isPAT??this.config.isPAT??!1,t.baseUrl??null]),o=this.cachedUserIds.get(r);if(o)return Promise.resolve(o);let i=this.inflightUserIds.get(r);if(i)return i;let a=this.fetchCurrentUserId(e,t,r);return this.inflightUserIds.set(r,a),a}async fetchCurrentUserId(e,t,r){try{let o=await this.getCurrentUserForInstance({namespace:e},t);return this.cachedUserIds.set(r,o.data.id),o.data.id}finally{this.inflightUserIds.delete(r)}}getRepoApiUrl(e,t,r,o){return`${C(this.config,o)}/${encodeURIComponent(e)}/${encodeURIComponent(t)}/_apis/git/repositories/${encodeURIComponent(r)}`}async getCurrentUser(e={},t={}){if(t.isPAT||this.config.isPAT)throw new Error("Azure DevOps does not support PATs for this function.");let r=`${at(this.config,t)}/profile/profiles/me`,o=await this.config.request({url:r,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 r=`${at(this.config,t)}/accounts?memberId=${e.userId}&api-version=6.0`;return{data:(await this.config.request({url:r,headers:w(this.config,t)})).body.value.map(i=>({id:i.accountId,name:i.accountName}))}}async getCollectionsForUser(e,t={}){let r=`${C(this.config,t)}/_apis/projectCollections`;return{data:(await this.config.request({url:r,headers:w(this.config,t)})).body.value.map(i=>({id:i.id,name:i.name}))}}async getAzureProjects(e,t={}){let r=new URL(`${C(this.config,t)}/${encodeURIComponent(e.namespace)}/_apis/projects`);r.searchParams.set("$top",D.toString()),e.cursor&&r.searchParams.set("$skip",e.cursor);let o=await this.config.request({url:r.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:r,projectId:o}=e;return{data:{scope:(await this.config.request({url:`${ut(this.config,t)}/${encodeURIComponent(r)}/_apis/graph/descriptors/${o}?api-version=6.0`,headers:w(this.config,t)})).body.value}}}async getAzureGraphAccountsForAzureProject(e,t={}){let{namespace:r,projectScopeDescriptor:o,cursor:i}=e,a=new URL(`${ut(this.config,t)}/${encodeURIComponent(r)}/_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:r}=e;if(!r.storageKeyURL)throw new Error("Expected 'storageKeyURL' to not be null for 'azureGraphAccount'");let o=await this.config.request({url:r.storageKeyURL,headers:w(this.config,t)});return{data:{avatarUrl:r.avatarUrl,email:r.email,id:o.body.value,name:r.name,username:r.username,url:null}}}async getAccountsFromAzureGraphAccounts(e,t={}){let r=[];for(let o of e.azureGraphAccounts){let i=await this.getAccountFromAzureGraphAccount({azureGraphAccount:o},t);r.push(i.data)}return{data:r}}async getRepo(e,t={}){if(!e.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let r=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:Zt(e.namespace,r.body)}}async getRepos(e,t={}){let r=[],o=[];return await Promise.all(e.map(async i=>{try{let a=await this.getRepo(i,t);r.push(a.data)}catch(a){o.push({input:i,error:a})}})),{data:r,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=>Zt(e.namespace,o))}}async getRefs(e,t,r={}){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,r)}/${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",D.toString()),t.cursor&&o.searchParams.set("continuationToken",t.cursor);let i=await this.config.request({url:o.toString(),headers:w(this.config,r)}),a=i.headers["x-ms-continuationtoken"];return{pageInfo:{hasNextPage:!!a,endCursor:a||null},data:i.body.value.map(u=>({name:Ee(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={},r=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=${r}&%24skip=${(l-1)*r}`,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=>Re(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:r}=e||{},o=[];return await Promise.all(r.map(async i=>{try{(await this.getPullRequestsForRepoBase({repo:i,...e},t)).body.value.forEach(u=>{o.push(Re(i.namespace,u))})}catch(a){if(a.statusCode!==404&&a.statusCode!==401)throw a}})),{data:o}}async getPullRequestsForProjectBase(e,t={},r=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",r.toString()),d.searchParams.set("$skip",((c-1)*r).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=>Re(e.namespace,a))||[]}}async getPullRequestsForProjects(e,t={}){let{projects:r}=e||{},o=[];return await Promise.all(r.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(Re(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:r,project:o,name:i},pullRequestId:a}=e,u=await this.config.request({url:`${C(this.config,t)}/${encodeURIComponent(r)}/${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,r){return await this.config.request({method:"PATCH",url:`${C(this.config,r)}/${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,r),"Content-Type":"application/json"}})}async closePullRequest(e,t={}){let{pullRequest:r}=e,o={status:"abandoned"};if(!(await this.updatePullRequest(r,JSON.stringify(o),t)).body.status)throw new Error("Could not close pull request")}async mergePullRequest(e,t={}){let{pullRequest:r,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:r.headRef?.oid},status:"completed"};if(!(await this.updatePullRequest(r,JSON.stringify(a),t)).body.status)throw new Error("Could not merge pull request")}async addPullRequestLabel(e,t={}){let{pullRequest:r,label:o}=e;if(!r.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(r.repository.owner.login)}/${encodeURIComponent(r.repository.project)}/_apis/git/repositories/${r.repository.name}/pullrequests/${r.id}/labels?api-version=6.0`,body:JSON.stringify(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:r,label:o}=e;if(!r.repository.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');await this.config.request({method:"DELETE",url:`${C(this.config,t)}/${encodeURIComponent(r.repository.owner.login)}/${encodeURIComponent(r.repository.project)}/_apis/git/repositories/${r.repository.name}/pullrequests/${r.id}/labels/${encodeURIComponent(o.name)}?api-version=6.0`,headers:{...w(this.config,t)}})}async setPullRequestLabels(e,t={}){let{pullRequest:r,labels:o}=e;if(!r.repository.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let i=r.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:r,label:a},t);for(let a of i)o.find(u=>a.id===u.id)||await this.removePullRequestLabel({pullRequest:r,label:a},t)}async setPullRequestAsDraft(e,t={}){let{pullRequest:r,isDraft:o}=e,i={isDraft:o};if(!(await this.updatePullRequest(r,JSON.stringify(i),t)).body.status)throw new Error("Could not set the pull request as draft")}async addPullRequestReviewer(e,t={}){let{pullRequest:r,reviewer:o,isRequired:i}=e,a={id:o.id,isRequired:i};if(!(await this.config.request({method:"PUT",url:`${C(this.config,t)}/${encodeURIComponent(r.repository.owner.login)}/${encodeURIComponent(r.repository.project)}/_apis/git/repositories/${r.repository.name}/pullrequests/${r.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:r,reviewer:o}=e;await this.config.request({method:"DELETE",url:`${C(this.config,t)}/${encodeURIComponent(r.repository.owner.login)}/${encodeURIComponent(r.repository.project)}/_apis/git/repositories/${r.repository.name}/pullrequests/${r.id}/reviewers/${o.id}?api-version=6.0`,headers:{...w(this.config,t),Accept:"application/json"}})}async setPullRequestReviewers(e,t={}){let{pullRequest:r,reviewers:o}=e;for(let i of o)r.assignees.find(a=>a.id===i.id)||await this.addPullRequestReviewer({pullRequest:r,reviewer:i,isRequired:!0},t);for(let i of r.assignees)o.find(a=>i.id===a.id)||await this.removePullRequestReviewer({pullRequest:r,reviewer:i},t)}async getIssuesForAzureProject(e,t={}){let{page:r,assigneeLogins:o,authorLogin:i,mentionLogin:a,labelNames:u,statusByWorkItemIdByStatusId:l}=e||{},p=r||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=>ls(e.namespace,e.project,h,l||{}))}}async getPermissionsForRepos(e,t={}){let{namespace:r,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(r)}/_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:r,repos:o}=e,i=await this.getPermissionsForRepos({namespace:r,repos:o},t);return{data:o.map(a=>({...a,permissions:i.data[`${a.projectId}/${a.id}`]}))}}async updateIssue(e,t,r={}){return await this.config.request({method:"PATCH",url:`${C(this.config,r)}/${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,r),"Content-Type":"application/json-patch+json"}})}async setIssueStatus(e,t={}){let{issue:r,status:o}=e,i=[{op:"add",path:"/fields/System.State",value:o.name}];if(!(await this.updateIssue(r,i,t)).body.fields?.["System.State"])throw new Error("Could not set issue status")}async setIssueAssignee(e,t={}){let{issue:r,assignee:o}=e,i=[{op:"add",path:"/fields/System.AssignedTo",value:o?.name??""}];if(!(await this.updateIssue(r,i,t)).body.fields?.["System.State"])throw new Error("Could not set issue assignee")}async setIssueLabels(e,t={}){let{issue:r,labels:o}=e,a=[{op:"replace",path:"/fields/System.Tags",value:o.map(l=>l.name).join(";")}];if(!(await this.updateIssue(r,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:r,project:o}=e;return{data:(await this.config.request({url:`${C(this.config,t)}/${encodeURIComponent(r)}/${encodeURIComponent(o||"")}/_apis/wit/workitemtypes?api-version=6.0`,headers:{...w(this.config,t)}})).body.value}}async getLabelsForProject(e,t={}){let{namespace:r,project:o}=e;return{data:(await this.config.request({url:`${C(this.config,t)}/${encodeURIComponent(r)}/${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:r,number:o}=e;if(!r.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let i=await this.config.request({url:`${this.getRepoApiUrl(r.namespace,r.project,r.name,t)}/pullrequests/${o}?api-version=7.1`,headers:w(this.config,t)});return{data:Re(r.namespace,i.body)}}async getPullRequestDescription(e,t={}){let{repo:r,number:o}=e;if(!r.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(r.namespace,r.project,r.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:r,number:o,description:i}=e;if(!r.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(r.namespace,r.project,r.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 r=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(!r.body.value?.length)throw new Error("No merge base found between the specified commits.");return{data:r.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 r=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([r.body])}}async getPullRequestDiff(e,t={}){if(!e.repo.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let r=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:`${r}/pullrequests/${e.pullRequestId}?api-version=7.1`,headers:o}),this.config.request({url:`${r}/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 S=(await this.config.request({url:`${r}/pullrequests/${e.pullRequestId}/iterations/${d.id}/changes?api-version=7.1&$top=${g}&$skip=${I}`,headers:o})).body.changeEntries??[];if(S.length===0||(m.push(...S),S.length<g))break;I+=S.length}if(m.length===0)return"";let y=5,h=[],v=new TextDecoder,$=P=>P instanceof ArrayBuffer?v.decode(P):typeof P=="string"?P:"",x=async(P,S)=>{try{let Y=await this.config.request({url:`${r}/items?path=${encodeURIComponent(P)}&versionDescriptor[version]=${encodeURIComponent(S)}&versionDescriptor[versionType]=commit&includeContent=true&api-version=7.1`,headers:i});return $(Y.body)}catch{return""}},E=P=>{if(typeof P=="number")return{add:(P&1)!==0,rename:(P&8)!==0,delete:(P&16)!==0};let S=P.toLowerCase().split(",").map(Y=>Y.trim());return{add:S.includes("add"),rename:S.includes("rename"),delete:S.includes("delete")}};for(let P=0;P<m.length;P+=y){let S=m.slice(P,P+y),Y=await Promise.all(S.map(async ne=>{let{add:oe,rename:tt,delete:ee}=E(ne.changeType),fe=ne.originalPath??ne.item.originalPath,A=ne.item.path,qe=ee?A??fe??"":A??"",Bt=tt||ee?fe??qe:qe,[Br,Mr]=await Promise.all([oe?Promise.resolve(""):x(Bt,l),ee?Promise.resolve(""):x(qe,p)]),zr=oe?"/dev/null":`a${Bt}`,Hr=ee?"/dev/null":`b${qe}`;return(0,Yt.createTwoFilesPatch)(zr,Hr,Br,Mr)}));h.push(...Y)}return h.join(`
|
|
2
|
-
`)}getPullRequestWriteHeaders(e){return{...w(this.config,e),"Content-Type":"application/json"}}setReviewerVote(e,t,r,o,i){return this.config.request({method:"PUT",url:`${e}/pullRequests/${t}/reviewers/${encodeURIComponent(r)}?api-version=7.1`,headers:this.getPullRequestWriteHeaders(i),body:JSON.stringify({vote:o})})}postPullRequestThread(e,t,r,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:r,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 r=this.getRepoApiUrl(e.repo.namespace,e.repo.project,e.repo.name,t),o=w(this.config,t),i=await this.config.request({url:`${r}/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:lt(e.repo.namespace,e.repo.project,e.repo.name,e.pullRequestNumber,u.id,l.id),author:l.author?se(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 r=this.getRepoApiUrl(e.pullRequest.repository.owner.login,e.pullRequest.repository.project,e.pullRequest.repository.name,t);await this.postPullRequestThread(r,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 r=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=pt(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:`${r}/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:`${r}/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 lt(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:`${r}/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 Xt(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 r=Kt(e.commentId),o=this.getRepoApiUrl(r.namespace,r.project,r.repoName,t);await this.config.request({method:"PATCH",url:`${o}/pullRequests/${r.prId}/threads/${r.threadId}/comments/${r.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 r=Kt(e.commentId),o=this.getRepoApiUrl(r.namespace,r.project,r.repoName,t);await this.config.request({method:"DELETE",url:`${o}/pullRequests/${r.prId}/threads/${r.threadId}/comments/${r.commentId}?api-version=7.1`,headers:w(this.config,t)})}async deleteInlineComment(e,t={}){return this.deleteComment(e,t)}async resolveReviewThread(e,t={}){let r=pt(e.threadId),o=this.getRepoApiUrl(r.namespace,r.project,r.repoName,t);await this.config.request({method:"PATCH",url:`${o}/pullRequests/${r.prId}/threads/${r.threadId}?api-version=7.1`,headers:this.getPullRequestWriteHeaders(t),body:JSON.stringify({status:2})})}async unresolveReviewThread(e,t={}){let r=pt(e.threadId),o=this.getRepoApiUrl(r.namespace,r.project,r.repoName,t);await this.config.request({method:"PATCH",url:`${o}/pullRequests/${r.prId}/threads/${r.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 r=e.pullRequest.repository.owner.login,o=this.getRepoApiUrl(r,e.pullRequest.repository.project,e.pullRequest.repository.name,t),i=await this.getCurrentUserId(r,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 r=e.pullRequest.repository.owner.login,o=this.getRepoApiUrl(r,e.pullRequest.repository.project,e.pullRequest.repository.name,t),i=await this.getCurrentUserId(r,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 r=this.getRepoApiUrl(e.pullRequest.repository.owner.login,e.pullRequest.repository.project,e.pullRequest.repository.name,t);await this.postPullRequestThread(r,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:r,project:o,name:i}=e.repo,{pullRequestId:a}=e,u=this.getRepoApiUrl(r,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)=>lt(r,o,i,a,h,v),g=h=>Xt(r,o,i,a,h),m=new Map;for(let h of c.body.value){if(h.isDeleted)continue;let v=h.comments.filter(A=>!A.isDeleted&&A.commentType!=="system"),$=v.find(A=>A.parentCommentId===0)??v[0];if(!$)continue;let x=$.author?.id;if(!x)continue;let E=v.filter(A=>A.id!==$.id),P=h.threadContext,S=P?.rightFileStart?{side:"RIGHT",start:P.rightFileStart,end:P.rightFileEnd}:P?.leftFileStart?{side:"LEFT",start:P.leftFileStart,end:P.leftFileEnd}:null,Y=S?.end?.line??S?.start.line??null,ne=S?.start&&S.end&&S.start.line!==S.end.line?S.start.line:null,oe=P?.filePath??"",tt=oe.startsWith("/")?oe.slice(1):oe,ee={id:d(h.id,$.id),author:$.author?se($.author):null,body:$.content??"",createdAt:$.publishedDate?new Date($.publishedDate):null,url:"",diffLines:[],filename:tt,replies:E.map(A=>({id:d(h.id,A.id),author:A.author?se(A.author):null,body:A.content??"",createdAt:A.publishedDate?new Date(A.publishedDate):null,url:""})),isOutdated:!1,isResolved:is.has(os(h.status)),line:Y,startLine:ne,side:S?.side??null,threadId:g(h.id)},fe=m.get(x);fe?fe.push(ee):m.set(x,[ee])}let I=[],y=new Set;for(let h of p.body.value){if(h.hasDeclined)continue;let v=h.vote??0,$=m.get(h.id);v===0&&!$?.length||(I.push({id:h.id,author:se(h),body:"",createdAt:null,url:"",reviewComments:$??[]}),y.add(h.id))}for(let[h,v]of m){if(y.has(h)||!v.length)continue;let $=v[0].author;$&&I.push({id:h,author:$,body:"",createdAt:null,url:"",reviewComments:v})}return{data:I}}};var U=(s,n={})=>f(n.token||s.token,n.isPAT||s.isPAT);var G="https://api.bitbucket.org/2.0",ps={OPEN:"OPEN",MERGED:"MERGED",DECLINED:"CLOSED"},Ce={owner:4,admin:3,contributor:2,member:1},$e=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}),er=s=>{let n=s.links.clone,e=n?.find(r=>r.name==="ssh"),t=n?.find(r=>r.name==="https");return e&&t?{cloneUrlHTTPS:t.href,cloneUrlSSH:e.href}:null},dt=s=>({id:s.uuid,namespace:s.workspace.slug,name:s.slug,webUrl:s.links.html.href,httpsUrl:s.links.clone.find(n=>n.name==="https")?.href??null,sshUrl:s.links.clone.find(n=>n.name==="ssh")?.href??null,defaultBranch:{name:s.mainbranch.name},permissions:null}),ct=s=>{let n=s.id,e=s.participants?.map(t=>{let r="REVIEW_REQUESTED";return t.approved?r="APPROVED":t.state==="changes_requested"?r="CHANGES_REQUESTED":t.participated_on!==null&&(r="COMMENTED"),{reviewer:$e(t.user),state:r}})??[];return{id:n.toString(),title:s.title,description:s.description,number:n,state:ps[s.state],isDraft:!1,commentCount:s.comment_count,upvoteCount:null,author:$e(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:er(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,headRepository:{id:s.source.repository.uuid,name:s.source.repository.name,owner:{login:s.source.repository.full_name.split("/")[0]},remoteInfo:er(s.source.repository)},mergeableState:"MERGEABLE",permissions:null}},ds=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}}},cs=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}}},ue=class extends N{async refreshToken(n){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 ${n.base64ClientIDColonClientSecret}`},body:`grant_type=refresh_token&refresh_token=${n.refreshToken}`})).body}}async getCurrentUser(n={},e={}){let t=await this.config.request({url:`${G}/user`,headers:U(this.config,e)});return{data:$e(t.body)}}async getUserForCommit(n,e={}){let r=(await this.config.request({url:`${G}/repositories/${n.repo.namespace}/${n.repo.name}/commit/${n.oid}`,headers:U(this.config,e)})).body.author,o=r.raw.match(/([^<]+)<(.+)>/);return{data:{name:o?o[1].trim():null,email:o?o[2]:null,avatarUrl:r.user?.links.avatar.href||null}}}async getRepo(n,e={}){let t=await this.config.request({url:`${G}/repositories/${n.namespace}/${n.name}`,headers:U(this.config,e)});return{data:dt(t.body)}}async getRepos(n,e={}){let t=[],r=[];return await Promise.all(n.map(async o=>{try{let i=await this.getRepo(o,e);t.push(i.data)}catch(i){r.push({input:o,error:i})}})),{data:t,errors:r}}async getReposForWorkspace(n,e={}){let t=new URL(`${G}/repositories/${encodeURIComponent(n.workspace)}`);t.searchParams.set("page",n.page?.toString()||"1"),t.searchParams.set("pagelen",D.toString()),n.minimumRole&&t.searchParams.set("role",n.minimumRole);let r=await this.config.request({url:t.toString(),headers:U(this.config,e)}),o=!!r.body.next;return{pageInfo:{hasNextPage:o,nextPage:o?r.body.page+1:null},data:r.body.values.map(dt)}}async getAllReposForWorkspace(n,e={}){let t=[],r=1;for(;r!==null;){let o=await this.getReposForWorkspace({workspace:n.workspace,minimumRole:n.minimumRole,page:r},e);t.push(...o.data),r=o.pageInfo.hasNextPage?o.pageInfo.nextPage:null}return t}async getAllReposForWorkspaceWithPermissions(n,e={}){let t=new Map,r=[],o=Ce[n.minimumRole||"member"];o<=Ce.admin&&r.push("admin"),o<=Ce.contributor&&r.push("contributor"),o<=Ce.member&&r.push("member");let i=[];for(let a of r){i=await this.getAllReposForWorkspace({workspace:n.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:cs(u)}})}}async getReposForCurrentUser(n,e={}){let t=new URL(`${G}/repositories`);t.searchParams.set("role","member"),t.searchParams.set("pagelen",D.toString()),n.cursor&&t.searchParams.set("after",n.cursor);let r=await this.config.request({url:t.toString(),headers:U(this.config,e)}),o=!!r.body.next,i=null;return r.body.next&&(i=new URL(r.body.next).searchParams.get("after")),{pageInfo:{hasNextPage:o,endCursor:i},data:r.body.values.map(dt)}}async getBranches(n,e={}){let t=new URL(`${G}/repositories/${n.repo.namespace}/${n.repo.name}/refs/branches`);t.searchParams.set("page",n.page?.toString()||"1"),t.searchParams.set("pagelen",D.toString());let r=await this.config.request({url:t.toString(),headers:U(this.config,e)}),o=!!r.body.next;return{pageInfo:{hasNextPage:o,nextPage:o?r.body.page+1:null},data:r.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(n,e={}){let t=new URL(`${G}/repositories/${n.repo.namespace}/${n.repo.name}/refs/tags`);t.searchParams.set("pagelen",D.toString()),n.cursor&&t.searchParams.set("page",n.cursor);let r=await this.config.request({url:t.toString(),headers:U(this.config,e)}),o=!!r.body.next,i=null;return r.body.next&&(i=new URL(r.body.next).searchParams.get("page")),{pageInfo:{hasNextPage:o,endCursor:i},data:r.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(n={},e={}){let t=new URL(`${G}/user/workspaces`);t.searchParams.set("page",n?.page?.toString()||"1"),t.searchParams.set("pagelen","50"),n?.administrator!==void 0&&t.searchParams.set("administrator",n.administrator.toString());let r=await this.config.request({url:t.toString(),headers:U(this.config,e)}),o=!!r.body.next;return{pageInfo:{hasNextPage:o,nextPage:o?r.body.page+1:null},data:r.body.values.map(i=>({id:i.workspace.uuid,slug:i.workspace.slug}))}}async getWorkspacesForUser(n,e={}){let t=new URL(`${G}/user/permissions/workspaces`);t.searchParams.set("page",n.page?.toString()||"1"),t.searchParams.set("pagelen","50");let r=await this.config.request({url:t.toString(),headers:U(this.config,e)}),o=!!r.body.next;return{pageInfo:{hasNextPage:o,nextPage:o?r.body.page+1:null},data:r.body.values.map(i=>({id:i.workspace.uuid,slug:i.workspace.slug,name:i.workspace.name}))}}async getPullRequestsForUserAndWorkspace(n,e={}){let t=new URL(`${G}/workspaces/${n.workspaceSlug}/pullrequests/${n.userId}`);if(t.searchParams.set("fields","+values.participants,+values.destination.repository.links.clone.*,+values.source.repository.links.clone.*"),t.searchParams.set("page",n.page?.toString()||"1"),t.searchParams.set("pagelen","50"),n.repos&&n.repos.length>0){let i=`state = "open" AND (${n.repos.map(a=>`source.repository.full_name = "${a.namespace}/${a.name}"`).join(" OR ")})`;t.searchParams.set("q",i)}let r=await this.config.request({url:t.toString(),headers:U(this.config,e)}),o=!!r.body.next;return{pageInfo:{hasNextPage:o,nextPage:o?r.body.page+1:null},data:r.body.values.map(ct)}}async getPullRequestsForRepoBase(n,e={}){let t=new URL(`${G}/repositories/${encodeURI(n.repo.namespace)}/${encodeURI(n.repo.name)}/pullrequests?state=OPEN`),r=[];n.reviewerId&&r.push(`reviewers.uuid="${n.reviewerId}"`),n.authorLogin&&r.push(`author.uuid="${n.authorLogin}"`);let o='state="OPEN"';return r.length&&(o+=` AND (${r.join(n.useOrFilter?" OR ":" AND ")})`),t.searchParams.set("fields","+values.participants,+values.destination.repository.links.clone.*,+values.source.repository.links.clone.*"),t.searchParams.set("page",n.page?.toString()||"1"),t.searchParams.set("pagelen","50"),t.searchParams.set("q",o),await this.config.request({url:t.toString(),headers:U(this.config,e)})}async getPullRequestsForRepo(n,e={}){let t=[],r=await this.getPullRequestsForRepoBase(n,e);r.body.values.forEach(i=>{t.push(ct(i))});let o=!!r.body.next;return{pageInfo:{hasNextPage:o,nextPage:o?r.body.page+1:null},data:t}}async getPullRequestsForRepos(n,e={}){let t=[];return await Promise.all(n.repos.map(async r=>{try{(await this.getPullRequestsForRepoBase({repo:r,...n},e)).body.values.forEach(i=>{t.push(ct(i))})}catch(o){if(o.statusCode!==404&&o.statusCode!==401)throw o}})),{data:t}}async getAccountsForWorkspace(n,e={}){let t=new URL(`${G}/workspaces/${encodeURI(n.workspace)}/members`);t.searchParams.set("page",n.page?.toString()||"1"),t.searchParams.set("pagelen","100");let r=await this.config.request({url:t.toString(),headers:U(this.config,e)}),o=!!r.body.next;return{pageInfo:{hasNextPage:o,nextPage:o?r.body.page+1:null},data:r.body.values.map(i=>$e(i.user))}}async getReposPermissionsForCurrentUser(n,e={}){let t=new URL(`${G}/user/permissions/repositories`);t.searchParams.set("page",n.page?.toString()||"1"),t.searchParams.set("pagelen","100");let r=await this.config.request({url:t.toString(),headers:U(this.config,e)}),o=!!r.body.next;return{pageInfo:{hasNextPage:o,nextPage:o?r.body.page+1:null},data:r.body.values.reduce((i,a)=>({...i,[a.repository.uuid]:ds(a.permission)}),{})}}async decorateReposWithPermissions(n,e={}){let t={},r=1;do{let o=await this.getReposPermissionsForCurrentUser({page:r},e);t={...o.data,...t},r=o.pageInfo.hasNextPage?o.pageInfo.nextPage:null}while(r!==null);return{data:n.repos.map(o=>({...o,permissions:t[o.id]??{canCreateWebhook:!1,canPush:!1,isAdmin:!1}}))}}async closePullRequest(n,e={}){let{pullRequest:t}=n;if(!(await this.config.request({method:"POST",url:`${G}/repositories/${t.repository.owner.login}/${t.repository.name}/pullrequests/${t.id}/decline`,headers:U(this.config,e)})).body.title)throw new Error("Could not close pull request")}async mergePullRequest(n,e={}){let{pullRequest:t,mergeStrategy:r}=n,o;switch(r){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:`${G}/repositories/${t.repository.owner.login}/${t.repository.name}/pullrequests/${t.id}/merge`,body:JSON.stringify(i),headers:{...U(this.config,e),"Content-Type":"application/json"}})).body.title)throw new Error("Could not merge pull request")}async setPullRequestReviewers(n,e={}){let{pullRequest:t,reviewers:r}=n,o={reviewers:r.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:`${G}/repositories/${t.repository.owner.login}/${t.repository.name}/pullrequests/${t.id}`,body:JSON.stringify(o),headers:{...U(this.config,e),"Content-Type":"application/json"}})).body.title)throw new Error("Could not set pull request reviewers")}};var tr=s=>s?s.find(n=>n.permission==="USER_ADMIN"||n.permission==="PROJECT_ADMIN"||n.permission==="ADMIN"||n.permission==="SYS_ADMIN"||n.permission==="REPO_ADMIN")?{canCreateWebhook:!0,canPush:!0,isAdmin:!0}:s.find(n=>n.permission==="REPO_WRITE"||n.permission==="REPO_CREATE"||n.permission==="PROJECT_CREATE"||n.permission==="PROJECT_WRITE")?{canCreateWebhook:!1,canPush:!0,isAdmin:!1}:{canCreateWebhook:!1,canPush:!1,isAdmin:!1}:{canCreateWebhook:!1,canPush:!1,isAdmin:!1};var Ie=s=>{let n=s.links.self[0].href;return{name:s.displayName,email:s.emailAddress,avatarUrl:s.avatarUrl??(n&&`${n}/avatar.png`),id:s.id.toString(),username:s.name,url:n}},De=s=>{let n={OPEN:"OPEN",MERGED:"MERGED",DECLINED:"CLOSED"},e={UNAPPROVED:"REVIEW_REQUESTED",NEEDS_WORK:"CHANGES_REQUESTED",APPROVED:"APPROVED"},t=s.reviewers.map(u=>({reviewer:Ie(u.user),state:e[u.status]})),r=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:n[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:Ie(s.author.user),assignees:null,reviews:t,reviewDecision:j(t),repository:{id:s.toRef.repository.id.toString(),name:s.toRef.repository.name,owner:{login:s.toRef.repository.project.key},remoteInfo:o&&r?{cloneUrlHTTPS:o,cloneUrlSSH:r}: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}},rr=s=>({id:s.id.toString(),namespace:s.project.key,name:s.slug,webUrl:s.links.self[0]?.href??null,httpsUrl:s.links.clone.find(n=>n.name==="https"||n.name==="http")?.href??null,sshUrl:s.links.clone.find(n=>n.name==="ssh")?.href??null,defaultBranch:null,permissions:null}),le=class extends _{getBaseUrl(n){let e=n.baseUrl||this.config.baseUrl;if(!e)throw new Error('Bitbucket Server requires "baseUrl"');return e}getRequestHeaders(n){return f(n.token||this.config.token)}async getCurrentUser(n={},e={}){let t=await this.config.request({url:`${this.getBaseUrl(e)}/users?limit=2`,headers:this.getRequestHeaders(e)}),{headers:{"x-auserid":r,"x-ausername":o}}=t,i=r?parseInt(r,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:Ie(l)}}async getUserForCommit(n,e){let{repo:t,oid:r}=n,o=await this.config.request({url:`${this.getBaseUrl(e)}/projects/${t.namespace}/repos/${t.name}/commits/${r}`,headers:this.getRequestHeaders(e)});if(!o.body.author)throw new Error("Could not find user for commit");return{data:Ie(o.body.author)}}async getRepo(n,e={}){let t=await this.config.request({url:`${this.getBaseUrl(e)}/projects/${n.namespace}/repos/${n.name}`,headers:this.getRequestHeaders(e)});return{data:rr(t.body)}}async getRepos(n,e={}){let t=[],r=[];return await Promise.all(n.map(async o=>{try{let i=await this.getRepo(o,e);t.push(i.data)}catch(i){r.push({input:o,error:i})}})),{data:t,errors:r}}async getReposForCurrentUser(n,e={}){let t=n.page??0,r=await this.config.request({url:`${this.getBaseUrl(e)}/repos?start=${t}`,headers:this.getRequestHeaders(e)});return{pageInfo:{hasNextPage:!r.body.isLastPage,nextPage:r.body.nextPageStart},data:r.body.values.map(rr)}}async getRepoPermissionsForUsername(n,e={}){let t=new URL(`${this.getBaseUrl(e)}/projects/${n.repo.namespace}/repos/${n.repo.name}/permissions/search?filterText=${n.username}`);try{let r=await this.config.request({url:t.toString(),headers:this.getRequestHeaders(e)});return{data:tr(r.body.values)}}catch(r){if(r.response?.status===401)return{data:{canCreateWebhook:!1,canPush:!1,isAdmin:!1}};throw r}}async decorateReposWithPermissions(n,e={}){return await Promise.all(n.repos.map(async r=>{let o=await this.getRepoPermissionsForUsername({repo:r,username:n.username},e);return{...r,permissions:o.data}}))}async getPullRequestsForRepoBase(n,e={}){let t=new URL(`${this.getBaseUrl(e)}/projects/${encodeURI(n.repo.namespace)}/repos/${encodeURI(n.repo.name)}/pull-requests?state=OPEN`);return t.searchParams.set("start",n.page?.toString()||"0"),t.searchParams.set("limit","50"),await this.config.request({url:t.toString(),headers:this.getRequestHeaders(e)})}async getPullRequestsForRepo(n,e={}){let t=[],r=await this.getPullRequestsForRepoBase(n,e);r.body.values.forEach(i=>{if(n.authorLogin&&i.author.user.name!==n.authorLogin)return null;t.push(De(i))});let o=r.body.values.length!==0;return{pageInfo:{hasNextPage:o,nextPage:o?r.body.start+r.body.values.length:null},data:t}}async getPullRequestsForRepos(n,e={}){let t=[];return await Promise.all(n.repos.map(async r=>{try{(await this.getPullRequestsForRepoBase({repo:r,...n},e)).body.values.forEach(i=>{if(n.authorLogin&&i.author.user.name!==n.authorLogin)return null;t.push(De(i))})}catch(o){if(o.statusCode!==404&&o.statusCode!==401)throw o}})),{data:t}}async getPullRequestsForCurrentUser(n,e={}){let t=new URL(`${this.getBaseUrl(e)}/dashboard/pull-requests`);t.searchParams.set("state","OPEN"),t.searchParams.set("start",n.page?.toString()||"0"),t.searchParams.set("limit","50");let r=await this.config.request({url:t.toString(),headers:this.getRequestHeaders(e)}),o=r.body.values.length!==0;return{pageInfo:{hasNextPage:o,nextPage:o?r.body.start+r.body.values.length:null},data:r.body.values.map(De)}}async closePullRequest(n,e={}){let{pullRequest:t}=n;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(n,e={}){let{pullRequest:t,mergeStrategyId:r}=n;if(n.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:r,version:t.version}),headers:{...this.getRequestHeaders(e),"Content-Type":"application/json"}})).body.title)throw new Error("Could not merge pull request")}async getMergeStrategies(n={}){let e=await this.config.request({url:`${this.getBaseUrl(n)}/admin/pull-requests/git`,headers:{...this.getRequestHeaders(n),"Content-Type":"application/json"}});return{data:{defaultStrategy:e.body.mergeConfig.defaultStrategy,strategies:e.body.mergeConfig.strategies}}}async setPullRequestReviewers(n,e={}){let{pullRequest:t,reviewers:r}=n;if(t.version===void 0)throw new Error('Bitbucket Server requires "version" for this function.');let o={reviewers:r.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(n,e={}){let t=new URL(`${this.getBaseUrl(e)}/projects/${encodeURI(n.project)}/permissions/users`);t.searchParams.set("start",n.page?.toString()||"0"),t.searchParams.set("limit","50");let r=await this.config.request({url:t.toString(),headers:this.getRequestHeaders(e)}),o=r.body.values.length!==0;return{pageInfo:{hasNextPage:o,nextPage:o?r.body.start+r.body.values.length:null},data:r.body.values.map(i=>Ie(i.user))}}};var Rr=require("js-base64");var Le=(e=>(e.Open="OPEN",e.Closed="CLOSED",e))(Le||{});var R=class extends Error{constructor(e,t){let r=t?.map(i=>`'${i.message}'`).join(", "),o=r?`${e}: ${r}`:e;super(o);this.graphQLErrors=t??[]}};var ms={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]},sr=15,nr=100,be={__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,Q=(s,n)=>{let e=ms[n];for(let t=0;t<3;t++){if(s[t]>e[t])return!0;if(s[t]<e[t])return!1}return!0},Ae="https://api.github.com",gs=`${Ae}/graphql`,Ge=`
|
|
1
|
+
"use strict";var rt=Object.defineProperty;var Jr=Object.getOwnPropertyDescriptor;var Vr=Object.getOwnPropertyNames;var Kr=Object.prototype.hasOwnProperty;var Xr=(s,n)=>{for(var e in n)rt(s,e,{get:n[e],enumerable:!0})},Zr=(s,n,e,t)=>{if(n&&typeof n=="object"||typeof n=="function")for(let r of Vr(n))!Kr.call(s,r)&&r!==e&&rt(s,r,{get:()=>n[r],enumerable:!(t=Jr(n,r))||t.enumerable});return s};var Yr=s=>Zr(rt({},"__esModule",{value:!0}),s);var Tn={};Xr(Tn,{AzureDevOps:()=>ae,Bitbucket:()=>ue,BitbucketServer:()=>le,EntityIdentifierProviderType:()=>Qr,EntityType:()=>jr,EntityVersion:()=>Fr,GitBuildStatusStage:()=>Mt,GitBuildStatusState:()=>ve,GitDiffLineType:()=>st,GitHub:()=>pe,GitHubIssueCloseReason:()=>Br,GitIssueState:()=>Le,GitLab:()=>ce,GitMergeStrategy:()=>ie,GitPullRequestMergeableState:()=>re,GitPullRequestReviewState:()=>K,GitPullRequestState:()=>te,GraphQLErrors:()=>R,Jira:()=>me,JiraServer:()=>ge,PullRequestAsyncStatus:()=>Nr,Trello:()=>he,default:()=>Gn,isFetch:()=>Se});module.exports=Yr(Tn);var Yt=require("diff");var Mt=(r=>(r.Build="build",r.Production="production",r.Staging="staging",r.Test="test",r))(Mt||{}),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||{}),ie=(o=>(o.MergeCommit="MERGE_COMMIT",o.Rebase="REBASE",o.RebaseThenMergeCommit="REBASE_THEN_MERGE_COMMIT",o.FastForward="FAST_FORWARD",o.Squash="SQUASH",o))(ie||{}),te=(t=>(t.Open="OPEN",t.Closed="CLOSED",t.Merged="MERGED",t))(te||{}),K=(r=>(r.Approved="APPROVED",r.ChangesRequested="CHANGES_REQUESTED",r.Commented="COMMENTED",r.ReviewRequested="REVIEW_REQUESTED",r))(K||{}),re=(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))(re||{}),st=(t=>(t.ADDED="ADDED",t.DELETED="DELETED",t.UNMODIFIED="UNMODIFIED",t))(st||{});var zt={APPROVED:0,COMMENTED:1,REVIEW_REQUESTED:2,CHANGES_REQUESTED:3},j=s=>!s||s.length===0?null:s.reduce((n,e)=>zt[e.state]>zt[n]?e.state:n,"APPROVED");var nt=(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))(nt||{});var $=100;var Ht=globalThis.fetch;var es=async s=>{let n=s.headers.get("content-type")||"",e=null;if(n.startsWith("application/json")){let o=await s.text();e=o.trim().length>0?JSON.parse(o):null}else if(n.startsWith("text/")||n===""||n.startsWith("application/vnd.github.diff")||n.startsWith("application/vnd.github.patch"))e=await s.text();else if(n.startsWith("application/vnd.github.raw+json")||n.startsWith("application/octet-stream"))e=await s.arrayBuffer();else throw new Error(`Unsupported content-type: ${n}`);let t={};s.headers.forEach((o,i)=>{t[i]=o});let r={body:e,headers:t,status:s.status,statusText:s.statusText};if(!s.ok){let o=new Error(s.statusText);throw Object.assign(o,{response:r}),o}return r},ot=s=>async({url:n,...e})=>{let t=await s(n,e);return es(t)};var Se=(s,n=!1)=>s.name==="fetch"||n;var N=class{constructor(n){let e=n?.request||Ht;this.config={...n,request:Se(e,n?.forceIsFetch)?ot(e):e}}updateConfig(n){this.config={...this.config,...n,request:n.request&&Se(n.request,n?.forceIsFetch??this.config.forceIsFetch)?ot(n.request):this.config.request}}},_=class extends N{};var f=(s,n)=>{let e={};return s&&(e.Authorization=`${n?"Basic":"Bearer"} ${s}`),e},Wt=s=>s?s.reduce((n,e)=>(n[e]=!0,n),{}):void 0,X=(s,n,e)=>!s||n.some(t=>s[t])?e:"",Jt=async s=>{let n=[],e=!0,t;for(;e;){let r=await s(t);n=n.concat(r.data),e=!!r?.pageInfo?.hasNextPage,t=r?.pageInfo?.endCursor||r?.pageInfo?.nextPage}return n};async function it(s){return(await Promise.allSettled(s)).map(e=>ts(e)).filter(e=>e!=null)}function ts(s,n=void 0){return s?.status==="fulfilled"?s.value:n}var rs="https://app.vssps.visualstudio.com/_apis",ss="https://vssps.dev.azure.com/",ns="https://dev.azure.com",w=(s,n={})=>f(n.token||s.token,n.isPAT||s.isPAT),Vt=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/"),at=(s,n)=>{let e=n.baseUrl||s.baseUrl||rs;return e=e.replace(/\/$/,""),e},C=(s,n)=>{let e=n.baseUrl||s.baseUrl||ns;return e=e.replace(/\/$/,""),e},ut=(s,n)=>{let e=n.baseUrl||s.baseUrl||ss;return e=e.replace(/\/$/,""),e};var os={active:"OPEN",completed:"MERGED",abandoned:"CLOSED"},is=s=>{if(typeof s!="string")return s;let n=s.charAt(0).toUpperCase()+s.slice(1);return nt[n]??0},as=new Set([2,3,4,5]),us={10:"APPROVED",5:"APPROVED",0:"REVIEW_REQUESTED",[-5]:"CHANGES_REQUESTED",[-10]:"CHANGES_REQUESTED"},se=s=>({id:s.id,name:s.displayName??null,username:(s.uniqueName||s.displayName)??null,email:null,avatarUrl:s.imageUrl??null,url:null}),Ee=s=>s.startsWith("refs/heads/")?s.replace("refs/heads/",""):s,ls=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"}},lt=(s,n,e,t,r,o)=>`${s}|${n}|${e}|${t}|${r}|${o}`,Kt=s=>{let n=s.split("|");if(n.length!==6)throw new Error("Invalid Azure comment ID format");return{namespace:n[0],project:n[1],repoName:n[2],prId:n[3],threadId:n[4],commentId:n[5]}},Xt=(s,n,e,t,r)=>`${s}|${n}|${e}|${t}|${r}`,pt=s=>{let n=s.split("|");if(n.length!==5)throw new Error("Invalid Azure thread ID format");return{namespace:n[0],project:n[1],repoName:n[2],prId:n[3],threadId:n[4]}},Re=(s,n)=>{let e=[],t=[];return n.reviewers.forEach(r=>{let o={reviewer:se(r),state:us[r.vote??0]||"REVIEW_REQUESTED"};r.isRequired&&e.push(o),t.push(o)}),{id:n.pullRequestId.toString(),title:n.title,description:n.description??null,number:n.codeReviewId,state:os[n.status],isDraft:n.isDraft,commentCount:null,upvoteCount:null,author:se(n.createdBy),createdDate:new Date(n.creationDate),updatedDate:new Date(n.closedDate||n.creationDate),closedDate:n.closedDate?new Date(n.closedDate):null,mergedDate:n.closedDate&&n.status==="completed"?new Date(n.closedDate):null,repository:{id:n.repository.id,name:n.repository.name,project:n.repository.project.name,owner:{login:s},remoteInfo:null},headCommit:{buildStatuses:null},baseRef:{name:Ee(n.targetRefName),oid:n.lastMergeTargetCommit.commitId},headRef:{name:Ee(n.sourceRefName),oid:n.lastMergeSourceCommit.commitId},url:Vt(n),assignees:n.reviewers.map(se),reviews:t,reviewDecision:j(e),additions:null,deletions:null,fileCount:null,commitCount:null,headRepository:n.forkSource?{id:n.forkSource.repository.id,name:n.forkSource.repository.name,project:void 0,owner:{login:s},remoteInfo:null}:{id:n.repository.id,name:n.repository.name,project:n.repository.project.name,owner:{login:s},remoteInfo:null},mergeableState:ls(n.mergeStatus),labels:n.labels?.map(r=>({color:null,description:null,id:r.id,name:r.name}))??[],permissions:null}},Zt=(s,n)=>({id:n.id,name:n.name,namespace:s,project:n.project.name,projectId:n.project.id,webUrl:n.webUrl,httpsUrl:n.remoteUrl,sshUrl:n.sshUrl,defaultBranch:n.defaultBranch?{name:Ee(n.defaultBranch)}:null,permissions:null}),ps=(s,n,e,t)=>{let r=e.fields,o=r["System.AssignedTo"],i=r["System.State"],a=r["System.WorkItemType"],u;return i&&a&&(u=t[a]?.[i]),{id:e.id.toString(),number:e.id.toString(),title:r["System.Title"],commentCount:r["System.CommentCount"],author:{avatarUrl:r["System.CreatedBy"]._links?.avatar?.href??null,email:null,id:r["System.CreatedBy"].id,name:r["System.CreatedBy"].uniqueName??null,username:r["System.CreatedBy"].displayName??null,url:null},closedDate:r["Microsoft.VSTS.Common.ClosedDate"]?new Date(r["Microsoft.VSTS.Common.ClosedDate"]):null,createdDate:new Date(r["System.CreatedDate"]),updatedDate:new Date(r["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:r["System.Description"]??null,state:{name:u?.title||i,color:null},type:r["System.WorkItemType"],repository:null,project:{namespace:s,name:n,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()}))??[]}},ae=class extends _{constructor(){super(...arguments);this.cachedUserIds=new Map;this.inflightUserIds=new Map}getCurrentUserId(e,t){let r=JSON.stringify([e,t.token??null,t.isPAT??this.config.isPAT??!1,t.baseUrl??null]),o=this.cachedUserIds.get(r);if(o)return Promise.resolve(o);let i=this.inflightUserIds.get(r);if(i)return i;let a=this.fetchCurrentUserId(e,t,r);return this.inflightUserIds.set(r,a),a}async fetchCurrentUserId(e,t,r){try{let o=await this.getCurrentUserForInstance({namespace:e},t);return this.cachedUserIds.set(r,o.data.id),o.data.id}finally{this.inflightUserIds.delete(r)}}getRepoApiUrl(e,t,r,o){return`${C(this.config,o)}/${encodeURIComponent(e)}/${encodeURIComponent(t)}/_apis/git/repositories/${encodeURIComponent(r)}`}async getCurrentUser(e={},t={}){if(t.isPAT||this.config.isPAT)throw new Error("Azure DevOps does not support PATs for this function.");let r=`${at(this.config,t)}/profile/profiles/me`,o=await this.config.request({url:r,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 r=`${at(this.config,t)}/accounts?memberId=${e.userId}&api-version=6.0`;return{data:(await this.config.request({url:r,headers:w(this.config,t)})).body.value.map(i=>({id:i.accountId,name:i.accountName}))}}async getCollectionsForUser(e,t={}){let r=`${C(this.config,t)}/_apis/projectCollections`;return{data:(await this.config.request({url:r,headers:w(this.config,t)})).body.value.map(i=>({id:i.id,name:i.name}))}}async getAzureProjects(e,t={}){let r=new URL(`${C(this.config,t)}/${encodeURIComponent(e.namespace)}/_apis/projects`);r.searchParams.set("$top",$.toString()),e.cursor&&r.searchParams.set("$skip",e.cursor);let o=await this.config.request({url:r.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:r,projectId:o}=e;return{data:{scope:(await this.config.request({url:`${ut(this.config,t)}/${encodeURIComponent(r)}/_apis/graph/descriptors/${o}?api-version=6.0`,headers:w(this.config,t)})).body.value}}}async getAzureGraphAccountsForAzureProject(e,t={}){let{namespace:r,projectScopeDescriptor:o,cursor:i}=e,a=new URL(`${ut(this.config,t)}/${encodeURIComponent(r)}/_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:r}=e;if(!r.storageKeyURL)throw new Error("Expected 'storageKeyURL' to not be null for 'azureGraphAccount'");let o=await this.config.request({url:r.storageKeyURL,headers:w(this.config,t)});return{data:{avatarUrl:r.avatarUrl,email:r.email,id:o.body.value,name:r.name,username:r.username,url:null}}}async getAccountsFromAzureGraphAccounts(e,t={}){let r=[];for(let o of e.azureGraphAccounts){let i=await this.getAccountFromAzureGraphAccount({azureGraphAccount:o},t);r.push(i.data)}return{data:r}}async getRepo(e,t={}){if(!e.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let r=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:Zt(e.namespace,r.body)}}async getRepos(e,t={}){let r=[],o=[];return await Promise.all(e.map(async i=>{try{let a=await this.getRepo(i,t);r.push(a.data)}catch(a){o.push({input:i,error:a})}})),{data:r,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=>Zt(e.namespace,o))}}async getRefs(e,t,r={}){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,r)}/${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,r)}),a=i.headers["x-ms-continuationtoken"];return{pageInfo:{hasNextPage:!!a,endCursor:a||null},data:i.body.value.map(u=>({name:Ee(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={},r=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=${r}&%24skip=${(l-1)*r}`,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=>Re(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:r}=e||{},o=[];return await Promise.all(r.map(async i=>{try{(await this.getPullRequestsForRepoBase({repo:i,...e},t)).body.value.forEach(u=>{o.push(Re(i.namespace,u))})}catch(a){if(a.statusCode!==404&&a.statusCode!==401)throw a}})),{data:o}}async getPullRequestsForProjectBase(e,t={},r=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",r.toString()),d.searchParams.set("$skip",((c-1)*r).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=>Re(e.namespace,a))||[]}}async getPullRequestsForProjects(e,t={}){let{projects:r}=e||{},o=[];return await Promise.all(r.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(Re(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:r,project:o,name:i},pullRequestId:a}=e,u=await this.config.request({url:`${C(this.config,t)}/${encodeURIComponent(r)}/${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,r){return await this.config.request({method:"PATCH",url:`${C(this.config,r)}/${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,r),"Content-Type":"application/json"}})}async closePullRequest(e,t={}){let{pullRequest:r}=e,o={status:"abandoned"};if(!(await this.updatePullRequest(r,JSON.stringify(o),t)).body.status)throw new Error("Could not close pull request")}async mergePullRequest(e,t={}){let{pullRequest:r,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:r.headRef?.oid},status:"completed"};if(!(await this.updatePullRequest(r,JSON.stringify(a),t)).body.status)throw new Error("Could not merge pull request")}async addPullRequestLabel(e,t={}){let{pullRequest:r,label:o}=e;if(!r.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(r.repository.owner.login)}/${encodeURIComponent(r.repository.project)}/_apis/git/repositories/${r.repository.name}/pullrequests/${r.id}/labels?api-version=6.0`,body:JSON.stringify(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:r,label:o}=e;if(!r.repository.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');await this.config.request({method:"DELETE",url:`${C(this.config,t)}/${encodeURIComponent(r.repository.owner.login)}/${encodeURIComponent(r.repository.project)}/_apis/git/repositories/${r.repository.name}/pullrequests/${r.id}/labels/${encodeURIComponent(o.name)}?api-version=6.0`,headers:{...w(this.config,t)}})}async setPullRequestLabels(e,t={}){let{pullRequest:r,labels:o}=e;if(!r.repository.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let i=r.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:r,label:a},t);for(let a of i)o.find(u=>a.id===u.id)||await this.removePullRequestLabel({pullRequest:r,label:a},t)}async setPullRequestAsDraft(e,t={}){let{pullRequest:r,isDraft:o}=e,i={isDraft:o};if(!(await this.updatePullRequest(r,JSON.stringify(i),t)).body.status)throw new Error("Could not set the pull request as draft")}async addPullRequestReviewer(e,t={}){let{pullRequest:r,reviewer:o,isRequired:i}=e,a={id:o.id,isRequired:i};if(!(await this.config.request({method:"PUT",url:`${C(this.config,t)}/${encodeURIComponent(r.repository.owner.login)}/${encodeURIComponent(r.repository.project)}/_apis/git/repositories/${r.repository.name}/pullrequests/${r.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:r,reviewer:o}=e;await this.config.request({method:"DELETE",url:`${C(this.config,t)}/${encodeURIComponent(r.repository.owner.login)}/${encodeURIComponent(r.repository.project)}/_apis/git/repositories/${r.repository.name}/pullrequests/${r.id}/reviewers/${o.id}?api-version=6.0`,headers:{...w(this.config,t),Accept:"application/json"}})}async setPullRequestReviewers(e,t={}){let{pullRequest:r,reviewers:o}=e;for(let i of o)r.assignees.find(a=>a.id===i.id)||await this.addPullRequestReviewer({pullRequest:r,reviewer:i,isRequired:!0},t);for(let i of r.assignees)o.find(a=>i.id===a.id)||await this.removePullRequestReviewer({pullRequest:r,reviewer:i},t)}async getIssuesForAzureProject(e,t={}){let{page:r,assigneeLogins:o,authorLogin:i,mentionLogin:a,labelNames:u,statusByWorkItemIdByStatusId:l}=e||{},p=r||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=>ps(e.namespace,e.project,h,l||{}))}}async getPermissionsForRepos(e,t={}){let{namespace:r,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(r)}/_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:r,repos:o}=e,i=await this.getPermissionsForRepos({namespace:r,repos:o},t);return{data:o.map(a=>({...a,permissions:i.data[`${a.projectId}/${a.id}`]}))}}async updateIssue(e,t,r={}){return await this.config.request({method:"PATCH",url:`${C(this.config,r)}/${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,r),"Content-Type":"application/json-patch+json"}})}async setIssueStatus(e,t={}){let{issue:r,status:o}=e,i=[{op:"add",path:"/fields/System.State",value:o.name}];if(!(await this.updateIssue(r,i,t)).body.fields?.["System.State"])throw new Error("Could not set issue status")}async setIssueAssignee(e,t={}){let{issue:r,assignee:o}=e,i=[{op:"add",path:"/fields/System.AssignedTo",value:o?.name??""}];if(!(await this.updateIssue(r,i,t)).body.fields?.["System.State"])throw new Error("Could not set issue assignee")}async setIssueLabels(e,t={}){let{issue:r,labels:o}=e,a=[{op:"replace",path:"/fields/System.Tags",value:o.map(l=>l.name).join(";")}];if(!(await this.updateIssue(r,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:r,project:o}=e;return{data:(await this.config.request({url:`${C(this.config,t)}/${encodeURIComponent(r)}/${encodeURIComponent(o||"")}/_apis/wit/workitemtypes?api-version=6.0`,headers:{...w(this.config,t)}})).body.value}}async getLabelsForProject(e,t={}){let{namespace:r,project:o}=e;return{data:(await this.config.request({url:`${C(this.config,t)}/${encodeURIComponent(r)}/${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:r,number:o}=e;if(!r.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let i=await this.config.request({url:`${this.getRepoApiUrl(r.namespace,r.project,r.name,t)}/pullrequests/${o}?api-version=7.1`,headers:w(this.config,t)});return{data:Re(r.namespace,i.body)}}async getPullRequestDescription(e,t={}){let{repo:r,number:o}=e;if(!r.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(r.namespace,r.project,r.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:r,number:o,description:i}=e;if(!r.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(r.namespace,r.project,r.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 r=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(!r.body.value?.length)throw new Error("No merge base found between the specified commits.");return{data:r.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 r=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([r.body])}}async getPullRequestDiff(e,t={}){if(!e.repo.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let r=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:`${r}/pullrequests/${e.pullRequestId}?api-version=7.1`,headers:o}),this.config.request({url:`${r}/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 S=(await this.config.request({url:`${r}/pullrequests/${e.pullRequestId}/iterations/${d.id}/changes?api-version=7.1&$top=${g}&$skip=${I}`,headers:o})).body.changeEntries??[];if(S.length===0||(m.push(...S),S.length<g))break;I+=S.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,S)=>{try{let Y=await this.config.request({url:`${r}/items?path=${encodeURIComponent(P)}&versionDescriptor[version]=${encodeURIComponent(S)}&versionDescriptor[versionType]=commit&includeContent=true&api-version=7.1`,headers:i});return D(Y.body)}catch{return""}},E=P=>{if(typeof P=="number")return{add:(P&1)!==0,rename:(P&8)!==0,delete:(P&16)!==0};let S=P.toLowerCase().split(",").map(Y=>Y.trim());return{add:S.includes("add"),rename:S.includes("rename"),delete:S.includes("delete")}};for(let P=0;P<m.length;P+=y){let S=m.slice(P,P+y),Y=await Promise.all(S.map(async ne=>{let{add:oe,rename:tt,delete:ee}=E(ne.changeType),fe=ne.originalPath??ne.item.originalPath,A=ne.item.path,qe=ee?A??fe??"":A??"",Bt=tt||ee?fe??qe:qe,[Mr,zr]=await Promise.all([oe?Promise.resolve(""):x(Bt,l),ee?Promise.resolve(""):x(qe,p)]),Hr=oe?"/dev/null":`a${Bt}`,Wr=ee?"/dev/null":`b${qe}`;return(0,Yt.createTwoFilesPatch)(Hr,Wr,Mr,zr)}));h.push(...Y)}return h.join(`
|
|
2
|
+
`)}getPullRequestWriteHeaders(e){return{...w(this.config,e),"Content-Type":"application/json"}}setReviewerVote(e,t,r,o,i){return this.config.request({method:"PUT",url:`${e}/pullRequests/${t}/reviewers/${encodeURIComponent(r)}?api-version=7.1`,headers:this.getPullRequestWriteHeaders(i),body:JSON.stringify({vote:o})})}postPullRequestThread(e,t,r,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:r,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 r=this.getRepoApiUrl(e.repo.namespace,e.repo.project,e.repo.name,t),o=w(this.config,t),i=await this.config.request({url:`${r}/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:lt(e.repo.namespace,e.repo.project,e.repo.name,e.pullRequestNumber,u.id,l.id),author:l.author?se(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 r=this.getRepoApiUrl(e.pullRequest.repository.owner.login,e.pullRequest.repository.project,e.pullRequest.repository.name,t);await this.postPullRequestThread(r,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 r=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=pt(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:`${r}/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:`${r}/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 lt(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:`${r}/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 Xt(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 r=Kt(e.commentId),o=this.getRepoApiUrl(r.namespace,r.project,r.repoName,t);await this.config.request({method:"PATCH",url:`${o}/pullRequests/${r.prId}/threads/${r.threadId}/comments/${r.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 r=Kt(e.commentId),o=this.getRepoApiUrl(r.namespace,r.project,r.repoName,t);await this.config.request({method:"DELETE",url:`${o}/pullRequests/${r.prId}/threads/${r.threadId}/comments/${r.commentId}?api-version=7.1`,headers:w(this.config,t)})}async deleteInlineComment(e,t={}){return this.deleteComment(e,t)}async resolveReviewThread(e,t={}){let r=pt(e.threadId),o=this.getRepoApiUrl(r.namespace,r.project,r.repoName,t);await this.config.request({method:"PATCH",url:`${o}/pullRequests/${r.prId}/threads/${r.threadId}?api-version=7.1`,headers:this.getPullRequestWriteHeaders(t),body:JSON.stringify({status:2})})}async unresolveReviewThread(e,t={}){let r=pt(e.threadId),o=this.getRepoApiUrl(r.namespace,r.project,r.repoName,t);await this.config.request({method:"PATCH",url:`${o}/pullRequests/${r.prId}/threads/${r.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 r=e.pullRequest.repository.owner.login,o=this.getRepoApiUrl(r,e.pullRequest.repository.project,e.pullRequest.repository.name,t),i=await this.getCurrentUserId(r,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 r=e.pullRequest.repository.owner.login,o=this.getRepoApiUrl(r,e.pullRequest.repository.project,e.pullRequest.repository.name,t),i=await this.getCurrentUserId(r,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 r=this.getRepoApiUrl(e.pullRequest.repository.owner.login,e.pullRequest.repository.project,e.pullRequest.repository.name,t);await this.postPullRequestThread(r,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:r,project:o,name:i}=e.repo,{pullRequestId:a}=e,u=this.getRepoApiUrl(r,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)=>lt(r,o,i,a,h,v),g=h=>Xt(r,o,i,a,h),m=new Map;for(let h of c.body.value){if(h.isDeleted)continue;let v=h.comments.filter(A=>!A.isDeleted&&A.commentType!=="system"),D=v.find(A=>A.parentCommentId===0)??v[0];if(!D)continue;let x=D.author?.id;if(!x)continue;let E=v.filter(A=>A.id!==D.id),P=h.threadContext,S=P?.rightFileStart?{side:"RIGHT",start:P.rightFileStart,end:P.rightFileEnd}:P?.leftFileStart?{side:"LEFT",start:P.leftFileStart,end:P.leftFileEnd}:null,Y=S?.end?.line??S?.start.line??null,ne=S?.start&&S.end&&S.start.line!==S.end.line?S.start.line:null,oe=P?.filePath??"",tt=oe.startsWith("/")?oe.slice(1):oe,ee={id:d(h.id,D.id),author:D.author?se(D.author):null,body:D.content??"",createdAt:D.publishedDate?new Date(D.publishedDate):null,url:"",diffLines:[],filename:tt,replies:E.map(A=>({id:d(h.id,A.id),author:A.author?se(A.author):null,body:A.content??"",createdAt:A.publishedDate?new Date(A.publishedDate):null,url:""})),isOutdated:!1,isResolved:as.has(is(h.status)),line:Y,startLine:ne,side:S?.side??null,threadId:g(h.id)},fe=m.get(x);fe?fe.push(ee):m.set(x,[ee])}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:se(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 U=(s,n={})=>f(n.token||s.token,n.isPAT||s.isPAT);var G="https://api.bitbucket.org/2.0",ds={OPEN:"OPEN",MERGED:"MERGED",DECLINED:"CLOSED"},Ce={owner:4,admin:3,contributor:2,member:1},$e=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}),er=s=>{let n=s.links.clone,e=n?.find(r=>r.name==="ssh"),t=n?.find(r=>r.name==="https");return e&&t?{cloneUrlHTTPS:t.href,cloneUrlSSH:e.href}:null},dt=s=>({id:s.uuid,namespace:s.workspace.slug,name:s.slug,webUrl:s.links.html.href,httpsUrl:s.links.clone.find(n=>n.name==="https")?.href??null,sshUrl:s.links.clone.find(n=>n.name==="ssh")?.href??null,defaultBranch:{name:s.mainbranch.name},permissions:null}),ct=s=>{let n=s.id,e=s.participants?.map(t=>{let r="REVIEW_REQUESTED";return t.approved?r="APPROVED":t.state==="changes_requested"?r="CHANGES_REQUESTED":t.participated_on!==null&&(r="COMMENTED"),{reviewer:$e(t.user),state:r}})??[];return{id:n.toString(),title:s.title,description:s.description,number:n,state:ds[s.state],isDraft:!1,commentCount:s.comment_count,upvoteCount:null,author:$e(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:er(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,headRepository:{id:s.source.repository.uuid,name:s.source.repository.name,owner:{login:s.source.repository.full_name.split("/")[0]},remoteInfo:er(s.source.repository)},mergeableState:"MERGEABLE",permissions:null}},cs=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}}},ms=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}}},ue=class extends N{async refreshToken(n){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 ${n.base64ClientIDColonClientSecret}`},body:`grant_type=refresh_token&refresh_token=${n.refreshToken}`})).body}}async getCurrentUser(n={},e={}){let t=await this.config.request({url:`${G}/user`,headers:U(this.config,e)});return{data:$e(t.body)}}async getUserForCommit(n,e={}){let r=(await this.config.request({url:`${G}/repositories/${n.repo.namespace}/${n.repo.name}/commit/${n.oid}`,headers:U(this.config,e)})).body.author,o=r.raw.match(/([^<]+)<(.+)>/);return{data:{name:o?o[1].trim():null,email:o?o[2]:null,avatarUrl:r.user?.links.avatar.href||null}}}async getRepo(n,e={}){let t=await this.config.request({url:`${G}/repositories/${n.namespace}/${n.name}`,headers:U(this.config,e)});return{data:dt(t.body)}}async getRepos(n,e={}){let t=[],r=[];return await Promise.all(n.map(async o=>{try{let i=await this.getRepo(o,e);t.push(i.data)}catch(i){r.push({input:o,error:i})}})),{data:t,errors:r}}async getReposForWorkspace(n,e={}){let t=new URL(`${G}/repositories/${encodeURIComponent(n.workspace)}`);t.searchParams.set("page",n.page?.toString()||"1"),t.searchParams.set("pagelen",$.toString()),n.minimumRole&&t.searchParams.set("role",n.minimumRole);let r=await this.config.request({url:t.toString(),headers:U(this.config,e)}),o=!!r.body.next;return{pageInfo:{hasNextPage:o,nextPage:o?r.body.page+1:null},data:r.body.values.map(dt)}}async getAllReposForWorkspace(n,e={}){let t=[],r=1;for(;r!==null;){let o=await this.getReposForWorkspace({workspace:n.workspace,minimumRole:n.minimumRole,page:r},e);t.push(...o.data),r=o.pageInfo.hasNextPage?o.pageInfo.nextPage:null}return t}async getAllReposForWorkspaceWithPermissions(n,e={}){let t=new Map,r=[],o=Ce[n.minimumRole||"member"];o<=Ce.admin&&r.push("admin"),o<=Ce.contributor&&r.push("contributor"),o<=Ce.member&&r.push("member");let i=[];for(let a of r){i=await this.getAllReposForWorkspace({workspace:n.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:ms(u)}})}}async getReposForCurrentUser(n,e={}){let t=new URL(`${G}/repositories`);t.searchParams.set("role","member"),t.searchParams.set("pagelen",$.toString()),n.cursor&&t.searchParams.set("after",n.cursor);let r=await this.config.request({url:t.toString(),headers:U(this.config,e)}),o=!!r.body.next,i=null;return r.body.next&&(i=new URL(r.body.next).searchParams.get("after")),{pageInfo:{hasNextPage:o,endCursor:i},data:r.body.values.map(dt)}}async getBranches(n,e={}){let t=new URL(`${G}/repositories/${n.repo.namespace}/${n.repo.name}/refs/branches`);t.searchParams.set("page",n.page?.toString()||"1"),t.searchParams.set("pagelen",$.toString());let r=await this.config.request({url:t.toString(),headers:U(this.config,e)}),o=!!r.body.next;return{pageInfo:{hasNextPage:o,nextPage:o?r.body.page+1:null},data:r.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(n,e={}){let t=new URL(`${G}/repositories/${n.repo.namespace}/${n.repo.name}/refs/tags`);t.searchParams.set("pagelen",$.toString()),n.cursor&&t.searchParams.set("page",n.cursor);let r=await this.config.request({url:t.toString(),headers:U(this.config,e)}),o=!!r.body.next,i=null;return r.body.next&&(i=new URL(r.body.next).searchParams.get("page")),{pageInfo:{hasNextPage:o,endCursor:i},data:r.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(n={},e={}){let t=new URL(`${G}/user/workspaces`);t.searchParams.set("page",n?.page?.toString()||"1"),t.searchParams.set("pagelen","50"),n?.administrator!==void 0&&t.searchParams.set("administrator",n.administrator.toString());let r=await this.config.request({url:t.toString(),headers:U(this.config,e)}),o=!!r.body.next;return{pageInfo:{hasNextPage:o,nextPage:o?r.body.page+1:null},data:r.body.values.map(i=>({id:i.workspace.uuid,slug:i.workspace.slug}))}}async getWorkspacesForUser(n,e={}){let t=new URL(`${G}/user/permissions/workspaces`);t.searchParams.set("page",n.page?.toString()||"1"),t.searchParams.set("pagelen","50");let r=await this.config.request({url:t.toString(),headers:U(this.config,e)}),o=!!r.body.next;return{pageInfo:{hasNextPage:o,nextPage:o?r.body.page+1:null},data:r.body.values.map(i=>({id:i.workspace.uuid,slug:i.workspace.slug,name:i.workspace.name}))}}async getPullRequestsForUserAndWorkspace(n,e={}){let t=new URL(`${G}/workspaces/${n.workspaceSlug}/pullrequests/${n.userId}`);if(t.searchParams.set("fields","+values.participants,+values.destination.repository.links.clone.*,+values.source.repository.links.clone.*"),t.searchParams.set("page",n.page?.toString()||"1"),t.searchParams.set("pagelen","50"),n.repos&&n.repos.length>0){let i=`state = "open" AND (${n.repos.map(a=>`source.repository.full_name = "${a.namespace}/${a.name}"`).join(" OR ")})`;t.searchParams.set("q",i)}let r=await this.config.request({url:t.toString(),headers:U(this.config,e)}),o=!!r.body.next;return{pageInfo:{hasNextPage:o,nextPage:o?r.body.page+1:null},data:r.body.values.map(ct)}}async getPullRequestsForRepoBase(n,e={}){let t=new URL(`${G}/repositories/${encodeURI(n.repo.namespace)}/${encodeURI(n.repo.name)}/pullrequests?state=OPEN`),r=[];n.reviewerId&&r.push(`reviewers.uuid="${n.reviewerId}"`),n.authorLogin&&r.push(`author.uuid="${n.authorLogin}"`);let o='state="OPEN"';return r.length&&(o+=` AND (${r.join(n.useOrFilter?" OR ":" AND ")})`),t.searchParams.set("fields","+values.participants,+values.destination.repository.links.clone.*,+values.source.repository.links.clone.*"),t.searchParams.set("page",n.page?.toString()||"1"),t.searchParams.set("pagelen","50"),t.searchParams.set("q",o),await this.config.request({url:t.toString(),headers:U(this.config,e)})}async getPullRequestsForRepo(n,e={}){let t=[],r=await this.getPullRequestsForRepoBase(n,e);r.body.values.forEach(i=>{t.push(ct(i))});let o=!!r.body.next;return{pageInfo:{hasNextPage:o,nextPage:o?r.body.page+1:null},data:t}}async getPullRequestsForRepos(n,e={}){let t=[];return await Promise.all(n.repos.map(async r=>{try{(await this.getPullRequestsForRepoBase({repo:r,...n},e)).body.values.forEach(i=>{t.push(ct(i))})}catch(o){if(o.statusCode!==404&&o.statusCode!==401)throw o}})),{data:t}}async getAccountsForWorkspace(n,e={}){let t=new URL(`${G}/workspaces/${encodeURI(n.workspace)}/members`);t.searchParams.set("page",n.page?.toString()||"1"),t.searchParams.set("pagelen","100");let r=await this.config.request({url:t.toString(),headers:U(this.config,e)}),o=!!r.body.next;return{pageInfo:{hasNextPage:o,nextPage:o?r.body.page+1:null},data:r.body.values.map(i=>$e(i.user))}}async getReposPermissionsForCurrentUser(n,e={}){let t=new URL(`${G}/user/permissions/repositories`);t.searchParams.set("page",n.page?.toString()||"1"),t.searchParams.set("pagelen","100");let r=await this.config.request({url:t.toString(),headers:U(this.config,e)}),o=!!r.body.next;return{pageInfo:{hasNextPage:o,nextPage:o?r.body.page+1:null},data:r.body.values.reduce((i,a)=>({...i,[a.repository.uuid]:cs(a.permission)}),{})}}async decorateReposWithPermissions(n,e={}){let t={},r=1;do{let o=await this.getReposPermissionsForCurrentUser({page:r},e);t={...o.data,...t},r=o.pageInfo.hasNextPage?o.pageInfo.nextPage:null}while(r!==null);return{data:n.repos.map(o=>({...o,permissions:t[o.id]??{canCreateWebhook:!1,canPush:!1,isAdmin:!1}}))}}async closePullRequest(n,e={}){let{pullRequest:t}=n;if(!(await this.config.request({method:"POST",url:`${G}/repositories/${t.repository.owner.login}/${t.repository.name}/pullrequests/${t.id}/decline`,headers:U(this.config,e)})).body.title)throw new Error("Could not close pull request")}async mergePullRequest(n,e={}){let{pullRequest:t,mergeStrategy:r}=n,o;switch(r){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:`${G}/repositories/${t.repository.owner.login}/${t.repository.name}/pullrequests/${t.id}/merge`,body:JSON.stringify(i),headers:{...U(this.config,e),"Content-Type":"application/json"}})).body.title)throw new Error("Could not merge pull request")}async setPullRequestReviewers(n,e={}){let{pullRequest:t,reviewers:r}=n,o={reviewers:r.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:`${G}/repositories/${t.repository.owner.login}/${t.repository.name}/pullrequests/${t.id}`,body:JSON.stringify(o),headers:{...U(this.config,e),"Content-Type":"application/json"}})).body.title)throw new Error("Could not set pull request reviewers")}};var tr=s=>s?s.find(n=>n.permission==="USER_ADMIN"||n.permission==="PROJECT_ADMIN"||n.permission==="ADMIN"||n.permission==="SYS_ADMIN"||n.permission==="REPO_ADMIN")?{canCreateWebhook:!0,canPush:!0,isAdmin:!0}:s.find(n=>n.permission==="REPO_WRITE"||n.permission==="REPO_CREATE"||n.permission==="PROJECT_CREATE"||n.permission==="PROJECT_WRITE")?{canCreateWebhook:!1,canPush:!0,isAdmin:!1}:{canCreateWebhook:!1,canPush:!1,isAdmin:!1}:{canCreateWebhook:!1,canPush:!1,isAdmin:!1};var Ie=s=>{let n=s.links.self[0].href;return{name:s.displayName,email:s.emailAddress,avatarUrl:s.avatarUrl??(n&&`${n}/avatar.png`),id:s.id.toString(),username:s.name,url:n}},De=s=>{let n={OPEN:"OPEN",MERGED:"MERGED",DECLINED:"CLOSED"},e={UNAPPROVED:"REVIEW_REQUESTED",NEEDS_WORK:"CHANGES_REQUESTED",APPROVED:"APPROVED"},t=s.reviewers.map(u=>({reviewer:Ie(u.user),state:e[u.status]})),r=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:n[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:Ie(s.author.user),assignees:null,reviews:t,reviewDecision:j(t),repository:{id:s.toRef.repository.id.toString(),name:s.toRef.repository.name,owner:{login:s.toRef.repository.project.key},remoteInfo:o&&r?{cloneUrlHTTPS:o,cloneUrlSSH:r}: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}},rr=s=>({id:s.id.toString(),namespace:s.project.key,name:s.slug,webUrl:s.links.self[0]?.href??null,httpsUrl:s.links.clone.find(n=>n.name==="https"||n.name==="http")?.href??null,sshUrl:s.links.clone.find(n=>n.name==="ssh")?.href??null,defaultBranch:null,permissions:null}),le=class extends _{getBaseUrl(n){let e=n.baseUrl||this.config.baseUrl;if(!e)throw new Error('Bitbucket Server requires "baseUrl"');return e}getRequestHeaders(n){return f(n.token||this.config.token)}async getCurrentUser(n={},e={}){let t=await this.config.request({url:`${this.getBaseUrl(e)}/users?limit=2`,headers:this.getRequestHeaders(e)}),{headers:{"x-auserid":r,"x-ausername":o}}=t,i=r?parseInt(r,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:Ie(l)}}async getUserForCommit(n,e){let{repo:t,oid:r}=n,o=await this.config.request({url:`${this.getBaseUrl(e)}/projects/${t.namespace}/repos/${t.name}/commits/${r}`,headers:this.getRequestHeaders(e)});if(!o.body.author)throw new Error("Could not find user for commit");return{data:Ie(o.body.author)}}async getRepo(n,e={}){let t=await this.config.request({url:`${this.getBaseUrl(e)}/projects/${n.namespace}/repos/${n.name}`,headers:this.getRequestHeaders(e)});return{data:rr(t.body)}}async getRepos(n,e={}){let t=[],r=[];return await Promise.all(n.map(async o=>{try{let i=await this.getRepo(o,e);t.push(i.data)}catch(i){r.push({input:o,error:i})}})),{data:t,errors:r}}async getReposForCurrentUser(n,e={}){let t=n.page??0,r=await this.config.request({url:`${this.getBaseUrl(e)}/repos?start=${t}`,headers:this.getRequestHeaders(e)});return{pageInfo:{hasNextPage:!r.body.isLastPage,nextPage:r.body.nextPageStart},data:r.body.values.map(rr)}}async getRepoPermissionsForUsername(n,e={}){let t=new URL(`${this.getBaseUrl(e)}/projects/${n.repo.namespace}/repos/${n.repo.name}/permissions/search?filterText=${n.username}`);try{let r=await this.config.request({url:t.toString(),headers:this.getRequestHeaders(e)});return{data:tr(r.body.values)}}catch(r){if(r.response?.status===401)return{data:{canCreateWebhook:!1,canPush:!1,isAdmin:!1}};throw r}}async decorateReposWithPermissions(n,e={}){return await Promise.all(n.repos.map(async r=>{let o=await this.getRepoPermissionsForUsername({repo:r,username:n.username},e);return{...r,permissions:o.data}}))}async getPullRequestsForRepoBase(n,e={}){let t=new URL(`${this.getBaseUrl(e)}/projects/${encodeURI(n.repo.namespace)}/repos/${encodeURI(n.repo.name)}/pull-requests?state=OPEN`);return t.searchParams.set("start",n.page?.toString()||"0"),t.searchParams.set("limit","50"),await this.config.request({url:t.toString(),headers:this.getRequestHeaders(e)})}async getPullRequestsForRepo(n,e={}){let t=[],r=await this.getPullRequestsForRepoBase(n,e);r.body.values.forEach(i=>{if(n.authorLogin&&i.author.user.name!==n.authorLogin)return null;t.push(De(i))});let o=r.body.values.length!==0;return{pageInfo:{hasNextPage:o,nextPage:o?r.body.start+r.body.values.length:null},data:t}}async getPullRequestsForRepos(n,e={}){let t=[];return await Promise.all(n.repos.map(async r=>{try{(await this.getPullRequestsForRepoBase({repo:r,...n},e)).body.values.forEach(i=>{if(n.authorLogin&&i.author.user.name!==n.authorLogin)return null;t.push(De(i))})}catch(o){if(o.statusCode!==404&&o.statusCode!==401)throw o}})),{data:t}}async getPullRequestsForCurrentUser(n,e={}){let t=new URL(`${this.getBaseUrl(e)}/dashboard/pull-requests`);t.searchParams.set("state","OPEN"),t.searchParams.set("start",n.page?.toString()||"0"),t.searchParams.set("limit","50");let r=await this.config.request({url:t.toString(),headers:this.getRequestHeaders(e)}),o=r.body.values.length!==0;return{pageInfo:{hasNextPage:o,nextPage:o?r.body.start+r.body.values.length:null},data:r.body.values.map(De)}}async closePullRequest(n,e={}){let{pullRequest:t}=n;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(n,e={}){let{pullRequest:t,mergeStrategyId:r}=n;if(n.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:r,version:t.version}),headers:{...this.getRequestHeaders(e),"Content-Type":"application/json"}})).body.title)throw new Error("Could not merge pull request")}async getMergeStrategies(n={}){let e=await this.config.request({url:`${this.getBaseUrl(n)}/admin/pull-requests/git`,headers:{...this.getRequestHeaders(n),"Content-Type":"application/json"}});return{data:{defaultStrategy:e.body.mergeConfig.defaultStrategy,strategies:e.body.mergeConfig.strategies}}}async setPullRequestReviewers(n,e={}){let{pullRequest:t,reviewers:r}=n;if(t.version===void 0)throw new Error('Bitbucket Server requires "version" for this function.');let o={reviewers:r.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(n,e={}){let t=new URL(`${this.getBaseUrl(e)}/projects/${encodeURI(n.project)}/permissions/users`);t.searchParams.set("start",n.page?.toString()||"0"),t.searchParams.set("limit","50");let r=await this.config.request({url:t.toString(),headers:this.getRequestHeaders(e)}),o=r.body.values.length!==0;return{pageInfo:{hasNextPage:o,nextPage:o?r.body.start+r.body.values.length:null},data:r.body.values.map(i=>Ie(i.user))}}};var Rr=require("js-base64");var Le=(e=>(e.Open="OPEN",e.Closed="CLOSED",e))(Le||{});var R=class extends Error{constructor(e,t){let r=t?.map(i=>`'${i.message}'`).join(", "),o=r?`${e}: ${r}`:e;super(o);this.graphQLErrors=t??[]}};var gs={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]},sr=15,nr=100,be={__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,Q=(s,n)=>{let e=gs[n];for(let t=0;t<3;t++){if(s[t]>e[t])return!0;if(s[t]<e[t])return!1}return!0},Ae="https://api.github.com",hs=`${Ae}/graphql`,Ge=`
|
|
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
|
+
`,fs=`
|
|
11
11
|
... on CheckRun {
|
|
12
12
|
completedAt
|
|
13
13
|
conclusion
|
|
@@ -21,7 +21,7 @@ color
|
|
|
21
21
|
description
|
|
22
22
|
id
|
|
23
23
|
name
|
|
24
|
-
`,or=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.")},
|
|
24
|
+
`,or=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.")},Rs=(s,n)=>{let e=n.baseUrl||s.baseUrl;return e?(e=e.replace(/\/$/,""),or(e),Ue.test(e)&&(e=e.replace(Ue,"")),`${e}/api/graphql`):hs},B=(s,n)=>{let e=n.baseUrl||s.baseUrl;return e?(e=e.replace(/\/$/,""),or(e),Ue.test(e)&&(e=e.replace(Ue,"")),`${e}/api/v3`):Ae},b=(s,n,e)=>{let t=f(e.token||s.token);return t["X-Github-Next-Global-ID"]="1",t["Content-Type"]="application/json",t.Accept="application/vnd.github.merge-info-preview+json",s.request({url:Rs(s,e),method:"POST",headers:t,body:JSON.stringify(n)})},Is={user:!0,"user:email":!0,"read:user":!0},H=s=>s.some(n=>Is[n]),k=(s=!1,n=!1,e)=>`
|
|
25
25
|
__typename
|
|
26
26
|
${X(e,["graphQLId"],"id")}
|
|
27
27
|
${X(e,["id"],"databaseId")}
|
|
@@ -30,7 +30,7 @@ ${X(e,["name","username"],"login")}
|
|
|
30
30
|
${n?X(e,["email"],"email"):""}
|
|
31
31
|
${X(e,["avatarUrl"],`avatarUrl${s?"(size: $avatarSize)":""}`)}
|
|
32
32
|
${X(e,["url"],"url")}
|
|
33
|
-
`,
|
|
33
|
+
`,bs=(s=!1)=>`
|
|
34
34
|
latestReviews(first: 100) {
|
|
35
35
|
nodes {
|
|
36
36
|
author {
|
|
@@ -85,7 +85,7 @@ commits(last: 1) {
|
|
|
85
85
|
contexts(first: 100) {
|
|
86
86
|
totalCount
|
|
87
87
|
nodes {
|
|
88
|
-
${!e||Q(e,"CHECK_RUN")?
|
|
88
|
+
${!e||Q(e,"CHECK_RUN")?fs:""}
|
|
89
89
|
... on StatusContext {
|
|
90
90
|
context
|
|
91
91
|
createdAt
|
|
@@ -160,7 +160,7 @@ reviewRequests(first: 100) {
|
|
|
160
160
|
}
|
|
161
161
|
}
|
|
162
162
|
}
|
|
163
|
-
${!e||Q(e,"LATEST_REVIEWS")?
|
|
163
|
+
${!e||Q(e,"LATEST_REVIEWS")?bs(n):""}
|
|
164
164
|
additions
|
|
165
165
|
deletions
|
|
166
166
|
changedFiles
|
|
@@ -175,7 +175,7 @@ labels(first: 100) {
|
|
|
175
175
|
}
|
|
176
176
|
}
|
|
177
177
|
${!e||Q(e,"VIEWER_CAN_MERGE_AS_ADMIN")?"viewerCanMergeAsAdmin":""}
|
|
178
|
-
`,
|
|
178
|
+
`,ys=(s=!1,n)=>`
|
|
179
179
|
id
|
|
180
180
|
${!n||Q(n,"ISSUE_FULL_DATABASE_ID")?"fullDatabaseId":"databaseId"}
|
|
181
181
|
title
|
|
@@ -223,7 +223,7 @@ labels(first: 100) {
|
|
|
223
223
|
${Te}
|
|
224
224
|
}
|
|
225
225
|
}
|
|
226
|
-
`,
|
|
226
|
+
`,Ps={"-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"},ws=new RegExp('(([^\\s]+:)?\\"(?:[^\\"\\\\]|\\\\.)*\\"?)|([^\\"\\s]+)',"g"),gt=s=>{let n=[];return(s.match(ws)??[]).forEach(t=>{if(t.includes(":")&&t!="is:closed"){let r=t.split(":")[0];Ps[r]&&n.push(t)}}),n},ht=(s,n,e,t)=>{let r=s==="issue";return{query:`
|
|
227
227
|
query SearchIssuesOrPullRequests($query: String! $after: String) {
|
|
228
228
|
search(type:ISSUE query:$query first: ${t.maxPageSize} after:$after) {
|
|
229
229
|
pageInfo {
|
|
@@ -232,13 +232,13 @@ query SearchIssuesOrPullRequests($query: String! $after: String) {
|
|
|
232
232
|
}
|
|
233
233
|
nodes {
|
|
234
234
|
... on ${r?"Issue":"PullRequest"} {
|
|
235
|
-
${r?
|
|
235
|
+
${r?ys(t.supportsEmail,t.enterpriseVersion??null):Oe(t.supportsDrafts??!1,t.supportsEmail,t.enterpriseVersion??null)}
|
|
236
236
|
}
|
|
237
237
|
}
|
|
238
238
|
}
|
|
239
|
-
}`,variables:{query:`is:${s} is:open ${t.includeFromArchivedRepos?"":"archived:false"} ${n}`,after:e}}},
|
|
239
|
+
}`,variables:{query:`is:${s} is:open ${t.includeFromArchivedRepos?"":"archived:false"} ${n}`,after:e}}},qs="Field 'isDraft' doesn't exist on type 'PullRequest'",xe=(s=[])=>s.some(n=>n?.message===qs),vs=/@@ -(\d+)(?:,\d+ | )\+(\d+)(?:,\d+ | )@@(?:\\n)?/,Ss=`
|
|
240
240
|
\
|
|
241
|
-
+`,ar=(s,n,e,t)=>{let r=
|
|
241
|
+
+`,ar=(s,n,e,t)=>{let r=vs.exec(s);if(!r||!r[0]||!r[1])return[];let o=parseInt(r[1],10),i=parseInt(r[2],10),a=s.replace(Ss,`
|
|
242
242
|
+`).split(`
|
|
243
243
|
`).slice(1),u=o-1,l=i-1,p=a.map(g=>{let m,I;switch(g[0]){case"-":{m="DELETED",u+=1,I=`${g.slice(1)}
|
|
244
244
|
`;break}case"+":{m="ADDED",l+=1,I=`${g.slice(1)}
|
|
@@ -368,7 +368,7 @@ defaultBranchRef {
|
|
|
368
368
|
name
|
|
369
369
|
}
|
|
370
370
|
viewerPermission
|
|
371
|
-
`,
|
|
371
|
+
`,Es={APPROVED:"APPROVED",CHANGES_REQUESTED:"CHANGES_REQUESTED",COMMENTED:"COMMENTED",REVIEW_REQUESTED:"REVIEW_REQUESTED"},Cs={MERGEABLE:"MERGEABLE",CONFLICTING:"CONFLICTS",UNKNOWN:"UNKNOWN"},$s={BEHIND:"BEHIND",BLOCKED:"BLOCKED",UNKNOWN:"UNKNOWN_AND_BLOCKED",UNSTABLE:"UNSTABLE",CLEAN:null,DIRTY:null,DRAFT:null,HAS_HOOKS:null},Ds={OPEN:"OPEN",CLOSED:"CLOSED"},Ls=["ADMIN","MAINTAIN","TRIAGE","WRITE"],bt=s=>({color:`#${s.color}`,description:s.description,graphQLId:s.id,id:null,name:s.name}),Us=s=>({canCreateWebhook:s==="ADMIN",canPush:s==="ADMIN"||s==="MAINTAIN"||s==="WRITE",isAdmin:s==="ADMIN"}),Rt=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:Us(s.viewerPermission)}),As=s=>({canCreateWebhook:s.admin,canPush:s.admin||s.maintain||s.push,isAdmin:s.admin}),fr=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:As(s.permissions)}),Gs=s=>({path:s.path,isDirectory:s.type==="tree"}),Ts={OPEN:"OPEN",CLOSED:"CLOSED",MERGED:"MERGED"},Os={id:!0,graphQLId:!0,name:!0,username:!0,email:!0,avatarUrl:!0,url:!0},F=(s,n=Os)=>{let e={};return n.id&&(e.id="databaseId"in s?s.databaseId.toString():s.id),n.graphQLId&&(e.graphQLId=s.id),n.name&&(e.name=s.name??s.login),n.username&&(e.username=s.login),n.email&&(e.email=s.email??null),n.avatarUrl&&(e.avatarUrl=s.avatarUrl),n.url&&(e.url=s.url),e},xs=(s,n)=>{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"}[n]},_s=s=>({ERROR:"ERROR",EXPECTED:"PENDING",FAILURE:"FAILED",PENDING:"PENDING",SUCCESS:"SUCCESS"})[s],It=s=>{let n=null;s.author?n=s.author:n=be;let e=(s.reviewRequests?.nodes||[]).filter(O).filter(i=>!i.asCodeOwner),t=s.headRepository?.url;t&&!t.endsWith(".git")&&(t=`${t}.git`);let r=s.repository?.url;r&&!r.endsWith(".git")&&(r=`${r}.git`);let o=e.filter(i=>i.requestedReviewer&&"__typename"in i.requestedReviewer).map(i=>({reviewer:F(i.requestedReviewer),state:"REVIEW_REQUESTED"})).concat((s.latestReviews?.nodes||[]).filter(O).map(i=>{let a=be;return i.author&&i.author.__typename&&(a=i.author),{reviewer:F(a),state:Es[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:Ts[s.state],commentCount:s.comments.totalCount,upvoteCount:s.reactions.totalCount,author:n&&n.__typename?F(n):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:r,cloneUrlSSH:s.repository.sshUrl}},headRepository:s.headRepository?{id:s.headRepository.databaseId.toString(),graphQLId:s.headRepository.id,name:s.headRepository.name,owner:{login:s.headRepository.owner.login},remoteInfo:{cloneUrlHTTPS:t,cloneUrlSSH:s.headRepository.sshUrl}}:null,headCommit:{buildStatuses:s.commits.nodes?.filter(O)[0]?.commit.statusCheckRollup?.contexts.nodes?.filter(O).map(i=>"context"in i?{completedAt:null,description:i.description,name:i.context,state:_s(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:xs(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(O).map(i=>F(i)):null,reviews:o,reviewDecision:j(o),additions:s.additions,deletions:s.deletions,fileCount:s.changedFiles,commitCount:s.commits.totalCount,mergeableState:$s[s.mergeStateStatus]??Cs[s.mergeable],milestone:s.milestone?yt(s.milestone):null,labels:s.labels?.nodes?.filter(O).map(bt)??[],permissions:{canMerge:Ls.includes(s.repository.viewerPermission),canMergeAndBypassProtections:s.viewerCanMergeAsAdmin??!1}}},ks=s=>{let{id:n,comments:e,isOutdated:t,isResolved:r,line:o,startLine:i,diffSide:a,originalLine:u,originalStartLine:l,startDiffSide:p}=s,c=e.nodes?.[0];if(!c)return null;let{author:d,body:g,databaseId:m,fullDatabaseId:I,id:y,path:h,publishedAt:v,url:D}=c,x=o??u,E=i??l,P=a??p;return{author:d?{avatarUrl:d.avatarUrl,email:null,name:d.login}:null,body:g,createdAt:v?new Date(v):null,diffLines:ar(c.diffHunk,x,E,P),id:I??m.toString(),isOutdated:t,isResolved:r,graphQLId:y,threadId:n,filename:h,replies:e.nodes?.filter(O).slice(1).map(Ns)??[],url:D,line:x,startLine:E,side:P}},Ns=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}),Fs=s=>{let n=null;return s.author?n=s.author:n=be,{id:s.fullDatabaseId!==void 0?s.fullDatabaseId:s.databaseId.toString(),graphQLId:s.id,number:s.number,title:s.title,author:n&&n.__typename?F(n):null,commentCount:s.comments.totalCount,closedDate:s.closedAt?new Date(s.closedAt):null,createdDate:new Date(s.createdAt),description:null,state:{name:Ds[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(O).map(e=>F(e))??[],upvoteCount:s.reactions.totalCount,milestone:s.milestone?yt(s.milestone):null,labels:s.labels?.nodes?.filter(O).map(bt)??[]}},yt=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}),pe=class extends _{constructor(){super(...arguments);this._scopesCache={};this._enterpriseVersionsCache={}}async getScopes(e){let t=e.token||this.config.token;if(!t)return[];let r=this._scopesCache[t];if(!r){let i=(await b(this.config,{query:"query { rateLimit(dryRun: true) { __typename } }"},e)).headers["x-oauth-scopes"];r=i?i.split(", "):[],this._scopesCache[t]=r}return r}async getEnterpriseVersion(e){let t=e.baseUrl||this.config.baseUrl;if(!t)return null;let r=this._enterpriseVersionsCache[t];if(!r){let o=await this.config.request({url:`${B(this.config,e)}/meta`,headers:f(e.token||this.config.token)});if(!o.body.installed_version)return null;r=o.body.installed_version.split(".").slice(0,3).map(i=>parseInt(i,10)),this._enterpriseVersionsCache[t]=r}return r}getEnterpriseAvatarUrlIfNeeded(e,t,r){let o=r.baseUrl||this.config.baseUrl;return!o||o.startsWith(Ae)?e:t?`https://avatars.githubusercontent.com/u/e?email=${encodeURIComponent(t)}`:""}async getCurrentUser(e={},t={}){if(e.fields&&!e.fields.length)throw new Error('"fields" must contain at least one field or be omitted');let r=Wt(e.fields),o=await this.getScopes(t),i=await b(this.config,{query:`
|
|
372
372
|
query getCurrentUser {
|
|
373
373
|
viewer {
|
|
374
374
|
${k(!1,H(o),r)}
|
|
@@ -388,7 +388,7 @@ query getAccountsForRepo($owner: String!, $name: String! $cursor: String, $first
|
|
|
388
388
|
}
|
|
389
389
|
}
|
|
390
390
|
}
|
|
391
|
-
`,variables:{owner:o,name:i,cursor:a,first
|
|
391
|
+
`,variables:{owner:o,name:i,cursor:a,first:$}},t);if(!u.body.data)throw new R("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=>F(l))??[]}}async getUserForCommit(e,t={}){let r=await b(this.config,{query:`
|
|
392
392
|
query getUserForCommit(
|
|
393
393
|
$owner: String!
|
|
394
394
|
$name: String!
|
|
@@ -469,7 +469,7 @@ query getOrgsForCurrentUser($cursor: String, $first: Int!) {
|
|
|
469
469
|
}
|
|
470
470
|
}
|
|
471
471
|
}
|
|
472
|
-
`,variables:{cursor:e.cursor,first
|
|
472
|
+
`,variables:{cursor:e.cursor,first:$}},t);if(!r.body.data)throw new R("Could not fetch orgs for current user",r.body.errors);let o=r.body.data.viewer.organizations.nodes||[];return{pageInfo:r.body.data.viewer.organizations.pageInfo,data:o.map(i=>({id:i.databaseId.toString(),graphQLId:i.id,username:i.login,name:i.name||null,email:i.email||null,avatarUrl:i.avatarUrl}))}}async getOrgMembers(e,t={}){let r=await b(this.config,{query:`
|
|
473
473
|
query getOrgMember($cursor: String, $first: Int!, $login: String!) {
|
|
474
474
|
viewer {
|
|
475
475
|
organization(login: $login) {
|
|
@@ -485,7 +485,7 @@ query getOrgMember($cursor: String, $first: Int!, $login: String!) {
|
|
|
485
485
|
}
|
|
486
486
|
}
|
|
487
487
|
}
|
|
488
|
-
`,variables:{cursor:e.cursor,first
|
|
488
|
+
`,variables:{cursor:e.cursor,first:$,login:e.org}},t);if(!r.body.data?.viewer.organization?.membersWithRole&&r.body.errors?.length)throw new R("Could not read the members of the organization",r.body.errors);let o=r.body.data?.viewer.organization?.membersWithRole.nodes||[];return{pageInfo:{hasNextPage:r.body.data?.viewer.organization?.membersWithRole.pageInfo.hasNextPage??!1,endCursor:r.body.data?.viewer.organization?.membersWithRole.pageInfo.endCursor??null},data:o.map(i=>F({...i,avatarUrl:this.getEnterpriseAvatarUrlIfNeeded(i.avatarUrl,i.email,t)}))}}async getRepo(e,t={}){let r=await b(this.config,{query:`
|
|
489
489
|
query getRepo($owner: String!, $name: String!) {
|
|
490
490
|
repository(owner: $owner, name: $name) {
|
|
491
491
|
${ft}
|
|
@@ -514,7 +514,7 @@ query getReposForUsernames($query: String!, $cursor: String, $first: Int!) {
|
|
|
514
514
|
}
|
|
515
515
|
}
|
|
516
516
|
}
|
|
517
|
-
`,variables:{query:`fork:true ${e.usernames.map(i=>`user:${i}`).join(" ")}`,cursor:e.cursor,first
|
|
517
|
+
`,variables:{query:`fork:true ${e.usernames.map(i=>`user:${i}`).join(" ")}`,cursor:e.cursor,first:$}},t);if(!r.body.data)throw new R("Could not fetch repos for usernames",r.body.errors);let o=r.body.data.search.nodes||[];return{pageInfo:r.body.data.search.pageInfo,data:o.map(Rt)}}async getReposForOwners(e,t={}){return this.getReposForUsernames({usernames:e.owners.filter(r=>r.username).map(r=>r.username),cursor:e.cursor},t)}async getRefs(e,t,r={}){let o=await b(this.config,{query:`
|
|
518
518
|
query getRefs($owner: String!, $name: String!, $refPrefix: String!, $cursor: String, $first: Int!) {
|
|
519
519
|
repository(owner: $owner, name: $name) {
|
|
520
520
|
refs(refPrefix: $refPrefix first: $first after: $cursor) {
|
|
@@ -535,7 +535,7 @@ query getRefs($owner: String!, $name: String!, $refPrefix: String!, $cursor: Str
|
|
|
535
535
|
}
|
|
536
536
|
}
|
|
537
537
|
}
|
|
538
|
-
`,variables:{owner:t.repo.namespace,name:t.repo.name,refPrefix:e,cursor:t.cursor,first
|
|
538
|
+
`,variables:{owner:t.repo.namespace,name:t.repo.name,refPrefix:e,cursor:t.cursor,first:$}},r),i=o.body.data?.repository;if(!i)throw new R("Ref repository not found.",o.body.errors);let a=i.refs;return a?{pageInfo:a.pageInfo,data:(a.nodes||[]).map(u=>{let l=u.target?.oid?u.target:null;return{name:u.name,commit:l?{oid:l.oid,authoredDate:new Date(l.authoredDate),committedDate:new Date(l.committedDate)}:null}})}:{pageInfo:{endCursor:null,hasNextPage:!1},data:[]}}async getBranches(e,t={}){return this.getRefs("refs/heads/",e,t)}async getTags(e,t={}){return this.getRefs("refs/tags/",e,t)}async getBlame(e,t={}){let r=await b(this.config,{query:`
|
|
539
539
|
query getBlame($owner: String!, $name: String!, $ref: String!, $path: String!) {
|
|
540
540
|
repository(owner: $owner, name: $name) {
|
|
541
541
|
object(expression: $ref) {
|
|
@@ -574,7 +574,7 @@ query getBlame($owner: String!, $name: String!, $ref: String!, $path: String!) {
|
|
|
574
574
|
}
|
|
575
575
|
}
|
|
576
576
|
}
|
|
577
|
-
`,variables:{owner:e.repo.namespace,name:e.repo.name,ref:e.ref,path:e.path}},t),o=r.body.data?.repository;if(!o)throw new R("Blame repository not found.",r.body.errors);let i=o.object;if(!i||!("blame"in i))throw new R("Ref not found.",r.body.errors);if(i.blame.ranges.length===0)throw new R("File not found.",r.body.errors);return{data:{ranges:i.blame.ranges.map(a=>({startingLine:a.startingLine,endingLine:a.endingLine,commit:{oid:a.commit.oid,parentOids:a.commit.parents.nodes?.map(u=>u.oid)||[],authoredDate:new Date(a.commit.authoredDate),author:a.commit.author?{name:a.commit.author.name,email:a.commit.author.email,avatarUrl:a.commit.author.avatarUrl}:null,committedDate:new Date(a.commit.committedDate),committer:a.commit.committer?{name:a.commit.committer.name,email:a.commit.committer.email,avatarUrl:a.commit.committer.avatarUrl}:null,message:a.commit.message,fileCount:a.commit.changedFilesIfAvailable,additions:a.commit.additions,deletions:a.commit.deletions}}))}}}async getFileContents(e,t={}){let r=await this.config.request({url:`${B(this.config,t)}/repos/${e.repo.namespace}/${e.repo.name}/contents/${encodeURIComponent(e.path)}?ref=${e.ref}`,headers:{...f(t.token||this.config.token),Accept:"application/vnd.github.raw+json"}});if(r.headers["content-type"].startsWith("application/json"))throw new Error(`GitHub: got directory when fetching "${e.path}", getFileContents does not support fetching directories`);if(!r.headers["content-type"].startsWith("application/vnd.github.raw+json"))throw new Error(`GitHub: unsupported content type "${r.headers["content-type"]}" when fetching "${e.path}"`);return{data:new Blob([r.body])}}async getMergeBase(e,t={}){return{data:(await this.config.request({url:`${B(this.config,t)}/repos/${e.repo.namespace}/${e.repo.name}/compare/${encodeURIComponent(e.base)}...${encodeURIComponent(e.head)}`,headers:f(t.token||this.config.token)})).body.merge_base_commit.sha}}async getPullRequestDiff(e,t={}){return(await this.config.request({url:`${B(this.config,t)}/repos/${e.repo.namespace}/${e.repo.name}/pulls/${e.pullRequestId}`,headers:{...f(t.token||this.config.token),Accept:"application/vnd.github.diff"}})).body??""}async searchPullRequests(e,t={}){let r=await this.getEnterpriseVersion(t),o=await this.getScopes(t),i=H(o),a=p=>{let c=p&&typeof e.isDraft=="boolean"?`${e.query} draft:${e.isDraft}`:e.query;return ht("pr",c,e.cursor,{maxPageSize:e.maxPageSize??sr,supportsEmail:i,supportsDrafts:p,enterpriseVersion:r,includeFromArchivedRepos:e.includeFromArchivedRepos})},u=await b(this.config,a(!0),t);u.body.errors&&xe(u.body.errors)&&(this.config.baseUrl||t.baseUrl)&&(u=await b(this.config,a(!1),t));let{data:l}=u.body;if(!l)throw new R("Could not search pull requests",u.body.errors);return{pageInfo:{hasNextPage:l.search.pageInfo.hasNextPage,endCursor:l.search.pageInfo.endCursor},data:l.search.nodes?.filter(O).map(It)||[]}}async searchIssues(e,t={}){let r=await this.getEnterpriseVersion(t),o=await this.getScopes(t),i=H(o),a=await b(this.config,ht("issue",e.query,e.cursor,{supportsEmail:i,includeFromArchivedRepos:e.includeFromArchivedRepos,maxPageSize:e.maxPageSize??nr,enterpriseVersion:r}),t),{data:u}=a.body;if(!u)throw new R("Could not search issues",a.body.errors);return{pageInfo:{hasNextPage:u.search.pageInfo.hasNextPage,endCursor:u.search.pageInfo.endCursor},data:u.search.nodes?.filter(O).map(
|
|
577
|
+
`,variables:{owner:e.repo.namespace,name:e.repo.name,ref:e.ref,path:e.path}},t),o=r.body.data?.repository;if(!o)throw new R("Blame repository not found.",r.body.errors);let i=o.object;if(!i||!("blame"in i))throw new R("Ref not found.",r.body.errors);if(i.blame.ranges.length===0)throw new R("File not found.",r.body.errors);return{data:{ranges:i.blame.ranges.map(a=>({startingLine:a.startingLine,endingLine:a.endingLine,commit:{oid:a.commit.oid,parentOids:a.commit.parents.nodes?.map(u=>u.oid)||[],authoredDate:new Date(a.commit.authoredDate),author:a.commit.author?{name:a.commit.author.name,email:a.commit.author.email,avatarUrl:a.commit.author.avatarUrl}:null,committedDate:new Date(a.commit.committedDate),committer:a.commit.committer?{name:a.commit.committer.name,email:a.commit.committer.email,avatarUrl:a.commit.committer.avatarUrl}:null,message:a.commit.message,fileCount:a.commit.changedFilesIfAvailable,additions:a.commit.additions,deletions:a.commit.deletions}}))}}}async getFileContents(e,t={}){let r=await this.config.request({url:`${B(this.config,t)}/repos/${e.repo.namespace}/${e.repo.name}/contents/${encodeURIComponent(e.path)}?ref=${e.ref}`,headers:{...f(t.token||this.config.token),Accept:"application/vnd.github.raw+json"}});if(r.headers["content-type"].startsWith("application/json"))throw new Error(`GitHub: got directory when fetching "${e.path}", getFileContents does not support fetching directories`);if(!r.headers["content-type"].startsWith("application/vnd.github.raw+json"))throw new Error(`GitHub: unsupported content type "${r.headers["content-type"]}" when fetching "${e.path}"`);return{data:new Blob([r.body])}}async getMergeBase(e,t={}){return{data:(await this.config.request({url:`${B(this.config,t)}/repos/${e.repo.namespace}/${e.repo.name}/compare/${encodeURIComponent(e.base)}...${encodeURIComponent(e.head)}`,headers:f(t.token||this.config.token)})).body.merge_base_commit.sha}}async getPullRequestDiff(e,t={}){return(await this.config.request({url:`${B(this.config,t)}/repos/${e.repo.namespace}/${e.repo.name}/pulls/${e.pullRequestId}`,headers:{...f(t.token||this.config.token),Accept:"application/vnd.github.diff"}})).body??""}async searchPullRequests(e,t={}){let r=await this.getEnterpriseVersion(t),o=await this.getScopes(t),i=H(o),a=p=>{let c=p&&typeof e.isDraft=="boolean"?`${e.query} draft:${e.isDraft}`:e.query;return ht("pr",c,e.cursor,{maxPageSize:e.maxPageSize??sr,supportsEmail:i,supportsDrafts:p,enterpriseVersion:r,includeFromArchivedRepos:e.includeFromArchivedRepos})},u=await b(this.config,a(!0),t);u.body.errors&&xe(u.body.errors)&&(this.config.baseUrl||t.baseUrl)&&(u=await b(this.config,a(!1),t));let{data:l}=u.body;if(!l)throw new R("Could not search pull requests",u.body.errors);return{pageInfo:{hasNextPage:l.search.pageInfo.hasNextPage,endCursor:l.search.pageInfo.endCursor},data:l.search.nodes?.filter(O).map(It)||[]}}async searchIssues(e,t={}){let r=await this.getEnterpriseVersion(t),o=await this.getScopes(t),i=H(o),a=await b(this.config,ht("issue",e.query,e.cursor,{supportsEmail:i,includeFromArchivedRepos:e.includeFromArchivedRepos,maxPageSize:e.maxPageSize??nr,enterpriseVersion:r}),t),{data:u}=a.body;if(!u)throw new R("Could not search issues",a.body.errors);return{pageInfo:{hasNextPage:u.search.pageInfo.hasNextPage,endCursor:u.search.pageInfo.endCursor},data:u.search.nodes?.filter(O).map(Fs)||[]}}async getPullRequestsAssociatedWithUser(e,t={}){let r=[`involves:${e.username}`];return e.repos?.length&&e.repos.forEach(o=>{r.push(`repo:${o.namespace}/${o.name}`)}),e.labelNames&&e.labelNames.forEach(o=>{r.push(`label:"${o}"`)}),this.searchPullRequests({query:r.join(" "),cursor:e.cursor,includeFromArchivedRepos:e.includeFromArchivedRepos,maxPageSize:e.maxPageSize},t)}async getPullRequestsForRepos(e,t={}){let{assigneeLogins:r,updatedBefore:o,authorLogin:i,repos:a,reviewRequestedLogin:u,startQuery:l,mentionLogin:p,labelNames:c,maxPageSize:d}=e,g=gt(l||"");return a.forEach(m=>{g.push(`repo:${m.namespace}/${m.name}`)}),r&&r.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}`),c&&c.forEach(m=>{g.push(`label:"${m}"`)}),this.searchPullRequests({query:`sort:updated ${g.join(" ")}`,isDraft:e.isDraft,cursor:e.cursor,includeFromArchivedRepos:e.includeFromArchivedRepos,maxPageSize:d},t)}async getPullRequestForRepo(e,t={}){let r=await this.getEnterpriseVersion(t),o=await this.getScopes(t),i=H(o),a=c=>({query:`query getPullRequest(
|
|
578
578
|
$owner: String!
|
|
579
579
|
$name: String!
|
|
580
580
|
$number: Int!
|
|
@@ -798,7 +798,7 @@ query getBlame($owner: String!, $name: String!, $ref: String!, $path: String!) {
|
|
|
798
798
|
}
|
|
799
799
|
}
|
|
800
800
|
}
|
|
801
|
-
}`,l=await b(this.config,{query:u,variables:{namespace:o,name:i,pullRequestId:a}},t),p=l.body.data?.repository.pullRequest.reviewThreads.nodes?.filter(O).reduce((d,g)=>{if(!g.comments.nodes?.[0]?.pullRequestReview)return d;let m=g.comments.nodes[0].pullRequestReview,I=
|
|
801
|
+
}`,l=await b(this.config,{query:u,variables:{namespace:o,name:i,pullRequestId:a}},t),p=l.body.data?.repository.pullRequest.reviewThreads.nodes?.filter(O).reduce((d,g)=>{if(!g.comments.nodes?.[0]?.pullRequestReview)return d;let m=g.comments.nodes[0].pullRequestReview,I=ks(g);return I&&(d[m.id]||(d[m.id]=[]),d[m.id].push(I)),d},{})??{};return{data:l.body.data?.repository.pullRequest.reviews.nodes?.filter(O).filter(d=>p[d.id]).map(d=>({author:d.author?{avatarUrl:d.author.avatarUrl,email:null,name:d.author.login}:null,body:d.body,createdAt:d.publishedAt?new Date(d.publishedAt):null,id:d.fullDatabaseId??d.databaseId.toString(),graphQLId:d.id,reviewComments:p[d.id],url:d.url}))??[]}}async getCommentsForPullRequest(e,t={}){let r=await this.getEnterpriseVersion(t),o=!r||Q(r,"ISSUE_FULL_DATABASE_ID"),{repo:{namespace:i,name:a},pullRequestNumber:u,cursor:l}=e,p=await b(this.config,{query:hr(o),variables:{namespace:i,name:a,pullRequestNumber:u,cursor:l,first:$}},t),c=p.body.data?.repository;if(!c)throw new R("Could not fetch pull request comments",p.body.errors);return{data:c.pullRequest.comments.nodes?.filter(O).map(ur)??[],pageInfo:c.pullRequest.comments.pageInfo}}async getIssuesAssociatedWithUser(e,t={}){let[r,o]=e.cursor?.split(";")||[void 0,void 0],i=[];e.labelNames&&e.labelNames.forEach(d=>{i.push(`label:"${d}"`)});let[a,u]=await Promise.all([r==="null"?null:this.searchIssues({query:`author:${e.username} ${i.join(" ")}`,cursor:r,includeFromArchivedRepos:e.includeFromArchivedRepos,maxPageSize:e.maxPageSize},t),o==="null"?null:this.searchIssues({query:`assignee:${e.username} ${i.join(" ")}`,cursor:o,includeFromArchivedRepos:e.includeFromArchivedRepos,maxPageSize:e.maxPageSize},t)]),l={},p=[],c=d=>{l[d.id]||(l[d.id]=!0,p.push(d))};return a?.data.forEach(c),u?.data.forEach(c),{pageInfo:{hasNextPage:a?.pageInfo.hasNextPage||u?.pageInfo.hasNextPage||!1,endCursor:`${a?.pageInfo.hasNextPage&&a?.pageInfo.endCursor||"null"};${u?.pageInfo.hasNextPage&&u?.pageInfo.endCursor||"null"}`},data:p}}async setPullRequestLabels(e,t={}){let{pullRequest:r,labels:o}=e;if(!r.graphQLId)throw new Error('GitHub requires "graphQLId" for this function.');let i=`mutation SetPullRequestLabels($pullRequestGraphQLId: ID!, $labelGraphQLIds: [ID!]) {
|
|
802
802
|
updatePullRequest(input: { pullRequestId: $pullRequestGraphQLId, labelIds: $labelGraphQLIds }) {
|
|
803
803
|
pullRequest {
|
|
804
804
|
id
|
|
@@ -854,7 +854,7 @@ query getLabelsForRepo($owner: String!, $name: String! $cursor: String, $first:
|
|
|
854
854
|
}
|
|
855
855
|
}
|
|
856
856
|
}
|
|
857
|
-
`,variables:{owner:r,name:o,cursor:i,first
|
|
857
|
+
`,variables:{owner:r,name:o,cursor:i,first:$}},t);if(!a.body.data)throw new R("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(yt)??[]}}async getLabelsForRepo(e,t={}){let{repo:{namespace:r,name:o},cursor:i}=e,a=await b(this.config,{query:`
|
|
858
858
|
query getLabelsForRepo($owner: String!, $name: String! $cursor: String, $first: Int!) {
|
|
859
859
|
repository(owner: $owner, name: $name) {
|
|
860
860
|
labels(first: $first, after: $cursor) {
|
|
@@ -868,7 +868,7 @@ query getLabelsForRepo($owner: String!, $name: String! $cursor: String, $first:
|
|
|
868
868
|
}
|
|
869
869
|
}
|
|
870
870
|
}
|
|
871
|
-
`,variables:{owner:r,name:o,cursor:i,first
|
|
871
|
+
`,variables:{owner:r,name:o,cursor:i,first:$}},t);if(!a.body.data)throw new R("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(bt)??[]}}async getTreeForRepo(e,t={}){let r=await this.config.request({url:`${B(this.config,t)}/repos/${e.repo.namespace}/${e.repo.name}/git/trees/${e.branch}?recursive=1`,headers:{...f(t.token||this.config.token)}});if(!r.body)throw new Error("Could not fetch trees");return{data:r.body.tree.map(Gs)}}};var js="https://gitlab.com/api/v4",Qs="https://gitlab.com/api/graphql",Pt=/\/api\/v\d+$/,Ir=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.")},L=(s,n)=>{let e=n.baseUrl||s.baseUrl;return e?(e=e.replace(/\/$/,""),Ir(e),Pt.test(e)||(e=e+"/api/v4"),e):js},Bs=(s,n)=>{let e=n.baseUrl||s.baseUrl;return e?(e=e.replace(/\/$/,""),Ir(e),Pt.test(e)&&(e=e.replace(Pt,"")),`${e}/api/graphql`):Qs},q=(s,n,e)=>{let t=f(e.token||s.token);return s.request({url:Bs(s,e),method:"POST",headers:{...t,"Content-Type":"application/json"},body:JSON.stringify(n)})},ye=s=>s?.map(n=>`"${n.message}"`).join(", ");var Lt=s=>s.split("/").slice(0,-1).join("/"),Ut=s=>s.split("/").at(-1)??"",br=s=>{let n=parseInt(`${s["x-next-page"]}`,10);return Number.isNaN(n)?{hasNextPage:!1,nextPage:null}:{hasNextPage:!0,nextPage:n}},_e=s=>({id:s.id.replace(de,""),graphQLId:s.id,namespace:Lt(s.fullPath),name:Ut(s.fullPath),webUrl:s.webUrl}),ke=s=>({id:s.id.replace(de,""),graphQLId:s.id,httpsUrl:s.httpUrlToRepo,namespace:Lt(s.fullPath),name:Ut(s.fullPath),sshUrl:s.sshUrlToRepo,webUrl:s.webUrl}),Ms={assigned:"assignedMergeRequests",authored:"authoredMergeRequests",reviewRequested:"reviewRequestedMergeRequests"},zs={CAN_BE_MERGED:"MERGEABLE",CANNOT_BE_MERGED:"CONFLICTS",CANNOT_BE_MERGED_RECHECK:"UNKNOWN",UNCHECKED:"UNKNOWN",CHECKING:"UNKNOWN"};var Pr="gid://gitlab/User/",de="gid://gitlab/Project/",Hs="gid://gitlab/MergeRequest/",Ws="gid://gitlab/Issue/",Js="gid://gitlab/ProjectLabel/",Vs="gid://gitlab/Milestone/",Ks="gid://gitlab/Ci::Build/",At=`
|
|
872
872
|
description
|
|
873
873
|
dueDate
|
|
874
874
|
id
|
|
@@ -933,7 +933,7 @@ webUrl
|
|
|
933
933
|
milestone {
|
|
934
934
|
${At}
|
|
935
935
|
}
|
|
936
|
-
`,
|
|
936
|
+
`,Xs=`
|
|
937
937
|
stages {
|
|
938
938
|
nodes {
|
|
939
939
|
jobs {
|
|
@@ -999,14 +999,14 @@ labels {
|
|
|
999
999
|
}
|
|
1000
1000
|
${s?"project { id httpUrlToRepo fullPath sshUrlToRepo webUrl archived } sourceProject { id httpUrlToRepo fullPath sshUrlToRepo webUrl }":""}
|
|
1001
1001
|
${n?`milestone { ${At} }`:""}
|
|
1002
|
-
${e?`headPipeline { ${
|
|
1003
|
-
`,T=s=>`${s.namespace}/${s.name}`,
|
|
1002
|
+
${e?`headPipeline { ${Xs} }`:""}
|
|
1003
|
+
`,T=s=>`${s.namespace}/${s.name}`,Zs=s=>`${s.namespace}/${s.name}`,Ys=s=>/Field '[^']+' (?:doesn'?t|does not) exist on type|Field '[^']+' is not defined|undefined field '[^']+' on type/i.test(s.message),en=s=>({canCreateWebhook:s.adminOperations,canPush:s.pushCode,isAdmin:s.adminOperations}),St=s=>({id:s.id.replace(de,""),graphQLId:s.id,namespace:Lt(s.fullPath),name:Ut(s.fullPath),webUrl:s.webUrl,httpsUrl:s.httpUrlToRepo,sshUrl:s.sshUrlToRepo,defaultBranch:s.repository?.rootRef?{name:s.repository.rootRef}:null,permissions:en(s.userPermissions)}),tn=s=>({path:s.path,isDirectory:s.type==="tree"}),rn={opened:"OPEN",merged:"MERGED",closed:"CLOSED"},Ne=(s,n,e)=>!n&&s?.startsWith("/")?`https://gitlab.com${s}`:n&&s?.startsWith("/")&&e?`${e.replace(/\/+?$/,"")}${s}`:s,J=(s,n,e)=>{let t=Ne(s.avatarUrl,n,e);return{id:s.id.replace(Pr,""),graphQLId:s.id,name:s.name,username:s.username,email:s.publicEmail??null,avatarUrl:t,url:s.webUrl}},Tt=s=>({color:s.color,description:s.description,id:s.id.replace(Js,""),graphQLId:s.id,name:s.title}),sn=(s,n)=>s?s==="FAILED"&&n?"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,nn=(s,n,e)=>{let t={APPROVED:"APPROVED",REQUESTED_CHANGES:"CHANGES_REQUESTED",REVIEWED:"COMMENTED",UNAPPROVED:"REVIEW_REQUESTED",UNREVIEWED:"REVIEW_REQUESTED"};return{reviewer:J(s,n,e),state:s.mergeRequestInteraction?.reviewState?t[s.mergeRequestInteraction.reviewState]:"REVIEW_REQUESTED"}},Et=(s,n,e,t,r)=>{let o=s.reviewers?.nodes?s.reviewers.nodes.map(i=>nn(i,t,r)):null;return{id:s.id.replace(Hs,""),graphQLId:s.id,title:s.title,description:s.description,number:parseInt(s.iid,10),state:rn[s.state],commentCount:s.userNotesCount||0,upvoteCount:s.upvotes,author:s.author?J(s.author,t,r):null,createdDate:new Date(s.createdAt),isDraft:s.draft,repository:{id:n.id,graphQLId:n.graphQLId,name:n.name,owner:{login:n.namespace},remoteInfo:n.httpsUrl&&n.sshUrl?{cloneUrlHTTPS:n.httpsUrl,cloneUrlSSH:n.sshUrl}:null},headRepository:e?{id:e.id,graphQLId:e.graphQLId,name:e.name,owner:{login:e.namespace},remoteInfo:{cloneUrlHTTPS:e.httpsUrl,cloneUrlSSH:e.sshUrl}}:null,headCommit:{buildStatuses: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:sn(a.status,a.allowFailure),stage:i.name??null,startedAt:new Date(a.createdAt),url:`${n.webUrl}/-/jobs/${a.id.replace(Ks,"")}`}))??[])??[]},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=>J(i,t,r)):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:zs[s.mergeStatusEnum],milestone:s.milestone?Ot(s.milestone,n.webUrl):null,labels:s.labels?.nodes?.map(Tt)??[],permissions:null}},Ct=(s,n,e,t)=>({author:J(s.author,e,t),assignees:s.assignees.nodes.map(r=>J(r,e,t)),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(Ws,""),labels:s.labels?.nodes?.map(Tt)??[],number:s.iid,repository:{id:n.id.replace(de,""),graphQLId:n.id,name:n.name,owner:{login:n.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?Ot(s.milestone,n.webUrl):null}),Ot=(s,n)=>({id:s.id.replace(Vs,""),graphQLId:s.id,number:parseInt(s.iid,10),title:s.title,description:s.description,isOpen:s.state==="active",url:`${n}/-/${s.webPath.replace(/.+?\/-\//,"")}`,startDate:s.startDate?new Date(s.startDate):null,dueDate:s.dueDate?new Date(s.dueDate):null}),on=s=>Buffer.from(JSON.stringify(s),"utf8").toString("base64"),an=(s,n)=>{if(!s)return{page:1,perPage:n};try{let e=JSON.parse(Buffer.from(s,"base64").toString("utf8")),t=typeof e.page=="number"&&e.page>0?e.page:1,r=typeof e.perPage=="number"&&e.perPage>0?e.perPage:n;return{page:t,perPage:r}}catch{return{page:1,perPage:n}}},un=(s,n,e)=>({id:s.id.toString(),graphQLId:`${Pr}${s.id}`,name:s.name,username:s.username,email:s.email??null,avatarUrl:Ne(s.avatar_url,n,e),url:s.web_url}),yr=(s,n,e)=>({avatarUrl:Ne(s.avatar_url,n,e)??"",email:null,name:s.name}),ln=s=>s?.new_line!=null?"RIGHT":s?.old_line!=null?"LEFT":null,pn=s=>{let n=s.old_path||s.new_path,e=s.new_path||s.old_path,t=[`diff --git a/${n} b/${e}`];return s.new_file&&s.b_mode?t.push(`new file mode ${s.b_mode}`):s.deleted_file&&s.a_mode?t.push(`deleted file mode ${s.a_mode}`):s.a_mode&&s.b_mode&&s.a_mode!==s.b_mode&&(t.push(`old mode ${s.a_mode}`),t.push(`new mode ${s.b_mode}`)),s.renamed_file&&(t.push(`rename from ${s.old_path}`),t.push(`rename to ${s.new_path}`)),s.diff&&s.diff.length>0?(t.push(`--- ${s.new_file?"/dev/null":`a/${n}`}`),t.push(`+++ ${s.deleted_file?"/dev/null":`b/${e}`}`),`${t.join(`
|
|
1004
1004
|
`)}
|
|
1005
1005
|
${s.diff.endsWith(`
|
|
1006
1006
|
`)?s.diff:`${s.diff}
|
|
1007
1007
|
`}`):`${t.join(`
|
|
1008
1008
|
`)}
|
|
1009
|
-
`},
|
|
1009
|
+
`},wr="|",Dt=(s,n,e,t)=>[s,n,e.toString(),t.toString()].join(wr),dn=s=>{let n=s.split(wr);if(n.length!==4)throw new Error("Invalid GitLab comment ID format \u2014 expected a composite ID produced by getCommentsForPullRequest or addInlineCommentToPullRequest.");return{namespace:n[0],name:n[1],mergeRequestIid:n[2],noteId:n[3]}},$t=(s,n,e,t)=>({author:s.author?un(s.author,n,e):null,body:s.body,createdAt:s.created_at?new Date(s.created_at):null,id:Dt(t.namespace,t.name,t.mergeRequestIid,s.id),url:""}),ce=class extends _{getIsSelfHosted(n){return!!n.baseUrl||!!this.config.baseUrl}async getCurrentUser(n={},e={}){let r=(await q(this.config,{query:`
|
|
1010
1010
|
query getCurrentUser {
|
|
1011
1011
|
currentUser {
|
|
1012
1012
|
${W}
|
|
@@ -1090,7 +1090,7 @@ query getReposForCurrentUser($after: String) {
|
|
|
1090
1090
|
}
|
|
1091
1091
|
}
|
|
1092
1092
|
}
|
|
1093
|
-
`,variables:{after:n.cursor}},e);if(!t.body.data?.projects)throw new Error(ye(t.body.errors)||t.statusText||"Unknown error");let r=t.body.data?.projects?.nodes||[];return{pageInfo:t.body.data?.projects?.pageInfo,data:r.map(St)}}async getRefs(n,e,t={}){let r=T(e.repo),o=new URL(`${L(this.config,t)}/projects/${encodeURIComponent(r)}/repository/${n}`);o.searchParams.set("page",e.page?.toString()||"1"),o.searchParams.set("per_page"
|
|
1093
|
+
`,variables:{after:n.cursor}},e);if(!t.body.data?.projects)throw new Error(ye(t.body.errors)||t.statusText||"Unknown error");let r=t.body.data?.projects?.nodes||[];return{pageInfo:t.body.data?.projects?.pageInfo,data:r.map(St)}}async getGroupsForCurrentUser(n={},e={}){let t=new URL(`${L(this.config,e)}/groups`);t.searchParams.set("top_level_only",(n.topLevelOnly??!0).toString()),t.searchParams.set("page",n.page?.toString()||"1"),t.searchParams.set("per_page",$.toString());let r=await this.config.request({url:t.toString(),headers:f(e.token||this.config.token)});return{pageInfo:br(r.headers),data:r.body.map(o=>({id:o.id.toString(),path:o.path,fullPath:o.full_path,name:o.name,webUrl:o.web_url}))}}async getRefs(n,e,t={}){let r=T(e.repo),o=new URL(`${L(this.config,t)}/projects/${encodeURIComponent(r)}/repository/${n}`);o.searchParams.set("page",e.page?.toString()||"1"),o.searchParams.set("per_page",$.toString());let i=await this.config.request({url:o.toString(),headers:f(t.token||this.config.token)});return{pageInfo:br(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(n,e={}){return this.getRefs("branches",n,e)}async getTags(n,e={}){return this.getRefs("tags",n,e)}async getBlame(n,e={}){let t=T(n.repo),r=new URL(`${L(this.config,e)}/projects/${encodeURIComponent(t)}/repository/files/${encodeURIComponent(n.path)}/blame`);r.searchParams.set("ref",n.ref);let o=await this.config.request({url:r.toString(),headers:f(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(n,e={}){let t="";n.repo?.id?t=`projectId:"${n.repo.id}"`:n.repo?.namespace&&n.repo?.name&&(t=`projectPath:"${n.repo.namespace}/${n.repo.name}"`);let r=Ms[n.association],o=await q(this.config,{query:`
|
|
1094
1094
|
query getPullRequestsForUser($username: String! $cursor: String $labelNames: [String!]) {
|
|
1095
1095
|
user(username: $username) {
|
|
1096
1096
|
${r}(state:opened first:100 after:$cursor labels: $labelNames${t?` ${t}`:""}) {
|
|
@@ -1199,7 +1199,7 @@ query getPullRequestsForRepo(
|
|
|
1199
1199
|
id
|
|
1200
1200
|
}
|
|
1201
1201
|
}
|
|
1202
|
-
}`;if(!(await q(this.config,{query:i,variables:{fullPath:`${t.repository.owner.login}/${t.repository.name}`,pullRequestId:t.number.toString(),labelGraphQLIds:o}},e)).body.data?.mergeRequestSetLabels?.mergeRequest?.id)throw new Error("Could not set pull request labels")}async getIssue(n,e={}){let t=
|
|
1202
|
+
}`;if(!(await q(this.config,{query:i,variables:{fullPath:`${t.repository.owner.login}/${t.repository.name}`,pullRequestId:t.number.toString(),labelGraphQLIds:o}},e)).body.data?.mergeRequestSetLabels?.mergeRequest?.id)throw new Error("Could not set pull request labels")}async getIssue(n,e={}){let t=Zs(n),r=await q(this.config,{query:`
|
|
1203
1203
|
query GetSingleIssue($projectId: ID!, $issueNumber: String!) {
|
|
1204
1204
|
project(fullPath: $projectId) {
|
|
1205
1205
|
id
|
|
@@ -1337,7 +1337,7 @@ query getLabelsForRepo(
|
|
|
1337
1337
|
}
|
|
1338
1338
|
}
|
|
1339
1339
|
}
|
|
1340
|
-
`,variables:{fullPath:`${t}/${r}`,after:o}},e);return{pageInfo:i.body.data?.project?.labels?.pageInfo??{endCursor:null,hasNextPage:!1},data:i.body.data?.project?.labels?.nodes?.map(Tt)??[]}}async getTreeForRepo(n,e={}){let t=T(n.repo),r=new URL(n.cursor??`${L(this.config,e)}/projects/${encodeURIComponent(t)}/repository/tree`);r.searchParams.set("per_page","10000"),r.searchParams.set("recursive","true"),r.searchParams.set("pagination","keyset"),r.searchParams.set("ref",n.branch);let o=await this.config.request({url:r.toString(),headers:f(e.token||this.config.token)}),i=o.headers.link;return{data:o.body.map(
|
|
1340
|
+
`,variables:{fullPath:`${t}/${r}`,after:o}},e);return{pageInfo:i.body.data?.project?.labels?.pageInfo??{endCursor:null,hasNextPage:!1},data:i.body.data?.project?.labels?.nodes?.map(Tt)??[]}}async getTreeForRepo(n,e={}){let t=T(n.repo),r=new URL(n.cursor??`${L(this.config,e)}/projects/${encodeURIComponent(t)}/repository/tree`);r.searchParams.set("per_page","10000"),r.searchParams.set("recursive","true"),r.searchParams.set("pagination","keyset"),r.searchParams.set("ref",n.branch);let o=await this.config.request({url:r.toString(),headers:f(e.token||this.config.token)}),i=o.headers.link;return{data:o.body.map(tn),pageInfo:{endCursor:i?i.substring(1,i.indexOf(">")):null,hasNextPage:!!i}}}async getPullRequestForRepo(n,e={}){let t=T(n.repo),o=(await q(this.config,{query:`
|
|
1341
1341
|
query getPullRequestForRepo($fullPath: ID!, $iid: String!) {
|
|
1342
1342
|
project(fullPath: $fullPath) {
|
|
1343
1343
|
id
|
|
@@ -1358,15 +1358,15 @@ query getPullRequestForRepo($fullPath: ID!, $iid: String!) {
|
|
|
1358
1358
|
}
|
|
1359
1359
|
}
|
|
1360
1360
|
}
|
|
1361
|
-
`,variables:{fullPath:t,iid:n.number.toString()}},e)).body.data?.project,i=o?.mergeRequest;if(!o||!i)return{data:null};let a=ke(o),u=i.sourceProject?ke(i.sourceProject):null;return{data:Et(i,a,u,this.getIsSelfHosted(e),this.config.baseUrl??e.baseUrl)}}getMergeRequestUrl(n,e,t){let r=T(n);return`${L(this.config,t)}/projects/${encodeURIComponent(r)}/merge_requests/${e}`}async getPullRequestDescription(n,e={}){try{return{data:{description:(await this.config.request({url:this.getMergeRequestUrl(n.repo,n.number,e),headers:f(e.token||this.config.token)})).body?.description??""}}}catch{return{data:{description:null}}}}async setPullRequestDescription(n,e={}){return{data:{description:(await this.config.request({method:"PUT",url:this.getMergeRequestUrl(n.repo,n.number,e),headers:{...f(e.token||this.config.token),"Content-Type":"application/json"},body:JSON.stringify({description:n.description})})).body?.description??n.description}}}async getFileContents(n,e={}){let t=T(n.repo),r=new URL(`${L(this.config,e)}/projects/${encodeURIComponent(t)}/repository/files/${encodeURIComponent(n.path)}/raw`);r.searchParams.set("ref",n.ref);let o=await this.config.request({url:r.toString(),headers:f(e.token||this.config.token)});return{data:new Blob([o.body])}}async getCommentsForPullRequest(n,e={}){let t=T(n.repo),{page:r,perPage:o}=on(n.cursor,D),i=new URL(`${L(this.config,e)}/projects/${encodeURIComponent(t)}/merge_requests/${n.pullRequestNumber}/notes`);i.searchParams.set("page",r.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:n.repo.namespace,name:n.repo.name,mergeRequestIid:n.pullRequestNumber},c=a.body.filter(m=>!m.system&&!m.position).map(m=>$t(m,u,l,p)),d=!!a.headers["x-next-page"],g=d?nn({page:r+1,perPage:o}):null;return{data:c,pageInfo:{endCursor:g,hasNextPage:d}}}async getReviewsForPullRequest(n,e={}){let t=T(n.repo),r=this.getIsSelfHosted(e),o=this.config.baseUrl??e.baseUrl,i=f(e.token||this.config.token),a=L(this.config,e),u=encodeURIComponent(t),[l,p]=await Promise.all([this.config.request({url:`${a}/projects/${u}/merge_requests/${n.pullRequestId}/approvals`,headers:i}),this.fetchAllMergeRequestDiscussions(t,n.pullRequestId,e)]),c=(l.body.approved_by??[]).map(m=>m?.user).filter(m=>!!m).map(m=>{let I=br(m,r,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:n.repo.namespace,name:n.repo.name,mergeRequestIid:n.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=>$t(P,r,o,d)),x={...$t(h,r,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:un(h.position),isOutdated:!1,isResolved:!!m.resolved,threadId:m.id,replies:v};return{author:h.author?br(h.author,r,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(n,e={}){let t=T(n.repo),r=encodeURIComponent(t),o=L(this.config,e);return(await this.fetchAllPagedGitLabREST(`${o}/projects/${r}/merge_requests/${n.pullRequestId}/diffs`,e)).map(ln).join("")}async getMergeBase(n,e={}){let t=T(n.repo),r=new URL(`${L(this.config,e)}/projects/${encodeURIComponent(t)}/repository/merge_base`);r.searchParams.append("refs[]",n.base),r.searchParams.append("refs[]",n.head);let i=(await this.config.request({url:r.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(n,e,t){let r=L(this.config,t),o=encodeURIComponent(n);return this.fetchAllPagedGitLabREST(`${r}/projects/${o}/merge_requests/${e}/discussions`,t)}async fetchAllPagedGitLabREST(n,e){let t=f(e.token||this.config.token),r=[],o=1,i=50;for(;o<=i;){let a=new URL(n);a.searchParams.set("page",o.toString()),a.searchParams.set("per_page",D.toString());let u=await this.config.request({url:a.toString(),headers:t});r.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 r}async addCommentToPullRequest(n,e={}){let{pullRequest:t,comment:r}=n;if(!r||r.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=`${L(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:r})})).body?.id)throw new Error("Could not add comment to pull request")}async addInlineCommentToPullRequest(n,e={}){let{pullRequest:t,comment:r,path:o,line:i,side:a="RIGHT",threadId:u}=n;if(!r?.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=L(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:r})});return v.body?.id!=null?Dt(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:r,position:I})})).body?.notes?.[0]?.id;return h!=null?Dt(t.repository.owner.login,t.repository.name,t.number,h):void 0}getNoteUrl(n,e){if(!n)throw new Error('GitLab requires "commentId" for this function.');let{namespace:t,name:r,mergeRequestIid:o,noteId:i}=pn(n);return`${L(this.config,e)}/projects/${encodeURIComponent(`${t}/${r}`)}/merge_requests/${o}/notes/${i}`}async deleteNote(n,e){await this.config.request({method:"DELETE",url:this.getNoteUrl(n,e),headers:f(e.token||this.config.token)})}async deleteComment(n,e={}){await this.deleteNote(n.commentId,e)}async deleteInlineComment(n,e={}){await this.deleteNote(n.commentId,e)}async editNote(n,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(n,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(n,e={}){await this.editNote(n.commentId,n.body,e)}async editInlineComment(n,e={}){await this.editNote(n.commentId,n.body,e)}async resolveReviewThread(n,e={}){await this.setReviewThreadResolved(n,!0,e)}async unresolveReviewThread(n,e={}){await this.setReviewThreadResolved(n,!1,e)}async setReviewThreadResolved(n,e,t){if(!n.repo||n.pullRequestNumber==null)throw new Error("GitLab requires input.repo and input.pullRequestNumber to locate the discussion to (un)resolve.");if(!n.threadId)throw new Error("GitLab requires input.threadId to (un)resolve a discussion.");let r=T(n.repo),o=new URL(`${L(this.config,t)}/projects/${encodeURIComponent(r)}/merge_requests/${n.pullRequestNumber}/discussions/${encodeURIComponent(n.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(n,e={}){let{pullRequest:t,comment:r}=n,o=`${t.repository.owner.login}/${t.repository.name}`,i=L(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}),r&&r.trim()!==""&&await this.postMergeRequestNote(o,t.number,r,e)}async commentOnPullRequest(n,e={}){let{pullRequest:t,comment:r}=n;if(!r||r.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,r,e)}async requestPullRequestChanges(n,e={}){let{pullRequest:t,comment:r}=n;if(!r||r.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=`${L(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,r,e)}async tryRequestChangesMutation(n,e,t){let r=`mutation MergeRequestRequestChanges($fullPath: ID!, $pullRequestId: String!) {
|
|
1361
|
+
`,variables:{fullPath:t,iid:n.number.toString()}},e)).body.data?.project,i=o?.mergeRequest;if(!o||!i)return{data:null};let a=ke(o),u=i.sourceProject?ke(i.sourceProject):null;return{data:Et(i,a,u,this.getIsSelfHosted(e),this.config.baseUrl??e.baseUrl)}}getMergeRequestUrl(n,e,t){let r=T(n);return`${L(this.config,t)}/projects/${encodeURIComponent(r)}/merge_requests/${e}`}async getPullRequestDescription(n,e={}){try{return{data:{description:(await this.config.request({url:this.getMergeRequestUrl(n.repo,n.number,e),headers:f(e.token||this.config.token)})).body?.description??""}}}catch{return{data:{description:null}}}}async setPullRequestDescription(n,e={}){return{data:{description:(await this.config.request({method:"PUT",url:this.getMergeRequestUrl(n.repo,n.number,e),headers:{...f(e.token||this.config.token),"Content-Type":"application/json"},body:JSON.stringify({description:n.description})})).body?.description??n.description}}}async getFileContents(n,e={}){let t=T(n.repo),r=new URL(`${L(this.config,e)}/projects/${encodeURIComponent(t)}/repository/files/${encodeURIComponent(n.path)}/raw`);r.searchParams.set("ref",n.ref);let o=await this.config.request({url:r.toString(),headers:f(e.token||this.config.token)});return{data:new Blob([o.body])}}async getCommentsForPullRequest(n,e={}){let t=T(n.repo),{page:r,perPage:o}=an(n.cursor,$),i=new URL(`${L(this.config,e)}/projects/${encodeURIComponent(t)}/merge_requests/${n.pullRequestNumber}/notes`);i.searchParams.set("page",r.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:n.repo.namespace,name:n.repo.name,mergeRequestIid:n.pullRequestNumber},c=a.body.filter(m=>!m.system&&!m.position).map(m=>$t(m,u,l,p)),d=!!a.headers["x-next-page"],g=d?on({page:r+1,perPage:o}):null;return{data:c,pageInfo:{endCursor:g,hasNextPage:d}}}async getReviewsForPullRequest(n,e={}){let t=T(n.repo),r=this.getIsSelfHosted(e),o=this.config.baseUrl??e.baseUrl,i=f(e.token||this.config.token),a=L(this.config,e),u=encodeURIComponent(t),[l,p]=await Promise.all([this.config.request({url:`${a}/projects/${u}/merge_requests/${n.pullRequestId}/approvals`,headers:i}),this.fetchAllMergeRequestDiscussions(t,n.pullRequestId,e)]),c=(l.body.approved_by??[]).map(m=>m?.user).filter(m=>!!m).map(m=>{let I=yr(m,r,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:n.repo.namespace,name:n.repo.name,mergeRequestIid:n.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=>$t(P,r,o,d)),x={...$t(h,r,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:ln(h.position),isOutdated:!1,isResolved:!!m.resolved,threadId:m.id,replies:v};return{author:h.author?yr(h.author,r,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(n,e={}){let t=T(n.repo),r=encodeURIComponent(t),o=L(this.config,e);return(await this.fetchAllPagedGitLabREST(`${o}/projects/${r}/merge_requests/${n.pullRequestId}/diffs`,e)).map(pn).join("")}async getMergeBase(n,e={}){let t=T(n.repo),r=new URL(`${L(this.config,e)}/projects/${encodeURIComponent(t)}/repository/merge_base`);r.searchParams.append("refs[]",n.base),r.searchParams.append("refs[]",n.head);let i=(await this.config.request({url:r.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(n,e,t){let r=L(this.config,t),o=encodeURIComponent(n);return this.fetchAllPagedGitLabREST(`${r}/projects/${o}/merge_requests/${e}/discussions`,t)}async fetchAllPagedGitLabREST(n,e){let t=f(e.token||this.config.token),r=[],o=1,i=50;for(;o<=i;){let a=new URL(n);a.searchParams.set("page",o.toString()),a.searchParams.set("per_page",$.toString());let u=await this.config.request({url:a.toString(),headers:t});r.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 r}async addCommentToPullRequest(n,e={}){let{pullRequest:t,comment:r}=n;if(!r||r.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=`${L(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:r})})).body?.id)throw new Error("Could not add comment to pull request")}async addInlineCommentToPullRequest(n,e={}){let{pullRequest:t,comment:r,path:o,line:i,side:a="RIGHT",threadId:u}=n;if(!r?.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=L(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:r})});return v.body?.id!=null?Dt(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:r,position:I})})).body?.notes?.[0]?.id;return h!=null?Dt(t.repository.owner.login,t.repository.name,t.number,h):void 0}getNoteUrl(n,e){if(!n)throw new Error('GitLab requires "commentId" for this function.');let{namespace:t,name:r,mergeRequestIid:o,noteId:i}=dn(n);return`${L(this.config,e)}/projects/${encodeURIComponent(`${t}/${r}`)}/merge_requests/${o}/notes/${i}`}async deleteNote(n,e){await this.config.request({method:"DELETE",url:this.getNoteUrl(n,e),headers:f(e.token||this.config.token)})}async deleteComment(n,e={}){await this.deleteNote(n.commentId,e)}async deleteInlineComment(n,e={}){await this.deleteNote(n.commentId,e)}async editNote(n,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(n,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(n,e={}){await this.editNote(n.commentId,n.body,e)}async editInlineComment(n,e={}){await this.editNote(n.commentId,n.body,e)}async resolveReviewThread(n,e={}){await this.setReviewThreadResolved(n,!0,e)}async unresolveReviewThread(n,e={}){await this.setReviewThreadResolved(n,!1,e)}async setReviewThreadResolved(n,e,t){if(!n.repo||n.pullRequestNumber==null)throw new Error("GitLab requires input.repo and input.pullRequestNumber to locate the discussion to (un)resolve.");if(!n.threadId)throw new Error("GitLab requires input.threadId to (un)resolve a discussion.");let r=T(n.repo),o=new URL(`${L(this.config,t)}/projects/${encodeURIComponent(r)}/merge_requests/${n.pullRequestNumber}/discussions/${encodeURIComponent(n.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(n,e={}){let{pullRequest:t,comment:r}=n,o=`${t.repository.owner.login}/${t.repository.name}`,i=L(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}),r&&r.trim()!==""&&await this.postMergeRequestNote(o,t.number,r,e)}async commentOnPullRequest(n,e={}){let{pullRequest:t,comment:r}=n;if(!r||r.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,r,e)}async requestPullRequestChanges(n,e={}){let{pullRequest:t,comment:r}=n;if(!r||r.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=`${L(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,r,e)}async tryRequestChangesMutation(n,e,t){let r=`mutation MergeRequestRequestChanges($fullPath: ID!, $pullRequestId: String!) {
|
|
1362
1362
|
mergeRequestRequestChanges(input: { projectPath: $fullPath, iid: $pullRequestId }) {
|
|
1363
1363
|
errors
|
|
1364
1364
|
mergeRequest {
|
|
1365
1365
|
id
|
|
1366
1366
|
}
|
|
1367
1367
|
}
|
|
1368
|
-
}`,o=await q(this.config,{query:r,variables:{fullPath:n,pullRequestId:e.toString()}},t),i=o.body.errors;if(i?.length){if(i.some(
|
|
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?qr:wr,d=new URL(`${Z(s,t,o)}${c}`);d.searchParams.set("jql",l),d.searchParams.set("maxResults",Fe.toString()),d.searchParams.set("fields",xt.join(",")),d.searchParams.set("expand","transitions"),r&&(p?d.searchParams.set("startAt",r):d.searchParams.set("nextPageToken",r));let g=await s.request({url:d.toString(),headers:f(t.token||s.token)}),m=g.body.issues.map(h=>_t(h,a,e,o)),I=!1,y="";return p?(I=m.length==Fe,y=(parseInt(r??"0",10)+m.length).toString()):(I=!!g.body.nextPageToken,y=g.body.nextPageToken??null),{data:m,pageInfo:{hasNextPage:I,endCursor:y}}},vr=async(s,n,e,t={})=>{let{cursor:r,resourceId:o,jql:i,fields:a}=n||{},u=[...xt],l=a?.Sprint;l&&u.push(l);let p=!o,c=p?qr:wr,d=new URL(`${Z(s,t,o)}${c}`);d.searchParams.set("jql",i.join(" AND ")),d.searchParams.set("maxResults",Fe.toString()),d.searchParams.set("fields",u.join(",")),d.searchParams.set("expand","transitions"),r&&(p?d.searchParams.set("startAt",r):d.searchParams.set("nextPageToken",r));let g=await s.request({url:d.toString(),headers:f(t.token||s.token)}),m=g.body.issues.map(h=>_t(h,a,e,o)),I=!1,y="";return p?(I=m.length==Fe,y=(parseInt(r??"0",10)+m.length).toString()):(I=!!g.body.nextPageToken,y=g.body.nextPageToken??null),{data:m,pageInfo:{hasNextPage:I,endCursor:y}}},ze=async(s,n,e,t={})=>{let{assigneeLogins:r,authorLogin:o,mentionLogin:i,labelNames:a,cursor:u,projectKey:l,resourceId:p,fields:c}=n||{},d=[`project = "${l}"`,"statusCategory != Done"];return o&&d.push(`creator in ("${o}")`),r&&r.length!==0&&d.push(`assignee in ("${r.join('", "')}")`),i&&d.push(`comment ~ "${i}"`),a&&a.forEach(g=>d.push(`labels = "${g}"`)),vr(s,{resourceId:p,jql:d,cursor:u,fields:c},e,t)},He=async(s,n,e,t={})=>{let{assigneeLogins:r,authorLogin:o,mentionLogin:i,labelNames:a,cursor:u,projectKeys:l,resourceId:p,fields:c}=n||{},g=["("+l.map(m=>`project = "${m}"`).join(" OR ")+")","statusCategory != Done"];return o&&g.push(`creator in ("${o}")`),r&&r.length!==0&&g.push(`assignee in ("${r.join('", "')}")`),i&&g.push(`comment ~ "${i}"`),a&&a.forEach(m=>g.push(`labels = "${m}"`)),vr(s,{resourceId:p,jql:g,fields:c,cursor:u},e,t)},We=async(s,n,e={})=>{let{issue:t,labels:r}=n;if(!t.project)throw new Error('Jira requires a "project" for this function.');let o={fields:{labels:r.map(i=>i.name)}};await s.request({method:"PUT",url:`${Z(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"}})},Je=async(s,n,e={})=>{let{issue:t,components:r}=n;if(!t.project)throw new Error('Jira requires a "project" for this function.');let o={fields:{components:r.map(i=>({id:i.id}))}};await s.request({method:"PUT",url:`${Z(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"}})},Ve=async(s,n,e={})=>{let{issue:t,status:r}=n;if(!t.project)throw new Error('Jira requires a "project" for this function.');if(!r.id)throw new Error('Jira requires a status "id" for this function.');let o={transition:{id:r.id}};await s.request({method:"POST",url:`${Z(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"}})},Ke=async(s,n,e={})=>{let{resourceId:t,projectIdOrKey:r}=n,o=new URL(`${Z(s,e,t)}/rest/api/2/project/${r}/components`);return{data:(await s.request({url:o.toString(),headers:f(e.token||s.token)})).body}};var Pe="https://api.atlassian.com/ex/jira",kt=100,me=class extends N{constructor(){super(...arguments);this._resourceUrlCache={};this._issueFieldsCache={}}async getIssueFieldsForResource(e,t={}){if(!this._issueFieldsCache[e.resourceId]){let r=await Qe(this.config,e,t);this._issueFieldsCache[e.resourceId]=r.reduce((o,i)=>({...o,[i.name]:i.id}),{})}return this._issueFieldsCache[e.resourceId]??null}async getResourceUrl(e,t={}){let r=t.token||this.config.token;if(!r)return null;let o=this._resourceUrlCache[r];return o?o[e.resourceId]??null:(await this.getJiraResourcesForCurrentUser(t),this._resourceUrlCache[r]?.[e.resourceId]??null)}async getCurrentUserForResource(e,t={}){let r=await this.getResourceUrl({resourceId:e.resourceId},t),o=await this.config.request({url:`${t.baseUrl||Pe}/${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:r?`${r}/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)}),r=e.token||this.config.token,o=r?this._resourceUrlCache[r]||{}: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 r&&(this._resourceUrlCache[r]=o),{data:i}}async getJiraProjectsForResource(e,t={}){let r=new URL(`${t.baseUrl||Pe}/${e.resourceId}/rest/api/2/project/search`);r.searchParams.set("maxResults",kt.toString()),e.cursor&&r.searchParams.set("startAt",e.cursor);let o=await this.config.request({url:r.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 r=[];return await Promise.all(e.resourceIds.map(async o=>{try{return await Jt(i=>this.getJiraProjectsForResource({resourceId:o,cursor:i},t))}catch{return[]}})).then((...o)=>{o.forEach(i=>{r=r.concat(...i)})}),{data:r}}async getAccountsForJiraProject(e,t={}){let{resourceId:r,projectKey:o,cursor:i}=e,a=await this.getResourceUrl({resourceId:r},t),u=new URL(`${t.baseUrl||Pe}/${r}/rest/api/2/user/assignable/search`);u.searchParams.set("maxResults",kt.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=>je(p,a,!1))}}async getComponentsForJiraProject(e,t={}){return await Ke(this.config,e,t)}async getIssue(e,t={}){let r=await this.getIssueFieldsForResource({resourceId:e.resourceId},t),o=await this.getResourceUrl({resourceId:e.resourceId},t);return await Be(this.config,{...e,fields:r},o,t)}async getIssuesForProject(e,t={}){let r=await this.getIssueFieldsForResource({resourceId:e.resourceId},t),o=await this.getResourceUrl({resourceId:e.resourceId},t);return await ze(this.config,{...e,fields:r},o,t)}async getIssuesForProjects(e,t={}){let r=await this.getIssueFieldsForResource({resourceId:e.resourceId},t),o=await this.getResourceUrl({resourceId:e.resourceId},t);return await He(this.config,{...e,fields:r},o,t)}async getIssuesForResourceForCurrentUser(e,t={}){let r=await this.getIssueFieldsForResource({resourceId:e.resourceId},t),o=await this.getResourceUrl({resourceId:e.resourceId},t);return await Me(this.config,{...e,fields:r},o,t)}async setIssueStatus(e,t={}){await Ve(this.config,e,t)}async setIssueAssignee(e,t={}){let{issue:r,assignee:o}=e;if(!r.project)throw new Error('Jira Cloud requires a "project" for this function.');if(!r.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||Pe}/${r.project.resourceId}/rest/api/2/issue/${r.id}/assignee`,body:JSON.stringify(i),headers:{...f(t.token||this.config.token),"Content-Type":"application/json"}})}async setIssueComponents(e,t={}){await Je(this.config,e,t)}async setIssueLabels(e,t={}){await We(this.config,e,t)}async getLabelsForResource(e,t={}){let{resourceId:r,cursor:o}=e,i=new URL(`${t.baseUrl||Pe}/${r}/rest/api/2/label`);i.searchParams.set("maxResults",kt.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 ge=class extends _{constructor(){super(...arguments);this._issueFieldsCache={}}async getIssueFieldsForResource(e={}){let t=e?.baseUrl||this.config.baseUrl||"";if(!this._issueFieldsCache[t]){let r=await Qe(this.config,{},e);this._issueFieldsCache[t]=r.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(r=>({id:r.id,name:r.name}))}}async getIssue(e,t={}){let r=e.resourceUrl||t.baseUrl||this.config.baseUrl;if(!r)throw new Error('Jira Server requires a "resourceUrl" or "baseUrl" for this function.');let o=await this.getIssueFieldsForResource(t);return await Be(this.config,{...e,fields:o},r,t)}async getIssuesForProject(e,t={}){let r=e.resourceUrl||t.baseUrl||this.config.baseUrl;if(!r)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},r,t)}async getIssuesForProjects(e,t={}){let r=e.resourceUrl||t.baseUrl||this.config.baseUrl;if(!r)throw new Error('Jira Server requires a "resourceUrl" or "baseUrl" for this function.');let o=await this.getIssueFieldsForResource(t);return await He(this.config,{...e,fields:o},r,t)}async getIssuesForResourceForCurrentUser(e,t={}){let r=e.resourceUrl||t.baseUrl||this.config.baseUrl;if(!r)throw new Error('Jira Server requires a "resourceUrl" or "baseUrl" for this function.');let o=await this.getIssueFieldsForResource(t);return await Me(this.config,{...e,fields:o},r,t)}async setIssueStatus(e,t={}){await Ve(this.config,e,t)}async setIssueLabels(e,t={}){await We(this.config,e,t)}async setIssueComponents(e,t={}){await Je(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:r})=>({color:null,description:null,id:null,name:r}))}}async getComponentsForJiraProject(e,t={}){return await Ke(this.config,e,t)}};var M="https://api.trello.com",In=1e3,z=(s,n)=>({...f(n),Authorization:`OAuth oauth_consumer_key="${s}", oauth_token="${n}"`}),bn=s=>({id:s.id,username:s.username,url:s.url,name:s.fullName,email:s.email,avatarUrl:s.avatarUrl}),yn=(s,n)=>{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:n[s.idList??""]?{id:s.idList,name:n[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}))}},he=class extends N{async getCurrentUser(n,e={}){let t=await this.config.request({url:`${e.baseUrl||M}/1/members/me`,headers:z(n.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(n,e={}){return{data:(await this.config.request({url:`${e.baseUrl||M}/1/members/me/boards?fields=name&filter=open`,headers:z(n.appKey,e.token||this.config.token)})).body.map(r=>({id:r.id,name:r.name}))}}async getListsForTrelloBoard(n,e={}){let{appKey:t,boardId:r}=n;return{data:(await this.config.request({url:`${e.baseUrl||M}/1/boards/${r}/lists`,headers:z(t,e.token||this.config.token)})).body}}async getAccountForId(n,e={}){let{appKey:t,memberId:r}=n,o=await this.config.request({url:`${e.baseUrl||M}/1/members/${r}`,headers:z(t,e.token||this.config.token)});return{data:bn(o.body)}}async getAccountsForTrelloBoard(n,e={}){let{appKey:t,boardId:r}=n;return{data:(await this.config.request({url:`${e.baseUrl||M}/1/boards/${r}/members`,headers:z(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(n,e={}){let t=["-is:archived","sort:edited"],{appKey:r,boardId:o,filterText:i,assigneeLogins:a,labelNamesOrColors:u,trelloBoardListsById:l}=n||{};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||M}/1/search?query=${p}&cards_limit=${In}&card_members=true`,headers:z(r,e.token||this.config.token)})).body.cards.map(d=>yn(d,l||{}))}}async updateIssue(n,e,t,r){return await this.config.request({method:"PUT",url:`${r.baseUrl||M}/1/cards/${e.id}?${t}`,headers:z(n,r.token||this.config.token)})}async setIssueStatus(n,e={}){let{appKey:t,issue:r,status:o}=n;if(!o.id)throw new Error('Trello requires a status "id" for this function.');let i=`idList=${o.id}`;if(!(await this.updateIssue(t,r,i,e)).body.id)throw new Error("Could not set issue status")}async setIssueAssignees(n,e={}){let{appKey:t,issue:r,assignees:o}=n,i=o.map(l=>l.id),a=`idMembers=${encodeURIComponent(i.join(","))}`;if(!(await this.updateIssue(t,r,a,e)).body.id)throw new Error("Could not set issue status")}async setIssueLabels(n,e={}){let{appKey:t,issue:r,labels:o}=n,i=o.map(u=>u.id).join(",");if(!(await this.config.request({method:"PUT",url:`${e.baseUrl||M}/1/cards/${r.id}?idLabels=${encodeURIComponent(i)}`,headers:z(t,e.token||this.config.token)})).body.id)throw new Error("Could not set issue status")}async setIssueArchived(n,e={}){let{appKey:t,issue:r,archived:o}=n;if(!(await this.config.request({method:"PUT",url:`${e.baseUrl||M}/1/cards/${r.id}?closed=${o}`,headers:z(t,e.token||this.config.token)})).body.id)throw new Error("Could not update issue archived status")}async archiveIssue(n,e={}){await this.setIssueArchived({...n,archived:!0},e)}async unArchiveIssue(n,e={}){await this.setIssueArchived({...n,archived:!1},e)}async getLabelsForBoard(n,e={}){let{appKey:t,boardId:r}=n;return{data:(await this.config.request({url:`${e.baseUrl||M}/1/boards/${r}/labels`,headers:z(t,e.token||this.config.token)})).body.map(i=>({color:i.color,description:null,id:i.id,name:i.name}))}}};var Ft=100,Xe=class{constructor(){this.set=new Set;this.arr=[]}push(...n){let e=n.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}},V=async(s,n,e,t)=>{let r=n.token||s.token;if(!r)throw new Error("Linear API key is required");let o=await s.request({url:"https://api.linear.app/graphql",method:"POST",headers:{Authorization:r,"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},Nt=s=>s?s instanceof Date?s:new Date(s):null,Pn=`
|
|
1368
|
+
}`,o=await q(this.config,{query:r,variables:{fullPath:n,pullRequestId:e.toString()}},t),i=o.body.errors;if(i?.length){if(i.some(Ys))return!1;throw new Error(`Could not request pull request changes: ${ye(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(n,e,t,r){let o=L(this.config,r),i=encodeURIComponent(n),a=f(r.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:t})})}};var cn="https://api.atlassian.com/ex/jira",Fe=100,xt=["assignee","comment","summary","created","creator","updated","votes","issuetype","status","labels","components","project","fixVersions","description"],qr="/rest/api/2/search/jql",vr="/rest/api/2/search",_t=(s,n,e,t)=>{let r=s.fields.assignee,o=!t,i=(s.fields[n?.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:je(s.fields.creator,e,o),updatedDate:new Date(s.fields.updated),assignees:r?[je(r,e,o)]:[],description:s.fields.description,repository:null,project:{name:s.fields.project.name,resourceId:t??null,key:s.fields.project.key,namespace:null,id:s.fields.project.id},state:fn(s.fields.status),statusTransitions:s.transitions?.map(mn)??[],components:s.fields.components?.map(gn)??[],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(Rn),fixVersions:s.fields.fixVersions.map(In)}},mn=s=>{let n;switch(s.to.statusCategory.name){case"To Do":n="TO_DO";break;case"In Progress":n="IN_PROGRESS";break;default:n="DONE";break}return{name:s.name,id:s.id,to:{id:s.to.id,name:s.to.name,color:s.to.statusCategory.colorName,category:n}}},gn=s=>({description:s.description??null,id:s.id,name:s.name}),hn=(s,n,e)=>e&&s.name?`${n}/secure/ViewProfile.jspa?name=${encodeURIComponent(s.name)}`:`${n}/jira/people/${s.accountId}`,je=(s,n,e)=>({id:(e?s.key:s.accountId)??"",name:s.displayName,email:s.emailAddress,avatarUrl:s.avatarUrls["48x48"],username:s.displayName,url:hn(s,n,e)}),fn=s=>{let n;switch(s.statusCategory.name){case"To Do":n="TO_DO";break;case"In Progress":n="IN_PROGRESS";break;default:n="DONE";break}return{id:s.id,name:s.name,color:s.statusCategory.colorName,category:n}},Rn=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}),In=s=>({id:s.id,description:s.description,name:s.name,archived:s.archived,released:s.released,releaseDate:s.releaseDate?new Date(s.releaseDate):null}),Z=(s,n,e)=>e?`${n.baseUrl||cn}/${e}`:`${n?.baseUrl||s.baseUrl}`,Qe=async(s,n,e={})=>{let{resourceId:t}=n;return(await s.request({url:`${Z(s,e,t)}/rest/api/2/field`,headers:f(e.token||s.token)})).body},Be=async(s,n,e,t={})=>{let{number:r,resourceId:o,fields:i}=n||{},a=await s.request({url:`${Z(s,t,o)}/rest/api/2/issue/${r}?fields=${xt.join(",")}&expand=transitions`,headers:f(t.token||s.token)});return{data:_t(a.body,i,e,o)}},Me=async(s,n,e,t={})=>{let{cursor:r,resourceId:o,labelNames:i,fields:a}=n||{},u=["statusCategory != Done",`(creator = currentUser() OR assignee = currentUser()
|
|
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?vr:qr,d=new URL(`${Z(s,t,o)}${c}`);d.searchParams.set("jql",l),d.searchParams.set("maxResults",Fe.toString()),d.searchParams.set("fields",xt.join(",")),d.searchParams.set("expand","transitions"),r&&(p?d.searchParams.set("startAt",r):d.searchParams.set("nextPageToken",r));let g=await s.request({url:d.toString(),headers:f(t.token||s.token)}),m=g.body.issues.map(h=>_t(h,a,e,o)),I=!1,y="";return p?(I=m.length==Fe,y=(parseInt(r??"0",10)+m.length).toString()):(I=!!g.body.nextPageToken,y=g.body.nextPageToken??null),{data:m,pageInfo:{hasNextPage:I,endCursor:y}}},Sr=async(s,n,e,t={})=>{let{cursor:r,resourceId:o,jql:i,fields:a}=n||{},u=[...xt],l=a?.Sprint;l&&u.push(l);let p=!o,c=p?vr:qr,d=new URL(`${Z(s,t,o)}${c}`);d.searchParams.set("jql",i.join(" AND ")),d.searchParams.set("maxResults",Fe.toString()),d.searchParams.set("fields",u.join(",")),d.searchParams.set("expand","transitions"),r&&(p?d.searchParams.set("startAt",r):d.searchParams.set("nextPageToken",r));let g=await s.request({url:d.toString(),headers:f(t.token||s.token)}),m=g.body.issues.map(h=>_t(h,a,e,o)),I=!1,y="";return p?(I=m.length==Fe,y=(parseInt(r??"0",10)+m.length).toString()):(I=!!g.body.nextPageToken,y=g.body.nextPageToken??null),{data:m,pageInfo:{hasNextPage:I,endCursor:y}}},ze=async(s,n,e,t={})=>{let{assigneeLogins:r,authorLogin:o,mentionLogin:i,labelNames:a,cursor:u,projectKey:l,resourceId:p,fields:c}=n||{},d=[`project = "${l}"`,"statusCategory != Done"];return o&&d.push(`creator in ("${o}")`),r&&r.length!==0&&d.push(`assignee in ("${r.join('", "')}")`),i&&d.push(`comment ~ "${i}"`),a&&a.forEach(g=>d.push(`labels = "${g}"`)),Sr(s,{resourceId:p,jql:d,cursor:u,fields:c},e,t)},He=async(s,n,e,t={})=>{let{assigneeLogins:r,authorLogin:o,mentionLogin:i,labelNames:a,cursor:u,projectKeys:l,resourceId:p,fields:c}=n||{},g=["("+l.map(m=>`project = "${m}"`).join(" OR ")+")","statusCategory != Done"];return o&&g.push(`creator in ("${o}")`),r&&r.length!==0&&g.push(`assignee in ("${r.join('", "')}")`),i&&g.push(`comment ~ "${i}"`),a&&a.forEach(m=>g.push(`labels = "${m}"`)),Sr(s,{resourceId:p,jql:g,fields:c,cursor:u},e,t)},We=async(s,n,e={})=>{let{issue:t,labels:r}=n;if(!t.project)throw new Error('Jira requires a "project" for this function.');let o={fields:{labels:r.map(i=>i.name)}};await s.request({method:"PUT",url:`${Z(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"}})},Je=async(s,n,e={})=>{let{issue:t,components:r}=n;if(!t.project)throw new Error('Jira requires a "project" for this function.');let o={fields:{components:r.map(i=>({id:i.id}))}};await s.request({method:"PUT",url:`${Z(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"}})},Ve=async(s,n,e={})=>{let{issue:t,status:r}=n;if(!t.project)throw new Error('Jira requires a "project" for this function.');if(!r.id)throw new Error('Jira requires a status "id" for this function.');let o={transition:{id:r.id}};await s.request({method:"POST",url:`${Z(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"}})},Ke=async(s,n,e={})=>{let{resourceId:t,projectIdOrKey:r}=n,o=new URL(`${Z(s,e,t)}/rest/api/2/project/${r}/components`);return{data:(await s.request({url:o.toString(),headers:f(e.token||s.token)})).body}};var Pe="https://api.atlassian.com/ex/jira",kt=100,me=class extends N{constructor(){super(...arguments);this._resourceUrlCache={};this._issueFieldsCache={}}async getIssueFieldsForResource(e,t={}){if(!this._issueFieldsCache[e.resourceId]){let r=await Qe(this.config,e,t);this._issueFieldsCache[e.resourceId]=r.reduce((o,i)=>({...o,[i.name]:i.id}),{})}return this._issueFieldsCache[e.resourceId]??null}async getResourceUrl(e,t={}){let r=t.token||this.config.token;if(!r)return null;let o=this._resourceUrlCache[r];return o?o[e.resourceId]??null:(await this.getJiraResourcesForCurrentUser(t),this._resourceUrlCache[r]?.[e.resourceId]??null)}async getCurrentUserForResource(e,t={}){let r=await this.getResourceUrl({resourceId:e.resourceId},t),o=await this.config.request({url:`${t.baseUrl||Pe}/${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:r?`${r}/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)}),r=e.token||this.config.token,o=r?this._resourceUrlCache[r]||{}: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 r&&(this._resourceUrlCache[r]=o),{data:i}}async getJiraProjectsForResource(e,t={}){let r=new URL(`${t.baseUrl||Pe}/${e.resourceId}/rest/api/2/project/search`);r.searchParams.set("maxResults",kt.toString()),e.cursor&&r.searchParams.set("startAt",e.cursor);let o=await this.config.request({url:r.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 r=[];return await Promise.all(e.resourceIds.map(async o=>{try{return await Jt(i=>this.getJiraProjectsForResource({resourceId:o,cursor:i},t))}catch{return[]}})).then((...o)=>{o.forEach(i=>{r=r.concat(...i)})}),{data:r}}async getAccountsForJiraProject(e,t={}){let{resourceId:r,projectKey:o,cursor:i}=e,a=await this.getResourceUrl({resourceId:r},t),u=new URL(`${t.baseUrl||Pe}/${r}/rest/api/2/user/assignable/search`);u.searchParams.set("maxResults",kt.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=>je(p,a,!1))}}async getComponentsForJiraProject(e,t={}){return await Ke(this.config,e,t)}async getIssue(e,t={}){let r=await this.getIssueFieldsForResource({resourceId:e.resourceId},t),o=await this.getResourceUrl({resourceId:e.resourceId},t);return await Be(this.config,{...e,fields:r},o,t)}async getIssuesForProject(e,t={}){let r=await this.getIssueFieldsForResource({resourceId:e.resourceId},t),o=await this.getResourceUrl({resourceId:e.resourceId},t);return await ze(this.config,{...e,fields:r},o,t)}async getIssuesForProjects(e,t={}){let r=await this.getIssueFieldsForResource({resourceId:e.resourceId},t),o=await this.getResourceUrl({resourceId:e.resourceId},t);return await He(this.config,{...e,fields:r},o,t)}async getIssuesForResourceForCurrentUser(e,t={}){let r=await this.getIssueFieldsForResource({resourceId:e.resourceId},t),o=await this.getResourceUrl({resourceId:e.resourceId},t);return await Me(this.config,{...e,fields:r},o,t)}async setIssueStatus(e,t={}){await Ve(this.config,e,t)}async setIssueAssignee(e,t={}){let{issue:r,assignee:o}=e;if(!r.project)throw new Error('Jira Cloud requires a "project" for this function.');if(!r.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||Pe}/${r.project.resourceId}/rest/api/2/issue/${r.id}/assignee`,body:JSON.stringify(i),headers:{...f(t.token||this.config.token),"Content-Type":"application/json"}})}async setIssueComponents(e,t={}){await Je(this.config,e,t)}async setIssueLabels(e,t={}){await We(this.config,e,t)}async getLabelsForResource(e,t={}){let{resourceId:r,cursor:o}=e,i=new URL(`${t.baseUrl||Pe}/${r}/rest/api/2/label`);i.searchParams.set("maxResults",kt.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 ge=class extends _{constructor(){super(...arguments);this._issueFieldsCache={}}async getIssueFieldsForResource(e={}){let t=e?.baseUrl||this.config.baseUrl||"";if(!this._issueFieldsCache[t]){let r=await Qe(this.config,{},e);this._issueFieldsCache[t]=r.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(r=>({id:r.id,name:r.name}))}}async getIssue(e,t={}){let r=e.resourceUrl||t.baseUrl||this.config.baseUrl;if(!r)throw new Error('Jira Server requires a "resourceUrl" or "baseUrl" for this function.');let o=await this.getIssueFieldsForResource(t);return await Be(this.config,{...e,fields:o},r,t)}async getIssuesForProject(e,t={}){let r=e.resourceUrl||t.baseUrl||this.config.baseUrl;if(!r)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},r,t)}async getIssuesForProjects(e,t={}){let r=e.resourceUrl||t.baseUrl||this.config.baseUrl;if(!r)throw new Error('Jira Server requires a "resourceUrl" or "baseUrl" for this function.');let o=await this.getIssueFieldsForResource(t);return await He(this.config,{...e,fields:o},r,t)}async getIssuesForResourceForCurrentUser(e,t={}){let r=e.resourceUrl||t.baseUrl||this.config.baseUrl;if(!r)throw new Error('Jira Server requires a "resourceUrl" or "baseUrl" for this function.');let o=await this.getIssueFieldsForResource(t);return await Me(this.config,{...e,fields:o},r,t)}async setIssueStatus(e,t={}){await Ve(this.config,e,t)}async setIssueLabels(e,t={}){await We(this.config,e,t)}async setIssueComponents(e,t={}){await Je(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:r})=>({color:null,description:null,id:null,name:r}))}}async getComponentsForJiraProject(e,t={}){return await Ke(this.config,e,t)}};var M="https://api.trello.com",bn=1e3,z=(s,n)=>({...f(n),Authorization:`OAuth oauth_consumer_key="${s}", oauth_token="${n}"`}),yn=s=>({id:s.id,username:s.username,url:s.url,name:s.fullName,email:s.email,avatarUrl:s.avatarUrl}),Pn=(s,n)=>{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:n[s.idList??""]?{id:s.idList,name:n[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}))}},he=class extends N{async getCurrentUser(n,e={}){let t=await this.config.request({url:`${e.baseUrl||M}/1/members/me`,headers:z(n.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(n,e={}){return{data:(await this.config.request({url:`${e.baseUrl||M}/1/members/me/boards?fields=name&filter=open`,headers:z(n.appKey,e.token||this.config.token)})).body.map(r=>({id:r.id,name:r.name}))}}async getListsForTrelloBoard(n,e={}){let{appKey:t,boardId:r}=n;return{data:(await this.config.request({url:`${e.baseUrl||M}/1/boards/${r}/lists`,headers:z(t,e.token||this.config.token)})).body}}async getAccountForId(n,e={}){let{appKey:t,memberId:r}=n,o=await this.config.request({url:`${e.baseUrl||M}/1/members/${r}`,headers:z(t,e.token||this.config.token)});return{data:yn(o.body)}}async getAccountsForTrelloBoard(n,e={}){let{appKey:t,boardId:r}=n;return{data:(await this.config.request({url:`${e.baseUrl||M}/1/boards/${r}/members`,headers:z(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(n,e={}){let t=["-is:archived","sort:edited"],{appKey:r,boardId:o,filterText:i,assigneeLogins:a,labelNamesOrColors:u,trelloBoardListsById:l}=n||{};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||M}/1/search?query=${p}&cards_limit=${bn}&card_members=true`,headers:z(r,e.token||this.config.token)})).body.cards.map(d=>Pn(d,l||{}))}}async updateIssue(n,e,t,r){return await this.config.request({method:"PUT",url:`${r.baseUrl||M}/1/cards/${e.id}?${t}`,headers:z(n,r.token||this.config.token)})}async setIssueStatus(n,e={}){let{appKey:t,issue:r,status:o}=n;if(!o.id)throw new Error('Trello requires a status "id" for this function.');let i=`idList=${o.id}`;if(!(await this.updateIssue(t,r,i,e)).body.id)throw new Error("Could not set issue status")}async setIssueAssignees(n,e={}){let{appKey:t,issue:r,assignees:o}=n,i=o.map(l=>l.id),a=`idMembers=${encodeURIComponent(i.join(","))}`;if(!(await this.updateIssue(t,r,a,e)).body.id)throw new Error("Could not set issue status")}async setIssueLabels(n,e={}){let{appKey:t,issue:r,labels:o}=n,i=o.map(u=>u.id).join(",");if(!(await this.config.request({method:"PUT",url:`${e.baseUrl||M}/1/cards/${r.id}?idLabels=${encodeURIComponent(i)}`,headers:z(t,e.token||this.config.token)})).body.id)throw new Error("Could not set issue status")}async setIssueArchived(n,e={}){let{appKey:t,issue:r,archived:o}=n;if(!(await this.config.request({method:"PUT",url:`${e.baseUrl||M}/1/cards/${r.id}?closed=${o}`,headers:z(t,e.token||this.config.token)})).body.id)throw new Error("Could not update issue archived status")}async archiveIssue(n,e={}){await this.setIssueArchived({...n,archived:!0},e)}async unArchiveIssue(n,e={}){await this.setIssueArchived({...n,archived:!1},e)}async getLabelsForBoard(n,e={}){let{appKey:t,boardId:r}=n;return{data:(await this.config.request({url:`${e.baseUrl||M}/1/boards/${r}/labels`,headers:z(t,e.token||this.config.token)})).body.map(i=>({color:i.color,description:null,id:i.id,name:i.name}))}}};var Ft=100,Xe=class{constructor(){this.set=new Set;this.arr=[]}push(...n){let e=n.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}},V=async(s,n,e,t)=>{let r=n.token||s.token;if(!r)throw new Error("Linear API key is required");let o=await s.request({url:"https://api.linear.app/graphql",method:"POST",headers:{Authorization:r,"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},Nt=s=>s?s instanceof Date?s:new Date(s):null,wn=`
|
|
1370
1370
|
id
|
|
1371
1371
|
name
|
|
1372
1372
|
description
|
|
@@ -1374,11 +1374,11 @@ OR comment ~ currentUser() OR summary ~ currentUser() OR description ~ currentUs
|
|
|
1374
1374
|
startDate
|
|
1375
1375
|
targetDate
|
|
1376
1376
|
url
|
|
1377
|
-
`,
|
|
1377
|
+
`,Er=s=>({id:s.id,name:s.name,description:s.description??null,state:s.state,startDate:Nt(s.startDate),targetDate:Nt(s.targetDate),url:s.url}),Cr=async(s,n,e)=>{let t=`
|
|
1378
1378
|
query GetProjects($first: Int!, $after: String) {
|
|
1379
1379
|
projects(first: $first, after: $after) {
|
|
1380
1380
|
nodes {
|
|
1381
|
-
${
|
|
1381
|
+
${wn}
|
|
1382
1382
|
}
|
|
1383
1383
|
pageInfo {
|
|
1384
1384
|
hasNextPage
|
|
@@ -1386,7 +1386,7 @@ OR comment ~ currentUser() OR summary ~ currentUser() OR description ~ currentUs
|
|
|
1386
1386
|
}
|
|
1387
1387
|
}
|
|
1388
1388
|
}
|
|
1389
|
-
`;return(await V(s,n,t,{first:Ft,after:e})).projects},
|
|
1389
|
+
`;return(await V(s,n,t,{first:Ft,after:e})).projects},qn=`
|
|
1390
1390
|
id
|
|
1391
1391
|
name
|
|
1392
1392
|
number
|
|
@@ -1394,11 +1394,11 @@ OR comment ~ currentUser() OR summary ~ currentUser() OR description ~ currentUs
|
|
|
1394
1394
|
startsAt
|
|
1395
1395
|
endsAt
|
|
1396
1396
|
completedAt
|
|
1397
|
-
|
|
1397
|
+
`,$r=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:Nt(s.completedAt),url:""}),Dr=async(s,n,e)=>{let t=`
|
|
1398
1398
|
query GetCycles($first: Int!, $after: String) {
|
|
1399
1399
|
cycles(first: $first, after: $after) {
|
|
1400
1400
|
nodes {
|
|
1401
|
-
${
|
|
1401
|
+
${qn}
|
|
1402
1402
|
}
|
|
1403
1403
|
pageInfo {
|
|
1404
1404
|
hasNextPage
|
|
@@ -1406,16 +1406,16 @@ OR comment ~ currentUser() OR summary ~ currentUser() OR description ~ currentUs
|
|
|
1406
1406
|
}
|
|
1407
1407
|
}
|
|
1408
1408
|
}
|
|
1409
|
-
`;return(await V(s,n,t,{first:Ft,after:e})).cycles},
|
|
1409
|
+
`;return(await V(s,n,t,{first:Ft,after:e})).cycles},vn=`
|
|
1410
1410
|
id
|
|
1411
1411
|
name
|
|
1412
1412
|
color
|
|
1413
1413
|
description
|
|
1414
|
-
`,
|
|
1414
|
+
`,Lr=s=>({id:s.id,name:s.name,color:s.color,description:s.description??null}),Ur=async(s,n,e)=>{let t=`
|
|
1415
1415
|
query GetLabels($first: Int!, $after: String) {
|
|
1416
1416
|
projectLabels(first: $first, after: $after) {
|
|
1417
1417
|
nodes {
|
|
1418
|
-
${
|
|
1418
|
+
${vn}
|
|
1419
1419
|
}
|
|
1420
1420
|
pageInfo {
|
|
1421
1421
|
hasNextPage
|
|
@@ -1423,36 +1423,36 @@ OR comment ~ currentUser() OR summary ~ currentUser() OR description ~ currentUs
|
|
|
1423
1423
|
}
|
|
1424
1424
|
}
|
|
1425
1425
|
}
|
|
1426
|
-
`;return(await V(s,n,t,{first:Ft,after:e})).projectLabels};var we=(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))(we||{});function
|
|
1426
|
+
`;return(await V(s,n,t,{first:Ft,after:e})).projectLabels};var we=(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))(we||{});function Ar(s,n){return s?`${we[s]}:${n||""}`:n??null}function Gr(s){if(!s)return{category:0};let[n,e]=s.split(":");return n in we?{category:we[n],cursor:e||void 0}:{category:0,cursor:s}}var Tr=100;function Ye(s){return s?s instanceof Date?s:new Date(s):null}var _r=`
|
|
1427
1427
|
id
|
|
1428
1428
|
name
|
|
1429
1429
|
key
|
|
1430
1430
|
icon
|
|
1431
|
-
`;function
|
|
1431
|
+
`;function Sn(s){return{id:s.id,name:s.name,key:s.key,iconUrl:s.icon}}var Or=`
|
|
1432
1432
|
id
|
|
1433
1433
|
name
|
|
1434
1434
|
avatarUrl
|
|
1435
|
-
`;function
|
|
1435
|
+
`;function xr(s){return s?{id:s.id,name:s.name,username:s.name,email:null,avatarUrl:s.avatarUrl??null,url:null}:null}var En=`
|
|
1436
1436
|
id
|
|
1437
1437
|
name
|
|
1438
|
-
`;function
|
|
1438
|
+
`;function Cn(s,n){if(s)return{id:s.id,name:s.name,key:n?.key||null,namespace:null,resourceId:n?.id||null}}var $n=`
|
|
1439
1439
|
id
|
|
1440
1440
|
sortOrder
|
|
1441
1441
|
name
|
|
1442
1442
|
description
|
|
1443
1443
|
status
|
|
1444
1444
|
targetDate
|
|
1445
|
-
`;function
|
|
1445
|
+
`;function Dn(s){return s?{id:s.id,number:s.sortOrder,title:s.name,description:s.description??null,isOpen:s.status!=="done",url:"",startDate:null,dueDate:Ye(s.targetDate)}:null}function Ln(s){switch(s){case"completed":case"canceled":return"DONE";case"started":return"IN_PROGRESS";default:return"TO_DO"}}var Un=`
|
|
1446
1446
|
id
|
|
1447
1447
|
name
|
|
1448
1448
|
color
|
|
1449
1449
|
type
|
|
1450
|
-
`;function
|
|
1450
|
+
`;function An(s){return s?{id:s.id,name:s.name,color:s.color,category:Ln(s.type)}:null}var Qt=`
|
|
1451
1451
|
creator {
|
|
1452
|
-
${
|
|
1452
|
+
${Or}
|
|
1453
1453
|
}
|
|
1454
1454
|
assignee {
|
|
1455
|
-
${
|
|
1455
|
+
${Or}
|
|
1456
1456
|
}
|
|
1457
1457
|
archivedAt
|
|
1458
1458
|
createdAt
|
|
@@ -1460,21 +1460,21 @@ OR comment ~ currentUser() OR summary ~ currentUser() OR description ~ currentUs
|
|
|
1460
1460
|
id
|
|
1461
1461
|
identifier
|
|
1462
1462
|
project {
|
|
1463
|
-
${
|
|
1463
|
+
${En}
|
|
1464
1464
|
}
|
|
1465
1465
|
team {
|
|
1466
|
-
${
|
|
1466
|
+
${_r}
|
|
1467
1467
|
}
|
|
1468
1468
|
state {
|
|
1469
|
-
${
|
|
1469
|
+
${Un}
|
|
1470
1470
|
}
|
|
1471
1471
|
title
|
|
1472
1472
|
updatedAt
|
|
1473
1473
|
url
|
|
1474
1474
|
projectMilestone {
|
|
1475
|
-
${
|
|
1475
|
+
${$n}
|
|
1476
1476
|
}
|
|
1477
|
-
`;async function jt(s){return{author:
|
|
1477
|
+
`;async function jt(s){return{author:xr(await s.creator),assignees:[xr(await s.assignee)].filter(n=>n!=null),commentCount:null,closedDate:Ye(s.archivedAt),createdDate:Ye(s.createdAt),description:s.description??null,id:s.id,labels:[],number:s.identifier,repository:null,project:Cn(await s.project,await s.team),state:An(await s.state),title:s.title,type:null,updatedDate:Ye(s.updatedAt),upvoteCount:null,url:s.url,milestone:Dn(await s.projectMilestone)}}var Ze=`
|
|
1478
1478
|
nodes {
|
|
1479
1479
|
${Qt}
|
|
1480
1480
|
}
|
|
@@ -1500,7 +1500,7 @@ OR comment ~ currentUser() OR summary ~ currentUser() OR description ~ currentUs
|
|
|
1500
1500
|
query GetTeams {
|
|
1501
1501
|
teams {
|
|
1502
1502
|
nodes {
|
|
1503
|
-
${
|
|
1503
|
+
${_r}
|
|
1504
1504
|
}
|
|
1505
1505
|
}
|
|
1506
1506
|
}
|
|
@@ -1513,7 +1513,7 @@ OR comment ~ currentUser() OR summary ~ currentUser() OR description ~ currentUs
|
|
|
1513
1513
|
displayName
|
|
1514
1514
|
}
|
|
1515
1515
|
}
|
|
1516
|
-
`;return(await V(this.config,n,e)).viewer}async getIssue(n,e={}){let t=await this.fetchIssue(n.number,e);return{data:await jt(t)}}async getLinearOrganization(n={}){let e=await this.fetchOrganization(n);return{data:{id:e.id,name:e.name,key:e.urlKey,url:`https://linear.app/${e.urlKey}`}}}async getTeamsForCurrentUser(n={}){return{data:(await this.fetchTeams(n)).nodes.map(
|
|
1516
|
+
`;return(await V(this.config,n,e)).viewer}async getIssue(n,e={}){let t=await this.fetchIssue(n.number,e);return{data:await jt(t)}}async getLinearOrganization(n={}){let e=await this.fetchOrganization(n);return{data:{id:e.id,name:e.name,key:e.urlKey,url:`https://linear.app/${e.urlKey}`}}}async getTeamsForCurrentUser(n={}){return{data:(await this.fetchTeams(n)).nodes.map(Sn)}}async getProjects(n={},e={}){let t=await Cr(this.config,e,n.cursor??void 0);return{data:t.nodes.map(Er),pageInfo:{hasNextPage:t.pageInfo.hasNextPage,endCursor:t.pageInfo.endCursor??null}}}async getCycles(n={},e={}){let t=await Dr(this.config,e,n.cursor??void 0);return{data:t.nodes.map($r),pageInfo:{hasNextPage:t.pageInfo.hasNextPage,endCursor:t.pageInfo.endCursor??null}}}async getLabels(n={},e={}){let t=await Ur(this.config,e,n.cursor??void 0);return{data:t.nodes.map(Lr),pageInfo:{hasNextPage:t.pageInfo.hasNextPage,endCursor:t.pageInfo.endCursor??null}}}async getCurrentUser(n={}){return{data:await this.fetchViewer(n)}}async getIssuesForCurrentUser(n,e={}){let{cursor:t}=n,{category:r,cursor:o}=Gr(t),i=await this.fetchViewer(e),a,u,l=new Xe,p=async(c,d)=>{if(u||r>c)return;let g=await d(Math.max(Tr-l.length,1),r===c?o:void 0);if(!g)return;let m=await it(g.nodes.map(jt));l.push(...m),g.pageInfo.hasNextPage&&(a=c,u=g.pageInfo.endCursor)};return await p(1,async(c,d)=>(await this.rawRequest(e,`
|
|
1517
1517
|
query GetAssignedIssues($first: Int!, $after: String) {
|
|
1518
1518
|
viewer {
|
|
1519
1519
|
issues: assignedIssues(first: $first, after: $after) {
|
|
@@ -1585,10 +1585,10 @@ OR comment ~ currentUser() OR summary ~ currentUser() OR description ~ currentUs
|
|
|
1585
1585
|
}
|
|
1586
1586
|
}
|
|
1587
1587
|
}
|
|
1588
|
-
`,{first:c,after:d})).data?.comments;return m?{nodes:m.nodes.map(y=>y.issue),pageInfo:m.pageInfo}:void 0}),{data:l.items,pageInfo:{hasNextPage:!!u,endCursor:
|
|
1588
|
+
`,{first:c,after:d})).data?.comments;return m?{nodes:m.nodes.map(y=>y.issue),pageInfo:m.pageInfo}:void 0}),{data:l.items,pageInfo:{hasNextPage:!!u,endCursor:Ar(a,u)}}}async getIssues(n,e={}){let{teams:t,projects:r,labels:o,cursor:i}=n,a=[];if(t&&t.length>0){let g=t.map(m=>`"${m}"`).join(", ");a.push(`team: { id: { in: [${g}] } }`)}if(r&&r.length>0){let g=r.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
1589
|
query GetIssues($first: Int!, $after: String) {
|
|
1590
1590
|
issues(first: $first, after: $after${u?", ":""}${u}) {
|
|
1591
1591
|
${Ze}
|
|
1592
1592
|
}
|
|
1593
1593
|
}
|
|
1594
|
-
`,c=(await this.rawRequest(e,l,{first:
|
|
1594
|
+
`,c=(await this.rawRequest(e,l,{first:Tr,after:i})).data?.issues;return c?{data:await it(c.nodes.map(jt)),pageInfo:{hasNextPage:c.pageInfo.hasNextPage,endCursor:c.pageInfo.endCursor??null}}:{data:[],pageInfo:{hasNextPage:!1,endCursor:null}}}};var kr=s=>{let n={request:s?.request};return{azureDevOps:new ae({...n,...s?.azureDevOps}),bitbucket:new ue({...n,...s?.bitbucket}),bitbucketServer:new le({...n,...s?.bitbucketServer}),github:new pe({...n,...s?.github}),gitlab:new ce({...n,...s?.gitlab}),jira:new me({...n,...s?.jira}),jiraServer:new ge({...n,...s?.jiraServer}),linear:new et({...n,...s?.linear}),trello:new he({...n,...s?.trello})}};var Nr=(i=>(i.Conflicts="conflicts",i.Failure="failure",i.NotSet="notSet",i.Queued="queued",i.RejectedByPolicy="rejectedByPolicy",i.Succeeded="succeeded",i))(Nr||{});var Fr=(e=>(e.Zero="0",e.One="1",e))(Fr||{}),jr=(e=>(e.PullRequest="pr",e.Issue="issue",e))(jr||{}),Qr=(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))(Qr||{});var Br=(e=>(e.Completed="COMPLETED",e.NotPlanned="NOT_PLANNED",e))(Br||{});var Gn=kr;
|