@gitkraken/provider-apis 0.53.0 → 0.54.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +9 -0
- package/dist/index.js +150 -149
- package/dist/index.provider-utils.js +1 -1
- package/dist/index.providers.js +181 -180
- package/dist/providers/bitbucketServer/bitbucketServer.d.ts +3 -11
- package/dist/providers/github/github.d.ts +8 -0
- package/dist/providers/github/githubHelpers.d.ts +1 -1
- package/dist/providers/gitlab/gitlab.d.ts +4 -1
- package/dist/types/exportedTypes/gitProvider.d.ts +6 -0
- package/dist/types/exportedTypes/issueProvider.d.ts +3 -2
- package/package.json +1 -1
package/dist/index.providers.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
"use strict";var mt=Object.defineProperty;var vs=Object.getOwnPropertyDescriptor;var Es=Object.getOwnPropertyNames;var Cs=Object.prototype.hasOwnProperty;var $s=(r,n)=>{for(var e in n)mt(r,e,{get:n[e],enumerable:!0})},Ds=(r,n,e,t)=>{if(n&&typeof n=="object"||typeof n=="function")for(let s of Es(n))!Cs.call(r,s)&&s!==e&&mt(r,s,{get:()=>n[s],enumerable:!(t=vs(n,s))||t.enumerable});return r};var Ls=r=>Ds(mt({},"__esModule",{value:!0}),r);var Do={};$s(Do,{AzureDevOps:()=>fe,Bitbucket:()=>Re,BitbucketServer:()=>Ie,EntityIdentifierProviderType:()=>bs,EntityType:()=>Is,EntityVersion:()=>Rs,GitBuildStatusStage:()=>sr,GitBuildStatusState:()=>Te,GitDiffLineType:()=>gt,GitHub:()=>be,GitHubIssueCloseReason:()=>ys,GitIssueState:()=>ue,GitLab:()=>ye,GitMergeStrategy:()=>me,GitPullRequestMergeableState:()=>ie,GitPullRequestReviewState:()=>ee,GitPullRequestState:()=>Y,GraphQLErrors:()=>I,Jira:()=>Pe,JiraServer:()=>we,PullRequestAsyncStatus:()=>fs,Trello:()=>Se,default:()=>$o,isFetch:()=>Oe});module.exports=Ls(Do);var Rr=require("diff");var sr=(s=>(s.Build="build",s.Production="production",s.Staging="staging",s.Test="test",s))(sr||{}),Te=(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))(Te||{}),me=(o=>(o.MergeCommit="MERGE_COMMIT",o.Rebase="REBASE",o.RebaseThenMergeCommit="REBASE_THEN_MERGE_COMMIT",o.FastForward="FAST_FORWARD",o.Squash="SQUASH",o))(me||{}),Y=(t=>(t.Open="OPEN",t.Closed="CLOSED",t.Merged="MERGED",t))(Y||{}),ee=(s=>(s.Approved="APPROVED",s.ChangesRequested="CHANGES_REQUESTED",s.Commented="COMMENTED",s.ReviewRequested="REVIEW_REQUESTED",s))(ee||{}),ie=(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))(ie||{}),gt=(t=>(t.ADDED="ADDED",t.DELETED="DELETED",t.UNMODIFIED="UNMODIFIED",t))(gt||{});var nr={APPROVED:0,COMMENTED:1,REVIEW_REQUESTED:2,CHANGES_REQUESTED:3},B=r=>!r||r.length===0?null:r.reduce((n,e)=>nr[e.state]>nr[n]?e.state:n,"APPROVED");var Us=new Set(["ECONNABORTED","ECONNREFUSED","ECONNRESET","EAI_AGAIN","ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"]),R=(r,n)=>{let e={};return r&&(e.Authorization=`${n?"Basic":"Bearer"} ${r}`),e},ar=r=>r?r.reduce((n,e)=>(n[e]=!0,n),{}):void 0,te=(r,n,e)=>!r||n.some(t=>r[t])?e:"",ur=async r=>{let n=[],e=!0,t;for(;e;){let s=await r(t);n=n.concat(s.data),e=!!s?.pageInfo?.hasNextPage,t=s?.pageInfo?.endCursor||s?.pageInfo?.nextPage}return n};async function ht(r){return(await Promise.allSettled(r)).map(e=>_s(e)).filter(e=>e!=null)}var U=(r,{fallback:n,max:e})=>!r||r<=0?n:e===void 0?r:Math.min(r,e),k=(r,n)=>{if(!n||n.length===0)return r;let e=new Set(n);return r.filter(t=>e.has(t.state))},As=r=>{if(!(!r||typeof r!="object")){if("statusCode"in r&&typeof r.statusCode=="number")return r.statusCode;if("response"in r&&r.response&&typeof r.response=="object"&&"status"in r.response&&typeof r.response.status=="number")return r.response.status}},Gs=r=>{if(!(!r||typeof r!="object"||!("code"in r)||typeof r.code!="string"))return r.code},lr=r=>{if(typeof r=="string")return r;if(r instanceof Error)return r.message},Ts=r=>{let n=As(r);if(n===401)return"authentication";if(n===404)return"not-found";if(n===429)return"rate-limit";if(n!==void 0)return"provider";let e=Gs(r);if(e&&Us.has(e))return"network";let t=lr(r)?.toLowerCase();return t&&(t.includes("network")||t.includes("fetch failed")||t.includes("timed out")||t.includes("timeout")||t.includes("econn")||t.includes("enotfound")||t.includes("eai_again"))?"network":"unknown"},Os=(r,n)=>{let e=lr(n);return{scope:r,kind:Ts(n),...e?{message:e}:{}}},ge=(r,n=[])=>({completeness:r,...n.length?{failures:n}:{}}),or={complete:0,unknown:1,partial:2},ir=(r,n)=>or[r]>=or[n]?r:n,ae=r=>r?r.id||`${r.namespace}/${r.name}`:void 0;async function J(r,{run:n,failureScope:e,completeness:t,concurrency:s}){let o=async p=>{try{return{scope:p,result:await n(p)}}catch(d){return{scope:p,error:d}}},i;if(s===void 0)i=await Promise.all(r.map(o));else{if(!Number.isInteger(s)||s<=0)throw new Error("concurrency must be a positive integer");let p=new Array(r.length);await ft(r.map((d,c)=>({scope:d,index:c})),s,async({scope:d,index:c})=>{p[c]=await o(d)}),i=p}let a=[],u=[],l="complete";return i.forEach(p=>{if("error"in p){a.push(Os(e(p.scope),p.error)),l=ir(l,"partial");return}if(p.result===void 0)return;let d=p.result;l=ir(l,t?t(d):"complete"),u.push({scope:p.scope,result:d})}),{successes:u,metadata:ge(l,a)}}function _s(r,n=void 0){return r?.status==="fulfilled"?r.value:n}async function ft(r,n,e){if(!Number.isFinite(n)||!Number.isInteger(n)||n<=0)throw new Error("batchSize must be a positive integer");for(let t=0;t<r.length;t+=n){let s=r.slice(t,t+n);await Promise.all(s.map(e))}}var ue=(e=>(e.Open="OPEN",e.Closed="CLOSED",e))(ue||{});var Rt=(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))(Rt||{});var C=100;var pr=globalThis.fetch;var xs=async r=>{let n=r.headers.get("content-type")||"",e=null;if(n.startsWith("application/json")){let o=await r.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 r.text();else if(n.startsWith("application/vnd.github.raw+json")||n.startsWith("application/octet-stream"))e=await r.arrayBuffer();else throw new Error(`Unsupported content-type: ${n}`);let t={};r.headers.forEach((o,i)=>{t[i]=o});let s={body:e,headers:t,status:r.status,statusText:r.statusText};if(!r.ok){let o=new Error(r.statusText);throw Object.assign(o,{response:s}),o}return s},It=r=>async({url:n,...e})=>{let t=await r(n,e);return xs(t)};var Oe=(r,n=!1)=>r.name==="fetch"||n;var j=class{constructor(n){let e=n?.request||pr;this.config={...n,request:Oe(e,n?.forceIsFetch)?It(e):e}}updateConfig(n){this.config={...this.config,...n,request:n.request&&Oe(n.request,n?.forceIsFetch??this.config.forceIsFetch)?It(n.request):this.config.request}}},N=class extends j{};var ks="https://app.vssps.visualstudio.com/_apis",Ns="https://vssps.dev.azure.com/",Fs="https://dev.azure.com",S=(r,n={})=>R(n.token||r.token,n.isPAT||r.isPAT),dr=r=>r.url.replace("/_apis/git/repositories/","/_git/").replace(`/${r.repository.project.id}/`,`/${encodeURIComponent(r.repository.project.name)}/`).replace(`/${r.repository.id}/`,`/${encodeURIComponent(r.repository.name)}/`).replace("/pullRequests/","/pullrequest/"),bt=(r,n)=>{let e=n.baseUrl||r.baseUrl||ks;return e=e.replace(/\/$/,""),e},$=(r,n)=>{let e=n.baseUrl||r.baseUrl||Fs;return e=e.replace(/\/$/,""),e},yt=(r,n)=>{let e=n.baseUrl||r.baseUrl||Ns;return e=e.replace(/\/$/,""),e};var js={active:"OPEN",completed:"MERGED",abandoned:"CLOSED"},Qs={OPEN:"active",MERGED:"completed",CLOSED:"abandoned"},he=100,Bs=200,cr=5,zs=200,mr=r=>{if(!r||r.length===0)return"active";let n=Array.from(new Set(r.map(e=>Qs[e])));return n.length===1?n[0]:"all"},Ms=r=>{if(!r||r.length===0)return["[Microsoft.VSTS.Common.ClosedDate] = ''","[Microsoft.VSTS.Common.ResolvedDate] = ''"];let n=new Set(r),e=n.has("OPEN"),t=n.has("CLOSED");return e&&t?[]:t?["([Microsoft.VSTS.Common.ClosedDate] <> '' OR [Microsoft.VSTS.Common.ResolvedDate] <> '')"]:["[Microsoft.VSTS.Common.ClosedDate] = ''","[Microsoft.VSTS.Common.ResolvedDate] = ''"]},Hs=r=>{if(typeof r!="string")return r;let n=r.charAt(0).toUpperCase()+r.slice(1);return Rt[n]??0},Ws=new Set([2,3,4,5]),Js={10:"APPROVED",5:"APPROVED",0:"REVIEW_REQUESTED",[-5]:"CHANGES_REQUESTED",[-10]:"CHANGES_REQUESTED"},le=r=>({id:r.id,name:r.displayName??null,username:(r.uniqueName||r.displayName)??null,email:null,avatarUrl:r.imageUrl??null,url:null}),_e=r=>r.startsWith("refs/heads/")?r.replace("refs/heads/",""):r,Vs=r=>{switch(r){case"conflicts":return"CONFLICTS";case"failure":return"FAILING_CHECKS";case"rejectedByPolicy":return"BLOCKED";case"succeeded":return"MERGEABLE";case"notSet":case"queued":default:return"UNKNOWN"}},Pt=(r,n,e,t,s,o)=>`${r}|${n}|${e}|${t}|${s}|${o}`,gr=r=>{let n=r.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]}},hr=(r,n,e,t,s)=>`${r}|${n}|${e}|${t}|${s}`,wt=r=>{let n=r.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]}},ve=(r,n,e)=>{let t=!!n.forkSource,s=[],o=[];return n.reviewers.forEach(i=>{let a={reviewer:le(i),state:Js[i.vote??0]||"REVIEW_REQUESTED"};i.isRequired&&s.push(a),o.push(a)}),{id:n.pullRequestId.toString(),title:n.title,description:n.description??null,number:n.codeReviewId,state:js[n.status],isDraft:n.isDraft,commentCount:null,upvoteCount:null,author:le(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,isCrossRepository:t,repository:{id:n.repository.id,name:n.repository.name,project:n.repository.project.name,owner:{login:r},remoteInfo:e?.get(n.repository.id)??null},headCommit:{buildStatuses:null},baseRef:{name:_e(n.targetRefName),oid:n.lastMergeTargetCommit.commitId},headRef:{name:_e(n.sourceRefName),oid:n.lastMergeSourceCommit.commitId},url:dr(n),assignees:n.reviewers.map(le),reviews:o,reviewDecision:B(s),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:r},remoteInfo:e?.get(n.forkSource.repository.id)??null,isFork:!0}:{id:n.repository.id,name:n.repository.name,project:n.repository.project.name,owner:{login:r},remoteInfo:e?.get(n.repository.id)??null,isFork:!1},mergeableState:Vs(n.mergeStatus),labels:n.labels?.map(i=>({color:null,description:null,id:i.id,name:i.name}))??[],permissions:null}},fr=(r,n)=>({id:n.id,name:n.name,namespace:r,project:n.project.name,projectId:n.project.id,webUrl:n.webUrl,httpsUrl:n.remoteUrl,sshUrl:n.sshUrl,defaultBranch:n.defaultBranch?{name:_e(n.defaultBranch)}:null,permissions:null}),Ks=(r,n,e,t)=>{let s=e.fields,o=s["System.AssignedTo"],i=s["System.State"],a=s["System.WorkItemType"],u;return i&&a&&(u=t[a]?.[i]),{id:e.id.toString(),number:e.id.toString(),title:s["System.Title"],commentCount:s["System.CommentCount"],author:{avatarUrl:s["System.CreatedBy"]._links?.avatar?.href??null,email:null,id:s["System.CreatedBy"].id,name:s["System.CreatedBy"].uniqueName??null,username:s["System.CreatedBy"].displayName??null,url:null},closedDate:s["Microsoft.VSTS.Common.ClosedDate"]?new Date(s["Microsoft.VSTS.Common.ClosedDate"]):null,createdDate:new Date(s["System.CreatedDate"]),updatedDate:new Date(s["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:s["System.Description"]??null,state:{name:u?.title||i,color:null},type:s["System.WorkItemType"],repository:null,project:{namespace:r,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()}))??[]}},fe=class extends N{constructor(){super(...arguments);this.cachedUserIds=new Map;this.inflightUserIds=new Map}getCurrentUserId(e,t){let s=JSON.stringify([e,t.token??null,t.isPAT??this.config.isPAT??!1,t.baseUrl??null]),o=this.cachedUserIds.get(s);if(o)return Promise.resolve(o);let i=this.inflightUserIds.get(s);if(i)return i;let a=this.fetchCurrentUserId(e,t,s);return this.inflightUserIds.set(s,a),a}async fetchCurrentUserId(e,t,s){try{let o=await this.getCurrentUserForInstance({namespace:e},t);return this.cachedUserIds.set(s,o.data.id),o.data.id}finally{this.inflightUserIds.delete(s)}}getRepoApiUrl(e,t,s,o){return`${$(this.config,o)}/${encodeURIComponent(e)}/${encodeURIComponent(t)}/_apis/git/repositories/${encodeURIComponent(s)}`}async getCurrentUser(e={},t={}){if(t.isPAT||this.config.isPAT)throw new Error("Azure DevOps does not support PATs for this function.");let s=`${bt(this.config,t)}/profile/profiles/me`,o=await this.config.request({url:s,headers:S(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:`${$(this.config,t)}/${encodeURIComponent(e.namespace)}/_apis/ConnectionData`,headers:S(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:`${$(this.config,t)}/${encodeURIComponent(e.repo.namespace)}/${encodeURIComponent(e.repo.project)}/_apis/git/repositories/${encodeURIComponent(e.repo.name)}/commits/${e.oid}`,headers:S(this.config,t)})).body.author;return{data:{name:o.name,email:o.email,avatarUrl:o.imageUrl}}}async getOrgsForUser(e,t={}){let s=`${bt(this.config,t)}/accounts?memberId=${e.userId}&api-version=6.0`;return{data:(await this.config.request({url:s,headers:S(this.config,t)})).body.value.map(i=>({id:i.accountId,name:i.accountName}))}}async getCollectionsForUser(e,t={}){let s=`${$(this.config,t)}/_apis/projectCollections`;return{data:(await this.config.request({url:s,headers:S(this.config,t)})).body.value.map(i=>({id:i.id,name:i.name}))}}async getAzureProjects(e,t={}){let s=new URL(`${$(this.config,t)}/${encodeURIComponent(e.namespace)}/_apis/projects`);s.searchParams.set("$top",C.toString()),e.cursor&&s.searchParams.set("$skip",e.cursor);let o=await this.config.request({url:s.toString(),headers:S(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:s,projectId:o}=e;return{data:{scope:(await this.config.request({url:`${yt(this.config,t)}/${encodeURIComponent(s)}/_apis/graph/descriptors/${o}?api-version=6.0`,headers:S(this.config,t)})).body.value}}}async getAzureGraphAccountsForAzureProject(e,t={}){let{namespace:s,projectScopeDescriptor:o,cursor:i}=e,a=new URL(`${yt(this.config,t)}/${encodeURIComponent(s)}/_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:S(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:s}=e;if(!s.storageKeyURL)throw new Error("Expected 'storageKeyURL' to not be null for 'azureGraphAccount'");let o=await this.config.request({url:s.storageKeyURL,headers:S(this.config,t)});return{data:{avatarUrl:s.avatarUrl,email:s.email,id:o.body.value,name:s.name,username:s.username,url:null}}}async getAccountsFromAzureGraphAccounts(e,t={}){let s=[];for(let o of e.azureGraphAccounts){let i=await this.getAccountFromAzureGraphAccount({azureGraphAccount:o},t);s.push(i.data)}return{data:s}}async getRepo(e,t={}){if(!e.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let s=await this.config.request({url:`${$(this.config,t)}/${encodeURIComponent(e.namespace)}/${encodeURIComponent(e.project)}/_apis/git/repositories/${encodeURIComponent(e.name)}`,headers:S(this.config,t)});return{data:fr(e.namespace,s.body)}}async getRepos(e,t={}){let s=[],o=[];return await Promise.all(e.map(async i=>{try{let a=await this.getRepo(i,t);s.push(a.data)}catch(a){o.push({input:i,error:a})}})),{data:s,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:`${$(this.config,t)}/${encodeURIComponent(e.namespace)}/${encodeURIComponent(e.project)}/_apis/git/repositories`,headers:S(this.config,t)})).body.value.map(o=>fr(e.namespace,o))}}async getRefs(e,t,s={}){if(!t.repo.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let o=new URL(`${$(this.config,s)}/${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",C.toString()),t.cursor&&o.searchParams.set("continuationToken",t.cursor);let i=await this.config.request({url:o.toString(),headers:S(this.config,s)}),a=i.headers["x-ms-continuationtoken"];return{pageInfo:{hasNextPage:!!a,endCursor:a||null},data:i.body.value.map(u=>({name:_e(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 fetchRemoteInfoByRepoId(e,t,s){let o=new Map;if(!e)return o;let i=new Map;for(let{namespace:a,pullRequests:u}of t)for(let l of u)i.has(l.repository.id)||i.set(l.repository.id,a),l.forkSource&&!i.has(l.forkSource.repository.id)&&i.set(l.forkSource.repository.id,a);return await ft([...i],10,async([a,u])=>{try{let l=await this.config.request({url:`${$(this.config,s)}/${encodeURIComponent(u)}/_apis/git/repositories/${encodeURIComponent(a)}`,headers:S(this.config,s)}),{remoteUrl:p,sshUrl:d}=l.body;p&&d&&o.set(a,{cloneUrlHTTPS:p,cloneUrlSSH:d})}catch{}}),o}async getPullRequestsForRepoBase(e,t={},s=he){let{page:o,repo:i,assigneeLogins:a,authorLogin:u,reviewerId:l}=e||{},p=o||1;if(!i.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let d=U(e.pageSize,{fallback:s}),c=l??(a&&a.length?a[0]:void 0),g=`searchCriteria.status=${mr(e.states)}`;return c&&(g+=`&searchCriteria.reviewerId=${encodeURIComponent(c)}`),u&&(g+=`&searchCriteria.creatorId=${encodeURIComponent(u)}`),await this.config.request({url:`${$(this.config,t)}/${encodeURIComponent(i.namespace)}/${encodeURIComponent(i.project||"")}/_apis/git/repositories/${encodeURIComponent(i.name)}/pullRequests?${g}&%24top=${d}&%24skip=${(p-1)*d}`,headers:S(this.config,t)})}async getPullRequestsForRepo(e,t={}){let s=U(e.pageSize,{fallback:he}),o=e.page||1,i=await this.getPullRequestsForRepoBase(e,t,s),a=i.body.value.length===s,u=await this.fetchRemoteInfoByRepoId(e.includeRemoteInfo,[{namespace:e.repo.namespace,pullRequests:i.body.value}],t);return{pageInfo:{hasNextPage:a,nextPage:a?o+1:null,currentPage:o},data:k(i.body.value.map(l=>ve(e.repo.namespace,l,u)),e.states)}}async getPullRequestsForRepos(e,t={}){if(!e.repos.every(d=>d.project))throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let{repos:s}=e||{},o=U(e.pageSize,{fallback:he}),{successes:i,metadata:a}=await J(s,{run:d=>this.getPullRequestsForRepoBase({repo:d,assigneeLogins:e.assigneeLogins,authorLogin:e.authorLogin,reviewerId:e.reviewerId,states:e.states,pageSize:o},t,o),failureScope:d=>({providerId:"azure",projectId:d.project,repositoryId:ae(d)}),completeness:d=>d.body.value.length===o?"unknown":"complete",concurrency:cr}),u=i.map(({scope:d,result:c})=>({namespace:d.namespace,pullRequests:c.body.value})),l=await this.fetchRemoteInfoByRepoId(e.includeRemoteInfo,u,t),p=u.flatMap(({namespace:d,pullRequests:c})=>c.map(g=>ve(d,g,l)));return{data:k(p,e.states),metadata:a}}async getPullRequestsForProjectBase(e,t={},s=he){let{namespace:o,project:i,page:a,assigneeLogins:u,authorLogin:l,reviewerId:p,repo:d}=e;if(d?.project&&d.project!==i)throw new Error("Could not fetch pull requests, project mismatch");let c=a||1,g=U(e.pageSize,{fallback:s}),m=p??(u&&u.length?u[0]:void 0),h=new URL(`${$(this.config,t)}/${encodeURIComponent(o)}/${encodeURIComponent(i)}/_apis/git/pullRequests`);return h.searchParams.set("searchCriteria.status",mr(e.states)),h.searchParams.set("$top",g.toString()),h.searchParams.set("$skip",((c-1)*g).toString()),d?.id&&d?.project===i&&h.searchParams.set("searchCriteria.repositoryId",d.id),m&&h.searchParams.set("searchCriteria.reviewerId",m),l&&h.searchParams.set("searchCriteria.creatorId",l),await this.config.request({url:h.toString(),headers:S(this.config,t)})}async getPullRequestsForProject(e,t={}){let s=U(e.pageSize,{fallback:he}),o=e.page||1,i=await this.getPullRequestsForProjectBase(e,t,s),a=i.body.value.length===s,u=await this.fetchRemoteInfoByRepoId(e.includeRemoteInfo,i?[{namespace:e.namespace,pullRequests:i.body.value}]:[],t);return{pageInfo:{hasNextPage:a,nextPage:a?o+1:null,currentPage:o},data:k(i?.body.value.map(l=>ve(e.namespace,l,u))||[],e.states)}}async getPullRequestsForProjects(e,t={}){let{projects:s}=e||{};if(e.repo&&!e.repo.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let o=U(e.pageSize,{fallback:he}),{successes:i,metadata:a}=await J(s,{run:d=>e.repo&&e.repo.project!==d.project?Promise.resolve(void 0):this.getPullRequestsForProjectBase({...d,assigneeLogins:e.assigneeLogins,authorLogin:e.authorLogin,reviewerId:e.reviewerId,states:e.states,pageSize:o,repo:e.repo},t,o),failureScope:d=>({providerId:"azure",projectId:d.project,repositoryId:ae(e.repo)}),completeness:d=>d.body.value.length===o?"unknown":"complete",concurrency:cr}),u=i.map(({scope:d,result:c})=>({namespace:d.namespace,pullRequests:c.body.value})),l=await this.fetchRemoteInfoByRepoId(e.includeRemoteInfo,u,t),p=u.flatMap(({namespace:d,pullRequests:c})=>c.map(g=>ve(d,g,l)));return{data:k(p,e.states),metadata:a}}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:s,project:o,name:i},pullRequestId:a}=e,u=await this.config.request({url:`${$(this.config,t)}/${encodeURIComponent(s)}/${encodeURIComponent(o||"")}/_apis/git/repositories/${i}/pullrequests/${a}?includeCommits=true?api-version=6.0`,headers:{...S(this.config,t)}});if(!u.body.mergeStatus)throw new Error("Could not fetch pull request");return{data:u.body.mergeStatus}}async updatePullRequest(e,t,s){return await this.config.request({method:"PATCH",url:`${$(this.config,s)}/${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:{...S(this.config,s),"Content-Type":"application/json"}})}async closePullRequest(e,t={}){let{pullRequest:s}=e,o={status:"abandoned"};if(!(await this.updatePullRequest(s,JSON.stringify(o),t)).body.status)throw new Error("Could not close pull request")}async mergePullRequest(e,t={}){let{pullRequest:s,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:s.headRef?.oid},status:"completed"};if(!(await this.updatePullRequest(s,JSON.stringify(a),t)).body.status)throw new Error("Could not merge pull request")}async addPullRequestLabel(e,t={}){let{pullRequest:s,label:o}=e;if(!s.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:`${$(this.config,t)}/${encodeURIComponent(s.repository.owner.login)}/${encodeURIComponent(s.repository.project)}/_apis/git/repositories/${s.repository.name}/pullrequests/${s.id}/labels?api-version=6.0`,body:JSON.stringify(i),headers:{...S(this.config,t),"Content-Type":"application/json"}})).body.id)throw new Error("Could not add pull request label")}async removePullRequestLabel(e,t={}){let{pullRequest:s,label:o}=e;if(!s.repository.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');await this.config.request({method:"DELETE",url:`${$(this.config,t)}/${encodeURIComponent(s.repository.owner.login)}/${encodeURIComponent(s.repository.project)}/_apis/git/repositories/${s.repository.name}/pullrequests/${s.id}/labels/${encodeURIComponent(o.name)}?api-version=6.0`,headers:{...S(this.config,t)}})}async setPullRequestLabels(e,t={}){let{pullRequest:s,labels:o}=e;if(!s.repository.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let i=s.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:s,label:a},t);for(let a of i)o.find(u=>a.id===u.id)||await this.removePullRequestLabel({pullRequest:s,label:a},t)}async setPullRequestAsDraft(e,t={}){let{pullRequest:s,isDraft:o}=e,i={isDraft:o};if(!(await this.updatePullRequest(s,JSON.stringify(i),t)).body.status)throw new Error("Could not set the pull request as draft")}async addPullRequestReviewer(e,t={}){let{pullRequest:s,reviewer:o,isRequired:i}=e,a={id:o.id,isRequired:i};if(!(await this.config.request({method:"PUT",url:`${$(this.config,t)}/${encodeURIComponent(s.repository.owner.login)}/${encodeURIComponent(s.repository.project)}/_apis/git/repositories/${s.repository.name}/pullrequests/${s.id}/reviewers/${o.id}?api-version=6.0`,body:JSON.stringify(a),headers:{...S(this.config,t),"Content-Type":"application/json"}})).body.id)throw new Error("Could not add pull request reviewer")}async removePullRequestReviewer(e,t={}){let{pullRequest:s,reviewer:o}=e;await this.config.request({method:"DELETE",url:`${$(this.config,t)}/${encodeURIComponent(s.repository.owner.login)}/${encodeURIComponent(s.repository.project)}/_apis/git/repositories/${s.repository.name}/pullrequests/${s.id}/reviewers/${o.id}?api-version=6.0`,headers:{...S(this.config,t),Accept:"application/json"}})}async setPullRequestReviewers(e,t={}){let{pullRequest:s,reviewers:o}=e;for(let i of o)s.assignees.find(a=>a.id===i.id)||await this.addPullRequestReviewer({pullRequest:s,reviewer:i,isRequired:!0},t);for(let i of s.assignees)o.find(a=>i.id===a.id)||await this.removePullRequestReviewer({pullRequest:s,reviewer:i},t)}async getIssuesForAzureProject(e,t={}){let{page:s,assigneeLogins:o,authorLogin:i,mentionLogin:a,labelNames:u,statusByWorkItemIdByStatusId:l}=e||{},p=s||1,d=Math.min(U(e.pageSize,{fallback:Bs}),zs),c=["[System.TeamProject] = @project",...Ms(e.states)];i&&c.push(`[System.CreatedBy] = '${i.replace("'","''")}'`),o&&o[0]&&c.push(`[System.AssignedTo] = '${o[0].replace("'","''")}'`),a&&c.push("[System.Id] IN (@recentMentions)"),u&&u.forEach(L=>c.push(`[System.Tags] Contains '${L}'`));let g=`Select [Microsoft.VSTS.Common.ClosedDate], [Microsoft.VSTS.Common.ResolvedDate] From WorkItems Where ${c.join(" AND ")} order by [System.CreatedDate] desc`,m=await this.config.request({url:`${$(this.config,t)}/${encodeURIComponent(e.namespace)}/${encodeURIComponent(e.project)}/_apis/wit/wiql?api-version=6.0`,body:JSON.stringify({query:g}),method:"POST",headers:{...S(this.config,t),"Content-Type":"application/json"}}),h=m.body.workItems.slice((p-1)*d,d*p).map(L=>L.id),y=m.body.workItems.length,f=Math.ceil(y/d),P=y>d*p;if(h.length===0)return{pageInfo:{hasNextPage:!1,nextPage:null,currentPage:p,totalCount:y,totalPages:f},data:[]};let q=await this.config.request({url:`${$(this.config,t)}/${encodeURIComponent(e.namespace)}/${encodeURIComponent(e.project)}/_apis/wit/workitemsbatch?api-version=6.0`,body:JSON.stringify({ids:h,$expand:"Links"}),method:"POST",headers:{...S(this.config,t),"Content-Type":"application/json"}});return{pageInfo:{hasNextPage:P,nextPage:P?p+1:null,currentPage:p,totalCount:y,totalPages:f},data:q.body.value.map(L=>Ks(e.namespace,e.project,L,l||{}))}}async getPermissionsForRepos(e,t={}){let{namespace:s,repos:o}=e,i={4:["canPush","canCreateWebhook"],1024:["isAdmin"],2048:["isAdmin"],4096:["isAdmin"],8192:["isAdmin"]},a=d=>{let c="2e9eb7ed-3c0a-47d4-87c1-0ffdd275fd87",g=`repoV2/${d.projectId}/${d.id}`;return Object.keys(i).map(m=>({securityNamespaceId:c,token:g,permissions:m}))},u={alwaysAllowAdministrators:!1,evaluations:o.flatMap(a)};return{data:(await this.config.request({method:"POST",url:`${$(this.config,t)}/${encodeURIComponent(s)}/_apis/security/permissionevaluationbatch?api-version=7.0`,body:JSON.stringify(u),headers:{...S(this.config,t),"Content-Type":"application/json"}})).body.evaluations.reduce((d,c)=>{let[,g,m]=c.token.split("/"),h=`${g}/${m}`,y=i[c.permissions];for(let f of y)d[h]===void 0&&(d[h]={canCreateWebhook:!0,canPush:!0,isAdmin:!0}),c.value===!1&&(d[h][f]=!1);return d},{})}}async decorateReposWithPermissions(e,t={}){let{namespace:s,repos:o}=e,i=await this.getPermissionsForRepos({namespace:s,repos:o},t);return{data:o.map(a=>({...a,permissions:i.data[`${a.projectId}/${a.id}`]}))}}async updateIssue(e,t,s={}){return await this.config.request({method:"PATCH",url:`${$(this.config,s)}/${encodeURIComponent(e.project.namespace)}/${encodeURIComponent(e.project.name)}/_apis/wit/workitems/${e.id}?api-version=6.0`,body:JSON.stringify(t),headers:{...S(this.config,s),"Content-Type":"application/json-patch+json"}})}async setIssueStatus(e,t={}){let{issue:s,status:o}=e,i=[{op:"add",path:"/fields/System.State",value:o.name}];if(!(await this.updateIssue(s,i,t)).body.fields?.["System.State"])throw new Error("Could not set issue status")}async setIssueAssignee(e,t={}){let{issue:s,assignee:o}=e,i=[{op:"add",path:"/fields/System.AssignedTo",value:o?.name??""}];if(!(await this.updateIssue(s,i,t)).body.fields?.["System.State"])throw new Error("Could not set issue assignee")}async setIssueLabels(e,t={}){let{issue:s,labels:o}=e,a=[{op:"replace",path:"/fields/System.Tags",value:o.map(l=>l.name).join(";")}];if(!(await this.updateIssue(s,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:s,project:o}=e;return{data:(await this.config.request({url:`${$(this.config,t)}/${encodeURIComponent(s)}/${encodeURIComponent(o||"")}/_apis/wit/workitemtypes?api-version=6.0`,headers:{...S(this.config,t)}})).body.value}}async getLabelsForProject(e,t={}){let{namespace:s,project:o}=e;return{data:(await this.config.request({url:`${$(this.config,t)}/${encodeURIComponent(s)}/${encodeURIComponent(o||"")}/_apis/wit/tags?api-version=6.0`,headers:{...S(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:s,number:o}=e;if(!s.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let i=await this.config.request({url:`${this.getRepoApiUrl(s.namespace,s.project,s.name,t)}/pullrequests/${o}?api-version=7.1`,headers:S(this.config,t)}),a=await this.fetchRemoteInfoByRepoId(e.includeRemoteInfo,[{namespace:s.namespace,pullRequests:[i.body]}],t);return{data:ve(s.namespace,i.body,a)}}async getPullRequestDescription(e,t={}){let{repo:s,number:o}=e;if(!s.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(s.namespace,s.project,s.name,t)}/pullrequests/${o}?api-version=7.1`,headers:S(this.config,t)})).body?.description??""}}}catch{return{data:{description:null}}}}async setPullRequestDescription(e,t={}){let{repo:s,number:o,description:i}=e;if(!s.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(s.namespace,s.project,s.name,t)}/pullrequests/${o}?api-version=7.1`,headers:{...S(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 s=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:S(this.config,t)});if(!s.body.value?.length)throw new Error("No merge base found between the specified commits.");return{data:s.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 s=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:{...S(this.config,t),Accept:"application/octet-stream"}});return{data:new Blob([s.body])}}async getPullRequestDiff(e,t={}){if(!e.repo.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let s=this.getRepoApiUrl(e.repo.namespace,e.repo.project,e.repo.name,t),o=S(this.config,t),i={...o,Accept:"application/octet-stream"},[a,u]=await Promise.all([this.config.request({url:`${s}/pullrequests/${e.pullRequestId}?api-version=7.1`,headers:o}),this.config.request({url:`${s}/pullrequests/${e.pullRequestId}/iterations?api-version=7.1`,headers:o})]),l=a.body.lastMergeTargetCommit.commitId,p=a.body.lastMergeSourceCommit.commitId,d=u.body.value;if(d.length===0)return"";let c=d[d.length-1],g=1e3,m=[],h=0;for(;;){let E=(await this.config.request({url:`${s}/pullrequests/${e.pullRequestId}/iterations/${c.id}/changes?api-version=7.1&$top=${g}&$skip=${h}`,headers:o})).body.changeEntries??[];if(E.length===0||(m.push(...E),E.length<g))break;h+=E.length}if(m.length===0)return"";let y=5,f=[],P=new TextDecoder,q=w=>w instanceof ArrayBuffer?P.decode(w):typeof w=="string"?w:"",L=async(w,E)=>{try{let ne=await this.config.request({url:`${s}/items?path=${encodeURIComponent(w)}&versionDescriptor[version]=${encodeURIComponent(E)}&versionDescriptor[versionType]=commit&includeContent=true&api-version=7.1`,headers:i});return q(ne.body)}catch{return""}},D=w=>{if(typeof w=="number")return{add:(w&1)!==0,rename:(w&8)!==0,delete:(w&16)!==0};let E=w.toLowerCase().split(",").map(ne=>ne.trim());return{add:E.includes("add"),rename:E.includes("rename"),delete:E.includes("delete")}};for(let w=0;w<m.length;w+=y){let E=m.slice(w,w+y),ne=await Promise.all(E.map(async de=>{let{add:ce,rename:ct,delete:oe}=D(de.changeType),qe=de.originalPath??de.item.originalPath,T=de.item.path,Ge=oe?T??qe??"":T??"",rr=ct||oe?qe??Ge:Ge,[Ps,ws]=await Promise.all([ce?Promise.resolve(""):L(rr,l),oe?Promise.resolve(""):L(Ge,p)]),Ss=ce?"/dev/null":`a${rr}`,qs=oe?"/dev/null":`b${Ge}`;return(0,Rr.createTwoFilesPatch)(Ss,qs,Ps,ws)}));f.push(...ne)}return f.join(`
|
|
2
|
-
`)}getPullRequestWriteHeaders(e){return{...S(this.config,e),"Content-Type":"application/json"}}setReviewerVote(e,t,s,o,i){return this.config.request({method:"PUT",url:`${e}/pullRequests/${t}/reviewers/${encodeURIComponent(s)}?api-version=7.1`,headers:this.getPullRequestWriteHeaders(i),body:JSON.stringify({vote:o})})}postPullRequestThread(e,t,s,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:s,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 s=this.getRepoApiUrl(e.repo.namespace,e.repo.project,e.repo.name,t),o=S(this.config,t),i=await this.config.request({url:`${s}/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:Pt(e.repo.namespace,e.repo.project,e.repo.name,e.pullRequestNumber,u.id,l.id),author:l.author?le(l.author):null,body:l.content||"",createdAt:l.publishedDate?new Date(l.publishedDate):null,url:""});return{data:a,pageInfo:{hasNextPage:!1,endCursor:null}}}async addCommentToPullRequest(e,t={}){if(!e.pullRequest.repository.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let s=this.getRepoApiUrl(e.pullRequest.repository.owner.login,e.pullRequest.repository.project,e.pullRequest.repository.name,t);await this.postPullRequestThread(s,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 s=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=wt(e.threadId),d=e.pullRequest.repository.owner.login,c=e.pullRequest.repository.project,g=e.pullRequest.repository.name,m=String(e.pullRequest.id);if(p.namespace!==d||p.project!==c||p.repoName!==g||p.prId!==m)throw new Error(`Azure thread ID context mismatch: threadId targets ${p.namespace}/${p.project}/${p.repoName} pull request ${p.prId}, but input.pullRequest targets ${d}/${c}/${g} pull request ${m}.`);let y=(await this.config.request({url:`${s}/pullRequests/${e.pullRequest.id}/threads/${p.threadId}?api-version=7.1`,headers:S(this.config,t)})).body.comments?.find(P=>P.parentCommentId===0);if(!y)throw new Error(`Could not determine root comment for Azure DevOps thread ${p.threadId}.`);let f=await this.config.request({method:"POST",url:`${s}/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 Pt(d,c,g,Number(m),Number(p.threadId),f.body.id)}let i=e.path.startsWith("/")?e.path:`/${e.path}`,a={line:e.line,offset:1},u={filePath:i};e.side==="LEFT"?(u.leftFileStart=a,u.leftFileEnd=a):(u.rightFileStart=a,u.rightFileEnd=a);let l=await this.config.request({method:"POST",url:`${s}/pullRequests/${e.pullRequest.id}/threads?api-version=7.1`,headers:o,body:JSON.stringify({comments:[{parentCommentId:0,content:e.comment,commentType:1}],status:1,threadContext:u})});return hr(e.pullRequest.repository.owner.login,e.pullRequest.repository.project,e.pullRequest.repository.name,Number(e.pullRequest.id),l.body.id)}async editComment(e,t={}){let s=gr(e.commentId),o=this.getRepoApiUrl(s.namespace,s.project,s.repoName,t);await this.config.request({method:"PATCH",url:`${o}/pullRequests/${s.prId}/threads/${s.threadId}/comments/${s.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 s=gr(e.commentId),o=this.getRepoApiUrl(s.namespace,s.project,s.repoName,t);await this.config.request({method:"DELETE",url:`${o}/pullRequests/${s.prId}/threads/${s.threadId}/comments/${s.commentId}?api-version=7.1`,headers:S(this.config,t)})}async deleteInlineComment(e,t={}){return this.deleteComment(e,t)}async resolveReviewThread(e,t={}){let s=wt(e.threadId),o=this.getRepoApiUrl(s.namespace,s.project,s.repoName,t);await this.config.request({method:"PATCH",url:`${o}/pullRequests/${s.prId}/threads/${s.threadId}?api-version=7.1`,headers:this.getPullRequestWriteHeaders(t),body:JSON.stringify({status:2})})}async unresolveReviewThread(e,t={}){let s=wt(e.threadId),o=this.getRepoApiUrl(s.namespace,s.project,s.repoName,t);await this.config.request({method:"PATCH",url:`${o}/pullRequests/${s.prId}/threads/${s.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 s=e.pullRequest.repository.owner.login,o=this.getRepoApiUrl(s,e.pullRequest.repository.project,e.pullRequest.repository.name,t),i=await this.getCurrentUserId(s,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 s=e.pullRequest.repository.owner.login,o=this.getRepoApiUrl(s,e.pullRequest.repository.project,e.pullRequest.repository.name,t),i=await this.getCurrentUserId(s,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 s=this.getRepoApiUrl(e.pullRequest.repository.owner.login,e.pullRequest.repository.project,e.pullRequest.repository.name,t);await this.postPullRequestThread(s,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:s,project:o,name:i}=e.repo,{pullRequestId:a}=e,u=this.getRepoApiUrl(s,o,i,t),l=S(this.config,t),[p,d]=await Promise.all([this.config.request({url:`${u}/pullRequests/${a}/reviewers?api-version=7.1`,headers:l}),this.config.request({url:`${u}/pullRequests/${a}/threads?api-version=7.1`,headers:l})]),c=(f,P)=>Pt(s,o,i,a,f,P),g=f=>hr(s,o,i,a,f),m=new Map;for(let f of d.body.value){if(f.isDeleted)continue;let P=f.comments.filter(T=>!T.isDeleted&&T.commentType!=="system"),q=P.find(T=>T.parentCommentId===0)??P[0];if(!q)continue;let L=q.author?.id;if(!L)continue;let D=P.filter(T=>T.id!==q.id),w=f.threadContext,E=w?.rightFileStart?{side:"RIGHT",start:w.rightFileStart,end:w.rightFileEnd}:w?.leftFileStart?{side:"LEFT",start:w.leftFileStart,end:w.leftFileEnd}:null,ne=E?.end?.line??E?.start.line??null,de=E?.start&&E.end&&E.start.line!==E.end.line?E.start.line:null,ce=w?.filePath??"",ct=ce.startsWith("/")?ce.slice(1):ce,oe={id:c(f.id,q.id),author:q.author?le(q.author):null,body:q.content??"",createdAt:q.publishedDate?new Date(q.publishedDate):null,url:"",diffLines:[],filename:ct,replies:D.map(T=>({id:c(f.id,T.id),author:T.author?le(T.author):null,body:T.content??"",createdAt:T.publishedDate?new Date(T.publishedDate):null,url:""})),isOutdated:!1,isResolved:Ws.has(Hs(f.status)),line:ne,startLine:de,side:E?.side??null,threadId:g(f.id)},qe=m.get(L);qe?qe.push(oe):m.set(L,[oe])}let h=[],y=new Set;for(let f of p.body.value){if(f.hasDeclined)continue;let P=f.vote??0,q=m.get(f.id);P===0&&!q?.length||(h.push({id:f.id,author:le(f),body:"",createdAt:null,url:"",reviewComments:q??[]}),y.add(f.id))}for(let[f,P]of m){if(y.has(f)||!P.length)continue;let q=P[0].author;q&&h.push({id:f,author:q,body:"",createdAt:null,url:"",reviewComments:P})}return{data:h}}};var G=(r,n={})=>R(n.token||r.token,n.isPAT||r.isPAT);var O="https://api.bitbucket.org/2.0",Xs={OPEN:"OPEN",MERGED:"MERGED",DECLINED:"CLOSED",SUPERSEDED:"CLOSED"},Zs={OPEN:["OPEN"],MERGED:["MERGED"],CLOSED:["DECLINED","SUPERSEDED"]},xe=50,Ys=5,Ir=r=>{let n=!r||r.length===0?["OPEN"]:Array.from(new Set(r.flatMap(t=>Zs[t]))),e=n.map(t=>`state="${t}"`).join(" OR ");return n.length>1?`(${e})`:e},en=r=>r.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),br=r=>{let n=r?.trim();if(!n)return null;let e=en(n);return`(title ~ "${e}" OR description ~ "${e}")`},yr=r=>{let n=!!r.next,e=typeof r.size=="number"?r.size:null,t=typeof r.pagelen=="number"&&r.pagelen>0?r.pagelen:null;return{hasNextPage:n,nextPage:n?r.page+1:null,currentPage:typeof r.page=="number"?r.page:null,totalCount:e,totalPages:e!==null&&t?Math.ceil(e/t):null}},ke={owner:4,admin:3,contributor:2,member:1},Ne=r=>({id:r.uuid,name:r.display_name||r.nickname,username:r.nickname||r.display_name,email:null,avatarUrl:r.links.avatar.href,url:r.links.html.href}),Pr=r=>{let n=r.links.clone,e=n?.find(s=>s.name==="ssh"),t=n?.find(s=>s.name==="https");return e&&t?{cloneUrlHTTPS:t.href,cloneUrlSSH:e.href}:null},St=r=>({id:r.uuid,namespace:r.workspace.slug,name:r.slug,webUrl:r.links.html.href,httpsUrl:r.links.clone.find(n=>n.name==="https")?.href??null,sshUrl:r.links.clone.find(n=>n.name==="ssh")?.href??null,defaultBranch:{name:r.mainbranch.name},permissions:null}),qt=r=>{let n=r.id,e=r.participants?.map(t=>{let s="REVIEW_REQUESTED";return t.approved?s="APPROVED":t.state==="changes_requested"?s="CHANGES_REQUESTED":t.participated_on!==null&&(s="COMMENTED"),{reviewer:Ne(t.user),state:s}})??[];return{id:n.toString(),title:r.title,description:r.description,number:n,state:Xs[r.state],isDraft:!1,commentCount:r.comment_count,upvoteCount:null,author:Ne(r.author),createdDate:new Date(r.created_on),updatedDate:new Date(r.updated_on),closedDate:null,mergedDate:null,repository:{id:r.destination.repository.uuid,name:r.destination.repository.name,owner:{login:r.destination.repository.full_name.split("/")[0]},remoteInfo:Pr(r.destination.repository)},headCommit:{buildStatuses:null},baseRef:{name:r.destination.branch.name,oid:r.destination.commit.hash},headRef:{name:r.source.branch.name,oid:r.source.commit.hash},url:r.links.html.href,assignees:null,reviews:e,reviewDecision:B(e),additions:null,deletions:null,fileCount:null,commitCount:null,isCrossRepository:r.source.repository.uuid!==r.destination.repository.uuid,headRepository:{id:r.source.repository.uuid,name:r.source.repository.name,owner:{login:r.source.repository.full_name.split("/")[0]},remoteInfo:Pr(r.source.repository)},mergeableState:"MERGEABLE",permissions:null}},tn=r=>{switch(r){case"owner":case"admin":return{canCreateWebhook:!0,canPush:!0,isAdmin:!0};case"write":return{canCreateWebhook:!1,canPush:!0,isAdmin:!1};case"read":case"none":return{canCreateWebhook:!1,canPush:!1,isAdmin:!1}}},rn=r=>{switch(r){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}}},Re=class extends j{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:`${O}/user`,headers:G(this.config,e)});return{data:Ne(t.body)}}async getUserForCommit(n,e={}){let s=(await this.config.request({url:`${O}/repositories/${n.repo.namespace}/${n.repo.name}/commit/${n.oid}`,headers:G(this.config,e)})).body.author,o=s.raw.match(/([^<]+)<(.+)>/);return{data:{name:o?o[1].trim():null,email:o?o[2]:null,avatarUrl:s.user?.links.avatar.href||null}}}async getRepo(n,e={}){let t=await this.config.request({url:`${O}/repositories/${n.namespace}/${n.name}`,headers:G(this.config,e)});return{data:St(t.body)}}async getRepos(n,e={}){let t=[],s=[];return await Promise.all(n.map(async o=>{try{let i=await this.getRepo(o,e);t.push(i.data)}catch(i){s.push({input:o,error:i})}})),{data:t,errors:s}}async getReposForWorkspace(n,e={}){let t=new URL(`${O}/repositories/${encodeURIComponent(n.workspace)}`);t.searchParams.set("page",n.page?.toString()||"1"),t.searchParams.set("pagelen",C.toString()),n.minimumRole&&t.searchParams.set("role",n.minimumRole);let s=await this.config.request({url:t.toString(),headers:G(this.config,e)}),o=!!s.body.next;return{pageInfo:{hasNextPage:o,nextPage:o?s.body.page+1:null},data:s.body.values.map(St)}}async getAllReposForWorkspace(n,e={}){let t=[],s=1;for(;s!==null;){let o=await this.getReposForWorkspace({workspace:n.workspace,minimumRole:n.minimumRole,page:s},e);t.push(...o.data),s=o.pageInfo.hasNextPage?o.pageInfo.nextPage:null}return t}async getAllReposForWorkspaceWithPermissions(n,e={}){let t=new Map,s=[],o=ke[n.minimumRole||"member"];o<=ke.admin&&s.push("admin"),o<=ke.contributor&&s.push("contributor"),o<=ke.member&&s.push("member");let i=[];for(let a of s){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:rn(u)}})}}async getReposForCurrentUser(n,e={}){let t=new URL(`${O}/repositories`);t.searchParams.set("role","member"),t.searchParams.set("pagelen",C.toString()),n.cursor&&t.searchParams.set("after",n.cursor);let s=await this.config.request({url:t.toString(),headers:G(this.config,e)}),o=!!s.body.next,i=null;return s.body.next&&(i=new URL(s.body.next).searchParams.get("after")),{pageInfo:{hasNextPage:o,endCursor:i},data:s.body.values.map(St)}}async getBranches(n,e={}){let t=new URL(`${O}/repositories/${n.repo.namespace}/${n.repo.name}/refs/branches`);t.searchParams.set("page",n.page?.toString()||"1"),t.searchParams.set("pagelen",C.toString());let s=await this.config.request({url:t.toString(),headers:G(this.config,e)}),o=!!s.body.next;return{pageInfo:{hasNextPage:o,nextPage:o?s.body.page+1:null},data:s.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(`${O}/repositories/${n.repo.namespace}/${n.repo.name}/refs/tags`);t.searchParams.set("pagelen",C.toString()),n.cursor&&t.searchParams.set("page",n.cursor);let s=await this.config.request({url:t.toString(),headers:G(this.config,e)}),o=!!s.body.next,i=null;return s.body.next&&(i=new URL(s.body.next).searchParams.get("page")),{pageInfo:{hasNextPage:o,endCursor:i},data:s.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(`${O}/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 s=await this.config.request({url:t.toString(),headers:G(this.config,e)}),o=!!s.body.next;return{pageInfo:{hasNextPage:o,nextPage:o?s.body.page+1:null},data:s.body.values.map(i=>({id:i.workspace.uuid,slug:i.workspace.slug}))}}async getWorkspacesForUser(n,e={}){let t=new URL(`${O}/user/permissions/workspaces`);t.searchParams.set("page",n.page?.toString()||"1"),t.searchParams.set("pagelen","50");let s=await this.config.request({url:t.toString(),headers:G(this.config,e)}),o=!!s.body.next;return{pageInfo:{hasNextPage:o,nextPage:o?s.body.page+1:null},data:s.body.values.map(i=>({id:i.workspace.uuid,slug:i.workspace.slug,name:i.workspace.name}))}}async getPullRequestsForUserAndWorkspace(n,e={}){let t=new URL(`${O}/workspaces/${n.workspaceSlug}/pullrequests/${n.userId}`);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",U(n.pageSize,{fallback:xe,max:xe}).toString());let s=[Ir(n.states)];n.repos&&n.repos.length>0&&s.push(`(${n.repos.map(a=>`source.repository.full_name = "${a.namespace}/${a.name}"`).join(" OR ")})`);let o=br(n.query);o&&s.push(o),t.searchParams.set("q",s.join(" AND "));let i=await this.config.request({url:t.toString(),headers:G(this.config,e)});return{pageInfo:yr(i.body),data:i.body.values.map(qt)}}async getPullRequestsForReviewerAndWorkspace(n,e={}){let t=n.repos?.length?n.repos:await this.getAllReposForWorkspace({workspace:n.workspaceSlug},e);return this.getPullRequestsForRepos({repos:t,reviewerId:n.reviewerId,states:n.states,query:n.query,pageSize:n.pageSize},e)}async getPullRequestsForRepoBase(n,e={}){let t=new URL(`${O}/repositories/${encodeURI(n.repo.namespace)}/${encodeURI(n.repo.name)}/pullrequests`),s=[];n.reviewerId&&s.push(`reviewers.uuid="${n.reviewerId}"`),n.authorLogin&&s.push(`author.uuid="${n.authorLogin}"`);let o=Ir(n.states);s.length&&(o+=` AND (${s.join(n.useOrFilter?" OR ":" AND ")})`);let i=br(n.query);return i&&(o+=` AND ${i}`),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",U(n.pageSize,{fallback:xe,max:xe}).toString()),t.searchParams.set("q",o),await this.config.request({url:t.toString(),headers:G(this.config,e)})}async getPullRequestsForRepo(n,e={}){let t=[],s=await this.getPullRequestsForRepoBase(n,e);return s.body.values.forEach(o=>{t.push(qt(o))}),{pageInfo:yr(s.body),data:t}}async getPullRequestsForRepos(n,e={}){let{successes:t,metadata:s}=await J(n.repos,{run:i=>this.getPullRequestsForRepoBase({repo:i,authorLogin:n.authorLogin,reviewerId:n.reviewerId,useOrFilter:n.useOrFilter,states:n.states,query:n.query,pageSize:n.pageSize},e),failureScope:i=>({providerId:"bitbucket",repositoryId:ae(i)}),completeness:i=>i.body.next?"partial":"complete",concurrency:Ys}),o=[];return t.forEach(({result:i})=>{i.body.values.forEach(a=>{o.push(qt(a))})}),{data:o,metadata:s}}async getAccountsForWorkspace(n,e={}){let t=new URL(`${O}/workspaces/${encodeURI(n.workspace)}/members`);t.searchParams.set("page",n.page?.toString()||"1"),t.searchParams.set("pagelen","100");let s=await this.config.request({url:t.toString(),headers:G(this.config,e)}),o=!!s.body.next;return{pageInfo:{hasNextPage:o,nextPage:o?s.body.page+1:null},data:s.body.values.map(i=>Ne(i.user))}}async getReposPermissionsForCurrentUser(n,e={}){let t=new URL(`${O}/user/permissions/repositories`);t.searchParams.set("page",n.page?.toString()||"1"),t.searchParams.set("pagelen","100");let s=await this.config.request({url:t.toString(),headers:G(this.config,e)}),o=!!s.body.next;return{pageInfo:{hasNextPage:o,nextPage:o?s.body.page+1:null},data:s.body.values.reduce((i,a)=>({...i,[a.repository.uuid]:tn(a.permission)}),{})}}async decorateReposWithPermissions(n,e={}){let t={},s=1;do{let o=await this.getReposPermissionsForCurrentUser({page:s},e);t={...o.data,...t},s=o.pageInfo.hasNextPage?o.pageInfo.nextPage:null}while(s!==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:`${O}/repositories/${t.repository.owner.login}/${t.repository.name}/pullrequests/${t.id}/decline`,headers:G(this.config,e)})).body.title)throw new Error("Could not close pull request")}async mergePullRequest(n,e={}){let{pullRequest:t,mergeStrategy:s}=n,o;switch(s){case"MERGE_COMMIT":{o="merge_commit";break}case"FAST_FORWARD":{o="fast_forward";break}case"SQUASH":{o="squash";break}}let i={merge_strategy:o,type:"pullrequest"};if(!(await this.config.request({method:"POST",url:`${O}/repositories/${t.repository.owner.login}/${t.repository.name}/pullrequests/${t.id}/merge`,body:JSON.stringify(i),headers:{...G(this.config,e),"Content-Type":"application/json"}})).body.title)throw new Error("Could not merge pull request")}async setPullRequestReviewers(n,e={}){let{pullRequest:t,reviewers:s}=n,o={reviewers:s.map(a=>{if(a.username)throw new Error('Bitbucket reviewer requires "username" for this function.');return{username:a.username}})};if(!(await this.config.request({method:"PUT",url:`${O}/repositories/${t.repository.owner.login}/${t.repository.name}/pullrequests/${t.id}`,body:JSON.stringify(o),headers:{...G(this.config,e),"Content-Type":"application/json"}})).body.title)throw new Error("Could not set pull request reviewers")}};var wr=r=>r?r.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}:r.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 Ee=r=>{let n=r.links.self[0].href;return{name:r.displayName,email:r.emailAddress,avatarUrl:r.avatarUrl??(n&&`${n}/avatar.png`),id:r.id.toString(),username:r.name,url:n}},Fe=r=>{let n={OPEN:"OPEN",MERGED:"MERGED",DECLINED:"CLOSED"},e={UNAPPROVED:"REVIEW_REQUESTED",NEEDS_WORK:"CHANGES_REQUESTED",APPROVED:"APPROVED"},t=r.reviewers.map(u=>({reviewer:Ee(u.user),state:e[u.status]})),s=r.toRef.repository.links.clone.find(u=>u.name==="ssh")?.href??null,o=r.toRef.repository.links.clone.find(u=>u.name==="https")?.href??null;o||(o=r.toRef.repository.links.clone.find(u=>u.name==="http")?.href??null);let i=r.fromRef.repository.links.clone.find(u=>u.name==="ssh")?.href??null,a=r.fromRef.repository.links.clone.find(u=>u.name==="https")?.href??null;return a||(a=r.fromRef.repository.links.clone.find(u=>u.name==="http")?.href??null),{id:r.id.toString(),number:r.id,title:r.title,description:r.description,url:r.links.self[0].href,state:n[r.state],isDraft:!1,createdDate:new Date(r.createdDate),updatedDate:new Date(r.updatedDate),closedDate:r.closedDate?new Date(r.closedDate):null,mergedDate:r.state=="MERGED"&&r.closedDate?new Date(r.closedDate):null,baseRef:{name:r.toRef.displayId,oid:r.toRef.latestCommit},headRef:{name:r.fromRef.displayId,oid:r.fromRef.latestCommit},commentCount:r.properties.commentCount,upvoteCount:null,commitCount:null,fileCount:null,additions:null,deletions:null,author:Ee(r.author.user),assignees:null,reviews:t,reviewDecision:B(t),isCrossRepository:r.fromRef.repository.id!==r.toRef.repository.id,repository:{id:r.toRef.repository.id.toString(),name:r.toRef.repository.name,owner:{login:r.toRef.repository.project.key},remoteInfo:o&&s?{cloneUrlHTTPS:o,cloneUrlSSH:s}:null},headRepository:{id:r.fromRef.repository.id.toString(),name:r.fromRef.repository.name,owner:{login:r.fromRef.repository.project.key},remoteInfo:a&&i?{cloneUrlHTTPS:a,cloneUrlSSH:i}:null},headCommit:null,mergeableState:"MERGEABLE",permissions:null,version:r.version}},Sr=r=>({id:r.id.toString(),namespace:r.project.key,name:r.slug,webUrl:r.links.self[0]?.href??null,httpsUrl:r.links.clone.find(n=>n.name==="https"||n.name==="http")?.href??null,sshUrl:r.links.clone.find(n=>n.name==="ssh")?.href??null,defaultBranch:null,permissions:null}),qr=50,sn=5,nn={OPEN:"OPEN",MERGED:"MERGED",CLOSED:"DECLINED"},vr=r=>{if(!r||r.length===0)return"OPEN";let n=Array.from(new Set(r.map(e=>nn[e])));return n.length===1?n[0]:"ALL"},Er=(r,n)=>typeof r!="number"||n<=0?null:Math.floor(r/n)+1,Ie=class extends N{getBaseUrl(n){let e=n.baseUrl||this.config.baseUrl;if(!e)throw new Error('Bitbucket Server requires "baseUrl"');return e}getRequestHeaders(n){return R(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":s,"x-ausername":o}}=t,i=s?parseInt(s,10):null,a=decodeURIComponent(o),l=(await this.config.request({url:`${this.getBaseUrl(e)}/users?filter=${o}&avatarSize=64`,headers:this.getRequestHeaders(e)})).body.values.find(({emailAddress:p,id:d,name:c,slug:g})=>i?i===d:a===c||a===p||a===g);if(!l)throw new Error("Could not find current Bitbucket Server user");return{data:Ee(l)}}async getUserForCommit(n,e){let{repo:t,oid:s}=n,o=await this.config.request({url:`${this.getBaseUrl(e)}/projects/${t.namespace}/repos/${t.name}/commits/${s}`,headers:this.getRequestHeaders(e)});if(!o.body.author)throw new Error("Could not find user for commit");return{data:Ee(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:Sr(t.body)}}async getRepos(n,e={}){let t=[],s=[];return await Promise.all(n.map(async o=>{try{let i=await this.getRepo(o,e);t.push(i.data)}catch(i){s.push({input:o,error:i})}})),{data:t,errors:s}}async getReposForCurrentUser(n,e={}){let t=n.page??0,s=await this.config.request({url:`${this.getBaseUrl(e)}/repos?start=${t}`,headers:this.getRequestHeaders(e)});return{pageInfo:{hasNextPage:!s.body.isLastPage,nextPage:s.body.nextPageStart},data:s.body.values.map(Sr)}}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 s=await this.config.request({url:t.toString(),headers:this.getRequestHeaders(e)});return{data:wr(s.body.values)}}catch(s){if(s.response?.status===401)return{data:{canCreateWebhook:!1,canPush:!1,isAdmin:!1}};throw s}}async decorateReposWithPermissions(n,e={}){return await Promise.all(n.repos.map(async s=>{let o=await this.getRepoPermissionsForUsername({repo:s,username:n.username},e);return{...s,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`);return t.searchParams.set("state",vr(n.states)),t.searchParams.set("start",n.page?.toString()||"0"),t.searchParams.set("limit",U(n.pageSize,{fallback:qr}).toString()),n.reviewerLogin&&(t.searchParams.set("role.1","REVIEWER"),t.searchParams.set("username.1",n.reviewerLogin)),await this.config.request({url:t.toString(),headers:this.getRequestHeaders(e)})}async getPullRequestsForRepo(n,e={}){let t=[],s=await this.getPullRequestsForRepoBase(n,e);s.body.values.forEach(i=>{if(n.authorLogin&&i.author.user.name!==n.authorLogin)return null;t.push(Fe(i))});let o=!s.body.isLastPage;return{pageInfo:{hasNextPage:o,nextPage:o?s.body.nextPageStart:null,currentPage:Er(s.body.start,s.body.limit)},data:k(t,n.states)}}async getPullRequestsForRepos(n,e={}){let{successes:t,metadata:s}=await J(n.repos,{run:i=>this.getPullRequestsForRepoBase({repo:i,reviewerLogin:n.reviewerLogin,states:n.states,pageSize:n.pageSize},e),failureScope:i=>({providerId:"bitbucketServer",repositoryId:ae(i)}),completeness:i=>i.body.isLastPage?"complete":"partial",concurrency:sn}),o=[];return t.forEach(({result:i})=>{i.body.values.forEach(a=>{n.authorLogin&&a.author.user.name!==n.authorLogin||o.push(Fe(a))})}),{data:k(o,n.states),metadata:s}}async getPullRequestsForCurrentUser(n,e={}){let t=new URL(`${this.getBaseUrl(e)}/dashboard/pull-requests`);t.searchParams.set("state",vr(n.states)),t.searchParams.set("start",n.page?.toString()||"0");let s=U(n.pageSize,{fallback:qr});t.searchParams.set("limit",s.toString()),n.reviewerLogin&&(t.searchParams.set("role.1","REVIEWER"),t.searchParams.set("username.1",n.reviewerLogin));let o=await this.config.request({url:t.toString(),headers:this.getRequestHeaders(e)}),i=!o.body.isLastPage;return{pageInfo:{hasNextPage:i,nextPage:i?o.body.nextPageStart:null,currentPage:Er(o.body.start,o.body.limit)},data:k(o.body.values.map(Fe),n.states)}}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:s}=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:s,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:s}=n;if(t.version===void 0)throw new Error('Bitbucket Server requires "version" for this function.');let o={reviewers:s.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 s=await this.config.request({url:t.toString(),headers:this.getRequestHeaders(e)}),o=s.body.values.length!==0;return{pageInfo:{hasNextPage:o,nextPage:o?s.body.start+s.body.values.length:null},data:s.body.values.map(i=>Ee(i.user))}}};var Br=require("js-base64");var I=class extends Error{constructor(e,t){let s=t?.map(i=>`'${i.message}'`).join(", "),o=s?`${e}: ${s}`:e;super(o);this.graphQLErrors=t??[]}};var on={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]},Cr=15,$r=100,Ce={__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"},x=r=>!!r,z=(r,n)=>{let e=on[n];for(let t=0;t<3;t++){if(r[t]>e[t])return!0;if(r[t]<e[t])return!1}return!0},Qe="https://api.github.com",an=`${Qe}/graphql`,Be=`
|
|
1
|
+
"use strict";var gt=Object.defineProperty;var $s=Object.getOwnPropertyDescriptor;var Ds=Object.getOwnPropertyNames;var Ls=Object.prototype.hasOwnProperty;var Us=(r,n)=>{for(var e in n)gt(r,e,{get:n[e],enumerable:!0})},As=(r,n,e,t)=>{if(n&&typeof n=="object"||typeof n=="function")for(let s of Ds(n))!Ls.call(r,s)&&s!==e&>(r,s,{get:()=>n[s],enumerable:!(t=$s(n,s))||t.enumerable});return r};var Gs=r=>As(gt({},"__esModule",{value:!0}),r);var Go={};Us(Go,{AzureDevOps:()=>fe,Bitbucket:()=>Re,BitbucketServer:()=>Ie,EntityIdentifierProviderType:()=>ws,EntityType:()=>Ps,EntityVersion:()=>ys,GitBuildStatusStage:()=>nr,GitBuildStatusState:()=>Te,GitDiffLineType:()=>ht,GitHub:()=>be,GitHubIssueCloseReason:()=>Ss,GitIssueState:()=>le,GitLab:()=>ye,GitMergeStrategy:()=>ge,GitPullRequestMergeableState:()=>ae,GitPullRequestReviewState:()=>te,GitPullRequestState:()=>ee,GraphQLErrors:()=>I,Jira:()=>Pe,JiraServer:()=>we,PullRequestAsyncStatus:()=>bs,Trello:()=>Se,default:()=>Ao,isFetch:()=>_e});module.exports=Gs(Go);var Rr=require("diff");var nr=(s=>(s.Build="build",s.Production="production",s.Staging="staging",s.Test="test",s))(nr||{}),Te=(l=>(l.ActionRequired="ACTION_REQUIRED",l.Cancelled="CANCELLED",l.Error="ERROR",l.Failed="FAILED",l.Pending="PENDING",l.Running="RUNNING",l.Skipped="SKIPPED",l.Success="SUCCESS",l.Warning="WARNING",l.OptionalActionRequired="OPTIONAL_ACTION_REQUIRED",l))(Te||{}),ge=(o=>(o.MergeCommit="MERGE_COMMIT",o.Rebase="REBASE",o.RebaseThenMergeCommit="REBASE_THEN_MERGE_COMMIT",o.FastForward="FAST_FORWARD",o.Squash="SQUASH",o))(ge||{}),ee=(t=>(t.Open="OPEN",t.Closed="CLOSED",t.Merged="MERGED",t))(ee||{}),te=(s=>(s.Approved="APPROVED",s.ChangesRequested="CHANGES_REQUESTED",s.Commented="COMMENTED",s.ReviewRequested="REVIEW_REQUESTED",s))(te||{}),ae=(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))(ae||{}),ht=(t=>(t.ADDED="ADDED",t.DELETED="DELETED",t.UNMODIFIED="UNMODIFIED",t))(ht||{});var or={APPROVED:0,COMMENTED:1,REVIEW_REQUESTED:2,CHANGES_REQUESTED:3},B=r=>!r||r.length===0?null:r.reduce((n,e)=>or[e.state]>or[n]?e.state:n,"APPROVED");var Ts=new Set(["ECONNABORTED","ECONNREFUSED","ECONNRESET","EAI_AGAIN","ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"]),R=(r,n)=>{let e={};return r&&(e.Authorization=`${n?"Basic":"Bearer"} ${r}`),e},ar=r=>r?r.reduce((n,e)=>(n[e]=!0,n),{}):void 0,re=(r,n,e)=>!r||n.some(t=>r[t])?e:"",ur=async r=>{let n=[],e=!0,t;for(;e;){let s=await r(t);n=n.concat(s.data),e=!!s?.pageInfo?.hasNextPage,t=s?.pageInfo?.endCursor||s?.pageInfo?.nextPage}return n};async function ft(r){return(await Promise.allSettled(r)).map(e=>Ns(e)).filter(e=>e!=null)}var $=(r,{fallback:n,max:e})=>!r||r<=0?n:e===void 0?r:Math.min(r,e),k=(r,n)=>{if(!n||n.length===0)return r;let e=new Set(n);return r.filter(t=>e.has(t.state))},Os=r=>{if(!(!r||typeof r!="object")){if("statusCode"in r&&typeof r.statusCode=="number")return r.statusCode;if("response"in r&&r.response&&typeof r.response=="object"&&"status"in r.response&&typeof r.response.status=="number")return r.response.status}},_s=r=>{if(!(!r||typeof r!="object"||!("code"in r)||typeof r.code!="string"))return r.code},lr=r=>{if(typeof r=="string")return r;if(r instanceof Error)return r.message},xs=r=>{let n=Os(r);if(n===401)return"authentication";if(n===404)return"not-found";if(n===429)return"rate-limit";if(n!==void 0)return"provider";let e=_s(r);if(e&&Ts.has(e))return"network";let t=lr(r)?.toLowerCase();return t&&(t.includes("network")||t.includes("fetch failed")||t.includes("timed out")||t.includes("timeout")||t.includes("econn")||t.includes("enotfound")||t.includes("eai_again"))?"network":"unknown"},ks=(r,n)=>{let e=lr(n);return{scope:r,kind:xs(n),...e?{message:e}:{}}},J=(r,n=[])=>({completeness:r,...n.length?{failures:n}:{}}),ir={complete:0,unknown:1,partial:2},Oe=(r,n)=>ir[r]>=ir[n]?r:n,ue=r=>r?r.id||`${r.namespace}/${r.name}`:void 0;async function V(r,{run:n,failureScope:e,completeness:t,concurrency:s}){let o=async l=>{try{return{scope:l,result:await n(l)}}catch(d){return{scope:l,error:d}}},i;if(s===void 0)i=await Promise.all(r.map(o));else{if(!Number.isInteger(s)||s<=0)throw new Error("concurrency must be a positive integer");let l=new Array(r.length);await Rt(r.map((d,c)=>({scope:d,index:c})),s,async({scope:d,index:c})=>{l[c]=await o(d)}),i=l}let a=[],u=[],p="complete";return i.forEach(l=>{if("error"in l){a.push(ks(e(l.scope),l.error)),p=Oe(p,"partial");return}if(l.result===void 0)return;let d=l.result;p=Oe(p,t?t(d):"complete"),u.push({scope:l.scope,result:d})}),{successes:u,metadata:J(p,a)}}function Ns(r,n=void 0){return r?.status==="fulfilled"?r.value:n}async function Rt(r,n,e){if(!Number.isFinite(n)||!Number.isInteger(n)||n<=0)throw new Error("batchSize must be a positive integer");for(let t=0;t<r.length;t+=n){let s=r.slice(t,t+n);await Promise.all(s.map(e))}}var le=(e=>(e.Open="OPEN",e.Closed="CLOSED",e))(le||{});var It=(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))(It||{});var C=100;var pr=globalThis.fetch;var Fs=async r=>{let n=r.headers.get("content-type")||"",e=null;if(n.startsWith("application/json")){let o=await r.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 r.text();else if(n.startsWith("application/vnd.github.raw+json")||n.startsWith("application/octet-stream"))e=await r.arrayBuffer();else throw new Error(`Unsupported content-type: ${n}`);let t={};r.headers.forEach((o,i)=>{t[i]=o});let s={body:e,headers:t,status:r.status,statusText:r.statusText};if(!r.ok){let o=new Error(r.statusText);throw Object.assign(o,{response:s}),o}return s},bt=r=>async({url:n,...e})=>{let t=await r(n,e);return Fs(t)};var _e=(r,n=!1)=>r.name==="fetch"||n;var j=class{constructor(n){let e=n?.request||pr;this.config={...n,request:_e(e,n?.forceIsFetch)?bt(e):e}}updateConfig(n){this.config={...this.config,...n,request:n.request&&_e(n.request,n?.forceIsFetch??this.config.forceIsFetch)?bt(n.request):this.config.request}}},N=class extends j{};var js="https://app.vssps.visualstudio.com/_apis",Qs="https://vssps.dev.azure.com/",Bs="https://dev.azure.com",S=(r,n={})=>R(n.token||r.token,n.isPAT||r.isPAT),dr=r=>r.url.replace("/_apis/git/repositories/","/_git/").replace(`/${r.repository.project.id}/`,`/${encodeURIComponent(r.repository.project.name)}/`).replace(`/${r.repository.id}/`,`/${encodeURIComponent(r.repository.name)}/`).replace("/pullRequests/","/pullrequest/"),yt=(r,n)=>{let e=n.baseUrl||r.baseUrl||js;return e=e.replace(/\/$/,""),e},D=(r,n)=>{let e=n.baseUrl||r.baseUrl||Bs;return e=e.replace(/\/$/,""),e},Pt=(r,n)=>{let e=n.baseUrl||r.baseUrl||Qs;return e=e.replace(/\/$/,""),e};var Ms={active:"OPEN",completed:"MERGED",abandoned:"CLOSED"},zs={OPEN:"active",MERGED:"completed",CLOSED:"abandoned"},he=100,Hs=200,cr=5,Ws=200,mr=r=>{if(!r||r.length===0)return"active";let n=Array.from(new Set(r.map(e=>zs[e])));return n.length===1?n[0]:"all"},Js=r=>{if(!r||r.length===0)return["[Microsoft.VSTS.Common.ClosedDate] = ''","[Microsoft.VSTS.Common.ResolvedDate] = ''"];let n=new Set(r),e=n.has("OPEN"),t=n.has("CLOSED");return e&&t?[]:t?["([Microsoft.VSTS.Common.ClosedDate] <> '' OR [Microsoft.VSTS.Common.ResolvedDate] <> '')"]:["[Microsoft.VSTS.Common.ClosedDate] = ''","[Microsoft.VSTS.Common.ResolvedDate] = ''"]},Vs=r=>{if(typeof r!="string")return r;let n=r.charAt(0).toUpperCase()+r.slice(1);return It[n]??0},Ks=new Set([2,3,4,5]),Xs={10:"APPROVED",5:"APPROVED",0:"REVIEW_REQUESTED",[-5]:"CHANGES_REQUESTED",[-10]:"CHANGES_REQUESTED"},pe=r=>({id:r.id,name:r.displayName??null,username:(r.uniqueName||r.displayName)??null,email:null,avatarUrl:r.imageUrl??null,url:null}),xe=r=>r.startsWith("refs/heads/")?r.replace("refs/heads/",""):r,Zs=r=>{switch(r){case"conflicts":return"CONFLICTS";case"failure":return"FAILING_CHECKS";case"rejectedByPolicy":return"BLOCKED";case"succeeded":return"MERGEABLE";case"notSet":case"queued":default:return"UNKNOWN"}},wt=(r,n,e,t,s,o)=>`${r}|${n}|${e}|${t}|${s}|${o}`,gr=r=>{let n=r.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]}},hr=(r,n,e,t,s)=>`${r}|${n}|${e}|${t}|${s}`,St=r=>{let n=r.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]}},ve=(r,n,e)=>{let t=!!n.forkSource,s=[],o=[];return n.reviewers.forEach(i=>{let a={reviewer:pe(i),state:Xs[i.vote??0]||"REVIEW_REQUESTED"};i.isRequired&&s.push(a),o.push(a)}),{id:n.pullRequestId.toString(),title:n.title,description:n.description??null,number:n.codeReviewId,state:Ms[n.status],isDraft:n.isDraft,commentCount:null,upvoteCount:null,author:pe(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,isCrossRepository:t,repository:{id:n.repository.id,name:n.repository.name,project:n.repository.project.name,owner:{login:r},remoteInfo:e?.get(n.repository.id)??null},headCommit:{buildStatuses:null},baseRef:{name:xe(n.targetRefName),oid:n.lastMergeTargetCommit.commitId},headRef:{name:xe(n.sourceRefName),oid:n.lastMergeSourceCommit.commitId},url:dr(n),assignees:n.reviewers.map(pe),reviews:o,reviewDecision:B(s),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:r},remoteInfo:e?.get(n.forkSource.repository.id)??null,isFork:!0}:{id:n.repository.id,name:n.repository.name,project:n.repository.project.name,owner:{login:r},remoteInfo:e?.get(n.repository.id)??null,isFork:!1},mergeableState:Zs(n.mergeStatus),labels:n.labels?.map(i=>({color:null,description:null,id:i.id,name:i.name}))??[],permissions:null}},fr=(r,n)=>({id:n.id,name:n.name,namespace:r,project:n.project.name,projectId:n.project.id,webUrl:n.webUrl,httpsUrl:n.remoteUrl,sshUrl:n.sshUrl,defaultBranch:n.defaultBranch?{name:xe(n.defaultBranch)}:null,permissions:null}),Ys=(r,n,e,t)=>{let s=e.fields,o=s["System.AssignedTo"],i=s["System.State"],a=s["System.WorkItemType"],u;return i&&a&&(u=t[a]?.[i]),{id:e.id.toString(),number:e.id.toString(),title:s["System.Title"],commentCount:s["System.CommentCount"],author:{avatarUrl:s["System.CreatedBy"]._links?.avatar?.href??null,email:null,id:s["System.CreatedBy"].id,name:s["System.CreatedBy"].uniqueName??null,username:s["System.CreatedBy"].displayName??null,url:null},closedDate:s["Microsoft.VSTS.Common.ClosedDate"]?new Date(s["Microsoft.VSTS.Common.ClosedDate"]):null,createdDate:new Date(s["System.CreatedDate"]),updatedDate:new Date(s["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:s["System.Description"]??null,state:{name:u?.title||i,color:null},type:s["System.WorkItemType"],repository:null,project:{namespace:r,name:n,resourceId:null,key:null,id:null},upvoteCount:0,labels:e.fields["System.Tags"]?.split(";").map(p=>({color:null,description:null,id:null,name:p.trim()}))??[]}},fe=class extends N{constructor(){super(...arguments);this.cachedUserIds=new Map;this.inflightUserIds=new Map}getCurrentUserId(e,t){let s=JSON.stringify([e,t.token??null,t.isPAT??this.config.isPAT??!1,t.baseUrl??null]),o=this.cachedUserIds.get(s);if(o)return Promise.resolve(o);let i=this.inflightUserIds.get(s);if(i)return i;let a=this.fetchCurrentUserId(e,t,s);return this.inflightUserIds.set(s,a),a}async fetchCurrentUserId(e,t,s){try{let o=await this.getCurrentUserForInstance({namespace:e},t);return this.cachedUserIds.set(s,o.data.id),o.data.id}finally{this.inflightUserIds.delete(s)}}getRepoApiUrl(e,t,s,o){return`${D(this.config,o)}/${encodeURIComponent(e)}/${encodeURIComponent(t)}/_apis/git/repositories/${encodeURIComponent(s)}`}async getCurrentUser(e={},t={}){if(t.isPAT||this.config.isPAT)throw new Error("Azure DevOps does not support PATs for this function.");let s=`${yt(this.config,t)}/profile/profiles/me`,o=await this.config.request({url:s,headers:S(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:`${D(this.config,t)}/${encodeURIComponent(e.namespace)}/_apis/ConnectionData`,headers:S(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:`${D(this.config,t)}/${encodeURIComponent(e.repo.namespace)}/${encodeURIComponent(e.repo.project)}/_apis/git/repositories/${encodeURIComponent(e.repo.name)}/commits/${e.oid}`,headers:S(this.config,t)})).body.author;return{data:{name:o.name,email:o.email,avatarUrl:o.imageUrl}}}async getOrgsForUser(e,t={}){let s=`${yt(this.config,t)}/accounts?memberId=${e.userId}&api-version=6.0`;return{data:(await this.config.request({url:s,headers:S(this.config,t)})).body.value.map(i=>({id:i.accountId,name:i.accountName}))}}async getCollectionsForUser(e,t={}){let s=`${D(this.config,t)}/_apis/projectCollections`;return{data:(await this.config.request({url:s,headers:S(this.config,t)})).body.value.map(i=>({id:i.id,name:i.name}))}}async getAzureProjects(e,t={}){let s=new URL(`${D(this.config,t)}/${encodeURIComponent(e.namespace)}/_apis/projects`);s.searchParams.set("$top",C.toString()),e.cursor&&s.searchParams.set("$skip",e.cursor);let o=await this.config.request({url:s.toString(),headers:S(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:s,projectId:o}=e;return{data:{scope:(await this.config.request({url:`${Pt(this.config,t)}/${encodeURIComponent(s)}/_apis/graph/descriptors/${o}?api-version=6.0`,headers:S(this.config,t)})).body.value}}}async getAzureGraphAccountsForAzureProject(e,t={}){let{namespace:s,projectScopeDescriptor:o,cursor:i}=e,a=new URL(`${Pt(this.config,t)}/${encodeURIComponent(s)}/_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:S(this.config,t)}),p=u.headers["x-ms-continuationtoken"];return{pageInfo:{endCursor:p||null,hasNextPage:!!p},data:u.body.value.map(l=>({avatarUrl:l._links?.avatar?.href??null,descriptor:l.descriptor??null,email:l.mailAddress??null,name:l.displayName??null,storageKeyURL:l._links?.storageKey?.href??null,username:l.displayName??null}))}}async getAccountFromAzureGraphAccount(e,t={}){let{azureGraphAccount:s}=e;if(!s.storageKeyURL)throw new Error("Expected 'storageKeyURL' to not be null for 'azureGraphAccount'");let o=await this.config.request({url:s.storageKeyURL,headers:S(this.config,t)});return{data:{avatarUrl:s.avatarUrl,email:s.email,id:o.body.value,name:s.name,username:s.username,url:null}}}async getAccountsFromAzureGraphAccounts(e,t={}){let s=[];for(let o of e.azureGraphAccounts){let i=await this.getAccountFromAzureGraphAccount({azureGraphAccount:o},t);s.push(i.data)}return{data:s}}async getRepo(e,t={}){if(!e.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let s=await this.config.request({url:`${D(this.config,t)}/${encodeURIComponent(e.namespace)}/${encodeURIComponent(e.project)}/_apis/git/repositories/${encodeURIComponent(e.name)}`,headers:S(this.config,t)});return{data:fr(e.namespace,s.body)}}async getRepos(e,t={}){let s=[],o=[];return await Promise.all(e.map(async i=>{try{let a=await this.getRepo(i,t);s.push(a.data)}catch(a){o.push({input:i,error:a})}})),{data:s,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:`${D(this.config,t)}/${encodeURIComponent(e.namespace)}/${encodeURIComponent(e.project)}/_apis/git/repositories`,headers:S(this.config,t)})).body.value.map(o=>fr(e.namespace,o))}}async getRefs(e,t,s={}){if(!t.repo.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let o=new URL(`${D(this.config,s)}/${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",C.toString()),t.cursor&&o.searchParams.set("continuationToken",t.cursor);let i=await this.config.request({url:o.toString(),headers:S(this.config,s)}),a=i.headers["x-ms-continuationtoken"];return{pageInfo:{hasNextPage:!!a,endCursor:a||null},data:i.body.value.map(u=>({name:xe(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 fetchRemoteInfoByRepoId(e,t,s){let o=new Map;if(!e)return o;let i=new Map;for(let{namespace:a,pullRequests:u}of t)for(let p of u)i.has(p.repository.id)||i.set(p.repository.id,a),p.forkSource&&!i.has(p.forkSource.repository.id)&&i.set(p.forkSource.repository.id,a);return await Rt([...i],10,async([a,u])=>{try{let p=await this.config.request({url:`${D(this.config,s)}/${encodeURIComponent(u)}/_apis/git/repositories/${encodeURIComponent(a)}`,headers:S(this.config,s)}),{remoteUrl:l,sshUrl:d}=p.body;l&&d&&o.set(a,{cloneUrlHTTPS:l,cloneUrlSSH:d})}catch{}}),o}async getPullRequestsForRepoBase(e,t={},s=he){let{page:o,repo:i,assigneeLogins:a,authorLogin:u,reviewerId:p}=e||{},l=o||1;if(!i.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let d=$(e.pageSize,{fallback:s}),c=p??(a&&a.length?a[0]:void 0),m=`searchCriteria.status=${mr(e.states)}`;return c&&(m+=`&searchCriteria.reviewerId=${encodeURIComponent(c)}`),u&&(m+=`&searchCriteria.creatorId=${encodeURIComponent(u)}`),await this.config.request({url:`${D(this.config,t)}/${encodeURIComponent(i.namespace)}/${encodeURIComponent(i.project||"")}/_apis/git/repositories/${encodeURIComponent(i.name)}/pullRequests?${m}&%24top=${d}&%24skip=${(l-1)*d}`,headers:S(this.config,t)})}async getPullRequestsForRepo(e,t={}){let s=$(e.pageSize,{fallback:he}),o=e.page||1,i=await this.getPullRequestsForRepoBase(e,t,s),a=i.body.value.length===s,u=await this.fetchRemoteInfoByRepoId(e.includeRemoteInfo,[{namespace:e.repo.namespace,pullRequests:i.body.value}],t);return{pageInfo:{hasNextPage:a,nextPage:a?o+1:null,currentPage:o},data:k(i.body.value.map(p=>ve(e.repo.namespace,p,u)),e.states)}}async getPullRequestsForRepos(e,t={}){if(!e.repos.every(d=>d.project))throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let{repos:s}=e||{},o=$(e.pageSize,{fallback:he}),{successes:i,metadata:a}=await V(s,{run:d=>this.getPullRequestsForRepoBase({repo:d,assigneeLogins:e.assigneeLogins,authorLogin:e.authorLogin,reviewerId:e.reviewerId,states:e.states,pageSize:o},t,o),failureScope:d=>({providerId:"azure",projectId:d.project,repositoryId:ue(d)}),completeness:d=>d.body.value.length===o?"unknown":"complete",concurrency:cr}),u=i.map(({scope:d,result:c})=>({namespace:d.namespace,pullRequests:c.body.value})),p=await this.fetchRemoteInfoByRepoId(e.includeRemoteInfo,u,t),l=u.flatMap(({namespace:d,pullRequests:c})=>c.map(m=>ve(d,m,p)));return{data:k(l,e.states),metadata:a}}async getPullRequestsForProjectBase(e,t={},s=he){let{namespace:o,project:i,page:a,assigneeLogins:u,authorLogin:p,reviewerId:l,repo:d}=e;if(d?.project&&d.project!==i)throw new Error("Could not fetch pull requests, project mismatch");let c=a||1,m=$(e.pageSize,{fallback:s}),g=l??(u&&u.length?u[0]:void 0),h=new URL(`${D(this.config,t)}/${encodeURIComponent(o)}/${encodeURIComponent(i)}/_apis/git/pullRequests`);return h.searchParams.set("searchCriteria.status",mr(e.states)),h.searchParams.set("$top",m.toString()),h.searchParams.set("$skip",((c-1)*m).toString()),d?.id&&d?.project===i&&h.searchParams.set("searchCriteria.repositoryId",d.id),g&&h.searchParams.set("searchCriteria.reviewerId",g),p&&h.searchParams.set("searchCriteria.creatorId",p),await this.config.request({url:h.toString(),headers:S(this.config,t)})}async getPullRequestsForProject(e,t={}){let s=$(e.pageSize,{fallback:he}),o=e.page||1,i=await this.getPullRequestsForProjectBase(e,t,s),a=i.body.value.length===s,u=await this.fetchRemoteInfoByRepoId(e.includeRemoteInfo,i?[{namespace:e.namespace,pullRequests:i.body.value}]:[],t);return{pageInfo:{hasNextPage:a,nextPage:a?o+1:null,currentPage:o},data:k(i?.body.value.map(p=>ve(e.namespace,p,u))||[],e.states)}}async getPullRequestsForProjects(e,t={}){let{projects:s}=e||{};if(e.repo&&!e.repo.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let o=$(e.pageSize,{fallback:he}),{successes:i,metadata:a}=await V(s,{run:d=>e.repo&&e.repo.project!==d.project?Promise.resolve(void 0):this.getPullRequestsForProjectBase({...d,assigneeLogins:e.assigneeLogins,authorLogin:e.authorLogin,reviewerId:e.reviewerId,states:e.states,pageSize:o,repo:e.repo},t,o),failureScope:d=>({providerId:"azure",projectId:d.project,repositoryId:ue(e.repo)}),completeness:d=>d.body.value.length===o?"unknown":"complete",concurrency:cr}),u=i.map(({scope:d,result:c})=>({namespace:d.namespace,pullRequests:c.body.value})),p=await this.fetchRemoteInfoByRepoId(e.includeRemoteInfo,u,t),l=u.flatMap(({namespace:d,pullRequests:c})=>c.map(m=>ve(d,m,p)));return{data:k(l,e.states),metadata:a}}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:s,project:o,name:i},pullRequestId:a}=e,u=await this.config.request({url:`${D(this.config,t)}/${encodeURIComponent(s)}/${encodeURIComponent(o||"")}/_apis/git/repositories/${i}/pullrequests/${a}?includeCommits=true?api-version=6.0`,headers:{...S(this.config,t)}});if(!u.body.mergeStatus)throw new Error("Could not fetch pull request");return{data:u.body.mergeStatus}}async updatePullRequest(e,t,s){return await this.config.request({method:"PATCH",url:`${D(this.config,s)}/${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:{...S(this.config,s),"Content-Type":"application/json"}})}async closePullRequest(e,t={}){let{pullRequest:s}=e,o={status:"abandoned"};if(!(await this.updatePullRequest(s,JSON.stringify(o),t)).body.status)throw new Error("Could not close pull request")}async mergePullRequest(e,t={}){let{pullRequest:s,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:s.headRef?.oid},status:"completed"};if(!(await this.updatePullRequest(s,JSON.stringify(a),t)).body.status)throw new Error("Could not merge pull request")}async addPullRequestLabel(e,t={}){let{pullRequest:s,label:o}=e;if(!s.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:`${D(this.config,t)}/${encodeURIComponent(s.repository.owner.login)}/${encodeURIComponent(s.repository.project)}/_apis/git/repositories/${s.repository.name}/pullrequests/${s.id}/labels?api-version=6.0`,body:JSON.stringify(i),headers:{...S(this.config,t),"Content-Type":"application/json"}})).body.id)throw new Error("Could not add pull request label")}async removePullRequestLabel(e,t={}){let{pullRequest:s,label:o}=e;if(!s.repository.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');await this.config.request({method:"DELETE",url:`${D(this.config,t)}/${encodeURIComponent(s.repository.owner.login)}/${encodeURIComponent(s.repository.project)}/_apis/git/repositories/${s.repository.name}/pullrequests/${s.id}/labels/${encodeURIComponent(o.name)}?api-version=6.0`,headers:{...S(this.config,t)}})}async setPullRequestLabels(e,t={}){let{pullRequest:s,labels:o}=e;if(!s.repository.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let i=s.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:s,label:a},t);for(let a of i)o.find(u=>a.id===u.id)||await this.removePullRequestLabel({pullRequest:s,label:a},t)}async setPullRequestAsDraft(e,t={}){let{pullRequest:s,isDraft:o}=e,i={isDraft:o};if(!(await this.updatePullRequest(s,JSON.stringify(i),t)).body.status)throw new Error("Could not set the pull request as draft")}async addPullRequestReviewer(e,t={}){let{pullRequest:s,reviewer:o,isRequired:i}=e,a={id:o.id,isRequired:i};if(!(await this.config.request({method:"PUT",url:`${D(this.config,t)}/${encodeURIComponent(s.repository.owner.login)}/${encodeURIComponent(s.repository.project)}/_apis/git/repositories/${s.repository.name}/pullrequests/${s.id}/reviewers/${o.id}?api-version=6.0`,body:JSON.stringify(a),headers:{...S(this.config,t),"Content-Type":"application/json"}})).body.id)throw new Error("Could not add pull request reviewer")}async removePullRequestReviewer(e,t={}){let{pullRequest:s,reviewer:o}=e;await this.config.request({method:"DELETE",url:`${D(this.config,t)}/${encodeURIComponent(s.repository.owner.login)}/${encodeURIComponent(s.repository.project)}/_apis/git/repositories/${s.repository.name}/pullrequests/${s.id}/reviewers/${o.id}?api-version=6.0`,headers:{...S(this.config,t),Accept:"application/json"}})}async setPullRequestReviewers(e,t={}){let{pullRequest:s,reviewers:o}=e;for(let i of o)s.assignees.find(a=>a.id===i.id)||await this.addPullRequestReviewer({pullRequest:s,reviewer:i,isRequired:!0},t);for(let i of s.assignees)o.find(a=>i.id===a.id)||await this.removePullRequestReviewer({pullRequest:s,reviewer:i},t)}async getIssuesForAzureProject(e,t={}){let{page:s,assigneeLogins:o,authorLogin:i,mentionLogin:a,labelNames:u,statusByWorkItemIdByStatusId:p}=e||{},l=s||1,d=Math.min($(e.pageSize,{fallback:Hs}),Ws),c=["[System.TeamProject] = @project",...Js(e.states)];i&&c.push(`[System.CreatedBy] = '${i.replace("'","''")}'`),o&&o[0]&&c.push(`[System.AssignedTo] = '${o[0].replace("'","''")}'`),a&&c.push("[System.Id] IN (@recentMentions)"),u&&u.forEach(U=>c.push(`[System.Tags] Contains '${U}'`));let m=`Select [Microsoft.VSTS.Common.ClosedDate], [Microsoft.VSTS.Common.ResolvedDate] From WorkItems Where ${c.join(" AND ")} order by [System.CreatedDate] desc`,g=await this.config.request({url:`${D(this.config,t)}/${encodeURIComponent(e.namespace)}/${encodeURIComponent(e.project)}/_apis/wit/wiql?api-version=6.0`,body:JSON.stringify({query:m}),method:"POST",headers:{...S(this.config,t),"Content-Type":"application/json"}}),h=g.body.workItems.slice((l-1)*d,d*l).map(U=>U.id),y=g.body.workItems.length,f=Math.ceil(y/d),P=y>d*l;if(h.length===0)return{pageInfo:{hasNextPage:!1,nextPage:null,currentPage:l,totalCount:y,totalPages:f},data:[]};let q=await this.config.request({url:`${D(this.config,t)}/${encodeURIComponent(e.namespace)}/${encodeURIComponent(e.project)}/_apis/wit/workitemsbatch?api-version=6.0`,body:JSON.stringify({ids:h,$expand:"Links"}),method:"POST",headers:{...S(this.config,t),"Content-Type":"application/json"}});return{pageInfo:{hasNextPage:P,nextPage:P?l+1:null,currentPage:l,totalCount:y,totalPages:f},data:q.body.value.map(U=>Ys(e.namespace,e.project,U,p||{}))}}async getPermissionsForRepos(e,t={}){let{namespace:s,repos:o}=e,i={4:["canPush","canCreateWebhook"],1024:["isAdmin"],2048:["isAdmin"],4096:["isAdmin"],8192:["isAdmin"]},a=d=>{let c="2e9eb7ed-3c0a-47d4-87c1-0ffdd275fd87",m=`repoV2/${d.projectId}/${d.id}`;return Object.keys(i).map(g=>({securityNamespaceId:c,token:m,permissions:g}))},u={alwaysAllowAdministrators:!1,evaluations:o.flatMap(a)};return{data:(await this.config.request({method:"POST",url:`${D(this.config,t)}/${encodeURIComponent(s)}/_apis/security/permissionevaluationbatch?api-version=7.0`,body:JSON.stringify(u),headers:{...S(this.config,t),"Content-Type":"application/json"}})).body.evaluations.reduce((d,c)=>{let[,m,g]=c.token.split("/"),h=`${m}/${g}`,y=i[c.permissions];for(let f of y)d[h]===void 0&&(d[h]={canCreateWebhook:!0,canPush:!0,isAdmin:!0}),c.value===!1&&(d[h][f]=!1);return d},{})}}async decorateReposWithPermissions(e,t={}){let{namespace:s,repos:o}=e,i=await this.getPermissionsForRepos({namespace:s,repos:o},t);return{data:o.map(a=>({...a,permissions:i.data[`${a.projectId}/${a.id}`]}))}}async updateIssue(e,t,s={}){return await this.config.request({method:"PATCH",url:`${D(this.config,s)}/${encodeURIComponent(e.project.namespace)}/${encodeURIComponent(e.project.name)}/_apis/wit/workitems/${e.id}?api-version=6.0`,body:JSON.stringify(t),headers:{...S(this.config,s),"Content-Type":"application/json-patch+json"}})}async setIssueStatus(e,t={}){let{issue:s,status:o}=e,i=[{op:"add",path:"/fields/System.State",value:o.name}];if(!(await this.updateIssue(s,i,t)).body.fields?.["System.State"])throw new Error("Could not set issue status")}async setIssueAssignee(e,t={}){let{issue:s,assignee:o}=e,i=[{op:"add",path:"/fields/System.AssignedTo",value:o?.name??""}];if(!(await this.updateIssue(s,i,t)).body.fields?.["System.State"])throw new Error("Could not set issue assignee")}async setIssueLabels(e,t={}){let{issue:s,labels:o}=e,a=[{op:"replace",path:"/fields/System.Tags",value:o.map(p=>p.name).join(";")}];if(!(await this.updateIssue(s,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:s,project:o}=e;return{data:(await this.config.request({url:`${D(this.config,t)}/${encodeURIComponent(s)}/${encodeURIComponent(o||"")}/_apis/wit/workitemtypes?api-version=6.0`,headers:{...S(this.config,t)}})).body.value}}async getLabelsForProject(e,t={}){let{namespace:s,project:o}=e;return{data:(await this.config.request({url:`${D(this.config,t)}/${encodeURIComponent(s)}/${encodeURIComponent(o||"")}/_apis/wit/tags?api-version=6.0`,headers:{...S(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:s,number:o}=e;if(!s.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let i=await this.config.request({url:`${this.getRepoApiUrl(s.namespace,s.project,s.name,t)}/pullrequests/${o}?api-version=7.1`,headers:S(this.config,t)}),a=await this.fetchRemoteInfoByRepoId(e.includeRemoteInfo,[{namespace:s.namespace,pullRequests:[i.body]}],t);return{data:ve(s.namespace,i.body,a)}}async getPullRequestDescription(e,t={}){let{repo:s,number:o}=e;if(!s.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(s.namespace,s.project,s.name,t)}/pullrequests/${o}?api-version=7.1`,headers:S(this.config,t)})).body?.description??""}}}catch{return{data:{description:null}}}}async setPullRequestDescription(e,t={}){let{repo:s,number:o,description:i}=e;if(!s.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(s.namespace,s.project,s.name,t)}/pullrequests/${o}?api-version=7.1`,headers:{...S(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 s=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:S(this.config,t)});if(!s.body.value?.length)throw new Error("No merge base found between the specified commits.");return{data:s.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 s=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:{...S(this.config,t),Accept:"application/octet-stream"}});return{data:new Blob([s.body])}}async getPullRequestDiff(e,t={}){if(!e.repo.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let s=this.getRepoApiUrl(e.repo.namespace,e.repo.project,e.repo.name,t),o=S(this.config,t),i={...o,Accept:"application/octet-stream"},[a,u]=await Promise.all([this.config.request({url:`${s}/pullrequests/${e.pullRequestId}?api-version=7.1`,headers:o}),this.config.request({url:`${s}/pullrequests/${e.pullRequestId}/iterations?api-version=7.1`,headers:o})]),p=a.body.lastMergeTargetCommit.commitId,l=a.body.lastMergeSourceCommit.commitId,d=u.body.value;if(d.length===0)return"";let c=d[d.length-1],m=1e3,g=[],h=0;for(;;){let E=(await this.config.request({url:`${s}/pullrequests/${e.pullRequestId}/iterations/${c.id}/changes?api-version=7.1&$top=${m}&$skip=${h}`,headers:o})).body.changeEntries??[];if(E.length===0||(g.push(...E),E.length<m))break;h+=E.length}if(g.length===0)return"";let y=5,f=[],P=new TextDecoder,q=w=>w instanceof ArrayBuffer?P.decode(w):typeof w=="string"?w:"",U=async(w,E)=>{try{let oe=await this.config.request({url:`${s}/items?path=${encodeURIComponent(w)}&versionDescriptor[version]=${encodeURIComponent(E)}&versionDescriptor[versionType]=commit&includeContent=true&api-version=7.1`,headers:i});return q(oe.body)}catch{return""}},L=w=>{if(typeof w=="number")return{add:(w&1)!==0,rename:(w&8)!==0,delete:(w&16)!==0};let E=w.toLowerCase().split(",").map(oe=>oe.trim());return{add:E.includes("add"),rename:E.includes("rename"),delete:E.includes("delete")}};for(let w=0;w<g.length;w+=y){let E=g.slice(w,w+y),oe=await Promise.all(E.map(async ce=>{let{add:me,rename:mt,delete:ie}=L(ce.changeType),qe=ce.originalPath??ce.item.originalPath,T=ce.item.path,Ge=ie?T??qe??"":T??"",sr=mt||ie?qe??Ge:Ge,[qs,vs]=await Promise.all([me?Promise.resolve(""):U(sr,p),ie?Promise.resolve(""):U(Ge,l)]),Es=me?"/dev/null":`a${sr}`,Cs=ie?"/dev/null":`b${Ge}`;return(0,Rr.createTwoFilesPatch)(Es,Cs,qs,vs)}));f.push(...oe)}return f.join(`
|
|
2
|
+
`)}getPullRequestWriteHeaders(e){return{...S(this.config,e),"Content-Type":"application/json"}}setReviewerVote(e,t,s,o,i){return this.config.request({method:"PUT",url:`${e}/pullRequests/${t}/reviewers/${encodeURIComponent(s)}?api-version=7.1`,headers:this.getPullRequestWriteHeaders(i),body:JSON.stringify({vote:o})})}postPullRequestThread(e,t,s,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:s,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 s=this.getRepoApiUrl(e.repo.namespace,e.repo.project,e.repo.name,t),o=S(this.config,t),i=await this.config.request({url:`${s}/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 p of u.comments)p.commentType==="system"||p.isDeleted||a.push({id:wt(e.repo.namespace,e.repo.project,e.repo.name,e.pullRequestNumber,u.id,p.id),author:p.author?pe(p.author):null,body:p.content||"",createdAt:p.publishedDate?new Date(p.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 s=this.getRepoApiUrl(e.pullRequest.repository.owner.login,e.pullRequest.repository.project,e.pullRequest.repository.name,t);await this.postPullRequestThread(s,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 s=this.getRepoApiUrl(e.pullRequest.repository.owner.login,e.pullRequest.repository.project,e.pullRequest.repository.name,t),o=this.getPullRequestWriteHeaders(t);if(e.threadId){let l=St(e.threadId),d=e.pullRequest.repository.owner.login,c=e.pullRequest.repository.project,m=e.pullRequest.repository.name,g=String(e.pullRequest.id);if(l.namespace!==d||l.project!==c||l.repoName!==m||l.prId!==g)throw new Error(`Azure thread ID context mismatch: threadId targets ${l.namespace}/${l.project}/${l.repoName} pull request ${l.prId}, but input.pullRequest targets ${d}/${c}/${m} pull request ${g}.`);let y=(await this.config.request({url:`${s}/pullRequests/${e.pullRequest.id}/threads/${l.threadId}?api-version=7.1`,headers:S(this.config,t)})).body.comments?.find(P=>P.parentCommentId===0);if(!y)throw new Error(`Could not determine root comment for Azure DevOps thread ${l.threadId}.`);let f=await this.config.request({method:"POST",url:`${s}/pullRequests/${e.pullRequest.id}/threads/${l.threadId}/comments?api-version=7.1`,headers:o,body:JSON.stringify({content:e.comment,parentCommentId:y.id,commentType:1})});return wt(d,c,m,Number(g),Number(l.threadId),f.body.id)}let i=e.path.startsWith("/")?e.path:`/${e.path}`,a={line:e.line,offset:1},u={filePath:i};e.side==="LEFT"?(u.leftFileStart=a,u.leftFileEnd=a):(u.rightFileStart=a,u.rightFileEnd=a);let p=await this.config.request({method:"POST",url:`${s}/pullRequests/${e.pullRequest.id}/threads?api-version=7.1`,headers:o,body:JSON.stringify({comments:[{parentCommentId:0,content:e.comment,commentType:1}],status:1,threadContext:u})});return hr(e.pullRequest.repository.owner.login,e.pullRequest.repository.project,e.pullRequest.repository.name,Number(e.pullRequest.id),p.body.id)}async editComment(e,t={}){let s=gr(e.commentId),o=this.getRepoApiUrl(s.namespace,s.project,s.repoName,t);await this.config.request({method:"PATCH",url:`${o}/pullRequests/${s.prId}/threads/${s.threadId}/comments/${s.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 s=gr(e.commentId),o=this.getRepoApiUrl(s.namespace,s.project,s.repoName,t);await this.config.request({method:"DELETE",url:`${o}/pullRequests/${s.prId}/threads/${s.threadId}/comments/${s.commentId}?api-version=7.1`,headers:S(this.config,t)})}async deleteInlineComment(e,t={}){return this.deleteComment(e,t)}async resolveReviewThread(e,t={}){let s=St(e.threadId),o=this.getRepoApiUrl(s.namespace,s.project,s.repoName,t);await this.config.request({method:"PATCH",url:`${o}/pullRequests/${s.prId}/threads/${s.threadId}?api-version=7.1`,headers:this.getPullRequestWriteHeaders(t),body:JSON.stringify({status:2})})}async unresolveReviewThread(e,t={}){let s=St(e.threadId),o=this.getRepoApiUrl(s.namespace,s.project,s.repoName,t);await this.config.request({method:"PATCH",url:`${o}/pullRequests/${s.prId}/threads/${s.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 s=e.pullRequest.repository.owner.login,o=this.getRepoApiUrl(s,e.pullRequest.repository.project,e.pullRequest.repository.name,t),i=await this.getCurrentUserId(s,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 s=e.pullRequest.repository.owner.login,o=this.getRepoApiUrl(s,e.pullRequest.repository.project,e.pullRequest.repository.name,t),i=await this.getCurrentUserId(s,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 s=this.getRepoApiUrl(e.pullRequest.repository.owner.login,e.pullRequest.repository.project,e.pullRequest.repository.name,t);await this.postPullRequestThread(s,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:s,project:o,name:i}=e.repo,{pullRequestId:a}=e,u=this.getRepoApiUrl(s,o,i,t),p=S(this.config,t),[l,d]=await Promise.all([this.config.request({url:`${u}/pullRequests/${a}/reviewers?api-version=7.1`,headers:p}),this.config.request({url:`${u}/pullRequests/${a}/threads?api-version=7.1`,headers:p})]),c=(f,P)=>wt(s,o,i,a,f,P),m=f=>hr(s,o,i,a,f),g=new Map;for(let f of d.body.value){if(f.isDeleted)continue;let P=f.comments.filter(T=>!T.isDeleted&&T.commentType!=="system"),q=P.find(T=>T.parentCommentId===0)??P[0];if(!q)continue;let U=q.author?.id;if(!U)continue;let L=P.filter(T=>T.id!==q.id),w=f.threadContext,E=w?.rightFileStart?{side:"RIGHT",start:w.rightFileStart,end:w.rightFileEnd}:w?.leftFileStart?{side:"LEFT",start:w.leftFileStart,end:w.leftFileEnd}:null,oe=E?.end?.line??E?.start.line??null,ce=E?.start&&E.end&&E.start.line!==E.end.line?E.start.line:null,me=w?.filePath??"",mt=me.startsWith("/")?me.slice(1):me,ie={id:c(f.id,q.id),author:q.author?pe(q.author):null,body:q.content??"",createdAt:q.publishedDate?new Date(q.publishedDate):null,url:"",diffLines:[],filename:mt,replies:L.map(T=>({id:c(f.id,T.id),author:T.author?pe(T.author):null,body:T.content??"",createdAt:T.publishedDate?new Date(T.publishedDate):null,url:""})),isOutdated:!1,isResolved:Ks.has(Vs(f.status)),line:oe,startLine:ce,side:E?.side??null,threadId:m(f.id)},qe=g.get(U);qe?qe.push(ie):g.set(U,[ie])}let h=[],y=new Set;for(let f of l.body.value){if(f.hasDeclined)continue;let P=f.vote??0,q=g.get(f.id);P===0&&!q?.length||(h.push({id:f.id,author:pe(f),body:"",createdAt:null,url:"",reviewComments:q??[]}),y.add(f.id))}for(let[f,P]of g){if(y.has(f)||!P.length)continue;let q=P[0].author;q&&h.push({id:f,author:q,body:"",createdAt:null,url:"",reviewComments:P})}return{data:h}}};var G=(r,n={})=>R(n.token||r.token,n.isPAT||r.isPAT);var O="https://api.bitbucket.org/2.0",en={OPEN:"OPEN",MERGED:"MERGED",DECLINED:"CLOSED",SUPERSEDED:"CLOSED"},tn={OPEN:["OPEN"],MERGED:["MERGED"],CLOSED:["DECLINED","SUPERSEDED"]},ke=50,rn=5,Ir=r=>{let n=!r||r.length===0?["OPEN"]:Array.from(new Set(r.flatMap(t=>tn[t]))),e=n.map(t=>`state="${t}"`).join(" OR ");return n.length>1?`(${e})`:e},sn=r=>r.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),br=r=>{let n=r?.trim();if(!n)return null;let e=sn(n);return`(title ~ "${e}" OR description ~ "${e}")`},yr=r=>{let n=!!r.next,e=typeof r.size=="number"?r.size:null,t=typeof r.pagelen=="number"&&r.pagelen>0?r.pagelen:null;return{hasNextPage:n,nextPage:n?r.page+1:null,currentPage:typeof r.page=="number"?r.page:null,totalCount:e,totalPages:e!==null&&t?Math.ceil(e/t):null}},Ne={owner:4,admin:3,contributor:2,member:1},Fe=r=>({id:r.uuid,name:r.display_name||r.nickname,username:r.nickname||r.display_name,email:null,avatarUrl:r.links.avatar.href,url:r.links.html.href}),Pr=r=>{let n=r.links.clone,e=n?.find(s=>s.name==="ssh"),t=n?.find(s=>s.name==="https");return e&&t?{cloneUrlHTTPS:t.href,cloneUrlSSH:e.href}:null},qt=r=>({id:r.uuid,namespace:r.workspace.slug,name:r.slug,webUrl:r.links.html.href,httpsUrl:r.links.clone.find(n=>n.name==="https")?.href??null,sshUrl:r.links.clone.find(n=>n.name==="ssh")?.href??null,defaultBranch:{name:r.mainbranch.name},permissions:null}),vt=r=>{let n=r.id,e=r.participants?.map(t=>{let s="REVIEW_REQUESTED";return t.approved?s="APPROVED":t.state==="changes_requested"?s="CHANGES_REQUESTED":t.participated_on!==null&&(s="COMMENTED"),{reviewer:Fe(t.user),state:s}})??[];return{id:n.toString(),title:r.title,description:r.description,number:n,state:en[r.state],isDraft:!1,commentCount:r.comment_count,upvoteCount:null,author:Fe(r.author),createdDate:new Date(r.created_on),updatedDate:new Date(r.updated_on),closedDate:null,mergedDate:null,repository:{id:r.destination.repository.uuid,name:r.destination.repository.name,owner:{login:r.destination.repository.full_name.split("/")[0]},remoteInfo:Pr(r.destination.repository)},headCommit:{buildStatuses:null},baseRef:{name:r.destination.branch.name,oid:r.destination.commit.hash},headRef:{name:r.source.branch.name,oid:r.source.commit.hash},url:r.links.html.href,assignees:null,reviews:e,reviewDecision:B(e),additions:null,deletions:null,fileCount:null,commitCount:null,isCrossRepository:r.source.repository.uuid!==r.destination.repository.uuid,headRepository:{id:r.source.repository.uuid,name:r.source.repository.name,owner:{login:r.source.repository.full_name.split("/")[0]},remoteInfo:Pr(r.source.repository)},mergeableState:"MERGEABLE",permissions:null}},nn=r=>{switch(r){case"owner":case"admin":return{canCreateWebhook:!0,canPush:!0,isAdmin:!0};case"write":return{canCreateWebhook:!1,canPush:!0,isAdmin:!1};case"read":case"none":return{canCreateWebhook:!1,canPush:!1,isAdmin:!1}}},on=r=>{switch(r){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}}},Re=class extends j{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:`${O}/user`,headers:G(this.config,e)});return{data:Fe(t.body)}}async getUserForCommit(n,e={}){let s=(await this.config.request({url:`${O}/repositories/${n.repo.namespace}/${n.repo.name}/commit/${n.oid}`,headers:G(this.config,e)})).body.author,o=s.raw.match(/([^<]+)<(.+)>/);return{data:{name:o?o[1].trim():null,email:o?o[2]:null,avatarUrl:s.user?.links.avatar.href||null}}}async getRepo(n,e={}){let t=await this.config.request({url:`${O}/repositories/${n.namespace}/${n.name}`,headers:G(this.config,e)});return{data:qt(t.body)}}async getRepos(n,e={}){let t=[],s=[];return await Promise.all(n.map(async o=>{try{let i=await this.getRepo(o,e);t.push(i.data)}catch(i){s.push({input:o,error:i})}})),{data:t,errors:s}}async getReposForWorkspace(n,e={}){let t=new URL(`${O}/repositories/${encodeURIComponent(n.workspace)}`);t.searchParams.set("page",n.page?.toString()||"1"),t.searchParams.set("pagelen",C.toString()),n.minimumRole&&t.searchParams.set("role",n.minimumRole);let s=await this.config.request({url:t.toString(),headers:G(this.config,e)}),o=!!s.body.next;return{pageInfo:{hasNextPage:o,nextPage:o?s.body.page+1:null},data:s.body.values.map(qt)}}async getAllReposForWorkspace(n,e={}){let t=[],s=1;for(;s!==null;){let o=await this.getReposForWorkspace({workspace:n.workspace,minimumRole:n.minimumRole,page:s},e);t.push(...o.data),s=o.pageInfo.hasNextPage?o.pageInfo.nextPage:null}return t}async getAllReposForWorkspaceWithPermissions(n,e={}){let t=new Map,s=[],o=Ne[n.minimumRole||"member"];o<=Ne.admin&&s.push("admin"),o<=Ne.contributor&&s.push("contributor"),o<=Ne.member&&s.push("member");let i=[];for(let a of s){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:on(u)}})}}async getReposForCurrentUser(n,e={}){let t=new URL(`${O}/repositories`);t.searchParams.set("role","member"),t.searchParams.set("pagelen",C.toString()),n.cursor&&t.searchParams.set("after",n.cursor);let s=await this.config.request({url:t.toString(),headers:G(this.config,e)}),o=!!s.body.next,i=null;return s.body.next&&(i=new URL(s.body.next).searchParams.get("after")),{pageInfo:{hasNextPage:o,endCursor:i},data:s.body.values.map(qt)}}async getBranches(n,e={}){let t=new URL(`${O}/repositories/${n.repo.namespace}/${n.repo.name}/refs/branches`);t.searchParams.set("page",n.page?.toString()||"1"),t.searchParams.set("pagelen",C.toString());let s=await this.config.request({url:t.toString(),headers:G(this.config,e)}),o=!!s.body.next;return{pageInfo:{hasNextPage:o,nextPage:o?s.body.page+1:null},data:s.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(`${O}/repositories/${n.repo.namespace}/${n.repo.name}/refs/tags`);t.searchParams.set("pagelen",C.toString()),n.cursor&&t.searchParams.set("page",n.cursor);let s=await this.config.request({url:t.toString(),headers:G(this.config,e)}),o=!!s.body.next,i=null;return s.body.next&&(i=new URL(s.body.next).searchParams.get("page")),{pageInfo:{hasNextPage:o,endCursor:i},data:s.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(`${O}/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 s=await this.config.request({url:t.toString(),headers:G(this.config,e)}),o=!!s.body.next;return{pageInfo:{hasNextPage:o,nextPage:o?s.body.page+1:null},data:s.body.values.map(i=>({id:i.workspace.uuid,slug:i.workspace.slug}))}}async getWorkspacesForUser(n,e={}){let t=new URL(`${O}/user/permissions/workspaces`);t.searchParams.set("page",n.page?.toString()||"1"),t.searchParams.set("pagelen","50");let s=await this.config.request({url:t.toString(),headers:G(this.config,e)}),o=!!s.body.next;return{pageInfo:{hasNextPage:o,nextPage:o?s.body.page+1:null},data:s.body.values.map(i=>({id:i.workspace.uuid,slug:i.workspace.slug,name:i.workspace.name}))}}async getPullRequestsForUserAndWorkspace(n,e={}){let t=new URL(`${O}/workspaces/${n.workspaceSlug}/pullrequests/${n.userId}`);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",$(n.pageSize,{fallback:ke,max:ke}).toString());let s=[Ir(n.states)];n.repos&&n.repos.length>0&&s.push(`(${n.repos.map(a=>`source.repository.full_name = "${a.namespace}/${a.name}"`).join(" OR ")})`);let o=br(n.query);o&&s.push(o),t.searchParams.set("q",s.join(" AND "));let i=await this.config.request({url:t.toString(),headers:G(this.config,e)});return{pageInfo:yr(i.body),data:i.body.values.map(vt)}}async getPullRequestsForReviewerAndWorkspace(n,e={}){let t=n.repos?.length?n.repos:await this.getAllReposForWorkspace({workspace:n.workspaceSlug},e);return this.getPullRequestsForRepos({repos:t,reviewerId:n.reviewerId,states:n.states,query:n.query,pageSize:n.pageSize},e)}async getPullRequestsForRepoBase(n,e={}){let t=new URL(`${O}/repositories/${encodeURI(n.repo.namespace)}/${encodeURI(n.repo.name)}/pullrequests`),s=[];n.reviewerId&&s.push(`reviewers.uuid="${n.reviewerId}"`),n.authorLogin&&s.push(`author.uuid="${n.authorLogin}"`);let o=Ir(n.states);s.length&&(o+=` AND (${s.join(n.useOrFilter?" OR ":" AND ")})`);let i=br(n.query);return i&&(o+=` AND ${i}`),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",$(n.pageSize,{fallback:ke,max:ke}).toString()),t.searchParams.set("q",o),await this.config.request({url:t.toString(),headers:G(this.config,e)})}async getPullRequestsForRepo(n,e={}){let t=[],s=await this.getPullRequestsForRepoBase(n,e);return s.body.values.forEach(o=>{t.push(vt(o))}),{pageInfo:yr(s.body),data:t}}async getPullRequestsForRepos(n,e={}){let{successes:t,metadata:s}=await V(n.repos,{run:i=>this.getPullRequestsForRepoBase({repo:i,authorLogin:n.authorLogin,reviewerId:n.reviewerId,useOrFilter:n.useOrFilter,states:n.states,query:n.query,pageSize:n.pageSize},e),failureScope:i=>({providerId:"bitbucket",repositoryId:ue(i)}),completeness:i=>i.body.next?"partial":"complete",concurrency:rn}),o=[];return t.forEach(({result:i})=>{i.body.values.forEach(a=>{o.push(vt(a))})}),{data:o,metadata:s}}async getAccountsForWorkspace(n,e={}){let t=new URL(`${O}/workspaces/${encodeURI(n.workspace)}/members`);t.searchParams.set("page",n.page?.toString()||"1"),t.searchParams.set("pagelen","100");let s=await this.config.request({url:t.toString(),headers:G(this.config,e)}),o=!!s.body.next;return{pageInfo:{hasNextPage:o,nextPage:o?s.body.page+1:null},data:s.body.values.map(i=>Fe(i.user))}}async getReposPermissionsForCurrentUser(n,e={}){let t=new URL(`${O}/user/permissions/repositories`);t.searchParams.set("page",n.page?.toString()||"1"),t.searchParams.set("pagelen","100");let s=await this.config.request({url:t.toString(),headers:G(this.config,e)}),o=!!s.body.next;return{pageInfo:{hasNextPage:o,nextPage:o?s.body.page+1:null},data:s.body.values.reduce((i,a)=>({...i,[a.repository.uuid]:nn(a.permission)}),{})}}async decorateReposWithPermissions(n,e={}){let t={},s=1;do{let o=await this.getReposPermissionsForCurrentUser({page:s},e);t={...o.data,...t},s=o.pageInfo.hasNextPage?o.pageInfo.nextPage:null}while(s!==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:`${O}/repositories/${t.repository.owner.login}/${t.repository.name}/pullrequests/${t.id}/decline`,headers:G(this.config,e)})).body.title)throw new Error("Could not close pull request")}async mergePullRequest(n,e={}){let{pullRequest:t,mergeStrategy:s}=n,o;switch(s){case"MERGE_COMMIT":{o="merge_commit";break}case"FAST_FORWARD":{o="fast_forward";break}case"SQUASH":{o="squash";break}}let i={merge_strategy:o,type:"pullrequest"};if(!(await this.config.request({method:"POST",url:`${O}/repositories/${t.repository.owner.login}/${t.repository.name}/pullrequests/${t.id}/merge`,body:JSON.stringify(i),headers:{...G(this.config,e),"Content-Type":"application/json"}})).body.title)throw new Error("Could not merge pull request")}async setPullRequestReviewers(n,e={}){let{pullRequest:t,reviewers:s}=n,o={reviewers:s.map(a=>{if(a.username)throw new Error('Bitbucket reviewer requires "username" for this function.');return{username:a.username}})};if(!(await this.config.request({method:"PUT",url:`${O}/repositories/${t.repository.owner.login}/${t.repository.name}/pullrequests/${t.id}`,body:JSON.stringify(o),headers:{...G(this.config,e),"Content-Type":"application/json"}})).body.title)throw new Error("Could not set pull request reviewers")}};var wr=r=>r?r.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}:r.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 Ee=r=>{let n=r.links.self[0].href;return{name:r.displayName,email:r.emailAddress,avatarUrl:r.avatarUrl??(n&&`${n}/avatar.png`),id:r.id.toString(),username:r.name,url:n}},je=r=>{let n={OPEN:"OPEN",MERGED:"MERGED",DECLINED:"CLOSED"},e={UNAPPROVED:"REVIEW_REQUESTED",NEEDS_WORK:"CHANGES_REQUESTED",APPROVED:"APPROVED"},t=r.reviewers.map(u=>({reviewer:Ee(u.user),state:e[u.status]})),s=r.toRef.repository.links.clone.find(u=>u.name==="ssh")?.href??null,o=r.toRef.repository.links.clone.find(u=>u.name==="https")?.href??null;o||(o=r.toRef.repository.links.clone.find(u=>u.name==="http")?.href??null);let i=r.fromRef.repository.links.clone.find(u=>u.name==="ssh")?.href??null,a=r.fromRef.repository.links.clone.find(u=>u.name==="https")?.href??null;return a||(a=r.fromRef.repository.links.clone.find(u=>u.name==="http")?.href??null),{id:r.id.toString(),number:r.id,title:r.title,description:r.description,url:r.links.self[0].href,state:n[r.state],isDraft:!1,createdDate:new Date(r.createdDate),updatedDate:new Date(r.updatedDate),closedDate:r.closedDate?new Date(r.closedDate):null,mergedDate:r.state=="MERGED"&&r.closedDate?new Date(r.closedDate):null,baseRef:{name:r.toRef.displayId,oid:r.toRef.latestCommit},headRef:{name:r.fromRef.displayId,oid:r.fromRef.latestCommit},commentCount:r.properties.commentCount,upvoteCount:null,commitCount:null,fileCount:null,additions:null,deletions:null,author:Ee(r.author.user),assignees:null,reviews:t,reviewDecision:B(t),isCrossRepository:r.fromRef.repository.id!==r.toRef.repository.id,repository:{id:r.toRef.repository.id.toString(),name:r.toRef.repository.name,owner:{login:r.toRef.repository.project.key},remoteInfo:o&&s?{cloneUrlHTTPS:o,cloneUrlSSH:s}:null},headRepository:{id:r.fromRef.repository.id.toString(),name:r.fromRef.repository.name,owner:{login:r.fromRef.repository.project.key},remoteInfo:a&&i?{cloneUrlHTTPS:a,cloneUrlSSH:i}:null},headCommit:null,mergeableState:"MERGEABLE",permissions:null,version:r.version}},Sr=r=>({id:r.id.toString(),namespace:r.project.key,name:r.slug,webUrl:r.links.self[0]?.href??null,httpsUrl:r.links.clone.find(n=>n.name==="https"||n.name==="http")?.href??null,sshUrl:r.links.clone.find(n=>n.name==="ssh")?.href??null,defaultBranch:null,permissions:null}),qr=50,an=5,un={OPEN:"OPEN",MERGED:"MERGED",CLOSED:"DECLINED"},vr=r=>{if(!r||r.length===0)return"OPEN";let n=Array.from(new Set(r.map(e=>un[e])));return n.length===1?n[0]:"ALL"},Er=(r,n)=>typeof r!="number"||n<=0?null:Math.floor(r/n)+1,Cr=(r,n)=>{if(typeof r!="number"||!Number.isFinite(r))return 0;let e=Math.floor(r);return e<=1?0:(e-1)*n},$r=r=>{let n=Er(r.start,r.limit);return{hasNextPage:!r.isLastPage,nextPage:r.isLastPage?null:Er(r.nextPageStart,r.limit),currentPage:n}},Ie=class extends N{getBaseUrl(n){let e=n.baseUrl||this.config.baseUrl;if(!e)throw new Error('Bitbucket Server requires "baseUrl"');return e}getRequestHeaders(n){return R(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":s,"x-ausername":o}}=t,i=s?parseInt(s,10):null,a=decodeURIComponent(o),p=(await this.config.request({url:`${this.getBaseUrl(e)}/users?filter=${o}&avatarSize=64`,headers:this.getRequestHeaders(e)})).body.values.find(({emailAddress:l,id:d,name:c,slug:m})=>i?i===d:a===c||a===l||a===m);if(!p)throw new Error("Could not find current Bitbucket Server user");return{data:Ee(p)}}async getUserForCommit(n,e){let{repo:t,oid:s}=n,o=await this.config.request({url:`${this.getBaseUrl(e)}/projects/${t.namespace}/repos/${t.name}/commits/${s}`,headers:this.getRequestHeaders(e)});if(!o.body.author)throw new Error("Could not find user for commit");return{data:Ee(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:Sr(t.body)}}async getRepos(n,e={}){let t=[],s=[];return await Promise.all(n.map(async o=>{try{let i=await this.getRepo(o,e);t.push(i.data)}catch(i){s.push({input:o,error:i})}})),{data:t,errors:s}}async getReposForCurrentUser(n,e={}){let t=n.page??0,s=await this.config.request({url:`${this.getBaseUrl(e)}/repos?start=${t}`,headers:this.getRequestHeaders(e)});return{pageInfo:{hasNextPage:!s.body.isLastPage,nextPage:s.body.nextPageStart},data:s.body.values.map(Sr)}}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 s=await this.config.request({url:t.toString(),headers:this.getRequestHeaders(e)});return{data:wr(s.body.values)}}catch(s){if(s.response?.status===401)return{data:{canCreateWebhook:!1,canPush:!1,isAdmin:!1}};throw s}}async decorateReposWithPermissions(n,e={}){return await Promise.all(n.repos.map(async s=>{let o=await this.getRepoPermissionsForUsername({repo:s,username:n.username},e);return{...s,permissions:o.data}}))}async getPullRequestsForRepoBase(n,e={}){let t=$(n.pageSize,{fallback:qr}),s=new URL(`${this.getBaseUrl(e)}/projects/${encodeURI(n.repo.namespace)}/repos/${encodeURI(n.repo.name)}/pull-requests`);return s.searchParams.set("state",vr(n.states)),s.searchParams.set("start",Cr(n.page,t).toString()),s.searchParams.set("limit",t.toString()),n.reviewerLogin&&(s.searchParams.set("role.1","REVIEWER"),s.searchParams.set("username.1",n.reviewerLogin)),await this.config.request({url:s.toString(),headers:this.getRequestHeaders(e)})}async getPullRequestsForRepo(n,e={}){let t=[],s=await this.getPullRequestsForRepoBase(n,e);return s.body.values.forEach(o=>{if(n.authorLogin&&o.author.user.name!==n.authorLogin)return null;t.push(je(o))}),{pageInfo:$r(s.body),data:k(t,n.states)}}async getPullRequestsForRepos(n,e={}){let{successes:t,metadata:s}=await V(n.repos,{run:i=>this.getPullRequestsForRepoBase({repo:i,reviewerLogin:n.reviewerLogin,states:n.states,pageSize:n.pageSize},e),failureScope:i=>({providerId:"bitbucketServer",repositoryId:ue(i)}),completeness:i=>i.body.isLastPage?"complete":"partial",concurrency:an}),o=[];return t.forEach(({result:i})=>{i.body.values.forEach(a=>{n.authorLogin&&a.author.user.name!==n.authorLogin||o.push(je(a))})}),{data:k(o,n.states),metadata:s}}async getPullRequestsForCurrentUser(n,e={}){let t=new URL(`${this.getBaseUrl(e)}/dashboard/pull-requests`);t.searchParams.set("state",vr(n.states));let s=$(n.pageSize,{fallback:qr});t.searchParams.set("start",Cr(n.page,s).toString()),t.searchParams.set("limit",s.toString()),n.reviewerLogin&&(t.searchParams.set("role.1","REVIEWER"),t.searchParams.set("username.1",n.reviewerLogin));let o=await this.config.request({url:t.toString(),headers:this.getRequestHeaders(e)});return{pageInfo:$r(o.body),data:k(o.body.values.map(je),n.states)}}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:s}=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:s,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:s}=n;if(t.version===void 0)throw new Error('Bitbucket Server requires "version" for this function.');let o={reviewers:s.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 s=await this.config.request({url:t.toString(),headers:this.getRequestHeaders(e)}),o=s.body.values.length!==0;return{pageInfo:{hasNextPage:o,nextPage:o?s.body.start+s.body.values.length:null},data:s.body.values.map(i=>Ee(i.user))}}};var Hr=require("js-base64");var I=class extends Error{constructor(e,t){let s=t?.map(i=>`'${i.message}'`).join(", "),o=s?`${e}: ${s}`:e;super(o);this.graphQLErrors=t??[]}};var ln={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]},Dr=100,Lr=100,Ce={__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"},x=r=>!!r,M=(r,n)=>{let e=ln[n];for(let t=0;t<3;t++){if(r[t]>e[t])return!0;if(r[t]<e[t])return!1}return!0},Be="https://api.github.com",pn=`${Be}/graphql`,Me=`
|
|
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
|
+
`,dn=`
|
|
11
11
|
... on CheckRun {
|
|
12
12
|
completedAt
|
|
13
13
|
conclusion
|
|
@@ -16,21 +16,21 @@ url
|
|
|
16
16
|
permalink
|
|
17
17
|
startedAt
|
|
18
18
|
}
|
|
19
|
-
`,
|
|
19
|
+
`,Qe=/\/api\/v\d+$/,ze=`
|
|
20
20
|
color
|
|
21
21
|
description
|
|
22
22
|
id
|
|
23
23
|
name
|
|
24
|
-
`,
|
|
24
|
+
`,Ur=r=>{if(r.endsWith("/api/graphql"))throw new Error("The graphql endpoint is being used as the baseUrl. This package uses both GraphQL and REST APIs, and the REST version cannot be assumed. Use the REST endpoint as the baseUrl instead.")},cn=(r,n)=>{let e=n.baseUrl||r.baseUrl;return e?(e=e.replace(/\/$/,""),Ur(e),Qe.test(e)&&(e=e.replace(Qe,"")),`${e}/api/graphql`):pn},z=(r,n)=>{let e=n.baseUrl||r.baseUrl;return e?(e=e.replace(/\/$/,""),Ur(e),Qe.test(e)&&(e=e.replace(Qe,"")),`${e}/api/v3`):Be},b=(r,n,e)=>{let t=R(e.token||r.token);return t["X-Github-Next-Global-ID"]="1",t["Content-Type"]="application/json",t.Accept="application/vnd.github.merge-info-preview+json",r.request({url:cn(r,e),method:"POST",headers:t,body:JSON.stringify(n)})},mn={user:!0,"user:email":!0,"read:user":!0},K=r=>r.some(n=>mn[n]),F=(r=!1,n=!1,e)=>`
|
|
25
25
|
__typename
|
|
26
|
-
${
|
|
27
|
-
${
|
|
28
|
-
${
|
|
29
|
-
${
|
|
30
|
-
${n?
|
|
31
|
-
${
|
|
32
|
-
${
|
|
33
|
-
`,
|
|
26
|
+
${re(e,["graphQLId"],"id")}
|
|
27
|
+
${re(e,["id"],"databaseId")}
|
|
28
|
+
${re(e,["name"],"name")}
|
|
29
|
+
${re(e,["name","username"],"login")}
|
|
30
|
+
${n?re(e,["email"],"email"):""}
|
|
31
|
+
${re(e,["avatarUrl"],`avatarUrl${r?"(size: $avatarSize)":""}`)}
|
|
32
|
+
${re(e,["url"],"url")}
|
|
33
|
+
`,gn=(r=!1)=>`
|
|
34
34
|
latestReviews(first: 100) {
|
|
35
35
|
nodes {
|
|
36
36
|
author {
|
|
@@ -38,28 +38,28 @@ latestReviews(first: 100) {
|
|
|
38
38
|
${F(!1,r)}
|
|
39
39
|
}
|
|
40
40
|
... on EnterpriseUserAccount {
|
|
41
|
-
${
|
|
41
|
+
${Et(!1)}
|
|
42
42
|
}
|
|
43
43
|
}
|
|
44
44
|
state
|
|
45
45
|
}
|
|
46
46
|
}
|
|
47
|
-
`,
|
|
47
|
+
`,Ar=(r=!1)=>`
|
|
48
48
|
__typename
|
|
49
49
|
id
|
|
50
50
|
databaseId
|
|
51
51
|
login
|
|
52
52
|
avatarUrl${r?"(size: $avatarSize)":""}
|
|
53
53
|
url
|
|
54
|
-
`,
|
|
54
|
+
`,Et=(r=!1)=>`
|
|
55
55
|
__typename
|
|
56
56
|
id
|
|
57
57
|
login
|
|
58
58
|
avatarUrl${r?"(size: $avatarSize)":""}
|
|
59
59
|
url
|
|
60
|
-
`,
|
|
60
|
+
`,He=(r,n=!1,e)=>`
|
|
61
61
|
id
|
|
62
|
-
${!e||
|
|
62
|
+
${!e||M(e,"PR_FULL_DATABASE_ID")?"fullDatabaseId":"databaseId"}
|
|
63
63
|
number
|
|
64
64
|
title
|
|
65
65
|
body
|
|
@@ -69,10 +69,10 @@ author {
|
|
|
69
69
|
${F(!1,n)}
|
|
70
70
|
}
|
|
71
71
|
... on Bot {
|
|
72
|
-
${
|
|
72
|
+
${Ar(!1)}
|
|
73
73
|
}
|
|
74
74
|
... on EnterpriseUserAccount {
|
|
75
|
-
${
|
|
75
|
+
${Et(!1)}
|
|
76
76
|
}
|
|
77
77
|
}
|
|
78
78
|
commits(last: 1) {
|
|
@@ -85,7 +85,7 @@ commits(last: 1) {
|
|
|
85
85
|
contexts(first: 100) {
|
|
86
86
|
totalCount
|
|
87
87
|
nodes {
|
|
88
|
-
${!e||
|
|
88
|
+
${!e||M(e,"CHECK_RUN")?dn:""}
|
|
89
89
|
... on StatusContext {
|
|
90
90
|
context
|
|
91
91
|
createdAt
|
|
@@ -153,7 +153,7 @@ assignees(first: 100) {
|
|
|
153
153
|
}
|
|
154
154
|
reviewRequests(first: 100) {
|
|
155
155
|
nodes {
|
|
156
|
-
${!e||
|
|
156
|
+
${!e||M(e,"AS_CODE_OWNER")?"asCodeOwner":""}
|
|
157
157
|
requestedReviewer {
|
|
158
158
|
... on User {
|
|
159
159
|
${F(!1,n)}
|
|
@@ -161,34 +161,34 @@ reviewRequests(first: 100) {
|
|
|
161
161
|
}
|
|
162
162
|
}
|
|
163
163
|
}
|
|
164
|
-
${!e||
|
|
164
|
+
${!e||M(e,"LATEST_REVIEWS")?gn(n):""}
|
|
165
165
|
additions
|
|
166
166
|
deletions
|
|
167
167
|
changedFiles
|
|
168
168
|
mergeable
|
|
169
169
|
mergeStateStatus
|
|
170
170
|
milestone {
|
|
171
|
-
${
|
|
171
|
+
${Me}
|
|
172
172
|
}
|
|
173
173
|
labels(first: 100) {
|
|
174
174
|
nodes {
|
|
175
175
|
${ze}
|
|
176
176
|
}
|
|
177
177
|
}
|
|
178
|
-
${!e||
|
|
179
|
-
`,
|
|
178
|
+
${!e||M(e,"VIEWER_CAN_MERGE_AS_ADMIN")?"viewerCanMergeAsAdmin":""}
|
|
179
|
+
`,hn=(r=!1,n)=>`
|
|
180
180
|
id
|
|
181
|
-
${!n||
|
|
181
|
+
${!n||M(n,"ISSUE_FULL_DATABASE_ID")?"fullDatabaseId":"databaseId"}
|
|
182
182
|
title
|
|
183
183
|
author {
|
|
184
184
|
... on User {
|
|
185
185
|
${F(!1,r)}
|
|
186
186
|
}
|
|
187
187
|
... on Bot {
|
|
188
|
-
${
|
|
188
|
+
${Ar(!1)}
|
|
189
189
|
}
|
|
190
190
|
... on EnterpriseUserAccount {
|
|
191
|
-
${
|
|
191
|
+
${Et(!1)}
|
|
192
192
|
}
|
|
193
193
|
}
|
|
194
194
|
closedAt
|
|
@@ -217,34 +217,35 @@ assignees(first: 100) {
|
|
|
217
217
|
}
|
|
218
218
|
state
|
|
219
219
|
milestone {
|
|
220
|
-
${
|
|
220
|
+
${Me}
|
|
221
221
|
}
|
|
222
222
|
labels(first: 100) {
|
|
223
223
|
nodes {
|
|
224
224
|
${ze}
|
|
225
225
|
}
|
|
226
226
|
}
|
|
227
|
-
`,
|
|
227
|
+
`,fn={"-linked":"-linked",archived:"archived",assignee:"assignee",author:"author",base:"base",closed:"closed",commenter:"commenter",comments:"comments",created:"created",draft:"draft",head:"head",label:"label",language:"language",linked:"linked",in:"in",interactions:"interactions",involves:"involves",is:"is",mentions:"mentions",merged:"merged",milestone:"milestone",no:"no",org:"org",project:"project",reactions:"reactions",repo:"repo",review:"review","reviewed-by":"reviewed-by","review-requested":"review-requested",state:"state",status:"status",team:"team","team-review-requested":"team-review-requested",type:"type",updated:"updated",user:"user","user-review-requested":"user-review-requested"},Rn=new RegExp('(([^\\s]+:)?\\"(?:[^\\"\\\\]|\\\\.)*\\"?)|([^\\"\\s]+)',"g"),Ct=r=>{let n=[];return(r.match(Rn)??[]).forEach(t=>{if(t.includes(":")&&t!="is:closed"){let s=t.split(":")[0];fn[s]&&n.push(t)}}),n},$t="is:open",Gr=r=>{if(!r||r.length===0)return $t;let n=new Set(r),e=n.has("OPEN"),t=n.has("CLOSED"),s=n.has("MERGED");return e&&(t||s)?"":e?"is:open":t&&s?"is:closed":s?"is:merged":"is:closed is:unmerged"},Tr=r=>{if(!r||r.length===0)return $t;let n=new Set(r),e=n.has("OPEN"),t=n.has("CLOSED");return e&&t?"":t?"is:closed":"is:open"},Dt=(r,n,e,t)=>{let s=r==="issue",o=t.stateQualifier??$t;return{query:`
|
|
228
228
|
query SearchIssuesOrPullRequests($query: String! $after: String) {
|
|
229
229
|
search(type:ISSUE query:$query first: ${t.maxPageSize} after:$after) {
|
|
230
|
+
issueCount
|
|
230
231
|
pageInfo {
|
|
231
232
|
hasNextPage
|
|
232
233
|
endCursor
|
|
233
234
|
}
|
|
234
235
|
nodes {
|
|
235
236
|
... on ${s?"Issue":"PullRequest"} {
|
|
236
|
-
${s?
|
|
237
|
+
${s?hn(t.supportsEmail,t.enterpriseVersion??null):He(t.supportsDrafts??!1,t.supportsEmail,t.enterpriseVersion??null)}
|
|
237
238
|
}
|
|
238
239
|
}
|
|
239
240
|
}
|
|
240
|
-
}`,variables:{query:`is:${r} ${o} ${t.includeFromArchivedRepos?"":"archived:false"} ${n}`,after:e}}},
|
|
241
|
+
}`,variables:{query:`is:${r} ${o} ${t.includeFromArchivedRepos?"":"archived:false"} ${n}`,after:e}}},In="Field 'isDraft' doesn't exist on type 'PullRequest'",We=(r=[])=>r.some(n=>n?.message===In),bn=/@@ -(\d+)(?:,\d+ | )\+(\d+)(?:,\d+ | )@@(?:\\n)?/,yn=`
|
|
241
242
|
\
|
|
242
|
-
+`,
|
|
243
|
+
+`,Or=(r,n,e,t)=>{let s=bn.exec(r);if(!s||!s[0]||!s[1])return[];let o=parseInt(s[1],10),i=parseInt(s[2],10),a=r.replace(yn,`
|
|
243
244
|
+`).split(`
|
|
244
|
-
`).slice(1),u=o-1,
|
|
245
|
-
`;break}case"+":{
|
|
246
|
-
`;break}default:
|
|
247
|
-
`}return{line:h,oldLineNumber:
|
|
245
|
+
`).slice(1),u=o-1,p=i-1,l=a.map(m=>{let g,h;switch(m[0]){case"-":{g="DELETED",u+=1,h=`${m.slice(1)}
|
|
246
|
+
`;break}case"+":{g="ADDED",p+=1,h=`${m.slice(1)}
|
|
247
|
+
`;break}default:g="UNMODIFIED",p+=1,u+=1,h=`${m}
|
|
248
|
+
`}return{line:h,oldLineNumber:g!=="ADDED"?u:null,newLineNumber:g!=="DELETED"?p:null,type:g}}),d=e,c=n;if(d!==null&&c!==null&&t!==null&&d<c){let m=0,g=l.length,h=t==="LEFT"?"oldLineNumber":"newLineNumber";for(let y=0;y<l.length;y++){let P=l[y][h];P===d?m=y:P===c&&(g=y)}l=l.slice(m,g+1)}return l},_r=r=>{let n=r.author;return n||(n=Ce),{author:{id:"databaseId"in n?n.databaseId.toString():n.id,graphQLId:n.id,name:("name"in n?n.name:n.login)??n.login,username:n.login,email:("email"in n?n.email:null)??null,avatarUrl:n.avatarUrl,url:n.url},body:r.body,createdAt:r.publishedAt?new Date(r.publishedAt):null,graphQLId:r.id,id:r.fullDatabaseId??r.databaseId?.toString()??r.id,url:r.url}};var xr=`mutation DeleteIssueComment(
|
|
248
249
|
$issueCommentId: ID!
|
|
249
250
|
) {
|
|
250
251
|
deleteIssueComment(input: {
|
|
@@ -252,7 +253,7 @@ query SearchIssuesOrPullRequests($query: String! $after: String) {
|
|
|
252
253
|
}) {
|
|
253
254
|
clientMutationId
|
|
254
255
|
}
|
|
255
|
-
}`,
|
|
256
|
+
}`,kr=`mutation DeletePullRequestReviewComment(
|
|
256
257
|
$pullRequestReviewCommentId: ID!
|
|
257
258
|
) {
|
|
258
259
|
deletePullRequestReviewComment(input: {
|
|
@@ -262,7 +263,7 @@ query SearchIssuesOrPullRequests($query: String! $after: String) {
|
|
|
262
263
|
id
|
|
263
264
|
}
|
|
264
265
|
}
|
|
265
|
-
}`,
|
|
266
|
+
}`,Nr=`mutation UpdateIssueComment(
|
|
266
267
|
$issueCommentId: ID!,
|
|
267
268
|
$body: String!
|
|
268
269
|
) {
|
|
@@ -275,7 +276,7 @@ query SearchIssuesOrPullRequests($query: String! $after: String) {
|
|
|
275
276
|
body
|
|
276
277
|
}
|
|
277
278
|
}
|
|
278
|
-
}`,
|
|
279
|
+
}`,Fr=`mutation ResolveReviewThread(
|
|
279
280
|
$pullRequestReviewThreadId: ID!
|
|
280
281
|
) {
|
|
281
282
|
resolveReviewThread(input: {
|
|
@@ -286,7 +287,7 @@ query SearchIssuesOrPullRequests($query: String! $after: String) {
|
|
|
286
287
|
isResolved
|
|
287
288
|
}
|
|
288
289
|
}
|
|
289
|
-
}`,
|
|
290
|
+
}`,jr=`mutation UnresolveReviewThread(
|
|
290
291
|
$pullRequestReviewThreadId: ID!
|
|
291
292
|
) {
|
|
292
293
|
unresolveReviewThread(input: {
|
|
@@ -297,7 +298,7 @@ query SearchIssuesOrPullRequests($query: String! $after: String) {
|
|
|
297
298
|
isResolved
|
|
298
299
|
}
|
|
299
300
|
}
|
|
300
|
-
}`,
|
|
301
|
+
}`,Qr=`mutation UpdatePullRequestReviewComment(
|
|
301
302
|
$pullRequestReviewCommentId: ID!,
|
|
302
303
|
$body: String!
|
|
303
304
|
) {
|
|
@@ -310,7 +311,7 @@ query SearchIssuesOrPullRequests($query: String! $after: String) {
|
|
|
310
311
|
body
|
|
311
312
|
}
|
|
312
313
|
}
|
|
313
|
-
}`;var
|
|
314
|
+
}`;var Br=r=>`
|
|
314
315
|
query GetPullRequestComments(
|
|
315
316
|
$namespace: String!
|
|
316
317
|
$name: String!
|
|
@@ -356,7 +357,7 @@ query GetPullRequestComments(
|
|
|
356
357
|
}
|
|
357
358
|
}
|
|
358
359
|
}
|
|
359
|
-
`;var
|
|
360
|
+
`;var Lt=`
|
|
360
361
|
id
|
|
361
362
|
databaseId
|
|
362
363
|
owner {
|
|
@@ -369,10 +370,10 @@ defaultBranchRef {
|
|
|
369
370
|
name
|
|
370
371
|
}
|
|
371
372
|
viewerPermission
|
|
372
|
-
`,
|
|
373
|
+
`,Pn={APPROVED:"APPROVED",CHANGES_REQUESTED:"CHANGES_REQUESTED",COMMENTED:"COMMENTED",REVIEW_REQUESTED:"REVIEW_REQUESTED"},wn=1e3,Mr=r=>r!=null&&r>wn?J("partial"):void 0,Sn={MERGEABLE:"MERGEABLE",CONFLICTING:"CONFLICTS",UNKNOWN:"UNKNOWN"},qn={BEHIND:"BEHIND",BLOCKED:"BLOCKED",UNKNOWN:"UNKNOWN_AND_BLOCKED",UNSTABLE:"UNSTABLE",CLEAN:null,DIRTY:null,DRAFT:null,HAS_HOOKS:null},vn={OPEN:"OPEN",CLOSED:"CLOSED"},En=["ADMIN","MAINTAIN","TRIAGE","WRITE"],Gt=r=>({color:`#${r.color}`,description:r.description,graphQLId:r.id,id:null,name:r.name}),Cn=r=>({canCreateWebhook:r==="ADMIN",canPush:r==="ADMIN"||r==="MAINTAIN"||r==="WRITE",isAdmin:r==="ADMIN"}),Ut=r=>({id:r.databaseId.toString(),graphQLId:r.id,namespace:r.owner.login,name:r.name,webUrl:r.url,httpsUrl:r.url.endsWith(".git")?r.url:`${r.url}.git`,sshUrl:r.sshUrl,defaultBranch:r.defaultBranchRef,permissions:Cn(r.viewerPermission)}),$n=r=>({canCreateWebhook:r.admin,canPush:r.admin||r.maintain||r.push,isAdmin:r.admin}),zr=r=>({id:r.id.toString(),graphQLId:r.node_id,namespace:r.owner.login,name:r.name,webUrl:r.html_url,httpsUrl:r.clone_url,sshUrl:r.ssh_url,defaultBranch:{name:r.default_branch},permissions:$n(r.permissions)}),Dn=r=>({path:r.path,isDirectory:r.type==="tree"}),Ln={OPEN:"OPEN",CLOSED:"CLOSED",MERGED:"MERGED"},Un={id:!0,graphQLId:!0,name:!0,username:!0,email:!0,avatarUrl:!0,url:!0},Q=(r,n=Un)=>{let e={};return n.id&&(e.id="databaseId"in r?r.databaseId.toString():r.id),n.graphQLId&&(e.graphQLId=r.id),n.name&&(e.name=r.name??r.login),n.username&&(e.username=r.login),n.email&&(e.email=r.email??null),n.avatarUrl&&(e.avatarUrl=r.avatarUrl),n.url&&(e.url=r.url),e},An=(r,n)=>{let e={IN_PROGRESS:"RUNNING",PENDING:"PENDING",QUEUED:"PENDING",REQUESTED:"PENDING",WAITING:"PENDING"};return r!=="COMPLETED"?e[r]:{ACTION_REQUIRED:"ACTION_REQUIRED",CANCELLED:"CANCELLED",FAILURE:"FAILED",NEUTRAL:null,SKIPPED:"SKIPPED",STALE:"FAILED",STARTUP_FAILURE:"FAILED",SUCCESS:"SUCCESS",TIMED_OUT:"ERROR"}[n]},Gn=r=>({ERROR:"ERROR",EXPECTED:"PENDING",FAILURE:"FAILED",PENDING:"PENDING",SUCCESS:"SUCCESS"})[r],At=r=>{let n=null;r.author?n=r.author:n=Ce;let e=(r.reviewRequests?.nodes||[]).filter(x).filter(i=>!i.asCodeOwner),t=r.headRepository?.url;t&&!t.endsWith(".git")&&(t=`${t}.git`);let s=r.repository?.url;s&&!s.endsWith(".git")&&(s=`${s}.git`);let o=e.filter(i=>i.requestedReviewer&&"__typename"in i.requestedReviewer).map(i=>({reviewer:Q(i.requestedReviewer),state:"REVIEW_REQUESTED"})).concat((r.latestReviews?.nodes||[]).filter(x).map(i=>{let a=Ce;return i.author&&i.author.__typename&&(a=i.author),{reviewer:Q(a),state:Pn[i.state]}}));return{id:r.fullDatabaseId!==void 0?r.fullDatabaseId:r.databaseId.toString(),graphQLId:r.id,title:r.title,description:r.body,number:r.number,state:Ln[r.state],commentCount:r.comments.totalCount,upvoteCount:r.reactions.totalCount,author:n&&n.__typename?Q(n):null,createdDate:new Date(r.createdAt),isDraft:r.isDraft,repository:{id:r.repository.databaseId.toString(),graphQLId:r.repository.id,name:r.repository.name,owner:{login:r.repository.owner.login},remoteInfo:{cloneUrlHTTPS:s,cloneUrlSSH:r.repository.sshUrl}},isCrossRepository:r.headRepository!=null&&r.headRepository.databaseId!==r.repository.databaseId,headRepository:r.headRepository?{id:r.headRepository.databaseId.toString(),graphQLId:r.headRepository.id,name:r.headRepository.name,owner:{login:r.headRepository.owner.login},remoteInfo:{cloneUrlHTTPS:t,cloneUrlSSH:r.headRepository.sshUrl},isFork:r.headRepository.isFork}:null,headCommit:{buildStatuses:r.commits.nodes?.filter(x)[0]?.commit.statusCheckRollup?.contexts.nodes?.filter(x).map(i=>"context"in i?{completedAt:null,description:i.description,name:i.context,state:Gn(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:An(i.status,i.conclusion),startedAt:i.startedAt?new Date(i.startedAt):null,stage:null,url:i.permalink})??[]},headRef:r.headRef?{name:r.headRef.name,oid:r.headRef.target?.oid??null}:null,baseRef:r.baseRef?{name:r.baseRef.name,oid:r.baseRef.target?.oid??null}:null,url:r.url,updatedDate:new Date(r.updatedAt),closedDate:r.closedAt?new Date(r.closedAt):null,mergedDate:r.mergedAt?new Date(r.mergedAt):null,assignees:r.assignees.nodes?r.assignees.nodes.filter(x).map(i=>Q(i)):null,reviews:o,reviewDecision:B(o),additions:r.additions,deletions:r.deletions,fileCount:r.changedFiles,commitCount:r.commits.totalCount,mergeableState:qn[r.mergeStateStatus]??Sn[r.mergeable],milestone:r.milestone?Tt(r.milestone):null,labels:r.labels?.nodes?.filter(x).map(Gt)??[],permissions:{canMerge:En.includes(r.repository.viewerPermission),canMergeAndBypassProtections:r.viewerCanMergeAsAdmin??!1}}},Tn=r=>{let{id:n,comments:e,isOutdated:t,isResolved:s,line:o,startLine:i,diffSide:a,originalLine:u,originalStartLine:p,startDiffSide:l}=r,d=e.nodes?.[0];if(!d)return null;let{author:c,body:m,databaseId:g,fullDatabaseId:h,id:y,path:f,publishedAt:P,url:q}=d,U=o??u,L=i??p,w=a??l;return{author:c?{avatarUrl:c.avatarUrl,email:null,name:c.login}:null,body:m,createdAt:P?new Date(P):null,diffLines:Or(d.diffHunk,U,L,w),id:h??g.toString(),isOutdated:t,isResolved:s,graphQLId:y,threadId:n,filename:f,replies:e.nodes?.filter(x).slice(1).map(On)??[],url:q,line:U,startLine:L,side:w}},On=r=>({author:r.author?{avatarUrl:r.author.avatarUrl,email:null,name:r.author.login}:null,body:r.body,createdAt:r.publishedAt?new Date(r.publishedAt):null,graphQLId:r.id,id:r.fullDatabaseId??r.databaseId.toString(),url:r.url}),_n=r=>{let n=null;return r.author?n=r.author:n=Ce,{id:r.fullDatabaseId!==void 0?r.fullDatabaseId:r.databaseId.toString(),graphQLId:r.id,number:r.number,title:r.title,author:n&&n.__typename?Q(n):null,commentCount:r.comments.totalCount,closedDate:r.closedAt?new Date(r.closedAt):null,createdDate:new Date(r.createdAt),description:null,state:{name:vn[r.state],color:null},type:null,repository:{id:r.repository.databaseId.toString(),graphQLId:r.repository.id,name:r.repository.name,owner:{login:r.repository.owner.login}},url:r.url,updatedDate:new Date(r.updatedAt),assignees:r.assignees.nodes?.filter(x).map(e=>Q(e))??[],upvoteCount:r.reactions.totalCount,milestone:r.milestone?Tt(r.milestone):null,labels:r.labels?.nodes?.filter(x).map(Gt)??[]}},Tt=r=>({id:r.number.toString(),graphQLId:r.id.toString(),number:r.number,title:r.title,description:r.description,isOpen:r.state=="OPEN",url:r.url,startDate:null,dueDate:r.dueOn?new Date(r.dueOn):null}),be=class extends N{constructor(){super(...arguments);this._scopesCache={};this._enterpriseVersionsCache={}}async getScopes(e){let t=e.token||this.config.token;if(!t)return[];let s=this._scopesCache[t];if(!s){let i=(await b(this.config,{query:"query { rateLimit(dryRun: true) { __typename } }"},e)).headers["x-oauth-scopes"];s=i?i.split(", "):[],this._scopesCache[t]=s}return s}async getEnterpriseVersion(e){let t=e.baseUrl||this.config.baseUrl;if(!t)return null;let s=this._enterpriseVersionsCache[t];if(!s){let o=await this.config.request({url:`${z(this.config,e)}/meta`,headers:R(e.token||this.config.token)});if(!o.body.installed_version)return null;s=o.body.installed_version.split(".").slice(0,3).map(i=>parseInt(i,10)),this._enterpriseVersionsCache[t]=s}return s}getEnterpriseAvatarUrlIfNeeded(e,t,s){let o=s.baseUrl||this.config.baseUrl;return!o||o.startsWith(Be)?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 s=ar(e.fields),o=await this.getScopes(t),i=await b(this.config,{query:`
|
|
373
374
|
query getCurrentUser {
|
|
374
375
|
viewer {
|
|
375
|
-
${F(!1,
|
|
376
|
+
${F(!1,K(o),s)}
|
|
376
377
|
}
|
|
377
378
|
}
|
|
378
379
|
`},t),a=i.body.data?.viewer;if(!a)throw new I("Current user not found.",i.body.errors);return{data:Q(a,s)}}async getAccountsForRepo(e,t={}){let s=await this.getScopes(t),{repo:{namespace:o,name:i},cursor:a}=e,u=await b(this.config,{query:`
|
|
@@ -380,7 +381,7 @@ query getAccountsForRepo($owner: String!, $name: String! $cursor: String, $first
|
|
|
380
381
|
repository(owner: $owner, name: $name) {
|
|
381
382
|
assignableUsers(first: $first, after: $cursor) {
|
|
382
383
|
nodes {
|
|
383
|
-
${F(!1,
|
|
384
|
+
${F(!1,K(s))}
|
|
384
385
|
}
|
|
385
386
|
pageInfo {
|
|
386
387
|
endCursor
|
|
@@ -389,7 +390,7 @@ query getAccountsForRepo($owner: String!, $name: String! $cursor: String, $first
|
|
|
389
390
|
}
|
|
390
391
|
}
|
|
391
392
|
}
|
|
392
|
-
`,variables:{owner:o,name:i,cursor:a,first:C}},t);if(!u.body.data)throw new I("Could not fetch accounts for repo",u.body.errors);return{pageInfo:u.body.data.repository?.assignableUsers?.pageInfo??{endCursor:null,hasNextPage:!1},data:u.body.data.repository?.assignableUsers?.nodes?.map(
|
|
393
|
+
`,variables:{owner:o,name:i,cursor:a,first:C}},t);if(!u.body.data)throw new I("Could not fetch accounts for repo",u.body.errors);return{pageInfo:u.body.data.repository?.assignableUsers?.pageInfo??{endCursor:null,hasNextPage:!1},data:u.body.data.repository?.assignableUsers?.nodes?.map(p=>Q(p))??[]}}async getUserForCommit(e,t={}){let s=await b(this.config,{query:`
|
|
393
394
|
query getUserForCommit(
|
|
394
395
|
$owner: String!
|
|
395
396
|
$name: String!
|
|
@@ -408,7 +409,7 @@ query getUserForCommit(
|
|
|
408
409
|
}
|
|
409
410
|
}
|
|
410
411
|
}
|
|
411
|
-
`,variables:{owner:e.repo.namespace,name:e.repo.name,oid:e.oid,avatarSize:e.avatarSize}},t),o=s.body.data?.repository;if(!o)throw new I("Repository not found.",s.body.errors);let i=o.object?.author;if(!i)throw new I("Commit not found.",s.body.errors);return{data:{name:i.name,email:i.email,avatarUrl:this.getEnterpriseAvatarUrlIfNeeded(i.avatarUrl,i.email,t)}}}async createCommit(e,t={}){let{commitMessage:s,deletedFiles:o,newOrModifiedFiles:i,repo:a,target:u}=e,
|
|
412
|
+
`,variables:{owner:e.repo.namespace,name:e.repo.name,oid:e.oid,avatarSize:e.avatarSize}},t),o=s.body.data?.repository;if(!o)throw new I("Repository not found.",s.body.errors);let i=o.object?.author;if(!i)throw new I("Commit not found.",s.body.errors);return{data:{name:i.name,email:i.email,avatarUrl:this.getEnterpriseAvatarUrlIfNeeded(i.avatarUrl,i.email,t)}}}async createCommit(e,t={}){let{commitMessage:s,deletedFiles:o,newOrModifiedFiles:i,repo:a,target:u}=e,p=await b(this.config,{query:`
|
|
412
413
|
mutation createCommitOnBranch(
|
|
413
414
|
$branchName: String!,
|
|
414
415
|
$expectedHeadOid: GitObjectID!,
|
|
@@ -435,12 +436,12 @@ mutation createCommitOnBranch(
|
|
|
435
436
|
}
|
|
436
437
|
}
|
|
437
438
|
}
|
|
438
|
-
`,variables:{branchName:u.name,expectedHeadOid:u.oid,fileChanges:{additions:Object.entries(i).map(([
|
|
439
|
+
`,variables:{branchName:u.name,expectedHeadOid:u.oid,fileChanges:{additions:Object.entries(i).map(([l,d])=>({contents:Hr.Base64.encode(d),path:l})),deletions:o.map(l=>({path:l}))},message:{body:s.description,headline:s.summary},repositoryNameWithOwner:`${a.namespace}/${a.name}`}},t);if(!p.body.data)throw new I("Could not create commit",p.body.errors);return{data:{name:p.body.data.createCommitOnBranch.ref.name,commit:{authoredDate:new Date(p.body.data.createCommitOnBranch.commit.authoredDate),committedDate:new Date(p.body.data.createCommitOnBranch.commit.committedDate),oid:p.body.data.createCommitOnBranch.commit.oid}}}}async getAccountForEmail(e,t={}){let s=await this.getScopes(t),o=await b(this.config,{query:`
|
|
439
440
|
query getAccountForEmail($query: String! $avatarSize: Int) {
|
|
440
441
|
search(query: $query, type: USER, first: 1) {
|
|
441
442
|
nodes {
|
|
442
443
|
... on User {
|
|
443
|
-
${F(!0,
|
|
444
|
+
${F(!0,K(s))}
|
|
444
445
|
}
|
|
445
446
|
}
|
|
446
447
|
}
|
|
@@ -448,7 +449,7 @@ query getAccountForEmail($query: String! $avatarSize: Int) {
|
|
|
448
449
|
`,variables:{query:`in:email ${e.email}`,avatarSize:e.avatarSize}},t),i=o.body.data?.search?.nodes?.[0];if(!i)throw new I("Could not find user via email",o.body.errors);return{data:Q({...i,avatarUrl:this.getEnterpriseAvatarUrlIfNeeded(i.avatarUrl,i.email,t)})}}async getAccountForUsername(e,t={}){let s=await this.getScopes(t),o=await b(this.config,{query:`
|
|
449
450
|
query getUserForUsername($login: String! $avatarSize: Int) {
|
|
450
451
|
user(login: $login) {
|
|
451
|
-
${F(!0,
|
|
452
|
+
${F(!0,K(s))}
|
|
452
453
|
}
|
|
453
454
|
}
|
|
454
455
|
`,variables:{login:e.username,avatarSize:e.avatarSize}},t),i=o.body.data?.user;if(!i)throw new I("Could not find user via username",o.body.errors);return{data:Q({...i,avatarUrl:this.getEnterpriseAvatarUrlIfNeeded(i.avatarUrl,i.email,t)})}}async getOrgsForCurrentUser(e={},t={}){let s=await b(this.config,{query:`
|
|
@@ -489,19 +490,19 @@ query getOrgMember($cursor: String, $first: Int!, $login: String!) {
|
|
|
489
490
|
`,variables:{cursor:e.cursor,first:C,login:e.org}},t);if(!s.body.data?.viewer.organization?.membersWithRole&&s.body.errors?.length)throw new I("Could not read the members of the organization",s.body.errors);let o=s.body.data?.viewer.organization?.membersWithRole.nodes||[];return{pageInfo:{hasNextPage:s.body.data?.viewer.organization?.membersWithRole.pageInfo.hasNextPage??!1,endCursor:s.body.data?.viewer.organization?.membersWithRole.pageInfo.endCursor??null},data:o.map(i=>Q({...i,avatarUrl:this.getEnterpriseAvatarUrlIfNeeded(i.avatarUrl,i.email,t)}))}}async getRepo(e,t={}){let s=await b(this.config,{query:`
|
|
490
491
|
query getRepo($owner: String!, $name: String!) {
|
|
491
492
|
repository(owner: $owner, name: $name) {
|
|
492
|
-
${
|
|
493
|
+
${Lt}
|
|
493
494
|
}
|
|
494
495
|
}
|
|
495
|
-
`,variables:{owner:e.namespace,name:e.name}},t);if(!s.body.data?.repository)throw new I(`Repository ${e.namespace}/${e.name} not found`,s.body.errors);return{data:
|
|
496
|
-
getRepo_${
|
|
497
|
-
${
|
|
496
|
+
`,variables:{owner:e.namespace,name:e.name}},t);if(!s.body.data?.repository)throw new I(`Repository ${e.namespace}/${e.name} not found`,s.body.errors);return{data:Ut(s.body.data.repository)}}async getRepos(e,t={}){let s=e.map(({namespace:u,name:p},l)=>`
|
|
497
|
+
getRepo_${l}: repository(owner: "${u}", name: "${p}") {
|
|
498
|
+
${Lt}
|
|
498
499
|
}
|
|
499
500
|
`).join(`
|
|
500
501
|
`),o=await b(this.config,{query:`
|
|
501
502
|
query batchGetRepos {
|
|
502
503
|
${s}
|
|
503
504
|
}
|
|
504
|
-
`},t);if(!o.body.data)throw new I("Could not fetch repos",o.body.errors);let i=[],a=[];return e.forEach((u,
|
|
505
|
+
`},t);if(!o.body.data)throw new I("Could not fetch repos",o.body.errors);let i=[],a=[];return e.forEach((u,p)=>{let l=o.body.data[`getRepo_${p}`];l?i.push(Ut(l)):a.push({input:u})}),{data:i,errors:a}}async fetchMultipleRESTPages(e,t,s,o){let i=[];for(let d=0;d<t;d++)i.push(s(e+d));let a=await Promise.all(i),u=[];for(let d of a){if(!d.body)throw new Error(d.statusText||"Unknown error");u=u.concat(d.body.map(c=>o(c)))}let p=a.every(d=>d.body.length===100),l=e+t;return{data:u,pageInfo:{hasNextPage:p,nextPage:p?l:null}}}async getReposForCurrentUser(e,t={}){if(e.simultaneousPagesToFetch&&e.simultaneousPagesToFetch>40)throw new Error("The argument 'simultaneousPagesToFetch' cannot exceed 40 for 'getReposForCurrentUser'");let s=new URLSearchParams;s.append("per_page","100"),e.affiliations&&s.append("affiliation",e.affiliations.join(","));let o=i=>this.config.request({url:`${z(this.config,t)}/user/repos?${s.toString()}&page=${i}`,headers:{...R(t.token||this.config.token),Accept:"application/vnd.github.raw+json","X-Github-Next-Global-ID":1}});return await this.fetchMultipleRESTPages(e.page??1,e.simultaneousPagesToFetch??4,o,zr)}async getReposForOrg(e,t={}){if(e.simultaneousPagesToFetch&&e.simultaneousPagesToFetch>40)throw new Error("The argument 'simultaneousPagesToFetch' cannot exceed 40 for 'getReposForOrg'");let s=o=>this.config.request({url:`${z(this.config,t)}/orgs/${e.orgName}/repos?per_page=100&page=${o}`,headers:{...R(t.token||this.config.token),Accept:"application/vnd.github.raw+json","X-Github-Next-Global-ID":1}});return await this.fetchMultipleRESTPages(e.page??1,e.simultaneousPagesToFetch??4,s,zr)}async getReposForUsernames(e,t={}){if(!e.usernames.length)return{pageInfo:{endCursor:null,hasNextPage:!1},data:[]};let s=await b(this.config,{query:`
|
|
505
506
|
query getReposForUsernames($query: String!, $cursor: String, $first: Int!) {
|
|
506
507
|
search(query: $query, type: REPOSITORY, first: $first, after: $cursor) {
|
|
507
508
|
pageInfo {
|
|
@@ -510,12 +511,12 @@ query getReposForUsernames($query: String!, $cursor: String, $first: Int!) {
|
|
|
510
511
|
}
|
|
511
512
|
nodes {
|
|
512
513
|
... on Repository {
|
|
513
|
-
${
|
|
514
|
+
${Lt}
|
|
514
515
|
}
|
|
515
516
|
}
|
|
516
517
|
}
|
|
517
518
|
}
|
|
518
|
-
`,variables:{query:`fork:true ${e.usernames.map(i=>`user:${i}`).join(" ")}`,cursor:e.cursor,first:C}},t);if(!s.body.data)throw new I("Could not fetch repos for usernames",s.body.errors);let o=s.body.data.search.nodes||[];return{pageInfo:s.body.data.search.pageInfo,data:o.map(
|
|
519
|
+
`,variables:{query:`fork:true ${e.usernames.map(i=>`user:${i}`).join(" ")}`,cursor:e.cursor,first:C}},t);if(!s.body.data)throw new I("Could not fetch repos for usernames",s.body.errors);let o=s.body.data.search.nodes||[];return{pageInfo:s.body.data.search.pageInfo,data:o.map(Ut)}}async getReposForOwners(e,t={}){return this.getReposForUsernames({usernames:e.owners.filter(s=>s.username).map(s=>s.username),cursor:e.cursor},t)}async getRefs(e,t,s={}){let o=await b(this.config,{query:`
|
|
519
520
|
query getRefs($owner: String!, $name: String!, $refPrefix: String!, $cursor: String, $first: Int!) {
|
|
520
521
|
repository(owner: $owner, name: $name) {
|
|
521
522
|
refs(refPrefix: $refPrefix first: $first after: $cursor) {
|
|
@@ -536,7 +537,7 @@ query getRefs($owner: String!, $name: String!, $refPrefix: String!, $cursor: Str
|
|
|
536
537
|
}
|
|
537
538
|
}
|
|
538
539
|
}
|
|
539
|
-
`,variables:{owner:t.repo.namespace,name:t.repo.name,refPrefix:e,cursor:t.cursor,first:C}},s),i=o.body.data?.repository;if(!i)throw new I("Ref repository not found.",o.body.errors);let a=i.refs;return a?{pageInfo:a.pageInfo,data:(a.nodes||[]).map(u=>{let
|
|
540
|
+
`,variables:{owner:t.repo.namespace,name:t.repo.name,refPrefix:e,cursor:t.cursor,first:C}},s),i=o.body.data?.repository;if(!i)throw new I("Ref repository not found.",o.body.errors);let a=i.refs;return a?{pageInfo:a.pageInfo,data:(a.nodes||[]).map(u=>{let p=u.target?.oid?u.target:null;return{name:u.name,commit:p?{oid:p.oid,authoredDate:new Date(p.authoredDate),committedDate:new Date(p.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 s=await b(this.config,{query:`
|
|
540
541
|
query getBlame($owner: String!, $name: String!, $ref: String!, $path: String!) {
|
|
541
542
|
repository(owner: $owner, name: $name) {
|
|
542
543
|
object(expression: $ref) {
|
|
@@ -575,7 +576,7 @@ query getBlame($owner: String!, $name: String!, $ref: String!, $path: String!) {
|
|
|
575
576
|
}
|
|
576
577
|
}
|
|
577
578
|
}
|
|
578
|
-
`,variables:{owner:e.repo.namespace,name:e.repo.name,ref:e.ref,path:e.path}},t),o=s.body.data?.repository;if(!o)throw new I("Blame repository not found.",s.body.errors);let i=o.object;if(!i||!("blame"in i))throw new I("Ref not found.",s.body.errors);if(i.blame.ranges.length===0)throw new I("File not found.",s.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 s=await this.config.request({url:`${
|
|
579
|
+
`,variables:{owner:e.repo.namespace,name:e.repo.name,ref:e.ref,path:e.path}},t),o=s.body.data?.repository;if(!o)throw new I("Blame repository not found.",s.body.errors);let i=o.object;if(!i||!("blame"in i))throw new I("Ref not found.",s.body.errors);if(i.blame.ranges.length===0)throw new I("File not found.",s.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 s=await this.config.request({url:`${z(this.config,t)}/repos/${e.repo.namespace}/${e.repo.name}/contents/${encodeURIComponent(e.path)}?ref=${e.ref}`,headers:{...R(t.token||this.config.token),Accept:"application/vnd.github.raw+json"}});if(s.headers["content-type"].startsWith("application/json"))throw new Error(`GitHub: got directory when fetching "${e.path}", getFileContents does not support fetching directories`);if(!s.headers["content-type"].startsWith("application/vnd.github.raw+json"))throw new Error(`GitHub: unsupported content type "${s.headers["content-type"]}" when fetching "${e.path}"`);return{data:new Blob([s.body])}}async getMergeBase(e,t={}){return{data:(await this.config.request({url:`${z(this.config,t)}/repos/${e.repo.namespace}/${e.repo.name}/compare/${encodeURIComponent(e.base)}...${encodeURIComponent(e.head)}`,headers:R(t.token||this.config.token)})).body.merge_base_commit.sha}}async getPullRequestDiff(e,t={}){return(await this.config.request({url:`${z(this.config,t)}/repos/${e.repo.namespace}/${e.repo.name}/pulls/${e.pullRequestId}`,headers:{...R(t.token||this.config.token),Accept:"application/vnd.github.diff"}})).body??""}async searchPullRequests(e,t={}){let s=await this.getEnterpriseVersion(t),o=await this.getScopes(t),i=K(o),a=Gr(e.states),u=$(e.maxPageSize,{fallback:Dr,max:C}),p=c=>{let m=c&&typeof e.isDraft=="boolean"?`${e.query} draft:${e.isDraft}`:e.query;return Dt("pr",m,e.cursor,{maxPageSize:u,supportsEmail:i,supportsDrafts:c,enterpriseVersion:s,includeFromArchivedRepos:e.includeFromArchivedRepos,stateQualifier:a})},l=await b(this.config,p(!0),t);l.body.errors&&We(l.body.errors)&&(this.config.baseUrl||t.baseUrl)&&(l=await b(this.config,p(!1),t));let{data:d}=l.body;if(!d)throw new I("Could not search pull requests",l.body.errors);return{pageInfo:{hasNextPage:d.search.pageInfo.hasNextPage,endCursor:d.search.pageInfo.endCursor},data:k(d.search.nodes?.filter(x).map(At)||[],e.states),metadata:Mr(d.search.issueCount)}}async searchIssues(e,t={}){let s=await this.getEnterpriseVersion(t),o=await this.getScopes(t),i=K(o),a=Tr(e.states),u=$(e.maxPageSize,{fallback:Lr,max:C}),p=await b(this.config,Dt("issue",e.query,e.cursor,{supportsEmail:i,includeFromArchivedRepos:e.includeFromArchivedRepos,maxPageSize:u,enterpriseVersion:s,stateQualifier:a}),t),{data:l}=p.body;if(!l)throw new I("Could not search issues",p.body.errors);return{pageInfo:{hasNextPage:l.search.pageInfo.hasNextPage,endCursor:l.search.pageInfo.endCursor},data:l.search.nodes?.filter(x).map(_n)||[],metadata:Mr(l.search.issueCount)}}async getPullRequestsAssociatedWithUser(e,t={}){let s=[`involves:${e.username}`];return e.repos?.length&&e.repos.forEach(o=>{s.push(`repo:${o.namespace}/${o.name}`)}),e.labelNames&&e.labelNames.forEach(o=>{s.push(`label:"${o}"`)}),this.searchPullRequests({query:s.join(" "),cursor:e.cursor,includeFromArchivedRepos:e.includeFromArchivedRepos,maxPageSize:e.maxPageSize,states:e.states},t)}async getPullRequestsForRepos(e,t={}){let{assigneeLogins:s,updatedBefore:o,authorLogin:i,repos:a,reviewRequestedLogin:u,startQuery:p,mentionLogin:l,labelNames:d,maxPageSize:c}=e,m=Ct(p||"");return a.forEach(g=>{m.push(`repo:${g.namespace}/${g.name}`)}),s&&s.forEach(g=>{m.push(`assignee:${g}`)}),o&&m.push(`updated:<${o}`),i&&m.push(`author:${i}`),u&&m.push(`review-requested:${u}`),l&&m.push(`mentions:${l}`),d&&d.forEach(g=>{m.push(`label:"${g}"`)}),this.searchPullRequests({query:`sort:updated ${m.join(" ")}`,isDraft:e.isDraft,cursor:e.cursor,includeFromArchivedRepos:e.includeFromArchivedRepos,maxPageSize:c,states:e.states},t)}async getPullRequestForRepo(e,t={}){let s=await this.getEnterpriseVersion(t),o=await this.getScopes(t),i=K(o),a=d=>({query:`query getPullRequest(
|
|
579
580
|
$owner: String!
|
|
580
581
|
$name: String!
|
|
581
582
|
$number: Int!
|
|
@@ -585,18 +586,18 @@ query getBlame($owner: String!, $name: String!, $ref: String!, $path: String!) {
|
|
|
585
586
|
name: $name
|
|
586
587
|
) {
|
|
587
588
|
pullRequest(number: $number) {
|
|
588
|
-
${
|
|
589
|
+
${He(d,i,s)}
|
|
589
590
|
}
|
|
590
591
|
}
|
|
591
|
-
}`,variables:{owner:e.repo.namespace,name:e.repo.name,number:e.number}}),u=await b(this.config,a(!0),t);u.body.errors&&
|
|
592
|
+
}`,variables:{owner:e.repo.namespace,name:e.repo.name,number:e.number}}),u=await b(this.config,a(!0),t);u.body.errors&&We(u.body.errors)&&(this.config.baseUrl||t.baseUrl)&&(u=await b(this.config,a(!1),t));let{data:p}=u.body;if(!p)throw new I("Could not fetch pull request by number",u.body.errors);let l=u.body.data?.repository.pullRequest;return{data:l?At(l):null}}async getPullRequestDescription(e,t={}){try{let s=await this.config.request({url:`${z(this.config,t)}/repos/${e.repo.namespace}/${e.repo.name}/pulls/${e.number}`,headers:{...R(t.token||this.config.token),Accept:"application/vnd.github.full+json"}});return{data:{description:s.body?.body??"",descriptionHtml:s.body?.body_html||null}}}catch{return{data:{description:null,descriptionHtml:null}}}}async setPullRequestDescription(e,t={}){let s=await this.config.request({method:"PATCH",url:`${z(this.config,t)}/repos/${e.repo.namespace}/${e.repo.name}/pulls/${e.number}`,headers:{...R(t.token||this.config.token),Accept:"application/vnd.github+json","Content-Type":"application/json"},body:JSON.stringify({body:e.description})});return{data:{description:s.body?.body??e.description,descriptionHtml:s.body?.body_html||null}}}async getPullRequestByGraphQLId(e,t={}){let s=await this.getEnterpriseVersion(t),o=await this.getScopes(t),i=K(o),a=d=>({query:`query getPullRequest(
|
|
592
593
|
$graphQLId: ID!
|
|
593
594
|
) {
|
|
594
595
|
node(id: $graphQLId) {
|
|
595
596
|
... on PullRequest {
|
|
596
|
-
${
|
|
597
|
+
${He(d,i,s)}
|
|
597
598
|
}
|
|
598
599
|
}
|
|
599
|
-
}`,variables:{graphQLId:e.graphQLId}}),u=await b(this.config,a(!0),t);u.body.errors&&
|
|
600
|
+
}`,variables:{graphQLId:e.graphQLId}}),u=await b(this.config,a(!0),t);u.body.errors&&We(u.body.errors)&&(this.config.baseUrl||t.baseUrl)&&(u=await b(this.config,a(!1),t));let{data:p}=u.body;if(!p)throw new I("Could not fetch pull request by id",u.body.errors);let l=u.body.data?.node;return{data:l?At(l):null}}async closePullRequest(e,t={}){let{pullRequest:{graphQLId:s}}=e;if(!s)throw new Error('GitHub requires "graphQLId" for this function.');let o=`mutation ClosePullRequest($pullRequestGraphQLId: ID!) {
|
|
600
601
|
closePullRequest(input: { pullRequestId: $pullRequestGraphQLId }) {
|
|
601
602
|
pullRequest {
|
|
602
603
|
id
|
|
@@ -669,7 +670,7 @@ query getBlame($owner: String!, $name: String!, $ref: String!, $path: String!) {
|
|
|
669
670
|
}
|
|
670
671
|
}
|
|
671
672
|
}
|
|
672
|
-
}`,a=await b(this.config,{query:i,variables:{subjectId:s.graphQLId,body:o}},t);if(!a.body.data?.addComment?.commentEdge?.node?.id)throw new I("Could not add comment to pull request",a.body.errors)}async addInlineCommentToPullRequest(e,t={}){let{pullRequest:s,comment:o,path:i,line:a,side:u="RIGHT",threadId:
|
|
673
|
+
}`,a=await b(this.config,{query:i,variables:{subjectId:s.graphQLId,body:o}},t);if(!a.body.data?.addComment?.commentEdge?.node?.id)throw new I("Could not add comment to pull request",a.body.errors)}async addInlineCommentToPullRequest(e,t={}){let{pullRequest:s,comment:o,path:i,line:a,side:u="RIGHT",threadId:p}=e;if(!s.graphQLId)throw new Error('GitHub requires "graphQLId" for this function.');if(!o?.trim())throw new Error("GitHub requires a comment when adding an inline comment to a pull request.");if(p)return this.addReplyToReviewThread({threadId:p,comment:o},t);if(!i?.trim())throw new Error("GitHub requires a file path when adding an inline comment to a pull request.");if(!Number.isInteger(a)||a<1)throw new Error("GitHub requires a positive line number when adding an inline comment to a pull request.");if(u!=="LEFT"&&u!=="RIGHT")throw new Error('GitHub requires side to be either "LEFT" or "RIGHT".');return this.createReviewThread({pullRequest:s,comment:o,path:i,line:a,side:u},t)}async deleteInlineComment(e,t={}){let{commentId:s}=e;if(!s)throw new Error('GitHub requires "commentId" for this function.');let o=await b(this.config,{query:kr,variables:{pullRequestReviewCommentId:s}},t);if(!o.body.data?.deletePullRequestReviewComment)throw new I("Could not delete inline comment",o.body.errors)}async deleteComment(e,t={}){let{commentId:s}=e;if(!s)throw new Error('GitHub requires "commentId" for this function.');let o=await b(this.config,{query:xr,variables:{issueCommentId:s}},t);if(!o.body.data?.deleteIssueComment)throw new I("Could not delete comment",o.body.errors)}async editComment(e,t={}){let{commentId:s,body:o}=e;if(!s)throw new Error('GitHub requires "commentId" for this function.');if(!o?.trim())throw new Error("GitHub requires a body when editing a comment.");let i=await b(this.config,{query:Nr,variables:{issueCommentId:s,body:o}},t);if(!i.body.data?.updateIssueComment?.issueComment?.id)throw new I("Could not edit comment",i.body.errors)}async editInlineComment(e,t={}){let{commentId:s,body:o}=e;if(!s)throw new Error('GitHub requires "commentId" for this function.');if(!o?.trim())throw new Error("GitHub requires a body when editing an inline comment.");let i=await b(this.config,{query:Qr,variables:{pullRequestReviewCommentId:s,body:o}},t);if(!i.body.data?.updatePullRequestReviewComment?.pullRequestReviewComment?.id)throw new I("Could not edit inline comment",i.body.errors)}async resolveReviewThread(e,t={}){let{threadId:s}=e;if(!s)throw new Error('GitHub requires "threadId" for this function.');let o=await b(this.config,{query:Fr,variables:{pullRequestReviewThreadId:s}},t);if(!o.body.data?.resolveReviewThread?.thread?.id)throw new I("Could not resolve review thread",o.body.errors)}async unresolveReviewThread(e,t={}){let{threadId:s}=e;if(!s)throw new Error('GitHub requires "threadId" for this function.');let o=await b(this.config,{query:jr,variables:{pullRequestReviewThreadId:s}},t);if(!o.body.data?.unresolveReviewThread?.thread?.id)throw new I("Could not unresolve review thread",o.body.errors)}async addReplyToReviewThread(e,t){let{threadId:s,comment:o}=e,i=`mutation AddPullRequestReviewThreadReply(
|
|
673
674
|
$threadId: ID!,
|
|
674
675
|
$body: String!
|
|
675
676
|
) {
|
|
@@ -681,7 +682,7 @@ query getBlame($owner: String!, $name: String!, $ref: String!, $path: String!) {
|
|
|
681
682
|
id
|
|
682
683
|
}
|
|
683
684
|
}
|
|
684
|
-
}`,a=await b(this.config,{query:i,variables:{threadId:s,body:o}},t);if(!a.body.data?.addPullRequestReviewThreadReply?.comment?.id)throw new I("Could not add reply to pull request review thread",a.body.errors);return s}async createReviewThread(e,t){let{pullRequest:s,comment:o,path:i,line:a,side:u}=e,
|
|
685
|
+
}`,a=await b(this.config,{query:i,variables:{threadId:s,body:o}},t);if(!a.body.data?.addPullRequestReviewThreadReply?.comment?.id)throw new I("Could not add reply to pull request review thread",a.body.errors);return s}async createReviewThread(e,t){let{pullRequest:s,comment:o,path:i,line:a,side:u}=e,p=`mutation AddInlineCommentToPullRequest(
|
|
685
686
|
$pullRequestId: ID!,
|
|
686
687
|
$body: String!,
|
|
687
688
|
$path: String!,
|
|
@@ -707,7 +708,7 @@ query getBlame($owner: String!, $name: String!, $ref: String!, $path: String!) {
|
|
|
707
708
|
}
|
|
708
709
|
}
|
|
709
710
|
}
|
|
710
|
-
}`,
|
|
711
|
+
}`,l=await b(this.config,{query:p,variables:{pullRequestId:s.graphQLId,body:o,path:i,line:a,side:u}},t);if(!l.body.data?.addPullRequestReview?.pullRequestReview?.id)throw new I("Could not add inline comment to pull request",l.body.errors);return l.body.data?.addPullRequestReview?.pullRequestReview?.comments?.nodes?.[0]?.id}async setPullRequestMilestone(e,t={}){let{pullRequest:s,milestone:o}=e;if(!s.graphQLId)throw new Error('GitHub requires "graphQLId" for this function.');let i=`mutation SetPullRequestMilestone($pullRequestGraphQLId: ID!, $milestoneGraphQLId: ID) {
|
|
711
712
|
updatePullRequest(input: { pullRequestId: $pullRequestGraphQLId, milestoneId: $milestoneGraphQLId }) {
|
|
712
713
|
pullRequest {
|
|
713
714
|
id
|
|
@@ -725,19 +726,19 @@ query getBlame($owner: String!, $name: String!, $ref: String!, $path: String!) {
|
|
|
725
726
|
id
|
|
726
727
|
}
|
|
727
728
|
}
|
|
728
|
-
}`,o=await b(this.config,{query:s,variables:{pullRequestGraphQLId:e}},t);if(!o.body.data?.convertPullRequestToDraft?.pullRequest?.id)throw new I("Could not convert pull request to draft",o.body.errors)}async setPullRequestAsDraft(e,t={}){let{pullRequest:{graphQLId:s},isDraft:o}=e;if(!s)throw new Error('GitHub requires "graphQLId" for this function.');if(o){await this.convertPullRequestToDraft(s,t);return}await this.markPullRequestReadyForReview(s,t)}async setPullRequestReviewers(e,t={}){let{pullRequest:{reviews:s,graphQLId:o},reviewers:i}=e;if(!s)throw new Error('GitHub requires "reviews" for this function');if(!o)throw new Error('GitHub requires "graphQLId" for this function.');let a=s.filter(d=>d.state!=="REVIEW_REQUESTED").map(d=>{if(!d.reviewer.graphQLId)throw new Error('GitHub requires reviewer "graphQLId" for this function.');return d.reviewer.graphQLId}),u=i.map(d=>{if(!d.graphQLId)throw new Error('GitHub requires reviewer "graphQLId" for this function.');return d.graphQLId}).filter(d=>a.indexOf(d)===-1),
|
|
729
|
+
}`,o=await b(this.config,{query:s,variables:{pullRequestGraphQLId:e}},t);if(!o.body.data?.convertPullRequestToDraft?.pullRequest?.id)throw new I("Could not convert pull request to draft",o.body.errors)}async setPullRequestAsDraft(e,t={}){let{pullRequest:{graphQLId:s},isDraft:o}=e;if(!s)throw new Error('GitHub requires "graphQLId" for this function.');if(o){await this.convertPullRequestToDraft(s,t);return}await this.markPullRequestReadyForReview(s,t)}async setPullRequestReviewers(e,t={}){let{pullRequest:{reviews:s,graphQLId:o},reviewers:i}=e;if(!s)throw new Error('GitHub requires "reviews" for this function');if(!o)throw new Error('GitHub requires "graphQLId" for this function.');let a=s.filter(d=>d.state!=="REVIEW_REQUESTED").map(d=>{if(!d.reviewer.graphQLId)throw new Error('GitHub requires reviewer "graphQLId" for this function.');return d.reviewer.graphQLId}),u=i.map(d=>{if(!d.graphQLId)throw new Error('GitHub requires reviewer "graphQLId" for this function.');return d.graphQLId}).filter(d=>a.indexOf(d)===-1),p=`mutation SetPullRequestReviewers($pullRequestGraphQLId: ID!, $reviewerGraphQLIds: [ID!]!) {
|
|
729
730
|
requestReviews(input: { pullRequestId: $pullRequestGraphQLId, userIds: $reviewerGraphQLIds }) {
|
|
730
731
|
pullRequest {
|
|
731
732
|
id
|
|
732
733
|
}
|
|
733
734
|
}
|
|
734
|
-
}`,
|
|
735
|
+
}`,l=await b(this.config,{query:p,variables:{pullRequestGraphQLId:o,reviewerGraphQLIds:u}},t);if(!l.body.data?.requestReviews?.pullRequest?.id)throw new I("Could not set pull request reviewers",l.body.errors)}async reRequestPullRequestReviews(e,t={}){let{pullRequest:{reviews:s,graphQLId:o},reviewers:i}=e;if(!o)throw new Error('GitHub requires "graphQLId" for this function.');if(!s)throw new Error('GitHub requires "reviews" for this function.');let a=[];for(let l of i){if(!l.graphQLId)throw new Error('GitHub requires reviwer "graphQLId" for this function.');if(!s.find(d=>d.reviewer.graphQLId===l.graphQLId))throw new Error("Can only re-request review from existing reviewer.");a.push(l.graphQLId)}let u=`mutation SetPullRequestReviewers($pullRequestGraphQLId: ID!, $reviewerGraphQLIds: [ID!]!) {
|
|
735
736
|
requestReviews(input: { pullRequestId: $pullRequestGraphQLId, userIds: $reviewerGraphQLIds, union: true }) {
|
|
736
737
|
pullRequest {
|
|
737
738
|
id
|
|
738
739
|
}
|
|
739
740
|
}
|
|
740
|
-
}`,
|
|
741
|
+
}`,p=await b(this.config,{query:u,variables:{pullRequestGraphQLId:o,reviewerGraphQLIds:a}},t);if(!p.body.data?.requestReviews?.pullRequest?.id)throw new I("Could not re-request pull request reviews",p.body.errors)}async setPullRequestAssignees(e,t={}){let{pullRequest:s,assignees:o}=e;if(!s.graphQLId)throw new Error('GitHub requires "graphQLId" for this function.');let i=o.map(p=>{if(!p.graphQLId)throw new Error('GitHub requires assignee "graphQLId" for this function.');return p.graphQLId}),a=`mutation SetPullRequestAssignees($pullRequestGraphQLId: ID!, $assigneeGraphQLIds: [ID!]!) {
|
|
741
742
|
updatePullRequest(input: { pullRequestId: $pullRequestGraphQLId, assigneeIds: $assigneeGraphQLIds }) {
|
|
742
743
|
pullRequest {
|
|
743
744
|
id
|
|
@@ -771,7 +772,7 @@ query getBlame($owner: String!, $name: String!, $ref: String!, $path: String!) {
|
|
|
771
772
|
login
|
|
772
773
|
}
|
|
773
774
|
body
|
|
774
|
-
${!s||
|
|
775
|
+
${!s||M(s,"PR_REVIEW_COMMENT_FULL_DATABASE_ID")?"fullDatabaseId":"databaseId"}
|
|
775
776
|
diffHunk
|
|
776
777
|
id
|
|
777
778
|
path
|
|
@@ -791,7 +792,7 @@ query getBlame($owner: String!, $name: String!, $ref: String!, $path: String!) {
|
|
|
791
792
|
login
|
|
792
793
|
}
|
|
793
794
|
body
|
|
794
|
-
${!s||
|
|
795
|
+
${!s||M(s,"PR_REVIEW_FULL_DATABASE_ID")?"fullDatabaseId":"databaseId"}
|
|
795
796
|
id
|
|
796
797
|
publishedAt
|
|
797
798
|
url
|
|
@@ -799,13 +800,13 @@ query getBlame($owner: String!, $name: String!, $ref: String!, $path: String!) {
|
|
|
799
800
|
}
|
|
800
801
|
}
|
|
801
802
|
}
|
|
802
|
-
}`,
|
|
803
|
+
}`,p=await b(this.config,{query:u,variables:{namespace:o,name:i,pullRequestId:a}},t),l=p.body.data?.repository.pullRequest.reviewThreads.nodes?.filter(x).reduce((c,m)=>{if(!m.comments.nodes?.[0]?.pullRequestReview)return c;let g=m.comments.nodes[0].pullRequestReview,h=Tn(m);return h&&(c[g.id]||(c[g.id]=[]),c[g.id].push(h)),c},{})??{};return{data:p.body.data?.repository.pullRequest.reviews.nodes?.filter(x).filter(c=>l[c.id]).map(c=>({author:c.author?{avatarUrl:c.author.avatarUrl,email:null,name:c.author.login}:null,body:c.body,createdAt:c.publishedAt?new Date(c.publishedAt):null,id:c.fullDatabaseId??c.databaseId.toString(),graphQLId:c.id,reviewComments:l[c.id],url:c.url}))??[]}}async getCommentsForPullRequest(e,t={}){let s=await this.getEnterpriseVersion(t),o=!s||M(s,"ISSUE_FULL_DATABASE_ID"),{repo:{namespace:i,name:a},pullRequestNumber:u,cursor:p}=e,l=await b(this.config,{query:Br(o),variables:{namespace:i,name:a,pullRequestNumber:u,cursor:p,first:C}},t),d=l.body.data?.repository;if(!d)throw new I("Could not fetch pull request comments",l.body.errors);return{data:d.pullRequest.comments.nodes?.filter(x).map(_r)??[],pageInfo:d.pullRequest.comments.pageInfo}}async getIssuesAssociatedWithUser(e,t={}){let[s,o]=e.cursor?.split(";")||[void 0,void 0],i=[];e.labelNames&&e.labelNames.forEach(m=>{i.push(`label:"${m}"`)});let[a,u]=await Promise.all([s==="null"?null:this.searchIssues({query:`author:${e.username} ${i.join(" ")}`,cursor:s,includeFromArchivedRepos:e.includeFromArchivedRepos,maxPageSize:e.maxPageSize,states:e.states},t),o==="null"?null:this.searchIssues({query:`assignee:${e.username} ${i.join(" ")}`,cursor:o,includeFromArchivedRepos:e.includeFromArchivedRepos,maxPageSize:e.maxPageSize,states:e.states},t)]),p={},l=[],d=m=>{p[m.id]||(p[m.id]=!0,l.push(m))};a?.data.forEach(d),u?.data.forEach(d);let c=a?.metadata&&u?.metadata?J(Oe(a.metadata.completeness,u.metadata.completeness),[...a.metadata.failures??[],...u.metadata.failures??[]]):a?.metadata??u?.metadata;return{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:l,metadata:c}}async setPullRequestLabels(e,t={}){let{pullRequest:s,labels:o}=e;if(!s.graphQLId)throw new Error('GitHub requires "graphQLId" for this function.');let i=`mutation SetPullRequestLabels($pullRequestGraphQLId: ID!, $labelGraphQLIds: [ID!]) {
|
|
803
804
|
updatePullRequest(input: { pullRequestId: $pullRequestGraphQLId, labelIds: $labelGraphQLIds }) {
|
|
804
805
|
pullRequest {
|
|
805
806
|
id
|
|
806
807
|
}
|
|
807
808
|
}
|
|
808
|
-
}`,a=await b(this.config,{query:i,variables:{pullRequestGraphQLId:s.graphQLId,labelGraphQLIds:o.map(u=>{if(!u.graphQLId)throw new Error('GitHub requires label "graphQLId" for this function.');return u.graphQLId})}},t);if(!a.body.data?.updatePullRequest?.pullRequest?.id)throw new I("Could not set pull request labels",a.body.errors)}async getIssuesForRepos(e,t={}){let s=
|
|
809
|
+
}`,a=await b(this.config,{query:i,variables:{pullRequestGraphQLId:s.graphQLId,labelGraphQLIds:o.map(u=>{if(!u.graphQLId)throw new Error('GitHub requires label "graphQLId" for this function.');return u.graphQLId})}},t);if(!a.body.data?.updatePullRequest?.pullRequest?.id)throw new I("Could not set pull request labels",a.body.errors)}async getIssuesForRepos(e,t={}){let s=Ct(e.startQuery||""),{cursor:o,assigneeLogins:i,updatedBefore:a,authorLogin:u,mentionLogin:p,labelNames:l}=e;return e.repos.forEach(d=>{s.push(`repo:${d.namespace}/${d.name}`)}),i&&i.forEach(d=>{s.push(`assignee:${d}`)}),a&&s.push(`updated:<${a}`),u&&s.push(`author:${u}`),p&&s.push(`mentions:${p}`),l&&l.forEach(d=>{s.push(`label:"${d}"`)}),this.searchIssues({query:`sort:updated ${s.join(" ")}`,cursor:o,includeFromArchivedRepos:e.includeFromArchivedRepos,maxPageSize:e.maxPageSize,states:e.states},t)}async closeIssueWithReason(e,t={}){let{issue:s,reason:o}=e;if(!s.graphQLId)throw new Error('GitHub requires "graphQLId" for this function.');let i=`mutation CloseIssueWithReason($issueGraphQLId: ID!, $reason: IssueClosedStateReason!) {
|
|
809
810
|
closeIssue(input: { issueId: $issueGraphQLId, stateReason: $reason }) {
|
|
810
811
|
issue {
|
|
811
812
|
id
|
|
@@ -823,7 +824,7 @@ query getBlame($owner: String!, $name: String!, $ref: String!, $path: String!) {
|
|
|
823
824
|
id
|
|
824
825
|
}
|
|
825
826
|
}
|
|
826
|
-
}`,i=await b(this.config,{query:o,variables:{issueGraphQLId:s.graphQLId}},t);if(!i.body.data?.reopenIssue?.issue?.id)throw new I("Could not reopen issue",i.body.errors)}async setIssueLabels(e,t={}){let{issue:s,labels:o}=e;if(!s.graphQLId)throw new Error('GitHub requires "graphQLId" for this function.');let i=o.map(
|
|
827
|
+
}`,i=await b(this.config,{query:o,variables:{issueGraphQLId:s.graphQLId}},t);if(!i.body.data?.reopenIssue?.issue?.id)throw new I("Could not reopen issue",i.body.errors)}async setIssueLabels(e,t={}){let{issue:s,labels:o}=e;if(!s.graphQLId)throw new Error('GitHub requires "graphQLId" for this function.');let i=o.map(p=>p.graphQLId),a=`mutation SetIssueLabels($issueGraphQLId: ID!, $labelGraphQLIds: [ID!]) {
|
|
827
828
|
updateIssue(input: { id: $issueGraphQLId, labelIds: $labelGraphQLIds }) {
|
|
828
829
|
issue {
|
|
829
830
|
id
|
|
@@ -835,7 +836,7 @@ query getBlame($owner: String!, $name: String!, $ref: String!, $path: String!) {
|
|
|
835
836
|
id
|
|
836
837
|
}
|
|
837
838
|
}
|
|
838
|
-
}`,a=await b(this.config,{query:`${i}`,variables:{issueGraphQLId:s.graphQLId,milestoneGraphQLId:o?.graphQLId??null}},t);if(!a.body.data?.updateIssue?.issue?.id)throw new I("Could not set milestone of issue",a.body.errors)}async setIssueAssignees(e,t={}){let{issue:s,assignees:o}=e;if(!s.graphQLId)throw new Error('GitHub requires "graphQLId" for this function.');let i=o.map(
|
|
839
|
+
}`,a=await b(this.config,{query:`${i}`,variables:{issueGraphQLId:s.graphQLId,milestoneGraphQLId:o?.graphQLId??null}},t);if(!a.body.data?.updateIssue?.issue?.id)throw new I("Could not set milestone of issue",a.body.errors)}async setIssueAssignees(e,t={}){let{issue:s,assignees:o}=e;if(!s.graphQLId)throw new Error('GitHub requires "graphQLId" for this function.');let i=o.map(p=>{if(!p.graphQLId)throw new Error('GitHub requires assignee "graphQLId" for this function.');return p.graphQLId}),a=`mutation SetIssueAssignees($issueGraphQLId: ID!, $assigneeGraphQLIds: [ID!]!) {
|
|
839
840
|
updateIssue(input: { id: $issueGraphQLId, assigneeIds: $assigneeGraphQLIds }) {
|
|
840
841
|
issue {
|
|
841
842
|
id
|
|
@@ -846,7 +847,7 @@ query getLabelsForRepo($owner: String!, $name: String! $cursor: String, $first:
|
|
|
846
847
|
repository(owner: $owner, name: $name) {
|
|
847
848
|
milestones(first: $first, after: $cursor) {
|
|
848
849
|
nodes {
|
|
849
|
-
${
|
|
850
|
+
${Me}
|
|
850
851
|
}
|
|
851
852
|
pageInfo {
|
|
852
853
|
endCursor
|
|
@@ -855,7 +856,7 @@ query getLabelsForRepo($owner: String!, $name: String! $cursor: String, $first:
|
|
|
855
856
|
}
|
|
856
857
|
}
|
|
857
858
|
}
|
|
858
|
-
`,variables:{owner:s,name:o,cursor:i,first:C}},t);if(!a.body.data)throw new I("Could not fetch milestones",a.body.errors);return{pageInfo:a.body.data.repository.milestones?.pageInfo??{endCursor:null,hasNextPage:!1},data:a.body.data.repository.milestones?.nodes?.map(
|
|
859
|
+
`,variables:{owner:s,name:o,cursor:i,first:C}},t);if(!a.body.data)throw new I("Could not fetch milestones",a.body.errors);return{pageInfo:a.body.data.repository.milestones?.pageInfo??{endCursor:null,hasNextPage:!1},data:a.body.data.repository.milestones?.nodes?.map(Tt)??[]}}async getLabelsForRepo(e,t={}){let{repo:{namespace:s,name:o},cursor:i}=e,a=await b(this.config,{query:`
|
|
859
860
|
query getLabelsForRepo($owner: String!, $name: String! $cursor: String, $first: Int!) {
|
|
860
861
|
repository(owner: $owner, name: $name) {
|
|
861
862
|
labels(first: $first, after: $cursor) {
|
|
@@ -869,7 +870,7 @@ query getLabelsForRepo($owner: String!, $name: String! $cursor: String, $first:
|
|
|
869
870
|
}
|
|
870
871
|
}
|
|
871
872
|
}
|
|
872
|
-
`,variables:{owner:s,name:o,cursor:i,first:C}},t);if(!a.body.data)throw new I("Could not fetch labels",a.body.errors);return{pageInfo:a.body.data.repository.labels?.pageInfo??{endCursor:null,hasNextPage:!1},data:a.body.data.repository.labels?.nodes?.map(
|
|
873
|
+
`,variables:{owner:s,name:o,cursor:i,first:C}},t);if(!a.body.data)throw new I("Could not fetch labels",a.body.errors);return{pageInfo:a.body.data.repository.labels?.pageInfo??{endCursor:null,hasNextPage:!1},data:a.body.data.repository.labels?.nodes?.map(Gt)??[]}}async getTreeForRepo(e,t={}){let s=await this.config.request({url:`${z(this.config,t)}/repos/${e.repo.namespace}/${e.repo.name}/git/trees/${e.branch}?recursive=1`,headers:{...R(t.token||this.config.token)}});if(!s.body)throw new Error("Could not fetch trees");return{data:s.body.tree.map(Dn)}}};var xn="https://gitlab.com/api/v4",kn="https://gitlab.com/api/graphql",Ot=/\/api\/v\d+$/,Wr=r=>{if(r.endsWith("/api/graphql"))throw new Error("The graphql endpoint is being used as the baseUrl. This package uses both GraphQL and REST APIs, and the REST version cannot be assumed. Use the REST endpoint as the baseUrl instead.")},A=(r,n)=>{let e=n.baseUrl||r.baseUrl;return e?(e=e.replace(/\/$/,""),Wr(e),Ot.test(e)||(e=e+"/api/v4"),e):xn},Nn=(r,n)=>{let e=n.baseUrl||r.baseUrl;return e?(e=e.replace(/\/$/,""),Wr(e),Ot.test(e)&&(e=e.replace(Ot,"")),`${e}/api/graphql`):kn},v=(r,n,e)=>{let t=R(e.token||r.token);return r.request({url:Nn(r,e),method:"POST",headers:{...t,"Content-Type":"application/json"},body:JSON.stringify(n)})},$e=r=>r?.map(n=>`"${n.message}"`).join(", ");var Ve=r=>r.split("/").slice(0,-1).join("/"),Ke=r=>r.split("/").at(-1)??"",_t=r=>{let n=parseInt(`${r["x-next-page"]}`,10);return Number.isNaN(n)?{hasNextPage:!1,nextPage:null}:{hasNextPage:!0,nextPage:n}},Je=r=>({id:r.id.replace(de,""),graphQLId:r.id,namespace:Ve(r.fullPath),name:Ke(r.fullPath),webUrl:r.webUrl}),De=r=>({id:r.id.replace(de,""),graphQLId:r.id,httpsUrl:r.httpUrlToRepo,namespace:Ve(r.fullPath),name:Ke(r.fullPath),sshUrl:r.sshUrlToRepo,webUrl:r.webUrl}),Fn={assigned:"assignedMergeRequests",authored:"authoredMergeRequests",reviewRequested:"reviewRequestedMergeRequests"},jn={CAN_BE_MERGED:"MERGEABLE",CANNOT_BE_MERGED:"CONFLICTS",CANNOT_BE_MERGED_RECHECK:"UNKNOWN",UNCHECKED:"UNKNOWN",CHECKING:"UNKNOWN"};var Zr="gid://gitlab/User/",de="gid://gitlab/Project/",Qn="gid://gitlab/MergeRequest/",Yr="gid://gitlab/Issue/",Bn="gid://gitlab/ProjectLabel/",Mn="gid://gitlab/Milestone/",zn="gid://gitlab/Ci::Build/",Ht=`
|
|
873
874
|
description
|
|
874
875
|
dueDate
|
|
875
876
|
id
|
|
@@ -878,7 +879,7 @@ startDate
|
|
|
878
879
|
state
|
|
879
880
|
title
|
|
880
881
|
webPath
|
|
881
|
-
`,
|
|
882
|
+
`,xt=`
|
|
882
883
|
id
|
|
883
884
|
fullPath
|
|
884
885
|
webUrl
|
|
@@ -892,14 +893,14 @@ userPermissions {
|
|
|
892
893
|
downloadCode
|
|
893
894
|
pushCode
|
|
894
895
|
}
|
|
895
|
-
`,
|
|
896
|
+
`,X=`
|
|
896
897
|
id
|
|
897
898
|
name
|
|
898
899
|
username
|
|
899
900
|
publicEmail
|
|
900
901
|
avatarUrl
|
|
901
902
|
webUrl
|
|
902
|
-
`,
|
|
903
|
+
`,Wt=`
|
|
903
904
|
color
|
|
904
905
|
description
|
|
905
906
|
id
|
|
@@ -910,13 +911,13 @@ httpUrlToRepo
|
|
|
910
911
|
fullPath
|
|
911
912
|
sshUrlToRepo
|
|
912
913
|
webUrl
|
|
913
|
-
`,
|
|
914
|
+
`,kt=`
|
|
914
915
|
author {
|
|
915
|
-
${
|
|
916
|
+
${X}
|
|
916
917
|
}
|
|
917
918
|
assignees {
|
|
918
919
|
nodes {
|
|
919
|
-
${
|
|
920
|
+
${X}
|
|
920
921
|
}
|
|
921
922
|
}
|
|
922
923
|
closedAt
|
|
@@ -927,7 +928,7 @@ id
|
|
|
927
928
|
iid
|
|
928
929
|
labels {
|
|
929
930
|
nodes {
|
|
930
|
-
${
|
|
931
|
+
${Wt}
|
|
931
932
|
}
|
|
932
933
|
}
|
|
933
934
|
state
|
|
@@ -938,9 +939,9 @@ upvotes
|
|
|
938
939
|
userNotesCount
|
|
939
940
|
webUrl
|
|
940
941
|
milestone {
|
|
941
|
-
${
|
|
942
|
+
${Ht}
|
|
942
943
|
}
|
|
943
|
-
`,
|
|
944
|
+
`,Hn=`
|
|
944
945
|
stages {
|
|
945
946
|
nodes {
|
|
946
947
|
jobs {
|
|
@@ -956,11 +957,11 @@ stages {
|
|
|
956
957
|
name
|
|
957
958
|
}
|
|
958
959
|
}
|
|
959
|
-
`,
|
|
960
|
+
`,Nt=(r,n,e)=>`
|
|
960
961
|
id
|
|
961
962
|
state
|
|
962
963
|
author {
|
|
963
|
-
${
|
|
964
|
+
${X}
|
|
964
965
|
}
|
|
965
966
|
diffRefs {
|
|
966
967
|
baseSha
|
|
@@ -986,12 +987,12 @@ targetBranch
|
|
|
986
987
|
sourceBranch
|
|
987
988
|
assignees {
|
|
988
989
|
nodes {
|
|
989
|
-
${
|
|
990
|
+
${X}
|
|
990
991
|
}
|
|
991
992
|
}
|
|
992
993
|
reviewers {
|
|
993
994
|
nodes {
|
|
994
|
-
${
|
|
995
|
+
${X}
|
|
995
996
|
mergeRequestInteraction {
|
|
996
997
|
approved
|
|
997
998
|
reviewState
|
|
@@ -1001,25 +1002,25 @@ reviewers {
|
|
|
1001
1002
|
mergeStatusEnum
|
|
1002
1003
|
labels {
|
|
1003
1004
|
nodes {
|
|
1004
|
-
${
|
|
1005
|
+
${Wt}
|
|
1005
1006
|
}
|
|
1006
1007
|
}
|
|
1007
1008
|
${r?`project { ${Le} archived } sourceProject { ${Le} }`:""}
|
|
1008
|
-
${n?`milestone { ${
|
|
1009
|
-
${e?`headPipeline { ${
|
|
1010
|
-
`,_=r=>`${r.namespace}/${r.name}`,
|
|
1009
|
+
${n?`milestone { ${Ht} }`:""}
|
|
1010
|
+
${e?`headPipeline { ${Hn} }`:""}
|
|
1011
|
+
`,_=r=>`${r.namespace}/${r.name}`,Wn=r=>`${r.namespace}/${r.name}`,Jn=r=>/Field '[^']+' (?:doesn'?t|does not) exist on type|Field '[^']+' is not defined|undefined field '[^']+' on type/i.test(r.message),Vn=r=>({canCreateWebhook:r.adminOperations,canPush:r.pushCode,isAdmin:r.adminOperations}),Ft=r=>({id:r.id.replace(de,""),graphQLId:r.id,namespace:Ve(r.fullPath),name:Ke(r.fullPath),webUrl:r.webUrl,httpsUrl:r.httpUrlToRepo,sshUrl:r.sshUrlToRepo,defaultBranch:r.repository?.rootRef?{name:r.repository.rootRef}:null,permissions:Vn(r.userPermissions)}),Kn=r=>({path:r.path,isDirectory:r.type==="tree"}),Xn={opened:"OPEN",merged:"MERGED",closed:"CLOSED"},Zn={OPEN:"opened",MERGED:"merged",CLOSED:"closed"},Jr=r=>{if(!r||r.length===0)return"state: opened";let n=Array.from(new Set(r));return n.length>1?"":`state: ${Zn[n[0]]}`},Vr=r=>{if(!r||r.length===0)return"state: opened";let n=Array.from(new Set(r));return n.length>1?"":`state: ${n[0]==="CLOSED"?"closed":"opened"}`},se=100,Yn=20,eo=250,Xe=(r,n,e)=>!n&&r?.startsWith("/")?`https://gitlab.com${r}`:n&&r?.startsWith("/")&&e?`${e.replace(/\/+?$/,"")}${r}`:r,Z=(r,n,e)=>{let t=Xe(r.avatarUrl,n,e);return{id:r.id.replace(Zr,""),graphQLId:r.id,name:r.name,username:r.username,email:r.publicEmail??null,avatarUrl:t,url:r.webUrl}},Jt=r=>({color:r.color,description:r.description,id:r.id.replace(Bn,""),graphQLId:r.id,name:r.title}),to=(r,n)=>r?r==="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"}[r]:null,ro=(r,n,e)=>{let t={APPROVED:"APPROVED",REQUESTED_CHANGES:"CHANGES_REQUESTED",REVIEWED:"COMMENTED",UNAPPROVED:"REVIEW_REQUESTED",UNREVIEWED:"REVIEW_REQUESTED"};return{reviewer:Z(r,n,e),state:r.mergeRequestInteraction?.reviewState?t[r.mergeRequestInteraction.reviewState]:"REVIEW_REQUESTED"}},jt=(r,n,e,t,s)=>{let o=r.reviewers?.nodes?r.reviewers.nodes.map(i=>ro(i,t,s)):null;return{id:r.id.replace(Qn,""),graphQLId:r.id,title:r.title,description:r.description,number:parseInt(r.iid,10),state:Xn[r.state],commentCount:r.userNotesCount||0,upvoteCount:r.upvotes,author:r.author?Z(r.author,t,s):null,createdDate:new Date(r.createdAt),isDraft:r.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},isCrossRepository:e!=null&&e.id!==n.id,headRepository:e?{id:e.id,graphQLId:e.graphQLId,name:e.name,owner:{login:e.namespace},remoteInfo:{cloneUrlHTTPS:e.httpsUrl,cloneUrlSSH:e.sshUrl}}:null,headCommit:{buildStatuses:r.headPipeline?.stages?.nodes?.flatMap(i=>i.jobs?.nodes?.map(a=>({completedAt:a.finishedAt?new Date(a.finishedAt):null,description:null,name:a.name??null,state:to(a.status,a.allowFailure),stage:i.name??null,startedAt:new Date(a.createdAt),url:`${n.webUrl}/-/jobs/${a.id.replace(zn,"")}`}))??[])??[]},baseRef:{name:r.targetBranch,oid:r.diffRefs?.baseSha??null},headRef:{name:r.sourceBranch,oid:r.diffRefs?.headSha??null},url:r.webUrl,updatedDate:new Date(r.updatedAt),closedDate:r.mergedAt?new Date(r.mergedAt):null,mergedDate:r.mergedAt?new Date(r.mergedAt):null,assignees:r.assignees?.nodes?r.assignees.nodes.map(i=>Z(i,t,s)):null,reviews:o,reviewDecision:B(o),additions:r.diffStatsSummary?.additions||0,deletions:r.diffStatsSummary?.deletions||0,fileCount:r.diffStatsSummary?.fileCount||0,commitCount:r.commitCount||0,mergeableState:jn[r.mergeStatusEnum],milestone:r.milestone?Vt(r.milestone,n.webUrl):null,labels:r.labels?.nodes?.map(Jt)??[],permissions:null}},Qt=(r,n,e,t)=>({author:Z(r.author,e,t),assignees:r.assignees.nodes.map(s=>Z(s,e,t)),commentCount:r.userNotesCount,closedDate:r.closedAt?new Date(r.closedAt):null,createdDate:new Date(r.createdAt),description:r.description,graphQLId:r.id,id:r.id.replace(Yr,""),labels:r.labels?.nodes?.map(Jt)??[],number:r.iid,repository:{id:n.id.replace(de,""),graphQLId:n.id,name:n.name,owner:{login:n.namespace}},updatedDate:new Date(r.updatedAt),upvoteCount:r.upvotes,state:{name:r.state,color:null},type:r.type,title:r.title,url:r.webUrl,milestone:r.milestone?Vt(r.milestone,n.webUrl):null}),Vt=(r,n)=>({id:r.id.replace(Mn,""),graphQLId:r.id,number:parseInt(r.iid,10),title:r.title,description:r.description,isOpen:r.state==="active",url:`${n}/-/${r.webPath.replace(/.+?\/-\//,"")}`,startDate:r.startDate?new Date(r.startDate):null,dueDate:r.dueDate?new Date(r.dueDate):null}),so=r=>Buffer.from(JSON.stringify(r),"utf8").toString("base64"),no=(r,n)=>{if(!r)return{page:1,perPage:n};try{let e=JSON.parse(Buffer.from(r,"base64").toString("utf8")),t=typeof e.page=="number"&&e.page>0?e.page:1,s=typeof e.perPage=="number"&&e.perPage>0?e.perPage:n;return{page:t,perPage:s}}catch{return{page:1,perPage:n}}},Mt=(r,n,e)=>({id:r.id.toString(),graphQLId:`${Zr}${r.id}`,name:r.name,username:r.username,email:r.email??null,avatarUrl:Xe(r.avatar_url,n,e),url:r.web_url}),Kr=(r,n,e)=>({avatarUrl:Xe(r.avatar_url,n,e)??"",email:null,name:r.name}),Xr=r=>r.replace(/^\/+/,"").split("/")[0]==="groups",oo=r=>{let n=r.references?.full;if(n){let t=n.includes("#")?n.slice(0,n.lastIndexOf("#")):n;if(t&&!Xr(t))return t}let e="/-/issues";try{let{pathname:t}=new URL(r.web_url),s=t.indexOf(e);if(s===-1)return;let o=t.slice(0,s).replace(/^\/+/,"");return!o||Xr(o)?void 0:o}catch{return}},io=(r,n,e)=>{let t=oo(r);return{author:r.author?Mt(r.author,n,e):null,assignees:(r.assignees??[]).map(s=>Mt(s,n,e)),commentCount:r.user_notes_count,closedDate:r.closed_at?new Date(r.closed_at):null,createdDate:new Date(r.created_at),description:r.description,graphQLId:`${Yr}${r.id}`,id:r.id.toString(),labels:(r.labels??[]).map(s=>({color:null,description:null,id:null,name:s})),number:r.iid.toString(),repository:{graphQLId:`${de}${r.project_id}`,id:r.project_id.toString(),name:t?Ke(t):"",owner:{login:t?Ve(t):void 0}},updatedDate:new Date(r.updated_at),upvoteCount:r.upvotes,state:{name:r.state,color:null},type:null,title:r.title,url:r.web_url}},ao=r=>r?.new_line!=null?"RIGHT":r?.old_line!=null?"LEFT":null,uo=r=>{let n=r.old_path||r.new_path,e=r.new_path||r.old_path,t=[`diff --git a/${n} b/${e}`];return r.new_file&&r.b_mode?t.push(`new file mode ${r.b_mode}`):r.deleted_file&&r.a_mode?t.push(`deleted file mode ${r.a_mode}`):r.a_mode&&r.b_mode&&r.a_mode!==r.b_mode&&(t.push(`old mode ${r.a_mode}`),t.push(`new mode ${r.b_mode}`)),r.renamed_file&&(t.push(`rename from ${r.old_path}`),t.push(`rename to ${r.new_path}`)),r.diff&&r.diff.length>0?(t.push(`--- ${r.new_file?"/dev/null":`a/${n}`}`),t.push(`+++ ${r.deleted_file?"/dev/null":`b/${e}`}`),`${t.join(`
|
|
1011
1012
|
`)}
|
|
1012
1013
|
${r.diff.endsWith(`
|
|
1013
1014
|
`)?r.diff:`${r.diff}
|
|
1014
1015
|
`}`):`${t.join(`
|
|
1015
1016
|
`)}
|
|
1016
|
-
`},
|
|
1017
|
+
`},es="|",zt=(r,n,e,t)=>[r,n,e.toString(),t.toString()].join(es),lo=r=>{let n=r.split(es);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]}},Bt=(r,n,e,t)=>({author:r.author?Mt(r.author,n,e):null,body:r.body,createdAt:r.created_at?new Date(r.created_at):null,id:zt(t.namespace,t.name,t.mergeRequestIid,r.id),url:""}),ye=class extends N{getIsSelfHosted(n){return!!n.baseUrl||!!this.config.baseUrl}async getCurrentUser(n={},e={}){let s=(await v(this.config,{query:`
|
|
1017
1018
|
query getCurrentUser {
|
|
1018
1019
|
currentUser {
|
|
1019
|
-
${
|
|
1020
|
+
${X}
|
|
1020
1021
|
}
|
|
1021
1022
|
}
|
|
1022
|
-
`},e)).body.data?.currentUser;if(!s)throw new Error("Current user not found.");return{data:
|
|
1023
|
+
`},e)).body.data?.currentUser;if(!s)throw new Error("Current user not found.");return{data:Z(s,this.getIsSelfHosted(e),this.config.baseUrl??e.baseUrl)}}async getUserForCommit(n,e={}){let t=_(n.repo),o=(await v(this.config,{query:`
|
|
1023
1024
|
query getUserForCommit($fullPath: ID!, $oid: String!) {
|
|
1024
1025
|
project(fullPath: $fullPath) {
|
|
1025
1026
|
repository {
|
|
@@ -1035,21 +1036,21 @@ query getUserForCommit($fullPath: ID!, $oid: String!) {
|
|
|
1035
1036
|
}
|
|
1036
1037
|
}
|
|
1037
1038
|
}
|
|
1038
|
-
`,variables:{fullPath:t,oid:n.oid}},e)).body.data?.project?.repository?.tree?.lastCommit;if(!o)throw new Error("Commit not found.");let i=
|
|
1039
|
+
`,variables:{fullPath:t,oid:n.oid}},e)).body.data?.project?.repository?.tree?.lastCommit;if(!o)throw new Error("Commit not found.");let i=Xe(o.author.avatarUrl,this.getIsSelfHosted(e),this.config.baseUrl??e.baseUrl);return{data:{name:o.authorName,email:o.authorEmail,avatarUrl:i}}}async getAccountForEmail(n,e={}){let s=(await v(this.config,{query:`
|
|
1039
1040
|
query getAccountForEmail($email: String!) {
|
|
1040
1041
|
users(search: $email) {
|
|
1041
1042
|
nodes {
|
|
1042
|
-
${
|
|
1043
|
+
${X}
|
|
1043
1044
|
}
|
|
1044
1045
|
}
|
|
1045
1046
|
}
|
|
1046
|
-
`,variables:{email:n.email}},e)).body.data?.users?.nodes?.[0];if(!s)throw new Error("User not found.");return{data:
|
|
1047
|
+
`,variables:{email:n.email}},e)).body.data?.users?.nodes?.[0];if(!s)throw new Error("User not found.");return{data:Z(s,this.getIsSelfHosted(e),this.config.baseUrl??e.baseUrl)}}async getAccountForUsername(n,e={}){let s=(await v(this.config,{query:`
|
|
1047
1048
|
query getAccountForUsername($username: String!) {
|
|
1048
1049
|
user(username: $username) {
|
|
1049
|
-
${
|
|
1050
|
+
${X}
|
|
1050
1051
|
}
|
|
1051
1052
|
}
|
|
1052
|
-
`,variables:{username:n.username}},e)).body.data?.user;if(!s)throw new Error("User not found.");return{data:
|
|
1053
|
+
`,variables:{username:n.username}},e)).body.data?.user;if(!s)throw new Error("User not found.");return{data:Z(s,this.getIsSelfHosted(e),this.config.baseUrl??e.baseUrl)}}async getAccountsForRepo(n,e={}){let{repo:{namespace:t,name:s},cursor:o}=n,i=await v(this.config,{query:`
|
|
1053
1054
|
query getAccountsForRepo(
|
|
1054
1055
|
$fullPath: ID!
|
|
1055
1056
|
$after: String
|
|
@@ -1060,7 +1061,7 @@ query getAccountsForRepo(
|
|
|
1060
1061
|
projectMembers(after: $after) {
|
|
1061
1062
|
nodes {
|
|
1062
1063
|
user {
|
|
1063
|
-
${
|
|
1064
|
+
${X}
|
|
1064
1065
|
}
|
|
1065
1066
|
}
|
|
1066
1067
|
pageInfo {
|
|
@@ -1070,22 +1071,22 @@ query getAccountsForRepo(
|
|
|
1070
1071
|
}
|
|
1071
1072
|
}
|
|
1072
1073
|
}
|
|
1073
|
-
`,variables:{fullPath:`${t}/${s}`,after:o}},e),a=i.body.data?.project?.projectMembers?.nodes?.map(u=>u.user).filter(u=>u!==null);return{pageInfo:i.body.data?.project?.projectMembers?.pageInfo??{endCursor:null,hasNextPage:!1},data:a?.map(u=>
|
|
1074
|
+
`,variables:{fullPath:`${t}/${s}`,after:o}},e),a=i.body.data?.project?.projectMembers?.nodes?.map(u=>u.user).filter(u=>u!==null);return{pageInfo:i.body.data?.project?.projectMembers?.pageInfo??{endCursor:null,hasNextPage:!1},data:a?.map(u=>Z(u,this.getIsSelfHosted(e),this.config.baseUrl??e.baseUrl))??[]}}async getRepo(n,e={}){let t=_(n),s=await v(this.config,{query:`
|
|
1074
1075
|
query getRepo($fullPath: ID!) {
|
|
1075
1076
|
project(fullPath: $fullPath) {
|
|
1076
|
-
${
|
|
1077
|
+
${xt}
|
|
1077
1078
|
}
|
|
1078
1079
|
}
|
|
1079
|
-
`,variables:{fullPath:t}},e);if(!s.body.data?.project)throw new Error(`Repository ${t} not found`);return{data:
|
|
1080
|
-
getRepo_${
|
|
1081
|
-
${
|
|
1080
|
+
`,variables:{fullPath:t}},e);if(!s.body.data?.project)throw new Error(`Repository ${t} not found`);return{data:Ft(s.body.data.project)}}async getReposBase(n,e={}){let s=n.map(_).map((u,p)=>`
|
|
1081
|
+
getRepo_${p}: project(fullPath: "${u}") {
|
|
1082
|
+
${xt}
|
|
1082
1083
|
}
|
|
1083
1084
|
`).join(`
|
|
1084
1085
|
`),o=await v(this.config,{query:`
|
|
1085
1086
|
query batchGetRepos {
|
|
1086
1087
|
${s}
|
|
1087
1088
|
}
|
|
1088
|
-
`},e);if(!o.body.data)throw new Error($e(o.body.errors)||o.statusText||"Unknown error");let i=[],a=[];return n.forEach((u,
|
|
1089
|
+
`},e);if(!o.body.data)throw new Error($e(o.body.errors)||o.statusText||"Unknown error");let i=[],a=[];return n.forEach((u,p)=>{let l=o.body.data[`getRepo_${p}`];l?i.push(Ft(l)):a.push({input:u})}),{data:i,errors:a}}async getRepos(n,e={}){let t=[];for(let i=0;i<n.length;i+=15)t.push(n.slice(i,i+15));return(await Promise.all(t.map(i=>this.getReposBase(i,e)))).reduce((i,a)=>({data:[...i.data,...a.data],errors:[...i.errors,...a.errors]}),{data:[],errors:[]})}async getReposForCurrentUser(n,e={}){let t=await v(this.config,{query:`
|
|
1089
1090
|
query getReposForCurrentUser($after: String) {
|
|
1090
1091
|
projects(membership: true first: 100 after: $after) {
|
|
1091
1092
|
pageInfo {
|
|
@@ -1093,11 +1094,11 @@ query getReposForCurrentUser($after: String) {
|
|
|
1093
1094
|
hasNextPage
|
|
1094
1095
|
}
|
|
1095
1096
|
nodes {
|
|
1096
|
-
${
|
|
1097
|
+
${xt}
|
|
1097
1098
|
}
|
|
1098
1099
|
}
|
|
1099
1100
|
}
|
|
1100
|
-
`,variables:{after:n.cursor}},e);if(!t.body.data?.projects)throw new Error($e(t.body.errors)||t.statusText||"Unknown error");let s=t.body.data?.projects?.nodes||[];return{pageInfo:t.body.data?.projects?.pageInfo,data:s.map(
|
|
1101
|
+
`,variables:{after:n.cursor}},e);if(!t.body.data?.projects)throw new Error($e(t.body.errors)||t.statusText||"Unknown error");let s=t.body.data?.projects?.nodes||[];return{pageInfo:t.body.data?.projects?.pageInfo,data:s.map(Ft)}}async getGroupsForCurrentUser(n={},e={}){let t=new URL(`${A(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",C.toString());let s=await this.config.request({url:t.toString(),headers:R(e.token||this.config.token)});return{pageInfo:_t(s.headers),data:s.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 s=_(e.repo),o=new URL(`${A(this.config,t)}/projects/${encodeURIComponent(s)}/repository/${n}`);o.searchParams.set("page",e.page?.toString()||"1"),o.searchParams.set("per_page",C.toString());let i=await this.config.request({url:o.toString(),headers:R(t.token||this.config.token)});return{pageInfo:_t(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=_(n.repo),s=new URL(`${A(this.config,e)}/projects/${encodeURIComponent(t)}/repository/files/${encodeURIComponent(n.path)}/blame`);s.searchParams.set("ref",n.ref);let o=await this.config.request({url:s.toString(),headers:R(e.token||this.config.token)}),i=0;return{data:{ranges:o.body.map(a=>{let u=i+1;return i+=a.lines.length,{startingLine:u,endingLine:i,commit:{oid:a.commit.id,parentOids:a.commit.parent_ids,authoredDate:new Date(a.commit.authored_date),author:{name:a.commit.author_name,email:a.commit.author_email,avatarUrl:null},committedDate:new Date(a.commit.committed_date),committer:{name:a.commit.committer_name,email:a.commit.committer_email,avatarUrl:null},message:a.commit.message,fileCount:null,additions:null,deletions:null}}})}}}async getPullRequestsForUser(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 s=Fn[n.association],o=Jr(n.states),i=$(n.pageSize,{fallback:se,max:se}),a=await v(this.config,{query:`
|
|
1101
1102
|
query getPullRequestsForUser($username: String! $cursor: String $labelNames: [String!]) {
|
|
1102
1103
|
user(username: $username) {
|
|
1103
1104
|
${s}(${o} first: ${i} after:$cursor labels: $labelNames${t?` ${t}`:""}) {
|
|
@@ -1106,16 +1107,16 @@ query getPullRequestsForUser($username: String! $cursor: String $labelNames: [St
|
|
|
1106
1107
|
hasNextPage
|
|
1107
1108
|
}
|
|
1108
1109
|
nodes {
|
|
1109
|
-
${
|
|
1110
|
+
${Nt(!0,!0,!0)}
|
|
1110
1111
|
}
|
|
1111
1112
|
}
|
|
1112
1113
|
}
|
|
1113
1114
|
}
|
|
1114
|
-
`,variables:{username:n.username,cursor:n.cursor,labelNames:n.labelNames}},e);if(!a.body.data)throw new Error($e(a.body.errors)||a.statusText||"Unknown error");if(!a.body.data.user)throw new Error("User not found");let u=a.body.data.user[s];if(!u)throw new Error("Unexpected response");let
|
|
1115
|
+
`,variables:{username:n.username,cursor:n.cursor,labelNames:n.labelNames}},e);if(!a.body.data)throw new Error($e(a.body.errors)||a.statusText||"Unknown error");if(!a.body.data.user)throw new Error("User not found");let u=a.body.data.user[s];if(!u)throw new Error("Unexpected response");let p=u.nodes?.filter(l=>n.includeFromArchivedRepos||!l.project.archived).map(l=>jt(l,De(l.project),l.sourceProject?De(l.sourceProject):null,this.getIsSelfHosted(e),this.config.baseUrl??e.baseUrl))||[];return{pageInfo:u.pageInfo,data:k(p,n.states)}}async getPullRequestsAssociatedWithUser(n,e={}){let[t,s,o]=n.cursor?.split(";")||[void 0,void 0,void 0],i=t?.split("-")||[],a=s?.split("-")||[],u=o?.split("-")||[],p=[],l=[],d=[],c=0;do{let L=n.repos&&n.repos[c];i[c]==="null"?p.push(null):p.push(this.getPullRequestsForUser({username:n.username,association:"authored",cursor:i[c],includeFromArchivedRepos:n.includeFromArchivedRepos,labelNames:n.labelNames,states:n.states,...L&&{repo:L}},e)),a[c]==="null"?l.push(null):l.push(this.getPullRequestsForUser({username:n.username,association:"assigned",cursor:a[c],includeFromArchivedRepos:n.includeFromArchivedRepos,labelNames:n.labelNames,states:n.states,...L&&{repo:L}},e)),u[c]==="null"?d.push(null):d.push(this.getPullRequestsForUser({username:n.username,association:"reviewRequested",cursor:u[c],includeFromArchivedRepos:n.includeFromArchivedRepos,labelNames:n.labelNames,states:n.states,...L&&{repo:L}},e)),c++}while(c<(n.repos?.length||0));let m=[p,l,d].flat(),g=await Promise.all(m),h={},y=[],f=L=>{h[L.id]||(h[L.id]=!0,y.push(L))},P=!1,U=g.map((L,w)=>{let E="";return L&&L.data.forEach(f),L?.pageInfo.hasNextPage?(P=!0,E+=`${L.pageInfo.endCursor||"null"}`):E+="null",n.repos?.length&&(w+1)%n.repos.length!==0?E+="-":w+1<g.length&&(E+=";"),E}).join("");return{pageInfo:{hasNextPage:P,endCursor:U},data:y}}getVariablesForPullRequests(n){let{updatedBefore:e,isDraft:t,authorLogin:s,assigneeLogins:o,labelNames:i,reviewRequestedLogin:a}=n||{},u={},p=[],l=[],d=(c,m,g)=>{p.push(`$${c}: ${g}`),l.push(`${c}: $${c}`),u[c]=m};return e&&d("updatedBefore",e,"Time"),s&&d("authorUsername",s,"String"),o&&o.length&&(o.length===1?d("assigneeUsername",o[0],"String"):d("assigneeUsernames",o,"[String!]")),i&&d("labelName",i,"[String]"),t!=null&&d("draft",t,"Boolean"),a&&d("reviewerUsername",a,"String"),{variables:u,variableTypes:p,mergeRequestArguments:l}}async getPullRequestsForRepoBase(n,e={},t){let{cursor:s,repo:o}=n||{},i=_(o),a=Jr(n.states),u=$(n.pageSize,{fallback:se,max:se}),{variables:p,variableTypes:l,mergeRequestArguments:d}=this.getVariablesForPullRequests(n),c={fullPath:i,...p},m=await v(this.config,{query:`
|
|
1115
1116
|
query getPullRequestsForRepo(
|
|
1116
1117
|
$fullPath: ID!
|
|
1117
1118
|
$after: String
|
|
1118
|
-
${
|
|
1119
|
+
${l.length?l.join(" "):""}
|
|
1119
1120
|
) {
|
|
1120
1121
|
project(
|
|
1121
1122
|
fullPath: $fullPath
|
|
@@ -1136,7 +1137,7 @@ query getPullRequestsForRepo(
|
|
|
1136
1137
|
hasNextPage
|
|
1137
1138
|
}
|
|
1138
1139
|
nodes {
|
|
1139
|
-
${
|
|
1140
|
+
${Nt(!1,!0,!0)}
|
|
1140
1141
|
sourceProject {
|
|
1141
1142
|
${Le}
|
|
1142
1143
|
}
|
|
@@ -1144,7 +1145,7 @@ query getPullRequestsForRepo(
|
|
|
1144
1145
|
}
|
|
1145
1146
|
}
|
|
1146
1147
|
}
|
|
1147
|
-
`,variables:{...c,after:s}},e),
|
|
1148
|
+
`,variables:{...c,after:s}},e),g=[],h=m.body.data?.project;if(!t&&h?.archived)return{pageInfo:null,data:[]};let y=Je(h||{id:"",fullPath:"",webUrl:""});return(h?.mergeRequests?.nodes||[]).forEach(P=>{let q=P.sourceProject?De(P.sourceProject):null;g.push(jt(P,y,q,this.getIsSelfHosted(e),this.config.baseUrl??e.baseUrl))}),{pageInfo:h?.mergeRequests?.pageInfo,data:k(g,n.states)}}async getPullRequestsForRepo(n,e={}){return this.getPullRequestsForRepoBase(n,e,!1)}async getPullRequestsForRepos(n,e={}){let{repos:t,assigneeLogins:s,updatedBefore:o,authorLogin:i,labelNames:a,isDraft:u,reviewRequestedLogin:p}=n;return{data:(await Promise.all(t.map(d=>this.getPullRequestsForRepoBase({repo:d,assigneeLogins:s,updatedBefore:o,authorLogin:i,labelNames:a,isDraft:u,reviewRequestedLogin:p,states:n.states,pageSize:n.pageSize},e,n.includeFromArchivedRepos??!1)))).flatMap(d=>d.data)}}async closePullRequest(n,e={}){let{pullRequest:t}=n,s=`mutation ClosePullRequest($fullPath: ID!, $pullRequestId: String!) {
|
|
1148
1149
|
mergeRequestUpdate(input: { projectPath: $fullPath, iid: $pullRequestId, state: CLOSED }) {
|
|
1149
1150
|
errors,
|
|
1150
1151
|
mergeRequest {
|
|
@@ -1182,7 +1183,7 @@ query getPullRequestsForRepo(
|
|
|
1182
1183
|
id
|
|
1183
1184
|
}
|
|
1184
1185
|
}
|
|
1185
|
-
}`,a=(await v(this.config,{query:o,variables:{fullPath:`${t.repository.owner.login}/${t.repository.name}`,pullRequestId:t.number.toString(),isDraft:s}},e)).body.data?.mergeRequestSetDraft;if(!a?.mergeRequest?.id||a?.errors?.length!==0)throw new Error("Could not set pull request as draft")}async setPullRequestReviewers(n,e={}){let{pullRequest:t,reviewers:s}=n,o=s.map(
|
|
1186
|
+
}`,a=(await v(this.config,{query:o,variables:{fullPath:`${t.repository.owner.login}/${t.repository.name}`,pullRequestId:t.number.toString(),isDraft:s}},e)).body.data?.mergeRequestSetDraft;if(!a?.mergeRequest?.id||a?.errors?.length!==0)throw new Error("Could not set pull request as draft")}async setPullRequestReviewers(n,e={}){let{pullRequest:t,reviewers:s}=n,o=s.map(p=>{if(!p.username)throw new Error('GitLab requires reviewer "username" for this function.');return p.username}),i=`mutation MergeRequestSetReviewers($fullPath: ID!, $pullRequestId: String!, $reviewerUsernames: [String!]!) {
|
|
1186
1187
|
mergeRequestSetReviewers(input: { projectPath: $fullPath, iid: $pullRequestId, reviewerUsernames: $reviewerUsernames }) {
|
|
1187
1188
|
errors,
|
|
1188
1189
|
mergeRequest {
|
|
@@ -1196,7 +1197,7 @@ query getPullRequestsForRepo(
|
|
|
1196
1197
|
id
|
|
1197
1198
|
}
|
|
1198
1199
|
}
|
|
1199
|
-
}`,a=(await v(this.config,{query:o,variables:{fullPath:`${t.repository.owner.login}/${t.repository.name}`,pullRequestId:t.number.toString(),reviewerUserId:s.graphQLId}},e)).body.data?.mergeRequestReviewerRereview;if(!a?.mergeRequest?.id||a?.errors?.length!==0)throw new Error("Could not set pull request reviewers")}async reRequestPullRequestReviews(n,e={}){let{pullRequest:t,reviewers:s}=n,o=t.reviews;if(!o)throw new Error('GitLab requires "reviews" for this function.');let i=s.filter(a=>o.find(u=>u.reviewer.graphQLId===a.graphQLId));await Promise.all(i.map(a=>this.reRequestPullRequestReview({pullRequest:t,reviewer:a},e)))}async setPullRequestAssignees(n,e={}){let{pullRequest:t,assignees:s}=n,o=s.map(
|
|
1200
|
+
}`,a=(await v(this.config,{query:o,variables:{fullPath:`${t.repository.owner.login}/${t.repository.name}`,pullRequestId:t.number.toString(),reviewerUserId:s.graphQLId}},e)).body.data?.mergeRequestReviewerRereview;if(!a?.mergeRequest?.id||a?.errors?.length!==0)throw new Error("Could not set pull request reviewers")}async reRequestPullRequestReviews(n,e={}){let{pullRequest:t,reviewers:s}=n,o=t.reviews;if(!o)throw new Error('GitLab requires "reviews" for this function.');let i=s.filter(a=>o.find(u=>u.reviewer.graphQLId===a.graphQLId));await Promise.all(i.map(a=>this.reRequestPullRequestReview({pullRequest:t,reviewer:a},e)))}async setPullRequestAssignees(n,e={}){let{pullRequest:t,assignees:s}=n,o=s.map(p=>{if(!p.username)throw new Error('GitLab requires assignee "username" for this function.');return p.username}),i=`mutation MergeRequestSetAssignees($fullPath: ID!, $pullRequestId: String!, $assigneeUsernames: [String!]!) {
|
|
1200
1201
|
mergeRequestSetAssignees(input: { projectPath: $fullPath, iid: $pullRequestId, assigneeUsernames: $assigneeUsernames }) {
|
|
1201
1202
|
errors,
|
|
1202
1203
|
mergeRequest {
|
|
@@ -1209,22 +1210,22 @@ query getPullRequestsForRepo(
|
|
|
1209
1210
|
id
|
|
1210
1211
|
}
|
|
1211
1212
|
}
|
|
1212
|
-
}`;if(!(await v(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=
|
|
1213
|
+
}`;if(!(await v(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=Wn(n),s=await v(this.config,{query:`
|
|
1213
1214
|
query GetSingleIssue($projectId: ID!, $issueNumber: String!) {
|
|
1214
1215
|
project(fullPath: $projectId) {
|
|
1215
1216
|
id
|
|
1216
1217
|
fullPath
|
|
1217
1218
|
webUrl
|
|
1218
1219
|
issue(iid: $issueNumber) {
|
|
1219
|
-
${
|
|
1220
|
+
${kt}
|
|
1220
1221
|
}
|
|
1221
1222
|
}
|
|
1222
1223
|
}
|
|
1223
|
-
`,variables:{issueNumber:n.number,projectId:t}},e);if(!s.body.data?.project)throw new Error(`Repository ${t} not found`);if(!s.body.data?.project?.issue)throw new Error(`Issue ${n.number} not found`);return{data:
|
|
1224
|
+
`,variables:{issueNumber:n.number,projectId:t}},e);if(!s.body.data?.project)throw new Error(`Repository ${t} not found`);if(!s.body.data?.project?.issue)throw new Error(`Issue ${n.number} not found`);return{data:Qt(s.body.data.project.issue,Je(s.body.data.project),this.getIsSelfHosted(e),this.config.baseUrl??e.baseUrl)}}getVariablesForIssues(n){let{updatedBefore:e,authorLogin:t,assigneeLogins:s,labelNames:o}=n||{},i={},a=[],u=[],p=(l,d,c)=>{a.push(`$${l}: ${c}`),u.push(`${l}: $${l}`),i[l]=d};return e&&p("updatedBefore",e,"Time"),t&&p("authorUsername",t,"String"),s&&s.length&&(s.length===1?p("assigneeUsername",s[0],"String"):p("assigneeUsernames",s,"[String!]")),o&&p("labelName",o,"[String]"),{variables:i,variableTypes:a,issueArguments:u}}async getIssuesForRepo(n,e={}){let{cursor:t,repo:s}=n||{},o=_(s),i=Vr(n.states),a=$(n.pageSize,{fallback:se,max:se}),{variables:u,variableTypes:p,issueArguments:l}=this.getVariablesForIssues(n),d={fullPath:o,...u},c=`
|
|
1224
1225
|
query GetIssuesFromProject(
|
|
1225
1226
|
$fullPath: ID!
|
|
1226
1227
|
$after: String
|
|
1227
|
-
${
|
|
1228
|
+
${p.length?p.join(" "):""}
|
|
1228
1229
|
) {
|
|
1229
1230
|
project(
|
|
1230
1231
|
fullPath: $fullPath
|
|
@@ -1237,10 +1238,10 @@ query GetSingleIssue($projectId: ID!, $issueNumber: String!) {
|
|
|
1237
1238
|
${i}
|
|
1238
1239
|
sort: UPDATED_DESC
|
|
1239
1240
|
after: $after
|
|
1240
|
-
${
|
|
1241
|
+
${l.length?l.join(" "):""}
|
|
1241
1242
|
) {
|
|
1242
1243
|
nodes {
|
|
1243
|
-
${
|
|
1244
|
+
${kt}
|
|
1244
1245
|
}
|
|
1245
1246
|
pageInfo {
|
|
1246
1247
|
endCursor
|
|
@@ -1248,7 +1249,7 @@ query GetSingleIssue($projectId: ID!, $issueNumber: String!) {
|
|
|
1248
1249
|
}
|
|
1249
1250
|
}
|
|
1250
1251
|
}
|
|
1251
|
-
}`,
|
|
1252
|
+
}`,m=await v(this.config,{query:c,variables:{...d,after:t}},e),g=[],h=m.body.data?.project,y=Je(h||{id:"",fullPath:"",webUrl:""});return(h?.issues?.nodes||[]).forEach(P=>{g.push(Qt(P,y,this.getIsSelfHosted(e),this.config.baseUrl??e.baseUrl))}),{pageInfo:h?.issues?.pageInfo??{endCursor:null,hasNextPage:!1},data:g.sort((P,q)=>(P.updatedDate||P.createdDate).getTime()-(q.updatedDate||q.createdDate).getTime())}}async getIssuesForRepos(n,e={}){let{cursor:t}=n||{},s=Vr(n.states),o=$(n.pageSize,{fallback:se,max:se}),i=n.repoIds.map(h=>h.toString().startsWith(de)?h:`${de}${h}`),{variables:a,variableTypes:u,issueArguments:p}=this.getVariablesForIssues(n),l={projectIds:i,...a},d=`
|
|
1252
1253
|
query GetIssuesFromProject(
|
|
1253
1254
|
$projectIds: [ID!]
|
|
1254
1255
|
$after: String
|
|
@@ -1271,15 +1272,15 @@ query GetSingleIssue($projectId: ID!, $issueNumber: String!) {
|
|
|
1271
1272
|
first: ${o}
|
|
1272
1273
|
${s}
|
|
1273
1274
|
sort: UPDATED_DESC
|
|
1274
|
-
${
|
|
1275
|
+
${p.length?p.join(" "):""}
|
|
1275
1276
|
) {
|
|
1276
1277
|
nodes {
|
|
1277
|
-
${
|
|
1278
|
+
${kt}
|
|
1278
1279
|
}
|
|
1279
1280
|
}
|
|
1280
1281
|
}
|
|
1281
1282
|
}
|
|
1282
|
-
}`,c=await v(this.config,{query:d,variables:{...
|
|
1283
|
+
}`,c=await v(this.config,{query:d,variables:{...l,after:t}},e),m=[];return(c.body.data?.projects?.nodes||[]).forEach(h=>{if(!n.includeFromArchivedRepos&&h.archived)return;let y=Je(h);(h.issues?.nodes||[]).forEach(P=>m.push(Qt(P,y,this.getIsSelfHosted(e),this.config.baseUrl??e.baseUrl)))}),{pageInfo:c.body?.data?.projects?.pageInfo??{endCursor:null,hasNextPage:!1},data:m.sort((h,y)=>(h.updatedDate||h.createdDate).getTime()-(y.updatedDate||y.createdDate).getTime())}}async getIssuesForCurrentUser(n={},e={}){let t=n.scope??"assigned_to_me",{assigneeUsername:s,authorUsername:o}=n,i=n.page?.toString()||"1",a=$(n.pageSize,{fallback:C,max:C}),u=new URL(`${A(this.config,e)}/issues`);u.searchParams.set("scope",t),u.searchParams.set("state","opened"),s&&u.searchParams.set("assignee_username",s),o&&u.searchParams.set("author_username",o),u.searchParams.set("page",i),u.searchParams.set("per_page",a.toString());let p=await this.config.request({url:u.toString(),headers:R(e.token||this.config.token)});return{pageInfo:_t(p.headers),data:p.body.map(l=>io(l,this.getIsSelfHosted(e),this.config.baseUrl??e.baseUrl))}}async setIssueState(n,e={}){let{issue:t,state:s}=n;if(!t.repository)throw new Error('GitLab requires "repository" for this function.');let o=`mutation SetIssueState($fullPath: ID!, $issueId: String!, $status: IssueStateEvent!) {
|
|
1283
1284
|
updateIssue(input: { projectPath: $fullPath, iid: $issueId, stateEvent: $status }) {
|
|
1284
1285
|
issue {
|
|
1285
1286
|
id
|
|
@@ -1301,7 +1302,7 @@ query GetSingleIssue($projectId: ID!, $issueNumber: String!) {
|
|
|
1301
1302
|
}
|
|
1302
1303
|
}
|
|
1303
1304
|
}
|
|
1304
|
-
}`,i=await v(this.config,{query:o,variables:{fullPath:`${t.repository.owner.login}/${t.repository.name}`,issueId:t.number,milestoneId:s?.id??null}},e),a=i.body.data?.updateIssue;if(!a?.issue?.id||i.body.errors||a?.errors?.length!==0)throw new Error("Could not set milestone of issue")}async setIssueAssignees(n,e={}){let{issue:t,assignees:s}=n;if(!t.repository)throw new Error('GitLab requires "repository" for this function.');let o=s.map(
|
|
1305
|
+
}`,i=await v(this.config,{query:o,variables:{fullPath:`${t.repository.owner.login}/${t.repository.name}`,issueId:t.number,milestoneId:s?.id??null}},e),a=i.body.data?.updateIssue;if(!a?.issue?.id||i.body.errors||a?.errors?.length!==0)throw new Error("Could not set milestone of issue")}async setIssueAssignees(n,e={}){let{issue:t,assignees:s}=n;if(!t.repository)throw new Error('GitLab requires "repository" for this function.');let o=s.map(p=>p.username),i=`mutation SetIssueAssignees($fullPath: ID!, $issueId: String!, $assigneeUsernames: [String!]!) {
|
|
1305
1306
|
issueSetAssignees(input: { projectPath: $fullPath, iid: $issueId, assigneeUsernames: $assigneeUsernames }) {
|
|
1306
1307
|
errors,
|
|
1307
1308
|
issue {
|
|
@@ -1319,7 +1320,7 @@ query getLabelsForRepo(
|
|
|
1319
1320
|
webUrl
|
|
1320
1321
|
milestones(after: $after) {
|
|
1321
1322
|
nodes {
|
|
1322
|
-
${
|
|
1323
|
+
${Ht}
|
|
1323
1324
|
}
|
|
1324
1325
|
pageInfo {
|
|
1325
1326
|
endCursor
|
|
@@ -1328,7 +1329,7 @@ query getLabelsForRepo(
|
|
|
1328
1329
|
}
|
|
1329
1330
|
}
|
|
1330
1331
|
}
|
|
1331
|
-
`,variables:{fullPath:`${t}/${s}`,after:o}},e);return{pageInfo:i.body.data?.project?.milestones?.pageInfo??{endCursor:null,hasNextPage:!1},data:i.body.data?.project?.milestones?.nodes?.map(a=>
|
|
1332
|
+
`,variables:{fullPath:`${t}/${s}`,after:o}},e);return{pageInfo:i.body.data?.project?.milestones?.pageInfo??{endCursor:null,hasNextPage:!1},data:i.body.data?.project?.milestones?.nodes?.map(a=>Vt(a,i.body.data?.project?.webUrl||""))??[]}}async getLabelsForRepo(n,e={}){let{repo:{namespace:t,name:s},cursor:o}=n,i=await v(this.config,{query:`
|
|
1332
1333
|
query getLabelsForRepo(
|
|
1333
1334
|
$fullPath: ID!
|
|
1334
1335
|
$after: String
|
|
@@ -1338,7 +1339,7 @@ query getLabelsForRepo(
|
|
|
1338
1339
|
) {
|
|
1339
1340
|
labels(after: $after) {
|
|
1340
1341
|
nodes {
|
|
1341
|
-
${
|
|
1342
|
+
${Wt}
|
|
1342
1343
|
}
|
|
1343
1344
|
pageInfo {
|
|
1344
1345
|
endCursor
|
|
@@ -1347,28 +1348,28 @@ query getLabelsForRepo(
|
|
|
1347
1348
|
}
|
|
1348
1349
|
}
|
|
1349
1350
|
}
|
|
1350
|
-
`,variables:{fullPath:`${t}/${s}`,after:o}},e);return{pageInfo:i.body.data?.project?.labels?.pageInfo??{endCursor:null,hasNextPage:!1},data:i.body.data?.project?.labels?.nodes?.map(
|
|
1351
|
+
`,variables:{fullPath:`${t}/${s}`,after:o}},e);return{pageInfo:i.body.data?.project?.labels?.pageInfo??{endCursor:null,hasNextPage:!1},data:i.body.data?.project?.labels?.nodes?.map(Jt)??[]}}async getTreeForRepo(n,e={}){let t=_(n.repo),s=new URL(n.cursor??`${A(this.config,e)}/projects/${encodeURIComponent(t)}/repository/tree`);s.searchParams.set("per_page","10000"),s.searchParams.set("recursive","true"),s.searchParams.set("pagination","keyset"),s.searchParams.set("ref",n.branch);let o=await this.config.request({url:s.toString(),headers:R(e.token||this.config.token)}),i=o.headers.link;return{data:o.body.map(Kn),pageInfo:{endCursor:i?i.substring(1,i.indexOf(">")):null,hasNextPage:!!i}}}async getPullRequestForRepo(n,e={}){let t=_(n.repo),o=(await v(this.config,{query:`
|
|
1351
1352
|
query getPullRequestForRepo($fullPath: ID!, $iid: String!) {
|
|
1352
1353
|
project(fullPath: $fullPath) {
|
|
1353
1354
|
${Le}
|
|
1354
1355
|
archived
|
|
1355
1356
|
mergeRequest(iid: $iid) {
|
|
1356
|
-
${
|
|
1357
|
+
${Nt(!1,!0,!0)}
|
|
1357
1358
|
sourceProject {
|
|
1358
1359
|
${Le}
|
|
1359
1360
|
}
|
|
1360
1361
|
}
|
|
1361
1362
|
}
|
|
1362
1363
|
}
|
|
1363
|
-
`,variables:{fullPath:t,iid:n.number.toString()}},e)).body.data?.project,i=o?.mergeRequest;if(!o||!i)return{data:null};let a=De(o),u=i.sourceProject?De(i.sourceProject):null;return{data:Ft(i,a,u,this.getIsSelfHosted(e),this.config.baseUrl??e.baseUrl)}}getMergeRequestUrl(n,e,t){let s=_(n);return`${A(this.config,t)}/projects/${encodeURIComponent(s)}/merge_requests/${e}`}async getPullRequestDescription(n,e={}){try{return{data:{description:(await this.config.request({url:this.getMergeRequestUrl(n.repo,n.number,e),headers:R(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:{...R(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=_(n.repo),s=new URL(`${A(this.config,e)}/projects/${encodeURIComponent(t)}/repository/files/${encodeURIComponent(n.path)}/raw`);s.searchParams.set("ref",n.ref);let o=await this.config.request({url:s.toString(),headers:R(e.token||this.config.token)});return{data:new Blob([o.body])}}async getCommentsForPullRequest(n,e={}){let t=_(n.repo),{page:s,perPage:o}=eo(n.cursor,C),i=new URL(`${A(this.config,e)}/projects/${encodeURIComponent(t)}/merge_requests/${n.pullRequestNumber}/notes`);i.searchParams.set("page",s.toString()),i.searchParams.set("per_page",o.toString()),i.searchParams.set("sort","asc"),i.searchParams.set("order_by","created_at");let a=await this.config.request({url:i.toString(),headers:R(e.token||this.config.token)}),u=this.getIsSelfHosted(e),l=this.config.baseUrl??e.baseUrl,p={namespace:n.repo.namespace,name:n.repo.name,mergeRequestIid:n.pullRequestNumber},d=a.body.filter(m=>!m.system&&!m.position).map(m=>Qt(m,u,l,p)),c=!!a.headers["x-next-page"],g=c?Yn({page:s+1,perPage:o}):null;return{data:d,pageInfo:{endCursor:g,hasNextPage:c}}}async getReviewsForPullRequest(n,e={}){let t=_(n.repo),s=this.getIsSelfHosted(e),o=this.config.baseUrl??e.baseUrl,i=R(e.token||this.config.token),a=A(this.config,e),u=encodeURIComponent(t),[l,p]=await Promise.all([this.config.request({url:`${a}/projects/${u}/merge_requests/${n.pullRequestId}/approvals`,headers:i}),this.fetchAllMergeRequestDiscussions(t,n.pullRequestId,e)]),d=(l.body.approved_by??[]).map(m=>m?.user).filter(m=>!!m).map(m=>{let h=Wr(m,s,o),y=`approval-${m.id}`;return{author:h,body:"",createdAt:l.body.updated_at?new Date(l.body.updated_at):null,id:y,graphQLId:y,reviewComments:[],url:l.body.web_url??""}}),c={namespace:n.repo.namespace,name:n.repo.name,mergeRequestIid:n.pullRequestId},g=p.filter(m=>m.notes.some(h=>!h.system&&!!h.position)).map(m=>{let h=m.notes.filter(w=>!w.system),f=h.filter(w=>!!w.position)[0];if(!f)return null;let P=h.filter(w=>w.id!==f.id).map(w=>Qt(w,s,o,c)),L={...Qt(f,s,o,c),diffLines:[],filename:f.position?.new_path??f.position?.old_path??"",line:f.position?.new_line??f.position?.old_line??null,startLine:f.position?.line_range?.start?.new_line??null,side:so(f.position),isOutdated:!1,isResolved:!!m.resolved,threadId:m.id,replies:P};return{author:f.author?Wr(f.author,s,o):null,body:f.body??"",createdAt:f.created_at?new Date(f.created_at):null,id:m.id,graphQLId:m.id,reviewComments:[L],url:""}}).filter(m=>m!==null);return{data:[...d,...g]}}async getPullRequestDiff(n,e={}){let t=_(n.repo),s=encodeURIComponent(t),o=A(this.config,e);return(await this.fetchAllPagedGitLabREST(`${o}/projects/${s}/merge_requests/${n.pullRequestId}/diffs`,e,{perPage:Vn,maxPages:Kn})).map(no).join("")}async getMergeBase(n,e={}){let t=_(n.repo),s=new URL(`${A(this.config,e)}/projects/${encodeURIComponent(t)}/repository/merge_base`);s.searchParams.append("refs[]",n.base),s.searchParams.append("refs[]",n.head);let i=(await this.config.request({url:s.toString(),headers:R(e.token||this.config.token)})).body?.id;if(!i)throw new Error("No merge base found between the specified commits.");return{data:i}}async fetchAllMergeRequestDiscussions(n,e,t){let s=A(this.config,t),o=encodeURIComponent(n);return this.fetchAllPagedGitLabREST(`${s}/projects/${o}/merge_requests/${e}/discussions`,t)}async fetchAllPagedGitLabREST(n,e,{perPage:t=C,maxPages:s=50}={}){let o=R(e.token||this.config.token),i=[],a=1;for(;a<=s;){let u=new URL(n);u.searchParams.set("page",a.toString()),u.searchParams.set("per_page",t.toString());let l=await this.config.request({url:u.toString(),headers:o});i.push(...l.body);let p=l.headers["x-next-page"];if(!p)break;let d=parseInt(`${p}`,10);if(Number.isNaN(d)||d<=a)break;a=d}return i}async addCommentToPullRequest(n,e={}){let{pullRequest:t,comment:s}=n;if(!s||s.trim()==="")throw new Error("GitLab requires a comment when adding a comment to a pull request.");let o=`${t.repository.owner.login}/${t.repository.name}`,i=`${A(this.config,e)}/projects/${encodeURIComponent(o)}/merge_requests/${t.number}/notes`;if(!(await this.config.request({method:"POST",url:i,headers:{...R(e.token||this.config.token),"Content-Type":"application/json"},body:JSON.stringify({body:s})})).body?.id)throw new Error("Could not add comment to pull request")}async addInlineCommentToPullRequest(n,e={}){let{pullRequest:t,comment:s,path:o,line:i,side:a="RIGHT",threadId:u}=n;if(!s?.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),d=A(this.config,e),c={...R(e.token||this.config.token),"Content-Type":"application/json"};if(u){let P=await this.config.request({method:"POST",url:`${d}/projects/${p}/merge_requests/${t.number}/discussions/${encodeURIComponent(u)}/notes`,headers:c,body:JSON.stringify({body:s})});return P.body?.id!=null?zt(t.repository.owner.login,t.repository.name,t.number,P.body.id):void 0}if(!o?.trim())throw new Error("GitLab requires a file path when adding an inline comment to a pull request.");if(!Number.isInteger(i)||i<1)throw new Error("GitLab requires a positive line number when adding an inline comment to a pull request.");if(a!=="LEFT"&&a!=="RIGHT")throw new Error('GitLab requires side to be either "LEFT" or "RIGHT".');let m=(await this.config.request({url:`${d}/projects/${p}/merge_requests/${t.number}`,headers:R(e.token||this.config.token)})).body?.diff_refs;if(!m?.base_sha||!m?.start_sha||!m?.head_sha)throw new Error("Could not resolve merge request diff refs required to create an inline comment");let h={position_type:"text",base_sha:m.base_sha,start_sha:m.start_sha,head_sha:m.head_sha,new_path:o,old_path:o};a==="RIGHT"?h.new_line=i:h.old_line=i;let f=(await this.config.request({method:"POST",url:`${d}/projects/${p}/merge_requests/${t.number}/discussions`,headers:c,body:JSON.stringify({body:s,position:h})})).body?.notes?.[0]?.id;return f!=null?zt(t.repository.owner.login,t.repository.name,t.number,f):void 0}getNoteUrl(n,e){if(!n)throw new Error('GitLab requires "commentId" for this function.');let{namespace:t,name:s,mergeRequestIid:o,noteId:i}=oo(n);return`${A(this.config,e)}/projects/${encodeURIComponent(`${t}/${s}`)}/merge_requests/${o}/notes/${i}`}async deleteNote(n,e){await this.config.request({method:"DELETE",url:this.getNoteUrl(n,e),headers:R(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:{...R(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 s=_(n.repo),o=new URL(`${A(this.config,t)}/projects/${encodeURIComponent(s)}/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:R(t.token||this.config.token)})}async approvePullRequest(n,e={}){let{pullRequest:t,comment:s}=n,o=`${t.repository.owner.login}/${t.repository.name}`,i=A(this.config,e),a=encodeURIComponent(o),u=R(e.token||this.config.token);await this.config.request({url:`${i}/projects/${a}/merge_requests/${t.number}/approve`,method:"POST",headers:u}),s&&s.trim()!==""&&await this.postMergeRequestNote(o,t.number,s,e)}async commentOnPullRequest(n,e={}){let{pullRequest:t,comment:s}=n;if(!s||s.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,s,e)}async requestPullRequestChanges(n,e={}){let{pullRequest:t,comment:s}=n;if(!s||s.trim()==="")throw new Error("GitLab requires a comment when requesting changes on a pull request.");let o=`${t.repository.owner.login}/${t.repository.name}`;if(!await this.tryRequestChangesMutation(o,t.number,e)){let u=`${A(this.config,e)}/projects/${encodeURIComponent(o)}/merge_requests/${t.number}`,l=R(e.token||this.config.token);(await this.config.request({url:`${u}/approvals`,method:"GET",headers:l})).body?.user_has_approved&&await this.config.request({url:`${u}/unapprove`,method:"POST",headers:l})}await this.postMergeRequestNote(o,t.number,s,e)}async tryRequestChangesMutation(n,e,t){let s=`mutation MergeRequestRequestChanges($fullPath: ID!, $pullRequestId: String!) {
|
|
1364
|
+
`,variables:{fullPath:t,iid:n.number.toString()}},e)).body.data?.project,i=o?.mergeRequest;if(!o||!i)return{data:null};let a=De(o),u=i.sourceProject?De(i.sourceProject):null;return{data:jt(i,a,u,this.getIsSelfHosted(e),this.config.baseUrl??e.baseUrl)}}getMergeRequestUrl(n,e,t){let s=_(n);return`${A(this.config,t)}/projects/${encodeURIComponent(s)}/merge_requests/${e}`}async getPullRequestDescription(n,e={}){try{return{data:{description:(await this.config.request({url:this.getMergeRequestUrl(n.repo,n.number,e),headers:R(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:{...R(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=_(n.repo),s=new URL(`${A(this.config,e)}/projects/${encodeURIComponent(t)}/repository/files/${encodeURIComponent(n.path)}/raw`);s.searchParams.set("ref",n.ref);let o=await this.config.request({url:s.toString(),headers:R(e.token||this.config.token)});return{data:new Blob([o.body])}}async getCommentsForPullRequest(n,e={}){let t=_(n.repo),{page:s,perPage:o}=no(n.cursor,C),i=new URL(`${A(this.config,e)}/projects/${encodeURIComponent(t)}/merge_requests/${n.pullRequestNumber}/notes`);i.searchParams.set("page",s.toString()),i.searchParams.set("per_page",o.toString()),i.searchParams.set("sort","asc"),i.searchParams.set("order_by","created_at");let a=await this.config.request({url:i.toString(),headers:R(e.token||this.config.token)}),u=this.getIsSelfHosted(e),p=this.config.baseUrl??e.baseUrl,l={namespace:n.repo.namespace,name:n.repo.name,mergeRequestIid:n.pullRequestNumber},d=a.body.filter(g=>!g.system&&!g.position).map(g=>Bt(g,u,p,l)),c=!!a.headers["x-next-page"],m=c?so({page:s+1,perPage:o}):null;return{data:d,pageInfo:{endCursor:m,hasNextPage:c}}}async getReviewsForPullRequest(n,e={}){let t=_(n.repo),s=this.getIsSelfHosted(e),o=this.config.baseUrl??e.baseUrl,i=R(e.token||this.config.token),a=A(this.config,e),u=encodeURIComponent(t),[p,l]=await Promise.all([this.config.request({url:`${a}/projects/${u}/merge_requests/${n.pullRequestId}/approvals`,headers:i}),this.fetchAllMergeRequestDiscussions(t,n.pullRequestId,e)]),d=(p.body.approved_by??[]).map(g=>g?.user).filter(g=>!!g).map(g=>{let h=Kr(g,s,o),y=`approval-${g.id}`;return{author:h,body:"",createdAt:p.body.updated_at?new Date(p.body.updated_at):null,id:y,graphQLId:y,reviewComments:[],url:p.body.web_url??""}}),c={namespace:n.repo.namespace,name:n.repo.name,mergeRequestIid:n.pullRequestId},m=l.filter(g=>g.notes.some(h=>!h.system&&!!h.position)).map(g=>{let h=g.notes.filter(w=>!w.system),f=h.filter(w=>!!w.position)[0];if(!f)return null;let P=h.filter(w=>w.id!==f.id).map(w=>Bt(w,s,o,c)),U={...Bt(f,s,o,c),diffLines:[],filename:f.position?.new_path??f.position?.old_path??"",line:f.position?.new_line??f.position?.old_line??null,startLine:f.position?.line_range?.start?.new_line??null,side:ao(f.position),isOutdated:!1,isResolved:!!g.resolved,threadId:g.id,replies:P};return{author:f.author?Kr(f.author,s,o):null,body:f.body??"",createdAt:f.created_at?new Date(f.created_at):null,id:g.id,graphQLId:g.id,reviewComments:[U],url:""}}).filter(g=>g!==null);return{data:[...d,...m]}}async getPullRequestDiff(n,e={}){let t=_(n.repo),s=encodeURIComponent(t),o=A(this.config,e);return(await this.fetchAllPagedGitLabREST(`${o}/projects/${s}/merge_requests/${n.pullRequestId}/diffs`,e,{perPage:Yn,maxPages:eo})).map(uo).join("")}async getMergeBase(n,e={}){let t=_(n.repo),s=new URL(`${A(this.config,e)}/projects/${encodeURIComponent(t)}/repository/merge_base`);s.searchParams.append("refs[]",n.base),s.searchParams.append("refs[]",n.head);let i=(await this.config.request({url:s.toString(),headers:R(e.token||this.config.token)})).body?.id;if(!i)throw new Error("No merge base found between the specified commits.");return{data:i}}async fetchAllMergeRequestDiscussions(n,e,t){let s=A(this.config,t),o=encodeURIComponent(n);return this.fetchAllPagedGitLabREST(`${s}/projects/${o}/merge_requests/${e}/discussions`,t)}async fetchAllPagedGitLabREST(n,e,{perPage:t=C,maxPages:s=50}={}){let o=R(e.token||this.config.token),i=[],a=1;for(;a<=s;){let u=new URL(n);u.searchParams.set("page",a.toString()),u.searchParams.set("per_page",t.toString());let p=await this.config.request({url:u.toString(),headers:o});i.push(...p.body);let l=p.headers["x-next-page"];if(!l)break;let d=parseInt(`${l}`,10);if(Number.isNaN(d)||d<=a)break;a=d}return i}async addCommentToPullRequest(n,e={}){let{pullRequest:t,comment:s}=n;if(!s||s.trim()==="")throw new Error("GitLab requires a comment when adding a comment to a pull request.");let o=`${t.repository.owner.login}/${t.repository.name}`,i=`${A(this.config,e)}/projects/${encodeURIComponent(o)}/merge_requests/${t.number}/notes`;if(!(await this.config.request({method:"POST",url:i,headers:{...R(e.token||this.config.token),"Content-Type":"application/json"},body:JSON.stringify({body:s})})).body?.id)throw new Error("Could not add comment to pull request")}async addInlineCommentToPullRequest(n,e={}){let{pullRequest:t,comment:s,path:o,line:i,side:a="RIGHT",threadId:u}=n;if(!s?.trim())throw new Error("GitLab requires a comment when adding an inline comment to a pull request.");let p=`${t.repository.owner.login}/${t.repository.name}`,l=encodeURIComponent(p),d=A(this.config,e),c={...R(e.token||this.config.token),"Content-Type":"application/json"};if(u){let P=await this.config.request({method:"POST",url:`${d}/projects/${l}/merge_requests/${t.number}/discussions/${encodeURIComponent(u)}/notes`,headers:c,body:JSON.stringify({body:s})});return P.body?.id!=null?zt(t.repository.owner.login,t.repository.name,t.number,P.body.id):void 0}if(!o?.trim())throw new Error("GitLab requires a file path when adding an inline comment to a pull request.");if(!Number.isInteger(i)||i<1)throw new Error("GitLab requires a positive line number when adding an inline comment to a pull request.");if(a!=="LEFT"&&a!=="RIGHT")throw new Error('GitLab requires side to be either "LEFT" or "RIGHT".');let g=(await this.config.request({url:`${d}/projects/${l}/merge_requests/${t.number}`,headers:R(e.token||this.config.token)})).body?.diff_refs;if(!g?.base_sha||!g?.start_sha||!g?.head_sha)throw new Error("Could not resolve merge request diff refs required to create an inline comment");let h={position_type:"text",base_sha:g.base_sha,start_sha:g.start_sha,head_sha:g.head_sha,new_path:o,old_path:o};a==="RIGHT"?h.new_line=i:h.old_line=i;let f=(await this.config.request({method:"POST",url:`${d}/projects/${l}/merge_requests/${t.number}/discussions`,headers:c,body:JSON.stringify({body:s,position:h})})).body?.notes?.[0]?.id;return f!=null?zt(t.repository.owner.login,t.repository.name,t.number,f):void 0}getNoteUrl(n,e){if(!n)throw new Error('GitLab requires "commentId" for this function.');let{namespace:t,name:s,mergeRequestIid:o,noteId:i}=lo(n);return`${A(this.config,e)}/projects/${encodeURIComponent(`${t}/${s}`)}/merge_requests/${o}/notes/${i}`}async deleteNote(n,e){await this.config.request({method:"DELETE",url:this.getNoteUrl(n,e),headers:R(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:{...R(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 s=_(n.repo),o=new URL(`${A(this.config,t)}/projects/${encodeURIComponent(s)}/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:R(t.token||this.config.token)})}async approvePullRequest(n,e={}){let{pullRequest:t,comment:s}=n,o=`${t.repository.owner.login}/${t.repository.name}`,i=A(this.config,e),a=encodeURIComponent(o),u=R(e.token||this.config.token);await this.config.request({url:`${i}/projects/${a}/merge_requests/${t.number}/approve`,method:"POST",headers:u}),s&&s.trim()!==""&&await this.postMergeRequestNote(o,t.number,s,e)}async commentOnPullRequest(n,e={}){let{pullRequest:t,comment:s}=n;if(!s||s.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,s,e)}async requestPullRequestChanges(n,e={}){let{pullRequest:t,comment:s}=n;if(!s||s.trim()==="")throw new Error("GitLab requires a comment when requesting changes on a pull request.");let o=`${t.repository.owner.login}/${t.repository.name}`;if(!await this.tryRequestChangesMutation(o,t.number,e)){let u=`${A(this.config,e)}/projects/${encodeURIComponent(o)}/merge_requests/${t.number}`,p=R(e.token||this.config.token);(await this.config.request({url:`${u}/approvals`,method:"GET",headers:p})).body?.user_has_approved&&await this.config.request({url:`${u}/unapprove`,method:"POST",headers:p})}await this.postMergeRequestNote(o,t.number,s,e)}async tryRequestChangesMutation(n,e,t){let s=`mutation MergeRequestRequestChanges($fullPath: ID!, $pullRequestId: String!) {
|
|
1364
1365
|
mergeRequestRequestChanges(input: { projectPath: $fullPath, iid: $pullRequestId }) {
|
|
1365
1366
|
errors
|
|
1366
1367
|
mergeRequest {
|
|
1367
1368
|
id
|
|
1368
1369
|
}
|
|
1369
1370
|
}
|
|
1370
|
-
}`,o=await v(this.config,{query:s,variables:{fullPath:n,pullRequestId:e.toString()}},t),i=o.body.errors;if(i?.length){if(i.some(
|
|
1371
|
-
OR comment ~ currentUser() OR summary ~ currentUser() OR description ~ currentUser())`];i&&i.forEach(f=>u.push(`labels = "${f}"`));let l=`${u.join(" AND ")} ORDER BY updated DESC`,p=!o,d=p?es:Yr,c=new URL(`${se(r,t,o)}${d}`);c.searchParams.set("jql",l),c.searchParams.set("maxResults",Xe.toString()),c.searchParams.set("fields",Vt.join(",")),c.searchParams.set("expand","transitions"),s&&(p?c.searchParams.set("startAt",s):c.searchParams.set("nextPageToken",s));let g=await r.request({url:c.toString(),headers:R(t.token||r.token)}),m=g.body.issues.map(f=>Kt(f,a,e,o)),h=!1,y="";return p?(h=m.length==Xe,y=(parseInt(s??"0",10)+m.length).toString()):(h=!!g.body.nextPageToken,y=g.body.nextPageToken??null),{data:m,pageInfo:{hasNextPage:h,endCursor:y}}},ts=async(r,n,e,t={})=>{let{cursor:s,resourceId:o,jql:i,fields:a}=n||{},u=U(n?.pageSize,{fallback:Xe,max:Xe}),l=[...Vt],p=a?.Sprint;p&&l.push(p);let d=!o,c=d?es:Yr,g=new URL(`${se(r,t,o)}${c}`);g.searchParams.set("jql",i.join(" AND ")),g.searchParams.set("maxResults",u.toString()),g.searchParams.set("fields",l.join(",")),g.searchParams.set("expand","transitions"),s&&(d?g.searchParams.set("startAt",s):g.searchParams.set("nextPageToken",s));let m=await r.request({url:g.toString(),headers:R(t.token||r.token)}),h=m.body.issues.map(P=>Kt(P,a,e,o)),y=!1,f="";if(d){let P=parseInt(s??"0",10),q=typeof m.body.startAt=="number"?m.body.startAt:Number.isNaN(P)?0:P,L=m.body.total;y=typeof L=="number"?q+h.length<L:h.length===u,f=(q+h.length).toString()}else y=!!m.body.nextPageToken,f=m.body.nextPageToken??null;return{data:h,pageInfo:{hasNextPage:y,endCursor:f}}},rt=async(r,n,e,t={})=>{let{assigneeLogins:s,authorLogin:o,mentionLogin:i,labelNames:a,cursor:u,projectKey:l,resourceId:p,fields:d}=n||{},c=[`project = "${l}"`],g=Zr(n.states);return g&&c.push(g),o&&c.push(`creator in ("${o}")`),s&&s.length!==0&&c.push(`assignee in ("${s.join('", "')}")`),i&&c.push(`comment ~ "${i}"`),a&&a.forEach(m=>c.push(`labels = "${m}"`)),ts(r,{resourceId:p,jql:c,cursor:u,fields:d,pageSize:n.pageSize},e,t)},st=async(r,n,e,t={})=>{let{assigneeLogins:s,authorLogin:o,mentionLogin:i,labelNames:a,cursor:u,projectKeys:l,resourceId:p,fields:d}=n||{},g=["("+l.map(h=>`project = "${h}"`).join(" OR ")+")"],m=Zr(n.states);return m&&g.push(m),o&&g.push(`creator in ("${o}")`),s&&s.length!==0&&g.push(`assignee in ("${s.join('", "')}")`),i&&g.push(`comment ~ "${i}"`),a&&a.forEach(h=>g.push(`labels = "${h}"`)),ts(r,{resourceId:p,jql:g,fields:d,cursor:u,pageSize:n.pageSize},e,t)},nt=async(r,n,e={})=>{let{issue:t,labels:s}=n;if(!t.project)throw new Error('Jira requires a "project" for this function.');let o={fields:{labels:s.map(i=>i.name)}};await r.request({method:"PUT",url:`${se(r,e,t.project.resourceId??void 0)}/rest/api/2/issue/${t.id}`,body:JSON.stringify(o),headers:{...R(e.token||r.token),"Content-Type":"application/json"}})},ot=async(r,n,e={})=>{let{issue:t,components:s}=n;if(!t.project)throw new Error('Jira requires a "project" for this function.');let o={fields:{components:s.map(i=>({id:i.id}))}};await r.request({method:"PUT",url:`${se(r,e,t.project.resourceId??void 0)}/rest/api/2/issue/${t.id}`,body:JSON.stringify(o),headers:{...R(e.token||r.token),"Content-Type":"application/json"}})},it=async(r,n,e={})=>{let{issue:t,status:s}=n;if(!t.project)throw new Error('Jira requires a "project" for this function.');if(!s.id)throw new Error('Jira requires a status "id" for this function.');let o={transition:{id:s.id}};await r.request({method:"POST",url:`${se(r,e,t.project.resourceId??void 0)}/rest/api/2/issue/${t.id}/transitions`,body:JSON.stringify(o),headers:{...R(e.token||r.token),"Content-Type":"application/json"}})},at=async(r,n,e={})=>{let{resourceId:t,projectIdOrKey:s}=n,o=new URL(`${se(r,e,t)}/rest/api/2/project/${s}/components`);return{data:(await r.request({url:o.toString(),headers:R(e.token||r.token)})).body}};var Ue="https://api.atlassian.com/ex/jira",Xt=100,go=5,Pe=class extends j{constructor(){super(...arguments);this._resourceUrlCache={};this._issueFieldsCache={}}async getIssueFieldsForResource(e,t={}){if(!this._issueFieldsCache[e.resourceId]){let s=await Ye(this.config,e,t);this._issueFieldsCache[e.resourceId]=s.reduce((o,i)=>({...o,[i.name]:i.id}),{})}return this._issueFieldsCache[e.resourceId]??null}async getResourceUrl(e,t={}){let s=t.token||this.config.token;if(!s)return null;let o=this._resourceUrlCache[s];return o?o[e.resourceId]??null:(await this.getJiraResourcesForCurrentUser(t),this._resourceUrlCache[s]?.[e.resourceId]??null)}async getCurrentUserForResource(e,t={}){let s=await this.getResourceUrl({resourceId:e.resourceId},t),o=await this.config.request({url:`${t.baseUrl||Ue}/${e.resourceId}/rest/api/2/myself`,headers:R(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:s?`${s}/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:R(e.token||this.config.token)}),s=e.token||this.config.token,o=s?this._resourceUrlCache[s]||{}: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 s&&(this._resourceUrlCache[s]=o),{data:i}}async getJiraProjectsForResource(e,t={}){let s=new URL(`${t.baseUrl||Ue}/${e.resourceId}/rest/api/2/project/search`);s.searchParams.set("maxResults",Xt.toString()),e.cursor&&s.searchParams.set("startAt",e.cursor);let o=await this.config.request({url:s.toString(),headers:R(t.token||this.config.token)});return{pageInfo:{hasNextPage:o.body.values.length!==0,endCursor:(o.body.startAt+o.body.values.length).toString()},metadata:ge("complete"),data:o.body.values.map(i=>({id:i.id,key:i.key,name:i.name,resourceId:e.resourceId}))}}async getJiraProjectsForResources(e,t={}){let{successes:s,metadata:o}=await J(e.resourceIds,{run:a=>ur(u=>this.getJiraProjectsForResource({resourceId:a,cursor:u},t)),failureScope:a=>({providerId:"jira",resourceId:a}),concurrency:go}),i=[];return s.forEach(({result:a})=>{i.push(...a)}),{data:i,metadata:o}}async getAccountsForJiraProject(e,t={}){let{resourceId:s,projectKey:o,cursor:i}=e,a=await this.getResourceUrl({resourceId:s},t),u=new URL(`${t.baseUrl||Ue}/${s}/rest/api/2/user/assignable/search`);u.searchParams.set("maxResults",Xt.toString()),i&&u.searchParams.set("startAt",i),u.searchParams.set("project",o);let l=await this.config.request({url:u.toString(),headers:R(t.token||this.config.token)});return{pageInfo:{hasNextPage:l.body.length!==0,endCursor:((i?parseInt(i):0)+l.body.length).toString()},metadata:ge("complete"),data:l.body.filter(p=>p.accountType!=="app"&&p.active).map(p=>Ze(p,a,!1))}}async getComponentsForJiraProject(e,t={}){return await at(this.config,e,t)}async getIssue(e,t={}){let s=await this.getIssueFieldsForResource({resourceId:e.resourceId},t),o=await this.getResourceUrl({resourceId:e.resourceId},t);return await et(this.config,{...e,fields:s},o,t)}async getIssuesForProject(e,t={}){let s=await this.getIssueFieldsForResource({resourceId:e.resourceId},t),o=await this.getResourceUrl({resourceId:e.resourceId},t);return await rt(this.config,{...e,fields:s},o,t)}async getIssuesForProjects(e,t={}){let s=await this.getIssueFieldsForResource({resourceId:e.resourceId},t),o=await this.getResourceUrl({resourceId:e.resourceId},t);return await st(this.config,{...e,fields:s},o,t)}async getIssuesForResourceForCurrentUser(e,t={}){let s=await this.getIssueFieldsForResource({resourceId:e.resourceId},t),o=await this.getResourceUrl({resourceId:e.resourceId},t);return await tt(this.config,{...e,fields:s},o,t)}async setIssueStatus(e,t={}){await it(this.config,e,t)}async setIssueAssignee(e,t={}){let{issue:s,assignee:o}=e;if(!s.project)throw new Error('Jira Cloud requires a "project" for this function.');if(!s.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||Ue}/${s.project.resourceId}/rest/api/2/issue/${s.id}/assignee`,body:JSON.stringify(i),headers:{...R(t.token||this.config.token),"Content-Type":"application/json"}})}async setIssueComponents(e,t={}){await ot(this.config,e,t)}async setIssueLabels(e,t={}){await nt(this.config,e,t)}async getLabelsForResource(e,t={}){let{resourceId:s,cursor:o}=e,i=new URL(`${t.baseUrl||Ue}/${s}/rest/api/2/label`);i.searchParams.set("maxResults",Xt.toString()),o&&i.searchParams.set("startAt",o);let a=await this.config.request({url:i.toString(),headers:R(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 we=class extends N{constructor(){super(...arguments);this._issueFieldsCache={}}async getIssueFieldsForResource(e={}){let t=e?.baseUrl||this.config.baseUrl||"";if(!this._issueFieldsCache[t]){let s=await Ye(this.config,{},e);this._issueFieldsCache[t]=s.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:R(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:R(e?.token||this.config.token)})).body.map(s=>({id:s.id,name:s.name}))}}async getIssue(e,t={}){let s=e.resourceUrl||t.baseUrl||this.config.baseUrl;if(!s)throw new Error('Jira Server requires a "resourceUrl" or "baseUrl" for this function.');let o=await this.getIssueFieldsForResource(t);return await et(this.config,{...e,fields:o},s,t)}async getIssuesForProject(e,t={}){let s=e.resourceUrl||t.baseUrl||this.config.baseUrl;if(!s)throw new Error('Jira Server requires a "resourceUrl" or "baseUrl" for this function.');let o=await this.getIssueFieldsForResource(t);return await rt(this.config,{...e,fields:o},s,t)}async getIssuesForProjects(e,t={}){let s=e.resourceUrl||t.baseUrl||this.config.baseUrl;if(!s)throw new Error('Jira Server requires a "resourceUrl" or "baseUrl" for this function.');let o=await this.getIssueFieldsForResource(t);return await st(this.config,{...e,fields:o},s,t)}async getIssuesForResourceForCurrentUser(e,t={}){let s=e.resourceUrl||t.baseUrl||this.config.baseUrl;if(!s)throw new Error('Jira Server requires a "resourceUrl" or "baseUrl" for this function.');let o=await this.getIssueFieldsForResource(t);return await tt(this.config,{...e,fields:o},s,t)}async setIssueStatus(e,t={}){await it(this.config,e,t)}async setIssueLabels(e,t={}){await nt(this.config,e,t)}async setIssueComponents(e,t={}){await ot(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:R(e.token||this.config.token)})).body.results.map(({displayName:s})=>({color:null,description:null,id:null,name:s}))}}async getComponentsForJiraProject(e,t={}){return await at(this.config,e,t)}};var H="https://api.trello.com",rs=1e3,W=(r,n)=>({...R(n),Authorization:`OAuth oauth_consumer_key="${r}", oauth_token="${n}"`}),ho=r=>({id:r.id,username:r.username,url:r.url,name:r.fullName,email:r.email,avatarUrl:r.avatarUrl}),fo=(r,n)=>{let e=new Date(1e3*parseInt(r.id.substring(0,8),16));return{id:r.id,commentCount:r.badges.comments,number:r.idShort.toString(),title:r.name,url:r.url,closedDate:null,createdDate:new Date(e.toISOString()),author:null,updatedDate:new Date(r.dateLastActivity),assignees:r.members.map(t=>({id:t.id,username:t.username,name:t.fullName,email:null,avatarUrl:t.avatarUrl,url:null})),description:null,state:n[r.idList??""]?{id:r.idList,name:n[r.idList].name,color:null}:null,type:null,repository:null,upvoteCount:r.badges.votes,labels:r.labels.map(t=>({color:t.color,description:null,id:t.id,name:t.name}))}},Se=class extends j{async getCurrentUser(n,e={}){let t=await this.config.request({url:`${e.baseUrl||H}/1/members/me`,headers:W(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||H}/1/members/me/boards?fields=name&filter=open`,headers:W(n.appKey,e.token||this.config.token)})).body.map(s=>({id:s.id,name:s.name}))}}async getListsForTrelloBoard(n,e={}){let{appKey:t,boardId:s}=n;return{data:(await this.config.request({url:`${e.baseUrl||H}/1/boards/${s}/lists`,headers:W(t,e.token||this.config.token)})).body}}async getAccountForId(n,e={}){let{appKey:t,memberId:s}=n,o=await this.config.request({url:`${e.baseUrl||H}/1/members/${s}`,headers:W(t,e.token||this.config.token)});return{data:ho(o.body)}}async getAccountsForTrelloBoard(n,e={}){let{appKey:t,boardId:s}=n;return{data:(await this.config.request({url:`${e.baseUrl||H}/1/boards/${s}/members`,headers:W(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:s,boardId:o,filterText:i,assigneeLogins:a,labelNamesOrColors:u,trelloBoardListsById:l}=n||{};a&&t.push("@me"),u&&u.forEach(g=>t.push(`label:"${g}"`));let p=`${i?`${i}`:""}${t.join(" ")} board:${o}`,d=await this.config.request({url:`${e.baseUrl||H}/1/search?query=${p}&cards_limit=${rs}&card_members=true`,headers:W(s,e.token||this.config.token)}),c=d.body.cards.length>=rs?"unknown":"complete";return{data:d.body.cards.map(g=>fo(g,l||{})),metadata:ge(c)}}async updateIssue(n,e,t,s){return await this.config.request({method:"PUT",url:`${s.baseUrl||H}/1/cards/${e.id}?${t}`,headers:W(n,s.token||this.config.token)})}async setIssueStatus(n,e={}){let{appKey:t,issue:s,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,s,i,e)).body.id)throw new Error("Could not set issue status")}async setIssueAssignees(n,e={}){let{appKey:t,issue:s,assignees:o}=n,i=o.map(l=>l.id),a=`idMembers=${encodeURIComponent(i.join(","))}`;if(!(await this.updateIssue(t,s,a,e)).body.id)throw new Error("Could not set issue status")}async setIssueLabels(n,e={}){let{appKey:t,issue:s,labels:o}=n,i=o.map(u=>u.id).join(",");if(!(await this.config.request({method:"PUT",url:`${e.baseUrl||H}/1/cards/${s.id}?idLabels=${encodeURIComponent(i)}`,headers:W(t,e.token||this.config.token)})).body.id)throw new Error("Could not set issue status")}async setIssueArchived(n,e={}){let{appKey:t,issue:s,archived:o}=n;if(!(await this.config.request({method:"PUT",url:`${e.baseUrl||H}/1/cards/${s.id}?closed=${o}`,headers:W(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:s}=n;return{data:(await this.config.request({url:`${e.baseUrl||H}/1/boards/${s}/labels`,headers:W(t,e.token||this.config.token)})).body.map(i=>({color:i.color,description:null,id:i.id,name:i.name}))}}};var Yt=100,ut=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}},Z=async(r,n,e,t)=>{let s=n.token||r.token;if(!s)throw new Error("Linear API key is required");let o=await r.request({url:"https://api.linear.app/graphql",method:"POST",headers:{Authorization:s,"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},Zt=r=>r?r instanceof Date?r:new Date(r):null,Ro=`
|
|
1371
|
+
}`,o=await v(this.config,{query:s,variables:{fullPath:n,pullRequestId:e.toString()}},t),i=o.body.errors;if(i?.length){if(i.some(Jn))return!1;throw new Error(`Could not request pull request changes: ${$e(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,s){let o=A(this.config,s),i=encodeURIComponent(n),a=R(s.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 po="https://api.atlassian.com/ex/jira",Ze=100,ts=r=>{if(!r||r.length===0)return"statusCategory != Done";let n=new Set(r),e=n.has("OPEN"),t=n.has("CLOSED");return e&&t?null:t?"statusCategory = Done":"statusCategory != Done"},Kt=["assignee","comment","summary","created","creator","updated","votes","issuetype","status","labels","components","project","fixVersions","description"],rs="/rest/api/2/search/jql",ss="/rest/api/2/search",Xt=(r,n,e,t)=>{let s=r.fields.assignee,o=!t,i=(r.fields[n?.Sprint??""]??[]).filter(a=>typeof a=="object");return{id:r.id,commentCount:r.fields.comment.comments.length,number:r.key,title:r.fields.summary,url:e?`${e}/browse/${r.key}`:null,closedDate:null,createdDate:new Date(r.fields.created),author:Ye(r.fields.creator,e,o),updatedDate:new Date(r.fields.updated),assignees:s?[Ye(s,e,o)]:[],description:r.fields.description,repository:null,project:{name:r.fields.project.name,resourceId:t??null,key:r.fields.project.key,namespace:null,id:r.fields.project.id},state:ho(r.fields.status),statusTransitions:r.transitions?.map(co)??[],components:r.fields.components?.map(mo)??[],type:r.fields.issuetype.name,upvoteCount:r.fields.votes?.votes||0,labels:r.fields.labels?.map(a=>({color:null,description:null,id:null,name:a}))??[],sprints:i.map(fo),fixVersions:r.fields.fixVersions.map(Ro)}},co=r=>{let n;switch(r.to.statusCategory.name){case"To Do":n="TO_DO";break;case"In Progress":n="IN_PROGRESS";break;default:n="DONE";break}return{name:r.name,id:r.id,to:{id:r.to.id,name:r.to.name,color:r.to.statusCategory.colorName,category:n}}},mo=r=>({description:r.description??null,id:r.id,name:r.name}),go=(r,n,e)=>e&&r.name?`${n}/secure/ViewProfile.jspa?name=${encodeURIComponent(r.name)}`:`${n}/jira/people/${r.accountId}`,Ye=(r,n,e)=>({id:(e?r.key:r.accountId)??"",name:r.displayName,email:r.emailAddress,avatarUrl:r.avatarUrls["48x48"],username:r.displayName,url:go(r,n,e)}),ho=r=>{let n;switch(r.statusCategory.name){case"To Do":n="TO_DO";break;case"In Progress":n="IN_PROGRESS";break;default:n="DONE";break}return{id:r.id,name:r.name,color:r.statusCategory.colorName,category:n}},fo=r=>({id:r.id.toString(),name:r.name,isActive:r.state==="active",startDate:r.startDate?new Date(r.startDate):null,endDate:r.endDate?new Date(r.endDate):null,completedDate:r.completeDate?new Date(r.completeDate):null}),Ro=r=>({id:r.id,description:r.description,name:r.name,archived:r.archived,released:r.released,releaseDate:r.releaseDate?new Date(r.releaseDate):null}),ne=(r,n,e)=>e?`${n.baseUrl||po}/${e}`:`${n?.baseUrl||r.baseUrl}`,et=async(r,n,e={})=>{let{resourceId:t}=n;return(await r.request({url:`${ne(r,e,t)}/rest/api/2/field`,headers:R(e.token||r.token)})).body},tt=async(r,n,e,t={})=>{let{number:s,resourceId:o,fields:i}=n||{},a=await r.request({url:`${ne(r,t,o)}/rest/api/2/issue/${s}?fields=${Kt.join(",")}&expand=transitions`,headers:R(t.token||r.token)});return{data:Xt(a.body,i,e,o)}},rt=async(r,n,e,t={})=>{let{cursor:s,resourceId:o,labelNames:i,fields:a}=n||{},u=["statusCategory != Done",`(creator = currentUser() OR assignee = currentUser()
|
|
1372
|
+
OR comment ~ currentUser() OR summary ~ currentUser() OR description ~ currentUser())`];i&&i.forEach(f=>u.push(`labels = "${f}"`));let p=`${u.join(" AND ")} ORDER BY updated DESC`,l=!o,d=l?ss:rs,c=new URL(`${ne(r,t,o)}${d}`);c.searchParams.set("jql",p),c.searchParams.set("maxResults",Ze.toString()),c.searchParams.set("fields",Kt.join(",")),c.searchParams.set("expand","transitions"),s&&(l?c.searchParams.set("startAt",s):c.searchParams.set("nextPageToken",s));let m=await r.request({url:c.toString(),headers:R(t.token||r.token)}),g=m.body.issues.map(f=>Xt(f,a,e,o)),h=!1,y="";return l?(h=g.length==Ze,y=(parseInt(s??"0",10)+g.length).toString()):(h=!!m.body.nextPageToken,y=m.body.nextPageToken??null),{data:g,pageInfo:{hasNextPage:h,endCursor:y}}},ns=async(r,n,e,t={})=>{let{cursor:s,resourceId:o,jql:i,fields:a}=n||{},u=$(n?.pageSize,{fallback:Ze,max:Ze}),p=[...Kt],l=a?.Sprint;l&&p.push(l);let d=!o,c=d?ss:rs,m=new URL(`${ne(r,t,o)}${c}`);m.searchParams.set("jql",i.join(" AND ")),m.searchParams.set("maxResults",u.toString()),m.searchParams.set("fields",p.join(",")),m.searchParams.set("expand","transitions"),s&&(d?m.searchParams.set("startAt",s):m.searchParams.set("nextPageToken",s));let g=await r.request({url:m.toString(),headers:R(t.token||r.token)}),h=g.body.issues.map(P=>Xt(P,a,e,o)),y=!1,f="";if(d){let P=parseInt(s??"0",10),q=typeof g.body.startAt=="number"?g.body.startAt:Number.isNaN(P)?0:P,U=g.body.total;y=typeof U=="number"?q+h.length<U:h.length===u,f=(q+h.length).toString()}else y=!!g.body.nextPageToken,f=g.body.nextPageToken??null;return{data:h,pageInfo:{hasNextPage:y,endCursor:f}}},st=async(r,n,e,t={})=>{let{assigneeLogins:s,authorLogin:o,mentionLogin:i,labelNames:a,cursor:u,projectKey:p,resourceId:l,fields:d}=n||{},c=[`project = "${p}"`],m=ts(n.states);return m&&c.push(m),o&&c.push(`creator in ("${o}")`),s&&s.length!==0&&c.push(`assignee in ("${s.join('", "')}")`),i&&c.push(`comment ~ "${i}"`),a&&a.forEach(g=>c.push(`labels = "${g}"`)),ns(r,{resourceId:l,jql:c,cursor:u,fields:d,pageSize:n.pageSize},e,t)},nt=async(r,n,e,t={})=>{let{assigneeLogins:s,authorLogin:o,mentionLogin:i,labelNames:a,cursor:u,projectKeys:p,resourceId:l,fields:d}=n||{},m=["("+p.map(h=>`project = "${h}"`).join(" OR ")+")"],g=ts(n.states);return g&&m.push(g),o&&m.push(`creator in ("${o}")`),s&&s.length!==0&&m.push(`assignee in ("${s.join('", "')}")`),i&&m.push(`comment ~ "${i}"`),a&&a.forEach(h=>m.push(`labels = "${h}"`)),ns(r,{resourceId:l,jql:m,fields:d,cursor:u,pageSize:n.pageSize},e,t)},ot=async(r,n,e={})=>{let{issue:t,labels:s}=n;if(!t.project)throw new Error('Jira requires a "project" for this function.');let o={fields:{labels:s.map(i=>i.name)}};await r.request({method:"PUT",url:`${ne(r,e,t.project.resourceId??void 0)}/rest/api/2/issue/${t.id}`,body:JSON.stringify(o),headers:{...R(e.token||r.token),"Content-Type":"application/json"}})},it=async(r,n,e={})=>{let{issue:t,components:s}=n;if(!t.project)throw new Error('Jira requires a "project" for this function.');let o={fields:{components:s.map(i=>({id:i.id}))}};await r.request({method:"PUT",url:`${ne(r,e,t.project.resourceId??void 0)}/rest/api/2/issue/${t.id}`,body:JSON.stringify(o),headers:{...R(e.token||r.token),"Content-Type":"application/json"}})},at=async(r,n,e={})=>{let{issue:t,status:s}=n;if(!t.project)throw new Error('Jira requires a "project" for this function.');if(!s.id)throw new Error('Jira requires a status "id" for this function.');let o={transition:{id:s.id}};await r.request({method:"POST",url:`${ne(r,e,t.project.resourceId??void 0)}/rest/api/2/issue/${t.id}/transitions`,body:JSON.stringify(o),headers:{...R(e.token||r.token),"Content-Type":"application/json"}})},ut=async(r,n,e={})=>{let{resourceId:t,projectIdOrKey:s}=n,o=new URL(`${ne(r,e,t)}/rest/api/2/project/${s}/components`);return{data:(await r.request({url:o.toString(),headers:R(e.token||r.token)})).body}};var Ue="https://api.atlassian.com/ex/jira",Zt=100,Io=5,Pe=class extends j{constructor(){super(...arguments);this._resourceUrlCache={};this._issueFieldsCache={}}async getIssueFieldsForResource(e,t={}){if(!this._issueFieldsCache[e.resourceId]){let s=await et(this.config,e,t);this._issueFieldsCache[e.resourceId]=s.reduce((o,i)=>({...o,[i.name]:i.id}),{})}return this._issueFieldsCache[e.resourceId]??null}async getResourceUrl(e,t={}){let s=t.token||this.config.token;if(!s)return null;let o=this._resourceUrlCache[s];return o?o[e.resourceId]??null:(await this.getJiraResourcesForCurrentUser(t),this._resourceUrlCache[s]?.[e.resourceId]??null)}async getCurrentUserForResource(e,t={}){let s=await this.getResourceUrl({resourceId:e.resourceId},t),o=await this.config.request({url:`${t.baseUrl||Ue}/${e.resourceId}/rest/api/2/myself`,headers:R(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:s?`${s}/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:R(e.token||this.config.token)}),s=e.token||this.config.token,o=s?this._resourceUrlCache[s]||{}: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 s&&(this._resourceUrlCache[s]=o),{data:i}}async getJiraProjectsForResource(e,t={}){let s=new URL(`${t.baseUrl||Ue}/${e.resourceId}/rest/api/2/project/search`);s.searchParams.set("maxResults",Zt.toString()),e.cursor&&s.searchParams.set("startAt",e.cursor);let o=await this.config.request({url:s.toString(),headers:R(t.token||this.config.token)});return{pageInfo:{hasNextPage:o.body.values.length!==0,endCursor:(o.body.startAt+o.body.values.length).toString()},metadata:J("complete"),data:o.body.values.map(i=>({id:i.id,key:i.key,name:i.name,resourceId:e.resourceId}))}}async getJiraProjectsForResources(e,t={}){let{successes:s,metadata:o}=await V(e.resourceIds,{run:a=>ur(u=>this.getJiraProjectsForResource({resourceId:a,cursor:u},t)),failureScope:a=>({providerId:"jira",resourceId:a}),concurrency:Io}),i=[];return s.forEach(({result:a})=>{i.push(...a)}),{data:i,metadata:o}}async getAccountsForJiraProject(e,t={}){let{resourceId:s,projectKey:o,cursor:i}=e,a=await this.getResourceUrl({resourceId:s},t),u=new URL(`${t.baseUrl||Ue}/${s}/rest/api/2/user/assignable/search`);u.searchParams.set("maxResults",Zt.toString()),i&&u.searchParams.set("startAt",i),u.searchParams.set("project",o);let p=await this.config.request({url:u.toString(),headers:R(t.token||this.config.token)});return{pageInfo:{hasNextPage:p.body.length!==0,endCursor:((i?parseInt(i):0)+p.body.length).toString()},metadata:J("complete"),data:p.body.filter(l=>l.accountType!=="app"&&l.active).map(l=>Ye(l,a,!1))}}async getComponentsForJiraProject(e,t={}){return await ut(this.config,e,t)}async getIssue(e,t={}){let s=await this.getIssueFieldsForResource({resourceId:e.resourceId},t),o=await this.getResourceUrl({resourceId:e.resourceId},t);return await tt(this.config,{...e,fields:s},o,t)}async getIssuesForProject(e,t={}){let s=await this.getIssueFieldsForResource({resourceId:e.resourceId},t),o=await this.getResourceUrl({resourceId:e.resourceId},t);return await st(this.config,{...e,fields:s},o,t)}async getIssuesForProjects(e,t={}){let s=await this.getIssueFieldsForResource({resourceId:e.resourceId},t),o=await this.getResourceUrl({resourceId:e.resourceId},t);return await nt(this.config,{...e,fields:s},o,t)}async getIssuesForResourceForCurrentUser(e,t={}){let s=await this.getIssueFieldsForResource({resourceId:e.resourceId},t),o=await this.getResourceUrl({resourceId:e.resourceId},t);return await rt(this.config,{...e,fields:s},o,t)}async setIssueStatus(e,t={}){await at(this.config,e,t)}async setIssueAssignee(e,t={}){let{issue:s,assignee:o}=e;if(!s.project)throw new Error('Jira Cloud requires a "project" for this function.');if(!s.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||Ue}/${s.project.resourceId}/rest/api/2/issue/${s.id}/assignee`,body:JSON.stringify(i),headers:{...R(t.token||this.config.token),"Content-Type":"application/json"}})}async setIssueComponents(e,t={}){await it(this.config,e,t)}async setIssueLabels(e,t={}){await ot(this.config,e,t)}async getLabelsForResource(e,t={}){let{resourceId:s,cursor:o}=e,i=new URL(`${t.baseUrl||Ue}/${s}/rest/api/2/label`);i.searchParams.set("maxResults",Zt.toString()),o&&i.searchParams.set("startAt",o);let a=await this.config.request({url:i.toString(),headers:R(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 we=class extends N{constructor(){super(...arguments);this._issueFieldsCache={}}async getIssueFieldsForResource(e={}){let t=e?.baseUrl||this.config.baseUrl||"";if(!this._issueFieldsCache[t]){let s=await et(this.config,{},e);this._issueFieldsCache[t]=s.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:R(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:R(e?.token||this.config.token)})).body.map(s=>({id:s.id,name:s.name}))}}async getIssue(e,t={}){let s=e.resourceUrl||t.baseUrl||this.config.baseUrl;if(!s)throw new Error('Jira Server requires a "resourceUrl" or "baseUrl" for this function.');let o=await this.getIssueFieldsForResource(t);return await tt(this.config,{...e,fields:o},s,t)}async getIssuesForProject(e,t={}){let s=e.resourceUrl||t.baseUrl||this.config.baseUrl;if(!s)throw new Error('Jira Server requires a "resourceUrl" or "baseUrl" for this function.');let o=await this.getIssueFieldsForResource(t);return await st(this.config,{...e,fields:o},s,t)}async getIssuesForProjects(e,t={}){let s=e.resourceUrl||t.baseUrl||this.config.baseUrl;if(!s)throw new Error('Jira Server requires a "resourceUrl" or "baseUrl" for this function.');let o=await this.getIssueFieldsForResource(t);return await nt(this.config,{...e,fields:o},s,t)}async getIssuesForResourceForCurrentUser(e,t={}){let s=e.resourceUrl||t.baseUrl||this.config.baseUrl;if(!s)throw new Error('Jira Server requires a "resourceUrl" or "baseUrl" for this function.');let o=await this.getIssueFieldsForResource(t);return await rt(this.config,{...e,fields:o},s,t)}async setIssueStatus(e,t={}){await at(this.config,e,t)}async setIssueLabels(e,t={}){await ot(this.config,e,t)}async setIssueComponents(e,t={}){await it(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:R(e.token||this.config.token)})).body.results.map(({displayName:s})=>({color:null,description:null,id:null,name:s}))}}async getComponentsForJiraProject(e,t={}){return await ut(this.config,e,t)}};var H="https://api.trello.com",os=1e3,W=(r,n)=>({...R(n),Authorization:`OAuth oauth_consumer_key="${r}", oauth_token="${n}"`}),bo=r=>({id:r.id,username:r.username,url:r.url,name:r.fullName,email:r.email,avatarUrl:r.avatarUrl}),yo=(r,n)=>{let e=new Date(1e3*parseInt(r.id.substring(0,8),16));return{id:r.id,commentCount:r.badges.comments,number:r.idShort.toString(),title:r.name,url:r.url,closedDate:null,createdDate:new Date(e.toISOString()),author:null,updatedDate:new Date(r.dateLastActivity),assignees:r.members.map(t=>({id:t.id,username:t.username,name:t.fullName,email:null,avatarUrl:t.avatarUrl,url:null})),description:null,state:n[r.idList??""]?{id:r.idList,name:n[r.idList].name,color:null}:null,type:null,repository:null,upvoteCount:r.badges.votes,labels:r.labels.map(t=>({color:t.color,description:null,id:t.id,name:t.name}))}},Se=class extends j{async getCurrentUser(n,e={}){let t=await this.config.request({url:`${e.baseUrl||H}/1/members/me`,headers:W(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||H}/1/members/me/boards?fields=name&filter=open`,headers:W(n.appKey,e.token||this.config.token)})).body.map(s=>({id:s.id,name:s.name}))}}async getListsForTrelloBoard(n,e={}){let{appKey:t,boardId:s}=n;return{data:(await this.config.request({url:`${e.baseUrl||H}/1/boards/${s}/lists`,headers:W(t,e.token||this.config.token)})).body}}async getAccountForId(n,e={}){let{appKey:t,memberId:s}=n,o=await this.config.request({url:`${e.baseUrl||H}/1/members/${s}`,headers:W(t,e.token||this.config.token)});return{data:bo(o.body)}}async getAccountsForTrelloBoard(n,e={}){let{appKey:t,boardId:s}=n;return{data:(await this.config.request({url:`${e.baseUrl||H}/1/boards/${s}/members`,headers:W(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:s,boardId:o,filterText:i,assigneeLogins:a,labelNamesOrColors:u,trelloBoardListsById:p}=n||{};a&&t.push("@me"),u&&u.forEach(m=>t.push(`label:"${m}"`));let l=`${i?`${i}`:""}${t.join(" ")} board:${o}`,d=await this.config.request({url:`${e.baseUrl||H}/1/search?query=${l}&cards_limit=${os}&card_members=true`,headers:W(s,e.token||this.config.token)}),c=d.body.cards.length>=os?"unknown":"complete";return{data:d.body.cards.map(m=>yo(m,p||{})),metadata:J(c)}}async updateIssue(n,e,t,s){return await this.config.request({method:"PUT",url:`${s.baseUrl||H}/1/cards/${e.id}?${t}`,headers:W(n,s.token||this.config.token)})}async setIssueStatus(n,e={}){let{appKey:t,issue:s,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,s,i,e)).body.id)throw new Error("Could not set issue status")}async setIssueAssignees(n,e={}){let{appKey:t,issue:s,assignees:o}=n,i=o.map(p=>p.id),a=`idMembers=${encodeURIComponent(i.join(","))}`;if(!(await this.updateIssue(t,s,a,e)).body.id)throw new Error("Could not set issue status")}async setIssueLabels(n,e={}){let{appKey:t,issue:s,labels:o}=n,i=o.map(u=>u.id).join(",");if(!(await this.config.request({method:"PUT",url:`${e.baseUrl||H}/1/cards/${s.id}?idLabels=${encodeURIComponent(i)}`,headers:W(t,e.token||this.config.token)})).body.id)throw new Error("Could not set issue status")}async setIssueArchived(n,e={}){let{appKey:t,issue:s,archived:o}=n;if(!(await this.config.request({method:"PUT",url:`${e.baseUrl||H}/1/cards/${s.id}?closed=${o}`,headers:W(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:s}=n;return{data:(await this.config.request({url:`${e.baseUrl||H}/1/boards/${s}/labels`,headers:W(t,e.token||this.config.token)})).body.map(i=>({color:i.color,description:null,id:i.id,name:i.name}))}}};var er=100,lt=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}},Y=async(r,n,e,t)=>{let s=n.token||r.token;if(!s)throw new Error("Linear API key is required");let o=await r.request({url:"https://api.linear.app/graphql",method:"POST",headers:{Authorization:s,"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},Yt=r=>r?r instanceof Date?r:new Date(r):null,Po=`
|
|
1372
1373
|
id
|
|
1373
1374
|
name
|
|
1374
1375
|
description
|
|
@@ -1376,11 +1377,11 @@ OR comment ~ currentUser() OR summary ~ currentUser() OR description ~ currentUs
|
|
|
1376
1377
|
startDate
|
|
1377
1378
|
targetDate
|
|
1378
1379
|
url
|
|
1379
|
-
`,
|
|
1380
|
+
`,is=r=>({id:r.id,name:r.name,description:r.description??null,state:r.state,startDate:Yt(r.startDate),targetDate:Yt(r.targetDate),url:r.url}),as=async(r,n,e)=>{let t=`
|
|
1380
1381
|
query GetProjects($first: Int!, $after: String) {
|
|
1381
1382
|
projects(first: $first, after: $after) {
|
|
1382
1383
|
nodes {
|
|
1383
|
-
${
|
|
1384
|
+
${Po}
|
|
1384
1385
|
}
|
|
1385
1386
|
pageInfo {
|
|
1386
1387
|
hasNextPage
|
|
@@ -1388,7 +1389,7 @@ OR comment ~ currentUser() OR summary ~ currentUser() OR description ~ currentUs
|
|
|
1388
1389
|
}
|
|
1389
1390
|
}
|
|
1390
1391
|
}
|
|
1391
|
-
`;return(await
|
|
1392
|
+
`;return(await Y(r,n,t,{first:er,after:e})).projects},wo=`
|
|
1392
1393
|
id
|
|
1393
1394
|
name
|
|
1394
1395
|
number
|
|
@@ -1396,11 +1397,11 @@ OR comment ~ currentUser() OR summary ~ currentUser() OR description ~ currentUs
|
|
|
1396
1397
|
startsAt
|
|
1397
1398
|
endsAt
|
|
1398
1399
|
completedAt
|
|
1399
|
-
`,
|
|
1400
|
+
`,us=r=>({id:r.id,name:r.name??`Cycle ${r.number}`,number:r.number,description:r.description??null,startsAt:new Date(r.startsAt),endsAt:new Date(r.endsAt),completedAt:Yt(r.completedAt),url:""}),ls=async(r,n,e)=>{let t=`
|
|
1400
1401
|
query GetCycles($first: Int!, $after: String) {
|
|
1401
1402
|
cycles(first: $first, after: $after) {
|
|
1402
1403
|
nodes {
|
|
1403
|
-
${
|
|
1404
|
+
${wo}
|
|
1404
1405
|
}
|
|
1405
1406
|
pageInfo {
|
|
1406
1407
|
hasNextPage
|
|
@@ -1408,16 +1409,16 @@ OR comment ~ currentUser() OR summary ~ currentUser() OR description ~ currentUs
|
|
|
1408
1409
|
}
|
|
1409
1410
|
}
|
|
1410
1411
|
}
|
|
1411
|
-
`;return(await
|
|
1412
|
+
`;return(await Y(r,n,t,{first:er,after:e})).cycles},So=`
|
|
1412
1413
|
id
|
|
1413
1414
|
name
|
|
1414
1415
|
color
|
|
1415
1416
|
description
|
|
1416
|
-
`,
|
|
1417
|
+
`,ps=r=>({id:r.id,name:r.name,color:r.color,description:r.description??null}),ds=async(r,n,e)=>{let t=`
|
|
1417
1418
|
query GetLabels($first: Int!, $after: String) {
|
|
1418
1419
|
projectLabels(first: $first, after: $after) {
|
|
1419
1420
|
nodes {
|
|
1420
|
-
${
|
|
1421
|
+
${So}
|
|
1421
1422
|
}
|
|
1422
1423
|
pageInfo {
|
|
1423
1424
|
hasNextPage
|
|
@@ -1425,36 +1426,36 @@ OR comment ~ currentUser() OR summary ~ currentUser() OR description ~ currentUs
|
|
|
1425
1426
|
}
|
|
1426
1427
|
}
|
|
1427
1428
|
}
|
|
1428
|
-
`;return(await
|
|
1429
|
+
`;return(await Y(r,n,t,{first:er,after:e})).projectLabels};var Ae=(i=>(i[i.None=0]="None",i[i.Assignee=1]="Assignee",i[i.Creator=2]="Creator",i[i.Mention=3]="Mention",i[i.MentionInDescription=4]="MentionInDescription",i[i.MentionInComments=5]="MentionInComments",i))(Ae||{});function cs(r,n){return r?`${Ae[r]}:${n||""}`:n??null}function ms(r){if(!r)return{category:0};let[n,e]=r.split(":");return n in Ae?{category:Ae[n],cursor:e||void 0}:{category:0,cursor:r}}var gs=100;function dt(r){return r?r instanceof Date?r:new Date(r):null}var Rs=`
|
|
1429
1430
|
id
|
|
1430
1431
|
name
|
|
1431
1432
|
key
|
|
1432
1433
|
icon
|
|
1433
|
-
`;function
|
|
1434
|
+
`;function qo(r){return{id:r.id,name:r.name,key:r.key,iconUrl:r.icon}}var hs=`
|
|
1434
1435
|
id
|
|
1435
1436
|
name
|
|
1436
1437
|
avatarUrl
|
|
1437
|
-
`;function
|
|
1438
|
+
`;function fs(r){return r?{id:r.id,name:r.name,username:r.name,email:null,avatarUrl:r.avatarUrl??null,url:null}:null}var vo=`
|
|
1438
1439
|
id
|
|
1439
1440
|
name
|
|
1440
|
-
`;function
|
|
1441
|
+
`;function Eo(r,n){if(r)return{id:r.id,name:r.name,key:n?.key||null,namespace:null,resourceId:n?.id||null}}var Co=`
|
|
1441
1442
|
id
|
|
1442
1443
|
sortOrder
|
|
1443
1444
|
name
|
|
1444
1445
|
description
|
|
1445
1446
|
status
|
|
1446
1447
|
targetDate
|
|
1447
|
-
`;function
|
|
1448
|
+
`;function $o(r){return r?{id:r.id,number:r.sortOrder,title:r.name,description:r.description??null,isOpen:r.status!=="done",url:"",startDate:null,dueDate:dt(r.targetDate)}:null}function Do(r){switch(r){case"completed":case"canceled":return"DONE";case"started":return"IN_PROGRESS";default:return"TO_DO"}}var Lo=`
|
|
1448
1449
|
id
|
|
1449
1450
|
name
|
|
1450
1451
|
color
|
|
1451
1452
|
type
|
|
1452
|
-
`;function
|
|
1453
|
+
`;function Uo(r){return r?{id:r.id,name:r.name,color:r.color,category:Do(r.type)}:null}var rr=`
|
|
1453
1454
|
creator {
|
|
1454
|
-
${
|
|
1455
|
+
${hs}
|
|
1455
1456
|
}
|
|
1456
1457
|
assignee {
|
|
1457
|
-
${
|
|
1458
|
+
${hs}
|
|
1458
1459
|
}
|
|
1459
1460
|
archivedAt
|
|
1460
1461
|
createdAt
|
|
@@ -1462,35 +1463,35 @@ OR comment ~ currentUser() OR summary ~ currentUser() OR description ~ currentUs
|
|
|
1462
1463
|
id
|
|
1463
1464
|
identifier
|
|
1464
1465
|
project {
|
|
1465
|
-
${
|
|
1466
|
+
${vo}
|
|
1466
1467
|
}
|
|
1467
1468
|
team {
|
|
1468
|
-
${
|
|
1469
|
+
${Rs}
|
|
1469
1470
|
}
|
|
1470
1471
|
state {
|
|
1471
|
-
${
|
|
1472
|
+
${Lo}
|
|
1472
1473
|
}
|
|
1473
1474
|
title
|
|
1474
1475
|
updatedAt
|
|
1475
1476
|
url
|
|
1476
1477
|
projectMilestone {
|
|
1477
|
-
${
|
|
1478
|
+
${Co}
|
|
1478
1479
|
}
|
|
1479
|
-
`;async function
|
|
1480
|
+
`;async function tr(r){return{author:fs(await r.creator),assignees:[fs(await r.assignee)].filter(n=>n!=null),commentCount:null,closedDate:dt(r.archivedAt),createdDate:dt(r.createdAt),description:r.description??null,id:r.id,labels:[],number:r.identifier,repository:null,project:Eo(await r.project,await r.team),state:Uo(await r.state),title:r.title,type:null,updatedDate:dt(r.updatedAt),upvoteCount:null,url:r.url,milestone:$o(await r.projectMilestone)}}var pt=`
|
|
1480
1481
|
nodes {
|
|
1481
|
-
${
|
|
1482
|
+
${rr}
|
|
1482
1483
|
}
|
|
1483
1484
|
pageInfo {
|
|
1484
1485
|
hasNextPage
|
|
1485
1486
|
endCursor
|
|
1486
1487
|
}
|
|
1487
|
-
`,
|
|
1488
|
+
`,ct=class extends j{async fetchIssue(n,e){let t=`
|
|
1488
1489
|
query GetIssue($identifier: String!) {
|
|
1489
1490
|
issue(id: $identifier) {
|
|
1490
|
-
${
|
|
1491
|
+
${rr}
|
|
1491
1492
|
}
|
|
1492
1493
|
}
|
|
1493
|
-
`;return(await
|
|
1494
|
+
`;return(await Y(this.config,e,t,{identifier:n})).issue}async fetchOrganization(n){let e=`
|
|
1494
1495
|
query GetOrganization {
|
|
1495
1496
|
organization {
|
|
1496
1497
|
id
|
|
@@ -1498,15 +1499,15 @@ OR comment ~ currentUser() OR summary ~ currentUser() OR description ~ currentUs
|
|
|
1498
1499
|
urlKey
|
|
1499
1500
|
}
|
|
1500
1501
|
}
|
|
1501
|
-
`;return(await
|
|
1502
|
+
`;return(await Y(this.config,n,e)).organization}async fetchTeams(n){let e=`
|
|
1502
1503
|
query GetTeams {
|
|
1503
1504
|
teams {
|
|
1504
1505
|
nodes {
|
|
1505
|
-
${
|
|
1506
|
+
${Rs}
|
|
1506
1507
|
}
|
|
1507
1508
|
}
|
|
1508
1509
|
}
|
|
1509
|
-
`;return(await
|
|
1510
|
+
`;return(await Y(this.config,n,e)).teams}async rawRequest(n,e,t){return{data:await Y(this.config,n,e,t)}}async fetchViewer(n){let e=`
|
|
1510
1511
|
query GetViewer {
|
|
1511
1512
|
viewer {
|
|
1512
1513
|
id
|
|
@@ -1515,23 +1516,23 @@ OR comment ~ currentUser() OR summary ~ currentUser() OR description ~ currentUs
|
|
|
1515
1516
|
displayName
|
|
1516
1517
|
}
|
|
1517
1518
|
}
|
|
1518
|
-
`;return(await
|
|
1519
|
+
`;return(await Y(this.config,n,e)).viewer}async getIssue(n,e={}){let t=await this.fetchIssue(n.number,e);return{data:await tr(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(qo)}}async getProjects(n={},e={}){let t=await as(this.config,e,n.cursor??void 0);return{data:t.nodes.map(is),pageInfo:{hasNextPage:t.pageInfo.hasNextPage,endCursor:t.pageInfo.endCursor??null}}}async getCycles(n={},e={}){let t=await ls(this.config,e,n.cursor??void 0);return{data:t.nodes.map(us),pageInfo:{hasNextPage:t.pageInfo.hasNextPage,endCursor:t.pageInfo.endCursor??null}}}async getLabels(n={},e={}){let t=await ds(this.config,e,n.cursor??void 0);return{data:t.nodes.map(ps),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:s,cursor:o}=ms(t),i=await this.fetchViewer(e),a,u,p=new lt,l=async(d,c)=>{if(u||s>d)return;let m=await c(Math.max(gs-p.length,1),s===d?o:void 0);if(!m)return;let g=await ft(m.nodes.map(tr));p.push(...g),m.pageInfo.hasNextPage&&(a=d,u=m.pageInfo.endCursor)};return await l(1,async(d,c)=>(await this.rawRequest(e,`
|
|
1519
1520
|
query GetAssignedIssues($first: Int!, $after: String) {
|
|
1520
1521
|
viewer {
|
|
1521
1522
|
issues: assignedIssues(first: $first, after: $after) {
|
|
1522
|
-
${
|
|
1523
|
+
${pt}
|
|
1523
1524
|
}
|
|
1524
1525
|
}
|
|
1525
1526
|
}
|
|
1526
|
-
`,{first:d,after:c})).data?.viewer?.issues),await
|
|
1527
|
+
`,{first:d,after:c})).data?.viewer?.issues),await l(2,async(d,c)=>(await this.rawRequest(e,`
|
|
1527
1528
|
query GetCreatedIssues($first: Int!, $after: String) {
|
|
1528
1529
|
viewer {
|
|
1529
1530
|
issues: createdIssues(first: $first, after: $after) {
|
|
1530
|
-
${
|
|
1531
|
+
${pt}
|
|
1531
1532
|
}
|
|
1532
1533
|
}
|
|
1533
1534
|
}
|
|
1534
|
-
`,{first:d,after:c})).data?.viewer?.issues),await
|
|
1535
|
+
`,{first:d,after:c})).data?.viewer?.issues),await l(4,async(d,c)=>(await this.rawRequest(e,`
|
|
1535
1536
|
query GetMentionedIssues($first: Int!, $after: String) {
|
|
1536
1537
|
issues(
|
|
1537
1538
|
first: $first
|
|
@@ -1552,10 +1553,10 @@ OR comment ~ currentUser() OR summary ~ currentUser() OR description ~ currentUs
|
|
|
1552
1553
|
}]
|
|
1553
1554
|
}
|
|
1554
1555
|
){
|
|
1555
|
-
${
|
|
1556
|
+
${pt}
|
|
1556
1557
|
}
|
|
1557
1558
|
}
|
|
1558
|
-
`,{first:d,after:c})).data?.issues),await
|
|
1559
|
+
`,{first:d,after:c})).data?.issues),await l(5,async(d,c)=>{let g=(await this.rawRequest(e,`
|
|
1559
1560
|
query GetCommentedIssues($first: Int!, $after: String) {
|
|
1560
1561
|
comments(
|
|
1561
1562
|
first: $first
|
|
@@ -1578,7 +1579,7 @@ OR comment ~ currentUser() OR summary ~ currentUser() OR description ~ currentUs
|
|
|
1578
1579
|
){
|
|
1579
1580
|
nodes {
|
|
1580
1581
|
issue {
|
|
1581
|
-
${
|
|
1582
|
+
${rr}
|
|
1582
1583
|
}
|
|
1583
1584
|
}
|
|
1584
1585
|
pageInfo {
|
|
@@ -1587,10 +1588,10 @@ OR comment ~ currentUser() OR summary ~ currentUser() OR description ~ currentUs
|
|
|
1587
1588
|
}
|
|
1588
1589
|
}
|
|
1589
1590
|
}
|
|
1590
|
-
`,{first:d,after:c})).data?.comments;return
|
|
1591
|
+
`,{first:d,after:c})).data?.comments;return g?{nodes:g.nodes.map(y=>y.issue),pageInfo:g.pageInfo}:void 0}),{data:p.items,pageInfo:{hasNextPage:!!u,endCursor:cs(a,u)}}}async getIssues(n,e={}){let{teams:t,projects:s,labels:o,cursor:i}=n,a=[];if(t&&t.length>0){let m=t.map(g=>`"${g}"`).join(", ");a.push(`team: { id: { in: [${m}] } }`)}if(s&&s.length>0){let m=s.map(g=>`"${g}"`).join(", ");a.push(`project: { id: { in: [${m}] } }`)}if(o&&o.length>0){let m=o.map(g=>`"${g}"`).join(", ");a.push(`labels: { name: { in: [${m}] } }`)}let u=a.length>0?`filter: { ${a.join(", ")} }`:"",p=`
|
|
1591
1592
|
query GetIssues($first: Int!, $after: String) {
|
|
1592
1593
|
issues(first: $first, after: $after${u?", ":""}${u}) {
|
|
1593
|
-
${
|
|
1594
|
+
${pt}
|
|
1594
1595
|
}
|
|
1595
1596
|
}
|
|
1596
|
-
`,d=(await this.rawRequest(e,
|
|
1597
|
+
`,d=(await this.rawRequest(e,p,{first:gs,after:i})).data?.issues;return d?{data:await ft(d.nodes.map(tr)),pageInfo:{hasNextPage:d.pageInfo.hasNextPage,endCursor:d.pageInfo.endCursor??null}}:{data:[],pageInfo:{hasNextPage:!1,endCursor:null}}}};var Is=r=>{let n={request:r?.request};return{azureDevOps:new fe({...n,...r?.azureDevOps}),bitbucket:new Re({...n,...r?.bitbucket}),bitbucketServer:new Ie({...n,...r?.bitbucketServer}),github:new be({...n,...r?.github}),gitlab:new ye({...n,...r?.gitlab}),jira:new Pe({...n,...r?.jira}),jiraServer:new we({...n,...r?.jiraServer}),linear:new ct({...n,...r?.linear}),trello:new Se({...n,...r?.trello})}};var bs=(i=>(i.Conflicts="conflicts",i.Failure="failure",i.NotSet="notSet",i.Queued="queued",i.RejectedByPolicy="rejectedByPolicy",i.Succeeded="succeeded",i))(bs||{});var ys=(e=>(e.Zero="0",e.One="1",e))(ys||{}),Ps=(e=>(e.PullRequest="pr",e.Issue="issue",e))(Ps||{}),ws=(c=>(c.Azure="azure",c.AzureDevOpsServer="azureDevOpsServer",c.Github="github",c.GithubEnterprise="githubEnterprise",c.Gitlab="gitlab",c.GitlabSelfHosted="gitlabSelfHosted",c.Bitbucket="bitbucket",c.BitbucketServer="bitbucketServer",c.Jira="jira",c.JiraServer="jiraServer",c.Linear="linear",c.Trello="trello",c))(ws||{});var Ss=(e=>(e.Completed="COMPLETED",e.NotPlanned="NOT_PLANNED",e))(Ss||{});var Ao=Is;
|